[B4] [B3] IFC-Import zu echten Bauteilen (wählbar), Farbe und GlobalId am Kontext-Mesh

- Rust (fileio/ifc_semantic.rs, import_ifc_elements): erkennt Wände (Rechteck im Grundriss,
  Achse, Dicke, Höhe, Enden auf anstossende Achsen, Schichtseite aus Usage/Bändern/aussen),
  Türen/Fenster/Durchbrüche in Wandöffnungen, Decken (Prisma, Löcher/Öffnungen), Stützen
  (Rechteck/Kreis), Räume (IfcSpace), Geschosse; nicht sicher Abbildbares bleibt Mesh.
- TS (io/ifcElements.ts): Geschosse/Wand-/Deckentypen/Materialien wiederverwenden oder anlegen,
  Übernahme über setProject (Ops); Import-Dialog Mesh|Bauteile, CLI import-ifc --elements.
- [B3]: ImportedMesh.color (#rrggbb) und ifcGlobalId, Name ohne GlobalId.
- Rundreise Demo-Haus: alle Wände, Öffnungen, Decke, Raum gleich wie das Original.

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 13:02:02 +00:00
1 parent 5ef3d07efa
commit a5394d7bfa
14 files changed
+2563 -161

No files matched your search

+29 -7
View File
@@ -280,7 +280,7 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
- ○ **[65] Explosionsaxonometrie.** · S–M
- ○ **[66] Präsentationspläne mit einem Klick.** · M
- ○ **[67] Skizzenstil.** · M
- ◐ **[25] IFC-Import** → [B3] ✅ (Mesh), [B4] ○. · L
- ◐ **[25] IFC-Import** → [B3] ✅ (Mesh), [B4] ◐ (Bauteile). · L
- ◐ **[26] Dächer über beliebige Grundrisse.** `geometry/roofSkeleton.ts` (Walm/Sattel/Mansarde/
Krüppelwalm auf L/T/U, Kehlen, Giebel); Port nach Rust läuft [K2]. Offen: Innenhöfe, schiefwinklige
Grundrisse → [B2]. · M
@@ -325,12 +325,34 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module
und 39 von 46 IFC4.3-sample-models gleich (≤ 3 %; nur lokal, nicht eingecheckt). Offen:
IfcAdvancedBrep (NURBS), IFC4.3-Ausrichtung (IfcGradientCurve, IfcLinearPlacement,
IfcSectionedSolidHorizontal), IfcGridPlacement, B-Spline-Kurven, StartParam/EndParam der Sweeps,
Profil-Kantenradien/Neigungen; Farbe/GlobalId gelesen, aber `ImportedMesh` hat kein Feld dafür
(GlobalId steht im Namen); CSG bei sehr grossen Netzen (> 200 000 Dreiecke) übersprungen; nur
Linux-Container/vitest, nicht in der Tauri-App geprüft (Worker nur mit Attrappe getestet). · M
- ○ **[B4] IFC-Import zu echten Bauteilen** (zweite Stufe von [25]). · L · nach [B3]. Stand 28.10.:
Geometrie-Grundlage steht (Öffnungen/Booleans/Sweeps als Mesh, [B3]); offen: Wand/Decke/Stütze aus
Extrusion + Achse erkennen, Öffnungen als `Opening` statt abgezogen, Material/Typ übernehmen.
Profil-Kantenradien/Neigungen; CSG bei sehr grossen Netzen (> 200 000 Dreiecke) übersprungen; nur
Linux-Container/vitest, nicht in der Tauri-App geprüft (Worker nur mit Attrappe getestet).
(28.10., 3. Schritt) `ImportedMesh.color` (`#rrggbb` aus Stil/Material) und `ifcGlobalId` gefüllt,
Name ohne GlobalId; Rundreise Speichern/Laden getestet. Offen: Anzeige der Farbe in 3D —
`plan/toWalls3d.ts::emitMeshes` setzt für Kontext-Meshes fest `IMPORTED_RGB`; Vorschlag: dort
`obj.color` (über `hexToRgb`/255) nehmen, falls gesetzt (der Plan zeichnet nur Umrisse in der
Ebenenfarbe). · M
- ◐ **[B4] IFC-Import zu echten Bauteilen** (zweite Stufe von [25]). · L · nach [B3]. Stand 28.10.:
Wahl im Import-Dialog (`ui/IfcImportDialog.tsx`: Kontext-Meshes = Standard | Bauteile), CLI
`import-ifc … --elements`. Erkennung in Rust (`fileio/src/ifc_semantic.rs`, `import_ifc_elements`),
über die Körperform statt den Darstellungstyp: Wand = Rechteck im Grundriss (kleinstes umschliessendes
Rechteck, unten eben, oben ≥ 35 % eben, Volumen 70–100 %), Achse = Mitte, Enden auf die Achse
anstossender Wände gezogen (L/T), Schichten aus IfcMaterialLayerSet(Usage) von Bauteil oder Typ,
Seite der Aussenschicht aus Usage, sonst Schicht-Bändern, sonst „weg vom Geschoss-Schwerpunkt";
Öffnungen (quaderförmig, durch die ganze Wand) → Tür/Fenster/Wanddurchbruch (sonst bleibt die Wand
Mesh); IfcSlab als senkrechtes Prisma → Decke (Löcher + durchgehende Öffnungen als
Deckenöffnungen, nicht Teil eines Daches); IfcColumn Rechteck/Kreis → Stütze; IfcSpace (Prisma ohne
Loch) → Raum (LongName, SIA 416 aus `CH_Raum`); Geschosse nach Höhe wiederverwendet (±5 mm) oder
angelegt. TS (`io/ifcElements.ts`) ordnet nur zu: Wand-/Deckentyp nach Schichten (Material + Dicke)
wiederverwenden oder anlegen, Materialien nach Namen; Projekt über `setProject` (Ops). Rundreise
Demo-Haus (Export → Import als Bauteile in `emptyProject`): alle 9 Wände (Achse, Richtung, Typ, Höhe,
Geschoss), 3 Öffnungen (Lage, Grösse, Brüstung, Typ), Decke, Raum gleich, keine neuen Typen;
Dach/Treppe bleiben Mesh. buildingSMART Sample-Test-Files (35, lokal): alle lesbar, Ergebnis gültig;
erkannt v. a. Räume, Stützen, `wall-with-opening-and-window` (Wand + Fenster); die Simple-Scene-Wände
sind Giebelwände (bleiben Mesh). Offen: Dächer, Treppen, Träger, schräge/gekrümmte Wände, Wände mit
Profiländerung, Decken aus Dreiecksnetzen mit T-Stössen (zwei Teilflächen → Mesh), Tür-Anschlag/
Öffnungsrichtung, Tür-/Fenstertyp aus IfcDoorType/IfcWindowType, Farbe der Bauteile; nur Linux-
Container/vitest, nicht in der Tauri-App geprüft (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
+213 -114
View File
@@ -1,7 +1,8 @@
// IFC-Import als Mesh ([B3], erste Stufe von [25]): liest aus einer IFC-Datei (IFC2x3, IFC4, IFC4.3)
// je Bauteil (IfcProduct mit Körper-Darstellung) GlobalId, Klasse, Name, Geschoss, Farbe und
// Dreiecke in Metern (Weltkoordinaten der Datei, Z = Höhe). Daraus werden auf der TS-Seite
// importierte Kontext-Meshes (`src/io/ifcImport.ts`); echte Bauteile kommen mit [B4].
// importierte Kontext-Meshes (`src/io/ifcImport.ts`); echte Bauteile erkennt auf Wunsch
// `ifc_semantic.rs` ([B4], `import_ifc_opts(…, true)`), sie fehlen dann unter den Meshes.
//
// Eigener Code (nichts aus BIMCraft `import.rs` übernommen; BIMCraft rechnet in mm, hier Meter).
//
@@ -141,6 +142,14 @@ impl Xf {
fn is_finite(&self) -> bool {
self.r.iter().flatten().chain(self.t.iter()).all(|v| v.is_finite())
}
/// Ursprung (Verschiebung) der Abbildung.
pub(crate) fn origin(&self) -> V3 {
self.t
}
/// Bildet eine Richtung ab (ohne Verschiebung).
pub(crate) fn apply_dir(&self, v: V3) -> V3 {
Xf { r: self.r, t: [0.0; 3] }.apply(v)
}
}
/// 2D-Abbildung p' = A·p + t (für Profil-Lagen).
@@ -475,6 +484,8 @@ pub struct IfcImport {
pub parse_errors: usize,
/// Abbruch wegen Dreiecks-Obergrenze.
pub truncated: bool,
/// Erkannte Bauteile ([B4]), nur mit [`import_ifc_opts`]`(…, true)`.
pub elements: Option<crate::ifc_semantic::Semantic>,
}
/// Bauteilklassen, die als Mesh keinen Sinn ergeben (Volumen-Hilfskörper, Beschriftung).
@@ -497,9 +508,9 @@ const NON_BODY_REPS: &[&str] = &[
// Leser
// ---------------------------------------------------------------------------
struct Reader<'a> {
f: &'a StepFile,
len_scale: f64,
pub(crate) struct Reader<'a> {
pub(crate) f: &'a StepFile,
pub(crate) len_scale: f64,
angle_scale: f64,
placements: HashMap<u64, Xf>,
item_colors: HashMap<u64, [f64; 4]>,
@@ -593,7 +604,7 @@ impl<'a> Reader<'a> {
}
/// Objekt-Platzierung in Weltkoordinaten (IfcLocalPlacement-Kette, zwischengespeichert).
fn object_placement(&mut self, id: u64, depth: usize) -> Xf {
pub(crate) fn object_placement(&mut self, id: u64, depth: usize) -> Xf {
if let Some(x) = self.placements.get(&id) {
return *x;
}
@@ -1372,9 +1383,9 @@ impl<'a> Reader<'a> {
// ---- Bauteile ---------------------------------------------------------------------------
/// Körper eines Bauteils in Weltkoordinaten (ohne Öffnungen) und erste Elementfarbe; `None` ohne
/// Körper-Darstellung. Hört nach etwa `max_tris` Dreiecken auf.
fn product_body(&mut self, id: u64, max_tris: usize) -> Option<(Mesh, Option<[f64; 4]>)> {
/// Platzierung und Körper-Elemente (ids der Darstellungselemente) eines Bauteils; `None` ohne
/// Körper-Darstellung.
fn body_items(&mut self, id: u64) -> Option<(Xf, Vec<u64>)> {
let f = self.f;
let e = f.get(id)?;
// IfcProduct: Representation (Attribut 7) zeigt auf eine IfcProductDefinitionShape.
@@ -1396,14 +1407,19 @@ impl<'a> Reader<'a> {
Some(p) => self.object_placement(p, 0),
None => Xf::IDENTITY,
};
Some((place, chosen.iter().flat_map(|rep| refs(rep.arg(3))).collect()))
}
/// Körper eines Bauteils in Weltkoordinaten (ohne Öffnungen) und erste Elementfarbe; `None` ohne
/// Körper-Darstellung. Hört nach etwa `max_tris` Dreiecken auf.
pub(crate) fn product_body(&mut self, id: u64, max_tris: usize) -> Option<(Mesh, Option<[f64; 4]>)> {
let (place, items) = self.body_items(id)?;
let mut local = Mesh::default();
let mut color = None;
'reps: for rep in chosen {
for it in refs(rep.arg(3)) {
self.item(it, &mut local, 0, &mut color);
if local.triangle_count() > max_tris {
break 'reps;
}
for it in items {
self.item(it, &mut local, 0, &mut color);
if local.triangle_count() > max_tris {
break;
}
}
let mut mesh = Mesh::default();
@@ -1411,6 +1427,27 @@ impl<'a> Reader<'a> {
Some((mesh, color))
}
/// 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> {
let Some((place, items)) = self.body_items(id) else { return Vec::new() };
let mut out = Vec::new();
let mut total = 0;
for it in items {
let mut local = Mesh::default();
let mut color = None;
self.item(it, &mut local, 0, &mut color);
total += local.triangle_count();
let mut mesh = Mesh::default();
mesh.append(&local, &place);
out.push(mesh);
if total > max_tris {
break;
}
}
out
}
// ---- Farben ----------------------------------------------------------------------------
fn style_color(&self, styles: &[Value], depth: usize) -> Option<[f64; 4]> {
@@ -1509,8 +1546,128 @@ fn units(f: &StepFile, ids: &[u64]) -> (f64, f64) {
(len_scale, angle_scale)
}
/// Beziehungen der Datei, die Mesh- und Bauteil-Import ([B4]) brauchen.
#[derive(Default)]
pub(crate) struct Rels {
/// Bauteil → räumliche Struktur (IfcRelContainedInSpatialStructure).
pub container: HashMap<u64, u64>,
/// Teil → Ganzes (IfcRelAggregates).
pub parent: HashMap<u64, u64>,
/// Objekt (auch Typ) → Material (IfcRelAssociatesMaterial).
pub material_of: HashMap<u64, u64>,
/// Material → Farbe (IfcMaterialDefinitionRepresentation).
pub material_color: HashMap<u64, [f64; 4]>,
/// Wirt → Öffnungen (IfcRelVoidsElement).
pub voids: HashMap<u64, Vec<u64>>,
}
impl Rels {
/// Material (auch Schichten/Profile/Bestandteile/Listen) → Farbe des ersten Materials.
pub(crate) fn resolve_material_color(&self, f: &StepFile, mut m: u64) -> Option<[f64; 4]> {
for _ in 0..6 {
if let Some(c) = self.material_color.get(&m) {
return Some(*c);
}
let e = f.get(m)?;
let next = match e.ty.as_str() {
"IFCMATERIALLAYERSETUSAGE" | "IFCMATERIALPROFILESETUSAGE" | "IFCMATERIALPROFILESETUSAGETAPERING" => e.arg(0),
"IFCMATERIALLAYERSET" | "IFCMATERIALLIST" => e.arg(0).and_then(|v| v.as_list()).and_then(|l| l.first()),
"IFCMATERIALPROFILESET" | "IFCMATERIALCONSTITUENTSET" => e.arg(2).and_then(|v| v.as_list()).and_then(|l| l.first()),
"IFCMATERIALLAYER" => e.arg(0),
"IFCMATERIALPROFILE" | "IFCMATERIALCONSTITUENT" => e.arg(2),
_ => None,
};
m = next?.as_ref_id()?;
}
None
}
/// Geschoss (IfcBuildingStorey-id) eines Bauteils: Enthaltensein, sonst aufwärts über Aggregation.
pub(crate) fn storey_id(&self, f: &StepFile, mut id: u64) -> Option<u64> {
for _ in 0..32 {
let e = f.get(id)?;
if e.ty == "IFCBUILDINGSTOREY" {
return Some(id);
}
id = match self.container.get(&id) {
Some(s) => *s,
None => *self.parent.get(&id)?,
};
}
None
}
fn gather(f: &StepFile, ids: &[u64], r: &mut Reader) -> Rels {
let mut rels = Rels::default();
let refs = |v: Option<&Value>| -> Vec<u64> { v.and_then(|v| v.as_list()).unwrap_or(&[]).iter().filter_map(|x| x.as_ref_id()).collect() };
for &id in ids {
let e = &f.entities[&id];
match e.ty.as_str() {
"IFCRELCONTAINEDINSPATIALSTRUCTURE" => {
if let Some(s) = e.arg(5).and_then(|v| v.as_ref_id()) {
for el in refs(e.arg(4)) {
rels.container.entry(el).or_insert(s);
}
}
}
"IFCRELAGGREGATES" => {
if let Some(p) = e.arg(4).and_then(|v| v.as_ref_id()) {
for c in refs(e.arg(5)) {
rels.parent.entry(c).or_insert(p);
}
}
}
"IFCRELASSOCIATESMATERIAL" => {
if let Some(m) = e.arg(5).and_then(|v| v.as_ref_id()) {
for o in refs(e.arg(4)) {
rels.material_of.entry(o).or_insert(m);
}
}
}
"IFCRELVOIDSELEMENT" => {
if let (Some(h), Some(o)) = (e.arg(4).and_then(|v| v.as_ref_id()), e.arg(5).and_then(|v| v.as_ref_id())) {
rels.voids.entry(h).or_default().push(o);
}
}
"IFCSTYLEDITEM" => {
if let Some(item) = e.arg(0).and_then(|v| v.as_ref_id()) {
if let Some(c) = e.arg(1).and_then(|v| v.as_list()).and_then(|l| r.style_color(l, 0)) {
r.item_colors.entry(item).or_insert(c);
}
}
}
"IFCMATERIALDEFINITIONREPRESENTATION" => {
if let Some(m) = e.arg(3).and_then(|v| v.as_ref_id()) {
'reps: for rep in refs(e.arg(2)) {
for it in refs(f.get(rep).and_then(|x| x.arg(3))) {
let Some(si) = f.get(it) else { continue };
if si.ty != "IFCSTYLEDITEM" {
continue;
}
if let Some(c) = si.arg(1).and_then(|v| v.as_list()).and_then(|l| r.style_color(l, 0)) {
rels.material_color.entry(m).or_insert(c);
break 'reps;
}
}
}
}
}
_ => {}
}
}
rels
}
}
/// Liest eine IFC-Datei als Meshes je Bauteil.
pub fn import_ifc(bytes: &[u8]) -> Result<IfcImport, String> {
import_ifc_opts(bytes, false)
}
/// Wie [`import_ifc`]; mit `elements` werden zusätzlich echte Bauteile erkannt ([B4],
/// `ifc_semantic.rs`): Wände, Decken, Stützen, Türen/Fenster in Wandöffnungen, Räume, Geschosse.
/// Erkannte Bauteile (und ihre Türen/Fenster) fehlen dann in `products`.
pub fn import_ifc_opts(bytes: &[u8], elements: bool) -> Result<IfcImport, String> {
let f = ifc_step::parse(bytes)?;
if !f.schema.is_empty() && !f.schema.starts_with("IFC") {
return Err(format!("kein IFC-Schema: {}", f.schema));
@@ -1536,108 +1693,26 @@ pub fn import_ifc(bytes: &[u8]) -> Result<IfcImport, String> {
let mut result = IfcImport { schema: f.schema.clone(), length_scale: len_scale, parse_errors: f.errors, ..Default::default() };
// Beziehungen: Geschoss-Zugehörigkeit, Aggregation, Material, Farben.
let mut container: HashMap<u64, u64> = HashMap::new();
let mut parent: HashMap<u64, u64> = HashMap::new();
let mut material_of: HashMap<u64, u64> = HashMap::new();
let mut material_color: HashMap<u64, [f64; 4]> = HashMap::new();
let mut voids: HashMap<u64, Vec<u64>> = HashMap::new();
let refs = |v: Option<&Value>| -> Vec<u64> { v.and_then(|v| v.as_list()).unwrap_or(&[]).iter().filter_map(|x| x.as_ref_id()).collect() };
for &id in &ids {
let e = &f.entities[&id];
match e.ty.as_str() {
"IFCRELCONTAINEDINSPATIALSTRUCTURE" => {
if let Some(s) = e.arg(5).and_then(|v| v.as_ref_id()) {
for el in refs(e.arg(4)) {
container.entry(el).or_insert(s);
}
}
}
"IFCRELAGGREGATES" => {
if let Some(p) = e.arg(4).and_then(|v| v.as_ref_id()) {
for c in refs(e.arg(5)) {
parent.entry(c).or_insert(p);
}
}
}
"IFCRELASSOCIATESMATERIAL" => {
if let Some(m) = e.arg(5).and_then(|v| v.as_ref_id()) {
for o in refs(e.arg(4)) {
material_of.entry(o).or_insert(m);
}
}
}
"IFCRELVOIDSELEMENT" => {
if let (Some(h), Some(o)) = (e.arg(4).and_then(|v| v.as_ref_id()), e.arg(5).and_then(|v| v.as_ref_id())) {
voids.entry(h).or_default().push(o);
}
}
"IFCSTYLEDITEM" => {
if let Some(item) = e.arg(0).and_then(|v| v.as_ref_id()) {
if let Some(c) = e.arg(1).and_then(|v| v.as_list()).and_then(|l| r.style_color(l, 0)) {
r.item_colors.entry(item).or_insert(c);
}
}
}
"IFCMATERIALDEFINITIONREPRESENTATION" => {
if let Some(m) = e.arg(3).and_then(|v| v.as_ref_id()) {
'reps: for rep in refs(e.arg(2)) {
for it in refs(f.get(rep).and_then(|x| x.arg(3))) {
let Some(si) = f.get(it) else { continue };
if si.ty != "IFCSTYLEDITEM" {
continue;
}
if let Some(c) = si.arg(1).and_then(|v| v.as_list()).and_then(|l| r.style_color(l, 0)) {
material_color.entry(m).or_insert(c);
break 'reps;
}
}
}
}
}
_ => {}
}
}
// Material (auch Schichten/Profile/Bestandteile/Listen) → Farbe des ersten Materials.
let resolve_material_color = |mut m: u64| -> Option<[f64; 4]> {
for _ in 0..6 {
if let Some(c) = material_color.get(&m) {
return Some(*c);
}
let e = f.get(m)?;
let next = match e.ty.as_str() {
"IFCMATERIALLAYERSETUSAGE" | "IFCMATERIALPROFILESETUSAGE" | "IFCMATERIALPROFILESETUSAGETAPERING" => e.arg(0),
"IFCMATERIALLAYERSET" | "IFCMATERIALLIST" => e.arg(0).and_then(|v| v.as_list()).and_then(|l| l.first()),
"IFCMATERIALPROFILESET" | "IFCMATERIALCONSTITUENTSET" => e.arg(2).and_then(|v| v.as_list()).and_then(|l| l.first()),
"IFCMATERIALLAYER" => e.arg(0),
"IFCMATERIALPROFILE" | "IFCMATERIALCONSTITUENT" => e.arg(2),
_ => None,
};
m = next?.as_ref_id()?;
}
None
let rels = Rels::gather(&f, &ids, &mut r);
let voids = &rels.voids;
let parent = &rels.parent;
let material_of = &rels.material_of;
let resolve_material_color = |m: u64| rels.resolve_material_color(&f, m);
let storey_of = |id: u64| -> Option<String> {
let s = f.get(rels.storey_id(&f, id)?)?;
let name = s.arg(2).and_then(|v| v.as_str()).or_else(|| s.arg(7).and_then(|v| v.as_str()));
Some(name.unwrap_or("").to_string())
};
let storey_of = |mut id: u64| -> Option<String> {
for _ in 0..32 {
let e = f.get(id)?;
if e.ty == "IFCBUILDINGSTOREY" {
let name = e.arg(2).and_then(|v| v.as_str()).or_else(|| e.arg(7).and_then(|v| v.as_str()));
return Some(name.unwrap_or("").to_string());
}
id = match container.get(&id) {
Some(s) => *s,
None => *parent.get(&id)?,
};
}
None
};
// Bauteil-Import ([B4]): erkannte Bauteile kommen nicht als Mesh.
let semantic = elements.then(|| crate::ifc_semantic::analyze(&mut r, &rels, &ids));
let converted: HashSet<u64> = semantic.as_ref().map(|s| s.converted.clone()).unwrap_or_default();
let mut total_tris = 0usize;
for &id in &ids {
let e = &f.entities[&id];
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 !has_shape {
if !has_shape || converted.contains(&id) {
continue;
}
if SKIP_CLASSES.contains(&e.ty.as_str()) {
@@ -1697,6 +1772,7 @@ pub fn import_ifc(bytes: &[u8]) -> Result<IfcImport, String> {
}
result.skipped_items = r.skipped;
result.simplified_booleans = r.simplified;
result.elements = semantic;
Ok(result)
}
@@ -1725,7 +1801,7 @@ const CLASS_NAMES: &[&str] = &[
"IfcWallElementedCase", "IfcWallStandardCase", "IfcWasteTerminal", "IfcWindow", "IfcWindowStandardCase",
];
fn class_name(upper: &str) -> String {
pub(crate) fn class_name(upper: &str) -> String {
CLASS_NAMES.iter().find(|c| c.eq_ignore_ascii_case(upper)).map_or_else(|| upper.to_string(), |c| c.to_string())
}
@@ -1808,12 +1884,14 @@ mod web {
use wasm_bindgen::prelude::*;
/// Ergebnis für JS: `meta` (JSON: Bauteile mit Längen der Puffer, Bericht), `positions()`
/// (alle Bauteile hintereinander, x,y,z in m), `indices()` (je Bauteil ab 0).
/// (alle Bauteile hintereinander, x,y,z in m), `indices()` (je Bauteil ab 0), `elementData()`
/// (Zahlen der erkannten Bauteile, [B4], s. `ifc_semantic::encode`; leer beim reinen Mesh-Import).
#[wasm_bindgen]
pub struct IfcImportResult {
meta: String,
positions: Vec<f64>,
indices: Vec<u32>,
element_data: Vec<f64>,
}
#[wasm_bindgen]
@@ -1828,12 +1906,27 @@ mod web {
pub fn indices(&self) -> Vec<u32> {
self.indices.clone()
}
#[wasm_bindgen(js_name = elementData)]
pub fn element_data(&self) -> Vec<f64> {
self.element_data.clone()
}
}
/// IFC-Bytes → Meshes je Bauteil. Unlesbare Datei → JS-Fehler mit Meldung (kein Panic).
#[wasm_bindgen]
pub fn import_ifc(bytes: &[u8]) -> Result<IfcImportResult, JsValue> {
let r = super::import_ifc(bytes).map_err(|e| JsValue::from_str(&e))?;
encode(super::import_ifc(bytes).map_err(|e| JsValue::from_str(&e))?)
}
/// Wie `import_ifc`, dazu echte Bauteile ([B4]): `meta.elements` (Wände, Öffnungen, Decken,
/// Stützen, Räume; Texte und Verweise) mit Zahlen in `elementData()`, `meta.storeys`; erkannte
/// Bauteile fehlen in den Meshes.
#[wasm_bindgen]
pub fn import_ifc_elements(bytes: &[u8]) -> Result<IfcImportResult, JsValue> {
encode(super::import_ifc_opts(bytes, true).map_err(|e| JsValue::from_str(&e))?)
}
fn encode(r: super::IfcImport) -> Result<IfcImportResult, JsValue> {
let mut positions = Vec::new();
let mut indices = Vec::new();
let products: Vec<serde_json::Value> = r
@@ -1853,7 +1946,7 @@ mod web {
})
})
.collect();
let meta = serde_json::json!({
let mut meta = serde_json::json!({
"schema": r.schema,
"lengthScale": r.length_scale,
"products": products,
@@ -1866,7 +1959,13 @@ mod web {
"parseErrors": r.parse_errors,
"truncated": r.truncated,
});
Ok(IfcImportResult { meta: meta.to_string(), positions, indices })
let mut element_data = Vec::new();
if let Some(sem) = &r.elements {
let (v, data) = crate::ifc_semantic::encode(sem);
meta["elements"] = v;
element_data = data;
}
Ok(IfcImportResult { meta: meta.to_string(), positions, indices, element_data })
}
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -18,6 +18,7 @@ pub mod split;
mod web_import;
pub mod ifc_step;
pub mod ifc_import;
pub mod ifc_semantic;
pub mod ifc_export;
pub mod csg;
mod ifc_sweep;
+45 -2
View File
@@ -55,6 +55,8 @@ import { Toast } from "./ui/Toast";
import { isTauriRuntime, PROJECT_TEMPLATE_EXT } from "./native/projectFile";
import { stepTextToImportedMeshes } from "./io/stepImport";
import { formatIfcReport, ifcBytesToImportedMeshes } from "./io/ifcImport";
import { formatIfcElementsSummary, ifcElementsToProject, readIfcElements } from "./io/ifcElements";
import { IfcImportDialog, type IfcImportMode } from "./ui/IfcImportDialog";
import { projectGeoOrigin } from "./model/geoRebase";
import { applyClashMarkers, runClashCheck } from "./analysis/clash";
import { checkForUpdate } from "./update/checkForUpdate";
@@ -1698,8 +1700,37 @@ export default function App() {
setRoomStamp,
} = useProjectActions(setProject, notify, planViewRef);
// IFC-Import ([B3]): Bauteile als Kontext-Meshes (Format-Modul, `io/ifcImport.ts`), Bericht als Toast.
const importIfcFile = (f: File) => {
// IFC-Import: erst die Wahl Mesh/Bauteile (`IfcImportDialog`), dann [B3] Kontext-Meshes
// (`io/ifcImport.ts`) oder [B4] echte Bauteile (`io/ifcElements.ts`, übernommen über setProject).
const [pendingIfc, setPendingIfc] = useState<File | null>(null);
const importIfcFile = (f: File) => setPendingIfc(f);
const runIfcImport = (f: File, mode: IfcImportMode) => {
if (mode === "elements") {
void f
.arrayBuffer()
.then((buf) => readIfcElements(new Uint8Array(buf)))
.then(({ products, report, elements }) => {
let summary: ReturnType<typeof ifcElementsToProject>["summary"] | null = null;
let bounds: { x: number; y: number }[] = [];
setProject((p) => {
const r = ifcElementsToProject(p, products, elements, { fileName: f.name, geoOrigin: projectGeoOrigin(p) });
summary = r.summary;
const added = new Set(p.walls.map((w) => w.id));
bounds = r.project.walls.filter((w) => !added.has(w.id)).flatMap((w) => [w.start, w.end]);
return r.project;
});
if (bounds.length) planViewRef.current?.fitBounds(bounds);
if (summary) {
const s: ReturnType<typeof ifcElementsToProject>["summary"] = summary;
const empty = s.walls + s.ceilings + s.columns + s.rooms + s.meshes === 0;
notify(formatIfcElementsSummary(s, report, t), empty || report.truncated ? "warning" : "info");
}
})
.catch((err) =>
notify(`${t("ifc.import.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"),
);
return;
}
void f
.arrayBuffer()
.then((buf) => ifcBytesToImportedMeshes(new Uint8Array(buf), f.name, { geoOrigin: projectGeoOrigin(project) }))
@@ -3998,6 +4029,18 @@ export default function App() {
/>
)}
{pendingIfc && (
<IfcImportDialog
fileName={pendingIfc.name}
onCancel={() => setPendingIfc(null)}
onImport={(mode) => {
const f = pendingIfc;
setPendingIfc(null);
runIfcImport(f, mode);
}}
/>
)}
{pendingDiscard && (
<UnsavedChangesDialog
onCancel={() => setPendingDiscard(null)}
+20 -4
View File
@@ -9,8 +9,9 @@
// dossier-cli <projekt.obp> section <Name> [--out schnitt.svg] (braucht render3d-WASM)
// dossier-cli <projekt.obp> elevation <Name> [--out ansicht.svg]
// dossier-cli <projekt.obp> dxf|dwg|ifc|step|obj|stl|schedule|kennzahlen|sun [--level EG] [--out datei]
// dossier-cli <projekt.obp> import-ifc <datei.ifc> [--out neu.obp] [--group product|class]
// IFC als Kontext-Meshes ([B3]); Bericht als JSON auf stdout
// dossier-cli <projekt.obp> import-ifc <datei.ifc> [--out neu.obp] [--group product|class] [--elements]
// IFC als Kontext-Meshes ([B3]), mit --elements als echte
// Bauteile ([B4]); Bericht als JSON auf stdout
// dossier-cli <projekt.obp> model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png)
// dossier-cli <projekt.obp> mcp MCP-Server (stdio): project_info, query, render_svg, apply_ops, validate
// dossier-cli <projekt.obp> bench [--runs 10] Zeitprofil der Ableitungen (ms je Aufruf)
@@ -25,6 +26,8 @@ import {
buildPlanDwg,
loadFileio,
readIfc,
readIfcElements,
ifcElementsToProject,
ifcToImportedMeshes,
projectGeoOrigin,
ensureContextCategories,
@@ -269,9 +272,22 @@ export async function run(argv: string[]): Promise<number> {
} catch (e) {
fail(`Datei nicht lesbar: ${src} (${e instanceof Error ? e.message : String(e)})`);
}
const { products, report } = await readIfc(bytes);
const group = args.flags.get("group");
const meshes = ifcToImportedMeshes(products, src.split(/[\\/]/).pop() ?? src, {
const fileName = src.split(/[\\/]/).pop() ?? src;
if (args.flags.has("elements")) {
const { products, report, elements } = await readIfcElements(bytes);
const r = ifcElementsToProject(project, products, elements, {
fileName,
geoOrigin: projectGeoOrigin(project),
group: group === "product" || group === "class" ? group : "auto",
});
process.stdout.write(JSON.stringify({ ...report, products: undefined, elements: r.summary, kept: elements.kept }, null, 2) + "\n");
const target = args.flags.get("out");
if (target) out(args, serializeProject(applyOps(project, diffToOps(project, r.project))), target);
return 0;
}
const { products, report } = await readIfc(bytes);
const meshes = ifcToImportedMeshes(products, fileName, {
geoOrigin: projectGeoOrigin(project),
group: group === "product" || group === "class" ? group : "auto",
});
+1
View File
@@ -7,6 +7,7 @@ export { buildPlanDxf } from "../export/exportDxf";
export { buildPlanDwg } from "../export/exportDxf";
export { loadFileio } from "../engine/fileioWasm";
export { readIfc, ifcToImportedMeshes } from "../io/ifcImport";
export { readIfcElements, ifcElementsToProject } from "../io/ifcElements";
export { projectGeoOrigin } from "../model/geoRebase";
export { ensureContextCategories } from "../model/contextCategories";
export { projectToWorldCoords } from "../model/geoRebase";
+8
View File
@@ -1763,6 +1763,14 @@ 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.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.import": "Importieren",
"recover.title": "Ungesicherte Arbeit gefunden",
"recover.message": "Von „{name}“ gibt es eine automatische Sicherung vom {when}, die nicht gespeichert wurde.",
"recover.unsaved": "unbenanntes Projekt",
+8
View File
@@ -1724,6 +1724,14 @@ 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.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.import": "Import",
"recover.title": "Unsaved work found",
"recover.message": "There is an automatic backup of “{name}” from {when} that was never saved.",
"recover.unsaved": "untitled project",
+201
View File
@@ -0,0 +1,201 @@
// IFC-Import zu echten Bauteilen ([B4]): Rundreise eigener Export → Import als Bauteile → gleiche
// Wände/Öffnungen/Decken/Räume (Lage, Dicke, Höhe, Typ) wie das Original (Demo-Haus); dazu Farbe und
// GlobalId am Kontext-Mesh ([B3]-Nachtrag) und die Speichern/Laden-Rundreise.
import "../engine/fileioWasm.setup";
import { describe, expect, it } from "vitest";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { applyOps, diffToOps, validateProject } from "../core/ops";
import { exportIfcSpf } from "../export/exportIfc";
import { emptyProject, sampleProject } from "../model/sampleProject";
import type { Column, Opening, Project, Vec2, Wall } from "../model/types";
import { wallTypeThickness } from "../model/types";
import { formatIfcElementsSummary, ifcElementsToProject, readIfcElements } from "./ifcElements";
import { ifcToImportedMeshes, readIfc, type IfcProduct } from "./ifcImport";
import { parseProjectFile, serializeProject } from "./projectFormat";
const bytesOf = (s: string) => new TextEncoder().encode(s);
const near = (a: Vec2, b: Vec2, tol = 1e-6) => Math.hypot(a.x - b.x, a.y - b.y) <= tol;
const symmetric = (p: Project, wallTypeId: string) => {
const l = p.wallTypes.find((t) => t.id === wallTypeId)!.layers;
return l.every((x, i) => x.componentId === l[l.length - 1 - i].componentId && Math.abs(x.thickness - l[l.length - 1 - i].thickness) < 1e-9);
};
async function importInto(base: Project, src: Project) {
const { products, report, elements } = await readIfcElements(bytesOf(exportIfcSpf(src)));
const r = ifcElementsToProject(base, products, elements, { fileName: "haus.ifc" });
return { ...r, report, elements, products };
}
describe("IFC-Import als Bauteile: Rundreise Demo-Haus", () => {
it("gleiche Wände (Achse, Typ, Höhe, Geschoss), Öffnungen, Decke, Raum; Rest als Mesh", async () => {
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 Treppe bleiben Kontext-Mesh.
expect((p.context ?? []).map((c) => (c as { layer?: string }).layer).sort()).toEqual(["IfcRoof", "IfcStair"]);
expect(validateProject(p)).toEqual([]);
const byOrig = new Map<string, Wall>();
for (const w of sampleProject.walls) {
const sym = symmetric(sampleProject, w.wallTypeId);
const got = p.walls.find(
(g) =>
g.floorId === w.floorId &&
((near(g.start, w.start) && near(g.end, w.end)) || (sym && near(g.start, w.end) && near(g.end, w.start))),
);
expect(got, `${w.id} ${JSON.stringify(p.walls.map((x) => [x.start, x.end]))}`).toBeDefined();
expect(got!.wallTypeId).toBe(w.wallTypeId);
expect(got!.height).toBeCloseTo(w.height, 9);
expect(got!.bottom).toBeUndefined();
expect(got!.categoryCode).toBe("20");
byOrig.set(w.id, got!);
}
for (const o of sampleProject.openings ?? []) {
const host = byOrig.get(o.hostWallId)!;
const got = (p.openings ?? []).find((g) => g.hostWallId === host.id && Math.abs(g.width - o.width) < 1e-6 && g.kind === o.kind) as Opening;
expect(got, o.id).toBeDefined();
const orig = sampleProject.walls.find((w) => w.id === o.hostWallId)!;
const len = Math.hypot(orig.end.x - orig.start.x, orig.end.y - orig.start.y);
const pos = near(host.start, orig.start) ? o.position : len - o.position - o.width;
expect(got.position).toBeCloseTo(pos, 6);
expect(got.height).toBeCloseTo(o.height, 6);
expect(got.sillHeight).toBeCloseTo(o.sillHeight, 6);
expect(got.typeId).toBe(o.typeId);
}
const c = sampleProject.ceilings![0];
const gc = p.ceilings![0];
expect(gc.floorId).toBe(c.floorId);
expect(gc.ceilingTypeId).toBe(c.ceilingTypeId);
expect(gc.top).toBeUndefined();
expect(gc.outline.length).toBe(c.outline.length);
for (const q of c.outline) expect(gc.outline.some((g) => near(g, q)), JSON.stringify(q)).toBe(true);
const room = sampleProject.rooms![0];
const gr = p.rooms![0];
expect([gr.name, gr.siaCategory, gr.floorId]).toEqual([room.name, room.siaCategory, room.floorId]);
for (const q of room.boundary) expect(gr.boundary.some((g) => near(g, q))).toBe(true);
const text = formatIfcElementsSummary(summary, report, (k, v) => `${k}${JSON.stringify(v ?? {})}`);
expect(text).toContain('"walls":9');
});
it("in ein Projekt ohne Geschosse/Typen: legt Geschosse, Wand-/Deckentypen und Materialien an", async () => {
const bare: Project = {
...emptyProject,
drawingLevels: emptyProject.drawingLevels.filter((l) => l.kind !== "floor"),
wallTypes: [],
ceilingTypes: [],
components: [],
};
const { project: p, summary } = await importInto(bare, sampleProject);
expect(summary).toMatchObject({ walls: 9, openings: 3, ceilings: 1, rooms: 1, floors: 2, wallTypes: 2, ceilingTypes: 1 });
// Materialien: Aussenputz, Wärmedämmung, Backstein, Innenputz, Zementestrich, Beton.
expect(summary.components).toBe(6);
const floors = p.drawingLevels.filter((l) => l.kind === "floor");
expect(floors.map((f) => [f.name, f.baseElevation, f.floorHeight])).toEqual([
["Erdgeschoss", 0, 2.6],
["Obergeschoss", 2.6, 2.6],
]);
const aw = p.wallTypes.find((t) => t.name === "Aussenwand 34.5 cm")!;
expect(wallTypeThickness(aw)).toBeCloseTo(0.345, 9);
expect(aw.layers.map((l) => p.components.find((c) => c.id === l.componentId)!.name)).toEqual([
"Aussenputz", "Wärmedämmung", "Backstein", "Innenputz",
]);
expect(p.walls.filter((w) => w.wallTypeId === aw.id).length).toBe(8);
expect(validateProject(p)).toEqual([]);
});
it("über Ops angewandt und gespeichert/geladen bleibt alles gleich", async () => {
const { project: next } = await importInto(emptyProject, sampleProject);
const applied = applyOps(emptyProject, diffToOps(emptyProject, next));
expect(applied.walls).toEqual(next.walls);
expect(applied.openings).toEqual(next.openings);
const back = parseProjectFile(serializeProject(applied));
expect(back.ok).toBe(true);
if (!back.ok) return;
expect(back.warnings).toEqual([]);
expect(back.project.walls).toEqual(next.walls);
expect(back.project.ceilings).toEqual(next.ceilings);
expect(back.project.context).toEqual(next.context);
});
it("Stützen (rechteckig gedreht, rund) und abgesetzte Wand-Unterkante", async () => {
const cols: Column[] = [
{ id: "S1", type: "column", floorId: "eg", categoryCode: "50", position: { x: 1, y: 1 }, profile: { kind: "rect", width: 0.3, depth: 0.5 }, rotation: 0, height: 2.4 },
{ id: "S2", type: "column", floorId: "og", categoryCode: "50", position: { x: 3, y: 2 }, profile: { kind: "round", radius: 0.15 }, rotation: 0, height: 2.5 },
];
const src: Project = { ...sampleProject, columns: cols };
const { project: p, summary } = await importInto(emptyProject, src);
expect(summary.columns).toBe(2);
const s1 = p.columns!.find((c) => c.profile.kind === "rect")!;
expect(s1.floorId).toBe("eg");
expect(near(s1.position, { x: 1, y: 1 })).toBe(true);
expect(s1.profile).toEqual({ kind: "rect", width: 0.3, depth: 0.5 });
expect(s1.rotation).toBeCloseTo(0, 9);
expect(s1.height).toBeCloseTo(2.4, 9);
const s2 = p.columns!.find((c) => c.profile.kind === "round")!;
expect(s2.floorId).toBe("og");
expect(near(s2.position, { x: 3, y: 2 }, 1e-4)).toBe(true);
expect(s2.profile.kind === "round" && s2.profile.radius).toBeCloseTo(0.15, 6);
});
});
describe("Kontext-Mesh: Farbe und GlobalId", () => {
const product = (color: IfcProduct["color"], globalId = "2O2Fr$t4X7Zf8NOew3FLOH"): IfcProduct => ({
globalId,
ifcClass: "IfcWall",
name: "Wand",
storey: "EG",
color,
positions: new Float64Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]),
indices: new Uint32Array([0, 2, 1, 0, 1, 3, 0, 3, 2, 1, 2, 3]),
});
it("Farbe als #rrggbb, GlobalId als Feld, Name ohne GlobalId", () => {
const [m] = ifcToImportedMeshes([product([1, 0.5, 0, 0.8])], "x.ifc", { group: "product" });
expect(m.color).toBe("#ff8000");
expect(m.ifcGlobalId).toBe("2O2Fr$t4X7Zf8NOew3FLOH");
expect(m.name).toBe("EG: Wand");
const [n] = ifcToImportedMeshes([product(null, "")], "x.ifc", { group: "product" });
expect(n.color).toBeUndefined();
expect(n.ifcGlobalId).toBeUndefined();
// Zusammengelegt: gemeinsame Farbe nur, wenn alle gleich.
expect(ifcToImportedMeshes([product([1, 0, 0, 1]), product([1, 0, 0, 1])], "x.ifc", { group: "class" })[0].color).toBe("#ff0000");
expect(ifcToImportedMeshes([product([1, 0, 0, 1]), product([0, 0, 1, 1])], "x.ifc", { group: "class" })[0].color).toBeUndefined();
});
it("Farbe aus der Datei (IfcStyledItem) kommt am Mesh an und übersteht Speichern/Laden", async () => {
const { products } = await readIfc(new Uint8Array(readFileSync(new URL("./testdata/ifc-geometry-cases.ifc", import.meta.url))));
const meshes = ifcToImportedMeshes(products, "cases.ifc");
expect(meshes.every((m) => m.ifcGlobalId && !m.name.includes("["))).toBe(true);
const withColor = { ...meshes[0], color: "#336699" };
const proj: Project = { ...emptyProject, context: [withColor] };
const back = parseProjectFile(serializeProject(proj));
expect(back.ok && back.project.context?.[0]).toEqual(withColor);
});
});
// Freie Beispieldateien (github.com/buildingSMART/Sample-Test-Files u. a., nicht im Repo):
// DOSSIER_IFC_SAMPLES=<Verzeichnis>. Prüft: kein Absturz, gültiges Projekt, Zählung je Datei.
const samples = process.env.DOSSIER_IFC_SAMPLES;
describe.skipIf(!samples || !existsSync(samples))("IFC-Import als Bauteile: Beispieldateien", { timeout: 600_000 }, () => {
it("alle Dateien lesbar, Ergebnis gültig", async () => {
const files: string[] = [];
const walk = (d: string) => {
for (const n of readdirSync(d)) {
const f = join(d, n);
if (statSync(f).isDirectory()) walk(f);
else if (/\.ifc$/i.test(n)) files.push(f);
}
};
walk(samples!);
const rows: string[] = [];
for (const f of files) {
const { products, elements } = await readIfcElements(new Uint8Array(readFileSync(f)));
const { project, summary } = ifcElementsToProject(emptyProject, products, elements, { fileName: f });
expect(validateProject(project), f).toEqual([]);
rows.push(`${f.slice(samples!.length + 1)}: ${JSON.stringify(summary)}`);
}
process.stderr.write(rows.join("\n") + "\n");
});
});
+550
View File
@@ -0,0 +1,550 @@
// IFC-Import zu echten Bauteilen ([B4], zweite Stufe von [25]): baut aus dem, was das Format-Modul
// erkannt hat (`src-tauri/fileio/src/ifc_semantic.rs`: Achse, Dicke, Höhe, Umriss … in Metern),
// Dossier-Objekte — Geschosse, Wände (Wandtyp aus den Materialschichten, wiederverwendet oder neu),
// Türen/Fenster/Wanddurchbrüche, Decken (Deckentyp), Stützen, Räume. Was Rust nicht sicher abbilden
// konnte, kommt wie beim Mesh-Import als Kontext-Mesh (`ifcImport.ts`).
//
// Keine Geometrie-Rechnung hier: TS ordnet nur zu (Geschoss nach Höhe, Typ nach Schichten) und setzt
// die Objekte zusammen. Das Projekt wird nicht verändert — der Aufrufer übernimmt das Ergebnis über
// `setProject` (App) bzw. `diffToOps`/`applyOps` (CLI), also über Ops.
import { ensureContextCategories } from "../model/contextCategories";
import type {
Ceiling,
CeilingType,
Column,
Component,
DrawingLevel,
ImportedMesh,
LayerCategory,
Opening,
Project,
Room,
SiaCategory,
Vec2,
Wall,
WallType,
} from "../model/types";
import {
decodeIfc,
geoShift,
ifcColorHex,
ifcToImportedMeshes,
readIfcFlat,
type IfcFlat,
type IfcImportReport,
type IfcProduct,
} from "./ifcImport";
// ── Rohdaten aus Rust ────────────────────────────────────────────────────────────────────────
export interface IfcMatLayer {
material: string;
/** 0 = einziges Material ohne Schichtdicke (gilt für die ganze Dicke). */
thickness: number;
color: [number, number, number, number] | null;
}
interface IfcInfo {
globalId: string;
ifcClass: string;
name: string | null;
/** Index in `storeys`. */
storey: number | null;
color: [number, number, number, number] | null;
typeName: string | null;
layers: IfcMatLayer[];
}
export interface IfcStoreyData {
globalId: string;
name: string;
elevation: number;
}
export interface IfcWallData extends IfcInfo {
/** Achse; erste Schicht rechts der Richtung start → end (wie Dossier). */
start: Vec2;
end: Vec2;
z0: number;
z1: number;
thickness: number;
}
export interface IfcOpeningData extends IfcInfo {
/** Index in `walls`. */
host: number;
kind: "door" | "window" | "hole";
position: number;
width: number;
sill: number;
height: number;
}
export interface IfcSlabData extends IfcInfo {
outline: Vec2[];
holes: Vec2[][];
z0: number;
z1: number;
}
export interface IfcColumnData extends IfcInfo {
center: Vec2;
rotation: number;
profile: { kind: "rect"; width: number; depth: number } | { kind: "round"; radius: number };
z0: number;
z1: number;
}
export interface IfcSpaceData extends IfcInfo {
longName: string | null;
sia: string | null;
boundary: Vec2[];
z0: number;
z1: number;
}
/** Erkannte Bauteile einer Datei. */
export interface IfcElementsData {
storeys: IfcStoreyData[];
walls: IfcWallData[];
openings: IfcOpeningData[];
slabs: IfcSlabData[];
columns: IfcColumnData[];
spaces: IfcSpaceData[];
/** Nicht sicher abbildbare Kandidaten je Klasse (bleiben Mesh). */
kept: Record<string, number>;
}
interface RawElement extends IfcInfo {
kind: "wall" | "opening" | "slab" | "column" | "space";
at: number;
n: number;
host?: number;
openingKind?: "door" | "window" | "hole";
profile?: "rect" | "round";
longName?: string | null;
sia?: string | null;
}
/** Erkannte Bauteile aus dem Rohergebnis; `null`, wenn ohne Bauteil-Erkennung gelesen. */
export function decodeIfcElements(flat: IfcFlat): IfcElementsData | null {
const meta = JSON.parse(flat.meta) as { elements?: { storeys: IfcStoreyData[]; elements: RawElement[]; kept: Record<string, number> } };
const raw = meta.elements;
const data = flat.elementData;
if (!raw || !data) return null;
const out: IfcElementsData = { storeys: raw.storeys, walls: [], openings: [], slabs: [], columns: [], spaces: [], kept: raw.kept ?? {} };
// Wand-Index in Rust → Index in `out.walls` (verworfene Wände fallen heraus).
const wallIndex = new Map<number, number>();
let rustWall = 0;
for (const e of raw.elements) {
const v = data.subarray(e.at, e.at + e.n);
if (v.length !== e.n || !v.every(Number.isFinite)) {
if (e.kind === "wall") rustWall++;
continue;
}
const info: IfcInfo = {
globalId: e.globalId,
ifcClass: e.ifcClass,
name: e.name,
storey: e.storey,
color: e.color,
typeName: e.typeName,
layers: e.layers ?? [],
};
const rings = (start: number, count: number): { rings: Vec2[][]; ok: boolean } => {
const res: Vec2[][] = [];
let i = start;
for (let r = 0; r < count; r++) {
const n = v[i++];
if (!(n >= 3) || i + 2 * n > v.length) return { rings: res, ok: false };
const ring: Vec2[] = [];
for (let k = 0; k < n; k++) ring.push({ x: v[i + 2 * k], y: v[i + 2 * k + 1] });
i += 2 * n;
res.push(ring);
}
return { rings: res, ok: true };
};
switch (e.kind) {
case "wall":
if (v.length === 7) {
wallIndex.set(rustWall, out.walls.length);
out.walls.push({ ...info, start: { x: v[0], y: v[1] }, end: { x: v[2], y: v[3] }, z0: v[4], z1: v[5], thickness: v[6] });
}
rustWall++;
break;
case "opening": {
const host = wallIndex.get(e.host ?? -1);
if (host !== undefined && v.length === 4) {
out.openings.push({ ...info, host, kind: e.openingKind ?? "hole", position: v[0], width: v[1], sill: v[2], height: v[3] });
}
break;
}
case "slab": {
const r = rings(3, v[2]);
if (r.ok && r.rings.length >= 1) out.slabs.push({ ...info, z0: v[0], z1: v[1], outline: r.rings[0], holes: r.rings.slice(1) });
break;
}
case "column":
if (v.length === 7) {
const profile =
e.profile === "round" ? { kind: "round" as const, radius: v[5] } : { kind: "rect" as const, width: v[5], depth: v[6] };
out.columns.push({ ...info, center: { x: v[0], y: v[1] }, rotation: v[2], z0: v[3], z1: v[4], profile });
}
break;
case "space": {
const r = rings(2, 1);
if (r.ok) out.spaces.push({ ...info, longName: e.longName ?? null, sia: e.sia ?? null, z0: v[0], z1: v[1], boundary: r.rings[0] });
break;
}
}
}
return out;
}
/** Liest IFC-Bytes mit Bauteil-Erkennung (im Worker, sonst direkt). */
export async function readIfcElements(
bytes: Uint8Array,
): Promise<{ products: IfcProduct[]; report: IfcImportReport; elements: IfcElementsData }> {
const flat = await readIfcFlat(bytes, true);
const { products, report } = decodeIfc(flat);
const elements = decodeIfcElements(flat) ?? { storeys: [], walls: [], openings: [], slabs: [], columns: [], spaces: [], kept: {} };
return { products, report, elements };
}
// ── Aufbau der Dossier-Objekte ───────────────────────────────────────────────────────────────
export interface IfcElementsOptions {
/** Dateiname (für die Namen der Kontext-Meshes). */
fileName: string;
/** LV95-Ursprung des Projekts (`projectGeoOrigin`), sonst null. */
geoOrigin?: { e: number; n: number } | null;
group?: "product" | "class" | "auto";
}
/** Was übernommen wurde (für Meldung und Tests). */
export interface IfcElementsSummary {
walls: number;
openings: number;
ceilings: number;
columns: number;
rooms: number;
/** Neu angelegte Geschosse. */
floors: number;
wallTypes: number;
ceilingTypes: number;
components: number;
/** Bauteile als Kontext-Mesh. */
meshes: number;
/** Davon Kandidaten, die nicht sicher abbildbar waren. */
kept: number;
}
const WALL_CATEGORY = "20";
const OPENING_CATEGORY = "21";
const CEILING_CATEGORY = "30";
const COLUMN_CATEGORY = "50";
const ROOM_CATEGORY = "60";
const ROOM_COLOR = "#6b7280";
const SIA: readonly SiaCategory[] = ["HNF", "NNF", "VF", "FF", "KGF", "AGF"];
/** Toleranzen (m): gleiche Höhe eines Geschosses, gleiche Schichtdicke. */
const LEVEL_TOL = 0.005;
const LAYER_TOL = 0.0005;
let counter = 0;
const round = (x: number, step = 1e-9) => Math.round(x / step) * step;
function flatCategories(list: LayerCategory[], out: LayerCategory[] = []): LayerCategory[] {
for (const c of list) {
out.push(c);
if (c.children) flatCategories(c.children, out);
}
return out;
}
/**
* Setzt die erkannten Bauteile und die übrigen Kontext-Meshes ins Projekt (neues Objekt, das alte
* bleibt unverändert). Geschosse werden nach Höhe wiederverwendet (±5 mm) oder angelegt, Wand- und
* Deckentypen nach Schichten (Material + Dicke) wiederverwendet oder angelegt, Materialien nach Namen.
*/
export function ifcElementsToProject(
project: Project,
products: IfcProduct[],
elements: IfcElementsData,
opts: IfcElementsOptions,
): { project: Project; summary: IfcElementsSummary } {
const stamp = Date.now().toString(36);
const newId = (kind: string) => `ifc-${kind}-${stamp}-${counter++}`;
const summary: IfcElementsSummary = {
walls: 0, openings: 0, ceilings: 0, columns: 0, rooms: 0, floors: 0, wallTypes: 0, ceilingTypes: 0, components: 0, meshes: 0,
kept: Object.values(elements.kept).reduce((s, n) => s + n, 0),
};
// Verschiebung bei Landeskoordinaten: gemeinsam für Bauteile und Meshes.
const extra: number[] = [];
for (const w of elements.walls) extra.push(w.start.x, w.start.y, w.end.x, w.end.y);
for (const s of elements.slabs) for (const p of s.outline) extra.push(p.x, p.y);
for (const c of elements.columns) extra.push(c.center.x, c.center.y);
for (const s of elements.spaces) for (const p of s.boundary) extra.push(p.x, p.y);
const [dx, dy] = geoShift(products, opts.geoOrigin, extra);
const mv = (p: Vec2): Vec2 => ({ x: round(p.x + dx), y: round(p.y + dy) });
// ── Geschosse ──
const levels: DrawingLevel[] = [...project.drawingLevels];
const floorsSorted = () => levels.filter((l) => l.kind === "floor").sort((a, b) => (a.baseElevation ?? 0) - (b.baseElevation ?? 0));
const topOf = new Map<number, number>();
const noteTop = (storey: number | null, z: number) => {
if (storey !== null) topOf.set(storey, Math.max(topOf.get(storey) ?? -Infinity, z));
};
for (const w of elements.walls) noteTop(w.storey, w.z1);
for (const c of elements.columns) noteTop(c.storey, c.z1);
const storeyFloor = elements.storeys.map((s, i) => {
const existing = levels.find((l) => l.kind === "floor" && Math.abs((l.baseElevation ?? 0) - s.elevation) <= LEVEL_TOL);
if (existing) return existing.id;
const next = elements.storeys[i + 1];
const top = topOf.get(i);
const height = next ? next.elevation - s.elevation : top !== undefined && top > s.elevation + 0.5 ? top - s.elevation : 2.6;
const level: DrawingLevel = {
id: newId("floor"),
name: s.name || `IFC ${round(s.elevation, 0.001)}`,
kind: "floor",
visible: true,
locked: false,
floorHeight: round(height, 1e-6),
cutHeight: 1,
baseElevation: round(s.elevation, 1e-6),
};
// Einfügen vor dem ersten höheren Geschoss, sonst nach dem letzten.
const floors = floorsSorted();
const higher = floors.find((l) => (l.baseElevation ?? 0) > s.elevation);
const at = higher ? levels.indexOf(higher) : floors.length ? levels.indexOf(floors[floors.length - 1]) + 1 : 0;
levels.splice(at, 0, level);
summary.floors++;
return level.id;
});
/** Geschoss eines Bauteils: aus der Datei, sonst das höchste mit OK FB ≤ Unterkante. */
const floorOf = (storey: number | null, z0: number): DrawingLevel => {
const id = storey !== null ? storeyFloor[storey] : undefined;
const byId = id ? levels.find((l) => l.id === id) : undefined;
if (byId) return byId;
const floors = floorsSorted();
const below = floors.filter((l) => (l.baseElevation ?? 0) <= z0 + LEVEL_TOL);
const f = below[below.length - 1] ?? floors[0];
if (f) return f;
const level: DrawingLevel = { id: newId("floor"), name: "IFC", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1, baseElevation: 0 };
levels.push(level);
summary.floors++;
return level;
};
const anchorOffset = (z: number, f: DrawingLevel) => round(z - (f.baseElevation ?? 0), 1e-6);
// ── Materialien und Typen ──
const components: Component[] = [...project.components];
const hatchId = project.hatches.find((h) => h.id === "none")?.id ?? project.hatches[0]?.id ?? "none";
const componentFor = (name: string, color: string | undefined): string => {
const key = name.trim().toLowerCase();
const found = components.find((c) => c.name.trim().toLowerCase() === key);
if (found) return found.id;
const c: Component = { id: newId("component"), name: name.trim() || "IFC", color: color ?? "#b0b0b0", hatchId, joinPriority: 50 };
components.push(c);
summary.components++;
return c.id;
};
/** Schichten eines Bauteils der Dicke `t`: die der Datei, wenn sie aufgehen, sonst eine Schicht. */
const layerSpec = (e: IfcInfo, t: number): { material: string; thickness: number; color?: string }[] => {
const ls = e.layers;
const sum = ls.reduce((s, l) => s + l.thickness, 0);
if (ls.length > 0 && ls.every((l) => l.thickness > 0) && Math.abs(sum - t) <= 0.005) {
return ls.map((l) => ({ material: l.material, thickness: round(l.thickness, 1e-6), color: ifcColorHex(l.color) }));
}
const first = ls.length === 1 ? ls[0] : undefined;
return [{ material: first?.material ?? "", thickness: round(t, 1e-6), color: ifcColorHex(first?.color ?? e.color) }];
};
const sameLayers = (
have: { componentId: string; thickness: number }[],
want: { material: string; thickness: number }[],
): boolean =>
have.length === want.length &&
have.every((l, i) => {
if (Math.abs(l.thickness - want[i].thickness) > LAYER_TOL) return false;
const name = components.find((c) => c.id === l.componentId)?.name.trim().toLowerCase() ?? "";
return want[i].material ? name === want[i].material.trim().toLowerCase() : true;
});
const typeName = (e: IfcInfo, t: number) => e.typeName?.trim() || `IFC ${round(t * 100, 0.1)} cm`;
const wallTypes: WallType[] = [...project.wallTypes];
const wallTypeFor = (e: IfcInfo, t: number): string => {
const spec = layerSpec(e, t);
const name = typeName(e, t);
// Ohne Material: nur ein gleich benannter, gleich dicker Typ passt.
const found = wallTypes.find((wt) => sameLayers(wt.layers, spec) && (spec.some((l) => l.material) || wt.name === name));
if (found) return found.id;
const wt: WallType = {
id: newId("walltype"),
name,
layers: spec.map((l) => ({ componentId: componentFor(l.material, l.color), thickness: l.thickness })),
};
wallTypes.push(wt);
summary.wallTypes++;
return wt.id;
};
const ceilingTypes: CeilingType[] = [...(project.ceilingTypes ?? [])];
const ceilingTypeFor = (e: IfcInfo, t: number): string => {
const spec = layerSpec(e, t);
const name = typeName(e, t);
const found = ceilingTypes.find((ct) => sameLayers(ct.layers, spec) && (spec.some((l) => l.material) || ct.name === name));
if (found) return found.id;
const ct: CeilingType = {
id: newId("ceilingtype"),
name,
layers: spec.map((l) => ({ componentId: componentFor(l.material, l.color), thickness: l.thickness })),
};
ceilingTypes.push(ct);
summary.ceilingTypes++;
return ct.id;
};
// ── Wände und Öffnungen ──
const walls: Wall[] = [];
for (const w of elements.walls) {
const f = floorOf(w.storey, w.z0);
const height = round(w.z1 - w.z0, 1e-6);
const bottom = anchorOffset(w.z0, f);
walls.push({
id: newId("wall"),
type: "wall",
floorId: f.id,
categoryCode: WALL_CATEGORY,
start: mv(w.start),
end: mv(w.end),
wallTypeId: wallTypeFor(w, w.thickness),
height,
...(Math.abs(bottom) > LEVEL_TOL ? { bottom: { mode: "floor" as const, floorId: f.id, offset: bottom } } : {}),
});
}
const openings: Opening[] = [];
for (const o of elements.openings) {
const host = walls[o.host];
if (!host) continue;
const kind = o.kind === "window" ? "window" : "door";
const typeId = o.kind === "door" ? project.doorTypes?.[0]?.id : o.kind === "window" ? project.windowTypes?.[0]?.id : undefined;
openings.push({
id: newId("opening"),
type: "opening",
hostWallId: host.id,
categoryCode: OPENING_CATEGORY,
kind,
position: round(o.position, 1e-6),
width: round(o.width, 1e-6),
height: round(o.height, 1e-6),
sillHeight: round(o.sill, 1e-6),
...(o.kind === "hole" ? { doorType: "wandoeffnung" as const } : {}),
...(typeId ? { typeId } : {}),
});
}
// ── Decken, Stützen, Räume ──
const ceilings: Ceiling[] = [];
for (const s of elements.slabs) {
const f = floorOf(s.storey, s.z0);
const t = s.z1 - s.z0;
const floorTop = (f.baseElevation ?? 0) + (f.floorHeight ?? 0);
ceilings.push({
id: newId("ceiling"),
type: "ceiling",
floorId: f.id,
categoryCode: CEILING_CATEGORY,
outline: s.outline.map(mv),
...(s.holes.length ? { openings: s.holes.map((h) => h.map(mv)) } : {}),
wallTypeId: project.wallTypes[0]?.id ?? wallTypes[0]?.id ?? "",
ceilingTypeId: ceilingTypeFor(s, t),
...(Math.abs(s.z1 - floorTop) > LEVEL_TOL ? { top: { mode: "floor" as const, floorId: f.id, offset: anchorOffset(s.z1, f) } } : {}),
});
}
const columns: Column[] = [];
for (const c of elements.columns) {
const f = floorOf(c.storey, c.z0);
const bottom = anchorOffset(c.z0, f);
const material = c.layers[0]?.material;
columns.push({
id: newId("column"),
type: "column",
floorId: f.id,
categoryCode: COLUMN_CATEGORY,
position: mv(c.center),
profile:
c.profile.kind === "round"
? { kind: "round", radius: round(c.profile.radius, 1e-6) }
: { kind: "rect", width: round(c.profile.width, 1e-6), depth: round(c.profile.depth, 1e-6) },
rotation: c.rotation,
height: round(c.z1 - c.z0, 1e-6),
...(material ? { componentId: componentFor(material, ifcColorHex(c.layers[0].color ?? c.color)) } : {}),
...(Math.abs(bottom) > LEVEL_TOL ? { bottom: { mode: "floor" as const, floorId: f.id, offset: bottom } } : {}),
});
}
const roomColor = flatCategories(project.layers).find((c) => c.code === ROOM_CATEGORY)?.color ?? ROOM_COLOR;
const rooms: Room[] = [];
for (const s of elements.spaces) {
const f = floorOf(s.storey, s.z0);
const boundary = s.boundary.map(mv);
const sia = SIA.find((c) => c === s.sia?.trim().toUpperCase());
const n = boundary.length;
rooms.push({
id: newId("room"),
type: "room",
floorId: f.id,
categoryCode: ROOM_CATEGORY,
siaCategory: sia ?? "HNF",
name: s.longName || s.name || `Raum ${(project.rooms?.length ?? 0) + rooms.length + 1}`,
boundary,
color: roomColor,
stampAnchor: { x: boundary.reduce((a, p) => a + p.x, 0) / n, y: boundary.reduce((a, p) => a + p.y, 0) / n },
});
}
// ── Übrige Bauteile als Kontext-Mesh ──
const meshes: ImportedMesh[] = ifcToImportedMeshes(products, opts.fileName, { geoOrigin: opts.geoOrigin, group: opts.group, shift: [dx, dy] });
summary.walls = walls.length;
summary.openings = openings.length;
summary.ceilings = ceilings.length;
summary.columns = columns.length;
summary.rooms = rooms.length;
summary.meshes = meshes.length;
const next: Project = {
...project,
drawingLevels: levels,
components,
wallTypes,
...(ceilingTypes.length || project.ceilingTypes ? { ceilingTypes } : {}),
walls: [...project.walls, ...walls],
openings: [...(project.openings ?? []), ...openings],
ceilings: [...(project.ceilings ?? []), ...ceilings],
columns: [...(project.columns ?? []), ...columns],
rooms: [...(project.rooms ?? []), ...rooms],
...(meshes.length
? {
context: [...(project.context ?? []), ...meshes],
layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))),
}
: {}),
};
return { project: next, summary };
}
/** Meldung zum Bauteil-Import; `tr` übersetzt (Kern kennt kein i18n). */
export function formatIfcElementsSummary(
s: IfcElementsSummary,
r: IfcImportReport,
tr: (key: "ifc.import.elements" | "ifc.import.kept", vars?: Record<string, string | number>) => string,
): string {
const parts = [
tr("ifc.import.elements", {
schema: r.schema || "IFC",
walls: s.walls,
openings: s.openings,
ceilings: s.ceilings,
columns: s.columns,
rooms: s.rooms,
floors: s.floors,
meshes: s.meshes,
}),
];
if (s.kept) parts.push(tr("ifc.import.kept", { n: s.kept }));
return parts.join(" · ");
}
+76 -34
View File
@@ -1,9 +1,10 @@
// IFC-Import als Mesh ([B3]): dünne Fassade über `import_ifc` im Format-Modul (`src-tauri/fileio`,
// `ifc_import.rs`). Jedes IFC-Bauteil mit Körper wird zu einem `ImportedMesh` der Kontext-Schicht
// (wie der STEP-Import, `stepImport.ts`); echte Bauteile (Wand, Decke …) kommen mit [B4].
// (wie der STEP-Import, `stepImport.ts`); echte Bauteile (Wand, Decke …) baut auf Wunsch
// `ifcElements.ts` ([B4]) aus `import_ifc_elements`.
//
// Gruppierung: je Bauteil ein Mesh (anwählbar, Name/Geschoss/GlobalId bleiben erhalten, im
// Kontext-Panel nach IFC-Klasse gruppiert über `layer`). Bei sehr vielen Bauteilen (> `MAX_SINGLE`)
// Gruppierung: je Bauteil ein Mesh (anwählbar, Name/Geschoss bleiben erhalten, GlobalId in
// `ifcGlobalId`, Farbe in `color`; im Kontext-Panel nach IFC-Klasse gruppiert über `layer`). Bei sehr vielen Bauteilen (> `MAX_SINGLE`)
// werden Bauteile gleicher Klasse und gleichen Geschosses zusammengelegt, damit Projektdatei und
// Kontext-Panel handhabbar bleiben.
//
@@ -18,6 +19,7 @@
import { loadFileio } from "../engine/fileioWasm";
import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories";
import type { ImportedMesh } from "../model/types";
import { rgbToHex } from "../model/color";
/** Ein gelesenes IFC-Bauteil. */
export interface IfcProduct {
@@ -62,23 +64,27 @@ interface RawProduct {
indexCount: number;
}
/** Rohergebnis aus Rust: Bericht (JSON) und alle Bauteile hintereinander in zwei flachen Puffern. */
/** Rohergebnis aus Rust: Bericht (JSON) und alle Bauteile hintereinander in zwei flachen Puffern;
* mit `elements` dazu die Zahlen der erkannten Bauteile ([B4], `ifcElements.ts`). */
export interface IfcFlat {
meta: string;
positions: Float64Array;
indices: Uint32Array;
elementData?: Float64Array;
}
/** Worker-Protokoll (`ifcImport.worker.ts`). */
export type IfcWorkerRequest = { type: "parse"; data: ArrayBuffer };
/** Worker-Protokoll (`ifcImport.worker.ts`); `elements` = echte Bauteile erkennen ([B4]). */
export type IfcWorkerRequest = { type: "parse"; data: ArrayBuffer; elements?: boolean };
export type IfcWorkerResponse = { type: "result"; flat: IfcFlat } | { type: "error"; message: string };
/** Liest IFC-Bytes mit dem geladenen Format-Modul (Worker oder aufrufender Thread). */
export async function importIfcFlat(bytes: Uint8Array): Promise<IfcFlat> {
export async function importIfcFlat(bytes: Uint8Array, elements = false): Promise<IfcFlat> {
const m = await loadFileio();
const r = m.import_ifc(bytes);
const r = elements ? m.import_ifc_elements(bytes) : m.import_ifc(bytes);
try {
return { meta: r.meta, positions: r.positions(), indices: r.indices() };
const flat: IfcFlat = { meta: r.meta, positions: r.positions(), indices: r.indices() };
if (elements) flat.elementData = r.elementData();
return flat;
} finally {
r.free();
}
@@ -88,15 +94,17 @@ export async function importIfcFlat(bytes: Uint8Array): Promise<IfcFlat> {
export async function handleIfcWorkerRequest(req: IfcWorkerRequest): Promise<{ res: IfcWorkerResponse; transfer: Transferable[] }> {
try {
if (req?.type !== "parse" || !(req.data instanceof ArrayBuffer)) throw new Error("ungültige Anfrage");
const flat = await importIfcFlat(new Uint8Array(req.data));
return { res: { type: "result", flat }, transfer: [flat.positions.buffer, flat.indices.buffer] };
const flat = await importIfcFlat(new Uint8Array(req.data), req.elements === true);
const transfer: Transferable[] = [flat.positions.buffer, flat.indices.buffer];
if (flat.elementData) transfer.push(flat.elementData.buffer);
return { res: { type: "result", flat }, transfer };
} catch (err) {
return { res: { type: "error", message: err instanceof Error ? err.message : String(err) }, transfer: [] };
}
}
/** Liest im Web-Worker; `null`, wenn kein Worker verfügbar ist oder er nicht startet. */
function readInWorker(bytes: Uint8Array): Promise<IfcFlat | null> {
function readInWorker(bytes: Uint8Array, elements: boolean): Promise<IfcFlat | null> {
if (typeof Worker === "undefined") return Promise.resolve(null);
return new Promise((resolve, reject) => {
let worker: Worker;
@@ -117,7 +125,8 @@ function readInWorker(bytes: Uint8Array): Promise<IfcFlat | null> {
};
// Kopie übertragen: der Aufrufer behält seine Bytes.
const data = bytes.slice().buffer;
worker.postMessage({ type: "parse", data } satisfies IfcWorkerRequest, [data]);
const req: IfcWorkerRequest = elements ? { type: "parse", data, elements } : { type: "parse", data };
worker.postMessage(req, [data]);
});
}
@@ -145,8 +154,18 @@ export function decodeIfc(flat: IfcFlat): { products: IfcProduct[]; report: IfcI
/** Liest IFC-Bytes (im Worker, sonst direkt). Wirft bei unlesbarer Datei (Meldung aus Rust). */
export async function readIfc(bytes: Uint8Array): Promise<{ products: IfcProduct[]; report: IfcImportReport }> {
const flat = (await readInWorker(bytes)) ?? (await importIfcFlat(bytes));
return decodeIfc(flat);
return decodeIfc(await readIfcFlat(bytes));
}
/** Rohergebnis lesen (im Worker, sonst direkt); `elements` = echte Bauteile erkennen ([B4]). */
export async function readIfcFlat(bytes: Uint8Array, elements = false): Promise<IfcFlat> {
return (await readInWorker(bytes, elements)) ?? (await importIfcFlat(bytes, elements));
}
/** RGBA 0..1 → `#rrggbb` (Alpha entfällt). */
export function ifcColorHex(c: readonly number[] | null | undefined): string | undefined {
if (!c || c.length < 3 || !c.slice(0, 3).every((v) => Number.isFinite(v))) return undefined;
return rgbToHex({ r: c[0] * 255, g: c[1] * 255, b: c[2] * 255 });
}
/** Ab so vielen Bauteilen wird je Klasse + Geschoss zusammengelegt. */
@@ -157,12 +176,19 @@ export interface IfcToMeshesOptions {
geoOrigin?: { e: number; n: number } | null;
/** "product" = je Bauteil, "class" = je Klasse + Geschoss, "auto" (Standard) nach `MAX_SINGLE`. */
group?: "product" | "class" | "auto";
/** Feste Verschiebung statt der aus den Bauteilen geschätzten ([B4]: gemeinsam mit den Bauteilen). */
shift?: [number, number];
}
let counter = 0;
/** Verschiebung, falls die Datei in Landeskoordinaten liegt und das Projekt einen Bezug hat. */
function geoShift(products: IfcProduct[], origin: { e: number; n: number } | null | undefined): [number, number] {
/** Verschiebung, falls die Datei in Landeskoordinaten liegt und das Projekt einen Bezug hat;
* `extra` = weitere Punkte (x,y flach, z. B. erkannte Bauteile [B4]). */
export function geoShift(
products: IfcProduct[],
origin: { e: number; n: number } | null | undefined,
extra: readonly number[] = [],
): [number, number] {
if (!origin) return [0, 0];
let sx = 0;
let sy = 0;
@@ -174,6 +200,11 @@ function geoShift(products: IfcProduct[], origin: { e: number; n: number } | nul
n++;
}
}
for (let i = 0; i + 1 < extra.length; i += 2) {
sx += extra[i];
sy += extra[i + 1];
n++;
}
if (n === 0) return [0, 0];
const cx = sx / n;
const cy = sy / n;
@@ -184,7 +215,7 @@ function geoShift(products: IfcProduct[], origin: { e: number; n: number } | nul
/** Bauteile → Kontext-Meshes (Kategorie „Situation" wie STEP; `layer` = IFC-Klasse). */
export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, opts: IfcToMeshesOptions = {}): ImportedMesh[] {
const base = fileName.replace(/\.[^.]+$/, "") || "IFC";
const [dx, dy] = geoShift(products, opts.geoOrigin);
const [dx, dy] = opts.shift ?? geoShift(products, opts.geoOrigin);
const stamp = Date.now().toString(36);
const group = opts.group ?? "auto";
const perProduct = group === "product" || (group === "auto" && products.length <= MAX_SINGLE);
@@ -203,14 +234,19 @@ export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, op
};
if (perProduct) {
return products.map((p) => ({
id: `imported-ifc-${stamp}-${counter++}`,
type: "importedMesh" as const,
name: [p.storey, p.name || p.ifcClass].filter(Boolean).join(": ") + (p.globalId ? ` [${p.globalId}]` : ""),
layer: p.ifcClass,
categoryCode: GENERIC_IMPORT_CATEGORY.code,
...toArrays([p]),
}));
return products.map((p) => {
const color = ifcColorHex(p.color);
return {
id: `imported-ifc-${stamp}-${counter++}`,
type: "importedMesh" as const,
name: [p.storey, p.name || p.ifcClass].filter(Boolean).join(": "),
layer: p.ifcClass,
categoryCode: GENERIC_IMPORT_CATEGORY.code,
...(color ? { color } : {}),
...(p.globalId ? { ifcGlobalId: p.globalId } : {}),
...toArrays([p]),
};
});
}
const groups = new Map<string, IfcProduct[]>();
for (const p of products) {
@@ -219,14 +255,20 @@ export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, op
if (g) g.push(p);
else groups.set(key, [p]);
}
return [...groups.values()].map((parts) => ({
id: `imported-ifc-${stamp}-${counter++}`,
type: "importedMesh" as const,
name: `${base}: ${[parts[0].storey, parts[0].ifcClass].filter(Boolean).join(" ")} (${parts.length})`,
layer: parts[0].ifcClass,
categoryCode: GENERIC_IMPORT_CATEGORY.code,
...toArrays(parts),
}));
return [...groups.values()].map((parts) => {
// Gemeinsame Farbe nur, wenn alle Teile dieselbe haben.
const colors = new Set(parts.map((p) => ifcColorHex(p.color) ?? ""));
const color = colors.size === 1 ? [...colors][0] : "";
return {
id: `imported-ifc-${stamp}-${counter++}`,
type: "importedMesh" as const,
name: `${base}: ${[parts[0].storey, parts[0].ifcClass].filter(Boolean).join(" ")} (${parts.length})`,
layer: parts[0].ifcClass,
categoryCode: GENERIC_IMPORT_CATEGORY.code,
...(color ? { color } : {}),
...toArrays(parts),
};
});
}
/** Datei-Bytes → Kontext-Meshes + Bericht. */
+4
View File
@@ -2380,6 +2380,10 @@ export interface ImportedMesh {
* IMMER sichtbar (Rückwärtskompatibilität), s. `generatePlan/context.ts`.
*/
categoryCode?: string;
/** Farbe aus der Quelldatei (`#rrggbb`, z. B. IFC-Oberflächenstil/Material); fehlt sie, gilt die Kontext-Grundfarbe. */
color?: string;
/** IFC-GlobalId des Quell-Bauteils (IFC-Import je Bauteil). */
ifcGlobalId?: string;
positions: number[];
indices: number[];
}
+69
View File
@@ -0,0 +1,69 @@
// Auswahl beim IFC-Import ([B3]/[B4]): als Kontext-Meshes (Standard, wie bisher) oder als echte
// Bauteile (`io/ifcElements.ts`). Overlay-Muster wie `UnsavedChangesDialog` (kein `window.confirm`).
import { useEffect, useState } from "react";
import { t } from "../i18n";
export type IfcImportMode = "mesh" | "elements";
export interface IfcImportDialogProps {
fileName: string;
onImport: (mode: IfcImportMode) => void;
onCancel: () => void;
}
export function IfcImportDialog({ fileName, onImport, onCancel }: IfcImportDialogProps) {
const [mode, setMode] = useState<IfcImportMode>("mesh");
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onCancel();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onCancel]);
return (
<div className="imp-overlay" onClick={onCancel}>
<div
className="imp-dialog"
role="dialog"
aria-modal="true"
aria-label={t("ifc.importDialog.title")}
onClick={(e) => e.stopPropagation()}
>
<header className="imp-head">
<span className="imp-head-title">{t("ifc.importDialog.title")}</span>
<button className="imp-close" onClick={onCancel} aria-label={t("export.close")}>
×
</button>
</header>
<div className="imp-body">
<section className="imp-section">
<div className="imp-section-title">{fileName}</div>
<label className="imp-radio">
<input type="radio" name="ifc-mode" checked={mode === "mesh"} onChange={() => setMode("mesh")} />
<span>{t("ifc.importDialog.asMesh")}</span>
</label>
<div className="imp-note">{t("ifc.importDialog.asMeshHint")}</div>
<label className="imp-radio">
<input type="radio" name="ifc-mode" checked={mode === "elements"} onChange={() => setMode("elements")} />
<span>{t("ifc.importDialog.asElements")}</span>
</label>
<div className="imp-note">{t("ifc.importDialog.asElementsHint")}</div>
</section>
</div>
<footer className="imp-foot">
<button className="imp-btn" onClick={onCancel}>
{t("export.cancel")}
</button>
<button className="imp-btn primary" onClick={() => onImport(mode)}>
{t("ifc.importDialog.import")}
</button>
</footer>
</div>
</div>
);
}