From c33706f225664c0035159f54d8865bb96ddf225d Mon Sep 17 00:00:00 2001 From: karim Date: Fri, 23 Oct 2026 14:56:38 +0200 Subject: [PATCH] Kollisionspruefung (truck-meshalgo): Menue Bearbeiten, rote Marker im Grundriss --- src/App.tsx | 18 ++++ src/analysis/clash.test.ts | 27 ++++++ src/analysis/clash.ts | 171 +++++++++++++++++++++++++++++++++++++ src/export/exportStep.ts | 2 +- src/i18n/de.ts | 4 + src/i18n/en.ts | 4 + src/native/appMenu.ts | 6 ++ 7 files changed, 231 insertions(+), 1 deletion(-) create mode 100644 src/analysis/clash.test.ts create mode 100644 src/analysis/clash.ts diff --git a/src/App.tsx b/src/App.tsx index 1187c0b7..33fd5d6e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -52,6 +52,7 @@ import { UnsavedChangesDialog } from "./ui/UnsavedChangesDialog"; import { Toast } from "./ui/Toast"; import { isTauriRuntime, PROJECT_TEMPLATE_EXT } from "./io/projectFile"; import { stepTextToImportedMeshes } from "./io/stepImport"; +import { applyClashMarkers, runClashCheck } from "./analysis/clash"; import { checkForUpdate } from "./update/checkForUpdate"; import type { PlanViewHandle } from "./plan/PlanView"; import type { DisplayResolver } from "./viewport/Viewport3D"; @@ -2383,6 +2384,23 @@ export default function App() { onExportStl, onExportStep, onImportStep: () => stepInputRef.current?.click(), + onClashCheck: () => { + const p0 = project; + runClashCheck(p0) + .then((clashes) => { + setProject((p) => applyClashMarkers(p, clashes, activeCategoryCode)); + window.alert( + clashes.length === 0 + ? t("clash.none") + : `${t("clash.found")}: ${clashes.length}\n` + + clashes + .slice(0, 20) + .map((c, k) => `K${k + 1}: ${c.a.kind} ↔ ${c.b.kind}${c.volume !== null ? ` · ${c.volume.toFixed(3)} m³` : ""}`) + .join("\n"), + ); + }) + .catch((err) => window.alert(`${t("clash.failed")}: ${err instanceof Error ? err.message : String(err)}`)); + }, onUndo: undo, onRedo: redo, onDeleteSelection: deleteSelection, diff --git a/src/analysis/clash.test.ts b/src/analysis/clash.test.ts new file mode 100644 index 00000000..cd820220 --- /dev/null +++ b/src/analysis/clash.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; +import { sampleProject } from "../model/sampleProject"; +import { applyClashMarkers, candidatePairs, clashItems, CLASH_MARKER_PREFIX } from "./clash"; +import type { ClashItem } from "./clash"; + +const it0 = (id: string, kind: ClashItem["kind"]): ClashItem => ({ id, kind, spec: { kind: "cuboid", min: [0, 0, 0], max: [1, 1, 1] } }); +const box = (x0: number, x1: number) => ({ min: [x0, 0, 0] as [number, number, number], max: [x1, 1, 1] as [number, number, number] }); + +describe("Kollisionspruefung", () => { + it("prueft nur Paare mit freiem Koerper und ueberlappenden Huellen", () => { + const items = [it0("w1", "wall"), it0("w2", "wall"), it0("s1", "solid"), it0("s2", "solid")]; + const boxes = [box(0, 2), box(1, 3), box(1.5, 2.5), box(5, 6)]; + expect(candidatePairs(items, boxes)).toEqual([[0, 2], [1, 2]]); + }); + it("Bauteile des Beispielprojekts werden erfasst", () => { + const items = clashItems(sampleProject); + expect(items.some((i) => i.kind === "wall")).toBe(true); + }); + it("Marker ersetzen alte Marker", () => { + const clash = { a: it0("a", "solid"), b: it0("b", "wall"), volume: 0.12, center: [1, 2, 0.5] as [number, number, number] }; + const p1 = applyClashMarkers(sampleProject, [clash, clash], "A"); + const n1 = p1.drawings2d.filter((d) => d.id.startsWith(CLASH_MARKER_PREFIX)).length; + expect(n1).toBe(4); + const p2 = applyClashMarkers(p1, [clash], "A"); + expect(p2.drawings2d.filter((d) => d.id.startsWith(CLASH_MARKER_PREFIX)).length).toBe(2); + }); +}); diff --git a/src/analysis/clash.ts b/src/analysis/clash.ts new file mode 100644 index 00000000..d5f71175 --- /dev/null +++ b/src/analysis/clash.ts @@ -0,0 +1,171 @@ +// Kollisionsprüfung (truck-meshalgo): findet Durchdringungen zwischen freien Körpern +// (Extrusionen/B-Rep-Grundkörper, importierte Meshes) und allen übrigen Bauteilen +// (Wandschichten, Decken, andere Körper). Wand↔Wand und Wand↔Decke werden NICHT geprüft — +// sie greifen konstruktiv ineinander (Gehrungen, Auflager) und wären reine Falschmeldungen. +// +// Ergebnis: je Kollision ein Paar + Durchdringungsvolumen + Mittelpunkt. `clashMarkers` +// macht daraus rote Markierungen (Kreis + Text, nicht druckend) auf dem passenden Geschoss. + +import type { Drawing2D, Project, Vec2 } from "../model/types"; +import { getFloor } from "../model/types"; +import { projectToModel3d } from "../plan/toWalls3d"; +import { extrudedSolidSpec } from "../plan/extrudedSolidSpec"; +import { wallSpec } from "../export/exportStep"; +import { solidClash, solidProps } from "../engine/truckSolid"; +import type { SolidSpec } from "../engine/truckSolid"; + +export type ClashKind = "wall" | "slab" | "solid" | "mesh"; + +export interface ClashItem { + /** Id des Ursprungs-Elements (Wand, Decke, Körper, Import). */ + id: string; + kind: ClashKind; + spec: SolidSpec; +} + +export interface Clash { + a: ClashItem; + b: ClashItem; + /** Durchdringungsvolumen (m³), `null` wenn nicht berechenbar. */ + volume: number | null; + /** Mittelpunkt der Durchdringungslinien (Welt-Meter). */ + center: [number, number, number]; +} + +/** Prefix der Marker-Ids (ein neuer Lauf ersetzt die alten Marker). */ +export const CLASH_MARKER_PREFIX = "clash-"; +/** Kleinere Überlappung gilt als Berührung (Rundung, bündige Flächen). */ +const MIN_VOLUME = 1e-5; + +const FREE: ReadonlySet = new Set(["solid", "mesh"]); + +/** Alle prüfbaren Bauteile des Projekts (reiner Kern, kein WASM). */ +export function clashItems(project: Project): ClashItem[] { + const out: ClashItem[] = []; + const model = projectToModel3d(project, { layeredWalls: true }); + for (const w of model.walls) { + const spec = wallSpec(w); + if (spec) out.push({ id: w.wallId, kind: "wall", spec }); + } + for (const s of model.slabs) { + if (s.outline.length < 3 || s.zTop - s.zBottom < 1e-4) continue; + out.push({ + id: s.ceilingId, + kind: "slab", + spec: { kind: "extrude", points: s.outline.flatMap((p) => [p[0], p[1]]), height: s.zTop - s.zBottom, z0: s.zBottom }, + }); + } + for (const solid of project.extrudedSolids ?? []) { + let baseZ = 0; + try { + baseZ = solid.levelId ? (getFloor(project, solid.levelId).baseElevation ?? 0) : 0; + } catch { + baseZ = 0; + } + const spec = extrudedSolidSpec(solid, baseZ); + if (spec) out.push({ id: solid.id, kind: "solid", spec }); + } + for (const m of project.context ?? []) { + if (m.type !== "importedMesh") continue; + if (m.indices.length >= 12) out.push({ id: m.id, kind: "mesh", spec: { kind: "mesh", positions: m.positions, indices: m.indices } }); + } + return out; +} + +type Box = { min: [number, number, number]; max: [number, number, number] }; + +const overlaps = (a: Box, b: Box, eps = 0.002): boolean => + a.min[0] < b.max[0] - eps && b.min[0] < a.max[0] - eps && + a.min[1] < b.max[1] - eps && b.min[1] < a.max[1] - eps && + a.min[2] < b.max[2] - eps && b.min[2] < a.max[2] - eps; + +/** Zu prüfende Paare: mindestens ein freier Körper, Hüllquader überlappen (reiner Kern). */ +export function candidatePairs(items: ClashItem[], boxes: Box[]): Array<[number, number]> { + const pairs: Array<[number, number]> = []; + for (let i = 0; i < items.length; i++) { + for (let j = i + 1; j < items.length; j++) { + if (!FREE.has(items[i].kind) && !FREE.has(items[j].kind)) continue; + if (items[i].id === items[j].id) continue; + if (overlaps(boxes[i], boxes[j])) pairs.push([i, j]); + } + } + return pairs; +} + +/** Führt die Kollisionsprüfung aus. `onProgress(done, total)` für lange Läufe. */ +export async function runClashCheck( + project: Project, + onProgress?: (done: number, total: number) => void, +): Promise { + const items = clashItems(project); + const boxes: Box[] = []; + const valid: boolean[] = []; + for (const it of items) { + try { + const p = await solidProps(it.spec, 0.02); + boxes.push({ min: p.min, max: p.max }); + valid.push(true); + } catch { + boxes.push({ min: [0, 0, 0], max: [0, 0, 0] }); + valid.push(false); + } + } + const pairs = candidatePairs(items, boxes).filter(([i, j]) => valid[i] && valid[j]); + const found = new Map(); + let done = 0; + for (const [i, j] of pairs) { + onProgress?.(done++, pairs.length); + let r; + try { + r = await solidClash(items[i].spec, items[j].spec, 0.01); + } catch { + continue; + } + if (!r.colliding || r.lines.length === 0) continue; + if (r.overlapVolume !== null && r.overlapVolume < MIN_VOLUME) continue; + const c: [number, number, number] = [0, 0, 0]; + for (const l of r.lines) { + c[0] += (l[0] + l[3]) / 2; + c[1] += (l[1] + l[4]) / 2; + c[2] += (l[2] + l[5]) / 2; + } + const n = r.lines.length; + const clash: Clash = { a: items[i], b: items[j], volume: r.overlapVolume, center: [c[0] / n, c[1] / n, c[2] / n] }; + // Mehrere Wandschichten derselben Wand → eine Kollision (grösstes Volumen). + const key = [items[i].id, items[j].id].sort().join("|"); + const prev = found.get(key); + if (!prev || (clash.volume ?? 0) > (prev.volume ?? 0)) found.set(key, clash); + } + onProgress?.(pairs.length, pairs.length); + return [...found.values()]; +} + +/** Geschoss, in dessen Höhenbereich `z` liegt (sonst das unterste). */ +export function floorAtElevation(project: Project, z: number): string | null { + const floors = project.drawingLevels + .filter((l) => l.kind === "floor") + .sort((a, b) => (a.baseElevation ?? 0) - (b.baseElevation ?? 0)); + let best: string | null = floors[0]?.id ?? null; + for (const f of floors) if ((f.baseElevation ?? 0) <= z + 1e-6) best = f.id; + return best; +} + +/** Ersetzt alte Kollisions-Marker durch neue (Kreis + Beschriftung, rot, nicht druckend). */ +export function applyClashMarkers(project: Project, clashes: Clash[], categoryCode: string): Project { + const keep = project.drawings2d.filter((d) => !d.id.startsWith(CLASH_MARKER_PREFIX)); + const markers: Drawing2D[] = []; + clashes.forEach((c, k) => { + const levelId = floorAtElevation(project, c.center[2]); + if (!levelId) return; + const at: Vec2 = { x: c.center[0], y: c.center[1] }; + const base = { type: "drawing2d" as const, levelId, categoryCode, color: "#e0242a", noPrint: true }; + markers.push({ ...base, id: `${CLASH_MARKER_PREFIX}${k}-c`, geom: { shape: "circle", center: at, r: 0.35 } }); + const vol = c.volume !== null ? ` ${c.volume.toFixed(3)} m³` : ""; + markers.push({ + ...base, + id: `${CLASH_MARKER_PREFIX}${k}-t`, + geom: { shape: "text", at: { x: at.x + 0.45, y: at.y + 0.1 }, text: `K${k + 1}${vol}`, height: 0.2, angle: 0 }, + }); + }); + return { ...project, drawings2d: [...keep, ...markers] }; +} diff --git a/src/export/exportStep.ts b/src/export/exportStep.ts index adba003c..3bfb4657 100644 --- a/src/export/exportStep.ts +++ b/src/export/exportStep.ts @@ -69,7 +69,7 @@ export function wallProfile( return { outer, holes: inner }; } -function wallSpec(w: RWall): SolidSpec | null { +export function wallSpec(w: RWall): SolidSpec | null { const dx = w.end[0] - w.start[0]; const dy = w.end[1] - w.start[1]; const len = Math.hypot(dx, dy); diff --git a/src/i18n/de.ts b/src/i18n/de.ts index efa0ecc3..67253491 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1742,6 +1742,10 @@ export const de = { "step.import.failed": "STEP-Import fehlgeschlagen", "step.import.done": "STEP importiert: {n} Körper", "menu.native.importStep": "STEP importieren …", + "menu.native.clashCheck": "Kollisionsprüfung …", + "clash.none": "Keine Kollisionen gefunden.", + "clash.found": "Kollisionen gefunden", + "clash.failed": "Kollisionsprüfung fehlgeschlagen", "about.title": "Über dossier", "about.version": "Version", "about.desc": "Open Source Computer Aided Architecture Design — 2D-Vektordesign sowie normgerechte Pläne aus einem semantischen Gebäudemodell.", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 5b9f707b..e55abc36 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1703,6 +1703,10 @@ export const en: Record = { "step.import.failed": "STEP import failed", "step.import.done": "STEP imported: {n} solids", "menu.native.importStep": "Import STEP …", + "menu.native.clashCheck": "Clash detection …", + "clash.none": "No clashes found.", + "clash.found": "Clashes found", + "clash.failed": "Clash detection failed", "file.export": "Export", "file.openFailed": "Could not read the project file.", diff --git a/src/native/appMenu.ts b/src/native/appMenu.ts index e938bd32..c2e9e5ac 100644 --- a/src/native/appMenu.ts +++ b/src/native/appMenu.ts @@ -34,6 +34,7 @@ export interface NativeAppMenuHandlers { onExportStl: () => void; onExportStep: () => void; onImportStep: () => void; + onClashCheck: () => void; onUndo: () => void; onRedo: () => void; @@ -246,6 +247,11 @@ export function useNativeAppMenu( text: t("menu.native.rotate"), action: () => handlersRef.current.onRotate(), }), + await PredefinedMenuItem.new({ item: "Separator" }), + await MenuItem.new({ + text: t("menu.native.clashCheck"), + action: () => handlersRef.current.onClashCheck(), + }), ], });