From 0971db3af6da27e45cc0b768b00a589790696d18 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 19:50:21 +0000 Subject: [PATCH] [217] Kern: Panic durch f64::clamp mit vertauschten/NaN-Grenzen behoben MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit wall_top_at (wall_piece_mesh, 3D, Exporte) klemmte die Oberkante auf [Unterkante, Unterkante + Höhe]; bei negativer/NaN-Höhe panikierte clamp und legte das WASM-Modul lahm. Neu jsnum::clamp_safe / ClampSafe (Grenzen tauschen, NaN wie JS); 28 weitere clamp-Aufrufe mit berechneten Grenzen umgestellt. Regressionstests in Rust und im Robustheitstest. TODO [217] angelegt. --- TODO.md | 5 ++++ src-tauri/core/src/cmd_draw.rs | 3 ++- src-tauri/core/src/cmd_wall_edit.rs | 3 ++- src-tauri/core/src/dim_assoc.rs | 3 ++- src-tauri/core/src/grip_drag.rs | 3 ++- src-tauri/core/src/hlr.rs | 5 ++-- src-tauri/core/src/model3d/tests.rs | 23 ++++++++++++++++ src-tauri/core/src/model3d/walls.rs | 6 ++++- src-tauri/core/src/opening_shape.rs | 11 ++++---- src-tauri/core/src/opening_slide.rs | 7 ++--- src-tauri/core/src/plan/context.rs | 3 ++- src-tauri/core/src/plan/elevation_geom.rs | 5 ++-- src-tauri/core/src/plan/section/shapes.rs | 3 ++- src-tauri/core/src/stairs3d.rs | 3 ++- src-tauri/core/src/sun.rs | 3 ++- src-tauri/core/src/terrain.rs | 7 ++--- src-tauri/core/src/tree.rs | 3 ++- src-tauri/core/src/wall_arc.rs | 3 ++- src-tauri/core/src/wall_bands.rs | 7 ++--- src-tauri/hatchgen/src/jsnum.rs | 33 +++++++++++++++++++++++ src/core/robustness.test.ts | 10 +++++++ 21 files changed, 120 insertions(+), 29 deletions(-) diff --git a/TODO.md b/TODO.md index fbf40030..629bf9f8 100644 --- a/TODO.md +++ b/TODO.md @@ -57,6 +57,11 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC. ### Phase 1 (13.–19.11.): Stabil und baubar - ○ **[206]** Referenz-Ablauf als e2e-Spec (Browser) und als Checkliste für die Mac-Abnahme (`doc/RELEASE-1.0.md`): jeder Schritt oben ein Test; was fehlt, wird hier als Aufgabe eingetragen. · M +- ✓ **[217]** Kern-Panics aus dem Robustheitstest (12.11.): `wall_top_at` nutzte `f64::clamp(base, base+height)` — bei negativer/NaN-Höhe + min > max bzw. NaN → Panic in `wall_piece_mesh` (und über 3D/Exporte, u. a. `exportIfcSpf`). Neu `jsnum::clamp_safe`/`ClampSafe` + (Grenzen tauschen, NaN wie JS); 28 weitere `.clamp(` mit berechneten Grenzen in Kern-Modulen umgestellt. „Zufall 13“-Timeout war + Last (je Fall < 1 s, ganze Datei ~30 s), keine Endlosschleife. Regressionstests: Rust `wandkoerper_mit_kaputter_hoehe_ohne_panic`, + `jsnum::clamp_ohne_panic`, vitest in `robustness.test.ts`. Offen: ganzzahlige `usize::clamp` mit berechneten Grenzen nicht einzeln geprüft. - [30] Release-Workflow lauffähig: macOS universal signiert/notarisiert, Updater, Versionsnummer 1.0.0-beta; [57]/[120] CI auf GitHub grün. - „Mac-Gegenprobe“ (Sammelpunkt unten) für alles im Referenz-Ablauf abarbeiten (Maintainer), Befunde sofort beheben; [194] Texte synchron, [195b] Objektfenster, [190] Cmd+J auf dem Mac bestätigen. diff --git a/src-tauri/core/src/cmd_draw.rs b/src-tauri/core/src/cmd_draw.rs index b19ef2ef..17ac86eb 100644 --- a/src-tauri/core/src/cmd_draw.rs +++ b/src-tauri/core/src/cmd_draw.rs @@ -4,6 +4,7 @@ //! Klickpunkten (Bögen, Kreise, Vielecke, Rundungen, Revisionswolke …), die Vorschau-Formen je Mausschritt //! und die Treffer der Befehle (Tangenten-Objekt, Massketten). Einstieg über `cmd_create`. +use crate::jsnum::ClampSafe; use crate::cmd_create::{ add_op, b_of, circle_pts, find, n_of, normalize, obj, opt_n, opt_p, p_of, pair, point_segment_distance, polyline_edges, pts_of, pv, pvs, s, s_of, seg_len, to_p, Ctx, Preview, V, EPS, @@ -1151,7 +1152,7 @@ fn auto_dims(root: &Map, pr: &Project, ctx: &Ctx, prefix: &str, s // Wandmitte gegenüber der Achse (Referenzlinie links/rechts bzw. -versatz, wie `dim_assoc`). let half = th / 2.0; let shift = match (w.reference_offset, w.reference_line) { - (Some(v), _) => v.clamp(-half, half), + (Some(v), _) => v.clamp_safe(-half, half), (None, Some(WallReferenceLine::Left)) => half, (None, Some(WallReferenceLine::Right)) => -half, _ => 0.0, diff --git a/src-tauri/core/src/cmd_wall_edit.rs b/src-tauri/core/src/cmd_wall_edit.rs index e1686174..e01158e0 100644 --- a/src-tauri/core/src/cmd_wall_edit.rs +++ b/src-tauri/core/src/cmd_wall_edit.rs @@ -22,6 +22,7 @@ //! Grenzen (Schneider) sind die Achsen (Option „Fläche": die beiden Aussenflächen) der übrigen Wände des //! Geschosses, 2D-Linien/-Polylinien (mit Bögen)/-Rechtecke/-Kreise/-Bögen und Achsraster der Ebene. +use crate::jsnum::ClampSafe; use crate::cmd_transform::{IdGen, Shapes}; use crate::json_util::{arr, as_copy, field, js_num, pt, with, with_all}; use crate::joins::Line; @@ -685,7 +686,7 @@ pub fn extend<'a>(root: &'a Project, w: &'a Wall, at: P, face: bool) -> Option(w: &'a Wall, p1: P, p2: P) -> Option> { let mut p = plan(w, false)?; let len = p.ax.len; - let (s1, s2) = (p.ax.local(p1).0.clamp(0.0, len), p.ax.local(p2).0.clamp(0.0, len)); + let (s1, s2) = (p.ax.local(p1).0.clamp_safe(0.0, len), p.ax.local(p2).0.clamp_safe(0.0, len)); let (lo, hi) = if s1 <= s2 { (s1, s2) } else { (s2, s1) }; if hi - lo < MIN_LEN { if lo < MIN_LEN || lo > len - MIN_LEN { diff --git a/src-tauri/core/src/dim_assoc.rs b/src-tauri/core/src/dim_assoc.rs index fec870f2..88b59649 100644 --- a/src-tauri/core/src/dim_assoc.rs +++ b/src-tauri/core/src/dim_assoc.rs @@ -25,6 +25,7 @@ //! Bezüge nur, wenn das Element mitkopiert wird (auf die Kopie umgeschrieben). //! - **Lösen** ([`detach_ops`], Befehl „Bemassung lösen"): `refs` weg, `pts` bleibt. +use crate::jsnum::ClampSafe; use crate::document::Lookup; use crate::model::{DimFeature, DimRef}; use crate::ops::Op; @@ -96,7 +97,7 @@ fn wall_geo(lk: &Lookup, w: &Value) -> Option { let total: f64 = layers.iter().sum(); let half = total / 2.0; let ref_off = match (num(w.get("referenceOffset")), str_of(w, "referenceLine")) { - (Some(v), _) => v.clamp(-half, half), + (Some(v), _) => v.clamp_safe(-half, half), (None, Some("left")) => half, (None, Some("right")) => -half, _ => 0.0, diff --git a/src-tauri/core/src/grip_drag.rs b/src-tauri/core/src/grip_drag.rs index d9bc04c0..393c9c94 100644 --- a/src-tauri/core/src/grip_drag.rs +++ b/src-tauri/core/src/grip_drag.rs @@ -15,6 +15,7 @@ //! //! Zahlen wie in JS (`jsnum`: min/max/round, Trigonometrie über libm); NaN steht für „fehlt". +use crate::jsnum::ClampSafe; use crate::jsmath::hypot2; use crate::jsnum; use std::f64::consts::PI; @@ -351,7 +352,7 @@ fn arc_slide_sheet(a: &crate::wall_arc::WallArc, u: P, position: f64, width: f64 let q = a.point(p + width / 2.0, 0.0); q.x * u.0 + q.y * u.1 }; - let p0 = position.clamp(0.0, hi); + let p0 = position.clamp_safe(0.0, hi); if du == 0.0 { return Some((p0, 0.0)); } diff --git a/src-tauri/core/src/hlr.rs b/src-tauri/core/src/hlr.rs index a6647f88..39ff0139 100644 --- a/src-tauri/core/src/hlr.rs +++ b/src-tauri/core/src/hlr.rs @@ -30,6 +30,7 @@ //! //! Die sichtbaren Teilflächen (Füllungen konsistent zu den Kanten) rechnet `hlr_fill.rs`. +use crate::jsnum::ClampSafe; use std::collections::HashMap; use std::hash::{BuildHasherDefault, Hasher}; @@ -318,7 +319,7 @@ fn feature_edges(faces: &[Face], prep: &[Option], covered: &[bool], opts: ends.push(if i > 0 && entries[i - 1].0 == x.0 { ends[i - 1].max(end) } else { end }); } let diag = if count > 0 { norm(sub(hi, lo)).max(tol) } else { 1.0 }; - let h = if count > 0 { (total / count as f64).clamp(diag / 512.0, diag / 2.0).max(tol * 16.0) } else { 1.0 }; + let h = if count > 0 { (total / count as f64).clamp_safe(diag / 512.0, diag / 2.0).max(tol * 16.0) } else { 1.0 }; let cell = |x: f64, k: usize| ((x - lo[k]) / h).floor() as i64; let range = |e: &Edge, k: usize| (cell(e.a[k].min(e.b[k]) - tol, k), cell(e.a[k].max(e.b[k]) + tol, k)); let mut grid: FxMap<(i64, i64, i64), Vec> = FxMap::default(); @@ -590,7 +591,7 @@ impl OccGrid { if c.is_nan() { 0 } else { - c.clamp(0.0, (self.n[k] - 1) as f64) as usize + c.clamp_safe(0.0, (self.n[k] - 1) as f64) as usize } } } diff --git a/src-tauri/core/src/model3d/tests.rs b/src-tauri/core/src/model3d/tests.rs index 8b146e7f..2ab045a6 100644 --- a/src-tauri/core/src/model3d/tests.rs +++ b/src-tauri/core/src/model3d/tests.rs @@ -635,3 +635,26 @@ fn verbau_im_3d_klasse_und_pick() { assert!(g.context_meshes.iter().any(|m| m.context_object_id == "bg" && m.tris.len() == 24)); assert!(pick_geometry(&mk(false)).unwrap().context_meshes.iter().all(|m| m.context_object_id != "bg" || m.tris.len() != 24), "Klasse aus: kein Verbau-Pick"); } + +/// [217] Wandkörper mit negativer/NaN-Höhe und ebener Oberkante: `wall_top_at`/`wall_piece_mesh` dürfen nicht +/// panikieren (`f64::clamp` mit min > max oder NaN-Grenzen legte das WASM-Modul lahm). +#[test] +fn wandkoerper_mit_kaputter_hoehe_ohne_panic() { + use crate::plan::walls::tests::pocket_project; + let ws = emit_walls(&pocket_project(DoorTypeKind::Schiebe, None, 1.0), false).unwrap(); + let mut w = ws[0].clone(); + w.top_plane = Some([3.0, 0.1, 0.0]); + for h in [-3.0, f64::NAN, 0.0, f64::INFINITY, -1e300] { + w.height = h; + let _ = wall_top_at(&w, [0.0, 0.0]); + let _ = wall_piece_mesh(&w); + let _ = wall_piece_volume(&w); + } + for c in [[f64::NAN, 0.0, 0.0], [f64::INFINITY, 1.0, 1.0]] { + w.height = 2.5; + w.top_plane = Some(c); + assert!(wall_top_at(&w, [1.0, 1.0]).is_finite()); + } + w.base_elevation = f64::NAN; + let _ = wall_piece_mesh(&w); +} diff --git a/src-tauri/core/src/model3d/walls.rs b/src-tauri/core/src/model3d/walls.rs index d9689316..e4c98ee3 100644 --- a/src-tauri/core/src/model3d/walls.rs +++ b/src-tauri/core/src/model3d/walls.rs @@ -937,7 +937,11 @@ pub(crate) fn wall_footprint(w: &RWall) -> Option<[[f64; 2]; 4]> { pub(crate) fn wall_top_at(w: &RWall, q: [f64; 2]) -> f64 { let zt = w.base_elevation + w.height; match w.top_plane { - Some(c) => (c[0] + c[1] * (q[0] - w.start[0]) + c[2] * (q[1] - w.start[1])).clamp(w.base_elevation, zt), + // Negative Höhe oder NaN: Grenzen vertauscht bzw. ungültig -> ebene Oberkante, kein Panic. + Some(c) => { + let z = crate::jsnum::clamp_safe(c[0] + c[1] * (q[0] - w.start[0]) + c[2] * (q[1] - w.start[1]), w.base_elevation, zt); + if z.is_finite() { z } else { zt } + } None => zt, } } diff --git a/src-tauri/core/src/opening_shape.rs b/src-tauri/core/src/opening_shape.rs index 6356b100..00107367 100644 --- a/src-tauri/core/src/opening_shape.rs +++ b/src-tauri/core/src/opening_shape.rs @@ -11,6 +11,7 @@ //! Deckenoberkante (Mittelpunkt `hostPoint`), Breite längs der Traufe, Höhe das Gefälle hinauf. Die //! Öffnung schneidet alle Schichten senkrecht zur Fläche (Normale `n`). +use crate::jsnum::ClampSafe; use crate::model::*; pub type P = [f64; 2]; @@ -61,7 +62,7 @@ pub fn outline(shape: OpeningShape, rise: Option, w: f64, h: f64) -> Option match shape { OpeningShape::Rundbogen | OpeningShape::Segmentbogen => { let r = if shape == OpeningShape::Rundbogen { w / 2.0 } else { rise.unwrap_or(w / 6.0) }; - let r = r.clamp(MIN * 10.0, (w / 2.0).min(h)); + let r = r.clamp_safe(MIN * 10.0, (w / 2.0).min(h)); let big = (w * w / 4.0 + r * r) / (2.0 * r); let c = [w / 2.0, h - big]; let a0 = (big - r).atan2(w / 2.0); @@ -70,7 +71,7 @@ pub fn outline(shape: OpeningShape, rise: Option, w: f64, h: f64) -> Option arc(&mut pts, c, big, a0, std::f64::consts::PI - a0); } OpeningShape::Spitzbogen => { - let r = rise.unwrap_or(w * 3f64.sqrt() / 2.0).clamp(w / 2.0, h.max(w / 2.0)).min(h); + let r = rise.unwrap_or(w * 3f64.sqrt() / 2.0).clamp_safe(w / 2.0, h.max(w / 2.0)).min(h); if r < w / 2.0 - MIN { // Zu niedrig für einen Spitzbogen: Rundbogen. return outline(OpeningShape::Rundbogen, None, w, h); @@ -93,11 +94,11 @@ pub fn outline(shape: OpeningShape, rise: Option, w: f64, h: f64) -> Option } } OpeningShape::Schraeg => { - let d = rise.unwrap_or(w / 2.0).clamp(-h, h); + let d = rise.unwrap_or(w / 2.0).clamp_safe(-h, h); pts = vec![[0.0, 0.0], [w, 0.0], [w, h - (-d).max(0.0)], [0.0, h - d.max(0.0)]]; } OpeningShape::Giebel => { - let r = rise.unwrap_or(w / 2.0).clamp(0.0, h); + let r = rise.unwrap_or(w / 2.0).clamp_safe(0.0, h); pts = vec![[0.0, 0.0], [w, 0.0], [w, h - r], [w / 2.0, h], [0.0, h - r]]; } _ => return None, @@ -179,7 +180,7 @@ pub fn layer_fill_quads(poly: &[P], w: f64, h: f64, s: [f64; 4]) -> Vec<[P; 4]> return fill_quads(poly, w, h); } let (ww, hh) = (w + s[0] + s[1], h + s[2] + s[3]); - let moved: Vec

= outset_sides(poly, s).into_iter().map(|q| [(q[0] + s[0]).clamp(0.0, ww), (q[1] + s[3]).clamp(0.0, hh)]).collect(); + let moved: Vec

= outset_sides(poly, s).into_iter().map(|q| [(q[0] + s[0]).clamp_safe(0.0, ww), (q[1] + s[3]).clamp_safe(0.0, hh)]).collect(); fill_quads(&dedup(moved), ww, hh).into_iter().map(|q| q.map(|c| [c[0] - s[0], c[1] - s[3]])).collect() } diff --git a/src-tauri/core/src/opening_slide.rs b/src-tauri/core/src/opening_slide.rs index 1e1b38cc..13aab1d5 100644 --- a/src-tauri/core/src/opening_slide.rs +++ b/src-tauri/core/src/opening_slide.rs @@ -7,6 +7,7 @@ //! einen Steg von [`MIN_WEB`]; schon überlappende Daten (Bestand) bleiben, wie sie sind. //! - **Dach-/Deckenöffnungen**: Mittelpunkt im Umriss des Wirts halten ([`clamp_inside`]). +use crate::jsnum::ClampSafe; use crate::json_util::{field, num_of}; use crate::ops::id_of; use crate::wall_arc::WallArc; @@ -84,7 +85,7 @@ impl Axis { Axis::Line { s, u, .. } => (p.0 - s.0) * u.0 + (p.1 - s.1) * u.1, Axis::Arc(a) => a.local(kernel2d::Vec2::new(p.0, p.1)).0, }; - let q = self.point(t.clamp(0.0, self.len()), 0.0); + let q = self.point(t.clamp_safe(0.0, self.len()), 0.0); (t, crate::jsmath::hypot2(p.0 - q.0, p.1 - q.1)) } } @@ -123,7 +124,7 @@ pub fn place(root: &Map, host: &str, len: f64, width: f64, from: return None; } let max = max.max(0.0); - let want = want.clamp(0.0, max); + let want = want.clamp_safe(0.0, max); // Gesperrte Anfangslagen je Nachbar: offenes Intervall (lo, hi). let blocked: Vec<(f64, f64)> = neighbours(root, host, skip).into_iter().map(|(a, b)| (a - width - MIN_WEB, b + MIN_WEB)).collect(); let inside = |x: f64, (lo, hi): (f64, f64)| x > lo + EPS && x < hi - EPS; @@ -141,7 +142,7 @@ pub fn place(root: &Map, host: &str, len: f64, width: f64, from: .chain(blocked.iter().flat_map(|(lo, hi)| [*lo, *hi])) .filter(|x| free(*x)) .min_by(|a, b| (a - want).abs().total_cmp(&(b - want).abs())) - .map(|x| Placed { position: x.clamp(0.0, max), clamped: (x - want).abs() > EPS }) + .map(|x| Placed { position: x.clamp_safe(0.0, max), clamped: (x - want).abs() > EPS }) } /// Öffnung `o` in ihrer Wand auf den Anfang `want` setzen (gleitend ab ihrer jetzigen Lage; geklemmt auf diff --git a/src-tauri/core/src/plan/context.rs b/src-tauri/core/src/plan/context.rs index aa76990a..06d0ca42 100644 --- a/src-tauri/core/src/plan/context.rs +++ b/src-tauri/core/src/plan/context.rs @@ -3,6 +3,7 @@ //! Symbole der Schnitt-/Ansichtsebenen — Rust-Gegenstück zu `generatePlan/{context,sections}.ts`. //! Die Geometrie liegt in `plan_misc.rs`; die Meshes werden direkt aus dem Dokument gelesen. +use crate::jsnum::ClampSafe; use super::domains::Ctx; use super::overrides::{js_space, js_trim}; use super::prim::Primitive; @@ -392,7 +393,7 @@ impl Iso { /// Punkt bei Bogenlänge `s` (geschlossen: modulo Länge). fn at(&self, s: f64) -> [f64; 2] { let l = self.len(); - let s = if self.closed && l > 0.0 { s.rem_euclid(l) } else { s.clamp(0.0, l) }; + let s = if self.closed && l > 0.0 { s.rem_euclid(l) } else { s.clamp_safe(0.0, l) }; let i = self.cum.partition_point(|c| *c <= s).clamp(1, self.pts.len() - 1); let (a, b) = (self.pts[i - 1], self.pts[i]); let d = self.cum[i] - self.cum[i - 1]; diff --git a/src-tauri/core/src/plan/elevation_geom.rs b/src-tauri/core/src/plan/elevation_geom.rs index 133a75c1..7b6f5b46 100644 --- a/src-tauri/core/src/plan/elevation_geom.rs +++ b/src-tauri/core/src/plan/elevation_geom.rs @@ -52,6 +52,7 @@ //! `[n, (verlStart, verlEnde) × n]`: Wandenden bis zur Aussenfläche der dicksten anstossenden Wand //! desselben Geschosses (`wallCornerExtensions`). +use crate::jsnum::ClampSafe; use crate::jsmath::{hypot, hypot2}; use crate::jsnum::{max, min, round}; use crate::ugrid::Grid1; @@ -209,7 +210,7 @@ impl OccCells { return 0; } let c = ((u - self.lo) * self.inv).floor(); - if c.is_nan() { 0 } else { c.clamp(0.0, (self.cells.len() - 1) as f64) as usize } + if c.is_nan() { 0 } else { c.clamp_safe(0.0, (self.cells.len() - 1) as f64) as usize } } } @@ -617,7 +618,7 @@ fn wall_faces(f: &Frame, w: &[f64], src: usize, out: &mut Vec) { let corner = |s_along: f64, t_off: f64, y: f64| -> V3 { let (x, z) = (sx + a_hat[0] * s_along + n_hat[0] * t_off, sz + a_hat[2] * s_along + n_hat[2] * t_off); let y = match plane { - Some(c) if y == zt => (c[0] + c[1] * (x - sx) + c[2] * (z - sz)).clamp(zb, zt), + Some(c) if y == zt => (c[0] + c[1] * (x - sx) + c[2] * (z - sz)).clamp_safe(zb, zt), _ => y, }; [x, y, z] diff --git a/src-tauri/core/src/plan/section/shapes.rs b/src-tauri/core/src/plan/section/shapes.rs index 2b81eba9..63190c44 100644 --- a/src-tauri/core/src/plan/section/shapes.rs +++ b/src-tauri/core/src/plan/section/shapes.rs @@ -2,6 +2,7 @@ //! Monolith-Vereinigung der Platten, Laufplatten gerader Betontreppen ([G1]) und Schnitt parallel zur //! Wand durch die Leibungen ([106]). Aufgerufen von `compute_section()` (`mod.rs`). +use crate::jsnum::ClampSafe; use super::*; /// `appendRoofSections`: Schnittspur der Dachflächen, je Schicht ein Band. @@ -34,7 +35,7 @@ pub(super) fn shaped_wall_cuts(cuts: &mut [Cut], p: &Project, walls_r: &[RWall], if along < from - 1e-4 || along > to + 1e-4 { continue; } - let along = along.clamp(from, to); + let along = along.clamp_safe(from, to); let (zb, zt) = opening_extent(p, wall, o); let Some(poly) = crate::opening_shape::opening_outline(o, to - from, zt - zb) else { continue }; let Some((lo, hi)) = crate::opening_shape::v_range(&poly, along - from) else { continue }; diff --git a/src-tauri/core/src/stairs3d.rs b/src-tauri/core/src/stairs3d.rs index 73833aa8..9d17bd15 100644 --- a/src-tauri/core/src/stairs3d.rs +++ b/src-tauri/core/src/stairs3d.rs @@ -13,6 +13,7 @@ //! (Laufplatte, Geländer): `[n, (treppe, nPos, nIdx, positionen…, indizes…)…]`. `treppe` ist der //! Index in der Eingabe. Unsinn (NaN, kaputte Puffer) ergibt ein leeres Ergebnis. +use crate::jsnum::ClampSafe; use crate::flat_read::Reader; use crate::jsmath::{hypot, hypot2}; use crate::mesh3d::Mesh; @@ -762,7 +763,7 @@ pub fn stringers(buf: &[f64]) -> Vec { let pitch = |run: f64| base + rise + run * lift / len; let top_end = base + lift + STRINGER_ABOVE; // Seitenprofil (Lauf, Höhe), gegen den Uhrzeigersinn. - let rf = ((STRINGER_BELOW - rise) * len / lift).clamp(0.0, len); + let rf = ((STRINGER_BELOW - rise) * len / lift).clamp_safe(0.0, len); let prof = [(0.0, base), (rf, base), (len, pitch(len) - STRINGER_BELOW), (len, top_end), (len - going, top_end), (0.0, pitch(0.0) + STRINGER_ABOVE)]; let sides: Vec = geo.treads[r.clone()].iter().flat_map(|t| t.pts.iter().map(|q| ax.side_of(pt(q)))).collect(); let (lo, hi) = sides.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &x| (a.min(x), b.max(x))); diff --git a/src-tauri/core/src/sun.rs b/src-tauri/core/src/sun.rs index 9d69e91b..3ecd570b 100644 --- a/src-tauri/core/src/sun.rs +++ b/src-tauri/core/src/sun.rs @@ -9,6 +9,7 @@ //! Flächen-Körper, je Empfänger (Gelände, Decken, Dachflächen unter dem Schnitt) projiziert. //! • [`without_holes`]: Polygon mit Löchern → lochfreie Teile gleicher Fläche (Plan-Primitiv). +use crate::jsnum::ClampSafe; use crate::flat::{Polygon, Ring}; use crate::polygon_bool; @@ -890,7 +891,7 @@ fn wall_gaps(os: &[&crate::model::Opening], axis: f64, zb: f64, zt: f64) -> Vec< let (ua, ub) = (w * i as f64 / n as f64, w * (i + 1) as f64 / n as f64); let (Some(ra), Some(rb)) = (crate::opening_shape::v_range(&shape, ua + eps), crate::opening_shape::v_range(&shape, ub - eps)) else { continue }; let (lo, hi) = (ob + ra.0.max(rb.0), ot.min(ob + ra.1.min(rb.1))); - let (u0, u1) = ((pos + ua).clamp(from, to), (pos + ub).clamp(from, to)); + let (u0, u1) = ((pos + ua).clamp_safe(from, to), (pos + ub).clamp_safe(from, to)); if u1 - u0 >= MIN_GAP && hi - lo > MIN_GAP { out.push([u0, u1, lo, hi]); } diff --git a/src-tauri/core/src/terrain.rs b/src-tauri/core/src/terrain.rs index e3d1a087..56343a6c 100644 --- a/src-tauri/core/src/terrain.rs +++ b/src-tauri/core/src/terrain.rs @@ -15,6 +15,7 @@ //! Höhen sind Rohwerte des Netzes (bei swissALTI3D/DXF meist m ü. M.); den Bezug zum Modell (±0.00) //! liefert [`datum`]. +use crate::jsnum::ClampSafe; use crate::delaunay::{orient2d, triangulate}; use std::collections::{HashMap, HashSet, VecDeque}; @@ -625,7 +626,7 @@ pub fn fix_flat(t: &mut Tin, fixed: &HashSet<(u32, u32)>, interval: f64) { up = true; down = true; } - let zm = z0 + (est / 3.0 - z0).clamp(if down { -cap } else { 0.0 }, if up { cap } else { 0.0 }); + let zm = z0 + (est / 3.0 - z0).clamp_safe(if down { -cap } else { 0.0 }, if up { cap } else { 0.0 }); let k = t.xy.len() as u32; t.xy.push(m); t.z.push(zm); @@ -668,11 +669,11 @@ pub fn refine(t: &mut Tin, fixed: &mut HashSet<(u32, u32)>, interval: f64, tol: let h = lin + ((g[a][0] - g[b][0]) * d[0] + (g[a][1] - g[b][1]) * d[1]) / 8.0; if (za - zb).abs() < 1e-9 { let (olo, ohi) = opp.get(&e).copied().unwrap_or((za, za)); - za + (h - za).clamp((olo - za).max(-cap).min(0.0), (ohi - za).min(cap).max(0.0)) + za + (h - za).clamp_safe((olo - za).max(-cap).min(0.0), (ohi - za).min(cap).max(0.0)) } else { // streng zwischen den Enden (sonst entstünden neue flache Dreiecke) let (lo, hi) = (za.min(zb), za.max(zb)); - h.clamp(lo + 0.1 * (hi - lo), hi - 0.1 * (hi - lo)) + h.clamp_safe(lo + 0.1 * (hi - lo), hi - 0.1 * (hi - lo)) } }; if (zm - lin).abs() > tol || len > max_edge { diff --git a/src-tauri/core/src/tree.rs b/src-tauri/core/src/tree.rs index 756e3138..1155667b 100644 --- a/src-tauri/core/src/tree.rs +++ b/src-tauri/core/src/tree.rs @@ -7,6 +7,7 @@ //! sonst auf der UK des Geschosses; dazu `baseOffset`. Höhen über dem Fuss: Kronenansatz `crownBase`, //! Spitze `height`. +use crate::jsnum::ClampSafe; use crate::jsnum; use crate::model::*; @@ -62,7 +63,7 @@ impl TreeGeom { // Stamm nie dicker als die Krone. let trunk_r = jsnum::min(pos(t.trunk_diameter, DEFAULT_TRUNK_DIAMETER) / 2.0, crown_r * 0.8); // Kronenansatz zwischen 0 und 90 % der Höhe. - let cb = if t.crown_base.is_finite() { t.crown_base.clamp(0.0, 0.9 * h) } else { jsnum::min(DEFAULT_CROWN_BASE, 0.5 * h) }; + let cb = if t.crown_base.is_finite() { t.crown_base.clamp_safe(0.0, 0.9 * h) } else { jsnum::min(DEFAULT_CROWN_BASE, 0.5 * h) }; Some(TreeGeom { c: [t.position.x, t.position.y], base, foot: base, trunk_r, crown_r, crown_bottom: base + cb, top: base + h, shape: t.shape }) } diff --git a/src-tauri/core/src/wall_arc.rs b/src-tauri/core/src/wall_arc.rs index 545f5266..64a3c360 100644 --- a/src-tauri/core/src/wall_arc.rs +++ b/src-tauri/core/src/wall_arc.rs @@ -14,6 +14,7 @@ //! zwischen denen gerade Teilwände mit radialen Gehrungs-Schnitten liegen; die Versätze eines //! Sehnenpolygons sind wieder Sehnenpolygone, die Teilkörper schliessen also lückenlos. +use crate::jsnum::ClampSafe; use crate::joins::Line; use kernel2d::{add, dot, scale, sub, Vec2}; use std::f64::consts::PI; @@ -483,7 +484,7 @@ pub fn chord_walls(w: &crate::wall_bands::WallIn, arc: &WallArc) -> Vec = (0..=steps).map(|i| if i == steps { b } else { a + (b - a) * i as f64 / steps as f64 }).collect(); - let inner = |s: f64| s.clamp(a + 1e-6, b - 1e-6); + let inner = |s: f64| s.clamp_safe(a + 1e-6, b - 1e-6); let fac: Vec = ts.iter().map(|&s| t.at(pt(inner(s)))).collect(); // Läufe gleicher Bereiche und die Grenzen dazwischen (Achsmass, Schnittlinie). let mut runs: Vec<(Fac, f64, Option)> = vec![(fac[0], a, cut_a)]; @@ -735,7 +736,7 @@ fn strip_tops(w: &WallIn, t: &Tops, u: Vec2, n: Vec2, off: f64, th: f64, a: f64, } } let prev = runs.last().map_or(a, |r| r.1); - let s_cut = line.and_then(|l| band_cut_distance(w, u, n, off, &l)).filter(|x| x.is_finite()).unwrap_or(sm).clamp(prev, b); + let s_cut = line.and_then(|l| band_cut_distance(w, u, n, off, &l)).filter(|x| x.is_finite()).unwrap_or(sm).clamp_safe(prev, b); runs.push((fb, s_cut, line)); } let k_last = runs.len() - 1; @@ -972,7 +973,7 @@ pub fn wall_bands(w: &WallIn, ctx: &FloorContext) -> Vec { } else { let mut cursor = lo; for c in &cutouts { - let (cf, ct) = (c.from.clamp(lo, hi), c.to.clamp(lo, hi)); + let (cf, ct) = (c.from.clamp_safe(lo, hi), c.to.clamp_safe(lo, hi)); let seg_from = cursor.max(cf); if cf > cursor { seg(&mut em, cursor, cf, z_bottom, z_top); diff --git a/src-tauri/hatchgen/src/jsnum.rs b/src-tauri/hatchgen/src/jsnum.rs index 0bc61f98..eb7ede9f 100644 --- a/src-tauri/hatchgen/src/jsnum.rs +++ b/src-tauri/hatchgen/src/jsnum.rs @@ -48,6 +48,27 @@ pub fn max(a: f64, b: f64) -> f64 { } } +/// `Math.min(Math.max(x, a), b)` ohne Panic: vertauschte Grenzen (a > b) werden getauscht, NaN in `x` +/// oder einer Grenze liefert NaN (wie JS; `f64::clamp` würde bei min > max oder NaN-Grenzen panikieren). +#[inline] +pub fn clamp_safe(x: f64, a: f64, b: f64) -> f64 { + let (lo, hi) = if a > b { (b, a) } else { (a, b) }; + min(max(x, lo), hi) +} + +/// Methodenform von [`clamp_safe`]: `x.clamp_safe(a, b)` statt `x.clamp(a, b)` bei Grenzen, die aus Modellwerten +/// berechnet werden (können vertauscht oder NaN sein). +pub trait ClampSafe { + fn clamp_safe(self, a: f64, b: f64) -> f64; +} + +impl ClampSafe for f64 { + #[inline] + fn clamp_safe(self, a: f64, b: f64) -> f64 { + clamp_safe(self, a, b) + } +} + /// `Math.round(x)`: halbe Werte Richtung +∞, −0 bleibt −0, Werte in (−0.5, 0) → −0. #[inline] pub fn round(x: f64) -> f64 { @@ -87,6 +108,18 @@ pub fn to_int32(x: f64) -> i32 { mod tests { use super::*; + #[test] + fn clamp_ohne_panic() { + assert_eq!(clamp_safe(5.0, 0.0, 3.0), 3.0); + assert_eq!(clamp_safe(-5.0, 0.0, 3.0), 0.0); + assert_eq!(clamp_safe(1.0, 3.0, 0.0), 1.0, "vertauschte Grenzen werden getauscht"); + assert_eq!(clamp_safe(9.0, 3.0, 0.0), 3.0); + assert!(clamp_safe(f64::NAN, 0.0, 1.0).is_nan()); + assert!(clamp_safe(0.5, f64::NAN, 1.0).is_nan()); + assert!(clamp_safe(0.5, 0.0, f64::NAN).is_nan()); + assert_eq!(clamp_safe(f64::INFINITY, 0.0, 1.0), 1.0); + } + #[test] fn rundung_wie_js() { assert_eq!(round(2.5), 3.0); diff --git a/src/core/robustness.test.ts b/src/core/robustness.test.ts index 5f76129a..841934a7 100644 --- a/src/core/robustness.test.ts +++ b/src/core/robustness.test.ts @@ -362,6 +362,16 @@ describe("Kern robust gegen kaputte Projekte", () => { }, 240_000); } + it("[217] Wände mit negativer/NaN-Höhe unter dem Dach: 3D und Exporte ohne Kern-Panic", async () => { + for (const h of [-3, NaN, 0, -1e300]) { + const p = clone(richProject()); + for (const w of list(p, "walls")) w.height = h; + for (const r of list(p, "roofs")) r.floorId = list(p, "walls")[0]?.floorId ?? r.floorId; + const errors = await runAll(p as unknown as Project); + expect(errors, `Höhe ${h}`).toEqual([]); + } + }, 120_000); + it("hängender Wandtyp: Plan wie mit dem Rückfall-Typ (kein Werfen, Wand bleibt sichtbar)", () => { const p = clone(sampleProject); p.walls[0].wallTypeId = "nope";