[B4] IFC-Import Teil 2: L- und Wendeltreppen, gedrehte Dächer/Neigung je Kante, Bogenwände mit Öffnungen, Träger als Extrusionskörper, gedrehte Georeferenz

Treppe: Wendel (Zentrum, Winkelschritt, Breite, Drehsinn, Spindel) und L (Podest an der Ecke) aus den
Trittflächen; U-/Mehrpodest-Treppen bleiben Mesh mit Grund stairTurn. Dach: kleinstes umschliessendes
Rechteck auch gedreht, Sattel mit edgePitchDeg wo die Standardform nicht passt (Pult fallend, gedreht),
Tonnendach-Streifen ganz Mesh. Bogenwand: Öffnungen nach Bogenlänge. IfcBeam als senkrechtes Prisma ->
extrudedSolids. Georeferenz mit XAxisAbscissa/Ordinate: Bauteile und Meshes kartenparallel gedreht.
Dialog: Träger-Zeile, Gründe. Testhilfe: Element-Arten um roof/stair/beam ergänzt (tsc).
This commit is contained in:
Claude committed 2026-11-06 22:50:27 +00:00
1 parent 957f3d0d04
commit 6fa42b3216
10 files changed
+1225 -181

No files matched your search

+23
View File
@@ -3486,6 +3486,29 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module
fallend nach +x/+y (Dossier-Pult steigt nur dorthin), gedrehte/nicht rechteckige Dächer, Tonnen-/Mansarddächer,
Podest-, L- und Wendeltreppen, Bogenwände mit Öffnungen, Ständerwände (Rahmen + Beplankung), gedrehte Georeferenz,
Träger/Geländer; nur Linux-Container (CLI-SVG + Chromium), nicht in der Tauri-App, Dialog nur per tsc.
(6.11., Teil 2) Treppen (`ifc_shapes.rs`): Tritte je Höhe mit Schwerpunkt (Belag über Rohbau nur zusammengefasst,
wenn an derselben Stelle); Wendel → Dossier-Wendel (Zentrum aus den Tritt-Schwerpunkten, gleicher Winkelschritt,
Radius/Breite aus Innen-/Aussenkante, Drehsinn, Spindel aus senkrechten Flächen ringsum im Auge); L (zwei
rechtwinklige Läufe gleicher Breite, quadratisches Podest an der Ecke, Stufenaufteilung wie Dossier) → `shape: "L"`;
andere Podesttreppen (U mit Halbpodest, zwei Viertelpodeste) → Grund `stairTurn` (Dossier kennt nur gerade/L/Wendel,
gerade Treppe ohne Podest, keine Höhenlage je Lauf). Dächer: Rechteck auch gedreht (kleinstes umschliessendes);
Flach/Walm gedreht als Umriss, sonst (gedreht, Pult fallend nach +x/+y, Flächen über Eck) Sattel mit
`edgePitchDeg` (Traufe je Kante, Giebel `null`; Kern-Test: Dossier-Fläche = IFC-Fläche); Tonnendach aus ebenen
Streifen (≥ 4 Neigungen um eine waagrechte Achse) bleibt ganz Mesh statt Flickwerk aus Einzelstreifen. Bogenwand mit
Öffnungen: Kasten in der Tangente, durch die ganze Dicke auch an den Laibungen → Lage nach Bogenlänge (Laibungen
radial wie Dossier). IfcBeam als senkrechtes Prisma → `extrudedSolids` (Grundriss, Höhe, `baseOffset`); schräge/
liegende Profile bleiben Mesh. Gedrehte Georeferenz (XAxisAbscissa/-Ordinate, LV95-Bezug, Massstab 1): Bauteile
und Meshes kartenparallel gedreht (+y = Nord, Stützen drehen mit, Dächer mit Neigung je Kante), dann
zurückgeschoben; ohne Projekt-Bezug lokal und ungedreht. Dialog: Zeile „Träger", Gründe `stairTurn`, Texte.
Quote (vorher → nachher): FZK-Haus Wendeltreppe 0 → 1, Träger 0 → 4/4 (Pfetten); Smiley West unverändert (Wände
270/281, Dächer 11), 30 U-Treppen jetzt mit Grund `stairTurn`, 10 Träger nicht prismatisch; Institute Dächer 6 → 0
(die 6 waren Streifen der Tonnendächer, jetzt ganz Mesh), 4 Treppen mit zwei Viertelpodesten `stairTurn`;
Schependomlaan Dächer 19 → 22 (Pult fallend), Wände 795 → 797, Träger 0 → 85/174 (89 schräg/Profil). In den
Beispielen keine L-Treppe, keine Bogenwand mit Öffnung und keine gedrehte Georeferenz — nur synthetisch geprüft
(Rust-Tests fileio + Kern). Bilder (lokal): FZK EG-Grundriss und Schnitt durch die Wendeltreppe, Institute Schnitt.
Offen: U-/Mehrpodest-Treppen (Modell bräuchte Form „U" oder Höhenlage je Lauf; 34 in den Beispielen), Podest allein
(Schependomlaan „trapbordes"), Tonnen-/Mansarddach, Träger schräg/als Profil (Modell ohne Träger), Extrusionskörper
über der Schnitthöhe im Grundriss nicht sichtbar; nur Linux-Container, nicht in der Tauri-App.
- ◐ **[B5] IFC-Export nachziehen** (`exportIfc.ts`). Stand 28.10.:
- ✅ Nicht-ASCII nach ISO 10303-21 (`\X2\`/`\X4\`).
- ✅ Materialschichten: Wand-/Decken-/Dachtypen als IfcWallType/IfcSlabType/IfcRoofType mit
+239 -12
View File
@@ -1,5 +1,6 @@
//! IFC-Import zu echten Bauteilen ([B4], [K4] S4; vorher `io/ifcElements.ts`): baut aus dem, was das
//! Format-Modul erkannt hat (`fileio/src/ifc_semantic.rs`: Achse, Dicke, Höhe, Umriss … in Metern),
//! Format-Modul erkannt hat (`fileio/src/ifc_semantic.rs`: Achse, Dicke, Höhe, Umriss … in Metern; dazu Dächer
//! auch mit Neigung je Kante, Treppen gerade/L/Wendel, Träger als Extrusionskörper, gedrehte Georeferenz),
//! Dossier-Objekte — Geschosse, Wände (Wandtyp aus den Materialschichten, wiederverwendet oder neu),
//! Türen/Fenster/Wanddurchbrüche, Decken (Deckentyp), Stützen, Räume; der Rest kommt als Kontext-Mesh
//! (`import_context`). Ergebnis sind Ops auf dem Projekt (ein Undo-Schritt) und eine Zusammenfassung.
@@ -126,10 +127,15 @@ struct RoofData {
pitch_deg: f64,
eave_z: f64,
thickness: f64,
/// Neigung je Umrisskante (`None` = Giebel); gilt, wenn `custom` (Form dann Sattel bzw. Walm).
edge_pitch: Vec<Option<f64>>,
custom: bool,
}
struct StairData {
info: Info,
/// "straight", "L", "spiral".
shape: String,
start: [f64; 2],
dir: [f64; 2],
run_length: f64,
@@ -137,6 +143,20 @@ struct StairData {
step_count: f64,
z0: f64,
total_rise: f64,
run2_length: f64,
turn: f64,
center: [f64; 2],
radius: f64,
sweep: f64,
center_column: f64,
}
/// Träger als senkrechtes Prisma → Extrusionskörper.
struct BeamData {
info: Info,
outline: Vec<[f64; 2]>,
z0: f64,
z1: f64,
}
struct Storey {
@@ -154,6 +174,7 @@ struct Elements {
spaces: Vec<SpaceData>,
roofs: Vec<RoofData>,
stairs: Vec<StairData>,
beams: Vec<BeamData>,
kept: Map<String, Value>,
/// Je Klasse die Gründe, weshalb Kandidaten Mesh blieben (`{"IfcWall": {"slopedTop": 3}}`).
kept_reasons: Map<String, Value>,
@@ -281,15 +302,30 @@ fn decode_elements(meta: &Value, data: &[f64]) -> Elements {
if let Some(mut r) = rings(v, 3, 1.0) {
let shape = s_of(e.get("shape")).filter(|x| ["flach", "pult", "sattel", "walm"].contains(&x.as_str()));
let axis = s_of(e.get("ridgeAxis")).filter(|x| x == "x" || x == "y");
let outline = r.remove(0);
// Neigung je Kante: Zahl ≥ 0 (Traufe) oder null (Giebel), eine je Umrisskante.
let edge_pitch: Option<Vec<Option<f64>>> = e.get("edgePitch").and_then(Value::as_array).map(|a| a.iter().map(|x| x.as_f64().filter(|p| p.is_finite() && *p >= 0.0 && *p < 89.0)).collect());
let edge_pitch = edge_pitch.filter(|a| a.len() == outline.len()).unwrap_or_default();
let custom = e.get("custom").and_then(Value::as_bool).unwrap_or(false) && !edge_pitch.is_empty();
if let (Some(shape), Some(ridge_axis)) = (shape, axis) {
out.roofs.push(RoofData { info, outline: r.remove(0), shape, ridge_axis, eave_z: v[0], pitch_deg: v[1], thickness: v[2] });
out.roofs.push(RoofData { info, outline, shape, ridge_axis, eave_z: v[0], pitch_deg: v[1], thickness: v[2], edge_pitch, custom });
}
}
}
"stair" => {
if v.len() == 9 && v[6] >= 2.0 && v[6] <= 200.0 && v[4] > 0.0 && v[5] > 0.0 {
let shape = s_of(e.get("shape")).unwrap_or_else(|| "straight".into());
let ok = (v.len() == 9 || v.len() == 16) && v[6] >= 2.0 && v[6] <= 200.0 && v[4] > 0.0 && v[5] > 0.0;
let x = |i: usize| v.get(i).copied().unwrap_or(0.0);
let shape_ok = match shape.as_str() {
"straight" => true,
"L" => x(9) > 0.0 && x(10).abs() == 1.0,
"spiral" => x(13) > 0.0 && x(14) != 0.0 && x(14).abs() <= 3600.0,
_ => false,
};
if ok && shape_ok {
out.stairs.push(StairData {
info,
shape,
start: [v[0], v[1]],
dir: [v[2], v[3]],
run_length: v[4],
@@ -297,9 +333,20 @@ fn decode_elements(meta: &Value, data: &[f64]) -> Elements {
step_count: v[6].round(),
z0: v[7],
total_rise: v[8],
run2_length: x(9),
turn: x(10),
center: [x(11), x(12)],
radius: x(13),
sweep: x(14),
center_column: x(15),
});
}
}
"beam" => {
if let (Some(mut r), true) = (rings(v, 2, 1.0), v.len() >= 2 && v[1] > v[0]) {
out.beams.push(BeamData { info, outline: r.remove(0), z0: v[0], z1: v[1] });
}
}
"space" => {
if let Some(mut r) = rings(v, 2, 1.0) {
out.spaces.push(SpaceData {
@@ -511,7 +558,7 @@ fn list_of(root: &Map<String, Value>, key: &str) -> Vec<(Value, bool)> {
fn elements_ops(root: &Map<String, Value>, meta: &Value, products: &[IfcProduct], el: &Elements, opts: &IfcOptions, now: f64) -> (Vec<Op>, Value, usize) {
let kept: f64 = el.kept.values().map(|v| v.as_f64().unwrap_or(f64::NAN)).sum();
let mut summary = Map::new();
for k in ["walls", "openings", "ceilings", "columns", "rooms", "roofs", "stairs", "floors", "wallTypes", "ceilingTypes", "roofTypes", "doorTypes", "windowTypes", "components", "meshes", "classified"] {
for k in ["walls", "openings", "ceilings", "columns", "rooms", "roofs", "stairs", "beams", "floors", "wallTypes", "ceilingTypes", "roofTypes", "doorTypes", "windowTypes", "components", "meshes", "classified"] {
summary.insert(k.into(), 0.into());
}
summary.insert("kept".into(), js_num(kept));
@@ -540,6 +587,9 @@ fn elements_ops(root: &Map<String, Value>, meta: &Value, products: &[IfcProduct]
for s in &el.stairs {
extra.extend(s.start);
}
for b in &el.beams {
b.outline.iter().for_each(|p| extra.extend(p));
}
let [dx, dy] = map_shift(meta, root).unwrap_or_else(|| geo_shift(products, project_geo_origin(root), &extra));
let mv = |p: [f64; 2]| pt([round(p[0] + dx, 1e-9), round(p[1] + dy, 1e-9)]);
@@ -812,6 +862,11 @@ fn elements_ops(root: &Map<String, Value>, meta: &Value, products: &[IfcProduct]
"shape": r.shape, "pitchDeg": js_num(round(r.pitch_deg, 1e-6)), "overhang": 0, "ridgeAxis": r.ridge_axis,
"baseElevation": js_num(round(r.eave_z, 1e-6)), "thickness": js_num(round(r.thickness, 1e-6)),
});
// Standardform passt nicht (gedreht, Pult fallend …): Neigung je Kante, Giebel wo keine Traufe ist.
if r.custom && r.shape != "flach" {
v["shape"] = (if r.edge_pitch.iter().all(Option::is_some) { "walm" } else { "sattel" }).into();
v["edgePitchDeg"] = r.edge_pitch.iter().map(|p| p.map_or(Value::Null, |x| js_num(round(x, 1e-6)))).collect();
}
// Dachtyp nur mit Material aus der Datei; sonst einschichtig über `thickness`.
if r.info.layers.iter().any(|l| !l.material.trim().is_empty()) {
v["roofTypeId"] = type_for(&mut ctx, &mut roof_types, &r.info, r.thickness, "rooftype", "roofTypes").into();
@@ -821,12 +876,42 @@ fn elements_ops(root: &Map<String, Value>, meta: &Value, products: &[IfcProduct]
let mut stairs: Vec<Value> = Vec::new();
for s in &el.stairs {
let (fid, _, _) = floor_of(&mut ctx, s.info.storey, s.z0);
stairs.push(json!({
"id": ctx.new_id("stair"), "type": "stair", "floorId": fid, "categoryCode": STAIR_CATEGORY, "shape": "straight",
let mut v = json!({
"id": ctx.new_id("stair"), "type": "stair", "floorId": fid, "categoryCode": STAIR_CATEGORY, "shape": s.shape,
"start": mv(s.start), "dir": {"x": js_num(round(s.dir[0], 1e-9)), "y": js_num(round(s.dir[1], 1e-9))},
"runLength": js_num(round(s.run_length, 1e-6)), "width": js_num(round(s.width, 1e-6)),
"totalRise": js_num(round(s.total_rise, 1e-6)), "stepCount": js_num(s.step_count), "up": true,
}));
});
match s.shape.as_str() {
"L" => {
v["run2Length"] = js_num(round(s.run2_length, 1e-6));
v["turn"] = js_num(s.turn.signum());
}
"spiral" => {
v["center"] = mv(s.center);
v["radius"] = js_num(round(s.radius, 1e-6));
v["sweep"] = js_num(round(s.sweep, 1e-6));
if s.center_column > 0.0 {
v["centerColumn"] = js_num(round(s.center_column, 1e-6));
}
}
_ => {}
}
stairs.push(v);
}
// Träger als Extrusionskörper (Grundriss + Höhe über der Geschoss-UK).
let mut solids: Vec<Value> = Vec::new();
for b in &el.beams {
let (fid, base, _) = floor_of(&mut ctx, b.info.storey, b.z0);
let mut v = json!({
"id": ctx.new_id("solid"), "type": "extrudedSolid", "levelId": fid,
"points": b.outline.iter().map(|&p| mv(p)).collect::<Vec<_>>(), "height": js_num(round(b.z1 - b.z0, 1e-6)),
});
let off = anchor_offset(b.z0, base);
if off.abs() > 1e-9 {
v["baseOffset"] = js_num(off);
}
solids.push(v);
}
// ── Übrige Bauteile als Kontext-Mesh ──
@@ -840,7 +925,7 @@ fn elements_ops(root: &Map<String, Value>, meta: &Value, products: &[IfcProduct]
+ el.roofs.iter().filter(|r| r.info.classified).count()
+ el.stairs.iter().filter(|s| s.info.classified).count()
+ products.iter().filter(|p| !p.classifications.is_empty()).count();
for (k, n) in [("walls", walls.len()), ("openings", openings.len()), ("ceilings", ceilings.len()), ("columns", columns.len()), ("rooms", rooms.len()), ("roofs", roofs.len()), ("stairs", stairs.len()), ("meshes", n_meshes), ("classified", classified)] {
for (k, n) in [("walls", walls.len()), ("openings", openings.len()), ("ceilings", ceilings.len()), ("columns", columns.len()), ("rooms", rooms.len()), ("roofs", roofs.len()), ("stairs", stairs.len()), ("beams", solids.len()), ("meshes", n_meshes), ("classified", classified)] {
ctx.summary.insert(k.into(), n.into());
}
@@ -859,12 +944,12 @@ fn elements_ops(root: &Map<String, Value>, meta: &Value, products: &[IfcProduct]
if !walls.is_empty() {
ops.push(Op::Add { collection: "walls".into(), items: walls, at: None });
}
for (key, items) in [("openings", openings), ("ceilings", ceilings), ("columns", columns), ("rooms", rooms), ("roofs", roofs), ("stairs", stairs)] {
for (key, items) in [("openings", openings), ("ceilings", ceilings), ("columns", columns), ("rooms", rooms), ("roofs", roofs), ("stairs", stairs), ("extrudedSolids", solids)] {
if root.get(key).is_some_and(|v| crate::json_util::truthy(Some(v))) {
if !items.is_empty() {
ops.push(Op::Add { collection: key.into(), items, at: None });
}
} else {
} else if !(key == "extrudedSolids" && items.is_empty()) {
ops.push(Op::SetField { key: key.into(), value: Some(Value::Array(items)), at: None });
}
}
@@ -887,18 +972,80 @@ fn map_shift(meta: &Value, root: &Map<String, Value>) -> Option<[f64; 2]> {
let ax = [axis.first()?.as_f64()?, axis.get(1)?.as_f64()?];
let crs = m.get("crs").and_then(Value::as_str).unwrap_or("");
let lv95 = crs.is_empty() || crs.contains("2056") || crs.to_uppercase().contains("LV95");
let plain = (ax[0] - 1.0).abs() < 1e-9 && ax[1].abs() < 1e-9 && (num("scale").unwrap_or(1.0) - 1.0).abs() < 1e-9;
let plain = ax[0].is_finite() && ax[1].is_finite() && ax[0].hypot(ax[1]) > 1e-12 && (num("scale").unwrap_or(1.0) - 1.0).abs() < 1e-9;
let o = project_geo_origin(root)?;
(lv95 && plain && o[0].is_finite() && o[1].is_finite() && e.is_finite() && n.is_finite()).then(|| [e - o[0], n - o[1]])
}
/// Drehung der Georeferenz ([B4], XAxisAbscissa/-Ordinate: Richtung der lokalen x-Achse in der Karte) als
/// (cos, sin), wenn [`map_shift`] gilt und die Datei gedreht ist; das Dossier-Modell ist kartenparallel
/// (+y = Nord), die Bauteile werden also vor dem Rückschub um diesen Winkel gedreht.
fn map_rotation(meta: &Value, root: &Map<String, Value>) -> Option<[f64; 2]> {
map_shift(meta, root)?;
let axis = meta.get("mapConversion")?.get("xAxis").and_then(Value::as_array)?;
let (x, y) = (axis.first()?.as_f64()?, axis.get(1)?.as_f64()?);
let l = x.hypot(y);
let (c, s) = (x / l, y / l);
(s.abs() > 1e-12 || c < 0.0).then_some([c, s])
}
/// Alle erkannten Bauteile um den Nullpunkt drehen (`cs` = cos, sin). Dächer mit Neigung werden „je Kante"
/// (die Standardformen hängen an den Achsen); Stützen drehen mit.
fn rotate_elements(el: &mut Elements, cs: [f64; 2]) {
let [c, s] = cs;
let rot = |p: &mut [f64; 2]| *p = [c * p[0] - s * p[1], s * p[0] + c * p[1]];
let ring = |r: &mut Vec<[f64; 2]>| r.iter_mut().for_each(rot);
for w in &mut el.walls {
rot(&mut w.start);
rot(&mut w.end);
}
for sl in &mut el.slabs {
ring(&mut sl.outline);
sl.holes.iter_mut().for_each(ring);
}
for col in &mut el.columns {
rot(&mut col.center);
col.rotation += s.atan2(c);
}
for sp in &mut el.spaces {
ring(&mut sp.boundary);
}
for r in &mut el.roofs {
ring(&mut r.outline);
if r.shape != "flach" && r.edge_pitch.len() == r.outline.len() {
r.custom = true;
}
}
for st in &mut el.stairs {
rot(&mut st.start);
rot(&mut st.dir);
rot(&mut st.center);
}
for b in &mut el.beams {
ring(&mut b.outline);
}
}
/// IFC ins Projekt `root`: als Kontext-Meshes oder (mit `opts.elements`) als Bauteile.
pub fn ifc_import(root: &Map<String, Value>, meta_json: &str, positions: &[f64], indices: &[f64], element_data: &[f64], opts: &IfcOptions, now: f64) -> Result<IfcResult, String> {
let meta: Value = serde_json::from_str(meta_json).map_err(|e| format!("IFC-Bericht: {e}"))?;
// Gedrehte Georeferenz: Meshes und Bauteile kartenparallel drehen.
let rotation = map_rotation(&meta, root);
let rotated: Vec<f64>;
let positions = match rotation {
Some([c, s]) => {
rotated = positions.chunks(3).flat_map(|p| if p.len() == 3 { vec![c * p[0] - s * p[1], s * p[0] + c * p[1], p[2]] } else { p.to_vec() }).collect();
&rotated[..]
}
None => positions,
};
let products = crate::import_context::decode_ifc_products(&meta, positions, indices)?;
let report = crate::import_context::ifc_report(&meta, &products);
if opts.elements {
let el = decode_elements(&meta, element_data);
let mut el = decode_elements(&meta, element_data);
if let Some(cs) = rotation {
rotate_elements(&mut el, cs);
}
let kept = el.kept.clone();
let (ops, summary, n) = elements_ops(root, &meta, &products, &el, opts, now);
// Statt der Roh-Bauteile die Zusammenfassung (an derselben Stelle des Berichts).
@@ -1036,4 +1183,84 @@ mod tests {
let r = ifc_import(&bare, &m.to_string(), &[], &[], &data, &opts, 0.0).unwrap();
assert!(at(&added(&r.ops, "walls")[0]["start"], 5.0, 0.0));
}
/// L- und Wendeltreppe, Dach mit Neigung je Kante, Träger; Georeferenz um 90° gedreht (lokal x = Nord).
fn meta_rotated(x_axis: [f64; 2]) -> (Value, Vec<f64>) {
let data = vec![
// Wand
0.0, 0.0, 4.0, 0.0, 0.0, 2.5, 0.2, 0.0,
// Pultdach fallend nach +y: Traufe an Kante 2 (y = 8), sonst Giebel
3.0, 30.0, 0.2, 4.0, 0.0, 0.0, 10.0, 0.0, 10.0, 8.0, 0.0, 8.0,
// L-Treppe: sx, sy, dx, dy, lauf1, breite, stufen, z0, steighöhe, lauf2, turn, cx, cy, r, sweep, spindel
1.0, 2.0, 1.0, 0.0, 1.12, 1.0, 9.0, 0.0, 1.53, 1.12, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0,
// Wendeltreppe
2.8, 3.0, 0.0, 1.0, 4.54, 1.0, 13.0, 0.0, 2.34, 0.0, 0.0, 2.0, 3.0, 0.8, 325.0, 0.3,
// Träger: z0, z1, Ring
2.6, 3.0, 4.0, 0.0, 0.0, 4.0, 0.0, 4.0, 0.2, 0.0, 0.2,
];
let info = |kind: &str, at: usize, n: usize| json!({"kind": kind, "at": at, "n": n, "storey": 0, "layers": [], "classifications": [], "common": {}});
let mut roof = info("roof", 8, 12);
roof["shape"] = "sattel".into();
roof["ridgeAxis"] = "x".into();
roof["edgePitch"] = json!([null, null, 30.0, null]);
roof["custom"] = true.into();
let mut l = info("stair", 20, 16);
l["shape"] = "L".into();
let mut sp = info("stair", 36, 16);
sp["shape"] = "spiral".into();
let meta = json!({
"schema": "IFC4", "lengthScale": 1, "products": [], "skippedItems": {}, "skippedProducts": {},
"productsWithoutGeometry": 0, "simplifiedBooleans": 0, "voidsApplied": 0, "voidsIgnored": 0, "parseErrors": 0, "truncated": false,
"mapConversion": {"eastings": 2600100.0, "northings": 1200050.0, "height": 0.0, "xAxis": x_axis, "scale": 1.0, "crs": "EPSG:2056"},
"elements": {
"storeys": [{"globalId": "s", "name": "EG", "elevation": 0.0}],
"elements": [info("wall", 0, 8), roof, l, sp, info("beam", 52, 11)],
"kept": {}, "keptReasons": {},
},
});
(meta, data)
}
#[test]
fn l_and_spiral_stair_edge_pitch_roof_beam_and_rotated_map() {
let opts = IfcOptions { file_name: "a.ifc".into(), group: None, elements: true };
// Ungedreht: Werte wie erkannt.
let (m, data) = meta_rotated([1.0, 0.0]);
let r = ifc_import(&root(), &m.to_string(), &[], &[], &data, &opts, 0.0).unwrap();
let roofs = added(&r.ops, "roofs");
assert_eq!((roofs[0]["shape"].as_str(), &roofs[0]["edgePitchDeg"]), (Some("sattel"), &json!([null, null, 30, null])));
let stairs = added(&r.ops, "stairs");
let l = stairs[0];
assert_eq!((l["shape"].as_str(), l["turn"].as_f64(), l["stepCount"].as_f64()), (Some("L"), Some(1.0), Some(9.0)));
assert!((l["run2Length"].as_f64().unwrap() - 1.12).abs() < 1e-9);
assert!(at(&l["start"], 101.0, 52.0));
let s = stairs[1];
assert_eq!((s["shape"].as_str(), s["sweep"].as_f64()), (Some("spiral"), Some(325.0)));
assert!((s["radius"].as_f64().unwrap() - 0.8).abs() < 1e-9 && (s["centerColumn"].as_f64().unwrap() - 0.3).abs() < 1e-9);
assert!(at(&s["center"], 102.0, 53.0) && at(&s["start"], 102.8, 53.0));
let solids = added(&r.ops, "extrudedSolids");
assert_eq!(solids.len(), 1);
assert_eq!(solids[0]["type"].as_str(), Some("extrudedSolid"));
assert!((solids[0]["height"].as_f64().unwrap() - 0.4).abs() < 1e-9 && (solids[0]["baseOffset"].as_f64().unwrap() - 2.6).abs() < 1e-9);
assert!(at(&solids[0]["points"][2], 104.0, 50.2));
assert_eq!(r.summary.unwrap()["beams"].as_f64(), Some(1.0));
// Lokal x zeigt nach Norden (90°): alles um 90° gedreht, dann verschoben.
let (m, data) = meta_rotated([0.0, 1.0]);
let r = ifc_import(&root(), &m.to_string(), &[], &[], &data, &opts, 0.0).unwrap();
let w = added(&r.ops, "walls")[0];
assert!(at(&w["start"], 100.0, 50.0) && at(&w["end"], 100.0, 54.0), "{w}");
let roof = added(&r.ops, "roofs")[0];
assert!(at(&roof["outline"][2], 92.0, 60.0) && at(&roof["outline"][3], 92.0, 50.0), "{roof}");
assert_eq!((roof["shape"].as_str(), &roof["edgePitchDeg"]), (Some("sattel"), &json!([null, null, 30, null])));
let stairs = added(&r.ops, "stairs");
assert!(at(&stairs[0]["start"], 98.0, 51.0) && at(&stairs[0]["dir"], 0.0, 1.0), "{}", stairs[0]);
assert!(at(&stairs[1]["center"], 97.0, 52.0) && at(&stairs[1]["start"], 97.0, 52.8), "{}", stairs[1]);
assert!(at(&added(&r.ops, "extrudedSolids")[0]["points"][2], 99.8, 54.0));
// Ohne Projekt-Bezug bleibt die Datei lokal und ungedreht.
let mut bare = root();
bare.remove("geoAnchor");
let r = ifc_import(&bare, &m.to_string(), &[], &[], &data, &opts, 0.0).unwrap();
assert!(at(&added(&r.ops, "walls")[0]["end"], 4.0, 0.0));
}
}
+24
View File
@@ -979,6 +979,30 @@ mod tests {
assert!((z_at(&g, 3.0, 3.5).unwrap() - 0.5).abs() < 1e-9);
}
/// IFC-Import [B4]: Pult fallend nach +y und gedrehtes Satteldach als Sattel mit Neigung je Kante.
#[test]
fn pult_und_gedrehter_sattel_ueber_neigung_je_kante() {
let tan = 30f64.to_radians().tan();
// Pult über RECT, Traufe an Kante 2 (y = 4), höchste Stelle bei y = 0, drei Giebel.
let p = RoofParams { pitch_deg: 30.0, edge_pitch_deg: Some(vec![None, None, Some(30.0), None]), ..params(&RECT, Shape::Sattel) };
let g = roof_geometry(&p, 3.0);
for (x, y) in [(1.0, 0.5), (3.0, 2.0), (5.5, 3.5)] {
assert!((z_at(&g, x, y).unwrap() - (3.0 + (4.0 - y) * tan)).abs() < 1e-9, "{x} {y}");
}
assert_eq!(g.gables.len(), 3);
// Satteldach 6 × 4 um 30° gedreht: Traufen an den langen Kanten, Giebel an den kurzen.
let (s, c) = 30f64.to_radians().sin_cos();
let rot = |p: P2| [c * p[0] - s * p[1], s * p[0] + c * p[1]];
let outline: Vec<P2> = RECT.iter().map(|&p| rot(p)).collect();
let p = RoofParams { pitch_deg: 30.0, edge_pitch_deg: Some(vec![Some(30.0), None, Some(30.0), None]), ..params(&outline, Shape::Sattel) };
let g = roof_geometry(&p, 0.0);
for (u, v) in [(1.0, 0.5), (3.0, 2.0), (5.5, 3.5), (0.2, 1.0)] {
let q = rot([u, v]);
assert!((z_at(&g, q[0], q[1]).unwrap() - v.min(4.0 - v) * tan).abs() < 1e-9, "{u} {v}");
}
assert_eq!(g.gables.len(), 2);
}
#[test]
fn giebel_je_kante_wie_satteldach() {
// Walm mit Giebel an den beiden Kanten quer zur X-Achse = Satteldach entlang X.
+310 -88
View File
@@ -33,6 +33,9 @@
// Raum ohne Körper: Umriss aus „FootPrint", Höhe aus „Box" (ArchiCAD IFC2x3). Dreiecksnetze mit
// T-Stössen: Kanten werden an Punkten darauf geteilt. Grund je Mesh gebliebenem Kandidaten
// (`kept_reasons`, Kennwort → Dialog `ifc.reason.*`).
// - (6.11., Teil 2) Treppe auch als L (Podest an der Ecke) und Wendel; Dach auch gedreht bzw. mit Neigung je
// Kante (Pult fallend …), Tonnendach-Streifen bleiben ganz Mesh; Bogenwand mit Öffnungen (Lage nach
// Bogenlänge); Träger (IfcBeam) als senkrechtes Prisma → Extrusionskörper.
// - Klassifikation (IfcRelAssociatesClassification → IfcClassificationReference, Bauteil oder Typ) an jedem
// erkannten Bauteil (`Info::classifications`); IfcZone (IfcRelAssignsToGroup) liefert dem Raum die
// SIA-416-Kategorie, wenn er keine eigene `SIA416`-Eigenschaft trägt.
@@ -183,8 +186,12 @@ pub struct Space {
#[derive(Clone, Debug, Default)]
pub struct Roof {
pub info: Info,
/// Umriss der Traufe (aussen, gegen den Uhrzeigersinn, Rechteck bei Sattel/Walm/Pult).
/// Umriss der Traufe (aussen, gegen den Uhrzeigersinn, Rechteck, auch gedreht).
pub outline: Vec<V2>,
/// Je Umrisskante (Punkt i → i+1) die Neigung (Grad) einer Traufe, `None` = Giebel bzw. Flachdach.
pub edge_pitch: Vec<Option<f64>>,
/// Die Dossier-Standardform passt nicht (gedreht, Pult fallend …): `edge_pitch` gilt (Form "sattel").
pub custom: bool,
/// Dossier-Dachform: "flach", "pult", "sattel", "walm".
pub shape: &'static str,
pub pitch_deg: f64,
@@ -198,19 +205,38 @@ pub struct Roof {
pub parts: Vec<u64>,
}
/// Gerade Treppe ([B4]) aus IfcStair/IfcStairFlight.
/// Treppe ([B4]) aus IfcStair/IfcStairFlight: gerade, L (Podest an der Ecke) oder Wendel.
#[derive(Clone, Debug, Default)]
pub struct Stair {
pub info: Info,
/// Mitte der Antrittskante (unten).
/// Dossier-Grundform: "straight", "L", "spiral".
pub shape: &'static str,
/// Mitte der Antrittskante (unten); Wendel: Punkt der Lauflinie an der Antrittskante.
pub start: V2,
/// Einheits-Laufrichtung (aufwärts).
/// Einheits-Laufrichtung (aufwärts) des ersten Laufs; Wendel: Tangente am Antritt.
pub dir: V2,
pub run_length: f64,
pub width: f64,
pub step_count: usize,
pub z0: f64,
pub total_rise: f64,
/// L: Länge des zweiten Laufs und Abbiegerichtung (+1 links, −1 rechts).
pub run2_length: f64,
pub turn: f64,
/// Wendel: Zentrum, Radius der Lauflinie, Gesamtwinkel (Grad, + = gegen den Uhrzeigersinn), Spindel (0 = keine).
pub center: V2,
pub radius: f64,
pub sweep_deg: f64,
pub center_column: f64,
}
/// Träger ([B4], IfcBeam) als senkrechtes Prisma: Dossier-Extrusionskörper (Grundriss + Höhe).
#[derive(Clone, Debug, Default)]
pub struct Beam {
pub info: Info,
pub outline: Vec<V2>,
pub z0: f64,
pub z1: f64,
}
/// Erkannte Bauteile einer Datei.
@@ -225,6 +251,8 @@ pub struct Semantic {
pub spaces: Vec<Space>,
pub roofs: Vec<Roof>,
pub stairs: Vec<Stair>,
/// Träger als senkrechte Prismen (Dossier-Extrusionskörper).
pub beams: Vec<Beam>,
/// Kandidaten (Wand, Decke, Stütze, Raum, Dach, Treppe), die nicht sicher abbildbar waren, je Klasse.
pub kept: BTreeMap<String, usize>,
/// Dieselben je Klasse und Grund (Kennwort, s. [`Reason`]).
@@ -590,6 +618,42 @@ fn box_in_frame(m: &Mesh, o: V2, d: V2) -> Option<([f64; 6], f64)> {
Some((b, signed_volume(&m.positions, &m.indices) / bv))
}
/// Öffnung einer Bogenwand: Winkelbereich (rad, gegen den Uhrzeigersinn, im Bogen `a0 … a1`) der Laibungen auf
/// der Achse und Höhenbereich. Der Körper ist ein Kasten in der Tangente an seiner Mitte, durch die ganze
/// Wanddicke (auch an den Laibungen, wo der Ring zur Tangente hin abfällt); sonst `None`.
fn arc_span(m: &Mesh, a: &crate::ifc_shapes::ArcFit, z0: f64, z1: f64) -> Option<(f64, f64, f64, f64)> {
let n = m.positions.len() / 3;
if n == 0 {
return None;
}
let (sx, sy) = m.positions.chunks_exact(3).fold((0.0, 0.0), |s, c| (s.0 + c[0], s.1 + c[1]));
let mid = (sy / n as f64 - a.center[1]).atan2(sx / n as f64 - a.center[0]);
// Winkel in den Bogen legen.
let mut mid = mid;
while mid < a.a0 - 1e-9 {
mid += std::f64::consts::TAU;
}
let r = a.radius;
let (ri, ro) = (r - a.thickness / 2.0, r + a.thickness / 2.0);
let o = [a.center[0] + r * mid.cos(), a.center[1] + r * mid.sin()];
let d = [-mid.sin(), mid.cos()];
// Rahmen: u entlang der Tangente (gegen den Uhrzeigersinn), v = left(d) zeigt zum Zentrum.
let (b, fill) = box_in_frame(m, o, d)?;
let umax = b[0].abs().max(b[1].abs());
if !(umax < ri) {
return None;
}
let outer = r - ro; // v der Aussenfläche an der Mitte (am weitesten aussen)
let inner = r - (ri * ri - umax * umax).sqrt(); // v der Innenfläche an der Laibung (am weitesten innen)
let through = b[2] <= outer + 1e-3 && b[3] >= inner - 1e-3;
let (p0, p1) = (mid + (b[0] / r).asin(), mid + (b[1] / r).asin());
let inside = p0 >= a.a0 - 1e-6 && p1 <= a.a1 + 1e-6 && b[5] > z0 + 0.01 && b[4] < z1 - 0.01;
if !(through && inside && (0.95..=1.0 + 1e-3).contains(&fill)) {
return None;
}
Some((p0, p1, b[4].max(z0), b[5].min(z1)))
}
// ---------------------------------------------------------------------------
// Erkennung
// ---------------------------------------------------------------------------
@@ -610,6 +674,8 @@ struct WallCand {
items: Vec<Mesh>,
/// Bogenwand: Bulge der Achse start → end (Modell-Konvention, + = Scheitel links); 0 = gerade.
bulge: f64,
/// Bogenwand: Kreis der Achse (Öffnungen liegen nach Winkel).
arc: Option<crate::ifc_shapes::ArcFit>,
}
struct Ctx<'r, 'a> {
@@ -900,23 +966,39 @@ impl Ctx<'_, '_> {
_ => None,
};
let items = if layers.len() > 1 && usage_side.is_none() { self.r.product_item_meshes(id, MAX_BODY_TRIS) } else { Vec::new() };
Ok(WallCand { info: self.info(id, color), start, end, z0: s.z0, z1: s.z1, thickness: t, openings, usage_side, items, bulge: 0.0 })
Ok(WallCand { info: self.info(id, color), start, end, z0: s.z0, z1: s.z1, thickness: t, openings, usage_side, items, bulge: 0.0, arc: None })
}
/// Bogenwand ([T2]): senkrechtes Prisma mit einem Ringausschnitt als Grundriss, ohne Öffnungen.
/// Bogenwand ([T2]): senkrechtes Prisma mit einem Ringausschnitt als Grundriss. (6.11.) Öffnungen:
/// quaderförmig (Kasten in der Tangente an ihrer Mitte), durch die ganze Wanddicke, innerhalb von Bogen
/// und Höhe; Dossier legt sie nach Bogenlänge auf die Achse (Laibungen radial).
fn arc_wall(&mut self, id: u64, s: &Shape, color: Option<[f64; 4]>) -> Result<WallCand, &'static str> {
let (ring, holes) = prism(s).ok_or(R_NOT_RECT)?;
if !holes.is_empty() {
return Err(R_NOT_RECT);
}
let a = crate::ifc_shapes::fit_arc_ring(&ring).ok_or(R_NOT_RECT)?;
if self.rels.voids.get(&id).is_some_and(|v| !v.is_empty()) {
return Err(R_OPENING);
let mut openings = Vec::new();
for &o in self.rels.voids.get(&id).map(Vec::as_slice).unwrap_or(&[]) {
let (om, _) = self.body(o).ok_or(R_OPENING)?;
if arc_span(&om, &a, s.z0, s.z1).is_none() {
return Err(R_OPENING);
}
let (filling, kind) = match self.fills.get(&o).map(Vec::as_slice).unwrap_or(&[]) {
[] => (None, OpeningKind::Hole),
[x] => match self.r.f.get(*x).map(|e| e.ty.as_str()).unwrap_or("") {
t if t.starts_with("IFCDOOR") => (Some(*x), OpeningKind::Door),
t if t.starts_with("IFCWINDOW") => (Some(*x), OpeningKind::Window),
_ => return Err(R_OPENING),
},
_ => return Err(R_OPENING),
};
openings.push((o, filling, kind, om, None));
}
let at = |w: f64| [a.center[0] + a.radius * w.cos(), a.center[1] + a.radius * w.sin()];
// Gegen den Uhrzeigersinn: Scheitel rechts der Sehne → Bulge negativ.
let bulge = -((a.a1 - a.a0) / 4.0).tan();
Ok(WallCand { info: self.info(id, color), start: at(a.a0), end: at(a.a1), z0: s.z0, z1: s.z1, thickness: a.thickness, openings: Vec::new(), usage_side: None, items: Vec::new(), bulge })
Ok(WallCand { info: self.info(id, color), start: at(a.a0), end: at(a.a1), z0: s.z0, z1: s.z1, thickness: a.thickness, openings, usage_side: None, items: Vec::new(), bulge, arc: Some(a) })
}
fn slab(&mut self, id: u64) -> Result<Slab, &'static str> {
@@ -989,6 +1071,21 @@ impl Ctx<'_, '_> {
Ok(Column { info: self.info(id, color), center, rotation, profile, z0: s.z0, z1: s.z1 })
}
/// Träger: senkrechtes Prisma (waagrechter Rechteck- oder Plattenträger) ohne Loch; schräge Träger und
/// Profile (I, U …) liegend bleiben Mesh.
fn beam(&mut self, id: u64) -> Result<Beam, &'static str> {
let (mesh, color) = self.body(id).ok_or(R_NO_BODY)?;
let s = shape(&mesh).ok_or(R_SHAPE)?;
let (outline, holes) = prism(&s).ok_or(R_NOT_PRISM)?;
if !holes.is_empty() {
return Err(R_NOT_PRISM);
}
if !(s.z1 - s.z0 >= 0.01 && s.z1 - s.z0 <= 5.0) {
return Err(R_DIMENSIONS);
}
Ok(Beam { info: self.info(id, color), outline, z0: s.z0, z1: s.z1 })
}
fn space(&mut self, id: u64) -> Result<Space, &'static str> {
let (boundary, z0, z1, color) = match self.body(id) {
Some((mesh, color)) => {
@@ -1191,67 +1288,89 @@ fn roofs(cx: &mut Ctx, out: &mut Semantic, ids: &[u64], children: &HashMap<u64,
let mut fail = HashMap::new();
for (main, parts, is_roof) in groups {
let mut todo = vec![parts];
// Mehrere frei stehende Platten, die zusammen kein Dach ergeben: jede einzeln versuchen.
let mut tried_single = false;
while let Some(group) = todo.pop() {
let try_fit = |cx: &mut Ctx, group: &[u64]| -> Result<(crate::ifc_shapes::RoofFit, Option<[f64; 4]>), &'static str> {
let main = if is_roof { main } else { group[0] };
let has_voids = group.iter().chain([&main]).any(|p| rels.voids.get(p).is_some_and(|v| !v.is_empty()));
let b = if has_voids { Vec::new() } else { bodies(cx, &group) };
if group.iter().chain([&main]).any(|p| rels.voids.get(p).is_some_and(|v| !v.is_empty())) {
return Err(R_OPENING);
}
let b = bodies(cx, group);
if b.len() != group.len() {
return Err(R_NO_BODY);
}
let color = b.iter().find_map(|x| x.2);
let res = if has_voids {
Err(R_OPENING)
} else if b.len() != group.len() {
Err(R_NO_BODY)
} else {
let meshes: Vec<Mesh> = b.into_iter().map(|x| x.1).collect();
crate::ifc_shapes::fit_roof(&meshes)
};
match res {
Ok(fit) => {
let [x0, y0, x1, y1] = fit.bbox;
let mut info = cx.info(main, color);
if info.storey.is_none() {
info.storey = group.iter().find_map(|p| cx.info(*p, None).storey);
}
if info.layers.is_empty() {
let l = cx.info(group[0], None);
info.layers = l.layers;
info.type_name = info.type_name.or(l.type_name);
}
out.converted.insert(main);
out.converted.extend(group.iter().copied());
out.roofs.push(Roof {
info,
outline: vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]],
shape: fit.shape,
pitch_deg: fit.pitch_deg,
ridge_axis: fit.ridge_axis,
eave_z: fit.eave_z,
thickness: fit.thickness,
parts: group.clone(),
});
cx.roofs.push(fit);
}
Err(why) => {
if !is_roof && group.len() > 1 && !tried_single {
tried_single = true;
todo.extend(group.iter().map(|p| vec![*p]));
continue;
}
for p in &group {
fail.insert(*p, why);
}
if is_roof {
out.keep("IfcRoof", why);
let meshes: Vec<Mesh> = b.into_iter().map(|x| x.1).collect();
crate::ifc_shapes::fit_roof(&meshes).map(|f| (f, color))
};
type Fit = (crate::ifc_shapes::RoofFit, Option<[f64; 4]>);
let fits: Result<Vec<(Vec<u64>, Fit)>, &'static str> = match try_fit(cx, &parts) {
Ok(f) => Ok(vec![(parts.clone(), f)]),
// Mehrere frei stehende Platten, die zusammen kein Dach ergeben: jede einzeln — ausser bei einem
// Tonnendach aus ebenen Streifen (sonst Flickwerk aus Pult- und Flachdächern).
Err(why) if !is_roof && parts.len() > 1 => {
let meshes: Vec<Mesh> = bodies(cx, &parts).into_iter().map(|x| x.1).collect();
if crate::ifc_shapes::is_barrel(&meshes) {
Err(why)
} else {
let mut ok = Vec::new();
for p in &parts {
match try_fit(cx, &[*p]) {
Ok(f) => ok.push((vec![*p], f)),
Err(w) => {
fail.insert(*p, w);
}
}
}
Ok(ok)
}
}
Err(why) => Err(why),
};
let fits = match fits {
Ok(f) => f,
Err(why) => {
for p in &parts {
fail.insert(*p, why);
}
if is_roof {
out.keep("IfcRoof", why);
}
continue;
}
};
for (group, (fit, color)) in fits {
let main = if is_roof { main } else { group[0] };
let outline = fit.outline().to_vec();
let edge_pitch: Vec<Option<f64>> = fit.eaves.iter().map(|&e| e.then_some(fit.pitch_deg)).collect();
let mut info = cx.info(main, color);
if info.storey.is_none() {
info.storey = group.iter().find_map(|p| cx.info(*p, None).storey);
}
if info.layers.is_empty() {
let l = cx.info(group[0], None);
info.layers = l.layers;
info.type_name = info.type_name.or(l.type_name);
}
out.converted.insert(main);
out.converted.extend(group.iter().copied());
out.roofs.push(Roof {
info,
outline,
edge_pitch,
custom: fit.edge_pitch.is_some(),
shape: fit.shape,
pitch_deg: fit.pitch_deg,
ridge_axis: fit.ridge_axis,
eave_z: fit.eave_z,
thickness: fit.thickness,
parts: group.clone(),
});
cx.roofs.push(fit);
}
}
fail
}
/// Treppen ([B4]): IfcStair (eigener Körper und Teile ausser Geländern) bzw. frei stehender
/// IfcStairFlight → gerade Dossier-Treppe.
fn stairs(cx: &mut Ctx, out: &mut Semantic, ids: &[u64], children: &HashMap<u64, Vec<u64>>) {
@@ -1272,24 +1391,58 @@ fn stairs(cx: &mut Ctx, out: &mut Semantic, ids: &[u64], children: &HashMap<u64,
let color = b.iter().find_map(|x| x.2);
let used: Vec<u64> = b.iter().map(|x| x.0).collect();
let meshes: Vec<Mesh> = b.into_iter().map(|x| x.1).collect();
match crate::ifc_shapes::fit_stair(&meshes) {
// Oberster Tritt auf Geschosshöhe: er ist der Austritt; sonst kommt dieser noch dazu.
let exits = |z0: f64, riser: f64, treads: usize, top_is_exit: bool| {
let top = z0 + riser * treads as f64;
top_is_exit || elevations.iter().any(|z| (z - top).abs() <= 0.02)
};
let fit = match crate::ifc_shapes::fit_stair(&meshes) {
Ok(st) => {
let steps = if exits(st.z0, st.riser, st.treads, st.top_is_exit) { st.treads } else { st.treads + 1 };
Ok(Stair { shape: "straight", start: st.start, dir: st.dir, run_length: st.going * steps as f64, width: st.width, step_count: steps, z0: st.z0, total_rise: st.riser * steps as f64, ..Default::default() })
}
Err(_) => match crate::ifc_shapes::fit_spiral(&meshes) {
Ok(sp) => {
let steps = if exits(sp.z0, sp.riser, sp.treads, sp.top_is_exit) { sp.treads } else { sp.treads + 1 };
let sweep = sp.step * steps as f64;
let (c, s) = (sp.a0.cos(), sp.a0.sin());
let sense = sp.step.signum();
Ok(Stair {
shape: "spiral",
start: [sp.center[0] + sp.radius * c, sp.center[1] + sp.radius * s],
dir: [-s * sense, c * sense],
run_length: sp.radius * sweep.abs(),
width: sp.width,
step_count: steps,
z0: sp.z0,
total_rise: sp.riser * steps as f64,
center: sp.center,
radius: sp.radius,
sweep_deg: sweep.to_degrees(),
center_column: sp.column.unwrap_or(0.0),
..Default::default()
})
}
Err(_) => crate::ifc_shapes::fit_l_stair(&meshes).and_then(|l| {
// Dossier: Lauf 1 = n1 Tritte, Podest = ein Tritt, Lauf 2 bis zum Austritt; die Aufteilung der
// Stufen auf die Läufe folgt den Lauflängen und muss die der Datei ergeben.
let z_top = l.z0 + l.riser * (l.n1 + 1 + l.n2) as f64;
let s2 = if l.top_is_exit || elevations.iter().any(|z| (z - z_top).abs() <= 0.02) { l.n2 } else { l.n2 + 1 };
let (run1, run2) = (l.going1 * l.n1 as f64, l.going2 * s2 as f64);
let body = (l.n1 + s2) as f64;
if (body * run1 / (run1 + run2)).round() as usize != l.n1 || s2 < 1 {
return Err(crate::ifc_shapes::R_STAIR_TURN);
}
let steps = l.n1 + 1 + s2;
Ok(Stair { shape: "L", start: l.start, dir: l.dir, run_length: run1, width: l.width, step_count: steps, z0: l.z0, total_rise: l.riser * steps as f64, run2_length: run2, turn: l.turn, ..Default::default() })
}),
},
};
match fit {
Ok(st) => {
// Oberster Tritt auf Geschosshöhe: er ist der Austritt; sonst kommt dieser noch dazu.
let top = st.z0 + st.riser * st.treads as f64;
let steps = if st.top_is_exit || elevations.iter().any(|z| (z - top).abs() <= 0.02) { st.treads } else { st.treads + 1 };
out.converted.insert(id);
out.converted.extend(used);
let info = cx.info(id, color);
out.stairs.push(Stair {
info,
start: st.start,
dir: st.dir,
run_length: st.going * steps as f64,
width: st.width,
step_count: steps,
z0: st.z0,
total_rise: st.riser * steps as f64,
});
out.stairs.push(Stair { info: cx.info(id, color), ..st });
}
Err(why) => out.keep(&class_name(&e.ty), why),
}
@@ -1400,7 +1553,7 @@ pub(crate) fn analyze(r: &mut Reader, rels: &Rels, ids: &[u64]) -> Semantic {
for &id in ids {
let Some(e) = f.get(id) else { continue };
let ty = e.ty.as_str();
let candidate = matches!(ty, "IFCWALL" | "IFCWALLSTANDARDCASE" | "IFCSLAB" | "IFCSLABSTANDARDCASE" | "IFCCOLUMN" | "IFCCOLUMNSTANDARDCASE" | "IFCSPACE");
let candidate = matches!(ty, "IFCWALL" | "IFCWALLSTANDARDCASE" | "IFCSLAB" | "IFCSLABSTANDARDCASE" | "IFCCOLUMN" | "IFCCOLUMNSTANDARDCASE" | "IFCSPACE" | "IFCBEAM" | "IFCBEAMSTANDARDCASE");
let has_shape = e.arg(6).and_then(|v| v.as_ref_id()).and_then(|i| f.get(i)).is_some_and(|s| s.ty == "IFCPRODUCTDEFINITIONSHAPE");
if !candidate || !has_shape || out.converted.contains(&id) {
continue;
@@ -1414,6 +1567,7 @@ pub(crate) fn analyze(r: &mut Reader, rels: &Rels, ids: &[u64]) -> Semantic {
"IFCWALL" | "IFCWALLSTANDARDCASE" => cx.wall(id).map(|w| walls.push(w)),
"IFCSLAB" | "IFCSLABSTANDARDCASE" => cx.slab(id).map(|s| out.slabs.push(s)),
"IFCCOLUMN" | "IFCCOLUMNSTANDARDCASE" => cx.column(id).map(|c| out.columns.push(c)),
"IFCBEAM" | "IFCBEAMSTANDARDCASE" => cx.beam(id).map(|b| out.beams.push(b)),
_ => cx.space(id).map(|s| out.spaces.push(s)),
}
};
@@ -1466,11 +1620,20 @@ pub(crate) fn analyze(r: &mut Reader, rels: &Rels, ids: &[u64]) -> Semantic {
let host = out.walls.len();
let len = len2(sub2(end, start));
for (o, filling, kind, mesh, form) in &w.openings {
let Some((b, _)) = box_in_frame(mesh, start, d) else { continue };
let u0 = b[0].max(0.0);
let u1 = b[1].min(len);
let z0 = b[4].max(w.z0);
let z1 = b[5].min(w.z1);
// Lage entlang der Achse (Bogenwand: Bogenlänge ab dem Dossier-Anfang) und Richtung der Wand dort.
let (u0, u1, z0, z1, d) = match &w.arc {
Some(a) => {
let Some((p0, p1, z0, z1)) = arc_span(mesh, a, w.z0, w.z1) else { continue };
let (s0, s1) = if side > 0 { (a.radius * (a.a1 - p1), a.radius * (a.a1 - p0)) } else { (a.radius * (p0 - a.a0), a.radius * (p1 - a.a0)) };
let pm = (p0 + p1) / 2.0;
let t = if side > 0 { [pm.sin(), -pm.cos()] } else { [-pm.sin(), pm.cos()] };
(s0.max(0.0), s1.min(a.radius * (a.a1 - a.a0)), z0, z1, t)
}
None => {
let Some((b, _)) = box_in_frame(mesh, start, d) else { continue };
(b[0].max(0.0), b[1].min(len), b[4].max(w.z0), b[5].min(w.z1), d)
}
};
let info = cx.info(filling.unwrap_or(*o), None);
let (operation, swing, hinge) = match filling {
Some(x) => cx.operation(*x, d),
@@ -1585,8 +1748,10 @@ fn unhosted_fillings(cx: &mut Ctx, out: &mut Semantic, ids: &[u64]) {
// slab: z0, z1, nRings, (nPts, x, y, …)* (erster Ring = Umriss)
// column: cx, cy, rotation, z0, z1, a, b (rect: Breite, Tiefe; round: Radius, 0)
// space: z0, z1, nPts, x, y, …
// roof: eaveZ, pitchDeg, thickness, nPts, x, y, … (Form, Firstrichtung im JSON)
// stair: sx, sy, dx, dy, runLength, width, stepCount, z0, totalRise
// roof: eaveZ, pitchDeg, thickness, nPts, x, y, … (Form, Firstrichtung, Neigung je Kante im JSON)
// stair: sx, sy, dx, dy, runLength, width, stepCount, z0, totalRise, run2Length, turn, cx, cy, radius,
// sweepDeg, centerColumn (Grundform im JSON)
// beam: z0, z1, nPts, x, y, …
// ---------------------------------------------------------------------------
#[cfg(feature = "web")]
@@ -1667,11 +1832,18 @@ pub(crate) fn encode(s: &Semantic) -> (serde_json::Value, Vec<f64>) {
for r in &s.roofs {
let mut nums = vec![r.eave_z, r.pitch_deg, r.thickness];
ring(&r.outline, &mut nums);
push("roof", &r.info, json!({ "shape": r.shape, "ridgeAxis": r.ridge_axis }), nums, &mut data);
push("roof", &r.info, json!({ "shape": r.shape, "ridgeAxis": r.ridge_axis, "edgePitch": r.edge_pitch, "custom": r.custom }), nums, &mut data);
}
for b in &s.beams {
let mut nums = vec![b.z0, b.z1];
ring(&b.outline, &mut nums);
push("beam", &b.info, json!({}), nums, &mut data);
}
for st in &s.stairs {
let nums = vec![st.start[0], st.start[1], st.dir[0], st.dir[1], st.run_length, st.width, st.step_count as f64, st.z0, st.total_rise];
push("stair", &st.info, json!({}), nums, &mut data);
let nums = vec![
st.start[0], st.start[1], st.dir[0], st.dir[1], st.run_length, st.width, st.step_count as f64, st.z0, st.total_rise, st.run2_length, st.turn, st.center[0], st.center[1], st.radius, st.sweep_deg, st.center_column,
];
push("stair", &st.info, json!({ "shape": st.shape }), nums, &mut data);
}
let storeys: Vec<_> = s.storeys.iter().map(|st| json!({ "globalId": st.global_id, "name": st.name, "elevation": st.elevation })).collect();
// Nicht endliche Zahlen gäbe es nur bei Unsinn; JSON/JS-Seite verwirft sie.
@@ -2230,6 +2402,25 @@ ENDSEC;\nEND-ISO-10303-21;\n"
assert_eq!(apex_left, w.bulge > 0.0);
assert!(r.products.is_empty());
// Dieselbe Bogenwand mit Öffnung (Kasten 1.0 entlang der Tangente bei 45°, 0.6 tief, Brüstung 0.9,
// 1.2 hoch): Lage nach Bogenlänge auf der Achse, Laibungen bei 45° ± asin(0.5/5).
let (c, s45) = (0.5f64.sqrt(), 0.5f64.sqrt());
let at = (5.0 * c + 0.5 * s45, 5.0 * s45 - 0.5 * c, 0.9);
let hole = rect_product(500, "IFCOPENINGELEMENT", at, (-s45, c), (1.0, 0.6), 1.2, "");
let arc = brep_product(100, "IFCWALL", &prism_faces(&ring, 0.0, |_, _| 2.5), "$");
let (r, s) = sem(&file(METRE, &format!("{arc}{hole}#509=IFCRELVOIDSELEMENT('v',$,$,$,#100,#500);")));
assert_eq!((s.walls.len(), s.openings.len()), (1, 1), "{:?}", s.kept_reasons);
let o = &s.openings[0];
let half = (0.5f64 / 5.0).asin();
assert_eq!(o.kind, OpeningKind::Hole);
assert!((o.position - 5.0 * (std::f64::consts::FRAC_PI_4 - half)).abs() < 1e-6 && (o.width - 10.0 * half).abs() < 1e-6, "{o:?}");
assert!(close(o.sill, 0.9) && close(o.height, 1.2), "{o:?}");
assert!(r.products.is_empty(), "{:?}", r.products.iter().map(|p| &p.class).collect::<Vec<_>>());
// Nische (nicht durch die ganze Dicke): Wand bleibt Mesh.
let niche = rect_product(500, "IFCOPENINGELEMENT", (at.0 - 0.2 * c, at.1 - 0.2 * s45, 0.9), (-s45, c), (1.0, 0.2), 1.2, "");
let (_, s) = sem(&file(METRE, &format!("{arc}{niche}#509=IFCRELVOIDSELEMENT('v',$,$,$,#100,#500);")));
assert_eq!(s.kept_reasons.get("IfcWall").and_then(|m| m.get("opening")), Some(&1), "{:?}", s.kept_reasons);
// Runde Öffnung (Durchmesser 1, Mitte auf 1.5 m) in einer geraden Wand.
let wall = rect_product(200, "IFCWALL", (0.0, 0.0, 0.0), (1.0, 0.0), (4.0, 0.3), 2.5, "");
let round = "#501=IFCCARTESIANPOINT((2.,0.4,1.5));#502=IFCDIRECTION((0.,-1.,0.));#503=IFCAXIS2PLACEMENT3D(#501,#502,#12);\
@@ -2269,6 +2460,26 @@ ENDSEC;\nEND-ISO-10303-21;\n"
assert!(r.products.is_empty(), "{:?}", r.products.iter().map(|p| &p.class).collect::<Vec<_>>());
}
#[test]
fn horizontal_beam_becomes_prism_sloped_stays_mesh() {
// Waagrechter Träger 4 × 0.2, 0.4 hoch auf 2.6 m, um 30° gedreht.
let (s, c) = 30f64.to_radians().sin_cos();
let beam = rect_product(100, "IFCBEAM", (1.0, 2.0, 2.6), (c, s), (4.0, 0.2), 0.4, "");
let (r, sm) = sem(&file(METRE, &beam));
assert_eq!(sm.beams.len(), 1, "{:?}", sm.kept_reasons);
let b = &sm.beams[0];
assert!(close(b.z0, 2.6) && close(b.z1, 3.0) && close(area2(&b.outline).abs(), 0.8), "{b:?}");
assert!(b.outline.iter().any(|p| close2(*p, [1.0 - 0.1 * -s, 2.0 - 0.1 * c])), "{b:?}");
assert!(r.products.is_empty());
// Schräger Träger (Sparren): bleibt Mesh.
let mut faces = Vec::new();
let ring = [[0.0, 0.0], [4.0, 0.0], [4.0, 0.2], [0.0, 0.2]];
faces.extend(prism_faces(&ring, 0.0, |x, _| 0.3 + 0.5 * x).into_iter().map(|f| f.into_iter().map(|p| if p[2] == 0.0 { [p[0], p[1], 0.5 * p[0]] } else { p }).collect()));
let (_, sm) = sem(&file(METRE, &brep_product(200, "IFCBEAM", &faces, "$")));
assert!(sm.beams.is_empty());
assert_eq!(sm.kept.get("IfcBeam"), Some(&1), "{:?}", sm.kept_reasons);
}
#[test]
fn map_conversion_is_read() {
let geo = "#700=IFCPROJECTEDCRS('EPSG:2056',$,$,$,$,$,#701);#701=IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.);\
@@ -2323,11 +2534,22 @@ ENDSEC;\nEND-ISO-10303-21;\n"
*meshes.entry(p.class.as_str()).or_insert(0) += 1;
}
eprintln!(
"== {} ({}, {:.1}s{})\n Geschosse {} · Wände {} · Öffnungen {} · Decken {} · Stützen {} · Räume {} · Dächer {} · Treppen {}\n als Mesh behalten (Grund): {:?}\n Meshes je Klasse: {:?}",
"== {} ({}, {:.1}s{})\n Geschosse {} · Wände {} · Öffnungen {} · Decken {} · Stützen {} · Räume {} · Dächer {} · Treppen {} · Träger {}\n als Mesh behalten (Grund): {:?}\n Meshes je Klasse: {:?}",
f.file_name().unwrap().to_string_lossy(), r.schema, t.elapsed().as_secs_f64(), if r.truncated { ", abgebrochen" } else { "" },
s.storeys.len(), s.walls.len(), s.openings.len(), s.slabs.len(), s.columns.len(), s.spaces.len(), s.roofs.len(), s.stairs.len(),
s.storeys.len(), s.walls.len(), s.openings.len(), s.slabs.len(), s.columns.len(), s.spaces.len(), s.roofs.len(), s.stairs.len(), s.beams.len(),
s.kept_reasons, meshes
);
let mut forms: BTreeMap<String, usize> = BTreeMap::new();
for r in &s.roofs {
*forms.entry(format!("Dach {}{}", r.shape, if r.custom { " je Kante" } else { "" })).or_insert(0) += 1;
if r.custom && std::env::var("DOSSIER_IFC_DEBUG").is_ok() {
eprintln!(" Dach je Kante {:?} {:.1}° Traufe {:.2} Umriss {:?} Kanten {:?}", r.info.name, r.pitch_deg, r.eave_z, r.outline, r.edge_pitch);
}
}
for st in &s.stairs {
*forms.entry(format!("Treppe {}", st.shape)).or_insert(0) += 1;
}
eprintln!(" Formen: {forms:?}");
}
}
}
+614 -73
View File
@@ -4,12 +4,17 @@
//
// Eigener Code.
// - Dach: Dachflächen = nach oben zeigende Dreiecke, nach Ebene gruppiert (je Normale die oberste;
// Schicht-Körper übereinander zählen einmal). Grundriss = achsparalleles Rechteck, ganz bedeckt;
// Form nach Zahl und Richtung der Flächen: 1 waagrecht = Flach, 1 geneigt = Pult (steigt nach +x/+y,
// wie das Dossier-Pultdach), 2 gegenläufig = Sattel, 4 = Walm; alle gleich geneigt. Jeder Punkt
// der Dachflächen muss auf der Dossier-Dachfläche liegen (±3 cm), sonst kein Dach.
// Schicht-Körper übereinander zählen einmal). Grundriss = kleinstes umschliessendes Rechteck (auch
// gedreht), ganz bedeckt; alle Flächen gleich geneigt, je Fläche eine Traufkante des Rechtecks.
// Achsparallel die Dossier-Standardformen (1 waagrecht = Flach, Pult steigend nach +x/+y, Sattel,
// Walm); Flach und Walm auch gedreht (folgen dem Umriss); sonst (gedreht, Pult fallend nach +x/+y,
// zwei Flächen über Eck …) Satteldach mit Neigung je Kante (`edgePitchDeg`, Giebel ohne Traufe). Jeder
// Punkt der Dachflächen muss auf der Dossier-Dachfläche liegen (±3 cm), sonst kein Dach.
// - Treppe: gerader Lauf — Trittflächen (waagrechte Oberseiten) in gleichen Höhenschritten, deren
// Vorderkanten linear entlang der Laufrichtung fortschreiten.
// Vorderkanten linear entlang der Laufrichtung fortschreiten. (6.11.) Wendel — Tritt-Schwerpunkte auf
// einem Kreis in gleichen Winkelschritten, jeder Tritt über die ganze Breite, Spindel aus senkrechten
// Flächen ringsum im Auge. L — zwei rechtwinklige Läufe gleicher Breite, quadratisches Podest an der
// Ecke (wie Dossier); andere Podesttreppen (U, mehrere Podeste) → Grund `stairTurn`.
// - Bogenwand: senkrechtes Prisma, Umriss auf zwei konzentrischen Kreisen (Ringausschnitt).
//
// Unsinn ergibt `Err(Grund)`, nie Panic.
@@ -78,45 +83,93 @@ fn planes(tris: &[&([V3; 3], V3, f64)]) -> Vec<Plane> {
out
}
/// Erkanntes Dach (Dossier-Parameter, Überstand 0: der Umriss ist schon die Traufe).
/// Erkanntes Dach (Dossier-Parameter, Überstand 0: der Umriss ist schon die Traufe). Grundriss = Rechteck im
/// Rahmen (`d`, links von `d`), auch gedreht; je Rechteckkante Traufe (geneigt) oder Giebel.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct RoofFit {
/// x0, y0, x1, y1.
pub bbox: [f64; 4],
/// Richtung der Rechteck-Kante 0 (Einheitsvektor); quer dazu `[-d[1], d[0]]`.
pub d: V2,
/// u0, u1, v0, v1 im Rahmen.
pub rect: [f64; 4],
/// Traufkanten: 0 = v0 (steigt nach +v), 1 = u1 (nach −u), 2 = v1 (nach −v), 3 = u0 (nach +u).
pub eaves: [bool; 4],
/// Dossier-Dachform: "flach", "pult", "sattel", "walm".
pub shape: &'static str,
pub pitch_deg: f64,
pub ridge_axis: &'static str,
/// Neigung je Umrisskante (`Roof.edgePitchDeg`, `None` = Giebel), wenn die Standardform nicht passt
/// (gedreht, Pult fallend nach +x/+y …); Form dann "sattel".
pub edge_pitch: Option<[Option<f64>; 4]>,
pub eave_z: f64,
/// Dicke senkrecht zur Dachfläche.
pub thickness: f64,
}
impl RoofFit {
/// Höhe der Dach-Oberseite im Grundrisspunkt (Dossier-Dachfläche, ohne Grenze auf den Umriss).
/// Umriss (Traufe) gegen den Uhrzeigersinn, Kante i = Punkt i → i+1 wie [`RoofFit::eaves`].
pub fn outline(&self) -> [V2; 4] {
let [u0, u1, v0, v1] = self.rect;
let (d, n) = (self.d, [-self.d[1], self.d[0]]);
let at = |u: f64, v: f64| [d[0] * u + n[0] * v, d[1] * u + n[1] * v];
[at(u0, v0), at(u1, v0), at(u1, v1), at(u0, v1)]
}
fn local(&self, x: f64, y: f64) -> (f64, f64) {
(x * self.d[0] + y * self.d[1], -x * self.d[1] + y * self.d[0])
}
/// Höhe der Dach-Oberseite im Grundrisspunkt (Dossier-Dachfläche, ohne Grenze auf den Umriss): je
/// Traufkante steigt eine Ebene, das Dach ist die unterste (konvexer Umriss, gleiche Neigung).
pub fn top_at(&self, x: f64, y: f64) -> f64 {
let [x0, y0, x1, y1] = self.bbox;
// Im Kanon läuft der First entlang u; v quer dazu.
let (u, v, u0, u1, v0, v1) = if self.ridge_axis == "x" { (x, y, x0, x1, y0, y1) } else { (y, x, y0, y1, x0, x1) };
let tan = (self.pitch_deg.to_radians()).tan();
let rise = match self.shape {
"pult" => v - v0,
"sattel" => (v - v0).min(v1 - v),
"walm" => (v - v0).min(v1 - v).min(u - u0).min(u1 - u),
_ => 0.0,
};
self.eave_z + rise * tan
let (u, v) = self.local(x, y);
let [u0, u1, v0, v1] = self.rect;
let dist = [v - v0, u1 - u, v1 - v, u - u0];
let rise = (0..4).filter(|&i| self.eaves[i]).map(|i| dist[i]).fold(f64::INFINITY, f64::min);
let rise = if rise.is_finite() { rise } else { 0.0 };
self.eave_z + rise * self.pitch_deg.to_radians().tan()
}
/// Dach-Unterkante im Grundrisspunkt; `None` ausserhalb.
pub fn underside_at(&self, x: f64, y: f64) -> Option<f64> {
let [x0, y0, x1, y1] = self.bbox;
if !(x >= x0 - 1e-6 && x <= x1 + 1e-6 && y >= y0 - 1e-6 && y <= y1 + 1e-6) {
let (u, v) = self.local(x, y);
let [u0, u1, v0, v1] = self.rect;
if !(u >= u0 - 1e-6 && u <= u1 + 1e-6 && v >= v0 - 1e-6 && v <= v1 + 1e-6) {
return None;
}
Some(self.top_at(x, y) - self.thickness / self.pitch_deg.to_radians().cos().max(0.05))
}
}
/// Tonnendach aus ebenen Streifen: mindestens vier verschieden geneigte obere Flächen, alle parallel zu
/// einer waagrechten Achse (Zylinder-Facetten).
pub(crate) fn is_barrel(meshes: &[Mesh]) -> bool {
let tris: Vec<_> = meshes.iter().flat_map(triangles).collect();
let mut normals: Vec<(V3, f64)> = Vec::new();
for (_, n, a) in tris.iter().filter(|t| t.1[2] > 0.08) {
match normals.iter_mut().find(|q| dot3(q.0, *n) > 0.9999) {
Some(q) => q.1 += a,
None => normals.push((*n, *a)),
}
if normals.len() > 200 {
return false;
}
}
let total: f64 = normals.iter().map(|q| q.1).sum();
normals.retain(|q| q.1 >= 0.01 * total);
if normals.len() < 4 {
return false;
}
let n1 = normals.iter().max_by(|a, b| a.1.total_cmp(&b.1)).map(|q| q.0).unwrap_or([0.0, 0.0, 1.0]);
let Some(n2) = normals.iter().map(|q| q.0).find(|n| dot3(*n, n1) < 0.9999) else { return false };
let c = cross3(n1, n2);
let l = c[0].hypot(c[1]);
if !(l > 1e-6 && c[2].abs() < 0.01 * l) {
return false;
}
let a = [c[0] / l, c[1] / l, 0.0];
normals.iter().all(|q| dot3(q.0, a).abs() < 0.01)
}
/// Dach aus den Körpern seiner Teile.
pub(crate) fn fit_roof(meshes: &[Mesh]) -> Result<RoofFit, &'static str> {
let tris: Vec<_> = meshes.iter().flat_map(triangles).collect();
@@ -144,21 +197,10 @@ pub(crate) fn fit_roof(meshes: &[Mesh]) -> Result<RoofFit, &'static str> {
#[cfg(test)]
if std::env::var("DOSSIER_IFC_DEBUG").is_ok() {
let pr: f64 = top.iter().map(|p| p.area * p.n[2]).sum();
let (mut b0, mut b1) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
for q in top.iter().flat_map(|p| p.pts.iter()) {
for k in 0..3 {
b0[k] = b0[k].min(q[k]);
b1[k] = b1[k].max(q[k]);
}
}
eprintln!(
"Dach: {} Flächen oben (alle {}), proj {pr:.2} bbox {:.2}×{:.2} z {:.2}..{:.2}, Normalen {:?}",
"Dach: {} Flächen oben (alle {}), proj {pr:.2}, Normalen {:?}",
top.len(),
top_all.len(),
b1[0] - b0[0],
b1[1] - b0[1],
b0[2],
b1[2],
top.iter().map(|p| ([p.n[0] as f32, p.n[1] as f32, p.n[2] as f32], p.area as f32)).collect::<Vec<_>>()
);
}
@@ -166,17 +208,13 @@ pub(crate) fn fit_roof(meshes: &[Mesh]) -> Result<RoofFit, &'static str> {
return Err(R_ROOF_FORM);
}
let pts: Vec<V3> = top.iter().flat_map(|p| p.pts.iter().copied()).collect();
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
let mut eave_z = f64::INFINITY;
for q in &pts {
x0 = x0.min(q[0]);
y0 = y0.min(q[1]);
x1 = x1.max(q[0]);
y1 = y1.max(q[1]);
eave_z = eave_z.min(q[2]);
}
let box_area = (x1 - x0) * (y1 - y0);
// Projizierte Fläche der Dachflächen = Rechteck (achsparallel, ganz bedeckt, keine Doppelung).
let plan: Vec<V2> = pts.iter().map(|q| [q[0], q[1]]).collect();
// Kleinstes umschliessendes Rechteck (auch gedreht); achsparallel bleibt achsparallel.
let (d, u0, u1, v0, v1) = crate::ifc_semantic::min_area_rect(&plan).ok_or(R_ROOF_FORM)?;
let n = [-d[1], d[0]];
let eave_z = pts.iter().map(|q| q[2]).fold(f64::INFINITY, f64::min);
let box_area = (u1 - u0) * (v1 - v0);
// Projizierte Fläche der Dachflächen = Rechteck (ganz bedeckt, keine Doppelung).
let projected: f64 = top.iter().map(|p| p.area * p.n[2]).sum();
if !(box_area > 0.01 && (projected - box_area).abs() <= 0.03 * box_area) {
return Err(R_ROOF_FORM);
@@ -186,41 +224,75 @@ pub(crate) fn fit_roof(meshes: &[Mesh]) -> Result<RoofFit, &'static str> {
if top.iter().any(|p| (pitch(p) - pitch_deg).abs() > 0.3) {
return Err(R_ROOF_FORM);
}
// Steigrichtung je Fläche (gegen die waagrechte Normale): 0 = +x, 1 = −x, 2 = +y, 3 = −y.
// Traufkante je Fläche aus der Steigrichtung (gegen die waagrechte Normale) im Rahmen.
let flat = pitch_deg < 0.3;
let mut dirs = Vec::new();
if !flat {
let mut eaves = [false; 4];
if flat {
if top.len() != 1 {
return Err(R_ROOF_FORM);
}
} else {
for p in &top {
let (hx, hy) = (-p.n[0], -p.n[1]);
let l = hx.hypot(hy);
let (hx, hy) = (hx / l, hy / l);
let k = if hx > 0.9995 {
let (hu, hv) = ((hx * d[0] + hy * d[1]) / l, (hx * n[0] + hy * n[1]) / l);
let k = if hv > 0.9995 {
0
} else if hx < -0.9995 {
} else if hu < -0.9995 {
1
} else if hy > 0.9995 {
} else if hv < -0.9995 {
2
} else if hy < -0.9995 {
} else if hu > 0.9995 {
3
} else {
return Err(R_ROOF_FORM);
};
if dirs.contains(&k) {
if eaves[k] {
return Err(R_ROOF_FORM);
}
dirs.push(k);
eaves[k] = true;
}
dirs.sort_unstable();
}
let longer_x = x1 - x0 >= y1 - y0;
let (shape, ridge_axis, pitch_deg) = match (flat, dirs.as_slice()) {
(true, _) if top.len() == 1 => ("flach", if longer_x { "x" } else { "y" }, 0.0),
(false, [2]) => ("pult", "x", pitch_deg),
(false, [0]) => ("pult", "y", pitch_deg),
(false, [2, 3]) => ("sattel", "x", pitch_deg),
(false, [0, 1]) => ("sattel", "y", pitch_deg),
(false, [0, 1, 2, 3]) => ("walm", if longer_x { "x" } else { "y" }, pitch_deg),
_ => return Err(R_ROOF_FORM),
// Dossier-Form: achsparallel die Standardformen (Pult steigt nur nach +x/+y), Walm und Flach auch
// gedreht (folgen dem Umriss); sonst Satteldach mit Neigung je Kante (Giebel, wo keine Traufe ist).
let aligned = d[0].abs() > 1.0 - 1e-9 || d[1].abs() > 1.0 - 1e-9;
// Welt-Steigrichtung der Kante k: 0 = +n, 1 = −d, 2 = −n, 3 = +d; als „+x“/„+y“ …
let world = |k: usize| -> V2 {
match k {
0 => n,
1 => [-d[0], -d[1]],
2 => [-n[0], -n[1]],
_ => d,
}
};
let rises: Vec<V2> = (0..4).filter(|&k| eaves[k]).map(world).collect();
let is = |v: &V2, x: f64, y: f64| (v[0] - x).abs() < 1e-6 && (v[1] - y).abs() < 1e-6;
let has = |x: f64, y: f64| rises.iter().any(|v| is(v, x, y));
let longer_x = (d[0].abs() > 0.5) == (u1 - u0 >= v1 - v0);
let count = rises.len();
let standard: Option<(&'static str, &'static str)> = if flat {
Some(("flach", if aligned && longer_x { "x" } else { "y" }))
} else if count == 4 {
Some(("walm", if !aligned || longer_x { "x" } else { "y" }))
} else if !aligned {
None
} else if count == 1 && has(0.0, 1.0) {
Some(("pult", "x"))
} else if count == 1 && has(1.0, 0.0) {
Some(("pult", "y"))
} else if count == 2 && has(0.0, 1.0) && has(0.0, -1.0) {
Some(("sattel", "x"))
} else if count == 2 && has(1.0, 0.0) && has(-1.0, 0.0) {
Some(("sattel", "y"))
} else {
None
};
let (shape, ridge_axis, edge_pitch) = match standard {
Some((s, a)) => (s, a, None),
None => {
let axis = if (d[0].abs() >= d[1].abs()) == (u1 - u0 >= v1 - v0) { "x" } else { "y" };
("sattel", axis, Some([0, 1, 2, 3].map(|k| eaves[k].then_some(pitch_deg))))
}
};
// Dicke: Abstand zur untersten Gegenfläche der grössten Dachfläche.
let main = top.iter().max_by(|a, b| a.area.total_cmp(&b.area)).ok_or(R_ROOF_FORM)?;
@@ -228,7 +300,7 @@ pub(crate) fn fit_roof(meshes: &[Mesh]) -> Result<RoofFit, &'static str> {
if !(thickness > 0.01 && thickness <= 2.0) {
return Err(R_ROOF_FORM);
}
let fit = RoofFit { bbox: [x0, y0, x1, y1], shape, pitch_deg, ridge_axis, eave_z, thickness };
let fit = RoofFit { d, rect: [u0, u1, v0, v1], eaves, shape, pitch_deg: if flat { 0.0 } else { pitch_deg }, ridge_axis, edge_pitch, eave_z, thickness };
if pts.iter().any(|q| (q[2] - fit.top_at(q[0], q[1])).abs() > 0.03) {
return Err(R_ROOF_FORM);
}
@@ -368,6 +440,323 @@ pub(crate) fn fit_stair(meshes: &[Mesh]) -> Result<StairFit, &'static str> {
Ok(StairFit { start, dir, width, going, riser, treads: k, z0, top_is_exit })
}
/// Trittfläche einer Höhe: waagrechte Oberseiten (Belag über Rohbau zusammengefasst, die obere zählt).
#[derive(Clone, Debug)]
struct Level {
z: f64,
area: f64,
/// Flächengewichteter Schwerpunkt im Grundriss.
c: V2,
pts: Vec<V2>,
}
/// Trittflächen aller Höhen (aufsteigend) und die Höhenausdehnung des Körpers.
fn stair_levels(tris: &[([V3; 3], V3, f64)]) -> (Vec<Level>, f64, f64) {
let (mut z0, mut z1) = (f64::INFINITY, f64::NEG_INFINITY);
for t in tris {
for p in &t.0 {
z0 = z0.min(p[2]);
z1 = z1.max(p[2]);
}
}
let mut levels: Vec<Level> = Vec::new();
for (pts, _, a) in tris.iter().filter(|t| t.1[2] > 0.999) {
let z = (pts[0][2] + pts[1][2] + pts[2][2]) / 3.0;
let c = [(pts[0][0] + pts[1][0] + pts[2][0]) / 3.0, (pts[0][1] + pts[1][1] + pts[2][1]) / 3.0];
let l = match levels.iter_mut().find(|l| (l.z - z).abs() <= 0.005) {
Some(l) => l,
None => {
if levels.len() >= 400 {
return (Vec::new(), z0, z1);
}
levels.push(Level { z, area: 0.0, c: [0.0, 0.0], pts: Vec::new() });
levels.last_mut().unwrap_or_else(|| unreachable!())
}
};
l.c = [l.c[0] + c[0] * a, l.c[1] + c[1] * a];
l.area += a;
l.pts.extend(pts.iter().map(|p| [p[0], p[1]]));
}
for l in &mut levels {
l.c = [l.c[0] / l.area, l.c[1] / l.area];
}
levels.retain(|l| l.z > z0 + 0.02 && l.area > 1e-4);
levels.sort_by(|a, b| a.z.total_cmp(&b.z));
let mut merged: Vec<Level> = Vec::new();
for l in levels {
match merged.last_mut() {
// Belag: wenige cm über dem Rohbau-Tritt, fast an derselben Stelle.
Some(m) if l.z - m.z < 0.08 && (l.c[0] - m.c[0]).hypot(l.c[1] - m.c[1]) < 0.08 => *m = l,
_ => merged.push(l),
}
}
// Kleine Flächen (Handlauf, Wangenkopf, Nasen) zählen nicht als Tritt.
let mut areas: Vec<f64> = merged.iter().map(|l| l.area).collect();
areas.sort_by(f64::total_cmp);
let median = areas.get(areas.len() / 2).copied().unwrap_or(0.0);
merged.retain(|l| l.area >= 0.3 * median);
(merged, z0, z1)
}
/// Gleichmässige Steigung über alle Höhen (Podest zählt als Tritt); `None` sonst.
fn uniform_riser(levels: &[Level]) -> Option<f64> {
let k = levels.len();
if k < 3 {
return None;
}
let h = (levels[k - 1].z - levels[0].z) / (k - 1) as f64;
((0.1..=0.4).contains(&h) && levels.iter().enumerate().all(|(i, l)| (l.z - (levels[0].z + h * i as f64)).abs() <= 0.012)).then_some(h)
}
/// Wendeltreppe: Zentrum, Lauflinie, Drehsinn.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct SpiralFit {
pub center: V2,
/// Radius der Lauflinie (Mitte der Laufbreite).
pub radius: f64,
pub width: f64,
/// Winkel (rad) der Antrittskante (Anfang des ersten Tritts).
pub a0: f64,
/// Winkel je Stufe (rad), + = gegen den Uhrzeigersinn aufwärts.
pub step: f64,
pub riser: f64,
pub treads: usize,
pub z0: f64,
pub top_is_exit: bool,
/// Spindel (Radius), wenn der Körper eine senkrechte Mittelsäule hat.
pub column: Option<f64>,
}
/// Kreis durch Punkte (algebraisch, Kåsa): Mittelpunkt und Radius.
fn fit_circle(p: &[V2]) -> Option<(V2, f64)> {
let n = p.len() as f64;
if n < 3.0 {
return None;
}
// Schwerpunkt abziehen (Kondition).
let (mx, my) = p.iter().fold((0.0, 0.0), |a, q| (a.0 + q[0] / n, a.1 + q[1] / n));
let (mut suu, mut svv, mut suv, mut suuu, mut svvv, mut suvv, mut svuu) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
for q in p {
let (u, v) = (q[0] - mx, q[1] - my);
suu += u * u;
svv += v * v;
suv += u * v;
suuu += u * u * u;
svvv += v * v * v;
suvv += u * v * v;
svuu += v * u * u;
}
let det = suu * svv - suv * suv;
if !(det.abs() > 1e-12) {
return None;
}
let (b1, b2) = ((suuu + suvv) / 2.0, (svvv + svuu) / 2.0);
let uc = (b1 * svv - b2 * suv) / det;
let vc = (suu * b2 - suv * b1) / det;
let r = (uc * uc + vc * vc + (suu + svv) / n).sqrt();
(r.is_finite() && uc.is_finite() && vc.is_finite()).then_some(([mx + uc, my + vc], r))
}
/// Wendeltreppe aus den Körpern ihrer Teile: keilförmige Tritte um ein Zentrum, gleiche Steigung und
/// gleicher Winkel je Stufe, jeder Tritt über die ganze Laufbreite.
pub(crate) fn fit_spiral(meshes: &[Mesh]) -> Result<SpiralFit, &'static str> {
let tris: Vec<_> = meshes.iter().flat_map(triangles).collect();
let (mut levels, z_lo, z_hi) = stair_levels(&tris);
// Oberste Fläche ausser Takt (Spindelkopf, Austrittspodest): ohne sie versuchen.
if uniform_riser(&levels).is_none() && levels.len() > 4 {
levels.pop();
}
let riser = uniform_riser(&levels).ok_or(R_STAIR_FORM)?;
let k = levels.len();
if k < 4 {
return Err(R_STAIR_FORM);
}
let cs: Vec<V2> = levels.iter().map(|l| l.c).collect();
let (center, rc) = fit_circle(&cs).ok_or(R_STAIR_FORM)?;
if !(0.2..=6.0).contains(&rc) || cs.iter().any(|c| ((c[0] - center[0]).hypot(c[1] - center[1]) - rc).abs() > 0.03) {
return Err(R_STAIR_FORM);
}
// Winkel der Schwerpunkte fortlaufend (ohne Sprung bei ±π), linear in der Stufennummer.
let mut ang: Vec<f64> = Vec::with_capacity(k);
for c in &cs {
let a = (c[1] - center[1]).atan2(c[0] - center[0]);
let a = match ang.last() {
Some(&p) => p + (a - p + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI,
None => a,
};
ang.push(a);
}
let step = (ang[k - 1] - ang[0]) / (k - 1) as f64;
if !((3f64.to_radians()..=45f64.to_radians()).contains(&step.abs())) || ang.iter().enumerate().any(|(i, a)| (a - (ang[0] + step * i as f64)).abs() > 1.5f64.to_radians()) {
return Err(R_STAIR_FORM);
}
// Laufbreite: jeder Tritt reicht vom Innen- zum Aussenradius.
let radii = |l: &Level| l.pts.iter().map(|p| (p[0] - center[0]).hypot(p[1] - center[1])).fold((f64::INFINITY, 0.0f64), |(lo, hi), r| (lo.min(r), hi.max(r)));
let spans: Vec<(f64, f64)> = levels.iter().map(radii).collect();
let r_in = spans.iter().map(|s| s.0).fold(f64::INFINITY, f64::min);
let r_out = spans.iter().map(|s| s.1).fold(0.0, f64::max);
if spans.iter().any(|s| s.0 > r_in + 0.03 || s.1 < r_out - 0.03) || !(r_out - r_in >= 0.4 && r_out <= 6.0) {
return Err(R_STAIR_FORM);
}
// Spindel: senkrechte Flächen innerhalb des Innenradius, ringsum (12 Sektoren) über den grössten
// Teil der Höhe.
let mut col_r = 0.0f64;
let mut bins = [(f64::INFINITY, f64::NEG_INFINITY); 12];
for (pts, n, _) in &tris {
if n[2].abs() > 0.05 {
continue;
}
let rmax = pts.iter().map(|p| (p[0] - center[0]).hypot(p[1] - center[1])).fold(0.0f64, f64::max);
if rmax <= r_in + 0.01 {
col_r = col_r.max(rmax);
for p in pts {
let a = (p[1] - center[1]).atan2(p[0] - center[0]).rem_euclid(std::f64::consts::TAU);
let b = &mut bins[((a / std::f64::consts::TAU * 12.0) as usize).min(11)];
*b = (b.0.min(p[2]), b.1.max(p[2]));
}
}
}
let around = bins.iter().all(|b| b.1 - b.0 >= 0.5 * (z_hi - z_lo));
let column = (col_r > 0.01 && around).then_some(col_r);
// Dossier-Wendel: Innenradius ≥ 0.1 (Lauflinie ≥ halbe Breite + 0.1).
let r_in = r_in.max(column.unwrap_or(0.0)).max(0.1);
let top_is_exit = (z_hi - levels[k - 1].z).abs() <= 0.03;
Ok(SpiralFit { center, radius: (r_in + r_out) / 2.0, width: r_out - r_in, a0: ang[0] - step / 2.0, step, riser, treads: k, z0: levels[0].z - riser, top_is_exit, column })
}
/// Lauf einer Treppe aus seinen Tritten (mindestens zwei): Richtung aufwärts, Auftritt, Breite, Lage.
#[derive(Clone, Debug)]
struct Run {
dir: V2,
going: f64,
width: f64,
/// Vorderkante des ersten Tritts entlang `dir` (Skalar).
front: f64,
/// Mitte quer zur Laufrichtung (Skalar entlang `left(dir)`).
mid: f64,
}
fn run_of(levels: &[Level]) -> Option<Run> {
let k = levels.len();
if k < 2 {
return None;
}
let (a, b) = (levels[0].c, levels[k - 1].c);
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let l = dx.hypot(dy);
if !(l > 1e-6) {
return None;
}
let d = [dx / l, dy / l];
let n = [-d[1], d[0]];
let going = l / (k - 1) as f64;
if !(0.15..=0.45).contains(&going) {
return None;
}
let ext = |l: &Level, ax: V2| l.pts.iter().map(|p| p[0] * ax[0] + p[1] * ax[1]).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), u| (lo.min(u), hi.max(u)));
let fronts: Vec<f64> = levels.iter().map(|l| ext(l, d).0).collect();
let (mut v0, mut v1) = (f64::INFINITY, f64::NEG_INFINITY);
for l in levels {
let (lo, hi) = ext(l, n);
// Alle Tritte über dieselbe Breite.
if v0.is_finite() && ((lo - v0).abs() > 0.03 || (hi - v1).abs() > 0.03) {
return None;
}
v0 = v0.min(lo);
v1 = v1.max(hi);
}
if fronts.iter().enumerate().any(|(i, f)| (f - (fronts[0] + going * i as f64)).abs() > 0.03) || !(0.4..=6.0).contains(&(v1 - v0)) {
return None;
}
Some(Run { dir: d, going, width: v1 - v0, front: fronts[0], mid: (v0 + v1) / 2.0 })
}
/// L-Treppe (Dossier: zwei rechtwinklige Läufe gleicher Breite, quadratisches Podest an der Ecke).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LFit {
/// Mitte der Antrittskante.
pub start: V2,
pub dir: V2,
pub width: f64,
/// Tritte im ersten bzw. zweiten Lauf (ohne Podest).
pub n1: usize,
pub n2: usize,
pub going1: f64,
pub going2: f64,
pub riser: f64,
/// +1 = zweiter Lauf links, −1 = rechts.
pub turn: f64,
pub z0: f64,
pub top_is_exit: bool,
}
/// Grund: Podesttreppe mit Wende, die Dossier nicht abbildet (U, mehrere Podeste, Podest nicht an der Ecke).
pub(crate) const R_STAIR_TURN: &str = "stairTurn";
/// L-Treppe aus den Körpern ihrer Teile; eine Podesttreppe anderer Form gibt [`R_STAIR_TURN`].
pub(crate) fn fit_l_stair(meshes: &[Mesh]) -> Result<LFit, &'static str> {
let tris: Vec<_> = meshes.iter().flat_map(triangles).collect();
let (levels, _, z_hi) = stair_levels(&tris);
let k = levels.len();
if k < 4 {
return Err(R_STAIR_FORM);
}
let mut areas: Vec<f64> = levels.iter().map(|l| l.area).collect();
areas.sort_by(f64::total_cmp);
let median = areas[k / 2];
let landings: Vec<usize> = (0..k).filter(|&i| levels[i].area >= 2.0 * median).collect();
// Podest = grosse Fläche zwischen zwei Läufen (der oberste/unterste Tritt kann ein Austritt sein).
let inner: Vec<usize> = landings.iter().copied().filter(|&i| i > 0 && i + 1 < k).collect();
#[cfg(test)]
if std::env::var("DOSSIER_IFC_DEBUG").is_ok() {
eprintln!("L-Treppe: Ebenen {:?}, Podeste {landings:?}", levels.iter().map(|l| (l.z as f32, l.area as f32)).collect::<Vec<_>>());
}
if inner.is_empty() {
return Err(R_STAIR_FORM);
}
if inner.len() > 1 {
return Err(R_STAIR_TURN);
}
let li = inner[0];
let top = if landings.contains(&(k - 1)) && k - 1 > li + 1 { k - 1 } else { k };
let riser = uniform_riser(&levels[..top]).ok_or(R_STAIR_TURN)?;
let (Some(r1), Some(r2)) = (run_of(&levels[..li]), run_of(&levels[li + 1..top])) else { return Err(R_STAIR_TURN) };
let n1 = [-r1.dir[1], r1.dir[0]];
let cross = r1.dir[0] * r2.dir[1] - r1.dir[1] * r2.dir[0];
if (r1.dir[0] * r2.dir[0] + r1.dir[1] * r2.dir[1]).abs() > 0.02 || (r1.width - r2.width).abs() > 0.03 {
return Err(R_STAIR_TURN);
}
let w = (r1.width + r2.width) / 2.0;
let (g1, g2) = (r1.going, r2.going);
let n_1 = li;
let n_2 = top - li - 1;
// Dossier: Podest = Quadrat w × w am Ende des ersten Laufs (Länge n1·Auftritt), zweiter Lauf mittig daran.
let start = [r1.dir[0] * r1.front + n1[0] * r1.mid, r1.dir[1] * r1.front + n1[1] * r1.mid];
let run1 = n_1 as f64 * g1;
let corner = [start[0] + r1.dir[0] * (run1 + w / 2.0), start[1] + r1.dir[1] * (run1 + w / 2.0)];
let n2 = [-r2.dir[1], r2.dir[0]];
let dot = |a: V2, b: V2| a[0] * b[0] + a[1] * b[1];
if (dot(corner, n2) - r2.mid).abs() > 0.04 || (dot(corner, r2.dir) + w / 2.0 - r2.front).abs() > 0.04 {
return Err(R_STAIR_TURN);
}
let land = &levels[li];
let (mut u0, mut u1, mut v0, mut v1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
for p in &land.pts {
let (u, v) = (dot(*p, r1.dir), dot(*p, n1));
u0 = u0.min(u);
u1 = u1.max(u);
v0 = v0.min(v);
v1 = v1.max(v);
}
let ue = r1.front + run1;
if (u0 - ue).abs() > 0.05 || (u1 - ue - w).abs() > 0.05 || (v0 - (r1.mid - w / 2.0)).abs() > 0.05 || (v1 - (r1.mid + w / 2.0)).abs() > 0.05 {
return Err(R_STAIR_TURN);
}
// Ein Austrittspodest oben ist kein Tritt des zweiten Laufs: der Austritt kommt dazu.
let top_is_exit = top == k && (z_hi - levels[k - 1].z).abs() <= 0.03;
Ok(LFit { start, dir: r1.dir, width: w, n1: n_1, n2: n_2, going1: g1, going2: g2, riser, turn: cross.signum(), z0: levels[0].z - riser, top_is_exit })
}
/// Bogen einer Bogenwand: Achse (Mitte der Dicke) von `start` nach `end` gegen den Uhrzeigersinn um
/// `center`.
#[derive(Clone, Debug, PartialEq)]
@@ -477,20 +866,69 @@ mod tests {
let f = fit_roof(&[a.clone(), b]).unwrap();
assert_eq!((f.shape, f.ridge_axis), ("sattel", "x"));
assert!((f.pitch_deg - 30.0).abs() < 1e-6 && (f.eave_z - 3.0).abs() < 1e-9 && (f.thickness - 0.2).abs() < 1e-6, "{f:?}");
assert_eq!(f.bbox, [0.0, 0.0, 10.0, 8.0]);
assert_eq!(f.outline(), [[0.0, 0.0], [10.0, 0.0], [10.0, 8.0], [0.0, 8.0]]);
assert_eq!(f.edge_pitch, None);
assert!((f.top_at(5.0, 4.0) - (3.0 + 4.0 * tan)).abs() < 1e-9);
// Eine Platte allein: Pultdach steigt nach +y.
let p = fit_roof(&[a]).unwrap();
assert_eq!((p.shape, p.ridge_axis), ("pult", "x"));
// Fallend nach +y kann das Dossier-Pultdach nicht.
let p = fit_roof(&[a.clone()]).unwrap();
assert_eq!((p.shape, p.ridge_axis, p.edge_pitch), ("pult", "x", None));
// Fallend nach +y (Dossier-Pult steigt nur nach +x/+y): Satteldach mit Traufe an y = 8, sonst Giebel.
let c = plate(0.0, 10.0, 8.0, 4.0, 3.0, 3.0 + 4.0 * tan, 0.2);
assert_eq!(fit_roof(&[c]), Err(R_ROOF_FORM));
let f = fit_roof(&[c]).unwrap();
assert_eq!(f.shape, "sattel");
let ep = f.edge_pitch.unwrap();
let o = f.outline();
let eave = (0..4).find(|&i| ep[i].is_some()).unwrap();
assert_eq!(ep.iter().filter(|e| e.is_some()).count(), 1);
assert!((ep[eave].unwrap() - 30.0).abs() < 1e-6 && (o[eave][1] - 8.0).abs() < 1e-9 && (o[(eave + 1) % 4][1] - 8.0).abs() < 1e-9, "{f:?}");
// Ungleiche Neigung: kein Satteldach.
let a = plate(0.0, 10.0, 0.0, 4.0, 3.0, 3.0 + 4.0 * tan, 0.2);
let b = plate(0.0, 10.0, 8.0, 4.0, 3.0, 3.0 + 3.0 * tan, 0.2);
assert!(fit_roof(&[a, b]).is_err());
}
/// Netz um den Ursprung gedreht (Grundriss, Winkel in Grad).
fn rotated(mut m: Mesh, deg: f64) -> Mesh {
let (s, c) = deg.to_radians().sin_cos();
for p in m.positions.chunks_exact_mut(3) {
let (x, y) = (p[0], p[1]);
p[0] = c * x - s * y;
p[1] = s * x + c * y;
}
m
}
#[test]
fn rotated_saddle_and_hip_roof() {
// Satteldach wie oben, um 30° gedreht: Satteldach mit Neigung je Kante (Giebel an den Stirnseiten).
let tan = 30f64.to_radians().tan();
let a = rotated(plate(0.0, 10.0, 0.0, 4.0, 3.0, 3.0 + 4.0 * tan, 0.2), 30.0);
let b = rotated(plate(0.0, 10.0, 8.0, 4.0, 3.0, 3.0 + 4.0 * tan, 0.2), 30.0);
let f = fit_roof(&[a, b]).unwrap();
assert_eq!(f.shape, "sattel");
let ep = f.edge_pitch.unwrap();
let o = f.outline();
for i in 0..4 {
let (p, q) = (o[i], o[(i + 1) % 4]);
let long = ((q[0] - p[0]).hypot(q[1] - p[1]) - 10.0).abs() < 1e-6;
assert_eq!(ep[i].is_some(), long, "Kante {i}: {f:?}");
}
let (s, c) = 30f64.to_radians().sin_cos();
let ridge_mid = [5.0 * c - 4.0 * s, 5.0 * s + 4.0 * c];
assert!((f.top_at(ridge_mid[0], ridge_mid[1]) - (3.0 + 4.0 * tan)).abs() < 1e-6);
let area: f64 = (0..4).map(|i| o[i][0] * o[(i + 1) % 4][1] - o[(i + 1) % 4][0] * o[i][1]).sum::<f64>() / 2.0;
assert!((area - 80.0).abs() < 1e-6, "{area}");
// Gedrehtes Pultdach (eine Platte): Traufe an einer langen Kante, drei Giebel.
let p = fit_roof(&[rotated(plate(0.0, 10.0, 0.0, 4.0, 3.0, 3.0 + 4.0 * tan, 0.2), 30.0)]).unwrap();
assert_eq!((p.shape, p.edge_pitch.unwrap().iter().filter(|e| e.is_some()).count()), ("sattel", 1));
// Flachdach gedreht: bleibt Flachdach mit gedrehtem Umriss.
let mut m = Mesh::default();
quad(&mut m, [[0.0, 0.0, 3.3], [4.0, 0.0, 3.3], [4.0, 2.0, 3.3], [0.0, 2.0, 3.3]]);
quad(&mut m, [[0.0, 2.0, 3.0], [4.0, 2.0, 3.0], [4.0, 0.0, 3.0], [0.0, 0.0, 3.0]]);
let f = fit_roof(&[rotated(m, 20.0)]).unwrap();
assert_eq!((f.shape, f.edge_pitch), ("flach", None));
assert!((f.d[1] / f.d[0] - 20f64.to_radians().tan()).abs() < 1e-9, "{f:?}");
}
#[test]
fn flat_roof_and_capped_wall_volume() {
let mut m = Mesh::default();
@@ -500,7 +938,17 @@ mod tests {
assert_eq!((f.shape, f.ridge_axis, f.pitch_deg), ("flach", "x", 0.0));
assert!((f.thickness - 0.3).abs() < 1e-9);
// Giebelwand unter Satteldach (Traufe 3, 45°, Dicke 0.2 → Unterkante 3 − 0.2·√2 an der Traufe).
let r = RoofFit { bbox: [0.0, 0.0, 10.0, 8.0], shape: "sattel", pitch_deg: 45.0, ridge_axis: "x", eave_z: 3.0, thickness: 0.2 };
let r = RoofFit {
d: [1.0, 0.0],
rect: [0.0, 10.0, 0.0, 8.0],
eaves: [true, false, true, false],
shape: "sattel",
pitch_deg: 45.0,
ridge_axis: "x",
edge_pitch: None,
eave_z: 3.0,
thickness: 0.2,
};
let u = 3.0 - 0.2 * 2f64.sqrt();
// Wand in x = 0.1 entlang y, 0 … 8, bis 10 hoch: gekappt auf Dreieck + Rechteck.
let v = capped_volume([0.1, 0.0], [0.0, 1.0], 8.0, 0.2, 0.0, 10.0, &[r]);
@@ -526,6 +974,99 @@ mod tests {
assert!((s.width - 1.0).abs() < 1e-9);
}
/// Senkrechtes Prisma über dem konvexen Ring (gegen den Uhrzeigersinn) von z0 bis z1.
fn block(m: &mut Mesh, ring: &[V2], z0: f64, z1: f64) {
let b = m.positions.len() as u32 / 3;
let n = ring.len() as u32;
for z in [z0, z1] {
for p in ring {
m.positions.extend_from_slice(&[p[0], p[1], z]);
}
}
for i in 1..n - 1 {
m.indices.extend_from_slice(&[b, b + i + 1, b + i]);
m.indices.extend_from_slice(&[b + n, b + n + i, b + n + i + 1]);
}
for i in 0..n {
let j = (i + 1) % n;
m.indices.extend_from_slice(&[b + i, b + j, b + n + j, b + i, b + n + j, b + n + i]);
}
}
fn wedge(c: V2, r0: f64, r1: f64, a: f64, b: f64) -> Vec<V2> {
let mut ring = vec![[c[0] + r0 * a.cos(), c[1] + r0 * a.sin()]];
for k in 0..=4 {
let t = a + (b - a) * k as f64 / 4.0;
ring.push([c[0] + r1 * t.cos(), c[1] + r1 * t.sin()]);
}
ring.push([c[0] + r0 * b.cos(), c[1] + r0 * b.sin()]);
ring
}
#[test]
fn spiral_stair_with_center_column() {
// 12 Keile à 25° gegen den Uhrzeigersinn ab 10°, Radien 0.3 … 1.3 um (2, 3), Steigung 0.18; Spindel
// r = 0.3 bis 2.4 hoch. Der oberste Tritt (2.16) ist nicht die höchste Stelle → Austritt kommt dazu.
let c = [2.0, 3.0];
let mut m = Mesh::default();
for i in 0..12 {
let (a, b) = ((10.0 + 25.0 * i as f64).to_radians(), (10.0 + 25.0 * (i + 1) as f64).to_radians());
block(&mut m, &wedge(c, 0.3, 1.3, a, b), 0.18 * i as f64, 0.18 * (i + 1) as f64);
}
let col: Vec<V2> = (0..16).map(|k| std::f64::consts::TAU * k as f64 / 16.0).map(|t| [c[0] + 0.3 * t.cos(), c[1] + 0.3 * t.sin()]).collect();
block(&mut m, &col, 0.0, 2.4);
assert!(fit_stair(&[m.clone()]).is_err());
let s = fit_spiral(&[m]).unwrap();
assert!((s.center[0] - 2.0).abs() < 1e-3 && (s.center[1] - 3.0).abs() < 1e-3, "{s:?}");
assert!((s.step.to_degrees() - 25.0).abs() < 0.01 && (s.a0.to_degrees() - 10.0).abs() < 0.05, "{s:?}");
assert!((s.riser - 0.18).abs() < 1e-9 && s.treads == 12 && s.z0.abs() < 1e-9 && !s.top_is_exit);
assert!((s.radius - 0.8).abs() < 1e-3 && (s.width - 1.0).abs() < 1e-3, "{s:?}");
assert!((s.column.unwrap() - 0.3).abs() < 1e-3);
// Im Uhrzeigersinn, ohne Spindel.
let mut m = Mesh::default();
for i in 0..8 {
let (a, b) = ((-30.0 * i as f64).to_radians(), (-30.0 * (i + 1) as f64).to_radians());
block(&mut m, &wedge([0.0, 0.0], 0.15, 1.1, b, a), 0.0, 0.17 * (i + 1) as f64);
}
let s = fit_spiral(&[m]).unwrap();
assert!((s.step.to_degrees() + 30.0).abs() < 0.01 && s.a0.abs() < 1e-3 && s.column.is_none() && s.top_is_exit, "{s:?}");
}
#[test]
fn l_stair_and_u_stair() {
// L: 4 Tritte (0.28 × 1.0, Steigung 0.17) in +x ab x = 1, Mitte y = 2; Podest 1 × 1 auf 5·0.17;
// 4 Tritte links herum (+y) ab y = 2.5, Mitte x = 2.62.
let mut m = Mesh::default();
let h = 0.17;
for i in 0..4 {
let (x0, x1) = (1.0 + 0.28 * i as f64, 1.0 + 0.28 * (i + 1) as f64);
block(&mut m, &[[x0, 1.5], [x1, 1.5], [x1, 2.5], [x0, 2.5]], 0.0, h * (i + 1) as f64);
}
block(&mut m, &[[2.12, 1.5], [3.12, 1.5], [3.12, 2.5], [2.12, 2.5]], 0.0, 5.0 * h);
for i in 0..4 {
let (y0, y1) = (2.5 + 0.28 * i as f64, 2.5 + 0.28 * (i + 1) as f64);
block(&mut m, &[[2.12, y0], [3.12, y0], [3.12, y1], [2.12, y1]], 0.0, h * (6 + i) as f64);
}
assert!(fit_stair(&[m.clone()]).is_err() && fit_spiral(&[m.clone()]).is_err());
let l = fit_l_stair(&[m]).unwrap();
assert!((l.start[0] - 1.0).abs() < 1e-9 && (l.start[1] - 2.0).abs() < 1e-9 && (l.dir[0] - 1.0).abs() < 1e-9, "{l:?}");
assert!((l.width - 1.0).abs() < 1e-9 && (l.going1 - 0.28).abs() < 1e-9 && (l.going2 - 0.28).abs() < 1e-9);
assert_eq!((l.n1, l.n2, l.turn, l.top_is_exit), (4, 4, 1.0, true));
assert!((l.riser - h).abs() < 1e-9 && l.z0.abs() < 1e-9);
// U (Wende um 180°, Läufe nebeneinander): Podesttreppe, die Dossier nicht abbildet.
let mut m = Mesh::default();
for i in 0..4 {
let (x0, x1) = (1.0 + 0.28 * i as f64, 1.0 + 0.28 * (i + 1) as f64);
block(&mut m, &[[x0, 1.5], [x1, 1.5], [x1, 2.5], [x0, 2.5]], 0.0, h * (i + 1) as f64);
}
block(&mut m, &[[2.12, 1.5], [3.12, 1.5], [3.12, 3.5], [2.12, 3.5]], 0.0, 5.0 * h);
for i in 0..4 {
let (x1, x0) = (2.12 - 0.28 * i as f64, 2.12 - 0.28 * (i + 1) as f64);
block(&mut m, &[[x0, 2.5], [x1, 2.5], [x1, 3.5], [x0, 3.5]], 0.0, h * (6 + i) as f64);
}
assert_eq!(fit_l_stair(&[m]), Err(R_STAIR_TURN));
}
#[test]
fn arc_ring_center_radius_sweep() {
// Viertelring um (1, 2), Radien 4.9 … 5.1, von 0° bis 90°.
+5 -3
View File
@@ -2462,7 +2462,7 @@ export const de = {
"ifc.importDialog.asMesh": "Als Kontext-Meshes (Standard)",
"ifc.importDialog.asMeshHint": "Jedes Bauteil als nicht bearbeitbares Mesh der Kontext-Schicht, wie in der Datei.",
"ifc.importDialog.asElements": "Als Bauteile",
"ifc.importDialog.asElementsHint": "Wände (auch Bogen- und Giebelwände), Decken, Dächer, gerade Treppen, Stützen, Türen/Fenster, Räume und Geschosse werden bearbeitbare Dossier-Bauteile; was nicht sicher abbildbar ist, bleibt Mesh.",
"ifc.importDialog.asElementsHint": "Wände (auch Bogen- und Giebelwände), Decken, Dächer, gerade, L- und Wendeltreppen, Stützen, Träger, Türen/Fenster, Räume und Geschosse werden bearbeitbare Dossier-Bauteile; was nicht sicher abbildbar ist, bleibt Mesh.",
"ifc.importDialog.import": "Importieren",
"ifc.importReport.title": "IFC-Import: Bericht",
"ifc.importReport.recognized": "Als Bauteile übernommen",
@@ -2475,6 +2475,7 @@ export const de = {
"ifc.importReport.rooms": "Räume",
"ifc.importReport.roofs": "Dächer",
"ifc.importReport.stairs": "Treppen",
"ifc.importReport.beams": "Träger (als Extrusionskörper)",
"ifc.importReport.floors": "Neue Geschosse",
"ifc.importReport.types": "Neue Typen (Wand, Decke, Dach, Tür, Fenster)",
"ifc.importReport.meshes": "Übrige Bauteile als Kontext-Mesh",
@@ -2489,8 +2490,9 @@ export const de = {
"ifc.reason.profile": "Querschnitt weder Rechteck noch Kreis",
"ifc.reason.holes": "Raum mit Loch",
"ifc.reason.part": "Teil eines anderen Bauteils",
"ifc.reason.roofForm": "Dachform nicht Flach/Pult/Sattel/Walm (achsparallel)",
"ifc.reason.stairForm": "keine gerade, gleichmässige Treppe",
"ifc.reason.roofForm": "Dachform nicht abbildbar (kein Rechteck, ungleiche Neigung, Tonnendach …)",
"ifc.reason.stairForm": "keine gleichmässige gerade, L- oder Wendeltreppe",
"ifc.reason.stairTurn": "Podesttreppe mit Wende (U, mehrere Podeste): Dossier kennt nur gerade, L- und Wendeltreppen",
"menu.native.importMesh": "3D-Modell importieren …",
"mesh.import.title": "3D-Modell importieren",
"mesh.import.failed": "3D-Modell-Import fehlgeschlagen",
+5 -3
View File
@@ -2412,7 +2412,7 @@ export const en: Record<TranslationKey, string> = {
"ifc.importDialog.asMesh": "As context meshes (default)",
"ifc.importDialog.asMeshHint": "Every element as a non-editable mesh on the context layer, as in the file.",
"ifc.importDialog.asElements": "As building elements",
"ifc.importDialog.asElementsHint": "Walls (including curved and gable walls), slabs, roofs, straight stairs, columns, doors/windows, rooms and storeys become editable Dossier elements; anything not safely mappable stays a mesh.",
"ifc.importDialog.asElementsHint": "Walls (including curved and gable walls), slabs, roofs, straight, L and spiral stairs, columns, beams, doors/windows, rooms and storeys become editable Dossier elements; anything not safely mappable stays a mesh.",
"ifc.importDialog.import": "Import",
"ifc.importReport.title": "IFC import: report",
"ifc.importReport.recognized": "Imported as building elements",
@@ -2425,6 +2425,7 @@ export const en: Record<TranslationKey, string> = {
"ifc.importReport.rooms": "Rooms",
"ifc.importReport.roofs": "Roofs",
"ifc.importReport.stairs": "Stairs",
"ifc.importReport.beams": "Beams (as extruded solids)",
"ifc.importReport.floors": "New storeys",
"ifc.importReport.types": "New types (wall, slab, roof, door, window)",
"ifc.importReport.meshes": "Other elements as context mesh",
@@ -2439,8 +2440,9 @@ export const en: Record<TranslationKey, string> = {
"ifc.reason.profile": "cross-section neither rectangle nor circle",
"ifc.reason.holes": "room with a hole",
"ifc.reason.part": "part of another element",
"ifc.reason.roofForm": "roof shape not flat/mono-pitch/gable/hip (axis-aligned)",
"ifc.reason.stairForm": "not a straight, regular stair",
"ifc.reason.roofForm": "roof shape not mappable (not a rectangle, unequal pitch, barrel roof …)",
"ifc.reason.stairForm": "not a regular straight, L or spiral stair",
"ifc.reason.stairTurn": "landing stair with a turn (U, several landings): Dossier only has straight, L and spiral stairs",
"menu.native.importMesh": "Import 3D model …",
"mesh.import.title": "Import 3D model",
"mesh.import.failed": "3D model import failed",
+3 -1
View File
@@ -119,9 +119,11 @@ export interface IfcElementsSummary {
ceilings: number;
columns: number;
rooms: number;
/** Dächer (Flach/Pult/Sattel/Walm) und gerade Treppen ([B4]). */
/** Dächer (Flach/Pult/Sattel/Walm, auch mit Neigung je Kante) und Treppen (gerade, L, Wendel) ([B4]). */
roofs: number;
stairs: number;
/** Träger (IfcBeam) als Extrusionskörper ([B4]). */
beams?: number;
/** Neu angelegte Geschosse. */
floors: number;
wallTypes: number;
+1 -1
View File
@@ -87,7 +87,7 @@ export interface IfcProductView {
/** Roh erkanntes Bauteil (`meta.elements.elements` des Lesers). */
export interface IfcRawElement {
kind: "wall" | "opening" | "slab" | "column" | "space";
kind: "wall" | "opening" | "slab" | "column" | "space" | "roof" | "stair" | "beam";
globalId: string;
ifcClass: string;
name: string | null;
+1
View File
@@ -76,6 +76,7 @@ const RECOGNIZED: ReadonlyArray<[string, (s: IfcElementsSummary) => number]> = [
["ifc.importReport.ceilings", (s) => s.ceilings],
["ifc.importReport.roofs", (s) => s.roofs ?? 0],
["ifc.importReport.stairs", (s) => s.stairs ?? 0],
["ifc.importReport.beams", (s) => s.beams ?? 0],
["ifc.importReport.columns", (s) => s.columns],
["ifc.importReport.rooms", (s) => s.rooms],
["ifc.importReport.floors", (s) => s.floors],