Merge remote-tracking branch 'origin/master' into worktree-agent-a0b8c8c0c6a96ff24

This commit is contained in:
Claude committed 2026-10-29 17:44:47 +00:00
commit 27c187de01
19 files changed
+688 -591

No files matched your search

+230
View File
@@ -0,0 +1,230 @@
//! Umriss-Linien der 3D-Auswahl (früher `selectionHighlightLines` in `plan/toWalls3d.ts`): je
//! gewähltes Bauteil die Kanten seiner Hülle als Linienliste `[x, y, z, r, g, b] × 2` (Welt-Meter,
//! y = Höhe), die der 3D-Viewport ohne Tiefentest obenauf zeichnet. Wände/Öffnungen als Quader,
//! Decken/Treppen als Prisma, Dächer als Flächen-/Giebel-Umrisse, Kontext-Meshes als Hüllquader.
//! Rechnung und Reihenfolge wie die TS-Fassung (f32 wie `Float32Array`).
use crate::jsmath::hypot2;
use crate::model::{ContextObject, Project};
use crate::model3d::{emit_slabs, emit_walls, pick_openings, pick_stairs};
use std::collections::HashSet;
const EPS: f64 = 1e-4;
type V3 = [f64; 3];
/// Gewählte ids je Art und Linienfarbe.
#[derive(serde::Deserialize, Default)]
#[serde(default)]
pub struct Args {
pub walls: Vec<String>,
pub ceilings: Vec<String>,
pub openings: Vec<String>,
pub stairs: Vec<String>,
pub roofs: Vec<String>,
pub context: Vec<String>,
pub rgb: [f64; 3],
}
const BOX_EDGES: [(usize, usize); 12] = [(0, 1), (0, 2), (0, 4), (1, 3), (1, 5), (2, 3), (2, 6), (3, 7), (4, 5), (4, 6), (5, 7), (6, 7)];
struct Out {
v: Vec<f32>,
rgb: [f64; 3],
}
impl Out {
fn edge(&mut self, a: V3, b: V3) {
let c = self.rgb;
for q in [a, b] {
self.v.extend([q[0], q[1], q[2], c[0], c[1], c[2]].map(|x| x as f32));
}
}
/// Quader um die Achse `start → end` (Dicke quer, Höhe ab `base`).
fn box_edges(&mut self, start: [f64; 2], end: [f64; 2], thickness: f64, height: f64, base: f64) {
let ax = end[0] - start[0];
let az = end[1] - start[1];
let len = hypot2(ax, az);
if len < EPS || height <= EPS || thickness <= EPS {
return;
}
let axis = [ax / len, 0.0, az / len];
let normal = [az / len, 0.0, -ax / len];
let half_len = len / 2.0;
let half_height = height / 2.0;
let half_thick = thickness / 2.0;
let center = [(start[0] + end[0]) / 2.0, base + height / 2.0, (start[1] + end[1]) / 2.0];
let mut corners = [[0.0; 3]; 8];
for (i, c) in corners.iter_mut().enumerate() {
let s_l = if i & 1 != 0 { 1.0 } else { -1.0 };
let s_h = if i & 2 != 0 { 1.0 } else { -1.0 };
let s_t = if i & 4 != 0 { 1.0 } else { -1.0 };
*c = [
center[0] + s_l * half_len * axis[0] + s_t * half_thick * normal[0],
center[1] + s_h * half_height,
center[2] + s_l * half_len * axis[2] + s_t * half_thick * normal[2],
];
}
for (i, j) in BOX_EDGES {
self.edge(corners[i], corners[j]);
}
}
/// Prisma über dem Grundriss `outline` von `z_bottom` bis `z_top`.
fn prism_edges(&mut self, outline: &[[f64; 2]], z_bottom: f64, z_top: f64) {
let n = outline.len();
if n < 3 || z_top - z_bottom <= EPS {
return;
}
let bottom = |i: usize| [outline[i][0], z_bottom, outline[i][1]];
let top = |i: usize| [outline[i][0], z_top, outline[i][1]];
let mut j = n - 1;
for i in 0..n {
self.edge(bottom(j), bottom(i));
self.edge(top(j), top(i));
j = i;
}
for i in 0..n {
self.edge(bottom(i), top(i));
}
}
}
fn set(ids: &[String]) -> HashSet<&str> {
ids.iter().map(String::as_str).collect()
}
/// Linienliste der Hervorhebung (leer, wenn nichts gewählt ist).
pub fn selection_highlight_lines(p: &Project, a: &Args) -> Result<Vec<f32>, String> {
let mut out = Out { v: Vec::new(), rgb: a.rgb };
let (walls, ceilings, openings, stairs, roofs, context) = (set(&a.walls), set(&a.ceilings), set(&a.openings), set(&a.stairs), set(&a.roofs), set(&a.context));
if !walls.is_empty() {
for w in emit_walls(p, true)? {
if walls.contains(w.wall_id.as_str()) {
out.box_edges(w.start, w.end, w.thickness, w.height, w.base_elevation);
}
}
}
if !openings.is_empty() {
for o in pick_openings(p) {
if openings.contains(o.opening_id.as_str()) {
out.box_edges(o.start, o.end, o.thickness, o.height, o.base_elevation);
}
}
}
if !ceilings.is_empty() {
for s in emit_slabs(p) {
if ceilings.contains(s.ceiling_id.as_str()) {
out.prism_edges(&s.outline, s.z_bottom, s.z_top);
}
}
}
if !stairs.is_empty() {
for st in pick_stairs(p) {
if stairs.contains(st.stair_id.as_str()) {
out.prism_edges(&st.outline, st.z_bottom, st.z_top);
}
}
}
if !roofs.is_empty() {
for roof in p.roofs.as_deref().unwrap_or(&[]) {
if !roofs.contains(roof.id.as_str()) {
continue;
}
let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof));
for pts in g.planes.iter().chain(g.gables.iter()) {
let m = pts.len();
if m == 0 {
continue;
}
let mut j = m - 1;
for i in 0..m {
let (q, r) = (pts[j], pts[i]);
out.edge([q[0], q[2], q[1]], [r[0], r[2], r[1]]);
j = i;
}
}
}
}
if !context.is_empty() {
for obj in p.context.as_deref().unwrap_or(&[]) {
let (pos, id) = match obj {
ContextObject::TerrainMesh(m) => (&m.positions, &m.id),
ContextObject::ImportedMesh(m) => (&m.positions, &m.id),
_ => continue,
};
if !context.contains(id.as_str()) {
continue;
}
let (mut min_x, mut max_x, mut min_y, mut max_y, mut min_h, mut max_h) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
for c in pos.chunks_exact(3) {
let (x, y, h) = (c[0], c[1], c[2]);
if x < min_x {
min_x = x;
}
if x > max_x {
max_x = x;
}
if y < min_y {
min_y = y;
}
if y > max_y {
max_y = y;
}
if h < min_h {
min_h = h;
}
if h > max_h {
max_h = h;
}
}
if !min_x.is_finite() {
continue;
}
let mut corners = [[0.0; 3]; 8];
for (i, c) in corners.iter_mut().enumerate() {
*c = [if i & 1 != 0 { max_x } else { min_x }, if i & 2 != 0 { max_h } else { min_h }, if i & 4 != 0 { max_y } else { min_y }];
}
for (i, j) in BOX_EDGES {
out.edge(corners[i], corners[j]);
}
}
}
Ok(out.v)
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Project {
serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap()
}
fn lines(p: &Project, a: serde_json::Value) -> Vec<f32> {
selection_highlight_lines(p, &serde_json::from_value(a).unwrap()).unwrap()
}
#[test]
fn leer_ohne_auswahl() {
let p = sample();
assert!(lines(&p, serde_json::json!({})).is_empty());
assert!(lines(&p, serde_json::json!({"walls": ["gibt-es-nicht"]})).is_empty());
}
#[test]
fn wand_zwoelf_kanten_decke_prisma() {
let p = sample();
let w = emit_walls(&p, true).unwrap();
let id = &w[0].wall_id;
let n = w.iter().filter(|x| &x.wall_id == id).count();
let l = lines(&p, serde_json::json!({"walls": [id], "rgb": [1.0, 0.5, 0.0]}));
assert_eq!(l.len(), n * 12 * 12);
assert_eq!(&l[3..6], &[1.0, 0.5, 0.0]);
let s = &emit_slabs(&p)[0];
let l = lines(&p, serde_json::json!({"ceilings": [s.ceiling_id]}));
assert_eq!(l.len() % (3 * 12) , 0);
assert!(!l.is_empty());
}
}
+2
View File
@@ -104,6 +104,8 @@ pub mod import_ifc;
pub mod cmd_paste;
pub mod cmd_split;
pub mod snap_model;
pub mod solid_specs;
pub mod highlight3d;
#[cfg(feature = "web")]
mod web;
+29 -17
View File
@@ -1423,23 +1423,8 @@ pub struct PickGeometry {
pub drawings: Vec<PickDrawingSeg>,
}
/// Geometrie für den 3D-Raycast (`pickGeometry`).
pub fn pick_geometry(p: &Project) -> Result<PickGeometry, String> {
// Dächer: Flächen + Giebel als Welt-Dreiecke (Fächer ab Punkt 0), Modell [x, y, h] → Welt [x, h, y].
let mut roofs = Vec::new();
for roof in p.roofs.as_deref().unwrap_or(&[]) {
let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof));
let to_world = |q: &V3| -> V3 { [q[0], q[2], q[1]] };
let mut tris: Vec<Tri> = Vec::new();
for poly in g.planes.iter().chain(g.gables.iter()) {
for i in 1..poly.len().saturating_sub(1) {
tris.push([to_world(&poly[0]), to_world(&poly[i]), to_world(&poly[i + 1])]);
}
}
if !tris.is_empty() {
roofs.push(PickRoof { tris, roof_id: roof.id.clone() });
}
}
/// Öffnungen als Quader (Laibung zu Laibung, Wanddicke, Brüstung bis Sturz) für Pick und Hervorhebung.
pub fn pick_openings(p: &Project) -> Vec<PickBox> {
let mut openings = Vec::new();
for o in p.openings.as_deref().unwrap_or(&[]) {
let Some(wall) = p.walls.iter().find(|w| w.id == o.host_wall_id) else { continue };
@@ -1461,6 +1446,11 @@ pub fn pick_geometry(p: &Project) -> Result<PickGeometry, String> {
opening_id: o.id.clone(),
});
}
openings
}
/// Treppen als achsparallele Hülle (UK bis OK) für Pick und Hervorhebung.
pub fn pick_stairs(p: &Project) -> Vec<PickStair> {
let mut stairs = Vec::new();
for st in p.stairs.as_deref().unwrap_or(&[]) {
let (z_bottom, z_top) = p.stair_vertical_extent(st);
@@ -1473,6 +1463,28 @@ pub fn pick_geometry(p: &Project) -> Result<PickGeometry, String> {
let (min_x, min_y, max_x, max_y) = if b.len() >= 4 { (b[0], b[1], b[2], b[3]) } else { (0.0, 0.0, 0.0, 0.0) };
stairs.push(PickStair { outline: [[min_x, min_y], [max_x, min_y], [max_x, max_y], [min_x, max_y]], z_bottom, z_top, stair_id: st.id.clone() });
}
stairs
}
/// Geometrie für den 3D-Raycast (`pickGeometry`).
pub fn pick_geometry(p: &Project) -> Result<PickGeometry, String> {
// Dächer: Flächen + Giebel als Welt-Dreiecke (Fächer ab Punkt 0), Modell [x, y, h] → Welt [x, h, y].
let mut roofs = Vec::new();
for roof in p.roofs.as_deref().unwrap_or(&[]) {
let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof));
let to_world = |q: &V3| -> V3 { [q[0], q[2], q[1]] };
let mut tris: Vec<Tri> = Vec::new();
for poly in g.planes.iter().chain(g.gables.iter()) {
for i in 1..poly.len().saturating_sub(1) {
tris.push([to_world(&poly[0]), to_world(&poly[i]), to_world(&poly[i + 1])]);
}
}
if !tris.is_empty() {
roofs.push(PickRoof { tris, roof_id: roof.id.clone() });
}
}
let openings = pick_openings(p);
let stairs = pick_stairs(p);
// Kontext-Meshes: rohe Welt-Dreiecke, Modell (x, y, z) → Welt (x, z, −y).
let mut context_meshes = Vec::new();
for obj in p.context.as_deref().unwrap_or(&[]) {
+5 -5
View File
@@ -159,15 +159,15 @@ pub fn site_and_shadow(p: &Project, floor: &str, when_ms: Option<f64>) -> (Vec<(
const EPS: f64 = 1e-7;
/// Ein Abzugskörper als Prisma (Welt-Höhen).
struct VoidPrism {
pts: Vec<Vec2>,
z0: f64,
z1: f64,
pub(crate) struct VoidPrism {
pub(crate) pts: Vec<Vec2>,
pub(crate) z0: f64,
pub(crate) z1: f64,
}
/// Abzugskörper des Projekts (`voidPrisms`): `operation: "subtract"`, ohne B-Rep, ohne Verjüngung,
/// gültiges Profil und Höhe.
fn void_prisms(p: &Project) -> Vec<VoidPrism> {
pub(crate) fn void_prisms(p: &Project) -> Vec<VoidPrism> {
let mut out = Vec::new();
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
let is_void = s.operation.as_deref() == Some("subtract") && s.brep.is_none() && s.taper.unwrap_or(0.0) < 1e-6 && s.points.len() >= 3 && s.height > 0.0;
+65
View File
@@ -158,3 +158,68 @@ pub fn resolve_stroke_weight(override_: Option<f64>, source: Option<AttributeSou
}
fallback
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
const SAMPLE: &str = include_str!("../../tests/fixtures/sample_project.json");
/// Bauteil mit Vorder-/Hintergrund und Kategorie mit Farbe, Schraffur, Strichstärke (früher `shared.resolve.test.ts`).
fn comp_cat() -> (Component, LayerCategory) {
let p: Project = serde_json::from_str(SAMPLE).unwrap();
let mut comp = p.components.first().cloned().expect("Bauteil");
comp.foreground = Some("#112233".into());
comp.background = Some("#445566".into());
let mut cat = p.flat_categories().first().map(|c| (*c).clone()).expect("Kategorie");
cat.color = "#abcdef".into();
cat.hatch = Some("sia-wall".into());
cat.lw = 0.5;
(comp, cat)
}
#[test]
fn vorder_hintergrund_default_nach_bauteil() {
let (comp, cat) = comp_cat();
for src in [None, Some(AttributeSource::Object)] {
assert_eq!(resolve_foreground(&comp, None, Some(&cat), src), Some("#112233"));
assert_eq!(resolve_background(&comp, None, Some(&cat), src), Some("#445566"));
}
assert_eq!(resolve_foreground(&comp, None, Some(&cat), Some(AttributeSource::Layer)), Some("#abcdef"));
assert_eq!(resolve_background(&comp, None, Some(&cat), Some(AttributeSource::Layer)), Some("#abcdef"));
assert_eq!(resolve_foreground(&comp, Some("#ff00ff"), Some(&cat), Some(AttributeSource::Layer)), Some("#ff00ff"));
assert_eq!(resolve_foreground(&comp, Some("#ff00ff"), Some(&cat), None), Some("#ff00ff"));
}
#[test]
fn schraffur_und_strichstaerke_nach_ebene() {
let (_, cat) = comp_cat();
assert_eq!(resolve_hatch_id(None, None, Some(&cat), Some("eigene")), Some("eigene"));
assert_eq!(resolve_hatch_id(None, Some(AttributeSource::Layer), Some(&cat), Some("eigene")), Some("sia-wall"));
assert_eq!(resolve_stroke_weight(None, None, Some(&cat), 0.13), 0.13);
assert_eq!(resolve_stroke_weight(None, Some(AttributeSource::Layer), Some(&cat), 0.13), 0.5);
}
#[test]
fn motiv_und_verlauf_unveraendert_durchgereicht() {
let mut v: serde_json::Value = serde_json::from_str(SAMPLE).unwrap();
v["hatches"] = json!([
{"id": "h-custom", "name": "Motiv", "pattern": "custom", "scale": 1, "angle": 0, "color": "#000",
"motif": {"points": [{"x": 0, "y": 0}, {"x": 2, "y": 1}, {"x": 4, "y": 0}], "length": 4}},
{"id": "h-grad", "name": "Verlauf", "kind": "gradient", "pattern": "diagonal", "scale": 1, "angle": 0, "color": "#000",
"gradient": {"color1": "#ffffff", "color2": "#000000", "angle": 45, "type": "radial"}},
{"id": "h-diag", "name": "Diagonal", "pattern": "diagonal", "scale": 1, "angle": 30, "color": "#000", "relativeToWall": true}
]);
let p: Project = serde_json::from_value(v).unwrap();
let m = resolve_hatch(&p, "h-custom", None, None, None).unwrap();
assert_eq!(serde_json::to_value(&m.motif).unwrap()["length"], json!(4.0));
let g = resolve_hatch(&p, "h-grad", None, None, None).unwrap();
assert!(g.gradient.is_some() && g.kind.is_some());
let d = resolve_hatch(&p, "h-diag", Some(90.0), None, None).unwrap();
assert!(d.motif.is_none() && d.gradient.is_none());
assert_eq!(d.angle, -60.0);
assert_eq!(resolve_hatch(&p, "h-diag", None, None, None).unwrap().angle, 30.0);
assert_eq!(d.color, HATCH_INK);
}
}
+17 -1
View File
@@ -40,7 +40,18 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
("scheduleCsv", 1) => Ok(export_schedule::export_schedule_csv(p, text, args[0] != 0.0)),
("pickGeometry", _) => json(&model3d::pick_geometry(p)?),
("modelJson", _) => crate::model::to_value_typed_only(p).map(|v| v.to_string()).map_err(|e| e.to_string()),
("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?),
// Mit Abzugskörpern (`args[3]` ≠ 0) zusätzlich `voidCuts`: die getroffenen Wände/Decken als
// truck-Spezifikationen (`solid_specs.rs`).
("model3dParts", n) if n >= 3 => {
let parts = model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?;
if args.get(3).is_some_and(|v| *v != 0.0) {
let cuts = crate::solid_specs::void_cuts(p, &parts.walls, &parts.slabs);
let mut v = serde_json::to_value(&parts).map_err(|e| e.to_string())?;
v["voidCuts"] = serde_json::to_value(&cuts).map_err(|e| e.to_string())?;
return Ok(v.to_string());
}
json(&parts)
}
// Gruppen ([K4] S3, `groups.rs`): `text` = Gruppen-id bzw. JSON der Argumente.
("groupMembership", _) => json(&crate::groups::transitive_membership(p, text)),
("containingGroup", _) => {
@@ -186,6 +197,11 @@ pub fn run_bin(p: &Project, name: &str, args: &[f64], text: &str) -> Result<Vec<
let prims = crate::plan_buf::View::parse(&bytes).and_then(|v| v.prims()).ok_or("planUnderlay: Plan-Puffer unlesbar")?;
Ok(crate::plan::underlay::underlay_buf(&crate::plan::underlay::underlay_primitives(line, sign, prims, min_y)))
}
// Umriss-Linien der 3D-Auswahl (`highlight3d.rs`): `text` = JSON der ids je Art + `rgb`; Antwort f32-LE.
("selectionHighlight", _) => {
let a: crate::highlight3d::Args = serde_json::from_str(text).map_err(|e| format!("selectionHighlight: {e}"))?;
Ok(crate::highlight3d::selection_highlight_lines(p, &a)?.iter().flat_map(|v| v.to_le_bytes()).collect())
}
("sectionPlan", _) => crate::plan::section::section_plan_buf(p, args, text),
("elevationPlan", _) => crate::plan::elevation::elevation_plan_buf(p, args, text),
_ => Err(format!("Unbekannte Abfrage: {name}")),
+252
View File
@@ -0,0 +1,252 @@
//! B-Rep-Spezifikationen der Bauteile für truck (früher `plan/wallSpec.ts`, `plan/voids.ts` 3D-Teil,
//! `plan/toWalls3d/voids3d.ts`): Wandprofil mit Öffnungen, Wand als `extrudePlane`, und die
//! Abzugskörper im 3D — jede Wand und Decke, die ein Abzugskörper trifft, als verkettete Differenz.
//! Die Spezifikationen gehen als JSON an truck (`SolidSpec` in `engine/truckSolid.ts`); Rechnung und
//! Reihenfolge wie in TS (bitgleich, `jsnum`/`jsmath`).
use crate::jsmath::hypot2;
use crate::jsnum::{max, min};
use crate::model::Vec2;
use crate::model3d::{RHole, RSlab, RWall};
use crate::plan::extras::{void_prisms, VoidPrism};
use crate::model::Project;
use serde_json::{json, Value};
const EPS: f64 = 1e-6;
/// Schicht/Öffnung so dünn, dass sie als nicht vorhanden gilt.
const MIN_THICKNESS: f64 = 1e-4;
/// Wandprofil (u = Achse, v = Höhe über Wandfuss) mit Öffnungen: Löcher, die ganz im Profil liegen;
/// Öffnungen am Wandfuss (Türen) als Kerben im Aussenring. Öffnungen am Wandkopf werden um 1 mm
/// gekappt (ein Loch darf den Rand nicht berühren). Ergebnis: (Aussenring, Löcher), flach u,v.
pub fn wall_profile(length: f64, height: f64, holes: &[RHole], base_elevation: f64) -> (Vec<f64>, Vec<Vec<f64>>) {
let mut inner: Vec<Vec<f64>> = Vec::new();
let mut notches: Vec<[f64; 3]> = Vec::new();
let cut = 1e-3;
for h in holes {
let u0 = max(0.0, min(length, h.from));
let u1 = max(0.0, min(length, h.to));
if u1 - u0 < MIN_THICKNESS {
continue;
}
let v0 = h.z_bottom - base_elevation;
let v1 = min(height - cut, h.z_top - base_elevation);
if v1 - max(v0, 0.0) < MIN_THICKNESS {
continue;
}
if v0 <= cut {
notches.push([u0, u1, v1]);
} else {
inner.push(vec![u0, v0, u1, v0, u1, v1, u0, v1]);
}
}
// Kerben sortieren (stabil, wie `Array.sort`) und überlappende zusammenfassen.
notches.sort_by(|a, b| (a[0] - b[0]).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal));
let mut merged: Vec<[f64; 3]> = Vec::new();
for n in notches {
match merged.last_mut() {
Some(last) if n[0] <= last[1] + EPS => {
last[1] = max(last[1], n[1]);
last[2] = max(last[2], n[2]);
}
_ => merged.push(n),
}
}
// Aussenring CCW in (u,v): Wandfuss links→rechts mit Kerben, dann Kopf rechts→links.
let mut outer = vec![0.0, 0.0];
for [a, b, top] in merged {
outer.extend_from_slice(&[a, 0.0, a, top, b, top, b, 0.0]);
}
outer.extend_from_slice(&[length, 0.0, length, height, 0.0, height]);
(outer, inner)
}
/// Eingabe von [`wall_spec`]: Achse, Dicke, Höhe, UK, Öffnungen (Teil von `RWall`).
pub struct WallIn<'a> {
pub start: [f64; 2],
pub end: [f64; 2],
pub thickness: f64,
pub height: f64,
pub base_elevation: f64,
pub holes: &'a [RHole],
}
impl<'a> WallIn<'a> {
pub fn of(w: &'a RWall) -> Self {
WallIn { start: w.start, end: w.end, thickness: w.thickness, height: w.height, base_elevation: w.base_elevation, holes: w.holes.as_deref().unwrap_or(&[]) }
}
}
/// Wand(schicht) als `extrudePlane`: Profil in der Wandebene, Ursprung auf einer Wandfläche,
/// Tiefe = Dicke. `None` bei entarteter Wand.
pub fn wall_spec(w: &WallIn) -> Option<Value> {
let dx = w.end[0] - w.start[0];
let dy = w.end[1] - w.start[1];
let len = hypot2(dx, dy);
if len < MIN_THICKNESS || w.height < MIN_THICKNESS || w.thickness < MIN_THICKNESS {
return None;
}
let ux = dx / len;
let uy = dy / len;
// u × v (v = +Z) = (uy, −ux, 0): Extrusionsrichtung. Ursprung = eine Wandfläche.
let nx = uy;
let ny = -ux;
let (outer, holes) = wall_profile(len, w.height, w.holes, w.base_elevation);
Some(json!({
"kind": "extrudePlane",
"points": outer,
"holes": holes,
"origin": [w.start[0] - (nx * w.thickness) / 2.0, w.start[1] - (ny * w.thickness) / 2.0, w.base_elevation],
"uAxis": [ux, uy, 0.0],
"vAxis": [0.0, 0.0, 1.0],
"depth": w.thickness,
}))
}
/// Achsparallele Hülle (x0, y0, x1, y1) wie `Math.min(...)`/`Math.max(...)`.
fn bbox(pts: impl Iterator<Item = (f64, f64)>) -> [f64; 4] {
let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
for (x, y) in pts {
b[0] = min(b[0], x);
b[1] = min(b[1], y);
b[2] = max(b[2], x);
b[3] = max(b[3], y);
}
b
}
fn box_hit(a: &[f64; 4], b: &[f64; 4]) -> bool {
a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3]
}
/// Grundriss-Ecken einer Wand(schicht).
fn wall_corners(w: &RWall) -> [(f64, f64); 4] {
let dx = w.end[0] - w.start[0];
let dy = w.end[1] - w.start[1];
let h = hypot2(dx, dy);
// `|| 1`: 0 und NaN gelten als falsch.
let len = if h == 0.0 || h.is_nan() { 1.0 } else { h };
let nx = (-dy / len) * (w.thickness / 2.0);
let ny = (dx / len) * (w.thickness / 2.0);
[
(w.start[0] + nx, w.start[1] + ny),
(w.end[0] + nx, w.end[1] + ny),
(w.end[0] - nx, w.end[1] - ny),
(w.start[0] - nx, w.start[1] - ny),
]
}
/// Abzugskörper, die ein Prisma (Grundriss-Hülle + Höhenbereich) treffen.
fn hitting<'a>(voids: &'a [VoidPrism], foot: &[f64; 4], z0: f64, z1: f64) -> Vec<&'a VoidPrism> {
voids
.iter()
.filter(|v| v.z0 < z1 - 1e-6 && v.z1 > z0 + 1e-6 && box_hit(&bbox(v.pts.iter().map(|p: &Vec2| (p.x, p.y))), foot))
.collect()
}
/// Bauteil minus alle Körper (verkettete Differenzen).
fn subtract(base: Value, voids: &[&VoidPrism]) -> Value {
voids.iter().fold(base, |acc, v| {
let pts: Vec<f64> = v.pts.iter().flat_map(|p| [p.x, p.y]).collect();
json!({"kind": "boolean", "op": "difference", "a": acc, "b": {"kind": "extrude", "points": pts, "height": v.z1 - v.z0, "z0": v.z0}})
})
}
/// Bauteile des 3D-Modells, die ein Abzugskörper trifft: (Index im Modell, Spezifikation Bauteil −
/// Körper). TS tesselliert sie über truck und ersetzt das Bauteil durch das Mesh.
#[derive(serde::Serialize, Default, Debug)]
pub struct VoidCuts {
pub walls: Vec<(usize, Value)>,
pub slabs: Vec<(usize, Value)>,
}
/// Abzugskörper auf Wände und Decken des Modells anwenden (früher `applyVoids3d`, Spezifikationsteil).
pub fn void_cuts(p: &Project, walls: &[RWall], slabs: &[RSlab]) -> VoidCuts {
let voids = void_prisms(p);
let mut out = VoidCuts::default();
if voids.is_empty() {
return out;
}
for (i, w) in walls.iter().enumerate() {
let hits = hitting(&voids, &bbox(wall_corners(w).into_iter()), w.base_elevation, w.base_elevation + w.height);
if hits.is_empty() {
continue;
}
if let Some(base) = wall_spec(&WallIn::of(w)) {
out.walls.push((i, subtract(base, &hits)));
}
}
for (i, s) in slabs.iter().enumerate() {
if s.outline.len() < 3 {
continue;
}
let hits = hitting(&voids, &bbox(s.outline.iter().map(|q| (q[0], q[1]))), s.z_bottom, s.z_top);
if hits.is_empty() {
continue;
}
let pts: Vec<f64> = s.outline.iter().flat_map(|q| [q[0], q[1]]).collect();
let base = json!({"kind": "extrude", "points": pts, "height": s.z_top - s.z_bottom, "z0": s.z_bottom});
out.slabs.push((i, subtract(base, &hits)));
}
out
}
/// Flache Wand für die Bindung: `[sx, sy, ex, ey, Dicke, Höhe, UK, (von, bis, UK, OK) × n]`.
pub fn wall_spec_flat(f: &[f64]) -> String {
if f.len() < 7 || (f.len() - 7) % 4 != 0 {
return String::new();
}
let holes: Vec<RHole> = f[7..].chunks_exact(4).map(|c| RHole { from: c[0], to: c[1], z_bottom: c[2], z_top: c[3] }).collect();
let w = WallIn { start: [f[0], f[1]], end: [f[2], f[3]], thickness: f[4], height: f[5], base_elevation: f[6], holes: &holes };
wall_spec(&w).map_or_else(String::new, |v| v.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
fn hole(from: f64, to: f64, zb: f64, zt: f64) -> RHole {
RHole { from, to, z_bottom: zb, z_top: zt }
}
#[test]
fn profil_tuer_als_kerbe_fenster_als_loch() {
let (outer, holes) = wall_profile(5.0, 2.6, &[hole(1.0, 2.0, 0.0, 2.1), hole(3.0, 4.0, 0.9, 2.1)], 0.0);
assert_eq!(outer, vec![0.0, 0.0, 1.0, 0.0, 1.0, 2.1, 2.0, 2.1, 2.0, 0.0, 5.0, 0.0, 5.0, 2.6, 0.0, 2.6]);
assert_eq!(holes, vec![vec![3.0, 0.9, 4.0, 0.9, 4.0, 2.1, 3.0, 2.1]]);
}
#[test]
fn profil_kerben_verschmolzen_und_kopf_gekappt() {
let (outer, _) = wall_profile(4.0, 2.5, &[hole(2.0, 3.0, 0.0, 2.0), hole(0.5, 2.2, 0.0, 2.6)], 0.0);
assert_eq!(outer, vec![0.0, 0.0, 0.5, 0.0, 0.5, 2.499, 3.0, 2.499, 3.0, 0.0, 4.0, 0.0, 4.0, 2.5, 0.0, 2.5]);
}
#[test]
fn wand_spec_entartet_und_flach() {
assert_eq!(wall_spec_flat(&[0.0, 0.0, 0.0, 0.0, 0.2, 2.5, 0.0]), "");
assert_eq!(wall_spec_flat(&[0.0, 0.0, 1.0]), "");
let v: Value = serde_json::from_str(&wall_spec_flat(&[0.0, 0.0, 4.0, 0.0, 0.2, 2.5, 1.0])).unwrap();
assert_eq!(v["kind"], "extrudePlane");
assert_eq!(v["origin"], json!([0.0, 0.1, 1.0]));
assert_eq!(v["depth"], json!(0.2));
}
#[test]
fn abzug_trifft_nur_ueberlappende_bauteile() {
let mut v: Value = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap();
v["extrudedSolids"] = json!([{"id": "v1", "type": "extrudedSolid", "levelId": "eg", "operation": "subtract", "height": 1.0, "baseOffset": 1.0,
"points": [{"x": -100.0, "y": -100.0}, {"x": 100.0, "y": -100.0}, {"x": 100.0, "y": 100.0}, {"x": -100.0, "y": 100.0}]}]);
let p: Project = serde_json::from_value(v).unwrap();
let walls = crate::model3d::emit_walls(&p, true).unwrap();
let slabs = crate::model3d::emit_slabs(&p);
let c = void_cuts(&p, &walls, &slabs);
assert!(!c.walls.is_empty());
for (i, spec) in &c.walls {
let w = &walls[*i];
assert!(w.base_elevation < 2.0 && w.base_elevation + w.height > 1.0);
assert_eq!(spec["kind"], "boolean");
assert_eq!(spec["b"]["z0"], json!(p.floor("eg").and_then(|f| f.base_elevation).unwrap_or(0.0) + 1.0));
}
}
}
+6
View File
@@ -7,3 +7,9 @@ use wasm_bindgen::prelude::wasm_bindgen;
pub fn voids_subtract_rings_flat(pts: &[f64], cutters: &[f64], no_stroke: &[f64]) -> Vec<f64> {
crate::voids::subtract_rings_flat(pts, cutters, no_stroke)
}
/// Wand als truck-Spezifikation (`solid_specs::wall_spec_flat`): JSON oder leer (entartet/kaputt).
#[wasm_bindgen]
pub fn wall_spec_flat(f: &[f64]) -> String {
crate::solid_specs::wall_spec_flat(f)
}