[K1][K2] Bögen und Treppen nach Rust: bulge.ts und stair.ts nur noch Fassade über den Kern
Bögen: Tessellation, Drei-Punkt-/Radius-/Tangenten-Bogen, bulgePointAt und ganze Polylinien (bulge_polyline_points) in kernel2d; TS-Formeln gelöscht, Aufrufer mit Segmentschleifen nutzen bulgePolylinePoints. Treppen: stair_geometry um Referenz (links/rechts) ergänzt, stair_outline neu; stairCut/stairBBox/defaultStepCount über flache Puffer; pointInPolygon/pointHitsStair (ungenutzt) gelöscht.
This commit is contained in:
21 files changed
+1395
-734
No files matched your search
@@ -26,11 +26,13 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
- ◐ **[K1] 2D-Geometrie.** (27.10.) Polygon-Booleans aus Rust (i_overlay) ersetzen `polygon-clipping`
|
||||
(entfernt). `kernel2d` produktiv aus Rust (`kernel2d.ts` nur Fassade, Paritätstest weg; gemessen nicht
|
||||
langsamer). Schatten, Baurecht (exakter Puffer statt Kapsel), Aussenbemassung, Kennzahlen in Rust; die
|
||||
SIA-416-Zuordnung (`roomArea.ts::balance`) und `checkRoomProgram` bleiben vorerst TS. Offen: `bulge.ts`
|
||||
(Bogenformeln doppelt), Triangulierung, Straight Skeleton [B2]. · M
|
||||
SIA-416-Zuordnung (`roomArea.ts::balance`) und `checkRoomProgram` bleiben vorerst TS. `bulge.ts` ist Fassade über den
|
||||
Rust-Kern (`bulge_polyline_points` für ganze Polylinien; `hasRealBulge`/`pointOnCircle` bleiben TS,
|
||||
Einzeiler). Offen: Triangulierung, Straight Skeleton [B2]. · M
|
||||
- ◐ **[K2] Geometrie-Ableitungen.** (27.10.) Dachgeometrie in Rust (`roof.rs`, `roof_skeleton.rs`;
|
||||
`roofSkeleton.ts` gelöscht, ~2× schneller, Ergebnis bitgleich). Offen: Wand-Joins/-Bänder (`toWalls3d`),
|
||||
Treppen, Räume. · L
|
||||
`roofSkeleton.ts` gelöscht, ~2× schneller, Ergebnis bitgleich). Treppen in Rust (`stair_geometry`,
|
||||
`stair_outline`, `stair_cut`; `stair.ts` Fassade, 27.10.). Offen: Wand-Joins/-Bänder (`toWalls3d`),
|
||||
Räume. · L
|
||||
- ○ **[K3] Plan, Schnitt, Ansicht in Rust**, Primitive direkt an render2d (ohne TS-Umweg). · L
|
||||
- ○ **[K4] Modell und Ops in Rust** [2]; TS bekommt die Typen generiert (z. B. `ts-rs`). · XL
|
||||
- **Fertig wenn** (je Etappe): TS-Fassung gelöscht, `npm run check` grün, App/CLI/IFC unverändert.
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
//! Bogen-Formeln (DXF-bulge) als flache Aufrufe für `src/geometry/bulge.ts`. Die Mathematik steht
|
||||
//! in `kernel2d` (`bulge.rs`); hier nur die Eingabe-Prüfung (NaN/∞ → neutrales Ergebnis, nie Panic)
|
||||
//! und die flache Kodierung der Ergebnisse:
|
||||
//! - Bogen `[cx, cy, r, a0, a1, sweep]`, „kein Bogen" = leerer Puffer
|
||||
//! - CCW-Bogen `[cx, cy, r, a0, a1]`, „kein Bogen" = leerer Puffer
|
||||
//! - Punkte `[x0, y0, x1, y1, …]`
|
||||
|
||||
use kernel2d::{self as k, ArcParams, Vec2};
|
||||
|
||||
fn v(x: f64, y: f64) -> Vec2 {
|
||||
Vec2::new(x, y)
|
||||
}
|
||||
|
||||
fn finite(xs: &[f64]) -> bool {
|
||||
xs.iter().all(|x| x.is_finite())
|
||||
}
|
||||
|
||||
fn flat_pts(pts: &[Vec2]) -> Vec<f64> {
|
||||
pts.iter().flat_map(|p| [p.x, p.y]).collect()
|
||||
}
|
||||
|
||||
fn flat_arc(a: Option<ArcParams>) -> Vec<f64> {
|
||||
a.map(|a| vec![a.center.x, a.center.y, a.r, a.a0, a.a1]).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn arc(ax: f64, ay: f64, bx: f64, by: f64, bulge: f64) -> Vec<f64> {
|
||||
if !finite(&[ax, ay, bx, by, bulge]) {
|
||||
return Vec::new();
|
||||
}
|
||||
match k::bulge_arc(v(ax, ay), v(bx, by), bulge) {
|
||||
Some(a) if finite(&[a.center.x, a.center.y, a.r, a.a0, a.a1, a.sweep]) => {
|
||||
vec![a.center.x, a.center.y, a.r, a.a0, a.a1, a.sweep]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn arc_points(ax: f64, ay: f64, bx: f64, by: f64, bulge: f64) -> Vec<f64> {
|
||||
if !finite(&[ax, ay, bx, by]) {
|
||||
return vec![ax, ay, bx, by];
|
||||
}
|
||||
let bulge = if bulge.is_finite() { bulge } else { 0.0 };
|
||||
flat_pts(&k::bulge_arc_points(v(ax, ay), v(bx, by), bulge))
|
||||
}
|
||||
|
||||
/// `pts` = `[x0, y0, …]`, `bulge` je Kante (fehlende/NaN-Einträge = Gerade).
|
||||
pub fn polyline_points(pts: &[f64], bulge: &[f64], closed: bool) -> Vec<f64> {
|
||||
if !finite(pts) {
|
||||
return Vec::new();
|
||||
}
|
||||
let p: Vec<Vec2> = pts.chunks_exact(2).map(|c| v(c[0], c[1])).collect();
|
||||
let b: Vec<f64> = bulge.iter().map(|x| if x.is_finite() { *x } else { 0.0 }).collect();
|
||||
flat_pts(&k::bulge_polyline_points(&p, &b, closed))
|
||||
}
|
||||
|
||||
pub fn from_sagitta_point(ax: f64, ay: f64, bx: f64, by: f64, px: f64, py: f64) -> f64 {
|
||||
if !finite(&[ax, ay, bx, by, px, py]) {
|
||||
return 0.0;
|
||||
}
|
||||
k::bulge_from_sagitta_point(v(ax, ay), v(bx, by), v(px, py))
|
||||
}
|
||||
|
||||
pub fn between_angles(cx: f64, cy: f64, r: f64, a_from: f64, a_to: f64, sweep_sign: f64) -> f64 {
|
||||
if !finite(&[cx, cy, r, a_from, a_to, sweep_sign]) {
|
||||
return 0.0;
|
||||
}
|
||||
k::bulge_between_angles(v(cx, cy), r, a_from, a_to, sweep_sign)
|
||||
}
|
||||
|
||||
pub fn point_at(ax: f64, ay: f64, bx: f64, by: f64, bulge: f64, t: f64) -> Vec<f64> {
|
||||
if !finite(&[ax, ay, bx, by, t]) {
|
||||
return vec![ax, ay];
|
||||
}
|
||||
let bulge = if bulge.is_finite() { bulge } else { 0.0 };
|
||||
let p = k::bulge_point_at(v(ax, ay), v(bx, by), bulge, t);
|
||||
vec![p.x, p.y]
|
||||
}
|
||||
|
||||
pub fn through_point(ax: f64, ay: f64, tx: f64, ty: f64, bx: f64, by: f64) -> f64 {
|
||||
if !finite(&[ax, ay, tx, ty, bx, by]) {
|
||||
return 0.0;
|
||||
}
|
||||
k::bulge_through_point(v(ax, ay), v(tx, ty), v(bx, by))
|
||||
}
|
||||
|
||||
pub fn arc_through_points(ax: f64, ay: f64, tx: f64, ty: f64, bx: f64, by: f64) -> Vec<f64> {
|
||||
if !finite(&[ax, ay, tx, ty, bx, by]) {
|
||||
return Vec::new();
|
||||
}
|
||||
flat_arc(k::arc_through_points(v(ax, ay), v(tx, ty), v(bx, by)))
|
||||
}
|
||||
|
||||
pub fn arc_from_start_end_radius(ax: f64, ay: f64, bx: f64, by: f64, r: f64, nx: f64, ny: f64) -> Vec<f64> {
|
||||
if !finite(&[ax, ay, bx, by, r, nx, ny]) {
|
||||
return Vec::new();
|
||||
}
|
||||
flat_arc(k::arc_from_start_end_radius(v(ax, ay), v(bx, by), r, v(nx, ny)))
|
||||
}
|
||||
|
||||
pub fn arc_from_start_end_direction(ax: f64, ay: f64, bx: f64, by: f64, dx: f64, dy: f64) -> Vec<f64> {
|
||||
if !finite(&[ax, ay, bx, by, dx, dy]) {
|
||||
return Vec::new();
|
||||
}
|
||||
flat_arc(k::arc_from_start_end_direction(v(ax, ay), v(bx, by), v(dx, dy)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bogen_flach() {
|
||||
let a = arc(0.0, 0.0, 2.0, 0.0, 1.0);
|
||||
assert_eq!(a.len(), 6);
|
||||
assert!((a[0] - 1.0).abs() < 1e-9 && a[1].abs() < 1e-9 && (a[2] - 1.0).abs() < 1e-9);
|
||||
assert!(arc(0.0, 0.0, 2.0, 0.0, 0.0).is_empty());
|
||||
assert!(arc(0.0, 0.0, 0.0, 0.0, 1.0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsinn_ohne_panic() {
|
||||
let nan = f64::NAN;
|
||||
assert!(arc(nan, 0.0, 1.0, 0.0, 1.0).is_empty());
|
||||
assert!(arc(0.0, 0.0, 1.0, 0.0, nan).is_empty());
|
||||
assert!(arc(0.0, 0.0, 1.0, 0.0, f64::INFINITY).is_empty());
|
||||
assert_eq!(arc_points(0.0, 0.0, 1.0, 0.0, nan), vec![0.0, 0.0, 1.0, 0.0]);
|
||||
assert_eq!(arc_points(nan, 0.0, 1.0, 0.0, 1.0).len(), 4);
|
||||
assert!(polyline_points(&[0.0, nan, 1.0, 1.0], &[], false).is_empty());
|
||||
assert!(polyline_points(&[], &[], true).is_empty());
|
||||
assert_eq!(polyline_points(&[0.0, 0.0, 1.0, 0.0, 5.0], &[nan], false), vec![0.0, 0.0, 1.0, 0.0]);
|
||||
assert_eq!(from_sagitta_point(nan, 0.0, 1.0, 0.0, 0.0, 1.0), 0.0);
|
||||
assert_eq!(between_angles(0.0, 0.0, 1.0, nan, 1.0, 1.0), 0.0);
|
||||
assert_eq!(point_at(0.0, 0.0, 1.0, 0.0, 1.0, nan), vec![0.0, 0.0]);
|
||||
assert_eq!(through_point(nan, 0.0, 1.0, 0.0, 2.0, 1.0), 0.0);
|
||||
assert!(arc_through_points(nan, 0.0, 1.0, 0.0, 2.0, 1.0).is_empty());
|
||||
assert!(arc_from_start_end_radius(0.0, 0.0, 2.0, 0.0, nan, 0.0, 1.0).is_empty());
|
||||
assert!(arc_from_start_end_direction(0.0, 0.0, 2.0, 0.0, nan, 1.0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polylinie_ganz() {
|
||||
// Quadrat, eine Kante Halbkreis: Start nicht doppelt, Schlusskante enthalten
|
||||
let p = polyline_points(&[0.0, 0.0, 2.0, 0.0, 2.0, 2.0, 0.0, 2.0], &[1.0, 0.0, 0.0, 0.0], true);
|
||||
assert_eq!(p.len() / 2, 17 + 2); // a..b (17), +c, +d; Schlusskante ohne Startpunkt
|
||||
assert_eq!(&p[..2], &[0.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bogen_ccw_flach() {
|
||||
let c = arc_through_points(2.0, 0.0, 1.0, 1.0, 0.0, 0.0);
|
||||
assert_eq!(c.len(), 5);
|
||||
assert!(arc_through_points(0.0, 0.0, 1.0, 0.0, 2.0, 0.0).is_empty());
|
||||
assert_eq!(arc_from_start_end_radius(0.0, 0.0, 2.0, 0.0, 1.0, 1.0, 5.0).len(), 5);
|
||||
assert_eq!(arc_from_start_end_direction(0.0, 0.0, 1.0, 1.0, 0.0, 1.0).len(), 5);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ pub mod sun;
|
||||
pub mod site_rules;
|
||||
pub mod auto_dimensions;
|
||||
pub mod kennzahlen;
|
||||
pub mod bulge;
|
||||
pub mod stair;
|
||||
|
||||
#[cfg(feature = "web")]
|
||||
mod web;
|
||||
@@ -0,0 +1,272 @@
|
||||
//! Treppen-Geometrie als flache Aufrufe für `src/geometry/stair.ts`. Die Mathematik steht in
|
||||
//! `kernel2d` (`stair_geometry`, `stair_outline`, `stair_cut`, `stair_bbox`); hier Kodierung.
|
||||
//!
|
||||
//! Parameter (16 Zahlen): `[form (0 gerade, 1 L, 2 Wendel), startX, startY, dirX, dirY, lauf, lauf2,
|
||||
//! richtung, zentrumX, zentrumY, radius, winkel°, breite, stufen, auf, referenz]`; optionale
|
||||
//! Felder (`lauf2 … winkel`, `auf`) als NaN = fehlend; `richtung` ±1; `auf` 0/1; `referenz`
|
||||
//! 0 mitte, 1 links, 2 rechts. Pflichtfelder müssen endlich sein, sonst leeres Ergebnis.
|
||||
//!
|
||||
//! Geometrie `[hoeheSetz, auftritt, steigung, nTritte, (index, oben, unten, x0, y0 … x3, y3)…,
|
||||
//! nPodest (−1 = keins), x, y …, nLauf, x, y …, schaft ax, ay, bx, by, spitze 6 Zahlen]`.
|
||||
//! Aussenlinie `[0, n, x, y …]` (Polygon) oder `[1, 4 Linien-Zahlen ×2, (cx, cy, r, a0, a1) ×2]`.
|
||||
//! Schnitt `[nUnter, idx…, nUeber, idx…, nBruch (0|2), 8 Zahlen]`; Rahmen `[minX, minY, maxX, maxY]`.
|
||||
|
||||
use crate::flat_read::Reader;
|
||||
use kernel2d::{
|
||||
stair_bbox, stair_cut, stair_geometry, stair_outline, StairArrow, StairGeometry, StairParams,
|
||||
TreadRect, Vec2,
|
||||
};
|
||||
|
||||
/// Obergrenze der Stufenzahl (Schutz vor Endlosschleifen bei Unsinn).
|
||||
const MAX_STEPS: f64 = 10_000.0;
|
||||
|
||||
fn opt(v: f64) -> Option<f64> {
|
||||
if v.is_nan() {
|
||||
None
|
||||
} else {
|
||||
Some(v)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decode_params(buf: &[f64]) -> Option<StairParams> {
|
||||
let mut r = Reader::new(buf);
|
||||
let form = r.num()?;
|
||||
let (sx, sy, dx, dy, lauf) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
|
||||
let (lauf2, turn, cx, cy, radius, sweep) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
|
||||
let (width, steps, up, refz) = (r.num()?, r.num()?, r.num()?, r.num()?);
|
||||
let required = [form, sx, sy, dx, dy, lauf, width, steps];
|
||||
if !required.iter().all(|x| x.is_finite()) || steps.abs() > MAX_STEPS {
|
||||
return None;
|
||||
}
|
||||
let center = if cx.is_nan() || cy.is_nan() { None } else { Some(Vec2::new(cx, cy)) };
|
||||
// JS `Math.round`: .5 rundet auf
|
||||
let step_count = (steps + 0.5).floor() as i64;
|
||||
let shape = match form as i64 {
|
||||
1 => "L",
|
||||
2 => "spiral",
|
||||
_ => "straight",
|
||||
};
|
||||
let referenz = match refz as i64 {
|
||||
1 => Some("links".to_string()),
|
||||
2 => Some("rechts".to_string()),
|
||||
_ => None,
|
||||
};
|
||||
Some(StairParams {
|
||||
shape: shape.to_string(),
|
||||
start: Vec2::new(sx, sy),
|
||||
dir: Vec2::new(dx, dy),
|
||||
run_length: lauf,
|
||||
run2_length: opt(lauf2),
|
||||
turn: opt(turn).map(|t| t as i32),
|
||||
center,
|
||||
radius: opt(radius),
|
||||
sweep: opt(sweep),
|
||||
width,
|
||||
step_count,
|
||||
up: opt(up).map(|u| u != 0.0),
|
||||
referenz,
|
||||
})
|
||||
}
|
||||
|
||||
fn push_pts(out: &mut Vec<f64>, pts: &[Vec2]) {
|
||||
for p in pts {
|
||||
out.push(p.x);
|
||||
out.push(p.y);
|
||||
}
|
||||
}
|
||||
|
||||
fn to_vec2(pts: Vec<[f64; 2]>) -> Vec<Vec2> {
|
||||
pts.into_iter().map(|p| Vec2::new(p[0], p[1])).collect()
|
||||
}
|
||||
|
||||
pub fn encode_geometry(g: &StairGeometry) -> Vec<f64> {
|
||||
let mut out = vec![g.riser_height, g.tread_depth, g.total_rise, g.treads.len() as f64];
|
||||
for t in &g.treads {
|
||||
out.extend([t.index as f64, t.top_rise, t.base_rise]);
|
||||
push_pts(&mut out, &t.pts);
|
||||
}
|
||||
match &g.landing {
|
||||
Some(l) => {
|
||||
out.push(l.len() as f64);
|
||||
push_pts(&mut out, l);
|
||||
}
|
||||
None => out.push(-1.0),
|
||||
}
|
||||
out.push(g.run_line.len() as f64);
|
||||
push_pts(&mut out, &g.run_line);
|
||||
push_pts(&mut out, &[g.arrow.shaft.0, g.arrow.shaft.1, g.arrow.head.0, g.arrow.head.1, g.arrow.head.2]);
|
||||
out
|
||||
}
|
||||
|
||||
pub fn decode_geometry(buf: &[f64]) -> Option<StairGeometry> {
|
||||
let mut r = Reader::new(buf);
|
||||
let (riser_height, tread_depth, total_rise) = (r.num()?, r.num()?, r.num()?);
|
||||
let n = r.count()?;
|
||||
let mut treads = Vec::with_capacity(n.min(1 << 16));
|
||||
for _ in 0..n {
|
||||
let (index, top_rise, base_rise) = (r.num()?, r.num()?, r.num()?);
|
||||
let pts = to_vec2(r.points(4)?);
|
||||
treads.push(TreadRect { pts, index: index as i64, top_rise, base_rise });
|
||||
}
|
||||
let nl = r.num()?;
|
||||
let landing = if nl < 0.0 {
|
||||
None
|
||||
} else if nl.is_finite() && nl.fract() == 0.0 && nl < 1e6 {
|
||||
Some(to_vec2(r.points(nl as usize)?))
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let run_line = to_vec2(r.ring()?);
|
||||
let a = to_vec2(r.points(5)?);
|
||||
Some(StairGeometry {
|
||||
treads,
|
||||
landing,
|
||||
riser_height,
|
||||
tread_depth,
|
||||
run_line,
|
||||
arrow: StairArrow { shaft: (a[0], a[1]), head: (a[2], a[3], a[4]) },
|
||||
total_rise,
|
||||
})
|
||||
}
|
||||
|
||||
/// Vorgabe-Stufenzahl (endlich, ≥ MIN_STEPS).
|
||||
pub fn default_step_count(total_rise: f64, run_length: f64) -> u32 {
|
||||
kernel2d::default_step_count(total_rise, run_length).clamp(0, 1_000_000) as u32
|
||||
}
|
||||
|
||||
pub fn geometry(params: &[f64], total_rise: f64) -> Vec<f64> {
|
||||
match decode_params(params) {
|
||||
Some(p) if total_rise.is_finite() => encode_geometry(&stair_geometry(&p, total_rise)),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn outline(params: &[f64]) -> Vec<f64> {
|
||||
let Some(p) = decode_params(params) else { return Vec::new() };
|
||||
let o = stair_outline(&p);
|
||||
if let Some(poly) = o.polygon {
|
||||
let mut out = vec![0.0, poly.len() as f64];
|
||||
push_pts(&mut out, &poly);
|
||||
return out;
|
||||
}
|
||||
let Some(s) = o.spiral else { return Vec::new() };
|
||||
let mut out = vec![1.0];
|
||||
for (a, b) in s.lines {
|
||||
push_pts(&mut out, &[a, b]);
|
||||
}
|
||||
for (c, r, a0, a1) in s.arcs {
|
||||
out.extend([c.x, c.y, r, a0, a1]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn cut(geo: &[f64], cut_rise: f64) -> Vec<f64> {
|
||||
let Some(g) = decode_geometry(geo) else { return Vec::new() };
|
||||
let c = stair_cut(&g, cut_rise);
|
||||
let mut out = vec![c.below_indices.len() as f64];
|
||||
out.extend(c.below_indices.iter().map(|i| *i as f64));
|
||||
out.push(c.above_indices.len() as f64);
|
||||
out.extend(c.above_indices.iter().map(|i| *i as f64));
|
||||
match c.break_line {
|
||||
Some(lines) => {
|
||||
out.push(lines.len() as f64);
|
||||
for (a, b) in lines {
|
||||
push_pts(&mut out, &[a, b]);
|
||||
}
|
||||
}
|
||||
None => out.push(0.0),
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn bbox(geo: &[f64]) -> Vec<f64> {
|
||||
let Some(g) = decode_geometry(geo) else { return Vec::new() };
|
||||
let b = stair_bbox(&g);
|
||||
vec![b.min_x, b.min_y, b.max_x, b.max_y]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const NAN: f64 = f64::NAN;
|
||||
|
||||
fn straight() -> Vec<f64> {
|
||||
vec![0.0, 0.0, 0.0, 1.0, 0.0, 3.0, NAN, NAN, NAN, NAN, NAN, NAN, 1.2, 16.0, NAN, 0.0]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn geometrie_hin_und_zurueck() {
|
||||
let buf = geometry(&straight(), 2.8);
|
||||
let g = decode_geometry(&buf).unwrap();
|
||||
assert_eq!(g.treads.len(), 16);
|
||||
assert_eq!(encode_geometry(&g), buf);
|
||||
assert!(g.landing.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schnitt_und_rahmen_aus_flacher_geometrie() {
|
||||
let buf = geometry(&straight(), 2.8);
|
||||
let c = cut(&buf, 1.0);
|
||||
assert_eq!(c[0], 5.0);
|
||||
assert_eq!(c[6], 11.0);
|
||||
assert_eq!(c[6 + 11 + 1], 2.0); // zwei Bruchstriche
|
||||
assert_eq!(c.len(), 1 + 5 + 1 + 11 + 1 + 8);
|
||||
let b = bbox(&buf);
|
||||
assert!((b[2] - 3.0).abs() < 1e-9 && (b[1] + 0.6).abs() < 1e-9);
|
||||
// oberhalb aller Tritte: kein Bruch
|
||||
assert_eq!(*cut(&buf, 99.0).last().unwrap(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aussenlinie_flach() {
|
||||
let o = outline(&straight());
|
||||
assert_eq!(&o[..2], &[0.0, 4.0]);
|
||||
let mut sp = straight();
|
||||
sp[0] = 2.0;
|
||||
sp[10] = 1.0;
|
||||
let o = outline(&sp);
|
||||
assert_eq!(o.len(), 1 + 8 + 10);
|
||||
assert_eq!(o[0], 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsinn_ohne_panic() {
|
||||
assert!(geometry(&[], 2.8).is_empty());
|
||||
assert!(geometry(&straight()[..10], 2.8).is_empty());
|
||||
let mut p = straight();
|
||||
p[12] = NAN; // Breite
|
||||
assert!(geometry(&p, 2.8).is_empty());
|
||||
let mut p = straight();
|
||||
p[13] = 1e12; // Stufenzahl
|
||||
assert!(geometry(&p, 2.8).is_empty());
|
||||
assert!(geometry(&straight(), NAN).is_empty());
|
||||
assert!(outline(&[NAN]).is_empty());
|
||||
assert!(cut(&[], 1.0).is_empty());
|
||||
assert!(cut(&[1.0, 2.0, 3.0, 5.0, 0.0], 1.0).is_empty());
|
||||
assert!(bbox(&[0.0, 0.0, 0.0, -3.0]).is_empty());
|
||||
assert!(decode_geometry(&[0.0, 0.0, 0.0, 1e300]).is_none());
|
||||
// negative Stufenzahl wird auf die Mindestzahl gehoben
|
||||
let mut p = straight();
|
||||
p[13] = -4.0;
|
||||
assert_eq!(decode_geometry(&geometry(&p, 2.8)).unwrap().treads.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vorgabe_stufenzahl() {
|
||||
assert_eq!(default_step_count(2.8, 10.0), 16);
|
||||
assert_eq!(default_step_count(NAN, 3.0), 2);
|
||||
assert!(default_step_count(f64::INFINITY, 0.0) >= 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn referenz_und_optionen() {
|
||||
let mut p = straight();
|
||||
p[15] = 1.0; // links
|
||||
let g = decode_geometry(&geometry(&p, 2.8)).unwrap();
|
||||
assert!((g.treads[0].pts[0].y - 0.0).abs() < 1e-9);
|
||||
p[14] = 0.0; // Pfeil nach unten
|
||||
let g = decode_geometry(&geometry(&p, 2.8)).unwrap();
|
||||
assert_eq!(g.arrow.head.1, g.run_line[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Bindungen der Bogen-Formeln (`crate::bulge`) für `src/geometry/bulge.ts`. Skalare Argumente
|
||||
//! (kein Puffer) für Einzelaufrufe; Polylinien als flache `Float64Array`s.
|
||||
|
||||
use crate::bulge as b;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// `[cx, cy, r, a0, a1, sweep]`; leer = Gerade/entartet.
|
||||
#[wasm_bindgen]
|
||||
pub fn bulge_arc(ax: f64, ay: f64, bx: f64, by: f64, bulge: f64) -> Vec<f64> {
|
||||
b::arc(ax, ay, bx, by, bulge)
|
||||
}
|
||||
|
||||
/// Tessellierte Bogenpunkte `[x0, y0, …]` (Gerade: nur a, b).
|
||||
#[wasm_bindgen]
|
||||
pub fn bulge_arc_points(ax: f64, ay: f64, bx: f64, by: f64, bulge: f64) -> Vec<f64> {
|
||||
b::arc_points(ax, ay, bx, by, bulge)
|
||||
}
|
||||
|
||||
/// Ganze Polylinie tessellieren: Punkte `[x0, y0, …]`, bulge je Kante, geschlossen ja/nein.
|
||||
#[wasm_bindgen]
|
||||
pub fn bulge_polyline_points(pts: &[f64], bulge: &[f64], closed: bool) -> Vec<f64> {
|
||||
b::polyline_points(pts, bulge, closed)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn bulge_from_sagitta_point(ax: f64, ay: f64, bx: f64, by: f64, px: f64, py: f64) -> f64 {
|
||||
b::from_sagitta_point(ax, ay, bx, by, px, py)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn bulge_between_angles(cx: f64, cy: f64, r: f64, a_from: f64, a_to: f64, sweep_sign: f64) -> f64 {
|
||||
b::between_angles(cx, cy, r, a_from, a_to, sweep_sign)
|
||||
}
|
||||
|
||||
/// `[x, y]` auf dem Bogen bei t∈[0,1].
|
||||
#[wasm_bindgen]
|
||||
pub fn bulge_point_at(ax: f64, ay: f64, bx: f64, by: f64, bulge: f64, t: f64) -> Vec<f64> {
|
||||
b::point_at(ax, ay, bx, by, bulge, t)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn bulge_through_point(ax: f64, ay: f64, tx: f64, ty: f64, bx: f64, by: f64) -> f64 {
|
||||
b::through_point(ax, ay, tx, ty, bx, by)
|
||||
}
|
||||
|
||||
/// `[cx, cy, r, a0, a1]` (CCW) oder leer.
|
||||
#[wasm_bindgen]
|
||||
pub fn arc_through_points(ax: f64, ay: f64, tx: f64, ty: f64, bx: f64, by: f64) -> Vec<f64> {
|
||||
b::arc_through_points(ax, ay, tx, ty, bx, by)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn arc_from_start_end_radius(ax: f64, ay: f64, bx: f64, by: f64, r: f64, nx: f64, ny: f64) -> Vec<f64> {
|
||||
b::arc_from_start_end_radius(ax, ay, bx, by, r, nx, ny)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn arc_from_start_end_direction(ax: f64, ay: f64, bx: f64, by: f64, dx: f64, dy: f64) -> Vec<f64> {
|
||||
b::arc_from_start_end_direction(ax, ay, bx, by, dx, dy)
|
||||
}
|
||||
@@ -10,6 +10,8 @@ mod sun;
|
||||
mod site_rules;
|
||||
mod auto_dimensions;
|
||||
mod kennzahlen;
|
||||
mod bulge;
|
||||
mod stair;
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
//! Bindungen der Treppen-Geometrie (`crate::stair`). Kodierung s. dort.
|
||||
|
||||
use crate::stair as s;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Parameter (16 Zahlen) + Gesamt-Steighöhe → flache Treppengeometrie; Unsinn → leer.
|
||||
#[wasm_bindgen]
|
||||
pub fn stair_geometry_flat(params: &[f64], total_rise: f64) -> Vec<f64> {
|
||||
s::geometry(params, total_rise)
|
||||
}
|
||||
|
||||
/// Plan-Aussenlinie: `[0, n, x, y …]` (Polygon) oder `[1, …]` (Wendel).
|
||||
#[wasm_bindgen]
|
||||
pub fn stair_outline_flat(params: &[f64]) -> Vec<f64> {
|
||||
s::outline(params)
|
||||
}
|
||||
|
||||
/// Schnittaufteilung aus flacher Geometrie und Schnitthöhe über der Treppen-UK.
|
||||
#[wasm_bindgen]
|
||||
pub fn stair_cut_flat(geometry: &[f64], cut_rise: f64) -> Vec<f64> {
|
||||
s::cut(geometry, cut_rise)
|
||||
}
|
||||
|
||||
/// `[minX, minY, maxX, maxY]` aller Tritte + Podest.
|
||||
#[wasm_bindgen]
|
||||
pub fn stair_bbox_flat(geometry: &[f64]) -> Vec<f64> {
|
||||
s::bbox(geometry)
|
||||
}
|
||||
|
||||
/// Vorgabe-Stufenzahl aus Steighöhe und Lauflänge.
|
||||
#[wasm_bindgen]
|
||||
pub fn stair_default_step_count(total_rise: f64, run_length: f64) -> u32 {
|
||||
s::default_step_count(total_rise, run_length)
|
||||
}
|
||||
@@ -4,8 +4,8 @@
|
||||
// `bulge[i]` krümmt die Kante pts[i]→pts[i+1] (geschlossen zusätzlich
|
||||
// pts[n-1]→pts[0]); ein fehlender Eintrag oder 0 bedeutet Gerade.
|
||||
//
|
||||
// Die Bogen-Grundformeln (`bulge_arc`, `bulge_between_angles`) entsprechen
|
||||
// `src/geometry/bulge.ts` (dort weiter für Darstellung/Griffe genutzt).
|
||||
// Die Bogen-Grundformeln (`bulge_arc`, Tessellation, Drei-Punkt-/Radius-/Tangenten-Bogen) sind
|
||||
// die einzige Fassung; `src/geometry/bulge.ts` ist nur noch die Fassade darüber.
|
||||
|
||||
use crate::{
|
||||
add, circle_circle_intersect, dist, line_circle_intersect, line_intersect, offset_segment,
|
||||
@@ -105,6 +105,160 @@ pub fn bulge_between_angles(center: Vec2, r: f64, a_from: f64, a_to: f64, sweep_
|
||||
bulge_from_sagitta_point(p, q, m)
|
||||
}
|
||||
|
||||
/// Kreisbogen als Mittelpunkt/Radius/Winkelpaar (immer CCW von `a0` nach `a1`, wie `{shape:"arc"}`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ArcParams {
|
||||
pub center: Vec2,
|
||||
pub r: f64,
|
||||
pub a0: f64,
|
||||
pub a1: f64,
|
||||
}
|
||||
|
||||
/// Bogen als CCW-geordnetes Winkelpaar (bei negativem Schwenk a0/a1 vertauscht).
|
||||
fn ccw_arc(arc: BulgeArc) -> ArcParams {
|
||||
if arc.sweep < 0.0 {
|
||||
ArcParams { center: arc.center, r: arc.r, a0: arc.a1, a1: arc.a0 }
|
||||
} else {
|
||||
ArcParams { center: arc.center, r: arc.r, a0: arc.a0, a1: arc.a1 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Tessellierte Bogenpunkte von `a` nach `b` inkl. beider Endpunkte (~1 Segment je 12°, gerade
|
||||
/// Segmentzahl, damit der Apex bei t=0.5 ein echter Punkt in der Mitte ist). Gerade → `[a, b]`.
|
||||
pub fn bulge_arc_points(a: Vec2, b: Vec2, bulge: f64) -> Vec<Vec2> {
|
||||
let Some(arc) = bulge_arc(a, b, bulge) else { return vec![a, b] };
|
||||
if !(arc.sweep.is_finite() && arc.r.is_finite()) {
|
||||
return vec![a, b];
|
||||
}
|
||||
let mut n = ((arc.sweep.abs() / (PI / 15.0)).ceil() as usize).max(2);
|
||||
if n % 2 != 0 {
|
||||
n += 1;
|
||||
}
|
||||
(0..=n)
|
||||
.map(|i| {
|
||||
let t = arc.a0 + arc.sweep * (i as f64 / n as f64);
|
||||
Vec2::new(arc.center.x + arc.r * t.cos(), arc.center.y + arc.r * t.sin())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Tessellation einer ganzen Polylinie mit bulge je Kante (fehlend/0 = Gerade). Die Kantenpunkte
|
||||
/// werden verkettet, der Stossunterschied (doppelter Endpunkt) entfällt. Geschlossen: die
|
||||
/// Schlusskante a[n-1]→a[0] ist enthalten, der Startpunkt wird nicht wiederholt.
|
||||
pub fn bulge_polyline_points(pts: &[Vec2], bulge: &[f64], closed: bool) -> Vec<Vec2> {
|
||||
let n = pts.len();
|
||||
if n == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let edges = if closed { n } else { n - 1 };
|
||||
let mut out = vec![pts[0]];
|
||||
for i in 0..edges {
|
||||
let seg = bulge_arc_points(pts[i], pts[(i + 1) % n], bulge_at(bulge, i));
|
||||
let skip_last = closed && i == edges - 1;
|
||||
let end = if skip_last { seg.len() - 1 } else { seg.len() };
|
||||
out.extend_from_slice(&seg[1..end]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Punkt auf dem Bogen bei t∈[0,1] (0=a, 1=b, 0.5=Apex) — der nächste Tessellationspunkt.
|
||||
pub fn bulge_point_at(a: Vec2, b: Vec2, bulge: f64, t: f64) -> Vec2 {
|
||||
let pts = bulge_arc_points(a, b, bulge);
|
||||
if pts.len() <= 2 {
|
||||
return Vec2::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
|
||||
}
|
||||
let last = (pts.len() - 1) as f64;
|
||||
// wie JS `Math.round` (aufrunden bei .5), NaN → Index 0
|
||||
let idx = (t * last + 0.5).floor();
|
||||
let idx = if idx.is_nan() { 0.0 } else { idx.clamp(0.0, last) };
|
||||
pts[idx as usize]
|
||||
}
|
||||
|
||||
/// bulge des Drei-Punkt-Bogens a→through→b; (nahezu) kollinear → 0.
|
||||
pub fn bulge_through_point(a: Vec2, through: Vec2, b: Vec2) -> f64 {
|
||||
let d = 2.0 * (a.x * (through.y - b.y) + through.x * (b.y - a.y) + b.x * (a.y - through.y));
|
||||
if d.abs() < BULGE_EPS {
|
||||
return 0.0;
|
||||
}
|
||||
let a2 = a.x * a.x + a.y * a.y;
|
||||
let t2 = through.x * through.x + through.y * through.y;
|
||||
let b2 = b.x * b.x + b.y * b.y;
|
||||
let center = Vec2::new(
|
||||
(a2 * (through.y - b.y) + t2 * (b.y - a.y) + b2 * (a.y - through.y)) / d,
|
||||
(a2 * (b.x - through.x) + t2 * (a.x - b.x) + b2 * (through.x - a.x)) / d,
|
||||
);
|
||||
let r = (a.x - center.x).hypot(a.y - center.y);
|
||||
if r < BULGE_EPS {
|
||||
return 0.0;
|
||||
}
|
||||
let ang = |p: Vec2| (p.y - center.y).atan2(p.x - center.x);
|
||||
let a_from = ang(a);
|
||||
let ccw_to_through = norm_angle(ang(through) - a_from);
|
||||
let ccw_to_b = norm_angle(ang(b) - a_from);
|
||||
let sign = if ccw_to_through <= ccw_to_b { 1.0 } else { -1.0 };
|
||||
bulge_between_angles(center, r, a_from, ang(b), sign)
|
||||
}
|
||||
|
||||
/// Kreisbogen durch drei Punkte (CCW-geordnet); None bei kollinearen Punkten.
|
||||
pub fn arc_through_points(a: Vec2, through: Vec2, b: Vec2) -> Option<ArcParams> {
|
||||
let bulge = bulge_through_point(a, through, b);
|
||||
if bulge.abs() < BULGE_EPS {
|
||||
return None;
|
||||
}
|
||||
bulge_arc(a, b, bulge).map(ccw_arc)
|
||||
}
|
||||
|
||||
/// Kleinerer Bogen von `a` nach `b` mit Radius `r`; `near` wählt die Seite der Sehne.
|
||||
/// None, wenn `r` kleiner als die halbe Sehne oder die Sehne entartet ist.
|
||||
pub fn arc_from_start_end_radius(a: Vec2, b: Vec2, r: f64, near: Vec2) -> Option<ArcParams> {
|
||||
let dx = b.x - a.x;
|
||||
let dy = b.y - a.y;
|
||||
let chord = dx.hypot(dy);
|
||||
if chord < BULGE_EPS {
|
||||
return None;
|
||||
}
|
||||
let h = chord / 2.0;
|
||||
if r < h - BULGE_EPS {
|
||||
return None;
|
||||
}
|
||||
let rr = r.max(h);
|
||||
let s = rr - (rr * rr - h * h).max(0.0).sqrt();
|
||||
let ux = dx / chord;
|
||||
let uy = dy / chord;
|
||||
let (nx, ny) = (-uy, ux);
|
||||
let mx = (a.x + b.x) / 2.0;
|
||||
let my = (a.y + b.y) / 2.0;
|
||||
let side = if (near.x - mx) * nx + (near.y - my) * ny >= 0.0 { 1.0 } else { -1.0 };
|
||||
bulge_arc(a, b, side * s / h).map(ccw_arc)
|
||||
}
|
||||
|
||||
/// Bogen von `a` nach `b`, bei `a` tangential zur Richtung `dir` (Punkt auf dem Tangentenstrahl).
|
||||
/// None bei entarteter Tangente oder wenn sie entlang der Sehne zeigt.
|
||||
pub fn arc_from_start_end_direction(a: Vec2, b: Vec2, dir: Vec2) -> Option<ArcParams> {
|
||||
let (tx, ty) = (dir.x - a.x, dir.y - a.y);
|
||||
let t_len = tx.hypot(ty);
|
||||
if t_len < BULGE_EPS {
|
||||
return None;
|
||||
}
|
||||
let (ux, uy) = (tx / t_len, ty / t_len);
|
||||
let tangent_normal = Vec2::new(-uy, ux);
|
||||
let mid = Vec2::new((a.x + b.x) / 2.0, (a.y + b.y) / 2.0);
|
||||
let chord_normal = Vec2::new(-(b.y - a.y), b.x - a.x);
|
||||
let center = line_intersect(a, tangent_normal, mid, chord_normal)?;
|
||||
let r = (a.x - center.x).hypot(a.y - center.y);
|
||||
if r < BULGE_EPS {
|
||||
return None;
|
||||
}
|
||||
let a0 = (a.y - center.y).atan2(a.x - center.x);
|
||||
let a1 = (b.y - center.y).atan2(b.x - center.x);
|
||||
let ccw_matches = -a0.sin() * ux + a0.cos() * uy >= 0.0;
|
||||
Some(if ccw_matches {
|
||||
ArcParams { center, r, a0, a1 }
|
||||
} else {
|
||||
ArcParams { center, r, a0: a1, a1: a0 }
|
||||
})
|
||||
}
|
||||
|
||||
/// bulge-Eintrag `i` (fehlend → 0, also Gerade).
|
||||
fn bulge_at(bulge: &[f64], i: usize) -> f64 {
|
||||
bulge.get(i).copied().unwrap_or(0.0)
|
||||
@@ -776,4 +930,108 @@ mod tests {
|
||||
assert_eq!(out[0].pts, vec![v(0.0, 0.0), v(1.0, 0.0), v(2.0, 0.0), v(3.0, 0.0)]);
|
||||
assert_eq!(out[0].bulge, vec![0.0, -0.25, -0.5]);
|
||||
}
|
||||
|
||||
// --- Tessellation und Konstruktionen ---------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn arc_points_halbkreis_apex_in_der_mitte() {
|
||||
let pts = bulge_arc_points(v(0.0, 0.0), v(2.0, 0.0), 1.0);
|
||||
assert_eq!(pts.len() % 2, 1); // gerade Segmentzahl
|
||||
assert!(close(pts[0], 0.0, 0.0) && close(*pts.last().unwrap(), 2.0, 0.0));
|
||||
assert!(close(pts[pts.len() / 2], 1.0, 1.0));
|
||||
for p in &pts {
|
||||
assert!(((p.x - 1.0).hypot(p.y) - 1.0).abs() < P);
|
||||
}
|
||||
// 180° / 12° = 15 -> 16 Segmente
|
||||
assert_eq!(pts.len(), 17);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arc_points_gerade_und_unsinn() {
|
||||
let a = v(0.0, 0.0);
|
||||
let b = v(4.0, 2.0);
|
||||
assert_eq!(bulge_arc_points(a, b, 0.0), vec![a, b]);
|
||||
assert_eq!(bulge_arc_points(a, a, 1.0), vec![a, a]);
|
||||
assert_eq!(bulge_arc_points(a, b, f64::NAN), vec![a, b]);
|
||||
let inf = bulge_arc_points(a, b, f64::INFINITY);
|
||||
assert!(inf.len() >= 2);
|
||||
let nan = bulge_arc_points(v(f64::NAN, 0.0), b, 1.0);
|
||||
assert!(nan.len() >= 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polyline_points_offen_und_geschlossen() {
|
||||
let pts = [v(0.0, 0.0), v(2.0, 0.0), v(2.0, 2.0)];
|
||||
let open = bulge_polyline_points(&pts, &[0.0, 0.0], false);
|
||||
assert_eq!(open, pts.to_vec());
|
||||
let closed = bulge_polyline_points(&pts, &[1.0], true);
|
||||
// Kante 0 ist ein Halbkreis (17 Punkte, a..b), Kanten 1 und 2 gerade; Start nicht doppelt
|
||||
assert_eq!(closed.len(), 17 + 1 + 0);
|
||||
assert_eq!(closed[0], pts[0]);
|
||||
assert_ne!(closed[closed.len() - 1], pts[0]);
|
||||
assert!(bulge_polyline_points(&[], &[], true).is_empty());
|
||||
assert_eq!(bulge_polyline_points(&[v(1.0, 1.0)], &[], false), vec![v(1.0, 1.0)]);
|
||||
assert_eq!(bulge_polyline_points(&[v(1.0, 1.0)], &[], true).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_at_endpunkte_und_apex() {
|
||||
let a = v(0.0, 0.0);
|
||||
let b = v(2.0, 0.0);
|
||||
assert!(close(bulge_point_at(a, b, 1.0, 0.0), 0.0, 0.0));
|
||||
assert!(close(bulge_point_at(a, b, 1.0, 0.5), 1.0, 1.0));
|
||||
assert!(close(bulge_point_at(a, b, 1.0, 1.0), 2.0, 0.0));
|
||||
assert!(close(bulge_point_at(a, b, 0.0, 0.25), 0.5, 0.0)); // Gerade: linear
|
||||
let _ = bulge_point_at(a, b, 1.0, f64::NAN); // kein Panic
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn through_point_roundtrip() {
|
||||
// Halbkreis über (0,0)–(1,1)–(2,0): Apex links der Sehne a→b? Sehne +x, Apex oben = links → +1
|
||||
let b = bulge_through_point(v(0.0, 0.0), v(1.0, 1.0), v(2.0, 0.0));
|
||||
assert!((b - 1.0).abs() < P);
|
||||
let b = bulge_through_point(v(0.0, 0.0), v(1.0, -1.0), v(2.0, 0.0));
|
||||
assert!((b + 1.0).abs() < P);
|
||||
assert_eq!(bulge_through_point(v(0.0, 0.0), v(1.0, 0.0), v(2.0, 0.0)), 0.0);
|
||||
assert_eq!(bulge_through_point(v(0.0, 0.0), v(0.0, 0.0), v(0.0, 0.0)), 0.0);
|
||||
let _ = bulge_through_point(v(f64::NAN, 0.0), v(1.0, 0.0), v(2.0, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arc_through_points_ccw_geordnet() {
|
||||
let arc = arc_through_points(v(2.0, 0.0), v(1.0, 1.0), v(0.0, 0.0)).unwrap();
|
||||
assert!(close(arc.center, 1.0, 0.0) && (arc.r - 1.0).abs() < P);
|
||||
// Lauf a→b ist CCW (über oben nach links): a0 = 0, a1 = π
|
||||
assert!(arc.a0.abs() < P && (arc.a1 - PI).abs() < P);
|
||||
let cw = arc_through_points(v(0.0, 0.0), v(1.0, 1.0), v(2.0, 0.0)).unwrap();
|
||||
// CW von a nach b -> vertauscht: a0 = 0 (=b), a1 = π (=a)
|
||||
assert!(cw.a0.abs() < P && (cw.a1 - PI).abs() < P);
|
||||
assert!(arc_through_points(v(0.0, 0.0), v(1.0, 0.0), v(2.0, 0.0)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arc_start_end_radius_kleinerer_bogen() {
|
||||
let a = v(0.0, 0.0);
|
||||
let b = v(2.0, 0.0);
|
||||
let up = arc_from_start_end_radius(a, b, 1.0, v(1.0, 5.0)).unwrap();
|
||||
assert!(close(up.center, 1.0, 0.0) && (up.r - 1.0).abs() < P);
|
||||
let flat = arc_from_start_end_radius(a, b, 10.0, v(1.0, -3.0)).unwrap();
|
||||
assert!((flat.r - 10.0).abs() < P);
|
||||
assert!(flat.center.y > 0.0); // Bogen wölbt nach unten -> Zentrum oben
|
||||
assert!(arc_from_start_end_radius(a, b, 0.5, v(1.0, 1.0)).is_none());
|
||||
assert!(arc_from_start_end_radius(a, a, 1.0, v(1.0, 1.0)).is_none());
|
||||
let _ = arc_from_start_end_radius(a, b, f64::NAN, v(1.0, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arc_start_end_direction_tangente() {
|
||||
// Start (0,0), Tangente +y, Ende (1,1): Viertelkreis um (1,0)? Mittelpunkt auf der Normalen (x-Achse)
|
||||
let arc = arc_from_start_end_direction(v(0.0, 0.0), v(1.0, 1.0), v(0.0, 1.0)).unwrap();
|
||||
assert!(close(arc.center, 1.0, 0.0) && (arc.r - 1.0).abs() < P);
|
||||
// Tangente +y bei (0,0) um Zentrum (1,0): Lauf ist CW -> a0/a1 vertauscht
|
||||
assert!((arc.a0 - PI / 2.0).abs() < P && (arc.a1 - PI).abs() < P);
|
||||
assert!(arc_from_start_end_direction(v(0.0, 0.0), v(2.0, 0.0), v(1.0, 0.0)).is_none());
|
||||
assert!(arc_from_start_end_direction(v(0.0, 0.0), v(2.0, 0.0), v(0.0, 0.0)).is_none());
|
||||
let _ = arc_from_start_end_direction(v(f64::NAN, 0.0), v(2.0, 0.0), v(1.0, 1.0));
|
||||
}
|
||||
}
|
||||
@@ -1397,7 +1397,7 @@ fn eye_polygon(center: Vec2, r: f64) -> Vec<Vec2> {
|
||||
/// Treppen-Parameter (enthaelt alle geometrisch relevanten
|
||||
/// Felder des TS-Typs `Stair`; Modell-Semantik-Felder wie id/floorId werden
|
||||
/// ignoriert).
|
||||
#[derive(Deserialize)]
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StairParams {
|
||||
pub shape: String,
|
||||
@@ -1418,6 +1418,25 @@ pub struct StairParams {
|
||||
pub step_count: i64,
|
||||
#[serde(default)]
|
||||
pub up: Option<bool>,
|
||||
/// Bezugskante der gespeicherten Achse: "links" | "mitte" | "rechts" (fehlend = Mitte).
|
||||
#[serde(default)]
|
||||
pub referenz: Option<String>,
|
||||
}
|
||||
|
||||
/// Achse auf die visuelle Treppen-MITTE versetzen (Referenz links/rechts): `start` und `center`
|
||||
/// wandern um ±halbe Breite quer zur Laufrichtung. "mitte"/fehlend: unverändert.
|
||||
/// `links` = Achse ist die linke Kante, die Mitte liegt eine halbe Breite rechts (−n).
|
||||
fn stair_at_mid(stair: &StairParams, u: Vec2, half_w: f64) -> StairParams {
|
||||
let mut s = stair.clone();
|
||||
let mid_off = match stair.referenz.as_deref() {
|
||||
Some("links") => -half_w,
|
||||
Some("rechts") => half_w,
|
||||
_ => return s,
|
||||
};
|
||||
let c = scale(stair_left_n(u), mid_off);
|
||||
s.start = add(stair.start, c);
|
||||
s.center = stair.center.map(|ce| add(ce, c));
|
||||
s
|
||||
}
|
||||
|
||||
/// Gerade Treppe (Port von `straightGeometry`).
|
||||
@@ -1590,6 +1609,8 @@ pub fn stair_geometry(stair: &StairParams, total_rise: f64) -> StairGeometry {
|
||||
let half_w = (0.05_f64).max(stair.width / 2.0);
|
||||
let u = stair_norm(stair.dir);
|
||||
let n = stair_left_n(u);
|
||||
let s = stair_at_mid(stair, u, half_w);
|
||||
let stair = &s;
|
||||
|
||||
if stair.shape == "spiral" {
|
||||
return spiral_geometry(stair, total_rise, steps, riser_height, half_w);
|
||||
@@ -1600,6 +1621,91 @@ pub fn stair_geometry(stair: &StairParams, total_rise: f64) -> StairGeometry {
|
||||
straight_geometry(stair, total_rise, steps, riser_height, half_w, u, n)
|
||||
}
|
||||
|
||||
/// Aussenlinie einer Wendeltreppe: radiale Schliesslinien + Innen-/Aussenbogen.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SpiralOutline {
|
||||
/// Radiale Abschlusslinien (Innenpunkt → Aussenpunkt) bei a0 und a1.
|
||||
pub lines: [(Vec2, Vec2); 2],
|
||||
/// Kreisbögen (Mittelpunkt, r, a0, a1): Innen- und Aussenkreis.
|
||||
pub arcs: [(Vec2, f64, f64, f64); 2],
|
||||
}
|
||||
|
||||
/// Plan-Aussenlinie: genau eines von `polygon` (gerade/L) bzw. `spiral` (Wendel) ist gesetzt.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StairOutline {
|
||||
pub polygon: Option<Vec<Vec2>>,
|
||||
pub spiral: Option<SpiralOutline>,
|
||||
}
|
||||
|
||||
/// Linien-Schnittpunkt wie TS `lineIntersect2d` (det < 1e-9 → None).
|
||||
fn stair_line_intersect(p1: Vec2, d1: Vec2, p2: Vec2, d2: Vec2) -> Option<Vec2> {
|
||||
let det = d1.x * (-d2.y) - d1.y * (-d2.x);
|
||||
if det.abs() < 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let dx = p2.x - p1.x;
|
||||
let dy = p2.y - p1.y;
|
||||
let t = (dx * (-d2.y) - dy * (-d2.x)) / det;
|
||||
Some(Vec2 { x: p1.x + d1.x * t, y: p1.y + d1.y * t })
|
||||
}
|
||||
|
||||
/// Aussenlinie einer Treppe im Grundriss (Port von `stairOutline`; Referenz wie in `stair_geometry`).
|
||||
pub fn stair_outline(stair: &StairParams) -> StairOutline {
|
||||
let half_w = (0.05_f64).max(stair.width / 2.0);
|
||||
let u = stair_norm(stair.dir);
|
||||
let st = stair_at_mid(stair, u, half_w);
|
||||
let s = &st;
|
||||
let n = stair_left_n(u);
|
||||
if s.shape == "spiral" {
|
||||
let center = s.center.unwrap_or(s.start);
|
||||
let radius = (half_w + 0.1).max(s.radius.unwrap_or(s.width));
|
||||
let sweep = s.sweep.unwrap_or(270.0) * DEG;
|
||||
let sv = sub(s.start, center);
|
||||
let a0 = sv.y.atan2(sv.x);
|
||||
let a1 = a0 + sweep;
|
||||
let r_in = (radius - half_w).max(0.02);
|
||||
let r_out = radius + half_w;
|
||||
let at = |r: f64, a: f64| Vec2 { x: center.x + r * a.cos(), y: center.y + r * a.sin() };
|
||||
return StairOutline {
|
||||
polygon: None,
|
||||
spiral: Some(SpiralOutline {
|
||||
lines: [(at(r_in, a0), at(r_out, a0)), (at(r_in, a1), at(r_out, a1))],
|
||||
arcs: [(center, r_in, a0, a1), (center, r_out, a0, a1)],
|
||||
}),
|
||||
};
|
||||
}
|
||||
if s.shape == "L" {
|
||||
let l1 = s.run_length.max(1e-4);
|
||||
let turn = s.turn.unwrap_or(1);
|
||||
let u2 = if turn > 0 { n } else { scale(n, -1.0) };
|
||||
let n2 = stair_left_n(u2);
|
||||
let l2 = s.run2_length.unwrap_or(s.run_length).max(1e-4);
|
||||
let corner = add(s.start, scale(u, l1 + half_w));
|
||||
let run2_start = add(corner, scale(u2, half_w));
|
||||
let p0l = add(s.start, scale(n, half_w));
|
||||
let p0r = add(s.start, scale(n, -half_w));
|
||||
let end_run2 = add(run2_start, scale(u2, l2));
|
||||
let p3l = add(end_run2, scale(n2, half_w));
|
||||
let p3r = add(end_run2, scale(n2, -half_w));
|
||||
let corner_l = stair_line_intersect(p0l, u, p3l, scale(u2, -1.0))
|
||||
.unwrap_or_else(|| add(corner, scale(n, half_w)));
|
||||
let corner_r = stair_line_intersect(p0r, u, p3r, scale(u2, -1.0))
|
||||
.unwrap_or_else(|| add(corner, scale(n, -half_w)));
|
||||
return StairOutline { polygon: Some(vec![p0l, p0r, corner_r, p3r, p3l, corner_l]), spiral: None };
|
||||
}
|
||||
let l = s.run_length.max(1e-4);
|
||||
let end = add(s.start, scale(u, l));
|
||||
StairOutline {
|
||||
polygon: Some(vec![
|
||||
add(s.start, scale(n, half_w)),
|
||||
add(s.start, scale(n, -half_w)),
|
||||
add(end, scale(n, -half_w)),
|
||||
add(end, scale(n, half_w)),
|
||||
]),
|
||||
spiral: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Punkt-in-Polygon (Ray-Casting) — gleiches Muster wie `pointInOutline` /
|
||||
/// stair.ts `pointInPolygon` (Nenner-Guard `|| 1e-12`).
|
||||
pub fn point_in_polygon(p: Vec2, poly: &[Vec2]) -> bool {
|
||||
@@ -2653,4 +2759,163 @@ mod tests {
|
||||
assert!(split_closed_by_chord(&pts, 0, 0.5, 7, 0.5).is_none());
|
||||
assert!(remove_segment(&[], true, 3).pts.is_empty());
|
||||
}
|
||||
|
||||
// --- Treppen ---------------------------------------------------------------------------
|
||||
|
||||
fn stair(shape: &str) -> StairParams {
|
||||
StairParams {
|
||||
shape: shape.to_string(),
|
||||
start: Vec2 { x: 0.0, y: 0.0 },
|
||||
dir: Vec2 { x: 1.0, y: 0.0 },
|
||||
run_length: 3.0,
|
||||
run2_length: None,
|
||||
turn: None,
|
||||
center: None,
|
||||
radius: None,
|
||||
sweep: None,
|
||||
width: 1.2,
|
||||
step_count: 16,
|
||||
up: None,
|
||||
referenz: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn near(a: Vec2, x: f64, y: f64) -> bool {
|
||||
(a.x - x).abs() < 1e-9 && (a.y - y).abs() < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stair_gerade_tritte_lauflinie_pfeil() {
|
||||
let g = stair_geometry(&stair("straight"), 2.8);
|
||||
assert_eq!(g.treads.len(), 16);
|
||||
assert!((g.riser_height - 0.175).abs() < 1e-12);
|
||||
assert!((g.tread_depth - 3.0 / 16.0).abs() < 1e-12);
|
||||
assert!(g.landing.is_none());
|
||||
let t0 = &g.treads[0];
|
||||
assert!(near(t0.pts[0], 0.0, 0.6) && near(t0.pts[2], 3.0 / 16.0, -0.6));
|
||||
assert!((g.treads[15].top_rise - 2.8).abs() < 1e-12);
|
||||
assert_eq!(g.run_line.len(), 2);
|
||||
// Pfeilspitze am oberen Ende (up Default = true)
|
||||
assert!(near(g.arrow.head.1, g.run_line[1].x, g.run_line[1].y));
|
||||
let mut down = stair("straight");
|
||||
down.up = Some(false);
|
||||
let gd = stair_geometry(&down, 2.8);
|
||||
assert!(near(gd.arrow.head.1, gd.run_line[0].x, gd.run_line[0].y));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stair_l_podest_und_zweiter_lauf() {
|
||||
let mut p = stair("L");
|
||||
p.run2_length = Some(2.0);
|
||||
let g = stair_geometry(&p, 2.8);
|
||||
assert_eq!(g.treads.len(), 15); // 16 Stufen − 1 Podest
|
||||
let land = g.landing.as_ref().unwrap();
|
||||
assert_eq!(land.len(), 4);
|
||||
assert_eq!(g.run_line.len(), 3);
|
||||
// Podest-Mitte = start + u·(run1 + halfW)
|
||||
assert!(near(g.run_line[1], 3.6, 0.0));
|
||||
// zweiter Lauf geht nach +y (turn Default = links)
|
||||
assert!(g.run_line[2].y > 1.0);
|
||||
assert_eq!(g.treads[g.treads.len() - 1].index, 15);
|
||||
p.turn = Some(-1);
|
||||
assert!(stair_geometry(&p, 2.8).run_line[2].y < -1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stair_wendel_keile_und_auge() {
|
||||
let mut p = stair("spiral");
|
||||
p.center = Some(Vec2 { x: 0.0, y: 0.0 });
|
||||
p.start = Vec2 { x: 1.0, y: 0.0 };
|
||||
p.radius = Some(1.0);
|
||||
p.step_count = 12;
|
||||
let g = stair_geometry(&p, 2.4);
|
||||
assert_eq!(g.treads.len(), 12);
|
||||
assert_eq!(g.landing.as_ref().unwrap().len(), 12);
|
||||
assert_eq!(g.run_line.len(), 13);
|
||||
assert!((g.tread_depth - (1.0 * 270.0 * DEG) / 12.0).abs() < 1e-12);
|
||||
// Innenradius = radius − halfW = 0.4
|
||||
assert!(near(g.treads[0].pts[0], 0.4, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stair_referenz_versetzt_achse_auf_die_mitte() {
|
||||
let mut p = stair("straight");
|
||||
p.referenz = Some("links".into());
|
||||
let g = stair_geometry(&p, 2.8);
|
||||
// Achse = linke Kante → Mitte eine halbe Breite rechts (−y bei Lauf +x)
|
||||
assert!(near(g.treads[0].pts[0], 0.0, 0.0) && near(g.treads[0].pts[3], 0.0, -1.2));
|
||||
p.referenz = Some("rechts".into());
|
||||
let g = stair_geometry(&p, 2.8);
|
||||
assert!(near(g.treads[0].pts[0], 0.0, 1.2));
|
||||
// Wendel: auch das Zentrum wandert mit
|
||||
let mut sp = stair("spiral");
|
||||
sp.referenz = Some("rechts".into());
|
||||
sp.center = Some(Vec2 { x: 5.0, y: 5.0 });
|
||||
let o = stair_outline(&sp);
|
||||
assert!((o.spiral.unwrap().arcs[0].0.y - 5.6).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stair_outline_formen() {
|
||||
let o = stair_outline(&stair("straight"));
|
||||
let poly = o.polygon.unwrap();
|
||||
assert_eq!(poly.len(), 4);
|
||||
assert!(near(poly[0], 0.0, 0.6) && near(poly[2], 3.0, -0.6));
|
||||
assert!(o.spiral.is_none());
|
||||
let mut l = stair("L");
|
||||
l.run2_length = Some(2.0);
|
||||
let poly = stair_outline(&l).polygon.unwrap();
|
||||
assert_eq!(poly.len(), 6);
|
||||
let sp = stair_outline(&stair("spiral")).spiral.unwrap();
|
||||
assert!((sp.arcs[0].1 - 0.5).abs() < 1e-9 || sp.arcs[0].1 > 0.0);
|
||||
assert!((sp.arcs[1].1 - sp.arcs[0].1 - 1.2).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stair_unsinn_ohne_panic() {
|
||||
let mut p = stair("straight");
|
||||
p.dir = Vec2 { x: 0.0, y: 0.0 };
|
||||
let _ = stair_geometry(&p, 2.8);
|
||||
p.width = f64::NAN;
|
||||
p.run_length = f64::NAN;
|
||||
let g = stair_geometry(&p, f64::NAN);
|
||||
assert_eq!(g.treads.len(), 16);
|
||||
p.step_count = -5;
|
||||
assert_eq!(stair_geometry(&p, 2.8).treads.len(), 2);
|
||||
for shape in ["L", "spiral"] {
|
||||
let mut q = stair(shape);
|
||||
q.width = f64::NAN;
|
||||
q.step_count = 0;
|
||||
let _ = stair_geometry(&q, 1.0);
|
||||
let _ = stair_outline(&q);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stair_cut_bbox_und_treffer() {
|
||||
let g = stair_geometry(&stair("straight"), 2.8);
|
||||
let c = stair_cut(&g, 1.0);
|
||||
assert_eq!(c.below_indices.len(), 5); // 0.175·5 = 0.875 ≤ 1 < 1.05
|
||||
assert_eq!(c.above_indices.len(), 11);
|
||||
assert_eq!(c.break_line.as_ref().unwrap().len(), 2);
|
||||
assert!(stair_cut(&g, 99.0).break_line.is_none());
|
||||
let b = stair_bbox(&g);
|
||||
assert!((b.max_x - 3.0).abs() < 1e-9 && (b.min_y + 0.6).abs() < 1e-9);
|
||||
assert!(point_hits_stair(Vec2 { x: 1.0, y: 0.0 }, &g));
|
||||
assert!(!point_hits_stair(Vec2 { x: 1.0, y: 5.0 }, &g));
|
||||
let leer = StairGeometry {
|
||||
treads: vec![], landing: None, riser_height: 0.0, tread_depth: 0.0,
|
||||
run_line: vec![], arrow: StairArrow { shaft: (Vec2 { x: 0.0, y: 0.0 }, Vec2 { x: 0.0, y: 0.0 }), head: (Vec2 { x: 0.0, y: 0.0 }, Vec2 { x: 0.0, y: 0.0 }, Vec2 { x: 0.0, y: 0.0 }) },
|
||||
total_rise: 0.0,
|
||||
};
|
||||
assert_eq!(stair_bbox(&leer).max_x, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_step_count_regeln() {
|
||||
assert_eq!(default_step_count(2.8, 10.0), 16);
|
||||
assert_eq!(default_step_count(2.8, 3.0), 13); // Lauflänge deckelt: floor(3/0.24)+1
|
||||
assert_eq!(default_step_count(0.1, 0.0), 2);
|
||||
assert_eq!(default_step_count(f64::NAN, 3.0), 2);
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@
|
||||
// Bezeichner englisch, Kommentare/UI deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { Drawing2D, Drawing2DGeom } from "../../model/types";
|
||||
import { bulgeArcPoints, hasRealBulge } from "../../core";
|
||||
import { bulgePolylinePoints, hasRealBulge } from "../../core";
|
||||
import { extendBulgeSegment, extendSegment, pointSegmentDistance, polylineEdges } from "../../core";
|
||||
import type {
|
||||
Command,
|
||||
@@ -56,13 +56,8 @@ function geomToOpenCurve(g: Drawing2DGeom): Curve | null {
|
||||
*/
|
||||
function curveHitEdges(curve: Curve): [Vec2, Vec2][] {
|
||||
if (!hasRealBulge(curve.bulge)) return polylineEdges(curve.pts, curve.closed);
|
||||
const n = curve.pts.length;
|
||||
const edgeCount = curve.closed ? n : n - 1;
|
||||
const chain: Vec2[] = [curve.pts[0]];
|
||||
for (let i = 0; i < edgeCount; i++) {
|
||||
const seg = bulgeArcPoints(curve.pts[i], curve.pts[(i + 1) % n], curve.bulge?.[i]);
|
||||
chain.push(...seg.slice(1));
|
||||
}
|
||||
const chain = bulgePolylinePoints(curve.pts, curve.bulge, curve.closed);
|
||||
if (curve.closed) chain.push(curve.pts[0]); // Schlusskante mit-tesselliert, Kette endet am Start
|
||||
return polylineEdges(chain, false);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
// Vorzeichen, wenn negativ getippt.
|
||||
|
||||
import type { Drawing2D, Drawing2DGeom } from "../../model/types";
|
||||
import { bulgeArcPoints, hasRealBulge } from "../../core";
|
||||
import { bulgePolylinePoints, hasRealBulge } from "../../core";
|
||||
import { uniqueId } from "../../tools/types";
|
||||
import { leftNormal, normalize, sub } from "../../model/geometry";
|
||||
import { offsetPolyline, offsetPolylineWithBulge, offsetSegment, pointSegmentDistance, polylineEdges } from "../../core";
|
||||
@@ -86,20 +86,15 @@ function singleSelectedCurve(project: Project, sel: CommandSelection): Drawing2D
|
||||
|
||||
/**
|
||||
* Kanten für Klick-Trefftests/Vorschau: bei Bogen-Segmenten (bulge) wird die
|
||||
* Kurve zu Geradenstücken tesselliert (`bulgeArcPoints`), damit Klick-/Seiten-
|
||||
* Kurve zu Geradenstücken tesselliert (`bulgePolylinePoints`), damit Klick-/Seiten-
|
||||
* Tests entlang der TATSÄCHLICHEN (runden) Kontur funktionieren statt entlang
|
||||
* der geraden Sehne. Die eigentliche Offset-Geometrie bleibt exakt (bulge-
|
||||
* erhaltend, s. `offsetPolylineWithBulge`) — nur diese Hilfsfunktion approximiert.
|
||||
*/
|
||||
function curveHitEdges(curve: Curve): [Vec2, Vec2][] {
|
||||
if (!hasRealBulge(curve.bulge)) return polylineEdges(curve.pts, curve.closed);
|
||||
const n = curve.pts.length;
|
||||
const edgeCount = curve.closed ? n : n - 1;
|
||||
const chain: Vec2[] = [curve.pts[0]];
|
||||
for (let i = 0; i < edgeCount; i++) {
|
||||
const seg = bulgeArcPoints(curve.pts[i], curve.pts[(i + 1) % n], curve.bulge?.[i]);
|
||||
chain.push(...seg.slice(1));
|
||||
}
|
||||
const chain = bulgePolylinePoints(curve.pts, curve.bulge, curve.closed);
|
||||
if (curve.closed) chain.push(curve.pts[0]); // Schlusskante mit-tesselliert, Kette endet am Start
|
||||
return polylineEdges(chain, false); // Schlusskante (falls closed) ist bereits mit-tesselliert
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
// Tangenten-Referenz und bleibt gerade.
|
||||
|
||||
import type { Drawing2D } from "../../model/types";
|
||||
import { bulgeArcPoints, bulgeThroughPoint } from "../../core";
|
||||
import { bulgePolylinePoints, bulgeThroughPoint } from "../../core";
|
||||
import { segmentHud, uniqueId } from "../../tools/types";
|
||||
import type {
|
||||
Command,
|
||||
@@ -190,11 +190,7 @@ function polyDraft(
|
||||
: 0;
|
||||
const allBulges = cursor ? [...bulges, previewBulge] : bulges;
|
||||
// Bogen-Segmente für die Vorschau ausrollen.
|
||||
const pts: Vec2[] = all.length ? [all[0]] : [];
|
||||
for (let i = 0; i < all.length - 1; i++) {
|
||||
const sub = bulgeArcPoints(all[i], all[i + 1], allBulges[i] ?? 0);
|
||||
for (let k = 1; k < sub.length; k++) pts.push(sub[k]);
|
||||
}
|
||||
const pts = bulgePolylinePoints(all, allBulges, false);
|
||||
// Ring nur ab 3 Punkten zeigen; darunter bleibt die Vorschau offen.
|
||||
const showClosed = closed && all.length >= 3;
|
||||
const preview: DraftShape[] = [{ kind: "poly", pts, closed: showClosed }];
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
import type { Drawing2D } from "../../model/types";
|
||||
import { deltaHud, segmentHud, uniqueId } from "../../tools/types";
|
||||
import { filletCorner } from "../../core";
|
||||
import { bulgeArcPoints, bulgeThroughPoint } from "../../core";
|
||||
import { bulgePolylinePoints, bulgeThroughPoint } from "../../core";
|
||||
import type {
|
||||
Command,
|
||||
CommandContext,
|
||||
@@ -257,12 +257,7 @@ function roundedRectPts(corners: Vec2[], r: number): { pts: Vec2[]; bulge: numbe
|
||||
|
||||
/** Tessellierte Punkte einer gerundeten geschlossenen Kontur — für die Live-Vorschau. */
|
||||
function tessellateRounded(pts: Vec2[], bulge: number[]): Vec2[] {
|
||||
const out: Vec2[] = [];
|
||||
const n = pts.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
out.push(...bulgeArcPoints(pts[i], pts[(i + 1) % n], bulge[i]).slice(0, -1));
|
||||
}
|
||||
return out;
|
||||
return bulgePolylinePoints(pts, bulge, true);
|
||||
}
|
||||
|
||||
// ── Vorschau ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Aufrufe hinweg (wie `lastSides` bei `polygon.ts`).
|
||||
|
||||
import type { Drawing2D } from "../../model/types";
|
||||
import { bulgeArcPoints } from "../../core";
|
||||
import { bulgePolylinePoints } from "../../core";
|
||||
import { revisionCloudPts } from "../../core";
|
||||
import { segmentHud, uniqueId } from "../../tools/types";
|
||||
import type {
|
||||
@@ -53,11 +53,7 @@ function revcloudDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
|
||||
const expanded = revisionCloudPts(all, false, lastArcSize);
|
||||
const pts: Vec2[] = [];
|
||||
if (expanded) {
|
||||
pts.push(expanded.pts[0]);
|
||||
for (let i = 0; i < expanded.pts.length - 1; i++) {
|
||||
const sub = bulgeArcPoints(expanded.pts[i], expanded.pts[i + 1], expanded.bulge[i]);
|
||||
for (let k = 1; k < sub.length; k++) pts.push(sub[k]);
|
||||
}
|
||||
pts.push(...bulgePolylinePoints(expanded.pts, expanded.bulge, false));
|
||||
}
|
||||
const preview: DraftShape[] = [{ kind: "poly", pts, closed: false }];
|
||||
const draft: ToolDraft = { preview, vertices: points };
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
// Bezeichner englisch, Kommentare/UI deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { Drawing2D, Drawing2DGeom } from "../../model/types";
|
||||
import { bulgeArcPoints, hasRealBulge } from "../../core";
|
||||
import { bulgePolylinePoints, hasRealBulge } from "../../core";
|
||||
import { uniqueId } from "../../tools/types";
|
||||
import { pointSegmentDistance, polylineEdges, trimPolylineWithBulge, vecEqual } from "../../core";
|
||||
import type {
|
||||
@@ -78,13 +78,8 @@ export function isTrimmable(d: Drawing2D): boolean {
|
||||
*/
|
||||
export function curveHitEdges(curve: Curve): [Vec2, Vec2][] {
|
||||
if (!hasRealBulge(curve.bulge)) return polylineEdges(curve.pts, curve.closed);
|
||||
const n = curve.pts.length;
|
||||
const edgeCount = curve.closed ? n : n - 1;
|
||||
const chain: Vec2[] = [curve.pts[0]];
|
||||
for (let i = 0; i < edgeCount; i++) {
|
||||
const seg = bulgeArcPoints(curve.pts[i], curve.pts[(i + 1) % n], curve.bulge?.[i]);
|
||||
chain.push(...seg.slice(1));
|
||||
}
|
||||
const chain = bulgePolylinePoints(curve.pts, curve.bulge, curve.closed);
|
||||
if (curve.closed) chain.push(curve.pts[0]); // Schlusskante mit-tesselliert, Kette endet am Start
|
||||
return polylineEdges(chain, false);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ export {
|
||||
arcThroughPoints,
|
||||
bulgeArc,
|
||||
bulgeArcPoints,
|
||||
bulgePolylinePoints,
|
||||
bulgeBetweenAngles,
|
||||
bulgeFromSagittaPoint,
|
||||
bulgePointAt,
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
arcThroughPoints,
|
||||
bulgeArc,
|
||||
bulgeArcPoints,
|
||||
bulgePolylinePoints,
|
||||
bulgeFromSagittaPoint,
|
||||
bulgeThroughPoint,
|
||||
} from "./bulge";
|
||||
@@ -269,3 +270,35 @@ describe("arcFromStartEndDirection — Start/Ende/Tangentenrichtung (commands/cm
|
||||
expect(arcFromStartEndDirection({ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 0, y: 0 })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("bulgePolylinePoints (ganze Polylinie auf einmal)", () => {
|
||||
const sq: Vec2[] = [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 2 }, { x: 0, y: 2 }];
|
||||
|
||||
it("entspricht der Verkettung von bulgeArcPoints je Kante", () => {
|
||||
const bulge = [1, 0, -0.5, 0];
|
||||
const expected: Vec2[] = [sq[0]];
|
||||
for (let i = 0; i < 3; i++) expected.push(...bulgeArcPoints(sq[i], sq[i + 1], bulge[i]).slice(1));
|
||||
const got = bulgePolylinePoints(sq, bulge, false);
|
||||
expect(got.length).toBe(expected.length);
|
||||
got.forEach((p, i) => {
|
||||
expect(p.x).toBeCloseTo(expected[i].x, 12);
|
||||
expect(p.y).toBeCloseTo(expected[i].y, 12);
|
||||
});
|
||||
});
|
||||
|
||||
it("geschlossen: Schlusskante enthalten, Startpunkt nicht wiederholt", () => {
|
||||
const got = bulgePolylinePoints(sq, [0, 0, 0, 1], true);
|
||||
expect(got[0]).toEqual(sq[0]);
|
||||
expect(got[got.length - 1]).not.toEqual(sq[0]);
|
||||
// Schlusskante (0,2)→(0,0) läuft nach −y, links davon ist +x: Halbkreis nach x > 0
|
||||
expect(got.some((p) => p.x > 0.5 && p.y > 0.5 && p.y < 1.5)).toBe(true);
|
||||
});
|
||||
|
||||
it("Unsinn (leer, NaN) ohne Fehler", () => {
|
||||
expect(bulgePolylinePoints([], undefined, true)).toEqual([]);
|
||||
expect(bulgePolylinePoints([{ x: NaN, y: 0 }, { x: 1, y: 0 }], [1], false)).toEqual([]);
|
||||
expect(bulgeArc({ x: NaN, y: 0 }, { x: 1, y: 0 }, 1)).toBeNull();
|
||||
expect(bulgeThroughPoint({ x: 0, y: 0 }, { x: NaN, y: 1 }, { x: 2, y: 0 })).toBe(0);
|
||||
expect(bulgeArcPoints({ x: 0, y: 0 }, { x: 1, y: 0 }, NaN)).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
+76
-209
@@ -1,17 +1,19 @@
|
||||
// Bulge — DXF-Konvention für Bogen-Segmente in Polylinien: `bulge = tan(Δ/4)`
|
||||
// (Δ = Öffnungswinkel des Kreisbogens von a nach b). Reine Geometrie, keine
|
||||
// Abhängigkeit vom Modell — s. Kopfkommentar bei `Drawing2DGeom["polyline"].
|
||||
// bulge` (model/types.ts) für die Feld-Semantik.
|
||||
// (Δ = Öffnungswinkel des Kreisbogens von a nach b). Dünne Fassade über den Rust-Kern
|
||||
// (`src-tauri/kernel2d/src/bulge.rs`, Bindungen `src-tauri/core/src/web/bulge.rs`); die
|
||||
// Formeln (Sehnen-Pfeilhöhen-Beziehung `r = (h²+s²)/(2s)`, `s = h·bulge`) stehen nur dort.
|
||||
// Feld-Semantik: s. Kopfkommentar bei `Drawing2DGeom["polyline"].bulge` (model/types.ts).
|
||||
//
|
||||
// Herleitung (Sehnen-Pfeilhöhen-Beziehung, exakt, ohne Kreisbogen-Trigonometrie
|
||||
// im Radius): für eine Sehne der halben Länge h mit Pfeilhöhe (Sagitta) s gilt
|
||||
// die Kreissegment-Identität r = (h²+s²) / (2s). Die Bulge-Definition liefert
|
||||
// zusätzlich exakt s = h·bulge (Standard-Identität (1−cosX)/sinX = tan(X/2)
|
||||
// mit X = Δ/2). Damit lässt sich der komplette Bogen (Zentrum/Radius) ohne
|
||||
// eine einzige inverse Winkelfunktion aus bulge ableiten.
|
||||
// Einzelaufrufe geben skalare Argumente, ganze Polylinien gehen auf einmal über
|
||||
// `bulgePolylinePoints` (flache `Float64Array`s, Muster `coreFlat.ts`).
|
||||
//
|
||||
// Bewusst in TS geblieben (zwei Einzeiler, kein Rechenkern):
|
||||
// • `hasRealBulge` — läuft pro Zeichnung/Befehl über das bulge-Array; ein WASM-Aufruf müsste das
|
||||
// Array erst in eine `Float64Array` kopieren und wäre langsamer als `some` (Messung s. Commit).
|
||||
// • `pointOnCircle` — zwei Multiplikationen je Punkt, in Schleifen aufgerufen.
|
||||
|
||||
import type { Vec2 } from "../model/types";
|
||||
import { lineIntersect } from "../model/geometry";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
const EPS = 1e-9;
|
||||
|
||||
@@ -31,116 +33,63 @@ interface BulgeArc {
|
||||
|
||||
/** Kreisbogen-Parameter aus zwei Endpunkten + `bulge`, oder `null` bei (nahezu) 0 (Gerade). */
|
||||
export function bulgeArc(a: Vec2, b: Vec2, bulge: number): BulgeArc | null {
|
||||
if (Math.abs(bulge) < EPS) return null;
|
||||
const dx = b.x - a.x, dy = b.y - a.y;
|
||||
const chord = Math.hypot(dx, dy);
|
||||
if (chord < EPS) return null;
|
||||
const ux = dx / chord, uy = dy / chord;
|
||||
const nx = -uy, ny = ux; // Links-Normale von a→b
|
||||
const h = chord / 2;
|
||||
const s = h * bulge; // Sagitta (Pfeilhöhe), Vorzeichen wie bulge
|
||||
const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
|
||||
const rSigned = (h * h + s * s) / (2 * s);
|
||||
const cx = mx + nx * (s - rSigned);
|
||||
const cy = my + ny * (s - rSigned);
|
||||
const r = Math.abs(rSigned);
|
||||
const apexX = mx + nx * s, apexY = my + ny * s;
|
||||
const a0 = Math.atan2(a.y - cy, a.x - cx);
|
||||
const a1 = Math.atan2(b.y - cy, b.x - cx);
|
||||
const aApex = Math.atan2(apexY - cy, apexX - cx);
|
||||
const TAU = Math.PI * 2;
|
||||
const norm = (x: number) => ((x % TAU) + TAU) % TAU;
|
||||
// Die Sehnenmitte (Apex) liegt per Konstruktion auf dem Bogen — die Schwenk-
|
||||
// richtung (CCW oder CW von a0 nach a1) ist genau die, die den Apex-Winkel
|
||||
// unterwegs passiert. Robust gegen Vorzeichenfehler in der Herleitung oben:
|
||||
// wird direkt gegen den bekannten Apex-Punkt geprüft statt abstrakt hergeleitet.
|
||||
const ccwSweep = norm(a1 - a0);
|
||||
const ccwPassesApex = norm(aApex - a0) <= ccwSweep + 1e-7;
|
||||
const sweep = ccwPassesApex ? ccwSweep : -(TAU - ccwSweep);
|
||||
return { center: { x: cx, y: cy }, r, a0, a1, sweep };
|
||||
const r = core().bulge_arc(a.x, a.y, b.x, b.y, bulge);
|
||||
if (r.length < 6) return null;
|
||||
return { center: { x: r[0], y: r[1] }, r: r[2], a0: r[3], a1: r[4], sweep: r[5] };
|
||||
}
|
||||
|
||||
function toPoints(f: Float64Array): Vec2[] {
|
||||
const out: Vec2[] = new Array(f.length >> 1);
|
||||
for (let i = 0; i < out.length; i++) out[i] = { x: f[2 * i], y: f[2 * i + 1] };
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tessellierte Bogenpunkte von a nach b (inkl. beider Endpunkte) — für
|
||||
* Rendering/Fläche/Hit-Test/Export, die nur Geradensegmente kennen (analog
|
||||
* `circlePts`/`ellipsePts`). `null`-Bulge (Gerade) liefert `[a, b]`.
|
||||
* Rendering/Fläche/Hit-Test/Export, die nur Geradensegmente kennen. Gerade
|
||||
* (bulge fehlt/0) liefert `[a, b]`. Gerade Segmentzahl, damit der Apex (t=0.5)
|
||||
* ein echter Punkt in der Mitte ist (s. `bulgePointAt`).
|
||||
*/
|
||||
export function bulgeArcPoints(a: Vec2, b: Vec2, bulge: number | undefined): Vec2[] {
|
||||
const arc = bulge !== undefined ? bulgeArc(a, b, bulge) : null;
|
||||
if (!arc) return [a, b];
|
||||
const { center, r, a0, sweep } = arc;
|
||||
// Auflösung: ~1 Segment je 12° reicht für Plan-Massstäbe (analog `circlePts`
|
||||
// N=48 bei vollem Kreis ⇒ 7.5°/Segment; hier etwas gröber, dafür adaptiv zur
|
||||
// tatsächlichen Bogenlänge statt immer 48 Punkte für jedes kleine Bögchen).
|
||||
// Gerade Segmentzahl erzwingen, damit der exakte Apex-Punkt (t=0.5) immer
|
||||
// als echter Tessellations-Punkt in der Mitte des Arrays landet (wichtig
|
||||
// für den Bulge-Griff, s. `bulgePointAt`).
|
||||
let N = Math.max(2, Math.ceil(Math.abs(sweep) / (Math.PI / 15)));
|
||||
if (N % 2 !== 0) N += 1;
|
||||
const pts: Vec2[] = [];
|
||||
for (let i = 0; i <= N; i++) {
|
||||
const t = a0 + sweep * (i / N);
|
||||
pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) });
|
||||
if (bulge === undefined || bulge === 0) return [a, b];
|
||||
return toPoints(core().bulge_arc_points(a.x, a.y, b.x, b.y, bulge));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ganze Polylinie tessellieren (`bulge[i]` krümmt die Kante pts[i]→pts[i+1], geschlossen zusätzlich
|
||||
* die Schlusskante). Kantenpunkte verkettet ohne doppelte Stösse; bei `closed` wird der Startpunkt
|
||||
* am Ende nicht wiederholt.
|
||||
*/
|
||||
export function bulgePolylinePoints(pts: readonly Vec2[], bulge: readonly number[] | undefined, closed: boolean): Vec2[] {
|
||||
const flat = new Float64Array(pts.length * 2);
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
flat[2 * i] = pts[i].x;
|
||||
flat[2 * i + 1] = pts[i].y;
|
||||
}
|
||||
return pts;
|
||||
return toPoints(core().bulge_polyline_points(flat, Float64Array.from(bulge ?? []), closed));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulge aus einem gezogenen Punkt `p` relativ zur Sehne a-b ableiten (Griff-
|
||||
* Interaktion: Segment-Mitte senkrecht zur Sehne ziehen). Exakt die Umkehrung
|
||||
* der `s = h·bulge`-Identität oben — kein Winkel involviert.
|
||||
* Interaktion: Segment-Mitte senkrecht zur Sehne ziehen). Umkehrung von `s = h·bulge`.
|
||||
*/
|
||||
export function bulgeFromSagittaPoint(a: Vec2, b: Vec2, p: Vec2): number {
|
||||
const dx = b.x - a.x, dy = b.y - a.y;
|
||||
const chord = Math.hypot(dx, dy);
|
||||
if (chord < EPS) return 0;
|
||||
const ux = dx / chord, uy = dy / chord;
|
||||
const nx = -uy, ny = ux;
|
||||
const h = chord / 2;
|
||||
const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
|
||||
const s = (p.x - mx) * nx + (p.y - my) * ny;
|
||||
return s / h;
|
||||
return core().bulge_from_sagitta_point(a.x, a.y, b.x, b.y, p.x, p.y);
|
||||
}
|
||||
|
||||
/** Punkt auf dem aktuellen Bogen bei Parameter t∈[0,1] (0=a, 1=b, 0.5=Apex) — für den Bulge-Griff. */
|
||||
export function bulgePointAt(a: Vec2, b: Vec2, bulge: number, t: number): Vec2 {
|
||||
const pts = bulgeArcPoints(a, b, bulge);
|
||||
if (pts.length <= 2) return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
|
||||
const idx = Math.round(t * (pts.length - 1));
|
||||
return pts[Math.max(0, Math.min(pts.length - 1, idx))];
|
||||
const r = core().bulge_point_at(a.x, a.y, b.x, b.y, bulge, t);
|
||||
return { x: r[0], y: r[1] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulge eines Kreisbogens, der von `a` über `through` nach `b` läuft — der
|
||||
* klassische Drei-Punkt-Bogen. Anders als die Tangenten-Variante hängt er NUR
|
||||
* von diesen drei Punkten ab, nicht vom vorherigen Segment: Radius und
|
||||
* Wölbung sind damit pro Segment frei wählbar (Nutzer-Anforderung).
|
||||
*
|
||||
* Liegen die drei Punkte (nahezu) auf einer Geraden, gibt es keinen Kreis —
|
||||
* dann 0 (gerade).
|
||||
* Bulge eines Kreisbogens, der von `a` über `through` nach `b` läuft — der klassische
|
||||
* Drei-Punkt-Bogen, nur von diesen drei Punkten abhängig (nicht vom vorherigen Segment).
|
||||
* Liegen die Punkte (nahezu) auf einer Geraden, gibt es keinen Kreis — dann 0.
|
||||
*/
|
||||
export function bulgeThroughPoint(a: Vec2, through: Vec2, b: Vec2): number {
|
||||
// Umkreismittelpunkt über die Schnittpunkt-Formel der Mittelsenkrechten.
|
||||
const d = 2 * (a.x * (through.y - b.y) + through.x * (b.y - a.y) + b.x * (a.y - through.y));
|
||||
if (Math.abs(d) < EPS) return 0;
|
||||
const a2 = a.x * a.x + a.y * a.y;
|
||||
const t2 = through.x * through.x + through.y * through.y;
|
||||
const b2 = b.x * b.x + b.y * b.y;
|
||||
const center = {
|
||||
x: (a2 * (through.y - b.y) + t2 * (b.y - a.y) + b2 * (a.y - through.y)) / d,
|
||||
y: (a2 * (b.x - through.x) + t2 * (a.x - b.x) + b2 * (through.x - a.x)) / d,
|
||||
};
|
||||
const r = Math.hypot(a.x - center.x, a.y - center.y);
|
||||
if (r < EPS) return 0;
|
||||
const ang = (p: Vec2) => Math.atan2(p.y - center.y, p.x - center.x);
|
||||
const TAU = Math.PI * 2;
|
||||
const norm = (x: number) => ((x % TAU) + TAU) % TAU;
|
||||
// Schwenkrichtung ist die, bei der `through` unterwegs passiert wird.
|
||||
const aFrom = ang(a);
|
||||
const ccwToThrough = norm(ang(through) - aFrom);
|
||||
const ccwToB = norm(ang(b) - aFrom);
|
||||
const sweepSign: 1 | -1 = ccwToThrough <= ccwToB ? 1 : -1;
|
||||
return bulgeBetweenAngles(center, r, aFrom, ang(b), sweepSign);
|
||||
return core().bulge_through_point(a.x, a.y, through.x, through.y, b.x, b.y);
|
||||
}
|
||||
|
||||
/** Punkt auf einem Kreis (center, r) beim Winkel `a` (Radiant). */
|
||||
@@ -148,38 +97,27 @@ export function pointOnCircle(center: Vec2, r: number, a: number): Vec2 {
|
||||
return { x: center.x + r * Math.cos(a), y: center.y + r * Math.sin(a) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Kreisbogen-Parameter (Mittelpunkt/Radius/Start-/Endwinkel) durch drei Punkte
|
||||
* `a`→`through`→`b` — der klassische Drei-Punkt-Bogen, hier direkt als
|
||||
* `{center,r,a0,a1}` statt als `bulge` (für Werkzeuge, die einen eigenständigen
|
||||
* `{shape:"arc"}` erzeugen, z. B. `commands/cmds/arc.ts`, statt ein
|
||||
* Polylinien-Segment). `a0`/`a1` sind IMMER so geordnet, dass der Bogen CCW von
|
||||
* a0 nach a1 läuft (Konvention von `{shape:"arc"}`, s. dort) — anders als
|
||||
* `bulgeThroughPoint`, dessen Vorzeichen die Sehnen-Richtung a→b behält.
|
||||
* `null` bei (nahezu) kollinearen Punkten (kein Kreis).
|
||||
*/
|
||||
export function arcThroughPoints(
|
||||
a: Vec2,
|
||||
through: Vec2,
|
||||
b: Vec2,
|
||||
): { center: Vec2; r: number; a0: number; a1: number } | null {
|
||||
const bulge = bulgeThroughPoint(a, through, b);
|
||||
if (Math.abs(bulge) < EPS) return null;
|
||||
const arc = bulgeArc(a, b, bulge);
|
||||
if (!arc) return null;
|
||||
return arc.sweep < 0
|
||||
? { center: arc.center, r: arc.r, a0: arc.a1, a1: arc.a0 }
|
||||
: { center: arc.center, r: arc.r, a0: arc.a0, a1: arc.a1 };
|
||||
type ArcParams = { center: Vec2; r: number; a0: number; a1: number };
|
||||
|
||||
function toArcParams(r: Float64Array): ArcParams | null {
|
||||
if (r.length < 5) return null;
|
||||
return { center: { x: r[0], y: r[1] }, r: r[2], a0: r[3], a1: r[4] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulge-Wert für den Teilbogen desselben Kreises (center, r) von Winkel `aFrom`
|
||||
* zu `aTo`, in der durch `sweepSign` vorgegebenen Schwenkrichtung (+1 = CCW,
|
||||
* −1 = CW — dieselbe Richtung wie der Eltern-Bogen, aus dem dieser Teilbogen
|
||||
* stammt, z. B. beim Zuschneiden/Offsetten eines Bogen-Segments). Statt die
|
||||
* Vorzeichen-Herleitung erneut zu machen (fehleranfällig), wird ein echter
|
||||
* Punkt AUF dem Teilbogen (bei der Winkel-Mitte) konstruiert und darüber
|
||||
* `bulgeFromSagittaPoint` (bereits getestet, s. `bulgeArc`) wiederverwendet.
|
||||
* Kreisbogen-Parameter durch drei Punkte `a`→`through`→`b`, direkt als `{center,r,a0,a1}`
|
||||
* für Werkzeuge, die einen eigenständigen `{shape:"arc"}` erzeugen (`commands/cmds/arc.ts`).
|
||||
* `a0`/`a1` sind IMMER so geordnet, dass der Bogen CCW von a0 nach a1 läuft. `null` bei
|
||||
* (nahezu) kollinearen Punkten.
|
||||
*/
|
||||
export function arcThroughPoints(a: Vec2, through: Vec2, b: Vec2): ArcParams | null {
|
||||
return toArcParams(core().arc_through_points(a.x, a.y, through.x, through.y, b.x, b.y));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulge-Wert für den Teilbogen desselben Kreises (center, r) von Winkel `aFrom` zu `aTo`, in der
|
||||
* durch `sweepSign` vorgegebenen Schwenkrichtung (+1 = CCW, −1 = CW), z. B. beim Zuschneiden/
|
||||
* Offsetten eines Bogen-Segments.
|
||||
*/
|
||||
export function bulgeBetweenAngles(
|
||||
center: Vec2,
|
||||
@@ -188,94 +126,23 @@ export function bulgeBetweenAngles(
|
||||
aTo: number,
|
||||
sweepSign: 1 | -1,
|
||||
): number {
|
||||
const TAU = Math.PI * 2;
|
||||
const norm = (x: number) => ((x % TAU) + TAU) % TAU;
|
||||
const delta = sweepSign > 0 ? norm(aTo - aFrom) : -norm(aFrom - aTo);
|
||||
const mid = aFrom + delta / 2;
|
||||
const P = pointOnCircle(center, r, aFrom);
|
||||
const Q = pointOnCircle(center, r, aTo);
|
||||
const M = pointOnCircle(center, r, mid);
|
||||
return bulgeFromSagittaPoint(P, Q, M);
|
||||
return core().bulge_between_angles(center.x, center.y, r, aFrom, aTo, sweepSign);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kreisbogen-Parameter durch zwei Endpunkte `a`→`b` mit vorgegebenem Radius
|
||||
* `r` — die zweite fehlende Bogen-Konstruktionsmethode aus der Recherche
|
||||
* „Grösster Hebel" (`commands/cmds/arc.ts`, Methode „Start-Ende-Radius").
|
||||
* `near` (typischerweise der Cursor) entscheidet, auf welche Seite der Sehne
|
||||
* sich der Bogen wölbt — analog zu einem gezogenen Bulge-Griff. Liefert
|
||||
* immer den KLEINEREN der beiden möglichen Bögen (Sehnenwinkel ≤ 180°): der
|
||||
* Radius allein legt zwei Kreise fest (Zentrum auf einer der beiden Seiten
|
||||
* der Sehne), aber erst zusammen mit „welcher Bogen dieses Kreises" ergäbe
|
||||
* sich sonst eine dritte, unnötige Mehrdeutigkeit — der kleinere Bogen ist
|
||||
* die für eine Zieh-Geste erwartbare, stetige Wahl (grosser Radius ⇒ flacher
|
||||
* Bogen, kleiner Radius (nahe der halben Sehnenlänge) ⇒ Halbkreis).
|
||||
* `null`, wenn `r` kleiner als die halbe Sehnenlänge ist (kein Kreis möglich)
|
||||
* oder die Sehne entartet (a≈b).
|
||||
* Kreisbogen durch zwei Endpunkte `a`→`b` mit vorgegebenem Radius `r` (Methode „Start-Ende-
|
||||
* Radius"). `near` (typischerweise der Cursor) wählt die Seite der Sehne; es entsteht immer der
|
||||
* KLEINERE der beiden möglichen Bögen (Sehnenwinkel ≤ 180°). `null`, wenn `r` kleiner als die
|
||||
* halbe Sehnenlänge ist oder die Sehne entartet.
|
||||
*/
|
||||
export function arcFromStartEndRadius(
|
||||
a: Vec2,
|
||||
b: Vec2,
|
||||
r: number,
|
||||
near: Vec2,
|
||||
): { center: Vec2; r: number; a0: number; a1: number } | null {
|
||||
const dx = b.x - a.x, dy = b.y - a.y;
|
||||
const chord = Math.hypot(dx, dy);
|
||||
if (chord < EPS) return null;
|
||||
const h = chord / 2;
|
||||
if (r < h - EPS) return null;
|
||||
const rr = Math.max(r, h);
|
||||
const s = rr - Math.sqrt(Math.max(0, rr * rr - h * h)); // Sagitta des kleineren Bogens
|
||||
const ux = dx / chord, uy = dy / chord;
|
||||
const nx = -uy, ny = ux; // Links-Normale von a→b, wie `bulgeArc`
|
||||
const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
|
||||
const sideSign = (near.x - mx) * nx + (near.y - my) * ny >= 0 ? 1 : -1;
|
||||
const bulge = (sideSign * s) / h;
|
||||
const arc = bulgeArc(a, b, bulge);
|
||||
if (!arc) return null;
|
||||
return arc.sweep < 0
|
||||
? { center: arc.center, r: arc.r, a0: arc.a1, a1: arc.a0 }
|
||||
: { center: arc.center, r: arc.r, a0: arc.a0, a1: arc.a1 };
|
||||
export function arcFromStartEndRadius(a: Vec2, b: Vec2, r: number, near: Vec2): ArcParams | null {
|
||||
return toArcParams(core().arc_from_start_end_radius(a.x, a.y, b.x, b.y, r, near.x, near.y));
|
||||
}
|
||||
|
||||
/**
|
||||
* Kreisbogen-Parameter durch zwei Endpunkte `a`→`b`, tangential zu einer bei
|
||||
* `a` vorgegebenen Richtung (`dir`, ein Punkt AUF dem Tangentenstrahl, nicht
|
||||
* zwingend auf dem Bogen selbst) — dritte fehlende Bogen-Konstruktions-
|
||||
* methode. Der Kreismittelpunkt steht per Definition senkrecht zur Tangente
|
||||
* bei `a` UND auf der Mittelsenkrechten von a-b — beide Geraden geschnitten
|
||||
* (`lineIntersect`) ergeben ihn eindeutig, ohne Fallunterscheidung. Die
|
||||
* Schwenkrichtung (CCW/CW von a0 nach a1) wird so gewählt, dass die
|
||||
* Bogen-Tangente bei a tatsächlich in Richtung `dir` zeigt (nicht rückwärts).
|
||||
* `null` bei entarteter Tangente (`dir`≈`a`) oder wenn die Tangente exakt
|
||||
* entlang der Sehne a-b zeigt (Mittelsenkrechte und Tangenten-Normale
|
||||
* parallel — kein eindeutiger Kreis, Grenzfall „Gerade").
|
||||
* Kreisbogen durch `a`→`b`, bei `a` tangential zur Richtung `dir` (ein Punkt AUF dem
|
||||
* Tangentenstrahl). `null` bei entarteter Tangente oder wenn sie entlang der Sehne a-b zeigt.
|
||||
*/
|
||||
export function arcFromStartEndDirection(
|
||||
a: Vec2,
|
||||
b: Vec2,
|
||||
dir: Vec2,
|
||||
): { center: Vec2; r: number; a0: number; a1: number } | null {
|
||||
const tx = dir.x - a.x, ty = dir.y - a.y;
|
||||
const tLen = Math.hypot(tx, ty);
|
||||
if (tLen < EPS) return null;
|
||||
const ux = tx / tLen, uy = ty / tLen;
|
||||
const tangentNormal = { x: -uy, y: ux }; // senkrecht zur Tangente bei a
|
||||
const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
|
||||
const chordNormal = { x: -(b.y - a.y), y: b.x - a.x }; // senkrecht zur Sehne a-b
|
||||
const center = lineIntersect(a, tangentNormal, mid, chordNormal);
|
||||
if (!center) return null;
|
||||
const r = Math.hypot(a.x - center.x, a.y - center.y);
|
||||
if (r < EPS) return null;
|
||||
const a0raw = Math.atan2(a.y - center.y, a.x - center.x);
|
||||
const a1raw = Math.atan2(b.y - center.y, b.x - center.x);
|
||||
// CCW-Tangentenrichtung bei a0raw ist die Ableitung von (cos,sin) nach
|
||||
// wachsendem Winkel: (−sin,cos). Zeigt sie NICHT in Richtung (ux,uy), muss
|
||||
// der Bogen stattdessen CW laufen (a0/a1 vertauscht, wie `arcThroughPoints`
|
||||
// bei negativem `sweep`).
|
||||
const tangentCCW = { x: -Math.sin(a0raw), y: Math.cos(a0raw) };
|
||||
const matchesCCW = tangentCCW.x * ux + tangentCCW.y * uy >= 0;
|
||||
return matchesCCW
|
||||
? { center, r, a0: a0raw, a1: a1raw }
|
||||
: { center, r, a0: a1raw, a1: a0raw };
|
||||
export function arcFromStartEndDirection(a: Vec2, b: Vec2, dir: Vec2): ArcParams | null {
|
||||
return toArcParams(core().arc_from_start_end_direction(a.x, a.y, b.x, b.y, dir.x, dir.y));
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* `geometry/stair.ts` — Fassade über den Rust-Kern: Form-Prüfungen für gerade/L/Wendel,
|
||||
* Referenz, Schnitt, Rahmen und Unsinn-Eingaben (Rust-Tests decken die Mathematik je Fall ab).
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { defaultStepCount, stairBBox, stairCut, stairGeometry, stairOutline } from "./stair";
|
||||
import type { Stair } from "../model/types";
|
||||
|
||||
const base: Stair = {
|
||||
id: "s", type: "stair", floorId: "eg", categoryCode: "40", shape: "straight",
|
||||
start: { x: 0, y: 0 }, dir: { x: 1, y: 0 }, runLength: 3, width: 1.2, stepCount: 16,
|
||||
};
|
||||
|
||||
describe("stairGeometry", () => {
|
||||
it("gerade: 16 Tritte, Setzstufe, Lauflinie, Pfeil nach oben", () => {
|
||||
const g = stairGeometry(base, 2.8);
|
||||
expect(g.treads).toHaveLength(16);
|
||||
expect(g.riserHeight).toBeCloseTo(0.175, 12);
|
||||
expect(g.landing).toBeNull();
|
||||
expect(g.treads[15].topRise).toBeCloseTo(2.8, 12);
|
||||
expect(g.arrow.head[1]).toEqual(g.runLine[1]);
|
||||
expect(stairGeometry({ ...base, up: false }, 2.8).arrow.head[1]).toEqual(g.runLine[0]);
|
||||
});
|
||||
|
||||
it("L: Podest + zweiter Lauf, turn dreht die Richtung", () => {
|
||||
const l: Stair = { ...base, shape: "L", run2Length: 2 };
|
||||
const g = stairGeometry(l, 2.8);
|
||||
expect(g.treads).toHaveLength(15);
|
||||
expect(g.landing).toHaveLength(4);
|
||||
expect(g.runLine[2].y).toBeGreaterThan(1);
|
||||
expect(stairGeometry({ ...l, turn: -1 }, 2.8).runLine[2].y).toBeLessThan(-1);
|
||||
});
|
||||
|
||||
it("Wendel: Keile, Auge mit 12 Punkten, Lauflinie als Bogen", () => {
|
||||
const sp: Stair = { ...base, shape: "spiral", center: { x: 0, y: 0 }, start: { x: 1, y: 0 }, radius: 1, stepCount: 12 };
|
||||
const g = stairGeometry(sp, 2.4);
|
||||
expect(g.treads).toHaveLength(12);
|
||||
expect(g.landing).toHaveLength(12);
|
||||
expect(g.runLine).toHaveLength(13);
|
||||
});
|
||||
|
||||
it("Referenz links versetzt die Achse eine halbe Breite auf die Mitte", () => {
|
||||
const g = stairGeometry({ ...base, referenz: "links" }, 2.8);
|
||||
expect(g.treads[0].pts[0].y).toBeCloseTo(0, 12);
|
||||
expect(g.treads[0].pts[3].y).toBeCloseTo(-1.2, 12);
|
||||
expect(stairOutline({ ...base, referenz: "rechts" }, 0).polygon![0].y).toBeCloseTo(1.2, 12);
|
||||
});
|
||||
|
||||
it("Unsinn (NaN, 0 Stufen) liefert leere bzw. Mindest-Geometrie ohne Fehler", () => {
|
||||
expect(stairGeometry({ ...base, width: NaN }, 2.8).treads).toEqual([]);
|
||||
expect(stairGeometry(base, NaN).treads).toEqual([]);
|
||||
expect(stairGeometry({ ...base, stepCount: 0 }, 2.8).treads).toHaveLength(2);
|
||||
expect(stairOutline({ ...base, runLength: NaN }, 0)).toEqual({ polygon: null, spiral: null });
|
||||
expect(stairBBox(stairGeometry(base, NaN))).toEqual({ minX: 0, minY: 0, maxX: 0, maxY: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("stairCut / stairBBox / defaultStepCount", () => {
|
||||
it("Schnitt teilt die Tritte und legt eine Doppel-Bruchlinie", () => {
|
||||
const g = stairGeometry(base, 2.8);
|
||||
const c = stairCut(g, 1.0);
|
||||
expect(c.belowIndices).toEqual([0, 1, 2, 3, 4]);
|
||||
expect(c.aboveIndices).toHaveLength(11);
|
||||
expect(c.breakLine).toHaveLength(2);
|
||||
expect(stairCut(g, 99).breakLine).toBeNull();
|
||||
expect(stairCut(stairGeometry(base, NaN), 1)).toEqual({ belowIndices: [], aboveIndices: [], breakLine: null });
|
||||
});
|
||||
|
||||
it("BBox über Tritte", () => {
|
||||
const b = stairBBox(stairGeometry(base, 2.8));
|
||||
expect(b.maxX).toBeCloseTo(3, 12);
|
||||
expect(b.minY).toBeCloseTo(-0.6, 12);
|
||||
});
|
||||
|
||||
it("Vorgabe-Stufenzahl: Steighöhe 0.17, gedeckelt durch die Lauflänge, mind. 2", () => {
|
||||
expect(defaultStepCount(2.8, 10)).toBe(16);
|
||||
expect(defaultStepCount(2.8, 3)).toBe(13);
|
||||
expect(defaultStepCount(0.1, 0)).toBe(2);
|
||||
});
|
||||
});
|
||||
+126
-461
@@ -1,57 +1,23 @@
|
||||
// Geometrie-Helfer für Treppen (Stairs) — reine Funktionen über `Vec2`, kein
|
||||
// externer Kernel. Aus einer `Stair` (gerade/L/Wendel) werden abgeleitet:
|
||||
// Geometrie-Helfer für Treppen (Stairs) — Fassade über den Rust-Kern
|
||||
// (`src-tauri/kernel2d/src/lib.rs`: `stair_geometry`, `stair_outline`, `stair_cut`, `stair_bbox`;
|
||||
// Bindungen `src-tauri/core/src/web/stair.rs`, Kodierung `src-tauri/core/src/stair.rs`).
|
||||
// Aus einer `Stair` (gerade/L/Wendel) werden abgeleitet:
|
||||
// • die Tritt-Rechtecke im Grundriss (jeweils mit ihrer Z-Höhe der Setzstufe),
|
||||
// • das Zwischenpodest-Polygon (L / Wendel-Auge),
|
||||
// • die Lauflinie (Polyline) + der Auf-/Abpfeil,
|
||||
// • die Schnittposition (welche Tritte unter/über der Grundriss-Schnitthöhe
|
||||
// liegen → im Plan durchgezogen vs. gestrichelt) samt SIA-Bruchlinie.
|
||||
// liegen → im Plan durchgezogen vs. gestrichelt) samt SIA-Bruchlinie,
|
||||
// • die Plan-Aussenlinie (`stairOutline`).
|
||||
//
|
||||
// Die 3D-Darstellung baut aus denselben Tritt-Rechtecken + Setzstufen-Höhen die
|
||||
// Stufenboxen (siehe Viewport3D). So bleiben Plan und 3D konsistent aus EINER
|
||||
// Quelle abgeleitet.
|
||||
// Stufenboxen (siehe `plan/toWalls3d/stairs.ts`). So bleiben Plan und 3D konsistent
|
||||
// aus EINER Quelle abgeleitet. Referenz (links/mitte/rechts): die gespeicherte Achse wird im
|
||||
// Kern auf die visuelle Treppen-MITTE versetzt, Lauflinie samt Pfeil liegen stets auf der Mitte.
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
// Bezeichner englisch, Kommentare deutsch.
|
||||
|
||||
import type { Stair, Vec2 } from "../model/types";
|
||||
|
||||
const DEG = Math.PI / 180;
|
||||
|
||||
const sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });
|
||||
const add = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x + b.x, y: a.y + b.y });
|
||||
const scale = (a: Vec2, s: number): Vec2 => ({ x: a.x * s, y: a.y * s });
|
||||
const lenOf = (a: Vec2): number => Math.hypot(a.x, a.y);
|
||||
const norm = (a: Vec2): Vec2 => {
|
||||
const l = lenOf(a) || 1e-9;
|
||||
return { x: a.x / l, y: a.y / l };
|
||||
};
|
||||
/** Linke Normale (n = (−u.y, u.x)) — quer zur Laufrichtung. */
|
||||
const leftN = (u: Vec2): Vec2 => ({ x: -u.y, y: u.x });
|
||||
|
||||
/**
|
||||
* Perp-Versatz von der Referenzkante zur visuellen Treppen-MITTE, entlang der
|
||||
* linken Normale `n = leftN(u)`. Entspricht `mid_off` aus `_treppe_2d_side_offsets`
|
||||
* im Rhino-Plugin (Konvention: `perp` = CCW-Normale = linke Normale):
|
||||
* • referenz "links" → Achse ist die LINKE Kante; die Mitte liegt eine
|
||||
* halbe Breite in −n-Richtung (rechts) → mid_off = −width/2.
|
||||
* • referenz "rechts" → Achse ist die RECHTE Kante; die Mitte liegt eine
|
||||
* halbe Breite in +n-Richtung (links) → mid_off = +width/2.
|
||||
* • referenz "mitte"/undefined → Achse ist bereits die Mitte → 0.
|
||||
*
|
||||
* ANNAHME (selbstkritisch): „links" heisst „linke Kante in Laufrichtung", und die
|
||||
* linke Kante liegt in +n (n = leftN(u), 90° links der Laufrichtung). Von der
|
||||
* linken Kante zur Mitte geht es also nach −n, daher mid_off = −width/2. Das
|
||||
* deckt sich mit `_treppe_2d_side_offsets` (referenz="links" → off_a=0, off_b=−b,
|
||||
* Mitte = −b/2·perp). Wird die Richtung im UI als seitenverkehrt empfunden, ist
|
||||
* hier das Vorzeichen zu drehen — die Geometrie bleibt in sich konsistent.
|
||||
*/
|
||||
function referenzMidShift(stair: Stair, u: Vec2): Vec2 {
|
||||
const ref = stair.referenz ?? "mitte";
|
||||
if (ref === "mitte") return { x: 0, y: 0 };
|
||||
const n = leftN(u);
|
||||
const halfW = Math.max(0.05, stair.width / 2);
|
||||
const midOff = ref === "links" ? -halfW : halfW;
|
||||
return scale(n, midOff);
|
||||
}
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
/** SIA-nahe Schrittregel: gute Steigungshöhe ≈ 0.17 m, Auftritt ≈ 0.29 m. */
|
||||
export const IDEAL_RISER = 0.17;
|
||||
@@ -64,10 +30,7 @@ export const MIN_STEPS = 2;
|
||||
* Auftritt ~0.24 m). Immer ≥ MIN_STEPS.
|
||||
*/
|
||||
export function defaultStepCount(totalRise: number, runLength: number): number {
|
||||
const byRise = Math.max(MIN_STEPS, Math.round(totalRise / IDEAL_RISER));
|
||||
// Auftrittstiefe = runLength / (steps − 1); mind. 0.24 m halten.
|
||||
const maxByRun = runLength > 0 ? Math.max(MIN_STEPS, Math.floor(runLength / 0.24) + 1) : byRise;
|
||||
return Math.max(MIN_STEPS, Math.min(byRise, maxByRun));
|
||||
return core().stair_default_step_count(totalRise, runLength);
|
||||
}
|
||||
|
||||
/** Ein Tritt im Grundriss (Rechteck-Polygon) samt Setzstufen-Z (Oberkante). */
|
||||
@@ -100,252 +63,100 @@ export interface StairGeometry {
|
||||
totalRise: number;
|
||||
}
|
||||
|
||||
/** Rechteck-Tritt zwischen Achsparametern a0..a1 entlang `dir`, Breite `width`. */
|
||||
function treadRect(
|
||||
origin: Vec2,
|
||||
dir: Vec2,
|
||||
n: Vec2,
|
||||
a0: number,
|
||||
a1: number,
|
||||
halfW: number,
|
||||
): Vec2[] {
|
||||
const p0 = add(origin, scale(dir, a0));
|
||||
const p1 = add(origin, scale(dir, a1));
|
||||
return [
|
||||
add(p0, scale(n, halfW)),
|
||||
add(p1, scale(n, halfW)),
|
||||
add(p1, scale(n, -halfW)),
|
||||
add(p0, scale(n, -halfW)),
|
||||
];
|
||||
const FORM = { straight: 0, L: 1, spiral: 2 } as const;
|
||||
const REFERENZ = { mitte: 0, links: 1, rechts: 2 } as const;
|
||||
|
||||
/** Treppen-Parameter als 16 Zahlen (Aufbau: `src-tauri/core/src/stair.rs`); fehlend = NaN. */
|
||||
function encodeStair(s: Stair): Float64Array {
|
||||
const n = (v: number | undefined) => (v === undefined ? Number.NaN : v);
|
||||
return Float64Array.of(
|
||||
FORM[s.shape] ?? 0,
|
||||
s.start.x, s.start.y,
|
||||
s.dir.x, s.dir.y,
|
||||
s.runLength,
|
||||
n(s.run2Length),
|
||||
n(s.turn),
|
||||
n(s.center?.x), n(s.center?.y),
|
||||
n(s.radius),
|
||||
n(s.sweep),
|
||||
s.width,
|
||||
s.stepCount,
|
||||
s.up === undefined ? Number.NaN : s.up ? 1 : 0,
|
||||
REFERENZ[s.referenz ?? "mitte"] ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
const pt = (f: Float64Array, i: number): Vec2 => ({ x: f[i], y: f[i + 1] });
|
||||
|
||||
function ptsAt(f: Float64Array, i: number, n: number): Vec2[] {
|
||||
const out: Vec2[] = new Array(n);
|
||||
for (let k = 0; k < n; k++) out[k] = pt(f, i + 2 * k);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Flache Treppengeometrie (Aufbau: `stair.rs`) → Objekt; leer (Unsinn-Eingabe) → leere Geometrie. */
|
||||
function decodeGeometry(f: Float64Array): StairGeometry {
|
||||
if (f.length < 4) {
|
||||
const z = { x: 0, y: 0 };
|
||||
return {
|
||||
treads: [], landing: null, riserHeight: 0, treadDepth: 0, runLine: [],
|
||||
arrow: { shaft: [z, z], head: [z, z, z] }, totalRise: 0,
|
||||
};
|
||||
}
|
||||
const nTreads = f[3];
|
||||
let i = 4;
|
||||
const treads: TreadRect[] = [];
|
||||
for (let t = 0; t < nTreads; t++, i += 11) {
|
||||
treads.push({ index: f[i], topRise: f[i + 1], baseRise: f[i + 2], pts: ptsAt(f, i + 3, 4) });
|
||||
}
|
||||
const nl = f[i++];
|
||||
let landing: Vec2[] | null = null;
|
||||
if (nl >= 0) {
|
||||
landing = ptsAt(f, i, nl);
|
||||
i += 2 * nl;
|
||||
}
|
||||
const nRun = f[i++];
|
||||
const runLine = ptsAt(f, i, nRun);
|
||||
i += 2 * nRun;
|
||||
const a = ptsAt(f, i, 5);
|
||||
return {
|
||||
treads,
|
||||
landing,
|
||||
riserHeight: f[0],
|
||||
treadDepth: f[1],
|
||||
runLine,
|
||||
arrow: { shaft: [a[0], a[1]], head: [a[2], a[3], a[4]] },
|
||||
totalRise: f[2],
|
||||
};
|
||||
}
|
||||
|
||||
/** Geometrie → flacher Puffer (gleicher Aufbau wie die Ausgabe von `stair_geometry_flat`). */
|
||||
function encodeGeometry(g: StairGeometry): Float64Array {
|
||||
const out: number[] = [g.riserHeight, g.treadDepth, g.totalRise, g.treads.length];
|
||||
const push = (p: Vec2) => out.push(p.x, p.y);
|
||||
for (const t of g.treads) {
|
||||
out.push(t.index, t.topRise, t.baseRise);
|
||||
t.pts.forEach(push);
|
||||
}
|
||||
if (g.landing) {
|
||||
out.push(g.landing.length);
|
||||
g.landing.forEach(push);
|
||||
} else out.push(-1);
|
||||
out.push(g.runLine.length);
|
||||
g.runLine.forEach(push);
|
||||
push(g.arrow.shaft[0]);
|
||||
push(g.arrow.shaft[1]);
|
||||
g.arrow.head.forEach(push);
|
||||
return Float64Array.from(out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Leitet die vollständige Geometrie einer Treppe ab. `totalRise` MUSS vom
|
||||
* Aufrufer aufgelöst übergeben werden (Geschosshöhe-Default liegt in
|
||||
* `stairVerticalExtent`), damit dieses Modul three-/projektfrei bleibt.
|
||||
* `stairVerticalExtent`), damit dieses Modul modellfrei bleibt.
|
||||
*/
|
||||
export function stairGeometry(stair: Stair, totalRise: number): StairGeometry {
|
||||
const steps = Math.max(MIN_STEPS, Math.round(stair.stepCount));
|
||||
const riserHeight = totalRise / steps;
|
||||
const halfW = Math.max(0.05, stair.width / 2);
|
||||
const u = norm(stair.dir);
|
||||
const n = leftN(u);
|
||||
|
||||
// Referenz (links/mitte/rechts): die gespeicherte Achse wird auf die visuelle
|
||||
// Treppen-MITTE versetzt, danach greift die bestehende, um die Achse zentrierte
|
||||
// Tritt-/Lauflinien-Logik unverändert. So bleibt die Lauflinie samt Pfeil stets
|
||||
// auf der Mitte (nicht auf der Referenzkante). "mitte"/undefined ⇒ Nullversatz.
|
||||
const c = referenzMidShift(stair, u);
|
||||
const s = stair.referenz && stair.referenz !== "mitte"
|
||||
? { ...stair, start: add(stair.start, c), center: stair.center ? add(stair.center, c) : stair.center }
|
||||
: stair;
|
||||
|
||||
if (s.shape === "spiral") {
|
||||
return spiralGeometry(s, totalRise, steps, riserHeight, halfW);
|
||||
}
|
||||
if (s.shape === "L") {
|
||||
return lGeometry(s, totalRise, steps, riserHeight, halfW, u, n);
|
||||
}
|
||||
return straightGeometry(s, totalRise, steps, riserHeight, halfW, u, n);
|
||||
}
|
||||
|
||||
/** Gerade Treppe: gleich breite Tritte über die Lauflänge. */
|
||||
function straightGeometry(
|
||||
stair: Stair,
|
||||
totalRise: number,
|
||||
steps: number,
|
||||
riserHeight: number,
|
||||
halfW: number,
|
||||
u: Vec2,
|
||||
n: Vec2,
|
||||
): StairGeometry {
|
||||
const runLength = Math.max(0.1, stair.runLength);
|
||||
const treadDepth = runLength / steps;
|
||||
const treads: TreadRect[] = [];
|
||||
for (let i = 0; i < steps; i++) {
|
||||
treads.push({
|
||||
pts: treadRect(stair.start, u, n, i * treadDepth, (i + 1) * treadDepth, halfW),
|
||||
index: i,
|
||||
baseRise: i * riserHeight,
|
||||
topRise: (i + 1) * riserHeight,
|
||||
});
|
||||
}
|
||||
const runLine: Vec2[] = [
|
||||
add(stair.start, scale(u, treadDepth * 0.5)),
|
||||
add(stair.start, scale(u, runLength - treadDepth * 0.15)),
|
||||
];
|
||||
return {
|
||||
treads,
|
||||
landing: null,
|
||||
riserHeight,
|
||||
treadDepth,
|
||||
runLine,
|
||||
arrow: arrowFor(runLine, stair.up !== false),
|
||||
totalRise,
|
||||
};
|
||||
}
|
||||
|
||||
/** L-Treppe: zwei Läufe + quadratisches Zwischenpodest an der Ecke. */
|
||||
function lGeometry(
|
||||
stair: Stair,
|
||||
totalRise: number,
|
||||
steps: number,
|
||||
riserHeight: number,
|
||||
halfW: number,
|
||||
u: Vec2,
|
||||
n: Vec2,
|
||||
): StairGeometry {
|
||||
const run1 = Math.max(0.1, stair.runLength);
|
||||
const run2 = Math.max(0.1, stair.run2Length ?? stair.runLength);
|
||||
const turn = stair.turn ?? 1;
|
||||
// Podest quadratisch (Kantenlänge = Laufbreite) am Ende des ersten Laufs.
|
||||
const podest = 2 * halfW;
|
||||
// Stufen auf beide Läufe verteilen (grob proportional zur Lauflänge), ein Tritt
|
||||
// fällt aufs Podest.
|
||||
const bodySteps = steps - 1; // ein Tritt = Podest
|
||||
const s1 = Math.max(1, Math.round((bodySteps * run1) / (run1 + run2)));
|
||||
const s2 = Math.max(1, bodySteps - s1);
|
||||
const td1 = run1 / s1;
|
||||
const td2 = run2 / s2;
|
||||
|
||||
const treads: TreadRect[] = [];
|
||||
let rise = 0;
|
||||
for (let i = 0; i < s1; i++) {
|
||||
treads.push({
|
||||
pts: treadRect(stair.start, u, n, i * td1, (i + 1) * td1, halfW),
|
||||
index: i,
|
||||
baseRise: rise,
|
||||
topRise: rise + riserHeight,
|
||||
});
|
||||
rise += riserHeight;
|
||||
}
|
||||
// Zweiter Lauf beginnt am Ende des Podests. Richtung um 90° gedreht (turn).
|
||||
const cornerCenter = add(stair.start, scale(u, run1 + halfW));
|
||||
const u2: Vec2 = turn > 0 ? n : scale(n, -1); // links/rechts abbiegen
|
||||
const n2 = leftN(u2);
|
||||
// Podest-Tritt (quadratisch um cornerCenter, an u/u2 ausgerichtet).
|
||||
const landing: Vec2[] = [
|
||||
add(add(cornerCenter, scale(u, -halfW)), scale(n, halfW)),
|
||||
add(add(cornerCenter, scale(u, halfW)), scale(n, halfW)),
|
||||
add(add(cornerCenter, scale(u, halfW)), scale(n, -halfW)),
|
||||
add(add(cornerCenter, scale(u, -halfW)), scale(n, -halfW)),
|
||||
];
|
||||
const podestTopRise = rise + riserHeight;
|
||||
rise += riserHeight;
|
||||
// Startpunkt des zweiten Laufs: Podest-Kante in Richtung u2.
|
||||
const run2Start = add(cornerCenter, scale(u2, halfW));
|
||||
for (let i = 0; i < s2; i++) {
|
||||
treads.push({
|
||||
pts: treadRect(run2Start, u2, n2, i * td2, (i + 1) * td2, halfW),
|
||||
index: s1 + 1 + i,
|
||||
baseRise: rise,
|
||||
topRise: rise + riserHeight,
|
||||
});
|
||||
rise += riserHeight;
|
||||
}
|
||||
void podest;
|
||||
void podestTopRise;
|
||||
|
||||
const runLine: Vec2[] = [
|
||||
add(stair.start, scale(u, td1 * 0.5)),
|
||||
cornerCenter,
|
||||
add(run2Start, scale(u2, run2 - td2 * 0.15)),
|
||||
];
|
||||
return {
|
||||
treads,
|
||||
landing,
|
||||
riserHeight,
|
||||
treadDepth: td1,
|
||||
runLine,
|
||||
arrow: arrowFor(runLine, stair.up !== false),
|
||||
totalRise,
|
||||
};
|
||||
}
|
||||
|
||||
/** Wendeltreppe: keilförmige Tritte um ein Zentrum (vereinfachtes Modell). */
|
||||
function spiralGeometry(
|
||||
stair: Stair,
|
||||
totalRise: number,
|
||||
steps: number,
|
||||
riserHeight: number,
|
||||
halfW: number,
|
||||
): StairGeometry {
|
||||
const center = stair.center ?? stair.start;
|
||||
const radius = Math.max(halfW + 0.1, stair.radius ?? stair.width);
|
||||
const sweep = (stair.sweep ?? 270) * DEG;
|
||||
// Startwinkel aus start→center (Lauflinie beginnt am Startpunkt).
|
||||
const startVec = sub(stair.start, center);
|
||||
const a0 = Math.atan2(startVec.y, startVec.x);
|
||||
const dA = sweep / steps;
|
||||
const rIn = Math.max(0.02, radius - halfW);
|
||||
const rOut = radius + halfW;
|
||||
|
||||
const treads: TreadRect[] = [];
|
||||
for (let i = 0; i < steps; i++) {
|
||||
const t0 = a0 + i * dA;
|
||||
const t1 = a0 + (i + 1) * dA;
|
||||
// Keil-Viereck: innen(t0) → außen(t0) → außen(t1) → innen(t1).
|
||||
const pts: Vec2[] = [
|
||||
{ x: center.x + rIn * Math.cos(t0), y: center.y + rIn * Math.sin(t0) },
|
||||
{ x: center.x + rOut * Math.cos(t0), y: center.y + rOut * Math.sin(t0) },
|
||||
{ x: center.x + rOut * Math.cos(t1), y: center.y + rOut * Math.sin(t1) },
|
||||
{ x: center.x + rIn * Math.cos(t1), y: center.y + rIn * Math.sin(t1) },
|
||||
];
|
||||
treads.push({
|
||||
pts,
|
||||
index: i,
|
||||
baseRise: i * riserHeight,
|
||||
topRise: (i + 1) * riserHeight,
|
||||
});
|
||||
}
|
||||
// Lauflinie = Bogen auf Radius `radius` (mittlere Lauflinie).
|
||||
const runLine: Vec2[] = [];
|
||||
const N = Math.max(2, steps);
|
||||
for (let i = 0; i <= N; i++) {
|
||||
const tt = a0 + (sweep * i) / N;
|
||||
runLine.push({ x: center.x + radius * Math.cos(tt), y: center.y + radius * Math.sin(tt) });
|
||||
}
|
||||
return {
|
||||
treads,
|
||||
// Wendel-Auge (Innenkreis) als „Podest"-Polygon.
|
||||
landing: eyePolygon(center, rIn),
|
||||
riserHeight,
|
||||
treadDepth: (2 * Math.PI * radius * (sweep / (2 * Math.PI))) / steps,
|
||||
runLine,
|
||||
arrow: arrowFor(runLine, stair.up !== false),
|
||||
totalRise,
|
||||
};
|
||||
}
|
||||
|
||||
/** Achteck-Approximation des Wendel-Auges (Innenkreis). */
|
||||
function eyePolygon(center: Vec2, r: number): Vec2[] {
|
||||
const pts: Vec2[] = [];
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const t = (i / 12) * Math.PI * 2;
|
||||
pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) });
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Auf-/Abpfeil aus der Lauflinie: Schaft = erstes→letztes Segment, Spitze am
|
||||
* oberen (bzw. bei `up=false` am unteren) Ende. `up` kehrt die Richtung um.
|
||||
*/
|
||||
function arrowFor(
|
||||
runLine: Vec2[],
|
||||
up: boolean,
|
||||
): { shaft: [Vec2, Vec2]; head: [Vec2, Vec2, Vec2] } {
|
||||
const a = runLine[0];
|
||||
const b = runLine[runLine.length - 1];
|
||||
const tip = up ? b : a;
|
||||
const from = up ? runLine[runLine.length - 2] : runLine[1];
|
||||
const dir = norm(sub(tip, from));
|
||||
const n = leftN(dir);
|
||||
const s = 0.22; // Flügellänge (Meter)
|
||||
const back = add(tip, scale(dir, -s));
|
||||
const w1 = add(back, scale(n, s * 0.55));
|
||||
const w2 = add(back, scale(n, -s * 0.55));
|
||||
return { shaft: [a, b], head: [w1, tip, w2] };
|
||||
return decodeGeometry(core().stair_geometry_flat(encodeStair(stair), totalRise));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -370,34 +181,22 @@ export interface StairCut {
|
||||
* legt dort die Bruchlinie quer über den Lauf.
|
||||
*/
|
||||
export function stairCut(geo: StairGeometry, cutRise: number): StairCut {
|
||||
const below: number[] = [];
|
||||
const above: number[] = [];
|
||||
let breakIdx = -1;
|
||||
for (const tr of geo.treads) {
|
||||
if (tr.topRise <= cutRise + 1e-6) {
|
||||
below.push(tr.index);
|
||||
} else {
|
||||
if (breakIdx < 0) breakIdx = tr.index;
|
||||
above.push(tr.index);
|
||||
}
|
||||
}
|
||||
const f = core().stair_cut_flat(encodeGeometry(geo), cutRise);
|
||||
if (f.length < 3) return { belowIndices: [], aboveIndices: [], breakLine: null };
|
||||
let i = 0;
|
||||
const nBelow = f[i++];
|
||||
const belowIndices = Array.from(f.subarray(i, i + nBelow));
|
||||
i += nBelow;
|
||||
const nAbove = f[i++];
|
||||
const aboveIndices = Array.from(f.subarray(i, i + nAbove));
|
||||
i += nAbove;
|
||||
const nBreak = f[i++];
|
||||
let breakLine: [Vec2, Vec2][] | null = null;
|
||||
if (breakIdx >= 0) {
|
||||
const tr = geo.treads.find((t) => t.index === breakIdx);
|
||||
if (tr) {
|
||||
// Diagonale Bruchlinie über den Tritt: von einer Ecke zur gegenüberliegenden,
|
||||
// als Doppelstrich (leicht versetzt) — SIA-Treppen-Schnittsymbol.
|
||||
const [c0, c1, c2, c3] = tr.pts;
|
||||
const mid01 = scale(add(c0, c1), 0.5);
|
||||
const mid23 = scale(add(c2, c3), 0.5);
|
||||
const off = scale(norm(sub(c1, c0)), 0.06);
|
||||
breakLine = [
|
||||
[add(mid01, off), add(mid23, off)],
|
||||
[sub(mid01, off), sub(mid23, off)],
|
||||
];
|
||||
}
|
||||
if (nBreak > 0) {
|
||||
breakLine = [];
|
||||
for (let k = 0; k < nBreak; k++, i += 4) breakLine.push([pt(f, i), pt(f, i + 2)]);
|
||||
}
|
||||
return { belowIndices: below, aboveIndices: above, breakLine };
|
||||
return { belowIndices, aboveIndices, breakLine };
|
||||
}
|
||||
|
||||
/** Achsparallele Bounding-Box aller Tritte (+ Podest) einer Treppengeometrie. */
|
||||
@@ -407,113 +206,13 @@ export function stairBBox(geo: StairGeometry): {
|
||||
maxX: number;
|
||||
maxY: number;
|
||||
} {
|
||||
let minX = Infinity,
|
||||
minY = Infinity,
|
||||
maxX = -Infinity,
|
||||
maxY = -Infinity;
|
||||
const acc = (p: Vec2) => {
|
||||
minX = Math.min(minX, p.x);
|
||||
minY = Math.min(minY, p.y);
|
||||
maxX = Math.max(maxX, p.x);
|
||||
maxY = Math.max(maxY, p.y);
|
||||
};
|
||||
for (const tr of geo.treads) for (const p of tr.pts) acc(p);
|
||||
if (geo.landing) for (const p of geo.landing) acc(p);
|
||||
if (!isFinite(minX)) return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
|
||||
return { minX, minY, maxX, maxY };
|
||||
}
|
||||
|
||||
/** Punkt-in-Polygon (Ray-Casting) — für die Body-Auswahl im Grundriss/3D. */
|
||||
export function pointInPolygon(p: Vec2, poly: Vec2[]): boolean {
|
||||
let inside = false;
|
||||
const nn = poly.length;
|
||||
for (let i = 0, j = nn - 1; i < nn; j = i++) {
|
||||
const a = poly[i];
|
||||
const b = poly[j];
|
||||
const intersect =
|
||||
a.y > p.y !== b.y > p.y &&
|
||||
p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y || 1e-12) + a.x;
|
||||
if (intersect) inside = !inside;
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
/** Ob ein Modellpunkt IRGENDEINEN Tritt (oder das Podest) einer Treppe trifft. */
|
||||
export function pointHitsStair(p: Vec2, geo: StairGeometry): boolean {
|
||||
for (const tr of geo.treads) if (pointInPolygon(p, tr.pts)) return true;
|
||||
if (geo.landing && pointInPolygon(p, geo.landing)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ── Treppen-Aussenlinie (Plan-Outline) ───────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Schliessendes Umriss-Polygon einer geraden Treppe im Grundriss (4 Ecken CCW).
|
||||
* Entspricht `_aussen_gerade` im Rhino-Plugin (Rechteck über Laufbreite + Lauflänge).
|
||||
* Liefert null bei entarteter Geometrie.
|
||||
*/
|
||||
function straightOutlinePoints(stair: Stair, halfW: number): Vec2[] | null {
|
||||
const u = norm({ x: stair.dir.x, y: stair.dir.y });
|
||||
const n = leftN(u);
|
||||
const L = Math.max(1e-4, stair.runLength);
|
||||
const s = stair.start;
|
||||
// Vier Ecken: Start-links → Start-rechts → End-rechts → End-links (CCW).
|
||||
return [
|
||||
add(s, scale(n, halfW)),
|
||||
add(s, scale(n, -halfW)),
|
||||
add(add(s, scale(u, L)), scale(n, -halfW)),
|
||||
add(add(s, scale(u, L)), scale(n, halfW)),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 2D-Linien-Schnittpunkt. Liefert null bei Parallelität (det < ε).
|
||||
* Entspricht `_line_intersect_xy` im Rhino-Plugin.
|
||||
*/
|
||||
function lineIntersect2d(p1: Vec2, d1: Vec2, p2: Vec2, d2: Vec2): Vec2 | null {
|
||||
const det = d1.x * (-d2.y) - d1.y * (-d2.x);
|
||||
if (Math.abs(det) < 1e-9) return null;
|
||||
const dx = p2.x - p1.x;
|
||||
const dy = p2.y - p1.y;
|
||||
const t = (dx * (-d2.y) - dy * (-d2.x)) / det;
|
||||
return { x: p1.x + d1.x * t, y: p1.y + d1.y * t };
|
||||
}
|
||||
|
||||
/**
|
||||
* Umriss-Polygon einer L-Treppe im Grundriss. Entspricht `_aussen_l_polygon`
|
||||
* im Rhino-Plugin: Linien-Schnittpunkte liefern die Ecken des L-Polygons.
|
||||
* Liefert null bei entarteter Geometrie.
|
||||
*/
|
||||
function lOutlinePoints(stair: Stair, halfW: number): Vec2[] | null {
|
||||
const u1 = norm(stair.dir);
|
||||
const n1 = leftN(u1);
|
||||
const L1 = Math.max(1e-4, stair.runLength);
|
||||
const turn = stair.turn ?? 1;
|
||||
const u2: Vec2 = turn > 0 ? n1 : scale(n1, -1);
|
||||
const n2 = leftN(u2);
|
||||
const L2 = Math.max(1e-4, stair.run2Length ?? stair.runLength);
|
||||
|
||||
// Podest-Zentrum am Ende des ersten Laufs (Mitte = halfW hinter dem Lauf-Ende).
|
||||
const corner = add(stair.start, scale(u1, L1 + halfW));
|
||||
const run2Start = add(corner, scale(u2, halfW));
|
||||
|
||||
// Lauf-1-Anfang je Seite
|
||||
const p0l = add(stair.start, scale(n1, halfW));
|
||||
const p0r = add(stair.start, scale(n1, -halfW));
|
||||
// Lauf-2-Ende je Seite
|
||||
const endRun2 = add(run2Start, scale(u2, L2));
|
||||
const p3l = add(endRun2, scale(n2, halfW));
|
||||
const p3r = add(endRun2, scale(n2, -halfW));
|
||||
// Innere Eck-Punkte: Schnittpunkt der parallelen Seitenlinien je Seite.
|
||||
const cornerL = lineIntersect2d(p0l, u1, p3l, scale(u2, -1)) ?? add(corner, scale(n1, halfW));
|
||||
const cornerR = lineIntersect2d(p0r, u1, p3r, scale(u2, -1)) ?? add(corner, scale(n1, -halfW));
|
||||
// CCW-Polygon: p0l → p0r → cornerR → p3r → p3l → cornerL
|
||||
return [p0l, p0r, cornerR, p3r, p3l, cornerL];
|
||||
const f = core().stair_bbox_flat(encodeGeometry(geo));
|
||||
if (f.length < 4) return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
|
||||
return { minX: f[0], minY: f[1], maxX: f[2], maxY: f[3] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Spiral-Outline: Innenbogen + Aussenbogen + zwei radiale Schliesslinien.
|
||||
* Entspricht `_aussen_wendel` im Rhino-Plugin (immer vollständig, ohne Cut).
|
||||
* Die Bögen werden als Kreisbogen-Parameter geliefert (cx/cy/r/a0/a1), die
|
||||
* radialen Schliesslinien als Segment-Paare.
|
||||
*/
|
||||
@@ -524,60 +223,26 @@ export interface SpiralOutlineSegments {
|
||||
arcs: { cx: number; cy: number; r: number; a0: number; a1: number }[];
|
||||
}
|
||||
|
||||
function spiralOutline(stair: Stair, halfW: number): SpiralOutlineSegments | null {
|
||||
const center = stair.center ?? stair.start;
|
||||
const radius = Math.max(halfW + 0.1, stair.radius ?? stair.width);
|
||||
const sweep = (stair.sweep ?? 270) * (Math.PI / 180);
|
||||
const startVec = sub(stair.start, center);
|
||||
const a0 = Math.atan2(startVec.y, startVec.x);
|
||||
const a1 = a0 + sweep;
|
||||
const rIn = Math.max(0.02, radius - halfW);
|
||||
const rOut = radius + halfW;
|
||||
|
||||
const ptAt = (r: number, a: number): Vec2 => ({
|
||||
x: center.x + r * Math.cos(a),
|
||||
y: center.y + r * Math.sin(a),
|
||||
});
|
||||
|
||||
return {
|
||||
lines: [
|
||||
[ptAt(rIn, a0), ptAt(rOut, a0)],
|
||||
[ptAt(rIn, a1), ptAt(rOut, a1)],
|
||||
],
|
||||
arcs: [
|
||||
{ cx: center.x, cy: center.y, r: rIn, a0, a1 },
|
||||
{ cx: center.x, cy: center.y, r: rOut, a0, a1 },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Aussenlinie einer Treppe im Grundriss je nach Form:
|
||||
* • gerade → geschlossenes Rechteck als Polygon-Punkte.
|
||||
* • L → L-Polygon via Linien-Schnittpunkten.
|
||||
* • Wendel → `SpiralOutlineSegments` (Bögen + radiale Linien).
|
||||
*
|
||||
* Genau einer von `polygon` / `spiral` ist nicht null.
|
||||
* Genau einer von `polygon` / `spiral` ist nicht null (bei Unsinn-Eingabe beide null).
|
||||
*/
|
||||
export function stairOutline(
|
||||
stair: Stair,
|
||||
totalRise: number,
|
||||
): { polygon: Vec2[] | null; spiral: SpiralOutlineSegments | null } {
|
||||
void totalRise; // Signatur-Konsistenz mit stairGeometry; derzeit ungenutzt
|
||||
const halfW = Math.max(0.05, stair.width / 2);
|
||||
// Referenz (links/mitte/rechts): die gespeicherte Achse zuerst auf die
|
||||
// visuelle Treppen-Mitte versetzen, danach die um die Mitte zentrierte
|
||||
// Aussenlinien-Logik unverändert anwenden (identisch zu `stairGeometry`).
|
||||
const u = norm(stair.dir);
|
||||
const c = referenzMidShift(stair, u);
|
||||
const s = stair.referenz && stair.referenz !== "mitte"
|
||||
? { ...stair, start: add(stair.start, c), center: stair.center ? add(stair.center, c) : stair.center }
|
||||
: stair;
|
||||
if (s.shape === "spiral") {
|
||||
return { polygon: null, spiral: spiralOutline(s, halfW) };
|
||||
}
|
||||
if (s.shape === "L") {
|
||||
return { polygon: lOutlinePoints(s, halfW), spiral: null };
|
||||
}
|
||||
return { polygon: straightOutlinePoints(s, halfW), spiral: null };
|
||||
const f = core().stair_outline_flat(encodeStair(stair));
|
||||
if (f.length === 0) return { polygon: null, spiral: null };
|
||||
if (f[0] === 0) return { polygon: ptsAt(f, 2, f[1]), spiral: null };
|
||||
const l = ptsAt(f, 1, 4);
|
||||
const arcs = [0, 1].map((k) => {
|
||||
const j = 9 + 5 * k;
|
||||
return { cx: f[j], cy: f[j + 1], r: f[j + 2], a0: f[j + 3], a1: f[j + 4] };
|
||||
});
|
||||
return { polygon: null, spiral: { lines: [[l[0], l[1]], [l[2], l[3]]], arcs } };
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
import { layersStyleSig } from "./layerSig";
|
||||
import { ellipsePts, sampleBezierChain, sampleCatmullRom, sampleUniformBSpline } from "../../geometry/curves";
|
||||
import { scaleGeom } from "../../geometry/geomTransform";
|
||||
import { bulgeArc, bulgeArcPoints } from "../../geometry/bulge";
|
||||
import { bulgeArc, bulgePolylinePoints } from "../../geometry/bulge";
|
||||
import { END_MARK_DEFAULT_SIZE_MM, addEndMark, pullBack } from "./endMarks";
|
||||
import {
|
||||
DEFAULT_SCALE_DENOMINATOR,
|
||||
@@ -570,18 +570,10 @@ function addDrawing2DInner(
|
||||
// dadurch bleibt der Bogen bei jedem Zoom rund und kommt im DXF als
|
||||
// ARC statt als Kette von LINEs an (dasselbe Primitiv, das die
|
||||
// Kreis-/Bogen-Werkzeuge schon nutzen, inkl. Auswahl + GL-Pfad).
|
||||
const ring: Vec2[] = [g.pts[0]];
|
||||
for (let i = 0; i < g.pts.length - 1; i++) {
|
||||
const sub = bulgeArcPoints(g.pts[i], g.pts[i + 1], g.bulge?.[i]);
|
||||
for (let k = 1; k < sub.length; k++) ring.push(sub[k]);
|
||||
}
|
||||
if (g.closed && g.pts.length > 2) {
|
||||
const sub = bulgeArcPoints(g.pts[g.pts.length - 1], g.pts[0], g.bulge?.[g.pts.length - 1]);
|
||||
for (let k = 1; k < sub.length; k++) ring.push(sub[k]);
|
||||
// Letzter Punkt dupliziert ring[0] (Schliess-Segment endet dort) — für
|
||||
// die Füllfläche nicht nötig, das SVG-`<polygon>` schliesst implizit.
|
||||
fillPoly(ring.slice(0, -1));
|
||||
}
|
||||
// Geschlossen ohne wiederholten Startpunkt — das SVG-`<polygon>` schliesst implizit.
|
||||
const closedRing = g.closed && g.pts.length > 2;
|
||||
const ring = bulgePolylinePoints(g.pts, g.bulge, closedRing);
|
||||
if (closedRing) fillPoly(ring);
|
||||
/** Ein Segment a→b: gerade als Linie, gekrümmt als echter Bogen. */
|
||||
const emitSegment = (a: Vec2, b: Vec2, bulge: number | undefined) => {
|
||||
const arc = bulge !== undefined ? bulgeArc(a, b, bulge) : null;
|
||||
|
||||
Reference in new issue
Block a user