diff --git a/TODO.md b/TODO.md index eccbaa30..fa9089dd 100644 --- a/TODO.md +++ b/TODO.md @@ -353,8 +353,25 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module - ✅ Georeferenz [69]. - ○ Offen: IsExternal/LoadBearing/ThermalTransmittance für Wand/Decke/Tür/Fenster brauchen Modellfelder (z. B. am Wandtyp tragend/aussen, λ je Bauteil → U-Wert). · S–M - - ○ Offen: IfcMaterialLayerSetUsage + Achs-Darstellung („Axis") an Extrusions-Wänden; - Tür/Fenster mit Rahmen/Blatt statt Box; Bogenwände als echte Kurve. · M + - ✅ IfcMaterialLayerSetUsage + Achs-Darstellung an Extrusions-Wänden. (28.10.) Wand-Placement am + Wandanfang, X = Achse, Y = linke Normale (Rust rechnet die Welt-Profile und die Öffnungen ins + Wandsystem); „Axis“-Darstellung (IfcPolyline, Unterkontext GRAPH_VIEW) + Usage (AXIS2, POSITIVE, + Offset = Abstand der Aussenschicht von der Achse), nur wenn die Typ-Schichten den Bandquerschnitt + füllen. Mesh-Wände (schräge Oberkante, Laibung) bleiben ohne Achse/Usage. ifcopenshell liest + Achse = Wandachse (auch schräg/rückwärts gezeichnet) und die Bänder in Schichtreihenfolge ab Offset. + Offen: nicht in Revit/ArchiCAD geöffnet. + - ✅ Tür/Fenster mit echter Geometrie statt Box. (28.10.) `export/ifcOpenings.ts`: Fenster = Blendrahmen + (4 Teile) + Mittelpfosten + eine Glasscheibe je Flügel (Flügeltabelle/`wingCount`), Tür = Zarge (3 Teile) + + Blatt/Blätter (Glastür: Rahmen um eine Glasfläche = `glazingRatio`, Oberlicht mit Kämpfer); getrennte + Körper in einer Darstellung, je mit IfcStyledItem (Rahmen/Blatt/Glas mit Transparenz). Masse aus dem + Modell (Rahmenbreite/-tiefe, Schichteinzug, Verglasung), sonst die Konstanten des 3D (6 cm, 7 cm, Blatt + 4 cm; Glaspaket 6/24/36 mm). Eigenes Füllungs-Placement (Tür: Y = Aufschlagrichtung). OperationType + (Blattzahl, Scharnierseite, Schiebe) und PartitioningType (1–3 Flügel). Reine Wandöffnung: kein Körper. + Geprüft: ifcopenshell (0 Befunde; Volumen Rahmen + Glas, Welt-Lage, Stile je Körper), Modell-Rechnung + in `ifcOpenings.test.ts`. Offen: LEFT/RIGHT der Tür nach IFC-Konvention (Blick von der Aufschlagseite) + gelesen, nicht in Revit/ArchiCAD gegengeprüft; ohne Sprossen, Fensterbank, Rollladenkasten, Schwelle, + Flügelrahmen. + - ○ Offen: Bogenwände als echte Kurve. · M - ✅ Eigener IFC-Import ([B3]) zieht Öffnungen ab (28.10.): Rundreise vergleicht alle Wände mit dem ausgeschnittenen Volumen (`ifcImport.test.ts`). - ✅ Export nach Rust. (28.10.) `src-tauri/fileio/src/ifc_export.rs` schreibt die STEP-Datei @@ -411,16 +428,22 @@ Code-Übernahme Lizenz der Abhängigkeiten prüfen, Pflicht [51]. Reihenfolge, Ebenen, Strichstärken, True-Color, Koordinaten ≤ 5e-7 m (Rundung des alten Writers auf 6 Stellen; neu volle f64). Neu: 2D-Texte als TEXT (fehlten bisher), CLI exportiert georeferenziert wie die App. Gegencheck ezdxf (`scripts/validate-dxf.py`, Test übersprungen ohne `pip install ezdxf`): 0 Auditor-Fehler. - Offen: Binär-DXF-Export. + - ✅ **Binär-DXF-Export** (28.10.): `export_dxf_binary` (acadrust `DxfWriter::new_binary`, R2018 UTF-8), + Dialog-Format „DXF binär“, CLI `dxf --binary`. Rundreise acadrust + ezdxf (gleiche Entitäten/Ebenen wie + ASCII, 0 Auditor-Fehler, kleiner als der Text). Offen: in AutoCAD/BricsCAD selbst nicht geöffnet. + - ✅ **Verlauf als echte Gradient-HATCH** (28.10.): `kind === "gradient"` → neuer Datensatz `REC_GRADIENT` + (`export.rs`): Name LINEAR/SPHERICAL, Farbstützen 0/1, Winkel = SVG-Richtung der Ansicht. ezdxf liest + Name, Rotation und beide Farben. Offen: Aussehen/Richtung in AutoCAD selbst ungeprüft (Winkel 0 = + Farbe 1 links angenommen); mehr als zwei Farbstützen kennt das Modell nicht. - ✅ **Export: echte HATCH-Entitäten** (28.10.): Schraffuren (`pattern` diagonal/Kreuz/Dämmung/frei, auch gestrichelt) und Vollfüllungen gehen als HATCH ins DXF/DWG statt als einzelne geklippte Linien: Rand = geschlossene Polylinienkante des Plan-Polygons, Musterzeilen aus Winkel und Linienabstand (Versatz schon gedreht, Strich-/Lückenfolge als `dash_lengths`), Vordergrundfarbe als True-Color, Ebene `HATCH`, vor dem Umriss gezeichnet (neuer flacher Datensatz `REC_HATCH`, `export.rs`). Zufallsstriche (`random`) haben - kein Musteräquivalent und bleiben Linien; Bild-/Verlauf-Schraffur wie bisher nur Umriss. Geprüft: + kein Musteräquivalent und bleiben Linien; Bild-Schraffur wie bisher nur Umriss (Verlauf: s. u.). Geprüft: acadrust-Rundreise DXF und DWG, ezdxf (Auditor 0 Fehler, Rand/Farbe/Musterzeilen), libredwg zählt gleiche Typen. Offen: Aussehen in AutoCAD/BricsCAD selbst nicht geprüft (Musterphase ab Ursprung bei - LV95-Koordinaten); Verlauf als echte Gradient-HATCH möglich (acadrust kann es), noch nicht umgesetzt. + LV95-Koordinaten); Verlauf siehe unten (jetzt Gradient-HATCH). - ✅ **DXF-Import in Rust** (28.10.): statt eigenem Tag-Reader acadrust (ASCII und Binär, R12–2018+, Code-Seiten) in `fileio/src/import.rs` → flacher f64-Puffer + String-Tabelle, dekodiert in `io/dxfParser.ts` (Rückgabetyp unverändert, neu `insUnits`). dxf-parser entfernt; Aufteilung grosser diff --git a/scripts/validate-dxf.py b/scripts/validate-dxf.py index 2998c535..07cd5054 100644 --- a/scripts/validate-dxf.py +++ b/scripts/validate-dxf.py @@ -15,7 +15,14 @@ from ezdxf import recover def main(path: str) -> int: - doc, auditor = recover.readfile(path) + # recover.readfile liest nur ASCII; Binär-DXF ("AutoCAD Binary DXF") geht über readfile + Audit. + with open(path, "rb") as fh: + binary = fh.read(18) == b"AutoCAD Binary DXF" + if binary: + doc = ezdxf.readfile(path) + auditor = doc.audit() + else: + doc, auditor = recover.readfile(path) msp = doc.modelspace() entities = [] for e in msp: @@ -36,6 +43,17 @@ def main(path: str) -> int: item["paths"] = len(e.paths) item["pattern_lines"] = len(e.pattern.lines) if e.pattern else 0 item["rgb"] = list(e.rgb) if e.dxf.hasattr("true_color") else None + g = e.gradient + item["gradient"] = ( + { + "name": g.name, + "rotation": g.rotation, + "color1": list(g.color1), + "color2": list(g.color2), + } + if g is not None + else None + ) first = e.paths[0] if len(e.paths) else None item["pts"] = [[v[0], v[1]] for v in first.vertices] if first is not None and hasattr(first, "vertices") else [] elif t == "TEXT": diff --git a/src-tauri/fileio/src/export.rs b/src-tauri/fileio/src/export.rs index ca02b4d2..a4b5b58b 100644 --- a/src-tauri/fileio/src/export.rs +++ b/src-tauri/fileio/src/export.rs @@ -31,12 +31,16 @@ // n_dash, d0 … d(n_dash−1) (Strichmuster in m: an, aus, an, aus …; 0 = durchgezogen), // n_fam, (angle (rad), spacing (m)) × n_fam, n, x0, y0, … x(n−1), y(n−1) (äusserer Rand) // +// GRADIENT = 8, layer, rgb1 (0xRRGGBB), rgb2 (0xRRGGBB), angle (rad, Richtung rgb1 → rgb2, DXF-Konvention), +// kind (0 = linear, 1 = radial: rgb1 in der Mitte, rgb2 am Rand), n, x0, y0, … (äusserer Rand) +// // `layer` ist der Index des LAYER-Datensatzes (Reihenfolge des Auftretens, ab 0), er muss vorher // stehen. Schraffuren sind echte HATCH-Entitäten ([C2], 28.10.): Vollfüllung (`SOLID`) oder ein // Linienmuster, das hier aus Winkel und Linienabstand der Dossier-Schraffur gebaut wird (je Linienschar // eine Musterzeile, Basispunkt Ursprung — wie die Phase der bisherigen Schraffurlinien; Versatz = // Abstand senkrecht zur Linie, schon gedreht, wie DXF es speichert). Der Rand ist eine geschlossene -// Polylinien-Kante. Zufallsstriche (`random`) haben kein Musteräquivalent: TS gibt sie weiter als +// Polylinien-Kante. Farbverläufe (GRADIENT, [C2], 28.10.) sind echte Gradient-HATCHs (Gruppencodes +// 450–470: Name LINEAR bzw. SPHERICAL, zwei Farbstützen 0 und 1, Winkel in Radiant). Zufallsstriche (`random`) haben kein Musteräquivalent: TS gibt sie weiter als // LINE-Datensätze aus. // // Fehlerverhalten: ein kaputter Puffer (falsche Version, unbekannter Datensatz, abgeschnitten, Index @@ -44,8 +48,8 @@ // (der alte Writer schrieb dafür „0.0“ — eine Linie zum Nullpunkt ist schlechter als keine). use acadrust::entities::{ - BoundaryEdge, BoundaryPath, BoundaryPathFlags, Hatch, HatchPattern, HatchPatternLine, HatchPatternType, - PolylineEdge, + BoundaryEdge, BoundaryPath, BoundaryPathFlags, Hatch, HatchGradientPattern, HatchPattern, HatchPatternLine, + HatchPatternType, PolylineEdge, }; use acadrust::{ Arc, CadDocument, Circle, Color, DwgWriter, DxfVersion, DxfWriter, EntityType, Layer, Line, @@ -62,6 +66,7 @@ pub const REC_ARC: f64 = 4.0; pub const REC_CIRCLE: f64 = 5.0; pub const REC_TEXT: f64 = 6.0; pub const REC_HATCH: f64 = 7.0; +pub const REC_GRADIENT: f64 = 8.0; /// DXF-Ausgabeversion (s. Kopf). pub const DXF_VERSION: DxfVersion = DxfVersion::AC1032; @@ -192,12 +197,34 @@ fn make_hatch(pts: &[f64], solid: bool, families: &[(f64, f64)], dashes: &[f64]) h.pattern_type = HatchPatternType::Custom; h }; + add_outer_boundary(&mut hatch, pts); + hatch +} + +/// Äusserer Rand als geschlossene Polylinien-Kante. +fn add_outer_boundary(hatch: &mut Hatch, pts: &[f64]) { let mut path = BoundaryPath::with_flags(BoundaryPathFlags::from_bits(1 | 2)); // äusserer Rand, Polylinie path.add_edge(BoundaryEdge::Polyline(PolylineEdge::new( pts.chunks_exact(2).map(|p| Vector2::new(p[0], p[1])).collect(), true, ))); hatch.add_path(path); +} + +/// Zweifarben-Verlauf als Gradient-HATCH (wie AutoCAD: Muster „SOLID“ + Gradient-Gruppencodes). +/// `radial` = Kugelverlauf (`SPHERICAL`), sonst `LINEAR` mit Drehwinkel `angle` (rad). +fn make_gradient_hatch(pts: &[f64], rgb1: u32, rgb2: u32, angle: f64, radial: bool) -> Hatch { + let mut hatch = Hatch::solid(); + let mut g = HatchGradientPattern::new(); + g.enabled = true; + g.angle = if radial { 0.0 } else { angle }; + g.shift = 0.0; + g.is_single_color = false; + g.name = if radial { "SPHERICAL" } else { "LINEAR" }.to_string(); + g.add_color(0.0, layer_color(rgb1 as f64)); + g.add_color(1.0, layer_color(rgb2 as f64)); + hatch.gradient_color = g; + add_outer_boundary(&mut hatch, pts); hatch } @@ -294,6 +321,17 @@ pub fn build_document(flat: &[f64], strings: &str) -> Result= 3 && all_finite(pts) && angle.is_finite() && in_range(rgb1) && in_range(rgb2)).then(|| { + EntityType::Hatch(Box::new(make_gradient_hatch(pts, rgb1 as u32, rgb2 as u32, angle, kind == 1.0))) + }) } else { return Err(format!("unbekannter Datensatz {tag} bei {}", r.pos - 1)); }; @@ -314,6 +352,16 @@ pub fn export_dxf(flat: &[f64], strings: &str) -> Result, String> { .map_err(|e| format!("DXF schreiben: {e}")) } +/// Flache Zeichnung → Binär-DXF-Bytes (R2018, UTF-8). acadrust hebt R2000/R2004 bei Binär-DXF selbst auf +/// R2010 an (BricsCAD lehnt die alten Köpfe ab); R2018 ist davon unberührt. +pub fn export_dxf_binary(flat: &[f64], strings: &str) -> Result, String> { + let doc = build_document(flat, strings)?; + DxfWriter::new_binary(&doc) + .with_version(DXF_VERSION) + .write_to_vec() + .map_err(|e| format!("Binär-DXF schreiben: {e}")) +} + /// Flache Zeichnung → DWG-Bytes (R2018). pub fn export_dwg(flat: &[f64], strings: &str) -> Result, String> { export_dwg_version(flat, strings, DWG_VERSION) @@ -341,6 +389,12 @@ mod web { super::export_dxf(flat, strings).unwrap_or_default() } + /// Flache Zeichnung → Binär-DXF-Bytes (R2018); leer bei kaputtem Puffer. + #[wasm_bindgen] + pub fn export_dxf_binary_flat(flat: &[f64], strings: &str) -> Vec { + super::export_dxf_binary(flat, strings).unwrap_or_default() + } + /// Flache Zeichnung → DWG-Bytes (R2018); leer bei kaputtem Puffer. #[wasm_bindgen] pub fn export_dwg_flat(flat: &[f64], strings: &str) -> Vec { @@ -644,4 +698,90 @@ mod tests { let doc = read_dxf(export_dxf(&col, "P").unwrap()); assert!(matches!(doc.entities().next().unwrap().as_entity().common().color, Color::ByLayer)); } + + /// Verlauf-HATCH: linear (45°) und radial, Farben, Name, Rand — DXF, Binär-DXF und DWG. + fn gradient_sample() -> (Vec, String) { + let (e, n) = (E, N); + let flat = vec![ + FLAT_VERSION, + REC_LAYER, 0.0, -1.0, 13.0, + REC_GRADIENT, 0.0, 0xff_ff_ff as f64, 0x00_33_99 as f64, std::f64::consts::FRAC_PI_4, 0.0, + 4.0, e, n, e + 4.0, n, e + 4.0, n + 3.0, e, n + 3.0, + REC_GRADIENT, 0.0, 0xff_00_00 as f64, 0x00_00_ff as f64, 0.0, 1.0, + 3.0, e, n, e + 2.0, n, e + 1.0, n + 1.0, + ]; + (flat, "HATCH".to_string()) + } + + fn check_gradients(doc: &CadDocument) { + let hs: Vec<&Hatch> = doc.entities().filter_map(|x| if let EntityType::Hatch(h) = x { Some(h.as_ref()) } else { None }).collect(); + assert_eq!(hs.len(), 2); + for h in &hs { + assert!(h.gradient_color.enabled); + assert_eq!(h.gradient_color.colors.len(), 2); + assert_eq!(h.common.layer, "HATCH"); + assert_eq!(h.paths.len(), 1); + } + let g = &hs[0].gradient_color; + assert_eq!(g.name, "LINEAR"); + assert!((g.angle - std::f64::consts::FRAC_PI_4).abs() < 1e-9); + assert_eq!(g.colors[0].color.rgb(), Some((0xff, 0xff, 0xff))); + assert_eq!(g.colors[1].color.rgb(), Some((0x00, 0x33, 0x99))); + assert_eq!(hs[1].gradient_color.name, "SPHERICAL"); + assert_eq!(hs[1].gradient_color.colors[0].color.rgb(), Some((0xff, 0, 0))); + } + + #[test] + fn gradient_roundtrip_dxf_binary_und_dwg() { + let (flat, strings) = gradient_sample(); + check_gradients(&read_dxf(export_dxf(&flat, &strings).unwrap())); + let bin = export_dxf_binary(&flat, &strings).unwrap(); + assert!(bin.starts_with(b"AutoCAD Binary DXF")); + check_gradients(&read_dxf(bin)); + check_gradients(&read_dwg(export_dwg(&flat, &strings).unwrap())); + } + + #[test] + fn gradient_dxf_text_hat_gruppencodes_450_bis_470() { + let (flat, strings) = gradient_sample(); + let text = String::from_utf8(export_dxf(&flat, &strings).unwrap()).unwrap(); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let has = |code: &str, val: &str| lines.windows(2).any(|w| w[0] == code && w[1] == val); + assert!(has("450", "1") && has("470", "LINEAR") && has("470", "SPHERICAL") && has("453", "2")); + } + + #[test] + fn kaputte_gradienten_werden_verworfen() { + let head = [FLAT_VERSION, REC_LAYER, 0.0, -1.0, 13.0]; + let sq = [4.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]; + for pre in [ + [f64::NAN, 0.0, 0.0, 0.0], + [0.0, 1e12, 0.0, 0.0], + [0.0, 0.0, f64::INFINITY, 0.0], + ] { + let mut v = head.to_vec(); + v.push(REC_GRADIENT); + v.push(0.0); + v.extend_from_slice(&pre); + v.extend_from_slice(&sq); + assert_eq!(read_dxf(export_dxf(&v, "P").unwrap()).entities().count(), 0, "{pre:?}"); + } + // Weniger als 3 Randpunkte und abgeschnittener Puffer. + let mut two = head.to_vec(); + two.extend_from_slice(&[REC_GRADIENT, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 1.0, 1.0]); + assert_eq!(read_dxf(export_dxf(&two, "P").unwrap()).entities().count(), 0); + let mut cut = head.to_vec(); + cut.extend_from_slice(&[REC_GRADIENT, 0.0, 0.0, 0.0, 0.0]); + assert!(export_dxf(&cut, "P").is_err()); + assert!(export_dxf_binary(&cut, "P").is_err()); + } + + #[test] + fn binary_dxf_mit_allen_datensatzarten() { + let (flat, strings) = sample(); + let bin = export_dxf_binary(&flat, &strings).unwrap(); + check(&read_dxf(bin)); + let (flat, strings) = hatch_sample(); + check_hatches(&read_dxf(export_dxf_binary(&flat, &strings).unwrap())); + } } diff --git a/src-tauri/fileio/src/ifc_export.rs b/src-tauri/fileio/src/ifc_export.rs index b3a595c1..cbfed233 100644 --- a/src-tauri/fileio/src/ifc_export.rs +++ b/src-tauri/fileio/src/ifc_export.rs @@ -20,11 +20,22 @@ // 2 = IfcPositiveRatioMeasure (value = Zahl) // structure= Geschoss-Index oder −1 (Gebäude) // -// WALL_SOLIDS = 1, structure, id, name, TYPEREF, PSETS, n_solids, (PTS, z_rel, depth) × n_solids +// WALL_SOLIDS = 1, structure, id, name, TYPEREF, PSETS, FRAME, n_solids, (PTS, z_rel, depth) × n_solids +// FRAME = has_frame (0/1); wenn 1: ox, oy, ux, uy (Wandanfang und Achsrichtung in Welt-XY, ux²+uy² = 1), +// axis_len, usage (0/1), offset. Mit Rahmen sitzt das Placement am Wandanfang, X = Achse, Y = linke +// Normale ([B5]: so ordnen Revit/ArchiCAD die Schichten der Achse zu); die PTS bleiben Welt-XY und +// werden hier ins Wandsystem gerechnet. Dazu eine „Axis“-Darstellung (IfcPolyline 0 … axis_len) +// 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 // OPENING = 4, wall_id, structure, opening_id, is_door (0/1), fill_name, PTS (Öffnungskörper), z_rel, -// depth, PTS (Füllung), width, PSETS +// depth, width, kind_text (Text oder −1 = keine: Tür OperationType, Fenster PartitioningType, +// IFC-Enum-Name), FILL_FRAME, n_parts, (role, PTS, z_rel, depth) × n_parts, PSETS +// FILL_FRAME = ox, oy, ux, uy (Welt-XY): Placement der Füllung (X = u, Y = linke Normale von u). Die +// Teile-PTS bleiben Welt-XY, z_rel zählt ab Öffnungs-Unterkante. n_parts = 0: kein Körper. +// role: 0 Rahmen/Zarge, 1 Türblatt, 2 Glas. Alle Teile eines Bauteils 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 // EXTRUSION = 6, structure, id, PTS, z_rel, depth // SPACE = 7, structure, id, name, long_name, external (0/1), height, PTS, net_area, gross_area, @@ -367,6 +378,24 @@ impl<'a> Reader<'a> { let s = self.take(n.checked_mul(2).ok_or("Überlauf")?)?; Ok(s.chunks_exact(2).map(|c| (c[0], c[1])).collect()) } + /// Teile einer Füllung: n, (Rolle 0 Rahmen / 1 Blatt / 2 Glas, PTS, z_rel, depth) × n. + fn parts(&mut self) -> Result, String> { + let n = self.idx()?; + if n > MAX_PARTS { + return Err(format!("zu viele Teile ({n}) bei {}", self.pos - 1)); + } + let mut out = Vec::with_capacity(n); + for _ in 0..n { + let role = self.idx()?; + if role > 2 { + return Err(format!("unbekannte Teilrolle {role} bei {}", self.pos - 1)); + } + let pts = self.pts()?; + let (z_rel, depth) = (self.f()?, self.f()?); + out.push(Part { role, pts, z_rel, depth }); + } + Ok(out) + } fn mesh(&mut self) -> Result { let nv = self.idx()?; let positions = self.take(nv.checked_mul(3).ok_or("Überlauf")?)?.to_vec(); @@ -429,6 +458,71 @@ impl<'a> Reader<'a> { } } +/// Obergrenze der Körper je Tür/Fenster (Rahmenteile, Scheiben, Pfosten). +const MAX_PARTS: usize = 256; + +/// Ein Körper einer Tür/eines Fensters (Welt-XY-Profil, Unterkante ab Öffnungs-UK). +struct Part { + /// 0 Rahmen/Zarge, 1 Türblatt, 2 Glas. + role: usize, + pts: Vec<(f64, f64)>, + z_rel: f64, + depth: f64, +} + +/// IfcDoorTypeOperationEnum / IfcWindowTypePartitioningEnum (IFC4): nur gültige Namen kommen durch. +const DOOR_OPERATIONS: &[&str] = &[ + "SINGLE_SWING_LEFT", "SINGLE_SWING_RIGHT", "DOUBLE_DOOR_SINGLE_SWING", "DOUBLE_DOOR_SINGLE_SWING_OPPOSITE_LEFT", + "DOUBLE_DOOR_SINGLE_SWING_OPPOSITE_RIGHT", "DOUBLE_SWING_LEFT", "DOUBLE_SWING_RIGHT", "DOUBLE_DOOR_DOUBLE_SWING", + "SWING_FIXED_LEFT", "SWING_FIXED_RIGHT", "SLIDING_TO_LEFT", "SLIDING_TO_RIGHT", "DOUBLE_DOOR_SLIDING", + "FOLDING_TO_LEFT", "FOLDING_TO_RIGHT", "DOUBLE_DOOR_FOLDING", "REVOLVING", "ROLLINGUP", "NOTDEFINED", +]; +const WINDOW_PARTITIONINGS: &[&str] = &[ + "SINGLE_PANEL", "DOUBLE_PANEL_VERTICAL", "DOUBLE_PANEL_HORIZONTAL", "TRIPLE_PANEL_VERTICAL", "TRIPLE_PANEL_BOTTOM", + "TRIPLE_PANEL_TOP", "TRIPLE_PANEL_LEFT", "TRIPLE_PANEL_RIGHT", "TRIPLE_PANEL_HORIZONTAL", "NOTDEFINED", +]; + +/// Farbe und Durchsichtigkeit je Teilrolle (wie `PART_RGB` im 3D: Rahmen hellgrau, Blatt warm, Glas bläulich). +const PART_STYLES: [(&str, [f64; 3], f64); 3] = [ + ("Rahmen", [0.85, 0.85, 0.83], 0.0), + ("Türblatt", [0.93, 0.90, 0.85], 0.0), + ("Glas", [0.62, 0.76, 0.85], 0.6), +]; + +/// Lokales Wand-/Füllungssystem in Welt-XY: Ursprung und Richtung der X-Achse (Y = linke Normale). +#[derive(Clone, Copy)] +struct Frame { + ox: f64, + oy: f64, + ux: f64, + uy: f64, +} + +impl Frame { + /// Identität (Welt-Koordinaten). + const WORLD: Frame = Frame { ox: 0.0, oy: 0.0, ux: 1.0, uy: 0.0 }; + + fn is_world(&self) -> bool { + self.ox == 0.0 && self.oy == 0.0 && self.ux == 1.0 && self.uy == 0.0 + } + + /// Welt-XY → lokal (X = u, Y = linke Normale (−uy, ux)). + fn local(&self, x: f64, y: f64) -> (f64, f64) { + let (dx, dy) = (x - self.ox, y - self.oy); + (dx * self.ux + dy * self.uy, -dx * self.uy + dy * self.ux) + } + + fn local_pts(&self, pts: &[(f64, f64)]) -> Vec<(f64, f64)> { + pts.iter().map(|&(x, y)| self.local(x, y)).collect() + } + + /// Dieses System (in Welt-XY) im System `parent` ausgedrückt: Ursprung abbilden, Richtung nur drehen. + fn relative_to(&self, parent: &Frame) -> Frame { + let (ox, oy) = parent.local(self.ox, self.oy); + Frame { ox, oy, ux: self.ux * parent.ux + self.uy * parent.uy, uy: -self.ux * parent.uy + self.uy * parent.ux } + } +} + struct Mesh { positions: Vec, indices: Vec, @@ -506,6 +600,8 @@ struct PsetAcc { struct TypeAcc { key: String, type_id: usize, + /// IfcMaterialLayerSet des Typs (0 = keiner) für die LayerSetUsage der Exemplare. + layer_set: usize, occurrences: Vec, } @@ -527,8 +623,13 @@ struct Builder { materials: HashMap, types: Vec, type_index: HashMap, - /// Wand-id → (Entität, Placement) für die Öffnungen. - walls: HashMap, + /// Wand-id → (Entität, Placement, Wandsystem) für die Öffnungen. + walls: HashMap, + /// Oberflächenstil je Teilrolle (Rahmen, Blatt, Glas), beim ersten Gebrauch angelegt (0 = noch nicht). + styles: [usize; 3], + /// Untergeordneter Kontext „Axis“ (GRAPH_VIEW), beim ersten Gebrauch angelegt (0 = noch nicht). + axis_context: usize, + spaces: Vec<(i64, Vec)>, column_materials: Vec<(String, String, Vec)>, } @@ -625,6 +726,73 @@ impl Builder { self.add("IFCLOCALPLACEMENT", format!("#{relative_to},#{axis}")) } + /// Placement am Punkt (`frame.ox`, `frame.oy`, 0) mit gedrehter X-Achse relativ zu `relative_to`. + fn emit_placement_frame(&mut self, frame: &Frame, relative_to: usize) -> usize { + let origin = self.add("IFCCARTESIANPOINT", list(&[fmt_real(frame.ox), fmt_real(frame.oy), fmt_real(0.0)])); + let dir = self.add("IFCDIRECTION", list(&[fmt_real(frame.ux), fmt_real(frame.uy), fmt_real(0.0)])); + // IFC4: Axis und RefDirection stehen nur zusammen (Axis = +Z). + let axis = self.add("IFCAXIS2PLACEMENT3D", format!("#{origin},#{},#{dir}", self.extrude_dir)); + self.add("IFCLOCALPLACEMENT", format!("#{relative_to},#{axis}")) + } + + /// Oberflächenstil der Teilrolle (einmal je Datei): IfcSurfaceStyle mit IfcSurfaceStyleRendering. + fn part_style(&mut self, role: usize) -> usize { + if self.styles[role] == 0 { + let (name, rgb, transparency) = PART_STYLES[role]; + let colour = self.add("IFCCOLOURRGB", format!("$,{},{},{}", fmt_real(rgb[0]), fmt_real(rgb[1]), fmt_real(rgb[2]))); + let rendering = self.add( + "IFCSURFACESTYLERENDERING", + format!("#{colour},{},$,$,$,$,$,$,{}", fmt_real(transparency), enum_("NOTDEFINED")), + ); + self.styles[role] = self.add( + "IFCSURFACESTYLE", + format!("{},{},{}", ifc_string(name), enum_("BOTH"), refs(&[rendering])), + ); + } + self.styles[role] + } + + /// Körper einer Tür/eines Fensters: je Teil eine Extrusion mit eigenem Stil, alle in EINER + /// SweptSolid-Darstellung (getrennte Körper im selben Bauteil). Profile kommen im Füllungssystem. + fn emit_parts_shape(&mut self, parts: &[Part], frame: &Frame) -> usize { + let mut solids = Vec::with_capacity(parts.len()); + for p in parts { + let solid = self.emit_extrusion(&frame.local_pts(&p.pts), p.z_rel, p.depth); + let style = self.part_style(p.role); + self.add("IFCSTYLEDITEM", format!("#{solid},{},$", refs(&[style]))); + solids.push(solid); + } + self.emit_swept_shape(&solids) + } + + /// Untergeordneter Darstellungskontext „Axis“ (GRAPH_VIEW), einmal je Datei. + fn axis_context(&mut self) -> usize { + if self.axis_context == 0 { + self.axis_context = self.add( + "IFCGEOMETRICREPRESENTATIONSUBCONTEXT", + format!("{},{},*,*,*,*,#{},$,{},$", ifc_string("Axis"), ifc_string("Model"), self.context, enum_("GRAPH_VIEW")), + ); + } + self.axis_context + } + + /// Wand-Darstellung: „Axis“ (IfcPolyline 0 … `len` in lokal X) und „Body“ (SweptSolid aus `solids`). + fn emit_wall_shape(&mut self, solids: &[usize], len: f64) -> usize { + let p0 = self.add("IFCCARTESIANPOINT", list(&[fmt_real(0.0), fmt_real(0.0)])); + let p1 = self.add("IFCCARTESIANPOINT", list(&[fmt_real(len), fmt_real(0.0)])); + let curve = self.add("IFCPOLYLINE", refs(&[p0, p1])); + let axis_ctx = self.axis_context(); + let axis = self.add( + "IFCSHAPEREPRESENTATION", + format!("#{axis_ctx},{},{},{}", ifc_string("Axis"), ifc_string("Curve2D"), refs(&[curve])), + ); + let body = self.add( + "IFCSHAPEREPRESENTATION", + format!("#{},{},{},{}", self.context, ifc_string("Body"), ifc_string("SweptSolid"), refs(solids)), + ); + self.add("IFCPRODUCTDEFINITIONSHAPE", format!("$,$,{}", refs(&[axis, body]))) + } + /// SweptSolid-Körper aus Extrusionen. fn emit_swept_shape(&mut self, solids: &[usize]) -> usize { let rep = self.add( @@ -708,6 +876,7 @@ impl Builder { t.kind.ifc(), format!("{guid},#{},{},$,$,$,$,$,$,{}", self.owner_history, ifc_string(&t.name), enum_(&t.predefined)), ); + let mut layer_set = 0; if !layer_ids.is_empty() { let set = self.add("IFCMATERIALLAYERSET", format!("{},{},$", refs(&layer_ids), ifc_string(&t.name))); let rel_guid = self.gid(&format!("{key}/material")); @@ -715,12 +884,20 @@ impl Builder { "IFCRELASSOCIATESMATERIAL", format!("{rel_guid},#{},$,$,{},#{set}", self.owner_history, refs(&[type_id])), ); + layer_set = set; } self.type_index.insert(key.clone(), self.types.len()); - self.types.push(TypeAcc { key, type_id, occurrences: Vec::new() }); + self.types.push(TypeAcc { key, type_id, layer_set, occurrences: Vec::new() }); self.types.len() - 1 } + /// IfcMaterialLayerSet eines schon angelegten Typs (`finish_typed` legt ihn an). + fn layer_set_of(&self, t: &TypeRef) -> Option { + let key = format!("type/{}/{}", t.kind.ifc(), t.id); + let set = self.types[*self.type_index.get(&key)?].layer_set; + (set != 0).then_some(set) + } + /// Gemeinsamer Abschluss der Bauteile mit Typ und Psets: Typ (falls vorhanden) anlegen, Entität /// schreiben, Typ-Exemplar, Eingliederung und Psets vormerken. #[allow(clippy::too_many_arguments)] @@ -810,6 +987,8 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { types: Vec::new(), type_index: HashMap::new(), walls: HashMap::new(), + axis_context: 0, + styles: [0; 3], spaces: Vec::new(), column_materials: Vec::new(), }; @@ -966,18 +1145,49 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { let name = r.string()?; let ty = r.type_ref()?; let psets = r.psets()?; + let has_frame = r.flag()?; + let (frame, axis_len, usage, offset) = if has_frame { + let (ox, oy, ux, uy) = (r.f()?, r.f()?, r.f()?, r.f()?); + if ((ux * ux + uy * uy) - 1.0).abs() > 1e-6 { + return Err(format!("Achsrichtung nicht normiert bei {}", r.pos - 1)); + } + let (len, usage, offset) = (r.f()?, r.flag()?, r.f()?); + (Frame { ox, oy, ux, uy }, len, usage, offset) + } else { + (Frame::WORLD, 0.0, false, 0.0) + }; let n = r.idx()?; let mut solids = Vec::new(); for _ in 0..n { - let pts = r.pts()?; + let pts = frame.local_pts(&r.pts()?); let z_rel = r.f()?; let depth = r.f()?; solids.push(w.emit_extrusion(&pts, z_rel, depth)); } - let placement = w.emit_placement(0.0, w.placement_of(structure)); - let shape = w.emit_swept_shape(&solids); + let parent = w.placement_of(structure); + let (placement, shape) = if has_frame { + (w.emit_placement_frame(&frame, parent), w.emit_wall_shape(&solids, axis_len)) + } else { + (w.emit_placement(0.0, parent), w.emit_swept_shape(&solids)) + }; let entity = w.finish_typed("IFCWALL", format!("wall/{id}"), &name, &ty, &psets, structure, placement, shape, None, true); - w.walls.insert(id, (entity, placement)); + if has_frame && usage { + // Schichten des Typs der Wandachse zuordnen: erste Schicht (aussen) liegt bei `offset` + // von der Achse, die übrigen folgen in +Y (linke Normale). + let set = ty.as_ref().and_then(|t| w.layer_set_of(t)); + if let Some(set) = set { + let u = w.add( + "IFCMATERIALLAYERSETUSAGE", + format!("#{set},{},{},{},$", enum_("AXIS2"), enum_("POSITIVE"), fmt_real(offset)), + ); + let g = w.gid(&format!("wall/{id}/material")); + w.add( + "IFCRELASSOCIATESMATERIAL", + format!("{g},#{},$,$,{},#{u}", w.owner_history, refs(&[entity])), + ); + } + } + w.walls.insert(id, (entity, placement, frame)); } c if c == REC_WALL_MESH => { let structure = r.structure(n_storeys)?; @@ -988,7 +1198,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { let mesh = r.mesh()?; let (placement, shape) = w.emit_triangulated_product(&mesh, w.placement_of(structure)); let entity = w.finish_typed("IFCWALL", format!("wall/{id}"), &name, &ty, &psets, structure, placement, shape, None, true); - w.walls.insert(id, (entity, placement)); + w.walls.insert(id, (entity, placement, Frame::WORLD)); } c if c == REC_CEILING => { let structure = r.structure(n_storeys)?; @@ -1011,12 +1221,26 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { let void_pts = r.pts()?; let void_z = r.f()?; let depth = r.f()?; - let fill_pts = r.pts()?; let width = r.f()?; + let kind = r.opt_string()?; + let (fox, foy, fux, fuy) = (r.f()?, r.f()?, r.f()?, r.f()?); + if ((fux * fux + fuy * fuy) - 1.0).abs() > 1e-6 { + return Err(format!("Füllungsrichtung nicht normiert bei {}", r.pos - 1)); + } + let fill_frame = Frame { ox: fox, oy: foy, ux: fux, uy: fuy }; + let parts = r.parts()?; let psets = r.psets()?; - let Some(&(host_entity, host_placement)) = w.walls.get(&wall_id) else { + let allowed = if is_door { DOOR_OPERATIONS } else { WINDOW_PARTITIONINGS }; + if let Some(k) = &kind { + if !allowed.contains(&k.as_str()) { + return Err(format!("unbekannte Ausführung {k:?} bei {}", r.pos - 1)); + } + } + let Some(&(host_entity, host_placement, host_frame)) = w.walls.get(&wall_id) else { continue; // Wirtswand nicht geschrieben (degeneriert) }; + // Die Geometrie kommt in Welt-XY; Wände mit eigenem Placement rechnen wir ins Wandsystem. + let void_pts = if host_frame.is_world() { void_pts } else { host_frame.local_pts(&void_pts) }; let (opening_placement, opening_shape) = w.emit_box_product(&void_pts, void_z, depth, host_placement); let g = w.gid(&format!("opening/{opening_id}")); let opening_entity = w.add( @@ -1033,12 +1257,16 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { "IFCRELVOIDSELEMENT", format!("{g},#{},$,$,#{host_entity},#{opening_entity}", w.owner_history), ); - let (fill_placement, fill_shape) = w.emit_box_product(&fill_pts, 0.0, depth, opening_placement); + // Füllung: eigenes Placement (Ursprung/Richtung aus dem Modell, relativ zur Öffnung = zur Wand), + // Körper in diesem System; ohne Teile (reine Wandöffnung) keine Darstellung. + let fill_placement = w.emit_placement_frame(&fill_frame.relative_to(&host_frame), opening_placement); + let fill_shape = if parts.is_empty() { "$".to_string() } else { format!("#{}", w.emit_parts_shape(&parts, &fill_frame)) }; let g = w.gid(&format!("fill/{opening_id}")); + let operation = kind.as_deref().map(enum_).unwrap_or_else(|| "$".to_string()); let fill_entity = w.add( if is_door { "IFCDOOR" } else { "IFCWINDOW" }, format!( - "{g},#{},{},$,$,#{fill_placement},#{fill_shape},$,{},{},{},$,$", + "{g},#{},{},$,$,#{fill_placement},{fill_shape},$,{},{},{},{operation},$", w.owner_history, ifc_string(&fill_name), fmt_real(depth), @@ -1388,6 +1616,43 @@ mod tests { fn no_type(&mut self) { self.f.push(0.0); } + /// OPENING-Datensatz im neuen Format (Gegenstück zu `FlatIfc.opening`). + #[allow(clippy::too_many_arguments)] + fn opening( + &mut self, + wall: &str, + id: &str, + is_door: bool, + name: &str, + void_pts: &[(f64, f64)], + void_z: f64, + depth: f64, + width: f64, + kind: Option<&str>, + frame: [f64; 4], + parts: &[(f64, &[(f64, f64)], f64, f64)], + ) { + self.n(&[REC_OPENING]); + self.str(wall); + self.n(&[-1.0]); + self.str(id); + self.n(&[if is_door { 1.0 } else { 0.0 }]); + self.str(name); + self.pts(void_pts); + self.n(&[void_z, depth, width]); + match kind { + Some(k) => self.str(k), + None => self.f.push(-1.0), + } + self.n(&frame); + self.f.push(parts.len() as f64); + for (role, pts, z, d) in parts { + self.f.push(*role); + self.pts(pts); + self.n(&[*z, *d]); + } + self.no_psets(); + } fn wall_type(&mut self) { self.n(&[1.0, 0.0]); self.str("T1"); @@ -1440,22 +1705,27 @@ mod tests { b.str("Aussenwand"); b.wall_type(); b.ref_pset("Pset_WallCommon", "Aussenwand"); + // W1 mit Wandsystem (Achse, LayerSetUsage), W2 ohne (altes Verhalten). + if wid == "W1" { + b.n(&[1.0, 0.0, 0.0, 1.0, 0.0, 5.0, 1.0, -0.2]); + } else { + b.n(&[0.0]); + } b.n(&[1.0]); b.pts(&SQUARE); b.n(&[0.0, 2.6]); } - // Öffnung in W1: Tür. - b.n(&[REC_OPENING]); - b.str("W1"); - b.n(&[0.0]); - b.str("T1"); - b.n(&[1.0]); - b.str("Haustür"); - b.pts(&[(1.0, -0.02), (1.9, -0.02), (1.9, 0.42), (1.0, 0.42)]); - b.n(&[0.0, 2.1]); - b.pts(&[(1.0, 0.0), (1.9, 0.0), (1.9, 0.4), (1.0, 0.4)]); - b.n(&[0.9]); - b.ref_pset("Pset_DoorCommon", "Tür 90"); + // Öffnung in W1: Tür mit Zarge, Blatt und Glas. + b.opening( + "W1", "T1", true, "Haustür", + &[(1.0, -0.02), (1.9, -0.02), (1.9, 0.42), (1.0, 0.42)], 0.0, 2.1, 0.9, + Some("SINGLE_SWING_LEFT"), [1.45, 0.0, 0.0, 1.0], + &[ + (0.0, &[(1.0, 0.0), (1.06, 0.0), (1.06, 0.07), (1.0, 0.07)], 0.0, 2.1), + (1.0, &[(1.06, 0.015), (1.84, 0.015), (1.84, 0.055), (1.06, 0.055)], 0.0, 2.04), + (2.0, &[(1.2, 0.02), (1.6, 0.02), (1.6, 0.05), (1.2, 0.05)], 0.5, 1.0), + ], + ); // Decke, Treppe, Extrusion. b.n(&[REC_CEILING, 0.0]); b.str("D1"); @@ -1595,13 +1865,137 @@ mod tests { assert_eq!(count(&ifc, "IFCMATERIALLAYERSET"), 2); // Wandtyp + Dachtyp assert_eq!(count(&ifc, "IFCMATERIAL"), 2); // Beton (geteilt mit Dachtyp und Stütze) + Dämmung assert_eq!(count(&ifc, "IFCRELDEFINESBYTYPE"), 2); - assert_eq!(count(&ifc, "IFCPROPERTYSET"), 6); // Wall, Door, Space, Roof, Column + CH_Raum + assert_eq!(count(&ifc, "IFCPROPERTYSET"), 5); // Wall, Space, Roof, Column + CH_Raum (Tür ohne Pset) // Eingliederung: Geschoss (Wände, Decke, Treppe, Tür, Dach, Stütze) und Gebäude (Extrusion). assert_eq!(count(&ifc, "IFCRELCONTAINEDINSPATIALSTRUCTURE"), 2); // Project→Site, Site→Building, Building→Storeys, Geschoss→Räume. assert_eq!(count(&ifc, "IFCRELAGGREGATES"), 4); } + /// Zeile der ersten Entität eines Typs. + 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")) + } + + /// Kopf (META) eines Mini-Projekts ohne Geschoss. + fn mini() -> B { + let mut b = B::new(); + b.str("t"); + b.str("H"); + b.n(&[1_700_000_000.0]); + b.str("2026-10-28T12:00:00"); + b.n(&[0.0, f64::NAN, 0.0]); + b + } + + #[test] + fn wand_mit_achse_und_layer_set_usage() { + let ifc = build(&full_house(false)).unwrap(); + check_structure(&ifc); + // Nur W1 hat Wandsystem: eine Usage, eine Axis-Darstellung, ein Axis-Kontext. + assert_eq!(count(&ifc, "IFCMATERIALLAYERSETUSAGE"), 1); + assert_eq!(count(&ifc, "IFCGEOMETRICREPRESENTATIONSUBCONTEXT"), 1); + let usage = first_line(&ifc, "IFCMATERIALLAYERSETUSAGE"); + assert!(usage.contains(".AXIS2.,.POSITIVE.,-0.2,$"), "{usage}"); + // Die Usage verweist auf das LayerSet des Typs (dasselbe wie die Typ-Zuordnung). + let set_no: usize = usage.split("(#").nth(1).unwrap().split(',').next().unwrap().parse().unwrap(); + assert!(ifc.contains(&format!("#{set_no}=IFCMATERIALLAYERSET("))); + // Axis: IfcPolyline von (0,0) nach (5,0) in Kurve2D. + assert!(ifc.contains("'Axis','Curve2D'")); + assert!(ifc.contains("IFCCARTESIANPOINT((5.0,0.0))")); + assert!(ifc.contains("IFCDIRECTION((1.0,0.0,0.0))")); + } + + #[test] + fn gedrehte_wand_rechnet_profil_und_oeffnung_ins_wandsystem() { + // Wand von (10,20) nach (10,25): u = (0,1), linke Normale = (−1,0). + let mut b = mini(); + b.n(&[REC_WALL_SOLIDS, -1.0]); + b.str("W"); + b.str("Wand"); + b.no_type(); + b.no_psets(); + b.n(&[1.0, 10.0, 20.0, 0.0, 1.0, 5.0, 0.0, 0.0]); + b.n(&[1.0]); + b.pts(&[(10.2, 20.0), (10.2, 25.0), (9.8, 25.0), (9.8, 20.0)]); + b.n(&[0.0, 2.6]); + b.opening( + "W", "O", false, "Fenster", + &[(10.3, 21.0), (10.3, 22.0), (9.7, 22.0), (9.7, 21.0)], 0.9, 1.2, 1.0, + Some("SINGLE_PANEL"), [10.0, 21.5, 0.0, 1.0], + &[(0.0, &[(10.2, 21.0), (10.2, 22.0), (9.8, 22.0), (9.8, 21.0)], 0.0, 1.2)], + ); + let ifc = build(&b).unwrap(); + check_structure(&ifc); + // Wandprofil lokal: x = Länge entlang u, y = linke Normale (10.2 → −0.2, 9.8 → 0.2). + assert!(ifc.contains("IFCCARTESIANPOINT((0.0,-0.2))")); + assert!(ifc.contains("IFCCARTESIANPOINT((5.0,0.2))")); + // Öffnung lokal bei x = 1…2, quer −0.3…0.3. + assert!(ifc.contains("IFCCARTESIANPOINT((1.0,-0.3))")); + assert!(ifc.contains("IFCCARTESIANPOINT((2.0,0.3))")); + assert!(ifc.contains("IFCDIRECTION((0.0,1.0,0.0))")); + // Ohne Typ keine Usage, trotzdem Axis. + assert_eq!(count(&ifc, "IFCMATERIALLAYERSETUSAGE"), 0); + assert!(ifc.contains("'Axis','Curve2D'")); + } + + #[test] + fn tuer_hat_getrennte_koerper_mit_stilen_und_operation() { + let ifc = build(&full_house(false)).unwrap(); + check_structure(&ifc); + let door = first_line(&ifc, "IFCDOOR"); + assert!(door.contains(".DOOR.,.SINGLE_SWING_LEFT.,$);"), "{door}"); + // Drei Körper (Zarge, Blatt, Glas) in EINER Darstellung, je ein IfcStyledItem, drei Stile. + assert_eq!(count(&ifc, "IFCSTYLEDITEM"), 3); + assert_eq!(count(&ifc, "IFCSURFACESTYLE"), 3); + assert_eq!(count(&ifc, "IFCSURFACESTYLERENDERING"), 3); + assert!(ifc.contains("IFCSURFACESTYLE('Glas',.BOTH.,")); + assert!(ifc.contains("IFCSURFACESTYLERENDERING(#")); + let shapes = ifc.lines().filter(|l| l.contains("IFCSHAPEREPRESENTATION") && l.contains("'SweptSolid'") && l.matches('#').count() == 5).count(); + assert!(shapes >= 1, "Darstellung mit 3 Körpern fehlt"); + // Füllungs-Placement mit Richtung (0,1,0) relativ zur Öffnung; Ursprung lokal. + assert!(ifc.contains("IFCCARTESIANPOINT((1.45,0.0,0.0))")); + } + + #[test] + fn fenster_ohne_teile_hat_keine_darstellung_und_enum_ist_geprueft() { + let mut b = full_house(false); + b.opening("W1", "F1", false, "Fenster", &SQUARE, 0.9, 1.2, 1.2, Some("DOUBLE_PANEL_VERTICAL"), [2.0, 0.0, 1.0, 0.0], &[]); + b.opening("W1", "T2", true, "Wandöffnung", &SQUARE, 0.0, 2.1, 1.0, None, [3.0, 0.0, 1.0, 0.0], &[]); + let ifc = build(&b).unwrap(); + check_structure(&ifc); + let win = first_line(&ifc, "IFCWINDOW"); + assert!(win.contains(".WINDOW.,.DOUBLE_PANEL_VERTICAL.,$);"), "{win}"); + assert!(win.contains(",$,$,1.2,1.2,.WINDOW."), "ohne Teile keine Darstellung: {win}"); + // Ungültige Ausführung (Fenster-Wert an der Tür und umgekehrt) ist ein Fehler, nie Panic. + let mut bad = full_house(false); + bad.opening("W1", "T3", true, "Tür", &SQUARE, 0.0, 2.1, 1.0, Some("SINGLE_PANEL"), [1.0, 0.0, 1.0, 0.0], &[]); + assert!(build(&bad).is_err()); + let mut bad = full_house(false); + bad.opening("W1", "F3", false, "Fenster", &SQUARE, 0.9, 1.2, 1.2, Some("SINGLE_SWING_LEFT"), [1.0, 0.0, 1.0, 0.0], &[]); + assert!(build(&bad).is_err()); + // Unbekannte Teilrolle, schiefe Richtung: Fehler. + let mut bad = full_house(false); + bad.opening("W1", "F4", false, "Fenster", &SQUARE, 0.9, 1.2, 1.2, None, [1.0, 0.0, 1.0, 0.0], &[(3.0, &SQUARE, 0.0, 1.0)]); + assert!(build(&bad).is_err()); + let mut bad = full_house(false); + bad.opening("W1", "F5", false, "Fenster", &SQUARE, 0.9, 1.2, 1.2, None, [1.0, 0.0, 3.0, 0.0], &[]); + assert!(build(&bad).is_err()); + } + + #[test] + fn schiefe_achsrichtung_ist_fehler() { + let mut b = mini(); + b.n(&[REC_WALL_SOLIDS, -1.0]); + b.str("W"); + b.str("Wand"); + b.no_type(); + b.no_psets(); + b.n(&[1.0, 0.0, 0.0, 2.0, 0.0, 5.0, 0.0, 0.0, 0.0]); + assert!(build(&b).is_err()); + } + #[test] fn ohne_georeferenz_und_deterministisch() { let b = full_house(false); @@ -1647,17 +2041,7 @@ mod tests { b.n(&[1.0]); b.str("iso"); b.n(&[0.0, f64::NAN, 0.0]); - b.n(&[REC_OPENING]); - b.str("gibt-es-nicht"); - b.n(&[-1.0]); - b.str("O1"); - b.n(&[0.0]); - b.str("Fenster"); - b.pts(&SQUARE); - b.n(&[0.0, 1.0]); - b.pts(&SQUARE); - b.n(&[1.0]); - b.no_psets(); + b.opening("gibt-es-nicht", "O1", false, "Fenster", &SQUARE, 0.0, 1.0, 1.0, None, [0.0, 0.0, 1.0, 0.0], &[]); let ifc = build(&b).unwrap(); check_structure(&ifc); assert_eq!(count(&ifc, "IFCOPENINGELEMENT"), 0); diff --git a/src/cli/main.ts b/src/cli/main.ts index 698b4b25..e0338271 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -8,7 +8,7 @@ // dossier-cli plan [--level EG] [--scale 100] [--out eg.svg] // dossier-cli section [--out schnitt.svg] (braucht render3d-WASM) // dossier-cli elevation [--out ansicht.svg] -// dossier-cli dxf|dwg|ifc|step|obj|stl|schedule|kennzahlen|sun [--level EG] [--out datei] +// dossier-cli dxf [--binary]|dwg|ifc|step|obj|stl|schedule|kennzahlen|sun [--level EG] [--out datei] // dossier-cli import-ifc [--out neu.obp] [--group product|class] // IFC als Kontext-Meshes ([B3]); Bericht als JSON auf stdout // dossier-cli model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png) @@ -23,6 +23,7 @@ import { fileURLToPath } from "node:url"; import { buildPlanDxf, buildPlanDwg, + buildPlanDxfBinary, loadFileio, readIfc, ifcToImportedMeshes, @@ -221,7 +222,8 @@ export async function run(argv: string[]): Promise { const world = projectToWorldCoords(project); const plan = generatePlan(world, lvl.id, allCodes); await loadFileio(); - if (command === "dxf") out(args, buildPlanDxf(plan, world), `${lvl.name}.dxf`); + if (command === "dxf" && args.flags.has("binary")) out(args, buildPlanDxfBinary(plan, world), `${lvl.name}.dxf`); + else if (command === "dxf") out(args, buildPlanDxf(plan, world), `${lvl.name}.dxf`); else out(args, buildPlanDwg(plan, world), `${lvl.name}.dwg`); return 0; } diff --git a/src/core/extra.ts b/src/core/extra.ts index f50ec927..53fdb450 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -5,6 +5,7 @@ export { parseProjectFile, serializeProject, PROJECT_FORMAT_VERSION } from "../i export { exportIfcSpf } from "../export/exportIfc"; export { buildPlanDxf } from "../export/exportDxf"; export { buildPlanDwg } from "../export/exportDxf"; +export { buildPlanDxfBinary } from "../export/exportDxf"; export { loadFileio } from "../engine/fileioWasm"; export { readIfc, ifcToImportedMeshes } from "../io/ifcImport"; export { projectGeoOrigin } from "../model/geoRebase"; diff --git a/src/export/exportDxf.ezdxf.test.ts b/src/export/exportDxf.ezdxf.test.ts index 9ce19cd3..58f9536b 100644 --- a/src/export/exportDxf.ezdxf.test.ts +++ b/src/export/exportDxf.ezdxf.test.ts @@ -9,7 +9,7 @@ import { spawnSync } from "node:child_process"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { buildPlanDxf } from "./exportDxf"; +import { buildPlanDxf, buildPlanDxfBinary } from "./exportDxf"; import { sampleProject } from "../model/sampleProject"; import { generatePlan } from "../plan/generatePlan"; import type { Plan } from "../plan/generatePlan"; @@ -29,6 +29,7 @@ interface EzEntity { paths?: number; pattern_lines?: number; rgb?: number[] | null; + gradient?: { name: string; rotation: number; color1: number[]; color2: number[] } | null; } interface EzResult { version: string; @@ -38,7 +39,7 @@ interface EzResult { entities: EzEntity[]; } -function ezdxfRead(name: string, dxf: string): { status: number | null; result: EzResult | null; err: string } { +function ezdxfRead(name: string, dxf: string | Uint8Array): { status: number | null; result: EzResult | null; err: string } { const dir = mkdtempSync(join(tmpdir(), "dossier-dxf-")); const file = join(dir, `${name}.dxf`); writeFileSync(file, dxf); @@ -122,4 +123,50 @@ describe.skipIf(!hasEzdxf)("DXF-Export gegen ezdxf", { timeout: 60_000 }, () => expect(h.pts).toEqual(sq.map((p) => [p.x, p.y])); } }); + + const gradPlan = (): Plan => { + const sq = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }, { x: 0, y: 3 }]; + const poly = (gradient: object) => ({ + kind: "polygon", pts: sq, fill: "#eee", stroke: "#111", strokeWidthMm: 0.25, + hatch: { pattern: "crosshatch", scale: 1, angle: 0, color: "#336699", lineWeight: 0.13, dash: null, kind: "gradient", gradient }, + }); + return { + primitives: [ + poly({ color1: "#ffffff", color2: "#003399", angle: 90, type: "linear" }), + poly({ color1: "#f00", color2: "#00f", angle: 0, type: "radial" }), + ], + bounds: { minX: 0, minY: 0, maxX: 4, maxY: 3 }, + } as unknown as Plan; + }; + + it("Verlauf: ezdxf liest echte Gradient-HATCHs (linear, radial) ohne Auditor-Fehler", () => { + const r = ezdxfRead("gradient", buildPlanDxf(gradPlan(), sampleProject)); + expect(r.result, r.err).not.toBeNull(); + expect(r.result!.errors).toEqual([]); + expect(r.status).toBe(0); + const hs = r.result!.entities.filter((e) => e.type === "HATCH"); + expect(hs.length).toBe(2); + expect(hs[0].gradient).toMatchObject({ name: "LINEAR", color1: [255, 255, 255], color2: [0, 0x33, 0x99] }); + expect(hs[0].gradient!.rotation).toBeCloseTo(90, 6); + expect(hs[1].gradient).toMatchObject({ name: "SPHERICAL", color1: [255, 0, 0], color2: [0, 0, 255] }); + }); + + it("Binär-DXF: ezdxf liest dieselbe Zeichnung wie die ASCII-Fassung ohne Auditor-Fehler", () => { + const plan = generatePlan(sampleProject, "eg", new Set(flattenCategories(sampleProject.layers).map((l) => l.code))); + const asc = ezdxfRead("bin-asc", buildPlanDxf(plan, sampleProject)); + const bin = ezdxfRead("bin-bin", buildPlanDxfBinary(plan, sampleProject)); + expect(bin.result, bin.err).not.toBeNull(); + expect(bin.result!.errors).toEqual([]); + expect(bin.status).toBe(0); + expect(bin.result!.entities).toEqual(asc.result!.entities); + expect(Object.keys(bin.result!.layers)).toEqual(Object.keys(asc.result!.layers)); + // und kleiner als der Text + expect(buildPlanDxfBinary(plan, sampleProject).length).toBeLessThan(buildPlanDxf(plan, sampleProject).length); + }); + + it("Binär-DXF mit Verlauf: Gradient bleibt erhalten", () => { + const r = ezdxfRead("bin-grad", buildPlanDxfBinary(gradPlan(), sampleProject)); + expect(r.result!.errors).toEqual([]); + expect(r.result!.entities.filter((e) => e.type === "HATCH").map((h) => h.gradient?.name)).toEqual(["LINEAR", "SPHERICAL"]); + }); }); diff --git a/src/export/exportDxf.gradient.test.ts b/src/export/exportDxf.gradient.test.ts index 817cb166..ab38cbf7 100644 --- a/src/export/exportDxf.gradient.test.ts +++ b/src/export/exportDxf.gradient.test.ts @@ -1,15 +1,14 @@ /** * DXF-Export von Verlauf-Schraffuren (`HatchStyle.kind === "gradient"`). - * DXF trägt keine echten Farbverläufe (wie bereits bei Bild-Schraffuren - * akzeptiert) — der Export muss auf die reine Umriss-Polylinie zurückfallen - * und darf KEINE (aus dem stehengebliebenen `pattern`-Feld abgeleiteten) - * Musterlinien mehr ausgeben. + * Verläufe gehen als echte Gradient-HATCH ins DXF ([C2], 28.10.: Gruppencodes 450–470); + * es dürfen KEINE (aus dem stehengebliebenen `pattern`-Feld abgeleiteten) Musterlinien + * mehr ausgegeben werden. Ohne lesbare Farben bleibt es beim Umriss. */ import { describe, expect, it } from "vitest"; import "../engine/fileioWasm.setup"; import { buildPlanDxf } from "./exportDxf"; -import { nums, readDxf } from "./cadReadBack.testutil"; +import { num, nums, readDxf, str } from "./cadReadBack.testutil"; import { sampleProject } from "../model/sampleProject"; import type { Plan } from "../plan/generatePlan"; import type { HatchRender } from "../plan/generatePlan/shared"; @@ -58,7 +57,7 @@ describe("buildPlanDxf — Verlauf-Schraffur", () => { expect(nums(h, 53).map((a) => Math.round(a))).toEqual([0, 90]); }); - it("gradient: KEINE Musterlinien, nur die Umriss-Polylinie", () => { + it("gradient: eine Gradient-HATCH (LINEAR, zwei Farben, Winkel) plus Umriss, keine Musterlinien", () => { const dxf = buildPlanDxf( planWith([ polyWith({ @@ -69,7 +68,42 @@ describe("buildPlanDxf — Verlauf-Schraffur", () => { sampleProject, ); expect(countEntities(dxf, "LINE")).toBe(0); - expect(countEntities(dxf, "HATCH")).toBe(0); + expect(countEntities(dxf, "HATCH")).toBe(1); expect(countEntities(dxf, "LWPOLYLINE")).toBe(1); // Umriss bleibt erhalten + const h = readDxf(dxf).entities.find((e) => e.type === "HATCH")!; + expect(str(h, 470)).toBe("LINEAR"); + expect(num(h, 460)).toBeCloseTo(Math.PI / 4, 9); + expect(nums(h, 463)).toEqual([0, 1]); + expect(nums(h, 421)).toEqual([0xffffff, 0x000000]); + }); + + it("gradient radial: SPHERICAL; 3-stellige Farben werden erweitert", () => { + const dxf = buildPlanDxf( + planWith([polyWith({ kind: "gradient", gradient: { color1: "#f00", color2: "#00f", angle: 0, type: "radial" } })]), + sampleProject, + ); + const h = readDxf(dxf).entities.find((e) => e.type === "HATCH")!; + expect(str(h, 470)).toBe("SPHERICAL"); + expect(nums(h, 421)).toEqual([0xff0000, 0x0000ff]); + }); + + it("gradient ohne lesbare Farbe oder ohne Parameter: nur der Umriss", () => { + for (const hatch of [ + polyWith({ kind: "gradient", gradient: { color1: "none", color2: "#000000", angle: 0, type: "linear" } }), + polyWith({ kind: "gradient" }), + ]) { + const dxf = buildPlanDxf(planWith([hatch]), sampleProject); + expect(countEntities(dxf, "HATCH")).toBe(0); + expect(countEntities(dxf, "LWPOLYLINE")).toBe(1); + } + }); + + it("gradient ohne Schraffuren-Option: nur der Umriss", () => { + const dxf = buildPlanDxf( + planWith([polyWith({ kind: "gradient", gradient: { color1: "#fff", color2: "#000", angle: 0, type: "linear" } })]), + sampleProject, + { includeHatches: false }, + ); + expect(countEntities(dxf, "HATCH")).toBe(0); }); }); diff --git a/src/export/exportDxf.ts b/src/export/exportDxf.ts index 676f2c3c..9f8516e8 100644 --- a/src/export/exportDxf.ts +++ b/src/export/exportDxf.ts @@ -32,7 +32,12 @@ export interface ExportDxfOptions { } /** Ausgabeformat des Modell-Space-Exports. */ -export type CadExportFormat = "dxf" | "dwg"; +export type CadExportFormat = "dxf" | "dxfbin" | "dwg"; + +/** Dateiendung zum Ausgabeformat (Binär-DXF trägt ebenfalls `.dxf`). */ +export function cadExtension(format: CadExportFormat): "dxf" | "dwg" { + return format === "dwg" ? "dwg" : "dxf"; +} /** Sammel-Layer-Namen für Primitive ohne eigene Kategorie. */ const LAYER_HATCH = "HATCH"; @@ -54,6 +59,7 @@ const REC_ARC = 4; const REC_CIRCLE = 5; const REC_TEXT = 6; const REC_HATCH = 7; +const REC_GRADIENT = 8; /** * Sammelt Ebenen und Entitäten als flachen Zahlenpuffer + Zeichenkettenliste. Ebenen sind @@ -128,6 +134,17 @@ export class FlatDrawing { for (const p of pts) this.nums.push(p.x, p.y); } + /** + * Zweifarben-Verlauf als echte Gradient-HATCH-Entität (Rand `pts`, geschlossen). `rgb1`/`rgb2` = + * 0xRRGGBB; `angle` (Radiant) = Richtung von `rgb1` nach `rgb2` (nur linear); `radial`: `rgb1` in der + * Mitte, `rgb2` am Rand. + */ + addGradient(layer: string, pts: Vec2[], g: { rgb1: number; rgb2: number; angle: number; radial: boolean }): void { + if (pts.length < 3) return; + this.nums.push(REC_GRADIENT, this.layer(layer), g.rgb1, g.rgb2, g.angle, g.radial ? 1 : 0, pts.length); + for (const p of pts) this.nums.push(p.x, p.y); + } + /** Argumente für die Rust-Bindungen. */ args(): [Float64Array, string] { return [Float64Array.from(this.nums), this.strings.join("\0")]; @@ -213,6 +230,15 @@ export function buildPlanDxf( return new TextDecoder().decode(writeCad("dxf", collectPlanDrawing(plan, project, opts))); } +/** Wie {@link buildPlanDxf}, aber als Binär-DXF (R2018, Bytes; deutlich kleiner und schneller zu lesen). */ +export function buildPlanDxfBinary( + plan: Plan, + project: Project, + opts: ExportDxfOptions = {}, +): Uint8Array { + return writeCad("dxfbin", collectPlanDrawing(plan, project, opts)); +} + /** Wie {@link buildPlanDxf}, aber als DWG (R2018, Bytes). */ export function buildPlanDwg( plan: Plan, @@ -226,10 +252,15 @@ export function buildPlanDwg( function writeCad(format: CadExportFormat, drawing: FlatDrawing): Uint8Array { const m = fileio(); const [flat, strings] = drawing.args(); - const bytes = format === "dxf" ? m.export_dxf_flat(flat, strings) : m.export_dwg_flat(flat, strings); + const bytes = + format === "dxf" + ? m.export_dxf_flat(flat, strings) + : format === "dxfbin" + ? m.export_dxf_binary_flat(flat, strings) + : m.export_dwg_flat(flat, strings); if (bytes.length === 0) { const why = m.export_check_flat(flat, strings); - throw new Error(`${format.toUpperCase()}-Export fehlgeschlagen${why ? `: ${why}` : ""}`); + throw new Error(`${cadExtension(format).toUpperCase()}-Export fehlgeschlagen${why ? `: ${why}` : ""}`); } return bytes; } @@ -289,11 +320,20 @@ function emitPrimitive( if (pts.length < 2) break; // Schraffur ([C2], 28.10.) als echte HATCH-Entität UNTER dem Umriss (Zeichenreihenfolge der // Datei): Vollfüllung bzw. Linienmuster (diagonal/Kreuz/Dämmung/frei, auch gestrichelt) mit dem - // Polygon als Rand und der aufgelösten Vordergrundfarbe. Bild-/Verlauf-Schraffur (kind==="image"/ - // "gradient") trägt DXF nicht → FALLBACK ohne Muster (nur der Umriss). Random-Vektor + // Polygon als Rand und der aufgelösten Vordergrundfarbe. Verlauf-Schraffur (kind==="gradient") + // als echte Gradient-HATCH (zwei Farben, linear/radial); ohne lesbare Farben oder Bild- + // Schraffur (kind==="image") trägt DXF das nicht → FALLBACK ohne Muster (nur der Umriss). Random-Vektor // (deterministische Streu-Striche, Modell-Meter, identischer Seed wie Bildschirm/PDF) hat kein // Musteräquivalent → bleibt als einzelne Linien auf dem HATCH-Layer. - if (includeHatches && p.hatch.kind !== "image" && p.hatch.kind !== "gradient" && pts.length >= 3) { + if (includeHatches && p.hatch.kind === "gradient" && pts.length >= 3) { + const g = p.hatch.gradient; + const rgb1 = g ? rgbOrNull(g.color1) : null; + const rgb2 = g ? rgbOrNull(g.color2) : null; + if (g && rgb1 !== null && rgb2 !== null && Number.isFinite(g.angle)) { + // Richtung wie der SVG-Verlauf der Ansicht: Vektor (cos, sin) in Plan-Koordinaten = DXF-Winkel. + dxf.addGradient(LAYER_HATCH, pts, { rgb1, rgb2, angle: (g.angle * Math.PI) / 180, radial: g.type === "radial" }); + } + } else if (includeHatches && p.hatch.kind !== "image" && pts.length >= 3) { const h = p.hatch; if (h.pattern === "solid") { dxf.addHatch(LAYER_HATCH, pts, { solid: true, rgb: rgbOrNull(h.color) }); @@ -430,8 +470,10 @@ export function rgbFromHex(hex: string): number { /** "#rrggbb" → 0xRRGGBB, bei unlesbarer Farbe (z. B. "none") null = Farbe der Ebene. */ function rgbOrNull(hex: string): number | null { - const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim()); - return m ? parseInt(m[1], 16) : null; + const m = /^#?([0-9a-f]{6}|[0-9a-f]{3})$/i.exec(hex.trim()); + if (!m) return null; + const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1]; + return parseInt(h, 16); } /** Millimeter → DXF-LWEIGHT (1/100 mm), gerundet auf gültige Stufen ≥ 0. */ @@ -448,12 +490,13 @@ export async function savePlanDxf( await loadFileio(); const format = opts.format ?? "dxf"; const data = writeCad(format, collectPlanDrawing(plan, project, opts)); + const ext = cadExtension(format); const name = (opts.fileName ?? "grundriss").replace(/\.(dxf|dwg)$/i, ""); - const blob = new Blob([data as BlobPart], { type: format === "dxf" ? "application/dxf" : "image/vnd.dwg" }); + const blob = new Blob([data as BlobPart], { type: ext === "dxf" ? "application/dxf" : "image/vnd.dwg" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; - a.download = `${name}.${format}`; + a.download = `${name}.${ext}`; document.body.appendChild(a); a.click(); document.body.removeChild(a); diff --git a/src/export/exportIfc.ts b/src/export/exportIfc.ts index dd1e5630..3dde5c4a 100644 --- a/src/export/exportIfc.ts +++ b/src/export/exportIfc.ts @@ -31,8 +31,12 @@ // werden trotzdem als Beziehung angelegt; die Öffnung liegt im Loch und zieht nichts ab. // • Decke → IfcSlab (outline-Polygon, PredefinedType FLOOR). // • Öffnung → IfcOpeningElement (Quader über die ganze Wanddicke, etwas vorstehend) in der -// Wand (IfcRelVoidsElement), darin IfcDoor/IfcWindow (IfcRelFillsElement) mit eigener -// Box-Geometrie; kein Blatt-/Rahmendetail (bewusste Vereinfachung). +// Wand (IfcRelVoidsElement), darin IfcDoor/IfcWindow (IfcRelFillsElement) aus getrennten Körpern +// ([B5], 28.10., `ifcOpenings.ts`): Rahmen/Zarge + Türblatt bzw. Glas je Flügel, mit Farbe/ +// Transparenz je Rolle; OperationType (Tür: Blattzahl, Scharnierseite, Schiebe) und +// PartitioningType (Fenster: Flügelzahl). Masse aus dem Modell (Rahmenbreite/-tiefe, Einzug, +// Verglasung, Glasanteil, Oberlicht), sonst die Konstanten des 3D. Ohne Sprossen, Fensterbank, +// Schwelle; reine Wandöffnung ohne Körper. // • Extrusion → IfcBuildingElementProxy aus points+height. // • Dach → IfcRoof (Schicht-Meshes wie im 3D), Dachtyp → IfcRoofType mit Schichten. // • Stütze → IfcColumn (Profil-Extrusion), Bauteil → IfcMaterial. @@ -43,8 +47,12 @@ // echte Stufengeometrie ist ausgelassen (siehe stairFootprint()). // // Material-Schichten: je Wand-/Deckentyp ein IfcWallType/IfcSlabType mit -// IfcMaterialLayerSet, die Exemplare erben ihn über IfcRelDefinesByType. (Noch) KEIN -// IfcMaterialLayerSetUsage am Exemplar: die Wand hat keine Achs-Darstellung. +// IfcMaterialLayerSet, die Exemplare erben ihn über IfcRelDefinesByType. Extrusions-Wände +// ([B5], 28.10.) tragen zusätzlich eine „Axis"-Darstellung (IfcPolyline entlang der Wandachse) +// und eine IfcMaterialLayerSetUsage (AXIS2, POSITIVE, Offset = Abstand der Aussenschicht von der +// Achse), damit Revit/ArchiCAD die Schichten der Achse zuordnen: das Wand-Placement sitzt am +// 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. // // Eigenschaften ([B5]): Pset_WallCommon/SlabCommon/RoofCommon/ColumnCommon/DoorCommon/ // WindowCommon/SpaceCommon nur mit Werten, die das Modell hergibt (Reference = Typname, @@ -79,6 +87,7 @@ import { columnFootprint } from "../geometry/column"; import { openingInterval, openingVerticalExtent } from "../geometry/opening"; import { emitRoofs } from "../plan/toWalls3d/roofs"; import { fileio } from "../engine/fileioWasm"; +import { fillGeometry, type FillGeometry } from "./ifcOpenings"; /** Deterministische 22-stellige IFC-GUID aus einem Namen (Rust, `ifc_export.rs::ifc_guid`). */ export function ifcGuid(name: string): string { @@ -187,10 +196,24 @@ class FlatIfc { for (const s of m.storeys) this.nums.push(this.str(s.id), this.str(s.name), s.base); } - wallSolids(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], solids: { pts: Vec2[]; zRel: number; depth: number }[]): void { + /** + * Extrusions-Wand. `frame`: Wandanfang, Achsrichtung (Einheitsvektor), Länge und — wenn die Schichten + * des Typs genau den Wandquerschnitt füllen — der Abstand `offset` der ersten Schicht von der + * Wandachse entlang der linken Normalen (→ IfcMaterialLayerSetUsage). + */ + wallSolids( + structure: number, + id: string, + name: string, + ty: TypeRefIn | null, + psets: PsetIn[], + frame: { origin: Vec2; u: Vec2; length: number; offset: number | null }, + solids: { pts: Vec2[]; zRel: number; depth: number }[], + ): void { this.nums.push(REC_WALL_SOLIDS, structure, this.str(id), this.str(name)); this.typeRef(ty); this.psets(psets); + this.nums.push(1, frame.origin.x, frame.origin.y, frame.u.x, frame.u.y, frame.length, frame.offset === null ? 0 : 1, frame.offset ?? 0); this.nums.push(solids.length); for (const s of solids) { this.pts(s.pts); @@ -222,15 +245,19 @@ class FlatIfc { voidRect: Vec2[]; voidZRel: number; depth: number; - fillRect: Vec2[]; width: number; + fill: FillGeometry; psets: PsetIn[]; }): void { this.nums.push(REC_OPENING, this.str(o.wallId), o.structure, this.str(o.openingId), o.isDoor ? 1 : 0, this.str(o.fillName)); this.pts(o.voidRect); - this.nums.push(o.voidZRel, o.depth); - this.pts(o.fillRect); - this.nums.push(o.width); + this.nums.push(o.voidZRel, o.depth, o.width, o.fill.kind === null ? -1 : this.str(o.fill.kind)); + this.nums.push(o.fill.origin.x, o.fill.origin.y, o.fill.u.x, o.fill.u.y, o.fill.parts.length); + for (const p of o.fill.parts) { + this.nums.push(p.role); + this.pts(p.pts); + this.nums.push(p.zRel, p.depth); + } this.psets(o.psets); } @@ -583,8 +610,22 @@ export function exportIfcSpf(projectIn: Project): string { return { pts: rect, zRel: b.baseElevation - baseOf(structure), depth: b.height }; }); const id = wallIdentity(wall); - flat.wallSolids(structure, wall.id, id.name, id.ty, id.psets, solids); - hostExtent.set(wall.id, crossExtent(wall, bands)); + // 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). + const extent = crossExtent(wall, bands); + const layerSum = id.ty?.layers.reduce((a, l) => a + l.thickness, 0) ?? 0; + const usage = id.ty !== null && layerSum > 0 && Math.abs(extent.nHi - extent.nLo - layerSum) < 1e-3; + flat.wallSolids( + structure, + wall.id, + id.name, + id.ty, + id.psets, + { origin: wall.start, u: normalize(sub(wall.end, wall.start)), length: Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y), offset: usage ? extent.nLo : null }, + solids, + ); + hostExtent.set(wall.id, extent); } // Mesh-Weg: Loch-Ausschnitte aller betroffenen Bänder in EINEM Kern-Aufruf. const meshBands = meshWalls.flatMap((m) => m.bands); @@ -638,8 +679,8 @@ export function exportIfcSpf(projectIn: Project): string { // ── Öffnungen: IfcOpeningElement in der Wand, IfcDoor/IfcWindow darin ─── // Der Öffnungskörper ist ein Quader über das Achs-Intervall und die Höhe, wie sie das 3D // stanzt (`openingInterval`/`openingVerticalExtent`), quer über alle Bänder der Wand plus - // OPENING_OVERSHOOT. Die Füllung (Tür/Fenster) sitzt im Öffnungs-Placement, über die - // Banddicke, ohne Blatt-/Rahmendetail. + // OPENING_OVERSHOOT. Die Füllung (Tür/Fenster) hat ein eigenes Placement + // (Öffnungsmitte, Achse bzw. Aufschlagrichtung) und liegt in der Rahmentiefe (`ifcOpenings.ts`). for (const wall of project.walls ?? []) { const host = hostExtent.get(wall.id); if (!host) continue; // Wirtswand übersprungen (degeneriert) @@ -673,8 +714,8 @@ export function exportIfcSpf(projectIn: Project): string { voidRect: axisRect(wall, c.from, c.to, host.nLo - OPENING_OVERSHOOT, host.nHi + OPENING_OVERSHOOT), voidZRel: c.zBottom - baseOf(structure), depth, - fillRect: axisRect(wall, c.from, c.to, host.nLo, host.nHi), width: c.to - c.from, + fill: fillGeometry(project, wall, opening, c, host), psets: [{ name: psetName, props }], }); } diff --git a/src/export/exportIfc.validate.test.ts b/src/export/exportIfc.validate.test.ts index e02e19a8..c25507c4 100644 --- a/src/export/exportIfc.validate.test.ts +++ b/src/export/exportIfc.validate.test.ts @@ -39,7 +39,7 @@ for w in m.by_type("IfcWall"): sh = ifcopenshell.geom.create_shape(s, w) out[w.GlobalId] = {"volume": us.get_volume(sh.geometry), "openings": len(w.HasOpenings), "fills": sum(len(r.RelatedOpeningElement.HasFillings) for r in w.HasOpenings), - "rep": w.Representation.Representations[0].RepresentationType} + "rep": [r for r in w.Representation.Representations if r.RepresentationIdentifier == "Body"][0].RepresentationType} print(json.dumps(out)) `; @@ -52,6 +52,95 @@ function wallVolumes(name: string, ifc: string): Record { return JSON.parse(r.stdout); } +// Achse und IfcMaterialLayerSetUsage je IfcWall: Placement, Achs-Polylinie (lokal), Usage und je +// Körper (Extrusion) der Bereich quer zur Achse (lokal Y) — alles unabhängig vom Exporter gelesen. +const WALL_AXES = ` +import json, sys +import ifcopenshell, ifcopenshell.util.placement as up +m = ifcopenshell.open(sys.argv[1]) +out = {} +for w in m.by_type("IfcWall"): + reps = {r.RepresentationIdentifier: r for r in w.Representation.Representations} + mat = up.get_local_placement(w.ObjectPlacement) + item = {"identifiers": sorted(reps), "usage": None, "axis": None, "items": []} + if "Axis" in reps: + pts = [p.Coordinates for p in reps["Axis"].Items[0].Points] + a = mat @ [pts[0][0], pts[0][1], 0, 1] + b = mat @ [pts[1][0], pts[1][1], 0, 1] + item["axis"] = [[a[0], a[1]], [b[0], b[1]], reps["Axis"].RepresentationType, [list(p) for p in pts]] + for e in reps["Body"].Items: + if e.is_a("IfcExtrudedAreaSolid"): + ys = [p.Coordinates[1] for p in e.SweptArea.OuterCurve.Points] + item["items"].append([min(ys), max(ys)]) + for rel in w.HasAssociations: + if rel.is_a("IfcRelAssociatesMaterial") and rel.RelatingMaterial.is_a("IfcMaterialLayerSetUsage"): + u = rel.RelatingMaterial + item["usage"] = {"dir": u.LayerSetDirection, "sense": u.DirectionSense, "offset": u.OffsetFromReferenceLine, + "layers": [l.LayerThickness for l in u.ForLayerSet.MaterialLayers]} + out[w.GlobalId] = item +print(json.dumps(out)) +`; + +interface WallAxis { + identifiers: string[]; + usage: { dir: string; sense: string; offset: number; layers: number[] } | null; + axis: [number[], number[], string, number[][]] | null; + items: number[][]; +} + +function wallAxes(name: string, ifc: string): Record { + const r = spawnSync("python3", ["-c", WALL_AXES, writeIfc(name, ifc)], { encoding: "utf8", timeout: 120_000 }); + expect(r.status, r.stderr).toBe(0); + return JSON.parse(r.stdout); +} + +// Türen/Fenster nach ifcopenshell: Körper je Darstellungselement (Volumen, Welt-Bounding-Box), Stil je +// Element und Ausführung. +const FILL_INFO = ` +import json, sys +import ifcopenshell, ifcopenshell.geom, ifcopenshell.util.shape as us +m = ifcopenshell.open(sys.argv[1]) +s = ifcopenshell.geom.settings() +s.set("use-world-coords", True) +out = [] +for e in m.by_type("IfcDoor") + m.by_type("IfcWindow"): + sh = ifcopenshell.geom.create_shape(s, e) + v = sh.geometry.verts + xs, ys, zs = v[0::3], v[1::3], v[2::3] + items = [] + rep = [r for r in e.Representation.Representations if r.RepresentationIdentifier == "Body"][0] + for it in rep.Items: + solid = ifcopenshell.geom.create_shape(s, it) + styles = [st.Name for si in it.StyledByItem for ps in si.Styles for st in [ps]] + items.append({"volume": us.get_volume(solid), "styles": styles, + "z": [min(solid.verts[2::3]), max(solid.verts[2::3])]}) + out.append({"type": e.is_a(), "name": e.Name, "volume": us.get_volume(sh.geometry), + "bbox": [min(xs), max(xs), min(ys), max(ys), min(zs), max(zs)], "items": items, + "op": getattr(e, "OperationType", None) or getattr(e, "PartitioningType", None), + "predefined": e.PredefinedType, "h": e.OverallHeight, "w": e.OverallWidth, + "filled": len(e.FillsVoids)}) +print(json.dumps(out)) +`; + +interface FillInfo { + type: string; + name: string; + volume: number; + bbox: number[]; + items: { volume: number; styles: string[]; z: number[] }[]; + op: string | null; + predefined: string; + h: number; + w: number; + filled: number; +} + +function fillInfo(name: string, ifc: string): FillInfo[] { + const r = spawnSync("python3", ["-c", FILL_INFO, writeIfc(name, ifc)], { encoding: "utf8", timeout: 120_000 }); + expect(r.status, r.stderr).toBe(0); + return JSON.parse(r.stdout); +} + /** Eine freistehende Wand 5 × 0.4 × 2.6 m mit einem Fenster 1.2 × 1.2 m (Brüstung 0.9 m). */ function singleWall(recess: boolean): Project { return { @@ -134,4 +223,124 @@ describe.skipIf(!hasIfcOpenShell)("IFC-Export gegen ifcopenshell", { timeout: 60 } expect(swept).toBeGreaterThan(0); }); + + it("[B5] Wandachse + LayerSetUsage: Achse = Wandachse, Schichten ab Aussenfläche in Normalenrichtung", () => { + // Zwei Schichten (0.1 aussen, 0.3 innen), Wand schräg gestellt und rückwärts gezeichnet. + const [c0, c1] = sampleProject.components; + const base = singleWall(false); + const rotated: Project = { + ...base, + walls: [{ ...base.walls[0], start: { x: 12, y: 7 }, end: { x: 9, y: 3 } }], + wallTypes: [...base.wallTypes.filter((t) => t.id !== "solo"), { id: "solo", name: "Zweischicht", layers: [{ componentId: c0.id, thickness: 0.1 }, { componentId: c1.id, thickness: 0.3 }] }], + openings: [], + }; + const ifc = exportIfcSpf(rotated); + expect(validate("achse", ifc).out).toContain("0 Befunde"); + const [w] = Object.values(wallAxes("achse", ifc)); + expect(w.identifiers).toEqual(["Axis", "Body"]); + expect(w.axis![2]).toBe("Curve2D"); + expect(w.axis![0][0]).toBeCloseTo(12, 6); + expect(w.axis![0][1]).toBeCloseTo(7, 6); + expect(w.axis![1][0]).toBeCloseTo(9, 6); + expect(w.axis![1][1]).toBeCloseTo(3, 6); + expect(w.axis![3][1]).toEqual([5, 0]); // Länge √(9+16) = 5 entlang lokal X + expect(w.usage).toMatchObject({ dir: "AXIS2", sense: "POSITIVE", layers: [0.1, 0.3] }); + // Referenzlinie in der Mitte (Standard) → Offset −total/2; Körper je Schicht in Reihenfolge. + const off = w.usage!.offset; + let y = off; + expect(w.items.length).toBe(2); + w.items.forEach(([lo, hi], i) => { + expect(lo).toBeCloseTo(y, 6); + y += w.usage!.layers[i]; + expect(hi).toBeCloseTo(y, 6); + }); + }); + it("[B5] Demo-Haus: jede Extrusions-Wand hat Achse und Usage, Körper-Bänder = Schichten in Reihenfolge", () => { + const project = sampleProject; + const axes = wallAxes("demo-achsen", exportIfcSpf(project)); + let withAxis = 0; + for (const wall of project.walls) { + const w = axes[ifcGuid(`${project.id}/wall/${wall.id}`)]; + expect(w, wall.id).toBeDefined(); + if (!w.axis) { + expect(w.usage, wall.id).toBeNull(); // Mesh-Wand + continue; + } + withAxis++; + expect(w.axis[0][0], wall.id).toBeCloseTo(wall.start.x, 6); + expect(w.axis[0][1], wall.id).toBeCloseTo(wall.start.y, 6); + expect(w.axis[1][0], wall.id).toBeCloseTo(wall.end.x, 6); + expect(w.axis[1][1], wall.id).toBeCloseTo(wall.end.y, 6); + if (!w.usage) continue; // Schichtsumme passt nicht zum Querschnitt + // Mehrere Bänder je Schicht möglich (Joins): die verschiedenen Querbereiche ergeben die Schichten. + const spans = [...new Map(w.items.map(([lo, hi]) => [`${lo.toFixed(6)}/${hi.toFixed(6)}`, [lo, hi]])).values()].sort((a, b) => a[0] - b[0]); + expect(spans.length, wall.id).toBe(w.usage.layers.length); + let y = w.usage.offset; + spans.forEach(([lo, hi], i) => { + expect(lo, `${wall.id} Schicht ${i}`).toBeCloseTo(y, 6); + y += w.usage!.layers[i]; + expect(hi, `${wall.id} Schicht ${i}`).toBeCloseTo(y, 6); + }); + } + expect(withAxis).toBeGreaterThan(0); + }); + + it("[B5] Fenster: Rahmen + Glas als getrennte Körper, Volumen und Lage = Modell", () => { + const ifc = exportIfcSpf(singleWall(false)); // Fenster 1.2 × 1.2 bei x 1…2.2, Brüstung 0.9, Wand 0.4 dick, dreifach + expect(validate("fenster-koerper", ifc).out).toContain("0 Befunde"); + const [f] = fillInfo("fenster-koerper", ifc); + expect(f.type).toBe("IfcWindow"); + expect(f.filled).toBe(1); + expect(f.op).toBe("SINGLE_PANEL"); + expect(f.items.map((i) => i.styles[0]).sort()).toEqual(["Glas", "Rahmen", "Rahmen", "Rahmen", "Rahmen"]); + const fw = 0.06; + const frame = (1.2 * 1.2 - (1.2 - 2 * fw) ** 2) * 0.07; + const glass = (1.2 - 2 * fw) ** 2 * 0.036; // dreifach: 36 mm + expect(f.volume).toBeCloseTo(frame + glass, 6); + const glassItem = f.items.find((i) => i.styles[0] === "Glas")!; + expect(glassItem.volume).toBeCloseTo(glass, 6); + // Welt-Lage: x 1…2.2, Wandaussenseite y −0.2 + Rahmentiefe, z = Brüstung … Brüstung + 1.2 (Geschoss-UK 0). + expect(f.bbox[0]).toBeCloseTo(1, 6); + expect(f.bbox[1]).toBeCloseTo(2.2, 6); + expect(f.bbox[2]).toBeCloseTo(-0.2, 6); + expect(f.bbox[3]).toBeCloseTo(-0.2 + 0.07, 6); + expect(f.bbox[4]).toBeCloseTo(0.9, 6); + expect(f.bbox[5]).toBeCloseTo(2.1, 6); + expect(f.h).toBeCloseTo(1.2, 9); + expect(f.w).toBeCloseTo(1.2, 9); + }); + it("[B5] Tür (Wand schräg gestellt): Zarge, zwei Glasblätter, OperationType; Körper liegen in der Öffnung", () => { + const base = singleWall(false); + const dtype = { id: "dt", name: "Glastür", kind: "dreh", leafCount: 2, leafStyle: "glas", glazingRatio: 0.5, frameThickness: 0.06, defaultWidth: 1.6, defaultHeight: 2.1 }; + const p: Project = { + ...base, + walls: [{ ...base.walls[0], start: { x: 3, y: 1 }, end: { x: 3, y: 6 } }], // entlang +Y, linke Normale = −X + doorTypes: [dtype], + windowTypes: [], + openings: [{ id: "T1", type: "opening", hostWallId: "W1", categoryCode: "21", kind: "door", position: 1, width: 1.6, height: 2.1, sillHeight: 0, typeId: "dt", hinge: "end", swing: "left" }], + } as unknown as Project; + const ifc = exportIfcSpf(p); + expect(validate("tuer-koerper", ifc).out).toContain("0 Befunde"); + const [d] = fillInfo("tuer-koerper", ifc); + expect(d.type).toBe("IfcDoor"); + expect(d.filled).toBe(1); + // Wand entlang +Y: n = (−1, 0); swing links/innen → Aufschlag −X; Scharnier am Ende, zweiflügelig → DOUBLE_DOOR_SINGLE_SWING. + expect(d.op).toBe("DOUBLE_DOOR_SINGLE_SWING"); + // Rahmen: 3 Teile; Blätter: 2 × (4 Rahmenteile) mit Stil „Türblatt"; Glas: 2. + const roles = d.items.map((i) => i.styles[0]); + expect(roles.filter((r) => r === "Rahmen").length).toBe(3); + expect(roles.filter((r) => r === "Türblatt").length).toBe(8); + expect(roles.filter((r) => r === "Glas").length).toBe(2); + // Lage: Achse y 2…3.6 (Öffnung ab 1 m), quer zur Wand (x) innerhalb der Wanddicke 2.8…3.2, Boden z = 0. + expect(d.bbox[2]).toBeCloseTo(2, 6); + expect(d.bbox[3]).toBeCloseTo(3.6, 6); + expect(d.bbox[0]).toBeGreaterThanOrEqual(2.8 - 1e-6); + expect(d.bbox[1]).toBeLessThanOrEqual(3.2 + 1e-6); + expect(d.bbox[4]).toBeCloseTo(0, 6); + expect(d.bbox[5]).toBeCloseTo(2.1, 6); + // Glasanteil je Blatt = 50 % der Blattfläche (Blatt 0.74 × 2.04 je Flügel). + const leafArea = 0.74 * (2.1 - 0.06); + const glassVol = d.items.filter((i) => i.styles[0] === "Glas").reduce((a, i) => a + i.volume, 0); + expect(glassVol).toBeCloseTo(2 * leafArea * 0.5 * 0.024, 6); + }); }); diff --git a/src/export/ifcOpenings.test.ts b/src/export/ifcOpenings.test.ts new file mode 100644 index 00000000..3d1a3366 --- /dev/null +++ b/src/export/ifcOpenings.test.ts @@ -0,0 +1,204 @@ +// Geometrie der Türen/Fenster im IFC-Export ([B5]): Rahmen, Blatt, Glas, Ausführung. Reine Rechnung, +// kein WASM nötig. + +import { describe, expect, it } from "vitest"; +import { fillGeometry, DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_DEPTH, DOOR_LEAF_THICK } from "./ifcOpenings"; +import type { DoorType, Opening, Project, Wall, WindowType } from "../model/types"; + +const wall = { id: "W", start: { x: 0, y: 0 }, end: { x: 5, y: 0 } } as Wall; +const host = { nLo: -0.2, nHi: 0.2 }; + +function proj(over: { doorTypes?: DoorType[]; windowTypes?: WindowType[] }): Project { + return { doorTypes: over.doorTypes ?? [], windowTypes: over.windowTypes ?? [] } as unknown as Project; +} +function door(over: Partial = {}): Opening { + return { id: "D", type: "opening", hostWallId: "W", categoryCode: "21", kind: "door", position: 1, width: 1, height: 2.1, sillHeight: 0, ...over } as Opening; +} +function win(over: Partial = {}): Opening { + return { id: "F", type: "opening", hostWallId: "W", categoryCode: "21", kind: "window", position: 1, width: 1.2, height: 1.2, sillHeight: 0.9, ...over } as Opening; +} +const cut = (o: Opening) => ({ from: o.position, to: o.position + o.width, zBottom: o.sillHeight, zTop: o.sillHeight + o.height }); +const wt = (over: Partial = {}): WindowType => + ({ id: "wt", name: "Fenster", kind: "dreh", wingCount: 1, glazing: "zweifach", frameThickness: 0.08, defaultSillHeight: 0.9, defaultWidth: 1.2, defaultHeight: 1.2, ...over }) as WindowType; +const dtp = (over: Partial = {}): DoorType => + ({ id: "dt", name: "Tür", kind: "dreh", leafCount: 1, leafStyle: "glatt", frameThickness: 0.06, defaultWidth: 1, defaultHeight: 2.1, ...over }) as DoorType; + +const bbox = (pts: { x: number; y: number }[]) => ({ + x0: Math.min(...pts.map((p) => p.x)), + x1: Math.max(...pts.map((p) => p.x)), + y0: Math.min(...pts.map((p) => p.y)), + y1: Math.max(...pts.map((p) => p.y)), +}); +const volume = (parts: { pts: { x: number; y: number }[]; depth: number }[]) => + parts.reduce((a, p) => { + const b = bbox(p.pts); + return a + (b.x1 - b.x0) * (b.y1 - b.y0) * p.depth; + }, 0); + +describe("fillGeometry — Fenster", () => { + it("Blendrahmen aus 4 Teilen + eine Glasscheibe, Masse aus Konstanten, Glas = Paketdicke", () => { + const o = win({ typeId: "wt" }); + const g = fillGeometry(proj({ windowTypes: [wt()] }), wall, o, cut(o), host); + const frame = g.parts.filter((p) => p.role === 0); + const glass = g.parts.filter((p) => p.role === 2); + expect(frame.length).toBe(4); + expect(glass.length).toBe(1); + expect(g.kind).toBe("SINGLE_PANEL"); + // Rahmenvolumen = (W·H − lichtes Mass) · Tiefe + const fw = DEFAULT_FRAME_WIDTH; + expect(volume(frame)).toBeCloseTo((1.2 * 1.2 - (1.2 - 2 * fw) * (1.2 - 2 * fw)) * DEFAULT_FRAME_DEPTH, 9); + // Glas füllt das lichte Mass, 24 mm (zweifach), mittig in der Rahmentiefe (aussen = nLo). + const gb = bbox(glass[0].pts); + expect(gb.x1 - gb.x0).toBeCloseTo(1.2 - 2 * fw, 9); + expect(gb.y1 - gb.y0).toBeCloseTo(0.024, 9); + expect((gb.y0 + gb.y1) / 2).toBeCloseTo(-0.2 + DEFAULT_FRAME_DEPTH / 2, 9); + expect(glass[0].zRel).toBeCloseTo(fw, 9); + expect(glass[0].depth).toBeCloseTo(1.2 - 2 * fw, 9); + }); + it("Rahmenbreite/-tiefe/Einzug/Verglasung aus dem Typ; Einzug von innen", () => { + const o = win({ typeId: "wt" }); + const t = wt({ frameWidth: 0.09, frameDepth: 0.1, insetFromFace: 0.05, insetFace: "innen", glazing: "dreifach" }); + const g = fillGeometry(proj({ windowTypes: [t] }), wall, o, cut(o), host); + const frame = g.parts.filter((p) => p.role === 0); + const b = bbox(frame[0].pts); + // innen = nHi: Vorderkante 5 cm eingezogen → Rahmen von 0.05 bis 0.15 (Tiefe 10 cm nach aussen) + expect(b.y0).toBeCloseTo(0.05, 9); + expect(b.y1).toBeCloseTo(0.15, 9); + expect(bbox(frame[2].pts).y1 - bbox(frame[2].pts).y0).toBeCloseTo(0.1, 9); + const gl = bbox(g.parts.find((p) => p.role === 2)!.pts); + expect(gl.y1 - gl.y0).toBeCloseTo(0.036, 9); + expect(gl.x1 - gl.x0).toBeCloseTo(1.2 - 0.18, 9); + }); + it("Rahmentiefe wird auf die Wanddicke geklemmt", () => { + const o = win({ typeId: "wt" }); + const g = fillGeometry(proj({ windowTypes: [wt({ frameDepth: 1 })] }), wall, o, cut(o), host); + const b = bbox(g.parts[0].pts); + expect(b.y0).toBeCloseTo(-0.2, 9); + expect(b.y1).toBeCloseTo(0.2, 9); + }); + it("Flügelzahl → Mittelpfosten + eine Scheibe je Flügel, PartitioningType", () => { + for (const [wing, kind] of [ + [2, "DOUBLE_PANEL_VERTICAL"], + [3, "TRIPLE_PANEL_VERTICAL"], + [4, "NOTDEFINED"], + ] as const) { + const o = win({ typeId: "wt", wingCount: wing }); + const g = fillGeometry(proj({ windowTypes: [wt()] }), wall, o, cut(o), host); + expect(g.parts.filter((p) => p.role === 2).length, `${wing}`).toBe(wing); + expect(g.parts.filter((p) => p.role === 0).length, `${wing}`).toBe(4 + (wing - 1)); + expect(g.kind).toBe(kind); + } + }); + it("Flügeltabelle mit Pfosten und fester Breite: Gläser abgrenzend, keine Überlappung", () => { + const o = win({ typeId: "wt" }); + const t = wt({ + sashes: [ + { kind: "fluegel", autoWidth: false, width: 0.5 }, + { kind: "pfosten", postWidth: 0.1 }, + { kind: "fluegel" }, + ], + }); + const g = fillGeometry(proj({ windowTypes: [t] }), wall, o, cut(o), host); + const glass = g.parts.filter((p) => p.role === 2).map((p) => bbox(p.pts)); + expect(glass.length).toBe(2); + expect(glass[0].x1 - glass[0].x0).toBeCloseTo(0.5, 9); + const clear = 1.2 - 2 * 0.06; + expect(glass[1].x1 - glass[1].x0).toBeCloseTo(clear - 0.6, 9); + expect(glass[1].x0).toBeCloseTo(glass[0].x1 + 0.1, 9); + expect(g.kind).toBe("DOUBLE_PANEL_VERTICAL"); + }); + it("ohne Typ: Standardmasse, zweifach, Flügelzahl der Öffnung", () => { + const o = win({ wingCount: 2 }); + const g = fillGeometry(proj({}), wall, o, cut(o), host); + const glass = g.parts.filter((p) => p.role === 2); + expect(glass.length).toBe(2); + const b = bbox(glass[0].pts); + expect(b.y1 - b.y0).toBeCloseTo(0.024, 9); + }); + it("alle Teile liegen innerhalb der Öffnung und der Wand", () => { + const o = win({ typeId: "wt", wingCount: 2 }); + const g = fillGeometry(proj({ windowTypes: [wt()] }), wall, o, cut(o), host); + for (const p of g.parts) { + const b = bbox(p.pts); + expect(b.x0).toBeGreaterThanOrEqual(1 - 1e-9); + expect(b.x1).toBeLessThanOrEqual(2.2 + 1e-9); + expect(b.y0).toBeGreaterThanOrEqual(-0.2 - 1e-9); + expect(b.y1).toBeLessThanOrEqual(0.2 + 1e-9); + expect(p.zRel).toBeGreaterThanOrEqual(-1e-9); + expect(p.zRel + p.depth).toBeLessThanOrEqual(1.2 + 1e-9); + } + }); +}); + +describe("fillGeometry — Tür", () => { + it("Zarge (3 Teile) + Blatt, Blatt 4 cm mittig, Höhe bis unter den Sturz", () => { + const o = door({ typeId: "dt" }); + const g = fillGeometry(proj({ doorTypes: [dtp()] }), wall, o, cut(o), host); + expect(g.parts.filter((p) => p.role === 0).length).toBe(3); + const leaf = g.parts.filter((p) => p.role === 1); + expect(leaf.length).toBe(1); + const lb = bbox(leaf[0].pts); + expect(lb.y1 - lb.y0).toBeCloseTo(DOOR_LEAF_THICK, 9); + expect(lb.x1 - lb.x0).toBeCloseTo(1 - 2 * DEFAULT_FRAME_WIDTH, 9); + expect(leaf[0].zRel).toBe(0); + expect(leaf[0].depth).toBeCloseTo(2.1 - DEFAULT_FRAME_WIDTH, 9); + expect(g.parts.some((p) => p.role === 2)).toBe(false); + }); + it("zweiflügelig: zwei Blätter, DOUBLE_DOOR_SINGLE_SWING", () => { + const o = door({ typeId: "dt" }); + const g = fillGeometry(proj({ doorTypes: [dtp({ leafCount: 2 })] }), wall, o, cut(o), host); + expect(g.parts.filter((p) => p.role === 1).length).toBe(2); + expect(g.kind).toBe("DOUBLE_DOOR_SINGLE_SWING"); + }); + it("Glastür: Glasfläche = glazingRatio des Blatts, Blatt als Rahmen darum, ohne Überlappung", () => { + const o = door({ typeId: "dt" }); + const g = fillGeometry(proj({ doorTypes: [dtp({ leafStyle: "glas", glazingRatio: 0.36 })] }), wall, o, cut(o), host); + const glass = g.parts.filter((p) => p.role === 2); + expect(glass.length).toBe(1); + const gb = bbox(glass[0].pts); + const leafW = 1 - 2 * DEFAULT_FRAME_WIDTH; + const leafH = 2.1 - DEFAULT_FRAME_WIDTH; + expect(((gb.x1 - gb.x0) * glass[0].depth) / (leafW * leafH)).toBeCloseTo(0.36, 9); + const leaf = g.parts.filter((p) => p.role === 1); + expect(leaf.length).toBe(4); + // Blatt ohne Glasfläche = volle Blattfläche − Glasfläche, über 4 cm + expect(volume(leaf)).toBeCloseTo((leafW * leafH - (gb.x1 - gb.x0) * glass[0].depth) * DOOR_LEAF_THICK, 9); + }); + it("Oberlicht: Riegel + Glasstreifen, Blatt entsprechend kürzer", () => { + const o = door({ typeId: "dt" }); + const g = fillGeometry(proj({ doorTypes: [dtp({ transomHeight: 0.4 })] }), wall, o, cut(o), host); + const glass = g.parts.filter((p) => p.role === 2); + expect(glass.length).toBe(1); + expect(glass[0].depth).toBeCloseTo(0.4, 9); + expect(glass[0].zRel + glass[0].depth).toBeCloseTo(2.1 - DEFAULT_FRAME_WIDTH, 9); + const leaf = g.parts.find((p) => p.role === 1)!; + expect(leaf.zRel + leaf.depth).toBeCloseTo(2.1 - DEFAULT_FRAME_WIDTH - 0.4 - DEFAULT_FRAME_WIDTH, 9); + }); + it("reine Wandöffnung (Typ oder Inline): kein Körper, keine Ausführung", () => { + const o = door({ typeId: "dt" }); + expect(fillGeometry(proj({ doorTypes: [dtp({ kind: "wandoeffnung" })] }), wall, o, cut(o), host)).toMatchObject({ kind: null, parts: [] }); + const o2 = door({ doorType: "wandoeffnung" }); + expect(fillGeometry(proj({}), wall, o2, cut(o2), host)).toMatchObject({ kind: null, parts: [] }); + }); + it("Scharnierseite und Aufschlag → LEFT/RIGHT (von der Aufschlagseite gesehen), Schiebetür", () => { + // Wand entlang +X, linke Normale +Y. Standard: Aufschlag nach +Y, Scharnier am Anfang (x klein): + // von +Y nach −Y gesehen liegt x klein rechts → RIGHT. + const kind = (o: Opening, t: DoorType = dtp()) => fillGeometry(proj({ doorTypes: [t] }), wall, o, cut(o), host).kind; + expect(kind(door({ typeId: "dt" }))).toBe("SINGLE_SWING_RIGHT"); + expect(kind(door({ typeId: "dt", hinge: "end" }))).toBe("SINGLE_SWING_LEFT"); + // Aufschlag nach aussen (−Y): Blickrichtung dreht → Seiten tauschen. + expect(kind(door({ typeId: "dt", openingDir: "out" }))).toBe("SINGLE_SWING_LEFT"); + expect(kind(door({ typeId: "dt", swing: "right" }))).toBe("SINGLE_SWING_LEFT"); + expect(kind(door({ typeId: "dt" }), dtp({ kind: "schiebe" }))).toBe("SLIDING_TO_RIGHT"); + expect(kind(door({ typeId: "dt" }), dtp({ kind: "schiebe", leafCount: 2 }))).toBe("DOUBLE_DOOR_SLIDING"); + }); + it("Füllungssystem: Y = Aufschlagrichtung, Ursprung = Öffnungsmitte auf der Achse", () => { + const o = door({ typeId: "dt" }); + const g = fillGeometry(proj({ doorTypes: [dtp()] }), wall, o, cut(o), host); + expect(g.origin).toEqual({ x: 1.5, y: 0 }); + expect(g.u.x).toBeCloseTo(1, 12); // Aufschlag +Y → X = (swing.y, −swing.x) = (1, 0) + expect(g.u.y).toBeCloseTo(0, 12); + const out = fillGeometry(proj({ doorTypes: [dtp()] }), wall, door({ typeId: "dt", openingDir: "out" }), cut(o), host); + expect(out.u.x).toBeCloseTo(-1, 12); + }); +}); diff --git a/src/export/ifcOpenings.ts b/src/export/ifcOpenings.ts new file mode 100644 index 00000000..9594763f --- /dev/null +++ b/src/export/ifcOpenings.ts @@ -0,0 +1,260 @@ +// Geometrie der Türen und Fenster für den IFC-Export ([B5], 28.10.): statt einer Box getrennte Körper im +// selben Bauteil — Rahmen/Zarge, Türblatt bzw. Glas — plus OperationType (Tür) und PartitioningType +// (Fenster). Alles sind vertikale Extrusionen von Grundriss-Rechtecken (wie die Wände), Profile in +// Welt-XY, Höhen ab Öffnungs-Unterkante; Rust (`ifc_export.rs`) rechnet sie ins Füllungssystem. +// +// Masse kommen aus dem Modell, soweit es sie hergibt (Rahmenbreite/-tiefe, Schichteinzug, Flügelzahl und +// -tabelle, Verglasung, Blattzahl, Glasanteil, Oberlicht). Fehlendes füllen dieselben Konstanten wie das +// 3D (`src-tauri/core/src/openings3d.rs`), damit IFC und Ansicht dasselbe zeigen: +// - Rahmenbreite 6 cm (`DEFAULT_FRAME_WIDTH`), Rahmentiefe 7 cm (`DEFAULT_FRAME_DEPTH`: reale Rahmen +// sind 70–90 mm tief, nicht so dick wie die Wand), Türblatt 4 cm (`DOOR_LEAF_THICK`). +// - Glaspaket: nur im IFC nötig, das 3D zeichnet Einzelscheiben. 1 Scheibe 6 mm, 2 Scheiben 24 mm +// (4-16-4, übliches Isolierglas), 3 Scheiben 36 mm (4-12-4-12-4 ≈ 36 mm). +// Nicht abgebildet (bewusst einfach): Sprossen, Fensterbank/Rollladenkasten, Schwelle, Flügelrahmen im +// Blendrahmen, Kassettenfelder, Schiebe-Laufschiene — die Körper stehen im geschlossenen Zustand. + +import type { Opening, Project, SashDef, Vec2, Wall } from "../model/types"; +import { getDoorType, getWindowType, glazingPanesOf } from "../model/types"; + +/** Rolle eines Körpers: 0 Rahmen/Zarge, 1 Türblatt, 2 Glas (Kodierung `ifc_export.rs`). */ +export type FillRole = 0 | 1 | 2; + +export interface FillPart { + role: FillRole; + /** Profil in Welt-XY (Rechteck, gegen den Uhrzeigersinn in Achs-/Normalenrichtung). */ + pts: Vec2[]; + /** Unterkante ab Öffnungs-Unterkante (m). */ + zRel: number; + /** Höhe des Körpers (m). */ + depth: number; +} + +export interface FillGeometry { + /** Ursprung des Füllungssystems (Welt-XY): Öffnungsmitte auf der Wandachse. */ + origin: Vec2; + /** X-Richtung des Füllungssystems (Einheitsvektor); Y = linke Normale davon. */ + u: Vec2; + /** IfcDoorTypeOperationEnum bzw. IfcWindowTypePartitioningEnum; null = Modell gibt nichts her. */ + kind: string | null; + parts: FillPart[]; +} + +export const DEFAULT_FRAME_WIDTH = 0.06; +export const DEFAULT_FRAME_DEPTH = 0.07; +export const DOOR_LEAF_THICK = 0.04; +/** Glaspaket-Dicke je Scheibenzahl (1, 2, 3). */ +export const GLASS_PACKAGE_THICKNESS = [0.006, 0.024, 0.036] as const; +/** Glasanteil des Türblatts, wenn der Typ keinen angibt (`glas` ohne `glazingRatio`). */ +const DEFAULT_GLAZING_RATIO = 0.5; +/** Kleinste Teilabmessung, damit nie ein flaches Profil entsteht (Meter). */ +const MIN_DIM = 0.005; + +const sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y }); +const norm = (v: Vec2): Vec2 => { + const len = Math.hypot(v.x, v.y) || 1; + return { x: v.x / len, y: v.y / len }; +}; +const leftOf = (u: Vec2): Vec2 => ({ x: -u.y, y: u.x }); +const dotv = (a: Vec2, b: Vec2): number => a.x * b.x + a.y * b.y; + +/** Flügeleinteilung eines Fensters, auf die Achsbreite aufgelöst: (von, bis, Pfosten?) ab Laibungsanfang. */ +interface SashSpan { + from: number; + to: number; + post: boolean; +} + +/** + * Löst Flügel (`fluegel`) und Pfosten (`pfosten`) zu Intervallen auf: Pfosten und Flügel mit fester Breite + * behalten sie, die übrigen teilen den Rest gleichmässig (gleiche Regel wie `sashSegments` im 2D). Ohne + * Tabelle: `wingCount` gleiche Flügel. + */ +function sashSpans(sashes: readonly SashDef[] | undefined, wingCount: number, total: number): SashSpan[] { + const list: readonly SashDef[] = + sashes && sashes.length > 0 + ? sashes + : Array.from({ length: Math.max(1, Math.round(wingCount)) }, (): SashDef => ({ kind: "fluegel" })); + const postW = (s: SashDef): number => Math.max(0, s.postWidth ?? 0.06); + const fixedW = (s: SashDef): number | null => (s.kind === "pfosten" ? postW(s) : s.autoWidth === false ? Math.max(0, s.width ?? 0) : null); + let fixed = 0; + let auto = 0; + for (const s of list) { + const w = fixedW(s); + if (w === null) auto++; + else fixed += w; + } + const autoW = auto > 0 ? Math.max(0, total - fixed) / auto : 0; + const out: SashSpan[] = []; + let at = 0; + for (const s of list) { + const w = fixedW(s) ?? autoW; + out.push({ from: at, to: at + w, post: s.kind === "pfosten" }); + at += w; + } + return out; +} + +/** + * Körper und Ausführung der Füllung einer Öffnung. + * + * `c` = Achs-Intervall (`from`/`to`, Abstand ab `wall.start`) und absolute Höhen der Öffnung, `host` = + * Querausdehnung der ganzen Wand (`nLo`/`nHi` entlang der linken Normalen ab `wall.start`; `nLo` ist die + * Aussenseite, wie im 2D/3D). + */ +export function fillGeometry( + project: Project, + wall: Wall, + opening: Opening, + c: { from: number; to: number; zBottom: number; zTop: number }, + host: { nLo: number; nHi: number }, +): FillGeometry { + const u = norm(sub(wall.end, wall.start)); + const n = leftOf(u); + const isDoor = opening.kind === "door"; + const W = c.to - c.from; + const H = c.zTop - c.zBottom; + const at = (a: number, b: number): Vec2 => ({ + x: wall.start.x + u.x * a + n.x * b, + y: wall.start.y + u.y * a + n.y * b, + }); + /** Rechteck [a0,a1] entlang der Achse × [b0,b1] quer dazu (Welt-XY). */ + const rect = (a0: number, a1: number, b0: number, b1: number): Vec2[] => [at(a0, b0), at(a1, b0), at(a1, b1), at(a0, b1)]; + const center = c.from + W / 2; + const origin = at(center, 0); + const parts: FillPart[] = []; + const add = (role: FillRole, a0: number, a1: number, b0: number, b1: number, z0: number, z1: number): void => { + if (a1 - a0 < 1e-6 || b1 - b0 < 1e-6 || z1 - z0 < 1e-6) return; + parts.push({ role, pts: rect(a0, a1, b0, b1), zRel: z0, depth: z1 - z0 }); + }; + + const dt = isDoor ? getDoorType(project, opening) : undefined; + const wt = isDoor ? undefined : getWindowType(project, opening); + const t = dt ?? wt; + + // Querlage des Rahmens: Tiefe (Typ oder 7 cm), Schichteinzug von der gewählten Wandfläche, auf die + // Wanddicke geklemmt — dieselbe Rechnung wie `windowSymbol` (2D) und `resolveFrameNormalRange` (3D). + const total = host.nHi - host.nLo; + const frameDepth = Math.min(total, t?.frameDepth && t.frameDepth > 1e-9 ? t.frameDepth : DEFAULT_FRAME_DEPTH); + const inset = Math.max(0, t?.insetFromFace ?? 0); + const outside = (t?.insetFace ?? "aussen") === "aussen"; + const front = outside ? host.nLo + inset : host.nHi - inset; + const back = outside ? front + frameDepth : front - frameDepth; + let b0 = Math.max(host.nLo, Math.min(host.nHi, Math.min(front, back))); + let b1 = Math.max(host.nLo, Math.min(host.nHi, Math.max(front, back))); + if (b1 - b0 < MIN_DIM) { + b0 = host.nLo; + b1 = host.nHi; + } + const bMid = (b0 + b1) / 2; + + // Sichtbare Rahmenbreite: höchstens ein Viertel der kleineren Öffnungsabmessung, sonst bliebe nichts offen. + const fw = Math.max(MIN_DIM, Math.min(t?.frameWidth && t.frameWidth > 1e-9 ? t.frameWidth : DEFAULT_FRAME_WIDTH, Math.min(W, H) / 4)); + const aIn0 = c.from + fw; + const aIn1 = c.to - fw; + + if (!isDoor) { + // ── Fenster: Blendrahmen (Pfosten links/rechts, Sturz, Sohlbank), Mittelpfosten, Glas je Flügel ── + const wing = opening.wingCount ?? wt?.wingCount ?? 1; + add(0, c.from, aIn0, b0, b1, 0, H); + add(0, aIn1, c.to, b0, b1, 0, H); + add(0, aIn0, aIn1, b0, b1, H - fw, H); + add(0, aIn0, aIn1, b0, b1, 0, fw); + const panes = wt ? glazingPanesOf(wt) : 2; + const gt = Math.min(GLASS_PACKAGE_THICKNESS[panes - 1], b1 - b0); + const g0 = bMid - gt / 2; + const g1 = bMid + gt / 2; + const spans = sashSpans(wt?.sashes, wing, aIn1 - aIn0); + let glassCount = 0; + spans.forEach((s, i) => { + const x0 = aIn0 + s.from; + const x1 = aIn0 + s.to; + if (s.post) { + add(0, x0, x1, b0, b1, fw, H - fw); + return; + } + // Zwischen zwei Flügeln ohne Pfosten steht ein Mittelpfosten (Breite = Rahmenbreite) auf der Grenze. + const prev = spans[i - 1]; + const next = spans[i + 1]; + const gx0 = i === 0 || prev.post ? x0 : x0 + fw / 2; + const gx1 = i === spans.length - 1 || next.post ? x1 : x1 - fw / 2; + if (next && !next.post) add(0, x1 - fw / 2, x1 + fw / 2, b0, b1, fw, H - fw); + add(2, gx0, gx1, g0, g1, fw, H - fw); + glassCount++; + }); + // Teilung nach IFC: nur die senkrechten Standardfälle sind benannt (sonst NOTDEFINED, das Modell + // kennt Sprossen und Seitenverhältnisse, die IFC nicht als Enum führt). + const kind = glassCount === 1 ? "SINGLE_PANEL" : glassCount === 2 ? "DOUBLE_PANEL_VERTICAL" : glassCount === 3 ? "TRIPLE_PANEL_VERTICAL" : "NOTDEFINED"; + return { origin, u, kind, parts }; + } + + // ── Tür ── + const kind = dt?.kind ?? (opening.doorType === "wandoeffnung" ? "wandoeffnung" : "dreh"); + const leafCount = dt?.leafCount ?? 1; + // Aufschlagrichtung wie `doorSymbol`: linke Achsnormale, `openingDir: "out"` spiegelt sie. + const swingSign = (opening.swing ?? "left") === "left" ? 1 : -1; + const dirSign = (opening.openingDir ?? "in") === "in" ? 1 : -1; + const swingDir: Vec2 = { x: n.x * swingSign * dirSign, y: n.y * swingSign * dirSign }; + // Füllungssystem der Tür: Y = Aufschlagrichtung (IFC: die Tür schlägt nach +Y auf), X = Y × Z. + const doorU: Vec2 = { x: swingDir.y, y: -swingDir.x }; + if (kind === "wandoeffnung") return { origin, u: doorU, kind: null, parts: [] }; + + // Zarge: Pfosten links/rechts über die ganze Höhe und Sturz (keine Schwelle). + add(0, c.from, aIn0, b0, b1, 0, H); + add(0, aIn1, c.to, b0, b1, 0, H); + add(0, aIn0, aIn1, b0, b1, H - fw, H); + + // Oberlicht: fester Glasstreifen über einem Kämpfer (Riegel in Rahmenbreite) innerhalb der Öffnungshöhe. + const th = dt?.transomHeight ?? 0; + const hasTransom = th > MIN_DIM && th < H - fw - 0.5; + const leafTop = hasTransom ? H - fw - th - fw : H - fw; + if (hasTransom) { + add(0, aIn0, aIn1, b0, b1, leafTop, leafTop + fw); + const gt = Math.min(GLASS_PACKAGE_THICKNESS[1], b1 - b0); + add(2, aIn0, aIn1, bMid - gt / 2, bMid + gt / 2, leafTop + fw, H - fw); + } + + // Türblatt/-blätter im lichten Mass der Zarge, mittig in der Rahmentiefe. + const lt = Math.min(DOOR_LEAF_THICK, b1 - b0); + const l0 = bMid - lt / 2; + const l1 = bMid + lt / 2; + const leafSpans: [number, number][] = + leafCount >= 2 + ? [ + [aIn0, (aIn0 + aIn1) / 2], + [(aIn0 + aIn1) / 2, aIn1], + ] + : [[aIn0, aIn1]]; + const glazed = dt?.leafStyle === "glas"; + const ratio = Math.min(0.9, Math.max(0.05, dt?.glazingRatio ?? DEFAULT_GLAZING_RATIO)); + for (const [x0, x1] of leafSpans) { + if (!glazed) { + add(1, x0, x1, l0, l1, 0, leafTop); + continue; + } + // Glastür: Glasfläche = `glazingRatio` des Blatts (gleichmässig verkleinert um die Blattmitte), das + // Blatt als umlaufender Rahmen darum; das Glas füllt die Blattdicke zu 60 % (4–24 mm, mittig). + const s = Math.sqrt(ratio); + const cx = (x0 + x1) / 2; + const cz = leafTop / 2; + const gw = (x1 - x0) * s; + const gh = leafTop * s; + const [px0, px1, pz0, pz1] = [cx - gw / 2, cx + gw / 2, cz - gh / 2, cz + gh / 2]; + add(1, x0, x1, l0, l1, 0, pz0); + add(1, x0, x1, l0, l1, pz1, leafTop); + add(1, x0, px0, l0, l1, pz0, pz1); + add(1, px1, x1, l0, l1, pz0, pz1); + const gt = Math.min(GLASS_PACKAGE_THICKNESS[1], lt * 0.6); + add(2, px0, px1, bMid - gt / 2, bMid + gt / 2, pz0, pz1); + } + + // OperationType: Blattzahl und Scharnierseite. IFC blickt von der Aufschlagseite (+Y des Füllungssystems) + // auf die Tür; "links" = Scharnier auf der +X-Seite des Systems (X = Y × Z, von +Y aus gesehen links). + const hingeAtStart = (opening.hinge ?? "start") === "start"; + const hingeAxis = hingeAtStart ? c.from : c.to; + const hingeLocalX = dotv(sub(at(hingeAxis, 0), origin), doorU); + const left = hingeLocalX > 0; + let op: string; + if (kind === "schiebe") op = leafCount >= 2 ? "DOUBLE_DOOR_SLIDING" : left ? "SLIDING_TO_LEFT" : "SLIDING_TO_RIGHT"; + else op = leafCount >= 2 ? "DOUBLE_DOOR_SINGLE_SWING" : left ? "SINGLE_SWING_LEFT" : "SINGLE_SWING_RIGHT"; + return { origin, u: doorU, kind: op, parts }; +} diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 95548559..571d366e 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1703,6 +1703,7 @@ export const de = { "exportDxf.hatches.no": "Nur Umrisse", "exportDxf.format": "Format", "exportDxf.format.dxf": "DXF (AutoCAD 2018, Text)", + "exportDxf.format.dxfbin": "DXF binär (AutoCAD 2018, kompakt)", "exportDxf.format.dwg": "DWG (AutoCAD 2018)", "exportDxf.failed": "Export fehlgeschlagen", "exportDxf.unitsNote": diff --git a/src/i18n/en.ts b/src/i18n/en.ts index e4b7c3d6..b3f0a862 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1691,6 +1691,7 @@ export const en: Record = { "exportDxf.hatches.no": "Outlines only", "exportDxf.format": "Format", "exportDxf.format.dxf": "DXF (AutoCAD 2018, text)", + "exportDxf.format.dxfbin": "DXF binary (AutoCAD 2018, compact)", "exportDxf.format.dwg": "DWG (AutoCAD 2018)", "exportDxf.failed": "Export failed", "exportDxf.unitsNote": diff --git a/src/io/ifcImport.test.ts b/src/io/ifcImport.test.ts index 0e8a635b..81d9c501 100644 --- a/src/io/ifcImport.test.ts +++ b/src/io/ifcImport.test.ts @@ -90,7 +90,7 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => { expect(p, wall.id).toBeDefined(); const wallLine = [...lines.values()].find((l) => l.includes(`=IFCWALL('${p.globalId}'`))!; const shape = lines.get(/,(#\d+),\$,\$\);$/.exec(wallLine)![1])!; - const rep = lines.get(/\(\(?(#\d+)\)\);$/.exec(shape)![1])!; + const rep = lines.get(/(#\d+)\)\);$/.exec(shape)![1])!; // letzte Darstellung = Body (davor ggf. Axis) const isSwept = rep.includes("'SweptSolid'"); if (isSwept) swept++; const expected = cut.get(wall.id)!; diff --git a/src/ui/ExportDxfDialog.tsx b/src/ui/ExportDxfDialog.tsx index 4f43af65..3d7e5739 100644 --- a/src/ui/ExportDxfDialog.tsx +++ b/src/ui/ExportDxfDialog.tsx @@ -13,7 +13,7 @@ import type { CadExportFormat } from "../export/exportDxf"; /** Entscheidung, die der Dialog beim Bestätigen liefert. */ export interface ExportDxfDecision { - /** Dateiformat: DXF (R2018 ASCII) oder DWG (R2018). */ + /** Dateiformat: DXF (R2018 ASCII), Binär-DXF (R2018) oder DWG (R2018). */ format: CadExportFormat; includeHatches: boolean; /** „nur Auswahl" statt des ganzen Plans (nur relevant, wenn `selectionCount > 0`). */ @@ -78,10 +78,11 @@ export function ExportDxfDialog({
{t("exportDxf.format")}
setFormat(v === "dwg" ? "dwg" : "dxf")} + onChange={(v) => setFormat(v === "dwg" ? "dwg" : v === "dxfbin" ? "dxfbin" : "dxf")} title={t("exportDxf.format")} options={[ { value: "dxf", label: t("exportDxf.format.dxf") }, + { value: "dxfbin", label: t("exportDxf.format.dxfbin") }, { value: "dwg", label: t("exportDxf.format.dwg") }, ]} />