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

# Conflicts:
#	TODO.md
This commit is contained in:
Claude committed 2026-10-30 09:30:36 +00:00
commit 9eff2cd5e6
36 files changed
+1412 -55

No files matched your search

+1 -1
View File
@@ -881,7 +881,7 @@ const PROFILE_HIT_TOL: f64 = 0.25;
/// Extrudierbares Profil einer Zeichnung: geschlossene Polylinie (≥ 3 Punkte), Rechteck, Kreis.
/// Punkte als JSON-Werte (Polylinie: die gespeicherten), dazu `circle` beim Kreis.
fn profile_of(d: &Value) -> Option<(Vec<Value>, Option<Value>)> {
pub(crate) fn profile_of(d: &Value) -> Option<(Vec<Value>, Option<Value>)> {
let g = field(d, "geom")?;
match field(g, "shape").and_then(Value::as_str)? {
"polyline" => {
+179
View File
@@ -150,6 +150,130 @@ pub fn solid_from_inputs(shape: &str, p0: V, p1: Option<V>, nums: &[f64]) -> Opt
}
}
// ═════════════════════════════════════════════════════════════════════════════
// Rotationskörper und Loft aus Plan-Profilen ([T7])
// ═════════════════════════════════════════════════════════════════════════════
/// Rotationskörper: das Plan-Profil (geschlossen, in der Zeichenebene) dreht sich um die Achse
/// `a → b` (liegt waagrecht im Plan, auf Höhe des grössten Profilabstands, damit ein voller Körper auf
/// der Geschoss-UK steht). Das Profil muss ganz auf einer Seite der Achse liegen; es wird als
/// (r = Abstand, z = Lage entlang der Achse) an `revolve` von truck gegeben und per `transform` ins
/// Modell gesetzt (lokal x → Querrichtung, y → oben, z → Achse). `angle_deg` in (0, 360]; positive
/// Drehung hebt das Profil nach oben. Ergebnis: Grundriss-Rechteck, Höhe, B-Rep-Beschreibung, Label.
pub fn revolve_from_profile(profile: &[V], a: V, b: V, angle_deg: f64) -> Option<(Vec<V>, f64, Value, String)> {
let len = hypot2(b.0 - a.0, b.1 - a.1);
if profile.len() < 3 || !(len > 1e-6) || !angle_deg.is_finite() || !(angle_deg > 0.0) {
return None;
}
let mut d = ((b.0 - a.0) / len, (b.1 - a.1) / len);
let side = |d: V, p: V| (p.0 - a.0) * -d.1 + (p.1 - a.1) * d.0;
let (lo, hi) = profile.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(side(d, *p)), hi.max(side(d, *p))));
if !(lo.is_finite() && hi.is_finite()) {
return None;
}
if lo < -1e-6 {
if hi > 1e-6 {
return None; // Profil überquert die Achse
}
d = (-d.0, -d.1); // Profil liegt rechts: Achse umdrehen, damit r >= 0
}
let n = (-d.1, d.0);
let ring: Vec<(f64, f64)> = profile.iter().map(|p| (side(d, *p).max(0.0), (p.0 - a.0) * d.0 + (p.1 - a.1) * d.1)).collect();
let r_max = ring.iter().fold(0.0_f64, |m, q| m.max(q.0));
if !(r_max > 1e-6) {
return None;
}
let (z_min, z_max) = ring.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q.1), hi.max(q.1)));
if !(z_max - z_min > 1e-6) {
return None;
}
let angle = angle_deg.min(360.0);
let flat: Vec<Value> = ring.iter().flat_map(|q| [js_num(q.0), js_num(q.1)]).collect();
let inner = obj(vec![("kind", s("revolve")), ("profile", Value::Array(flat)), ("angleDeg", js_num(angle))]);
let m = [n.0, 0.0, d.0, a.0, n.1, 0.0, d.1, a.1, 0.0, 1.0, 0.0, r_max];
let spec = obj(vec![("kind", s("transform")), ("m", Value::Array(m.iter().map(|x| js_num(*x)).collect())), ("solid", inner)]);
let at = |along: f64, perp: f64| (a.0 + d.0 * along + n.0 * perp, a.1 + d.1 * along + n.1 * perp);
let pts = vec![at(z_min, -r_max), at(z_max, -r_max), at(z_max, r_max), at(z_min, r_max)];
Some((pts, 2.0 * r_max, spec, format!("Rotationskörper {}°", fixed2(angle))))
}
fn ring_area(r: &[V]) -> f64 {
let n = r.len();
(0..n).map(|i| r[i].0 * r[(i + 1) % n].1 - r[(i + 1) % n].0 * r[i].1).sum::<f64>() / 2.0
}
/// Gleiche Punktzahl für alle Ringe: kürzere Ringe teilen ihre längste Kante, bis sie so viele Punkte
/// haben wie der längste (Ecken bleiben erhalten); alle gegen den Uhrzeigersinn.
fn match_rings(rings: &[Vec<V>]) -> Vec<Vec<V>> {
let target = rings.iter().map(Vec::len).max().unwrap_or(0);
rings
.iter()
.map(|r| {
let mut r = r.clone();
if ring_area(&r) < 0.0 {
r.reverse();
}
while r.len() < target {
let n = r.len();
let len = |k: usize| hypot2(r[(k + 1) % n].0 - r[k].0, r[(k + 1) % n].1 - r[k].1);
let Some(i) = (0..n).max_by(|&i, &j| len(i).partial_cmp(&len(j)).unwrap_or(std::cmp::Ordering::Equal)) else { break };
let (p, q) = (r[i], r[(i + 1) % n]);
r.insert(i + 1, ((p.0 + q.0) / 2.0, (p.1 + q.1) / 2.0));
}
r
})
.collect()
}
/// Loft durch >= 2 Plan-Profile, gleichmässig über `height` verteilt (erstes Profil unten).
pub fn loft_from_rings(rings: &[Vec<V>], height: f64) -> Option<(Vec<V>, f64, Value, String)> {
if rings.len() < 2 || !(height > 1e-6) || rings.iter().any(|r| r.len() < 3 || r.iter().any(|p| !(p.0.is_finite() && p.1.is_finite()))) {
return None;
}
let rings = match_rings(rings);
let last = (rings.len() - 1) as f64;
let sections: Vec<Value> = rings
.iter()
.enumerate()
.map(|(i, r)| obj(vec![("z", js_num(height * i as f64 / last)), ("points", Value::Array(r.iter().flat_map(|p| [js_num(p.0), js_num(p.1)]).collect()))]))
.collect();
let spec = obj(vec![("kind", s("loft")), ("sections", Value::Array(sections))]);
Some((rings[0].clone(), height, spec, format!("Loft {} Profile h={}", rings.len(), fixed2(height))))
}
fn profile_ring(root: &Map<String, Value>, id: &str) -> Option<Vec<V>> {
let (pts, _) = find(root, "drawings2d", id).and_then(crate::cmd_create::profile_of)?;
Some(pts.iter().map(xy).collect())
}
fn brep_solid_ops(root: &Map<String, Value>, ctx: &Ctx, ids: &mut IdGen, sources: &[&str], made: Option<(Vec<V>, f64, Value, String)>) -> Vec<Op> {
let Some((pts, height, spec, label)) = made else { return Vec::new() };
let solid = obj(vec![
("id", s(&ids.next("body"))),
("type", s("extrudedSolid")),
("levelId", s(ctx.level)),
("points", pvs(&pts)),
("height", js_num(height)),
("brep", obj(vec![("spec", spec), ("origin", pv(pts[0])), ("label", s(&label))])),
]);
let mut ops = crate::cmd_create::remove_op(root, "drawings2d", sources);
ops.extend(add_op("extrudedSolids", vec![solid]));
ops
}
fn revolve_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let src = s_of(v, "source");
let made = profile_ring(root, src).and_then(|ring| revolve_from_profile(&ring, p_of(v, "a"), p_of(v, "b"), num_or(field(v, "angle"), 360.0)));
brep_solid_ops(root, ctx, ids, &[src], made)
}
fn loft_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let sources: Vec<&str> = arr(v.get("sources")).iter().filter_map(Value::as_str).collect();
let rings: Option<Vec<Vec<V>>> = sources.iter().map(|id| profile_ring(root, id)).collect();
let made = rings.and_then(|r| loft_from_rings(&r, n_of(v, "height")));
brep_solid_ops(root, ctx, ids, &sources, made)
}
fn solid_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let nums: Vec<f64> = arr(v.get("nums")).iter().map(|x| num_of(Some(x))).collect();
let Some((pts, height, spec, label)) = solid_from_inputs(s_of(v, "shape"), p_of(v, "p0"), opt_p(v, "p1"), &nums) else {
@@ -645,6 +769,8 @@ fn direction_arrow(a: V, b: V, sign: f64, out: &mut Shapes) {
pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option<Vec<Op>> {
Some(match s_of(v, "cmd") {
"solid" => solid_ops(v, ctx, ids),
"revolve" => revolve_ops(root, v, ctx, ids),
"loft" => loft_ops(root, v, ctx, ids),
"solidbool" => solidbool_ops(root, v, ids),
"voidbox" => voidbox_ops(v, ctx, ids),
"terrain" => terrain_ops(root, ids),
@@ -798,4 +924,57 @@ mod tests {
assert!(pos.iter().skip(2).step_by(3).all(|z| (1.0..=2.0).contains(&z.as_f64().unwrap())));
assert!(terrain_from_contours(&[], "t")["indices"].as_array().unwrap().is_empty());
}
/// [T7] Rotationskörper: Achse waagrecht im Plan, Profil auf einer Seite, Matrix bildet lokal x → Quer, z → Achse ab.
#[test]
fn rotationskoerper_aus_profil() {
let prof = [(0.0, 0.0), (2.0, 0.0), (2.0, 1.0), (0.0, 1.0)];
let (pts, h, spec, label) = revolve_from_profile(&prof, (0.0, 0.0), (5.0, 0.0), 360.0).unwrap();
assert_eq!(h, 2.0);
assert_eq!(label, "Rotationskörper 360.00°");
assert_eq!(spec["kind"], "transform");
assert_eq!(spec["solid"]["profile"], json!([0, 0, 0, 2, 1, 2, 1, 0]));
let m: Vec<f64> = spec["m"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
let w = |l: [f64; 3]| [m[0] * l[0] + m[1] * l[1] + m[2] * l[2] + m[3], m[4] * l[0] + m[5] * l[1] + m[6] * l[2] + m[7], m[8] * l[0] + m[9] * l[1] + m[10] * l[2] + m[11]];
assert_eq!(w([1.0, 0.0, 2.0]), [2.0, 1.0, 1.0]);
assert_eq!(w([0.0, 1.0, 0.0]), [0.0, 0.0, 2.0]);
assert_eq!(pts.len(), 4);
let rechts = [(0.0, 0.0), (2.0, 0.0), (2.0, -1.0), (0.0, -1.0)];
let (_, _, spec2, _) = revolve_from_profile(&rechts, (0.0, 0.0), (5.0, 0.0), 90.0).unwrap();
assert_eq!(spec2["solid"]["angleDeg"], 90.0);
assert!(revolve_from_profile(&[(0.0, -1.0), (2.0, -1.0), (2.0, 1.0), (0.0, 1.0)], (0.0, 0.0), (5.0, 0.0), 360.0).is_none());
assert!(revolve_from_profile(&prof, (0.0, 0.0), (0.0, 0.0), 360.0).is_none());
assert!(revolve_from_profile(&prof, (0.0, 0.0), (5.0, 0.0), f64::NAN).is_none());
}
/// [T7] Loft: gleiche Punktzahl (Kante teilen), Höhen gleichmässig, Ringe gegen den Uhrzeigersinn.
#[test]
fn loft_aus_profilen() {
let quad = vec![(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)];
let tri_cw = vec![(0.5, 0.5), (0.5, 1.5), (1.5, 0.5)];
let (pts, h, spec, label) = loft_from_rings(&[quad.clone(), tri_cw, quad.clone()], 3.0).unwrap();
assert_eq!((pts.len(), h), (4, 3.0));
assert_eq!(label, "Loft 3 Profile h=3.00");
let secs = spec["sections"].as_array().unwrap();
assert_eq!(secs.len(), 3);
assert_eq!(secs[1]["z"], 1.5);
assert!(secs.iter().all(|s| s["points"].as_array().unwrap().len() == 8));
assert!(loft_from_rings(&[quad.clone()], 3.0).is_none());
assert!(loft_from_rings(&[quad.clone(), quad], 0.0).is_none());
}
#[test]
fn rotation_und_loft_befehle_legen_koerper_an_und_entfernen_quellen() {
let d = |id: &str, pts: Value| json!({"id": id, "type": "drawing2d", "levelId": "eg", "geom": {"shape": "polyline", "closed": true, "pts": pts}});
let sq = |x: f64, s: f64| json!([{"x": x, "y": 0}, {"x": x + s, "y": 0}, {"x": x + s, "y": s}, {"x": x, "y": s}]);
let root = json!({"drawings2d": [d("A", sq(0.0, 2.0)), d("B", sq(10.0, 1.0))]});
let root = root.as_object().unwrap();
let ctx = Ctx { level: "eg", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 };
let mut ids = IdGen::new("t");
let ops = loft_ops(root, &json!({"sources": ["A", "B"], "height": 2.0}), &ctx, &mut ids);
assert_eq!(ops.len(), 2);
let ops = revolve_ops(root, &json!({"source": "A", "a": {"x": -1, "y": -1}, "b": {"x": 5, "y": -1}, "angle": 180}), &ctx, &mut ids);
assert_eq!(ops.len(), 2);
assert!(revolve_ops(root, &json!({"source": "ZZ", "a": {"x": 0, "y": 0}, "b": {"x": 1, "y": 0}}), &ctx, &mut ids).is_empty());
}
}
+31 -3
View File
@@ -374,6 +374,7 @@ pub fn decode_mesh(f: &[f64], strings: &[String]) -> Result<(Vec<MeshObject>, Va
k += 1.0;
}
let mut objects = Vec::new();
let mut repaired = [0usize; 3];
let mut k = 0.0;
while k < n_obj {
let h = f.get(at..at + 9).ok_or("Mesh-Import: Puffer beschädigt")?;
@@ -385,12 +386,17 @@ pub fn decode_mesh(f: &[f64], strings: &[String]) -> Result<(Vec<MeshObject>, Va
if !(np.fract() == 0.0 && ni.fract() == 0.0 && np >= 0.0 && ni >= 0.0) || at + np as usize + ni as usize > f.len() {
return Err("Mesh-Import: Puffer beschädigt".into());
}
let positions = f[at..at + np as usize].to_vec();
let positions: Vec<f64> = f[at..at + np as usize].to_vec();
at += np as usize;
// Wie `Uint32Array`: ganzzahlig modulo 2³².
let indices = f[at..at + ni as usize].iter().map(|&x| (jsnum::to_int32(x) as u32) as f64).collect();
let indices: Vec<f64> = f[at..at + ni as usize].iter().map(|&x| (jsnum::to_int32(x) as u32) as f64).collect();
at += ni as usize;
objects.push(MeshObject { name, group, color, positions, indices });
// Reparatur ([T5]): verschweissen, Entartete raus, kleine Löcher zu; Zähler gehen in den Bericht.
let r = crate::mesh_repair::repair(&positions, &indices);
repaired[0] += r.welded;
repaired[1] += r.degenerate;
repaired[2] += r.holes;
objects.push(MeshObject { name, group, color, positions: r.pos, indices: r.idx });
k += 1.0;
}
let report = json!({
@@ -405,6 +411,7 @@ pub fn decode_mesh(f: &[f64], strings: &[String]) -> Result<(Vec<MeshObject>, Va
"truncated": f[9] == 1.0,
"warnings": warnings,
"objects": objects.len(),
"repaired": {"welded": repaired[0], "degenerate": repaired[1], "holes": repaired[2]},
});
Ok((objects, report))
}
@@ -593,3 +600,24 @@ mod step_tests {
assert!(decode_step(&[1.0, f64::NAN]).is_err());
}
}
#[cfg(test)]
mod repair_tests {
use super::*;
/// [T5] Der Import verschweisst Ecken und meldet die Reparatur im Bericht.
#[test]
fn mesh_import_repariert_und_berichtet() {
let mut f = vec![1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0];
// Objekt: Name 0, Gruppe -1, keine Farbe, 6 Ecken (Quadrat als zwei Dreiecke, STL-artig) + 1 entartetes Dreieck
f.extend([0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 18.0, 9.0]);
f.extend([0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 0., 0., 1., 1., 0., 0., 1., 0.]);
f.extend([0., 1., 2., 3., 4., 5., 0., 0., 1.]);
let (objects, report) = decode_mesh(&f, &["q".to_string()]).unwrap();
assert_eq!(objects[0].positions.len(), 12); // 4 statt 6 Ecken
assert_eq!(objects[0].indices.len(), 6);
assert_eq!(report["repaired"]["welded"], 2);
assert_eq!(report["repaired"]["degenerate"], 1);
assert_eq!(report["repaired"]["holes"], 0);
}
}
+1
View File
@@ -37,6 +37,7 @@ pub mod js_fmt;
pub use dossier_hatch::jsmath;
pub mod stairs3d;
pub mod mesh3d;
pub mod mesh_repair;
pub mod ceilings3d;
pub mod columns3d;
pub mod drawing2d_3d;
+237
View File
@@ -0,0 +1,237 @@
//! Reparatur importierter Dreiecksnetze ([T5]): Ecken verschweissen (STL liefert jedes Dreieck mit eigenen
//! Ecken), entartete Dreiecke entfernen, kleine Löcher in sonst geschlossenen Netzen mit einem Fächer
//! schliessen. Reine Funktion über flache Puffer (`pos` = `[x, y, z, …]` in Metern, `idx` = Dreiecks-Indizes
//! als `f64`); Unsinn (NaN, Indizes ausserhalb) bleibt unverändert bzw. wird als entartet entfernt.
use std::collections::HashMap;
/// Verschweiss-Toleranz (Meter): 0.01 mm — fängt Rundungsdifferenzen der Formate, nicht echte Spalte.
pub const WELD_TOL: f64 = 1e-5;
/// Löcher mit höchstens so vielen Randkanten werden geschlossen.
pub const MAX_HOLE_EDGES: usize = 8;
/// Löcher nur schliessen, wenn höchstens dieser Anteil der Kanten am Rand liegt (sonst offene Fläche gewollt).
const MAX_BOUNDARY_SHARE: f64 = 0.05;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Repaired {
pub pos: Vec<f64>,
pub idx: Vec<f64>,
/// Zusammengelegte Ecken.
pub welded: usize,
/// Entfernte entartete Dreiecke (doppelte Ecke, Fläche ≈ 0, ungültiger Index).
pub degenerate: usize,
/// Geschlossene Löcher.
pub holes: usize,
}
fn tri_area2(p: &[[f64; 3]; 3]) -> f64 {
let (a, b, c) = (p[0], p[1], p[2]);
let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt()
}
pub fn repair(pos: &[f64], idx: &[f64]) -> Repaired {
repair_with(pos, idx, MAX_BOUNDARY_SHARE)
}
/// Wie [`repair`], mit frei wählbarem Randanteil-Schutz (Tests, strenge Importe).
pub fn repair_with(pos: &[f64], idx: &[f64], max_boundary_share: f64) -> Repaired {
let nv = pos.len() / 3;
// 1) Verschweissen über ein Raster (Zelle = Toleranz); Nachbarzellen werden nicht geprüft — Ecken, die
// knapp über einer Zellgrenze liegen, bleiben getrennt (konservativ, nie falsch verbunden).
let mut cell: HashMap<(i64, i64, i64), u32> = HashMap::new();
let mut map: Vec<Option<u32>> = vec![None; nv];
let mut out_pos: Vec<f64> = Vec::new();
for i in 0..nv {
let p = [pos[3 * i], pos[3 * i + 1], pos[3 * i + 2]];
if !p.iter().all(|x| x.is_finite()) {
continue;
}
let key = ((p[0] / WELD_TOL).round() as i64, (p[1] / WELD_TOL).round() as i64, (p[2] / WELD_TOL).round() as i64);
let id = *cell.entry(key).or_insert_with(|| {
out_pos.extend(p);
(out_pos.len() / 3 - 1) as u32
});
map[i] = Some(id);
}
let welded = map.iter().flatten().count() - out_pos.len() / 3;
// 2) Dreiecke übernehmen, entartete verwerfen
let mut tris: Vec<[u32; 3]> = Vec::new();
let mut degenerate = 0;
for t in idx.chunks_exact(3) {
let v: Vec<Option<u32>> = t.iter().map(|&k| if k >= 0.0 && k.fract() == 0.0 && (k as usize) < nv { map[k as usize] } else { None }).collect();
let (Some(a), Some(b), Some(c)) = (v[0], v[1], v[2]) else {
degenerate += 1;
continue;
};
let p = |i: u32| [out_pos[3 * i as usize], out_pos[3 * i as usize + 1], out_pos[3 * i as usize + 2]];
if a == b || b == c || a == c || tri_area2(&[p(a), p(b), p(c)]) < 1e-12 {
degenerate += 1;
continue;
}
tris.push([a, b, c]);
}
// 3) Löcher schliessen
let holes = close_holes(&mut tris, max_boundary_share);
Repaired { pos: out_pos, idx: tris.iter().flatten().map(|&k| k as f64).collect(), welded, degenerate, holes }
}
/// Kleine Randschleifen eines fast geschlossenen Netzes mit einem Fächer füllen; Anzahl geschlossener Löcher.
fn close_holes(tris: &mut Vec<[u32; 3]>, max_boundary_share: f64) -> usize {
let mut directed: HashMap<(u32, u32), usize> = HashMap::new();
for t in tris.iter() {
for k in 0..3 {
*directed.entry((t[k], t[(k + 1) % 3])).or_insert(0) += 1;
}
}
// Randkanten: Kante a→b ohne Gegenkante b→a; Nicht-Mannigfaltigkeit (Kante mehrfach) → nichts anfassen
if directed.values().any(|&n| n > 1) {
return 0;
}
let boundary: Vec<(u32, u32)> = directed.keys().filter(|&&(a, b)| !directed.contains_key(&(b, a))).copied().collect();
if boundary.is_empty() || boundary.len() as f64 > max_boundary_share * directed.len() as f64 {
return 0;
}
// Der Rand läuft a→b; die fehlenden Dreiecke tragen b→a, der Deckel läuft also gegen die Randrichtung.
let mut next: HashMap<u32, Vec<u32>> = HashMap::new();
for &(a, b) in &boundary {
next.entry(a).or_default().push(b);
}
if next.values().any(|v| v.len() != 1) {
return 0; // Rand verzweigt sich (Schmetterlingsecke) — nicht raten
}
let mut seen: std::collections::HashSet<u32> = std::collections::HashSet::new();
let mut closed = 0;
let mut starts: Vec<u32> = next.keys().copied().collect();
starts.sort_unstable();
for s in starts {
if seen.contains(&s) {
continue;
}
let mut ring = vec![s];
let mut cur = s;
let mut ok = true;
loop {
let n = next[&cur][0];
if n == s {
break;
}
if ring.len() >= MAX_HOLE_EDGES || !next.contains_key(&n) || ring.contains(&n) {
ok = false;
break;
}
ring.push(n);
cur = n;
}
seen.extend(ring.iter().copied());
if !ok || ring.len() < 3 {
continue;
}
ring.reverse();
for k in 1..ring.len() - 1 {
tris.push([ring[0], ring[k], ring[k + 1]]);
}
closed += 1;
}
closed
}
#[cfg(test)]
mod tests {
use super::*;
/// Würfel mit eigenen Ecken je Dreieck (wie STL), Kantenlänge 1, nach aussen orientiert.
fn soup(skip: &[usize]) -> (Vec<f64>, Vec<f64>) {
let v = [[0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 1., 0.], [0., 0., 1.], [1., 0., 1.], [1., 1., 1.], [0., 1., 1.]];
let f: [[usize; 3]; 12] = [
[0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7], [0, 1, 5], [0, 5, 4],
[1, 2, 6], [1, 6, 5], [2, 3, 7], [2, 7, 6], [3, 0, 4], [3, 4, 7],
];
let (mut pos, mut idx) = (Vec::new(), Vec::new());
for (i, t) in f.iter().enumerate() {
if skip.contains(&i) {
continue;
}
for &k in t {
idx.push((pos.len() / 3) as f64);
pos.extend(v[k]);
}
}
(pos, idx)
}
fn volume(r: &Repaired) -> f64 {
r.idx
.chunks(3)
.map(|t| {
let p = |i: f64| [r.pos[3 * i as usize], r.pos[3 * i as usize + 1], r.pos[3 * i as usize + 2]];
let (a, b, c) = (p(t[0]), p(t[1]), p(t[2]));
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
})
.sum()
}
#[test]
fn stl_suppe_wird_verschweisst() {
let (pos, idx) = soup(&[]);
let r = repair(&pos, &idx);
assert_eq!(r.pos.len() / 3, 8);
assert_eq!(r.welded, 36 - 8);
assert_eq!((r.degenerate, r.holes), (0, 0));
assert!((volume(&r) - 1.0).abs() < 1e-12);
}
#[test]
fn entartete_dreiecke_fliegen_raus() {
let (mut pos, mut idx) = soup(&[]);
let n = (pos.len() / 3) as f64;
pos.extend([5., 5., 5., 6., 6., 6., 7., 7., 7.]); // kollinear
idx.extend([n, n + 1., n + 2.]);
idx.extend([0., 0., 1.]); // doppelte Ecke
idx.extend([0., 1., 9999.]); // Index ausserhalb
let r = repair(&pos, &idx);
assert_eq!(r.degenerate, 3);
assert_eq!(r.idx.len(), 36);
}
#[test]
fn offene_flaeche_bleibt_offen() {
// Einzelnes Quadrat: Rand 100 % → gewollt offen
let pos = [0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0.];
let idx = [0., 1., 2., 0., 2., 3.];
let r = repair(&pos, &idx);
assert_eq!((r.holes, r.idx.len()), (0, 6));
}
#[test]
fn loch_wird_mit_faecher_geschlossen_und_ist_nach_aussen_orientiert() {
// Würfel ohne zwei Dreiecke (Deckel) → 4-Kanten-Loch; der Randanteil-Schutz (5 %) lässt es offen …
let (pos, idx) = soup(&[2, 3]);
assert_eq!(repair(&pos, &idx).holes, 0);
// … ohne Schutz wird es geschlossen und das Netz ist wieder ein Würfel (Volumen 1, richtig herum)
let r = repair_with(&pos, &idx, 1.0);
assert_eq!(r.holes, 1);
assert_eq!(r.idx.len(), 36);
assert!((volume(&r) - 1.0).abs() < 1e-12, "Volumen {}", volume(&r));
}
#[test]
fn grosses_loch_bleibt_offen() {
// Kegelmantel ohne Boden: Randschleife mit 9 Kanten > MAX_HOLE_EDGES — wird nie geschlossen
let n = 9;
let mut pos = Vec::new();
for k in 0..n {
let a = std::f64::consts::TAU * k as f64 / n as f64;
pos.extend([a.cos(), a.sin(), 0.0]);
}
pos.extend([0.0, 0.0, 1.0]);
let mut idx = Vec::new();
for k in 0..n {
idx.extend([k as f64, ((k + 1) % n) as f64, n as f64]);
}
let r = repair_with(&pos, &idx, 1.0);
assert_eq!(r.holes, 0);
}
}
+5
View File
@@ -3127,6 +3127,11 @@ pub struct Stair {
#[serde(rename = "arrowStyle", default, skip_serializing_if = "Option::is_none")]
#[ts(optional, inline)]
pub arrow_style: Option<StairArrowStyle>,
/// Nur Wendel: Radius (Meter) der Mittelsäule (Spindel) im Zentrum. Fehlt er oder ist er
/// ≤ 0, gibt es keine Säule.
#[serde(rename = "centerColumn", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub center_column: Option<f64>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
+6 -5
View File
@@ -1164,7 +1164,7 @@ fn rail_rgb() -> Rgb {
hex_to_rgb("#74797f", SLAB_RGB)
}
/// Flache Eingabe der Treppen für `stairs3d` (23 Zahlen je Treppe); `wanted` wählt vor.
/// Flache Eingabe der Treppen für `stairs3d` (24 Zahlen je Treppe); `wanted` wählt vor.
fn stair_input<'a>(p: &'a Project, wanted: impl Fn(&Stair, Option<&StairType>) -> bool) -> Option<(Vec<(usize, &'a Stair)>, Vec<f64>)> {
let mut stairs: Vec<(usize, &Stair)> = Vec::new();
let mut types: Vec<Option<&StairType>> = Vec::new();
@@ -1199,6 +1199,7 @@ fn stair_input<'a>(p: &'a Project, wanted: impl Fn(&Stair, Option<&StairType>) -
Some(StairTypeRailing::Beide) => 3.0,
_ => 0.0,
});
buf.push(s.center_column.filter(|r| r.is_finite() && *r > 0.0).unwrap_or(0.0));
}
Some((stairs, buf))
}
@@ -1230,17 +1231,17 @@ fn meshes_of(meshes: Vec<crate::mesh3d::Mesh>, color: Rgb) -> Vec<RMesh> {
crease_angle: None, positions: m.positions, indices: m.indices, kind: "extrusion", color, vertex_colors: None, material_index: None }).collect()
}
/// Glatte Ortbeton-Laufplatten gerader Treppen (`emitStairMeshes`).
/// Glatte Ortbeton-Laufplatten gerader Treppen und Wendelfläche (Schraubenfläche) von Wendeltreppen (`emitStairMeshes`).
pub fn emit_stair_meshes(p: &Project) -> Vec<RMesh> {
match stair_input(p, |s, st| st.is_some_and(|t| t.structure == StairTypeStructure::Beton) && s.shape == StairShape::Straight) {
match stair_input(p, |s, st| st.is_some_and(|t| t.structure == StairTypeStructure::Beton) && matches!(s.shape, StairShape::Straight | StairShape::Spiral)) {
Some((_, buf)) => meshes_of(crate::stairs3d::slab_meshes(&buf), stair_rgb()),
None => vec![],
}
}
/// Handlauf und Pfosten gerader Treppen (`emitStairRailings`).
/// Handlauf und Pfosten gerader Treppen (`emitStairRailings`); bei Wendeltreppen als Schraubensweep.
pub fn emit_stair_railings(p: &Project) -> Vec<RMesh> {
match stair_input(p, |s, st| s.shape == StairShape::Straight && st.and_then(|t| t.railing).is_some_and(|r| r != StairTypeRailing::Keine)) {
match stair_input(p, |s, st| matches!(s.shape, StairShape::Straight | StairShape::Spiral) && st.and_then(|t| t.railing).is_some_and(|r| r != StairTypeRailing::Keine)) {
Some((_, buf)) => meshes_of(crate::stairs3d::railings(&buf), rail_rgb()),
None => vec![],
}
+1
View File
@@ -914,6 +914,7 @@ fn stair_selection(root: &Map<String, Value>, s: &Value) -> Result<J, String> {
.v("up", Value::Bool(field(s, "up") != Some(&Value::Bool(false))))
.raw("arrowStyle", s, "arrowStyle")
.raw("referenz", s, "referenz")
.raw("centerColumn", s, "centerColumn")
.raw("typeId", s, "typeId")
.raw("floorId", s, "floorId")
.o("floorName", floor_name(floor, field(s, "floorId")))
+266 -10
View File
@@ -3,9 +3,10 @@
//! (`railings`). Die Treppengeometrie selbst kommt aus `kernel2d` (`stair_geometry`); TS sammelt aus
//! dem `Project` nur Parameter, Höhen und Tragart und färbt die Ergebnisse ein.
//!
//! Eingabe (je Treppe 23 Zahlen, davor die Anzahl): die 16 Treppen-Parameter (s. [`crate::stair`]),
//! Eingabe (je Treppe 24 Zahlen, davor die Anzahl): die 16 Treppen-Parameter (s. [`crate::stair`]),
//! `zUnten, zOben, tragart (0 massiv, 1 beton, 2 offen: Wange/aufgesattelt/Spindel),
//! trittdicke, nase, geschlosseneSetzstufen (0/1), gelaender (0 keine, 1 links, 2 rechts, 3 beide)`.
//! trittdicke, nase, geschlosseneSetzstufen (0/1), gelaender (0 keine, 1 links, 2 rechts, 3 beide),
//! saeulenRadius (0 keine; nur Wendel)`.
//!
//! Ausgabe Slabs: `[n, (treppe, monolith 0/1, zUnten, zOben, nPkt, x, y …)…]`; Ausgabe Meshes
//! (Laufplatte, Geländer): `[n, (treppe, nPos, nIdx, positionen…, indizes…)…]`. `treppe` ist der
@@ -41,12 +42,16 @@ struct StairIn {
nosing: f64,
closed_risers: bool,
railing: u8,
column_radius: f64,
}
impl StairIn {
fn straight(&self) -> bool {
self.params.shape == "straight"
}
fn spiral(&self) -> bool {
self.params.shape == "spiral"
}
}
fn decode(buf: &[f64]) -> Option<Vec<Option<StairIn>>> {
@@ -58,8 +63,8 @@ fn decode(buf: &[f64]) -> Option<Vec<Option<StairIn>>> {
for v in p.iter_mut() {
*v = r.num()?;
}
let (z_bottom, z_top, structure, tread_thickness, nosing, closed, railing) =
(r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
let (z_bottom, z_top, structure, tread_thickness, nosing, closed, railing, column) =
(r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
// Eine unbrauchbare Treppe fällt einzeln weg (Index bleibt erhalten).
let valid = [z_bottom, z_top, tread_thickness, nosing].iter().all(|v| v.is_finite());
out.push(match (valid, decode_params(&p)) {
@@ -72,6 +77,7 @@ fn decode(buf: &[f64]) -> Option<Vec<Option<StairIn>>> {
nosing,
closed_risers: closed != 0.0,
railing: railing.clamp(0.0, 3.0) as u8,
column_radius: if column.is_finite() && column > 0.0 { column.min(5.0) } else { 0.0 },
}),
_ => None,
});
@@ -237,7 +243,21 @@ fn slabs_of(s: &StairIn, idx: usize, for_section: bool, out: &mut Vec<Slab>) {
let Some((geo, total_rise)) = geometry_of(s) else { return };
let z_bottom = s.z_bottom;
let structure = s.structure;
if structure == BETON && s.straight() && !for_section {
let mut column: Option<Slab> = None;
if s.spiral() && s.column_radius > 0.0 {
if let Some(c) = &s.params.center {
let pts = (0..COLUMN_SEGMENTS)
.map(|k| {
let a = std::f64::consts::TAU * k as f64 / COLUMN_SEGMENTS as f64;
[c.x + s.column_radius * a.cos(), c.y + s.column_radius * a.sin()]
})
.collect();
// Säule zuletzt einfügen: siehe unten; hier nur vormerken
column = Some(Slab { src: idx, monolith: true, z_bottom, z_top: s.z_top, pts });
}
}
if structure == BETON && (s.straight() || s.spiral()) && !for_section {
out.extend(column);
return;
}
let riser = geo.riser_height;
@@ -317,9 +337,114 @@ fn slabs_of(s: &StairIn, idx: usize, for_section: bool, out: &mut Vec<Slab>) {
});
}
}
out.extend(column);
}
/// Kreisbogenstücke je Tritt in Wendelfläche und Handlauf.
const HELIX_SEGMENTS: usize = 6;
/// Ecken der Mittelsäule (Vieleck).
const COLUMN_SEGMENTS: usize = 24;
/// Wendel-Masse: Zentrum, Winkelbereich, Radien (wie `spiral_geometry` in `kernel2d`).
struct Helix {
center: P,
a0: f64,
sweep: f64,
r_in: f64,
r_out: f64,
}
fn helix_of(s: &StairIn) -> Option<Helix> {
let p = &s.params;
let half_w = 0.05_f64.max(p.width / 2.0);
let center = p.center.unwrap_or(p.start);
let radius = (half_w + 0.1).max(p.radius.unwrap_or(p.width));
let a0 = (p.start.y - center.y).atan2(p.start.x - center.x);
let sweep = p.sweep.unwrap_or(270.0).to_radians();
if !(sweep.abs() > 1e-6) {
return None;
}
Some(Helix { center: [center.x, center.y], a0, sweep, r_in: (radius - half_w).max(0.02), r_out: radius + half_w })
}
impl Helix {
fn at(&self, r: f64, ang: f64) -> P {
[self.center[0] + r * ang.cos(), self.center[1] + r * ang.sin()]
}
}
/// Wendelfläche einer Ortbetontreppe: je Tritt ein geschlossener Block, dessen Untersicht eine echte
/// Schraubenfläche ist (z linear im Winkel, radiale Erzeugende); Oberseite = ebener Tritt.
fn spiral_mesh(s: &StairIn, idx: usize, out: &mut Vec<Mesh>) {
let Some((geo, total_rise)) = geometry_of(s) else { return };
let Some(h) = helix_of(s) else { return };
let n = geo.treads.len();
if n == 0 {
return;
}
let waist = concrete_waist(geo.riser_height);
let z_bottom = s.z_bottom;
let soffit = |frac: f64| z_bottom.max(z_bottom + frac * total_rise - waist);
let d_a = h.sweep / n as f64;
let mut positions: Vec<f64> = Vec::new();
let mut indices: Vec<u32> = Vec::new();
for (i, tr) in geo.treads.iter().enumerate() {
let top = z_bottom + tr.top_rise;
// Ringe entlang des Tritts: (innen unten, aussen unten, Winkel)
let m = HELIX_SEGMENTS;
let base = (positions.len() / 3) as u32;
for j in 0..=m {
let f = j as f64 / m as f64;
let ang = h.a0 + (i as f64 + f) * d_a;
let zb = soffit((i as f64 + f) / n as f64);
for (r, z) in [(h.r_in, zb), (h.r_out, zb), (h.r_in, top), (h.r_out, top)] {
let q = h.at(r, ang);
positions.extend([q[0], q[1], z]);
}
}
// Eckindizes je Ring j: 0 = innen unten, 1 = aussen unten, 2 = innen oben, 3 = aussen oben
let v = |j: usize, k: u32| base + 4 * j as u32 + k;
let mut quad = |a: u32, b: u32, c: u32, d: u32| indices.extend([a, b, c, a, c, d]);
for j in 0..m {
quad(v(j, 0), v(j, 1), v(j + 1, 1), v(j + 1, 0)); // Untersicht (Wendelfläche)
quad(v(j, 2), v(j + 1, 2), v(j + 1, 3), v(j, 3)); // Trittfläche
quad(v(j, 0), v(j + 1, 0), v(j + 1, 2), v(j, 2)); // innere Wange
quad(v(j, 1), v(j, 3), v(j + 1, 3), v(j + 1, 1)); // äussere Wange
}
quad(v(0, 0), v(0, 2), v(0, 3), v(0, 1)); // Setzstufe (Anfang)
quad(v(m, 0), v(m, 1), v(m, 3), v(m, 2)); // Ende
}
if indices.is_empty() {
return;
}
// Drehsinn legt die Orientierung fest: bei negativem Volumen alle Dreiecke wenden.
let mut mesh = Mesh { src: idx, positions, indices };
if signed_volume(&mesh) < 0.0 {
for t in mesh.indices.chunks_mut(3) {
t.swap(1, 2);
}
}
out.push(mesh);
}
fn signed_volume(m: &Mesh) -> f64 {
let p = |i: u32| {
let k = 3 * i as usize;
[m.positions[k], m.positions[k + 1], m.positions[k + 2]]
};
m.indices
.chunks(3)
.map(|t| {
let (a, b, c) = (p(t[0]), p(t[1]), p(t[2]));
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
})
.sum()
}
fn meshes_of(s: &StairIn, idx: usize, out: &mut Vec<Mesh>) {
if s.structure == BETON && s.spiral() {
return spiral_mesh(s, idx, out);
}
if s.structure != BETON || !s.straight() || s.params.run_length <= EPS {
return;
}
@@ -414,8 +539,63 @@ fn strut_box(a: V3, b: V3, half: f64) -> Option<(Vec<f64>, Vec<u32>)> {
Some((positions, indices))
}
/// Handlauf einer Wendeltreppe als Schraubensweep (Quader-Stücke auf der Schraubenlinie) samt
/// Pfosten auf den Trittmitten, in einem Netz je Treppe.
fn spiral_railing(s: &StairIn, idx: usize, out: &mut Vec<Mesh>) {
let Some((geo, total_rise)) = geometry_of(s) else { return };
let Some(h) = helix_of(s) else { return };
let n = geo.treads.len();
if n == 0 {
return;
}
// Laufrichtung = Drehsinn: links der Laufrichtung liegt bei CCW der Innenrand.
let ccw = h.sweep > 0.0;
let sides: &[bool] = match s.railing {
3 => &[true, false],
1 => &[true],
_ => &[false],
};
let half = RAIL_THICK / 2.0;
let mut positions: Vec<f64> = Vec::new();
let mut indices: Vec<u32> = Vec::new();
let mut push = |m: Option<(Vec<f64>, Vec<u32>)>| {
if let Some((p, i)) = m {
let base = (positions.len() / 3) as u32;
positions.extend(p);
indices.extend(i.into_iter().map(|k| k + base));
}
};
let rail_z = |frac: f64| s.z_bottom + frac * total_rise + RAIL_HEIGHT;
for &left in sides {
let r = if left == ccw { h.r_in } else { h.r_out };
let total_seg = n * HELIX_SEGMENTS;
let pt_at = |k: usize| {
let f = k as f64 / total_seg as f64;
let q = h.at(r, h.a0 + f * h.sweep);
[q[0], q[1], rail_z(f)]
};
for k in 0..total_seg {
push(strut_box(pt_at(k), pt_at(k + 1), half));
}
for (i, tr) in geo.treads.iter().enumerate() {
let f = (i as f64 + 0.5) / n as f64;
let q = h.at(r, h.a0 + f * h.sweep);
push(strut_box([q[0], q[1], s.z_bottom + tr.top_rise], [q[0], q[1], rail_z(f)], half));
}
}
if !indices.is_empty() {
out.push(Mesh { src: idx, positions, indices });
}
}
fn railings_of(s: &StairIn, idx: usize, out: &mut Vec<Mesh>) {
if !s.straight() || s.railing == 0 {
if s.railing == 0 {
return;
}
if s.spiral() {
return spiral_railing(s, idx, out);
}
if !s.straight() {
return;
}
let Some((geo, _)) = geometry_of(s) else { return };
@@ -502,7 +682,7 @@ mod tests {
vec![
1.0, // eine Treppe
0.0, 0.0, 0.0, 1.0, 0.0, 3.0, nan, nan, nan, nan, nan, nan, 1.0, 10.0, nan, 0.0, // Parameter
0.0, 2.8, structure, 0.04, nosing, closed, railing,
0.0, 2.8, structure, 0.04, nosing, closed, railing, 0.0,
]
}
@@ -573,7 +753,7 @@ mod tests {
let nan = f64::NAN;
let l = vec![
1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 2.0, 1.5, 1.0, nan, nan, nan, nan, 1.0, 10.0, nan, 0.0, // L
0.0, 2.8, 0.0, 0.04, 0.0, 0.0, 0.0,
0.0, 2.8, 0.0, 0.04, 0.0, 0.0, 0.0, 0.0,
];
let s = slabs(&l, false);
assert!(s.len() >= 10);
@@ -581,9 +761,85 @@ mod tests {
assert!((last.z_top - 1.4).abs() < 1e-9 && last.z_bottom == 0.0);
let w = vec![
1.0, 2.0, 1.0, 0.0, 1.0, 0.0, 1.0, nan, nan, 0.0, 0.0, 1.5, 270.0, 1.0, 12.0, nan, 0.0, // Wendel
0.0, 2.8, 2.0, 0.04, 0.0, 0.0, 3.0,
0.0, 2.8, 2.0, 0.04, 0.0, 0.0, 3.0, 0.0,
];
assert!(!slabs(&w, false).is_empty());
assert!(railings(&w).is_empty()); // Geländer nur für gerade Läufe
assert!(!railings(&w).is_empty()); // Wendelgeländer = Schraubensweep
}
fn spiral(structure: f64, railing: f64, column: f64) -> Vec<f64> {
let nan = f64::NAN;
vec![
1.0, 2.0, 1.0, 0.0, 1.0, 0.0, 1.0, nan, nan, 0.0, 0.0, 1.5, 270.0, 1.0, 12.0, nan, 0.0, // Wendel
0.0, 2.8, structure, 0.04, 0.0, 0.0, railing, column,
]
}
/// Volumen eines geschlossenen Netzes (Divergenzsatz); positiv = Normalen nach aussen.
fn volume(m: &Mesh) -> f64 {
let p = |i: u32| [m.positions[3 * i as usize], m.positions[3 * i as usize + 1], m.positions[3 * i as usize + 2]];
m.indices
.chunks(3)
.map(|t| {
let (a, b, c) = (p(t[0]), p(t[1]), p(t[2]));
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
})
.sum()
}
#[test]
fn wendel_beton_hat_schraubenfläche() {
let ms = slab_meshes(&spiral(1.0, 0.0, 0.0));
assert_eq!(ms.len(), 1);
let m = &ms[0];
// Ringsektor 270° (r 1…2) = 7.07 m², mittlere Dicke ≈ Laufplatte + halbe Steigung
let v = volume(m);
assert!(v > 1.5 && v < 3.2, "Volumen {v}");
// Untersicht folgt der Schraube: an jedem Punkt z_unten = z0 + Winkelanteil·Steighöhe − Dicke (oder 0)
let a0 = 0.0_f64; // Start (1,0) um Zentrum (0,0)
let waist = concrete_waist(2.8 / 12.0);
let mut checked = 0;
for c in m.positions.chunks(3) {
let ang = c[1].atan2(c[0]).rem_euclid(std::f64::consts::TAU) - a0;
let f = ang / (270.0_f64).to_radians();
let on_helix = (0.0..=1.0).contains(&f) && (c[2] - (f * 2.8 - waist).max(0.0)).abs() < 1e-6;
if on_helix {
checked += 1;
}
}
assert!(checked > 12 * 2, "zu wenige Punkte auf der Wendelfläche: {checked}");
// Im Grundriss/3D werden die Tritt-Prismen für Beton nicht doppelt gezeichnet, im Schnitt schon
assert!(slabs(&spiral(1.0, 0.0, 0.0), false).is_empty());
assert!(!slabs(&spiral(1.0, 0.0, 0.0), true).is_empty());
// Drehsinn negativ: Netz bleibt geschlossen/nach aussen orientiert
let mut cw = spiral(1.0, 0.0, 0.0);
cw[12] = -270.0;
assert!(volume(&slab_meshes(&cw)[0]) > 1.5);
}
#[test]
fn wendel_handlauf_ist_schraubensweep() {
let rs = railings(&spiral(1.0, 1.0, 0.0));
assert!(!rs.is_empty());
let zs: Vec<f64> = rs.iter().flat_map(|m| m.positions.chunks(3).map(|c| c[2])).collect();
let (lo, hi) = (zs.iter().cloned().fold(f64::INFINITY, f64::min), zs.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
assert!(lo < 0.95 && hi > 2.8 + 0.85, "{lo} {hi}");
// Handlauf liegt auf einem Kreis (Innenkante r = 1.0 bei Linksgeländer, CCW) — alle Punkte r ≈ 1 ± Querschnitt
let big = rs.iter().max_by_key(|m| m.indices.len()).unwrap();
let r: Vec<f64> = big.positions.chunks(3).map(|c| c[0].hypot(c[1])).collect();
assert!(r.iter().all(|r| (r - 1.0).abs() < 0.05), "Radius streut");
assert!(big.positions.chunks(3).any(|c| c[2] > 2.0) && big.positions.chunks(3).any(|c| c[2] < 1.2));
}
#[test]
fn wendel_mittelsaeule_als_block() {
let none = slabs(&spiral(0.0, 0.0, 0.0), false).len();
let with = slabs(&spiral(0.0, 0.0, 0.12), false);
assert_eq!(with.len(), none + 1);
let col = with.last().unwrap();
assert!(col.z_bottom == 0.0 && (col.z_top - 2.8).abs() < 1e-9 && col.pts.len() >= 12);
assert!(col.pts.iter().all(|p| (p[0].hypot(p[1]) - 0.12).abs() < 1e-9));
// auch bei Beton (Grundriss ohne Tritt-Prismen) und nur für Wendel
assert_eq!(slabs(&spiral(1.0, 0.0, 0.12), false).len(), 1);
}
}
+26
View File
@@ -1127,6 +1127,32 @@ mod dbg_step {
assert!((vol(&mir) - 6.0).abs() < 1e-6, "mir {}", vol(&mir));
}
/// [T7] Rotationskörper um eine waagrechte Planachse (Befehl `revolve`, `cmd_solid.rs`): Zylinder r=1, l=2
/// auf dem Boden; Halbdrehung = halbes Volumen; STEP-Export klappt.
#[test]
fn revolve_um_waagrechte_achse_steht_auf_dem_boden() {
let spec = |angle: f64| SolidSpec::Transform {
m: [-1.0, 0.0, 0.0, 3.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0],
solid: Box::new(SolidSpec::Revolve { profile: vec![0.0, 0.0, 0.0, 2.0, 1.0, 2.0, 1.0, 0.0], cx: 0.0, cy: 0.0, angle_deg: angle }),
};
let vol_zmin = |sp: &SolidSpec| {
let m = solid_mesh_core(sp, 0.005).unwrap();
let p: Vec<[f64; 3]> = m.positions.chunks(3).map(|c| [c[0] as f64, c[1] as f64, c[2] as f64]).collect();
let v: f64 = m.indices.chunks(3).map(|t| {
let (a, b, c) = (p[t[0] as usize], p[t[1] as usize], p[t[2] as usize]);
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
}).sum();
(v, p.iter().map(|q| q[2]).fold(f64::INFINITY, f64::min), p.iter().map(|q| q[2]).fold(f64::NEG_INFINITY, f64::max))
};
let (v, z0, z1) = vol_zmin(&spec(360.0));
assert!((v - 2.0 * std::f64::consts::PI).abs() < 0.02, "Volumen {v}");
assert!(z0.abs() < 1e-3 && (z1 - 2.0).abs() < 1e-3, "z {z0}..{z1}");
let (vh, h0, _) = vol_zmin(&spec(180.0));
assert!((vh - std::f64::consts::PI).abs() < 0.02, "halb {vh}");
assert!(h0 > 0.99, "Halbdrehung steigt nach oben: {h0}");
assert!(export_step_core(&[spec(360.0)], &StepHeader::default()).is_ok());
}
#[test]
fn bool_result_step_dump() {
let dir = std::env::var("STEP_DUMP_DIR").unwrap_or_default();