From 041b32468961f82fe0206ef7ca0648fc343fe56c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 11:50:45 +0000 Subject: [PATCH] [B5] IFC-Export nach Rust: ifc_export.rs schreibt die STEP-Datei MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TS (exportIfc.ts) sammelt nur noch Bauteile und Geometrie als flachen Puffer, Rust (src-tauri/fileio/src/ifc_export.rs, Format-Modul pkgFileIo) baut Entitäten, GUIDs, Typen mit Materialschichten, Psets, Beziehungen, Räume, Georeferenz und die \X2\/\X4\-Kodierung. TS-STEP-Erzeugung gelöscht; ifcGuid/ifcString sind Fassaden. exportIfcSpf bleibt synchron, verlangt aber das geladene Format-Modul (Dialog und CLI laden per loadFileio, Tests per fileioWasm.setup). Golden-Vergleich gegen die TS-Fassung (45 Exporte): zeichengleich bis auf Zeitstempel. Rust-Tests: Zahlen/Strings/GUIDs, Wohlgeformtheit, Fehlerpfade ohne Panic. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- TODO.md | 16 +- src-tauri/fileio/src/ifc_export.rs | 1709 +++++++++++++++++++++++++ src-tauri/fileio/src/lib.rs | 1 + src/cli/main.ts | 1 + src/export/exportIfc.test.ts | 1 + src/export/exportIfc.ts | 1097 ++++++---------- src/export/exportIfc.validate.test.ts | 1 + src/i18n/de.ts | 1 + src/i18n/en.ts | 1 + src/state/useProjectFileActions.ts | 6 +- 10 files changed, 2117 insertions(+), 717 deletions(-) create mode 100644 src-tauri/fileio/src/ifc_export.rs diff --git a/TODO.md b/TODO.md index 395d5efd..7bf95f3e 100644 --- a/TODO.md +++ b/TODO.md @@ -343,8 +343,20 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module 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 + - ✅ Export nach Rust. (28.10.) `src-tauri/fileio/src/ifc_export.rs` schreibt die STEP-Datei + (Entitäten, GUID-Hash, Typen/Materialschichten, Psets, Beziehungen, Räume, Georeferenz, + `\X2\`/`\X4\`); `exportIfc.ts` sammelt nur noch (Bänder, Öffnungen, Dach-Meshes, Raumflächen) + und gibt einen flachen Puffer + Zeichenketten an `export_ifc_flat` (Muster `export.rs`/DXF). Die + TS-STEP-Erzeugung ist gelöscht; `ifcGuid`/`ifcString` sind dünne Fassaden. `exportIfcSpf` bleibt + synchron, verlangt aber das geladene Format-Modul (wie `buildPlanDxf`): Dialog und CLI `ifc` + laden per `loadFileio()`, Tests per `fileioWasm.setup`. Golden-Vergleich gegen die TS-Fassung + (45 Exporte aus `exportIfc.test`, `exportIfc.validate.test`, `ifcImport.test`, inkl. Demo-Haus, + Georeferenz, Dach, Stützen, Räume, Umlaute): Entitäten, Reihenfolge, Nummern, GUIDs und Zahlen + zeichengleich (bis auf Zeitstempel). Abweichungen nur in Grenzfällen: unpaarige UTF-16-Surrogate + in Namen werden U+FFFD (TS: `\X2\D800\X0\`), `\0` in Namen entfällt, NaN/∞ in einer Koordinate + ist jetzt ein Fehler statt „NaN“ in der Datei. Rundung wie `toFixed(6)` (Gleichstand auf). + Offen: Laden von pkgFileIo ist beim ersten IFC-Export neu (bisher synchron ohne Wartezeit); + Export im Worker; nur Linux-Container/vitest, nicht in der Tauri-App geprüft. · 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 diff --git a/src-tauri/fileio/src/ifc_export.rs b/src-tauri/fileio/src/ifc_export.rs new file mode 100644 index 00000000..b3a595c1 --- /dev/null +++ b/src-tauri/fileio/src/ifc_export.rs @@ -0,0 +1,1709 @@ +// IFC4-Schreiber ([B5], Port von `src/export/exportIfc.ts`): erzeugt aus einer flachen Bauteilliste die +// STEP-Datei (ISO 10303-21). TS sammelt aus Projekt und Plan (Wand-Bänder, Öffnungen, Dach-Meshes, +// Raumflächen, Georeferenz — alles Geometrie, die im TS-Modell lebt) und gibt sie fertig gerechnet +// weiter; Rust vergibt die Entitätsnummern und baut die Entitäten, GUIDs, Typen mit Materialschichten, +// Eigenschaftssätze (gleicher Inhalt = ein Pset), Beziehungen, Räume und die Georeferenz. Die Reihenfolge +// der Entitäten ist die der TS-Fassung (Golden-Vergleich 28.10.). +// +// Flache Kodierung (Muster `export.rs`): Zahlen als `f64`-Puffer, Zeichenketten getrennt als EINE +// Zeichenkette, Teile durch `\0` getrennt; im Zahlenpuffer steht ihr Index (−1 = keine). +// +// [FLAT_VERSION, META, Datensatz, Datensatz, …] +// META = project_id, project_name, now (Sekunden, ganzzahlig), iso (Zeitstempel, Text), has_geo (0/1), +// ref_elevation (NaN = keine), n_storeys, (id, name, base) × n_storeys +// PTS = n, x0, y0, …, x(n−1), y(n−1) (Profil, offen; Rust schliesst es) +// MESH = n_verts, x, y, z, …, n_tris, i0, i1, i2, …, closed (0/1) (Indizes 0-basiert) +// TYPEREF = has (0/1); wenn 1: kind (0 Wand, 1 Decke, 2 Dach), type_id, type_name, predefined (Text), +// n_layers, (component_id, component_name, thickness) × n_layers +// PSETS = n, (name, n_props, (prop_name, kind, value) × n_props) × n +// kind 0 = IfcIdentifier (value = Zeichenketten-Index), 1 = IfcBoolean (0/1), +// 2 = IfcPositiveRatioMeasure (value = Zahl) +// structure= Geschoss-Index oder −1 (Gebäude) +// +// WALL_SOLIDS = 1, structure, id, name, TYPEREF, PSETS, n_solids, (PTS, z_rel, depth) × n_solids +// WALL_MESH = 2, structure, id, name, TYPEREF, PSETS, MESH +// CEILING = 3, structure, id, name, TYPEREF, PSETS, PTS, z_rel, depth +// OPENING = 4, wall_id, structure, opening_id, is_door (0/1), fill_name, PTS (Öffnungskörper), z_rel, +// depth, PTS (Füllung), width, PSETS +// STAIR = 5, structure, id, predefined (Text), PTS, z_rel, depth +// EXTRUSION = 6, structure, id, PTS, z_rel, depth +// SPACE = 7, structure, id, name, long_name, external (0/1), height, PTS, net_area, gross_area, +// sia_category, PSETS +// END_SPACES = 8 (bündelt die Räume je Geschoss zu IfcRelAggregates) +// ROOF = 9, structure, id, name, predefined (Text), TYPEREF, PSETS, MESH +// COLUMN = 10, structure, id, label, PTS, z_rel, depth, component_id (−1 = keine), component_name, PSETS +// END_COLUMNS = 11 (Materialzuordnung der Stützen) +// +// Danach folgen (am Pufferende) Typ-Zuordnungen, Eigenschaftssätze, räumliche Eingliederung und Fuss. +// +// Fehlerverhalten: ein kaputter Puffer (falsche Version, unbekannter Datensatz, abgeschnitten, Index +// ausserhalb, NaN/∞ in einer Koordinate) ergibt einen Fehler, nie einen Panic. +// +// Abweichungen zur TS-Fassung: Zeichenketten mit unpaarigen UTF-16-Surrogaten kommen über wasm-bindgen als +// U+FFFD an (TS schrieb `\X2\D800\X0\`); `\0` in Namen wird auf TS-Seite entfernt; NaN/∞ in Koordinaten +// ist ein Fehler statt der Zeichenkette „NaN“. + +use std::collections::HashMap; + +/// Version der flachen Kodierung (erstes Element des Puffers). +pub const FLAT_VERSION: f64 = 1.0; + +pub const REC_WALL_SOLIDS: f64 = 1.0; +pub const REC_WALL_MESH: f64 = 2.0; +pub const REC_CEILING: f64 = 3.0; +pub const REC_OPENING: f64 = 4.0; +pub const REC_STAIR: f64 = 5.0; +pub const REC_EXTRUSION: f64 = 6.0; +pub const REC_SPACE: f64 = 7.0; +pub const REC_END_SPACES: f64 = 8.0; +pub const REC_ROOF: f64 = 9.0; +pub const REC_COLUMN: f64 = 10.0; +pub const REC_END_COLUMNS: f64 = 11.0; + +// ── IFC-GUID (Kompression nach IfcOpenShell `guid.compress`) ──────────────── + +const IFC_GUID_CHARS: &[u8; 64] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$"; + +/// Kodiert `v` big-endian in `len` IFC-GUID-Zeichen (Basis 64). +fn guid_b64(v: u32, len: usize, out: &mut String) { + for i in (0..len).rev() { + out.push(IFC_GUID_CHARS[((v >> (6 * i)) & 63) as usize] as char); + } +} + +/// Komprimiert 16 Bytes zur 22-stelligen IFC-GUID (erstes Byte → 2 Zeichen, dann 5 × 3 Byte → 4 Zeichen). +fn compress_guid(bytes: &[u8; 16]) -> String { + let mut out = String::with_capacity(22); + guid_b64(u32::from(bytes[0]), 2, &mut out); + let mut i = 1; + while i < 16 { + let v = (u32::from(bytes[i]) << 16) + (u32::from(bytes[i + 1]) << 8) + u32::from(bytes[i + 2]); + guid_b64(v, 4, &mut out); + i += 3; + } + out +} + +/// Mischt die Bits eines 64-Bit-Werts (MurmurHash3-fmix64). +fn fmix64(mut k: u64) -> u64 { + k ^= k >> 33; + k = k.wrapping_mul(0xff51_afd7_ed55_8ccd); + k ^= k >> 33; + k = k.wrapping_mul(0xc4ce_b9fe_1a85_ec53); + k ^= k >> 33; + k +} + +/// FNV-1a-64 über Bytes (vorwärts oder rückwärts) — reines Streuungswerkzeug, keine Kryptografie. +fn fnv1a64(bytes: &[u8], seed: u64, reverse: bool) -> u64 { + const PRIME: u64 = 0x0000_0100_0000_01b3; + let mut hash = seed; + for i in 0..bytes.len() { + let b = if reverse { bytes[bytes.len() - 1 - i] } else { bytes[i] }; + hash ^= u64::from(b); + hash = hash.wrapping_mul(PRIME); + } + hash +} + +/// Deterministische 22-stellige IFC-GUID 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 mit Variante 10. Im Export lautet der Name `//[/]`. +pub fn ifc_guid(name: &str) -> String { + let bytes = name.as_bytes(); + let h1 = fmix64(fnv1a64(bytes, 0xcbf2_9ce4_8422_2325, false)); + let h2 = fmix64(fnv1a64(bytes, 0x9e37_79b9_7f4a_7c15, true) ^ (bytes.len() as u64)); + let mut b = [0u8; 16]; + b[..8].copy_from_slice(&h1.to_be_bytes()); + b[8..].copy_from_slice(&h2.to_be_bytes()); + // Hex-Zeichen 12 (= obere Hälfte von Byte 6) = Version 8; Hex-Zeichen 16 (= obere Hälfte von Byte 8) + // = Variante 10xx. + b[6] = (b[6] & 0x0f) | 0x80; + b[8] = (b[8] & 0x3f) | 0x80; + compress_guid(&b) +} + +// ── STEP-Formatierung ─────────────────────────────────────────────────────── + +/// STEP-String-Literal (ISO 10303-21): druckbares ASCII bleibt, Backslash und Apostroph werden verdoppelt, +/// alles andere (Umlaute, Steuerzeichen) als `\X2\HHHH…\X0\` (BMP) bzw. `\X4\HHHHHHHH…\X0\` (ausserhalb). +pub fn ifc_string(s: &str) -> String { + use std::fmt::Write; + let mut out = String::with_capacity(s.len() + 2); + out.push('\''); + let mut run: Vec = Vec::new(); + fn flush(run: &mut Vec, out: &mut String) { + if run.is_empty() { + return; + } + let wide = run.iter().any(|&c| c > 0xffff); + out.push_str(if wide { "\\X4\\" } else { "\\X2\\" }); + for &c in run.iter() { + if wide { + let _ = write!(out, "{c:08X}"); + } else { + let _ = write!(out, "{c:04X}"); + } + } + out.push_str("\\X0\\"); + run.clear(); + } + for ch in s.chars() { + let c = ch as u32; + if (0x20..=0x7e).contains(&c) { + flush(&mut run, &mut out); + match ch { + '\\' => out.push_str("\\\\"), + '\'' => out.push_str("''"), + _ => out.push(ch), + } + } else { + // \X2\ und \X4\ nicht mischen: Wechsel der Breite beginnt einen neuen Block. + if let Some(&first) = run.first() { + if (first > 0xffff) != (c > 0xffff) { + flush(&mut run, &mut out); + } + } + run.push(c); + } + } + flush(&mut run, &mut out); + out.push('\''); + out +} + +/// STEP-REAL-Literal — immer mit Dezimalpunkt, ohne unnötige Nachkommastellen. Rundet wie JavaScripts +/// `toFixed(6)` (Betrag, bei Gleichstand auf), damit die Ausgabe der TS-Fassung gleicht. +pub fn fmt_real(x: f64) -> String { + if !x.is_finite() { + return "0.0".to_string(); + } + let neg = x < 0.0; + let a = x.abs(); + // Ziffernfolge aus Ganzzahl- und 6 Nachkommastellen (ohne Punkt). + let digits: String = { + let sc = a * 1e6; + let fast = if sc < 1e12 { + let fl = sc.floor(); + let frac = sc - fl; + if (frac - 0.5).abs() > 1e-3 { + let n = if frac > 0.5 { fl + 1.0 } else { fl } as u64; + Some(format!("{n:07}")) + } else { + None + } + } else { + None + }; + match fast { + Some(d) => d, + None => exact_scaled_digits(a), + } + }; + let (int_part, frac_part) = digits.split_at(digits.len() - 6); + let int_trim = int_part.trim_start_matches('0'); + let int_str = if int_trim.is_empty() { "0" } else { int_trim }; + let frac_trim = frac_part.trim_end_matches('0'); + let mut s = String::with_capacity(digits.len() + 3); + if neg { + s.push('-'); + } + s.push_str(int_str); + s.push('.'); + s.push_str(if frac_trim.is_empty() { "0" } else { frac_trim }); + s +} + +/// `a · 10⁶` auf eine Ganzzahl gerundet (Gleichstand auf), aus der exakten Dezimaldarstellung des `f64`. +fn exact_scaled_digits(a: f64) -> String { + let exact = format!("{a:.80}"); + let (int_s, frac_s) = exact.split_once('.').unwrap_or((exact.as_str(), "")); + let frac_b = frac_s.as_bytes(); + let mut d: Vec = int_s.bytes().collect(); + for i in 0..6 { + d.push(*frac_b.get(i).unwrap_or(&b'0')); + } + let round_up = frac_b.get(6).is_some_and(|&c| c >= b'5'); + if round_up { + let mut i = d.len(); + loop { + if i == 0 { + d.insert(0, b'1'); + break; + } + i -= 1; + if d[i] == b'9' { + d[i] = b'0'; + } else { + d[i] += 1; + break; + } + } + } + while d.len() < 7 { + d.insert(0, b'0'); + } + String::from_utf8(d).unwrap_or_else(|_| "0000000".to_string()) +} + +fn enum_(v: &str) -> String { + format!(".{v}.") +} + +fn list(items: &[String]) -> String { + format!("({})", items.join(",")) +} + +fn refs(ids: &[usize]) -> String { + let v: Vec = ids.iter().map(|id| format!("#{id}")).collect(); + list(&v) +} + +/// JSON-Zeichenkette für den Pset-Schlüssel (nur `"` und `\` kommen in IFC-Literalen vor, alles andere ist +/// druckbares ASCII). +fn json_str(s: &str) -> String { + let mut o = String::with_capacity(s.len() + 2); + o.push('"'); + for ch in s.chars() { + match ch { + '"' => o.push_str("\\\""), + '\\' => o.push_str("\\\\"), + _ => o.push(ch), + } + } + o.push('"'); + o +} + +// ── Eingabe ───────────────────────────────────────────────────────────────── + +struct Reader<'a> { + buf: &'a [f64], + pos: usize, + strings: Vec<&'a str>, +} + +impl<'a> Reader<'a> { + fn done(&self) -> bool { + self.pos >= self.buf.len() + } + fn raw(&mut self) -> Result { + let v = *self + .buf + .get(self.pos) + .ok_or_else(|| format!("Puffer abgeschnitten bei {}", self.pos))?; + self.pos += 1; + Ok(v) + } + /// Endliche Zahl. + fn f(&mut self) -> Result { + let v = self.raw()?; + if !v.is_finite() { + return Err(format!("Zahl ist NaN/∞ bei {}", self.pos - 1)); + } + Ok(v) + } + /// Nicht-negative Ganzzahl (Index, Anzahl). + fn idx(&mut self) -> Result { + let v = self.raw()?; + if !v.is_finite() || v < 0.0 || v.fract() != 0.0 || v > u32::MAX as f64 { + return Err(format!("ungültiger Index {v} bei {}", self.pos - 1)); + } + Ok(v as usize) + } + fn flag(&mut self) -> Result { + Ok(self.idx()? != 0) + } + /// Index oder −1. + fn opt_idx(&mut self) -> Result, String> { + let v = self.raw()?; + if v == -1.0 { + return Ok(None); + } + if !v.is_finite() || v < 0.0 || v.fract() != 0.0 || v > u32::MAX as f64 { + return Err(format!("ungültiger Index {v} bei {}", self.pos - 1)); + } + Ok(Some(v as usize)) + } + fn string(&mut self) -> Result { + let i = self.idx()?; + self.strings + .get(i) + .map(|s| (*s).to_string()) + .ok_or_else(|| format!("Zeichenketten-Index {i} ausserhalb ({})", self.strings.len())) + } + fn opt_string(&mut self) -> Result, String> { + match self.opt_idx()? { + None => Ok(None), + Some(i) => self + .strings + .get(i) + .map(|s| Some((*s).to_string())) + .ok_or_else(|| format!("Zeichenketten-Index {i} ausserhalb ({})", self.strings.len())), + } + } + fn take(&mut self, n: usize) -> Result<&'a [f64], String> { + let end = self.pos.checked_add(n).ok_or("Überlauf")?; + let s = self + .buf + .get(self.pos..end) + .ok_or_else(|| format!("Puffer abgeschnitten bei {}", self.pos))?; + self.pos = end; + if s.iter().any(|v| !v.is_finite()) { + return Err(format!("Zahl ist NaN/∞ vor {}", self.pos)); + } + Ok(s) + } + /// Struktur: Geschoss-Index (geprüft gegen `n_storeys`) oder −1 = Gebäude. + fn structure(&mut self, n_storeys: usize) -> Result { + match self.opt_idx()? { + None => Ok(-1), + Some(i) if i < n_storeys => Ok(i as i64), + Some(i) => Err(format!("Geschoss-Index {i} ausserhalb ({n_storeys})")), + } + } + fn pts(&mut self) -> Result, String> { + let n = self.idx()?; + let s = self.take(n.checked_mul(2).ok_or("Überlauf")?)?; + Ok(s.chunks_exact(2).map(|c| (c[0], c[1])).collect()) + } + fn mesh(&mut self) -> Result { + let nv = self.idx()?; + let positions = self.take(nv.checked_mul(3).ok_or("Überlauf")?)?.to_vec(); + let nt = self.idx()?; + let n_idx = nt.checked_mul(3).ok_or("Überlauf")?; + let raw = self.take(n_idx)?; + let mut indices = Vec::with_capacity(n_idx); + for &v in raw { + if v < 0.0 || v.fract() != 0.0 || v >= nv as f64 { + return Err(format!("Dreiecks-Index {v} ausserhalb ({nv} Punkte)")); + } + indices.push(v as usize); + } + let closed = self.flag()?; + Ok(Mesh { positions, indices, closed }) + } + fn type_ref(&mut self) -> Result, String> { + if !self.flag()? { + return Ok(None); + } + let kind = match self.idx()? { + 0 => TypeKind::Wall, + 1 => TypeKind::Slab, + 2 => TypeKind::Roof, + k => return Err(format!("unbekannte Typart {k}")), + }; + let id = self.string()?; + let name = self.string()?; + let predefined = self.string()?; + let n = self.idx()?; + let mut layers = Vec::new(); + for _ in 0..n { + let component_id = self.string()?; + let component_name = self.string()?; + let thickness = self.raw()?; // NaN → 0 (wie TS) + layers.push(Layer { component_id, component_name, thickness }); + } + Ok(Some(TypeRef { kind, id, name, predefined, layers })) + } + fn psets(&mut self) -> Result, String> { + let n = self.idx()?; + let mut out = Vec::new(); + for _ in 0..n { + let name = self.string()?; + let np = self.idx()?; + let mut props = Vec::new(); + for _ in 0..np { + let pname = self.string()?; + let value = match self.idx()? { + 0 => PropVal::Ident(self.string()?), + 1 => PropVal::Bool(self.flag()?), + 2 => PropVal::Ratio(self.f()?), + k => return Err(format!("unbekannte Eigenschaftsart {k}")), + }; + props.push((pname, value)); + } + out.push(Pset { name, props }); + } + Ok(out) + } +} + +struct Mesh { + positions: Vec, + indices: Vec, + closed: bool, +} + +#[derive(Clone, Copy, PartialEq)] +enum TypeKind { + Wall, + Slab, + Roof, +} + +impl TypeKind { + fn ifc(self) -> &'static str { + match self { + TypeKind::Wall => "IFCWALLTYPE", + TypeKind::Slab => "IFCSLABTYPE", + TypeKind::Roof => "IFCROOFTYPE", + } + } +} + +struct Layer { + component_id: String, + component_name: String, + thickness: f64, +} + +struct TypeRef { + kind: TypeKind, + id: String, + name: String, + predefined: String, + layers: Vec, +} + +enum PropVal { + Ident(String), + Bool(bool), + Ratio(f64), +} + +impl PropVal { + /// IFC-Wert-Ausdruck, z. B. `IFCIDENTIFIER('…')`. + fn expr(&self) -> String { + match self { + PropVal::Ident(s) => format!("IFCIDENTIFIER({})", ifc_string(s)), + PropVal::Bool(b) => format!("IFCBOOLEAN({})", if *b { ".T." } else { ".F." }), + PropVal::Ratio(r) => format!("IFCPOSITIVERATIOMEASURE({})", fmt_real(*r)), + } + } +} + +struct Pset { + name: String, + props: Vec<(String, PropVal)>, +} + +// ── Schreiber ─────────────────────────────────────────────────────────────── + +struct Storey { + id: String, + entity: usize, + placement: usize, +} + +struct PsetAcc { + name: String, + key: String, + props: Vec<(String, String)>, + related: Vec, +} + +struct TypeAcc { + key: String, + type_id: usize, + occurrences: Vec, +} + +/// Entitäten-Schreiber mit allem Zustand, den die TS-Fassung in Closures hielt. +struct Builder { + lines: Vec, + project_id: String, + owner_history: usize, + context: usize, + identity_axis: usize, + extrude_dir: usize, + building_entity: usize, + building_placement: usize, + storeys: Vec, + /// Eingliederung je Struktur (−1 = Gebäude), in Reihenfolge des ersten Auftretens. + containment: Vec<(i64, Vec)>, + psets: Vec, + pset_index: HashMap, + materials: HashMap, + types: Vec, + type_index: HashMap, + /// Wand-id → (Entität, Placement) für die Öffnungen. + walls: HashMap, + spaces: Vec<(i64, Vec)>, + column_materials: Vec<(String, String, Vec)>, +} + +impl Builder { + /// Schreibt eine neue Entity-Zeile und liefert ihre Nummer. + fn add(&mut self, ty: &str, params: String) -> usize { + let id = self.lines.len() + 1; + self.lines.push(format!("#{id}={ty}({params});")); + id + } + + /// Dauerhafte GlobalId (als STEP-String) aus `/[/]`, im Namensraum des Projekts. + fn gid(&self, key: &str) -> String { + ifc_string(&ifc_guid(&format!("{}/{key}", self.project_id))) + } + + fn placement_of(&self, structure: i64) -> usize { + if structure < 0 { + self.building_placement + } else { + self.storeys[structure as usize].placement + } + } + + fn entity_of(&self, structure: i64) -> usize { + if structure < 0 { + self.building_entity + } else { + self.storeys[structure as usize].entity + } + } + + fn key_of(&self, structure: i64) -> String { + if structure < 0 { + "building".to_string() + } else { + format!("storey/{}", self.storeys[structure as usize].id) + } + } + + fn add_to_containment(&mut self, structure: i64, element: usize) { + if let Some((_, v)) = self.containment.iter_mut().find(|(s, _)| *s == structure) { + v.push(element); + } else { + self.containment.push((structure, vec![element])); + } + } + + /// Eigenschaftssatz vormerken: gleicher Inhalt ⇒ EIN Pset für alle Bauteile (GUID aus dem Inhalt). + fn add_pset(&mut self, pset: &Pset, element: usize) { + if pset.props.is_empty() { + return; // IfcPropertySet verlangt mindestens eine Eigenschaft + } + let props: Vec<(String, String)> = pset.props.iter().map(|(n, v)| (n.clone(), v.expr())).collect(); + // Schlüssel wie in der TS-Fassung: `/`. + let json: Vec = props + .iter() + .map(|(n, v)| format!("[{},{}]", json_str(n), json_str(v))) + .collect(); + let key = format!("{}/[{}]", pset.name, json.join(",")); + if let Some(&i) = self.pset_index.get(&key) { + self.psets[i].related.push(element); + } else { + self.pset_index.insert(key.clone(), self.psets.len()); + self.psets.push(PsetAcc { name: pset.name.clone(), key, props, related: vec![element] }); + } + } + + /// Profil (geschlossenes Polygon) als IfcExtrudedAreaSolid, Unterkante `z_rel` in `+Z`. + fn emit_extrusion(&mut self, footprint: &[(f64, f64)], z_rel: f64, depth: f64) -> usize { + let mut pt_ids = Vec::with_capacity(footprint.len() + 1); + for p in footprint.iter().chain(footprint.first()) { + let id = self.add("IFCCARTESIANPOINT", list(&[fmt_real(p.0), fmt_real(p.1)])); + pt_ids.push(id); + } + let polyline = self.add("IFCPOLYLINE", refs(&pt_ids)); + let profile = self.add("IFCARBITRARYCLOSEDPROFILEDEF", format!("{},$,#{polyline}", enum_("AREA"))); + let mut position = self.identity_axis; + if z_rel != 0.0 { + let pt = self.add("IFCCARTESIANPOINT", list(&[fmt_real(0.0), fmt_real(0.0), fmt_real(z_rel)])); + position = self.add("IFCAXIS2PLACEMENT3D", format!("#{pt},$,$")); + } + self.add( + "IFCEXTRUDEDAREASOLID", + format!("#{profile},#{position},#{},{}", self.extrude_dir, fmt_real(depth.max(0.001))), + ) + } + + /// Placement im Abstand `z_rel` über `relative_to`. + fn emit_placement(&mut self, z_rel: f64, relative_to: usize) -> usize { + let origin = self.add("IFCCARTESIANPOINT", list(&[fmt_real(0.0), fmt_real(0.0), fmt_real(z_rel)])); + let axis = self.add("IFCAXIS2PLACEMENT3D", format!("#{origin},$,$")); + self.add("IFCLOCALPLACEMENT", format!("#{relative_to},#{axis}")) + } + + /// SweptSolid-Körper aus Extrusionen. + fn emit_swept_shape(&mut self, solids: &[usize]) -> usize { + let rep = self.add( + "IFCSHAPEREPRESENTATION", + format!("#{},{},{},{}", self.context, ifc_string("Body"), ifc_string("SweptSolid"), refs(solids)), + ); + self.add("IFCPRODUCTDEFINITIONSHAPE", format!("$,$,{}", refs(&[rep]))) + } + + /// Profil+Extrusion+Shape+Placement für einen geschlossenen Footprint; liefert (Placement, Shape). + fn emit_box_product(&mut self, footprint: &[(f64, f64)], z_bottom_rel: f64, depth: f64, relative_to: usize) -> (usize, usize) { + let solid = self.emit_extrusion(footprint, 0.0, depth); + let shape = self.emit_swept_shape(&[solid]); + let placement = self.emit_placement(z_bottom_rel, relative_to); + (placement, shape) + } + + /// Dreiecks-Mesh als IfcTriangulatedFaceSet + Shape + Placement (Punkte tragen die Geometrie absolut + /// im Rahmen der Trägerstruktur). + fn emit_triangulated_product(&mut self, mesh: &Mesh, relative_to: usize) -> (usize, usize) { + let coords: Vec = mesh + .positions + .chunks_exact(3) + .map(|c| format!("({},{},{})", fmt_real(c[0]), fmt_real(c[1]), fmt_real(c[2]))) + .collect(); + let point_list = self.add("IFCCARTESIANPOINTLIST3D", format!("({})", coords.join(","))); + let tris: Vec = mesh + .indices + .chunks_exact(3) + .map(|c| format!("({},{},{})", c[0] + 1, c[1] + 1, c[2] + 1)) + .collect(); + // Closed=.T. nur, wenn TS das Mesh als dichtes, aussen orientiertes Volumen geprüft hat. + let closed = if mesh.closed { ".T." } else { "$" }; + let face_set = self.add("IFCTRIANGULATEDFACESET", format!("#{point_list},$,{closed},({}),$", tris.join(","))); + let rep = self.add( + "IFCSHAPEREPRESENTATION", + format!("#{},{},{},{}", self.context, ifc_string("Body"), ifc_string("Tessellation"), refs(&[face_set])), + ); + let shape = self.add("IFCPRODUCTDEFINITIONSHAPE", format!("$,$,{}", refs(&[rep]))); + let placement = self.emit_placement(0.0, relative_to); + (placement, shape) + } + + /// IfcBuildingElement-Subtyp mit dem üblichen 9-Attribut-Flatten. + fn emit_building_element(&mut self, ty: &str, guid: String, name: &str, placement: usize, shape: usize, predefined: Option) -> usize { + self.add( + ty, + format!( + "{guid},#{},{},$,$,#{placement},#{shape},$,{}", + self.owner_history, + ifc_string(name), + predefined.as_deref().unwrap_or("$") + ), + ) + } + + /// Material je Bauteil (einmal, beim ersten Gebrauch). + fn material_of(&mut self, component_id: &str, component_name: &str) -> usize { + if let Some(&id) = self.materials.get(component_id) { + return id; + } + let id = self.add("IFCMATERIAL", format!("{},$,$", ifc_string(component_name))); + self.materials.insert(component_id.to_string(), id); + id + } + + /// Typ (IfcWallType/SlabType/RoofType mit IfcMaterialLayerSet), einmal je Typ; liefert den Index. + fn type_for(&mut self, t: &TypeRef) -> usize { + let key = format!("type/{}/{}", t.kind.ifc(), t.id); + if let Some(&i) = self.type_index.get(&key) { + return i; + } + let mut layer_ids = Vec::new(); + for l in &t.layers { + let m = self.material_of(&l.component_id, &l.component_name); + let thickness = if l.thickness.is_finite() { l.thickness.max(0.0) } else { 0.0 }; + layer_ids.push(self.add("IFCMATERIALLAYER", format!("#{m},{},$,$,$,$,$", fmt_real(thickness)))); + } + let guid = self.gid(&key); + let type_id = self.add( + t.kind.ifc(), + format!("{guid},#{},{},$,$,$,$,$,$,{}", self.owner_history, ifc_string(&t.name), enum_(&t.predefined)), + ); + if !layer_ids.is_empty() { + let set = self.add("IFCMATERIALLAYERSET", format!("{},{},$", refs(&layer_ids), ifc_string(&t.name))); + let rel_guid = self.gid(&format!("{key}/material")); + self.add( + "IFCRELASSOCIATESMATERIAL", + format!("{rel_guid},#{},$,$,{},#{set}", self.owner_history, refs(&[type_id])), + ); + } + self.type_index.insert(key.clone(), self.types.len()); + self.types.push(TypeAcc { key, type_id, occurrences: Vec::new() }); + self.types.len() - 1 + } + + /// Gemeinsamer Abschluss der Bauteile mit Typ und Psets: Typ (falls vorhanden) anlegen, Entität + /// schreiben, Typ-Exemplar, Eingliederung und Psets vormerken. + #[allow(clippy::too_many_arguments)] + fn finish_typed( + &mut self, + ifc: &str, + guid_key: String, + name: &str, + ty: &Option, + psets: &[Pset], + structure: i64, + placement: usize, + shape: usize, + predefined: Option, + type_first: bool, + ) -> usize { + // Wand und Decke legen den Typ vor dem Bauteil an, das Dach danach (Reihenfolge der TS-Fassung). + let mut type_idx = if type_first { ty.as_ref().map(|t| self.type_for(t)) } else { None }; + let guid = self.gid(&guid_key); + let entity = self.emit_building_element(ifc, guid, name, placement, shape, predefined); + if !type_first { + type_idx = ty.as_ref().map(|t| self.type_for(t)); + } + if let Some(i) = type_idx { + self.types[i].occurrences.push(entity); + } + self.add_to_containment(structure, entity); + for p in psets { + self.add_pset(p, entity); + } + entity + } +} + +/// Ob die Eingabe überhaupt einen Datensatz verlangt — Hilfe für die Fehlermeldung. +fn rec_name(code: f64) -> &'static str { + match code { + c if c == REC_WALL_SOLIDS => "WALL_SOLIDS", + c if c == REC_WALL_MESH => "WALL_MESH", + c if c == REC_CEILING => "CEILING", + c if c == REC_OPENING => "OPENING", + _ => "?", + } +} + +/// Baut aus dem flachen Puffer die STEP-Datei (IFC4). Fehler als Text. +pub fn build_ifc(flat: &[f64], strings: &str) -> Result { + let mut r = Reader { buf: flat, pos: 0, strings: strings.split('\0').collect() }; + let version = r.raw()?; + if version != FLAT_VERSION { + return Err(format!("unbekannte Version {version}")); + } + // ── META ── + let project_id = r.string()?; + let project_name = r.string()?; + let now_f = r.f()?; + if now_f.fract() != 0.0 { + return Err("Zeitstempel nicht ganzzahlig".to_string()); + } + let now = now_f as i64; + let iso = r.string()?; + let has_geo = r.flag()?; + let ref_elevation = r.raw()?; + let n_storeys = r.idx()?; + let mut storey_defs = Vec::new(); + for _ in 0..n_storeys { + let id = r.string()?; + let name = r.string()?; + let base = r.f()?; + storey_defs.push((id, name, base)); + } + + let mut w = Builder { + lines: Vec::new(), + project_id, + owner_history: 0, + context: 0, + identity_axis: 0, + extrude_dir: 0, + building_entity: 0, + building_placement: 0, + storeys: Vec::new(), + containment: Vec::new(), + psets: Vec::new(), + pset_index: HashMap::new(), + materials: HashMap::new(), + types: Vec::new(), + type_index: HashMap::new(), + walls: HashMap::new(), + spaces: Vec::new(), + column_materials: Vec::new(), + }; + let pname = |dflt: &str| if project_name.is_empty() { dflt.to_string() } else { project_name.clone() }; + + // Geteilte Grundgeometrie: Ursprung, Z-Extrusionsrichtung, Identitäts-Placement. + let origin = w.add("IFCCARTESIANPOINT", list(&[fmt_real(0.0), fmt_real(0.0), fmt_real(0.0)])); + w.extrude_dir = w.add("IFCDIRECTION", list(&[fmt_real(0.0), fmt_real(0.0), fmt_real(1.0)])); + w.identity_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{origin},$,$")); + + // Owner-History (minimal, aber vorhanden — manche Importer verlangen sie). + let org = w.add("IFCORGANIZATION", format!("$,{},$,$,$", ifc_string("dossier"))); + let person = w.add("IFCPERSON", format!("{},$,$,$,$,$,$,$", ifc_string("dossier"))); + let person_org = w.add("IFCPERSONANDORGANIZATION", format!("#{person},#{org},$")); + let app = w.add( + "IFCAPPLICATION", + format!("#{org},{},{},{}", ifc_string("1.0"), ifc_string("dossier"), ifc_string("dossier")), + ); + // ChangeAction ADDED verlangt ein LastModifiedDate (IFC4-Regel IfcOwnerHistory.CorrectChangeAction). + w.owner_history = w.add( + "IFCOWNERHISTORY", + format!("#{person_org},#{app},$,{},{now},$,$,{now}", enum_("ADDED")), + ); + + // Einheiten (Meter, Radiant, m², m³). + let len_unit = w.add("IFCSIUNIT", format!("*,{},$,{}", enum_("LENGTHUNIT"), enum_("METRE"))); + let area_unit = w.add("IFCSIUNIT", format!("*,{},$,{}", enum_("AREAUNIT"), enum_("SQUARE_METRE"))); + let vol_unit = w.add("IFCSIUNIT", format!("*,{},$,{}", enum_("VOLUMEUNIT"), enum_("CUBIC_METRE"))); + let angle_unit = w.add("IFCSIUNIT", format!("*,{},$,{}", enum_("PLANEANGLEUNIT"), enum_("RADIAN"))); + let unit_assignment = w.add( + "IFCUNITASSIGNMENT", + refs(&[len_unit, area_unit, vol_unit, angle_unit]), + ); + + // Geometrischer Kontext (3D, Precision 1e-5). + w.context = w.add( + "IFCGEOMETRICREPRESENTATIONCONTEXT", + format!("$,{},3,{},#{},$", ifc_string("Model"), fmt_real(0.00001), w.identity_axis), + ); + + // Georeferenz: Geometrie liegt schon in LV95-Weltkoordinaten (TS), die Abbildung ist die Identität; + // das Koordinatensystem wird trotzdem deklariert (IFC4 IfcProjectedCRS + IfcMapConversion). + if has_geo { + let crs = w.add( + "IFCPROJECTEDCRS", + format!( + "{},{},{},$,{},$,#{len_unit}", + ifc_string("EPSG:2056"), + ifc_string("CH1903+ / LV95"), + ifc_string("CH1903+"), + ifc_string("Swiss Oblique Mercator") + ), + ); + w.add( + "IFCMAPCONVERSION", + format!( + "#{},#{crs},{},{},{},{},{},{}", + w.context, + fmt_real(0.0), + fmt_real(0.0), + fmt_real(0.0), + fmt_real(1.0), + fmt_real(0.0), + fmt_real(1.0) + ), + ); + } + + // Räumliche Hierarchie: Project → Site → Building → Storeys. + let site_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{origin},$,$")); + let site_placement = w.add("IFCLOCALPLACEMENT", format!("$,#{site_axis}")); + let building_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{origin},$,$")); + w.building_placement = w.add("IFCLOCALPLACEMENT", format!("#{site_placement},#{building_axis}")); + + let g = w.gid("project"); + let project_entity = w.add( + "IFCPROJECT", + format!( + "{g},#{},{},$,$,$,$,{},#{unit_assignment}", + w.owner_history, + ifc_string(&pname("Projekt")), + refs(&[w.context]) + ), + ); + // RefElevation (m ü. M.): rein informativ, die Geometrie wird nicht verschoben. + let site_ref_elev = if ref_elevation.is_finite() { fmt_real(ref_elevation) } else { "$".to_string() }; + let g = w.gid("site"); + let site_entity = w.add( + "IFCSITE", + format!( + "{g},#{},{},$,$,#{site_placement},$,$,{},$,$,{site_ref_elev},$,$", + w.owner_history, + ifc_string("Standort"), + enum_("ELEMENT") + ), + ); + let g = w.gid("building"); + w.building_entity = w.add( + "IFCBUILDING", + format!( + "{g},#{},{},$,$,#{},$,$,{},$,$,$", + w.owner_history, + ifc_string(&pname("Gebäude")), + w.building_placement, + enum_("ELEMENT") + ), + ); + let g = w.gid("aggregates/site"); + w.add( + "IFCRELAGGREGATES", + format!("{g},#{},$,$,#{project_entity},{}", w.owner_history, refs(&[site_entity])), + ); + let g = w.gid("aggregates/building"); + w.add( + "IFCRELAGGREGATES", + format!("{g},#{},$,$,#{site_entity},{}", w.owner_history, refs(&[w.building_entity])), + ); + + // Je Geschoss ein IfcBuildingStorey (Elevation = base). + let mut storey_entities = Vec::new(); + for (id, name, base) in storey_defs { + let pt = w.add("IFCCARTESIANPOINT", list(&[fmt_real(0.0), fmt_real(0.0), fmt_real(base)])); + let axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{pt},$,$")); + let placement = w.add("IFCLOCALPLACEMENT", format!("#{},#{axis}", w.building_placement)); + let g = w.gid(&format!("storey/{id}")); + let entity = w.add( + "IFCBUILDINGSTOREY", + format!( + "{g},#{},{},$,$,#{placement},$,$,{},{}", + w.owner_history, + ifc_string(&name), + enum_("ELEMENT"), + fmt_real(base) + ), + ); + w.storeys.push(Storey { id, entity, placement }); + storey_entities.push(entity); + } + if !storey_entities.is_empty() { + let g = w.gid("aggregates/storeys"); + w.add( + "IFCRELAGGREGATES", + format!("{g},#{},$,$,#{},{}", w.owner_history, w.building_entity, refs(&storey_entities)), + ); + } + + // ── Datensätze ── + while !r.done() { + let code = r.raw()?; + match code { + c if c == REC_WALL_SOLIDS => { + let structure = r.structure(n_storeys)?; + let id = r.string()?; + let name = r.string()?; + let ty = r.type_ref()?; + let psets = r.psets()?; + let n = r.idx()?; + let mut solids = Vec::new(); + for _ in 0..n { + let pts = r.pts()?; + let z_rel = r.f()?; + let depth = r.f()?; + solids.push(w.emit_extrusion(&pts, z_rel, depth)); + } + let placement = w.emit_placement(0.0, w.placement_of(structure)); + let shape = w.emit_swept_shape(&solids); + let entity = w.finish_typed("IFCWALL", format!("wall/{id}"), &name, &ty, &psets, structure, placement, shape, None, true); + w.walls.insert(id, (entity, placement)); + } + c if c == REC_WALL_MESH => { + let structure = r.structure(n_storeys)?; + let id = r.string()?; + let name = r.string()?; + let ty = r.type_ref()?; + let psets = r.psets()?; + let mesh = r.mesh()?; + let (placement, shape) = w.emit_triangulated_product(&mesh, w.placement_of(structure)); + let entity = w.finish_typed("IFCWALL", format!("wall/{id}"), &name, &ty, &psets, structure, placement, shape, None, true); + w.walls.insert(id, (entity, placement)); + } + c if c == REC_CEILING => { + let structure = r.structure(n_storeys)?; + let id = r.string()?; + let name = r.string()?; + let ty = r.type_ref()?; + let psets = r.psets()?; + let pts = r.pts()?; + let z_rel = r.f()?; + let depth = r.f()?; + let (placement, shape) = w.emit_box_product(&pts, z_rel, depth, w.placement_of(structure)); + w.finish_typed("IFCSLAB", format!("slab/{id}"), &name, &ty, &psets, structure, placement, shape, Some(enum_("FLOOR")), true); + } + c if c == REC_OPENING => { + let wall_id = r.string()?; + let structure = r.structure(n_storeys)?; + let opening_id = r.string()?; + let is_door = r.flag()?; + let fill_name = r.string()?; + let void_pts = r.pts()?; + let void_z = r.f()?; + let depth = r.f()?; + let fill_pts = r.pts()?; + let width = r.f()?; + let psets = r.psets()?; + let Some(&(host_entity, host_placement)) = w.walls.get(&wall_id) else { + continue; // Wirtswand nicht geschrieben (degeneriert) + }; + let (opening_placement, opening_shape) = w.emit_box_product(&void_pts, void_z, depth, host_placement); + let g = w.gid(&format!("opening/{opening_id}")); + let opening_entity = w.add( + "IFCOPENINGELEMENT", + format!( + "{g},#{},{},$,$,#{opening_placement},#{opening_shape},$,{}", + w.owner_history, + ifc_string(if is_door { "Türöffnung" } else { "Fensteröffnung" }), + enum_("OPENING") + ), + ); + let g = w.gid(&format!("voids/{opening_id}")); + w.add( + "IFCRELVOIDSELEMENT", + format!("{g},#{},$,$,#{host_entity},#{opening_entity}", w.owner_history), + ); + let (fill_placement, fill_shape) = w.emit_box_product(&fill_pts, 0.0, depth, opening_placement); + let g = w.gid(&format!("fill/{opening_id}")); + let fill_entity = w.add( + if is_door { "IFCDOOR" } else { "IFCWINDOW" }, + format!( + "{g},#{},{},$,$,#{fill_placement},#{fill_shape},$,{},{},{},$,$", + w.owner_history, + ifc_string(&fill_name), + fmt_real(depth), + fmt_real(width), + enum_(if is_door { "DOOR" } else { "WINDOW" }) + ), + ); + let g = w.gid(&format!("fills/{opening_id}")); + w.add( + "IFCRELFILLSELEMENT", + format!("{g},#{},$,$,#{opening_entity},#{fill_entity}", w.owner_history), + ); + w.add_to_containment(structure, fill_entity); + for p in &psets { + w.add_pset(p, fill_entity); + } + } + c if c == REC_STAIR => { + let structure = r.structure(n_storeys)?; + let id = r.string()?; + let predefined = r.string()?; + let pts = r.pts()?; + let z_rel = r.f()?; + let depth = r.f()?; + let (placement, shape) = w.emit_box_product(&pts, z_rel, depth, w.placement_of(structure)); + let g = w.gid(&format!("stair/{id}")); + let entity = w.emit_building_element("IFCSTAIR", g, "Treppe", placement, shape, Some(enum_(&predefined))); + w.add_to_containment(structure, entity); + } + c if c == REC_EXTRUSION => { + let structure = r.structure(n_storeys)?; + let id = r.string()?; + let pts = r.pts()?; + let z_rel = r.f()?; + let depth = r.f()?; + let (placement, shape) = w.emit_box_product(&pts, z_rel, depth, w.placement_of(structure)); + let g = w.gid(&format!("extrusion/{id}")); + let entity = w.emit_building_element("IFCBUILDINGELEMENTPROXY", g, "Extrusion", placement, shape, None); + w.add_to_containment(structure, entity); + } + c if c == REC_SPACE => { + let structure = r.structure(n_storeys)?; + let id = r.string()?; + let name = r.string()?; + let long_name = r.string()?; + let external = r.flag()?; + let height = r.f()?; + let pts = r.pts()?; + let net = r.f()?; + let gross = r.f()?; + let sia = r.string()?; + let psets = r.psets()?; + let (placement, shape) = w.emit_box_product(&pts, 0.0, height, w.placement_of(structure)); + let g = w.gid(&format!("space/{id}")); + let space = w.add( + "IFCSPACE", + format!( + "{g},#{},{},$,$,#{placement},#{shape},{},{},{},$", + w.owner_history, + ifc_string(&name), + ifc_string(&long_name), + enum_("ELEMENT"), + enum_(if external { "EXTERNAL" } else { "INTERNAL" }) + ), + ); + if let Some((_, v)) = w.spaces.iter_mut().find(|(s, _)| *s == structure) { + v.push(space); + } else { + w.spaces.push((structure, vec![space])); + } + let q_net = w.add("IFCQUANTITYAREA", format!("{},$,$,{},$", ifc_string("NetFloorArea"), fmt_real(net))); + let q_gross = w.add("IFCQUANTITYAREA", format!("{},$,$,{},$", ifc_string("GrossFloorArea"), fmt_real(gross))); + let q_height = w.add("IFCQUANTITYLENGTH", format!("{},$,$,{},$", ifc_string("Height"), fmt_real(height))); + let g = w.gid(&format!("space/{id}/qto")); + let qto = w.add( + "IFCELEMENTQUANTITY", + format!( + "{g},#{},{},$,$,{}", + w.owner_history, + ifc_string("Qto_SpaceBaseQuantities"), + refs(&[q_net, q_gross, q_height]) + ), + ); + let g = w.gid(&format!("space/{id}/qto-rel")); + w.add( + "IFCRELDEFINESBYPROPERTIES", + format!("{g},#{},$,$,{},#{qto}", w.owner_history, refs(&[space])), + ); + let sia_prop = w.add( + "IFCPROPERTYSINGLEVALUE", + format!("{},$,IFCLABEL({}),$", ifc_string("SIA416"), ifc_string(&sia)), + ); + let g = w.gid(&format!("space/{id}/pset")); + let pset = w.add( + "IFCPROPERTYSET", + format!("{g},#{},{},$,{}", w.owner_history, ifc_string("CH_Raum"), refs(&[sia_prop])), + ); + let g = w.gid(&format!("space/{id}/pset-rel")); + w.add( + "IFCRELDEFINESBYPROPERTIES", + format!("{g},#{},$,$,{},#{pset}", w.owner_history, refs(&[space])), + ); + for p in &psets { + w.add_pset(p, space); + } + } + c if c == REC_END_SPACES => { + let spaces = std::mem::take(&mut w.spaces); + for (structure, ids) in spaces { + let g = w.gid(&format!("aggregates/spaces/{}", w.key_of(structure))); + w.add( + "IFCRELAGGREGATES", + format!("{g},#{},$,$,#{},{}", w.owner_history, w.entity_of(structure), refs(&ids)), + ); + } + } + c if c == REC_ROOF => { + let structure = r.structure(n_storeys)?; + let id = r.string()?; + let name = r.string()?; + let predefined = r.string()?; + let ty = r.type_ref()?; + let psets = r.psets()?; + let mesh = r.mesh()?; + let (placement, shape) = w.emit_triangulated_product(&mesh, w.placement_of(structure)); + w.finish_typed("IFCROOF", format!("roof/{id}"), &name, &ty, &psets, structure, placement, shape, Some(enum_(&predefined)), false); + } + c if c == REC_COLUMN => { + let structure = r.structure(n_storeys)?; + let id = r.string()?; + let label = r.string()?; + let pts = r.pts()?; + let z_rel = r.f()?; + let depth = r.f()?; + let component = r.opt_string()?; + let component_name = r.opt_string()?; + let psets = r.psets()?; + let (placement, shape) = w.emit_box_product(&pts, z_rel, depth, w.placement_of(structure)); + let g = w.gid(&format!("column/{id}")); + let entity = w.emit_building_element("IFCCOLUMN", g, &label, placement, shape, Some(enum_("COLUMN"))); + w.add_to_containment(structure, entity); + for p in &psets { + w.add_pset(p, entity); + } + if let Some(cid) = component { + if let Some((_, _, v)) = w.column_materials.iter_mut().find(|(c, _, _)| *c == cid) { + v.push(entity); + } else { + let nm = component_name.unwrap_or_else(|| cid.clone()); + w.column_materials.push((cid, nm, vec![entity])); + } + } + } + c if c == REC_END_COLUMNS => { + let mats = std::mem::take(&mut w.column_materials); + for (cid, name, ids) in mats { + let g = w.gid(&format!("material/{cid}/columns")); + let material = w.material_of(&cid, &name); + w.add( + "IFCRELASSOCIATESMATERIAL", + format!("{g},#{},$,$,{},#{material}", w.owner_history, refs(&ids)), + ); + } + } + other => return Err(format!("unbekannter Datensatz {other} ({}) bei {}", rec_name(other), r.pos - 1)), + } + } + + // ── Typ-Zuordnung (je Bauteiltyp eine IfcRelDefinesByType) ── + let types = std::mem::take(&mut w.types); + for t in &types { + if t.occurrences.is_empty() { + continue; + } + let g = w.gid(&format!("{}/occurrences", t.key)); + w.add( + "IFCRELDEFINESBYTYPE", + format!("{g},#{},$,$,{},#{}", w.owner_history, refs(&t.occurrences), t.type_id), + ); + } + + // ── Eigenschaftssätze ── + let psets = std::mem::take(&mut w.psets); + for ps in &psets { + let mut prop_ids = Vec::new(); + for (n, v) in &ps.props { + prop_ids.push(w.add("IFCPROPERTYSINGLEVALUE", format!("{},$,{v},$", ifc_string(n)))); + } + let g = w.gid(&format!("pset/{}", ps.key)); + let pset_id = w.add( + "IFCPROPERTYSET", + format!("{g},#{},{},$,{}", w.owner_history, ifc_string(&ps.name), refs(&prop_ids)), + ); + let g = w.gid(&format!("pset/{}/rel", ps.key)); + w.add( + "IFCRELDEFINESBYPROPERTIES", + format!("{g},#{},$,$,{},#{pset_id}", w.owner_history, refs(&ps.related)), + ); + } + + // ── Räumliche Eingliederung (gebündelt je Trägerstruktur) ── + let containment = std::mem::take(&mut w.containment); + for (structure, ids) in &containment { + let g = w.gid(&format!("contains/{}", w.key_of(*structure))); + w.add( + "IFCRELCONTAINEDINSPATIALSTRUCTURE", + format!("{g},#{},$,$,{},#{}", w.owner_history, refs(ids), w.entity_of(*structure)), + ); + } + + // ── Kopf + Zusammenbau ── + let file_name = format!("{}.ifc", pname("modell")); + let mut out = String::with_capacity(w.lines.iter().map(|l| l.len() + 1).sum::() + 512); + out.push_str("ISO-10303-21;\nHEADER;\n"); + out.push_str(&format!("FILE_DESCRIPTION({},{});\n", list(&[ifc_string("")]), ifc_string("2;1"))); + out.push_str(&format!( + "FILE_NAME({},{},{},{},{},{},{});\n", + ifc_string(&file_name), + ifc_string(&iso), + list(&[ifc_string("dossier")]), + list(&[ifc_string("dossier")]), + ifc_string("dossier"), + ifc_string("dossier"), + ifc_string("") + )); + out.push_str("FILE_SCHEMA(('IFC4'));\nENDSEC;\n\nDATA;\n"); + for l in &w.lines { + out.push_str(l); + out.push('\n'); + } + out.push_str("ENDSEC;\nEND-ISO-10303-21;\n"); + Ok(out) +} + +// --------------------------------------------------------------------------- +// WASM-Fassade (nur bei Feature "web") +// --------------------------------------------------------------------------- + +#[cfg(feature = "web")] +mod wasm { + use wasm_bindgen::prelude::*; + + /// Flache Bauteilliste → IFC4-Text (STEP); leer bei kaputtem Puffer (Grund: `export_ifc_check_flat`). + #[wasm_bindgen] + pub fn export_ifc_flat(flat: &[f64], strings: &str) -> String { + super::build_ifc(flat, strings).unwrap_or_default() + } + + /// Fehlertext zur Eingabe (leer = in Ordnung) — für Meldungen auf der TS-Seite. + #[wasm_bindgen] + pub fn export_ifc_check_flat(flat: &[f64], strings: &str) -> String { + match super::build_ifc(flat, strings) { + Ok(_) => String::new(), + Err(e) => e, + } + } + + /// Deterministische 22-stellige IFC-GUID aus einem Namen. + #[wasm_bindgen] + pub fn ifc_guid(name: &str) -> String { + super::ifc_guid(name) + } + + /// STEP-String-Literal (mit Apostrophen, `\X2\`/`\X4\` für Nicht-ASCII). + #[wasm_bindgen] + pub fn ifc_string(s: &str) -> String { + super::ifc_string(s) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strings_wie_ts() { + assert_eq!(ifc_string("Gebäude"), "'Geb\\X2\\00E4\\X0\\ude'"); + assert_eq!(ifc_string("Grösse Ü"), "'Gr\\X2\\00F6\\X0\\sse \\X2\\00DC\\X0\\'"); + assert_eq!(ifc_string("it's a\\b"), "'it''s a\\\\b'"); + assert_eq!(ifc_string("äö"), "'\\X2\\00E400F6\\X0\\'"); + assert_eq!(ifc_string("a😀"), "'a\\X4\\0001F600\\X0\\'"); + assert_eq!(ifc_string("a\nb"), "'a\\X2\\000A\\X0\\b'"); + assert_eq!(ifc_string(""), "''"); + // BMP und Ausserhalb im selben Lauf: neuer Block bei Breitenwechsel. + assert_eq!(ifc_string("ä😀"), "'\\X2\\00E4\\X0\\\\X4\\0001F600\\X0\\'"); + } + + #[test] + fn reals_wie_tofixed() { + assert_eq!(fmt_real(0.0), "0.0"); + assert_eq!(fmt_real(-0.0), "0.0"); + assert_eq!(fmt_real(1.0), "1.0"); + assert_eq!(fmt_real(100.0), "100.0"); + assert_eq!(fmt_real(0.00001), "0.00001"); + assert_eq!(fmt_real(-2.5), "-2.5"); + assert_eq!(fmt_real(0.1 + 0.2), "0.3"); + assert_eq!(fmt_real(2.6), "2.6"); + assert_eq!(fmt_real(-1e-9), "-0.0"); + assert_eq!(fmt_real(1e-9), "0.0"); + assert_eq!(fmt_real(0.999_999_6), "1.0"); + assert_eq!(fmt_real(2_600_000.123_456_7), "2600000.123457"); + // Gleichstand (exakt darstellbar): toFixed rundet auf, nicht auf gerade. + assert_eq!(fmt_real(0.007_812_5), "0.007813"); + assert_eq!(fmt_real(0.023_437_5), "0.023438"); + assert_eq!(fmt_real(-0.007_812_5), "-0.007813"); + // Sehr grosse Werte (Langpfad). + assert_eq!(fmt_real(1e15), "1000000000000000.0"); + assert_eq!(fmt_real(f64::NAN), "0.0"); + } + + #[test] + fn guid_wie_ts() { + // Werte aus der TS-Fassung (Golden vom 28.10., Projekt-id "t"). + assert_eq!(ifc_guid("t/project"), "2fgJPaxQwDyuZfE6V6_Rif"); + assert_eq!(ifc_guid("t/site"), "3rG4QSmdUCaBHFz1QMCvjw"); + assert_eq!(ifc_guid("t/wall/W1"), "0n_zVrPdE0cg_UxWSd1GmA"); + assert_eq!(ifc_guid("t/wall/W1"), ifc_guid("t/wall/W1")); + assert_ne!(ifc_guid("t/wall/W1"), ifc_guid("t/wall/W2")); + } + + /// Baut flache Puffer für die Tests (Gegenstück zu `FlatIfc` in `exportIfc.ts`). + struct B { + f: Vec, + s: Vec, + } + impl B { + fn new() -> Self { + B { f: vec![FLAT_VERSION], s: Vec::new() } + } + fn s(&mut self, x: &str) -> f64 { + self.s.push(x.to_string()); + (self.s.len() - 1) as f64 + } + fn n(&mut self, v: &[f64]) { + self.f.extend_from_slice(v); + } + fn str(&mut self, x: &str) { + let i = self.s(x); + self.f.push(i); + } + fn pts(&mut self, p: &[(f64, f64)]) { + self.f.push(p.len() as f64); + for (x, y) in p { + self.f.extend([*x, *y]); + } + } + fn no_type(&mut self) { + self.f.push(0.0); + } + fn wall_type(&mut self) { + self.n(&[1.0, 0.0]); + self.str("T1"); + self.str("Aussenwand"); + self.str("STANDARD"); + self.f.push(2.0); + for (c, name, t) in [("c1", "Beton", 0.2), ("c2", "Dämmung", 0.12)] { + self.str(c); + self.str(name); + self.f.push(t); + } + } + fn ref_pset(&mut self, set: &str, v: &str) { + self.f.push(1.0); + self.str(set); + self.f.push(1.0); + self.str("Reference"); + self.f.push(0.0); + self.str(v); + } + fn no_psets(&mut self) { + self.f.push(0.0); + } + fn mesh_tetra(&mut self) { + self.n(&[4.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + self.n(&[4.0, 0.0, 2.0, 1.0, 0.0, 1.0, 3.0, 1.0, 2.0, 3.0, 2.0, 0.0, 3.0]); + self.f.push(1.0); + } + fn data(&self) -> (&[f64], String) { + (&self.f, self.s.join("\0")) + } + } + + const SQUARE: [(f64, f64); 4] = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.4), (0.0, 0.4)]; + + /// Ein Projekt mit je einem Bauteil jeder Art; zwei Wände gleichen Typs (Pset/Typ müssen sich teilen). + fn full_house(with_geo: bool) -> B { + let mut b = B::new(); + b.str("t"); + b.str("Haus Ä"); + b.n(&[1_700_000_000.0]); + b.str("2026-10-28T12:00:00"); + b.n(&[if with_geo { 1.0 } else { 0.0 }, if with_geo { 421.5 } else { f64::NAN }, 1.0]); + b.str("eg"); + b.str("Erdgeschoss"); + b.n(&[0.0]); + for wid in ["W1", "W2"] { + b.n(&[REC_WALL_SOLIDS, 0.0]); + b.str(wid); + b.str("Aussenwand"); + b.wall_type(); + b.ref_pset("Pset_WallCommon", "Aussenwand"); + b.n(&[1.0]); + b.pts(&SQUARE); + b.n(&[0.0, 2.6]); + } + // Öffnung in W1: Tür. + b.n(&[REC_OPENING]); + b.str("W1"); + b.n(&[0.0]); + b.str("T1"); + b.n(&[1.0]); + b.str("Haustür"); + b.pts(&[(1.0, -0.02), (1.9, -0.02), (1.9, 0.42), (1.0, 0.42)]); + b.n(&[0.0, 2.1]); + b.pts(&[(1.0, 0.0), (1.9, 0.0), (1.9, 0.4), (1.0, 0.4)]); + b.n(&[0.9]); + b.ref_pset("Pset_DoorCommon", "Tür 90"); + // Decke, Treppe, Extrusion. + b.n(&[REC_CEILING, 0.0]); + b.str("D1"); + b.str("Decke"); + b.no_type(); + b.no_psets(); + b.pts(&SQUARE); + b.n(&[2.6, 0.2]); + b.n(&[REC_STAIR, 0.0]); + b.str("S1"); + b.str("STRAIGHT_RUN_STAIR"); + b.pts(&SQUARE); + b.n(&[0.0, 2.6]); + b.n(&[REC_EXTRUSION, -1.0]); + b.str("X1"); + b.pts(&SQUARE); + b.n(&[0.0, 1.0]); + // Raum. + b.n(&[REC_SPACE, 0.0]); + b.str("R1"); + b.str("101"); + b.str("Wohnen"); + b.n(&[0.0, 2.5]); + b.pts(&SQUARE); + b.n(&[1.9, 2.0]); + b.str("HNF"); + b.f.push(1.0); + b.str("Pset_SpaceCommon"); + b.f.push(2.0); + b.str("Reference"); + b.f.push(0.0); + b.str("101"); + b.str("IsExternal"); + b.n(&[1.0, 0.0]); + b.n(&[REC_END_SPACES]); + // Dach mit Typ. + b.n(&[REC_ROOF, 0.0]); + b.str("Ro1"); + b.str("Satteldach"); + b.str("GABLE_ROOF"); + b.n(&[1.0, 2.0]); + b.str("RT1"); + b.str("Satteldach"); + b.str("GABLE_ROOF"); + b.n(&[1.0]); + b.str("c1"); + b.str("Beton"); + b.n(&[0.3]); + b.ref_pset("Pset_RoofCommon", "Satteldach"); + b.mesh_tetra(); + // Stütze mit Material. + b.n(&[REC_COLUMN, 0.0]); + b.str("C1"); + b.str("Stütze 30"); + b.pts(&SQUARE); + b.n(&[0.0, 2.6]); + b.str("c1"); + b.str("Beton"); + b.ref_pset("Pset_ColumnCommon", "Stütze 30"); + b.n(&[REC_END_COLUMNS]); + b + } + + fn build(b: &B) -> Result { + let (f, s) = b.data(); + build_ifc(f, &s) + } + + /// Jede `#n` ist definiert, keine Nummer doppelt, Nummern lückenlos ab 1. + fn check_structure(ifc: &str) { + let mut defined = std::collections::HashSet::new(); + let mut order = Vec::new(); + for line in ifc.lines() { + if let Some(rest) = line.strip_prefix('#') { + let (num, _) = rest.split_once('=').expect("Entity ohne ="); + let n: usize = num.parse().expect("Nummer"); + assert!(defined.insert(n), "doppelte Nummer #{n}"); + order.push(n); + } + } + assert!(order.iter().copied().eq(1..=order.len()), "Nummern nicht lückenlos"); + for line in ifc.lines().filter(|l| l.starts_with('#')) { + let body = line.split_once('=').unwrap().1; + let mut chars = body.chars().peekable(); + let mut in_str = false; + while let Some(c) = chars.next() { + if c == '\'' { + in_str = !in_str; + } else if c == '#' && !in_str { + let mut num = String::new(); + while let Some(&d) = chars.peek() { + if d.is_ascii_digit() { + num.push(d); + chars.next(); + } else { + break; + } + } + let n: usize = num.parse().expect("Referenz"); + assert!(defined.contains(&n), "hängende Referenz #{n} in {line}"); + } + } + } + } + + fn count(ifc: &str, ty: &str) -> usize { + let head = format!("{ty}("); + ifc.lines().filter(|l| l.split_once('=').is_some_and(|(_, b)| b.starts_with(&head))).count() + } + + #[test] + fn volles_haus_ist_wohlgeformt() { + let ifc = build(&full_house(true)).unwrap(); + assert!(ifc.starts_with("ISO-10303-21;\nHEADER;\n")); + assert!(ifc.contains("FILE_SCHEMA(('IFC4'));")); + assert!(ifc.ends_with("ENDSEC;\nEND-ISO-10303-21;\n")); + assert!(ifc.is_ascii(), "Datei muss reines ASCII sein"); + check_structure(&ifc); + assert_eq!(count(&ifc, "IFCWALL"), 2); + assert_eq!(count(&ifc, "IFCSLAB"), 1); + assert_eq!(count(&ifc, "IFCROOF"), 1); + assert_eq!(count(&ifc, "IFCCOLUMN"), 1); + assert_eq!(count(&ifc, "IFCSTAIR"), 1); + assert_eq!(count(&ifc, "IFCSPACE"), 1); + assert_eq!(count(&ifc, "IFCDOOR"), 1); + assert_eq!(count(&ifc, "IFCOPENINGELEMENT"), 1); + assert_eq!(count(&ifc, "IFCRELVOIDSELEMENT"), 1); + assert_eq!(count(&ifc, "IFCRELFILLSELEMENT"), 1); + assert_eq!(count(&ifc, "IFCBUILDINGELEMENTPROXY"), 1); + assert_eq!(count(&ifc, "IFCBUILDINGSTOREY"), 1); + assert_eq!(count(&ifc, "IFCPROJECTEDCRS"), 1); + assert_eq!(count(&ifc, "IFCMAPCONVERSION"), 1); + assert!(ifc.contains(",421.5,$,$);"), "RefElevation"); + assert!(ifc.contains("'Haus \\X2\\00C4\\X0\\'")); + // Gleiche Wandtypen teilen Typ, Materialschichten und Pset. + assert_eq!(count(&ifc, "IFCWALLTYPE"), 1); + assert_eq!(count(&ifc, "IFCMATERIALLAYERSET"), 2); // Wandtyp + Dachtyp + assert_eq!(count(&ifc, "IFCMATERIAL"), 2); // Beton (geteilt mit Dachtyp und Stütze) + Dämmung + assert_eq!(count(&ifc, "IFCRELDEFINESBYTYPE"), 2); + assert_eq!(count(&ifc, "IFCPROPERTYSET"), 6); // Wall, Door, Space, Roof, Column + CH_Raum + // Eingliederung: Geschoss (Wände, Decke, Treppe, Tür, Dach, Stütze) und Gebäude (Extrusion). + assert_eq!(count(&ifc, "IFCRELCONTAINEDINSPATIALSTRUCTURE"), 2); + // Project→Site, Site→Building, Building→Storeys, Geschoss→Räume. + assert_eq!(count(&ifc, "IFCRELAGGREGATES"), 4); + } + + #[test] + fn ohne_georeferenz_und_deterministisch() { + let b = full_house(false); + let ifc = build(&b).unwrap(); + assert_eq!(count(&ifc, "IFCPROJECTEDCRS"), 0); + assert!(!ifc.contains(",421.5,")); + assert_eq!(ifc, build(&b).unwrap(), "zweimal bauen = gleiche Datei"); + // GlobalIds eindeutig. + let mut seen = std::collections::HashSet::new(); + for l in ifc.lines().filter(|l| l.starts_with('#')) { + let body = l.split_once('(').unwrap().1; + if let Some(rest) = body.strip_prefix('\'') { + if rest.len() > 22 && rest.as_bytes()[22] == b'\'' { + assert!(seen.insert(rest[..22].to_string()), "doppelte GlobalId {}", &rest[..22]); + } + } + } + assert!(seen.len() > 20); + } + + #[test] + fn leeres_projekt_ist_gueltig() { + let mut b = B::new(); + b.str("p"); + b.str(""); + b.n(&[1.0]); + b.str("iso"); + b.n(&[0.0, f64::NAN, 0.0]); + let ifc = build(&b).unwrap(); + check_structure(&ifc); + assert!(ifc.contains("IFCPROJECT('")); + assert!(ifc.contains("'Projekt'") && ifc.contains("'Geb\\X2\\00E4\\X0\\ude'")); + assert!(ifc.contains("FILE_NAME('modell.ifc'")); + assert_eq!(count(&ifc, "IFCBUILDINGSTOREY"), 0); + assert_eq!(count(&ifc, "IFCRELAGGREGATES"), 2); + } + + #[test] + fn oeffnung_ohne_wirtswand_wird_uebersprungen() { + let mut b = B::new(); + b.str("p"); + b.str("x"); + b.n(&[1.0]); + b.str("iso"); + b.n(&[0.0, f64::NAN, 0.0]); + b.n(&[REC_OPENING]); + b.str("gibt-es-nicht"); + b.n(&[-1.0]); + b.str("O1"); + b.n(&[0.0]); + b.str("Fenster"); + b.pts(&SQUARE); + b.n(&[0.0, 1.0]); + b.pts(&SQUARE); + b.n(&[1.0]); + b.no_psets(); + let ifc = build(&b).unwrap(); + check_structure(&ifc); + assert_eq!(count(&ifc, "IFCOPENINGELEMENT"), 0); + } + + #[test] + fn kaputte_puffer_ergeben_fehler_nie_panic() { + assert!(build_ifc(&[], "").is_err()); + assert!(build_ifc(&[2.0], "").is_err()); + assert!(build_ifc(&[FLAT_VERSION], "").is_err()); // META fehlt + assert!(build_ifc(&[FLAT_VERSION, 0.0, 0.0, f64::NAN], "a\0b").is_err()); + assert!(build_ifc(&[FLAT_VERSION, 5.0], "a").is_err()); // Zeichenketten-Index ausserhalb + let b = full_house(true); + let (f, s) = b.data(); + // An jeder Stelle abgeschnitten: nie Panic (Fehler oder, auf Datensatzgrenzen, Erfolg). + for n in 0..f.len() { + let _ = build_ifc(&f[..n], &s); + } + // Jedes Element einzeln verdorben (NaN, ∞, −1, riesig, gebrochen): nie Panic. + for i in 0..f.len() { + for bad in [f64::NAN, f64::INFINITY, -1.0, 1e30, 0.5] { + let mut g = f.to_vec(); + g[i] = bad; + let _ = build_ifc(&g, &s); + } + } + // Unbekannter Datensatz, Geschoss-Index ausserhalb, Dreiecks-Index ausserhalb. + let mut g = vec![FLAT_VERSION, 0.0, 0.0, 1.0, 0.0, 0.0, f64::NAN, 0.0, 99.0]; + assert!(build_ifc(&g, "a").is_err()); + g[8] = REC_STAIR; + g.extend([3.0]); + assert!(build_ifc(&g, "a").is_err()); + let mut m = B::new(); + m.str("p"); + m.str("x"); + m.n(&[1.0]); + m.str("i"); + m.n(&[0.0, f64::NAN, 0.0]); + m.n(&[REC_ROOF, -1.0]); + m.str("R"); + m.str("R"); + m.str("FLAT_ROOF"); + m.no_type(); + m.no_psets(); + m.n(&[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0]); // Index 1 bei nur 1 Punkt + let (f, s) = m.data(); + assert!(build_ifc(f, &s).is_err()); + } +} diff --git a/src-tauri/fileio/src/lib.rs b/src-tauri/fileio/src/lib.rs index 13741fd6..45962532 100644 --- a/src-tauri/fileio/src/lib.rs +++ b/src-tauri/fileio/src/lib.rs @@ -18,6 +18,7 @@ pub mod split; mod web_import; pub mod ifc_step; pub mod ifc_import; +pub mod ifc_export; use std::collections::HashMap; use std::io::Cursor; diff --git a/src/cli/main.ts b/src/cli/main.ts index 6070d59a..698b4b25 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -226,6 +226,7 @@ export async function run(argv: string[]): Promise { return 0; } case "ifc": + await loadFileio(); out(args, exportIfcSpf(project), `${project.name || "projekt"}.ifc`); return 0; case "obj": diff --git a/src/export/exportIfc.test.ts b/src/export/exportIfc.test.ts index 114868c8..45492cae 100644 --- a/src/export/exportIfc.test.ts +++ b/src/export/exportIfc.test.ts @@ -12,6 +12,7 @@ // Fixture-Muster gespiegelt von exportSchedule.test.ts. import { describe, it, expect } from "vitest"; +import "../engine/fileioWasm.setup"; import { exportIfcSpf, ifcGuid, ifcString } from "./exportIfc"; import type { Ceiling, diff --git a/src/export/exportIfc.ts b/src/export/exportIfc.ts index 1c82e4dd..dd1e5630 100644 --- a/src/export/exportIfc.ts +++ b/src/export/exportIfc.ts @@ -1,7 +1,10 @@ // IFC4-Export (STEP Physical File / ISO-10303-21) des semantischen Modells. -// Reiner Rechen-/Serialisierungskern: keine UI, kein Datei-IO, kein WASM, keine -// neue Dependency — IFC wird direkt als Text geschrieben (analog exportDxf.ts/ -// exportSchedule.ts). Der Download (Blob+Anchor) passiert im App-Layer. +// +// Seit [B5] (28.10.) schreibt Rust die Datei (`src-tauri/fileio/src/ifc_export.rs`, Format-Modul +// pkgFileIo): TS sammelt hier aus Projekt und Plan die Bauteile samt fertig gerechneter Geometrie +// (Wand-Bänder, Öffnungen, Dach-Meshes, Raumflächen) als flachen Puffer, Rust vergibt die Nummern und +// baut Entitäten, GUIDs, Typen mit Materialschichten, Psets und Beziehungen. Verlangt das geladene +// Format-Modul (`await loadFileio()`, wie `buildPlanDxf`). Der Download passiert im App-Layer. // // Abbildung: // Project → IfcProject → IfcSite → IfcBuilding → je "floor"-Geschoss ein @@ -52,17 +55,11 @@ // 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. +// Typ-ids, nie an STEP-Nummern. Der Hash lebt in Rust (`ifc_guid`). // // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). Einheit: METER. -import type { - Opening, - Project, - Stair, - Vec2, - Wall, -} from "../model/types"; +import type { Opening, Project, Stair, Vec2, Wall } from "../model/types"; import { columnLabel, getCeilingType, @@ -73,11 +70,7 @@ import { openingsOfWall, } from "../model/types"; import { projectToWorldCoords } from "../model/geoRebase"; -import { - ceilingVerticalExtent, - columnVerticalExtent, - stairVerticalExtent, -} from "../model/wall"; +import { ceilingVerticalExtent, columnVerticalExtent, stairVerticalExtent } from "../model/wall"; import { pickGeometry } from "../plan/toWalls3d"; import type { RWall } from "../plan/toWalls3d"; import { isWatertight, wallCutMeshes, type CutMesh } from "../plan/wallMeshCut"; @@ -85,154 +78,227 @@ import { evaluateRoom } from "../geometry/roomArea"; import { columnFootprint } from "../geometry/column"; import { openingInterval, openingVerticalExtent } from "../geometry/opening"; import { emitRoofs } from "../plan/toWalls3d/roofs"; +import { fileio } from "../engine/fileioWasm"; -// ── IFC-GUID (Base64-Kompression, 22 Zeichen) ─────────────────────────────── -// Standard-Kompressionsalgorithmus (IfcOpenShell guid.compress): das erste -// Byte des 128-Bit-Werts wird auf 2 Zeichen abgebildet, die restlichen 15 -// Byte in 5 Dreiergruppen zu je 4 Zeichen — macht 2 + 5×4 = 22 Zeichen. - -const IFC_GUID_CHARS = - "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$"; - -/** Kodiert `v` big-endian in `len` IFC-GUID-Zeichen (Basis 64). */ -function ifcGuidB64(v: number, len: number): string { - let out = ""; - for (let i = len - 1; i >= 0; i--) { - out += IFC_GUID_CHARS[Math.floor(v / 64 ** i) % 64]; - } - return out; -} - -/** Komprimiert einen 128-Bit-Wert (32 Hex-Zeichen) zur 22-stelligen IFC-GUID. */ -function compressGuidHex(hex32: string): string { - const bytes: number[] = []; - for (let i = 0; i < 32; i += 2) bytes.push(parseInt(hex32.slice(i, i + 2), 16)); - let out = ifcGuidB64(bytes[0], 2); - for (let i = 1; i < 16; i += 3) { - const v = (bytes[i] << 16) + (bytes[i + 1] << 8) + bytes[i + 2]; - out += ifcGuidB64(v, 4); - } - return out; -} - -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; - 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; -} - -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 einem Namen. Im Export lautet der Name immer - * `//[/]` (s. `exportIfcSpf`), damit gleiche ids verschiedener - * Bauteilarten oder Projekte nicht kollidieren. - */ +/** Deterministische 22-stellige IFC-GUID aus einem Namen (Rust, `ifc_export.rs::ifc_guid`). */ export function ifcGuid(name: string): string { - return compressGuidHex(nameToHex32(name)); + return fileio().ifc_guid(name); } -// ── STEP-Formatierung ─────────────────────────────────────────────────────── - -/** - * STEP-String-Literal (ISO 10303-21): druckbares ASCII bleibt, Backslash und Apostroph werden - * verdoppelt, alles andere (Umlaute, Steuerzeichen) als \X2\HHHH…\X0\ (BMP) bzw. - * \X4\HHHHHHHH…\X0\ (ausserhalb der BMP). Die Datei bleibt so reines ASCII. - */ +/** STEP-String-Literal mit Apostrophen, Nicht-ASCII als `\X2\`/`\X4\` (Rust, `ifc_export.rs::ifc_string`). */ export function ifcString(s: string): string { - let out = ""; - let run: number[] = []; - const flush = () => { - if (run.length === 0) return; - const wide = run.some((c) => c > 0xffff); - const hex = run.map((c) => c.toString(16).toUpperCase().padStart(wide ? 8 : 4, "0")).join(""); - out += `${wide ? "\\X4\\" : "\\X2\\"}${hex}\\X0\\`; - run = []; - }; - for (const ch of s) { - const c = ch.codePointAt(0)!; - if (c >= 0x20 && c <= 0x7e) { - flush(); - out += ch === "\\" ? "\\\\" : ch === "'" ? "''" : ch; - } else { - // \X2\ und \X4\ nicht mischen: Wechsel der Breite beginnt einen neuen Block. - if (run.length > 0 && (run[0] > 0xffff) !== (c > 0xffff)) flush(); - run.push(c); + return fileio().ifc_string(s); +} + +// ── Flacher Puffer (Gegenstück zu src-tauri/fileio/src/ifc_export.rs, dort die Kodierung) ───── + +const FLAT_VERSION = 1; +const REC_WALL_SOLIDS = 1; +const REC_WALL_MESH = 2; +const REC_CEILING = 3; +const REC_OPENING = 4; +const REC_STAIR = 5; +const REC_EXTRUSION = 6; +const REC_SPACE = 7; +const REC_END_SPACES = 8; +const REC_ROOF = 9; +const REC_COLUMN = 10; +const REC_END_COLUMNS = 11; + +/** Typart in der flachen Kodierung (0 Wand, 1 Decke, 2 Dach). */ +type TypeKind = 0 | 1 | 2; + +interface TypeRefIn { + kind: TypeKind; + id: string; + name: string; + predefined: string; + layers: { componentId: string; componentName: string; thickness: number }[]; +} + +/** Pset-Eigenschaft: Kennung, Art (IfcIdentifier, IfcBoolean, IfcPositiveRatioMeasure) und Wert. */ +type PropIn = { name: string; ident: string } | { name: string; bool: boolean } | { name: string; ratio: number }; +interface PsetIn { + name: string; + props: PropIn[]; +} + +/** Sammelt die Bauteile als Zahlenpuffer + Zeichenkettenliste. */ +class FlatIfc { + private nums: number[] = [FLAT_VERSION]; + private strings: string[] = []; + + private str(s: string): number { + this.strings.push(s.replace(/\0/g, "")); + return this.strings.length - 1; + } + private optStr(s: string | null): number { + return s === null ? -1 : this.str(s); + } + private pts(pts: readonly Vec2[]): void { + this.nums.push(pts.length); + for (const p of pts) this.nums.push(p.x, p.y); + } + private mesh(positions: readonly number[], indices: readonly number[], closed: boolean): void { + this.nums.push(positions.length / 3); + for (let i = 0; i < positions.length; i++) this.nums.push(positions[i]); + this.nums.push(indices.length / 3); + for (let i = 0; i < indices.length; i++) this.nums.push(indices[i]); + this.nums.push(closed ? 1 : 0); + } + private typeRef(t: TypeRefIn | null): void { + if (!t) { + this.nums.push(0); + return; + } + this.nums.push(1, t.kind, this.str(t.id), this.str(t.name), this.str(t.predefined), t.layers.length); + for (const l of t.layers) this.nums.push(this.str(l.componentId), this.str(l.componentName), l.thickness); + } + private psets(list: readonly PsetIn[]): void { + this.nums.push(list.length); + for (const ps of list) { + this.nums.push(this.str(ps.name), ps.props.length); + for (const p of ps.props) { + if ("ident" in p) this.nums.push(this.str(p.name), 0, this.str(p.ident)); + else if ("bool" in p) this.nums.push(this.str(p.name), 1, p.bool ? 1 : 0); + else this.nums.push(this.str(p.name), 2, p.ratio); + } } } - flush(); - return `'${out}'`; -} -const S = ifcString; - -/** STEP-REAL-Literal — immer mit Dezimalpunkt, ohne unnötige Nachkommastellen. */ -function R(x: number): string { - const v = Object.is(x, -0) ? 0 : x; - let s = v.toFixed(6); - s = s.replace(/0+$/, ""); - if (s.endsWith(".")) s += "0"; - if (!s.includes(".")) s += ".0"; - return s; -} - -/** STEP-Enumerationswert `.WERT.`. */ -function ENUM(v: string): string { - return `.${v}.`; -} - -/** STEP-Liste `(a,b,c)`. */ -function LIST(items: string[]): string { - return `(${items.join(",")})`; -} - -// ── STEP-Writer ────────────────────────────────────────────────────────────── - -class StepWriter { - private lines: string[] = []; - private nextId = 1; - - /** Schreibt eine neue Entity-Zeile und liefert ihre `#id`. */ - add(type: string, params: string): number { - const id = this.nextId++; - this.lines.push(`#${id}=${type}(${params});`); - return id; + meta(m: { + projectId: string; + projectName: string; + now: number; + iso: string; + hasGeo: boolean; + refElevation: number | null; + storeys: { id: string; name: string; base: number }[]; + }): void { + this.nums.push( + this.str(m.projectId), + this.str(m.projectName), + m.now, + this.str(m.iso), + m.hasGeo ? 1 : 0, + m.refElevation ?? Number.NaN, + m.storeys.length, + ); + for (const s of m.storeys) this.nums.push(this.str(s.id), this.str(s.name), s.base); } - get entityLines(): readonly string[] { - return this.lines; + wallSolids(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], solids: { pts: Vec2[]; zRel: number; depth: number }[]): void { + this.nums.push(REC_WALL_SOLIDS, structure, this.str(id), this.str(name)); + this.typeRef(ty); + this.psets(psets); + this.nums.push(solids.length); + for (const s of solids) { + this.pts(s.pts); + this.nums.push(s.zRel, s.depth); + } + } + + wallMesh(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], positions: number[], indices: number[], closed: boolean): void { + this.nums.push(REC_WALL_MESH, structure, this.str(id), this.str(name)); + this.typeRef(ty); + this.psets(psets); + this.mesh(positions, indices, closed); + } + + ceiling(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], outline: Vec2[], zRel: number, depth: number): void { + this.nums.push(REC_CEILING, structure, this.str(id), this.str(name)); + this.typeRef(ty); + this.psets(psets); + this.pts(outline); + this.nums.push(zRel, depth); + } + + opening(o: { + wallId: string; + structure: number; + openingId: string; + isDoor: boolean; + fillName: string; + voidRect: Vec2[]; + voidZRel: number; + depth: number; + fillRect: Vec2[]; + width: number; + psets: PsetIn[]; + }): void { + this.nums.push(REC_OPENING, this.str(o.wallId), o.structure, this.str(o.openingId), o.isDoor ? 1 : 0, this.str(o.fillName)); + this.pts(o.voidRect); + this.nums.push(o.voidZRel, o.depth); + this.pts(o.fillRect); + this.nums.push(o.width); + this.psets(o.psets); + } + + stair(structure: number, id: string, predefined: string, footprint: Vec2[], zRel: number, depth: number): void { + this.nums.push(REC_STAIR, structure, this.str(id), this.str(predefined)); + this.pts(footprint); + this.nums.push(zRel, depth); + } + + extrusion(structure: number, id: string, pts: Vec2[], zRel: number, depth: number): void { + this.nums.push(REC_EXTRUSION, structure, this.str(id)); + this.pts(pts); + this.nums.push(zRel, depth); + } + + space(s: { + structure: number; + id: string; + name: string; + longName: string; + external: boolean; + height: number; + boundary: Vec2[]; + netArea: number; + grossArea: number; + siaCategory: string; + psets: PsetIn[]; + }): void { + this.nums.push(REC_SPACE, s.structure, this.str(s.id), this.str(s.name), this.str(s.longName), s.external ? 1 : 0, s.height); + this.pts(s.boundary); + this.nums.push(s.netArea, s.grossArea, this.str(s.siaCategory)); + this.psets(s.psets); + } + + endSpaces(): void { + this.nums.push(REC_END_SPACES); + } + + roof(structure: number, id: string, name: string, predefined: string, ty: TypeRefIn | null, psets: PsetIn[], positions: number[], indices: number[], closed: boolean): void { + this.nums.push(REC_ROOF, structure, this.str(id), this.str(name), this.str(predefined)); + this.typeRef(ty); + this.psets(psets); + this.mesh(positions, indices, closed); + } + + column(c: { + structure: number; + id: string; + label: string; + footprint: Vec2[]; + zRel: number; + depth: number; + component: { id: string; name: string } | null; + psets: PsetIn[]; + }): void { + this.nums.push(REC_COLUMN, c.structure, this.str(c.id), this.str(c.label)); + this.pts(c.footprint); + this.nums.push(c.zRel, c.depth, this.optStr(c.component?.id ?? null), this.optStr(c.component?.name ?? null)); + this.psets(c.psets); + } + + endColumns(): void { + this.nums.push(REC_END_COLUMNS); + } + + /** Argumente für die Rust-Bindung: `[Zahlenpuffer, Zeichenketten durch \0 getrennt]`. */ + args(): [Float64Array, string] { + return [new Float64Array(this.nums), this.strings.join("\0")]; } } @@ -367,33 +433,24 @@ function stairFootprint(stair: Stair): Vec2[] { // ── IFC4-Export ────────────────────────────────────────────────────────────── -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; +const ROOF_PREDEFINED: Record = { + flach: "FLAT_ROOF", + pult: "SHED_ROOF", + sattel: "GABLE_ROOF", + walm: "HIP_ROOF", + mansarde: "MANSARD_ROOF", + zelt: "HIPPED_GABLE_ROOF", +}; + +const identifier = (name: string, v: string): PropIn => ({ name, ident: v }); /** * Baut aus einem Projekt einen vollständigen IFC4-SPF-String (STEP Physical - * File). Reiner Rechenkern — kein Datei-IO. Leeres Projekt ⇒ valider Minimal- - * IFC (Project/Site/Building, kein Crash). + * File). Kein Datei-IO. Leeres Projekt ⇒ valider Minimal-IFC (Project/Site/Building, kein Crash). + * Verlangt das geladene Format-Modul (`await loadFileio()`). */ export function exportIfcSpf(projectIn: Project): string { // Georeferenziert exportieren: ist ein Standort-Bezug gesetzt (geoAnchor), @@ -402,297 +459,46 @@ export function exportIfcSpf(projectIn: Project): string { // Modell lokal nahe (0,0) bearbeitet wurde (s. projectToWorldCoords / der // „Neuer Bezugspunkt"-Workflow). Ohne Bezug bleibt alles lokal (Identität). 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). - const originPoint = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(0)])); - const extrudeDir = w.add("IFCDIRECTION", LIST([R(0), R(0), R(1)])); - const identityAxis = w.add("IFCAXIS2PLACEMENT3D", `#${originPoint},$,$`); - - // Owner-History (minimal, aber vorhanden — manche Importer verlangen sie). - const org = w.add("IFCORGANIZATION", `$,${S("dossier")},$,$,$`); - const person = w.add( - "IFCPERSON", - `${S("dossier")},$,$,$,$,$,$,$`, - ); - const personOrg = w.add("IFCPERSONANDORGANIZATION", `#${person},#${org},$`); - const app = w.add( - "IFCAPPLICATION", - `#${org},${S("1.0")},${S("dossier")},${S("dossier")}`, - ); - // ChangeAction ADDED verlangt ein LastModifiedDate (IFC4-Regel IfcOwnerHistory.CorrectChangeAction): - // beim frischen Export ist es der Erstellungszeitpunkt. - const now = Math.floor(Date.now() / 1000); - const ownerHistory = w.add( - "IFCOWNERHISTORY", - `#${personOrg},#${app},$,${ENUM("ADDED")},${now},$,$,${now}`, - ); - - // Einheiten (Meter, Radiant, m², m³). - const lenUnit = w.add("IFCSIUNIT", `*,${ENUM("LENGTHUNIT")},$,${ENUM("METRE")}`); - const areaUnit = w.add("IFCSIUNIT", `*,${ENUM("AREAUNIT")},$,${ENUM("SQUARE_METRE")}`); - const volUnit = w.add("IFCSIUNIT", `*,${ENUM("VOLUMEUNIT")},$,${ENUM("CUBIC_METRE")}`); - const angleUnit = w.add( - "IFCSIUNIT", - `*,${ENUM("PLANEANGLEUNIT")},$,${ENUM("RADIAN")}`, - ); - const unitAssignment = w.add( - "IFCUNITASSIGNMENT", - LIST([`#${lenUnit}`, `#${areaUnit}`, `#${volUnit}`, `#${angleUnit}`]), - ); - - // Geometrischer Kontext (3D, Precision 1e-5). - const context = w.add( - "IFCGEOMETRICREPRESENTATIONCONTEXT", - `$,${S("Model")},3,${R(0.00001)},#${identityAxis},$`, - ); - - // Georeferenz: Die Geometrie liegt bereits in LV95-Weltkoordinaten (s. oben), die Abbildung - // lokal→Welt ist daher die Identität; das Koordinatensystem wird trotzdem deklariert, damit - // Importer die Datei als EPSG:2056 erkennen (IFC4 IfcProjectedCRS + IfcMapConversion). - if (project.geoAnchor) { - const crs = w.add( - "IFCPROJECTEDCRS", - `${S("EPSG:2056")},${S("CH1903+ / LV95")},${S("CH1903+")},$,${S("Swiss Oblique Mercator")},$,#${lenUnit}`, - ); - w.add("IFCMAPCONVERSION", `#${context},#${crs},${R(0)},${R(0)},${R(0)},${R(1)},${R(0)},${R(1)}`); - } - - // Räumliche Hierarchie: Project → Site → Building → Storeys. - const siteAxis = w.add("IFCAXIS2PLACEMENT3D", `#${originPoint},$,$`); - const sitePlacement = w.add("IFCLOCALPLACEMENT", `$,#${siteAxis}`); - const buildingAxis = w.add("IFCAXIS2PLACEMENT3D", `#${originPoint},$,$`); - const buildingPlacement = w.add( - "IFCLOCALPLACEMENT", - `#${sitePlacement},#${buildingAxis}`, - ); - - const projectId = w.add( - "IFCPROJECT", - `${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 — - // die Geometrie wird NICHT verschoben (das Terrain trägt bereits reale Höhen). - const refElevation = project.geoAnchor?.height; - const siteRefElev = typeof refElevation === "number" ? R(refElevation) : "$"; - const siteId = w.add( - "IFCSITE", - `${gid("site")},#${ownerHistory},${S("Standort")},$,$,#${sitePlacement},$,$,${ENUM("ELEMENT")},$,$,${siteRefElev},$,$`, - ); - const buildingId = w.add( - "IFCBUILDING", - `${gid("building")},#${ownerHistory},${S(project.name || "Gebäude")},$,$,#${buildingPlacement},$,$,${ENUM("ELEMENT")},$,$,$`, - ); - w.add( - "IFCRELAGGREGATES", - `${gid("aggregates/site")},#${ownerHistory},$,$,#${projectId},${LIST([`#${siteId}`])}`, - ); - w.add( - "IFCRELAGGREGATES", - `${gid("aggregates/building")},#${ownerHistory},$,$,#${siteId},${LIST([`#${buildingId}`])}`, - ); + const flat = new FlatIfc(); // Je "floor"-Geschoss ein IfcBuildingStorey (Elevation = baseElevation). const floors = project.drawingLevels.filter((l) => l.kind === "floor"); - const storeyByFloorId = new Map(); - const storeyEntityIds: number[] = []; - for (const floor of floors) { - const base = floor.baseElevation ?? 0; - const pt = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(base)])); - const axis = w.add("IFCAXIS2PLACEMENT3D", `#${pt},$,$`); - const placementId = w.add("IFCLOCALPLACEMENT", `#${buildingPlacement},#${axis}`); - const entityId = w.add( - "IFCBUILDINGSTOREY", - `${gid(`storey/${floor.id}`)},#${ownerHistory},${S(floor.name)},$,$,#${placementId},$,$,${ENUM("ELEMENT")},${R(base)}`, - ); - storeyByFloorId.set(floor.id, { entityId, placementId, baseElevation: base, key: `storey/${floor.id}` }); - storeyEntityIds.push(entityId); - } - if (storeyEntityIds.length > 0) { - w.add( - "IFCRELAGGREGATES", - `${gid("aggregates/storeys")},#${ownerHistory},$,$,#${buildingId},${LIST(storeyEntityIds.map((id) => `#${id}`))}`, - ); - } + const storeyIndexByFloorId = new Map(); + const storeyBase: number[] = []; + floors.forEach((floor, i) => { + storeyIndexByFloorId.set(floor.id, i); + storeyBase.push(floor.baseElevation ?? 0); + }); + /** Geschoss → Index der Trägerstruktur, oder −1 = Gebäude (verwaiste floorId). */ + const structureOf = (floorId: string): number => storeyIndexByFloorId.get(floorId) ?? -1; + const baseOf = (structure: number): number => (structure < 0 ? 0 : storeyBase[structure]); - /** Geschoss → Trägerstruktur (Storey), oder defensiv das Gebäude (verwaiste floorId). */ - const buildingStructure: Structure = { entityId: buildingId, placementId: buildingPlacement, baseElevation: 0, key: "building" }; - const resolveStructure = (floorId: string): Structure => storeyByFloorId.get(floorId) ?? buildingStructure; + // RefElevation (m ü. M.): reale Datumshöhe des Standorts aus dem Georeferenzierungs-Bezug (wie + // ArchiCADs Vermessungspunkt). Rein informativ — die Geometrie wird NICHT verschoben. + const refElevation = project.geoAnchor?.height; + flat.meta({ + projectId: project.id, + projectName: project.name ?? "", + now: Math.floor(Date.now() / 1000), + iso: new Date().toISOString().replace(/\.\d+Z$/, ""), + hasGeo: !!project.geoAnchor, + refElevation: typeof refElevation === "number" ? refElevation : null, + storeys: floors.map((f, i) => ({ id: f.id, name: f.name, base: storeyBase[i] })), + }); - // 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 = (structure: Structure, elementId: number): void => { - const arr = containment.get(structure); - if (arr) arr.push(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. */ - const emitBoxProduct = ( - footprint: Vec2[], - zBottomRel: number, - depth: number, - placementRelTo: number, - ): { placementId: number; shapeId: number } => { - const shapeId = emitSweptShape([emitExtrusion(footprint, 0, depth)]); - return { placementId: emitPlacement(zBottomRel, placementRelTo), shapeId }; - }; - - /** - * Baut aus einem Dreiecks-Mesh (`positions` flach x,y,z in IFC-Koordinaten — - * bereits Z-up und relativ zur `placementRelTo`-Herkunft, `indices` je 3 = - * 1-basiert-1 CoordIndex-Tripel) ein IfcTriangulatedFaceSet + Shape + Placement. - * IFC4-Tessellierung: IfcCartesianPointList3D (CoordList) + IfcTriangulatedFace - * Set (CoordIndex, 1-basiert). Das Element-Placement sitzt im Ursprung der - * Trägerstruktur (die Punkte tragen die Geometrie bereits absolut in deren Frame). - */ - const emitTriangulatedProduct = ( - positions: number[], - indices: number[], - placementRelTo: number, - closed: boolean, - ): { placementId: number; shapeId: number } => { - const coords: string[] = []; - for (let i = 0; i < positions.length; i += 3) { - coords.push(`(${R(positions[i])},${R(positions[i + 1])},${R(positions[i + 2])})`); - } - const pointListId = w.add("IFCCARTESIANPOINTLIST3D", `(${coords.join(",")})`); - const tris: string[] = []; - for (let i = 0; i < indices.length; i += 3) { - tris.push(`(${indices[i] + 1},${indices[i + 1] + 1},${indices[i + 2] + 1})`); - } - // Closed=.T. NUR wenn das Mesh nachweislich ein dichtes, aussen orientiertes - // Volumen ist (siehe isWatertight): Wände sind extrudierte Querschnitts- - // Polygone (Fenster = Durchgangsloch, Tür = umlaufende П-Kerbe) → geschlossene - // Körper → `.T.` (Viewer rendern sie als Solid statt als offene Fläche). Der - // Guard fängt echte Defekte ab (invertierte Wicklung → Volumen < 0 → `$`). - // Normals=$ (Viewer leitet sie aus der — jetzt aussen orientierten — Wicklung ab). - const closedFlag = closed ? ".T." : "$"; - const faceSetId = w.add("IFCTRIANGULATEDFACESET", `#${pointListId},$,${closedFlag},(${tris.join(",")}),$`); - const shapeRepId = w.add( - "IFCSHAPEREPRESENTATION", - `#${context},${S("Body")},${S("Tessellation")},${LIST([`#${faceSetId}`])}`, - ); - const shapeId = w.add("IFCPRODUCTDEFINITIONSHAPE", `$,$,${LIST([`#${shapeRepId}`])}`); - return { placementId: emitPlacement(0, placementRelTo), shapeId }; - }; - - /** Baut ein IfcBuildingElement-Subtyp mit dem üblichen 9-Attribut-Flatten. */ - const emitBuildingElement = ( - type: string, - guid: string, - name: string, - placementId: number, - shapeId: number, - predefinedType: string | null, - ): number => - w.add( - type, - `${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 (s. Dateikopf). - const materialIdByComponent = new Map(); - const materialOf = (componentId: string): number => { - const hit = materialIdByComponent.get(componentId); - if (hit !== undefined) return hit; - const name = project.components.find((c) => c.id === componentId)?.name ?? componentId; - const id = w.add("IFCMATERIAL", `${S(name)},$,$`); - materialIdByComponent.set(componentId, id); - return id; - }; - interface ElementTypeRef { - typeId: number; - occurrences: number[]; - } - const elementTypes = new Map(); - const typeFor = ( - ifcType: "IFCWALLTYPE" | "IFCSLABTYPE" | "IFCROOFTYPE", + const componentName = (componentId: string): string => + project.components.find((c) => c.id === componentId)?.name ?? componentId; + const typeRef = ( + kind: TypeKind, predefined: string, t: { id: string; name: string; layers: { componentId: string; thickness: number }[] }, - ): ElementTypeRef => { - const key = `type/${ifcType}/${t.id}`; - const hit = elementTypes.get(key); - if (hit) return hit; - const layerIds = t.layers.map((l) => - w.add("IFCMATERIALLAYER", `#${materialOf(l.componentId)},${R(Math.max(0, Number.isFinite(l.thickness) ? l.thickness : 0))},$,$,$,$,$`), - ); - const typeId = w.add( - ifcType, - `${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", - `${gid(`${key}/material`)},#${ownerHistory},$,$,${LIST([`#${typeId}`])},#${setId}`, - ); - } - const ref = { typeId, occurrences: [] }; - elementTypes.set(key, ref); - return ref; - }; + ): TypeRefIn => ({ + kind, + id: t.id, + name: t.name, + predefined, + layers: t.layers.map((l) => ({ componentId: l.componentId, componentName: componentName(l.componentId), thickness: l.thickness })), + }); // ── Wände ────────────────────────────────────────────────────────────── // Die Wand-Schicht-Bänder kommen aus DEMSELBEN geflachten Modell wie STL/OBJ @@ -712,8 +518,7 @@ export function exportIfcSpf(projectIn: Project): string { // 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; - for (const band of allBands) { + for (const band of pickGeometry(project).walls) { const list = bandsByWallId.get(band.wallId); if (list) list.push(band); else bandsByWallId.set(band.wallId, [band]); @@ -728,28 +533,22 @@ export function exportIfcSpf(projectIn: Project): string { } 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; + /** Name, Typ und Pset einer Wand (verwaister Wandtyp: Roh-ID als Name, kein Typ). */ + const wallIdentity = (wall: Wall): { name: string; ty: TypeRefIn | null; psets: PsetIn[] } => { try { const wt = getWallType(project, wall); - name = wt.name; - reference = wt.name; - wallType = typeFor("IFCWALLTYPE", "STANDARD", wt); + return { + name: wt.name, + ty: typeRef(0, "STANDARD", wt), + psets: [{ name: "Pset_WallCommon", props: [identifier("Reference", wt.name)] }], + }; } catch { - /* verwaister Wandtyp — Roh-ID als Name, kein Typ */ + return { name: wall.id, ty: null, psets: [] }; } - 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); + }; + /** Ausdehnung aller Bänder quer zur Wandachse (entlang der linken Normalen ab `wall.start`). */ + const crossExtent = (wall: Wall, bands: readonly RWall[]): { nLo: number; nHi: number } => { + const n = leftNormal(normalize(sub(wall.end, wall.start))); let nLo = Infinity; let nHi = -Infinity; for (const b of bands) { @@ -757,8 +556,12 @@ export function exportIfcSpf(projectIn: Project): string { nLo = Math.min(nLo, off - b.thickness / 2); nHi = Math.max(nHi, off + b.thickness / 2); } - wallRefById.set(wall.id, { entityId, placementId, nLo, nHi }); + return { nLo, nHi }; }; + + const meshWalls: { wall: Wall; bands: RWall[] }[] = []; + const hostExtent = new Map(); + const cutoutsByWallId = new Map(); for (const wall of project.walls ?? []) { 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, @@ -770,23 +573,25 @@ export function exportIfcSpf(projectIn: Project): string { meshWalls.push({ wall, bands: bandsByWallId.get(wall.id)! }); continue; } - const structure = resolveStructure(wall.floorId); + const structure = structureOf(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); + return { pts: rect, zRel: b.baseElevation - baseOf(structure), depth: b.height }; }); - emitWallEntity(wall, structure, emitPlacement(0, structure.placementId), emitSweptShape(solids), bands); + const id = wallIdentity(wall); + flat.wallSolids(structure, wall.id, id.name, id.ty, id.psets, solids); + hostExtent.set(wall.id, crossExtent(wall, 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 structure = structureOf(wall.floorId); const positions: number[] = []; const indices: number[] = []; for (const band of bands) { @@ -794,11 +599,7 @@ export function exportIfcSpf(projectIn: Project): string { if (!cut) continue; const base = positions.length / 3; for (let i = 0; i < cut.positions.length; i += 3) { - positions.push( - cut.positions[i], - cut.positions[i + 2], - cut.positions[i + 1] - structure.baseElevation, - ); + positions.push(cut.positions[i], cut.positions[i + 2], cut.positions[i + 1] - baseOf(structure)); } // Wicklung umkehren (Reflexions-Ausgleich, s. o.): (a,b,c) → (a,c,b). for (let i = 0; i < cut.indices.length; i += 3) { @@ -806,44 +607,32 @@ export function exportIfcSpf(projectIn: Project): string { } } if (indices.length === 0) continue; + // Closed=.T. NUR wenn das Mesh nachweislich ein dichtes, aussen orientiertes Volumen ist + // (Wände sind extrudierte Querschnitts-Polygone → geschlossene Körper); der Guard fängt echte + // Defekte ab (invertierte Wicklung → Volumen < 0 → `$`). const closed = isWatertight({ positions, indices }); - const { placementId, shapeId } = emitTriangulatedProduct(positions, indices, structure.placementId, closed); - emitWallEntity(wall, structure, placementId, shapeId, bands); + const id = wallIdentity(wall); + flat.wallMesh(structure, wall.id, id.name, id.ty, id.psets, positions, indices, closed); + hostExtent.set(wall.id, crossExtent(wall, bandsByWallId.get(wall.id)!)); } // ── Decken ───────────────────────────────────────────────────────────── for (const ceiling of project.ceilings ?? []) { if (ceiling.outline.length < 3) continue; const { zBottom, zTop } = ceilingVerticalExtent(project, ceiling); - const structure = resolveStructure(ceiling.floorId); - const { placementId, shapeId } = emitBoxProduct( - ceiling.outline, - zBottom - structure.baseElevation, - zTop - zBottom, - structure.placementId, - ); + const structure = structureOf(ceiling.floorId); let name: string = ceiling.id; - let slabType: ElementTypeRef | null = null; - let reference: string | null = null; + let ty: TypeRefIn | null = null; + const psets: PsetIn[] = []; try { const ct = getCeilingType(project, ceiling); name = ct.name; - reference = ct.name; - slabType = typeFor("IFCSLABTYPE", "FLOOR", ct); + ty = typeRef(1, "FLOOR", ct); + psets.push({ name: "Pset_SlabCommon", props: [identifier("Reference", ct.name)] }); } catch { /* verwaister Deckentyp — Roh-ID als Name, kein Typ */ } - const entityId = emitBuildingElement( - "IFCSLAB", - gid(`slab/${ceiling.id}`), - name, - placementId, - shapeId, - ENUM("FLOOR"), - ); - slabType?.occurrences.push(entityId); - addToContainment(structure, entityId); - if (reference !== null) addPset("Pset_SlabCommon", [["Reference", identifier(reference)]], entityId); + flat.ceiling(structure, ceiling.id, name, ty, psets, ceiling.outline, zBottom - baseOf(structure), zTop - zBottom); } // ── Öffnungen: IfcOpeningElement in der Wand, IfcDoor/IfcWindow darin ─── @@ -852,61 +641,42 @@ export function exportIfcSpf(projectIn: Project): string { // 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); + const host = hostExtent.get(wall.id); if (!host) continue; // Wirtswand übersprungen (degeneriert) - const structure = resolveStructure(wall.floorId); + const structure = structureOf(wall.floorId); 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( - 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][] = []; + const props: PropIn[] = []; + let psetName: string; if (isDoor) { + psetName = "Pset_DoorCommon"; const dt = getDoorType(project, opening); - if (dt) props.push(["Reference", identifier(dt.name)]); + if (dt) props.push(identifier("Reference", dt.name)); const ratio = dt?.glazingRatio; if (dt?.leafStyle === "glas" && typeof ratio === "number" && ratio > 0 && ratio <= 1) { - props.push(["GlazingAreaFraction", `IFCPOSITIVERATIOMEASURE(${R(ratio)})`]); + props.push({ name: "GlazingAreaFraction", ratio }); } - addPset("Pset_DoorCommon", props, fillEntityId); } else { + psetName = "Pset_WindowCommon"; const wt = getWindowType(project, opening); - if (wt) props.push(["Reference", identifier(wt.name)]); - addPset("Pset_WindowCommon", props, fillEntityId); + if (wt) props.push(identifier("Reference", wt.name)); } + flat.opening({ + wallId: wall.id, + structure, + openingId: opening.id, + isDoor, + fillName: openingLabel(opening), + voidRect: axisRect(wall, c.from, c.to, host.nLo - OPENING_OVERSHOOT, host.nHi + OPENING_OVERSHOOT), + voidZRel: c.zBottom - baseOf(structure), + depth, + fillRect: axisRect(wall, c.from, c.to, host.nLo, host.nHi), + width: c.to - c.from, + psets: [{ name: psetName, props }], + }); } } @@ -915,28 +685,9 @@ export function exportIfcSpf(projectIn: Project): string { const footprint = stairFootprint(stair); if (footprint.length < 3) continue; const { zBottom, zTop } = stairVerticalExtent(project, stair); - const structure = resolveStructure(stair.floorId); - const { placementId, shapeId } = emitBoxProduct( - footprint, - zBottom - structure.baseElevation, - zTop - zBottom, - structure.placementId, - ); - const predefinedType = - stair.shape === "straight" - ? ENUM("STRAIGHT_RUN_STAIR") - : stair.shape === "spiral" - ? ENUM("SPIRAL_STAIR") - : ENUM("QUARTER_TURN_STAIR"); - const entityId = emitBuildingElement( - "IFCSTAIR", - gid(`stair/${stair.id}`), - "Treppe", - placementId, - shapeId, - predefinedType, - ); - addToContainment(structure, entityId); + const structure = structureOf(stair.floorId); + const predefined = stair.shape === "straight" ? "STRAIGHT_RUN_STAIR" : stair.shape === "spiral" ? "SPIRAL_STAIR" : "QUARTER_TURN_STAIR"; + flat.stair(structure, stair.id, predefined, footprint, zBottom - baseOf(structure), zTop - zBottom); } // ── Extrudierte Körper (truck-Integration) → IfcBuildingElementProxy ─── @@ -944,22 +695,8 @@ export function exportIfcSpf(projectIn: Project): string { if (solid.points.length < 3) continue; const floor = floors.find((f) => f.id === solid.levelId); const base = floor?.baseElevation ?? 0; - const structure = resolveStructure(solid.levelId); - const { placementId, shapeId } = emitBoxProduct( - solid.points, - base - structure.baseElevation, - solid.height, - structure.placementId, - ); - const entityId = emitBuildingElement( - "IFCBUILDINGELEMENTPROXY", - gid(`extrusion/${solid.id}`), - "Extrusion", - placementId, - shapeId, - null, - ); - addToContainment(structure, entityId); + const structure = structureOf(solid.levelId); + flat.extrusion(structure, solid.id, solid.points, base - baseOf(structure), solid.height); } // ── Räume → IfcSpace ─────────────────────────────────────────────────── @@ -968,76 +705,45 @@ export function exportIfcSpf(projectIn: Project): string { // Geschoss AGGREGIERT (IfcRelAggregates), nicht enthalten. Dazu Basismengen // (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 structure = structureOf(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", - `${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); - if (list) list.push(spaceId); - else spacesByStructure.set(structure, [spaceId]); - const area = evaluateRoom(room.boundary, room.siaCategory); - const qNet = w.add("IFCQUANTITYAREA", `${S("NetFloorArea")},$,$,${R(area.netArea)},$`); - const qGross = w.add("IFCQUANTITYAREA", `${S("GrossFloorArea")},$,$,${R(area.grossArea)},$`); - const qHeight = w.add("IFCQUANTITYLENGTH", `${S("Height")},$,$,${R(height)},$`); - const qto = w.add( - "IFCELEMENTQUANTITY", - `${gid(`space/${room.id}/qto`)},#${ownerHistory},${S("Qto_SpaceBaseQuantities")},$,$,${LIST([`#${qNet}`, `#${qGross}`, `#${qHeight}`])}`, - ); - w.add( - "IFCRELDEFINESBYPROPERTIES", - `${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", - `${gid(`space/${room.id}/pset`)},#${ownerHistory},${S("CH_Raum")},$,${LIST([`#${sia}`])}`, - ); - w.add( - "IFCRELDEFINESBYPROPERTIES", - `${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 [structure, spaceIds] of spacesByStructure) { - w.add( - "IFCRELAGGREGATES", - `${gid(`aggregates/spaces/${structure.key}`)},#${ownerHistory},$,$,#${structure.entityId},${LIST(spaceIds.map((id) => `#${id}`))}`, - ); + const common: PropIn[] = []; + if (room.stamp?.number) common.push(identifier("Reference", room.stamp.number)); + common.push({ name: "IsExternal", bool: external }); + flat.space({ + structure, + id: room.id, + name: room.stamp?.number || room.id, + longName: room.name, + external, + height, + boundary: room.boundary, + netArea: area.netArea, + grossArea: area.grossArea, + siaCategory: room.siaCategory, + psets: [{ name: "Pset_SpaceCommon", props: common }], + }); } + flat.endSpaces(); // ── Dächer → IfcRoof ─────────────────────────────────────────────────── // Dieselben geschlossenen Schicht-Meshes wie das 3D (`emitRoofs`: Dachflächen je Schicht, // an First/Grat gehrt), zu EINEM Face-Set je Dach vereint. Modell-Koordinaten sind bereits // Z-oben (kein Achsentausch wie bei den Wänden); die Wicklung wird so gewählt, dass das Volumen // positiv ist — nur dann ist das Face-Set als geschlossen markiert. - const ROOF_PREDEFINED: Record = { - flach: "FLAT_ROOF", - pult: "SHED_ROOF", - sattel: "GABLE_ROOF", - walm: "HIP_ROOF", - mansarde: "MANSARD_ROOF", - zelt: "HIPPED_GABLE_ROOF", - }; for (const roof of project.roofs ?? []) { - const structure = resolveStructure(roof.floorId); + const structure = structureOf(roof.floorId); const positions: number[] = []; const indices: number[] = []; for (const mesh of emitRoofs({ ...project, roofs: [roof] })) { const base = positions.length / 3; for (let i = 0; i < mesh.positions.length; i += 3) { - positions.push(mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2] - structure.baseElevation); + positions.push(mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2] - baseOf(structure)); } for (const ix of mesh.indices) indices.push(base + ix); } @@ -1051,89 +757,52 @@ export function exportIfcSpf(projectIn: Project): string { closed = true; } } - 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", gid(`roof/${roof.id}`), roofType?.name ?? "Dach", placementId, shapeId, ENUM(predefined)); - if (roofType) typeFor("IFCROOFTYPE", predefined, roofType).occurrences.push(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); + const props: PropIn[] = []; + if (roofType) props.push(identifier("Reference", roofType.name)); + props.push({ name: "IsExternal", bool: true }); + flat.roof( + structure, + roof.id, + roofType?.name ?? "Dach", + predefined, + roofType ? typeRef(2, predefined, roofType) : null, + [{ name: "Pset_RoofCommon", props }], + positions, + indices, + closed, + ); } // ── Stützen → IfcColumn (Profil-Extrusion, Material = Bauteil) ────────── - const materialAssoc = new Map(); for (const col of project.columns ?? []) { const footprint = columnFootprint(col); if (footprint.length < 3) continue; const { zBottom, zTop } = columnVerticalExtent(project, col); if (!(zTop > zBottom)) continue; - const structure = resolveStructure(col.floorId); - const { placementId, shapeId } = emitBoxProduct(footprint, zBottom - structure.baseElevation, zTop - zBottom, structure.placementId); + const structure = structureOf(col.floorId); 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 list = materialAssoc.get(col.componentId); - if (list) list.push(entityId); - else materialAssoc.set(col.componentId, [entityId]); - } + flat.column({ + structure, + id: col.id, + label, + footprint, + zRel: zBottom - baseOf(structure), + depth: zTop - zBottom, + component: col.componentId ? { id: col.componentId, name: componentName(col.componentId) } : null, + psets: [{ name: "Pset_ColumnCommon", props: [identifier("Reference", label)] }], + }); } - for (const [componentId, ids] of materialAssoc) { - w.add( - "IFCRELASSOCIATESMATERIAL", - `${gid(`material/${componentId}/columns`)},#${ownerHistory},$,$,${LIST(ids.map((id) => `#${id}`))},#${materialOf(componentId)}`, - ); + flat.endColumns(); + + const m = fileio(); + const [buf, strings] = flat.args(); + const text = m.export_ifc_flat(buf, strings); + if (text.length === 0) { + const why = m.export_ifc_check_flat(buf, strings); + throw new Error(`IFC-Export fehlgeschlagen${why ? `: ${why}` : ""}`); } - - // ── Typ-Zuordnung (je Bauteiltyp eine IfcRelDefinesByType) ───────────── - for (const [key, ref] of elementTypes) { - if (ref.occurrences.length === 0) continue; - w.add( - "IFCRELDEFINESBYTYPE", - `${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 [structure, elementIds] of containment) { - w.add( - "IFCRELCONTAINEDINSPATIALSTRUCTURE", - `${gid(`contains/${structure.key}`)},#${ownerHistory},$,$,${LIST(elementIds.map((id) => `#${id}`))},#${structure.entityId}`, - ); - } - - // ── Kopf + Zusammenbau ─────────────────────────────────────────────────── - const iso = new Date().toISOString().replace(/\.\d+Z$/, ""); - const fileName = `${project.name || "modell"}.ifc`; - const header = [ - "ISO-10303-21;", - "HEADER;", - `FILE_DESCRIPTION(${LIST([S("")])},${S("2;1")});`, - `FILE_NAME(${S(fileName)},${S(iso)},${LIST([S("dossier")])},${LIST([S("dossier")])},${S("dossier")},${S("dossier")},${S("")});`, - "FILE_SCHEMA(('IFC4'));", - "ENDSEC;", - "", - "DATA;", - ]; - const footer = ["ENDSEC;", "END-ISO-10303-21;"]; - - return [...header, ...w.entityLines, ...footer].join("\n") + "\n"; + return text; } diff --git a/src/export/exportIfc.validate.test.ts b/src/export/exportIfc.validate.test.ts index 7dd152b8..e02e19a8 100644 --- a/src/export/exportIfc.validate.test.ts +++ b/src/export/exportIfc.validate.test.ts @@ -7,6 +7,7 @@ import { spawnSync } from "node:child_process"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import "../engine/fileioWasm.setup"; import { exportIfcSpf, ifcGuid } from "./exportIfc"; import { pickGeometry } from "../plan/toWalls3d"; import { wallCutMeshes } from "../plan/wallMeshCut"; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index cef294bd..95548559 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1751,6 +1751,7 @@ export const de = { "exportSave.fmt.stl": "STL (3D-Mesh)", "exportSave.fmt.step": "STEP (B-Rep, truck)", "step.export.failed": "STEP-Export fehlgeschlagen", + "ifc.export.failed": "IFC-Export fehlgeschlagen", "step.export.skipped": "{n} Körper konnten nicht exportiert werden", "step.import.failed": "STEP-Import fehlgeschlagen", "step.import.done": "STEP importiert: {n} Körper", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index a9632e06..e4b7c3d6 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1712,6 +1712,7 @@ export const en: Record = { "file.exportStl": "Export STL (3D mesh)", "exportSave.fmt.step": "STEP (B-rep, truck)", "step.export.failed": "STEP export failed", + "ifc.export.failed": "IFC export failed", "step.export.skipped": "{n} solids could not be exported", "step.import.failed": "STEP import failed", "step.import.done": "STEP imported: {n} solids", diff --git a/src/state/useProjectFileActions.ts b/src/state/useProjectFileActions.ts index 7dc13ac2..6e94ed89 100644 --- a/src/state/useProjectFileActions.ts +++ b/src/state/useProjectFileActions.ts @@ -22,6 +22,7 @@ import { distinctImportLayers, planImportCategories } from "../io/dxfToDrawings" import type { ImportDecision } from "../ui/ImportDialog"; import { exportScheduleCsv } from "../export/exportSchedule"; import { exportIfcSpf } from "../export/exportIfc"; +import { loadFileio } from "../engine/fileioWasm"; import { exportProjectStep } from "../export/exportStep"; import { exportObj, exportStl } from "../export/exportMesh"; import type { ExportSaveFormat } from "../ui/ExportSaveDialog"; @@ -503,7 +504,10 @@ export function useProjectFileActions( downloadTextFile("" + exportScheduleCsv(project), filename, "text/csv;charset=utf-8;"); break; case "ifc": - downloadTextFile(exportIfcSpf(project), filename); + // IFC schreibt Rust (Format-Modul pkgFileIo, wird beim ersten Export nachgeladen). + void loadFileio() + .then(() => downloadTextFile(exportIfcSpf(project), filename)) + .catch((e) => notify(`${t("ifc.export.failed")}: ${e instanceof Error ? e.message : String(e)}`, "error")); break; case "obj": downloadTextFile(exportObj(project), filename);