diff --git a/TODO.md b/TODO.md index c45b6d7d..1c05cc28 100644 --- a/TODO.md +++ b/TODO.md @@ -1167,7 +1167,18 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). Treppenuntersicht, Abzugskörper beliebiger Form im Schnitt. · L - ◐ **[G2] Wand an Dach.** 27.10.: schräge Oberkante (`topDrop`) in render3d statt 15-cm-Treppung. Offen: Schnitt, exakte Lösung über [B6]. · M–L -- ○ **[G3] Öffnungen beliebiger Form** (Rundbogen, rund, schräg) als Abzugskörper. · M · nach [G1]. +- ◐ **[G3] Öffnungen beliebiger Form** (29.10.) `Opening.shape` (rundbogen, segmentbogen, spitzbogen, rund/oval, + schraeg, giebel) + `shapeRise` (Stich). Kern `opening_shape.rs`: konvexer Umriss im Öffnungsrechteck; die Wand + behält das Rechteck-Loch, der Rest zwischen Rechteck und Umriss kommt als Füllkörper (senkrechte Streifen = + 8-Ecken-Quader, Wandfarbe) dazu — render3d, Wandbänder und Exporte bleiben unverändert. Schnitt: Wandband an der + Schnittstelle bis an den Umriss verlängert, Rahmen/Glas auf lichter Höhe; Ansicht: Rahmen als Umriss, Glas + eingerückt; 3D: Rahmen-Ring und Glas (bzw. Türblatt) entlang des Umrisses; IFC: Öffnungskörper als Profil quer + durch die Wand (neuer Datensatz OPENING_SOLID), Füllung als Netz; Netz-Wände bekommen die Füllkörper. Grundriss + bleibt SIA-Symbol. UI: „Fenster bearbeiten" → Grösse (Form, Stich). Für Formen abgeschaltet (Hinweis im Dialog): + Anschlag, Sturz-Querschnitt, Storenkasten, Flügel-/Sprossenteilung in Ansicht/3D; Fensterbank nur bei flachem + Boden. Geprüft: Rust-Tests, CLI-Schnitt/-Ansicht als PNG angesehen (Linux). Offen: Projektion hinter der + Schnittebene zeigt das Rechteck-Loch, Wand-Füllkörper einfarbig (nicht je Schicht), Abzugskörper beliebiger + Form, nicht in der Tauri-App/Metal geprüft. · M - ○ **[G4] Exakte Sichtbarkeit (HLR)** für Ansicht und Projektionsteil des Schnitts. · XL - ○ **[G5] Dächer untereinander, Gauben, Wand ↔ Decke** per Boolean. · L · nach [G1]/[G2]. - ○ **[G6] Allgemeine Polygon-Dominanz im Schnitt** (nicht nur Rechtecke). · M @@ -1446,6 +1457,20 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). CLI-Grundriss/-Schnitt/-Ansicht angesehen (Linux). Offen: Taschen-Schiebetür (in der Wand), Ansicht zeigt bei zweiflügeliger Schiebetür nur einen Pfeil, 3D/Ansicht ohne Hebeschiebe-Bandseite in der Ansicht, Brüstungs-/Riegel- Einteilung unten (nur Oberlicht), nicht in der Tauri-App geprüft. +- ◐ **[100] Dachfenster und Öffnungen in Dach/Decke.** (29.10., Grundlage für Lukarnen) Wirt allgemein: `Opening` + neu `hostRoofId` | `hostCeilingId` (dann `hostWallId` leer), `hostPoint` (Mitte im Grundriss), `hostAngle` + (Breitenrichtung auf waagrechten Flächen). `width` quer zum Gefälle, `height` entlang des Gefälles, in der + Dachebene gemessen. Kern `opening_shape::host_frame` (Dachfläche über den Punkt, Normale, alle Schichten); + 3D: Loch durch jede Dachschicht (Reststücke + Leibungen, Schichtkörper bleiben dicht), Rahmen/Glas/Eindeck- + rahmen (vereinfacht) als Quader, Live-Schnitt-Schichten mit Loch; Decke: Ring in die Aussparungen + (`ceiling_hole_rings`: 3D, Grundriss, IFC). Grundriss (Dach-Geschoss): Rahmen und Glas gestrichelt, Pick über + die Öffnung; Schnitt: Lücke in allen Dachschichten, Rahmen/Glas/Eindeckrahmen geschnitten; Ansicht: Rahmen + + Glas auf zugewandten Flächen; IFC: IfcOpeningElement im IfcRoof (bzw. IfcSlab) + IfcWindow (Netz). Befehl + „Dachfenster" (`roofwindow`, Alias dachfenster/oberlicht): ein Klick, 78 × 118 cm, Dach mit dem Punkt im + Umriss, sonst Decke des Geschosses. Geprüft: Rust-Tests, CLI-Grundriss/-Schnitt/-Ansicht angesehen (Linux). + Offen: Verschieben/Griffe und Objekt-Info für Dach-Öffnungen (Info zeigt Wand-Felder), Fenster-/Türliste + (Geschoss aus der Wand), Löschen des Dachs löscht die Fenster nicht mit (Prüfung meldet den fehlenden Wirt), + Eindeckrahmen nur als flacher Ring, Lukarnen, nicht in der Tauri-App geprüft. · M ## Priorität 4 — später diff --git a/src-tauri/core/src/cmd_solid.rs b/src-tauri/core/src/cmd_solid.rs index 5b082074..37c0bd5a 100644 --- a/src-tauri/core/src/cmd_solid.rs +++ b/src-tauri/core/src/cmd_solid.rs @@ -403,6 +403,49 @@ fn ceiling_opening_ops(root: &Map, v: &Value, ctx: &Ctx) -> Vec, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let at = p_of(v, "p"); + if !(at.0.is_finite() && at.1.is_finite()) { + return Vec::new(); + } + let contains = |e: &&Value| { + let ring = ring_of(e); + ring.len() >= 3 && point_in_polygon(at, &ring) + }; + let on_level = |e: &&Value| crate::cmd_create::floor_of(e) == Some(ctx.level); + let roofs = arr(root.get("roofs")); + let host = roofs + .iter() + .filter(contains) + .find(on_level) + .or_else(|| roofs.iter().find(contains)) + .map(|r| ("hostRoofId", id_of(r))) + .or_else(|| arr(root.get("ceilings")).iter().filter(contains).find(on_level).map(|c| ("hostCeilingId", id_of(c)))); + let Some((key, Some(host_id))) = host else { return Vec::new() }; + let width = num_or(field(v, "width"), 0.78).max(0.1); + let height = num_or(field(v, "height"), 1.18).max(0.1); + let mut f = vec![ + ("id", s(&ids.next("O"))), + ("type", s("opening")), + ("hostWallId", s("")), + (key, s(host_id)), + ("hostPoint", pv(at)), + ("categoryCode", crate::cmd_create::category_or(root, "21", ctx)), + ("kind", s("window")), + ("position", js_num(0.0)), + ("width", js_num(width)), + ("height", js_num(height)), + ("sillHeight", js_num(0.0)), + ]; + if let Some(t) = arr(root.get("windowTypes")).first().and_then(|t| field(t, "id")).filter(|id| truthy(Some(id))) { + f.push(("typeId", t.clone())); + } + add_op("openings", vec![obj(f)]) +} + /// Hof-Ring des Dach-Hof-Befehls: ≥ 3 Punkte wie gezeichnet, 2 Punkte als Rechteck. fn hole_ring(points: &[V]) -> Option> { match points { @@ -529,6 +572,7 @@ pub fn ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> "terrain" => terrain_ops(root, ids), "ceilingOpening" => ceiling_opening_ops(root, v, ctx), "roofHole" => roof_hole_ops(root, v, ctx), + "roofWindow" => roof_window_ops(root, v, ctx, ids), "sectionline" => sectionline_ops(root, v, ids), _ => return None, }) @@ -590,6 +634,29 @@ mod tests { assert_eq!(extruded_solid_spec(&solid, 1.0).unwrap()["kind"], "loft"); } + /// [100] Dachfenster: Dach mit dem Punkt im Umriss (aktives Geschoss zuerst), sonst Decke, sonst nichts. + #[test] + fn dachfenster_befehl() { + let rect = json!([{"x": 0, "y": 0}, {"x": 5, "y": 0}, {"x": 5, "y": 4}, {"x": 0, "y": 4}]); + let root = json!({"roofs": [{"id": "R", "floorId": "og", "outline": rect}], "ceilings": [{"id": "C", "floorId": "eg", "outline": rect}], "windowTypes": [{"id": "wt"}]}); + let root = root.as_object().unwrap(); + let run = |level: &str, x: f64| { + let mut ids = IdGen::new("s"); + let ctx = Ctx { level, floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 }; + ops(root, &json!({"cmd": "roofWindow", "p": {"x": x, "y": 1.0}}), &ctx, &mut ids).unwrap() + }; + let item = |o: &[Op]| match &o[0] { + Op::Add { items, .. } => items[0].clone(), + _ => panic!(), + }; + let r = item(&run("og", 2.0)); + assert_eq!((r["hostRoofId"].as_str(), r["hostWallId"].as_str(), r["width"].as_f64(), r["typeId"].as_str()), (Some("R"), Some(""), Some(0.78), Some("wt"))); + assert_eq!(r["hostPoint"]["x"], 2.0); + // Dach liegt auf einem anderen Geschoss: trotzdem Dach (Dächer überdecken Geschosse). + assert_eq!(item(&run("eg", 2.0))["hostRoofId"], "R"); + assert!(run("eg", 9.0).is_empty()); + } + #[test] fn gelaende_aus_hoehenlinien() { let c = json!([{"z": 1, "pts": [{"x": 0, "y": 0}, {"x": 4, "y": 0}]}, {"z": 2, "pts": [{"x": 0, "y": 3}, {"x": 4, "y": 3}]}]); diff --git a/src-tauri/core/src/ifc_data.rs b/src-tauri/core/src/ifc_data.rs index 44d447e4..6b762df0 100644 --- a/src-tauri/core/src/ifc_data.rs +++ b/src-tauri/core/src/ifc_data.rs @@ -46,6 +46,7 @@ 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; +const REC_OPENING_SOLID: f64 = 15.0; /// Toleranz des Kerns (`wall_bands.rs::EPS`) für „Öffnung trifft Band". const BAND_EPS: f64 = 1e-4; @@ -423,6 +424,101 @@ fn fill_params(p: &Project, o: &Opening) -> FillParams { /// FILL schreiben: Wandachse, Achs-Intervall und Höhen der Öffnung, Querausdehnung der Wand /// (`host` = n_lo aussen, n_hi), dann die Parameter. +/// Psets und Basismengen einer Tür/eines Fensters (Kennwerte nur mit Angabe im Modell). +fn fill_psets(p: &Project, o: &Opening, width: f64, height: f64) -> Vec { + let is_door = o.kind == ElementKind::Door; + 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" + }; + // Nummer ersetzt den Typnamen als Reference; Kennwerte nur mit Angabe im Modell. + if let Some(mark) = o.mark.as_deref().map(str::trim).filter(|m| !m.is_empty()) { + props.retain(|x| !matches!(x, Prop::Ident("Reference", _))); + props.insert(0, ident("Reference", mark)); + } + if let Some(e) = crate::opening_schedule::opening_external(p, o) { + props.push(Prop::Bool("IsExternal", e)); + } + let label = |name: &'static str, v: &Option| v.as_deref().map(str::trim).filter(|x| !x.is_empty()).map(|x| Prop::Label(name, x.to_string())); + props.extend(label("FireRating", &o.fire_rating)); + props.extend(label("AcousticRating", &o.sound_class)); + props.extend(o.u_value.filter(|u| *u > 0.0).map(|u| Prop::Thermal("ThermalTransmittance", u))); + props.extend(label("SecurityRating", &o.burglary_class)); + let mut psets = vec![Pset { name: pset_name, props }]; + psets.extend(qto(if is_door { "Qto_DoorBaseQuantities" } else { "Qto_WindowBaseQuantities" }, qty::opening_quantities(width, height))); + psets +} + +/// Öffnungskörper einer Form-/Dachöffnung ([G3]/[100]): Profil in (x, y) des Systems `origin`/`x_dir`/ +/// `z_dir`, entlang `z_dir` um `depth` extrudiert (Welt relativ zur Geschoss-UK). +struct SolidOpening { + host: String, + profile: Vec<[f64; 2]>, + origin: [f64; 3], + x_dir: [f64; 3], + z_dir: [f64; 3], + depth: f64, +} + +/// Dreiecke eines 8-Ecken-Quaders wie `model3d::OPENING_BOX_TRIS`. +const BOX_TRIS: [u32; 36] = [0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6, 0, 1, 5, 0, 5, 4, 2, 3, 7, 2, 7, 6, 0, 2, 6, 0, 6, 4, 1, 3, 7, 1, 7, 5]; + +fn push_box(positions: &mut Vec, indices: &mut Vec, b: &[f64; 24], base: f64) { + let at = (positions.len() / 3) as u32; + for c in b.chunks_exact(3) { + positions.extend_from_slice(&[c[0], c[1], c[2] - base]); + } + indices.extend(BOX_TRIS.iter().map(|i| at + i)); +} + +/// Füllung (Rahmen, Glas/Blatt) einer Formöffnung als Netz, Z relativ zur Geschoss-UK. +fn shaped_fill_mesh(p: &Project, wall: &Wall, o: &Opening, c: &Cutout, base: f64) -> (Vec, Vec) { + let total = p.wall_thickness(wall, 0.2); + let wr = crate::opening_geom::WallRef { + start: crate::opening_geom::v(wall.start.x, wall.start.y), + end: crate::opening_geom::v(wall.end.x, wall.end.y), + total, + ref_off: crate::joins::reference_offset(model3d::wall_reference(wall), total), + }; + let wall_rgb = model3d::shaped_wall_opening_meshes(p, wall, &wr, o, [c.from, c.to, c.z_bottom, c.z_top]); + let (mut positions, mut indices) = (Vec::new(), Vec::new()); + // Die Füllkörper (Wandfarbe) gehören zur Wand, nicht zur Füllung: die Öffnung schneidet sie ohnehin nicht. + let fills = crate::opening_shape::opening_outline(o, c.to - c.from, c.z_top - c.z_bottom).map_or(0, |poly| crate::opening_shape::fill_quads(&poly, c.to - c.from, c.z_top - c.z_bottom).len()); + for m in wall_rgb.iter().skip(fills) { + if let Ok(b) = <[f64; 24]>::try_from(m.positions.as_slice()) { + push_box(&mut positions, &mut indices, &b, base); + } + } + (positions, indices) +} + +#[allow(clippy::too_many_arguments)] +fn w_solid_opening(f: &mut Flat, s: &SolidOpening, structure: f64, o: &Opening, label: &str, (width, height): (f64, f64), psets: &[Pset], fill: &(Vec, Vec)) { + let (h, oid, lab) = (f.str(&s.host), f.str(&o.id), f.str(label)); + f.nums(&[REC_OPENING_SOLID, h, structure, oid, if o.kind == ElementKind::Door { 1.0 } else { 0.0 }, lab]); + f.num(s.profile.len() as f64); + for q in &s.profile { + f.nums(q); + } + f.nums(&s.origin).nums(&s.x_dir).nums(&s.z_dir).nums(&[s.depth, height, width]); + w_psets(f, psets); + w_mesh(f, &fill.0, &fill.1, false); +} + 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)]); @@ -667,6 +763,24 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result i += 3; } } + // Formöffnungen ([G3]): Füllkörper zwischen Rechteck-Loch und Umriss gehören zur Wand. + for &(k, c) in cutouts_by_wall.get(&wall.id).map_or(&[][..], |v| v.as_slice()) { + let o = &openings[k]; + let Some(poly) = crate::opening_shape::opening_outline(o, c.to - c.from, c.z_top - c.z_bottom) else { continue }; + let n = crate::opening_shape::fill_quads(&poly, c.to - c.from, c.z_top - c.z_bottom).len(); + let total = p.wall_thickness(wall, 0.2); + let wr = crate::opening_geom::WallRef { + start: crate::opening_geom::v(wall.start.x, wall.start.y), + end: crate::opening_geom::v(wall.end.x, wall.end.y), + total, + ref_off: crate::joins::reference_offset(model3d::wall_reference(wall), total), + }; + for m in model3d::shaped_wall_opening_meshes(&p, wall, &wr, o, [c.from, c.to, c.z_bottom, c.z_top]).iter().take(n) { + if let Ok(b) = <[f64; 24]>::try_from(m.positions.as_slice()) { + push_box(&mut positions, &mut indices, &b, base); + } + } + } if indices.is_empty() { continue; } @@ -711,7 +825,8 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result psets.push(Pset { name: "Pset_SlabCommon", props: slab_props }); } // 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(); + let hole_rings = crate::opening_shape::ceiling_hole_rings(&p, c); + let inner: Vec<&[Vec2]> = hole_rings.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()); @@ -736,40 +851,25 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result } 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" - }; - // Nummer ersetzt den Typnamen als Reference; Kennwerte nur mit Angabe im Modell. - if let Some(mark) = o.mark.as_deref().map(str::trim).filter(|m| !m.is_empty()) { - props.retain(|x| !matches!(x, Prop::Ident("Reference", _))); - props.insert(0, ident("Reference", mark)); - } - if let Some(e) = crate::opening_schedule::opening_external(&p, o) { - props.push(Prop::Bool("IsExternal", e)); - } - let label = |name: &'static str, v: &Option| v.as_deref().map(str::trim).filter(|x| !x.is_empty()).map(|x| Prop::Label(name, x.to_string())); - props.extend(label("FireRating", &o.fire_rating)); - props.extend(label("AcousticRating", &o.sound_class)); - props.extend(o.u_value.filter(|u| *u > 0.0).map(|u| Prop::Thermal("ThermalTransmittance", u))); - props.extend(label("SecurityRating", &o.burglary_class)); - 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 psets = fill_psets(&p, o, c.to - c.from, depth); let label = crate::plan::walls::opening_label(o); + // Formöffnung ([G3]): Öffnungskörper = Umriss quer durch die Wand, Füllung als Netz. + if let Some(poly) = crate::opening_shape::opening_outline(o, c.to - c.from, depth) { + let u = normalize(sub(wall.end, wall.start)); + let ln = left_normal(u); + let at = add_scaled(add_scaled(wall.start, u, c.from), ln, host.1 + OPENING_OVERSHOOT); + let solid = SolidOpening { + host: format!("wall/{}", wall.id), + profile: poly, + origin: [at.x, at.y, c.z_bottom - base_of(structure)], + x_dir: [u.x, u.y, 0.0], + z_dir: [-ln.x, -ln.y, 0.0], + depth: host.1 - host.0 + 2.0 * OPENING_OVERSHOOT, + }; + let fill = shaped_fill_mesh(&p, wall, o, &c, base_of(structure)); + w_solid_opening(&mut f, &solid, structure, o, &label, (c.to - c.from, depth), &psets, &fill); + continue; + } let a = f.str(&wall.id); let oid = f.str(&o.id); let lab = f.str(&label); @@ -945,6 +1045,40 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result } p.roofs = roofs; + // ── Dach-/Deckenfenster ([100]): IfcOpeningElement im Dach bzw. in der Decke, IfcWindow/IfcDoor darin ── + for o in openings.iter() { + let Some(fr) = crate::opening_shape::host_frame(&p, o) else { continue }; + let (host_key, floor_id) = if fr.plane.is_some() { + let r = &p.roofs.as_deref().unwrap_or(&[])[fr.host]; + (format!("roof/{}", r.id), r.floor_id.clone()) + } else { + let c = &p.ceilings.as_deref().unwrap_or(&[])[fr.host]; + (format!("slab/{}", c.id), c.floor_id.clone()) + }; + let structure = structure_of(&floor_id); + let base = base_of(structure); + 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 (w, h) = (o.width, o.height); + // Profil-Y = Z × X = −eh: Ursprung an der oberen Ecke, das Profil läuft das Gefälle hinab. + let corner = fr.at(-w / 2.0, h / 2.0, -0.5); + let solid = SolidOpening { + host: host_key, + profile: vec![[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]], + origin: [corner[0], corner[1], corner[2] - base], + x_dir: fr.ew, + z_dir: [-fr.n[0], -fr.n[1], -fr.n[2]], + depth: fr.thickness + 1.0, + }; + let (mut positions, mut indices) = (Vec::new(), Vec::new()); + for (_, b) in crate::opening_shape::surface_window_boxes(&p, o, &fr) { + push_box(&mut positions, &mut indices, &b, base); + } + let psets = fill_psets(&p, o, w, h); + let label = crate::plan::walls::opening_label(o); + w_solid_opening(&mut f, &solid, structure, o, &label, (w, h), &psets, &(positions, indices)); + } + // ── Stützen → IfcColumn (Profil-Extrusion, Material = Bauteil) ────────── for col in p.columns.as_deref().unwrap_or(&[]) { let footprint = model3d::column_footprint(col); @@ -1055,6 +1189,20 @@ mod tests { text.split('\0').map(String::from).collect() } + /// [G3]/[100] Formöffnung und Dachfenster als Öffnungskörper-Datensatz mit Wirt. + #[test] + fn formoeffnung_und_dachfenster() { + let mut p = sample(); + for o in p.openings.iter_mut().flatten().filter(|o| o.id == "O1") { + o.shape = Some(OpeningShape::Spitzbogen); + } + p.openings.as_mut().unwrap().push(Opening { id: "DF".into(), kind: ElementKind::Window, width: 0.78, height: 1.18, host_roof_id: Some("RF1".into()), host_point: Some(Vec2 { x: 2.5, y: 1.0 }), ..Default::default() }); + let f = ifc_export_data(&p, &IfcOptions::default()).unwrap(); + let s = strings(&f); + assert!(s.iter().any(|x| x == "wall/W1") && s.iter().any(|x| x == "roof/RF1")); + assert_eq!(f.nums.iter().filter(|v| **v == REC_OPENING_SOLID).count() >= 2, true); + } + #[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() }; diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index ff77e7be..cccf6e3c 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -48,6 +48,7 @@ pub mod gpu_compile; pub mod plan_stairs; pub mod plan_walls; pub mod opening_geom; +pub mod opening_shape; pub mod plan_openings; pub mod delaunay; pub mod document; diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 201c6b2a..126f4eff 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -2085,6 +2085,29 @@ pub enum OpeningOpeningDir { Unknown, } +/// Umrissform einer Öffnung ([G3]). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)] +pub enum OpeningShape { + #[default] + #[serde(rename = "rechteck")] + Rechteck, + #[serde(rename = "rundbogen")] + Rundbogen, + #[serde(rename = "segmentbogen")] + Segmentbogen, + #[serde(rename = "spitzbogen")] + Spitzbogen, + #[serde(rename = "rund")] + Rund, + #[serde(rename = "schraeg")] + Schraeg, + #[serde(rename = "giebel")] + Giebel, + #[serde(other)] + #[ts(skip)] + Unknown, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)] pub enum OpeningLintelLines { #[default] @@ -2300,6 +2323,40 @@ pub struct Opening { #[serde(rename = "sillLineStyle", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub sill_line_style: Option, + /// Umriss der Öffnung in der Wandebene ([G3]); fehlt ⇒ Rechteck. Bestimmt den Wandausschnitt + /// (Schnitt, Ansicht, 3D, IFC-Öffnungskörper); der Grundriss bleibt beim SIA-Symbol. Die + /// Öffnung füllt ihr Rechteck `width × height`; Bogen/Schräge liegen oben (Rund: Ellipse darin). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional, inline)] + pub shape: Option, + /// Stichhöhe der Form in Metern ([G3]): Segmentbogen = Bogenstich (Default Breite/6), Spitzbogen = + /// Höhe über dem Kämpfer (≥ Breite/2, Default gleichseitig), Giebel = Höhe des Dreiecks (Default + /// Breite/2), Schräg = Höhenunterschied links→rechts (> 0 rechts höher, Default Breite/2). + /// Rundbogen/Rund/Rechteck ignorieren es. + #[serde(rename = "shapeRise", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub shape_rise: Option, + /// Wirt Dach ([100], Dachfenster): Öffnung in einer Dachfläche; `hostWallId` bleibt leer. Lage + /// über {@link hostPoint}; `width` quer zum Gefälle, `height` entlang des Gefälles (in der + /// Dachebene gemessen); `position`/`sillHeight` gelten nicht. + #[serde(rename = "hostRoofId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub host_roof_id: Option, + /// Wirt Decke ([100], Deckenöffnung mit Oberlicht): Öffnung in einer Decke, Lage über + /// {@link hostPoint}, `width` × `height` waagrecht (gedreht um {@link hostAngle}). + #[serde(rename = "hostCeilingId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub host_ceiling_id: Option, + /// Nur Dach-/Deckenwirt ([100]): Mittelpunkt der Öffnung im Grundriss (Meter). + #[serde(rename = "hostPoint", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub host_point: Option, + /// Nur Dach-/Deckenwirt ([100]): Drehung der Breitenrichtung im Grundriss in Grad, wo die + /// Fläche waagrecht ist (Decke, Flachdach); geneigte Dachflächen richten die Breite längs der + /// Traufe aus. Fehlt ⇒ 0 (x-Achse). + #[serde(rename = "hostAngle", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub host_angle: Option, #[serde(flatten)] #[ts(skip)] pub extra: Extra, diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index 7d3f3642..124472ce 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -106,9 +106,10 @@ pub fn emit_slabs(p: &Project) -> Vec { let (z_bottom, z_top) = p.ceiling_vertical_extent(c); let layers = ceiling_layers(p, c); w.ring(&c.outline); - let openings = c.openings.as_deref().unwrap_or(&[]); + // Aussparungen inkl. der Deckenöffnungen ([100]). + let openings = crate::opening_shape::ceiling_hole_rings(p, c); w.num(openings.len() as f64); - for o in openings { + for o in &openings { w.ring(o); } w.num(z_bottom).num(z_top).num(layers.map_or(0, |l| l.len()) as f64); @@ -729,6 +730,7 @@ fn write_opening(w: &mut FlatWriter, p: &Project, op: &Opening) { /// Öffnungs-Einbauteile als Quader-Meshes (`emitOpeningMeshes`); `detail`: 0 grob, 1 mittel, 2 fein. pub fn emit_opening_meshes(p: &Project, detail: f64) -> Vec { + let mut shaped: Vec = Vec::new(); let mut w = FlatWriter::new(); w.num(detail).num(p.walls.len() as f64); for wall in &p.walls { @@ -743,6 +745,11 @@ pub fn emit_opening_meshes(p: &Project, detail: f64) -> Vec { let o_bottom = zb + op.sill_height.max(0.0); let o_top = zt.min(o_bottom + op.height); let t = *thickness.get_or_insert_with(|| p.wall_thickness(wall, 0.2)); + // Formöffnung ([G3]): Füllkörper, Rahmen und Glas entlang des Umrisses statt der Quader-Teile. + if crate::opening_shape::is_shaped(op) { + shaped.extend(shaped_wall_opening_meshes(p, wall, &wr, op, [from, to, o_bottom, o_top])); + continue; + } w.nums(&[from, to, o_bottom, o_top, flag(op.kind != ElementKind::Window), t]); write_opening(&mut w, p, op); count += 1.0; @@ -768,6 +775,87 @@ pub fn emit_opening_meshes(p: &Project, detail: f64) -> Vec { }); i += 25; } + out.extend(shaped); + // Dach-/Deckenfenster ([100]). + for op in p.openings.as_deref().unwrap_or(&[]) { + if let Some(f) = crate::opening_shape::host_frame(p, op) { + for (part, positions) in crate::opening_shape::surface_window_boxes(p, op, &f) { + out.push(box_mesh(positions, PART_RGB[part as usize])); + } + } + } + out +} + +fn box_mesh(positions: [f64; 24], color: Rgb) -> RMesh { + RMesh { positions: positions.to_vec(), indices: OPENING_BOX_TRIS.to_vec(), kind: "extrusion", color, vertex_colors: None, material_index: None } +} + +/// Formöffnung in der Wand ([G3]) als Quader: Füllkörper (Wandfarbe, ganze Wanddicke) zwischen dem +/// Rechteck-Loch und dem Umriss, Rahmen-Ring und Glas (bzw. Türblatt) entlang des Umrisses. Rahmenlage +/// quer zur Wand wie bei den Rechteck-Öffnungen (`openings3d::frame_normal_range`). Nicht für Formen: +/// Anschlag, Fensterbank, Storenkasten, Flügel-/Sprossenteilung (bleiben beim Rechteck). +pub(crate) fn shaped_wall_opening_meshes(p: &Project, wall: &Wall, wr: &WallRef, op: &Opening, [from, to, zb, zt]: [f64; 4]) -> Vec { + use crate::opening_shape as os; + let (w, h) = (to - from, zt - zb); + let Some(poly) = os::opening_outline(op, w, h) else { return Vec::new() }; + let (dx, dy) = (wall.end.x - wall.start.x, wall.end.y - wall.start.y); + let len = hypot2(dx, dy); + if len < 1e-9 { + return Vec::new(); + } + let (ux, uy) = (dx / len, dy / len); + // Quer-Achse wie `openings3d` (rechte Normale); die Wandmitte liegt bei −ref_off. + let shift = -wr.ref_off; + let map = |u: f64, v: f64, n: f64| -> [f64; 3] { + let (s, t) = (from + u, n + shift); + [wall.start.x + ux * s + uy * t, wall.start.y + uy * s - ux * t, zb + v] + }; + let half = wr.total / 2.0; + let mut out = Vec::new(); + let wall_rgb = resolve_wall_bands(p, &wall_material_color_maps(p), wall, false).0.first().map_or(WALL_RGB, |b| b.color); + for q in os::fill_quads(&poly, w, h) { + out.push(box_mesh(os::quad_box(&q, -half, half, &map), wall_rgb)); + } + let door = op.kind == ElementKind::Door; + let ty = if door { + p.door_type(op).map(|t| (t.frame_depth, t.inset_from_face, t.inset_face == Some(DoorTypeInsetFace::Innen), t.inset_face == Some(DoorTypeInsetFace::Mitte), t.frame_width)) + } else { + p.window_type(op).map(|t| (t.frame_depth, t.inset_from_face, t.inset_face == Some(WindowTypeInsetFace::Innen), t.inset_face == Some(WindowTypeInsetFace::Mitte), t.frame_width)) + }; + let glass = PART_RGB[0]; + let Some((fd, inset_face, inner, mid, fw)) = ty else { + // Ohne Typ: eine Vollscheibe mittig (wie das Rechteck-Fenster ohne Typ). + if !door { + let g = crate::openings3d::GLASS_HALF_THICK; + for q in os::strip_quads(&poly) { + out.push(box_mesh(os::quad_box(&q, -g, g, &map), glass)); + } + } + return out; + }; + let depth = crate::openings3d::across_wall_depth(fd.unwrap_or(f64::NAN).max(0.0), wr.total); + let (n_min, n_max) = crate::openings3d::frame_normal_range(half, depth, inset_face.unwrap_or(0.0), inner, mid); + let fw = fw.filter(|v| *v > 0.0).unwrap_or(crate::openings3d::DEFAULT_FRAME_WIDTH).min(w.min(h) / 3.0); + let inner_poly = os::inset(&poly, fw); + for (k, q) in os::ring_quads(&poly, &inner_poly).into_iter().enumerate() { + // Tür: unten keine Schwelle (Kante 0 = Boden). + if door && k == 0 && op.shape != Some(OpeningShape::Rund) { + continue; + } + out.push(box_mesh(os::quad_box(&q, n_min, n_max, &map), PART_RGB[1])); + } + let (inner_glass, color) = if door { + let c = (n_min + n_max) / 2.0; + let t = crate::openings3d::DOOR_LEAF_THICK / 2.0; + ((c - t, c + t), PART_RGB[5]) + } else { + let n1 = n_max - 0.02; + ((n1 - 2.0 * crate::openings3d::GLASS_HALF_THICK, n1), glass) + }; + for q in os::strip_quads(&inner_poly) { + out.push(box_mesh(os::quad_box(&q, inner_glass.0, inner_glass.1, &map), color)); + } out } @@ -901,7 +989,7 @@ fn push_fan_triangles(positions: &mut Vec, indices: &mut Vec, pts: &[V } /// Newell-Normale einer Dachfläche, nach oben orientiert (`planeNormalUp`). -fn plane_normal_up(pts: &[V3]) -> V3 { +pub(crate) fn plane_normal_up(pts: &[V3]) -> V3 { let (mut nx, mut ny, mut nz) = (0.0, 0.0, 0.0); for i in 0..pts.len() { let c = pts[i]; @@ -1175,6 +1263,139 @@ fn push_roof_slab_between(positions: &mut Vec, indices: &mut Vec, top: } } +/// Dachfenster-Loch in einer Dachfläche ([100]): Ecken auf der Dach-Oberkante (Gegenuhrzeigersinn um +/// `n`) und die Normale. +pub(crate) struct RoofHoleRect { + pub corners: [V3; 4], + pub n: V3, +} + +fn sub3(a: V3, b: V3) -> V3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +/// Schneidet aus einer ebenen, konvexen Fläche die Rechtecke `holes` (senkrecht zur Fläche) aus: +/// konvexe Reststücke, gleicher Drehsinn wie `poly` (Sutherland-Hodgman je Rechteck-Kante). +pub(crate) fn clip_plane_holes(poly: &[V3], holes: &[RoofHoleRect]) -> Vec> { + let Some(first) = holes.first() else { return vec![poly.to_vec()] }; + let n = first.n; + let e1 = { + let d = sub3(first.corners[1], first.corners[0]); + let l = dot3(d, d).sqrt().max(1e-12); + [d[0] / l, d[1] / l, d[2] / l] + }; + let e2 = cross3(n, e1); + let offs = poly.first().map_or(0.0, |q| dot3(*q, n)); + let to2 = |q: V3| [dot3(q, e1), dot3(q, e2)]; + let lift = |q: [f64; 2]| -> V3 { [e1[0] * q[0] + e2[0] * q[1] + n[0] * offs, e1[1] * q[0] + e2[1] * q[1] + n[1] * offs, e1[2] * q[0] + e2[2] * q[1] + n[2] * offs] }; + let clip = |pts: &[[f64; 2]], a: [f64; 2], b: [f64; 2], keep_left: bool| -> Vec<[f64; 2]> { + let side = |p: [f64; 2]| { + let c = (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]); + if keep_left { c } else { -c } + }; + let mut out = Vec::new(); + for i in 0..pts.len() { + let (p, q) = (pts[i], pts[(i + 1) % pts.len()]); + let (sp, sq) = (side(p), side(q)); + if sp >= 0.0 { + out.push(p); + } + if (sp >= 0.0) != (sq >= 0.0) { + let t = sp / (sp - sq); + out.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]); + } + } + out + }; + let area = |pts: &[[f64; 2]]| (0..pts.len()).map(|i| pts[i][0] * pts[(i + 1) % pts.len()][1] - pts[(i + 1) % pts.len()][0] * pts[i][1]).sum::().abs() / 2.0; + let mut pieces: Vec> = vec![poly.iter().map(|q| to2(*q)).collect()]; + for h in holes { + let r: Vec<[f64; 2]> = h.corners.iter().map(|q| to2(*q)).collect(); + let mut next = Vec::new(); + for piece in pieces { + let mut rest = piece; + for k in 0..4 { + let (a, b) = (r[k], r[(k + 1) % 4]); + let outside = clip(&rest, a, b, false); + if outside.len() >= 3 && area(&outside) > 1e-10 { + next.push(outside); + } + rest = clip(&rest, a, b, true); + if rest.len() < 3 { + break; + } + } + } + pieces = next; + } + pieces.into_iter().map(|pc| pc.into_iter().map(lift).collect()).collect() +} + +/// Wie [`push_roof_slab_between`], mit Dachfenster-Löchern: Deck-/Bodenfläche als Reststücke, dazu je +/// Loch vier Leibungen von `d0` bis `d1` unter der Dach-Oberkante. +fn push_roof_slab_with_holes(positions: &mut Vec, indices: &mut Vec, top: &[V3], bottom: &[V3], shared: &[bool], holes: &[RoofHoleRect], d0: f64, d1: f64) { + let mut nz = 0.0; + for i in 0..top.len() { + let a = top[i]; + let b = top[(i + 1) % top.len()]; + nz += (a[0] - b[0]) * (a[1] + b[1]); + } + let ccw = nz > 0.0; + for pc in clip_plane_holes(top, holes) { + push_fan_triangles(positions, indices, &pc, !ccw); + } + for pc in clip_plane_holes(bottom, holes) { + push_fan_triangles(positions, indices, &pc, ccw); + } + for i in 0..top.len() { + if shared[i] { + continue; + } + let j = (i + 1) % top.len(); + let base = (positions.len() / 3) as u32; + positions.extend(top[i]); + positions.extend(bottom[i]); + positions.extend(bottom[j]); + positions.extend(top[j]); + if ccw { + indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]); + } else { + indices.extend([base, base + 2, base + 1, base, base + 3, base + 2]); + } + } + for h in holes { + let at = |q: V3, d: f64| [q[0] - h.n[0] * d, q[1] - h.n[1] * d, q[2] - h.n[2] * d]; + let center = [0, 1, 2].map(|k| h.corners.iter().map(|c| c[k]).sum::() / 4.0); + for k in 0..4 { + let (a, b) = (h.corners[k], h.corners[(k + 1) % 4]); + let quad = [at(a, d0), at(b, d0), at(b, d1), at(a, d1)]; + let nrm = cross3(sub3(quad[1], quad[0]), sub3(quad[3], quad[0])); + let mid = [0, 1, 2].map(|c| (a[c] + b[c]) / 2.0); + let inward = dot3(nrm, sub3(center, mid)) > 0.0; + let base = (positions.len() / 3) as u32; + for q in quad { + positions.extend(q); + } + if inward { + indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]); + } else { + indices.extend([base, base + 2, base + 1, base, base + 3, base + 2]); + } + } + } +} + +/// Dachfenster-Löcher je Dachfläche eines Dachs (Index in `Project::roofs`). +pub(crate) fn roof_holes_by_plane(p: &Project, roof_index: usize, planes: usize) -> Vec> { + let mut out: Vec> = (0..planes).map(|_| Vec::new()).collect(); + for (o, f) in crate::opening_shape::roof_openings(p, roof_index) { + if let Some(list) = f.plane.and_then(|i| out.get_mut(i)) { + list.push(RoofHoleRect { corners: crate::opening_shape::host_rect_plan(&f, o.width, o.height), n: f.n }); + } + } + out +} + fn roof_color(p: &Project, override_color: Option, component_id: &str) -> Result { if let Some(c) = override_color { return Ok(c); @@ -1190,11 +1411,12 @@ fn roof_color(p: &Project, override_color: Option, component_id: &str) -> R pub fn emit_roofs(p: &Project, only_roof: Option<&str>) -> Result, String> { let maps = material_color_maps(p, only_roof); let mut out = Vec::new(); - for roof in p.roofs.as_deref().unwrap_or(&[]).iter().filter(|r| only_roof.is_none_or(|id| r.id == id)) { + for (ri, roof) in p.roofs.as_deref().unwrap_or(&[]).iter().enumerate().filter(|(_, r)| only_roof.is_none_or(|id| r.id == id)) { let eaves_z = p.roof_base_elevation(roof); let g = crate::roof::roof_geometry(&roof.params(), eaves_z); let override_color = roof.color.as_deref().filter(|c| !c.is_empty()).map(|c| hex_to_rgb(c, ROOF_RGB)); let mitre = Mitre::new(&g.planes); + let holes = roof_holes_by_plane(p, ri, g.planes.len()); let mut offset_above = 0.0; for layer in p.roof_layers(roof) { let t = layer.thickness.max(0.0); @@ -1210,7 +1432,11 @@ pub fn emit_roofs(p: &Project, only_roof: Option<&str>) -> Result, St } let top = mitre.at(i, offset_above); let bottom = mitre.at(i, offset_above + t); - push_roof_slab_between(&mut positions, &mut indices, &top, &bottom, &mitre.shared[i]); + if holes[i].is_empty() { + push_roof_slab_between(&mut positions, &mut indices, &top, &bottom, &mitre.shared[i]); + } else { + push_roof_slab_with_holes(&mut positions, &mut indices, &top, &bottom, &mitre.shared[i], &holes[i], offset_above, offset_above + t); + } } if !indices.is_empty() { out.push(RMesh { positions, indices, kind: "extrusion", color, vertex_colors: None, material_index }); @@ -1224,10 +1450,11 @@ pub fn emit_roofs(p: &Project, only_roof: Option<&str>) -> Result, St /// Dachschicht-Eingabe für den 3D-Live-Schnitt (`emitRoofCutLayers`). pub fn emit_roof_cut_layers(p: &Project) -> Result, String> { let mut out = Vec::new(); - for roof in p.roofs.as_deref().unwrap_or(&[]) { + for (ri, roof) in p.roofs.as_deref().unwrap_or(&[]).iter().enumerate() { let eaves_z = p.roof_base_elevation(roof); let g = crate::roof::roof_geometry(&roof.params(), eaves_z); let override_color = roof.color.as_deref().filter(|c| !c.is_empty()).map(|c| hex_to_rgb(c, ROOF_RGB)); + let holes = roof_holes_by_plane(p, ri, g.planes.len()); let mut offset_above = 0.0; for layer in p.roof_layers(roof) { let t = layer.thickness.max(0.0); @@ -1237,10 +1464,13 @@ pub fn emit_roof_cut_layers(p: &Project) -> Result, String> { let color = roof_color(p, override_color, &layer.component_id)?; let line = resolve_cut_line_style(p, layer.joint_line_style_id.as_deref()); let cut = line.map(|(c, w)| RCutMeta { line_color: Some(c), line_weight: Some(w), ..Default::default() }); - for plane in &g.planes { + for (i, plane) in g.planes.iter().enumerate() { let nrm = plane_normal_up(plane); - let polygon = plane.iter().map(|q| [q[0] - nrm[0] * offset_above, q[1] - nrm[1] * offset_above, q[2] - nrm[2] * offset_above]).collect(); - out.push(RRoofLayer { polygon, normal: nrm, thickness: t, color, cut: cut.clone() }); + let polygon: Vec = plane.iter().map(|q| [q[0] - nrm[0] * offset_above, q[1] - nrm[1] * offset_above, q[2] - nrm[2] * offset_above]).collect(); + // Dachfenster ([100]): Reststücke statt der ganzen Fläche (Loch im Live-Schnitt). + for polygon in clip_plane_holes(&polygon, &holes[i]) { + out.push(RRoofLayer { polygon, normal: nrm, thickness: t, color, cut: cut.clone() }); + } } offset_above += t; } @@ -1593,6 +1823,74 @@ mod tests { assert!(m.at(0, 0.2)[0][2] < 5.2); } + fn sample() -> Project { + serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap() + } + + /// [G3] Rundbogen: Füllkörper in Wandfarbe zwischen Rechteck-Loch und Bogen, Rahmen und Glas entlang + /// des Umrisses; alle Quader innerhalb des Öffnungs-Rechtecks. + #[test] + fn formoeffnung_fuellkoerper_rahmen_glas() { + let mut p = sample(); + let plain = emit_opening_meshes(&p, 2.0).len(); + for o in p.openings.iter_mut().flatten().filter(|o| o.id == "O1") { + o.shape = Some(OpeningShape::Rundbogen); + } + let meshes = emit_opening_meshes(&p, 2.0); + assert_ne!(meshes.len(), plain); + let w1 = p.walls.iter().find(|w| w.id == "W1").unwrap(); + let wall_rgb = resolve_wall_bands(&p, &wall_material_color_maps(&p), w1, false).0[0].color; + let fills: Vec<&RMesh> = meshes.iter().filter(|m| m.color == wall_rgb).collect(); + assert!(fills.len() >= 10, "Bogenzwickel als Streifen: {}", fills.len()); + let (zb, _) = p.wall_vertical_extent(w1); + // O1: x 3…4 an der Wand y = 0, Brüstung 0,9, Höhe 1,2: Füllung nur über dem Kämpfer (0,7). + for m in &fills { + for c in m.positions.chunks_exact(3) { + assert!(c[0] > 3.0 - 1e-9 && c[0] < 4.0 + 1e-9 && c[2] >= zb + 0.9 + 0.7 - 1e-9 && c[2] <= zb + 2.1 + 1e-9, "{c:?}"); + } + } + assert!(meshes.iter().any(|m| m.color == PART_RGB[0]) && meshes.iter().any(|m| m.color == PART_RGB[1])); + } + + /// [100] Dachfenster: jede Dachschicht bleibt ein geschlossener Körper mit Loch; Fensterteile kommen dazu. + #[test] + fn dachfenster_schneidet_alle_schichten() { + let mut p = sample(); + let before = emit_roofs(&p, None).unwrap(); + p.openings.as_mut().unwrap().push(Opening { + id: "DF".into(), + kind: ElementKind::Window, + width: 0.78, + height: 1.18, + host_roof_id: Some("RF1".into()), + host_point: Some(Vec2 { x: 2.5, y: 1.0 }), + ..Default::default() + }); + let after = emit_roofs(&p, None).unwrap(); + assert_eq!(before.len(), after.len()); + for m in &after { + assert!(crate::wall_mesh_cut::is_watertight(&m.positions, &m.indices, 1e-6), "Schicht dicht"); + } + let vol = |ms: &[RMesh]| ms.iter().map(|m| crate::export_flat::mesh_volume(&m.positions, &m.indices)).sum::(); + let removed = vol(&before) - vol(&after); + let t: f64 = p.roof_layers(&p.roofs.as_ref().unwrap()[0]).iter().map(|l| l.thickness).sum(); + assert!((removed - 0.78 * 1.18 * t).abs() < 1e-6, "Loch = Fläche × Dicke: {removed}"); + let parts = emit_opening_meshes(&p, 2.0).len() - emit_opening_meshes(&sample(), 2.0).len(); + assert!(parts >= 9, "Rahmen, Glas, Eindeckrahmen: {parts}"); + let layers = emit_roof_cut_layers(&p).unwrap().len(); + assert!(layers > emit_roof_cut_layers(&sample()).unwrap().len()); + } + + /// [100] Deckenöffnung: Aussparung im Slab. + #[test] + fn deckenoeffnung_im_slab() { + let mut p = sample(); + let n0: usize = emit_slabs(&p).iter().map(|s| s.outline.len()).sum(); + p.openings.as_mut().unwrap().push(Opening { id: "DO".into(), kind: ElementKind::Window, width: 1.0, height: 1.0, host_ceiling_id: Some("C1".into()), host_point: Some(Vec2 { x: 2.0, y: 2.0 }), ..Default::default() }); + let n1: usize = emit_slabs(&p).iter().map(|s| s.outline.len()).sum(); + assert!(n1 > n0, "Loch-Ring eingebunden"); + } + #[test] fn beispielprojekt_hat_decken_und_gueltige_farben() { let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap(); diff --git a/src-tauri/core/src/opening_shape.rs b/src-tauri/core/src/opening_shape.rs new file mode 100644 index 00000000..3cf000c3 --- /dev/null +++ b/src-tauri/core/src/opening_shape.rs @@ -0,0 +1,628 @@ +//! Öffnungs-Formen ([G3]) und Öffnungen in Dach/Decke ([100]). +//! +//! **Formen:** Rundbogen, Segmentbogen, Spitzbogen, Rund (Ellipse), Schräg, Giebel als konvexer Umriss +//! in der Öffnungsebene (u = 0 … Breite entlang der Wand, v = 0 … Höhe ab Brüstung, Gegenuhrzeigersinn). +//! Die Wand behält ihr Rechteck-Loch (render3d, Wandbänder, Exporte bleiben unverändert); was zwischen +//! Rechteck und Umriss stehen bleibt, kommt als **Füllkörper** dazu — senkrechte Streifen zwischen den +//! Umriss-Ecken, je ein konvexes Viereck, also gewöhnliche 8-Ecken-Quader wie die Fenster-Einbauteile. +//! Dieselbe Zerlegung liefert Rahmen (Ring Umriss → eingerückter Umriss) und Glas. +//! +//! **Wirte Dach/Decke:** [`host_frame`] legt ein Rechteck `width × height` in die Dachfläche bzw. auf die +//! Deckenoberkante (Mittelpunkt `hostPoint`), Breite längs der Traufe, Höhe das Gefälle hinauf. Die +//! Öffnung schneidet alle Schichten senkrecht zur Fläche (Normale `n`). + +use crate::model::*; + +pub type P = [f64; 2]; +pub type V3 = [f64; 3]; + +const MIN: f64 = 1e-6; +/// Bogen-Feinheit: höchstens 7,5° je Sehne. +const ARC_STEP: f64 = std::f64::consts::PI / 24.0; + +/// Hat die Öffnung eine Form ausser dem Rechteck? +pub fn is_shaped(o: &Opening) -> bool { + matches!(o.shape, Some(s) if s != OpeningShape::Rechteck && s != OpeningShape::Unknown) +} + +/// Gerader (flacher) Boden: Fensterbank/Schwelle möglich (alle Formen ausser Rund). +pub fn has_flat_bottom(o: &Opening) -> bool { + o.shape != Some(OpeningShape::Rund) +} + +fn arc(out: &mut Vec

, c: P, r: f64, a0: f64, a1: f64) { + let n = (((a1 - a0).abs() / ARC_STEP).ceil() as usize).clamp(2, 96); + for k in 0..=n { + let a = a0 + (a1 - a0) * k as f64 / n as f64; + out.push([c[0] + r * a.cos(), c[1] + r * a.sin()]); + } +} + +fn dedup(mut pts: Vec

) -> Vec

{ + pts.dedup_by(|b, a| (a[0] - b[0]).abs() < MIN && (a[1] - b[1]).abs() < MIN); + while pts.len() > 1 { + let (f, l) = (pts[0], pts[pts.len() - 1]); + if (f[0] - l[0]).abs() < MIN && (f[1] - l[1]).abs() < MIN { + pts.pop(); + } else { + break; + } + } + pts +} + +/// Umriss der Form in `w × h` (konvex, Gegenuhrzeigersinn); `None` für Rechteck oder Unsinn. +pub fn outline(shape: OpeningShape, rise: Option, w: f64, h: f64) -> Option> { + if !(w > MIN && h > MIN && w.is_finite() && h.is_finite()) { + return None; + } + let rise = rise.filter(|r| r.is_finite()); + let mut pts: Vec

= Vec::new(); + match shape { + OpeningShape::Rundbogen | OpeningShape::Segmentbogen => { + let r = if shape == OpeningShape::Rundbogen { w / 2.0 } else { rise.unwrap_or(w / 6.0) }; + let r = r.clamp(MIN * 10.0, (w / 2.0).min(h)); + let big = (w * w / 4.0 + r * r) / (2.0 * r); + let c = [w / 2.0, h - big]; + let a0 = (big - r).atan2(w / 2.0); + pts.push([0.0, 0.0]); + pts.push([w, 0.0]); + arc(&mut pts, c, big, a0, std::f64::consts::PI - a0); + } + OpeningShape::Spitzbogen => { + let r = rise.unwrap_or(w * 3f64.sqrt() / 2.0).clamp(w / 2.0, h.max(w / 2.0)).min(h); + if r < w / 2.0 - MIN { + // Zu niedrig für einen Spitzbogen: Rundbogen. + return outline(OpeningShape::Rundbogen, None, w, h); + } + let s = h - r; + let c = (w * w / 4.0 + r * r) / w; + pts.push([0.0, 0.0]); + pts.push([w, 0.0]); + // Rechter Bogen um (w − c, s) von (w, s) zum Scheitel, linker um (c, s) vom Scheitel nach (0, s). + let apex_r = r.atan2(w / 2.0 - (w - c)); + arc(&mut pts, [w - c, s], c, 0.0, apex_r); + let apex_l = r.atan2(w / 2.0 - c); + arc(&mut pts, [c, s], c, apex_l, std::f64::consts::PI); + } + OpeningShape::Rund => { + let n = 48; + for k in 0..n { + let a = -std::f64::consts::FRAC_PI_2 + 2.0 * std::f64::consts::PI * k as f64 / n as f64; + pts.push([w / 2.0 + w / 2.0 * a.cos(), h / 2.0 + h / 2.0 * a.sin()]); + } + } + OpeningShape::Schraeg => { + let d = rise.unwrap_or(w / 2.0).clamp(-h, h); + pts = vec![[0.0, 0.0], [w, 0.0], [w, h - (-d).max(0.0)], [0.0, h - d.max(0.0)]]; + } + OpeningShape::Giebel => { + let r = rise.unwrap_or(w / 2.0).clamp(0.0, h); + pts = vec![[0.0, 0.0], [w, 0.0], [w, h - r], [w / 2.0, h], [0.0, h - r]]; + } + _ => return None, + } + let pts = dedup(pts); + (pts.len() >= 3).then_some(pts) +} + +/// Umriss einer Öffnung (Form aus dem Modell), sonst `None`. +pub fn opening_outline(o: &Opening, w: f64, h: f64) -> Option> { + if !is_shaped(o) { + return None; + } + outline(o.shape.unwrap_or_default(), o.shape_rise, w, h) +} + +/// Senkrechte Ausdehnung `[v_lo, v_hi]` eines konvexen Umrisses bei `u`; ausserhalb ⇒ `None`. +pub fn v_range(poly: &[P], u: f64) -> Option<(f64, f64)> { + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + for i in 0..poly.len() { + let (a, b) = (poly[i], poly[(i + 1) % poly.len()]); + let (u0, u1) = (a[0].min(b[0]), a[0].max(b[0])); + if u < u0 - MIN || u > u1 + MIN { + continue; + } + if (b[0] - a[0]).abs() < MIN { + lo = lo.min(a[1].min(b[1])); + hi = hi.max(a[1].max(b[1])); + } else { + let t = ((u - a[0]) / (b[0] - a[0])).clamp(0.0, 1.0); + let v = a[1] + (b[1] - a[1]) * t; + lo = lo.min(v); + hi = hi.max(v); + } + } + (lo <= hi).then_some((lo, hi)) +} + +fn breakpoints(poly: &[P], extra: &[f64]) -> Vec { + let mut us: Vec = poly.iter().map(|q| q[0]).chain(extra.iter().copied()).collect(); + us.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + us.dedup_by(|b, a| (*a - *b).abs() < MIN); + us +} + +/// Füllstreifen zwischen Rechteck `w × h` und Umriss: konvexe Vierecke (Gegenuhrzeigersinn). +pub fn fill_quads(poly: &[P], w: f64, h: f64) -> Vec<[P; 4]> { + let mut out = Vec::new(); + let us = breakpoints(poly, &[0.0, w]); + for k in 0..us.len().saturating_sub(1) { + let (ua, ub) = (us[k], us[k + 1]); + if ub - ua < MIN { + continue; + } + let ra = v_range(poly, ua).unwrap_or((h, h)); + let rb = v_range(poly, ub).unwrap_or((h, h)); + if h - ra.1 > MIN || h - rb.1 > MIN { + out.push([[ua, ra.1], [ub, rb.1], [ub, h], [ua, h]]); + } + if ra.0 > MIN || rb.0 > MIN { + out.push([[ua, 0.0], [ub, 0.0], [ub, rb.0], [ua, ra.0]]); + } + } + out +} + +/// Konvexes Polygon in senkrechte Streifen zerlegt (Glas). +pub fn strip_quads(poly: &[P]) -> Vec<[P; 4]> { + let mut out = Vec::new(); + let us = breakpoints(poly, &[]); + for k in 0..us.len().saturating_sub(1) { + let (ua, ub) = (us[k], us[k + 1]); + if ub - ua < MIN { + continue; + } + let (Some(ra), Some(rb)) = (v_range(poly, ua), v_range(poly, ub)) else { continue }; + out.push([[ua, ra.0], [ub, rb.0], [ub, rb.1], [ua, ra.1]]); + } + out +} + +/// Konvexes Polygon (Gegenuhrzeigersinn) um `d` nach innen versetzt (Gehrung je Ecke). +pub fn inset(poly: &[P], d: f64) -> Vec

{ + let n = poly.len(); + let line = |i: usize| -> (P, P) { + let (a, b) = (poly[i], poly[(i + 1) % n]); + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + let l = (dx * dx + dy * dy).sqrt().max(1e-12); + let nl = [-dy / l, dx / l]; + ([a[0] + nl[0] * d, a[1] + nl[1] * d], [dx / l, dy / l]) + }; + (0..n) + .map(|i| { + let (p0, d0) = line((i + n - 1) % n); + let (p1, d1) = line(i); + let den = d0[0] * d1[1] - d0[1] * d1[0]; + if den.abs() < 1e-9 { + return p1; + } + let t = ((p1[0] - p0[0]) * d1[1] - (p1[1] - p0[1]) * d1[0]) / den; + [p0[0] + d0[0] * t, p0[1] + d0[1] * t] + }) + .collect() +} + +/// Rahmen-Ring: je Umriss-Kante ein Viereck zwischen Aussen- und Innenumriss. +pub fn ring_quads(outer: &[P], inner: &[P]) -> Vec<[P; 4]> { + let n = outer.len().min(inner.len()); + (0..n).map(|i| [outer[i], outer[(i + 1) % n], inner[(i + 1) % n], inner[i]]).collect() +} + +/// Quader-Ecken (Bit 0 = u, Bit 1 = v, Bit 2 = n wie `OPENING_BOX_TRIS`) eines Vierecks `q` +/// (Gegenuhrzeigersinn) zwischen `n0` und `n1`; `map(u, v, n)` → Modellpunkt (x, y, z). +pub fn quad_box(q: &[P; 4], n0: f64, n1: f64, map: &impl Fn(f64, f64, f64) -> V3) -> [f64; 24] { + let order = [q[0], q[1], q[3], q[2]]; + let mut out = [0.0; 24]; + for i in 0..8 { + let [u, v] = order[i & 3]; + let p = map(u, v, if i & 4 != 0 { n1 } else { n0 }); + out[i * 3..i * 3 + 3].copy_from_slice(&p); + } + out +} + +// ── Wirte Dach und Decke ([100]) ───────────────────────────────────────────── + +/// Öffnungs-System in einer Dach- oder Deckenfläche: Mittelpunkt `c` auf der Oberfläche, `ew` Breite +/// (waagrecht), `eh` Höhe (das Gefälle hinauf), `n` Flächennormale nach oben; `thickness` = alle Schichten. +#[derive(Clone, Debug, PartialEq)] +pub struct HostFrame { + pub c: V3, + pub ew: V3, + pub eh: V3, + pub n: V3, + pub thickness: f64, + /// Dachfläche (Index in `roof_geometry().planes`), bei Decken `None`. + pub plane: Option, + /// Index des Wirts in `Project::roofs` bzw. `Project::ceilings`. + pub host: usize, +} + +impl HostFrame { + /// Punkt in Breite `u`, Höhe `v` (ab Mitte) und `d` unter der Oberfläche. + pub fn at(&self, u: f64, v: f64, d: f64) -> V3 { + let mut p = self.c; + for k in 0..3 { + p[k] += self.ew[k] * u + self.eh[k] * v - self.n[k] * d; + } + p + } +} + +pub fn cross(a: V3, b: V3) -> V3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +pub fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn normalize(a: V3) -> Option { + let l = dot(a, a).sqrt(); + (l > 1e-12 && l.is_finite()).then(|| [a[0] / l, a[1] / l, a[2] / l]) +} + +fn point_in_xy(x: f64, y: f64, poly: &[V3]) -> bool { + let mut inside = false; + let n = poly.len(); + let mut j = n.wrapping_sub(1); + for i in 0..n { + let (a, b) = (poly[i], poly[j]); + if (a[1] > y) != (b[1] > y) && x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0] { + inside = !inside; + } + j = i; + } + inside +} + +fn axes(n: V3, angle_deg: f64) -> (V3, V3) { + let ew = normalize([-n[1], n[0], 0.0]).unwrap_or_else(|| { + let a = angle_deg.to_radians(); + [a.cos(), a.sin(), 0.0] + }); + (ew, cross(n, ew)) +} + +/// Ist die Öffnung in einem Dach oder einer Decke gehostet? +pub fn is_surface_hosted(o: &Opening) -> bool { + o.host_roof_id.as_deref().is_some_and(|s| !s.is_empty()) || o.host_ceiling_id.as_deref().is_some_and(|s| !s.is_empty()) +} + +/// Öffnungs-System eines Dach-/Deckenwirts; `None` ohne Wirt, Lage ausserhalb oder Unsinn. +pub fn host_frame(p: &Project, o: &Opening) -> Option { + let hp = o.host_point?; + if !(hp.x.is_finite() && hp.y.is_finite() && o.width > MIN && o.height > MIN) { + return None; + } + let angle = o.host_angle.filter(|a| a.is_finite()).unwrap_or(0.0); + if let Some(id) = o.host_roof_id.as_deref().filter(|s| !s.is_empty()) { + let (host, roof) = p.roofs.as_deref()?.iter().enumerate().find(|(_, r)| r.id == id)?; + let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)); + let (plane, pts) = g.planes.iter().enumerate().find(|(_, pl)| pl.len() >= 3 && point_in_xy(hp.x, hp.y, pl))?; + let n = crate::model3d::plane_normal_up(pts); + if n[2] < 1e-3 { + return None; + } + let z = pts[0][2] - (n[0] * (hp.x - pts[0][0]) + n[1] * (hp.y - pts[0][1])) / n[2]; + let thickness = p.roof_layers(roof).iter().fold(0.0, |s, l| s + l.thickness.max(0.0)); + let (ew, eh) = axes(n, angle); + return Some(HostFrame { c: [hp.x, hp.y, z], ew, eh, n, thickness, plane: Some(plane), host }); + } + let id = o.host_ceiling_id.as_deref().filter(|s| !s.is_empty())?; + let (host, c) = p.ceilings.as_deref()?.iter().enumerate().find(|(_, c)| c.id == id)?; + let (zb, zt) = p.ceiling_vertical_extent(c); + let n = [0.0, 0.0, 1.0]; + let (ew, eh) = axes(n, angle); + Some(HostFrame { c: [hp.x, hp.y, zt], ew, eh, n, thickness: (zt - zb).max(0.0), plane: None, host }) +} + +/// Rechteck der Öffnung im Grundriss (Oberfläche, Gegenuhrzeigersinn). +pub fn host_rect_plan(f: &HostFrame, w: f64, h: f64) -> [V3; 4] { + [f.at(-w / 2.0, -h / 2.0, 0.0), f.at(w / 2.0, -h / 2.0, 0.0), f.at(w / 2.0, h / 2.0, 0.0), f.at(-w / 2.0, h / 2.0, 0.0)] +} + +/// Aussparungen einer Decke: gezeichnete (`openings`) und die der gehosteten Öffnungen. +pub fn ceiling_hole_rings(p: &Project, c: &Ceiling) -> Vec> { + let mut out: Vec> = c.openings.clone().unwrap_or_default(); + for o in p.openings.as_deref().unwrap_or(&[]) { + if o.host_ceiling_id.as_deref() != Some(c.id.as_str()) { + continue; + } + if let Some(f) = host_frame(p, o) { + out.push(host_rect_plan(&f, o.width, o.height).iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect()); + } + } + out +} + +/// Dachfenster eines Dachs (Index in `Project::roofs`) mit ihrem System. +pub fn roof_openings(p: &Project, roof_index: usize) -> Vec<(&Opening, HostFrame)> { + let Some(roof) = p.roofs.as_deref().and_then(|r| r.get(roof_index)) else { return Vec::new() }; + p.openings + .as_deref() + .unwrap_or(&[]) + .iter() + .filter(|o| o.host_roof_id.as_deref() == Some(roof.id.as_str())) + .filter_map(|o| host_frame(p, o).map(|f| (o, f))) + .collect() +} + +/// Rahmenbreite eines Dach-/Deckenfensters (Fenstertyp, sonst 7 cm). +pub fn surface_frame_width(p: &Project, o: &Opening) -> f64 { + p.window_type(o).and_then(|t| t.frame_width).filter(|v| *v > 0.0).unwrap_or(0.07).min(o.width.min(o.height) / 3.0) +} + +/// Einbauteile eines Dach-/Deckenfensters als Quader `(Bauteil, Ecken)`: Rahmen (Ring in der lichten +/// Öffnung, 6 cm über die Oberfläche hinaus, Tiefe = Rahmentiefe des Typs, sonst 16 cm), Glas oben im +/// Rahmen, Eindeckrahmen (vereinfacht: flacher Ring 6 cm breit, 3 cm hoch rund um die Öffnung). +/// Bauteil-Codes wie `openings3d::Part` (0 Glas, 1 Rahmen, 2 Sonnenschutz/Blech). +pub fn surface_window_boxes(p: &Project, o: &Opening, f: &HostFrame) -> Vec<(u8, [f64; 24])> { + let (w, h) = (o.width, o.height); + let fw = surface_frame_width(p, o); + let depth = p.window_type(o).and_then(|t| t.frame_depth).filter(|v| *v > 0.0).unwrap_or(0.16).min(f.thickness.max(0.05) + 0.06); + let map = |u: f64, v: f64, n: f64| f.at(u - w / 2.0, v - h / 2.0, -n); + let outer = vec![[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]]; + let inner = inset(&outer, fw); + let mut out = Vec::new(); + let top = 0.06; + for q in ring_quads(&outer, &inner) { + out.push((1, quad_box(&q, top - depth, top, &map))); + } + if o.kind == ElementKind::Window { + for q in strip_quads(&inner) { + out.push((0, quad_box(&q, top - 0.03, top - 0.01, &map))); + } + } + if o.host_roof_id.is_some() { + let flash = [[-0.06, -0.06], [w + 0.06, -0.06], [w + 0.06, h + 0.06], [-0.06, h + 0.06]]; + for q in ring_quads(&flash, &outer) { + out.push((2, quad_box(&q, 0.0, 0.03, &map))); + } + } + out +} + +// ── Schnitt (senkrechte Ebene) ────────────────────────────────────────────── + +/// Kanten eines 8-Ecken-Quaders (Ecken unterscheiden sich in genau einem Bit). +const BOX_EDGES: [(usize, usize); 12] = [(0, 1), (2, 3), (4, 5), (6, 7), (0, 2), (1, 3), (4, 6), (5, 7), (0, 4), (1, 5), (2, 6), (3, 7)]; + +/// Schnitt eines konvexen 8-Ecken-Quaders (`quad_box`-Ecken) mit der senkrechten Schnittebene durch `base` +/// in Richtung `u` (Grundriss): konvexes Polygon in Schnitt-Koordinaten (t entlang `u`, z), Gegenuhrzeigersinn. +pub fn box_section(corners: &[f64; 24], base: (f64, f64), u: (f64, f64)) -> Option> { + let c = |i: usize| [corners[i * 3], corners[i * 3 + 1], corners[i * 3 + 2]]; + let side = |q: V3| (q[0] - base.0) * -u.1 + (q[1] - base.1) * u.0; + let mut pts: Vec

= Vec::new(); + for (a, b) in BOX_EDGES { + let (pa, pb) = (c(a), c(b)); + let (sa, sb) = (side(pa), side(pb)); + if (sa > 0.0) == (sb > 0.0) || (sa - sb).abs() < 1e-15 { + continue; + } + let t = sa / (sa - sb); + let q = [pa[0] + (pb[0] - pa[0]) * t, pa[1] + (pb[1] - pa[1]) * t, pa[2] + (pb[2] - pa[2]) * t]; + pts.push([(q[0] - base.0) * u.0 + (q[1] - base.1) * u.1, q[2]]); + } + if pts.len() < 3 { + return None; + } + let cx = pts.iter().map(|q| q[0]).sum::() / pts.len() as f64; + let cy = pts.iter().map(|q| q[1]).sum::() / pts.len() as f64; + pts.sort_by(|a, b| (a[1] - cy).atan2(a[0] - cx).partial_cmp(&(b[1] - cy).atan2(b[0] - cx)).unwrap_or(std::cmp::Ordering::Equal)); + let pts = dedup(pts); + (pts.len() >= 3 && polygon_area(&pts) > 1e-10).then_some(pts) +} + +fn polygon_area(p: &[P]) -> f64 { + (0..p.len()).map(|i| p[i][0] * p[(i + 1) % p.len()][1] - p[(i + 1) % p.len()][0] * p[i][1]).sum::() / 2.0 +} + +fn clip_half(pts: &[P], a: P, b: P, keep_left: bool) -> Vec

{ + let side = |p: P| { + let c = (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]); + if keep_left { c } else { -c } + }; + let mut out = Vec::new(); + for i in 0..pts.len() { + let (p, q) = (pts[i], pts[(i + 1) % pts.len()]); + let (sp, sq) = (side(p), side(q)); + if sp >= 0.0 { + out.push(p); + } + if (sp >= 0.0) != (sq >= 0.0) { + let t = sp / (sp - sq); + out.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]); + } + } + out +} + +/// Konvexes Polygon minus konvexes Loch: konvexe Reststücke (leer, wenn ganz im Loch). +pub fn subtract_convex(poly: &[P], hole: &[P]) -> Vec> { + let mut h = hole.to_vec(); + if polygon_area(&h) < 0.0 { + h.reverse(); + } + let mut out = Vec::new(); + let mut rest = poly.to_vec(); + for k in 0..h.len() { + let (a, b) = (h[k], h[(k + 1) % h.len()]); + let outside = clip_half(&rest, a, b, false); + if outside.len() >= 3 && polygon_area(&outside).abs() > 1e-10 { + out.push(outside); + } + rest = clip_half(&rest, a, b, true); + if rest.len() < 3 { + return if out.is_empty() { vec![poly.to_vec()] } else { out }; + } + } + out +} + +/// Lochkörper eines Dach-/Deckenfensters (durch alle Schichten, 0,5 m Zugabe beidseits). +pub fn surface_hole_box(o: &Opening, f: &HostFrame) -> [f64; 24] { + let (w, h) = (o.width, o.height); + quad_box(&[[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]], -0.5, f.thickness + 0.5, &|u, v, n| f.at(u - w / 2.0, v - h / 2.0, n)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn area(p: &[P]) -> f64 { + (0..p.len()).map(|i| p[i][0] * p[(i + 1) % p.len()][1] - p[(i + 1) % p.len()][0] * p[i][1]).sum::() / 2.0 + } + + fn quads_area(q: &[[P; 4]]) -> f64 { + q.iter().map(|q| area(q)).sum() + } + + #[test] + fn schnitt_durch_quader_und_loch() { + let q = [[0.0, 0.0], [2.0, 0.0], [2.0, 1.0], [0.0, 1.0]]; + let b = quad_box(&q, 0.0, 3.0, &|u, v, n| [u, n, v]); + // Ebene x = 1 (Blick entlang −x, u = +y): Rechteck n 0..3 × v 0..1. + let sec = box_section(&b, (1.0, -5.0), (0.0, 1.0)).unwrap(); + assert!((polygon_area(&sec) - 3.0).abs() < 1e-12, "{sec:?}"); + assert!(box_section(&b, (5.0, 0.0), (0.0, 1.0)).is_none()); + let band = vec![[0.0, 0.0], [10.0, 0.0], [10.0, 1.0], [0.0, 1.0]]; + let pieces = subtract_convex(&band, &[[4.0, -1.0], [6.0, -1.0], [6.0, 2.0], [4.0, 2.0]]); + assert_eq!(pieces.len(), 2); + assert!((pieces.iter().map(|p| polygon_area(p)).sum::() - 8.0).abs() < 1e-12); + assert_eq!(subtract_convex(&band, &[[20.0, 0.0], [21.0, 0.0], [21.0, 1.0]]).len(), 1); + } + + #[test] + fn rechteck_hat_keinen_umriss() { + assert!(outline(OpeningShape::Rechteck, None, 1.0, 2.0).is_none()); + assert!(outline(OpeningShape::Rundbogen, None, f64::NAN, 2.0).is_none()); + assert!(outline(OpeningShape::Rundbogen, None, 0.0, 2.0).is_none()); + } + + #[test] + fn rundbogen_halbkreis_oben() { + let p = outline(OpeningShape::Rundbogen, None, 1.0, 2.0).unwrap(); + assert!(area(&p) > 0.0, "Gegenuhrzeigersinn"); + // Fläche: Rechteck 1 × 1.5 + Halbkreis r = 0.5. + let want = 1.5 + std::f64::consts::PI * 0.25 / 2.0; + assert!((area(&p) - want).abs() < 5e-3, "{} vs {want}", area(&p)); + assert_eq!(v_range(&p, 0.5).map(|r| (r.1 * 1e6).round() / 1e6), Some(2.0)); + let (lo, hi) = v_range(&p, 0.0).unwrap(); + assert!(lo.abs() < 1e-9 && (hi - 1.5).abs() < 1e-9); + // Füllung + Umriss = Rechteck. + assert!((quads_area(&fill_quads(&p, 1.0, 2.0)) + area(&p) - 2.0).abs() < 1e-9); + } + + #[test] + fn segment_und_spitzbogen() { + let s = outline(OpeningShape::Segmentbogen, Some(0.2), 1.2, 1.5).unwrap(); + assert!((v_range(&s, 0.6).unwrap().1 - 1.5).abs() < 1e-3); + assert!((v_range(&s, 0.0).unwrap().1 - 1.3).abs() < 1e-9); + let g = outline(OpeningShape::Spitzbogen, None, 1.0, 2.0).unwrap(); + assert!((v_range(&g, 0.5).unwrap().1 - 2.0).abs() < 1e-6, "Scheitel oben"); + let spring = 2.0 - 3f64.sqrt() / 2.0; + assert!((v_range(&g, 0.0).unwrap().1 - spring).abs() < 1e-9); + assert!((quads_area(&fill_quads(&g, 1.0, 2.0)) + area(&g) - 2.0).abs() < 1e-9); + // Spitzbogen niedriger als halbe Breite: Rundbogen. + assert!(outline(OpeningShape::Spitzbogen, Some(0.1), 1.0, 0.3).is_some()); + } + + #[test] + fn rund_schraeg_giebel() { + let r = outline(OpeningShape::Rund, None, 0.8, 0.8).unwrap(); + assert!((area(&r) - std::f64::consts::PI * 0.16).abs() < 0.01); + assert!((quads_area(&fill_quads(&r, 0.8, 0.8)) + area(&r) - 0.64).abs() < 1e-9); + let s = outline(OpeningShape::Schraeg, Some(0.4), 1.0, 2.0).unwrap(); + assert_eq!(v_range(&s, 0.0).unwrap().1, 1.6); + assert_eq!(v_range(&s, 1.0).unwrap().1, 2.0); + let s = outline(OpeningShape::Schraeg, Some(-0.4), 1.0, 2.0).unwrap(); + assert_eq!(v_range(&s, 1.0).unwrap().1, 1.6); + let g = outline(OpeningShape::Giebel, Some(0.5), 1.0, 2.0).unwrap(); + assert_eq!(v_range(&g, 0.5).unwrap().1, 2.0); + assert!((quads_area(&fill_quads(&g, 1.0, 2.0)) - 0.25).abs() < 1e-9); + } + + #[test] + fn inset_und_ring() { + let sq = vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]; + let i = inset(&sq, 0.1); + assert!((area(&i) - 0.64).abs() < 1e-12); + assert!((quads_area(&ring_quads(&sq, &i)) - 0.36).abs() < 1e-12); + assert!((quads_area(&strip_quads(&i)) - 0.64).abs() < 1e-12); + let r = outline(OpeningShape::Rundbogen, None, 1.0, 2.0).unwrap(); + let ri = inset(&r, 0.06); + assert!(v_range(&ri, 0.5).unwrap().1 < 1.95 && v_range(&ri, 0.5).unwrap().1 > 1.93); + } + + #[test] + fn quader_ecken_wie_achsquader() { + let q = [[0.0, 0.0], [1.0, 0.0], [1.0, 2.0], [0.0, 2.0]]; + let b = quad_box(&q, -0.1, 0.1, &|u, v, n| [u, n, v]); + // Ecke 3 = (u1, v1, n0), Ecke 4 = (u0, v0, n1). + assert_eq!(&b[9..12], &[1.0, -0.1, 2.0]); + assert_eq!(&b[12..15], &[0.0, 0.1, 0.0]); + } + + fn roof_project() -> Project { + let mut p = Project::default(); + let rect = serde_json::json!([{"x":0,"y":0},{"x":10,"y":0},{"x":10,"y":8},{"x":0,"y":8}]); + p.roofs = Some(vec![serde_json::from_value(serde_json::json!({"id": "R", "type": "roof", "floorId": "F", "categoryCode": "35", + "outline": rect, "shape": "sattel", "pitchDeg": 45, "overhang": 0, "ridgeAxis": "x", "baseElevation": 3, "thickness": 0.3})).unwrap()]); + p.ceilings = Some(vec![serde_json::from_value(serde_json::json!({"id": "C", "type": "ceiling", "floorId": "F", "categoryCode": "30", + "wallTypeId": "", "outline": rect, "thickness": 0.25})).unwrap()]); + p.openings = Some(vec![Opening { + id: "D".into(), + kind: ElementKind::Window, + width: 0.8, + height: 1.2, + host_roof_id: Some("R".into()), + host_point: Some(Vec2 { x: 5.0, y: 2.0 }), + ..Default::default() + }]); + p + } + + #[test] + fn dachfenster_liegt_in_der_dachflaeche() { + let p = roof_project(); + let o = &p.openings.as_ref().unwrap()[0]; + let f = host_frame(&p, o).expect("Dachfläche gefunden"); + // Südfläche (y < 4) bei 45°: Oberfläche bei y = 2 liegt 2 m über der Traufe (3 m) — plus Überhöhung + // durch die Dachdicke nicht, die Ebene ist die Oberkante. + assert!((f.n[2] - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9 && f.n[1] < 0.0, "{:?}", f.n); + assert!(f.ew[2].abs() < 1e-12 && f.eh[2] > 0.0 && f.eh[1] > 0.0, "Höhe das Gefälle hinauf"); + assert!((f.thickness - 0.3).abs() < 1e-9); + let corners = host_rect_plan(&f, 0.8, 1.2); + let dz = corners[3][2] - corners[0][2]; + assert!((dz - 1.2 * std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9); + assert_eq!(roof_openings(&p, 0).len(), 1); + assert!(!surface_window_boxes(&p, o, &f).is_empty()); + // Ausserhalb jeder Dachfläche: kein System. + let mut far = o.clone(); + far.host_point = Some(Vec2 { x: 50.0, y: 2.0 }); + assert!(host_frame(&p, &far).is_none()); + } + + #[test] + fn deckenoeffnung_wird_aussparung() { + let mut p = roof_project(); + let c = p.ceilings.as_ref().unwrap()[0].clone(); + assert!(ceiling_hole_rings(&p, &c).is_empty()); + p.openings = Some(vec![Opening { + id: "O".into(), + kind: ElementKind::Window, + width: 1.0, + height: 2.0, + host_ceiling_id: Some("C".into()), + host_point: Some(Vec2 { x: 3.0, y: 3.0 }), + host_angle: Some(90.0), + ..Default::default() + }]); + let rings = ceiling_hole_rings(&p, &c); + assert_eq!(rings.len(), 1); + let xs: Vec = rings[0].iter().map(|v| (v.x * 1e9).round() / 1e9).collect(); + assert_eq!(xs.iter().cloned().fold(f64::INFINITY, f64::min), 2.0, "um 90° gedreht: Höhe entlang x"); + } +} diff --git a/src-tauri/core/src/openings3d.rs b/src-tauri/core/src/openings3d.rs index a40e3942..2059763c 100644 --- a/src-tauri/core/src/openings3d.rs +++ b/src-tauri/core/src/openings3d.rs @@ -17,15 +17,15 @@ use crate::joins::{js_hypot, js_round}; use crate::wall_bands::EPS; /// Halbe Dicke EINER Fensterscheibe (8 mm je Scheibe). -const GLASS_HALF_THICK: f64 = 0.004; +pub(crate) const GLASS_HALF_THICK: f64 = 0.004; /// Luftraum zwischen zwei Scheiben einer Mehrfachverglasung. const GLASS_PANE_GAP: f64 = 0.006; /// Halbe Breite der Symbol-Diagonalen (~5 mm Gesamtbreite). const SYMBOL_HALF_WIDTH: f64 = 0.0025; /// Türblatt-Dicke quer zur Wand. -const DOOR_LEAF_THICK: f64 = 0.04; +pub(crate) const DOOR_LEAF_THICK: f64 = 0.04; /// Default-Ansichtsbreite des Rahmenprofils, wenn der Typ keine nennt. -const DEFAULT_FRAME_WIDTH: f64 = 0.06; +pub(crate) const DEFAULT_FRAME_WIDTH: f64 = 0.06; /// Default-Rahmentiefe (deckt sich mit `geometry/opening.ts::DEFAULT_FRAME_DEPTH`, 2D = 3D). const DEFAULT_FRAME_DEPTH: f64 = 0.07; /// Stegbreite der Kassetten-Füllstäbe. @@ -423,14 +423,14 @@ struct FrameParams<'a> { } /// Rahmentiefe quer zur Wand: `frame_depth` (> EPS) oder Default, auf die Wanddicke geklemmt. -fn across_wall_depth(frame_depth: f64, wall_thickness: f64) -> f64 { +pub(crate) fn across_wall_depth(frame_depth: f64, wall_thickness: f64) -> f64 { let depth = if frame_depth > EPS { frame_depth } else { DEFAULT_FRAME_DEPTH }; jmin(depth, wall_thickness) } /// Quer-Versatz `[n_min, n_max]` des Rahmenkörpers: Vorderkante bündig mit der gewählten /// Wandfläche (minus Schichteinzug), `depth` zur Wandmitte hin, auf die halbe Dicke geklemmt. -fn frame_normal_range(half: f64, depth: f64, inset: f64, inner: bool, mid: bool) -> (f64, f64) { +pub(crate) fn frame_normal_range(half: f64, depth: f64, inset: f64, inner: bool, mid: bool) -> (f64, f64) { let sign = if inner { -1.0 } else { 1.0 }; let (front, back) = if mid { (depth / 2.0, -depth / 2.0) } else { (sign * (half - inset), sign * (half - inset) - sign * depth) }; let a = clamp_range(front, -half, half); diff --git a/src-tauri/core/src/plan/domains.rs b/src-tauri/core/src/plan/domains.rs index 737b6e58..729fc185 100644 --- a/src-tauri/core/src/plan/domains.rs +++ b/src-tauri/core/src/plan/domains.rs @@ -278,7 +278,7 @@ fn ceilings(c: &Ctx, out: &mut Vec, bounds: &mut Bounds) -> Result<() continue; } let pts: Vec<[f64; 2]> = ce.outline.iter().map(|v| [v.x, v.y]).collect(); - let holes: Vec> = ce.openings.as_deref().unwrap_or(&[]).iter().map(|h| h.iter().map(|v| [v.x, v.y]).collect()).collect(); + let holes: Vec> = crate::opening_shape::ceiling_hole_rings(p, ce).iter().map(|h| h.iter().map(|v| [v.x, v.y]).collect()).collect(); let merged = crate::polygon_holes::merge_holes(&pts, &holes, 1e-4); let layers = ceiling_layers(p, ce)?; let comp = match layers.first() { @@ -351,6 +351,35 @@ fn roofs(c: &Ctx, out: &mut Vec, bounds: &mut Bounds) { for l in &geo.breaks { out.push(line(pv(l[0]), pv(l[1]), "roof-break", ROOF_BREAK_MM, Some(Some(ROOF_BREAK_DASH.to_vec())), stroke, greyed)); } + roof_windows(c, out, roof); + } +} + +/// Dachfenster ([100]) im Grundriss des Dach-Geschosses: Rahmen-Umriss und Glas als Projektion der +/// Dachfläche, gestrichelt (über der Schnitthöhe); Pick über die Öffnungs-id. +fn roof_windows(c: &Ctx, out: &mut Vec, roof: &Roof) { + let p = c.p; + let Some(ri) = p.roofs.as_deref().and_then(|r| r.iter().position(|x| x.id == roof.id)) else { return }; + for (o, f) in crate::opening_shape::roof_openings(p, ri) { + if !c.shown(&o.category_code) { + continue; + } + let greyed = Some(c.greyed(&o.category_code)); + let category = c.cat(&o.category_code); + let stroke = o.color.as_deref().or(category.map(|k| k.color.as_str())).unwrap_or(POCHE_STROKE); + let fw = crate::opening_shape::surface_frame_width(p, o); + for (inset, cls, w) in [(0.0, "roof-window-frame", ROOF_EAVES_MM), (fw, "roof-window-glass", ROOF_BREAK_MM)] { + let (hw, hh) = (o.width / 2.0 - inset, o.height / 2.0 - inset); + let r = [f.at(-hw, -hh, 0.0), f.at(hw, -hh, 0.0), f.at(hw, hh, 0.0), f.at(-hw, hh, 0.0)]; + for k in 0..4 { + let (a, b) = (r[k], r[(k + 1) % 4]); + let mut l = line(Vec2 { x: a[0], y: a[1] }, Vec2 { x: b[0], y: b[1] }, cls, w, Some(Some(OVERHEAD_DASH.to_vec())), stroke, greyed); + if let Primitive::Line { opening_id, .. } = &mut l { + *opening_id = Some(o.id.clone()); + } + out.push(l); + } + } } } diff --git a/src-tauri/core/src/plan/elevation.rs b/src-tauri/core/src/plan/elevation.rs index b2565101..649c1ec0 100644 --- a/src-tauri/core/src/plan/elevation.rs +++ b/src-tauri/core/src/plan/elevation.rs @@ -221,6 +221,16 @@ struct ProjOpening { sill: Vec<[Pt; 4]>, symbol: Vec<(Pt, Pt)>, id: String, + /// Formöffnung ([G3]): Rahmen-Umriss und Glas entlang des Umrisses statt der Rechtecke. + shape: Option<(Vec, Vec, Vec>, String)>, +} + +/// Umriss einer Formöffnung in Anteilen (0…1) und das um die Rahmenbreite eingerückte Glas. +type ShapeNorm = (Vec<[f64; 2]>, Vec<[f64; 2]>, Vec<[[f64; 2]; 4]>, String); + +fn map_quad(q: &[Pt; 4], s: f64, t: f64) -> Pt { + let lerp = |a: Pt, b: Pt, k: f64| -> Pt { [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k] }; + lerp(lerp(q[0], q[1], s), lerp(q[3], q[2], s), t) } fn sash_kind(k: OpeningKind) -> f64 { @@ -237,6 +247,7 @@ fn sash_kind(k: OpeningKind) -> f64 { fn collect_openings(p: &Project, frame: &[f64; 9]) -> Vec { let mut b = vec![0.0]; let mut ids: Vec<&str> = Vec::new(); + let mut shapes: Vec> = Vec::new(); let by_wall = p.openings_by_wall(); for wall in &p.walls { let thickness = p.wall_type(wall).map_or(0.2, |t| t.layers.iter().fold(0.0, |s, l| s + l.thickness)); @@ -332,6 +343,13 @@ fn collect_openings(p: &Project, frame: &[f64; 9]) -> Vec { ]); } ids.push(&op.id); + shapes.push(crate::opening_shape::opening_outline(op, to - from, ot - ob).map(|poly| { + let (w, h) = (to - from, ot - ob); + let fw = if door { dt.and_then(|t| t.frame_width) } else { wt.and_then(|t| t.frame_width) }.unwrap_or(0.06).min(w.min(h) / 3.0); + let norm = |q: &[f64; 2]| [q[0] / w, q[1] / h]; + let fills = crate::opening_shape::fill_quads(&poly, w, h).iter().map(|q| q.map(|c| norm(&c))).collect(); + (poly.iter().map(norm).collect(), crate::opening_shape::inset(&poly, fw).iter().map(norm).collect(), fills, wall.id.clone()) + })); b[0] += 1.0; } } @@ -376,11 +394,57 @@ fn collect_openings(p: &Project, frame: &[f64; 9]) -> Vec { let sash_rects = quads(&mut i); let sill = quads(&mut i); let symbol = lines(&mut i); - out.push(ProjOpening { pts, depth, glass, door_leaf, divisions, sash_rects, sill, symbol, id: ids[k].to_string() }); + let m = |q: &[f64; 2]| map_quad(&pts, q[0], q[1]); + let shape = shapes[k].as_ref().map(|(o, g, fl, wid)| (o.iter().map(m).collect(), g.iter().map(m).collect(), fl.iter().map(|q| q.iter().map(m).collect()).collect(), wid.clone())); + if shape.is_some() { + // Formöffnung ([G3]): ohne Flügel-/Sprossenteilung, Türblatt und Symbole (Rechteck-Raster). + let round = p.openings.as_deref().unwrap_or(&[]).iter().any(|o| o.id == ids[k] && !crate::opening_shape::has_flat_bottom(o)); + out.push(ProjOpening { pts, depth, glass: Vec::new(), door_leaf: Vec::new(), divisions: Vec::new(), sash_rects: Vec::new(), sill: if round { Vec::new() } else { sill }, symbol: Vec::new(), id: ids[k].to_string(), shape }); + continue; + } + out.push(ProjOpening { pts, depth, glass, door_leaf, divisions, sash_rects, sill, symbol, id: ids[k].to_string(), shape }); } + surface_openings(p, frame, &mut out); out } +/// Dach-/Deckenfenster ([100]) in der Ansicht: Rahmen-Rechteck in der Dachfläche (6 cm über der +/// Eindeckung) und Glas, nur wenn die Fläche zum Betrachter zeigt. +fn surface_openings(p: &Project, frame: &[f64; 9], out: &mut Vec) { + let (fp, fnrm, fu) = ([frame[0], frame[1], frame[2]], [frame[3], frame[4], frame[5]], [frame[6], frame[7], frame[8]]); + let proj = |q: [f64; 3]| -> (Pt, f64) { + // Modell (x, y, z) → Ansichtswelt (x, Höhe, y). + let w = [q[0] - fp[0], q[2] - fp[1], q[1] - fp[2]]; + ([w[0] * fu[0] + w[1] * fu[1] + w[2] * fu[2], q[2]], w[0] * fnrm[0] + w[1] * fnrm[1] + w[2] * fnrm[2]) + }; + for o in p.openings.as_deref().unwrap_or(&[]) { + let Some(f) = crate::opening_shape::host_frame(p, o) else { continue }; + if f.plane.is_none() || fnrm[0] * f.n[0] + fnrm[1] * f.n[2] + fnrm[2] * f.n[1] >= -1e-4 { + continue; + } + let (w, h) = (o.width, o.height); + let fw = crate::opening_shape::surface_frame_width(p, o); + let quad = |inset: f64| -> ([Pt; 4], f64) { + let c = [f.at(-w / 2.0 + inset, -h / 2.0 + inset, -0.06), f.at(w / 2.0 - inset, -h / 2.0 + inset, -0.06), f.at(w / 2.0 - inset, h / 2.0 - inset, -0.06), f.at(-w / 2.0 + inset, h / 2.0 - inset, -0.06)]; + let pr = c.map(proj); + ([pr[0].0, pr[1].0, pr[2].0, pr[3].0], (pr[0].1 + pr[1].1 + pr[2].1 + pr[3].1) / 4.0) + }; + let (pts, own) = quad(0.0); + if own <= 1e-6 { + continue; + } + // Painter: knapp vor der eigenen Dachfläche (deren Tiefe = Mittel ihrer Ecken wie `project_face`). + let plane_depth = p.roofs.as_deref().and_then(|r| r.get(f.host)).and_then(|roof| { + let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)); + let pl = g.planes.get(f.plane?)?.clone(); + Some(pl.iter().map(|q| proj(*q).1).sum::() / pl.len() as f64) + }); + let depth = plane_depth.map_or(own, |d| d.min(own)); + let glass = if o.kind == ElementKind::Window { vec![quad(fw).0] } else { Vec::new() }; + out.push(ProjOpening { pts, depth, glass, door_leaf: Vec::new(), divisions: Vec::new(), sash_rects: Vec::new(), sill: Vec::new(), symbol: Vec::new(), id: o.id.clone(), shape: None }); + } +} + fn encode_shadow_faces(faces: &[&Face]) -> Vec { let mut b = vec![faces.len() as f64]; for f in faces { @@ -675,11 +739,24 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono: }; let d = op.depth - EPS * 100.0; let id = Some(op.id.as_str()); + // Formöffnung: das Rechteck-Loch der Wand ausserhalb des Umrisses in Wandfarbe schliessen. + if let Some((_, _, fills, wid)) = &op.shape { + let wall_fill = faces.iter().find(|f| f.role == Role::Wall && f.id == *wid).map_or("#ffffff".to_string(), |f| fill_for(f.fill)); + for q in fills { + let pts = to_vec(q); + items.push(Item { depth: d + EPS * 10.0, seq, rank: None, prim: polygon(pts, &wall_fill, "none", 0.0, no_hatch()) }); + seq += 1; + } + } let mut push = |prim: Primitive| { items.push(Item { depth: d, seq, rank: None, prim }); seq += 1; }; - push(poly_prim(to_vec(&op.pts), if mono { "#ffffff" } else { FRAME_FILL_COLOR }, EDGE_INK, FRAME_MM, id)); + let frame_pts = op.shape.as_ref().map_or(&op.pts[..], |(o, _, _, _)| &o[..]); + push(poly_prim(to_vec(frame_pts), if mono { "#ffffff" } else { FRAME_FILL_COLOR }, EDGE_INK, FRAME_MM, id)); + if let Some((_, g, _, _)) = &op.shape { + push(poly_prim(to_vec(g), if mono { GLASS_FILL_MONO } else { GLASS_FILL_COLOR }, EDGE_INK, EDGE_MM, id)); + } for r in &op.sill { push(poly_prim(to_vec(r), if mono { "#ffffff" } else { SILL_FILL_COLOR }, EDGE_INK, EDGE_MM, id)); } @@ -692,7 +769,7 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono: for r in &op.door_leaf { push(poly_prim(to_vec(r), if mono { "#ffffff" } else { DOOR_LEAF_FILL_COLOR }, EDGE_INK, EDGE_MM, id)); } - if shadows { + if shadows && op.shape.is_none() { let q = &op.pts; let lerp = |a: Pt, b: Pt, t: f64| -> Pt { [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t] }; let quad_at = |fa: f64, fz: f64| lerp(lerp(q[0], q[1], fa), lerp(q[3], q[2], fa), fz); @@ -782,4 +859,25 @@ mod tests { // Painter: die Bodenlinie zuletzt assert!(matches!(prims.last(), Some(Primitive::Line { cls, .. }) if cls == "elevation-ground")); } + + /// [G3] Formöffnung: Rahmen als Umriss (viele Ecken), Glas eingerückt; [100] Dachfenster auf der + /// Südfläche sichtbar. + #[test] + fn formoeffnung_und_dachfenster_in_der_ansicht() { + let mut p = sample(); + for o in p.openings.iter_mut().flatten().filter(|o| o.id == "O1") { + o.shape = Some(OpeningShape::Rund); + } + p.openings.as_mut().unwrap().push(Opening { id: "DF".into(), kind: ElementKind::Window, category_code: "21".into(), width: 0.78, height: 1.18, host_roof_id: Some("RF1".into()), host_point: Some(Vec2 { x: 2.5, y: 1.0 }), ..Default::default() }); + let l = p.drawing_levels.iter().find(|l| l.id == "ansicht-sued").unwrap(); + let level = LevelSpec::from_json(&serde_json::to_value(l).unwrap()); + let (prims, _) = elevation_primitives(&p, &level, false, false, &Visibility::default()).unwrap().unwrap(); + let polys = |id: &str| -> Vec { prims.iter().filter_map(|pr| if let Primitive::Polygon { pts, opening_id: Some(o), .. } = pr { (o == id).then_some(pts.len()) } else { None }).collect() }; + let o1 = polys("O1"); + assert!(o1.len() == 2 && o1.iter().all(|n| *n >= 40), "Rahmen + Glas als Ellipse: {o1:?}"); + assert_eq!(polys("DF"), vec![4, 4], "Dachfenster: Rahmen + Glas"); + let first_df = prims.iter().position(|pr| matches!(pr, Primitive::Polygon { opening_id: Some(o), .. } if o == "DF")).unwrap(); + let last_roof = prims.iter().rposition(|pr| matches!(pr, Primitive::Polygon { roof_id: Some(_), .. })).unwrap(); + assert!(first_df > last_roof, "Dachfenster vor der Dachfläche gezeichnet"); + } } diff --git a/src-tauri/core/src/plan/section.rs b/src-tauri/core/src/plan/section.rs index 7a0bdbbc..e651987f 100644 --- a/src-tauri/core/src/plan/section.rs +++ b/src-tauri/core/src/plan/section.rs @@ -737,6 +737,49 @@ fn subtract_dominant_bands(bands: Vec) -> Vec { // ── Dächer ──────────────────────────────────────────────────────────────────── /// `appendRoofSections`: Schnittspur der Dachflächen, je Schicht ein Band. +/// Formöffnungen ([G3]): Die Wand hat im Modell das Rechteck-Loch; an der Schnittstelle reicht die +/// Wand bis an den Umriss. Die geschnittenen Wandbänder über bzw. unter der Öffnung werden bis zur +/// lichten Höhe des Umrisses an dieser Stelle verlängert. +fn shaped_wall_cuts(cuts: &mut [Cut], p: &Project, walls_r: &[RWall], base: (f64, f64), u: (f64, f64)) { + let ul = hypot2(u.0, u.1); + if !(ul > 1e-12) { + return; + } + let u = (u.0 / ul, u.1 / ul); + for o in p.openings.as_deref().unwrap_or(&[]).iter().filter(|o| crate::opening_shape::is_shaped(o)) { + let Some(wall) = p.walls.iter().find(|w| w.id == o.host_wall_id) else { continue }; + let Some((from, to)) = opening_interval(wall, o) else { continue }; + let (a, _) = axis_frame(wall); + let den = a.0 * u.1 - a.1 * u.0; + if den.abs() < MIN_CROSS { + continue; + } + let (rx, ry) = (base.0 - wall.start.x, base.1 - wall.start.y); + let along = (rx * u.1 - ry * u.0) / den; + if along <= from + 1e-4 || along >= to - 1e-4 { + continue; + } + let (zb, zt) = opening_extent(p, wall, o); + let Some(poly) = crate::opening_shape::opening_outline(o, to - from, zt - zb) else { continue }; + let Some((lo, hi)) = crate::opening_shape::v_range(&poly, along - from) else { continue }; + let (new_bottom, new_top) = (zb + lo, zb + hi); + const TOL: f64 = 2e-3; + for c in cuts.iter_mut().filter(|c| c.kind == Kind::Wall && walls_r.get(c.index).is_some_and(|w| w.wall_id == wall.id)) { + let (y_lo, y_hi) = c.pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), q| (l.min(q[1]), h.max(q[1]))); + let (from_y, to_y) = if (y_lo - zt).abs() < TOL && new_top < zt - 1e-6 { + (zt, new_top) + } else if (y_hi - zb).abs() < TOL && new_bottom > zb + 1e-6 { + (zb, new_bottom) + } else { + continue; + }; + for q in c.pts.iter_mut().filter(|q| (q[1] - from_y).abs() < TOL) { + q[1] = to_y; + } + } + } +} + fn append_roof_sections(cuts: &mut Vec, p: &Project, plane: &Plane) { let roofs = p.roofs.as_deref().unwrap_or(&[]); if roofs.is_empty() { @@ -760,6 +803,11 @@ fn append_roof_sections(cuts: &mut Vec, p: &Project, plane: &Plane) { } } let sg = crate::plan_section::roof_segments(bx, by, ux, uy, &pl); + // Dachfenster ([100]): Lochkörper in der Schnittebene, aus jeder Schicht ausgeschnitten. + let holes: Vec> = crate::opening_shape::roof_openings(p, index) + .iter() + .filter_map(|(o, f)| crate::opening_shape::box_section(&crate::opening_shape::surface_hole_box(o, f), (bx, by), (ux, uy))) + .collect(); let n = sg.first().copied().unwrap_or(0.0) as usize; for k in 0..n { let o = 1 + 5 * k; @@ -774,14 +822,19 @@ fn append_roof_sections(cuts: &mut Vec, p: &Project, plane: &Plane) { let top0 = z0 - prefix; let top1 = z1 - prefix; prefix += vt; - let mut c = Cut::new(Kind::Roof, index, vec![[t_lo, top0], [t_hi, top1], [t_hi, top1 - vt], [t_lo, top0 - vt]]); - if !layer.component_id.is_empty() { - if let Some(h) = p.component(&layer.component_id).and_then(|comp| resolve_hatch(p, &comp.hatch_id, None, None, None)) { - c.fill = Some(poche_fill(h.pattern).to_string()); - c.hatch = Some(h); - } + let mut pieces = vec![vec![[t_lo, top0], [t_hi, top1], [t_hi, top1 - vt], [t_lo, top0 - vt]]]; + for h in &holes { + pieces = pieces.iter().flat_map(|pc| crate::opening_shape::subtract_convex(pc, h)).collect(); + } + let hatch = if layer.component_id.is_empty() { None } else { p.component(&layer.component_id).and_then(|comp| resolve_hatch(p, &comp.hatch_id, None, None, None)) }; + for pts in pieces { + let mut c = Cut::new(Kind::Roof, index, pts); + if let Some(h) = &hatch { + c.fill = Some(poche_fill(h.pattern).to_string()); + c.hatch = Some(h.clone()); + } + cuts.push(c); } - cuts.push(c); } } } @@ -1146,6 +1199,7 @@ pub fn compute_section(p: &Project, level: &LevelSpec, bodies: &[BodyMesh]) -> R let visible: Vec = raw.visible_edges.iter().filter(not_cut).map(&mut edge).collect(); let hidden: Vec = raw.hidden_edges.iter().filter(not_cut).map(&mut edge).collect(); + shaped_wall_cuts(&mut cuts, p, &walls_r, plane.base(), plane.u_model()); append_roof_sections(&mut cuts, p, &plane); let walls = wall_owners(p, &walls_r); let slabs = slab_owners(p, &slabs_r); @@ -1376,7 +1430,12 @@ fn cross_section(p: &Project, wall: &Wall, o: &Opening, p0: (f64, f64), u: (f64, if along < from + 1e-4 || along > to - 1e-4 { return Ok(None); } - let (z_bottom, z_top) = opening_extent(p, wall, o); + let (mut z_bottom, mut z_top) = opening_extent(p, wall, o); + // Formöffnung ([G3]): lichte Höhe an der Schnittstelle aus dem Umriss. + if let Some(poly) = crate::opening_shape::opening_outline(o, to - from, z_top - z_bottom) { + let Some((lo, hi)) = crate::opening_shape::v_range(&poly, along - from) else { return Ok(None) }; + (z_bottom, z_top) = (z_bottom + lo, z_bottom + hi); + } if z_top - z_bottom < 1e-3 { return Ok(None); } @@ -1467,9 +1526,13 @@ fn window_cut(p: &Project, wall: &Wall, o: &Opening, c: &CrossSection) -> Result out.push(l); } if let Some(t) = wt { - let shading = t.shading.as_ref().filter(|s| s.create); + // Formöffnung ([G3]): kein Sturz-Querschnitt, kein Storenkasten (Bogen/Schräge statt Sturz). + let shaped = crate::opening_shape::is_shaped(o); + let shading = t.shading.as_ref().filter(|s| s.create && !shaped); let sturz_box = shading.filter(|s| s.mount == Some(WindowShadingMount::Sturz)).map_or(0.0, |s| max(0.0, s.r#box.depth)); - lintel_cut(&mut out, o, c, t.lintel_height, sturz_box); + if !shaped { + lintel_cut(&mut out, o, c, t.lintel_height, sturz_box); + } // Fensterbänke nur bei ausdrücklicher Wahl (bisherige Schnitte bleiben gleich). let zb = c.z_bottom; if matches!(t.sill_board, Some(WindowTypeSillBoard::Aussen | WindowTypeSillBoard::Beide)) { @@ -1522,7 +1585,9 @@ fn lintel_cut(out: &mut Vec, o: &Opening, c: &CrossSection, height: O fn door_cut(p: &Project, o: &Opening, c: &CrossSection) -> Vec { let mut out = vec![opening_poly(rect(c.u_at(c.face_min), c.u_at(c.face_max), c.z_bottom, c.z_top), false, &o.id)]; - lintel_cut(&mut out, o, c, p.door_type(o).and_then(|t| t.lintel_height), 0.0); + if !crate::opening_shape::is_shaped(o) { + lintel_cut(&mut out, o, c, p.door_type(o).and_then(|t| t.lintel_height), 0.0); + } let kind = p.door_type(o).map(|t| t.kind); if o.door_type == Some(OpeningDoorType::Wandoeffnung) || kind == Some(DoorTypeKind::Wandoeffnung) { return out; @@ -1576,6 +1641,16 @@ pub fn section_opening_primitives(p: &Project, level: &LevelSpec, vis: &Visibili if !vis.visible(&o.category_code) || !vis.render(&o.category_code) { continue; } + // Dach-/Deckenfenster ([100]): Schnitt durch Rahmen, Glas und Eindeckrahmen. + if let Some(f) = crate::opening_shape::host_frame(p, o) { + let greyed = vis.greyed(&o.category_code); + for (part, corners) in crate::opening_shape::surface_window_boxes(p, o, &f) { + let Some(pts) = crate::opening_shape::box_section(&corners, p0, u) else { continue }; + let pr = opening_poly(pts.iter().map(|q| v2(q[0], q[1])).collect(), part != 0, &o.id); + out.push(if greyed { pr.with_greyed(true) } else { pr }); + } + continue; + } let Some(wall) = walls_by_id.get(o.host_wall_id.as_str()).copied() else { continue }; if !vis.visible(&wall.category_code) { continue; @@ -1752,6 +1827,57 @@ mod tests { assert!(json.contains(LINTEL_FILL) && json.contains(SHADING_PACK_FILL), "{json}"); } + /// [G3] Rundbogen-Fenster: an der Schnittstelle reicht die Wand bis an den Bogen, Rahmen/Glas folgen. + #[test] + fn rundbogen_im_schnitt() { + let mut p = sample(); + let o1 = p.openings.as_deref().unwrap().iter().find(|o| o.id == "O1").unwrap().clone(); + let w1 = p.walls.iter().find(|w| w.id == o1.host_wall_id).unwrap().clone(); + let (u, n) = axis_frame(&w1); + // Viertel der Breite: Bogen 0,5 m Radius, Kämpfer 0,7 m über der Brüstung. + let m = o1.position + o1.width / 4.0; + let c = (w1.start.x + u.0 * m, w1.start.y + u.1 * m); + let l = LevelSpec { kind: "section".into(), line: Some([Vec2 { x: c.0 - n.0 * 3.0, y: c.1 - n.1 * 3.0 }, Vec2 { x: c.0 + n.0 * 3.0, y: c.1 + n.1 * 3.0 }]), ..Default::default() }; + let (zb, zt) = opening_extent(&p, &w1, &o1); + let top_of = |p: &Project| -> f64 { + let out = compute_section(p, &l, &[]).unwrap().unwrap(); + out.cuts.iter().filter(|c| c.kind == Kind::Wall && c.source_id.as_deref() == Some("W1")).flat_map(|c| c.pts.iter().map(|q| q[1])).filter(|y| *y > zb + 0.1).fold(f64::INFINITY, f64::min) + }; + assert!((top_of(&p) - zt).abs() < 1e-3, "Rechteck: Sturz bei {zt}"); + for o in p.openings.iter_mut().flatten().filter(|o| o.id == "O1") { + o.shape = Some(OpeningShape::Rundbogen); + } + let want = zb + 0.7 + (0.25f64 - 0.0625).sqrt(); + assert!((top_of(&p) - want).abs() < 5e-3, "{} vs {want}", top_of(&p)); + let prims = section_opening_primitives(&p, &l, &Visibility::default()).unwrap(); + let ys: Vec = prims.iter().filter_map(|pr| if let Primitive::Polygon { pts, opening_id: Some(id), .. } = pr { (id == "O1").then(|| pts.iter().map(|q| q.y).fold(f64::NEG_INFINITY, f64::max)) } else { None }).collect(); + assert!(!ys.is_empty() && ys.iter().all(|y| *y < want + 5e-3), "kein Sturz/Kasten über dem Bogen: {ys:?}"); + } + + /// [100] Dachfenster: Lücke in allen Dachschichten, Rahmen/Glas geschnitten. + #[test] + fn dachfenster_im_schnitt() { + let mut p = sample(); + let l = LevelSpec { kind: "section".into(), line: Some([Vec2 { x: 2.5, y: -2.0 }, Vec2 { x: 2.5, y: 6.0 }]), ..Default::default() }; + let roof_cuts = |p: &Project| compute_section(p, &l, &[]).unwrap().unwrap().cuts.iter().filter(|c| c.kind == Kind::Roof).count(); + let before = roof_cuts(&p); + assert!(before > 0); + p.openings.as_mut().unwrap().push(Opening { + id: "DF".into(), + kind: ElementKind::Window, + category_code: "21".into(), + width: 0.78, + height: 1.18, + host_roof_id: Some("RF1".into()), + host_point: Some(Vec2 { x: 2.5, y: 1.0 }), + ..Default::default() + }); + assert!(roof_cuts(&p) > before, "Schichten links und rechts des Fensters"); + let prims = section_opening_primitives(&p, &l, &Visibility::default()).unwrap(); + let df: Vec<_> = prims.iter().filter(|pr| matches!(pr, Primitive::Polygon { opening_id: Some(id), .. } if id == "DF")).collect(); + assert!(df.len() >= 4, "Rahmen beidseits, Glas, Eindeckrahmen: {}", df.len()); + } + #[test] fn beschnittene_baender_behalten_ihre_ebene() { // Von der Dominanz beschnittene Wand-/Deckenstücke tragen ihre Kategorie weiter: Ebene aus → weg. diff --git a/src-tauri/core/src/project_refs.rs b/src-tauri/core/src/project_refs.rs index 8737a216..cec52da5 100644 --- a/src-tauri/core/src/project_refs.rs +++ b/src-tauri/core/src/project_refs.rs @@ -61,6 +61,11 @@ pub fn dangling_refs(p: &Project) -> Vec { } for o in p.openings.as_deref().unwrap_or(&[]) { miss(&mut out, "Öffnung", &o.id, "Wand", &o.host_wall_id, &walls); + // Dach-/Deckenwirt ([100]). + let roof_ids = ids(p.roofs.as_deref().unwrap_or(&[]), |r| r.id.as_str()); + let ceiling_ids = ids(p.ceilings.as_deref().unwrap_or(&[]), |c| c.id.as_str()); + miss(&mut out, "Öffnung", &o.id, "Dach", o.host_roof_id.as_deref().unwrap_or(""), &roof_ids); + miss(&mut out, "Öffnung", &o.id, "Decke", o.host_ceiling_id.as_deref().unwrap_or(""), &ceiling_ids); let types = if door_types.contains(o.type_id.as_deref().unwrap_or("")) { &door_types } else { &window_types }; miss(&mut out, "Öffnung", &o.id, "Typ", o.type_id.as_deref().unwrap_or(""), types); check_pens(&mut out, &pens, "Öffnung", &o.id, [&o.color_pen_id, &none, &none]); diff --git a/src-tauri/fileio/src/ifc_export.rs b/src-tauri/fileio/src/ifc_export.rs index 9dd191b8..1289557a 100644 --- a/src-tauri/fileio/src/ifc_export.rs +++ b/src-tauri/fileio/src/ifc_export.rs @@ -48,6 +48,11 @@ // Normale von u; Tür: Y = Aufschlagrichtung); ohne Teile (Wandöffnung) kein Körper. Alle Teile // (0 Rahmen/Zarge, 1 Türblatt, 2 Glas) sind getrennte Körper in EINER Darstellung, je mit eigenem // IfcStyledItem (Farbe/Transparenz je Rolle). +// OPENING_SOLID = 15 ([G3] Formöffnung, [100] Dach-/Deckenfenster): host ("wall/", "roof/", +// "slab/"), structure, opening_id, is_door, fill_name, n, (x, y) × n (Profil), origin (3), +// x_dir (3), z_dir (3), depth, height, width, PSETS, MESH (Füllung, Welt rel. Geschoss-UK). +// IfcOpeningElement = Profil-Extrusion entlang z_dir (Position origin/x_dir/z_dir) im Geschoss- +// Placement, IfcRelVoidsElement zum Wirt; IfcWindow/IfcDoor mit dem Netz, IfcRelFillsElement. // STAIR = 5, structure, id, predefined (Text), PTS, z_rel, depth (Ersatzkörper, nur ohne Läufe/Podest), // PSETS, n_flights, FLIGHT × n_flights, has_landing, [LANDING], has_rail, [RAIL] // FLIGHT = name, n_risers, n_treads, riser_height, tread_length, predefined (Text, IfcStairFlightTypeEnum), @@ -120,6 +125,7 @@ pub const REC_END_COLUMNS: f64 = 11.0; pub const REC_CLASSIFICATION: f64 = 12.0; pub const REC_ZONE: f64 = 13.0; pub const REC_ATTACH: f64 = 14.0; +pub const REC_OPENING_SOLID: f64 = 15.0; // ── IFC-GUID (Kompression nach IfcOpenShell `guid.compress`) ──────────────── @@ -1229,6 +1235,7 @@ fn rec_name(code: f64) -> &'static str { c if c == REC_WALL_MESH => "WALL_MESH", c if c == REC_CEILING => "CEILING", c if c == REC_OPENING => "OPENING", + c if c == REC_OPENING_SOLID => "OPENING_SOLID", c if c == REC_CLASSIFICATION => "CLASSIFICATION", c if c == REC_ZONE => "ZONE", c if c == REC_ATTACH => "ATTACH", @@ -1661,6 +1668,72 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { w.add_pset(p, fill_entity, &format!("fill/{opening_id}")); } } + c if c == REC_OPENING_SOLID => { + let host = r.string()?; + let structure = r.structure(n_storeys)?; + let opening_id = r.string()?; + let is_door = r.flag()?; + let fill_name = r.string()?; + let profile = r.pts()?; + let mut v = [0.0; 10]; + for x in v.iter_mut() { + *x = r.f()?; + } + let (height, width) = (r.f()?, r.f()?); + let psets = r.psets()?; + let mesh = r.mesh()?; + if v.iter().any(|x| !x.is_finite()) || profile.len() < 3 || profile.iter().any(|q| !(q.0.is_finite() && q.1.is_finite())) { + return Err(format!("Öffnungskörper mit NaN/∞ bei {}", r.pos - 1)); + } + let host_entity = match host.strip_prefix("wall/") { + Some(id) => w.walls.get(id).map(|x| x.0), + None => w.elements.get(&host).copied(), + }; + let Some(host_entity) = host_entity else { continue }; + let parent = w.placement_of(structure); + let polyline = w.emit_closed_polyline(&profile); + let prof = w.add("IFCARBITRARYCLOSEDPROFILEDEF", format!("{},$,#{polyline}", enum_("AREA"))); + let o = w.add("IFCCARTESIANPOINT", list(&[fmt_real(v[0]), fmt_real(v[1]), fmt_real(v[2])])); + let xd = w.add("IFCDIRECTION", list(&[fmt_real(v[3]), fmt_real(v[4]), fmt_real(v[5])])); + let zd = w.add("IFCDIRECTION", list(&[fmt_real(v[6]), fmt_real(v[7]), fmt_real(v[8])])); + let pos = w.add("IFCAXIS2PLACEMENT3D", format!("#{o},#{zd},#{xd}")); + let solid = w.add("IFCEXTRUDEDAREASOLID", format!("#{prof},#{pos},#{},{}", w.extrude_dir, fmt_real(v[9].max(0.001)))); + let shape = w.emit_swept_shape(&[solid]); + let opening_placement = w.emit_placement(0.0, parent); + let g = w.gid(&format!("opening/{opening_id}")); + let opening_entity = w.add( + "IFCOPENINGELEMENT", + format!( + "{g},#{},{},$,$,#{opening_placement},#{shape},${}", + w.owner_history, + ifc_string(if is_door { "Türöffnung" } else { "Fensteröffnung" }), + if v2 { String::new() } else { format!(",{}", enum_("OPENING")) } + ), + ); + let g = w.gid(&format!("voids/{opening_id}")); + w.add("IFCRELVOIDSELEMENT", format!("{g},#{},$,$,#{host_entity},#{opening_entity}", w.owner_history)); + let fill_placement = w.emit_placement(0.0, opening_placement); + let fill_shape = if mesh.indices.is_empty() { + "$".to_string() + } else { + let (item, rep_type) = if w.v2() { w.emit_face_brep(&mesh) } else { (w.emit_face_set(&mesh), "Tessellation") }; + let rep = w.add("IFCSHAPEREPRESENTATION", format!("#{},{},{},{}", w.context, ifc_string("Body"), ifc_string(rep_type), refs(&[item]))); + format!("#{}", w.add("IFCPRODUCTDEFINITIONSHAPE", format!("$,$,{}", refs(&[rep])))) + }; + let g = w.gid(&format!("fill/{opening_id}")); + let tail = if v2 { String::new() } else { format!(",{},$,$", enum_(if is_door { "DOOR" } else { "WINDOW" })) }; + let fill_entity = w.add( + if is_door { "IFCDOOR" } else { "IFCWINDOW" }, + format!("{g},#{},{},$,$,#{fill_placement},{fill_shape},$,{},{}{tail}", w.owner_history, ifc_string(&fill_name), fmt_real(height), fmt_real(width)), + ); + let g = w.gid(&format!("fills/{opening_id}")); + w.add("IFCRELFILLSELEMENT", format!("{g},#{},$,$,#{opening_entity},#{fill_entity}", w.owner_history)); + w.add_to_containment(structure, fill_entity); + w.elements.insert(format!("fill/{opening_id}"), fill_entity); + for p in &psets { + w.add_pset(p, fill_entity, &format!("fill/{opening_id}")); + } + } c if c == REC_STAIR => { let structure = r.structure(n_storeys)?; let id = r.string()?; @@ -3044,6 +3117,52 @@ mod tests { assert_eq!(b, full_house_2x3(true)); } + /// [100]/[G3] Öffnungskörper als gedrehte Profil-Extrusion im Dach, Füllung als Netz. + #[test] + fn dachfenster_oeffnungskoerper() { + for v2 in [false, true] { + let mut b = mini_in(if v2 { B::v2() } else { B::new() }); + b.n(&[REC_ROOF, -1.0]); + b.str("R"); + b.str("Dach"); + b.str("GABLE_ROOF"); + b.no_type(); + b.no_psets(); + b.n(&[4.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0]); + b.n(&[2.0, 0.0, 1.0, 2.0, 0.0, 2.0, 3.0]); + b.f.push(0.0); + b.n(&[REC_OPENING_SOLID]); + b.str("roof/R"); + b.n(&[-1.0]); + b.str("DF"); + b.n(&[0.0]); + b.str("Dachfenster"); + b.pts(&[(0.0, 0.0), (0.78, 0.0), (0.78, 1.18), (0.0, 1.18)]); + b.n(&[0.1, 0.2, 0.3, 1.0, 0.0, 0.0, 0.0, 0.5, -0.866, 1.3, 1.18, 0.78]); + b.no_psets(); + b.n(&[3.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 2.0, 0.0]); + // Unbekannter Wirt: übersprungen. + b.n(&[REC_OPENING_SOLID]); + b.str("roof/X"); + b.n(&[-1.0]); + b.str("DX"); + b.n(&[0.0]); + b.str("x"); + b.pts(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)]); + b.n(&[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]); + b.no_psets(); + b.n(&[0.0, 0.0, 0.0]); + let ifc = build(&b).unwrap(); + check_structure(&ifc); + assert_eq!(count(&ifc, "IFCOPENINGELEMENT"), 1); + assert_eq!(count(&ifc, "IFCWINDOW"), 1); + assert_eq!(count(&ifc, "IFCRELVOIDSELEMENT"), 1); + assert_eq!(count(&ifc, "IFCRELFILLSELEMENT"), 1); + assert!(ifc.contains("IFCDIRECTION((0.0,0.5,-0.866))"), "Extrusionsrichtung = −Normale"); + assert_eq!(count(&ifc, "IFCARBITRARYCLOSEDPROFILEDEF"), 1); + } + } + #[test] fn ifc2x3_offenes_netz_ist_shell_based_surface_model() { let mut b = mini_in(B::v2()); diff --git a/src/commands/cmds/roofWindow.ts b/src/commands/cmds/roofWindow.ts new file mode 100644 index 00000000..a07556ad --- /dev/null +++ b/src/commands/cmds/roofWindow.ts @@ -0,0 +1,35 @@ +// Dachfenster ([100]) als Engine-Befehl: ein Klick setzt ein Fenster (78 × 118 cm, in der Dachebene +// gemessen) mit seiner Mitte an den Punkt — in das Dach, dessen Umriss den Punkt enthält (Dächer des +// aktiven Geschosses zuerst), sonst als Oberlicht in die Decke des Geschosses. Die Öffnung schneidet +// alle Schichten (Kern: `cmd_solid.rs::roof_window_ops`, Geometrie `opening_shape.rs`). + +import { createMutation } from "../createCore"; +import type { Command, CommandResult, CommandState } from "../types"; + +const idle = (): [CommandState, CommandResult] => [{ phase: "start", lastPoint: null }, { draft: null, done: true }]; + +export const roofWindowCommand: Command = { + name: "roofwindow", + labelKey: "cmd.roofWindow.label", + floorOnly: true, + prompt: () => "cmd.roofWindow.start", + accepts: () => ["point"], + options: () => [], + init: (): CommandState => ({ phase: "start", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + if (input.kind !== "point") return [state, { draft: null }]; + return [ + { phase: "start", lastPoint: input.point }, + { draft: null, commit: createMutation(ctx, { cmd: "roofWindow", p: input.point }) }, + ]; + }, + + onMove: (state, point): [CommandState, CommandResult] => [ + state, + { draft: { preview: [{ kind: "poly", pts: [point], closed: false }], vertices: [point] } }, + ], + + onConfirm: (): [CommandState, CommandResult] => idle(), + onCancel: (): [CommandState, CommandResult] => idle(), +}; diff --git a/src/commands/registry.ts b/src/commands/registry.ts index afaab770..e4535cea 100644 --- a/src/commands/registry.ts +++ b/src/commands/registry.ts @@ -18,6 +18,7 @@ import { solidCommand } from "./cmds/solid"; import { solidBoolCommand } from "./cmds/solidbool"; import { voidBoxCommand } from "./cmds/voidbox"; import { ceilingOpeningCommand } from "./cmds/ceilingOpening"; +import { roofWindowCommand } from "./cmds/roofWindow"; import { roofHoleCommand } from "./cmds/roofHole"; import { roomCommand } from "./cmds/room"; import { rectCommand } from "./cmds/rect"; @@ -78,6 +79,7 @@ export const COMMANDS: Record = { solidbool: solidBoolCommand, voidbox: voidBoxCommand, ceilingopening: ceilingOpeningCommand, + roofwindow: roofWindowCommand, roofhole: roofHoleCommand, room: roomCommand, line: lineCommand, @@ -161,6 +163,8 @@ export const ALIASES: Record = { body: "solid", deckenloch: "ceilingopening", aussparung: "ceilingopening", + dachfenster: "roofwindow", + oberlicht: "roofwindow", dachhof: "roofhole", lichthof: "roofhole", rf: "roof", diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 9461aa26..4e5bc2e5 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -570,6 +570,16 @@ export const de = { "oed.f.width": "Breite (m)", "oed.f.height": "Höhe (m)", "oed.f.sillHeight": "Brüstungshöhe (m)", + "oed.f.shape": "Form", + "oed.f.shapeRise": "Stich / Höhe der Form (m)", + "oed.shapeNote": "Formöffnung: Schnitt, Ansicht, 3D und IFC folgen dem Umriss. Anschlag, Sturz, Storenkasten und Flügelteilung gelten nur für Rechtecke.", + "oed.shape.rechteck": "Rechteck", + "oed.shape.rundbogen": "Rundbogen", + "oed.shape.segmentbogen": "Segmentbogen", + "oed.shape.spitzbogen": "Spitzbogen", + "oed.shape.rund": "Rund / oval", + "oed.shape.schraeg": "Schräg", + "oed.shape.giebel": "Giebel (spitz)", "oed.f.position": "Position (m)", "oed.f.frameThickness": "Rahmenstärke quer (m)", "oed.f.frameDepth": "Rahmentiefe (m)", @@ -1346,6 +1356,8 @@ export const de = { "cmd.roof.label": "Dach", "cmd.roof.start": "Erste Dachecke:", "cmd.roof.corner": "Gegenecke:", + "cmd.roofWindow.label": "Dachfenster", + "cmd.roofWindow.start": "Mitte des Dachfensters (in einer Dachfläche, sonst Oberlicht in der Decke):", "cmd.ceilingOpening.label": "Deckenloch", "cmd.ceilingOpening.start": "Erste Ecke der Aussparung (in einer Decke):", "cmd.ceilingOpening.corner": "Gegenecke:", @@ -2586,6 +2598,7 @@ export const de = { "history.cmd.block": "Block einfügen", "history.cmd.break": "Auftrennen", "history.cmd.ceiling": "Decke zeichnen", + "history.cmd.roofWindow": "Dachfenster", "history.cmd.ceilingOpening": "Deckenöffnung", "history.cmd.chamfer": "Fase", "history.cmd.circle": "Kreis zeichnen", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index c027fbfd..bce7f7e7 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -569,6 +569,16 @@ export const en: Record = { "oed.f.width": "Width (m)", "oed.f.height": "Height (m)", "oed.f.sillHeight": "Sill height (m)", + "oed.f.shape": "Shape", + "oed.f.shapeRise": "Rise of the shape (m)", + "oed.shapeNote": "Shaped opening: section, elevation, 3D and IFC follow the outline. Rebate, lintel, blind box and sash division apply to rectangles only.", + "oed.shape.rechteck": "Rectangle", + "oed.shape.rundbogen": "Round arch", + "oed.shape.segmentbogen": "Segmental arch", + "oed.shape.spitzbogen": "Pointed arch", + "oed.shape.rund": "Round / oval", + "oed.shape.schraeg": "Sloped", + "oed.shape.giebel": "Gable (pointed)", "oed.f.position": "Position (m)", "oed.f.frameThickness": "Frame depth across (m)", "oed.f.frameDepth": "Frame depth (m)", @@ -1335,6 +1345,8 @@ export const en: Record = { "cmd.roof.label": "Roof", "cmd.roof.start": "First roof corner:", "cmd.roof.corner": "Opposite corner:", + "cmd.roofWindow.label": "Roof window", + "cmd.roofWindow.start": "Centre of the roof window (in a roof face, otherwise skylight in the ceiling):", "cmd.ceilingOpening.label": "Slab opening", "cmd.ceilingOpening.start": "First corner of the opening (inside a slab):", "cmd.ceilingOpening.corner": "Opposite corner:", @@ -2572,6 +2584,7 @@ export const en: Record = { "history.cmd.block": "Insert block", "history.cmd.break": "Break", "history.cmd.ceiling": "Draw ceiling", + "history.cmd.roofWindow": "Roof window", "history.cmd.ceilingOpening": "Ceiling opening", "history.cmd.chamfer": "Chamfer", "history.cmd.circle": "Draw circle", diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index 53a0848e..877e60f8 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -1647,6 +1647,38 @@ export type Opening = { * Fenstertyp dort eine Sims-Linie aktiviert hat. */ sillLineStyle?: LineStyleOverride; + /** + * Umriss der Öffnung in der Wandebene ([G3]); fehlt ⇒ Rechteck. Bestimmt den Wandausschnitt + * (Schnitt, Ansicht, 3D, IFC-Öffnungskörper); der Grundriss bleibt beim SIA-Symbol. Die + * Öffnung füllt ihr Rechteck `width × height`; Bogen/Schräge liegen oben (Rund: Ellipse darin). + */ + shape?: "rechteck" | "rundbogen" | "segmentbogen" | "spitzbogen" | "rund" | "schraeg" | "giebel"; + /** + * Stichhöhe der Form in Metern ([G3]): Segmentbogen = Bogenstich (Default Breite/6), Spitzbogen = + * Höhe über dem Kämpfer (≥ Breite/2, Default gleichseitig), Giebel = Höhe des Dreiecks (Default + * Breite/2), Schräg = Höhenunterschied links→rechts (> 0 rechts höher, Default Breite/2). + * Rundbogen/Rund/Rechteck ignorieren es. + */ + shapeRise?: number; + /** + * Wirt Dach ([100], Dachfenster): Öffnung in einer Dachfläche; `hostWallId` bleibt leer. Lage + * über {@link hostPoint}; `width` quer zum Gefälle, `height` entlang des Gefälles (in der + * Dachebene gemessen); `position`/`sillHeight` gelten nicht. + */ + hostRoofId?: string; + /** + * Wirt Decke ([100], Deckenöffnung mit Oberlicht): Öffnung in einer Decke, Lage über + * {@link hostPoint}, `width` × `height` waagrecht (gedreht um {@link hostAngle}). + */ + hostCeilingId?: string; + /** Nur Dach-/Deckenwirt ([100]): Mittelpunkt der Öffnung im Grundriss (Meter). */ + hostPoint?: Vec2; + /** + * Nur Dach-/Deckenwirt ([100]): Drehung der Breitenrichtung im Grundriss in Grad, wo die + * Fläche waagrecht ist (Decke, Flachdach); geneigte Dachflächen richten die Breite längs der + * Traufe aus. Fehlt ⇒ 0 (x-Achse). + */ + hostAngle?: number; }; /** diff --git a/src/panels/ToolsPanel.tsx b/src/panels/ToolsPanel.tsx index 286a8f59..defb12af 100644 --- a/src/panels/ToolsPanel.tsx +++ b/src/panels/ToolsPanel.tsx @@ -355,7 +355,7 @@ const TOOLS_2D: ToolId[] = [ "image", ]; const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"]; -const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "extrude", "solid", "solidbool", "sectionline", "viewline", "autodim"]; +const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "roofwindow", "extrude", "solid", "solidbool", "sectionline", "viewline", "autodim"]; const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "break", "extend", "fillet", "chamfer", "join", "defblock", "measure"]; type ToolsView = "list" | "icons"; diff --git a/src/ui/OpeningEditorDialog.tsx b/src/ui/OpeningEditorDialog.tsx index a3d7e385..1c55b62d 100644 --- a/src/ui/OpeningEditorDialog.tsx +++ b/src/ui/OpeningEditorDialog.tsx @@ -425,10 +425,43 @@ function GroessePanel({ min={0} onCommit={(n) => onPatchOpening({ position: n })} /> + {/* [G3] Umrissform (Wandausschnitt in Schnitt, Ansicht, 3D, IFC; Grundriss bleibt SIA-Symbol). */} + + label={t("oed.f.shape")} + value={opening.shape ?? "rechteck"} + options={OPENING_SHAPE_OPTS()} + onChange={(v) => onPatchOpening({ shape: v === "rechteck" ? undefined : v, shapeRise: undefined })} + /> + {(opening.shape === "segmentbogen" || + opening.shape === "spitzbogen" || + opening.shape === "schraeg" || + opening.shape === "giebel") && ( + onPatchOpening({ shapeRise: n })} + /> + )} + {opening.shape && opening.shape !== "rechteck" &&

{t("oed.shapeNote")}

} ); } +type OpeningShapeValue = NonNullable; + +/** Stich ohne Angabe wie im Kern (`opening_shape::outline`). */ +function defaultShapeRise(o: Opening): number { + const w = o.width; + const r = o.shape === "segmentbogen" ? w / 6 : o.shape === "spitzbogen" ? (w * Math.sqrt(3)) / 2 : w / 2; + return Math.round(r * 1000) / 1000; +} + +const OPENING_SHAPE_OPTS = (): { value: OpeningShapeValue; label: string }[] => + (["rechteck", "rundbogen", "segmentbogen", "spitzbogen", "rund", "schraeg", "giebel"] as const).map((v) => ({ + value: v, + label: t(`oed.shape.${v}`), + })); + function RahmenPanel({ isDoor, wt, diff --git a/src/ui/ribbon/CommandIcon.tsx b/src/ui/ribbon/CommandIcon.tsx index 83c8bfaf..3131179f 100644 --- a/src/ui/ribbon/CommandIcon.tsx +++ b/src/ui/ribbon/CommandIcon.tsx @@ -190,6 +190,15 @@ export function CommandIcon({ name }: { name: string }) { ); + case "roofwindow": + // Dachfenster: Dachfläche mit Fensterrahmen und Glas. + return ( + + + + + + ); case "ceilingopening": // Deckenloch: Decken-Rechteck mit ausgespartem Innenrechteck. return (