From 501ea13a7a13e52b3d6f4f1d2ee0bf5b71c3bc67 Mon Sep 17 00:00:00 2001 From: karim Date: Fri, 23 Oct 2026 13:40:46 +0200 Subject: [PATCH] truck-meshalgo: Kennwerte (Volumen, Oberflaeche, Schwerpunkt, Dichtheit) im Objekt-Panel, Kollisionspruefung (WASM) --- src-tauri/trucksolid/src/brep.rs | 111 ++++++++++++++++++++++++++++++ src-tauri/trucksolid/src/lib.rs | 42 +++++++++++ src/engine/truckBrep.wasm.test.ts | 13 ++++ src/engine/truckSolid.ts | 35 ++++++++++ src/i18n/de.ts | 4 ++ src/i18n/en.ts | 4 ++ src/panels/ObjectInfoPanel.tsx | 46 ++++++++++++- src/state/selectionInfo.ts | 5 ++ 8 files changed, 259 insertions(+), 1 deletion(-) diff --git a/src-tauri/trucksolid/src/brep.rs b/src-tauri/trucksolid/src/brep.rs index e4c6caae..68059e18 100644 --- a/src-tauri/trucksolid/src/brep.rs +++ b/src-tauri/trucksolid/src/brep.rs @@ -673,6 +673,99 @@ pub struct StepMesh { pub indices: Vec, } +fn polygon_of(m: &MeshOutput) -> PolygonMesh { + let positions: Vec = m + .positions + .chunks(3) + .map(|c| Point3::new(c[0] as f64, c[1] as f64, c[2] as f64)) + .collect(); + let tris: Vec<[usize; 3]> = m + .indices + .chunks(3) + .map(|t| [t[0] as usize, t[1] as usize, t[2] as usize]) + .collect(); + let mut poly = PolygonMesh::new( + StandardAttributes { positions, ..Default::default() }, + Faces::from_iter(&tris), + ); + // Eckpunkte verschweissen (tessellierte Flächen teilen keine Indizes). + poly.put_together_same_attrs(1e-6).remove_degenerate_faces().remove_unused_attrs(); + poly +} + +/// Kennwerte eines Körpers (aus dem tessellierten Mesh, Sehnenabweichung `tol`). +#[derive(Serialize, Debug)] +pub struct SolidProps { + /// Volumen in m³ (≥ 0; bei umgekehrter Orientierung der Betrag). + pub volume: f64, + /// Oberfläche in m². + pub area: f64, + /// Schwerpunkt [x, y, z] in m. + pub centroid: [f64; 3], + /// Mesh ist geschlossen und orientiert (wasserdicht). + pub closed: bool, + pub min: [f64; 3], + pub max: [f64; 3], +} + +pub fn solid_props_core(spec: &SolidSpec, tol: f64) -> Res { + use truck_meshalgo::analyzers::{CalcVolume, Topology}; + let m = solid_mesh_core(spec, tol)?; + let poly = polygon_of(&m); + let cog = poly.center_of_gravity(); + let vol = poly.volume(); + let mut area = 0.0; + for t in poly.faces().triangle_iter() { + let (a, b, c) = (poly.positions()[t[0].pos], poly.positions()[t[1].pos], poly.positions()[t[2].pos]); + area += (b - a).cross(c - a).magnitude() / 2.0; + } + let bb = poly.bounding_box(); + let (mn, mx) = (bb.min(), bb.max()); + Ok(SolidProps { + volume: vol.abs(), + area, + centroid: if cog.w.abs() > 1e-12 { + [cog.x / cog.w, cog.y / cog.w, cog.z / cog.w] + } else { + [0.0; 3] + }, + closed: matches!(poly.shell_condition(), ShellCondition::Closed), + min: [mn.x, mn.y, mn.z], + max: [mx.x, mx.y, mx.z], + }) +} + +/// Ergebnis einer Kollisionsprüfung zweier Körper. +#[derive(Serialize, Debug)] +pub struct ClashResult { + pub colliding: bool, + /// Durchdringungslinien (Segmente [x0,y0,z0,x1,y1,z1]), höchstens `max_lines`. + pub lines: Vec<[f64; 6]>, + /// Volumen der Durchdringung (m³), nur wenn beide Körper boolesch verschneidbar sind. + pub overlap_volume: Option, +} + +pub fn clash_core(a: &SolidSpec, b: &SolidSpec, tol: f64, max_lines: usize) -> Res { + use truck_meshalgo::analyzers::Collision; + let (pa, pb) = (polygon_of(&solid_mesh_core(a, tol)?), polygon_of(&solid_mesh_core(b, tol)?)); + let segs = pa.extract_interference(&pb); + let overlap_volume = if segs.is_empty() { + None + } else { + let inter = SolidSpec::Boolean { op: BoolKind::Intersection, a: Box::new(a.clone()), b: Box::new(b.clone()) }; + solid_props_core(&inter, tol).ok().map(|p| p.volume) + }; + Ok(ClashResult { + colliding: !segs.is_empty(), + lines: segs + .iter() + .take(max_lines) + .map(|(p, q)| [p.x, p.y, p.z, q.x, q.y, q.z]) + .collect(), + overlap_volume, + }) +} + /// Längeneinheit einer STEP-Datei in Metern (`LENGTH_UNIT`: SI mit Präfix oder Zoll/Fuss). pub fn step_length_unit_in_m(text: &str) -> f64 { for line in text.lines().chain(text.split(';')) { @@ -1043,4 +1136,22 @@ mod dbg_step { let max = xs.iter().cloned().fold(f32::MIN, f32::max); assert!((max - 2.0).abs() < 1e-3, "Import zurück in Meter, war {max}"); } + + #[test] + fn props_and_clash() { + let b = SolidSpec::Cuboid { min: [0.0; 3], max: [2.0, 1.0, 3.0] }; + let p = solid_props_core(&b, 0.01).unwrap(); + assert!((p.volume - 6.0).abs() < 1e-9 && (p.area - 22.0).abs() < 1e-9, "{p:?}"); + assert!((p.centroid[0] - 1.0).abs() < 1e-9 && (p.centroid[2] - 1.5).abs() < 1e-9); + assert!(p.closed); + let sph = SolidSpec::Sphere { center: [0.0; 3], r: 1.0 }; + let v = solid_props_core(&sph, 0.002).unwrap().volume; + assert!((v - 4.0 / 3.0 * PI).abs() / v < 0.01, "Kugel {v}"); + let b2 = SolidSpec::Cuboid { min: [1.0, 0.5, 1.0], max: [3.0, 2.0, 2.0] }; + let c = clash_core(&b, &b2, 0.01, 100).unwrap(); + assert!(c.colliding && !c.lines.is_empty()); + assert!((c.overlap_volume.unwrap() - 0.5).abs() < 1e-6, "{:?}", c.overlap_volume); + let far = SolidSpec::Cuboid { min: [10.0; 3], max: [11.0; 3] }; + assert!(!clash_core(&b, &far, 0.01, 100).unwrap().colliding); + } } diff --git a/src-tauri/trucksolid/src/lib.rs b/src-tauri/trucksolid/src/lib.rs index 2a19fb9a..80cffd16 100644 --- a/src-tauri/trucksolid/src/lib.rs +++ b/src-tauri/trucksolid/src/lib.rs @@ -359,6 +359,48 @@ mod web { serde_json::to_string(&mesh).map_err(|e| JsError::new(&e.to_string())) } + /// Volumen, Oberfläche, Schwerpunkt, Hülle und Dichtheit eines Körpers. + /// Input JSON: `{ "spec": {…}, "tol": 0.005 }` + #[wasm_bindgen] + pub fn solid_props(input_json: &str) -> std::result::Result { + #[derive(serde::Deserialize)] + struct In { + spec: brep::SolidSpec, + #[serde(default = "tol")] + tol: f64, + } + fn tol() -> f64 { + 0.005 + } + let i: In = serde_json::from_str(input_json).map_err(|e| JsError::new(&e.to_string()))?; + let p = brep::solid_props_core(&i.spec, i.tol).map_err(|e| JsError::new(&e))?; + serde_json::to_string(&p).map_err(|e| JsError::new(&e.to_string())) + } + + /// Kollisionsprüfung zweier Körper (Durchdringungslinien + Überlappungsvolumen). + /// Input JSON: `{ "a": {…}, "b": {…}, "tol": 0.01, "maxLines": 200 }` + #[wasm_bindgen] + pub fn solid_clash(input_json: &str) -> std::result::Result { + #[derive(serde::Deserialize)] + struct In { + a: brep::SolidSpec, + b: brep::SolidSpec, + #[serde(default = "tol")] + tol: f64, + #[serde(default = "max_lines", rename = "maxLines")] + max_lines: usize, + } + fn tol() -> f64 { + 0.01 + } + fn max_lines() -> usize { + 200 + } + let i: In = serde_json::from_str(input_json).map_err(|e| JsError::new(&e.to_string()))?; + let r = brep::clash_core(&i.a, &i.b, i.tol, i.max_lines).map_err(|e| JsError::new(&e))?; + serde_json::to_string(&r).map_err(|e| JsError::new(&e.to_string())) + } + /// B-Rep-Körper aus einer Spezifikation (s. `brep::SolidSpec`) → Mesh. /// Input JSON: `{ "spec": {kind:"extrude",…}, "tol": 0.01 }` #[wasm_bindgen] diff --git a/src/engine/truckBrep.wasm.test.ts b/src/engine/truckBrep.wasm.test.ts index 9f876a34..ae9a3727 100644 --- a/src/engine/truckBrep.wasm.test.ts +++ b/src/engine/truckBrep.wasm.test.ts @@ -76,4 +76,17 @@ describe("trucksolid-WASM", () => { expect(vols[0]).toBeCloseTo((5 * 2.6 - 1.2 * 1.2) * 0.3, 1); // Wand expect(vols[1]).toBeCloseTo(Math.PI * 2, 1); // Zylinder }); + + it("Kennwerte + Kollision (truck-meshalgo)", () => { + const cub = (x0: number, y0: number, z0: number, x1: number, y1: number, z1: number) => ({ kind: "cuboid", min: [x0, y0, z0], max: [x1, y1, z1] }); + const p = JSON.parse(mod.solid_props(JSON.stringify({ spec: cub(0, 0, 0, 2, 1, 3) }))); + expect(p.volume).toBeCloseTo(6, 6); + expect(p.area).toBeCloseTo(22, 6); + expect(p.closed).toBe(true); + const c = JSON.parse(mod.solid_clash(JSON.stringify({ a: cub(0, 0, 0, 2, 1, 3), b: cub(1, 0.5, 1, 3, 2, 2) }))); + expect(c.colliding).toBe(true); + expect(c.overlap_volume).toBeCloseTo(0.5, 5); + const far = JSON.parse(mod.solid_clash(JSON.stringify({ a: cub(0, 0, 0, 1, 1, 1), b: cub(5, 5, 5, 6, 6, 6) }))); + expect(far.colliding).toBe(false); + }); }); diff --git a/src/engine/truckSolid.ts b/src/engine/truckSolid.ts index 3db56282..93029810 100644 --- a/src/engine/truckSolid.ts +++ b/src/engine/truckSolid.ts @@ -120,6 +120,41 @@ export async function buildSolidMesh(spec: SolidSpec, tol = 0.01): Promise { + const m = await getModule(); + return JSON.parse(m.solid_props(JSON.stringify({ spec, tol }))) as SolidProps; +} + +export interface ClashResult { + colliding: boolean; + /** Durchdringungslinien [x0,y0,z0,x1,y1,z1]. */ + lines: Array<[number, number, number, number, number, number]>; + /** Volumen der Durchdringung (m³), falls berechenbar. */ + overlapVolume: number | null; +} + +/** Kollisionsprüfung zweier Körper (truck-meshalgo). */ +export async function solidClash(a: SolidSpec, b: SolidSpec, tol = 0.01): Promise { + const m = await getModule(); + const r = JSON.parse(m.solid_clash(JSON.stringify({ a, b, tol }))) as { + colliding: boolean; + lines: ClashResult["lines"]; + overlap_volume: number | null; + }; + return { colliding: r.colliding, lines: r.lines, overlapVolume: r.overlap_volume }; +} + /** Exportiert Körper als STEP-Text (ISO 10303-42 B-Rep). */ export async function exportStepSolids( solids: SolidSpec[], diff --git a/src/i18n/de.ts b/src/i18n/de.ts index c42ab4a5..efa0ecc3 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -712,6 +712,10 @@ export const de = { "objinfo.extrudedSolid.cornerRadius": "Eckenradius", "objinfo.extrudedSolid.chamfer": "Fase", "objinfo.extrudedSolid.brep": "B-Rep-Körper", + "objinfo.extrudedSolid.volume": "Volumen", + "objinfo.extrudedSolid.surface": "Oberfläche", + "objinfo.extrudedSolid.centroid": "Schwerpunkt", + "objinfo.extrudedSolid.notClosed": "Körper nicht wasserdicht", "objinfo.extrudedSolid.area": "Grundfläche", "objinfo.extrudedSolid.floor": "Geschoss", "objinfo.rotate": "Drehen", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 30ac347c..5b9f707b 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -708,6 +708,10 @@ export const en: Record = { "objinfo.extrudedSolid.cornerRadius": "Corner radius", "objinfo.extrudedSolid.chamfer": "Chamfer", "objinfo.extrudedSolid.brep": "B-rep solid", + "objinfo.extrudedSolid.volume": "Volume", + "objinfo.extrudedSolid.surface": "Surface", + "objinfo.extrudedSolid.centroid": "Centroid", + "objinfo.extrudedSolid.notClosed": "Solid is not watertight", "objinfo.extrudedSolid.area": "Footprint area", "objinfo.extrudedSolid.floor": "Floor", "objinfo.rotate": "Rotate", diff --git a/src/panels/ObjectInfoPanel.tsx b/src/panels/ObjectInfoPanel.tsx index 3cbea4c1..e70a73ba 100644 --- a/src/panels/ObjectInfoPanel.tsx +++ b/src/panels/ObjectInfoPanel.tsx @@ -14,7 +14,9 @@ // Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). Alle sichtbaren // Texte über t(...). -import { useState } from "react"; +import { solidProps } from "../engine/truckSolid"; +import type { SolidProps, SolidSpec } from "../engine/truckSolid"; +import { useEffect, useState } from "react"; // Anzeige-Fallbacks für die Öffnungs-Linien-Übersteuerung (LineStyleRow) — // dieselben Werte wie POCHE_STROKE/SYMBOL_HAIRLINE_MM in plan/generatePlan.ts // (reine UI-Default-Anzeige, kein Re-Export nötig). @@ -637,6 +639,46 @@ export function DetailRefSection({ ); } +/** Volumen/Oberfläche/Schwerpunkt aus truck (asynchron, aus dem tessellierten B-Rep). */ +function SolidPropsRows({ spec }: { spec: SolidSpec | null }) { + const [props, setProps] = useState(null); + const key = JSON.stringify(spec); + useEffect(() => { + let alive = true; + setProps(null); + if (!spec) return; + solidProps(spec).then( + (p) => alive && setProps(p), + () => alive && setProps(null), + ); + return () => { + alive = false; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + if (!props) return null; + const f = (v: number, d = 2) => v.toLocaleString(undefined, { minimumFractionDigits: d, maximumFractionDigits: d }); + return ( + <> +
+ {t("objinfo.extrudedSolid.volume")} + {f(props.volume)} m³ +
+
+ {t("objinfo.extrudedSolid.surface")} + {f(props.area)} m² +
+
+ {t("objinfo.extrudedSolid.centroid")} + + {f(props.centroid[0])} / {f(props.centroid[1])} / {f(props.centroid[2])} + +
+ {!props.closed &&
{t("objinfo.extrudedSolid.notClosed")}
} + + ); +} + // ── Extrusions-Attribut-Abschnitt (truck-Integration) ─────────────────────── // Höhe editierbar (löst Re-Extrusion aus); Grundfläche + Geschoss read-only. export function ExtrudedSolidSection({ @@ -668,6 +710,8 @@ export function ExtrudedSolidSection({ /> + + {solid.brepLabel && (
{t("objinfo.extrudedSolid.brep")} diff --git a/src/state/selectionInfo.ts b/src/state/selectionInfo.ts index e9ed3110..6ff86126 100644 --- a/src/state/selectionInfo.ts +++ b/src/state/selectionInfo.ts @@ -10,6 +10,8 @@ // // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). +import { extrudedSolidSpec } from "../plan/extrudedSolidSpec"; +import type { SolidSpec } from "../engine/truckSolid"; import { ceilingThickness, flattenCategories, @@ -321,6 +323,8 @@ export interface ExtrudedSolidInfo { brepLabel?: string; /** Grundfläche des Profils (m²). */ area: number; + /** B-Rep-Beschreibung (Weltkoordinaten) für Kennwerte — `null`, wenn truck keine hat. */ + spec: SolidSpec | null; /** Geschoss, dessen `baseElevation` die UK des Körpers bestimmt. */ floorId: string; floorName: string; @@ -1052,6 +1056,7 @@ function extrudedSolidSelection(project: Project, s: ExtrudedSolid): Selection { chamfer: s.chamfer ?? 0, ...(s.brep ? { brepLabel: s.brep.label ?? "B-Rep" } : {}), area: polygonArea(s.points), + spec: extrudedSolidSpec(s, floor?.baseElevation ?? 0), floorId: s.levelId, floorName: floor?.name ?? s.levelId, };