diff --git a/TODO.md b/TODO.md index 57348e8d..bdd38fc7 100644 --- a/TODO.md +++ b/TODO.md @@ -261,7 +261,21 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern ([B5]/[C11]: IFC2x3, Basismengen, Öffnungen, Zonen, Klassifikation, glTF …). Behalten ist die `fileio`-Fassung; die Kern-Duplikate `export_ifc.rs`, `export_mesh.rs`, `geo_rebase.rs`, `web/export_ifc.rs`, `doc_export_ifc` und die Abfragen `objFile`/`stlFile` sind gelöscht. Die Exporte holen ihre 3D-Teile über `export/model3dParts.ts` aus dem - Dokument (`queries.rs`). Offen: `fileio`-Schreiber direkt aus dem Dokument füttern statt über den TS-Sammler. + Dokument (`queries.rs`). ~~Offen: `fileio`-Schreiber direkt aus dem Dokument füttern statt über den TS-Sammler.~~ + **Export-Sammler im Kern (29.10.):** Der Kern erzeugt den flachen Puffer der `fileio`-Schreiber selbst (Abfragen + `ifcExportData`/`meshExportData` über `queryBin`, Byte-Hülle `export_flat.rs`); TS gibt nur Optionen + Zeitstempel + weiter und reicht die Bytes an `fileio` (zwei WASM-Module). Neu: `ifc_data.rs`, `ifc_quantities.rs`, + `ifc_stairs.rs`, `mesh_data.rs`, `export_flat.rs` (Puffer, `orient_outward`, Volumen), `geo_rebase.rs` + (LV95-Verschiebung, `lv95_to_wgs84`). Gelöscht: TS-Sammler in `exportIfc.ts`/`exportMesh.ts`, `ifcQuantities`, + `ifcStairs`, `ifcClassification`, `ifcOpenings`, `meshOrient`, `model3dParts`, `plan/wallMeshCut` samt Bindungen. + Gleichheit: 1396 Ausgaben (alle Exporte der Test-Suite aufgezeichnet und mit Varianten wiederholt, Beispielprojekt + IFC4/IFC2x3 × eBKP-H × Ebenen, mit Georeferenz, 80 Zufallsprojekte mit allen Bauteilarten, bigSample(3)) vorher/ + nachher zeichengleich (mit festem Zeitstempel), auch die Fehlermeldungen; `validate-ifc.py` über 110 Dateien + 0 Befunde, glTF-Validator über 390 GLB/glTF 0 Fehler (nach [C11]-Korrektur der leeren Szene). Messung (Node, + Linux-Container, `--no-opt`-WASM, bigSample(20)): IFC 82,5 s → 2,4 s, GLB 212 s → 1,9 s; Beispielprojekt IFC + 11 → 4 ms, GLB 15 → 2,5 ms (vorher je Bauteil ein eigenes Kern-Dokument aus dem ganzen Projekt-JSON). Nicht in + der Tauri-App geprüft (e2e im Browser: IFC-Export grün). Bleibt: DXF-Sammler (`exportDxf.ts`), STEP (truck) und + die Modell-Verschiebung `translateProject` in TS (Befehl „Neuer Bezugspunkt“, DXF). Nächste: Export (Schedule/CSV, STL/OBJ, STEP), Plan/Schnitt/Ansicht-Sammler (generatePlan, toSection, toElevation) — hängt an Plan-Puffer v2. Grundriss (28.10.): Decken, Dächer, Räume, Wände+Öffnungen, Treppen, Stützen, Extrusionen, Kontext und Schnittlinien kommen über `planDomains` aus dem Dokument ([K3d]); übrig in `generatePlan`: 2D-Zeichnungen, Schatten/Baurecht, Abzugskörper. @@ -947,6 +961,11 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module Netz-Wände/Dächer als Brep sind grösser als IfcTriangulatedFaceSet (ein Punkt je Ecke, drei Entitäten je Dreieck). · M - Geprüft nur im Linux-Container (vitest + ifcopenshell 0.9: 0 Befunde, Volumen), nicht in Solibri/BIMcollab und nicht in der Tauri-App. + - ✅ Sammler nach Rust (29.10., [K4]): Mengen, Treppen-Teile, Füllungs-Parameter, Klassifikation/Zonen, + Geschoss-Kennwerte und Georeferenz rechnet der Kern (`core/src/ifc_data.rs`, `ifc_quantities.rs`, + `ifc_stairs.rs`, `geo_rebase.rs`) direkt aus dem Dokument; `exportIfc.ts` ist Fassade (Optionen, Zeitstempel, + Bytes an `fileio`). Ausgabe zeichengleich (s. [K4] S2). Dabei gefunden und behoben: Innenhöfe der Dächer + (`Roof.holes`) wanderten bei Georeferenz nicht mit (auch `translateProject` in TS). - ◐ **[BCF] BCF 2.1/3.0 (BIM Collaboration Format).** (28.10.) Koordinations-Themen mit Solibri, BIMcollab, Revit, ArchiCAD austauschen. Rust `src-tauri/fileio/src/bcf.rs` (+ `bcf_read`/`bcf_write` im pkgFileIo, JSON an der Grenze, Snapshots Base64): .bcfzip lesen/schreiben (Themen mit Typ/Status/Priorität/Zuständig/ @@ -1197,6 +1216,9 @@ Code-Übernahme Lizenz der Abhängigkeiten prüfen, Pflicht [51]. truck-Extrusionen (nur Prisma-Näherung) nicht wie im 3D; Dreieckszahl nicht gegen die GPU-Puffer von render3d gemessen (Wand-Löcher und Decken aus denselben Ableitungen, Dächer/Stützen/Treppen/Öffnungen identisch); nicht in Blender/Twinmotion/Enscape geöffnet, nur Validator; nicht in der Tauri-App getestet. · S + **Sammler nach Rust (29.10., [K4]):** Szene (Knoten, Teil-Netze je Material, Materialtabelle, `orientOutward`) + baut der Kern aus dem Dokument (`core/src/mesh_data.rs`); `exportMesh.ts` ist Fassade. Ausgabe zeichengleich + (s. [K4] S2); leere Szene jetzt ohne leere `nodes`-Liste (Validator EMPTY_ENTITY bei leerem Projekt). - ◐ **[C12] Allgemeiner Mesh-Import als Kontext-Meshes** (Gegenstück zu [C11], 28.10.): Nachbargebäude, Möbel und Umgebungsmodelle aus SketchUp/Blender/Rhino. Eigener Code in `src-tauri/fileio/src/mesh_import.rs` (OBJ + MTL, STL, PLY mit Flächen) und `mesh_import_gltf.rs` (glTF 2.0/GLB mit kleinem JSON-Leser, keine neue Abhängigkeit; earcutr diff --git a/src-tauri/core/src/export_flat.rs b/src-tauri/core/src/export_flat.rs new file mode 100644 index 00000000..e3525359 --- /dev/null +++ b/src-tauri/core/src/export_flat.rs @@ -0,0 +1,264 @@ +//! Gemeinsames für die Export-Sammler im Kern ([K4], [B5], [C11]): der flache Puffer, den die +//! Schreiber in `src-tauri/fileio` lesen (Zahlen + Zeichenkettenliste, Kodierung dort in +//! `ifc_export.rs`/`mesh_export.rs`), die Byte-Hülle für die Übergabe an TS und Netz-Helfer +//! (Wicklung nach aussen, Volumen). Port von `src/export/meshOrient.ts` und den Puffer-Klassen aus +//! `exportIfc.ts`/`exportMesh.ts`; Rechenreihenfolge wie dort, damit die Dateien zeichengleich bleiben. +//! +//! Byte-Hülle (little endian, alles f64 bis auf die Zeichenketten): +//! `[MAGIC, nZahlen, nBytes, Zahlen…, UTF-8 der Zeichenketten durch \0 getrennt]`. Fehler kommen als +//! Fehlerpuffer des Plan-Puffers (`plan_buf::encode_error`, `[ERR_MAGIC, n, UTF-16…]`). + +use std::collections::HashMap; + +/// Kennung der Byte-Hülle ("DXEF"). +pub const MAGIC: f64 = 1_146_635_590.0; + +/// Zahlenpuffer + Zeichenkettenliste (`FlatIfc`/`encodeScene` in TS). +#[derive(Debug, Default, Clone, PartialEq)] +pub struct Flat { + pub nums: Vec, + pub strings: Vec, +} + +impl Flat { + pub fn new(version: f64) -> Self { + Flat { nums: vec![version], strings: Vec::new() } + } + + pub fn num(&mut self, v: f64) -> &mut Self { + self.nums.push(v); + self + } + + pub fn nums(&mut self, v: &[f64]) -> &mut Self { + self.nums.extend_from_slice(v); + self + } + + /// Zeichenkette anhängen (ohne `\0`, das trennt die Liste) und ihren Index liefern. + pub fn str(&mut self, s: &str) -> f64 { + self.strings.push(s.replace('\0', "")); + (self.strings.len() - 1) as f64 + } + + /// Byte-Hülle für TS (s. Modulkopf). + pub fn to_bytes(&self) -> Vec { + let text = self.strings.join("\0"); + let mut out = Vec::with_capacity(24 + self.nums.len() * 8 + text.len()); + out.extend_from_slice(&MAGIC.to_le_bytes()); + out.extend_from_slice(&(self.nums.len() as f64).to_le_bytes()); + out.extend_from_slice(&(text.len() as f64).to_le_bytes()); + for v in &self.nums { + out.extend_from_slice(&v.to_le_bytes()); + } + out.extend_from_slice(text.as_bytes()); + out + } +} + +/// Liest die Byte-Hülle zurück (Tests). +pub fn from_bytes(b: &[u8]) -> Option<(Vec, String)> { + let f = |i: usize| -> Option { Some(f64::from_le_bytes(b.get(i * 8..i * 8 + 8)?.try_into().ok()?)) }; + if f(0)? != MAGIC { + return None; + } + let (n, len) = (f(1)? as usize, f(2)? as usize); + let nums = (0..n).map(|i| f(3 + i)).collect::>>()?; + let at = 24 + n * 8; + let text = String::from_utf8(b.get(at..at + len)?.to_vec()).ok()?; + Some((nums, text)) +} + +/// Zahl als Schlüssel wie `String(v)` in JS: −0 = 0, alle NaN gleich. +pub fn js_key(v: f64) -> u64 { + if v.is_nan() { + f64::NAN.to_bits() + } else { + (v + 0.0).to_bits() + } +} + +/// Volumen eines geschlossenen Dreiecks-Netzes (Betrag der Summe der Tetraeder zum Ursprung, `meshVolume`). +pub fn mesh_volume(positions: &[f64], indices: &[u32]) -> f64 { + let p = |i: usize| positions.get(i).copied().unwrap_or(f64::NAN); + let mut v = 0.0; + let mut i = 0; + while i + 2 < indices.len() { + let a = indices[i] as usize * 3; + let b = indices[i + 1] as usize * 3; + let c = indices[i + 2] as usize * 3; + v += p(a) * (p(b + 1) * p(c + 2) - p(b + 2) * p(c + 1)) - p(a + 1) * (p(b) * p(c + 2) - p(b + 2) * p(c)) + p(a + 2) * (p(b) * p(c + 1) - p(b + 1) * p(c)); + i += 3; + } + v.abs() / 6.0 +} + +/// Richtet ein Dreiecks-Netz (Weltkoordinaten) so aus, dass die Flächennormalen nach AUSSEN zeigen +/// (`orientOutward`): Dreiecke werden über gemeinsame Kanten (Eckpunkte auf 0,01 mm verschweisst) +/// zu Zusammenhangs-Komponenten verbunden, jede Komponente zuerst in sich widerspruchsfrei gewickelt +/// (Nachbarn durchlaufen eine gemeinsame Kante gegenläufig) und dann nach dem Vorzeichen ihres +/// Volumens gedreht. Kanten mit mehr als zwei Dreiecken (Verschneidungen) verbinden nicht. +/// Indizes ausserhalb des Netzes lassen das Netz unverändert (kein Panic). +pub fn orient_outward(pos: &[f64], idx: &[u32]) -> Vec { + let n_tri = idx.len() / 3; + let n_vert = pos.len() / 3; + if idx[..n_tri * 3].iter().any(|&i| i as usize >= n_vert) { + return idx.to_vec(); + } + let q = |v: f64| js_key(crate::jsnum::round(v * 1e5)); + let mut weld: HashMap<(u64, u64, u64), usize> = HashMap::new(); + let mut canon = vec![0usize; n_vert]; + for (i, c) in canon.iter_mut().enumerate() { + let key = (q(pos[3 * i]), q(pos[3 * i + 1]), q(pos[3 * i + 2])); + let next = weld.len(); + *c = *weld.entry(key).or_insert(next); + } + let n = weld.len() + 1; + // Kante (min, max) → Einträge (Dreieck · 2 + vorwärts?), in der Reihenfolge des ersten Auftretens. + let mut edge_at: HashMap = HashMap::new(); + let mut edges: Vec> = Vec::new(); + let corner = |t: usize, k: usize| canon[idx[3 * t + k] as usize]; + for t in 0..n_tri { + for k in 0..3 { + let a = corner(t, k); + let b = corner(t, (k + 1) % 3); + if a == b { + continue; + } + let key = a.min(b) * n + a.max(b); + let entry = t * 2 + usize::from(a < b); + match edge_at.get(&key) { + Some(&e) => edges[e].push(entry), + None => { + edge_at.insert(key, edges.len()); + edges.push(vec![entry]); + } + } + } + } + // Nachbarschaft über Kanten mit genau zwei Dreiecken: Wicklungs-Parität (1 = gegenläufig nötig). + let mut adj: Vec> = vec![Vec::new(); n_tri]; + for list in &edges { + if list.len() != 2 { + continue; + } + let (e1, e2) = (list[0], list[1]); + let (t1, t2) = (e1 >> 1, e2 >> 1); + if t1 == t2 { + continue; + } + let parity = usize::from((e1 & 1) == (e2 & 1)); + adj[t1].push(t2 * 2 + parity); + adj[t2].push(t1 * 2 + parity); + } + let mut flip: Vec = vec![-1; n_tri]; + let mut out = idx.to_vec(); + for s in 0..n_tri { + if flip[s] >= 0 { + continue; + } + let mut comp = vec![s]; + flip[s] = 0; + let mut h = 0; + while h < comp.len() { + let t = comp[h]; + for &e in &adj[t] { + let u = e >> 1; + if flip[u] < 0 { + flip[u] = flip[t] ^ (e & 1) as i8; + comp.push(u); + } + } + h += 1; + } + let mut vol = 0.0; + for &t in &comp { + let (a, b, c) = if flip[t] != 0 { (idx[3 * t], idx[3 * t + 2], idx[3 * t + 1]) } else { (idx[3 * t], idx[3 * t + 1], idx[3 * t + 2]) }; + let (a, b, c) = (a as usize * 3, b as usize * 3, c as usize * 3); + vol += pos[a] * (pos[b + 1] * pos[c + 2] - pos[b + 2] * pos[c + 1]) - pos[a + 1] * (pos[b] * pos[c + 2] - pos[b + 2] * pos[c]) + pos[a + 2] * (pos[b] * pos[c + 1] - pos[b + 1] * pos[c]); + } + let turn = i8::from(vol < 0.0); + for &t in &comp { + if flip[t] ^ turn != 0 { + out[3 * t + 1] = idx[3 * t + 2]; + out[3 * t + 2] = idx[3 * t + 1]; + } + } + } + out +} + +/// `String.prototype.trim` (JS-Leerraum: Zs, Tab, VT, FF, BOM und Zeilenenden; anders als Rust ohne U+0085). +pub fn js_trim(s: &str) -> &str { + let ws = |c: char| (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}'; + s.trim_matches(ws) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Würfel mit gemischter Wicklung (je zweites Dreieck gedreht). + fn cube(mixed: bool) -> (Vec, Vec) { + let pos = vec![0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0., 0., 0., 1., 1., 0., 1., 1., 1., 1., 0., 1., 1.]; + let quads = [[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]; + let mut idx = Vec::new(); + for (k, q) in quads.iter().enumerate() { + idx.extend([q[0], q[1], q[2]]); + if mixed && k % 2 == 1 { + idx.extend([q[0], q[3], q[2]]); + } else { + idx.extend([q[0], q[2], q[3]]); + } + } + (pos, idx) + } + + fn signed_volume(pos: &[f64], idx: &[u32]) -> f64 { + let mut v = 0.0; + for t in idx.chunks_exact(3) { + let (a, b, c) = (t[0] as usize * 3, t[1] as usize * 3, t[2] as usize * 3); + v += pos[a] * (pos[b + 1] * pos[c + 2] - pos[b + 2] * pos[c + 1]) - pos[a + 1] * (pos[b] * pos[c + 2] - pos[b + 2] * pos[c]) + pos[a + 2] * (pos[b] * pos[c + 1] - pos[b + 1] * pos[c]); + } + v / 6.0 + } + + #[test] + fn wuerfel_wird_nach_aussen_gewickelt() { + let (pos, idx) = cube(true); + let out = orient_outward(&pos, &idx); + assert!((signed_volume(&pos, &out) - 1.0).abs() < 1e-12); + assert!((mesh_volume(&pos, &out) - 1.0).abs() < 1e-12); + // Ganz umgedreht → wieder aussen. + let rev: Vec = idx.chunks_exact(3).flat_map(|t| [t[0], t[2], t[1]]).collect(); + assert!((signed_volume(&pos, &orient_outward(&pos, &rev)) - 1.0).abs() < 1e-12); + } + + #[test] + fn unsinn_ohne_panik() { + assert_eq!(orient_outward(&[0.0; 9], &[0, 1, 7]), vec![0, 1, 7]); + assert!(orient_outward(&[], &[]).is_empty()); + assert_eq!(orient_outward(&[f64::NAN; 9], &[0, 1, 2]), vec![0, 1, 2]); + assert!(mesh_volume(&[0.0; 3], &[0, 5, 9]).is_nan()); + } + + #[test] + fn huelle_hin_und_zurueck() { + let mut f = Flat::new(4.0); + let a = f.str("Wand\0«ä»"); + f.num(a).nums(&[1.5, f64::NAN]); + let i = f.str("x"); + f.num(i); + let (nums, text) = from_bytes(&f.to_bytes()).unwrap(); + assert_eq!(nums.len(), 5); + assert_eq!(nums[1], 0.0); + assert!(nums[3].is_nan()); + assert_eq!(text, "Wand«ä»\0x"); + } + + #[test] + fn trim_wie_js() { + assert_eq!(js_trim("\u{feff} 20\t\n"), "20"); + assert_eq!(js_trim("\u{85}20"), "\u{85}20"); + } +} diff --git a/src-tauri/core/src/geo_rebase.rs b/src-tauri/core/src/geo_rebase.rs new file mode 100644 index 00000000..cf3434d3 --- /dev/null +++ b/src-tauri/core/src/geo_rebase.rs @@ -0,0 +1,193 @@ +//! Ursprungs-Verschiebung des ganzen Projekts für georeferenzierte Modell-Exporte ([K4], Gegenstück +//! zu `projectToWorldCoords` in `src/model/geoRebase.ts`, das für DXF und den Befehl „Neuer +//! Bezugspunkt" in TS bleibt): reine, verlustfreie Translation aller Modell-Koordinaten um einen +//! festen Vektor. `geoAnchor` wandert mit, damit der LV95-Bezug exakt erhalten bleibt. Nur +//! Translation — keine Rotation (Achsen- und Winkelfelder blieben sonst falsch). Richtungsvektoren +//! (z. B. `Stair.dir`) bleiben unangetastet. Dazu LV95 → WGS84 (`lv95ToWgs84` aus `src/io/lv95.ts`). + +use crate::model::*; + +fn shift(p: Vec2, dx: f64, dy: f64) -> Vec2 { + Vec2 { x: p.x + dx, y: p.y + dy } +} + +fn shift_all(pts: &mut [Vec2], dx: f64, dy: f64) { + for p in pts { + *p = shift(*p, dx, dy); + } +} + +fn shift_geom(g: &mut Drawing2DGeom, dx: f64, dy: f64) { + use Drawing2DGeom::*; + match g { + Line { a, b } | Xline { a, b } | Ray { a, b } => { + *a = shift(*a, dx, dy); + *b = shift(*b, dx, dy); + } + Polyline { pts, .. } | Bezier { pts } | Spline { pts, .. } | Dimension { pts, .. } => shift_all(pts, dx, dy), + Rect { min, max } | Image { min, max, .. } => { + *min = shift(*min, dx, dy); + *max = shift(*max, dx, dy); + } + Circle { center, .. } | Arc { center, .. } | Ellipse { center, .. } => *center = shift(*center, dx, dy), + Kote { at, .. } | Detailref { at, .. } | Scalebar { at, .. } | Pointmarker { at } | Block { at, .. } => *at = shift(*at, dx, dy), + Text { at, leader_target, leader_bend_points, path_pts, .. } => { + *at = shift(*at, dx, dy); + if let Some(t) = leader_target { + *t = shift(*t, dx, dy); + } + if let Some(v) = leader_bend_points { + shift_all(v, dx, dy); + } + if let Some(v) = path_pts { + shift_all(v, dx, dy); + } + } + } +} + +fn shift_context(o: &mut ContextObject, dx: f64, dy: f64) { + match o { + ContextObject::ContourSet(s) => { + for c in &mut s.contours { + shift_all(&mut c.pts, dx, dy); + if let Some(cv) = &mut c.curve { + cv.cx += dx; + cv.cy += dy; + } + } + } + ContextObject::Image(i) => { + i.min = shift(i.min, dx, dy); + i.max = shift(i.max, dx, dy); + } + ContextObject::ImportedMesh(m) => shift_positions(&mut m.positions, dx, dy), + ContextObject::TerrainMesh(m) => shift_positions(&mut m.positions, dx, dy), + } +} + +/// Nur x/y (Grundriss) verschieben, die Höhe bleibt. +fn shift_positions(pos: &mut [f64], dx: f64, dy: f64) { + for c in pos.chunks_exact_mut(3) { + c[0] += dx; + c[1] += dy; + } +} + +/// Verschiebt sämtliche Modell-Koordinaten (`translateProject`), auch die Innenhöfe der Dächer. +pub fn translate_project(p: &Project, dx: f64, dy: f64) -> Project { + if dx == 0.0 && dy == 0.0 { + return p.clone(); + } + let mut out = p.clone(); + for w in &mut out.walls { + w.start = shift(w.start, dx, dy); + w.end = shift(w.end, dx, dy); + } + for c in out.ceilings.iter_mut().flatten() { + shift_all(&mut c.outline, dx, dy); + for h in c.openings.iter_mut().flatten() { + shift_all(h, dx, dy); + } + } + for r in out.roofs.iter_mut().flatten() { + shift_all(&mut r.outline, dx, dy); + for h in r.holes.iter_mut().flatten() { + shift_all(h, dx, dy); + } + } + for s in out.stairs.iter_mut().flatten() { + s.start = shift(s.start, dx, dy); + s.center = s.center.map(|c| shift(c, dx, dy)); + } + for r in out.rooms.iter_mut().flatten() { + shift_all(&mut r.boundary, dx, dy); + r.stamp_anchor = r.stamp_anchor.map(|a| shift(a, dx, dy)); + } + for c in out.columns.iter_mut().flatten() { + c.position = shift(c.position, dx, dy); + } + for s in out.extruded_solids.iter_mut().flatten() { + shift_all(&mut s.points, dx, dy); + if let Some(c) = &mut s.circle { + c.center = shift(c.center, dx, dy); + } + } + for d in &mut out.drawings2d { + shift_geom(&mut d.geom, dx, dy); + } + for o in out.context.iter_mut().flatten() { + shift_context(o, dx, dy); + } + for l in &mut out.drawing_levels { + if let Some(pts) = &mut l.line_points { + pts[0] = shift(pts[0], dx, dy); + pts[1] = shift(pts[1], dx, dy); + } + } + if let Some(a) = &mut out.geo_anchor { + a.model = shift(a.model, dx, dy); + } + out +} + +/// LV95-Ursprung: die reale Landeskoordinate, die auf den Modell-Nullpunkt abgebildet wird. +pub fn project_geo_origin(p: &Project) -> Option<(f64, f64)> { + let a = p.geo_anchor.as_ref()?; + Some((a.lv95.e - a.model.x, a.lv95.n - a.model.y)) +} + +/// Kopie mit Geometrie in realen Weltkoordinaten (LV95) für Modell-Exporte; ohne Bezug unverändert. +pub fn project_to_world_coords(p: &Project) -> Project { + match project_geo_origin(p) { + Some((e, n)) => translate_project(p, e, n), + None => p.clone(), + } +} + +/// LV95 → WGS84 (swisstopo-Näherungsformeln; Rechenreihenfolge wie `lv95ToWgs84` in TS): +/// `(Breite, Länge)` in Dezimalgrad. +pub fn lv95_to_wgs84(e: f64, n: f64) -> (f64, f64) { + let y = (e - 2600000.0) / 1000000.0; + let x = (n - 1200000.0) / 1000000.0; + let y2 = y * y; + let x2 = x * x; + let lam = 2.6779094 + 4.728982 * y + 0.791484 * y * x + 0.1306 * y * x2 - 0.0436 * y * y2; + let phi = 16.9023892 + 3.238272 * x - 0.270978 * y2 - 0.002528 * x2 - 0.0447 * y2 * x - 0.014 * x * x2; + ((phi * 100.0) / 36.0, (lam * 100.0) / 36.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verschiebt_alles_und_haelt_den_anker() { + let mut p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap(); + p.geo_anchor = Some(ProjectGeoAnchor { lv95: ProjectGeoAnchorLv95 { e: 2_600_000.0, n: 1_200_000.0, ..Default::default() }, model: Vec2 { x: 1.0, y: 2.0 }, ..Default::default() }); + let w = project_to_world_coords(&p); + assert_eq!(w.walls[0].start.x, p.walls[0].start.x + 2_599_999.0); + assert_eq!(w.walls[0].start.y, p.walls[0].start.y + 1_199_998.0); + // Der Anker wandert mit: das verschobene Modell liegt bereits in Landeskoordinaten (Ursprung 0, 0). + assert_eq!(project_geo_origin(&w), Some((0.0, 0.0))); + assert_eq!(project_to_world_coords(&Project { geo_anchor: None, ..p.clone() }), Project { geo_anchor: None, ..p }); + } + + #[test] + fn dach_innenhoefe_wandern_mit() { + let mut p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap(); + let roofs = p.roofs.as_mut().unwrap(); + roofs[0].holes = Some(vec![vec![Vec2 { x: 1.0, y: 1.0 }, Vec2 { x: 2.0, y: 1.0 }, Vec2 { x: 2.0, y: 2.0 }]]); + let t = translate_project(&p, 10.0, -5.0); + let r = &t.roofs.as_ref().unwrap()[0]; + assert_eq!(r.outline[0], Vec2 { x: p.roofs.as_ref().unwrap()[0].outline[0].x + 10.0, y: p.roofs.as_ref().unwrap()[0].outline[0].y - 5.0 }); + assert_eq!(r.holes.as_ref().unwrap()[0][2], Vec2 { x: 12.0, y: -3.0 }); + } + + #[test] + fn lv95_bern() { + // Bezugspunkt Bern (alte Sternwarte): 46°57'08.66" N, 7°26'22.50" E. + let (lat, lon) = lv95_to_wgs84(2600000.0, 1200000.0); + assert!((lat - 46.951082).abs() < 1e-5 && (lon - 7.438637).abs() < 1e-5, "{lat} {lon}"); + } +} diff --git a/src-tauri/core/src/ifc_data.rs b/src-tauri/core/src/ifc_data.rs new file mode 100644 index 00000000..6e3ffce7 --- /dev/null +++ b/src-tauri/core/src/ifc_data.rs @@ -0,0 +1,1141 @@ +//! IFC-Export: Sammler im Kern ([K4] S2, [B5]; vorher `src/export/exportIfc.ts`, `ifcOpenings.ts`, +//! `ifcClassification.ts`). Liest das Projekt-Dokument und erzeugt den flachen Puffer, den der +//! Schreiber in `src-tauri/fileio/src/ifc_export.rs` zur STEP-Datei macht (Kodierung dort im Kopf, +//! FLAT_VERSION 4). TS gibt nur noch Optionen (Schema, Klassifikation) und den Zeitstempel weiter und +//! reicht die Bytes an `fileio` (zwei WASM-Module, keine gemischten Crates). +//! +//! Abbildung (Einzelheiten im Kopf von `ifc_export.rs` und in `TODO.md` [B5]): +//! • Geschosse: je "floor"-Ebene ein IfcBuildingStorey; Bauteile mit verwaister Geschoss-id hängen +//! am Gebäude (Struktur −1, Basis 0). +//! • Wand: Schicht-Bänder wie im 3D (`emit_walls`). Extrusion je Band + IfcOpeningElement, wenn das +//! exakt dasselbe ergibt wie das 3D (`bands_match_openings`), sonst öffnungsgenaues Netz +//! (`wall_cut_mesh`, Achsentausch mit Wicklungsumkehr, Closed nach `is_watertight`). +//! • Decke, Öffnung (Füllungs-Parameter für `ifc_openings.rs`), Treppe (`ifc_stairs.rs`), +//! Extrusion, Raum (SIA 416), Zonen, Geschoss-Kennwerte, Dach (Schicht-Netze wie im 3D), Stütze. +//! • Basismengen (`ifc_quantities.rs`), Psets nur mit Modellwerten. +//! • Klassifikation (Option): eBKP-H-Hauptgruppen je Bauteilart (Quelle CRB, SN 506 511:2020; +//! Wand/Decke/Stütze/Treppe = C, Dach = F, Fenster = E, Tür und Raum ohne — nicht geraten) und/oder +//! die Ebene des Modells als System „Dossier-Ebenen" (Code = `categoryCode`, Name = Ebenenname). +//! Das Modell führt KEINEN eBKP-H-Code; `categoryCode` ist die Grafik-Ebene. +//! Georeferenz: mit `geoAnchor` liegt die ganze Geometrie in LV95 (`geo_rebase`). +//! Zahlsemantik und Reihenfolge wie die frühere TS-Fassung: die Dateien bleiben zeichengleich. + +use crate::export_flat::{js_trim, Flat}; +use crate::geo_rebase::{lv95_to_wgs84, project_to_world_coords}; +use crate::ifc_quantities::{self as qty, Cutout, Qty, QtyKind}; +use crate::ifc_stairs::{stair_parts, FlightBody, StairParts}; +use crate::jsmath::hypot2; +use crate::jsnum::{max, min}; +use crate::model::*; +use crate::model3d::{self, RWall}; +use crate::wall_mesh_cut::{is_watertight, wall_cut_mesh_checked, CutWall}; +use std::collections::HashMap; + +const FLAT_VERSION: f64 = 4.0; +const REC_WALL_SOLIDS: f64 = 1.0; +const REC_WALL_MESH: f64 = 2.0; +const REC_CEILING: f64 = 3.0; +const REC_OPENING: f64 = 4.0; +const REC_STAIR: f64 = 5.0; +const REC_EXTRUSION: f64 = 6.0; +const REC_SPACE: f64 = 7.0; +const REC_END_SPACES: f64 = 8.0; +const REC_ROOF: f64 = 9.0; +const REC_COLUMN: f64 = 10.0; +const REC_END_COLUMNS: f64 = 11.0; +const REC_CLASSIFICATION: f64 = 12.0; +const REC_ZONE: f64 = 13.0; +const REC_ATTACH: f64 = 14.0; + +/// Toleranz des Kerns (`wall_bands.rs::EPS`) für „Öffnung trifft Band". +const BAND_EPS: f64 = 1e-4; +/// Wie weit der Öffnungskörper beidseits über die Wandflächen vorsteht (keine koplanaren Booleans). +const OPENING_OVERSHOOT: f64 = 0.02; + +/// Optionen des IFC-Exports. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct IfcOptions { + /// IFC2x3 statt IFC4. + pub ifc2x3: bool, + /// eBKP-H-Hauptgruppen je Bauteilart. + pub ebkph: bool, + /// `categoryCode` als System „Dossier-Ebenen". + pub layer_codes: bool, + /// Zeitstempel (Sekunden seit 1970) und dieselbe Zeit als ISO-Text ohne Sekundenbruchteil. + pub now: f64, + pub iso: String, +} + +// ── Puffer-Bausteine (Reihenfolge der Aufrufe = Reihenfolge der Zeichenketten) ───────────────── + +/// Pset-Eigenschaft (0 IfcIdentifier, 1 IfcBoolean, 2 IfcPositiveRatioMeasure, 3–5 Mengen). +enum Prop { + Ident(&'static str, String), + Bool(&'static str, bool), + Ratio(&'static str, f64), + Qty(&'static str, QtyKind, f64), +} + +struct Pset { + name: &'static str, + props: Vec, +} + +struct TypeRef<'a> { + kind: f64, + id: &'a str, + name: &'a str, + predefined: &'a str, + layers: Vec<(&'a str, &'a str, f64)>, +} + +/// Typ (id, Name, Schichten: Bauteil-id, Bauteilname, Dicke) als Datensatz-Verweis. +type TypeData = (String, String, Vec<(String, String, f64)>); + +fn type_ref<'a>(t: &'a TypeData, kind: f64, predefined: &'a str) -> TypeRef<'a> { + TypeRef { kind, id: &t.0, name: &t.1, predefined, layers: t.2.iter().map(|(a, b, c)| (a.as_str(), b.as_str(), *c)).collect() } +} + +fn ident(name: &'static str, v: &str) -> Prop { + Prop::Ident(name, v.to_string()) +} + +/// Basismengen als Pset `Qto_…` (nur wenn Mengen vorliegen). +fn qto(name: &'static str, quantities: Vec) -> Vec { + if quantities.is_empty() { + return vec![]; + } + vec![Pset { name, props: quantities.into_iter().map(|q| Prop::Qty(q.name, q.kind, q.value)).collect() }] +} + +fn w_pts(f: &mut Flat, pts: &[Vec2]) { + f.num(pts.len() as f64); + for p in pts { + f.nums(&[p.x, p.y]); + } +} + +fn w_mesh(f: &mut Flat, positions: &[f64], indices: &[u32], closed: bool) { + f.num((positions.len() / 3) as f64).nums(positions); + f.num((indices.len() / 3) as f64); + for &i in indices { + f.num(i as f64); + } + f.num(if closed { 1.0 } else { 0.0 }); +} + +fn w_type(f: &mut Flat, t: Option<&TypeRef>) { + let Some(t) = t else { + f.num(0.0); + return; + }; + let (id, name, pre) = (f.str(t.id), f.str(t.name), f.str(t.predefined)); + f.nums(&[1.0, t.kind, id, name, pre, t.layers.len() as f64]); + for &(cid, cname, thickness) in &t.layers { + let (a, b) = (f.str(cid), f.str(cname)); + f.nums(&[a, b, thickness]); + } +} + +fn w_psets(f: &mut Flat, list: &[Pset]) { + f.num(list.len() as f64); + for ps in list { + let n = f.str(ps.name); + f.nums(&[n, ps.props.len() as f64]); + for p in &ps.props { + match p { + Prop::Ident(name, v) => { + let (a, b) = (f.str(name), f.str(v)); + f.nums(&[a, 0.0, b]); + } + Prop::Bool(name, v) => { + let a = f.str(name); + f.nums(&[a, 1.0, if *v { 1.0 } else { 0.0 }]); + } + Prop::Ratio(name, v) => { + let a = f.str(name); + f.nums(&[a, 2.0, *v]); + } + Prop::Qty(name, kind, v) => { + let a = f.str(name); + let code = match kind { + QtyKind::Length => 3.0, + QtyKind::Area => 4.0, + QtyKind::Volume => 5.0, + }; + f.nums(&[a, code, *v]); + } + } + } + } +} + +/// Kopf eines Bauteil-Datensatzes: `[art, struktur, id, name]`. +fn w_head(f: &mut Flat, rec: f64, structure: f64, id: &str, name: &str) { + let (a, b) = (f.str(id), f.str(name)); + f.nums(&[rec, structure, a, b]); +} + +// ── Geometrie-Helfer (Welt-Meter) ─────────────────────────────────────────── + +fn sub(a: Vec2, b: Vec2) -> Vec2 { + Vec2 { x: a.x - b.x, y: a.y - b.y } +} +fn normalize(v: Vec2) -> Vec2 { + let l = hypot2(v.x, v.y); + let l = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + Vec2 { x: v.x / l, y: v.y / l } +} +fn left_normal(u: Vec2) -> Vec2 { + Vec2 { x: -u.y, y: u.x } +} +fn add_scaled(p: Vec2, d: Vec2, s: f64) -> Vec2 { + Vec2 { x: p.x + d.x * s, y: p.y + d.y * s } +} +fn dot(a: Vec2, b: Vec2) -> f64 { + a.x * b.x + a.y * b.y +} +fn v2(p: [f64; 2]) -> Vec2 { + Vec2 { x: p[0], y: p[1] } +} + +/// Rechteck `[from,to]` entlang der Wandachse × `[n_lo,n_hi]` quer dazu (Welt-XY, CCW). +fn axis_rect(wall: &Wall, from: f64, to: f64, n_lo: f64, n_hi: f64) -> Vec { + let u = normalize(sub(wall.end, wall.start)); + let n = left_normal(u); + let a = add_scaled(wall.start, u, from); + let b = add_scaled(wall.start, u, to); + vec![add_scaled(a, n, n_lo), add_scaled(b, n, n_lo), add_scaled(b, n, n_hi), add_scaled(a, n, n_hi)] +} + +/// Sortierung `byFrom` (Anfang, dann Unterkante; NaN gilt als gleich wie in `Array.sort`). +fn by_from(p: &[f64; 4], q: &[f64; 4]) -> std::cmp::Ordering { + let d = p[0] - q[0]; + let d = if d != 0.0 && !d.is_nan() { d } else { p[2] - q[2] }; + if d < 0.0 { + std::cmp::Ordering::Less + } else if d > 0.0 { + std::cmp::Ordering::Greater + } else { + std::cmp::Ordering::Equal + } +} + +/// Ob die Schicht-Bänder einer Wand exakt „Quader minus Öffnungen" sind: kein Band mit schräger +/// Oberkante, und jedes Band trägt genau die Öffnungen als Löcher, die es in der Höhe trifft — in +/// derselben Grösse. Dann ergibt Extrusion je Band minus IfcOpeningElement denselben Körper wie das 3D. +fn bands_match_openings(wall: &Wall, bands: &[&RWall], cutouts: &[Cutout]) -> bool { + let u = normalize(sub(wall.end, wall.start)); + for b in bands { + if b.top_drop.is_some_and(|d| d[0].abs() > 1e-9 || d[1].abs() > 1e-9) { + return false; + } + let a = dot(Vec2 { x: b.start[0] - wall.start.x, y: b.start[1] - wall.start.y }, u); + let zb = b.base_elevation; + let zt = b.base_elevation + b.height; + let mut expected: Vec<[f64; 4]> = + cutouts.iter().filter(|h| h.z_top > zb + BAND_EPS && h.z_bottom < zt - BAND_EPS).map(|h| [h.from - a, h.to - a, h.z_bottom, h.z_top]).collect(); + expected.sort_by(by_from); + let mut actual: Vec<[f64; 4]> = b.holes.as_deref().unwrap_or(&[]).iter().map(|h| [h.from, h.to, h.z_bottom, h.z_top]).collect(); + actual.sort_by(by_from); + if expected.len() != actual.len() { + return false; + } + for (e, x) in expected.iter().zip(&actual) { + for k in 0..4 { + if !((e[k] - x[k]).abs() <= 1e-6) { + return false; + } + } + } + } + true +} + +/// Ausdehnung aller Bänder quer zur Wandachse (entlang der linken Normalen ab `wall.start`). +fn cross_extent(wall: &Wall, bands: &[&RWall]) -> (f64, f64) { + let n = left_normal(normalize(sub(wall.end, wall.start))); + let (mut n_lo, mut n_hi) = (f64::INFINITY, f64::NEG_INFINITY); + for b in bands { + let off = dot(Vec2 { x: b.start[0] - wall.start.x, y: b.start[1] - wall.start.y }, n); + n_lo = min(n_lo, off - b.thickness / 2.0); + n_hi = max(n_hi, off + b.thickness / 2.0); + } + (n_lo, n_hi) +} + +/// Vereinfachter Bounding-Footprint einer Treppe (gerade: Lauf-Rechteck; sonst achsparallele Box der +/// Kontrollpunkte bzw. des Wendel-Kreises, um die halbe Laufbreite erweitert). +fn stair_footprint(st: &Stair) -> Vec { + let half_w = max(st.width, 0.0) / 2.0; + if st.shape == StairShape::Straight { + let u = normalize(st.dir); + let n = left_normal(u); + let end = add_scaled(st.start, u, st.run_length); + return vec![add_scaled(st.start, n, -half_w), add_scaled(end, n, -half_w), add_scaled(end, n, half_w), add_scaled(st.start, n, half_w)]; + } + let truthy = |v: Option| v.filter(|x| *x != 0.0 && !x.is_nan()); + let mut pts = vec![st.start]; + let u = normalize(st.dir); + let corner = add_scaled(st.start, u, st.run_length); + pts.push(corner); + if st.shape == StairShape::L { + if let (Some(run2), Some(turn)) = (truthy(st.run2_length), truthy(st.turn)) { + let n = left_normal(u); + pts.push(add_scaled(corner, Vec2 { x: n.x * turn, y: n.y * turn }, run2)); + } + } + if st.shape == StairShape::Spiral { + if let Some(c) = st.center { + let r = st.radius.unwrap_or(0.0) + half_w; + return vec![Vec2 { x: c.x - r, y: c.y - r }, Vec2 { x: c.x + r, y: c.y - r }, Vec2 { x: c.x + r, y: c.y + r }, Vec2 { x: c.x - r, y: c.y + r }]; + } + } + let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for p in &pts { + min_x = min(min_x, p.x); + min_y = min(min_y, p.y); + max_x = max(max_x, p.x); + max_y = max(max_y, p.y); + } + min_x -= half_w; + min_y -= half_w; + max_x += half_w; + max_y += half_w; + vec![Vec2 { x: min_x, y: min_y }, Vec2 { x: max_x, y: min_y }, Vec2 { x: max_x, y: max_y }, Vec2 { x: min_x, y: max_y }] +} + +fn roof_predefined(s: RoofShape) -> &'static str { + match s { + RoofShape::Flach => "FLAT_ROOF", + RoofShape::Pult => "SHED_ROOF", + RoofShape::Sattel => "GABLE_ROOF", + RoofShape::Walm => "HIP_ROOF", + RoofShape::Mansarde => "MANSARD_ROOF", + RoofShape::Zelt => "HIPPED_GABLE_ROOF", + RoofShape::Unknown => "NOTDEFINED", + } +} + +// ── Türen und Fenster (Parameter für `fileio/src/ifc_openings.rs`) ───────────────────────────── + + +/// Ein Eintrag der Flügeltabelle (`SashDef`): Pfosten?, Pfostenbreite, feste Breite?, Breite. +#[derive(Debug, Clone, PartialEq)] +struct FillSash { + post: bool, + post_width: Option, + fixed: bool, + width: Option, +} + +/// Parameter der Füllung einer Öffnung (Kodierung FILL im Kopf von `ifc_export.rs`), aus Typ und +/// Öffnung; fehlende Typwerte bleiben „keine", die Standardmasse kennt nur `fileio`. +#[derive(Debug, Clone, PartialEq)] +struct FillParams { + frame_depth: Option, + inset: Option, + inset_outside: bool, + frame_width: Option, + /// Fenster: Flügelzahl, Scheiben (1–3), Flügeltabelle. + wing_count: f64, + panes: f64, + sashes: Vec, + /// Tür: 0 Dreh, 1 Schiebe, 2 reine Wandöffnung. + door_kind: f64, + leaf_count: f64, + /// +1 Aufschlag links der Achse, −1 rechts; Richtung +1 innen, −1 aussen. + swing_sign: f64, + dir_sign: f64, + hinge_at_start: bool, + transom_height: f64, + glazed: bool, + glazing_ratio: Option, +} + +fn fill_params(p: &Project, o: &Opening) -> FillParams { + let is_door = o.kind == ElementKind::Door; + let dt = if is_door { p.door_type(o) } else { None }; + let wt = if is_door { None } else { p.window_type(o) }; + FillParams { + frame_depth: dt.map_or(wt.and_then(|t| t.frame_depth), |t| t.frame_depth), + inset: dt.map_or(wt.and_then(|t| t.inset_from_face), |t| t.inset_from_face), + inset_outside: match (dt, wt) { + (Some(t), _) => matches!(t.inset_face, None | Some(DoorTypeInsetFace::Aussen)), + (None, Some(t)) => matches!(t.inset_face, None | Some(WindowTypeInsetFace::Aussen)), + _ => true, + }, + frame_width: dt.map_or(wt.and_then(|t| t.frame_width), |t| t.frame_width), + wing_count: o.wing_count.or(wt.map(|t| t.wing_count)).unwrap_or(1.0), + panes: wt.map_or(2.0, |t| match t.glazing_panes { + Some(v) if v != 0.0 && !v.is_nan() => v, + _ => match t.glazing { + WindowTypeGlazing::Dreifach => 3.0, + WindowTypeGlazing::Zweifach => 2.0, + _ => 1.0, + }, + }), + sashes: wt + .and_then(|t| t.sashes.as_deref()) + .unwrap_or(&[]) + .iter() + .map(|s| FillSash { post: s.kind == SashDefKind::Pfosten, post_width: s.post_width, fixed: s.auto_width == Some(false), width: s.width }) + .collect(), + // Türart: Typ vor Öffnung. + door_kind: match dt.map(|t| t.kind) { + Some(DoorTypeKind::Schiebe) => 1.0, + Some(DoorTypeKind::Wandoeffnung) => 2.0, + Some(_) => 0.0, + None if o.door_type == Some(OpeningDoorType::Wandoeffnung) => 2.0, + None => 0.0, + }, + leaf_count: dt.map_or(1.0, |t| t.leaf_count), + swing_sign: if matches!(o.swing, None | Some(SwingSide::Left)) { 1.0 } else { -1.0 }, + dir_sign: if matches!(o.opening_dir, None | Some(OpeningOpeningDir::In)) { 1.0 } else { -1.0 }, + hinge_at_start: matches!(o.hinge, None | Some(OpeningHinge::Start)), + transom_height: dt.and_then(|t| t.transom_height).unwrap_or(0.0), + glazed: dt.is_some_and(|t| t.leaf_style == DoorTypeLeafStyle::Glas), + glazing_ratio: dt.and_then(|t| t.glazing_ratio), + } +} + +/// FILL schreiben: Wandachse, Achs-Intervall und Höhen der Öffnung, Querausdehnung der Wand +/// (`host` = n_lo aussen, n_hi), dann die Parameter. +fn w_fill(f: &mut Flat, wall: &Wall, c: &Cutout, host: (f64, f64), x: &FillParams) { + let opt = |f: &mut Flat, v: Option| { + f.nums(&[if v.is_some() { 1.0 } else { 0.0 }, v.unwrap_or(0.0)]); + }; + let flag = |b: bool| if b { 1.0 } else { 0.0 }; + f.nums(&[wall.start.x, wall.start.y, wall.end.x, wall.end.y, c.from, c.to, c.z_bottom, c.z_top, host.0, host.1]); + opt(f, x.frame_depth); + opt(f, x.inset); + f.num(flag(x.inset_outside)); + opt(f, x.frame_width); + f.nums(&[x.wing_count, x.panes, x.sashes.len() as f64]); + for s in &x.sashes { + f.num(flag(s.post)); + opt(f, s.post_width); + f.num(flag(s.fixed)); + opt(f, s.width); + } + f.nums(&[x.door_kind, x.leaf_count, x.swing_sign, x.dir_sign, flag(x.hinge_at_start), x.transom_height, flag(x.glazed)]); + opt(f, x.glazing_ratio); +} + +/// Ebene (Code, Name) eines Bauteils als Klassifikation; ohne Code `None`, ohne bekannte Ebene der +/// Code als Name. +fn layer_classification(p: &Project, category_code: &str) -> Option<(String, String)> { + let code = js_trim(category_code); + if code.is_empty() { + return None; + } + Some((code.to_string(), p.layer_category(code).map_or(code, |l| l.name.as_str()).to_string())) +} + + +// ── Klassifikation ────────────────────────────────────────────────────────── + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Wall, + Slab, + Roof, + Column, + Stair, + Window, + Door, + Space, +} + +/// eBKP-H-Hauptgruppe zur Bauteilart, oder `None` (Tür, Raum: nicht eindeutig). +fn ebkph_group(k: Kind) -> Option<(&'static str, &'static str)> { + match k { + Kind::Wall | Kind::Slab | Kind::Column | Kind::Stair => Some(("C", "Konstruktion Gebäude")), + Kind::Roof => Some(("F", "Bedachung Gebäude")), + Kind::Window => Some(("E", "Äussere Wandbekleidung Gebäude")), + Kind::Door | Kind::Space => None, + } +} + +fn w_classification(f: &mut Flat, system: (&str, &str, &str), refs: &[(String, String, String)]) { + if refs.is_empty() { + return; + } + let (a, b, c) = (f.str(system.0), f.str(system.1), f.str(system.2)); + f.nums(&[REC_CLASSIFICATION, a, b, c, refs.len() as f64]); + for (key, code, name) in refs { + let (a, b, c) = (f.str(key), f.str(code), f.str(name)); + f.nums(&[a, b, c]); + } +} + +fn sia_key(c: SiaCategory) -> String { + serde_json::to_value(c).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default() +} + +fn sia_label(key: &str) -> &'static str { + match key { + "HNF" => "Hauptnutzfläche", + "NNF" => "Nebennutzfläche", + "VF" => "Verkehrsfläche", + "FF" => "Funktionsfläche", + "KGF" => "Konstruktionsfläche", + "AGF" => "Aussengeschossfläche", + _ => "", + } +} + +const SIA_CATEGORIES: [SiaCategory; 6] = [SiaCategory::HNF, SiaCategory::NNF, SiaCategory::VF, SiaCategory::FF, SiaCategory::KGF, SiaCategory::AGF]; + +/// Gleiche Fehlermeldung wie die Pick-Geometrie des 3D (`pickGeometry`): eine Öffnung in einer Wand +/// mit unbekanntem Wandtyp bricht ab, bevor die Wände gerechnet werden. +pub(crate) fn pick_opening_check(p: &Project) -> Result<(), String> { + for o in p.openings.as_deref().unwrap_or(&[]) { + let Some(wall) = p.walls.iter().find(|w| w.id == o.host_wall_id) else { continue }; + let axis = hypot2(wall.end.x - wall.start.x, wall.end.y - wall.start.y); + let from = max(0.0, min(o.position, axis)); + let to = max(from, min(o.position + o.width, axis)); + if to - from < 1e-4 { + continue; + } + if p.wall_type(wall).is_none() { + return Err(format!("Unbekannter Wandtyp: {}", wall.wall_type_id)); + } + } + Ok(()) +} + +/// Der flache IFC-Puffer aus dem Projekt (s. Modulkopf). +pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result { + // Georeferenziert: die ganze Geometrie auf die echten LV95-Koordinaten (ohne Bezug unverändert). + let mut p = project_to_world_coords(src); + let mut f = Flat::new(FLAT_VERSION); + + // Je "floor"-Ebene ein IfcBuildingStorey (Elevation = baseElevation). + let floors: Vec = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).cloned().collect(); + let mut storey_of: HashMap<&str, usize> = HashMap::new(); + let storey_base: Vec = floors.iter().map(|l| l.base_elevation.unwrap_or(0.0)).collect(); + for (i, fl) in floors.iter().enumerate() { + storey_of.insert(fl.id.as_str(), i); + } + let structure_of = |floor_id: &str| -> f64 { storey_of.get(floor_id).map_or(-1.0, |&i| i as f64) }; + let base_of = |structure: f64| -> f64 { if structure < 0.0 { 0.0 } else { storey_base[structure as usize] } }; + + // Kopf: RefElevation = reale Datumshöhe (informativ), RefLatitude/-Longitude des Bezugspunkts. + let anchor = p.geo_anchor.clone(); + let lat_lon = anchor.as_ref().map(|a| (a.lv95.e, a.lv95.n)).filter(|(e, n)| e.is_finite() && n.is_finite()).map(|(e, n)| lv95_to_wgs84(e, n)).filter(|(la, lo)| la.is_finite() && lo.is_finite()); + let (pid, pname) = (f.str(&p.id), f.str(&p.name)); + let iso = f.str(&opt.iso); + f.nums(&[ + pid, + pname, + opt.now, + iso, + if anchor.is_some() { 1.0 } else { 0.0 }, + anchor.as_ref().and_then(|a| a.height).unwrap_or(f64::NAN), + lat_lon.map_or(f64::NAN, |x| x.0), + lat_lon.map_or(f64::NAN, |x| x.1), + if opt.ifc2x3 { 1.0 } else { 0.0 }, + floors.len() as f64, + ]); + for (i, fl) in floors.iter().enumerate() { + let (a, b) = (f.str(&fl.id), f.str(&fl.name)); + f.nums(&[a, b, storey_base[i]]); + } + + // Klassifikation: je geschriebenem Bauteil Schlüssel (wie für die GUID), Art und Ebene; `fileio` + // überspringt Schlüssel ohne geschriebenes Bauteil. + let mut classified: Vec<(String, Kind, String)> = Vec::new(); + + let component_name = |p: &Project, id: &str| -> String { p.component(id).map_or_else(|| id.to_string(), |c| c.name.clone()) }; + + // ── Wände ────────────────────────────────────────────────────────────── + pick_opening_check(&p)?; + let all_bands = model3d::emit_walls(&p, true)?; + let mut bands_by_wall: HashMap<&str, Vec<&RWall>> = HashMap::new(); + for b in &all_bands { + bands_by_wall.entry(b.wall_id.as_str()).or_default().push(b); + } + let no_bands: Vec<&RWall> = Vec::new(); + let mut host_extent: HashMap = HashMap::new(); + let mut cutouts_by_wall: HashMap> = HashMap::new(); + let mut mesh_walls: Vec = Vec::new(); + let openings: Vec = p.openings.clone().unwrap_or_default(); + let wall_ident = |p: &Project, wall: &Wall, quantities: Vec| -> (String, Option, Vec) { + let q = qto("Qto_WallBaseQuantities", quantities); + match p.wall_type(wall) { + Some(wt) => { + let layers = wt.layers.iter().map(|l| (l.component_id.clone(), component_name(p, &l.component_id), l.thickness)).collect(); + let mut ps = vec![Pset { name: "Pset_WallCommon", props: vec![ident("Reference", &wt.name)] }]; + ps.extend(q); + (wt.name.clone(), Some((wt.id.clone(), wt.name.clone(), layers)), ps) + } + None => (wall.id.clone(), None, q), + } + }; + let cutouts_of = |p: &Project, wall: &Wall| -> Vec<(usize, Cutout)> { + let mut out = Vec::new(); + let (zb, zt) = p.wall_vertical_extent(wall); + let axis = hypot2(wall.end.x - wall.start.x, wall.end.y - wall.start.y); + for (k, o) in openings.iter().enumerate().filter(|(_, o)| o.host_wall_id == wall.id) { + let from = max(0.0, min(o.position, axis)); + let to = max(from, min(o.position + o.width, axis)); + if to - from < 1e-4 { + continue; + } + let bottom = zb + max(0.0, o.sill_height); + let top = min(zt, bottom + o.height); + out.push((k, Cutout { from, to, z_bottom: bottom, z_top: top })); + } + out + }; + + for (wi, wall) in p.walls.iter().enumerate() { + let all = bands_by_wall.get(wall.id.as_str()).unwrap_or(&no_bands); + let bands: Vec<&RWall> = all.iter().copied().filter(|b| hypot2(b.end[0] - b.start[0], b.end[1] - b.start[1]) > 1e-9 && b.height > 1e-9 && b.thickness > 1e-9).collect(); + if bands.is_empty() { + continue; // degenerierte Wand / keine Geometrie + } + let cutouts = cutouts_of(&p, wall); + let plain: Vec = cutouts.iter().map(|x| x.1).collect(); + cutouts_by_wall.insert(wall.id.clone(), cutouts); + classified.push((format!("wall/{}", wall.id), Kind::Wall, wall.category_code.clone())); + if !bands_match_openings(wall, &bands, &plain) { + mesh_walls.push(wi); + continue; + } + let structure = structure_of(&wall.floor_id); + let (name, ty, psets) = wall_ident(&p, wall, qty::wall_quantities(wall.start, wall.end, &bands, &plain, None)); + // Wandsystem: Placement am Wandanfang, X = Achse, Y = linke Normale; IfcMaterialLayerSetUsage nur, + // wenn die Typ-Schichten den Querschnitt der Bänder füllen (sonst wäre der Offset gelogen). + let extent = cross_extent(wall, &bands); + let layer_sum = ty.as_ref().map_or(0.0, |t| t.2.iter().fold(0.0, |a, l| a + l.2)); + let usage = ty.is_some() && layer_sum > 0.0 && (extent.1 - extent.0 - layer_sum).abs() < 1e-3; + w_head(&mut f, REC_WALL_SOLIDS, structure, &wall.id, &name); + w_type(&mut f, ty.as_ref().map(|t| type_ref(t, 0.0, "STANDARD")).as_ref()); + w_psets(&mut f, &psets); + let u = normalize(sub(wall.end, wall.start)); + f.nums(&[1.0, wall.start.x, wall.start.y, u.x, u.y, hypot2(wall.end.x - wall.start.x, wall.end.y - wall.start.y), if usage { 1.0 } else { 0.0 }, if usage { extent.0 } else { 0.0 }]); + f.num(bands.len() as f64); + let base = base_of(structure); + for b in &bands { + let (s, e) = (v2(b.start), v2(b.end)); + let n = left_normal(normalize(sub(e, s))); + let h = b.thickness / 2.0; + w_pts(&mut f, &[add_scaled(s, n, -h), add_scaled(e, n, -h), add_scaled(e, n, h), add_scaled(s, n, h)]); + f.nums(&[b.base_elevation - base, b.height]); + } + host_extent.insert(wall.id.clone(), extent); + } + // Netz-Weg: alle Bänder einer Wand zu EINEM Face-Set; Modell-Welt (x, Höhe, y) → IFC (x, y, z), + // die Spiegelung kehrt die Wicklung um, daher (a, c, b). Z relativ zur Geschoss-UK. + for &wi in &mesh_walls { + let wall = &p.walls[wi]; + let structure = structure_of(&wall.floor_id); + let base = base_of(structure); + let bands = bands_by_wall.get(wall.id.as_str()).unwrap_or(&no_bands); + let (mut positions, mut indices) = (Vec::::new(), Vec::::new()); + for b in bands { + let cut = wall_cut_mesh_checked(&CutWall { + start: b.start, + end: b.end, + thickness: b.thickness, + base_elevation: b.base_elevation, + height: b.height, + holes: b.holes.as_deref().unwrap_or(&[]).iter().map(|h| [h.from, h.to, h.z_bottom, h.z_top]).collect(), + }); + let at = (positions.len() / 3) as u32; + for c in cut.chunks_exact(3) { + positions.extend_from_slice(&[c[0], c[2], c[1] - base]); + } + let n = (cut.len() / 3) as u32; + let mut i = 0; + while i + 2 < n { + indices.extend_from_slice(&[at + i, at + i + 2, at + i + 1]); + i += 3; + } + } + if indices.is_empty() { + continue; + } + // Closed nur, wenn das Netz nachweislich dicht und aussen orientiert ist. + let closed = is_watertight(&positions, &indices, 1e-6); + let net = closed.then(|| crate::export_flat::mesh_volume(&positions, &indices)); + let plain: Vec = cutouts_by_wall.get(&wall.id).map_or_else(Vec::new, |v| v.iter().map(|x| x.1).collect()); + let mut quantities = qty::wall_quantities(wall.start, wall.end, bands, &plain, net); + if net.is_none() { + let gross = quantities.iter().find(|x| x.name == "GrossVolume").map_or(f64::NAN, |x| x.value); + if let Some(nv) = quantities.iter_mut().find(|x| x.name == "NetVolume") { + nv.value = max(0.0, gross - qty::hole_volume(bands)); + } + } + let (name, ty, psets) = wall_ident(&p, wall, quantities); + w_head(&mut f, REC_WALL_MESH, structure, &wall.id, &name); + w_type(&mut f, ty.as_ref().map(|t| type_ref(t, 0.0, "STANDARD")).as_ref()); + w_psets(&mut f, &psets); + w_mesh(&mut f, &positions, &indices, closed); + host_extent.insert(wall.id.clone(), cross_extent(wall, bands)); + } + + // ── Decken ───────────────────────────────────────────────────────────── + for c in p.ceilings.as_deref().unwrap_or(&[]) { + if c.outline.len() < 3 { + continue; + } + let (z_bottom, z_top) = p.ceiling_vertical_extent(c); + let structure = structure_of(&c.floor_id); + classified.push((format!("slab/{}", c.id), Kind::Slab, c.category_code.clone())); + let mut name = c.id.clone(); + let mut ty: Option = None; + let mut psets: Vec = Vec::new(); + if let Some((id, tname, layers)) = model3d::ceiling_type_ref(&p, c) { + name = tname.to_string(); + ty = Some((id.to_string(), tname.to_string(), layers.iter().map(|l| (l.component_id.clone(), component_name(&p, &l.component_id), l.thickness)).collect())); + psets.push(Pset { name: "Pset_SlabCommon", props: vec![ident("Reference", tname)] }); + } + // Aussparungen (wie im 3D) als innere Ringe des Profils; Netto zieht sie ab. + let inner: Vec<&[Vec2]> = c.openings.as_deref().unwrap_or(&[]).iter().filter(|r| r.len() >= 3).map(|r| r.as_slice()).collect(); + psets.extend(qto("Qto_SlabBaseQuantities", qty::slab_quantities(&c.outline, &inner, z_top - z_bottom))); + w_head(&mut f, REC_CEILING, structure, &c.id, &name); + w_type(&mut f, ty.as_ref().map(|t| type_ref(t, 1.0, "FLOOR")).as_ref()); + w_psets(&mut f, &psets); + w_pts(&mut f, &c.outline); + f.num(inner.len() as f64); + for r in &inner { + w_pts(&mut f, r); + } + f.nums(&[z_bottom - base_of(structure), z_top - z_bottom]); + } + + // ── Öffnungen: IfcOpeningElement in der Wand, IfcDoor/IfcWindow darin ─── + for wall in &p.walls { + let Some(&host) = host_extent.get(&wall.id) else { continue }; + let structure = structure_of(&wall.floor_id); + for &(k, c) in cutouts_by_wall.get(&wall.id).map_or(&[][..], |v| v.as_slice()) { + let o = &openings[k]; + let depth = c.z_top - c.z_bottom; + if !(depth > 1e-6) { + continue; + } + let is_door = o.kind == ElementKind::Door; + classified.push((format!("fill/{}", o.id), if is_door { Kind::Door } else { Kind::Window }, o.category_code.clone())); + let mut props: Vec = Vec::new(); + let pset_name = if is_door { + let dt = p.door_type(o); + if let Some(dt) = dt { + props.push(ident("Reference", &dt.name)); + if dt.leaf_style == DoorTypeLeafStyle::Glas { + if let Some(ratio) = dt.glazing_ratio.filter(|r| *r > 0.0 && *r <= 1.0) { + props.push(Prop::Ratio("GlazingAreaFraction", ratio)); + } + } + } + "Pset_DoorCommon" + } else { + if let Some(wt) = p.window_type(o) { + props.push(ident("Reference", &wt.name)); + } + "Pset_WindowCommon" + }; + let mut psets = vec![Pset { name: pset_name, props }]; + psets.extend(qto(if is_door { "Qto_DoorBaseQuantities" } else { "Qto_WindowBaseQuantities" }, qty::opening_quantities(c.to - c.from, depth))); + let label = crate::plan::walls::opening_label(o); + let a = f.str(&wall.id); + let oid = f.str(&o.id); + let lab = f.str(&label); + f.nums(&[REC_OPENING, a, structure, oid, if is_door { 1.0 } else { 0.0 }, lab]); + w_pts(&mut f, &axis_rect(wall, c.from, c.to, host.0 - OPENING_OVERSHOOT, host.1 + OPENING_OVERSHOOT)); + f.nums(&[c.z_bottom - base_of(structure), depth, c.to - c.from]); + w_fill(&mut f, wall, &c, host, &fill_params(&p, o)); + w_psets(&mut f, &psets); + } + } + + // ── Treppen: Läufe, Podest, Geländer wie im 3D; ohne Teile der Fussabdruck-Quader ── + let stairs = p.stairs.take(); + for st in stairs.as_deref().unwrap_or(&[]) { + let footprint = stair_footprint(st); + if footprint.len() < 3 { + continue; + } + let (z_bottom, z_top) = p.stair_vertical_extent(st); + let structure = structure_of(&st.floor_id); + classified.push((format!("stair/{}", st.id), Kind::Stair, st.category_code.clone())); + let predefined = match st.shape { + StairShape::Straight => "STRAIGHT_RUN_STAIR", + StairShape::Spiral => "SPIRAL_STAIR", + _ => "QUARTER_TURN_STAIR", + }; + let base = base_of(structure); + p.stairs = Some(vec![st.clone()]); + let parts = stair_parts(&p, st, base); + w_stair(&mut f, structure, &st.id, predefined, &footprint, z_bottom - base, z_top - z_bottom, &parts); + } + p.stairs = stairs; + + // ── Extrudierte Körper → IfcBuildingElementProxy ─────────────────────── + for s in p.extruded_solids.as_deref().unwrap_or(&[]) { + if s.points.len() < 3 { + continue; + } + let base = floors.iter().find(|fl| fl.id == s.level_id).and_then(|fl| fl.base_elevation).unwrap_or(0.0); + let structure = structure_of(&s.level_id); + let id = f.str(&s.id); + f.nums(&[REC_EXTRUSION, structure, id]); + w_pts(&mut f, &s.points); + f.nums(&[base - base_of(structure), s.height]); + } + + // ── Räume → IfcSpace (im Geschoss aggregiert), Basismengen, SIA-416-Kategorie ── + let mut room_areas: Vec<(String, String, SiaCategory, f64)> = Vec::new(); + for room in p.rooms.as_deref().unwrap_or(&[]) { + if room.boundary.len() < 3 { + continue; + } + let structure = structure_of(&room.floor_id); + let height = floors.iter().find(|fl| fl.id == room.floor_id).and_then(|fl| fl.floor_height).filter(|h| *h != 0.0 && !h.is_nan() && *h > 0.0).unwrap_or(2.5); + let external = room.sia_category == SiaCategory::AGF; + let ring: Vec<[f64; 2]> = room.boundary.iter().map(|v| [v.x, v.y]).collect(); + let area = crate::room_area::evaluate(&ring, 0.0); + room_areas.push((room.id.clone(), room.floor_id.clone(), room.sia_category, area.net)); + classified.push((format!("space/{}", room.id), Kind::Space, room.category_code.clone())); + let number = room.stamp.as_ref().and_then(|s| s.number.as_deref()).filter(|n| !n.is_empty()); + let mut common: Vec = Vec::new(); + if let Some(n) = number { + common.push(ident("Reference", n)); + } + common.push(Prop::Bool("IsExternal", external)); + let (id, name, long) = (f.str(&room.id), f.str(number.unwrap_or(&room.id)), f.str(&room.name)); + f.nums(&[REC_SPACE, structure, id, name, long, if external { 1.0 } else { 0.0 }, height]); + w_pts(&mut f, &room.boundary); + let cat = f.str(&sia_key(room.sia_category)); + f.nums(&[area.net, area.gross, cat]); + w_psets(&mut f, &[Pset { name: "Pset_SpaceCommon", props: common }]); + } + f.num(REC_END_SPACES); + + // SIA 416: je vorkommender Kategorie eine IfcZone mit den Räumen. + for cat in SIA_CATEGORIES { + let members: Vec<&(String, String, SiaCategory, f64)> = room_areas.iter().filter(|r| r.2 == cat).collect(); + if members.is_empty() { + continue; + } + let net = members.iter().fold(0.0, |a, r| a + r.3); + let key = sia_key(cat); + let (k, n, l) = (f.str(&format!("sia416/{key}")), f.str(&key), f.str(sia_label(&key))); + f.nums(&[REC_ZONE, k, n, l, members.len() as f64]); + for r in &members { + let id = f.str(&r.0); + f.num(id); + } + w_psets( + &mut f, + &[ + Pset { name: "CH_Zone", props: vec![ident("SIA416", &key)] }, + Pset { name: "CH_Qto_SIA416", props: vec![Prop::Qty("NetFloorArea", QtyKind::Area, max(0.0, net))] }, + ], + ); + } + // Geschoss-Kennwerte: GF/NGF als Basismenge des IfcBuildingStorey, alle SIA-416-Flächen als CH_Qto_SIA416. + for fl in &floors { + let rooms: Vec<(usize, f64)> = room_areas.iter().filter(|r| r.1 == fl.id).map(|r| (SIA_CATEGORIES.iter().position(|c| *c == r.2).unwrap_or(usize::MAX), r.3)).collect(); + if rooms.is_empty() { + continue; + } + let b = crate::room_area::balance(&rooms); + let by_key = |k: &str| -> f64 { + match k { + "NF" => b.agg_area[0], + "NGF" => b.agg_area[1], + "GF" => b.agg_area[2], + _ => crate::room_area::CATEGORIES.iter().position(|c| *c == k).map_or(0.0, |i| b.leaf_area[i]), + } + }; + let key = f.str(&format!("storey/{}", fl.id)); + f.nums(&[REC_ATTACH, key]); + w_psets( + &mut f, + &[ + Pset { + name: "Qto_BuildingStoreyBaseQuantities", + props: vec![Prop::Qty("GrossFloorArea", QtyKind::Area, max(0.0, by_key("GF"))), Prop::Qty("NetFloorArea", QtyKind::Area, max(0.0, by_key("NGF")))], + }, + Pset { + name: "CH_Qto_SIA416", + props: ["HNF", "NNF", "NF", "VF", "FF", "NGF", "KGF", "AGF", "GF"].iter().map(|k| Prop::Qty(k, QtyKind::Area, max(0.0, by_key(k)))).collect(), + }, + ], + ); + } + + // ── Dächer → IfcRoof (Schicht-Netze wie im 3D, ein Face-Set je Dach, Modell ist Z-oben) ── + let roofs = p.roofs.take(); + for roof in roofs.as_deref().unwrap_or(&[]) { + let structure = structure_of(&roof.floor_id); + let base = base_of(structure); + classified.push((format!("roof/{}", roof.id), Kind::Roof, roof.category_code.clone())); + p.roofs = Some(vec![roof.clone()]); + let meshes = model3d::emit_roofs(&p, None)?; + let (mut positions, mut indices) = (Vec::::new(), Vec::::new()); + for m in &meshes { + let at = (positions.len() / 3) as u32; + for c in m.positions.chunks_exact(3) { + positions.extend_from_slice(&[c[0], c[1], c[2] - base]); + } + indices.extend(m.indices.iter().map(|i| at + i)); + } + if indices.is_empty() { + continue; + } + let mut closed = is_watertight(&positions, &indices, 1e-6); + if !closed { + let flipped: Vec = indices.chunks_exact(3).flat_map(|t| [t[0], t[2], t[1]]).collect(); + if is_watertight(&positions, &flipped, 1e-6) { + indices = flipped; + closed = true; + } + } + let predefined = roof_predefined(roof.shape); + let roof_type = roof.roof_type_id.as_deref().filter(|s| !s.is_empty()).and_then(|id| p.roof_types.as_deref().unwrap_or(&[]).iter().find(|t| t.id == id)); + // Ein Dach ist Gebäudehülle: IsExternal folgt aus der Bauteilart. + let mut props: Vec = Vec::new(); + if let Some(t) = roof_type { + props.push(ident("Reference", &t.name)); + } + props.push(Prop::Bool("IsExternal", true)); + let planes = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)).planes; + let mut psets = vec![Pset { name: "Pset_RoofCommon", props }]; + psets.extend(qto("Qto_RoofBaseQuantities", qty::roof_quantities(&planes))); + let ty = roof_type.map(|t| (t.id.clone(), t.name.clone(), t.layers.iter().map(|l| (l.component_id.clone(), component_name(&p, &l.component_id), l.thickness)).collect::>())); + let (id, name, pre) = (f.str(&roof.id), f.str(roof_type.map_or("Dach", |t| t.name.as_str())), f.str(predefined)); + f.nums(&[REC_ROOF, structure, id, name, pre]); + w_type(&mut f, ty.as_ref().map(|t| type_ref(t, 2.0, predefined)).as_ref()); + w_psets(&mut f, &psets); + w_mesh(&mut f, &positions, &indices, closed); + } + p.roofs = roofs; + + // ── Stützen → IfcColumn (Profil-Extrusion, Material = Bauteil) ────────── + for col in p.columns.as_deref().unwrap_or(&[]) { + let footprint = model3d::column_footprint(col); + if footprint.len() < 3 { + continue; + } + let (z_bottom, z_top) = p.column_vertical_extent(col); + if !(z_top > z_bottom) { + continue; + } + let structure = structure_of(&col.floor_id); + classified.push((format!("column/{}", col.id), Kind::Column, col.category_code.clone())); + let label = crate::plan::domains::column_label(col); + let mut psets = vec![Pset { name: "Pset_ColumnCommon", props: vec![ident("Reference", &label)] }]; + psets.extend(qto("Qto_ColumnBaseQuantities", qty::column_quantities(&footprint, z_top - z_bottom))); + let (id, lab) = (f.str(&col.id), f.str(&label)); + f.nums(&[REC_COLUMN, structure, id, lab]); + w_pts(&mut f, &footprint); + let comp = col.component_id.as_deref().filter(|s| !s.is_empty()); + let cid = comp.map_or(-1.0, |c| f.str(c)); + let cname = comp.map_or(-1.0, |c| { + let n = component_name(&p, c); + f.str(&n) + }); + f.nums(&[z_bottom - base_of(structure), z_top - z_bottom, cid, cname]); + w_psets(&mut f, &psets); + } + f.num(REC_END_COLUMNS); + + // ── Klassifikation (Optionen), am Ende: alle Bauteile sind geschrieben ── + if opt.ebkph { + let refs: Vec<(String, String, String)> = + classified.iter().filter_map(|(key, kind, _)| ebkph_group(*kind).map(|(c, n)| (key.clone(), c.to_string(), n.to_string()))).collect(); + w_classification(&mut f, ("eBKP-H", "CRB Schweizerische Zentralstelle für Baurationalisierung", "SN 506 511:2020"), &refs); + } + if opt.layer_codes { + let refs: Vec<(String, String, String)> = + classified.iter().filter_map(|(key, _, code)| layer_classification(&p, code).map(|(c, n)| (key.clone(), c, n))).collect(); + w_classification(&mut f, ("Dossier-Ebenen", "Dossier", ""), &refs); + } + Ok(f) +} + +#[allow(clippy::too_many_arguments)] +fn w_stair(f: &mut Flat, structure: f64, id: &str, predefined: &str, footprint: &[Vec2], z_rel: f64, depth: f64, parts: &StairParts) { + let (a, b) = (f.str(id), f.str(predefined)); + f.nums(&[REC_STAIR, structure, a, b]); + w_pts(f, footprint); + f.nums(&[z_rel, depth]); + w_psets(f, &[]); + f.num(parts.flights.len() as f64); + for fl in &parts.flights { + let n = f.str(&fl.name); + f.nums(&[n, fl.risers, fl.treads, fl.riser_height, fl.tread_length]); + let p = f.str(fl.predefined); + f.num(p); + w_psets(f, &qto("Qto_StairFlightBaseQuantities", fl.quantities.clone())); + match &fl.body { + FlightBody::Mesh(m) => { + f.num(1.0); + w_mesh(f, &m.positions, &m.indices, false); + } + FlightBody::Solids(solids) => { + f.nums(&[0.0, solids.len() as f64]); + for s in solids { + w_pts(f, &s.pts); + f.nums(&[s.z_rel, s.depth]); + } + } + } + } + match &parts.landing { + Some(l) => { + let n = f.str("Podest"); + f.nums(&[1.0, n]); + w_pts(f, &l.pts); + f.nums(&[l.z_rel, l.depth]); + w_psets(f, &qto("Qto_SlabBaseQuantities", l.quantities.clone())); + } + None => { + f.num(0.0); + } + } + match &parts.rail { + Some(r) => { + let (n, pre) = (f.str("Handlauf"), f.str("HANDRAIL")); + f.nums(&[1.0, n, pre]); + w_psets(f, &qto("Qto_RailingBaseQuantities", r.quantities.clone())); + w_mesh(f, &r.mesh.positions, &r.mesh.indices, false); + } + None => { + f.num(0.0); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::export_flat::from_bytes; + + fn sample() -> Project { + serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap() + } + + fn strings(f: &Flat) -> Vec { + let (_, text) = from_bytes(&f.to_bytes()).unwrap(); + text.split('\0').map(String::from).collect() + } + + #[test] + fn beispielprojekt_alle_bauteile() { + let opt = IfcOptions { ebkph: true, layer_codes: true, now: 1.0, iso: "2026-10-29T10:00:00".into(), ..Default::default() }; + let f = ifc_export_data(&sample(), &opt).unwrap(); + assert_eq!(f.nums[0], FLAT_VERSION); + let s = strings(&f); + for want in ["W1", "Pset_WallCommon", "Qto_WallBaseQuantities", "Pset_DoorCommon", "Qto_SlabBaseQuantities", "Qto_StairFlightBaseQuantities", "Pset_RoofCommon", "sia416/HNF", "storey/eg", "eBKP-H", "Dossier-Ebenen", "Wände"] { + assert!(s.iter().any(|x| x == want), "fehlt: {want}"); + } + } + + #[test] + fn georeferenz_verschiebt_und_setzt_breite() { + let mut p = sample(); + p.geo_anchor = Some(ProjectGeoAnchor { lv95: ProjectGeoAnchorLv95 { e: 2_683_000.0, n: 1_247_000.0, ..Default::default() }, model: Vec2 { x: 0.0, y: 0.0 }, height: Some(400.0), ..Default::default() }); + let f = ifc_export_data(&p, &IfcOptions::default()).unwrap(); + // Kopf: [Version, id, name, now, iso, hasGeo, refElevation, lat, lon, schema, nStoreys …] + assert_eq!(f.nums[5], 1.0); + assert_eq!(f.nums[6], 400.0); + assert!((f.nums[7] - 47.37).abs() < 0.1 && (f.nums[8] - 8.54).abs() < 0.1, "{} {}", f.nums[7], f.nums[8]); + assert!(f.nums.iter().any(|v| *v > 2_683_000.0)); + } + + #[test] + fn leeres_projekt_und_unbekannter_wandtyp() { + let mut p = Project { id: "leer".into(), ..Default::default() }; + let f = ifc_export_data(&p, &IfcOptions::default()).unwrap(); + assert_eq!(f.nums.last(), Some(&REC_END_COLUMNS)); + p = sample(); + p.walls[0].wall_type_id = "fehlt".into(); + assert_eq!(ifc_export_data(&p, &IfcOptions::default()).unwrap_err(), "Unbekannter Wandtyp: fehlt"); + } + + #[test] + fn treppen_fussabdruck() { + let st = Stair { shape: StairShape::Spiral, center: Some(Vec2 { x: 1.0, y: 1.0 }), radius: Some(1.0), width: 1.0, ..Default::default() }; + assert_eq!(stair_footprint(&st)[0], Vec2 { x: -0.5, y: -0.5 }); + let st = Stair { shape: StairShape::Straight, dir: Vec2 { x: 0.0, y: 2.0 }, run_length: 3.0, width: 1.0, ..Default::default() }; + assert_eq!(stair_footprint(&st)[2], Vec2 { x: -0.5, y: 3.0 }); + } + + fn opening(kind: ElementKind, type_id: Option<&str>) -> Opening { + Opening { id: "O".into(), host_wall_id: "W".into(), kind, position: 1.0, width: 1.2, height: 1.2, type_id: type_id.map(String::from), ..Default::default() } + } + + #[test] + fn fenster_parameter_aus_typ_und_oeffnung() { + let mut p = Project::default(); + p.window_types = Some(vec![WindowType { + id: "wt".into(), + kind: OpeningKind::Dreh, + wing_count: 3.0, + glazing: WindowTypeGlazing::Dreifach, + frame_width: Some(0.09), + frame_depth: Some(0.1), + inset_from_face: Some(0.05), + inset_face: Some(WindowTypeInsetFace::Innen), + sashes: Some(vec![ + SashDef { kind: SashDefKind::Fluegel, auto_width: Some(false), width: Some(0.5), ..Default::default() }, + SashDef { kind: SashDefKind::Pfosten, post_width: Some(0.1), ..Default::default() }, + SashDef { kind: SashDefKind::Fluegel, ..Default::default() }, + ]), + ..Default::default() + }]); + let o = Opening { wing_count: Some(2.0), ..opening(ElementKind::Window, Some("wt")) }; + let x = fill_params(&p, &o); + assert_eq!((x.frame_depth, x.frame_width, x.inset, x.inset_outside, x.wing_count, x.panes), (Some(0.1), Some(0.09), Some(0.05), false, 2.0, 3.0)); + assert_eq!( + x.sashes, + vec![ + FillSash { post: false, post_width: None, fixed: true, width: Some(0.5) }, + FillSash { post: true, post_width: Some(0.1), fixed: false, width: None }, + FillSash { post: false, post_width: None, fixed: false, width: None }, + ] + ); + // Ohne Typ: nichts vom Typ, zwei Scheiben, ein Flügel. + let x = fill_params(&p, &opening(ElementKind::Window, None)); + assert_eq!((x.frame_depth, x.inset_outside, x.wing_count, x.panes, x.sashes.len()), (None, true, 1.0, 2.0, 0)); + } + + #[test] + fn tuer_parameter() { + let mut p = Project::default(); + let dt = |kind| DoorType { id: "dt".into(), kind, leaf_count: 2.0, leaf_style: DoorTypeLeafStyle::Glas, glazing_ratio: Some(0.36), transom_height: Some(0.4), ..Default::default() }; + p.door_types = Some(vec![dt(DoorTypeKind::Schiebe)]); + let o = Opening { hinge: Some(OpeningHinge::End), swing: Some(SwingSide::Right), opening_dir: Some(OpeningOpeningDir::Out), ..opening(ElementKind::Door, Some("dt")) }; + let x = fill_params(&p, &o); + assert_eq!((x.door_kind, x.leaf_count, x.swing_sign, x.dir_sign, x.hinge_at_start, x.transom_height, x.glazed, x.glazing_ratio), (1.0, 2.0, -1.0, -1.0, false, 0.4, true, Some(0.36))); + let x = fill_params(&p, &opening(ElementKind::Door, None)); + assert_eq!((x.door_kind, x.leaf_count, x.swing_sign, x.dir_sign, x.hinge_at_start, x.transom_height, x.glazed), (0.0, 1.0, 1.0, 1.0, true, 0.0, false)); + let wo = Opening { door_type: Some(OpeningDoorType::Wandoeffnung), ..opening(ElementKind::Door, None) }; + assert_eq!(fill_params(&p, &wo).door_kind, 2.0); + p.door_types = Some(vec![dt(DoorTypeKind::Wandoeffnung)]); + assert_eq!(fill_params(&p, &opening(ElementKind::Door, Some("dt"))).door_kind, 2.0); + } + + #[test] + fn klassifikation_ebkph_und_ebenen() { + assert_eq!(ebkph_group(Kind::Wall), Some(("C", "Konstruktion Gebäude"))); + for k in [Kind::Slab, Kind::Column, Kind::Stair] { + assert_eq!(ebkph_group(k).map(|g| g.0), Some("C")); + } + assert_eq!(ebkph_group(Kind::Roof), Some(("F", "Bedachung Gebäude"))); + assert_eq!(ebkph_group(Kind::Window), Some(("E", "Äussere Wandbekleidung Gebäude"))); + assert_eq!(ebkph_group(Kind::Door), None); + assert_eq!(ebkph_group(Kind::Space), None); + let p = sample(); + assert_eq!(layer_classification(&p, "20").map(|x| x.0), Some("20".to_string())); + assert_eq!(layer_classification(&p, "25").map(|x| x.1), Some("Stützen".to_string())); + assert_eq!(layer_classification(&p, "777"), Some(("777".to_string(), "777".to_string()))); + assert_eq!(layer_classification(&p, ""), None); + assert_eq!(layer_classification(&p, " "), None); + } +} diff --git a/src-tauri/core/src/ifc_quantities.rs b/src-tauri/core/src/ifc_quantities.rs new file mode 100644 index 00000000..e968706b --- /dev/null +++ b/src-tauri/core/src/ifc_quantities.rs @@ -0,0 +1,371 @@ +//! Basismengen (Qto_*BaseQuantities) für den IFC-Export ([B5], [K4]; Port von +//! `src/export/ifcQuantities.ts`): Längen, Flächen und Volumen aus derselben Geometrie, die in die +//! Datei geschrieben wird — für Kostenplanung (eBKP-H/BKP) und Mengenermittlung. Reine Rechnung auf +//! einfachen Eingaben (Bänder, Ringe, Netze); `ifc_data.rs` sammelt, `fileio` schreibt die +//! IfcElementQuantity. Rechenreihenfolge und Zahlsemantik wie in TS (`Math.hypot/min/max`). +//! +//! Netto = abzüglich Öffnungen (Wand, Decke). Fehlt einer Menge die Grundlage (z. B. Höhe bei +//! schräger Wandoberkante: „nur angeben, wenn konstant"), fällt sie weg statt geraten zu werden. + +use crate::jsmath::{hypot, hypot2}; +use crate::jsnum::{max, min}; +use crate::model::Vec2; +use crate::model3d::RWall; + +/// Art einer Menge (Code in der flachen Kodierung: 3 Länge, 4 Fläche, 5 Volumen). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum QtyKind { + Length, + Area, + Volume, +} + +/// Eine Menge: Name nach IFC4-Vorlage, Art und Wert (immer endlich und ≥ 0, ausser nachträglich gesetzt). +#[derive(Debug, Clone, PartialEq)] +pub struct Qty { + pub name: &'static str, + pub kind: QtyKind, + pub value: f64, +} + +/// Rundungsfehler und kaputte Eingaben (NaN) auf 0, nie negativ. +fn clean(v: f64) -> f64 { + if v.is_finite() && v > 0.0 { + v + } else { + 0.0 + } +} + +fn q(name: &'static str, kind: QtyKind, value: f64) -> Qty { + Qty { name, kind, value: clean(value) } +} +fn len(name: &'static str, v: f64) -> Qty { + q(name, QtyKind::Length, v) +} +fn area(name: &'static str, v: f64) -> Qty { + q(name, QtyKind::Area, v) +} +fn vol(name: &'static str, v: f64) -> Qty { + q(name, QtyKind::Volume, v) +} + +/// Fläche eines Rings (Shoelace, unabhängig vom Umlaufsinn); offener Ring. +pub fn ring_area(pts: &[Vec2]) -> f64 { + let mut a = 0.0; + let n = pts.len(); + for i in 0..n { + let j = if i == 0 { n - 1 } else { i - 1 }; + a += pts[j].x * pts[i].y - pts[i].x * pts[j].y; + } + a.abs() / 2.0 +} + +/// Umfang eines geschlossenen Rings. +pub fn ring_perimeter(pts: &[Vec2]) -> f64 { + let mut p = 0.0; + let n = pts.len(); + for i in 0..n { + let j = if i == 0 { n - 1 } else { i - 1 }; + p += hypot2(pts[i].x - pts[j].x, pts[i].y - pts[j].y); + } + p +} + +/// Öffnung einer Wand: Achs-Intervall (ab Wandanfang) und absolute Höhen. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Cutout { + pub from: f64, + pub to: f64, + pub z_bottom: f64, + pub z_top: f64, +} + +fn overlap(a0: f64, a1: f64, b0: f64, b1: f64) -> f64 { + max(0.0, min(a1, b1) - max(a0, b0)) +} + +fn sloped_band(b: &RWall) -> bool { + b.top_drop.is_some_and(|d| d[0].abs() > 1e-9 || d[1].abs() > 1e-9) +} + +/// Wand-Basismengen aus den Schicht-Bändern (dieselben wie im 3D) und den Öffnungen. +/// • Length: Achslänge; Width: Gesamtdicke quer zur Achse; Height: nur bei konstanter Höhe. +/// • GrossSideArea: Achslänge × Wandhöhe (schräge Oberkante: höchste mittlere Bandhöhe); +/// NetSideArea: abzüglich der Öffnungsflächen. +/// • GrossVolume: Summe der Band-Quader; NetVolume: abzüglich der Öffnungen je Band — oder +/// `net_volume`, wenn die Wand als Netz mit schon ausgestanzten Öffnungen geschrieben wird. +pub fn wall_quantities(start: Vec2, end: Vec2, bands: &[&RWall], cutouts: &[Cutout], net_volume: Option) -> Vec { + if bands.is_empty() { + return Vec::new(); + } + let axis_len = hypot2(end.x - start.x, end.y - start.y); + let ux = if axis_len > 0.0 { (end.x - start.x) / axis_len } else { 1.0 }; + let uy = if axis_len > 0.0 { (end.y - start.y) / axis_len } else { 0.0 }; + let (mut n_lo, mut n_hi) = (f64::INFINITY, f64::NEG_INFINITY); + let (mut z_min, mut z_max) = (f64::INFINITY, f64::NEG_INFINITY); + let mut sloped = false; + let mut gross = 0.0; + let mut tallest = 0.0; + for b in bands { + let l = hypot2(b.end[0] - b.start[0], b.end[1] - b.start[1]); + let off = -(b.start[0] - start.x) * uy + (b.start[1] - start.y) * ux; + n_lo = min(n_lo, off - b.thickness / 2.0); + n_hi = max(n_hi, off + b.thickness / 2.0); + z_min = min(z_min, b.base_elevation); + z_max = max(z_max, b.base_elevation + b.height); + let drop = b.top_drop.map_or(0.0, |d| (d[0] + d[1]) / 2.0); + if sloped_band(b) { + sloped = true; + } + gross += l * b.thickness * (b.height - drop); + tallest = max(tallest, b.height - drop); + } + let gross_side = axis_len * (if sloped { tallest } else { z_max - z_min }); + let mut cut_side = 0.0; + let mut cut_volume = 0.0; + for c in cutouts { + cut_side += (c.to - c.from) * overlap(c.z_bottom, c.z_top, z_min, z_max); + for b in bands { + let a0 = (b.start[0] - start.x) * ux + (b.start[1] - start.y) * uy; + let a1 = (b.end[0] - start.x) * ux + (b.end[1] - start.y) * uy; + let ox = overlap(min(a0, a1), max(a0, a1), c.from, c.to); + cut_volume += ox * overlap(c.z_bottom, c.z_top, b.base_elevation, b.base_elevation + b.height) * b.thickness; + } + } + // Netto aus dem Netz kann den Band-Quader um Rundung/Gehrungsdetails überschreiten: Brutto nie unter Netto. + let net = net_volume.unwrap_or_else(|| max(0.0, gross - cut_volume)); + gross = max(gross, net); + let mut out = vec![len("Length", axis_len), len("Width", n_hi - n_lo)]; + if !sloped && z_max - z_min > 0.0 { + out.push(len("Height", z_max - z_min)); + } + out.extend([ + area("GrossSideArea", gross_side), + area("NetSideArea", max(0.0, gross_side - cut_side)), + vol("GrossVolume", gross), + vol("NetVolume", net), + ]); + out +} + +/// Brutto-Volumen der Löcher in den Bändern (für Netz-Wände ohne dichtes Netz). +pub fn hole_volume(bands: &[&RWall]) -> f64 { + let mut v = 0.0; + for b in bands { + for h in b.holes.as_deref().unwrap_or(&[]) { + v += (h.to - h.from) * overlap(h.z_bottom, h.z_top, b.base_elevation, b.base_elevation + b.height) * b.thickness; + } + } + v +} + +/// Platten-Basismengen (Decke, Podest): Dicke, Umfang der Aussenkontur, Flächen und Volumen; Netto +/// zieht die Aussparungen ab. +pub fn slab_quantities(outline: &[Vec2], openings: &[&[Vec2]], thickness: f64) -> Vec { + let gross = ring_area(outline); + let mut holes = 0.0; + for r in openings { + holes += ring_area(r); + } + let net = max(0.0, gross - holes); + vec![ + len("Width", thickness), + len("Perimeter", ring_perimeter(outline)), + area("GrossArea", gross), + area("NetArea", net), + vol("GrossVolume", gross * thickness), + vol("NetVolume", net * thickness), + ] +} + +/// Dach-Basismengen aus den geneigten Dachflächen (Aussenseite): geneigte Fläche (brutto = netto) +/// und Grundrissprojektion (Newell: Vektorfläche je Polygon). +pub fn roof_quantities(planes: &[Vec<[f64; 3]>]) -> Vec { + let mut sloped = 0.0; + let mut projected = 0.0; + for pts in planes { + let (mut nx, mut ny, mut nz) = (0.0, 0.0, 0.0); + let n = pts.len(); + for i in 0..n { + let c = pts[if i == 0 { n - 1 } else { i - 1 }]; + let d = pts[i]; + nx += (c[1] - d[1]) * (c[2] + d[2]); + ny += (c[2] - d[2]) * (c[0] + d[0]); + nz += (c[0] - d[0]) * (c[1] + d[1]); + } + sloped += hypot(&[nx, ny, nz]) / 2.0; + projected += nz.abs() / 2.0; + } + vec![area("GrossArea", sloped), area("NetArea", sloped), area("ProjectedArea", projected)] +} + +/// Stützen-Basismengen: Länge, Querschnitt, Mantel, Oberfläche und Volumen. +pub fn column_quantities(footprint: &[Vec2], length: f64) -> Vec { + let cross = ring_area(footprint); + let outer = ring_perimeter(footprint) * length; + vec![ + len("Length", length), + area("CrossSectionArea", cross), + area("OuterSurfaceArea", outer), + area("NetSurfaceArea", outer + 2.0 * cross), + vol("GrossVolume", cross * length), + vol("NetVolume", cross * length), + ] +} + +/// Tür-/Fenster-Basismengen (lichte Öffnung): Breite, Höhe, Umfang, Fläche. +pub fn opening_quantities(width: f64, height: f64) -> Vec { + let w = clean(width); + let h = clean(height); + vec![len("Width", w), len("Height", h), len("Perimeter", 2.0 * (w + h)), area("Area", w * h)] +} + +/// Treppenlauf: Lauflänge entlang der Lauflinie und Volumen. +pub fn flight_quantities(length: f64, volume: f64) -> Vec { + vec![len("Length", length), vol("GrossVolume", volume), vol("NetVolume", volume)] +} + +/// Geländer: Länge. +pub fn railing_quantities(length: f64) -> Vec { + vec![len("Length", length)] +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model3d::RHole; + + fn v(x: f64, y: f64) -> Vec2 { + Vec2 { x, y } + } + + fn band(start: [f64; 2], end: [f64; 2], thickness: f64, base: f64, height: f64) -> RWall { + RWall { + start, + end, + thickness, + height, + base_elevation: base, + top_drop: None, + color: [0.5, 0.5, 0.5], + layers: vec![], + wall_id: "w".into(), + holes: None, + hatch: None, + material_index: None, + cut: None, + } + } + + fn get(q: &[Qty], name: &str) -> Option { + q.iter().find(|x| x.name == name).map(|x| x.value) + } + + fn close(a: Option, b: f64) -> bool { + a.is_some_and(|a| (a - b).abs() < 1e-9) + } + + #[test] + fn ringe() { + let r = [v(0.0, 0.0), v(4.0, 0.0), v(4.0, 3.0), v(0.0, 3.0)]; + assert_eq!(ring_area(&r), 12.0); + assert_eq!(ring_perimeter(&r), 14.0); + let mut rev = r.to_vec(); + rev.reverse(); + assert_eq!(ring_area(&rev), 12.0); + assert_eq!(ring_area(&[]), 0.0); + } + + #[test] + fn wand_sonderfaelle() { + let (s, e) = (v(0.0, 0.0), v(5.0, 0.0)); + // Innere Schicht endet unter der Decke: Seitenfläche mit voller Wandhöhe, Volumen je Schicht. + let outer = band([0.0, 0.0], [5.0, 0.0], 0.2, 0.0, 2.6); + let inner = band([0.1, 0.0], [4.9, 0.0], 0.1, 0.0, 2.3); + let q = wall_quantities(s, e, &[&outer, &inner], &[], None); + assert!(close(get(&q, "Height"), 2.6) && close(get(&q, "GrossSideArea"), 13.0)); + assert!(close(get(&q, "GrossVolume"), 5.0 * 0.2 * 2.6 + 4.8 * 0.1 * 2.3)); + // Gehrung/Anschluss: kürzeres Band ändert das Volumen, nicht die Wandlänge. + let q = wall_quantities(s, e, &[&inner], &[], None); + assert_eq!(get(&q, "Length"), Some(5.0)); + assert_eq!(get(&q, "NetVolume"), get(&q, "GrossVolume")); + // Öffnung grösser als die Wand: netto nie negativ; Öffnung ausserhalb zieht nichts ab. + let big = [Cutout { from: -1.0, to: 6.0, z_bottom: -1.0, z_top: 5.0 }, Cutout { from: 8.0, to: 9.0, z_bottom: 0.0, z_top: 2.0 }]; + let q = wall_quantities(s, e, &[&outer], &big, None); + assert_eq!(get(&q, "NetSideArea"), Some(0.0)); + assert!(close(get(&q, "NetVolume"), 0.0)); + // Netz-Wand: Netto aus dem Netz, Brutto bleibt der Quader. + let q = wall_quantities(s, e, &[&outer], &[], Some(1.5)); + assert_eq!(get(&q, "NetVolume"), Some(1.5)); + assert!(close(get(&q, "GrossVolume"), 13.0 * 0.2)); + assert!(wall_quantities(s, e, &[], &[], None).is_empty()); + } + + #[test] + fn satteldach_30_grad() { + let h = (std::f64::consts::PI / 6.0).tan() * 2.0; + let planes = vec![vec![[0.0, 0.0, 0.0], [5.0, 0.0, 0.0], [5.0, 2.0, h], [0.0, 2.0, h]], vec![[0.0, 4.0, 0.0], [0.0, 2.0, h], [5.0, 2.0, h], [5.0, 4.0, 0.0]]]; + let q = roof_quantities(&planes); + assert!((get(&q, "ProjectedArea").unwrap() - 20.0).abs() < 1e-9); + assert!((get(&q, "GrossArea").unwrap() - 20.0 / (std::f64::consts::PI / 6.0).cos()).abs() < 1e-9); + assert_eq!(get(&q, "NetArea"), get(&q, "GrossArea")); + } + + #[test] + fn wand_brutto_netto() { + // Wand 5 m, zwei Schichten (0.2 + 0.1) übereinander-bündig, 2.6 m hoch, eine Öffnung 1×1.2 m. + let b1 = band([0.0, -0.05], [5.0, -0.05], 0.2, 0.0, 2.6); + let b2 = band([0.0, 0.1], [5.0, 0.1], 0.1, 0.0, 2.5); + let cut = Cutout { from: 1.0, to: 2.0, z_bottom: 0.9, z_top: 2.1 }; + let q = wall_quantities(v(0.0, 0.0), v(5.0, 0.0), &[&b1, &b2], &[cut], None); + assert!(close(get(&q, "Length"), 5.0)); + assert!(close(get(&q, "Width"), 0.3)); + assert!(close(get(&q, "Height"), 2.6)); + assert!(close(get(&q, "GrossSideArea"), 13.0)); + assert!(close(get(&q, "NetSideArea"), 13.0 - 1.2)); + let gross = 5.0 * 0.2 * 2.6 + 5.0 * 0.1 * 2.5; + assert!(close(get(&q, "GrossVolume"), gross)); + assert!(close(get(&q, "NetVolume"), gross - 1.2 * 0.3)); + // Netz-Volumen übersteuert, Brutto nie darunter. + let q = wall_quantities(v(0.0, 0.0), v(5.0, 0.0), &[&b1], &[], Some(99.0)); + assert!(close(get(&q, "NetVolume"), 99.0) && close(get(&q, "GrossVolume"), 99.0)); + } + + #[test] + fn schraege_wand_ohne_hoehe() { + let mut b = band([0.0, 0.0], [4.0, 0.0], 0.3, 0.0, 3.0); + b.top_drop = Some([0.0, 1.0]); + let q = wall_quantities(v(0.0, 0.0), v(4.0, 0.0), &[&b], &[], None); + assert!(get(&q, "Height").is_none()); + assert!(close(get(&q, "GrossSideArea"), 4.0 * 2.5)); + assert!(close(get(&q, "GrossVolume"), 4.0 * 0.3 * 2.5)); + } + + #[test] + fn loch_volumen() { + let mut b = band([0.0, 0.0], [4.0, 0.0], 0.3, 0.0, 2.5); + b.holes = Some(vec![RHole { from: 1.0, to: 2.0, z_bottom: 2.0, z_top: 3.0 }]); + assert!((hole_volume(&[&b]) - 0.5 * 0.3).abs() < 1e-12); + } + + #[test] + fn platte_dach_stuetze_oeffnung() { + let outline = [v(0.0, 0.0), v(10.0, 0.0), v(10.0, 5.0), v(0.0, 5.0)]; + let hole = [v(1.0, 1.0), v(2.0, 1.0), v(2.0, 2.0), v(1.0, 2.0)]; + let q = slab_quantities(&outline, &[&hole], 0.2); + assert!(close(get(&q, "NetArea"), 49.0) && close(get(&q, "Perimeter"), 30.0) && close(get(&q, "GrossVolume"), 10.0)); + // Satteldach-Hälfte: 10 × 5 m Grundriss, 3 m hoch. + let plane = vec![[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [10.0, 5.0, 3.0], [0.0, 5.0, 3.0]]; + let q = roof_quantities(&[plane]); + assert!(close(get(&q, "ProjectedArea"), 50.0)); + assert!(close(get(&q, "GrossArea"), 10.0 * 34f64.sqrt())); + let q = column_quantities(&[v(0.0, 0.0), v(0.3, 0.0), v(0.3, 0.3), v(0.0, 0.3)], 2.5); + assert!(close(get(&q, "NetVolume"), 0.225)); + let q = opening_quantities(f64::NAN, 2.0); + assert_eq!(get(&q, "Width"), Some(0.0)); + assert!(close(get(&q, "Perimeter"), 4.0)); + assert_eq!(flight_quantities(-1.0, 2.0)[0].value, 0.0); + assert_eq!(railing_quantities(3.0)[0].value, 3.0); + } +} diff --git a/src-tauri/core/src/ifc_stairs.rs b/src-tauri/core/src/ifc_stairs.rs new file mode 100644 index 00000000..dd977855 --- /dev/null +++ b/src-tauri/core/src/ifc_stairs.rs @@ -0,0 +1,299 @@ +//! Treppen im IFC-Export ([B5], [K4]; Port von `src/export/ifcStairs.ts`): statt eines +//! Fussabdruck-Quaders die Teile der Treppe wie im 3D — Läufe (IfcStairFlight), Podest (IfcSlab +//! LANDING) und Handlauf/Pfosten (IfcRailing), zusammengefasst von der IfcStair. Quelle sind +//! dieselben Ableitungen wie im 3D (`emit_stairs` Tritt-Prismen und Podest, `emit_stair_meshes` +//! glatte Ortbeton-Laufplatte, `emit_stair_railings`), je Treppe mit einem Projekt aufgerufen, das +//! nur diese Treppe enthält (die Ableitungen liefern keine ids). Hier: Zuordnung und Basismengen; +//! die Entitäten schreibt `fileio` (`ifc_export.rs`, STAIR). +//! +//! Zuordnung der Tritt-Prismen: bei "L" ist das Podest das Prisma mit dem Umriss des Podest-Polygons +//! der Treppengeometrie; Tritte bis zur Podest-Oberkante gehören zum ersten, die darüber zum +//! zweiten Lauf. Gerade und Wendeltreppen haben einen Lauf (die Wendel-Mitte bleibt Teil davon). + +use crate::export_flat::{js_key, mesh_volume, orient_outward}; +use crate::ifc_quantities::{flight_quantities, railing_quantities, ring_area, slab_quantities, Qty}; +use crate::jsmath::hypot2; +use crate::jsnum::round; +use crate::model::*; +use crate::model3d::{self, RMesh, RSlab}; + +/// Ein Prisma (Profil in Welt-XY, Unterkante relativ zum Geschoss, Tiefe). +#[derive(Debug, Clone, PartialEq)] +pub struct StairSolid { + pub pts: Vec, + pub z_rel: f64, + pub depth: f64, +} + +/// Ein Netz (IFC: x, y, z-hoch, Z relativ zum Geschoss). +#[derive(Debug, Clone, PartialEq)] +pub struct IfcMesh { + pub positions: Vec, + pub indices: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum FlightBody { + Solids(Vec), + Mesh(IfcMesh), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct StairFlightParts { + pub name: String, + pub risers: f64, + pub treads: f64, + pub riser_height: f64, + pub tread_length: f64, + /// IfcStairFlightTypeEnum. + pub predefined: &'static str, + pub quantities: Vec, + pub body: FlightBody, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Landing { + pub pts: Vec, + pub z_rel: f64, + pub depth: f64, + pub quantities: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Rail { + pub mesh: IfcMesh, + pub quantities: Vec, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct StairParts { + pub flights: Vec, + pub landing: Option, + pub rail: Option, +} + +const EPS: f64 = 1e-6; + +/// Gleicher Umriss (gleiche Punktmenge, auch bei anderer Reihenfolge/Startpunkt). +fn same_ring(a: &[[f64; 2]], b: &[kernel2d::Vec2]) -> bool { + a.len() == b.len() && a.iter().all(|p| b.iter().any(|q| (p[0] - q.x).abs() < EPS && (p[1] - q.y).abs() < EPS)) +} + +fn centroid(pts: &[Vec2]) -> Vec2 { + let (mut x, mut y) = (0.0, 0.0); + for p in pts { + x += p.x; + } + for p in pts { + y += p.y; + } + Vec2 { x: x / pts.len() as f64, y: y / pts.len() as f64 } +} + +/// Netze aneinanderhängen (Indizes verschoben). +fn concat(meshes: &[RMesh]) -> (Vec, Vec) { + let (mut positions, mut indices) = (Vec::new(), Vec::new()); + for m in meshes { + let at = (positions.len() / 3) as u32; + positions.extend_from_slice(&m.positions); + indices.extend(m.indices.iter().map(|i| at + i)); + } + (positions, indices) +} + +/// Netz (Modell x, y, z-hoch) nach IFC: Z relativ zum Geschoss, Wicklung nach aussen. +fn ifc_mesh(mut positions: Vec, indices: &[u32], base: f64) -> IfcMesh { + let mut i = 2; + while i < positions.len() { + positions[i] -= base; + i += 3; + } + let indices = orient_outward(&positions, indices); + IfcMesh { positions, indices } +} + +fn solid_of(s: &RSlab, base: f64) -> StairSolid { + StairSolid { pts: s.outline.iter().map(|p| Vec2 { x: p[0], y: p[1] }).collect(), z_rel: s.z_bottom - base, depth: s.z_top - s.z_bottom } +} + +/// Teile einer Treppe für den IFC-Export. `one` = Projekt, das NUR diese Treppe enthält (sonst wie +/// das ganze Projekt), `base` = Geschoss-UK, auf die Z-Werte bezogen werden. Leere Teile ergeben +/// `flights: []`, `landing: None`, `rail: None`. +pub fn stair_parts(one: &Project, stair: &Stair, base: f64) -> StairParts { + let (z_bottom, z_top) = one.stair_vertical_extent(stair); + let rise = z_top - z_bottom; + let geo = crate::stair::decode_geometry(&crate::stair::geometry(&stair.encode(), rise)); + let (riser_height, tread_depth, n_treads) = geo.as_ref().map_or((0.0, 0.0, 0), |g| (g.riser_height, g.tread_depth, g.treads.len())); + let geo_landing = geo.as_ref().and_then(|g| g.landing.as_ref()); + let slabs = model3d::emit_stairs(one, false); + let meshes = model3d::emit_stair_meshes(one); + let predefined = if stair.shape == StairShape::Spiral { "SPIRAL" } else { "STRAIGHT" }; + + // Podest nur bei "L" (bei der Wendel ist das Polygon die Treppenmitte, Teil des Laufs). + let landing_idx = match (stair.shape, geo_landing) { + (StairShape::L, Some(l)) => slabs.iter().position(|s| same_ring(&s.outline, l)), + _ => None, + }; + let tread_slabs: Vec<&RSlab> = slabs.iter().enumerate().filter(|(i, _)| Some(*i) != landing_idx).map(|(_, s)| s).collect(); + + let mut groups: Vec> = Vec::new(); + if let Some(li) = landing_idx { + let top = slabs[li].z_top + EPS; + let lower: Vec<&RSlab> = tread_slabs.iter().copied().filter(|s| s.z_top <= top).collect(); + let upper: Vec<&RSlab> = tread_slabs.iter().copied().filter(|s| s.z_top > top).collect(); + for g in [lower, upper] { + if !g.is_empty() { + groups.push(g); + } + } + } else if !tread_slabs.is_empty() { + groups.push(tread_slabs); + } + + let mut flights: Vec = Vec::new(); + let n_groups = groups.len(); + for (k, g) in groups.iter().enumerate() { + // Tritte = verschiedene Oberkanten (Setzstufen-Platten und Nasen teilen die Höhe ihres Tritts). + let mut tops: Vec = Vec::new(); + for s in g { + let key = js_key(round(s.z_top / 1e-4)); + if !tops.contains(&key) { + tops.push(key); + } + } + let treads = tops.len() as f64; + // Lauflänge: Weg zwischen erstem und letztem Tritt (Schwerpunkte) plus eine Trittiefe, mit der Steigung. + let mut lowest = g[0]; + let mut highest = g[0]; + for s in g { + if s.z_top < lowest.z_top { + lowest = s; + } + if s.z_top > highest.z_top { + highest = s; + } + } + let c0 = centroid(&solid_of(lowest, base).pts); + let c1 = centroid(&solid_of(highest, base).pts); + let run = hypot2(c1.x - c0.x, c1.y - c0.y) + tread_depth; + let lift = highest.z_top - lowest.z_top + riser_height; + let solids: Vec = g.iter().map(|s| solid_of(s, base)).collect(); + let mut volume = 0.0; + for x in g { + let pts: Vec = x.outline.iter().map(|p| Vec2 { x: p[0], y: p[1] }).collect(); + volume += ring_area(&pts) * (x.z_top - x.z_bottom); + } + flights.push(StairFlightParts { + name: if n_groups > 1 { format!("Lauf {}", k + 1) } else { "Lauf".to_string() }, + risers: treads, + treads, + riser_height, + tread_length: tread_depth, + predefined, + quantities: flight_quantities(hypot2(run, lift), volume), + body: FlightBody::Solids(solids), + }); + } + // Glatte Ortbeton-Laufplatte (gerade Betontreppe): ein Lauf als Netz. + if !meshes.is_empty() { + let (positions, indices) = concat(&meshes); + let mesh = ifc_mesh(positions, &indices, base); + let volume = mesh_volume(&mesh.positions, &mesh.indices); + flights.push(StairFlightParts { + name: if flights.is_empty() { "Lauf".to_string() } else { format!("Lauf {}", flights.len() + 1) }, + risers: n_treads as f64, + treads: n_treads as f64, + riser_height, + tread_length: tread_depth, + predefined, + quantities: flight_quantities(hypot2(stair.run_length, rise), volume), + body: FlightBody::Mesh(mesh), + }); + } + + let landing = landing_idx.map(|li| { + let s = solid_of(&slabs[li], base); + let quantities = slab_quantities(&s.pts, &[], s.depth); + Landing { pts: s.pts, z_rel: s.z_rel, depth: s.depth, quantities } + }); + + let rail_meshes = model3d::emit_stair_railings(one); + let rail = (!rail_meshes.is_empty()).then(|| { + let (positions, indices) = concat(&rail_meshes); + let sides = if one.stair_type(stair).and_then(|t| t.railing) == Some(StairTypeRailing::Beide) { 2.0 } else { 1.0 }; + Rail { mesh: ifc_mesh(positions, &indices, base), quantities: railing_quantities(hypot2(stair.run_length, rise) * sides) } + }); + StairParts { flights, landing, rail } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn project_with(stair: Stair, ty: Option) -> Project { + let mut p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap(); + if let Some(t) = ty { + p.stair_types.get_or_insert_with(Vec::new).push(t); + } + p.stairs = Some(vec![stair]); + p + } + + fn stair(shape: StairShape, type_id: Option<&str>) -> Stair { + Stair { + id: "S".into(), + floor_id: "eg".into(), + shape, + start: Vec2 { x: 0.0, y: 0.0 }, + dir: Vec2 { x: 1.0, y: 0.0 }, + run_length: 3.0, + run2_length: (shape == StairShape::L).then_some(2.0), + turn: (shape == StairShape::L).then_some(1.0), + width: 1.0, + total_rise: Some(2.6), + step_count: 15.0, + type_id: type_id.map(String::from), + ..Default::default() + } + } + + #[test] + fn gerade_massivtreppe_ein_lauf() { + let st = stair(StairShape::Straight, None); + let p = project_with(st.clone(), None); + let parts = stair_parts(&p, &st, 0.0); + assert_eq!(parts.flights.len(), 1); + let f = &parts.flights[0]; + assert_eq!(f.name, "Lauf"); + assert!(f.treads > 0.0 && f.riser_height > 0.0); + assert!(matches!(&f.body, FlightBody::Solids(s) if !s.is_empty())); + assert!(parts.landing.is_none() && parts.rail.is_none()); + } + + #[test] + fn l_treppe_zwei_laeufe_und_podest() { + let st = stair(StairShape::L, None); + let p = project_with(st.clone(), None); + let parts = stair_parts(&p, &st, 0.0); + assert_eq!(parts.flights.iter().map(|f| f.name.as_str()).collect::>(), ["Lauf 1", "Lauf 2"]); + let l = parts.landing.expect("Podest"); + assert!(l.depth > 0.0 && l.quantities.iter().any(|q| q.name == "NetArea" && q.value > 0.0)); + } + + #[test] + fn betontreppe_mit_handlauf_beidseitig() { + let ty = StairType { id: "beton2".into(), structure: StairTypeStructure::Beton, closed_risers: true, tread_thickness: 0.05, railing: Some(StairTypeRailing::Beide), default_width: 1.0, ..Default::default() }; + let st = stair(StairShape::Straight, Some("beton2")); + let p = project_with(st.clone(), Some(ty)); + let parts = stair_parts(&p, &st, 0.5); + let m = parts.flights.iter().find_map(|f| match &f.body { + FlightBody::Mesh(m) => Some(m), + _ => None, + }); + let m = m.expect("Laufplatte als Netz"); + assert!(mesh_volume(&m.positions, &m.indices) > 0.0); + let rail = parts.rail.expect("Handlauf"); + let len = rail.quantities[0].value; + assert!((len - 2.0 * hypot2(3.0, 2.6)).abs() < 1e-9); + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 86366c92..7914c94d 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -65,6 +65,12 @@ pub mod snap; pub mod plan_svg; pub mod plan_dxf; pub mod plan_print_svg; +pub mod export_flat; +pub mod geo_rebase; +pub mod ifc_quantities; +pub mod ifc_stairs; +pub mod ifc_data; +pub mod mesh_data; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/mesh_data.rs b/src-tauri/core/src/mesh_data.rs new file mode 100644 index 00000000..229d1354 --- /dev/null +++ b/src-tauri/core/src/mesh_data.rs @@ -0,0 +1,525 @@ +//! OBJ-/STL-/glTF-Export: Sammler im Kern ([K4] S2, [C11]; vorher `buildScene` in +//! `src/export/exportMesh.ts`). Liest das Projekt-Dokument und erzeugt die Szene als flachen Puffer +//! für den Schreiber `src-tauri/fileio/src/mesh_export.rs` (Kodierung dort, FLAT_VERSION 1): ein +//! Knoten je Bauteil-Vorkommen mit Teil-Netzen je Material, Materialtabelle, Geschosse. +//! +//! Dreiecks-Quelle wie im 3D-Viewer: +//! • Wände: Schicht-Bänder (`emit_walls`), gelochte Bänder öffnungsgenau (`wall_cut_mesh`, inkl. +//! Laibungen), lochlose als 8-Ecken-Box. +//! • Decken und Extrusionen: Umriss-Prisma (Ear-Clipping-Kappen + Mantel); Extrusionen mit `taper` +//! (oberer Ring zum Schwerpunkt verjüngt) — bewusst die Prisma-Näherung, nicht die truck-Körper. +//! • Dächer, Stützen, Treppen (Tritte, Laufplatte, Handlauf), Öffnungsteile (je Öffnung ein +//! Knoten): dieselben `emit_*`-Ableitungen wie das 3D, je Bauteil mit einem Projekt aufgerufen, +//! das nur dieses Bauteil enthält (die Ableitungen liefern keine ids). +//! • Gelände und importierte Meshes (Farbe der Quelle, falls gesetzt). +//! Achsen intern Modell (x, y, z-hoch) → Welt (x, z, y); der Schreiber stellt die Rechtshändigkeit +//! her (Datei (x, z, −y), Norden = −Z). Geschlossene Teile werden nach aussen gewickelt +//! (`orient_outward`), da render3d doppelseitig zeichnet. Zahlsemantik und Reihenfolge wie die +//! frühere TS-Fassung: die Dateien bleiben zeichengleich. + +use crate::export_flat::{orient_outward, Flat}; +use crate::jsmath::hypot2; +use crate::jsnum::{max, min}; +use crate::model::*; +use crate::model3d::{self, RMesh, RWall}; +use crate::style::{hex_to_rgb, Rgb}; +use crate::wall_mesh_cut::{wall_cut_mesh_checked, CutWall}; +use std::collections::HashMap; + +const FLAT_VERSION: f64 = 1.0; + +/// Was in die Szene kommt (Standard: alles). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct MeshOptions { + /// Verglasung und Rahmenteile je Öffnung als eigener Knoten. + pub opening_parts: bool, + /// Gelände und importierte Kontext-Meshes. + pub context: bool, + /// Geschoss als Eltern-Knoten (nur glTF; OBJ/STL: aus). + pub by_level: bool, +} + +impl Default for MeshOptions { + fn default() -> Self { + MeshOptions { opening_parts: true, context: true, by_level: true } + } +} + +/// Teil-Netz mit EINEM Material, lokale Indizes. +struct Prim { + material: f64, + positions: Vec, + indices: Vec, +} + +/// Ein Bauteil-Vorkommen mit ≥ 1 Teil-Netz. +struct Group { + name: String, + kind: &'static str, + id: String, + level: f64, + prims: Vec, +} + +impl Group { + fn new(name: String, kind: &'static str, id: &str, level: f64) -> Self { + Group { name, kind, id: id.to_string(), level, prims: Vec::new() } + } + fn prim(&mut self, material: f64) -> &mut Prim { + self.prims.push(Prim { material, positions: Vec::new(), indices: Vec::new() }); + self.prims.last_mut().unwrap() + } +} + +/// Material der Szene: Farbe sRGB 0..1, Alpha < 1 = transparent (Glas). +struct Material { + name: String, + rgba: [f64; 4], + metallic: f64, + roughness: f64, +} + +/// Materialtabelle: gleiche Farbe + Name = ein Material (Schlüssel wie in TS als Text). +#[derive(Default)] +struct Materials { + list: Vec, + by_key: HashMap, +} + +impl Materials { + fn get(&mut self, name: &str, rgb: Rgb, alpha: f64, metallic: f64, roughness: f64) -> f64 { + use crate::js_fmt::js_number as n; + let key = format!("{name}|{},{},{}|{}|{}|{}", n(rgb[0]), n(rgb[1]), n(rgb[2]), n(alpha), n(metallic), n(roughness)); + if let Some(&i) = self.by_key.get(&key) { + return i as f64; + } + let i = self.list.len(); + self.list.push(Material { name: name.to_string(), rgba: [rgb[0], rgb[1], rgb[2], alpha], metallic, roughness }); + self.by_key.insert(key, i); + i as f64 + } + fn solid(&mut self, name: &str, rgb: Rgb) -> f64 { + self.get(name, rgb, 1.0, 0.0, 0.9) + } +} + +/// OBJ-Gruppennamen ohne Leerraum/Sonderzeichen (je UTF-16-Einheit ein `_`, wie das JS-RegExp). +fn sanitize_name(id: &str) -> String { + let mut out = String::new(); + for c in id.chars() { + if c.is_ascii_alphanumeric() || c == '_' || c == '-' { + out.push(c); + } else { + for _ in 0..c.len_utf16() { + out.push('_'); + } + } + } + if out.is_empty() { + "x".to_string() + } else { + out + } +} + +/// Die 6 Quader-Seiten (Bits: 0 Achse, 1 Höhe, 2 Dicke), aussen gewunden; je Quadrupel 2 Dreiecke. +const BOX_QUADS: [[usize; 4]; 6] = [[4, 6, 7, 5], [1, 3, 2, 0], [2, 3, 7, 6], [4, 5, 1, 0], [1, 5, 7, 3], [2, 6, 4, 0]]; + +/// Voller Wand-Schicht-Quader ohne Öffnungen (lochlose Bänder); entartete Bänder fallen weg. +fn push_wall_box(g: &mut Prim, w: &RWall) { + let [sx, sy] = w.start; + let [ex, ey] = w.end; + let dx = ex - sx; + let dz = ey - sy; + let len = hypot2(dx, dz); + if len < 1e-9 || w.height <= 1e-9 || w.thickness <= 1e-9 { + return; + } + let ax = dx / len; + let az = dz / len; + // Normale = Welt-Hoch × Achse: (az, 0, −ax). + let nx = az; + let nz = -ax; + let half_len = len / 2.0; + let half_height = w.height / 2.0; + let half_thick = w.thickness / 2.0; + let cx = (sx + ex) / 2.0; + let cz = (sy + ey) / 2.0; + let cy = w.base_elevation + w.height / 2.0; + let base = (g.positions.len() / 3) as f64; + for i in 0..8 { + let sl = if i & 1 != 0 { 1.0 } else { -1.0 }; + let sh = if i & 2 != 0 { 1.0 } else { -1.0 }; + let st = if i & 4 != 0 { 1.0 } else { -1.0 }; + g.positions.extend_from_slice(&[cx + sl * half_len * ax + st * half_thick * nx, cy + sh * half_height, cz + sl * half_len * az + st * half_thick * nz]); + } + for [a, b, c, d] in BOX_QUADS { + let (a, b, c, d) = (base + a as f64, base + b as f64, base + c as f64, base + d as f64); + g.indices.extend_from_slice(&[a, b, c, a, c, d]); + } +} + +/// Signierte Fläche eines Modell-XY-Umrisses (Shoelace); ≥ 0 = CCW. +fn signed_area_xy(pts: &[Vec2]) -> f64 { + let mut a = 0.0; + let n = pts.len(); + for i in 0..n { + let j = if i == 0 { n - 1 } else { i - 1 }; + a += pts[j].x * pts[i].y - pts[i].x * pts[j].y; + } + a / 2.0 +} + +/// Extrudiertes Umriss-Prisma (Decke, Treppen-Tritt, Extrusion): Kappen + Mantel, aussen gewunden; +/// `taper` (0..1) verjüngt den oberen Ring linear zum Schwerpunkt. +fn push_prism(g: &mut Prim, outline: &[Vec2], z_bottom: f64, z_top: f64, taper: f64) { + if outline.len() < 3 || z_top - z_bottom <= 1e-9 { + return; + } + let ccw: Vec = if signed_area_xy(outline) >= 0.0 { outline.to_vec() } else { outline.iter().rev().copied().collect() }; + let n = ccw.len(); + let (mut cx, mut cy) = (0.0, 0.0); + for p in &ccw { + cx += p.x; + cy += p.y; + } + cx /= n as f64; + cy /= n as f64; + let t = min(1.0, max(0.0, taper)); + let base = (g.positions.len() / 3) as f64; + for p in &ccw { + g.positions.extend_from_slice(&[p.x, z_bottom, p.y]); + } + for p in &ccw { + g.positions.extend_from_slice(&[cx + (p.x - cx) * (1.0 - t), z_top, cy + (p.y - cy) * (1.0 - t)]); + } + let nf = n as f64; + let cap = crate::gpu_compile::triangulate(&ccw.iter().map(|p| crate::hatch::v2(p.x, p.y)).collect::>()); + for tri in cap.chunks_exact(3) { + let (a, b, c) = (tri[0] as f64, tri[1] as f64, tri[2] as f64); + g.indices.extend_from_slice(&[base + a, base + b, base + c]); + g.indices.extend_from_slice(&[base + nf + a, base + nf + c, base + nf + b]); + } + for i in 0..n { + let j = (i + 1) % n; + let (bi, bj, ti, tj) = (base + i as f64, base + j as f64, base + nf + i as f64, base + nf + j as f64); + g.indices.extend_from_slice(&[bi, ti, tj, bi, tj, bj]); + } +} + +/// Modell-Netz (x, y, z-hoch) anhängen: Achsen nach Welt (x, z, y), Wicklung umgekehrt (Spiegelung); +/// `closed` ⇒ nach aussen gewickelt. Indizes ausserhalb und NaN fallen weg. +fn append_model_mesh(prim: &mut Prim, positions: &[f64], indices: &[f64], closed: bool) { + let mut pos: Vec = Vec::with_capacity(positions.len()); + let mut i = 0; + while i + 2 < positions.len() { + pos.extend_from_slice(&[positions[i], positions[i + 2], positions[i + 1]]); + i += 3; + } + let nv = (pos.len() / 3) as f64; + let ok = |v: f64| v >= 0.0 && v < nv; + let mut tri: Vec = Vec::new(); + let mut i = 0; + while i + 2 < indices.len() { + let (a, b, c) = (indices[i], indices[i + 1], indices[i + 2]); + if ok(a) && ok(b) && ok(c) { + tri.extend_from_slice(&[a, c, b]); + } + i += 3; + } + let idx: Vec = if closed && tri.iter().all(|v| v.fract() == 0.0) { + let t: Vec = tri.iter().map(|&v| v as u32).collect(); + orient_outward(&pos, &t).into_iter().map(f64::from).collect() + } else { + tri + }; + let base = (prim.positions.len() / 3) as f64; + prim.positions.extend_from_slice(&pos); + prim.indices.extend(idx.iter().map(|i| base + i)); +} + +fn u32s(v: &[u32]) -> Vec { + v.iter().map(|&i| f64::from(i)).collect() +} + +/// Standardfarbe der Extrusionen (wie `SLAB_RGB`). +const SLAB_COLOR: Rgb = [0.86, 0.86, 0.88]; +/// Verglasung und Rahmenteile aus `emit_opening_meshes` (Farben `PART_RGB`). +const GLASS_COLOR: Rgb = [0.62, 0.76, 0.85]; +const OPENING_PART_NAMES: [(Rgb, &str); 5] = [ + ([0.85, 0.85, 0.83], "Blendrahmen"), + ([0.88, 0.88, 0.9], "Fluegelrahmen"), + ([0.8, 0.8, 0.78], "Fensterbank/Zarge"), + ([0.25, 0.27, 0.3], "Schwelle"), + ([0.93, 0.9, 0.85], "Tuerblatt"), +]; +const TERRAIN_RGB: Rgb = [169.0 / 255.0, 176.0 / 255.0, 162.0 / 255.0]; +const IMPORTED_RGB: Rgb = [159.0 / 255.0, 166.0 / 255.0, 174.0 / 255.0]; + +fn same_rgb(a: &Rgb, b: &Rgb) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +/// Die Szene als flacher Puffer (s. Modulkopf). +pub fn mesh_export_data(src: &Project, opt: &MeshOptions) -> Result { + let mut p = src.clone(); + let mut groups: Vec = Vec::new(); + let mut mats = Materials::default(); + crate::ifc_data::pick_opening_check(&p)?; + let walls = model3d::emit_walls(&p, true)?; + let slabs = model3d::emit_slabs(&p); + let levels: Vec<(String, String)> = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).map(|l| (l.id.clone(), l.name.clone())).collect(); + let level_of = |floor_id: Option<&str>| -> f64 { floor_id.and_then(|id| levels.iter().position(|l| l.0 == id)).map_or(-1.0, |i| i as f64) }; + let component_name = |p: &Project, id: Option<&str>, fallback: &str| -> String { + id.and_then(|id| p.component(id)).map(|c| c.name.as_str()).filter(|n| !n.is_empty()).unwrap_or(fallback).to_string() + }; + + // Wände: alle Schicht-Bänder DERSELBEN Wand-Id in EINE Gruppe. + let mut wall_group: HashMap = HashMap::new(); + let mut wall_floor: HashMap<&str, &str> = HashMap::new(); + for w in &p.walls { + wall_floor.insert(&w.id, &w.floor_id); + } + for w in &walls { + let gi = match wall_group.get(&w.wall_id) { + Some(&i) => i, + None => { + groups.push(Group::new(format!("Wand_{}", sanitize_name(&w.wall_id)), "wall", &w.wall_id, level_of(wall_floor.get(w.wall_id.as_str()).copied()))); + wall_group.insert(w.wall_id.clone(), groups.len() - 1); + groups.len() - 1 + } + }; + let mat = mats.solid(&component_name(&p, w.cut.as_ref().and_then(|c| c.component_id.as_deref()), "Wand"), w.color); + let prim = groups[gi].prim(mat); + if w.holes.as_ref().is_some_and(|h| !h.is_empty()) { + // Öffnungsgenau inkl. Laibungen (Welt x, Höhe, y), wie im 3D. + let cut = wall_cut_mesh_checked(&CutWall { + start: w.start, + end: w.end, + thickness: w.thickness, + base_elevation: w.base_elevation, + height: w.height, + holes: w.holes.as_deref().unwrap_or(&[]).iter().map(|h| [h.from, h.to, h.z_bottom, h.z_top]).collect(), + }); + let base = (prim.positions.len() / 3) as f64; + prim.positions.extend_from_slice(&cut); + prim.indices.extend((0..cut.len() / 3).map(|i| base + i as f64)); + } else { + push_wall_box(prim, w); + } + } + + // Decken: ein Prisma je Platte. + let mut ceiling_floor: HashMap<&str, &str> = HashMap::new(); + for c in p.ceilings.as_deref().unwrap_or(&[]) { + ceiling_floor.insert(&c.id, &c.floor_id); + } + for s in &slabs { + let mut g = Group::new(format!("Decke_{}", sanitize_name(&s.ceiling_id)), "slab", &s.ceiling_id, level_of(ceiling_floor.get(s.ceiling_id.as_str()).copied())); + let outline: Vec = s.outline.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect(); + let mat = mats.solid(&component_name(&p, s.cut.as_ref().and_then(|c| c.component_id.as_deref()), "Decke"), s.color); + push_prism(g.prim(mat), &outline, s.z_bottom, s.z_top, 0.0); + groups.push(g); + } + + // Extrudierte Profile: Prisma je Körper (Prisma-Näherung statt truck-Körper). + for s in p.extruded_solids.as_deref().unwrap_or(&[]) { + if s.points.len() < 3 || s.height <= 0.0 { + continue; + } + let base_z = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)); + let mut g = Group::new(format!("Extrusion_{}", sanitize_name(&s.id)), "extrusion", &s.id, level_of(Some(&s.level_id))); + let mat = mats.solid("Extrusion", SLAB_COLOR); + push_prism(g.prim(mat), &s.points, base_z, base_z + s.height, s.taper.unwrap_or(0.0)); + groups.push(g); + } + + // Dächer, Stützen, Treppen: je Bauteil EIN Aufruf der 3D-Ableitung mit nur diesem Bauteil. + let add_meshes = |g: &mut Group, mats: &mut Materials, meshes: &[RMesh], name: &str| { + for m in meshes { + if m.indices.is_empty() { + continue; + } + let mat = mats.solid(name, m.color); + append_model_mesh(g.prim(mat), &m.positions, &u32s(&m.indices), true); + } + }; + let roofs = p.roofs.take(); + for roof in roofs.as_deref().unwrap_or(&[]) { + let mut g = Group::new(format!("Dach_{}", sanitize_name(&roof.id)), "roof", &roof.id, level_of(Some(&roof.floor_id))); + p.roofs = Some(vec![roof.clone()]); + add_meshes(&mut g, &mut mats, &model3d::emit_roofs(&p, None)?, "Dach"); + groups.push(g); + } + p.roofs = roofs; + let columns = p.columns.take(); + for col in columns.as_deref().unwrap_or(&[]) { + let mut g = Group::new(format!("Stuetze_{}", sanitize_name(&col.id)), "column", &col.id, level_of(Some(&col.floor_id))); + p.columns = Some(vec![col.clone()]); + let name = component_name(&p, col.component_id.as_deref(), "Stuetze"); + add_meshes(&mut g, &mut mats, &model3d::emit_columns(&p), &name); + groups.push(g); + } + p.columns = columns; + let stairs = p.stairs.take(); + for st in stairs.as_deref().unwrap_or(&[]) { + let mut g = Group::new(format!("Treppe_{}", sanitize_name(&st.id)), "stair", &st.id, level_of(Some(&st.floor_id))); + p.stairs = Some(vec![st.clone()]); + for s in model3d::emit_stairs(&p, false) { + let outline: Vec = s.outline.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect(); + let mat = mats.solid("Treppe", s.color); + push_prism(g.prim(mat), &outline, s.z_bottom, s.z_top, 0.0); + } + add_meshes(&mut g, &mut mats, &model3d::emit_stair_meshes(&p), "Treppe"); + add_meshes(&mut g, &mut mats, &model3d::emit_stair_railings(&p), "Handlauf"); + groups.push(g); + } + p.stairs = stairs; + + // Öffnungsteile: je Öffnung ein Knoten mit Glas und Rahmenteilen als Teil-Netze je Material; + // die Ableitung nur mit der Wirtswand und dieser Öffnung. + if opt.opening_parts { + let all_walls = std::mem::take(&mut p.walls); + let openings = p.openings.take(); + for op in openings.as_deref().unwrap_or(&[]) { + let Some(host) = all_walls.iter().find(|w| w.id == op.host_wall_id) else { continue }; + p.walls = vec![host.clone()]; + p.openings = Some(vec![op.clone()]); + let parts = model3d::emit_opening_meshes(&p, 1.0); + if parts.is_empty() { + continue; + } + let (prefix, kind) = match op.kind { + ElementKind::Window => ("Fenster", "window"), + ElementKind::Door => ("Tuer", "door"), + ElementKind::Unknown => ("Tuer", ""), + }; + let mut g = Group::new(format!("{prefix}_{}", sanitize_name(&op.id)), kind, &op.id, level_of(Some(&host.floor_id))); + let mut prims: HashMap<&str, usize> = HashMap::new(); + for m in &parts { + let glass = same_rgb(&m.color, &GLASS_COLOR); + let name = if glass { "Glas" } else { OPENING_PART_NAMES.iter().find(|(c, _)| same_rgb(c, &m.color)).map_or("Oeffnungsteil", |x| x.1) }; + let pi = match prims.get(name) { + Some(&i) => i, + None => { + // Glas transparent und glatt (BLEND), Rahmen matt. + let mat = if glass { mats.get(name, m.color, 0.35, 0.0, 0.05) } else { mats.get(name, m.color, 1.0, 0.0, 0.6) }; + g.prim(mat); + prims.insert(name, g.prims.len() - 1); + g.prims.len() - 1 + } + }; + append_model_mesh(&mut g.prims[pi], &m.positions, &u32s(&m.indices), true); + } + groups.push(g); + } + p.walls = all_walls; + p.openings = openings; + } + + // Gelände und importierte Meshes (IFC/DXF): Farbe der Quelle, falls gesetzt. + if opt.context { + for obj in p.context.as_deref().unwrap_or(&[]) { + let (terrain, id, name, color, positions, indices) = match obj { + ContextObject::TerrainMesh(m) => (true, &m.id, &m.name, None, &m.positions, &m.indices), + ContextObject::ImportedMesh(m) => (false, &m.id, &m.name, m.color.as_deref(), &m.positions, &m.indices), + _ => continue, + }; + if positions.len() < 9 || indices.len() < 3 { + continue; + } + let rgb = match (terrain, color.filter(|c| !c.is_empty())) { + (false, Some(c)) => hex_to_rgb(c, IMPORTED_RGB), + (true, _) => TERRAIN_RGB, + _ => IMPORTED_RGB, + }; + let mut g = Group::new(format!("{}_{}", if terrain { "Gelaende" } else { "Kontext" }, sanitize_name(id)), if terrain { "terrain" } else { "context" }, id, -1.0); + let mat_name = if terrain { "Gelaende" } else if name.is_empty() { "Kontext" } else { name.as_str() }; + let mat = mats.solid(mat_name, rgb); + append_model_mesh(g.prim(mat), positions, indices, false); + groups.push(g); + } + } + + // Flacher Puffer (Gegenstück zu `mesh_export.rs`). + let mut f = Flat::new(FLAT_VERSION); + f.num(if opt.by_level { 1.0 } else { 0.0 }); + f.num(mats.list.len() as f64); + for m in &mats.list { + let n = f.str(&m.name); + f.nums(&[n, m.rgba[0], m.rgba[1], m.rgba[2], m.rgba[3], m.metallic, m.roughness]); + } + f.num(levels.len() as f64); + for (id, name) in &levels { + let (a, b) = (f.str(id), f.str(name)); + f.nums(&[a, b]); + } + let groups: Vec<&Group> = groups.iter().filter(|g| g.prims.iter().any(|p| !p.indices.is_empty())).collect(); + f.num(groups.len() as f64); + for g in groups { + let (name, kind, id) = (f.str(&g.name), f.str(g.kind), f.str(&g.id)); + f.nums(&[name, kind, id, g.level, g.prims.len() as f64]); + for pr in &g.prims { + f.nums(&[pr.material, (pr.positions.len() / 3) as f64]); + f.nums(&pr.positions); + f.num((pr.indices.len() / 3) as f64); + f.nums(&pr.indices); + } + } + Ok(f) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample() -> Project { + serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap() + } + + #[test] + fn namen_wie_js() { + assert_eq!(sanitize_name("W 1/ä"), "W_1__"); + assert_eq!(sanitize_name("a😀b"), "a__b"); + assert_eq!(sanitize_name(""), "x"); + } + + #[test] + fn beispielprojekt_knoten_und_materialien() { + let f = mesh_export_data(&sample(), &MeshOptions::default()).unwrap(); + assert_eq!(f.nums[0], FLAT_VERSION); + for want in ["Wand_W1", "Decke_C1", "Dach_RF1", "Treppe_ST1", "Fenster_O1", "Tuer_D1", "Glas"] { + assert!(f.strings.iter().any(|s| s == want), "fehlt: {want}"); + } + let f2 = mesh_export_data(&sample(), &MeshOptions { opening_parts: false, ..Default::default() }).unwrap(); + assert!(!f2.strings.iter().any(|s| s == "Fenster_O1")); + assert!(f2.nums.len() < f.nums.len()); + } + + #[test] + fn prisma_aussen_gewickelt() { + let mut g = Group::new("x".into(), "slab", "x", -1.0); + let sq = [Vec2 { x: 0.0, y: 0.0 }, Vec2 { x: 0.0, y: 1.0 }, Vec2 { x: 1.0, y: 1.0 }, Vec2 { x: 1.0, y: 0.0 }]; + push_prism(g.prim(0.0), &sq, 0.0, 1.0, 0.0); + let pr = &g.prims[0]; + assert_eq!(pr.positions.len(), 8 * 3); + assert_eq!(pr.indices.len(), (2 * 2 + 4 * 2) * 3); + // Geschlossen und konsistent gewickelt: Betrag des Volumens = 1 (Einheitswürfel). + let idx: Vec = pr.indices.iter().map(|&i| i as u32).collect(); + let mut v = 0.0; + for t in idx.chunks_exact(3) { + let q = |i: u32| &pr.positions[i as usize * 3..i as usize * 3 + 3]; + let (a, b, c) = (q(t[0]), q(t[1]), q(t[2])); + v += a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]); + } + assert!(((v / 6.0).abs() - 1.0).abs() < 1e-12, "{v}"); + } + + #[test] + fn kaputtes_kontext_netz_ohne_panik() { + let mut p = Project { id: "k".into(), ..Default::default() }; + p.context = Some(vec![ContextObject::ImportedMesh(ImportedMesh { id: "m".into(), positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, f64::NAN], indices: vec![0.0, 1.0, 9.0, 0.0, 1.0, 2.0, f64::NAN, 0.0, 1.0], ..Default::default() })]); + let f = mesh_export_data(&p, &MeshOptions::default()).unwrap(); + assert!(f.strings.iter().any(|s| s == "Kontext_m")); + } +} diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 50ee88af..4ae50ea9 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -49,6 +49,15 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result Result, String> { match (name, args.len()) { ("planDomains", 1) => crate::plan::domains::plan_domains_buf(p, &crate::plan::domains::PlanArgs::parse(args[0], text)?), + // Export-Sammler ([K4], [B5], [C11]): flacher Puffer für `fileio` (Byte-Hülle `export_flat.rs`). + ("ifcExportData", 4) => { + let opt = crate::ifc_data::IfcOptions { now: args[0], ifc2x3: args[1] != 0.0, ebkph: args[2] != 0.0, layer_codes: args[3] != 0.0, iso: text.to_string() }; + crate::ifc_data::ifc_export_data(p, &opt).map(|f| f.to_bytes()) + } + ("meshExportData", 3) => { + let opt = crate::mesh_data::MeshOptions { opening_parts: args[0] != 0.0, context: args[1] != 0.0, by_level: args[2] != 0.0 }; + crate::mesh_data::mesh_export_data(p, &opt).map(|f| f.to_bytes()) + } _ => Err(format!("Unbekannte Abfrage: {name}")), } } diff --git a/src-tauri/core/src/wall_mesh_cut.rs b/src-tauri/core/src/wall_mesh_cut.rs index 0514fd44..2eac8a8e 100644 --- a/src-tauri/core/src/wall_mesh_cut.rs +++ b/src-tauri/core/src/wall_mesh_cut.rs @@ -2,14 +2,14 @@ //! aus EINEM Wandband (`RWall`: Achse, Dicke, UK, Höhe, rechteckige Löcher) entsteht das //! Dreiecksnetz mit ausgestanzten Öffnungen samt Laibungsflächen — dieselbe Zerlegung wie //! `render3d/src/mesh.rs::extrude_layer_segment_with_holes`, aber ohne Gehrung (die Bänder aus -//! [`crate::wall_bands`] sind an den Enden schon gekürzt). Portiert aus `src/plan/wallMeshCut.ts`. +//! [`crate::wall_bands`] sind an den Enden schon gekürzt). Portiert aus `src/plan/wallMeshCut.ts` (gelöscht); +//! Verbraucher sind die Export-Sammler `ifc_data.rs` und `mesh_data.rs`. //! //! Achsen: Modell (x, y) → Welt (x, Höhe, y), Y-up. Jedes Dreieck hat drei eigene Ecken; die //! Indizes sind daher fortlaufend `0, 1, 2, …` und werden nicht übertragen. //! //! Bitgleich zur früheren TS-Fassung (gleiche Operationsreihenfolge, `Math.hypot` wie V8). -use crate::flat_read::Reader; use crate::joins::js_hypot; use crate::openings3d::{jmax, jmin}; use kernel2d::{add, left_normal, scale, Vec2}; @@ -259,51 +259,18 @@ pub fn is_watertight(positions: &[f64], indices: &[u32], eps: f64) -> bool { js_hypot3(ax, ay, az) < eps && vol6 > eps } -// ── Flache Kodierung ───────────────────────────────────────────────────────── -// -// Eingabe: `[nBänder, (sx, sy, ex, ey, Dicke, UK, Höhe, nLöcher, (from, to, zb, zt)…)…]`. -// Ausgabe: `[nBänder, (nZahlen, x, Höhe, y, …)…]` — je Band die Weltpunkte, drei je Dreiecksecke. -// Kaputte Eingabe ⇒ `[0]`; ein Band mit NaN/∞ ⇒ leeres Mesh. - -fn decode(buf: &[f64]) -> Option> { - let mut r = Reader::new(buf); - let n = r.count()?; - let mut out = Vec::with_capacity(n.min(1 << 16)); - for _ in 0..n { - let start = [r.num()?, r.num()?]; - let end = [r.num()?, r.num()?]; - let (thickness, base_elevation, height) = (r.num()?, r.num()?, r.num()?); - let nh = r.count()?; - let mut holes = Vec::with_capacity(nh.min(1024)); - for _ in 0..nh { - holes.push([r.num()?, r.num()?, r.num()?, r.num()?]); - } - out.push(CutWall { start, end, thickness, base_elevation, height, holes }); - } - Some(out) -} - fn finite(w: &CutWall) -> bool { [w.start[0], w.start[1], w.end[0], w.end[1], w.thickness, w.base_elevation, w.height].iter().all(|v| v.is_finite()) && w.holes.iter().flatten().all(|v| v.is_finite()) } -/// Flache Bindung für viele Bänder auf einmal; nie ein Panic. -pub fn wall_cut_meshes_flat(buf: &[f64]) -> Vec { - let Some(walls) = decode(buf) else { return vec![0.0] }; - let mut out = vec![walls.len() as f64]; - for w in &walls { - let m = if finite(w) { wall_cut_mesh(w) } else { Vec::new() }; - out.push(m.len() as f64); - out.extend_from_slice(&m); +/// [`wall_cut_mesh`] mit Eingabeprüfung (Export-Sammler `ifc_data`/`mesh_data`): NaN/∞ ⇒ leer. +pub fn wall_cut_mesh_checked(w: &CutWall) -> Vec { + if finite(w) { + wall_cut_mesh(w) + } else { + Vec::new() } - out -} - -/// Flache Bindung von [`solid_subrects`]: `holes` als `[from, to, zb, zt, …]`; Ausgabe ebenso. -pub fn solid_subrects_flat(u_lo: f64, u_hi: f64, z_lo: f64, z_hi: f64, holes: &[f64]) -> Vec { - let hs: Vec<[f64; 4]> = holes.chunks_exact(4).map(|c| [c[0], c[1], c[2], c[3]]).collect(); - solid_subrects(u_lo, u_hi, z_lo, z_hi, &hs).into_iter().flatten().collect() } #[cfg(test)] @@ -373,27 +340,23 @@ mod tests { } #[test] - fn flach_viele_baender() { - let buf = [2.0, 0.0, 0.0, 5.0, 0.0, 0.4, 0.0, 2.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.4, 0.0, 2.6, 1.0, 1.0, 2.0, 0.0, 2.0]; - let out = wall_cut_meshes_flat(&buf); - assert_eq!(out[0], 2.0); - assert_eq!(out[1], 108.0); - assert_eq!(out[2 + 108], 0.0); // Nullwand ⇒ leer - assert_eq!(solid_subrects_flat(0.0, 5.0, 0.0, 2.6, &[2.0, 3.0, 0.0, 2.1, 9.0]).len(), 5 * 4); + fn tuer_am_boden_ohne_untere_laibung() { + // 5 Teilrechtecke × 2 Seiten + Deckel + 2 Boden-Stücke + 2 Kappen + 3 Laibungen = 18 Quads = 36 Dreiecke. + let tuer = wall_cut_mesh(&band(vec![[2.0, 3.0, 0.0, 2.1]])); + assert_eq!(tuer.len(), 36 * 9); + assert_eq!(wall_cut_mesh_checked(&band(vec![[2.0, 3.0, 0.0, 2.1]])), tuer); + let null = CutWall { end: [0.0, 0.0], ..band(vec![]) }; + assert!(wall_cut_mesh_checked(&null).is_empty()); } #[test] fn unsinn_ohne_panic() { - assert_eq!(wall_cut_meshes_flat(&[]), vec![0.0]); - assert_eq!(wall_cut_meshes_flat(&[f64::NAN]), vec![0.0]); - assert_eq!(wall_cut_meshes_flat(&[1e300]), vec![0.0]); - assert_eq!(wall_cut_meshes_flat(&[1.0, 0.0, 0.0, 5.0]), vec![0.0]); - let out = wall_cut_meshes_flat(&[1.0, 0.0, 0.0, f64::NAN, 0.0, 0.4, 0.0, 2.6, 0.0]); - assert_eq!(out, vec![1.0, 0.0]); + let w = CutWall { end: [f64::NAN, 0.0], ..band(vec![]) }; + assert!(wall_cut_mesh_checked(&w).is_empty()); + assert!(wall_cut_mesh_checked(&band(vec![[f64::INFINITY, 1.0, 0.0, 1.0]])).is_empty()); // Löcher verkehrt herum, riesig, negativ. let w = band(vec![[3.0, 1.0, 2.0, 0.5], [-1e9, 1e9, -1e9, 1e9], [f64::NAN, 1.0, 0.0, 1.0]]); let _ = wall_cut_mesh(&w); let _ = solid_subrects(f64::NAN, 1.0, 0.0, f64::INFINITY, &[[f64::NAN; 4]]); - let _ = solid_subrects_flat(0.0, 1.0, 0.0, 1.0, &[1.0, 2.0]); } } diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index abb96b4b..2d9407bb 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -16,7 +16,6 @@ mod room_area; mod room_boundary; mod polygon_holes; mod drawing2d_3d; -mod wall_mesh_cut; mod plan_buf; mod project_format; mod gpu_compile; diff --git a/src-tauri/core/src/web/wall_mesh_cut.rs b/src-tauri/core/src/web/wall_mesh_cut.rs deleted file mode 100644 index d58aba82..00000000 --- a/src-tauri/core/src/web/wall_mesh_cut.rs +++ /dev/null @@ -1,21 +0,0 @@ -//! Bindungen des Wand-Loch-Mesh (`crate::wall_mesh_cut`). Kodierung s. dort. - -use wasm_bindgen::prelude::wasm_bindgen; - -/// Viele Wandbänder flach → je Band die Weltpunkte der Dreiecke; nie ein Panic. -#[wasm_bindgen] -pub fn wall_cut_meshes_flat(buf: &[f64]) -> Vec { - crate::wall_mesh_cut::wall_cut_meshes_flat(buf) -} - -/// Rechteck minus Löcher als Teilrechtecke (`[u0, u1, z0, z1, …]`). -#[wasm_bindgen] -pub fn solid_subrects_flat(u_lo: f64, u_hi: f64, z_lo: f64, z_hi: f64, holes: &[f64]) -> Vec { - crate::wall_mesh_cut::solid_subrects_flat(u_lo, u_hi, z_lo, z_hi, holes) -} - -/// Geschlossenes, nach aussen gewundenes Mesh? (Gauss-Kriterium.) -#[wasm_bindgen] -pub fn is_watertight_flat(positions: &[f64], indices: &[u32], eps: f64) -> bool { - crate::wall_mesh_cut::is_watertight(positions, indices, eps) -} diff --git a/src-tauri/fileio/src/mesh_export.rs b/src-tauri/fileio/src/mesh_export.rs index 147ba6f7..acc40395 100644 --- a/src-tauri/fileio/src/mesh_export.rs +++ b/src-tauri/fileio/src/mesh_export.rs @@ -466,10 +466,15 @@ fn build_gltf(s: &Scene, uri_for_buffer: bool) -> (String, Vec) { } let mut j = String::from( - "{\"asset\":{\"version\":\"2.0\",\"generator\":\"Dossier\",\"extras\":{\"units\":\"m\",\"upAxis\":\"Y\",\"note\":\"Modell (x,y,z-hoch) -> glTF (x,z,-y); Norden = -Z\"}},\"scene\":0,\"scenes\":[{\"nodes\":[", + "{\"asset\":{\"version\":\"2.0\",\"generator\":\"Dossier\",\"extras\":{\"units\":\"m\",\"upAxis\":\"Y\",\"note\":\"Modell (x,y,z-hoch) -> glTF (x,z,-y); Norden = -Z\"}},\"scene\":0,\"scenes\":[{", ); - j.push_str(&scene_nodes.iter().map(usize::to_string).collect::>().join(",")); - j.push_str("]}]"); + // Leere Szene ohne `nodes` (glTF verlangt ≥ 1 Eintrag, wenn die Liste da ist; Validator EMPTY_ENTITY). + if !scene_nodes.is_empty() { + j.push_str("\"nodes\":["); + j.push_str(&scene_nodes.iter().map(usize::to_string).collect::>().join(",")); + j.push(']'); + } + j.push_str("}]"); if n_nodes > 0 { j.push_str(",\"nodes\":["); j.push_str(&nodes); @@ -722,7 +727,7 @@ mod tests { let glb = export_glb(&n, "").unwrap(); let (json, bl) = json_of_glb(&glb); assert_eq!(bl, 0); - assert!(json.trim_end().ends_with("\"scene\":0,\"scenes\":[{\"nodes\":[]}]}")); + assert!(json.trim_end().ends_with("\"scene\":0,\"scenes\":[{}]}"), "{json}"); assert_eq!(export_obj(&n, "").unwrap().lines().count(), 5); assert_eq!(export_stl(&n, "").unwrap(), "solid dossier\nendsolid dossier\n"); } diff --git a/src/core/document.ts b/src/core/document.ts index 9f7fb616..4c5d92c2 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -36,6 +36,8 @@ export type QueryName = | "pickGeometry" | "model3dParts" | "planDomains" + | "ifcExportData" + | "meshExportData" | "modelJson"; export class ProjectDocument { diff --git a/src/export/exportIfc.classification.test.ts b/src/export/exportIfc.classification.test.ts index 6dc246a2..345cf12d 100644 --- a/src/export/exportIfc.classification.test.ts +++ b/src/export/exportIfc.classification.test.ts @@ -8,7 +8,6 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import "../engine/fileioWasm.setup"; import { exportIfcSpf } from "./exportIfc"; -import { EBKPH_GROUPS, ebkphGroup, layerClassification } from "./ifcClassification"; import { readIfcElements } from "../io/ifcElements"; import { classificationSuffix, ifcToImportedMeshes, readIfc } from "../io/ifcImport"; import { sampleProject } from "../model/sampleProject"; @@ -35,27 +34,7 @@ function houseWithRooms(): Project { }; } -describe("eBKP-H-Standardzuordnung", () => { - it("nur gesicherte Hauptgruppen, Tür und Raum bleiben unklassifiziert", () => { - expect(Object.keys(EBKPH_GROUPS)).toEqual(["C", "E", "F"]); - expect(ebkphGroup("wall")).toEqual({ code: "C", name: "Konstruktion Gebäude" }); - expect(ebkphGroup("slab")?.code).toBe("C"); - expect(ebkphGroup("column")?.code).toBe("C"); - expect(ebkphGroup("stair")?.code).toBe("C"); - expect(ebkphGroup("roof")).toEqual({ code: "F", name: "Bedachung Gebäude" }); - expect(ebkphGroup("window")).toEqual({ code: "E", name: "Äussere Wandbekleidung Gebäude" }); - expect(ebkphGroup("door")).toBeNull(); - expect(ebkphGroup("space")).toBeNull(); - }); - - it("Ebene: Name aus dem Ebenenbaum, unbekannter Code bleibt Code, ohne Code nichts", () => { - expect(layerClassification(sampleProject, "20")?.code).toBe("20"); - expect(layerClassification(sampleProject, "25")?.name).toBe("Stützen"); // Unterkategorie - expect(layerClassification(sampleProject, "777")).toEqual({ code: "777", name: "777" }); - expect(layerClassification(sampleProject, undefined)).toBeNull(); - expect(layerClassification(sampleProject, " ")).toBeNull(); - }); -}); +// Zuordnungstabelle eBKP-H und Ebenen-Auflösung: Rust-Tests in `src-tauri/core/src/ifc_data.rs`. describe("IFC-Export: Zonen und Geschoss-Kennwerte (SIA 416)", () => { it("je Kategorie eine IfcZone mit ihren Räumen, Kategorie und Fläche als Eigenschaft", () => { diff --git a/src/export/exportIfc.test.ts b/src/export/exportIfc.test.ts index 45492cae..f09dd7ef 100644 --- a/src/export/exportIfc.test.ts +++ b/src/export/exportIfc.test.ts @@ -701,3 +701,17 @@ describe("[B5] Pset_*Common mit den Werten aus dem Modell", () => { expect(kueche).toContain(".INTERNAL."); }); }); + +describe("Sammler im Kern ([K4], 29.10.)", () => { + it("Fehler des Kerns kommen mit dessen Meldung (unbekannter Wandtyp)", () => { + const p = fixtureProject(); + const broken: Project = { ...p, walls: p.walls.map((w, i) => (i === 0 ? { ...w, wallTypeId: "fehlt" } : w)) }; + expect(() => exportIfcSpf(broken)).toThrow("Unbekannter Wandtyp: fehlt"); + }); + + it("zweimal exportieren gibt dieselbe Datei (bis auf den Zeitstempel)", () => { + const strip = (s: string) => s.replace(/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d/g, "T").replace(/IFCOWNERHISTORY\([^;]*;/g, ""); + const p = fixtureProject(); + expect(strip(exportIfcSpf(p, { ebkph: true, layerCodes: true }))).toBe(strip(exportIfcSpf(p, { ebkph: true, layerCodes: true }))); + }); +}); diff --git a/src/export/exportIfc.ts b/src/export/exportIfc.ts index 632e9908..fbabc7df 100644 --- a/src/export/exportIfc.ts +++ b/src/export/exportIfc.ts @@ -1,149 +1,34 @@ // IFC-Export (IFC4 oder IFC2x3, STEP Physical File / ISO-10303-21) des semantischen Modells. // -// Schema ([B5], 28.10.): `options.schema` = "IFC4" (Standard) oder "IFC2X3" (Coordination View 2.0). -// TS sammelt in beiden Fällen dasselbe; nur das META trägt die Wahl (und die WGS84-Breite/Länge des -// Bezugspunkts für `IfcSite.RefLatitude/RefLongitude`), die Entitäten des Schemas schreibt Rust. +// Seit [K4]/[B5] (29.10.) rechnet alles in Rust: der Kern sammelt aus dem Projekt-Dokument den flachen +// Puffer (`src-tauri/core/src/ifc_data.rs`, Abfrage `ifcExportData`: Wand-Bänder, Öffnungen samt +// Füllungs-Parametern, Treppen-Teile, Dach-Netze, Räume, Zonen, Geschoss-Kennwerte, Basismengen, +// Klassifikation, Georeferenz), das Format-Modul schreibt daraus die Datei +// (`src-tauri/fileio/src/ifc_export.rs`: Entitäten, GUIDs, Typen mit Materialschichten, Psets, +// Beziehungen). Zwei WASM-Module, die Bytes reichen von einem zum anderen; TS gibt nur Optionen und +// den Zeitstempel weiter. Verlangt das geladene Format-Modul (`await loadFileio()`, wie +// `buildPlanDxf`). Der Download passiert im App-Layer. // -// Seit [B5] (28.10.) schreibt Rust die Datei (`src-tauri/fileio/src/ifc_export.rs`, Format-Modul -// pkgFileIo): TS sammelt hier aus Projekt und Plan die Bauteile samt fertig gerechneter Geometrie -// (Wand-Bänder, Öffnungen, Dach-Meshes, Raumflächen) als flachen Puffer, Rust vergibt die Nummern und -// baut Entitäten, GUIDs, Typen mit Materialschichten, Psets und Beziehungen. Verlangt das geladene -// Format-Modul (`await loadFileio()`, wie `buildPlanDxf`). Der Download passiert im App-Layer. -// -// Abbildung: -// Project → IfcProject → IfcSite → IfcBuilding → je "floor"-Geschoss ein -// IfcBuildingStorey (IfcRelAggregates-Kette). Bauteile hängen über -// IfcRelContainedInSpatialStructure am jeweiligen Geschoss (verwaiste -// Geschossreferenzen fallen defensiv auf IfcBuilding zurück). -// -// Decken/Treppen/Extrusionen als IfcExtrudedAreaSolid (unser Modell IST -// Extrusion): Profil = IfcArbitraryClosedProfileDef(IfcPolyline) in der -// XY-Ebene, extrudiert entlang +Z. Die horizontale Objekt-Platzierungskette -// (Site/Building/Storey/Element) trägt bewusst NUR die Z-Verschiebung -// (Geschoss-Elevation); die Profilpunkte tragen direkt die Welt-X/Y-Koordinaten. -// -// • Wand → IfcWall aus denselben Schicht-Bändern wie das 3D (`pickGeometry`: Joins/ -// Gehrungen, Decken-Dominanz, Durchgangs-Aussparungen bereits aufgelöst). Zwei Wege ([B5]): -// – Regelfall: UNGESCHNITTENER Körper, je Band ein IfcExtrudedAreaSolid (Rechteck × Höhe) -// in EINER SweptSolid-Darstellung; Fenster/Türen als IfcOpeningElement (IfcRelVoids -// Element), der Viewer zieht sie ab. Gewählt nur, wenn das exakt dasselbe ergibt wie das -// 3D: jedes Band ist ein Quader (keine schräge Oberkante) und seine Löcher sind genau die -// Öffnungen (`bandsMatchOpenings`). -// – sonst (Wand unter Dach mit schräger Oberkante, Laibungs-Rücksprung der innersten -// Schicht …): öffnungsgenaues Dreiecks-Mesh (IfcTriangulatedFaceSet) wie STL/OBJ -// (`plan/wallMeshCut.ts`, Löcher inkl. Laibungen schon ausgestanzt). Öffnung + Füllung -// werden trotzdem als Beziehung angelegt; die Öffnung liegt im Loch und zieht nichts ab. -// • Decke → IfcSlab (outline-Polygon, PredefinedType FLOOR). -// • Öffnung → IfcOpeningElement (Quader über die ganze Wanddicke, etwas vorstehend) in der -// Wand (IfcRelVoidsElement), darin IfcDoor/IfcWindow (IfcRelFillsElement) aus getrennten Körpern -// ([B5], 28.10., Parameter `ifcOpenings.ts`, Rechnung `ifc_openings.rs`): 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. -// • Raum → IfcSpace (im Geschoss aggregiert) mit Qto_SpaceBaseQuantities und SIA-416-Kategorie. -// • Treppe → IfcStair ohne eigene Darstellung, zusammengefasst (IfcRelAggregates) aus Läufen -// (IfcStairFlight: Prismen der Tritte bzw. glatte Ortbeton-Laufplatte als Netz, Steigungs-/Auftrittsmasse), -// Podest (IfcSlab LANDING, nur "L") und Handlauf/Pfosten (IfcRailing HANDRAIL, wo das 3D sie zeigt) — -// dieselben Ableitungen wie das 3D (`ifcStairs.ts`). Ohne Teile bleibt der Fussabdruck-Quader -// (`stairFootprint()`). -// -// Material-Schichten: je Wand-/Deckentyp ein IfcWallType/IfcSlabType mit -// IfcMaterialLayerSet, die Exemplare erben ihn über IfcRelDefinesByType. Extrusions-Wände -// ([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. -// -// Basismengen ([B5], 28.10.): Qto_WallBaseQuantities (Length, Width, Height, GrossSideArea, NetSideArea, -// GrossVolume, NetVolume), Qto_SlabBaseQuantities, Qto_RoofBaseQuantities, Qto_ColumnBaseQuantities, -// Qto_DoorBaseQuantities/Qto_WindowBaseQuantities (Width, Height, Perimeter, Area), Qto_StairFlightBaseQuantities -// und Qto_RailingBaseQuantities — aus der Geometrie (`ifcQuantities.ts`), Netto = abzüglich Öffnungen; -// Rust schreibt je Bauteil einen IfcElementQuantity. Deckenaussparungen sind echte Löcher im Profil. -// -// Eigenschaften ([B5]): Pset_WallCommon/SlabCommon/RoofCommon/ColumnCommon/DoorCommon/ -// WindowCommon/SpaceCommon nur mit Werten, die das Modell hergibt (Reference = Typname, -// IsExternal beim Dach und bei SIA-416-AGF-Räumen, Glasanteil der Glastür). Kein U-Wert, -// keine Tragfunktion: dafür hat das Modell keine Felder. -// -// Schweizer Praxis ([B5], 28.10.): -// • Zonen: je vorkommender SIA-416-Kategorie (HNF, NNF, VF, FF, KGF, AGF) eine IfcZone mit -// IfcRelAssignsToGroup der IfcSpaces, Eigenschaft `CH_Zone.SIA416` und Summe der Nettoflächen -// (`CH_Qto_SIA416.NetFloorArea`). Immer dabei, sobald Räume da sind. -// • Geschoss-Kennwerte: je Geschoss mit Räumen `Qto_BuildingStoreyBaseQuantities` (GrossFloorArea = GF, -// NetFloorArea = NGF nach SIA 416) und `CH_Qto_SIA416` mit allen Blatt-/Summenflächen (HNF … GF). -// • Klassifikation (Option, `ifcClassification.ts`): eBKP-H-Hauptgruppen je Bauteilart und/oder die -// Ebene des Modells als System „Dossier-Ebenen" — IfcClassification + IfcClassificationReference + -// IfcRelAssociatesClassification. -// • Achsraster: nicht exportiert — das Modell führt keine Raster-Ressource (nur die Regel „grid" der -// parametrischen Wände mit festem Abstand). -// -// GUIDs ([B5]/[10]): deterministisch aus `//[/]` über einen -// 128-Bit-Hash + Standard-IFC-GUID-Kompression (Zeichensatz 0-9,A-Z,a-z,_,$) — zweimal -// exportieren gibt dieselben GlobalIds, BIM-Koordination (Solibri, BIMcollab) erkennt die -// Bauteile wieder. Abgeleitete Entitäten (Rels, Typen, Psets) hängen an Element-/Geschoss-/ -// Typ-ids, nie an STEP-Nummern. Der Hash lebt in Rust (`ifc_guid`). -// -// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). Einheit: METER. +// Abbildung und Grenzen: Kopf von `ifc_data.rs` und `ifc_export.rs`, `TODO.md` [B5]. -import type { Opening, Project, Stair, Vec2, Wall } from "../model/types"; -import type { StairParts } from "./ifcStairs"; -import { - columnLabel, - getCeilingType, - getDoorType, - getWallType, - getWindowType, - openingLabel, - openingsOfWall, -} from "../model/types"; -import { projectToWorldCoords } from "../model/geoRebase"; -import { ceilingVerticalExtent, columnVerticalExtent, stairVerticalExtent } from "../model/wall"; -import { pickGeometry } from "../plan/toWalls3d"; -import type { RWall } from "../plan/toWalls3d"; -import { isWatertight, wallCutMeshes, type CutMesh } from "../plan/wallMeshCut"; -import { evaluateRoom } from "../geometry/roomArea"; -import { columnFootprint } from "../geometry/column"; -import { openingInterval, openingVerticalExtent } from "../geometry/opening"; +import type { Project } from "../model/types"; import { fileio } from "../engine/fileioWasm"; -import { lv95ToWgs84 } from "../io/lv95"; -import { fillParams, type FillParams } from "./ifcOpenings"; -import { stairParts } from "./ifcStairs"; -import { - columnQuantities, - holeVolume, - meshVolume, - openingQuantities, - roofQuantities, - slabQuantities, - wallQuantities, - type Qty, -} from "./ifcQuantities"; -import { roofBaseElevation, roofGeometry } from "../geometry/roof"; -import { SIA_CATEGORIES, balance, siaLabel, type SiaCategory } from "../geometry/roomArea"; -import { emitRoofs } from "./model3dParts"; -import { - EBKPH_SYSTEM, - LAYER_SYSTEM, - ebkphGroup, - layerClassification, - type ClassificationSystem, - type ClassifiedKind, - type IfcExportOptions, - type IfcSchema, -} from "./ifcClassification"; +import { documentFor } from "../core/document"; -export type { IfcExportOptions, IfcSchema } from "./ifcClassification"; +/** IFC-Schema der Ausgabe: IFC4 (Standard) oder IFC2x3 (Coordination View 2.0, TC1). */ +export type IfcSchema = "IFC4" | "IFC2X3"; -/** WGS84 des LV95-Bezugspunkts (swisstopo-Näherung); `null` ohne Bezug oder bei unbrauchbaren Zahlen. */ -function refLatLon(lv95: { e: number; n: number } | undefined): { lat: number; lon: number } | null { - if (!lv95 || !Number.isFinite(lv95.e) || !Number.isFinite(lv95.n)) return null; - const { lat, lon } = lv95ToWgs84(lv95.e, lv95.n); - return Number.isFinite(lat) && Number.isFinite(lon) ? { lat, lon } : null; +/** Optionen des IFC-Exports: Schema und Klassifikation. */ +export interface IfcExportOptions { + /** Schema der Datei; ohne Angabe IFC4. */ + schema?: IfcSchema; + /** + * eBKP-H-Hauptgruppen je Bauteilart (Standardzuordnung, Vorschlag für die Kostenplanung: Wand, + * Decke, Stütze, Treppe = C; Dach = F; Fenster = E; Tür und Raum ohne). + */ + ebkph?: boolean; + /** `categoryCode` (Ebene) des Modells als System „Dossier-Ebenen". */ + layerCodes?: boolean; } /** Deterministische 22-stellige IFC-GUID aus einem Namen (Rust, `ifc_export.rs::ifc_guid`). */ @@ -156,933 +41,41 @@ export function ifcString(s: string): string { return fileio().ifc_string(s); } -// ── Flacher Puffer (Gegenstück zu src-tauri/fileio/src/ifc_export.rs, dort die Kodierung) ───── +/** Kennung der Byte-Hülle des Kerns ("DXEF", `export_flat.rs`) und des Fehlerpuffers ("PLBe", `plan_buf.rs`). */ +const FLAT_MAGIC = 1146635590; +const ERR_MAGIC = 0x504c4265; -const FLAT_VERSION = 4; -const REC_WALL_SOLIDS = 1; -const REC_WALL_MESH = 2; -const REC_CEILING = 3; -const REC_OPENING = 4; -const REC_STAIR = 5; -const REC_EXTRUSION = 6; -const REC_SPACE = 7; -const REC_END_SPACES = 8; -const REC_ROOF = 9; -const REC_COLUMN = 10; -const REC_END_COLUMNS = 11; -const REC_CLASSIFICATION = 12; -const REC_ZONE = 13; -const REC_ATTACH = 14; - -/** Typart in der flachen Kodierung (0 Wand, 1 Decke, 2 Dach). */ -type TypeKind = 0 | 1 | 2; - -interface TypeRefIn { - kind: TypeKind; - id: string; - name: string; - predefined: string; - layers: { componentId: string; componentName: string; thickness: number }[]; +/** + * Byte-Hülle einer Export-Abfrage des Kerns (`export_flat.rs`) → `[Zahlenpuffer, Zeichenketten durch \0 + * getrennt]` für die `fileio`-Schreiber. Ein Fehlerpuffer des Kerns wirft mit dessen Meldung. + */ +export function decodeExportFlat(bytes: Uint8Array): [Float64Array, string] { + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const at = (i: number): number => (bytes.byteLength >= (i + 1) * 8 ? dv.getFloat64(i * 8, true) : Number.NaN); + if (at(0) === ERR_MAGIC) { + const n = Math.min(at(1), (bytes.byteLength - 16) / 2); + let msg = ""; + for (let i = 0; i < n; i++) msg += String.fromCharCode(dv.getUint16(16 + i * 2, true)); + throw new Error(msg); + } + const n = at(1); + const len = at(2); + if (at(0) !== FLAT_MAGIC || !(24 + n * 8 + len <= bytes.byteLength)) throw new Error("Export-Puffer des Kerns unlesbar"); + const nums = bytes.byteOffset % 8 === 0 ? new Float64Array(bytes.buffer, bytes.byteOffset + 24, n) : new Float64Array(bytes.slice(24, 24 + n * 8).buffer); + return [nums, new TextDecoder().decode(bytes.subarray(24 + n * 8, 24 + n * 8 + len))]; } /** - * Pset-Eigenschaft: Kennung, Art (IfcIdentifier, IfcBoolean, IfcPositiveRatioMeasure) und Wert; in einem Satz - * `Qto_…` Mengen (Länge, Fläche, Volumen) — Rust schreibt daraus je Bauteil einen IfcElementQuantity. + * Baut aus einem Projekt einen vollständigen IFC-SPF-String (IFC4, oder IFC2x3 mit `options.schema`). Kein + * Datei-IO. Leeres Projekt ⇒ valider Minimal-IFC (Project/Site/Building). Georeferenziert (`geoAnchor`): + * Geometrie in LV95. Verlangt das geladene Format-Modul (`await loadFileio()`). */ -type PropIn = - | { name: string; ident: string } - | { name: string; bool: boolean } - | { name: string; ratio: number } - | { name: string; length: number } - | { name: string; area: number } - | { name: string; volume: number }; -interface PsetIn { - name: string; - props: PropIn[]; -} - -/** Sammelt die Bauteile als Zahlenpuffer + Zeichenkettenliste. */ -class FlatIfc { - private nums: number[] = [FLAT_VERSION]; - private strings: string[] = []; - - private str(s: string): number { - this.strings.push(s.replace(/\0/g, "")); - return this.strings.length - 1; - } - private optStr(s: string | null): number { - return s === null ? -1 : this.str(s); - } - private pts(pts: readonly Vec2[]): void { - this.nums.push(pts.length); - for (const p of pts) this.nums.push(p.x, p.y); - } - private mesh(positions: readonly number[], indices: readonly number[], closed: boolean): void { - this.nums.push(positions.length / 3); - for (let i = 0; i < positions.length; i++) this.nums.push(positions[i]); - this.nums.push(indices.length / 3); - for (let i = 0; i < indices.length; i++) this.nums.push(indices[i]); - this.nums.push(closed ? 1 : 0); - } - private typeRef(t: TypeRefIn | null): void { - if (!t) { - this.nums.push(0); - return; - } - this.nums.push(1, t.kind, this.str(t.id), this.str(t.name), this.str(t.predefined), t.layers.length); - for (const l of t.layers) this.nums.push(this.str(l.componentId), this.str(l.componentName), l.thickness); - } - private psets(list: readonly PsetIn[]): void { - this.nums.push(list.length); - for (const ps of list) { - this.nums.push(this.str(ps.name), ps.props.length); - for (const p of ps.props) { - if ("ident" in p) this.nums.push(this.str(p.name), 0, this.str(p.ident)); - else if ("bool" in p) this.nums.push(this.str(p.name), 1, p.bool ? 1 : 0); - else if ("ratio" in p) this.nums.push(this.str(p.name), 2, p.ratio); - else if ("length" in p) this.nums.push(this.str(p.name), 3, p.length); - else if ("area" in p) this.nums.push(this.str(p.name), 4, p.area); - else this.nums.push(this.str(p.name), 5, p.volume); - } - } - } - - meta(m: { - projectId: string; - projectName: string; - now: number; - iso: string; - hasGeo: boolean; - refElevation: number | null; - /** WGS84-Grad des Bezugspunkts (nur IFC2x3-Site); `null` = keine. */ - refLatLon: { lat: number; lon: number } | null; - schema: IfcSchema; - storeys: { id: string; name: string; base: number }[]; - }): void { - this.nums.push( - this.str(m.projectId), - this.str(m.projectName), - m.now, - this.str(m.iso), - m.hasGeo ? 1 : 0, - m.refElevation ?? Number.NaN, - m.refLatLon?.lat ?? Number.NaN, - m.refLatLon?.lon ?? Number.NaN, - m.schema === "IFC2X3" ? 1 : 0, - m.storeys.length, - ); - for (const s of m.storeys) this.nums.push(this.str(s.id), this.str(s.name), s.base); - } - - /** - * 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); - this.nums.push(s.zRel, s.depth); - } - } - - wallMesh(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], positions: number[], indices: number[], closed: boolean): void { - this.nums.push(REC_WALL_MESH, structure, this.str(id), this.str(name)); - this.typeRef(ty); - this.psets(psets); - this.mesh(positions, indices, closed); - } - - ceiling(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], outline: Vec2[], inner: readonly (readonly Vec2[])[], zRel: number, depth: number): void { - this.nums.push(REC_CEILING, structure, this.str(id), this.str(name)); - this.typeRef(ty); - this.psets(psets); - this.pts(outline); - this.nums.push(inner.length); - for (const ring of inner) this.pts(ring); - this.nums.push(zRel, depth); - } - - opening(o: { - wallId: string; - structure: number; - openingId: string; - isDoor: boolean; - fillName: string; - voidRect: Vec2[]; - voidZRel: number; - depth: number; - width: number; - fill: FillParams; - 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, o.width); - // FILL (Kopf von `ifc_export.rs`): Parameter, die Rust zu Körpern und Ausführung rechnet. - const f = o.fill; - const opt = (v: number | null | undefined) => this.nums.push(v == null ? 0 : 1, v ?? 0); - this.nums.push(f.wallStart.x, f.wallStart.y, f.wallEnd.x, f.wallEnd.y, f.from, f.to, f.zBottom, f.zTop, f.nLo, f.nHi); - opt(f.frameDepth); - opt(f.inset); - this.nums.push(f.insetOutside ? 1 : 0); - opt(f.frameWidth); - this.nums.push(f.wingCount, f.panes, f.sashes.length); - for (const s of f.sashes) { - this.nums.push(s.post ? 1 : 0); - opt(s.postWidth); - this.nums.push(s.fixed ? 1 : 0); - opt(s.width); - } - this.nums.push(f.doorKind, f.leafCount, f.swingSign, f.dirSign, f.hingeAtStart ? 1 : 0, f.transomHeight, f.glazed ? 1 : 0); - opt(f.glazingRatio); - this.psets(o.psets); - } - - stair(structure: number, id: string, predefined: string, footprint: Vec2[], zRel: number, depth: number, parts: StairParts): void { - this.nums.push(REC_STAIR, structure, this.str(id), this.str(predefined)); - this.pts(footprint); - this.nums.push(zRel, depth); - this.psets([]); - this.nums.push(parts.flights.length); - for (const f of parts.flights) { - this.nums.push(this.str(f.name), f.risers, f.treads, f.riserHeight, f.treadLength, this.str(f.predefined)); - this.psets(qto("Qto_StairFlightBaseQuantities", f.quantities)); - if (f.mesh) { - this.nums.push(1); - this.mesh(f.mesh.positions, f.mesh.indices, false); - } else { - const solids = f.solids ?? []; - this.nums.push(0, solids.length); - for (const s of solids) { - this.pts(s.pts); - this.nums.push(s.zRel, s.depth); - } - } - } - if (parts.landing) { - const l = parts.landing; - this.nums.push(1, this.str(l.name)); - this.pts(l.pts); - this.nums.push(l.zRel, l.depth); - this.psets(qto("Qto_SlabBaseQuantities", l.quantities)); - } else { - this.nums.push(0); - } - if (parts.rail) { - const r = parts.rail; - this.nums.push(1, this.str(r.name), this.str(r.predefined)); - this.psets(qto("Qto_RailingBaseQuantities", r.quantities)); - this.mesh(r.mesh.positions, r.mesh.indices, false); - } else { - this.nums.push(0); - } - } - - extrusion(structure: number, id: string, pts: Vec2[], zRel: number, depth: number): void { - this.nums.push(REC_EXTRUSION, structure, this.str(id)); - this.pts(pts); - this.nums.push(zRel, depth); - } - - space(s: { - structure: number; - id: string; - name: string; - longName: string; - external: boolean; - height: number; - boundary: Vec2[]; - netArea: number; - grossArea: number; - siaCategory: string; - psets: PsetIn[]; - }): void { - this.nums.push(REC_SPACE, s.structure, this.str(s.id), this.str(s.name), this.str(s.longName), s.external ? 1 : 0, s.height); - this.pts(s.boundary); - this.nums.push(s.netArea, s.grossArea, this.str(s.siaCategory)); - this.psets(s.psets); - } - - endSpaces(): void { - this.nums.push(REC_END_SPACES); - } - - roof(structure: number, id: string, name: string, predefined: string, ty: TypeRefIn | null, psets: PsetIn[], positions: number[], indices: number[], closed: boolean): void { - this.nums.push(REC_ROOF, structure, this.str(id), this.str(name), this.str(predefined)); - this.typeRef(ty); - this.psets(psets); - this.mesh(positions, indices, closed); - } - - column(c: { - structure: number; - id: string; - label: string; - footprint: Vec2[]; - zRel: number; - depth: number; - component: { id: string; name: string } | null; - psets: PsetIn[]; - }): void { - this.nums.push(REC_COLUMN, c.structure, this.str(c.id), this.str(c.label)); - this.pts(c.footprint); - this.nums.push(c.zRel, c.depth, this.optStr(c.component?.id ?? null), this.optStr(c.component?.name ?? null)); - this.psets(c.psets); - } - - endColumns(): void { - this.nums.push(REC_END_COLUMNS); - } - - /** Zone (IfcZone) mit den Räumen `spaceIds`; `key` ergibt die dauerhafte GUID. */ - zone(key: string, name: string, longName: string, spaceIds: readonly string[], psets: PsetIn[]): void { - this.nums.push(REC_ZONE, this.str(key), this.str(name), this.str(longName), spaceIds.length); - for (const id of spaceIds) this.nums.push(this.str(id)); - this.psets(psets); - } - - /** Psets/Mengen an ein geschriebenes Bauteil (Schlüssel wie für seine GUID, z. B. `storey/`). */ - attach(key: string, psets: PsetIn[]): void { - this.nums.push(REC_ATTACH, this.str(key)); - this.psets(psets); - } - - /** Ein Klassifikationssystem mit Zuordnungen (Bauteil-Schlüssel → Code, Name der Referenz). */ - classification(system: ClassificationSystem, refs: readonly { key: string; code: string; name: string }[]): void { - if (refs.length === 0) return; - this.nums.push(REC_CLASSIFICATION, this.str(system.name), this.str(system.source), this.str(system.edition), refs.length); - for (const r of refs) this.nums.push(this.str(r.key), this.str(r.code), this.str(r.name)); - } - - /** Argumente für die Rust-Bindung: `[Zahlenpuffer, Zeichenketten durch \0 getrennt]`. */ - args(): [Float64Array, string] { - return [new Float64Array(this.nums), this.strings.join("\0")]; - } -} - -// ── Geometrie-Helfer (reines 2D-Vec2-Rechnen, Welt-Meter) ─────────────────── - -function sub(a: Vec2, b: Vec2): Vec2 { - return { x: a.x - b.x, y: a.y - b.y }; -} -function normalize(v: Vec2): Vec2 { - const len = Math.hypot(v.x, v.y) || 1; - return { x: v.x / len, y: v.y / len }; -} -function leftNormal(u: Vec2): Vec2 { - return { x: -u.y, y: u.x }; -} -function addScaled(p: Vec2, d: Vec2, s: number): Vec2 { - return { x: p.x + d.x * s, y: p.y + d.y * s }; -} -function dot(a: Vec2, b: Vec2): number { - return a.x * b.x + a.y * b.y; -} - -/** Rechteck `[from,to]` entlang der Wandachse × `[nLo,nHi]` quer dazu (Welt-XY, CCW). */ -function axisRect(wall: Wall, from: number, to: number, nLo: number, nHi: number): Vec2[] { - const u = normalize(sub(wall.end, wall.start)); - const n = leftNormal(u); - const a = addScaled(wall.start, u, from); - const b = addScaled(wall.start, u, to); - return [addScaled(a, n, nLo), addScaled(b, n, nLo), addScaled(b, n, nHi), addScaled(a, n, nHi)]; -} - -/** Öffnung einer Wand, wie sie das 3D als Loch in die Bänder stanzt (Achs-Intervall + absolute Z). */ -interface WallCutout { - opening: Opening; - from: number; - to: number; - zBottom: number; - zTop: number; -} - -/** Toleranz des Rust-Kerns (`wall_bands.rs::EPS`) für „Öffnung trifft Band". */ -const BAND_EPS = 1e-4; - -/** - * Ob die Schicht-Bänder einer Wand exakt „Quader minus Öffnungen" sind: kein Band mit schräger - * Oberkante, und jedes Band trägt genau die Öffnungen als Löcher, die es in der Höhe trifft — in - * derselben Grösse (kein Laibungs-Rücksprung o. ä.). Dann ergibt Extrusion je Band minus - * IfcOpeningElement denselben Körper wie das 3D-Mesh. - */ -function bandsMatchOpenings(wall: Wall, bands: readonly RWall[], cutouts: readonly WallCutout[]): boolean { - const u = normalize(sub(wall.end, wall.start)); - const byFrom = (p: number[], q: number[]) => p[0] - q[0] || p[2] - q[2]; - for (const b of bands) { - if (b.topDrop && (Math.abs(b.topDrop[0]) > 1e-9 || Math.abs(b.topDrop[1]) > 1e-9)) return false; - const a = dot({ x: b.start[0] - wall.start.x, y: b.start[1] - wall.start.y }, u); - const zb = b.baseElevation; - const zt = b.baseElevation + b.height; - const expected = cutouts - .filter((h) => h.zTop > zb + BAND_EPS && h.zBottom < zt - BAND_EPS) - .map((h) => [h.from - a, h.to - a, h.zBottom, h.zTop]) - .sort(byFrom); - const actual = (b.holes ?? []).map((h) => [h.from, h.to, h.zBottom, h.zTop]).sort(byFrom); - if (expected.length !== actual.length) return false; - for (let i = 0; i < expected.length; i++) { - for (let k = 0; k < 4; k++) if (!(Math.abs(expected[i][k] - actual[i][k]) <= 1e-6)) return false; - } - } - return true; -} - -/** - * Vereinfachter Bounding-Footprint einer Treppe (bewusst NICHT die echte - * Stufen-/Podestkontur, siehe Dateikopf): - * • "straight" — echtes, ausgerichtetes Lauf-Rechteck (Länge × Breite). - * • "L"/"spiral" — achsenausgerichtete Bounding-Box der Kontrollpunkte - * (Start/Eckpunkt/Ende bzw. Wendel-Zentrum±Radius), um die halbe - * Laufbreite erweitert. - */ -function stairFootprint(stair: Stair): Vec2[] { - const halfW = Math.max(stair.width, 0) / 2; - if (stair.shape === "straight") { - const u = normalize(stair.dir); - const n = leftNormal(u); - const end = addScaled(stair.start, u, stair.runLength); - return [ - addScaled(stair.start, n, -halfW), - addScaled(end, n, -halfW), - addScaled(end, n, halfW), - addScaled(stair.start, n, halfW), - ]; - } - const pts: Vec2[] = [stair.start]; - const u = normalize(stair.dir); - const corner = addScaled(stair.start, u, stair.runLength); - pts.push(corner); - if (stair.shape === "L" && stair.run2Length && stair.turn) { - const n = leftNormal(u); - const turnDir: Vec2 = { x: n.x * stair.turn, y: n.y * stair.turn }; - pts.push(addScaled(corner, turnDir, stair.run2Length)); - } - if (stair.shape === "spiral" && stair.center) { - const r = (stair.radius ?? 0) + halfW; - const c = stair.center; - return [ - { x: c.x - r, y: c.y - r }, - { x: c.x + r, y: c.y - r }, - { x: c.x + r, y: c.y + r }, - { x: c.x - r, y: c.y + r }, - ]; - } - let minX = Infinity; - let minY = Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - for (const p of pts) { - minX = Math.min(minX, p.x); - minY = Math.min(minY, p.y); - maxX = Math.max(maxX, p.x); - maxY = Math.max(maxY, p.y); - } - minX -= halfW; - minY -= halfW; - maxX += halfW; - maxY += halfW; - return [ - { x: minX, y: minY }, - { x: maxX, y: minY }, - { x: maxX, y: maxY }, - { x: minX, y: maxY }, - ]; -} - -// ── IFC4-Export ────────────────────────────────────────────────────────────── - -/** Wie weit der Öffnungskörper beidseits über die Wandflächen vorsteht (keine koplanaren Booleans). */ -const OPENING_OVERSHOOT = 0.02; - -const ROOF_PREDEFINED: Record = { - flach: "FLAT_ROOF", - pult: "SHED_ROOF", - sattel: "GABLE_ROOF", - walm: "HIP_ROOF", - mansarde: "MANSARD_ROOF", - zelt: "HIPPED_GABLE_ROOF", -}; - -const identifier = (name: string, v: string): PropIn => ({ name, ident: v }); - -/** Basismengen als Pset `Qto_…` (nur wenn Mengen vorliegen). */ -function qto(name: string, quantities: readonly Qty[]): PsetIn[] { - if (quantities.length === 0) return []; - return [ - { - name, - props: quantities.map((x): PropIn => (x.kind === "length" ? { name: x.name, length: x.value } : x.kind === "area" ? { name: x.name, area: x.value } : { name: x.name, volume: x.value })), - }, - ]; -} - -/** - * Baut aus einem Projekt einen vollständigen IFC-SPF-String (IFC4, oder IFC2x3 mit `options.schema`; STEP Physical - * File). Kein Datei-IO. Leeres Projekt ⇒ valider Minimal-IFC (Project/Site/Building, kein Crash). - * Verlangt das geladene Format-Modul (`await loadFileio()`). - */ -export function exportIfcSpf(projectIn: Project, options: IfcExportOptions = {}): string { - // Georeferenziert exportieren: ist ein Standort-Bezug gesetzt (geoAnchor), - // wird die gesamte Geometrie auf die ECHTEN LV95-Weltkoordinaten verschoben, - // damit die IFC-Datei in anderer Software lagerichtig sitzt — auch wenn das - // Modell lokal nahe (0,0) bearbeitet wurde (s. projectToWorldCoords / der - // „Neuer Bezugspunkt"-Workflow). Ohne Bezug bleibt alles lokal (Identität). - const project = projectToWorldCoords(projectIn); - const flat = new FlatIfc(); - - // Je "floor"-Geschoss ein IfcBuildingStorey (Elevation = baseElevation). - const floors = project.drawingLevels.filter((l) => l.kind === "floor"); - const storeyIndexByFloorId = new Map(); - const storeyBase: number[] = []; - floors.forEach((floor, i) => { - storeyIndexByFloorId.set(floor.id, i); - storeyBase.push(floor.baseElevation ?? 0); - }); - /** Geschoss → Index der Trägerstruktur, oder −1 = Gebäude (verwaiste floorId). */ - const structureOf = (floorId: string): number => storeyIndexByFloorId.get(floorId) ?? -1; - const baseOf = (structure: number): number => (structure < 0 ? 0 : storeyBase[structure]); - - // RefElevation (m ü. M.): reale Datumshöhe des Standorts aus dem Georeferenzierungs-Bezug (wie - // ArchiCADs Vermessungspunkt). Rein informativ — die Geometrie wird NICHT verschoben. - const refElevation = project.geoAnchor?.height; - flat.meta({ - projectId: project.id, - projectName: project.name ?? "", - now: Math.floor(Date.now() / 1000), - iso: new Date().toISOString().replace(/\.\d+Z$/, ""), - hasGeo: !!project.geoAnchor, - refElevation: typeof refElevation === "number" ? refElevation : null, - refLatLon: refLatLon(project.geoAnchor?.lv95), - schema: options.schema === "IFC2X3" ? "IFC2X3" : "IFC4", - storeys: floors.map((f, i) => ({ id: f.id, name: f.name, base: storeyBase[i] })), - }); - - // Klassifikation: je Bauteil, das geschrieben wird, Schlüssel (wie für die GUID), Art und Ebene sammeln; - // Rust überspringt Schlüssel ohne geschriebenes Bauteil (degenerierte Wand, Öffnung ohne Körper …). - const classified: { key: string; kind: ClassifiedKind; categoryCode: string | undefined }[] = []; - const classify = (key: string, kind: ClassifiedKind, categoryCode: string | undefined): void => { - classified.push({ key, kind, categoryCode }); - }; - - const componentName = (componentId: string): string => - project.components.find((c) => c.id === componentId)?.name ?? componentId; - const typeRef = ( - kind: TypeKind, - predefined: string, - t: { id: string; name: string; layers: { componentId: string; thickness: number }[] }, - ): TypeRefIn => ({ - kind, - id: t.id, - name: t.name, - predefined, - layers: t.layers.map((l) => ({ componentId: l.componentId, componentName: componentName(l.componentId), thickness: l.thickness })), - }); - - // ── Wände ────────────────────────────────────────────────────────────── - // Die Wand-Schicht-Bänder kommen aus DEMSELBEN geflachten Modell wie STL/OBJ - // (`pickGeometry`, Joins/Gehrungen + Öffnungs-`holes` bereits aufgelöst). - // - // Extrusions-Weg (s. Dateikopf): je Band ein Rechteck-Profil (Achse ± halbe Banddicke) - // von der Band-UK über die Bandhöhe; die Öffnungen schneidet der Viewer über RelVoids. - // - // Mesh-Weg: alle Bänder einer Wand-Id zu EINEM Face-Set. IFC-Koordinaten: das - // Mesh liegt in Welt (Modell-x, Höhe, Modell-y) mit Y-up → IFC (x, y, z=Höhe) - // mit Z-up, also (mx, mz, my); Z relativ zur Geschoss-UK, damit die Storey- - // Placement-Elevation nicht doppelt zählt. - // WICHTIG — WICKLUNG: der Achsen-Swap (x,y,z)→(x,z,y) ist eine REFLEXION - // (Determinante −1) und KEHRT die Dreiecks-Wicklung UM → aus aussen orientierten - // würden innen orientierte Normalen, der Viewer cullt dann die Vorderseiten und - // die Wand wirkt HOHL/offen. Deshalb wird beim Swap die Wicklung jedes Dreiecks - // umgedreht (i0,i2,i1). Watertightness (isWatertight) misst das anschliessend am - // fertigen IFC-Mesh → treibt das Closed-Flag des Face-Sets. - const bandsByWallId = new Map(); - for (const band of pickGeometry(project).walls) { - const list = bandsByWallId.get(band.wallId); - if (list) list.push(band); - else bandsByWallId.set(band.wallId, [band]); - } - const cutoutsOf = (wall: Wall): WallCutout[] => { - const out: WallCutout[] = []; - for (const opening of openingsOfWall(project, wall.id)) { - const iv = openingInterval(wall, opening); - if (!iv) continue; - const v = openingVerticalExtent(project, wall, opening); - out.push({ opening, from: iv.from, to: iv.to, zBottom: v.zBottom, zTop: v.zTop }); - } - return out; - }; - /** Name, Typ und Pset einer Wand (verwaister Wandtyp: Roh-ID als Name, kein Typ); `quantities` = Basismengen. */ - const wallIdentity = (wall: Wall, quantities: readonly Qty[]): { name: string; ty: TypeRefIn | null; psets: PsetIn[] } => { - const qtoSets = qto("Qto_WallBaseQuantities", quantities); - try { - const wt = getWallType(project, wall); - return { - name: wt.name, - ty: typeRef(0, "STANDARD", wt), - psets: [{ name: "Pset_WallCommon", props: [identifier("Reference", wt.name)] }, ...qtoSets], - }; - } catch { - return { name: wall.id, ty: null, psets: qtoSets }; - } - }; - /** Ausdehnung aller Bänder quer zur Wandachse (entlang der linken Normalen ab `wall.start`). */ - const crossExtent = (wall: Wall, bands: readonly RWall[]): { nLo: number; nHi: number } => { - const n = leftNormal(normalize(sub(wall.end, wall.start))); - let nLo = Infinity; - let nHi = -Infinity; - for (const b of bands) { - const off = dot({ x: b.start[0] - wall.start.x, y: b.start[1] - wall.start.y }, n); - nLo = Math.min(nLo, off - b.thickness / 2); - nHi = Math.max(nHi, off + b.thickness / 2); - } - return { nLo, nHi }; - }; - - const meshWalls: { wall: Wall; bands: RWall[] }[] = []; - const hostExtent = new Map(); - const cutoutsByWallId = new Map(); - for (const wall of project.walls ?? []) { - const bands = (bandsByWallId.get(wall.id) ?? []).filter( - (b) => Math.hypot(b.end[0] - b.start[0], b.end[1] - b.start[1]) > 1e-9 && b.height > 1e-9 && b.thickness > 1e-9, - ); - if (bands.length === 0) continue; // degenerierte Wand / keine Geometrie - const cutouts = cutoutsOf(wall); - cutoutsByWallId.set(wall.id, cutouts); - classify(`wall/${wall.id}`, "wall", wall.categoryCode); - if (!bandsMatchOpenings(wall, bands, cutouts)) { - meshWalls.push({ wall, bands: bandsByWallId.get(wall.id)! }); - continue; - } - const structure = structureOf(wall.floorId); - const solids = bands.map((b) => { - const s: Vec2 = { x: b.start[0], y: b.start[1] }; - const e: Vec2 = { x: b.end[0], y: b.end[1] }; - const n = leftNormal(normalize(sub(e, s))); - const h = b.thickness / 2; - const rect = [addScaled(s, n, -h), addScaled(e, n, -h), addScaled(e, n, h), addScaled(s, n, h)]; - return { pts: rect, zRel: b.baseElevation - baseOf(structure), depth: b.height }; - }); - const id = wallIdentity(wall, wallQuantities(wall, bands, cutouts)); - // Wandsystem: Placement am Wandanfang, X = Achse, Y = linke Normale; die Schichten des Typs - // stehen ab der Aussenfläche (negative Normale) nebeneinander — IfcMaterialLayerSetUsage nur, - // wenn ihre Summe dem Querschnitt der Bänder entspricht (sonst wäre der Offset gelogen). - 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); - const cutOf = new Map(); - wallCutMeshes(meshBands).forEach((m, i) => cutOf.set(meshBands[i], m)); - for (const { wall, bands } of meshWalls) { - const structure = structureOf(wall.floorId); - const positions: number[] = []; - const indices: number[] = []; - for (const band of bands) { - const cut = cutOf.get(band); - if (!cut) continue; - const base = positions.length / 3; - for (let i = 0; i < cut.positions.length; i += 3) { - positions.push(cut.positions[i], cut.positions[i + 2], cut.positions[i + 1] - baseOf(structure)); - } - // Wicklung umkehren (Reflexions-Ausgleich, s. o.): (a,b,c) → (a,c,b). - for (let i = 0; i < cut.indices.length; i += 3) { - indices.push(base + cut.indices[i], base + cut.indices[i + 2], base + cut.indices[i + 1]); - } - } - if (indices.length === 0) continue; - // Closed=.T. NUR wenn das Mesh nachweislich ein dichtes, aussen orientiertes Volumen ist - // (Wände sind extrudierte Querschnitts-Polygone → geschlossene Körper); der Guard fängt echte - // Defekte ab (invertierte Wicklung → Volumen < 0 → `$`). - const closed = isWatertight({ positions, indices }); - // Netto: Volumen des Netzes (Öffnungen samt Laibungen schon ausgestanzt); ohne dichtes Netz Quader minus Löcher. - const meshBandsOfWall = bandsByWallId.get(wall.id)!; - const net = closed ? meshVolume(positions, indices) : undefined; - const quantities = wallQuantities(wall, meshBandsOfWall, cutoutsByWallId.get(wall.id) ?? [], net); - if (net === undefined) { - const gross = quantities.find((x) => x.name === "GrossVolume")!.value; - quantities.find((x) => x.name === "NetVolume")!.value = Math.max(0, gross - holeVolume(meshBandsOfWall)); - } - const id = wallIdentity(wall, quantities); - flat.wallMesh(structure, wall.id, id.name, id.ty, id.psets, positions, indices, closed); - hostExtent.set(wall.id, crossExtent(wall, bandsByWallId.get(wall.id)!)); - } - - // ── Decken ───────────────────────────────────────────────────────────── - for (const ceiling of project.ceilings ?? []) { - if (ceiling.outline.length < 3) continue; - const { zBottom, zTop } = ceilingVerticalExtent(project, ceiling); - const structure = structureOf(ceiling.floorId); - classify(`slab/${ceiling.id}`, "slab", ceiling.categoryCode); - let name: string = ceiling.id; - let ty: TypeRefIn | null = null; - const psets: PsetIn[] = []; - try { - const ct = getCeilingType(project, ceiling); - name = ct.name; - ty = typeRef(1, "FLOOR", ct); - psets.push({ name: "Pset_SlabCommon", props: [identifier("Reference", ct.name)] }); - } catch { - /* verwaister Deckentyp — Roh-ID als Name, kein Typ */ - } - // Aussparungen (wie im 3D) als innere Ringe des Profils; Mengen: Netto zieht sie ab. - const inner = (ceiling.openings ?? []).filter((ring) => ring.length >= 3); - psets.push(...qto("Qto_SlabBaseQuantities", slabQuantities(ceiling.outline, inner, zTop - zBottom))); - flat.ceiling(structure, ceiling.id, name, ty, psets, ceiling.outline, inner, zBottom - baseOf(structure), zTop - zBottom); - } - - // ── Öffnungen: IfcOpeningElement in der Wand, IfcDoor/IfcWindow darin ─── - // 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) hat ein eigenes Placement - // (Öffnungsmitte, Achse bzw. Aufschlagrichtung) und liegt in der Rahmentiefe (`ifc_openings.rs`). - for (const wall of project.walls ?? []) { - const host = hostExtent.get(wall.id); - if (!host) continue; // Wirtswand übersprungen (degeneriert) - const structure = structureOf(wall.floorId); - for (const c of cutoutsByWallId.get(wall.id) ?? []) { - const { opening } = c; - const depth = c.zTop - c.zBottom; - if (!(depth > 1e-6)) continue; - const isDoor = opening.kind === "door"; - classify(`fill/${opening.id}`, isDoor ? "door" : "window", opening.categoryCode); - const props: PropIn[] = []; - let psetName: string; - if (isDoor) { - psetName = "Pset_DoorCommon"; - const dt = getDoorType(project, opening); - if (dt) props.push(identifier("Reference", dt.name)); - const ratio = dt?.glazingRatio; - if (dt?.leafStyle === "glas" && typeof ratio === "number" && ratio > 0 && ratio <= 1) { - props.push({ name: "GlazingAreaFraction", ratio }); - } - } else { - psetName = "Pset_WindowCommon"; - const wt = getWindowType(project, opening); - if (wt) props.push(identifier("Reference", wt.name)); - } - flat.opening({ - wallId: wall.id, - structure, - openingId: opening.id, - isDoor, - fillName: openingLabel(opening), - voidRect: axisRect(wall, c.from, c.to, host.nLo - OPENING_OVERSHOOT, host.nHi + OPENING_OVERSHOOT), - voidZRel: c.zBottom - baseOf(structure), - depth, - width: c.to - c.from, - fill: fillParams(project, wall, opening, c, host), - psets: [{ name: psetName, props }, ...qto(isDoor ? "Qto_DoorBaseQuantities" : "Qto_WindowBaseQuantities", openingQuantities(c.to - c.from, depth))], - }); - } - } - - // ── Treppen: Läufe, Podest, Geländer wie im 3D (`ifcStairs.ts`); ohne Teile der Fussabdruck-Quader ── - for (const stair of project.stairs ?? []) { - const footprint = stairFootprint(stair); - if (footprint.length < 3) continue; - const { zBottom, zTop } = stairVerticalExtent(project, stair); - const structure = structureOf(stair.floorId); - classify(`stair/${stair.id}`, "stair", stair.categoryCode); - const predefined = stair.shape === "straight" ? "STRAIGHT_RUN_STAIR" : stair.shape === "spiral" ? "SPIRAL_STAIR" : "QUARTER_TURN_STAIR"; - flat.stair(structure, stair.id, predefined, footprint, zBottom - baseOf(structure), zTop - zBottom, stairParts(project, stair, baseOf(structure))); - } - - // ── Extrudierte Körper (truck-Integration) → IfcBuildingElementProxy ─── - for (const solid of project.extrudedSolids ?? []) { - if (solid.points.length < 3) continue; - const floor = floors.find((f) => f.id === solid.levelId); - const base = floor?.baseElevation ?? 0; - const structure = structureOf(solid.levelId); - flat.extrusion(structure, solid.id, solid.points, base - baseOf(structure), solid.height); - } - - // ── Räume → IfcSpace ─────────────────────────────────────────────────── - // Je Raum ein IfcSpace (Name = Raumnummer, LongName = Raumname), als Extrusion der lichten - // Innenkontur über die lichte Geschosshöhe. Räume sind räumliche Elemente: sie werden im - // Geschoss AGGREGIERT (IfcRelAggregates), nicht enthalten. Dazu Basismengen - // (Qto_SpaceBaseQuantities), die SIA-416-Kategorie als Eigenschaft und Pset_SpaceCommon - // (AGF = Aussengeschossfläche ⇒ aussen, alles andere innen). - const roomAreas: { id: string; floorId: string; category: SiaCategory; area: number }[] = []; - for (const room of project.rooms ?? []) { - if (room.boundary.length < 3) continue; - const structure = structureOf(room.floorId); - const floor = floors.find((f) => f.id === room.floorId); - const height = floor?.floorHeight && floor.floorHeight > 0 ? floor.floorHeight : 2.5; - const external = room.siaCategory === "AGF"; - const area = evaluateRoom(room.boundary, room.siaCategory); - roomAreas.push({ id: room.id, floorId: room.floorId, category: room.siaCategory, area: area.netArea }); - classify(`space/${room.id}`, "space", room.categoryCode); - const common: PropIn[] = []; - if (room.stamp?.number) common.push(identifier("Reference", room.stamp.number)); - common.push({ name: "IsExternal", bool: external }); - flat.space({ - structure, - id: room.id, - name: room.stamp?.number || room.id, - longName: room.name, - external, - height, - boundary: room.boundary, - netArea: area.netArea, - grossArea: area.grossArea, - siaCategory: room.siaCategory, - psets: [{ name: "Pset_SpaceCommon", props: common }], - }); - } - flat.endSpaces(); - - // SIA 416 ([70], [B5]): je vorkommender Kategorie eine IfcZone mit den Räumen. Kategorie als Eigenschaft - // (`CH_Zone.SIA416`, die der Import wieder liest), Summe der Nettoflächen als Menge. - for (const cat of SIA_CATEGORIES) { - const members = roomAreas.filter((r) => r.category === cat); - if (members.length === 0) continue; - const net = members.reduce((a, r) => a + r.area, 0); - flat.zone( - `sia416/${cat}`, - cat, - siaLabel(cat), - members.map((r) => r.id), - [ - { name: "CH_Zone", props: [identifier("SIA416", cat)] }, - { name: "CH_Qto_SIA416", props: [{ name: "NetFloorArea", area: Math.max(0, net) }] }, - ], - ); - } - // Geschoss-Kennwerte: GF/NGF als Basismenge des IfcBuildingStorey, alle SIA-416-Flächen als CH_Qto_SIA416. - for (const floor of floors) { - const rooms = roomAreas.filter((r) => r.floorId === floor.id); - if (rooms.length === 0) continue; - const bal = balance(rooms.map((r) => ({ category: r.category, area: r.area }))); - const keys = ["HNF", "NNF", "NF", "VF", "FF", "NGF", "KGF", "AGF", "GF"] as const; - flat.attach(`storey/${floor.id}`, [ - { - name: "Qto_BuildingStoreyBaseQuantities", - props: [ - { name: "GrossFloorArea", area: Math.max(0, bal.byKey.GF) }, - { name: "NetFloorArea", area: Math.max(0, bal.byKey.NGF) }, - ], - }, - { name: "CH_Qto_SIA416", props: keys.map((k): PropIn => ({ name: k, area: Math.max(0, bal.byKey[k]) })) }, - ]); - } - - // ── Dächer → IfcRoof ─────────────────────────────────────────────────── - // Dieselben geschlossenen Schicht-Meshes wie das 3D (`emitRoofs`: Dachflächen je Schicht, - // an First/Grat gehrt), zu EINEM Face-Set je Dach vereint. Modell-Koordinaten sind bereits - // Z-oben (kein Achsentausch wie bei den Wänden); die Wicklung wird so gewählt, dass das Volumen - // positiv ist — nur dann ist das Face-Set als geschlossen markiert. - for (const roof of project.roofs ?? []) { - const structure = structureOf(roof.floorId); - classify(`roof/${roof.id}`, "roof", roof.categoryCode); - const positions: number[] = []; - const indices: number[] = []; - for (const mesh of emitRoofs({ ...project, roofs: [roof] })) { - const base = positions.length / 3; - for (let i = 0; i < mesh.positions.length; i += 3) { - positions.push(mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2] - baseOf(structure)); - } - for (const ix of mesh.indices) indices.push(base + ix); - } - if (indices.length === 0) continue; - let closed = isWatertight({ positions, indices }); - if (!closed) { - const flipped: number[] = []; - for (let i = 0; i < indices.length; i += 3) flipped.push(indices[i], indices[i + 2], indices[i + 1]); - if (isWatertight({ positions, indices: flipped })) { - indices.splice(0, indices.length, ...flipped); - closed = true; - } - } - const predefined = ROOF_PREDEFINED[roof.shape] ?? "NOTDEFINED"; - const roofType = roof.roofTypeId ? (project.roofTypes ?? []).find((t) => t.id === roof.roofTypeId) : undefined; - // Ein Dach ist Gebäudehülle: IsExternal folgt aus der Bauteilart, nicht aus einer Annahme. - const props: PropIn[] = []; - if (roofType) props.push(identifier("Reference", roofType.name)); - props.push({ name: "IsExternal", bool: true }); - // Mengen aus den geneigten Dachflächen (Aussenseite), wie sie auch das Netz erzeugen. - const planes = roofGeometry(roof, roofBaseElevation(project, roof)).planes.map((pl) => pl.pts); - flat.roof( - structure, - roof.id, - roofType?.name ?? "Dach", - predefined, - roofType ? typeRef(2, predefined, roofType) : null, - [{ name: "Pset_RoofCommon", props }, ...qto("Qto_RoofBaseQuantities", roofQuantities(planes))], - positions, - indices, - closed, - ); - } - - // ── Stützen → IfcColumn (Profil-Extrusion, Material = Bauteil) ────────── - for (const col of project.columns ?? []) { - const footprint = columnFootprint(col); - if (footprint.length < 3) continue; - const { zBottom, zTop } = columnVerticalExtent(project, col); - if (!(zTop > zBottom)) continue; - const structure = structureOf(col.floorId); - classify(`column/${col.id}`, "column", col.categoryCode); - const label = columnLabel(col); - flat.column({ - structure, - id: col.id, - label, - footprint, - zRel: zBottom - baseOf(structure), - depth: zTop - zBottom, - component: col.componentId ? { id: col.componentId, name: componentName(col.componentId) } : null, - psets: [{ name: "Pset_ColumnCommon", props: [identifier("Reference", label)] }, ...qto("Qto_ColumnBaseQuantities", columnQuantities(footprint, zTop - zBottom))], - }); - } - flat.endColumns(); - - // ── Klassifikation (Optionen), am Ende: alle Bauteile sind geschrieben ────────────── - if (options.ebkph) { - flat.classification( - EBKPH_SYSTEM, - classified.flatMap((c) => { - const g = ebkphGroup(c.kind); - return g ? [{ key: c.key, code: g.code, name: g.name }] : []; - }), - ); - } - if (options.layerCodes) { - flat.classification( - LAYER_SYSTEM, - classified.flatMap((c) => { - const l = layerClassification(project, c.categoryCode); - return l ? [{ key: c.key, code: l.code, name: l.name }] : []; - }), - ); - } - +export function exportIfcSpf(project: Project, options: IfcExportOptions = {}): string { + const now = Date.now(); + const iso = new Date(now).toISOString().replace(/\.\d+Z$/, ""); + const args = [Math.floor(now / 1000), options.schema === "IFC2X3" ? 1 : 0, options.ebkph ? 1 : 0, options.layerCodes ? 1 : 0]; + const [buf, strings] = decodeExportFlat(documentFor(project).queryBin("ifcExportData", args, iso)); const m = fileio(); - const [buf, strings] = flat.args(); const text = m.export_ifc_flat(buf, strings); if (text.length === 0) { const why = m.export_ifc_check_flat(buf, strings); diff --git a/src/export/exportIfc.validate.test.ts b/src/export/exportIfc.validate.test.ts index c25507c4..f5331604 100644 --- a/src/export/exportIfc.validate.test.ts +++ b/src/export/exportIfc.validate.test.ts @@ -9,8 +9,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import "../engine/fileioWasm.setup"; import { exportIfcSpf, ifcGuid } from "./exportIfc"; -import { pickGeometry } from "../plan/toWalls3d"; -import { wallCutMeshes } from "../plan/wallMeshCut"; +import { wallMeshVolumes } from "./meshScene.testutil"; import { sampleProject } from "../model/sampleProject"; import type { Project } from "../model/types"; @@ -202,17 +201,8 @@ describe.skipIf(!hasIfcOpenShell)("IFC-Export gegen ifcopenshell", { timeout: 60 }); it("[B5] Demo-Haus: jede Wand hat nach ifcopenshell (Öffnungen abgezogen) das Volumen des 3D-Meshes", () => { const project = sampleProject; - const bands = pickGeometry(project).walls; - const meshVolume = new Map(); - wallCutMeshes(bands).forEach((m, i) => { - let v6 = 0; - for (let k = 0; k < m.indices.length; k += 3) { - const [a, b, c] = [m.indices[k], m.indices[k + 1], m.indices[k + 2]].map((j) => m.positions.slice(j * 3, j * 3 + 3)); - v6 += a[0] * (b[1] * c[2] - b[2] * c[1]) + a[1] * (b[2] * c[0] - b[0] * c[2]) + a[2] * (b[0] * c[1] - b[1] * c[0]); - } - const id = bands[i].wallId; - meshVolume.set(id, (meshVolume.get(id) ?? 0) + Math.abs(v6) / 6); - }); + // Vergleichswert: dieselben öffnungsgenauen Wand-Netze wie im 3D/OBJ (Kern, `mesh_data.rs`). + const meshVolume = wallMeshVolumes(project); const walls = wallVolumes("demo-volumen", exportIfcSpf(project)); let swept = 0; for (const wall of project.walls) { diff --git a/src/export/exportMesh.complete.test.ts b/src/export/exportMesh.complete.test.ts index 4f9ef4bc..5af54c0a 100644 --- a/src/export/exportMesh.complete.test.ts +++ b/src/export/exportMesh.complete.test.ts @@ -1,13 +1,23 @@ // Mesh-Export vollständig ([C11], 28.10.): Dächer, Treppen, Stützen, Kontext-Meshes, ein Knoten je Öffnung, -// rechtshändige Achsen in OBJ/STL/glTF, Dreieckszahl wie die 3D-Ableitung, Khronos-Validator. +// rechtshändige Achsen in OBJ/STL/glTF, Dreieckszahl wie die 3D-Ableitung, Khronos-Validator. Die Wicklung +// (`orient_outward`) prüfen die Rust-Tests in `export_flat.rs`, hier das Volumen je Bauteil in der Datei. import { describe, it, expect } from "vitest"; import "../engine/fileioWasm.setup"; import validator from "gltf-validator"; import { exportGlb, exportGltf, exportObj, exportStl } from "./exportMesh"; -import { orientOutward } from "./meshOrient"; import { sampleProject } from "../model/sampleProject"; import type { Column, ImportedMesh, Project, TerrainMesh } from "../model/types"; -import { emitColumns, emitOpeningMeshes, emitRoofs, emitStairMeshes, emitStairRailings, emitStairs } from "./model3dParts"; +import { ProjectDocument, type QueryName } from "../core/document"; + +/** 3D-Ableitung des Kerns (`queries.rs`) auf einem eigenen Dokument — Vergleichswert für die Dreieckszahl. */ +function derive(project: Project, name: QueryName, args: number[] = []): T { + const doc = new ProjectDocument(project); + try { + return doc.query(name, args); + } finally { + doc.close(); + } +} interface Gltf { nodes: { name: string; mesh?: number; children?: number[]; extras?: { type: string; id: string } }[]; @@ -85,31 +95,6 @@ function objVolumes(obj: string): Map { return out; } -describe("orientOutward", () => { - it("dreht einen innen gewickelten Würfel nach aussen und gleicht gemischte Wicklung an", () => { - const pos = CUBE_POS; - const mixed = CUBE_IDX.slice(); - // ein Dreieck umdrehen ⇒ widersprüchliche Wicklung - [mixed[1], mixed[2]] = [mixed[2], mixed[1]]; - const inward: number[] = []; - for (let i = 0; i < CUBE_IDX.length; i += 3) inward.push(CUBE_IDX[i], CUBE_IDX[i + 2], CUBE_IDX[i + 1]); - const vol = (idx: number[]) => { - let v = 0; - for (let i = 0; i < idx.length; i += 3) { - const [a, b, c] = [idx[i] * 3, idx[i + 1] * 3, idx[i + 2] * 3]; - v += - pos[a] * (pos[b + 1] * pos[c + 2] - pos[b + 2] * pos[c + 1]) - - pos[a + 1] * (pos[b] * pos[c + 2] - pos[b + 2] * pos[c]) + - pos[a + 2] * (pos[b] * pos[c + 1] - pos[b + 1] * pos[c]); - } - return v / 6; - }; - expect(vol(CUBE_IDX)).toBeCloseTo(8, 9); - expect(vol(orientOutward(pos, inward))).toBeCloseTo(8, 9); - expect(vol(orientOutward(pos, mixed))).toBeCloseTo(8, 9); - }); -}); - describe("Mesh-Export vollständig", () => { const project = withContext(sampleProject); @@ -182,14 +167,15 @@ describe("Mesh-Export vollständig", () => { it("Dreieckszahl je Bauteilart = Summe der 3D-Ableitungen (Dach, Treppe, Stütze, Öffnungsteile)", () => { const g = glbJson(exportGlb(project)); const tris = (type: string) => g.nodes.filter((n) => n.extras?.type === type).reduce((s, n) => s + nodeTris(g, n), 0); - const meshTris = (ms: { indices: number[] }[]) => ms.reduce((s, m) => s + m.indices.length / 3, 0); - expect(tris("roof")).toBe(meshTris(emitRoofs(project))); - expect(tris("column")).toBe(meshTris(emitColumns(project))); - expect(tris("window") + tris("door")).toBe(meshTris(emitOpeningMeshes(project, "mittel"))); - const stairMeshes = meshTris(emitStairMeshes(project)) + meshTris(emitStairRailings(project)); + const meshTris = (name: QueryName, args: number[] = []) => derive<{ indices: number[] }[]>(project, name, args).reduce((s, m) => s + m.indices.length / 3, 0); + expect(tris("roof")).toBe(meshTris("roofMeshes")); + expect(tris("column")).toBe(meshTris("columnMeshes")); + expect(tris("window") + tris("door")).toBe(meshTris("openingMeshes", [1])); + const stairMeshes = meshTris("stairMeshes") + meshTris("stairRailings"); // Stufen-Prismen: jede Stufe wird zu einem Prisma (2 Kappen + Mantel) — mindestens die Mesh-Dreiecke. - expect(emitStairs(project).length).toBeGreaterThan(0); - expect(tris("stair")).toBeGreaterThanOrEqual(stairMeshes + emitStairs(project).length * 12); + const steps = derive(project, "stairSlabs", [0]).length; + expect(steps).toBeGreaterThan(0); + expect(tris("stair")).toBeGreaterThanOrEqual(stairMeshes + steps * 12); // OBJ und glTF enthalten dieselben Dreiecke const faces = exportObj(project).split("\n").filter((l) => l.startsWith("f ")).length; const all = g.nodes.reduce((s, n) => s + nodeTris(g, n), 0); @@ -209,4 +195,12 @@ describe("Mesh-Export vollständig", () => { const r2 = await validator.validateString(exportGltf(project), { maxIssues: 50 }); expect(r2.issues.numErrors).toBe(0); }); + + it("leeres Projekt: gültige Szene ohne Knoten (kein leeres `nodes`, Validator EMPTY_ENTITY)", async () => { + const empty: Project = { ...sampleProject, walls: [], openings: [], ceilings: [], roofs: [], stairs: [], rooms: [], columns: [], context: [] }; + const r1 = await validator.validateBytes(exportGlb(empty), { maxIssues: 50 }); + expect(r1.issues.messages.filter((m) => m.severity === 0)).toEqual([]); + const r2 = await validator.validateString(exportGltf(empty), { maxIssues: 50 }); + expect(r2.issues.numErrors).toBe(0); + }); }); diff --git a/src/export/exportMesh.ts b/src/export/exportMesh.ts index cfeb625d..86d600a8 100644 --- a/src/export/exportMesh.ts +++ b/src/export/exportMesh.ts @@ -1,317 +1,17 @@ -// OBJ-/STL-/glTF-Export des 3D-Gebäudemodells als Dreiecks-Mesh. Seit [C4] (28.10.) schreibt Rust die -// Datei (`src-tauri/fileio/src/mesh_export.rs`, Format-Modul pkgFileIo, vorher `await loadFileio()`): -// buildScene() liest das Projekt und sammelt Dreiecke, Materialien und Geschosse flach, exportObj()/ -// exportStl()/exportGlb()/exportGltf() rufen den Schreiber synchron auf. Kein Datei-IO hier. +// OBJ-/STL-/glTF-Export des 3D-Gebäudemodells als Dreiecks-Mesh. Seit [K4]/[C11] (29.10.) rechnet alles +// in Rust: der Kern sammelt aus dem Projekt-Dokument die Szene (`src-tauri/core/src/mesh_data.rs`, +// Abfrage `meshExportData`: ein Knoten je Bauteil, Teil-Netze je Material, Materialtabelle, +// Geschosse; Wicklung nach aussen), das Format-Modul schreibt daraus die Datei +// (`src-tauri/fileio/src/mesh_export.rs`). TS gibt nur die Optionen weiter und reicht die Bytes vom +// Kern an `fileio`. Verlangt das geladene Format-Modul (`await loadFileio()`). Kein Datei-IO hier. // -// TRIANGEL-QUELLE (bewusste v1-Entscheidung, siehe PENDENZEN): -// • Wände: pickGeometry() aus toWalls3d.ts liefert dieselben Schicht-Bänder, -// die auch der 3D-Viewer zeichnet (EIN RWall je Materiallage/Achsen- -// Teilstück, bereits mit End-Cuts/Gehrungen/Decken-Dominanz aufgelöst). -// Bänder mit Öffnungs-`holes` werden über den gemeinsamen Loch-Ausschnitt- -// Generator (`plan/wallMeshCut.ts` → Rust-Kern, Gitter-Zerlegung wie render3ds -// `extrude_layer_segment_with_holes`) ÖFFNUNGSGENAU trianguliert — die -// Fenster/Türen sind sichtbar ausgestanzt inkl. Laibungsflächen, genau wie -// im 3D-Viewer. Lochlose Bänder bleiben die klassische geteilte 8-Ecken-Box. -// • Decken: pickGeometry() liefert den Umriss + zBottom/zTop je Decke; -// der Umriss wird mit dem vorhandenen Ear-Clipping-Triangulator -// (`triangulate` aus plan/glPlan/glPlanCompile.ts, bereits getestet und -// konkav-fähig) zu Boden-/Deckenkappen trianguliert, dazwischen ein -// Seitenmantel — ein einfaches Umriss-Prisma. -// • ExtrudedSolids (truck-Profile): `src/engine/truckSolid.ts` liefert zwar -// "echte" truck-Dreiecke, ABER nur asynchron über WASM -// (`extrudePolygon`/`extrudeCircle` geben Promises zurück). Das würde die -// geforderte SYNCHRONE, WASM-freie Signatur `exportObj(project): string` -// brechen. Deshalb nutzt dieser Export stattdessen DIESELBE Prisma- -// Triangulierung wie die Decken (Umriss aus `solid.points` — bei -// Kreisprofilen bereits eine 48-Eck-Tessellierung, siehe -// `ExtrudedSolid.points`-Doc) inkl. `taper`-Verjüngung (linear zum -// Schwerpunkt skaliert, wie die truck-Extrusion es tut). Das ist eine -// bewusste Abweichung vom ursprünglichen Plan ("truckSolid-Dreiecke") zu- -// gunsten der pure-Modul-Architektur — ehrlich dokumentiert, kein -// Stillschweigen. -// -// ACHSEN-KONVENTION (intern, Weg zum Schreiber): Modell (x, y, z-hoch) → Welt (x, z, y) wie die -// Pick-/Highlight-Geometrie in toWalls3d.ts (`selectionHighlightLines`). Das ist eine Spiegelung -// des Modells; der Rust-Schreiber stellt für ALLE Formate (OBJ, STL, glTF) die Rechtshändigkeit -// her: Gesamtabbildung Modell (x, y, z-hoch) → Datei (x, z, −y), Norden = −Z. -// -// WEITERE BAUTEILE ([C11], 28.10.): Dächer, Treppen (Tritte, Laufplatte, Handlauf), Stützen, -// Öffnungsteile (je Öffnung ein Knoten), Gelände und importierte Kontext-Meshes. Quelle sind -// dieselben `emit*`-Ableitungen wie im 3D-Viewer (`projectToModel3d`). Diese liefern keine -// Bauteil-ids; deshalb wird jede Ableitung je Bauteil mit einem Projekt aufgerufen, das nur dieses -// Bauteil enthält (reines Lesen, `src/plan` bleibt unverändert). Die Ableitungen schreiben keine -// verlässliche Wicklung (render3d zeichnet doppelseitig): {@link orientOutward} richtet jedes -// geschlossene Teil nach aussen aus. +// Achsen: Datei rechtshändig, Y-up — Modell (x, y, z-hoch) → (x, z, −y), Norden = −Z, Meter. +// Dreiecks-Quelle, Prisma-Näherung der Extrusionen und Grenzen: Kopf von `mesh_data.rs`, `TODO.md` [C11]. -import type { Project, Vec2 } from "../model/types"; -import { getFloor } from "../model/types"; -import { pickGeometry } from "../plan/toWalls3d"; -import type { RWall } from "../plan/toWalls3d"; -import { wallCutMeshes, type CutMesh } from "../plan/wallMeshCut"; -import { triangulate } from "../plan/glPlan/glPlanCompile"; -import type { RMesh } from "../plan/toWalls3d/shared"; -import { IMPORTED_RGB, TERRAIN_RGB, hexToRgb } from "../plan/toWalls3d/shared"; +import type { Project } from "../model/types"; import { fileio } from "../engine/fileioWasm"; -import { orientOutward } from "./meshOrient"; -import { emitColumns, emitOpeningMeshes, emitRoofs, emitStairMeshes, emitStairRailings, emitStairs } from "./model3dParts"; - -/** - * Ein Teil-Mesh mit EINEM Material und LOKALEN (0-basierten) Vertex-/Dreiecks-Indizes. Der Rust-Schreiber - * (`mesh_export.rs`) verschiebt die Indizes beim Serialisieren auf die globale OBJ-Nummerierung. - */ -interface MeshPrim { - /** Index in die Materialtabelle (`SceneBuilder.materials`), −1 = keins. */ - material: number; - /** Flaches Weltkoordinaten-Array (x,y,z, x,y,z, …), Meter, Y-up. */ - positions: number[]; - /** Dreiecks-Indizes (3 je Dreieck), 0-basiert relativ zu `positions`. */ - indices: number[]; -} - -/** Eine Mesh-Gruppe = ein Bauteil-Vorkommen (Wand, Decke, Dach, Treppe, Öffnung …) mit ≥ 1 Teil-Mesh. */ -interface MeshGroup { - name: string; - /** Bauteilart für glTF-`extras` ("wall", "slab", "extrusion", "roof", "stair", "column", "window", "door", "terrain", "context"). */ - kind: string; - /** Bauteil-id im Modell ("" bei Sammelgruppen). */ - id: string; - /** Index in `levels` oder −1. */ - level: number; - prims: MeshPrim[]; -} - -function newGroup(name: string, kind: string, id: string, level: number): MeshGroup { - return { name, kind, id, level, prims: [] }; -} - -function newPrim(group: MeshGroup, material: number): MeshPrim { - const prim: MeshPrim = { material, positions: [], indices: [] }; - group.prims.push(prim); - return prim; -} - -/** OBJ-Gruppennamen dürfen keine Whitespaces/Sonderzeichen enthalten. */ -function sanitizeName(id: string): string { - return id.replace(/[^A-Za-z0-9_-]/g, "_") || "x"; -} - -/** - * Die 6 Quader-Seiten als Eckpunkt-Quadrupel (Index-Bits: bit0=Achse −/+, - * bit1=Höhe −/+, bit2=Dicke −/+ — dieselbe Konvention wie `emitOpeningMeshes`/ - * `selectionHighlightLines` in toWalls3d.ts), in nach AUSSEN gewundener - * Reihenfolge (für ein rechtshändiges Dreibein Achse×Höhe=Dicke-Normale, wie - * es die Wandbox-Konstruktion unten aufspannt). Jedes Quadrupel wird zu 2 - * Dreiecken (0,1,2)+(0,2,3). - */ -const BOX_QUADS: Array<[number, number, number, number]> = [ - [4, 6, 7, 5], // Dicke + - [1, 3, 2, 0], // Dicke − - [2, 3, 7, 6], // Höhe + (Wandkopf) - [4, 5, 1, 0], // Höhe − (Wand-UK) - [1, 5, 7, 3], // Achse + (Wandende) - [2, 6, 4, 0], // Achse − (Wandanfang) -]; - -/** - * Hängt EIN Wand-Schicht-Band (`RWall`, siehe toWalls3d.ts) an eine Mesh-Gruppe - * an: hat das Band echte Öffnungs-`holes`, wird das öffnungsgenaue Loch-Ausschnitt- - * Mesh `cut` (vorab für alle Bänder über {@link wallCutMeshes}) verwendet — die - * Fenster/Türen sind sichtbar ausgestanzt inkl. Laibungen, exakt wie im 3D-Viewer. - * Ohne Löcher bleibt es die klassische, geteilte 8-Ecken-Box ({@link pushWallBox}) - * (Joins/Gehrungen stecken schon in `start`/`end`). - */ -function pushWall(group: MeshPrim, w: RWall, cut: CutMesh | undefined): void { - if (cut) { - const base = group.positions.length / 3; - for (const p of cut.positions) group.positions.push(p); - for (const idx of cut.indices) group.indices.push(base + idx); - return; - } - pushWallBox(group, w); -} - -/** - * Hängt EINEN vollen Wand-Schicht-Quader (`RWall`) an eine Mesh-Gruppe an — Box - * über Achse×Höhe×Dicke, OHNE Öffnungs-Ausschnitt (nur für lochlose Bänder, siehe - * {@link pushWall}). Degenerierte Bänder (Länge/Höhe/Dicke ≤ 0) werden übersprungen. - */ -function pushWallBox(group: MeshPrim, w: RWall): void { - const [sx, sy] = w.start; - const [ex, ey] = w.end; - const dx = ex - sx; - const dz = ey - sy; - const len = Math.hypot(dx, dz); - if (len < 1e-9 || w.height <= 1e-9 || w.thickness <= 1e-9) return; - const ax = dx / len; - const az = dz / len; - // Normale = Welt-Hoch × Achse (rechtshändig), dieselbe Konvention wie - // `selectionHighlightLines`: normal = (az, 0, −ax). - const nx = az; - const nz = -ax; - const halfLen = len / 2; - const halfHeight = w.height / 2; - const halfThick = w.thickness / 2; - const cx = (sx + ex) / 2; - const cz = (sy + ey) / 2; - const cy = w.baseElevation + w.height / 2; - const base = group.positions.length / 3; - for (let i = 0; i < 8; i++) { - const sL = i & 1 ? 1 : -1; - const sH = i & 2 ? 1 : -1; - const sT = i & 4 ? 1 : -1; - group.positions.push( - cx + sL * halfLen * ax + sT * halfThick * nx, - cy + sH * halfHeight, - cz + sL * halfLen * az + sT * halfThick * nz, - ); - } - for (const [a, b, c, d] of BOX_QUADS) { - group.indices.push(base + a, base + b, base + c, base + a, base + c, base + d); - } -} - -/** Signierte Fläche eines Modell-XY-Umrisses (Shoelace); ≥0 = CCW. */ -function signedAreaXY(pts: Vec2[]): number { - let a = 0; - for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { - a += pts[j].x * pts[i].y - pts[i].x * pts[j].y; - } - return a / 2; -} - -/** - * Hängt ein extrudiertes Umriss-Prisma (Decke ODER truck-Profil-Extrusion, - * siehe Moduldoc) an eine Mesh-Gruppe an: Boden-/Deckkappe (Ear-Clipping- - * Triangulierung via `triangulate`) + Seitenmantel. `taper` (0..1) verjüngt - * den OBEREN Ring linear zum Flächenschwerpunkt — dieselbe Semantik wie - * `ExtrudedSolid.taper`/die truck-Extrusion (0 = Prisma, 1 = Spitze/Pyramide). - * Der Umriss wird intern auf CCW (Modell-XY) normalisiert, damit die - * Seitenmantel-Normalen unabhängig von der Eingabe-Wicklung nach außen zeigen. - */ -function pushPrism( - group: MeshPrim, - outline: Vec2[], - zBottom: number, - zTop: number, - taper = 0, -): void { - if (outline.length < 3 || zTop - zBottom <= 1e-9) return; - const ccw = signedAreaXY(outline) >= 0 ? outline : [...outline].reverse(); - const n = ccw.length; - let cx = 0; - let cyModel = 0; - for (const p of ccw) { - cx += p.x; - cyModel += p.y; - } - cx /= n; - cyModel /= n; - const t = Math.min(1, Math.max(0, taper)); - const base = group.positions.length / 3; - // Unterer Ring (base + 0..n-1), oberer Ring (base + n..2n-1). - for (const p of ccw) group.positions.push(p.x, zBottom, p.y); - for (const p of ccw) { - const tx = cx + (p.x - cx) * (1 - t); - const ty = cyModel + (p.y - cyModel) * (1 - t); - group.positions.push(tx, zTop, ty); - } - // Kappen: `triangulate` liefert bei CCW-Eingabe stets CCW-in-Modell-XY- - // Dreiecke — eingebettet in die Weltebene (x, const, y) entspricht das einer - // nach UNTEN (−Y) zeigenden Flächennormale (Kreuzprodukt-Herleitung siehe - // Moduldoc-Kommentar oben). Die Bodenkappe nutzt diese Wicklung direkt - // (Normale zeigt nach unten = nach außen), die Deckkappe braucht die - // umgekehrte Wicklung (Normale nach oben). - const capTris = triangulate(ccw); - for (let i = 0; i < capTris.length; i += 3) { - const a = capTris[i]; - const b = capTris[i + 1]; - const c = capTris[i + 2]; - group.indices.push(base + a, base + b, base + c); - group.indices.push(base + n + a, base + n + c, base + n + b); - } - // Seitenmantel: je Umrisskante ein Quad (2 Dreiecke), Wicklung so, dass die - // Normale nach außen zeigt (siehe Moduldoc-Herleitung). - for (let i = 0; i < n; i++) { - const j = (i + 1) % n; - const bi = base + i; - const bj = base + j; - const ti = base + n + i; - const tj = base + n + j; - group.indices.push(bi, ti, tj); - group.indices.push(bi, tj, bj); - } -} - -/** - * Hängt ein Modell-Mesh (x, y, z-hoch) an ein Teil-Mesh: Achsen nach Welt (x, z, y) und Wicklung - * nach aussen. `closed`: geschlossener Körper ⇒ {@link orientOutward}; sonst (Gelände, offene - * Importe) bleibt die Wicklung des Modells erhalten — die Achsenspiegelung kehrt sie um. - */ -function appendModelMesh(prim: MeshPrim, positions: readonly number[], indices: readonly number[], closed: boolean): void { - const pos: number[] = []; - for (let i = 0; i + 2 < positions.length; i += 3) pos.push(positions[i], positions[i + 2], positions[i + 1]); - const nv = pos.length / 3; - const tri: number[] = []; - for (let i = 0; i + 2 < indices.length; i += 3) { - const a = indices[i]; - const b = indices[i + 1]; - const c = indices[i + 2]; - // Indizes ausserhalb (kaputter Import) und entartete Dreiecke weglassen. - if (!(a >= 0 && a < nv && b >= 0 && b < nv && c >= 0 && c < nv)) continue; - tri.push(a, c, b); - } - const idx = closed ? orientOutward(pos, tri) : tri; - const base = prim.positions.length / 3; - for (const v of pos) prim.positions.push(v); - for (const i of idx) prim.indices.push(base + i); -} - -type Rgb = [number, number, number]; - -/** Material der Szene: Farbe sRGB 0..1, `rgba[3]` < 1 = transparent (Glas). */ -interface SceneMaterial { - name: string; - rgba: [number, number, number, number]; - metallic: number; - roughness: number; -} - -/** Materialtabelle: gleiche Farbe + Name = ein Material. */ -class Materials { - readonly list: SceneMaterial[] = []; - private readonly byKey = new Map(); - - get(name: string, rgb: Rgb, alpha = 1, metallic = 0, roughness = 0.9): number { - const key = `${name}|${rgb.join(",")}|${alpha}|${metallic}|${roughness}`; - let i = this.byKey.get(key); - if (i === undefined) { - i = this.list.length; - this.list.push({ name, rgba: [rgb[0], rgb[1], rgb[2], alpha], metallic, roughness }); - this.byKey.set(key, i); - } - return i; - } -} - -/** Die für den Rust-Schreiber gesammelte Szene. */ -interface MeshScene { - groups: MeshGroup[]; - materials: SceneMaterial[]; - levels: { id: string; name: string }[]; -} - -/** Standardfarbe der Extrusionen/Decken (wie `SLAB_RGB` in toWalls3d/shared.ts). */ -const SLAB_COLOR: Rgb = [0.86, 0.86, 0.88]; -/** Verglasung und Rahmenteile aus `emitOpeningMeshes` (Farben `PART_RGB` in toWalls3d/openings.ts). */ -const GLASS_COLOR: Rgb = [0.62, 0.76, 0.85]; -const OPENING_PART_NAMES: Array<[Rgb, string]> = [ - [[0.85, 0.85, 0.83], "Blendrahmen"], - [[0.88, 0.88, 0.9], "Fluegelrahmen"], - [[0.8, 0.8, 0.78], "Fensterbank/Zarge"], - [[0.25, 0.27, 0.3], "Schwelle"], - [[0.93, 0.9, 0.85], "Tuerblatt"], -]; -const sameRgb = (a: readonly number[], b: readonly number[]) => a.length === 3 && b.length === 3 && a.every((v, i) => Math.abs(v - b[i]) < 1e-9); +import { documentFor } from "../core/document"; +import { decodeExportFlat } from "./exportIfc"; /** Was in die Szene kommt. Alles standardmässig an (vollständiges 3D-Modell). */ export interface MeshOptions { @@ -321,172 +21,11 @@ export interface MeshOptions { context?: boolean; } -/** - * Baut alle Mesh-Gruppen (Wände, Decken, Extrusionen, Dächer, Treppen, Stützen, Öffnungsteile, - * Kontext-Meshes) und die Materialtabelle. - */ -function buildScene(project: Project, opts: MeshOptions = {}): MeshScene { - const groups: MeshGroup[] = []; - const mats = new Materials(); - const { walls, slabs } = pickGeometry(project); - const levels = project.drawingLevels.filter((l) => l.kind === "floor").map((l) => ({ id: l.id, name: l.name })); - const levelOf = (floorId: string | undefined): number => levels.findIndex((l) => l.id === floorId); - const componentName = (id: string | undefined, fallback: string): string => - (id !== undefined && project.components.find((c) => c.id === id)?.name) || fallback; - - // Wände: alle Schicht-Bänder DERSELBEN Wand-Id in EINE Gruppe (mehrere - // Materiallagen ergeben mehrere Boxen im selben Bauteil-Vorkommen). - const wallGroups = new Map(); - const wallFloor = new Map(project.walls.map((w) => [w.id, w.floorId])); - // Loch-Ausschnitte aller gelochten Bänder in EINEM Kern-Aufruf. - const holed = walls.filter((w) => w.holes && w.holes.length > 0); - const cuts = new Map(); - wallCutMeshes(holed).forEach((m, i) => cuts.set(holed[i], m)); - for (const w of walls) { - let g = wallGroups.get(w.wallId); - if (!g) { - g = newGroup(`Wand_${sanitizeName(w.wallId)}`, "wall", w.wallId, levelOf(wallFloor.get(w.wallId))); - wallGroups.set(w.wallId, g); - groups.push(g); - } - const mat = mats.get(componentName(w.cut?.componentId, "Wand"), w.color); - pushWall(newPrim(g, mat), w, cuts.get(w)); - } - - // Decken: ein Prisma je Decke. - const ceilingFloor = new Map((project.ceilings ?? []).map((c) => [c.id, c.floorId])); - for (const s of slabs) { - const g = newGroup(`Decke_${sanitizeName(s.ceilingId)}`, "slab", s.ceilingId, levelOf(ceilingFloor.get(s.ceilingId))); - const outline: Vec2[] = s.outline.map(([x, y]) => ({ x, y })); - pushPrism(newPrim(g, mats.get(componentName(s.cut?.componentId, "Decke"), s.color)), outline, s.zBottom, s.zTop); - groups.push(g); - } - - // Extrudierte Profile (truck-Integration): eigenes Prisma je Körper (siehe - // Moduldoc — bewusst NICHT die truck-WASM-Dreiecke, aus Sync-/Pure-Gründen). - for (const solid of project.extrudedSolids ?? []) { - if (solid.points.length < 3 || solid.height <= 0) continue; - let baseZ = 0; - try { - baseZ = getFloor(project, solid.levelId).baseElevation ?? 0; - } catch { - // Geschoss nicht (mehr) auflösbar: bei UK 0 extrudieren (Fallback, wie toWalls3d). - } - const g = newGroup(`Extrusion_${sanitizeName(solid.id)}`, "extrusion", solid.id, levelOf(solid.levelId)); - pushPrism(newPrim(g, mats.get("Extrusion", SLAB_COLOR)), solid.points, baseZ, baseZ + solid.height, solid.taper ?? 0); - groups.push(g); - } - - // Dächer, Stützen, Treppen: je Bauteil EIN Aufruf der 3D-Ableitung mit einem Projekt, das nur dieses - // Bauteil enthält — so tragen die Meshes die Bauteil-id (die Ableitungen liefern keine). - const addMeshes = (g: MeshGroup, meshes: RMesh[], name: string, closed = true) => { - for (const m of meshes) { - if (m.indices.length === 0) continue; - appendModelMesh(newPrim(g, mats.get(name, m.color)), m.positions, m.indices, closed); - } - }; - for (const roof of project.roofs ?? []) { - const g = newGroup(`Dach_${sanitizeName(roof.id)}`, "roof", roof.id, levelOf(roof.floorId)); - addMeshes(g, emitRoofs({ ...project, roofs: [roof] }), "Dach"); - groups.push(g); - } - for (const col of project.columns ?? []) { - const g = newGroup(`Stuetze_${sanitizeName(col.id)}`, "column", col.id, levelOf(col.floorId)); - addMeshes(g, emitColumns({ ...project, columns: [col] }), componentName(col.componentId, "Stuetze")); - groups.push(g); - } - for (const stair of project.stairs ?? []) { - const one: Project = { ...project, stairs: [stair] }; - const g = newGroup(`Treppe_${sanitizeName(stair.id)}`, "stair", stair.id, levelOf(stair.floorId)); - for (const s of emitStairs(one)) { - const outline: Vec2[] = s.outline.map(([x, y]) => ({ x, y })); - pushPrism(newPrim(g, mats.get("Treppe", s.color)), outline, s.zBottom, s.zTop); - } - addMeshes(g, emitStairMeshes(one), "Treppe"); - addMeshes(g, emitStairRailings(one), "Handlauf"); - groups.push(g); - } - - // Öffnungsteile: je Öffnung ein Knoten (Name Fenster_/Tuer_) mit Glas und den Rahmenteilen als - // Teil-Meshes je Material. Auch hier die Ableitung nur mit der Wirtswand und dieser Öffnung. - if (opts.openingParts ?? true) { - for (const op of project.openings ?? []) { - const host = project.walls.find((w) => w.id === op.hostWallId); - if (!host) continue; - const parts = emitOpeningMeshes({ ...project, walls: [host], openings: [op] }, "mittel"); - if (parts.length === 0) continue; - const g = newGroup(`${op.kind === "window" ? "Fenster" : "Tuer"}_${sanitizeName(op.id)}`, op.kind, op.id, levelOf(host.floorId)); - const prims = new Map(); - for (const m of parts) { - const glass = sameRgb(m.color, GLASS_COLOR); - const name = glass ? "Glas" : (OPENING_PART_NAMES.find(([c]) => sameRgb(c, m.color))?.[1] ?? "Oeffnungsteil"); - let prim = prims.get(name); - if (!prim) { - // Glas transparent und glatt (BLEND), Rahmen matt. - const mat = glass ? mats.get(name, m.color, 0.35, 0, 0.05) : mats.get(name, m.color, 1, 0, 0.6); - prim = newPrim(g, mat); - prims.set(name, prim); - } - appendModelMesh(prim, m.positions, m.indices, true); - } - groups.push(g); - } - } - - // Gelände und importierte Meshes (IFC/DXF): Farbe der Quelle, falls gesetzt. - if (opts.context ?? true) { - for (const obj of project.context ?? []) { - if (obj.type !== "terrainMesh" && obj.type !== "importedMesh") continue; - if (obj.positions.length < 9 || obj.indices.length < 3) continue; - const terrain = obj.type === "terrainMesh"; - const rgb: Rgb = !terrain && obj.color ? hexToRgb(obj.color, IMPORTED_RGB) : terrain ? TERRAIN_RGB : IMPORTED_RGB; - const g = newGroup(`${terrain ? "Gelaende" : "Kontext"}_${sanitizeName(obj.id)}`, terrain ? "terrain" : "context", obj.id, -1); - const prim = newPrim(g, mats.get(terrain ? "Gelaende" : obj.name || "Kontext", rgb)); - appendModelMesh(prim, obj.positions, obj.indices, false); - groups.push(g); - } - } - - return { - groups: groups.filter((g) => g.prims.some((p) => p.indices.length > 0)), - materials: mats.list, - levels, - }; -} - -// ── Flacher Puffer (Gegenstück zu src-tauri/fileio/src/mesh_export.rs, dort die Kodierung) ───── - -const FLAT_VERSION = 1; - -/** Kodiert die Szene als `[Zahlenpuffer, Zeichenketten durch \0 getrennt]`. */ -function encodeScene(scene: MeshScene, byLevel: boolean): [Float64Array, string] { - const nums: number[] = [FLAT_VERSION, byLevel ? 1 : 0]; - const strings: string[] = []; - const str = (s: string): number => { - strings.push(s.replace(/\0/g, "")); - return strings.length - 1; - }; - nums.push(scene.materials.length); - for (const m of scene.materials) nums.push(str(m.name), m.rgba[0], m.rgba[1], m.rgba[2], m.rgba[3], m.metallic, m.roughness); - nums.push(scene.levels.length); - for (const l of scene.levels) nums.push(str(l.id), str(l.name)); - nums.push(scene.groups.length); - for (const g of scene.groups) { - nums.push(str(g.name), str(g.kind), str(g.id), g.level, g.prims.length); - for (const p of g.prims) { - nums.push(p.material, p.positions.length / 3); - for (let i = 0; i < p.positions.length; i++) nums.push(p.positions[i]); - nums.push(p.indices.length / 3); - for (let i = 0; i < p.indices.length; i++) nums.push(p.indices[i]); - } - } - return [new Float64Array(nums), strings.join("\0")]; -} - /** Ruft eine Rust-Bindung; leeres Ergebnis (kaputter Puffer) wird zum Fehler mit dem Grund. */ function write(project: Project, opts: MeshOptions, byLevel: boolean, run: (m: ReturnType, buf: Float64Array, strings: string) => T): T { + const args = [(opts.openingParts ?? true) ? 1 : 0, (opts.context ?? true) ? 1 : 0, byLevel ? 1 : 0]; + const [buf, strings] = decodeExportFlat(documentFor(project).queryBin("meshExportData", args)); const m = fileio(); - const [buf, strings] = encodeScene(buildScene(project, opts), byLevel); const out = run(m, buf, strings); if (out.length === 0) { const why = m.export_mesh_check_flat(buf, strings); @@ -497,9 +36,9 @@ function write(project: Project, opts: MeshOption /** * Baut einen vollständigen Wavefront-OBJ-String des 3D-Gebäudemodells (Meter, Y-up rechtshändig: - * Modell (x, y, z-hoch) → (x, z, −y), siehe Moduldoc). Ein `o`-Objekt je Bauteil-Vorkommen (Wand, Decke, - * Extrusion, Dach, Treppe, Stütze, Fenster/Tür, Kontext-Mesh). Leeres Projekt ⇒ gültige Datei nur mit - * Kopf-Kommentaren. Verlangt das geladene Format-Modul (`await loadFileio()`). + * Modell (x, y, z-hoch) → (x, z, −y)). Ein `o`-Objekt je Bauteil-Vorkommen (Wand, Decke, Extrusion, Dach, + * Treppe, Stütze, Fenster/Tür, Kontext-Mesh). Leeres Projekt ⇒ gültige Datei nur mit Kopf-Kommentaren. + * Verlangt das geladene Format-Modul (`await loadFileio()`). */ export function exportObj(project: Project, opts: MeshOptions = {}): string { return write(project, opts, false, (m, b, s) => m.export_mesh_obj_flat(b, s)); diff --git a/src/export/ifcClassification.ts b/src/export/ifcClassification.ts deleted file mode 100644 index 2a0e4fcd..00000000 --- a/src/export/ifcClassification.ts +++ /dev/null @@ -1,104 +0,0 @@ -// Klassifikation im IFC-Export ([B5], 28.10.): welche Klassifikationssysteme das Modell hergibt und die -// Standard-Zuordnung nach eBKP-H. Reine Tabellen/Funktionen, kein IFC-Schreiben (das macht Rust über -// den Datensatz CLASSIFICATION, `ifc_export.rs`). -// -// Was das Modell führt: KEINEN eBKP-H-/BKP-Code. `categoryCode` an Bauteilen ist die Grafik-Ebene -// („20" Wände, „30" Decken …, `LayerCategory`), kein Kostenschlüssel. Daher zwei getrennte Wege: -// • `layerCodes` — die Ebene des Modells als eigenes System „Dossier-Ebenen" (Code = `categoryCode`, -// Name = Ebenenname). Stammt aus dem Modell, behauptet keinen Standard. -// • `ebkph` — Standardzuordnung je Bauteilart auf eBKP-H-HAUPTGRUPPEN (siehe `EBKPH_GROUPS`). -// -// Quelle eBKP-H: CRB, „eBKP-H Elementbasierter Baukostenplan Hochbau", SN 506 511 (Ausgabe 2020). -// Gesichert sind nur die Hauptgruppen-Buchstaben und ihre Namen (A Grundstück, B Vorbereitung, -// C Konstruktion Gebäude, D Technik Gebäude, E Äussere Wandbekleidung Gebäude, F Bedachung Gebäude, -// G Ausbau Gebäude, H Nutzungsspezifische Anlagen Gebäude, I Umgebung Gebäude, J Ausstattung, -// V Planungsleistungen, W Nebenkosten, Y Reserve, Z Mehrwertsteuer). Keine Untergruppen (C01 …): -// die hängen von Konstruktionsart und Lage ab, die das Modell nicht trägt. -// -// Die Zuordnung ist deshalb bewusst grob und ein VORSCHLAG für die Kostenplanung, kein Ersatz für -// die Einordnung durch die Kostenplanerin: -// Wand → C (Wandkonstruktion; Aussen-/Innenbekleidung E/G und nichttragende Innenwände -// unterscheidet das Modell nicht — dafür fehlt ein Feld am Wandtyp) -// Decke → C (Deckenkonstruktion; Bodenbeläge/Unterdecken wären G) -// Stütze → C -// Treppe → C (Treppenkonstruktion; Belag/Geländer wären G) -// Dach → F (Dachaufbau mit Eindeckung/Abdichtung; die reine Tragkonstruktion wäre C) -// Fenster → E (Fenster der Gebäudehülle) -// Tür → keine (Aussentür E, Innentür G — nicht unterscheidbar, daher nicht geraten) -// Raum → keine (Räume sind Flächen, kein Bauteil; sie haben die SIA-416-Zonen) - -import type { LayerCategory, Project } from "../model/types"; - -/** IFC-Schema der Ausgabe: IFC4 (Standard) oder IFC2x3 (Coordination View 2.0, TC1). */ -export type IfcSchema = "IFC4" | "IFC2X3"; - -/** Optionen des IFC-Exports: Schema und Klassifikation. */ -export interface IfcExportOptions { - /** Schema der Datei; ohne Angabe IFC4. */ - schema?: IfcSchema; - /** eBKP-H-Hauptgruppen je Bauteilart (Standardzuordnung, s. Dateikopf). */ - ebkph?: boolean; - /** `categoryCode` (Ebene) des Modells als System „Dossier-Ebenen". */ - layerCodes?: boolean; -} - -/** Bauteilarten, die klassifiziert werden können. */ -export type ClassifiedKind = "wall" | "slab" | "roof" | "column" | "stair" | "window" | "door" | "space"; - -/** Ein Klassifikationssystem für IfcClassification. */ -export interface ClassificationSystem { - name: string; - source: string; - /** Ausgabe; leer = keine Angabe. */ - edition: string; -} - -export const EBKPH_SYSTEM: ClassificationSystem = { - name: "eBKP-H", - source: "CRB Schweizerische Zentralstelle für Baurationalisierung", - edition: "SN 506 511:2020", -}; - -export const LAYER_SYSTEM: ClassificationSystem = { - name: "Dossier-Ebenen", - source: "Dossier", - edition: "", -}; - -/** Gesicherte eBKP-H-Hauptgruppen (nur die hier verwendeten). */ -export const EBKPH_GROUPS = { - C: "Konstruktion Gebäude", - E: "Äussere Wandbekleidung Gebäude", - F: "Bedachung Gebäude", -} as const; - -const EBKPH_BY_KIND: Partial> = { - wall: "C", - slab: "C", - column: "C", - stair: "C", - roof: "F", - window: "E", -}; - -/** eBKP-H-Hauptgruppe zur Bauteilart, oder `null` (Tür, Raum: nicht eindeutig). */ -export function ebkphGroup(kind: ClassifiedKind): { code: string; name: string } | null { - const code = EBKPH_BY_KIND[kind]; - return code ? { code, name: EBKPH_GROUPS[code] } : null; -} - -function findLayer(list: readonly LayerCategory[], code: string): LayerCategory | undefined { - for (const c of list) { - if (c.code === code) return c; - const sub = c.children ? findLayer(c.children, code) : undefined; - if (sub) return sub; - } - return undefined; -} - -/** Ebene (Code + Name) eines Bauteils; ohne Code `null`, ohne bekannte Ebene der Code als Name. */ -export function layerClassification(project: Project, categoryCode: string | undefined): { code: string; name: string } | null { - const code = categoryCode?.trim(); - if (!code) return null; - return { code, name: findLayer(project.layers, code)?.name ?? code }; -} diff --git a/src/export/ifcOpenings.test.ts b/src/export/ifcOpenings.test.ts deleted file mode 100644 index 8a01bf1f..00000000 --- a/src/export/ifcOpenings.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -// Türen/Fenster im IFC-Export ([B5]): TS sammelt nur die Parameter aus Typ und Öffnung; die Geometrie -// rechnet Rust (`src-tauri/fileio/src/ifc_openings.rs`, dort die Fälle Rahmen/Blatt/Glas/Ausführung). - -import { describe, expect, it } from "vitest"; -import { fillParams } 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 }; -const proj = (over: { doorTypes?: DoorType[]; windowTypes?: WindowType[] }) => - ({ doorTypes: over.doorTypes ?? [], windowTypes: over.windowTypes ?? [] }) as unknown as Project; -const door = (over: Partial = {}) => - ({ id: "D", type: "opening", hostWallId: "W", categoryCode: "21", kind: "door", position: 1, width: 1, height: 2.1, sillHeight: 0, ...over }) as Opening; -const win = (over: Partial = {}) => - ({ 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: "dreifach", 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; - -describe("fillParams", () => { - it("Fenster: Typwerte, Flügeltabelle, Flügelzahl der Öffnung vor dem Typ", () => { - const t = wt({ - frameWidth: 0.09, - frameDepth: 0.1, - insetFromFace: 0.05, - insetFace: "innen", - wingCount: 3, - sashes: [{ kind: "fluegel", autoWidth: false, width: 0.5 }, { kind: "pfosten", postWidth: 0.1 }, { kind: "fluegel" }], - }); - const o = win({ typeId: "wt", wingCount: 2 }); - expect(fillParams(proj({ windowTypes: [t] }), wall, o, cut(o), host)).toMatchObject({ - from: 1, - to: 2.2, - zBottom: 0.9, - zTop: 2.1, - nLo: -0.2, - nHi: 0.2, - frameDepth: 0.1, - frameWidth: 0.09, - inset: 0.05, - insetOutside: false, - wingCount: 2, - panes: 3, - sashes: [ - { post: false, fixed: true, width: 0.5 }, - { post: true, postWidth: 0.1, fixed: false }, - { post: false, fixed: false }, - ], - }); - // Ohne Typ: nichts vom Typ, zwei Scheiben, eine Flügel. - const p = fillParams(proj({}), wall, win(), cut(win()), host); - expect(p).toMatchObject({ frameDepth: undefined, frameWidth: undefined, insetOutside: true, wingCount: 1, panes: 2, sashes: [] }); - }); - - it("Tür: Art, Blätter, Aufschlag, Scharnier, Oberlicht, Glas", () => { - const o = door({ typeId: "dt", hinge: "end", swing: "right", openingDir: "out" }); - const t = dtp({ kind: "schiebe", leafCount: 2, transomHeight: 0.4, leafStyle: "glas", glazingRatio: 0.36 }); - expect(fillParams(proj({ doorTypes: [t] }), wall, o, cut(o), host)).toMatchObject({ - doorKind: 1, - leafCount: 2, - swingSign: -1, - dirSign: -1, - hingeAtStart: false, - transomHeight: 0.4, - glazed: true, - glazingRatio: 0.36, - }); - const plain = fillParams(proj({}), wall, door(), cut(door()), host); - expect(plain).toMatchObject({ doorKind: 0, leafCount: 1, swingSign: 1, dirSign: 1, hingeAtStart: true, transomHeight: 0, glazed: false }); - expect(fillParams(proj({}), wall, door({ doorType: "wandoeffnung" }), cut(door()), host).doorKind).toBe(2); - expect(fillParams(proj({ doorTypes: [dtp({ kind: "wandoeffnung" })] }), wall, door({ typeId: "dt" }), cut(door()), host).doorKind).toBe(2); - }); -}); diff --git a/src/export/ifcOpenings.ts b/src/export/ifcOpenings.ts deleted file mode 100644 index 1455877b..00000000 --- a/src/export/ifcOpenings.ts +++ /dev/null @@ -1,91 +0,0 @@ -// Türen und Fenster im IFC-Export ([B5]): sammelt die Parameter einer Füllung aus dem Modell (Typ und -// Öffnung) für den Rust-Schreiber. Körper (Rahmen/Zarge, Türblatt, Glas), Füllungs-Placement und -// OperationType/PartitioningType rechnet `src-tauri/fileio/src/ifc_openings.rs` (Port der früheren -// TS-Rechnung, 28.10.; Kodierung FILL im Kopf von `ifc_export.rs`). Fehlende Typwerte bleiben `undefined`, -// die Standardmasse (Rahmen 6 × 7 cm, Blatt 4 cm, Glaspakete) kennt nur Rust. - -import type { Opening, Project, Vec2, Wall } from "../model/types"; -import { getDoorType, getWindowType, glazingPanesOf } from "../model/types"; - -/** Ein Eintrag der Flügeltabelle, wie im Modell (`SashDef`). */ -export interface FillSash { - post: boolean; - postWidth?: number; - fixed: boolean; - width?: number; -} - -/** Parameter einer Füllung (Reihenfolge der Kodierung: `FlatIfc.opening` in `exportIfc.ts`). */ -export interface FillParams { - wallStart: Vec2; - wallEnd: Vec2; - /** Achs-Intervall (Abstand ab `wall.start`) und absolute Höhen der Öffnung. */ - from: number; - to: number; - zBottom: number; - zTop: number; - /** Querausdehnung der ganzen Wand entlang der linken Normalen ab `wall.start` (`nLo` = Aussenseite). */ - nLo: number; - nHi: number; - frameDepth?: number; - inset?: number; - insetOutside: boolean; - frameWidth?: number; - /** Fenster: Flügelzahl, Scheiben (1–3), Flügeltabelle. */ - wingCount: number; - panes: number; - sashes: FillSash[]; - /** Tür: 0 Dreh, 1 Schiebe, 2 reine Wandöffnung. */ - doorKind: 0 | 1 | 2; - leafCount: number; - /** +1 Aufschlag links der Achse, −1 rechts; Richtung +1 innen, −1 aussen. */ - swingSign: 1 | -1; - dirSign: 1 | -1; - hingeAtStart: boolean; - transomHeight: number; - glazed: boolean; - glazingRatio?: number; -} - -/** - * Parameter der Füllung einer Öffnung. `c` = Achs-Intervall und absolute Höhen der Öffnung, `host` = - * Querausdehnung der ganzen Wand (wie im 2D/3D). - */ -export function fillParams( - project: Project, - wall: Wall, - opening: Opening, - c: { from: number; to: number; zBottom: number; zTop: number }, - host: { nLo: number; nHi: number }, -): FillParams { - const isDoor = opening.kind === "door"; - const dt = isDoor ? getDoorType(project, opening) : undefined; - const wt = isDoor ? undefined : getWindowType(project, opening); - const t = dt ?? wt; - const kind = dt?.kind ?? (opening.doorType === "wandoeffnung" ? "wandoeffnung" : "dreh"); - return { - wallStart: wall.start, - wallEnd: wall.end, - from: c.from, - to: c.to, - zBottom: c.zBottom, - zTop: c.zTop, - nLo: host.nLo, - nHi: host.nHi, - frameDepth: t?.frameDepth, - inset: t?.insetFromFace, - insetOutside: (t?.insetFace ?? "aussen") === "aussen", - frameWidth: t?.frameWidth, - wingCount: opening.wingCount ?? wt?.wingCount ?? 1, - panes: wt ? glazingPanesOf(wt) : 2, - sashes: (wt?.sashes ?? []).map((s) => ({ post: s.kind === "pfosten", postWidth: s.postWidth, fixed: s.autoWidth === false, width: s.width })), - doorKind: kind === "schiebe" ? 1 : kind === "wandoeffnung" ? 2 : 0, - leafCount: dt?.leafCount ?? 1, - swingSign: (opening.swing ?? "left") === "left" ? 1 : -1, - dirSign: (opening.openingDir ?? "in") === "in" ? 1 : -1, - hingeAtStart: (opening.hinge ?? "start") === "start", - transomHeight: dt?.transomHeight ?? 0, - glazed: dt?.leafStyle === "glas", - glazingRatio: dt?.glazingRatio, - }; -} diff --git a/src/export/ifcQuantities.test.ts b/src/export/ifcQuantities.test.ts deleted file mode 100644 index 8e6506de..00000000 --- a/src/export/ifcQuantities.test.ts +++ /dev/null @@ -1,164 +0,0 @@ -// Basismengen für den IFC-Export ([B5], 28.10.): reine Rechnung aus der Geometrie, Werte nachrechenbar. -import { describe, it, expect } from "vitest"; -import type { RWall } from "../plan/toWalls3d"; -import { - columnQuantities, - flightQuantities, - meshVolume, - openingQuantities, - railingQuantities, - ringArea, - ringPerimeter, - roofQuantities, - slabQuantities, - wallQuantities, -} from "./ifcQuantities"; - -const byName = (q: { name: string; value: number }[]) => Object.fromEntries(q.map((x) => [x.name, x.value])); - -/** Wandband: Quader `len` lang entlang x ab `x0`, Dicke, Höhe ab `base`. */ -function band(x0: number, len: number, thickness: number, height: number, base = 0, topDrop?: [number, number]): RWall { - return { start: [x0, 0], end: [x0 + len, 0], thickness, height, baseElevation: base, color: [1, 1, 1], layers: [], wallId: "W", ...(topDrop ? { topDrop } : {}) }; -} - -describe("Hilfen", () => { - it("Ringfläche (unabhängig vom Umlaufsinn) und Umfang", () => { - const sq = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }, { x: 0, y: 3 }]; - expect(ringArea(sq)).toBe(12); - expect(ringArea([...sq].reverse())).toBe(12); - expect(ringPerimeter(sq)).toBe(14); - expect(ringArea([])).toBe(0); - }); - - it("Mesh-Volumen eines Würfels, unabhängig von der Wicklung", () => { - const pos = [0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0, 0, 0, 2, 2, 0, 2, 2, 2, 2, 0, 2, 2]; - const idx = [0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7]; - expect(meshVolume(pos, idx)).toBeCloseTo(8, 12); - const rev: number[] = []; - for (let i = 0; i < idx.length; i += 3) rev.push(idx[i], idx[i + 2], idx[i + 1]); - expect(meshVolume(pos, rev)).toBeCloseTo(8, 12); - expect(meshVolume([], [])).toBe(0); - }); -}); - -describe("Wand", () => { - const wall = { start: { x: 0, y: 0 }, end: { x: 5, y: 0 } }; - - it("eine Schicht: Länge, Dicke, Höhe, Seitenfläche, Volumen; Öffnung wird netto abgezogen", () => { - const q = byName( - wallQuantities(wall, [band(0, 5, 0.3, 2.6)], [{ from: 1, to: 2, zBottom: 0.9, zTop: 2.1 }]), - ); - expect(q.Length).toBe(5); - expect(q.Width).toBeCloseTo(0.3, 12); - expect(q.Height).toBeCloseTo(2.6, 12); - expect(q.GrossSideArea).toBeCloseTo(13, 12); - expect(q.NetSideArea).toBeCloseTo(13 - 1.2, 12); - expect(q.GrossVolume).toBeCloseTo(13 * 0.3, 12); - expect(q.NetVolume).toBeCloseTo((13 - 1.2) * 0.3, 12); - }); - - it("mehrere Schichten: Dicke und Volumen summieren, Öffnung schneidet jede Schicht", () => { - // Aussenschicht 0.2 (Achse −0.15 … ), Dämmung 0.1: Mittellinien bei y = −0.05 und +0.1 - const a = { ...band(0, 5, 0.2, 2.6), start: [0, -0.05], end: [5, -0.05] } as RWall; - const b = { ...band(0, 5, 0.1, 2.6), start: [0, 0.1], end: [5, 0.1] } as RWall; - const q = byName(wallQuantities(wall, [a, b], [{ from: 2, to: 3, zBottom: 0, zTop: 2.1 }])); - expect(q.Width).toBeCloseTo(0.3, 12); - expect(q.GrossVolume).toBeCloseTo(5 * 0.3 * 2.6, 12); - expect(q.NetVolume).toBeCloseTo((5 * 2.6 - 1 * 2.1) * 0.3, 12); - }); - - it("innere Schicht endet unter der Decke: Seitenfläche mit voller Wandhöhe, Volumen je Schicht", () => { - const outer = band(0, 5, 0.2, 2.6); - const inner = band(0.1, 4.8, 0.1, 2.3); - const q = byName(wallQuantities(wall, [outer, inner], [])); - expect(q.Height).toBeCloseTo(2.6, 12); - expect(q.GrossSideArea).toBeCloseTo(13, 12); - expect(q.GrossVolume).toBeCloseTo(5 * 0.2 * 2.6 + 4.8 * 0.1 * 2.3, 12); - }); - - it("Gehrung/Anschluss: kürzeres Band ändert Volumen, nicht die Wandlänge", () => { - const q = byName(wallQuantities(wall, [band(0.1, 4.8, 0.3, 2.6)], [])); - expect(q.Length).toBe(5); - expect(q.GrossVolume).toBeCloseTo(4.8 * 0.3 * 2.6, 12); - expect(q.NetVolume).toBeCloseTo(q.GrossVolume, 12); - }); - - it("schräge Oberkante: Höhe fehlt (nicht konstant), Fläche und Volumen mit mittlerer Höhe", () => { - const q = byName(wallQuantities(wall, [band(0, 5, 0.3, 3, 0, [0, 1])], [])); - expect(q.Height).toBeUndefined(); - expect(q.GrossSideArea).toBeCloseTo(5 * 2.5, 12); - expect(q.GrossVolume).toBeCloseTo(5 * 0.3 * 2.5, 12); - }); - - it("Mesh-Wand: Netto-Volumen aus dem Netz, Brutto bleibt der Quader", () => { - const q = byName(wallQuantities(wall, [band(0, 5, 0.3, 2.6)], [{ from: 1, to: 2, zBottom: 0.9, zTop: 2.1 }], 3.5)); - expect(q.NetVolume).toBe(3.5); - expect(q.GrossVolume).toBeCloseTo(13 * 0.3, 12); - }); - - it("Öffnung grösser als die Wand: Netto nie negativ; Öffnung ausserhalb zieht nichts ab", () => { - const q = byName(wallQuantities(wall, [band(0, 5, 0.3, 2.6)], [{ from: -1, to: 6, zBottom: -1, zTop: 5 }, { from: 8, to: 9, zBottom: 0, zTop: 2 }])); - expect(q.NetSideArea).toBe(0); - expect(q.NetVolume).toBeCloseTo(0, 12); - }); - - it("keine Bänder: keine Mengen", () => { - expect(wallQuantities(wall, [], [])).toEqual([]); - }); -}); - -describe("Decke, Dach, Stütze, Öffnung, Treppe", () => { - it("Decke: Fläche, Umfang, Dicke; Aussparung nur netto", () => { - const outline = [{ x: 0, y: 0 }, { x: 5, y: 0 }, { x: 5, y: 4 }, { x: 0, y: 4 }]; - const hole = [{ x: 1, y: 1 }, { x: 2, y: 1 }, { x: 2, y: 2 }, { x: 1, y: 2 }]; - const q = byName(slabQuantities(outline, [hole], 0.2)); - expect(q.Width).toBeCloseTo(0.2, 12); - expect(q.Perimeter).toBe(18); - expect(q.GrossArea).toBe(20); - expect(q.NetArea).toBe(19); - expect(q.GrossVolume).toBeCloseTo(4, 12); - expect(q.NetVolume).toBeCloseTo(3.8, 12); - }); - - it("Dach: geneigte Fläche > Grundrissfläche (Satteldach 30°)", () => { - // Zwei Flächen 5 × 2 m Grundriss, 30° geneigt: je 5 × 2/cos(30°). - const h = Math.tan(Math.PI / 6) * 2; - const planes = [ - [[0, 0, 0], [5, 0, 0], [5, 2, h], [0, 2, h]], - [[0, 4, 0], [0, 2, h], [5, 2, h], [5, 4, 0]], - ] as [number, number, number][][]; - const q = byName(roofQuantities(planes)); - expect(q.ProjectedArea).toBeCloseTo(20, 9); - expect(q.GrossArea).toBeCloseTo(20 / Math.cos(Math.PI / 6), 9); - expect(q.NetArea).toBe(q.GrossArea); - }); - - it("Stütze 0.3 × 0.3 × 2.6", () => { - const fp = [{ x: 0, y: 0 }, { x: 0.3, y: 0 }, { x: 0.3, y: 0.3 }, { x: 0, y: 0.3 }]; - const q = byName(columnQuantities(fp, 2.6)); - expect(q.Length).toBe(2.6); - expect(q.CrossSectionArea).toBeCloseTo(0.09, 12); - expect(q.OuterSurfaceArea).toBeCloseTo(1.2 * 2.6, 12); - expect(q.NetSurfaceArea).toBeCloseTo(1.2 * 2.6 + 0.18, 12); - expect(q.GrossVolume).toBeCloseTo(0.09 * 2.6, 12); - expect(q.NetVolume).toBeCloseTo(q.GrossVolume, 12); - }); - - it("Fenster/Tür: Breite, Höhe, Umfang, Fläche", () => { - const q = byName(openingQuantities(1.2, 1.5)); - expect(q.Width).toBe(1.2); - expect(q.Height).toBe(1.5); - expect(q.Perimeter).toBeCloseTo(5.4, 12); - expect(q.Area).toBeCloseTo(1.8, 12); - }); - - it("Lauf und Geländer", () => { - expect(byName(flightQuantities(3.4, 1.2))).toEqual({ Length: 3.4, GrossVolume: 1.2, NetVolume: 1.2 }); - expect(byName(railingQuantities(5))).toEqual({ Length: 5 }); - }); - - it("nie NaN/negativ: kaputte Eingaben ergeben 0", () => { - const q = openingQuantities(Number.NaN, -1); - for (const x of q) expect(Number.isFinite(x.value) && x.value >= 0).toBe(true); - }); -}); diff --git a/src/export/ifcQuantities.ts b/src/export/ifcQuantities.ts deleted file mode 100644 index 6c89b42f..00000000 --- a/src/export/ifcQuantities.ts +++ /dev/null @@ -1,213 +0,0 @@ -// Basismengen (Qto_*BaseQuantities) für den IFC-Export ([B5], 28.10.): Längen, Flächen und Volumen -// aus derselben Geometrie, die in die Datei geschrieben wird — für Kostenplanung (eBKP-H/BKP) und -// Mengenermittlung. Reine Rechnung auf einfachen Eingaben (Bänder, Ringe, Netze), kein Zugriff auf -// das Projekt; `exportIfc.ts` sammelt und ruft sie auf, Rust schreibt die IfcElementQuantity. -// -// Netto = abzüglich Öffnungen (Wand, Decke). Fehlt einer Menge die Grundlage (z. B. Höhe bei schräger -// Wandoberkante: „nur angeben, wenn konstant“), lassen wir sie weg statt zu raten. - -import type { Vec2 } from "../model/types"; -import type { RWall } from "../plan/toWalls3d"; - -/** Eine Menge: Name nach IFC4-Vorlage, Art (Länge/Fläche/Volumen) und Wert (immer endlich und ≥ 0). */ -export interface Qty { - name: string; - kind: "length" | "area" | "volume"; - value: number; -} - -/** Rundungsfehler und kaputte Eingaben (NaN) auf 0, nie negativ. */ -const clean = (v: number): number => (Number.isFinite(v) && v > 0 ? v : 0); -const q = (name: string, kind: Qty["kind"], value: number): Qty => ({ name, kind, value: clean(value) }); -const len = (name: string, v: number) => q(name, "length", v); -const area = (name: string, v: number) => q(name, "area", v); -const vol = (name: string, v: number) => q(name, "volume", v); - -/** Fläche eines Rings (Shoelace, unabhängig vom Umlaufsinn); offener Ring, die Schlusskante gilt als gegeben. */ -export function ringArea(pts: readonly Vec2[]): number { - let a = 0; - for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) a += pts[j].x * pts[i].y - pts[i].x * pts[j].y; - return Math.abs(a) / 2; -} - -/** Umfang eines geschlossenen Rings. */ -export function ringPerimeter(pts: readonly Vec2[]): number { - let p = 0; - for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) p += Math.hypot(pts[i].x - pts[j].x, pts[i].y - pts[j].y); - return p; -} - -/** Volumen eines geschlossenen Dreiecks-Netzes (Betrag der Summe der Tetraeder-Volumen zum Ursprung). */ -export function meshVolume(positions: readonly number[], indices: readonly number[]): number { - let v = 0; - for (let i = 0; i + 2 < indices.length; i += 3) { - const a = indices[i] * 3; - const b = indices[i + 1] * 3; - const c = indices[i + 2] * 3; - v += - positions[a] * (positions[b + 1] * positions[c + 2] - positions[b + 2] * positions[c + 1]) - - positions[a + 1] * (positions[b] * positions[c + 2] - positions[b + 2] * positions[c]) + - positions[a + 2] * (positions[b] * positions[c + 1] - positions[b + 1] * positions[c]); - } - return Math.abs(v) / 6; -} - -/** Öffnung einer Wand: Achs-Intervall (ab Wandanfang) und absolute Höhen. */ -export interface Cutout { - from: number; - to: number; - zBottom: number; - zTop: number; -} - -const overlap = (a0: number, a1: number, b0: number, b1: number): number => Math.max(0, Math.min(a1, b1) - Math.max(a0, b0)); - -/** - * Wand-Basismengen aus den Schicht-Bändern (dieselben wie im 3D) und den Öffnungen. - * • Length: Achslänge; Width: Gesamtdicke quer zur Achse; Height: nur bei konstanter Höhe. - * • GrossSideArea: Achslänge × Wandhöhe (schräge Oberkante: höchste mittlere Bandhöhe); - * NetSideArea: abzüglich der Öffnungsflächen. - * • GrossVolume: Summe der Band-Quader (Gehrungen/Anschlüsse stecken in den Bandlängen); - * NetVolume: abzüglich der Öffnungen je Band — oder `netVolume`, wenn die Wand als Netz mit schon - * ausgestanzten Öffnungen (und Laibungen) geschrieben wird. - */ -export function wallQuantities( - wall: { start: Vec2; end: Vec2 }, - bands: readonly RWall[], - cutouts: readonly Cutout[], - netVolume?: number, -): Qty[] { - if (bands.length === 0) return []; - const axisLen = Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y); - const ux = axisLen > 0 ? (wall.end.x - wall.start.x) / axisLen : 1; - const uy = axisLen > 0 ? (wall.end.y - wall.start.y) / axisLen : 0; - // Quer zur Achse: Ausdehnung aller Bänder entlang der linken Normalen (−uy, ux). - let nLo = Infinity; - let nHi = -Infinity; - let zMin = Infinity; - let zMax = -Infinity; - let sloped = false; - let gross = 0; - let tallest = 0; - for (const b of bands) { - const l = Math.hypot(b.end[0] - b.start[0], b.end[1] - b.start[1]); - const off = -(b.start[0] - wall.start.x) * uy + (b.start[1] - wall.start.y) * ux; - nLo = Math.min(nLo, off - b.thickness / 2); - nHi = Math.max(nHi, off + b.thickness / 2); - zMin = Math.min(zMin, b.baseElevation); - zMax = Math.max(zMax, b.baseElevation + b.height); - const drop = b.topDrop ? (b.topDrop[0] + b.topDrop[1]) / 2 : 0; - if (b.topDrop && (Math.abs(b.topDrop[0]) > 1e-9 || Math.abs(b.topDrop[1]) > 1e-9)) sloped = true; - gross += l * b.thickness * (b.height - drop); - tallest = Math.max(tallest, b.height - drop); - } - // Seitenfläche der Wandebene: innere Schichten enden oft unter der Decke (niedrigere Bänder), die Wand - // selbst reicht über die volle Höhe — bei konstanter Oberkante zählt die Gesamthöhe, bei schräger die - // höchste mittlere Bandhöhe. - const grossSide = axisLen * (sloped ? tallest : zMax - zMin); - let cutSide = 0; - let cutVolume = 0; - for (const c of cutouts) { - cutSide += (c.to - c.from) * overlap(c.zBottom, c.zTop, zMin, zMax); - for (const b of bands) { - const a0 = (b.start[0] - wall.start.x) * ux + (b.start[1] - wall.start.y) * uy; - const a1 = (b.end[0] - wall.start.x) * ux + (b.end[1] - wall.start.y) * uy; - const ox = overlap(Math.min(a0, a1), Math.max(a0, a1), c.from, c.to); - cutVolume += ox * overlap(c.zBottom, c.zTop, b.baseElevation, b.baseElevation + b.height) * b.thickness; - } - } - // Netto aus dem Netz kann den Band-Quader um Rundung/Gehrungsdetails überschreiten: Brutto nie unter Netto. - const net = netVolume ?? Math.max(0, gross - cutVolume); - gross = Math.max(gross, net); - const out: Qty[] = [len("Length", axisLen), len("Width", nHi - nLo)]; - if (!sloped && zMax - zMin > 0) out.push(len("Height", zMax - zMin)); - out.push( - area("GrossSideArea", grossSide), - area("NetSideArea", Math.max(0, grossSide - cutSide)), - vol("GrossVolume", gross), - vol("NetVolume", net), - ); - return out; -} - -/** Brutto-Volumen der Löcher in einem Band (für Netz-Wände ohne Netz-Volumen, s. `wallQuantities`). */ -export function holeVolume(bands: readonly RWall[]): number { - let v = 0; - for (const b of bands) for (const h of b.holes ?? []) v += (h.to - h.from) * overlap(h.zBottom, h.zTop, b.baseElevation, b.baseElevation + b.height) * b.thickness; - return v; -} - -/** - * Platten-Basismengen (Decke, Podest): Dicke, Umfang der Aussenkontur, Flächen und Volumen; Netto - * zieht die Aussparungen ab. - */ -export function slabQuantities(outline: readonly Vec2[], openings: readonly (readonly Vec2[])[], thickness: number): Qty[] { - const gross = ringArea(outline); - const net = Math.max(0, gross - openings.reduce((s, r) => s + ringArea(r), 0)); - return [ - len("Width", thickness), - len("Perimeter", ringPerimeter(outline)), - area("GrossArea", gross), - area("NetArea", net), - vol("GrossVolume", gross * thickness), - vol("NetVolume", net * thickness), - ]; -} - -type Vec3 = readonly [number, number, number]; - -/** - * Dach-Basismengen aus den geneigten Dachflächen (Aussenseite): geneigte Fläche (brutto = netto, das - * Modell kennt keine Dachfenster/Aussparungen) und Grundrissprojektion. - */ -export function roofQuantities(planes: readonly (readonly Vec3[])[]): Qty[] { - let sloped = 0; - let projected = 0; - for (const pts of planes) { - // Newell: Vektorfläche des Polygons; Betrag = Fläche, z-Anteil = Projektion auf den Grundriss. - let nx = 0; - let ny = 0; - let nz = 0; - for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { - const c = pts[j]; - const d = pts[i]; - nx += (c[1] - d[1]) * (c[2] + d[2]); - ny += (c[2] - d[2]) * (c[0] + d[0]); - nz += (c[0] - d[0]) * (c[1] + d[1]); - } - sloped += Math.hypot(nx, ny, nz) / 2; - projected += Math.abs(nz) / 2; - } - return [area("GrossArea", sloped), area("NetArea", sloped), area("ProjectedArea", projected)]; -} - -/** Stützen-Basismengen: Länge, Querschnitt, Mantel, Oberfläche und Volumen (keine Aussparungen). */ -export function columnQuantities(footprint: readonly Vec2[], length: number): Qty[] { - const cross = ringArea(footprint); - const outer = ringPerimeter(footprint) * length; - return [ - len("Length", length), - area("CrossSectionArea", cross), - area("OuterSurfaceArea", outer), - area("NetSurfaceArea", outer + 2 * cross), - vol("GrossVolume", cross * length), - vol("NetVolume", cross * length), - ]; -} - -/** Tür-/Fenster-Basismengen (lichte Öffnung): Breite, Höhe, Umfang, Fläche. */ -export function openingQuantities(width: number, height: number): Qty[] { - const w = clean(width); - const h = clean(height); - return [len("Width", w), len("Height", h), len("Perimeter", 2 * (w + h)), area("Area", w * h)]; -} - -/** Treppenlauf: Lauflänge entlang der Lauflinie und Volumen (keine Aussparungen). */ -export function flightQuantities(length: number, volume: number): Qty[] { - return [len("Length", length), vol("GrossVolume", volume), vol("NetVolume", volume)]; -} - -/** Geländer: Länge. */ -export function railingQuantities(length: number): Qty[] { - return [len("Length", length)]; -} diff --git a/src/export/ifcStairs.ts b/src/export/ifcStairs.ts deleted file mode 100644 index 609b3d03..00000000 --- a/src/export/ifcStairs.ts +++ /dev/null @@ -1,170 +0,0 @@ -// Treppen im IFC-Export ([B5], 28.10.): statt eines Fussabdruck-Quaders die Teile der Treppe wie im 3D — -// Läufe (IfcStairFlight), Podest (IfcSlab LANDING) und Handlauf/Pfosten (IfcRailing), zusammengefasst -// von der IfcStair (IfcRelAggregates). Quelle sind dieselben Ableitungen wie im 3D-Viewer -// (`emitStairs` Tritt-Prismen und Podest, `emitStairMeshes` glatte Ortbeton-Laufplatte, -// `emitStairRailings`), je Treppe mit einem Ein-Treppen-Projekt aufgerufen (die Ableitungen liefern keine -// ids). Dieses Modul sammelt und rechnet die Basismengen; die Entitäten schreibt Rust (`ifc_export.rs`, STAIR). -// -// Zuordnung der Tritt-Prismen: bei "L" ist das Podest das Prisma mit dem Umriss des Podest-Polygons der -// Treppengeometrie; Tritte bis zur Podest-Oberkante gehören zum ersten, die darüber zum zweiten Lauf. -// Gerade und Wendeltreppen haben einen Lauf (die Wendel-Mitte bleibt Teil davon, wie im 3D). - -import type { Project, Stair, Vec2 } from "../model/types"; -import { getStairType } from "../model/types"; -import { stairVerticalExtent } from "../model/wall"; -import { stairGeometry } from "../geometry/stair"; -import type { RSlab } from "../plan/toWalls3d"; -import { orientOutward } from "./meshOrient"; -import { flightQuantities, meshVolume, railingQuantities, ringArea, slabQuantities, type Qty } from "./ifcQuantities"; -import { emitStairMeshes, emitStairRailings, emitStairs } from "./model3dParts"; - -/** Ein Prisma (Profil in Welt-XY, Unterkante relativ zum Geschoss, Tiefe). */ -export interface StairSolid { - pts: Vec2[]; - zRel: number; - depth: number; -} - -export interface StairFlightParts { - name: string; - risers: number; - treads: number; - riserHeight: number; - treadLength: number; - /** IfcStairFlightTypeEnum. */ - predefined: "STRAIGHT" | "SPIRAL"; - quantities: Qty[]; - /** Entweder Prismen oder ein Dreiecks-Netz (IFC: x, y, z-hoch, Z relativ zum Geschoss). */ - solids?: StairSolid[]; - mesh?: { positions: number[]; indices: number[] }; -} - -export interface StairParts { - flights: StairFlightParts[]; - landing: { name: string; pts: Vec2[]; zRel: number; depth: number; quantities: Qty[] } | null; - rail: { name: string; predefined: "HANDRAIL"; mesh: { positions: number[]; indices: number[] }; quantities: Qty[] } | null; -} - -const EPS = 1e-6; - -/** Gleicher Umriss (gleiche Punktmenge, auch bei anderer Reihenfolge/Startpunkt). */ -function sameRing(a: readonly [number, number][], b: readonly Vec2[]): boolean { - if (a.length !== b.length) return false; - return a.every((p) => b.some((q) => Math.abs(p[0] - q.x) < EPS && Math.abs(p[1] - q.y) < EPS)); -} - -const centroid = (pts: readonly Vec2[]): Vec2 => ({ - x: pts.reduce((s, p) => s + p.x, 0) / pts.length, - y: pts.reduce((s, p) => s + p.y, 0) / pts.length, -}); - -/** Netz (Modell x, y, z-hoch) nach IFC: Z relativ zum Geschoss, Wicklung nach aussen. */ -function ifcMesh(positions: readonly number[], indices: readonly number[], base: number): { positions: number[]; indices: number[] } { - const pos = positions.slice(); - for (let i = 2; i < pos.length; i += 3) pos[i] -= base; - return { positions: pos, indices: orientOutward(pos, indices) }; -} - -/** - * Teile einer Treppe für den IFC-Export; `base` = Oberkante des Geschosses, dem die Treppe zugeordnet - * ist (Z-Werte werden relativ dazu geschrieben). Leere Teile (keine Geometrie) ergeben `flights: []`, - * `landing: null`, `rail: null` — der Aufrufer fällt dann auf den Fussabdruck zurück. - */ -export function stairParts(project: Project, stair: Stair, base: number): StairParts { - const one: Project = { ...project, stairs: [stair] }; - const { zBottom, zTop } = stairVerticalExtent(project, stair); - const rise = zTop - zBottom; - const geo = stairGeometry(stair, rise); - const slabs = emitStairs(one); - const meshes = emitStairMeshes(one); - const predefined = stair.shape === "spiral" ? "SPIRAL" : "STRAIGHT"; - - // Podest nur bei "L" (bei der Wendel ist das Polygon die Treppenmitte, Teil des Laufs). - let landingSlab: RSlab | undefined; - if (stair.shape === "L" && geo.landing) landingSlab = slabs.find((s) => sameRing(s.outline, geo.landing as Vec2[])); - const treadSlabs = slabs.filter((s) => s !== landingSlab); - - const solidOf = (s: RSlab): StairSolid => ({ pts: s.outline.map(([x, y]) => ({ x, y })), zRel: s.zBottom - base, depth: s.zTop - s.zBottom }); - const groups: RSlab[][] = []; - if (landingSlab) { - const top = landingSlab.zTop + EPS; - const lower = treadSlabs.filter((s) => s.zTop <= top); - const upper = treadSlabs.filter((s) => s.zTop > top); - for (const g of [lower, upper]) if (g.length > 0) groups.push(g); - } else if (treadSlabs.length > 0) { - groups.push(treadSlabs); - } - - const flights: StairFlightParts[] = []; - groups.forEach((g, k) => { - // Tritte = verschiedene Oberkanten (Setzstufen-Platten und Nasen teilen die Höhe ihres Tritts). - const tops = [...new Set(g.map((s) => Math.round(s.zTop / 1e-4)))]; - const treads = tops.length; - // Lauflänge: Weg zwischen erstem und letztem Tritt (Schwerpunkte) plus eine Trittiefe, mit der Steigung. - const lowest = g.reduce((m, s) => (s.zTop < m.zTop ? s : m), g[0]); - const highest = g.reduce((m, s) => (s.zTop > m.zTop ? s : m), g[0]); - const c0 = centroid(solidOf(lowest).pts); - const c1 = centroid(solidOf(highest).pts); - const run = Math.hypot(c1.x - c0.x, c1.y - c0.y) + geo.treadDepth; - const lift = highest.zTop - lowest.zTop + geo.riserHeight; - const solids = g.map(solidOf); - const volume = g.reduce((s, x) => s + ringArea(x.outline.map(([px, py]) => ({ x: px, y: py }))) * (x.zTop - x.zBottom), 0); - flights.push({ - name: groups.length > 1 ? `Lauf ${k + 1}` : "Lauf", - risers: treads, - treads, - riserHeight: geo.riserHeight, - treadLength: geo.treadDepth, - predefined, - quantities: flightQuantities(Math.hypot(run, lift), volume), - solids, - }); - }); - // Glatte Ortbeton-Laufplatte (gerade Betontreppe): ein Lauf als Netz. - if (meshes.length > 0) { - const positions: number[] = []; - const indices: number[] = []; - for (const m of meshes) { - const at = positions.length / 3; - for (const v of m.positions) positions.push(v); - for (const i of m.indices) indices.push(at + i); - } - const mesh = ifcMesh(positions, indices, base); - flights.push({ - name: flights.length > 0 ? `Lauf ${flights.length + 1}` : "Lauf", - risers: geo.treads.length, - treads: geo.treads.length, - riserHeight: geo.riserHeight, - treadLength: geo.treadDepth, - predefined, - quantities: flightQuantities(Math.hypot(stair.runLength, rise), meshVolume(mesh.positions, mesh.indices)), - mesh, - }); - } - - let landing: StairParts["landing"] = null; - if (landingSlab) { - const s = solidOf(landingSlab); - landing = { name: "Podest", pts: s.pts, zRel: s.zRel, depth: s.depth, quantities: slabQuantities(s.pts, [], s.depth) }; - } - - let rail: StairParts["rail"] = null; - const railMeshes = emitStairRailings(one); - if (railMeshes.length > 0) { - const positions: number[] = []; - const indices: number[] = []; - for (const m of railMeshes) { - const at = positions.length / 3; - for (const v of m.positions) positions.push(v); - for (const i of m.indices) indices.push(at + i); - } - const sides = getStairType(project, stair)?.railing === "beide" ? 2 : 1; - rail = { - name: "Handlauf", - predefined: "HANDRAIL", - mesh: ifcMesh(positions, indices, base), - quantities: railingQuantities(Math.hypot(stair.runLength, rise) * sides), - }; - } - return { flights, landing, rail }; -} diff --git a/src/export/meshOrient.ts b/src/export/meshOrient.ts deleted file mode 100644 index baec14bb..00000000 --- a/src/export/meshOrient.ts +++ /dev/null @@ -1,94 +0,0 @@ -// Wicklung von Dreiecks-Netzen nach aussen ausrichten — gemeinsam für Mesh-Export (OBJ/STL/glTF) und -// IFC-Export. Die 3D-Ableitungen (`plan/toWalls3d/*`) liefern keine verlässliche Wicklung, weil render3d -// doppelseitig zeichnet; Dateiformate verlangen sie. - -/** - * Richtet ein Dreiecks-Netz (Weltkoordinaten) so aus, dass die Flächennormalen nach AUSSEN zeigen: - * Dreiecke werden über gemeinsame Kanten (Eckpunkte auf 0,01 mm verschweisst) zu Zusammenhangs- - * Komponenten verbunden, jede Komponente zuerst in sich widerspruchsfrei gewickelt (Nachbarn - * durchlaufen eine gemeinsame Kante gegenläufig) und dann nach dem Vorzeichen ihres Volumens - * gedreht. Kanten mit mehr als zwei Dreiecken (Verschneidungen) verbinden nicht. Offene - * Komponenten haben kein sinnvolles Volumen und bleiben, wie sie sind (nach dem Konsistenz-Schritt). - */ -export function orientOutward(pos: readonly number[], idx: readonly number[]): number[] { - const nTri = Math.floor(idx.length / 3); - const nVert = pos.length / 3; - const weld = new Map(); - const canon = new Array(nVert); - const q = (v: number) => Math.round(v * 1e5); - for (let i = 0; i < nVert; i++) { - const key = `${q(pos[3 * i])},${q(pos[3 * i + 1])},${q(pos[3 * i + 2])}`; - let c = weld.get(key); - if (c === undefined) { - c = weld.size; - weld.set(key, c); - } - canon[i] = c; - } - const N = weld.size + 1; - // Kante (min,max) → [(Dreieck, vorwärts?)…] - const edges = new Map(); - const corner = (t: number, k: number) => canon[idx[3 * t + k]]; - for (let t = 0; t < nTri; t++) { - for (let k = 0; k < 3; k++) { - const a = corner(t, k); - const b = corner(t, (k + 1) % 3); - if (a === b) continue; - const key = Math.min(a, b) * N + Math.max(a, b); - const list = edges.get(key); - const entry = t * 2 + (a < b ? 1 : 0); - if (list) list.push(entry); - else edges.set(key, [entry]); - } - } - // Nachbarschaft über Kanten mit genau zwei Dreiecken: Wicklungs-Paritaet (0 = gleich, 1 = gegenläufig noetig). - const adj: number[][] = Array.from({ length: nTri }, () => []); - for (const list of edges.values()) { - if (list.length !== 2) continue; - const [e1, e2] = list; - const t1 = e1 >> 1; - const t2 = e2 >> 1; - if (t1 === t2) continue; - // Gleiche Durchlaufrichtung = Widerspruch ⇒ eines muss gedreht werden. - const parity = (e1 & 1) === (e2 & 1) ? 1 : 0; - adj[t1].push(t2 * 2 + parity); - adj[t2].push(t1 * 2 + parity); - } - const flip = new Array(nTri).fill(-1); - const out = idx.slice(); - for (let s = 0; s < nTri; s++) { - if (flip[s] >= 0) continue; - const comp: number[] = [s]; - flip[s] = 0; - for (let h = 0; h < comp.length; h++) { - const t = comp[h]; - for (const e of adj[t]) { - const u = e >> 1; - if (flip[u] < 0) { - flip[u] = flip[t] ^ (e & 1); - comp.push(u); - } - } - } - // Volumen der Komponente mit den bisherigen Drehungen; Offenheit: Kante mit nur einem Dreieck. - let vol = 0; - for (const t of comp) { - const [a, b, c] = flip[t] ? [idx[3 * t], idx[3 * t + 2], idx[3 * t + 1]] : [idx[3 * t], idx[3 * t + 1], idx[3 * t + 2]]; - const A = a * 3; - const B = b * 3; - const C = c * 3; - vol += - pos[A] * (pos[B + 1] * pos[C + 2] - pos[B + 2] * pos[C + 1]) - - pos[A + 1] * (pos[B] * pos[C + 2] - pos[B + 2] * pos[C]) + - pos[A + 2] * (pos[B] * pos[C + 1] - pos[B + 1] * pos[C]); - } - const turn = vol < 0 ? 1 : 0; - for (const t of comp) { - if (flip[t] ^ turn) { - out[3 * t + 1] = idx[3 * t + 2]; - out[3 * t + 2] = idx[3 * t + 1]; - } - } - } - return out; -} diff --git a/src/export/meshScene.testutil.ts b/src/export/meshScene.testutil.ts new file mode 100644 index 00000000..93ce7a6f --- /dev/null +++ b/src/export/meshScene.testutil.ts @@ -0,0 +1,59 @@ +// Testhilfe: liest die Mesh-Szene des Kerns (`meshExportData`, Kodierung `mesh_export.rs`) — z. B. das +// öffnungsgenaue Wand-Volumen je Wand als Vergleichswert für IFC-Export und -Import. + +import type { Project } from "../model/types"; +import { documentFor } from "../core/document"; +import { decodeExportFlat } from "./exportIfc"; + +export interface SceneGroup { + name: string; + kind: string; + id: string; + prims: { positions: Float64Array; indices: Float64Array }[]; +} + +/** Knoten der Mesh-Szene (Welt x, Höhe, y; Wicklung nach aussen im Modell). */ +export function meshSceneGroups(project: Project): SceneGroup[] { + const [b, text] = decodeExportFlat(documentFor(project).queryBin("meshExportData", [1, 1, 0])); + const s = text.split("\0"); + let i = 2; + i += 1 + b[i] * 7; + i += 1 + b[i] * 2; + const n = b[i++]; + const out: SceneGroup[] = []; + for (let g = 0; g < n; g++) { + const group: SceneGroup = { name: s[b[i]], kind: s[b[i + 1]], id: s[b[i + 2]], prims: [] }; + const np = b[i + 4]; + i += 5; + for (let k = 0; k < np; k++) { + const nv = b[i + 1]; + const positions = b.subarray(i + 2, i + 2 + nv * 3); + i += 2 + nv * 3; + const nt = b[i]; + const indices = b.subarray(i + 1, i + 1 + nt * 3); + i += 1 + nt * 3; + group.prims.push({ positions, indices }); + } + out.push(group); + } + return out; +} + +/** Volumen je Wand (Summe der Beträge je Schicht-Band, Öffnungen samt Laibungen ausgestanzt). */ +export function wallMeshVolumes(project: Project): Map { + const out = new Map(); + for (const g of meshSceneGroups(project)) { + if (g.kind !== "wall") continue; + let sum = 0; + for (const { positions: p, indices: x } of g.prims) { + let v6 = 0; + for (let t = 0; t + 2 < x.length; t += 3) { + const [a, b, c] = [x[t] * 3, x[t + 1] * 3, x[t + 2] * 3]; + v6 += p[a] * (p[b + 1] * p[c + 2] - p[b + 2] * p[c + 1]) + p[a + 1] * (p[b + 2] * p[c] - p[b] * p[c + 2]) + p[a + 2] * (p[b] * p[c + 1] - p[b + 1] * p[c]); + } + sum += Math.abs(v6) / 6; + } + out.set(g.id, sum); + } + return out; +} diff --git a/src/export/model3dParts.ts b/src/export/model3dParts.ts deleted file mode 100644 index 6d59365a..00000000 --- a/src/export/model3dParts.ts +++ /dev/null @@ -1,50 +0,0 @@ -// 3D-Teile einzelner Bauteile für die Exporte (OBJ/STL/glTF, IFC): dieselben Ableitungen wie das 3D, -// gerechnet im Kern auf dem Projekt-Dokument (`queries.rs`, [K4]). Die Exporte rufen sie je Bauteil -// mit einem Ein-Bauteil-Projekt auf (die Ableitungen liefern keine ids); damit das gemeinsame -// Dokument der App nicht bei jedem Aufruf umgebaut wird, bekommt jeder Aufruf ein eigenes, kurzlebiges -// Dokument. - -import type { Project } from "../model/types"; -import type { RMesh, RSlab } from "../plan/toWalls3d/shared"; -import { ProjectDocument, type QueryName } from "../core/document"; - -const DETAIL_CODE: Record = { grob: 0, mittel: 1, fein: 2 }; - -function queryOnce(project: Project, name: QueryName, args: number[] = [], text = ""): T { - const doc = new ProjectDocument(project); - try { - return doc.query(name, args, text); - } finally { - doc.close(); - } -} - -/** Dach-Meshes (geschlossene Schicht-Körper je Dach). */ -export function emitRoofs(project: Project): RMesh[] { - return queryOnce(project, "roofMeshes"); -} - -/** Stützen als Profil-Extrusionen. */ -export function emitColumns(project: Project): RMesh[] { - return queryOnce(project, "columnMeshes"); -} - -/** Öffnungs-Einbauteile (Rahmen, Glas, Blatt) im Detailgrad `detail`. */ -export function emitOpeningMeshes(project: Project, detail: "grob" | "mittel" | "fein" = "fein"): RMesh[] { - return queryOnce(project, "openingMeshes", [DETAIL_CODE[detail] ?? 2]); -} - -/** Treppentritte (und Podeste) als extrudierte Platten; `forSection` wie im Schnitt. */ -export function emitStairs(project: Project, forSection = false): RSlab[] { - return queryOnce(project, "stairSlabs", [forSection ? 1 : 0]); -} - -/** Glatte Ortbeton-Laufplatten. */ -export function emitStairMeshes(project: Project): RMesh[] { - return queryOnce(project, "stairMeshes"); -} - -/** Handläufe und Pfosten. */ -export function emitStairRailings(project: Project): RMesh[] { - return queryOnce(project, "stairRailings"); -} diff --git a/src/io/ifcImport.test.ts b/src/io/ifcImport.test.ts index 0a8138a0..d27d7b9d 100644 --- a/src/io/ifcImport.test.ts +++ b/src/io/ifcImport.test.ts @@ -16,8 +16,7 @@ import { exportIfcSpf, ifcGuid } from "../export/exportIfc"; import { sampleProject } from "../model/sampleProject"; import { ceilingVerticalExtent } from "../model/wall"; import { polygonArea } from "../geometry/roomArea"; -import { pickGeometry } from "../plan/toWalls3d"; -import { wallCutMeshes } from "../plan/wallMeshCut"; +import { wallMeshVolumes } from "../export/meshScene.testutil"; import { formatIfcReport, handleIfcWorkerRequest, ifcToImportedMeshes, readIfc, type IfcProduct, type IfcWorkerRequest } from "./ifcImport"; function volume(pos: ArrayLike, idx: ArrayLike): number { @@ -77,10 +76,7 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => { // Wände: dieselben Ausschnitt-Netze wie der Export (Bänder je Wand). [B5] schreibt einfache Wände als // ungeschnittene Extrusion + IfcOpeningElement, der Import zieht die Öffnungen ab ([B3]) → bei allen // Wänden das ausgeschnittene Volumen. - const bands = pickGeometry(sampleProject).walls; - const cut = new Map(); - const add = (m: Map, id: string, v: number) => m.set(id, (m.get(id) ?? 0) + Math.abs(v)); - wallCutMeshes(bands).forEach((m, i) => add(cut, bands[i].wallId, volume(m.positions, m.indices))); + const cut = wallMeshVolumes(sampleProject); const lines = new Map(ifc.split("\n").map((l) => [l.slice(0, l.indexOf("=")), l] as const)); const wallsGot = products.filter((p) => p.ifcClass === "IfcWall"); expect(wallsGot.length).toBe(sampleProject.walls.length); diff --git a/src/model/geoRebase.test.ts b/src/model/geoRebase.test.ts index edc05a3e..b05943d7 100644 --- a/src/model/geoRebase.test.ts +++ b/src/model/geoRebase.test.ts @@ -38,11 +38,16 @@ describe("translateProject", () => { expect(oc.openings![0]).toEqual(src.openings![0].map((p) => ({ x: p.x + DX, y: p.y + DY }))); }); - it("verschiebt Dach-Umriss", () => { - const out = translateProject(sampleProject, DX, DY); - const r = sampleProject.roofs![0]; + it("verschiebt Dach-Umriss inkl. Innenhöfe", () => { + const hole = [{ x: 1, y: 1 }, { x: 2, y: 1 }, { x: 2, y: 2 }, { x: 1, y: 2 }]; + const withHole: Project = { ...sampleProject, roofs: [{ ...sampleProject.roofs![0], holes: [hole] }] }; + const out = translateProject(withHole, DX, DY); + const r = withHole.roofs![0]; const or_ = out.roofs!.find((x) => x.id === r.id)!; expect(or_.outline).toEqual(r.outline.map((p) => ({ x: p.x + DX, y: p.y + DY }))); + expect(or_.holes![0]).toEqual(hole.map((p) => ({ x: p.x + DX, y: p.y + DY }))); + // Ohne Höfe kein neues Feld. + expect("holes" in translateProject(sampleProject, DX, DY).roofs![0]).toBe(false); }); it("Treppe: start/center verschieben sich, dir (Richtungsvektor) bleibt unverändert", () => { diff --git a/src/model/geoRebase.ts b/src/model/geoRebase.ts index ec8b0c96..46a6c654 100644 --- a/src/model/geoRebase.ts +++ b/src/model/geoRebase.ts @@ -78,7 +78,11 @@ export function translateProject(project: Project, dx: number, dy: number): Proj outline: shiftAll(c.outline, dx, dy), openings: c.openings?.map((h) => shiftAll(h, dx, dy)), })), - roofs: project.roofs?.map((r) => ({ ...r, outline: shiftAll(r.outline, dx, dy) })), + roofs: project.roofs?.map((r) => ({ + ...r, + outline: shiftAll(r.outline, dx, dy), + ...(r.holes ? { holes: r.holes.map((h) => shiftAll(h, dx, dy)) } : {}), + })), stairs: project.stairs?.map((s) => ({ ...s, start: shift(s.start, dx, dy), diff --git a/src/plan/toWalls3d/roofWinding.test.ts b/src/plan/toWalls3d/roofWinding.test.ts index 5177dc4c..50a45704 100644 --- a/src/plan/toWalls3d/roofWinding.test.ts +++ b/src/plan/toWalls3d/roofWinding.test.ts @@ -3,7 +3,6 @@ import { describe, expect, it } from "vitest"; import { roofMeshes } from "../toWalls3d"; -import { isWatertight } from "../wallMeshCut"; import { sampleProject } from "../../model/sampleProject"; import type { Project, Roof, RoofShape } from "../../model/types"; @@ -42,7 +41,8 @@ describe("Dach-Meshes geschlossen und nach aussen gewunden", () => { for (const m of meshes) { const c = closure(m); expect(c.vol6).toBeGreaterThan(0); - if (exact.includes(shape)) expect(isWatertight(m, 1e-6)).toBe(true); + // Dicht (Gauss: ∮ n dA = 0, wie `is_watertight` im Kern), sonst kleine Restlücke. + if (exact.includes(shape)) expect(c.gap).toBeLessThan(1e-6); else expect(c.gap).toBeLessThan(0.01); } }); diff --git a/src/plan/toWalls3d/shared.ts b/src/plan/toWalls3d/shared.ts index a83931ab..6e6ac16b 100644 --- a/src/plan/toWalls3d/shared.ts +++ b/src/plan/toWalls3d/shared.ts @@ -245,10 +245,6 @@ export interface RModel3d { export const WALL_RGB: RRgb = [0.82, 0.8, 0.76]; /** Etwas hellerer, kühlerer Ton für Deckenplatten (heben sich von Wänden ab). */ export const SLAB_RGB: RRgb = [0.86, 0.86, 0.88]; -/** Gedämpftes Lehm-/Geländegrün-grau (three.js mats.terrain = 0xa9b0a2). */ -export const TERRAIN_RGB: RRgb = [169 / 255, 176 / 255, 162 / 255]; -/** Neutrales Hellgrau für importierte Meshes (three.js mats.mesh = 0x9fa6ae). */ -export const IMPORTED_RGB: RRgb = [159 / 255, 166 / 255, 174 / 255]; /** Fallback-Farbe für 2D-Zeichnungen ohne color/lineStyle/Kategorie (wie drawing2DColor in Viewport3D.tsx, "#888888"). */ export const DRAWING_LINE_FALLBACK_RGB: RRgb = [0x88 / 255, 0x88 / 255, 0x88 / 255]; diff --git a/src/plan/wallMeshCut.test.ts b/src/plan/wallMeshCut.test.ts deleted file mode 100644 index 728e9c05..00000000 --- a/src/plan/wallMeshCut.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -// Unit-Tests für den gemeinsamen Wand-Loch-Ausschnitt-Generator (wallMeshCut.ts, -// TS-Port von render3d/src/mesh.rs::extrude_layer_segment_with_holes). Prüft die -// geometrische Zerlegung (gleiche Rechteck-Anzahl wie die Rust-Referenz), nicht -// nur „läuft". - -import { describe, it, expect } from "vitest"; -import { isWatertight, solidSubrects, wallCutMesh } from "./wallMeshCut"; -import type { CutMesh } from "./wallMeshCut"; -import type { RWall } from "./toWalls3d"; - -/** - * Geschlossene-Fläche-Kennzahlen: Vektorfläche ∮ n dA (Σ (v1−v0)×(v2−v0)) und - * 6× signiertes Volumen (Σ v0·(v1×v2)). Dienen den Watertight-Tests direkt (statt - * eines naiven Kanten-Manifold-Zählers, der an den legitimen T-Stössen der vollen - * Deckel/Boden-Streifen scheitern würde — siehe isWatertight-Doc in wallMeshCut.ts). - */ -function surfaceIntegrals(m: CutMesh): { areaLen: number; vol6: number } { - const p = m.positions; - let ax = 0; - let ay = 0; - let az = 0; - let vol6 = 0; - for (let t = 0; t < m.indices.length; t += 3) { - const i0 = m.indices[t] * 3; - const i1 = m.indices[t + 1] * 3; - const i2 = m.indices[t + 2] * 3; - const e1 = [p[i1] - p[i0], p[i1 + 1] - p[i0 + 1], p[i1 + 2] - p[i0 + 2]]; - const e2 = [p[i2] - p[i0], p[i2 + 1] - p[i0 + 1], p[i2 + 2] - p[i0 + 2]]; - const cx = e1[1] * e2[2] - e1[2] * e2[1]; - const cy = e1[2] * e2[0] - e1[0] * e2[2]; - const cz = e1[0] * e2[1] - e1[1] * e2[0]; - ax += cx; - ay += cy; - az += cz; - vol6 += p[i0] * cx + p[i0 + 1] * cy + p[i0 + 2] * cz; - } - return { areaLen: Math.hypot(ax, ay, az), vol6 }; -} - -/** Ein RWall-Band mit optionalen Löchern (frei stehend, Achse entlang +x). */ -function band(holes?: RWall["holes"]): RWall { - return { - start: [0, 0], - end: [5, 0], - thickness: 0.4, - height: 2.6, - baseElevation: 0, - color: [0.8, 0.8, 0.8], - layers: [], - wallId: "W1", - ...(holes ? { holes } : {}), - }; -} - -describe("solidSubrects — Koordinaten-Kompression (Rust-Parität)", () => { - it("ohne Loch: genau ein Vollrechteck", () => { - expect(solidSubrects(0, 5, 0, 2.6, [])).toEqual([[0, 5, 0, 2.6]]); - }); - - it("ein voll im Inneren liegendes Loch → 3×3-Gitter minus 1 = 8 solide Teilrechtecke", () => { - const rects = solidSubrects(0, 5, 0, 2.6, [[2, 3, 0.9, 2.4]]); - expect(rects).toHaveLength(8); - // Keiner der Teilrechteck-Mittelpunkte liegt im Loch. - for (const [ua, ub, za, zb] of rects) { - const cu = (ua + ub) / 2; - const cz = (za + zb) / 2; - expect(cu > 2 && cu < 3 && cz > 0.9 && cz < 2.4).toBe(false); - } - }); - - it("randständiges Loch (Tür am Boden) → 3×2-Gitter minus 1 = 5 Teilrechtecke", () => { - expect(solidSubrects(0, 5, 0, 2.6, [[2, 3, 0, 2.1]])).toHaveLength(5); - }); - - it("zwei versetzt übereinanderliegende Löcher: keine überlappenden/entarteten Teilrechtecke", () => { - const rects = solidSubrects(0, 5, 0, 2.8, [ - [1, 2, 0.9, 1.4], - [3, 4, 1.6, 2.2], - ]); - // Alle Teilrechtecke haben echte Ausdehnung und liegen ausserhalb beider Löcher. - for (const [ua, ub, za, zb] of rects) { - expect(ub - ua).toBeGreaterThan(0); - expect(zb - za).toBeGreaterThan(0); - } - expect(rects.length).toBeGreaterThan(0); - }); -}); - -describe("wallCutMesh — Loch-Ausschnitt-Mesh", () => { - it("ohne Loch: 12 Dreiecke (volle Box-Äquivalenz)", () => { - const m = wallCutMesh(band()); - expect(m.indices.length / 3).toBe(12); - }); - - it("Fenster im Inneren: 48 Dreiecke, 4 Laibungen, Loch-Rand-Vertices vorhanden", () => { - const m = wallCutMesh(band([{ from: 2, to: 3, zBottom: 0.9, zTop: 2.4 }])); - expect(m.indices.length / 3).toBe(48); - // Vertices an allen vier Loch-Rändern (Brüstung/Sturz/links/rechts). - const has = (axis: number, val: number) => { - for (let i = 0; i < m.positions.length; i += 3) { - if (Math.abs(m.positions[i + axis] - val) < 1e-6) return true; - } - return false; - }; - expect(has(1, 0.9)).toBe(true); // y = Brüstungs-OK - expect(has(1, 2.4)).toBe(true); // y = Sturz-UK - expect(has(0, 2)).toBe(true); // x = linke Kante - expect(has(0, 3)).toBe(true); // x = rechte Kante - // KEIN Vertex liegt strikt im offenen Loch-Rechteck (die Fläche ist wirklich weg). - for (let i = 0; i < m.positions.length; i += 3) { - const x = m.positions[i]; - const y = m.positions[i + 1]; - const strictlyInside = x > 2 + 1e-6 && x < 3 - 1e-6 && y > 0.9 + 1e-6 && y < 2.4 - 1e-6; - expect(strictlyInside).toBe(false); - } - }); - - it("Tür am Boden: 36 Dreiecke (untere Laibung entfällt, Boden bekommt die Lücke)", () => { - const m = wallCutMesh(band([{ from: 2, to: 3, zBottom: 0, zTop: 2.1 }])); - expect(m.indices.length / 3).toBe(36); - }); - - it("alle Dreiecks-Indizes referenzieren existierende Vertices", () => { - const m = wallCutMesh(band([{ from: 2, to: 3, zBottom: 0.9, zTop: 2.4 }])); - const vcount = m.positions.length / 3; - for (const idx of m.indices) { - expect(idx).toBeGreaterThanOrEqual(0); - expect(idx).toBeLessThan(vcount); - } - }); -}); - -describe("wallCutMesh — Wasserdichtigkeit + Aussen-Orientierung (der hohl/offen-Bug)", () => { - it("volle Wand OHNE Loch: geschlossen (∮ n dA = 0), Normalen aussen (Volumen = L·T·H)", () => { - const m = wallCutMesh(band()); - const { areaLen, vol6 } = surfaceIntegrals(m); - expect(areaLen).toBeLessThan(1e-6); // ∮ n dA = 0 ⇒ kein Loch, kein invertiertes Dreieck - expect(vol6 / 6).toBeCloseTo(5 * 0.4 * 2.6, 6); // > 0 ⇒ aussen orientiert - expect(isWatertight(m)).toBe(true); - }); - - it("Wand mit Fenster: trotz T-Stösse geschlossen + aussen orientiert (Volumen = Wand − Fensterquader)", () => { - const m = wallCutMesh(band([{ from: 2, to: 3, zBottom: 0.9, zTop: 2.4 }])); - const { areaLen, vol6 } = surfaceIntegrals(m); - expect(areaLen).toBeLessThan(1e-6); - expect(vol6 / 6).toBeCloseTo(5 * 0.4 * 2.6 - 1 * 0.4 * (2.4 - 0.9), 6); - expect(isWatertight(m)).toBe(true); - }); - - it("eine EINZELNE invertierte Kappe würde erkannt (Regressionswächter gegen falsche Wicklung)", () => { - // Bau die volle Wand, kehre die Wicklung EINES Dreiecks um → nicht mehr dicht. - const m = wallCutMesh(band()); - const broken: CutMesh = { positions: m.positions.slice(), indices: m.indices.slice() }; - [broken.indices[1], broken.indices[2]] = [broken.indices[2], broken.indices[1]]; - expect(isWatertight(broken)).toBe(false); - }); - - it("Türwand ist ein GESCHLOSSENER Prisma-Körper (Querschnitt = П-Polygon, Türkerbe umlaufend)", () => { - // Die Türkerbe ist eine Einbuchtung der UNTEREN Umriss-Kante (kein Loch): der - // Querschnitt bleibt EIN einfaches, geschlossenes Polygon (П-Form), das über - // die Dicke extrudiert wieder einen geschlossenen Körper ergibt. Die fehlende - // untere Laibung und die Boden-Lücke heben sich in ∮ n dA exakt auf. - const m = wallCutMesh(band([{ from: 2, to: 3, zBottom: 0, zTop: 2.1 }])); - const { areaLen, vol6 } = surfaceIntegrals(m); - expect(areaLen).toBeLessThan(1e-6); - expect(vol6 / 6).toBeCloseTo(5 * 0.4 * 2.6 - 1 * 0.4 * 2.1, 6); - expect(isWatertight(m)).toBe(true); - }); -}); diff --git a/src/plan/wallMeshCut.ts b/src/plan/wallMeshCut.ts deleted file mode 100644 index aaf03a7e..00000000 --- a/src/plan/wallMeshCut.ts +++ /dev/null @@ -1,98 +0,0 @@ -// Wand-Mesh MIT echtem Loch-Ausschnitt (Fenster/Türen) für die Datei-Exporte -// (STL/OBJ/IFC): aus einem RWall-Band (Achse `start→end`, `thickness`, -// `baseElevation`, `height` + rechteckige `holes`) entsteht das Dreiecks-Mesh mit -// ausgestanzten Öffnungen inkl. Laibungen — so sehen die Exporte aus wie die -// 3D-Ansicht. Gerechnet wird im Rust-Kern (`src-tauri/core/src/wall_mesh_cut.rs`, -// dieselbe Zerlegung wie `render3d/src/mesh.rs::extrude_layer_segment_with_holes`, -// ohne Gehrung: die Bänder sind an den Enden schon gekürzt). Hier bleibt die -// flache Übergabe. -// -// ACHSEN: Modell (x, y) → Welt (x, Höhe, y), Y-UP — wie exportMesh.ts und der -// 3D-Viewer. - -import { core } from "../engine/coreWasm"; -import { FlatWriter } from "../geometry/coreFlat"; -import type { RWall } from "./toWalls3d"; - -/** - * Ein Dreiecks-Mesh in LOKALEN (0-basierten) Indizes: `positions` flach - * (x,y,z, …) in Weltmetern (Y-up), `indices` je 3 = ein Dreieck. - */ -export interface CutMesh { - positions: number[]; - indices: number[]; -} - -/** - * Zerlegt das Rechteck `[uLo,uHi]×[zLo,zHi]` MINUS `holes` (`[u0,u1,z0,z1]`) in - * achsparallele, disjunkte solide Teilrechtecke (Koordinaten-Kompression wie - * `mesh.rs::solid_subrects`). - */ -export function solidSubrects( - uLo: number, - uHi: number, - zLo: number, - zHi: number, - holes: Array<[number, number, number, number]>, -): Array<[number, number, number, number]> { - const flat = new Float64Array(holes.length * 4); - holes.forEach((h, i) => flat.set(h, i * 4)); - const r = core().solid_subrects_flat(uLo, uHi, zLo, zHi, flat); - const out: Array<[number, number, number, number]> = []; - for (let i = 0; i + 4 <= r.length; i += 4) out.push([r[i], r[i + 1], r[i + 2], r[i + 3]]); - return out; -} - -/** - * Ob ein Mesh eine GESCHLOSSENE, nach aussen gewundene Fläche ist — Gauss- - * Kriterium (∮ n dA = 0 und signiertes Volumen > 0) statt eines Kanten-Zählers, - * damit die legitimen T-Stösse der vollen Deckel/Boden-Streifen nicht als - * „offen" gelten. Rechnet im Kern; die Übergabe-Puffer werden wiederverwendet - * (frische Typed Arrays je Aufruf kosteten mehr als die Rechnung selbst). - */ -export function isWatertight(mesh: CutMesh, eps = 1e-6): boolean { - const p = mesh.positions; - const x = mesh.indices; - if (scratchPos.length < p.length) scratchPos = new Float64Array(p.length * 2); - if (scratchIdx.length < x.length) scratchIdx = new Uint32Array(x.length * 2); - for (let i = 0; i < p.length; i++) scratchPos[i] = p[i]; - // Ungültige Indizes (negativ, gebrochen, NaN) zeigen ins Leere ⇒ „nicht dicht". - for (let i = 0; i < x.length; i++) scratchIdx[i] = Number.isInteger(x[i]) && x[i] >= 0 && x[i] < 0xffffffff ? x[i] : 0xffffffff; - return core().is_watertight_flat(scratchPos.subarray(0, p.length), scratchIdx.subarray(0, x.length), eps); -} - -let scratchPos = new Float64Array(1024); -let scratchIdx = new Uint32Array(1024); - -/** - * Loch-Ausschnitt-Meshes vieler Bänder in EINEM Kern-Aufruf (Reihenfolge wie - * `walls`). Aufbau je Band: Langseiten (Gitter minus Löcher), Deckel/Boden und - * Stirnkappen minus randständiger Löcher, Laibungen je Loch. Ohne Löcher die - * volle Box; entartete Bänder liefern ein leeres Mesh. - */ -export function wallCutMeshes(walls: readonly RWall[]): CutMesh[] { - const w = new FlatWriter().num(walls.length); - for (const b of walls) { - const holes = b.holes ?? []; - w.num(b.start[0], b.start[1], b.end[0], b.end[1], b.thickness, b.baseElevation, b.height, holes.length); - for (const h of holes) w.num(h.from, h.to, h.zBottom, h.zTop); - } - const buf = core().wall_cut_meshes_flat(w.done()); - const out: CutMesh[] = []; - let i = 1; - for (let k = 0; k < walls.length; k++) { - const len = i < buf.length ? buf[i++] : 0; - const positions = new Array(len); - for (let j = 0; j < len; j++) positions[j] = buf[i + j]; - i += len; - const indices = new Array(len / 3); - for (let j = 0; j < len / 3; j++) indices[j] = j; - out.push({ positions, indices }); - } - return out; -} - -/** Loch-Ausschnitt-Mesh EINES Bandes (s. {@link wallCutMeshes}). */ -export function wallCutMesh(w: RWall): CutMesh { - return wallCutMeshes([w])[0]; -} diff --git a/src/ui/ExportSaveDialog.tsx b/src/ui/ExportSaveDialog.tsx index 49a17fbc..8afd16ac 100644 --- a/src/ui/ExportSaveDialog.tsx +++ b/src/ui/ExportSaveDialog.tsx @@ -10,7 +10,7 @@ import { useEffect, useState } from "react"; import { t } from "../i18n"; import { Dropdown } from "./Dropdown"; -import type { IfcExportOptions, IfcSchema } from "../export/ifcClassification"; +import type { IfcExportOptions, IfcSchema } from "../export/exportIfc"; /** Direkt-herunterladbare Exportformate (mit Datei-Endung). */ export type ExportSaveFormat = "csv" | "ifc" | "obj" | "stl" | "glb" | "step";