diff --git a/NOTICE b/NOTICE index a346a880..d088e03c 100644 --- a/NOTICE +++ b/NOTICE @@ -23,3 +23,13 @@ truck (https://github.com/ricosjp/truck, truck-meshalgo src/tessellation/triangu csg.js (https://github.com/evanw/csg.js, Datei csg.js), Copyright (c) 2011 Evan Wallace, MIT License Verfahren (BSP-Bäume, Ebenen-Teilung, clipTo/invert, Vereinigung/Differenz/Schnitt) in Rust neu geschrieben und angepasst: src-tauri/fileio/src/csg.rs (IFC-Import: Öffnungen, Boolesche Körper). + +zip (https://github.com/zip-rs/zip2), MIT, mit flate2 (MIT OR Apache-2.0) und zopfli (Apache-2.0) + Abhängigkeit von src-tauri/fileio (BCF: .bcfzip lesen und schreiben, nur Deflate), unverändert. + +quick-xml (https://github.com/tafia/quick-xml), MIT + Abhängigkeit von src-tauri/fileio (BCF: markup.bcf und Viewpoints lesen), unverändert. + +BCF-Spezifikation (https://github.com/buildingSMART/BCF-XML, Schemas), buildingSMART, CC BY-ND 4.0 + Nur das Dateiformat als Vorlage; eigener Code in src-tauri/fileio/src/bcf.rs. Die Test-Beispiele + stehen nicht im Repo (Test buildingsmart_beispiele liest sie über BCF_TESTCASES aus einem lokalen Klon). diff --git a/TODO.md b/TODO.md index 7cfcdcf7..af2cf4b7 100644 --- a/TODO.md +++ b/TODO.md @@ -447,6 +447,24 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module Export im Worker; nur Linux-Container/vitest, nicht in der Tauri-App geprüft. · L - Geprüft nur im Linux-Container (vitest + ifcopenshell 0.9: 0 Befunde, Volumen), nicht in Solibri/BIMcollab und nicht in der Tauri-App. +- ◐ **[BCF] BCF 2.1/3.0 (BIM Collaboration Format).** (28.10.) Koordinations-Themen mit Solibri, BIMcollab, + Revit, ArchiCAD austauschen. Rust `src-tauri/fileio/src/bcf.rs` (+ `bcf_read`/`bcf_write` im pkgFileIo, + JSON an der Grenze, Snapshots Base64): .bcfzip lesen/schreiben (Themen mit Typ/Status/Priorität/Zuständig/ + Fällig/Labels, Kommentare, Viewpoints mit Perspektiv-/Orthokamera, Auswahl, Sichtbarkeits-Ausnahmen, + Schnittebenen, Snapshot; 2.1 und 3.0). Crates `zip` (MIT, nur Deflate) und `quick-xml` (MIT), in NOTICE. + TS `io/bcf.ts` (Fassade, reine Hilfen), `io/bcfMatch.ts` (GlobalId ↔ Dossier-id mit derselben Ableitung wie + der IFC-Export: `ifcGuid("//")`; importierte Meshes über `ifcGlobalId`), Dock-Panel + „BCF-Themen" (`panels/BcfPanel.tsx`, nicht im Standard-Layout, Menü Fenster > BCF-Themen bzw. macOS Fenster > Panels): Datei öffnen, + Themenliste, Klick wählt die Bauteile, Kommentar, Status, Thema aus Auswahl, Speichern. Themen liegen in + der eigenen Datei, kein Feld in `src/model`. CLI `dossier-cli bcf-info `. + Geprüft: Rust-Rundreise 2.1/3.0, Unsinn → Fehler (inkl. Zufallsbytes, Zip-Bomben-Grenze, XML-Tiefe), + alle 71 buildingSMART-Beispieldateien (Test Cases v2.1/v3.0, lokal; CC BY-ND, deshalb nicht im Repo, + Test `buildingsmart_beispiele` über `BCF_TESTCASES`), vitest Fassade und GlobalId-Zuordnung gegen den + IFC-Export des Demo-Hauses. Nicht geprüft: Austausch mit echter Solibri/BIMcollab-Software, Tauri-App. + Offen: Kamera des Viewpoints setzen und für neue Themen aus dem 3D-Viewport lesen (`Wasm3DViewport` hält + die Orbit-Kamera intern, ohne Setter/Getter; Achsen Z-oben wie IFC, Viewport vermutlich Y-oben); + Snapshot aus dem Viewport; `extensions.xml` (3.0), Farbgruppen/Linien, BimSnippet, Dokument-Referenzen + und verwandte Themen gehen beim Speichern verloren; Panel in den Standard-Dock aufnehmen. · M - ○ **[B6] Wand unter Dach als Prismen zwischen Ebenen** (für [G2]). `walls.rs:413–472, 592–654`. · M - ○ **[B7] Dach-Verschneidung und Gauben in 2.5D** (für [G5]). · M · nach [B2]/[B6]. - ○ **[B8] Bogenwände, schneller Weg** (für [T2]). · S/M–L diff --git a/src-tauri/fileio/Cargo.lock b/src-tauri/fileio/Cargo.lock index 88b231cf..94697b31 100644 --- a/src-tauri/fileio/Cargo.lock +++ b/src-tauri/fileio/Cargo.lock @@ -44,6 +44,15 @@ version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +dependencies = [ + "derive_arbitrary", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -118,6 +127,28 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "derive_arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "dossier-fileio" version = "0.1.0" @@ -126,10 +157,12 @@ dependencies = [ "console_error_panic_hook", "earcutr", "getrandom", + "quick-xml", "serde", "serde_json", "spade", "wasm-bindgen", + "zip", ] [[package]] @@ -276,6 +309,12 @@ version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + [[package]] name = "memchr" version = "2.8.2" @@ -374,6 +413,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quick-xml" +version = "0.39.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdcc8dd4e2f670d309a5f0e83fe36dfdc05af317008fea29144da1a2ac858e5e" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.46" @@ -624,8 +672,37 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "zip" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +dependencies = [ + "arbitrary", + "crc32fast", + "crossbeam-utils", + "displaydoc", + "flate2", + "indexmap", + "memchr", + "thiserror", + "zopfli", +] + [[package]] name = "zmij" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" + +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] diff --git a/src-tauri/fileio/Cargo.toml b/src-tauri/fileio/Cargo.toml index 0e2813da..cfe31b14 100644 --- a/src-tauri/fileio/Cargo.toml +++ b/src-tauri/fileio/Cargo.toml @@ -45,3 +45,11 @@ console_error_panic_hook = { version = "0.1", optional = true } earcutr = "0.5" # IFC-Import: eingeschränkte Delaunay-Triangulierung getrimmter Freiformflächen (MIT OR Apache-2.0). spade = "2.15" + +# BCF ([BCF]): .bcfzip (ZIP) lesen/schreiben und markup.bcf/viewpoint.bcfv (XML) lesen. +# zip: MIT, nur Deflate in reinem Rust (flate2/miniz_oxide, zopfli: Apache-2.0); quick-xml: MIT. +zip = { version = "2", default-features = false, features = ["deflate"] } +quick-xml = "0.39" + +[dev-dependencies] +serde_json = "1" diff --git a/src-tauri/fileio/src/bcf.rs b/src-tauri/fileio/src/bcf.rs new file mode 100644 index 00000000..657d0124 --- /dev/null +++ b/src-tauri/fileio/src/bcf.rs @@ -0,0 +1,1042 @@ +// BCF (BIM Collaboration Format, buildingSMART) 2.1 und 3.0: .bcfzip lesen und schreiben. +// +// Eigener Code nach der Spezifikation (github.com/buildingSMART/BCF-XML, Schemas markup.xsd, visinfo.xsd, +// project.xsd, version.xsd; dort CC BY-ND 4.0 — Beispieldateien liegen deshalb NICHT im Repo, der Test +// `buildingsmart_beispiele` liest sie nur, wenn `BCF_TESTCASES` auf ein lokales Klon-Verzeichnis zeigt). +// Fremde Crates: `zip` (MIT) und `quick-xml` (MIT), s. NOTICE. +// +// Datenmodell: Text (Themen, Kommentare, Viewpoints), Kamera und Komponenten-GUIDs. Die Grenze nach TS +// ist JSON (`bcf_read`/`bcf_write` unten, Feature "web"); Snapshots gehen als Base64-Text mit. +// Aufbau der Datei: `bcf.version` · `project.bcfp` (optional) · je Thema ein Ordner `/` mit +// `markup.bcf`, `*.bcfv` (Viewpoint) und `*.png`/`*.jpg` (Snapshot). +// +// Nicht abgebildet (beim Schreiben verworfen): BimSnippet, Dokument-Referenzen, verwandte Themen, +// Linien/Bitmaps und Farbgruppen der Viewpoints, `extensions.xml`/`documents.xml`. +// +// Kein Panic: Eingabe ist beliebig; alle Zugriffe laufen über `Result`, Grössen sind begrenzt. + +use std::collections::HashMap; +use std::io::{Cursor, Read, Write}; + +use quick_xml::events::Event; +use quick_xml::Reader; +use serde::{Deserialize, Serialize}; + +/// Obergrenze je ZIP-Eintrag nach dem Entpacken (Schutz vor Zip-Bomben). +const MAX_ENTRY_BYTES: u64 = 64 * 1024 * 1024; +/// Obergrenze der Themenzahl und der XML-Verschachtelung. +const MAX_TOPICS: usize = 100_000; +const MAX_DEPTH: usize = 64; + +// ── Datenmodell ───────────────────────────────────────────────────────────── + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct BcfFile { + /// "2.1" oder "3.0" (wie in der Datei; beim Schreiben wählt der Aufrufer). + pub version: String, + pub project_id: String, + pub project_name: String, + pub topics: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct HeaderFile { + pub ifc_project: String, + pub ifc_spatial_structure_element: String, + pub is_external: bool, + pub filename: String, + pub date: String, + pub reference: String, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct Topic { + pub guid: String, + pub topic_type: String, + pub topic_status: String, + pub title: String, + pub priority: String, + pub creation_date: String, + pub creation_author: String, + pub modified_date: String, + pub modified_author: String, + pub due_date: String, + pub assigned_to: String, + pub stage: String, + pub description: String, + pub labels: Vec, + pub header_files: Vec, + pub comments: Vec, + pub viewpoints: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct Comment { + pub guid: String, + pub date: String, + pub author: String, + pub comment: String, + /// Guid des zugehörigen Viewpoints (leer = keiner). + pub viewpoint_guid: String, + pub modified_date: String, + pub modified_author: String, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct Viewpoint { + pub guid: String, + /// Dateiname im Themenordner (`*.bcfv`); leer = beim Schreiben erzeugen. + pub file: String, + /// Dateiname des Snapshots (`*.png`/`*.jpg`); leer = beim Schreiben erzeugen. + pub snapshot_file: String, + /// Snapshot als Base64 (leer = keiner). + pub snapshot: String, + pub camera: Option, + pub selection: Vec, + /// `DefaultVisibility`: true = alles sichtbar ausser `exceptions`, false = alles unsichtbar ausser `exceptions`. + pub default_visibility: bool, + pub exceptions: Vec, + pub clipping_planes: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct Camera { + /// "perspective" oder "orthogonal". + pub kind: String, + pub position: [f64; 3], + pub direction: [f64; 3], + pub up: [f64; 3], + /// Vertikaler Öffnungswinkel in Grad (perspektivisch). + pub field_of_view: f64, + /// Massstab Ansicht→Welt (orthogonal). + pub view_to_world_scale: f64, + pub aspect_ratio: f64, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct Component { + /// 22-stellige IFC-GlobalId. + pub ifc_guid: String, + pub originating_system: String, + pub authoring_tool_id: String, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct ClippingPlane { + pub location: [f64; 3], + pub direction: [f64; 3], +} + +// ── Base64 (Snapshots) ────────────────────────────────────────────────────── + +const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +fn b64_encode(data: &[u8]) -> String { + let mut out = String::with_capacity(data.len().div_ceil(3) * 4); + for chunk in data.chunks(3) { + let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)]; + let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); + out.push(B64[(n >> 18) as usize & 63] as char); + out.push(B64[(n >> 12) as usize & 63] as char); + out.push(if chunk.len() > 1 { B64[(n >> 6) as usize & 63] as char } else { '=' }); + out.push(if chunk.len() > 2 { B64[n as usize & 63] as char } else { '=' }); + } + out +} + +fn b64_decode(text: &str) -> Option> { + let mut out = Vec::with_capacity(text.len() / 4 * 3); + let (mut acc, mut bits) = (0u32, 0u32); + for c in text.bytes() { + let v = match c { + b'A'..=b'Z' => c - b'A', + b'a'..=b'z' => c - b'a' + 26, + b'0'..=b'9' => c - b'0' + 52, + b'+' => 62, + b'/' => 63, + b'=' => break, + b' ' | b'\n' | b'\r' | b'\t' => continue, + _ => return None, + }; + acc = (acc << 6) | u32::from(v); + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + acc &= (1 << bits) - 1; + } + } + Some(out) +} + +// ── XML lesen: einfacher Baum ─────────────────────────────────────────────── + +#[derive(Debug, Default)] +struct Node { + name: String, + attrs: Vec<(String, String)>, + text: String, + children: Vec, +} + +impl Node { + fn child(&self, name: &str) -> Option<&Node> { + self.children.iter().find(|c| c.name == name) + } + fn kids<'a>(&'a self, name: &'a str) -> impl Iterator { + self.children.iter().filter(move |c| c.name == name) + } + fn attr(&self, name: &str) -> &str { + self.attrs.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str()).unwrap_or("") + } + /// Text eines Kindelements (getrimmt), leer wenn es fehlt. + fn text_of(&self, name: &str) -> String { + self.child(name).map(|c| c.text.trim().to_string()).unwrap_or_default() + } +} + +fn local(name: &[u8]) -> String { + let s = String::from_utf8_lossy(name); + match s.rfind(':') { + Some(i) => s[i + 1..].to_string(), + None => s.into_owned(), + } +} + +/// XML → Baum (Namensräume/Präfixe werden verworfen). Fehler bei kaputtem XML oder zu tiefer Verschachtelung. +fn parse_xml(bytes: &[u8]) -> Result { + // BOM überspringen. + let bytes = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes); + let mut reader = Reader::from_reader(bytes); + let mut stack: Vec = vec![Node::default()]; + let mut root: Option = None; + loop { + let ev = reader.read_event().map_err(|e| format!("XML: {e}"))?; + match ev { + Event::Start(ref e) | Event::Empty(ref e) => { + let mut node = Node { name: local(e.name().as_ref()), ..Node::default() }; + for a in e.attributes().flatten() { + let v = a.unescape_value().map(|c| c.into_owned()).unwrap_or_default(); + node.attrs.push((local(a.key.as_ref()), v)); + } + stack.push(node); + if stack.len() > MAX_DEPTH { + return Err("XML: zu tief verschachtelt".into()); + } + // Empty-Elemente haben kein End-Ereignis: sofort schliessen (s. unten, Event::Empty-Zweig). + if matches!(ev, Event::Empty(_)) { + close(&mut stack, &mut root)?; + } + } + Event::End(_) => close(&mut stack, &mut root)?, + Event::Text(t) => { + if let Some(top) = stack.last_mut() { + top.text.push_str(&t.decode().map_err(|e| format!("XML: {e}"))?); + } + } + Event::CData(t) => { + if let Some(top) = stack.last_mut() { + top.text.push_str(&String::from_utf8_lossy(&t)); + } + } + Event::GeneralRef(r) => { + let name = String::from_utf8_lossy(&r).into_owned(); + let ch = match r.resolve_char_ref() { + Ok(Some(c)) => Some(c.to_string()), + _ => quick_xml::escape::resolve_predefined_entity(&name).map(str::to_string), + }; + if let (Some(s), Some(top)) = (ch, stack.last_mut()) { + top.text.push_str(&s); + } + } + Event::Eof => break, + _ => {} + } + } + if stack.len() != 1 { + return Err("XML: Element nicht geschlossen".into()); + } + root.ok_or_else(|| "XML: leeres Dokument".to_string()) +} + +fn close(stack: &mut Vec, root: &mut Option) -> Result<(), String> { + if stack.len() < 2 { + return Err("XML: schliessendes Element ohne Anfang".into()); + } + let node = stack.pop().unwrap_or_default(); + if stack.len() >= 2 { + if let Some(parent) = stack.last_mut() { + parent.children.push(node); + } + } else if root.is_some() { + return Err("XML: mehrere Wurzelelemente".into()); + } else { + *root = Some(node); + } + Ok(()) +} + +// ── Lesen ─────────────────────────────────────────────────────────────────── + +fn num(s: &str) -> f64 { + match s.trim().parse::() { + Ok(v) if v.is_finite() => v, + _ => 0.0, + } +} + +fn point(n: Option<&Node>) -> [f64; 3] { + match n { + Some(n) => [num(&n.text_of("X")), num(&n.text_of("Y")), num(&n.text_of("Z"))], + None => [0.0; 3], + } +} + +fn parse_components(list: Option<&Node>) -> Vec { + let Some(list) = list else { return Vec::new() }; + list.kids("Component") + .map(|c| Component { + ifc_guid: c.attr("IfcGuid").to_string(), + originating_system: c.text_of("OriginatingSystem"), + authoring_tool_id: c.text_of("AuthoringToolId"), + }) + .filter(|c| !c.ifc_guid.is_empty()) + .collect() +} + +fn parse_viewpoint(xml: &[u8], vp: &mut Viewpoint) -> Result<(), String> { + let root = parse_xml(xml)?; + if root.name != "VisualizationInfo" { + return Err(format!("Viewpoint: Wurzel \"{}\" statt VisualizationInfo", root.name)); + } + if vp.guid.is_empty() { + vp.guid = root.attr("Guid").to_string(); + } + vp.default_visibility = true; + if let Some(comps) = root.child("Components") { + vp.selection = parse_components(comps.child("Selection")); + if let Some(vis) = comps.child("Visibility") { + vp.default_visibility = !vis.attr("DefaultVisibility").eq_ignore_ascii_case("false"); + vp.exceptions = parse_components(vis.child("Exceptions")); + } + } + let cam = |n: &Node, kind: &str| Camera { + kind: kind.to_string(), + position: point(n.child("CameraViewPoint")), + direction: point(n.child("CameraDirection")), + up: point(n.child("CameraUpVector")), + field_of_view: num(&n.text_of("FieldOfView")), + view_to_world_scale: num(&n.text_of("ViewToWorldScale")), + aspect_ratio: num(&n.text_of("AspectRatio")), + }; + vp.camera = root + .child("PerspectiveCamera") + .map(|n| cam(n, "perspective")) + .or_else(|| root.child("OrthogonalCamera").map(|n| cam(n, "orthogonal"))); + if let Some(planes) = root.child("ClippingPlanes") { + vp.clipping_planes = planes + .kids("ClippingPlane") + .map(|p| ClippingPlane { location: point(p.child("Location")), direction: point(p.child("Direction")) }) + .collect(); + } + Ok(()) +} + +fn parse_header_files(header: &Node) -> Vec { + // 2.1: Header > File; 3.0: Header > Files > File. + let mut out = Vec::new(); + let mut collect = |parent: &Node| { + for f in parent.kids("File") { + out.push(HeaderFile { + ifc_project: f.attr("IfcProject").to_string(), + ifc_spatial_structure_element: f.attr("IfcSpatialStructureElement").to_string(), + is_external: !f.attr("IsExternal").eq_ignore_ascii_case("false"), + filename: f.text_of("Filename"), + date: f.text_of("Date"), + reference: f.text_of("Reference"), + }); + } + }; + collect(header); + if let Some(files) = header.child("Files") { + collect(files); + } + out +} + +fn parse_comment(c: &Node) -> Comment { + Comment { + guid: c.attr("Guid").to_string(), + date: c.text_of("Date"), + author: c.text_of("Author"), + comment: c.text_of("Comment"), + viewpoint_guid: c.child("Viewpoint").map(|v| v.attr("Guid").to_string()).unwrap_or_default(), + modified_date: c.text_of("ModifiedDate"), + modified_author: c.text_of("ModifiedAuthor"), + } +} + +/// Gibt den Eintrag `name` relativ zum Themenordner zurück (Pfade mit `..` und absolute werden verworfen). +fn read_entry(files: &HashMap>, dir: &str, name: &str) -> Option> { + let name = name.trim().replace('\\', "/"); + if name.is_empty() || name.starts_with('/') || name.split('/').any(|p| p == "..") { + return None; + } + files.get(&format!("{dir}{name}")).cloned().or_else(|| files.get(&name).cloned()) +} + +fn parse_topic(markup: &[u8], dir: &str, files: &HashMap>) -> Result { + let root = parse_xml(markup)?; + if root.name != "Markup" { + return Err(format!("markup.bcf: Wurzel \"{}\" statt Markup", root.name)); + } + let tn = root.child("Topic").ok_or("markup.bcf: Topic fehlt")?; + let mut t = Topic { + guid: tn.attr("Guid").to_string(), + topic_type: tn.attr("TopicType").to_string(), + topic_status: tn.attr("TopicStatus").to_string(), + title: tn.text_of("Title"), + priority: tn.text_of("Priority"), + creation_date: tn.text_of("CreationDate"), + creation_author: tn.text_of("CreationAuthor"), + modified_date: tn.text_of("ModifiedDate"), + modified_author: tn.text_of("ModifiedAuthor"), + due_date: tn.text_of("DueDate"), + assigned_to: tn.text_of("AssignedTo"), + stage: tn.text_of("Stage"), + description: tn.text_of("Description"), + ..Topic::default() + }; + if t.guid.is_empty() { + return Err("markup.bcf: Topic ohne Guid".into()); + } + if let Some(h) = root.child("Header") { + t.header_files = parse_header_files(h); + } + // Labels: 2.1 mehrfach text; 3.0 . + for l in tn.kids("Labels") { + let inner: Vec<&Node> = l.kids("Label").collect(); + if inner.is_empty() { + let s = l.text.trim(); + if !s.is_empty() { + t.labels.push(s.to_string()); + } + } + for n in inner { + let s = n.text.trim(); + if !s.is_empty() { + t.labels.push(s.to_string()); + } + } + } + // Kommentare: 2.1 direkt unter Markup, 3.0 unter Topic > Comments. + for c in root.kids("Comment") { + t.comments.push(parse_comment(c)); + } + for cs in tn.kids("Comments") { + for c in cs.kids("Comment") { + t.comments.push(parse_comment(c)); + } + } + // Viewpoints: 2.1 Markup > Viewpoints (je Eintrag), 3.0 Topic > Viewpoints > ViewPoint. + let mut entries: Vec<&Node> = Vec::new(); + for v in root.kids("Viewpoints") { + entries.push(v); + } + for vs in tn.kids("Viewpoints") { + let inner: Vec<&Node> = vs.kids("ViewPoint").collect(); + if inner.is_empty() { entries.push(vs) } else { entries.extend(inner) } + } + for e in entries { + let mut vp = Viewpoint { + guid: e.attr("Guid").to_string(), + file: e.text_of("Viewpoint"), + snapshot_file: e.text_of("Snapshot"), + default_visibility: true, + ..Viewpoint::default() + }; + if vp.file.is_empty() && !vp.snapshot_file.is_empty() { + // Nur Snapshot, kein Viewpoint-Dokument: Eintrag behalten. + } else if vp.file.is_empty() { + continue; + } + if !vp.file.is_empty() { + if let Some(xml) = read_entry(files, dir, &vp.file) { + // Kaputte Viewpoint-Datei: Thema bleibt lesbar, der Viewpoint ohne Kamera. + let _ = parse_viewpoint(&xml, &mut vp); + } + } + if !vp.snapshot_file.is_empty() { + if let Some(png) = read_entry(files, dir, &vp.snapshot_file) { + vp.snapshot = b64_encode(&png); + } + } + t.viewpoints.push(vp); + } + Ok(t) +} + +/// .bcfzip lesen. Fehler bei Unsinn (kein ZIP, weder `bcf.version` noch ein `markup.bcf`, kaputtes Markup). +pub fn read_bcf(bytes: &[u8]) -> Result { + let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("Keine BCF-Datei (ZIP): {e}"))?; + let mut files: HashMap> = HashMap::new(); + for i in 0..zip.len() { + let Ok(entry) = zip.by_index(i) else { continue }; + if entry.is_dir() { + continue; + } + let name = entry.name().replace('\\', "/"); + let mut buf = Vec::new(); + entry.take(MAX_ENTRY_BYTES + 1).read_to_end(&mut buf).map_err(|e| format!("ZIP-Eintrag {name}: {e}"))?; + if buf.len() as u64 > MAX_ENTRY_BYTES { + return Err(format!("ZIP-Eintrag {name} ist zu gross")); + } + files.insert(name, buf); + } + let mut out = BcfFile::default(); + if let Some(v) = files.get("bcf.version") { + if let Ok(root) = parse_xml(v) { + out.version = root.attr("VersionId").to_string(); + } + } + let mut markups: Vec<&String> = files + .keys() + .filter(|k| k.ends_with("/markup.bcf") && k.matches('/').count() == 1) + .collect(); + markups.sort(); + if out.version.is_empty() && markups.is_empty() { + return Err("Keine BCF-Datei: weder bcf.version noch markup.bcf gefunden".into()); + } + if markups.len() > MAX_TOPICS { + return Err("Zu viele Themen".into()); + } + if let Some(p) = files.get("project.bcfp") { + if let Ok(root) = parse_xml(p) { + if let Some(pr) = root.child("Project") { + out.project_id = pr.attr("ProjectId").to_string(); + out.project_name = pr.text_of("Name"); + } + } + } + for key in markups { + let dir = &key[..key.len() - "markup.bcf".len()]; + let topic = parse_topic(&files[key], dir, &files).map_err(|e| format!("{key}: {e}"))?; + out.topics.push(topic); + } + if out.version.is_empty() { + out.version = "2.1".into(); + } + Ok(out) +} + +// ── Schreiben ─────────────────────────────────────────────────────────────── + +fn esc(s: &str) -> String { + let mut o = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => o.push_str("&"), + '<' => o.push_str("<"), + '>' => o.push_str(">"), + '"' => o.push_str("""), + // In XML 1.0 unzulässige Steuerzeichen weglassen. + c if (c as u32) < 0x20 && c != '\n' && c != '\r' && c != '\t' => {} + c => o.push(c), + } + } + o +} + +/// Schreibt `text`, nur wenn `text` nicht leer ist. +fn leaf(out: &mut String, ind: usize, name: &str, text: &str) { + if !text.is_empty() { + out.push_str(&format!("{:ind$}<{name}>{}\n", "", esc(text), ind = ind)); + } +} + +fn f(v: f64) -> String { + if v.is_finite() { format!("{v}") } else { "0".into() } +} + +fn xyz(out: &mut String, ind: usize, name: &str, p: &[f64; 3]) { + out.push_str(&format!("{:ind$}<{name}>\n", "", ind = ind)); + for (n, v) in ["X", "Y", "Z"].iter().zip(p) { + out.push_str(&format!("{:ind$}<{n}>{}\n", "", f(*v), ind = ind + 2)); + } + out.push_str(&format!("{:ind$}\n", "", ind = ind)); +} + +fn components(out: &mut String, ind: usize, list: &[Component]) { + for c in list { + if c.ifc_guid.is_empty() { + continue; + } + out.push_str(&format!("{:ind$}\n", "", esc(&c.ifc_guid), ind = ind)); + leaf(out, ind + 2, "OriginatingSystem", &c.originating_system); + leaf(out, ind + 2, "AuthoringToolId", &c.authoring_tool_id); + out.push_str(&format!("{:ind$}\n", "", ind = ind)); + } +} + +fn viewpoint_xml(vp: &Viewpoint) -> String { + let mut o = String::from("\n"); + o.push_str(&format!("\n", esc(&vp.guid))); + o.push_str(" \n"); + if vp.selection.is_empty() { + o.push_str(" \n"); + } else { + o.push_str(" \n"); + components(&mut o, 6, &vp.selection); + o.push_str(" \n"); + } + o.push_str(&format!(" \n", vp.default_visibility)); + if vp.exceptions.is_empty() { + o.push_str(" \n"); + } else { + o.push_str(" \n"); + components(&mut o, 8, &vp.exceptions); + o.push_str(" \n"); + } + o.push_str(" \n \n"); + if let Some(c) = &vp.camera { + let ortho = c.kind == "orthogonal"; + let tag = if ortho { "OrthogonalCamera" } else { "PerspectiveCamera" }; + o.push_str(&format!(" <{tag}>\n")); + xyz(&mut o, 4, "CameraViewPoint", &c.position); + xyz(&mut o, 4, "CameraDirection", &c.direction); + xyz(&mut o, 4, "CameraUpVector", &c.up); + if ortho { + o.push_str(&format!(" {}\n", f(c.view_to_world_scale))); + } else { + o.push_str(&format!(" {}\n", f(if c.field_of_view > 0.0 { c.field_of_view } else { 60.0 }))); + } + if c.aspect_ratio > 0.0 && !ortho { + o.push_str(&format!(" {}\n", f(c.aspect_ratio))); + } + o.push_str(&format!(" \n")); + } + if !vp.clipping_planes.is_empty() { + o.push_str(" \n"); + for p in &vp.clipping_planes { + o.push_str(" \n"); + xyz(&mut o, 6, "Location", &p.location); + xyz(&mut o, 6, "Direction", &p.direction); + o.push_str(" \n"); + } + o.push_str(" \n"); + } + o.push_str("\n"); + o +} + +/// Eine sichere Datei-Namenskomponente (keine Pfadtrenner). +fn safe_name(s: &str) -> bool { + !s.is_empty() && !s.contains(['/', '\\']) && s != ".." && s != "." +} + +fn markup_xml(t: &Topic, v3: bool, vp_files: &[(String, String)]) -> String { + let mut o = String::from("\n\n"); + if !t.header_files.is_empty() { + o.push_str("
\n"); + let ind = if v3 { 6 } else { 4 }; + if v3 { + o.push_str(" \n"); + } + for h in &t.header_files { + let mut attrs = String::new(); + if !h.ifc_project.is_empty() { + attrs.push_str(&format!(" IfcProject=\"{}\"", esc(&h.ifc_project))); + } + if !h.ifc_spatial_structure_element.is_empty() { + attrs.push_str(&format!(" IfcSpatialStructureElement=\"{}\"", esc(&h.ifc_spatial_structure_element))); + } + attrs.push_str(&format!(" IsExternal=\"{}\"", h.is_external)); + o.push_str(&format!("{:ind$}\n", "", ind = ind)); + leaf(&mut o, ind + 2, "Filename", &h.filename); + leaf(&mut o, ind + 2, "Date", &h.date); + leaf(&mut o, ind + 2, "Reference", &h.reference); + o.push_str(&format!("{:ind$}\n", "", ind = ind)); + } + if v3 { + o.push_str(" \n"); + } + o.push_str("
\n"); + } + let ty = if t.topic_type.is_empty() { "Issue" } else { &t.topic_type }; + let st = if t.topic_status.is_empty() { "Open" } else { &t.topic_status }; + o.push_str(&format!(" \n", esc(&t.guid), esc(ty), esc(st))); + leaf(&mut o, 4, "Title", if t.title.is_empty() { "-" } else { &t.title }); + leaf(&mut o, 4, "Priority", &t.priority); + // Labels: 2.1 mehrfach , 3.0 . + if v3 { + if !t.labels.is_empty() { + o.push_str(" \n"); + for l in &t.labels { + leaf(&mut o, 6, "Label", l); + } + o.push_str(" \n"); + } + } else { + for l in &t.labels { + leaf(&mut o, 4, "Labels", l); + } + } + leaf(&mut o, 4, "CreationDate", if t.creation_date.is_empty() { "1970-01-01T00:00:00Z" } else { &t.creation_date }); + leaf(&mut o, 4, "CreationAuthor", if t.creation_author.is_empty() { "-" } else { &t.creation_author }); + leaf(&mut o, 4, "ModifiedDate", &t.modified_date); + leaf(&mut o, 4, "ModifiedAuthor", &t.modified_author); + leaf(&mut o, 4, "DueDate", &t.due_date); + leaf(&mut o, 4, "AssignedTo", &t.assigned_to); + leaf(&mut o, 4, "Stage", &t.stage); + leaf(&mut o, 4, "Description", &t.description); + + let comment = |o: &mut String, ind: usize, c: &Comment| { + o.push_str(&format!("{:ind$}\n", "", esc(&c.guid), ind = ind)); + if !v3 { + leaf(o, ind + 2, "VerbalStatus", ""); + } + leaf(o, ind + 2, "Date", if c.date.is_empty() { "1970-01-01T00:00:00Z" } else { &c.date }); + leaf(o, ind + 2, "Author", if c.author.is_empty() { "-" } else { &c.author }); + leaf(o, ind + 2, "Comment", &c.comment); + if !c.viewpoint_guid.is_empty() { + o.push_str(&format!("{:ind$}\n", "", esc(&c.viewpoint_guid), ind = ind + 2)); + } + leaf(o, ind + 2, "ModifiedDate", &c.modified_date); + leaf(o, ind + 2, "ModifiedAuthor", &c.modified_author); + o.push_str(&format!("{:ind$}\n", "", ind = ind)); + }; + let vpoint = |o: &mut String, ind: usize, vp: &Viewpoint, file: &str, snap: &str| { + let tag = if v3 { "ViewPoint" } else { "Viewpoints" }; + o.push_str(&format!("{:ind$}<{tag} Guid=\"{}\">\n", "", esc(&vp.guid), ind = ind)); + leaf(o, ind + 2, "Viewpoint", file); + leaf(o, ind + 2, "Snapshot", snap); + o.push_str(&format!("{:ind$}\n", "", ind = ind)); + }; + if v3 { + if !t.comments.is_empty() { + o.push_str(" \n"); + for c in &t.comments { + comment(&mut o, 6, c); + } + o.push_str(" \n"); + } + if !t.viewpoints.is_empty() { + o.push_str(" \n"); + for (vp, (file, snap)) in t.viewpoints.iter().zip(vp_files) { + vpoint(&mut o, 6, vp, file, snap); + } + o.push_str(" \n"); + } + o.push_str(" \n"); + } else { + o.push_str("
\n"); + for c in &t.comments { + comment(&mut o, 2, c); + } + for (vp, (file, snap)) in t.viewpoints.iter().zip(vp_files) { + vpoint(&mut o, 2, vp, file, snap); + } + } + o.push_str("\n"); + o +} + +/// BCF als .bcfzip schreiben; `version` "2.1" oder "3.0". +pub fn write_bcf(file: &BcfFile, version: &str) -> Result, String> { + let v3 = match version { + "2.1" => false, + "3.0" => true, + v => return Err(format!("BCF-Version {v} wird nicht unterstützt (2.1 oder 3.0)")), + }; + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + let mut put = |name: &str, data: &[u8]| -> Result<(), String> { + zip.start_file(name, opts).map_err(|e| format!("ZIP: {e}"))?; + zip.write_all(data).map_err(|e| format!("ZIP: {e}")) + }; + + put( + "bcf.version", + format!( + "\n\n {version}\n\n" + ) + .as_bytes(), + )?; + if !file.project_id.is_empty() { + let proj = format!( + " \n {}\n \n", + esc(&file.project_id), + esc(&file.project_name) + ); + let root = if v3 { "ProjectInfo" } else { "ProjectExtension" }; + put("project.bcfp", format!("\n<{root}>\n{proj}\n").as_bytes())?; + } + let mut seen = std::collections::HashSet::new(); + for t in &file.topics { + if !safe_name(&t.guid) || !seen.insert(t.guid.clone()) { + return Err(format!("Thema mit ungültiger oder doppelter Guid \"{}\"", t.guid)); + } + let dir = format!("{}/", t.guid); + let mut names: Vec<(String, String)> = Vec::new(); + for (i, vp) in t.viewpoints.iter().enumerate() { + let base = if safe_name(&vp.guid) { vp.guid.clone() } else { format!("vp{i}") }; + let bytes = b64_decode(&vp.snapshot).unwrap_or_default(); + let vfile = if safe_name(&vp.file) { vp.file.clone() } else { format!("viewpoint-{base}.bcfv") }; + let sfile = if bytes.is_empty() { + String::new() + } else if safe_name(&vp.snapshot_file) { + vp.snapshot_file.clone() + } else { + format!("snapshot-{base}.png") + }; + put(&format!("{dir}{vfile}"), viewpoint_xml(vp).as_bytes())?; + if !sfile.is_empty() { + put(&format!("{dir}{sfile}"), &bytes)?; + } + names.push((vfile, sfile)); + } + put(&format!("{dir}markup.bcf"), markup_xml(t, v3, &names).as_bytes())?; + } + zip.finish().map(|c| c.into_inner()).map_err(|e| format!("ZIP: {e}")) +} + +// ── JSON-Grenze (WASM) ────────────────────────────────────────────────────── + +#[cfg(feature = "web")] +mod wasm { + use wasm_bindgen::prelude::*; + + /// .bcfzip → JSON (`BcfFile`); JS-Fehler mit Meldung bei Unsinn. + #[wasm_bindgen] + pub fn bcf_read(bytes: &[u8]) -> Result { + let f = super::read_bcf(bytes).map_err(|e| JsValue::from_str(&e))?; + serde_json::to_string(&f).map_err(|e| JsValue::from_str(&e.to_string())) + } + + /// JSON (`BcfFile`) → .bcfzip der Version "2.1" oder "3.0"; JS-Fehler bei Unsinn. + #[wasm_bindgen] + pub fn bcf_write(json: &str, version: &str) -> Result, JsValue> { + let f: super::BcfFile = serde_json::from_str(json).map_err(|e| JsValue::from_str(&format!("BCF-JSON: {e}")))?; + super::write_bcf(&f, version).map_err(|e| JsValue::from_str(&e)) + } +} + +// ── Tests ─────────────────────────────────────────────────────────────────── + +#[cfg(test)] +mod tests { + use super::*; + + fn sample() -> BcfFile { + let png = vec![0x89, b'P', b'N', b'G', 1, 2, 3, 4, 5]; + BcfFile { + version: "3.0".into(), + project_id: "p-1".into(), + project_name: "Haus & Co".into(), + topics: vec![Topic { + guid: "11111111-2222-3333-4444-555555555555".into(), + topic_type: "Clash".into(), + topic_status: "Active".into(), + title: "Wand \"W1\" kollidiert".into(), + priority: "High".into(), + creation_date: "2026-10-28T10:00:00Z".into(), + creation_author: "karim@example.ch".into(), + modified_date: "2026-10-28T11:00:00Z".into(), + modified_author: "anna@example.ch".into(), + due_date: "2026-11-01T00:00:00Z".into(), + assigned_to: "anna@example.ch".into(), + stage: "Entwurf".into(), + description: "Zeile 1\nZeile 2 mit ü und ".into(), + labels: vec!["Statik".into(), "Brandschutz".into()], + header_files: vec![HeaderFile { + ifc_project: "0n_zVrPdE0cg_UxWSd1GmA".into(), + filename: "haus.ifc".into(), + is_external: false, + ..HeaderFile::default() + }], + comments: vec![Comment { + guid: "c1".into(), + date: "2026-10-28T10:05:00Z".into(), + author: "anna@example.ch".into(), + comment: "Bitte prüfen & bestätigen".into(), + viewpoint_guid: "vp-1".into(), + ..Comment::default() + }], + viewpoints: vec![Viewpoint { + guid: "vp-1".into(), + file: String::new(), + snapshot_file: String::new(), + snapshot: b64_encode(&png), + camera: Some(Camera { + kind: "perspective".into(), + position: [1.5, -2.0, 3.25], + direction: [0.0, 1.0, 0.0], + up: [0.0, 0.0, 1.0], + field_of_view: 55.0, + aspect_ratio: 1.6, + ..Camera::default() + }), + selection: vec![Component { ifc_guid: "0n_zVrPdE0cg_UxWSd1GmA".into(), originating_system: "Dossier".into(), ..Component::default() }], + default_visibility: false, + exceptions: vec![Component { ifc_guid: "3rG4QSmdUCaBHFz1QMCvjw".into(), ..Component::default() }], + clipping_planes: vec![ClippingPlane { location: [0.0, 0.0, 1.2], direction: [0.0, 0.0, -1.0] }], + }], + }], + } + } + + /// Erwartet nach dem Schreiben: Dateinamen sind erzeugt worden. + fn normalize(mut f: BcfFile) -> BcfFile { + for t in &mut f.topics { + for v in &mut t.viewpoints { + v.file.clear(); + v.snapshot_file.clear(); + } + } + f + } + + #[test] + fn rundreise_beide_versionen() { + for ver in ["2.1", "3.0"] { + let src = sample(); + let bytes = write_bcf(&src, ver).unwrap(); + let back = read_bcf(&bytes).unwrap(); + assert_eq!(back.version, ver); + assert_eq!(back.project_id, "p-1"); + assert_eq!(back.project_name, "Haus & Co"); + let (a, b) = (&src.topics[0], &back.topics[0]); + assert_eq!(normalize(BcfFile { topics: vec![b.clone()], ..BcfFile::default() }).topics[0].viewpoints[0], a.viewpoints[0], "Viewpoint {ver}"); + let mut b2 = b.clone(); + for v in &mut b2.viewpoints { + v.file.clear(); + v.snapshot_file.clear(); + } + assert_eq!(&b2, a, "Thema {ver}"); + } + } + + #[test] + fn snapshot_bytes_bleiben_erhalten() { + let bytes = write_bcf(&sample(), "2.1").unwrap(); + let back = read_bcf(&bytes).unwrap(); + assert_eq!(b64_decode(&back.topics[0].viewpoints[0].snapshot).unwrap(), vec![0x89, b'P', b'N', b'G', 1, 2, 3, 4, 5]); + } + + #[test] + fn orthogonale_kamera() { + let mut f = sample(); + f.topics[0].viewpoints[0].camera = + Some(Camera { kind: "orthogonal".into(), view_to_world_scale: 12.5, direction: [0.0, 0.0, -1.0], up: [0.0, 1.0, 0.0], ..Camera::default() }); + for ver in ["2.1", "3.0"] { + let back = read_bcf(&write_bcf(&f, ver).unwrap()).unwrap(); + let c = back.topics[0].viewpoints[0].camera.clone().unwrap(); + assert_eq!(c.kind, "orthogonal"); + assert_eq!(c.view_to_world_scale, 12.5); + } + } + + #[test] + fn unsinn_ergibt_fehler() { + assert!(read_bcf(b"").is_err()); + assert!(read_bcf(b"kein zip").is_err()); + assert!(read_bcf(&[0x50, 0x4b, 0x03, 0x04, 0, 0, 0]).is_err()); + // ZIP ohne BCF-Inhalt. + let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); + z.start_file("x.txt", zip::write::SimpleFileOptions::default()).unwrap(); + z.write_all(b"hi").unwrap(); + let bytes = z.finish().unwrap().into_inner(); + assert!(read_bcf(&bytes).is_err()); + // Kaputtes Markup. + let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); + z.start_file("a/markup.bcf", zip::write::SimpleFileOptions::default()).unwrap(); + z.write_all(b"").unwrap(); + let bytes = z.finish().unwrap().into_inner(); + assert!(read_bcf(&bytes).is_err()); + // Zufällige Bytes dürfen nie paniken. + let mut s = 12345u32; + for n in 0..200 { + let junk: Vec = (0..n * 7).map(|_| { s = s.wrapping_mul(1664525).wrapping_add(1013904223); (s >> 24) as u8 }).collect(); + let _ = read_bcf(&junk); + } + } + + #[test] + fn schreiben_prueft_eingabe() { + assert!(write_bcf(&sample(), "9.9").is_err()); + let mut f = sample(); + f.topics[0].guid = "../x".into(); + assert!(write_bcf(&f, "2.1").is_err()); + let mut g = sample(); + g.topics.push(g.topics[0].clone()); + assert!(write_bcf(&g, "2.1").is_err()); + // Kaputtes Base64 und Steuerzeichen paniken nicht. + let mut h = sample(); + h.topics[0].viewpoints[0].snapshot = "!!!".into(); + h.topics[0].description = "a\u{1}b".into(); + let back = read_bcf(&write_bcf(&h, "3.0").unwrap()).unwrap(); + assert_eq!(back.topics[0].description, "ab"); + } + + #[test] + fn tief_verschachteltes_xml_wird_abgelehnt() { + let xml = format!("{}{}", "".repeat(200), "".repeat(200)); + assert!(parse_xml(xml.as_bytes()).is_err()); + } + + #[test] + fn base64_rundreise() { + for n in 0..20u8 { + let d: Vec = (0..n).collect(); + assert_eq!(b64_decode(&b64_encode(&d)).unwrap(), d); + } + assert_eq!(b64_encode(b"Man"), "TWFu"); + assert!(b64_decode("a$b").is_none()); + } + + /// buildingSMART-Beispiele (CC BY-ND 4.0, nicht im Repo): `BCF_TESTCASES=/"Test Cases"`. + #[test] + fn buildingsmart_beispiele() { + let Ok(dir) = std::env::var("BCF_TESTCASES") else { return }; + let (mut n, mut cams, mut sels) = (0, 0, 0); + let mut stack = vec![std::path::PathBuf::from(dir)]; + while let Some(d) = stack.pop() { + for e in std::fs::read_dir(&d).unwrap().flatten() { + let p = e.path(); + if p.is_dir() { + if p.file_name().is_some_and(|f| f == "unzipped") { continue } + stack.push(p); + } else if p.extension().is_some_and(|x| x == "bcf" || x == "bcfzip") { + let bytes = std::fs::read(&p).unwrap(); + let f = read_bcf(&bytes).unwrap_or_else(|err| panic!("{}: {err}", p.display())); + assert!(!f.topics.is_empty(), "{}: keine Themen", p.display()); + for t in &f.topics { + assert!(!t.guid.is_empty() && !t.title.is_empty(), "{}", p.display()); + } + for v in f.topics.iter().flat_map(|t| &t.viewpoints) { + cams += usize::from(v.camera.is_some()); + sels += usize::from(!v.selection.is_empty()); + } + // Rundreise in beide Versionen bleibt lesbar. + for ver in ["2.1", "3.0"] { + let back = read_bcf(&write_bcf(&f, ver).unwrap()).unwrap(); + assert_eq!(back.topics.len(), f.topics.len()); + assert_eq!(back.topics[0].title, f.topics[0].title); + assert_eq!(back.topics[0].viewpoints.len(), f.topics[0].viewpoints.len()); + } + n += 1; + } + } + } + eprintln!("{n} buildingSMART-Dateien gelesen, {cams} Kameras, {sels} Viewpoints mit Auswahl"); + assert!(n > 0 && cams > 0 && sels > 0); + } +} diff --git a/src-tauri/fileio/src/lib.rs b/src-tauri/fileio/src/lib.rs index 769d4c89..179c21f1 100644 --- a/src-tauri/fileio/src/lib.rs +++ b/src-tauri/fileio/src/lib.rs @@ -23,6 +23,7 @@ pub mod ifc_import; pub mod ifc_semantic; pub mod ifc_export; pub mod ifc_openings; +pub mod bcf; pub mod csg; mod ifc_sweep; mod ifc_nurbs; diff --git a/src/App.tsx b/src/App.tsx index 58a171e0..4d717fd9 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -3440,6 +3440,7 @@ export default function App() { resourcesOpen={resourcesOpen} onToggleResources={() => toggleResources()} onOpenSettings={() => openSettings()} + onOpenBcf={() => setLayout((l) => revealPanel(l, "bcf"))} /> ) } diff --git a/src/cli/main.ts b/src/cli/main.ts index a65f6af6..821ddb31 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -58,6 +58,8 @@ import { parseProjectFile, planToSvgString, serializeProject, + parseBcf, + bcfInfo, setWasmBytesProvider, initCore, validateProject, @@ -134,12 +136,38 @@ function out(args: Args, text: string | Uint8Array, defaultName: string): void { } } +/** `dossier-cli bcf-info `: Themen einer BCF-Datei (2.1/3.0) als JSON, ohne Snapshot-Bytes. */ +async function runBcfInfo(path: string | undefined): Promise { + if (!path) { + process.stderr.write("Aufruf: dossier-cli bcf-info \n"); + return 2; + } + setWasmBytesProvider(async (name) => { + const rel = WASM_FILES[name]; + if (!rel) throw new Error(`unbekanntes WASM-Modul ${name}`); + return readFileSync(join(wasmDir(), rel)); + }); + let bytes: Uint8Array; + try { + bytes = new Uint8Array(readFileSync(path)); + } catch (e) { + fail(`Datei nicht lesbar: ${path} (${e instanceof Error ? e.message : String(e)})`); + } + try { + process.stdout.write(JSON.stringify(bcfInfo(await parseBcf(bytes)), null, 2) + "\n"); + } catch (e) { + fail(`BCF: ${e instanceof Error ? e.message : String(e)}`); + } + return 0; +} + export async function run(argv: string[]): Promise { const args = parseArgs(argv); const [file, command, ...rest] = args.positional; + if (file === "bcf-info") return runBcfInfo(command); if (!file || !command) { process.stderr.write( - "Aufruf: dossier-cli [Optionen]\n", + "Aufruf: dossier-cli [Optionen]\n dossier-cli bcf-info \n", ); return 2; } diff --git a/src/core/extra.ts b/src/core/extra.ts index a4d1c4b7..6e820a97 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -9,6 +9,7 @@ export { buildPlanDxfBinary } from "../export/exportDxf"; export { loadFileio } from "../engine/fileioWasm"; export { readIfc, ifcToImportedMeshes } from "../io/ifcImport"; export { readIfcElements, ifcElementsToProject } from "../io/ifcElements"; +export { parseBcf, writeBcf, bcfInfo } from "../io/bcf"; export { projectGeoOrigin } from "../model/geoRebase"; export { ensureContextCategories } from "../model/contextCategories"; export { projectToWorldCoords } from "../model/geoRebase"; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 94929041..580c32ab 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -2245,6 +2245,39 @@ export const de = { "start.recent": "Zuletzt geöffnet", "start.recent.remove": "Aus der Liste entfernen", "start.recentMissing": "Datei nicht gefunden — aus der Liste entfernt.", + "nav.bcf": "BCF-Themen", + "bcf.open": "Öffnen…", + "bcf.new": "Neu", + "bcf.save": "Speichern…", + "bcf.format": "Format", + "bcf.author": "Autor", + "bcf.author.placeholder": "Name oder E-Mail", + "bcf.empty": "Keine BCF-Datei geladen. Eine .bcfzip von Solibri, BIMcollab, Revit oder ArchiCAD öffnen oder ein neues Thema aus der Auswahl anlegen. Die Themen liegen in einer eigenen Datei, nicht im Projekt.", + "bcf.noTopics": "Die Datei enthält keine Themen.", + "bcf.fileInfo": "{name} · BCF {version} · {n} Themen", + "bcf.newFromSelection": "Thema aus Auswahl", + "bcf.newFromSelection.hint": "Legt ein Thema an, das auf die im Modell gewählten Bauteile zeigt (über deren IFC-GlobalId).", + "bcf.needSelection": "Zuerst Bauteile im Modell auswählen.", + "bcf.defaultTitle": "Neues Thema", + "bcf.status": "Status", + "bcf.type": "Typ", + "bcf.priority": "Priorität", + "bcf.assignedTo": "Zuständig", + "bcf.dueDate": "Fällig", + "bcf.labels": "Labels", + "bcf.description": "Beschreibung", + "bcf.comments": "Kommentare", + "bcf.commentPlaceholder": "Kommentar schreiben…", + "bcf.addComment": "Kommentieren", + "bcf.camera": "Kamera", + "bcf.camera.perspective": "perspektivisch, Position {x} / {y} / {z} m, Sichtfeld {fov}°", + "bcf.camera.orthogonal": "orthogonal, Position {x} / {y} / {z} m", + "bcf.components": "{found} von {total} Bauteilen im Modell gefunden und gewählt.", + "bcf.components.none": "Dieses Thema verweist auf keine Bauteile.", + "bcf.selectElements": "Bauteile wählen", + "bcf.openFailed": "BCF-Datei nicht lesbar: {error}", + "bcf.saved": "BCF gespeichert.", + "bcf.saveFailed": "BCF nicht gespeichert: {error}", } as const; export type TranslationKey = keyof typeof de; diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 86198e5b..f0dd08a3 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -2231,4 +2231,37 @@ export const en: Record = { "start.recent": "Recently opened", "start.recent.remove": "Remove from list", "start.recentMissing": "File not found — removed from the list.", + "nav.bcf": "BCF issues", + "bcf.open": "Open…", + "bcf.new": "New", + "bcf.save": "Save…", + "bcf.format": "Format", + "bcf.author": "Author", + "bcf.author.placeholder": "Name or e-mail", + "bcf.empty": "No BCF file loaded. Open a .bcfzip from Solibri, BIMcollab, Revit or ArchiCAD, or create a new issue from the selection. Issues live in their own file, not in the project.", + "bcf.noTopics": "The file contains no issues.", + "bcf.fileInfo": "{name} · BCF {version} · {n} issues", + "bcf.newFromSelection": "Issue from selection", + "bcf.newFromSelection.hint": "Creates an issue pointing at the elements selected in the model (via their IFC GlobalId).", + "bcf.needSelection": "Select elements in the model first.", + "bcf.defaultTitle": "New issue", + "bcf.status": "Status", + "bcf.type": "Type", + "bcf.priority": "Priority", + "bcf.assignedTo": "Assigned to", + "bcf.dueDate": "Due", + "bcf.labels": "Labels", + "bcf.description": "Description", + "bcf.comments": "Comments", + "bcf.commentPlaceholder": "Write a comment…", + "bcf.addComment": "Comment", + "bcf.camera": "Camera", + "bcf.camera.perspective": "perspective, position {x} / {y} / {z} m, field of view {fov}°", + "bcf.camera.orthogonal": "orthogonal, position {x} / {y} / {z} m", + "bcf.components": "{found} of {total} elements found in the model and selected.", + "bcf.components.none": "This issue does not point at any elements.", + "bcf.selectElements": "Select elements", + "bcf.openFailed": "BCF file not readable: {error}", + "bcf.saved": "BCF saved.", + "bcf.saveFailed": "BCF not saved: {error}", }; diff --git a/src/io/bcf.test.ts b/src/io/bcf.test.ts new file mode 100644 index 00000000..6f6080ba --- /dev/null +++ b/src/io/bcf.test.ts @@ -0,0 +1,148 @@ +// BCF-Fassade ([BCF]): Rundreise über Rust, Fehlerfälle, reine Hilfen und die GlobalId-Zuordnung +// zum IFC-Export (gleiche Ableitung → Dossier → IFC → BCF → Dossier trifft). + +import "../engine/fileioWasm.setup"; +import { describe, expect, it } from "vitest"; +import { + addComment, + addTopic, + bcfInfo, + emptyBcf, + newTopic, + newViewpoint, + parseBcf, + setTopicStatus, + writeBcf, + type BcfCamera, +} from "./bcf"; +import { buildGuidIndex, emptyBcfSelection, resolveGuids, selectionToGuids, viewpointGuids } from "./bcfMatch"; +import { exportIfcSpf, ifcGuid } from "../export/exportIfc"; +import { sampleProject } from "../model/sampleProject"; +import type { Project } from "../model/types"; + +const camera: BcfCamera = { + kind: "perspective", + position: [10, -12, 8], + direction: [-0.5, 0.6, -0.4], + up: [0, 0, 1], + fieldOfView: 50, + viewToWorldScale: 0, + aspectRatio: 1.5, +}; + +function sample() { + const vp = newViewpoint("vp-1", ["0n_zVrPdE0cg_UxWSd1GmA"], camera); + let f = emptyBcf("proj-1", "Haus Müller"); + f = addTopic(f, newTopic({ guid: "11111111-2222-3333-4444-555555555555", title: "Wand zu dünn", author: "a@b.ch", now: "2026-10-28T09:00:00Z", description: "Mindestens 30 cm", viewpoints: [vp] })); + f = addComment(f, "11111111-2222-3333-4444-555555555555", { guid: "c-1", date: "2026-10-28T09:10:00Z", author: "c@d.ch", comment: "Einverstanden", viewpointGuid: "vp-1", modifiedDate: "", modifiedAuthor: "" }); + return setTopicStatus(f, "11111111-2222-3333-4444-555555555555", "Resolved", "c@d.ch", "2026-10-28T09:20:00Z"); +} + +describe("BCF-Fassade", () => { + it("Rundreise 2.1 und 3.0 über Rust", async () => { + for (const version of ["2.1", "3.0"] as const) { + const bytes = await writeBcf(sample(), version); + expect(bytes[0]).toBe(0x50); // ZIP + const back = await parseBcf(bytes); + expect(back.version).toBe(version); + expect(back.projectName).toBe("Haus Müller"); + const t = back.topics[0]; + expect(t.title).toBe("Wand zu dünn"); + expect(t.topicStatus).toBe("Resolved"); + expect(t.modifiedAuthor).toBe("c@d.ch"); + expect(t.comments).toHaveLength(1); + expect(t.comments[0].comment).toBe("Einverstanden"); + expect(t.comments[0].viewpointGuid).toBe("vp-1"); + expect(t.viewpoints[0].camera).toEqual(camera); + expect(t.viewpoints[0].selection[0].ifcGuid).toBe("0n_zVrPdE0cg_UxWSd1GmA"); + } + }); + + it("Unsinn ergibt einen Fehler, keinen Absturz", async () => { + await expect(parseBcf(new Uint8Array([1, 2, 3]))).rejects.toThrow(); + await expect(parseBcf(new Uint8Array())).rejects.toThrow(); + await expect(writeBcf(sample(), "9.9" as never)).rejects.toThrow(/Version/); + const bad = { ...sample(), topics: [{ ...sample().topics[0], guid: "../x" }] }; + await expect(writeBcf(bad, "2.1")).rejects.toThrow(); + }); + + it("Hilfen ändern den Eingang nicht", () => { + const f = emptyBcf(); + const g = addTopic(f, newTopic({ guid: "g", title: "t", author: "a", now: "n" })); + expect(f.topics).toHaveLength(0); + expect(g.topics).toHaveLength(1); + const h = setTopicStatus(g, "g", "Closed", "x", "later"); + expect(g.topics[0].topicStatus).toBe("Open"); + expect(h.topics[0].topicStatus).toBe("Closed"); + }); + + it("bcfInfo ohne Snapshot-Bytes", async () => { + const info = bcfInfo(await parseBcf(await writeBcf(sample(), "3.0"))) as { topicCount: number; topics: { viewpoints: { selected: string[] }[] }[] }; + expect(info.topicCount).toBe(1); + expect(info.topics[0].viewpoints[0].selected).toEqual(["0n_zVrPdE0cg_UxWSd1GmA"]); + expect(JSON.stringify(info)).not.toContain("snapshot\":\""); + }); +}); + +describe("BCF-GlobalId-Zuordnung", () => { + const ifc = exportIfcSpf(sampleProject); + + it("jede GlobalId des Index steht im IFC-Export", () => { + const index = buildGuidIndex(sampleProject); + const channels = new Set(); + let found = 0; + for (const [guid, target] of index) { + // `opening/…` (IfcOpeningElement) wird in manchen Wänden nicht geschrieben — die Füllung (`fill/…`) schon. + if (ifc.includes(`'${guid}'`)) { + found++; + channels.add(target.channel); + } + } + expect(found).toBeGreaterThan(10); + for (const c of ["wallIds", "ceilingIds", "openingIds"]) expect(channels.has(c)).toBe(true); + }); + + it("Rundreise Auswahl → GlobalId → Auswahl", () => { + const sel = emptyBcfSelection(); + sel.wallIds = sampleProject.walls.slice(0, 2).map((w) => w.id); + sel.ceilingIds = (sampleProject.ceilings ?? []).slice(0, 1).map((c) => c.id); + sel.openingIds = (sampleProject.openings ?? []).slice(0, 1).map((o) => o.id); + const guids = selectionToGuids(sampleProject, sel); + expect(guids).toHaveLength(sel.wallIds.length + sel.ceilingIds.length + sel.openingIds.length); + for (const g of guids) expect(ifc).toContain(`'${g}'`); + const back = resolveGuids(sampleProject, guids); + expect(back.missing).toEqual([]); + expect(back.selection).toEqual(sel); + }); + + it("Wand-GlobalId entspricht der im Export (Projekt-id/wall/id)", () => { + const w = sampleProject.walls[0]; + const g = ifcGuid(`${sampleProject.id}/wall/${w.id}`); + expect(resolveGuids(sampleProject, [g]).selection.wallIds).toEqual([w.id]); + }); + + it("unbekannte GUIDs werden gemeldet", () => { + const r = resolveGuids(sampleProject, ["0000000000000000000000", ifcGuid(`${sampleProject.id}/wall/${sampleProject.walls[0].id}`)]); + expect(r.missing).toEqual(["0000000000000000000000"]); + expect(r.selection.wallIds).toHaveLength(1); + }); + + it("importierte Meshes über ifcGlobalId", () => { + const p = { + ...sampleProject, + context: [{ id: "m1", type: "importedMesh", name: "x", ifcGlobalId: "2O2Fr$t4X7Zf8NOew3FLOH", positions: [], indices: [] }], + } as unknown as Project; + expect(resolveGuids(p, ["2O2Fr$t4X7Zf8NOew3FLOH"]).selection.contextObjectIds).toEqual(["m1"]); + const sel = emptyBcfSelection(); + sel.contextObjectIds = ["m1"]; + expect(selectionToGuids(p, sel)).toEqual(["2O2Fr$t4X7Zf8NOew3FLOH"]); + }); + + it("viewpointGuids: Auswahl, sonst sichtbare Ausnahmen bei defaultVisibility=false", () => { + const vp = newViewpoint("v", ["A", "B", "A"]); + expect(viewpointGuids(vp)).toEqual(["A", "B"]); + const hidden = { ...newViewpoint("v", []), defaultVisibility: false, exceptions: [{ ifcGuid: "C", originatingSystem: "", authoringToolId: "" }] }; + expect(viewpointGuids(hidden)).toEqual(["C"]); + expect(viewpointGuids(newViewpoint("v", []))).toEqual([]); + }); +}); diff --git a/src/io/bcf.ts b/src/io/bcf.ts new file mode 100644 index 00000000..fc64b081 --- /dev/null +++ b/src/io/bcf.ts @@ -0,0 +1,224 @@ +// BCF (BIM Collaboration Format) 2.1/3.0: dünne TS-Fassade über das Rust-Modul `bcf.rs` +// (`src-tauri/fileio`, pkgFileIo). Rust liest/schreibt die .bcfzip, an der Grenze steht JSON +// (Text, Kamera, Komponenten-GUIDs; Snapshots als Base64). Die Themen gehören NICHT ins Projekt: +// sie leben in einer eigenen Datei (s. `panels/BcfPanel.tsx`). +// +// Reine Hilfen (`addComment`, `setTopicStatus`, `newTopic` …) ändern nichts am Eingang, sondern +// liefern Kopien; Zeit und Guid kommen vom Aufrufer (Tests deterministisch). + +import { loadFileio } from "../engine/fileioWasm"; + +export type BcfVersion = "2.1" | "3.0"; +export type Vec3 = [number, number, number]; + +export interface BcfComponent { + /** 22-stellige IFC-GlobalId. */ + ifcGuid: string; + originatingSystem: string; + authoringToolId: string; +} + +export interface BcfCamera { + kind: "perspective" | "orthogonal"; + position: Vec3; + direction: Vec3; + up: Vec3; + /** Vertikaler Öffnungswinkel in Grad (perspektivisch). */ + fieldOfView: number; + viewToWorldScale: number; + aspectRatio: number; +} + +export interface BcfClippingPlane { + location: Vec3; + direction: Vec3; +} + +export interface BcfViewpoint { + guid: string; + file: string; + snapshotFile: string; + /** Snapshot (PNG/JPEG) als Base64, leer = keiner. */ + snapshot: string; + camera: BcfCamera | null; + selection: BcfComponent[]; + /** true = alles sichtbar ausser `exceptions`; false = alles unsichtbar ausser `exceptions`. */ + defaultVisibility: boolean; + exceptions: BcfComponent[]; + clippingPlanes: BcfClippingPlane[]; +} + +export interface BcfComment { + guid: string; + date: string; + author: string; + comment: string; + viewpointGuid: string; + modifiedDate: string; + modifiedAuthor: string; +} + +export interface BcfHeaderFile { + ifcProject: string; + ifcSpatialStructureElement: string; + isExternal: boolean; + filename: string; + date: string; + reference: string; +} + +export interface BcfTopic { + guid: string; + topicType: string; + topicStatus: string; + title: string; + priority: string; + creationDate: string; + creationAuthor: string; + modifiedDate: string; + modifiedAuthor: string; + dueDate: string; + assignedTo: string; + stage: string; + description: string; + labels: string[]; + headerFiles: BcfHeaderFile[]; + comments: BcfComment[]; + viewpoints: BcfViewpoint[]; +} + +export interface BcfFile { + version: string; + projectId: string; + projectName: string; + topics: BcfTopic[]; +} + +function message(e: unknown, fallback: string): string { + return typeof e === "string" ? e : e instanceof Error ? e.message : fallback; +} + +/** .bcfzip lesen. Wirft bei Unsinn (kein ZIP, kein BCF) mit lesbarer Meldung. */ +export async function parseBcf(bytes: Uint8Array): Promise { + const m = await loadFileio(); + try { + return JSON.parse(m.bcf_read(bytes)) as BcfFile; + } catch (e) { + throw new Error(message(e, "BCF nicht lesbar")); + } +} + +/** .bcfzip der gewünschten Version erzeugen. */ +export async function writeBcf(file: BcfFile, version: BcfVersion = "2.1"): Promise { + const m = await loadFileio(); + try { + return m.bcf_write(JSON.stringify(file), version); + } catch (e) { + throw new Error(message(e, "BCF nicht schreibbar")); + } +} + +/** Übliche Status-Werte (BCF lässt eigene Werte über extensions zu). */ +export const BCF_STATUSES = ["Open", "In Progress", "Resolved", "Closed"] as const; + +export function emptyBcf(projectId = "", projectName = ""): BcfFile { + return { version: "2.1", projectId, projectName, topics: [] }; +} + +/** Neues Thema (Guid/Zeit vom Aufrufer). */ +export function newTopic(init: { + guid: string; + title: string; + author: string; + now: string; + description?: string; + viewpoints?: BcfViewpoint[]; +}): BcfTopic { + return { + guid: init.guid, + topicType: "Issue", + topicStatus: "Open", + title: init.title, + priority: "", + creationDate: init.now, + creationAuthor: init.author, + modifiedDate: "", + modifiedAuthor: "", + dueDate: "", + assignedTo: "", + stage: "", + description: init.description ?? "", + labels: [], + headerFiles: [], + comments: [], + viewpoints: init.viewpoints ?? [], + }; +} + +/** Viewpoint aus einer Komponenten-Auswahl (Kamera optional). */ +export function newViewpoint(guid: string, ifcGuids: string[], camera: BcfCamera | null = null, system = "Dossier"): BcfViewpoint { + return { + guid, + file: "", + snapshotFile: "", + snapshot: "", + camera, + selection: ifcGuids.map((ifcGuid) => ({ ifcGuid, originatingSystem: system, authoringToolId: "" })), + defaultVisibility: true, + exceptions: [], + clippingPlanes: [], + }; +} + +function mapTopic(file: BcfFile, guid: string, fn: (t: BcfTopic) => BcfTopic): BcfFile { + return { ...file, topics: file.topics.map((t) => (t.guid === guid ? fn(t) : t)) }; +} + +export function addTopic(file: BcfFile, topic: BcfTopic): BcfFile { + return { ...file, topics: [...file.topics, topic] }; +} + +export function setTopicStatus(file: BcfFile, guid: string, status: string, author: string, now: string): BcfFile { + return mapTopic(file, guid, (t) => ({ ...t, topicStatus: status, modifiedDate: now, modifiedAuthor: author })); +} + +export function addComment(file: BcfFile, guid: string, comment: BcfComment): BcfFile { + return mapTopic(file, guid, (t) => ({ + ...t, + comments: [...t.comments, comment], + modifiedDate: comment.date, + modifiedAuthor: comment.author, + })); +} + +/** Zusammenfassung für `dossier-cli bcf-info`: Themen als JSON-taugliches Objekt, ohne Snapshot-Bytes. */ +export function bcfInfo(file: BcfFile): unknown { + return { + version: file.version, + project: { id: file.projectId, name: file.projectName }, + topicCount: file.topics.length, + topics: file.topics.map((t) => ({ + guid: t.guid, + title: t.title, + type: t.topicType, + status: t.topicStatus, + priority: t.priority, + assignedTo: t.assignedTo, + dueDate: t.dueDate, + creationDate: t.creationDate, + creationAuthor: t.creationAuthor, + description: t.description, + labels: t.labels, + comments: t.comments.map((c) => ({ guid: c.guid, date: c.date, author: c.author, comment: c.comment })), + viewpoints: t.viewpoints.map((v) => ({ + guid: v.guid, + camera: v.camera, + selected: v.selection.map((c) => c.ifcGuid), + defaultVisibility: v.defaultVisibility, + exceptions: v.exceptions.map((c) => c.ifcGuid), + clippingPlanes: v.clippingPlanes.length, + hasSnapshot: v.snapshot.length > 0, + })), + })), + }; +} diff --git a/src/io/bcfMatch.ts b/src/io/bcfMatch.ts new file mode 100644 index 00000000..15ff2543 --- /dev/null +++ b/src/io/bcfMatch.ts @@ -0,0 +1,113 @@ +// BCF ↔ Dossier: IFC-GlobalId eines Komponenten-Verweises ↔ Bauteil-ids des Projekts. +// +// Dieselbe Ableitung wie der IFC-Export (`exportIfc.ts`/`ifc_export.rs`: `ifcGuid("//")`), +// damit die Rundreise Dossier → IFC → Solibri → BCF → Dossier trifft. Importierte Meshes tragen die +// GlobalId ihres Quell-Bauteils (`ImportedMesh.ifcGlobalId`). Bauteile, die im Export nicht vorkommen +// (2D-Zeichnungen, Gruppen), haben keine GlobalId. + +import type { BcfViewpoint } from "./bcf"; +import { ifcGuid } from "../export/exportIfc"; +import type { Project } from "../model/types"; + +/** Ids je Auswahlkanal (Namen wie `selected…Ids` im Zustand). */ +export interface BcfSelection { + wallIds: string[]; + ceilingIds: string[]; + openingIds: string[]; + stairIds: string[]; + roomIds: string[]; + extrudedSolidIds: string[]; + columnIds: string[]; + roofIds: string[]; + contextObjectIds: string[]; +} + +export type BcfChannel = keyof BcfSelection; + +export const emptyBcfSelection = (): BcfSelection => ({ + wallIds: [], + ceilingIds: [], + openingIds: [], + stairIds: [], + roomIds: [], + extrudedSolidIds: [], + columnIds: [], + roofIds: [], + contextObjectIds: [], +}); + +export function bcfSelectionSize(s: BcfSelection): number { + return Object.values(s).reduce((n, ids) => n + ids.length, 0); +} + +interface Target { + channel: BcfChannel; + id: string; +} + +/** GlobalId → Bauteil (alle Bauteile, die der IFC-Export mit dieser GlobalId schreibt). */ +export function buildGuidIndex(project: Project): Map { + const index = new Map(); + const pid = project.id; + const add = (key: string, channel: BcfChannel, id: string) => index.set(ifcGuid(`${pid}/${key}/${id}`), { channel, id }); + for (const w of project.walls ?? []) add("wall", "wallIds", w.id); + for (const c of project.ceilings ?? []) add("slab", "ceilingIds", c.id); + for (const r of project.roofs ?? []) add("roof", "roofIds", r.id); + for (const c of project.columns ?? []) add("column", "columnIds", c.id); + for (const s of project.stairs ?? []) add("stair", "stairIds", s.id); + for (const e of project.extrudedSolids ?? []) add("extrusion", "extrudedSolidIds", e.id); + for (const r of project.rooms ?? []) add("space", "roomIds", r.id); + for (const o of project.openings ?? []) { + // Tür/Fenster (IfcDoor/IfcWindow) und Öffnung (IfcOpeningElement) gehören zur selben Dossier-Öffnung. + add("fill", "openingIds", o.id); + add("opening", "openingIds", o.id); + } + for (const o of project.context ?? []) { + if (o.type === "importedMesh" && o.ifcGlobalId) index.set(o.ifcGlobalId, { channel: "contextObjectIds", id: o.id }); + } + return index; +} + +/** Komponenten-GUIDs → Auswahl; unbekannte GUIDs landen in `missing`. */ +export function resolveGuids(project: Project, guids: string[]): { selection: BcfSelection; missing: string[] } { + const index = buildGuidIndex(project); + const selection = emptyBcfSelection(); + const missing: string[] = []; + for (const g of guids) { + const hit = index.get(g); + if (!hit) { + missing.push(g); + continue; + } + if (!selection[hit.channel].includes(hit.id)) selection[hit.channel].push(hit.id); + } + return { selection, missing }; +} + +/** GUIDs, auf die ein Viewpoint zeigt: gewählte Komponenten, sonst die sichtbaren Ausnahmen bei „alles unsichtbar". */ +export function viewpointGuids(vp: BcfViewpoint): string[] { + const picked = vp.selection.map((c) => c.ifcGuid); + if (picked.length > 0) return [...new Set(picked)]; + if (!vp.defaultVisibility) return [...new Set(vp.exceptions.map((c) => c.ifcGuid))]; + return []; +} + +/** Auswahl → IFC-GlobalIds (Umkehrung von {@link resolveGuids}); Elemente ohne GlobalId entfallen. */ +export function selectionToGuids(project: Project, sel: BcfSelection): string[] { + const pid = project.id; + const guids: string[] = []; + const g = (key: string, ids: string[]) => ids.forEach((id) => guids.push(ifcGuid(`${pid}/${key}/${id}`))); + g("wall", sel.wallIds); + g("slab", sel.ceilingIds); + g("roof", sel.roofIds); + g("column", sel.columnIds); + g("stair", sel.stairIds); + g("extrusion", sel.extrudedSolidIds); + g("space", sel.roomIds); + g("fill", sel.openingIds); + for (const id of sel.contextObjectIds) { + const o = (project.context ?? []).find((c) => c.id === id); + if (o?.type === "importedMesh" && o.ifcGlobalId) guids.push(o.ifcGlobalId); + } + return guids; +} diff --git a/src/panels/BcfPanel.tsx b/src/panels/BcfPanel.tsx new file mode 100644 index 00000000..3140818f --- /dev/null +++ b/src/panels/BcfPanel.tsx @@ -0,0 +1,272 @@ +// Dock-Panel „BCF-Themen": Koordinations-Themen im BIM Collaboration Format (2.1/3.0) von Solibri, +// BIMcollab, Revit, ArchiCAD. Datei öffnen, Themenliste mit Status, Klick zeigt Beschreibung, +// Kommentare und Snapshot und wählt die betroffenen Bauteile im Modell aus (Zuordnung über die +// IFC-GlobalId, dieselbe Ableitung wie im IFC-Export: `io/bcfMatch.ts`). Kommentar hinzufügen, +// Status ändern, neues Thema aus der Auswahl, als .bcfzip speichern. +// +// Die Themen gehören nicht zum Projekt (eigene Datei, `bcfSession.ts`). Die Kamera eines Viewpoints +// wird angezeigt, aber noch nicht gesetzt: `Wasm3DViewport` hält seine Orbit-Kamera intern und bietet +// keine Setz-Funktion (s. TODO.md [BCF]). +// +// Bezeichner englisch, UI-Text deutsch/englisch über t(). + +import { useMemo, useRef } from "react"; +import { t } from "../i18n"; +import { usePanelHost } from "./host"; +import { getState, useStore } from "../state/appStore"; +import { saveBinaryFile } from "../native/saveFile"; +import { + BCF_STATUSES, + addComment, + addTopic, + emptyBcf, + newTopic, + newViewpoint, + parseBcf, + setTopicStatus, + writeBcf, + type BcfCamera, + type BcfFile, + type BcfTopic, + type BcfVersion, +} from "../io/bcf"; +import { + bcfSelectionSize, + emptyBcfSelection, + resolveGuids, + selectionToGuids, + viewpointGuids, + type BcfSelection, +} from "../io/bcfMatch"; +import { fileioLoaded, loadFileio } from "../engine/fileioWasm"; +import { setBcfSession, useBcfSession } from "./bcfSession"; + +const AUTHOR_KEY = "dossier.bcf.author"; + +function readAuthor(): string { + try { + return localStorage.getItem(AUTHOR_KEY) ?? ""; + } catch { + return ""; + } +} +function writeAuthor(v: string): void { + try { + localStorage.setItem(AUTHOR_KEY, v); + } catch { + /* ohne Speicher: nur für diese Sitzung */ + } +} + +function uuid(): string { + if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID(); + const h = (n: number) => Math.floor(Math.random() * 16 ** n).toString(16).padStart(n, "0"); + return `${h(8)}-${h(4)}-4${h(3)}-a${h(3)}-${h(12)}`; +} + +/** Auswahl des Modells in die Kanäle des Stores übernehmen (ersetzt die bisherige Auswahl). */ +function applySelection(sel: BcfSelection): void { + const s = getState(); + s.clearSelection(); + s.setSelectedWallIds(sel.wallIds); + s.setSelectedCeilingIds(sel.ceilingIds); + s.setSelectedOpeningIds(sel.openingIds); + s.setSelectedStairIds(sel.stairIds); + s.setSelectedRoomIds(sel.roomIds); + s.setSelectedExtrudedSolidIds(sel.extrudedSolidIds); + s.setSelectedColumnIds(sel.columnIds); + s.setSelectedRoofIds(sel.roofIds); + s.setSelectedContextObjectIds(sel.contextObjectIds); +} + +function currentSelection(): BcfSelection { + const s = getState(); + return { + ...emptyBcfSelection(), + wallIds: s.selectedWallIds, + ceilingIds: s.selectedCeilingIds, + openingIds: s.selectedOpeningIds, + stairIds: s.selectedStairIds, + roomIds: s.selectedRoomIds, + extrudedSolidIds: s.selectedExtrudedSolidIds, + columnIds: s.selectedColumnIds, + roofIds: s.selectedRoofIds, + contextObjectIds: s.selectedContextObjectIds, + }; +} + +const f1 = (n: number) => n.toLocaleString("de-CH", { maximumFractionDigits: 1 }); + +function cameraText(c: BcfCamera): string { + const p = { x: f1(c.position[0]), y: f1(c.position[1]), z: f1(c.position[2]) }; + return c.kind === "orthogonal" ? t("bcf.camera.orthogonal", p) : t("bcf.camera.perspective", { ...p, fov: f1(c.fieldOfView) }); +} + +export function BcfPanel() { + const host = usePanelHost(); + const notify = useStore((s) => s.notify); + const session = useBcfSession(); + const inputRef = useRef(null); + const authorRef = useRef(null); + const commentRef = useRef(null); + const { file, selectedGuid } = session; + const topic = file?.topics.find((x) => x.guid === selectedGuid) ?? null; + + const author = () => authorRef.current?.value.trim() || "Dossier"; + const now = () => new Date().toISOString(); + const update = (next: BcfFile) => setBcfSession({ file: next, dirty: true }); + + const openFile = async (f: File) => { + try { + const parsed = await parseBcf(new Uint8Array(await f.arrayBuffer())); + setBcfSession({ file: parsed, fileName: f.name, dirty: false, selectedGuid: null, version: parsed.version === "3.0" ? "3.0" : "2.1" }); + } catch (e) { + notify(t("bcf.openFailed", { error: e instanceof Error ? e.message : String(e) }), "error"); + } + }; + + const selectTopic = (tp: BcfTopic) => { + setBcfSession({ selectedGuid: tp.guid }); + const guids = [...new Set(tp.viewpoints.flatMap(viewpointGuids))]; + if (guids.length === 0) return; + // GlobalIds brauchen das Format-Modul (Rust-Hash); nach dem Öffnen ist es geladen. + void loadFileio().then(() => { + const { selection } = resolveGuids(host.project, guids); + const found = bcfSelectionSize(selection); + applySelection(selection); + notify(t("bcf.components", { found, total: guids.length }), found > 0 ? "info" : "warning"); + }); + }; + + const save = async () => { + if (!file) return; + try { + const bytes = await writeBcf(file, session.version); + const name = session.fileName.replace(/\.(bcf|bcfzip|zip)$/i, "") || host.project.name || "themen"; + if (await saveBinaryFile(bytes, `${name}.bcfzip`, "application/zip")) { + setBcfSession({ dirty: false, fileName: `${name}.bcfzip` }); + notify(t("bcf.saved"), "info"); + } + } catch (e) { + notify(t("bcf.saveFailed", { error: e instanceof Error ? e.message : String(e) }), "error"); + } + }; + + const createFromSelection = async () => { + const sel = currentSelection(); + if (bcfSelectionSize(sel) === 0) { + notify(t("bcf.needSelection"), "warning"); + return; + } + await loadFileio(); + const guids = selectionToGuids(host.project, sel); + const topicGuid = uuid(); + const tp = newTopic({ + guid: topicGuid, + title: t("bcf.defaultTitle"), + author: author(), + now: now(), + viewpoints: guids.length > 0 ? [newViewpoint(uuid(), guids)] : [], + }); + const base = file ?? emptyBcf(host.project.id, host.project.name ?? ""); + setBcfSession({ file: addTopic(base, tp), dirty: true, selectedGuid: topicGuid }); + }; + + const submitComment = () => { + const el = commentRef.current; + if (!file || !topic || !el || el.value.trim() === "") return; + update(addComment(file, topic.guid, { guid: uuid(), date: now(), author: author(), comment: el.value.trim(), viewpointGuid: "", modifiedDate: "", modifiedAuthor: "" })); + el.value = ""; + }; + + const retitle = (title: string) => { + if (!file || !topic) return; + update({ ...file, topics: file.topics.map((x) => (x.guid === topic.guid ? { ...x, title, modifiedDate: now(), modifiedAuthor: author() } : x)) }); + }; + + const snapshot = topic?.viewpoints.find((v) => v.snapshot)?.snapshot; + const camera = topic?.viewpoints.find((v) => v.camera)?.camera ?? null; + const topicGuids = topic ? [...new Set(topic.viewpoints.flatMap(viewpointGuids))] : []; + const project = host.project; + const foundCount = useMemo( + () => (topicGuids.length > 0 && fileioLoaded() ? bcfSelectionSize(resolveGuids(project, topicGuids).selection) : 0), + // eslint-disable-next-line react-hooks/exhaustive-deps + [project, topic], + ); + + return ( +
+
+ + + + { const f = e.target.files?.[0]; e.target.value = ""; if (f) void openFile(f); }} /> +
+
+ + +
+ + + {!file &&
{t("bcf.empty")}
} + {file &&
{t("bcf.fileInfo", { name: session.fileName || "–", version: file.version, n: file.topics.length })}
} + {file && file.topics.length === 0 &&
{t("bcf.noTopics")}
} + +
    + {file?.topics.map((tp) => ( +
  • + +
  • + ))} +
+ + {file && topic && ( +
+ retitle(e.target.value)} aria-label={t("bcf.defaultTitle")} /> +
+ + {topic.topicType &&
{t("bcf.type")}{topic.topicType}
} + {topic.priority &&
{t("bcf.priority")}{topic.priority}
} + {topic.assignedTo &&
{t("bcf.assignedTo")}{topic.assignedTo}
} + {topic.dueDate &&
{t("bcf.dueDate")}{topic.dueDate.slice(0, 10)}
} + {topic.labels.length > 0 &&
{t("bcf.labels")}{topic.labels.join(", ")}
} +
+ {topic.description &&
{topic.description}
} + {snapshot && } + {camera &&
{t("bcf.camera")}: {cameraText(camera)}
} +
+
{topicGuids.length > 0 ? t("bcf.components", { found: foundCount, total: topicGuids.length }) : t("bcf.components.none")}
+ {topicGuids.length > 0 && } +
+
{t("bcf.comments")}
+ {topic.comments.map((c) => ( +
+
{c.author} · {c.date.slice(0, 16).replace("T", " ")}
+
{c.comment}
+
+ ))} +