Merge branch 'worktree-agent-ae0df7110bf4298e3' into claude/practical-noether-1hb2s1

This commit is contained in:
Claude committed 2026-11-06 21:21:16 +00:00
commit 957f3d0d04
13 files changed
+1975 -110

No files matched your search

+25
View File
@@ -3461,6 +3461,31 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module
SIA-416-Kategorie des Raums, wenn er keine eigene `CH_Raum`-Eigenschaft hat: `CH_Zone.SIA416`, sonst der
Zonenname (HNF, NNF, VF, FF, KGF/KF, AGF; kein Raten bei anderen Namen). Rundreise Export → Import
geprüft. Offen: Klassifikation als Feld am Bauteil, IfcGrid (Modell ohne Raster).
(6.11., ArchiCAD-Exporte) Testdaten (nur lokal, nicht im Repo): KIT-Beispiele aus ArchiCAD 20, IFC4 („for unrestricted
use", Quelle IAI/KIT nennen: AC20-FZK-Haus, AC20-Institute-Var-2, AC-20-Smiley-West-10-Bldg) und Schependomlaan
(ArchiCAD 18, IFC2x3, TU Eindhoven, Datenfreigabe nur für Forschung/Lehre). Frei lizenzierte Vectorworks-Exporte
nicht gefunden. Neu in Rust (`fileio/src/ifc_shapes.rs`, `ifc_semantic.rs`): Dach aus IfcRoof (Platten) bzw.
IfcSlab ROOF (je Geschoss nach Berührung gruppiert) → Dossier-Dach Flach/Pult/Sattel/Walm (achsparalleles Rechteck,
gleiche Neigung, jede Dachflächen-Ecke ±3 cm auf der Dossier-Fläche, Dicke senkrecht, Traufhöhe, Dachtyp nur mit
Material); Giebel-/Pultwände = Wand bis zum höchsten Punkt, wenn ein erkanntes Dach die Krone genau so kappt wie
Dossier (Volumenvergleich, Dachanschluss automatisch); gerade Treppe (IfcStair ohne Geländer/IfcStairFlight:
Trittflächen gleichmässig, Belag über Rohbau zusammengefasst) → Antritt, Richtung, Laufbreite, Steigung, Auftritt;
Bogenwand (Ringausschnitt ohne Öffnungen) → `bulge`; runde Öffnung → `shape: "rund"`; Türen/Fenster ohne
IfcRelFillsElement → Wirt über die Lage (Loch schon im Wandkörper: fehlendes Volumen = Kästen der Füllungen);
IfcSpace nur mit „FootPrint"/„Box" (ArchiCAD 2x3) → Raum; Dreiecksnetze mit T-Stössen (Kanten an Punkten geteilt);
IfcMapConversion (Bericht `mapConversion`) → Rückschub auf den LV95-Projektnullpunkt (ungedreht, Massstab 1).
Kern (`import_ifc.rs`): Dächer, Treppen, `bulge`, `shape`, Tür-/Fenstertyp nach Typnamen der Datei (gleichnamig
wiederverwendet, sonst Kopie des passenden; „Tür …"/„Fenster …" des eigenen Exports zählen nicht), Gründe je Klasse
(`keptReasons`). Dialog: Bericht nach dem Import (`IfcImportReportDialog`: erkannt je Bauteilart, als Mesh geblieben
mit Grund, `ifc.reason.*`). Quote (Bauteile vorher → nachher): FZK-Haus Wände 9 → 13/13, Öffnungen 14 → 16/16,
Dach 0 → 1 (2 Platten), Räume 5/7 (Dachraum kein Prisma), Wendeltreppe Mesh; Institute Wände 111/121 (8 unter dem
Tonnendach, 2 nicht rechteckig), Dächer 6, 15 Tonnendach-Platten Mesh, Podesttreppen 4 Mesh; Smiley West Wände
270/281 (11 Ständerwände), Dächer 11 (10 Pult + 1 Flach), 30 Podesttreppen Mesh; Schependomlaan Wände 770 → 795,
Öffnungen 60 → 93, Räume 6 → 100, Dächer 19, Treppen 6/9. Rundreise Demo-Haus jetzt auch Dach und Treppe als
Bauteile. Bilder (lokal): FZK-Haus Grundriss EG/DG und Schnitt, vorher Meshes/nachher Bauteile. Offen: Pultdach
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.
- ◐ **[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
+297 -18
View File
@@ -22,6 +22,8 @@ const OPENING_CATEGORY: &str = "21";
const CEILING_CATEGORY: &str = "30";
const COLUMN_CATEGORY: &str = "50";
const ROOM_CATEGORY: &str = "60";
const ROOF_CATEGORY: &str = "35";
const STAIR_CATEGORY: &str = "40";
const ROOM_COLOR: &str = "#6b7280";
const SIA: [&str; 6] = ["HNF", "NNF", "VF", "FF", "KGF", "AGF"];
const LEVEL_TOL: f64 = 0.005;
@@ -69,6 +71,8 @@ struct WallData {
z0: f64,
z1: f64,
thickness: f64,
/// Bogenwand ([T2]), 0 = gerade.
bulge: f64,
}
struct OpeningData {
@@ -82,6 +86,8 @@ struct OpeningData {
operation: Option<String>,
swing: f64,
hinge: f64,
/// Umriss in der Wandebene (`Opening.shape`), z. B. "rund".
shape: Option<String>,
}
struct SlabData {
@@ -112,6 +118,27 @@ struct SpaceData {
z0: f64,
}
struct RoofData {
info: Info,
outline: Vec<[f64; 2]>,
shape: String,
ridge_axis: String,
pitch_deg: f64,
eave_z: f64,
thickness: f64,
}
struct StairData {
info: Info,
start: [f64; 2],
dir: [f64; 2],
run_length: f64,
width: f64,
step_count: f64,
z0: f64,
total_rise: f64,
}
struct Storey {
name: String,
elevation: f64,
@@ -125,7 +152,11 @@ struct Elements {
slabs: Vec<SlabData>,
columns: Vec<ColumnData>,
spaces: Vec<SpaceData>,
roofs: Vec<RoofData>,
stairs: Vec<StairData>,
kept: Map<String, Value>,
/// Je Klasse die Gründe, weshalb Kandidaten Mesh blieben (`{"IfcWall": {"slopedTop": 3}}`).
kept_reasons: Map<String, Value>,
}
fn s_of(v: Option<&Value>) -> Option<String> {
@@ -189,6 +220,7 @@ fn decode_elements(meta: &Value, data: &[f64]) -> Elements {
})
.unwrap_or_default();
out.kept = raw.get("kept").and_then(Value::as_object).cloned().unwrap_or_default();
out.kept_reasons = raw.get("keptReasons").and_then(Value::as_object).cloned().unwrap_or_default();
let mut wall_index: HashMap<i64, usize> = HashMap::new();
let mut rust_wall: i64 = 0;
for e in raw.get("elements").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) {
@@ -206,9 +238,10 @@ fn decode_elements(meta: &Value, data: &[f64]) -> Elements {
let info = info_of(e);
match kind {
"wall" => {
if v.len() == 7 {
if v.len() == 7 || v.len() == 8 {
wall_index.insert(rust_wall, out.walls.len());
out.walls.push(WallData { info, start: [v[0], v[1]], end: [v[2], v[3]], z0: v[4], z1: v[5], thickness: v[6] });
let bulge = v.get(7).copied().filter(|b| b.abs() <= 1e6).unwrap_or(0.0);
out.walls.push(WallData { info, start: [v[0], v[1]], end: [v[2], v[3]], z0: v[4], z1: v[5], thickness: v[6], bulge });
}
rust_wall += 1;
}
@@ -227,6 +260,7 @@ fn decode_elements(meta: &Value, data: &[f64]) -> Elements {
operation: s_of(e.get("operation")),
swing: v[4].signum() * (v[4] != 0.0) as u8 as f64,
hinge: v[5].signum() * (v[5] != 0.0) as u8 as f64,
shape: s_of(e.get("shape")),
});
}
}
@@ -243,6 +277,29 @@ fn decode_elements(meta: &Value, data: &[f64]) -> Elements {
out.columns.push(ColumnData { info, center: [v[0], v[1]], rotation: v[2], z0: v[3], z1: v[4], round, a: v[5], b: v[6] });
}
}
"roof" => {
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");
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] });
}
}
}
"stair" => {
if v.len() == 9 && v[6] >= 2.0 && v[6] <= 200.0 && v[4] > 0.0 && v[5] > 0.0 {
out.stairs.push(StairData {
info,
start: [v[0], v[1]],
dir: [v[2], v[3]],
run_length: v[4],
width: v[5],
step_count: v[6].round(),
z0: v[7],
total_rise: v[8],
});
}
}
"space" => {
if let Some(mut r) = rings(v, 2, 1.0) {
out.spaces.push(SpaceData {
@@ -424,18 +481,41 @@ fn type_for(ctx: &mut Ctx, types: &mut Vec<(Value, bool)>, e: &Info, t: f64, kin
id
}
/// Allgemeiner Name eines Tür-/Fensterstils (eigener Export: "Tür", "Fenster SINGLE_PANEL" …).
fn generic_fill_name(n: &str) -> bool {
let rest = n.strip_prefix("Tür").or_else(|| n.strip_prefix("Fenster")).or_else(|| n.strip_prefix("Door")).or_else(|| n.strip_prefix("Window"));
rest.is_some_and(|r| r.is_empty() || (r.starts_with(' ') && r.trim().chars().all(|c| c.is_ascii_uppercase() || c == '_')))
}
/// Tür-/Fenstertyp nach Namen: vorhanden (ohne Gross-/Kleinschreibung) oder neu als Kopie von `template`.
fn typed_by_name(ctx: &mut Ctx, types: &mut Vec<(Value, bool)>, name: Option<&str>, template: Option<&Value>, kind: &str, counter: &str) -> Option<String> {
let Some(name) = name else { return template.and_then(|t| t.get("id")).and_then(Value::as_str).map(str::to_string) };
let key = name.to_lowercase();
if let Some((t, _)) = types.iter().find(|(t, _)| t.get("name").and_then(Value::as_str).is_some_and(|n| n.trim().to_lowercase() == key)) {
return Some(id_of(t).to_string());
}
let mut t = template?.clone();
let id = ctx.new_id(kind);
t["id"] = id.clone().into();
t["name"] = name.into();
types.push((t, true));
ctx.bump(counter);
Some(id)
}
fn list_of(root: &Map<String, Value>, key: &str) -> Vec<(Value, bool)> {
root.get(key).and_then(Value::as_array).map(|a| a.iter().map(|v| (v.clone(), false)).collect()).unwrap_or_default()
}
/// Bauteile + übrige Kontext-Meshes ins Projekt `root` (vorher `ifcElementsToProject`).
fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Elements, opts: &IfcOptions, now: f64) -> (Vec<Op>, Value, usize) {
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", "floors", "wallTypes", "ceilingTypes", "components", "meshes", "classified"] {
for k in ["walls", "openings", "ceilings", "columns", "rooms", "roofs", "stairs", "floors", "wallTypes", "ceilingTypes", "roofTypes", "doorTypes", "windowTypes", "components", "meshes", "classified"] {
summary.insert(k.into(), 0.into());
}
summary.insert("kept".into(), js_num(kept));
summary.insert("keptReasons".into(), Value::Object(el.kept_reasons.clone()));
let hatches = root.get("hatches").and_then(Value::as_array).cloned().unwrap_or_default();
let hatch_id = hatches.iter().find(|h| id_of(h) == "none").or(hatches.first()).and_then(|h| h.get("id").and_then(Value::as_str)).unwrap_or("none").to_string();
let mut ctx = Ctx { stamp: stamp36(now), summary, levels: list_of(root, "drawingLevels"), components: list_of(root, "components"), hatch_id, root };
@@ -454,7 +534,13 @@ fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Element
for s in &el.spaces {
s.boundary.iter().for_each(|p| extra.extend(p));
}
let [dx, dy] = geo_shift(products, project_geo_origin(root), &extra);
for r in &el.roofs {
r.outline.iter().for_each(|p| extra.extend(p));
}
for s in &el.stairs {
extra.extend(s.start);
}
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)]);
// ── Geschosse ──
@@ -528,6 +614,9 @@ fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Element
let id = ctx.new_id("wall");
let wt = type_for(&mut ctx, &mut wall_types, &w.info, w.thickness, "walltype", "wallTypes");
let mut o = json!({"id": id, "type": "wall", "floorId": fid, "categoryCode": WALL_CATEGORY, "start": mv(w.start), "end": mv(w.end), "wallTypeId": wt, "height": js_num(height)});
if w.bulge.abs() > 1e-9 {
o["bulge"] = js_num(round(w.bulge, 1e-9));
}
if bottom.abs() > LEVEL_TOL {
o["bottom"] = json!({"mode": "floor", "floorId": fid, "offset": js_num(bottom)});
}
@@ -539,8 +628,8 @@ fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Element
}
walls.push(o);
}
let door_types = root.get("doorTypes").and_then(Value::as_array).cloned().unwrap_or_default();
let window_types = root.get("windowTypes").and_then(Value::as_array).cloned().unwrap_or_default();
let mut door_types: Vec<(Value, bool)> = list_of(root, "doorTypes");
let mut window_types: Vec<(Value, bool)> = list_of(root, "windowTypes");
let mut openings: Vec<Value> = Vec::new();
for o in &el.openings {
let Some(host) = walls.get(o.host) else { continue };
@@ -550,24 +639,36 @@ fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Element
let leaves = if op.starts_with("DOUBLE_DOOR") { 2.0 } else { 1.0 };
let door_type = (!op.is_empty())
.then(|| {
door_types.iter().find(|t| {
door_types.iter().map(|x| &x.0).find(|t| {
t.get("kind").and_then(Value::as_str) == Some(if sliding { "schiebe" } else { "dreh" }) && t.get("leafCount").and_then(Value::as_f64) == Some(leaves)
})
})
.flatten()
.or(door_types.first());
.or(door_types.first().map(|x| &x.0))
.cloned();
let wings: Option<f64> = match op {
"SINGLE_PANEL" => Some(1.0),
"DOUBLE_PANEL_VERTICAL" => Some(2.0),
"TRIPLE_PANEL_VERTICAL" => Some(3.0),
_ => None,
};
let window_type = wings.and_then(|w| window_types.iter().find(|t| t.get("wingCount").and_then(Value::as_f64) == Some(w))).or(window_types.first());
let type_id = match o.kind.as_str() {
"door" => door_type.and_then(|t| t.get("id")).and_then(Value::as_str),
"window" => window_type.and_then(|t| t.get("id")).and_then(Value::as_str),
let window_type = wings
.and_then(|w| window_types.iter().map(|x| &x.0).find(|t| t.get("wingCount").and_then(Value::as_f64) == Some(w)))
.or(window_types.first().map(|x| &x.0))
.cloned();
// Typ aus der Datei (IfcDoorType/IfcWindowType, IFC2x3 Style): gleichnamiger Dossier-Typ, sonst ein
// neuer nach dem Vorbild des passenden ([B4]). Allgemeine Namen ("Tür", "Fenster SINGLE_PANEL" aus
// dem eigenen Export) zählen nicht.
let named = o.info.type_name.as_deref().map(str::trim).filter(|n| !n.is_empty() && !generic_fill_name(n)).map(str::to_string);
let type_id: Option<String> = match o.kind.as_str() {
"door" => typed_by_name(&mut ctx, &mut door_types, named.as_deref(), door_type.as_ref(), "doortype", "doorTypes"),
"window" => typed_by_name(&mut ctx, &mut window_types, named.as_deref(), window_type.as_ref(), "windowtype", "windowTypes"),
_ => None,
};
let window_type = match (&type_id, o.kind.as_str()) {
(Some(id), "window") => window_types.iter().map(|x| &x.0).find(|t| id_of(t) == id).cloned(),
_ => window_type,
};
let mut v = Map::new();
v.insert("id".into(), ctx.new_id("opening").into());
v.insert("type".into(), "opening".into());
@@ -581,6 +682,9 @@ fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Element
if o.kind == "hole" {
v.insert("doorType".into(), "wandoeffnung".into());
}
if let Some(sh) = o.shape.as_deref().filter(|x| ["rund", "rundbogen", "segmentbogen", "spitzbogen", "schraeg", "giebel"].contains(x)) {
v.insert("shape".into(), sh.into());
}
if let Some(t) = type_id.filter(|t| !t.is_empty()) {
v.insert("typeId".into(), t.into());
}
@@ -593,7 +697,7 @@ fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Element
}
}
if let (true, Some(w)) = (o.kind == "window", wings) {
if window_type.and_then(|t| t.get("wingCount")).and_then(Value::as_f64).unwrap_or(1.0) != w {
if window_type.as_ref().and_then(|t| t.get("wingCount")).and_then(Value::as_f64).unwrap_or(1.0) != w {
v.insert("wingCount".into(), js_num(w));
}
}
@@ -698,6 +802,33 @@ fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Element
}));
}
let mut roof_types = list_of(root, "roofTypes");
let mut roofs: Vec<Value> = Vec::new();
for r in &el.roofs {
let (fid, _, _) = floor_of(&mut ctx, r.info.storey, r.eave_z);
let mut v = json!({
"id": ctx.new_id("roof"), "type": "roof", "floorId": fid, "categoryCode": ROOF_CATEGORY,
"outline": r.outline.iter().map(|&p| mv(p)).collect::<Vec<_>>(),
"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)),
});
// 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();
}
roofs.push(v);
}
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",
"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,
}));
}
// ── Übrige Bauteile als Kontext-Mesh ──
let meshes = ifc_meshes(products, &opts.file_name, opts.group.as_deref().unwrap_or("auto"), [dx, dy], now);
let n_meshes = meshes.len();
@@ -706,8 +837,10 @@ fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Element
+ el.slabs.iter().filter(|s| s.info.classified).count()
+ el.columns.iter().filter(|c| c.info.classified).count()
+ el.spaces.iter().filter(|s| s.info.classified).count()
+ 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()), ("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()), ("meshes", n_meshes), ("classified", classified)] {
ctx.summary.insert(k.into(), n.into());
}
@@ -718,10 +851,15 @@ fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Element
if !ceiling_types.is_empty() || root.get("ceilingTypes").is_some_and(|v| crate::json_util::truthy(Some(v))) {
ops.extend(grown_list_ops("ceilingTypes", root.get("ceilingTypes"), ceiling_types));
}
for (key, list) in [("roofTypes", roof_types), ("doorTypes", door_types), ("windowTypes", window_types)] {
if list.iter().any(|x| x.1) {
ops.extend(grown_list_ops(key, root.get(key), list));
}
}
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)] {
for (key, items) in [("openings", openings), ("ceilings", ceilings), ("columns", columns), ("rooms", rooms), ("roofs", roofs), ("stairs", stairs)] {
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 });
@@ -737,6 +875,23 @@ fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Element
(ops, Value::Object(ctx.summary), n_meshes)
}
/// Rückschub über die Georeferenz der Datei (IfcMapConversion, [B4]): die Datei liegt lokal, die Karte
/// = lokal + (Ost, Nord). Hat das Projekt einen LV95-Bezug, landet das Modell an seinem Kartenort
/// relativ zum Projekt-Nullpunkt. Nur ungedreht und Massstab 1 und nur bei LV95 (EPSG:2056) oder ohne
/// Angabe des Systems; sonst `None` (dann wie bisher über die Lage der Punkte).
fn map_shift(meta: &Value, root: &Map<String, Value>) -> Option<[f64; 2]> {
let m = meta.get("mapConversion")?;
let num = |k: &str| m.get(k).and_then(Value::as_f64);
let (e, n) = (num("eastings")?, num("northings")?);
let axis = m.get("xAxis").and_then(Value::as_array)?;
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 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]])
}
/// 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}"))?;
@@ -745,7 +900,7 @@ pub fn ifc_import(root: &Map<String, Value>, meta_json: &str, positions: &[f64],
if opts.elements {
let el = decode_elements(&meta, element_data);
let kept = el.kept.clone();
let (ops, summary, n) = elements_ops(root, &products, &el, opts, now);
let (ops, summary, n) = elements_ops(root, &meta, &products, &el, opts, now);
// Statt der Roh-Bauteile die Zusammenfassung (an derselben Stelle des Berichts).
let mut report = report;
if let Some(r) = report.as_object_mut() {
@@ -753,8 +908,132 @@ pub fn ifc_import(root: &Map<String, Value>, meta_json: &str, positions: &[f64],
}
return Ok(IfcResult { ops, summary: Some(summary), report, kept, context_objects: n });
}
let shift = geo_shift(&products, project_geo_origin(root), &[]);
let shift = map_shift(&meta, root).unwrap_or_else(|| geo_shift(&products, project_geo_origin(root), &[]));
let meshes = ifc_meshes(&products, &opts.file_name, opts.group.as_deref().unwrap_or("auto"), shift, now);
let n = meshes.len();
Ok(IfcResult { ops: context_ops(root, meshes), summary: None, report, kept: Map::new(), context_objects: n })
}
#[cfg(test)]
mod tests {
use super::*;
fn added<'a>(ops: &'a [Op], key: &str) -> Vec<&'a Value> {
let mut out = Vec::new();
for op in ops {
match op {
Op::Add { collection, items, .. } if collection == key => out.extend(items.iter()),
Op::SetField { key: k, value: Some(Value::Array(a)), .. } if k == key => out.extend(a.iter()),
_ => {}
}
}
out
}
fn at(v: &Value, x: f64, y: f64) -> bool {
(v["x"].as_f64().unwrap_or(f64::NAN) - x).abs() < 1e-9 && (v["y"].as_f64().unwrap_or(f64::NAN) - y).abs() < 1e-9
}
/// Erkannte Bauteile wie aus `fileio` (`ifc_semantic::encode`): Bogenwand mit runder Öffnung,
/// Satteldach, gerade Treppe, Tür mit eigenem Typnamen; Georeferenz LV95.
fn meta(door_type: &str) -> (Value, Vec<f64>) {
let data = vec![
// Wand: sx, sy, ex, ey, z0, z1, t, bulge
5.0, 0.0, 0.0, 5.0, 0.0, 2.5, 0.3, -0.41421356237,
// Öffnung: position, width, sill, height, swing, hinge
1.0, 1.0, 1.0, 1.0, 0.0, 0.0,
// Gerade Wand für die Tür
0.0, -2.0, 4.0, -2.0, 0.0, 2.5, 0.2, 0.0,
1.0, 0.9, 0.0, 2.1, 0.0, 0.0,
// Dach: eaveZ, pitch, t, n, Ring
3.0, 45.0, 0.2, 4.0, 0.0, 0.0, 10.0, 0.0, 10.0, 8.0, 0.0, 8.0,
// Treppe: sx, sy, dx, dy, lauf, breite, stufen, z0, steighöhe
1.0, 2.55, 1.0, 0.0, 1.68, 1.1, 6.0, 0.0, 1.05,
];
let info = |kind: &str, at: usize, n: usize| json!({"kind": kind, "at": at, "n": n, "storey": 0, "layers": [], "classifications": [], "common": {}});
let mut op1 = info("opening", 8, 6);
op1["host"] = 0.into();
op1["openingKind"] = "hole".into();
op1["shape"] = "rund".into();
let mut op2 = info("opening", 22, 6);
op2["host"] = 1.into();
op2["openingKind"] = "door".into();
op2["typeName"] = door_type.into();
let mut roof = info("roof", 28, 12);
roof["shape"] = "sattel".into();
roof["ridgeAxis"] = "x".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": [1.0, 0.0], "scale": 1.0, "crs": "EPSG:2056"},
"elements": {
"storeys": [{"globalId": "s", "name": "EG", "elevation": 0.0}],
"elements": [info("wall", 0, 8), op1, info("wall", 14, 8), op2, roof, info("stair", 40, 9)],
"kept": {"IfcStair": 1},
"keptReasons": {"IfcStair": {"stairForm": 1}},
},
});
(meta, data)
}
fn root() -> Map<String, Value> {
json!({
"drawingLevels": [], "components": [], "wallTypes": [], "hatches": [{"id": "none"}],
"doorTypes": [{"id": "dt1", "name": "Drehtür", "kind": "dreh", "leafCount": 1, "leafStyle": "glatt", "frameThickness": 0.05}],
"windowTypes": [{"id": "wt1", "name": "Fenster", "kind": "dreh", "wingCount": 1}],
"geoAnchor": {"lv95": {"e": 2600000.0, "n": 1200000.0}, "model": {"x": 0.0, "y": 0.0}},
})
.as_object()
.cloned()
.unwrap()
}
#[test]
fn roof_stair_arc_wall_round_opening_type_by_name_and_map_shift() {
let (m, data) = meta("Haustür Eiche");
let opts = IfcOptions { file_name: "a.ifc".into(), group: None, elements: true };
let r = ifc_import(&root(), &m.to_string(), &[], &[], &data, &opts, 0.0).unwrap();
let walls = added(&r.ops, "walls");
assert_eq!(walls.len(), 2);
// Verschiebung aus der Georeferenz: Karte − Projekt-Nullpunkt = (100, 50).
assert!(at(&walls[0]["start"], 105.0, 50.0), "{}", walls[0]);
assert!((walls[0]["bulge"].as_f64().unwrap() + 0.41421356237).abs() < 1e-9);
assert!(walls[1].get("bulge").is_none());
let openings = added(&r.ops, "openings");
assert_eq!(openings[0]["shape"], "rund");
// Neuer Türtyp mit dem Namen aus der Datei, nach dem Vorbild des vorhandenen.
let doors = added(&r.ops, "doorTypes");
assert_eq!(doors.len(), 1, "{:?}", r.ops);
assert_eq!((doors[0]["name"].as_str(), doors[0]["kind"].as_str()), (Some("Haustür Eiche"), Some("dreh")));
assert_eq!(openings[1]["typeId"], doors[0]["id"]);
let roofs = added(&r.ops, "roofs");
assert_eq!(roofs.len(), 1);
assert_eq!(
(roofs[0]["shape"].as_str(), roofs[0]["ridgeAxis"].as_str(), roofs[0]["pitchDeg"].as_f64(), roofs[0]["baseElevation"].as_f64()),
(Some("sattel"), Some("x"), Some(45.0), Some(3.0))
);
assert!(at(&roofs[0]["outline"][2], 110.0, 58.0));
// Ohne Material in der Datei: kein Dachtyp, einschichtig über die Dicke.
assert!(added(&r.ops, "roofTypes").is_empty() && roofs[0].get("roofTypeId").is_none());
assert!((roofs[0]["thickness"].as_f64().unwrap() - 0.2).abs() < 1e-9);
let stairs = added(&r.ops, "stairs");
assert_eq!((stairs[0]["stepCount"].as_f64(), stairs[0]["shape"].as_str()), (Some(6.0), Some("straight")));
assert!(at(&stairs[0]["start"], 101.0, 52.55));
let s = r.summary.unwrap();
assert_eq!((s["roofs"].as_f64(), s["stairs"].as_f64(), s["doorTypes"].as_f64()), (Some(1.0), Some(1.0), Some(1.0)));
assert_eq!(s["keptReasons"], json!({"IfcStair": {"stairForm": 1}}));
// Allgemeiner Stilname aus dem eigenen Export: kein neuer Typ; vorhandener Name: wiederverwendet.
for name in ["Tür SINGLE_SWING_LEFT", "drehtür"] {
let (m, data) = meta(name);
let r = ifc_import(&root(), &m.to_string(), &[], &[], &data, &opts, 0.0).unwrap();
assert!(added(&r.ops, "doorTypes").is_empty(), "{name}");
assert_eq!(added(&r.ops, "openings")[1]["typeId"], "dt1");
}
// Ohne Projekt-Bezug: lokal (keine Verschiebung).
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]["start"], 5.0, 0.0));
}
}
+84 -1
View File
@@ -515,6 +515,52 @@ pub struct IfcImport {
pub truncated: bool,
/// Erkannte Bauteile ([B4]), nur mit [`import_ifc_opts`]`(…, true)`.
pub elements: Option<crate::ifc_semantic::Semantic>,
/// Georeferenz (IfcMapConversion, IFC4): Kartenkoordinaten = Drehung·Massstab·lokal + Versatz.
pub map_conversion: Option<MapConversion>,
}
/// IfcMapConversion ([B4]): Versatz in Kartenmetern, Drehung der lokalen x-Achse, Massstab, Zielsystem.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MapConversion {
pub eastings: f64,
pub northings: f64,
pub height: f64,
/// Richtung der lokalen x-Achse im Kartensystem (Abszisse, Ordinate; normiert).
pub x_axis: [f64; 2],
pub scale: f64,
/// Name des Zielsystems (IfcProjectedCRS.Name, z. B. `EPSG:2056`).
pub crs: Option<String>,
}
/// Erste IfcMapConversion der Datei; Kartenwerte in Metern (MapUnit des IfcProjectedCRS, sonst m).
fn map_conversion(f: &StepFile, ids: &[u64]) -> Option<MapConversion> {
let e = ids.iter().filter_map(|i| f.get(*i)).find(|e| e.ty == "IFCMAPCONVERSION")?;
let num = |k: usize| e.arg(k).and_then(|v| v.as_f64());
let crs = e.arg(1).and_then(|v| v.as_ref_id()).and_then(|i| f.get(i));
// MapUnit (IfcProjectedCRS, 7. Attribut): IfcSIUnit mit Vorsatz.
let unit = crs
.and_then(|c| c.arg(6))
.and_then(|v| v.as_ref_id())
.and_then(|u| f.get(u))
.filter(|u| u.ty == "IFCSIUNIT")
.map(|u| match u.arg(2).and_then(|v| v.as_enum()) {
Some("MILLI") => 0.001,
Some("CENTI") => 0.01,
Some("KILO") => 1000.0,
_ => 1.0,
})
.unwrap_or(1.0);
let (ax, ay) = (num(5).unwrap_or(1.0), num(6).unwrap_or(0.0));
let l = ax.hypot(ay);
let m = MapConversion {
eastings: num(2)? * unit,
northings: num(3)? * unit,
height: num(4).unwrap_or(0.0) * unit,
x_axis: if l > 1e-12 { [ax / l, ay / l] } else { [1.0, 0.0] },
scale: num(7).filter(|s| *s > 0.0).unwrap_or(1.0),
crs: crs.and_then(|c| c.arg(0)).and_then(|v| v.as_str()).map(str::to_string),
};
(m.eastings.is_finite() && m.northings.is_finite() && m.height.is_finite() && m.scale.is_finite()).then_some(m)
}
/// Bauteilklassen, die als Mesh keinen Sinn ergeben (Volumen-Hilfskörper, Beschriftung).
@@ -1557,6 +1603,37 @@ impl<'a> Reader<'a> {
Some((mesh, color))
}
/// Grundriss eines Bauteils ohne Körper ([B4], z. B. ArchiCAD-IfcSpace nur mit „FootPrint" und „Box"):
/// geschlossener Umriss in Weltkoordinaten (erste Kurve der FootPrint-Darstellung) und Höhenbereich
/// aus der BoundingBox-Darstellung.
pub(crate) fn product_footprint(&mut self, id: u64) -> Option<(Vec<V2>, f64, f64)> {
let f = self.f;
let e = f.get(id)?;
let shape = f.get(e.arg(6)?.as_ref_id()?)?;
if shape.ty != "IFCPRODUCTDEFINITIONSHAPE" {
return None;
}
let reps: Vec<&Entity> = shape.arg(2)?.as_list()?.iter().filter_map(|x| f.get(x.as_ref_id()?)).filter(|r| r.ty == "IFCSHAPEREPRESENTATION").collect();
let ident = |r: &Entity| r.arg(1).and_then(|v| v.as_str()).unwrap_or("").to_ascii_uppercase();
let first = |r: &Entity| r.arg(3).and_then(|v| v.as_list()).and_then(|l| l.first()).and_then(|v| v.as_ref_id());
let foot = reps.iter().find(|r| ident(r) == "FOOTPRINT").and_then(|r| first(r))?;
let bbox = reps.iter().find(|r| ident(r) == "BOX").and_then(|r| first(r)).and_then(|b| f.get(b)).filter(|b| b.ty == "IFCBOUNDINGBOX")?;
let corner = self.point(bbox.arg(0))?;
let zdim = bbox.arg(3)?.as_f64()? * self.len_scale;
let curve_id = match f.get(foot)? {
c if c.ty == "IFCGEOMETRICCURVESET" || c.ty == "IFCGEOMETRICSET" => c.arg(0)?.as_list()?.first()?.as_ref_id()?,
_ => foot,
};
let pts = self.curve2d(Some(&Value::Ref(curve_id)), 0)?;
let place = match e.arg(5).and_then(|v| v.as_ref_id()) {
Some(p) => self.object_placement(p, 0),
None => Xf::IDENTITY,
};
let ring: Vec<V2> = pts.iter().map(|p| place.apply([p[0], p[1], corner[2]])).map(|q| [q[0], q[1]]).collect();
let z0 = place.apply([0.0, 0.0, corner[2]])[2];
(ring.len() >= 3 && zdim.is_finite() && zdim > 0.0 && ring.iter().all(|p| p[0].is_finite() && p[1].is_finite())).then_some((ring, z0, z0 + zdim))
}
/// Wie [`Self::product_body`], aber je Darstellungselement ein eigenes Netz (Weltkoordinaten) —
/// für den Bauteil-Import ([B4]), der z. B. die Schicht-Bänder einer Wand einzeln braucht.
pub(crate) fn product_item_meshes(&mut self, id: u64, max_tris: usize) -> Vec<Mesh> {
@@ -1879,7 +1956,7 @@ pub fn import_ifc_opts(bytes: &[u8], elements: bool) -> Result<IfcImport, String
edge_cache: HashMap::new(),
grid_axes: None,
};
let mut result = IfcImport { schema: f.schema.clone(), length_scale: len_scale, parse_errors: f.errors, ..Default::default() };
let mut result = IfcImport { schema: f.schema.clone(), length_scale: len_scale, parse_errors: f.errors, map_conversion: map_conversion(&f, &ids), ..Default::default() };
// Beziehungen: Geschoss-Zugehörigkeit, Aggregation, Material, Farben.
let rels = Rels::gather(&f, &ids, &mut r);
@@ -2150,6 +2227,12 @@ mod web {
"parseErrors": r.parse_errors,
"truncated": r.truncated,
});
if let Some(m) = &r.map_conversion {
meta["mapConversion"] = serde_json::json!({
"eastings": m.eastings, "northings": m.northings, "height": m.height,
"xAxis": m.x_axis, "scale": m.scale, "crs": m.crs,
});
}
let mut element_data = Vec::new();
if let Some(sem) = &r.elements {
let (v, data) = crate::ifc_semantic::encode(sem);
File diff suppressed because it is too large. Load diff
+548
View File
@@ -0,0 +1,548 @@
// IFC-Import zu Bauteilen ([B4]): Formerkennung für Dächer, Treppen und Bogenwände aus Dreiecksnetzen
// (Weltkoordinaten, Meter, z = Höhe). Wird von `ifc_semantic.rs` benutzt; hier nur Geometrie, keine
// IFC-Beziehungen.
//
// 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.
// - Treppe: gerader Lauf — Trittflächen (waagrechte Oberseiten) in gleichen Höhenschritten, deren
// Vorderkanten linear entlang der Laufrichtung fortschreiten.
// - Bogenwand: senkrechtes Prisma, Umriss auf zwei konzentrischen Kreisen (Ringausschnitt).
//
// Unsinn ergibt `Err(Grund)`, nie Panic.
use crate::ifc_import::{Mesh, V2, V3};
/// Grund: Dachform nicht abbildbar.
pub(crate) const R_ROOF_FORM: &str = "roofForm";
/// Grund: Treppe nicht gerade/gleichmässig.
pub(crate) const R_STAIR_FORM: &str = "stairForm";
fn sub3(a: V3, b: V3) -> V3 {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn cross3(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]]
}
fn dot3(a: V3, b: V3) -> f64 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
/// Dreiecke eines Netzes: (Eckpunkte, Einheitsnormale, Fläche); entartete ausgelassen.
pub(crate) fn triangles(m: &Mesh) -> Vec<([V3; 3], V3, f64)> {
let p = |i: u32| -> Option<V3> {
let k = i as usize * 3;
m.positions.get(k..k + 3).map(|s| [s[0], s[1], s[2]])
};
let mut out = Vec::with_capacity(m.indices.len() / 3);
for t in m.indices.chunks_exact(3) {
let (Some(a), Some(b), Some(c)) = (p(t[0]), p(t[1]), p(t[2])) else { continue };
let n = cross3(sub3(b, a), sub3(c, a));
let l = dot3(n, n).sqrt();
if !(l.is_finite() && l > 1e-12) || !a.iter().chain(&b).chain(&c).all(|x| x.is_finite()) {
continue;
}
out.push(([a, b, c], [n[0] / l, n[1] / l, n[2] / l], l / 2.0));
}
out
}
/// Ebene aus gleich orientierten Dreiecken.
struct Plane {
n: V3,
d: f64,
area: f64,
pts: Vec<V3>,
}
/// Gruppiert Dreiecke nach Ebene (Normale ±0.8°, Abstand ±5 mm).
fn planes(tris: &[&([V3; 3], V3, f64)]) -> Vec<Plane> {
let mut out: Vec<Plane> = Vec::new();
for (pts, n, a) in tris.iter().map(|t| (&t.0, t.1, t.2)) {
let c = [(pts[0][0] + pts[1][0] + pts[2][0]) / 3.0, (pts[0][1] + pts[1][1] + pts[2][1]) / 3.0, (pts[0][2] + pts[1][2] + pts[2][2]) / 3.0];
let d = dot3(n, c);
match out.iter_mut().find(|p| dot3(p.n, n) > 0.9999 && (p.d - d).abs() <= 0.005) {
Some(p) => {
p.area += a;
p.pts.extend_from_slice(pts);
}
None => out.push(Plane { n, d, area: a, pts: pts.to_vec() }),
}
if out.len() > 4000 {
break;
}
}
out
}
/// Erkanntes Dach (Dossier-Parameter, Überstand 0: der Umriss ist schon die Traufe).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct RoofFit {
/// x0, y0, x1, y1.
pub bbox: [f64; 4],
pub shape: &'static str,
pub pitch_deg: f64,
pub ridge_axis: &'static str,
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).
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
}
/// 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) {
return None;
}
Some(self.top_at(x, y) - self.thickness / self.pitch_deg.to_radians().cos().max(0.05))
}
}
/// 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();
let up: Vec<_> = tris.iter().filter(|t| t.1[2] > 0.08).collect();
let down: Vec<_> = tris.iter().filter(|t| t.1[2] < -0.08).collect();
if up.is_empty() || down.is_empty() {
return Err(R_ROOF_FORM);
}
let top_all = planes(&up);
let bottom = planes(&down);
let largest = top_all.iter().map(|p| p.area).fold(0.0, f64::max);
// Je Richtung nur die oberste Ebene (Schicht-Körper übereinander), kleine Flächen (Firstabdeckung,
// rechtwinklige Stirnschnitte der Platten) nicht.
let mut top: Vec<&Plane> = Vec::new();
for p in top_all.iter().filter(|p| p.area >= 0.1 * largest) {
match top.iter_mut().find(|q| dot3(q.n, p.n) > 0.9999) {
Some(q) => {
if p.d > q.d {
*q = p;
}
}
None => top.push(p),
}
}
#[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 {:?}",
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<_>>()
);
}
if top.is_empty() || top.len() > 4 {
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 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);
}
let pitch = |p: &Plane| p.n[2].clamp(-1.0, 1.0).acos().to_degrees();
let pitch_deg = pitch(top[0]);
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.
let flat = pitch_deg < 0.3;
let mut dirs = Vec::new();
if !flat {
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 {
0
} else if hx < -0.9995 {
1
} else if hy > 0.9995 {
2
} else if hy < -0.9995 {
3
} else {
return Err(R_ROOF_FORM);
};
if dirs.contains(&k) {
return Err(R_ROOF_FORM);
}
dirs.push(k);
}
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),
};
// 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)?;
let thickness = bottom.iter().filter(|b| dot3(b.n, main.n) < -0.9999).map(|b| main.d + b.d).fold(f64::NAN, f64::max);
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 };
if pts.iter().any(|q| (q[2] - fit.top_at(q[0], q[1])).abs() > 0.03) {
return Err(R_ROOF_FORM);
}
Ok(fit)
}
/// Volumen eines senkrechten Quaders über dem Rechteck (Ursprung `o`, Richtung `d`, Länge `len`, Dicke
/// `t` symmetrisch zur Achse), unten `z0`, oben `z1`, von den Dächern auf ihre Unterkante gekappt
/// (numerisch, 64 × 4 Stützstellen). So schneidet Dossier eine Wand mit Dachanschluss.
pub(crate) fn capped_volume(o: V2, d: V2, len: f64, t: f64, z0: f64, z1: f64, roofs: &[RoofFit]) -> f64 {
let (nu, nv) = (64, 4);
let n = [-d[1], d[0]];
let mut sum = 0.0;
for i in 0..nu {
let u = (i as f64 + 0.5) / nu as f64 * len;
for j in 0..nv {
let v = ((j as f64 + 0.5) / nv as f64 - 0.5) * t;
let (x, y) = (o[0] + d[0] * u + n[0] * v, o[1] + d[1] * u + n[1] * v);
let cap = roofs.iter().filter_map(|r| r.underside_at(x, y)).fold(z1, f64::min);
sum += (cap - z0).max(0.0);
}
}
sum / (nu * nv) as f64 * len * t
}
/// Erkannte gerade Treppe.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct StairFit {
/// Mitte der ersten Setzstufe (Antritt).
pub start: V2,
pub dir: V2,
pub width: f64,
/// Auftritt (Abstand der Vorderkanten).
pub going: f64,
/// Steigung (Höhe je Stufe).
pub riser: f64,
/// Anzahl Trittflächen im Körper.
pub treads: usize,
/// Antrittshöhe (erster Tritt − Steigung).
pub z0: f64,
/// Der oberste Tritt ist die höchste Stelle des Körpers (Austritt aufs Podest/Geschoss).
pub top_is_exit: bool,
}
/// Gerade Treppe aus den Körpern ihrer Teile (Läufe, Wangen …).
pub(crate) fn fit_stair(meshes: &[Mesh]) -> Result<StairFit, &'static str> {
let tris: Vec<_> = meshes.iter().flat_map(triangles).collect();
let mut plan: Vec<V2> = Vec::new();
let (mut z0, mut z1) = (f64::INFINITY, f64::NEG_INFINITY);
for t in &tris {
for p in &t.0 {
plan.push([p[0], p[1]]);
z0 = z0.min(p[2]);
z1 = z1.max(p[2]);
}
}
let (d, u0, u1, v0, v1) = crate::ifc_semantic::min_area_rect(&plan).ok_or(R_STAIR_FORM)?;
// Trittflächen: waagrechte Oberseiten, nach Höhe gruppiert (±5 mm), je Höhe die u-Ausdehnung.
let n = [-d[1], d[0]];
let mut levels: Vec<(f64, f64, f64, f64)> = Vec::new(); // (z, umin, umax, Fläche)
for (pts, nrm, a) in tris.iter().filter(|t| t.1[2] > 0.999) {
let _ = nrm;
let z = (pts[0][2] + pts[1][2] + pts[2][2]) / 3.0;
let us = pts.iter().map(|p| p[0] * d[0] + p[1] * d[1]);
let (lo, hi) = us.fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), u| (l.min(u), h.max(u)));
match levels.iter_mut().find(|l| (l.0 - z).abs() <= 0.005) {
Some(l) => {
l.1 = l.1.min(lo);
l.2 = l.2.max(hi);
l.3 += a;
}
None => levels.push((z, lo, hi, *a)),
}
if levels.len() > 400 {
return Err(R_STAIR_FORM);
}
}
let width = v1 - v0;
// Nur Flächen, die über die Laufbreite reichen (keine Handlauf-Oberseiten, Wangenköpfe).
#[cfg(test)]
if std::env::var("DOSSIER_IFC_DEBUG").is_ok() {
let mut l = levels.clone();
l.sort_by(|a, b| a.0.total_cmp(&b.0));
eprintln!("Treppe z0 {z0:.3} z1 {z1:.3} Breite {width:.3} Länge {:.3} Ebenen {:?}", u1 - u0, l.iter().map(|x| ((x.0 - z0) as f32, (x.1 - u0) as f32, (x.2 - u0) as f32, x.3 as f32)).collect::<Vec<_>>());
}
levels.retain(|l| l.3 >= 0.06 * width && l.0 > z0 + 0.02);
levels.sort_by(|a, b| a.0.total_cmp(&b.0));
// Belag über dem Rohbau (zwei Flächen wenige cm übereinander): die obere zählt.
let mut merged: Vec<(f64, f64, f64, f64)> = Vec::new();
for l in levels {
match merged.last_mut() {
Some(m) if l.0 - m.0 < 0.08 => *m = l,
_ => merged.push(l),
}
}
let levels = merged;
if levels.len() < 2 || !(0.4..=6.0).contains(&width) {
return Err(R_STAIR_FORM);
}
let k = levels.len();
let mut diffs: Vec<f64> = levels.windows(2).map(|w| w[1].0 - w[0].0).collect();
diffs.sort_by(f64::total_cmp);
let riser = diffs[diffs.len() / 2];
if !(0.1..=0.25).contains(&riser) {
return Err(R_STAIR_FORM);
}
// Gleichmässige Steigung und Vorderkanten linear in der Stufennummer (aufwärts entlang +d oder −d).
for (i, l) in levels.iter().enumerate() {
if (l.0 - (levels[0].0 + riser * i as f64)).abs() > 0.01 {
return Err(R_STAIR_FORM);
}
}
// Genauer als der Median: Mittel über den ganzen Lauf.
let riser = (levels[k - 1].0 - levels[0].0) / (k - 1) as f64;
let top_is_exit = (z1 - levels[k - 1].0).abs() <= 0.03;
let z0 = levels[0].0 - riser;
let up = levels[k - 1].1 + levels[k - 1].2 > levels[0].1 + levels[0].2;
// Vorderkante: bei Lauf in +d das untere u-Ende, sonst das obere.
let front = |l: &(f64, f64, f64, f64)| if up { l.1 } else { -l.2 };
let going = (front(&levels[k - 1]) - front(&levels[0])) / (k - 1) as f64;
if !(0.15..=0.45).contains(&going) {
return Err(R_STAIR_FORM);
}
for (i, l) in levels.iter().enumerate() {
if (front(l) - (front(&levels[0]) + going * i as f64)).abs() > 0.03 {
return Err(R_STAIR_FORM);
}
}
// Antritt = Vorderkante des ersten Tritts (Dossier: Tritt i über [i·a, (i+1)·a], Oberkante (i+1)·h).
let dir = if up { d } else { [-d[0], -d[1]] };
let s_world = if up { front(&levels[0]) } else { -front(&levels[0]) };
if s_world < u0 - 0.05 || s_world > u1 + 0.05 {
return Err(R_STAIR_FORM);
}
let vc = (v0 + v1) / 2.0;
let start = [d[0] * s_world + n[0] * vc, d[1] * s_world + n[1] * vc];
Ok(StairFit { start, dir, width, going, riser, treads: k, z0, top_is_exit })
}
/// Bogen einer Bogenwand: Achse (Mitte der Dicke) von `start` nach `end` gegen den Uhrzeigersinn um
/// `center`.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ArcFit {
pub center: V2,
pub radius: f64,
pub thickness: f64,
/// Winkel (rad) von Start und Ende, `a1 > a0`.
pub a0: f64,
pub a1: f64,
}
/// Ringausschnitt: Umriss (aussen) einer senkrechten Prisma-Wand auf zwei konzentrischen Kreisen.
pub(crate) fn fit_arc_ring(ring: &[V2]) -> Option<ArcFit> {
let n = ring.len();
if n < 8 {
return None;
}
// Mittelpunkt: häufigster Umkreismittelpunkt dreier aufeinanderfolgender Punkte (Raster 1 mm).
let mut votes: std::collections::HashMap<(i64, i64), (usize, V2)> = std::collections::HashMap::new();
for i in 0..n {
let (a, b, c) = (ring[i], ring[(i + 1) % n], ring[(i + 2) % n]);
let dd = 2.0 * (a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]));
if dd.abs() < 1e-12 {
continue;
}
let (a2, b2, c2) = (a[0] * a[0] + a[1] * a[1], b[0] * b[0] + b[1] * b[1], c[0] * c[0] + c[1] * c[1]);
let cx = (a2 * (b[1] - c[1]) + b2 * (c[1] - a[1]) + c2 * (a[1] - b[1])) / dd;
let cy = (a2 * (c[0] - b[0]) + b2 * (a[0] - c[0]) + c2 * (b[0] - a[0])) / dd;
if !(cx.is_finite() && cy.is_finite()) {
continue;
}
let e = votes.entry(((cx * 1000.0).round() as i64, (cy * 1000.0).round() as i64)).or_insert((0, [cx, cy]));
e.0 += 1;
}
let (count, center) = votes.values().max_by(|a, b| a.0.cmp(&b.0).then(b.1[0].total_cmp(&a.1[0])).then(b.1[1].total_cmp(&a.1[1])))?.to_owned();
if count < n / 3 {
return None;
}
let rs: Vec<f64> = ring.iter().map(|p| (p[0] - center[0]).hypot(p[1] - center[1])).collect();
let r_in = rs.iter().copied().fold(f64::INFINITY, f64::min);
let r_out = rs.iter().copied().fold(0.0, f64::max);
let t = r_out - r_in;
if !(t >= 0.01 && t <= 2.0 && r_in > 0.05) || rs.iter().any(|r| (r - r_in).abs() > 0.002 && (r - r_out).abs() > 0.002) {
return None;
}
// Winkelbereich: grösste Lücke zwischen den sortierten Winkeln liegt ausserhalb der Wand.
let mut ang: Vec<f64> = ring.iter().map(|p| (p[1] - center[1]).atan2(p[0] - center[0])).collect();
ang.sort_by(f64::total_cmp);
let mut gap = (ang[0] + std::f64::consts::TAU - ang[ang.len() - 1], ang.len() - 1);
for i in 0..ang.len() - 1 {
if ang[i + 1] - ang[i] > gap.0 {
gap = (ang[i + 1] - ang[i], i);
}
}
let a0 = ang[(gap.1 + 1) % ang.len()];
let mut a1 = ang[gap.1];
while a1 <= a0 {
a1 += std::f64::consts::TAU;
}
let sweep = a1 - a0;
if !(sweep > 0.05 && sweep < std::f64::consts::TAU - 0.05) {
return None;
}
Some(ArcFit { center, radius: (r_in + r_out) / 2.0, thickness: t, a0, a1 })
}
#[cfg(test)]
mod tests {
use super::*;
fn quad(m: &mut Mesh, p: [V3; 4]) {
let b = m.positions.len() as u32 / 3;
for q in p {
m.positions.extend_from_slice(&q);
}
m.indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]);
}
/// Geneigte Platte über [x0,x1] × [ya,yb], Oberseite von za (bei ya) nach zb (bei yb), Dicke
/// senkrecht `t` (Unterseite parallel), Stirnseiten senkrecht.
fn plate(x0: f64, x1: f64, ya: f64, yb: f64, za: f64, zb: f64, t: f64) -> Mesh {
let mut m = Mesh::default();
let (dy, dz) = (yb - ya, zb - za);
let l = dy.hypot(dz);
// Normale der Oberseite (zeigt nach oben): (0, −dz, dy)/l bei dy > 0.
let (ny, nz) = (-dz / l * dy.signum(), dy.abs() / l);
let off = |p: V3| [p[0], p[1] - ny * t, p[2] - nz * t];
let top = [[x0, ya, za], [x1, ya, za], [x1, yb, zb], [x0, yb, zb]];
let top = if dy > 0.0 { top } else { [top[1], top[0], top[3], top[2]] };
let bot: Vec<V3> = top.iter().map(|p| off(*p)).collect();
quad(&mut m, top);
quad(&mut m, [bot[3], bot[2], bot[1], bot[0]]);
for i in 0..4 {
let j = (i + 1) % 4;
quad(&mut m, [top[j], top[i], bot[i], bot[j]]);
}
m
}
#[test]
fn saddle_roof_from_two_plates() {
// Satteldach 10 × 8, First entlang x in y = 4, Traufe z = 3, 30°.
let tan = 30f64.to_radians().tan();
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 + 4.0 * tan, 0.2);
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!((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 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));
// 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());
}
#[test]
fn flat_roof_and_capped_wall_volume() {
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(&[m]).unwrap();
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 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]);
let want = (u * 8.0 + 4.0 * 4.0) * 0.2;
assert!((v - want).abs() / want < 0.005, "{v} {want}");
}
#[test]
fn straight_stair_from_steps() {
// 5 Stufen à 0.18 × 0.28, 1.0 breit, Lauf in −y ab y = 3; Klötze von z = 0 bis zur Trittfläche.
let mut m = Mesh::default();
for i in 0..5 {
let (ya, yb) = (3.0 - 0.28 * (i + 1) as f64, 3.0 - 0.28 * i as f64);
let z = 0.18 * (i + 1) as f64;
quad(&mut m, [[2.0, ya, z], [3.0, ya, z], [3.0, yb, z], [2.0, yb, z]]);
quad(&mut m, [[2.0, yb, 0.0], [3.0, yb, 0.0], [3.0, ya, 0.0], [2.0, ya, 0.0]]);
}
let s = fit_stair(&[m]).unwrap();
assert!((s.going - 0.28).abs() < 1e-9 && (s.riser - 0.18).abs() < 1e-9 && s.treads == 5, "{s:?}");
assert!((s.dir[0]).abs() < 1e-9 && (s.dir[1] + 1.0).abs() < 1e-9);
// Antritt = Vorderkante des ersten Tritts (Dossier: Tritt i über [i·a, (i+1)·a]).
assert!((s.start[0] - 2.5).abs() < 1e-9 && (s.start[1] - 3.0).abs() < 1e-9, "{s:?}");
assert!((s.width - 1.0).abs() < 1e-9);
}
#[test]
fn arc_ring_center_radius_sweep() {
// Viertelring um (1, 2), Radien 4.9 … 5.1, von 0° bis 90°.
let mut ring = Vec::new();
for i in 0..=16 {
let a = std::f64::consts::FRAC_PI_2 * i as f64 / 16.0;
ring.push([1.0 + 5.1 * a.cos(), 2.0 + 5.1 * a.sin()]);
}
for i in (0..=16).rev() {
let a = std::f64::consts::FRAC_PI_2 * i as f64 / 16.0;
ring.push([1.0 + 4.9 * a.cos(), 2.0 + 4.9 * a.sin()]);
}
let f = fit_arc_ring(&ring).unwrap();
assert!((f.center[0] - 1.0).abs() < 1e-6 && (f.center[1] - 2.0).abs() < 1e-6);
assert!((f.radius - 5.0).abs() < 1e-9 && (f.thickness - 0.2).abs() < 1e-9);
assert!(f.a0.abs() < 1e-9 && (f.a1 - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{f:?}");
// Rechteck ist kein Ring.
assert!(fit_arc_ring(&[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]).is_none());
}
}
+1
View File
@@ -24,6 +24,7 @@ mod web_pointcloud;
pub mod ifc_step;
pub mod ifc_import;
pub mod ifc_semantic;
mod ifc_shapes;
pub mod ifc_export;
pub mod ifc_openings;
pub mod mesh_export;
+9 -2
View File
@@ -48,8 +48,8 @@ import { RecoverAutosaveDialog } from "./ui/RecoverAutosaveDialog";
import { Toast } from "./ui/Toast";
import { isTauriRuntime, PROJECT_TEMPLATE_EXT } from "./native/projectFile";
import { readStepFlat } from "./engine/truckSolid";
import { formatIfcElementsSummary, formatIfcReport, readIfcFlat } from "./io/ifcImport";
import { IfcImportDialog, type IfcImportMode } from "./ui/IfcImportDialog";
import { formatIfcElementsSummary, formatIfcReport, readIfcFlat, type IfcElementsSummary } from "./io/ifcImport";
import { IfcImportDialog, IfcImportReportDialog, type IfcImportMode } from "./ui/IfcImportDialog";
import { MeshImportHost } from "./ui/MeshImportDialog";
import { openMeshFileDialog, requestMeshImport, splitMeshFiles } from "./state/meshImportStore";
import { formatMeshReport, isMeshFile, type MeshPlacement, type MeshRead } from "./io/meshImport";
@@ -1050,6 +1050,8 @@ export default function App() {
// IFC-Import: erst die Wahl Mesh/Bauteile (`IfcImportDialog`), dann liest das Format-Modul (Web-Worker) und der
// Kern übernimmt [B3] Kontext-Meshes oder [B4] echte Bauteile als EINEN Undo-Schritt ([K4] S4, `importIfc`).
const [pendingIfc, setPendingIfc] = useState<File | null>(null);
// Bericht nach dem Bauteil-Import ([B4]): erkannt je Bauteilart, als Mesh geblieben mit Grund.
const [ifcReport, setIfcReport] = useState<{ fileName: string; summary: IfcElementsSummary } | null>(null);
const importIfcFile = (f: File) => setPendingIfc(f);
const runIfcImport = (f: File, mode: IfcImportMode) => {
const elements = mode === "elements";
@@ -1066,6 +1068,7 @@ export default function App() {
const s = r.summary;
const empty = s.walls + s.ceilings + s.columns + s.rooms + s.meshes === 0;
notify(formatIfcElementsSummary(s, report, t), empty || report.truncated ? "warning" : "info");
setIfcReport({ fileName: f.name, summary: s });
return;
}
fitToContextObjects(addedItems(r.ops, "context") as ContextObject[]);
@@ -2804,6 +2807,10 @@ export default function App() {
/>
)}
{ifcReport && (
<IfcImportReportDialog fileName={ifcReport.fileName} summary={ifcReport.summary} onClose={() => setIfcReport(null)} />
)}
{pendingDiscard && (
<UnsavedChangesDialog
onCancel={() => setPendingDiscard(null)}
+3 -2
View File
@@ -105,8 +105,9 @@ describe("Rundreise Export → Import", () => {
expect(window.classifications?.map((c) => `${c.system}:${c.code}`).sort()).toEqual(["Dossier-Ebenen:21", "eBKP-H:E"]);
const door = raw.find((o) => o.kind === "opening" && o.openingKind === "door")!;
expect(door.classifications?.map((c) => c.system)).toEqual(["Dossier-Ebenen"]);
// Dach bleibt Mesh, trägt aber seine Klassifikation.
const roof = products.find((p) => p.ifcClass === "IfcRoof")!;
// Dach wird Bauteil ([B4], 6.11.) und trägt seine Klassifikation.
expect(products.find((p) => p.ifcClass === "IfcRoof")).toBeUndefined();
const roof = raw.find((e) => e.kind === "roof")!;
expect(roof.classifications?.map((c) => c.code).sort()).toEqual(["31", "F"]);
// Räume: Kategorie bleibt (auch über die Zone).
expect(raw.filter((e) => e.kind === "space").map((s) => s.sia).sort()).toEqual(["HNF", "HNF", "NNF", "VF"]);
+30 -3
View File
@@ -2455,15 +2455,42 @@ export const de = {
"ifc.import.voids": "{n} Öffnungen nicht abgezogen",
"ifc.import.booleans": "{n} Boolesche Körper vereinfacht (nur erster Operand)",
"ifc.import.truncated": "abgebrochen: zu viele Dreiecke",
"ifc.import.elements": "{schema} importiert: {walls} Wände, {openings} Türen/Fenster, {ceilings} Decken, {columns} Stützen, {rooms} Räume, {floors} neue Geschosse; {meshes} Bauteile als Kontext-Meshes",
"ifc.import.kept": "{n} Wände/Decken/Stützen/Räume nicht sicher abbildbar, als Mesh übernommen",
"ifc.import.elements": "{schema} importiert: {walls} Wände, {openings} Türen/Fenster, {ceilings} Decken, {columns} Stützen, {rooms} Räume, {roofs} Dächer, {stairs} Treppen, {floors} neue Geschosse; {meshes} Bauteile als Kontext-Meshes",
"ifc.import.kept": "{n} Kandidaten (Wände, Decken, Dächer, Treppen …) nicht sicher abbildbar, als Mesh übernommen",
"ifc.import.classified": "{n} Bauteile mit Klassifikation (eBKP-H …); bei Kontext-Meshes im Namen vermerkt",
"ifc.importDialog.title": "IFC importieren",
"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, Decken, 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 Treppen, Stützen, 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",
"ifc.importReport.kept": "Als Mesh geblieben (Grund)",
"ifc.importReport.keptNone": "Alle Kandidaten wurden Bauteile.",
"ifc.importReport.walls": "Wände",
"ifc.importReport.openings": "Türen, Fenster, Öffnungen",
"ifc.importReport.ceilings": "Decken",
"ifc.importReport.columns": "Stützen",
"ifc.importReport.rooms": "Räume",
"ifc.importReport.roofs": "Dächer",
"ifc.importReport.stairs": "Treppen",
"ifc.importReport.floors": "Neue Geschosse",
"ifc.importReport.types": "Neue Typen (Wand, Decke, Dach, Tür, Fenster)",
"ifc.importReport.meshes": "Übrige Bauteile als Kontext-Mesh",
"ifc.importReport.close": "Schliessen",
"ifc.reason.noBody": "kein lesbarer Körper",
"ifc.reason.shape": "Körper unbrauchbar",
"ifc.reason.dimensions": "Masse ausserhalb des Abbildbaren",
"ifc.reason.notRectangular": "Grundriss weder Rechteck noch Kreisring",
"ifc.reason.slopedTop": "schräge Krone ohne erkanntes Dach darüber",
"ifc.reason.notPrism": "kein senkrechtes Prisma",
"ifc.reason.opening": "Öffnung nicht abbildbar",
"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",
"menu.native.importMesh": "3D-Modell importieren …",
"mesh.import.title": "3D-Modell importieren",
"mesh.import.failed": "3D-Modell-Import fehlgeschlagen",
+30 -3
View File
@@ -2405,15 +2405,42 @@ export const en: Record<TranslationKey, string> = {
"ifc.import.voids": "{n} openings not subtracted",
"ifc.import.booleans": "{n} boolean solids simplified (first operand only)",
"ifc.import.truncated": "aborted: too many triangles",
"ifc.import.elements": "{schema} imported: {walls} walls, {openings} doors/windows, {ceilings} slabs, {columns} columns, {rooms} rooms, {floors} new storeys; {meshes} elements as context meshes",
"ifc.import.kept": "{n} walls/slabs/columns/rooms not safely mappable, kept as mesh",
"ifc.import.elements": "{schema} imported: {walls} walls, {openings} doors/windows, {ceilings} slabs, {columns} columns, {rooms} rooms, {roofs} roofs, {stairs} stairs, {floors} new storeys; {meshes} elements as context meshes",
"ifc.import.kept": "{n} candidates (walls, slabs, roofs, stairs …) not safely mappable, kept as mesh",
"ifc.import.classified": "{n} elements with a classification (eBKP-H …); noted in the name of context meshes",
"ifc.importDialog.title": "Import IFC",
"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, slabs, 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 stairs, columns, 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",
"ifc.importReport.kept": "Kept as mesh (reason)",
"ifc.importReport.keptNone": "All candidates became building elements.",
"ifc.importReport.walls": "Walls",
"ifc.importReport.openings": "Doors, windows, openings",
"ifc.importReport.ceilings": "Slabs",
"ifc.importReport.columns": "Columns",
"ifc.importReport.rooms": "Rooms",
"ifc.importReport.roofs": "Roofs",
"ifc.importReport.stairs": "Stairs",
"ifc.importReport.floors": "New storeys",
"ifc.importReport.types": "New types (wall, slab, roof, door, window)",
"ifc.importReport.meshes": "Other elements as context mesh",
"ifc.importReport.close": "Close",
"ifc.reason.noBody": "no readable body",
"ifc.reason.shape": "body unusable",
"ifc.reason.dimensions": "dimensions out of range",
"ifc.reason.notRectangular": "plan neither rectangle nor ring segment",
"ifc.reason.slopedTop": "sloped top without a recognised roof above",
"ifc.reason.notPrism": "not a vertical prism",
"ifc.reason.opening": "opening not mappable",
"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",
"menu.native.importMesh": "Import 3D model …",
"mesh.import.title": "Import 3D model",
"mesh.import.failed": "3D model import failed",
+18 -2
View File
@@ -33,9 +33,25 @@ describe("IFC-Import als Bauteile: Rundreise Demo-Haus", () => {
const { project: p, summary, report } = await importInto(emptyProject, sampleProject);
expect(report.parseErrors).toBe(0);
expect(summary).toMatchObject({ walls: 9, openings: 3, ceilings: 1, columns: 0, rooms: 1, floors: 0, wallTypes: 0, ceilingTypes: 0, components: 0, kept: 0 });
// Dach und Treppenlauf (die IfcStair selbst hat keine Darstellung) bleiben Kontext-Mesh.
expect((p.context ?? []).map((c) => (c as { layer?: string }).layer).sort()).toEqual(["IfcRoof", "IfcStairFlight"]);
// (6.11.) Dach und Treppe kommen als Bauteile zurück, kein Kontext-Mesh mehr.
expect(summary).toMatchObject({ roofs: 1, stairs: 1, roofTypes: 0, doorTypes: 0, windowTypes: 0 });
expect(p.context ?? []).toEqual([]);
expect(validateProject(p)).toEqual([]);
// Satteldach: Umriss = Traufe samt Überstand (0.4), Überstand 0, Traufhöhe = OK OG (5.2), 30°, First x.
const roof = p.roofs![0];
expect([roof.shape, roof.ridgeAxis, roof.overhang]).toEqual(["sattel", "x", 0]);
expect(roof.pitchDeg).toBeCloseTo(30, 4);
expect(roof.baseElevation!).toBeCloseTo(5.2, 6);
expect(roof.thickness).toBeCloseTo(0.2, 6);
for (const q of [{ x: -0.4, y: -0.4 }, { x: 5.4, y: 4.4 }]) expect(roof.outline.some((g) => near(g, q, 1e-6)), JSON.stringify(roof.outline)).toBe(true);
// Gerade Treppe: gleicher Antritt, Richtung, Breite, Stufen, Steighöhe und Lauflänge.
const st0 = sampleProject.stairs![0];
const st = p.stairs![0];
expect([st.shape, st.floorId, st.stepCount]).toEqual(["straight", st0.floorId, st0.stepCount]);
expect(near(st.start, st0.start, 1e-6) && near(st.dir, st0.dir, 1e-9), JSON.stringify(st)).toBe(true);
expect(st.width).toBeCloseTo(st0.width, 6);
expect(st.runLength).toBeCloseTo(st0.runLength, 6);
expect(st.totalRise!).toBeCloseTo(st0.totalRise!, 5);
const byOrig = new Map<string, Wall>();
for (const w of sampleProject.walls) {
+11
View File
@@ -119,10 +119,17 @@ export interface IfcElementsSummary {
ceilings: number;
columns: number;
rooms: number;
/** Dächer (Flach/Pult/Sattel/Walm) und gerade Treppen ([B4]). */
roofs: number;
stairs: number;
/** Neu angelegte Geschosse. */
floors: number;
wallTypes: number;
ceilingTypes: number;
roofTypes: number;
/** Neue Tür-/Fenstertypen nach dem Typnamen der Datei (IfcDoorType/IfcWindowType). */
doorTypes: number;
windowTypes: number;
components: number;
/** Bauteile als Kontext-Mesh. */
meshes: number;
@@ -130,6 +137,8 @@ export interface IfcElementsSummary {
classified: number;
/** Davon Kandidaten, die nicht sicher abbildbar waren. */
kept: number;
/** Je IFC-Klasse die Gründe (Kennwort → Anzahl), weshalb Kandidaten Mesh blieben; Text `ifc.reason.<kennwort>`. */
keptReasons: Record<string, Record<string, number>>;
}
/** IFC-Import als Ops im Kern ([K4] S4): Antwort von `ProjectDocument.importIfc`. */
@@ -171,6 +180,8 @@ export function formatIfcElementsSummary(
ceilings: s.ceilings,
columns: s.columns,
rooms: s.rooms,
roofs: s.roofs ?? 0,
stairs: s.stairs ?? 0,
floors: s.floors,
meshes: s.meshes,
}),
+98
View File
@@ -3,6 +3,7 @@
import { useEffect, useState } from "react";
import { t } from "../i18n";
import type { IfcElementsSummary } from "../io/ifcImport";
export type IfcImportMode = "mesh" | "elements";
@@ -67,3 +68,100 @@ export function IfcImportDialog({ fileName, onImport, onCancel }: IfcImportDialo
</div>
);
}
/** Zeilen „erkannt" des Berichts: Zähler aus der Zusammenfassung des Kerns. */
const RECOGNIZED: ReadonlyArray<[string, (s: IfcElementsSummary) => number]> = [
["ifc.importReport.walls", (s) => s.walls],
["ifc.importReport.openings", (s) => s.openings],
["ifc.importReport.ceilings", (s) => s.ceilings],
["ifc.importReport.roofs", (s) => s.roofs ?? 0],
["ifc.importReport.stairs", (s) => s.stairs ?? 0],
["ifc.importReport.columns", (s) => s.columns],
["ifc.importReport.rooms", (s) => s.rooms],
["ifc.importReport.floors", (s) => s.floors],
[
"ifc.importReport.types",
(s) => s.wallTypes + s.ceilingTypes + (s.roofTypes ?? 0) + (s.doorTypes ?? 0) + (s.windowTypes ?? 0),
],
["ifc.importReport.meshes", (s) => s.meshes],
];
/** Bericht nach dem Bauteil-Import ([B4]): was erkannt wurde und was mit welchem Grund Mesh blieb. */
export function IfcImportReportDialog({
fileName,
summary,
onClose,
}: {
fileName: string;
summary: IfcElementsSummary;
onClose: () => void;
}) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape" || e.key === "Enter") onClose();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
const kept = Object.entries(summary.keptReasons ?? {}).flatMap(([cls, reasons]) =>
Object.entries(reasons).map(([why, n]) => ({ cls, why, n })),
);
return (
<div className="imp-overlay" onClick={onClose}>
<div
className="imp-dialog"
role="dialog"
aria-modal="true"
aria-label={t("ifc.importReport.title")}
onClick={(e) => e.stopPropagation()}
>
<header className="imp-head">
<span className="imp-head-title">{t("ifc.importReport.title")}</span>
<button className="imp-close" onClick={onClose} aria-label={t("export.close")}>
×
</button>
</header>
<div className="imp-body">
<section className="imp-section">
<div className="imp-section-title">
{fileName} · {t("ifc.importReport.recognized")}
</div>
<table className="imp-table">
<tbody>
{RECOGNIZED.map(([key, n]) => (
<tr key={key}>
<td>{t(key)}</td>
<td style={{ textAlign: "right" }}>{n(summary)}</td>
</tr>
))}
</tbody>
</table>
</section>
<section className="imp-section">
<div className="imp-section-title">{t("ifc.importReport.kept")}</div>
{kept.length === 0 ? (
<div className="imp-note">{t("ifc.importReport.keptNone")}</div>
) : (
<table className="imp-table">
<tbody>
{kept.map(({ cls, why, n }) => (
<tr key={`${cls}/${why}`}>
<td>{cls}</td>
<td>{t(`ifc.reason.${why}`)}</td>
<td style={{ textAlign: "right" }}>{n}</td>
</tr>
))}
</tbody>
</table>
)}
</section>
</div>
<footer className="imp-foot">
<button className="imp-btn primary" onClick={onClose}>
{t("ifc.importReport.close")}
</button>
</footer>
</div>
</div>
);
}