diff --git a/TODO.md b/TODO.md index 8643908f..39ff5f9f 100644 --- a/TODO.md +++ b/TODO.md @@ -726,6 +726,34 @@ Code-Übernahme Lizenz der Abhängigkeiten prüfen, Pflicht [51]. truck-Extrusionen (nur Prisma-Näherung) nicht wie im 3D; Dreieckszahl nicht gegen die GPU-Puffer von render3d gemessen (Wand-Löcher und Decken aus denselben Ableitungen, Dächer/Stützen/Treppen/Öffnungen identisch); nicht in Blender/Twinmotion/Enscape geöffnet, nur Validator; nicht in der Tauri-App getestet. · S +- ◐ **[C12] Allgemeiner Mesh-Import als Kontext-Meshes** (Gegenstück zu [C11], 28.10.): Nachbargebäude, Möbel und + Umgebungsmodelle aus SketchUp/Blender/Rhino. Eigener Code in `src-tauri/fileio/src/mesh_import.rs` (OBJ + MTL, STL, + PLY mit Flächen) und `mesh_import_gltf.rs` (glTF 2.0/GLB mit kleinem JSON-Leser, keine neue Abhängigkeit; earcutr + für N-Ecke), Bindung `import_mesh` in `pkgFileIo`. OBJ: `o`/`g`/`usemtl` → je Objekt+Material ein Mesh (Gruppe = Ebene), + Polygone trianguliert (Drehsinn bleibt), negative Indizes, MTL `Kd`/`d`/`Tr` (`.mtl` nur, wenn mitgegeben). STL: ASCII + (mehrere `solid`) und binär, Eckpunkte verschweisst, Farbvarianten VisCAM/SolidView und Magics (`COLOR=`). glTF: + .gltf (Data-URI, externe `.bin` nur wenn mitgegeben) und .glb, Knoten-Hierarchie (Matrix oder TRS, Spiegelung dreht + die Wicklung), TRIANGLES/STRIP/FAN, Indizes u8/u16/u32, normalisierte Ganzzahl-Positionen, `baseColorFactor` → sRGB + als `color`; Draco/Meshopt → Fehlermeldung. PLY ohne Flächen → Fehler `[punktwolke]`, die App öffnet dann den + Punktwolken-Import. Achse: glTF Y-up = Umkehr der Export-Abbildung (Datei (X,Y,Z) → Modell (X,−Z,Y)); OBJ/STL/PLY + Z oben / Y oben / automatisch (Kopfkommentar „Dossier/Blender/Rhinoceros“, dann kleinste Ausdehnung, sonst OBJ Y, + STL/PLY Z; `up_certain` meldet, ob belastbar). Einheit mm/cm/m/inch/foot (glTF immer m). Budget 6 Mio. Dreiecke, + 24 Mio. Eckpunkte; NaN/Index ausserhalb/entartet werden verworfen und gezählt, nie Panic. TS: `io/meshImport.ts` + (+ `meshImport.worker.ts`, Rückfall im Thread), Abbildung wie [B3] (`color`, `layer` = Gruppe; > 2000 Objekte je + Gruppe+Farbe zusammengelegt), Dialog `ui/MeshImportDialog.tsx` (Einheit, Achse mit Erkennungsanzeige, Platzierung + „Projekt-Nullpunkt“ = Grundriss-Mitte auf 0 und Unterkante auf z = 0 / „Original-Koordinaten“ mit LV95-Rückschub wie IFC), + Menü „3D-Modell importieren …“ (mehrere Dateien: Modell + `.mtl`/`.bin`), Drag & Drop (auch mehrere Dateien), + CLI `import-mesh [--unit] [--up] [--placement] [--out]` und `convert` mit obj/stl/gltf/glb/ply als Eingabe + (Begleitdateien aus dem Verzeichnis). Einfügen nur über `setProject`/Ops (`addContextObjectsAndFit`). + Prüfung: 27 Rust-Tests (Rundreise glb/gltf/obj/stl mit den eigenen Schreibern: Dreieckszahl, Volumen, Lage, Farbe; + Quads/konkave N-Ecke, negative Indizes, MTL, Node-Matrizen/TRS, Strip/Fan, externe `.bin`, Budget, jede Kürzung gültiger + Dateien und Müll ohne Panic), 13 vitest (Fassade, Platzierung, Worker-Protokoll) + 4 CLI-Tests. `src/io/swissBuildings3d.ts` + hat keinen eigenen OBJ-Parser (nur DXF/DWG werden gelesen, `.obj` steht nur in der Asset-Prioritätsliste) — dort nichts + umzustellen. **Offen:** keine Texturen/UVs/Normalen/Vertex-Farben (glTF `COLOR_0`, OBJ `v x y z r g b`), keine + Instanzen-Erweiterungen (`EXT_mesh_gpu_instancing`), Sparse-Accessors ignoriert, Draco/Meshopt nicht gelesen, + `KHR_materials_pbrSpecularGlossiness` ignoriert; STL-Magics-Bit-Belegung nach Beschreibung, nicht an echten Dateien geprüft; + Achsen-Erkennung ist eine Heuristik; Dialog und Drag & Drop nicht in der Tauri-App und nicht im Browser angeklickt; + keine Dateien aus echtem SketchUp/Blender/Rhino gelesen (nur Rundreise und synthetische Fälle). · M ## Bewusst nicht übernommen diff --git a/src/App.tsx b/src/App.tsx index ce4c7a9c..743fd375 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -57,6 +57,9 @@ import { stepTextToImportedMeshes } from "./io/stepImport"; import { formatIfcReport, ifcBytesToImportedMeshes } from "./io/ifcImport"; import { formatIfcElementsSummary, ifcElementsToProject, readIfcElements } from "./io/ifcElements"; import { IfcImportDialog, type IfcImportMode } from "./ui/IfcImportDialog"; +import { MeshImportHost } from "./ui/MeshImportDialog"; +import { openMeshFileDialog, requestMeshImport, splitMeshFiles } from "./state/meshImportStore"; +import { formatMeshReport, isMeshFile } from "./io/meshImport"; import { projectGeoOrigin } from "./model/geoRebase"; import { applyClashMarkers, runClashCheck } from "./analysis/clash"; import { checkForUpdate } from "./update/checkForUpdate"; @@ -1748,6 +1751,7 @@ export default function App() { }; /** Datei aus Import-Dialog oder Drag & Drop: IFC direkt, sonst DXF/DWG-Dialog. */ const openImportForAnyFile = (f: File) => { + if (isMeshFile(f.name)) return requestMeshImport(f); if (isPointCloudFile(f.name)) return requestPointCloudImport(f); if (/\.ifc$/i.test(f.name)) importIfcFile(f); else openImportForFile(f); @@ -2456,6 +2460,7 @@ export default function App() { onImportStep: () => stepInputRef.current?.click(), onImportIfc: () => ifcInputRef.current?.click(), onImportPointCloud: () => openPointCloudFileDialog(), + onImportMesh: () => openMeshFileDialog(), onClashCheck: () => { const p0 = project; runClashCheck(p0) @@ -3146,6 +3151,13 @@ export default function App() { const { onAppDragEnter, onAppDragOver, onAppDragLeave, onAppDrop } = useFileDropImport( setDropActive, openImportForAnyFile, + (files) => { + // Mehrere Dateien: Modell + Begleitdateien (.mtl/.bin) gemeinsam an den Mesh-Import. + const r = splitMeshFiles(files); + if (!r) return false; + requestMeshImport(r.file, r.sidecars); + return true; + }, ); // Host-Context für die Panels — siehe state/usePanelHostBase.ts. @@ -3350,6 +3362,15 @@ export default function App() { /> {/* Punktwolken-Import ([27]): verstecktes Datei-Feld + Dialog (UI-Store, nicht im Projekt). */} + {/* 3D-Modell-Import (OBJ/STL/glTF/GLB/PLY): verstecktes Datei-Feld + Dialog. */} + { + if (meshes.length) addContextObjectsAndFit(meshes); + notify(formatMeshReport(report, t), meshes.length === 0 || report.truncated ? "warning" : "info"); + }} + /> {/* Verstecktes IFC-Datei-Input (Menü Datei, IFC importieren). */} dxfInputRef.current?.click()} onImportPointCloud={() => openPointCloudFileDialog()} + onImportMesh={() => openMeshFileDialog()} onUndo={undo} onRedo={redo} canUndo={canUndo} diff --git a/src/cli/importMesh.test.ts b/src/cli/importMesh.test.ts new file mode 100644 index 00000000..b5c480ad --- /dev/null +++ b/src/cli/importMesh.test.ts @@ -0,0 +1,66 @@ +// dossier-cli import-mesh und convert mit Mesh-Eingabe: Rundreise über echte Dateien (glb, gltf, obj+mtl, stl). +import { beforeAll, describe, expect, it } from "vitest"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { run } from "./main"; +import { parseProjectFile, sampleProject, serializeProject } from "../core"; +import type { Project } from "../core"; + +const dir = mkdtempSync(join(tmpdir(), "dossier-import-mesh-")); +const p = (name: string) => join(dir, name); +const obp = p("demo.obp"); + +/** Projektdatei lesen; schlägt der Test fehl, wenn sie ungültig ist. */ +function load(path: string): Project { + const r = parseProjectFile(readFileSync(path, "utf8")); + if (!r.ok) throw new Error(r.error); + return r.project; +} + +beforeAll(() => { + process.env.DOSSIER_WASM_DIR = join(process.cwd(), "src", "engine"); + writeFileSync(obp, serializeProject(sampleProject)); +}); + +describe("dossier-cli: Mesh-Import", () => { + it("convert: glb/gltf/obj/stl → obp mit Kontext-Meshes", async () => { + for (const ext of ["glb", "gltf", "obj", "stl"]) { + expect(await run(["convert", obp, p(`m.${ext}`)]), ext).toBe(0); + const out = p(`von-${ext}.obp`); + expect(await run(["convert", p(`m.${ext}`), out]), ext).toBe(0); + const project = load(out); + const ctx = project.context ?? []; + expect(ctx.length, ext).toBeGreaterThan(0); + expect(ctx.every((c) => c.type === "importedMesh" && c.indices.length > 0), ext).toBe(true); + } + }, 120_000); + + it("import-mesh: glTF mit Farbe, --out schreibt das Projekt", async () => { + const out = p("import.obp"); + expect(await run([obp, "import-mesh", p("m.glb"), "--out", out, "--placement", "original"])).toBe(0); + const project = load(out); + const before = sampleProject.context?.length ?? 0; + expect((project.context ?? []).length).toBeGreaterThan(before); + // Wände des Beispielprojekts haben Farben aus ihren Bauteilen. + expect((project.context ?? []).some((c) => c.type === "importedMesh" && typeof c.color === "string")).toBe(true); + }, 120_000); + + it("import-mesh: OBJ mit MTL aus dem Verzeichnis, Einheit und Achse", async () => { + writeFileSync(p("z.obj"), "mtllib z.mtl\no Kiste\nusemtl rot\nv 0 0 0\nv 1000 0 0\nv 0 1000 0\nv 0 0 2000\nf 1 3 2\nf 1 2 4\nf 2 3 4\nf 3 1 4\n"); + writeFileSync(p("z.mtl"), "newmtl rot\nKd 1 0 0\n"); + const out = p("z.obp"); + expect(await run([obp, "import-mesh", p("z.obj"), "--unit", "mm", "--up", "z", "--placement", "original", "--out", out])).toBe(0); + const project = load(out); + const m = (project.context ?? []).find((c) => c.name === "Kiste"); + if (m?.type !== "importedMesh") throw new Error("Kiste fehlt"); + expect(m.color).toBe("#ff0000"); + expect(Math.max(...m.positions.filter((_, i) => i % 3 === 2))).toBeCloseTo(2, 9); + }, 60_000); + + it("ungültige Optionen und kaputte Dateien: Exit-Code ≠ 0", async () => { + expect(await run([obp, "import-mesh", p("z.obj"), "--unit", "km"]).catch(() => 1)).not.toBe(0); + writeFileSync(p("kaputt.glb"), "kein glb"); + expect(await run([obp, "import-mesh", p("kaputt.glb")]).catch(() => 1)).not.toBe(0); + }, 60_000); +}); diff --git a/src/cli/main.ts b/src/cli/main.ts index ace62ff9..9134493d 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -17,6 +17,8 @@ // dossier-cli import-ifc [--out neu.obp] [--group product|class] [--elements] // IFC als Kontext-Meshes ([B3]), mit --elements als echte // Bauteile ([B4]); Bericht als JSON auf stdout +// dossier-cli import-mesh [--out neu.obp] [--unit mm|cm|m|inch|foot] [--up z|y|auto] +// [--placement center|original] 3D-Modell als Kontext-Meshes; Bericht als JSON // dossier-cli model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png) // dossier-cli pointcloud-info [--voxel 0.05] [--max 2000000] // Punktwolke lesen ([B9]) und Bericht als JSON (ohne Projekt) @@ -46,6 +48,10 @@ import { readIfcElements, ifcElementsToProject, ifcToImportedMeshes, + readMesh, + meshObjectsToImportedMeshes, + isMeshFile, + MESH_UNITS, projectGeoOrigin, ensureContextCategories, projectToWorldCoords, @@ -270,8 +276,8 @@ export async function run(argv: string[]): Promise { if (file === "pdf-info") return runPdfInfo(args, command); if (!file || (!command && args.cmds.length === 0)) { process.stderr.write( - "Aufruf: dossier-cli [Optionen]\n" + - " dossier-cli convert [--cmd \"befehl …\"]…\n" + + "Aufruf: dossier-cli [Optionen]\n" + + " dossier-cli convert [--cmd \"befehl …\"]…\n" + " dossier-cli --cmd \"befehl …\" [--cmd …] ({last} = zuletzt geschriebene Datei)\n" + " dossier-cli pointcloud-info [--voxel 0.05] [--max 2000000]\n" + " dossier-cli bcf-info \n" + @@ -331,6 +337,7 @@ async function importAny(path: string, args: Args): Promise { const fileName = path.split(/[\\/]/).pop() ?? path; const base: Project = { ...emptyProject, name: fileName.replace(/\.[^.]+$/, "") }; if (ext === "ifc") return (await ifcInto(base, bytes, fileName, args)).next; + if (isMeshFile(fileName)) return (await meshInto(base, bytes, path, args)).next; if (ext === "dxf" || ext === "dwg" || ext === "pdf") { await loadFileio(); let parsed; @@ -363,7 +370,7 @@ async function importAny(path: string, args: Args): Promise { ]; return applyOps(base, diffToOps(base, { ...base, layers, drawings2d: drawings, context: [...parsed.meshes] })); } - return fail(`Eingabeformat nicht unterstützt: .${ext} (obp, dxf, dwg, ifc, pdf)`); + return fail(`Eingabeformat nicht unterstützt: .${ext} (obp, dxf, dwg, ifc, pdf, obj, stl, gltf, glb, ply)`); } /** `convert `: Eingabe nach Endung lesen, Ausgabe nach Endung schreiben, dann `--cmd` ausführen. */ @@ -430,6 +437,60 @@ async function ifcInto(project: Project, bytes: Uint8Array, fileName: string, ar return { next, report: { ...report, byClass, triangles, contextObjects: meshes.length } }; } +/** Begleitdateien eines Mesh-Modells aus demselben Verzeichnis: `.mtl` (OBJ `mtllib`), externe `.bin` (glTF). */ +function meshSidecars(path: string, bytes: Uint8Array): { name: string; bytes: Uint8Array }[] { + const names: string[] = []; + const ext = extOf(path); + if (ext === "obj") { + for (const m of new TextDecoder().decode(bytes.subarray(0, Math.min(bytes.length, 1 << 20))).matchAll(/^mtllib[ \t]+(.+)$/gm)) { + names.push(...m[1].trim().split(/\s+/)); + } + } else if (ext === "gltf") { + try { + const j = JSON.parse(new TextDecoder().decode(bytes)) as { buffers?: { uri?: string }[] }; + for (const b of j.buffers ?? []) if (b.uri && !b.uri.startsWith("data:")) names.push(decodeURIComponent(b.uri)); + } catch { + /* kaputtes JSON meldet der Leser */ + } + } + const out: { name: string; bytes: Uint8Array }[] = []; + for (const n of names) { + try { + out.push({ name: n, bytes: new Uint8Array(readFileSync(join(dirname(path), n))) }); + } catch { + /* fehlende Datei meldet der Leser (MTL: Hinweis, glTF: Fehler) */ + } + } + return out; +} + +/** 3D-Modell (OBJ/STL/glTF/GLB/PLY) als Kontext-Meshes in ein Projekt übernehmen; `report` = Bericht für `import-mesh`. */ +async function meshInto(project: Project, bytes: Uint8Array, path: string, args: Args): Promise<{ next: Project; report: unknown }> { + const fileName = path.split(/[\\/]/).pop() ?? path; + const unit = args.flags.get("unit") ?? "m"; + if (!(MESH_UNITS as readonly string[]).includes(unit)) return fail(`--unit: ${MESH_UNITS.join("|")}`); + const up = args.flags.get("up") ?? "auto"; + if (up !== "auto" && up !== "z" && up !== "y") return fail("--up: z|y|auto"); + const placement = args.flags.get("placement") ?? "original"; + if (placement !== "center" && placement !== "original") return fail("--placement: center|original"); + let read; + try { + read = await readMesh(bytes, fileName, { unit: unit as (typeof MESH_UNITS)[number], up, files: meshSidecars(path, bytes) }); + } 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, + diffToOps(project, { + ...project, + context: [...(project.context ?? []), ...meshes], + layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))), + }), + ); + return { next, report: { ...read.report, contextObjects: meshes.length } }; +} + /** Führt EINEN Befehl gegen ein geladenes Projekt aus (Rückgabe = Exit-Code). */ async function execute(project: Project, file: string, command: string, rest: string[], args: Args): Promise { const scale = Number(args.flags.get("scale") ?? 100); @@ -582,6 +643,21 @@ async function execute(project: Project, file: string, command: string, rest: st if (target) out(args, serializeProject(r.next), target); return 0; } + case "import-mesh": { + const src = rest[0]; + if (!src) fail("import-mesh: Modelldatei fehlt"); + let bytes: Uint8Array; + try { + bytes = new Uint8Array(readFileSync(src)); + } catch (e) { + fail(`Datei nicht lesbar: ${src} (${e instanceof Error ? e.message : String(e)})`); + } + const r = await meshInto(project, bytes, src, args); + process.stdout.write(JSON.stringify(r.report, null, 2) + "\n"); + const target = args.flags.get("out"); + if (target) out(args, serializeProject(r.next), target); + return 0; + } case "mcp": await serveStdio(file); return 0; diff --git a/src/core/extra.ts b/src/core/extra.ts index 20faa860..98e03d02 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -37,3 +37,5 @@ export { readPointCloud, readPointCloudFlat, isPointCloudFile, DEFAULT_MAX_POINT export type { PointCloudData, PointCloudOptions, PointCloudReport } from "../io/pointCloud"; export { readPdfVectorPage, pdfPageToImport, pdfPageInfo, pdfMetersPerPt, 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"; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 45d04135..e88e4af4 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1834,6 +1834,36 @@ export const de = { "ifc.importDialog.asElements": "Als Bauteile", "ifc.importDialog.asElementsHint": "Wände, Decken, Stützen, Türen/Fenster, Räume und Geschosse werden bearbeitbare Dossier-Bauteile; was nicht sicher abbildbar ist, bleibt Mesh.", "ifc.importDialog.import": "Importieren", + "menu.native.importMesh": "3D-Modell importieren …", + "mesh.import.title": "3D-Modell importieren", + "mesh.import.failed": "3D-Modell-Import fehlgeschlagen", + "mesh.import.done": "{format} importiert: {n} Objekte, {tris} Dreiecke als Kontext-Meshes", + "mesh.import.up": "Achse erkannt: {axis} oben", + "mesh.import.upUncertain": "Achse unsicher, angenommen: {axis} oben (im Import-Dialog wählbar)", + "mesh.import.dropped": "{n} ungültige oder entartete Flächen verworfen", + "mesh.import.truncated": "abgebrochen: zu viele Dreiecke", + "mesh.import.noFaces": "Die PLY-Datei enthält keine Flächen (Punktwolke): sie wird als Punktwolke geöffnet.", + "mesh.import.missingExternal": "Zusätzliche Dateien fehlen: {list}. Wählen Sie sie zusammen mit dem Modell aus (oder ziehen Sie alle Dateien gemeinsam ins Fenster).", + "mesh.importDialog.files": "Begleitdateien: {list}", + "mesh.importDialog.unit": "Einheit der Datei", + "mesh.importDialog.unitFixed": "glTF/GLB ist immer in Metern.", + "mesh.importDialog.unit.mm": "Millimeter", + "mesh.importDialog.unit.cm": "Zentimeter", + "mesh.importDialog.unit.m": "Meter", + "mesh.importDialog.unit.inch": "Zoll (inch)", + "mesh.importDialog.unit.foot": "Fuss (foot)", + "mesh.importDialog.up": "Achse nach oben", + "mesh.importDialog.upFixed": "glTF/GLB ist immer Y oben.", + "mesh.importDialog.up.auto": "Automatisch erkennen", + "mesh.importDialog.up.z": "Z oben (Rhino, CAD, 3D-Druck)", + "mesh.importDialog.up.y": "Y oben (SketchUp, Blender, Spieleformate)", + "mesh.importDialog.detected": "Erkannt: {axis} oben, {n} Objekte, {tris} Dreiecke, {size} m × {depth} m × {height} m", + "mesh.importDialog.detectedUncertain": "Achse unsicher: bitte prüfen. Erkannt: {axis} oben, {n} Objekte, {tris} Dreiecke", + "mesh.importDialog.placement": "Platzierung", + "mesh.importDialog.placement.center": "Am Projekt-Nullpunkt (Mitte im Grundriss, Unterkante auf 0)", + "mesh.importDialog.placement.original": "An Original-Koordinaten (Landeskoordinaten werden bei Standort-Bezug auf den Nullpunkt gerechnet)", + "mesh.importDialog.reading": "Datei wird gelesen …", + "mesh.importDialog.import": "Importieren", "recover.title": "Ungesicherte Arbeit gefunden", "recover.message": "Von „{name}“ gibt es eine automatische Sicherung vom {when}, die nicht gespeichert wurde.", "recover.unsaved": "unbenanntes Projekt", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index a4f94833..29c7aad1 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1793,6 +1793,36 @@ export const en: Record = { "ifc.importDialog.asElements": "As building elements", "ifc.importDialog.asElementsHint": "Walls, slabs, columns, doors/windows, rooms and storeys become editable Dossier elements; anything not safely mappable stays a mesh.", "ifc.importDialog.import": "Import", + "menu.native.importMesh": "Import 3D model …", + "mesh.import.title": "Import 3D model", + "mesh.import.failed": "3D model import failed", + "mesh.import.done": "{format} imported: {n} objects, {tris} triangles as context meshes", + "mesh.import.up": "Axis detected: {axis} up", + "mesh.import.upUncertain": "Axis uncertain, assumed: {axis} up (selectable in the import dialog)", + "mesh.import.dropped": "{n} invalid or degenerate faces dropped", + "mesh.import.truncated": "aborted: too many triangles", + "mesh.import.noFaces": "The PLY file has no faces (point cloud): opening it as a point cloud.", + "mesh.import.missingExternal": "Additional files are missing: {list}. Select them together with the model (or drop all files into the window together).", + "mesh.importDialog.files": "Companion files: {list}", + "mesh.importDialog.unit": "File unit", + "mesh.importDialog.unitFixed": "glTF/GLB is always in metres.", + "mesh.importDialog.unit.mm": "Millimetres", + "mesh.importDialog.unit.cm": "Centimetres", + "mesh.importDialog.unit.m": "Metres", + "mesh.importDialog.unit.inch": "Inches", + "mesh.importDialog.unit.foot": "Feet", + "mesh.importDialog.up": "Up axis", + "mesh.importDialog.upFixed": "glTF/GLB is always Y up.", + "mesh.importDialog.up.auto": "Detect automatically", + "mesh.importDialog.up.z": "Z up (Rhino, CAD, 3D printing)", + "mesh.importDialog.up.y": "Y up (SketchUp, Blender, game formats)", + "mesh.importDialog.detected": "Detected: {axis} up, {n} objects, {tris} triangles, {size} m × {depth} m × {height} m", + "mesh.importDialog.detectedUncertain": "Axis uncertain: please check. Detected: {axis} up, {n} objects, {tris} triangles", + "mesh.importDialog.placement": "Placement", + "mesh.importDialog.placement.center": "At the project origin (centred in plan, bottom at 0)", + "mesh.importDialog.placement.original": "At original coordinates (national coordinates are moved to the origin if the project has a site reference)", + "mesh.importDialog.reading": "Reading file …", + "mesh.importDialog.import": "Import", "recover.title": "Unsaved work found", "recover.message": "There is an automatic backup of “{name}” from {when} that was never saved.", "recover.unsaved": "untitled project", diff --git a/src/io/meshImport.test.ts b/src/io/meshImport.test.ts new file mode 100644 index 00000000..bf7183cb --- /dev/null +++ b/src/io/meshImport.test.ts @@ -0,0 +1,257 @@ +// Mesh-Import: Rundreise mit dem eigenen OBJ/STL/glTF-Export (`export/exportMesh.ts`) → Rust-Leser → +// Kontext-Meshes; gleiche Dreieckszahl, Lage und Farbe. Sonderfälle (Quads, negative Indizes, kaputte +// Dateien) prüfen die Rust-Tests (`mesh_import_tests.rs`), hier die Fassade. + +import "../engine/fileioWasm.setup"; +import { describe, expect, it } from "vitest"; +import { exportGlb, exportGltf, exportObj, exportStl } from "../export/exportMesh"; +import type { ImportedMesh, Project, Wall } from "../model/types"; +import { + MESH_UNIT_SCALE, + NO_FACES_PREFIX, + decodeMesh, + formatMeshReport, + handleMeshWorkerRequest, + isMeshFile, + meshColorHex, + meshObjectsToImportedMeshes, + meshShift, + readMesh, + type MeshObject, + type MeshWorkerRequest, +} from "./meshImport"; + +function baseProject(): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [{ id: "c", name: "C", color: "#ccc", hatchId: "none", joinPriority: 10 }], + wallTypes: [{ id: "aw", name: "Aussenwand", layers: [{ componentId: "c", thickness: 0.4 }] }], + ceilingTypes: [{ id: "dt", name: "Betondecke", layers: [{ componentId: "c", thickness: 0.2 }] }], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Wände", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + openings: [], + ceilings: [], + stairs: [], + extrudedSolids: [], + rooms: [], + drawings2d: [], + context: [], + } as Project; +} + +/** Eine Wand (0,0)–(5,0), 2,6 m hoch, und ein orangefarbener Kontext-Würfel bei (20, 30). */ +function project(): Project { + const p = baseProject(); + const wall: Wall = { + id: "W1", + type: "wall", + floorId: "eg", + categoryCode: "20", + start: { x: 0, y: 0 }, + end: { x: 5, y: 0 }, + wallTypeId: "aw", + height: 2.6, + }; + p.walls = [wall]; + const cube: ImportedMesh = { + id: "K1", + type: "importedMesh", + name: "Nachbar", + color: "#ff8000", + positions: [20, 30, 0, 24, 30, 0, 24, 36, 0, 20, 36, 0, 20, 30, 9, 24, 30, 9, 24, 36, 9, 20, 36, 9], + indices: [0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7], + }; + p.context = [cube]; + return p; +} + +const enc = new TextEncoder(); + +function bbox(objs: MeshObject[]): { lo: number[]; hi: number[] } { + const lo = [Infinity, Infinity, Infinity]; + const hi = [-Infinity, -Infinity, -Infinity]; + for (const o of objs) { + for (let i = 0; i < o.positions.length; i += 3) { + for (let a = 0; a < 3; a++) { + lo[a] = Math.min(lo[a], o.positions[i + a]); + hi[a] = Math.max(hi[a], o.positions[i + a]); + } + } + } + return { lo, hi }; +} + +const tris = (objs: MeshObject[]) => 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"); + expect(report.format).toBe("gltf"); + expect(report.up).toBe("y"); + expect(objects.length).toBeGreaterThanOrEqual(2); + const nachbar = objects.find((o) => o.name.startsWith("Kontext_")); + expect(nachbar).toBeTruthy(); + expect(nachbar!.indices.length / 3).toBe(12); + // Lage: Würfel (20..24, 30..36, 0..9) liegt wieder dort. + const b = bbox([nachbar!]); + expect(b.lo[0]).toBeCloseTo(20, 4); + expect(b.hi[0]).toBeCloseTo(24, 4); + expect(b.lo[1]).toBeCloseTo(30, 4); + 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"); + // Wand: 0..5 in x, Höhe 2,6. + const wall = objects.find((o) => o.name.startsWith("Wand_"))!; + const bw = bbox([wall]); + expect(bw.lo[0]).toBeCloseTo(0, 4); + expect(bw.hi[0]).toBeCloseTo(5, 4); + expect(bw.hi[2]).toBeCloseTo(2.6, 4); + }); + + 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 n = tris(glb.objects); + expect(tris(gltf.objects)).toBe(n); + expect(tris(obj.objects)).toBe(n); + expect(tris(stl.objects)).toBe(n); + // OBJ trägt den Kopfkommentar (Y oben, sicher); STL wird an der Ausdehnung erkannt. + expect(obj.report.up).toBe("y"); + expect(obj.report.upCertain).toBe(true); + expect(stl.report.up).toBe("y"); + const ref = bbox(glb.objects); + for (const r of [gltf, obj, stl]) { + const b = bbox(r.objects); + for (let a = 0; a < 3; a++) { + expect(b.lo[a]).toBeCloseTo(ref.lo[a], 3); + expect(b.hi[a]).toBeCloseTo(ref.hi[a], 3); + } + } + }); + + 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"); + 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"); + expect(z.report.upAuto).toBe(false); + }); +}); + +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 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 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)); + expect((Math.min(...xs) + Math.max(...xs)) / 2).toBeCloseTo(0, 6); + expect((Math.min(...ys) + Math.max(...ys)) / 2).toBeCloseTo(0, 6); + 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("Bericht als Text", async () => { + const { report } = await readMesh(enc.encode(exportObj(project())), "m.obj"); + const text = formatMeshReport(report, (k, v) => `${k}${v ? JSON.stringify(v) : ""}`); + expect(text).toContain("mesh.import.done"); + expect(text).toContain("mesh.import.up"); + }); +}); + +describe("Mesh-Import: Fehler", () => { + it("kaputte Dateien: Fehlermeldung statt Absturz", async () => { + await expect(readMesh(enc.encode("das ist kein Mesh"), "x.obj")).rejects.toThrow(); + await expect(readMesh(new Uint8Array([1, 2, 3, 4]), "x.glb")).rejects.toThrow(); + await expect(readMesh(new Uint8Array(0), "x.stl")).rejects.toThrow(); + const glb = exportGlb(project()); + await expect(readMesh(glb.slice(0, 100), "x.glb")).rejects.toThrow(); + }); + + it("PLY ohne Flächen meldet die Punktwolke", async () => { + const ply = "ply\nformat ascii 1.0\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nend_header\n0 0 0\n"; + await expect(readMesh(enc.encode(ply), "x.ply")).rejects.toThrow(NO_FACES_PREFIX); + }); + + it("externe .bin: Meldung, dann mit Begleitdatei lesbar", async () => { + const bin = new Uint8Array(new Float32Array([0, 0, 0, 1, 0, 0, 0, 0, 1]).buffer); + const j = JSON.stringify({ + asset: { version: "2.0" }, + scenes: [{ nodes: [0] }], + nodes: [{ mesh: 0 }], + meshes: [{ primitives: [{ attributes: { POSITION: 0 } }] }], + accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: "VEC3" }], + bufferViews: [{ buffer: 0, byteLength: 36 }], + buffers: [{ uri: "d.bin", byteLength: 36 }], + }); + await expect(readMesh(enc.encode(j), "d.gltf")).rejects.toThrow("d.bin"); + const { report } = await readMesh(enc.encode(j), "d.gltf", { files: [{ name: "d.bin", bytes: bin }] }); + expect(report.triangles).toBe(1); + }); + + it("decodeMesh verwirft beschädigte Puffer", () => { + expect(() => decodeMesh({ flat: new Float64Array([9, 0]), strings: [] })).toThrow(); + }); + + it("Worker-Protokoll: Antwort und Fehler", async () => { + const data = exportGlb(project()).slice().buffer; + const req: MeshWorkerRequest = { type: "parse", data, name: "m.glb", unit: "m", up: "auto", maxTriangles: 0, files: [] }; + const ok = await handleMeshWorkerRequest(req); + expect(ok.res.type).toBe("result"); + expect(ok.transfer.length).toBe(1); + const bad = await handleMeshWorkerRequest({ ...req, data: new Uint8Array([1, 2]).buffer }); + expect(bad.res.type).toBe("error"); + }); + + it("Endungen", () => { + expect(isMeshFile("a.GLB")).toBe(true); + expect(isMeshFile("a.ifc")).toBe(false); + }); +}); diff --git a/src/io/meshImport.ts b/src/io/meshImport.ts new file mode 100644 index 00000000..70b87d0c --- /dev/null +++ b/src/io/meshImport.ts @@ -0,0 +1,374 @@ +// 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`). +// +// Laden im Web-Worker (`meshImport.worker.ts`), Rückfall im aufrufenden Thread (Node: CLI, Tests). +// +// Achse und Einheit entscheidet Rust (glTF: Y-up, Meter; OBJ/STL/PLY: Wahl bzw. Erkennung); Ergebnis ist +// Modell-Meter mit Z = Höhe. Platzierung: "center" = Grundriss-Mitte auf den Projekt-Nullpunkt, Unterkante +// auf z = 0; "original" = Koordinaten der Datei (liegen sie in Landeskoordinaten und das Projekt hat einen +// 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"; + +export type MeshUnit = "mm" | "cm" | "m" | "inch" | "foot"; +export type MeshUp = "auto" | "z" | "y"; +export type MeshPlacement = "center" | "original"; +export type MeshFormat = "obj" | "stl" | "gltf" | "ply"; + +/** Meter je Einheit. */ +export const MESH_UNIT_SCALE: Record = { mm: 0.001, cm: 0.01, m: 1, inch: 0.0254, foot: 0.3048 }; +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); +} + +export function isMeshSidecar(name: string): boolean { + const ext = name.toLowerCase().split(".").pop() ?? ""; + return (MESH_SIDECAR_EXTENSIONS as readonly string[]).includes(ext); +} + +export interface MeshReadOptions { + unit?: MeshUnit; + up?: MeshUp; + /** Dreiecksgrenze (0/fehlt = Voreinstellung 6 Mio.). */ + maxTriangles?: number; + /** Begleitdateien (`.mtl`, `.bin`). */ + 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. */ + up: "z" | "y"; + /** Achse wurde erkannt (nicht vorgegeben). */ + upAuto: boolean; + /** Erkennung belastbar (Kopfkommentar oder eindeutige Ausdehnung). */ + upCertain: boolean; + unitScale: number; + triangles: number; + degenerate: number; + badFaces: number; + truncated: boolean; + warnings: string[]; + objects: number; +} + +/** Rohergebnis aus Rust: Zahlenpuffer + Zeichenketten. */ +export interface MeshFlat { + flat: Float64Array; + strings: string[]; +} + +/** Worker-Protokoll (`meshImport.worker.ts`). */ +export type MeshWorkerRequest = { + type: "parse"; + data: ArrayBuffer; + name: string; + unit: MeshUnit; + up: MeshUp; + maxTriangles: number; + files: { name: string; data: ArrayBuffer }[]; +}; +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 }; +} + +/** Liest Mesh-Bytes mit dem geladenen Format-Modul (Worker oder aufrufender Thread). */ +export async function importMeshFlat( + bytes: Uint8Array, + name: string, + opts: Required> & { files: { name: string; bytes: Uint8Array }[] }, +): Promise { + const m = await loadFileio(); + const sizes = opts.files.map((f) => f.bytes.length); + const blob = new Uint8Array(sizes.reduce((a, b) => a + b, 0)); + let o = 0; + for (const f of opts.files) { + blob.set(f.bytes, o); + o += f.bytes.length; + } + const r = m.import_mesh( + bytes, + name, + MESH_UNIT_SCALE[opts.unit], + opts.up === "z" ? 1 : opts.up === "y" ? 2 : 0, + opts.maxTriangles, + opts.files.map((f) => f.name), + new Float64Array(sizes), + blob, + ); + try { + return { flat: r.flat(), strings: r.strings() }; + } finally { + r.free(); + } +} + +function resolve(o: MeshReadOptions | undefined) { + return { + unit: o?.unit ?? "m", + up: o?.up ?? "auto", + maxTriangles: o?.maxTriangles && o.maxTriangles > 0 ? o.maxTriangles : 0, + files: o?.files ?? [], + }; +} + +/** Beantwortet eine Worker-Anfrage; liefert Antwort und zu übertragende Puffer. */ +export async function handleMeshWorkerRequest(req: MeshWorkerRequest): Promise<{ res: MeshWorkerResponse; transfer: Transferable[] }> { + try { + if (req?.type !== "parse" || !(req.data instanceof ArrayBuffer)) throw new Error("ungültige Anfrage"); + const flat = await importMeshFlat(new Uint8Array(req.data), req.name, { + unit: req.unit, + up: req.up, + maxTriangles: req.maxTriangles, + files: (req.files ?? []).map((f) => ({ name: f.name, bytes: new Uint8Array(f.data) })), + }); + return { res: { type: "result", flat }, transfer: [flat.flat.buffer] }; + } catch (err) { + return { res: { type: "error", message: err instanceof Error ? err.message : String(err) }, transfer: [] }; + } +} + +/** Liest im Web-Worker; `null`, wenn kein Worker verfügbar ist oder er nicht startet. */ +function readInWorker(bytes: Uint8Array, name: string, o: ReturnType): Promise { + if (typeof Worker === "undefined") return Promise.resolve(null); + return new Promise((resolveP, reject) => { + let worker: Worker; + try { + worker = new Worker(new URL("./meshImport.worker.ts", import.meta.url), { type: "module" }); + } catch { + resolveP(null); + return; + } + worker.onmessage = (e: MessageEvent) => { + worker.terminate(); + if (e.data?.type === "result") resolveP(e.data.flat); + else reject(new Error(e.data?.type === "error" ? e.data.message : "Unerwartete Worker-Antwort")); + }; + worker.onerror = () => { + worker.terminate(); + resolveP(null); + }; + // Kopien übertragen: der Aufrufer behält seine Bytes. + const data = bytes.slice().buffer; + const files = o.files.map((f) => ({ name: f.name, data: f.bytes.slice().buffer })); + const req: MeshWorkerRequest = { type: "parse", data, name, unit: o.unit, up: o.up, maxTriangles: o.maxTriangles, files }; + worker.postMessage(req, [data, ...files.map((f) => f.data)]); + }); +} + +/** Rohergebnis lesen (im Worker, sonst direkt). */ +export async function readMeshFlat(bytes: Uint8Array, name: string, opts?: MeshReadOptions): Promise { + const o = resolve(opts); + return (await readInWorker(bytes, name, o)) ?? (await importMeshFlat(bytes, name, o)); +} + +/** Liest eine Mesh-Datei. Wirft mit der Meldung aus Rust bei unlesbaren Dateien. */ +export async function readMesh( + bytes: Uint8Array, + name: string, + opts?: MeshReadOptions, +): Promise<{ objects: MeshObject[]; report: MeshImportReport }> { + return decodeMesh(await readMeshFlat(bytes, name, opts)); +} + +// ── Abbildung auf Kontext-Meshes ──────────────────────────────────────────── + +export interface MeshToContextOptions { + placement?: MeshPlacement; + /** LV95-Ursprung des Projekts (`projectGeoOrigin`), sonst null (nur bei "original"). */ + geoOrigin?: { e: number; n: number } | null; + /** "object" = je Objekt, "merge" = je Gruppe + Farbe, "auto" (Standard) nach `MAX_SINGLE`. */ + group?: "object" | "merge" | "auto"; +} + +/** Verschiebung (x, y, z) je nach Platzierung. */ +export function meshShift(objects: readonly MeshObject[], opts: MeshToContextOptions = {}): [number, number, number] { + let minX = Infinity; + let maxX = -Infinity; + let minY = Infinity; + let maxY = -Infinity; + let minZ = Infinity; + for (const o of objects) { + const p = o.positions; + for (let i = 0; i + 2 < p.length; i += 3) { + if (p[i] < minX) minX = p[i]; + if (p[i] > maxX) maxX = p[i]; + if (p[i + 1] < minY) minY = p[i + 1]; + if (p[i + 1] > maxY) maxY = p[i + 1]; + if (p[i + 2] < minZ) minZ = p[i + 2]; + } + } + if (!Number.isFinite(minX)) return [0, 0, 0]; + const cx = (minX + maxX) / 2; + const cy = (minY + maxY) / 2; + if ((opts.placement ?? "center") === "center") return [-cx, -cy, -minZ]; + const origin = opts.geoOrigin; + if (origin && Math.hypot(cx - origin.e, cy - origin.n) < Math.hypot(cx, cy)) return [-origin.e, -origin.n, 0]; + return [0, 0, 0]; +} + +/** sRGB 0..1 → `#rrggbb` (Alpha entfällt). */ +export function meshColorHex(c: readonly number[] | null | undefined): string | undefined { + if (!c || c.length < 3 || !c.slice(0, 3).every((v) => Number.isFinite(v))) return undefined; + return rgbToHex({ r: c[0] * 255, g: c[1] * 255, b: c[2] * 255 }); +} + +let counter = 0; + +/** Objekte → Kontext-Meshes (Kategorie „Situation" wie IFC/STEP; `layer` = Gruppe, sonst Dateiname). */ +export function meshObjectsToImportedMeshes(objects: readonly MeshObject[], fileName: string, opts: MeshToContextOptions = {}): ImportedMesh[] { + const base = fileName.replace(/\.[^.]+$/, "") || "Mesh"; + const [dx, dy, dz] = meshShift(objects, opts); + const stamp = Date.now().toString(36); + const group = opts.group ?? "auto"; + const merge = group === "merge" || (group === "auto" && objects.length > MAX_SINGLE); + + const toArrays = (parts: readonly MeshObject[]): { positions: number[]; indices: number[] } => { + const positions: number[] = []; + const indices: number[] = []; + for (const p of parts) { + const off = positions.length / 3; + for (let i = 0; i + 2 < p.positions.length; i += 3) { + positions.push(p.positions[i] + dx, p.positions[i + 1] + dy, p.positions[i + 2] + dz); + } + for (let i = 0; i < p.indices.length; i++) indices.push(p.indices[i] + off); + } + return { positions, indices }; + }; + + if (!merge) { + return objects.map((o, i) => { + const color = meshColorHex(o.color); + return { + id: `imported-mesh-${stamp}-${counter++}`, + type: "importedMesh" as const, + name: o.name || `${base} ${i + 1}`, + layer: o.group || base, + categoryCode: GENERIC_IMPORT_CATEGORY.code, + ...(color ? { color } : {}), + ...toArrays([o]), + }; + }); + } + const groups = new Map(); + for (const o of objects) { + const key = `${o.group}\u0000${meshColorHex(o.color) ?? ""}`; + const g = groups.get(key); + if (g) g.push(o); + else groups.set(key, [o]); + } + return [...groups.values()].map((parts) => { + const color = meshColorHex(parts[0].color); + const g = parts[0].group; + return { + id: `imported-mesh-${stamp}-${counter++}`, + type: "importedMesh" as const, + name: `${base}${g ? `: ${g}` : ""} (${parts.length})`, + layer: g || base, + categoryCode: GENERIC_IMPORT_CATEGORY.code, + ...(color ? { color } : {}), + ...toArrays(parts), + }; + }); +} + +/** Datei-Bytes → Kontext-Meshes + Bericht. */ +export async function meshBytesToImportedMeshes( + bytes: Uint8Array, + fileName: string, + read?: MeshReadOptions, + place?: MeshToContextOptions, +): Promise<{ meshes: ImportedMesh[]; report: MeshImportReport }> { + const { objects, report } = await readMesh(bytes, fileName, read); + return { meshes: meshObjectsToImportedMeshes(objects, fileName, place), report }; +} + +/** Bericht als kurzer Text; `tr` übersetzt (Kern kennt kein i18n, die Hülle reicht `t` herein). */ +export function formatMeshReport( + r: MeshImportReport, + tr: ( + key: "mesh.import.done" | "mesh.import.up" | "mesh.import.upUncertain" | "mesh.import.dropped" | "mesh.import.truncated", + vars?: Record, + ) => string, +): string { + const parts = [tr("mesh.import.done", { n: r.objects, tris: r.triangles, format: r.format.toUpperCase() })]; + if (r.upAuto) parts.push(tr(r.upCertain ? "mesh.import.up" : "mesh.import.upUncertain", { axis: r.up.toUpperCase() })); + const dropped = r.degenerate + r.badFaces; + if (dropped) parts.push(tr("mesh.import.dropped", { n: dropped })); + if (r.truncated) parts.push(tr("mesh.import.truncated")); + return parts.join(" · "); +} diff --git a/src/io/meshImport.worker.ts b/src/io/meshImport.worker.ts new file mode 100644 index 00000000..0b2f7e83 --- /dev/null +++ b/src/io/meshImport.worker.ts @@ -0,0 +1,15 @@ +// Web-Worker für den Mesh-Import: 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. `meshImport.ts::readInWorker`). +// +// → { type: "parse", data, name, unit, up, maxTriangles, files } +// ← { type: "result", flat: { flat, strings } } | { type: "error", message } +// +// Der Zahlenpuffer wird übertragen, nicht kopiert. + +import { handleMeshWorkerRequest, type MeshWorkerRequest } from "./meshImport"; + +self.onmessage = async (e: MessageEvent) => { + const { res, transfer } = await handleMeshWorkerRequest(e.data); + (self as unknown as Worker).postMessage(res, transfer); +}; diff --git a/src/native/appMenu.ts b/src/native/appMenu.ts index ebdadef1..060dbcd6 100644 --- a/src/native/appMenu.ts +++ b/src/native/appMenu.ts @@ -38,6 +38,8 @@ export interface NativeAppMenuHandlers { onImportIfc: () => void; /** Punktwolke importieren ([27]); optional für ältere Aufrufer. */ onImportPointCloud?: () => void; + /** 3D-Modell importieren (OBJ/STL/glTF/GLB/PLY). */ + onImportMesh?: () => void; onClashCheck: () => void; onKennzahlen: () => void; @@ -186,6 +188,10 @@ export function useNativeAppMenu( text: t("menu.native.importPointCloud"), action: () => handlersRef.current.onImportPointCloud?.(), }), + await MenuItem.new({ + text: t("menu.native.importMesh"), + action: () => handlersRef.current.onImportMesh?.(), + }), await Submenu.new({ text: t("menu.native.export"), items: [ diff --git a/src/state/meshImportStore.ts b/src/state/meshImportStore.ts new file mode 100644 index 00000000..432d2747 --- /dev/null +++ b/src/state/meshImportStore.ts @@ -0,0 +1,66 @@ +// Import-Anfrage für 3D-Modelle (OBJ/STL/glTF/GLB/PLY): Menü, Drag & Drop → Dialog (`ui/MeshImportDialog.tsx`). +// Kleiner externer Store (Muster `pointCloudStore.ts`): UI-Zustand, kein Teil des Projekts. Die Anfrage +// besteht aus der Hauptdatei und den mitgegebenen Begleitdateien (`.mtl`, `.bin`). + +import { useSyncExternalStore } from "react"; +import { isMeshFile, isMeshSidecar } from "../io/meshImport"; + +export interface MeshImportRequest { + file: File; + sidecars: File[]; +} + +let pending: MeshImportRequest | null = null; +let fileInput: HTMLInputElement | null = null; +const listeners = new Set<() => void>(); + +function emit(): void { + for (const l of listeners) l(); +} + +/** Teilt eine Dateiliste in Hauptdatei (erste Mesh-Datei) und Begleitdateien; `null` ohne Mesh-Datei. */ +export function splitMeshFiles(files: readonly File[]): MeshImportRequest | null { + const file = files.find((f) => isMeshFile(f.name)); + if (!file) return null; + return { file, sidecars: files.filter((f) => f !== file && isMeshSidecar(f.name)) }; +} + +/** Öffnet den Import-Dialog. */ +export function requestMeshImport(file: File, sidecars: File[] = []): void { + pending = { file, sidecars }; + emit(); +} + +/** Schliesst den Import-Dialog. */ +export function closeMeshImport(): void { + if (pending === null) return; + pending = null; + emit(); +} + +export function useMeshImportRequest(): MeshImportRequest | null { + return useSyncExternalStore( + (l) => { + listeners.add(l); + return () => listeners.delete(l); + }, + () => pending, + () => pending, + ); +} + +/** Der Dialog-Host meldet sein verstecktes Datei-Feld an (oder ab mit `null`). */ +export function registerMeshFileInput(el: HTMLInputElement | null): void { + fileInput = el; +} + +/** Datei-Auswahl öffnen (Menü „3D-Modell importieren …"). Synchron im Klick, sonst blockt WebKit. */ +export function openMeshFileDialog(): void { + fileInput?.click(); +} + +/** Nur für Tests: Zustand zurücksetzen. */ +export function resetMeshImportStoreForTests(): void { + pending = null; + fileInput = null; +} diff --git a/src/state/useImportHandling.ts b/src/state/useImportHandling.ts index 37c4416e..44e30114 100644 --- a/src/state/useImportHandling.ts +++ b/src/state/useImportHandling.ts @@ -122,6 +122,8 @@ export function useImageImportHandling(opts: { export function useFileDropImport( setDropActive: (active: boolean) => void, openImportForFile: (file: File) => void, + /** Mehrere abgelegte Dateien (z. B. .gltf + .bin): `true`, wenn der Aufrufer sie übernommen hat. */ + openMany?: (files: File[]) => boolean, ): { onAppDragEnter: (e: DragEvent) => void; onAppDragOver: (e: DragEvent) => void; @@ -152,7 +154,9 @@ export function useFileDropImport( e.preventDefault(); dragDepthRef.current = 0; setDropActive(false); - const f = e.dataTransfer.files?.[0]; + const all = Array.from(e.dataTransfer.files ?? []); + if (all.length > 1 && openMany?.(all)) return; + const f = all[0]; if (f) openImportForFile(f); }; return { onAppDragEnter, onAppDragOver, onAppDragLeave, onAppDrop }; diff --git a/src/ui/AppMenuBar.tsx b/src/ui/AppMenuBar.tsx index 66723449..16510909 100644 --- a/src/ui/AppMenuBar.tsx +++ b/src/ui/AppMenuBar.tsx @@ -21,6 +21,7 @@ export interface AppMenuBarProps { onImport: () => void; /** Datei: Punktwolke importieren ([27]). */ onImportPointCloud?: () => void; + onImportMesh?: () => void; /** Bearbeiten: Undo/Redo (Store) + Löschen der aktuellen Auswahl. */ onUndo: () => void; @@ -56,6 +57,7 @@ export function AppMenuBar({ onSaveProject, onImport, onImportPointCloud, + onImportMesh, onUndo, onRedo, canUndo, @@ -83,6 +85,7 @@ export function AppMenuBar({ { divider: true }, { label: t("file.import"), onSelect: onImport }, ...(onImportPointCloud ? [{ label: t("menu.native.importPointCloud"), onSelect: onImportPointCloud }] : []), + ...(onImportMesh ? [{ label: t("menu.native.importMesh"), onSelect: onImportMesh }] : []), ]; const editItems: DropdownItem[] = [ diff --git a/src/ui/MeshImportDialog.tsx b/src/ui/MeshImportDialog.tsx new file mode 100644 index 00000000..fe3429df --- /dev/null +++ b/src/ui/MeshImportDialog.tsx @@ -0,0 +1,238 @@ +// 3D-Modell-Import (OBJ/STL/glTF/GLB/PLY → Kontext-Meshes): verstecktes Datei-Feld + Dialog mit Einheit, +// 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). +// +// Muster: PointCloudImportDialog (abgedunkeltes Overlay, Esc/Hintergrund schliessen). + +import { useEffect, useMemo, useRef, useState } from "react"; +import { t } from "../i18n"; +import { Dropdown } from "./Dropdown"; +import { + MESH_EXTENSIONS, + MESH_SIDECAR_EXTENSIONS, + MESH_UNITS, + MISSING_EXTERNAL_PREFIX, + NO_FACES_PREFIX, + meshObjectsToImportedMeshes, + readMesh, +} from "../io/meshImport"; +import type { MeshImportReport, MeshObject, MeshPlacement, 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; + 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); + return m ? m[1] : message; +} + +async function bytesOf(f: File): Promise { + return new Uint8Array(await f.arrayBuffer()); +} + +function MeshImportDialog({ req, project, onImport, notify }: { req: MeshImportRequest } & MeshImportHostProps) { + const { file, sidecars } = req; + const isGltf = /\.(gltf|glb)$/i.test(file.name); + const [unit, setUnit] = useState("m"); + const [up, setUp] = useState("auto"); + const [placement, setPlacement] = useState("center"); + const [busy, setBusy] = useState(true); + const [error, setError] = useState(null); + const [result, setResult] = useState<{ objects: MeshObject[]; report: MeshImportReport } | null>(null); + const seq = useRef(0); + // Dateiinhalt einmal laden, nicht bei jeder Änderung. + const cache = useRef<{ main: Uint8Array; files: { name: string; bytes: Uint8Array }[] } | null>(null); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") closeMeshImport(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, []); + + useEffect(() => { + const id = ++seq.current; + setBusy(true); + setError(null); + void (async () => { + try { + cache.current ??= { + main: await bytesOf(file), + files: await Promise.all(sidecars.map(async (f) => ({ name: f.name, bytes: await bytesOf(f) }))), + }; + const r = await readMesh(cache.current.main, file.name, { unit, up, files: cache.current.files }); + if (id !== seq.current) return; + setResult(r); + } catch (e) { + if (id !== seq.current) return; + const msg = e instanceof Error ? e.message : String(e); + if (msg.startsWith(NO_FACES_PREFIX)) { + // PLY ohne Flächen = Punktwolke: Dialog wechseln. + closeMeshImport(); + notify(t("mesh.import.noFaces"), "info"); + requestPointCloudImport(file); + return; + } + setResult(null); + setError( + msg.startsWith(MISSING_EXTERNAL_PREFIX) + ? t("mesh.import.missingExternal", { list: missingList(msg) }) + : `${t("mesh.import.failed")}: ${msg}`, + ); + } finally { + if (id === seq.current) setBusy(false); + } + })(); + }, [file, sidecars, unit, up]); + + const dims = useMemo(() => (result ? extent(result.objects) : null), [result]); + 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); + }; + + return ( +
closeMeshImport()}> +
e.stopPropagation()}> +
+ {t("mesh.import.title")} + +
+ +
+
+ + {file.name} · {(file.size / 1e6).toFixed(1)} MB + +
+ {sidecars.length > 0 &&
{t("mesh.importDialog.files", { list: sidecars.map((f) => f.name).join(", ") })}
} + +
+
{t("mesh.importDialog.unit")}
+ setUnit(v as MeshUnit)} + title={t("mesh.importDialog.unit")} + options={MESH_UNITS.map((u) => ({ value: u, label: t(`mesh.importDialog.unit.${u}`), disabled: isGltf && u !== "m" }))} + /> + {isGltf &&
{t("mesh.importDialog.unitFixed")}
} +
+ +
+
{t("mesh.importDialog.up")}
+ {(["auto", "z", "y"] as const).map((u) => ( + + ))} + {isGltf &&
{t("mesh.importDialog.upFixed")}
} +
+ +
+
{t("mesh.importDialog.placement")}
+ {(["center", "original"] as const).map((p) => ( + + ))} +
+ + {busy &&
{t("mesh.importDialog.reading")}
} + {error &&
{error}
} + {r && dims && !busy && ( +
+
+ {r.upAuto && !r.upCertain + ? t("mesh.importDialog.detectedUncertain", { axis: r.up.toUpperCase(), n: r.objects, tris: r.triangles }) + : t("mesh.importDialog.detected", { + axis: r.up.toUpperCase(), + n: r.objects, + tris: r.triangles, + size: fmt(dims[0]), + depth: fmt(dims[1]), + height: fmt(dims[2]), + })} +
+ {r.truncated &&
{t("mesh.import.truncated")}
} + {r.warnings.map((w) => ( +
+ {w} +
+ ))} +
+ )} +
+ +
+ + +
+
+
+ ); +} + +/** Verstecktes Datei-Feld (mehrere Dateien: Modell + `.mtl`/`.bin`) + Dialog; einmal in der App einhängen. */ +export function MeshImportHost(props: MeshImportHostProps) { + const req = useMeshImportRequest(); + return ( + <> + "." + e).join(",")} + style={{ display: "none" }} + data-testid="mesh-input" + onChange={(e) => { + const files = Array.from(e.target.files ?? []); + e.target.value = ""; + const r = splitMeshFiles(files); + if (r) requestMeshImport(r.file, r.sidecars); + }} + /> + {req && } + + ); +}