Merge [B4][B3] IFC-Import zu echten Bauteilen (Waende, Oeffnungen, Decken, Stuetzen, Raeume, Geschosse; Erkennung in Rust ifc_semantic.rs); ImportedMesh mit color/ifcGlobalId
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
14 files changed
+2563
-161
No files matched your search
+45
-2
@@ -55,6 +55,8 @@ import { Toast } from "./ui/Toast";
|
||||
import { isTauriRuntime, PROJECT_TEMPLATE_EXT } from "./native/projectFile";
|
||||
import { stepTextToImportedMeshes } from "./io/stepImport";
|
||||
import { formatIfcReport, ifcBytesToImportedMeshes } from "./io/ifcImport";
|
||||
import { formatIfcElementsSummary, ifcElementsToProject, readIfcElements } from "./io/ifcElements";
|
||||
import { IfcImportDialog, type IfcImportMode } from "./ui/IfcImportDialog";
|
||||
import { projectGeoOrigin } from "./model/geoRebase";
|
||||
import { applyClashMarkers, runClashCheck } from "./analysis/clash";
|
||||
import { checkForUpdate } from "./update/checkForUpdate";
|
||||
@@ -1698,8 +1700,37 @@ export default function App() {
|
||||
setRoomStamp,
|
||||
} = useProjectActions(setProject, notify, planViewRef);
|
||||
|
||||
// IFC-Import ([B3]): Bauteile als Kontext-Meshes (Format-Modul, `io/ifcImport.ts`), Bericht als Toast.
|
||||
const importIfcFile = (f: File) => {
|
||||
// IFC-Import: erst die Wahl Mesh/Bauteile (`IfcImportDialog`), dann [B3] Kontext-Meshes
|
||||
// (`io/ifcImport.ts`) oder [B4] echte Bauteile (`io/ifcElements.ts`, übernommen über setProject).
|
||||
const [pendingIfc, setPendingIfc] = useState<File | null>(null);
|
||||
const importIfcFile = (f: File) => setPendingIfc(f);
|
||||
const runIfcImport = (f: File, mode: IfcImportMode) => {
|
||||
if (mode === "elements") {
|
||||
void f
|
||||
.arrayBuffer()
|
||||
.then((buf) => readIfcElements(new Uint8Array(buf)))
|
||||
.then(({ products, report, elements }) => {
|
||||
let summary: ReturnType<typeof ifcElementsToProject>["summary"] | null = null;
|
||||
let bounds: { x: number; y: number }[] = [];
|
||||
setProject((p) => {
|
||||
const r = ifcElementsToProject(p, products, elements, { fileName: f.name, geoOrigin: projectGeoOrigin(p) });
|
||||
summary = r.summary;
|
||||
const added = new Set(p.walls.map((w) => w.id));
|
||||
bounds = r.project.walls.filter((w) => !added.has(w.id)).flatMap((w) => [w.start, w.end]);
|
||||
return r.project;
|
||||
});
|
||||
if (bounds.length) planViewRef.current?.fitBounds(bounds);
|
||||
if (summary) {
|
||||
const s: ReturnType<typeof ifcElementsToProject>["summary"] = summary;
|
||||
const empty = s.walls + s.ceilings + s.columns + s.rooms + s.meshes === 0;
|
||||
notify(formatIfcElementsSummary(s, report, t), empty || report.truncated ? "warning" : "info");
|
||||
}
|
||||
})
|
||||
.catch((err) =>
|
||||
notify(`${t("ifc.import.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
void f
|
||||
.arrayBuffer()
|
||||
.then((buf) => ifcBytesToImportedMeshes(new Uint8Array(buf), f.name, { geoOrigin: projectGeoOrigin(project) }))
|
||||
@@ -3998,6 +4029,18 @@ export default function App() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{pendingIfc && (
|
||||
<IfcImportDialog
|
||||
fileName={pendingIfc.name}
|
||||
onCancel={() => setPendingIfc(null)}
|
||||
onImport={(mode) => {
|
||||
const f = pendingIfc;
|
||||
setPendingIfc(null);
|
||||
runIfcImport(f, mode);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{pendingDiscard && (
|
||||
<UnsavedChangesDialog
|
||||
onCancel={() => setPendingDiscard(null)}
|
||||
|
||||
+20
-4
@@ -9,8 +9,9 @@
|
||||
// dossier-cli <projekt.obp> section <Name> [--out schnitt.svg] (braucht render3d-WASM)
|
||||
// dossier-cli <projekt.obp> elevation <Name> [--out ansicht.svg]
|
||||
// dossier-cli <projekt.obp> dxf [--binary]|dwg|ifc|step|obj|stl|schedule|kennzahlen|sun [--level EG] [--out datei]
|
||||
// dossier-cli <projekt.obp> import-ifc <datei.ifc> [--out neu.obp] [--group product|class]
|
||||
// IFC als Kontext-Meshes ([B3]); Bericht als JSON auf stdout
|
||||
// dossier-cli <projekt.obp> import-ifc <datei.ifc> [--out neu.obp] [--group product|class] [--elements]
|
||||
// IFC als Kontext-Meshes ([B3]), mit --elements als echte
|
||||
// Bauteile ([B4]); Bericht als JSON auf stdout
|
||||
// dossier-cli <projekt.obp> model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png)
|
||||
// dossier-cli <projekt.obp> mcp MCP-Server (stdio): project_info, query, render_svg, apply_ops, validate
|
||||
// dossier-cli <projekt.obp> bench [--runs 10] Zeitprofil der Ableitungen (ms je Aufruf)
|
||||
@@ -26,6 +27,8 @@ import {
|
||||
buildPlanDxfBinary,
|
||||
loadFileio,
|
||||
readIfc,
|
||||
readIfcElements,
|
||||
ifcElementsToProject,
|
||||
ifcToImportedMeshes,
|
||||
projectGeoOrigin,
|
||||
ensureContextCategories,
|
||||
@@ -271,9 +274,22 @@ export async function run(argv: string[]): Promise<number> {
|
||||
} catch (e) {
|
||||
fail(`Datei nicht lesbar: ${src} (${e instanceof Error ? e.message : String(e)})`);
|
||||
}
|
||||
const { products, report } = await readIfc(bytes);
|
||||
const group = args.flags.get("group");
|
||||
const meshes = ifcToImportedMeshes(products, src.split(/[\\/]/).pop() ?? src, {
|
||||
const fileName = src.split(/[\\/]/).pop() ?? src;
|
||||
if (args.flags.has("elements")) {
|
||||
const { products, report, elements } = await readIfcElements(bytes);
|
||||
const r = ifcElementsToProject(project, products, elements, {
|
||||
fileName,
|
||||
geoOrigin: projectGeoOrigin(project),
|
||||
group: group === "product" || group === "class" ? group : "auto",
|
||||
});
|
||||
process.stdout.write(JSON.stringify({ ...report, products: undefined, elements: r.summary, kept: elements.kept }, null, 2) + "\n");
|
||||
const target = args.flags.get("out");
|
||||
if (target) out(args, serializeProject(applyOps(project, diffToOps(project, r.project))), target);
|
||||
return 0;
|
||||
}
|
||||
const { products, report } = await readIfc(bytes);
|
||||
const meshes = ifcToImportedMeshes(products, fileName, {
|
||||
geoOrigin: projectGeoOrigin(project),
|
||||
group: group === "product" || group === "class" ? group : "auto",
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ 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 { projectGeoOrigin } from "../model/geoRebase";
|
||||
export { ensureContextCategories } from "../model/contextCategories";
|
||||
export { projectToWorldCoords } from "../model/geoRebase";
|
||||
|
||||
@@ -1764,6 +1764,14 @@ export const de = {
|
||||
"ifc.import.voids": "{n} Öffnungen nicht abgezogen",
|
||||
"ifc.import.booleans": "{n} Boolesche Körper vereinfacht (nur erster Operand)",
|
||||
"ifc.import.truncated": "abgebrochen: zu viele Dreiecke",
|
||||
"ifc.import.elements": "{schema} importiert: {walls} Wände, {openings} Türen/Fenster, {ceilings} Decken, {columns} Stützen, {rooms} Räume, {floors} neue Geschosse; {meshes} Bauteile als Kontext-Meshes",
|
||||
"ifc.import.kept": "{n} Wände/Decken/Stützen/Räume nicht sicher abbildbar, als Mesh übernommen",
|
||||
"ifc.importDialog.title": "IFC importieren",
|
||||
"ifc.importDialog.asMesh": "Als Kontext-Meshes (Standard)",
|
||||
"ifc.importDialog.asMeshHint": "Jedes Bauteil als nicht bearbeitbares Mesh der Kontext-Schicht, wie in der Datei.",
|
||||
"ifc.importDialog.asElements": "Als Bauteile",
|
||||
"ifc.importDialog.asElementsHint": "Wände, Decken, Stützen, Türen/Fenster, Räume und Geschosse werden bearbeitbare Dossier-Bauteile; was nicht sicher abbildbar ist, bleibt Mesh.",
|
||||
"ifc.importDialog.import": "Importieren",
|
||||
"recover.title": "Ungesicherte Arbeit gefunden",
|
||||
"recover.message": "Von „{name}“ gibt es eine automatische Sicherung vom {when}, die nicht gespeichert wurde.",
|
||||
"recover.unsaved": "unbenanntes Projekt",
|
||||
|
||||
@@ -1725,6 +1725,14 @@ export const en: Record<TranslationKey, string> = {
|
||||
"ifc.import.voids": "{n} openings not subtracted",
|
||||
"ifc.import.booleans": "{n} boolean solids simplified (first operand only)",
|
||||
"ifc.import.truncated": "aborted: too many triangles",
|
||||
"ifc.import.elements": "{schema} imported: {walls} walls, {openings} doors/windows, {ceilings} slabs, {columns} columns, {rooms} rooms, {floors} new storeys; {meshes} elements as context meshes",
|
||||
"ifc.import.kept": "{n} walls/slabs/columns/rooms not safely mappable, kept as mesh",
|
||||
"ifc.importDialog.title": "Import IFC",
|
||||
"ifc.importDialog.asMesh": "As context meshes (default)",
|
||||
"ifc.importDialog.asMeshHint": "Every element as a non-editable mesh on the context layer, as in the file.",
|
||||
"ifc.importDialog.asElements": "As building elements",
|
||||
"ifc.importDialog.asElementsHint": "Walls, slabs, columns, doors/windows, rooms and storeys become editable Dossier elements; anything not safely mappable stays a mesh.",
|
||||
"ifc.importDialog.import": "Import",
|
||||
"recover.title": "Unsaved work found",
|
||||
"recover.message": "There is an automatic backup of “{name}” from {when} that was never saved.",
|
||||
"recover.unsaved": "untitled project",
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
// IFC-Import zu echten Bauteilen ([B4]): Rundreise eigener Export → Import als Bauteile → gleiche
|
||||
// Wände/Öffnungen/Decken/Räume (Lage, Dicke, Höhe, Typ) wie das Original (Demo-Haus); dazu Farbe und
|
||||
// GlobalId am Kontext-Mesh ([B3]-Nachtrag) und die Speichern/Laden-Rundreise.
|
||||
|
||||
import "../engine/fileioWasm.setup";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { applyOps, diffToOps, validateProject } from "../core/ops";
|
||||
import { exportIfcSpf } from "../export/exportIfc";
|
||||
import { emptyProject, sampleProject } from "../model/sampleProject";
|
||||
import type { Column, Opening, Project, Vec2, Wall } from "../model/types";
|
||||
import { wallTypeThickness } from "../model/types";
|
||||
import { formatIfcElementsSummary, ifcElementsToProject, readIfcElements } from "./ifcElements";
|
||||
import { ifcToImportedMeshes, readIfc, type IfcProduct } from "./ifcImport";
|
||||
import { parseProjectFile, serializeProject } from "./projectFormat";
|
||||
|
||||
const bytesOf = (s: string) => new TextEncoder().encode(s);
|
||||
const near = (a: Vec2, b: Vec2, tol = 1e-6) => Math.hypot(a.x - b.x, a.y - b.y) <= tol;
|
||||
const symmetric = (p: Project, wallTypeId: string) => {
|
||||
const l = p.wallTypes.find((t) => t.id === wallTypeId)!.layers;
|
||||
return l.every((x, i) => x.componentId === l[l.length - 1 - i].componentId && Math.abs(x.thickness - l[l.length - 1 - i].thickness) < 1e-9);
|
||||
};
|
||||
|
||||
async function importInto(base: Project, src: Project) {
|
||||
const { products, report, elements } = await readIfcElements(bytesOf(exportIfcSpf(src)));
|
||||
const r = ifcElementsToProject(base, products, elements, { fileName: "haus.ifc" });
|
||||
return { ...r, report, elements, products };
|
||||
}
|
||||
|
||||
describe("IFC-Import als Bauteile: Rundreise Demo-Haus", () => {
|
||||
it("gleiche Wände (Achse, Typ, Höhe, Geschoss), Öffnungen, Decke, Raum; Rest als Mesh", async () => {
|
||||
const { project: p, summary, report } = await importInto(emptyProject, sampleProject);
|
||||
expect(report.parseErrors).toBe(0);
|
||||
expect(summary).toMatchObject({ walls: 9, openings: 3, ceilings: 1, columns: 0, rooms: 1, floors: 0, wallTypes: 0, ceilingTypes: 0, components: 0, kept: 0 });
|
||||
// Dach und Treppe bleiben Kontext-Mesh.
|
||||
expect((p.context ?? []).map((c) => (c as { layer?: string }).layer).sort()).toEqual(["IfcRoof", "IfcStair"]);
|
||||
expect(validateProject(p)).toEqual([]);
|
||||
|
||||
const byOrig = new Map<string, Wall>();
|
||||
for (const w of sampleProject.walls) {
|
||||
const sym = symmetric(sampleProject, w.wallTypeId);
|
||||
const got = p.walls.find(
|
||||
(g) =>
|
||||
g.floorId === w.floorId &&
|
||||
((near(g.start, w.start) && near(g.end, w.end)) || (sym && near(g.start, w.end) && near(g.end, w.start))),
|
||||
);
|
||||
expect(got, `${w.id} ${JSON.stringify(p.walls.map((x) => [x.start, x.end]))}`).toBeDefined();
|
||||
expect(got!.wallTypeId).toBe(w.wallTypeId);
|
||||
expect(got!.height).toBeCloseTo(w.height, 9);
|
||||
expect(got!.bottom).toBeUndefined();
|
||||
expect(got!.categoryCode).toBe("20");
|
||||
byOrig.set(w.id, got!);
|
||||
}
|
||||
for (const o of sampleProject.openings ?? []) {
|
||||
const host = byOrig.get(o.hostWallId)!;
|
||||
const got = (p.openings ?? []).find((g) => g.hostWallId === host.id && Math.abs(g.width - o.width) < 1e-6 && g.kind === o.kind) as Opening;
|
||||
expect(got, o.id).toBeDefined();
|
||||
const orig = sampleProject.walls.find((w) => w.id === o.hostWallId)!;
|
||||
const len = Math.hypot(orig.end.x - orig.start.x, orig.end.y - orig.start.y);
|
||||
const pos = near(host.start, orig.start) ? o.position : len - o.position - o.width;
|
||||
expect(got.position).toBeCloseTo(pos, 6);
|
||||
expect(got.height).toBeCloseTo(o.height, 6);
|
||||
expect(got.sillHeight).toBeCloseTo(o.sillHeight, 6);
|
||||
expect(got.typeId).toBe(o.typeId);
|
||||
}
|
||||
const c = sampleProject.ceilings![0];
|
||||
const gc = p.ceilings![0];
|
||||
expect(gc.floorId).toBe(c.floorId);
|
||||
expect(gc.ceilingTypeId).toBe(c.ceilingTypeId);
|
||||
expect(gc.top).toBeUndefined();
|
||||
expect(gc.outline.length).toBe(c.outline.length);
|
||||
for (const q of c.outline) expect(gc.outline.some((g) => near(g, q)), JSON.stringify(q)).toBe(true);
|
||||
const room = sampleProject.rooms![0];
|
||||
const gr = p.rooms![0];
|
||||
expect([gr.name, gr.siaCategory, gr.floorId]).toEqual([room.name, room.siaCategory, room.floorId]);
|
||||
for (const q of room.boundary) expect(gr.boundary.some((g) => near(g, q))).toBe(true);
|
||||
const text = formatIfcElementsSummary(summary, report, (k, v) => `${k}${JSON.stringify(v ?? {})}`);
|
||||
expect(text).toContain('"walls":9');
|
||||
});
|
||||
|
||||
it("in ein Projekt ohne Geschosse/Typen: legt Geschosse, Wand-/Deckentypen und Materialien an", async () => {
|
||||
const bare: Project = {
|
||||
...emptyProject,
|
||||
drawingLevels: emptyProject.drawingLevels.filter((l) => l.kind !== "floor"),
|
||||
wallTypes: [],
|
||||
ceilingTypes: [],
|
||||
components: [],
|
||||
};
|
||||
const { project: p, summary } = await importInto(bare, sampleProject);
|
||||
expect(summary).toMatchObject({ walls: 9, openings: 3, ceilings: 1, rooms: 1, floors: 2, wallTypes: 2, ceilingTypes: 1 });
|
||||
// Materialien: Aussenputz, Wärmedämmung, Backstein, Innenputz, Zementestrich, Beton.
|
||||
expect(summary.components).toBe(6);
|
||||
const floors = p.drawingLevels.filter((l) => l.kind === "floor");
|
||||
expect(floors.map((f) => [f.name, f.baseElevation, f.floorHeight])).toEqual([
|
||||
["Erdgeschoss", 0, 2.6],
|
||||
["Obergeschoss", 2.6, 2.6],
|
||||
]);
|
||||
const aw = p.wallTypes.find((t) => t.name === "Aussenwand 34.5 cm")!;
|
||||
expect(wallTypeThickness(aw)).toBeCloseTo(0.345, 9);
|
||||
expect(aw.layers.map((l) => p.components.find((c) => c.id === l.componentId)!.name)).toEqual([
|
||||
"Aussenputz", "Wärmedämmung", "Backstein", "Innenputz",
|
||||
]);
|
||||
expect(p.walls.filter((w) => w.wallTypeId === aw.id).length).toBe(8);
|
||||
expect(validateProject(p)).toEqual([]);
|
||||
});
|
||||
|
||||
it("über Ops angewandt und gespeichert/geladen bleibt alles gleich", async () => {
|
||||
const { project: next } = await importInto(emptyProject, sampleProject);
|
||||
const applied = applyOps(emptyProject, diffToOps(emptyProject, next));
|
||||
expect(applied.walls).toEqual(next.walls);
|
||||
expect(applied.openings).toEqual(next.openings);
|
||||
const back = parseProjectFile(serializeProject(applied));
|
||||
expect(back.ok).toBe(true);
|
||||
if (!back.ok) return;
|
||||
expect(back.warnings).toEqual([]);
|
||||
expect(back.project.walls).toEqual(next.walls);
|
||||
expect(back.project.ceilings).toEqual(next.ceilings);
|
||||
expect(back.project.context).toEqual(next.context);
|
||||
});
|
||||
|
||||
it("Stützen (rechteckig gedreht, rund) und abgesetzte Wand-Unterkante", async () => {
|
||||
const cols: Column[] = [
|
||||
{ id: "S1", type: "column", floorId: "eg", categoryCode: "50", position: { x: 1, y: 1 }, profile: { kind: "rect", width: 0.3, depth: 0.5 }, rotation: 0, height: 2.4 },
|
||||
{ id: "S2", type: "column", floorId: "og", categoryCode: "50", position: { x: 3, y: 2 }, profile: { kind: "round", radius: 0.15 }, rotation: 0, height: 2.5 },
|
||||
];
|
||||
const src: Project = { ...sampleProject, columns: cols };
|
||||
const { project: p, summary } = await importInto(emptyProject, src);
|
||||
expect(summary.columns).toBe(2);
|
||||
const s1 = p.columns!.find((c) => c.profile.kind === "rect")!;
|
||||
expect(s1.floorId).toBe("eg");
|
||||
expect(near(s1.position, { x: 1, y: 1 })).toBe(true);
|
||||
expect(s1.profile).toEqual({ kind: "rect", width: 0.3, depth: 0.5 });
|
||||
expect(s1.rotation).toBeCloseTo(0, 9);
|
||||
expect(s1.height).toBeCloseTo(2.4, 9);
|
||||
const s2 = p.columns!.find((c) => c.profile.kind === "round")!;
|
||||
expect(s2.floorId).toBe("og");
|
||||
expect(near(s2.position, { x: 3, y: 2 }, 1e-4)).toBe(true);
|
||||
expect(s2.profile.kind === "round" && s2.profile.radius).toBeCloseTo(0.15, 6);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Kontext-Mesh: Farbe und GlobalId", () => {
|
||||
const product = (color: IfcProduct["color"], globalId = "2O2Fr$t4X7Zf8NOew3FLOH"): IfcProduct => ({
|
||||
globalId,
|
||||
ifcClass: "IfcWall",
|
||||
name: "Wand",
|
||||
storey: "EG",
|
||||
color,
|
||||
positions: new Float64Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]),
|
||||
indices: new Uint32Array([0, 2, 1, 0, 1, 3, 0, 3, 2, 1, 2, 3]),
|
||||
});
|
||||
|
||||
it("Farbe als #rrggbb, GlobalId als Feld, Name ohne GlobalId", () => {
|
||||
const [m] = ifcToImportedMeshes([product([1, 0.5, 0, 0.8])], "x.ifc", { group: "product" });
|
||||
expect(m.color).toBe("#ff8000");
|
||||
expect(m.ifcGlobalId).toBe("2O2Fr$t4X7Zf8NOew3FLOH");
|
||||
expect(m.name).toBe("EG: Wand");
|
||||
const [n] = ifcToImportedMeshes([product(null, "")], "x.ifc", { group: "product" });
|
||||
expect(n.color).toBeUndefined();
|
||||
expect(n.ifcGlobalId).toBeUndefined();
|
||||
// Zusammengelegt: gemeinsame Farbe nur, wenn alle gleich.
|
||||
expect(ifcToImportedMeshes([product([1, 0, 0, 1]), product([1, 0, 0, 1])], "x.ifc", { group: "class" })[0].color).toBe("#ff0000");
|
||||
expect(ifcToImportedMeshes([product([1, 0, 0, 1]), product([0, 0, 1, 1])], "x.ifc", { group: "class" })[0].color).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Farbe aus der Datei (IfcStyledItem) kommt am Mesh an und übersteht Speichern/Laden", async () => {
|
||||
const { products } = await readIfc(new Uint8Array(readFileSync(new URL("./testdata/ifc-geometry-cases.ifc", import.meta.url))));
|
||||
const meshes = ifcToImportedMeshes(products, "cases.ifc");
|
||||
expect(meshes.every((m) => m.ifcGlobalId && !m.name.includes("["))).toBe(true);
|
||||
const withColor = { ...meshes[0], color: "#336699" };
|
||||
const proj: Project = { ...emptyProject, context: [withColor] };
|
||||
const back = parseProjectFile(serializeProject(proj));
|
||||
expect(back.ok && back.project.context?.[0]).toEqual(withColor);
|
||||
});
|
||||
});
|
||||
|
||||
// Freie Beispieldateien (github.com/buildingSMART/Sample-Test-Files u. a., nicht im Repo):
|
||||
// DOSSIER_IFC_SAMPLES=<Verzeichnis>. Prüft: kein Absturz, gültiges Projekt, Zählung je Datei.
|
||||
const samples = process.env.DOSSIER_IFC_SAMPLES;
|
||||
describe.skipIf(!samples || !existsSync(samples))("IFC-Import als Bauteile: Beispieldateien", { timeout: 600_000 }, () => {
|
||||
it("alle Dateien lesbar, Ergebnis gültig", async () => {
|
||||
const files: string[] = [];
|
||||
const walk = (d: string) => {
|
||||
for (const n of readdirSync(d)) {
|
||||
const f = join(d, n);
|
||||
if (statSync(f).isDirectory()) walk(f);
|
||||
else if (/\.ifc$/i.test(n)) files.push(f);
|
||||
}
|
||||
};
|
||||
walk(samples!);
|
||||
const rows: string[] = [];
|
||||
for (const f of files) {
|
||||
const { products, elements } = await readIfcElements(new Uint8Array(readFileSync(f)));
|
||||
const { project, summary } = ifcElementsToProject(emptyProject, products, elements, { fileName: f });
|
||||
expect(validateProject(project), f).toEqual([]);
|
||||
rows.push(`${f.slice(samples!.length + 1)}: ${JSON.stringify(summary)}`);
|
||||
}
|
||||
process.stderr.write(rows.join("\n") + "\n");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,550 @@
|
||||
// IFC-Import zu echten Bauteilen ([B4], zweite Stufe von [25]): baut aus dem, was das Format-Modul
|
||||
// erkannt hat (`src-tauri/fileio/src/ifc_semantic.rs`: Achse, Dicke, Höhe, Umriss … in Metern),
|
||||
// Dossier-Objekte — Geschosse, Wände (Wandtyp aus den Materialschichten, wiederverwendet oder neu),
|
||||
// Türen/Fenster/Wanddurchbrüche, Decken (Deckentyp), Stützen, Räume. Was Rust nicht sicher abbilden
|
||||
// konnte, kommt wie beim Mesh-Import als Kontext-Mesh (`ifcImport.ts`).
|
||||
//
|
||||
// Keine Geometrie-Rechnung hier: TS ordnet nur zu (Geschoss nach Höhe, Typ nach Schichten) und setzt
|
||||
// die Objekte zusammen. Das Projekt wird nicht verändert — der Aufrufer übernimmt das Ergebnis über
|
||||
// `setProject` (App) bzw. `diffToOps`/`applyOps` (CLI), also über Ops.
|
||||
|
||||
import { ensureContextCategories } from "../model/contextCategories";
|
||||
import type {
|
||||
Ceiling,
|
||||
CeilingType,
|
||||
Column,
|
||||
Component,
|
||||
DrawingLevel,
|
||||
ImportedMesh,
|
||||
LayerCategory,
|
||||
Opening,
|
||||
Project,
|
||||
Room,
|
||||
SiaCategory,
|
||||
Vec2,
|
||||
Wall,
|
||||
WallType,
|
||||
} from "../model/types";
|
||||
import {
|
||||
decodeIfc,
|
||||
geoShift,
|
||||
ifcColorHex,
|
||||
ifcToImportedMeshes,
|
||||
readIfcFlat,
|
||||
type IfcFlat,
|
||||
type IfcImportReport,
|
||||
type IfcProduct,
|
||||
} from "./ifcImport";
|
||||
|
||||
// ── Rohdaten aus Rust ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface IfcMatLayer {
|
||||
material: string;
|
||||
/** 0 = einziges Material ohne Schichtdicke (gilt für die ganze Dicke). */
|
||||
thickness: number;
|
||||
color: [number, number, number, number] | null;
|
||||
}
|
||||
|
||||
interface IfcInfo {
|
||||
globalId: string;
|
||||
ifcClass: string;
|
||||
name: string | null;
|
||||
/** Index in `storeys`. */
|
||||
storey: number | null;
|
||||
color: [number, number, number, number] | null;
|
||||
typeName: string | null;
|
||||
layers: IfcMatLayer[];
|
||||
}
|
||||
|
||||
export interface IfcStoreyData {
|
||||
globalId: string;
|
||||
name: string;
|
||||
elevation: number;
|
||||
}
|
||||
export interface IfcWallData extends IfcInfo {
|
||||
/** Achse; erste Schicht rechts der Richtung start → end (wie Dossier). */
|
||||
start: Vec2;
|
||||
end: Vec2;
|
||||
z0: number;
|
||||
z1: number;
|
||||
thickness: number;
|
||||
}
|
||||
export interface IfcOpeningData extends IfcInfo {
|
||||
/** Index in `walls`. */
|
||||
host: number;
|
||||
kind: "door" | "window" | "hole";
|
||||
position: number;
|
||||
width: number;
|
||||
sill: number;
|
||||
height: number;
|
||||
}
|
||||
export interface IfcSlabData extends IfcInfo {
|
||||
outline: Vec2[];
|
||||
holes: Vec2[][];
|
||||
z0: number;
|
||||
z1: number;
|
||||
}
|
||||
export interface IfcColumnData extends IfcInfo {
|
||||
center: Vec2;
|
||||
rotation: number;
|
||||
profile: { kind: "rect"; width: number; depth: number } | { kind: "round"; radius: number };
|
||||
z0: number;
|
||||
z1: number;
|
||||
}
|
||||
export interface IfcSpaceData extends IfcInfo {
|
||||
longName: string | null;
|
||||
sia: string | null;
|
||||
boundary: Vec2[];
|
||||
z0: number;
|
||||
z1: number;
|
||||
}
|
||||
|
||||
/** Erkannte Bauteile einer Datei. */
|
||||
export interface IfcElementsData {
|
||||
storeys: IfcStoreyData[];
|
||||
walls: IfcWallData[];
|
||||
openings: IfcOpeningData[];
|
||||
slabs: IfcSlabData[];
|
||||
columns: IfcColumnData[];
|
||||
spaces: IfcSpaceData[];
|
||||
/** Nicht sicher abbildbare Kandidaten je Klasse (bleiben Mesh). */
|
||||
kept: Record<string, number>;
|
||||
}
|
||||
|
||||
interface RawElement extends IfcInfo {
|
||||
kind: "wall" | "opening" | "slab" | "column" | "space";
|
||||
at: number;
|
||||
n: number;
|
||||
host?: number;
|
||||
openingKind?: "door" | "window" | "hole";
|
||||
profile?: "rect" | "round";
|
||||
longName?: string | null;
|
||||
sia?: string | null;
|
||||
}
|
||||
|
||||
/** Erkannte Bauteile aus dem Rohergebnis; `null`, wenn ohne Bauteil-Erkennung gelesen. */
|
||||
export function decodeIfcElements(flat: IfcFlat): IfcElementsData | null {
|
||||
const meta = JSON.parse(flat.meta) as { elements?: { storeys: IfcStoreyData[]; elements: RawElement[]; kept: Record<string, number> } };
|
||||
const raw = meta.elements;
|
||||
const data = flat.elementData;
|
||||
if (!raw || !data) return null;
|
||||
const out: IfcElementsData = { storeys: raw.storeys, walls: [], openings: [], slabs: [], columns: [], spaces: [], kept: raw.kept ?? {} };
|
||||
// Wand-Index in Rust → Index in `out.walls` (verworfene Wände fallen heraus).
|
||||
const wallIndex = new Map<number, number>();
|
||||
let rustWall = 0;
|
||||
for (const e of raw.elements) {
|
||||
const v = data.subarray(e.at, e.at + e.n);
|
||||
if (v.length !== e.n || !v.every(Number.isFinite)) {
|
||||
if (e.kind === "wall") rustWall++;
|
||||
continue;
|
||||
}
|
||||
const info: IfcInfo = {
|
||||
globalId: e.globalId,
|
||||
ifcClass: e.ifcClass,
|
||||
name: e.name,
|
||||
storey: e.storey,
|
||||
color: e.color,
|
||||
typeName: e.typeName,
|
||||
layers: e.layers ?? [],
|
||||
};
|
||||
const rings = (start: number, count: number): { rings: Vec2[][]; ok: boolean } => {
|
||||
const res: Vec2[][] = [];
|
||||
let i = start;
|
||||
for (let r = 0; r < count; r++) {
|
||||
const n = v[i++];
|
||||
if (!(n >= 3) || i + 2 * n > v.length) return { rings: res, ok: false };
|
||||
const ring: Vec2[] = [];
|
||||
for (let k = 0; k < n; k++) ring.push({ x: v[i + 2 * k], y: v[i + 2 * k + 1] });
|
||||
i += 2 * n;
|
||||
res.push(ring);
|
||||
}
|
||||
return { rings: res, ok: true };
|
||||
};
|
||||
switch (e.kind) {
|
||||
case "wall":
|
||||
if (v.length === 7) {
|
||||
wallIndex.set(rustWall, out.walls.length);
|
||||
out.walls.push({ ...info, start: { x: v[0], y: v[1] }, end: { x: v[2], y: v[3] }, z0: v[4], z1: v[5], thickness: v[6] });
|
||||
}
|
||||
rustWall++;
|
||||
break;
|
||||
case "opening": {
|
||||
const host = wallIndex.get(e.host ?? -1);
|
||||
if (host !== undefined && v.length === 4) {
|
||||
out.openings.push({ ...info, host, kind: e.openingKind ?? "hole", position: v[0], width: v[1], sill: v[2], height: v[3] });
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "slab": {
|
||||
const r = rings(3, v[2]);
|
||||
if (r.ok && r.rings.length >= 1) out.slabs.push({ ...info, z0: v[0], z1: v[1], outline: r.rings[0], holes: r.rings.slice(1) });
|
||||
break;
|
||||
}
|
||||
case "column":
|
||||
if (v.length === 7) {
|
||||
const profile =
|
||||
e.profile === "round" ? { kind: "round" as const, radius: v[5] } : { kind: "rect" as const, width: v[5], depth: v[6] };
|
||||
out.columns.push({ ...info, center: { x: v[0], y: v[1] }, rotation: v[2], z0: v[3], z1: v[4], profile });
|
||||
}
|
||||
break;
|
||||
case "space": {
|
||||
const r = rings(2, 1);
|
||||
if (r.ok) out.spaces.push({ ...info, longName: e.longName ?? null, sia: e.sia ?? null, z0: v[0], z1: v[1], boundary: r.rings[0] });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Liest IFC-Bytes mit Bauteil-Erkennung (im Worker, sonst direkt). */
|
||||
export async function readIfcElements(
|
||||
bytes: Uint8Array,
|
||||
): Promise<{ products: IfcProduct[]; report: IfcImportReport; elements: IfcElementsData }> {
|
||||
const flat = await readIfcFlat(bytes, true);
|
||||
const { products, report } = decodeIfc(flat);
|
||||
const elements = decodeIfcElements(flat) ?? { storeys: [], walls: [], openings: [], slabs: [], columns: [], spaces: [], kept: {} };
|
||||
return { products, report, elements };
|
||||
}
|
||||
|
||||
// ── Aufbau der Dossier-Objekte ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface IfcElementsOptions {
|
||||
/** Dateiname (für die Namen der Kontext-Meshes). */
|
||||
fileName: string;
|
||||
/** LV95-Ursprung des Projekts (`projectGeoOrigin`), sonst null. */
|
||||
geoOrigin?: { e: number; n: number } | null;
|
||||
group?: "product" | "class" | "auto";
|
||||
}
|
||||
|
||||
/** Was übernommen wurde (für Meldung und Tests). */
|
||||
export interface IfcElementsSummary {
|
||||
walls: number;
|
||||
openings: number;
|
||||
ceilings: number;
|
||||
columns: number;
|
||||
rooms: number;
|
||||
/** Neu angelegte Geschosse. */
|
||||
floors: number;
|
||||
wallTypes: number;
|
||||
ceilingTypes: number;
|
||||
components: number;
|
||||
/** Bauteile als Kontext-Mesh. */
|
||||
meshes: number;
|
||||
/** Davon Kandidaten, die nicht sicher abbildbar waren. */
|
||||
kept: number;
|
||||
}
|
||||
|
||||
const WALL_CATEGORY = "20";
|
||||
const OPENING_CATEGORY = "21";
|
||||
const CEILING_CATEGORY = "30";
|
||||
const COLUMN_CATEGORY = "50";
|
||||
const ROOM_CATEGORY = "60";
|
||||
const ROOM_COLOR = "#6b7280";
|
||||
const SIA: readonly SiaCategory[] = ["HNF", "NNF", "VF", "FF", "KGF", "AGF"];
|
||||
/** Toleranzen (m): gleiche Höhe eines Geschosses, gleiche Schichtdicke. */
|
||||
const LEVEL_TOL = 0.005;
|
||||
const LAYER_TOL = 0.0005;
|
||||
|
||||
let counter = 0;
|
||||
|
||||
const round = (x: number, step = 1e-9) => Math.round(x / step) * step;
|
||||
|
||||
function flatCategories(list: LayerCategory[], out: LayerCategory[] = []): LayerCategory[] {
|
||||
for (const c of list) {
|
||||
out.push(c);
|
||||
if (c.children) flatCategories(c.children, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt die erkannten Bauteile und die übrigen Kontext-Meshes ins Projekt (neues Objekt, das alte
|
||||
* bleibt unverändert). Geschosse werden nach Höhe wiederverwendet (±5 mm) oder angelegt, Wand- und
|
||||
* Deckentypen nach Schichten (Material + Dicke) wiederverwendet oder angelegt, Materialien nach Namen.
|
||||
*/
|
||||
export function ifcElementsToProject(
|
||||
project: Project,
|
||||
products: IfcProduct[],
|
||||
elements: IfcElementsData,
|
||||
opts: IfcElementsOptions,
|
||||
): { project: Project; summary: IfcElementsSummary } {
|
||||
const stamp = Date.now().toString(36);
|
||||
const newId = (kind: string) => `ifc-${kind}-${stamp}-${counter++}`;
|
||||
const summary: IfcElementsSummary = {
|
||||
walls: 0, openings: 0, ceilings: 0, columns: 0, rooms: 0, floors: 0, wallTypes: 0, ceilingTypes: 0, components: 0, meshes: 0,
|
||||
kept: Object.values(elements.kept).reduce((s, n) => s + n, 0),
|
||||
};
|
||||
|
||||
// Verschiebung bei Landeskoordinaten: gemeinsam für Bauteile und Meshes.
|
||||
const extra: number[] = [];
|
||||
for (const w of elements.walls) extra.push(w.start.x, w.start.y, w.end.x, w.end.y);
|
||||
for (const s of elements.slabs) for (const p of s.outline) extra.push(p.x, p.y);
|
||||
for (const c of elements.columns) extra.push(c.center.x, c.center.y);
|
||||
for (const s of elements.spaces) for (const p of s.boundary) extra.push(p.x, p.y);
|
||||
const [dx, dy] = geoShift(products, opts.geoOrigin, extra);
|
||||
const mv = (p: Vec2): Vec2 => ({ x: round(p.x + dx), y: round(p.y + dy) });
|
||||
|
||||
// ── Geschosse ──
|
||||
const levels: DrawingLevel[] = [...project.drawingLevels];
|
||||
const floorsSorted = () => levels.filter((l) => l.kind === "floor").sort((a, b) => (a.baseElevation ?? 0) - (b.baseElevation ?? 0));
|
||||
const topOf = new Map<number, number>();
|
||||
const noteTop = (storey: number | null, z: number) => {
|
||||
if (storey !== null) topOf.set(storey, Math.max(topOf.get(storey) ?? -Infinity, z));
|
||||
};
|
||||
for (const w of elements.walls) noteTop(w.storey, w.z1);
|
||||
for (const c of elements.columns) noteTop(c.storey, c.z1);
|
||||
const storeyFloor = elements.storeys.map((s, i) => {
|
||||
const existing = levels.find((l) => l.kind === "floor" && Math.abs((l.baseElevation ?? 0) - s.elevation) <= LEVEL_TOL);
|
||||
if (existing) return existing.id;
|
||||
const next = elements.storeys[i + 1];
|
||||
const top = topOf.get(i);
|
||||
const height = next ? next.elevation - s.elevation : top !== undefined && top > s.elevation + 0.5 ? top - s.elevation : 2.6;
|
||||
const level: DrawingLevel = {
|
||||
id: newId("floor"),
|
||||
name: s.name || `IFC ${round(s.elevation, 0.001)}`,
|
||||
kind: "floor",
|
||||
visible: true,
|
||||
locked: false,
|
||||
floorHeight: round(height, 1e-6),
|
||||
cutHeight: 1,
|
||||
baseElevation: round(s.elevation, 1e-6),
|
||||
};
|
||||
// Einfügen vor dem ersten höheren Geschoss, sonst nach dem letzten.
|
||||
const floors = floorsSorted();
|
||||
const higher = floors.find((l) => (l.baseElevation ?? 0) > s.elevation);
|
||||
const at = higher ? levels.indexOf(higher) : floors.length ? levels.indexOf(floors[floors.length - 1]) + 1 : 0;
|
||||
levels.splice(at, 0, level);
|
||||
summary.floors++;
|
||||
return level.id;
|
||||
});
|
||||
/** Geschoss eines Bauteils: aus der Datei, sonst das höchste mit OK FB ≤ Unterkante. */
|
||||
const floorOf = (storey: number | null, z0: number): DrawingLevel => {
|
||||
const id = storey !== null ? storeyFloor[storey] : undefined;
|
||||
const byId = id ? levels.find((l) => l.id === id) : undefined;
|
||||
if (byId) return byId;
|
||||
const floors = floorsSorted();
|
||||
const below = floors.filter((l) => (l.baseElevation ?? 0) <= z0 + LEVEL_TOL);
|
||||
const f = below[below.length - 1] ?? floors[0];
|
||||
if (f) return f;
|
||||
const level: DrawingLevel = { id: newId("floor"), name: "IFC", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1, baseElevation: 0 };
|
||||
levels.push(level);
|
||||
summary.floors++;
|
||||
return level;
|
||||
};
|
||||
const anchorOffset = (z: number, f: DrawingLevel) => round(z - (f.baseElevation ?? 0), 1e-6);
|
||||
|
||||
// ── Materialien und Typen ──
|
||||
const components: Component[] = [...project.components];
|
||||
const hatchId = project.hatches.find((h) => h.id === "none")?.id ?? project.hatches[0]?.id ?? "none";
|
||||
const componentFor = (name: string, color: string | undefined): string => {
|
||||
const key = name.trim().toLowerCase();
|
||||
const found = components.find((c) => c.name.trim().toLowerCase() === key);
|
||||
if (found) return found.id;
|
||||
const c: Component = { id: newId("component"), name: name.trim() || "IFC", color: color ?? "#b0b0b0", hatchId, joinPriority: 50 };
|
||||
components.push(c);
|
||||
summary.components++;
|
||||
return c.id;
|
||||
};
|
||||
/** Schichten eines Bauteils der Dicke `t`: die der Datei, wenn sie aufgehen, sonst eine Schicht. */
|
||||
const layerSpec = (e: IfcInfo, t: number): { material: string; thickness: number; color?: string }[] => {
|
||||
const ls = e.layers;
|
||||
const sum = ls.reduce((s, l) => s + l.thickness, 0);
|
||||
if (ls.length > 0 && ls.every((l) => l.thickness > 0) && Math.abs(sum - t) <= 0.005) {
|
||||
return ls.map((l) => ({ material: l.material, thickness: round(l.thickness, 1e-6), color: ifcColorHex(l.color) }));
|
||||
}
|
||||
const first = ls.length === 1 ? ls[0] : undefined;
|
||||
return [{ material: first?.material ?? "", thickness: round(t, 1e-6), color: ifcColorHex(first?.color ?? e.color) }];
|
||||
};
|
||||
const sameLayers = (
|
||||
have: { componentId: string; thickness: number }[],
|
||||
want: { material: string; thickness: number }[],
|
||||
): boolean =>
|
||||
have.length === want.length &&
|
||||
have.every((l, i) => {
|
||||
if (Math.abs(l.thickness - want[i].thickness) > LAYER_TOL) return false;
|
||||
const name = components.find((c) => c.id === l.componentId)?.name.trim().toLowerCase() ?? "";
|
||||
return want[i].material ? name === want[i].material.trim().toLowerCase() : true;
|
||||
});
|
||||
const typeName = (e: IfcInfo, t: number) => e.typeName?.trim() || `IFC ${round(t * 100, 0.1)} cm`;
|
||||
const wallTypes: WallType[] = [...project.wallTypes];
|
||||
const wallTypeFor = (e: IfcInfo, t: number): string => {
|
||||
const spec = layerSpec(e, t);
|
||||
const name = typeName(e, t);
|
||||
// Ohne Material: nur ein gleich benannter, gleich dicker Typ passt.
|
||||
const found = wallTypes.find((wt) => sameLayers(wt.layers, spec) && (spec.some((l) => l.material) || wt.name === name));
|
||||
if (found) return found.id;
|
||||
const wt: WallType = {
|
||||
id: newId("walltype"),
|
||||
name,
|
||||
layers: spec.map((l) => ({ componentId: componentFor(l.material, l.color), thickness: l.thickness })),
|
||||
};
|
||||
wallTypes.push(wt);
|
||||
summary.wallTypes++;
|
||||
return wt.id;
|
||||
};
|
||||
const ceilingTypes: CeilingType[] = [...(project.ceilingTypes ?? [])];
|
||||
const ceilingTypeFor = (e: IfcInfo, t: number): string => {
|
||||
const spec = layerSpec(e, t);
|
||||
const name = typeName(e, t);
|
||||
const found = ceilingTypes.find((ct) => sameLayers(ct.layers, spec) && (spec.some((l) => l.material) || ct.name === name));
|
||||
if (found) return found.id;
|
||||
const ct: CeilingType = {
|
||||
id: newId("ceilingtype"),
|
||||
name,
|
||||
layers: spec.map((l) => ({ componentId: componentFor(l.material, l.color), thickness: l.thickness })),
|
||||
};
|
||||
ceilingTypes.push(ct);
|
||||
summary.ceilingTypes++;
|
||||
return ct.id;
|
||||
};
|
||||
|
||||
// ── Wände und Öffnungen ──
|
||||
const walls: Wall[] = [];
|
||||
for (const w of elements.walls) {
|
||||
const f = floorOf(w.storey, w.z0);
|
||||
const height = round(w.z1 - w.z0, 1e-6);
|
||||
const bottom = anchorOffset(w.z0, f);
|
||||
walls.push({
|
||||
id: newId("wall"),
|
||||
type: "wall",
|
||||
floorId: f.id,
|
||||
categoryCode: WALL_CATEGORY,
|
||||
start: mv(w.start),
|
||||
end: mv(w.end),
|
||||
wallTypeId: wallTypeFor(w, w.thickness),
|
||||
height,
|
||||
...(Math.abs(bottom) > LEVEL_TOL ? { bottom: { mode: "floor" as const, floorId: f.id, offset: bottom } } : {}),
|
||||
});
|
||||
}
|
||||
const openings: Opening[] = [];
|
||||
for (const o of elements.openings) {
|
||||
const host = walls[o.host];
|
||||
if (!host) continue;
|
||||
const kind = o.kind === "window" ? "window" : "door";
|
||||
const typeId = o.kind === "door" ? project.doorTypes?.[0]?.id : o.kind === "window" ? project.windowTypes?.[0]?.id : undefined;
|
||||
openings.push({
|
||||
id: newId("opening"),
|
||||
type: "opening",
|
||||
hostWallId: host.id,
|
||||
categoryCode: OPENING_CATEGORY,
|
||||
kind,
|
||||
position: round(o.position, 1e-6),
|
||||
width: round(o.width, 1e-6),
|
||||
height: round(o.height, 1e-6),
|
||||
sillHeight: round(o.sill, 1e-6),
|
||||
...(o.kind === "hole" ? { doorType: "wandoeffnung" as const } : {}),
|
||||
...(typeId ? { typeId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
// ── Decken, Stützen, Räume ──
|
||||
const ceilings: Ceiling[] = [];
|
||||
for (const s of elements.slabs) {
|
||||
const f = floorOf(s.storey, s.z0);
|
||||
const t = s.z1 - s.z0;
|
||||
const floorTop = (f.baseElevation ?? 0) + (f.floorHeight ?? 0);
|
||||
ceilings.push({
|
||||
id: newId("ceiling"),
|
||||
type: "ceiling",
|
||||
floorId: f.id,
|
||||
categoryCode: CEILING_CATEGORY,
|
||||
outline: s.outline.map(mv),
|
||||
...(s.holes.length ? { openings: s.holes.map((h) => h.map(mv)) } : {}),
|
||||
wallTypeId: project.wallTypes[0]?.id ?? wallTypes[0]?.id ?? "",
|
||||
ceilingTypeId: ceilingTypeFor(s, t),
|
||||
...(Math.abs(s.z1 - floorTop) > LEVEL_TOL ? { top: { mode: "floor" as const, floorId: f.id, offset: anchorOffset(s.z1, f) } } : {}),
|
||||
});
|
||||
}
|
||||
const columns: Column[] = [];
|
||||
for (const c of elements.columns) {
|
||||
const f = floorOf(c.storey, c.z0);
|
||||
const bottom = anchorOffset(c.z0, f);
|
||||
const material = c.layers[0]?.material;
|
||||
columns.push({
|
||||
id: newId("column"),
|
||||
type: "column",
|
||||
floorId: f.id,
|
||||
categoryCode: COLUMN_CATEGORY,
|
||||
position: mv(c.center),
|
||||
profile:
|
||||
c.profile.kind === "round"
|
||||
? { kind: "round", radius: round(c.profile.radius, 1e-6) }
|
||||
: { kind: "rect", width: round(c.profile.width, 1e-6), depth: round(c.profile.depth, 1e-6) },
|
||||
rotation: c.rotation,
|
||||
height: round(c.z1 - c.z0, 1e-6),
|
||||
...(material ? { componentId: componentFor(material, ifcColorHex(c.layers[0].color ?? c.color)) } : {}),
|
||||
...(Math.abs(bottom) > LEVEL_TOL ? { bottom: { mode: "floor" as const, floorId: f.id, offset: bottom } } : {}),
|
||||
});
|
||||
}
|
||||
const roomColor = flatCategories(project.layers).find((c) => c.code === ROOM_CATEGORY)?.color ?? ROOM_COLOR;
|
||||
const rooms: Room[] = [];
|
||||
for (const s of elements.spaces) {
|
||||
const f = floorOf(s.storey, s.z0);
|
||||
const boundary = s.boundary.map(mv);
|
||||
const sia = SIA.find((c) => c === s.sia?.trim().toUpperCase());
|
||||
const n = boundary.length;
|
||||
rooms.push({
|
||||
id: newId("room"),
|
||||
type: "room",
|
||||
floorId: f.id,
|
||||
categoryCode: ROOM_CATEGORY,
|
||||
siaCategory: sia ?? "HNF",
|
||||
name: s.longName || s.name || `Raum ${(project.rooms?.length ?? 0) + rooms.length + 1}`,
|
||||
boundary,
|
||||
color: roomColor,
|
||||
stampAnchor: { x: boundary.reduce((a, p) => a + p.x, 0) / n, y: boundary.reduce((a, p) => a + p.y, 0) / n },
|
||||
});
|
||||
}
|
||||
|
||||
// ── Übrige Bauteile als Kontext-Mesh ──
|
||||
const meshes: ImportedMesh[] = ifcToImportedMeshes(products, opts.fileName, { geoOrigin: opts.geoOrigin, group: opts.group, shift: [dx, dy] });
|
||||
summary.walls = walls.length;
|
||||
summary.openings = openings.length;
|
||||
summary.ceilings = ceilings.length;
|
||||
summary.columns = columns.length;
|
||||
summary.rooms = rooms.length;
|
||||
summary.meshes = meshes.length;
|
||||
|
||||
const next: Project = {
|
||||
...project,
|
||||
drawingLevels: levels,
|
||||
components,
|
||||
wallTypes,
|
||||
...(ceilingTypes.length || project.ceilingTypes ? { ceilingTypes } : {}),
|
||||
walls: [...project.walls, ...walls],
|
||||
openings: [...(project.openings ?? []), ...openings],
|
||||
ceilings: [...(project.ceilings ?? []), ...ceilings],
|
||||
columns: [...(project.columns ?? []), ...columns],
|
||||
rooms: [...(project.rooms ?? []), ...rooms],
|
||||
...(meshes.length
|
||||
? {
|
||||
context: [...(project.context ?? []), ...meshes],
|
||||
layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
return { project: next, summary };
|
||||
}
|
||||
|
||||
/** Meldung zum Bauteil-Import; `tr` übersetzt (Kern kennt kein i18n). */
|
||||
export function formatIfcElementsSummary(
|
||||
s: IfcElementsSummary,
|
||||
r: IfcImportReport,
|
||||
tr: (key: "ifc.import.elements" | "ifc.import.kept", vars?: Record<string, string | number>) => string,
|
||||
): string {
|
||||
const parts = [
|
||||
tr("ifc.import.elements", {
|
||||
schema: r.schema || "IFC",
|
||||
walls: s.walls,
|
||||
openings: s.openings,
|
||||
ceilings: s.ceilings,
|
||||
columns: s.columns,
|
||||
rooms: s.rooms,
|
||||
floors: s.floors,
|
||||
meshes: s.meshes,
|
||||
}),
|
||||
];
|
||||
if (s.kept) parts.push(tr("ifc.import.kept", { n: s.kept }));
|
||||
return parts.join(" · ");
|
||||
}
|
||||
+76
-34
@@ -1,9 +1,10 @@
|
||||
// IFC-Import als Mesh ([B3]): dünne Fassade über `import_ifc` im Format-Modul (`src-tauri/fileio`,
|
||||
// `ifc_import.rs`). Jedes IFC-Bauteil mit Körper wird zu einem `ImportedMesh` der Kontext-Schicht
|
||||
// (wie der STEP-Import, `stepImport.ts`); echte Bauteile (Wand, Decke …) kommen mit [B4].
|
||||
// (wie der STEP-Import, `stepImport.ts`); echte Bauteile (Wand, Decke …) baut auf Wunsch
|
||||
// `ifcElements.ts` ([B4]) aus `import_ifc_elements`.
|
||||
//
|
||||
// Gruppierung: je Bauteil ein Mesh (anwählbar, Name/Geschoss/GlobalId bleiben erhalten, im
|
||||
// Kontext-Panel nach IFC-Klasse gruppiert über `layer`). Bei sehr vielen Bauteilen (> `MAX_SINGLE`)
|
||||
// Gruppierung: je Bauteil ein Mesh (anwählbar, Name/Geschoss bleiben erhalten, GlobalId in
|
||||
// `ifcGlobalId`, Farbe in `color`; im Kontext-Panel nach IFC-Klasse gruppiert über `layer`). Bei sehr vielen Bauteilen (> `MAX_SINGLE`)
|
||||
// werden Bauteile gleicher Klasse und gleichen Geschosses zusammengelegt, damit Projektdatei und
|
||||
// Kontext-Panel handhabbar bleiben.
|
||||
//
|
||||
@@ -18,6 +19,7 @@
|
||||
import { loadFileio } from "../engine/fileioWasm";
|
||||
import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories";
|
||||
import type { ImportedMesh } from "../model/types";
|
||||
import { rgbToHex } from "../model/color";
|
||||
|
||||
/** Ein gelesenes IFC-Bauteil. */
|
||||
export interface IfcProduct {
|
||||
@@ -62,23 +64,27 @@ interface RawProduct {
|
||||
indexCount: number;
|
||||
}
|
||||
|
||||
/** Rohergebnis aus Rust: Bericht (JSON) und alle Bauteile hintereinander in zwei flachen Puffern. */
|
||||
/** Rohergebnis aus Rust: Bericht (JSON) und alle Bauteile hintereinander in zwei flachen Puffern;
|
||||
* mit `elements` dazu die Zahlen der erkannten Bauteile ([B4], `ifcElements.ts`). */
|
||||
export interface IfcFlat {
|
||||
meta: string;
|
||||
positions: Float64Array;
|
||||
indices: Uint32Array;
|
||||
elementData?: Float64Array;
|
||||
}
|
||||
|
||||
/** Worker-Protokoll (`ifcImport.worker.ts`). */
|
||||
export type IfcWorkerRequest = { type: "parse"; data: ArrayBuffer };
|
||||
/** Worker-Protokoll (`ifcImport.worker.ts`); `elements` = echte Bauteile erkennen ([B4]). */
|
||||
export type IfcWorkerRequest = { type: "parse"; data: ArrayBuffer; elements?: boolean };
|
||||
export type IfcWorkerResponse = { type: "result"; flat: IfcFlat } | { type: "error"; message: string };
|
||||
|
||||
/** Liest IFC-Bytes mit dem geladenen Format-Modul (Worker oder aufrufender Thread). */
|
||||
export async function importIfcFlat(bytes: Uint8Array): Promise<IfcFlat> {
|
||||
export async function importIfcFlat(bytes: Uint8Array, elements = false): Promise<IfcFlat> {
|
||||
const m = await loadFileio();
|
||||
const r = m.import_ifc(bytes);
|
||||
const r = elements ? m.import_ifc_elements(bytes) : m.import_ifc(bytes);
|
||||
try {
|
||||
return { meta: r.meta, positions: r.positions(), indices: r.indices() };
|
||||
const flat: IfcFlat = { meta: r.meta, positions: r.positions(), indices: r.indices() };
|
||||
if (elements) flat.elementData = r.elementData();
|
||||
return flat;
|
||||
} finally {
|
||||
r.free();
|
||||
}
|
||||
@@ -88,15 +94,17 @@ export async function importIfcFlat(bytes: Uint8Array): Promise<IfcFlat> {
|
||||
export async function handleIfcWorkerRequest(req: IfcWorkerRequest): Promise<{ res: IfcWorkerResponse; transfer: Transferable[] }> {
|
||||
try {
|
||||
if (req?.type !== "parse" || !(req.data instanceof ArrayBuffer)) throw new Error("ungültige Anfrage");
|
||||
const flat = await importIfcFlat(new Uint8Array(req.data));
|
||||
return { res: { type: "result", flat }, transfer: [flat.positions.buffer, flat.indices.buffer] };
|
||||
const flat = await importIfcFlat(new Uint8Array(req.data), req.elements === true);
|
||||
const transfer: Transferable[] = [flat.positions.buffer, flat.indices.buffer];
|
||||
if (flat.elementData) transfer.push(flat.elementData.buffer);
|
||||
return { res: { type: "result", flat }, transfer };
|
||||
} catch (err) {
|
||||
return { res: { type: "error", message: err instanceof Error ? err.message : String(err) }, transfer: [] };
|
||||
}
|
||||
}
|
||||
|
||||
/** Liest im Web-Worker; `null`, wenn kein Worker verfügbar ist oder er nicht startet. */
|
||||
function readInWorker(bytes: Uint8Array): Promise<IfcFlat | null> {
|
||||
function readInWorker(bytes: Uint8Array, elements: boolean): Promise<IfcFlat | null> {
|
||||
if (typeof Worker === "undefined") return Promise.resolve(null);
|
||||
return new Promise((resolve, reject) => {
|
||||
let worker: Worker;
|
||||
@@ -117,7 +125,8 @@ function readInWorker(bytes: Uint8Array): Promise<IfcFlat | null> {
|
||||
};
|
||||
// Kopie übertragen: der Aufrufer behält seine Bytes.
|
||||
const data = bytes.slice().buffer;
|
||||
worker.postMessage({ type: "parse", data } satisfies IfcWorkerRequest, [data]);
|
||||
const req: IfcWorkerRequest = elements ? { type: "parse", data, elements } : { type: "parse", data };
|
||||
worker.postMessage(req, [data]);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -145,8 +154,18 @@ export function decodeIfc(flat: IfcFlat): { products: IfcProduct[]; report: IfcI
|
||||
|
||||
/** Liest IFC-Bytes (im Worker, sonst direkt). Wirft bei unlesbarer Datei (Meldung aus Rust). */
|
||||
export async function readIfc(bytes: Uint8Array): Promise<{ products: IfcProduct[]; report: IfcImportReport }> {
|
||||
const flat = (await readInWorker(bytes)) ?? (await importIfcFlat(bytes));
|
||||
return decodeIfc(flat);
|
||||
return decodeIfc(await readIfcFlat(bytes));
|
||||
}
|
||||
|
||||
/** Rohergebnis lesen (im Worker, sonst direkt); `elements` = echte Bauteile erkennen ([B4]). */
|
||||
export async function readIfcFlat(bytes: Uint8Array, elements = false): Promise<IfcFlat> {
|
||||
return (await readInWorker(bytes, elements)) ?? (await importIfcFlat(bytes, elements));
|
||||
}
|
||||
|
||||
/** RGBA 0..1 → `#rrggbb` (Alpha entfällt). */
|
||||
export function ifcColorHex(c: readonly number[] | null | undefined): string | undefined {
|
||||
if (!c || c.length < 3 || !c.slice(0, 3).every((v) => Number.isFinite(v))) return undefined;
|
||||
return rgbToHex({ r: c[0] * 255, g: c[1] * 255, b: c[2] * 255 });
|
||||
}
|
||||
|
||||
/** Ab so vielen Bauteilen wird je Klasse + Geschoss zusammengelegt. */
|
||||
@@ -157,12 +176,19 @@ export interface IfcToMeshesOptions {
|
||||
geoOrigin?: { e: number; n: number } | null;
|
||||
/** "product" = je Bauteil, "class" = je Klasse + Geschoss, "auto" (Standard) nach `MAX_SINGLE`. */
|
||||
group?: "product" | "class" | "auto";
|
||||
/** Feste Verschiebung statt der aus den Bauteilen geschätzten ([B4]: gemeinsam mit den Bauteilen). */
|
||||
shift?: [number, number];
|
||||
}
|
||||
|
||||
let counter = 0;
|
||||
|
||||
/** Verschiebung, falls die Datei in Landeskoordinaten liegt und das Projekt einen Bezug hat. */
|
||||
function geoShift(products: IfcProduct[], origin: { e: number; n: number } | null | undefined): [number, number] {
|
||||
/** Verschiebung, falls die Datei in Landeskoordinaten liegt und das Projekt einen Bezug hat;
|
||||
* `extra` = weitere Punkte (x,y flach, z. B. erkannte Bauteile [B4]). */
|
||||
export function geoShift(
|
||||
products: IfcProduct[],
|
||||
origin: { e: number; n: number } | null | undefined,
|
||||
extra: readonly number[] = [],
|
||||
): [number, number] {
|
||||
if (!origin) return [0, 0];
|
||||
let sx = 0;
|
||||
let sy = 0;
|
||||
@@ -174,6 +200,11 @@ function geoShift(products: IfcProduct[], origin: { e: number; n: number } | nul
|
||||
n++;
|
||||
}
|
||||
}
|
||||
for (let i = 0; i + 1 < extra.length; i += 2) {
|
||||
sx += extra[i];
|
||||
sy += extra[i + 1];
|
||||
n++;
|
||||
}
|
||||
if (n === 0) return [0, 0];
|
||||
const cx = sx / n;
|
||||
const cy = sy / n;
|
||||
@@ -184,7 +215,7 @@ function geoShift(products: IfcProduct[], origin: { e: number; n: number } | nul
|
||||
/** Bauteile → Kontext-Meshes (Kategorie „Situation" wie STEP; `layer` = IFC-Klasse). */
|
||||
export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, opts: IfcToMeshesOptions = {}): ImportedMesh[] {
|
||||
const base = fileName.replace(/\.[^.]+$/, "") || "IFC";
|
||||
const [dx, dy] = geoShift(products, opts.geoOrigin);
|
||||
const [dx, dy] = opts.shift ?? geoShift(products, opts.geoOrigin);
|
||||
const stamp = Date.now().toString(36);
|
||||
const group = opts.group ?? "auto";
|
||||
const perProduct = group === "product" || (group === "auto" && products.length <= MAX_SINGLE);
|
||||
@@ -203,14 +234,19 @@ export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, op
|
||||
};
|
||||
|
||||
if (perProduct) {
|
||||
return products.map((p) => ({
|
||||
id: `imported-ifc-${stamp}-${counter++}`,
|
||||
type: "importedMesh" as const,
|
||||
name: [p.storey, p.name || p.ifcClass].filter(Boolean).join(": ") + (p.globalId ? ` [${p.globalId}]` : ""),
|
||||
layer: p.ifcClass,
|
||||
categoryCode: GENERIC_IMPORT_CATEGORY.code,
|
||||
...toArrays([p]),
|
||||
}));
|
||||
return products.map((p) => {
|
||||
const color = ifcColorHex(p.color);
|
||||
return {
|
||||
id: `imported-ifc-${stamp}-${counter++}`,
|
||||
type: "importedMesh" as const,
|
||||
name: [p.storey, p.name || p.ifcClass].filter(Boolean).join(": "),
|
||||
layer: p.ifcClass,
|
||||
categoryCode: GENERIC_IMPORT_CATEGORY.code,
|
||||
...(color ? { color } : {}),
|
||||
...(p.globalId ? { ifcGlobalId: p.globalId } : {}),
|
||||
...toArrays([p]),
|
||||
};
|
||||
});
|
||||
}
|
||||
const groups = new Map<string, IfcProduct[]>();
|
||||
for (const p of products) {
|
||||
@@ -219,14 +255,20 @@ export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, op
|
||||
if (g) g.push(p);
|
||||
else groups.set(key, [p]);
|
||||
}
|
||||
return [...groups.values()].map((parts) => ({
|
||||
id: `imported-ifc-${stamp}-${counter++}`,
|
||||
type: "importedMesh" as const,
|
||||
name: `${base}: ${[parts[0].storey, parts[0].ifcClass].filter(Boolean).join(" ")} (${parts.length})`,
|
||||
layer: parts[0].ifcClass,
|
||||
categoryCode: GENERIC_IMPORT_CATEGORY.code,
|
||||
...toArrays(parts),
|
||||
}));
|
||||
return [...groups.values()].map((parts) => {
|
||||
// Gemeinsame Farbe nur, wenn alle Teile dieselbe haben.
|
||||
const colors = new Set(parts.map((p) => ifcColorHex(p.color) ?? ""));
|
||||
const color = colors.size === 1 ? [...colors][0] : "";
|
||||
return {
|
||||
id: `imported-ifc-${stamp}-${counter++}`,
|
||||
type: "importedMesh" as const,
|
||||
name: `${base}: ${[parts[0].storey, parts[0].ifcClass].filter(Boolean).join(" ")} (${parts.length})`,
|
||||
layer: parts[0].ifcClass,
|
||||
categoryCode: GENERIC_IMPORT_CATEGORY.code,
|
||||
...(color ? { color } : {}),
|
||||
...toArrays(parts),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Datei-Bytes → Kontext-Meshes + Bericht. */
|
||||
|
||||
@@ -2380,6 +2380,10 @@ export interface ImportedMesh {
|
||||
* IMMER sichtbar (Rückwärtskompatibilität), s. `generatePlan/context.ts`.
|
||||
*/
|
||||
categoryCode?: string;
|
||||
/** Farbe aus der Quelldatei (`#rrggbb`, z. B. IFC-Oberflächenstil/Material); fehlt sie, gilt die Kontext-Grundfarbe. */
|
||||
color?: string;
|
||||
/** IFC-GlobalId des Quell-Bauteils (IFC-Import je Bauteil). */
|
||||
ifcGlobalId?: string;
|
||||
positions: number[];
|
||||
indices: number[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// Auswahl beim IFC-Import ([B3]/[B4]): als Kontext-Meshes (Standard, wie bisher) oder als echte
|
||||
// Bauteile (`io/ifcElements.ts`). Overlay-Muster wie `UnsavedChangesDialog` (kein `window.confirm`).
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n";
|
||||
|
||||
export type IfcImportMode = "mesh" | "elements";
|
||||
|
||||
export interface IfcImportDialogProps {
|
||||
fileName: string;
|
||||
onImport: (mode: IfcImportMode) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function IfcImportDialog({ fileName, onImport, onCancel }: IfcImportDialogProps) {
|
||||
const [mode, setMode] = useState<IfcImportMode>("mesh");
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onCancel();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onCancel]);
|
||||
|
||||
return (
|
||||
<div className="imp-overlay" onClick={onCancel}>
|
||||
<div
|
||||
className="imp-dialog"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t("ifc.importDialog.title")}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<header className="imp-head">
|
||||
<span className="imp-head-title">{t("ifc.importDialog.title")}</span>
|
||||
<button className="imp-close" onClick={onCancel} aria-label={t("export.close")}>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="imp-body">
|
||||
<section className="imp-section">
|
||||
<div className="imp-section-title">{fileName}</div>
|
||||
<label className="imp-radio">
|
||||
<input type="radio" name="ifc-mode" checked={mode === "mesh"} onChange={() => setMode("mesh")} />
|
||||
<span>{t("ifc.importDialog.asMesh")}</span>
|
||||
</label>
|
||||
<div className="imp-note">{t("ifc.importDialog.asMeshHint")}</div>
|
||||
<label className="imp-radio">
|
||||
<input type="radio" name="ifc-mode" checked={mode === "elements"} onChange={() => setMode("elements")} />
|
||||
<span>{t("ifc.importDialog.asElements")}</span>
|
||||
</label>
|
||||
<div className="imp-note">{t("ifc.importDialog.asElementsHint")}</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<footer className="imp-foot">
|
||||
<button className="imp-btn" onClick={onCancel}>
|
||||
{t("export.cancel")}
|
||||
</button>
|
||||
<button className="imp-btn primary" onClick={() => onImport(mode)}>
|
||||
{t("ifc.importDialog.import")}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user