diff --git a/TODO.md b/TODO.md index 8d43855f..d4ab2637 100644 --- a/TODO.md +++ b/TODO.md @@ -445,6 +445,26 @@ 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 + - ✅ 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), + `Qto_ColumnBaseQuantities`, `Qto_DoorBaseQuantities`/`Qto_WindowBaseQuantities` (Width, Height, Perimeter, Area), + `Qto_StairFlightBaseQuantities`, `Qto_RailingBaseQuantities`; als IfcElementQuantity je Bauteil (nie geteilt), GUID + dauerhaft. Werte aus der Geometrie der Datei (`export/ifcQuantities.ts`, reine Rechnung), Netto = abzüglich + Öffnungen (Wand: je Schicht-Band, Netz-Wände: Volumen des Netzes). Height nur bei konstanter Oberkante (IFC-Vorgabe). + Mit ifcopenshell nachgerechnet (`exportIfc.quantities.test.ts`, ± 1 %): Wand-Netto und -Brutto (Demo-Haus: exakt), + Decke/Podest/Stütze/Läufe = Volumen, Dach = nach oben zeigende Netz-Dreiecke (geneigt und projiziert), + Tür/Fenster = Öffnungskörper; `validate-ifc.py` 0 Befunde. Rechnung bewusst in TS (Modell bleibt bis [K4] TS), die + Entitäten schreibt Rust (Pset-Arten 3–5, `FLAT_VERSION` 3). + - ✅ Deckenaussparungen als echte Löcher (IfcArbitraryProfileDefWithVoids statt Volldecke), wie im 3D. (28.10.) + - ✅ Treppen mit Läufen. (28.10.) IfcStair ohne Darstellung, per IfcRelAggregates mit IfcStairFlight (Prismen der + Tritte oder glatte Ortbeton-Laufplatte als Netz; NumberOfRisers/Treads, RiserHeight, TreadLength), IfcSlab(LANDING) + (Podest bei „L“) und IfcRailing(HANDRAIL) (Handlauf + Pfosten, wo das 3D sie zeigt: gerade Läufe). Quelle: dieselben + `emitStairs`/`emitStairMeshes`/`emitStairRailings` wie das 3D, je Treppe mit Ein-Treppen-Projekt (`export/ifcStairs.ts`). + Der eigene IFC-Import sieht jetzt `IfcStairFlight` statt `IfcStair` als Bauteil (Tests angepasst). Offen: Lauflänge + ist eine Näherung (Weg zwischen den Tritt-Schwerpunkten + Auftritt, mit Steigung), Wendeltreppe ein Lauf inkl. + Mitte, Geländer von L-/Wendeltreppen fehlt wie im 3D, Geländer-Länge = Lauflänge × Seiten; Pfosten nicht + als IfcMember; nicht in Revit/ArchiCAD geöffnet. - 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 index 7d903071..86b03fd0 100644 --- a/src-tauri/fileio/src/ifc_export.rs +++ b/src-tauri/fileio/src/ifc_export.rs @@ -17,7 +17,10 @@ // 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) +// 2 = IfcPositiveRatioMeasure (value = Zahl), +// 3 = IfcQuantityLength, 4 = IfcQuantityArea, 5 = IfcQuantityVolume (value = Zahl, ≥ 0). +// Heisst der Satz `Qto_…`, entsteht je Bauteil ein eigener IfcElementQuantity (Basismengen, +// nie geteilt); sonst ein IfcPropertySet (gleicher Inhalt = ein Pset für alle Bauteile). // structure= Geschoss-Index oder −1 (Gebäude) // // WALL_SOLIDS = 1, structure, id, name, TYPEREF, PSETS, FRAME, n_solids, (PTS, z_rel, depth) × n_solids @@ -28,7 +31,8 @@ // und, bei usage = 1 und vorhandenem Typ, IfcMaterialLayerSetUsage (AXIS2, POSITIVE, `offset` = // Abstand der ersten Schicht von der Achse entlang +Y). Ohne Rahmen: Placement ohne Drehung wie bisher. // WALL_MESH = 2, structure, id, name, TYPEREF, PSETS, MESH -// CEILING = 3, structure, id, name, TYPEREF, PSETS, PTS, z_rel, depth +// CEILING = 3, structure, id, name, TYPEREF, PSETS, PTS, n_inner, PTS × n_inner, z_rel, depth +// (innere Ringe = Deckenaussparungen, IfcArbitraryProfileDefWithVoids) // OPENING = 4, wall_id, structure, opening_id, is_door (0/1), fill_name, PTS (Öffnungskörper), z_rel, // depth, width, FILL, PSETS // FILL (Parameter aus dem Modell; Körper, Placement und OperationType/PartitioningType rechnet @@ -42,7 +46,14 @@ // Normale von u; Tür: Y = Aufschlagrichtung); ohne Teile (Wandöffnung) kein Körper. Alle Teile // (0 Rahmen/Zarge, 1 Türblatt, 2 Glas) sind getrennte Körper in EINER Darstellung, je mit eigenem // IfcStyledItem (Farbe/Transparenz je Rolle). -// STAIR = 5, structure, id, predefined (Text), PTS, z_rel, depth +// STAIR = 5, structure, id, predefined (Text), PTS, z_rel, depth (Ersatzkörper, nur ohne Läufe/Podest), +// PSETS, n_flights, FLIGHT × n_flights, has_landing, [LANDING], has_rail, [RAIL] +// FLIGHT = name, n_risers, n_treads, riser_height, tread_length, predefined (Text, IfcStairFlightTypeEnum), +// PSETS, shape (0 = Extrusionen, 1 = Dreiecks-Mesh), 0: n, (PTS, z_rel, depth) × n | 1: MESH +// LANDING = name, PTS, z_rel, depth, PSETS (IfcSlab, PredefinedType LANDING) +// RAIL = name, predefined (Text, IfcRailingTypeEnum), PSETS, MESH +// Mit mindestens einem Lauf/Podest/Geländer ist die IfcStair selbst ohne Darstellung und fasst Läufe, +// Podest und Geländer per IfcRelAggregates zusammen (nur die Treppe liegt im Geschoss). // 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 @@ -64,8 +75,8 @@ use std::collections::HashMap; use crate::ifc_openings::{fill_geometry, DoorKind, FillParams, FillPart, Sash, MAX_SASHES}; -/// Version der flachen Kodierung (erstes Element des Puffers). -pub const FLAT_VERSION: f64 = 2.0; +/// Version der flachen Kodierung (erstes Element des Puffers). 3 seit 28.10.: Basismengen (Pset-Arten 3–5), Deckenaussparungen, Treppen mit Läufen. +pub const FLAT_VERSION: f64 = 3.0; pub const REC_WALL_SOLIDS: f64 = 1.0; pub const REC_WALL_MESH: f64 = 2.0; @@ -475,6 +486,46 @@ impl<'a> Reader<'a> { let closed = self.flag()?; Ok(Mesh { positions, indices, closed }) } + /// Treppenlauf (s. Kopf, STAIR). + fn stair_flight(&mut self) -> Result { + let name = self.string()?; + let risers = self.idx()?; + let treads = self.idx()?; + let riser_height = self.f()?; + let tread_length = self.f()?; + let predefined = self.string()?; + let psets = self.psets()?; + let shape = match self.idx()? { + 0 => { + let n = self.idx()?; + let mut solids = Vec::new(); + for _ in 0..n { + let pts = self.pts()?; + solids.push((pts, self.f()?, self.f()?)); + } + FlightShape::Solids(solids) + } + 1 => FlightShape::Mesh(self.mesh()?), + k => return Err(format!("unbekannte Lauf-Form {k}")), + }; + Ok(StairFlight { name, risers, treads, riser_height, tread_length, predefined, psets, shape }) + } + /// Podest (s. Kopf, STAIR). + fn stair_landing(&mut self) -> Result { + let name = self.string()?; + let pts = self.pts()?; + let (z_rel, depth) = (self.f()?, self.f()?); + let psets = self.psets()?; + Ok(StairLanding { name, pts, z_rel, depth, psets }) + } + /// Geländer (s. Kopf, STAIR). + fn stair_rail(&mut self) -> Result { + let name = self.string()?; + let predefined = self.string()?; + let psets = self.psets()?; + let mesh = self.mesh()?; + Ok(StairRail { name, predefined, psets, mesh }) + } fn type_ref(&mut self) -> Result, String> { if !self.flag()? { return Ok(None); @@ -511,6 +562,9 @@ impl<'a> Reader<'a> { 0 => PropVal::Ident(self.string()?), 1 => PropVal::Bool(self.flag()?), 2 => PropVal::Ratio(self.f()?), + 3 => PropVal::Length(self.f()?), + 4 => PropVal::Area(self.f()?), + 5 => PropVal::Volume(self.f()?), k => return Err(format!("unbekannte Eigenschaftsart {k}")), }; props.push((pname, value)); @@ -571,6 +625,38 @@ struct Mesh { closed: bool, } +enum FlightShape { + /// Prismen (Profil in Welt-XY, Unterkante relativ zum Geschoss, Tiefe). + Solids(Vec<(Vec<(f64, f64)>, f64, f64)>), + Mesh(Mesh), +} + +struct StairFlight { + name: String, + risers: usize, + treads: usize, + riser_height: f64, + tread_length: f64, + predefined: String, + psets: Vec, + shape: FlightShape, +} + +struct StairLanding { + name: String, + pts: Vec<(f64, f64)>, + z_rel: f64, + depth: f64, + psets: Vec, +} + +struct StairRail { + name: String, + predefined: String, + psets: Vec, + mesh: Mesh, +} + #[derive(Clone, Copy, PartialEq)] enum TypeKind { Wall, @@ -606,6 +692,10 @@ enum PropVal { Ident(String), Bool(bool), Ratio(f64), + /// Basismengen (`Qto_…`): Länge, Fläche, Volumen. + Length(f64), + Area(f64), + Volume(f64), } impl PropVal { @@ -615,6 +705,17 @@ impl PropVal { 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)), + PropVal::Length(_) | PropVal::Area(_) | PropVal::Volume(_) => String::new(), + } + } + + /// Mengen-Entität und Wert (nur Basismengen), sonst `None`. + fn quantity(&self) -> Option<(&'static str, f64)> { + match self { + PropVal::Length(v) => Some(("IFCQUANTITYLENGTH", *v)), + PropVal::Area(v) => Some(("IFCQUANTITYAREA", *v)), + PropVal::Volume(v) => Some(("IFCQUANTITYVOLUME", *v)), + _ => None, } } } @@ -639,6 +740,15 @@ struct PsetAcc { related: Vec, } +/// Basismengen eines Bauteils (`Qto_…`), am Ende als IfcElementQuantity geschrieben. +struct QtoAcc { + /// Schlüssel des Bauteils (wie für seine GlobalId) — Grundlage der dauerhaften GUIDs. + owner_key: String, + name: String, + quantities: Vec<(&'static str, String, f64)>, + element: usize, +} + struct TypeAcc { key: String, type_id: usize, @@ -662,6 +772,7 @@ struct Builder { containment: Vec<(i64, Vec)>, psets: Vec, pset_index: HashMap, + qtos: Vec, materials: HashMap, types: Vec, type_index: HashMap, @@ -722,10 +833,24 @@ impl Builder { } /// Eigenschaftssatz vormerken: gleicher Inhalt ⇒ EIN Pset für alle Bauteile (GUID aus dem Inhalt). - fn add_pset(&mut self, pset: &Pset, element: usize) { + /// + /// Basismengen (`Qto_…`) sind dagegen je Bauteil eigen: `owner_key` (Schlüssel des Bauteils, wie für + /// seine GlobalId) bestimmt die GUIDs von Menge und Beziehung. + fn add_pset(&mut self, pset: &Pset, element: usize, owner_key: &str) { if pset.props.is_empty() { return; // IfcPropertySet verlangt mindestens eine Eigenschaft } + if pset.name.starts_with("Qto_") { + let quantities: Vec<(&'static str, String, f64)> = pset + .props + .iter() + .filter_map(|(n, v)| v.quantity().map(|(ty, x)| (ty, n.clone(), x))) + .collect(); + if !quantities.is_empty() { + self.qtos.push(QtoAcc { owner_key: owner_key.to_string(), name: pset.name.clone(), quantities, element }); + } + return; + } 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 @@ -741,15 +866,30 @@ impl Builder { } } - /// 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()) { + /// Geschlossener Linienzug (erster Punkt am Ende wiederholt) als IfcPolyline. + fn emit_closed_polyline(&mut self, ring: &[(f64, f64)]) -> usize { + let mut pt_ids = Vec::with_capacity(ring.len() + 1); + for p in ring.iter().chain(ring.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"))); + self.add("IFCPOLYLINE", refs(&pt_ids)) + } + + /// Profil (geschlossenes Polygon) als IfcExtrudedAreaSolid, Unterkante `z_rel` in `+Z`. + fn emit_extrusion(&mut self, footprint: &[(f64, f64)], z_rel: f64, depth: f64) -> usize { + self.emit_extrusion_voids(footprint, &[], z_rel, depth) + } + + /// Wie {@link emit_extrusion}, mit inneren Ringen (Aussparungen) als IfcArbitraryProfileDefWithVoids. + fn emit_extrusion_voids(&mut self, footprint: &[(f64, f64)], inner: &[Vec<(f64, f64)>], z_rel: f64, depth: f64) -> usize { + let polyline = self.emit_closed_polyline(footprint); + let profile = if inner.is_empty() { + self.add("IFCARBITRARYCLOSEDPROFILEDEF", format!("{},$,#{polyline}", enum_("AREA"))) + } else { + let holes: Vec = inner.iter().map(|ring| self.emit_closed_polyline(ring)).collect(); + self.add("IFCARBITRARYPROFILEDEFWITHVOIDS", format!("{},$,#{polyline},{}", enum_("AREA"), refs(&holes))) + }; 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)])); @@ -846,7 +986,12 @@ impl Builder { /// 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); + self.emit_box_product_voids(footprint, &[], z_bottom_rel, depth, relative_to) + } + + /// Wie {@link emit_box_product}, mit Aussparungen im Profil. + fn emit_box_product_voids(&mut self, footprint: &[(f64, f64)], inner: &[Vec<(f64, f64)>], z_bottom_rel: f64, depth: f64, relative_to: usize) -> (usize, usize) { + let solid = self.emit_extrusion_voids(footprint, inner, 0.0, depth); let shape = self.emit_swept_shape(&[solid]); let placement = self.emit_placement(z_bottom_rel, relative_to); (placement, shape) @@ -968,7 +1113,7 @@ impl Builder { } self.add_to_containment(structure, entity); for p in psets { - self.add_pset(p, entity); + self.add_pset(p, entity, &guid_key); } entity } @@ -1025,6 +1170,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { containment: Vec::new(), psets: Vec::new(), pset_index: HashMap::new(), + qtos: Vec::new(), materials: HashMap::new(), types: Vec::new(), type_index: HashMap::new(), @@ -1249,9 +1395,14 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { let ty = r.type_ref()?; let psets = r.psets()?; let pts = r.pts()?; + let n_inner = r.idx()?; + let mut inner = Vec::new(); + for _ in 0..n_inner { + inner.push(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 (placement, shape) = w.emit_box_product_voids(&pts, &inner, 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 => { @@ -1320,7 +1471,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { ); w.add_to_containment(structure, fill_entity); for p in &psets { - w.add_pset(p, fill_entity); + w.add_pset(p, fill_entity, &format!("fill/{opening_id}")); } } c if c == REC_STAIR => { @@ -1330,10 +1481,85 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { 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))); + let psets = r.psets()?; + let mut flights = Vec::new(); + for _ in 0..r.idx()? { + flights.push(r.stair_flight()?); + } + let landing = if r.flag()? { Some(r.stair_landing()?) } else { None }; + let rail = if r.flag()? { Some(r.stair_rail()?) } else { None }; + let key = format!("stair/{id}"); + let parent = w.placement_of(structure); + let g = w.gid(&key); + let entity = if flights.is_empty() && landing.is_none() && rail.is_none() { + // Ohne Teile: ein Ersatzkörper (Fussabdruck) wie bisher. + let (placement, shape) = w.emit_box_product(&pts, z_rel, depth, parent); + w.emit_building_element("IFCSTAIR", g, "Treppe", placement, shape, Some(enum_(&predefined))) + } else { + // Treppe ohne eigene Darstellung; Läufe, Podest und Geländer hängen per IfcRelAggregates daran. + let stair_placement = w.emit_placement(0.0, parent); + let stair = w.add( + "IFCSTAIR", + format!("{g},#{},{},$,$,#{stair_placement},$,$,{}", w.owner_history, ifc_string("Treppe"), enum_(&predefined)), + ); + let mut parts = Vec::new(); + for (k, f) in flights.iter().enumerate() { + let (placement, shape) = match &f.shape { + FlightShape::Solids(solids) => { + let ids: Vec = solids.iter().map(|(pts, z, d)| w.emit_extrusion(pts, *z, *d)).collect(); + let shape = w.emit_swept_shape(&ids); + (w.emit_placement(0.0, stair_placement), shape) + } + FlightShape::Mesh(mesh) => w.emit_triangulated_product(mesh, stair_placement), + }; + let fkey = format!("{key}/flight/{k}"); + let guid = w.gid(&fkey); + let flight = w.add( + "IFCSTAIRFLIGHT", + format!( + "{guid},#{},{},$,$,#{placement},#{shape},$,{},{},{},{},{}", + w.owner_history, + ifc_string(&f.name), + f.risers, + f.treads, + fmt_real(f.riser_height), + fmt_real(f.tread_length), + enum_(&f.predefined) + ), + ); + for p in &f.psets { + w.add_pset(p, flight, &fkey); + } + parts.push(flight); + } + if let Some(l) = &landing { + let (placement, shape) = w.emit_box_product(&l.pts, l.z_rel, l.depth, stair_placement); + let lkey = format!("{key}/landing"); + let guid = w.gid(&lkey); + let slab = w.emit_building_element("IFCSLAB", guid, &l.name, placement, shape, Some(enum_("LANDING"))); + for p in &l.psets { + w.add_pset(p, slab, &lkey); + } + parts.push(slab); + } + if let Some(rl) = &rail { + let (placement, shape) = w.emit_triangulated_product(&rl.mesh, stair_placement); + let rkey = format!("{key}/railing"); + let guid = w.gid(&rkey); + let railing = w.emit_building_element("IFCRAILING", guid, &rl.name, placement, shape, Some(enum_(&rl.predefined))); + for p in &rl.psets { + w.add_pset(p, railing, &rkey); + } + parts.push(railing); + } + let g = w.gid(&format!("aggregates/{key}")); + w.add("IFCRELAGGREGATES", format!("{g},#{},$,$,#{stair},{}", w.owner_history, refs(&parts))); + stair + }; w.add_to_containment(structure, entity); + for p in &psets { + w.add_pset(p, entity, &key); + } } c if c == REC_EXTRUSION => { let structure = r.structure(n_storeys)?; @@ -1409,7 +1635,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { format!("{g},#{},$,$,{},#{pset}", w.owner_history, refs(&[space])), ); for p in &psets { - w.add_pset(p, space); + w.add_pset(p, space, &format!("space/{id}")); } } c if c == REC_END_SPACES => { @@ -1448,7 +1674,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { 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); + w.add_pset(p, entity, &format!("column/{id}")); } if let Some(cid) = component { if let Some((_, _, v)) = w.column_materials.iter_mut().find(|(c, _, _)| *c == cid) { @@ -1506,6 +1732,20 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { ); } + // ── Basismengen (je Bauteil ein IfcElementQuantity) ── + let qtos = std::mem::take(&mut w.qtos); + for q in &qtos { + let mut ids = Vec::with_capacity(q.quantities.len()); + for (ty, name, value) in &q.quantities { + // IFC verlangt Mengen ≥ 0. + ids.push(w.add(ty, format!("{},$,$,{},$", ifc_string(name), fmt_real(value.max(0.0))))); + } + let g = w.gid(&format!("{}/{}", q.owner_key, q.name)); + let set = w.add("IFCELEMENTQUANTITY", format!("{g},#{},{},$,$,{}", w.owner_history, ifc_string(&q.name), refs(&ids))); + let g = w.gid(&format!("{}/{}/rel", q.owner_key, q.name)); + w.add("IFCRELDEFINESBYPROPERTIES", format!("{g},#{},$,$,{},#{set}", w.owner_history, refs(&[q.element]))); + } + // ── Räumliche Eingliederung (gebündelt je Trägerstruktur) ── let containment = std::mem::take(&mut w.containment); for (structure, ids) in &containment { @@ -1717,6 +1957,16 @@ mod tests { fn no_psets(&mut self) { self.f.push(0.0); } + /// Ein Satz mit Mengen (`kind` 3 Länge, 4 Fläche, 5 Volumen). + fn qto(&mut self, set: &str, q: &[(&str, f64, f64)]) { + self.f.push(1.0); + self.str(set); + self.f.push(q.len() as f64); + for (n, kind, v) in q { + self.str(n); + self.n(&[*kind, *v]); + } + } 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]); @@ -1793,12 +2043,14 @@ mod tests { b.no_type(); b.no_psets(); b.pts(&SQUARE); - b.n(&[2.6, 0.2]); + b.n(&[0.0, 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.no_psets(); + b.n(&[0.0, 0.0, 0.0]); b.n(&[REC_EXTRUSION, -1.0]); b.str("X1"); b.pts(&SQUARE); @@ -2084,6 +2336,170 @@ mod tests { assert!(seen.len() > 20); } + #[test] + fn basismengen_je_bauteil_eigen_mit_dauerhafter_guid() { + let mut b = mini(); + for id in ["W1", "W2"] { + b.n(&[REC_WALL_SOLIDS, -1.0]); + b.str(id); + b.str("Wand"); + b.no_type(); + b.qto("Qto_WallBaseQuantities", &[("Length", 3.0, 5.0), ("GrossSideArea", 4.0, 13.0), ("NetVolume", 5.0, 3.25), ("Width", 3.0, -1e-9)]); + b.n(&[0.0, 1.0]); + b.pts(&SQUARE); + b.n(&[0.0, 2.6]); + } + let ifc = build(&b).unwrap(); + check_structure(&ifc); + // Gleicher Inhalt, trotzdem je Wand ein eigener Satz (Mengen gehören dem Bauteil). + assert_eq!(count(&ifc, "IFCELEMENTQUANTITY"), 2); + assert_eq!(count(&ifc, "IFCPROPERTYSET"), 0); + assert_eq!(count(&ifc, "IFCQUANTITYLENGTH"), 4); + assert_eq!(count(&ifc, "IFCQUANTITYAREA"), 2); + assert_eq!(count(&ifc, "IFCQUANTITYVOLUME"), 2); + assert!(ifc.contains("IFCQUANTITYLENGTH('Length',$,$,5.0,$)")); + assert!(ifc.contains("IFCQUANTITYAREA('GrossSideArea',$,$,13.0,$)")); + assert!(ifc.contains("IFCQUANTITYVOLUME('NetVolume',$,$,3.25,$)")); + // Negative (Rundungs-)Werte werden auf 0 geklemmt (IFC verlangt ≥ 0). + assert!(ifc.contains("IFCQUANTITYLENGTH('Width',$,$,0.0,$)")); + assert_eq!(count(&ifc, "IFCRELDEFINESBYPROPERTIES"), 2); + let set = first_line(&ifc, "IFCELEMENTQUANTITY"); + assert!(set.contains("'Qto_WallBaseQuantities',$,$,("), "{set}"); + // Deterministisch, GUIDs verschieden je Wand. + assert_eq!(ifc, build(&b).unwrap()); + let guids: Vec<&str> = ifc.lines().filter(|l| l.contains("=IFCELEMENTQUANTITY(")).map(|l| &l[l.find('(').unwrap() + 2..][..22]).collect(); + assert_eq!(guids.len(), 2); + assert_ne!(guids[0], guids[1]); + // Eine andere Reihenfolge der Bauteile ändert die GUIDs nicht. + assert!(ifc.contains(&ifc_guid("t/wall/W1/Qto_WallBaseQuantities"))); + assert!(ifc.contains(&ifc_guid("t/wall/W2/Qto_WallBaseQuantities"))); + } + + #[test] + fn decke_mit_aussparung_hat_profil_mit_loechern() { + let mut b = mini(); + b.n(&[REC_CEILING, -1.0]); + b.str("D1"); + b.str("Decke"); + b.no_type(); + b.qto("Qto_SlabBaseQuantities", &[("GrossArea", 4.0, 2.0), ("NetArea", 4.0, 1.5)]); + b.pts(&SQUARE); + b.n(&[2.0]); + b.pts(&[(1.0, 0.1), (2.0, 0.1), (2.0, 0.3), (1.0, 0.3)]); + b.pts(&[(3.0, 0.1), (4.0, 0.1), (4.0, 0.3)]); + b.n(&[2.6, 0.2]); + let ifc = build(&b).unwrap(); + check_structure(&ifc); + assert_eq!(count(&ifc, "IFCARBITRARYPROFILEDEFWITHVOIDS"), 1); + assert_eq!(count(&ifc, "IFCARBITRARYCLOSEDPROFILEDEF"), 0); + let prof = first_line(&ifc, "IFCARBITRARYPROFILEDEFWITHVOIDS"); + assert!(prof.contains(".AREA.,$,#"), "{prof}"); + // Aussen- und zwei Innenkurven, jede geschlossen (Punkt 1 wiederholt). + assert_eq!(count(&ifc, "IFCPOLYLINE"), 3); + assert_eq!(count(&ifc, "IFCEXTRUDEDAREASOLID"), 1); + // Ohne Aussparung bleibt es das einfache Profil. + let plain = build(&full_house(false)).unwrap(); + assert_eq!(count(&plain, "IFCARBITRARYPROFILEDEFWITHVOIDS"), 0); + } + + /// Treppe mit zwei Läufen (Prismen), Podest und Geländer (Mesh). + fn stair_with_parts(b: &mut B) { + b.n(&[REC_STAIR, -1.0]); + b.str("S1"); + b.str("QUARTER_TURN_STAIR"); + b.pts(&SQUARE); + b.n(&[0.0, 2.6]); + b.no_psets(); + b.n(&[2.0]); + for (k, name) in ["Lauf 1", "Lauf 2"].iter().enumerate() { + b.str(name); + b.n(&[7.0, 7.0, 0.1857, 0.28]); + b.str("STRAIGHT"); + b.qto("Qto_StairFlightBaseQuantities", &[("Length", 3.0, 2.0), ("GrossVolume", 5.0, 1.0)]); + b.n(&[0.0, 2.0]); + b.pts(&SQUARE); + b.n(&[0.0, 0.2 * (k + 1) as f64]); + b.pts(&SQUARE); + b.n(&[0.5, 0.4]); + } + b.n(&[1.0]); + b.str("Podest"); + b.pts(&SQUARE); + b.n(&[0.0, 1.3]); + b.no_psets(); + b.n(&[1.0]); + b.str("Handlauf"); + b.str("HANDRAIL"); + b.no_psets(); + b.mesh_tetra(); + } + + #[test] + fn treppe_mit_laeufen_podest_und_gelaender() { + let b = full_house(false); + let mut m = mini(); + stair_with_parts(&mut m); + let ifc = build(&m).unwrap(); + check_structure(&ifc); + assert_eq!(count(&ifc, "IFCSTAIR"), 1); + assert_eq!(count(&ifc, "IFCSTAIRFLIGHT"), 2); + assert_eq!(count(&ifc, "IFCRAILING"), 1); + assert_eq!(count(&ifc, "IFCSLAB"), 1); + assert!(ifc.contains(".LANDING.);"), "Podest als IfcSlab(LANDING)"); + let stair = first_line(&ifc, "IFCSTAIR"); + assert!(stair.contains(",$,$,.QUARTER_TURN_STAIR.);") && !stair.contains("#,#"), "{stair}"); + let flight = first_line(&ifc, "IFCSTAIRFLIGHT"); + assert!(flight.contains(",7,7,0.1857,0.28,.STRAIGHT.);"), "{flight}"); + // Beide Läufe: Menge je Lauf; Treppe, Läufe, Podest, Geländer in EINER Aggregation, nur die Treppe im Geschoss/Gebäude. + assert_eq!(count(&ifc, "IFCELEMENTQUANTITY"), 2); + let agg = ifc.lines().find(|l| l.contains("IFCRELAGGREGATES(") && l.matches('#').count() == 7).expect("Aggregation der Treppe"); + assert!(agg.contains(",#"), "{agg}"); + let contained = first_line(&ifc, "IFCRELCONTAINEDINSPATIALSTRUCTURE"); + assert_eq!(contained.matches('#').count(), 4, "nur die Treppe (Nummer, Owner, Treppe, Gebäude): {contained}"); + // Läufe als Prismen, Geländer als Dreiecks-Netz. + assert_eq!(count(&ifc, "IFCEXTRUDEDAREASOLID"), 5); // 2 Läufe × 2 Prismen + Podest + assert_eq!(count(&ifc, "IFCTRIANGULATEDFACESET"), 1); + // Ohne Teile: Ersatzkörper (Fussabdruck) wie vorher. + let fallback = build(&b).unwrap(); + assert_eq!(count(&fallback, "IFCSTAIRFLIGHT"), 0); + assert_eq!(count(&fallback, "IFCSTAIR"), 1); + // Lauf mit Mesh-Form. + let mut g = mini(); + g.n(&[REC_STAIR, -1.0]); + g.str("S2"); + g.str("STRAIGHT_RUN_STAIR"); + g.pts(&SQUARE); + g.n(&[0.0, 2.6]); + g.no_psets(); + g.n(&[1.0]); + g.str("Lauf"); + g.n(&[15.0, 14.0, 0.17, 0.29]); + g.str("STRAIGHT"); + g.no_psets(); + g.n(&[1.0]); + g.mesh_tetra(); + g.n(&[0.0, 0.0]); + let mesh = build(&g).unwrap(); + check_structure(&mesh); + assert_eq!(count(&mesh, "IFCSTAIRFLIGHT"), 1); + assert_eq!(count(&mesh, "IFCTRIANGULATEDFACESET"), 1); + // Kaputte Lauf-Form: Fehler, nie Panic. + let mut bad = mini(); + bad.n(&[REC_STAIR, -1.0]); + bad.str("S3"); + bad.str("STRAIGHT_RUN_STAIR"); + bad.pts(&SQUARE); + bad.n(&[0.0, 2.6]); + bad.no_psets(); + bad.n(&[1.0]); + bad.str("Lauf"); + bad.n(&[1.0, 1.0, 0.17, 0.29]); + bad.str("STRAIGHT"); + bad.no_psets(); + bad.n(&[9.0]); + assert!(build(&bad).is_err()); + } + #[test] fn leeres_projekt_ist_gueltig() { let mut b = B::new(); diff --git a/src/export/exportIfc.quantities.test.ts b/src/export/exportIfc.quantities.test.ts new file mode 100644 index 00000000..84b08d98 --- /dev/null +++ b/src/export/exportIfc.quantities.test.ts @@ -0,0 +1,257 @@ +// Basismengen im IFC-Export ([B5], 28.10.): Qto_Wall/Slab/Roof/Column/Door/Window/StairFlight/Railing +// werden gegen die Geometrie geprüft, die ifcopenshell aus derselben Datei liest (± 1 %), dazu Schema und +// Express-Regeln (`scripts/validate-ifc.py`, 0 Befunde). Ohne Python/ifcopenshell wird der zweite Teil übersprungen. + +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 { sampleProject } from "../model/sampleProject"; +import type { Column, Project, Stair } from "../model/types"; + +const hasIfcOpenShell = spawnSync("python3", ["-c", "import ifcopenshell, ifcopenshell.validate, numpy"]).status === 0; + +/** Das Demo-Haus plus Stütze, Deckenaussparung, L-Treppe (massiv) und gerade Treppe mit Geländer. */ +function project(): Project { + const eg = "eg"; + const column: Column = { id: "C1", type: "column", floorId: eg, categoryCode: "50", position: { x: 6.5, y: 1 }, profile: { kind: "rect", width: 0.3, depth: 0.2 }, rotation: 0.3, height: 2.5 }; + const st0 = sampleProject.stairs![0]; + const lStair: Stair = { ...st0, id: "ST-L", typeId: "stair-massiv", shape: "L", start: { x: 7.5, y: 0.4 }, run2Length: 1.5, turn: 1, stepCount: 14 }; + const railed: Stair = { ...st0, id: "ST-R", typeId: "stair-rail", start: { x: 10, y: 0.4 } }; + return { + ...sampleProject, + ceilings: sampleProject.ceilings!.map((c) => ({ ...c, openings: [[{ x: 1, y: 1 }, { x: 2.5, y: 1 }, { x: 2.5, y: 2 }, { x: 1, y: 2 }]] })), + columns: [column], + stairTypes: [...sampleProject.stairTypes!, { id: "stair-rail", name: "Massiv mit Handlauf", structure: "massiv", closedRisers: true, treadThickness: 0.04, nosing: 0.03, railing: "beide", defaultWidth: 1 }], + stairs: [...sampleProject.stairs!, lStair, railed], + } as Project; +} + +function writeIfc(name: string, ifc: string): string { + const dir = mkdtempSync(join(tmpdir(), "dossier-qto-")); + const file = join(dir, `${name}.ifc`); + writeFileSync(file, ifc); + return file; +} + +/** + * Je Bauteil mit Basismengen: Klasse, Name, Mengen und unabhängig aus der Geometrie gelesene Werte + * (Volumen mit/ohne Öffnungsabzug, nach oben zeigende Fläche, Bounding-Box lokal). + */ +const QTO_INFO = ` +import json, sys +import numpy as np +import ifcopenshell, ifcopenshell.geom, ifcopenshell.util.element as ue, ifcopenshell.util.shape as us +m = ifcopenshell.open(sys.argv[1]) +net = ifcopenshell.geom.settings() +gross = ifcopenshell.geom.settings() +gross.set("disable-opening-subtractions", True) +local = ifcopenshell.geom.settings() +local.set("use-world-coords", False) + +def up_areas(geom): + v = np.array(geom.verts).reshape(-1, 3) + f = np.array(geom.faces).reshape(-1, 3) + n = np.cross(v[f[:, 1]] - v[f[:, 0]], v[f[:, 2]] - v[f[:, 0]]) + area = np.linalg.norm(n, axis=1) / 2 + nz = n[:, 2] / np.maximum(np.linalg.norm(n, axis=1), 1e-12) + up = nz > 0.1 + return float(area[up].sum()), float((area[up] * nz[up]).sum()) + +def opening_dims(wall): + out = [] + for rel in wall.HasOpenings: + e = rel.RelatedOpeningElement + g = ifcopenshell.geom.create_shape(local, e).geometry + v = np.array(g.verts).reshape(-1, 3) + d = v.max(axis=0) - v.min(axis=0) + out.append([float(x) for x in d]) + return out + +out = [] +for el in m.by_type("IfcElement"): + qtos = ue.get_psets(el, qtos_only=True) + if not qtos: + continue + item = {"cls": el.is_a(), "name": el.Name, "predefined": getattr(el, "PredefinedType", None), "qto": qtos} + if el.Representation is not None: + shape = ifcopenshell.geom.create_shape(net, el) + item["volume"] = us.get_volume(shape.geometry) + item["area"] = us.get_area(shape.geometry) + item["up"] = up_areas(shape.geometry) + item["rep"] = [r for r in el.Representation.Representations if r.RepresentationIdentifier == "Body"][0].RepresentationType + if el.is_a("IfcWall"): + item["grossVolume"] = us.get_volume(ifcopenshell.geom.create_shape(gross, el).geometry) + item["openings"] = opening_dims(el) + g = shape.geometry + v = np.array(g.verts).reshape(-1, 3) + item["zExtent"] = float(v[:, 2].max() - v[:, 2].min()) + if el.is_a("IfcSlab"): + prof = [r for r in el.Representation.Representations if r.RepresentationIdentifier == "Body"][0].Items[0].SweptArea + holes = [] + if prof.is_a("IfcArbitraryProfileDefWithVoids"): + for c in prof.InnerCurves: + p = np.array([q.Coordinates for q in c.Points]) + holes.append(float(abs(0.5 * np.sum(p[:-1, 0] * p[1:, 1] - p[1:, 0] * p[:-1, 1])))) + item["holeAreas"] = holes + item["depth"] = float(el.Representation.Representations[0].Items[0].Depth) + if el.is_a("IfcDoor") or el.is_a("IfcWindow"): + host = [r.RelatingOpeningElement for r in el.FillsVoids] + g = ifcopenshell.geom.create_shape(local, host[0]).geometry + v = np.array(g.verts).reshape(-1, 3) + item["openingDims"] = [float(x) for x in (v.max(axis=0) - v.min(axis=0))] + out.append(item) +print(json.dumps(out)) +`; + +interface Item { + cls: string; + name: string; + predefined: string | null; + qto: Record>; + volume?: number; + area?: number; + up?: [number, number]; + rep?: string; + grossVolume?: number; + openings?: number[][]; + zExtent?: number; + holeAreas?: number[]; + depth?: number; + openingDims?: number[]; +} + +function info(name: string, ifc: string): Item[] { + const r = spawnSync("python3", ["-c", QTO_INFO, writeIfc(name, ifc)], { encoding: "utf8", timeout: 120_000 }); + expect(r.status, r.stderr).toBe(0); + return JSON.parse(r.stdout); +} + +const rel = (a: number, b: number) => Math.abs(a - b) / Math.max(Math.abs(a), Math.abs(b), 1e-9); +const close = (a: number, b: number, tol = 0.01) => expect(rel(a, b), `${a} ≠ ${b}`).toBeLessThanOrEqual(tol); +const qof = (it: Item, set: string) => it.qto[set] ?? {}; + +describe("Basismengen im Export (ohne ifcopenshell)", () => { + it("jedes Bauteil trägt seine Mengen; Treppe mit Läufen, Podest und Geländer; Deckenaussparung", () => { + const ifc = exportIfcSpf(project()); + const count = (cls: string) => (ifc.match(new RegExp(`^#\\d+=${cls}\\(`, "gm")) ?? []).length; + const sets = (name: string) => (ifc.match(new RegExp(`IFCELEMENTQUANTITY\\('[^']*',#\\d+,'${name}'`, "g")) ?? []).length; + expect(sets("Qto_WallBaseQuantities")).toBe(count("IFCWALL")); + expect(sets("Qto_SlabBaseQuantities")).toBe(count("IFCSLAB")); // Decke + Podest der L-Treppe + expect(sets("Qto_RoofBaseQuantities")).toBe(1); + expect(sets("Qto_ColumnBaseQuantities")).toBe(1); + expect(sets("Qto_DoorBaseQuantities")).toBe(count("IFCDOOR")); + expect(sets("Qto_WindowBaseQuantities")).toBe(count("IFCWINDOW")); + expect(sets("Qto_StairFlightBaseQuantities")).toBe(count("IFCSTAIRFLIGHT")); + expect(sets("Qto_RailingBaseQuantities")).toBe(count("IFCRAILING")); + expect(count("IFCSTAIR")).toBe(3); + expect(count("IFCSTAIRFLIGHT")).toBe(1 /* Beton: Netz */ + 2 /* L */ + 1); + expect(count("IFCRAILING")).toBe(1); + expect(count("IFCARBITRARYPROFILEDEFWITHVOIDS")).toBe(1); + expect(ifc).toContain(".LANDING.);"); + }); + + it("Export ist deterministisch (GUIDs der Mengen stabil)", () => { + const strip = (s: string) => s.replace(/FILE_NAME\([^\n]*\n/, "").replace(/IFCOWNERHISTORY\([^\n]*\n/, ""); + expect(strip(exportIfcSpf(project()))).toBe(strip(exportIfcSpf(project()))); + }); +}); + +describe.skipIf(!hasIfcOpenShell)("Basismengen gegen ifcopenshell", { timeout: 120_000 }, () => { + const ifc = exportIfcSpf(project()); + const items = info("qto", ifc); + const of = (cls: string) => items.filter((i) => i.cls === cls); + + it("schema- und regelkonform, alle Körper erzeugbar (0 Befunde)", () => { + const r = spawnSync("python3", ["scripts/validate-ifc.py", writeIfc("qto-validate", ifc)], { encoding: "utf8", timeout: 120_000 }); + expect(`${r.stdout}\n${r.stderr}`).toContain("0 Befunde"); + expect(r.status).toBe(0); + }); + + it("Wände: Netto-Volumen = Geometrie mit Öffnungsabzug, Brutto = ohne (Extrusions-Wände), Länge/Höhe/Seitenfläche", () => { + const walls = of("IfcWall"); + expect(walls.length).toBe(9); + for (const w of walls) { + const q = qof(w, "Qto_WallBaseQuantities"); + close(q.NetVolume, w.volume!); + if (w.rep === "SweptSolid") { + close(q.GrossVolume, w.grossVolume!); + // Seitenfläche brutto = Länge × Höhe; netto zieht die Öffnungen ab (Breite × Höhe der Öffnungskörper). + close(q.GrossSideArea, q.Length * q.Height); + const holes = (w.openings ?? []).reduce((s, d) => s + Math.max(...d.slice(0, 2)) * d[2], 0); + // Öffnungsquader sind quer 4 cm dicker als die Wand: die längere der zwei Grundrissmasse ist die Öffnungsbreite, + // sofern sie grösser als die Wanddicke ist. + if ((w.openings ?? []).every((d) => Math.max(d[0], d[1]) > q.Width + 0.05)) close(q.NetSideArea, q.GrossSideArea - holes); + close(q.Height, w.zExtent!); + } else { + // Netz-Wand: Brutto ≥ Netto, Seitenfläche netto ≤ brutto. + expect(q.GrossVolume).toBeGreaterThanOrEqual(q.NetVolume); + } + expect(q.NetSideArea).toBeLessThanOrEqual(q.GrossSideArea + 1e-9); + } + expect(walls.some((w) => w.rep === "SweptSolid")).toBe(true); + expect(walls.some((w) => w.rep === "Tessellation")).toBe(true); + // Mindestens eine Wand mit Öffnung: Netto < Brutto. + expect(walls.some((w) => qof(w, "Qto_WallBaseQuantities").NetVolume < qof(w, "Qto_WallBaseQuantities").GrossVolume - 1e-6)).toBe(true); + }); + + it("Decken und Podest: Volumen nach ifcopenshell, Aussparung = Brutto − Netto", () => { + const slabs = of("IfcSlab"); + const floor = slabs.find((s) => s.predefined === "FLOOR")!; + const q = qof(floor, "Qto_SlabBaseQuantities"); + close(q.NetVolume, floor.volume!); + const holes = floor.holeAreas!.reduce((a, b) => a + b, 0); + expect(holes).toBeCloseTo(1.5, 9); + close(q.GrossVolume - q.NetVolume, holes * floor.depth!); + close(q.GrossArea - q.NetArea, holes); + close(q.Width, floor.depth!); + const landing = slabs.find((s) => s.predefined === "LANDING")!; + const ql = qof(landing, "Qto_SlabBaseQuantities"); + close(ql.NetVolume, landing.volume!); + close(ql.GrossArea * ql.Width, ql.GrossVolume); + }); + + it("Dach: Grundrissprojektion und geneigte Fläche = nach oben zeigende Netz-Dreiecke", () => { + const [roof] = of("IfcRoof"); + const q = qof(roof, "Qto_RoofBaseQuantities"); + close(q.GrossArea, roof.up![0]); + close(q.ProjectedArea, roof.up![1]); + expect(q.GrossArea).toBeGreaterThan(q.ProjectedArea); + }); + + it("Stütze: Volumen, Querschnitt × Länge", () => { + const [col] = of("IfcColumn"); + const q = qof(col, "Qto_ColumnBaseQuantities"); + close(q.GrossVolume, col.volume!); + close(q.CrossSectionArea * q.Length, q.GrossVolume); + close(q.CrossSectionArea, 0.3 * 0.2); + expect(q.Length).toBeCloseTo(2.5, 9); + }); + + it("Türen und Fenster: Breite/Höhe wie der Öffnungskörper, Fläche = Breite × Höhe", () => { + const fills = [...of("IfcDoor"), ...of("IfcWindow")]; + expect(fills.length).toBe(3); + for (const f of fills) { + const q = qof(f, f.cls === "IfcDoor" ? "Qto_DoorBaseQuantities" : "Qto_WindowBaseQuantities"); + close(q.Area, q.Width * q.Height); + close(q.Height, f.openingDims![2]); + expect([f.openingDims![0], f.openingDims![1]].some((d) => rel(d, q.Width) <= 0.01), `${f.name} Breite ${q.Width}`).toBe(true); + } + }); + + it("Treppenläufe: Brutto-Volumen = Geometrie; Geländer mit Länge", () => { + const flights = of("IfcStairFlight"); + expect(flights.length).toBe(4); + for (const f of flights) { + const q = qof(f, "Qto_StairFlightBaseQuantities"); + // Massive Treppen: Prismen können sich an den Nasen überlappen — ifcopenshell vereinigt nicht, Summe stimmt. + close(q.GrossVolume, f.volume!, 0.011); + expect(q.Length).toBeGreaterThan(1); + } + const [rail] = of("IfcRailing"); + expect(qof(rail, "Qto_RailingBaseQuantities").Length).toBeGreaterThan(3); + }); +}); diff --git a/src/export/exportIfc.ts b/src/export/exportIfc.ts index 2ae1dba3..46598b7f 100644 --- a/src/export/exportIfc.ts +++ b/src/export/exportIfc.ts @@ -41,10 +41,11 @@ // • Dach → IfcRoof (Schicht-Meshes wie im 3D), Dachtyp → IfcRoofType mit Schichten. // • Stütze → IfcColumn (Profil-Extrusion), Bauteil → IfcMaterial. // • Raum → IfcSpace (im Geschoss aggregiert) mit Qto_SpaceBaseQuantities und SIA-416-Kategorie. -// • Treppe → IfcStair, GEOMETRISCH bewusst vereinfacht auf einen -// extrudierten Bounding-Footprint (Lauf-Rechteck bei "straight"; Achsen- -// ausgerichtete Bounding-Box der Kontrollpunkte bei "L"/"spiral") — die -// echte Stufengeometrie ist ausgelassen (siehe stairFootprint()). +// • Treppe → IfcStair ohne eigene Darstellung, zusammengefasst (IfcRelAggregates) aus Läufen +// (IfcStairFlight: Prismen der Tritte bzw. glatte Ortbeton-Laufplatte als Netz, Steigungs-/Auftrittsmasse), +// Podest (IfcSlab LANDING, nur "L") und Handlauf/Pfosten (IfcRailing HANDRAIL, wo das 3D sie zeigt) — +// dieselben Ableitungen wie das 3D (`ifcStairs.ts`). Ohne Teile bleibt der Fussabdruck-Quader +// (`stairFootprint()`). // // Material-Schichten: je Wand-/Deckentyp ein IfcWallType/IfcSlabType mit // IfcMaterialLayerSet, die Exemplare erben ihn über IfcRelDefinesByType. Extrusions-Wände @@ -54,6 +55,12 @@ // Wandanfang, X = Achse, Y = linke Normale (Rust rechnet die Welt-Profile ins Wandsystem). Mesh- // Wände (schräge Oberkante, Laibungs-Rücksprung) haben weder Achse noch Usage. // +// Basismengen ([B5], 28.10.): Qto_WallBaseQuantities (Length, Width, Height, GrossSideArea, NetSideArea, +// GrossVolume, NetVolume), Qto_SlabBaseQuantities, Qto_RoofBaseQuantities, Qto_ColumnBaseQuantities, +// Qto_DoorBaseQuantities/Qto_WindowBaseQuantities (Width, Height, Perimeter, Area), Qto_StairFlightBaseQuantities +// und Qto_RailingBaseQuantities — aus der Geometrie (`ifcQuantities.ts`), Netto = abzüglich Öffnungen; +// Rust schreibt je Bauteil einen IfcElementQuantity. Deckenaussparungen sind echte Löcher im Profil. +// // Eigenschaften ([B5]): Pset_WallCommon/SlabCommon/RoofCommon/ColumnCommon/DoorCommon/ // WindowCommon/SpaceCommon nur mit Werten, die das Modell hergibt (Reference = Typname, // IsExternal beim Dach und bei SIA-416-AGF-Räumen, Glasanteil der Glastür). Kein U-Wert, @@ -68,6 +75,7 @@ // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). Einheit: METER. import type { Opening, Project, Stair, Vec2, Wall } from "../model/types"; +import type { StairParts } from "./ifcStairs"; import { columnLabel, getCeilingType, @@ -88,6 +96,18 @@ import { openingInterval, openingVerticalExtent } from "../geometry/opening"; import { emitRoofs } from "../plan/toWalls3d/roofs"; import { fileio } from "../engine/fileioWasm"; import { fillParams, type FillParams } from "./ifcOpenings"; +import { stairParts } from "./ifcStairs"; +import { + columnQuantities, + holeVolume, + meshVolume, + openingQuantities, + roofQuantities, + slabQuantities, + wallQuantities, + type Qty, +} from "./ifcQuantities"; +import { roofBaseElevation, roofGeometry } from "../geometry/roof"; /** Deterministische 22-stellige IFC-GUID aus einem Namen (Rust, `ifc_export.rs::ifc_guid`). */ export function ifcGuid(name: string): string { @@ -101,7 +121,7 @@ export function ifcString(s: string): string { // ── Flacher Puffer (Gegenstück zu src-tauri/fileio/src/ifc_export.rs, dort die Kodierung) ───── -const FLAT_VERSION = 2; +const FLAT_VERSION = 3; const REC_WALL_SOLIDS = 1; const REC_WALL_MESH = 2; const REC_CEILING = 3; @@ -125,8 +145,17 @@ interface TypeRefIn { 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 }; +/** + * Pset-Eigenschaft: Kennung, Art (IfcIdentifier, IfcBoolean, IfcPositiveRatioMeasure) und Wert; in einem Satz + * `Qto_…` Mengen (Länge, Fläche, Volumen) — Rust schreibt daraus je Bauteil einen IfcElementQuantity. + */ +type PropIn = + | { name: string; ident: string } + | { name: string; bool: boolean } + | { name: string; ratio: number } + | { name: string; length: number } + | { name: string; area: number } + | { name: string; volume: number }; interface PsetIn { name: string; props: PropIn[]; @@ -170,7 +199,10 @@ class FlatIfc { 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); + else if ("ratio" in p) this.nums.push(this.str(p.name), 2, p.ratio); + else if ("length" in p) this.nums.push(this.str(p.name), 3, p.length); + else if ("area" in p) this.nums.push(this.str(p.name), 4, p.area); + else this.nums.push(this.str(p.name), 5, p.volume); } } } @@ -228,11 +260,13 @@ class FlatIfc { this.mesh(positions, indices, closed); } - ceiling(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], outline: Vec2[], zRel: number, depth: number): void { + ceiling(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], outline: Vec2[], inner: readonly (readonly 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(inner.length); + for (const ring of inner) this.pts(ring); this.nums.push(zRel, depth); } @@ -272,10 +306,44 @@ class FlatIfc { this.psets(o.psets); } - stair(structure: number, id: string, predefined: string, footprint: Vec2[], zRel: number, depth: number): void { + stair(structure: number, id: string, predefined: string, footprint: Vec2[], zRel: number, depth: number, parts: StairParts): void { this.nums.push(REC_STAIR, structure, this.str(id), this.str(predefined)); this.pts(footprint); this.nums.push(zRel, depth); + this.psets([]); + this.nums.push(parts.flights.length); + for (const f of parts.flights) { + this.nums.push(this.str(f.name), f.risers, f.treads, f.riserHeight, f.treadLength, this.str(f.predefined)); + this.psets(qto("Qto_StairFlightBaseQuantities", f.quantities)); + if (f.mesh) { + this.nums.push(1); + this.mesh(f.mesh.positions, f.mesh.indices, false); + } else { + const solids = f.solids ?? []; + this.nums.push(0, solids.length); + for (const s of solids) { + this.pts(s.pts); + this.nums.push(s.zRel, s.depth); + } + } + } + if (parts.landing) { + const l = parts.landing; + this.nums.push(1, this.str(l.name)); + this.pts(l.pts); + this.nums.push(l.zRel, l.depth); + this.psets(qto("Qto_SlabBaseQuantities", l.quantities)); + } else { + this.nums.push(0); + } + if (parts.rail) { + const r = parts.rail; + this.nums.push(1, this.str(r.name), this.str(r.predefined)); + this.psets(qto("Qto_RailingBaseQuantities", r.quantities)); + this.mesh(r.mesh.positions, r.mesh.indices, false); + } else { + this.nums.push(0); + } } extrusion(structure: number, id: string, pts: Vec2[], zRel: number, depth: number): void { @@ -485,6 +553,17 @@ const ROOF_PREDEFINED: Record = { const identifier = (name: string, v: string): PropIn => ({ name, ident: v }); +/** Basismengen als Pset `Qto_…` (nur wenn Mengen vorliegen). */ +function qto(name: string, quantities: readonly Qty[]): PsetIn[] { + if (quantities.length === 0) return []; + return [ + { + name, + props: quantities.map((x): PropIn => (x.kind === "length" ? { name: x.name, length: x.value } : x.kind === "area" ? { name: x.name, area: x.value } : { name: x.name, volume: x.value })), + }, + ]; +} + /** * Baut aus einem Projekt einen vollständigen IFC4-SPF-String (STEP Physical * File). Kein Datei-IO. Leeres Projekt ⇒ valider Minimal-IFC (Project/Site/Building, kein Crash). @@ -571,17 +650,18 @@ export function exportIfcSpf(projectIn: Project): string { } return out; }; - /** 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[] } => { + /** Name, Typ und Pset einer Wand (verwaister Wandtyp: Roh-ID als Name, kein Typ); `quantities` = Basismengen. */ + const wallIdentity = (wall: Wall, quantities: readonly Qty[]): { name: string; ty: TypeRefIn | null; psets: PsetIn[] } => { + const qtoSets = qto("Qto_WallBaseQuantities", quantities); try { const wt = getWallType(project, wall); return { name: wt.name, ty: typeRef(0, "STANDARD", wt), - psets: [{ name: "Pset_WallCommon", props: [identifier("Reference", wt.name)] }], + psets: [{ name: "Pset_WallCommon", props: [identifier("Reference", wt.name)] }, ...qtoSets], }; } catch { - return { name: wall.id, ty: null, psets: [] }; + return { name: wall.id, ty: null, psets: qtoSets }; } }; /** Ausdehnung aller Bänder quer zur Wandachse (entlang der linken Normalen ab `wall.start`). */ @@ -620,7 +700,7 @@ export function exportIfcSpf(projectIn: Project): string { const rect = [addScaled(s, n, -h), addScaled(e, n, -h), addScaled(e, n, h), addScaled(s, n, h)]; return { pts: rect, zRel: b.baseElevation - baseOf(structure), depth: b.height }; }); - const id = wallIdentity(wall); + const id = wallIdentity(wall, wallQuantities(wall, bands, cutouts)); // Wandsystem: Placement am Wandanfang, X = Achse, Y = linke Normale; die Schichten des Typs // stehen ab der Aussenfläche (negative Normale) nebeneinander — IfcMaterialLayerSetUsage nur, // wenn ihre Summe dem Querschnitt der Bänder entspricht (sonst wäre der Offset gelogen). @@ -663,7 +743,15 @@ export function exportIfcSpf(projectIn: Project): string { // (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 id = wallIdentity(wall); + // Netto: Volumen des Netzes (Öffnungen samt Laibungen schon ausgestanzt); ohne dichtes Netz Quader minus Löcher. + const meshBandsOfWall = bandsByWallId.get(wall.id)!; + const net = closed ? meshVolume(positions, indices) : undefined; + const quantities = wallQuantities(wall, meshBandsOfWall, cutoutsByWallId.get(wall.id) ?? [], net); + if (net === undefined) { + const gross = quantities.find((x) => x.name === "GrossVolume")!.value; + quantities.find((x) => x.name === "NetVolume")!.value = Math.max(0, gross - holeVolume(meshBandsOfWall)); + } + const id = wallIdentity(wall, quantities); flat.wallMesh(structure, wall.id, id.name, id.ty, id.psets, positions, indices, closed); hostExtent.set(wall.id, crossExtent(wall, bandsByWallId.get(wall.id)!)); } @@ -684,7 +772,10 @@ export function exportIfcSpf(projectIn: Project): string { } catch { /* verwaister Deckentyp — Roh-ID als Name, kein Typ */ } - flat.ceiling(structure, ceiling.id, name, ty, psets, ceiling.outline, zBottom - baseOf(structure), zTop - zBottom); + // Aussparungen (wie im 3D) als innere Ringe des Profils; Mengen: Netto zieht sie ab. + const inner = (ceiling.openings ?? []).filter((ring) => ring.length >= 3); + psets.push(...qto("Qto_SlabBaseQuantities", slabQuantities(ceiling.outline, inner, zTop - zBottom))); + flat.ceiling(structure, ceiling.id, name, ty, psets, ceiling.outline, inner, zBottom - baseOf(structure), zTop - zBottom); } // ── Öffnungen: IfcOpeningElement in der Wand, IfcDoor/IfcWindow darin ─── @@ -727,19 +818,19 @@ export function exportIfcSpf(projectIn: Project): string { depth, width: c.to - c.from, fill: fillParams(project, wall, opening, c, host), - psets: [{ name: psetName, props }], + psets: [{ name: psetName, props }, ...qto(isDoor ? "Qto_DoorBaseQuantities" : "Qto_WindowBaseQuantities", openingQuantities(c.to - c.from, depth))], }); } } - // ── Treppen (vereinfachter Bounding-Footprint, siehe Dateikopf) ──────── + // ── Treppen: Läufe, Podest, Geländer wie im 3D (`ifcStairs.ts`); ohne Teile der Fussabdruck-Quader ── for (const stair of project.stairs ?? []) { const footprint = stairFootprint(stair); if (footprint.length < 3) continue; const { zBottom, zTop } = stairVerticalExtent(project, stair); 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); + flat.stair(structure, stair.id, predefined, footprint, zBottom - baseOf(structure), zTop - zBottom, stairParts(project, stair, baseOf(structure))); } // ── Extrudierte Körper (truck-Integration) → IfcBuildingElementProxy ─── @@ -815,13 +906,15 @@ export function exportIfcSpf(projectIn: Project): string { const props: PropIn[] = []; if (roofType) props.push(identifier("Reference", roofType.name)); props.push({ name: "IsExternal", bool: true }); + // Mengen aus den geneigten Dachflächen (Aussenseite), wie sie auch das Netz erzeugen. + const planes = roofGeometry(roof, roofBaseElevation(project, roof)).planes.map((pl) => pl.pts); flat.roof( structure, roof.id, roofType?.name ?? "Dach", predefined, roofType ? typeRef(2, predefined, roofType) : null, - [{ name: "Pset_RoofCommon", props }], + [{ name: "Pset_RoofCommon", props }, ...qto("Qto_RoofBaseQuantities", roofQuantities(planes))], positions, indices, closed, @@ -844,7 +937,7 @@ export function exportIfcSpf(projectIn: Project): string { 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)] }], + psets: [{ name: "Pset_ColumnCommon", props: [identifier("Reference", label)] }, ...qto("Qto_ColumnBaseQuantities", columnQuantities(footprint, zTop - zBottom))], }); } flat.endColumns(); diff --git a/src/export/exportMesh.complete.test.ts b/src/export/exportMesh.complete.test.ts index 9c7db853..fe71922c 100644 --- a/src/export/exportMesh.complete.test.ts +++ b/src/export/exportMesh.complete.test.ts @@ -3,7 +3,8 @@ import { describe, it, expect } from "vitest"; import "../engine/fileioWasm.setup"; import validator from "gltf-validator"; -import { exportGlb, exportGltf, exportObj, exportStl, orientOutward } from "./exportMesh"; +import { exportGlb, exportGltf, exportObj, exportStl } from "./exportMesh"; +import { orientOutward } from "./meshOrient"; import { sampleProject } from "../model/sampleProject"; import type { Column, ImportedMesh, Project, TerrainMesh } from "../model/types"; import { emitOpeningMeshes } from "../plan/toWalls3d/openings"; diff --git a/src/export/exportMesh.ts b/src/export/exportMesh.ts index 39681d61..d7e9e15a 100644 --- a/src/export/exportMesh.ts +++ b/src/export/exportMesh.ts @@ -56,6 +56,7 @@ import { emitStairMeshes, emitStairRailings, emitStairs } from "../plan/toWalls3 import type { RMesh } from "../plan/toWalls3d/shared"; import { IMPORTED_RGB, TERRAIN_RGB, hexToRgb } from "../plan/toWalls3d/shared"; import { fileio } from "../engine/fileioWasm"; +import { orientOutward } from "./meshOrient"; /** * Ein Teil-Mesh mit EINEM Material und LOKALEN (0-basierten) Vertex-/Dreiecks-Indizes. Der Rust-Schreiber @@ -244,97 +245,6 @@ function pushPrism( } } -/** - * Richtet ein Dreiecks-Netz (Weltkoordinaten) so aus, dass die Flächennormalen nach AUSSEN zeigen: - * Dreiecke werden über gemeinsame Kanten (Eckpunkte auf 0,01 mm verschweisst) zu Zusammenhangs- - * Komponenten verbunden, jede Komponente zuerst in sich widerspruchsfrei gewickelt (Nachbarn - * durchlaufen eine gemeinsame Kante gegenläufig) und dann nach dem Vorzeichen ihres Volumens - * gedreht. Kanten mit mehr als zwei Dreiecken (Verschneidungen) verbinden nicht. Offene - * Komponenten haben kein sinnvolles Volumen und bleiben, wie sie sind (nach dem Konsistenz-Schritt). - */ -export function orientOutward(pos: readonly number[], idx: readonly number[]): number[] { - const nTri = Math.floor(idx.length / 3); - const nVert = pos.length / 3; - const weld = new Map(); - const canon = new Array(nVert); - const q = (v: number) => Math.round(v * 1e5); - for (let i = 0; i < nVert; i++) { - const key = `${q(pos[3 * i])},${q(pos[3 * i + 1])},${q(pos[3 * i + 2])}`; - let c = weld.get(key); - if (c === undefined) { - c = weld.size; - weld.set(key, c); - } - canon[i] = c; - } - const N = weld.size + 1; - // Kante (min,max) → [(Dreieck, vorwärts?)…] - const edges = new Map(); - const corner = (t: number, k: number) => canon[idx[3 * t + k]]; - for (let t = 0; t < nTri; t++) { - for (let k = 0; k < 3; k++) { - const a = corner(t, k); - const b = corner(t, (k + 1) % 3); - if (a === b) continue; - const key = Math.min(a, b) * N + Math.max(a, b); - const list = edges.get(key); - const entry = t * 2 + (a < b ? 1 : 0); - if (list) list.push(entry); - else edges.set(key, [entry]); - } - } - // Nachbarschaft über Kanten mit genau zwei Dreiecken: Wicklungs-Paritaet (0 = gleich, 1 = gegenläufig noetig). - const adj: number[][] = Array.from({ length: nTri }, () => []); - for (const list of edges.values()) { - if (list.length !== 2) continue; - const [e1, e2] = list; - const t1 = e1 >> 1; - const t2 = e2 >> 1; - if (t1 === t2) continue; - // Gleiche Durchlaufrichtung = Widerspruch ⇒ eines muss gedreht werden. - const parity = (e1 & 1) === (e2 & 1) ? 1 : 0; - adj[t1].push(t2 * 2 + parity); - adj[t2].push(t1 * 2 + parity); - } - const flip = new Array(nTri).fill(-1); - const out = idx.slice(); - for (let s = 0; s < nTri; s++) { - if (flip[s] >= 0) continue; - const comp: number[] = [s]; - flip[s] = 0; - for (let h = 0; h < comp.length; h++) { - const t = comp[h]; - for (const e of adj[t]) { - const u = e >> 1; - if (flip[u] < 0) { - flip[u] = flip[t] ^ (e & 1); - comp.push(u); - } - } - } - // Volumen der Komponente mit den bisherigen Drehungen; Offenheit: Kante mit nur einem Dreieck. - let vol = 0; - for (const t of comp) { - const [a, b, c] = flip[t] ? [idx[3 * t], idx[3 * t + 2], idx[3 * t + 1]] : [idx[3 * t], idx[3 * t + 1], idx[3 * t + 2]]; - const A = a * 3; - const B = b * 3; - const C = c * 3; - vol += - pos[A] * (pos[B + 1] * pos[C + 2] - pos[B + 2] * pos[C + 1]) - - pos[A + 1] * (pos[B] * pos[C + 2] - pos[B + 2] * pos[C]) + - pos[A + 2] * (pos[B] * pos[C + 1] - pos[B + 1] * pos[C]); - } - const turn = vol < 0 ? 1 : 0; - for (const t of comp) { - if (flip[t] ^ turn) { - out[3 * t + 1] = idx[3 * t + 2]; - out[3 * t + 2] = idx[3 * t + 1]; - } - } - } - return out; -} - /** * Hängt ein Modell-Mesh (x, y, z-hoch) an ein Teil-Mesh: Achsen nach Welt (x, z, y) und Wicklung * nach aussen. `closed`: geschlossener Körper ⇒ {@link orientOutward}; sonst (Gelände, offene diff --git a/src/export/ifcQuantities.test.ts b/src/export/ifcQuantities.test.ts new file mode 100644 index 00000000..8e6506de --- /dev/null +++ b/src/export/ifcQuantities.test.ts @@ -0,0 +1,164 @@ +// Basismengen für den IFC-Export ([B5], 28.10.): reine Rechnung aus der Geometrie, Werte nachrechenbar. +import { describe, it, expect } from "vitest"; +import type { RWall } from "../plan/toWalls3d"; +import { + columnQuantities, + flightQuantities, + meshVolume, + openingQuantities, + railingQuantities, + ringArea, + ringPerimeter, + roofQuantities, + slabQuantities, + wallQuantities, +} from "./ifcQuantities"; + +const byName = (q: { name: string; value: number }[]) => Object.fromEntries(q.map((x) => [x.name, x.value])); + +/** Wandband: Quader `len` lang entlang x ab `x0`, Dicke, Höhe ab `base`. */ +function band(x0: number, len: number, thickness: number, height: number, base = 0, topDrop?: [number, number]): RWall { + return { start: [x0, 0], end: [x0 + len, 0], thickness, height, baseElevation: base, color: [1, 1, 1], layers: [], wallId: "W", ...(topDrop ? { topDrop } : {}) }; +} + +describe("Hilfen", () => { + it("Ringfläche (unabhängig vom Umlaufsinn) und Umfang", () => { + const sq = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }, { x: 0, y: 3 }]; + expect(ringArea(sq)).toBe(12); + expect(ringArea([...sq].reverse())).toBe(12); + expect(ringPerimeter(sq)).toBe(14); + expect(ringArea([])).toBe(0); + }); + + it("Mesh-Volumen eines Würfels, unabhängig von der Wicklung", () => { + const pos = [0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0, 0, 0, 2, 2, 0, 2, 2, 2, 2, 0, 2, 2]; + const idx = [0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7]; + expect(meshVolume(pos, idx)).toBeCloseTo(8, 12); + const rev: number[] = []; + for (let i = 0; i < idx.length; i += 3) rev.push(idx[i], idx[i + 2], idx[i + 1]); + expect(meshVolume(pos, rev)).toBeCloseTo(8, 12); + expect(meshVolume([], [])).toBe(0); + }); +}); + +describe("Wand", () => { + const wall = { start: { x: 0, y: 0 }, end: { x: 5, y: 0 } }; + + it("eine Schicht: Länge, Dicke, Höhe, Seitenfläche, Volumen; Öffnung wird netto abgezogen", () => { + const q = byName( + wallQuantities(wall, [band(0, 5, 0.3, 2.6)], [{ from: 1, to: 2, zBottom: 0.9, zTop: 2.1 }]), + ); + expect(q.Length).toBe(5); + expect(q.Width).toBeCloseTo(0.3, 12); + expect(q.Height).toBeCloseTo(2.6, 12); + expect(q.GrossSideArea).toBeCloseTo(13, 12); + expect(q.NetSideArea).toBeCloseTo(13 - 1.2, 12); + expect(q.GrossVolume).toBeCloseTo(13 * 0.3, 12); + expect(q.NetVolume).toBeCloseTo((13 - 1.2) * 0.3, 12); + }); + + it("mehrere Schichten: Dicke und Volumen summieren, Öffnung schneidet jede Schicht", () => { + // Aussenschicht 0.2 (Achse −0.15 … ), Dämmung 0.1: Mittellinien bei y = −0.05 und +0.1 + const a = { ...band(0, 5, 0.2, 2.6), start: [0, -0.05], end: [5, -0.05] } as RWall; + const b = { ...band(0, 5, 0.1, 2.6), start: [0, 0.1], end: [5, 0.1] } as RWall; + const q = byName(wallQuantities(wall, [a, b], [{ from: 2, to: 3, zBottom: 0, zTop: 2.1 }])); + expect(q.Width).toBeCloseTo(0.3, 12); + expect(q.GrossVolume).toBeCloseTo(5 * 0.3 * 2.6, 12); + expect(q.NetVolume).toBeCloseTo((5 * 2.6 - 1 * 2.1) * 0.3, 12); + }); + + it("innere Schicht endet unter der Decke: Seitenfläche mit voller Wandhöhe, Volumen je Schicht", () => { + const outer = band(0, 5, 0.2, 2.6); + const inner = band(0.1, 4.8, 0.1, 2.3); + const q = byName(wallQuantities(wall, [outer, inner], [])); + expect(q.Height).toBeCloseTo(2.6, 12); + expect(q.GrossSideArea).toBeCloseTo(13, 12); + expect(q.GrossVolume).toBeCloseTo(5 * 0.2 * 2.6 + 4.8 * 0.1 * 2.3, 12); + }); + + it("Gehrung/Anschluss: kürzeres Band ändert Volumen, nicht die Wandlänge", () => { + const q = byName(wallQuantities(wall, [band(0.1, 4.8, 0.3, 2.6)], [])); + expect(q.Length).toBe(5); + expect(q.GrossVolume).toBeCloseTo(4.8 * 0.3 * 2.6, 12); + expect(q.NetVolume).toBeCloseTo(q.GrossVolume, 12); + }); + + it("schräge Oberkante: Höhe fehlt (nicht konstant), Fläche und Volumen mit mittlerer Höhe", () => { + const q = byName(wallQuantities(wall, [band(0, 5, 0.3, 3, 0, [0, 1])], [])); + expect(q.Height).toBeUndefined(); + expect(q.GrossSideArea).toBeCloseTo(5 * 2.5, 12); + expect(q.GrossVolume).toBeCloseTo(5 * 0.3 * 2.5, 12); + }); + + it("Mesh-Wand: Netto-Volumen aus dem Netz, Brutto bleibt der Quader", () => { + const q = byName(wallQuantities(wall, [band(0, 5, 0.3, 2.6)], [{ from: 1, to: 2, zBottom: 0.9, zTop: 2.1 }], 3.5)); + expect(q.NetVolume).toBe(3.5); + expect(q.GrossVolume).toBeCloseTo(13 * 0.3, 12); + }); + + it("Öffnung grösser als die Wand: Netto nie negativ; Öffnung ausserhalb zieht nichts ab", () => { + const q = byName(wallQuantities(wall, [band(0, 5, 0.3, 2.6)], [{ from: -1, to: 6, zBottom: -1, zTop: 5 }, { from: 8, to: 9, zBottom: 0, zTop: 2 }])); + expect(q.NetSideArea).toBe(0); + expect(q.NetVolume).toBeCloseTo(0, 12); + }); + + it("keine Bänder: keine Mengen", () => { + expect(wallQuantities(wall, [], [])).toEqual([]); + }); +}); + +describe("Decke, Dach, Stütze, Öffnung, Treppe", () => { + it("Decke: Fläche, Umfang, Dicke; Aussparung nur netto", () => { + const outline = [{ x: 0, y: 0 }, { x: 5, y: 0 }, { x: 5, y: 4 }, { x: 0, y: 4 }]; + const hole = [{ x: 1, y: 1 }, { x: 2, y: 1 }, { x: 2, y: 2 }, { x: 1, y: 2 }]; + const q = byName(slabQuantities(outline, [hole], 0.2)); + expect(q.Width).toBeCloseTo(0.2, 12); + expect(q.Perimeter).toBe(18); + expect(q.GrossArea).toBe(20); + expect(q.NetArea).toBe(19); + expect(q.GrossVolume).toBeCloseTo(4, 12); + expect(q.NetVolume).toBeCloseTo(3.8, 12); + }); + + it("Dach: geneigte Fläche > Grundrissfläche (Satteldach 30°)", () => { + // Zwei Flächen 5 × 2 m Grundriss, 30° geneigt: je 5 × 2/cos(30°). + const h = Math.tan(Math.PI / 6) * 2; + const planes = [ + [[0, 0, 0], [5, 0, 0], [5, 2, h], [0, 2, h]], + [[0, 4, 0], [0, 2, h], [5, 2, h], [5, 4, 0]], + ] as [number, number, number][][]; + const q = byName(roofQuantities(planes)); + expect(q.ProjectedArea).toBeCloseTo(20, 9); + expect(q.GrossArea).toBeCloseTo(20 / Math.cos(Math.PI / 6), 9); + expect(q.NetArea).toBe(q.GrossArea); + }); + + it("Stütze 0.3 × 0.3 × 2.6", () => { + const fp = [{ x: 0, y: 0 }, { x: 0.3, y: 0 }, { x: 0.3, y: 0.3 }, { x: 0, y: 0.3 }]; + const q = byName(columnQuantities(fp, 2.6)); + expect(q.Length).toBe(2.6); + expect(q.CrossSectionArea).toBeCloseTo(0.09, 12); + expect(q.OuterSurfaceArea).toBeCloseTo(1.2 * 2.6, 12); + expect(q.NetSurfaceArea).toBeCloseTo(1.2 * 2.6 + 0.18, 12); + expect(q.GrossVolume).toBeCloseTo(0.09 * 2.6, 12); + expect(q.NetVolume).toBeCloseTo(q.GrossVolume, 12); + }); + + it("Fenster/Tür: Breite, Höhe, Umfang, Fläche", () => { + const q = byName(openingQuantities(1.2, 1.5)); + expect(q.Width).toBe(1.2); + expect(q.Height).toBe(1.5); + expect(q.Perimeter).toBeCloseTo(5.4, 12); + expect(q.Area).toBeCloseTo(1.8, 12); + }); + + it("Lauf und Geländer", () => { + expect(byName(flightQuantities(3.4, 1.2))).toEqual({ Length: 3.4, GrossVolume: 1.2, NetVolume: 1.2 }); + expect(byName(railingQuantities(5))).toEqual({ Length: 5 }); + }); + + it("nie NaN/negativ: kaputte Eingaben ergeben 0", () => { + const q = openingQuantities(Number.NaN, -1); + for (const x of q) expect(Number.isFinite(x.value) && x.value >= 0).toBe(true); + }); +}); diff --git a/src/export/ifcQuantities.ts b/src/export/ifcQuantities.ts new file mode 100644 index 00000000..6c89b42f --- /dev/null +++ b/src/export/ifcQuantities.ts @@ -0,0 +1,213 @@ +// Basismengen (Qto_*BaseQuantities) für den IFC-Export ([B5], 28.10.): Längen, Flächen und Volumen +// aus derselben Geometrie, die in die Datei geschrieben wird — für Kostenplanung (eBKP-H/BKP) und +// Mengenermittlung. Reine Rechnung auf einfachen Eingaben (Bänder, Ringe, Netze), kein Zugriff auf +// das Projekt; `exportIfc.ts` sammelt und ruft sie auf, Rust schreibt die IfcElementQuantity. +// +// Netto = abzüglich Öffnungen (Wand, Decke). Fehlt einer Menge die Grundlage (z. B. Höhe bei schräger +// Wandoberkante: „nur angeben, wenn konstant“), lassen wir sie weg statt zu raten. + +import type { Vec2 } from "../model/types"; +import type { RWall } from "../plan/toWalls3d"; + +/** Eine Menge: Name nach IFC4-Vorlage, Art (Länge/Fläche/Volumen) und Wert (immer endlich und ≥ 0). */ +export interface Qty { + name: string; + kind: "length" | "area" | "volume"; + value: number; +} + +/** Rundungsfehler und kaputte Eingaben (NaN) auf 0, nie negativ. */ +const clean = (v: number): number => (Number.isFinite(v) && v > 0 ? v : 0); +const q = (name: string, kind: Qty["kind"], value: number): Qty => ({ name, kind, value: clean(value) }); +const len = (name: string, v: number) => q(name, "length", v); +const area = (name: string, v: number) => q(name, "area", v); +const vol = (name: string, v: number) => q(name, "volume", v); + +/** Fläche eines Rings (Shoelace, unabhängig vom Umlaufsinn); offener Ring, die Schlusskante gilt als gegeben. */ +export function ringArea(pts: readonly Vec2[]): number { + let a = 0; + for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) a += pts[j].x * pts[i].y - pts[i].x * pts[j].y; + return Math.abs(a) / 2; +} + +/** Umfang eines geschlossenen Rings. */ +export function ringPerimeter(pts: readonly Vec2[]): number { + let p = 0; + for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) p += Math.hypot(pts[i].x - pts[j].x, pts[i].y - pts[j].y); + return p; +} + +/** Volumen eines geschlossenen Dreiecks-Netzes (Betrag der Summe der Tetraeder-Volumen zum Ursprung). */ +export function meshVolume(positions: readonly number[], indices: readonly number[]): number { + let v = 0; + for (let i = 0; i + 2 < indices.length; i += 3) { + const a = indices[i] * 3; + const b = indices[i + 1] * 3; + const c = indices[i + 2] * 3; + v += + positions[a] * (positions[b + 1] * positions[c + 2] - positions[b + 2] * positions[c + 1]) - + positions[a + 1] * (positions[b] * positions[c + 2] - positions[b + 2] * positions[c]) + + positions[a + 2] * (positions[b] * positions[c + 1] - positions[b + 1] * positions[c]); + } + return Math.abs(v) / 6; +} + +/** Öffnung einer Wand: Achs-Intervall (ab Wandanfang) und absolute Höhen. */ +export interface Cutout { + from: number; + to: number; + zBottom: number; + zTop: number; +} + +const overlap = (a0: number, a1: number, b0: number, b1: number): number => Math.max(0, Math.min(a1, b1) - Math.max(a0, b0)); + +/** + * Wand-Basismengen aus den Schicht-Bändern (dieselben wie im 3D) und den Öffnungen. + * • Length: Achslänge; Width: Gesamtdicke quer zur Achse; Height: nur bei konstanter Höhe. + * • GrossSideArea: Achslänge × Wandhöhe (schräge Oberkante: höchste mittlere Bandhöhe); + * NetSideArea: abzüglich der Öffnungsflächen. + * • GrossVolume: Summe der Band-Quader (Gehrungen/Anschlüsse stecken in den Bandlängen); + * NetVolume: abzüglich der Öffnungen je Band — oder `netVolume`, wenn die Wand als Netz mit schon + * ausgestanzten Öffnungen (und Laibungen) geschrieben wird. + */ +export function wallQuantities( + wall: { start: Vec2; end: Vec2 }, + bands: readonly RWall[], + cutouts: readonly Cutout[], + netVolume?: number, +): Qty[] { + if (bands.length === 0) return []; + const axisLen = Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y); + const ux = axisLen > 0 ? (wall.end.x - wall.start.x) / axisLen : 1; + const uy = axisLen > 0 ? (wall.end.y - wall.start.y) / axisLen : 0; + // Quer zur Achse: Ausdehnung aller Bänder entlang der linken Normalen (−uy, ux). + let nLo = Infinity; + let nHi = -Infinity; + let zMin = Infinity; + let zMax = -Infinity; + let sloped = false; + let gross = 0; + let tallest = 0; + for (const b of bands) { + const l = Math.hypot(b.end[0] - b.start[0], b.end[1] - b.start[1]); + const off = -(b.start[0] - wall.start.x) * uy + (b.start[1] - wall.start.y) * ux; + nLo = Math.min(nLo, off - b.thickness / 2); + nHi = Math.max(nHi, off + b.thickness / 2); + zMin = Math.min(zMin, b.baseElevation); + zMax = Math.max(zMax, b.baseElevation + b.height); + const drop = b.topDrop ? (b.topDrop[0] + b.topDrop[1]) / 2 : 0; + if (b.topDrop && (Math.abs(b.topDrop[0]) > 1e-9 || Math.abs(b.topDrop[1]) > 1e-9)) sloped = true; + gross += l * b.thickness * (b.height - drop); + tallest = Math.max(tallest, b.height - drop); + } + // Seitenfläche der Wandebene: innere Schichten enden oft unter der Decke (niedrigere Bänder), die Wand + // selbst reicht über die volle Höhe — bei konstanter Oberkante zählt die Gesamthöhe, bei schräger die + // höchste mittlere Bandhöhe. + const grossSide = axisLen * (sloped ? tallest : zMax - zMin); + let cutSide = 0; + let cutVolume = 0; + for (const c of cutouts) { + cutSide += (c.to - c.from) * overlap(c.zBottom, c.zTop, zMin, zMax); + for (const b of bands) { + const a0 = (b.start[0] - wall.start.x) * ux + (b.start[1] - wall.start.y) * uy; + const a1 = (b.end[0] - wall.start.x) * ux + (b.end[1] - wall.start.y) * uy; + const ox = overlap(Math.min(a0, a1), Math.max(a0, a1), c.from, c.to); + cutVolume += ox * overlap(c.zBottom, c.zTop, b.baseElevation, b.baseElevation + b.height) * b.thickness; + } + } + // Netto aus dem Netz kann den Band-Quader um Rundung/Gehrungsdetails überschreiten: Brutto nie unter Netto. + const net = netVolume ?? Math.max(0, gross - cutVolume); + gross = Math.max(gross, net); + const out: Qty[] = [len("Length", axisLen), len("Width", nHi - nLo)]; + if (!sloped && zMax - zMin > 0) out.push(len("Height", zMax - zMin)); + out.push( + area("GrossSideArea", grossSide), + area("NetSideArea", Math.max(0, grossSide - cutSide)), + vol("GrossVolume", gross), + vol("NetVolume", net), + ); + return out; +} + +/** Brutto-Volumen der Löcher in einem Band (für Netz-Wände ohne Netz-Volumen, s. `wallQuantities`). */ +export function holeVolume(bands: readonly RWall[]): number { + let v = 0; + for (const b of bands) for (const h of b.holes ?? []) v += (h.to - h.from) * overlap(h.zBottom, h.zTop, b.baseElevation, b.baseElevation + b.height) * b.thickness; + return v; +} + +/** + * Platten-Basismengen (Decke, Podest): Dicke, Umfang der Aussenkontur, Flächen und Volumen; Netto + * zieht die Aussparungen ab. + */ +export function slabQuantities(outline: readonly Vec2[], openings: readonly (readonly Vec2[])[], thickness: number): Qty[] { + const gross = ringArea(outline); + const net = Math.max(0, gross - openings.reduce((s, r) => s + ringArea(r), 0)); + return [ + len("Width", thickness), + len("Perimeter", ringPerimeter(outline)), + area("GrossArea", gross), + area("NetArea", net), + vol("GrossVolume", gross * thickness), + vol("NetVolume", net * thickness), + ]; +} + +type Vec3 = readonly [number, number, number]; + +/** + * Dach-Basismengen aus den geneigten Dachflächen (Aussenseite): geneigte Fläche (brutto = netto, das + * Modell kennt keine Dachfenster/Aussparungen) und Grundrissprojektion. + */ +export function roofQuantities(planes: readonly (readonly Vec3[])[]): Qty[] { + let sloped = 0; + let projected = 0; + for (const pts of planes) { + // Newell: Vektorfläche des Polygons; Betrag = Fläche, z-Anteil = Projektion auf den Grundriss. + let nx = 0; + let ny = 0; + let nz = 0; + for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { + const c = pts[j]; + const d = pts[i]; + nx += (c[1] - d[1]) * (c[2] + d[2]); + ny += (c[2] - d[2]) * (c[0] + d[0]); + nz += (c[0] - d[0]) * (c[1] + d[1]); + } + sloped += Math.hypot(nx, ny, nz) / 2; + projected += Math.abs(nz) / 2; + } + return [area("GrossArea", sloped), area("NetArea", sloped), area("ProjectedArea", projected)]; +} + +/** Stützen-Basismengen: Länge, Querschnitt, Mantel, Oberfläche und Volumen (keine Aussparungen). */ +export function columnQuantities(footprint: readonly Vec2[], length: number): Qty[] { + const cross = ringArea(footprint); + const outer = ringPerimeter(footprint) * length; + return [ + len("Length", length), + area("CrossSectionArea", cross), + area("OuterSurfaceArea", outer), + area("NetSurfaceArea", outer + 2 * cross), + vol("GrossVolume", cross * length), + vol("NetVolume", cross * length), + ]; +} + +/** Tür-/Fenster-Basismengen (lichte Öffnung): Breite, Höhe, Umfang, Fläche. */ +export function openingQuantities(width: number, height: number): Qty[] { + const w = clean(width); + const h = clean(height); + return [len("Width", w), len("Height", h), len("Perimeter", 2 * (w + h)), area("Area", w * h)]; +} + +/** Treppenlauf: Lauflänge entlang der Lauflinie und Volumen (keine Aussparungen). */ +export function flightQuantities(length: number, volume: number): Qty[] { + return [len("Length", length), vol("GrossVolume", volume), vol("NetVolume", volume)]; +} + +/** Geländer: Länge. */ +export function railingQuantities(length: number): Qty[] { + return [len("Length", length)]; +} diff --git a/src/export/ifcStairs.ts b/src/export/ifcStairs.ts new file mode 100644 index 00000000..55f9eba9 --- /dev/null +++ b/src/export/ifcStairs.ts @@ -0,0 +1,170 @@ +// Treppen im IFC-Export ([B5], 28.10.): statt eines Fussabdruck-Quaders die Teile der Treppe wie im 3D — +// Läufe (IfcStairFlight), Podest (IfcSlab LANDING) und Handlauf/Pfosten (IfcRailing), zusammengefasst +// von der IfcStair (IfcRelAggregates). Quelle sind dieselben Ableitungen wie im 3D-Viewer +// (`emitStairs` Tritt-Prismen und Podest, `emitStairMeshes` glatte Ortbeton-Laufplatte, +// `emitStairRailings`), je Treppe mit einem Ein-Treppen-Projekt aufgerufen (die Ableitungen liefern keine +// ids). Dieses Modul sammelt und rechnet die Basismengen; die Entitäten schreibt Rust (`ifc_export.rs`, STAIR). +// +// Zuordnung der Tritt-Prismen: bei "L" ist das Podest das Prisma mit dem Umriss des Podest-Polygons der +// Treppengeometrie; Tritte bis zur Podest-Oberkante gehören zum ersten, die darüber zum zweiten Lauf. +// Gerade und Wendeltreppen haben einen Lauf (die Wendel-Mitte bleibt Teil davon, wie im 3D). + +import type { Project, Stair, Vec2 } from "../model/types"; +import { getStairType } from "../model/types"; +import { stairVerticalExtent } from "../model/wall"; +import { stairGeometry } from "../geometry/stair"; +import { emitStairMeshes, emitStairRailings, emitStairs } from "../plan/toWalls3d/stairs"; +import type { RSlab } from "../plan/toWalls3d"; +import { orientOutward } from "./meshOrient"; +import { flightQuantities, meshVolume, railingQuantities, ringArea, slabQuantities, type Qty } from "./ifcQuantities"; + +/** Ein Prisma (Profil in Welt-XY, Unterkante relativ zum Geschoss, Tiefe). */ +export interface StairSolid { + pts: Vec2[]; + zRel: number; + depth: number; +} + +export interface StairFlightParts { + name: string; + risers: number; + treads: number; + riserHeight: number; + treadLength: number; + /** IfcStairFlightTypeEnum. */ + predefined: "STRAIGHT" | "SPIRAL"; + quantities: Qty[]; + /** Entweder Prismen oder ein Dreiecks-Netz (IFC: x, y, z-hoch, Z relativ zum Geschoss). */ + solids?: StairSolid[]; + mesh?: { positions: number[]; indices: number[] }; +} + +export interface StairParts { + flights: StairFlightParts[]; + landing: { name: string; pts: Vec2[]; zRel: number; depth: number; quantities: Qty[] } | null; + rail: { name: string; predefined: "HANDRAIL"; mesh: { positions: number[]; indices: number[] }; quantities: Qty[] } | null; +} + +const EPS = 1e-6; + +/** Gleicher Umriss (gleiche Punktmenge, auch bei anderer Reihenfolge/Startpunkt). */ +function sameRing(a: readonly [number, number][], b: readonly Vec2[]): boolean { + if (a.length !== b.length) return false; + return a.every((p) => b.some((q) => Math.abs(p[0] - q.x) < EPS && Math.abs(p[1] - q.y) < EPS)); +} + +const centroid = (pts: readonly Vec2[]): Vec2 => ({ + x: pts.reduce((s, p) => s + p.x, 0) / pts.length, + y: pts.reduce((s, p) => s + p.y, 0) / pts.length, +}); + +/** Netz (Modell x, y, z-hoch) nach IFC: Z relativ zum Geschoss, Wicklung nach aussen. */ +function ifcMesh(positions: readonly number[], indices: readonly number[], base: number): { positions: number[]; indices: number[] } { + const pos = positions.slice(); + for (let i = 2; i < pos.length; i += 3) pos[i] -= base; + return { positions: pos, indices: orientOutward(pos, indices) }; +} + +/** + * Teile einer Treppe für den IFC-Export; `base` = Oberkante des Geschosses, dem die Treppe zugeordnet + * ist (Z-Werte werden relativ dazu geschrieben). Leere Teile (keine Geometrie) ergeben `flights: []`, + * `landing: null`, `rail: null` — der Aufrufer fällt dann auf den Fussabdruck zurück. + */ +export function stairParts(project: Project, stair: Stair, base: number): StairParts { + const one: Project = { ...project, stairs: [stair] }; + const { zBottom, zTop } = stairVerticalExtent(project, stair); + const rise = zTop - zBottom; + const geo = stairGeometry(stair, rise); + const slabs = emitStairs(one); + const meshes = emitStairMeshes(one); + const predefined = stair.shape === "spiral" ? "SPIRAL" : "STRAIGHT"; + + // Podest nur bei "L" (bei der Wendel ist das Polygon die Treppenmitte, Teil des Laufs). + let landingSlab: RSlab | undefined; + if (stair.shape === "L" && geo.landing) landingSlab = slabs.find((s) => sameRing(s.outline, geo.landing as Vec2[])); + const treadSlabs = slabs.filter((s) => s !== landingSlab); + + const solidOf = (s: RSlab): StairSolid => ({ pts: s.outline.map(([x, y]) => ({ x, y })), zRel: s.zBottom - base, depth: s.zTop - s.zBottom }); + const groups: RSlab[][] = []; + if (landingSlab) { + const top = landingSlab.zTop + EPS; + const lower = treadSlabs.filter((s) => s.zTop <= top); + const upper = treadSlabs.filter((s) => s.zTop > top); + for (const g of [lower, upper]) if (g.length > 0) groups.push(g); + } else if (treadSlabs.length > 0) { + groups.push(treadSlabs); + } + + const flights: StairFlightParts[] = []; + groups.forEach((g, k) => { + // Tritte = verschiedene Oberkanten (Setzstufen-Platten und Nasen teilen die Höhe ihres Tritts). + const tops = [...new Set(g.map((s) => Math.round(s.zTop / 1e-4)))]; + const treads = tops.length; + // Lauflänge: Weg zwischen erstem und letztem Tritt (Schwerpunkte) plus eine Trittiefe, mit der Steigung. + const lowest = g.reduce((m, s) => (s.zTop < m.zTop ? s : m), g[0]); + const highest = g.reduce((m, s) => (s.zTop > m.zTop ? s : m), g[0]); + const c0 = centroid(solidOf(lowest).pts); + const c1 = centroid(solidOf(highest).pts); + const run = Math.hypot(c1.x - c0.x, c1.y - c0.y) + geo.treadDepth; + const lift = highest.zTop - lowest.zTop + geo.riserHeight; + const solids = g.map(solidOf); + const volume = g.reduce((s, x) => s + ringArea(x.outline.map(([px, py]) => ({ x: px, y: py }))) * (x.zTop - x.zBottom), 0); + flights.push({ + name: groups.length > 1 ? `Lauf ${k + 1}` : "Lauf", + risers: treads, + treads, + riserHeight: geo.riserHeight, + treadLength: geo.treadDepth, + predefined, + quantities: flightQuantities(Math.hypot(run, lift), volume), + solids, + }); + }); + // Glatte Ortbeton-Laufplatte (gerade Betontreppe): ein Lauf als Netz. + if (meshes.length > 0) { + const positions: number[] = []; + const indices: number[] = []; + for (const m of meshes) { + const at = positions.length / 3; + for (const v of m.positions) positions.push(v); + for (const i of m.indices) indices.push(at + i); + } + const mesh = ifcMesh(positions, indices, base); + flights.push({ + name: flights.length > 0 ? `Lauf ${flights.length + 1}` : "Lauf", + risers: geo.treads.length, + treads: geo.treads.length, + riserHeight: geo.riserHeight, + treadLength: geo.treadDepth, + predefined, + quantities: flightQuantities(Math.hypot(stair.runLength, rise), meshVolume(mesh.positions, mesh.indices)), + mesh, + }); + } + + let landing: StairParts["landing"] = null; + if (landingSlab) { + const s = solidOf(landingSlab); + landing = { name: "Podest", pts: s.pts, zRel: s.zRel, depth: s.depth, quantities: slabQuantities(s.pts, [], s.depth) }; + } + + let rail: StairParts["rail"] = null; + const railMeshes = emitStairRailings(one); + if (railMeshes.length > 0) { + const positions: number[] = []; + const indices: number[] = []; + for (const m of railMeshes) { + const at = positions.length / 3; + for (const v of m.positions) positions.push(v); + for (const i of m.indices) indices.push(at + i); + } + const sides = getStairType(project, stair)?.railing === "beide" ? 2 : 1; + rail = { + name: "Handlauf", + predefined: "HANDRAIL", + mesh: ifcMesh(positions, indices, base), + quantities: railingQuantities(Math.hypot(stair.runLength, rise) * sides), + }; + } + return { flights, landing, rail }; +} diff --git a/src/export/meshOrient.ts b/src/export/meshOrient.ts new file mode 100644 index 00000000..baec14bb --- /dev/null +++ b/src/export/meshOrient.ts @@ -0,0 +1,94 @@ +// Wicklung von Dreiecks-Netzen nach aussen ausrichten — gemeinsam für Mesh-Export (OBJ/STL/glTF) und +// IFC-Export. Die 3D-Ableitungen (`plan/toWalls3d/*`) liefern keine verlässliche Wicklung, weil render3d +// doppelseitig zeichnet; Dateiformate verlangen sie. + +/** + * Richtet ein Dreiecks-Netz (Weltkoordinaten) so aus, dass die Flächennormalen nach AUSSEN zeigen: + * Dreiecke werden über gemeinsame Kanten (Eckpunkte auf 0,01 mm verschweisst) zu Zusammenhangs- + * Komponenten verbunden, jede Komponente zuerst in sich widerspruchsfrei gewickelt (Nachbarn + * durchlaufen eine gemeinsame Kante gegenläufig) und dann nach dem Vorzeichen ihres Volumens + * gedreht. Kanten mit mehr als zwei Dreiecken (Verschneidungen) verbinden nicht. Offene + * Komponenten haben kein sinnvolles Volumen und bleiben, wie sie sind (nach dem Konsistenz-Schritt). + */ +export function orientOutward(pos: readonly number[], idx: readonly number[]): number[] { + const nTri = Math.floor(idx.length / 3); + const nVert = pos.length / 3; + const weld = new Map(); + const canon = new Array(nVert); + const q = (v: number) => Math.round(v * 1e5); + for (let i = 0; i < nVert; i++) { + const key = `${q(pos[3 * i])},${q(pos[3 * i + 1])},${q(pos[3 * i + 2])}`; + let c = weld.get(key); + if (c === undefined) { + c = weld.size; + weld.set(key, c); + } + canon[i] = c; + } + const N = weld.size + 1; + // Kante (min,max) → [(Dreieck, vorwärts?)…] + const edges = new Map(); + const corner = (t: number, k: number) => canon[idx[3 * t + k]]; + for (let t = 0; t < nTri; t++) { + for (let k = 0; k < 3; k++) { + const a = corner(t, k); + const b = corner(t, (k + 1) % 3); + if (a === b) continue; + const key = Math.min(a, b) * N + Math.max(a, b); + const list = edges.get(key); + const entry = t * 2 + (a < b ? 1 : 0); + if (list) list.push(entry); + else edges.set(key, [entry]); + } + } + // Nachbarschaft über Kanten mit genau zwei Dreiecken: Wicklungs-Paritaet (0 = gleich, 1 = gegenläufig noetig). + const adj: number[][] = Array.from({ length: nTri }, () => []); + for (const list of edges.values()) { + if (list.length !== 2) continue; + const [e1, e2] = list; + const t1 = e1 >> 1; + const t2 = e2 >> 1; + if (t1 === t2) continue; + // Gleiche Durchlaufrichtung = Widerspruch ⇒ eines muss gedreht werden. + const parity = (e1 & 1) === (e2 & 1) ? 1 : 0; + adj[t1].push(t2 * 2 + parity); + adj[t2].push(t1 * 2 + parity); + } + const flip = new Array(nTri).fill(-1); + const out = idx.slice(); + for (let s = 0; s < nTri; s++) { + if (flip[s] >= 0) continue; + const comp: number[] = [s]; + flip[s] = 0; + for (let h = 0; h < comp.length; h++) { + const t = comp[h]; + for (const e of adj[t]) { + const u = e >> 1; + if (flip[u] < 0) { + flip[u] = flip[t] ^ (e & 1); + comp.push(u); + } + } + } + // Volumen der Komponente mit den bisherigen Drehungen; Offenheit: Kante mit nur einem Dreieck. + let vol = 0; + for (const t of comp) { + const [a, b, c] = flip[t] ? [idx[3 * t], idx[3 * t + 2], idx[3 * t + 1]] : [idx[3 * t], idx[3 * t + 1], idx[3 * t + 2]]; + const A = a * 3; + const B = b * 3; + const C = c * 3; + vol += + pos[A] * (pos[B + 1] * pos[C + 2] - pos[B + 2] * pos[C + 1]) - + pos[A + 1] * (pos[B] * pos[C + 2] - pos[B + 2] * pos[C]) + + pos[A + 2] * (pos[B] * pos[C + 1] - pos[B + 1] * pos[C]); + } + const turn = vol < 0 ? 1 : 0; + for (const t of comp) { + if (flip[t] ^ turn) { + out[3 * t + 1] = idx[3 * t + 2]; + out[3 * t + 2] = idx[3 * t + 1]; + } + } + } + return out; +} diff --git a/src/io/ifcElements.test.ts b/src/io/ifcElements.test.ts index 6397c483..0571b01b 100644 --- a/src/io/ifcElements.test.ts +++ b/src/io/ifcElements.test.ts @@ -33,8 +33,8 @@ describe("IFC-Import als Bauteile: Rundreise Demo-Haus", () => { const { project: p, summary, report } = await importInto(emptyProject, sampleProject); expect(report.parseErrors).toBe(0); expect(summary).toMatchObject({ walls: 9, openings: 3, ceilings: 1, columns: 0, rooms: 1, floors: 0, wallTypes: 0, ceilingTypes: 0, components: 0, kept: 0 }); - // Dach und Treppe bleiben Kontext-Mesh. - expect((p.context ?? []).map((c) => (c as { layer?: string }).layer).sort()).toEqual(["IfcRoof", "IfcStair"]); + // Dach und Treppenlauf (die IfcStair selbst hat keine Darstellung) bleiben Kontext-Mesh. + expect((p.context ?? []).map((c) => (c as { layer?: string }).layer).sort()).toEqual(["IfcRoof", "IfcStairFlight"]); expect(validateProject(p)).toEqual([]); const byOrig = new Map(); diff --git a/src/io/ifcImport.test.ts b/src/io/ifcImport.test.ts index 0a8987bf..0a8138a0 100644 --- a/src/io/ifcImport.test.ts +++ b/src/io/ifcImport.test.ts @@ -40,7 +40,7 @@ const bytesOf = (s: string) => new TextEncoder().encode(s); /** Bauteile je IFC-Klasse aus dem Export-Text (Zeilen `#n=IFCWALL(`). */ function exportedCounts(ifc: string): Map { const m = new Map(); - for (const cls of ["IFCWALL", "IFCSLAB", "IFCROOF", "IFCDOOR", "IFCWINDOW", "IFCSTAIR", "IFCCOLUMN", "IFCBUILDINGELEMENTPROXY"]) { + for (const cls of ["IFCWALL", "IFCSLAB", "IFCROOF", "IFCDOOR", "IFCWINDOW", "IFCSTAIRFLIGHT", "IFCRAILING", "IFCCOLUMN", "IFCBUILDINGELEMENTPROXY"]) { const n = (ifc.match(new RegExp(`^#\\d+=${cls}\\(`, "gm")) ?? []).length; if (n) m.set(cls, n); }