diff --git a/TODO.md b/TODO.md index d2d9656b..2a0e5442 100644 --- a/TODO.md +++ b/TODO.md @@ -804,11 +804,36 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern wie vorher bis auf erzeugte ids. Messung (vitest/Node, `--no-opt`-WASM, Container unter Last, bigSample(20), 2,6 MB, 3600 Wände): Öffnen 106–115 ms (alter Weg ohne den Kern-Parse ≈ 210–260 ms: JSON zurück, Differenz, Commit), Speichern im Kern 32 ms (vorher Kopie des Baums ≈ 80 ms; `JSON.stringify` in JS 17–19 ms). - ◐ **Import-Umwandlung im Kern (29.10.):** Format-Modul liest, der Kern wandelt und wendet als EIN Undo-Schritt an - (`core/src/import_drawing.rs`, `import_ifc.rs`, `import_context.rs`, Bindungen `web/import.rs`, TS - `ProjectDocument.importDrawing/importIfc/importMesh`). Schritt 1: Kern-Fassung + vorübergehende Paritätstests - (`io/importParity.test.ts`, Fixtures über `DOSSIER_PARITY_FX`) neben der alten TS-Fassung; offen: Aufrufer umstellen, - TS-Umwandlung löschen. + **Import-Umwandlung im Kern (29.10.):** Das Format-Modul (`fileio`, eigenes WASM) liest wie bisher in flache + Puffer; der Kern wandelt sie und wendet das Ergebnis als EINEN Undo-Schritt an: `core/src/import_drawing.rs` + (DXF/DWG-Puffer v3 dekodieren, Stücke des parallelen Lesens zusammenführen, PDF-Seite mit Massstab → + Ebenen nach Stärke/Farbe/Strichmuster, Zusammenfassung für den Dialog, Ops: neue Zeichnungsebene, Kategorien + je Layer `layers::plan_import`, Linienstile der PDF-Strichmuster, 2D-Zeichnungen mit Bulge-Vorzeichen + Modell = − DXF, Platzierung „Ausschnittsmitte", Meshes als Kontext), `import_ifc.rs` ([B4] Bauteile: Geschosse, + Wand-/Deckentypen, Materialien, Öffnungen, Stützen, Räume), `import_context.rs` ([B3]/[C11] Kontext-Meshes aus + IFC und OBJ/STL/glTF/PLY, `ensureContextCategories`, LV95-Rückschub). Bindungen `web/import.rs` + (`doc_import_drawing/ifc/mesh`, `import_drawing_summary`, `import_drawing_meshes`, `mesh_import_report`, + `pdf_page_info`, Leseansicht `import_drawing_view` für Tests). TS: `ProjectDocument.importDrawing/importIfc/ + importMesh`, Store `commitImport`; Dialoge halten nur Puffer + Zusammenfassung (`io/importSource.ts`). + Gelöscht: `io/dxfToDrawings.ts`, `io/pdfLineStyles.ts`, `io/ifcElements.ts`, `decodeImport`, `decodeIfc`, + `ifcToImportedMeshes`, `decodeMesh`/`meshObjectsToImportedMeshes`, `pdfPageToImport`/`pdfPageInfo` (TS), + `buildDrawings`, `planImportLayers`, Store `addDrawingLevel`/`importDrawings`; `ensureContextCategories` ist + Fassade über den Kern. Gleichheit (einmalig, Paritätstest gegen die TS-Fassung, Stand `65e7f3a`): 23 DXF/DWG + (Fixtures `kataster.dxf`, `klein.dxf`, `layouts.dxf` + Layout, `tile*` DXF/Binär-DXF/DWG R13–2018, synthetischer + Kataster 3000) × 2 Projekte × 3 Entscheidungen (neue Ebene/Layer-Kategorien/Meshes, aktive Kategorie + + Ausschnittsmitte, bestehende Ebene); synthetischer Kataster 150 000 Entities in 4 parallel gelesenen Stücken; + 2 PDF × 4 Massstäbe × mit/ohne Text × 2 Projekte × 3 Entscheidungen + vorhandener Linienstil; 5 IFC (Demo-Haus, + 2 Testdaten, 2 mit ifcopenshell erzeugt: 3 Geschosse, Schichten, Stützen, Räume, eBKP-H, einmal in LV95) × 4 + Projekte (leer, Beispiel, mit LV95-Bezug, ohne Listen) × 3 Gruppierungen, Bauteile und Meshes; 6 Meshes + (OBJ+MTL, STL, GLB, glTF, PLY in LV95) × 3 Einheit/Achse × 3 Projekte × 2 Platzierungen × 3 Gruppierungen → + Projekt (bis auf erzeugte ids), Zusammenfassung, Berichte, `pdf-info` gleich. CLI (`convert`, `import-ifc` + auch `--elements`/`--group class`, `import-mesh`, `pdf-info`; 133 Ausgaben): 130 gleich, die 3 PDF-`convert` + bekommen jetzt wie die App Linienstile für Strichmuster (vorher im CLI nicht). Messung Kataster 150 000 + Entities (vitest/Node, `--no-opt`-WASM, Container unter Last): App-Weg ohne Lesen alt 3,2–4,3 s (TS dekodieren + + umwandeln + Commit im Kern), neu 2,0–2,7 s (Kern: Zusammenfassung ≈ 0,1 s, Import ≈ 1,7–2,0 s, `JSON.parse` der + Ops ≈ 0,6 s); CLI `convert` (inkl. Lesen und 78 MB Schreiben) alt ≈ 9,4 s, neu ≈ 9,6–11,9 s (das alte CLI ging + am Kern-Dokument vorbei). Offen: Ops-Rückgabe als JSON (42 MB beim 150k-Kataster) — die Leseansicht könnte + die Elemente billiger bekommen; STEP-Import (truck) unverändert in TS; nicht in Tauri/macOS geprüft. Offene Entscheide/Risiken: Kosten der JSON-Übergabe bei grossen Projekten (Teil-Updates statt Neuaufbau), Struktur-Sharing im React-Store (TS-Spiegel bleibt bis S3), Befehls-Zustandsautomaten sind viel Code (`src/commands/cmds/*`). - **Fertig wenn** (je Etappe): TS-Fassung gelöscht, `npm run check` grün, App/CLI/IFC unverändert. diff --git a/scripts/benchDxfParallel.ts b/scripts/benchDxfParallel.ts index 91c307f0..06b8ff74 100644 --- a/scripts/benchDxfParallel.ts +++ b/scripts/benchDxfParallel.ts @@ -1,7 +1,7 @@ // Misst den DXF-/DWG-Import (Rust-Format-Modul, `src/io/dxfParser.ts`) an einer ECHTEN Datei: // (1) Einzel-Pass, (2) für grosse ASCII-DXF die parallele Aufteilung (`split.rs`) über echte // `worker_threads` (Node-Äquivalent der Browser-Worker in `dxfParserAsync.ts`). Korrektheit: -// Gesamtzahlen (Konturen/Punkte/Texte/Meshes) müssen zwischen beiden Läufen IDENTISCH sein. +// Gesamtzahlen (Konturen/Texte/Meshes, Zusammenfassung des Kerns) müssen zwischen beiden Läufen IDENTISCH sein. // // Lauf: `node scripts/bench-dxf-parallel.mjs ` (vorher `npm run build:fileio`). @@ -9,8 +9,9 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { Worker } from "node:worker_threads"; import { initFileioSync } from "../src/engine/fileioWasm"; -import { decodeImport, importDrawingFlat } from "../src/io/dxfParser"; -import type { DxfImportResult } from "../src/io/dxfParser"; +import { initCoreSync } from "../src/engine/coreWasm"; +import { importDrawingFlat } from "../src/io/dxfParser"; +import { importSummary, packChunks, type ImportChunk, type ImportSummary } from "../src/io/importSource"; const path = process.argv[2]; const workerPath = process.argv[3]; @@ -21,16 +22,10 @@ if (!path || !workerPath) { const wasmPath = resolve("src/engine/pkgFileIo/fileio_bg.wasm"); const CLOSER = new TextEncoder().encode("0\nENDSEC\n0\nEOF\n"); -function countAll(res: DxfImportResult) { - let contours = 0; - let points = 0; - for (const set of res.contours) { - for (const c of set.contours) { - contours++; - points += c.pts.length; - } - } - return { contours, points, texts: res.texts?.length ?? 0, meshes: res.meshes.length }; +/** Zahlen der Zusammenfassung (Kern liest die Stücke wie in der App). */ +function countAll(chunks: ImportChunk[]) { + const s: ImportSummary = importSummary(packChunks(chunks)); + return { contours: s.contours, texts: s.texts, meshes: s.meshes, entities: s.diagnostics.total }; } console.log(`\nImport-Benchmark: ${path}\n`); @@ -38,6 +33,7 @@ const bytes = new Uint8Array(readFileSync(path)); console.log(` Datei: ${(bytes.length / 1024 / 1024).toFixed(0)} MB\n`); const t00 = performance.now(); const m = await initFileioSync(readFileSync(wasmPath)); +initCoreSync(readFileSync(resolve("src/engine/pkgCore/core_bg.wasm"))); console.log(` Modul laden: ${(performance.now() - t00).toFixed(0).padStart(7)} ms`); // Erster Lauf wärmt die WASM-Engine auf (Tier-up von Liftoff auf TurboFan) — gemessen wird beides. @@ -47,11 +43,10 @@ console.log(` Erster Lauf: ${(performance.now() - tw).toFixed(0).padStart(7) const t0 = performance.now(); const flat = importDrawingFlat(bytes); const tRust = performance.now(); -const single = decodeImport(flat.geom, flat.strings); +const singleCounts = countAll([flat]); const singleMs = performance.now() - t0; -const singleCounts = countAll(single); console.log( - ` Einzel-Pass: ${singleMs.toFixed(0).padStart(7)} ms (Rust ${(tRust - t0).toFixed(0)} ms, Dekodieren ${(performance.now() - tRust).toFixed(0)} ms)`, + ` Einzel-Pass: ${singleMs.toFixed(0).padStart(7)} ms (Lesen ${(tRust - t0).toFixed(0)} ms, Kern-Zusammenfassung ${(t0 + singleMs - tRust).toFixed(0)} ms)`, singleCounts, ); @@ -92,25 +87,16 @@ const results = await Promise.all( }), ), ); -const decoded = results.map((r, i) => decodeImport(r.geom, r.strings, `c${i}-`)); +const merged = countAll(results.map((r) => ({ geom: r.geom, strings: r.strings }))); const parallelMs = performance.now() - t1; for (const [i, r] of results.entries()) { console.log( ` Worker ${i}: Start→Modul ${(r.tGotInput - spawned[i]).toFixed(0)} ms, Rust ${(r.tParsed - r.tGotInput).toFixed(0)} ms`, ); } -const merged = decoded.reduce( - (a, r) => { - const c = countAll(r); - return { contours: a.contours + c.contours, points: a.points + c.points, texts: a.texts + c.texts, meshes: a.meshes + c.meshes }; - }, - { contours: 0, points: 0, texts: 0, meshes: 0 }, -); console.log(` Parallel (${chunks.length} Worker): ${(parallelMs + splitMs).toFixed(0).padStart(7)} ms inkl. Scan `, merged); const ok = - merged.contours === singleCounts.contours && - merged.points === singleCounts.points && - merged.texts === singleCounts.texts; + merged.contours === singleCounts.contours && merged.texts === singleCounts.texts && merged.meshes === singleCounts.meshes; console.log(`\n Korrektheit: ${ok ? "IDENTISCH ✓" : "ABWEICHUNG ✗"}`); console.log(` Speedup: ${(singleMs / (parallelMs + splitMs)).toFixed(2)}x\n`); if (!ok) process.exit(1); diff --git a/src-tauri/core/src/import_context.rs b/src-tauri/core/src/import_context.rs index 02cd7560..32869275 100644 --- a/src-tauri/core/src/import_context.rs +++ b/src-tauri/core/src/import_context.rs @@ -56,7 +56,8 @@ pub fn ensure_context_categories<'a>(layers: &mut Vec, codes: impl IntoIt return false; } let nested: Vec = NESTED.iter().filter(|d| missing.contains(d.code)).map(category).collect(); - if !nested.is_empty() { + let added_nested = !nested.is_empty(); + if added_nested { match layers.iter().position(|l| l.get("code").and_then(Value::as_str) == Some(CONTEXT_PARENT.code)) { Some(i) => { let mut l = layers[i].as_object().cloned().unwrap_or_default(); @@ -72,10 +73,11 @@ pub fn ensure_context_categories<'a>(layers: &mut Vec, codes: impl IntoIt } } } - if missing.contains(IMPORTED_ROOF.code) { + let roof = missing.contains(IMPORTED_ROOF.code); + if roof { layers.push(category(&IMPORTED_ROOF)); } - true + added_nested || roof } /// Ops: Kontext-Objekte anhängen (fehlt die Liste, wird sie gesetzt) und fehlende Kontext-Kategorien ergänzen. @@ -407,6 +409,25 @@ pub fn decode_mesh(f: &[f64], strings: &[String]) -> Result<(Vec, Va Ok((objects, report)) } +/// Ausdehnung aller Objekte (Meter, Modell-Achsen; Anzeige im Dialog); `None` ohne Punkte. +pub fn mesh_extent(objects: &[MeshObject]) -> Option<[f64; 3]> { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for o in objects { + for p in o.positions.chunks_exact(3) { + for a in 0..3 { + if p[a] < lo[a] { + lo[a] = p[a]; + } + if p[a] > hi[a] { + hi[a] = p[a]; + } + } + } + } + lo[0].is_finite().then(|| [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]]) +} + /// Verschiebung (x, y, z) je nach Platzierung (`meshShift`): `"center"` = Grundriss-Mitte auf den /// Nullpunkt, Unterkante auf 0; `"original"` = Datei-Koordinaten, Landeskoordinaten auf den Modell-Nullpunkt. pub fn mesh_shift(objects: &[MeshObject], placement: &str, origin: Option<[f64; 2]>) -> [f64; 3] { diff --git a/src-tauri/core/src/import_drawing_tests.rs b/src-tauri/core/src/import_drawing_tests.rs index 7d6b5934..47b2e8dc 100644 --- a/src-tauri/core/src/import_drawing_tests.rs +++ b/src-tauri/core/src/import_drawing_tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::import_context::{ensure_context_categories, mesh_objects_to_meshes, stamp36, MeshObject}; +use crate::import_context::{classification_suffix, ensure_context_categories, ifc_meshes, mesh_objects_to_meshes, stamp36, IfcProduct, MeshObject}; /// DXF-Puffer (Version 3) wie `fileio/src/import.rs::encode`: Layer „A" (rot) und „B", eine Linie, /// eine Polylinie mit Bogen, ein Kreis, eine Schraffur, ein Text, ein Mesh auf „0". @@ -142,6 +142,62 @@ fn pdf_mit_strichmuster() { assert_eq!(info["layers"], json!({"PDF 0.18 #ff0000 (Strich 1.05/0.7)": 1, "PDF Fläche #ffffff": 1})); } +#[test] +fn strichmuster_zu_linienstilen() { + assert!(same_dash(&[1.05, 0.7], &[1.0, 0.7])); + assert!(!same_dash(&[3.0, 1.0], &[1.0, 3.0])); + assert!(!same_dash(&[1.0, 1.0], &[1.0, 1.0, 1.0, 1.0])); + let solid = json!({"id": "thin", "name": "Volllinie", "weight": 0.13, "color": "#111", "dash": null}); + let dashed = json!({"id": "d", "name": "Strich", "weight": 0.02, "color": "#111", "dash": [1, 0.7]}); + let dashes: Vec<(String, Vec)> = + vec![("a".into(), vec![1.05, 0.7]), ("b".into(), vec![2.8, 1.4]), ("c".into(), vec![2.8, 1.4]), ("d".into(), vec![0.05, 0.7, 2.8, 0.7])]; + let (created, by_layer) = plan_dash_styles(&dashes, &[solid.clone(), dashed], "S {pattern}"); + assert_eq!(by_layer["a"], "d"); + assert_eq!(created.len(), 2); + assert_eq!(by_layer["b"], by_layer["c"]); + assert_eq!(created[0], json!({"id": "pdf-dash-2_8_1_4", "name": "S 2.8/1.4", "weight": 0.02, "color": "#1a1a1a", "dash": [2.8, 1.4]})); + assert_eq!(created[1]["dash"], json!([0.05, 0.7, 2.8, 0.7])); + // Gleiche id schon vergeben → Zähler. + let taken = json!({"id": "pdf-dash-2_8_1_4", "kind": "dot", "dash": [2.8, 1.4]}); + let (created, _) = plan_dash_styles(&dashes[1..2], &[taken], "{pattern}"); + assert_eq!(created[0]["id"], json!("pdf-dash-2_8_1_4-2")); + assert!(plan_dash_styles(&[], &[solid], "").0.is_empty()); +} + +#[test] +fn ifc_meshes_farbe_und_globalid() { + let pos = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]; + let idx = [0.0, 2.0, 1.0, 0.0, 1.0, 3.0]; + let product = |color: Option>, gid: &str| IfcProduct { + global_id: gid.into(), + ifc_class: "IfcWall".into(), + name: Some("Wand".into()), + storey: Some("EG".into()), + color, + classifications: vec![], + positions: &pos, + indices: &idx, + }; + let m = ifc_meshes(&[product(Some(vec![1.0, 0.5, 0.0, 0.8]), "2O2Fr$t4X7Zf8NOew3FLOH")], "x.ifc", "product", [0.0, 0.0], 0.0); + assert_eq!(m[0]["color"], json!("#ff8000")); + assert_eq!(m[0]["ifcGlobalId"], json!("2O2Fr$t4X7Zf8NOew3FLOH")); + assert_eq!(m[0]["name"], json!("EG: Wand")); + assert_eq!(m[0]["layer"], json!("IfcWall")); + let n = ifc_meshes(&[product(None, "")], "x.ifc", "product", [0.0, 0.0], 0.0); + assert!(n[0].get("color").is_none() && n[0].get("ifcGlobalId").is_none()); + // Zusammengelegt: gemeinsame Farbe nur, wenn alle gleich; Indizes versetzt. + let red = || Some(vec![1.0, 0.0, 0.0, 1.0]); + let g = ifc_meshes(&[product(red(), "a"), product(red(), "b")], "x.ifc", "class", [10.0, 0.0], 0.0); + assert_eq!(g[0]["color"], json!("#ff0000")); + assert_eq!(g[0]["name"], json!("x: EG IfcWall (2)")); + assert_eq!(g[0]["indices"].as_array().unwrap()[6], json!(4)); + assert_eq!(g[0]["positions"][0], json!(10)); + let h = ifc_meshes(&[product(red(), "a"), product(Some(vec![0.0, 0.0, 1.0, 1.0]), "b")], "x.ifc", "class", [0.0, 0.0], 0.0); + assert!(h[0].get("color").is_none()); + assert_eq!(classification_suffix(&[]), ""); + assert_eq!(classification_suffix(&[json!({"system": "", "code": "214", "name": null})]), " [214]"); +} + #[test] fn kontext_kategorien() { let mut l = vec![json!({"code": "20"})]; @@ -167,6 +223,12 @@ fn meshes_mitte_und_gruppen() { assert_eq!(m.len(), 1); assert_eq!(m[0]["name"], json!("haus: g (2)")); assert_eq!(m[0]["indices"], json!([0, 1, 0, 2, 3, 2])); + // Viele Objekte („auto"): je Gruppe + Farbe zusammengelegt. + let many: Vec = (0..2100).map(|i| obj(if i % 2 == 1 { "A" } else { "B" }, 0.0)).collect(); + let m = mesh_objects_to_meshes(&many, "x.obj", "original", None, "auto", 0.0); + assert_eq!(m.len(), 2); + assert_eq!(m[0]["indices"].as_array().unwrap().len(), 1050 * 3); + assert_eq!(m[0]["color"], json!("#ff8000")); } /// Zeitmessung (nativ, von Hand): `IMPORT_BENCH=` mit `.strings.json` daneben. diff --git a/src-tauri/core/src/web/import.rs b/src-tauri/core/src/web/import.rs index b5b30c74..8d7ad287 100644 --- a/src-tauri/core/src/web/import.rs +++ b/src-tauri/core/src/web/import.rs @@ -155,11 +155,15 @@ fn strings_of(json: &str) -> Result, String> { serde_json::from_str(json).map_err(|e| format!("Import-Texte: {e}")) } -/// Bericht eines gelesenen Mesh-Imports (Format, Achse, Einheit, Dreiecke, Hinweise) für den Dialog. +/// Bericht eines gelesenen Mesh-Imports (Format, Achse, Einheit, Dreiecke, Hinweise) und Ausdehnung +/// (`[dx, dy, dz]` in Metern, `null` ohne Punkte) für den Dialog: `{"report":{…},"extent":…}`. #[wasm_bindgen] pub fn mesh_import_report(flat: &[f64], strings_json: &str) -> String { match strings_of(strings_json).and_then(|s| crate::import_context::decode_mesh(flat, &s)) { - Ok((_, report)) => report.to_string(), + Ok((objects, report)) => { + let extent = crate::import_context::mesh_extent(&objects).map_or(Value::Null, |e| json!(e)); + json!({"report": report, "extent": extent}).to_string() + } Err(e) => err(e), } } diff --git a/src-tauri/core/src/web/layers.rs b/src-tauri/core/src/web/layers.rs index 69af3a41..aab42c60 100644 --- a/src-tauri/core/src/web/layers.rs +++ b/src-tauri/core/src/web/layers.rs @@ -51,10 +51,6 @@ pub fn layers_call(name: &str, layers_json: &str, arg_json: &str, now_ms: f64) - "insertAfter" => Value::Array(layers::insert_after(&cats, text(&arg["code"]), &arg["clone"])), "remove" => Value::Array(layers::remove(&cats, text(&arg))), "nextFreeCode" => Value::String(layers::next_free_code(&cats, if now_ms.is_finite() { now_ms } else { 0.0 })), - "planImport" => { - let plan = layers::plan_import(&strings(&arg["names"]), &cats, &obj(&arg["colors"]), &obj(&arg["weights"])); - json!({"children": plan.children, "parentCode": plan.parent_code, "codeByLayer": plan.code_by_layer}) - } // Fehlende Kontext-Kategorien ergänzen (`ensureContextCategories`); `null` = nichts fehlt. "ensureContext" => { let mut cats = cats; diff --git a/src/App.tsx b/src/App.tsx index 4ebb74f7..f72d381f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -35,6 +35,7 @@ import type { import { activePenSet, resolvePenColor, resolvePenWeight } from "./model/penSets"; import { PenColorField } from "./ui/PenColorField"; import { generatePlan, computeKennzahlen, checkRoomProgram } from "./core"; +import { addedItems } from "./core"; import { programStatusLabel } from "./panels/KennzahlenSection"; import type { CategoryDisplayResolver, ProjectMutation } from "./core"; import { sectionPlaneFromLevel, sectionUAxisModel } from "./core"; @@ -54,13 +55,11 @@ import { RecoverAutosaveDialog } from "./ui/RecoverAutosaveDialog"; 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 { formatIfcElementsSummary, formatIfcReport, readIfcFlat } from "./io/ifcImport"; import { IfcImportDialog, type IfcImportMode } from "./ui/IfcImportDialog"; import { MeshImportHost } from "./ui/MeshImportDialog"; import { openMeshFileDialog, requestMeshImport, splitMeshFiles } from "./state/meshImportStore"; import { formatMeshReport, isMeshFile } from "./io/meshImport"; -import { projectGeoOrigin } from "./model/geoRebase"; import { clashMarkerOps, runClashCheck } from "./analysis/clash"; import { checkForUpdate } from "./update/checkForUpdate"; import type { PlanViewHandle } from "./views/plan/PlanView"; @@ -205,7 +204,7 @@ import type { BooleanResult } from "./editors/booleanOps"; import { applyDrawingStyleOps, readDrawingStyle } from "./editors/matchProps"; // Globaler Store (Slices: project/selection/view/layout). -import { useStore } from "./state/appStore"; +import { getState, useStore } from "./state/appStore"; import { categoryLabel, findCategory } from "./model/layers"; import { reconcileLayout } from "./state/layoutSlice"; @@ -556,7 +555,7 @@ export default function App() { // Verstecktes Datei-Input für den DXF-Import (Site-Panel/„import"-Befehl). // Der Klick auf „DXF importieren" triggert .click() dieses Inputs; onChange - // liest die Datei als Text und reicht sie durch parseDxf → addContextObjects. + // öffnet den Import-Dialog; übernommen wird im Kern (`ProjectDocument.importDrawing`). const dxfInputRef = useRef(null); // Verstecktes Datei-Input für den STEP-Import (Menü Datei, STEP importieren). const stepInputRef = useRef(null); @@ -1597,8 +1596,6 @@ export default function App() { addDrawing, addSection, addElevation, - addDrawingLevel, - importDrawings, addCategory, patchCategory, addSubCategory, @@ -1666,8 +1663,8 @@ export default function App() { deleteStairType, importLineStyles, importHatches, - addContextObjects, addContextObjectsAndFit, + fitToContextObjects, removeContextObject, removeContextObjects, generateTerrain, @@ -1704,44 +1701,29 @@ export default function App() { setRoomStamp, } = useProjectActions(applyChange, notify, planViewRef); - // IFC-Import: erst die Wahl Mesh/Bauteile (`IfcImportDialog`), dann [B3] Kontext-Meshes - // (`io/ifcImport.ts`) oder [B4] echte Bauteile (`io/ifcElements.ts`, übernommen als Ops). + // IFC-Import: erst die Wahl Mesh/Bauteile (`IfcImportDialog`), dann liest das Format-Modul (Web-Worker) und der + // Kern übernimmt [B3] Kontext-Meshes oder [B4] echte Bauteile als EINEN Undo-Schritt ([K4] S4, `importIfc`). const [pendingIfc, setPendingIfc] = useState(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["summary"] | null = null; - let bounds: { x: number; y: number }[] = []; - // Als Ops in einem Schritt ([K4] S3): ein IFC-Import = ein Undo-Schritt. - applyChange((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.ops; - }); - if (bounds.length) planViewRef.current?.fitBounds(bounds); - if (summary) { - const s: ReturnType["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; - } + const elements = mode === "elements"; void f .arrayBuffer() - .then((buf) => ifcBytesToImportedMeshes(new Uint8Array(buf), f.name, { geoOrigin: projectGeoOrigin(project) })) - .then(({ meshes, report }) => { - if (meshes.length) addContextObjectsAndFit(meshes); - const warn = meshes.length === 0 || report.truncated || report.productsWithoutGeometry > 0; + .then((buf) => readIfcFlat(new Uint8Array(buf), elements)) + .then((flat) => { + const r = getState().commitImport((doc, base, now) => doc.importIfc(base, flat, { fileName: f.name, elements }, now)); + if (!r) return; + const report = r.report; + if (elements && r.summary) { + const bounds = addedItems(r.ops, "walls").flatMap((w) => [(w as Wall).start, (w as Wall).end]); + if (bounds.length) planViewRef.current?.fitBounds(bounds); + const s = r.summary; + const empty = s.walls + s.ceilings + s.columns + s.rooms + s.meshes === 0; + notify(formatIfcElementsSummary(s, report, t), empty || report.truncated ? "warning" : "info"); + return; + } + fitToContextObjects(addedItems(r.ops, "context") as ContextObject[]); + const warn = r.contextObjects === 0 || report.truncated || report.productsWithoutGeometry > 0; notify(formatIfcReport(report, t), warn ? "warning" : "info"); }) .catch((err) => @@ -1908,13 +1890,9 @@ export default function App() { runImport, } = useProjectFileActions( project, - applyChange, setImportState, setExportSaveFormat, activeCategoryCode, - addDrawingLevel, - importDrawings, - addContextObjects, setActiveLevelId, planViewRef, ); @@ -3354,11 +3332,13 @@ export default function App() { {/* 3D-Modell-Import (OBJ/STL/glTF/GLB/PLY): verstecktes Datei-Feld + Dialog. */} { - if (meshes.length) addContextObjectsAndFit(meshes); - notify(formatMeshReport(report, t), meshes.length === 0 || report.truncated ? "warning" : "info"); + onImport={(read, fileName, placement) => { + // Der Kern macht die Kontext-Meshes und übernimmt sie als EINEN Undo-Schritt ([K4] S4). + const r = getState().commitImport((doc, base, now) => doc.importMesh(base, read.flat, { fileName, placement }, now)); + if (!r) return; + fitToContextObjects(addedItems(r.ops, "context") as ContextObject[]); + notify(formatMeshReport(read.report, t), r.contextObjects === 0 || read.report.truncated ? "warning" : "info"); }} /> {/* Verstecktes IFC-Datei-Input (Menü Datei, IFC importieren). */} diff --git a/src/cli/main.ts b/src/cli/main.ts index 04337e41..63749e9c 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -43,19 +43,14 @@ import { buildPlanDxfBinary, loadFileio, readPointCloudFlat, - readPdfVectorPage, - pdfPageToImport, + readPdfVector, + pdfImport, pdfPageInfo, - readIfc, - readIfcElements, - ifcElementsToProject, - ifcToImportedMeshes, + readIfcFlat, readMesh, - meshObjectsToImportedMeshes, isMeshFile, MESH_UNITS, - projectGeoOrigin, - ensureContextCategories, + sharedDocument, projectToWorldCoords, computeSection, exportIfcSpf, @@ -88,15 +83,9 @@ import { exportGlb, exportGltf, parseDxf, - contoursToDrawings, - textsToDrawings, - planImportCategories, - distinctImportLayers, emptyProject, generateElevationPlan, applyOps, - addItems, - fieldOps, patchItem, generatePlan, generateSectionPlan, @@ -113,7 +102,7 @@ import { projectWarnings, sampleProject, } from "../core"; -import type { CoreOp, Project } from "../core"; +import type { Project } from "../core"; import { serveStdio } from "./mcp"; type Args = { positional: string[]; flags: Map; cmds: string[] }; @@ -245,6 +234,7 @@ async function runPdfInfo(args: Args, path: string | undefined): Promise return readFileSync(join(wasmDir(), rel)); }); await loadFileio(); + await initCore(); let bytes: Uint8Array; try { bytes = new Uint8Array(readFileSync(path)); @@ -252,14 +242,14 @@ async function runPdfInfo(args: Args, path: string | undefined): Promise fail(`Datei nicht lesbar: ${path} (${e instanceof Error ? e.message : String(e)})`); } const t0 = performance.now(); - let page; + let read; try { - page = readPdfVectorPage(bytes, pageArg(args)); + read = readPdfVector(bytes, pageArg(args)); } catch (e) { fail(`${path}: ${e instanceof Error ? e.message : String(e)}`); } const ms = Math.round(performance.now() - t0); - process.stdout.write(JSON.stringify({ file: path, bytes: bytes.byteLength, ms, ...pdfPageInfo(page) }, null, 2) + "\n"); + process.stdout.write(JSON.stringify({ file: path, bytes: bytes.byteLength, ms, ...pdfPageInfo(read) }, null, 2) + "\n"); return 0; } @@ -350,9 +340,14 @@ async function runCmds(project: Project, file: string, args: Args): Promise [l, ...(l.children ? flattenAllCategories(l.children) : [])]); +/** + * Dokument für einen Import ([K4] S4): das gemeinsame Abfrage-Dokument mit `project` geladen — danach spiegelt + * es das Ergebnis, Speichern und Abfragen darauf brauchen keinen neuen Abgleich (grosse Kataster-Importe). + */ +function importDoc(project: Project) { + const doc = sharedDocument(); + doc.load(project); + return doc; } /** Liest Eingabe nach Endung in ein Projekt: obp direkt, dxf/dwg als 2D-Zeichnung + Meshes, ifc als Kontext-Meshes (`--elements`: Bauteile). */ @@ -372,38 +367,35 @@ async function importAny(path: string, args: Args): Promise { if (ext === "dxf" || ext === "dwg" || ext === "pdf") { await loadFileio(); let parsed; - if (ext === "pdf") { + try { // Vektor-PDF ([76]): Massstab 1:--scale (Standard 100), Seite --page (Standard 1). - const scale = Number(args.flags.get("scale") ?? 100); - if (!Number.isFinite(scale) || scale <= 0) return fail("--scale: Massstabszahl > 0, z. B. 100 für 1:100"); - try { - parsed = pdfPageToImport(readPdfVectorPage(bytes, pageArg(args)), scale, { texts: !args.flags.has("no-text") }); - } catch (e) { - return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`); - } - } else parsed = parseDxf(bytes); + if (ext === "pdf") { + const scale = Number(args.flags.get("scale") ?? 100); + if (!Number.isFinite(scale) || scale <= 0) return fail("--scale: Massstabszahl > 0, z. B. 100 für 1:100"); + parsed = pdfImport(readPdfVector(bytes, pageArg(args)), scale, { texts: !args.flags.has("no-text") }); + } else parsed = parseDxf(bytes); + } catch (e) { + return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`); + } const level = base.drawingLevels.find((l) => l.kind === "floor"); if (!level) return fail("kein Geschoss für den Import"); - // Wie die App („DXF-Layer als Kategorien"): fehlende Layer als Unterkategorien einer neuen Elternkategorie. - const plan = planImportCategories( - distinctImportLayers(parsed.contours, parsed.texts ?? []), - flattenAllCategories(base.layers), - `Import ${fileName}`, - parsed.layerColors, - parsed.layerLineWeights, + // Wie die App („Layer als Kategorien", ein Undo-Schritt im Kern): fehlende Layer als Unterkategorien einer + // neuen Elternkategorie, Linienstile der PDF-Strichmuster, Meshes als Kontext. + const r = importDoc(base).importDrawing( + base, + parsed.src, + { + target: { kind: "existing", levelId: level.id }, + categoryMode: "byLayer", + activeCategoryCode: base.layers[0].code, + importMeshes: true, + parentName: `Import ${fileName}`, + dashStyleTemplate: "PDF-Strich {pattern} mm", + }, + Date.now(), ); - const layers = plan.parent ? [...base.layers, plan.parent] : base.layers; - const fallback = base.layers[0].code; - const toCode = (layer: string): string => plan.codeByLayer.get(layer) ?? fallback; - const drawings = [ - ...contoursToDrawings(parsed.contours, level.id, "byLayer", fallback, toCode, (l) => parsed.layerFillColors?.[l]), - ...textsToDrawings(parsed.texts ?? [], level.id, "byLayer", fallback, toCode), - ]; - return applyOps(base, [ - ...fieldOps(base, "layers", layers), - ...fieldOps(base, "drawings2d", drawings), - ...fieldOps(base, "context", [...parsed.meshes]), - ]); + if ("problems" in r) return fail(`${path}: ${r.problems.join("; ")}`); + return r.project; } return fail(`Eingabeformat nicht unterstützt: .${ext} (obp, dxf, dwg, ifc, pdf, obj, stl, gltf, glb, ply)`); } @@ -443,33 +435,18 @@ async function convert(input: string | undefined, output: string | undefined, ar return code === 0 ? runCmds(project, input, args) : code; } -/** Ops: Kontext-Meshes anhängen und — wie in der App (siteSlice) — fehlende Kontext-Kategorien als Ebene ergänzen. */ -function contextOps(project: Project, meshes: NonNullable): CoreOp[] { - return [ - ...(project.context ? addItems("context", meshes) : fieldOps(project, "context", meshes)), - ...fieldOps(project, "layers", ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : [])))), - ]; -} - -/** IFC in ein Projekt übernehmen (Kontext-Meshes, mit `--elements` als Bauteile); `report` = Bericht für `import-ifc`. */ +/** IFC in ein Projekt übernehmen (Kontext-Meshes, mit `--elements` als Bauteile; Kern, ein Schritt); `report` = Bericht für `import-ifc`. */ async function ifcInto(project: Project, bytes: Uint8Array, fileName: string, args: Args): Promise<{ next: Project; report: unknown }> { const group = args.flags.get("group"); const grouping = group === "product" || group === "class" ? group : "auto"; - if (args.flags.has("elements")) { - const { products, report, elements } = await readIfcElements(bytes); - const r = ifcElementsToProject(project, products, elements, { fileName, geoOrigin: projectGeoOrigin(project), group: grouping }); - return { - next: r.project, - report: { ...report, products: undefined, elements: r.summary, kept: elements.kept }, - }; - } - const { products, report } = await readIfc(bytes); - const meshes = ifcToImportedMeshes(products, fileName, { geoOrigin: projectGeoOrigin(project), group: grouping }); - const byClass: Record = {}; - for (const p of products) byClass[p.ifcClass] = (byClass[p.ifcClass] ?? 0) + 1; - const triangles = products.reduce((s, p) => s + p.indices.length / 3, 0); - const next = applyOps(project, contextOps(project, meshes)); - return { next, report: { ...report, byClass, triangles, contextObjects: meshes.length } }; + const elements = args.flags.has("elements"); + const flat = await readIfcFlat(bytes, elements); + const r = importDoc(project).importIfc(project, flat, { fileName, group: grouping, elements }, Date.now()); + if ("problems" in r) return fail(`${fileName}: ${r.problems.join("; ")}`); + const report = elements + ? { ...r.report, products: undefined, byClass: undefined, triangles: undefined, kept: r.kept } + : { ...r.report, contextObjects: r.contextObjects }; + return { next: r.project, report }; } /** Begleitdateien eines Mesh-Modells aus demselben Verzeichnis: `.mtl` (OBJ `mtllib`), externe `.bin` (glTF). */ @@ -514,9 +491,9 @@ async function meshInto(project: Project, bytes: Uint8Array, path: string, args: } catch (e) { return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`); } - const meshes = meshObjectsToImportedMeshes(read.objects, fileName, { placement, geoOrigin: projectGeoOrigin(project) }); - const next = applyOps(project, contextOps(project, meshes)); - return { next, report: { ...read.report, contextObjects: meshes.length } }; + const r = importDoc(project).importMesh(project, read.flat, { fileName, placement }, Date.now()); + if ("problems" in r) return fail(`${path}: ${r.problems.join("; ")}`); + return { next: r.project, report: { ...read.report, contextObjects: r.contextObjects } }; } /** Führt EINEN Befehl gegen ein geladenes Projekt aus (Rückgabe = Exit-Code). */ diff --git a/src/core/document.ts b/src/core/document.ts index d77f37b3..09b7df7a 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -12,6 +12,8 @@ import type { CoreOp } from "./ops"; import { fieldOps } from "./opsBuild"; import { opsMutation } from "./opsBuild"; import type { ProjectMutation } from "./opsBuild"; +import type { IfcImportResult } from "../io/ifcImport"; +import type { MeshImportReport } from "../io/meshImport"; /** * Gelesene Zeichnungs-Datei für den Kern ([K4] S4): Puffer des Format-Moduls, je Stück (paralleles Lesen @@ -373,14 +375,14 @@ export class ProjectDocument { /** IFC-Import ([B3]/[B4], [K4] S4): Kontext-Meshes bzw. (`opts.elements`) Bauteile, ein Undo-Schritt. */ importIfc(base: Project, flat: IfcFlatInput, opts: { fileName: string; group?: string; elements?: boolean }, now: number) { - return this.commitCore<{ report: Record; summary: Record | null; kept: Record; contextObjects: number }>(base, (h) => + return this.commitCore(base, (h) => core().doc_import_ifc(h, flat.meta, flat.positions, flat.indices, flat.elementData ?? new Float64Array(0), JSON.stringify(opts), "", now), ); } /** Mesh-Import (OBJ/STL/glTF/PLY, [C11], [K4] S4): Kontext-Meshes, ein Undo-Schritt. */ importMesh(base: Project, flat: { flat: Float64Array; strings: string[] }, opts: { fileName: string; placement?: string; group?: string }, now: number) { - return this.commitCore<{ report: Record; contextObjects: number }>(base, (h) => + return this.commitCore<{ report: MeshImportReport; contextObjects: number }>(base, (h) => core().doc_import_mesh(h, flat.flat, JSON.stringify(flat.strings), JSON.stringify(opts), "", now), ); } diff --git a/src/core/extra.ts b/src/core/extra.ts index 828ab3da..0ad6bf84 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -7,8 +7,7 @@ export { buildPlanDxf } from "../export/exportDxf"; export { buildPlanDwg } from "../export/exportDxf"; export { buildPlanDxfBinary } from "../export/exportDxf"; export { loadFileio } from "../engine/fileioWasm"; -export { readIfc, ifcToImportedMeshes } from "../io/ifcImport"; -export { readIfcElements, ifcElementsToProject } from "../io/ifcElements"; +export { readIfcFlat } from "../io/ifcImport"; export { parseBcf, writeBcf, bcfInfo } from "../io/bcf"; export { projectGeoOrigin } from "../model/geoRebase"; export { ensureContextCategories } from "../model/contextCategories"; @@ -42,14 +41,15 @@ export { checkSiteRules, allowedArea, multiPolygonArea, buildingFootprint, model export type { SiteCheck } from "../analysis/siteRules"; export { sampleProject } from "../model/sampleProject"; export { parseDxf } from "../io/dxfParser"; -export { contoursToDrawings, textsToDrawings, planImportCategories, distinctImportLayers } from "../io/dxfToDrawings"; +export { ProjectDocument, sharedDocument } from "./document"; export { emptyProject } from "../model/sampleProject"; export { readPointCloud, readPointCloudFlat, isPointCloudFile, DEFAULT_MAX_POINTS } from "../io/pointCloud"; export type { PointCloudData, PointCloudOptions, PointCloudReport } from "../io/pointCloud"; -export { readPdfVectorPage, pdfPageToImport, pdfPageInfo, pdfMetersPerPt, isPdfFile, PDF_SCALES } from "../io/pdfVector"; +export { readPdfVector, pdfImport, pdfPageInfo, isPdfFile, PDF_SCALES } from "../io/pdfVector"; export type { PdfVectorPage, PdfVectorPath, PdfVectorText } from "../io/pdfVector"; -export { readMesh, meshObjectsToImportedMeshes, formatMeshReport, isMeshFile, MESH_UNITS, MESH_UNIT_SCALE } from "../io/meshImport"; -export type { MeshObject, MeshImportReport, MeshUnit, MeshUp, MeshPlacement } from "../io/meshImport"; +export { readMesh, readMeshFlat, formatMeshReport, isMeshFile, MESH_UNITS, MESH_UNIT_SCALE } from "../io/meshImport"; +export type { MeshImportReport, MeshUnit, MeshUp, MeshPlacement } from "../io/meshImport"; +export { addedItems } from "./opsBuild"; export { addItems, fieldOps, findItem, itemsOf, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setField, setFieldIfChanged } from "./opsBuild"; export { cmdMutation } from "./document"; export type { EntityCollection, EntityOf, ProjectMutation } from "./opsBuild"; diff --git a/src/core/opsBuild.ts b/src/core/opsBuild.ts index 9a907662..aa4f4f19 100644 --- a/src/core/opsBuild.ts +++ b/src/core/opsBuild.ts @@ -102,6 +102,16 @@ export function addItems(collection: K, items: reado return [op]; } +/** Die Elemente, die `ops` in die Liste `collection` einfügen (`add`, bzw. `setField` der ganzen Liste). */ +export function addedItems(ops: readonly CoreOp[], collection: string): unknown[] { + const out: unknown[] = []; + for (const op of ops) { + if (op.kind === "add" && op.collection === collection) out.push(...op.items); + else if (op.kind === "setField" && op.key === collection && Array.isArray(op.value)) out.push(...(op.value as unknown[])); + } + return out; +} + /** Entfernt die Elemente aus `ids` (bzw. für die `ids(e)` wahr ist), die es gibt; leer, wenn keines trifft. */ export function removeItems( p: Project, diff --git a/src/export/exportDxf.cad.test.ts b/src/export/exportDxf.cad.test.ts index aa48c60b..26b3a2d6 100644 --- a/src/export/exportDxf.cad.test.ts +++ b/src/export/exportDxf.cad.test.ts @@ -11,7 +11,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { buildPlanDwg, buildPlanDxf, buildPlanDxfBinary, collectPlanDrawing } from "./exportDxf"; import { countByType, libreDwgReader, readDxf } from "./cadReadBack.testutil"; -import { parseDxf } from "../io/dxfParser"; +import { inspectDxf } from "../io/importView.testutil"; import { sampleProject } from "../model/sampleProject"; import { generatePlan } from "../plan/generatePlan"; import { flattenCategories } from "../model/types"; @@ -232,7 +232,7 @@ describe("Fachplaner-Export: DWG (libredwg) und eigener Import", () => { }); it("DXF-Import: Masszahlen, Möbelgeometrie und Türgeometrie kommen wieder an", () => { - const imp = parseDxf(buildPlanDxf(plan, project)); + const imp = inspectDxf(buildPlanDxf(plan, project)); const texts = (imp.texts ?? []).map((t) => t.text); expect(texts).toContain("2.00"); expect(texts).toContain("3.00"); @@ -246,6 +246,6 @@ describe("Fachplaner-Export: DWG (libredwg) und eigener Import", () => { it("DXF-Import: Papierbereich wird als Layout erkannt", () => { // Das Layout hat nur ein Ansichtsfenster (kein eigener Inhalt) und steht darum nicht in der Liste, ist aber lesbar. const dxf = buildPlanDxf(plan, project, { paperLayout: true }); - expect(() => parseDxf(dxf, "", "Plan_1-100")).not.toThrow(); + expect(() => inspectDxf(dxf, "Plan_1-100")).not.toThrow(); }); }); diff --git a/src/export/exportIfc.classification.test.ts b/src/export/exportIfc.classification.test.ts index 345cf12d..6e85dd1c 100644 --- a/src/export/exportIfc.classification.test.ts +++ b/src/export/exportIfc.classification.test.ts @@ -8,8 +8,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import "../engine/fileioWasm.setup"; import { exportIfcSpf } from "./exportIfc"; -import { readIfcElements } from "../io/ifcElements"; -import { classificationSuffix, ifcToImportedMeshes, readIfc } from "../io/ifcImport"; +import { importIfcInto, inspectIfc } from "../io/importView.testutil"; import { sampleProject } from "../model/sampleProject"; import type { Project, Room } from "../model/types"; @@ -98,29 +97,34 @@ describe("Rundreise Export → Import", () => { it("Klassifikation kommt an Bauteilen und am Mesh-Rest wieder an", async () => { const ifc = exportIfcSpf(houseWithRooms(), { ebkph: true, layerCodes: true }); const bytes = new TextEncoder().encode(ifc); - const { products, elements } = await readIfcElements(bytes); - const wall = elements.walls[0]; + const { products, raw } = await inspectIfc(bytes, true); + const wall = raw.filter((e) => e.kind === "wall")[0]; expect(wall.classifications?.map((c) => `${c.system}:${c.code}`).sort()).toEqual(["Dossier-Ebenen:20", "eBKP-H:C"]); expect(wall.classifications?.find((c) => c.system === "eBKP-H")?.name).toBe("Konstruktion Gebäude"); - const window = elements.openings.find((o) => o.kind === "window")!; + const window = raw.find((o) => o.kind === "opening" && o.openingKind === "window")!; expect(window.classifications?.map((c) => `${c.system}:${c.code}`).sort()).toEqual(["Dossier-Ebenen:21", "eBKP-H:E"]); - const door = elements.openings.find((o) => o.kind === "door")!; + const door = raw.find((o) => o.kind === "opening" && o.openingKind === "door")!; expect(door.classifications?.map((c) => c.system)).toEqual(["Dossier-Ebenen"]); // Dach bleibt Mesh, trägt aber seine Klassifikation. const roof = products.find((p) => p.ifcClass === "IfcRoof")!; expect(roof.classifications?.map((c) => c.code).sort()).toEqual(["31", "F"]); // Räume: Kategorie bleibt (auch über die Zone). - expect(elements.spaces.map((s) => s.sia).sort()).toEqual(["HNF", "HNF", "NNF", "VF"]); + expect(raw.filter((e) => e.kind === "space").map((s) => s.sia).sort()).toEqual(["HNF", "HNF", "NNF", "VF"]); + // Übernahme als Bauteile: Klassifikation gezählt (Wand/Decke/Raum haben kein Feld dafür). + const r = await importIfcInto(sampleProject, bytes, { elements: true }); + expect(r.summary?.classified).toBeGreaterThan(0); }); it("Mesh-Import: Klassifikation im Namen des Kontext-Objekts", async () => { const ifc = exportIfcSpf(sampleProject, { ebkph: true }); - const { products } = await readIfc(new TextEncoder().encode(ifc)); + const bytes = new TextEncoder().encode(ifc); + const { products } = await inspectIfc(bytes); expect(products.find((p) => p.ifcClass === "IfcRoof")?.classifications?.[0]).toMatchObject({ system: "eBKP-H", code: "F" }); - const roof = ifcToImportedMeshes(products, "haus.ifc", { group: "product" }).find((m) => m.layer === "IfcRoof")!; + const r = await importIfcInto(sampleProject, bytes, { group: "product" }); + const roof = r.meshes.find((m) => m.layer === "IfcRoof")!; expect(roof.name).toMatch(/ \[eBKP-H F\]$/); - expect(classificationSuffix(undefined)).toBe(""); - expect(classificationSuffix([{ system: "", code: "214", name: null }])).toBe(" [214]"); + // Ohne Klassifikation kein Zusatz. + expect(r.meshes.find((m) => m.layer === "IfcStairFlight")?.name).not.toMatch(/\[/); }); }); diff --git a/src/export/exportIfc.ifc2x3.test.ts b/src/export/exportIfc.ifc2x3.test.ts index 071658e5..e7147c5a 100644 --- a/src/export/exportIfc.ifc2x3.test.ts +++ b/src/export/exportIfc.ifc2x3.test.ts @@ -1,7 +1,7 @@ // IFC2x3-Export (Coordination View 2.0, [B5] 28.10.): Schema-Option des IFC-Exports. // // - Text: Kopf, Entitäten des Schemas (keine IFC4-Entitäten), gleiche GlobalIds wie IFC4. -// - Eigener Import (`src/io/ifcImport.ts`, `ifcElements.ts`): liest die 2x3-Datei als Meshes und als +// - Eigener Import (`src/io/ifcImport.ts`, Kern `import_ifc.rs`): liest die 2x3-Datei als Meshes und als // Bauteile mit demselben Ergebnis wie die IFC4-Datei. // - ifcopenshell (nur mit Python/ifcopenshell): Schema-Prüfung der 2x3-Datei ohne Befunde, Volumen und // Lage je Bauteil gleich der IFC4-Ausgabe. @@ -13,8 +13,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import "../engine/fileioWasm.setup"; import { exportIfcSpf } from "./exportIfc"; -import { ifcElementsToProject, readIfcElements } from "../io/ifcElements"; -import { readIfc } from "../io/ifcImport"; +import { importIfcInto, inspectIfc } from "../io/importView.testutil"; import { emptyProject, sampleProject } from "../model/sampleProject"; import type { Project } from "../model/types"; @@ -140,13 +139,13 @@ describe("IFC2x3-Export: eigener Import liest dasselbe wie bei IFC4", () => { const b = v3(sampleProject); it("Meshes: gleiche Körper (GlobalId, Volumen), Schema IFC2X3 erkannt", async () => { - const r4 = await readIfc(bytesOf(a)); - const r3 = await readIfc(bytesOf(b)); - expect(r4.report.schema).toBe("IFC4"); - expect(r3.report.schema).toBe("IFC2X3"); - expect(r3.report.parseErrors).toBe(0); - expect(r3.report.skippedItems).toEqual({}); - expect(r3.report.productsWithoutGeometry).toBe(0); + const r4 = await inspectIfc(bytesOf(a)); + const r3 = await inspectIfc(bytesOf(b)); + expect(r4.meta.schema).toBe("IFC4"); + expect(r3.meta.schema).toBe("IFC2X3"); + expect(r3.meta.parseErrors).toBe(0); + expect(r3.meta.skippedItems).toEqual({}); + expect(r3.meta.productsWithoutGeometry).toBe(0); expect(r3.products.length).toBe(r4.products.length); const vol = (p: { positions: ArrayLike; indices: ArrayLike }) => { let v = 0; @@ -169,11 +168,9 @@ describe("IFC2x3-Export: eigener Import liest dasselbe wie bei IFC4", () => { }); it("Bauteile: gleiche Wände, Öffnungen, Decken, Räume", async () => { - const e4 = await readIfcElements(bytesOf(a)); - const e3 = await readIfcElements(bytesOf(b)); - expect(e3.report.parseErrors).toBe(0); - const p4 = ifcElementsToProject(emptyProject, e4.products, e4.elements, { fileName: "haus.ifc" }); - const p3 = ifcElementsToProject(emptyProject, e3.products, e3.elements, { fileName: "haus.ifc" }); + const p4 = await importIfcInto(emptyProject, bytesOf(a), { elements: true }); + const p3 = await importIfcInto(emptyProject, bytesOf(b), { elements: true }); + expect(p3.report.parseErrors).toBe(0); expect(p3.summary).toEqual(p4.summary); for (const key of ["walls", "openings", "ceilings", "rooms", "wallTypes"] as const) { expect(normIds(p3.project[key]), key).toEqual(normIds(p4.project[key])); diff --git a/src/i18n/de.ts b/src/i18n/de.ts index ffdc583e..8a69b6ef 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1682,6 +1682,7 @@ export const de = { // ── Import-Dialog (ImportDialog) ───────────────────────────────────────── "import.title": "DXF importieren", + "import.failed": "Import fehlgeschlagen", "import.close": "Schließen", "import.file": "Datei", "import.summary.heading": "Inhalt", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 9824da9f..d309481b 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1670,6 +1670,7 @@ export const en: Record = { // Import dialog. "import.title": "Import DXF", + "import.failed": "Import failed", "import.close": "Close", "import.file": "File", "import.summary.heading": "Contents", diff --git a/src/io/dwgParser.test.ts b/src/io/dwgParser.test.ts index 6bd7d3f6..71131e37 100644 --- a/src/io/dwgParser.test.ts +++ b/src/io/dwgParser.test.ts @@ -8,8 +8,7 @@ import { beforeAll, describe, expect, it } from "vitest"; import { readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { parseDwg } from "./dwgParser"; -import { parseDxf } from "./dxfParser"; -import type { DxfImportResult } from "./dxfParser"; +import { inspectDxf, viewImport, type ImportView } from "./importView.testutil"; import { loadFileioForTests } from "../engine/fileioWasm.testing"; beforeAll(loadFileioForTests); @@ -18,14 +17,14 @@ const fixture = (name: string): Uint8Array => new Uint8Array(readFileSync(fileURLToPath(new URL(`./testdata/${name}`, import.meta.url)))); const asBuffer = (b: Uint8Array): ArrayBuffer => b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer; -function meshByLayer(res: DxfImportResult, layer: string) { +function meshByLayer(res: ImportView, layer: string) { const m = res.meshes.find((x) => x.layer === layer); expect(m, `Mesh auf Ebene ${layer}`).toBeDefined(); return m!; } /** Gemeinsame Erwartungen für alle Varianten der Kachel. */ -function checkTile(res: DxfImportResult) { +function checkTile(res: ImportView) { expect(res.meshes.map((m) => m.layer).sort()).toEqual(["Roof", "Wall"]); const roof = meshByLayer(res, "Roof"); // 3 Punkte, je um die INSERT-Einfügung verschoben (Skalierung 1, Drehung 0). @@ -50,13 +49,13 @@ function checkTile(res: DxfImportResult) { describe("parseDwg (acadrust)", () => { it("liest Polyface-Meshes aus Blöcken nach Ebene gruppiert, mit INSERT-Verschiebung (R2018)", async () => { - const res = await parseDwg(asBuffer(fixture("tile-r2018.dwg"))); + const res = viewImport((await parseDwg(asBuffer(fixture("tile-r2018.dwg")))).src); checkTile(res); expect(res.meshes.map((m) => m.name).sort()).toEqual(["DWG-Mesh (Roof)", "DWG-Mesh (Wall)"]); }); it("liest dieselbe Kachel als R2000-DWG", async () => { - checkTile(await parseDwg(asBuffer(fixture("tile-r2000.dwg")))); + checkTile(viewImport((await parseDwg(asBuffer(fixture("tile-r2000.dwg")))).src)); }); it("wirft bei kaputter DWG-Datei statt abzustürzen", async () => { @@ -71,17 +70,17 @@ describe("parseDwg (acadrust)", () => { describe("parseDxf — Binär-DXF und Code-Seite", () => { it("liest Binär-DXF gleich wie die ASCII-Quelle", () => { - checkTile(parseDxf(fixture("tile-r2000-bin.dxf"))); + checkTile(inspectDxf(fixture("tile-r2000-bin.dxf"))); }); it("ASCII-Quelle in cp1252 ($DWGCODEPAGE fehlt) — Umlaute bleiben erhalten", () => { - checkTile(parseDxf(fixture("tile.dxf"))); + checkTile(inspectDxf(fixture("tile.dxf"))); }); }); describe("parseDxf — Papierbereich-Layouts (Datei mit ezdxf erzeugt)", () => { it("listet Layouts mit Inhalt im Bericht; Modellraum bleibt Vorgabe", () => { - const res = parseDxf(fixture("layouts.dxf")); + const res = inspectDxf(fixture("layouts.dxf")); expect(res.layouts).toEqual([{ name: "A3 Grundriss", entities: 2 }]); expect(res.layout).toBeUndefined(); expect(res.recovered).toBe(false); @@ -90,7 +89,7 @@ describe("parseDxf — Papierbereich-Layouts (Datei mit ezdxf erzeugt)", () => { }); it("liest ein Layout statt des Modellraums (Papier in mm → Meter)", () => { - const res = parseDxf(fixture("layouts.dxf"), "", "A3 Grundriss"); + const res = inspectDxf(fixture("layouts.dxf"), "A3 Grundriss"); expect(res.layout).toBe("A3 Grundriss"); const c = res.contours[0].contours[0]; expect(c.pts[1].x).toBeCloseTo(0.42, 9); diff --git a/src/io/dwgParser.ts b/src/io/dwgParser.ts index a62cb840..e2bf3c1a 100644 --- a/src/io/dwgParser.ts +++ b/src/io/dwgParser.ts @@ -1,13 +1,13 @@ // DWG-Import → Kontext-Geometrie: dünne Fassade über das Rust-Format-Modul (acadrust, DWG R13–2018, // `src-tauri/fileio/src/import.rs`). Gleicher Weg wie DXF (`dxfParserAsync.ts`, Web-Worker), gleiches -// `DxfImportResult`: Konturen, Texte, Meshes je Ebene (z. B. „Roof"/„Wall"/„Floor" bei +// Ergebnis (`ParsedImport`, Kern liest den Puffer): Konturen, Texte, Meshes je Ebene (z. B. „Roof"/„Wall"/„Floor" bei // swissBUILDINGS3D v3 „separated", Polyface-Meshes in per INSERT platzierten Blöcken), Ebenenfarben, // Entity-Histogramm. -import type { DxfImportResult } from "./dxfParser"; +import type { ParsedImport } from "./importSource"; import { parseDxfAsync } from "./dxfParserAsync"; /** Liest eine DWG-Datei. Wirft bei unlesbaren Dateien (der Aufrufer zeigt den ODA-Hinweis). */ -export function parseDwg(data: ArrayBuffer, layout?: string): Promise { +export function parseDwg(data: ArrayBuffer, layout?: string): Promise { return parseDxfAsync(data, undefined, layout); } diff --git a/src/io/dxfBulgeImport.test.ts b/src/io/dxfBulgeImport.test.ts index 4ce386e8..cab99474 100644 --- a/src/io/dxfBulgeImport.test.ts +++ b/src/io/dxfBulgeImport.test.ts @@ -4,7 +4,8 @@ import { beforeAll, describe, expect, it } from "vitest"; import { parseDxf } from "./dxfParser"; import { loadFileioForTests } from "../engine/fileioWasm.testing"; -import { contoursToDrawings } from "./dxfToDrawings"; +import { importInto, inspectDxf } from "./importView.testutil"; +import { emptyProject } from "../model/sampleProject"; import { bulgePolylinePoints } from "../geometry/bulge"; import type { Vec2 } from "../model/types"; @@ -26,7 +27,7 @@ const PARZELLE = [ "10", "2600000", "20", "1200030", ]; -const toDrawings = (src: string) => contoursToDrawings(parseDxf(src).contours, "L", "active", "01", () => "01"); +const toDrawings = (src: string) => importInto(emptyProject, parseDxf(src), { categoryMode: "active", activeCategoryCode: "01" }).drawings; describe("DXF-Import: Polylinien mit Bögen", () => { it("bleiben eine Polylinie mit den DXF-Stützpunkten und Bulges", () => { @@ -45,7 +46,7 @@ describe("DXF-Import: Polylinien mit Bögen", () => { }); it("gleiche Bogen-Seite wie die Tessellierung des Imports (Vorzeichen DXF ↔ Modell)", () => { - const contour = parseDxf(dxf(PARZELLE)).contours[0].contours[0]; + const contour = inspectDxf(dxf(PARZELLE)).contours[0].contours[0]; const [d] = toDrawings(dxf(PARZELLE)); if (d.geom.shape !== "polyline") throw new Error("Polylinie erwartet"); const ours = bulgePolylinePoints(d.geom.pts, d.geom.bulge, true); diff --git a/src/io/dxfParser.test.ts b/src/io/dxfParser.test.ts index 4c182d90..4f84937e 100644 --- a/src/io/dxfParser.test.ts +++ b/src/io/dxfParser.test.ts @@ -4,8 +4,9 @@ import { beforeAll, describe, it, expect } from "vitest"; import { parseDxf } from "./dxfParser"; import { loadFileioForTests } from "../engine/fileioWasm.testing"; -import { contoursToDrawings, textsToDrawings } from "./dxfToDrawings"; -import type { Contour, ContourSet, Vec2 } from "../model/types"; +import { importInto, inspectDxf, type ViewContour } from "./importView.testutil"; +import { emptyProject } from "../model/sampleProject"; +import type { Vec2 } from "../model/types"; /** Minimales DXF aus Gruppencode/Wert-Paaren; nur eine ENTITIES-Sektion. */ function dxf(...entities: string[][]): string { @@ -46,8 +47,8 @@ beforeAll(loadFileioForTests); const dist = (p: Vec2, cx: number, cy: number) => Math.hypot(p.x - cx, p.y - cy); /** Einzige Kontur des Imports (Test-Bequemlichkeit). */ -function onlyContour(text: string): Contour { - const res = parseDxf(text); +function onlyContour(text: string): ViewContour { + const res = inspectDxf(text); expect(res.contours).toHaveLength(1); expect(res.contours[0].contours).toHaveLength(1); return res.contours[0].contours[0]; @@ -118,7 +119,7 @@ function ellipse2Dxf(): string { describe("parseDxf — gemischt", () => { it("liest mehrere Kurven-Entities in EINEN Konturensatz", () => { - const res = parseDxf(dxf(circle(0, 0, 0, 1), arc(0, 0, 2, 0, 90))); + const res = inspectDxf(dxf(circle(0, 0, 0, 1), arc(0, 0, 2, 0, 90))); expect(res.contours).toHaveLength(1); expect(res.contours[0].contours).toHaveLength(2); }); @@ -262,7 +263,7 @@ describe("parseDxf — INSERT", () => { }); it("expandiert ein 2×1-Array zu zwei Konturen", () => { - const res = parseDxf( + const res = inspectDxf( dxfFull([block("seg", 0, 0, line(0, 0, 1, 0))], [insert("seg", 0, 0, { nc: 2, dc: 10 })]), ); const cs = res.contours[0].contours; @@ -408,7 +409,7 @@ describe("parseDxf — HATCH", () => { "10", "3", "20", "3", "10", "7", "20", "3", "10", "7", "20", "7", "10", "3", "20", "7", "97", "0", ]; - const res = parseDxf(dxf(g)); + const res = inspectDxf(dxf(g)); expect(res.contours[0].contours).toHaveLength(2); expect(res.contours[0].contours.every((c) => c.filled && c.closed)).toBe(true); }); @@ -428,7 +429,7 @@ function mtextEnt(x: number, y: number, h: number, s: string): string[] { describe("parseDxf — TEXT/MTEXT", () => { it("TEXT → ImportedText mit Position/Höhe/Winkel (Grad→Radiant)", () => { - const res = parseDxf(dxf(textEnt(5, 3, 0.5, 90, "Hallo"))); + const res = inspectDxf(dxf(textEnt(5, 3, 0.5, 90, "Hallo"))); expect(res.texts).toHaveLength(1); const t0 = res.texts![0]; expect(t0.at.x).toBeCloseTo(5, 9); @@ -439,7 +440,7 @@ describe("parseDxf — TEXT/MTEXT", () => { }); it("MTEXT → Formatcodes gesäubert, \\P = neue Zeile (je Zeile ein Text, oben links verankert)", () => { - const res = parseDxf(dxf(mtextEnt(1, 2, 0.3, "Welt\\Pzeile2"))); + const res = inspectDxf(dxf(mtextEnt(1, 2, 0.3, "Welt\\Pzeile2"))); expect(res.texts!.map((t) => t.text)).toEqual(["Welt", "zeile2"]); expect(res.texts![0].at.x).toBeCloseTo(1, 9); expect(res.texts![0].at.y).toBeCloseTo(2 - 0.3, 9); @@ -448,37 +449,38 @@ describe("parseDxf — TEXT/MTEXT", () => { }); it("MTEXT: Schriftcodes, Stapel, \\~ und Sonderzeichen", () => { - const res = parseDxf(dxf(mtextEnt(0, 0, 0.2, "{\\fArial|b1;Fett}\\~\\H2x;gross \\S1/2; 12%%d"))); + const res = inspectDxf(dxf(mtextEnt(0, 0, 0.2, "{\\fArial|b1;Fett}\\~\\H2x;gross \\S1/2; 12%%d"))); expect(res.texts!.map((t) => t.text)).toEqual(["Fett gross 1/2 12°"]); }); it("TEXT zentriert: Anker ist der Ausrichtpunkt, Text beginnt links davon", () => { const g = ["0", "TEXT", "8", "0", "10", "0", "20", "0", "30", "0", "40", "1", "72", "1", "11", "10", "21", "5", "31", "0", "1", "Mitte"]; - const t = parseDxf(dxf(g)).texts![0]; + const t = inspectDxf(dxf(g)).texts![0]; expect(t.at.x).toBeLessThan(10); expect(t.at.x).toBeGreaterThan(10 - 6); expect(t.at.y).toBeCloseTo(5, 9); }); it("leerer Text wird übersprungen", () => { - const res = parseDxf(dxf(textEnt(0, 0, 0.2, 0, ""))); + const res = inspectDxf(dxf(textEnt(0, 0, 0.2, 0, ""))); expect(res.texts ?? []).toHaveLength(0); }); it("fehlende Höhe → positiver Default", () => { const g = ["0", "TEXT", "8", "0", "10", "0", "20", "0", "30", "0", "1", "X"]; - const res = parseDxf(dxf(g)); + const res = inspectDxf(dxf(g)); expect(res.texts![0].height).toBeGreaterThan(0); }); }); -describe("textsToDrawings", () => { - it("ImportedText → Drawing2D {shape:\"text\"}", () => { - const drawings = textsToDrawings( - [{ at: { x: 1, y: 2 }, text: "Hi", height: 0.4, angle: 0, layer: "L" }], - "lvl", "active", "CODE", (s) => s, - ); +/** DXF über den Kern ins leere Projekt importieren → die Zeichnungen der neuen Ebene. */ +const drawingsOf = (text: string) => importInto(emptyProject, parseDxf(text), { categoryMode: "active", activeCategoryCode: "CODE" }).drawings; + +describe("Import: Text → Zeichnung", () => { + it("TEXT → Drawing2D {shape:\"text\"}", () => { + const drawings = drawingsOf(dxf(textEnt(1, 2, 0.4, 0, "Hi"))); expect(drawings).toHaveLength(1); + expect(drawings[0].categoryCode).toBe("CODE"); const g = drawings[0].geom; expect(g.shape).toBe("text"); if (g.shape === "text") { @@ -507,13 +509,9 @@ describe("parseDxf — Kurven behalten echte Geometrie (curve)", () => { }); }); -describe("contoursToDrawings — Kurven → glatte Formen", () => { - it("curve circle → {shape:\"circle\"}", () => { - const set: ContourSet = { - id: "s", type: "contourSet", name: "c", - contours: [{ z: 0, closed: true, pts: [{ x: 0, y: 0 }], curve: { kind: "circle", cx: 1, cy: 2, r: 3, a0: 0, a1: Math.PI * 2 } }], - }; - const [d] = contoursToDrawings([set], "lvl", "active", "C", (s) => s); +describe("Import: Kurven → glatte Formen", () => { + it("CIRCLE → {shape:\"circle\"}", () => { + const [d] = drawingsOf(dxf(circle(1, 2, 0, 3))); expect(d.geom.shape).toBe("circle"); if (d.geom.shape === "circle") { expect(d.geom.r).toBeCloseTo(3, 9); @@ -521,12 +519,8 @@ describe("contoursToDrawings — Kurven → glatte Formen", () => { } }); - it("curve arc → {shape:\"arc\"}", () => { - const set: ContourSet = { - id: "s", type: "contourSet", name: "c", - contours: [{ z: 0, closed: false, pts: [{ x: 0, y: 0 }], curve: { kind: "arc", cx: 0, cy: 0, r: 5, a0: 0, a1: 1 } }], - }; - const [d] = contoursToDrawings([set], "lvl", "active", "C", (s) => s); + it("ARC → {shape:\"arc\"}", () => { + const [d] = drawingsOf(dxf(arc(0, 0, 5, 0, 57.29577951308232))); expect(d.geom.shape).toBe("arc"); if (d.geom.shape === "arc") { expect(d.geom.r).toBeCloseTo(5, 9); @@ -535,23 +529,16 @@ describe("contoursToDrawings — Kurven → glatte Formen", () => { }); }); -describe("contoursToDrawings — HATCH-Füllung", () => { +describe("Import: HATCH-Füllung", () => { it("gefüllte Kontur → Drawing2D mit fillColor und polyline-Form", () => { - const set: ContourSet = { - id: "s", type: "contourSet", name: "h", - contours: [{ z: 0, closed: true, filled: true, pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }] }], - }; - const [d] = contoursToDrawings([set], "lvl", "active", "CODE", (s) => s); + const [d] = drawingsOf(dxf(hatchPoly([[0, 0], [1, 0], [1, 1]]))); expect(d.geom.shape).toBe("polyline"); - expect(d.fillColor).toBeTruthy(); + expect(d.fillColor).toBe("#c8c8c8"); }); it("ungefüllte Kontur → Drawing2D ohne fillColor", () => { - const set: ContourSet = { - id: "s", type: "contourSet", name: "h", - contours: [{ z: 0, closed: true, pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }] }], - }; - const [d] = contoursToDrawings([set], "lvl", "active", "CODE", (s) => s); + const [d] = drawingsOf(dxf(["0", "LWPOLYLINE", "8", "0", "90", "3", "70", "1", "10", "0", "20", "0", "10", "1", "20", "0", "10", "1", "20", "1"])); + expect(d.geom.shape).toBe("polyline"); expect(d.fillColor).toBeUndefined(); }); }); @@ -575,7 +562,7 @@ describe("parseDxf — Polyface-Mesh (POLYLINE Flag 64, swissBUILDINGS3D-Format) "0", "SEQEND", "0", "ENDSEC", "0", "EOF", ]; - const res = parseDxf(lines.join("\n")); + const res = inspectDxf(lines.join("\n")); expect(res.meshes).toHaveLength(1); expect(res.meshes[0].positions.length / 3).toBe(3); expect(res.meshes[0].indices).toEqual([0, 1, 2]); @@ -594,7 +581,7 @@ describe("parseDxf — Polyface-Mesh (POLYLINE Flag 64, swissBUILDINGS3D-Format) "0", "SEQEND", "0", "ENDSEC", "0", "EOF", ]; - const res = parseDxf(lines.join("\n")); + const res = inspectDxf(lines.join("\n")); expect(res.meshes).toHaveLength(1); expect(res.meshes[0].positions.length / 3).toBe(4); expect(res.meshes[0].indices.length / 3).toBe(2); @@ -612,7 +599,7 @@ describe("parseDxf — Polyface-Mesh (POLYLINE Flag 64, swissBUILDINGS3D-Format) "0", "SEQEND", "0", "ENDSEC", "0", "EOF", ]; - const res = parseDxf(lines.join("\n")); + const res = inspectDxf(lines.join("\n")); expect(res.meshes).toHaveLength(1); expect(res.meshes[0].indices).toEqual([0, 1, 2]); }); @@ -630,7 +617,7 @@ describe("parseDxf — $INSUNITS", () => { }; it("Millimeter → Meter (Koordinaten, Texthöhe), unitScale 0.001", () => { - const res = parseDxf(withUnits(4)); + const res = inspectDxf(withUnits(4)); expect(res.insUnits).toBe(4); expect(res.unitScale).toBe(0.001); const c = res.contours[0].contours[0]; @@ -643,13 +630,13 @@ describe("parseDxf — $INSUNITS", () => { }); it("Zentimeter und Zoll", () => { - expect(parseDxf(withUnits(5)).contours[0].contours[0].pts[1].x).toBeCloseTo(30, 12); - expect(parseDxf(withUnits(1)).contours[0].contours[0].pts[0].x).toBeCloseTo(25.4, 12); + expect(inspectDxf(withUnits(5)).contours[0].contours[0].pts[1].x).toBeCloseTo(30, 12); + expect(inspectDxf(withUnits(1)).contours[0].contours[0].pts[0].x).toBeCloseTo(25.4, 12); }); it("Meter, ohne Einheit (0), unbekannt und fehlend bleiben 1:1", () => { for (const u of [6, 0, 77, null]) { - const res = parseDxf(withUnits(u)); + const res = inspectDxf(withUnits(u)); expect(res.unitScale, `${u}`).toBe(1); expect(res.contours[0].contours[0].pts[0].x, `${u}`).toBe(1000); } @@ -658,14 +645,12 @@ describe("parseDxf — $INSUNITS", () => { describe("parseDxf — SOLID/TRACE", () => { it("SOLID (Eckenfolge 1,2,4,3) → gefüllte geschlossene Kontur → Drawing2D mit Füllung", () => { - const res = parseDxf( - dxf(["0", "SOLID", "8", "S", "10", "0", "20", "0", "30", "0", "11", "2", "21", "0", "31", "0", "12", "0", "22", "1", "32", "0", "13", "2", "23", "1", "33", "0"]), - ); - const c = res.contours[0].contours[0]; + const text = dxf(["0", "SOLID", "8", "S", "10", "0", "20", "0", "30", "0", "11", "2", "21", "0", "31", "0", "12", "0", "22", "1", "32", "0", "13", "2", "23", "1", "33", "0"]); + const c = inspectDxf(text).contours[0].contours[0]; expect(c.filled).toBe(true); expect(c.closed).toBe(true); expect(c.pts).toEqual([{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 1 }, { x: 0, y: 1 }]); - const [d] = contoursToDrawings(res.contours, "L", "active", "01", () => "01"); + const [d] = drawingsOf(text); expect(d.fillColor).toBeDefined(); }); @@ -689,26 +674,26 @@ describe("parseDxf — Papierbereich-Layouts und beschädigte Dateien", () => { }; it("ohne Layouts: leere Liste, Modellraum, nicht wiederhergestellt", () => { - const res = parseDxf(withLayout()); + const res = inspectDxf(withLayout()); expect(res.layouts).toEqual([]); expect(res.layout).toBeUndefined(); expect(res.recovered).toBe(false); }); it("unbekanntes Layout → Fehler mit Meldung", () => { - expect(() => parseDxf(withLayout(), "", "Gibt es nicht")).toThrow(/nicht gefunden/); + expect(() => inspectDxf(withLayout(), "Gibt es nicht")).toThrow(/nicht gefunden/); }); it("leere/fremde Datei → verständliche Fehlermeldung statt Absturz", () => { - expect(() => parseDxf(new Uint8Array(0))).toThrow(/leer/); - expect(() => parseDxf("Dies ist ein Brief.\nMit Gruessen")).toThrow(/Keine DXF/); + expect(() => inspectDxf(new Uint8Array(0))).toThrow(/leer/); + expect(() => inspectDxf("Dies ist ein Brief.\nMit Gruessen")).toThrow(/Keine DXF/); }); it("abgeschnittene Datei → teilweise gelesen (recovered) oder Fehlermeldung, nie ein Absturz", () => { const full = dxf(circle(1, 1, 0, 1), circle(2, 2, 0, 1), circle(3, 3, 0, 1)); const cut = full.slice(0, full.indexOf("EOF") - 30); try { - const res = parseDxf(cut); + const res = inspectDxf(cut); expect(res.contours[0].contours.length).toBeGreaterThan(0); } catch (e) { expect(String(e)).toMatch(/\S/); diff --git a/src/io/dxfParser.ts b/src/io/dxfParser.ts index ebaad5e3..6afb3e27 100644 --- a/src/io/dxfParser.ts +++ b/src/io/dxfParser.ts @@ -1,82 +1,20 @@ -// DXF/DWG-Import → Kontext-Geometrie: dünne Fassade über das Rust-Format-Modul -// (`src-tauri/fileio/src/import.rs`, acadrust; WASM `pkgFileIo`, geladen über `engine/fileioWasm.ts`). +// DXF/DWG-Import: dünne Fassade über das Rust-Format-Modul (`src-tauri/fileio/src/import.rs`, acadrust; +// WASM `pkgFileIo`, geladen über `engine/fileioWasm.ts`). // -// Importierte Geometrie ist „dumme" KONTEXT-Geometrie (Anzeige + späteres Snap-Ziel), NICHT -// semantisch. Rust liest DXF (ASCII und Binär, R12–2018+) und DWG (R13–2018) und liefert einen -// flachen Puffer + String-Tabelle; hier wird daraus `DxfImportResult` (Konturen, Texte, Meshes, -// Ebenenfarben, Diagnose, $INSUNITS). Abgebildet werden LINE, LWPOLYLINE/POLYLINE (inkl. Bulges), -// ARC/CIRCLE (mit wahrer Kurve), ELLIPSE, SPLINE, HATCH und SOLID/TRACE (gefüllte Flächen), TEXT/MTEXT -// (Formatcodes aufgelöst, Ausrichtung/Drehung auf den Grundlinien-Anfang umgerechnet, mehrzeiliger -// MTEXT je Zeile ein Text), ATTRIB/ATTDEF, DIMENSION (Anonymblock, sonst aus Definitionspunkten und -// Stil mit Pfeilspitzen aufgebaut), LEADER/MULTILEADER (Linien mit Pfeilspitzen, Spline-Pfade, -// Text oder Block-Inhalt), 3DFACE, Polyface-/Polygon-Mesh, MESH; INSERT wird rekursiv aufgelöst -// (Basispunkt, Skalierung, Drehung, Raster; Ebene „0" erbt die Ebene der Referenz). `$INSUNITS` -// rechnet Rust auf Meter um. Papierbereich: `layouts` listet die Layouts der Datei, `parseDxf(…, layout)` -// liest eines statt des Modellraums. +// Rust liest DXF (ASCII und Binär, R12–2018+) und DWG (R13–2018) und liefert einen flachen Puffer + +// String-Tabelle: LINE, LWPOLYLINE/POLYLINE (inkl. Bulges), ARC/CIRCLE (mit wahrer Kurve), ELLIPSE, SPLINE, +// HATCH und SOLID/TRACE (gefüllte Flächen), TEXT/MTEXT, ATTRIB/ATTDEF, DIMENSION, LEADER/MULTILEADER, +// 3DFACE, Polyface-/Polygon-Mesh, MESH; INSERT rekursiv aufgelöst; `$INSUNITS` auf Meter umgerechnet. +// Papierbereich: `parseDxf(…, layout)` liest ein Layout statt des Modellraums. // -// `parseDxf` ist synchron und verlangt das geladene Modul (`loadFileio()`); die App ruft es im -// Web-Worker (`dxfParserAsync.ts`), Tests laden es per `loadFileioForTests()`. +// Die Umwandlung ins Projekt (Zeichnungen, Kategorien je Layer, Meshes) macht der Kern beim Bestätigen +// (`ProjectDocument.importDrawing`, [K4] S4); hier bleiben Puffer + Zusammenfassung für den Dialog. +// +// `parseDxf` ist synchron und verlangt das geladene Modul (`loadFileio()`); die App liest im Web-Worker +// (`dxfParserAsync.ts`), Tests laden es per `loadFileioForTests()`. -import type { Contour, ContourSet, ImportedMesh, ImportedText, Vec2 } from "../model/types"; -import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories"; import { fileioLoaded } from "../engine/fileioWasm"; - -/** - * Optionale Import-Diagnose: Histogramm der gelesenen Entity-Typen (Typ → Anzahl) - * und die Gesamtzahl. Macht beim Fall „keine Geometrie gefunden" sichtbar, WORAN es - * liegt (z. B. „0 Entities" = Encoding-/Versions-Problem vs. „500 ARC, 200 INSERT"). - */ -export interface ImportDiagnostics { - /** Anzahl je (Modellraum-)Entity-Typ, inkl. expandierter Block-Entities. */ - entityCounts: Record; - /** Gesamtzahl betrachteter Entities. */ - total: number; -} - -/** Ergebnis eines DXF-/DWG-Imports: rohe Meshes + Konturen-Sätze + Texte. */ -export interface DxfImportResult { - meshes: ImportedMesh[]; - contours: ContourSet[]; - /** Importierte TEXT/MTEXT-Elemente. */ - texts?: ImportedText[]; - /** Optionale Diagnose (Entity-Typ-Histogramm). */ - diagnostics?: ImportDiagnostics; - /** Farbe je DXF-Layer (Hex) aus der LAYER-Tabelle — für neu angelegte Kategorien. */ - layerColors?: Record; - /** Strichstärke je Layer in Papier-mm (PDF-Import [76]: aus der Linienbreite) — für neue Kategorien. */ - layerLineWeights?: Record; - /** Füllfarbe je Layer (PDF-Import [76]): gefüllte Konturen dieses Layers bekommen sie statt des Grau. */ - layerFillColors?: Record; - /** Strichmuster je Layer in Papier-mm, an/aus/an/aus (PDF-Import [76], Operator `d`) — wird zum Linienstil. */ - layerDashes?: Record; - /** `$INSUNITS` der Datei (0 = ohne Einheit, 4 = mm, 5 = cm, 6 = m …), roh wie gelesen. */ - insUnits?: number; - /** - * Meter je Zeicheneinheit nach `$INSUNITS` (mm 0.001, cm 0.01, m 1, Zoll 0.0254 …). Rust hat - * Koordinaten, Radien und Texthöhen damit schon in Meter umgerechnet; hier nur zur Anzeige - * („Datei in mm, umgerechnet“). 0/unbekannt = 1, die Koordinaten bleiben dann 1:1. - */ - unitScale?: number; - /** Papierbereich-Layouts der Datei (ohne „Model"), in Reiter-Reihenfolge; `entities` = Zeichnungs-Entities. */ - layouts?: { name: string; entities: number }[]; - /** Name des gelesenen Layouts; fehlt beim Modellraum. */ - layout?: string; - /** Die Datei war beschädigt/abgeschnitten und wurde nur teilweise gelesen. */ - recovered?: boolean; -} - -/** - * Kontur aus dem DXF/DWG-Import. Polylinien mit Bögen (LWPOLYLINE/POLYLINE, Schraffur-Rand aus einer - * Polylinie) tragen zusätzlich ihre Stützpunkte mit Bulge (DXF-Konvention = `Drawing2DGeom` polyline - * `bulge`): die 2D-Zeichnung bekommt echte Bögen statt des tessellierten `pts` (Kataster-Fund 29.10.: - * Strassenparzellen mit hunderten Zerlegungspunkten). Nur beim Import gebraucht, nicht im Modell. - */ -export interface ImportContour extends Contour { - bulgePolyline?: { pts: Vec2[]; bulge: number[] }; -} - -let importSeq = 0; -const nextId = (prefix: string, idPrefix: string) => `${idPrefix}${prefix}-${Date.now()}-${importSeq++}`; +import { parsedImport, type ImportChunk, type ParsedImport } from "./importSource"; /** Eingabe als Bytes (Text wird UTF-8-kodiert). */ function toBytes(input: string | ArrayBuffer | Uint8Array): Uint8Array { @@ -85,23 +23,19 @@ function toBytes(input: string | ArrayBuffer | Uint8Array): Uint8Array { } /** - * Liest eine DXF-Datei (Text oder Bytes; Binär-DXF und DWG werden am Inhalt erkannt) in Kontext- - * Geometrie. Wirft bei unlesbaren Dateien (Meldung aus Rust) oder wenn das Modul nicht geladen ist. - * `idPrefix` macht ids eindeutig, wenn mehrere Realms (Worker) parallel parsen. + * Liest eine DXF-Datei (Text oder Bytes; Binär-DXF und DWG werden am Inhalt erkannt): Puffer für den Kern + * und Zusammenfassung für den Dialog. Wirft bei unlesbaren Dateien (Meldung aus Rust) oder wenn das Modul + * nicht geladen ist. */ -export function parseDxf(input: string | ArrayBuffer | Uint8Array, idPrefix = "", layout?: string): DxfImportResult { - const { geom, strings } = importDrawingFlat(input, layout); - return decodeImport(geom, strings, idPrefix); +export function parseDxf(input: string | ArrayBuffer | Uint8Array, layout?: string): ParsedImport { + return parsedImport([importDrawingFlat(input, layout)]); } /** * Rust-Aufruf: flacher Puffer + String-Tabelle (für die Übergabe aus dem Worker). Mit `layout` wird * das Papierbereich-Layout dieses Namens gelesen (unbekannt → Fehler mit den vorhandenen Namen). */ -export function importDrawingFlat( - input: string | ArrayBuffer | Uint8Array, - layout?: string, -): { geom: Float64Array; strings: string[] } { +export function importDrawingFlat(input: string | ArrayBuffer | Uint8Array, layout?: string): ImportChunk { const m = fileioLoaded(); if (!m) throw new Error("Format-Modul nicht geladen: loadFileio() muss vor dem Import laufen."); const bytes = toBytes(input); @@ -112,120 +46,3 @@ export function importDrawingFlat( res.free(); } } - -/** Dekodiert den Puffer aus `import.rs::encode` (Aufbau dort beschrieben). */ -export function decodeImport(geom: Float64Array, strings: readonly string[], idPrefix = ""): DxfImportResult { - let i = 0; - const num = () => geom[i++]; - const str = () => strings[geom[i++]] ?? ""; - if (num() !== 3) throw new Error("Unbekanntes Importformat (Version)."); - const fmt = num() === 1 ? "DWG" : "DXF"; - const insUnits = num(); - const unitScale = num(); - const total = num(); - - const layerColors: Record = {}; - for (let n = num(), k = 0; k < n; k++) { - const name = str(); - layerColors[name] = `#${(num() & 0xffffff).toString(16).padStart(6, "0")}`; - } - const entityCounts: Record = {}; - for (let n = num(), k = 0; k < n; k++) { - const name = str(); - entityCounts[name] = num(); - } - - const contours: Contour[] = []; - for (let n = num(), k = 0; k < n; k++) { - const layer = str(); - const flags = num(); - const z = num(); - const c: Contour = { z, pts: [], closed: (flags & 1) !== 0, layer }; - if (flags & 2) c.filled = true; - if (flags & 4) { - const kind = num() === 1 ? "circle" : "arc"; - c.curve = { kind, cx: num(), cy: num(), r: num(), a0: num(), a1: num() }; - } - const np = num(); - const pts = new Array(np); - for (let p = 0; p < np; p++) pts[p] = { x: geom[i + 2 * p], y: geom[i + 2 * p + 1] }; - i += 2 * np; - c.pts = pts; - if (flags & 8) { - const nv = num(); - const vpts: Vec2[] = new Array(nv); - const bulge: number[] = new Array(nv); - for (let v = 0; v < nv; v++) { - vpts[v] = { x: geom[i + 3 * v], y: geom[i + 3 * v + 1] }; - bulge[v] = geom[i + 3 * v + 2]; - } - i += 3 * nv; - (c as ImportContour).bulgePolyline = { pts: vpts, bulge }; - } - contours.push(c); - } - - const texts: ImportedText[] = []; - for (let n = num(), k = 0; k < n; k++) { - const layer = str(); - const text = str(); - const x = num(); - const y = num(); - const height = num(); - const angle = num(); - texts.push({ at: { x, y }, text, height, angle, layer }); - } - - const meshes: ImportedMesh[] = []; - const nMeshes = num(); - for (let k = 0; k < nMeshes; k++) { - const layer = str(); - const nPos = num(); - const nIdx = num(); - const positions = Array.from(geom.subarray(i, i + nPos * 3)); - i += nPos * 3; - const indices = Array.from(geom.subarray(i, i + nIdx)); - i += nIdx; - meshes.push({ - id: nextId("imported", idPrefix), - type: "importedMesh", - name: nMeshes > 1 ? `${fmt}-Mesh (${layer})` : `${fmt}-Mesh`, - categoryCode: GENERIC_IMPORT_CATEGORY.code, - layer: layer === "0" ? undefined : layer, - positions, - indices, - }); - } - - const layouts: { name: string; entities: number }[] = []; - for (let n = num(), k = 0; k < n; k++) { - const name = str(); - layouts.push({ name, entities: num() }); - } - const recovered = num() === 1; - const layoutIdx = num(); - const layout = layoutIdx >= 0 ? (strings[layoutIdx] ?? undefined) : undefined; - - const contourSets: ContourSet[] = []; - if (contours.length > 0) { - contourSets.push({ - id: nextId("contours", idPrefix), - type: "contourSet", - name: `${fmt}-Konturen`, - categoryCode: GENERIC_IMPORT_CATEGORY.code, - contours, - }); - } - return { - meshes, - contours: contourSets, - texts, - layerColors, - diagnostics: { entityCounts, total }, - insUnits, - unitScale, - layouts, - layout, - recovered, - }; -} diff --git a/src/io/dxfParser.worker.ts b/src/io/dxfParser.worker.ts index cca88e04..6b1eb0a1 100644 --- a/src/io/dxfParser.worker.ts +++ b/src/io/dxfParser.worker.ts @@ -9,8 +9,8 @@ // → { type: "split", data: ArrayBuffer, chunkCount: number } // ← { type: "splitOffsets", offsets: number[] } | { type: "error", message } // -// Zurück geht der flache Puffer (übertragen, nicht kopiert); `dxfParser.ts::decodeImport` baut -// daraus im Haupt-Thread das `DxfImportResult`. `"split"` sucht die sicheren Schnittstellen einer +// Zurück geht der flache Puffer (übertragen, nicht kopiert); im Haupt-Thread liest ihn der Kern +// (Zusammenfassung für den Dialog, beim Bestätigen die Ops, `io/importSource.ts`). `"split"` sucht die sicheren Schnittstellen einer // grossen ASCII-DXF (Rust `split.rs`) — der Scan allein dauert bei 400 MB spürbar und gehört // daher ebenfalls in einen Worker. diff --git a/src/io/dxfParserAsync.ts b/src/io/dxfParserAsync.ts index fe7b880e..217f41ee 100644 --- a/src/io/dxfParserAsync.ts +++ b/src/io/dxfParserAsync.ts @@ -4,16 +4,15 @@ // Grosse ASCII-DXF werden zusätzlich PARALLEL gelesen (Nutzer-Report 09.10.): ein Split-Worker // sucht sichere Schnittstellen in der ENTITIES-Sektion (Rust `split.rs`), jedes Stück // (Präambel + Entities + Abschluss) läuft in einem eigenen Worker, danach werden die Teilergebnisse -// zusammengeführt. Schlägt Aufteilung oder ein Stück fehl, wird die ganze Datei einmal am Stück +// im Kern zusammengeführt. Schlägt Aufteilung oder ein Stück fehl, wird die ganze Datei einmal am Stück // gelesen — Korrektheit (amtliche Vermessungsdaten!) vor Geschwindigkeit. Binär-DXF und DWG werden // nicht geteilt. // // Ohne `Worker` (Node: CLI, Tests) wird direkt im aufrufenden Thread gelesen. -import type { ContourSet, ImportedMesh, ImportedText } from "../model/types"; import { loadFileio } from "../engine/fileioWasm"; -import { decodeImport, parseDxf } from "./dxfParser"; -import type { DxfImportResult, ImportDiagnostics } from "./dxfParser"; +import { parseDxf } from "./dxfParser"; +import { parsedImport, type ImportChunk, type ParsedImport } from "./importSource"; import type { DxfWorkerRequest, DxfWorkerResponse } from "./dxfParser.worker"; /** @@ -43,47 +42,12 @@ function runWorker(req: DxfWorkerRequest, transfer: Transferable[] = []): Promis }); } -async function runParseWorker( - data: ArrayBuffer, - idPrefix: string, - transfer: boolean, - layout?: string, -): Promise { +async function runParseWorker(data: ArrayBuffer, transfer: boolean, layout?: string): Promise { const res = await runWorker({ type: "parse", data, layout }, transfer ? [data] : []); - if (res.type === "result") return decodeImport(res.geom, res.strings, idPrefix); + if (res.type === "result") return { geom: res.geom, strings: res.strings }; throw new Error(res.type === "error" ? res.message : "Unerwartete Worker-Antwort"); } -/** Führt die Teilergebnisse mehrerer Stücke zusammen. */ -function mergeResults(results: DxfImportResult[]): DxfImportResult { - const meshes: ImportedMesh[] = []; - const contours: ContourSet[] = []; - const texts: ImportedText[] = []; - const layerColors: Record = {}; - const diagnostics: ImportDiagnostics = { entityCounts: {}, total: 0 }; - for (const r of results) { - for (const m of r.meshes) meshes.push(m); - for (const c of r.contours) contours.push(c); - for (const t of r.texts ?? []) texts.push(t); - // Jedes Stück trägt dieselbe Präambel (inkl. LAYER-Tabelle) — Vereinigung reicht. - Object.assign(layerColors, r.layerColors); - for (const [k, n] of Object.entries(r.diagnostics?.entityCounts ?? {})) { - diagnostics.entityCounts[k] = (diagnostics.entityCounts[k] ?? 0) + n; - } - diagnostics.total += r.diagnostics?.total ?? 0; - } - return { - meshes, - contours, - texts, - layerColors, - diagnostics, - insUnits: results[0]?.insUnits, - unitScale: results[0]?.unitScale, - layouts: results[0]?.layouts, - }; -} - function toArrayBuffer(data: string | ArrayBuffer): ArrayBuffer { if (typeof data !== "string") return data; const bytes = new TextEncoder().encode(data); @@ -114,10 +78,10 @@ export async function parseDxfAsync( data: string | ArrayBuffer, onProgress?: (phase: string) => void, layout?: string, -): Promise { +): Promise { if (typeof Worker === "undefined") { await loadFileio(); - return parseDxf(data, "", layout); + return parseDxf(data, layout); } const buf = toArrayBuffer(data); const chunkCount = Math.min( @@ -141,12 +105,12 @@ export async function parseDxfAsync( const chunks = buildChunks(new Uint8Array(buf), offsets); try { onProgress?.(`parse-parallel:${chunks.length}`); - const results = await Promise.all(chunks.map((c, i) => runParseWorker(c, `c${i}-`, true))); - return mergeResults(results); + // Die Stücke führt der Kern zusammen (`import_drawing::merge`). + return parsedImport(await Promise.all(chunks.map((c) => runParseWorker(c, true)))); } catch { // Ein Stück ist fehlgeschlagen → einmal am Stück lesen (garantiert korrekt). } } onProgress?.("parse-single"); - return runParseWorker(buf, "", false, layout); + return parsedImport([await runParseWorker(buf, false, layout)]); } diff --git a/src/io/dxfToDrawings.test.ts b/src/io/dxfToDrawings.test.ts deleted file mode 100644 index ec4c7e51..00000000 --- a/src/io/dxfToDrawings.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { describe, it, expect } from "vitest"; -import type { LayerCategory } from "../model/types"; -import { planImportCategories } from "./dxfToDrawings"; - -const cat = (code: string, name: string, children?: LayerCategory[]): LayerCategory => ({ - code, - name, - color: "#000000", - lw: 0.18, - visible: true, - locked: false, - children, -}); - -describe("planImportCategories", () => { - it("legt fehlende Layer als Unterkategorien EINER neuen Elternkategorie an", () => { - const existing = [cat("20", "Wände"), cat("90", "Referenzen")]; - const { parent, codeByLayer } = planImportCategories( - ["01421", "01422"], - existing, - "Import Luzern", - { "01421": "#ff0000" }, - ); - expect(parent?.name).toBe("Import Luzern"); - expect(parent?.children?.map((c) => c.name)).toEqual(["01421", "01422"]); - expect(parent?.children?.[0].color).toBe("#ff0000"); - // Codes laufen hinter dem grössten bestehenden weiter und sind eindeutig. - const codes = [parent!.code, ...parent!.children!.map((c) => c.code)]; - expect(new Set(codes).size).toBe(3); - expect(codes.every((c) => parseInt(c, 10) > 90)).toBe(true); - expect(codeByLayer.get("01421")).toBe(parent!.children![0].code); - }); - - it("nutzt bestehende gleichnamige Kategorien (case-insensitiv, auch verschachtelt)", () => { - const existing = [cat("05", "Kontext", [cat("10", "Situation")])]; - const { parent, codeByLayer } = planImportCategories(["SITUATION"], existing, "Import"); - expect(parent).toBeNull(); - expect(codeByLayer.get("SITUATION")).toBe("10"); - }); - - it("teilt sich eine Kategorie bei Layern, die sich nur in der Schreibweise unterscheiden", () => { - const { parent, codeByLayer } = planImportCategories(["Gebaeude", "GEBAEUDE"], [], "Import"); - expect(parent?.children).toHaveLength(1); - expect(codeByLayer.get("Gebaeude")).toBe(codeByLayer.get("GEBAEUDE")); - }); - - it("legt nichts an, wenn keine Layer vorhanden sind", () => { - expect(planImportCategories([], [cat("20", "Wände")], "Import").parent).toBeNull(); - }); -}); diff --git a/src/io/dxfToDrawings.ts b/src/io/dxfToDrawings.ts deleted file mode 100644 index 18f48b6b..00000000 --- a/src/io/dxfToDrawings.ts +++ /dev/null @@ -1,198 +0,0 @@ -// DXF-Konturen → semantische 2D-Zeichengeometrie (Drawing2D). -// -// Der DXF-Parser liefert „dumme" Konturen (Vec2 + Z + optionaler Layer-Name). -// Beim Import in eine ZEICHNUNGSEBENE werden daraus echte Drawing2D-Elemente -// (line/polyline). Die Z-Höhe der Kontur wird in 2D bewusst IGNORIERT (eine -// Zeichnungsebene ist flach). Das `closed`-Flag steuert line vs. polyline: -// • genau zwei Punkte, nicht geschlossen → `line`. -// • sonst → `polyline` (mit `closed`-Flag). -// -// Kategorie-Zuordnung (categoryMode): -// • "active" — alles bekommt die aktive Kategorie (activeCategoryCode). -// • "byLayer" — der DXF-Layer-Name wird auf einen Kategorie-Code gemappt. -// `layerToCode` liefert (deterministisch) einen Code je -// Layer-Name; unbekannte/leere Layer fallen auf `fallbackCode`. -// -// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). - -import type { Contour, ContourSet, Drawing2D, Drawing2DGeom, ImportedText, LayerCategory } from "../model/types"; -import type { ImportContour } from "./dxfParser"; -import { planImportLayers } from "../model/layers"; - -/** Wie DXF-Layer auf Kategorien abgebildet werden. */ -export type CategoryMode = "active" | "byLayer"; - -let drawingSeq = 0; -const nextId = (): string => `dxf2d-${Date.now()}-${drawingSeq++}`; - -/** Default-Füllfarbe für aus HATCH importierte Flächen (neutral, restylebar). */ -const DXF_HATCH_FILL = "#c8c8c8"; - -/** - * Wandelt einen Satz Konturen-Sätze in Drawing2D-Elemente für die Ziel-Ebene - * `levelId` um. Bei `categoryMode === "byLayer"` liefert `layerToCode` den - * Kategorie-Code je DXF-Layer-Name; sonst bekommt alles `fallbackCode`. - */ -export function contoursToDrawings( - sets: ContourSet[], - levelId: string, - categoryMode: CategoryMode, - fallbackCode: string, - layerToCode: (layerName: string) => string, - fillColorOf?: (layerName: string) => string | undefined, - /** Linienstil-Id je Layer (PDF-Strichmuster [76]); `undefined` = Kategorie-Default. */ - lineStyleOf?: (layerName: string) => string | undefined, -): Drawing2D[] { - const out: Drawing2D[] = []; - for (const set of sets) { - for (const contour of set.contours) { - const geom = contourGeom(contour); - if (!geom) continue; - const layerName = contour.layer ?? set.layer ?? ""; - const categoryCode = - categoryMode === "byLayer" && layerName - ? layerToCode(layerName) - : fallbackCode; - const drawing: Drawing2D = { - id: nextId(), - type: "drawing2d", - levelId, - categoryCode, - geom, - }; - const lineStyleId = lineStyleOf?.(layerName); - if (lineStyleId) drawing.lineStyleId = lineStyleId; - // Aus einer HATCH stammende Kontur → geschlossene, gefüllte Form. Vollton- - // Füllung als restylebarer Default (neutrales Grau); Umriss bleibt Kategorie. - if (contour.filled && geom.shape === "polyline") { - drawing.fillColor = fillColorOf?.(layerName) ?? DXF_HATCH_FILL; - } - out.push(drawing); - } - } - return out; -} - -/** - * Wandelt importierte Texte in Drawing2D-`text`-Elemente um — analog - * `contoursToDrawings` (gleiche Layer→Kategorie-Zuordnung). Winkel/Höhe kommen - * 1:1 aus `ImportedText` (Höhe in Modell-Metern, Winkel in Radiant). - */ -export function textsToDrawings( - texts: ImportedText[], - levelId: string, - categoryMode: CategoryMode, - fallbackCode: string, - layerToCode: (layerName: string) => string, -): Drawing2D[] { - const out: Drawing2D[] = []; - for (const it of texts) { - const layerName = it.layer ?? ""; - const categoryCode = - categoryMode === "byLayer" && layerName ? layerToCode(layerName) : fallbackCode; - out.push({ - id: nextId(), - type: "drawing2d", - levelId, - categoryCode, - geom: { - shape: "text", - at: { ...it.at }, - text: it.text, - height: it.height, - angle: it.angle, - }, - }); - } - return out; -} - -/** Eine Kontur → 2D-Geometrie (line bei 2 offenen Punkten, sonst polyline). */ -function contourGeom(contour: Contour): Drawing2DGeom | null { - // Echte Kurve (CIRCLE/ARC) → GLATTE Kreis-/Bogen-Form statt tesselliertem Vieleck. - const c = contour.curve; - if (c) { - if (c.kind === "circle") { - return { shape: "circle", center: { x: c.cx, y: c.cy }, r: c.r }; - } - return { shape: "arc", center: { x: c.cx, y: c.cy }, r: c.r, a0: c.a0, a1: c.a1 }; - } - // Polylinie mit Bögen (DXF-Bulges): Stützpunkte + `bulge` statt des tessellierten Linienzugs. - // VORZEICHEN: In DXF heisst Bulge > 0 „Bogen im Gegenuhrzeigersinn von a nach b" (Scheitel rechts - // der Sehne), im Modell liegt der Scheitel bei Bulge > 0 LINKS der Sehne (`kernel2d/src/bulge.rs`, - // Links-Normale) — also umgekehrt. Geprüft in `dxfBulgeImport.test.ts` gegen die Tessellierung des - // Imports. - const bp = (contour as ImportContour).bulgePolyline; - if (bp && bp.pts.length >= 2 && bp.bulge.length === bp.pts.length) { - return { - shape: "polyline", - pts: bp.pts.map((p) => ({ ...p })), - closed: contour.closed, - bulge: bp.bulge.map((b) => (b === 0 ? 0 : -b)), - }; - } - const pts = contour.pts; - if (pts.length < 2) return null; - if (pts.length === 2 && !contour.closed) { - return { shape: "line", a: { ...pts[0] }, b: { ...pts[1] } }; - } - return { - shape: "polyline", - pts: pts.map((p) => ({ ...p })), - closed: contour.closed, - }; -} - -/** - * Kategorien für DXF-Layer, die im Projekt noch KEINE gleichnamige Kategorie - * haben (Namensvergleich case-insensitiv, über den ganzen Baum). Sie werden als - * Unterkategorien EINER neuen Elternkategorie `parentName` angelegt, damit ein - * Import mit Dutzenden Layern (amtliche Vermessung) das Ebenen-Panel nicht flutet. - * Codes: fortlaufend ab dem grössten bestehenden numerischen Code (wie - * `nextFreeCode`). Liefert die neue Elternkategorie (oder null, wenn alle Layer - * schon existieren) und das Mapping Layer-Name → Code für ALLE Layer. - */ -export function planImportCategories( - layerNames: readonly string[], - existing: readonly LayerCategory[], - parentName: string, - layerColors: Readonly> = {}, - layerLineWeights: Readonly> = {}, -): { parent: LayerCategory | null; codeByLayer: Map } { - const { children, parentCode, codeByLayer } = planImportLayers(layerNames, existing, layerColors, layerLineWeights); - if (children.length === 0) return { parent: null, codeByLayer }; - const parent: LayerCategory = { - code: parentCode, - name: parentName, - color: "#707078", - lw: 0.18, - visible: true, - locked: false, - children, - }; - return { parent, codeByLayer }; -} - -/** Liste der unterschiedlichen DXF-Layer-Namen über alle Konturen-Sätze. */ -export function distinctLayers(sets: ContourSet[]): string[] { - const seen = new Set(); - for (const set of sets) { - for (const contour of set.contours) { - const name = contour.layer ?? set.layer ?? ""; - if (name) seen.add(name); - } - } - return [...seen]; -} - -/** Wie {@link distinctLayers}, aber über Konturen UND Texte (beide tragen einen Layer). */ -export function distinctImportLayers(sets: ContourSet[], texts: readonly ImportedText[]): string[] { - const seen = new Set(distinctLayers(sets)); - for (const it of texts) if (it.layer) seen.add(it.layer); - return [...seen]; -} - -/** Gesamtzahl der Konturen über alle Sätze (für die Datei-Zusammenfassung). */ -export function countContours(sets: ContourSet[]): number { - return sets.reduce((sum, s) => sum + s.contours.length, 0); -} diff --git a/src/io/ifcElements.ts b/src/io/ifcElements.ts deleted file mode 100644 index 3c6f5a4d..00000000 --- a/src/io/ifcElements.ts +++ /dev/null @@ -1,610 +0,0 @@ -// 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 — das Ergebnis sind Ops ([K4] S3), die der -// Aufrufer übernimmt (App: Store `applyChange`, ein Undo-Schritt; CLI: `applyOps`). - -import { ensureContextCategories } from "../model/contextCategories"; -import { applyOps } from "../core/ops"; -import type { CoreOp } from "../core/ops"; -import { addItems, fieldOps } from "../core/opsBuild"; -import type { EntityOf } from "../core/opsBuild"; -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 IfcClassificationRef, - 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[]; - /** Klassifikationen des Bauteils bzw. seines Typs (eBKP-H, BKP …); fehlt in älteren Rohdaten. */ - classifications?: IfcClassificationRef[]; -} - -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; - /** Ausführung: IfcDoorTypeOperationEnum bzw. IfcWindowTypePartitioningEnum (Bauteil, sonst Typ). */ - operation: string | null; - /** Tür: Aufschlag links (+1) / rechts (−1) der Wandachse, 0 = unbekannt (Rust `ifc_semantic`). */ - swing: number; - /** Tür: Scharnier am Wandanfang (+1) / -ende (−1), 0 = unbekannt. */ - hinge: 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; -} - -interface RawElement extends IfcInfo { - kind: "wall" | "opening" | "slab" | "column" | "space"; - at: number; - n: number; - host?: number; - openingKind?: "door" | "window" | "hole"; - operation?: string | null; - 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 } }; - 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(); - 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 ?? [], - ...(e.classifications?.length ? { classifications: e.classifications } : {}), - }; - 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 === 6) { - out.openings.push({ - ...info, - host, - kind: e.openingKind ?? "hole", - position: v[0], - width: v[1], - sill: v[2], - height: v[3], - operation: e.operation ?? null, - swing: Math.sign(v[4]), - hinge: Math.sign(v[5]), - }); - } - 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; - /** - * Übernommene Bauteile und Meshes mit Klassifikation (eBKP-H …). Das Modell hat an Wand/Decke/Stütze/ - * Raum kein Klassifikationsfeld: nur die Namen der Kontext-Meshes tragen sie (`[eBKP-H C]`), sonst wird - * sie gezählt und gemeldet. - */ - classified: 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: `ops` (für den Store), - * `project` = `applyOps(project, ops)` (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, -): { ops: CoreOp[]; 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, classified: 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(); - 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 op = o.operation ?? ""; - // Tür: Typ nach Art (Dreh/Schiebe) und Blattzahl aus der Ausführung, sonst der erste Typ. - const sliding = op.includes("SLIDING"); - const leaves = op.startsWith("DOUBLE_DOOR") ? 2 : 1; - const doorType = - (op ? project.doorTypes?.find((t) => t.kind === (sliding ? "schiebe" : "dreh") && t.leafCount === leaves) : undefined) ?? - project.doorTypes?.[0]; - // Fenster: Flügelzahl aus der Teilung (nur senkrechte Standardfälle); Typ mit dieser Flügelzahl, sonst - // der erste Typ mit eigener Flügelzahl an der Öffnung. - const wings = ({ SINGLE_PANEL: 1, DOUBLE_PANEL_VERTICAL: 2, TRIPLE_PANEL_VERTICAL: 3 } as Record)[op]; - const windowType = (wings ? project.windowTypes?.find((t) => t.wingCount === wings) : undefined) ?? project.windowTypes?.[0]; - const typeId = o.kind === "door" ? doorType?.id : o.kind === "window" ? windowType?.id : undefined; - const doorExtra = - o.kind === "door" - ? { - ...(o.hinge !== 0 ? { hinge: o.hinge > 0 ? ("start" as const) : ("end" as const) } : {}), - ...(o.swing !== 0 ? { swing: o.swing > 0 ? ("left" as const) : ("right" as const) } : {}), - } - : {}; - const windowExtra = o.kind === "window" && wings && (windowType?.wingCount ?? 1) !== wings ? { wingCount: wings } : {}; - 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 } : {}), - ...doorExtra, - ...windowExtra, - }); - } - - // ── 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 withClass = (l: readonly IfcInfo[]) => l.filter((e) => e.classifications?.length).length; - summary.classified = - withClass(elements.walls) + withClass(elements.openings.filter((o) => o.kind !== "hole")) + withClass(elements.slabs) + withClass(elements.columns) + withClass(elements.spaces) + - products.filter((p) => p.classifications?.length).length; - - // Fehlende Listen werden (wie früher beim Ersetzen des Projekts) leer angelegt. - const list = (key: K, items: EntityOf[]): CoreOp[] => - project[key] ? addItems(key, items) : fieldOps(project, key, items as Project[K]); - const ops: CoreOp[] = [ - ...fieldOps(project, "drawingLevels", levels), - ...fieldOps(project, "components", components), - ...fieldOps(project, "wallTypes", wallTypes), - ...(ceilingTypes.length || project.ceilingTypes ? fieldOps(project, "ceilingTypes", ceilingTypes) : []), - ...addItems("walls", walls), - ...list("openings", openings), - ...list("ceilings", ceilings), - ...list("columns", columns), - ...list("rooms", rooms), - ...(meshes.length - ? [ - ...(project.context ? addItems("context", meshes) : fieldOps(project, "context", meshes)), - ...fieldOps(project, "layers", ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : [])))), - ] - : []), - ]; - return { ops, project: applyOps(project, ops), 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" | "ifc.import.classified", vars?: Record) => 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 })); - if (s.classified) parts.push(tr("ifc.import.classified", { n: s.classified })); - return parts.join(" · "); -} diff --git a/src/io/ifcElements.test.ts b/src/io/ifcImport.elements.test.ts similarity index 84% rename from src/io/ifcElements.test.ts rename to src/io/ifcImport.elements.test.ts index ae2d13b3..4167ef15 100644 --- a/src/io/ifcElements.test.ts +++ b/src/io/ifcImport.elements.test.ts @@ -1,4 +1,4 @@ -// IFC-Import zu echten Bauteilen ([B4]): Rundreise eigener Export → Import als Bauteile → gleiche +// IFC-Import zu echten Bauteilen ([B4], Umwandlung im Kern `import_ifc.rs`): 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. @@ -12,8 +12,8 @@ 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 { formatIfcElementsSummary, type IfcElementsSummary } from "./ifcImport"; +import { importIfcInto } from "./importView.testutil"; import { parseProjectFile, serializeProject } from "./projectFormat"; const bytesOf = (s: string) => new TextEncoder().encode(s); @@ -24,9 +24,8 @@ const symmetric = (p: Project, wallTypeId: string) => { }; 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 }; + const r = await importIfcInto(base, bytesOf(exportIfcSpf(src)), { elements: true }); + return { ...r, summary: r.summary as IfcElementsSummary }; } describe("IFC-Import als Bauteile: Rundreise Demo-Haus", () => { @@ -178,32 +177,11 @@ describe("IFC-Import als Bauteile: Rundreise Demo-Haus", () => { }); 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(); - }); - + // Benennung, Farbe (#rrggbb, gemeinsame Farbe beim Zusammenlegen) und GlobalId prüft der Kern-Test + // `import_drawing_tests.rs::ifc_meshes_farbe_und_globalid`; hier die Rundreise aus einer Datei. 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"); + const { meshes } = await importIfcInto(emptyProject, new Uint8Array(readFileSync(new URL("./testdata/ifc-geometry-cases.ifc", import.meta.url))), { fileName: "cases.ifc" }); + expect(meshes.length).toBeGreaterThan(0); expect(meshes.every((m) => m.ifcGlobalId && !m.name.includes("["))).toBe(true); const withColor = { ...meshes[0], color: "#336699" }; const proj: Project = { ...emptyProject, context: [withColor] }; @@ -228,8 +206,7 @@ describe.skipIf(!samples || !existsSync(samples))("IFC-Import als Bauteile: Beis 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 }); + const { project, summary } = await importIfcInto(emptyProject, new Uint8Array(readFileSync(f)), { fileName: f, elements: true }); expect(validateProject(project), f).toEqual([]); rows.push(`${f.slice(samples!.length + 1)}: ${JSON.stringify(summary)}`); } diff --git a/src/io/ifcImport.test.ts b/src/io/ifcImport.test.ts index 16a8cab3..e01f1426 100644 --- a/src/io/ifcImport.test.ts +++ b/src/io/ifcImport.test.ts @@ -17,7 +17,9 @@ import { sampleProject } from "../model/sampleProject"; import { verticalExtents } from "../geometry/grips"; import { polygonArea } from "../geometry/roomArea"; import { wallMeshVolumes } from "../export/meshScene.testutil"; -import { formatIfcReport, handleIfcWorkerRequest, ifcToImportedMeshes, readIfc, type IfcProduct, type IfcWorkerRequest } from "./ifcImport"; +import { formatIfcReport, handleIfcWorkerRequest, type IfcWorkerRequest } from "./ifcImport"; +import { importIfcInto, inspectIfc, type IfcProductView as IfcProduct } from "./importView.testutil"; +import type { Project } from "../model/types"; function volume(pos: ArrayLike, idx: ArrayLike): number { let v = 0; @@ -52,7 +54,7 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => { const ifc = exportIfcSpf(sampleProject); it("gleiche Bauteilzahl je Klasse, Räume ausgelassen", async () => { - const { products, report } = await readIfc(bytesOf(ifc)); + const { products, report } = await inspectIfc(bytesOf(ifc)); expect(report.schema).toBe("IFC4"); expect(report.parseErrors).toBe(0); expect(report.productsWithoutGeometry).toBe(0); @@ -72,7 +74,7 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => { }); it("Volumen je Wand = Volumen der Wand-Netze, je Decke = Fläche × Dicke", async () => { - const { products, report } = await readIfc(bytesOf(ifc)); + const { products, report } = await inspectIfc(bytesOf(ifc)); // Wände: dieselben Ausschnitt-Netze wie der Export (Bänder je Wand). [B5] schreibt einfache Wände als // ungeschnittene Extrusion + IfcOpeningElement, der Import zieht die Öffnungen ab ([B3]) → bei allen // Wänden das ausgeschnittene Volumen. @@ -110,42 +112,34 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => { }); it("Kontext-Meshes: je Bauteil, Klasse als Ebene; Rückschub auf den Modell-Nullpunkt bei Georeferenz", async () => { - const { products, report } = await readIfc(bytesOf(ifc)); - const meshes = ifcToImportedMeshes(products, "haus.ifc"); + const { products, report } = await inspectIfc(bytesOf(ifc)); + const meshes = (await importIfcInto(sampleProject, bytesOf(ifc))).meshes; expect(meshes.length).toBe(products.length); expect(new Set(meshes.map((m) => m.id)).size).toBe(meshes.length); expect(meshes.every((m) => m.type === "importedMesh" && m.positions.length >= 9 && m.indices.length >= 3)).toBe(true); expect(meshes.find((m) => m.layer === "IfcWall")).toBeTruthy(); - const grouped = ifcToImportedMeshes(products, "haus.ifc", { group: "class" }); + const grouped = (await importIfcInto(sampleProject, bytesOf(ifc), { group: "class" })).meshes; expect(grouped.length).toBeLessThan(meshes.length); expect(grouped.reduce((s, m) => s + m.indices.length, 0)).toBe(meshes.reduce((s, m) => s + m.indices.length, 0)); // Datei in LV95 (Export mit Standort-Bezug) → zurück auf die lokalen Koordinaten. - const origin = { e: 2_600_000, n: 1_200_000 }; - const shifted = products.map((p) => { - const pos = new Float64Array(p.positions); - for (let i = 0; i < pos.length; i += 3) { - pos[i] += origin.e; - pos[i + 1] += origin.n; - } - return { ...p, positions: pos }; - }); - const back = ifcToImportedMeshes(shifted, "haus.ifc", { geoOrigin: origin }); + const geo: Project = { ...sampleProject, geoAnchor: { lv95: { e: 2_600_000, n: 1_200_000 }, model: { x: 0, y: 0 } } }; + const back = (await importIfcInto(geo, bytesOf(exportIfcSpf(geo)))).meshes; expect(back[0].positions[0]).toBeCloseTo(meshes[0].positions[0], 6); // Ohne Bezug in der Datei (lokal) bleibt alles, auch wenn das Projekt einen hat. - const local = ifcToImportedMeshes(products, "haus.ifc", { geoOrigin: origin }); + const local = (await importIfcInto(geo, bytesOf(ifc))).meshes; expect(local[0].positions[0]).toBeCloseTo(meshes[0].positions[0], 9); const text = formatIfcReport(report, (k, v) => `${k}${JSON.stringify(v ?? {})}`); expect(text).toContain("ifc.import.done"); }); it("Unsinn ergibt einen Fehler, keinen Absturz des Moduls", async () => { - await expect(readIfc(new Uint8Array())).rejects.toBeTruthy(); - await expect(readIfc(bytesOf("kein IFC"))).rejects.toBeTruthy(); + await expect(inspectIfc(new Uint8Array())).rejects.toBeTruthy(); + await expect(inspectIfc(bytesOf("kein IFC"))).rejects.toBeTruthy(); const broken = ifc.slice(0, Math.floor(ifc.length / 2)); - const r = await readIfc(bytesOf(broken)); + const r = await inspectIfc(bytesOf(broken)); expect(r.products.length).toBeGreaterThanOrEqual(0); // Modul lebt noch. - expect((await readIfc(bytesOf(ifc))).products.length).toBeGreaterThan(0); + expect((await inspectIfc(bytesOf(ifc))).products.length).toBeGreaterThan(0); }); }); @@ -160,7 +154,7 @@ const freeformFile = new URL("./testdata/ifc-freeform-cases.ifc", import.meta.ur describe("IFC-Import: Öffnungen, Boolesche Körper, Rotation, Sweeps", () => { it("alle Fälle gelesen, Volumen von Hand", async () => { - const { products, report } = await readIfc(new Uint8Array(readFileSync(casesFile))); + const { products, report } = await inspectIfc(new Uint8Array(readFileSync(casesFile))); expect(report.skippedItems).toEqual({}); expect(report.simplifiedBooleans).toBe(0); expect(report.voidsApplied).toBe(2); @@ -193,7 +187,7 @@ describe("IFC-Import: Öffnungen, Boolesche Körper, Rotation, Sweeps", () => { }); it("Freiform-Fälle: alle gelesen, Volumen von Hand", async () => { - const { products, report } = await readIfc(new Uint8Array(readFileSync(freeformFile))); + const { products, report } = await inspectIfc(new Uint8Array(readFileSync(freeformFile))); expect(report.skippedItems).toEqual({}); const pi = Math.PI; const want: Array<[string, number]> = [ @@ -236,12 +230,12 @@ describe("IFC-Import: Öffnungen, Boolesche Körper, Rotation, Sweeps", () => { vi.stubGlobal("Worker", FakeWorker); const bytes = new Uint8Array(readFileSync(casesFile)); const before = FakeWorker.started; - const { products, report } = await readIfc(bytes); + const { products, report } = await inspectIfc(bytes); expect(FakeWorker.started).toBe(before + 1); expect(products.length).toBe(15); expect(report.voidsApplied).toBe(2); expect(bytes.byteLength).toBeGreaterThan(0); - await expect(readIfc(bytesOf("kein IFC"))).rejects.toThrow(); + await expect(inspectIfc(bytesOf("kein IFC"))).rejects.toThrow(); const bad = await handleIfcWorkerRequest({ type: "nonsense" } as unknown as IfcWorkerRequest); expect(bad.res.type).toBe("error"); }); @@ -257,7 +251,7 @@ describe("IFC-Import: Öffnungen, Boolesche Körper, Rotation, Sweeps", () => { terminate() {} }, ); - const { products } = await readIfc(new Uint8Array(readFileSync(casesFile))); + const { products } = await inspectIfc(new Uint8Array(readFileSync(casesFile))); expect(products.length).toBe(15); }); }); @@ -280,7 +274,7 @@ function ifcopenshellProducts(file: string): Record { /** Vergleich je GlobalId; liefert Abweichungen als Text (leer = gleich). */ async function compare(file: string, rel: (p: IfcProduct) => number): Promise { const ref = ifcopenshellProducts(file); - const { products, report } = await readIfc(new Uint8Array(readFileSync(file))); + const { products, report } = await inspectIfc(new Uint8Array(readFileSync(file))); // ifcopenshell 0.9 liefert bei manchen Dateien in mm (z. B. buildingSMART // „wall-with-opening-and-window.ifc", IfcSIUnit MILLI) die Geometrie unskaliert in Dateieinheiten, // obwohl `convert-back-units` aus ist; unser Import rechnet dort richtig in m (Rust-Test mit mm). diff --git a/src/io/ifcImport.ts b/src/io/ifcImport.ts index c571bce8..b82b3eb6 100644 --- a/src/io/ifcImport.ts +++ b/src/io/ifcImport.ts @@ -1,25 +1,18 @@ -// 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 …) baut auf Wunsch -// `ifcElements.ts` ([B4]) aus `import_ifc_elements`. -// -// 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. +// IFC-Import ([B3] Kontext-Meshes, [B4] Bauteile): dünne Fassade über `import_ifc`/`import_ifc_elements` im +// Format-Modul (`src-tauri/fileio`, `ifc_import.rs`, `ifc_semantic.rs`). Die Umwandlung ins Projekt — je +// Bauteil ein `ImportedMesh` der Kontext-Schicht (GlobalId, Farbe, Klasse als `layer`; ab `MAX_SINGLE` +// Bauteilen je Klasse + Geschoss zusammengelegt) bzw. echte Wände, Öffnungen, Decken, Stützen, Räume — macht +// der Kern als EIN Undo-Schritt (`core/src/import_ifc.rs`, `ProjectDocument.importIfc`, [K4] S4). // // Lesen im Web-Worker (`ifcImport.worker.ts`), damit grosse Dateien die UI nicht blockieren: zurück // kommen nur der JSON-Bericht und zwei flache Puffer (übertragen, nicht kopiert). Ohne `Worker` (Node: // CLI, Tests) oder wenn der Worker nicht startet, wird im aufrufenden Thread gelesen. // // Koordinaten: Meter, Z = Höhe, unverändert aus der Datei — ausser die Datei liegt in -// Landeskoordinaten und das Projekt hat einen Standort-Bezug: dann wird auf den Modell-Nullpunkt -// zurückgeschoben (Gegenstück zu `projectToWorldCoords` beim Export). +// Landeskoordinaten und das Projekt hat einen Standort-Bezug: dann schiebt der Kern auf den Modell-Nullpunkt +// zurück (Gegenstück zu `projectToWorldCoords` beim Export). import { loadFileio } from "../engine/fileioWasm"; -import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories"; -import type { ImportedMesh } from "../model/types"; -import { rgbToHex } from "../model/color"; /** Klassifikation eines Bauteils (IfcClassificationReference), z. B. eBKP-H `C`. */ export interface IfcClassificationRef { @@ -29,22 +22,6 @@ export interface IfcClassificationRef { name: string | null; } -/** Ein gelesenes IFC-Bauteil. */ -export interface IfcProduct { - globalId: string; - /** IFC-Klasse, z. B. `IfcWall`. */ - ifcClass: string; - name: string | null; - storey: string | null; - /** RGBA 0..1 aus IfcStyledItem/Material, falls vorhanden. */ - color: [number, number, number, number] | null; - /** Klassifikationen (eBKP-H, BKP …); fehlt bei Quellen ohne. */ - classifications?: IfcClassificationRef[]; - /** x,y,z in Metern (Z = Höhe). */ - positions: Float64Array; - indices: Uint32Array; -} - /** Bericht des Imports: was gelesen, was übersprungen wurde. */ export interface IfcImportReport { schema: string; @@ -64,19 +41,8 @@ export interface IfcImportReport { truncated: boolean; } -interface RawProduct { - globalId: string; - ifcClass: string; - name: string | null; - storey: string | null; - color: [number, number, number, number] | null; - classifications?: IfcClassificationRef[]; - positionCount: number; - indexCount: number; -} - /** Rohergebnis aus Rust: Bericht (JSON) und alle Bauteile hintereinander in zwei flachen Puffern; - * mit `elements` dazu die Zahlen der erkannten Bauteile ([B4], `ifcElements.ts`). */ + * mit `elements` dazu die Zahlen der erkannten Bauteile ([B4], `core/src/import_ifc.rs`). */ export interface IfcFlat { meta: string; positions: Float64Array; @@ -141,167 +107,37 @@ function readInWorker(bytes: Uint8Array, elements: boolean): Promise & { products: RawProduct[] }; - let po = 0; - let io = 0; - const products: IfcProduct[] = []; - for (const p of meta.products) { - products.push({ - globalId: p.globalId, - ifcClass: p.ifcClass, - name: p.name, - storey: p.storey, - color: p.color, - ...(p.classifications?.length ? { classifications: p.classifications } : {}), - positions: flat.positions.subarray(po, po + p.positionCount), - indices: flat.indices.subarray(io, io + p.indexCount), - }); - po += p.positionCount; - io += p.indexCount; - } - return { products, report: { ...meta, products: products.length } }; -} - -/** 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 }> { - 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 { 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 }); +/** Was der Bauteil-Import übernommen hat (`import_ifc.rs`, 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; + /** Übernommene Bauteile und Meshes mit Klassifikation (eBKP-H …; nur Mesh-Namen tragen sie). */ + classified: number; + /** Davon Kandidaten, die nicht sicher abbildbar waren. */ + kept: number; } -/** Ab so vielen Bauteilen wird je Klasse + Geschoss zusammengelegt. */ -export const MAX_SINGLE = 2000; - -export interface IfcToMeshesOptions { - /** LV95-Ursprung des Projekts (`projectGeoOrigin`), sonst null. */ - 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; - * `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; - let n = 0; - for (const p of products) { - for (let i = 0; i + 2 < p.positions.length; i += 3 * 64) { - sx += p.positions[i]; - sy += p.positions[i + 1]; - 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; - const nearOrigin = Math.hypot(cx - origin.e, cy - origin.n) < Math.hypot(cx, cy); - return nearOrigin ? [-origin.e, -origin.n] : [0, 0]; -} - -/** - * Klassifikation als Namenszusatz des Kontext-Objekts (` [eBKP-H C]`): das Modell hat für Kontext-Meshes - * kein eigenes Klassifikationsfeld, der Name ist das einzige freie Feld (im Kontext-Panel sichtbar). - * Nur die erste Klassifikation; ohne leer. - */ -export function classificationSuffix(list: readonly IfcClassificationRef[] | undefined): string { - const c = list?.[0]; - if (!c) return ""; - return ` [${[c.system, c.code].filter(Boolean).join(" ")}]`; -} - -/** 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] = 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); - - const toArrays = (parts: IfcProduct[]): { positions: number[]; indices: number[] } => { - const positions: number[] = []; - const indices: number[] = []; - for (const p of parts) { - const off = positions.length / 3; - for (let i = 0; i + 2 < p.positions.length; i += 3) { - positions.push(p.positions[i] + dx, p.positions[i + 1] + dy, p.positions[i + 2]); - } - for (let i = 0; i < p.indices.length; i++) indices.push(p.indices[i] + off); - } - return { positions, indices }; - }; - - if (perProduct) { - 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(": ") + classificationSuffix(p.classifications), - layer: p.ifcClass, - categoryCode: GENERIC_IMPORT_CATEGORY.code, - ...(color ? { color } : {}), - ...(p.globalId ? { ifcGlobalId: p.globalId } : {}), - ...toArrays([p]), - }; - }); - } - const groups = new Map(); - for (const p of products) { - const key = `${p.ifcClass}\u0000${p.storey ?? ""}`; - const g = groups.get(key); - if (g) g.push(p); - else groups.set(key, [p]); - } - 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. */ -export async function ifcBytesToImportedMeshes( - bytes: Uint8Array, - fileName: string, - opts: IfcToMeshesOptions = {}, -): Promise<{ meshes: ImportedMesh[]; report: IfcImportReport }> { - const { products, report } = await readIfc(bytes); - return { meshes: ifcToImportedMeshes(products, fileName, opts), report }; +/** IFC-Import als Ops im Kern ([K4] S4): Antwort von `ProjectDocument.importIfc`. */ +export interface IfcImportResult { + report: IfcImportReport & { byClass: Record; triangles: number }; + summary: IfcElementsSummary | null; + kept: Record; + contextObjects: number; } /** Bericht als kurzer Text; `tr` übersetzt (Kern kennt kein i18n, die Hülle reicht `t` herein). */ @@ -320,3 +156,26 @@ export function formatIfcReport( if (r.truncated) parts.push(tr("ifc.import.truncated")); return parts.join(" · "); } + +/** 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" | "ifc.import.classified", vars?: Record) => 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 })); + if (s.classified) parts.push(tr("ifc.import.classified", { n: s.classified })); + return parts.join(" · "); +} diff --git a/src/io/ifcImport.worker.ts b/src/io/ifcImport.worker.ts index cac1844d..bfd03f67 100644 --- a/src/io/ifcImport.worker.ts +++ b/src/io/ifcImport.worker.ts @@ -1,6 +1,6 @@ // Web-Worker für den IFC-Import ([B3]): liest die Datei mit dem Format-Modul (`engine/fileioWasm.ts`) // AUSSERHALB des Haupt-Threads, damit grosse Modelle die UI nicht einfrieren. Ein Worker je Aufruf, -// danach beendet (s. `ifcImport.ts::readIfc`). +// danach beendet (s. `ifcImport.ts::readIfcFlat`). // // → { type: "parse", data: ArrayBuffer } // ← { type: "result", flat: { meta, positions, indices } } | { type: "error", message } diff --git a/src/io/importBench.test.ts b/src/io/importBench.test.ts deleted file mode 100644 index a0fcce96..00000000 --- a/src/io/importBench.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -// VORÜBERGEHEND ([K4] S4): Zeitmessung Kataster-Import alt (TS-Umwandlung + Commit) ↔ neu (Kern). -import "../engine/fileioWasm.setup"; -import { describe, it } from "vitest"; -import { existsSync, readFileSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { applyOps } from "../core/ops"; -import type { CoreOp } from "../core/ops"; -import { addItems, fieldOps } from "../core/opsBuild"; -import { ProjectDocument } from "../core/document"; -import { sampleProject } from "../model/sampleProject"; -import { flattenCategories } from "../model/types"; -import { decodeImport, importDrawingFlat } from "./dxfParser"; -import { countContours, distinctImportLayers, distinctLayers, planImportCategories } from "./dxfToDrawings"; -import { buildDrawings } from "../ui/ImportDialog"; -import { planDashLineStyles } from "./pdfLineStyles"; -import { packChunks, importSummary } from "./importSource"; -import { core } from "../engine/coreWasm"; - -const FX = process.env.DOSSIER_PARITY_FX ?? ""; -const file = join(FX, "kataster150k.dxf"); - -describe.skipIf(!existsSync(file))("Zeitmessung Kataster 150k", { timeout: 600_000 }, () => { - it("alt ↔ neu", () => { - const bytes = new Uint8Array(readFileSync(file)); - const runs = Number(process.env.BENCH_RUNS ?? 3); - for (let run = 0; run < runs; run++) { - let t0 = performance.now(); - const flat = importDrawingFlat(bytes); - const tParse = performance.now() - t0; - if (process.env.BENCH_DUMP) { - writeFileSync(join(FX, "k150.geom"), new Uint8Array(flat.geom.buffer, flat.geom.byteOffset, flat.geom.byteLength)); - writeFileSync(join(FX, "k150.strings.json"), JSON.stringify(flat.strings)); - } - // alt - t0 = performance.now(); - const parsed = decodeImport(flat.geom, flat.strings); - void [countContours(parsed.contours), distinctLayers(parsed.contours)]; - const tOldDecode = performance.now() - t0; - t0 = performance.now(); - const base = sampleProject; - const levelId = "drawing-1"; - const ops: CoreOp[] = addItems("drawingLevels", [{ id: levelId, name: "K", kind: "drawing", visible: true, locked: false }]); - let p = applyOps(base, ops); - const plan = planImportCategories(distinctImportLayers(parsed.contours, parsed.texts ?? []), flattenCategories(base.layers), "Import", parsed.layerColors, parsed.layerLineWeights); - const lops = fieldOps(p, "layers", [...p.layers, plan.parent!]); - p = applyOps(p, lops); - const dash = planDashLineStyles(parsed.layerDashes, base.lineStyles); - const drawings = buildDrawings({ target: { kind: "existing", levelId }, categoryMode: "byLayer", importMeshes: false, placement: "origin", parsed }, levelId, base, "20", plan.codeByLayer, dash.styleByLayer); - const all = [...ops, ...lops, ...addItems("drawings2d", drawings)]; - const tOldConvert = performance.now() - t0; - const docOld = new ProjectDocument(base); - t0 = performance.now(); - const rOld = docOld.commit(base, all, undefined, Date.now()); - const tOldCommit = performance.now() - t0; - if ("problems" in rOld) throw new Error(rOld.problems[0]); - docOld.close(); - // neu - t0 = performance.now(); - const src = packChunks([flat]); - const summary = importSummary(src); - const tNewSummary = performance.now() - t0; - const docNew = new ProjectDocument(base); - t0 = performance.now(); - const r = docNew.importDrawing(base, src, { target: { kind: "new", name: "K" }, categoryMode: "byLayer", activeCategoryCode: "20", importMeshes: false, parentName: "Import" }, Date.now()); - const tNewImport = performance.now() - t0; - if ("problems" in r) throw new Error(r.problems[0]); - // Aufteilung: Kern-Aufruf, JSON.parse, applyOps. - const docX = new ProjectDocument(base); - void docX.json(); - t0 = performance.now(); - const out = core().doc_import_drawing(docX.id, src.geom, JSON.stringify(src.strings), JSON.stringify(src.source), JSON.stringify({ target: { kind: "new", name: "K" }, categoryMode: "byLayer", activeCategoryCode: "20", importMeshes: false, parentName: "Import" }), "", Date.now()); - const tCore = performance.now() - t0; - t0 = performance.now(); - const parsedOut = JSON.parse(out) as { ops: CoreOp[] }; - const tParseOut = performance.now() - t0; - t0 = performance.now(); - applyOps(base, parsedOut.ops); - const tApply = performance.now() - t0; - console.log(` Kern ${tCore.toFixed(0)} ms (${(out.length / 1e6).toFixed(1)} MB JSON), JSON.parse ${tParseOut.toFixed(0)} ms, applyOps ${tApply.toFixed(0)} ms`); - docX.close(); - docNew.close(); - const f = (x: number) => x.toFixed(0).padStart(5); - console.log( - `Lauf ${run}: ${summary.contours + summary.texts} Elemente | Lesen ${f(tParse)} ms | alt: Dekodieren ${f(tOldDecode)} + Umwandeln ${f(tOldConvert)} + Commit ${f(tOldCommit)} = ${f(tOldDecode + tOldConvert + tOldCommit)} ms | neu: Zusammenfassung ${f(tNewSummary)} + Import ${f(tNewImport)} = ${f(tNewSummary + tNewImport)} ms`, - ); - } - }); -}); diff --git a/src/io/importParity.test.ts b/src/io/importParity.test.ts deleted file mode 100644 index 813a0bac..00000000 --- a/src/io/importParity.test.ts +++ /dev/null @@ -1,379 +0,0 @@ -// VORÜBERGEHEND ([K4] S4): Gleichheit alte TS-Umwandlung ↔ Kern-Import (`ProjectDocument.importDrawing/ -// importIfc/importMesh`). Gleiches Projekt (bis auf erzeugte ids), gleiche Zusammenfassung/Berichte. Wird mit -// der TS-Fassung gelöscht. Fixtures: `DOSSIER_PARITY_FX` (Verzeichnis), sonst übersprungen. - -import "../engine/fileioWasm.setup"; -import { describe, expect, it } from "vitest"; -import { existsSync, readFileSync, readdirSync } from "node:fs"; -import { join } from "node:path"; -import { applyOps } from "../core/ops"; -import type { CoreOp } from "../core/ops"; -import { addItems, fieldOps } from "../core/opsBuild"; -import { ProjectDocument } from "../core/document"; -import type { DrawingImportDecision } from "../core/document"; -import { emptyProject, sampleProject } from "../model/sampleProject"; -import type { ContextObject, ContourSet, Drawing2D, ImportedMesh, ImportedText, Project, Vec2 } from "../model/types"; -import { flattenCategories } from "../model/types"; -import { ensureContextCategories } from "../model/contextCategories"; -import { projectGeoOrigin } from "../model/geoRebase"; -import { decodeImport, importDrawingFlat, parseDxf, type DxfImportResult } from "./dxfParser"; -import { countContours, distinctImportLayers, distinctLayers, planImportCategories } from "./dxfToDrawings"; -import { buildDrawings } from "../ui/ImportDialog"; -import { planDashLineStyles } from "./pdfLineStyles"; -import { pdfPageInfo, pdfPageToImport, readPdfVectorPage } from "./pdfVector"; -import { packChunks, importSummary } from "./importSource"; -import { fileioLoaded } from "../engine/fileioWasm"; -import { t } from "../i18n"; -import { ifcElementsToProject, readIfcElements } from "./ifcElements"; -import { ifcToImportedMeshes, importIfcFlat, readIfc } from "./ifcImport"; -import { decodeMesh, importMeshFlat, meshObjectsToImportedMeshes, type MeshUnit, type MeshUp } from "./meshImport"; -import { core } from "../engine/coreWasm"; - -const FX = process.env.DOSSIER_PARITY_FX ?? ""; -const have = FX !== "" && existsSync(FX); -const fx = (n: string) => new Uint8Array(readFileSync(join(FX, n))); - -/** Erzeugte ids (Zeit + Zähler) durch Platzhalter in Reihenfolge des ersten Auftretens ersetzen. */ -function normalize(v: unknown): string { - const text = JSON.stringify(v); - const map = new Map(); - return text.replace( - /"((?:c\d+-)?imported-\d+-\d+|dxf2d-\d+-\d+|drawing-\d+|ifc-[a-z]+-[0-9a-z]+-\d+|imported-ifc-[0-9a-z]+-\d+|imported-mesh-[0-9a-z]+-\d+)"/g, - (_, id: string) => { - if (!map.has(id)) map.set(id, `#${map.size}`); - return `"${map.get(id)}"`; - }, - ); -} - -/** Schlüssel sortiert (Leseansicht ↔ Dokument: Felder mit `undefined` behalten in TS ihre Stelle). */ -function canon(v: unknown): unknown { - if (Array.isArray(v)) return v.map(canon); - if (v && typeof v === "object") return Object.fromEntries(Object.keys(v).sort().filter((k) => (v as Record)[k] !== undefined).map((k) => [k, canon((v as Record)[k])])); - return v; -} - -// ── Alte App-Fassung (`useProjectFileActions.runImportSteps`, Kopie der privaten Helfer) ───────── - -function drawingsBBox(drawings: Drawing2D[]) { - let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; - const acc = (x: number, y: number) => { - minX = Math.min(minX, x); minY = Math.min(minY, y); - maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); - }; - for (const d of drawings) { - const g = d.geom; - if (g.shape === "line") { acc(g.a.x, g.a.y); acc(g.b.x, g.b.y); } - else if (g.shape === "polyline") for (const p of g.pts) acc(p.x, p.y); - else if (g.shape === "circle" || g.shape === "arc") { acc(g.center.x - g.r, g.center.y - g.r); acc(g.center.x + g.r, g.center.y + g.r); } - else if (g.shape === "text") acc(g.at.x, g.at.y); - } - return Number.isFinite(minX) ? { minX, minY, maxX, maxY } : null; -} - -function translateDrawing(d: Drawing2D, dx: number, dy: number): Drawing2D { - const mv = (p: Vec2): Vec2 => ({ x: p.x + dx, y: p.y + dy }); - const g = d.geom; - switch (g.shape) { - case "line": return { ...d, geom: { ...g, a: mv(g.a), b: mv(g.b) } }; - case "polyline": return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; - case "circle": return { ...d, geom: { ...g, center: mv(g.center) } }; - case "arc": return { ...d, geom: { ...g, center: mv(g.center) } }; - case "text": return { ...d, geom: { ...g, at: mv(g.at) } }; - default: return d; - } -} - -interface Case { - target: DrawingImportDecision["target"]; - categoryMode: "byLayer" | "active"; - importMeshes: boolean; - viewCenter?: [number, number]; -} - -function oldApp(project: Project, parsed: DxfImportResult, c: Case, active: string, parentName: string): Project { - let p = project; - const apply = (ops: CoreOp[]) => { - p = applyOps(p, ops); - }; - let levelId: string; - if (c.target.kind === "new") { - const id = `drawing-${Date.now()}`; - const n = p.drawingLevels.filter((z) => z.kind === "drawing").length + 1; - apply(addItems("drawingLevels", [{ id, name: c.target.name.trim() || t("default.drawingName", { n }), kind: "drawing", visible: true, locked: false }])); - levelId = id; - } else levelId = c.target.levelId; - let codeByLayer: Map | undefined; - if (c.categoryMode === "byLayer") { - const plan = planImportCategories(distinctImportLayers(parsed.contours, parsed.texts ?? []), flattenCategories(project.layers), parentName, parsed.layerColors, parsed.layerLineWeights); - codeByLayer = plan.codeByLayer; - if (plan.parent) apply(fieldOps(p, "layers", [...p.layers, plan.parent])); - } - const dashPlan = planDashLineStyles(parsed.layerDashes, project.lineStyles); - if (dashPlan.created.length) apply(addItems("lineStyles", dashPlan.created.filter((x) => !p.lineStyles.some((l) => l.id === x.id)))); - let drawings = buildDrawings( - { target: c.target, categoryMode: c.categoryMode, importMeshes: c.importMeshes, placement: c.viewCenter ? "viewCenter" : "origin", parsed }, - levelId, - project, - active, - codeByLayer, - dashPlan.styleByLayer, - ); - if (c.viewCenter && drawings.length) { - const bb = drawingsBBox(drawings); - if (bb) { - const dx = c.viewCenter[0] - (bb.minX + bb.maxX) / 2; - const dy = c.viewCenter[1] - (bb.minY + bb.maxY) / 2; - drawings = drawings.map((d) => translateDrawing(d, dx, dy)); - } - } - if (drawings.length) apply(addItems("drawings2d", drawings)); - if (c.importMeshes && parsed.meshes.length) { - const added = parsed.meshes as ContextObject[]; - const codes = added.map((o) => o.categoryCode).filter((x): x is string => !!x); - apply([...addItems("context", added), ...fieldOps(p, "layers", ensureContextCategories(p.layers, codes))]); - } - return p; -} - -function oldSummary(parsed: DxfImportResult) { - const texts = parsed.texts ?? []; - return { - contours: countContours(parsed.contours), - texts: texts.length, - meshes: parsed.meshes.length, - layers: distinctLayers(parsed.contours), - diagnostics: parsed.diagnostics, - ...(parsed.insUnits !== undefined ? { insUnits: parsed.insUnits } : {}), - ...(parsed.unitScale !== undefined ? { unitScale: parsed.unitScale } : {}), - ...(parsed.layouts !== undefined ? { layouts: parsed.layouts } : {}), - ...(parsed.layout !== undefined ? { layout: parsed.layout } : {}), - recovered: parsed.recovered ?? false, - }; -} - -const LEVEL_TEMPLATE = t("default.drawingName", { n: "{n}" }); -const DASH_TEMPLATE = t("import.pdf.dashStyleName", { pattern: "{pattern}" }); - -function compareDrawing(project: Project, parsed: DxfImportResult, src: ReturnType, c: Case, label: string) { - const active = project.layers[0].code; - const parentName = `Import ${label}`; - const old = oldApp(project, parsed, c, active, parentName); - const doc = new ProjectDocument(project); - const r = doc.importDrawing(project, src, { ...c, activeCategoryCode: active, levelNameTemplate: LEVEL_TEMPLATE, parentName, dashStyleTemplate: DASH_TEMPLATE }, Date.now()); - if ("problems" in r) throw new Error(`${label}: ${r.problems.join("; ")}`); - expect(normalize(r.project), label).toBe(normalize(old)); - // Kern-Dokument = Leseansicht. - expect(normalize(canon(JSON.parse(doc.json()))), `${label} (Dokument)`).toBe(normalize(canon(r.project))); - doc.close(); -} - -const CASES: Case[] = [ - { target: { kind: "new", name: "" }, categoryMode: "byLayer", importMeshes: true }, - { target: { kind: "new", name: " Plan " }, categoryMode: "active", importMeshes: false, viewCenter: [12.5, -3.25] }, - { target: { kind: "existing", levelId: "eg" }, categoryMode: "byLayer", importMeshes: false, viewCenter: [0, 0] }, -]; - -const BASES: [string, Project][] = [ - ["leer", emptyProject], - ["beispiel", sampleProject], -]; - -function dxfFiles(): string[] { - return readdirSync(FX).filter((n) => /\.(dxf|dwg)$/i.test(n) && !n.startsWith("kataster150k")); -} - -describe.skipIf(!have)("Parität Zeichnungs-Import (DXF/DWG/PDF)", { timeout: 600_000 }, () => { - it("DXF/DWG: Projekt und Zusammenfassung gleich", () => { - let n = 0; - for (const name of dxfFiles()) { - const bytes = fx(name); - const flat = importDrawingFlat(bytes); - const parsed = decodeImport(flat.geom, flat.strings); - const src = packChunks([flat]); - expect(importSummary(src), name).toEqual(JSON.parse(JSON.stringify(oldSummary(parsed)))); - for (const [bn, base] of BASES) { - const levelId = base.drawingLevels[0].id; - for (const c of CASES) { - const cc = c.target.kind === "existing" ? { ...c, target: { kind: "existing" as const, levelId } } : c; - compareDrawing(base, parsed, src, cc, `${name}/${bn}/${JSON.stringify(cc)}`); - n++; - } - } - } - expect(n).toBeGreaterThan(20); - }); - - it("Layouts (Papierbereich)", () => { - const bytes = fx("layouts.dxf"); - const layouts = parseDxf(bytes).layouts ?? []; - expect(layouts.length).toBeGreaterThan(0); - for (const l of layouts) { - const flat = importDrawingFlat(bytes, l.name); - const parsed = decodeImport(flat.geom, flat.strings); - const src = packChunks([flat]); - expect(importSummary(src)).toEqual(JSON.parse(JSON.stringify(oldSummary(parsed)))); - compareDrawing(sampleProject, parsed, src, CASES[0], `layout ${l.name}`); - } - }); - - it("parallel gelesene Stücke (grosse DXF)", () => { - for (const name of ["kataster150k.dxf"]) { - const bytes = fx(name); - const offsets = Array.from(fileioLoaded()!.dxf_split_offsets(bytes, 4)); - expect(offsets.length, name).toBeGreaterThanOrEqual(3); - const closer = new TextEncoder().encode("0\nENDSEC\n0\nEOF\n"); - const pre = bytes.subarray(0, offsets[0]); - const chunks: Uint8Array[] = []; - for (let i = 0; i + 1 < offsets.length; i++) { - const body = bytes.subarray(offsets[i], offsets[i + 1]); - const c = new Uint8Array(pre.length + body.length + closer.length); - c.set(pre, 0); - c.set(body, pre.length); - c.set(closer, pre.length + body.length); - chunks.push(c); - } - const flats = chunks.map((c) => importDrawingFlat(c)); - const parts = flats.map((f, i) => decodeImport(f.geom, f.strings, `c${i}-`)); - const merged = mergeResults(parts); - const src = packChunks(flats); - expect(importSummary(src), name).toEqual(JSON.parse(JSON.stringify(oldSummary(merged)))); - compareDrawing(sampleProject, merged, src, CASES[0], `${name} Stücke`); - compareDrawing(emptyProject, merged, src, CASES[1], `${name} Stücke aktiv`); - } - }); - - it("Vektor-PDF: Seiten, Massstäbe, Texte, Strichmuster", () => { - for (const name of ["plan.pdf", "plan-rot.pdf"]) { - const bytes = fx(name); - const res = fileioLoaded()!.pdf_read_page(bytes, 0); - const flat = { geom: res.geom(), strings: res.strings() }; - res.free(); - const page = readPdfVectorPage(bytes, 0); - // pdf-info - expect(JSON.parse(core().pdf_page_info(flat.geom, JSON.stringify(flat.strings)))).toEqual(JSON.parse(JSON.stringify(pdfPageInfo(page)))); - for (const scale of [100, 50, 1, 333.3]) { - for (const texts of [true, false]) { - const parsed = pdfPageToImport(page, scale, { texts }); - const src = packChunks([flat], { kind: "pdf", scale, texts }); - expect(importSummary(src)).toEqual(JSON.parse(JSON.stringify(oldSummary(parsed)))); - for (const [bn, base] of BASES) { - for (const c of CASES) { - const cc = c.target.kind === "existing" ? { ...c, target: { kind: "existing" as const, levelId: base.drawingLevels[0].id } } : c; - compareDrawing(base, parsed, src, cc, `${name}/${scale}/${texts}/${bn}`); - } - } - } - } - // Projekt mit schon passendem Linienstil: wird wiederverwendet. - const withStyle: Project = { ...sampleProject, lineStyles: [...sampleProject.lineStyles, { id: "x", name: "x", weight: 0.1, color: "#000", dash: [1.05, 0.7] }] }; - compareDrawing(withStyle, pdfPageToImport(page, 100), packChunks([flat], { kind: "pdf", scale: 100 }), CASES[0], `${name} Stil`); - } - }); -}); - -function mergeResults(results: DxfImportResult[]): DxfImportResult { - const meshes: ImportedMesh[] = []; - const contours: ContourSet[] = []; - const texts: ImportedText[] = []; - const layerColors: Record = {}; - const diagnostics = { entityCounts: {} as Record, total: 0 }; - for (const r of results) { - for (const m of r.meshes) meshes.push(m); - for (const c of r.contours) contours.push(c); - for (const tt of r.texts ?? []) texts.push(tt); - Object.assign(layerColors, r.layerColors); - for (const [k, n] of Object.entries(r.diagnostics?.entityCounts ?? {})) diagnostics.entityCounts[k] = (diagnostics.entityCounts[k] ?? 0) + n; - diagnostics.total += r.diagnostics?.total ?? 0; - } - return { meshes, contours, texts, layerColors, diagnostics, insUnits: results[0]?.insUnits, unitScale: results[0]?.unitScale, layouts: results[0]?.layouts }; -} - -// ── IFC ────────────────────────────────────────────────────────────────────── - -function contextOps(project: Project, meshes: NonNullable): CoreOp[] { - return [ - ...(project.context ? addItems("context", meshes) : fieldOps(project, "context", meshes)), - ...fieldOps(project, "layers", ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : [])))), - ]; -} - -const geoProject: Project = { ...sampleProject, geoAnchor: { lv95: { e: 2600000, n: 1200000 }, model: { x: 0, y: 0 } } } as Project; -const IFC_BASES: [string, Project][] = [["leer", emptyProject], ["beispiel", sampleProject], ["geo", geoProject], ["ohneListen", { ...emptyProject, context: undefined, rooms: undefined, columns: undefined, ceilingTypes: undefined } as unknown as Project]]; - -describe.skipIf(!have)("Parität IFC-Import", { timeout: 600_000 }, () => { - it("Bauteile und Kontext-Meshes: Projekt, Zusammenfassung, Bericht gleich", async () => { - const files = readdirSync(FX).filter((n) => n.endsWith(".ifc")); - expect(files.length).toBeGreaterThanOrEqual(5); - for (const name of files) { - const bytes = fx(name); - const flat = await importIfcFlat(bytes, true); - const { products, report, elements } = await readIfcElements(bytes); - for (const [bn, base] of IFC_BASES) { - for (const group of ["auto", "product", "class"] as const) { - const label = `${name}/${bn}/${group}`; - const old = ifcElementsToProject(base, products, elements, { fileName: name, geoOrigin: projectGeoOrigin(base), group }); - const doc = new ProjectDocument(base); - const r = doc.importIfc(base, flat, { fileName: name, group, elements: true }, Date.now()); - if ("problems" in r) throw new Error(`${label}: ${r.problems.join("; ")}`); - expect(normalize(r.project), label).toBe(normalize(old.project)); - expect(r.summary, label).toEqual(old.summary); - expect(r.kept, label).toEqual(elements.kept); - // CLI `import-ifc --elements`: Bericht wie früher `{ ...report, products: undefined, elements: summary, kept }`. - expect(JSON.stringify({ ...r.report, products: undefined, byClass: undefined, triangles: undefined, kept: r.kept })).toBe( - JSON.stringify({ ...report, products: undefined, elements: old.summary, kept: elements.kept }), - ); - expect(normalize(canon(JSON.parse(doc.json()))), `${label} (Dokument)`).toBe(normalize(canon(r.project))); - doc.close(); - // Nur Kontext-Meshes ([B3]). - const m = await readIfc(bytes); - const meshes = ifcToImportedMeshes(m.products, name, { geoOrigin: projectGeoOrigin(base), group }); - const oldMesh = applyOps(base, contextOps(base, meshes)); - const flat2 = await importIfcFlat(bytes, false); - const doc2 = new ProjectDocument(base); - const r2 = doc2.importIfc(base, flat2, { fileName: name, group }, Date.now()); - if ("problems" in r2) throw new Error(r2.problems.join("; ")); - expect(normalize(r2.project), `${label} Meshes`).toBe(normalize(oldMesh)); - const byClass: Record = {}; - for (const p of m.products) byClass[p.ifcClass] = (byClass[p.ifcClass] ?? 0) + 1; - const triangles = m.products.reduce((s, p) => s + p.indices.length / 3, 0); - expect(r2.report).toEqual(JSON.parse(JSON.stringify({ ...m.report, byClass, triangles }))); - expect(r2.contextObjects).toBe(meshes.length); - doc2.close(); - } - } - } - }); -}); - -// ── Meshes ─────────────────────────────────────────────────────────────────── - -describe.skipIf(!have)("Parität Mesh-Import", { timeout: 600_000 }, () => { - it("OBJ/STL/glTF/GLB/PLY: Projekt und Bericht gleich", async () => { - const files = readdirSync(FX).filter((n) => /\.(obj|stl|glb|gltf|ply)$/i.test(n)); - expect(files.length).toBeGreaterThanOrEqual(6); - const sidecars = (n: string) => (n === "gruppen.obj" ? [{ name: "farben.mtl", bytes: fx("farben.mtl") }] : []); - for (const name of files) { - for (const [unit, up] of [["m", "auto"], ["mm", "y"], ["cm", "z"]] as [MeshUnit, MeshUp][]) { - const flat = await importMeshFlat(fx(name), name, { unit, up, maxTriangles: 0, files: sidecars(name) }); - const { objects, report } = decodeMesh(flat); - expect(JSON.parse(core().mesh_import_report(flat.flat, JSON.stringify(flat.strings)))).toEqual(JSON.parse(JSON.stringify(report))); - for (const [bn, base] of [["beispiel", sampleProject], ["geo", geoProject], ["leer", { ...emptyProject, context: undefined } as unknown as Project]] as [string, Project][]) { - for (const placement of ["center", "original"] as const) { - for (const group of ["auto", "object", "merge"] as const) { - const label = `${name}/${unit}/${bn}/${placement}/${group}`; - const meshes = meshObjectsToImportedMeshes(objects, name, { placement, geoOrigin: projectGeoOrigin(base), group }); - const old = applyOps(base, contextOps(base, meshes)); - const doc = new ProjectDocument(base); - const r = doc.importMesh(base, flat, { fileName: name, placement, group }, Date.now()); - if ("problems" in r) throw new Error(`${label}: ${r.problems.join("; ")}`); - expect(normalize(r.project), label).toBe(normalize(old)); - expect(r.contextObjects).toBe(meshes.length); - doc.close(); - } - } - } - } - } - }); -}); diff --git a/src/io/importView.testutil.ts b/src/io/importView.testutil.ts new file mode 100644 index 00000000..d51f71cf --- /dev/null +++ b/src/io/importView.testutil.ts @@ -0,0 +1,148 @@ +// Test-Hilfen für Importe ([K4] S4): die Import-Form des Kerns als Objekt ansehen (`import_drawing_view`, Form wie +// früher `DxfImportResult`), die Rohdaten des IFC-Lesers ansehen und Dateien über das Kern-Dokument ins Projekt +// übernehmen. + +import type { Contour, Drawing2D, ImportedMesh, ImportedText, Project } from "../model/types"; +import { core } from "../engine/coreWasm"; +import { ProjectDocument, type DrawingImportDecision } from "../core/document"; +import { addedItems } from "../core/opsBuild"; +import { parseDxf } from "./dxfParser"; +import type { ImportDiagnostics, ImportSource, ParsedImport } from "./importSource"; +import { importIfcFlat, readIfcFlat, type IfcClassificationRef, type IfcImportReport } from "./ifcImport"; +import { readMesh, type MeshReadOptions } from "./meshImport"; + +/** Kontur der Leseansicht (mit Bögen einer Polylinie). */ +export interface ViewContour extends Contour { + bulgePolyline?: { pts: { x: number; y: number }[]; bulge: number[] }; +} + +/** Leseansicht der Import-Form. */ +export interface ImportView { + meshes: ImportedMesh[]; + contours: { type: "contourSet"; categoryCode: string; contours: ViewContour[] }[]; + texts: ImportedText[]; + layerColors: Record; + layerLineWeights: Record; + layerFillColors: Record; + layerDashes: Record; + diagnostics: ImportDiagnostics; + insUnits?: number; + unitScale?: number; + layouts?: { name: string; entities: number }[]; + layout?: string; + recovered: boolean; +} + +export function viewImport(src: ImportSource): ImportView { + const out = core().import_drawing_view(src.geom, JSON.stringify(src.strings), JSON.stringify(src.source), Date.now()); + if (out.startsWith("\u0001")) throw new Error(out.slice(1)); + return JSON.parse(out) as ImportView; +} + +/** DXF/DWG lesen (Format-Modul geladen) und als Leseansicht liefern. */ +export function inspectDxf(input: string | ArrayBuffer | Uint8Array, layout?: string): ImportView { + return viewImport(parseDxf(input, layout).src); +} + +/** + * Gelesene Datei über das Kern-Dokument ins Projekt übernehmen (Standard: neue Zeichnung, Layer als Kategorien, + * Meshes als Kontext). Wirft bei zurückgewiesener Änderung. + */ +export function importInto(project: Project, parsed: ParsedImport, decision: Partial = {}) { + const doc = new ProjectDocument(project); + const r = doc.importDrawing( + project, + parsed.src, + { + target: { kind: "new", name: "Import" }, + categoryMode: "byLayer", + activeCategoryCode: project.layers[0]?.code ?? "20", + importMeshes: true, + levelNameTemplate: "Zeichnung {n}", + parentName: "Import", + dashStyleTemplate: "PDF-Strich {pattern} mm", + ...decision, + }, + Date.now(), + ); + doc.close(); + if ("problems" in r) throw new Error(r.problems.join("; ")); + const drawings: Drawing2D[] = r.project.drawings2d.filter((d) => d.levelId === r.levelId); + return { ...r, drawings }; +} + +// ── IFC und Meshes ────────────────────────────────────────────────────────── + +/** Ein gelesenes IFC-Bauteil (Leseansicht des Lesers für Tests). */ +export interface IfcProductView { + globalId: string; + ifcClass: string; + name: string | null; + storey: string | null; + color: [number, number, number, number] | null; + classifications?: IfcClassificationRef[]; + positions: Float64Array; + indices: Uint32Array; +} + +/** Roh erkanntes Bauteil (`meta.elements.elements` des Lesers). */ +export interface IfcRawElement { + kind: "wall" | "opening" | "slab" | "column" | "space"; + globalId: string; + ifcClass: string; + name: string | null; + openingKind?: "door" | "window" | "hole"; + sia?: string | null; + longName?: string | null; + classifications?: IfcClassificationRef[]; + at: number; + n: number; +} + +/** IFC lesen (Format-Modul, Web-Worker wenn vorhanden) und Bericht, Bauteile, roh erkannte Elemente ansehen. */ +export async function inspectIfc(bytes: Uint8Array, elements = false) { + const flat = await readIfcFlat(bytes, elements); + const meta = JSON.parse(flat.meta) as Omit & { + products: (Omit & { positionCount: number; indexCount: number })[]; + elements?: { storeys: { name: string; elevation: number }[]; elements: IfcRawElement[]; kept: Record }; + }; + let po = 0; + let io = 0; + const products: IfcProductView[] = meta.products.map(({ positionCount, indexCount, ...p }) => { + const out = { ...p, positions: flat.positions.subarray(po, po + positionCount), indices: flat.indices.subarray(io, io + indexCount) }; + po += positionCount; + io += indexCount; + return out; + }); + const report: IfcImportReport = { ...meta, products: products.length }; + return { flat, meta, report, products, raw: meta.elements?.elements ?? [], kept: meta.elements?.kept ?? {} }; +} + +/** IFC über das Kern-Dokument ins Projekt übernehmen ([B3] Meshes bzw. `elements: true` [B4] Bauteile). */ +export async function importIfcInto( + project: Project, + bytes: Uint8Array, + opts: { fileName?: string; group?: "auto" | "product" | "class"; elements?: boolean } = {}, +) { + const flat = await importIfcFlat(bytes, opts.elements === true); + const doc = new ProjectDocument(project); + const r = doc.importIfc(project, flat, { fileName: opts.fileName ?? "haus.ifc", ...(opts.group ? { group: opts.group } : {}), elements: opts.elements === true }, Date.now()); + doc.close(); + if ("problems" in r) throw new Error(r.problems.join("; ")); + return { ...r, meshes: addedItems(r.ops, "context") as ImportedMesh[] }; +} + +/** Mesh-Datei lesen und über das Kern-Dokument als Kontext-Meshes übernehmen. */ +export async function importMeshInto( + project: Project, + bytes: Uint8Array, + name: string, + opts: MeshReadOptions & { placement?: "center" | "original"; group?: "auto" | "object" | "merge" } = {}, +) { + const read = await readMesh(bytes, name, opts); + const doc = new ProjectDocument(project); + const r = doc.importMesh(project, read.flat, { fileName: name, ...(opts.placement ? { placement: opts.placement } : {}), ...(opts.group ? { group: opts.group } : {}) }, Date.now()); + doc.close(); + if ("problems" in r) throw new Error(r.problems.join("; ")); + return { ...r, read, meshes: addedItems(r.ops, "context") as ImportedMesh[] }; +} diff --git a/src/io/meshImport.test.ts b/src/io/meshImport.test.ts index bf7183cb..4ab952aa 100644 --- a/src/io/meshImport.test.ts +++ b/src/io/meshImport.test.ts @@ -9,17 +9,15 @@ import type { ImportedMesh, Project, Wall } from "../model/types"; import { MESH_UNIT_SCALE, NO_FACES_PREFIX, - decodeMesh, formatMeshReport, handleMeshWorkerRequest, isMeshFile, - meshColorHex, - meshObjectsToImportedMeshes, - meshShift, + meshReport, readMesh, - type MeshObject, + type MeshReadOptions, type MeshWorkerRequest, } from "./meshImport"; +import { importMeshInto } from "./importView.testutil"; function baseProject(): Project { return { @@ -73,7 +71,13 @@ function project(): Project { const enc = new TextEncoder(); -function bbox(objs: MeshObject[]): { lo: number[]; hi: number[] } { +/** Objekte einer Datei als Kontext-Meshes (je Objekt, Datei-Koordinaten) über den Kern. */ +async function objectsOf(bytes: Uint8Array, name: string, opts: MeshReadOptions = {}) { + const r = await importMeshInto(baseProject(), bytes, name, { ...opts, placement: "original", group: "object" }); + return { objects: r.meshes, report: r.read.report }; +} + +function bbox(objs: ImportedMesh[]): { lo: number[]; hi: number[] } { const lo = [Infinity, Infinity, Infinity]; const hi = [-Infinity, -Infinity, -Infinity]; for (const o of objs) { @@ -87,12 +91,12 @@ function bbox(objs: MeshObject[]): { lo: number[]; hi: number[] } { return { lo, hi }; } -const tris = (objs: MeshObject[]) => objs.reduce((n, o) => n + o.indices.length / 3, 0); +const tris = (objs: ImportedMesh[]) => objs.reduce((n, o) => n + o.indices.length / 3, 0); describe("Mesh-Import: Rundreise mit dem eigenen Export", () => { it("GLB: Objekte, Dreieckszahl, Lage und Farbe bleiben erhalten", async () => { const p = project(); - const { objects, report } = await readMesh(exportGlb(p), "m.glb"); + const { objects, report } = await objectsOf(exportGlb(p), "m.glb"); expect(report.format).toBe("gltf"); expect(report.up).toBe("y"); expect(objects.length).toBeGreaterThanOrEqual(2); @@ -107,7 +111,7 @@ describe("Mesh-Import: Rundreise mit dem eigenen Export", () => { expect(b.hi[1]).toBeCloseTo(36, 4); expect(b.hi[2]).toBeCloseTo(9, 4); // Farbe #ff8000 (sRGB → linear → sRGB). - expect(meshColorHex(nachbar!.color)).toBe("#ff8000"); + expect(nachbar!.color).toBe("#ff8000"); // Wand: 0..5 in x, Höhe 2,6. const wall = objects.find((o) => o.name.startsWith("Wand_"))!; const bw = bbox([wall]); @@ -118,10 +122,10 @@ describe("Mesh-Import: Rundreise mit dem eigenen Export", () => { it("glTF (eingebettet), OBJ und STL ergeben dieselbe Dreieckszahl und Ausdehnung wie GLB", async () => { const p = project(); - const glb = await readMesh(exportGlb(p), "m.glb"); - const gltf = await readMesh(enc.encode(exportGltf(p)), "m.gltf"); - const obj = await readMesh(enc.encode(exportObj(p)), "m.obj"); - const stl = await readMesh(enc.encode(exportStl(p)), "m.stl"); + const glb = await objectsOf(exportGlb(p), "m.glb"); + const gltf = await objectsOf(enc.encode(exportGltf(p)), "m.gltf"); + const obj = await objectsOf(enc.encode(exportObj(p)), "m.obj"); + const stl = await objectsOf(enc.encode(exportStl(p)), "m.stl"); const n = tris(glb.objects); expect(tris(gltf.objects)).toBe(n); expect(tris(obj.objects)).toBe(n); @@ -142,8 +146,8 @@ describe("Mesh-Import: Rundreise mit dem eigenen Export", () => { it("OBJ: Einheit und erzwungene Achse", async () => { const p = project(); - const mm = await readMesh(enc.encode(exportObj(p)), "m.obj", { unit: "mm" }); - const m = await readMesh(enc.encode(exportObj(p)), "m.obj"); + const mm = await objectsOf(enc.encode(exportObj(p)), "m.obj", { unit: "mm" }); + const m = await objectsOf(enc.encode(exportObj(p)), "m.obj"); expect(bbox(mm.objects).hi[0]).toBeCloseTo(bbox(m.objects).hi[0] * MESH_UNIT_SCALE.mm, 6); const z = await readMesh(enc.encode(exportObj(p)), "m.obj", { up: "z" }); expect(z.report.up).toBe("z"); @@ -154,15 +158,14 @@ describe("Mesh-Import: Rundreise mit dem eigenen Export", () => { describe("Mesh-Import: Abbildung auf Kontext-Meshes", () => { it("Farbe ins Feld color, Gruppe als Ebene, Platzierung Mitte/Original", async () => { const p = project(); - const { objects } = await readMesh(exportGlb(p), "Haus.glb"); - const orig = meshObjectsToImportedMeshes(objects, "Haus.glb", { placement: "original" }); + const orig = (await importMeshInto(baseProject(), exportGlb(p), "Haus.glb", { placement: "original" })).meshes; const nachbar = orig.find((m) => m.name.startsWith("Kontext_"))!; expect(nachbar.type).toBe("importedMesh"); expect(nachbar.color).toBe("#ff8000"); expect(nachbar.positions.length).toBe(24); expect(Math.min(...nachbar.positions.filter((_, i) => i % 3 === 0))).toBeCloseTo(20, 4); // Mitte: Grundriss-Mitte aller Objekte auf (0, 0), Unterkante auf z = 0. - const centered = meshObjectsToImportedMeshes(objects, "Haus.glb", { placement: "center" }); + const centered = (await importMeshInto(baseProject(), exportGlb(p), "Haus.glb", { placement: "center" })).meshes; const xs = centered.flatMap((m) => m.positions.filter((_, i) => i % 3 === 0)); const ys = centered.flatMap((m) => m.positions.filter((_, i) => i % 3 === 1)); const zs = centered.flatMap((m) => m.positions.filter((_, i) => i % 3 === 2)); @@ -171,31 +174,16 @@ describe("Mesh-Import: Abbildung auf Kontext-Meshes", () => { expect(Math.min(...zs)).toBeCloseTo(0, 6); }); - it("Landeskoordinaten werden bei Original-Platzierung auf den Modell-Nullpunkt geschoben", () => { - const o: MeshObject = { - name: "N", - group: "", - color: null, - positions: new Float64Array([2600010, 1200010, 0, 2600020, 1200010, 0, 2600020, 1200020, 5]), - indices: new Uint32Array([0, 1, 2]), - }; - const shift = meshShift([o], { placement: "original", geoOrigin: { e: 2600000, n: 1200000 } }); - expect(shift).toEqual([-2600000, -1200000, 0]); - expect(meshShift([o], { placement: "original", geoOrigin: null })).toEqual([0, 0, 0]); - }); - - it("viele Objekte werden je Gruppe und Farbe zusammengelegt", () => { - const objs: MeshObject[] = Array.from({ length: 2100 }, (_, i) => ({ - name: `O${i}`, - group: i % 2 ? "A" : "B", - color: [1, 0, 0, 1], - positions: new Float64Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), - indices: new Uint32Array([0, 1, 2]), - })); - const m = meshObjectsToImportedMeshes(objs, "x.obj", { placement: "original" }); - expect(m).toHaveLength(2); - expect(m[0].indices.length / 3).toBe(1050); - expect(m[0].color).toBe("#ff0000"); + it("Landeskoordinaten werden bei Original-Platzierung auf den Modell-Nullpunkt geschoben", async () => { + const ply = enc.encode( + "ply\nformat ascii 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty list uchar int vertex_indices\nend_header\n" + + "2600010 1200010 0\n2600020 1200010 0\n2600020 1200020 5\n3 0 1 2\n", + ); + const geo: Project = { ...baseProject(), geoAnchor: { lv95: { e: 2600000, n: 1200000 }, model: { x: 0, y: 0 } } }; + const [m] = (await importMeshInto(geo, ply, "n.ply", { up: "z", placement: "original" })).meshes; + expect(m.positions.slice(0, 3)).toEqual([10, 10, 0]); + const [n] = (await importMeshInto(baseProject(), ply, "n.ply", { up: "z", placement: "original" })).meshes; + expect(n.positions[0]).toBeCloseTo(2600010, 3); }); it("Bericht als Text", async () => { @@ -236,8 +224,8 @@ describe("Mesh-Import: Fehler", () => { expect(report.triangles).toBe(1); }); - it("decodeMesh verwirft beschädigte Puffer", () => { - expect(() => decodeMesh({ flat: new Float64Array([9, 0]), strings: [] })).toThrow(); + it("beschädigte Puffer: Meldung des Kerns", () => { + expect(() => meshReport({ flat: new Float64Array([9, 0]), strings: [] })).toThrow(); }); it("Worker-Protokoll: Antwort und Fehler", async () => { diff --git a/src/io/meshImport.ts b/src/io/meshImport.ts index f01f2ea6..1a1d17ec 100644 --- a/src/io/meshImport.ts +++ b/src/io/meshImport.ts @@ -1,7 +1,8 @@ // Allgemeiner Mesh-Import als Kontext-Meshes ([B3]/[C11]): OBJ (+ MTL), STL, glTF/GLB, PLY mit Flächen — // Nachbargebäude und Umgebungsmodelle aus SketchUp/Blender/Rhino, Möbel. Dünne Fassade über den Rust-Leser -// (`src-tauri/fileio/src/mesh_import.rs`, Modul `pkgFileIo`); hier nur Aufruf, Dekodierung der flachen Puffer -// und die Abbildung auf `ImportedMesh` (wie `ifcImport.ts`, Farbe im Feld `color`). +// (`src-tauri/fileio/src/mesh_import.rs`, Modul `pkgFileIo`); hier nur der Aufruf. Bericht und Abbildung auf +// `ImportedMesh` (Farbe im Feld `color`, Platzierung, Gruppierung) liest der Kern aus den flachen Puffern +// (`core/src/import_context.rs`; Übernahme als EIN Undo-Schritt über `ProjectDocument.importMesh`, [K4] S4). // // Laden im Web-Worker (`meshImport.worker.ts`), Rückfall im aufrufenden Thread (Node: CLI, Tests). // @@ -11,9 +12,7 @@ // Standort-Bezug: auf den Modell-Nullpunkt zurückgeschoben, wie beim IFC-Import). import { loadFileio } from "../engine/fileioWasm"; -import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories"; -import type { ImportedMesh } from "../model/types"; -import { rgbToHex } from "../model/color"; +import { core } from "../engine/coreWasm"; export type MeshUnit = "mm" | "cm" | "m" | "inch" | "foot"; export type MeshUp = "auto" | "z" | "y"; @@ -26,15 +25,11 @@ export const MESH_UNITS: readonly MeshUnit[] = ["mm", "cm", "m", "inch", "foot"] /** Endungen der Hauptdateien (Menü, Drag & Drop); `mtl`/`bin` sind Begleitdateien. */ export const MESH_EXTENSIONS = ["obj", "stl", "gltf", "glb", "ply"] as const; export const MESH_SIDECAR_EXTENSIONS = ["mtl", "bin"] as const; -/** Ab so vielen Objekten wird je Gruppe + Farbe zusammengelegt (Projektdatei, Kontext-Panel). */ -export const MAX_SINGLE = 2000; /** Präfix des Rust-Fehlers für PLY ohne Flächen. */ export const NO_FACES_PREFIX = "[punktwolke]"; /** Präfix des Rust-Fehlers für fehlende externe glTF-Puffer. */ export const MISSING_EXTERNAL_PREFIX = "[extern]"; -const FORMATS: readonly MeshFormat[] = ["obj", "stl", "gltf", "ply"]; - export function isMeshFile(name: string): boolean { const ext = name.toLowerCase().split(".").pop() ?? ""; return (MESH_EXTENSIONS as readonly string[]).includes(ext); @@ -54,16 +49,6 @@ export interface MeshReadOptions { files?: { name: string; bytes: Uint8Array }[]; } -/** Ein gelesenes Objekt (Modell-Meter, Z = Höhe). */ -export interface MeshObject { - name: string; - group: string; - /** sRGB 0..1 mit Alpha, falls die Datei eine Farbe hat. */ - color: [number, number, number, number] | null; - positions: Float64Array; - indices: Uint32Array; -} - export interface MeshImportReport { format: MeshFormat; /** Verwendete Achse. */ @@ -99,51 +84,11 @@ export type MeshWorkerRequest = { }; export type MeshWorkerResponse = { type: "result"; flat: MeshFlat } | { type: "error"; message: string }; -const FLAT_VERSION = 1; -const HEAD = 12; - -/** Flache Puffer → Objekte + Bericht (Aufbau: Kopf von `mesh_import.rs`). */ -export function decodeMesh(r: MeshFlat): { objects: MeshObject[]; report: MeshImportReport } { - const f = r.flat; - if (f.length < HEAD || f[0] !== FLAT_VERSION) throw new Error("Mesh-Import: unbekannte Kodierung"); - const nWarn = f[10]; - const nObj = f[11]; - let at = HEAD; - const warnings: string[] = []; - for (let i = 0; i < nWarn; i++) warnings.push(r.strings[f[at++]] ?? ""); - const objects: MeshObject[] = []; - for (let k = 0; k < nObj; k++) { - const name = r.strings[f[at]] ?? ""; - const group = f[at + 1] >= 0 ? (r.strings[f[at + 1]] ?? "") : ""; - const color: MeshObject["color"] = f[at + 2] === 1 ? [f[at + 3], f[at + 4], f[at + 5], f[at + 6]] : null; - const np = f[at + 7]; - const ni = f[at + 8]; - at += 9; - if (!Number.isInteger(np) || !Number.isInteger(ni) || np < 0 || ni < 0 || at + np + ni > f.length) { - throw new Error("Mesh-Import: Puffer beschädigt"); - } - const positions = f.slice(at, at + np); - at += np; - const idx = f.subarray(at, at + ni); - const indices = new Uint32Array(ni); - for (let i = 0; i < ni; i++) indices[i] = idx[i]; - at += ni; - objects.push({ name, group, color, positions, indices }); - } - const report: MeshImportReport = { - format: FORMATS[f[1]] ?? "obj", - up: f[2] === 1 ? "y" : "z", - upAuto: f[3] === 1, - upCertain: f[4] === 1, - unitScale: f[5], - triangles: f[6], - degenerate: f[7], - badFaces: f[8], - truncated: f[9] === 1, - warnings, - objects: objects.length, - }; - return { objects, report }; +/** Bericht und Ausdehnung (Meter; `null` ohne Punkte) eines gelesenen Modells — der Kern liest den Puffer. */ +export function meshReport(r: MeshFlat): { report: MeshImportReport; extent: [number, number, number] | null } { + const out = core().mesh_import_report(r.flat, JSON.stringify(r.strings)); + if (out.startsWith("\u0001")) throw new Error(out.slice(1)); + return JSON.parse(out) as { report: MeshImportReport; extent: [number, number, number] | null }; } /** Liest Mesh-Bytes mit dem geladenen Format-Modul (Worker oder aufrufender Thread). */ @@ -236,114 +181,17 @@ export async function readMeshFlat(bytes: Uint8Array, name: string, opts?: MeshR return (await readInWorker(bytes, name, o)) ?? (await importMeshFlat(bytes, name, o)); } +/** Gelesene Mesh-Datei: Puffer (für den Import im Kern), Bericht, Ausdehnung. */ +export interface MeshRead { + flat: MeshFlat; + report: MeshImportReport; + extent: [number, number, number] | null; +} + /** Liest eine Mesh-Datei. Wirft mit der Meldung aus Rust bei unlesbaren Dateien. */ -export async function readMesh( - bytes: Uint8Array, - name: string, - opts?: MeshReadOptions, -): Promise<{ objects: MeshObject[]; report: MeshImportReport }> { - return decodeMesh(await readMeshFlat(bytes, name, opts)); -} - -// ── Abbildung auf Kontext-Meshes ──────────────────────────────────────────── - -export interface MeshToContextOptions { - placement?: MeshPlacement; - /** LV95-Ursprung des Projekts (`projectGeoOrigin`), sonst null (nur bei "original"). */ - geoOrigin?: { e: number; n: number } | null; - /** "object" = je Objekt, "merge" = je Gruppe + Farbe, "auto" (Standard) nach `MAX_SINGLE`. */ - group?: "object" | "merge" | "auto"; -} - -/** Verschiebung (x, y, z) je nach Platzierung. */ -export function meshShift(objects: readonly MeshObject[], opts: MeshToContextOptions = {}): [number, number, number] { - let minX = Infinity; - let maxX = -Infinity; - let minY = Infinity; - let maxY = -Infinity; - let minZ = Infinity; - for (const o of objects) { - const p = o.positions; - for (let i = 0; i + 2 < p.length; i += 3) { - if (p[i] < minX) minX = p[i]; - if (p[i] > maxX) maxX = p[i]; - if (p[i + 1] < minY) minY = p[i + 1]; - if (p[i + 1] > maxY) maxY = p[i + 1]; - if (p[i + 2] < minZ) minZ = p[i + 2]; - } - } - if (!Number.isFinite(minX)) return [0, 0, 0]; - const cx = (minX + maxX) / 2; - const cy = (minY + maxY) / 2; - if ((opts.placement ?? "center") === "center") return [-cx, -cy, -minZ]; - const origin = opts.geoOrigin; - if (origin && Math.hypot(cx - origin.e, cy - origin.n) < Math.hypot(cx, cy)) return [-origin.e, -origin.n, 0]; - return [0, 0, 0]; -} - -/** sRGB 0..1 → `#rrggbb` (Alpha entfällt). */ -export function meshColorHex(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 }); -} - -let counter = 0; - -/** Objekte → Kontext-Meshes (Kategorie „Situation" wie IFC/STEP; `layer` = Gruppe, sonst Dateiname). */ -export function meshObjectsToImportedMeshes(objects: readonly MeshObject[], fileName: string, opts: MeshToContextOptions = {}): ImportedMesh[] { - const base = fileName.replace(/\.[^.]+$/, "") || "Mesh"; - const [dx, dy, dz] = meshShift(objects, opts); - const stamp = Date.now().toString(36); - const group = opts.group ?? "auto"; - const merge = group === "merge" || (group === "auto" && objects.length > MAX_SINGLE); - - const toArrays = (parts: readonly MeshObject[]): { positions: number[]; indices: number[] } => { - const positions: number[] = []; - const indices: number[] = []; - for (const p of parts) { - const off = positions.length / 3; - for (let i = 0; i + 2 < p.positions.length; i += 3) { - positions.push(p.positions[i] + dx, p.positions[i + 1] + dy, p.positions[i + 2] + dz); - } - for (let i = 0; i < p.indices.length; i++) indices.push(p.indices[i] + off); - } - return { positions, indices }; - }; - - if (!merge) { - return objects.map((o, i) => { - const color = meshColorHex(o.color); - return { - id: `imported-mesh-${stamp}-${counter++}`, - type: "importedMesh" as const, - name: o.name || `${base} ${i + 1}`, - layer: o.group || base, - categoryCode: GENERIC_IMPORT_CATEGORY.code, - ...(color ? { color } : {}), - ...toArrays([o]), - }; - }); - } - const groups = new Map(); - for (const o of objects) { - const key = `${o.group}\u0000${meshColorHex(o.color) ?? ""}`; - const g = groups.get(key); - if (g) g.push(o); - else groups.set(key, [o]); - } - return [...groups.values()].map((parts) => { - const color = meshColorHex(parts[0].color); - const g = parts[0].group; - return { - id: `imported-mesh-${stamp}-${counter++}`, - type: "importedMesh" as const, - name: `${base}${g ? `: ${g}` : ""} (${parts.length})`, - layer: g || base, - categoryCode: GENERIC_IMPORT_CATEGORY.code, - ...(color ? { color } : {}), - ...toArrays(parts), - }; - }); +export async function readMesh(bytes: Uint8Array, name: string, opts?: MeshReadOptions): Promise { + const flat = await readMeshFlat(bytes, name, opts); + return { flat, ...meshReport(flat) }; } /** Bericht als kurzer Text; `tr` übersetzt (Kern kennt kein i18n, die Hülle reicht `t` herein). */ diff --git a/src/io/pdfCalibrate.test.ts b/src/io/pdfCalibrate.test.ts index d6dbf476..e7d1221f 100644 --- a/src/io/pdfCalibrate.test.ts +++ b/src/io/pdfCalibrate.test.ts @@ -1,7 +1,6 @@ // [76] Zwei-Punkt-Kalibrierung und Fangindex des PDF-Imports sowie Strichmuster → Linienstil. import { describe, expect, it } from "vitest"; -import type { LineStyle } from "../model/types"; import { buildSnapIndex, collectSnapPoints, @@ -10,7 +9,6 @@ import { pdfPaperMm, pdfScaleFromDistance, } from "./pdfCalibrate"; -import { planDashLineStyles, sameDash } from "./pdfLineStyles"; import { PT_TO_MM, type PdfVectorPage, type PdfVectorPath } from "./pdfVector"; const path = (pts: [number, number][], extra: Partial = {}): PdfVectorPath => ({ @@ -96,32 +94,3 @@ describe("Fangindex", () => { expect(out.nearest(899, 901, 5)).toEqual({ x: 900, y: 900 }); }); }); - -describe("Strichmuster → Linienstil", () => { - const solid: LineStyle = { id: "thin", name: "Volllinie", weight: 0.13, color: "#111", dash: null }; - const dashed: LineStyle = { id: "d", name: "Strich", weight: 0.02, color: "#111", dash: [1, 0.7] }; - - it("vergleicht mit Toleranz", () => { - expect(sameDash([1.05, 0.7], [1, 0.7])).toBe(true); - expect(sameDash([3, 1], [1, 3])).toBe(false); - expect(sameDash([1, 1], [1, 1, 1, 1])).toBe(false); - }); - - it("nimmt vorhandenen Stil mit gleichem Muster, legt sonst genau einen neuen an", () => { - const plan = planDashLineStyles( - { a: [1.05, 0.7], b: [2.8, 1.4], c: [2.8, 1.4], d: [0.05, 0.7, 2.8, 0.7] }, - [solid, dashed], - ); - expect(plan.styleByLayer.get("a")).toBe("d"); - expect(plan.created).toHaveLength(2); - expect(plan.styleByLayer.get("b")).toBe(plan.styleByLayer.get("c")); - const made = plan.created[0]; - expect(made).toMatchObject({ dash: [2.8, 1.4], weight: 0.02 }); - expect(made.id).toBe("pdf-dash-2_8_1_4"); - expect(plan.created[1].dash).toEqual([0.05, 0.7, 2.8, 0.7]); - }); - - it("ohne Muster nichts", () => { - expect(planDashLineStyles(undefined, [solid])).toEqual({ created: [], styleByLayer: new Map() }); - }); -}); diff --git a/src/io/pdfLineStyles.ts b/src/io/pdfLineStyles.ts deleted file mode 100644 index 3a6ab20a..00000000 --- a/src/io/pdfLineStyles.ts +++ /dev/null @@ -1,55 +0,0 @@ -// PDF-Strichmuster → Linienstile ([76], Operator `d`). Der PDF-Import liefert je Ebene ein Muster in -// Papier-mm (`DxfImportResult.layerDashes`); hier wird es einem vorhandenen Linienstil mit gleichem -// Muster zugeordnet oder als neuer Strichmuster-Stil angelegt. Ohne Änderung am Modell: ein -// `LineStyle` mit `dash` (mm Papier, an/aus/an/aus) ist schon vorgesehen, das Drawing2D trägt -// `lineStyleId`. Das Muster hängt nicht vom Plan-Massstab ab (Papier-mm wie im PDF). - -import type { LineStyle } from "../model/types"; -import { t } from "../i18n"; -import { pdfDashLabel } from "./pdfVector"; - -/** Relative bzw. absolute (mm) Toleranz beim Vergleich zweier Muster. */ -const REL_TOL = 0.15; -const ABS_TOL = 0.06; - -/** Gleiches Muster (gleiche Länge, jedes Glied innerhalb der Toleranz)? */ -export function sameDash(a: readonly number[], b: readonly number[]): boolean { - return a.length === b.length && a.every((v, i) => Math.abs(v - b[i]) <= Math.max(ABS_TOL, REL_TOL * Math.max(v, b[i]))); -} - -export interface DashStylePlan { - /** Neu anzulegende Linienstile (am Projekt anhängen, bevor die Zeichnungen verweisen). */ - created: LineStyle[]; - /** Ebenenname → Linienstil-Id (vorhanden oder neu). */ - styleByLayer: Map; -} - -/** Ordnet jedem Muster einen Linienstil zu; gleiche Muster teilen sich einen. */ -export function planDashLineStyles( - layerDashes: Readonly> | undefined, - existing: readonly LineStyle[], -): DashStylePlan { - const created: LineStyle[] = []; - const styleByLayer = new Map(); - if (!layerDashes) return { created, styleByLayer }; - const usedIds = new Set(existing.map((l) => l.id)); - for (const [layer, dash] of Object.entries(layerDashes)) { - if (dash.length < 2) continue; - const known = [...existing, ...created].find( - (l) => (l.kind ?? "dash") === "dash" && l.dash !== null && sameDash(l.dash, dash), - ); - if (known) { - styleByLayer.set(layer, known.id); - continue; - } - const label = pdfDashLabel(dash); - const base = `pdf-dash-${label.replace(/[^0-9a-z]+/gi, "_")}`; - let id = base; - for (let n = 2; usedIds.has(id); n++) id = `${base}-${n}`; - usedIds.add(id); - // Haarlinien-Default wie bei neuen Linienstilen; Strichstärke und Farbe kommen von der Ebene. - created.push({ id, name: t("import.pdf.dashStyleName", { pattern: label }), weight: 0.02, color: "#1a1a1a", dash: [...dash] }); - styleByLayer.set(layer, id); - } - return { created, styleByLayer }; -} diff --git a/src/io/pdfVector.test.ts b/src/io/pdfVector.test.ts index 0df25e1c..b551f80f 100644 --- a/src/io/pdfVector.test.ts +++ b/src/io/pdfVector.test.ts @@ -1,17 +1,15 @@ -// [76] Vektor-PDF → DXF-Import-Form → 2D-Zeichnung: Massstab, Ebenen nach Farbe/Strichstärke, +// [76] Vektor-PDF → Import-Form (Kern) → 2D-Zeichnung: Massstab, Ebenen nach Farbe/Strichstärke, // Flächenfarben, Texte; kaputte Dateien werfen, ohne das WASM-Modul lahmzulegen. import { beforeAll, describe, expect, it } from "vitest"; import { loadFileioForTests } from "../engine/fileioWasm.testing"; -import { - isPdfFile, - pdfLineWeightMm, - pdfMetersPerPt, - pdfPageInfo, - pdfPageToImport, - readPdfVectorPage, -} from "./pdfVector"; -import { contoursToDrawings, distinctImportLayers, planImportCategories, textsToDrawings } from "./dxfToDrawings"; +import { isPdfFile, pdfImport, pdfPageInfo, readPdfVector, PT_TO_MM } from "./pdfVector"; +import { importInto, viewImport } from "./importView.testutil"; +import { emptyProject } from "../model/sampleProject"; + +const readPdfVectorPage = (bytes: Uint8Array, page = 0) => readPdfVector(bytes, page).page; +/** Modell-Meter je pt bei 1:`scale`. */ +const pdfMetersPerPt = (scale: number) => (PT_TO_MM / 1000) * scale; /** Minimales einseitiges PDF (A4 hoch) mit Inhalt `content`, Schrift F1 = Helvetica. */ function makePdf(content: string, pageExtra = ""): Uint8Array { @@ -46,7 +44,8 @@ beforeAll(loadFileioForTests); describe("Vektor-PDF-Import", () => { it("liest Pfade, Farben, Strichstärken und Text in pt", () => { - const page = readPdfVectorPage(makePdf(PLAN)); + const read = readPdfVector(makePdf(PLAN)); + const page = read.page; expect(page.pageCount).toBe(1); expect([page.width, page.height]).toEqual([595, 842]); expect(page.paths).toHaveLength(4); @@ -57,27 +56,33 @@ describe("Vektor-PDF-Import", () => { expect(page.texts).toEqual([ { text: "Wohnen", font: "Helvetica", x: 72, y: 300, size: 10, angle: 0, color: "#000000" }, ]); - const info = pdfPageInfo(page); + const info = pdfPageInfo(read); expect(info).toMatchObject({ pages: 1, page: 1, paths: 4, texts: 1, bboxPt: [0, 0, 595, 842] }); }); it("Massstab 1:100 und Ebenen nach Strichstärke/Farbe → 2D-Zeichnung", () => { - const page = readPdfVectorPage(makePdf(PLAN)); - const res = pdfPageToImport(page, 100); + const parsed = pdfImport(readPdfVector(makePdf(PLAN)), 100); + const res = viewImport(parsed.src); const k = pdfMetersPerPt(100); expect(k).toBeCloseTo(0.0352778, 6); - const layers = distinctImportLayers(res.contours, res.texts ?? []).sort(); - expect(layers).toEqual(["PDF 0.18 #ff0000 (Strich 1.05/0.7)", "PDF 0.50 #000000", "PDF Fläche #808080", "PDF Text #000000"]); - expect(res.layerLineWeights?.["PDF 0.50 #000000"]).toBe(0.5); - expect(pdfLineWeightMm(0.5)).toBe(0.18); + expect(parsed.summary.unitScale).toBeCloseTo(k, 12); + expect(res.layerLineWeights["PDF 0.50 #000000"]).toBe(0.5); + expect(res.layerLineWeights["PDF 0.18 #ff0000 (Strich 1.05/0.7)"]).toBe(0.18); + expect(res.layerDashes["PDF 0.18 #ff0000 (Strich 1.05/0.7)"]).toEqual([1.05, 0.7]); - const plan = planImportCategories(layers, [], "Import plan.pdf", res.layerColors, res.layerLineWeights); - const cat = plan.parent?.children?.find((c) => c.name === "PDF 0.18 #ff0000 (Strich 1.05/0.7)"); + const r = importInto(emptyProject, parsed, { parentName: "Import plan.pdf" }); + const parent = r.project.layers.find((c) => c.name === "Import plan.pdf"); + expect((parent?.children ?? []).map((c) => c.name).sort()).toEqual([ + "PDF 0.18 #ff0000 (Strich 1.05/0.7)", + "PDF 0.50 #000000", + "PDF Fläche #808080", + "PDF Text #000000", + ]); + const cat = parent?.children?.find((c) => c.name === "PDF 0.18 #ff0000 (Strich 1.05/0.7)"); expect(cat).toMatchObject({ color: "#ff0000", lw: 0.18 }); - const code = (l: string) => plan.codeByLayer.get(l) ?? "00"; - const drawings = contoursToDrawings(res.contours, "eg", "byLayer", "00", code, (l) => res.layerFillColors?.[l]); - // Linie, gestrichelte Linie, Fläche + Umriss (Hintergrund weggelassen). - expect(drawings).toHaveLength(4); + // Linie, gestrichelte Linie, Fläche + Umriss (Hintergrund weggelassen), Text. + const drawings = r.drawings; + expect(drawings).toHaveLength(5); const line = drawings[0].geom; expect(line.shape).toBe("line"); if (line.shape === "line") { @@ -85,16 +90,23 @@ describe("Vektor-PDF-Import", () => { expect(line.b.x - line.a.x).toBeCloseTo(3.527778, 5); // 100 pt = 35.28 mm Papier = 3.53 m bei 1:100 } // Strichmuster → Linienstil: nur die gestrichelte Ebene bekommt eine lineStyleId. - const styled = contoursToDrawings(res.contours, "eg", "byLayer", "00", code, undefined, (l) => - res.layerDashes?.[l] ? "pdf-dash" : undefined, - ); - expect(styled.filter((d) => d.lineStyleId === "pdf-dash")).toHaveLength(1); - expect(res.layerDashes?.["PDF 0.18 #ff0000 (Strich 1.05/0.7)"]).toEqual([1.05, 0.7]); - const fill = drawings.find((d) => d.fillColor); - expect(fill?.fillColor).toBe("#808080"); - const texts = textsToDrawings(res.texts ?? [], "eg", "byLayer", "00", code); - expect(texts[0].geom).toMatchObject({ shape: "text", text: "Wohnen" }); - if (texts[0].geom.shape === "text") expect(texts[0].geom.height).toBeCloseTo(10 * k, 9); + const styled = drawings.filter((d) => d.lineStyleId); + expect(styled).toHaveLength(1); + const style = r.project.lineStyles.find((l) => l.id === styled[0].lineStyleId); + expect(style).toMatchObject({ name: "PDF-Strich 1.05/0.7 mm", dash: [1.05, 0.7] }); + expect(drawings.find((d) => d.fillColor)?.fillColor).toBe("#808080"); + const text = drawings.find((d) => d.geom.shape === "text")!; + expect(text.geom).toMatchObject({ shape: "text", text: "Wohnen" }); + if (text.geom.shape === "text") expect(text.geom.height).toBeCloseTo(10 * k, 9); + // Ohne Texte. + expect(pdfImport(readPdfVector(makePdf(PLAN)), 100, { texts: false }).summary.texts).toBe(0); + }); + + it("vorhandener Linienstil mit gleichem Muster wird wiederverwendet", () => { + const base = { ...emptyProject, lineStyles: [...emptyProject.lineStyles, { id: "eigen", name: "eigen", weight: 0.1, color: "#000", dash: [1.1, 0.7] }] }; + const r = importInto(base, pdfImport(readPdfVector(makePdf(PLAN)), 100)); + expect(r.project.lineStyles).toHaveLength(base.lineStyles.length); + expect(r.drawings.filter((d) => d.lineStyleId === "eigen")).toHaveLength(1); }); it("Rotate 90 dreht die Seite (Breite/Höhe getauscht)", () => { @@ -138,24 +150,23 @@ describe("Vektor-PDF-Import", () => { expect(page.paths[1].curve).toMatchObject({ kind: "arc" }); expect(page.paths[1].curve?.a1).toBeCloseTo(Math.PI / 2, 3); - const res = pdfPageToImport(page, 100); + const parsed = pdfImport(readPdfVector(makePdf(circle + arc)), 100); const m = pdfMetersPerPt(100); - const contours = res.contours[0].contours; + const contours = viewImport(parsed.src).contours[0].contours; expect(contours[0].curve).toMatchObject({ kind: "circle" }); expect(contours[0].curve?.cx).toBeCloseTo(cx * m, 9); expect(contours[0].curve?.r).toBeCloseTo(r * m, 9); - const drawings = contoursToDrawings(res.contours, "eg", "active", "00", () => "00"); + const drawings = importInto(emptyProject, parsed, { categoryMode: "active", activeCategoryCode: "00" }).drawings; expect(drawings[0].geom).toMatchObject({ shape: "circle" }); expect(drawings[1].geom).toMatchObject({ shape: "arc" }); }); it("Strichmuster: Muster in Papier-mm je Ebene, Clip-Rechteck beschneidet", () => { - const page = readPdfVectorPage( - makePdf("50 50 100 100 re W n 1 0 0 RG [8 4] 0 d 0 100 m 300 100 l S"), - ); + const read = readPdfVector(makePdf("50 50 100 100 re W n 1 0 0 RG [8 4] 0 d 0 100 m 300 100 l S")); + const page = read.page; expect(page.paths).toHaveLength(1); expect(page.paths[0].pts).toEqual([{ x: 50, y: 100 }, { x: 150, y: 100 }]); - const res = pdfPageToImport(page, 50); + const res = viewImport(pdfImport(read, 50).src); const layer = Object.keys(res.layerDashes ?? {})[0]; expect(layer).toMatch(/Strich 2\.8\/1\.4/); expect(res.layerDashes?.[layer]).toEqual([2.8, 1.4]); diff --git a/src/io/pdfVector.ts b/src/io/pdfVector.ts index 02609c40..19d31c5a 100644 --- a/src/io/pdfVector.ts +++ b/src/io/pdfVector.ts @@ -1,20 +1,19 @@ // Vektor-PDF-Import ([76] Vektorfang auf PDF): dünne Fassade über das Rust-Format-Modul // (`src-tauri/fileio/src/pdf_vector.rs`, WASM `pkgFileIo`). Rust liest Pfade und Texte einer Seite in -// PDF-Punkten (angezeigte Seite: Ursprung links unten, /Rotate angewendet); hier wird daraus mit dem -// Massstab dieselbe Form wie beim DXF-Import (`DxfImportResult`), damit Import-Dialog und -// `dxfToDrawings.ts` unverändert weiterarbeiten. Die übernommenen Linien sind normale 2D-Zeichnungen +// PDF-Punkten (angezeigte Seite: Ursprung links unten, /Rotate angewendet); den Puffer wandelt der Kern +// beim Import mit dem Massstab um wie einen DXF-Import (`core/src/import_drawing.rs`); hier wird er nur für +// Vorschau und Kalibrierung dekodiert. Die übernommenen Linien sind normale 2D-Zeichnungen // und damit auch Fangziele (anders als die gerasterte PDF-Unterlage aus `pdfImport.ts`, die bleibt). // // Ebenen: gruppiert nach Strichstärke (Papier-mm) und Farbe, z. B. „PDF 0.35 #000000"; gestrichelte // Linien mit Muster in Papier-mm, z. B. „PDF 0.18 #ff0000 (Strich 0.9/0.6)" (daraus wird beim Import -// ein Linienstil, s. `pdfLineStyles.ts`); Flächen als „PDF Fläche #rrggbb" (Füllfarbe), Texte als +// ein Linienstil); Flächen als „PDF Fläche #rrggbb" (Füllfarbe), Texte als // „PDF Text #rrggbb". Kreise/Bögen aus Bézier-Folgen kommen als echte Kurven (`Contour.curve`) an. // Massstab: 1 pt = 25.4/72 mm Papier; Modell-Meter = pt × 25.4/72/1000 × Massstabszahl. -import type { Contour, ContourSet, ImportedText } from "../model/types"; -import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories"; import { fileioLoaded } from "../engine/fileioWasm"; -import type { DxfImportResult } from "./dxfParser"; +import { core } from "../engine/coreWasm"; +import { parsedImport, type ImportChunk, type ParsedImport } from "./importSource"; /** Papier-Millimeter je PDF-Punkt. */ export const PT_TO_MM = 25.4 / 72; @@ -90,18 +89,6 @@ export function isPdfFile(name: string, bytes?: Uint8Array): boolean { return head.includes("%PDF-"); } -/** Liest Seite `pageIndex` (0-basiert). Wirft bei unlesbaren/verschlüsselten Dateien (Meldung aus Rust). */ -export function readPdfVectorPage(bytes: Uint8Array, pageIndex = 0): PdfVectorPage { - const m = fileioLoaded(); - if (!m) throw new Error("Format-Modul nicht geladen: loadFileio() muss vor dem Import laufen."); - const res = m.pdf_read_page(bytes, pageIndex); - try { - return decodePdfPage(res.geom(), res.strings()); - } finally { - res.free(); - } -} - /** Dekodiert den Puffer aus `pdf_vector.rs::encode` (Aufbau dort beschrieben). */ export function decodePdfPage(geom: Float64Array, strings: readonly string[]): PdfVectorPage { let i = 0; @@ -155,161 +142,36 @@ export function decodePdfPage(geom: Float64Array, strings: readonly string[]): P return { pageCount, pageIndex, width, height, mediaBox, cropBox, rotate, truncated, images, paths, texts }; } -/** Modell-Meter je PDF-Punkt bei Massstab 1:`scale`. */ -export function pdfMetersPerPt(scale: number): number { - return (PT_TO_MM / 1000) * scale; +/** Gelesene Seite: Puffer des Format-Moduls (für den Kern) und dekodierte Seite (Vorschau, Kalibrierung). */ +export interface PdfRead { + chunk: ImportChunk; + page: PdfVectorPage; } -/** Strichstärke in Papier-mm, auf 0.01 mm gerundet (Haarlinie = 0). */ -export function pdfLineWeightMm(lineWidthPt: number): number { - return Math.round(lineWidthPt * PT_TO_MM * 100) / 100; -} - -/** Strichmuster in Papier-mm (an/aus/an/aus …), auf 0.05 mm gerundet; Punkte (an = 0) bleiben 0. */ -export function pdfDashMm(dashPt: readonly number[]): number[] { - return dashPt.map((d) => Math.round((d * PT_TO_MM) / 0.05) * 0.05).map((d) => Math.round(d * 100) / 100); -} - -/** Kurzschrift eines Strichmusters für Ebenen-/Stilnamen: „0.9/0.6". */ -export function pdfDashLabel(dashMm: readonly number[]): string { - return dashMm.map((d) => String(Math.round(d * 100) / 100)).join("/"); -} - -/** Ebenenname einer gestrichenen Linie (Stärke + Farbe, ggf. Strichmuster in Papier-mm). */ -export function pdfStrokeLayer(p: Pick): string { - const lw = pdfLineWeightMm(p.lineWidth).toFixed(2); - const dash = p.dash.length ? ` (Strich ${pdfDashLabel(pdfDashMm(p.dash))})` : ""; - return `PDF ${lw} ${p.stroke ?? "#000000"}${dash}`; -} - -export interface PdfImportOptions { - /** Texte übernehmen (Standard: ja). */ - texts?: boolean; +/** Liest Seite `pageIndex` (0-basiert) samt Puffer. Wirft bei unlesbaren/verschlüsselten Dateien. */ +export function readPdfVector(bytes: Uint8Array, pageIndex = 0): PdfRead { + const m = fileioLoaded(); + if (!m) throw new Error("Format-Modul nicht geladen: loadFileio() muss vor dem Import laufen."); + const res = m.pdf_read_page(bytes, pageIndex); + try { + const chunk = { geom: res.geom(), strings: res.strings() }; + return { chunk, page: decodePdfPage(chunk.geom, chunk.strings) }; + } finally { + res.free(); + } } /** - * Seite → DXF-Import-Form (Konturen, Texte, Ebenenfarben/-stärken, Flächenfarben) bei Massstab - * 1:`scale`. Die linke untere Seitenecke liegt im Nullpunkt. Gefüllte und gestrichene Pfade ergeben - * zwei Konturen (Fläche auf der Flächen-Ebene, Umriss auf der Linien-Ebene); weisse Hintergrund- - * Flächen, die mehr als die halbe Seite bedecken, werden weggelassen. + * Seite als Import bei Massstab 1:`scale` (Dialog-Zustand). Die Umwandlung — Ebenen nach Strichstärke/Farbe + * bzw. Strichmuster, Flächen, Texte, Linienstile der Strichmuster — macht der Kern (`import_drawing.rs`). */ -export function pdfPageToImport(page: PdfVectorPage, scale: number, opts: PdfImportOptions = {}): DxfImportResult { - const k = pdfMetersPerPt(scale); - const layerColors: Record = {}; - const layerLineWeights: Record = {}; - const layerFillColors: Record = {}; - const layerDashes: Record = {}; - const contours: Contour[] = []; - const pageArea = page.width * page.height; - const counts: Record = {}; - const toM = (pts: { x: number; y: number }[]) => pts.map((p) => ({ x: p.x * k, y: p.y * k })); - for (const p of page.paths) { - if (p.fill && p.closed && !(p.fill === "#ffffff" && !p.stroke && polygonArea(p.pts) > 0.5 * pageArea)) { - const layer = `PDF Fläche ${p.fill}`; - layerColors[layer] = p.fill; - layerFillColors[layer] = p.fill; - layerLineWeights[layer] ??= 0.05; - contours.push({ z: 0, pts: toM(p.pts), closed: true, filled: true, layer }); - counts.fill = (counts.fill ?? 0) + 1; - } - if (p.stroke) { - const layer = pdfStrokeLayer(p); - layerColors[layer] = p.stroke; - layerLineWeights[layer] = Math.max(0.05, pdfLineWeightMm(p.lineWidth)); - if (p.dash.length) layerDashes[layer] ??= pdfDashMm(p.dash); - const contour: Contour = { z: 0, pts: toM(p.pts), closed: p.closed, layer }; - if (p.curve) { - const c = p.curve; - contour.curve = { kind: c.kind, cx: c.cx * k, cy: c.cy * k, r: c.r * k, a0: c.a0, a1: c.a1 }; - } - contours.push(contour); - counts.stroke = (counts.stroke ?? 0) + 1; - } - } - const texts: ImportedText[] = []; - if (opts.texts !== false) { - for (const t of page.texts) { - const layer = `PDF Text ${t.color}`; - layerColors[layer] = t.color; - texts.push({ at: { x: t.x * k, y: t.y * k }, text: t.text, height: t.size * k, angle: t.angle, layer }); - } - } - const sets: ContourSet[] = contours.length - ? [ - { - id: `pdf-contours-${Date.now()}-${page.pageIndex}`, - type: "contourSet", - name: "PDF-Konturen", - categoryCode: GENERIC_IMPORT_CATEGORY.code, - contours, - }, - ] - : []; - return { - meshes: [], - contours: sets, - texts, - layerColors, - layerLineWeights, - layerFillColors, - layerDashes, - diagnostics: { - entityCounts: { PATH: counts.stroke ?? 0, FILL: counts.fill ?? 0, TEXT: texts.length, IMAGE: page.images }, - total: page.paths.length + page.texts.length, - }, - unitScale: k, - recovered: page.truncated, - }; +export function pdfImport(read: PdfRead, scale: number, opts: { texts?: boolean } = {}): ParsedImport { + return parsedImport([read.chunk], { kind: "pdf", scale, ...(opts.texts === false ? { texts: false } : {}) }); } -function polygonArea(pts: { x: number; y: number }[]): number { - let a = 0; - for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) a += (pts[j].x + pts[i].x) * (pts[j].y - pts[i].y); - return Math.abs(a / 2); -} - -/** Kurzbericht einer Seite (CLI `pdf-info`): Zahlen und Umriss der Geometrie in pt und Papier-mm. */ -export function pdfPageInfo(page: PdfVectorPage) { - let minX = Infinity; - let minY = Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - let points = 0; - const grow = (x: number, y: number) => { - if (x < minX) minX = x; - if (y < minY) minY = y; - if (x > maxX) maxX = x; - if (y > maxY) maxY = y; - }; - for (const p of page.paths) { - points += p.pts.length; - for (const q of p.pts) grow(q.x, q.y); - } - for (const t of page.texts) grow(t.x, t.y); - const layers: Record = {}; - for (const p of page.paths) { - if (p.stroke) { - const l = pdfStrokeLayer(p); - layers[l] = (layers[l] ?? 0) + 1; - } - if (p.fill) { - const l = `PDF Fläche ${p.fill}`; - layers[l] = (layers[l] ?? 0) + 1; - } - } - const r = (v: number) => Math.round(v * 100) / 100; - return { - pages: page.pageCount, - page: page.pageIndex + 1, - sizePt: [r(page.width), r(page.height)], - sizeMm: [r(page.width * PT_TO_MM), r(page.height * PT_TO_MM)], - rotate: page.rotate, - paths: page.paths.length, - points, - texts: page.texts.length, - images: page.images, - truncated: page.truncated, - bboxPt: Number.isFinite(minX) ? [r(minX), r(minY), r(maxX), r(maxY)] : null, - layers, - }; +/** Kurzbericht einer Seite (CLI `pdf-info`, Kern): Zahlen, Ebenen und Umriss in pt und Papier-mm. */ +export function pdfPageInfo(read: PdfRead): Record { + const out = core().pdf_page_info(read.chunk.geom, JSON.stringify(read.chunk.strings)); + if (out.startsWith("\u0001")) throw new Error(out.slice(1)); + return JSON.parse(out) as Record; } diff --git a/src/io/swissBuildings3d.ts b/src/io/swissBuildings3d.ts index f7b50f8e..66f55043 100644 --- a/src/io/swissBuildings3d.ts +++ b/src/io/swissBuildings3d.ts @@ -35,6 +35,7 @@ import { bboxAround, lv95BboxToWgs84, makeOrigin } from "./lv95"; import type { GeoOrigin, LV95 } from "./lv95"; import { stacQuery, pickAsset, downloadAssetText, downloadAssetBinary } from "./stacApi"; import { parseDxfAsync } from "./dxfParserAsync"; +import { importMeshes } from "./importSource"; import type { ImportedMesh } from "../model/types"; import { GEO_CATEGORY_DEFS, IMPORTED_ROOF_CATEGORY } from "../model/contextCategories"; @@ -409,14 +410,14 @@ export async function fetchBuildings3d( continue; } const { parseDwg } = await import("./dwgParser"); - rawMeshes = (await parseDwg(buf)).meshes; + rawMeshes = importMeshes((await parseDwg(buf)).src); } else { const text = await downloadAssetText(asset, [".dxf"]); if (!text) { skipped++; continue; } - rawMeshes = (await parseDxfAsync(text)).meshes; + rawMeshes = importMeshes((await parseDxfAsync(text)).src); } } catch (err) { // `parseDwg`/`parseDxf` werfen bei fatalen Parse-Fehlern BEWUSST (s. diff --git a/src/model/contextCategories.test.ts b/src/model/contextCategories.test.ts index f1422a5c..608f7b1c 100644 --- a/src/model/contextCategories.test.ts +++ b/src/model/contextCategories.test.ts @@ -16,6 +16,7 @@ import { TERRAIN_CATEGORY, IMPORTED_ROOF_CATEGORY, CONTEXT_PARENT_CATEGORY, + GENERIC_IMPORT_CATEGORY, } from "./contextCategories"; import type { LayerCategory } from "./types"; @@ -107,4 +108,11 @@ describe("ensureContextCategories", () => { const out = ensureContextCategories([], ["zz-unknown"]); expect(out).toEqual([]); }); + + it("Tabelle im Kern = Definitionen hier (alle Codes)", () => { + const nested = [TERRAIN_CATEGORY, IMAGE_CATEGORY, GENERIC_IMPORT_CATEGORY, ...Object.values(GEO_CATEGORY_DEFS)]; + const cat = (c: { code: string; name: string; color: string; lw: number }) => ({ code: c.code, name: c.name, color: c.color, lw: c.lw, visible: true, locked: false }); + const out = ensureContextCategories([], [...nested.map((c) => c.code), IMPORTED_ROOF_CATEGORY.code]); + expect(out).toEqual([{ ...cat(CONTEXT_PARENT_CATEGORY), children: nested.map(cat) }, cat(IMPORTED_ROOF_CATEGORY)]); + }); }); diff --git a/src/model/contextCategories.ts b/src/model/contextCategories.ts index a901a090..4f749c2d 100644 --- a/src/model/contextCategories.ts +++ b/src/model/contextCategories.ts @@ -23,6 +23,7 @@ import type { GeoCategory } from "../io/geoContext"; import { flattenCategories } from "./layers"; +import { core } from "../engine/coreWasm"; import type { LayerCategory } from "./types"; /** Eine Kategorie-Definition (Code + Default-Name/Farbe/Strichstärke). */ @@ -102,65 +103,27 @@ export const GEO_CATEGORY_DEFS: Record = { green: { code: "18", name: "Grünflächen", color: "#70b070", lw: 0.13 }, }; -/** Kategorien, die als KINDER von {@link CONTEXT_PARENT_CATEGORY} gruppiert - * werden (alles ausser der Top-Level-Ausnahme „31 Dächer"). */ -const NESTED_CONTEXT_CATEGORIES: ContextCategoryDef[] = [ - TERRAIN_CATEGORY, - IMAGE_CATEGORY, - GENERIC_IMPORT_CATEGORY, - ...Object.values(GEO_CATEGORY_DEFS), -]; - -const toLayerCategory = (c: ContextCategoryDef): LayerCategory => ({ - code: c.code, - name: c.name, - color: c.color, - lw: c.lw, - visible: true, - locked: false, -}); - /** * Ergänzt `layers` um jede fehlende Kontext-Kategorie aus `codes` — bereits * vorhandene Codes (auch vom Nutzer umbenannte, egal auf welcher Baumtiefe) * bleiben unverändert, nur wirklich fehlende werden mit ihrem Default-Namen/ - * -Farbe ergänzt. Fehlende {@link NESTED_CONTEXT_CATEGORIES} landen als - * KINDER von {@link CONTEXT_PARENT_CATEGORY} (legt „05 Kontext" bei Bedarf - * selbst an); die Top-Level-Ausnahme „31 Dächer" bleibt Top-Level (s. + * -Farbe ergänzt. Fehlende Kinder (alles ausser „31 Dächer") landen unter + * {@link CONTEXT_PARENT_CATEGORY} (legt „05 Kontext" bei Bedarf selbst an); + * die Top-Level-Ausnahme „31 Dächer" bleibt Top-Level (s. * {@link IMPORTED_ROOF_CATEGORY}-Moduldoc). Reiner No-op, wenn nichts fehlt * (liefert dieselbe Referenz zurück, spart eine unnötige `project`-Neuanlage). + * Rechnung im Kern (`core/src/import_context.rs`, auch für Importe; Tabelle der + * Kategorien dort, Gleichheit mit den Definitionen hier prüft `contextCategories.test.ts`). */ export function ensureContextCategories( layers: LayerCategory[], codes: Iterable, ): LayerCategory[] { const existing = new Set(flattenCategories(layers).map((c) => c.code)); - const missing = new Set(); - for (const code of codes) { - if (!existing.has(code)) missing.add(code); - } - if (missing.size === 0) return layers; - - const missingNested = NESTED_CONTEXT_CATEGORIES.filter((c) => missing.has(c.code)).map( - toLayerCategory, - ); - const missingTopLevel = missing.has(IMPORTED_ROOF_CATEGORY.code) - ? [toLayerCategory(IMPORTED_ROOF_CATEGORY)] - : []; - - let out = layers; - if (missingNested.length > 0) { - const parentIdx = out.findIndex((l) => l.code === CONTEXT_PARENT_CATEGORY.code); - if (parentIdx >= 0) { - out = out.map((l, i) => - i === parentIdx ? { ...l, children: [...(l.children ?? []), ...missingNested] } : l, - ); - } else { - out = [...out, { ...toLayerCategory(CONTEXT_PARENT_CATEGORY), children: missingNested }]; - } - } - if (missingTopLevel.length > 0) { - out = [...out, ...missingTopLevel]; - } - return out; + const missing = [...codes].filter((c) => !existing.has(c)); + if (missing.length === 0) return layers; + const out = core().layers_call("ensureContext", JSON.stringify(layers), JSON.stringify(missing), Date.now()); + if (out === "") throw new Error("Kern: Kontext-Kategorien fehlgeschlagen"); + const next = JSON.parse(out) as LayerCategory[] | null; + return next ?? layers; } diff --git a/src/model/layers.test.ts b/src/model/layers.test.ts index f5b72fce..bc12e9f4 100644 --- a/src/model/layers.test.ts +++ b/src/model/layers.test.ts @@ -11,7 +11,6 @@ import { insertAfterCode, nextFreeCode, patchCategoryByCode, - planImportLayers, recomputeFloorElevations, removeCategoryByCode, toggleCategoryByCode, @@ -53,14 +52,6 @@ describe("Kategorie-Baum (Kern)", () => { expect(nextFreeCode([])).toBe("01"); expect(nextFreeCode(tree())).toBe("102"); }); - - it("Import-Layer: bestehende Namen (case-insensitiv) behalten ihren Code", () => { - const r = planImportLayers(["wände", "Neu", "NEU"], tree(), { Neu: "#123" }, {}); - expect(r.children).toHaveLength(1); - expect(r.children[0]).toMatchObject({ code: "102", name: "Neu", color: "#123", lw: 0.18 }); - expect(r.parentCode).toBe("103"); - expect([...r.codeByLayer]).toEqual([["wände", "20"], ["Neu", "102"], ["NEU", "102"]]); - }); }); describe("Geschoss-Stapelung (Kern)", () => { diff --git a/src/model/layers.ts b/src/model/layers.ts index 87125bdb..59fc3ea9 100644 --- a/src/model/layers.ts +++ b/src/model/layers.ts @@ -100,21 +100,6 @@ export const insertAfterCode = (cats: LayerCategory[], code: string, clone: Laye /** Entfernt die Kategorie mit `code` (samt Kindern) aus dem Baum. */ export const removeCategoryByCode = (cats: LayerCategory[], code: string): LayerCategory[] => call("remove", cats, code); -/** Neue Kategorien für Import-Layer ohne gleichnamige Kategorie (s. `planImportCategories`, `io/dxfToDrawings.ts`). */ -export function planImportLayers( - layerNames: readonly string[], - existing: readonly LayerCategory[], - colors: Readonly>, - weights: Readonly>, -): { children: LayerCategory[]; parentCode: string; codeByLayer: Map } { - const r = call<{ children: LayerCategory[]; parentCode: string; codeByLayer: [string, string][] }>("planImport", existing as LayerCategory[], { - names: layerNames, - colors, - weights, - }); - return { children: r.children, parentCode: r.parentCode, codeByLayer: new Map(r.codeByLayer) }; -} - /** Auswahl nach Elementart (ids je Art, wie `selectionLockMembers` in App.tsx). */ export interface SelectionMembers { wallIds?: readonly string[]; diff --git a/src/state/activeLevelFallback.test.ts b/src/state/activeLevelFallback.test.ts index b83b97d2..8d174b6c 100644 --- a/src/state/activeLevelFallback.test.ts +++ b/src/state/activeLevelFallback.test.ts @@ -14,7 +14,9 @@ beforeEach(() => { describe("aktive Ebene nach Undo/Redo", () => { it("fällt nach Undo einer neuen Zeichnungsebene auf die zuvor aktive Ebene zurück", () => { getState().setActiveLevelId("og"); - const id = getState().addDrawingLevel("Blatt"); + const before = new Set(getState().project.drawingLevels.map((l) => l.id)); + getState().addDrawing(); + const id = getState().project.drawingLevels.find((l) => !before.has(l.id))!.id; getState().setActiveLevelId(id); const depth = getState().undoDepth; getState().undo(); diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index d8f02f51..9d011f7c 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -11,7 +11,7 @@ import { applyOps } from "../core/ops"; import type { CoreOp } from "../core/ops"; import type { ProjectMutation } from "../core"; -import type { LoadFileResult } from "../core/document"; +import type { LoadFileResult, ProjectDocument } from "../core/document"; import { addItems, fieldOps, @@ -91,6 +91,13 @@ export interface ProjectSlice { applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), coalesceKey?: string) => void; /** Die zuletzt angewendeten Ops (JSON-serialisierbar), jüngste zuletzt. */ recentOps: () => CoreOp[][]; + /** + * Import im Kern ([K4] S4): `run` rechnet die Ops auf dem Store-Dokument und wendet sie an (EIN Undo-Schritt, + * z. B. `doc.importDrawing`). Ergebnis mit den angewendeten Ops, `null` = zurückgewiesen (gemeldet). + */ + commitImport: ( + run: (doc: ProjectDocument, base: Project, now: number) => ({ project: Project; ops: CoreOp[] } & R) | { problems: string[] }, + ) => ({ ops: CoreOp[] } & R) | null; /** * Ein anderes Projekt übernehmen (Neu, Musterhaus; [K4] S4): lädt es als Ganzes ins Kern-Dokument * und leert den Verlauf (Rückgängig führt nicht ins vorherige Projekt). @@ -112,13 +119,6 @@ export interface ProjectSlice { addSection: () => void; /** Legt eine neue Ansichts-Zeichnungsebene (kind:"elevation") als Platzhalter an. */ addElevation: () => void; - /** - * Legt eine neue freie Zeichnungsebene (kind:"drawing") mit dem gegebenen - * Namen an und liefert ihre ID zurück (z. B. als Ziel eines DXF-Imports). - */ - addDrawingLevel: (name: string) => string; - /** Hängt fertige Drawing2D-Elemente an (z. B. aus einem DXF-Import). */ - importDrawings: (drawings: import("../model/types").Drawing2D[]) => void; patchLevel: (id: string, patch: Partial) => void; duplicateLevel: (id: string) => void; deleteLevel: (id: string) => void; @@ -563,6 +563,27 @@ export function createProjectSlice( applyChange, recentOps: () => opLog.slice(), + commitImport: (run) => { + let out: ReturnType | null = null; + set((s) => { + const doc = storeDocument(s.project); + const res = run(doc, s.project, Date.now()); + out = res; + if ("problems" in res) { + const problems = res.problems; + console.warn("Import verworfen:", problems); + queueMicrotask(() => get().notify(`${t("project.change.rejected")} ${problems[0]}`, "error")); + return {}; + } + if (res.ops.length === 0) return {}; + opLog.push(res.ops); + if (opLog.length > OP_LOG_LIMIT) opLog.shift(); + return { project: res.project, ...historyPatch(doc) }; + }); + const r = out as ReturnType | null; + return r && !("problems" in r) ? r : null; + }, + loadProject: (next) => { const doc = storeDocument(get().project); doc.load(next); @@ -649,27 +670,6 @@ export function createProjectSlice( return addItems("drawingLevels", [elevation]); }), - // Neue freie Zeichnungsebene mit explizitem Namen anlegen und ihre ID - // zurückgeben (Ziel-Ebene eines DXF-Imports). Der Name kommt vom Aufrufer - // (Dialog); leere Eingabe fällt auf den Default-Namen zurück. - addDrawingLevel: (name) => { - const id = `drawing-${Date.now()}`; - applyChange((p) => { - const n = p.drawingLevels.filter((z) => z.kind === "drawing").length + 1; - const drawing: DrawingLevel = { - id, - name: name.trim() || t("default.drawingName", { n }), - kind: "drawing", - visible: true, - locked: false, - }; - return addItems("drawingLevels", [drawing]); - }); - return id; - }, - - importDrawings: (drawings) => applyChange(addItems("drawings2d", drawings)), - patchLevel: (id, patch) => applyChange((p) => fieldOps( diff --git a/src/state/useDialogState.ts b/src/state/useDialogState.ts index d736dc39..9c4e42d0 100644 --- a/src/state/useDialogState.ts +++ b/src/state/useDialogState.ts @@ -9,7 +9,7 @@ // Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import { useState } from "react"; -import type { DxfImportResult } from "../io/dxfParser"; +import type { ParsedImport } from "../io/importSource"; import type { ExportSaveFormat } from "../ui/ExportSaveDialog"; import type { PdfImportOptions } from "../ui/ImportDialog"; import type { TabId as ResourceTabId } from "../ui/ResourceManager"; @@ -38,7 +38,7 @@ export function useDialogState() { const [importState, setImportState] = useState<{ fileName: string; isDwg: boolean; - parsed: DxfImportResult | null; + parsed: ParsedImport | null; // true, solange DWG noch geparst wird (WASM lädt/läuft). loading?: boolean; // Grober Phasenname während `loading` (nur DXF), s. ImportDialog.tsx. diff --git a/src/state/useProjectActions.ts b/src/state/useProjectActions.ts index d4e5d661..0a4b003d 100644 --- a/src/state/useProjectActions.ts +++ b/src/state/useProjectActions.ts @@ -76,8 +76,6 @@ export function useProjectActions( const addDrawing = useStore((s) => s.addDrawing); const addSection = useStore((s) => s.addSection); const addElevation = useStore((s) => s.addElevation); - const addDrawingLevel = useStore((s) => s.addDrawingLevel); - const importDrawings = useStore((s) => s.importDrawings); const addCategory = useStore((s) => s.addCategory); const patchCategory = useStore((s) => s.patchCategory); const addSubCategory = useStore((s) => s.addSubCategory); @@ -336,7 +334,11 @@ export function useProjectActions( // sonst muss man nach Standort-/Geo-Import manuell zur Geometrie suchen. const addContextObjectsAndFit = (objs: ContextObject[]) => { addContextObjects(objs); - const pts = contextObjectsBounds(objs); + fitToContextObjects(objs); + }; + /** Plan-Ansicht auf schon übernommene Kontext-Objekte einpassen (Importe im Kern, [K4] S4). */ + const fitToContextObjects = (objs: readonly ContextObject[]) => { + const pts = contextObjectsBounds(objs as ContextObject[]); if (pts) planViewRef.current?.fitBounds(pts); }; const removeContextObject = useStore((s) => s.removeContextObject); @@ -381,8 +383,6 @@ export function useProjectActions( addDrawing, addSection, addElevation, - addDrawingLevel, - importDrawings, addCategory, patchCategory, addSubCategory, @@ -452,6 +452,7 @@ export function useProjectActions( importHatches, addContextObjects, addContextObjectsAndFit, + fitToContextObjects, removeContextObject, removeContextObjects, generateTerrain, diff --git a/src/state/useProjectFileActions.ts b/src/state/useProjectFileActions.ts index 2f585b62..b50ef465 100644 --- a/src/state/useProjectFileActions.ts +++ b/src/state/useProjectFileActions.ts @@ -14,15 +14,11 @@ import type { AutosaveRecovery } from "./autosave"; import { useEffect, useRef, useState } from "react"; import type { RefObject } from "react"; import { t } from "../i18n"; -import type { DxfImportResult } from "../io/dxfParser"; import { parseDxfAsync } from "../io/dxfParserAsync"; -import { beginBusy } from "./busyStore"; -import { buildDrawings } from "../ui/ImportDialog"; -import { distinctImportLayers, planImportCategories } from "../io/dxfToDrawings"; +import { emptyImport, type ParsedImport } from "../io/importSource"; +import { beginBusy, endBusy } from "./busyStore"; import type { ImportDecision, PdfImportOptions } from "../ui/ImportDialog"; -import { isPdfFile, pdfPageToImport, readPdfVectorPage } from "../io/pdfVector"; -import { planDashLineStyles } from "../io/pdfLineStyles"; -import type { PdfVectorPage } from "../io/pdfVector"; +import { isPdfFile, pdfImport, readPdfVector, type PdfRead } from "../io/pdfVector"; import { exportScheduleCsv } from "../export/exportSchedule"; import { exportIfcSpf, type IfcExportOptions } from "../export/exportIfc"; import { loadFileio } from "../engine/fileioWasm"; @@ -43,90 +39,14 @@ import { import type { LockInfo } from "../native/projectFile"; import { addRecentProject, removeRecentProject } from "./recentProjects"; import { emptyProject, sampleProject } from "../model/sampleProject"; -import { flattenCategories } from "../model/types"; -import { addItems, fieldOps } from "../core"; -import type { CoreOp } from "../core/ops"; -import type { ContextObject, Drawing2D, Project, Vec2 } from "../model/types"; +import type { Project } from "../model/types"; import type { PlanViewHandle } from "../views/plan/PlanView"; -/** Umriss (bbox) aller Drawing2D-Geometrien in Modell-Metern (null = leer). */ -function drawingsBBox( - drawings: Drawing2D[], -): { minX: number; minY: number; maxX: number; maxY: number } | null { - let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; - const acc = (x: number, y: number) => { - minX = Math.min(minX, x); minY = Math.min(minY, y); - maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); - }; - for (const d of drawings) { - const g = d.geom; - if (g.shape === "line" || g.shape === "xline" || g.shape === "ray") { acc(g.a.x, g.a.y); acc(g.b.x, g.b.y); } - else if (g.shape === "polyline") for (const p of g.pts) acc(p.x, p.y); - else if (g.shape === "rect") { acc(g.min.x, g.min.y); acc(g.max.x, g.max.y); } - else if (g.shape === "circle" || g.shape === "arc") { - acc(g.center.x - g.r, g.center.y - g.r); - acc(g.center.x + g.r, g.center.y + g.r); - } else if (g.shape === "ellipse") { - acc(g.center.x - g.rx, g.center.y - g.ry); - acc(g.center.x + g.rx, g.center.y + g.ry); - } else if (g.shape === "bezier" || g.shape === "spline") { - for (const p of g.pts) acc(p.x, p.y); - } else if (g.shape === "dimension") { - for (const p of g.pts) acc(p.x, p.y); - } else if (g.shape === "kote") acc(g.at.x, g.at.y); - else if (g.shape === "detailref") acc(g.at.x, g.at.y); - else if (g.shape === "scalebar") { - acc(g.at.x, g.at.y); - acc(g.at.x + g.segmentLength * g.segments, g.at.y); - } - else if (g.shape === "pointmarker") acc(g.at.x, g.at.y); - else if (g.shape === "text") acc(g.at.x, g.at.y); - else if (g.shape === "block") acc(g.at.x, g.at.y); - } - return Number.isFinite(minX) ? { minX, minY, maxX, maxY } : null; -} - -/** Ein Drawing2D um (dx,dy) in Modell-Metern verschieben (alle Formen). */ -function translateDrawing(d: Drawing2D, dx: number, dy: number): Drawing2D { - const mv = (p: Vec2): Vec2 => ({ x: p.x + dx, y: p.y + dy }); - const g = d.geom; - switch (g.shape) { - case "line": return { ...d, geom: { ...g, a: mv(g.a), b: mv(g.b) } }; - case "xline": return { ...d, geom: { ...g, a: mv(g.a), b: mv(g.b) } }; - case "ray": return { ...d, geom: { ...g, a: mv(g.a), b: mv(g.b) } }; - case "polyline": return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; - case "rect": return { ...d, geom: { ...g, min: mv(g.min), max: mv(g.max) } }; - case "circle": return { ...d, geom: { ...g, center: mv(g.center) } }; - case "arc": return { ...d, geom: { ...g, center: mv(g.center) } }; - case "ellipse": return { ...d, geom: { ...g, center: mv(g.center) } }; - case "bezier": return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; - case "spline": return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; - case "dimension": return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; - case "kote": return { ...d, geom: { ...g, at: mv(g.at) } }; - case "detailref": return { ...d, geom: { ...g, at: mv(g.at) } }; - case "scalebar": return { ...d, geom: { ...g, at: mv(g.at) } }; - case "pointmarker": return { ...d, geom: { ...g, at: mv(g.at) } }; - case "text": - return { - ...d, - geom: { - ...g, - at: mv(g.at), - ...(g.leaderTarget ? { leaderTarget: mv(g.leaderTarget) } : {}), - ...(g.leaderBendPoints ? { leaderBendPoints: g.leaderBendPoints.map(mv) } : {}), - ...(g.pathPts ? { pathPts: g.pathPts.map(mv) } : {}), - }, - }; - case "block": return { ...d, geom: { ...g, at: mv(g.at) } }; - default: return d; - } -} - /** Modaler Import-Dialog-Zustand (DXF/DWG) — dieselbe Form wie in useDialogState. */ export type ImportDialogState = { fileName: string; isDwg: boolean; - parsed: DxfImportResult | null; + parsed: ParsedImport | null; loading?: boolean; /** Grober Phasenname während `loading` (DXF via `parseDxfAsync`'s * `onProgress`) — rein informativ, s. `ImportDialog.tsx`. */ @@ -158,13 +78,9 @@ function openProjectOrReport(content: string, notify: (msg: string, kind?: Notif export function useProjectFileActions( project: Project, - applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[])) => void, setImportState: (next: ImportDialogState) => void, setExportSaveFormat: (format: ExportSaveFormat | null) => void, activeCategoryCode: string, - addDrawingLevel: (name: string) => string, - importDrawings: (drawings: Drawing2D[]) => void, - addContextObjects: (objs: ContextObject[]) => void, setActiveLevelId: (id: string) => void, planViewRef: RefObject, ) { @@ -279,7 +195,7 @@ export function useProjectFileActions( setImportState({ fileName: src.fileName, isDwg: false, - parsed: { meshes: [], contours: [] }, + parsed: emptyImport(), loading: false, error: errorText(err), }); @@ -288,12 +204,14 @@ export function useProjectFileActions( // Vektor-PDF ([76]): Bytes und zuletzt gelesene Seite — Massstabswechsel rechnet nur um, ein // Seitenwechsel liest die Seite neu (Rust, synchron; das Format-Modul ist dann schon geladen). - const pdfSourceRef = useRef<{ fileName: string; bytes: Uint8Array; page: PdfVectorPage } | null>(null); + const pdfSourceRef = useRef<{ fileName: string; bytes: Uint8Array; read: PdfRead } | null>(null); - const pdfImportState = (fileName: string, page: PdfVectorPage, scale: number): ImportDialogState => ({ + const pdfImportState = (fileName: string, read: PdfRead, scale: number): ImportDialogState => { + const page = read.page; + return { fileName, isDwg: false, - parsed: pdfPageToImport(page, scale), + parsed: pdfImport(read, scale), loading: false, pdf: { pageCount: page.pageCount, @@ -304,7 +222,8 @@ export function useProjectFileActions( images: page.images, preview: page, }, - }); + }; + }; const openPdfImport = (file: File) => { pdfSourceRef.current = null; @@ -312,13 +231,13 @@ export function useProjectFileActions( void Promise.all([file.arrayBuffer(), loadFileio()]) .then(([buf]) => { const bytes = new Uint8Array(buf); - const page = readPdfVectorPage(bytes, 0); - pdfSourceRef.current = { fileName: file.name, bytes, page }; - setImportState(pdfImportState(file.name, page, 100)); + const read = readPdfVector(bytes, 0); + pdfSourceRef.current = { fileName: file.name, bytes, read }; + setImportState(pdfImportState(file.name, read, 100)); }) .catch((err) => { console.error("PDF-Import fehlgeschlagen:", err); - setImportState({ fileName: file.name, isDwg: false, parsed: { meshes: [], contours: [] }, loading: false, error: errorText(err) }); + setImportState({ fileName: file.name, isDwg: false, parsed: emptyImport(), loading: false, error: errorText(err) }); }); }; @@ -327,10 +246,10 @@ export function useProjectFileActions( const src = pdfSourceRef.current; if (!src || !(scale > 0)) return; try { - if (pageIndex !== src.page.pageIndex) src.page = readPdfVectorPage(src.bytes, pageIndex); - setImportState(pdfImportState(src.fileName, src.page, scale)); + if (pageIndex !== src.read.page.pageIndex) src.read = readPdfVector(src.bytes, pageIndex); + setImportState(pdfImportState(src.fileName, src.read, scale)); } catch (err) { - setImportState({ fileName: src.fileName, isDwg: false, parsed: { meshes: [], contours: [] }, loading: false, error: errorText(err) }); + setImportState({ fileName: src.fileName, isDwg: false, parsed: emptyImport(), loading: false, error: errorText(err) }); } }; @@ -408,7 +327,7 @@ export function useProjectFileActions( }) .catch((err) => { console.error("DXF-Import fehlgeschlagen:", err); - const parsed: DxfImportResult = { meshes: [], contours: [] }; + const parsed = emptyImport(); setImportState({ fileName: file.name, isDwg: false, parsed, loading: false, error: errorText(err) }); }); }; @@ -654,73 +573,41 @@ export function useProjectFileActions( const importParentName = (decision: ImportDecision): string => decision.target.kind === "new" ? decision.target.name : "DXF"; - // Bestätigte Import-Entscheidung ausführen: ggf. neue Zeichnung anlegen, die - // 2D-Konturen als Drawing2D anhängen, optional die Meshes als Kontext - // übernehmen. Reihenfolge: erst Ebene (echte ID), dann Drawings/Kontext. - // Alles als Ops in EINER Gruppe ([K4] S3): ein Import = ein Undo-Schritt. + // Bestätigte Import-Entscheidung ausführen: der Kern legt ggf. die neue Zeichnung an, ergänzt Kategorien + // je Layer und Linienstile (PDF-Strichmuster), hängt die 2D-Zeichnungen und optional die Meshes als + // Kontext an — als EIN Undo-Schritt ([K4] S4, `ProjectDocument.importDrawing`). const runImport = (decision: ImportDecision) => { // Hinweis bleibt, bis PlanView den neuen Plan gezeichnet hat (endBusyAfterPaint): // der Aufbau nach dem Einhängen blockiert noch einmal mehrere Sekunden. beginBusy(t("busy.import")); - getState().groupChanges(() => runImportSteps(decision)); - setImportState(null); - }; - const runImportSteps = (decision: ImportDecision) => { - const levelId = - decision.target.kind === "new" - ? addDrawingLevel(decision.target.name) - : decision.target.levelId; - // „DXF-Layer als Kategorien": fehlende Layer als Unterkategorien einer neuen - // Elternkategorie anlegen (vorher fielen sie ALLE auf die aktive Kategorie, - // bei Kataster-Importen „Wände"). Die Kategorien müssen VOR den Drawings im - // Projekt stehen, damit deren `categoryCode` auf etwas zeigt. - let codeByLayer: Map | undefined; - if (decision.categoryMode === "byLayer") { - const plan = planImportCategories( - distinctImportLayers(decision.parsed.contours, decision.parsed.texts ?? []), - flattenCategories(project.layers), - t("import.layers.parentName", { name: importParentName(decision) }), - decision.parsed.layerColors, - decision.parsed.layerLineWeights, + const center = decision.placement === "viewCenter" ? planViewRef.current?.viewCenterModel() : undefined; + let r: { levelId: string } | null = null; + try { + r = getState().commitImport((doc, base, now) => + doc.importDrawing( + base, + decision.parsed.src, + { + target: decision.target, + categoryMode: decision.categoryMode, + activeCategoryCode, + importMeshes: decision.importMeshes, + ...(center ? { viewCenter: [center.x, center.y] as [number, number] } : {}), + levelNameTemplate: t("default.drawingName", { n: "{n}" }), + parentName: t("import.layers.parentName", { name: importParentName(decision) }), + dashStyleTemplate: t("import.pdf.dashStyleName", { pattern: "{pattern}" }), + }, + now, + ), ); - codeByLayer = plan.codeByLayer; - if (plan.parent) { - const parent = plan.parent; - applyChange((p) => fieldOps(p, "layers", [...p.layers, parent])); - } + } catch (err) { + // Kaputter Puffer o. Ä. (Meldung des Kerns). + notify(`${t("import.failed")}: ${errorText(err)}`, "error"); } - // PDF-Strichmuster ([76]): passenden Linienstil nehmen oder Strichmuster-Stil anlegen (vor den Zeichnungen). - const dashPlan = planDashLineStyles(decision.parsed.layerDashes, project.lineStyles); - if (dashPlan.created.length) { - const created = dashPlan.created; - applyChange((p) => addItems("lineStyles", created.filter((c) => !p.lineStyles.some((l) => l.id === c.id)))); - } - let drawings = buildDrawings( - decision, - levelId, - project, - activeCategoryCode, - codeByLayer, - dashPlan.styleByLayer, - ); - // Platzierung „viewCenter": den Gesamt-Umriss so verschieben, dass seine - // Mitte auf die Mitte des aktuellen Ausschnitts fällt (sonst bleibt alles an - // den DXF-Koordinaten relativ zum Nullpunkt). - if (decision.placement === "viewCenter" && drawings.length) { - const center = planViewRef.current?.viewCenterModel(); - const bb = drawingsBBox(drawings); - if (center && bb) { - const dx = center.x - (bb.minX + bb.maxX) / 2; - const dy = center.y - (bb.minY + bb.maxY) / 2; - drawings = drawings.map((d) => translateDrawing(d, dx, dy)); - } - } - if (drawings.length) importDrawings(drawings); - if (decision.importMeshes && decision.parsed.meshes.length) { - addContextObjects(decision.parsed.meshes); - } - // Auf die Ziel-Ebene wechseln, damit die importierte Geometrie sichtbar ist. - setActiveLevelId(levelId); + setImportState(null); + // Auf die Ziel-Ebene wechseln, damit die importierte Geometrie sichtbar ist (zurückgewiesen: Hinweis weg). + if (r) setActiveLevelId(r.levelId); + else endBusy(); }; return { diff --git a/src/ui/IfcImportDialog.tsx b/src/ui/IfcImportDialog.tsx index eba9ecf0..1a32bf61 100644 --- a/src/ui/IfcImportDialog.tsx +++ b/src/ui/IfcImportDialog.tsx @@ -1,5 +1,5 @@ // 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`). +// Bauteile (Kern `import_ifc.rs`). Overlay-Muster wie `UnsavedChangesDialog` (kein `window.confirm`). import { useEffect, useState } from "react"; import { t } from "../i18n"; diff --git a/src/ui/ImportDialog.tsx b/src/ui/ImportDialog.tsx index 9536eef7..ed0103a6 100644 --- a/src/ui/ImportDialog.tsx +++ b/src/ui/ImportDialog.tsx @@ -8,8 +8,8 @@ // Muster wie ResourceManager: abgedunkeltes Overlay, Klick auf den Hintergrund // und Esc schließen. Diese Komponente HÄLT nur Formular-Zustand und liefert beim // Bestätigen eine strukturierte Entscheidung (`ImportDecision`) nach oben; die -// eigentlichen Store-Mutationen (Ebene anlegen, Drawings anhängen, Kontext) -// führt App in der richtigen Reihenfolge aus. +// eigentliche Umwandlung (Ebene anlegen, Kategorien, Zeichnungen, Kontext) macht +// der Kern als EIN Undo-Schritt (`ProjectDocument.importDrawing`, [K4] S4). // // Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). Alle sichtbaren // Texte über t(...). @@ -17,16 +17,8 @@ import { useEffect, useState } from "react"; import { t } from "../i18n"; import type { TranslationKey } from "../i18n"; -import type { DrawingLevelKind, ImportedMesh, Project } from "../model/types"; -import { flattenCategories } from "../model/types"; -import type { DxfImportResult, ImportDiagnostics } from "../io/dxfParser"; -import { - contoursToDrawings, - textsToDrawings, - countContours, - distinctLayers, -} from "../io/dxfToDrawings"; -import type { CategoryMode } from "../io/dxfToDrawings"; +import type { DrawingLevelKind, Project } from "../model/types"; +import type { ImportDiagnostics, ParsedImport } from "../io/importSource"; import { Dropdown } from "./Dropdown"; import { PDF_SCALES, PT_TO_MM } from "../io/pdfVector"; import type { PdfVectorPage } from "../io/pdfVector"; @@ -48,6 +40,9 @@ export interface PdfImportOptions { preview: PdfVectorPage; } +/** Wie Layer auf Kategorien abgebildet werden: je Layer eine Kategorie oder alles auf die aktive. */ +export type CategoryMode = "active" | "byLayer"; + /** Strukturierte Import-Entscheidung, die der Dialog beim Bestätigen liefert. */ export interface ImportDecision { /** Ziel: bestehende Ebene (id) ODER neue Zeichnung (name). */ @@ -62,8 +57,8 @@ export interface ImportDecision { * des aktuellen Ausschnitts geschoben. */ placement: "origin" | "viewCenter"; - /** Die geparsten Konturen-Sätze (für die spätere 2D-Konvertierung). */ - parsed: DxfImportResult; + /** Die gelesene Datei (Puffer für den Kern, `ProjectDocument.importDrawing`). */ + parsed: ParsedImport; } /** @@ -131,7 +126,7 @@ export interface ImportDialogProps { /** Wählt ein Papierbereich-Layout (Name) oder den Modellraum (`null`) zum Import; liest neu. */ onSelectLayout?: (layout: string | null) => void; /** Geparstes Ergebnis (null während Laden / bei DWG-Parse-Fehler). */ - parsed: DxfImportResult | null; + parsed: ParsedImport | null; /** Vektor-PDF ([76]): Seite/Massstab; `onPdfChange` liest neu bzw. rechnet um. */ pdf?: PdfImportOptions; onPdfChange?: (page: number, scale: number) => void; @@ -165,14 +160,13 @@ export function ImportDialog({ return () => window.removeEventListener("keydown", onKey); }, [onClose]); - const contourSets = parsed?.contours ?? []; - const meshes: ImportedMesh[] = parsed?.meshes ?? []; - const texts = parsed?.texts ?? []; - const contourCount = countContours(contourSets); - const textCount = texts.length; - const layers = distinctLayers(contourSets); + const summary = parsed?.summary; + const contourCount = summary?.contours ?? 0; + const textCount = summary?.texts ?? 0; + const meshCount = summary?.meshes ?? 0; + const layers = summary?.layers ?? []; const hasDrawings = contourCount > 0 || textCount > 0; - const hasMeshes = meshes.length > 0; + const hasMeshes = meshCount > 0; // ── Formular-Zustand ────────────────────────────────────────────────────── const firstLevelId = project.drawingLevels[0]?.id ?? ""; @@ -299,14 +293,14 @@ export function ImportDialog({ {textCount > 0 && (
  • {t("import.summary.texts", { n: textCount })}
  • )} -
  • {t("import.summary.meshes", { n: meshes.length })}
  • +
  • {t("import.summary.meshes", { n: meshCount })}
  • {layers.length > 0 ? t("import.summary.layers", { layers: layers.join(", ") }) : t("import.summary.noLayers")}
  • - {parsed?.recovered &&
    {t("import.summary.recovered")}
    } + {summary?.recovered &&
    {t("import.summary.recovered")}
    } {!hasDrawings && !hasMeshes && (
    {error ?? t("import.summary.empty")} @@ -315,9 +309,9 @@ export function ImportDialog({ Abdeckungslücke (z. B. „500 ARC, 200 INSERT"). Entity-Typ- Codes + Zahlen sind technische DWG-Bezeichner (Daten, keine übersetzbare Prosa). */} - {parsed?.diagnostics && ( + {summary?.diagnostics && (
    - {formatDiagnostics(parsed.diagnostics)} + {formatDiagnostics(summary.diagnostics)}
    )}
    @@ -391,17 +385,17 @@ export function ImportDialog({ )} {/* Papierbereich: Layouts der Datei (Bericht) und, wenn möglich, eines statt des Modellraums lesen. */} - {parsed?.layouts && parsed.layouts.length > 0 && ( + {summary?.layouts && summary.layouts.length > 0 && (
    {t("import.layouts.heading")}
    {onSelectLayout ? ( onSelectLayout(v === "" ? null : v)} title={t("import.layouts.heading")} options={[ { value: "", label: t("import.layouts.model") }, - ...parsed.layouts.map((l) => ({ + ...summary.layouts.map((l) => ({ value: l.name, label: `${l.name} · ${t("import.layouts.entities", { n: l.entities })}`, })), @@ -409,7 +403,7 @@ export function ImportDialog({ /> ) : (
      - {parsed.layouts.map((l) => ( + {summary.layouts.map((l) => (
    • {`${l.name} · ${t("import.layouts.entities", { n: l.entities })}`}
    • ))}
    @@ -561,54 +555,3 @@ export function ImportDialog({ ); } - -/** - * Baut aus einer Import-Entscheidung die fertigen Drawing2D-Elemente für die - * Ziel-Ebene `levelId`. `byLayer` mappt jeden DXF-Layer-Namen deterministisch - * auf einen Kategorie-Code: existiert eine Kategorie mit passendem Namen, wird - * deren Code genutzt; sonst fällt der Layer auf den aktiven Code zurück. - * - * (Die App ruft diese Funktion, NACHDEM sie ggf. die neue Ebene angelegt hat — - * sie braucht die echte Ziel-`levelId`.) - */ -export function buildDrawings( - decision: ImportDecision, - levelId: string, - project: Project, - activeCategoryCode: string, - codeByLayer?: ReadonlyMap, - lineStyleByLayer?: ReadonlyMap, -) { - // Layer-Name → Kategorie-Code: bevorzugt eine Kategorie mit demselben Namen - // (case-insensitiv), sonst der aktive Code. Identifier bleiben so stabil. - // `flattenCategories`, NICHT `project.layers` direkt: manche Kategorien - // (z. B. „Gebäude"/„Situation") liegen als KINDER unter „05 Kontext" (s. - // sampleProject.ts) — ein flacher Scan hätte sie beim Namensabgleich - // übersehen (Regression, beim Verschachteln der Kontext-Kategorien - // gefunden). - const byName = new Map(); - for (const c of flattenCategories(project.layers)) byName.set(c.name.toLowerCase(), c.code); - // `codeByLayer` (aus `planImportCategories`) hat Vorrang: dort sind auch die - // beim Import NEU angelegten Kategorien enthalten, die `project` hier (Stand - // vor dem Import) noch nicht kennt. - const layerToCode = (layerName: string): string => - codeByLayer?.get(layerName) ?? byName.get(layerName.toLowerCase()) ?? activeCategoryCode; - const fillColors = decision.parsed.layerFillColors; - const fromContours = contoursToDrawings( - decision.parsed.contours, - levelId, - decision.categoryMode, - activeCategoryCode, - layerToCode, - fillColors ? (layer) => fillColors[layer] : undefined, - lineStyleByLayer ? (layer) => lineStyleByLayer.get(layer) : undefined, - ); - const fromTexts = textsToDrawings( - decision.parsed.texts ?? [], - levelId, - decision.categoryMode, - activeCategoryCode, - layerToCode, - ); - return [...fromContours, ...fromTexts]; -} diff --git a/src/ui/MeshImportDialog.tsx b/src/ui/MeshImportDialog.tsx index fe3429df..c14d38c9 100644 --- a/src/ui/MeshImportDialog.tsx +++ b/src/ui/MeshImportDialog.tsx @@ -2,11 +2,11 @@ // Achse und Platzierung. Einmal in App eingehängt (`MeshImportHost`); geöffnet über Menü // (`openMeshFileDialog`) oder Drag & Drop (`requestMeshImport`). Die Datei wird beim Öffnen und bei jeder // Änderung von Einheit/Achse im Web-Worker gelesen (`readMesh`); der Dialog zeigt die erkannte Achse und die -// Ausdehnung, „Importieren" übernimmt das zuletzt gelesene Ergebnis (kein zweites Lesen). +// Ausdehnung (beides aus dem Kern), „Importieren" übernimmt das zuletzt gelesene Ergebnis (kein zweites Lesen). // // Muster: PointCloudImportDialog (abgedunkeltes Overlay, Esc/Hintergrund schliessen). -import { useEffect, useMemo, useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { t } from "../i18n"; import { Dropdown } from "./Dropdown"; import { @@ -15,39 +15,21 @@ import { MESH_UNITS, MISSING_EXTERNAL_PREFIX, NO_FACES_PREFIX, - meshObjectsToImportedMeshes, readMesh, } from "../io/meshImport"; -import type { MeshImportReport, MeshObject, MeshPlacement, MeshUnit, MeshUp } from "../io/meshImport"; +import type { MeshPlacement, MeshRead, MeshUnit, MeshUp } from "../io/meshImport"; import { closeMeshImport, registerMeshFileInput, requestMeshImport, splitMeshFiles, useMeshImportRequest } from "../state/meshImportStore"; import type { MeshImportRequest } from "../state/meshImportStore"; import { requestPointCloudImport } from "../state/pointCloudStore"; -import { projectGeoOrigin } from "../core"; -import type { ImportedMesh, Project } from "../model/types"; export interface MeshImportHostProps { - project: Project; - onImport: (meshes: ImportedMesh[], report: MeshImportReport) => void; + /** Übernehmen: der Kern macht aus dem gelesenen Modell Kontext-Meshes (`ProjectDocument.importMesh`). */ + onImport: (read: MeshRead, fileName: string, placement: MeshPlacement) => void; notify: (message: string, kind?: "info" | "warning" | "error") => void; } const fmt = (n: number) => (Math.abs(n) >= 100 ? n.toFixed(0) : n.toFixed(1)); -/** Ausdehnung aller Objekte (Meter, Modell-Achsen). */ -function extent(objects: readonly MeshObject[]): [number, number, number] { - const lo = [Infinity, Infinity, Infinity]; - const hi = [-Infinity, -Infinity, -Infinity]; - for (const o of objects) { - for (let i = 0; i + 2 < o.positions.length; i += 3) { - for (let a = 0; a < 3; a++) { - if (o.positions[i + a] < lo[a]) lo[a] = o.positions[i + a]; - if (o.positions[i + a] > hi[a]) hi[a] = o.positions[i + a]; - } - } - } - return [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]]; -} - /** Namen der fehlenden Begleitdateien aus der Rust-Meldung. */ function missingList(message: string): string { const m = /fehlen: (.*?) \(mit der/.exec(message); @@ -58,7 +40,7 @@ async function bytesOf(f: File): Promise { return new Uint8Array(await f.arrayBuffer()); } -function MeshImportDialog({ req, project, onImport, notify }: { req: MeshImportRequest } & MeshImportHostProps) { +function MeshImportDialog({ req, onImport, notify }: { req: MeshImportRequest } & MeshImportHostProps) { const { file, sidecars } = req; const isGltf = /\.(gltf|glb)$/i.test(file.name); const [unit, setUnit] = useState("m"); @@ -66,7 +48,7 @@ function MeshImportDialog({ req, project, onImport, notify }: { req: MeshImportR const [placement, setPlacement] = useState("center"); const [busy, setBusy] = useState(true); const [error, setError] = useState(null); - const [result, setResult] = useState<{ objects: MeshObject[]; report: MeshImportReport } | null>(null); + const [result, setResult] = useState(null); const seq = useRef(0); // Dateiinhalt einmal laden, nicht bei jeder Änderung. const cache = useRef<{ main: Uint8Array; files: { name: string; bytes: Uint8Array }[] } | null>(null); @@ -114,14 +96,13 @@ function MeshImportDialog({ req, project, onImport, notify }: { req: MeshImportR })(); }, [file, sidecars, unit, up]); - const dims = useMemo(() => (result ? extent(result.objects) : null), [result]); + const dims = result?.extent ?? null; const r = result?.report; const onDo = () => { if (!result) return; - const meshes = meshObjectsToImportedMeshes(result.objects, file.name, { placement, geoOrigin: projectGeoOrigin(project) }); closeMeshImport(); - onImport(meshes, result.report); + onImport(result, file.name, placement); }; return (