diff --git a/TODO.md b/TODO.md index 314e95f8..2a6e8bd8 100644 --- a/TODO.md +++ b/TODO.md @@ -174,7 +174,7 @@ Entscheid CLA vs. Verzicht auf Dual Licensing. ### Daten -- ○ **[10] IDs und GUIDs trennen.** IFC-GUIDs werden deterministisch aus der ID gehasht. · M +- ✅ **[10] IDs und GUIDs trennen.** IFC-GUIDs werden deterministisch aus Projekt-, Art- und Element-id gehasht (28.10., [B5]). · M - ○ **[11] Bibliothek per GUID.** · M ### Robustheit und Tests @@ -317,15 +317,36 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module Revolved/SweptDisk; Farbe/GlobalId gelesen, aber `ImportedMesh` hat kein Feld dafür (GlobalId steht im Namen); Laden im Worker; nur Linux-Container/vitest, nicht in der Tauri-App geprüft. · M - ○ **[B4] IFC-Import zu echten Bauteilen** (zweite Stufe von [25]). · L · nach [B3]. -- ◐ **[B5] IFC-Export nachziehen** (`exportIfc.ts`). Stand 27.10.: +- ◐ **[B5] IFC-Export nachziehen** (`exportIfc.ts`). Stand 28.10.: - ✅ Nicht-ASCII nach ISO 10303-21 (`\X2\`/`\X4\`). - ✅ Materialschichten: Wand-/Decken-/Dachtypen als IfcWallType/IfcSlabType/IfcRoofType mit IfcMaterialLayerSet, Exemplare über IfcRelDefinesByType (keine LayerSetUsage, Wand ist Mesh). - ✅ IfcSpace aus `Room` (Qto_SpaceBaseQuantities, SIA 416), IfcRoof, IfcColumn mit Material. - - ○ `IfcOpeningElement` + RelVoids/RelFills statt ausgeschnittener Meshes. · M - - ○ `Pset_*Common`. · S - - ○ Dauerhafte GUIDs (= [10]). · M + - ✅ `IfcOpeningElement` + RelVoids/RelFills statt ausgeschnittener Meshes. (28.10.) Wand als + ungeschnittene Extrusion (je Schicht-Band ein IfcExtrudedAreaSolid, SweptSolid), Öffnung als + Quader über die Wanddicke (+2 cm), Tür/Fenster im Öffnungs-Placement. Nur wenn exakt gleich wie + das 3D (`bandsMatchOpenings`: kein schräger Bandkopf, Löcher = Öffnungen); sonst (Wand unter + Dach, Laibungs-Rücksprung) bleibt das Mesh, Öffnung+Füllung trotzdem als Beziehung (zieht nichts + doppelt ab). Demo-Haus: 7 von 9 Wänden Extrusion; Volumen je Wand nach ifcopenshell = 3D-Mesh. + - ✅ `Pset_*Common`. (28.10.) Wall/Slab/Roof/Column/Door/Window/SpaceCommon nur mit Modellwerten: + Reference (Typname, Stützenprofil, Raumnummer), IsExternal (Dach; Raum aus SIA 416 AGF, IfcSpace + dann EXTERNAL), GlazingAreaFraction (Glastür). Gleicher Inhalt = ein Pset für alle Bauteile. + - ✅ Dauerhafte GUIDs (= [10]). (28.10.) 128-Bit-Hash (2× FNV-1a + fmix64, UUID v8) über + `//[/]`; Rels/Typen/Psets/Eingliederung an Element-/Geschoss-/ + Typ-ids statt STEP-Nummern. Tests: Rundreise stabil, eindeutig (Decke und Dach gleiche id), + unabhängig von anderen Bauteilen, projektübergreifend verschieden. GUIDs ändern sich einmalig + gegenüber Exporten vor dem 28.10. - ✅ Georeferenz [69]. + - ○ Offen: IsExternal/LoadBearing/ThermalTransmittance für Wand/Decke/Tür/Fenster brauchen + Modellfelder (z. B. am Wandtyp tragend/aussen, λ je Bauteil → U-Wert). · S–M + - ○ Offen: IfcMaterialLayerSetUsage + Achs-Darstellung („Axis") an Extrusions-Wänden; + Tür/Fenster mit Rahmen/Blatt statt Box; Bogenwände als echte Kurve. · M + - ○ Offen: eigener IFC-Import ([B3]) zieht Öffnungen noch nicht ab → Rundreise des eigenen + Exports zeigt Extrusions-Wände ohne Löcher, bis [B4] (Test `ifcImport.test.ts` angepasst). · M + - ○ Folgepunkt: Export nach Rust (`src-tauri/fileio`, wie der Import) portieren; TS-Fassung + `exportIfc.ts` dann löschen. · L + - Geprüft nur im Linux-Container (vitest + ifcopenshell 0.9: 0 Befunde, Volumen), nicht in + Solibri/BIMcollab und nicht in der Tauri-App. - ○ **[B6] Wand unter Dach als Prismen zwischen Ebenen** (für [G2]). `walls.rs:413–472, 592–654`. · M - ○ **[B7] Dach-Verschneidung und Gauben in 2.5D** (für [G5]). · M · nach [B2]/[B6]. - ○ **[B8] Bogenwände, schneller Weg** (für [T2]). · S/M–L diff --git a/src/export/exportIfc.test.ts b/src/export/exportIfc.test.ts index 2c33d81b..114868c8 100644 --- a/src/export/exportIfc.test.ts +++ b/src/export/exportIfc.test.ts @@ -145,6 +145,37 @@ function fixtureProject(): Project { } as Project; } +/** + * Wie {@link fixtureProject}, aber beide Öffnungen sind Fenster mit Laibungs-Rücksprung an der + * innersten Schicht: das Loch der (einzigen) Schicht ist grösser als die Öffnung, die Wand lässt sich + * nicht als Extrusion minus Öffnung schreiben → Mesh-Pfad (IfcTriangulatedFaceSet). + */ +function meshFixture(): Project { + const p = fixtureProject(); + (p as { windowTypes?: unknown[] }).windowTypes = [ + { id: "wt", name: "Holz-Metall IV", kind: "drehkipp", wingCount: 1, glazing: "dreifach", frameThickness: 0.08, defaultSillHeight: 0.9, defaultWidth: 1.2, defaultHeight: 1.2, innerLayerRecess: true }, + ]; + p.openings = [ + { ...p.openings![0], kind: "window", sillHeight: 0.9, height: 1.2, typeId: "wt" }, + { ...p.openings![1], height: 1.2, typeId: "wt" }, + ]; + return p; +} + +/** `#N` einer Entity-Zeile. */ +const idOf = (line: string) => line.slice(0, line.indexOf("=")); + +/** Alle GlobalIds (erstes Attribut jeder IfcRoot-Entity: 22-Zeichen-String gefolgt von der OwnerHistory). */ +function globalIds(spf: string): string[] { + return [...spf.matchAll(/^#\d+=IFC\w+\('([0-9A-Za-z_$]{22})',#\d+,/gm)].map((m) => m[1]); +} + +/** GlobalId der ersten Entity vom Typ `type`, deren Zeile `needle` enthält. */ +function guidOf(spf: string, type: string, needle = ""): string | undefined { + const line = spf.split("\n").find((l) => l.includes(`=${type}(`) && l.includes(needle)); + return line ? /\('([^']{22})'/.exec(line)?.[1] : undefined; +} + /** Sammelt alle definierten Entity-IDs (`#N=`) und alle referenzierten `#N`. */ function collectIds(spf: string): { defined: Set; referenced: Set; duplicates: number[] } { const defined = new Set(); @@ -199,30 +230,59 @@ describe("exportIfcSpf — IFC4-Export", () => { expect(wallLines).toHaveLength(2); }); - it("Tür/Fenster bleiben eigene Objekte (IfcDoor/IfcWindow); das Loch steckt im Wand-Mesh (kein IfcOpeningElement/Void/Fill)", () => { + it("Tür/Fenster: IfcOpeningElement in der Wand (RelVoids) und IfcDoor/IfcWindow darin (RelFills)", () => { const spf = exportIfcSpf(fixtureProject()); const lines = spf.split("\n"); - // Tür + Fenster als eigene Objekte erhalten. expect(lines.filter((l) => l.includes("=IFCDOOR("))).toHaveLength(1); expect(lines.filter((l) => l.includes("=IFCWINDOW("))).toHaveLength(1); - // Bewusste Abwägung: Wand ist jetzt ein Face-Set mit ausgeschnittenem Loch — - // die frühere IfcOpeningElement-Void/Fill-Semantik entfällt (siehe Dateikopf). - expect(lines.filter((l) => l.includes("=IFCOPENINGELEMENT("))).toHaveLength(0); - expect(lines.filter((l) => l.includes("=IFCRELVOIDSELEMENT("))).toHaveLength(0); - expect(lines.filter((l) => l.includes("=IFCRELFILLSELEMENT("))).toHaveLength(0); + const openings = lines.filter((l) => l.includes("=IFCOPENINGELEMENT(")); + expect(openings).toHaveLength(2); + for (const o of openings) expect(o).toContain(".OPENING."); + const voids = lines.filter((l) => l.includes("=IFCRELVOIDSELEMENT(")); + const fills = lines.filter((l) => l.includes("=IFCRELFILLSELEMENT(")); + expect(voids).toHaveLength(2); + expect(fills).toHaveLength(2); + // RelVoids: Wand → Öffnung; RelFills: Öffnung → Tür/Fenster. + const wallIds = lines.filter((l) => l.includes("=IFCWALL(")).map(idOf); + const openingIds = openings.map(idOf); + const fillIds = lines.filter((l) => l.includes("=IFCDOOR(") || l.includes("=IFCWINDOW(")).map(idOf); + for (const v of voids) { + const m = /,(#\d+),(#\d+)\);$/.exec(v)!; + expect(wallIds).toContain(m[1]); + expect(openingIds).toContain(m[2]); + } + for (const f of fills) { + const m = /,(#\d+),(#\d+)\);$/.exec(f)!; + expect(openingIds).toContain(m[1]); + expect(fillIds).toContain(m[2]); + } + // Öffnungen hängen nur über RelVoids an der Wand, nicht im Geschoss. + const contained = lines.filter((l) => l.includes("=IFCRELCONTAINEDINSPATIALSTRUCTURE(")); + for (const o of openingIds) for (const c of contained) expect(c).not.toMatch(new RegExp(`${o}[,)]`)); }); - it("bildet Wände als IfcTriangulatedFaceSet (IfcCartesianPointList3D + CoordIndex) statt Profil-Extrusion ab", () => { + it("einfache Wände: ungeschnittene Profil-Extrusion (SweptSolid) je Schicht-Band, kein Mesh", () => { const spf = exportIfcSpf(fixtureProject()); const lines = spf.split("\n"); - // Genau ein Face-Set + eine Punktliste je Wand (2 Wände). - expect(lines.filter((l) => l.includes("=IFCTRIANGULATEDFACESET("))).toHaveLength(2); - expect(lines.filter((l) => l.includes("=IFCCARTESIANPOINTLIST3D("))).toHaveLength(2); - // Wand-Shape ist als Tessellation deklariert (nicht mehr SweptSolid). - expect(spf).toContain("'Tessellation'"); - // Face-Set-CoordIndex referenziert 1-basierte Punkt-Indizes (Tripel-Listen). - const fs = lines.find((l) => l.includes("=IFCTRIANGULATEDFACESET(")); - expect(fs).toMatch(/\(\(\d+,\d+,\d+\)/); + expect(lines.filter((l) => l.includes("=IFCTRIANGULATEDFACESET("))).toHaveLength(0); + // Der Fenster-Wand-Körper ist voll: 5 m × 0.4 m Rechteck, 2.6 m hoch (das Loch macht die Öffnung). + expect(spf).toMatch(/=IFCEXTRUDEDAREASOLID\(#\d+,#\d+,#\d+,2\.6\);/); + }); + + it("Wand mit Laibungs-Rücksprung (innerste Schicht weiter offen): Mesh bleibt, Öffnung+Füllung trotzdem als Beziehung", () => { + const p = fixtureProject(); + p.components.push({ id: "d", name: "Dämmung", color: "#eee", hatchId: "none", joinPriority: 5 }); + p.wallTypes[0].layers = [{ componentId: "d", thickness: 0.16 }, { componentId: "c", thickness: 0.24 }]; + (p as { windowTypes?: unknown[] }).windowTypes = [ + { id: "wt", name: "Holz-Metall IV", kind: "drehkipp", wingCount: 1, glazing: "dreifach", frameThickness: 0.08, defaultSillHeight: 0.9, defaultWidth: 1.2, defaultHeight: 1.2, innerLayerRecess: true }, + ]; + p.openings![1] = { ...p.openings![1], typeId: "wt" }; + const lines = exportIfcSpf(p).split("\n"); + // W2 (Fenster mit Rücksprung) als Mesh, W1 (Tür) als Extrusion. + expect(lines.filter((l) => l.includes("=IFCTRIANGULATEDFACESET("))).toHaveLength(1); + expect(lines.filter((l) => l.includes("=IFCOPENINGELEMENT("))).toHaveLength(2); + expect(lines.filter((l) => l.includes("=IFCRELVOIDSELEMENT("))).toHaveLength(2); + expect(lines.filter((l) => l.includes("=IFCRELFILLSELEMENT("))).toHaveLength(2); }); it("bildet Decke, Treppe und Extrusion auf die erwarteten Entity-Typen ab", () => { @@ -234,11 +294,13 @@ describe("exportIfcSpf — IFC4-Export", () => { }); it("das Wand-Face-Set enthält das ausgeschnittene Fenster-Loch (Loch-Vertices + volle Dreieckszahl, keine dangling refs)", () => { + // Einschichtige Wände mit Rücksprung-Fenster: die einzige (= innerste) Schicht hat das geweitete + // Loch → Mesh-Pfad; Zerlegung wie bisher. // W2 hat das Fenster F1 (position 1, width 1.2, sill 0.9, height 1.5) → das // Loch liegt voll im Wand-Inneren; das Face-Set der Wand hat exakt die // Rust-Zerlegung: 8 Langseiten-Teilrechtecke ×2×2 + 8 (Deckel/Boden/Kappen) // + 8 (4 Laibungen) = 48 Dreiecke, 144 Punkte. - const spf = exportIfcSpf(fixtureProject()); + const spf = exportIfcSpf(meshFixture()); const lines = spf.split("\n"); const faceSets = lines.filter((l) => l.includes("=IFCTRIANGULATEDFACESET(")); // Das Loch-Face-Set hat 48 CoordIndex-Tripel. @@ -258,7 +320,7 @@ describe("exportIfcSpf — IFC4-Export", () => { // Dreiecks-Wicklung um → Normalen zeigten nach INNEN → Viewer cullten die // Vorderseiten → Wand wirkte oben/unten offen. Nach dem Wicklungs-Ausgleich // muss das signierte Volumen jedes Wandkörpers POSITIV sein (aussen orientiert). - const spf = exportIfcSpf(fixtureProject()); + const spf = exportIfcSpf(meshFixture()); const lines = spf.split("\n"); const byId = new Map(); for (const l of lines) { @@ -302,11 +364,74 @@ describe("exportIfcSpf — IFC4-Export", () => { it("GUIDs sind 22 Zeichen lang, nutzen den gültigen IFC-Zeichensatz und sind deterministisch", () => { const guid = ifcGuid("W1"); expect(guid).toHaveLength(22); - expect(guid).toMatch(/^[0-9A-Za-z_$]{22}$/); + // 128 Bit in 22 Zeichen: das erste Zeichen trägt nur 2 Bit (0–3). + expect(guid).toMatch(/^[0-3][0-9A-Za-z_$]{21}$/); expect(ifcGuid("W1")).toBe(guid); // stabil über Re-Export expect(ifcGuid("W2")).not.toBe(guid); // unterschiedliche IDs → unterschiedliche GUIDs }); + it("[B5] dauerhafte GUIDs: zweimal exportieren liefert dieselben GlobalIds", () => { + const a = globalIds(exportIfcSpf(fixtureProject())); + const b = globalIds(exportIfcSpf(fixtureProject())); + expect(a.length).toBeGreaterThan(20); + expect(b).toEqual(a); + }); + + it("[B5] GlobalIds sind in der Datei eindeutig — auch bei gleicher id verschiedener Bauteilarten", () => { + // Decke und Dach heissen beide „D1": Namensraum je Bauteilart trennt sie. + const p: Project = { + ...meshFixture(), + roofs: [ + { + id: "D1", type: "roof", floorId: "og", categoryCode: "35", + outline: [{ x: 0, y: 0 }, { x: 5, y: 0 }, { x: 5, y: 4 }, { x: 0, y: 4 }], + shape: "sattel", pitchDeg: 35, overhang: 0.3, ridgeAxis: "x", thickness: 0.25, + }, + ], + rooms: [ + { id: "R1", type: "room", floorId: "eg", categoryCode: "45", siaCategory: "HNF", name: "Küche", boundary: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }], color: "#ccc" }, + ], + columns: [ + { id: "S2", type: "column", floorId: "eg", categoryCode: "50", position: { x: 2, y: 2 }, profile: { kind: "round", radius: 0.1 }, rotation: 0, height: 2.6, componentId: "c" }, + ], + }; + const ids = globalIds(exportIfcSpf(p)); + expect(ids.length).toBeGreaterThan(30); + expect(new Set(ids).size).toBe(ids.length); + // Ebenso im Demo-Haus mit Extrusions-Wänden. + const ids2 = globalIds(exportIfcSpf(fixtureProject())); + expect(new Set(ids2).size).toBe(ids2.length); + }); + + it("[B5] GUID eines Bauteils hängt nur an Projekt und Bauteil, nicht an anderen Bauteilen oder der Reihenfolge", () => { + const base = exportIfcSpf(fixtureProject()); + const p = fixtureProject(); + p.walls = [ + { id: "W0", type: "wall", floorId: "og", categoryCode: "20", start: { x: 0, y: 4 }, end: { x: 0, y: 0 }, wallTypeId: "aw", height: 2.6 }, + ...[...p.walls].reverse(), + ]; + const more = exportIfcSpf(p); + for (const type of ["IFCWALL", "IFCSLAB", "IFCDOOR", "IFCOPENINGELEMENT", "IFCWALLTYPE"]) { + const g = guidOf(base, type); + expect(g, type).toBeDefined(); + expect(globalIds(more), type).toContain(g); + } + // Geschoss und räumliche Eingliederung des EG bleiben gleich, obwohl das OG neu Bauteile hat. + expect(guidOf(more, "IFCBUILDINGSTOREY", "'EG'")).toBe(guidOf(base, "IFCBUILDINGSTOREY", "'EG'")); + const containEg = (spf: string) => { + const eg = idOf(spf.split("\n").find((l) => l.includes("=IFCBUILDINGSTOREY(") && l.includes("'EG'"))!); + return guidOf(spf, "IFCRELCONTAINEDINSPATIALSTRUCTURE", `,${eg});`); + }; + expect(containEg(base)).toBeDefined(); + expect(containEg(more)).toBe(containEg(base)); + }); + + it("[B5] anderes Projekt ⇒ andere GUIDs (gleiche Bauteil-ids kollidieren nicht projektübergreifend)", () => { + const a = new Set(globalIds(exportIfcSpf(fixtureProject()))); + const b = globalIds(exportIfcSpf({ ...fixtureProject(), id: "anderes" })); + expect(b.filter((g) => a.has(g))).toEqual([]); + }); + it("georeferenziert: mit geoAnchor werden die ECHTEN LV95-Koordinaten geschrieben (lokal bearbeitet, weltweit lagerichtig)", () => { // Modell lokal nahe (0,0), aber geoAnchor sagt: Modell (0,0) = LV95 // (2600000,1200000). Der Export muss die Profil-/Punkt-Koordinaten auf die @@ -425,7 +550,6 @@ describe("Räume als IfcSpace", () => { describe("Materialschichten über Bauteiltypen", () => { const lines = (spf: string, type: string) => spf.split("\n").filter((l) => l.includes(`=${type}(`)); - const idOf = (line: string) => line.slice(0, line.indexOf("=")); it("Wandtyp → IfcWallType mit IfcMaterialLayerSet, Wände über IfcRelDefinesByType", () => { const p = fixtureProject(); p.components.push({ id: "d", name: "Dämmung", color: "#eee", hatchId: "none", joinPriority: 5 }); @@ -483,3 +607,96 @@ describe("Dächer und Stützen", () => { expect(spf.split("\n").some((l) => l.includes("=IFCRELASSOCIATESMATERIAL(") && l.includes(`(${colId})`))).toBe(true); }); }); + +describe("[B5] Pset_*Common mit den Werten aus dem Modell", () => { + const byId = (spf: string) => { + const m = new Map(); + for (const l of spf.split("\n")) { + const k = /^(#\d+)=/.exec(l); + if (k) m.set(k[1], l); + } + return m; + }; + /** Eigenschaften (Name → Wert-Ausdruck) des Psets `pset` am Bauteil `elementLine`. */ + const psetOf = (spf: string, elementLine: string, pset: string): Record | null => { + const lines = byId(spf); + const el = idOf(elementLine); + for (const rel of spf.split("\n").filter((l) => l.includes("=IFCRELDEFINESBYPROPERTIES("))) { + const m = /,\(([^)]*)\),(#\d+)\);$/.exec(rel)!; + if (!m[1].split(",").includes(el)) continue; + const ps = lines.get(m[2])!; + if (!ps.includes(`'${pset}'`)) continue; + const props = /,\(([^)]*)\)\);$/.exec(ps)![1].split(","); + const out: Record = {}; + for (const pid of props) { + const pm = /IFCPROPERTYSINGLEVALUE\('([^']*)',\$,(.*),\$\);$/.exec(lines.get(pid)!)!; + out[pm[1]] = pm[2]; + } + return out; + } + return null; + }; + const project = (): Project => ({ + ...fixtureProject(), + doorTypes: [ + { id: "dt-glas", name: "Glastür", kind: "dreh", leafCount: 1, leafStyle: "glas", glazingRatio: 0.6, frameThickness: 0.06, defaultWidth: 0.9, defaultHeight: 2.1 }, + ], + windowTypes: [{ id: "wt", name: "Holz-Metall IV", kind: "drehkipp", wingCount: 1, glazing: "dreifach", frameThickness: 0.08, defaultSillHeight: 0.9, defaultWidth: 1.2, defaultHeight: 1.5 }], + openings: [ + { ...fixtureProject().openings![0], typeId: "dt-glas" }, + { ...fixtureProject().openings![1], typeId: "wt" }, + ], + roofTypes: [{ id: "rt", name: "Ziegeldach", layers: [{ componentId: "c", thickness: 0.25 }] }], + roofs: [ + { + id: "DA", type: "roof", floorId: "og", categoryCode: "35", + outline: [{ x: 0, y: 0 }, { x: 5, y: 0 }, { x: 5, y: 4 }, { x: 0, y: 4 }], + shape: "sattel", pitchDeg: 35, overhang: 0.3, ridgeAxis: "x", thickness: 0.25, roofTypeId: "rt", + }, + ], + columns: [ + { id: "S1", type: "column", floorId: "eg", categoryCode: "50", position: { x: 2, y: 2 }, profile: { kind: "rect", width: 0.3, depth: 0.2 }, rotation: 0, height: 2.6 }, + ], + rooms: [ + { id: "R1", type: "room", floorId: "eg", categoryCode: "45", siaCategory: "HNF", name: "Küche", boundary: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }, { x: 0, y: 3 }], color: "#ccc", stamp: { number: "E.01" } as never }, + { id: "R2", type: "room", floorId: "eg", categoryCode: "45", siaCategory: "AGF", name: "Terrasse", boundary: [{ x: 6, y: 0 }, { x: 8, y: 0 }, { x: 8, y: 3 }, { x: 6, y: 3 }], color: "#ccc" }, + ], + }) as Project; + const line = (spf: string, type: string, needle = "") => spf.split("\n").find((l) => l.includes(`=${type}(`) && l.includes(needle))!; + + it("Wand/Decke: Reference = Typname, keine erfundenen Werte (IsExternal/LoadBearing/U-Wert fehlen im Modell)", () => { + const spf = exportIfcSpf(project()); + expect(psetOf(spf, line(spf, "IFCWALL"), "Pset_WallCommon")).toEqual({ Reference: "IFCIDENTIFIER('Aussenwand')" }); + expect(psetOf(spf, line(spf, "IFCSLAB"), "Pset_SlabCommon")).toEqual({ Reference: "IFCIDENTIFIER('Betondecke')" }); + expect(spf).not.toContain("'ThermalTransmittance'"); + expect(spf).not.toContain("'LoadBearing'"); + }); + it("Dach: Reference = Dachtyp, IsExternal (ein Dach ist Gebäudehülle)", () => { + const spf = exportIfcSpf(project()); + expect(psetOf(spf, line(spf, "IFCROOF"), "Pset_RoofCommon")).toEqual({ Reference: "IFCIDENTIFIER('Ziegeldach')", IsExternal: "IFCBOOLEAN(.T.)" }); + }); + it("Stütze: Reference = Profilbezeichnung", () => { + const spf = exportIfcSpf(project()); + expect(psetOf(spf, line(spf, "IFCCOLUMN"), "Pset_ColumnCommon")).toEqual({ Reference: "IFCIDENTIFIER('St\\X2\\00FC\\X0\\tze 30\\X2\\00D7\\X0\\20')" }); + }); + it("Tür/Fenster: Reference = Bauteiltyp, Glasanteil der Glastür", () => { + const spf = exportIfcSpf(project()); + expect(psetOf(spf, line(spf, "IFCDOOR"), "Pset_DoorCommon")).toEqual({ + Reference: "IFCIDENTIFIER('Glast\\X2\\00FC\\X0\\r')", + GlazingAreaFraction: "IFCPOSITIVERATIOMEASURE(0.6)", + }); + expect(psetOf(spf, line(spf, "IFCWINDOW"), "Pset_WindowCommon")).toEqual({ Reference: "IFCIDENTIFIER('Holz-Metall IV')" }); + // Ohne Typ kein leeres Pset. + const plain = exportIfcSpf(fixtureProject()); + expect(psetOf(plain, line(plain, "IFCDOOR"), "Pset_DoorCommon")).toBeNull(); + }); + it("Raum: Reference = Raumnummer, IsExternal aus SIA 416 (AGF = Aussengeschossfläche)", () => { + const spf = exportIfcSpf(project()); + const kueche = line(spf, "IFCSPACE", "'K\\X2\\00FC\\X0\\che'"); + const terrasse = line(spf, "IFCSPACE", "'Terrasse'"); + expect(psetOf(spf, kueche, "Pset_SpaceCommon")).toEqual({ Reference: "IFCIDENTIFIER('E.01')", IsExternal: "IFCBOOLEAN(.F.)" }); + expect(psetOf(spf, terrasse, "Pset_SpaceCommon")).toEqual({ IsExternal: "IFCBOOLEAN(.T.)" }); + expect(terrasse).toContain(".EXTERNAL."); + expect(kueche).toContain(".INTERNAL."); + }); +}); diff --git a/src/export/exportIfc.ts b/src/export/exportIfc.ts index 8a671042..1c82e4dd 100644 --- a/src/export/exportIfc.ts +++ b/src/export/exportIfc.ts @@ -3,7 +3,7 @@ // neue Dependency — IFC wird direkt als Text geschrieben (analog exportDxf.ts/ // exportSchedule.ts). Der Download (Blob+Anchor) passiert im App-Layer. // -// Abbildung (erste vollständige Scheibe): +// Abbildung: // Project → IfcProject → IfcSite → IfcBuilding → je "floor"-Geschoss ein // IfcBuildingStorey (IfcRelAggregates-Kette). Bauteile hängen über // IfcRelContainedInSpatialStructure am jeweiligen Geschoss (verwaiste @@ -15,20 +15,21 @@ // (Site/Building/Storey/Element) trägt bewusst NUR die Z-Verschiebung // (Geschoss-Elevation); die Profilpunkte tragen direkt die Welt-X/Y-Koordinaten. // -// • Wand → IfcWall mit ÖFFNUNGSGENAUEM Dreiecks-Mesh (IfcTriangulatedFace -// Set, IFC4: IfcCartesianPointList3D + CoordIndex) statt einer Profil- -// Extrusion. Gespeist aus DEMSELBEN Loch-Ausschnitt-Mesh wie STL/OBJ -// (`pickGeometry` → `plan/wallMeshCut.ts`): Joins/Gehrungen UND ausgeschnittene -// Fenster/Türen (inkl. Laibungen) sind im Körper enthalten. ABWÄGUNG (bewusst, -// Nutzer-Priorität "so wie im 3D"): dadurch verliert die Wand die parametrische -// IfcWall-Profil-Extrusion + IfcOpeningElement-Void-Semantik zugunsten -// VISUELLER PARITÄT in JEDEM Viewer (der Loch schon im Mesh sieht, ohne eine -// Boolean-Subtraktion ausführen zu müssen — genau der Bug des Nutzers: "das -// Fenster ist als Objekt da im IFC, aber die Löcher sind nicht da"). +// • Wand → IfcWall aus denselben Schicht-Bändern wie das 3D (`pickGeometry`: Joins/ +// Gehrungen, Decken-Dominanz, Durchgangs-Aussparungen bereits aufgelöst). Zwei Wege ([B5]): +// – Regelfall: UNGESCHNITTENER Körper, je Band ein IfcExtrudedAreaSolid (Rechteck × Höhe) +// in EINER SweptSolid-Darstellung; Fenster/Türen als IfcOpeningElement (IfcRelVoids +// Element), der Viewer zieht sie ab. Gewählt nur, wenn das exakt dasselbe ergibt wie das +// 3D: jedes Band ist ein Quader (keine schräge Oberkante) und seine Löcher sind genau die +// Öffnungen (`bandsMatchOpenings`). +// – sonst (Wand unter Dach mit schräger Oberkante, Laibungs-Rücksprung der innersten +// Schicht …): öffnungsgenaues Dreiecks-Mesh (IfcTriangulatedFaceSet) wie STL/OBJ +// (`plan/wallMeshCut.ts`, Löcher inkl. Laibungen schon ausgestanzt). Öffnung + Füllung +// werden trotzdem als Beziehung angelegt; die Öffnung liegt im Loch und zieht nichts ab. // • Decke → IfcSlab (outline-Polygon, PredefinedType FLOOR). -// • Öffnung → KEIN IfcOpeningElement/Void mehr (das Loch steckt im Wand-Mesh); -// Tür/Fenster bleiben als eigenes Objekt IfcDoor/IfcWindow mit eigener Box- -// Geometrie erhalten (füllt das ausgeschnittene Loch, "sieht aus wie 3D"). +// • Öffnung → IfcOpeningElement (Quader über die ganze Wanddicke, etwas vorstehend) in der +// Wand (IfcRelVoidsElement), darin IfcDoor/IfcWindow (IfcRelFillsElement) mit eigener +// Box-Geometrie; kein Blatt-/Rahmendetail (bewusste Vereinfachung). // • Extrusion → IfcBuildingElementProxy aus points+height. // • Dach → IfcRoof (Schicht-Meshes wie im 3D), Dachtyp → IfcRoofType mit Schichten. // • Stütze → IfcColumn (Profil-Extrusion), Bauteil → IfcMaterial. @@ -39,13 +40,19 @@ // echte Stufengeometrie ist ausgelassen (siehe stairFootprint()). // // Material-Schichten: je Wand-/Deckentyp ein IfcWallType/IfcSlabType mit -// IfcMaterialLayerSet, die Exemplare erben ihn über IfcRelDefinesByType. KEIN -// IfcMaterialLayerSetUsage am Exemplar: Richtung/Versatz der Usage beziehen sich -// auf eine Achs-Darstellung, die das Wand-Mesh nicht hat. +// IfcMaterialLayerSet, die Exemplare erben ihn über IfcRelDefinesByType. (Noch) KEIN +// IfcMaterialLayerSetUsage am Exemplar: die Wand hat keine Achs-Darstellung. // -// GUIDs: deterministisch aus der Element-ID über einen 128-Bit-Hash (zwei -// FNV-1a-64-Läufe) + Standard-IFC-GUID-Kompression (Base64-Variante, -// Zeichensatz 0-9,A-Z,a-z,_,$) — stabil über Re-Exporte hinweg. +// Eigenschaften ([B5]): Pset_WallCommon/SlabCommon/RoofCommon/ColumnCommon/DoorCommon/ +// WindowCommon/SpaceCommon nur mit Werten, die das Modell hergibt (Reference = Typname, +// IsExternal beim Dach und bei SIA-416-AGF-Räumen, Glasanteil der Glastür). Kein U-Wert, +// keine Tragfunktion: dafür hat das Modell keine Felder. +// +// GUIDs ([B5]/[10]): deterministisch aus `//[/]` über einen +// 128-Bit-Hash + Standard-IFC-GUID-Kompression (Zeichensatz 0-9,A-Z,a-z,_,$) — zweimal +// exportieren gibt dieselben GlobalIds, BIM-Koordination (Solibri, BIMcollab) erkennt die +// Bauteile wieder. Abgeleitete Entitäten (Rels, Typen, Psets) hängen an Element-/Geschoss-/ +// Typ-ids, nie an STEP-Nummern. // // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). Einheit: METER. @@ -59,23 +66,24 @@ import type { import { columnLabel, getCeilingType, + getDoorType, getWallType, + getWindowType, openingLabel, - wallTypeThickness, + openingsOfWall, } from "../model/types"; import { projectToWorldCoords } from "../model/geoRebase"; import { ceilingVerticalExtent, columnVerticalExtent, stairVerticalExtent, - wallReferenceOffset, - wallVerticalExtent, } from "../model/wall"; import { pickGeometry } from "../plan/toWalls3d"; import type { RWall } from "../plan/toWalls3d"; import { isWatertight, wallCutMeshes, type CutMesh } from "../plan/wallMeshCut"; import { evaluateRoom } from "../geometry/roomArea"; import { columnFootprint } from "../geometry/column"; +import { openingInterval, openingVerticalExtent } from "../geometry/opening"; import { emitRoofs } from "../plan/toWalls3d/roofs"; // ── IFC-GUID (Base64-Kompression, 22 Zeichen) ─────────────────────────────── @@ -107,28 +115,53 @@ function compressGuidHex(hex32: string): string { return out; } -/** FNV-1a-64 (BigInt) — reines Determinismus-/Streuungs-Werkzeug, keine Kryptografie. */ -function fnv1a64(str: string, seed: bigint): bigint { +const MASK64 = 0xffffffffffffffffn; + +/** Mischt die Bits eines 64-Bit-Werts (MurmurHash3-fmix64): jedes Eingabebit wirkt auf alle Ausgabebits. */ +function fmix64(k: bigint): bigint { + k ^= k >> 33n; + k = (k * 0xff51afd7ed558ccdn) & MASK64; + k ^= k >> 33n; + k = (k * 0xc4ceb9fe1a85ec53n) & MASK64; + k ^= k >> 33n; + return k; +} + +/** FNV-1a-64 über Bytes (vorwärts oder rückwärts) — reines Streuungswerkzeug, keine Kryptografie. */ +function fnv1a64(bytes: Uint8Array, seed: bigint, reverse: boolean): bigint { const prime = 0x100000001b3n; - const mask = 0xffffffffffffffffn; - let hash = seed & mask; - for (let i = 0; i < str.length; i++) { - hash ^= BigInt(str.charCodeAt(i)); - hash = (hash * prime) & mask; + let hash = seed & MASK64; + for (let i = 0; i < bytes.length; i++) { + hash ^= BigInt(bytes[reverse ? bytes.length - 1 - i : i]); + hash = (hash * prime) & MASK64; } return hash; } -/** Leitet aus einer stabilen Element-ID einen deterministischen 128-Bit-Hex-Wert ab. */ -function idToHex32(id: string): string { - const h1 = fnv1a64(id, 0xcbf29ce484222325n); - const h2 = fnv1a64(`${id}salt`, 0x9e3779b97f4a7c15n); - return h1.toString(16).padStart(16, "0") + h2.toString(16).padStart(16, "0"); +const utf8 = new TextEncoder(); + +/** + * Deterministischer 128-Bit-Wert (32 Hex-Zeichen) aus einem Namen: zwei unabhängige 64-Bit-Läufe + * (FNV-1a vorwärts/rückwärts mit verschiedenen Startwerten, je fmix64-nachgemischt), gekennzeichnet + * als RFC-9562-UUID Version 8 (namensbasiert, eigener Hash) mit Variante 10. + */ +function nameToHex32(name: string): string { + const bytes = utf8.encode(name); + const h1 = fmix64(fnv1a64(bytes, 0xcbf29ce484222325n, false)); + const h2 = fmix64(fnv1a64(bytes, 0x9e3779b97f4a7c15n, true) ^ BigInt(bytes.length)); + const hex = (h1.toString(16).padStart(16, "0") + h2.toString(16).padStart(16, "0")).split(""); + hex[12] = "8"; // Version 8 + hex[16] = ((parseInt(hex[16], 16) & 0x3) | 0x8).toString(16); // Variante 10xx + return hex.join(""); } -/** Deterministische 22-stellige IFC-GUID aus einer beliebigen Element-ID. */ -export function ifcGuid(id: string): string { - return compressGuidHex(idToHex32(id)); +/** + * Deterministische 22-stellige IFC-GUID aus einem Namen. Im Export lautet der Name immer + * `//[/]` (s. `exportIfcSpf`), damit gleiche ids verschiedener + * Bauteilarten oder Projekte nicht kollidieren. + */ +export function ifcGuid(name: string): string { + return compressGuidHex(nameToHex32(name)); } // ── STEP-Formatierung ─────────────────────────────────────────────────────── @@ -218,23 +251,56 @@ function leftNormal(u: Vec2): Vec2 { function addScaled(p: Vec2, d: Vec2, s: number): Vec2 { return { x: p.x + d.x * s, y: p.y + d.y * s }; } +function dot(a: Vec2, b: Vec2): number { + return a.x * b.x + a.y * b.y; +} -/** Rechteck-Footprint einer Öffnung im Wandloch (volle Wanddicke tief), CCW. */ -function openingFootprint(project: Project, wall: Wall, opening: Opening): Vec2[] { +/** Rechteck `[from,to]` entlang der Wandachse × `[nLo,nHi]` quer dazu (Welt-XY, CCW). */ +function axisRect(wall: Wall, from: number, to: number, nLo: number, nHi: number): Vec2[] { const u = normalize(sub(wall.end, wall.start)); const n = leftNormal(u); - const t = wallTypeThickness(getWallType(project, wall)); - const off = wallReferenceOffset(wall, t); - const inner = -t / 2 + off; - const outer = t / 2 + off; - const a = addScaled(wall.start, u, opening.position); - const b = addScaled(wall.start, u, opening.position + opening.width); - return [ - addScaled(a, n, inner), - addScaled(b, n, inner), - addScaled(b, n, outer), - addScaled(a, n, outer), - ]; + const a = addScaled(wall.start, u, from); + const b = addScaled(wall.start, u, to); + return [addScaled(a, n, nLo), addScaled(b, n, nLo), addScaled(b, n, nHi), addScaled(a, n, nHi)]; +} + +/** Öffnung einer Wand, wie sie das 3D als Loch in die Bänder stanzt (Achs-Intervall + absolute Z). */ +interface WallCutout { + opening: Opening; + from: number; + to: number; + zBottom: number; + zTop: number; +} + +/** Toleranz des Rust-Kerns (`wall_bands.rs::EPS`) für „Öffnung trifft Band". */ +const BAND_EPS = 1e-4; + +/** + * Ob die Schicht-Bänder einer Wand exakt „Quader minus Öffnungen" sind: kein Band mit schräger + * Oberkante, und jedes Band trägt genau die Öffnungen als Löcher, die es in der Höhe trifft — in + * derselben Grösse (kein Laibungs-Rücksprung o. ä.). Dann ergibt Extrusion je Band minus + * IfcOpeningElement denselben Körper wie das 3D-Mesh. + */ +function bandsMatchOpenings(wall: Wall, bands: readonly RWall[], cutouts: readonly WallCutout[]): boolean { + const u = normalize(sub(wall.end, wall.start)); + const byFrom = (p: number[], q: number[]) => p[0] - q[0] || p[2] - q[2]; + for (const b of bands) { + if (b.topDrop && (Math.abs(b.topDrop[0]) > 1e-9 || Math.abs(b.topDrop[1]) > 1e-9)) return false; + const a = dot({ x: b.start[0] - wall.start.x, y: b.start[1] - wall.start.y }, u); + const zb = b.baseElevation; + const zt = b.baseElevation + b.height; + const expected = cutouts + .filter((h) => h.zTop > zb + BAND_EPS && h.zBottom < zt - BAND_EPS) + .map((h) => [h.from - a, h.to - a, h.zBottom, h.zTop]) + .sort(byFrom); + const actual = (b.holes ?? []).map((h) => [h.from, h.to, h.zBottom, h.zTop]).sort(byFrom); + if (expected.length !== actual.length) return false; + for (let i = 0; i < expected.length; i++) { + for (let k = 0; k < 4; k++) if (!(Math.abs(expected[i][k] - actual[i][k]) <= 1e-6)) return false; + } + } + return true; } /** @@ -301,18 +367,29 @@ function stairFootprint(stair: Stair): Vec2[] { // ── IFC4-Export ────────────────────────────────────────────────────────────── -interface StoreyRef { - entityId: number; - placementId: number; - baseElevation: number; -} - interface Structure { entityId: number; placementId: number; baseElevation: number; + /** Stabiler Schlüssel für abgeleitete GUIDs (`storey/` oder `building`). */ + key: string; } +/** Was die Öffnungen von ihrer Wirtswand brauchen. */ +interface WallRef { + entityId: number; + placementId: number; + /** Ausdehnung aller Bänder quer zur Wandachse (entlang der linken Normalen ab `wall.start`). */ + nLo: number; + nHi: number; +} + +/** Wie weit der Öffnungskörper beidseits über die Wandflächen vorsteht (keine koplanaren Booleans). */ +const OPENING_OVERSHOOT = 0.02; + +/** IFC-Wert-Ausdruck einer Pset-Eigenschaft, z. B. `IFCIDENTIFIER('…')`. */ +type PropValue = string; + /** * Baut aus einem Projekt einen vollständigen IFC4-SPF-String (STEP Physical * File). Reiner Rechenkern — kein Datei-IO. Leeres Projekt ⇒ valider Minimal- @@ -327,6 +404,9 @@ export function exportIfcSpf(projectIn: Project): string { const project = projectToWorldCoords(projectIn); const w = new StepWriter(); + /** Dauerhafte GlobalId (als STEP-String) aus `/[/]`, im Namensraum des Projekts. */ + const gid = (key: string): string => S(ifcGuid(`${project.id}/${key}`)); + // Geteilte Grundgeometrie: Ursprung, Z-Extrusionsrichtung, Identitäts- // Placement (Position aller ExtrudedAreaSolid — Profile tragen direkt // Welt-X/Y, siehe Dateikopf). @@ -394,7 +474,7 @@ export function exportIfcSpf(projectIn: Project): string { const projectId = w.add( "IFCPROJECT", - `${S(ifcGuid(`${project.id}:project`))},#${ownerHistory},${S(project.name || "Projekt")},$,$,$,$,${LIST([`#${context}`])},#${unitAssignment}`, + `${gid("project")},#${ownerHistory},${S(project.name || "Projekt")},$,$,$,$,${LIST([`#${context}`])},#${unitAssignment}`, ); // RefElevation (m ü. M.): reale Datumshöhe des Standorts aus dem // Georeferenzierungs-Bezug (wie ArchiCADs Vermessungspunkt). Rein informativ — @@ -403,24 +483,24 @@ export function exportIfcSpf(projectIn: Project): string { const siteRefElev = typeof refElevation === "number" ? R(refElevation) : "$"; const siteId = w.add( "IFCSITE", - `${S(ifcGuid(`${project.id}:site`))},#${ownerHistory},${S("Standort")},$,$,#${sitePlacement},$,$,${ENUM("ELEMENT")},$,$,${siteRefElev},$,$`, + `${gid("site")},#${ownerHistory},${S("Standort")},$,$,#${sitePlacement},$,$,${ENUM("ELEMENT")},$,$,${siteRefElev},$,$`, ); const buildingId = w.add( "IFCBUILDING", - `${S(ifcGuid(`${project.id}:building`))},#${ownerHistory},${S(project.name || "Gebäude")},$,$,#${buildingPlacement},$,$,${ENUM("ELEMENT")},$,$,$`, + `${gid("building")},#${ownerHistory},${S(project.name || "Gebäude")},$,$,#${buildingPlacement},$,$,${ENUM("ELEMENT")},$,$,$`, ); w.add( "IFCRELAGGREGATES", - `${S(ifcGuid(`${project.id}:agg-site`))},#${ownerHistory},$,$,#${projectId},${LIST([`#${siteId}`])}`, + `${gid("aggregates/site")},#${ownerHistory},$,$,#${projectId},${LIST([`#${siteId}`])}`, ); w.add( "IFCRELAGGREGATES", - `${S(ifcGuid(`${project.id}:agg-building`))},#${ownerHistory},$,$,#${siteId},${LIST([`#${buildingId}`])}`, + `${gid("aggregates/building")},#${ownerHistory},$,$,#${siteId},${LIST([`#${buildingId}`])}`, ); // Je "floor"-Geschoss ein IfcBuildingStorey (Elevation = baseElevation). const floors = project.drawingLevels.filter((l) => l.kind === "floor"); - const storeyByFloorId = new Map(); + const storeyByFloorId = new Map(); const storeyEntityIds: number[] = []; for (const floor of floors) { const base = floor.baseElevation ?? 0; @@ -429,34 +509,80 @@ export function exportIfcSpf(projectIn: Project): string { const placementId = w.add("IFCLOCALPLACEMENT", `#${buildingPlacement},#${axis}`); const entityId = w.add( "IFCBUILDINGSTOREY", - `${S(ifcGuid(`${floor.id}:storey`))},#${ownerHistory},${S(floor.name)},$,$,#${placementId},$,$,${ENUM("ELEMENT")},${R(base)}`, + `${gid(`storey/${floor.id}`)},#${ownerHistory},${S(floor.name)},$,$,#${placementId},$,$,${ENUM("ELEMENT")},${R(base)}`, ); - storeyByFloorId.set(floor.id, { entityId, placementId, baseElevation: base }); + storeyByFloorId.set(floor.id, { entityId, placementId, baseElevation: base, key: `storey/${floor.id}` }); storeyEntityIds.push(entityId); } if (storeyEntityIds.length > 0) { w.add( "IFCRELAGGREGATES", - `${S(ifcGuid(`${project.id}:agg-storeys`))},#${ownerHistory},$,$,#${buildingId},${LIST(storeyEntityIds.map((id) => `#${id}`))}`, + `${gid("aggregates/storeys")},#${ownerHistory},$,$,#${buildingId},${LIST(storeyEntityIds.map((id) => `#${id}`))}`, ); } /** Geschoss → Trägerstruktur (Storey), oder defensiv das Gebäude (verwaiste floorId). */ - const resolveStructure = (floorId: string): Structure => { - const s = storeyByFloorId.get(floorId); - if (s) return { entityId: s.entityId, placementId: s.placementId, baseElevation: s.baseElevation }; - return { entityId: buildingId, placementId: buildingPlacement, baseElevation: 0 }; - }; + const buildingStructure: Structure = { entityId: buildingId, placementId: buildingPlacement, baseElevation: 0, key: "building" }; + const resolveStructure = (floorId: string): Structure => storeyByFloorId.get(floorId) ?? buildingStructure; // Räumliche Eingliederung sammelt sich je Trägerstruktur (Storey/Building) // und wird am Ende in EINE IfcRelContainedInSpatialStructure je Struktur // gebündelt (Öffnungen NICHT — die hängen nur über RelVoidsElement an ihrer // Wand, wie in IFC üblich). - const containment = new Map(); - const addToContainment = (structureId: number, elementId: number): void => { - const arr = containment.get(structureId); + const containment = new Map(); + const addToContainment = (structure: Structure, elementId: number): void => { + const arr = containment.get(structure); if (arr) arr.push(elementId); - else containment.set(structureId, [elementId]); + else containment.set(structure, [elementId]); + }; + + // Eigenschaftssätze: gleicher Inhalt ⇒ EIN IfcPropertySet + EINE IfcRelDefinesByProperties für + // alle Bauteile (z. B. alle Wände eines Typs). GUID aus dem Inhalt — stabil, solange er gleich bleibt. + const psets = new Map(); + const addPset = (name: string, props: [string, PropValue][], elementId: number): void => { + if (props.length === 0) return; // IfcPropertySet verlangt mindestens eine Eigenschaft + const key = `${name}/${JSON.stringify(props)}`; + const hit = psets.get(key); + if (hit) hit.related.push(elementId); + else psets.set(key, { name, props, related: [elementId] }); + }; + const identifier = (v: string): PropValue => `IFCIDENTIFIER(${S(v)})`; + const bool = (v: boolean): PropValue => `IFCBOOLEAN(${v ? ".T." : ".F."})`; + + /** Profil (geschlossenes Polygon in Welt-XY) als IfcExtrudedAreaSolid, Unterkante `zRel` in `+Z`. */ + const emitExtrusion = (footprint: Vec2[], zRel: number, depth: number): number => { + const closed = [...footprint, footprint[0]]; + const ptIds = closed.map((p) => w.add("IFCCARTESIANPOINT", LIST([R(p.x), R(p.y)]))); + const polylineId = w.add("IFCPOLYLINE", LIST(ptIds.map((id) => `#${id}`))); + const profileId = w.add( + "IFCARBITRARYCLOSEDPROFILEDEF", + `${ENUM("AREA")},$,#${polylineId}`, + ); + let position = identityAxis; + if (zRel !== 0) { + const pt = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(zRel)])); + position = w.add("IFCAXIS2PLACEMENT3D", `#${pt},$,$`); + } + return w.add( + "IFCEXTRUDEDAREASOLID", + `#${profileId},#${position},#${extrudeDir},${R(Math.max(depth, 0.001))}`, + ); + }; + + /** Placement im Abstand `zRel` über `placementRelTo`. */ + const emitPlacement = (zRel: number, placementRelTo: number): number => { + const elemOrigin = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(zRel)])); + const elemAxis = w.add("IFCAXIS2PLACEMENT3D", `#${elemOrigin},$,$`); + return w.add("IFCLOCALPLACEMENT", `#${placementRelTo},#${elemAxis}`); + }; + + /** SweptSolid-Körper aus Extrusionen. */ + const emitSweptShape = (solids: number[]): number => { + const shapeRepId = w.add( + "IFCSHAPEREPRESENTATION", + `#${context},${S("Body")},${S("SweptSolid")},${LIST(solids.map((id) => `#${id}`))}`, + ); + return w.add("IFCPRODUCTDEFINITIONSHAPE", `$,$,${LIST([`#${shapeRepId}`])}`); }; /** Baut Profil+Extrusion+Shape+Placement für einen geschlossenen Footprint. */ @@ -466,26 +592,8 @@ export function exportIfcSpf(projectIn: Project): string { depth: number, placementRelTo: number, ): { placementId: number; shapeId: number } => { - const closed = [...footprint, footprint[0]]; - const ptIds = closed.map((p) => w.add("IFCCARTESIANPOINT", LIST([R(p.x), R(p.y)]))); - const polylineId = w.add("IFCPOLYLINE", LIST(ptIds.map((id) => `#${id}`))); - const profileId = w.add( - "IFCARBITRARYCLOSEDPROFILEDEF", - `${ENUM("AREA")},$,#${polylineId}`, - ); - const solidId = w.add( - "IFCEXTRUDEDAREASOLID", - `#${profileId},#${identityAxis},#${extrudeDir},${R(Math.max(depth, 0.001))}`, - ); - const shapeRepId = w.add( - "IFCSHAPEREPRESENTATION", - `#${context},${S("Body")},${S("SweptSolid")},${LIST([`#${solidId}`])}`, - ); - const shapeId = w.add("IFCPRODUCTDEFINITIONSHAPE", `$,$,${LIST([`#${shapeRepId}`])}`); - const elemOrigin = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(zBottomRel)])); - const elemAxis = w.add("IFCAXIS2PLACEMENT3D", `#${elemOrigin},$,$`); - const placementId = w.add("IFCLOCALPLACEMENT", `#${placementRelTo},#${elemAxis}`); - return { placementId, shapeId }; + const shapeId = emitSweptShape([emitExtrusion(footprint, 0, depth)]); + return { placementId: emitPlacement(zBottomRel, placementRelTo), shapeId }; }; /** @@ -524,10 +632,7 @@ export function exportIfcSpf(projectIn: Project): string { `#${context},${S("Body")},${S("Tessellation")},${LIST([`#${faceSetId}`])}`, ); const shapeId = w.add("IFCPRODUCTDEFINITIONSHAPE", `$,$,${LIST([`#${shapeRepId}`])}`); - const elemOrigin = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(0)])); - const elemAxis = w.add("IFCAXIS2PLACEMENT3D", `#${elemOrigin},$,$`); - const placementId = w.add("IFCLOCALPLACEMENT", `#${placementRelTo},#${elemAxis}`); - return { placementId, shapeId }; + return { placementId: emitPlacement(0, placementRelTo), shapeId }; }; /** Baut ein IfcBuildingElement-Subtyp mit dem üblichen 9-Attribut-Flatten. */ @@ -541,15 +646,13 @@ export function exportIfcSpf(projectIn: Project): string { ): number => w.add( type, - `${S(guid)},#${ownerHistory},${S(name)},$,$,#${placementId},#${shapeId},$,${predefinedType ?? "$"}`, + `${guid},#${ownerHistory},${S(name)},$,$,#${placementId},#${shapeId},$,${predefinedType ?? "$"}`, ); // ── Bauteiltypen mit Materialschichten ───────────────────────────────── // Je Wand-/Deckentyp ein IfcWallType/IfcSlabType mit IfcMaterialLayerSet (Schichten in der // Reihenfolge des Typs, Material = Bauteil). Die Wände/Decken erben ihn über - // IfcRelDefinesByType. Bewusst KEIN IfcMaterialLayerSetUsage am Exemplar: die Wand-Geometrie ist - // ein Mesh ohne Achs-Darstellung, eine Usage (Richtung/Versatz zur Bezugslinie) hätte keinen - // Bezug (s. Dateikopf). + // IfcRelDefinesByType. Bewusst KEIN IfcMaterialLayerSetUsage am Exemplar (s. Dateikopf). const materialIdByComponent = new Map(); const materialOf = (componentId: string): number => { const hit = materialIdByComponent.get(componentId); @@ -569,7 +672,7 @@ export function exportIfcSpf(projectIn: Project): string { predefined: string, t: { id: string; name: string; layers: { componentId: string; thickness: number }[] }, ): ElementTypeRef => { - const key = `${ifcType}:${t.id}`; + const key = `type/${ifcType}/${t.id}`; const hit = elementTypes.get(key); if (hit) return hit; const layerIds = t.layers.map((l) => @@ -577,13 +680,13 @@ export function exportIfcSpf(projectIn: Project): string { ); const typeId = w.add( ifcType, - `${S(ifcGuid(key))},#${ownerHistory},${S(t.name)},$,$,$,$,$,$,${ENUM(predefined)}`, + `${gid(key)},#${ownerHistory},${S(t.name)},$,$,$,$,$,$,${ENUM(predefined)}`, ); if (layerIds.length > 0) { const setId = w.add("IFCMATERIALLAYERSET", `${LIST(layerIds.map((id) => `#${id}`))},${S(t.name)},$`); w.add( "IFCRELASSOCIATESMATERIAL", - `${S(ifcGuid(`${key}:material`))},#${ownerHistory},$,$,${LIST([`#${typeId}`])},#${setId}`, + `${gid(`${key}/material`)},#${ownerHistory},$,$,${LIST([`#${typeId}`])},#${setId}`, ); } const ref = { typeId, occurrences: [] }; @@ -591,35 +694,98 @@ export function exportIfcSpf(projectIn: Project): string { return ref; }; - // ── Wände (öffnungsgenaues Dreiecks-Mesh statt Profil-Extrusion) ──────── + // ── Wände ────────────────────────────────────────────────────────────── // Die Wand-Schicht-Bänder kommen aus DEMSELBEN geflachten Modell wie STL/OBJ - // (`pickGeometry`, Joins/Gehrungen + Öffnungs-`holes` bereits aufgelöst). Alle - // Bänder einer Wand-Id werden zu EINEM Face-Set vereint. IFC-Koordinaten: das + // (`pickGeometry`, Joins/Gehrungen + Öffnungs-`holes` bereits aufgelöst). + // + // Extrusions-Weg (s. Dateikopf): je Band ein Rechteck-Profil (Achse ± halbe Banddicke) + // von der Band-UK über die Bandhöhe; die Öffnungen schneidet der Viewer über RelVoids. + // + // Mesh-Weg: alle Bänder einer Wand-Id zu EINEM Face-Set. IFC-Koordinaten: das // Mesh liegt in Welt (Modell-x, Höhe, Modell-y) mit Y-up → IFC (x, y, z=Höhe) // mit Z-up, also (mx, mz, my); Z relativ zur Geschoss-UK, damit die Storey- // Placement-Elevation nicht doppelt zählt. - // // WICHTIG — WICKLUNG: der Achsen-Swap (x,y,z)→(x,z,y) ist eine REFLEXION // (Determinante −1) und KEHRT die Dreiecks-Wicklung UM → aus aussen orientierten // würden innen orientierte Normalen, der Viewer cullt dann die Vorderseiten und - // die Wand wirkt HOHL/offen (genau der gemeldete Bug). Deshalb wird beim Swap - // die Wicklung jedes Dreiecks umgedreht (i0,i2,i1), damit die Aussen-Normalen - // aussen bleiben. Watertightness (isWatertight) misst das anschliessend am + // die Wand wirkt HOHL/offen. Deshalb wird beim Swap die Wicklung jedes Dreiecks + // umgedreht (i0,i2,i1). Watertightness (isWatertight) misst das anschliessend am // fertigen IFC-Mesh → treibt das Closed-Flag des Face-Sets. const bandsByWallId = new Map(); const allBands = pickGeometry(project).walls; - // Loch-Ausschnitte aller Bänder in EINEM Kern-Aufruf. - const cutOf = new Map(); - wallCutMeshes(allBands).forEach((m, i) => cutOf.set(allBands[i], m)); for (const band of allBands) { const list = bandsByWallId.get(band.wallId); if (list) list.push(band); else bandsByWallId.set(band.wallId, [band]); } - const wallEntityIdByWallId = new Map(); + const cutoutsOf = (wall: Wall): WallCutout[] => { + const out: WallCutout[] = []; + for (const opening of openingsOfWall(project, wall.id)) { + const iv = openingInterval(wall, opening); + if (!iv) continue; + const v = openingVerticalExtent(project, wall, opening); + out.push({ opening, from: iv.from, to: iv.to, zBottom: v.zBottom, zTop: v.zTop }); + } + return out; + }; + const meshWalls: { wall: Wall; bands: RWall[] }[] = []; + const wallRefById = new Map(); + const cutoutsByWallId = new Map(); + const emitWallEntity = (wall: Wall, structure: Structure, placementId: number, shapeId: number, bands: RWall[]): void => { + let name = wall.id; + let wallType: ElementTypeRef | null = null; + let reference: string | null = null; + try { + const wt = getWallType(project, wall); + name = wt.name; + reference = wt.name; + wallType = typeFor("IFCWALLTYPE", "STANDARD", wt); + } catch { + /* verwaister Wandtyp — Roh-ID als Name, kein Typ */ + } + const entityId = emitBuildingElement("IFCWALL", gid(`wall/${wall.id}`), name, placementId, shapeId, null); + wallType?.occurrences.push(entityId); + addToContainment(structure, entityId); + if (reference !== null) addPset("Pset_WallCommon", [["Reference", identifier(reference)]], entityId); + // Querausdehnung aller Bänder (für den Öffnungskörper). + const u = normalize(sub(wall.end, wall.start)); + const n = leftNormal(u); + let nLo = Infinity; + let nHi = -Infinity; + for (const b of bands) { + const off = dot({ x: b.start[0] - wall.start.x, y: b.start[1] - wall.start.y }, n); + nLo = Math.min(nLo, off - b.thickness / 2); + nHi = Math.max(nHi, off + b.thickness / 2); + } + wallRefById.set(wall.id, { entityId, placementId, nLo, nHi }); + }; for (const wall of project.walls ?? []) { - const bands = bandsByWallId.get(wall.id); - if (!bands || bands.length === 0) continue; // degenerierte Wand / keine Geometrie + const bands = (bandsByWallId.get(wall.id) ?? []).filter( + (b) => Math.hypot(b.end[0] - b.start[0], b.end[1] - b.start[1]) > 1e-9 && b.height > 1e-9 && b.thickness > 1e-9, + ); + if (bands.length === 0) continue; // degenerierte Wand / keine Geometrie + const cutouts = cutoutsOf(wall); + cutoutsByWallId.set(wall.id, cutouts); + if (!bandsMatchOpenings(wall, bands, cutouts)) { + meshWalls.push({ wall, bands: bandsByWallId.get(wall.id)! }); + continue; + } + const structure = resolveStructure(wall.floorId); + const solids = bands.map((b) => { + const s: Vec2 = { x: b.start[0], y: b.start[1] }; + const e: Vec2 = { x: b.end[0], y: b.end[1] }; + const n = leftNormal(normalize(sub(e, s))); + const h = b.thickness / 2; + const rect = [addScaled(s, n, -h), addScaled(e, n, -h), addScaled(e, n, h), addScaled(s, n, h)]; + return emitExtrusion(rect, b.baseElevation - structure.baseElevation, b.height); + }); + emitWallEntity(wall, structure, emitPlacement(0, structure.placementId), emitSweptShape(solids), bands); + } + // Mesh-Weg: Loch-Ausschnitte aller betroffenen Bänder in EINEM Kern-Aufruf. + const meshBands = meshWalls.flatMap((m) => m.bands); + const cutOf = new Map(); + wallCutMeshes(meshBands).forEach((m, i) => cutOf.set(meshBands[i], m)); + for (const { wall, bands } of meshWalls) { const structure = resolveStructure(wall.floorId); const positions: number[] = []; const indices: number[] = []; @@ -642,19 +808,7 @@ export function exportIfcSpf(projectIn: Project): string { if (indices.length === 0) continue; const closed = isWatertight({ positions, indices }); const { placementId, shapeId } = emitTriangulatedProduct(positions, indices, structure.placementId, closed); - let name = wall.id; - let wallType: ElementTypeRef | null = null; - try { - const wt = getWallType(project, wall); - name = wt.name; - wallType = typeFor("IFCWALLTYPE", "STANDARD", wt); - } catch { - /* verwaister Wandtyp — Roh-ID als Name, kein Typ */ - } - const entityId = emitBuildingElement("IFCWALL", ifcGuid(wall.id), name, placementId, shapeId, null); - wallType?.occurrences.push(entityId); - wallEntityIdByWallId.set(wall.id, entityId); - addToContainment(structure.entityId, entityId); + emitWallEntity(wall, structure, placementId, shapeId, bands); } // ── Decken ───────────────────────────────────────────────────────────── @@ -670,62 +824,90 @@ export function exportIfcSpf(projectIn: Project): string { ); let name: string = ceiling.id; let slabType: ElementTypeRef | null = null; + let reference: string | null = null; try { const ct = getCeilingType(project, ceiling); name = ct.name; + reference = ct.name; slabType = typeFor("IFCSLABTYPE", "FLOOR", ct); } catch { /* verwaister Deckentyp — Roh-ID als Name, kein Typ */ } const entityId = emitBuildingElement( "IFCSLAB", - ifcGuid(ceiling.id), + gid(`slab/${ceiling.id}`), name, placementId, shapeId, ENUM("FLOOR"), ); slabType?.occurrences.push(entityId); - addToContainment(structure.entityId, entityId); + addToContainment(structure, entityId); + if (reference !== null) addPset("Pset_SlabCommon", [["Reference", identifier(reference)]], entityId); } - // ── Fenster/Türen als eigene Objekte (IfcDoor/IfcWindow) ──────────────── - // KEIN IfcOpeningElement/IfcRelVoidsElement/IfcRelFillsElement mehr: das Loch - // steckt bereits im Wand-Face-Set (s. o.). Eine Void-Relation beschriebe eine - // Boolean-Subtraktion gegen einen Swept-Solid, den es nicht mehr gibt — sie - // brächte in den Viewern nur Verwirrung (der Nutzer-Bug war genau, dass die - // Void nicht subtrahiert wurde). Tür/Fenster bleiben als EIGENES Objekt mit - // eigener Box-Geometrie erhalten, die das ausgeschnittene Loch füllt ("sieht - // aus wie 3D"): kein Blatt-/Rahmendetail (bewusste Vereinfachung). - for (const opening of project.openings ?? []) { - const wall = (project.walls ?? []).find((wl) => wl.id === opening.hostWallId); - if (!wall) continue; // verwaiste Wirtswand — keine Geometrie ableitbar - if (!wallEntityIdByWallId.has(wall.id)) continue; // Wirtswand übersprungen (degeneriert) - - const wallExtent = wallVerticalExtent(project, wall); + // ── Öffnungen: IfcOpeningElement in der Wand, IfcDoor/IfcWindow darin ─── + // Der Öffnungskörper ist ein Quader über das Achs-Intervall und die Höhe, wie sie das 3D + // stanzt (`openingInterval`/`openingVerticalExtent`), quer über alle Bänder der Wand plus + // OPENING_OVERSHOOT. Die Füllung (Tür/Fenster) sitzt im Öffnungs-Placement, über die + // Banddicke, ohne Blatt-/Rahmendetail. + for (const wall of project.walls ?? []) { + const host = wallRefById.get(wall.id); + if (!host) continue; // Wirtswand übersprungen (degeneriert) const structure = resolveStructure(wall.floorId); - const footprint = openingFootprint(project, wall, opening); - const zSillAbs = wallExtent.zBottom + opening.sillHeight; + for (const c of cutoutsByWallId.get(wall.id) ?? []) { + const { opening } = c; + const depth = c.zTop - c.zBottom; + if (!(depth > 1e-6)) continue; + const voidRect = axisRect(wall, c.from, c.to, host.nLo - OPENING_OVERSHOOT, host.nHi + OPENING_OVERSHOOT); + const { placementId: openingPlacement, shapeId: openingShape } = emitBoxProduct( + voidRect, + c.zBottom - structure.baseElevation, + depth, + host.placementId, + ); + const openingEntityId = w.add( + "IFCOPENINGELEMENT", + `${gid(`opening/${opening.id}`)},#${ownerHistory},${S(opening.kind === "door" ? "Türöffnung" : "Fensteröffnung")},$,$,#${openingPlacement},#${openingShape},$,${ENUM("OPENING")}`, + ); + w.add( + "IFCRELVOIDSELEMENT", + `${gid(`voids/${opening.id}`)},#${ownerHistory},$,$,#${host.entityId},#${openingEntityId}`, + ); - const { placementId: fillPlacement, shapeId: fillShape } = emitBoxProduct( - footprint, - zSillAbs - structure.baseElevation, - opening.height, - structure.placementId, - ); - const fillGuid = ifcGuid(`${opening.id}:fill`); - const fillName = openingLabel(opening); - const fillEntityId = - opening.kind === "door" - ? w.add( - "IFCDOOR", - `${S(fillGuid)},#${ownerHistory},${S(fillName)},$,$,#${fillPlacement},#${fillShape},$,${R(opening.height)},${R(opening.width)},${ENUM("DOOR")},$,$`, - ) - : w.add( - "IFCWINDOW", - `${S(fillGuid)},#${ownerHistory},${S(fillName)},$,$,#${fillPlacement},#${fillShape},$,${R(opening.height)},${R(opening.width)},${ENUM("WINDOW")},$,$`, - ); - addToContainment(structure.entityId, fillEntityId); + const { placementId: fillPlacement, shapeId: fillShape } = emitBoxProduct( + axisRect(wall, c.from, c.to, host.nLo, host.nHi), + 0, + depth, + openingPlacement, + ); + const fillName = openingLabel(opening); + const isDoor = opening.kind === "door"; + const fillEntityId = w.add( + isDoor ? "IFCDOOR" : "IFCWINDOW", + `${gid(`fill/${opening.id}`)},#${ownerHistory},${S(fillName)},$,$,#${fillPlacement},#${fillShape},$,${R(depth)},${R(c.to - c.from)},${ENUM(isDoor ? "DOOR" : "WINDOW")},$,$`, + ); + w.add( + "IFCRELFILLSELEMENT", + `${gid(`fills/${opening.id}`)},#${ownerHistory},$,$,#${openingEntityId},#${fillEntityId}`, + ); + addToContainment(structure, fillEntityId); + + const props: [string, PropValue][] = []; + if (isDoor) { + const dt = getDoorType(project, opening); + if (dt) props.push(["Reference", identifier(dt.name)]); + const ratio = dt?.glazingRatio; + if (dt?.leafStyle === "glas" && typeof ratio === "number" && ratio > 0 && ratio <= 1) { + props.push(["GlazingAreaFraction", `IFCPOSITIVERATIOMEASURE(${R(ratio)})`]); + } + addPset("Pset_DoorCommon", props, fillEntityId); + } else { + const wt = getWindowType(project, opening); + if (wt) props.push(["Reference", identifier(wt.name)]); + addPset("Pset_WindowCommon", props, fillEntityId); + } + } } // ── Treppen (vereinfachter Bounding-Footprint, siehe Dateikopf) ──────── @@ -748,13 +930,13 @@ export function exportIfcSpf(projectIn: Project): string { : ENUM("QUARTER_TURN_STAIR"); const entityId = emitBuildingElement( "IFCSTAIR", - ifcGuid(stair.id), + gid(`stair/${stair.id}`), "Treppe", placementId, shapeId, predefinedType, ); - addToContainment(structure.entityId, entityId); + addToContainment(structure, entityId); } // ── Extrudierte Körper (truck-Integration) → IfcBuildingElementProxy ─── @@ -771,34 +953,36 @@ export function exportIfcSpf(projectIn: Project): string { ); const entityId = emitBuildingElement( "IFCBUILDINGELEMENTPROXY", - ifcGuid(solid.id), + gid(`extrusion/${solid.id}`), "Extrusion", placementId, shapeId, null, ); - addToContainment(structure.entityId, entityId); + addToContainment(structure, entityId); } // ── Räume → IfcSpace ─────────────────────────────────────────────────── // Je Raum ein IfcSpace (Name = Raumnummer, LongName = Raumname), als Extrusion der lichten // Innenkontur über die lichte Geschosshöhe. Räume sind räumliche Elemente: sie werden im // Geschoss AGGREGIERT (IfcRelAggregates), nicht enthalten. Dazu Basismengen - // (Qto_SpaceBaseQuantities) und die SIA-416-Kategorie als Eigenschaft. - const spacesByStructure = new Map(); + // (Qto_SpaceBaseQuantities), die SIA-416-Kategorie als Eigenschaft und Pset_SpaceCommon + // (AGF = Aussengeschossfläche ⇒ aussen, alles andere innen). + const spacesByStructure = new Map(); for (const room of project.rooms ?? []) { if (room.boundary.length < 3) continue; const structure = resolveStructure(room.floorId); const floor = floors.find((f) => f.id === room.floorId); const height = floor?.floorHeight && floor.floorHeight > 0 ? floor.floorHeight : 2.5; const { placementId, shapeId } = emitBoxProduct(room.boundary, 0, height, structure.placementId); + const external = room.siaCategory === "AGF"; const spaceId = w.add( "IFCSPACE", - `${S(ifcGuid(room.id))},#${ownerHistory},${S(room.stamp?.number || room.id)},$,$,#${placementId},#${shapeId},${S(room.name)},${ENUM("ELEMENT")},${ENUM("INTERNAL")},$`, + `${gid(`space/${room.id}`)},#${ownerHistory},${S(room.stamp?.number || room.id)},$,$,#${placementId},#${shapeId},${S(room.name)},${ENUM("ELEMENT")},${ENUM(external ? "EXTERNAL" : "INTERNAL")},$`, ); - const list = spacesByStructure.get(structure.entityId); + const list = spacesByStructure.get(structure); if (list) list.push(spaceId); - else spacesByStructure.set(structure.entityId, [spaceId]); + else spacesByStructure.set(structure, [spaceId]); const area = evaluateRoom(room.boundary, room.siaCategory); const qNet = w.add("IFCQUANTITYAREA", `${S("NetFloorArea")},$,$,${R(area.netArea)},$`); @@ -806,26 +990,30 @@ export function exportIfcSpf(projectIn: Project): string { const qHeight = w.add("IFCQUANTITYLENGTH", `${S("Height")},$,$,${R(height)},$`); const qto = w.add( "IFCELEMENTQUANTITY", - `${S(ifcGuid(`${room.id}:qto`))},#${ownerHistory},${S("Qto_SpaceBaseQuantities")},$,$,${LIST([`#${qNet}`, `#${qGross}`, `#${qHeight}`])}`, + `${gid(`space/${room.id}/qto`)},#${ownerHistory},${S("Qto_SpaceBaseQuantities")},$,$,${LIST([`#${qNet}`, `#${qGross}`, `#${qHeight}`])}`, ); w.add( "IFCRELDEFINESBYPROPERTIES", - `${S(ifcGuid(`${room.id}:rel-qto`))},#${ownerHistory},$,$,${LIST([`#${spaceId}`])},#${qto}`, + `${gid(`space/${room.id}/qto-rel`)},#${ownerHistory},$,$,${LIST([`#${spaceId}`])},#${qto}`, ); const sia = w.add("IFCPROPERTYSINGLEVALUE", `${S("SIA416")},$,IFCLABEL(${S(room.siaCategory)}),$`); const pset = w.add( "IFCPROPERTYSET", - `${S(ifcGuid(`${room.id}:pset`))},#${ownerHistory},${S("CH_Raum")},$,${LIST([`#${sia}`])}`, + `${gid(`space/${room.id}/pset`)},#${ownerHistory},${S("CH_Raum")},$,${LIST([`#${sia}`])}`, ); w.add( "IFCRELDEFINESBYPROPERTIES", - `${S(ifcGuid(`${room.id}:rel-pset`))},#${ownerHistory},$,$,${LIST([`#${spaceId}`])},#${pset}`, + `${gid(`space/${room.id}/pset-rel`)},#${ownerHistory},$,$,${LIST([`#${spaceId}`])},#${pset}`, ); + const common: [string, PropValue][] = []; + if (room.stamp?.number) common.push(["Reference", identifier(room.stamp.number)]); + common.push(["IsExternal", bool(external)]); + addPset("Pset_SpaceCommon", common, spaceId); } - for (const [structureId, spaceIds] of spacesByStructure) { + for (const [structure, spaceIds] of spacesByStructure) { w.add( "IFCRELAGGREGATES", - `${S(ifcGuid(`spaces:${structureId}`))},#${ownerHistory},$,$,#${structureId},${LIST(spaceIds.map((id) => `#${id}`))}`, + `${gid(`aggregates/spaces/${structure.key}`)},#${ownerHistory},$,$,#${structure.entityId},${LIST(spaceIds.map((id) => `#${id}`))}`, ); } @@ -866,13 +1054,18 @@ export function exportIfcSpf(projectIn: Project): string { const { placementId, shapeId } = emitTriangulatedProduct(positions, indices, structure.placementId, closed); const predefined = ROOF_PREDEFINED[roof.shape] ?? "NOTDEFINED"; const roofType = roof.roofTypeId ? (project.roofTypes ?? []).find((t) => t.id === roof.roofTypeId) : undefined; - const entityId = emitBuildingElement("IFCROOF", ifcGuid(roof.id), roofType?.name ?? "Dach", placementId, shapeId, ENUM(predefined)); + const entityId = emitBuildingElement("IFCROOF", gid(`roof/${roof.id}`), roofType?.name ?? "Dach", placementId, shapeId, ENUM(predefined)); if (roofType) typeFor("IFCROOFTYPE", predefined, roofType).occurrences.push(entityId); - addToContainment(structure.entityId, entityId); + addToContainment(structure, entityId); + // Ein Dach ist Gebäudehülle: IsExternal folgt aus der Bauteilart, nicht aus einer Annahme. + const props: [string, PropValue][] = []; + if (roofType) props.push(["Reference", identifier(roofType.name)]); + props.push(["IsExternal", bool(true)]); + addPset("Pset_RoofCommon", props, entityId); } // ── Stützen → IfcColumn (Profil-Extrusion, Material = Bauteil) ────────── - const materialAssoc = new Map(); + const materialAssoc = new Map(); for (const col of project.columns ?? []) { const footprint = columnFootprint(col); if (footprint.length < 3) continue; @@ -880,19 +1073,20 @@ export function exportIfcSpf(projectIn: Project): string { if (!(zTop > zBottom)) continue; const structure = resolveStructure(col.floorId); const { placementId, shapeId } = emitBoxProduct(footprint, zBottom - structure.baseElevation, zTop - zBottom, structure.placementId); - const entityId = emitBuildingElement("IFCCOLUMN", ifcGuid(col.id), columnLabel(col), placementId, shapeId, ENUM("COLUMN")); - addToContainment(structure.entityId, entityId); + const label = columnLabel(col); + const entityId = emitBuildingElement("IFCCOLUMN", gid(`column/${col.id}`), label, placementId, shapeId, ENUM("COLUMN")); + addToContainment(structure, entityId); + addPset("Pset_ColumnCommon", [["Reference", identifier(label)]], entityId); if (col.componentId) { - const mat = materialOf(col.componentId); - const list = materialAssoc.get(mat); + const list = materialAssoc.get(col.componentId); if (list) list.push(entityId); - else materialAssoc.set(mat, [entityId]); + else materialAssoc.set(col.componentId, [entityId]); } } - for (const [mat, ids] of materialAssoc) { + for (const [componentId, ids] of materialAssoc) { w.add( "IFCRELASSOCIATESMATERIAL", - `${S(ifcGuid(`material:${mat}`))},#${ownerHistory},$,$,${LIST(ids.map((id) => `#${id}`))},#${mat}`, + `${gid(`material/${componentId}/columns`)},#${ownerHistory},$,$,${LIST(ids.map((id) => `#${id}`))},#${materialOf(componentId)}`, ); } @@ -901,15 +1095,28 @@ export function exportIfcSpf(projectIn: Project): string { if (ref.occurrences.length === 0) continue; w.add( "IFCRELDEFINESBYTYPE", - `${S(ifcGuid(`${key}:occurrences`))},#${ownerHistory},$,$,${LIST(ref.occurrences.map((id) => `#${id}`))},#${ref.typeId}`, + `${gid(`${key}/occurrences`)},#${ownerHistory},$,$,${LIST(ref.occurrences.map((id) => `#${id}`))},#${ref.typeId}`, + ); + } + + // ── Eigenschaftssätze (Pset_*Common) ─────────────────────────────────── + for (const [key, ps] of psets) { + const propIds = ps.props.map(([name, value]) => w.add("IFCPROPERTYSINGLEVALUE", `${S(name)},$,${value},$`)); + const psetId = w.add( + "IFCPROPERTYSET", + `${gid(`pset/${key}`)},#${ownerHistory},${S(ps.name)},$,${LIST(propIds.map((id) => `#${id}`))}`, + ); + w.add( + "IFCRELDEFINESBYPROPERTIES", + `${gid(`pset/${key}/rel`)},#${ownerHistory},$,$,${LIST(ps.related.map((id) => `#${id}`))},#${psetId}`, ); } // ── Räumliche Eingliederung (gebündelt je Trägerstruktur) ────────────── - for (const [structureId, elementIds] of containment) { + for (const [structure, elementIds] of containment) { w.add( "IFCRELCONTAINEDINSPATIALSTRUCTURE", - `${S(ifcGuid(`contain:${structureId}`))},#${ownerHistory},$,$,${LIST(elementIds.map((id) => `#${id}`))},#${structureId}`, + `${gid(`contains/${structure.key}`)},#${ownerHistory},$,$,${LIST(elementIds.map((id) => `#${id}`))},#${structure.entityId}`, ); } diff --git a/src/export/exportIfc.validate.test.ts b/src/export/exportIfc.validate.test.ts index 293df323..7dd152b8 100644 --- a/src/export/exportIfc.validate.test.ts +++ b/src/export/exportIfc.validate.test.ts @@ -7,19 +7,66 @@ import { spawnSync } from "node:child_process"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { exportIfcSpf } from "./exportIfc"; +import { exportIfcSpf, ifcGuid } from "./exportIfc"; +import { pickGeometry } from "../plan/toWalls3d"; +import { wallCutMeshes } from "../plan/wallMeshCut"; import { sampleProject } from "../model/sampleProject"; +import type { Project } from "../model/types"; const hasIfcOpenShell = spawnSync("python3", ["-c", "import ifcopenshell, ifcopenshell.validate, _pytest"]).status === 0; -function validate(name: string, ifc: string): { status: number | null; out: string } { +function writeIfc(name: string, ifc: string): string { const dir = mkdtempSync(join(tmpdir(), "dossier-ifc-")); const file = join(dir, `${name}.ifc`); writeFileSync(file, ifc); - const r = spawnSync("python3", ["scripts/validate-ifc.py", file], { encoding: "utf8", timeout: 120_000 }); + return file; +} + +function validate(name: string, ifc: string): { status: number | null; out: string } { + const r = spawnSync("python3", ["scripts/validate-ifc.py", writeIfc(name, ifc)], { encoding: "utf8", timeout: 120_000 }); return { status: r.status, out: `${r.stdout}\n${r.stderr}` }; } +// Volumen je IfcWall nach ifcopenshell (Öffnungen abgezogen) und die Öffnungs-Beziehungen. +const WALL_VOLUMES = ` +import json, sys +import ifcopenshell, ifcopenshell.geom, ifcopenshell.util.shape as us +m = ifcopenshell.open(sys.argv[1]) +s = ifcopenshell.geom.settings() +out = {} +for w in m.by_type("IfcWall"): + sh = ifcopenshell.geom.create_shape(s, w) + out[w.GlobalId] = {"volume": us.get_volume(sh.geometry), "openings": len(w.HasOpenings), + "fills": sum(len(r.RelatedOpeningElement.HasFillings) for r in w.HasOpenings), + "rep": w.Representation.Representations[0].RepresentationType} +print(json.dumps(out)) +`; + +type WallVolume = { volume: number; openings: number; fills: number; rep: string }; + +/** Je IfcWall (Schlüssel GlobalId): Volumen, Anzahl Öffnungen/Füllungen, Darstellungsart. */ +function wallVolumes(name: string, ifc: string): Record { + const r = spawnSync("python3", ["-c", WALL_VOLUMES, writeIfc(name, ifc)], { encoding: "utf8", timeout: 120_000 }); + expect(r.status, r.stderr).toBe(0); + return JSON.parse(r.stdout); +} + +/** Eine freistehende Wand 5 × 0.4 × 2.6 m mit einem Fenster 1.2 × 1.2 m (Brüstung 0.9 m). */ +function singleWall(recess: boolean): Project { + return { + ...sampleProject, + walls: [{ id: "W1", type: "wall", floorId: "eg", categoryCode: "20", start: { x: 0, y: 0 }, end: { x: 5, y: 0 }, wallTypeId: "solo", height: 2.6 }], + wallTypes: [...sampleProject.wallTypes, { id: "solo", name: "Beton 40", layers: [{ componentId: sampleProject.components[0].id, thickness: 0.4 }] }], + windowTypes: [{ id: "wt", name: "Fenster", kind: "drehkipp", wingCount: 1, glazing: "dreifach", frameThickness: 0.08, defaultSillHeight: 0.9, defaultWidth: 1.2, defaultHeight: 1.2, innerLayerRecess: recess }], + openings: [{ id: "F1", type: "opening", hostWallId: "W1", categoryCode: "21", kind: "window", position: 1, width: 1.2, height: 1.2, sillHeight: 0.9, typeId: "wt" }], + ceilings: [], + roofs: [], + rooms: [], + stairs: [], + columns: [], + } as Project; +} + // Startet je Fall einen Python-Prozess (~3 s, unter Last mehr): eigenes Zeitlimit statt 5 s. describe.skipIf(!hasIfcOpenShell)("IFC-Export gegen ifcopenshell", { timeout: 60_000 }, () => { it("Demo-Haus: gültig, alle Körper erzeugbar", () => { @@ -42,4 +89,48 @@ describe.skipIf(!hasIfcOpenShell)("IFC-Export gegen ifcopenshell", { timeout: 60 expect(r.out).toContain("0 Befunde"); expect(r.status).toBe(0); }); + it("[B5] Wand als Extrusion mit IfcOpeningElement: Volumen = Wand − Öffnung", () => { + const ifc = exportIfcSpf(singleWall(false)); + const r = validate("oeffnung", ifc); + expect(r.out).toContain("0 Befunde"); + const [w] = Object.values(wallVolumes("oeffnung", ifc)); + expect(w.rep).toBe("SweptSolid"); + expect(w.openings).toBe(1); + expect(w.fills).toBe(1); + expect(w.volume).toBeCloseTo(5 * 0.4 * 2.6 - 1.2 * 1.2 * 0.4, 4); + }); + it("[B5] Mesh-Wand (Laibungs-Rücksprung) mit Öffnung+Füllung: Öffnung zieht nichts doppelt ab", () => { + const ifc = exportIfcSpf(singleWall(true)); + const r = validate("oeffnung-mesh", ifc); + expect(r.out).toContain("0 Befunde"); + const [w] = Object.values(wallVolumes("oeffnung-mesh", ifc)); + expect(w.rep).toBe("Tessellation"); + expect(w.openings).toBe(1); + expect(w.fills).toBe(1); + // Rücksprung = Schichtdicke 0.4 rundum: Loch 2.0 × 2.0 m durch die ganze Wand. + expect(w.volume).toBeCloseTo(5 * 0.4 * 2.6 - 2.0 * 2.0 * 0.4, 3); + }); + it("[B5] Demo-Haus: jede Wand hat nach ifcopenshell (Öffnungen abgezogen) das Volumen des 3D-Meshes", () => { + const project = sampleProject; + const bands = pickGeometry(project).walls; + const meshVolume = new Map(); + wallCutMeshes(bands).forEach((m, i) => { + let v6 = 0; + for (let k = 0; k < m.indices.length; k += 3) { + const [a, b, c] = [m.indices[k], m.indices[k + 1], m.indices[k + 2]].map((j) => m.positions.slice(j * 3, j * 3 + 3)); + v6 += a[0] * (b[1] * c[2] - b[2] * c[1]) + a[1] * (b[2] * c[0] - b[0] * c[2]) + a[2] * (b[0] * c[1] - b[1] * c[0]); + } + const id = bands[i].wallId; + meshVolume.set(id, (meshVolume.get(id) ?? 0) + Math.abs(v6) / 6); + }); + const walls = wallVolumes("demo-volumen", exportIfcSpf(project)); + let swept = 0; + for (const wall of project.walls) { + const w = walls[ifcGuid(`${project.id}/wall/${wall.id}`)]; + expect(w, wall.id).toBeDefined(); + if (w.rep === "SweptSolid") swept++; + expect(w.volume, wall.id).toBeCloseTo(meshVolume.get(wall.id)!, 4); + } + expect(swept).toBeGreaterThan(0); + }); }); diff --git a/src/io/ifcImport.test.ts b/src/io/ifcImport.test.ts index 47c55482..11fdd841 100644 --- a/src/io/ifcImport.test.ts +++ b/src/io/ifcImport.test.ts @@ -12,7 +12,7 @@ import { spawnSync } from "node:child_process"; import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { exportIfcSpf } from "../export/exportIfc"; +import { exportIfcSpf, ifcGuid } from "../export/exportIfc"; import { sampleProject } from "../model/sampleProject"; import { ceilingVerticalExtent } from "../model/wall"; import { polygonArea } from "../geometry/roomArea"; @@ -75,15 +75,30 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => { it("Volumen je Wand = Volumen der Wand-Netze, je Decke = Fläche × Dicke", async () => { const { products } = await readIfc(bytesOf(ifc)); // Wände: dieselben Ausschnitt-Netze wie der Export (Bänder je Wand). + // [B5]: einfache Wände kommen als ungeschnittene Extrusion + IfcOpeningElement; der Import zieht + // Öffnungen noch nicht ab ([B3] offen) → dort das Volumen der vollen Bänder. const bands = pickGeometry(sampleProject).walls; - const byWall = new Map(); - wallCutMeshes(bands).forEach((m, i) => { - byWall.set(bands[i].wallId, (byWall.get(bands[i].wallId) ?? 0) + Math.abs(volume(m.positions, m.indices))); - }); - const wallsExpected = [...byWall.values()].sort((a, b) => a - b); - const wallsGot = products.filter((p) => p.ifcClass === "IfcWall").map(vol).sort((a, b) => a - b); - expect(wallsGot.length).toBe(wallsExpected.length); - wallsGot.forEach((v, i) => expect(relClose(v, wallsExpected[i], 1e-6), `${v} ≠ ${wallsExpected[i]}`).toBe(true)); + const cut = new Map(); + const full = new Map(); + const add = (m: Map, id: string, v: number) => m.set(id, (m.get(id) ?? 0) + Math.abs(v)); + wallCutMeshes(bands).forEach((m, i) => add(cut, bands[i].wallId, volume(m.positions, m.indices))); + wallCutMeshes(bands.map((b) => ({ ...b, holes: [] }))).forEach((m, i) => add(full, bands[i].wallId, volume(m.positions, m.indices))); + const lines = new Map(ifc.split("\n").map((l) => [l.slice(0, l.indexOf("=")), l] as const)); + const wallsGot = products.filter((p) => p.ifcClass === "IfcWall"); + expect(wallsGot.length).toBe(sampleProject.walls.length); + let swept = 0; + for (const wall of sampleProject.walls) { + const p = wallsGot.find((g) => g.globalId === ifcGuid(`${sampleProject.id}/wall/${wall.id}`))!; + expect(p, wall.id).toBeDefined(); + const wallLine = [...lines.values()].find((l) => l.includes(`=IFCWALL('${p.globalId}'`))!; + const shape = lines.get(/,(#\d+),\$,\$\);$/.exec(wallLine)![1])!; + const rep = lines.get(/\(\(?(#\d+)\)\);$/.exec(shape)![1])!; + const isSwept = rep.includes("'SweptSolid'"); + if (isSwept) swept++; + const expected = (isSwept ? full : cut).get(wall.id)!; + expect(relClose(vol(p), expected, 1e-6), `${wall.id}: ${vol(p)} ≠ ${expected}`).toBe(true); + } + expect(swept).toBeGreaterThan(0); const slabsExpected = (sampleProject.ceilings ?? []) .filter((c) => c.outline.length >= 3)