[K4] Merge: S4 Import-Umwandlung im Kern (DXF/DWG, PDF, IFC, Meshes; ein Undo-Schritt)

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-29 15:06:17 +00:00
commit b56b55bba7
55 files changed
+3592 -2529

No files matched your search

+30
View File
@@ -804,6 +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.):** 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.
+13 -27
View File
@@ -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 <pfad.dxf|pfad.dwg>` (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);
+500
View File
@@ -0,0 +1,500 @@
//! Kontext-Meshes aus Importen ([K4] S4, vorher `io/ifcImport.ts::ifcToImportedMeshes`,
//! `io/meshImport.ts::meshObjectsToImportedMeshes`, `model/contextCategories.ts::ensureContextCategories`
//! und die Op-Bauer im CLI/`siteSlice`): IFC-Bauteile ([B3]) und Objekte aus OBJ/STL/glTF/PLY ([C11]) werden
//! zu `ImportedMesh` der Kontext-Schicht, fehlende Kontext-Kategorien werden im Ebenen-Baum ergänzt.
//!
//! Eingaben sind die flachen Puffer des Format-Moduls (`fileio/src/ifc_import.rs`: Bericht als JSON +
//! Positionen/Indizes; `fileio/src/mesh_import.rs`: Zahlenpuffer + Strings). Zahlen wie in der TS-Fassung
//! (`Math.hypot`, `Math.round`), ids aus Zeit (Basis 36) + Zähler.
use crate::grips::js_num;
use crate::import_drawing::{next_seq, GENERIC_IMPORT_CODE};
use crate::jsmath;
use crate::jsnum;
use crate::ops::Op;
use serde_json::{json, Map, Value};
use std::collections::{HashMap, HashSet};
// ── Kontext-Kategorien ───────────────────────────────────────────────────────
struct Def {
code: &'static str,
name: &'static str,
color: &'static str,
lw: f64,
}
/// „05 Kontext" — Elternkategorie der Kontext-Kategorien.
const CONTEXT_PARENT: Def = Def { code: "05", name: "Kontext", color: "#707078", lw: 0.13 };
/// „31 Dächer" bleibt oberste Ebene.
const IMPORTED_ROOF: Def = Def { code: "31", name: "Dächer", color: "#7a4a3a", lw: 0.35 };
/// Kinder von „05 Kontext", in dieser Reihenfolge (`NESTED_CONTEXT_CATEGORIES`).
const NESTED: [Def; 10] = [
Def { code: "02", name: "Gelände", color: "#8a9478", lw: 0.13 },
Def { code: "03", name: "Luftbild", color: "#707078", lw: 0.13 },
Def { code: "10", name: "Situation", color: "#909090", lw: 0.18 },
Def { code: "12", name: "Gebäude", color: "#888888", lw: 0.25 },
Def { code: "11", name: "Strasse", color: "#a89070", lw: 0.18 },
Def { code: "04", name: "Wald", color: "#3a7a3a", lw: 0.13 },
Def { code: "15", name: "Parkplätze", color: "#a0a0a0", lw: 0.13 },
Def { code: "16", name: "Bahn", color: "#606060", lw: 0.18 },
Def { code: "17", name: "Gewässer", color: "#5a90b0", lw: 0.13 },
Def { code: "18", name: "Grünflächen", color: "#70b070", lw: 0.13 },
];
fn category(d: &Def) -> Value {
json!({"code": d.code, "name": d.name, "color": d.color, "lw": d.lw, "visible": true, "locked": false})
}
/// Ergänzt `layers` um jede fehlende Kontext-Kategorie aus `codes` (vorhandene Codes, auch umbenannte, bleiben).
/// Fehlende Kinder landen unter „05 Kontext" (bei Bedarf angelegt), „31 Dächer" oben. `true` = geändert.
pub fn ensure_context_categories<'a>(layers: &mut Vec<Value>, codes: impl IntoIterator<Item = &'a str>) -> bool {
let existing: HashSet<String> =
crate::layers::flatten(layers).into_iter().filter_map(|c| c.get("code").and_then(Value::as_str).map(str::to_string)).collect();
let missing: HashSet<&str> = codes.into_iter().filter(|c| !existing.contains(*c)).collect();
if missing.is_empty() {
return false;
}
let nested: Vec<Value> = NESTED.iter().filter(|d| missing.contains(d.code)).map(category).collect();
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();
let mut kids = l.get("children").and_then(Value::as_array).cloned().unwrap_or_default();
kids.extend(nested);
l.insert("children".into(), Value::Array(kids));
layers[i] = Value::Object(l);
}
None => {
let mut p = category(&CONTEXT_PARENT);
p.as_object_mut().unwrap().insert("children".into(), Value::Array(nested));
layers.push(p);
}
}
}
let roof = missing.contains(IMPORTED_ROOF.code);
if roof {
layers.push(category(&IMPORTED_ROOF));
}
added_nested || roof
}
/// Ops: Kontext-Objekte anhängen (fehlt die Liste, wird sie gesetzt) und fehlende Kontext-Kategorien ergänzen.
pub fn context_ops(root: &Map<String, Value>, meshes: Vec<Value>) -> Vec<Op> {
let codes: Vec<String> = meshes.iter().filter_map(|m| m.get("categoryCode").and_then(Value::as_str).filter(|c| !c.is_empty()).map(str::to_string)).collect();
let mut ops = Vec::new();
if root.get("context").is_some_and(|c| !c.is_null()) {
if !meshes.is_empty() {
ops.push(Op::Add { collection: "context".into(), items: meshes, at: None });
}
} else {
ops.push(Op::SetField { key: "context".into(), value: Some(Value::Array(meshes)), at: None });
}
let mut layers = root.get("layers").and_then(Value::as_array).cloned().unwrap_or_default();
if ensure_context_categories(&mut layers, codes.iter().map(String::as_str)) {
ops.push(Op::SetField { key: "layers".into(), value: Some(Value::Array(layers)), at: None });
}
ops
}
// ── Gemeinsames ──────────────────────────────────────────────────────────────
/// `Date.now().toString(36)`.
pub fn stamp36(now: f64) -> String {
let mut n = if now.is_finite() && now > 0.0 { now.trunc() as u64 } else { 0 };
if n == 0 {
return "0".into();
}
let mut d = Vec::new();
while n > 0 {
d.push(std::char::from_digit((n % 36) as u32, 36).unwrap());
n /= 36;
}
d.iter().rev().collect()
}
/// Dateiname ohne letzte Endung (`name.replace(/\.[^.]+$/, "")`), leer → `fallback`.
pub fn base_name(file: &str, fallback: &str) -> String {
let b = match file.rfind('.') {
Some(i) if i + 1 < file.len() => &file[..i],
_ => file,
};
if b.is_empty() { fallback.to_string() } else { b.to_string() }
}
/// RGBA 0..1 → `#rrggbb` (`rgbToHex`, Alpha entfällt); `None` ohne gültige Farbe.
pub fn color_hex(c: Option<&[f64]>) -> Option<String> {
let c = c?;
if c.len() < 3 || !c[..3].iter().all(|v| v.is_finite()) {
return None;
}
let h = |v: f64| jsnum::max(0.0, jsnum::min(255.0, jsnum::round(v * 255.0))) as u32;
Some(format!("#{:02x}{:02x}{:02x}", h(c[0]), h(c[1]), h(c[2])))
}
/// Farbe eines JSON-Werts (`[r, g, b, a]` oder `null`).
pub fn color_of(v: Option<&Value>) -> Option<Vec<f64>> {
v?.as_array().map(|a| a.iter().map(|x| x.as_f64().unwrap_or(f64::NAN)).collect())
}
fn mesh_value(id: String, name: String, layer: &str, color: Option<String>, extra: Option<(&str, &str)>, positions: Vec<Value>, indices: Vec<Value>) -> Value {
let mut o = Map::new();
o.insert("id".into(), id.into());
o.insert("type".into(), "importedMesh".into());
o.insert("name".into(), name.into());
o.insert("layer".into(), layer.into());
o.insert("categoryCode".into(), GENERIC_IMPORT_CODE.into());
if let Some(c) = color {
o.insert("color".into(), c.into());
}
if let Some((k, v)) = extra {
o.insert(k.into(), v.into());
}
o.insert("positions".into(), Value::Array(positions));
o.insert("indices".into(), Value::Array(indices));
Value::Object(o)
}
/// Positionen (verschoben) und Indizes mehrerer Teile hintereinander.
fn arrays<'a>(parts: impl Iterator<Item = (&'a [f64], &'a [f64])>, d: [f64; 3]) -> (Vec<Value>, Vec<Value>) {
let mut pos = Vec::new();
let mut idx = Vec::new();
for (p, ix) in parts {
let off = (pos.len() / 3) as f64;
let mut i = 0;
while i + 2 < p.len() {
pos.push(js_num(p[i] + d[0]));
pos.push(js_num(p[i + 1] + d[1]));
pos.push(js_num(p[i + 2] + d[2]));
i += 3;
}
for &k in ix {
idx.push(js_num(k + off));
}
}
(pos, idx)
}
/// Gruppen in Reihenfolge des ersten Auftretens.
fn group_by<T>(items: &[T], key: impl Fn(&T) -> String) -> Vec<Vec<usize>> {
let mut at: HashMap<String, usize> = HashMap::new();
let mut groups: Vec<Vec<usize>> = Vec::new();
for (i, it) in items.iter().enumerate() {
let k = key(it);
match at.get(&k) {
Some(&g) => groups[g].push(i),
None => {
at.insert(k, groups.len());
groups.push(vec![i]);
}
}
}
groups
}
/// LV95-Ursprung des Projekts (`projectGeoOrigin`: `geoAnchor.lv95 − geoAnchor.model`), ohne Bezug `None`.
pub fn project_geo_origin(root: &Map<String, Value>) -> Option<[f64; 2]> {
let a = root.get("geoAnchor").filter(|a| crate::grips::truthy(Some(a)))?;
let n = |p: &str, k: &str| a.get(p).and_then(|o| o.get(k)).and_then(Value::as_f64).unwrap_or(f64::NAN);
Some([n("lv95", "e") - n("model", "x"), n("lv95", "n") - n("model", "y")])
}
// ── IFC ([B3]) ───────────────────────────────────────────────────────────────
/// Ab so vielen Bauteilen bzw. Objekten wird zusammengelegt.
pub const MAX_SINGLE: usize = 2000;
/// Ein gelesenes IFC-Bauteil (Ansichten in die flachen Puffer).
pub struct IfcProduct<'a> {
pub global_id: String,
pub ifc_class: String,
pub name: Option<String>,
pub storey: Option<String>,
pub color: Option<Vec<f64>>,
pub classifications: Vec<Value>,
pub positions: &'a [f64],
pub indices: &'a [f64],
}
fn opt_str(v: Option<&Value>) -> Option<String> {
v.and_then(Value::as_str).map(str::to_string)
}
/// Bauteile aus dem Bericht (`meta.products`) und den Puffern (vorher `decodeIfc`).
pub fn decode_ifc_products<'a>(meta: &Value, positions: &'a [f64], indices: &'a [f64]) -> Result<Vec<IfcProduct<'a>>, String> {
let list = meta.get("products").and_then(Value::as_array).ok_or("IFC-Bericht ohne Bauteile")?;
let (mut po, mut io) = (0usize, 0usize);
let mut out = Vec::with_capacity(list.len());
for p in list {
let pc = p.get("positionCount").and_then(Value::as_u64).unwrap_or(0) as usize;
let ic = p.get("indexCount").and_then(Value::as_u64).unwrap_or(0) as usize;
let pe = (po + pc).min(positions.len());
let ie = (io + ic).min(indices.len());
out.push(IfcProduct {
global_id: opt_str(p.get("globalId")).unwrap_or_default(),
ifc_class: opt_str(p.get("ifcClass")).unwrap_or_default(),
name: opt_str(p.get("name")),
storey: opt_str(p.get("storey")),
color: color_of(p.get("color")),
classifications: p.get("classifications").and_then(Value::as_array).cloned().unwrap_or_default(),
positions: &positions[po.min(pe)..pe],
indices: &indices[io.min(ie)..ie],
});
po += pc;
io += ic;
}
Ok(out)
}
/// Verschiebung, falls die Datei in Landeskoordinaten liegt und das Projekt einen Bezug hat (`geoShift`);
/// `extra` = weitere Punkte (x, y flach).
pub fn geo_shift(products: &[IfcProduct], origin: Option<[f64; 2]>, extra: &[f64]) -> [f64; 2] {
let Some(o) = origin else { return [0.0, 0.0] };
let (mut sx, mut sy, mut n) = (0.0, 0.0, 0.0);
for p in products {
let mut i = 0;
while i + 2 < p.positions.len() {
sx += p.positions[i];
sy += p.positions[i + 1];
n += 1.0;
i += 3 * 64;
}
}
let mut i = 0;
while i + 1 < extra.len() {
sx += extra[i];
sy += extra[i + 1];
n += 1.0;
i += 2;
}
if n == 0.0 {
return [0.0, 0.0];
}
let (cx, cy) = (sx / n, sy / n);
if jsmath::hypot2(cx - o[0], cy - o[1]) < jsmath::hypot2(cx, cy) {
[-o[0], -o[1]]
} else {
[0.0, 0.0]
}
}
/// Klassifikation als Namenszusatz (` [eBKP-H C]`), nur die erste; ohne leer.
pub fn classification_suffix(list: &[Value]) -> String {
let Some(c) = list.first() else { return String::new() };
let parts: Vec<&str> = [c.get("system"), c.get("code")].iter().filter_map(|v| v.and_then(Value::as_str)).filter(|s| !s.is_empty()).collect();
format!(" [{}]", parts.join(" "))
}
/// Gruppierung: `"product"`, `"class"` oder `"auto"` (nach [`MAX_SINGLE`]).
pub fn ifc_meshes(products: &[IfcProduct], file_name: &str, group: &str, shift: [f64; 2], now: f64) -> Vec<Value> {
let base = base_name(file_name, "IFC");
let stamp = stamp36(now);
let d = [shift[0], shift[1], 0.0];
let per_product = group == "product" || (group != "class" && products.len() <= MAX_SINGLE);
if per_product {
return products
.iter()
.map(|p| {
let label = [p.storey.as_deref(), Some(p.name.as_deref().filter(|n| !n.is_empty()).unwrap_or(&p.ifc_class))]
.into_iter()
.flatten()
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join(": ");
let (pos, idx) = arrays(std::iter::once((p.positions, p.indices)), d);
let gid = (!p.global_id.is_empty()).then_some(("ifcGlobalId", p.global_id.as_str()));
mesh_value(
format!("imported-ifc-{stamp}-{}", next_seq()),
label + &classification_suffix(&p.classifications),
&p.ifc_class,
color_hex(p.color.as_deref()),
gid,
pos,
idx,
)
})
.collect();
}
group_by(products, |p| format!("{}\u{0}{}", p.ifc_class, p.storey.as_deref().unwrap_or("")))
.into_iter()
.map(|g| {
let first = &products[g[0]];
let colors: HashSet<String> = g.iter().map(|&i| color_hex(products[i].color.as_deref()).unwrap_or_default()).collect();
let color = if colors.len() == 1 { colors.into_iter().next().filter(|c| !c.is_empty()) } else { None };
let label = [first.storey.as_deref(), Some(first.ifc_class.as_str())].into_iter().flatten().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" ");
let (pos, idx) = arrays(g.iter().map(|&i| (products[i].positions, products[i].indices)), d);
mesh_value(format!("imported-ifc-{stamp}-{}", next_seq()), format!("{base}: {label} ({})", g.len()), &first.ifc_class, color, None, pos, idx)
})
.collect()
}
/// Bericht des IFC-Imports: Bericht des Lesers mit `products` = Anzahl, dazu Bauteile je Klasse und Dreiecke.
pub fn ifc_report(meta: &Value, products: &[IfcProduct]) -> Value {
let mut r = meta.as_object().cloned().unwrap_or_default();
r.insert("products".into(), products.len().into());
let mut by_class = Map::new();
for p in products {
let n = by_class.get(&p.ifc_class).and_then(Value::as_f64).unwrap_or(0.0) + 1.0;
by_class.insert(p.ifc_class.clone(), js_num(n));
}
let tris: f64 = products.iter().map(|p| p.indices.len() as f64 / 3.0).sum();
r.insert("byClass".into(), Value::Object(by_class));
r.insert("triangles".into(), js_num(tris));
Value::Object(r)
}
// ── Allgemeine Meshes ([C11]) ────────────────────────────────────────────────
pub struct MeshObject {
pub name: String,
pub group: String,
pub color: Option<Vec<f64>>,
pub positions: Vec<f64>,
pub indices: Vec<f64>,
}
const MESH_FORMATS: [&str; 4] = ["obj", "stl", "gltf", "ply"];
/// Flache Puffer → Objekte + Bericht (vorher `decodeMesh`, Aufbau: Kopf von `mesh_import.rs`).
pub fn decode_mesh(f: &[f64], strings: &[String]) -> Result<(Vec<MeshObject>, Value), String> {
const HEAD: usize = 12;
if f.len() < HEAD || f[0] != 1.0 {
return Err("Mesh-Import: unbekannte Kodierung".into());
}
let s = |k: f64| if k >= 0.0 && k.fract() == 0.0 { strings.get(k as usize).cloned().unwrap_or_default() } else { String::new() };
let n_warn = f[10];
let n_obj = f[11];
let mut at = HEAD;
let mut warnings = Vec::new();
let mut k = 0.0;
while k < n_warn {
warnings.push(Value::String(s(*f.get(at).ok_or("Mesh-Import: Puffer beschädigt")?)));
at += 1;
k += 1.0;
}
let mut objects = Vec::new();
let mut k = 0.0;
while k < n_obj {
let h = f.get(at..at + 9).ok_or("Mesh-Import: Puffer beschädigt")?;
let name = s(h[0]);
let group = if h[1] >= 0.0 { s(h[1]) } else { String::new() };
let color = (h[2] == 1.0).then(|| vec![h[3], h[4], h[5], h[6]]);
let (np, ni) = (h[7], h[8]);
at += 9;
if !(np.fract() == 0.0 && ni.fract() == 0.0 && np >= 0.0 && ni >= 0.0) || at + np as usize + ni as usize > f.len() {
return Err("Mesh-Import: Puffer beschädigt".into());
}
let positions = f[at..at + np as usize].to_vec();
at += np as usize;
// Wie `Uint32Array`: ganzzahlig modulo 2³².
let indices = f[at..at + ni as usize].iter().map(|&x| (jsnum::to_int32(x) as u32) as f64).collect();
at += ni as usize;
objects.push(MeshObject { name, group, color, positions, indices });
k += 1.0;
}
let report = json!({
"format": MESH_FORMATS.get(f[1] as usize).copied().filter(|_| f[1] >= 0.0 && f[1].fract() == 0.0).unwrap_or("obj"),
"up": if f[2] == 1.0 { "y" } else { "z" },
"upAuto": f[3] == 1.0,
"upCertain": f[4] == 1.0,
"unitScale": js_num(f[5]),
"triangles": js_num(f[6]),
"degenerate": js_num(f[7]),
"badFaces": js_num(f[8]),
"truncated": f[9] == 1.0,
"warnings": warnings,
"objects": objects.len(),
});
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] {
let (mut min_x, mut max_x, mut min_y, mut max_y, mut min_z) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY);
for o in objects {
let p = &o.positions;
let mut i = 0;
while i + 2 < p.len() {
if p[i] < min_x {
min_x = p[i];
}
if p[i] > max_x {
max_x = p[i];
}
if p[i + 1] < min_y {
min_y = p[i + 1];
}
if p[i + 1] > max_y {
max_y = p[i + 1];
}
if p[i + 2] < min_z {
min_z = p[i + 2];
}
i += 3;
}
}
if !min_x.is_finite() {
return [0.0, 0.0, 0.0];
}
let cx = (min_x + max_x) / 2.0;
let cy = (min_y + max_y) / 2.0;
if placement != "original" {
return [-cx, -cy, -min_z];
}
match origin {
Some(o) if jsmath::hypot2(cx - o[0], cy - o[1]) < jsmath::hypot2(cx, cy) => [-o[0], -o[1], 0.0],
_ => [0.0, 0.0, 0.0],
}
}
/// Objekte → Kontext-Meshes (`layer` = Gruppe, sonst Dateiname); `group`: `"object"`, `"merge"`, `"auto"`.
pub fn mesh_objects_to_meshes(objects: &[MeshObject], file_name: &str, placement: &str, origin: Option<[f64; 2]>, group: &str, now: f64) -> Vec<Value> {
let base = base_name(file_name, "Mesh");
let d = mesh_shift(objects, placement, origin);
let stamp = stamp36(now);
let merge = group == "merge" || (group != "object" && objects.len() > MAX_SINGLE);
if !merge {
return objects
.iter()
.enumerate()
.map(|(i, o)| {
let (pos, idx) = arrays(std::iter::once((o.positions.as_slice(), o.indices.as_slice())), d);
let name = if o.name.is_empty() { format!("{base} {}", i + 1) } else { o.name.clone() };
let layer = if o.group.is_empty() { base.as_str() } else { o.group.as_str() };
mesh_value(format!("imported-mesh-{stamp}-{}", next_seq()), name, layer, color_hex(o.color.as_deref()), None, pos, idx)
})
.collect();
}
group_by(objects, |o| format!("{}\u{0}{}", o.group, color_hex(o.color.as_deref()).unwrap_or_default()))
.into_iter()
.map(|g| {
let first = &objects[g[0]];
let (pos, idx) = arrays(g.iter().map(|&i| (objects[i].positions.as_slice(), objects[i].indices.as_slice())), d);
let gname = &first.group;
let name = format!("{base}{} ({})", if gname.is_empty() { String::new() } else { format!(": {gname}") }, g.len());
let layer = if gname.is_empty() { base.as_str() } else { gname.as_str() };
mesh_value(format!("imported-mesh-{stamp}-{}", next_seq()), name, layer, color_hex(first.color.as_deref()), None, pos, idx)
})
.collect()
}
+937
View File
@@ -0,0 +1,937 @@
//! Zeichnungs-Import ([K4] S4, vorher `io/dxfParser.ts::decodeImport`, `io/dxfToDrawings.ts`,
//! `io/pdfVector.ts::pdfPageToImport`, `io/pdfLineStyles.ts`, `ui/ImportDialog.tsx::buildDrawings` und
//! `state/useProjectFileActions.ts::runImport`): das Format-Modul (`src-tauri/fileio`, eigenes WASM) liest
//! DXF/DWG bzw. eine PDF-Seite in einen flachen Puffer + String-Tabelle; hier wird daraus die Import-Form
//! ([`DrawingImport`]: Konturen, Texte, Meshes, Ebenenfarben …), die Zusammenfassung für den Dialog
//! ([`summary_json`]) und die Ops, die alles ins Projekt bringen ([`import_ops`]): neue Zeichnungsebene,
//! Kategorien je DXF-Layer, Linienstile der PDF-Strichmuster, 2D-Zeichnungen, Kontext-Meshes — als EINE
//! Op-Folge (ein Undo-Schritt).
//!
//! Aufbau des Puffers: `fileio/src/import.rs::encode` (Version 3) bzw. `fileio/src/pdf_vector.rs::encode`
//! (Version 2). Grosse ASCII-DXF liest die App in mehreren Stücken parallel; jedes Stück ist ein eigener
//! Puffer (`chunks`), die Teilergebnisse werden wie früher in TS zusammengeführt.
//!
//! Zahlen und Texte wie in der TS-Fassung (`Math.round`, `toFixed`, `String(n)`, ids aus Zeit + Zähler),
//! Schlüsselreihenfolge der erzeugten Objekte wie die früheren Objekt-Literale.
use crate::grips::js_num;
use crate::js_fmt::{js_number, to_fixed};
use crate::jsnum;
use crate::ops::Op;
use serde_json::{json, Map, Value};
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
/// Kategorie generischer Importe (`GENERIC_IMPORT_CATEGORY`, „10 Situation").
pub const GENERIC_IMPORT_CODE: &str = "10";
/// Füllfarbe aus HATCH importierter Flächen (`DXF_HATCH_FILL`).
const DXF_HATCH_FILL: &str = "#c8c8c8";
/// Papier-Millimeter je PDF-Punkt.
pub const PT_TO_MM: f64 = 25.4 / 72.0;
thread_local! {
/// Laufnummer der erzeugten ids (wie die Modul-Zähler der TS-Fassung).
static SEQ: Cell<u64> = const { Cell::new(0) };
}
/// Nächste Laufnummer für ids.
pub fn next_seq() -> u64 {
SEQ.with(|s| {
let v = s.get();
s.set(v + 1);
v
})
}
/// Zeitstempel als Text wie `${Date.now()}` (ganze ms).
pub fn now_text(now: f64) -> String {
js_number(if now.is_finite() { now.trunc() } else { 0.0 })
}
/// `#rrggbb` aus einer Zahl (`(c & 0xffffff).toString(16).padStart(6, "0")`).
pub fn hex_color(c: f64) -> String {
format!("#{:06x}", jsnum::to_int32(c) & 0xffffff)
}
// ── Import-Form ──────────────────────────────────────────────────────────────
/// Echte Kurve einer Kontur (CIRCLE/ARC bzw. aus Bézier-Folgen erkannt).
#[derive(Clone, Debug)]
pub struct Curve {
pub circle: bool,
pub cx: f64,
pub cy: f64,
pub r: f64,
pub a0: f64,
pub a1: f64,
}
#[derive(Clone, Debug)]
pub struct Contour {
pub layer: String,
/// Höhe (in 2D-Zeichnungen ohne Bedeutung).
pub z: f64,
pub closed: bool,
pub filled: bool,
pub curve: Option<Curve>,
pub pts: Vec<[f64; 2]>,
/// Polylinie mit Bögen: Stützpunkte + DXF-Bulge je Stützpunkt.
pub bulge: Option<(Vec<[f64; 2]>, Vec<f64>)>,
}
#[derive(Clone, Debug)]
pub struct Text {
pub layer: String,
pub text: String,
pub x: f64,
pub y: f64,
pub height: f64,
pub angle: f64,
}
#[derive(Clone, Debug)]
pub struct Mesh {
pub id: String,
pub name: String,
pub layer: String,
pub positions: Vec<f64>,
pub indices: Vec<f64>,
}
/// Ergebnis eines Zeichnungs-Imports (vorher `DxfImportResult`).
#[derive(Clone, Debug, Default)]
pub struct DrawingImport {
pub contours: Vec<Contour>,
pub texts: Vec<Text>,
pub meshes: Vec<Mesh>,
/// Farbe je Layer (Reihenfolge wie ein JS-Objekt mit Zuweisung).
pub layer_colors: Map<String, Value>,
pub layer_line_weights: Map<String, Value>,
pub layer_fill_colors: Map<String, Value>,
pub layer_dashes: Vec<(String, Vec<f64>)>,
pub entity_counts: Map<String, Value>,
pub total: f64,
pub ins_units: Option<f64>,
pub unit_scale: Option<f64>,
pub layouts: Option<Vec<(String, f64)>>,
pub layout: Option<String>,
pub recovered: bool,
}
struct Rd<'a> {
g: &'a [f64],
s: &'a [String],
i: usize,
}
impl Rd<'_> {
fn num(&mut self) -> Result<f64, String> {
let v = *self.g.get(self.i).ok_or("Importpuffer zu kurz")?;
self.i += 1;
Ok(v)
}
fn count(&mut self) -> Result<usize, String> {
let v = self.num()?;
if v.is_finite() && v >= 0.0 && v.fract() == 0.0 && (v as usize) <= self.g.len() {
Ok(v as usize)
} else if v.is_finite() && v <= 0.0 {
Ok(0)
} else {
Err("Importpuffer beschädigt".into())
}
}
fn str(&mut self) -> Result<String, String> {
let k = self.num()?;
Ok(if k >= 0.0 && k.fract() == 0.0 { self.s.get(k as usize).cloned().unwrap_or_default() } else { String::new() })
}
fn take(&mut self, n: usize) -> Result<&[f64], String> {
let end = self.i.checked_add(n).filter(|&e| e <= self.g.len()).ok_or("Importpuffer zu kurz")?;
let out = &self.g[self.i..end];
self.i = end;
Ok(out)
}
}
/// Dekodiert einen DXF/DWG-Puffer (`import.rs::encode`, Version 3). `id_prefix` macht Mesh-ids
/// eindeutig, wenn mehrere Stücke parallel gelesen wurden (`c0-` …).
pub fn decode_drawing(geom: &[f64], strings: &[String], id_prefix: &str, now: f64) -> Result<DrawingImport, String> {
let mut r = Rd { g: geom, s: strings, i: 0 };
if r.num()? != 3.0 {
return Err("Unbekanntes Importformat (Version).".into());
}
let fmt = if r.num()? == 1.0 { "DWG" } else { "DXF" };
let ins_units = r.num()?;
let unit_scale = r.num()?;
let total = r.num()?;
let mut out = DrawingImport { total, ins_units: Some(ins_units), unit_scale: Some(unit_scale), ..Default::default() };
for _ in 0..r.count()? {
let name = r.str()?;
let c = r.num()?;
out.layer_colors.insert(name, Value::String(hex_color(c)));
}
for _ in 0..r.count()? {
let name = r.str()?;
let n = r.num()?;
out.entity_counts.insert(name, js_num(n));
}
let n_contours = r.count()?;
out.contours.reserve(n_contours);
for _ in 0..n_contours {
let layer = r.str()?;
let flags = jsnum::to_int32(r.num()?);
let z = r.num()?;
let mut c = Contour { layer, z, closed: flags & 1 != 0, filled: flags & 2 != 0, curve: None, pts: Vec::new(), bulge: None };
if flags & 4 != 0 {
let circle = r.num()? == 1.0;
let v = r.take(5)?;
c.curve = Some(Curve { circle, cx: v[0], cy: v[1], r: v[2], a0: v[3], a1: v[4] });
}
let np = r.count()?;
let v = r.take(2 * np)?;
c.pts = v.chunks_exact(2).map(|p| [p[0], p[1]]).collect();
if flags & 8 != 0 {
let nv = r.count()?;
let v = r.take(3 * nv)?;
let pts = v.chunks_exact(3).map(|p| [p[0], p[1]]).collect();
let bulge = v.chunks_exact(3).map(|p| p[2]).collect();
c.bulge = Some((pts, bulge));
}
out.contours.push(c);
}
for _ in 0..r.count()? {
let layer = r.str()?;
let text = r.str()?;
let v = r.take(4)?;
out.texts.push(Text { layer, text, x: v[0], y: v[1], height: v[2], angle: v[3] });
}
let n_meshes = r.count()?;
let stamp = now_text(now);
for _ in 0..n_meshes {
let layer = r.str()?;
let n_pos = r.count()?;
let n_idx = r.count()?;
let positions = r.take(n_pos * 3)?.to_vec();
let indices = r.take(n_idx)?.to_vec();
let name = if n_meshes > 1 { format!("{fmt}-Mesh ({layer})") } else { format!("{fmt}-Mesh") };
out.meshes.push(Mesh { id: format!("{id_prefix}imported-{stamp}-{}", next_seq()), name, layer, positions, indices });
}
let mut layouts = Vec::new();
for _ in 0..r.count()? {
let name = r.str()?;
layouts.push((name, r.num()?));
}
out.layouts = Some(layouts);
out.recovered = r.num()? == 1.0;
let layout_idx = r.num()?;
out.layout = (layout_idx >= 0.0).then(|| strings.get(layout_idx as usize).cloned()).flatten();
Ok(out)
}
/// Führt die Teilergebnisse mehrerer Stücke zusammen (vorher `dxfParserAsync.ts::mergeResults`).
pub fn merge(parts: Vec<DrawingImport>) -> DrawingImport {
let mut out = DrawingImport::default();
let mut first = true;
for p in parts {
if first {
out.ins_units = p.ins_units;
out.unit_scale = p.unit_scale;
out.layouts = p.layouts.clone();
first = false;
}
out.meshes.extend(p.meshes);
out.contours.extend(p.contours);
out.texts.extend(p.texts);
for (k, v) in p.layer_colors {
out.layer_colors.insert(k, v);
}
for (k, v) in p.entity_counts {
let n = out.entity_counts.get(&k).and_then(Value::as_f64).unwrap_or(0.0) + v.as_f64().unwrap_or(0.0);
out.entity_counts.insert(k, js_num(n));
}
out.total += p.total;
}
out
}
// ── Vektor-PDF ([76]) ────────────────────────────────────────────────────────
/// Pfad einer PDF-Seite (pt, angezeigte Seite).
pub struct PdfPath {
pub pts: Vec<[f64; 2]>,
pub closed: bool,
pub stroke: Option<String>,
pub fill: Option<String>,
pub line_width: f64,
pub dash: Vec<f64>,
pub curve: Option<Curve>,
}
pub struct PdfText {
pub text: String,
pub x: f64,
pub y: f64,
pub size: f64,
pub angle: f64,
pub color: String,
}
pub struct PdfPage {
pub page_count: f64,
pub page_index: f64,
pub width: f64,
pub height: f64,
pub rotate: f64,
pub truncated: bool,
pub images: f64,
pub paths: Vec<PdfPath>,
pub texts: Vec<PdfText>,
}
/// Dekodiert den Puffer aus `pdf_vector.rs::encode` (Version 2).
pub fn decode_pdf(geom: &[f64], strings: &[String]) -> Result<PdfPage, String> {
let mut r = Rd { g: geom, s: strings, i: 0 };
if r.num()? != 2.0 {
return Err("Unbekanntes PDF-Importformat (Version).".into());
}
let page_count = r.num()?;
let page_index = r.num()?;
let width = r.num()?;
let height = r.num()?;
r.take(8)?; // MediaBox, CropBox
let rotate = r.num()?;
let truncated = r.num()? == 1.0;
let images = r.num()?;
let mut paths = Vec::new();
for _ in 0..r.count()? {
let flags = jsnum::to_int32(r.num()?);
let s = r.num()?;
let f = r.num()?;
let line_width = r.num()?;
let nd = r.count()?;
let dash = r.take(nd)?.to_vec();
let np = r.count()?;
let pts = r.take(2 * np)?.chunks_exact(2).map(|p| [p[0], p[1]]).collect();
let curve = if flags & 16 != 0 {
let v = r.take(5)?;
Some(Curve { circle: flags & 32 != 0, cx: v[0], cy: v[1], r: v[2], a0: v[3], a1: v[4] })
} else {
None
};
paths.push(PdfPath {
pts,
closed: flags & 1 != 0,
stroke: (flags & 2 != 0).then(|| hex_color(s)),
fill: (flags & 4 != 0).then(|| hex_color(f)),
line_width,
dash,
curve,
});
}
let mut texts = Vec::new();
for _ in 0..r.count()? {
let text = r.str()?;
let _font = r.str()?;
let v = r.take(5)?;
texts.push(PdfText { text, x: v[0], y: v[1], size: v[2], angle: v[3], color: hex_color(v[4]) });
}
Ok(PdfPage { page_count, page_index, width, height, rotate, truncated, images, paths, texts })
}
/// Modell-Meter je PDF-Punkt bei Massstab 1:`scale`.
pub fn pdf_meters_per_pt(scale: f64) -> f64 {
(PT_TO_MM / 1000.0) * scale
}
/// Strichstärke in Papier-mm, auf 0.01 mm gerundet.
pub fn pdf_line_weight_mm(lw: f64) -> f64 {
jsnum::round(lw * PT_TO_MM * 100.0) / 100.0
}
/// Strichmuster in Papier-mm, auf 0.05 mm gerundet.
pub fn pdf_dash_mm(dash: &[f64]) -> Vec<f64> {
dash.iter().map(|d| jsnum::round((d * PT_TO_MM) / 0.05) * 0.05).map(|d| jsnum::round(d * 100.0) / 100.0).collect()
}
/// Kurzschrift eines Strichmusters: „0.9/0.6".
pub fn pdf_dash_label(dash_mm: &[f64]) -> String {
dash_mm.iter().map(|d| js_number(jsnum::round(d * 100.0) / 100.0)).collect::<Vec<_>>().join("/")
}
/// Ebenenname einer gestrichenen Linie.
pub fn pdf_stroke_layer(p: &PdfPath) -> String {
let lw = to_fixed(pdf_line_weight_mm(p.line_width), 2);
let dash = if p.dash.is_empty() { String::new() } else { format!(" (Strich {})", pdf_dash_label(&pdf_dash_mm(&p.dash))) };
format!("PDF {lw} {}{dash}", p.stroke.as_deref().unwrap_or("#000000"))
}
fn polygon_area(pts: &[[f64; 2]]) -> f64 {
let n = pts.len();
let mut a = 0.0;
let mut j = n.wrapping_sub(1);
for i in 0..n {
a += (pts[j][0] + pts[i][0]) * (pts[j][1] - pts[i][1]);
j = i;
}
(a / 2.0).abs()
}
/// Seite → Import-Form bei Massstab 1:`scale` (vorher `pdfPageToImport`).
pub fn pdf_to_import(page: &PdfPage, scale: f64, with_texts: bool) -> DrawingImport {
let k = pdf_meters_per_pt(scale);
let mut out = DrawingImport::default();
let page_area = page.width * page.height;
let (mut n_fill, mut n_stroke) = (0.0, 0.0);
let to_m = |pts: &[[f64; 2]]| pts.iter().map(|p| [p[0] * k, p[1] * k]).collect::<Vec<_>>();
for p in &page.paths {
if let Some(fill) = &p.fill {
if p.closed && !(fill == "#ffffff" && p.stroke.is_none() && polygon_area(&p.pts) > 0.5 * page_area) {
let layer = format!("PDF Fläche {fill}");
out.layer_colors.insert(layer.clone(), Value::String(fill.clone()));
out.layer_fill_colors.insert(layer.clone(), Value::String(fill.clone()));
if !out.layer_line_weights.get(&layer).is_some_and(|v| !v.is_null()) {
out.layer_line_weights.insert(layer.clone(), json!(0.05));
}
out.contours.push(Contour { layer, z: 0.0, closed: true, filled: true, curve: None, pts: to_m(&p.pts), bulge: None });
n_fill += 1.0;
}
}
if let Some(stroke) = &p.stroke {
let layer = pdf_stroke_layer(p);
out.layer_colors.insert(layer.clone(), Value::String(stroke.clone()));
out.layer_line_weights.insert(layer.clone(), js_num(jsnum::max(0.05, pdf_line_weight_mm(p.line_width))));
if !p.dash.is_empty() && !out.layer_dashes.iter().any(|(l, _)| *l == layer) {
out.layer_dashes.push((layer.clone(), pdf_dash_mm(&p.dash)));
}
let curve = p.curve.as_ref().map(|c| Curve { circle: c.circle, cx: c.cx * k, cy: c.cy * k, r: c.r * k, a0: c.a0, a1: c.a1 });
out.contours.push(Contour { layer, z: 0.0, closed: p.closed, filled: false, curve, pts: to_m(&p.pts), bulge: None });
n_stroke += 1.0;
}
}
if with_texts {
for t in &page.texts {
let layer = format!("PDF Text {}", t.color);
out.layer_colors.insert(layer.clone(), Value::String(t.color.clone()));
out.texts.push(Text { layer, text: t.text.clone(), x: t.x * k, y: t.y * k, height: t.size * k, angle: t.angle });
}
}
for (key, n) in [("PATH", n_stroke), ("FILL", n_fill), ("TEXT", out.texts.len() as f64), ("IMAGE", page.images)] {
out.entity_counts.insert(key.into(), js_num(n));
}
out.total = (page.paths.len() + page.texts.len()) as f64;
out.unit_scale = Some(k);
out.recovered = page.truncated;
out
}
/// Kurzbericht einer Seite (CLI `pdf-info`, vorher `pdfPageInfo`): Zahlen und Umriss in pt und Papier-mm.
pub fn pdf_page_info(page: &PdfPage) -> Value {
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
let mut grow = |x: f64, y: f64| {
if x < min_x {
min_x = x;
}
if y < min_y {
min_y = y;
}
if x > max_x {
max_x = x;
}
if y > max_y {
max_y = y;
}
};
let mut points = 0usize;
for p in &page.paths {
points += p.pts.len();
for q in &p.pts {
grow(q[0], q[1]);
}
}
for t in &page.texts {
grow(t.x, t.y);
}
let mut layers = Map::new();
let mut bump = |l: String| {
let n = layers.get(&l).and_then(Value::as_f64).unwrap_or(0.0) + 1.0;
layers.insert(l, js_num(n));
};
for p in &page.paths {
if p.stroke.is_some() {
bump(pdf_stroke_layer(p));
}
if let Some(f) = &p.fill {
bump(format!("PDF Fläche {f}"));
}
}
let r = |v: f64| js_num(jsnum::round(v * 100.0) / 100.0);
json!({
"pages": js_num(page.page_count),
"page": js_num(page.page_index + 1.0),
"sizePt": [r(page.width), r(page.height)],
"sizeMm": [r(page.width * PT_TO_MM), r(page.height * PT_TO_MM)],
"rotate": js_num(page.rotate),
"paths": page.paths.len(),
"points": points,
"texts": page.texts.len(),
"images": js_num(page.images),
"truncated": page.truncated,
"bboxPt": if min_x.is_finite() { json!([r(min_x), r(min_y), r(max_x), r(max_y)]) } else { Value::Null },
"layers": layers,
})
}
// ── Quelle (Bindung) ─────────────────────────────────────────────────────────
/// Woher die Import-Form kommt: `{"kind":"drawing"}` (Stücke eines DXF/DWG) oder
/// `{"kind":"pdf","scale":100,"texts":true}`.
#[derive(serde::Deserialize, Default)]
#[serde(default)]
pub struct Source {
pub kind: String,
pub scale: Option<f64>,
pub texts: Option<bool>,
}
/// Stücke aus dem Übergabepuffer: `[n, len_0 … len_{n−1}, daten_0 …]`, String-Tabellen als JSON-Liste von Listen.
pub fn split_chunks<'a>(geom: &'a [f64], strings: &'a [Vec<String>]) -> Result<Vec<(&'a [f64], &'a [String])>, String> {
let n = *geom.first().ok_or("Importpuffer leer")?;
if !(n.is_finite() && n >= 0.0 && n.fract() == 0.0 && (n as usize) < geom.len() && (n as usize) == strings.len()) {
return Err("Importpuffer beschädigt".into());
}
let n = n as usize;
let mut at = 1 + n;
let mut out = Vec::with_capacity(n);
for k in 0..n {
let len = geom[1 + k];
if !(len.is_finite() && len >= 0.0 && len.fract() == 0.0) {
return Err("Importpuffer beschädigt".into());
}
let end = at.checked_add(len as usize).filter(|&e| e <= geom.len()).ok_or("Importpuffer zu kurz")?;
out.push((&geom[at..end], strings[k].as_slice()));
at = end;
}
Ok(out)
}
/// Import-Form aus dem Übergabepuffer (`source` sagt, wie er zu lesen ist).
pub fn read_source(geom: &[f64], strings_json: &str, source: &Source, now: f64) -> Result<DrawingImport, String> {
let strings: Vec<Vec<String>> = serde_json::from_str(strings_json).map_err(|e| format!("Import-Texte: {e}"))?;
let chunks = split_chunks(geom, &strings)?;
if source.kind == "pdf" {
let (g, s) = chunks.first().ok_or("PDF-Seite fehlt")?;
let page = decode_pdf(g, s)?;
let scale = source.scale.unwrap_or(100.0);
return Ok(pdf_to_import(&page, scale, source.texts != Some(false)));
}
if chunks.len() == 1 {
return decode_drawing(chunks[0].0, chunks[0].1, "", now);
}
let parts = chunks.iter().enumerate().map(|(i, (g, s))| decode_drawing(g, s, &format!("c{i}-"), now)).collect::<Result<Vec<_>, _>>()?;
Ok(merge(parts))
}
// ── Zusammenfassung für den Dialog ───────────────────────────────────────────
/// Unterschiedliche Layer-Namen der Konturen (`distinctLayers`).
pub fn contour_layers(d: &DrawingImport) -> Vec<String> {
let mut seen = HashSet::new();
d.contours.iter().filter(|c| !c.layer.is_empty() && seen.insert(c.layer.as_str())).map(|c| c.layer.clone()).collect()
}
/// Wie [`contour_layers`], über Konturen UND Texte (`distinctImportLayers`).
pub fn import_layers(d: &DrawingImport) -> Vec<String> {
let mut seen: HashSet<&str> = HashSet::new();
let mut out = Vec::new();
for l in d.contours.iter().map(|c| c.layer.as_str()).chain(d.texts.iter().map(|t| t.layer.as_str())) {
if !l.is_empty() && seen.insert(l) {
out.push(l.to_string());
}
}
out
}
/// Was der Import-Dialog zeigt: Zahlen, Layer, Diagnose, Layouts, Einheit.
pub fn summary_json(d: &DrawingImport) -> Value {
let mut m = Map::new();
m.insert("contours".into(), d.contours.len().into());
m.insert("texts".into(), d.texts.len().into());
m.insert("meshes".into(), d.meshes.len().into());
m.insert("layers".into(), contour_layers(d).into());
m.insert("diagnostics".into(), json!({"entityCounts": d.entity_counts, "total": js_num(d.total)}));
if let Some(u) = d.ins_units {
m.insert("insUnits".into(), js_num(u));
}
if let Some(u) = d.unit_scale {
m.insert("unitScale".into(), js_num(u));
}
if let Some(l) = &d.layouts {
m.insert("layouts".into(), l.iter().map(|(name, n)| json!({"name": name, "entities": js_num(*n)})).collect());
}
if let Some(l) = &d.layout {
m.insert("layout".into(), l.clone().into());
}
m.insert("recovered".into(), d.recovered.into());
Value::Object(m)
}
/// Meshes als Kontext-Objekte (`ImportedMesh`, Kategorie „10 Situation"; Layer „0" ohne `layer`).
pub fn mesh_values(d: &DrawingImport) -> Vec<Value> {
d.meshes
.iter()
.map(|m| {
let mut o = Map::new();
o.insert("id".into(), m.id.clone().into());
o.insert("type".into(), "importedMesh".into());
o.insert("name".into(), m.name.clone().into());
o.insert("categoryCode".into(), GENERIC_IMPORT_CODE.into());
if m.layer != "0" {
o.insert("layer".into(), m.layer.clone().into());
}
o.insert("positions".into(), Value::Array(m.positions.iter().map(|&x| js_num(x)).collect()));
o.insert("indices".into(), Value::Array(m.indices.iter().map(|&x| js_num(x)).collect()));
Value::Object(o)
})
.collect()
}
/// Die ganze Import-Form als JSON (Leseansicht für Tests und Diagnose; Form wie das frühere
/// `DxfImportResult`: ein Konturen-Satz, Texte, Meshes, Ebenenfarben …).
pub fn view_json(d: &DrawingImport) -> Value {
let p = |q: &[f64; 2]| json!({"x": js_num(q[0]), "y": js_num(q[1])});
let contours: Vec<Value> = d
.contours
.iter()
.map(|c| {
let mut o = Map::new();
o.insert("z".into(), js_num(c.z));
o.insert("pts".into(), c.pts.iter().map(p).collect());
o.insert("closed".into(), c.closed.into());
o.insert("layer".into(), c.layer.clone().into());
if c.filled {
o.insert("filled".into(), true.into());
}
if let Some(k) = &c.curve {
o.insert(
"curve".into(),
json!({"kind": if k.circle { "circle" } else { "arc" }, "cx": js_num(k.cx), "cy": js_num(k.cy), "r": js_num(k.r), "a0": js_num(k.a0), "a1": js_num(k.a1)}),
);
}
if let Some((pts, b)) = &c.bulge {
o.insert("bulgePolyline".into(), json!({"pts": pts.iter().map(p).collect::<Vec<_>>(), "bulge": b.iter().map(|&x| js_num(x)).collect::<Vec<_>>()}));
}
Value::Object(o)
})
.collect();
let mut m = Map::new();
m.insert("meshes".into(), mesh_values(d).into());
let sets = if contours.is_empty() {
Vec::new()
} else {
vec![json!({"type": "contourSet", "categoryCode": GENERIC_IMPORT_CODE, "contours": contours})]
};
m.insert("contours".into(), sets.into());
m.insert(
"texts".into(),
d.texts.iter().map(|t| json!({"at": {"x": js_num(t.x), "y": js_num(t.y)}, "text": t.text, "height": js_num(t.height), "angle": js_num(t.angle), "layer": t.layer})).collect(),
);
m.insert("layerColors".into(), Value::Object(d.layer_colors.clone()));
m.insert("layerLineWeights".into(), Value::Object(d.layer_line_weights.clone()));
m.insert("layerFillColors".into(), Value::Object(d.layer_fill_colors.clone()));
m.insert("layerDashes".into(), d.layer_dashes.iter().map(|(l, v)| (l.clone(), json!(v.iter().map(|&x| js_num(x)).collect::<Vec<_>>()))).collect::<Map<_, _>>().into());
if let Value::Object(s) = summary_json(d) {
for k in ["diagnostics", "insUnits", "unitScale", "layouts", "layout", "recovered"] {
if let Some(v) = s.get(k) {
m.insert(k.into(), v.clone());
}
}
}
Value::Object(m)
}
// ── Ops ──────────────────────────────────────────────────────────────────────
/// Ziel-Ebene des Imports.
#[derive(serde::Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum Target {
Existing {
#[serde(rename = "levelId")]
level_id: String,
},
New {
name: String,
},
}
/// Entscheidung des Import-Dialogs (bzw. des CLI). Übersetzte Texte bringt die Hülle mit (der Kern kennt
/// kein i18n): `levelNameTemplate` (Name einer neuen Zeichnung ohne Eingabe, `{n}` = Nummer),
/// `parentName` (Elternkategorie der neuen Layer-Kategorien), `dashStyleTemplate` (Linienstil, `{pattern}`).
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Decision {
pub target: Target,
/// `"byLayer"` | `"active"`.
pub category_mode: String,
pub active_category_code: String,
#[serde(default)]
pub import_meshes: bool,
/// Mitte des Ausschnitts für `placement: "viewCenter"`; fehlt = an den Datei-Koordinaten.
#[serde(default)]
pub view_center: Option<[f64; 2]>,
#[serde(default)]
pub level_name_template: String,
#[serde(default)]
pub parent_name: String,
#[serde(default)]
pub dash_style_template: String,
}
/// Ergebnis von [`import_ops`].
pub struct ImportResult {
pub ops: Vec<Op>,
/// Ziel-Ebene (neu angelegt oder gewählt).
pub level_id: String,
pub drawings: usize,
pub meshes: usize,
}
fn layer_list(root: &Map<String, Value>) -> Vec<Value> {
root.get("layers").and_then(Value::as_array).cloned().unwrap_or_default()
}
/// Gleiches Strichmuster (Toleranz 15 % bzw. 0.06 mm je Glied, `sameDash`).
fn same_dash(a: &[f64], b: &[f64]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(v, w)| (v - w).abs() <= jsnum::max(0.06, 0.15 * jsnum::max(*v, *w)))
}
/// Linienstile der PDF-Strichmuster (`planDashLineStyles`): vorhandene mit gleichem Muster oder neue.
fn plan_dash_styles(dashes: &[(String, Vec<f64>)], existing: &[Value], name_template: &str) -> (Vec<Value>, HashMap<String, String>) {
let mut created: Vec<Value> = Vec::new();
let mut by_layer = HashMap::new();
let mut used: HashSet<String> = existing.iter().filter_map(|l| l.get("id").and_then(Value::as_str).map(str::to_string)).collect();
let dash_of = |l: &Value| -> Option<Vec<f64>> {
let kind = l.get("kind").and_then(Value::as_str).unwrap_or("dash");
if kind != "dash" {
return None;
}
l.get("dash")?.as_array().map(|a| a.iter().map(|x| x.as_f64().unwrap_or(f64::NAN)).collect())
};
for (layer, dash) in dashes {
if dash.len() < 2 {
continue;
}
let known = existing.iter().chain(created.iter()).find(|l| dash_of(l).is_some_and(|d| same_dash(&d, dash)));
if let Some(k) = known {
by_layer.insert(layer.clone(), k.get("id").and_then(Value::as_str).unwrap_or("").to_string());
continue;
}
let label = pdf_dash_label(dash);
let mut base = String::from("pdf-dash-");
let mut in_run = false;
for ch in label.chars() {
if ch.is_ascii_alphanumeric() {
base.push(ch);
in_run = false;
} else if !in_run {
base.push('_');
in_run = true;
}
}
let mut id = base.clone();
let mut n = 2;
while used.contains(&id) {
id = format!("{base}-{n}");
n += 1;
}
used.insert(id.clone());
let name = name_template.replace("{pattern}", &label);
created.push(json!({"id": id, "name": name, "weight": 0.02, "color": "#1a1a1a", "dash": dash.iter().map(|&d| js_num(d)).collect::<Vec<_>>()}));
by_layer.insert(layer.clone(), id);
}
(created, by_layer)
}
fn pt(p: [f64; 2], dx: f64, dy: f64) -> Value {
json!({"x": js_num(p[0] + dx), "y": js_num(p[1] + dy)})
}
/// Eine Kontur → 2D-Geometrie (`contourGeom`); `None` = zu wenig Punkte.
fn contour_geom(c: &Contour, dx: f64, dy: f64) -> Option<Value> {
if let Some(k) = &c.curve {
let center = pt([k.cx, k.cy], dx, dy);
return Some(if k.circle {
json!({"shape": "circle", "center": center, "r": js_num(k.r)})
} else {
json!({"shape": "arc", "center": center, "r": js_num(k.r), "a0": js_num(k.a0), "a1": js_num(k.a1)})
});
}
// VORZEICHEN: DXF-Bulge > 0 = Bogen im Gegenuhrzeigersinn (Scheitel rechts der Sehne), im Modell liegt
// der Scheitel bei Bulge > 0 LINKS der Sehne (`kernel2d/src/bulge.rs`) — also umgekehrt.
if let Some((pts, bulge)) = &c.bulge {
if pts.len() >= 2 && bulge.len() == pts.len() {
return Some(json!({
"shape": "polyline",
"pts": pts.iter().map(|&p| pt(p, dx, dy)).collect::<Vec<_>>(),
"closed": c.closed,
"bulge": bulge.iter().map(|&b| js_num(if b == 0.0 { 0.0 } else { -b })).collect::<Vec<_>>(),
}));
}
}
if c.pts.len() < 2 {
return None;
}
if c.pts.len() == 2 && !c.closed {
return Some(json!({"shape": "line", "a": pt(c.pts[0], dx, dy), "b": pt(c.pts[1], dx, dy)}));
}
Some(json!({"shape": "polyline", "pts": c.pts.iter().map(|&p| pt(p, dx, dy)).collect::<Vec<_>>(), "closed": c.closed}))
}
/// Umriss aller entstehenden Zeichnungen (`drawingsBBox` über Linie, Polylinie, Kreis/Bogen, Text).
fn bbox(d: &DrawingImport) -> Option<[f64; 4]> {
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
let mut acc = |x: f64, y: f64| {
min_x = jsnum::min(min_x, x);
min_y = jsnum::min(min_y, y);
max_x = jsnum::max(max_x, x);
max_y = jsnum::max(max_y, y);
};
for c in &d.contours {
if let Some(k) = &c.curve {
acc(k.cx - k.r, k.cy - k.r);
acc(k.cx + k.r, k.cy + k.r);
continue;
}
let pts = match &c.bulge {
Some((p, b)) if p.len() >= 2 && b.len() == p.len() => p,
_ if c.pts.len() < 2 => continue,
_ => &c.pts,
};
for p in pts {
acc(p[0], p[1]);
}
}
for t in &d.texts {
acc(t.x, t.y);
}
min_x.is_finite().then_some([min_x, min_y, max_x, max_y])
}
fn ensure_layers_with_parent(layers: &mut Vec<Value>, parent: Option<Value>) {
if let Some(p) = parent {
layers.push(p);
}
}
/// Die Ops eines bestätigten Imports auf dem Projekt `root` (vorher `runImport` + `buildDrawings`).
pub fn import_ops(root: &Map<String, Value>, d: &DrawingImport, dec: &Decision, now: f64) -> ImportResult {
let mut ops = Vec::new();
let stamp = now_text(now);
// Ziel-Ebene.
let level_id = match &dec.target {
Target::Existing { level_id } => level_id.clone(),
Target::New { name } => {
let id = format!("drawing-{stamp}");
let n = root
.get("drawingLevels")
.and_then(Value::as_array)
.map_or(0, |l| l.iter().filter(|z| z.get("kind").and_then(Value::as_str) == Some("drawing")).count())
+ 1;
let name = if name.trim().is_empty() { dec.level_name_template.replace("{n}", &n.to_string()) } else { name.trim().to_string() };
ops.push(Op::Add {
collection: "drawingLevels".into(),
items: vec![json!({"id": id, "name": name, "kind": "drawing", "visible": true, "locked": false})],
at: None,
});
id
}
};
// Layer als Kategorien: fehlende als Unterkategorien einer neuen Elternkategorie.
let mut layers = layer_list(root);
let mut layers_changed = false;
let by_layer = dec.category_mode == "byLayer";
let mut code_by_layer: HashMap<String, String> = HashMap::new();
if by_layer {
let names = import_layers(d);
let plan = crate::layers::plan_import(&names, &layers, &d.layer_colors, &d.layer_line_weights);
code_by_layer = plan.code_by_layer.into_iter().collect();
if !plan.children.is_empty() {
let parent = json!({"code": plan.parent_code, "name": dec.parent_name, "color": "#707078", "lw": 0.18, "visible": true, "locked": false, "children": plan.children});
ensure_layers_with_parent(&mut layers, Some(parent));
layers_changed = true;
}
}
// PDF-Strichmuster → Linienstile.
let existing_styles = root.get("lineStyles").and_then(Value::as_array).cloned().unwrap_or_default();
let (created, style_by_layer) = plan_dash_styles(&d.layer_dashes, &existing_styles, &dec.dash_style_template);
if !created.is_empty() {
ops.push(Op::Add { collection: "lineStyles".into(), items: created, at: None });
}
// Layer-Name → Kategorie: Plan, sonst gleichnamige Kategorie (Stand vor dem Import), sonst die aktive.
let mut by_name: HashMap<String, String> = HashMap::new();
for c in crate::layers::flatten(&layer_list(root)) {
if let (Some(code), Some(name)) = (c.get("code").and_then(Value::as_str), c.get("name").and_then(Value::as_str)) {
by_name.insert(name.to_lowercase(), code.to_string());
}
}
let active = dec.active_category_code.as_str();
let code_for = |layer: &str| -> String {
if !(by_layer && !layer.is_empty()) {
return active.to_string();
}
code_by_layer.get(layer).or_else(|| by_name.get(&layer.to_lowercase())).cloned().unwrap_or_else(|| active.to_string())
};
// Platzierung „viewCenter": Mitte des Umrisses auf die Mitte des Ausschnitts.
let (dx, dy) = match (dec.view_center, bbox(d)) {
(Some(c), Some(b)) => (c[0] - (b[0] + b[2]) / 2.0, c[1] - (b[1] + b[3]) / 2.0),
_ => (0.0, 0.0),
};
let mut drawings = Vec::with_capacity(d.contours.len() + d.texts.len());
for c in &d.contours {
let Some(geom) = contour_geom(c, dx, dy) else { continue };
let is_polyline = geom.get("shape").and_then(Value::as_str) == Some("polyline");
let mut o = Map::new();
o.insert("id".into(), format!("dxf2d-{stamp}-{}", next_seq()).into());
o.insert("type".into(), "drawing2d".into());
o.insert("levelId".into(), level_id.clone().into());
o.insert("categoryCode".into(), code_for(&c.layer).into());
o.insert("geom".into(), geom);
if let Some(s) = style_by_layer.get(&c.layer).filter(|s| !s.is_empty()) {
o.insert("lineStyleId".into(), s.clone().into());
}
if c.filled && is_polyline {
let fill = d.layer_fill_colors.get(&c.layer).and_then(Value::as_str).unwrap_or(DXF_HATCH_FILL);
o.insert("fillColor".into(), fill.into());
}
drawings.push(Value::Object(o));
}
for t in &d.texts {
drawings.push(json!({
"id": format!("dxf2d-{stamp}-{}", next_seq()),
"type": "drawing2d",
"levelId": level_id,
"categoryCode": code_for(&t.layer),
"geom": {"shape": "text", "at": pt([t.x, t.y], dx, dy), "text": t.text, "height": js_num(t.height), "angle": js_num(t.angle)},
}));
}
let n_drawings = drawings.len();
if !drawings.is_empty() {
ops.push(Op::Add { collection: "drawings2d".into(), items: drawings, at: None });
}
let mut n_meshes = 0;
if dec.import_meshes && !d.meshes.is_empty() {
let meshes = mesh_values(d);
n_meshes = meshes.len();
ops.push(Op::Add { collection: "context".into(), items: meshes, at: None });
if crate::import_context::ensure_context_categories(&mut layers, [GENERIC_IMPORT_CODE]) {
layers_changed = true;
}
}
if layers_changed {
ops.push(Op::SetField { key: "layers".into(), value: Some(Value::Array(layers)), at: None });
}
ImportResult { ops, level_id, drawings: n_drawings, meshes: n_meshes }
}
#[cfg(test)]
#[path = "import_drawing_tests.rs"]
mod tests;
+261
View File
@@ -0,0 +1,261 @@
use super::*;
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".
fn sample() -> (Vec<f64>, Vec<String>) {
let s: Vec<String> = ["A", "B", "LINE", "Wohnen", "0"].iter().map(|x| x.to_string()).collect();
let mut g = vec![3.0, 0.0, 6.0, 1.0, 5.0];
g.extend([2.0, 0.0, 16711680.0, 1.0, 255.0]); // Ebenenfarben
g.extend([1.0, 2.0, 5.0]); // Entity-Zähler
g.push(4.0); // Konturen
g.extend([0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 4.0, 0.0]); // Linie
g.extend([1.0, 8.0, 0.0, 3.0, 0.0, 0.0, 1.0, 0.5, 2.0, 0.0]); // Polylinie (tesselliert) …
g.extend([2.0, 0.0, 0.0, 0.5, 2.0, 0.0, 0.0]); // … + Stützpunkte mit Bulge
g.extend([0.0, 4.0, 0.0, 1.0, 10.0, 10.0, 2.0, 0.0, 6.283, 0.0]); // Kreis ohne Punkte
g.extend([1.0, 3.0, 0.0, 3.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0]); // Schraffur, geschlossen
g.extend([1.0, 1.0, 3.0, 5.0, 6.0, 0.25, 0.0]); // Text
g.extend([1.0, 4.0, 3.0, 3.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 2.0]); // Mesh
g.extend([0.0, 0.0, -1.0]); // Layouts, recovered, layout
(g, s)
}
fn chunked(g: &[f64]) -> Vec<f64> {
let mut out = vec![1.0, g.len() as f64];
out.extend_from_slice(g);
out
}
fn project() -> Map<String, Value> {
json!({
"drawingLevels": [{"id": "eg", "name": "EG", "kind": "floor", "visible": true, "locked": false}],
"layers": [{"code": "20", "name": "Wände", "color": "#000", "lw": 0.5, "visible": true, "locked": false},
{"code": "30", "name": "b", "color": "#000", "lw": 0.5, "visible": true, "locked": false}],
"lineStyles": [], "drawings2d": [], "context": [],
})
.as_object()
.unwrap()
.clone()
}
fn decision(v: Value) -> Decision {
serde_json::from_value(v).unwrap()
}
#[test]
fn dekodiert_den_puffer() {
let (g, s) = sample();
let d = decode_drawing(&g, &s, "", 1000.0).unwrap();
assert_eq!(d.contours.len(), 4);
assert_eq!(d.texts.len(), 1);
assert_eq!(d.meshes.len(), 1);
assert_eq!(d.meshes[0].name, "DXF-Mesh");
assert_eq!(d.layer_colors["A"], json!("#ff0000"));
assert_eq!(d.layer_colors["B"], json!("#0000ff"));
let sum = summary_json(&d);
assert_eq!(sum["contours"], json!(4));
assert_eq!(sum["layers"], json!(["A", "B"]));
assert_eq!(sum["diagnostics"], json!({"entityCounts": {"LINE": 5}, "total": 5}));
assert_eq!(sum["unitScale"], json!(1));
assert_eq!(sum["recovered"], json!(false));
// Kaputte Puffer: Fehler statt Panic.
for n in 0..g.len() {
let _ = decode_drawing(&g[..n], &s, "", 0.0);
}
assert!(decode_drawing(&[2.0], &s, "", 0.0).is_err());
assert!(read_source(&[5.0, 1.0], "[[]]", &Source::default(), 0.0).is_err());
}
#[test]
fn ops_neue_zeichnung_mit_layer_kategorien() {
let (g, s) = sample();
let d = read_source(&chunked(&g), &serde_json::to_string(&vec![s]).unwrap(), &Source::default(), 0.0).unwrap();
let dec = decision(json!({"target": {"kind": "new", "name": " "}, "categoryMode": "byLayer", "activeCategoryCode": "20",
"importMeshes": true, "levelNameTemplate": "Zeichnung {n}", "parentName": "Import x"}));
let r = import_ops(&project(), &d, &dec, 1234.0);
assert_eq!(r.level_id, "drawing-1234");
assert_eq!(r.drawings, 5);
assert_eq!(r.meshes, 1);
let ops: Vec<Value> = r.ops.iter().map(Op::to_json).collect();
assert_eq!(ops[0]["items"][0], json!({"id": "drawing-1234", "name": "Zeichnung 1", "kind": "drawing", "visible": true, "locked": false}));
let drawings = &ops[1]["items"];
assert_eq!(drawings[0]["geom"], json!({"shape": "line", "a": {"x": 0, "y": 0}, "b": {"x": 4, "y": 0}}));
assert_eq!(drawings[0]["categoryCode"], json!("31"));
// Bulge: Modell = − DXF.
assert_eq!(drawings[1]["geom"]["bulge"], json!([-0.5, 0]));
// „B" passt (ohne Gross-/Kleinschreibung) auf die vorhandene Kategorie „b".
assert_eq!(drawings[1]["categoryCode"], json!("30"));
assert_eq!(drawings[2]["geom"], json!({"shape": "circle", "center": {"x": 10, "y": 10}, "r": 2}));
assert_eq!(drawings[3]["fillColor"], json!("#c8c8c8"));
assert_eq!(drawings[4]["geom"], json!({"shape": "text", "at": {"x": 5, "y": 6}, "text": "Wohnen", "height": 0.25, "angle": 0}));
assert_eq!(ops[2]["collection"], json!("context"));
assert!(ops[2]["items"][0].get("layer").is_none());
// Kategorien: „Import x" mit A, B; dazu „05 Kontext" mit „10 Situation".
let layers = &ops[3]["value"];
assert_eq!(layers[2]["name"], json!("Import x"));
assert_eq!(layers[2]["code"], json!("32"));
assert_eq!(layers[2]["children"].as_array().unwrap().len(), 1);
assert_eq!(layers[2]["children"][0], json!({"code": "31", "name": "A", "color": "#ff0000", "lw": 0.18, "visible": true, "locked": false}));
assert_eq!(layers[3]["code"], json!("05"));
assert_eq!(layers[3]["children"][0]["code"], json!("10"));
}
#[test]
fn ops_aktive_kategorie_und_ausschnittsmitte() {
let (g, s) = sample();
let d = decode_drawing(&g, &s, "", 0.0).unwrap();
let dec = decision(json!({"target": {"kind": "existing", "levelId": "eg"}, "categoryMode": "active", "activeCategoryCode": "20", "viewCenter": [100.0, 50.0]}));
let r = import_ops(&project(), &d, &dec, 0.0);
assert_eq!(r.ops.len(), 1);
let ops = r.ops[0].to_json();
// Umriss x 0…12, y 0…12 → Mitte (6, 6).
assert_eq!(ops["items"][0]["geom"]["a"], json!({"x": 94, "y": 44}));
assert!(ops["items"].as_array().unwrap().iter().all(|d| d["categoryCode"] == json!("20") && d["levelId"] == json!("eg")));
}
#[test]
fn pdf_mit_strichmuster() {
let page = PdfPage {
page_count: 1.0,
page_index: 0.0,
width: 595.0,
height: 842.0,
rotate: 0.0,
truncated: false,
images: 0.0,
paths: vec![
PdfPath { pts: vec![[72.0, 100.0], [172.0, 100.0]], closed: false, stroke: Some("#ff0000".into()), fill: None, line_width: 0.5, dash: vec![3.0, 2.0], curve: None },
PdfPath { pts: vec![[0.0, 0.0], [595.0, 0.0], [595.0, 842.0], [0.0, 842.0]], closed: true, stroke: None, fill: Some("#ffffff".into()), line_width: 0.0, dash: vec![], curve: None },
],
texts: vec![],
};
let d = pdf_to_import(&page, 100.0, true);
assert_eq!(d.contours.len(), 1);
assert_eq!(d.contours[0].layer, "PDF 0.18 #ff0000 (Strich 1.05/0.7)");
assert_eq!(d.layer_dashes, vec![("PDF 0.18 #ff0000 (Strich 1.05/0.7)".to_string(), vec![1.05, 0.7])]);
let dec = decision(json!({"target": {"kind": "existing", "levelId": "eg"}, "categoryMode": "byLayer", "activeCategoryCode": "20", "dashStyleTemplate": "PDF-Strich {pattern}"}));
let r = import_ops(&project(), &d, &dec, 0.0);
let ops: Vec<Value> = r.ops.iter().map(Op::to_json).collect();
assert_eq!(ops[0]["items"][0], json!({"id": "pdf-dash-1_05_0_7", "name": "PDF-Strich 1.05/0.7", "weight": 0.02, "color": "#1a1a1a", "dash": [1.05, 0.7]}));
assert_eq!(ops[1]["items"][0]["lineStyleId"], json!("pdf-dash-1_05_0_7"));
let info = pdf_page_info(&page);
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<f64>)> =
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<Vec<f64>>, 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"})];
assert!(ensure_context_categories(&mut l, ["10", "31", "20"]));
assert_eq!(l[1]["code"], json!("05"));
assert_eq!(l[1]["children"][0]["name"], json!("Situation"));
assert_eq!(l[2]["code"], json!("31"));
assert!(!ensure_context_categories(&mut l, ["10"]));
assert!(ensure_context_categories(&mut l, ["02"]));
assert_eq!(l[1]["children"][1]["code"], json!("02"));
}
#[test]
fn meshes_mitte_und_gruppen() {
assert_eq!(stamp36(1_700_000_000_000.0), "loyw3v28");
let obj = |g: &str, x: f64| MeshObject { name: String::new(), group: g.into(), color: Some(vec![1.0, 0.5, 0.0, 1.0]), positions: vec![x, 0.0, 1.0, x + 2.0, 2.0, 3.0], indices: vec![0.0, 1.0, 0.0] };
let m = mesh_objects_to_meshes(&[obj("", 0.0), obj("g", 10.0)], "haus.obj", "center", None, "auto", 0.0);
assert_eq!(m[0]["name"], json!("haus 1"));
assert_eq!(m[0]["layer"], json!("haus"));
assert_eq!(m[0]["color"], json!("#ff8000"));
assert_eq!(m[0]["positions"], json!([-6, -1, 0, -4, 1, 2]));
let m = mesh_objects_to_meshes(&[obj("g", 0.0), obj("g", 10.0)], "haus.obj", "original", None, "merge", 0.0);
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<MeshObject> = (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=<geom-Datei>` mit `<geom>.strings.json` daneben.
#[test]
#[ignore]
fn zeitmessung_kataster() {
let Ok(path) = std::env::var("IMPORT_BENCH") else { return };
let bytes = std::fs::read(&path).unwrap();
let geom: Vec<f64> = bytes.chunks_exact(8).map(|c| f64::from_le_bytes(c.try_into().unwrap())).collect();
let strings: Vec<String> = serde_json::from_str(&std::fs::read_to_string(path.replace(".geom", ".strings.json")).unwrap()).unwrap();
let t = std::time::Instant::now();
let d = decode_drawing(&geom, &strings, "", 0.0).unwrap();
eprintln!("dekodieren {:?}", t.elapsed());
let mut root = project();
root.insert("drawingLevels".into(), json!([]));
let dec = decision(json!({"target": {"kind": "new", "name": "K"}, "categoryMode": "byLayer", "activeCategoryCode": "20", "parentName": "I"}));
let t = std::time::Instant::now();
let r = import_ops(&root, &d, &dec, 0.0);
eprintln!("ops {:?}", t.elapsed());
let t = std::time::Instant::now();
let mut out = Vec::new();
for op in &r.ops {
serde_json::to_writer(&mut out, &op.to_json()).unwrap();
}
eprintln!("json {:?} ({} MB)", t.elapsed(), out.len() / 1_000_000);
let mut doc = crate::document::Document::from_json(&Value::Object(root).to_string()).unwrap();
let t = std::time::Instant::now();
doc.commit(r.ops, None, 0.0, false).unwrap();
eprintln!("commit {:?}", t.elapsed());
}
+719
View File
@@ -0,0 +1,719 @@
//! IFC-Import zu echten Bauteilen ([B4], [K4] S4; vorher `io/ifcElements.ts`): baut aus dem, was das
//! Format-Modul erkannt hat (`fileio/src/ifc_semantic.rs`: Achse, Dicke, Höhe, Umriss … in Metern),
//! Dossier-Objekte — Geschosse, Wände (Wandtyp aus den Materialschichten, wiederverwendet oder neu),
//! Türen/Fenster/Wanddurchbrüche, Decken (Deckentyp), Stützen, Räume; der Rest kommt als Kontext-Mesh
//! (`import_context`). Ergebnis sind Ops auf dem Projekt (ein Undo-Schritt) und eine Zusammenfassung.
//!
//! Zuordnung wie in der TS-Fassung: Geschoss nach Höhe (±5 mm) wiederverwenden oder anlegen, Wand- und
//! Deckentypen nach Schichten (Material + Dicke, ±0.5 mm), Materialien nach Namen; Zahlen auf 1e-9 m bzw.
//! 1e-6 gerundet (`Math.round(x / step) * step`).
use crate::grips::js_num;
use crate::import_context::{color_hex, color_of, context_ops, geo_shift, ifc_meshes, project_geo_origin, stamp36, IfcProduct};
use crate::import_drawing::next_seq;
use crate::js_fmt::js_number;
use crate::jsnum;
use crate::ops::Op;
use serde_json::{json, Map, Value};
use std::collections::{HashMap, HashSet};
const WALL_CATEGORY: &str = "20";
const OPENING_CATEGORY: &str = "21";
const CEILING_CATEGORY: &str = "30";
const COLUMN_CATEGORY: &str = "50";
const ROOM_CATEGORY: &str = "60";
const ROOM_COLOR: &str = "#6b7280";
const SIA: [&str; 6] = ["HNF", "NNF", "VF", "FF", "KGF", "AGF"];
const LEVEL_TOL: f64 = 0.005;
const LAYER_TOL: f64 = 0.0005;
fn round(x: f64, step: f64) -> f64 {
jsnum::round(x / step) * step
}
// ── Erkannte Bauteile ────────────────────────────────────────────────────────
struct MatLayer {
material: String,
thickness: f64,
color: Option<Vec<f64>>,
}
struct Info {
storey: Option<usize>,
color: Option<Vec<f64>>,
type_name: Option<String>,
layers: Vec<MatLayer>,
classified: bool,
}
struct WallData {
info: Info,
start: [f64; 2],
end: [f64; 2],
z0: f64,
z1: f64,
thickness: f64,
}
struct OpeningData {
info: Info,
host: usize,
kind: String,
position: f64,
width: f64,
sill: f64,
height: f64,
operation: Option<String>,
swing: f64,
hinge: f64,
}
struct SlabData {
info: Info,
outline: Vec<[f64; 2]>,
holes: Vec<Vec<[f64; 2]>>,
z0: f64,
z1: f64,
}
struct ColumnData {
info: Info,
center: [f64; 2],
rotation: f64,
round: bool,
a: f64,
b: f64,
z0: f64,
z1: f64,
}
struct SpaceData {
info: Info,
name: Option<String>,
long_name: Option<String>,
sia: Option<String>,
boundary: Vec<[f64; 2]>,
z0: f64,
}
struct Storey {
name: String,
elevation: f64,
}
#[derive(Default)]
struct Elements {
storeys: Vec<Storey>,
walls: Vec<WallData>,
openings: Vec<OpeningData>,
slabs: Vec<SlabData>,
columns: Vec<ColumnData>,
spaces: Vec<SpaceData>,
kept: Map<String, Value>,
}
fn s_of(v: Option<&Value>) -> Option<String> {
v.and_then(Value::as_str).map(str::to_string)
}
fn info_of(e: &Value) -> Info {
let layers = e
.get("layers")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.map(|l| MatLayer {
material: s_of(l.get("material")).unwrap_or_default(),
thickness: l.get("thickness").and_then(Value::as_f64).unwrap_or(f64::NAN),
color: color_of(l.get("color")),
})
.collect()
})
.unwrap_or_default();
Info {
storey: e.get("storey").and_then(Value::as_f64).filter(|s| *s >= 0.0 && s.fract() == 0.0).map(|s| s as usize),
color: color_of(e.get("color")),
type_name: s_of(e.get("typeName")),
layers,
classified: e.get("classifications").and_then(Value::as_array).is_some_and(|a| !a.is_empty()),
}
}
/// Ringe ab `start` (je Anzahl + Punkte); `None` bei kaputten Daten.
fn rings(v: &[f64], start: usize, count: f64) -> Option<Vec<Vec<[f64; 2]>>> {
let mut out = Vec::new();
let mut i = start;
let mut r = 0.0;
while r < count {
let n = *v.get(i)?;
i += 1;
if !(n >= 3.0) || i as f64 + 2.0 * n > v.len() as f64 {
return None;
}
let n = n as usize;
out.push((0..n).map(|k| [v[i + 2 * k], v[i + 2 * k + 1]]).collect());
i += 2 * n;
r += 1.0;
}
Some(out)
}
/// Erkannte Bauteile aus dem Bericht (`meta.elements`) und den Zahlen (vorher `decodeIfcElements`).
fn decode_elements(meta: &Value, data: &[f64]) -> Elements {
let mut out = Elements::default();
let Some(raw) = meta.get("elements") else { return out };
out.storeys = raw
.get("storeys")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.map(|s| Storey { name: s_of(s.get("name")).unwrap_or_default(), elevation: s.get("elevation").and_then(Value::as_f64).unwrap_or(f64::NAN) })
.collect()
})
.unwrap_or_default();
out.kept = raw.get("kept").and_then(Value::as_object).cloned().unwrap_or_default();
let mut wall_index: HashMap<i64, usize> = HashMap::new();
let mut rust_wall: i64 = 0;
for e in raw.get("elements").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) {
let kind = e.get("kind").and_then(Value::as_str).unwrap_or("");
let at = e.get("at").and_then(Value::as_f64).unwrap_or(-1.0);
let n = e.get("n").and_then(Value::as_f64).unwrap_or(-1.0);
let ok = at >= 0.0 && n >= 0.0 && at.fract() == 0.0 && n.fract() == 0.0 && (at + n) as usize <= data.len();
let v: &[f64] = if ok { &data[at as usize..(at + n) as usize] } else { &[] };
if !ok || !v.iter().all(|x| x.is_finite()) {
if kind == "wall" {
rust_wall += 1;
}
continue;
}
let info = info_of(e);
match kind {
"wall" => {
if v.len() == 7 {
wall_index.insert(rust_wall, out.walls.len());
out.walls.push(WallData { info, start: [v[0], v[1]], end: [v[2], v[3]], z0: v[4], z1: v[5], thickness: v[6] });
}
rust_wall += 1;
}
"opening" => {
let host = e.get("host").and_then(Value::as_f64).unwrap_or(-1.0);
let host = if host.fract() == 0.0 { wall_index.get(&(host as i64)).copied() } else { None };
if let (Some(host), 6) = (host, v.len()) {
out.openings.push(OpeningData {
info,
host,
kind: s_of(e.get("openingKind")).unwrap_or_else(|| "hole".into()),
position: v[0],
width: v[1],
sill: v[2],
height: v[3],
operation: s_of(e.get("operation")),
swing: v[4].signum() * (v[4] != 0.0) as u8 as f64,
hinge: v[5].signum() * (v[5] != 0.0) as u8 as f64,
});
}
}
"slab" => {
if let Some(r) = v.get(2).and_then(|&c| rings(v, 3, c)) {
if let Some((outline, holes)) = r.split_first() {
out.slabs.push(SlabData { info, z0: v[0], z1: v[1], outline: outline.clone(), holes: holes.to_vec() });
}
}
}
"column" => {
if v.len() == 7 {
let round = e.get("profile").and_then(Value::as_str) == Some("round");
out.columns.push(ColumnData { info, center: [v[0], v[1]], rotation: v[2], z0: v[3], z1: v[4], round, a: v[5], b: v[6] });
}
}
"space" => {
if let Some(mut r) = rings(v, 2, 1.0) {
out.spaces.push(SpaceData {
info,
name: s_of(e.get("name")),
long_name: s_of(e.get("longName")),
sia: s_of(e.get("sia")),
z0: v[0],
boundary: r.remove(0),
});
}
}
_ => {}
}
}
out
}
// ── Aufbau ───────────────────────────────────────────────────────────────────
/// Optionen: Dateiname (Namen der Kontext-Meshes), Gruppierung der Meshes.
#[derive(serde::Deserialize, Default)]
#[serde(default, rename_all = "camelCase")]
pub struct IfcOptions {
pub file_name: String,
pub group: Option<String>,
/// Bauteile erkennen ([B4]); sonst nur Kontext-Meshes ([B3]).
pub elements: bool,
}
pub struct IfcResult {
pub ops: Vec<Op>,
/// Zusammenfassung (nur mit `elements`).
pub summary: Option<Value>,
/// Bericht des Lesers (ohne Bauteil-Liste), Bauteile je Klasse, Dreiecke.
pub report: Value,
pub kept: Map<String, Value>,
pub context_objects: usize,
}
fn floor_base(l: &Value) -> f64 {
l.get("baseElevation").and_then(Value::as_f64).unwrap_or(0.0)
}
fn is_floor(l: &Value) -> bool {
l.get("kind").and_then(Value::as_str) == Some("floor")
}
fn id_of(v: &Value) -> &str {
v.get("id").and_then(Value::as_str).unwrap_or("")
}
fn pt(p: [f64; 2]) -> Value {
json!({"x": js_num(p[0]), "y": js_num(p[1])})
}
/// Ops für eine Liste, an die nur neue Elemente (`is_new`) angefügt bzw. eingeschoben wurden (`fieldOps`).
fn grown_list_ops(key: &str, old: Option<&Value>, list: Vec<(Value, bool)>) -> Vec<Op> {
let unique_ids = |a: &[Value]| {
let mut seen = HashSet::new();
a.iter().all(|e| e.get("id").and_then(Value::as_str).is_some_and(|id| seen.insert(id.to_string())))
};
match old.and_then(Value::as_array) {
Some(a) if unique_ids(a) => {
let mut ops = Vec::new();
let mut i = 0;
while i < list.len() {
if !list[i].1 {
i += 1;
continue;
}
let at = i;
let mut run = Vec::new();
while i < list.len() && list[i].1 {
run.push(list[i].0.clone());
i += 1;
}
ops.push(Op::Add { collection: key.into(), items: run, at: Some(at) });
}
ops
}
_ => {
if old.is_some_and(|o| o.as_array().is_some()) && !list.iter().any(|x| x.1) {
return Vec::new();
}
vec![Op::SetField { key: key.into(), value: Some(Value::Array(list.into_iter().map(|x| x.0).collect())), at: None }]
}
}
}
struct Ctx<'a> {
stamp: String,
summary: Map<String, Value>,
levels: Vec<(Value, bool)>,
components: Vec<(Value, bool)>,
hatch_id: String,
root: &'a Map<String, Value>,
}
impl Ctx<'_> {
fn new_id(&self, kind: &str) -> String {
format!("ifc-{kind}-{}-{}", self.stamp, next_seq())
}
fn bump(&mut self, k: &str) {
let n = self.summary.get(k).and_then(Value::as_f64).unwrap_or(0.0) + 1.0;
self.summary.insert(k.into(), js_num(n));
}
/// Geschosse aufsteigend nach Höhe (Index in `levels`), stabil.
fn floors_sorted(&self) -> Vec<usize> {
let mut f: Vec<usize> = (0..self.levels.len()).filter(|&i| is_floor(&self.levels[i].0)).collect();
f.sort_by(|&a, &b| floor_base(&self.levels[a].0).partial_cmp(&floor_base(&self.levels[b].0)).unwrap_or(std::cmp::Ordering::Equal));
f
}
fn component_for(&mut self, name: &str, color: Option<String>) -> String {
let key = name.trim().to_lowercase();
if let Some((c, _)) = self.components.iter().find(|(c, _)| c.get("name").and_then(Value::as_str).unwrap_or("").trim().to_lowercase() == key) {
return id_of(c).to_string();
}
let id = self.new_id("component");
let n = if name.trim().is_empty() { "IFC".to_string() } else { name.trim().to_string() };
self.components.push((json!({"id": id, "name": n, "color": color.unwrap_or_else(|| "#b0b0b0".into()), "hatchId": self.hatch_id, "joinPriority": 50}), true));
self.bump("components");
id
}
fn component_name(&self, id: &str) -> String {
self.components.iter().find(|(c, _)| id_of(c) == id).and_then(|(c, _)| c.get("name").and_then(Value::as_str)).unwrap_or("").trim().to_lowercase()
}
}
struct Spec {
material: String,
thickness: f64,
color: Option<String>,
}
fn layer_spec(e: &Info, t: f64) -> Vec<Spec> {
let ls = &e.layers;
let sum = ls.iter().fold(0.0, |s, l| s + l.thickness);
if !ls.is_empty() && ls.iter().all(|l| l.thickness > 0.0) && (sum - t).abs() <= 0.005 {
return ls.iter().map(|l| Spec { material: l.material.clone(), thickness: round(l.thickness, 1e-6), color: color_hex(l.color.as_deref()) }).collect();
}
let first = if ls.len() == 1 { Some(&ls[0]) } else { None };
let color = first.and_then(|f| f.color.as_deref()).or(e.color.as_deref());
vec![Spec { material: first.map(|f| f.material.clone()).unwrap_or_default(), thickness: round(t, 1e-6), color: color_hex(color) }]
}
fn type_name(e: &Info, t: f64) -> String {
match e.type_name.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
Some(n) => n.to_string(),
None => format!("IFC {} cm", js_number(round(t * 100.0, 0.1))),
}
}
/// Wand- bzw. Deckentyp mit diesen Schichten (vorhanden oder neu); `kind` = `walltype`/`ceilingtype`.
fn type_for(ctx: &mut Ctx, types: &mut Vec<(Value, bool)>, e: &Info, t: f64, kind: &str, counter: &str) -> String {
let spec = layer_spec(e, t);
let name = type_name(e, t);
let any_material = spec.iter().any(|l| !l.material.is_empty());
let found = types.iter().find(|(ty, _)| {
let have = ty.get("layers").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]);
let same = have.len() == spec.len()
&& have.iter().zip(&spec).all(|(l, w)| {
let th = l.get("thickness").and_then(Value::as_f64).unwrap_or(f64::NAN);
if (th - w.thickness).abs() > LAYER_TOL {
return false;
}
let cname = ctx.component_name(l.get("componentId").and_then(Value::as_str).unwrap_or(""));
w.material.is_empty() || cname == w.material.trim().to_lowercase()
});
same && (any_material || ty.get("name").and_then(Value::as_str) == Some(name.as_str()))
});
if let Some((ty, _)) = found {
return id_of(ty).to_string();
}
let id = ctx.new_id(kind);
let layers: Vec<Value> = spec.into_iter().map(|l| json!({"componentId": ctx.component_for(&l.material, l.color), "thickness": js_num(l.thickness)})).collect();
types.push((json!({"id": id, "name": name, "layers": layers}), true));
ctx.bump(counter);
id
}
fn list_of(root: &Map<String, Value>, key: &str) -> Vec<(Value, bool)> {
root.get(key).and_then(Value::as_array).map(|a| a.iter().map(|v| (v.clone(), false)).collect()).unwrap_or_default()
}
/// Bauteile + übrige Kontext-Meshes ins Projekt `root` (vorher `ifcElementsToProject`).
fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Elements, opts: &IfcOptions, now: f64) -> (Vec<Op>, Value, usize) {
let kept: f64 = el.kept.values().map(|v| v.as_f64().unwrap_or(f64::NAN)).sum();
let mut summary = Map::new();
for k in ["walls", "openings", "ceilings", "columns", "rooms", "floors", "wallTypes", "ceilingTypes", "components", "meshes", "classified"] {
summary.insert(k.into(), 0.into());
}
summary.insert("kept".into(), js_num(kept));
let hatches = root.get("hatches").and_then(Value::as_array).cloned().unwrap_or_default();
let hatch_id = hatches.iter().find(|h| id_of(h) == "none").or(hatches.first()).and_then(|h| h.get("id").and_then(Value::as_str)).unwrap_or("none").to_string();
let mut ctx = Ctx { stamp: stamp36(now), summary, levels: list_of(root, "drawingLevels"), components: list_of(root, "components"), hatch_id, root };
// Verschiebung bei Landeskoordinaten: gemeinsam für Bauteile und Meshes.
let mut extra = Vec::new();
for w in &el.walls {
extra.extend([w.start[0], w.start[1], w.end[0], w.end[1]]);
}
for s in &el.slabs {
s.outline.iter().for_each(|p| extra.extend(p));
}
for c in &el.columns {
extra.extend(c.center);
}
for s in &el.spaces {
s.boundary.iter().for_each(|p| extra.extend(p));
}
let [dx, dy] = geo_shift(products, project_geo_origin(root), &extra);
let mv = |p: [f64; 2]| pt([round(p[0] + dx, 1e-9), round(p[1] + dy, 1e-9)]);
// ── Geschosse ──
let mut top_of: HashMap<usize, f64> = HashMap::new();
for (s, z) in el.walls.iter().map(|w| (w.info.storey, w.z1)).chain(el.columns.iter().map(|c| (c.info.storey, c.z1))) {
if let Some(s) = s {
let t = top_of.get(&s).copied().unwrap_or(f64::NEG_INFINITY);
top_of.insert(s, jsnum::max(t, z));
}
}
let mut storey_floor: Vec<String> = Vec::new();
for (i, s) in el.storeys.iter().enumerate() {
if let Some((l, _)) = ctx.levels.iter().find(|(l, _)| is_floor(l) && (floor_base(l) - s.elevation).abs() <= LEVEL_TOL) {
storey_floor.push(id_of(l).to_string());
continue;
}
let height = match (el.storeys.get(i + 1), top_of.get(&i)) {
(Some(next), _) => next.elevation - s.elevation,
(None, Some(&top)) if top > s.elevation + 0.5 => top - s.elevation,
_ => 2.6,
};
let id = ctx.new_id("floor");
let name = if s.name.is_empty() { format!("IFC {}", js_number(round(s.elevation, 0.001))) } else { s.name.clone() };
let level = json!({
"id": id, "name": name, "kind": "floor", "visible": true, "locked": false,
"floorHeight": js_num(round(height, 1e-6)), "cutHeight": 1, "baseElevation": js_num(round(s.elevation, 1e-6)),
});
let floors = ctx.floors_sorted();
let higher = floors.iter().find(|&&f| floor_base(&ctx.levels[f].0) > s.elevation).copied();
let at = match (higher, floors.last()) {
(Some(h), _) => h,
(None, Some(&last)) => last + 1,
(None, None) => 0,
};
ctx.levels.insert(at, (level, true));
ctx.bump("floors");
storey_floor.push(id);
}
// Geschoss eines Bauteils: aus der Datei, sonst das höchste mit OK FB ≤ Unterkante. Ergebnis: (id, Basis, Höhe).
let floor_of = |ctx: &mut Ctx, storey: Option<usize>, z0: f64| -> (String, f64, f64) {
let fields = |l: &Value| (id_of(l).to_string(), floor_base(l), l.get("floorHeight").and_then(Value::as_f64).unwrap_or(0.0));
if let Some(id) = storey.and_then(|s| storey_floor.get(s)) {
if let Some((l, _)) = ctx.levels.iter().find(|(l, _)| id_of(l) == id) {
return fields(l);
}
}
let floors = ctx.floors_sorted();
let below: Vec<usize> = floors.iter().copied().filter(|&f| floor_base(&ctx.levels[f].0) <= z0 + LEVEL_TOL).collect();
if let Some(&f) = below.last().or(floors.first()) {
return fields(&ctx.levels[f].0);
}
let id = ctx.new_id("floor");
let level = json!({"id": id, "name": "IFC", "kind": "floor", "visible": true, "locked": false, "floorHeight": 2.6, "cutHeight": 1, "baseElevation": 0});
let out = fields(&level);
ctx.levels.push((level, true));
ctx.bump("floors");
out
};
let anchor_offset = |z: f64, base: f64| round(z - base, 1e-6);
// ── Typen ──
let mut wall_types = list_of(root, "wallTypes");
let mut ceiling_types = list_of(root, "ceilingTypes");
// ── Wände und Öffnungen ──
let mut walls: Vec<Value> = Vec::new();
for w in &el.walls {
let (fid, base, _) = floor_of(&mut ctx, w.info.storey, w.z0);
let height = round(w.z1 - w.z0, 1e-6);
let bottom = anchor_offset(w.z0, base);
let id = ctx.new_id("wall");
let wt = type_for(&mut ctx, &mut wall_types, &w.info, w.thickness, "walltype", "wallTypes");
let mut o = json!({"id": id, "type": "wall", "floorId": fid, "categoryCode": WALL_CATEGORY, "start": mv(w.start), "end": mv(w.end), "wallTypeId": wt, "height": js_num(height)});
if bottom.abs() > LEVEL_TOL {
o["bottom"] = json!({"mode": "floor", "floorId": fid, "offset": js_num(bottom)});
}
walls.push(o);
}
let door_types = root.get("doorTypes").and_then(Value::as_array).cloned().unwrap_or_default();
let window_types = root.get("windowTypes").and_then(Value::as_array).cloned().unwrap_or_default();
let mut openings: Vec<Value> = Vec::new();
for o in &el.openings {
let Some(host) = walls.get(o.host) else { continue };
let kind = if o.kind == "window" { "window" } else { "door" };
let op = o.operation.as_deref().unwrap_or("");
let sliding = op.contains("SLIDING");
let leaves = if op.starts_with("DOUBLE_DOOR") { 2.0 } else { 1.0 };
let door_type = (!op.is_empty())
.then(|| {
door_types.iter().find(|t| {
t.get("kind").and_then(Value::as_str) == Some(if sliding { "schiebe" } else { "dreh" }) && t.get("leafCount").and_then(Value::as_f64) == Some(leaves)
})
})
.flatten()
.or(door_types.first());
let wings: Option<f64> = match op {
"SINGLE_PANEL" => Some(1.0),
"DOUBLE_PANEL_VERTICAL" => Some(2.0),
"TRIPLE_PANEL_VERTICAL" => Some(3.0),
_ => None,
};
let window_type = wings.and_then(|w| window_types.iter().find(|t| t.get("wingCount").and_then(Value::as_f64) == Some(w))).or(window_types.first());
let type_id = match o.kind.as_str() {
"door" => door_type.and_then(|t| t.get("id")).and_then(Value::as_str),
"window" => window_type.and_then(|t| t.get("id")).and_then(Value::as_str),
_ => None,
};
let mut v = Map::new();
v.insert("id".into(), ctx.new_id("opening").into());
v.insert("type".into(), "opening".into());
v.insert("hostWallId".into(), host["id"].clone());
v.insert("categoryCode".into(), OPENING_CATEGORY.into());
v.insert("kind".into(), kind.into());
v.insert("position".into(), js_num(round(o.position, 1e-6)));
v.insert("width".into(), js_num(round(o.width, 1e-6)));
v.insert("height".into(), js_num(round(o.height, 1e-6)));
v.insert("sillHeight".into(), js_num(round(o.sill, 1e-6)));
if o.kind == "hole" {
v.insert("doorType".into(), "wandoeffnung".into());
}
if let Some(t) = type_id.filter(|t| !t.is_empty()) {
v.insert("typeId".into(), t.into());
}
if o.kind == "door" {
if o.hinge != 0.0 {
v.insert("hinge".into(), if o.hinge > 0.0 { "start" } else { "end" }.into());
}
if o.swing != 0.0 {
v.insert("swing".into(), if o.swing > 0.0 { "left" } else { "right" }.into());
}
}
if let (true, Some(w)) = (o.kind == "window", wings) {
if window_type.and_then(|t| t.get("wingCount")).and_then(Value::as_f64).unwrap_or(1.0) != w {
v.insert("wingCount".into(), js_num(w));
}
}
openings.push(Value::Object(v));
}
// ── Decken, Stützen, Räume ──
let mut ceilings: Vec<Value> = Vec::new();
let first_wall_type = root.get("wallTypes").and_then(Value::as_array).and_then(|a| a.first()).and_then(|t| t.get("id")).and_then(Value::as_str).map(str::to_string);
for s in &el.slabs {
let (fid, base, fh) = floor_of(&mut ctx, s.info.storey, s.z0);
let t = s.z1 - s.z0;
let floor_top = base + fh;
let mut v = Map::new();
v.insert("id".into(), ctx.new_id("ceiling").into());
v.insert("type".into(), "ceiling".into());
v.insert("floorId".into(), fid.clone().into());
v.insert("categoryCode".into(), CEILING_CATEGORY.into());
v.insert("outline".into(), s.outline.iter().map(|&p| mv(p)).collect());
if !s.holes.is_empty() {
v.insert("openings".into(), s.holes.iter().map(|h| h.iter().map(|&p| mv(p)).collect::<Value>()).collect());
}
let wt = first_wall_type.clone().or_else(|| wall_types.first().map(|(t, _)| id_of(t).to_string())).unwrap_or_default();
v.insert("wallTypeId".into(), wt.into());
let ct = type_for(&mut ctx, &mut ceiling_types, &s.info, t, "ceilingtype", "ceilingTypes");
v.insert("ceilingTypeId".into(), ct.into());
if (s.z1 - floor_top).abs() > LEVEL_TOL {
v.insert("top".into(), json!({"mode": "floor", "floorId": fid, "offset": js_num(anchor_offset(s.z1, base))}));
}
ceilings.push(Value::Object(v));
}
let mut columns: Vec<Value> = Vec::new();
for c in &el.columns {
let (fid, base, _) = floor_of(&mut ctx, c.info.storey, c.z0);
let bottom = anchor_offset(c.z0, base);
let material = c.info.layers.first().map(|l| l.material.clone()).filter(|m| !m.is_empty());
let mut v = Map::new();
v.insert("id".into(), ctx.new_id("column").into());
v.insert("type".into(), "column".into());
v.insert("floorId".into(), fid.clone().into());
v.insert("categoryCode".into(), COLUMN_CATEGORY.into());
v.insert("position".into(), mv(c.center));
v.insert(
"profile".into(),
if c.round {
json!({"kind": "round", "radius": js_num(round(c.a, 1e-6))})
} else {
json!({"kind": "rect", "width": js_num(round(c.a, 1e-6)), "depth": js_num(round(c.b, 1e-6))})
},
);
v.insert("rotation".into(), js_num(c.rotation));
v.insert("height".into(), js_num(round(c.z1 - c.z0, 1e-6)));
if let Some(m) = material {
let l0 = &c.info.layers[0];
let color = color_hex(l0.color.as_deref().or(c.info.color.as_deref()));
v.insert("componentId".into(), ctx.component_for(&m, color).into());
}
if bottom.abs() > LEVEL_TOL {
v.insert("bottom".into(), json!({"mode": "floor", "floorId": fid, "offset": js_num(bottom)}));
}
columns.push(Value::Object(v));
}
let room_color = crate::layers::flatten(root.get("layers").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]))
.into_iter()
.find(|c| c.get("code").and_then(Value::as_str) == Some(ROOM_CATEGORY))
.and_then(|c| c.get("color"))
.filter(|c| !c.is_null())
.cloned()
.unwrap_or_else(|| ROOM_COLOR.into());
let rooms_before = root.get("rooms").and_then(Value::as_array).map_or(0, Vec::len);
let mut rooms: Vec<Value> = Vec::new();
for s in &el.spaces {
let (fid, _, _) = floor_of(&mut ctx, s.info.storey, s.z0);
let boundary: Vec<Value> = s.boundary.iter().map(|&p| mv(p)).collect();
let sia_key = s.sia.as_deref().map(|x| x.trim().to_uppercase());
let sia = SIA.iter().find(|c| Some(**c) == sia_key.as_deref()).copied().unwrap_or("HNF");
let n = boundary.len() as f64;
let (sx, sy) = boundary.iter().fold((0.0, 0.0), |(a, b), p| (a + p["x"].as_f64().unwrap_or(f64::NAN), b + p["y"].as_f64().unwrap_or(f64::NAN)));
let name = [s.long_name.as_deref(), s.name.as_deref()].into_iter().flatten().find(|x| !x.is_empty()).map(str::to_string).unwrap_or_else(|| format!("Raum {}", rooms_before + rooms.len() + 1));
rooms.push(json!({
"id": ctx.new_id("room"), "type": "room", "floorId": fid, "categoryCode": ROOM_CATEGORY, "siaCategory": sia,
"name": name, "boundary": boundary, "color": room_color, "stampAnchor": {"x": js_num(sx / n), "y": js_num(sy / n)},
}));
}
// ── Übrige Bauteile als Kontext-Mesh ──
let meshes = ifc_meshes(products, &opts.file_name, opts.group.as_deref().unwrap_or("auto"), [dx, dy], now);
let n_meshes = meshes.len();
let classified = el.walls.iter().filter(|w| w.info.classified).count()
+ el.openings.iter().filter(|o| o.kind != "hole" && o.info.classified).count()
+ el.slabs.iter().filter(|s| s.info.classified).count()
+ el.columns.iter().filter(|c| c.info.classified).count()
+ el.spaces.iter().filter(|s| s.info.classified).count()
+ products.iter().filter(|p| !p.classifications.is_empty()).count();
for (k, n) in [("walls", walls.len()), ("openings", openings.len()), ("ceilings", ceilings.len()), ("columns", columns.len()), ("rooms", rooms.len()), ("meshes", n_meshes), ("classified", classified)] {
ctx.summary.insert(k.into(), n.into());
}
let mut ops = Vec::new();
ops.extend(grown_list_ops("drawingLevels", root.get("drawingLevels"), std::mem::take(&mut ctx.levels)));
ops.extend(grown_list_ops("components", root.get("components"), std::mem::take(&mut ctx.components)));
ops.extend(grown_list_ops("wallTypes", root.get("wallTypes"), wall_types));
if !ceiling_types.is_empty() || root.get("ceilingTypes").is_some_and(|v| crate::grips::truthy(Some(v))) {
ops.extend(grown_list_ops("ceilingTypes", root.get("ceilingTypes"), ceiling_types));
}
if !walls.is_empty() {
ops.push(Op::Add { collection: "walls".into(), items: walls, at: None });
}
for (key, items) in [("openings", openings), ("ceilings", ceilings), ("columns", columns), ("rooms", rooms)] {
if root.get(key).is_some_and(|v| crate::grips::truthy(Some(v))) {
if !items.is_empty() {
ops.push(Op::Add { collection: key.into(), items, at: None });
}
} else {
ops.push(Op::SetField { key: key.into(), value: Some(Value::Array(items)), at: None });
}
}
if n_meshes > 0 {
ops.extend(context_ops(root, meshes));
}
let _ = ctx.root;
(ops, Value::Object(ctx.summary), n_meshes)
}
/// IFC ins Projekt `root`: als Kontext-Meshes oder (mit `opts.elements`) als Bauteile.
pub fn ifc_import(root: &Map<String, Value>, meta_json: &str, positions: &[f64], indices: &[f64], element_data: &[f64], opts: &IfcOptions, now: f64) -> Result<IfcResult, String> {
let meta: Value = serde_json::from_str(meta_json).map_err(|e| format!("IFC-Bericht: {e}"))?;
let products = crate::import_context::decode_ifc_products(&meta, positions, indices)?;
let report = crate::import_context::ifc_report(&meta, &products);
if opts.elements {
let el = decode_elements(&meta, element_data);
let kept = el.kept.clone();
let (ops, summary, n) = elements_ops(root, &products, &el, opts, now);
// Statt der Roh-Bauteile die Zusammenfassung (an derselben Stelle des Berichts).
let mut report = report;
if let Some(r) = report.as_object_mut() {
r.insert("elements".into(), summary.clone());
}
return Ok(IfcResult { ops, summary: Some(summary), report, kept, context_objects: n });
}
let shift = geo_shift(&products, project_geo_origin(root), &[]);
let meshes = ifc_meshes(&products, &opts.file_name, opts.group.as_deref().unwrap_or("auto"), shift, now);
let n = meshes.len();
Ok(IfcResult { ops: context_ops(root, meshes), summary: None, report, kept: Map::new(), context_objects: n })
}
+3
View File
@@ -92,6 +92,9 @@ pub mod commands;
pub mod cmd_transform;
pub mod cmd_edit;
pub mod polyline_vertex;
pub mod import_drawing;
pub mod import_context;
pub mod import_ifc;
#[cfg(feature = "web")]
mod web;
+214
View File
@@ -0,0 +1,214 @@
//! Bindungen der Import-Umwandlung ([K4] S4, `crate::import_drawing`, `crate::import_ifc`,
//! `crate::import_context`): das Format-Modul (eigenes WASM `pkgFileIo`) liest die Datei in flache Puffer,
//! der Kern macht daraus Ops und wendet sie als EINEN Undo-Schritt auf das Dokument an.
//!
//! Antworten als JSON; Fehler (kaputter Puffer, Dokument nicht offen) als Text mit `\u{1}` vorn, von der
//! Prüfung zurückgewiesene Änderungen als `{"problems":[…]}` (Dokument unverändert).
use super::document::with_doc;
use crate::document::Document;
use crate::import_drawing::{self as imp, Decision, Source};
use crate::ops::Op;
use serde_json::{json, Value};
use wasm_bindgen::prelude::wasm_bindgen;
fn err(e: impl std::fmt::Display) -> String {
format!("\u{1}{e}")
}
fn now_of(now_ms: f64) -> f64 {
if now_ms.is_finite() { now_ms } else { 0.0 }
}
/// Ops als JSON-Liste, ohne die Elemente zu kopieren (grosse Importe: 10⁵ Zeichnungen).
pub(crate) fn write_ops(out: &mut Vec<u8>, ops: &[Op]) {
out.push(b'[');
for (i, op) in ops.iter().enumerate() {
if i > 0 {
out.push(b',');
}
match op {
Op::Add { collection, items, at } => {
out.extend_from_slice(b"{\"kind\":\"add\",\"collection\":");
let _ = serde_json::to_writer(&mut *out, collection);
out.extend_from_slice(b",\"items\":[");
for (k, it) in items.iter().enumerate() {
if k > 0 {
out.push(b',');
}
let _ = serde_json::to_writer(&mut *out, it);
}
out.push(b']');
if let Some(a) = at {
out.extend_from_slice(format!(",\"at\":{a}").as_bytes());
}
out.push(b'}');
}
op => {
let _ = serde_json::to_writer(&mut *out, &op.to_json());
}
}
}
out.push(b']');
}
/// Ops als Benutzer-Änderung anwenden; Antwort `{"ops":[…], …extra}` bzw. `{"problems":[…]}`.
fn commit(d: &mut Document, ops: Vec<Op>, extra: &[(&str, Value)], key: &str, now: f64) -> String {
let mut out: Vec<u8> = b"{\"ops\":".to_vec();
write_ops(&mut out, &ops);
for (k, v) in extra {
out.push(b',');
let _ = serde_json::to_writer(&mut out, k);
out.push(b':');
let _ = serde_json::to_writer(&mut out, v);
}
out.push(b'}');
let text = String::from_utf8(out).unwrap_or_default();
if ops.is_empty() {
return text;
}
let marks = text.contains("\\u0001");
let key = (!key.is_empty()).then_some(key);
match d.commit(ops, key, now, marks) {
Ok(()) => text,
Err(problems) => json!({ "problems": problems }).to_string(),
}
}
fn source_of(json: &str) -> Source {
serde_json::from_str(json).unwrap_or_default()
}
/// Zusammenfassung eines gelesenen Zeichnungs-Imports für den Dialog (Zahlen, Layer, Diagnose, Layouts).
/// `geom` = Stücke (`[n, len_0 …, daten …]`), `strings_json` = String-Tabellen je Stück, `source_json` s. [`Source`].
#[wasm_bindgen]
pub fn import_drawing_summary(geom: &[f64], strings_json: &str, source_json: &str) -> String {
match imp::read_source(geom, strings_json, &source_of(source_json), 0.0) {
Ok(d) => imp::summary_json(&d).to_string(),
Err(e) => err(e),
}
}
/// Die ganze Import-Form als JSON (Leseansicht für Tests/Diagnose, s. `import_drawing::view_json`).
#[wasm_bindgen]
pub fn import_drawing_view(geom: &[f64], strings_json: &str, source_json: &str, now_ms: f64) -> String {
match imp::read_source(geom, strings_json, &source_of(source_json), now_of(now_ms)) {
Ok(d) => imp::view_json(&d).to_string(),
Err(e) => err(e),
}
}
/// Nur die Meshes eines Zeichnungs-Imports als Kontext-Objekte (JSON-Liste), z. B. swissBUILDINGS3D-Kacheln.
#[wasm_bindgen]
pub fn import_drawing_meshes(geom: &[f64], strings_json: &str, source_json: &str, now_ms: f64) -> String {
match imp::read_source(geom, strings_json, &source_of(source_json), now_of(now_ms)) {
Ok(d) => Value::Array(imp::mesh_values(&d)).to_string(),
Err(e) => err(e),
}
}
/// Bestätigten Zeichnungs-Import (DXF/DWG/PDF) als EINEN Undo-Schritt ins Dokument `h` übernehmen.
/// `decision_json` s. [`Decision`]. Antwort: `{"ops":[…],"levelId":"…","drawings":n,"meshes":n}`.
#[wasm_bindgen]
pub fn doc_import_drawing(h: u32, geom: &[f64], strings_json: &str, source_json: &str, decision_json: &str, key: &str, now_ms: f64) -> String {
let now = now_of(now_ms);
let dec: Decision = match serde_json::from_str(decision_json) {
Ok(d) => d,
Err(e) => return err(format!("Import-Entscheidung: {e}")),
};
let d = match imp::read_source(geom, strings_json, &source_of(source_json), now) {
Ok(d) => d,
Err(e) => return err(e),
};
with_doc(h, |doc| {
let r = imp::import_ops(doc.root(), &d, &dec, now);
let extra = [("levelId", Value::from(r.level_id)), ("drawings", r.drawings.into()), ("meshes", r.meshes.into())];
commit(doc, r.ops, &extra, key, now)
})
.unwrap_or_else(|| err("Dokument nicht offen"))
}
/// IFC ins Dokument `h` übernehmen (Kontext-Meshes, mit `opts.elements` Bauteile), ein Undo-Schritt.
/// `meta` = Bericht des Lesers (JSON), dazu Positionen, Indizes und (Bauteile) die Zahlen der Erkennung.
/// Antwort: `{"ops":[…],"report":{…},"summary":{…}|null,"kept":{…},"contextObjects":n}`.
#[wasm_bindgen]
pub fn doc_import_ifc(h: u32, meta: &str, positions: &[f64], indices: &[u32], element_data: &[f64], opts_json: &str, key: &str, now_ms: f64) -> String {
let now = now_of(now_ms);
let opts: crate::import_ifc::IfcOptions = serde_json::from_str(opts_json).unwrap_or_default();
let idx: Vec<f64> = indices.iter().map(|&i| i as f64).collect();
with_doc(h, |doc| match crate::import_ifc::ifc_import(doc.root(), meta, positions, &idx, element_data, &opts, now) {
Ok(r) => {
let extra = [
("report", r.report),
("summary", r.summary.unwrap_or(Value::Null)),
("kept", Value::Object(r.kept)),
("contextObjects", r.context_objects.into()),
];
commit(doc, r.ops, &extra, key, now)
}
Err(e) => err(e),
})
.unwrap_or_else(|| err("Dokument nicht offen"))
}
fn strings_of(json: &str) -> Result<Vec<String>, String> {
serde_json::from_str(json).map_err(|e| format!("Import-Texte: {e}"))
}
/// 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((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),
}
}
/// Optionen des Mesh-Imports: Dateiname, Platzierung (`center`|`original`), Gruppierung (`object`|`merge`|`auto`).
#[derive(serde::Deserialize, Default)]
#[serde(default, rename_all = "camelCase")]
struct MeshOptions {
file_name: String,
placement: Option<String>,
group: Option<String>,
}
/// Gelesenes 3D-Modell (OBJ/STL/glTF/PLY) als Kontext-Meshes ins Dokument `h`, ein Undo-Schritt.
/// Antwort: `{"ops":[…],"report":{…},"contextObjects":n}`.
#[wasm_bindgen]
pub fn doc_import_mesh(h: u32, flat: &[f64], strings_json: &str, opts_json: &str, key: &str, now_ms: f64) -> String {
let now = now_of(now_ms);
let opts: MeshOptions = serde_json::from_str(opts_json).unwrap_or_default();
let (objects, report) = match strings_of(strings_json).and_then(|s| crate::import_context::decode_mesh(flat, &s)) {
Ok(r) => r,
Err(e) => return err(e),
};
with_doc(h, |doc| {
let origin = crate::import_context::project_geo_origin(doc.root());
let meshes = crate::import_context::mesh_objects_to_meshes(
&objects,
&opts.file_name,
opts.placement.as_deref().unwrap_or("center"),
origin,
opts.group.as_deref().unwrap_or("auto"),
now,
);
let n = meshes.len();
let ops = crate::import_context::context_ops(doc.root(), meshes);
commit(doc, ops, &[("report", report), ("contextObjects", n.into())], key, now)
})
.unwrap_or_else(|| err("Dokument nicht offen"))
}
/// Kurzbericht einer gelesenen PDF-Seite (CLI `pdf-info`): Zahlen, Ebenen, Umriss.
#[wasm_bindgen]
pub fn pdf_page_info(geom: &[f64], strings_json: &str) -> String {
match strings_of(strings_json).and_then(|s| imp::decode_pdf(geom, &s)) {
Ok(p) => imp::pdf_page_info(&p).to_string(),
Err(e) => err(e),
}
}
+5 -3
View File
@@ -51,9 +51,11 @@ 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;
let codes = strings(&arg);
if crate::import_context::ensure_context_categories(&mut cats, codes.iter().map(String::as_str)) { Value::Array(cats) } else { Value::Null }
}
_ => return String::new(),
};
+1
View File
@@ -40,6 +40,7 @@ mod text_layout;
mod grips;
mod project_refs;
mod commands;
mod import;
use wasm_bindgen::prelude::wasm_bindgen;
+29 -49
View File
@@ -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<HTMLInputElement>(null);
// Verstecktes Datei-Input für den STEP-Import (Menü Datei, STEP importieren).
const stepInputRef = useRef<HTMLInputElement>(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<File | null>(null);
const importIfcFile = (f: File) => setPendingIfc(f);
const runIfcImport = (f: File, mode: IfcImportMode) => {
if (mode === "elements") {
void f
.arrayBuffer()
.then((buf) => readIfcElements(new Uint8Array(buf)))
.then(({ products, report, elements }) => {
let summary: ReturnType<typeof ifcElementsToProject>["summary"] | null = null;
let bounds: { x: number; y: number }[] = [];
// 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<typeof ifcElementsToProject>["summary"] = summary;
const empty = s.walls + s.ceilings + s.columns + s.rooms + s.meshes === 0;
notify(formatIfcElementsSummary(s, report, t), empty || report.truncated ? "warning" : "info");
}
})
.catch((err) =>
notify(`${t("ifc.import.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"),
);
return;
}
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() {
<PointCloudImportHost project={project} />
{/* 3D-Modell-Import (OBJ/STL/glTF/GLB/PLY): verstecktes Datei-Feld + Dialog. */}
<MeshImportHost
project={project}
notify={notify}
onImport={(meshes, report) => {
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). */}
+54 -77
View File
@@ -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<string, string>; cmds: string[] };
@@ -245,6 +234,7 @@ async function runPdfInfo(args: Args, path: string | undefined): Promise<number>
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<number>
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<numb
return 0;
}
/** Alle Kategorien inkl. verschachtelter (flach). */
function flattenAllCategories(ls: Project["layers"]): Project["layers"] {
return ls.flatMap((l) => [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<Project> {
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<Project["context"]>): 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<string, number> = {};
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). */
+79
View File
@@ -12,6 +12,43 @@ 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
* grosser DXF) hintereinander als `[n, len_0 … len_{n−1}, daten …]`, die String-Tabellen je Stück, und wie
* der Puffer zu lesen ist (DXF/DWG bzw. PDF-Seite mit Massstab).
*/
export interface ImportSource {
geom: Float64Array;
strings: string[][];
source: { kind: "drawing" } | { kind: "pdf"; scale: number; texts?: boolean };
}
/** Entscheidung des Import-Dialogs (bzw. CLI) für {@link ProjectDocument.importDrawing}; Texte schon übersetzt. */
export interface DrawingImportDecision {
target: { kind: "existing"; levelId: string } | { kind: "new"; name: string };
categoryMode: "byLayer" | "active";
activeCategoryCode: string;
importMeshes: boolean;
/** Mitte des Ausschnitts (Platzierung „viewCenter"); fehlt = an den Datei-Koordinaten. */
viewCenter?: [number, number];
/** Name einer neuen Zeichnung ohne Eingabe, `{n}` = Nummer. */
levelNameTemplate?: string;
/** Elternkategorie der neuen Layer-Kategorien. */
parentName?: string;
/** Name neuer Linienstile aus PDF-Strichmustern, `{pattern}` = Muster. */
dashStyleTemplate?: string;
}
/** Rohergebnis des IFC-Lesers (`fileio`): Bericht (JSON), Positionen, Indizes, Zahlen der Bauteil-Erkennung. */
export interface IfcFlatInput {
meta: string;
positions: Float64Array;
indices: Uint32Array;
elementData?: Float64Array;
}
/** Ergebnis des Ladens einer Projektdatei ({@link ProjectDocument.loadFile}). */
export type LoadFileResult =
@@ -308,6 +345,48 @@ export class ProjectDocument {
return { project, ops: r.ops };
}
/**
* Kern-Aufruf, der Ops rechnet und gleich als Benutzer-Änderung anwendet (Importe, [K4] S4): `call`
* bekommt das Handle und liefert `{ops, …}`, `{problems}` oder einen Fehlertext mit `\u0001` vorn (wirft).
* Die Leseansicht wird mit den angewendeten Ops nachgeführt; die übrigen Felder kommen unverändert zurück.
*/
private commitCore<R extends object>(base: Project, call: (h: number) => string): ({ project: Project; ops: CoreOp[] } & R) | { problems: string[] } {
this.ensure(base);
if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] };
const out = call(this.handle);
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
const r = fromMarkedJson<({ ops: CoreOp[] } & R) | { problems: string[] }>(out);
if ("problems" in r) return r;
const project = r.ops.length ? applyOps(base, r.ops) : base;
this.mirror = project;
return { ...r, project };
}
/**
* Zeichnungs-Import (DXF/DWG/PDF, [K4] S4): der Kern wandelt die gelesene Datei (`src`, Puffer des
* Format-Moduls) nach der Entscheidung des Dialogs in Ops (Zeichnungsebene, Kategorien je Layer,
* Linienstile, 2D-Zeichnungen, Kontext-Meshes) und wendet sie als EINEN Undo-Schritt an.
*/
importDrawing(base: Project, src: ImportSource, decision: DrawingImportDecision, now: number) {
return this.commitCore<{ levelId: string; drawings: number; meshes: number }>(base, (h) =>
core().doc_import_drawing(h, src.geom, JSON.stringify(src.strings), JSON.stringify(src.source), JSON.stringify(decision), "", now),
);
}
/** 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<IfcImportResult>(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: MeshImportReport; contextObjects: number }>(base, (h) =>
core().doc_import_mesh(h, flat.flat, JSON.stringify(flat.strings), JSON.stringify(opts), "", now),
);
}
/** Abfrage eines Befehls zwischen den Schritten (`doc_cmd_query`: Treffer, Vorschau-Formen), JSON-Antwort. */
cmdQuery<T>(req: object): T {
if (!this.handle) throw new Error("Kern-Abfrage „cmdQuery“: Dokument nicht offen");
+6 -6
View File
@@ -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";
+10
View File
@@ -102,6 +102,16 @@ export function addItems<K extends EntityCollection>(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<K extends EntityCollection>(
p: Project,
+3 -3
View File
@@ -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();
});
});
+15 -11
View File
@@ -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(/\[/);
});
});
+12 -15
View File
@@ -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<number>; indices: ArrayLike<number> }) => {
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]));
+1
View File
@@ -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",
+1
View File
@@ -1670,6 +1670,7 @@ export const en: Record<TranslationKey, string> = {
// Import dialog.
"import.title": "Import DXF",
"import.failed": "Import failed",
"import.close": "Close",
"import.file": "File",
"import.summary.heading": "Contents",
+9 -10
View File
@@ -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);
+3 -3
View File
@@ -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<DxfImportResult> {
export function parseDwg(data: ArrayBuffer, layout?: string): Promise<ParsedImport> {
return parseDxfAsync(data, undefined, layout);
}
+4 -3
View File
@@ -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);
+46 -61
View File
@@ -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/);
+19 -202
View File
@@ -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<string, number>;
/** 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<string, string>;
/** Strichstärke je Layer in Papier-mm (PDF-Import [76]: aus der Linienbreite) — für neue Kategorien. */
layerLineWeights?: Record<string, number>;
/** Füllfarbe je Layer (PDF-Import [76]): gefüllte Konturen dieses Layers bekommen sie statt des Grau. */
layerFillColors?: Record<string, string>;
/** Strichmuster je Layer in Papier-mm, an/aus/an/aus (PDF-Import [76], Operator `d`) — wird zum Linienstil. */
layerDashes?: Record<string, number[]>;
/** `$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<string, string> = {};
for (let n = num(), k = 0; k < n; k++) {
const name = str();
layerColors[name] = `#${(num() & 0xffffff).toString(16).padStart(6, "0")}`;
}
const entityCounts: Record<string, number> = {};
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,
};
}
+2 -2
View File
@@ -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.
+10 -46
View File
@@ -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<DxfImportResult> {
async function runParseWorker(data: ArrayBuffer, transfer: boolean, layout?: string): Promise<ImportChunk> {
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<string, string> = {};
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<DxfImportResult> {
): Promise<ParsedImport> {
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)]);
}
-50
View File
@@ -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();
});
});
-198
View File
@@ -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<Record<string, string>> = {},
layerLineWeights: Readonly<Record<string, number>> = {},
): { parent: LayerCategory | null; codeByLayer: Map<string, string> } {
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<string>();
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<string>(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);
}
-610
View File
@@ -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<string, number>;
}
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<string, number> } };
const raw = meta.elements;
const data = flat.elementData;
if (!raw || !data) return null;
const out: IfcElementsData = { storeys: raw.storeys, walls: [], openings: [], slabs: [], columns: [], spaces: [], kept: raw.kept ?? {} };
// Wand-Index in Rust → Index in `out.walls` (verworfene Wände fallen heraus).
const wallIndex = new Map<number, number>();
let rustWall = 0;
for (const e of raw.elements) {
const v = data.subarray(e.at, e.at + e.n);
if (v.length !== e.n || !v.every(Number.isFinite)) {
if (e.kind === "wall") rustWall++;
continue;
}
const info: IfcInfo = {
globalId: e.globalId,
ifcClass: e.ifcClass,
name: e.name,
storey: e.storey,
color: e.color,
typeName: e.typeName,
layers: e.layers ?? [],
...(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<number, number>();
const noteTop = (storey: number | null, z: number) => {
if (storey !== null) topOf.set(storey, Math.max(topOf.get(storey) ?? -Infinity, z));
};
for (const w of elements.walls) noteTop(w.storey, w.z1);
for (const c of elements.columns) noteTop(c.storey, c.z1);
const storeyFloor = elements.storeys.map((s, i) => {
const existing = levels.find((l) => l.kind === "floor" && Math.abs((l.baseElevation ?? 0) - s.elevation) <= LEVEL_TOL);
if (existing) return existing.id;
const next = elements.storeys[i + 1];
const top = topOf.get(i);
const height = next ? next.elevation - s.elevation : top !== undefined && top > s.elevation + 0.5 ? top - s.elevation : 2.6;
const level: DrawingLevel = {
id: newId("floor"),
name: s.name || `IFC ${round(s.elevation, 0.001)}`,
kind: "floor",
visible: true,
locked: false,
floorHeight: round(height, 1e-6),
cutHeight: 1,
baseElevation: round(s.elevation, 1e-6),
};
// Einfügen vor dem ersten höheren Geschoss, sonst nach dem letzten.
const floors = floorsSorted();
const higher = floors.find((l) => (l.baseElevation ?? 0) > s.elevation);
const at = higher ? levels.indexOf(higher) : floors.length ? levels.indexOf(floors[floors.length - 1]) + 1 : 0;
levels.splice(at, 0, level);
summary.floors++;
return level.id;
});
/** Geschoss eines Bauteils: aus der Datei, sonst das höchste mit OK FB ≤ Unterkante. */
const floorOf = (storey: number | null, z0: number): DrawingLevel => {
const id = storey !== null ? storeyFloor[storey] : undefined;
const byId = id ? levels.find((l) => l.id === id) : undefined;
if (byId) return byId;
const floors = floorsSorted();
const below = floors.filter((l) => (l.baseElevation ?? 0) <= z0 + LEVEL_TOL);
const f = below[below.length - 1] ?? floors[0];
if (f) return f;
const level: DrawingLevel = { id: newId("floor"), name: "IFC", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1, baseElevation: 0 };
levels.push(level);
summary.floors++;
return level;
};
const anchorOffset = (z: number, f: DrawingLevel) => round(z - (f.baseElevation ?? 0), 1e-6);
// ── Materialien und Typen ──
const components: Component[] = [...project.components];
const hatchId = project.hatches.find((h) => h.id === "none")?.id ?? project.hatches[0]?.id ?? "none";
const componentFor = (name: string, color: string | undefined): string => {
const key = name.trim().toLowerCase();
const found = components.find((c) => c.name.trim().toLowerCase() === key);
if (found) return found.id;
const c: Component = { id: newId("component"), name: name.trim() || "IFC", color: color ?? "#b0b0b0", hatchId, joinPriority: 50 };
components.push(c);
summary.components++;
return c.id;
};
/** Schichten eines Bauteils der Dicke `t`: die der Datei, wenn sie aufgehen, sonst eine Schicht. */
const layerSpec = (e: IfcInfo, t: number): { material: string; thickness: number; color?: string }[] => {
const ls = e.layers;
const sum = ls.reduce((s, l) => s + l.thickness, 0);
if (ls.length > 0 && ls.every((l) => l.thickness > 0) && Math.abs(sum - t) <= 0.005) {
return ls.map((l) => ({ material: l.material, thickness: round(l.thickness, 1e-6), color: ifcColorHex(l.color) }));
}
const first = ls.length === 1 ? ls[0] : undefined;
return [{ material: first?.material ?? "", thickness: round(t, 1e-6), color: ifcColorHex(first?.color ?? e.color) }];
};
const sameLayers = (
have: { componentId: string; thickness: number }[],
want: { material: string; thickness: number }[],
): boolean =>
have.length === want.length &&
have.every((l, i) => {
if (Math.abs(l.thickness - want[i].thickness) > LAYER_TOL) return false;
const name = components.find((c) => c.id === l.componentId)?.name.trim().toLowerCase() ?? "";
return want[i].material ? name === want[i].material.trim().toLowerCase() : true;
});
const typeName = (e: IfcInfo, t: number) => e.typeName?.trim() || `IFC ${round(t * 100, 0.1)} cm`;
const wallTypes: WallType[] = [...project.wallTypes];
const wallTypeFor = (e: IfcInfo, t: number): string => {
const spec = layerSpec(e, t);
const name = typeName(e, t);
// Ohne Material: nur ein gleich benannter, gleich dicker Typ passt.
const found = wallTypes.find((wt) => sameLayers(wt.layers, spec) && (spec.some((l) => l.material) || wt.name === name));
if (found) return found.id;
const wt: WallType = {
id: newId("walltype"),
name,
layers: spec.map((l) => ({ componentId: componentFor(l.material, l.color), thickness: l.thickness })),
};
wallTypes.push(wt);
summary.wallTypes++;
return wt.id;
};
const ceilingTypes: CeilingType[] = [...(project.ceilingTypes ?? [])];
const ceilingTypeFor = (e: IfcInfo, t: number): string => {
const spec = layerSpec(e, t);
const name = typeName(e, t);
const found = ceilingTypes.find((ct) => sameLayers(ct.layers, spec) && (spec.some((l) => l.material) || ct.name === name));
if (found) return found.id;
const ct: CeilingType = {
id: newId("ceilingtype"),
name,
layers: spec.map((l) => ({ componentId: componentFor(l.material, l.color), thickness: l.thickness })),
};
ceilingTypes.push(ct);
summary.ceilingTypes++;
return ct.id;
};
// ── Wände und Öffnungen ──
const walls: Wall[] = [];
for (const w of elements.walls) {
const f = floorOf(w.storey, w.z0);
const height = round(w.z1 - w.z0, 1e-6);
const bottom = anchorOffset(w.z0, f);
walls.push({
id: newId("wall"),
type: "wall",
floorId: f.id,
categoryCode: WALL_CATEGORY,
start: mv(w.start),
end: mv(w.end),
wallTypeId: wallTypeFor(w, w.thickness),
height,
...(Math.abs(bottom) > LEVEL_TOL ? { bottom: { mode: "floor" as const, floorId: f.id, offset: bottom } } : {}),
});
}
const openings: Opening[] = [];
for (const o of elements.openings) {
const host = walls[o.host];
if (!host) continue;
const kind = o.kind === "window" ? "window" : "door";
const 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<string, number>)[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 = <K extends "openings" | "ceilings" | "columns" | "rooms">(key: K, items: EntityOf<K>[]): 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 | number>) => string,
): string {
const parts = [
tr("ifc.import.elements", {
schema: r.schema || "IFC",
walls: s.walls,
openings: s.openings,
ceilings: s.ceilings,
columns: s.columns,
rooms: s.rooms,
floors: s.floors,
meshes: s.meshes,
}),
];
if (s.kept) parts.push(tr("ifc.import.kept", { n: s.kept }));
if (s.classified) parts.push(tr("ifc.import.classified", { n: s.classified }));
return parts.join(" · ");
}
@@ -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)}`);
}
+21 -27
View File
@@ -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<number>, idx: ArrayLike<number>): 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<string, OsProduct> {
/** Vergleich je GlobalId; liefert Abweichungen als Text (leer = gleich). */
async function compare(file: string, rel: (p: IfcProduct) => number): Promise<string[]> {
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).
+55 -196
View File
@@ -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<IfcFlat | n
});
}
/** Rohergebnis → Bauteile (Ansichten in die flachen Puffer) + Bericht. */
export function decodeIfc(flat: IfcFlat): { products: IfcProduct[]; report: IfcImportReport } {
const meta = JSON.parse(flat.meta) as Omit<IfcImportReport, "products"> & { 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<IfcFlat> {
return (await readInWorker(bytes, elements)) ?? (await importIfcFlat(bytes, elements));
}
/** RGBA 0..1 → `#rrggbb` (Alpha entfällt). */
export function ifcColorHex(c: readonly number[] | null | undefined): string | undefined {
if (!c || c.length < 3 || !c.slice(0, 3).every((v) => Number.isFinite(v))) return undefined;
return rgbToHex({ r: c[0] * 255, g: c[1] * 255, b: c[2] * 255 });
/** 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<string, IfcProduct[]>();
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<string, number>; triangles: number };
summary: IfcElementsSummary | null;
kept: Record<string, number>;
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 | number>) => string,
): string {
const parts = [
tr("ifc.import.elements", {
schema: r.schema || "IFC",
walls: s.walls,
openings: s.openings,
ceilings: s.ceilings,
columns: s.columns,
rooms: s.rooms,
floors: s.floors,
meshes: s.meshes,
}),
];
if (s.kept) parts.push(tr("ifc.import.kept", { n: s.kept }));
if (s.classified) parts.push(tr("ifc.import.classified", { n: s.classified }));
return parts.join(" · ");
}
+1 -1
View File
@@ -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 }
+90
View File
@@ -0,0 +1,90 @@
// Gelesene Import-Datei (DXF/DWG/PDF) als Eingabe für den Kern ([K4] S4): das Format-Modul (`pkgFileIo`,
// `src-tauri/fileio`) liest die Datei in flache Puffer, der Kern (`core/src/import_drawing.rs`) macht daraus
// die Zusammenfassung für den Dialog und beim Bestätigen die Ops (`ProjectDocument.importDrawing`). TS hält
// nur die Puffer (keine Umwandlung in Konturen/Zeichnungen mehr).
import type { ImportedMesh } from "../model/types";
import { core } from "../engine/coreWasm";
import type { ImportSource } from "../core/document";
export type { ImportSource };
/** Diagnose: gelesene Entity-Typen (Typ → Anzahl) und Gesamtzahl. */
export interface ImportDiagnostics {
entityCounts: Record<string, number>;
total: number;
}
/** Was der Import-Dialog von der gelesenen Datei zeigt (`import_drawing::summary_json`). */
export interface ImportSummary {
contours: number;
texts: number;
meshes: number;
/** Layer der Konturen (in Fundreihenfolge). */
layers: string[];
diagnostics: ImportDiagnostics;
/** `$INSUNITS` der Datei (0 = ohne Einheit, 4 = mm …). */
insUnits?: number;
/** Meter je Zeicheneinheit (schon umgerechnet; PDF: Meter je Punkt beim gewählten Massstab). */
unitScale?: number;
/** Papierbereich-Layouts der Datei (ohne „Model"); `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;
}
/** Gelesene Datei + Zusammenfassung (Zustand des Import-Dialogs). */
export interface ParsedImport {
src: ImportSource;
summary: ImportSummary;
}
/** Ein gelesenes Stück (flacher Puffer + String-Tabelle des Format-Moduls). */
export interface ImportChunk {
geom: Float64Array;
strings: string[];
}
/** Stücke zu einer Kern-Eingabe zusammenpacken: `[n, len_0 … len_{n−1}, daten …]`. */
export function packChunks(chunks: readonly ImportChunk[], source: ImportSource["source"] = { kind: "drawing" }): ImportSource {
const n = chunks.length;
const total = chunks.reduce((s, c) => s + c.geom.length, 0);
const geom = new Float64Array(1 + n + total);
geom[0] = n;
let at = 1 + n;
chunks.forEach((c, i) => {
geom[1 + i] = c.geom.length;
geom.set(c.geom, at);
at += c.geom.length;
});
return { geom, strings: chunks.map((c) => c.strings), source };
}
function call<T>(out: string): T {
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
return JSON.parse(out) as T;
}
/** Zusammenfassung für den Dialog (Kern). Wirft bei kaputtem Puffer. */
export function importSummary(src: ImportSource): ImportSummary {
return call(core().import_drawing_summary(src.geom, JSON.stringify(src.strings), JSON.stringify(src.source)));
}
/** Gelesene Stücke → Dialog-Zustand. */
export function parsedImport(chunks: readonly ImportChunk[], source?: ImportSource["source"]): ParsedImport {
const src = packChunks(chunks, source);
return { src, summary: importSummary(src) };
}
/** Leerer Import (Fehlerfall im Dialog). */
export function emptyImport(): ParsedImport {
const src = packChunks([]);
return { src, summary: { contours: 0, texts: 0, meshes: 0, layers: [], diagnostics: { entityCounts: {}, total: 0 }, recovered: false } };
}
/** Nur die Meshes als Kontext-Objekte (z. B. swissBUILDINGS3D-Kacheln, je Ebene ein Mesh). */
export function importMeshes(src: ImportSource, now = Date.now()): ImportedMesh[] {
return call(core().import_drawing_meshes(src.geom, JSON.stringify(src.strings), JSON.stringify(src.source), now));
}
+148
View File
@@ -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<string, string>;
layerLineWeights: Record<string, number>;
layerFillColors: Record<string, string>;
layerDashes: Record<string, number[]>;
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<DrawingImportDecision> = {}) {
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<IfcImportReport, "products"> & {
products: (Omit<IfcProductView, "positions" | "indices"> & { positionCount: number; indexCount: number })[];
elements?: { storeys: { name: string; elevation: number }[]; elements: IfcRawElement[]; kept: Record<string, number> };
};
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[] };
}
+33 -45
View File
@@ -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 () => {
+19 -171
View File
@@ -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<string, MeshObject[]>();
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<MeshRead> {
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). */
-31
View File
@@ -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> = {}): 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() });
});
});
-55
View File
@@ -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<string, string>;
}
/** Ordnet jedem Muster einen Linienstil zu; gleiche Muster teilen sich einen. */
export function planDashLineStyles(
layerDashes: Readonly<Record<string, number[]>> | undefined,
existing: readonly LineStyle[],
): DashStylePlan {
const created: LineStyle[] = [];
const styleByLayer = new Map<string, string>();
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 };
}
+52 -41
View File
@@ -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]);
+30 -168
View File
@@ -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<PdfVectorPath, "lineWidth" | "stroke" | "dash">): 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<string, string> = {};
const layerLineWeights: Record<string, number> = {};
const layerFillColors: Record<string, string> = {};
const layerDashes: Record<string, number[]> = {};
const contours: Contour[] = [];
const pageArea = page.width * page.height;
const counts: Record<string, number> = {};
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<string, number> = {};
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<string, unknown> {
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<string, unknown>;
}
+3 -2
View File
@@ -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.
+8
View File
@@ -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)]);
});
});
+12 -49
View File
@@ -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<GeoCategory, ContextCategoryDef> = {
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<string>,
): LayerCategory[] {
const existing = new Set(flattenCategories(layers).map((c) => c.code));
const missing = new Set<string>();
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;
}
-9
View File
@@ -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)", () => {
-15
View File
@@ -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<Record<string, string>>,
weights: Readonly<Record<string, number>>,
): { children: LayerCategory[]; parentCode: string; codeByLayer: Map<string, string> } {
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[];
+3 -1
View File
@@ -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();
+29 -29
View File
@@ -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: <R extends object>(
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<DrawingLevel>) => 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<typeof run> | 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<typeof run> | 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(
+2 -2
View File
@@ -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.
+6 -5
View File
@@ -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,
+50 -163
View File
@@ -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<PlanViewHandle | null>,
) {
@@ -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<string, string> | 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 {
+1 -1
View File
@@ -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";
+24 -81
View File
@@ -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 && (
<li>{t("import.summary.texts", { n: textCount })}</li>
)}
<li>{t("import.summary.meshes", { n: meshes.length })}</li>
<li>{t("import.summary.meshes", { n: meshCount })}</li>
<li>
{layers.length > 0
? t("import.summary.layers", { layers: layers.join(", ") })
: t("import.summary.noLayers")}
</li>
</ul>
{parsed?.recovered && <div className="imp-warn">{t("import.summary.recovered")}</div>}
{summary?.recovered && <div className="imp-warn">{t("import.summary.recovered")}</div>}
{!hasDrawings && !hasMeshes && (
<div className="imp-warn">
{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 && (
<div className="imp-diag">
{formatDiagnostics(parsed.diagnostics)}
{formatDiagnostics(summary.diagnostics)}
</div>
)}
</div>
@@ -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 && (
<section className="imp-section">
<div className="imp-section-title">{t("import.layouts.heading")}</div>
{onSelectLayout ? (
<Dropdown
value={parsed.layout ?? ""}
value={summary.layout ?? ""}
onChange={(v) => 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({
/>
) : (
<ul className="imp-summary">
{parsed.layouts.map((l) => (
{summary.layouts.map((l) => (
<li key={l.name}>{`${l.name} · ${t("import.layouts.entities", { n: l.entities })}`}</li>
))}
</ul>
@@ -561,54 +555,3 @@ export function ImportDialog({
</div>
);
}
/**
* 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<string, string>,
lineStyleByLayer?: ReadonlyMap<string, string>,
) {
// 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<string, string>();
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];
}
+9 -28
View File
@@ -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<Uint8Array> {
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<MeshUnit>("m");
@@ -66,7 +48,7 @@ function MeshImportDialog({ req, project, onImport, notify }: { req: MeshImportR
const [placement, setPlacement] = useState<MeshPlacement>("center");
const [busy, setBusy] = useState(true);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<{ objects: MeshObject[]; report: MeshImportReport } | null>(null);
const [result, setResult] = useState<MeshRead | null>(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 (