diff --git a/TODO.md b/TODO.md index 988fb3f4..6acf54dc 100644 --- a/TODO.md +++ b/TODO.md @@ -249,7 +249,7 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). - ✅ **[41] Massenmodelle.** `analysis/kennzahlen.ts`: GF/aGF je Geschoss, GV aus Körpern. - ✅ **[61] Raumprogramm gegen Modell.** `checkRoomProgram`, Editor im Flächenbilanz-Panel (27.10.). - ✅ **[62] Kennzahlenleiste.** Flächenbilanz-Panel: GF/aGF/GV/AZ/ÜZ, Parzellenfläche, je Geschoss (27.10.). -- ◐ **[70] Flächentabellen SIA 416 / IVHB.** SIA-416-Bilanz vorhanden (CSV); IVHB offen. · M +- ◐ **[70] Flächentabellen SIA 416 / IVHB.** SIA-416-Bilanz vorhanden (CSV); IVHB offen. IFC (28.10., [B5]): SIA-416-Zonen und Geschoss-GF/NGF als Qto im IFC-Export. · M - ○ **[42] Varianten.** · L - ✅ **[63] Baulinien, Grenzabstände, zulässige Hülle.** (27.10.) Parzelle/Baulinien aus Auswahl, Grenzabstand pauschal und je Kante, Gesamthöhe; zulässige Fläche und Verstösse im Grundriss. @@ -435,6 +435,13 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module Aufschlagrichtung; `openingDir` kommt als „in“ mit gespiegeltem `swing` zurück), 2-flügliges Fenster → Typ „Fenster 2-flügl.“. Offen: LEFT/RIGHT nur gegen den eigenen Export geprüft (nicht Revit/ArchiCAD); Türen ohne Ausführung bleiben beim Standard (kein Raten aus der Platzierung). + (28.10., Klassifikation/Zonen) IfcClassificationReference (Bauteil, sonst Typ; System aus ReferencedSource, + IFC4 und IFC2x3) wird gelesen (`Info.classifications`, `IfcProduct.classifications`): Kontext-Meshes + tragen sie im Namen (` [eBKP-H C]`), für Wand/Decke/Stütze/Raum gibt es kein Modellfeld (kein neues + angelegt) — Zählung in der Import-Meldung (`summary.classified`). IfcZone (IfcRelAssignsToGroup) → + SIA-416-Kategorie des Raums, wenn er keine eigene `CH_Raum`-Eigenschaft hat: `CH_Zone.SIA416`, sonst der + Zonenname (HNF, NNF, VF, FF, KGF/KF, AGF; kein Raten bei anderen Namen). Rundreise Export → Import + geprüft. Offen: Klassifikation als Feld am Bauteil, IfcGrid (Modell ohne Raster). - ◐ **[B5] IFC-Export nachziehen** (`exportIfc.ts`). Stand 28.10.: - ✅ Nicht-ASCII nach ISO 10303-21 (`\X2\`/`\X4\`). - ✅ Materialschichten: Wand-/Decken-/Dachtypen als IfcWallType/IfcSlabType/IfcRoofType mit @@ -498,6 +505,23 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module 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 + - ✅ IFC für die Schweizer Praxis (28.10.): (1) Klassifikation als Option im Export-Dialog + (`ExportSaveDialog`, CLI `ifc --ebkph --ebenen`): IfcClassification + IfcClassificationReference + + IfcRelAssociatesClassification (Rust-Datensatz CLASSIFICATION, eine Beziehung je Code). Das Modell führt + KEINEN eBKP-H-/BKP-Code; `categoryCode` ist die Grafik-Ebene. Daher zwei Wege: „eBKP-H-Klassifikation + hinzufügen“ = Standardzuordnung auf Hauptgruppen (`export/ifcClassification.ts`; Quelle CRB, eBKP-H, + SN 506 511:2020; nur die Buchstaben C Konstruktion Gebäude, E Äussere Wandbekleidung Gebäude, F Bedachung + Gebäude): Wand/Decke/Stütze/Treppe = C, Dach = F, Fenster = E, Tür und Raum ohne (Aussen/Innen nicht + unterscheidbar, nicht geraten); keine Untergruppen. „Ebene des Modells als Klassifikation“ = System + „Dossier-Ebenen“ (Code = `categoryCode`, Name = Ebenenname). (2) Zonen: je vorkommender SIA-416-Kategorie + eine IfcZone + IfcRelAssignsToGroup der IfcSpaces (immer, wenn Räume da sind), `CH_Zone.SIA416`, + `CH_Qto_SIA416.NetFloorArea`; je Geschoss `Qto_BuildingStoreyBaseQuantities` (GF/NGF) + `CH_Qto_SIA416` + (HNF … GF). (3) Achsraster: nicht exportiert, das Modell hat keine Raster-Ressource (nur die Regel „grid“ + der parametrischen Wände). Geprüft: ifcopenshell (`util.classification.get_references`, Zonen-Mitglieder, + Storey-Qtos; validate-ifc 0 Befunde), Rust- und vitest-Tests, GUIDs bleiben stabil. Offen: die eBKP-H- + Zuordnung ist ein Vorschlag (Tür, Untergruppen, Aussen-/Innenwand brauchen Modellfelder; Fenster → E und + Dach → F sind Entscheide auf Gruppenebene, vom Maintainer/Kostenplaner zu bestätigen); nicht in + Revit/ArchiCAD/Solibri geöffnet; nur Linux-Container/vitest, nicht in der Tauri-App geprüft. · S - ✅ Basismengen für Kostenplanung/Mengenermittlung. (28.10.) `Qto_WallBaseQuantities` (Length, Width, Height, GrossSideArea, NetSideArea, GrossVolume, NetVolume), `Qto_SlabBaseQuantities` (Decke und Podest: Width, Perimeter, Gross-/NetArea, Gross-/NetVolume), `Qto_RoofBaseQuantities` (GrossArea, NetArea, ProjectedArea), diff --git a/src-tauri/fileio/src/ifc_export.rs b/src-tauri/fileio/src/ifc_export.rs index 86b03fd0..910b373d 100644 --- a/src-tauri/fileio/src/ifc_export.rs +++ b/src-tauri/fileio/src/ifc_export.rs @@ -61,6 +61,17 @@ // 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) +// CLASSIFICATION = 12, name, source, edition (Text, leer = keine), n_refs, (key, code, ref_name) × n_refs +// ([B5], 28.10.) Ein Klassifikationssystem (IfcClassification) mit je Code einer +// IfcClassificationReference und EINER IfcRelAssociatesClassification für alle Bauteile mit +// diesem Code. `key` = Schlüssel des Bauteils wie für seine GlobalId (`wall/`, `slab/`, +// `roof/`, `column/`, `stair/`, `fill/<Öffnungs-id>` (Tür/Fenster), `space/`, +// `storey/`); unbekannte Schlüssel werden übersprungen (kein Fehler). Gehört ans Ende +// (nach allen Bauteilen); ein System ohne auflösbares Bauteil entsteht nicht. +// ZONE = 13, key, name, long_name, n_spaces, (space_id) × n_spaces, PSETS +// IfcZone mit IfcRelAssignsToGroup der Räume (`space/`-Entitäten; unbekannte ids werden +// übersprungen, ohne Raum keine Zone). GlobalId aus `zone/`; Psets/Mengen wie bei Bauteilen. +// ATTACH = 14, key, PSETS (Psets/Mengen an ein schon geschriebenes Bauteil/Geschoss, Schlüssel wie oben) // // Danach folgen (am Pufferende) Typ-Zuordnungen, Eigenschaftssätze, räumliche Eingliederung und Fuss. // @@ -89,6 +100,9 @@ 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; +pub const REC_CLASSIFICATION: f64 = 12.0; +pub const REC_ZONE: f64 = 13.0; +pub const REC_ATTACH: f64 = 14.0; // ── IFC-GUID (Kompression nach IfcOpenShell `guid.compress`) ──────────────── @@ -785,6 +799,8 @@ struct Builder { spaces: Vec<(i64, Vec)>, column_materials: Vec<(String, String, Vec)>, + /// Bauteil-Schlüssel (wie für die GlobalId, z. B. `wall/`) → Entität; Ziel von Klassifikation/Zone/Attach. + elements: HashMap, } impl Builder { @@ -840,7 +856,7 @@ impl Builder { if pset.props.is_empty() { return; // IfcPropertySet verlangt mindestens eine Eigenschaft } - if pset.name.starts_with("Qto_") { + if pset.name.starts_with("Qto_") || pset.name.starts_with("CH_Qto_") { let quantities: Vec<(&'static str, String, f64)> = pset .props .iter() @@ -1115,6 +1131,7 @@ impl Builder { for p in psets { self.add_pset(p, entity, &guid_key); } + self.elements.insert(guid_key, entity); entity } } @@ -1126,6 +1143,9 @@ fn rec_name(code: f64) -> &'static str { c if c == REC_WALL_MESH => "WALL_MESH", c if c == REC_CEILING => "CEILING", c if c == REC_OPENING => "OPENING", + c if c == REC_CLASSIFICATION => "CLASSIFICATION", + c if c == REC_ZONE => "ZONE", + c if c == REC_ATTACH => "ATTACH", _ => "?", } } @@ -1179,6 +1199,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { styles: [0; 3], spaces: Vec::new(), column_materials: Vec::new(), + elements: HashMap::new(), }; let pname = |dflt: &str| if project_name.is_empty() { dflt.to_string() } else { project_name.clone() }; @@ -1312,6 +1333,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { fmt_real(base) ), ); + w.elements.insert(format!("storey/{id}"), entity); w.storeys.push(Storey { id, entity, placement }); storey_entities.push(entity); } @@ -1470,6 +1492,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { format!("{g},#{},$,$,#{opening_entity},#{fill_entity}", w.owner_history), ); w.add_to_containment(structure, fill_entity); + w.elements.insert(format!("fill/{opening_id}"), fill_entity); for p in &psets { w.add_pset(p, fill_entity, &format!("fill/{opening_id}")); } @@ -1557,6 +1580,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { stair }; w.add_to_containment(structure, entity); + w.elements.insert(key.clone(), entity); for p in &psets { w.add_pset(p, entity, &key); } @@ -1571,6 +1595,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { 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); + w.elements.insert(format!("extrusion/{id}"), entity); } c if c == REC_SPACE => { let structure = r.structure(n_storeys)?; @@ -1597,6 +1622,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { enum_(if external { "EXTERNAL" } else { "INTERNAL" }) ), ); + w.elements.insert(format!("space/{id}"), space); if let Some((_, v)) = w.spaces.iter_mut().find(|(s, _)| *s == structure) { v.push(space); } else { @@ -1673,6 +1699,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { 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); + w.elements.insert(format!("column/{id}"), entity); for p in &psets { w.add_pset(p, entity, &format!("column/{id}")); } @@ -1696,6 +1723,88 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { ); } } + c if c == REC_CLASSIFICATION => { + let name = r.string()?; + let source = r.string()?; + let edition = r.string()?; + let n = r.idx()?; + // Je Code in Reihenfolge des ersten Auftretens: (Name der Referenz, Bauteile). + let mut by_code: Vec<(String, String, Vec)> = Vec::new(); + for _ in 0..n { + let key = r.string()?; + let code = r.string()?; + let ref_name = r.string()?; + if code.is_empty() { + continue; // ohne Code keine Referenz + } + let Some(&entity) = w.elements.get(&key) else { continue }; + if let Some((_, _, v)) = by_code.iter_mut().find(|(c, _, _)| *c == code) { + if !v.contains(&entity) { + v.push(entity); + } + } else { + by_code.push((code, ref_name, vec![entity])); + } + } + if !by_code.is_empty() { + let opt = |s: &str| if s.is_empty() { "$".to_string() } else { ifc_string(s) }; + let system = w.add("IFCCLASSIFICATION", format!("{},{},$,{},$,$,$", opt(&source), opt(&edition), ifc_string(&name))); + for (code, ref_name, ids) in by_code { + let reference = w.add( + "IFCCLASSIFICATIONREFERENCE", + format!("$,{},{},#{system},$,$", ifc_string(&code), opt(&ref_name)), + ); + let g = w.gid(&format!("classification/{name}/{code}")); + w.add( + "IFCRELASSOCIATESCLASSIFICATION", + format!("{g},#{},$,$,{},#{reference}", w.owner_history, refs(&ids)), + ); + } + } + } + c if c == REC_ZONE => { + let key = r.string()?; + let name = r.string()?; + let long_name = r.string()?; + let n = r.idx()?; + let mut members = Vec::new(); + for _ in 0..n { + let id = r.string()?; + if let Some(&e) = w.elements.get(&format!("space/{id}")) { + if !members.contains(&e) { + members.push(e); + } + } + } + let psets = r.psets()?; + if members.is_empty() { + continue; + } + let zone_key = format!("zone/{key}"); + let g = w.gid(&zone_key); + let zone = w.add( + "IFCZONE", + format!("{g},#{},{},$,$,{}", w.owner_history, ifc_string(&name), ifc_string(&long_name)), + ); + let g = w.gid(&format!("{zone_key}/spaces")); + w.add( + "IFCRELASSIGNSTOGROUP", + format!("{g},#{},$,$,{},$,#{zone}", w.owner_history, refs(&members)), + ); + w.elements.insert(zone_key.clone(), zone); + for p in &psets { + w.add_pset(p, zone, &zone_key); + } + } + c if c == REC_ATTACH => { + let key = r.string()?; + let psets = r.psets()?; + if let Some(&entity) = w.elements.get(&key) { + for p in &psets { + w.add_pset(p, entity, &key); + } + } + } other => return Err(format!("unbekannter Datensatz {other} ({}) bei {}", rec_name(other), r.pos - 1)), } } @@ -2185,6 +2294,117 @@ mod tests { } /// Zeile der ersten Entität eines Typs. + /// Pset-Kodierung mit Einträgen `(Name, Art, Wert)`; Art 0 = IfcIdentifier (Wert = Text), 4 = Fläche. + fn put_pset(b: &mut B, name: &str, props: &[(&str, f64, Result<&str, f64>)]) { + b.f.push(1.0); + b.str(name); + b.f.push(props.len() as f64); + for (n, kind, v) in props { + b.str(n); + b.f.push(*kind); + match v { + Ok(text) => b.str(text), + Err(x) => b.f.push(*x), + } + } + } + + /// Klassifikation (eBKP-H), Zone (SIA 416) und Geschoss-Mengen: Entitäten, Zuordnung, dauerhafte GUIDs. + #[test] + fn klassifikation_zone_und_geschossmengen() { + let mut b = full_house(false); + b.n(&[REC_ZONE]); + b.str("sia416/HNF"); + b.str("HNF"); + b.str("Hauptnutzfläche"); + b.n(&[2.0]); + b.str("R1"); + b.str("R9"); // unbekannt: übersprungen + put_pset(&mut b, "CH_Zone", &[("SIA416", 0.0, Ok("HNF"))]); + // Zweiter Satz im selben PSETS-Block geht nicht (Zahl steht vorn) — Mengen separat über ATTACH. + b.n(&[REC_ATTACH]); + b.str("zone/sia416/HNF"); + put_pset(&mut b, "CH_Qto_SIA416", &[("NetFloorArea", 4.0, Err(1.9))]); + b.n(&[REC_ATTACH]); + b.str("storey/eg"); + put_pset(&mut b, "Qto_BuildingStoreyBaseQuantities", &[("GrossFloorArea", 4.0, Err(2.4)), ("NetFloorArea", 4.0, Err(1.9))]); + // Zone ohne auflösbaren Raum: nichts schreiben. + b.n(&[REC_ZONE]); + b.str("sia416/FF"); + b.str("FF"); + b.str("Funktionsfläche"); + b.n(&[1.0]); + b.str("R9"); + b.f.push(0.0); + b.n(&[REC_CLASSIFICATION]); + b.str("eBKP-H"); + b.str("CRB"); + b.str("SN 506 511:2020"); + b.n(&[6.0]); + for (k, code, name) in [ + ("wall/W1", "C", "Konstruktion Gebäude"), + ("wall/W2", "C", "Konstruktion Gebäude"), + ("fill/T1", "E", "Äussere Wandbekleidung Gebäude"), + ("roof/Ro1", "F", "Bedachung Gebäude"), + ("wall/Gibtsnicht", "C", "Konstruktion Gebäude"), + ("space/R1", "", ""), + ] { + b.str(k); + b.str(code); + b.str(name); + } + // System ohne auflösbares Bauteil: nicht schreiben. + b.n(&[REC_CLASSIFICATION]); + b.str("Leer"); + b.str(""); + b.str(""); + b.n(&[1.0]); + b.str("wall/nope"); + b.str("X"); + b.str("X"); + let ifc = build(&b).unwrap(); + check_structure(&ifc); + assert_eq!(count(&ifc, "IFCCLASSIFICATION"), 1); + // Codes C, E, F; der Eintrag ohne Code und der unbekannte Schlüssel fallen weg. + assert_eq!(count(&ifc, "IFCCLASSIFICATIONREFERENCE"), 3); + assert_eq!(count(&ifc, "IFCRELASSOCIATESCLASSIFICATION"), 3); + let sys = first_line(&ifc, "IFCCLASSIFICATION"); + assert!(sys.contains("'CRB','SN 506 511:2020',$,'eBKP-H',$,$,$"), "{sys}"); + // Erste Beziehung (Code C): beide Wände. + let rel_c = first_line(&ifc, "IFCRELASSOCIATESCLASSIFICATION"); + assert!(rel_c.contains(",(#") && rel_c.matches(",#").count() + rel_c.matches("(#").count() >= 3, "{rel_c}"); + assert_eq!(count(&ifc, "IFCZONE"), 1); + assert_eq!(count(&ifc, "IFCRELASSIGNSTOGROUP"), 1); + let zone = first_line(&ifc, "IFCZONE"); + assert!(zone.contains(",'HNF',$,$,'Hauptnutzfl\\X2\\00E4\\X0\\che'"), "{zone}"); + assert!(ifc.contains("'Qto_BuildingStoreyBaseQuantities'")); + assert!(ifc.contains("'CH_Qto_SIA416'")); + assert!(ifc.contains("'CH_Zone'")); + // Dauerhaft: gleiche Eingabe, gleiche Datei. + assert_eq!(ifc, build(&b).unwrap()); + } + + #[test] + fn klassifikation_leere_codes_wohlgeformt_und_ohne_zone_nichts() { + // Ohne die neuen Datensätze ändert sich nichts: keine Klassifikation, keine Zone. + let ifc = build(&full_house(false)).unwrap(); + assert_eq!(count(&ifc, "IFCCLASSIFICATION"), 0); + assert_eq!(count(&ifc, "IFCZONE"), 0); + // Abgeschnittene neue Datensätze: Fehler statt Panic. + for cut in 1..6 { + let mut b = full_house(false); + b.n(&[REC_CLASSIFICATION]); + b.str("a"); + b.str("b"); + b.str("c"); + b.n(&[3.0]); + let n = b.f.len(); + b.f.truncate(n - cut.min(3)); + let (f, s) = b.data(); + let _ = build_ifc(f, &s); // darf Err sein, nie panicken + } + } + fn first_line<'a>(ifc: &'a str, ty: &str) -> &'a str { let head = format!("{ty}("); ifc.lines().find(|l| l.split_once('=').is_some_and(|(_, b)| b.starts_with(&head))).unwrap_or_else(|| panic!("{ty} fehlt")) diff --git a/src-tauri/fileio/src/ifc_import.rs b/src-tauri/fileio/src/ifc_import.rs index 8a8386cd..ef3d5fc6 100644 --- a/src-tauri/fileio/src/ifc_import.rs +++ b/src-tauri/fileio/src/ifc_import.rs @@ -457,6 +457,23 @@ pub(crate) fn arc_segments(span: f64, r: f64) -> usize { // Ergebnis // --------------------------------------------------------------------------- +/// Eine Klassifikations-Zuordnung (IfcRelAssociatesClassification -> IfcClassificationReference), z. B. +/// eBKP-H `C` "Konstruktion Gebäude". +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Classification { + /// Name des Systems (IfcClassification.Name, sonst Source), z. B. `eBKP-H`. + pub system: String, + /// Code (IfcClassificationReference.Identification bzw. IFC2x3 ItemReference). + pub code: String, + pub name: Option, +} + +/// Klassifikationen als JSON für die JS-Seite (`system`, `code`, `name`). +#[cfg(feature = "web")] +pub(crate) fn classifications_json(list: &[Classification]) -> Vec { + list.iter().map(|c| serde_json::json!({ "system": c.system, "code": c.code, "name": c.name })).collect() +} + /// Ein importiertes Bauteil. #[derive(Clone, Debug, Default)] pub struct IfcProductMesh { @@ -467,6 +484,8 @@ pub struct IfcProductMesh { pub storey: Option, /// RGBA 0..1. pub color: Option<[f64; 4]>, + /// Klassifikationen des Bauteils (eBKP-H, BKP, Uniclass ...). + pub classifications: Vec, pub mesh: Mesh, } @@ -1670,6 +1689,10 @@ pub(crate) struct Rels { pub material_color: HashMap, /// Wirt → Öffnungen (IfcRelVoidsElement). pub voids: HashMap>, + /// Objekt (auch Typ) → Klassifikationsverweise (IfcRelAssociatesClassification). + pub classification_of: HashMap>, + /// Objekt → Gruppen/Zonen (IfcRelAssignsToGroup). + pub groups_of: HashMap>, } impl Rels { @@ -1693,6 +1716,45 @@ impl Rels { None } + /// Klassifikationen eines Objekts (IfcClassificationReference mit Code; ein reines IfcClassification ohne + /// Code zählt nicht), mit dem System aus `ReferencedSource` (über verschachtelte Verweise nach oben). + pub(crate) fn classifications(&self, f: &StepFile, id: u64) -> Vec { + let mut out: Vec = Vec::new(); + for &c in self.classification_of.get(&id).map(Vec::as_slice).unwrap_or(&[]) { + let Some(e) = f.get(c) else { continue }; + if e.ty != "IFCCLASSIFICATIONREFERENCE" { + continue; + } + let code = e.arg(1).and_then(|v| v.as_str()).unwrap_or("").trim().to_string(); + if code.is_empty() { + continue; + } + let name = e.arg(2).and_then(|v| v.as_str()).filter(|n| !n.is_empty()).map(str::to_string); + // System: ReferencedSource, ggf. über weitere Referenzen bis zur IfcClassification. + let mut system = String::new(); + let mut cur = e.arg(3).and_then(|v| v.as_ref_id()); + for _ in 0..8 { + let Some(se) = cur.and_then(|i| f.get(i)) else { break }; + if se.ty == "IFCCLASSIFICATION" { + system = se + .arg(3) + .and_then(|v| v.as_str()) + .filter(|n| !n.is_empty()) + .or_else(|| se.arg(0).and_then(|v| v.as_str())) + .unwrap_or("") + .to_string(); + break; + } + cur = se.arg(3).and_then(|v| v.as_ref_id()); + } + let item = Classification { system, code, name }; + if !out.contains(&item) { + out.push(item); + } + } + out + } + /// Geschoss (IfcBuildingStorey-id) eines Bauteils: Enthaltensein, sonst aufwärts über Aggregation. pub(crate) fn storey_id(&self, f: &StepFile, mut id: u64) -> Option { for _ in 0..32 { @@ -1735,6 +1797,20 @@ impl Rels { } } } + "IFCRELASSOCIATESCLASSIFICATION" => { + if let Some(c) = e.arg(5).and_then(|v| v.as_ref_id()) { + for o in refs(e.arg(4)) { + rels.classification_of.entry(o).or_default().push(c); + } + } + } + "IFCRELASSIGNSTOGROUP" => { + if let Some(g) = e.arg(6).and_then(|v| v.as_ref_id()) { + for o in refs(e.arg(4)) { + rels.groups_of.entry(o).or_default().push(g); + } + } + } "IFCRELVOIDSELEMENT" => { if let (Some(h), Some(o)) = (e.arg(4).and_then(|v| v.as_ref_id()), e.arg(5).and_then(|v| v.as_ref_id())) { rels.voids.entry(h).or_default().push(o); @@ -1877,6 +1953,7 @@ pub fn import_ifc_opts(bytes: &[u8], elements: bool) -> Result, pub layers: Vec, + /// Klassifikationen (eBKP-H, BKP ...) des Bauteils, sonst seines Typs. + pub classifications: Vec, } #[derive(Clone, Debug, Default)] @@ -557,9 +562,39 @@ impl Ctx<'_, '_> { color: color.or_else(|| mat.and_then(|m| self.rels.resolve_material_color(f, m))), type_name, layers, + classifications: { + let own = self.rels.classifications(f, id); + if own.is_empty() { + self.type_of.get(&id).map(|t| self.rels.classifications(f, *t)).unwrap_or_default() + } else { + own + } + }, } } + /// SIA-416-Kategorie eines Raums aus seinen Zonen (IfcZone über IfcRelAssignsToGroup): Eigenschaft + /// `SIA416` der Zone (Dossier-Export), sonst der Zonenname, wenn er eine Kategorie ist. + fn zone_sia(&self, id: u64) -> Option { + let f = self.r.f; + for g in self.rels.groups_of.get(&id).map(Vec::as_slice).unwrap_or(&[]) { + let Some(z) = f.get(*g) else { continue }; + if z.ty != "IFCZONE" { + continue; + } + if let Some(v) = self.sia.get(g) { + return Some(v.clone()); + } + let name = z.arg(2).and_then(|v| v.as_str()).unwrap_or("").trim().to_uppercase(); + // SIA 416 schreibt KF; unser Modell heisst KGF. + let name = if name == "KF" { "KGF".to_string() } else { name }; + if ["HNF", "NNF", "VF", "FF", "KGF", "AGF"].contains(&name.as_str()) { + return Some(name); + } + } + None + } + /// Material des Bauteils, sonst seines Typs. fn material_id(&self, id: u64) -> Option { self.rels.material_of.get(&id).or_else(|| self.type_of.get(&id).and_then(|t| self.rels.material_of.get(t))).copied() @@ -774,7 +809,7 @@ impl Ctx<'_, '_> { } let f = self.r.f; let long_name = f.get(id).and_then(|e| e.arg(7)).and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(str::to_string); - Some(Space { info: self.info(id, color), long_name, sia: self.sia.get(&id).cloned(), boundary, z0: s.z0, z1: s.z1 }) + Some(Space { info: self.info(id, color), long_name, sia: self.sia.get(&id).cloned().or_else(|| self.zone_sia(id)), boundary, z0: s.z0, z1: s.z1 }) } } @@ -1049,6 +1084,7 @@ pub(crate) fn encode(s: &Semantic) -> (serde_json::Value, Vec) { "color": i.color, "typeName": i.type_name, "layers": i.layers.iter().map(|l| json!({ "material": l.material, "thickness": l.thickness, "color": l.color })).collect::>(), + "classifications": crate::ifc_import::classifications_json(&i.classifications), }) }; let mut push = |kind: &str, i: &Info, extra: serde_json::Value, nums: Vec, data: &mut Vec| { @@ -1397,6 +1433,87 @@ ENDSEC;\nEND-ISO-10303-21;\n" assert!(r.skipped_products.is_empty(), "{:?}", r.skipped_products); } + /// Raum (3 x 2, ohne eigene SIA-Eigenschaft) mit `extra` (Zone, Klassifikation ...) dahinter. + fn space_file(extra: &str) -> String { + let body = format!( + "#501=IFCCARTESIANPOINT((0.,0.));#502=IFCCARTESIANPOINT((3.,0.));#503=IFCCARTESIANPOINT((3.,2.));#504=IFCCARTESIANPOINT((0.,2.));\ +#505=IFCPOLYLINE((#501,#502,#503,#504,#501));#506=IFCARBITRARYCLOSEDPROFILEDEF(.AREA.,$,#505);#507=IFCEXTRUDEDAREASOLID(#506,#13,#11,2.5);\ +#508=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#507));#509=IFCPRODUCTDEFINITIONSHAPE($,$,(#508));\ +#500=IFCSPACE('sp',$,'1.01',$,$,#22,#509,'Bad',.ELEMENT.,.INTERNAL.,$);\ +#520=IFCRELAGGREGATES('as',$,$,$,#23,(#500));\n{extra}" + ); + file(METRE, &body) + } + + #[test] + fn zone_name_and_zone_property_give_sia_category() { + // Zone heisst wie die Kategorie. + let (_, s) = sem(&space_file("#600=IFCZONE('z',$,'nnf',$,$,$);#601=IFCRELASSIGNSTOGROUP('ag',$,$,$,(#500),$,#600);")); + assert_eq!(s.spaces.len(), 1, "{:?}", s.kept); + assert_eq!(s.spaces[0].sia.as_deref(), Some("NNF")); + // SIA 416 schreibt KF, das Modell KGF. + let (_, s) = sem(&space_file("#600=IFCZONE('z',$,'KF',$,$,$);#601=IFCRELASSIGNSTOGROUP('ag',$,$,$,(#500),$,#600);")); + assert_eq!(s.spaces[0].sia.as_deref(), Some("KGF")); + // Eigenschaft der Zone (Dossier-Export) schlägt den Namen. + let zone = "#600=IFCZONE('z',$,'Zone 7',$,$,$);#601=IFCRELASSIGNSTOGROUP('ag',$,$,$,(#500),$,#600);\ +#602=IFCPROPERTYSINGLEVALUE('SIA416',$,IFCLABEL('VF'),$);#603=IFCPROPERTYSET('zp',$,'CH_Zone',$,(#602));\ +#604=IFCRELDEFINESBYPROPERTIES('zr',$,$,$,(#600),#603);"; + let (_, s) = sem(&space_file(zone)); + assert_eq!(s.spaces[0].sia.as_deref(), Some("VF")); + // Beliebiger Zonenname ohne Eigenschaft: keine Kategorie (kein Raten); eine IfcGroup zählt nicht. + let (_, s) = sem(&space_file("#600=IFCZONE('z',$,'Wohnung 3',$,$,$);#601=IFCRELASSIGNSTOGROUP('ag',$,$,$,(#500),$,#600);")); + assert_eq!(s.spaces[0].sia, None); + let (_, s) = sem(&space_file("#600=IFCGROUP('z',$,'HNF',$,$);#601=IFCRELASSIGNSTOGROUP('ag',$,$,$,(#500),$,#600);")); + assert_eq!(s.spaces[0].sia, None); + // Eigene Raum-Eigenschaft hat Vorrang vor der Zone. + let own = "#600=IFCZONE('z',$,'HNF',$,$,$);#601=IFCRELASSIGNSTOGROUP('ag',$,$,$,(#500),$,#600);\ +#610=IFCPROPERTYSINGLEVALUE('SIA416',$,IFCLABEL('FF'),$);#611=IFCPROPERTYSET('rp',$,'CH_Raum',$,(#610));\ +#612=IFCRELDEFINESBYPROPERTIES('rr',$,$,$,(#500),#611);"; + let (_, s) = sem(&space_file(own)); + assert_eq!(s.spaces[0].sia.as_deref(), Some("FF")); + } + + #[test] + fn classification_references_of_element_type_and_mesh() { + // Stütze (Bauteil) mit eBKP-H, Raum mit Klassifikation über verschachtelte Referenz, BKP am Typ, + // dazu ein Dach (bleibt Mesh) mit Klassifikation. + let col = rect_product(40, "IFCCOLUMN", (1.0, 1.0, 0.0), (1.0, 0.0), (0.4, 0.4), 2.75, ""); + let roof = rect_product(41, "IFCROOF", (1.0, 1.0, 3.0), (1.0, 0.0), (4.0, 3.0), 0.3, ""); + let cls = "#700=IFCCLASSIFICATION('CRB','2020',$,'eBKP-H',$,$,$);\ +#701=IFCCLASSIFICATIONREFERENCE($,'C','Konstruktion Geb\\X2\\00E4\\X0\\ude',#700,$,$);\ +#702=IFCRELASSOCIATESCLASSIFICATION('c1',$,$,$,(#40),#701);\ +#703=IFCCLASSIFICATIONREFERENCE($,'C02',$,#701,$,$);\ +#704=IFCRELASSOCIATESCLASSIFICATION('c2',$,$,$,(#41),#703);\ +#705=IFCCLASSIFICATIONREFERENCE($,' ',$,#700,$,$);\ +#706=IFCRELASSOCIATESCLASSIFICATION('c3',$,$,$,(#40),#705);\ +#707=IFCRELASSOCIATESCLASSIFICATION('c4',$,$,$,(#40),#700);"; + let (r, s) = sem(&file(METRE, &format!("{col}{roof}{cls}"))); + assert_eq!(s.columns.len(), 1, "{:?}", s.kept); + let c = &s.columns[0].info.classifications; + // Leerer Code und ein blosses IfcClassification (ohne Code) zählen nicht. + assert_eq!(c.len(), 1, "{c:?}"); + assert_eq!((c[0].system.as_str(), c[0].code.as_str(), c[0].name.as_deref()), ("eBKP-H", "C", Some("Konstruktion Gebäude"))); + // Roof bleibt Mesh, die Klassifikation kommt trotzdem mit (verschachtelte Referenz: System von oben). + let p = r.products.iter().find(|p| p.class == "IfcRoof").expect("Dach als Mesh"); + assert_eq!(p.classifications.len(), 1); + assert_eq!((p.classifications[0].system.as_str(), p.classifications[0].code.as_str(), p.classifications[0].name.as_deref()), ("eBKP-H", "C02", None)); + } + + #[test] + fn classification_from_type_and_ifc2x3_layout() { + // Klassifikation am Typ (IfcRelDefinesByType) erbt das Bauteil; Wandtyp ohne Bauteil-Eigenes. + let col = rect_product(40, "IFCCOLUMN", (1.0, 1.0, 0.0), (1.0, 0.0), (0.4, 0.4), 2.75, ""); + let cls = "#710=IFCCOLUMNTYPE('ct',$,'S30',$,$,$,$,$,$,.COLUMN.);\ +#711=IFCRELDEFINESBYTYPE('dt',$,$,$,(#40),#710);\ +#712=IFCCLASSIFICATION('CRB',$,$,'BKP',$,$,$);\ +#713=IFCCLASSIFICATIONREFERENCE($,'214',$,#712,$,$);\ +#714=IFCRELASSOCIATESCLASSIFICATION('c5',$,$,$,(#710),#713);"; + let (_, s) = sem(&file(METRE, &format!("{col}{cls}"))); + let c = &s.columns[0].info.classifications; + assert_eq!(c.len(), 1, "{c:?}"); + assert_eq!((c[0].system.as_str(), c[0].code.as_str()), ("BKP", "214")); + } + impl Profile { /// Auf 1e-9 gerundet (Vergleich in Tests). fn round(self) -> Profile { diff --git a/src/App.tsx b/src/App.tsx index 743fd375..69f95422 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -4035,8 +4035,8 @@ export default function App() { { - runExport(fmt, filename); + onSave={(fmt, filename, ifcOptions) => { + runExport(fmt, filename, ifcOptions); setExportSaveFormat(null); }} onClose={() => setExportSaveFormat(null)} diff --git a/src/cli/main.ts b/src/cli/main.ts index 9134493d..6993d474 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -9,6 +9,7 @@ // json = render2d-Szene (planToRenderScene) // dossier-cli section [--out schnitt.svg] (braucht render3d-WASM) // dossier-cli elevation [--out ansicht.svg] +// dossier-cli ifc [--ebkph] [--ebenen] (IFC mit eBKP-H-Hauptgruppen bzw. Modell-Ebenen als Klassifikation) // dossier-cli dxf [--binary]|dwg|ifc|step|obj|stl|glb|gltf|schedule|kennzahlen|sun [--level EG] [--out datei] // glb/gltf = glTF 2.0 (Y-up, Meter, Geschoss als Eltern; --flat ohne Geschoss-Knoten) // dossier-cli convert [--cmd "befehl"]… Format nach Endung: dxf/dwg/ifc/obp → obp-Import, @@ -585,7 +586,8 @@ async function execute(project: Project, file: string, command: string, rest: st } case "ifc": await loadFileio(); - out(args, exportIfcSpf(project), `${project.name || "projekt"}.ifc`); + // --ebkph: eBKP-H-Hauptgruppen je Bauteilart; --ebenen: Ebene (categoryCode) des Modells als Klassifikation. + out(args, exportIfcSpf(project, { ebkph: args.flags.has("ebkph"), layerCodes: args.flags.has("ebenen") }), `${project.name || "projekt"}.ifc`); return 0; case "obj": await loadFileio(); diff --git a/src/export/exportIfc.classification.test.ts b/src/export/exportIfc.classification.test.ts new file mode 100644 index 00000000..6dc246a2 --- /dev/null +++ b/src/export/exportIfc.classification.test.ts @@ -0,0 +1,200 @@ +// IFC für die Schweizer Praxis ([B5], 28.10.): Klassifikation (eBKP-H-Hauptgruppen, Ebene des Modells), +// SIA-416-Zonen und Geschoss-Kennwerte; Rundreise Export → Import und Prüfung mit ifcopenshell. + +import { describe, expect, it } from "vitest"; +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 } from "./exportIfc"; +import { EBKPH_GROUPS, ebkphGroup, layerClassification } from "./ifcClassification"; +import { readIfcElements } from "../io/ifcElements"; +import { classificationSuffix, ifcToImportedMeshes, readIfc } from "../io/ifcImport"; +import { sampleProject } from "../model/sampleProject"; +import type { Project, Room } from "../model/types"; + +const hasIfcOpenShell = spawnSync("python3", ["-c", "import ifcopenshell, ifcopenshell.util.classification, ifcopenshell.validate, _pytest"]).status === 0; + +const lines = (ifc: string, ty: string): string[] => ifc.split("\n").filter((l) => new RegExp(`^#\\d+=${ty}\\(`).test(l)); + +/** Demo-Haus mit Räumen in mehreren SIA-Kategorien (zwei im EG, einer im OG). */ +function houseWithRooms(): Project { + const base = sampleProject.rooms![0]; + const at = (id: string, floorId: string, siaCategory: Room["siaCategory"], dx: number): Room => ({ + ...base, + id, + floorId, + siaCategory, + name: id, + boundary: base.boundary.map((p) => ({ x: p.x + dx, y: p.y })), + }); + return { + ...sampleProject, + rooms: [base, at("R2", "eg", "HNF", 6), at("R3", "eg", "VF", 12), at("R4", "og", "NNF", 0)], + }; +} + +describe("eBKP-H-Standardzuordnung", () => { + it("nur gesicherte Hauptgruppen, Tür und Raum bleiben unklassifiziert", () => { + expect(Object.keys(EBKPH_GROUPS)).toEqual(["C", "E", "F"]); + expect(ebkphGroup("wall")).toEqual({ code: "C", name: "Konstruktion Gebäude" }); + expect(ebkphGroup("slab")?.code).toBe("C"); + expect(ebkphGroup("column")?.code).toBe("C"); + expect(ebkphGroup("stair")?.code).toBe("C"); + expect(ebkphGroup("roof")).toEqual({ code: "F", name: "Bedachung Gebäude" }); + expect(ebkphGroup("window")).toEqual({ code: "E", name: "Äussere Wandbekleidung Gebäude" }); + expect(ebkphGroup("door")).toBeNull(); + expect(ebkphGroup("space")).toBeNull(); + }); + + it("Ebene: Name aus dem Ebenenbaum, unbekannter Code bleibt Code, ohne Code nichts", () => { + expect(layerClassification(sampleProject, "20")?.code).toBe("20"); + expect(layerClassification(sampleProject, "25")?.name).toBe("Stützen"); // Unterkategorie + expect(layerClassification(sampleProject, "777")).toEqual({ code: "777", name: "777" }); + expect(layerClassification(sampleProject, undefined)).toBeNull(); + expect(layerClassification(sampleProject, " ")).toBeNull(); + }); +}); + +describe("IFC-Export: Zonen und Geschoss-Kennwerte (SIA 416)", () => { + it("je Kategorie eine IfcZone mit ihren Räumen, Kategorie und Fläche als Eigenschaft", () => { + const ifc = exportIfcSpf(houseWithRooms()); + // HNF (R1, R2), VF (R3), NNF (R4) → 3 Zonen; 4 Räume in 3 Zuordnungen. + const zones = lines(ifc, "IFCZONE"); + expect(zones).toHaveLength(3); + expect(zones.map((l) => l.match(/,'(HNF|NNF|VF)',\$,\$,/)?.[1]).sort()).toEqual(["HNF", "NNF", "VF"]); + expect(lines(ifc, "IFCRELASSIGNSTOGROUP")).toHaveLength(3); + expect(ifc).toContain("'CH_Zone'"); + expect(ifc).toContain("'CH_Qto_SIA416'"); + // Ohne Option keine Klassifikation. + expect(lines(ifc, "IFCCLASSIFICATION")).toHaveLength(0); + }); + + it("ohne Räume keine Zonen und keine Geschoss-Mengen", () => { + const ifc = exportIfcSpf({ ...sampleProject, rooms: [] }); + expect(lines(ifc, "IFCZONE")).toHaveLength(0); + expect(ifc).not.toContain("Qto_BuildingStoreyBaseQuantities"); + }); + + it("GUIDs der Zonen und der übrigen Bauteile bleiben stabil (zweimal exportiert gleich)", () => { + const a = exportIfcSpf(houseWithRooms()); + const b = exportIfcSpf(houseWithRooms()); + const guids = (t: string) => [...t.matchAll(/=IFC[A-Z]+\('([0-9A-Za-z_$]{22})'/g)].map((m) => m[1]); + // Zeitstempel im Kopf/OwnerHistory ändern sich nicht innerhalb derselben Sekunde zuverlässig → nur GUIDs. + expect(guids(a)).toEqual(guids(b)); + expect(new Set(guids(a)).size).toBe(guids(a).length); + }); +}); + +describe("IFC-Export: Klassifikation", () => { + it("eBKP-H: ein System, je Hauptgruppe eine Referenz und eine Beziehung; Türen und Räume ohne", () => { + const ifc = exportIfcSpf(houseWithRooms(), { ebkph: true }); + const sys = lines(ifc, "IFCCLASSIFICATION"); + expect(sys).toHaveLength(1); + expect(sys[0]).toContain("'SN 506 511:2020'"); + expect(sys[0]).toContain("'eBKP-H'"); + const refs = lines(ifc, "IFCCLASSIFICATIONREFERENCE"); + // C (Wand, Decke, Treppe), F (Dach), E (Fenster) — Stützen hat das Demo-Haus nicht. + expect(refs.map((l) => l.match(/^#\d+=IFCCLASSIFICATIONREFERENCE\(\$,'(\w)'/)![1]).sort()).toEqual(["C", "E", "F"]); + expect(lines(ifc, "IFCRELASSOCIATESCLASSIFICATION")).toHaveLength(3); + }); + + it("Ebene des Modells als eigenes System, beide Systeme zusammen möglich", () => { + const ifc = exportIfcSpf(houseWithRooms(), { layerCodes: true, ebkph: true }); + expect(lines(ifc, "IFCCLASSIFICATION")).toHaveLength(2); + expect(ifc).toContain("'Dossier-Ebenen'"); + const codes = lines(ifc, "IFCCLASSIFICATIONREFERENCE").map((l) => l.match(/^#\d+=IFCCLASSIFICATIONREFERENCE\(\$,'(\w+)'/)![1]); + // Wände 20, Decke 30, Dach 31, Treppe 40, Türen/Fenster 21, Räume 60 + eBKP-H C, E, F. + for (const c of ["20", "21", "30", "31", "40", "60", "C", "E", "F"]) expect(codes, c).toContain(c); + }); + + it("ohne Bauteile (leeres Projekt) kein leeres System", () => { + const ifc = exportIfcSpf({ ...sampleProject, walls: [], openings: [], ceilings: [], roofs: [], stairs: [], rooms: [], columns: [], extrudedSolids: [] }, { ebkph: true, layerCodes: true }); + expect(lines(ifc, "IFCCLASSIFICATION")).toHaveLength(0); + }); +}); + +describe("Rundreise Export → Import", () => { + it("Klassifikation kommt an Bauteilen und am Mesh-Rest wieder an", async () => { + const ifc = exportIfcSpf(houseWithRooms(), { ebkph: true, layerCodes: true }); + const bytes = new TextEncoder().encode(ifc); + const { products, elements } = await readIfcElements(bytes); + const wall = elements.walls[0]; + expect(wall.classifications?.map((c) => `${c.system}:${c.code}`).sort()).toEqual(["Dossier-Ebenen:20", "eBKP-H:C"]); + expect(wall.classifications?.find((c) => c.system === "eBKP-H")?.name).toBe("Konstruktion Gebäude"); + const window = elements.openings.find((o) => o.kind === "window")!; + expect(window.classifications?.map((c) => `${c.system}:${c.code}`).sort()).toEqual(["Dossier-Ebenen:21", "eBKP-H:E"]); + const door = elements.openings.find((o) => o.kind === "door")!; + expect(door.classifications?.map((c) => c.system)).toEqual(["Dossier-Ebenen"]); + // Dach bleibt Mesh, trägt aber seine Klassifikation. + const roof = products.find((p) => p.ifcClass === "IfcRoof")!; + expect(roof.classifications?.map((c) => c.code).sort()).toEqual(["31", "F"]); + // Räume: Kategorie bleibt (auch über die Zone). + expect(elements.spaces.map((s) => s.sia).sort()).toEqual(["HNF", "HNF", "NNF", "VF"]); + }); + + it("Mesh-Import: Klassifikation im Namen des Kontext-Objekts", async () => { + const ifc = exportIfcSpf(sampleProject, { ebkph: true }); + const { products } = await readIfc(new TextEncoder().encode(ifc)); + expect(products.find((p) => p.ifcClass === "IfcRoof")?.classifications?.[0]).toMatchObject({ system: "eBKP-H", code: "F" }); + const roof = ifcToImportedMeshes(products, "haus.ifc", { group: "product" }).find((m) => m.layer === "IfcRoof")!; + expect(roof.name).toMatch(/ \[eBKP-H F\]$/); + expect(classificationSuffix(undefined)).toBe(""); + expect(classificationSuffix([{ system: "", code: "214", name: null }])).toBe(" [214]"); + }); +}); + +describe.skipIf(!hasIfcOpenShell)("ifcopenshell", () => { + const PY = ` +import json, sys +import ifcopenshell, ifcopenshell.util.classification as uc, ifcopenshell.util.element as ue +m = ifcopenshell.open(sys.argv[1]) +out = {"classes": {}, "zones": {}, "storeys": {}} +for e in m.by_type("IfcProduct"): + refs = uc.get_references(e) + if refs: + out["classes"].setdefault(e.is_a(), []).extend(sorted(f"{uc.get_classification(r).Name}:{r.Identification}" for r in refs)) +for z in m.by_type("IfcZone"): + members = [a.is_a() for rel in z.IsGroupedBy for a in rel.RelatedObjects] + psets = ue.get_psets(z) + out["zones"][z.Name] = {"members": members, "sia": psets["CH_Zone"]["SIA416"], "area": psets["CH_Qto_SIA416"]["NetFloorArea"]} +for s in m.by_type("IfcBuildingStorey"): + out["storeys"][s.Name] = ue.get_psets(s, qtos_only=True) +print(json.dumps(out)) +`; + const run = (name: string, ifc: string) => { + const dir = mkdtempSync(join(tmpdir(), "dossier-ifc-cls-")); + const file = join(dir, `${name}.ifc`); + writeFileSync(file, ifc); + const r = spawnSync("python3", ["-c", PY, file], { encoding: "utf8", timeout: 120_000 }); + expect(r.status, r.stderr).toBe(0); + const v = spawnSync("python3", ["scripts/validate-ifc.py", file], { encoding: "utf8", timeout: 180_000 }); + return { read: JSON.parse(r.stdout), valid: { status: v.status, out: `${v.stdout}${v.stderr}` } }; + }; + + it("liest Klassifikation, Zonen und Geschoss-Mengen; 0 Befunde", () => { + const { read, valid } = run("klassifiziert", exportIfcSpf(houseWithRooms(), { ebkph: true, layerCodes: true })); + expect(valid.out).toMatch(/ 0 Befunde/); + expect(valid.status).toBe(0); + expect(read.classes.IfcWall).toContain("eBKP-H:C"); + expect(read.classes.IfcWall).toContain("Dossier-Ebenen:20"); + expect(read.classes.IfcRoof).toContain("eBKP-H:F"); + expect(read.classes.IfcWindow).toContain("eBKP-H:E"); + expect(read.classes.IfcDoor).not.toContain("eBKP-H:E"); + expect(Object.keys(read.zones).sort()).toEqual(["HNF", "NNF", "VF"]); + expect(read.zones.HNF.members).toEqual(["IfcSpace", "IfcSpace"]); + expect(read.zones.HNF.sia).toBe("HNF"); + // Zwei gleich grosse Räume: doppelte Nettofläche des Einzelraums. + expect(read.zones.HNF.area).toBeCloseTo(read.zones.VF.area * 2, 6); + const eg = read.storeys["Erdgeschoss"] ?? Object.values(read.storeys)[0]; + expect(eg.Qto_BuildingStoreyBaseQuantities.GrossFloorArea).toBeGreaterThan(0); + expect(eg.CH_Qto_SIA416.GF).toBeCloseTo(eg.Qto_BuildingStoreyBaseQuantities.GrossFloorArea, 9); + }, 300_000); + + it("Standardexport (ohne Option) mit Zonen: 0 Befunde", () => { + const { valid } = run("standard", exportIfcSpf(houseWithRooms())); + expect(valid.out).toMatch(/ 0 Befunde/); + expect(valid.status).toBe(0); + }, 300_000); +}); diff --git a/src/export/exportIfc.ts b/src/export/exportIfc.ts index 46598b7f..808ea797 100644 --- a/src/export/exportIfc.ts +++ b/src/export/exportIfc.ts @@ -66,6 +66,18 @@ // IsExternal beim Dach und bei SIA-416-AGF-Räumen, Glasanteil der Glastür). Kein U-Wert, // keine Tragfunktion: dafür hat das Modell keine Felder. // +// Schweizer Praxis ([B5], 28.10.): +// • Zonen: je vorkommender SIA-416-Kategorie (HNF, NNF, VF, FF, KGF, AGF) eine IfcZone mit +// IfcRelAssignsToGroup der IfcSpaces, Eigenschaft `CH_Zone.SIA416` und Summe der Nettoflächen +// (`CH_Qto_SIA416.NetFloorArea`). Immer dabei, sobald Räume da sind. +// • Geschoss-Kennwerte: je Geschoss mit Räumen `Qto_BuildingStoreyBaseQuantities` (GrossFloorArea = GF, +// NetFloorArea = NGF nach SIA 416) und `CH_Qto_SIA416` mit allen Blatt-/Summenflächen (HNF … GF). +// • Klassifikation (Option, `ifcClassification.ts`): eBKP-H-Hauptgruppen je Bauteilart und/oder die +// Ebene des Modells als System „Dossier-Ebenen" — IfcClassification + IfcClassificationReference + +// IfcRelAssociatesClassification. +// • Achsraster: nicht exportiert — das Modell führt keine Raster-Ressource (nur die Regel „grid" der +// parametrischen Wände mit festem Abstand). +// // GUIDs ([B5]/[10]): deterministisch aus `//[/]` über einen // 128-Bit-Hash + Standard-IFC-GUID-Kompression (Zeichensatz 0-9,A-Z,a-z,_,$) — zweimal // exportieren gibt dieselben GlobalIds, BIM-Koordination (Solibri, BIMcollab) erkennt die @@ -108,6 +120,18 @@ import { type Qty, } from "./ifcQuantities"; import { roofBaseElevation, roofGeometry } from "../geometry/roof"; +import { SIA_CATEGORIES, balance, siaLabel, type SiaCategory } from "../geometry/roomArea"; +import { + EBKPH_SYSTEM, + LAYER_SYSTEM, + ebkphGroup, + layerClassification, + type ClassificationSystem, + type ClassifiedKind, + type IfcExportOptions, +} from "./ifcClassification"; + +export type { IfcExportOptions } from "./ifcClassification"; /** Deterministische 22-stellige IFC-GUID aus einem Namen (Rust, `ifc_export.rs::ifc_guid`). */ export function ifcGuid(name: string): string { @@ -133,6 +157,9 @@ const REC_END_SPACES = 8; const REC_ROOF = 9; const REC_COLUMN = 10; const REC_END_COLUMNS = 11; +const REC_CLASSIFICATION = 12; +const REC_ZONE = 13; +const REC_ATTACH = 14; /** Typart in der flachen Kodierung (0 Wand, 1 Decke, 2 Dach). */ type TypeKind = 0 | 1 | 2; @@ -402,6 +429,26 @@ class FlatIfc { this.nums.push(REC_END_COLUMNS); } + /** Zone (IfcZone) mit den Räumen `spaceIds`; `key` ergibt die dauerhafte GUID. */ + zone(key: string, name: string, longName: string, spaceIds: readonly string[], psets: PsetIn[]): void { + this.nums.push(REC_ZONE, this.str(key), this.str(name), this.str(longName), spaceIds.length); + for (const id of spaceIds) this.nums.push(this.str(id)); + this.psets(psets); + } + + /** Psets/Mengen an ein geschriebenes Bauteil (Schlüssel wie für seine GUID, z. B. `storey/`). */ + attach(key: string, psets: PsetIn[]): void { + this.nums.push(REC_ATTACH, this.str(key)); + this.psets(psets); + } + + /** Ein Klassifikationssystem mit Zuordnungen (Bauteil-Schlüssel → Code, Name der Referenz). */ + classification(system: ClassificationSystem, refs: readonly { key: string; code: string; name: string }[]): void { + if (refs.length === 0) return; + this.nums.push(REC_CLASSIFICATION, this.str(system.name), this.str(system.source), this.str(system.edition), refs.length); + for (const r of refs) this.nums.push(this.str(r.key), this.str(r.code), this.str(r.name)); + } + /** Argumente für die Rust-Bindung: `[Zahlenpuffer, Zeichenketten durch \0 getrennt]`. */ args(): [Float64Array, string] { return [new Float64Array(this.nums), this.strings.join("\0")]; @@ -569,7 +616,7 @@ function qto(name: string, quantities: readonly Qty[]): PsetIn[] { * 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 { +export function exportIfcSpf(projectIn: Project, options: IfcExportOptions = {}): string { // Georeferenziert exportieren: ist ein Standort-Bezug gesetzt (geoAnchor), // wird die gesamte Geometrie auf die ECHTEN LV95-Weltkoordinaten verschoben, // damit die IFC-Datei in anderer Software lagerichtig sitzt — auch wenn das @@ -603,6 +650,13 @@ export function exportIfcSpf(projectIn: Project): string { storeys: floors.map((f, i) => ({ id: f.id, name: f.name, base: storeyBase[i] })), }); + // Klassifikation: je Bauteil, das geschrieben wird, Schlüssel (wie für die GUID), Art und Ebene sammeln; + // Rust überspringt Schlüssel ohne geschriebenes Bauteil (degenerierte Wand, Öffnung ohne Körper …). + const classified: { key: string; kind: ClassifiedKind; categoryCode: string | undefined }[] = []; + const classify = (key: string, kind: ClassifiedKind, categoryCode: string | undefined): void => { + classified.push({ key, kind, categoryCode }); + }; + const componentName = (componentId: string): string => project.components.find((c) => c.id === componentId)?.name ?? componentId; const typeRef = ( @@ -687,6 +741,7 @@ export function exportIfcSpf(projectIn: Project): string { if (bands.length === 0) continue; // degenerierte Wand / keine Geometrie const cutouts = cutoutsOf(wall); cutoutsByWallId.set(wall.id, cutouts); + classify(`wall/${wall.id}`, "wall", wall.categoryCode); if (!bandsMatchOpenings(wall, bands, cutouts)) { meshWalls.push({ wall, bands: bandsByWallId.get(wall.id)! }); continue; @@ -761,6 +816,7 @@ export function exportIfcSpf(projectIn: Project): string { if (ceiling.outline.length < 3) continue; const { zBottom, zTop } = ceilingVerticalExtent(project, ceiling); const structure = structureOf(ceiling.floorId); + classify(`slab/${ceiling.id}`, "slab", ceiling.categoryCode); let name: string = ceiling.id; let ty: TypeRefIn | null = null; const psets: PsetIn[] = []; @@ -792,6 +848,7 @@ export function exportIfcSpf(projectIn: Project): string { const depth = c.zTop - c.zBottom; if (!(depth > 1e-6)) continue; const isDoor = opening.kind === "door"; + classify(`fill/${opening.id}`, isDoor ? "door" : "window", opening.categoryCode); const props: PropIn[] = []; let psetName: string; if (isDoor) { @@ -829,6 +886,7 @@ export function exportIfcSpf(projectIn: Project): string { if (footprint.length < 3) continue; const { zBottom, zTop } = stairVerticalExtent(project, stair); const structure = structureOf(stair.floorId); + classify(`stair/${stair.id}`, "stair", stair.categoryCode); 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, stairParts(project, stair, baseOf(structure))); } @@ -848,6 +906,7 @@ 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 roomAreas: { id: string; floorId: string; category: SiaCategory; area: number }[] = []; for (const room of project.rooms ?? []) { if (room.boundary.length < 3) continue; const structure = structureOf(room.floorId); @@ -855,6 +914,8 @@ export function exportIfcSpf(projectIn: Project): string { const height = floor?.floorHeight && floor.floorHeight > 0 ? floor.floorHeight : 2.5; const external = room.siaCategory === "AGF"; const area = evaluateRoom(room.boundary, room.siaCategory); + roomAreas.push({ id: room.id, floorId: room.floorId, category: room.siaCategory, area: area.netArea }); + classify(`space/${room.id}`, "space", room.categoryCode); const common: PropIn[] = []; if (room.stamp?.number) common.push(identifier("Reference", room.stamp.number)); common.push({ name: "IsExternal", bool: external }); @@ -874,6 +935,41 @@ export function exportIfcSpf(projectIn: Project): string { } flat.endSpaces(); + // SIA 416 ([70], [B5]): je vorkommender Kategorie eine IfcZone mit den Räumen. Kategorie als Eigenschaft + // (`CH_Zone.SIA416`, die der Import wieder liest), Summe der Nettoflächen als Menge. + for (const cat of SIA_CATEGORIES) { + const members = roomAreas.filter((r) => r.category === cat); + if (members.length === 0) continue; + const net = members.reduce((a, r) => a + r.area, 0); + flat.zone( + `sia416/${cat}`, + cat, + siaLabel(cat), + members.map((r) => r.id), + [ + { name: "CH_Zone", props: [identifier("SIA416", cat)] }, + { name: "CH_Qto_SIA416", props: [{ name: "NetFloorArea", area: Math.max(0, net) }] }, + ], + ); + } + // Geschoss-Kennwerte: GF/NGF als Basismenge des IfcBuildingStorey, alle SIA-416-Flächen als CH_Qto_SIA416. + for (const floor of floors) { + const rooms = roomAreas.filter((r) => r.floorId === floor.id); + if (rooms.length === 0) continue; + const bal = balance(rooms.map((r) => ({ category: r.category, area: r.area }))); + const keys = ["HNF", "NNF", "NF", "VF", "FF", "NGF", "KGF", "AGF", "GF"] as const; + flat.attach(`storey/${floor.id}`, [ + { + name: "Qto_BuildingStoreyBaseQuantities", + props: [ + { name: "GrossFloorArea", area: Math.max(0, bal.byKey.GF) }, + { name: "NetFloorArea", area: Math.max(0, bal.byKey.NGF) }, + ], + }, + { name: "CH_Qto_SIA416", props: keys.map((k): PropIn => ({ name: k, area: Math.max(0, bal.byKey[k]) })) }, + ]); + } + // ── 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 @@ -881,6 +977,7 @@ export function exportIfcSpf(projectIn: Project): string { // positiv ist — nur dann ist das Face-Set als geschlossen markiert. for (const roof of project.roofs ?? []) { const structure = structureOf(roof.floorId); + classify(`roof/${roof.id}`, "roof", roof.categoryCode); const positions: number[] = []; const indices: number[] = []; for (const mesh of emitRoofs({ ...project, roofs: [roof] })) { @@ -928,6 +1025,7 @@ export function exportIfcSpf(projectIn: Project): string { const { zBottom, zTop } = columnVerticalExtent(project, col); if (!(zTop > zBottom)) continue; const structure = structureOf(col.floorId); + classify(`column/${col.id}`, "column", col.categoryCode); const label = columnLabel(col); flat.column({ structure, @@ -942,6 +1040,26 @@ export function exportIfcSpf(projectIn: Project): string { } flat.endColumns(); + // ── Klassifikation (Optionen), am Ende: alle Bauteile sind geschrieben ────────────── + if (options.ebkph) { + flat.classification( + EBKPH_SYSTEM, + classified.flatMap((c) => { + const g = ebkphGroup(c.kind); + return g ? [{ key: c.key, code: g.code, name: g.name }] : []; + }), + ); + } + if (options.layerCodes) { + flat.classification( + LAYER_SYSTEM, + classified.flatMap((c) => { + const l = layerClassification(project, c.categoryCode); + return l ? [{ key: c.key, code: l.code, name: l.name }] : []; + }), + ); + } + const m = fileio(); const [buf, strings] = flat.args(); const text = m.export_ifc_flat(buf, strings); diff --git a/src/export/ifcClassification.ts b/src/export/ifcClassification.ts new file mode 100644 index 00000000..7e979ee2 --- /dev/null +++ b/src/export/ifcClassification.ts @@ -0,0 +1,99 @@ +// Klassifikation im IFC-Export ([B5], 28.10.): welche Klassifikationssysteme das Modell hergibt und die +// Standard-Zuordnung nach eBKP-H. Reine Tabellen/Funktionen, kein IFC-Schreiben (das macht Rust über +// den Datensatz CLASSIFICATION, `ifc_export.rs`). +// +// Was das Modell führt: KEINEN eBKP-H-/BKP-Code. `categoryCode` an Bauteilen ist die Grafik-Ebene +// („20" Wände, „30" Decken …, `LayerCategory`), kein Kostenschlüssel. Daher zwei getrennte Wege: +// • `layerCodes` — die Ebene des Modells als eigenes System „Dossier-Ebenen" (Code = `categoryCode`, +// Name = Ebenenname). Stammt aus dem Modell, behauptet keinen Standard. +// • `ebkph` — Standardzuordnung je Bauteilart auf eBKP-H-HAUPTGRUPPEN (siehe `EBKPH_GROUPS`). +// +// Quelle eBKP-H: CRB, „eBKP-H Elementbasierter Baukostenplan Hochbau", SN 506 511 (Ausgabe 2020). +// Gesichert sind nur die Hauptgruppen-Buchstaben und ihre Namen (A Grundstück, B Vorbereitung, +// C Konstruktion Gebäude, D Technik Gebäude, E Äussere Wandbekleidung Gebäude, F Bedachung Gebäude, +// G Ausbau Gebäude, H Nutzungsspezifische Anlagen Gebäude, I Umgebung Gebäude, J Ausstattung, +// V Planungsleistungen, W Nebenkosten, Y Reserve, Z Mehrwertsteuer). Keine Untergruppen (C01 …): +// die hängen von Konstruktionsart und Lage ab, die das Modell nicht trägt. +// +// Die Zuordnung ist deshalb bewusst grob und ein VORSCHLAG für die Kostenplanung, kein Ersatz für +// die Einordnung durch die Kostenplanerin: +// Wand → C (Wandkonstruktion; Aussen-/Innenbekleidung E/G und nichttragende Innenwände +// unterscheidet das Modell nicht — dafür fehlt ein Feld am Wandtyp) +// Decke → C (Deckenkonstruktion; Bodenbeläge/Unterdecken wären G) +// Stütze → C +// Treppe → C (Treppenkonstruktion; Belag/Geländer wären G) +// Dach → F (Dachaufbau mit Eindeckung/Abdichtung; die reine Tragkonstruktion wäre C) +// Fenster → E (Fenster der Gebäudehülle) +// Tür → keine (Aussentür E, Innentür G — nicht unterscheidbar, daher nicht geraten) +// Raum → keine (Räume sind Flächen, kein Bauteil; sie haben die SIA-416-Zonen) + +import type { LayerCategory, Project } from "../model/types"; + +/** Optionen der Klassifikation im IFC-Export. */ +export interface IfcExportOptions { + /** eBKP-H-Hauptgruppen je Bauteilart (Standardzuordnung, s. Dateikopf). */ + ebkph?: boolean; + /** `categoryCode` (Ebene) des Modells als System „Dossier-Ebenen". */ + layerCodes?: boolean; +} + +/** Bauteilarten, die klassifiziert werden können. */ +export type ClassifiedKind = "wall" | "slab" | "roof" | "column" | "stair" | "window" | "door" | "space"; + +/** Ein Klassifikationssystem für IfcClassification. */ +export interface ClassificationSystem { + name: string; + source: string; + /** Ausgabe; leer = keine Angabe. */ + edition: string; +} + +export const EBKPH_SYSTEM: ClassificationSystem = { + name: "eBKP-H", + source: "CRB Schweizerische Zentralstelle für Baurationalisierung", + edition: "SN 506 511:2020", +}; + +export const LAYER_SYSTEM: ClassificationSystem = { + name: "Dossier-Ebenen", + source: "Dossier", + edition: "", +}; + +/** Gesicherte eBKP-H-Hauptgruppen (nur die hier verwendeten). */ +export const EBKPH_GROUPS = { + C: "Konstruktion Gebäude", + E: "Äussere Wandbekleidung Gebäude", + F: "Bedachung Gebäude", +} as const; + +const EBKPH_BY_KIND: Partial> = { + wall: "C", + slab: "C", + column: "C", + stair: "C", + roof: "F", + window: "E", +}; + +/** eBKP-H-Hauptgruppe zur Bauteilart, oder `null` (Tür, Raum: nicht eindeutig). */ +export function ebkphGroup(kind: ClassifiedKind): { code: string; name: string } | null { + const code = EBKPH_BY_KIND[kind]; + return code ? { code, name: EBKPH_GROUPS[code] } : null; +} + +function findLayer(list: readonly LayerCategory[], code: string): LayerCategory | undefined { + for (const c of list) { + if (c.code === code) return c; + const sub = c.children ? findLayer(c.children, code) : undefined; + if (sub) return sub; + } + return undefined; +} + +/** Ebene (Code + Name) eines Bauteils; ohne Code `null`, ohne bekannte Ebene der Code als Name. */ +export function layerClassification(project: Project, categoryCode: string | undefined): { code: string; name: string } | null { + const code = categoryCode?.trim(); + if (!code) return null; + return { code, name: findLayer(project.layers, code)?.name ?? code }; +} diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 1f476906..cb6e20b2 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1774,6 +1774,11 @@ export const de = { "exportSave.format": "Format", "exportSave.filename": "Dateiname", "exportSave.locationNote": "Wird in den Standard-Download-Ordner gespeichert.", + "exportSave.ifc.ebkph": "eBKP-H-Klassifikation hinzufügen", + "exportSave.ifc.ebkphHint": "Hauptgruppe je Bauteilart: Wand, Decke, Stütze, Treppe = C, Dach = F, Fenster = E; Türen bleiben ohne. Vorschlag für die Kostenplanung (CRB, eBKP-H, SN 506 511) — Aussen-/Innenwände und Untergruppen unterscheidet das Modell nicht.", + "exportSave.ifc.layers": "Ebene (Kategorie-Code) des Modells als Klassifikation", + "exportSave.ifc.layersHint": "System «Dossier-Ebenen»: Code und Name der Grafik-Ebene jedes Bauteils (kein Baukostenplan).", + "exportSave.ifc.zonesNote": "SIA-416-Zonen (HNF, NNF …) und Geschossflächen sind immer enthalten, sobald Räume vorhanden sind.", "exportSave.fmt.csv": "Bauteilliste (CSV)", "exportSave.fmt.ifc": "IFC (BIM)", "exportSave.fmt.obj": "OBJ (3D-Mesh)", @@ -1842,6 +1847,7 @@ export const de = { "ifc.import.truncated": "abgebrochen: zu viele Dreiecke", "ifc.import.elements": "{schema} importiert: {walls} Wände, {openings} Türen/Fenster, {ceilings} Decken, {columns} Stützen, {rooms} Räume, {floors} neue Geschosse; {meshes} Bauteile als Kontext-Meshes", "ifc.import.kept": "{n} Wände/Decken/Stützen/Räume nicht sicher abbildbar, als Mesh übernommen", + "ifc.import.classified": "{n} Bauteile mit Klassifikation (eBKP-H …); bei Kontext-Meshes im Namen vermerkt", "ifc.importDialog.title": "IFC importieren", "ifc.importDialog.asMesh": "Als Kontext-Meshes (Standard)", "ifc.importDialog.asMeshHint": "Jedes Bauteil als nicht bearbeitbares Mesh der Kontext-Schicht, wie in der Datei.", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index e0456911..739c9db7 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1801,6 +1801,7 @@ export const en: Record = { "ifc.import.truncated": "aborted: too many triangles", "ifc.import.elements": "{schema} imported: {walls} walls, {openings} doors/windows, {ceilings} slabs, {columns} columns, {rooms} rooms, {floors} new storeys; {meshes} elements as context meshes", "ifc.import.kept": "{n} walls/slabs/columns/rooms not safely mappable, kept as mesh", + "ifc.import.classified": "{n} elements with a classification (eBKP-H …); noted in the name of context meshes", "ifc.importDialog.title": "Import IFC", "ifc.importDialog.asMesh": "As context meshes (default)", "ifc.importDialog.asMeshHint": "Every element as a non-editable mesh on the context layer, as in the file.", @@ -1935,6 +1936,11 @@ export const en: Record = { "exportSave.format": "Format", "exportSave.filename": "File name", "exportSave.locationNote": "Saved to the default downloads folder.", + "exportSave.ifc.ebkph": "Add eBKP-H classification", + "exportSave.ifc.ebkphHint": "Main group per element type: wall, slab, column, stair = C, roof = F, window = E; doors stay unclassified. A suggestion for cost planning (CRB, eBKP-H, SN 506 511) — the model does not tell exterior from interior walls or know sub-groups.", + "exportSave.ifc.layers": "Model layer (category code) as classification", + "exportSave.ifc.layersHint": "System “Dossier-Ebenen”: code and name of each element's graphic layer (not a cost plan).", + "exportSave.ifc.zonesNote": "SIA 416 zones (HNF, NNF …) and storey areas are always included when rooms exist.", "exportSave.fmt.csv": "Component schedule (CSV)", "exportSave.fmt.ifc": "IFC (BIM)", "exportSave.fmt.obj": "OBJ (3D mesh)", diff --git a/src/io/ifcElements.ts b/src/io/ifcElements.ts index c09999a9..61a816cc 100644 --- a/src/io/ifcElements.ts +++ b/src/io/ifcElements.ts @@ -31,6 +31,7 @@ import { ifcColorHex, ifcToImportedMeshes, readIfcFlat, + type IfcClassificationRef, type IfcFlat, type IfcImportReport, type IfcProduct, @@ -54,6 +55,8 @@ interface IfcInfo { color: [number, number, number, number] | null; typeName: string | null; layers: IfcMatLayer[]; + /** Klassifikationen des Bauteils bzw. seines Typs (eBKP-H, BKP …); fehlt in älteren Rohdaten. */ + classifications?: IfcClassificationRef[]; } export interface IfcStoreyData { @@ -153,6 +156,7 @@ export function decodeIfcElements(flat: IfcFlat): IfcElementsData | null { color: e.color, typeName: e.typeName, layers: e.layers ?? [], + ...(e.classifications?.length ? { classifications: e.classifications } : {}), }; const rings = (start: number, count: number): { rings: Vec2[][]; ok: boolean } => { const res: Vec2[][] = []; @@ -249,6 +253,12 @@ export interface IfcElementsSummary { components: number; /** Bauteile als Kontext-Mesh. */ meshes: number; + /** + * Übernommene Bauteile und Meshes mit Klassifikation (eBKP-H …). Das Modell hat an Wand/Decke/Stütze/ + * Raum kein Klassifikationsfeld: nur die Namen der Kontext-Meshes tragen sie (`[eBKP-H C]`), sonst wird + * sie gezählt und gemeldet. + */ + classified: number; /** Davon Kandidaten, die nicht sicher abbildbar waren. */ kept: number; } @@ -290,7 +300,7 @@ export function ifcElementsToProject( const stamp = Date.now().toString(36); const newId = (kind: string) => `ifc-${kind}-${stamp}-${counter++}`; const summary: IfcElementsSummary = { - walls: 0, openings: 0, ceilings: 0, columns: 0, rooms: 0, floors: 0, wallTypes: 0, ceilingTypes: 0, components: 0, meshes: 0, + walls: 0, openings: 0, ceilings: 0, columns: 0, rooms: 0, floors: 0, wallTypes: 0, ceilingTypes: 0, components: 0, meshes: 0, classified: 0, kept: Object.values(elements.kept).reduce((s, n) => s + n, 0), }; @@ -544,6 +554,10 @@ export function ifcElementsToProject( summary.columns = columns.length; summary.rooms = rooms.length; summary.meshes = meshes.length; + const withClass = (l: readonly IfcInfo[]) => l.filter((e) => e.classifications?.length).length; + summary.classified = + withClass(elements.walls) + withClass(elements.openings.filter((o) => o.kind !== "hole")) + withClass(elements.slabs) + withClass(elements.columns) + withClass(elements.spaces) + + products.filter((p) => p.classifications?.length).length; const next: Project = { ...project, @@ -570,7 +584,7 @@ export function ifcElementsToProject( export function formatIfcElementsSummary( s: IfcElementsSummary, r: IfcImportReport, - tr: (key: "ifc.import.elements" | "ifc.import.kept", vars?: Record) => string, + tr: (key: "ifc.import.elements" | "ifc.import.kept" | "ifc.import.classified", vars?: Record) => string, ): string { const parts = [ tr("ifc.import.elements", { @@ -585,5 +599,6 @@ export function formatIfcElementsSummary( }), ]; if (s.kept) parts.push(tr("ifc.import.kept", { n: s.kept })); + if (s.classified) parts.push(tr("ifc.import.classified", { n: s.classified })); return parts.join(" · "); } diff --git a/src/io/ifcImport.ts b/src/io/ifcImport.ts index 0106aacc..c571bce8 100644 --- a/src/io/ifcImport.ts +++ b/src/io/ifcImport.ts @@ -21,6 +21,14 @@ import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories"; import type { ImportedMesh } from "../model/types"; import { rgbToHex } from "../model/color"; +/** Klassifikation eines Bauteils (IfcClassificationReference), z. B. eBKP-H `C`. */ +export interface IfcClassificationRef { + /** Name des Systems (IfcClassification), z. B. `eBKP-H`; leer, wenn die Datei keines nennt. */ + system: string; + code: string; + name: string | null; +} + /** Ein gelesenes IFC-Bauteil. */ export interface IfcProduct { globalId: string; @@ -30,6 +38,8 @@ export interface IfcProduct { storey: string | null; /** RGBA 0..1 aus IfcStyledItem/Material, falls vorhanden. */ color: [number, number, number, number] | null; + /** Klassifikationen (eBKP-H, BKP …); fehlt bei Quellen ohne. */ + classifications?: IfcClassificationRef[]; /** x,y,z in Metern (Z = Höhe). */ positions: Float64Array; indices: Uint32Array; @@ -60,6 +70,7 @@ interface RawProduct { name: string | null; storey: string | null; color: [number, number, number, number] | null; + classifications?: IfcClassificationRef[]; positionCount: number; indexCount: number; } @@ -143,6 +154,7 @@ export function decodeIfc(flat: IfcFlat): { products: IfcProduct[]; report: IfcI name: p.name, storey: p.storey, color: p.color, + ...(p.classifications?.length ? { classifications: p.classifications } : {}), positions: flat.positions.subarray(po, po + p.positionCount), indices: flat.indices.subarray(io, io + p.indexCount), }); @@ -212,6 +224,17 @@ export function geoShift( return nearOrigin ? [-origin.e, -origin.n] : [0, 0]; } +/** + * Klassifikation als Namenszusatz des Kontext-Objekts (` [eBKP-H C]`): das Modell hat für Kontext-Meshes + * kein eigenes Klassifikationsfeld, der Name ist das einzige freie Feld (im Kontext-Panel sichtbar). + * Nur die erste Klassifikation; ohne leer. + */ +export function classificationSuffix(list: readonly IfcClassificationRef[] | undefined): string { + const c = list?.[0]; + if (!c) return ""; + return ` [${[c.system, c.code].filter(Boolean).join(" ")}]`; +} + /** Bauteile → Kontext-Meshes (Kategorie „Situation" wie STEP; `layer` = IFC-Klasse). */ export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, opts: IfcToMeshesOptions = {}): ImportedMesh[] { const base = fileName.replace(/\.[^.]+$/, "") || "IFC"; @@ -239,7 +262,7 @@ export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, op return { id: `imported-ifc-${stamp}-${counter++}`, type: "importedMesh" as const, - name: [p.storey, p.name || p.ifcClass].filter(Boolean).join(": "), + name: [p.storey, p.name || p.ifcClass].filter(Boolean).join(": ") + classificationSuffix(p.classifications), layer: p.ifcClass, categoryCode: GENERIC_IMPORT_CATEGORY.code, ...(color ? { color } : {}), diff --git a/src/state/useProjectFileActions.ts b/src/state/useProjectFileActions.ts index 1673b6bf..b9e05255 100644 --- a/src/state/useProjectFileActions.ts +++ b/src/state/useProjectFileActions.ts @@ -24,7 +24,7 @@ import { isPdfFile, pdfPageToImport, readPdfVectorPage } from "../io/pdfVector"; import { planDashLineStyles } from "../io/pdfLineStyles"; import type { PdfVectorPage } from "../io/pdfVector"; import { exportScheduleCsv } from "../export/exportSchedule"; -import { exportIfcSpf } from "../export/exportIfc"; +import { exportIfcSpf, type IfcExportOptions } from "../export/exportIfc"; import { loadFileio } from "../engine/fileioWasm"; import { exportProjectStep } from "../export/exportStep"; import { exportGlb, exportObj, exportStl } from "../export/exportMesh"; @@ -587,7 +587,7 @@ export function useProjectFileActions( // Führt den gewählten Direkt-Export (CSV/IFC/OBJ/STL) mit dem im Dialog // gewählten Dateinamen aus. Erzeugung aus dem jeweiligen reinen Kern, Download // über den robusten Helfer. - const runExport = (format: ExportSaveFormat, filename: string) => { + const runExport = (format: ExportSaveFormat, filename: string, ifcOptions?: IfcExportOptions) => { switch (format) { case "csv": downloadTextFile("" + exportScheduleCsv(project), filename, "text/csv;charset=utf-8;"); @@ -595,7 +595,7 @@ export function useProjectFileActions( case "ifc": // IFC schreibt Rust (Format-Modul pkgFileIo, wird beim ersten Export nachgeladen). void loadFileio() - .then(() => downloadTextFile(exportIfcSpf(project), filename)) + .then(() => downloadTextFile(exportIfcSpf(project, ifcOptions), filename)) .catch((e) => notify(`${t("ifc.export.failed")}: ${e instanceof Error ? e.message : String(e)}`, "error")); break; case "obj": diff --git a/src/ui/ExportSaveDialog.tsx b/src/ui/ExportSaveDialog.tsx index 07c18e2e..60d35a54 100644 --- a/src/ui/ExportSaveDialog.tsx +++ b/src/ui/ExportSaveDialog.tsx @@ -10,6 +10,7 @@ import { useEffect, useState } from "react"; import { t } from "../i18n"; import { Dropdown } from "./Dropdown"; +import type { IfcExportOptions } from "../export/ifcClassification"; /** Direkt-herunterladbare Exportformate (mit Datei-Endung). */ export type ExportSaveFormat = "csv" | "ifc" | "obj" | "stl" | "glb" | "step"; @@ -29,7 +30,8 @@ export interface ExportSaveDialogProps { initialFormat: ExportSaveFormat; /** Basis-Dateiname OHNE Endung (i. d. R. Projektname). */ baseName: string; - onSave: (format: ExportSaveFormat, filename: string) => void; + /** `ifc`: Klassifikations-Optionen (nur bei Format IFC gesetzt). */ + onSave: (format: ExportSaveFormat, filename: string, ifc?: IfcExportOptions) => void; onClose: () => void; } @@ -59,7 +61,10 @@ export function ExportSaveDialog({ const [name, setName] = useState(baseName); const filename = withExt(name, EXPORT_FORMAT_EXT[format]); - const onConfirm = () => onSave(format, filename); + // IFC-Klassifikation (Schweizer Praxis): beides aus, bis die Nutzerin es wählt. + const [ebkph, setEbkph] = useState(false); + const [layerCodes, setLayerCodes] = useState(false); + const onConfirm = () => onSave(format, filename, format === "ifc" ? { ebkph, layerCodes } : undefined); return (
@@ -95,6 +100,22 @@ export function ExportSaveDialog({ /> + {format === "ifc" && ( +
+ +
{t("exportSave.ifc.ebkphHint")}
+ +
{t("exportSave.ifc.layersHint")}
+
{t("exportSave.ifc.zonesNote")}
+
+ )} +
{t("exportSave.filename")}