Merge remote-tracking branch 'origin/master' into worktree-agent-a0f13906a9829e7a3
# Conflicts: # src-tauri/core/src/plan/elevation.rs # src-tauri/core/src/plan/section.rs
This commit is contained in:
101 files changed
+8304
-374
No files matched your search
@@ -20,6 +20,9 @@ pub struct WallIn {
|
||||
pub start: Vec2,
|
||||
pub end: Vec2,
|
||||
pub thickness: f64,
|
||||
/// Versatz der Wandmitte von der Achse (links der Laufrichtung positiv): Wände mit Referenzlinie
|
||||
/// links/rechts oder -versatz liegen nicht mittig auf ihrer Achse.
|
||||
pub shift: f64,
|
||||
}
|
||||
|
||||
/// Öffnung: Index der Wirtswand in der Wandliste, Leibungspunkte auf der Achse.
|
||||
@@ -66,8 +69,9 @@ fn wall_rect(w: &WallIn, t: f64, ext_start: f64, ext_end: f64) -> Ring {
|
||||
let len = dx.hypot(dy);
|
||||
let (ux, uy) = (dx / len, dy / len);
|
||||
let (nx, ny) = (-uy * (t / 2.0), ux * (t / 2.0));
|
||||
let a = [w.start[0] - ux * ext_start, w.start[1] - uy * ext_start];
|
||||
let b = [w.end[0] + ux * ext_end, w.end[1] + uy * ext_end];
|
||||
let sh = if w.shift.is_finite() { w.shift } else { 0.0 };
|
||||
let a = [w.start[0] - ux * ext_start - uy * sh, w.start[1] - uy * ext_start + ux * sh];
|
||||
let b = [w.end[0] + ux * ext_end - uy * sh, w.end[1] + uy * ext_end + ux * sh];
|
||||
vec![[a[0] + nx, a[1] + ny], [b[0] + nx, b[1] + ny], [b[0] - nx, b[1] - ny], [a[0] - nx, a[1] - ny]]
|
||||
}
|
||||
|
||||
@@ -185,7 +189,8 @@ pub fn auto_exterior_dimensions(walls: &[WallIn], openings: &[OpeningIn], scale_
|
||||
continue; // Wand quer zu n
|
||||
}
|
||||
let t = if w.thickness.is_finite() && w.thickness > 0.0 { w.thickness } else { 0.3 };
|
||||
let outer_s = dot(w.start, n) + t / 2.0;
|
||||
let left = [-dy / len, dx / len];
|
||||
let outer_s = dot(w.start, n) + (if w.shift.is_finite() { w.shift } else { 0.0 }) * dot(left, n) + t / 2.0;
|
||||
let (ja, jb) = (dot(o.jamb_start, u), dot(o.jamb_end, u));
|
||||
if !ja.is_finite() || !jb.is_finite() {
|
||||
continue;
|
||||
@@ -239,7 +244,7 @@ mod tests {
|
||||
/// L-förmiger Grundriss aus 0.3-m-Wänden (Achsen).
|
||||
fn l_walls() -> Vec<WallIn> {
|
||||
let axis = [[0.0, 0.0], [10.0, 0.0], [10.0, 6.0], [4.0, 6.0], [4.0, 9.0], [0.0, 9.0]];
|
||||
(0..axis.len()).map(|i| WallIn { start: axis[i], end: axis[(i + 1) % axis.len()], thickness: 0.3 }).collect()
|
||||
(0..axis.len()).map(|i| WallIn { start: axis[i], end: axis[(i + 1) % axis.len()], thickness: 0.3, shift: 0.0 }).collect()
|
||||
}
|
||||
fn lengths(pts: &[Vec2]) -> Vec<f64> {
|
||||
pts.windows(2).map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])).collect()
|
||||
@@ -285,17 +290,36 @@ mod tests {
|
||||
assert!((south.offset - 1.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
/// Wand mit Referenzlinie links: die Achse liegt an der Innenkante, die Aussenmasse stimmen trotzdem.
|
||||
#[test]
|
||||
fn nicht_mittige_wand_misst_die_echte_flaeche() {
|
||||
// Achse y = 0, Körper y 0 … 0.3 (shift +0.15), Öffnung 1 … 2 m.
|
||||
let w = [WallIn { start: [0.0, 0.0], end: [5.0, 0.0], thickness: 0.3, shift: 0.15 }];
|
||||
let o = OpeningIn { wall: 0, jamb_start: [1.0, 0.0], jamb_end: [2.0, 0.0] };
|
||||
let dims = auto_exterior_dimensions(&w, &[o], 100.0);
|
||||
let south = dims.iter().find(|d| d.side == 0 && d.chain == CHAIN_TOTAL).unwrap();
|
||||
let north = dims.iter().find(|d| d.side == 2 && d.chain == CHAIN_TOTAL).unwrap();
|
||||
// Masslinie Süd liegt 1.0 m (1:100) vor der Südfläche y = 0; Nord vor y = 0.3.
|
||||
let south_y = south.pts[0][1] - south.offset * 1.0 * 0.0;
|
||||
assert!((south_y - 0.0).abs() < 1e-6 || (south_y - 0.3).abs() < 1e-6, "{south_y}");
|
||||
assert!((north.pts[0][1] - 0.3).abs() < 1e-6, "{:?}", north.pts);
|
||||
assert!((south.pts[0][1] - 0.0).abs() < 1e-6, "{:?}", south.pts);
|
||||
// Leibungen der Öffnung hängen an der Nordfläche (y = 0.3), nicht an y = 0.15.
|
||||
let op = dims.iter().find(|d| d.side == 2 && d.chain == CHAIN_OPENINGS).unwrap();
|
||||
assert!(op.src.iter().all(|q| (q[1] - 0.3).abs() < 1e-6), "{:?}", op.src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsinn_ohne_panik() {
|
||||
assert!(auto_exterior_dimensions(&[], &[], 100.0).is_empty());
|
||||
let bad = [
|
||||
WallIn { start: [f64::NAN, 0.0], end: [1.0, 0.0], thickness: 0.3 },
|
||||
WallIn { start: [0.0, 0.0], end: [0.0, 0.0], thickness: 0.3 },
|
||||
WallIn { start: [f64::NAN, 0.0], end: [1.0, 0.0], thickness: 0.3, shift: 0.0 },
|
||||
WallIn { start: [0.0, 0.0], end: [0.0, 0.0], thickness: 0.3, shift: 0.0 },
|
||||
];
|
||||
let o = OpeningIn { wall: 7, jamb_start: [0.0, 0.0], jamb_end: [1.0, 0.0] };
|
||||
assert!(auto_exterior_dimensions(&bad, &[o], f64::NAN).is_empty());
|
||||
// Dicke NaN → 0.3; Öffnung mit NaN-Leibung wird übergangen.
|
||||
let w = [WallIn { start: [0.0, 0.0], end: [5.0, 0.0], thickness: f64::NAN }];
|
||||
let w = [WallIn { start: [0.0, 0.0], end: [5.0, 0.0], thickness: f64::NAN, shift: 0.0 }];
|
||||
let o = OpeningIn { wall: 0, jamb_start: [f64::NAN, 0.0], jamb_end: [1.0, 0.0] };
|
||||
let dims = auto_exterior_dimensions(&w, &[o], 0.0);
|
||||
assert!(dims.iter().all(|d| d.chain != CHAIN_OPENINGS));
|
||||
|
||||
@@ -881,7 +881,7 @@ const PROFILE_HIT_TOL: f64 = 0.25;
|
||||
|
||||
/// Extrudierbares Profil einer Zeichnung: geschlossene Polylinie (≥ 3 Punkte), Rechteck, Kreis.
|
||||
/// Punkte als JSON-Werte (Polylinie: die gespeicherten), dazu `circle` beim Kreis.
|
||||
fn profile_of(d: &Value) -> Option<(Vec<Value>, Option<Value>)> {
|
||||
pub(crate) fn profile_of(d: &Value) -> Option<(Vec<Value>, Option<Value>)> {
|
||||
let g = field(d, "geom")?;
|
||||
match field(g, "shape").and_then(Value::as_str)? {
|
||||
"polyline" => {
|
||||
|
||||
@@ -961,6 +961,127 @@ fn dimension_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGe
|
||||
}
|
||||
}
|
||||
|
||||
// ── Achsraster ([112]) und Radius-/Bogenmass ([38]) ─────────────────────────
|
||||
|
||||
/// Geometrie des neuen Rasters: `at` (Ursprung), `xs`/`ys` (Feldweiten als Text), `radial`, `angle`
|
||||
/// (Bogenmass), optional `extend`, `bubbles`, `levels`. `None` bei unlesbaren Feldweiten.
|
||||
fn grid_geom(v: &Value) -> Option<Value> {
|
||||
let radial = b_of(v, "radial");
|
||||
let xs = crate::grid::parse_bays(s_of(v, "xs"))?;
|
||||
let ys = crate::grid::parse_bays(s_of(v, "ys")).or_else(|| (!radial).then(Vec::new).filter(|_| s_of(v, "ys").trim().is_empty()))?;
|
||||
let (a, b) = crate::grid::axes_from_bays(radial, &xs, &ys);
|
||||
let list = |l: &[crate::model::GridAxis]| Value::Array(l.iter().map(|x| obj(vec![("label", s(&x.label)), ("pos", js_num(x.pos))])).collect());
|
||||
let mut f = vec![("shape", s("grid")), ("origin", pt_val(v, "at")), ("angle", js_num(opt_n(v, "angle").unwrap_or(0.0))), ("a", list(&a)), ("b", list(&b))];
|
||||
if radial {
|
||||
f.push(("radial", Value::Bool(true)));
|
||||
}
|
||||
for k in ["extend", "bubbleMm"] {
|
||||
if let Some(x) = opt_n(v, k) {
|
||||
f.push((k, js_num(x)));
|
||||
}
|
||||
}
|
||||
if matches!(s_of(v, "bubbles"), "start" | "end" | "both") {
|
||||
f.push(("bubbles", s(s_of(v, "bubbles"))));
|
||||
}
|
||||
if let Some(l) = v.get("levels").filter(|l| l.as_array().is_some_and(|a| !a.is_empty())) {
|
||||
f.push(("levels", l.clone()));
|
||||
}
|
||||
Some(obj(f))
|
||||
}
|
||||
|
||||
/// Vorschau des Rasters am Cursor: Achsen als Linien, Ringe als Polygonzug.
|
||||
fn grid_preview(v: &Value, pts: &[V], p: &mut Preview) {
|
||||
let Some(at) = pts.first() else { return };
|
||||
let mut v2 = v.clone();
|
||||
v2["at"] = pv(*at);
|
||||
let Some(g) = grid_geom(&v2).and_then(|g| serde_json::from_value::<crate::model::Drawing2DGeom>(g).ok()) else { return };
|
||||
let Some(spec) = crate::grid::Spec::of(&g) else { return };
|
||||
p.ok = true;
|
||||
for ax in spec.axes() {
|
||||
match ax.shape {
|
||||
crate::grid::Shape::Line { a, b } => p.shapes.line(a, b),
|
||||
crate::grid::Shape::Arc { c, r, a0, a1 } => {
|
||||
let n = (((a1 - a0).abs() / (PI / 24.0)).ceil() as usize).clamp(2, 400);
|
||||
let q: Vec<V> = (0..=n).map(|i| a0 + (a1 - a0) * i as f64 / n as f64).map(|t| (c.0 + r * jsnum::cos(t), c.1 + r * jsnum::sin(t))).collect();
|
||||
p.shapes.poly_open(&q);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dim_kind(v: &Value) -> Option<crate::model::DimKind> {
|
||||
use crate::model::DimKind;
|
||||
match s_of(v, "kind") {
|
||||
"radius" => Some(DimKind::Radius),
|
||||
"diameter" => Some(DimKind::Diameter),
|
||||
"arc" => Some(DimKind::Arc),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Toleranz beim Treffen eines Kreises/Bogens (Modell-Meter, `tol` der Anfrage).
|
||||
fn round_tol(v: &Value) -> f64 {
|
||||
opt_n(v, "tol").filter(|t| *t > 0.0).unwrap_or(0.15)
|
||||
}
|
||||
|
||||
/// Radius-/Durchmesser-/Bogenlängen-Mass: Klicks auf dem Rand eines Kreises, Bogens oder einer
|
||||
/// Bogenwand; Mittelpunkt und Randpunkte hängen daran (`refs`). Bogenlänge: `side` (Punkt der
|
||||
/// Masslinie) oder `offset` bestimmt den Abstand vom Bogen.
|
||||
fn dimround_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
use crate::model::DimKind;
|
||||
let Some(kind) = dim_kind(v) else { return Vec::new() };
|
||||
let clicks: Vec<V> = arr(v.get("pts")).iter().map(pair).collect();
|
||||
let lk = crate::document::Lookup::plain(root);
|
||||
let Some((pts, refs)) = crate::dim_assoc::round_dimension(&lk, ctx.level, kind, &clicks, round_tol(v)) else { return Vec::new() };
|
||||
let offset = match (kind, opt_p(v, "side")) {
|
||||
(DimKind::Arc, Some(side)) => hypot2(side.0 - pts[0].0, side.1 - pts[0].1) - hypot2(pts[1].0 - pts[0].0, pts[1].1 - pts[0].1),
|
||||
(DimKind::Arc, None) => opt_n(v, "offset").unwrap_or(0.5),
|
||||
_ => 0.0,
|
||||
};
|
||||
let kind_s = match kind {
|
||||
DimKind::Radius => "radius",
|
||||
DimKind::Diameter => "diameter",
|
||||
DimKind::Arc => "arc",
|
||||
};
|
||||
let geom = obj(vec![
|
||||
("shape", s("dimension")),
|
||||
("pts", pvs(&pts)),
|
||||
("offset", js_num(offset)),
|
||||
("kind", s(kind_s)),
|
||||
("refs", serde_json::to_value(refs).unwrap_or(Value::Null)),
|
||||
]);
|
||||
add_drawing(v, ctx, ids, geom)
|
||||
}
|
||||
|
||||
/// Vorschau: Radius-/Durchmesserlinie bzw. Bogen zwischen den Klicks (Cursor = letzter Punkt).
|
||||
fn dimround_preview(root: &Map<String, Value>, v: &Value, ctx: &Ctx, pts: &[V], p: &mut Preview) {
|
||||
use crate::model::DimKind;
|
||||
let Some(kind) = dim_kind(v) else { return };
|
||||
let lk = crate::document::Lookup::plain(root);
|
||||
let tol = round_tol(v);
|
||||
let arc_phase = kind == DimKind::Arc;
|
||||
// Klickpunkte: bei der Bogenlänge die ersten zwei (Cursor als zweiter, solange er läuft).
|
||||
let clicks: Vec<V> = if arc_phase { pts.iter().take(2).copied().collect() } else { pts.iter().take(1).copied().collect() };
|
||||
let Some((q, _)) = crate::dim_assoc::round_dimension(&lk, ctx.level, kind, &clicks, tol).or_else(|| crate::dim_assoc::round_dimension(&lk, ctx.level, kind, &clicks[..1], tol).filter(|_| arc_phase)) else { return };
|
||||
p.ok = true;
|
||||
let c = q[0];
|
||||
match kind {
|
||||
DimKind::Radius => p.shapes.line(c, q[1]),
|
||||
DimKind::Diameter => p.shapes.line((2.0 * c.0 - q[1].0, 2.0 * c.1 - q[1].1), q[1]),
|
||||
DimKind::Arc => {
|
||||
let r = hypot2(q[1].0 - c.0, q[1].1 - c.1);
|
||||
let a0 = angle(c, q[1]);
|
||||
let a1 = if q.len() > 2 { angle(c, q[2]) } else { a0 };
|
||||
let sweep = (a1 - a0).rem_euclid(TAU);
|
||||
let off = pts.get(2).map_or(0.0, |s| hypot2(s.0 - c.0, s.1 - c.1) - r);
|
||||
let n = ((sweep / (PI / 24.0)).ceil() as usize).clamp(1, 400);
|
||||
let poly: Vec<V> = (0..=n).map(|i| a0 + sweep * i as f64 / n as f64).map(|t| (c.0 + (r + off) * jsnum::cos(t), c.1 + (r + off) * jsnum::sin(t))).collect();
|
||||
p.shapes.poly_open(&poly);
|
||||
p.info.push(r * sweep);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bemassungs-Vorschau. `phase` next: `pts` = Kette + roher Cursor → Kette bis zum (auf die Masslinie
|
||||
/// projizierten) Cursor, `info = [cx, cy]`; offset: `pts` = Kette + Cursor (oder ohne → Abstand 0),
|
||||
/// Hilfs- und Masslinien, `info = [Abstand, Summe]`.
|
||||
@@ -1016,7 +1137,15 @@ fn auto_dims(root: &Map<String, Value>, ctx: &Ctx, prefix: &str, scale: f64) ->
|
||||
let tid = field(w, "wallTypeId").and_then(Value::as_str);
|
||||
let th = types.iter().find(|t| id_of(t) == tid).map_or(0.3, type_thickness);
|
||||
let (a, b) = (p(w, "start"), p(w, "end"));
|
||||
WallIn { start: [a.0, a.1], end: [b.0, b.1], thickness: th }
|
||||
// Wandmitte gegenüber der Achse (Referenzlinie links/rechts bzw. -versatz, wie `dim_assoc`).
|
||||
let half = th / 2.0;
|
||||
let shift = match (field(w, "referenceOffset").and_then(Value::as_f64), field(w, "referenceLine").and_then(Value::as_str)) {
|
||||
(Some(v), _) => v.clamp(-half, half),
|
||||
(None, Some("left")) => half,
|
||||
(None, Some("right")) => -half,
|
||||
_ => 0.0,
|
||||
};
|
||||
WallIn { start: [a.0, a.1], end: [b.0, b.1], thickness: th, shift }
|
||||
})
|
||||
.collect();
|
||||
let mut oin = Vec::new();
|
||||
@@ -1154,6 +1283,11 @@ pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) ->
|
||||
),
|
||||
"pointmarker" => add_drawing(v, ctx, ids, obj(vec![("shape", s("pointmarker")), ("at", pt_val(v, "at"))])),
|
||||
"block" => block_ops(v, ctx, ids),
|
||||
"grid" => match grid_geom(v) {
|
||||
Some(g) => add_drawing(v, ctx, ids, g),
|
||||
None => Vec::new(),
|
||||
},
|
||||
"dimround" => dimround_ops(root, v, ctx, ids),
|
||||
"dimension" => dimension_ops(root, v, ctx, ids),
|
||||
"autodim" => autodim_ops(root, ctx),
|
||||
_ => return None,
|
||||
@@ -1227,6 +1361,8 @@ pub fn preview(root: &Map<String, Value>, v: &Value, ctx: &Ctx, pts: &[V], p: &m
|
||||
}
|
||||
}
|
||||
"dimension" => dimension_preview(v, pts, p),
|
||||
"grid" => grid_preview(v, pts, p),
|
||||
"dimround" => dimround_preview(root, v, ctx, pts, p),
|
||||
"autodim" => p.ok = !auto_dims(root, ctx, "autodim", 100.0).is_empty(),
|
||||
_ => return false,
|
||||
}
|
||||
@@ -1282,6 +1418,52 @@ mod tests {
|
||||
assert!((at.1 - (0.0 - 0.0035)).abs() < 1e-12);
|
||||
}
|
||||
|
||||
/// [112] Befehl „Achsraster": Feldweiten als Text → Achsen 1, 2, 3 / A, B …; unlesbar → nichts.
|
||||
#[test]
|
||||
fn achsraster_befehl() {
|
||||
let v = json!({"cmd": "grid", "at": {"x": 1, "y": 2}, "xs": "5 3x6", "ys": "4,5 4", "angle": 0, "bubbles": "end", "levels": ["L"]});
|
||||
let o = ops(&Map::new(), &v, &ctx(), &mut IdGen::new("s")).unwrap();
|
||||
let g = &o[0].to_json()["items"][0]["geom"];
|
||||
assert_eq!(g["shape"], "grid");
|
||||
assert_eq!(g["a"].as_array().unwrap().len(), 5);
|
||||
assert_eq!(g["a"][4]["pos"], 23);
|
||||
assert_eq!(g["b"][2]["label"], "C");
|
||||
assert_eq!(g["b"][2]["pos"], 8.5);
|
||||
assert_eq!(g["bubbles"], "end");
|
||||
assert_eq!(g["origin"]["x"], 1);
|
||||
assert!(serde_json::from_value::<crate::model::Drawing2DGeom>(g.clone()).is_ok());
|
||||
// Ohne `angle` (Befehl aus der Hülle) gilt 0; leere Querachsen sind erlaubt.
|
||||
let bare = json!({"cmd": "grid", "at": [0, 0], "xs": "5", "ys": ""});
|
||||
let o2 = ops(&Map::new(), &bare, &ctx(), &mut IdGen::new("s")).unwrap();
|
||||
assert_eq!(o2[0].to_json()["items"][0]["geom"]["angle"], 0);
|
||||
let bad = json!({"cmd": "grid", "at": {"x": 0, "y": 0}, "xs": "x", "ys": ""});
|
||||
assert!(ops(&Map::new(), &bad, &ctx(), &mut IdGen::new("s")).unwrap().is_empty());
|
||||
// Vorschau am Cursor.
|
||||
let mut p = Preview { shapes: Shapes::default(), ok: false, info: vec![] };
|
||||
grid_preview(&v, &[(0.0, 0.0)], &mut p);
|
||||
assert!(p.ok && !p.shapes.buf.is_empty());
|
||||
}
|
||||
|
||||
/// [38] Befehl Radius/Bogenmass: trifft den Kreis, hängt Mittelpunkt und Rand an.
|
||||
#[test]
|
||||
fn rundmass_befehl() {
|
||||
let root = json!({"drawings2d": [{"id": "K", "levelId": "L", "categoryCode": "20", "geom": {"shape": "circle", "center": {"x": 1, "y": 1}, "r": 2}}]});
|
||||
let root = root.as_object().unwrap().clone();
|
||||
let v = json!({"cmd": "dimround", "kind": "diameter", "pts": [[3.01, 1.0]]});
|
||||
let o = ops(&root, &v, &ctx(), &mut IdGen::new("s")).unwrap();
|
||||
let g = &o[0].to_json()["items"][0]["geom"];
|
||||
assert_eq!(g["kind"], "diameter");
|
||||
assert_eq!(g["refs"][0]["feature"], "center");
|
||||
assert_eq!(g["refs"][1]["feature"], "rim");
|
||||
let v = json!({"cmd": "dimround", "kind": "arc", "pts": [[3.0, 1.0], [1.0, 3.0]], "side": [1.0, 4.0]});
|
||||
let g = &ops(&root, &v, &ctx(), &mut IdGen::new("s")).unwrap()[0].to_json()["items"][0]["geom"];
|
||||
assert_eq!(g["pts"].as_array().unwrap().len(), 3);
|
||||
assert!((g["offset"].as_f64().unwrap() - 1.0).abs() < 1e-9);
|
||||
// Kein Kreis in der Nähe → nichts.
|
||||
let far = json!({"cmd": "dimround", "kind": "radius", "pts": [[50.0, 50.0]]});
|
||||
assert!(ops(&root, &far, &ctx(), &mut IdGen::new("s")).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revisionswolke_beulen() {
|
||||
assert!(revision_cloud(&[(0.0, 0.0)], false, 0.3).is_none());
|
||||
|
||||
@@ -733,6 +733,7 @@ fn map_points(g: &Value, f: &dyn Fn(P) -> P) -> Value {
|
||||
"rect" | "image" => with_all(g, vec![("min", m("min")), ("max", m("max"))]),
|
||||
"circle" | "arc" | "ellipse" => with(g, "center", m("center")),
|
||||
"text" | "kote" | "detailref" | "scalebar" | "pointmarker" | "block" => with(g, "at", m("at")),
|
||||
"grid" => with(g, "origin", m("origin")),
|
||||
_ => g.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
+259
-30
@@ -150,6 +150,130 @@ pub fn solid_from_inputs(shape: &str, p0: V, p1: Option<V>, nums: &[f64]) -> Opt
|
||||
}
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Rotationskörper und Loft aus Plan-Profilen ([T7])
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Rotationskörper: das Plan-Profil (geschlossen, in der Zeichenebene) dreht sich um die Achse
|
||||
/// `a → b` (liegt waagrecht im Plan, auf Höhe des grössten Profilabstands, damit ein voller Körper auf
|
||||
/// der Geschoss-UK steht). Das Profil muss ganz auf einer Seite der Achse liegen; es wird als
|
||||
/// (r = Abstand, z = Lage entlang der Achse) an `revolve` von truck gegeben und per `transform` ins
|
||||
/// Modell gesetzt (lokal x → Querrichtung, y → oben, z → Achse). `angle_deg` in (0, 360]; positive
|
||||
/// Drehung hebt das Profil nach oben. Ergebnis: Grundriss-Rechteck, Höhe, B-Rep-Beschreibung, Label.
|
||||
pub fn revolve_from_profile(profile: &[V], a: V, b: V, angle_deg: f64) -> Option<(Vec<V>, f64, Value, String)> {
|
||||
let len = hypot2(b.0 - a.0, b.1 - a.1);
|
||||
if profile.len() < 3 || !(len > 1e-6) || !angle_deg.is_finite() || !(angle_deg > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let mut d = ((b.0 - a.0) / len, (b.1 - a.1) / len);
|
||||
let side = |d: V, p: V| (p.0 - a.0) * -d.1 + (p.1 - a.1) * d.0;
|
||||
let (lo, hi) = profile.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(side(d, *p)), hi.max(side(d, *p))));
|
||||
if !(lo.is_finite() && hi.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
if lo < -1e-6 {
|
||||
if hi > 1e-6 {
|
||||
return None; // Profil überquert die Achse
|
||||
}
|
||||
d = (-d.0, -d.1); // Profil liegt rechts: Achse umdrehen, damit r >= 0
|
||||
}
|
||||
let n = (-d.1, d.0);
|
||||
let ring: Vec<(f64, f64)> = profile.iter().map(|p| (side(d, *p).max(0.0), (p.0 - a.0) * d.0 + (p.1 - a.1) * d.1)).collect();
|
||||
let r_max = ring.iter().fold(0.0_f64, |m, q| m.max(q.0));
|
||||
if !(r_max > 1e-6) {
|
||||
return None;
|
||||
}
|
||||
let (z_min, z_max) = ring.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q.1), hi.max(q.1)));
|
||||
if !(z_max - z_min > 1e-6) {
|
||||
return None;
|
||||
}
|
||||
let angle = angle_deg.min(360.0);
|
||||
let flat: Vec<Value> = ring.iter().flat_map(|q| [js_num(q.0), js_num(q.1)]).collect();
|
||||
let inner = obj(vec![("kind", s("revolve")), ("profile", Value::Array(flat)), ("angleDeg", js_num(angle))]);
|
||||
let m = [n.0, 0.0, d.0, a.0, n.1, 0.0, d.1, a.1, 0.0, 1.0, 0.0, r_max];
|
||||
let spec = obj(vec![("kind", s("transform")), ("m", Value::Array(m.iter().map(|x| js_num(*x)).collect())), ("solid", inner)]);
|
||||
let at = |along: f64, perp: f64| (a.0 + d.0 * along + n.0 * perp, a.1 + d.1 * along + n.1 * perp);
|
||||
let pts = vec![at(z_min, -r_max), at(z_max, -r_max), at(z_max, r_max), at(z_min, r_max)];
|
||||
Some((pts, 2.0 * r_max, spec, format!("Rotationskörper {}°", fixed2(angle))))
|
||||
}
|
||||
|
||||
fn ring_area(r: &[V]) -> f64 {
|
||||
let n = r.len();
|
||||
(0..n).map(|i| r[i].0 * r[(i + 1) % n].1 - r[(i + 1) % n].0 * r[i].1).sum::<f64>() / 2.0
|
||||
}
|
||||
|
||||
/// Gleiche Punktzahl für alle Ringe: kürzere Ringe teilen ihre längste Kante, bis sie so viele Punkte
|
||||
/// haben wie der längste (Ecken bleiben erhalten); alle gegen den Uhrzeigersinn.
|
||||
fn match_rings(rings: &[Vec<V>]) -> Vec<Vec<V>> {
|
||||
let target = rings.iter().map(Vec::len).max().unwrap_or(0);
|
||||
rings
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let mut r = r.clone();
|
||||
if ring_area(&r) < 0.0 {
|
||||
r.reverse();
|
||||
}
|
||||
while r.len() < target {
|
||||
let n = r.len();
|
||||
let len = |k: usize| hypot2(r[(k + 1) % n].0 - r[k].0, r[(k + 1) % n].1 - r[k].1);
|
||||
let Some(i) = (0..n).max_by(|&i, &j| len(i).partial_cmp(&len(j)).unwrap_or(std::cmp::Ordering::Equal)) else { break };
|
||||
let (p, q) = (r[i], r[(i + 1) % n]);
|
||||
r.insert(i + 1, ((p.0 + q.0) / 2.0, (p.1 + q.1) / 2.0));
|
||||
}
|
||||
r
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Loft durch >= 2 Plan-Profile, gleichmässig über `height` verteilt (erstes Profil unten).
|
||||
pub fn loft_from_rings(rings: &[Vec<V>], height: f64) -> Option<(Vec<V>, f64, Value, String)> {
|
||||
if rings.len() < 2 || !(height > 1e-6) || rings.iter().any(|r| r.len() < 3 || r.iter().any(|p| !(p.0.is_finite() && p.1.is_finite()))) {
|
||||
return None;
|
||||
}
|
||||
let rings = match_rings(rings);
|
||||
let last = (rings.len() - 1) as f64;
|
||||
let sections: Vec<Value> = rings
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, r)| obj(vec![("z", js_num(height * i as f64 / last)), ("points", Value::Array(r.iter().flat_map(|p| [js_num(p.0), js_num(p.1)]).collect()))]))
|
||||
.collect();
|
||||
let spec = obj(vec![("kind", s("loft")), ("sections", Value::Array(sections))]);
|
||||
Some((rings[0].clone(), height, spec, format!("Loft {} Profile h={}", rings.len(), fixed2(height))))
|
||||
}
|
||||
|
||||
fn profile_ring(root: &Map<String, Value>, id: &str) -> Option<Vec<V>> {
|
||||
let (pts, _) = find(root, "drawings2d", id).and_then(crate::cmd_create::profile_of)?;
|
||||
Some(pts.iter().map(xy).collect())
|
||||
}
|
||||
|
||||
fn brep_solid_ops(root: &Map<String, Value>, ctx: &Ctx, ids: &mut IdGen, sources: &[&str], made: Option<(Vec<V>, f64, Value, String)>) -> Vec<Op> {
|
||||
let Some((pts, height, spec, label)) = made else { return Vec::new() };
|
||||
let solid = obj(vec![
|
||||
("id", s(&ids.next("body"))),
|
||||
("type", s("extrudedSolid")),
|
||||
("levelId", s(ctx.level)),
|
||||
("points", pvs(&pts)),
|
||||
("height", js_num(height)),
|
||||
("brep", obj(vec![("spec", spec), ("origin", pv(pts[0])), ("label", s(&label))])),
|
||||
]);
|
||||
let mut ops = crate::cmd_create::remove_op(root, "drawings2d", sources);
|
||||
ops.extend(add_op("extrudedSolids", vec![solid]));
|
||||
ops
|
||||
}
|
||||
|
||||
fn revolve_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
let src = s_of(v, "source");
|
||||
let made = profile_ring(root, src).and_then(|ring| revolve_from_profile(&ring, p_of(v, "a"), p_of(v, "b"), num_or(field(v, "angle"), 360.0)));
|
||||
brep_solid_ops(root, ctx, ids, &[src], made)
|
||||
}
|
||||
|
||||
fn loft_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
let sources: Vec<&str> = arr(v.get("sources")).iter().filter_map(Value::as_str).collect();
|
||||
let rings: Option<Vec<Vec<V>>> = sources.iter().map(|id| profile_ring(root, id)).collect();
|
||||
let made = rings.and_then(|r| loft_from_rings(&r, n_of(v, "height")));
|
||||
brep_solid_ops(root, ctx, ids, &sources, made)
|
||||
}
|
||||
|
||||
fn solid_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
let nums: Vec<f64> = arr(v.get("nums")).iter().map(|x| num_of(Some(x))).collect();
|
||||
let Some((pts, height, spec, label)) = solid_from_inputs(s_of(v, "shape"), p_of(v, "p0"), opt_p(v, "p1"), &nums) else {
|
||||
@@ -327,46 +451,70 @@ fn voidbox_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
/// Gelände-TIN aus Höhenlinien (`generateTerrainFromContours`): alle endlichen Stützpunkte, Delaunay
|
||||
/// über (x, y), Höhe der Kontur je Punkt; Null-Flächen-Dreiecke verworfen.
|
||||
pub fn terrain_from_contours(contours: &[Value], id: &str) -> Value {
|
||||
let (mut xs, mut ys, mut zs) = (Vec::new(), Vec::new(), Vec::new());
|
||||
for c in contours {
|
||||
let z = num_of(field(c, "z"));
|
||||
let z = if z.is_finite() { z } else { 0.0 };
|
||||
for p in arr(field(c, "pts")) {
|
||||
let (x, y) = xy(p);
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
continue;
|
||||
terrain_from_contours_with(contours, id, crate::terrain::TerrainOpts::default())
|
||||
}
|
||||
|
||||
/// Gelände aus Höhenlinien ([T6], `terrain.rs`): Konturen als Bruchkanten (constrained Delaunay),
|
||||
/// flache Dreiecke behoben, adaptiv geglättet (ohne Überschwingen). Äquidistanz der Plan-Höhenlinien =
|
||||
/// kleinster Höhenabstand der Konturen. Unter drei Punkten ein leeres Netz.
|
||||
pub fn terrain_from_contours_with(contours: &[Value], id: &str, o: crate::terrain::TerrainOpts) -> Value {
|
||||
let cs: Vec<crate::terrain::ContourIn> = contours
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let z = num_of(field(c, "z"));
|
||||
crate::terrain::ContourIn {
|
||||
z: if z.is_finite() { z } else { 0.0 },
|
||||
pts: arr(field(c, "pts")).iter().map(xy).filter(|p| p.0.is_finite() && p.1.is_finite()).map(|p| [p.0, p.1]).collect(),
|
||||
closed: truthy(field(c, "closed")),
|
||||
}
|
||||
xs.push(x);
|
||||
ys.push(y);
|
||||
zs.push(z);
|
||||
}
|
||||
}
|
||||
if xs.len() < 3 {
|
||||
})
|
||||
.collect();
|
||||
let t = crate::terrain::terrain_from_contours(&cs, &[], o);
|
||||
if t.tris.is_empty() {
|
||||
return json!({ "id": id, "type": "terrainMesh", "name": "Gelände", "categoryCode": "02", "positions": [], "indices": [] });
|
||||
}
|
||||
let coords: Vec<f64> = xs.iter().zip(&ys).flat_map(|(x, y)| [*x, *y]).collect();
|
||||
let tri = crate::delaunay::triangulate(&coords);
|
||||
let positions: Vec<Value> = (0..xs.len()).flat_map(|i| [js_num(xs[i]), js_num(ys[i]), js_num(zs[i])]).collect();
|
||||
let mut indices = Vec::new();
|
||||
for t in tri.chunks_exact(3) {
|
||||
let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize);
|
||||
let area2 = ((xs[b] - xs[a]) * (ys[c] - ys[a]) - (xs[c] - xs[a]) * (ys[b] - ys[a])).abs();
|
||||
if area2 <= 1e-9 {
|
||||
continue;
|
||||
}
|
||||
indices.extend([Value::from(t[0]), Value::from(t[1]), Value::from(t[2])]);
|
||||
}
|
||||
let (pos, idx) = t.to_flat(0.0);
|
||||
let iv = crate::terrain::interval_of(&cs.iter().map(|c| c.z).collect::<Vec<_>>());
|
||||
obj(vec![
|
||||
("id", s(id)),
|
||||
("type", s("terrainMesh")),
|
||||
("name", s("Gelände")),
|
||||
("layer", s("Terrain")),
|
||||
("categoryCode", s("02")),
|
||||
("positions", Value::Array(positions)),
|
||||
("indices", Value::Array(indices)),
|
||||
("positions", Value::Array(pos.into_iter().map(js_num).collect())),
|
||||
("indices", Value::Array(idx.into_iter().map(Value::from).collect())),
|
||||
("contourInterval", js_num(iv)),
|
||||
])
|
||||
}
|
||||
|
||||
/// [68] Baugrube aus dem gezeichneten Umriss (≥ 3 Punkte; 2 Punkte = Rechteck). Sohle = Geschoss-
|
||||
/// Unterkante − 0.30 m (Magerbeton + Bodenplatte), Böschung 45°.
|
||||
fn excavation_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
let mut pts: Vec<V> = pts_of(v, "pts").into_iter().filter(|p| p.0.is_finite() && p.1.is_finite()).collect();
|
||||
if pts.len() == 2 {
|
||||
pts = rect_corners(pts[0], pts[1]).to_vec();
|
||||
}
|
||||
let area2: f64 = (0..pts.len()).map(|i| pts[i].0 * pts[(i + 1) % pts.len()].1 - pts[(i + 1) % pts.len()].0 * pts[i].1).sum();
|
||||
if pts.len() < 3 || area2.abs() < 0.02 {
|
||||
return Vec::new();
|
||||
}
|
||||
let base = arr(root.get("floors")).iter().find(|f| field(f, "id").and_then(Value::as_str) == Some(ctx.level)).map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0));
|
||||
let n = arr(root.get("context")).iter().filter(|o| field(o, "type").and_then(Value::as_str) == Some("excavation")).count();
|
||||
add_op(
|
||||
"context",
|
||||
vec![obj(vec![
|
||||
("id", s(&ids.next("excavation"))),
|
||||
("type", s("excavation")),
|
||||
("name", s(&format!("Baugrube {}", n + 1))),
|
||||
("layer", s("Terrain")),
|
||||
("categoryCode", s("02")),
|
||||
("outline", pvs(&pts)),
|
||||
("bottom", js_num(base - 0.3)),
|
||||
("slope", js_num(crate::excavation::DEFAULT_SLOPE)),
|
||||
])],
|
||||
)
|
||||
}
|
||||
|
||||
fn terrain_ops(root: &Map<String, Value>, ids: &mut IdGen) -> Vec<Op> {
|
||||
let Some(set) = arr(root.get("context")).iter().find(|o| field(o, "type").and_then(Value::as_str) == Some("contourSet")) else {
|
||||
return Vec::new();
|
||||
@@ -621,9 +769,12 @@ fn direction_arrow(a: V, b: V, sign: f64, out: &mut Shapes) {
|
||||
pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option<Vec<Op>> {
|
||||
Some(match s_of(v, "cmd") {
|
||||
"solid" => solid_ops(v, ctx, ids),
|
||||
"revolve" => revolve_ops(root, v, ctx, ids),
|
||||
"loft" => loft_ops(root, v, ctx, ids),
|
||||
"solidbool" => solidbool_ops(root, v, ids),
|
||||
"voidbox" => voidbox_ops(v, ctx, ids),
|
||||
"terrain" => terrain_ops(root, ids),
|
||||
"excavation" => excavation_ops(root, v, ctx, ids),
|
||||
"ceilingOpening" => ceiling_opening_ops(root, v, ctx),
|
||||
"roofHole" => roof_hole_ops(root, v, ctx),
|
||||
"roofWindow" => roof_window_ops(root, v, ctx, ids),
|
||||
@@ -741,11 +892,89 @@ mod tests {
|
||||
assert!(run("eg", 9.0).is_empty());
|
||||
}
|
||||
|
||||
/// [68] Baugrube: Umriss (2 Punkte = Rechteck), Sohle = Geschoss − 0.30, als Kontext-Objekt.
|
||||
#[test]
|
||||
fn baugrube_befehl() {
|
||||
let root = json!({"floors": [{"id": "ug", "baseElevation": -3.0}]});
|
||||
let root = root.as_object().unwrap();
|
||||
let run = |pts: Value| {
|
||||
let mut ids = IdGen::new("s");
|
||||
let ctx = Ctx { level: "ug", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 };
|
||||
ops(root, &json!({"cmd": "excavation", "pts": pts}), &ctx, &mut ids).unwrap()
|
||||
};
|
||||
let o = run(json!([{"x": 0, "y": 0}, {"x": 10, "y": 8}]));
|
||||
let Op::Add { collection, items, .. } = &o[0] else { panic!() };
|
||||
assert_eq!(collection, "context");
|
||||
assert_eq!((items[0]["type"].as_str(), items[0]["bottom"].as_f64()), (Some("excavation"), Some(-3.3)));
|
||||
assert_eq!(items[0]["outline"].as_array().unwrap().len(), 4);
|
||||
assert!(run(json!([{"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0}])).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gelaende_aus_hoehenlinien() {
|
||||
let c = json!([{"z": 1, "pts": [{"x": 0, "y": 0}, {"x": 4, "y": 0}]}, {"z": 2, "pts": [{"x": 0, "y": 3}, {"x": 4, "y": 3}]}]);
|
||||
let raw = terrain_from_contours_with(c.as_array().unwrap(), "t", crate::terrain::TerrainOpts { smooth: 0, max_edge: 100.0, breaklines: true });
|
||||
assert_eq!(raw["indices"].as_array().unwrap().len(), 6);
|
||||
assert_eq!(raw["positions"][2], 1);
|
||||
assert_eq!(raw["contourInterval"], 1);
|
||||
// Standard: verdichtet und geglättet, Höhen bleiben im Bereich der Konturen.
|
||||
let t = terrain_from_contours(c.as_array().unwrap(), "t");
|
||||
assert_eq!(t["indices"].as_array().unwrap().len(), 6);
|
||||
assert_eq!(t["positions"][2], 1);
|
||||
let pos = t["positions"].as_array().unwrap();
|
||||
assert!(t["indices"].as_array().unwrap().len() > 6);
|
||||
assert!(pos.iter().skip(2).step_by(3).all(|z| (1.0..=2.0).contains(&z.as_f64().unwrap())));
|
||||
assert!(terrain_from_contours(&[], "t")["indices"].as_array().unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// [T7] Rotationskörper: Achse waagrecht im Plan, Profil auf einer Seite, Matrix bildet lokal x → Quer, z → Achse ab.
|
||||
#[test]
|
||||
fn rotationskoerper_aus_profil() {
|
||||
let prof = [(0.0, 0.0), (2.0, 0.0), (2.0, 1.0), (0.0, 1.0)];
|
||||
let (pts, h, spec, label) = revolve_from_profile(&prof, (0.0, 0.0), (5.0, 0.0), 360.0).unwrap();
|
||||
assert_eq!(h, 2.0);
|
||||
assert_eq!(label, "Rotationskörper 360.00°");
|
||||
assert_eq!(spec["kind"], "transform");
|
||||
assert_eq!(spec["solid"]["profile"], json!([0, 0, 0, 2, 1, 2, 1, 0]));
|
||||
let m: Vec<f64> = spec["m"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
|
||||
let w = |l: [f64; 3]| [m[0] * l[0] + m[1] * l[1] + m[2] * l[2] + m[3], m[4] * l[0] + m[5] * l[1] + m[6] * l[2] + m[7], m[8] * l[0] + m[9] * l[1] + m[10] * l[2] + m[11]];
|
||||
assert_eq!(w([1.0, 0.0, 2.0]), [2.0, 1.0, 1.0]);
|
||||
assert_eq!(w([0.0, 1.0, 0.0]), [0.0, 0.0, 2.0]);
|
||||
assert_eq!(pts.len(), 4);
|
||||
let rechts = [(0.0, 0.0), (2.0, 0.0), (2.0, -1.0), (0.0, -1.0)];
|
||||
let (_, _, spec2, _) = revolve_from_profile(&rechts, (0.0, 0.0), (5.0, 0.0), 90.0).unwrap();
|
||||
assert_eq!(spec2["solid"]["angleDeg"], 90.0);
|
||||
assert!(revolve_from_profile(&[(0.0, -1.0), (2.0, -1.0), (2.0, 1.0), (0.0, 1.0)], (0.0, 0.0), (5.0, 0.0), 360.0).is_none());
|
||||
assert!(revolve_from_profile(&prof, (0.0, 0.0), (0.0, 0.0), 360.0).is_none());
|
||||
assert!(revolve_from_profile(&prof, (0.0, 0.0), (5.0, 0.0), f64::NAN).is_none());
|
||||
}
|
||||
|
||||
/// [T7] Loft: gleiche Punktzahl (Kante teilen), Höhen gleichmässig, Ringe gegen den Uhrzeigersinn.
|
||||
#[test]
|
||||
fn loft_aus_profilen() {
|
||||
let quad = vec![(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)];
|
||||
let tri_cw = vec![(0.5, 0.5), (0.5, 1.5), (1.5, 0.5)];
|
||||
let (pts, h, spec, label) = loft_from_rings(&[quad.clone(), tri_cw, quad.clone()], 3.0).unwrap();
|
||||
assert_eq!((pts.len(), h), (4, 3.0));
|
||||
assert_eq!(label, "Loft 3 Profile h=3.00");
|
||||
let secs = spec["sections"].as_array().unwrap();
|
||||
assert_eq!(secs.len(), 3);
|
||||
assert_eq!(secs[1]["z"], 1.5);
|
||||
assert!(secs.iter().all(|s| s["points"].as_array().unwrap().len() == 8));
|
||||
assert!(loft_from_rings(&[quad.clone()], 3.0).is_none());
|
||||
assert!(loft_from_rings(&[quad.clone(), quad], 0.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_und_loft_befehle_legen_koerper_an_und_entfernen_quellen() {
|
||||
let d = |id: &str, pts: Value| json!({"id": id, "type": "drawing2d", "levelId": "eg", "geom": {"shape": "polyline", "closed": true, "pts": pts}});
|
||||
let sq = |x: f64, s: f64| json!([{"x": x, "y": 0}, {"x": x + s, "y": 0}, {"x": x + s, "y": s}, {"x": x, "y": s}]);
|
||||
let root = json!({"drawings2d": [d("A", sq(0.0, 2.0)), d("B", sq(10.0, 1.0))]});
|
||||
let root = root.as_object().unwrap();
|
||||
let ctx = Ctx { level: "eg", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 };
|
||||
let mut ids = IdGen::new("t");
|
||||
let ops = loft_ops(root, &json!({"sources": ["A", "B"], "height": 2.0}), &ctx, &mut ids);
|
||||
assert_eq!(ops.len(), 2);
|
||||
let ops = revolve_ops(root, &json!({"source": "A", "a": {"x": -1, "y": -1}, "b": {"x": 5, "y": -1}, "angle": 180}), &ctx, &mut ids);
|
||||
assert_eq!(ops.len(), 2);
|
||||
assert!(revolve_ops(root, &json!({"source": "ZZ", "a": {"x": 0, "y": 0}, "b": {"x": 1, "y": 0}}), &ctx, &mut ids).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -166,6 +166,21 @@ pub fn mv_geom(g: &Value, xf: &Xf) -> Option<Value> {
|
||||
"circle" | "arc" | "ellipse" => with(g, "center", p("center")),
|
||||
"bezier" | "spline" | "dimension" => with(g, "pts", ps("pts")),
|
||||
"kote" | "detailref" | "scalebar" | "pointmarker" => with(g, "at", p("at")),
|
||||
"grid" => {
|
||||
// Ursprung und Richtung über einen mit abgebildeten Richtungspunkt; eine Spiegelung kehrt die
|
||||
// Querachsen um (rechtwinklig: Y-Lagen, radial: Strahlwinkel).
|
||||
let (ox, oy) = xy(field(g, "origin").unwrap_or(&Value::Null));
|
||||
let ang = num_of(field(g, "angle"));
|
||||
let no = xf.apply(ox, oy);
|
||||
let nt = xf.apply(ox + jsnum::cos(ang), oy + jsnum::sin(ang));
|
||||
let mut f = vec![("origin", pt(no.0, no.1)), ("angle", js_num(jsnum::atan2(nt.1 - no.1, nt.0 - no.0)))];
|
||||
if xf.reverses() {
|
||||
let key = if field(g, "radial").and_then(Value::as_bool) == Some(true) { "a" } else { "b" };
|
||||
let neg = Value::Array(arr(field(g, key)).iter().map(|x| with(x, "pos", js_num(-num_of(field(x, "pos"))))).collect());
|
||||
f.push((key, neg));
|
||||
}
|
||||
with_all(g, f)
|
||||
}
|
||||
"text" => {
|
||||
// Hinweis-Ziel, Knicke und Pfadpunkte wandern mit.
|
||||
let mut f = vec![("at", Some(p("at")))];
|
||||
@@ -205,6 +220,18 @@ pub fn scale_geom(g: &Value, xf: &Xf, k: f64) -> Option<Value> {
|
||||
"circle" | "arc" => with(&g, "r", times("r")),
|
||||
"ellipse" => with_all(&g, vec![("rx", times("rx")), ("ry", times("ry"))]),
|
||||
"dimension" => with(&g, "offset", times("offset")),
|
||||
"grid" => {
|
||||
let scaled = |key: &str| Value::Array(arr(field(&g, key)).iter().map(|x| with(x, "pos", js_num(num_of(field(x, "pos")) * k))).collect());
|
||||
let radial = field(&g, "radial").and_then(Value::as_bool) == Some(true);
|
||||
let mut f = vec![("b", scaled("b"))];
|
||||
if !radial {
|
||||
f.push(("a", scaled("a")));
|
||||
}
|
||||
if field(&g, "extend").is_some() {
|
||||
f.push(("extend", times("extend")));
|
||||
}
|
||||
with_all(&g, f)
|
||||
}
|
||||
"text" => {
|
||||
let mut f = vec![("height", times("height"))];
|
||||
if field(&g, "width").is_some() {
|
||||
|
||||
+402
-34
@@ -4,8 +4,12 @@
|
||||
//! - **Anhängen** ([`attach`]): ein gefangener Punkt wird über Deckungsgleichheit (Toleranz [`TOL`])
|
||||
//! einem Merkmal zugeordnet — Öffnungs-Leibung/-Mitte, Wandende, Wandecke (Schnitt zweier
|
||||
//! Wandlinien), Punkt auf Wandachse/Schichtgrenze, Stütze (Mitte, Ecken, Kanten), Decken-/Dach-/
|
||||
//! Raum-Umriss (Ecken, Kanten), 2D-Zeichnung (Eckpunkte, Mittelpunkte, Kanten). Bogenwände
|
||||
//! werden nicht angehängt. Freie Klicks decken sich praktisch nie und bleiben frei.
|
||||
//! Raum-Umriss (Ecken, Kanten), 2D-Zeichnung (Eckpunkte, Mittelpunkte, Kanten), Treppe (Umriss
|
||||
//! und Podest: Ecken, Kanten), Bogenwand (Enden, Punkt auf Achse/Fläche, Mittelpunkt), Rasterachse
|
||||
//! und Achsschnittpunkt ([112]). Freie Klicks decken sich praktisch nie und bleiben frei.
|
||||
//! - **Radius/Durchmesser/Bogenlänge** ([`refs_for_round`]): Mittelpunkt und Punkte auf dem Rand
|
||||
//! (`DimFeature::Rim`, Winkel) von 2D-Kreis, -Bogen oder Bogenwand; sie werden einzeln (ohne
|
||||
//! Kettenprojektion) nachgeführt.
|
||||
//! - **Nachführen** ([`sync_ops`]): nach jeder Benutzer-Änderung (`Document::commit`) löst der Kern
|
||||
//! die Bezüge auf und schreibt die Lage in `pts` zurück (dieselbe Undo-Stufe). Damit lesen alle
|
||||
//! Ableitungen (Plan, DXF, Griffe, Auswahl-Info) einfach `pts`, und `pts` ist immer die zuletzt
|
||||
@@ -78,6 +82,7 @@ struct WallGeo {
|
||||
offs: Vec<f64>,
|
||||
total: f64,
|
||||
arc: bool,
|
||||
warc: Option<crate::wall_arc::WallArc>,
|
||||
}
|
||||
|
||||
fn wall_geo(lk: &Lookup, w: &Value) -> Option<WallGeo> {
|
||||
@@ -106,16 +111,40 @@ fn wall_geo(lk: &Lookup, w: &Value) -> Option<WallGeo> {
|
||||
}
|
||||
}
|
||||
let arc = crate::wall_arc::is_arc_bulge(num(w.get("bulge")));
|
||||
Some(WallGeo { a, b, offs, total, arc })
|
||||
let warc = if arc { crate::wall_arc::WallArc::of(kernel2d::Vec2 { x: a.0, y: a.1 }, kernel2d::Vec2 { x: b.0, y: b.1 }, num(w.get("bulge"))) } else { None };
|
||||
Some(WallGeo { a, b, offs, total, arc, warc })
|
||||
}
|
||||
|
||||
impl WallGeo {
|
||||
/// Linie `index` (fehlt = Achse): Anfang und Ende.
|
||||
fn offset(&self, index: Option<u32>) -> Option<f64> {
|
||||
match index {
|
||||
None => Some(0.0),
|
||||
Some(k) => self.offs.get(k as usize).copied(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Punkt auf Linie `index` beim Anteil `t` (Bogenwand: entlang der Bogenlänge auf dem Versatzbogen).
|
||||
fn point(&self, index: Option<u32>, t: f64) -> Option<P> {
|
||||
let o = self.offset(index)?;
|
||||
match &self.warc {
|
||||
Some(w) => {
|
||||
let q = w.point(t * w.length(), o);
|
||||
Some((q.x, q.y))
|
||||
}
|
||||
None => {
|
||||
let (a, b) = self.line(index)?;
|
||||
Some(lerp(a, b, t))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Linie `index` (fehlt = Achse): Anfang und Ende (Bogenwand: Sehne zwischen den Bogenenden).
|
||||
fn line(&self, index: Option<u32>) -> Option<(P, P)> {
|
||||
let o = match index {
|
||||
None => 0.0,
|
||||
Some(k) => *self.offs.get(k as usize)?,
|
||||
};
|
||||
let o = self.offset(index)?;
|
||||
if let Some(w) = &self.warc {
|
||||
let (p0, p1) = (w.point(0.0, o), w.point(w.length(), o));
|
||||
return Some(((p0.x, p0.y), (p1.x, p1.y)));
|
||||
}
|
||||
let n = left(unit(self.a, self.b)?);
|
||||
Some((add(self.a, n, o), add(self.b, n, o)))
|
||||
}
|
||||
@@ -149,6 +178,32 @@ struct Shape {
|
||||
pts: Vec<P>,
|
||||
closed: bool,
|
||||
center: Option<P>,
|
||||
/// Weitere geschlossene Umrisse (Treppenpodest): Ecken/Kanten zählen nach denen von `pts` weiter.
|
||||
more: Vec<Vec<P>>,
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
fn new(pts: Vec<P>, closed: bool, center: Option<P>) -> Shape {
|
||||
Shape { pts, closed, center, more: Vec::new() }
|
||||
}
|
||||
|
||||
fn vertex(&self, mut i: usize) -> Option<P> {
|
||||
if i < self.pts.len() {
|
||||
return Some(self.pts[i]);
|
||||
}
|
||||
i -= self.pts.len();
|
||||
for m in &self.more {
|
||||
if i < m.len() {
|
||||
return Some(m[i]);
|
||||
}
|
||||
i -= m.len();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn vertex_count(&self) -> usize {
|
||||
self.pts.len() + self.more.iter().map(Vec::len).sum::<usize>()
|
||||
}
|
||||
}
|
||||
|
||||
fn pts_list(v: Option<&Value>) -> Vec<P> {
|
||||
@@ -163,35 +218,55 @@ fn column_shape(c: &Value) -> Option<Shape> {
|
||||
let rot = num(c.get("rotation")).unwrap_or(0.0);
|
||||
let (co, si) = (crate::jsnum::cos(rot), crate::jsnum::sin(rot));
|
||||
let pts = [(-hw, -hd), (hw, -hd), (hw, hd), (-hw, hd)].iter().map(|&(x, y)| (at.0 + x * co - y * si, at.1 + x * si + y * co)).collect();
|
||||
return Some(Shape { pts, closed: true, center: Some(at) });
|
||||
return Some(Shape::new(pts, true, Some(at)));
|
||||
}
|
||||
Some(Shape { pts: Vec::new(), closed: false, center: Some(at) })
|
||||
Some(Shape::new(Vec::new(), false, Some(at)))
|
||||
}
|
||||
|
||||
fn drawing_shape(d: &Value) -> Option<Shape> {
|
||||
let g = d.get("geom")?;
|
||||
let p = |k: &str| pt(g.get(k));
|
||||
Some(match str_of(g, "shape")? {
|
||||
"line" => Shape { pts: vec![p("a")?, p("b")?], closed: false, center: None },
|
||||
"polyline" => Shape { pts: pts_list(g.get("pts")), closed: g.get("closed").and_then(Value::as_bool).unwrap_or(false), center: None },
|
||||
"line" => Shape::new(vec![p("a")?, p("b")?], false, None),
|
||||
"polyline" => Shape::new(pts_list(g.get("pts")), g.get("closed").and_then(Value::as_bool).unwrap_or(false), None),
|
||||
"rect" => {
|
||||
let (lo, hi) = (p("min")?, p("max")?);
|
||||
Shape { pts: vec![lo, (hi.0, lo.1), hi, (lo.0, hi.1)], closed: true, center: None }
|
||||
Shape::new(vec![lo, (hi.0, lo.1), hi, (lo.0, hi.1)], true, None)
|
||||
}
|
||||
"circle" | "arc" | "ellipse" => Shape { pts: Vec::new(), closed: false, center: Some(p("center")?) },
|
||||
"circle" | "arc" | "ellipse" => Shape::new(Vec::new(), false, Some(p("center")?)),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Listen, in denen Ecke/Kante/Mitte ihr Element suchen (in dieser Reihenfolge).
|
||||
const SHAPE_LISTS: [&str; 5] = ["columns", "ceilings", "roofs", "rooms", "drawings2d"];
|
||||
const SHAPE_LISTS: [&str; 6] = ["columns", "ceilings", "roofs", "rooms", "drawings2d", "stairs"];
|
||||
|
||||
/// Treppe: Umriss (gerade/L: Aussenlinie; Wendel: die vier Ecken der Schliesslinien), Podest als
|
||||
/// weiterer Umriss, Mittelpunkt nur bei der Wendel.
|
||||
fn stair_shape(e: &Value) -> Option<Shape> {
|
||||
let s: crate::model::Stair = serde_json::from_value(e.clone()).ok()?;
|
||||
let sp = crate::stair::decode_params(&s.encode())?;
|
||||
let o = kernel2d::stair_outline(&sp);
|
||||
let t = |q: &kernel2d::Vec2| (q.x, q.y);
|
||||
if let Some(poly) = o.polygon {
|
||||
let mut sh = Shape::new(poly.iter().map(t).collect(), true, None);
|
||||
if let Some(l) = kernel2d::stair_geometry(&sp, 3.0).landing {
|
||||
sh.more.push(l.iter().map(t).collect());
|
||||
}
|
||||
return Some(sh);
|
||||
}
|
||||
let sp2 = o.spiral?;
|
||||
let [(i0, o0), (i1, o1)] = sp2.lines;
|
||||
Some(Shape::new(vec![t(&i0), t(&o0), t(&o1), t(&i1)], true, Some((sp2.arcs[0].0.x, sp2.arcs[0].0.y))))
|
||||
}
|
||||
|
||||
fn shape_of(coll: &str, e: &Value) -> Option<Shape> {
|
||||
match coll {
|
||||
"columns" => column_shape(e),
|
||||
"ceilings" | "roofs" => Some(Shape { pts: pts_list(e.get("outline")), closed: true, center: None }),
|
||||
"rooms" => Some(Shape { pts: pts_list(e.get("boundary")), closed: true, center: None }),
|
||||
"ceilings" | "roofs" => Some(Shape::new(pts_list(e.get("outline")), true, None)),
|
||||
"rooms" => Some(Shape::new(pts_list(e.get("boundary")), true, None)),
|
||||
"drawings2d" => drawing_shape(e),
|
||||
"stairs" => stair_shape(e),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -200,17 +275,66 @@ fn find_shape(lk: &Lookup, id: &str) -> Option<Shape> {
|
||||
SHAPE_LISTS.iter().find_map(|c| lk.find(c, id).map(|e| (*c, e))).and_then(|(c, e)| shape_of(c, e))
|
||||
}
|
||||
|
||||
fn edge(s: &Shape, i: usize) -> Option<(P, P)> {
|
||||
let n = s.pts.len();
|
||||
fn ring_edge(pts: &[P], closed: bool, i: usize) -> Option<(P, P)> {
|
||||
let n = pts.len();
|
||||
if i + 1 < n {
|
||||
Some((s.pts[i], s.pts[i + 1]))
|
||||
} else if s.closed && n > 2 && i + 1 == n {
|
||||
Some((s.pts[i], s.pts[0]))
|
||||
Some((pts[i], pts[i + 1]))
|
||||
} else if closed && n > 2 && i + 1 == n {
|
||||
Some((pts[i], pts[0]))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn ring_edges(pts: &[P], closed: bool) -> usize {
|
||||
if closed && pts.len() > 2 {
|
||||
pts.len()
|
||||
} else {
|
||||
pts.len().saturating_sub(1)
|
||||
}
|
||||
}
|
||||
|
||||
fn edge(s: &Shape, mut i: usize) -> Option<(P, P)> {
|
||||
let n = ring_edges(&s.pts, s.closed);
|
||||
if i < n {
|
||||
return ring_edge(&s.pts, s.closed, i);
|
||||
}
|
||||
i -= n;
|
||||
for m in &s.more {
|
||||
let k = ring_edges(m, true);
|
||||
if i < k {
|
||||
return ring_edge(m, true, i);
|
||||
}
|
||||
i -= k;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn edge_count(s: &Shape) -> usize {
|
||||
ring_edges(&s.pts, s.closed) + s.more.iter().map(|m| ring_edges(m, true)).sum::<usize>()
|
||||
}
|
||||
|
||||
/// Rasterachse `index` des Rasters `id` und das Raster selbst.
|
||||
fn with_grid<T>(lk: &Lookup, id: &str, f: impl FnOnce(&crate::grid::Spec) -> Option<T>) -> Option<T> {
|
||||
let d = lk.find("drawings2d", id)?;
|
||||
let g: crate::model::Drawing2DGeom = serde_json::from_value(d.get("geom")?.clone()).ok()?;
|
||||
f(&crate::grid::Spec::of(&g)?)
|
||||
}
|
||||
|
||||
/// Kreis/Bogen (2D-Zeichnung) oder Bogenwand-Schicht: Mittelpunkt, Radius.
|
||||
fn round_of(lk: &Lookup, id: &str, index: Option<u32>) -> Option<(P, f64)> {
|
||||
if let Some(d) = lk.find("drawings2d", id) {
|
||||
let g = d.get("geom")?;
|
||||
if matches!(str_of(g, "shape"), Some("circle" | "arc")) {
|
||||
return Some((pt(g.get("center"))?, num(g.get("r"))?));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
let g = wall_geo(lk, lk.find("walls", id)?)?;
|
||||
let w = g.warc?;
|
||||
Some(((w.center.x, w.center.y), w.radius_at(g.offset(index)?)))
|
||||
}
|
||||
|
||||
/// Schnitt zweier unendlicher Geraden (parallel → `None`).
|
||||
fn intersect(a: (P, P), b: (P, P)) -> Option<P> {
|
||||
let r = sub(a.1, a.0);
|
||||
@@ -229,17 +353,27 @@ fn intersect(a: (P, P), b: (P, P)) -> Option<P> {
|
||||
pub fn resolve(lk: &Lookup, r: &DimRef) -> Option<P> {
|
||||
let wall_line = |id: &str, idx: Option<u32>| -> Option<(P, P)> { wall_geo(lk, lk.find("walls", id)?)?.line(idx) };
|
||||
let p = match r.feature {
|
||||
DimFeature::Wall => {
|
||||
let (a, b) = wall_line(&r.id, r.index)?;
|
||||
lerp(a, b, r.t?)
|
||||
}
|
||||
DimFeature::Wall => wall_geo(lk, lk.find("walls", &r.id)?)?.point(r.index, r.t?)?,
|
||||
DimFeature::Opening => opening_point(lk, lk.find("openings", &r.id)?, r.index?, r.index2)?,
|
||||
DimFeature::Vertex => *find_shape(lk, &r.id)?.pts.get(r.index? as usize)?,
|
||||
DimFeature::Vertex => find_shape(lk, &r.id)?.vertex(r.index? as usize)?,
|
||||
DimFeature::Edge => {
|
||||
let (a, b) = edge(&find_shape(lk, &r.id)?, r.index? as usize)?;
|
||||
lerp(a, b, r.t?)
|
||||
}
|
||||
DimFeature::Center => find_shape(lk, &r.id)?.center?,
|
||||
DimFeature::Center => match find_shape(lk, &r.id) {
|
||||
Some(sh) => sh.center?,
|
||||
None => {
|
||||
let w = wall_geo(lk, lk.find("walls", &r.id)?)?.warc?;
|
||||
(w.center.x, w.center.y)
|
||||
}
|
||||
},
|
||||
DimFeature::Axis => with_grid(lk, &r.id, |g| g.point_at(r.index?, r.t?))?,
|
||||
DimFeature::AxisCross => with_grid(lk, &r.id, |g| g.cross(r.index?, r.index2?))?,
|
||||
DimFeature::Rim => {
|
||||
let (c, rad) = round_of(lk, &r.id, r.index)?;
|
||||
let a = r.t?;
|
||||
(c.0 + rad * a.cos(), c.1 + rad * a.sin())
|
||||
}
|
||||
DimFeature::Intersection => intersect(wall_line(&r.id, r.index)?, wall_line(r.id2.as_deref()?, r.index2)?)?,
|
||||
};
|
||||
finite(p).then_some(p)
|
||||
@@ -276,7 +410,6 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
|
||||
.iter()
|
||||
.filter(|w| on_level(w, "floorId", level))
|
||||
.filter_map(|w| Some((str_of(w, "id")?, wall_geo(lk, w)?)))
|
||||
.filter(|(_, g)| !g.arc)
|
||||
.collect();
|
||||
// 1) Öffnungen: Leibungen und Mitte auf jeder Linie der Wirtswand.
|
||||
for o in list(lk, "openings") {
|
||||
@@ -300,9 +433,24 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// 2b) Bogenwände: Mittelpunkt, Punkt auf Achse/Schichtgrenze (Anteil der Bogenlänge).
|
||||
for (id, g) in walls.iter().filter(|(_, g)| g.warc.is_some()) {
|
||||
let Some(w) = &g.warc else { continue };
|
||||
if dist((w.center.x, w.center.y), s) <= tol {
|
||||
return Some(rf(id, DimFeature::Center));
|
||||
}
|
||||
let (ls, ln) = w.local(kernel2d::Vec2 { x: s.0, y: s.1 });
|
||||
let len = w.length();
|
||||
for (k, _, _) in g.lines() {
|
||||
let Some(o) = g.offset(k) else { continue };
|
||||
if (ln - o).abs() <= tol && ls >= -tol && ls <= len + tol {
|
||||
return Some(DimRef { index: k, t: Some((ls / len).clamp(0.0, 1.0)), ..rf(id, DimFeature::Wall) });
|
||||
}
|
||||
}
|
||||
}
|
||||
// 3) Wandecken: auf den Linien zweier Wände (Verlängerung bis zur Wanddicke über das Ende).
|
||||
let mut hits: Vec<(&str, Option<u32>, P, P, f64)> = Vec::new();
|
||||
for (id, g) in &walls {
|
||||
for (id, g) in walls.iter().filter(|(_, g)| !g.arc) {
|
||||
let len = dist(g.a, g.b);
|
||||
let m = (g.total.max(0.3) + tol) / len;
|
||||
for (k, a, b) in g.lines() {
|
||||
@@ -324,7 +472,7 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
|
||||
if let Some(h) = hits.iter().find(|h| (0.0..=1.0).contains(&h.4)) {
|
||||
return Some(DimRef { index: h.1, t: Some(h.4), ..rf(h.0, DimFeature::Wall) });
|
||||
}
|
||||
// 5) Stützen, Decken, Dächer, Räume, 2D-Zeichnungen: Mitte, Ecken, Kanten.
|
||||
// 5) Stützen, Decken, Dächer, Räume, 2D-Zeichnungen, Treppen: Mitte, Ecken, Kanten.
|
||||
for coll in SHAPE_LISTS {
|
||||
let key = if coll == "drawings2d" { "levelId" } else { "floorId" };
|
||||
for e in list(lk, coll).iter().filter(|e| on_level(e, key, level)) {
|
||||
@@ -332,10 +480,10 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
|
||||
if sh.center.is_some_and(|c| dist(c, s) <= tol) {
|
||||
return Some(rf(id, DimFeature::Center));
|
||||
}
|
||||
if let Some(i) = sh.pts.iter().position(|p| dist(*p, s) <= tol) {
|
||||
if let Some(i) = (0..sh.vertex_count()).find(|&i| sh.vertex(i).is_some_and(|p| dist(p, s) <= tol)) {
|
||||
return Some(DimRef { index: Some(i as u32), ..rf(id, DimFeature::Vertex) });
|
||||
}
|
||||
for i in 0..sh.pts.len() {
|
||||
for i in 0..edge_count(&sh) {
|
||||
let Some((a, b)) = edge(&sh, i) else { continue };
|
||||
if let Some((t, d)) = param(a, b, s) {
|
||||
if d <= tol && (0.0..=1.0).contains(&t) {
|
||||
@@ -345,9 +493,93 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// 6) Achsraster ([112]): Achsschnittpunkt, sonst Punkt auf einer Achse.
|
||||
for d in list(lk, "drawings2d") {
|
||||
let Some(id) = str_of(d, "id") else { continue };
|
||||
let Some(g) = d.get("geom").filter(|g| str_of(g, "shape") == Some("grid")) else { continue };
|
||||
let Ok(geom) = serde_json::from_value::<crate::model::Drawing2DGeom>(g.clone()) else { continue };
|
||||
let Some(spec) = crate::grid::Spec::of(&geom) else { continue };
|
||||
let visible = serde_json::from_value::<crate::model::Drawing2D>(d.clone()).map(|dd| crate::grid::visible_on(&dd, level)).unwrap_or(false);
|
||||
if !visible {
|
||||
continue;
|
||||
}
|
||||
let n = (spec.a.len() + spec.b.len()) as u32;
|
||||
for i in 0..spec.a.len() as u32 {
|
||||
for j in spec.a.len() as u32..n {
|
||||
if spec.cross(i, j).is_some_and(|p| dist(p, s) <= tol) {
|
||||
return Some(DimRef { index: Some(i), index2: Some(j), ..rf(id, DimFeature::AxisCross) });
|
||||
}
|
||||
}
|
||||
}
|
||||
for i in 0..n {
|
||||
if let Some((t, d)) = spec.project(i, s) {
|
||||
if d <= tol && (-1e-9..=1.0 + 1e-9).contains(&t) {
|
||||
return Some(DimRef { index: Some(i), t: Some(t.clamp(0.0, 1.0)), ..rf(id, DimFeature::Axis) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Rand-Bezug (Winkel `a`) auf dem Kreis/Bogen `id` ([38]).
|
||||
fn rim(id: &str, index: Option<u32>, a: f64) -> DimRef {
|
||||
DimRef { index, t: Some(a), ..rf(id, DimFeature::Rim) }
|
||||
}
|
||||
|
||||
/// Kreis/Bogen (2D-Zeichnung des Geschosses) oder Bogenwand-Schicht, auf deren Rand `s` liegt
|
||||
/// (Toleranz `tol`): Kennung, Schichtgrenze, Mittelpunkt, Radius.
|
||||
pub fn find_round(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<(String, Option<u32>, P, f64)> {
|
||||
// Nächster Rand innerhalb der Toleranz (bei konzentrischen Kreisen/Schichten der genaueste).
|
||||
let mut best: Option<(f64, (String, Option<u32>, P, f64))> = None;
|
||||
let mut offer = |err: f64, hit: (String, Option<u32>, P, f64)| {
|
||||
if err <= tol && best.as_ref().is_none_or(|(e, _)| err < *e) {
|
||||
best = Some((err, hit));
|
||||
}
|
||||
};
|
||||
for d in list(lk, "drawings2d").iter().filter(|d| on_level(d, "levelId", level)) {
|
||||
let (Some(id), Some(g)) = (str_of(d, "id"), d.get("geom")) else { continue };
|
||||
if !matches!(str_of(g, "shape"), Some("circle" | "arc")) {
|
||||
continue;
|
||||
}
|
||||
let (Some(c), Some(r)) = (pt(g.get("center")), num(g.get("r"))) else { continue };
|
||||
offer((dist(c, s) - r).abs(), (id.to_owned(), None, c, r));
|
||||
}
|
||||
for w in list(lk, "walls").iter().filter(|w| on_level(w, "floorId", level)) {
|
||||
let (Some(id), Some(g)) = (str_of(w, "id"), wall_geo(lk, w)) else { continue };
|
||||
let Some(arc) = g.warc else { continue };
|
||||
let c = (arc.center.x, arc.center.y);
|
||||
let mut ks: Vec<Option<u32>> = vec![None];
|
||||
ks.extend((0..g.offs.len() as u32).map(Some));
|
||||
for k in ks {
|
||||
let Some(o) = g.offset(k) else { continue };
|
||||
let r = arc.radius_at(o);
|
||||
offer((dist(c, s) - r).abs(), (id.to_owned(), k, c, r));
|
||||
}
|
||||
}
|
||||
best.map(|(_, h)| h)
|
||||
}
|
||||
|
||||
/// Radius-/Durchmesser-/Bogenlängen-Bemassung ([38]): aus den Klickpunkten `clicks` (ein Punkt auf
|
||||
/// dem Rand; bei der Bogenlänge Anfang und Ende) die Punkte `pts` (Mittelpunkt, Randpunkt[e]) und
|
||||
/// ihre Bezüge. `None`, wenn kein Kreis/Bogen/Bogenwand getroffen wird.
|
||||
pub fn round_dimension(lk: &Lookup, level: &str, kind: crate::model::DimKind, clicks: &[P], tol: f64) -> Option<(Vec<P>, Vec<Option<DimRef>>)> {
|
||||
use crate::model::DimKind;
|
||||
let first = *clicks.first()?;
|
||||
let (id, idx, c, r) = find_round(lk, level, first, tol)?;
|
||||
let ang = |p: P| (p.1 - c.1).atan2(p.0 - c.0);
|
||||
let on_rim = |a: f64| (c.0 + r * a.cos(), c.1 + r * a.sin());
|
||||
let a0 = ang(first);
|
||||
let mut pts = vec![c, on_rim(a0)];
|
||||
let mut refs = vec![Some(rf(&id, DimFeature::Center)), Some(rim(&id, idx, a0))];
|
||||
if kind == DimKind::Arc {
|
||||
let a1 = ang(*clicks.get(1)?);
|
||||
pts.push(on_rim(a1));
|
||||
refs.push(Some(rim(&id, idx, a1)));
|
||||
}
|
||||
Some((pts, refs))
|
||||
}
|
||||
|
||||
/// Bezüge einer neuen Kette `pts`: je Punkt der erste Fangpunkt aus `snaps`, der auf ihn projiziert
|
||||
/// (Kette = Gerade pts[0]→pts[1]) und an einem Merkmal hängt; `d` = Normalabstand Fangpunkt → Punkt.
|
||||
/// `keep(i)` liefert einen schon bekannten Bezug (Ergänzen einer Kette). Kein Bezug → `None`.
|
||||
@@ -411,6 +643,13 @@ pub fn resolve_chain(lk: &Lookup, pts: &[P], refs: &[Option<DimRef>]) -> (Vec<P>
|
||||
(out, lost)
|
||||
}
|
||||
|
||||
/// Punkte ohne Kettenprojektion (Radius-/Bogenmass): jeder hängende Punkt an seiner Lage.
|
||||
fn resolve_each(lk: &Lookup, pts: &[P], refs: &[Option<DimRef>]) -> (Vec<P>, Vec<bool>) {
|
||||
let q: Vec<Option<P>> = (0..pts.len()).map(|i| refs.get(i).and_then(Option::as_ref).and_then(|r| resolve(lk, r))).collect();
|
||||
let lost = (0..refs.len()).map(|i| refs[i].is_some() && q.get(i).copied().flatten().is_none()).collect();
|
||||
(pts.iter().zip(&q).map(|(p, n)| n.unwrap_or(*p)).collect(), lost)
|
||||
}
|
||||
|
||||
fn refs_of(g: &Value) -> Option<Vec<Option<DimRef>>> {
|
||||
let r = g.get("refs")?;
|
||||
let refs: Vec<Option<DimRef>> = serde_json::from_value(r.clone()).ok()?;
|
||||
@@ -441,7 +680,8 @@ pub fn sync_ops(lk: &Lookup) -> Vec<Op> {
|
||||
if pts.len() != g.get("pts").and_then(Value::as_array).map_or(0, Vec::len) {
|
||||
continue;
|
||||
}
|
||||
let (np, lost) = resolve_chain(lk, &pts, &refs);
|
||||
let round = str_of(g, "kind").is_some();
|
||||
let (np, lost) = if round { resolve_each(lk, &pts, &refs) } else { resolve_chain(lk, &pts, &refs) };
|
||||
let moved = np.iter().zip(&pts).any(|(a, b)| dist(*a, *b) > MOVE_EPS);
|
||||
let flags_changed = refs.iter().zip(&lost).any(|(r, l)| r.as_ref().is_some_and(|r| r.lost.unwrap_or(false) != *l));
|
||||
if !moved && !flags_changed {
|
||||
@@ -690,6 +930,134 @@ mod tests {
|
||||
assert!(d.last_extra().is_empty());
|
||||
}
|
||||
|
||||
fn grid_project() -> Map<String, Value> {
|
||||
root(json!({
|
||||
"drawings2d": [
|
||||
{"id": "G", "type": "drawing2d", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 6}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 4}], "extend": 1}}
|
||||
]
|
||||
}))
|
||||
}
|
||||
|
||||
/// [112] Rasterachsen: Punkt auf Achse, Achsschnittpunkt; die Bemassung folgt der verschobenen Achse.
|
||||
#[test]
|
||||
fn rasterachsen_bezuege_folgen_der_achse() {
|
||||
let mut r = grid_project();
|
||||
let lk = Lookup::plain(&r);
|
||||
// Achsschnittpunkt 2/B (index 1 × index 3), Punkt auf Achse 1.
|
||||
let cross = attach(&lk, "eg", (6.0, 4.0), TOL).unwrap();
|
||||
assert_eq!((cross.feature, cross.index, cross.index2), (DimFeature::AxisCross, Some(1), Some(3)));
|
||||
let on1 = attach(&lk, "eg", (0.0, 2.5), TOL).unwrap();
|
||||
assert_eq!((on1.feature, on1.index), (DimFeature::Axis, Some(0)));
|
||||
close(resolve(&lk, &on1).unwrap(), (0.0, 2.5));
|
||||
// Bemassung zwischen Achse 1 und Achse 2 (Kette bei y = 1): Länge 6; Achse 2 nach x = 7.5 → 7.5.
|
||||
let pts = [(0.0, 1.0), (6.0, 1.0)];
|
||||
let refs = vec![attach(&lk, "eg", (0.0, 1.0), TOL), attach(&lk, "eg", (6.0, 1.0), TOL)];
|
||||
assert!(refs.iter().all(|x| x.as_ref().is_some_and(|x| x.feature == DimFeature::Axis)));
|
||||
set(&mut r, "drawings2d", "G", "geom", json!({"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 7.5}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 4}], "extend": 1}));
|
||||
let (np, lost) = resolve_chain(&Lookup::plain(&r), &pts, &refs);
|
||||
assert_eq!(lost, vec![false, false]);
|
||||
close(np[0], (0.0, 1.0));
|
||||
close(np[1], (7.5, 1.0));
|
||||
// Raster gelöscht → ungültig.
|
||||
r.insert("drawings2d".into(), json!([]));
|
||||
assert!(resolve(&Lookup::plain(&r), refs[1].as_ref().unwrap()).is_none());
|
||||
}
|
||||
|
||||
fn arc_project() -> Map<String, Value> {
|
||||
root(json!({
|
||||
"wallTypes": [{"id": "T", "layers": [{"thickness": 0.1}, {"thickness": 0.2}]}],
|
||||
// Halbkreis: Mittelpunkt (5, 0), Achsradius 5, Scheitel (5, 5).
|
||||
"walls": [{"id": "A", "floorId": "eg", "wallTypeId": "T", "start": {"x": 0, "y": 0}, "end": {"x": 10, "y": 0}, "bulge": 1}],
|
||||
"drawings2d": [{"id": "K", "levelId": "eg", "geom": {"shape": "circle", "center": {"x": 30, "y": 0}, "r": 2}}]
|
||||
}))
|
||||
}
|
||||
|
||||
/// [38] Bogenwand: Enden, Punkt auf Achse/Fläche (Anteil der Bogenlänge), Mittelpunkt, Rand-Bezug.
|
||||
#[test]
|
||||
fn bogenwand_bezuege() {
|
||||
let mut r = arc_project();
|
||||
let lk = Lookup::plain(&r);
|
||||
let apex = attach(&lk, "eg", (5.0, 5.0), TOL).unwrap();
|
||||
assert_eq!((apex.feature, apex.index), (DimFeature::Wall, None));
|
||||
assert!((apex.t.unwrap() - 0.5).abs() < 1e-9);
|
||||
let face = attach(&lk, "eg", (5.0, 5.15), TOL).unwrap();
|
||||
assert_eq!((face.feature, face.index), (DimFeature::Wall, Some(2)));
|
||||
let end = attach(&lk, "eg", (10.0, 0.0), TOL).unwrap();
|
||||
assert_eq!((end.feature, end.t), (DimFeature::Wall, Some(1.0)));
|
||||
let centre = attach(&lk, "eg", (5.0, 0.0), TOL).unwrap();
|
||||
assert_eq!(centre.feature, DimFeature::Center);
|
||||
close(resolve(&lk, ¢re).unwrap(), (5.0, 0.0));
|
||||
close(resolve(&lk, &face).unwrap(), (5.0, 5.15));
|
||||
// Rand-Bezug (Winkel 90°) auf der Fläche 2: Radius 5.15; Mittelpunkt und Winkel bleiben beim Strecken.
|
||||
let rim_ref = DimRef { index: Some(2), t: Some(std::f64::consts::FRAC_PI_2), ..rf("A", DimFeature::Rim) };
|
||||
close(resolve(&lk, &rim_ref).unwrap(), (5.0, 5.15));
|
||||
// Wand verlängern (Ende x = 12 → Mittelpunkt (6, 0), Radius 6): Scheitel folgt.
|
||||
set(&mut r, "walls", "A", "end", json!({"x": 12, "y": 0}));
|
||||
let lk = Lookup::plain(&r);
|
||||
close(resolve(&lk, &apex).unwrap(), (6.0, 6.0));
|
||||
close(resolve(&lk, ¢re).unwrap(), (6.0, 0.0));
|
||||
}
|
||||
|
||||
/// [38] Radius-, Durchmesser- und Bogenlängen-Bemassung hängen an Kreis und Bogenwand.
|
||||
#[test]
|
||||
fn radius_und_bogenmass_assoziativ() {
|
||||
use crate::model::DimKind;
|
||||
let mut r = arc_project();
|
||||
let lk = Lookup::plain(&r);
|
||||
let (pts, refs) = round_dimension(&lk, "eg", DimKind::Radius, &[(30.0, 2.0)], 0.1).unwrap();
|
||||
close(pts[0], (30.0, 0.0));
|
||||
close(pts[1], (30.0, 2.0));
|
||||
assert_eq!(refs[0].as_ref().unwrap().feature, DimFeature::Center);
|
||||
// Kreis verschieben und vergrössern → Mittelpunkt und Randpunkt folgen (ohne Kettenprojektion).
|
||||
set(&mut r, "drawings2d", "K", "geom", json!({"shape": "circle", "center": {"x": 40, "y": 5}, "r": 3}));
|
||||
let (np, lost) = resolve_each(&Lookup::plain(&r), &pts, &refs);
|
||||
assert_eq!(lost, vec![false, false]);
|
||||
close(np[0], (40.0, 5.0));
|
||||
close(np[1], (40.0, 8.0));
|
||||
// Bogenlänge auf der Aussenfläche der Bogenwand (Radius 5.15): Viertelkreis von 90° bis 0°.
|
||||
let lk = Lookup::plain(&r);
|
||||
let (pts, refs) = round_dimension(&lk, "eg", DimKind::Arc, &[(5.0, 5.15), (5.15, 0.0)], 0.04).unwrap();
|
||||
assert_eq!(pts.len(), 3);
|
||||
close(pts[0], (5.0, 0.0));
|
||||
assert_eq!(refs[1].as_ref().unwrap().index, Some(2));
|
||||
// Nichts getroffen.
|
||||
assert!(round_dimension(&lk, "eg", DimKind::Radius, &[(100.0, 100.0)], 0.1).is_none());
|
||||
}
|
||||
|
||||
/// [38] Treppe: Umriss-Ecken/-Kanten und Podest-Kanten der L-Treppe sind anhängbar.
|
||||
#[test]
|
||||
fn treppe_bezuege() {
|
||||
let stair = |shape: &str| json!({"id": "S", "type": "stair", "floorId": "eg", "categoryCode": "20", "shape": shape,
|
||||
"start": {"x": 0, "y": 0}, "dir": {"x": 1, "y": 0}, "runLength": 3, "run2Length": 2, "turn": 1, "width": 1, "stepCount": 16});
|
||||
let r = root(json!({"stairs": [stair("straight")]}));
|
||||
let lk = Lookup::plain(&r);
|
||||
let sh = find_shape(&lk, "S").unwrap();
|
||||
assert_eq!(sh.pts.len(), 4);
|
||||
// Eck 0 und Mitte der Kante 1 (Auftrittsende) hängen an und lösen auf.
|
||||
let v0 = sh.pts[0];
|
||||
let rv = attach(&lk, "eg", v0, TOL).unwrap();
|
||||
assert_eq!((rv.feature, rv.id.as_str(), rv.index), (DimFeature::Vertex, "S", Some(0)));
|
||||
let (a, b) = edge(&sh, 1).unwrap();
|
||||
let mid = lerp(a, b, 0.5);
|
||||
let re = attach(&lk, "eg", mid, TOL).unwrap();
|
||||
assert_eq!((re.feature, re.index), (DimFeature::Edge, Some(1)));
|
||||
close(resolve(&lk, &re).unwrap(), mid);
|
||||
// L-Treppe: zusätzlich Podest-Ecken und -Kanten (Indizes nach dem Umriss).
|
||||
let r = root(json!({"stairs": [stair("L")]}));
|
||||
let lk = Lookup::plain(&r);
|
||||
let sh = find_shape(&lk, "S").unwrap();
|
||||
assert_eq!(sh.pts.len(), 6);
|
||||
assert_eq!(sh.more.len(), 1);
|
||||
let n = sh.pts.len();
|
||||
let landing_corner = sh.vertex(n).unwrap();
|
||||
let rl = attach(&lk, "eg", landing_corner, TOL).unwrap();
|
||||
assert_eq!(rl.feature, DimFeature::Vertex);
|
||||
close(resolve(&lk, &rl).unwrap(), landing_corner);
|
||||
assert!(edge_count(&sh) > n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn befehl_bemassung_haengt_gefangene_punkte_an() {
|
||||
let r = project();
|
||||
|
||||
@@ -76,6 +76,8 @@ pub struct DormerGeom {
|
||||
pub main_thickness: f64,
|
||||
/// Ende der Gaubendach-Flächen hinten (lokal v).
|
||||
pub v_end: f64,
|
||||
/// Über den First hinaus und darum gekappt ([G5]).
|
||||
pub clamped: bool,
|
||||
}
|
||||
|
||||
/// Fläche des Gaubendachs: Grundriss-Polygon (lokal, Gegenuhrzeigersinn) und Ebene `z = a + bu·u + bv·v`
|
||||
@@ -157,8 +159,62 @@ pub fn roof_layers(p: &Project, roof: &Roof, d: &Dormer) -> Vec<Layer> {
|
||||
}
|
||||
|
||||
/// Gaubengeometrie; `None` bei unsinnigen Parametern (zu schmal, zu niedrig, Gaubendach steiler als das
|
||||
/// Hauptdach bei der Schleppgaube, Punkt nicht in einer geneigten Fläche).
|
||||
/// Hauptdach bei der Schleppgaube, Punkt nicht in einer geneigten Fläche). Reicht die Gaube über den
|
||||
/// First/Grat ihrer Dachfläche hinaus (zu hoch), wird sie abgefangen: Stirnhöhe (bzw. Tiefe der
|
||||
/// Schleppgaube) so gekappt, dass die Gaubendach-Oberkante spätestens am First auf die Hauptdach-Oberkante
|
||||
/// trifft (`clamped`); das Gaubendach endet am Rand der Dachfläche.
|
||||
pub fn geometry(p: &Project, roof: &Roof, d: &Dormer) -> Option<DormerGeom> {
|
||||
let g = geometry_raw(p, roof, d)?;
|
||||
let pts = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)).planes.into_iter().nth(g.frame.plane)?;
|
||||
let f = g.frame.clone();
|
||||
let inside = |v: f64| point_in_xy(f.plan(0.0, v)[0], f.plan(0.0, v)[1], &pts);
|
||||
// Tiefe bis zum Rand der Dachfläche (First/Grat) längs der Gaubenmitte.
|
||||
let (mut lo, mut hi) = (0.0, 60.0);
|
||||
if inside(hi) {
|
||||
return Some(g);
|
||||
}
|
||||
let mut g = g;
|
||||
for _ in 0..60 {
|
||||
let m = (lo + hi) / 2.0;
|
||||
if inside(m) {
|
||||
lo = m;
|
||||
} else {
|
||||
hi = m;
|
||||
}
|
||||
}
|
||||
let v_edge = lo;
|
||||
// Wo die Gaubendach-OBERKANTE die Hauptdach-Oberkante trifft (hinter dem Lochrand).
|
||||
let (tm, t, hw, rv) = (f.tan_main, g.tan_p, g.width / 2.0, g.roof_vertical());
|
||||
let meet = match g.kind {
|
||||
DormerKind::Schlepp => (g.front_height + rv) / (tm - t),
|
||||
DormerKind::Flach => (g.front_height + rv) / tm,
|
||||
_ => (g.front_height + hw * t + rv) / tm,
|
||||
};
|
||||
let v_r = v_edge - 1e-3;
|
||||
// Gaubendach nicht über den Rand der Dachfläche hinaus verlängern (sonst ragt es jenseits des Firsts);
|
||||
// 1 cm davor endet es unter der Hauptdach-Oberkante (nicht bündig mit dem First: keine Splitter).
|
||||
let cap = |g: &mut DormerGeom, meet: f64| g.v_end = g.v_end.min((v_edge - 0.01).max(meet.min(v_edge)));
|
||||
if meet <= v_r + 1e-9 {
|
||||
cap(&mut g, meet);
|
||||
return Some(g);
|
||||
}
|
||||
let mut d2 = d.clone();
|
||||
match g.kind {
|
||||
DormerKind::Schlepp if d.depth.is_some_and(|x| x.is_finite() && x > 0.1) => d2.depth = Some(d2.depth.unwrap_or(0.0) - (meet - v_r)),
|
||||
DormerKind::Schlepp => d2.front_height = v_r * (tm - t) - rv,
|
||||
DormerKind::Flach => d2.front_height = v_r * tm - rv,
|
||||
_ => d2.front_height = v_r * tm - hw * t - rv,
|
||||
}
|
||||
if !(d2.front_height >= 0.3) || d2.depth.is_some_and(|x| !(x > 0.1)) {
|
||||
return None;
|
||||
}
|
||||
let mut g2 = geometry_raw(p, roof, &d2)?;
|
||||
cap(&mut g2, v_r);
|
||||
g2.clamped = true;
|
||||
Some(g2)
|
||||
}
|
||||
|
||||
fn geometry_raw(p: &Project, roof: &Roof, d: &Dormer) -> Option<DormerGeom> {
|
||||
let frame = frame(p, roof, d)?;
|
||||
if !(finite_pos(d.width) && d.width >= 0.4 && d.width <= 30.0 && finite_pos(d.front_height) && d.front_height <= 10.0) {
|
||||
return None;
|
||||
@@ -186,7 +242,7 @@ pub fn geometry(p: &Project, roof: &Roof, d: &Dormer) -> Option<DormerGeom> {
|
||||
return None;
|
||||
}
|
||||
let z_e = frame.z_m0 + d.front_height;
|
||||
let mut g = DormerGeom { frame, kind: d.kind, width: d.width, front_height: d.front_height, overhang, tan_p, z_e, roof_layers, wall_layers, roof_thickness, wall_thickness, main_thickness, v_end: 0.0 };
|
||||
let mut g = DormerGeom { frame, kind: d.kind, width: d.width, front_height: d.front_height, overhang, tan_p, z_e, roof_layers, wall_layers, roof_thickness, wall_thickness, main_thickness, v_end: 0.0, clamped: false };
|
||||
// Hinten weit genug, dass die ganze Gaubendach-Unterkante unter der Hauptdach-Unterkante endet.
|
||||
let main_v = main_thickness * (1.0 + tm * tm).sqrt();
|
||||
let top_extra = roof_thickness * (1.0 + tan_p * tan_p).sqrt();
|
||||
@@ -214,6 +270,49 @@ impl DormerGeom {
|
||||
}
|
||||
}
|
||||
|
||||
/// Unterkante des Gaubeninneren als Facetten für Wände darunter ([G2]): Bereich zwischen Stirn und
|
||||
/// Wangen bis zum Lochrand, je Gaubendach-Fläche eine Ebene (Welt).
|
||||
pub fn under_facets(&self) -> Vec<crate::wall_bands::RoofFacet> {
|
||||
let (hw, tw, t, ze) = (self.width / 2.0, self.wall_thickness, self.tan_p, self.z_e);
|
||||
let hi = hw - tw;
|
||||
if !(hi > 1e-3) {
|
||||
return Vec::new();
|
||||
}
|
||||
let ring: Vec<P> = match self.kind {
|
||||
DormerKind::Flach | DormerKind::Schlepp => vec![[-hi, tw], [hi, tw], [hi, self.hole_v(hi)], [-hi, self.hole_v(-hi)]],
|
||||
_ => vec![[-hi, tw], [hi, tw], [hi, self.hole_v(hi)], [0.0, self.hole_v(0.0)], [-hi, self.hole_v(-hi)]],
|
||||
};
|
||||
// (Ring lokal, z = a + bu·u + bv·v), Bereiche überdeckungsfrei.
|
||||
let mut parts: Vec<(Vec<P>, f64, f64, f64)> = Vec::new();
|
||||
match self.kind {
|
||||
DormerKind::Flach => parts.push((ring, ze, 0.0, 0.0)),
|
||||
DormerKind::Schlepp => parts.push((ring, ze, 0.0, t)),
|
||||
DormerKind::Sattel | DormerKind::Unknown => {
|
||||
parts.push((clip_half(&ring, [-1.0, 0.0, 0.0]), ze + hw * t, t, 0.0));
|
||||
parts.push((clip_half(&ring, [1.0, 0.0, 0.0]), ze + hw * t, -t, 0.0));
|
||||
}
|
||||
DormerKind::Walm => {
|
||||
// Stirn-Walm: v ≤ hw − |u|; Seiten: darüber, links/rechts.
|
||||
let front = clip_half(&clip_half(&ring, [-1.0, -1.0, hw]), [1.0, -1.0, hw]);
|
||||
parts.push((front, ze, 0.0, t));
|
||||
parts.push((clip_half(&clip_half(&ring, [-1.0, 0.0, 0.0]), [-1.0, 1.0, -hw]), ze + hw * t, t, 0.0));
|
||||
parts.push((clip_half(&clip_half(&ring, [1.0, 0.0, 0.0]), [1.0, 1.0, -hw]), ze + hw * t, -t, 0.0));
|
||||
}
|
||||
}
|
||||
let f = &self.frame;
|
||||
parts
|
||||
.into_iter()
|
||||
.filter(|(r, ..)| r.len() >= 3)
|
||||
.filter_map(|(r, a, bu, bv)| {
|
||||
// u = (q − p)·ew, v = −(q − p)·h.
|
||||
let gx = bu * f.ew[0] - bv * f.h[0];
|
||||
let gy = bu * f.ew[1] - bv * f.h[1];
|
||||
let c = a - gx * f.p[0] - gy * f.p[1];
|
||||
crate::wall_bands::RoofFacet::new(r.iter().map(|q| f.plan(q[0], q[1])).collect(), [c, gx, gy])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lotrechter Abstand Oberkante − Unterkante (Gaubendach).
|
||||
pub fn roof_vertical(&self) -> f64 {
|
||||
self.roof_thickness * (1.0 + self.tan_p * self.tan_p).sqrt()
|
||||
@@ -319,6 +418,24 @@ impl DormerGeom {
|
||||
}
|
||||
}
|
||||
|
||||
/// Konvexer Ring, beschnitten auf die Halbebene `a·u + b·v + c ≥ 0` (Sutherland-Hodgman).
|
||||
fn clip_half(ring: &[P], [a, b, c]: [f64; 3]) -> Vec<P> {
|
||||
let f = |q: P| a * q[0] + b * q[1] + c;
|
||||
let mut out = Vec::new();
|
||||
for i in 0..ring.len() {
|
||||
let (p, q) = (ring[i], ring[(i + 1) % ring.len()]);
|
||||
let (fp, fq) = (f(p), f(q));
|
||||
if fp >= 0.0 {
|
||||
out.push(p);
|
||||
}
|
||||
if (fp >= 0.0) != (fq >= 0.0) {
|
||||
let t = fp / (fp - fq);
|
||||
out.push([p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Gaube `dormer_id` im Dach `roof_id` (Index des Dachs, Gaube).
|
||||
pub fn find<'a>(p: &'a Project, roof_id: &str, dormer_id: &str) -> Option<(usize, &'a Roof, &'a Dormer)> {
|
||||
let (ri, roof) = p.roofs.as_deref()?.iter().enumerate().find(|(_, r)| r.id == roof_id)?;
|
||||
@@ -345,7 +462,7 @@ pub fn dormer_openings(p: &Project, roof_index: usize) -> Vec<(&Opening, &Dormer
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
pub(crate) fn gable_project() -> Project {
|
||||
@@ -362,6 +479,25 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zu_hohe_gaube_wird_vor_dem_first_gekappt() {
|
||||
let mut p = gable_project();
|
||||
let roof = &mut p.roofs.as_mut().unwrap()[0];
|
||||
roof.dormers.as_mut().unwrap()[0].front_height = 6.0;
|
||||
let roof = &p.roofs.as_ref().unwrap()[0];
|
||||
let g = geometry(&p, roof, &roof.dormers.as_ref().unwrap()[0]).expect("gekappt statt verworfen");
|
||||
assert!(g.clamped && g.front_height < 6.0);
|
||||
// Gaubendach trifft die Hauptdach-Oberkante 1 mm vor dem First (y = 4; Stirn bei y = 1 ⇒ 3 m),
|
||||
// nichts reicht über den First.
|
||||
let reach = g.hole().iter().map(|q| q[1]).fold(0.0, f64::max);
|
||||
let meet = (g.front_height + 1.2 * g.tan_p + g.roof_vertical()) / g.frame.tan_main;
|
||||
assert!(reach < 2.999 && (meet - 2.999).abs() < 1e-6 && g.v_end <= 3.0 + 1e-9, "{reach} {meet} {}", g.v_end);
|
||||
let q = gable_project();
|
||||
let r0 = &q.roofs.as_ref().unwrap()[0];
|
||||
let ok = geometry(&q, r0, &r0.dormers.as_ref().unwrap()[0]).unwrap();
|
||||
assert!(!ok.clamped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_and_hole_on_gable_roof() {
|
||||
let p = gable_project();
|
||||
|
||||
@@ -0,0 +1,711 @@
|
||||
//! Baugrube / Geländebearbeitung ([68], [T6]): ein Umriss (Sohle) auf fester Höhe, Böschungen bis zum
|
||||
//! Gelände (Abtrag) bzw. Schüttungen bis zum Gelände (Auftrag), optional mit Bermen.
|
||||
//!
|
||||
//! Neue Geländehöhe am Punkt p: clamp(t(p), b − d·tan β, b + H(d)) mit d = Abstand zum Umriss (innen 0),
|
||||
//! H(d) = Böschungsprofil (Neigung α der nächsten Kante, je `bermHeight` eine Berme der Breite
|
||||
//! `bermWidth`), β = Schüttungswinkel. Innen gilt damit überall die Sohle b; die Ecken der Böschung sind
|
||||
//! Kegel (wie beim Aushub mit dem Bagger).
|
||||
//!
|
||||
//! • Netz: das Gelände wird im Wirkbereich neu trianguliert — Rasterpunkte (exakte neue Höhe), Umriss
|
||||
//! und Böschungsoberkante (Schnitt Böschung/Gelände) als Bruchkanten, ausserhalb das Original-TIN
|
||||
//! samt seinen Kanten. Ergebnis je Gelände-Netz zwischengespeichert ([`site_terrain`]).
|
||||
//! • Mengen: Abtrag/Auftrag als Integral von (t − neu) über ein feines Raster (Mittelpunktregel auf der
|
||||
//! exakten Funktion, nicht auf dem Netz); Hinterfüllung = Abtrag ausserhalb der Gebäude-Grundfläche.
|
||||
//! Jede Baugrube wird gegen das gewachsene Terrain gerechnet.
|
||||
|
||||
use crate::model::{ContextObject, Excavation, Project, TerrainMesh};
|
||||
use crate::terrain::{constrained_tin, datum, isolines, P2, Tin, TinIndex};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::rc::Rc;
|
||||
|
||||
pub const DEFAULT_SLOPE: f64 = 45.0;
|
||||
pub const DEFAULT_FILL_SLOPE: f64 = 33.7;
|
||||
|
||||
fn tan_deg(a: f64) -> f64 {
|
||||
a.clamp(5.0, 89.5).to_radians().tan()
|
||||
}
|
||||
|
||||
/// Baugrube im Höhenbezug des Netzes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ExSpec {
|
||||
/// Umriss gegen den Uhrzeigersinn.
|
||||
pub ring: Vec<P2>,
|
||||
pub bottom: f64,
|
||||
pub cut_tan: Vec<f64>,
|
||||
pub fill_tan: f64,
|
||||
pub berm_w: f64,
|
||||
pub berm_h: f64,
|
||||
}
|
||||
|
||||
fn seg_dist(p: P2, a: P2, b: P2) -> f64 {
|
||||
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
|
||||
let l2 = dx * dx + dy * dy;
|
||||
let t = if l2 > 0.0 { (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(p[0] - a[0] - t * dx).hypot(p[1] - a[1] - t * dy)
|
||||
}
|
||||
|
||||
pub fn point_in_ring(p: P2, r: &[P2]) -> bool {
|
||||
let mut inside = false;
|
||||
let n = r.len();
|
||||
let mut j = n.wrapping_sub(1);
|
||||
for i in 0..n {
|
||||
let (a, b) = (r[i], r[j]);
|
||||
if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] {
|
||||
inside = !inside;
|
||||
}
|
||||
j = i;
|
||||
}
|
||||
inside
|
||||
}
|
||||
|
||||
fn signed_area(r: &[P2]) -> f64 {
|
||||
let n = r.len();
|
||||
(0..n).map(|i| r[i][0] * r[(i + 1) % n][1] - r[(i + 1) % n][0] * r[i][1]).sum::<f64>() / 2.0
|
||||
}
|
||||
|
||||
impl ExSpec {
|
||||
/// Aus dem Modell; `dz` = Höhenbezug des Netzes ([`datum`]). `None` bei kaputtem Umriss.
|
||||
pub fn of(e: &Excavation, dz: f64) -> Option<ExSpec> {
|
||||
let mut ring: Vec<P2> = e.outline.iter().map(|v| [v.x, v.y]).filter(|p| p[0].is_finite() && p[1].is_finite()).collect();
|
||||
ring.dedup_by(|a, b| (a[0] - b[0]).hypot(a[1] - b[1]) < 1e-9);
|
||||
if ring.len() > 2 && (ring[0][0] - ring[ring.len() - 1][0]).hypot(ring[0][1] - ring[ring.len() - 1][1]) < 1e-9 {
|
||||
ring.pop();
|
||||
}
|
||||
if ring.len() < 3 || !e.bottom.is_finite() || signed_area(&ring).abs() < 1e-6 {
|
||||
return None;
|
||||
}
|
||||
let n = ring.len();
|
||||
let slope = e.slope.filter(|s| s.is_finite() && *s > 0.0).unwrap_or(DEFAULT_SLOPE);
|
||||
let mut cut_tan: Vec<f64> = (0..n).map(|i| tan_deg(e.edge_slopes.as_ref().and_then(|v| v.get(i)).copied().filter(|s| s.is_finite() && *s > 0.0).unwrap_or(slope))).collect();
|
||||
if signed_area(&ring) < 0.0 {
|
||||
// Kante i (p_i → p_i+1) wird nach dem Umdrehen Kante n−2−i (mod n).
|
||||
ring.reverse();
|
||||
let old = cut_tan.clone();
|
||||
for i in 0..n {
|
||||
cut_tan[(2 * n - 2 - i) % n] = old[i];
|
||||
}
|
||||
}
|
||||
let bw = e.berm_width.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(0.0);
|
||||
let bh = e.berm_height.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(0.0);
|
||||
Some(ExSpec {
|
||||
ring,
|
||||
bottom: e.bottom + dz,
|
||||
cut_tan,
|
||||
fill_tan: tan_deg(e.fill_slope.filter(|s| s.is_finite() && *s > 0.0).unwrap_or(DEFAULT_FILL_SLOPE)),
|
||||
berm_w: if bh > 0.0 { bw } else { 0.0 },
|
||||
berm_h: if bw > 0.0 { bh } else { 0.0 },
|
||||
})
|
||||
}
|
||||
|
||||
/// Abstand zum Umriss (innen 0) und Index der nächsten Kante.
|
||||
pub fn dist(&self, p: P2) -> (f64, usize) {
|
||||
if point_in_ring(p, &self.ring) {
|
||||
return (0.0, 0);
|
||||
}
|
||||
let n = self.ring.len();
|
||||
(0..n).map(|i| (seg_dist(p, self.ring[i], self.ring[(i + 1) % n]), i)).fold((f64::INFINITY, 0), |a, b| if b.0 < a.0 { b } else { a })
|
||||
}
|
||||
|
||||
/// Böschungsprofil: Höhe über der Sohle im Abstand d bei Neigung tan.
|
||||
fn profile(&self, d: f64, tan: f64) -> f64 {
|
||||
if self.berm_w > 0.0 {
|
||||
let run = self.berm_h / tan;
|
||||
let period = run + self.berm_w;
|
||||
let k = (d / period).floor();
|
||||
k * self.berm_h + (d - k * period).min(run) * tan
|
||||
} else {
|
||||
d * tan
|
||||
}
|
||||
}
|
||||
|
||||
/// Abstand, bei dem das Profil die Höhe h erreicht (Umkehrung von [`profile`]).
|
||||
fn reach(&self, h: f64, tan: f64) -> f64 {
|
||||
if !(h > 0.0) {
|
||||
return 0.0;
|
||||
}
|
||||
if self.berm_w > 0.0 {
|
||||
let k = (h / self.berm_h).floor();
|
||||
k * (self.berm_h / tan + self.berm_w) + (h - k * self.berm_h) / tan
|
||||
} else {
|
||||
h / tan
|
||||
}
|
||||
}
|
||||
|
||||
/// Neue Geländehöhe zur alten Höhe `t` am Punkt p.
|
||||
pub fn apply(&self, t: f64, p: P2) -> f64 {
|
||||
let (d, i) = self.dist(p);
|
||||
let hi = self.bottom + self.profile(d, self.cut_tan[i]);
|
||||
let lo = self.bottom - d * self.fill_tan;
|
||||
t.max(lo).min(hi)
|
||||
}
|
||||
|
||||
fn bbox(&self) -> [f64; 4] {
|
||||
let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
|
||||
for p in &self.ring {
|
||||
b = [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])];
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Wirkbereich: grösster Abstand vom Umriss, in dem das Gelände geändert wird.
|
||||
pub fn reach_in(&self, orig: &Tin, idx: &TinIndex) -> f64 {
|
||||
let b = self.bbox();
|
||||
let min_tan = self.cut_tan.iter().copied().fold(f64::INFINITY, f64::min);
|
||||
let mut r = 0.0;
|
||||
for _ in 0..6 {
|
||||
let (mut lo, mut hi) = (self.bottom, self.bottom);
|
||||
for (p, z) in orig.xy.iter().zip(&orig.z) {
|
||||
if p[0] >= b[0] - r && p[0] <= b[2] + r && p[1] >= b[1] - r && p[1] <= b[3] + r {
|
||||
lo = lo.min(*z);
|
||||
hi = hi.max(*z);
|
||||
}
|
||||
}
|
||||
// Zwischen den Ecken (grosse Dreiecke): Stichproben im Bereich.
|
||||
for j in 0..=24 {
|
||||
for i in 0..=24 {
|
||||
let (x, y) = (b[0] - r + (b[2] - b[0] + 2.0 * r) * i as f64 / 24.0, b[1] - r + (b[3] - b[1] + 2.0 * r) * j as f64 / 24.0);
|
||||
if let Some(z) = idx.z_at(x, y) {
|
||||
lo = lo.min(z);
|
||||
hi = hi.max(z);
|
||||
}
|
||||
}
|
||||
}
|
||||
let nr = self.reach(hi - self.bottom, min_tan).max((self.bottom - lo) / self.fill_tan).min(2000.0);
|
||||
if nr <= r + 1e-6 {
|
||||
return nr;
|
||||
}
|
||||
r = nr;
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// Regelmässiges Raster über einem Rechteck (Knoten).
|
||||
struct Grid {
|
||||
x0: f64,
|
||||
y0: f64,
|
||||
s: f64,
|
||||
nx: usize,
|
||||
ny: usize,
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
fn new(b: [f64; 4], s: f64, max_nodes: usize) -> Grid {
|
||||
let (w, h) = (b[2] - b[0], b[3] - b[1]);
|
||||
let mut s = s;
|
||||
while ((w / s).ceil() + 1.0) * ((h / s).ceil() + 1.0) > max_nodes as f64 {
|
||||
s *= 1.25;
|
||||
}
|
||||
Grid { x0: b[0], y0: b[1], s, nx: (w / s).ceil() as usize + 1, ny: (h / s).ceil() as usize + 1 }
|
||||
}
|
||||
fn at(&self, i: usize, j: usize) -> P2 {
|
||||
[self.x0 + i as f64 * self.s, self.y0 + j as f64 * self.s]
|
||||
}
|
||||
/// TIN des Rasters mit den Werten `v` (NaN = fehlt; Zellen nur mit vier Werten).
|
||||
fn tin(&self, v: &[f64]) -> Tin {
|
||||
let mut t = Tin { xy: Vec::with_capacity(v.len()), z: v.to_vec(), tris: Vec::new() };
|
||||
for j in 0..self.ny {
|
||||
for i in 0..self.nx {
|
||||
t.xy.push(self.at(i, j));
|
||||
}
|
||||
}
|
||||
for j in 0..self.ny.saturating_sub(1) {
|
||||
for i in 0..self.nx.saturating_sub(1) {
|
||||
let k = (j * self.nx + i) as u32;
|
||||
let q = [k, k + 1, k + 1 + self.nx as u32, k + self.nx as u32];
|
||||
if q.iter().all(|&i| v[i as usize].is_finite()) {
|
||||
t.tris.push([q[0], q[1], q[2]]);
|
||||
t.tris.push([q[0], q[2], q[3]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
}
|
||||
|
||||
/// Ergebnis einer Baugrube auf einem Netz.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Excavated {
|
||||
pub tin: Tin,
|
||||
/// Böschungsoberkante (Abtrag) bzw. Böschungsfuss (Auftrag) im Gelände.
|
||||
pub daylight: Vec<Vec<P2>>,
|
||||
pub reach: f64,
|
||||
pub step: f64,
|
||||
}
|
||||
|
||||
/// Wendet eine Baugrube auf ein Netz an. `None`, wenn sie das Netz nicht trifft.
|
||||
pub fn excavate(orig: &Tin, ex: &ExSpec) -> Option<Excavated> {
|
||||
let idx = TinIndex::new(orig);
|
||||
let c = ex.ring.iter().fold([0.0, 0.0], |a, p| [a[0] + p[0], a[1] + p[1]]);
|
||||
let c = [c[0] / ex.ring.len() as f64, c[1] / ex.ring.len() as f64];
|
||||
if idx.z_at(c[0], c[1]).is_none() && ex.ring.iter().all(|p| idx.z_at(p[0], p[1]).is_none()) {
|
||||
return None;
|
||||
}
|
||||
let r = ex.reach_in(orig, &idx);
|
||||
let b = ex.bbox();
|
||||
let s0 = (((b[2] - b[0] + 2.0 * r) * (b[3] - b[1] + 2.0 * r)).sqrt() / 120.0).clamp(0.15, 2.0);
|
||||
let reg = [b[0] - r - s0, b[1] - r - s0, b[2] + r + s0, b[3] + r + s0];
|
||||
let g = Grid::new(reg, s0, 250_000);
|
||||
let s = g.s;
|
||||
let mut t_val = vec![f64::NAN; g.nx * g.ny];
|
||||
let mut d_val = vec![f64::INFINITY; g.nx * g.ny];
|
||||
let (mut cut_phi, mut fill_phi) = (vec![f64::NAN; g.nx * g.ny], vec![f64::NAN; g.nx * g.ny]);
|
||||
for j in 0..g.ny {
|
||||
for i in 0..g.nx {
|
||||
let p = g.at(i, j);
|
||||
let k = j * g.nx + i;
|
||||
let Some(t) = idx.z_at(p[0], p[1]) else { continue };
|
||||
let (d, e) = ex.dist(p);
|
||||
t_val[k] = t;
|
||||
d_val[k] = d;
|
||||
cut_phi[k] = t - (ex.bottom + ex.profile(d, ex.cut_tan[e]));
|
||||
fill_phi[k] = (ex.bottom - d * ex.fill_tan) - t;
|
||||
}
|
||||
}
|
||||
let mut pts: Vec<[f64; 3]> = Vec::new();
|
||||
let mut cons: Vec<(u32, u32)> = Vec::new();
|
||||
let chain = |line: &[P2], z: &dyn Fn(P2) -> Option<f64>, pts: &mut Vec<[f64; 3]>, cons: &mut Vec<(u32, u32)>| {
|
||||
let mut prev: Option<u32> = None;
|
||||
for &p in line {
|
||||
match z(p) {
|
||||
Some(h) => {
|
||||
pts.push([p[0], p[1], h]);
|
||||
let k = pts.len() as u32 - 1;
|
||||
if let Some(q) = prev {
|
||||
cons.push((q, k));
|
||||
}
|
||||
prev = Some(k);
|
||||
}
|
||||
None => prev = None,
|
||||
}
|
||||
}
|
||||
};
|
||||
// 1. Umriss der Sohle, verdichtet.
|
||||
let n = ex.ring.len();
|
||||
let mut ring_pts: Vec<P2> = Vec::new();
|
||||
for i in 0..n {
|
||||
let (a, q) = (ex.ring[i], ex.ring[(i + 1) % n]);
|
||||
let steps = ((a[0] - q[0]).hypot(a[1] - q[1]) / s).ceil().max(1.0) as usize;
|
||||
for k in 0..steps {
|
||||
let f = k as f64 / steps as f64;
|
||||
ring_pts.push([a[0] + (q[0] - a[0]) * f, a[1] + (q[1] - a[1]) * f]);
|
||||
}
|
||||
}
|
||||
ring_pts.push(ring_pts[0]);
|
||||
let bottom = ex.bottom;
|
||||
chain(&ring_pts, &|p| idx.z_at(p[0], p[1]).map(|t| ex.apply(t, p).min(bottom).max(bottom)), &mut pts, &mut cons);
|
||||
// 2. Böschungsoberkante / -fuss: Nullinien von t − hi bzw. lo − t ausserhalb des Umrisses.
|
||||
let mut daylight = Vec::new();
|
||||
for phi in [&cut_phi, &fill_phi] {
|
||||
let gt = g.tin(phi);
|
||||
for l in isolines(>, 1e12, 0.0) {
|
||||
let mut part: Vec<P2> = Vec::new();
|
||||
let flush = |part: &mut Vec<P2>, daylight: &mut Vec<Vec<P2>>| {
|
||||
if part.len() >= 2 {
|
||||
daylight.push(std::mem::take(part));
|
||||
} else {
|
||||
part.clear();
|
||||
}
|
||||
};
|
||||
let mut pl = l.pts.clone();
|
||||
if l.closed {
|
||||
pl.push(pl[0]);
|
||||
}
|
||||
for p in pl {
|
||||
if ex.dist(p).0 > 1e-6 {
|
||||
part.push(p);
|
||||
} else {
|
||||
flush(&mut part, &mut daylight);
|
||||
}
|
||||
}
|
||||
flush(&mut part, &mut daylight);
|
||||
}
|
||||
}
|
||||
for l in &daylight {
|
||||
chain(l, &|p| idx.z_at(p[0], p[1]), &mut pts, &mut cons);
|
||||
}
|
||||
// 3. Rasterpunkte im Wirkbereich.
|
||||
for j in 0..g.ny {
|
||||
for i in 0..g.nx {
|
||||
let k = j * g.nx + i;
|
||||
if t_val[k].is_finite() && d_val[k] <= r + s {
|
||||
let p = g.at(i, j);
|
||||
pts.push([p[0], p[1], ex.apply(t_val[k], p)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 4. Original ausserhalb samt Kanten.
|
||||
let mut keep = vec![u32::MAX; orig.xy.len()];
|
||||
for (i, p) in orig.xy.iter().enumerate() {
|
||||
if ex.dist(*p).0 > r + 1.5 * s {
|
||||
keep[i] = pts.len() as u32;
|
||||
pts.push([p[0], p[1], orig.z[i]]);
|
||||
}
|
||||
}
|
||||
let mut seen: HashSet<(u32, u32)> = HashSet::new();
|
||||
for tr in &orig.tris {
|
||||
for k in 0..3 {
|
||||
let (a, b) = (keep[tr[k] as usize], keep[tr[(k + 1) % 3] as usize]);
|
||||
if a != u32::MAX && b != u32::MAX && seen.insert((a.min(b), a.max(b))) {
|
||||
cons.push((a, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (mut tin, _) = constrained_tin(&pts, &cons, 0.3 * s, 0.0);
|
||||
// Dreiecke ausserhalb des Original-Netzes (konkave Ränder) weg.
|
||||
let xy = tin.xy.clone();
|
||||
tin.tris.retain(|tr| {
|
||||
let c = tr.iter().fold([0.0, 0.0], |a, &i| [a[0] + xy[i as usize][0] / 3.0, a[1] + xy[i as usize][1] / 3.0]);
|
||||
idx.z_at(c[0], c[1]).is_some()
|
||||
});
|
||||
Some(Excavated { tin, daylight, reach: r, step: s })
|
||||
}
|
||||
|
||||
// ── Mengen ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Abtrag, Auftrag, Hinterfüllung (m³) und Sohlenfläche (m²).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Volumes {
|
||||
pub cut: f64,
|
||||
pub fill: f64,
|
||||
pub backfill: f64,
|
||||
pub bottom_area: f64,
|
||||
}
|
||||
|
||||
/// Integriert (t − neu) über ein Raster der Weite ≤ `h` (Mittelpunkte, höchstens ~1.5 Mio. Proben).
|
||||
/// `footprint`: Gebäude-Grundfläche (Ringe); Abtrag darin zählt nicht zur Hinterfüllung.
|
||||
pub fn volumes(orig: &Tin, ex: &ExSpec, h: f64, footprint: &[Vec<P2>]) -> Volumes {
|
||||
let idx = TinIndex::new(orig);
|
||||
let r = ex.reach_in(orig, &idx);
|
||||
let b = ex.bbox();
|
||||
let reg = [b[0] - r, b[1] - r, b[2] + r, b[3] + r];
|
||||
let (w, hh) = (reg[2] - reg[0], reg[3] - reg[1]);
|
||||
let mut h = h.max(1e-3);
|
||||
while (w / h).ceil() * (hh / h).ceil() > 1.5e6 {
|
||||
h *= 1.2;
|
||||
}
|
||||
let (nx, ny) = ((w / h).ceil() as usize, (hh / h).ceil() as usize);
|
||||
let (hx, hy) = (w / nx as f64, hh / ny as f64);
|
||||
let cell = hx * hy;
|
||||
let mut v = Volumes { bottom_area: signed_area(&ex.ring).abs(), ..Default::default() };
|
||||
for j in 0..ny {
|
||||
for i in 0..nx {
|
||||
let p = [reg[0] + (i as f64 + 0.5) * hx, reg[1] + (j as f64 + 0.5) * hy];
|
||||
let Some(t) = idx.z_at(p[0], p[1]) else { continue };
|
||||
let dz = t - ex.apply(t, p);
|
||||
if dz > 0.0 {
|
||||
v.cut += dz * cell;
|
||||
if !footprint.iter().any(|f| point_in_ring(p, f)) {
|
||||
v.backfill += dz * cell;
|
||||
}
|
||||
} else {
|
||||
v.fill -= dz * cell;
|
||||
}
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
// ── Gelände mit Baugruben, zwischengespeichert ──────────────────────────────
|
||||
|
||||
/// Gelände-Netz samt angewandten Baugruben (Höhen roh, Modell = roh − `datum`).
|
||||
#[derive(Debug)]
|
||||
pub struct SiteTerrain {
|
||||
pub datum: f64,
|
||||
pub orig: Tin,
|
||||
/// Gelände nach allen Baugruben; `None`, wenn keine das Netz trifft.
|
||||
pub modified: Option<Tin>,
|
||||
/// (Baugrube, Spezifikation, Böschungsoberkante)
|
||||
pub items: Vec<(String, ExSpec, Vec<Vec<P2>>)>,
|
||||
}
|
||||
|
||||
impl SiteTerrain {
|
||||
pub fn current(&self) -> &Tin {
|
||||
self.modified.as_ref().unwrap_or(&self.orig)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn excavations(p: &Project) -> Vec<&Excavation> {
|
||||
p.context.as_deref().unwrap_or(&[]).iter().filter_map(|c| if let ContextObject::Excavation(e) = c { Some(e) } else { None }).collect()
|
||||
}
|
||||
|
||||
pub fn terrains(p: &Project) -> Vec<&TerrainMesh> {
|
||||
p.context.as_deref().unwrap_or(&[]).iter().filter_map(|c| if let ContextObject::TerrainMesh(t) = c { Some(t) } else { None }).collect()
|
||||
}
|
||||
|
||||
type Cache = Vec<(u64, Rc<SiteTerrain>)>;
|
||||
thread_local! {
|
||||
static CACHE: RefCell<Cache> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
fn hash_of(p: &Project, t: &TerrainMesh, ex: &[&Excavation]) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
for v in t.positions.iter().chain(&t.indices) {
|
||||
v.to_bits().hash(&mut h);
|
||||
}
|
||||
p.reference_elevation_masl.map(f64::to_bits).hash(&mut h);
|
||||
for e in ex {
|
||||
serde_json::to_string(e).unwrap_or_default().hash(&mut h);
|
||||
}
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Gelände-Netz `t` mit allen Baugruben des Projekts (zwischengespeichert, Schlüssel = Inhalt).
|
||||
pub fn site_terrain(p: &Project, t: &TerrainMesh) -> Rc<SiteTerrain> {
|
||||
let ex = excavations(p);
|
||||
let key = hash_of(p, t, &ex);
|
||||
if let Some(hit) = CACHE.with(|c| c.borrow().iter().find(|(k, _)| *k == key).map(|(_, v)| v.clone())) {
|
||||
return hit;
|
||||
}
|
||||
let orig = Tin::from_flat(&t.positions, &t.indices);
|
||||
let dz = datum(p.reference_elevation_masl, &orig.z);
|
||||
let mut cur: Option<Tin> = None;
|
||||
let mut items = Vec::new();
|
||||
for e in ex {
|
||||
let Some(spec) = ExSpec::of(e, dz) else { continue };
|
||||
let base = cur.as_ref().unwrap_or(&orig);
|
||||
if let Some(r) = excavate(base, &spec) {
|
||||
items.push((e.id.clone(), spec, r.daylight));
|
||||
cur = Some(r.tin);
|
||||
}
|
||||
}
|
||||
let st = Rc::new(SiteTerrain { datum: dz, orig, modified: cur, items });
|
||||
CACHE.with(|c| {
|
||||
let mut c = c.borrow_mut();
|
||||
c.insert(0, (key, st.clone()));
|
||||
c.truncate(4);
|
||||
});
|
||||
st
|
||||
}
|
||||
|
||||
/// Gelände-Netz im Modellbezug samt Baugruben (flach: Positionen, Indizes) und ob es geändert wurde.
|
||||
/// Ohne Baugrube und ohne Höhenbezug das Original (ohne Kopie).
|
||||
pub fn terrain_model_mesh<'a>(p: &Project, t: &'a TerrainMesh) -> (std::borrow::Cow<'a, [f64]>, std::borrow::Cow<'a, [f64]>, bool) {
|
||||
use std::borrow::Cow;
|
||||
let st = site_terrain(p, t);
|
||||
if st.modified.is_none() && st.datum == 0.0 {
|
||||
return (Cow::Borrowed(&t.positions), Cow::Borrowed(&t.indices), false);
|
||||
}
|
||||
let (pos, idx) = st.current().to_flat(-st.datum);
|
||||
(Cow::Owned(pos), Cow::Owned(idx), st.modified.is_some())
|
||||
}
|
||||
|
||||
/// Mengen je Baugrube (gegen das gewachsene Terrain des ersten Netzes, das sie trifft).
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExQty {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub bottom: f64,
|
||||
pub bottom_area: f64,
|
||||
pub cut: f64,
|
||||
pub fill: f64,
|
||||
pub backfill: f64,
|
||||
}
|
||||
|
||||
pub fn quantities(p: &Project) -> Vec<ExQty> {
|
||||
let fp: Vec<Vec<P2>> = crate::site_rules::building_footprint(p).iter().flat_map(|poly| poly.first().map(|r| r.iter().map(|v| [v.x, v.y]).collect::<Vec<P2>>())).collect();
|
||||
let mut out = Vec::new();
|
||||
for e in excavations(p) {
|
||||
for t in terrains(p) {
|
||||
let st = site_terrain(p, t);
|
||||
let Some((_, spec, _)) = st.items.iter().find(|(id, ..)| *id == e.id) else { continue };
|
||||
let h = (spec.ring.iter().map(|q| q[0]).fold(f64::NEG_INFINITY, f64::max) - spec.ring.iter().map(|q| q[0]).fold(f64::INFINITY, f64::min)).max(1.0) / 400.0;
|
||||
let v = volumes(&st.orig, spec, h.clamp(0.02, 0.5), &fp);
|
||||
out.push(ExQty { id: e.id.clone(), name: e.name.clone(), bottom: e.bottom, bottom_area: v.bottom_area, cut: v.cut, fill: v.fill, backfill: v.backfill });
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Höhe des gewachsenen (`designed = false`) bzw. gestalteten Terrains im Modellbezug; `None` ohne Gelände.
|
||||
pub fn terrain_z(p: &Project, x: f64, y: f64, designed: bool) -> Option<f64> {
|
||||
for t in terrains(p) {
|
||||
let st = site_terrain(p, t);
|
||||
let tin = if designed { st.current() } else { &st.orig };
|
||||
if let Some(z) = TinIndex::new(tin).z_at(x, y) {
|
||||
return Some(z - st.datum);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// ── Grundriss: Böschungsschraffur ────────────────────────────────────────────
|
||||
|
||||
/// Böschungsschraffur: Striche von der Oberkante zur Unterkante, abwechselnd lang und halb, im Abstand
|
||||
/// `spacing` entlang des Umrisses (an konvexen Ecken gefächert). `t` = Gelände vor dieser Baugrube.
|
||||
pub fn slope_hatch(t: &Tin, ex: &ExSpec, spacing: f64) -> Vec<(P2, P2)> {
|
||||
let idx = TinIndex::new(t);
|
||||
let r = ex.reach_in(t, &idx).max(spacing);
|
||||
let step = (spacing / 4.0).max(0.02);
|
||||
// Länge des geänderten Bereichs entlang des Strahls q + n·L; Vorzeichen: Abtrag (true) / Auftrag.
|
||||
let ray = |q: P2, n: P2| -> Option<(f64, bool)> {
|
||||
let mut last: Option<(f64, bool)> = None;
|
||||
let mut l = step / 2.0;
|
||||
while l <= r + step {
|
||||
let p = [q[0] + n[0] * l, q[1] + n[1] * l];
|
||||
let tz = idx.z_at(p[0], p[1])?;
|
||||
let dz = tz - ex.apply(tz, p);
|
||||
if dz.abs() < 1e-6 {
|
||||
break;
|
||||
}
|
||||
last = Some((l, dz > 0.0));
|
||||
l += step;
|
||||
}
|
||||
last
|
||||
};
|
||||
let n = ex.ring.len();
|
||||
let normal = |i: usize| {
|
||||
let (a, b) = (ex.ring[i], ex.ring[(i + 1) % n]);
|
||||
let l = (b[0] - a[0]).hypot(b[1] - a[1]).max(1e-12);
|
||||
[(b[1] - a[1]) / l, -(b[0] - a[0]) / l]
|
||||
};
|
||||
let mut rays: Vec<(P2, P2)> = Vec::new();
|
||||
for i in 0..n {
|
||||
let (a, b) = (ex.ring[i], ex.ring[(i + 1) % n]);
|
||||
let len = (b[0] - a[0]).hypot(b[1] - a[1]);
|
||||
let nn = normal(i);
|
||||
let k = (len / spacing).floor() as usize;
|
||||
let off = (len - k as f64 * spacing) / 2.0;
|
||||
for s in 0..=k {
|
||||
let f = (off + s as f64 * spacing) / len.max(1e-12);
|
||||
if f <= 1e-9 || f >= 1.0 - 1e-9 {
|
||||
continue;
|
||||
}
|
||||
rays.push(([a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f], nn));
|
||||
}
|
||||
// Fächer an der konvexen Ecke b.
|
||||
let n2 = normal((i + 1) % n);
|
||||
let cross = nn[0] * n2[1] - nn[1] * n2[0];
|
||||
if cross > 1e-9 {
|
||||
let a0 = nn[1].atan2(nn[0]);
|
||||
let mut a1 = n2[1].atan2(n2[0]);
|
||||
if a1 < a0 {
|
||||
a1 += std::f64::consts::TAU;
|
||||
}
|
||||
let mid = [((a0 + a1) / 2.0).cos(), ((a0 + a1) / 2.0).sin()];
|
||||
let lm = ray(b, mid).map_or(0.0, |r| r.0);
|
||||
let m = ((a1 - a0) * lm / spacing).floor() as usize;
|
||||
for s in 0..=m {
|
||||
let ang = a0 + (a1 - a0) * s as f64 / m.max(1) as f64;
|
||||
rays.push((b, [ang.cos(), ang.sin()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for (k, (q, nn)) in rays.into_iter().enumerate() {
|
||||
let Some((l, cut)) = ray(q, nn) else { continue };
|
||||
let far = [q[0] + nn[0] * l, q[1] + nn[1] * l];
|
||||
let (top, bot) = if cut { (far, q) } else { (q, far) };
|
||||
let f = if k % 2 == 0 { 1.0 } else { 0.5 };
|
||||
out.push((top, [top[0] + (bot[0] - top[0]) * f, top[1] + (bot[1] - top[1]) * f]));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Gelände vor der Baugrube `id` (für die Schraffur); `None`, wenn sie das Netz nicht trifft.
|
||||
pub fn terrain_before(st: &SiteTerrain, id: &str) -> Option<Tin> {
|
||||
let pos = st.items.iter().position(|(i, ..)| i == id)?;
|
||||
if pos == 0 {
|
||||
return Some(st.orig.clone());
|
||||
}
|
||||
let mut cur = st.orig.clone();
|
||||
for (_, spec, _) in &st.items[..pos] {
|
||||
cur = excavate(&cur, spec)?.tin;
|
||||
}
|
||||
Some(cur)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::Vec2;
|
||||
use crate::terrain::{mesh_volume, prism, watertight};
|
||||
|
||||
fn flat(z: f64, half: f64) -> Tin {
|
||||
Tin { xy: vec![[-half, -half], [half, -half], [half, half], [-half, half]], z: vec![z; 4], tris: vec![[0, 1, 2], [0, 2, 3]] }
|
||||
}
|
||||
|
||||
fn square(e: f64, bottom: f64) -> Excavation {
|
||||
Excavation {
|
||||
id: "bg".into(),
|
||||
outline: vec![Vec2 { x: -e, y: -e }, Vec2 { x: e, y: -e }, Vec2 { x: e, y: e }, Vec2 { x: -e, y: e }],
|
||||
bottom,
|
||||
slope: Some(45.0),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aushub_wie_analytisch() {
|
||||
// 10 × 10 m, 3 m tief, 45°: V = A·h + U·h²/(2 tan α) + π h³/(3 tan² α).
|
||||
let ex = ExSpec::of(&square(5.0, -3.0), 0.0).unwrap();
|
||||
let t = flat(0.0, 50.0);
|
||||
let exact = 100.0 * 3.0 + 40.0 * 9.0 / 2.0 + std::f64::consts::PI * 27.0 / 3.0;
|
||||
let v = volumes(&t, &ex, 0.02, &[]);
|
||||
assert!((v.cut - exact).abs() < 2e-3 * exact, "{} vs {exact}", v.cut);
|
||||
assert!(v.fill.abs() < 1e-9 && (v.bottom_area - 100.0).abs() < 1e-9);
|
||||
// Hinterfüllung: ohne Gebäude = Abtrag; mit Gebäude 10 × 10 = Abtrag − 300.
|
||||
assert!((v.backfill - v.cut).abs() < 1e-9);
|
||||
let fp = vec![vec![[-5.0, -5.0], [5.0, -5.0], [5.0, 5.0], [-5.0, 5.0]]];
|
||||
let v2 = volumes(&t, &ex, 0.02, &fp);
|
||||
assert!((v.cut - v2.backfill - 300.0).abs() < 1.0, "{}", v2.backfill);
|
||||
// Netz: dicht als Prisma, Volumen-Differenz ≈ Aushub.
|
||||
let r = excavate(&t, &ex).unwrap();
|
||||
let (v0, f0) = prism(&t, -10.0);
|
||||
let (v1, f1) = prism(&r.tin, -10.0);
|
||||
assert!(watertight(&f1));
|
||||
let dv = mesh_volume(&v0, &f0) - mesh_volume(&v1, &f1);
|
||||
assert!((dv - exact).abs() < 0.02 * exact, "{dv} vs {exact}");
|
||||
// Sohle und Böschungsoberkante: Oberkante als geschlossener Ring bei d = 3.
|
||||
let z = TinIndex::new(&r.tin).z_at(0.0, 0.0).unwrap();
|
||||
assert!((z + 3.0).abs() < 1e-9);
|
||||
assert!(!r.daylight.is_empty());
|
||||
for l in &r.daylight {
|
||||
for q in l {
|
||||
assert!((ex.dist(*q).0 - 3.0).abs() < 0.1, "{q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auftrag_am_hang_und_bermen() {
|
||||
// Hang 10 %: Plattform auf ±0 schneidet bergseits ein und wird talseits geschüttet.
|
||||
let t = Tin { xy: vec![[-50.0, -50.0], [50.0, -50.0], [50.0, 50.0], [-50.0, 50.0]], z: vec![-5.0, -5.0, 5.0, 5.0], tris: vec![[0, 1, 2], [0, 2, 3]] };
|
||||
let ex = ExSpec::of(&square(5.0, 0.0), 0.0).unwrap();
|
||||
let v = volumes(&t, &ex, 0.05, &[]);
|
||||
assert!(v.cut > 10.0 && v.fill > 10.0, "{v:?}");
|
||||
// Bermen verlängern die Böschung: mehr Aushub als ohne.
|
||||
let mut e = square(5.0, -6.0);
|
||||
let base = volumes(&flat(0.0, 60.0), &ExSpec::of(&e, 0.0).unwrap(), 0.05, &[]).cut;
|
||||
e.berm_width = Some(1.0);
|
||||
e.berm_height = Some(2.0);
|
||||
let sp = ExSpec::of(&e, 0.0).unwrap();
|
||||
assert!((sp.profile(2.0, 1.0) - 2.0).abs() < 1e-12 && (sp.profile(2.5, 1.0) - 2.0).abs() < 1e-12 && (sp.profile(3.5, 1.0) - 2.5).abs() < 1e-12);
|
||||
assert!((sp.reach(2.5, 1.0) - 3.5).abs() < 1e-12);
|
||||
assert!(volumes(&flat(0.0, 60.0), &sp, 0.05, &[]).cut > base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schraffur_und_unsinn() {
|
||||
let t = flat(0.0, 50.0);
|
||||
let mut e = square(5.0, -3.0);
|
||||
// Umlaufsinn im Uhrzeigersinn: Kantenneigungen wandern mit.
|
||||
e.outline.reverse();
|
||||
e.edge_slopes = Some(vec![60.0, 45.0, 45.0, 45.0]);
|
||||
let ex = ExSpec::of(&e, 0.0).unwrap();
|
||||
// Kante 0 war (−5,5)→(5,5) (oben); dort steiler: Böschung kürzer.
|
||||
let h = slope_hatch(&t, &ex, 0.5);
|
||||
assert!(h.len() > 40);
|
||||
let top: Vec<_> = h.iter().filter(|(a, _)| a[1] > 5.0 + 1e-6 && a[0].abs() < 4.0).collect();
|
||||
assert!(!top.is_empty() && top.iter().all(|(a, _)| a[1] < 5.0 + 3.0 / 60f64.to_radians().tan() + 0.2));
|
||||
assert!(ExSpec::of(&Excavation { outline: vec![Vec2 { x: 0.0, y: 0.0 }], ..Default::default() }, 0.0).is_none());
|
||||
assert!(ExSpec::of(&Excavation { bottom: f64::NAN, ..square(1.0, 0.0) }, 0.0).is_none());
|
||||
// Ausserhalb des Netzes: nichts.
|
||||
let far = ExSpec::of(&Excavation { outline: square(1.0, 0.0).outline.iter().map(|v| Vec2 { x: v.x + 500.0, y: v.y }).collect(), ..square(1.0, 0.0) }, 0.0).unwrap();
|
||||
assert!(excavate(&t, &far).is_none());
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ fn shift_geom(g: &mut Drawing2DGeom, dx: f64, dy: f64) {
|
||||
*max = shift(*max, dx, dy);
|
||||
}
|
||||
Circle { center, .. } | Arc { center, .. } | Ellipse { center, .. } => *center = shift(*center, dx, dy),
|
||||
Kote { at, .. } | Detailref { at, .. } | Scalebar { at, .. } | Pointmarker { at } | Block { at, .. } => *at = shift(*at, dx, dy),
|
||||
Grid { origin: at, .. } | Kote { at, .. } | Detailref { at, .. } | Scalebar { at, .. } | Pointmarker { at } | Block { at, .. } => *at = shift(*at, dx, dy),
|
||||
Text { at, leader_target, leader_bend_points, path_pts, .. } => {
|
||||
*at = shift(*at, dx, dy);
|
||||
if let Some(t) = leader_target {
|
||||
@@ -63,6 +63,7 @@ fn shift_context(o: &mut ContextObject, dx: f64, dy: f64) {
|
||||
}
|
||||
ContextObject::ImportedMesh(m) => shift_positions(&mut m.positions, dx, dy),
|
||||
ContextObject::TerrainMesh(m) => shift_positions(&mut m.positions, dx, dy),
|
||||
ContextObject::Excavation(e) => shift_all(&mut e.outline, dx, dy),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,7 @@ fn shift_geom(g: &Value, dx: f64, dy: f64) -> Value {
|
||||
"rect" | "image" => shift_pts_fields(&mut m, &["min", "max"], dx, dy, &[]),
|
||||
"circle" | "arc" | "ellipse" => shift_pts_fields(&mut m, &["center"], dx, dy, &[]),
|
||||
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" => shift_pts_fields(&mut m, &["at"], dx, dy, &[]),
|
||||
"grid" => shift_pts_fields(&mut m, &["origin"], dx, dy, &[]),
|
||||
"text" => {
|
||||
shift_pts_fields(&mut m, &["at"], dx, dy, &[]);
|
||||
if truthy(g.get("leaderTarget")) {
|
||||
|
||||
@@ -0,0 +1,466 @@
|
||||
//! Achsraster ([112]): Geometrie der Rasterachsen, Achsblasen, Fangpunkte und Schnitt-/Ansichtslinien.
|
||||
//!
|
||||
//! Das Raster ist eine 2D-Zeichnung (`Drawing2DGeom::Grid`, Auswahl/Verschieben/Kopieren/Ebenen wie
|
||||
//! jede Zeichnung). Rechtwinklig: `a` = Achsen parallel zur lokalen Y-Achse (X = `pos`), `b` = Achsen
|
||||
//! parallel zur lokalen X-Achse (Y = `pos`). Radial: `a` = Strahlen (`pos` = Grad gegen `angle`),
|
||||
//! `b` = Ringe (`pos` = Radius). Die Achsen tragen fortlaufende Indizes: erst `a`, dann `b`.
|
||||
|
||||
use crate::model::{Drawing2D, Drawing2DGeom, GridAxis, GridBubbles};
|
||||
|
||||
pub type P = (f64, f64);
|
||||
|
||||
/// Überstand der Achsen über die äusserste Querachse (Meter).
|
||||
pub const DEFAULT_EXTEND: f64 = 1.5;
|
||||
/// Blasen-Durchmesser (Papier-mm).
|
||||
pub const DEFAULT_BUBBLE_MM: f64 = 8.0;
|
||||
|
||||
/// Verlauf einer Achse: Strecke oder Kreisbogen (gegen den Uhrzeigersinn von `a0` nach `a1`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Shape {
|
||||
Line { a: P, b: P },
|
||||
Arc { c: P, r: f64, a0: f64, a1: f64 },
|
||||
}
|
||||
|
||||
/// Eine Rasterachse.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Axis {
|
||||
pub index: u32,
|
||||
pub label: String,
|
||||
pub shape: Shape,
|
||||
/// Blasen an Anfang/Ende: Endpunkt der Achse und Richtung nach aussen.
|
||||
pub bubbles: [Option<(P, P)>; 2],
|
||||
}
|
||||
|
||||
/// Parameter eines Rasters.
|
||||
pub struct Spec<'a> {
|
||||
pub origin: P,
|
||||
pub angle: f64,
|
||||
pub radial: bool,
|
||||
pub a: &'a [GridAxis],
|
||||
pub b: &'a [GridAxis],
|
||||
pub extend: f64,
|
||||
pub bubbles: GridBubbles,
|
||||
}
|
||||
|
||||
impl<'a> Spec<'a> {
|
||||
/// Raster einer Zeichnung (`None`, wenn sie keines ist).
|
||||
pub fn of(g: &'a Drawing2DGeom) -> Option<Spec<'a>> {
|
||||
let Drawing2DGeom::Grid { origin, angle, radial, a, b, extend, bubbles, .. } = g else { return None };
|
||||
Some(Spec {
|
||||
origin: (origin.x, origin.y),
|
||||
angle: *angle,
|
||||
radial: *radial == Some(true),
|
||||
a,
|
||||
b,
|
||||
extend: extend.filter(|e| e.is_finite() && *e >= 0.0).unwrap_or(DEFAULT_EXTEND),
|
||||
bubbles: bubbles.unwrap_or(GridBubbles::Both),
|
||||
})
|
||||
}
|
||||
|
||||
fn world(&self, x: f64, y: f64) -> P {
|
||||
let (s, c) = self.angle.sin_cos();
|
||||
(self.origin.0 + x * c - y * s, self.origin.1 + x * s + y * c)
|
||||
}
|
||||
|
||||
fn dir(&self, x: f64, y: f64) -> P {
|
||||
let (s, c) = self.angle.sin_cos();
|
||||
(x * c - y * s, x * s + y * c)
|
||||
}
|
||||
|
||||
fn span(list: &[GridAxis]) -> (f64, f64) {
|
||||
let it = list.iter().map(|g| g.pos).filter(|p| p.is_finite());
|
||||
let lo = it.clone().fold(f64::INFINITY, f64::min);
|
||||
let hi = it.fold(f64::NEG_INFINITY, f64::max);
|
||||
if lo > hi {
|
||||
(0.0, 0.0)
|
||||
} else {
|
||||
(lo, hi)
|
||||
}
|
||||
}
|
||||
|
||||
fn ray_angle(&self, pos: f64) -> f64 {
|
||||
self.angle + pos.to_radians()
|
||||
}
|
||||
|
||||
/// Alle Achsen (Index: `a` zuerst, dann `b`).
|
||||
pub fn axes(&self) -> Vec<Axis> {
|
||||
let want = |start: bool| match self.bubbles {
|
||||
GridBubbles::Both => true,
|
||||
GridBubbles::Start => start,
|
||||
GridBubbles::End => !start,
|
||||
};
|
||||
let mut out = Vec::with_capacity(self.a.len() + self.b.len());
|
||||
let ext = self.extend;
|
||||
if !self.radial {
|
||||
let (y0, y1) = Self::span(self.b);
|
||||
let (x0, x1) = Self::span(self.a);
|
||||
for (i, g) in self.a.iter().enumerate() {
|
||||
let (p0, p1) = (self.world(g.pos, y0 - ext), self.world(g.pos, y1 + ext));
|
||||
let (d0, d1) = (self.dir(0.0, -1.0), self.dir(0.0, 1.0));
|
||||
out.push(Axis {
|
||||
index: i as u32,
|
||||
label: g.label.clone(),
|
||||
shape: Shape::Line { a: p0, b: p1 },
|
||||
bubbles: [want(true).then_some((p0, d0)), want(false).then_some((p1, d1))],
|
||||
});
|
||||
}
|
||||
for (j, g) in self.b.iter().enumerate() {
|
||||
let (p0, p1) = (self.world(x0 - ext, g.pos), self.world(x1 + ext, g.pos));
|
||||
let (d0, d1) = (self.dir(-1.0, 0.0), self.dir(1.0, 0.0));
|
||||
out.push(Axis {
|
||||
index: (self.a.len() + j) as u32,
|
||||
label: g.label.clone(),
|
||||
shape: Shape::Line { a: p0, b: p1 },
|
||||
bubbles: [want(true).then_some((p0, d0)), want(false).then_some((p1, d1))],
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// Radial: Strahlen vom Mittelpunkt bis zum grössten Ring + Überstand, Ringe zwischen den Strahlen.
|
||||
let (_, rmax) = Self::span(self.b);
|
||||
for (i, g) in self.a.iter().enumerate() {
|
||||
let th = self.ray_angle(g.pos);
|
||||
let u = (th.cos(), th.sin());
|
||||
let end = (self.origin.0 + u.0 * (rmax + ext), self.origin.1 + u.1 * (rmax + ext));
|
||||
out.push(Axis {
|
||||
index: i as u32,
|
||||
label: g.label.clone(),
|
||||
shape: Shape::Line { a: self.origin, b: end },
|
||||
bubbles: [None, (self.bubbles != GridBubbles::Start).then_some((end, u))],
|
||||
});
|
||||
}
|
||||
let (t0, t1) = Self::span(self.a);
|
||||
let (t0, t1) = (self.ray_angle(t0), self.ray_angle(t1));
|
||||
for (j, g) in self.b.iter().enumerate() {
|
||||
let r = g.pos;
|
||||
let full = self.a.len() < 2 || t1 - t0 >= std::f64::consts::TAU - 1e-9 || r <= 1e-9;
|
||||
let (a0, a1) = if full {
|
||||
(self.angle, self.angle + std::f64::consts::TAU)
|
||||
} else {
|
||||
let da = (ext / r).min((std::f64::consts::TAU - (t1 - t0)) / 2.0);
|
||||
(t0 - da, t1 + da)
|
||||
};
|
||||
let at = |t: f64| (self.origin.0 + r * t.cos(), self.origin.1 + r * t.sin());
|
||||
let tan = |t: f64, s: f64| (-t.sin() * s, t.cos() * s);
|
||||
out.push(Axis {
|
||||
index: (self.a.len() + j) as u32,
|
||||
label: g.label.clone(),
|
||||
shape: Shape::Arc { c: self.origin, r, a0, a1 },
|
||||
bubbles: [
|
||||
(!full && want(true)).then(|| (at(a0), tan(a0, -1.0))),
|
||||
(if full { self.bubbles != GridBubbles::Start } else { want(false) }).then(|| (at(a1), tan(a1, 1.0))),
|
||||
],
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Schnittpunkte der Achsen: rechtwinklig `a` × `b`, radial Strahl × Ring.
|
||||
pub fn crossings(&self) -> Vec<P> {
|
||||
let mut out = Vec::new();
|
||||
for i in 0..self.a.len() {
|
||||
for j in 0..self.b.len() {
|
||||
if let Some(p) = self.cross(i as u32, (self.a.len() + j) as u32) {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Schnittpunkt zweier Achsen (Reihenfolge egal); gleiche Familie → `None`.
|
||||
pub fn cross(&self, i: u32, j: u32) -> Option<P> {
|
||||
let na = self.a.len() as u32;
|
||||
let (i, j) = if i < na && j >= na { (i, j) } else if j < na && i >= na { (j, i) } else { return None };
|
||||
let (ga, gb) = (self.a.get(i as usize)?, self.b.get((j - na) as usize)?);
|
||||
let p = if self.radial {
|
||||
let th = self.ray_angle(ga.pos);
|
||||
(self.origin.0 + gb.pos * th.cos(), self.origin.1 + gb.pos * th.sin())
|
||||
} else {
|
||||
self.world(ga.pos, gb.pos)
|
||||
};
|
||||
(p.0.is_finite() && p.1.is_finite()).then_some(p)
|
||||
}
|
||||
|
||||
/// Punkt auf Achse `index` beim Anteil `t` (0 = Anfang, 1 = Ende).
|
||||
pub fn point_at(&self, index: u32, t: f64) -> Option<P> {
|
||||
let ax = self.axes().into_iter().find(|a| a.index == index)?;
|
||||
let p = match ax.shape {
|
||||
Shape::Line { a, b } => (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t),
|
||||
Shape::Arc { c, r, a0, a1 } => {
|
||||
let th = a0 + (a1 - a0) * t;
|
||||
(c.0 + r * th.cos(), c.1 + r * th.sin())
|
||||
}
|
||||
};
|
||||
(p.0.is_finite() && p.1.is_finite()).then_some(p)
|
||||
}
|
||||
|
||||
/// Anteil `t` des Punkts `s` auf der Achse und sein Abstand zu ihr (nächster Punkt der Achse).
|
||||
pub fn project(&self, index: u32, s: P) -> Option<(f64, f64)> {
|
||||
let ax = self.axes().into_iter().find(|a| a.index == index)?;
|
||||
match ax.shape {
|
||||
Shape::Line { a, b } => {
|
||||
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
|
||||
let l2 = dx * dx + dy * dy;
|
||||
(l2 > 1e-18).then(|| {
|
||||
let t = ((s.0 - a.0) * dx + (s.1 - a.1) * dy) / l2;
|
||||
let q = (a.0 + dx * t, a.1 + dy * t);
|
||||
(t, (s.0 - q.0).hypot(s.1 - q.1))
|
||||
})
|
||||
}
|
||||
Shape::Arc { c, r, a0, a1 } => {
|
||||
let th = (s.1 - c.1).atan2(s.0 - c.0);
|
||||
let sweep = a1 - a0;
|
||||
let mut rel = (th - a0).rem_euclid(std::f64::consts::TAU);
|
||||
if rel > sweep.abs() + 1e-9 {
|
||||
// ausserhalb des Bogens: zum näheren Ende
|
||||
rel = if rel - sweep.abs() < std::f64::consts::TAU - rel { sweep.abs() } else { 0.0 };
|
||||
}
|
||||
(sweep.abs() > 1e-12).then(|| (rel / sweep.abs(), ((s.0 - c.0).hypot(s.1 - c.1) - r).abs()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Feldweiten aus Text: Zahlen, getrennt durch Leerzeichen/`;` (Komma als Dezimalzeichen), `N*W` oder
|
||||
/// `NxW` = N Felder zu W. Nur endliche Werte > 0, höchstens 200 Felder.
|
||||
pub fn parse_bays(text: &str) -> Option<Vec<f64>> {
|
||||
let mut out = Vec::new();
|
||||
for tok in text.split(|c: char| c.is_whitespace() || c == ';').filter(|t| !t.is_empty()) {
|
||||
let tok = tok.replace(',', ".");
|
||||
let (n, w) = match tok.split_once(['x', 'X', '*']) {
|
||||
Some((n, w)) => (n.parse::<usize>().ok()?, w.parse::<f64>().ok()?),
|
||||
None => (1, tok.parse::<f64>().ok()?),
|
||||
};
|
||||
if !(w.is_finite() && w > 0.0) || n == 0 || out.len() + n > 200 {
|
||||
return None;
|
||||
}
|
||||
out.extend(std::iter::repeat(w).take(n));
|
||||
}
|
||||
(!out.is_empty()).then_some(out)
|
||||
}
|
||||
|
||||
/// Beschriftung `i` (0-basiert) als Buchstaben A … Z, AA, AB … (ohne I und O wie im Hochbau üblich).
|
||||
pub fn letter_label(mut i: usize) -> String {
|
||||
const L: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
let mut s = Vec::new();
|
||||
loop {
|
||||
s.push(L[i % L.len()]);
|
||||
if i < L.len() {
|
||||
break;
|
||||
}
|
||||
i = i / L.len() - 1;
|
||||
}
|
||||
s.reverse();
|
||||
String::from_utf8(s).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Achsen aus Feldweiten: rechtwinklig a = 1, 2, 3 … bei 0, Σ…; b = A, B, C … ebenso. Radial: a =
|
||||
/// Strahlen (Winkel in Grad ab 0), b = Ringe (Radien = laufende Summe, der erste Ring beim ersten Mass).
|
||||
pub fn axes_from_bays(radial: bool, xs: &[f64], ys: &[f64]) -> (Vec<GridAxis>, Vec<GridAxis>) {
|
||||
let cum = |w: &[f64], zero: bool| {
|
||||
let mut acc = 0.0;
|
||||
let mut out = Vec::new();
|
||||
if zero {
|
||||
out.push(0.0);
|
||||
}
|
||||
for v in w {
|
||||
acc += v;
|
||||
out.push(acc);
|
||||
}
|
||||
out
|
||||
};
|
||||
let a = cum(xs, true).iter().enumerate().map(|(i, p)| GridAxis { label: (i + 1).to_string(), pos: *p }).collect();
|
||||
let b = cum(ys, !radial).iter().enumerate().map(|(i, p)| GridAxis { label: letter_label(i), pos: *p }).collect();
|
||||
(a, b)
|
||||
}
|
||||
|
||||
/// Achsen als Punktfolgen für die 3D-Spur (Bögen in 7.5°-Schritten).
|
||||
pub fn polylines_3d(spec: &Spec) -> Vec<Vec<P>> {
|
||||
spec.axes()
|
||||
.into_iter()
|
||||
.map(|ax| match ax.shape {
|
||||
Shape::Line { a, b } => vec![a, b],
|
||||
Shape::Arc { c, r, a0, a1 } => {
|
||||
let n = (((a1 - a0).abs() / (std::f64::consts::PI / 24.0)).ceil() as usize).clamp(2, 400);
|
||||
(0..=n).map(|i| a0 + (a1 - a0) * i as f64 / n as f64).map(|t| (c.0 + r * t.cos(), c.1 + r * t.sin())).collect()
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Wird das Raster `d` im Geschoss `level` gezeigt? (`levels` fehlt/leer = in allen Geschossen.)
|
||||
pub fn visible_on(d: &Drawing2D, level: &str) -> bool {
|
||||
match &d.geom {
|
||||
Drawing2DGeom::Grid { levels: Some(l), .. } if !l.is_empty() => l.iter().any(|x| x == level),
|
||||
Drawing2DGeom::Grid { .. } => true,
|
||||
_ => d.level_id == level,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bildmass der Blase (Durchmesser, Modell-Meter) aus Papier-mm und Massstab.
|
||||
pub fn bubble_diameter(mm: Option<f64>, scale: f64) -> f64 {
|
||||
mm.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(DEFAULT_BUBBLE_MM) * scale / 1000.0
|
||||
}
|
||||
|
||||
/// Senkrechte Achsen eines Schnitts/einer Ansicht: Raster-Achsen (nur Strecken) als (Beschriftung,
|
||||
/// Lage entlang der Schnittlinien-Achse u). `origin`/`dir` = Schnittlinie (Einheitsvektor `dir`).
|
||||
/// Schnitt (`projected` false): die Achse muss die Schnittebene innerhalb ihrer Länge schneiden.
|
||||
/// Ansicht (`projected` true): Achsen, die (bis 5°) senkrecht auf der Ansichtsebene stehen, erscheinen
|
||||
/// unabhängig von ihrer Länge an der Stelle, an der ihre Verlängerung die Ebene trifft.
|
||||
pub fn section_axes(spec: &Spec, origin: P, dir: P, projected: bool) -> Vec<(String, f64)> {
|
||||
let mut out = Vec::new();
|
||||
for ax in spec.axes() {
|
||||
let Shape::Line { a, b } = ax.shape else { continue };
|
||||
let (rx, ry) = (b.0 - a.0, b.1 - a.1);
|
||||
let den = dir.0 * ry - dir.1 * rx;
|
||||
let slope = if projected { 0.996 } else { 1e-9 };
|
||||
if den.abs() < slope * rx.hypot(ry).max(1e-12) {
|
||||
continue;
|
||||
}
|
||||
// Schnitt Gerade origin+u*dir mit der Achsstrecke a+t*r.
|
||||
let (qx, qy) = (a.0 - origin.0, a.1 - origin.1);
|
||||
let t = (qx * dir.1 - qy * dir.0) / den;
|
||||
if !projected && !(-1e-9..=1.0 + 1e-9).contains(&t) {
|
||||
continue;
|
||||
}
|
||||
let u = (qx * ry - qy * rx) / den;
|
||||
out.push((ax.label.clone(), u));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::Vec2;
|
||||
|
||||
fn ax(l: &str, p: f64) -> GridAxis {
|
||||
GridAxis { label: l.into(), pos: p }
|
||||
}
|
||||
|
||||
fn ortho() -> Drawing2DGeom {
|
||||
Drawing2DGeom::Grid {
|
||||
origin: Vec2 { x: 10.0, y: 20.0 },
|
||||
angle: 0.0,
|
||||
radial: None,
|
||||
a: vec![ax("1", 0.0), ax("2", 4.0), ax("3", 10.0)],
|
||||
b: vec![ax("A", 0.0), ax("B", 5.0)],
|
||||
extend: Some(2.0),
|
||||
bubbles: None,
|
||||
bubble_mm: None,
|
||||
levels: None,
|
||||
show_3d: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unregelmaessiger_raster_achsen_und_ueberstand() {
|
||||
let g = ortho();
|
||||
let s = Spec::of(&g).unwrap();
|
||||
let axes = s.axes();
|
||||
assert_eq!(axes.len(), 5);
|
||||
// Achse "2": senkrecht bei x = 14, von y = 18 bis 27.
|
||||
assert_eq!(axes[1].shape, Shape::Line { a: (14.0, 18.0), b: (14.0, 27.0) });
|
||||
// Achse "B": waagrecht bei y = 25, von x = 8 bis 22.
|
||||
assert_eq!(axes[4].shape, Shape::Line { a: (8.0, 25.0), b: (22.0, 25.0) });
|
||||
// Blasen an beiden Enden, Richtung nach aussen.
|
||||
assert_eq!(axes[1].bubbles[0], Some(((14.0, 18.0), (0.0, -1.0))));
|
||||
assert_eq!(axes[1].bubbles[1], Some(((14.0, 27.0), (0.0, 1.0))));
|
||||
assert_eq!(s.crossings().len(), 6);
|
||||
assert_eq!(s.cross(4, 1), Some((14.0, 25.0)));
|
||||
assert_eq!(s.cross(0, 1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gedrehtes_raster_und_blasenseite() {
|
||||
let mut g = ortho();
|
||||
if let Drawing2DGeom::Grid { angle, bubbles, .. } = &mut g {
|
||||
*angle = std::f64::consts::FRAC_PI_2;
|
||||
*bubbles = Some(GridBubbles::End);
|
||||
}
|
||||
let s = Spec::of(&g).unwrap();
|
||||
let p = s.cross(1, 4).unwrap(); // Achse 2 x B: lokal (4, 5) -> (10 - 5, 20 + 4)
|
||||
assert!((p.0 - 5.0).abs() < 1e-12 && (p.1 - 24.0).abs() < 1e-12);
|
||||
let a = &s.axes()[0];
|
||||
assert!(a.bubbles[0].is_none() && a.bubbles[1].is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_strahlen_ringe() {
|
||||
let g = Drawing2DGeom::Grid {
|
||||
origin: Vec2 { x: 0.0, y: 0.0 },
|
||||
angle: 0.0,
|
||||
radial: Some(true),
|
||||
a: vec![ax("1", 0.0), ax("2", 90.0)],
|
||||
b: vec![ax("A", 3.0), ax("B", 6.0)],
|
||||
extend: Some(1.0),
|
||||
bubbles: None,
|
||||
bubble_mm: None,
|
||||
levels: None,
|
||||
show_3d: None,
|
||||
};
|
||||
let s = Spec::of(&g).unwrap();
|
||||
let axes = s.axes();
|
||||
assert_eq!(axes.len(), 4);
|
||||
match axes[0].shape {
|
||||
Shape::Line { b, .. } => assert!((b.0 - 7.0).abs() < 1e-12 && b.1.abs() < 1e-12),
|
||||
_ => panic!(),
|
||||
}
|
||||
let p = s.cross(1, 3).unwrap();
|
||||
assert!(p.0.abs() < 1e-12 && (p.1 - 6.0).abs() < 1e-12);
|
||||
match axes[2].shape {
|
||||
Shape::Arc { a0, a1, r, .. } => {
|
||||
assert_eq!(r, 3.0);
|
||||
assert!(a0 < 0.0 && a1 > std::f64::consts::FRAC_PI_2);
|
||||
}
|
||||
_ => panic!(),
|
||||
}
|
||||
// Projektion auf den Ring.
|
||||
let (t, d) = s.project(2, (0.0, 3.5)).unwrap();
|
||||
assert!((d - 0.5).abs() < 1e-9 && t > 0.0 && t < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feldweiten_und_beschriftung() {
|
||||
assert_eq!(parse_bays("5 4,5 3x6"), Some(vec![5.0, 4.5, 6.0, 6.0, 6.0]));
|
||||
assert_eq!(parse_bays("2*3.2; 4"), Some(vec![3.2, 3.2, 4.0]));
|
||||
assert_eq!(parse_bays(""), None);
|
||||
assert_eq!(parse_bays("5 -1"), None);
|
||||
assert_eq!(parse_bays("abc"), None);
|
||||
assert_eq!(parse_bays("0x5"), None);
|
||||
assert_eq!((letter_label(0), letter_label(7), letter_label(8), letter_label(23), letter_label(24)), ("A".into(), "H".into(), "J".into(), "Z".into(), "AA".into()));
|
||||
let (a, b) = axes_from_bays(false, &[5.0, 3.0], &[4.0]);
|
||||
assert_eq!(a.iter().map(|x| (x.label.as_str(), x.pos)).collect::<Vec<_>>(), [("1", 0.0), ("2", 5.0), ("3", 8.0)]);
|
||||
assert_eq!(b.iter().map(|x| (x.label.as_str(), x.pos)).collect::<Vec<_>>(), [("A", 0.0), ("B", 4.0)]);
|
||||
// Radial: Ringe ohne Radius 0.
|
||||
let (_, rings) = axes_from_bays(true, &[45.0], &[2.0, 3.0]);
|
||||
assert_eq!(rings.iter().map(|x| x.pos).collect::<Vec<_>>(), [2.0, 5.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sichtbarkeit_je_geschoss() {
|
||||
let mut d = Drawing2D { level_id: "eg".into(), geom: ortho(), ..Default::default() };
|
||||
assert!(visible_on(&d, "og") && visible_on(&d, "eg"));
|
||||
if let Drawing2DGeom::Grid { levels, .. } = &mut d.geom {
|
||||
*levels = Some(vec!["eg".into()]);
|
||||
}
|
||||
assert!(visible_on(&d, "eg") && !visible_on(&d, "og"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schnittachsen_quer_zur_schnittlinie() {
|
||||
let g = ortho();
|
||||
let s = Spec::of(&g).unwrap();
|
||||
// Schnitt entlang +x bei y = 22: schneidet die senkrechten Achsen 1, 2, 3 bei u = 0, 4, 10 (ab x = 10).
|
||||
let r = section_axes(&s, (10.0, 22.0), (1.0, 0.0), false);
|
||||
let us: Vec<f64> = r.iter().map(|x| x.1).collect();
|
||||
assert_eq!(r.len(), 3);
|
||||
assert!((us[0]).abs() < 1e-9 && (us[1] - 4.0).abs() < 1e-9 && (us[2] - 10.0).abs() < 1e-9);
|
||||
// Ausserhalb der Achslänge: nichts.
|
||||
assert!(section_axes(&s, (10.0, 40.0), (1.0, 0.0), false).is_empty());
|
||||
// Ansicht von aussen (Ebene bei y = 40): die senkrechten Achsen erscheinen trotzdem, die waagrechten nicht.
|
||||
let v = section_axes(&s, (10.0, 40.0), (1.0, 0.0), true);
|
||||
assert_eq!(v.iter().map(|x| x.0.as_str()).collect::<Vec<_>>(), ["1", "2", "3"]);
|
||||
}
|
||||
}
|
||||
@@ -613,6 +613,11 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option<Val
|
||||
let ng = with(g, "pts", replace_at(pts, index, &p));
|
||||
return Some(with_geom(d, crate::dim_assoc::without_ref(&ng, index_in(index, n))));
|
||||
}
|
||||
if index == n as f64 && field(g, "kind").and_then(Value::as_str) == Some("arc") && n >= 2 {
|
||||
// Bogenlängen-Mass: Abstand der Masslinie vom Bogen (radial).
|
||||
let (c, p0) = (xy(&pts[0]), xy(&pts[1]));
|
||||
return set("offset", js_num(hypot2(x - c.0, y - c.1) - hypot2(p0.0 - c.0, p0.1 - c.1)));
|
||||
}
|
||||
if index == n as f64 {
|
||||
// Griff auf der Masslinie: nur `offset` (Normalabstand zur Punktreihe).
|
||||
let (a, b) = (xy(pts.first()?), xy(pts.last()?));
|
||||
@@ -698,6 +703,33 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option<Val
|
||||
set("at", p)
|
||||
}
|
||||
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" => set("at", p),
|
||||
"grid" => {
|
||||
// Griff 0 = Ursprung, danach je Achse (a, dann b) das Achsende: zieht die Achse auf die neue Lage.
|
||||
if index == 0.0 {
|
||||
return set("origin", p);
|
||||
}
|
||||
let (na, nb) = (arr(field(g, "a")).len(), arr(field(g, "b")).len());
|
||||
let k = index_in(index - 1.0, na + nb)?;
|
||||
let (ox, oy) = xy(field(g, "origin").unwrap_or(&Value::Null));
|
||||
let ang = num_of(field(g, "angle"));
|
||||
let (dx, dy) = (x - ox, y - oy);
|
||||
let radial = field(g, "radial").and_then(Value::as_bool) == Some(true);
|
||||
let (key, i) = if k < na { ("a", k) } else { ("b", k - na) };
|
||||
let pos = match (radial, key) {
|
||||
(false, "a") => dx * jsnum::cos(ang) + dy * jsnum::sin(ang),
|
||||
(false, _) => -dx * jsnum::sin(ang) + dy * jsnum::cos(ang),
|
||||
(true, "a") => {
|
||||
let d = (jsnum::atan2(dy, dx) - ang).to_degrees();
|
||||
let old = num_of(field(&arr(field(g, "a"))[i], "pos"));
|
||||
// auf den Winkel nächst dem alten legen (kein Sprung um 360°)
|
||||
old + (d - old + 180.0).rem_euclid(360.0) - 180.0
|
||||
}
|
||||
(true, _) => hypot2(dx, dy),
|
||||
};
|
||||
let list = arr(field(g, key));
|
||||
let nl = Value::Array(list.iter().enumerate().map(|(j, e)| if j == i { with(e, "pos", js_num(pos)) } else { e.clone() }).collect());
|
||||
set(key, nl)
|
||||
}
|
||||
"circle" => {
|
||||
let (cx, cy) = xy(field(g, "center").unwrap_or(&Value::Null));
|
||||
let r = pass(field(g, "r"));
|
||||
@@ -758,6 +790,7 @@ fn drawing_moved(d: &Value, dx: f64, dy: f64) -> Option<Value> {
|
||||
"rect" | "image" => with_all(g, vec![("min", mv("min")), ("max", mv("max"))]),
|
||||
"circle" | "arc" | "ellipse" => with(g, "center", mv("center")),
|
||||
"kote" | "detailref" | "scalebar" | "pointmarker" | "text" => with(g, "at", mv("at")),
|
||||
"grid" => with(g, "origin", mv("origin")),
|
||||
_ => return None,
|
||||
};
|
||||
Some(with_geom(d, ng))
|
||||
@@ -1229,6 +1262,18 @@ pub fn drawing_vertices(g: &Value, scale: f64) -> Option<Vec<(f64, f64)>> {
|
||||
out
|
||||
}
|
||||
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" => vec![p("at")],
|
||||
"grid" => {
|
||||
let geom: crate::model::Drawing2DGeom = serde_json::from_value(g.clone()).ok()?;
|
||||
let spec = crate::grid::Spec::of(&geom)?;
|
||||
let mut out = vec![p("origin")];
|
||||
for ax in spec.axes() {
|
||||
out.push(match ax.shape {
|
||||
crate::grid::Shape::Line { b, .. } => b,
|
||||
crate::grid::Shape::Arc { c, r, a1, .. } => (c.0 + r * jsnum::cos(a1), c.1 + r * jsnum::sin(a1)),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
"text" => {
|
||||
if truthy(field(g, "pathPts")) {
|
||||
pts("pathPts")
|
||||
|
||||
@@ -269,7 +269,7 @@ fn by_from(p: &[f64; 4], q: &[f64; 4]) -> std::cmp::Ordering {
|
||||
fn bands_match_openings(wall: &Wall, bands: &[&RWall], cutouts: &[Cutout]) -> bool {
|
||||
let u = normalize(sub(wall.end, wall.start));
|
||||
for b in bands {
|
||||
if b.top_drop.is_some_and(|d| d[0].abs() > 1e-9 || d[1].abs() > 1e-9) {
|
||||
if b.top_plane.is_some() || b.top_drop.is_some_and(|d| d[0].abs() > 1e-9 || d[1].abs() > 1e-9) {
|
||||
return false;
|
||||
}
|
||||
let a = dot(Vec2 { x: b.start[0] - wall.start.x, y: b.start[1] - wall.start.y }, u);
|
||||
@@ -497,6 +497,33 @@ struct SolidOpening {
|
||||
/// Dreiecke eines 8-Ecken-Quaders wie `model3d::OPENING_BOX_TRIS`.
|
||||
const BOX_TRIS: [u32; 36] = [0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6, 0, 1, 5, 0, 5, 4, 2, 3, 7, 2, 7, 6, 0, 2, 6, 0, 6, 4, 1, 3, 7, 1, 7, 5];
|
||||
|
||||
/// Gauben eines Dachs (Index) für die Mengen ([G5]): je Gaube Breite, Stirnhöhe, geneigte Fläche des
|
||||
/// Ausschnitts im Hauptdach, Volumen der Wände (Stirn/Wangen) und des Gaubendachs aus den Körpern.
|
||||
fn dormer_parts(p: &Project, ri: usize, roof: &Roof) -> Vec<qty::DormerIn> {
|
||||
let solids = crate::roof_assembly::roof_solids(p, ri);
|
||||
let vol = |id: &str, role: crate::roof_assembly::Role| -> f64 {
|
||||
solids.as_ref().map_or(0.0, |s| s.parts.iter().filter(|x| x.role == role && x.dormer.as_deref() == Some(id)).map(|x| x.mesh.volume().abs()).sum())
|
||||
};
|
||||
roof.dormers
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter_map(|d| {
|
||||
let g = crate::dormer::geometry(p, roof, d)?;
|
||||
let hole = g.hole();
|
||||
let n = hole.len();
|
||||
let proj = (0..n).map(|i| hole[i][0] * hole[(i + 1) % n][1] - hole[(i + 1) % n][0] * hole[i][1]).sum::<f64>().abs() / 2.0;
|
||||
Some(qty::DormerIn {
|
||||
width: d.width,
|
||||
front_height: g.front_height,
|
||||
opening_area: proj * (1.0 + g.frame.tan_main * g.frame.tan_main).sqrt(),
|
||||
wall_volume: vol(&d.id, crate::roof_assembly::Role::DormerWall),
|
||||
roof_volume: vol(&d.id, crate::roof_assembly::Role::DormerRoof),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn push_box(positions: &mut Vec<f64>, indices: &mut Vec<u32>, b: &[f64; 24], base: f64) {
|
||||
let at = (positions.len() / 3) as u32;
|
||||
for c in b.chunks_exact(3) {
|
||||
@@ -766,6 +793,17 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result<Flat, String>
|
||||
let bands = bands_by_wall.get(wall.id.as_str()).unwrap_or(&no_bands);
|
||||
let (mut positions, mut indices) = (Vec::<f64>::new(), Vec::<u32>::new());
|
||||
for b in bands {
|
||||
// Ebene Oberkante unter einem Dach ([G2]): Prisma bis an die Dachunterkante.
|
||||
if b.top_plane.is_some() && b.holes.as_ref().is_none_or(|h| h.is_empty()) {
|
||||
if let Some(m) = model3d::wall_piece_mesh(b) {
|
||||
let at = (positions.len() / 3) as u32;
|
||||
for c in m.positions.chunks_exact(3) {
|
||||
positions.extend_from_slice(&[c[0], c[1], c[2] - base]);
|
||||
}
|
||||
indices.extend(m.indices.iter().map(|i| at + i));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let cut = wall_cut_mesh_checked(&CutWall {
|
||||
start: b.start,
|
||||
end: b.end,
|
||||
@@ -1085,7 +1123,16 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result<Flat, String>
|
||||
props.extend(crate::u_value::roof_u_value(&p, roof).and_then(|u| u.u).map(|u| Prop::Thermal("ThermalTransmittance", u)));
|
||||
let planes = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)).planes;
|
||||
let mut psets = vec![Pset { name: "Pset_RoofCommon", props }];
|
||||
psets.extend(qto("Qto_RoofBaseQuantities", qty::roof_quantities(&planes)));
|
||||
let mut roof_q = qty::roof_quantities(&planes);
|
||||
// Gauben ([G5]): Ausschnitt im Hauptdach (geneigt) von der Nettofläche ab, eigene Mengen der Gauben.
|
||||
let dormer_q = p.roofs.as_deref().unwrap_or(&[]).iter().position(|r| r.id == roof.id).map_or_else(Vec::new, |ri| qty::dormer_quantities(&dormer_parts(&p, ri, roof)));
|
||||
if let Some(cut) = dormer_q.iter().find(|q| q.name == "OpeningArea").map(|q| q.value) {
|
||||
if let Some(net) = roof_q.iter_mut().find(|q| q.name == "NetArea") {
|
||||
net.value = max(0.0, net.value - cut);
|
||||
}
|
||||
}
|
||||
psets.extend(qto("Qto_RoofBaseQuantities", roof_q));
|
||||
psets.extend(qto("Qto_DossierDormerQuantities", dormer_q));
|
||||
let ty = roof_type.map(|t| (t.id.clone(), t.name.clone(), t.layers.iter().map(|l| (l.component_id.clone(), component_name(&p, &l.component_id), l.thickness)).collect::<Vec<_>>()));
|
||||
let (id, name, pre) = (f.str(&roof.id), f.str(roof_type.map_or("Dach", |t| t.name.as_str())), f.str(predefined));
|
||||
f.nums(&[REC_ROOF, structure, id, name, pre]);
|
||||
@@ -1253,6 +1300,20 @@ mod tests {
|
||||
assert_eq!(f.nums.iter().filter(|v| **v == REC_OPENING_SOLID).count() >= 2, true);
|
||||
}
|
||||
|
||||
/// [G5] Gauben-Mengen: Ausschnitt geneigt, Wand- und Dachvolumen aus den Körpern.
|
||||
#[test]
|
||||
fn gauben_mengen() {
|
||||
let p = crate::dormer::tests::gable_project();
|
||||
let roof = &p.roofs.as_ref().unwrap()[0];
|
||||
let d = dormer_parts(&p, 0, roof);
|
||||
assert_eq!(d.len(), 1);
|
||||
assert!(d[0].opening_area > 2.4 * 1.6 * 2f64.sqrt() && d[0].opening_area < 2.4 * 3.0 * 2f64.sqrt(), "{d:?}");
|
||||
assert!(d[0].wall_volume > 0.1 && d[0].roof_volume > 0.1, "{d:?}");
|
||||
let q = qty::dormer_quantities(&d);
|
||||
assert_eq!(q.len(), 5);
|
||||
assert!(qty::dormer_quantities(&[]).is_empty());
|
||||
}
|
||||
|
||||
/// [T2] Bogenwand: Datensatz WALL_ARC mit Kreisachse (Mitte, Radius, Startwinkel, Schwenk).
|
||||
#[test]
|
||||
fn bogenwand_als_netz_mit_kreisachse() {
|
||||
|
||||
@@ -115,9 +115,15 @@ pub fn wall_quantities(start: Vec2, end: Vec2, bands: &[&RWall], cutouts: &[Cuto
|
||||
z_min = min(z_min, b.base_elevation);
|
||||
z_max = max(z_max, b.base_elevation + b.height);
|
||||
let drop = b.top_drop.map_or(0.0, |d| (d[0] + d[1]) / 2.0);
|
||||
if sloped_band(b) {
|
||||
if sloped_band(b) || b.top_plane.is_some() {
|
||||
sloped = true;
|
||||
}
|
||||
if b.top_plane.is_some() {
|
||||
// Ebene Oberkante unter einem Dach ([G2]): exakt über die Grundfläche.
|
||||
gross += crate::model3d::wall_piece_volume(b);
|
||||
tallest = max(tallest, b.height);
|
||||
continue;
|
||||
}
|
||||
gross += l * b.thickness * (b.height - drop);
|
||||
tallest = max(tallest, b.height - drop);
|
||||
}
|
||||
@@ -235,6 +241,33 @@ pub fn roof_quantities(planes: &[Vec<[f64; 3]>]) -> Vec<Qty> {
|
||||
vec![area("GrossArea", sloped), area("NetArea", sloped), area("ProjectedArea", projected)]
|
||||
}
|
||||
|
||||
/// Eine Gaube für die Mengen ([G5]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct DormerIn {
|
||||
pub width: f64,
|
||||
pub front_height: f64,
|
||||
/// Geneigte Fläche des Ausschnitts im Hauptdach.
|
||||
pub opening_area: f64,
|
||||
pub wall_volume: f64,
|
||||
pub roof_volume: f64,
|
||||
}
|
||||
|
||||
/// Gauben eines Dachs, summiert: Anzahl als Länge der Breiten (`Width`), grösste Stirnhöhe, Ausschnitt
|
||||
/// im Hauptdach, Volumen der Gaubenwände und -dächer. Leer ohne Gauben.
|
||||
pub fn dormer_quantities(d: &[DormerIn]) -> Vec<Qty> {
|
||||
if d.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let sum = |f: fn(&DormerIn) -> f64| d.iter().map(f).sum::<f64>();
|
||||
vec![
|
||||
len("Width", sum(|x| x.width)),
|
||||
len("FrontHeight", d.iter().map(|x| x.front_height).fold(0.0, f64::max)),
|
||||
area("OpeningArea", sum(|x| x.opening_area)),
|
||||
vol("WallVolume", sum(|x| x.wall_volume)),
|
||||
vol("RoofVolume", sum(|x| x.roof_volume)),
|
||||
]
|
||||
}
|
||||
|
||||
/// Stützen-Basismengen: Länge, Querschnitt, Mantel, Oberfläche und Volumen.
|
||||
pub fn column_quantities(footprint: &[Vec2], length: f64) -> Vec<Qty> {
|
||||
let cross = ring_area(footprint);
|
||||
@@ -283,6 +316,7 @@ mod tests {
|
||||
height,
|
||||
base_elevation: base,
|
||||
top_drop: None,
|
||||
top_plane: None,
|
||||
color: [0.5, 0.5, 0.5],
|
||||
layers: vec![],
|
||||
wall_id: "w".into(),
|
||||
|
||||
@@ -374,6 +374,7 @@ pub fn decode_mesh(f: &[f64], strings: &[String]) -> Result<(Vec<MeshObject>, Va
|
||||
k += 1.0;
|
||||
}
|
||||
let mut objects = Vec::new();
|
||||
let mut repaired = [0usize; 3];
|
||||
let mut k = 0.0;
|
||||
while k < n_obj {
|
||||
let h = f.get(at..at + 9).ok_or("Mesh-Import: Puffer beschädigt")?;
|
||||
@@ -385,12 +386,17 @@ pub fn decode_mesh(f: &[f64], strings: &[String]) -> Result<(Vec<MeshObject>, Va
|
||||
if !(np.fract() == 0.0 && ni.fract() == 0.0 && np >= 0.0 && ni >= 0.0) || at + np as usize + ni as usize > f.len() {
|
||||
return Err("Mesh-Import: Puffer beschädigt".into());
|
||||
}
|
||||
let positions = f[at..at + np as usize].to_vec();
|
||||
let positions: Vec<f64> = f[at..at + np as usize].to_vec();
|
||||
at += np as usize;
|
||||
// Wie `Uint32Array`: ganzzahlig modulo 2³².
|
||||
let indices = f[at..at + ni as usize].iter().map(|&x| (jsnum::to_int32(x) as u32) as f64).collect();
|
||||
let indices: Vec<f64> = f[at..at + ni as usize].iter().map(|&x| (jsnum::to_int32(x) as u32) as f64).collect();
|
||||
at += ni as usize;
|
||||
objects.push(MeshObject { name, group, color, positions, indices });
|
||||
// Reparatur ([T5]): verschweissen, Entartete raus, kleine Löcher zu; Zähler gehen in den Bericht.
|
||||
let r = crate::mesh_repair::repair(&positions, &indices);
|
||||
repaired[0] += r.welded;
|
||||
repaired[1] += r.degenerate;
|
||||
repaired[2] += r.holes;
|
||||
objects.push(MeshObject { name, group, color, positions: r.pos, indices: r.idx });
|
||||
k += 1.0;
|
||||
}
|
||||
let report = json!({
|
||||
@@ -405,6 +411,7 @@ pub fn decode_mesh(f: &[f64], strings: &[String]) -> Result<(Vec<MeshObject>, Va
|
||||
"truncated": f[9] == 1.0,
|
||||
"warnings": warnings,
|
||||
"objects": objects.len(),
|
||||
"repaired": {"welded": repaired[0], "degenerate": repaired[1], "holes": repaired[2]},
|
||||
});
|
||||
Ok((objects, report))
|
||||
}
|
||||
@@ -593,3 +600,24 @@ mod step_tests {
|
||||
assert!(decode_step(&[1.0, f64::NAN]).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod repair_tests {
|
||||
use super::*;
|
||||
|
||||
/// [T5] Der Import verschweisst Ecken und meldet die Reparatur im Bericht.
|
||||
#[test]
|
||||
fn mesh_import_repariert_und_berichtet() {
|
||||
let mut f = vec![1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0];
|
||||
// Objekt: Name 0, Gruppe -1, keine Farbe, 6 Ecken (Quadrat als zwei Dreiecke, STL-artig) + 1 entartetes Dreieck
|
||||
f.extend([0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 18.0, 9.0]);
|
||||
f.extend([0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 0., 0., 1., 1., 0., 0., 1., 0.]);
|
||||
f.extend([0., 1., 2., 3., 4., 5., 0., 0., 1.]);
|
||||
let (objects, report) = decode_mesh(&f, &["q".to_string()]).unwrap();
|
||||
assert_eq!(objects[0].positions.len(), 12); // 4 statt 6 Ecken
|
||||
assert_eq!(objects[0].indices.len(), 6);
|
||||
assert_eq!(report["repaired"]["welded"], 2);
|
||||
assert_eq!(report["repaired"]["degenerate"], 1);
|
||||
assert_eq!(report["repaired"]["holes"], 0);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ pub mod export_schedule;
|
||||
pub mod opening_schedule;
|
||||
pub mod u_value;
|
||||
pub mod sheet_table;
|
||||
pub mod terrain;
|
||||
pub mod excavation;
|
||||
pub mod flat;
|
||||
pub mod flat_write;
|
||||
pub mod polygon_bool;
|
||||
@@ -28,6 +30,7 @@ pub mod stair;
|
||||
pub mod joins;
|
||||
pub mod wall_bands;
|
||||
pub mod wall_arc;
|
||||
pub mod grid;
|
||||
pub mod room_area;
|
||||
pub mod room_boundary;
|
||||
pub mod polygon_holes;
|
||||
@@ -35,6 +38,7 @@ pub mod js_fmt;
|
||||
pub use dossier_hatch::jsmath;
|
||||
pub mod stairs3d;
|
||||
pub mod mesh3d;
|
||||
pub mod mesh_repair;
|
||||
pub mod ceilings3d;
|
||||
pub mod columns3d;
|
||||
pub mod drawing2d_3d;
|
||||
|
||||
@@ -127,6 +127,19 @@ const BOX_QUADS: [[usize; 4]; 6] = [[4, 6, 7, 5], [1, 3, 2, 0], [2, 3, 7, 6], [4
|
||||
|
||||
/// Voller Wand-Schicht-Quader ohne Öffnungen (lochlose Bänder); entartete Bänder fallen weg.
|
||||
fn push_wall_box(g: &mut Prim, w: &RWall) {
|
||||
// Ebene Oberkante unter einem Dach ([G2]): Prisma, Modell (x, y, z) → Welt (x, Höhe, y), gespiegelt.
|
||||
if w.top_plane.is_some() {
|
||||
if let Some(m) = crate::model3d::wall_piece_mesh(w) {
|
||||
let base = (g.positions.len() / 3) as f64;
|
||||
for c in m.positions.chunks_exact(3) {
|
||||
g.positions.extend_from_slice(&[c[0], c[2], c[1]]);
|
||||
}
|
||||
for t in m.indices.chunks_exact(3) {
|
||||
g.indices.extend_from_slice(&[base + t[0] as f64, base + t[2] as f64, base + t[1] as f64]);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let [sx, sy] = w.start;
|
||||
let [ex, ey] = w.end;
|
||||
let dx = ex - sx;
|
||||
@@ -485,10 +498,14 @@ pub fn mesh_export_data(src: &Project, opt: &MeshOptions) -> Result<Flat, String
|
||||
if opt.context {
|
||||
for obj in p.context.as_deref().unwrap_or(&[]) {
|
||||
let (terrain, id, name, color, positions, indices) = match obj {
|
||||
ContextObject::TerrainMesh(m) => (true, &m.id, &m.name, None, &m.positions, &m.indices),
|
||||
ContextObject::ImportedMesh(m) => (false, &m.id, &m.name, m.color.as_deref(), &m.positions, &m.indices),
|
||||
ContextObject::TerrainMesh(m) => {
|
||||
let (pos, idx, _) = crate::excavation::terrain_model_mesh(&p, m);
|
||||
(true, &m.id, &m.name, None, pos, idx)
|
||||
}
|
||||
ContextObject::ImportedMesh(m) => (false, &m.id, &m.name, m.color.as_deref(), std::borrow::Cow::Borrowed(m.positions.as_slice()), std::borrow::Cow::Borrowed(m.indices.as_slice())),
|
||||
_ => continue,
|
||||
};
|
||||
let (positions, indices) = (&*positions, &*indices);
|
||||
if positions.len() < 9 || indices.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
//! Reparatur importierter Dreiecksnetze ([T5]): Ecken verschweissen (STL liefert jedes Dreieck mit eigenen
|
||||
//! Ecken), entartete Dreiecke entfernen, kleine Löcher in sonst geschlossenen Netzen mit einem Fächer
|
||||
//! schliessen. Reine Funktion über flache Puffer (`pos` = `[x, y, z, …]` in Metern, `idx` = Dreiecks-Indizes
|
||||
//! als `f64`); Unsinn (NaN, Indizes ausserhalb) bleibt unverändert bzw. wird als entartet entfernt.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Verschweiss-Toleranz (Meter): 0.01 mm — fängt Rundungsdifferenzen der Formate, nicht echte Spalte.
|
||||
pub const WELD_TOL: f64 = 1e-5;
|
||||
/// Löcher mit höchstens so vielen Randkanten werden geschlossen.
|
||||
pub const MAX_HOLE_EDGES: usize = 8;
|
||||
/// Löcher nur schliessen, wenn höchstens dieser Anteil der Kanten am Rand liegt (sonst offene Fläche gewollt).
|
||||
const MAX_BOUNDARY_SHARE: f64 = 0.05;
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Repaired {
|
||||
pub pos: Vec<f64>,
|
||||
pub idx: Vec<f64>,
|
||||
/// Zusammengelegte Ecken.
|
||||
pub welded: usize,
|
||||
/// Entfernte entartete Dreiecke (doppelte Ecke, Fläche ≈ 0, ungültiger Index).
|
||||
pub degenerate: usize,
|
||||
/// Geschlossene Löcher.
|
||||
pub holes: usize,
|
||||
}
|
||||
|
||||
fn tri_area2(p: &[[f64; 3]; 3]) -> f64 {
|
||||
let (a, b, c) = (p[0], p[1], p[2]);
|
||||
let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
|
||||
let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
|
||||
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
|
||||
(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt()
|
||||
}
|
||||
|
||||
pub fn repair(pos: &[f64], idx: &[f64]) -> Repaired {
|
||||
repair_with(pos, idx, MAX_BOUNDARY_SHARE)
|
||||
}
|
||||
|
||||
/// Wie [`repair`], mit frei wählbarem Randanteil-Schutz (Tests, strenge Importe).
|
||||
pub fn repair_with(pos: &[f64], idx: &[f64], max_boundary_share: f64) -> Repaired {
|
||||
let nv = pos.len() / 3;
|
||||
// 1) Verschweissen über ein Raster (Zelle = Toleranz); Nachbarzellen werden nicht geprüft — Ecken, die
|
||||
// knapp über einer Zellgrenze liegen, bleiben getrennt (konservativ, nie falsch verbunden).
|
||||
let mut cell: HashMap<(i64, i64, i64), u32> = HashMap::new();
|
||||
let mut map: Vec<Option<u32>> = vec![None; nv];
|
||||
let mut out_pos: Vec<f64> = Vec::new();
|
||||
for i in 0..nv {
|
||||
let p = [pos[3 * i], pos[3 * i + 1], pos[3 * i + 2]];
|
||||
if !p.iter().all(|x| x.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let key = ((p[0] / WELD_TOL).round() as i64, (p[1] / WELD_TOL).round() as i64, (p[2] / WELD_TOL).round() as i64);
|
||||
let id = *cell.entry(key).or_insert_with(|| {
|
||||
out_pos.extend(p);
|
||||
(out_pos.len() / 3 - 1) as u32
|
||||
});
|
||||
map[i] = Some(id);
|
||||
}
|
||||
let welded = map.iter().flatten().count() - out_pos.len() / 3;
|
||||
// 2) Dreiecke übernehmen, entartete verwerfen
|
||||
let mut tris: Vec<[u32; 3]> = Vec::new();
|
||||
let mut degenerate = 0;
|
||||
for t in idx.chunks_exact(3) {
|
||||
let v: Vec<Option<u32>> = t.iter().map(|&k| if k >= 0.0 && k.fract() == 0.0 && (k as usize) < nv { map[k as usize] } else { None }).collect();
|
||||
let (Some(a), Some(b), Some(c)) = (v[0], v[1], v[2]) else {
|
||||
degenerate += 1;
|
||||
continue;
|
||||
};
|
||||
let p = |i: u32| [out_pos[3 * i as usize], out_pos[3 * i as usize + 1], out_pos[3 * i as usize + 2]];
|
||||
if a == b || b == c || a == c || tri_area2(&[p(a), p(b), p(c)]) < 1e-12 {
|
||||
degenerate += 1;
|
||||
continue;
|
||||
}
|
||||
tris.push([a, b, c]);
|
||||
}
|
||||
// 3) Löcher schliessen
|
||||
let holes = close_holes(&mut tris, max_boundary_share);
|
||||
Repaired { pos: out_pos, idx: tris.iter().flatten().map(|&k| k as f64).collect(), welded, degenerate, holes }
|
||||
}
|
||||
|
||||
/// Kleine Randschleifen eines fast geschlossenen Netzes mit einem Fächer füllen; Anzahl geschlossener Löcher.
|
||||
fn close_holes(tris: &mut Vec<[u32; 3]>, max_boundary_share: f64) -> usize {
|
||||
let mut directed: HashMap<(u32, u32), usize> = HashMap::new();
|
||||
for t in tris.iter() {
|
||||
for k in 0..3 {
|
||||
*directed.entry((t[k], t[(k + 1) % 3])).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
// Randkanten: Kante a→b ohne Gegenkante b→a; Nicht-Mannigfaltigkeit (Kante mehrfach) → nichts anfassen
|
||||
if directed.values().any(|&n| n > 1) {
|
||||
return 0;
|
||||
}
|
||||
let boundary: Vec<(u32, u32)> = directed.keys().filter(|&&(a, b)| !directed.contains_key(&(b, a))).copied().collect();
|
||||
if boundary.is_empty() || boundary.len() as f64 > max_boundary_share * directed.len() as f64 {
|
||||
return 0;
|
||||
}
|
||||
// Der Rand läuft a→b; die fehlenden Dreiecke tragen b→a, der Deckel läuft also gegen die Randrichtung.
|
||||
let mut next: HashMap<u32, Vec<u32>> = HashMap::new();
|
||||
for &(a, b) in &boundary {
|
||||
next.entry(a).or_default().push(b);
|
||||
}
|
||||
if next.values().any(|v| v.len() != 1) {
|
||||
return 0; // Rand verzweigt sich (Schmetterlingsecke) — nicht raten
|
||||
}
|
||||
let mut seen: std::collections::HashSet<u32> = std::collections::HashSet::new();
|
||||
let mut closed = 0;
|
||||
let mut starts: Vec<u32> = next.keys().copied().collect();
|
||||
starts.sort_unstable();
|
||||
for s in starts {
|
||||
if seen.contains(&s) {
|
||||
continue;
|
||||
}
|
||||
let mut ring = vec![s];
|
||||
let mut cur = s;
|
||||
let mut ok = true;
|
||||
loop {
|
||||
let n = next[&cur][0];
|
||||
if n == s {
|
||||
break;
|
||||
}
|
||||
if ring.len() >= MAX_HOLE_EDGES || !next.contains_key(&n) || ring.contains(&n) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
ring.push(n);
|
||||
cur = n;
|
||||
}
|
||||
seen.extend(ring.iter().copied());
|
||||
if !ok || ring.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
ring.reverse();
|
||||
for k in 1..ring.len() - 1 {
|
||||
tris.push([ring[0], ring[k], ring[k + 1]]);
|
||||
}
|
||||
closed += 1;
|
||||
}
|
||||
closed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Würfel mit eigenen Ecken je Dreieck (wie STL), Kantenlänge 1, nach aussen orientiert.
|
||||
fn soup(skip: &[usize]) -> (Vec<f64>, Vec<f64>) {
|
||||
let v = [[0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 1., 0.], [0., 0., 1.], [1., 0., 1.], [1., 1., 1.], [0., 1., 1.]];
|
||||
let f: [[usize; 3]; 12] = [
|
||||
[0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7], [0, 1, 5], [0, 5, 4],
|
||||
[1, 2, 6], [1, 6, 5], [2, 3, 7], [2, 7, 6], [3, 0, 4], [3, 4, 7],
|
||||
];
|
||||
let (mut pos, mut idx) = (Vec::new(), Vec::new());
|
||||
for (i, t) in f.iter().enumerate() {
|
||||
if skip.contains(&i) {
|
||||
continue;
|
||||
}
|
||||
for &k in t {
|
||||
idx.push((pos.len() / 3) as f64);
|
||||
pos.extend(v[k]);
|
||||
}
|
||||
}
|
||||
(pos, idx)
|
||||
}
|
||||
|
||||
fn volume(r: &Repaired) -> f64 {
|
||||
r.idx
|
||||
.chunks(3)
|
||||
.map(|t| {
|
||||
let p = |i: f64| [r.pos[3 * i as usize], r.pos[3 * i as usize + 1], r.pos[3 * i as usize + 2]];
|
||||
let (a, b, c) = (p(t[0]), p(t[1]), p(t[2]));
|
||||
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stl_suppe_wird_verschweisst() {
|
||||
let (pos, idx) = soup(&[]);
|
||||
let r = repair(&pos, &idx);
|
||||
assert_eq!(r.pos.len() / 3, 8);
|
||||
assert_eq!(r.welded, 36 - 8);
|
||||
assert_eq!((r.degenerate, r.holes), (0, 0));
|
||||
assert!((volume(&r) - 1.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entartete_dreiecke_fliegen_raus() {
|
||||
let (mut pos, mut idx) = soup(&[]);
|
||||
let n = (pos.len() / 3) as f64;
|
||||
pos.extend([5., 5., 5., 6., 6., 6., 7., 7., 7.]); // kollinear
|
||||
idx.extend([n, n + 1., n + 2.]);
|
||||
idx.extend([0., 0., 1.]); // doppelte Ecke
|
||||
idx.extend([0., 1., 9999.]); // Index ausserhalb
|
||||
let r = repair(&pos, &idx);
|
||||
assert_eq!(r.degenerate, 3);
|
||||
assert_eq!(r.idx.len(), 36);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offene_flaeche_bleibt_offen() {
|
||||
// Einzelnes Quadrat: Rand 100 % → gewollt offen
|
||||
let pos = [0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0.];
|
||||
let idx = [0., 1., 2., 0., 2., 3.];
|
||||
let r = repair(&pos, &idx);
|
||||
assert_eq!((r.holes, r.idx.len()), (0, 6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loch_wird_mit_faecher_geschlossen_und_ist_nach_aussen_orientiert() {
|
||||
// Würfel ohne zwei Dreiecke (Deckel) → 4-Kanten-Loch; der Randanteil-Schutz (5 %) lässt es offen …
|
||||
let (pos, idx) = soup(&[2, 3]);
|
||||
assert_eq!(repair(&pos, &idx).holes, 0);
|
||||
// … ohne Schutz wird es geschlossen und das Netz ist wieder ein Würfel (Volumen 1, richtig herum)
|
||||
let r = repair_with(&pos, &idx, 1.0);
|
||||
assert_eq!(r.holes, 1);
|
||||
assert_eq!(r.idx.len(), 36);
|
||||
assert!((volume(&r) - 1.0).abs() < 1e-12, "Volumen {}", volume(&r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grosses_loch_bleibt_offen() {
|
||||
// Kegelmantel ohne Boden: Randschleife mit 9 Kanten > MAX_HOLE_EDGES — wird nie geschlossen
|
||||
let n = 9;
|
||||
let mut pos = Vec::new();
|
||||
for k in 0..n {
|
||||
let a = std::f64::consts::TAU * k as f64 / n as f64;
|
||||
pos.extend([a.cos(), a.sin(), 0.0]);
|
||||
}
|
||||
pos.extend([0.0, 0.0, 1.0]);
|
||||
let mut idx = Vec::new();
|
||||
for k in 0..n {
|
||||
idx.extend([k as f64, ((k + 1) % n) as f64, n as f64]);
|
||||
}
|
||||
let r = repair_with(&pos, &idx, 1.0);
|
||||
assert_eq!(r.holes, 0);
|
||||
}
|
||||
}
|
||||
@@ -2212,6 +2212,12 @@ pub struct Wall {
|
||||
#[serde(rename = "sliceTermination", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub slice_termination: Option<SliceTermination>,
|
||||
/// An Dach anschliessen ([G2]): `undefined` = automatisch (die Wand endet an der Dach-Unterkante,
|
||||
/// wo ihre Krone darüber liegt — je Schicht, Giebel/Traufe/Grat/Kehle/Gaube), `true` = zusätzlich bis
|
||||
/// unter das Dach verlängert, `false` = Dächer schneiden die Wand nicht.
|
||||
#[serde(rename = "roofAttach", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub roof_attach: Option<bool>,
|
||||
/// Ansichtsschraffur ([100]): Drehung (Grad) des Oberflächenmusters dieses Elements gegenüber der
|
||||
/// Ausrichtung am Element (Default 0).
|
||||
#[serde(rename = "surfacePatternAngle", default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -3121,6 +3127,11 @@ pub struct Stair {
|
||||
#[serde(rename = "arrowStyle", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional, inline)]
|
||||
pub arrow_style: Option<StairArrowStyle>,
|
||||
/// Nur Wendel: Radius (Meter) der Mittelsäule (Spindel) im Zentrum. Fehlt er oder ist er
|
||||
/// ≤ 0, gibt es keine Säule.
|
||||
#[serde(rename = "centerColumn", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub center_column: Option<f64>,
|
||||
#[serde(flatten)]
|
||||
#[ts(skip)]
|
||||
pub extra: Extra,
|
||||
@@ -4119,6 +4130,9 @@ pub enum LayoutTableSource {
|
||||
/// Bauteilliste mit U-Werten ([71]).
|
||||
#[serde(rename = "elements")]
|
||||
Elements,
|
||||
/// [68] Erdarbeiten: Baugruben mit Abtrag/Auftrag/Hinterfüllung.
|
||||
#[serde(rename = "earthworks")]
|
||||
Earthworks,
|
||||
#[serde(other)]
|
||||
#[ts(skip)]
|
||||
Unknown,
|
||||
@@ -5086,6 +5100,53 @@ pub struct TerrainMesh {
|
||||
#[serde(rename = "vertexColors", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub vertex_colors: Option<Vec<f64>>,
|
||||
/// [T6] Äquidistanz der Höhenlinien im Grundriss in m (aus dem Netz neu erzeugt, inkl. Baugruben).
|
||||
/// Fehlt der Wert oder ist er ≤ 0, zeigt der Grundriss nur den Rahmen.
|
||||
#[serde(rename = "contourInterval", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub contour_interval: Option<f64>,
|
||||
/// [T6] Jede n-te Höhenlinie ist Zähllinie (dicker, beschriftet). Default 5.
|
||||
#[serde(rename = "contourIndexEvery", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub contour_index_every: Option<f64>,
|
||||
#[serde(flatten)]
|
||||
#[ts(skip)]
|
||||
pub extra: Extra,
|
||||
}
|
||||
|
||||
/// [68] Baugrube / Geländebearbeitung: Sohle als Umriss auf der Höhe `bottom` (m, Modell ±0.00).
|
||||
/// Ausserhalb steigt die Böschung mit `slope` (Grad, Default 45; je Kante `edgeSlopes`, 0 = Default)
|
||||
/// bis zum Gelände (Abtrag); liegt das Gelände tiefer, fällt eine Schüttung mit `fillSlope` (Default
|
||||
/// 33.7 ≈ 2:3) bis zum Gelände (Auftrag). Bermen: alle `bermHeight` m Höhe eine waagrechte Berme der
|
||||
/// Breite `bermWidth`. Schneidet jedes Gelände-Netz, das den Umriss enthält.
|
||||
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
|
||||
#[serde(default)]
|
||||
pub struct Excavation {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub layer: Option<String>,
|
||||
#[serde(rename = "categoryCode", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub category_code: Option<String>,
|
||||
pub outline: Vec<Vec2>,
|
||||
pub bottom: f64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub slope: Option<f64>,
|
||||
#[serde(rename = "fillSlope", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub fill_slope: Option<f64>,
|
||||
#[serde(rename = "edgeSlopes", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub edge_slopes: Option<Vec<f64>>,
|
||||
#[serde(rename = "bermWidth", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub berm_width: Option<f64>,
|
||||
#[serde(rename = "bermHeight", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub berm_height: Option<f64>,
|
||||
#[serde(flatten)]
|
||||
#[ts(skip)]
|
||||
pub extra: Extra,
|
||||
|
||||
@@ -125,6 +125,26 @@ pub enum DimFeature {
|
||||
/// Schnittpunkt der Wandlinie (`id`, `index`) mit der Wandlinie (`id2`, `index2`) — Ecken.
|
||||
#[serde(rename = "intersection")]
|
||||
Intersection,
|
||||
/// Punkt auf Rasterachse `index` des Achsrasters `id` beim Anteil `t` entlang der Achse ([112]).
|
||||
#[serde(rename = "axis")]
|
||||
Axis,
|
||||
/// Schnittpunkt der Rasterachsen `index` und `index2` des Achsrasters `id` ([112]).
|
||||
#[serde(rename = "axiscross")]
|
||||
AxisCross,
|
||||
/// Punkt auf dem Kreis/Bogen (2D-Kreis, -Bogen, Bogenwand) `id` beim Winkel `t` (Bogenmass);
|
||||
/// bei Bogenwänden `index` = Schichtgrenze (fehlt = Achse). Für Radius-, Durchmesser- und
|
||||
/// Bogenlängen-Bemassung ([38]).
|
||||
#[serde(rename = "rim")]
|
||||
Rim,
|
||||
}
|
||||
|
||||
/// Art einer Bemassung ([38]).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum DimKind {
|
||||
Radius,
|
||||
Diameter,
|
||||
Arc,
|
||||
}
|
||||
|
||||
/// Bezug eines Bemassungspunkts auf ein Element ([38]).
|
||||
@@ -180,6 +200,23 @@ pub enum SplineMode {
|
||||
Control,
|
||||
}
|
||||
|
||||
/// Eine Achse des Achsrasters: Beschriftung und Lage (Abstand bzw. Winkel/Radius, s. `Grid`).
|
||||
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
|
||||
#[serde(default)]
|
||||
pub struct GridAxis {
|
||||
pub label: String,
|
||||
pub pos: f64,
|
||||
}
|
||||
|
||||
/// Welche Achsenden eine Blase tragen.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum GridBubbles {
|
||||
Start,
|
||||
End,
|
||||
Both,
|
||||
}
|
||||
|
||||
/// Geometrie eines 2D-Zeichenelements (Tag `shape`).
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(tag = "shape")]
|
||||
@@ -332,6 +369,11 @@ pub enum Drawing2DGeom {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
refs: Option<Vec<Option<DimRef>>>,
|
||||
/// Art der Bemassung (fehlt = linear): Radius/Durchmesser (`pts` = Mittelpunkt, Punkt auf dem
|
||||
/// Kreis) und Bogenlänge (`pts` = Mittelpunkt, Bogenanfang, Bogenende).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional, inline)]
|
||||
kind: Option<DimKind>,
|
||||
},
|
||||
/// Höhenkote (SIA 400 B.5.4, Figur 18): Dreieck-Symbol + Höhenwert (Meter,
|
||||
/// ±0.00-Referenz frei wählbar, s. Norm) an einem Punkt. `kind` bestimmt
|
||||
@@ -404,6 +446,41 @@ pub enum Drawing2DGeom {
|
||||
/// gleichbleibende Lesbarkeit im Plan.
|
||||
#[serde(rename = "pointmarker")]
|
||||
Pointmarker { at: Vec2 },
|
||||
/// Achsraster ([112], `grid.rs`): rechtwinklig (`a` = Achsen parallel zur lokalen Y-Achse bei
|
||||
/// X = `pos`, Beschriftung 1, 2, 3 …; `b` = Achsen parallel zur lokalen X-Achse bei Y = `pos`,
|
||||
/// A, B, C …) oder radial (`radial`: `a` = Strahlen unter `pos` Grad, `b` = Ringe mit Radius
|
||||
/// `pos`). `origin`/`angle` (Bogenmass) legen das lokale System fest.
|
||||
#[serde(rename = "grid")]
|
||||
Grid {
|
||||
origin: Vec2,
|
||||
#[serde(default)]
|
||||
angle: f64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
radial: Option<bool>,
|
||||
a: Vec<GridAxis>,
|
||||
b: Vec<GridAxis>,
|
||||
/// Überstand der Achsen über die äusserste Querachse (Meter, Standard 1.5).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
extend: Option<f64>,
|
||||
/// Enden mit Achsblase (Standard Anfang und Ende).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional, inline)]
|
||||
bubbles: Option<GridBubbles>,
|
||||
/// Blasen-Durchmesser in Papier-mm (Standard 8).
|
||||
#[serde(rename = "bubbleMm", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
bubble_mm: Option<f64>,
|
||||
/// Geschosse, in denen das Raster gezeigt wird; fehlt oder leer = in allen.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
levels: Option<Vec<String>>,
|
||||
/// Im 3D-Modell als dünne Linien zeigen.
|
||||
#[serde(rename = "show3d", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
show_3d: Option<bool>,
|
||||
},
|
||||
#[serde(rename = "text")]
|
||||
Text {
|
||||
at: Vec2,
|
||||
@@ -527,6 +604,8 @@ pub enum ContextObject {
|
||||
TerrainMesh(TerrainMesh),
|
||||
#[serde(rename = "image")]
|
||||
Image(ContextImage),
|
||||
#[serde(rename = "excavation")]
|
||||
Excavation(Excavation),
|
||||
}
|
||||
|
||||
impl Default for Drawing2DGeom {
|
||||
|
||||
+146
-40
@@ -255,6 +255,10 @@ pub struct RWall {
|
||||
pub base_elevation: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub top_drop: Option<[f64; 2]>,
|
||||
/// Ebene Oberkante unter einer Dachfläche ([G2]): `[z am Anfang (Mittellinie), dz/dx, dz/dy]`
|
||||
/// (Grundriss-Meter). Übersteuert `topDrop`; `height` ist dann der höchste Eckwert über der UK.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub top_plane: Option<[f64; 3]>,
|
||||
pub color: Rgb,
|
||||
pub layers: Vec<()>,
|
||||
pub wall_id: String,
|
||||
@@ -525,13 +529,13 @@ fn compute_joins_by_floor(p: &Project) -> Result<HashMap<String, WallCuts>, Stri
|
||||
Ok(merged)
|
||||
}
|
||||
|
||||
fn floor_context(p: &Project, floor_id: &str) -> FloorContext {
|
||||
fn floor_context(p: &Project, floor_id: &str, with_ceilings: bool) -> FloorContext {
|
||||
let ceilings: Vec<CeilingIn> = p
|
||||
.ceilings
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter(|c| c.floor_id == floor_id && c.outline.len() >= 3)
|
||||
.filter(|c| with_ceilings && c.floor_id == floor_id && c.outline.len() >= 3)
|
||||
.map(|c| {
|
||||
let (z_bottom, z_top) = p.ceiling_vertical_extent(c);
|
||||
CeilingIn {
|
||||
@@ -552,7 +556,14 @@ fn floor_context(p: &Project, floor_id: &str) -> FloorContext {
|
||||
let eaves_z = p.roof_base_elevation(r);
|
||||
let geo = crate::roof::roof_geometry(&r.params(), eaves_z);
|
||||
let total: f64 = p.roof_layers(r).iter().fold(0.0, |s, l| s + l.thickness.max(0.0));
|
||||
RoofIn { eaves_z, total_thickness: total, eaves: geo.eaves, planes: geo.planes }
|
||||
let mut ri = RoofIn::new(eaves_z, total, geo.eaves, geo.planes);
|
||||
// Gauben ([G2]): unter dem Gaubeninneren endet die Wand an der Gaubendach-Unterkante.
|
||||
for d in r.dormers.as_deref().unwrap_or(&[]) {
|
||||
if let Some(g) = crate::dormer::geometry(p, r, d) {
|
||||
ri.facets.extend(g.under_facets());
|
||||
}
|
||||
}
|
||||
ri
|
||||
})
|
||||
.collect();
|
||||
FloorContext::new(ceilings, roofs)
|
||||
@@ -571,17 +582,13 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result<Vec<RWall>, String> {
|
||||
let joins = if layered { Some(compute_joins_by_floor(p)?) } else { None };
|
||||
let maps = wall_material_color_maps(p);
|
||||
let mut contexts: HashMap<&str, FloorContext> = HashMap::new();
|
||||
let empty = FloorContext::default();
|
||||
let mut out = Vec::new();
|
||||
let by_wall = p.openings_by_wall();
|
||||
for wall in &p.walls {
|
||||
let (bands, stacked) = resolve_wall_bands(p, &maps, wall, layered);
|
||||
let (z_bottom, z_top) = p.wall_vertical_extent(wall);
|
||||
let ctx = if layered {
|
||||
contexts.entry(wall.floor_id.as_str()).or_insert_with(|| floor_context(p, &wall.floor_id))
|
||||
} else {
|
||||
&empty
|
||||
};
|
||||
// Schnitt-Eingabe: nur die Dächer ([G2]); Decken rechnet der Schnitt selbst (Dominanz).
|
||||
let ctx = contexts.entry(wall.floor_id.as_str()).or_insert_with(|| floor_context(p, &wall.floor_id, layered));
|
||||
let win = wall_bands::WallIn {
|
||||
start: kv(wall.start),
|
||||
end: kv(wall.end),
|
||||
@@ -599,6 +606,7 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result<Vec<RWall>, String> {
|
||||
bands: bands.iter().map(|b| BandIn { thickness: b.thickness, priority: b.priority }).collect(),
|
||||
openings: wall_openings(p, wall, by_wall.get(wall.id.as_str()).map_or(&[][..], |v| v.as_slice()), true),
|
||||
cuts: if layered { joins.as_ref().and_then(|j| j.get(&wall.id)).cloned().unwrap_or_default() } else { WallCuts::default() },
|
||||
roof_attach: wall.roof_attach,
|
||||
reveals: if layered && stacked { wall_reveals(p, wall, by_wall.get(wall.id.as_str()).map_or(&[][..], |v| v.as_slice()), bands.len()) } else { Vec::new() },
|
||||
};
|
||||
// Bogenwand ([T2]): Sehnen-Teilwände mit radialen Gehrungen.
|
||||
@@ -618,8 +626,8 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result<Vec<RWall>, String> {
|
||||
let Some(b) = bands.get(piece.band) else { continue };
|
||||
// Schnitt-Eingabe der Bogen-Teilwände: radiale Gehrungen auch ohne Schichtband-Pfad.
|
||||
if arc.is_some() && !layered {
|
||||
piece.start_cut = win.cuts.start_cut;
|
||||
piece.end_cut = win.cuts.end_cut;
|
||||
piece.start_cut = piece.start_cut.or(win.cuts.start_cut);
|
||||
piece.end_cut = piece.end_cut.or(win.cuts.end_cut);
|
||||
}
|
||||
out.push(RWall {
|
||||
start: [piece.start.x, piece.start.y],
|
||||
@@ -628,6 +636,7 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result<Vec<RWall>, String> {
|
||||
height: piece.z_top - piece.z_bottom,
|
||||
base_elevation: piece.z_bottom,
|
||||
top_drop: piece.top_drop,
|
||||
top_plane: piece.top_plane.map(|c| [c[0] + c[1] * piece.start.x + c[2] * piece.start.y, c[1], c[2]]),
|
||||
color: b.color,
|
||||
layers: vec![],
|
||||
wall_id: wall.id.clone(),
|
||||
@@ -637,7 +646,10 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result<Vec<RWall>, String> {
|
||||
cut: band_cut_meta(b),
|
||||
start_cut: piece.start_cut.map(|l| [l.point.x, l.point.y, l.dir.x, l.dir.y]),
|
||||
end_cut: piece.end_cut.map(|l| [l.point.x, l.point.y, l.dir.x, l.dir.y]),
|
||||
joint: arc.map_or([false; 2], |a| [inner_joint(&a, wall, &keep, piece.start), inner_joint(&a, wall, &keep, piece.end)]),
|
||||
joint: {
|
||||
let j = arc.map_or([false; 2], |a| [inner_joint(&a, wall, &keep, piece.start), inner_joint(&a, wall, &keep, piece.end)]);
|
||||
[j[0] || piece.joint[0], j[1] || piece.joint[1]]
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -646,6 +658,68 @@ pub fn emit_walls(p: &Project, layered: bool) -> Result<Vec<RWall>, String> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Grundriss-Ecken eines Wandkörpers an seinen Schnittlinien: Anfang +n, Ende +n, Ende −n, Anfang −n
|
||||
/// (+n = linke Normale). `None` bei entarteter Achse.
|
||||
pub(crate) fn wall_footprint(w: &RWall) -> Option<[[f64; 2]; 4]> {
|
||||
let (dx, dy) = (w.end[0] - w.start[0], w.end[1] - w.start[1]);
|
||||
let l = hypot2(dx, dy);
|
||||
if !(l > 1e-9) || !(w.thickness > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let (ux, uy) = (dx / l, dy / l);
|
||||
let (nx, ny) = (-uy, ux);
|
||||
let h = w.thickness / 2.0;
|
||||
let at = |p: [f64; 2], o: f64, cut: Option<[f64; 4]>| -> [f64; 2] {
|
||||
let q = [p[0] + nx * o, p[1] + ny * o];
|
||||
let Some([cx, cy, ex, ey]) = cut else { return q };
|
||||
let den = ux * ey - uy * ex;
|
||||
if den.abs() < 1e-12 {
|
||||
return q;
|
||||
}
|
||||
let t = ((cx - q[0]) * ey - (cy - q[1]) * ex) / den;
|
||||
if t.is_finite() && t.abs() < l {
|
||||
[q[0] + ux * t, q[1] + uy * t]
|
||||
} else {
|
||||
q
|
||||
}
|
||||
};
|
||||
Some([at(w.start, h, w.start_cut), at(w.end, h, w.end_cut), at(w.end, -h, w.end_cut), at(w.start, -h, w.start_cut)])
|
||||
}
|
||||
|
||||
/// Oberkante eines Wandkörpers an einem Grundriss-Punkt (ebene Oberkante unter einem Dach, [G2]).
|
||||
pub(crate) fn wall_top_at(w: &RWall, q: [f64; 2]) -> f64 {
|
||||
let zt = w.base_elevation + w.height;
|
||||
match w.top_plane {
|
||||
Some(c) => (c[0] + c[1] * (q[0] - w.start[0]) + c[2] * (q[1] - w.start[1])).clamp(w.base_elevation, zt),
|
||||
None => zt,
|
||||
}
|
||||
}
|
||||
|
||||
/// Wandkörper mit ebener Oberkante als geschlossenes Netz (Modell x, y, z), ohne Löcher.
|
||||
pub(crate) fn wall_piece_mesh(w: &RWall) -> Option<crate::solid_bool::Mesh> {
|
||||
let fp = wall_footprint(w)?;
|
||||
let zb = w.base_elevation;
|
||||
let m = crate::solid_bool::Mesh::prism_between(&fp, &|_, _| zb, &|x, y| wall_top_at(w, [x, y]));
|
||||
(!m.is_empty()).then_some(m)
|
||||
}
|
||||
|
||||
/// Volumen eines Wandkörpers ohne Löcher: Grundfläche × Höhe im Schwerpunkt (exakt bei ebener Oberkante).
|
||||
pub(crate) fn wall_piece_volume(w: &RWall) -> f64 {
|
||||
let Some(q) = wall_footprint(w) else { return 0.0 };
|
||||
let (mut a, mut cx, mut cy) = (0.0, 0.0, 0.0);
|
||||
for i in 0..4 {
|
||||
let (p0, p1) = (q[i], q[(i + 1) % 4]);
|
||||
let c = p0[0] * p1[1] - p1[0] * p0[1];
|
||||
a += c;
|
||||
cx += (p0[0] + p1[0]) * c;
|
||||
cy += (p0[1] + p1[1]) * c;
|
||||
}
|
||||
if a.abs() < 1e-15 {
|
||||
return 0.0;
|
||||
}
|
||||
(a / 2.0).abs() * (wall_top_at(w, [cx / (3.0 * a), cy / (3.0 * a)]) - w.base_elevation)
|
||||
}
|
||||
|
||||
// ── Öffnungs-Einbauteile (Glas, Rahmen, Sprossen, Bank, Kasten) ─────────────
|
||||
|
||||
/// Farbe je Bauteil-Klasse (Index = `Part` in `openings3d.rs`).
|
||||
@@ -1058,7 +1132,7 @@ fn rail_rgb() -> Rgb {
|
||||
hex_to_rgb("#74797f", SLAB_RGB)
|
||||
}
|
||||
|
||||
/// Flache Eingabe der Treppen für `stairs3d` (23 Zahlen je Treppe); `wanted` wählt vor.
|
||||
/// Flache Eingabe der Treppen für `stairs3d` (24 Zahlen je Treppe); `wanted` wählt vor.
|
||||
fn stair_input<'a>(p: &'a Project, wanted: impl Fn(&Stair, Option<&StairType>) -> bool) -> Option<(Vec<(usize, &'a Stair)>, Vec<f64>)> {
|
||||
let mut stairs: Vec<(usize, &Stair)> = Vec::new();
|
||||
let mut types: Vec<Option<&StairType>> = Vec::new();
|
||||
@@ -1093,6 +1167,7 @@ fn stair_input<'a>(p: &'a Project, wanted: impl Fn(&Stair, Option<&StairType>) -
|
||||
Some(StairTypeRailing::Beide) => 3.0,
|
||||
_ => 0.0,
|
||||
});
|
||||
buf.push(s.center_column.filter(|r| r.is_finite() && *r > 0.0).unwrap_or(0.0));
|
||||
}
|
||||
Some((stairs, buf))
|
||||
}
|
||||
@@ -1123,17 +1198,17 @@ fn meshes_of(meshes: Vec<crate::mesh3d::Mesh>, color: Rgb) -> Vec<RMesh> {
|
||||
meshes.into_iter().map(|m| RMesh { positions: m.positions, indices: m.indices, kind: "extrusion", color, vertex_colors: None, material_index: None }).collect()
|
||||
}
|
||||
|
||||
/// Glatte Ortbeton-Laufplatten gerader Treppen (`emitStairMeshes`).
|
||||
/// Glatte Ortbeton-Laufplatten gerader Treppen und Wendelfläche (Schraubenfläche) von Wendeltreppen (`emitStairMeshes`).
|
||||
pub fn emit_stair_meshes(p: &Project) -> Vec<RMesh> {
|
||||
match stair_input(p, |s, st| st.is_some_and(|t| t.structure == StairTypeStructure::Beton) && s.shape == StairShape::Straight) {
|
||||
match stair_input(p, |s, st| st.is_some_and(|t| t.structure == StairTypeStructure::Beton) && matches!(s.shape, StairShape::Straight | StairShape::Spiral)) {
|
||||
Some((_, buf)) => meshes_of(crate::stairs3d::slab_meshes(&buf), stair_rgb()),
|
||||
None => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Handlauf und Pfosten gerader Treppen (`emitStairRailings`).
|
||||
/// Handlauf und Pfosten gerader Treppen (`emitStairRailings`); bei Wendeltreppen als Schraubensweep.
|
||||
pub fn emit_stair_railings(p: &Project) -> Vec<RMesh> {
|
||||
match stair_input(p, |s, st| s.shape == StairShape::Straight && st.and_then(|t| t.railing).is_some_and(|r| r != StairTypeRailing::Keine)) {
|
||||
match stair_input(p, |s, st| matches!(s.shape, StairShape::Straight | StairShape::Spiral) && st.and_then(|t| t.railing).is_some_and(|r| r != StairTypeRailing::Keine)) {
|
||||
Some((_, buf)) => meshes_of(crate::stairs3d::railings(&buf), rail_rgb()),
|
||||
None => vec![],
|
||||
}
|
||||
@@ -1712,14 +1787,18 @@ pub fn emit_context_meshes(p: &Project) -> Vec<RMesh> {
|
||||
let mut out = Vec::new();
|
||||
for obj in p.context.as_deref().unwrap_or(&[]) {
|
||||
match obj {
|
||||
ContextObject::TerrainMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => out.push(RMesh {
|
||||
positions: m.positions.clone(),
|
||||
indices: indices_u32(&m.indices),
|
||||
kind: "terrain",
|
||||
color: TERRAIN_RGB,
|
||||
vertex_colors: m.vertex_colors.clone().filter(|v| !v.is_empty()),
|
||||
material_index: None,
|
||||
}),
|
||||
ContextObject::TerrainMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => {
|
||||
// [T6] Baugruben schneiden das Gelände; Höhen im Modellbezug (Luftbild-Farben nur ungeändert).
|
||||
let (pos, idx, changed) = crate::excavation::terrain_model_mesh(p, m);
|
||||
out.push(RMesh {
|
||||
positions: pos.into_owned(),
|
||||
indices: indices_u32(&idx),
|
||||
kind: "terrain",
|
||||
color: TERRAIN_RGB,
|
||||
vertex_colors: if changed { None } else { m.vertex_colors.clone().filter(|v| !v.is_empty()) },
|
||||
material_index: None,
|
||||
})
|
||||
}
|
||||
ContextObject::ImportedMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => out.push(RMesh {
|
||||
positions: m.positions.clone(),
|
||||
indices: indices_u32(&m.indices),
|
||||
@@ -1810,24 +1889,28 @@ fn for_each_drawing_chunk(p: &Project, with_color: bool, mut f: impl FnMut(&[f64
|
||||
buf.truncate(1);
|
||||
};
|
||||
for d in &p.drawings2d {
|
||||
let (kind, pts): (f64, Vec<Vec2>) = match &d.geom {
|
||||
Drawing2DGeom::Line { a, b } => (1.0, vec![*a, *b]),
|
||||
Drawing2DGeom::Rect { min, max } => (3.0, vec![*min, *max]),
|
||||
Drawing2DGeom::Polyline { pts, .. } => (2.0, pts.clone()),
|
||||
// Teile einer Zeichnung: (Art, Punkte); ein Achsraster mit `show3d` liefert je Achse eines.
|
||||
let parts: Vec<(f64, Vec<Vec2>)> = match &d.geom {
|
||||
Drawing2DGeom::Line { a, b } => vec![(1.0, vec![*a, *b])],
|
||||
Drawing2DGeom::Rect { min, max } => vec![(3.0, vec![*min, *max])],
|
||||
Drawing2DGeom::Polyline { pts, .. } => vec![(2.0, pts.clone())],
|
||||
Drawing2DGeom::Grid { show_3d: Some(true), .. } => crate::grid::Spec::of(&d.geom).map(|s| crate::grid::polylines_3d(&s)).unwrap_or_default().into_iter().map(|q| (2.0, q.into_iter().map(|(x, y)| Vec2 { x, y }).collect())).collect(),
|
||||
_ => continue,
|
||||
};
|
||||
let need = 7 + 2 * pts.len();
|
||||
if buf.len() + need > CHUNK_DOUBLES {
|
||||
flush(&mut buf, &mut ids, &mut f);
|
||||
}
|
||||
let closed = matches!(&d.geom, Drawing2DGeom::Polyline { closed: true, .. });
|
||||
let elev = *elevations.entry(d.level_id.as_str()).or_insert_with(|| p.floor(&d.level_id).map_or(0.0, |l| l.base_elevation.unwrap_or(0.0)) + DRAWING_LINE_ELEVATION_EPS);
|
||||
let rgb = if with_color { drawing_color(d, &by_category, &by_line_style) } else { [0.0; 3] };
|
||||
let closed = matches!(&d.geom, Drawing2DGeom::Polyline { closed: true, .. });
|
||||
buf.extend([kind, elev, rgb[0], rgb[1], rgb[2], if closed { 1.0 } else { 0.0 }, pts.len() as f64]);
|
||||
for q in &pts {
|
||||
buf.extend([q.x, q.y]);
|
||||
for (kind, pts) in parts {
|
||||
let need = 7 + 2 * pts.len();
|
||||
if buf.len() + need > CHUNK_DOUBLES {
|
||||
flush(&mut buf, &mut ids, &mut f);
|
||||
}
|
||||
buf.extend([kind, elev, rgb[0], rgb[1], rgb[2], if closed { 1.0 } else { 0.0 }, pts.len() as f64]);
|
||||
for q in &pts {
|
||||
buf.extend([q.x, q.y]);
|
||||
}
|
||||
ids.push(d);
|
||||
}
|
||||
ids.push(d);
|
||||
}
|
||||
flush(&mut buf, &mut ids, &mut f);
|
||||
}
|
||||
@@ -1982,10 +2065,14 @@ pub fn pick_geometry(p: &Project) -> Result<PickGeometry, String> {
|
||||
let mut context_meshes = Vec::new();
|
||||
for obj in p.context.as_deref().unwrap_or(&[]) {
|
||||
let (pos, idx, id) = match obj {
|
||||
ContextObject::TerrainMesh(m) => (&m.positions, &m.indices, &m.id),
|
||||
ContextObject::ImportedMesh(m) => (&m.positions, &m.indices, &m.id),
|
||||
ContextObject::TerrainMesh(m) => {
|
||||
let (pos, idx, _) = crate::excavation::terrain_model_mesh(p, m);
|
||||
(pos, idx, &m.id)
|
||||
}
|
||||
ContextObject::ImportedMesh(m) => (std::borrow::Cow::Borrowed(m.positions.as_slice()), std::borrow::Cow::Borrowed(m.indices.as_slice()), &m.id),
|
||||
_ => continue,
|
||||
};
|
||||
let (pos, idx) = (&*pos, &*idx);
|
||||
let vcount = pos.len() / 3;
|
||||
let at = |i: usize| -> V3 { [pos[i * 3], pos[i * 3 + 2], -pos[i * 3 + 1]] };
|
||||
let mut tris: Vec<Tri> = Vec::new();
|
||||
@@ -2015,6 +2102,25 @@ pub fn pick_geometry(p: &Project) -> Result<PickGeometry, String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [112] Achsraster mit `show3d` erscheint als Boden-Spur (eine Strecke je Achse), ohne Flag nicht.
|
||||
#[test]
|
||||
fn achsraster_im_3d_nur_mit_flag() {
|
||||
let mk = |show: serde_json::Value| -> Project {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "openings": [], "walls": [],
|
||||
"drawingLevels": [{"id": "F", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 1.0}],
|
||||
"drawings2d": [{"id": "G", "type": "drawing2d", "levelId": "F", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 4}], "b": [{"label": "A", "pos": 0}], "show3d": show}}]
|
||||
}))
|
||||
.unwrap()
|
||||
};
|
||||
assert!(drawing_line_verts(&mk(serde_json::json!(false))).is_empty());
|
||||
let v = drawing_line_verts(&mk(serde_json::json!(true)));
|
||||
// 3 Achsen × 1 Segment × 2 Endpunkte × 6 Zahlen.
|
||||
assert_eq!(v.len(), 3 * 2 * 6);
|
||||
assert!((v[1] - 1.01).abs() < 1e-4, "Höhe = Geschoss-UK + 0.01: {}", v[1]);
|
||||
}
|
||||
|
||||
/// Walmdach 12×7 m: zwei Trapeze + zwei Walm-Dreiecke, First (3,3)-(8,3).
|
||||
fn walm_planes() -> Vec<Vec<V3>> {
|
||||
vec![
|
||||
|
||||
@@ -65,6 +65,7 @@ pub fn plan_context(c: &Ctx, out: &mut Vec<Primitive>) {
|
||||
ContextObject::ContourSet(s) => s.category_code.as_deref(),
|
||||
ContextObject::TerrainMesh(t) => t.category_code.as_deref(),
|
||||
ContextObject::Image(i) => i.category_code.as_deref(),
|
||||
ContextObject::Excavation(e) => e.category_code.as_deref(),
|
||||
};
|
||||
if code.is_some_and(|k| !c.shown(k)) {
|
||||
continue;
|
||||
@@ -99,12 +100,109 @@ pub fn plan_context(c: &Ctx, out: &mut Vec<Primitive>) {
|
||||
}
|
||||
out.push(pick_band(q, Some(&t.id), None));
|
||||
}
|
||||
terrain_contours(c, t, out);
|
||||
}
|
||||
ContextObject::Excavation(e) => excavation_lines(c, e, out),
|
||||
ContextObject::Image(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const TERRAIN_INK: &str = "#7a5b3a";
|
||||
const EXCAVATION_INK: &str = "#1f242c";
|
||||
|
||||
fn ink_line(a: Vec2, b: Vec2, w: f64, color: &str, dash: Option<Vec<f64>>) -> Primitive {
|
||||
Primitive::Line { a, b, cls: "context-line".into(), weight_mm: w, dash: dash.map(Some), zigzag: None, motif: None, color: Some(color.into()), drawing_id: None, opening_id: None, stair_id: None, greyed: None, opacity: None }
|
||||
}
|
||||
|
||||
/// [T6] Höhenlinien aus dem Gelände-Netz (samt Baugruben) in der Äquidistanz `contourInterval`; jede
|
||||
/// `contourIndexEvery`-te ist Zähllinie (dicker, mit Höhenangabe, lesbar gedreht).
|
||||
fn terrain_contours(c: &Ctx, t: &TerrainMesh, out: &mut Vec<Primitive>) {
|
||||
let Some(iv) = t.contour_interval.filter(|v| v.is_finite() && *v > 0.0) else { return };
|
||||
let every = t.contour_index_every.filter(|v| v.is_finite() && *v >= 1.0).map_or(5, |v| v.round() as i64);
|
||||
let st = crate::excavation::site_terrain(c.p, t);
|
||||
let text_h = 0.002 * c.a.scale.max(1.0);
|
||||
for l in crate::terrain::isolines(st.current(), iv, 0.0) {
|
||||
let k = (l.level / iv).round() as i64;
|
||||
let index = k.rem_euclid(every) == 0;
|
||||
let w = if index { 0.25 } else { 0.1 };
|
||||
let n = l.pts.len();
|
||||
let segs = if l.closed { n } else { n - 1 };
|
||||
for i in 0..segs {
|
||||
let (a, b) = (l.pts[i], l.pts[(i + 1) % n]);
|
||||
out.push(ink_line(v2(a[0], a[1]), v2(b[0], b[1]), w, TERRAIN_INK, None));
|
||||
}
|
||||
if !index {
|
||||
continue;
|
||||
}
|
||||
// Beschriftung in der Mitte der Linie (nur, wenn sie lang genug ist).
|
||||
let len: f64 = (0..segs).map(|i| (l.pts[(i + 1) % n][0] - l.pts[i][0]).hypot(l.pts[(i + 1) % n][1] - l.pts[i][1])).sum();
|
||||
if len < 12.0 * text_h {
|
||||
continue;
|
||||
}
|
||||
let mut acc = 0.0;
|
||||
for i in 0..segs {
|
||||
let (a, b) = (l.pts[i], l.pts[(i + 1) % n]);
|
||||
let d = (b[0] - a[0]).hypot(b[1] - a[1]);
|
||||
if acc + d >= len / 2.0 && d > 0.0 {
|
||||
let f = (len / 2.0 - acc) / d;
|
||||
let mut ang = (b[1] - a[1]).atan2(b[0] - a[0]);
|
||||
if ang > std::f64::consts::FRAC_PI_2 || ang <= -std::f64::consts::FRAC_PI_2 {
|
||||
ang += std::f64::consts::PI;
|
||||
}
|
||||
// Text mittig auf die Linie (Breite ≈ 0.6 · Höhe je Zeichen, Grundlinie ≈ −0.35 · Höhe).
|
||||
let text = crate::js_fmt::to_fixed(l.level, if iv.fract() == 0.0 { 0 } else { 1 });
|
||||
let half = 0.3 * text_h * text.chars().count() as f64;
|
||||
let (c, s) = (ang.cos(), ang.sin());
|
||||
let m = (a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f);
|
||||
out.push(Primitive::DrawingText {
|
||||
at: v2(m.0 - c * half + s * 0.35 * text_h, m.1 - s * half - c * 0.35 * text_h),
|
||||
text,
|
||||
height_m: text_h,
|
||||
angle: ang,
|
||||
color: TERRAIN_INK.into(),
|
||||
marks: None,
|
||||
wrap_width: None,
|
||||
doc: None,
|
||||
drawing_id: None,
|
||||
greyed: None,
|
||||
opacity: None,
|
||||
});
|
||||
break;
|
||||
}
|
||||
acc += d;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [68] Baugrube im Grundriss: Sohle (Böschungsfuss) und Böschungsoberkante, Böschungsschraffur.
|
||||
fn excavation_lines(c: &Ctx, e: &Excavation, out: &mut Vec<Primitive>) {
|
||||
let ring: Vec<Vec2> = e.outline.iter().copied().filter(|q| q.x.is_finite() && q.y.is_finite()).collect();
|
||||
if ring.len() < 3 {
|
||||
return;
|
||||
}
|
||||
for i in 0..ring.len() {
|
||||
out.push(ink_line(ring[i], ring[(i + 1) % ring.len()], 0.25, EXCAVATION_INK, None));
|
||||
}
|
||||
out.push(pick_band(ring.clone(), Some(&e.id), None));
|
||||
let spacing = (0.004 * c.a.scale.max(1.0)).max(0.2);
|
||||
for t in crate::excavation::terrains(c.p) {
|
||||
let st = crate::excavation::site_terrain(c.p, t);
|
||||
let Some((_, spec, daylight)) = st.items.iter().find(|(id, ..)| *id == e.id) else { continue };
|
||||
for l in daylight {
|
||||
for w in l.windows(2) {
|
||||
out.push(ink_line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), 0.18, EXCAVATION_INK, None));
|
||||
}
|
||||
}
|
||||
if let Some(before) = crate::excavation::terrain_before(&st, &e.id) {
|
||||
for (a, b) in crate::excavation::slope_hatch(&before, spec, spacing) {
|
||||
out.push(ink_line(v2(a[0], a[1]), v2(b[0], b[1]), 0.1, EXCAVATION_INK, None));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// Kurz-Tag eines Schnitt-Labels: letztes Wort des Namens, sonst der ganze (getrimmte) Name.
|
||||
pub fn section_label_tag(name: &str) -> String {
|
||||
let t = js_trim(name);
|
||||
@@ -185,6 +283,36 @@ pub fn plan_section_lines(c: &Ctx, out: &mut Vec<Primitive>) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [T6]/[68] Höhenlinien (Zähllinien dicker + beschriftet) und Baugrube (Sohle, Oberkante, Schraffur).
|
||||
#[test]
|
||||
fn hoehenlinien_und_baugrube() {
|
||||
// Ebene schräg: z = x/10 über 0..40 m → Linien bei x = 10, 20, 30 (Äquidistanz 1), Zähllinie bei 0/5 m.
|
||||
let t = TerrainMesh {
|
||||
id: "t".into(),
|
||||
positions: vec![0.0, 0.0, 0.0, 60.0, 0.0, 6.0, 60.0, 40.0, 6.0, 0.0, 40.0, 0.0],
|
||||
indices: vec![0.0, 1.0, 2.0, 0.0, 2.0, 3.0],
|
||||
category_code: Some("02".into()),
|
||||
contour_interval: Some(1.0),
|
||||
..Default::default()
|
||||
};
|
||||
let pit = Excavation {
|
||||
id: "bg".into(),
|
||||
outline: vec![v2(20.0, 15.0), v2(30.0, 15.0), v2(30.0, 25.0), v2(20.0, 25.0)],
|
||||
bottom: 1.0,
|
||||
..Default::default()
|
||||
};
|
||||
let p = Project { context: Some(vec![ContextObject::TerrainMesh(t), ContextObject::Excavation(pit)]), ..Default::default() };
|
||||
let a = super::super::domains::PlanArgs::parse(1.0, r#"{"show": ["02"], "scale": 100}"#).unwrap();
|
||||
let mut out = Vec::new();
|
||||
plan_context(&Ctx::new(&p, &a), &mut out);
|
||||
let w = |m: f64| out.iter().filter(|q| matches!(q, Primitive::Line { weight_mm, color: Some(c), .. } if *weight_mm == m && c == TERRAIN_INK)).count();
|
||||
assert!(w(0.1) > 4 && w(0.25) > 0, "{} {}", w(0.1), w(0.25));
|
||||
let labels: Vec<&str> = out.iter().filter_map(|q| if let Primitive::DrawingText { text, .. } = q { Some(text.as_str()) } else { None }).collect();
|
||||
assert!(labels.contains(&"5"), "{labels:?}");
|
||||
let ex = out.iter().filter(|q| matches!(q, Primitive::Line { color: Some(c), .. } if c == EXCAVATION_INK)).count();
|
||||
assert!(ex > 20, "{ex}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn label_tag_wie_ts() {
|
||||
assert_eq!(section_label_tag("Schnitt A"), "A");
|
||||
|
||||
@@ -54,6 +54,9 @@ pub fn symbol_factor(p: &Project, level: &str) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rand um die Achsen im Ausmass, damit die Blasen ins Bild passen (Meter).
|
||||
const GRID_BUBBLE_MARGIN_M: f64 = 1.0;
|
||||
|
||||
// Massstabsbalken, Papier-mm.
|
||||
const SCALEBAR_HEIGHT_MM: f64 = 1.5;
|
||||
const SCALEBAR_TICK_MM: f64 = 1.0;
|
||||
@@ -211,6 +214,7 @@ pub fn shape_name(g: &Drawing2DGeom) -> &'static str {
|
||||
Drawing2DGeom::Detailref { .. } => "detailref",
|
||||
Drawing2DGeom::Scalebar { .. } => "scalebar",
|
||||
Drawing2DGeom::Pointmarker { .. } => "pointmarker",
|
||||
Drawing2DGeom::Grid { .. } => "grid",
|
||||
Drawing2DGeom::Text { .. } => "text",
|
||||
Drawing2DGeom::Block { .. } => "block",
|
||||
Drawing2DGeom::Image { .. } => "image",
|
||||
@@ -738,9 +742,22 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed
|
||||
em.seg(q[q.len() - 1], q[0]);
|
||||
}
|
||||
}
|
||||
Drawing2DGeom::Dimension { pts, offset, gap_mm, overshoot_mm, tick_len_mm, text_height_mm, line_weight_mm, ext_weight_mm, tick_weight_mm, text_offsets_mm, refs } => {
|
||||
Drawing2DGeom::Dimension { pts, offset, gap_mm, overshoot_mm, tick_len_mm, text_height_mm, line_weight_mm, ext_weight_mm, tick_weight_mm, text_offsets_mm, refs, kind } => {
|
||||
let mm = |x: f64| mm_to_model(x, scale);
|
||||
for i in 0..pts.len().saturating_sub(1) {
|
||||
if let Some(k) = kind {
|
||||
let st = DimStyle {
|
||||
gap: mm(gap_mm.unwrap_or(DIM_GAP_MM)),
|
||||
overshoot: mm(overshoot_mm.unwrap_or(DIM_OVERSHOOT_MM)),
|
||||
tick_len: mm(tick_len_mm.unwrap_or(DIM_TICK_LEN_MM)),
|
||||
text_height: mm(text_height_mm.unwrap_or(DIM_TEXT_HEIGHT_MM)),
|
||||
line_weight: line_weight_mm.unwrap_or(em.weight),
|
||||
ext_weight: ext_weight_mm.unwrap_or(em.weight),
|
||||
tick_weight: tick_weight_mm.unwrap_or(em.weight * 2.0),
|
||||
text_offset: (0.0, 0.0),
|
||||
};
|
||||
dimension_round(&mut em, pts, *offset, *k, &st);
|
||||
}
|
||||
for i in 0..(if kind.is_some() { 0 } else { pts.len().saturating_sub(1) }) {
|
||||
let st = DimStyle {
|
||||
gap: mm(gap_mm.unwrap_or(DIM_GAP_MM)),
|
||||
overshoot: mm(overshoot_mm.unwrap_or(DIM_OVERSHOOT_MM)),
|
||||
@@ -817,6 +834,11 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed
|
||||
em.seg(v(at.x - cross, at.y), v(at.x + cross, at.y));
|
||||
em.seg(v(at.x, at.y - cross), v(at.x, at.y + cross));
|
||||
}
|
||||
Drawing2DGeom::Grid { bubble_mm, .. } => {
|
||||
if let Some(spec) = crate::grid::Spec::of(geom) {
|
||||
emit_grid(&mut em, &spec, crate::grid::bubble_diameter(*bubble_mm, scale), scale);
|
||||
}
|
||||
}
|
||||
Drawing2DGeom::Text { at, text: s, height, angle, width, marks, doc, leader_target, leader_bend_points, path_pts } => {
|
||||
let color = marks.as_ref().and_then(|m| m.color.clone()).unwrap_or_else(|| em.color.to_string());
|
||||
if let Some(path) = path_pts.as_ref().filter(|q| q.len() >= 2) {
|
||||
@@ -941,6 +963,110 @@ fn dimension_segment(em: &mut Em, a: Vec2, b: Vec2, offset: f64, st: &DimStyle)
|
||||
em.sink.push(p, 0);
|
||||
}
|
||||
|
||||
/// Achsraster ([112]): Achsen strichpunktiert, an den Enden Blasen mit der Beschriftung.
|
||||
fn emit_grid(em: &mut Em, spec: &crate::grid::Spec, diameter: f64, scale: f64) {
|
||||
use crate::grid::Shape;
|
||||
let mm = |x: f64| mm_to_model(x, scale);
|
||||
let dash = [mm(12.0), mm(2.5), mm(1.5), mm(2.5)];
|
||||
let dash_ref = em.sink.fresh_ref();
|
||||
let w = jsnum::min(em.weight, XLINE_WEIGHT_MM.max(0.18));
|
||||
let r = diameter / 2.0;
|
||||
let text_h = diameter * 0.5;
|
||||
for ax in spec.axes() {
|
||||
match ax.shape {
|
||||
Shape::Line { a, b } => em.line(v(a.0, a.1), v(b.0, b.1), w, Some(&dash), dash_ref),
|
||||
Shape::Arc { c, r: rad, a0, a1 } => {
|
||||
let dash_v = Some(dash.to_vec());
|
||||
if a1 - a0 >= std::f64::consts::TAU - 1e-9 {
|
||||
em.sink.push(
|
||||
Primitive::DrawingCircle { center: v(c.0, c.1), r: rad, fill: "none".into(), stroke: em.color.into(), weight_mm: w, dash: Some(dash_v), drawing_id: Some(em.id.into()), greyed: Some(em.greyed), opacity: None },
|
||||
dash_ref,
|
||||
);
|
||||
} else {
|
||||
em.sink.push(
|
||||
Primitive::DrawingArc { center: v(c.0, c.1), r: rad, a0, a1, stroke: em.color.into(), weight_mm: w, dash: Some(dash_v), drawing_id: Some(em.id.into()), greyed: Some(em.greyed), opacity: None },
|
||||
dash_ref,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (end, dir) in ax.bubbles.iter().flatten() {
|
||||
let c = v(end.0 + dir.0 * r, end.1 + dir.1 * r);
|
||||
em.circle(c, r, "none", Some(None));
|
||||
let n = ax.label.chars().count() as f64;
|
||||
em.text(v(c.x - text_h * 0.3 * n, c.y - text_h * 0.35), ax.label.clone(), text_h);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Radius-, Durchmesser- und Bogenlängen-Mass ([38]): `pts` = Mittelpunkt, Punkt auf dem Kreis
|
||||
/// (bzw. Bogenanfang, Bogenende); Mass auf dem Rand mit Massstrichen und Masszahl.
|
||||
fn dimension_round(em: &mut Em, pts: &[Vec2], offset: f64, kind: DimKind, st: &DimStyle) {
|
||||
let (Some(&c), Some(&p)) = (pts.first(), pts.get(1)) else { return };
|
||||
let r = hypot2(p.x - c.x, p.y - c.y);
|
||||
if !(r > 1e-6) {
|
||||
return;
|
||||
}
|
||||
let (ux, uy) = ((p.x - c.x) / r, (p.y - c.y) / r);
|
||||
let tick = |em: &mut Em, q: Vec2, tx: f64, ty: f64| {
|
||||
let (nx, ny) = (-ty, tx);
|
||||
let (dx, dy) = ((tx + nx) / std::f64::consts::SQRT_2, (ty + ny) / std::f64::consts::SQRT_2);
|
||||
let h = st.tick_len / 2.0;
|
||||
em.line(v(q.x - dx * h, q.y - dy * h), v(q.x + dx * h, q.y + dy * h), st.tick_weight, None, 0);
|
||||
};
|
||||
let label = |em: &mut Em, at: Vec2, ang: f64, s: String| {
|
||||
let mut a = ang;
|
||||
if jsnum::cos(a) < 0.0 {
|
||||
a += std::f64::consts::PI;
|
||||
}
|
||||
let up = v(-jsnum::sin(a), jsnum::cos(a));
|
||||
let q = v(at.x + up.x * st.text_height * 0.6, at.y + up.y * st.text_height * 0.6);
|
||||
let pr = text(q, s, st.text_height, a, em.color, em.greyed, Some(em.id));
|
||||
em.sink.push(pr, 0);
|
||||
};
|
||||
let (dash, dref) = (em.dash.clone(), em.dash_ref);
|
||||
let dash = dash.as_deref();
|
||||
match kind {
|
||||
DimKind::Radius => {
|
||||
em.line(c, p, st.line_weight, dash, dref);
|
||||
tick(em, p, ux, uy);
|
||||
tick(em, c, ux, uy);
|
||||
let mid = v((c.x + p.x) / 2.0, (c.y + p.y) / 2.0);
|
||||
label(em, mid, jsnum::atan2(uy, ux), format!("R {}", to_fixed(r, 2)));
|
||||
}
|
||||
DimKind::Diameter => {
|
||||
let q = v(c.x - ux * r, c.y - uy * r);
|
||||
em.line(q, p, st.line_weight, dash, dref);
|
||||
tick(em, p, ux, uy);
|
||||
tick(em, q, ux, uy);
|
||||
label(em, c, jsnum::atan2(uy, ux), format!("\u{d8} {}", to_fixed(2.0 * r, 2)));
|
||||
}
|
||||
DimKind::Arc => {
|
||||
let Some(&p1) = pts.get(2) else { return };
|
||||
let a0 = jsnum::atan2(p.y - c.y, p.x - c.x);
|
||||
let a1 = jsnum::atan2(p1.y - c.y, p1.x - c.x);
|
||||
let sweep = (a1 - a0).rem_euclid(std::f64::consts::TAU);
|
||||
let rr = r + offset;
|
||||
if !(rr > 1e-6) || !(sweep > 1e-9) {
|
||||
return;
|
||||
}
|
||||
let sign = if offset >= 0.0 { 1.0 } else { -1.0 };
|
||||
for (a, pt) in [(a0, p), (a1, p1)] {
|
||||
let (cx, cy) = (jsnum::cos(a), jsnum::sin(a));
|
||||
em.line(v(pt.x + cx * st.gap * sign, pt.y + cy * st.gap * sign), v(c.x + cx * (rr + st.overshoot * sign), c.y + cy * (rr + st.overshoot * sign)), st.ext_weight, dash, dref);
|
||||
tick(em, v(c.x + cx * rr, c.y + cy * rr), -cy, cx);
|
||||
}
|
||||
em.sink.push(
|
||||
Primitive::DrawingArc { center: c, r: rr, a0, a1: a0 + sweep, stroke: em.color.into(), weight_mm: st.line_weight, dash: Some(dash.map(|x| x.to_vec())), drawing_id: Some(em.id.into()), greyed: Some(em.greyed), opacity: None },
|
||||
if dash.is_some() { dref } else { 0 },
|
||||
);
|
||||
let am = a0 + sweep / 2.0;
|
||||
let at = v(c.x + jsnum::cos(am) * rr, c.y + jsnum::sin(am) * rr);
|
||||
label(em, at, am + std::f64::consts::FRAC_PI_2, format!("L {}", to_fixed(r * sweep, 2)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dreht die Umlauf-Orientierung um (Spiegelung)? Flächenvorzeichen eines Test-Dreiecks.
|
||||
fn reverses_orientation(f: &dyn Fn(Vec2) -> Vec2) -> bool {
|
||||
let (p0, p1, p2) = (f(v(0.0, 0.0)), f(v(1.0, 0.0)), f(v(0.0, 1.0)));
|
||||
@@ -986,6 +1112,19 @@ pub fn mv_geom(g: &Drawing2DGeom, f: &dyn Fn(Vec2) -> Vec2) -> Drawing2DGeom {
|
||||
G::Detailref { at, label, sheet_layout_id, sheet_label } => G::Detailref { at: f(*at), label: label.clone(), sheet_layout_id: sheet_layout_id.clone(), sheet_label: sheet_label.clone() },
|
||||
G::Scalebar { at, segment_length, segments } => G::Scalebar { at: f(*at), segment_length: *segment_length, segments: *segments },
|
||||
G::Pointmarker { at } => G::Pointmarker { at: f(*at) },
|
||||
G::Grid { origin, angle, radial, a, b, extend, bubbles, bubble_mm, levels, show_3d } => {
|
||||
let o = f(*origin);
|
||||
let ex = f(v(origin.x + angle.cos(), origin.y + angle.sin()));
|
||||
let flip = reverses_orientation(f);
|
||||
let neg = |l: &Vec<GridAxis>| l.iter().map(|x| GridAxis { label: x.label.clone(), pos: -x.pos }).collect::<Vec<_>>();
|
||||
let ang = (ex.y - o.y).atan2(ex.x - o.x);
|
||||
let (a2, b2) = match (flip, radial == &Some(true)) {
|
||||
(false, _) => (a.clone(), b.clone()),
|
||||
(true, false) => (a.clone(), neg(b)),
|
||||
(true, true) => (neg(a), b.clone()),
|
||||
};
|
||||
G::Grid { origin: o, angle: ang, radial: *radial, a: a2, b: b2, extend: *extend, bubbles: *bubbles, bubble_mm: *bubble_mm, levels: levels.clone(), show_3d: *show_3d }
|
||||
}
|
||||
G::Text { at, text, height, angle, width, marks, doc, leader_target, leader_bend_points, path_pts } => G::Text {
|
||||
at: f(*at),
|
||||
text: text.clone(),
|
||||
@@ -1024,6 +1163,15 @@ pub fn scale_geom(g: &Drawing2DGeom, f: &dyn Fn(Vec2) -> Vec2, k: f64) -> Drawin
|
||||
*ry *= k;
|
||||
}
|
||||
G::Dimension { offset, .. } => *offset *= k,
|
||||
G::Grid { a, b, extend, radial, .. } => {
|
||||
if *radial != Some(true) {
|
||||
a.iter_mut().for_each(|x| x.pos *= k);
|
||||
}
|
||||
b.iter_mut().for_each(|x| x.pos *= k);
|
||||
if let Some(e) = extend {
|
||||
*e *= k;
|
||||
}
|
||||
}
|
||||
G::Text { height, width, .. } => {
|
||||
*height *= k;
|
||||
if let Some(w) = width {
|
||||
@@ -1097,6 +1245,25 @@ fn acc_bounds(g: &Drawing2DGeom, b: &mut Bounds) {
|
||||
}
|
||||
}
|
||||
G::Kote { at, .. } | G::Detailref { at, .. } | G::Pointmarker { at } | G::Text { at, .. } => acc(at),
|
||||
G::Grid { .. } => {
|
||||
if let Some(spec) = crate::grid::Spec::of(g) {
|
||||
for ax in spec.axes() {
|
||||
match ax.shape {
|
||||
// Rand für die Blasen an den Enden (Durchmesser bis ≈ 1 m bei 1:100).
|
||||
crate::grid::Shape::Line { a, b: e } => {
|
||||
acc(&v(a.0 - GRID_BUBBLE_MARGIN_M, a.1 - GRID_BUBBLE_MARGIN_M));
|
||||
acc(&v(e.0 + GRID_BUBBLE_MARGIN_M, e.1 + GRID_BUBBLE_MARGIN_M));
|
||||
acc(&v(a.0 + GRID_BUBBLE_MARGIN_M, a.1 + GRID_BUBBLE_MARGIN_M));
|
||||
acc(&v(e.0 - GRID_BUBBLE_MARGIN_M, e.1 - GRID_BUBBLE_MARGIN_M));
|
||||
}
|
||||
crate::grid::Shape::Arc { c, r, .. } => {
|
||||
acc(&v(c.0 - r - GRID_BUBBLE_MARGIN_M, c.1 - r - GRID_BUBBLE_MARGIN_M));
|
||||
acc(&v(c.0 + r + GRID_BUBBLE_MARGIN_M, c.1 + r + GRID_BUBBLE_MARGIN_M));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
G::Scalebar { at, segment_length, segments } => {
|
||||
acc(at);
|
||||
acc(&v(at.x + segment_length * segments, at.y));
|
||||
@@ -1107,7 +1274,7 @@ fn acc_bounds(g: &Drawing2DGeom, b: &mut Bounds) {
|
||||
|
||||
/// Liegt die Zeichnung auf dem Geschoss (und ist sie im Druck nicht ausgenommen, `noPrint`)?
|
||||
fn on_floor(c: &Ctx, d: &Drawing2D) -> bool {
|
||||
d.level_id == c.a.floor && !(c.a.for_print && d.no_print == Some(true))
|
||||
crate::grid::visible_on(d, &c.a.floor) && !(c.a.for_print && d.no_print == Some(true))
|
||||
}
|
||||
|
||||
/// Domäne „2D-Zeichnungen" von `planDomains`: alle gezeichneten Zeichnungen des Geschosses in
|
||||
@@ -1475,6 +1642,69 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// [112] Achsraster: strichpunktierte Achsen, Blasen (Kreis + Beschriftung) an beiden Enden,
|
||||
/// Ringe als Bögen, Blasengrösse folgt dem Massstab; auf anderen Geschossen sichtbar (`levels` leer).
|
||||
#[test]
|
||||
fn achsraster_achsen_und_blasen() {
|
||||
let p = project(serde_json::json!({}));
|
||||
let grid = |radial: bool| {
|
||||
drawing(serde_json::json!({"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0, "radial": radial,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": if radial { 90.0 } else { 5.0 }}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 4}], "extend": 1}))
|
||||
};
|
||||
let prims = render(&p, grid(false), 100.0);
|
||||
let lines = prims.iter().filter(|q| matches!(q, Primitive::Line { dash: Some(Some(_)), .. })).count();
|
||||
let circles: Vec<f64> = prims.iter().filter_map(|q| if let Primitive::DrawingCircle { r, .. } = q { Some(*r) } else { None }).collect();
|
||||
let texts: Vec<String> = prims.iter().filter_map(|q| if let Primitive::DrawingText { text, .. } = q { Some(text.clone()) } else { None }).collect();
|
||||
assert_eq!(lines, 4);
|
||||
assert_eq!(circles.len(), 8);
|
||||
// 8 mm Durchmesser bei 1:100 = 0.8 m → Radius 0.4.
|
||||
assert!(circles.iter().all(|r| (r - 0.4).abs() < 1e-9), "{circles:?}");
|
||||
assert_eq!(texts.len(), 8);
|
||||
assert!(["1", "2", "A", "B"].iter().all(|t| texts.iter().any(|x| x == t)));
|
||||
// Halber Massstab → halbe Blase.
|
||||
let half: Vec<f64> = render(&p, grid(false), 50.0).iter().filter_map(|q| if let Primitive::DrawingCircle { r, .. } = q { Some(*r) } else { None }).collect();
|
||||
assert!((half[0] - 0.2).abs() < 1e-9);
|
||||
// Radial: 2 Strahlen (Linien) und 2 Ringe (Bögen, Ring A mit Radius 0 entfällt als Vollkreis-Punkt).
|
||||
let prims = render(&p, grid(true), 100.0);
|
||||
assert_eq!(prims.iter().filter(|q| matches!(q, Primitive::Line { .. })).count(), 2);
|
||||
assert!(prims.iter().any(|q| matches!(q, Primitive::DrawingArc { r, .. } if (*r - 4.0).abs() < 1e-9)));
|
||||
}
|
||||
|
||||
/// [112] Raster erscheint in jedem Geschoss, bei `levels` nur in den genannten.
|
||||
#[test]
|
||||
fn achsraster_je_geschoss() {
|
||||
let g = |levels: Option<Vec<&str>>| {
|
||||
let mut d: Drawing2D = serde_json::from_value(drawing(serde_json::json!({"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0, "a": [], "b": []}))).unwrap();
|
||||
if let Drawing2DGeom::Grid { levels: l, .. } = &mut d.geom {
|
||||
*l = levels.map(|v| v.into_iter().map(String::from).collect());
|
||||
}
|
||||
d
|
||||
};
|
||||
let p = project(serde_json::json!({}));
|
||||
let a = args(100.0);
|
||||
let c = Ctx::new(&p, &a);
|
||||
let mut d = g(None);
|
||||
d.level_id = "og".into();
|
||||
assert!(on_floor(&c, &d), "ohne levels: in allen Geschossen (Plan zeigt eg)");
|
||||
assert!(!on_floor(&c, &g(Some(vec!["og"]))));
|
||||
assert!(on_floor(&c, &g(Some(vec!["og", "eg"]))));
|
||||
}
|
||||
|
||||
/// [38] Radius-, Durchmesser- und Bogenlängen-Mass: Linien, Masszahl mit R / Ø / L.
|
||||
#[test]
|
||||
fn rund_bemassung_zeichnet_zahl() {
|
||||
let p = project(serde_json::json!({}));
|
||||
let dim = |kind: &str, pts: serde_json::Value| drawing(serde_json::json!({"shape": "dimension", "pts": pts, "offset": 0.5, "kind": kind}));
|
||||
let texts = |prims: &[Primitive]| -> Vec<String> { prims.iter().filter_map(|q| if let Primitive::DrawingText { text, .. } = q { Some(text.clone()) } else { None }).collect() };
|
||||
let r = render(&p, dim("radius", serde_json::json!([{"x": 0, "y": 0}, {"x": 3, "y": 0}])), 100.0);
|
||||
assert_eq!(texts(&r), ["R 3.00"]);
|
||||
let r = render(&p, dim("diameter", serde_json::json!([{"x": 0, "y": 0}, {"x": 3, "y": 0}])), 100.0);
|
||||
assert_eq!(texts(&r), ["\u{d8} 6.00"]);
|
||||
let r = render(&p, dim("arc", serde_json::json!([{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 0, "y": 2}])), 100.0);
|
||||
assert_eq!(texts(&r), ["L 3.14"]);
|
||||
assert!(r.iter().any(|q| matches!(q, Primitive::DrawingArc { r, .. } if (*r - 2.5).abs() < 1e-9)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rechteck_flaeche_und_vier_linien_in_ebenenfarbe() {
|
||||
let p = project(serde_json::json!({}));
|
||||
|
||||
@@ -77,6 +77,229 @@ struct Face {
|
||||
normal: [f64; 3],
|
||||
}
|
||||
|
||||
/// Stirnflächen der Dachscheibe an den freien Rändern der Dachflächen (Traufe, Ortgang): je Rand ein
|
||||
/// Viereck von der Oberkante senkrecht zur Fläche um die Dicke nach innen (wie die 3D-Schichten).
|
||||
fn fascia_quads(planes: &[Vec<[f64; 3]>], total: f64) -> Vec<[[f64; 3]; 4]> {
|
||||
let mut out = Vec::new();
|
||||
if !(total > 1e-6) {
|
||||
return out;
|
||||
}
|
||||
let same = |a: [f64; 3], b: [f64; 3]| (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6 && (a[2] - b[2]).abs() < 1e-6;
|
||||
for (i, pl) in planes.iter().enumerate() {
|
||||
if pl.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let n = model3d::plane_normal_up(pl);
|
||||
if !(n[2] > 1e-3) {
|
||||
continue;
|
||||
}
|
||||
for k in 0..pl.len() {
|
||||
let (a, b) = (pl[k], pl[(k + 1) % pl.len()]);
|
||||
let shared = planes.iter().enumerate().any(|(j, o)| j != i && (0..o.len()).any(|m| { let (c, d) = (o[m], o[(m + 1) % o.len()]); (same(a, c) && same(b, d)) || (same(a, d) && same(b, c)) }));
|
||||
if shared || same(a, b) {
|
||||
continue;
|
||||
}
|
||||
let off = |q: [f64; 3]| [q[0] - n[0] * total, q[1] - n[1] * total, q[2] - n[2] * total];
|
||||
out.push([a, b, off(b), off(a)]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Dach-Scheiben für die Verdeckung der Wände darunter ([G2]): je Dachfläche Ober- und Unterkante,
|
||||
/// dazu die Stirnflächen der Ränder.
|
||||
struct RoofSheet {
|
||||
top: Vec<crate::wall_bands::RoofFacet>,
|
||||
under: Vec<crate::wall_bands::RoofFacet>,
|
||||
fascia: Vec<[[f64; 3]; 4]>,
|
||||
bounds: [f64; 4],
|
||||
}
|
||||
|
||||
/// Kreuzt die waagrechte Strecke `a → b` (Grundriss) auf Höhe `z` eine Stirnfläche (im Innern)?
|
||||
fn crosses_fascia(q: &[[f64; 3]; 4], a: (f64, f64), b: (f64, f64), z: f64) -> bool {
|
||||
let e1 = [q[1][0] - q[0][0], q[1][1] - q[0][1], q[1][2] - q[0][2]];
|
||||
let e2 = [q[3][0] - q[0][0], q[3][1] - q[0][1], q[3][2] - q[0][2]];
|
||||
let m = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
|
||||
let side = |x: f64, y: f64| m[0] * (x - q[0][0]) + m[1] * (y - q[0][1]) + m[2] * (z - q[0][2]);
|
||||
let (s0, s1) = (side(a.0, a.1), side(b.0, b.1));
|
||||
if !(s0 * s1 < 0.0) {
|
||||
return false;
|
||||
}
|
||||
let t = s0 / (s0 - s1);
|
||||
let x = [a.0 + (b.0 - a.0) * t - q[0][0], a.1 + (b.1 - a.1) * t - q[0][1], z - q[0][2]];
|
||||
let dot = |u: [f64; 3], v: [f64; 3]| u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
|
||||
let (l1, l2) = (dot(e1, e1), dot(e2, e2));
|
||||
if !(l1 > 1e-12 && l2 > 1e-12) {
|
||||
return false;
|
||||
}
|
||||
let (al, be) = (dot(x, e1) / l1, dot(x, e2) / l2);
|
||||
(0.0..=1.0).contains(&al) && be > 1e-6 && be < 1.0 - 1e-6
|
||||
}
|
||||
|
||||
impl RoofSheet {
|
||||
/// Oberkante minus `z` über dem Grundriss-Punkt (`None`: kein Dach), nur wo die Unterkante echt unter
|
||||
/// `z` liegt oder die Oberkante darunter (Strahl über dem Dach).
|
||||
fn above(&self, x: f64, y: f64, z: f64) -> Option<f64> {
|
||||
let b = self.bounds;
|
||||
if x < b[0] || x > b[2] || y < b[1] || y > b[3] {
|
||||
return None;
|
||||
}
|
||||
self.top.iter().zip(&self.under).filter(|(t, _)| t.contains(x, y)).map(|(t, u)| if u.z(x, y) < z - 1e-4 { t.z(x, y) - z } else { -1.0 }).reduce(f64::max)
|
||||
}
|
||||
}
|
||||
|
||||
/// Wandflächen unter Dächern ([G2]) gegen die Dachscheiben vor ihnen: Ecken, deren Sichtstrahl (zum
|
||||
/// Betrachter) durch ein Dach läuft, sind verdeckt. Ganz verdeckte Flächen entfallen (Oberseiten,
|
||||
/// Laibungen und Stirnen innen unter dem Dach); bei senkrechten Kanten wird die Fläche auf die Höhe
|
||||
/// gekappt, ab der das Dach sie verdeckt (Traufe vor der Wand). Ersetzt keine HLR ([G4]).
|
||||
fn cull_under_roofs(p: &Project, frame: &[f64; 9], walls: &[RWall], faces: &mut Vec<Face>) {
|
||||
let affected: std::collections::HashSet<&str> = walls.iter().filter(|w| w.top_plane.is_some() || w.joint != [false; 2]).map(|w| w.wall_id.as_str()).collect();
|
||||
if affected.is_empty() {
|
||||
return;
|
||||
}
|
||||
let sheets: Vec<RoofSheet> = p
|
||||
.roofs
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let g = crate::roof::roof_geometry(&r.params(), p.roof_base_elevation(r));
|
||||
let total: f64 = p.roof_layers(r).iter().map(|l| l.thickness.max(0.0)).sum();
|
||||
let top = crate::wall_bands::plane_facets(&g.planes, 0.0);
|
||||
let under = crate::wall_bands::plane_facets(&g.planes, total);
|
||||
let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
|
||||
for q in g.planes.iter().flatten() {
|
||||
b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[0]), b[3].max(q[1])];
|
||||
}
|
||||
// Stirnflächen, die in einem anderen Dach stecken (Kehlen verschnittener Dächer), verdecken nicht.
|
||||
let others: Vec<Vec<[f64; 3]>> = p
|
||||
.roofs
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter(|o| o.id != r.id && o.floor_id == r.floor_id)
|
||||
.flat_map(|o| crate::roof::roof_geometry(&o.params(), p.roof_base_elevation(o)).planes)
|
||||
.collect();
|
||||
let fascia = fascia_quads(&g.planes, total)
|
||||
.into_iter()
|
||||
.filter(|q| !others.iter().any(|o| crate::dormer::point_in_xy((q[0][0] + q[1][0]) / 2.0, (q[0][1] + q[1][1]) / 2.0, o)))
|
||||
.collect();
|
||||
RoofSheet { top, under, fascia, bounds: b }
|
||||
})
|
||||
.filter(|s| s.top.len() == s.under.len() && !s.top.is_empty())
|
||||
.collect();
|
||||
if sheets.is_empty() {
|
||||
return;
|
||||
}
|
||||
let (o, n, u) = ([frame[0], frame[2]], [frame[3], frame[5]], [frame[6], frame[8]]);
|
||||
let reach = sheets.iter().map(|s| (s.bounds[2] - s.bounds[0]).max(s.bounds[3] - s.bounds[1])).fold(0.0, f64::max) + 1.0;
|
||||
// Gaubenstirnen und -wangen als senkrechte Verdecker (lokal u, v; z von der Hauptdach-Unterkante bis
|
||||
// zum Gaubendach).
|
||||
let dormers: Vec<crate::dormer::DormerGeom> = p
|
||||
.roofs
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.flat_map(|r| r.dormers.as_deref().unwrap_or(&[]).iter().filter_map(move |d| crate::dormer::geometry(p, r, d)))
|
||||
.collect();
|
||||
let dormer_hit = |a: (f64, f64), b: (f64, f64), z: f64| -> bool {
|
||||
dormers.iter().any(|g| {
|
||||
let (la, lb) = (g.frame.local(a.0, a.1), g.frame.local(b.0, b.1));
|
||||
let hw = g.width / 2.0;
|
||||
let z_ok = |u: f64, v: f64| z >= g.frame.main_top(v) - g.main_thickness * 2.0 && z <= g.under(u, v) + g.roof_vertical();
|
||||
// Stirn (v = 0) oder Wange (|u| = hw) gekreuzt.
|
||||
let front = (la[1] > 0.0) != (lb[1] > 0.0) && la[0].abs() <= hw && z_ok(la[0], 0.0);
|
||||
let cheek = (la[0].abs() < hw) != (lb[0].abs() < hw) && la[1] >= 0.0 && la[1] <= g.hole_v(la[0]) && z_ok(la[0].clamp(-hw, hw), la[1]);
|
||||
front || cheek
|
||||
})
|
||||
};
|
||||
// Verdeckt: der Strahl zum Betrachter (−n im Grundriss) kreuzt die Dachoberfläche von unten nach
|
||||
// oben gesehen (erst darunter, näher zum Betrachter darüber) oder eine Gaubenwand.
|
||||
let hidden = |x: f64, y: f64, z: f64| -> bool {
|
||||
let steps = ((reach / 0.04).ceil() as usize).min(5000);
|
||||
let mut under = false;
|
||||
let mut prev = (x, y);
|
||||
let at = |t: f64| sheets.iter().filter_map(|s| s.above(x - n[0] * t, y - n[1] * t, z)).reduce(f64::max);
|
||||
for i in 1..=steps {
|
||||
let t = i as f64 * 0.04;
|
||||
let q = (x - n[0] * t, y - n[1] * t);
|
||||
if dormer_hit(prev, q, z) || sheets.iter().any(|s| s.fascia.iter().any(|f| crosses_fascia(f, prev, q, z))) {
|
||||
return true;
|
||||
}
|
||||
prev = q;
|
||||
match at(t) {
|
||||
Some(d) if d >= 0.0 => under = true,
|
||||
Some(_) if under => return true,
|
||||
None if under => {
|
||||
// Aus der Scheibe heraus (Traufkante): Oberkante genau an der Kante unter z?
|
||||
let (mut lo, mut hi) = (t - 0.04, t);
|
||||
for _ in 0..30 {
|
||||
let m = (lo + hi) / 2.0;
|
||||
if at(m).is_some() {
|
||||
lo = m;
|
||||
} else {
|
||||
hi = m;
|
||||
}
|
||||
}
|
||||
if at(lo).is_some_and(|d| d < -1e-6) {
|
||||
return true;
|
||||
}
|
||||
under = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
};
|
||||
faces.retain_mut(|f| {
|
||||
if f.role != Role::Wall || !affected.contains(f.id.as_str()) || f.pts.len() < 3 {
|
||||
return true;
|
||||
}
|
||||
// Tiefe je Ecke aus der Flächenebene (Normale in Welt x, Höhe, Grundriss-y).
|
||||
let k = f.normal[0] * n[0] + f.normal[2] * n[1];
|
||||
if k.abs() < 1e-9 {
|
||||
return true;
|
||||
}
|
||||
let m = f.pts.len() as f64;
|
||||
let (cu, cv) = (f.pts.iter().map(|q| q[0]).sum::<f64>() / m, f.pts.iter().map(|q| q[1]).sum::<f64>() / m);
|
||||
let nu = f.normal[0] * u[0] + f.normal[2] * u[1];
|
||||
let world = |q: Pt| -> (f64, f64, f64) {
|
||||
let d = f.depth + (nu * (cu - q[0]) + f.normal[1] * (cv - q[1])) / k;
|
||||
(o[0] + u[0] * q[0] + n[0] * d, o[1] + u[1] * q[0] + n[1] * d, q[1])
|
||||
};
|
||||
let hid: Vec<bool> = f.pts.iter().map(|&q| {
|
||||
let (x, y, z) = world(q);
|
||||
hidden(x, y, z - 1e-6)
|
||||
}).collect();
|
||||
if hid.iter().all(|h| *h) {
|
||||
return false;
|
||||
}
|
||||
if !hid.iter().any(|h| *h) {
|
||||
return true;
|
||||
}
|
||||
// Verdeckte Ecke mit sichtbarer Ecke senkrecht darunter: auf die Verdeckungsgrenze senken.
|
||||
let pts = f.pts.clone();
|
||||
for i in 0..pts.len() {
|
||||
if !hid[i] {
|
||||
continue;
|
||||
}
|
||||
let Some(j) = (0..pts.len()).find(|&j| !hid[j] && (pts[j][0] - pts[i][0]).abs() < 1e-6 && pts[j][1] < pts[i][1]) else { continue };
|
||||
let (x, y, _) = world(pts[i]);
|
||||
let (mut lo, mut hi) = (pts[j][1], pts[i][1]);
|
||||
for _ in 0..40 {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if hidden(x, y, mid) {
|
||||
hi = mid;
|
||||
} else {
|
||||
lo = mid;
|
||||
}
|
||||
}
|
||||
f.pts[i][1] = lo;
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// `elevationFrame` flach: `[P, N, U]`.
|
||||
fn frame_of(plane: &super::section::Plane) -> [f64; 9] {
|
||||
let [nx, ny, nz] = plane.normal;
|
||||
@@ -101,13 +324,21 @@ struct RoofIn {
|
||||
fn project_faces(frame: &[f64; 9], walls: &[RWall], slabs: &[RSlab], roofs: &[RoofIn]) -> Vec<Face> {
|
||||
let mut w = vec![walls.len() as f64];
|
||||
// Mit Schnittlinien (Bogen-Teilkörper, [T2]): die Ecken liegen auf der Gehrung statt rechtwinklig.
|
||||
let cut = walls.iter().any(|x| x.start_cut.is_some() || x.end_cut.is_some() || x.joint != [false; 2]);
|
||||
let planes = walls.iter().any(|x| x.top_plane.is_some());
|
||||
let cut = planes || walls.iter().any(|x| x.start_cut.is_some() || x.end_cut.is_some() || x.joint != [false; 2]);
|
||||
for x in walls {
|
||||
w.extend([x.start[0], x.start[1], x.end[0], x.end[1], x.thickness, x.height, x.base_elevation]);
|
||||
if cut {
|
||||
w.extend(corner_shifts(x));
|
||||
w.extend([if x.joint[0] { 1.0 } else { 0.0 }, if x.joint[1] { 1.0 } else { 0.0 }]);
|
||||
}
|
||||
// Ebene Oberkante unter einem Dach ([G2]).
|
||||
if planes {
|
||||
match x.top_plane {
|
||||
Some(c) => w.extend([1.0, c[0], c[1], c[2]]),
|
||||
None => w.extend([0.0; 4]),
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut sl = vec![slabs.len() as f64];
|
||||
for x in slabs {
|
||||
@@ -173,7 +404,10 @@ pub(crate) fn corner_shifts(x: &RWall) -> [f64; 4] {
|
||||
}
|
||||
|
||||
/// `collectRoofFaces`.
|
||||
fn collect_roof_faces(p: &Project, frame: &[f64; 9]) -> Result<Vec<Face>, String> {
|
||||
fn collect_roof_faces(p: &Project, frame: &[f64; 9], walls: &[RWall]) -> Result<Vec<Face>, String> {
|
||||
// Giebeldreiecke nur ohne Wand darunter ([G2]): sonst zeigt die Ansicht die Giebelwand selbst.
|
||||
let reached: std::collections::HashSet<&str> = walls.iter().filter(|w| w.top_plane.is_some()).map(|w| w.wall_id.as_str()).collect();
|
||||
let floors: std::collections::HashSet<&str> = p.walls.iter().filter(|w| reached.contains(w.id.as_str())).map(|w| w.floor_id.as_str()).collect();
|
||||
let mut roofs = Vec::new();
|
||||
for (ri, roof) in p.roofs.as_deref().unwrap_or(&[]).iter().enumerate() {
|
||||
let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof));
|
||||
@@ -207,7 +441,29 @@ fn collect_roof_faces(p: &Project, frame: &[f64; 9]) -> Result<Vec<Face>, String
|
||||
.collect()
|
||||
};
|
||||
// Wie die übrigen Dächer: Oberfläche der Eindeckung (Dach + Gaubendächer), dazu die Gaubenwände.
|
||||
roofs.push(RoofIn { id: roof.id.clone(), fill, planes: crate::roof_assembly::planar_faces(&solids.top, &front(&solids.top)), gables: g.gables.clone() });
|
||||
// Wände reichen ans Dach ([G2]): Stirnflächen der Ränder, die nicht in einem anderen Dach stecken.
|
||||
let gables = if floors.contains(roof.floor_id.as_str()) {
|
||||
let total: f64 = p.roof_layers(roof).iter().map(|l| l.thickness.max(0.0)).sum();
|
||||
let others: Vec<Vec<[f64; 3]>> = p
|
||||
.roofs
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter(|o| o.id != roof.id && o.floor_id == roof.floor_id)
|
||||
.flat_map(|o| crate::roof::roof_geometry(&o.params(), p.roof_base_elevation(o)).planes)
|
||||
.collect();
|
||||
fascia_quads(&g.planes, total)
|
||||
.into_iter()
|
||||
.filter(|q| {
|
||||
let (mx, my) = ((q[0][0] + q[1][0]) / 2.0, (q[0][1] + q[1][1]) / 2.0);
|
||||
!others.iter().any(|o| crate::dormer::point_in_xy(mx, my, o))
|
||||
})
|
||||
.map(|q| q.to_vec())
|
||||
.collect()
|
||||
} else {
|
||||
g.gables.clone()
|
||||
};
|
||||
roofs.push(RoofIn { id: roof.id.clone(), fill, planes: crate::roof_assembly::planar_faces(&solids.top, &front(&solids.top)), gables });
|
||||
let wall_comp = solids.parts.iter().find(|pt| pt.role == crate::roof_assembly::Role::DormerWall && pt.layer == 0).and_then(|pt| p.component(&pt.component_id));
|
||||
let wf = wall_comp.map_or([0.85, 0.83, 0.8], |c| hex_to_rgb(&c.color, [0.85, 0.83, 0.8]));
|
||||
let wall_faces = crate::roof_assembly::planar_faces(&solids.walls, &front(&solids.walls));
|
||||
@@ -216,7 +472,14 @@ fn collect_roof_faces(p: &Project, frame: &[f64; 9]) -> Result<Vec<Face>, String
|
||||
}
|
||||
continue;
|
||||
}
|
||||
roofs.push(RoofIn { id: roof.id.clone(), fill, planes: g.planes.clone(), gables: g.gables.clone() });
|
||||
// Wände reichen ans Dach: statt der Giebeldreiecke die Stirnflächen der Dachscheibe (Traufe, Ortgang).
|
||||
let gables = if floors.contains(roof.floor_id.as_str()) {
|
||||
let total: f64 = p.roof_layers(roof).iter().map(|l| l.thickness.max(0.0)).sum();
|
||||
fascia_quads(&g.planes, total).into_iter().map(|q| q.to_vec()).collect()
|
||||
} else {
|
||||
g.gables.clone()
|
||||
};
|
||||
roofs.push(RoofIn { id: roof.id.clone(), fill, planes: g.planes.clone(), gables });
|
||||
}
|
||||
Ok(project_faces(frame, &[], &[], &roofs))
|
||||
}
|
||||
@@ -261,6 +524,10 @@ fn extend_wall_corners(p: &Project, rwalls: &mut [RWall], u: (f64, f64)) {
|
||||
if let Some(&i) = pieces.iter().find(|&&i| close(rwalls[i].start, w.start)) {
|
||||
let s = rwalls[i].start;
|
||||
rwalls[i].start = [s[0] - ux * e_start, s[1] - uz * e_start];
|
||||
// Ebene Oberkante bezieht sich auf den Anfang ([G2]).
|
||||
if let Some(c) = rwalls[i].top_plane.as_mut() {
|
||||
c[0] -= (c[1] * ux + c[2] * uz) * e_start;
|
||||
}
|
||||
}
|
||||
}
|
||||
if e_end > EPS {
|
||||
@@ -666,6 +933,78 @@ fn elevation_edges(p: &Project, faces: &[Face], openings: &[ProjOpening], frame:
|
||||
crate::hlr::hidden_lines(&hf, &opts).into_iter().map(|s| EdgeSeg { a: s.a, b: s.b, hidden: s.hidden }).collect()
|
||||
}
|
||||
|
||||
/// [T6] Obere Hüllkurve des Geländes (samt Baugruben) in der Ansicht: Dreiecke mit Tiefe in [0, `depth_max`]
|
||||
/// und u im Bereich `range`, abgetastet in ≤ 800 Spalten.
|
||||
fn terrain_silhouette(p: &Project, t: &TerrainMesh, frame: &[f64; 9], range: (f64, f64), depth_max: f64) -> Vec<Vec<[f64; 2]>> {
|
||||
let (fp, fnrm, fu) = ([frame[0], frame[1], frame[2]], [frame[3], frame[4], frame[5]], [frame[6], frame[7], frame[8]]);
|
||||
let (pos, idx, _) = crate::excavation::terrain_model_mesh(p, t);
|
||||
let proj = |i: usize| -> (f64, f64, f64) {
|
||||
let q = [pos[3 * i], pos[3 * i + 1], pos[3 * i + 2]];
|
||||
let w = [q[0] - fp[0], q[2] - fp[1], q[1] - fp[2]];
|
||||
(w[0] * fu[0] + w[1] * fu[1] + w[2] * fu[2], q[2], w[0] * fnrm[0] + w[1] * fnrm[1] + w[2] * fnrm[2])
|
||||
};
|
||||
let (u0, u1) = range;
|
||||
if !(u1 > u0) {
|
||||
return Vec::new();
|
||||
}
|
||||
let n = 800usize;
|
||||
let du = (u1 - u0) / n as f64;
|
||||
let mut env = vec![f64::NEG_INFINITY; n + 1];
|
||||
let nv = pos.len() / 3;
|
||||
for tr in idx.chunks_exact(3) {
|
||||
if !tr.iter().all(|v| *v >= 0.0 && (*v as usize) < nv) {
|
||||
continue;
|
||||
}
|
||||
let q = [proj(tr[0] as usize), proj(tr[1] as usize), proj(tr[2] as usize)];
|
||||
if q.iter().all(|v| v.2 < 0.0) || q.iter().all(|v| v.2 > depth_max) {
|
||||
continue;
|
||||
}
|
||||
let lo = q.iter().map(|v| v.0).fold(f64::INFINITY, f64::min).max(u0);
|
||||
let hi = q.iter().map(|v| v.0).fold(f64::NEG_INFINITY, f64::max).min(u1);
|
||||
if !(hi >= lo) {
|
||||
continue;
|
||||
}
|
||||
let (k0, k1) = (((lo - u0) / du).ceil() as usize, (((hi - u0) / du).floor() as usize).min(n));
|
||||
for (k, e) in env.iter_mut().enumerate().take(k1 + 1).skip(k0) {
|
||||
let u = u0 + k as f64 * du;
|
||||
for i in 0..3 {
|
||||
let (a, b) = (q[i], q[(i + 1) % 3]);
|
||||
if (a.0 - u) * (b.0 - u) <= 0.0 && a.0 != b.0 {
|
||||
let z = a.1 + (b.1 - a.1) * (u - a.0) / (b.0 - a.0);
|
||||
*e = e.max(z);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out: Vec<Vec<[f64; 2]>> = Vec::new();
|
||||
let mut cur: Vec<[f64; 2]> = Vec::new();
|
||||
for (k, z) in env.iter().enumerate() {
|
||||
if z.is_finite() {
|
||||
cur.push([u0 + k as f64 * du, *z]);
|
||||
} else if cur.len() > 1 {
|
||||
out.push(std::mem::take(&mut cur));
|
||||
} else {
|
||||
cur.clear();
|
||||
}
|
||||
}
|
||||
if cur.len() > 1 {
|
||||
out.push(cur);
|
||||
}
|
||||
// Kollineare Zwischenpunkte weglassen (Raster), Form bleibt.
|
||||
for l in &mut out {
|
||||
let mut s: Vec<[f64; 2]> = vec![l[0]];
|
||||
for i in 1..l.len() - 1 {
|
||||
let (a, b, c) = (s[s.len() - 1], l[i], l[i + 1]);
|
||||
if ((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])).abs() > 1e-9 {
|
||||
s.push(b);
|
||||
}
|
||||
}
|
||||
s.push(l[l.len() - 1]);
|
||||
*l = s;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `generateElevationPlan`: Primitive und Ausmass; `None` ohne Ansichtslinie.
|
||||
pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono: bool, vis: &Visibility, scale: f64) -> Result<Option<(Vec<Primitive>, [f64; 4])>, String> {
|
||||
let Some(plane) = level.plane() else { return Ok(None) };
|
||||
@@ -675,7 +1014,8 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
|
||||
slabs.extend(model3d::emit_stairs(p, false));
|
||||
extend_wall_corners(p, &mut walls, (frame[6], frame[8]));
|
||||
let mut faces = project_faces(&frame, &walls, &slabs, &[]);
|
||||
faces.extend(collect_roof_faces(p, &frame)?);
|
||||
cull_under_roofs(p, &frame, &walls, &mut faces);
|
||||
faces.extend(collect_roof_faces(p, &frame, &walls)?);
|
||||
|
||||
// Kategorie einer Fläche (erstes Element mit der id, wie `find`).
|
||||
let mut wall_cat: HashMap<&str, &str> = HashMap::new();
|
||||
@@ -752,7 +1092,7 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
|
||||
// die Haarfugen zwischen ihnen.
|
||||
let fill = fill_for(f.fill);
|
||||
let seam = is_roof && assembled.contains(f.id.as_str());
|
||||
let mut prim = if seam { polygon(pts, &fill, &fill, 0.05, no_hatch()) } else { polygon(pts, &fill, "none", 0.0, no_hatch()) };
|
||||
let mut prim = if seam { polygon(pts, &fill, &fill, 0.15, no_hatch()) } else { polygon(pts, &fill, "none", 0.0, no_hatch()) };
|
||||
if let Primitive::Polygon { greyed: g, wall_id, ceiling_id, roof_id, .. } = &mut prim {
|
||||
*g = Some(greyed(f));
|
||||
if !f.id.is_empty() {
|
||||
@@ -942,7 +1282,33 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
|
||||
prims.push(outline_line(e.a, e.b));
|
||||
}
|
||||
}
|
||||
if acc.min_x.is_finite() && acc.min_y.is_finite() {
|
||||
// [T6] Gelände-Silhouette (gestaltetes Terrain) zwischen Ansichtsebene und vorderster Gebäudefläche; was
|
||||
// darunter liegt, verdeckt das Gelände (Papierfläche über dem Gebäude).
|
||||
let depth_max = faces.iter().map(|f| f.depth_min).fold(f64::INFINITY, f64::min) + 0.3;
|
||||
let mut has_terrain = false;
|
||||
if acc.min_x.is_finite() && depth_max.is_finite() && !crate::excavation::terrains(p).is_empty() {
|
||||
let terrain_shown = |c: Option<&str>| c.is_none_or(|c| !vis.has_vis || !vis.has_display || (vis.visible(c) && vis.render(c)));
|
||||
for t in crate::excavation::terrains(p) {
|
||||
if !terrain_shown(t.category_code.as_deref()) {
|
||||
continue;
|
||||
}
|
||||
for l in terrain_silhouette(p, t, &frame, (acc.min_x - 6.0, acc.max_x + 6.0), depth_max) {
|
||||
has_terrain = true;
|
||||
let low = l.iter().map(|q| q[1]).fold(acc.min_y, f64::min) - 1.0;
|
||||
let mut ring: Vec<Vec2> = l.iter().map(|q| v2(q[0], q[1])).collect();
|
||||
ring.push(v2(l[l.len() - 1][0], low));
|
||||
ring.push(v2(l[0][0], low));
|
||||
prims.push(polygon(ring, "#ffffff", "none", 0.0, no_hatch()));
|
||||
for w in l.windows(2) {
|
||||
acc.add(w[0][0], w[0][1]);
|
||||
acc.add(w[1][0], w[1][1]);
|
||||
prims.push(line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), "elevation-terrain", GROUND_MM, GROUND_INK));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Mit Gelände ersetzt die Silhouette die Grundlinie ([T6]).
|
||||
if acc.min_x.is_finite() && acc.min_y.is_finite() && !has_terrain {
|
||||
prims.push(line(v2(acc.min_x, acc.min_y), v2(acc.max_x, acc.min_y), "elevation-ground", GROUND_MM, GROUND_INK));
|
||||
}
|
||||
Ok(Some((prims, acc.bounds())))
|
||||
@@ -1107,7 +1473,12 @@ pub fn elevation_plan_buf(p: &Project, args: &[f64], text: &str) -> Result<Vec<u
|
||||
let mut w = crate::plan_buf::Writer::new(true);
|
||||
if let Some((prims, bounds)) = elevation_primitives(p, &level, shadows, mono, &vis, scale)? {
|
||||
w.group(&prims);
|
||||
w.bounds = Some(bounds);
|
||||
// Achsraster ([112]): Achsen quer zur Blickebene.
|
||||
let grid = super::grid_view::grid_prims(p, &level, bounds, scale);
|
||||
if !grid.is_empty() {
|
||||
w.group(&grid);
|
||||
}
|
||||
w.bounds = Some(super::grid_view::union_bounds(bounds, &grid));
|
||||
}
|
||||
Ok(w.finish())
|
||||
}
|
||||
@@ -1177,6 +1548,55 @@ mod tests {
|
||||
serde_json::to_string(&prims).unwrap()
|
||||
}
|
||||
|
||||
/// [G2] Wände unter dem Dach: in der Traufansicht verdeckt das Dach Giebel- und Innenwände (keine
|
||||
/// Wandfläche über der Traufkante), in der Giebelansicht steht die Giebelwand bis unter das Dach.
|
||||
#[test]
|
||||
fn waende_unter_dem_dach_in_der_ansicht() {
|
||||
let p: Project = serde_json::from_value(serde_json::json!({
|
||||
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "drawings2d": [], "openings": [],
|
||||
"drawingLevels": [
|
||||
{"id": "F", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 0},
|
||||
{"id": "s", "name": "S", "kind": "elevation", "visible": true, "locked": false, "linePoints": [{"x": -2, "y": -3}, {"x": 12, "y": -3}], "directionSign": 1},
|
||||
{"id": "w", "name": "W", "kind": "elevation", "visible": true, "locked": false, "linePoints": [{"x": -3, "y": 10}, {"x": -3, "y": -2}], "directionSign": 1}
|
||||
],
|
||||
"walls": [
|
||||
{"id": "WS", "type": "wall", "floorId": "F", "categoryCode": "20", "start": {"x": 0, "y": 0}, "end": {"x": 10, "y": 0}, "height": 3.5},
|
||||
{"id": "WW", "type": "wall", "floorId": "F", "categoryCode": "20", "start": {"x": 0, "y": 8}, "end": {"x": 0, "y": 0}, "height": 9.0},
|
||||
{"id": "WI", "type": "wall", "floorId": "F", "categoryCode": "20", "start": {"x": 5, "y": 0}, "end": {"x": 5, "y": 8}, "height": 9.0}
|
||||
],
|
||||
"roofs": [{"id": "R", "type": "roof", "floorId": "F", "categoryCode": "35",
|
||||
"outline": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 8}, {"x": 0, "y": 8}],
|
||||
"shape": "sattel", "pitchDeg": 45, "overhang": 0.5, "overhangGable": 0.3, "ridgeAxis": "x", "thickness": 0.3}]
|
||||
}))
|
||||
.unwrap();
|
||||
let view = |id: &str| {
|
||||
let l = p.drawing_levels.iter().find(|l| l.id == id).unwrap();
|
||||
let level = LevelSpec::from_json(&serde_json::to_value(l).unwrap());
|
||||
elevation_primitives(&p, &level, false, false, &Visibility::default(), 100.0).unwrap().unwrap().0
|
||||
};
|
||||
let wall_top = |prims: &[Primitive], id: &str| -> f64 {
|
||||
prims
|
||||
.iter()
|
||||
.filter_map(|q| match q {
|
||||
Primitive::Polygon { pts, wall_id: Some(w), .. } if w == id => Some(pts.iter().map(|v| v.y).fold(f64::NEG_INFINITY, f64::max)),
|
||||
_ => None,
|
||||
})
|
||||
.fold(f64::NEG_INFINITY, f64::max)
|
||||
};
|
||||
// Traufe: Oberkante der Dachfläche an der Vorderkante (tiefster Punkt der Dachflächen).
|
||||
let r = &p.roofs.as_ref().unwrap()[0];
|
||||
let eave = crate::roof::roof_geometry(&r.params(), p.roof_base_elevation(r)).planes.iter().flatten().map(|q| q[2]).fold(f64::INFINITY, f64::min);
|
||||
let s = view("s");
|
||||
// Sichtbar bis unter die Traufstirn (Dicke 0.3 senkrecht zur 45°-Fläche: 0.3·cos 45° tiefer).
|
||||
let fascia = eave - 0.3 * 0.5f64.sqrt();
|
||||
assert!(wall_top(&s, "WW") <= fascia + 1e-3 && wall_top(&s, "WI") <= fascia + 1e-3, "{} {} {fascia}", wall_top(&s, "WW"), wall_top(&s, "WI"));
|
||||
assert!((wall_top(&s, "WS") - fascia).abs() < 1e-3, "Traufwand bis zur Traufstirn sichtbar: {}", wall_top(&s, "WS"));
|
||||
// Giebel: First-Unterkante = Traufkante 3.0 + 4.5 (bei 45°) − 0.3·√2.
|
||||
let w = view("w");
|
||||
let ridge_under = 7.5 - 0.3 * 2f64.sqrt();
|
||||
assert!((wall_top(&w, "WW") - ridge_under).abs() < 1e-6, "{}", wall_top(&w, "WW"));
|
||||
}
|
||||
|
||||
/// [T2] Bogenwand in der Ansicht: keine Facetten-Fugen der Sehnen-Teilkörper, Umriss bleibt.
|
||||
#[test]
|
||||
fn bogenwand_ohne_facettenfugen() {
|
||||
@@ -1241,7 +1661,14 @@ mod tests {
|
||||
assert!(o1.len() == 2 && o1.iter().all(|n| *n >= 40), "Rahmen + Glas als Ellipse: {o1:?}");
|
||||
assert_eq!(polys("DF"), vec![4, 4], "Dachfenster: Rahmen + Glas");
|
||||
let first_df = prims.iter().position(|pr| matches!(pr, Primitive::Polygon { opening_id: Some(o), .. } if o == "DF")).unwrap();
|
||||
let last_roof = prims.iter().rposition(|pr| matches!(pr, Primitive::Polygon { roof_id: Some(_), .. })).unwrap();
|
||||
// Dachflächen, die das Dachfenster überdecken (die Traufstirn [G2] liegt davor, berührt es nicht).
|
||||
let bb = |pts: &[Vec2]| pts.iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, q| [b[0].min(q.x), b[1].min(q.y), b[2].max(q.x), b[3].max(q.y)]);
|
||||
let Primitive::Polygon { pts: df_pts, .. } = &prims[first_df] else { unreachable!() };
|
||||
let d = bb(df_pts);
|
||||
let last_roof = prims
|
||||
.iter()
|
||||
.rposition(|pr| matches!(pr, Primitive::Polygon { roof_id: Some(_), pts, .. } if { let r = bb(pts); r[0] < d[2] && r[2] > d[0] && r[1] < d[3] && r[3] > d[1] }))
|
||||
.unwrap();
|
||||
assert!(first_df > last_roof, "Dachfenster vor der Dachfläche gezeichnet");
|
||||
}
|
||||
|
||||
|
||||
@@ -436,6 +436,11 @@ pub fn extra_bounds(p: &Project, extra: &[(Primitive, u32)]) -> Bounds {
|
||||
}
|
||||
ContextObject::ImportedMesh(m) => mesh_bounds(&m.positions, &mut b),
|
||||
ContextObject::TerrainMesh(m) => mesh_bounds(&m.positions, &mut b),
|
||||
ContextObject::Excavation(e) => {
|
||||
for q in &e.outline {
|
||||
b.acc(q.x, q.y);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
b
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Achsraster in Schnitt und Ansicht ([112]): Rasterachsen quer zur Blickebene als senkrechte
|
||||
//! strichpunktierte Linien (x = Lage entlang der Schnittlinie, y = Höhe) mit Blase und Beschriftung
|
||||
//! oben (bzw. unten bei „nur Anfang"). Hängt als eigene Gruppe hinter dem Schnitt/der Ansicht.
|
||||
|
||||
use super::prim::Primitive;
|
||||
use super::section::{LevelSpec, Plane};
|
||||
use crate::grid::{bubble_diameter, section_axes, Spec};
|
||||
use crate::model::{Drawing2DGeom, GridBubbles, Project, Vec2};
|
||||
|
||||
const INK: &str = "#5a5f66";
|
||||
const AXIS_MM: f64 = 0.18;
|
||||
/// Überstand der Achse über die Gebäudehöhe und unter die Bodenlinie (Meter).
|
||||
const OVER_TOP: f64 = 0.8;
|
||||
const OVER_BOTTOM: f64 = 0.3;
|
||||
|
||||
fn v2(x: f64, y: f64) -> Vec2 {
|
||||
Vec2 { x, y }
|
||||
}
|
||||
|
||||
/// Achslinien und Blasen für eine Ebene; `bounds` = Ausmass des Schnitts/der Ansicht (x0, y0, x1, y1),
|
||||
/// `scale` = Massstabsnenner. Leer ohne Raster oder ohne Ebene.
|
||||
pub fn grid_prims(p: &Project, level: &LevelSpec, bounds: [f64; 4], scale: f64) -> Vec<Primitive> {
|
||||
let Some(plane) = level.plane() else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for d in &p.drawings2d {
|
||||
let Drawing2DGeom::Grid { bubble_mm, bubbles, .. } = &d.geom else { continue };
|
||||
let Some(spec) = Spec::of(&d.geom) else { continue };
|
||||
out.extend(one(&spec, &plane, level, bounds, scale, bubble_diameter(*bubble_mm, scale), bubbles.unwrap_or(GridBubbles::Both)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Ausmass der Achsen (für die Bounds des Aufrufers).
|
||||
pub fn extent(prims: &[Primitive]) -> Option<[f64; 4]> {
|
||||
let mut b: Option<[f64; 4]> = None;
|
||||
let mut acc = |x: f64, y: f64| {
|
||||
let r = b.get_or_insert([x, y, x, y]);
|
||||
r[0] = r[0].min(x);
|
||||
r[1] = r[1].min(y);
|
||||
r[2] = r[2].max(x);
|
||||
r[3] = r[3].max(y);
|
||||
};
|
||||
for q in prims {
|
||||
match q {
|
||||
Primitive::Line { a, b, .. } => {
|
||||
acc(a.x, a.y);
|
||||
acc(b.x, b.y);
|
||||
}
|
||||
Primitive::DrawingCircle { center, r, .. } => {
|
||||
acc(center.x - r, center.y - r);
|
||||
acc(center.x + r, center.y + r);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Vereinigt das Ausmass `bounds` mit dem der Achsen.
|
||||
pub fn union_bounds(bounds: [f64; 4], grid: &[Primitive]) -> [f64; 4] {
|
||||
extent(grid).map_or(bounds, |g| [bounds[0].min(g[0]), bounds[1].min(g[1]), bounds[2].max(g[2]), bounds[3].max(g[3])])
|
||||
}
|
||||
|
||||
fn one(spec: &Spec, plane: &Plane, level: &LevelSpec, bounds: [f64; 4], scale: f64, diameter: f64, bubbles: GridBubbles) -> Vec<Primitive> {
|
||||
let (bx, by) = plane.base();
|
||||
let (ux, uy) = plane.u_model();
|
||||
let l = ux.hypot(uy);
|
||||
if !(l > 1e-12) || !bounds.iter().all(|x| x.is_finite()) {
|
||||
return Vec::new();
|
||||
}
|
||||
let u = (ux / l, uy / l);
|
||||
// Länge der Schnittlinie in u: die Achsen ausserhalb dieser Spanne gehören nicht zum Bild.
|
||||
let [p0, p1] = level.line.unwrap_or([v2(bx, by), v2(bx, by)]);
|
||||
let e = (p1.x - p0.x) * u.0 + (p1.y - p0.y) * u.1;
|
||||
let (lo, hi) = (e.min(0.0), e.max(0.0));
|
||||
let mm = |x: f64| x * scale / 1000.0;
|
||||
let dash = vec![mm(12.0), mm(2.5), mm(1.5), mm(2.5)];
|
||||
let (y0, y1) = (bounds[1] - OVER_BOTTOM, bounds[3] + OVER_TOP);
|
||||
let (r, text_h) = (diameter / 2.0, diameter * 0.5);
|
||||
let mut out = Vec::new();
|
||||
for (label, x) in section_axes(spec, (bx, by), u, level.kind == "elevation") {
|
||||
if x < lo - 1e-9 || x > hi + 1e-9 {
|
||||
continue;
|
||||
}
|
||||
out.push(Primitive::Line {
|
||||
a: v2(x, y0),
|
||||
b: v2(x, y1),
|
||||
cls: "draw2d".into(),
|
||||
weight_mm: AXIS_MM,
|
||||
dash: Some(Some(dash.clone())),
|
||||
zigzag: None,
|
||||
motif: None,
|
||||
color: Some(INK.into()),
|
||||
drawing_id: None,
|
||||
opening_id: None,
|
||||
stair_id: None,
|
||||
greyed: None,
|
||||
opacity: None,
|
||||
});
|
||||
let (y, dir) = if bubbles == GridBubbles::Start { (y0, -1.0) } else { (y1, 1.0) };
|
||||
let c = v2(x, y + dir * r);
|
||||
out.push(Primitive::DrawingCircle { center: c, r, fill: "none".into(), stroke: INK.into(), weight_mm: 0.25, dash: None, drawing_id: None, greyed: None, opacity: None });
|
||||
let n = label.chars().count() as f64;
|
||||
out.push(Primitive::DrawingText {
|
||||
at: v2(c.x - text_h * 0.3 * n, c.y - text_h * 0.35),
|
||||
text: label.clone(),
|
||||
height_m: text_h,
|
||||
angle: 0.0,
|
||||
color: INK.into(),
|
||||
marks: None,
|
||||
wrap_width: None,
|
||||
doc: None,
|
||||
drawing_id: None,
|
||||
greyed: None,
|
||||
opacity: None,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn project(grid: serde_json::Value) -> Project {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "openings": [], "walls": [],
|
||||
"drawingLevels": [{"id": "F", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 0}],
|
||||
"drawings2d": [{"id": "G", "type": "drawing2d", "levelId": "F", "categoryCode": "20", "geom": grid}]
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn texts(prims: &[Primitive]) -> Vec<String> {
|
||||
prims.iter().filter_map(|q| if let Primitive::DrawingText { text, .. } = q { Some(text.clone()) } else { None }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn senkrechte_achsen_mit_blase() {
|
||||
let p = project(serde_json::json!({"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 4}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 6}]}));
|
||||
// Schnitt entlang +x bei y = 3 von x = -1 bis 8: schneidet die Achsen 1 und 2 (u = 1 und 5).
|
||||
let level = LevelSpec { kind: "section".into(), line: Some([v2(-1.0, 3.0), v2(8.0, 3.0)]), ..Default::default() };
|
||||
let prims = grid_prims(&p, &level, [0.0, 0.0, 9.0, 6.0], 100.0);
|
||||
let lines: Vec<(f64, f64, f64)> = prims.iter().filter_map(|q| if let Primitive::Line { a, b, .. } = q { Some((a.x, a.y, b.y)) } else { None }).collect();
|
||||
assert_eq!(lines.len(), 2, "{prims:?}");
|
||||
assert!((lines[0].0 - 1.0).abs() < 1e-9 && (lines[1].0 - 5.0).abs() < 1e-9);
|
||||
assert!(lines[0].1 < 0.0 && lines[0].2 > 6.0);
|
||||
assert_eq!(texts(&prims), ["1", "2"]);
|
||||
// Schnitt längs der Achsen 1/2: nur die waagrechten Achsen A, B queren.
|
||||
let level = LevelSpec { kind: "section".into(), line: Some([v2(2.0, -1.0), v2(2.0, 9.0)]), ..Default::default() };
|
||||
let prims = grid_prims(&p, &level, [0.0, 0.0, 9.0, 6.0], 100.0);
|
||||
assert_eq!(texts(&prims), ["A", "B"]);
|
||||
assert!(union_bounds([0.0, 0.0, 9.0, 6.0], &prims)[3] > 6.0);
|
||||
// Ansicht von Süden (y = -3): Achsen 1, 2 stehen senkrecht zur Ebene und erscheinen an ihrer Lage.
|
||||
let level = LevelSpec { kind: "elevation".into(), line: Some([v2(-1.0, -3.0), v2(8.0, -3.0)]), ..Default::default() };
|
||||
assert_eq!(texts(&grid_prims(&p, &level, [0.0, 0.0, 9.0, 6.0], 100.0)), ["1", "2"]);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ pub mod context;
|
||||
pub mod drawings;
|
||||
pub mod section;
|
||||
pub mod elevation;
|
||||
pub mod grid_view;
|
||||
pub mod cache;
|
||||
pub mod extras;
|
||||
pub mod underlay;
|
||||
|
||||
@@ -25,6 +25,9 @@ const SECTION_VISIBLE_MM: f64 = 0.18;
|
||||
const SECTION_GROUND_MM: f64 = 0.5;
|
||||
const SECTION_HIDDEN_MM: f64 = 0.13;
|
||||
const SECTION_HIDDEN_DASH: [f64; 2] = [0.12, 0.08];
|
||||
/// [T6] gewachsenes Terrain im Schnitt: gestrichelt, dünner als das gestaltete.
|
||||
const SECTION_NATURAL_MM: f64 = 0.25;
|
||||
const SECTION_NATURAL_DASH: [f64; 2] = [0.4, 0.2];
|
||||
/// Achswinkel geschnittener Wände/Decken für wandrelative Muster (s. `toSection.ts`).
|
||||
const SECTION_WALL_AXIS_ANGLE_DEG: f64 = 90.0;
|
||||
/// Decken liegen: wandbezogene Muster laufen waagrecht entlang der Schicht ([109]; vorher 90° wie Wände,
|
||||
@@ -187,6 +190,8 @@ pub struct Edge {
|
||||
pub struct Profile {
|
||||
pub category: Option<String>,
|
||||
pub pts: Vec<[f64; 2]>,
|
||||
/// [T6] gewachsenes Terrain (gestrichelt), nur wenn Baugruben das Gelände ändern.
|
||||
pub natural: bool,
|
||||
}
|
||||
|
||||
/// Ergebnis eines Schnitts (`SectionOutput`).
|
||||
@@ -196,6 +201,8 @@ pub struct Output {
|
||||
pub visible: Vec<Edge>,
|
||||
pub hidden: Vec<Edge>,
|
||||
pub profiles: Vec<Profile>,
|
||||
/// [T6] Erdreich unter dem gestalteten Terrain (Band, ohne Gebäude-Inneres), mit Schraffur.
|
||||
pub earth: Vec<(Vec<[f64; 2]>, HatchRender)>,
|
||||
}
|
||||
|
||||
/// Ein truck-Körper (aus TS, asynchron gebaut): Index in `extrudedSolids` + Netz.
|
||||
@@ -321,6 +328,7 @@ fn wall_input(w: &RWall) -> render3d::WallInput {
|
||||
height: json_f32(w.height),
|
||||
base_elevation: json_f32(w.base_elevation),
|
||||
top_drop: w.top_drop.map_or([0.0, 0.0], f32s2),
|
||||
top_plane: w.top_plane.map(f32s3),
|
||||
color: f32s3(w.color),
|
||||
openings: Vec::new(),
|
||||
layers: Some(Vec::new()),
|
||||
@@ -1448,14 +1456,85 @@ fn append_terrain_profiles(out: &mut Output, p: &Project, base: (f64, f64), u: (
|
||||
if t.positions.len() < 9 {
|
||||
continue;
|
||||
}
|
||||
let (_, lines) = cut_mesh(&t.positions, &t.indices, base, u);
|
||||
for line in lines {
|
||||
let parts = match range {
|
||||
Some((lo, hi)) => clip_line_to_u(&line, lo - TERRAIN_MARGIN, hi + TERRAIN_MARGIN),
|
||||
None => vec![line],
|
||||
};
|
||||
for pts in parts {
|
||||
out.profiles.push(Profile { category: t.category_code.clone(), pts });
|
||||
// [T6] Gelände samt Baugruben, Höhen im Modellbezug; das gewachsene Terrain gestrichelt dazu.
|
||||
let st = crate::excavation::site_terrain(p, t);
|
||||
let mut meshes = vec![(st.current().to_flat(-st.datum), false)];
|
||||
if st.modified.is_some() {
|
||||
meshes.push((st.orig.to_flat(-st.datum), true));
|
||||
}
|
||||
for ((pos, idx), natural) in meshes {
|
||||
let (_, lines) = cut_mesh(&pos, &idx, base, u);
|
||||
for line in lines {
|
||||
let parts = match range {
|
||||
Some((lo, hi)) => clip_line_to_u(&line, lo - TERRAIN_MARGIN, hi + TERRAIN_MARGIN),
|
||||
None => vec![line],
|
||||
};
|
||||
for pts in parts {
|
||||
out.profiles.push(Profile { category: t.category_code.clone(), pts, natural });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
append_earth(out, p, base, u);
|
||||
}
|
||||
|
||||
/// Tiefe des Erdreich-Bands unter der Geländelinie (m).
|
||||
const EARTH_BAND: f64 = 1.5;
|
||||
|
||||
/// [T6]/[109] Erdreich: Band unter dem gestalteten Terrain mit SIA-Erdreich-Schraffur, ohne das
|
||||
/// Gebäude-Innere (Grundfläche im Schnitt, von der tiefsten Schnittfläche aufwärts); die geschnittenen
|
||||
/// Bauteile selbst liegen ohnehin darüber.
|
||||
fn append_earth(out: &mut Output, p: &Project, base: (f64, f64), u: (f64, f64)) {
|
||||
let mut band: Vec<crate::flat::Polygon> = Vec::new();
|
||||
for pr in out.profiles.iter().filter(|pr| !pr.natural && pr.pts.len() >= 2) {
|
||||
let mut ring = pr.pts.clone();
|
||||
ring.extend(pr.pts.iter().rev().map(|q| [q[0], q[1] - EARTH_BAND]));
|
||||
band.push(vec![ring]);
|
||||
}
|
||||
if band.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut band = crate::polygon_bool::union(&band);
|
||||
// Gebäude-Inneres: Abschnitte der Schnittlinie in der Grundfläche.
|
||||
let mut holes: Vec<crate::flat::Polygon> = Vec::new();
|
||||
for poly in crate::site_rules::building_footprint(p) {
|
||||
let mut ts: Vec<f64> = Vec::new();
|
||||
for ring in &poly {
|
||||
let n = ring.len();
|
||||
for i in 0..n {
|
||||
let (a, b) = (ring[i], ring[(i + 1) % n]);
|
||||
// Schnitt der Geraden base + s·u mit der Kante a–b.
|
||||
let (ex, ey) = (b.x - a.x, b.y - a.y);
|
||||
let den = u.0 * ey - u.1 * ex;
|
||||
if den.abs() < 1e-12 {
|
||||
continue;
|
||||
}
|
||||
let (wx, wy) = (a.x - base.0, a.y - base.1);
|
||||
let s_ = (wx * ey - wy * ex) / den;
|
||||
let t_ = (wx * u.1 - wy * u.0) / den;
|
||||
if (0.0..1.0).contains(&t_) {
|
||||
ts.push(s_);
|
||||
}
|
||||
}
|
||||
}
|
||||
ts.sort_by(|a, b| a.total_cmp(b));
|
||||
for w in ts.chunks_exact(2) {
|
||||
let (u0, u1) = (w[0], w[1]);
|
||||
let low = out.cuts.iter().flat_map(|c| c.pts.iter()).filter(|q| q[0] >= u0 - 1e-6 && q[0] <= u1 + 1e-6).map(|q| q[1]).fold(f64::INFINITY, f64::min);
|
||||
if low.is_finite() {
|
||||
holes.push(vec![vec![[u0, low], [u1, low], [u1, 1e4], [u0, 1e4]]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !holes.is_empty() {
|
||||
band = crate::polygon_bool::difference(&band, &holes);
|
||||
}
|
||||
let hatch = super::style::resolve_hatch(p, "std-h-erdreich", None, None, None)
|
||||
.unwrap_or(HatchRender { pattern: HatchPattern::Earth, scale: 1.0, angle: 45.0, color: HATCH_INK.into(), line_weight: 0.1, ..no_hatch_base() });
|
||||
for poly in band {
|
||||
if let Some(outer) = poly.into_iter().next() {
|
||||
if outer.len() >= 3 {
|
||||
out.earth.push((outer, hatch.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1735,7 +1814,7 @@ pub fn compute_section(p: &Project, level: &LevelSpec, bodies: &[BodyMesh]) -> R
|
||||
// Projektion hinter der Ebene exakt ([G4]); die Schnittflächen verdecken, was hinter ihnen liegt.
|
||||
let (mut visible, hidden) = projection_edges(p, &plane, &walls_r, &wi, &slabs_r, bodies, &cuts, level.hidden_lines);
|
||||
shaped_projection(&mut visible, p, &walls_r, &plane);
|
||||
let mut out = Output { cuts, visible, hidden, profiles: Vec::new() };
|
||||
let mut out = Output { cuts, visible, hidden, profiles: Vec::new(), earth: Vec::new() };
|
||||
append_terrain_profiles(&mut out, p, base, u);
|
||||
if let Some(d) = level.depth {
|
||||
filter_by_depth(&mut out, p, &plane, d, &walls, &slabs, &slabs_r);
|
||||
@@ -1818,6 +1897,14 @@ pub fn section_primitives(out: &Output, mono: bool, hidden_lines: bool, vis: &Vi
|
||||
let mut prims = Vec::new();
|
||||
let mut acc = Acc::new();
|
||||
let shown = |code: &str| vis.visible(code) && vis.render(code);
|
||||
// [T6] Erdreich zuerst (unter allem), ohne Umriss; Kategorie wie das Gelände.
|
||||
let terrain_shown = out.profiles.iter().all(|pr| pr.category.as_deref().is_none_or(shown));
|
||||
if terrain_shown {
|
||||
for (ring, hatch) in &out.earth {
|
||||
let hatch = if mono { HatchRender { color: SECTION_INK.into(), ..hatch.clone() } } else { hatch.clone() };
|
||||
prims.push(polygon(ring.iter().map(|q| v2(q[0], q[1])).collect(), "none", "none", 0.0, hatch));
|
||||
}
|
||||
}
|
||||
for cp in &out.cuts {
|
||||
if cp.pts.len() < 3 {
|
||||
continue;
|
||||
@@ -1867,7 +1954,13 @@ pub fn section_primitives(out: &Output, mono: bool, hidden_lines: bool, vis: &Vi
|
||||
for w in pr.pts.windows(2) {
|
||||
acc.add(w[0][0], w[0][1]);
|
||||
acc.add(w[1][0], w[1][1]);
|
||||
prims.push(line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), "section-terrain", SECTION_GROUND_MM, SECTION_INK));
|
||||
let mut l = line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), "section-terrain", if pr.natural { SECTION_NATURAL_MM } else { SECTION_GROUND_MM }, SECTION_INK);
|
||||
if pr.natural {
|
||||
if let Primitive::Line { dash, .. } = &mut l {
|
||||
*dash = Some(Some(SECTION_NATURAL_DASH.to_vec()));
|
||||
}
|
||||
}
|
||||
prims.push(l);
|
||||
}
|
||||
}
|
||||
if hidden_lines {
|
||||
@@ -1886,7 +1979,8 @@ pub fn section_primitives(out: &Output, mono: bool, hidden_lines: bool, vis: &Vi
|
||||
acc.add(e.b[0], e.b[1]);
|
||||
prims.push(line(v2(e.a[0], e.a[1]), v2(e.b[0], e.b[1]), "section-visible", SECTION_VISIBLE_MM, SECTION_VISIBLE_INK));
|
||||
}
|
||||
if acc.min_x.is_finite() && acc.max_x > acc.min_x {
|
||||
// Mit Gelände ersetzt die Geländelinie die Grundlinie ([T6]).
|
||||
if acc.min_x.is_finite() && acc.max_x > acc.min_x && !(terrain_shown && !out.profiles.is_empty()) {
|
||||
prims.push(line(v2(acc.min_x, acc.min_y), v2(acc.max_x, acc.min_y), "section-ground", SECTION_GROUND_MM, SECTION_INK));
|
||||
}
|
||||
(prims, acc.bounds())
|
||||
@@ -2382,7 +2476,12 @@ pub fn section_plan_buf(p: &Project, args: &[f64], text: &str) -> Result<Vec<u8>
|
||||
w.group(&prims);
|
||||
let ops = if openings { section_opening_primitives(p, &level, &vis)? } else { Vec::new() };
|
||||
w.group(&ops);
|
||||
w.bounds = Some(bounds);
|
||||
// Achsraster ([112]): Achsen quer zur Schnittebene.
|
||||
let grid = super::grid_view::grid_prims(p, &level, bounds, v.get("scale").and_then(|s| s.as_f64()).filter(|s| *s > 0.0).unwrap_or(100.0));
|
||||
if !grid.is_empty() {
|
||||
w.group(&grid);
|
||||
}
|
||||
w.bounds = Some(super::grid_view::union_bounds(bounds, &grid));
|
||||
Ok(w.finish())
|
||||
}
|
||||
|
||||
@@ -2608,6 +2707,43 @@ mod tests {
|
||||
assert!(serde_json::to_string(&prims).unwrap().contains("section-hidden"));
|
||||
}
|
||||
|
||||
/// [T6]/[68] Gelände mit Baugrube: gestaltetes + gewachsenes Terrain, Erdreich ohne Gebäude-Inneres;
|
||||
/// Fassaden-Geländehöhen fürs Baurecht.
|
||||
#[test]
|
||||
fn gelaende_mit_baugrube_im_schnitt() {
|
||||
let mut p = sample();
|
||||
let flat = TerrainMesh {
|
||||
id: "t".into(),
|
||||
positions: vec![-50.0, -50.0, 0.0, 50.0, -50.0, 0.0, 50.0, 50.0, 0.0, -50.0, 50.0, 0.0],
|
||||
indices: vec![0.0, 1.0, 2.0, 0.0, 2.0, 3.0],
|
||||
category_code: Some("02".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let pit = Excavation {
|
||||
id: "bg".into(),
|
||||
outline: vec![Vec2 { x: -1.0, y: -1.0 }, Vec2 { x: 6.0, y: -1.0 }, Vec2 { x: 6.0, y: 5.0 }, Vec2 { x: -1.0, y: 5.0 }],
|
||||
bottom: -2.0,
|
||||
..Default::default()
|
||||
};
|
||||
p.context = Some(vec![ContextObject::TerrainMesh(flat), ContextObject::Excavation(pit)]);
|
||||
let out = compute_section(&p, &level(&p, "schnitt-a"), &[]).unwrap().unwrap();
|
||||
assert!(out.profiles.iter().any(|pr| pr.natural) && out.profiles.iter().any(|pr| !pr.natural));
|
||||
let designed_min = out.profiles.iter().filter(|pr| !pr.natural).flat_map(|pr| pr.pts.iter().map(|q| q[1])).fold(f64::INFINITY, f64::min);
|
||||
assert!((designed_min + 2.0).abs() < 1e-6, "{designed_min}");
|
||||
assert!(!out.earth.is_empty());
|
||||
let (prims, _) = section_primitives(&out, false, false, &Visibility::default());
|
||||
assert!(prims.iter().any(|q| matches!(q, Primitive::Polygon { hatch, .. } if hatch.pattern == HatchPattern::Earth)));
|
||||
assert!(prims.iter().any(|q| matches!(q, Primitive::Line { cls, dash: Some(Some(_)), .. } if cls == "section-terrain")));
|
||||
let (ep, _) = super::super::elevation::elevation_primitives(&p, &level(&p, "ansicht-sued"), false, false, &Visibility::default(), 100.0).unwrap().unwrap();
|
||||
let sil: Vec<f64> = ep.iter().filter_map(|q| if let Primitive::Line { cls, a, b, .. } = q { (cls == "elevation-terrain").then_some(a.y.min(b.y)) } else { None }).collect();
|
||||
// Die Ansichtslinie (y = −2) liegt in der Böschung: die Silhouette taucht vor dem Gebäude ein, nie unter die Sohle.
|
||||
assert!(!sil.is_empty() && sil.iter().all(|z| *z <= 1e-6 && *z >= -2.0 - 1e-6) && sil.iter().any(|z| *z < -0.5), "{sil:?}");
|
||||
assert!(ep.iter().any(|q| matches!(q, Primitive::Polygon { fill, .. } if fill == "#ffffff")));
|
||||
assert!(!ep.iter().any(|q| matches!(q, Primitive::Line { cls, .. } if cls == "elevation-ground")));
|
||||
let f = crate::site_rules::facade_terrain(&p);
|
||||
assert!(!f.is_empty() && f.iter().all(|q| q.natural == Some(0.0) && q.designed.is_some_and(|z| (z + 2.0).abs() < 1e-6)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn beschnittene_baender_behalten_ihre_ebene() {
|
||||
// Von der Dominanz beschnittene Wand-/Deckenstücke tragen ihre Kategorie weiter: Ebene aus → weg.
|
||||
@@ -3032,3 +3168,84 @@ mod abzug_faelle {
|
||||
assert_eq!(out[0].nse.as_ref().map(|n| n.len()), Some(2), "Schlüsselloch-Stege ungestrichen");
|
||||
}
|
||||
}
|
||||
|
||||
/// [G2] Wand an Dach: Schnitt und 3D-Körper der Wände unter einem Satteldach.
|
||||
#[cfg(test)]
|
||||
mod wand_an_dach {
|
||||
use super::*;
|
||||
|
||||
fn haus() -> Project {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "drawings2d": [],
|
||||
"drawingLevels": [
|
||||
{"id": "F", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 0},
|
||||
{"id": "q", "name": "Q", "kind": "section", "visible": true, "locked": false, "linePoints": [{"x": 2, "y": -2}, {"x": 2, "y": 10}], "directionSign": 1},
|
||||
{"id": "l", "name": "L", "kind": "section", "visible": true, "locked": false, "linePoints": [{"x": -2, "y": 4}, {"x": 12, "y": 4}], "directionSign": 1}
|
||||
],
|
||||
"walls": [
|
||||
{"id": "WS", "type": "wall", "floorId": "F", "categoryCode": "20", "start": {"x": 0, "y": 0}, "end": {"x": 10, "y": 0}, "height": 3.5},
|
||||
{"id": "WW", "type": "wall", "floorId": "F", "categoryCode": "20", "start": {"x": 0, "y": 8}, "end": {"x": 0, "y": 0}, "height": 9.0},
|
||||
{"id": "WB", "type": "wall", "floorId": "F", "categoryCode": "20", "start": {"x": 6, "y": 1}, "end": {"x": 6, "y": 7}, "height": 9.0, "bulge": 0.4}
|
||||
],
|
||||
"openings": [{"id": "F1", "type": "opening", "hostWallId": "WW", "categoryCode": "21", "kind": "window", "position": 3.5, "width": 1.0, "height": 1.2, "sillHeight": 3.6}],
|
||||
"roofs": [{"id": "R", "type": "roof", "floorId": "F", "categoryCode": "35",
|
||||
"outline": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 8}, {"x": 0, "y": 8}],
|
||||
"shape": "sattel", "pitchDeg": 45, "overhang": 0.5, "ridgeAxis": "x", "thickness": 0.3}]
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Dach-Unterkante (Traufkante 3.0 bei y = −0.5, 45°, Dicke 0.3 senkrecht).
|
||||
fn under(y: f64) -> f64 {
|
||||
3.0 + (4.5 - (y - 4.0).abs()) - 0.3 * 2f64.sqrt()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schnitt_endet_an_der_dachunterkante() {
|
||||
let p = haus();
|
||||
for id in ["q", "l"] {
|
||||
let l = p.drawing_levels.iter().find(|l| l.id == id).unwrap();
|
||||
let level = LevelSpec::from_json(&serde_json::to_value(l).unwrap());
|
||||
let out = compute_section(&p, &level, &[]).unwrap().unwrap();
|
||||
let walls: Vec<&Cut> = out.cuts.iter().filter(|c| c.kind == Kind::Wall).collect();
|
||||
assert!(!walls.is_empty());
|
||||
let top = walls.iter().flat_map(|c| c.pts.iter().map(|q| q[1])).fold(f64::NEG_INFINITY, f64::max);
|
||||
// Nie über der First-Unterkante.
|
||||
assert!(top <= under(4.0) + 1e-4, "{id}: {top}");
|
||||
}
|
||||
// Querschnitt quer zum First: Traufwand mit schräger Krone.
|
||||
let l = p.drawing_levels.iter().find(|l| l.id == "q").unwrap();
|
||||
let out = compute_section(&p, &LevelSpec::from_json(&serde_json::to_value(l).unwrap()), &[]).unwrap().unwrap();
|
||||
let sloped = out.cuts.iter().filter(|c| c.kind == Kind::Wall).any(|c| {
|
||||
let ys: Vec<f64> = c.pts.iter().map(|q| q[1]).filter(|v| *v > 2.0).collect();
|
||||
ys.len() >= 2 && (ys.iter().copied().fold(f64::NEG_INFINITY, f64::max) - ys.iter().copied().fold(f64::INFINITY, f64::min)) > 0.1
|
||||
});
|
||||
assert!(sloped, "Traufwand im Querschnitt mit schräger Krone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn koerper_dicht_und_volumen_exakt() {
|
||||
let p = haus();
|
||||
let walls = model3d::emit_walls(&p, true).unwrap();
|
||||
let ww: Vec<&RWall> = walls.iter().filter(|w| w.wall_id == "WW").collect();
|
||||
let mut vol = 0.0;
|
||||
for w in walls.iter().filter(|w| w.top_plane.is_some()) {
|
||||
let m = model3d::wall_piece_mesh(w).unwrap();
|
||||
assert!(m.is_closed(), "{w:?}");
|
||||
assert!((m.volume().abs() - model3d::wall_piece_volume(w)).abs() < 1e-9);
|
||||
}
|
||||
for w in &ww {
|
||||
assert!(w.holes.as_ref().is_none_or(|h| h.is_empty()), "Fenster unter dem Dach als Teilkörper: {w:?}");
|
||||
vol += model3d::wall_piece_volume(w);
|
||||
}
|
||||
// Giebelwand: Fünfeck unter der Unterkante × Dicke, minus Fenster.
|
||||
let t = p.wall_thickness(&p.walls[1], 0.2);
|
||||
let area = |y0: f64, y1: f64| (y1 - y0) * (under(y0) + under(y1)) / 2.0;
|
||||
let expect = t * (area(0.0, 4.0) + area(4.0, 8.0) - 1.2);
|
||||
// Gehrungen an den Ecken ändern das Volumen nur an den Enden.
|
||||
assert!((vol - expect).abs() < t * t * 7.0, "{vol} vs {expect}");
|
||||
// Bogenwand ([T2]): Sehnen-Teilwände ebenfalls unter dem Dach.
|
||||
let wb: Vec<&RWall> = walls.iter().filter(|w| w.wall_id == "WB").collect();
|
||||
assert!(wb.len() > 4 && wb.iter().all(|w| w.base_elevation + w.height <= under(4.0) + 1e-6), "{}", wb.len());
|
||||
}
|
||||
}
|
||||
@@ -1231,7 +1231,8 @@ fn emit_entries(cx: &mut Ctx, main: &mut Buf, entries: &[Entry], layer_by_code:
|
||||
let mut block_by_id: HashMap<&str, &Drawing2D> = HashMap::new();
|
||||
for d in &project.drawings2d {
|
||||
match d.geom {
|
||||
Drawing2DGeom::Dimension { .. } => {
|
||||
// Radius-/Durchmesser-/Bogenmass (`kind`) geht als Linien, Bögen und Text hinaus.
|
||||
Drawing2DGeom::Dimension { kind: None, .. } => {
|
||||
dim_by_id.insert(d.id.as_str(), d);
|
||||
}
|
||||
Drawing2DGeom::Block { .. } => {
|
||||
|
||||
@@ -476,8 +476,22 @@ fn wall_faces(f: &Frame, w: &[f64], src: usize, out: &mut Vec<Projected>) {
|
||||
let ht = w[4] / 2.0;
|
||||
let zb = w[6];
|
||||
let zt = w[6] + w[5];
|
||||
// Ebene Oberkante unter einem Dach ([G2]): Deckel-Ecken auf der Ebene.
|
||||
let plane = (w.len() >= 17 && w[13] == 1.0).then(|| [w[14], w[15], w[16]]);
|
||||
let corner = |s_along: f64, t_off: f64, y: f64| -> V3 {
|
||||
[sx + a_hat[0] * s_along + n_hat[0] * t_off, y, sz + a_hat[2] * s_along + n_hat[2] * t_off]
|
||||
let (x, z) = (sx + a_hat[0] * s_along + n_hat[0] * t_off, sz + a_hat[2] * s_along + n_hat[2] * t_off);
|
||||
let y = match plane {
|
||||
Some(c) if y == zt => (c[0] + c[1] * (x - sx) + c[2] * (z - sz)).clamp(zb, zt),
|
||||
_ => y,
|
||||
};
|
||||
[x, y, z]
|
||||
};
|
||||
let top_n: V3 = match plane {
|
||||
Some(c) => {
|
||||
let l = (c[1] * c[1] + 1.0 + c[2] * c[2]).sqrt();
|
||||
[-c[1] / l, 1.0 / l, -c[2] / l]
|
||||
}
|
||||
None => [0.0, 1.0, 0.0],
|
||||
};
|
||||
// Schnitt-Verschiebungen der vier Ecken längs der Achse ([T2]: Gehrung der Bogen-Teilkörper):
|
||||
// Anfang +n, Anfang −n, Ende +n, Ende −n; ohne Angabe 0 (rechtwinklig wie bisher).
|
||||
@@ -506,7 +520,7 @@ fn wall_faces(f: &Frame, w: &[f64], src: usize, out: &mut Vec<Projected>) {
|
||||
(neg(n_hat), [corner(s_m, -ht, zb), corner(s_m, -ht, zt), corner(e_m, -ht, zt), corner(e_m, -ht, zb)]),
|
||||
(start_n, [corner(s_m, -ht, zb), corner(s_p, ht, zb), corner(s_p, ht, zt), corner(s_m, -ht, zt)]),
|
||||
(end_n, [corner(e_m, -ht, zb), corner(e_m, -ht, zt), corner(e_p, ht, zt), corner(e_p, ht, zb)]),
|
||||
([0.0, 1.0, 0.0], [corner(s_m, -ht, zt), corner(s_p, ht, zt), corner(e_p, ht, zt), corner(e_m, -ht, zt)]),
|
||||
(top_n, [corner(s_m, -ht, zt), corner(s_p, ht, zt), corner(e_p, ht, zt), corner(e_m, -ht, zt)]),
|
||||
([0.0, -1.0, 0.0], [corner(s_m, -ht, zb), corner(e_m, -ht, zb), corner(e_p, ht, zb), corner(s_p, ht, zb)]),
|
||||
];
|
||||
for (i, (normal, poly)) in faces.into_iter().enumerate() {
|
||||
@@ -648,6 +662,9 @@ pub(crate) fn faces_full(frame: &[f64], walls: &[f64], slabs: &[f64], roofs: &[f
|
||||
7
|
||||
} else if walls.len() == 1 + 13 * nw {
|
||||
13
|
||||
} else if walls.len() == 1 + 17 * nw {
|
||||
// + ebene Oberkante ([G2]): Kennung (1 = vorhanden), z am Anfang, dz/dx, dz/dy.
|
||||
17
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -23,6 +23,7 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
|
||||
json(&room_program::layout(p, &opt))
|
||||
}
|
||||
("siteCheck", _) => json(&site_rules::check_project(p)),
|
||||
("excavationQuantities", _) => json(&crate::excavation::quantities(p)),
|
||||
("buildingFootprint", _) => json(&site_rules::building_footprint(p)),
|
||||
("modelTop", _) => json(&site_rules::model_top(p)),
|
||||
("shadows", 2) => json(&site_rules::area_out(&sun::shadow_polygons_project(p, sun::SunPosition { azimuth: args[0], elevation: args[1] }))),
|
||||
|
||||
@@ -826,7 +826,7 @@ mod tests {
|
||||
#[test]
|
||||
fn planar_faces_keep_area() {
|
||||
let mut r = sattel("R", [[0.0, 0.0], [10.0, 8.0]], "x");
|
||||
r["dormers"] = serde_json::json!([{"id": "D", "kind": "sattel", "position": {"x": 4.0, "y": 1.2}, "width": 2.4, "frontHeight": 1.3}]);
|
||||
r["dormers"] = serde_json::json!([{"id": "D", "kind": "sattel", "position": {"x": 4.0, "y": 1.2}, "width": 2.4, "frontHeight": 1.0}]);
|
||||
let p = base_project(serde_json::json!([r]));
|
||||
let s = roof_solids(&p, 0).unwrap();
|
||||
let all: Vec<usize> = (0..s.skin.indices.len() / 3).collect();
|
||||
@@ -844,7 +844,8 @@ mod tests {
|
||||
let faces = planar_faces(&s.skin, &all);
|
||||
let face_area: f64 = faces.iter().map(|f| area3(f)).sum();
|
||||
assert!((tri_area - face_area).abs() < 1e-6 * tri_area, "{tri_area} vs {face_area}");
|
||||
assert!(faces.len() * 2 < all.len(), "zusammengefasst: {} Flächen aus {} Dreiecken", faces.len(), all.len());
|
||||
// Gaubendach endet am First ([G5]): ein paar Dreiecke mehr im Hauptdach-Querschnitt.
|
||||
assert!(faces.len() * 3 < all.len() * 2, "zusammengefasst: {} Flächen aus {} Dreiecken", faces.len(), all.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -488,6 +488,8 @@ fn wall_selection(root: &Map<String, Value>, w: &Value) -> Result<J, String> {
|
||||
.raw("referenceOffset", w, "referenceOffset")
|
||||
.v("layerBoundaries", J::arr(boundaries))
|
||||
.v("sliceTermination", nn(field(w, "sliceTermination")).cloned().unwrap_or_else(|| "both".into()))
|
||||
// An Dach anschliessen ([G2]): fehlt = automatisch.
|
||||
.v("roofAttach", Value::String(match field(w, "roofAttach").and_then(|v| v.as_bool()) { Some(true) => "on", Some(false) => "off", None => "auto" }.into()))
|
||||
.raw("wallTypeId", w, "wallTypeId")
|
||||
.n("thickness", thickness)
|
||||
.v("singleLayer", Value::Bool(layers.len() <= 1))
|
||||
@@ -912,6 +914,7 @@ fn stair_selection(root: &Map<String, Value>, s: &Value) -> Result<J, String> {
|
||||
.v("up", Value::Bool(field(s, "up") != Some(&Value::Bool(false))))
|
||||
.raw("arrowStyle", s, "arrowStyle")
|
||||
.raw("referenz", s, "referenz")
|
||||
.raw("centerColumn", s, "centerColumn")
|
||||
.raw("typeId", s, "typeId")
|
||||
.raw("floorId", s, "floorId")
|
||||
.o("floorName", floor_name(floor, field(s, "floorId")))
|
||||
@@ -1133,6 +1136,16 @@ pub fn geom_bbox(g: &Value) -> [f64; 4] {
|
||||
}
|
||||
}
|
||||
Some("kote" | "text" | "block" | "detailref" | "pointmarker") => pts.push(p("at")),
|
||||
Some("grid") => {
|
||||
if let Some(spec) = serde_json::from_value::<crate::model::Drawing2DGeom>(g.clone()).ok().as_ref().and_then(crate::grid::Spec::of) {
|
||||
for ax in spec.axes() {
|
||||
match ax.shape {
|
||||
crate::grid::Shape::Line { a, b } => pts.extend([a, b]),
|
||||
crate::grid::Shape::Arc { c, r, .. } => pts.extend([(c.0 - r, c.1 - r), (c.0 + r, c.1 + r)]),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("scalebar") => {
|
||||
let at = p("at");
|
||||
pts.extend([at, (at.0 + num_of(field(g, "segmentLength")) * num_of(field(g, "segments")), at.1)]);
|
||||
|
||||
@@ -86,6 +86,15 @@ const ELEMENTS: &[Col] = &[
|
||||
c("ext", "openings.col.ext", 1.4, false, false),
|
||||
];
|
||||
|
||||
const EARTHWORKS: &[Col] = &[
|
||||
c("name", "sheetTable.col.name", 2.4, false, true),
|
||||
c("bottom", "sheetTable.col.bottom", 1.3, true, true),
|
||||
c("area", "sheetTable.col.area", 1.3, true, true),
|
||||
c("cut", "sheetTable.col.cut", 1.4, true, true),
|
||||
c("fill", "sheetTable.col.fill", 1.4, true, true),
|
||||
c("backfill", "sheetTable.col.backfill", 1.6, true, true),
|
||||
];
|
||||
|
||||
/// Schlüssel der Werttexte (Art, aussen/innen, Aufschlag …).
|
||||
pub const VALUE_KEYS: &[&str] = &[
|
||||
"sheetTable.v.window",
|
||||
@@ -111,6 +120,7 @@ pub fn catalog(source: LayoutTableSource) -> &'static [Col] {
|
||||
LayoutTableSource::Areas => AREAS,
|
||||
LayoutTableSource::Rooms => ROOMS,
|
||||
LayoutTableSource::Elements => ELEMENTS,
|
||||
LayoutTableSource::Earthworks => EARTHWORKS,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,7 +128,7 @@ pub fn catalog(source: LayoutTableSource) -> &'static [Col] {
|
||||
pub fn catalog_json() -> Value {
|
||||
let one = |s: &[Col]| s.iter().map(|k| json!({"id": k.id, "key": k.key, "numeric": k.numeric, "default": k.default})).collect::<Vec<_>>();
|
||||
json!({
|
||||
"sources": {"openings": one(OPENINGS), "areas": one(AREAS), "rooms": one(ROOMS), "elements": one(ELEMENTS)},
|
||||
"sources": {"openings": one(OPENINGS), "areas": one(AREAS), "rooms": one(ROOMS), "elements": one(ELEMENTS), "earthworks": one(EARTHWORKS)},
|
||||
"valueKeys": VALUE_KEYS,
|
||||
})
|
||||
}
|
||||
@@ -250,9 +260,22 @@ fn data_of(p: &Project, t: &LayoutTable, lb: &Labels) -> Data {
|
||||
LayoutTableSource::Areas => areas_data(p, lb),
|
||||
LayoutTableSource::Rooms => rooms_data(p),
|
||||
LayoutTableSource::Elements => elements_data(p, lb),
|
||||
LayoutTableSource::Earthworks => earthworks_data(p, lb),
|
||||
}
|
||||
}
|
||||
|
||||
/// [68] Erdarbeiten je Baugrube (m³ gegen das gewachsene Terrain) mit Summenzeile.
|
||||
fn earthworks_data(p: &Project, lb: &Labels) -> Data {
|
||||
let q = crate::excavation::quantities(p);
|
||||
let mut rows: Vec<Vec<Cell>> = q.iter().map(|e| vec![txt(e.name.clone()), num(e.bottom, 2), num(e.bottom_area, 1), num(e.cut, 1), num(e.fill, 1), num(e.backfill, 1)]).collect();
|
||||
let total_last = q.len() > 1;
|
||||
if total_last {
|
||||
let s = |f: fn(&crate::excavation::ExQty) -> f64| q.iter().map(f).sum::<f64>();
|
||||
rows.push(vec![txt(lb.get("sheetTable.v.total")), num(f64::NAN, 2), num(s(|e| e.bottom_area), 1), num(s(|e| e.cut), 1), num(s(|e| e.fill), 1), num(s(|e| e.backfill), 1)]);
|
||||
}
|
||||
Data { rows, total_last }
|
||||
}
|
||||
|
||||
/// Gewählte Spalten als Indizes in den Katalog (unbekannte Kennungen fallen weg; leer ⇒ Standard).
|
||||
fn column_indices(t: &LayoutTable) -> Vec<usize> {
|
||||
let cat = catalog(t.source);
|
||||
|
||||
@@ -340,6 +340,43 @@ pub struct SiteCheckOut {
|
||||
pub violation_area: f64,
|
||||
pub max_top: Option<f64>,
|
||||
pub height_exceeded: bool,
|
||||
/// [T6] Geländehöhen an der Fassade (Grundfläche, Ecken + alle ≤ 2 m), Modellbezug; leer ohne Gelände.
|
||||
pub facade_terrain: Vec<FacadePoint>,
|
||||
/// Tiefster Punkt des gewachsenen Terrains an der Fassade (massgebendes Terrain, vereinfacht).
|
||||
pub terrain_min: Option<f64>,
|
||||
/// Gesamthöhe über dem massgebenden Terrain (`maxTop − terrainMin`); ohne Gelände `None` (dann gilt ±0.00).
|
||||
pub height_above_terrain: Option<f64>,
|
||||
}
|
||||
|
||||
/// Fassadenpunkt mit gewachsenem und gestaltetem Terrain (Modellbezug; `None` ausserhalb des Geländes).
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct FacadePoint {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub natural: Option<f64>,
|
||||
pub designed: Option<f64>,
|
||||
}
|
||||
|
||||
/// Geländehöhen an der Fassade: Ecken der Aussenringe der Grundfläche und Zwischenpunkte (≤ 2 m).
|
||||
pub fn facade_terrain(p: &Project) -> Vec<FacadePoint> {
|
||||
if crate::excavation::terrains(p).is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for poly in building_footprint(p) {
|
||||
let Some(ring) = poly.first() else { continue };
|
||||
let n = ring.len();
|
||||
for i in 0..n {
|
||||
let (a, b) = (ring[i], ring[(i + 1) % n]);
|
||||
let k = (hypot2(b.x - a.x, b.y - a.y) / 2.0).ceil().max(1.0) as usize;
|
||||
for j in 0..k {
|
||||
let f = j as f64 / k as f64;
|
||||
let (x, y) = (a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f);
|
||||
out.push(FacadePoint { x, y, natural: crate::excavation::terrain_z(p, x, y, false), designed: crate::excavation::terrain_z(p, x, y, true) });
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Prüft das Modell gegen `siteRules`; `None` ohne (gültiges) Baurecht.
|
||||
@@ -351,7 +388,12 @@ pub fn check_project(p: &Project) -> Option<SiteCheckOut> {
|
||||
setbacks: (0..r.parcel.len()).map(|i| r.setbacks.as_ref().and_then(|s| s.get(i)).copied().unwrap_or(r.default_setback)).collect(),
|
||||
lines: r.building_lines.as_deref().unwrap_or(&[]).iter().map(|l| BuildingLine { a: [l.a.x, l.a.y], b: [l.b.x, l.b.y] }).collect(),
|
||||
};
|
||||
let c = check_site_rules(&rules, &footprint_parts(p), r.max_height.unwrap_or(f64::NAN), max_top.unwrap_or(f64::NAN))?;
|
||||
let facade = facade_terrain(p);
|
||||
let terrain_min = facade.iter().filter_map(|f| f.natural).reduce(f64::min);
|
||||
let height_above_terrain = max_top.zip(terrain_min).map(|(t, g)| t - g);
|
||||
// Mit Gelände zählt die Höhe über dem massgebenden Terrain, sonst über ±0.00.
|
||||
let top_for_check = height_above_terrain.or(max_top);
|
||||
let c = check_site_rules(&rules, &footprint_parts(p), r.max_height.unwrap_or(f64::NAN), top_for_check.unwrap_or(f64::NAN))?;
|
||||
Some(SiteCheckOut {
|
||||
parcel_area: c.parcel_area,
|
||||
allowed: area_out(&c.allowed),
|
||||
@@ -360,5 +402,8 @@ pub fn check_project(p: &Project) -> Option<SiteCheckOut> {
|
||||
violation_area: c.violation_area,
|
||||
max_top,
|
||||
height_exceeded: c.height_exceeded,
|
||||
facade_terrain: facade,
|
||||
terrain_min,
|
||||
height_above_terrain,
|
||||
})
|
||||
}
|
||||
@@ -265,18 +265,31 @@ pub fn collect_drawings(p: &Project, level: &str, codes: &HashSet<String>) -> Sn
|
||||
let mut segs: Vec<Seg> = Vec::new();
|
||||
let mut circles = Vec::new();
|
||||
let mut ellipses = Vec::new();
|
||||
let mut anchors = Vec::new();
|
||||
for d in &p.drawings2d {
|
||||
if d.level_id != level || !codes.contains(&d.category_code) {
|
||||
if !crate::grid::visible_on(d, level) || !codes.contains(&d.category_code) {
|
||||
continue;
|
||||
}
|
||||
match &d.geom {
|
||||
// Achsraster ([112]): Achsen als Strecken/Bögen, Achsschnittpunkte als Endpunkte.
|
||||
g @ Drawing2DGeom::Grid { .. } => {
|
||||
if let Some(spec) = crate::grid::Spec::of(g) {
|
||||
for ax in spec.axes() {
|
||||
match ax.shape {
|
||||
crate::grid::Shape::Line { a, b } => segs.push([a.0, a.1, b.0, b.1]),
|
||||
crate::grid::Shape::Arc { c, r, a0, a1 } => circles.push(Circle { cx: c.0, cy: c.1, r, arc: (a1 - a0 < std::f64::consts::TAU - 1e-9).then_some((a0, a1)) }),
|
||||
}
|
||||
}
|
||||
anchors.extend(spec.crossings());
|
||||
}
|
||||
}
|
||||
Drawing2DGeom::Circle { center, r } => circles.push(Circle { cx: center.x, cy: center.y, r: *r, arc: None }),
|
||||
Drawing2DGeom::Arc { center, r, a0, a1 } => circles.push(Circle { cx: center.x, cy: center.y, r: *r, arc: Some((*a0, *a1)) }),
|
||||
Drawing2DGeom::Ellipse { center, .. } => ellipses.push((center.x, center.y)),
|
||||
g => drawing_segs(g, &mut segs),
|
||||
}
|
||||
}
|
||||
SnapPart { segs: SnapSet::new(segs), circles, anchors: Vec::new(), ellipses }
|
||||
SnapPart { segs: SnapSet::new(segs), circles, anchors, ellipses }
|
||||
}
|
||||
|
||||
/// Die Kandidaten eines Geschosses: Modell, Zeichnungen, Nahmodus.
|
||||
@@ -656,6 +669,29 @@ mod tests {
|
||||
assert!(o.dwell.is_none() && o.a.is_none() && o.b.is_none());
|
||||
}
|
||||
|
||||
/// [112] Achsraster: Achsen als Strecken, Ringe als Kreise, Achsschnittpunkte als Endpunkte; in allen Geschossen.
|
||||
#[test]
|
||||
fn achsraster_fang() {
|
||||
let mut v = base();
|
||||
v["drawings2d"] = json!([{"id": "G", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 1, "y": 2}, "angle": 0,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 4}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 3}], "extend": 1}}]);
|
||||
let p: Project = serde_json::from_value(v).unwrap();
|
||||
let codes: HashSet<String> = ["20".to_string()].into_iter().collect();
|
||||
for level in ["eg", "og"] {
|
||||
let part = collect_drawings(&p, level, &codes);
|
||||
assert_eq!(part.anchors.len(), 4, "{level}");
|
||||
assert!(part.anchors.contains(&(5.0, 5.0)));
|
||||
}
|
||||
let mut v = base();
|
||||
v["drawings2d"] = json!([{"id": "G", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0, "radial": true,
|
||||
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 90}], "b": [{"label": "A", "pos": 3}], "extend": 1}}]);
|
||||
let p: Project = serde_json::from_value(v).unwrap();
|
||||
let part = collect_drawings(&p, "eg", &codes);
|
||||
assert_eq!(part.circles.len(), 1);
|
||||
assert_eq!(part.circles[0].r, 3.0);
|
||||
assert_eq!(part.anchors.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gleiche_nummer_solange_nichts_relevantes_aendert_teile_einzeln_neu() {
|
||||
let mut v = base();
|
||||
|
||||
+266
-10
@@ -3,9 +3,10 @@
|
||||
//! (`railings`). Die Treppengeometrie selbst kommt aus `kernel2d` (`stair_geometry`); TS sammelt aus
|
||||
//! dem `Project` nur Parameter, Höhen und Tragart und färbt die Ergebnisse ein.
|
||||
//!
|
||||
//! Eingabe (je Treppe 23 Zahlen, davor die Anzahl): die 16 Treppen-Parameter (s. [`crate::stair`]),
|
||||
//! Eingabe (je Treppe 24 Zahlen, davor die Anzahl): die 16 Treppen-Parameter (s. [`crate::stair`]),
|
||||
//! `zUnten, zOben, tragart (0 massiv, 1 beton, 2 offen: Wange/aufgesattelt/Spindel),
|
||||
//! trittdicke, nase, geschlosseneSetzstufen (0/1), gelaender (0 keine, 1 links, 2 rechts, 3 beide)`.
|
||||
//! trittdicke, nase, geschlosseneSetzstufen (0/1), gelaender (0 keine, 1 links, 2 rechts, 3 beide),
|
||||
//! saeulenRadius (0 keine; nur Wendel)`.
|
||||
//!
|
||||
//! Ausgabe Slabs: `[n, (treppe, monolith 0/1, zUnten, zOben, nPkt, x, y …)…]`; Ausgabe Meshes
|
||||
//! (Laufplatte, Geländer): `[n, (treppe, nPos, nIdx, positionen…, indizes…)…]`. `treppe` ist der
|
||||
@@ -41,12 +42,16 @@ struct StairIn {
|
||||
nosing: f64,
|
||||
closed_risers: bool,
|
||||
railing: u8,
|
||||
column_radius: f64,
|
||||
}
|
||||
|
||||
impl StairIn {
|
||||
fn straight(&self) -> bool {
|
||||
self.params.shape == "straight"
|
||||
}
|
||||
fn spiral(&self) -> bool {
|
||||
self.params.shape == "spiral"
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(buf: &[f64]) -> Option<Vec<Option<StairIn>>> {
|
||||
@@ -58,8 +63,8 @@ fn decode(buf: &[f64]) -> Option<Vec<Option<StairIn>>> {
|
||||
for v in p.iter_mut() {
|
||||
*v = r.num()?;
|
||||
}
|
||||
let (z_bottom, z_top, structure, tread_thickness, nosing, closed, railing) =
|
||||
(r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
|
||||
let (z_bottom, z_top, structure, tread_thickness, nosing, closed, railing, column) =
|
||||
(r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
|
||||
// Eine unbrauchbare Treppe fällt einzeln weg (Index bleibt erhalten).
|
||||
let valid = [z_bottom, z_top, tread_thickness, nosing].iter().all(|v| v.is_finite());
|
||||
out.push(match (valid, decode_params(&p)) {
|
||||
@@ -72,6 +77,7 @@ fn decode(buf: &[f64]) -> Option<Vec<Option<StairIn>>> {
|
||||
nosing,
|
||||
closed_risers: closed != 0.0,
|
||||
railing: railing.clamp(0.0, 3.0) as u8,
|
||||
column_radius: if column.is_finite() && column > 0.0 { column.min(5.0) } else { 0.0 },
|
||||
}),
|
||||
_ => None,
|
||||
});
|
||||
@@ -237,7 +243,21 @@ fn slabs_of(s: &StairIn, idx: usize, for_section: bool, out: &mut Vec<Slab>) {
|
||||
let Some((geo, total_rise)) = geometry_of(s) else { return };
|
||||
let z_bottom = s.z_bottom;
|
||||
let structure = s.structure;
|
||||
if structure == BETON && s.straight() && !for_section {
|
||||
let mut column: Option<Slab> = None;
|
||||
if s.spiral() && s.column_radius > 0.0 {
|
||||
if let Some(c) = &s.params.center {
|
||||
let pts = (0..COLUMN_SEGMENTS)
|
||||
.map(|k| {
|
||||
let a = std::f64::consts::TAU * k as f64 / COLUMN_SEGMENTS as f64;
|
||||
[c.x + s.column_radius * a.cos(), c.y + s.column_radius * a.sin()]
|
||||
})
|
||||
.collect();
|
||||
// Säule zuletzt einfügen: siehe unten; hier nur vormerken
|
||||
column = Some(Slab { src: idx, monolith: true, z_bottom, z_top: s.z_top, pts });
|
||||
}
|
||||
}
|
||||
if structure == BETON && (s.straight() || s.spiral()) && !for_section {
|
||||
out.extend(column);
|
||||
return;
|
||||
}
|
||||
let riser = geo.riser_height;
|
||||
@@ -317,9 +337,114 @@ fn slabs_of(s: &StairIn, idx: usize, for_section: bool, out: &mut Vec<Slab>) {
|
||||
});
|
||||
}
|
||||
}
|
||||
out.extend(column);
|
||||
}
|
||||
|
||||
/// Kreisbogenstücke je Tritt in Wendelfläche und Handlauf.
|
||||
const HELIX_SEGMENTS: usize = 6;
|
||||
/// Ecken der Mittelsäule (Vieleck).
|
||||
const COLUMN_SEGMENTS: usize = 24;
|
||||
|
||||
/// Wendel-Masse: Zentrum, Winkelbereich, Radien (wie `spiral_geometry` in `kernel2d`).
|
||||
struct Helix {
|
||||
center: P,
|
||||
a0: f64,
|
||||
sweep: f64,
|
||||
r_in: f64,
|
||||
r_out: f64,
|
||||
}
|
||||
|
||||
fn helix_of(s: &StairIn) -> Option<Helix> {
|
||||
let p = &s.params;
|
||||
let half_w = 0.05_f64.max(p.width / 2.0);
|
||||
let center = p.center.unwrap_or(p.start);
|
||||
let radius = (half_w + 0.1).max(p.radius.unwrap_or(p.width));
|
||||
let a0 = (p.start.y - center.y).atan2(p.start.x - center.x);
|
||||
let sweep = p.sweep.unwrap_or(270.0).to_radians();
|
||||
if !(sweep.abs() > 1e-6) {
|
||||
return None;
|
||||
}
|
||||
Some(Helix { center: [center.x, center.y], a0, sweep, r_in: (radius - half_w).max(0.02), r_out: radius + half_w })
|
||||
}
|
||||
|
||||
impl Helix {
|
||||
fn at(&self, r: f64, ang: f64) -> P {
|
||||
[self.center[0] + r * ang.cos(), self.center[1] + r * ang.sin()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Wendelfläche einer Ortbetontreppe: je Tritt ein geschlossener Block, dessen Untersicht eine echte
|
||||
/// Schraubenfläche ist (z linear im Winkel, radiale Erzeugende); Oberseite = ebener Tritt.
|
||||
fn spiral_mesh(s: &StairIn, idx: usize, out: &mut Vec<Mesh>) {
|
||||
let Some((geo, total_rise)) = geometry_of(s) else { return };
|
||||
let Some(h) = helix_of(s) else { return };
|
||||
let n = geo.treads.len();
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let waist = concrete_waist(geo.riser_height);
|
||||
let z_bottom = s.z_bottom;
|
||||
let soffit = |frac: f64| z_bottom.max(z_bottom + frac * total_rise - waist);
|
||||
let d_a = h.sweep / n as f64;
|
||||
let mut positions: Vec<f64> = Vec::new();
|
||||
let mut indices: Vec<u32> = Vec::new();
|
||||
for (i, tr) in geo.treads.iter().enumerate() {
|
||||
let top = z_bottom + tr.top_rise;
|
||||
// Ringe entlang des Tritts: (innen unten, aussen unten, Winkel)
|
||||
let m = HELIX_SEGMENTS;
|
||||
let base = (positions.len() / 3) as u32;
|
||||
for j in 0..=m {
|
||||
let f = j as f64 / m as f64;
|
||||
let ang = h.a0 + (i as f64 + f) * d_a;
|
||||
let zb = soffit((i as f64 + f) / n as f64);
|
||||
for (r, z) in [(h.r_in, zb), (h.r_out, zb), (h.r_in, top), (h.r_out, top)] {
|
||||
let q = h.at(r, ang);
|
||||
positions.extend([q[0], q[1], z]);
|
||||
}
|
||||
}
|
||||
// Eckindizes je Ring j: 0 = innen unten, 1 = aussen unten, 2 = innen oben, 3 = aussen oben
|
||||
let v = |j: usize, k: u32| base + 4 * j as u32 + k;
|
||||
let mut quad = |a: u32, b: u32, c: u32, d: u32| indices.extend([a, b, c, a, c, d]);
|
||||
for j in 0..m {
|
||||
quad(v(j, 0), v(j, 1), v(j + 1, 1), v(j + 1, 0)); // Untersicht (Wendelfläche)
|
||||
quad(v(j, 2), v(j + 1, 2), v(j + 1, 3), v(j, 3)); // Trittfläche
|
||||
quad(v(j, 0), v(j + 1, 0), v(j + 1, 2), v(j, 2)); // innere Wange
|
||||
quad(v(j, 1), v(j, 3), v(j + 1, 3), v(j + 1, 1)); // äussere Wange
|
||||
}
|
||||
quad(v(0, 0), v(0, 2), v(0, 3), v(0, 1)); // Setzstufe (Anfang)
|
||||
quad(v(m, 0), v(m, 1), v(m, 3), v(m, 2)); // Ende
|
||||
}
|
||||
if indices.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Drehsinn legt die Orientierung fest: bei negativem Volumen alle Dreiecke wenden.
|
||||
let mut mesh = Mesh { src: idx, positions, indices };
|
||||
if signed_volume(&mesh) < 0.0 {
|
||||
for t in mesh.indices.chunks_mut(3) {
|
||||
t.swap(1, 2);
|
||||
}
|
||||
}
|
||||
out.push(mesh);
|
||||
}
|
||||
|
||||
fn signed_volume(m: &Mesh) -> f64 {
|
||||
let p = |i: u32| {
|
||||
let k = 3 * i as usize;
|
||||
[m.positions[k], m.positions[k + 1], m.positions[k + 2]]
|
||||
};
|
||||
m.indices
|
||||
.chunks(3)
|
||||
.map(|t| {
|
||||
let (a, b, c) = (p(t[0]), p(t[1]), p(t[2]));
|
||||
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn meshes_of(s: &StairIn, idx: usize, out: &mut Vec<Mesh>) {
|
||||
if s.structure == BETON && s.spiral() {
|
||||
return spiral_mesh(s, idx, out);
|
||||
}
|
||||
if s.structure != BETON || !s.straight() || s.params.run_length <= EPS {
|
||||
return;
|
||||
}
|
||||
@@ -414,8 +539,63 @@ fn strut_box(a: V3, b: V3, half: f64) -> Option<(Vec<f64>, Vec<u32>)> {
|
||||
Some((positions, indices))
|
||||
}
|
||||
|
||||
/// Handlauf einer Wendeltreppe als Schraubensweep (Quader-Stücke auf der Schraubenlinie) samt
|
||||
/// Pfosten auf den Trittmitten, in einem Netz je Treppe.
|
||||
fn spiral_railing(s: &StairIn, idx: usize, out: &mut Vec<Mesh>) {
|
||||
let Some((geo, total_rise)) = geometry_of(s) else { return };
|
||||
let Some(h) = helix_of(s) else { return };
|
||||
let n = geo.treads.len();
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
// Laufrichtung = Drehsinn: links der Laufrichtung liegt bei CCW der Innenrand.
|
||||
let ccw = h.sweep > 0.0;
|
||||
let sides: &[bool] = match s.railing {
|
||||
3 => &[true, false],
|
||||
1 => &[true],
|
||||
_ => &[false],
|
||||
};
|
||||
let half = RAIL_THICK / 2.0;
|
||||
let mut positions: Vec<f64> = Vec::new();
|
||||
let mut indices: Vec<u32> = Vec::new();
|
||||
let mut push = |m: Option<(Vec<f64>, Vec<u32>)>| {
|
||||
if let Some((p, i)) = m {
|
||||
let base = (positions.len() / 3) as u32;
|
||||
positions.extend(p);
|
||||
indices.extend(i.into_iter().map(|k| k + base));
|
||||
}
|
||||
};
|
||||
let rail_z = |frac: f64| s.z_bottom + frac * total_rise + RAIL_HEIGHT;
|
||||
for &left in sides {
|
||||
let r = if left == ccw { h.r_in } else { h.r_out };
|
||||
let total_seg = n * HELIX_SEGMENTS;
|
||||
let pt_at = |k: usize| {
|
||||
let f = k as f64 / total_seg as f64;
|
||||
let q = h.at(r, h.a0 + f * h.sweep);
|
||||
[q[0], q[1], rail_z(f)]
|
||||
};
|
||||
for k in 0..total_seg {
|
||||
push(strut_box(pt_at(k), pt_at(k + 1), half));
|
||||
}
|
||||
for (i, tr) in geo.treads.iter().enumerate() {
|
||||
let f = (i as f64 + 0.5) / n as f64;
|
||||
let q = h.at(r, h.a0 + f * h.sweep);
|
||||
push(strut_box([q[0], q[1], s.z_bottom + tr.top_rise], [q[0], q[1], rail_z(f)], half));
|
||||
}
|
||||
}
|
||||
if !indices.is_empty() {
|
||||
out.push(Mesh { src: idx, positions, indices });
|
||||
}
|
||||
}
|
||||
|
||||
fn railings_of(s: &StairIn, idx: usize, out: &mut Vec<Mesh>) {
|
||||
if !s.straight() || s.railing == 0 {
|
||||
if s.railing == 0 {
|
||||
return;
|
||||
}
|
||||
if s.spiral() {
|
||||
return spiral_railing(s, idx, out);
|
||||
}
|
||||
if !s.straight() {
|
||||
return;
|
||||
}
|
||||
let Some((geo, _)) = geometry_of(s) else { return };
|
||||
@@ -502,7 +682,7 @@ mod tests {
|
||||
vec![
|
||||
1.0, // eine Treppe
|
||||
0.0, 0.0, 0.0, 1.0, 0.0, 3.0, nan, nan, nan, nan, nan, nan, 1.0, 10.0, nan, 0.0, // Parameter
|
||||
0.0, 2.8, structure, 0.04, nosing, closed, railing,
|
||||
0.0, 2.8, structure, 0.04, nosing, closed, railing, 0.0,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -573,7 +753,7 @@ mod tests {
|
||||
let nan = f64::NAN;
|
||||
let l = vec![
|
||||
1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 2.0, 1.5, 1.0, nan, nan, nan, nan, 1.0, 10.0, nan, 0.0, // L
|
||||
0.0, 2.8, 0.0, 0.04, 0.0, 0.0, 0.0,
|
||||
0.0, 2.8, 0.0, 0.04, 0.0, 0.0, 0.0, 0.0,
|
||||
];
|
||||
let s = slabs(&l, false);
|
||||
assert!(s.len() >= 10);
|
||||
@@ -581,9 +761,85 @@ mod tests {
|
||||
assert!((last.z_top - 1.4).abs() < 1e-9 && last.z_bottom == 0.0);
|
||||
let w = vec![
|
||||
1.0, 2.0, 1.0, 0.0, 1.0, 0.0, 1.0, nan, nan, 0.0, 0.0, 1.5, 270.0, 1.0, 12.0, nan, 0.0, // Wendel
|
||||
0.0, 2.8, 2.0, 0.04, 0.0, 0.0, 3.0,
|
||||
0.0, 2.8, 2.0, 0.04, 0.0, 0.0, 3.0, 0.0,
|
||||
];
|
||||
assert!(!slabs(&w, false).is_empty());
|
||||
assert!(railings(&w).is_empty()); // Geländer nur für gerade Läufe
|
||||
assert!(!railings(&w).is_empty()); // Wendelgeländer = Schraubensweep
|
||||
}
|
||||
|
||||
fn spiral(structure: f64, railing: f64, column: f64) -> Vec<f64> {
|
||||
let nan = f64::NAN;
|
||||
vec![
|
||||
1.0, 2.0, 1.0, 0.0, 1.0, 0.0, 1.0, nan, nan, 0.0, 0.0, 1.5, 270.0, 1.0, 12.0, nan, 0.0, // Wendel
|
||||
0.0, 2.8, structure, 0.04, 0.0, 0.0, railing, column,
|
||||
]
|
||||
}
|
||||
|
||||
/// Volumen eines geschlossenen Netzes (Divergenzsatz); positiv = Normalen nach aussen.
|
||||
fn volume(m: &Mesh) -> f64 {
|
||||
let p = |i: u32| [m.positions[3 * i as usize], m.positions[3 * i as usize + 1], m.positions[3 * i as usize + 2]];
|
||||
m.indices
|
||||
.chunks(3)
|
||||
.map(|t| {
|
||||
let (a, b, c) = (p(t[0]), p(t[1]), p(t[2]));
|
||||
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wendel_beton_hat_schraubenfläche() {
|
||||
let ms = slab_meshes(&spiral(1.0, 0.0, 0.0));
|
||||
assert_eq!(ms.len(), 1);
|
||||
let m = &ms[0];
|
||||
// Ringsektor 270° (r 1…2) = 7.07 m², mittlere Dicke ≈ Laufplatte + halbe Steigung
|
||||
let v = volume(m);
|
||||
assert!(v > 1.5 && v < 3.2, "Volumen {v}");
|
||||
// Untersicht folgt der Schraube: an jedem Punkt z_unten = z0 + Winkelanteil·Steighöhe − Dicke (oder 0)
|
||||
let a0 = 0.0_f64; // Start (1,0) um Zentrum (0,0)
|
||||
let waist = concrete_waist(2.8 / 12.0);
|
||||
let mut checked = 0;
|
||||
for c in m.positions.chunks(3) {
|
||||
let ang = c[1].atan2(c[0]).rem_euclid(std::f64::consts::TAU) - a0;
|
||||
let f = ang / (270.0_f64).to_radians();
|
||||
let on_helix = (0.0..=1.0).contains(&f) && (c[2] - (f * 2.8 - waist).max(0.0)).abs() < 1e-6;
|
||||
if on_helix {
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(checked > 12 * 2, "zu wenige Punkte auf der Wendelfläche: {checked}");
|
||||
// Im Grundriss/3D werden die Tritt-Prismen für Beton nicht doppelt gezeichnet, im Schnitt schon
|
||||
assert!(slabs(&spiral(1.0, 0.0, 0.0), false).is_empty());
|
||||
assert!(!slabs(&spiral(1.0, 0.0, 0.0), true).is_empty());
|
||||
// Drehsinn negativ: Netz bleibt geschlossen/nach aussen orientiert
|
||||
let mut cw = spiral(1.0, 0.0, 0.0);
|
||||
cw[12] = -270.0;
|
||||
assert!(volume(&slab_meshes(&cw)[0]) > 1.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wendel_handlauf_ist_schraubensweep() {
|
||||
let rs = railings(&spiral(1.0, 1.0, 0.0));
|
||||
assert!(!rs.is_empty());
|
||||
let zs: Vec<f64> = rs.iter().flat_map(|m| m.positions.chunks(3).map(|c| c[2])).collect();
|
||||
let (lo, hi) = (zs.iter().cloned().fold(f64::INFINITY, f64::min), zs.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
|
||||
assert!(lo < 0.95 && hi > 2.8 + 0.85, "{lo} {hi}");
|
||||
// Handlauf liegt auf einem Kreis (Innenkante r = 1.0 bei Linksgeländer, CCW) — alle Punkte r ≈ 1 ± Querschnitt
|
||||
let big = rs.iter().max_by_key(|m| m.indices.len()).unwrap();
|
||||
let r: Vec<f64> = big.positions.chunks(3).map(|c| c[0].hypot(c[1])).collect();
|
||||
assert!(r.iter().all(|r| (r - 1.0).abs() < 0.05), "Radius streut");
|
||||
assert!(big.positions.chunks(3).any(|c| c[2] > 2.0) && big.positions.chunks(3).any(|c| c[2] < 1.2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wendel_mittelsaeule_als_block() {
|
||||
let none = slabs(&spiral(0.0, 0.0, 0.0), false).len();
|
||||
let with = slabs(&spiral(0.0, 0.0, 0.12), false);
|
||||
assert_eq!(with.len(), none + 1);
|
||||
let col = with.last().unwrap();
|
||||
assert!(col.z_bottom == 0.0 && (col.z_top - 2.8).abs() < 1e-9 && col.pts.len() >= 12);
|
||||
assert!(col.pts.iter().all(|p| (p[0].hypot(p[1]) - 0.12).abs() < 1e-9));
|
||||
// auch bei Beton (Grundriss ohne Tritt-Prismen) und nur für Wendel
|
||||
assert_eq!(slabs(&spiral(1.0, 0.0, 0.12), false).len(), 1);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+609
-121
@@ -9,13 +9,13 @@
|
||||
//! als Löcher) und Schnitt-Eingabe (Pfeiler/Brüstung/Sturz-Segmente ohne Löcher).
|
||||
|
||||
use crate::joins::{js_hypot, reference_offset, Line, Reference, WallCuts};
|
||||
use crate::roof::roof_underside_at;
|
||||
use kernel2d::{add, dot, left_normal, line_intersect, point_in_outline, scale, sub, Vec2};
|
||||
|
||||
/// Toleranz der Wand-Ableitung (`EPS` in `toWalls3d/shared.ts`).
|
||||
pub const EPS: f64 = 1e-4;
|
||||
/// Schrittweite (Meter) der Dach-Unterkanten-Abtastung.
|
||||
const ROOF_CLIP_STEP: f64 = 0.15;
|
||||
/// Schrittweite (Meter) der Dach-Unterkanten-Abtastung (Wechsel der Dachfläche suchen; die Grenzen
|
||||
/// selbst sind exakt).
|
||||
const ROOF_SAMPLE: f64 = 0.05;
|
||||
|
||||
/// Ein Schicht-Band: Dicke und Verschneidungs-Rang (`None`: keine Decken-Subtraktion).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -65,13 +65,96 @@ pub struct CeilingIn {
|
||||
pub layers: Option<Vec<(f64, Option<f64>)>>,
|
||||
}
|
||||
|
||||
/// Ein Dach desselben Geschosses: Traufhöhe, Summe der Schichtdicken, Traufe-Umriss, Flächen.
|
||||
/// Ein Dach desselben Geschosses: Traufhöhe, Summe der Schichtdicken, Traufe-Umriss, Flächen und
|
||||
/// die Unterkanten-Facetten ([G2]), an denen Wände enden.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RoofIn {
|
||||
pub eaves_z: f64,
|
||||
pub total_thickness: f64,
|
||||
pub eaves: Vec<[f64; 2]>,
|
||||
pub planes: Vec<Vec<[f64; 3]>>,
|
||||
pub facets: Vec<RoofFacet>,
|
||||
}
|
||||
|
||||
impl RoofIn {
|
||||
/// Facetten aus den Dachflächen (Schichten senkrecht zur Fläche, Summe `total`).
|
||||
pub fn new(eaves_z: f64, total: f64, eaves: Vec<[f64; 2]>, planes: Vec<Vec<[f64; 3]>>) -> Self {
|
||||
let facets = plane_facets(&planes, total);
|
||||
RoofIn { eaves_z, total_thickness: total, eaves, planes, facets }
|
||||
}
|
||||
}
|
||||
|
||||
/// Ebene Unterkante eines Dachteils über dem Grundriss-Bereich `ring`: `z = c + gx·x + gy·y`. Wo sich
|
||||
/// Facetten überdecken (Kehlen verschnittener Dächer, Gaube über dem Hauptdach), gilt die obere Hülle.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RoofFacet {
|
||||
pub ring: Vec<[f64; 2]>,
|
||||
pub plane: [f64; 3],
|
||||
bounds: [f64; 4],
|
||||
}
|
||||
|
||||
impl RoofFacet {
|
||||
/// `None` bei weniger als drei Ecken oder nicht endlichen Werten.
|
||||
pub fn new(ring: Vec<[f64; 2]>, plane: [f64; 3]) -> Option<Self> {
|
||||
if ring.len() < 3 || !plane.iter().all(|v| v.is_finite()) || !ring.iter().all(|q| q[0].is_finite() && q[1].is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let b = outline_bounds(ring.iter().map(|q| (q[0], q[1])));
|
||||
Some(RoofFacet { ring, plane, bounds: [b.min_x, b.min_y, b.max_x, b.max_y] })
|
||||
}
|
||||
pub(crate) fn z(&self, x: f64, y: f64) -> f64 {
|
||||
self.plane[0] + self.plane[1] * x + self.plane[2] * y
|
||||
}
|
||||
pub(crate) fn contains(&self, x: f64, y: f64) -> bool {
|
||||
let b = self.bounds;
|
||||
if x < b[0] || x > b[2] || y < b[1] || y > b[3] {
|
||||
return false;
|
||||
}
|
||||
let mut inside = false;
|
||||
let n = self.ring.len();
|
||||
let mut j = n - 1;
|
||||
for i in 0..n {
|
||||
let (a, c) = (self.ring[i], self.ring[j]);
|
||||
if (a[1] > y) != (c[1] > y) && x < (c[0] - a[0]) * (y - a[1]) / (c[1] - a[1]) + a[0] {
|
||||
inside = !inside;
|
||||
}
|
||||
j = i;
|
||||
}
|
||||
inside
|
||||
}
|
||||
/// Höchster Wert über den Ecken.
|
||||
fn z_max(&self) -> f64 {
|
||||
self.ring.iter().map(|q| self.z(q[0], q[1])).fold(f64::NEG_INFINITY, f64::max)
|
||||
}
|
||||
}
|
||||
|
||||
/// Unterkanten-Facetten der Dachflächen: Oberfläche um `total` senkrecht zur Fläche gesenkt (wie die
|
||||
/// 3D-Schichten); senkrechte Flächen entfallen.
|
||||
pub fn plane_facets(planes: &[Vec<[f64; 3]>], total: f64) -> Vec<RoofFacet> {
|
||||
let t = if total.is_finite() { total.max(0.0) } else { 0.0 };
|
||||
let mut out = Vec::new();
|
||||
for pts in planes {
|
||||
if pts.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let (mut a, mut b, mut c) = (0.0, 0.0, 0.0);
|
||||
for i in 0..pts.len() {
|
||||
let (p, q) = (pts[i], pts[(i + 1) % pts.len()]);
|
||||
a += (p[1] - q[1]) * (p[2] + q[2]);
|
||||
b += (p[2] - q[2]) * (p[0] + q[0]);
|
||||
c += (p[0] - q[0]) * (p[1] + q[1]);
|
||||
}
|
||||
let len = (a * a + b * b + c * c).sqrt();
|
||||
if !(len > 1e-12) || c.abs() < 1e-6 * len {
|
||||
continue; // senkrecht oder entartet
|
||||
}
|
||||
let (gx, gy) = (-a / c, -b / c);
|
||||
let c0 = pts[0][2] - gx * pts[0][0] - gy * pts[0][1] - t * len / c.abs();
|
||||
if let Some(f) = RoofFacet::new(pts.iter().map(|q| [q[0], q[1]]).collect(), [c0, gx, gy]) {
|
||||
out.push(f);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Terminierung am Deckenanschluss (`Wall.sliceTermination`).
|
||||
@@ -102,6 +185,10 @@ pub struct WallIn {
|
||||
pub cuts: WallCuts,
|
||||
/// Schichteinzug ([106]); leer = alle Schichten bündig.
|
||||
pub reveals: Vec<RevealIn>,
|
||||
/// An Dach anschliessen ([G2], `Wall.roofAttach`): `None` = automatisch (Wand endet an der
|
||||
/// Dach-Unterkante, wo ihre Krone darüber liegt), `Some(true)` = zusätzlich bis unter das Dach
|
||||
/// verlängert, `Some(false)` = Dächer schneiden die Wand nicht.
|
||||
pub roof_attach: Option<bool>,
|
||||
}
|
||||
|
||||
/// Decken und Dächer eines Geschosses — einmal je Geschoss gelesen, für alle seine Wände; die
|
||||
@@ -125,7 +212,7 @@ impl FloorContext {
|
||||
roofs: roofs
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let b = outline_bounds(r.eaves.iter().map(|p| (p[0], p[1])));
|
||||
let b = outline_bounds(r.eaves.iter().map(|p| (p[0], p[1])).chain(r.facets.iter().flat_map(|f| f.ring.iter().map(|q| (q[0], q[1])))));
|
||||
(r, b)
|
||||
})
|
||||
.collect(),
|
||||
@@ -149,8 +236,15 @@ pub struct Piece {
|
||||
/// beginnt/endet dort, wo die Band-Mittellinie sie trifft. `None`: rechtwinklig.
|
||||
pub start_cut: Option<Line>,
|
||||
pub end_cut: Option<Line>,
|
||||
/// Eigene Dicke (Schichteinzug-Stück, [106]); `None` = Banddicke.
|
||||
/// Eigene Dicke (Schichteinzug-Stück, [106]; seitlich geteiltes Band unter einem Dach, [G2]);
|
||||
/// `None` = Banddicke.
|
||||
pub thickness: Option<f64>,
|
||||
/// Ebene Oberkante unter einer Dachfläche ([G2]): `z = c + gx·x + gy·y` (Welt); `None` = waagrecht
|
||||
/// auf `z_top`. `z_top` ist dann der höchste Eckwert, `top_drop` die Absenkung auf der Mittellinie.
|
||||
pub top_plane: Option<[f64; 3]>,
|
||||
/// Anfang/Ende liegt an einer inneren Stossfuge (Teilung an Dachkanten oder Öffnungen unter einem
|
||||
/// Dach): dort keine sichtbare Stirnfläche (Ansicht).
|
||||
pub joint: [bool; 2],
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -475,94 +569,337 @@ impl Emitter<'_> {
|
||||
start_cut: None,
|
||||
end_cut: None,
|
||||
thickness: None,
|
||||
top_plane: None,
|
||||
joint: [false; 2],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Oberkante des Bands unter den Dächern: Dach-Unterkante entlang der Achse abtasten, zu geraden
|
||||
/// Stücken (Toleranz 2 mm) zusammenfassen, Knicke exakt als Schnitt der Nachbargeraden; je Stück
|
||||
/// ein Körper mit schräger Oberkante. Ohne Dach darüber: ein Körper, unverändert.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn clip_to_roofs(w: &WallIn, ctx: &FloorContext, u: Vec2, n: Vec2, offset: f64, a: f64, bb: f64, zb: f64, zt: f64, emit: &mut dyn FnMut(f64, f64, f64, f64, f64)) {
|
||||
if zt - zb <= EPS || bb - a <= EPS {
|
||||
return;
|
||||
}
|
||||
let wb = wall_bounds(w, offset.abs() + 0.01);
|
||||
let roofs: Vec<&RoofIn> = ctx.roofs.iter().filter(|(r, rb)| r.eaves_z + 50.0 >= zb && bounds_overlap(wb, *rb)).map(|(r, _)| r).collect();
|
||||
if roofs.is_empty() {
|
||||
emit(a, bb, zb, zt, zt);
|
||||
return;
|
||||
}
|
||||
let span = bb - a;
|
||||
let count = 1usize.max((span / ROOF_CLIP_STEP).ceil() as usize);
|
||||
let top_at = |t: f64| {
|
||||
let tt = (bb - 1e-3).min((a + 1e-3).max(t));
|
||||
let p = add(add(w.start, scale(u, tt)), scale(n, offset));
|
||||
let mut clip = zt;
|
||||
for r in &roofs {
|
||||
if let Some(under) = roof_underside_at(&r.planes, r.total_thickness, p.x, p.y) {
|
||||
if under < clip {
|
||||
clip = under;
|
||||
// ── Wand an Dach ([G2]) ───────────────────────────────────────────────────────
|
||||
//
|
||||
// Die Oberkante eines Bands ist `clamp(U, zb, zt)` mit U = obere Hülle der Dach-Unterkanten-Facetten
|
||||
// über dem Punkt (stückweise eben). Das Band wird an den Grenzen der Bereiche geteilt — längs der
|
||||
// Achse mit der exakten Grenzlinie als Schnittlinie (First, Grat, Kehle, Höhenlinie U = zt bzw. zb),
|
||||
// quer über die Dicke (seitlich), wo eine Grenze längs durch das Band läuft (Traufwand, deren Krone die
|
||||
// Dachfläche schneidet). Jedes Stück bekommt eine ebene Oberkante: exakt je Schicht, an jeder Ecke.
|
||||
|
||||
/// Bereich der Oberkante an einem Punkt.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Fac {
|
||||
/// Kein Dach darüber: Wandkrone.
|
||||
Free,
|
||||
/// Unter dem Dach, Unterkante über der (verlängerten) Krone: waagrecht auf der Krone.
|
||||
Cap,
|
||||
/// Unterkante unter dem Fuss: kein Körper.
|
||||
Floor,
|
||||
/// Unterkante der Facette `k`.
|
||||
Roof(usize),
|
||||
}
|
||||
|
||||
struct Tops<'a> {
|
||||
facets: Vec<&'a RoofFacet>,
|
||||
zb: f64,
|
||||
zt_free: f64,
|
||||
zt_cap: f64,
|
||||
}
|
||||
|
||||
impl Tops<'_> {
|
||||
fn at(&self, p: Vec2) -> Fac {
|
||||
let mut best: Option<(f64, usize)> = None;
|
||||
for (k, f) in self.facets.iter().enumerate() {
|
||||
if f.contains(p.x, p.y) {
|
||||
let z = f.z(p.x, p.y);
|
||||
if best.is_none_or(|b| z > b.0) {
|
||||
best = Some((z, k));
|
||||
}
|
||||
}
|
||||
}
|
||||
zb.max(clip)
|
||||
};
|
||||
let mut ts = Vec::with_capacity(count + 1);
|
||||
let mut tops = Vec::with_capacity(count + 1);
|
||||
for i in 0..=count {
|
||||
ts.push(a + (span * i as f64) / count as f64);
|
||||
tops.push(top_at(ts[i]));
|
||||
}
|
||||
const TOL: f64 = 0.002;
|
||||
let mut runs: Vec<(usize, usize)> = Vec::new();
|
||||
let mut i0 = 0;
|
||||
while i0 < count {
|
||||
let mut i1 = i0 + 1;
|
||||
while i1 < count {
|
||||
let k = i1 + 1;
|
||||
let slope = (tops[k] - tops[i0]) / (ts[k] - ts[i0]);
|
||||
let ok = (i0 + 1..=k).all(|m| (tops[i0] + slope * (ts[m] - ts[i0]) - tops[m]).abs() <= TOL);
|
||||
if !ok {
|
||||
break;
|
||||
match best {
|
||||
None => Fac::Free,
|
||||
Some((z, _)) if z >= self.zt_cap - 1e-9 => {
|
||||
if self.zt_cap == self.zt_free {
|
||||
Fac::Free
|
||||
} else {
|
||||
Fac::Cap
|
||||
}
|
||||
}
|
||||
i1 = k;
|
||||
Some((z, _)) if z <= self.zb + 1e-9 => Fac::Floor,
|
||||
Some((_, k)) => Fac::Roof(k),
|
||||
}
|
||||
runs.push((i0, i1));
|
||||
i0 = i1;
|
||||
}
|
||||
let line = |r: (usize, usize)| {
|
||||
let m = (tops[r.1] - tops[r.0]) / (ts[r.1] - ts[r.0]);
|
||||
(m, tops[r.0] - m * ts[r.0])
|
||||
fn coef(&self, f: Fac) -> [f64; 3] {
|
||||
match f {
|
||||
Fac::Free => [self.zt_free, 0.0, 0.0],
|
||||
Fac::Cap => [self.zt_cap, 0.0, 0.0],
|
||||
Fac::Floor => [self.zb, 0.0, 0.0],
|
||||
Fac::Roof(k) => self.facets[k].plane,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ein Stück der Band-Oberkante: Achsmass `[a, b]` auf seiner Mittellinie (Versatz `off`, Dicke `th`),
|
||||
/// Schnittlinien, Höhe (`top` = höchster Eckwert) und Ebene.
|
||||
#[derive(Clone, Debug)]
|
||||
struct TopPiece {
|
||||
a: f64,
|
||||
b: f64,
|
||||
cut_a: Option<Line>,
|
||||
cut_b: Option<Line>,
|
||||
off: f64,
|
||||
th: f64,
|
||||
top: f64,
|
||||
plane: Option<[f64; 3]>,
|
||||
joint: [bool; 2],
|
||||
}
|
||||
|
||||
/// Dächer, die eine Wand im Höhenbereich `[zb, zt]` betreffen; `None` = keine (unverändert).
|
||||
fn roof_tops_ctx<'a>(w: &WallIn, ctx: &'a FloorContext, zb: f64, zt: f64) -> Option<Tops<'a>> {
|
||||
if w.roof_attach == Some(false) || ctx.roofs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let wb = wall_bounds(w, w.thickness_safe.max(0.0) + 0.01);
|
||||
let facets: Vec<&RoofFacet> = ctx
|
||||
.roofs
|
||||
.iter()
|
||||
.filter(|(r, rb)| r.eaves_z + 50.0 >= zb && bounds_overlap(wb, *rb))
|
||||
.flat_map(|(r, _)| r.facets.iter())
|
||||
.filter(|f| bounds_overlap(wb, Bounds { min_x: f.bounds[0], min_y: f.bounds[1], max_x: f.bounds[2], max_y: f.bounds[3] }))
|
||||
.collect();
|
||||
if facets.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Verlängern nur, wo der Höhenbereich bis zur Wandkrone reicht (nicht unter einer Decke).
|
||||
let zt_cap = if w.roof_attach == Some(true) && (zt - w.z_top).abs() < EPS { facets.iter().map(|f| f.z_max()).fold(zt, f64::max) } else { zt };
|
||||
Some(Tops { facets, zb, zt_free: zt, zt_cap })
|
||||
}
|
||||
|
||||
/// Ecken der Grundfläche eines Bandstücks (aussen +n, innen −n) an den Schnittlinien.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn strip_corners(w: &WallIn, u: Vec2, n: Vec2, off: f64, th: f64, a: f64, b: f64, cut_a: Option<Line>, cut_b: Option<Line>) -> [Vec2; 4] {
|
||||
let base = add(w.start, scale(n, off));
|
||||
let at = |s: f64, o: f64, cut: Option<Line>| {
|
||||
let q = add(add(base, scale(u, s)), scale(n, o));
|
||||
cut.and_then(|c| line_intersect(q, u, c.point, c.dir)).filter(|r| r.x.is_finite() && r.y.is_finite()).unwrap_or(q)
|
||||
};
|
||||
let mut cuts = vec![a];
|
||||
for r in 0..runs.len().saturating_sub(1) {
|
||||
let l1 = line(runs[r]);
|
||||
let l2 = line(runs[r + 1]);
|
||||
let lo = ts[runs[r].1 - 1];
|
||||
let hi = ts[count.min(runs[r].1 + 1)];
|
||||
let mut x = ts[runs[r].1];
|
||||
if (l1.0 - l2.0).abs() > 1e-9 {
|
||||
let cx = (l2.1 - l1.1) / (l1.0 - l2.0);
|
||||
if cx >= lo && cx <= hi {
|
||||
x = cx;
|
||||
}
|
||||
}
|
||||
cuts.push(x);
|
||||
let h = th / 2.0;
|
||||
[at(a, h, cut_a), at(b, h, cut_b), at(b, -h, cut_b), at(a, -h, cut_a)]
|
||||
}
|
||||
|
||||
/// Oberkante eines Bandstreifens `[a, b]` (Mittellinie `off`, Dicke `th`) unter den Dächern `t`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn strip_tops(w: &WallIn, t: &Tops, u: Vec2, n: Vec2, off: f64, th: f64, a: f64, b: f64, cut_a: Option<Line>, cut_b: Option<Line>, joint: [bool; 2], depth: u32, out: &mut Vec<TopPiece>) {
|
||||
if !(b - a > EPS) || !(th > 0.0) {
|
||||
return;
|
||||
}
|
||||
cuts.push(bb);
|
||||
for (k, &r) in runs.iter().enumerate() {
|
||||
let (sa, sb) = (cuts[k], cuts[k + 1]);
|
||||
if sb - sa <= EPS {
|
||||
let base = add(w.start, scale(n, off));
|
||||
let pt = |s: f64| add(base, scale(u, s));
|
||||
let steps = 8usize.max(((b - a) / ROOF_SAMPLE).ceil() as usize).min(20_000);
|
||||
let ts: Vec<f64> = (0..=steps).map(|i| if i == steps { b } else { a + (b - a) * i as f64 / steps as f64 }).collect();
|
||||
let inner = |s: f64| s.clamp(a + 1e-6, b - 1e-6);
|
||||
let fac: Vec<Fac> = ts.iter().map(|&s| t.at(pt(inner(s)))).collect();
|
||||
// Läufe gleicher Bereiche und die Grenzen dazwischen (Achsmass, Schnittlinie).
|
||||
let mut runs: Vec<(Fac, f64, Option<Line>)> = vec![(fac[0], a, cut_a)];
|
||||
for i in 1..=steps {
|
||||
let last = runs.last().map_or(fac[0], |r| r.0);
|
||||
if fac[i] == last {
|
||||
continue;
|
||||
}
|
||||
let value_at = |x: f64| {
|
||||
let l = line(r);
|
||||
zt.min(zb.max(l.0 * x + l.1))
|
||||
let (fa, fb) = (fac[i - 1], fac[i]);
|
||||
// Wechselstelle auf der Mittellinie (Bisektion), dann die exakte Grenzlinie beider Ebenen.
|
||||
let (mut lo, mut hi) = (ts[i - 1], ts[i]);
|
||||
for _ in 0..50 {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if t.at(pt(inner(mid))) == fa {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
let sm = (lo + hi) / 2.0;
|
||||
let p = pt(sm);
|
||||
let (ca, cb) = (t.coef(fa), t.coef(fb));
|
||||
let d = [ca[0] - cb[0], ca[1] - cb[1], ca[2] - cb[2]];
|
||||
let g = js_hypot(d[1], d[2]);
|
||||
let mut line = None;
|
||||
if g > 1e-9 {
|
||||
let dist = (d[0] + d[1] * p.x + d[2] * p.y) / g;
|
||||
let dir = Vec2::new(-d[2] / g, d[1] / g);
|
||||
// Nur, wenn die Grenze wirklich hier liegt (sonst Sprung, z. B. Traufe) und quer genug steht.
|
||||
if dist.abs() < 0.02 && (dir.x * u.y - dir.y * u.x).abs() > 0.17 {
|
||||
line = Some(Line { point: Vec2::new(p.x - d[1] / g * dist, p.y - d[2] / g * dist), dir });
|
||||
}
|
||||
}
|
||||
let prev = runs.last().map_or(a, |r| r.1);
|
||||
let s_cut = line.and_then(|l| band_cut_distance(w, u, n, off, &l)).filter(|x| x.is_finite()).unwrap_or(sm).clamp(prev, b);
|
||||
runs.push((fb, s_cut, line));
|
||||
}
|
||||
let k_last = runs.len() - 1;
|
||||
for k in 0..runs.len() {
|
||||
let (f, s0, c0) = runs[k];
|
||||
let (s1, c1) = if k < k_last { (runs[k + 1].1, runs[k + 1].2) } else { (b, cut_b) };
|
||||
if !(s1 - s0 > EPS) {
|
||||
continue;
|
||||
}
|
||||
let jt = [if k == 0 { joint[0] } else { true }, if k == k_last { joint[1] } else { true }];
|
||||
// Seitlich: läuft eine Grenze längs durchs Band (Kanten sehen einen anderen Bereich)?
|
||||
if depth < 3 && th > 0.004 {
|
||||
let mut other = None;
|
||||
'edges: for side in [1.0, -1.0] {
|
||||
let eo = side * (th / 2.0 - 1e-4);
|
||||
let e_lo = c0.and_then(|l| band_cut_distance(w, u, n, off + eo, &l)).unwrap_or(s0);
|
||||
let e_hi = c1.and_then(|l| band_cut_distance(w, u, n, off + eo, &l)).unwrap_or(s1);
|
||||
if !(e_hi - e_lo > 4.0 * EPS) {
|
||||
continue;
|
||||
}
|
||||
let m = 4usize.max(((e_hi - e_lo) / ROOF_SAMPLE).ceil() as usize).min(20_000);
|
||||
for j in 0..m {
|
||||
let s = e_lo + (e_hi - e_lo) * (j as f64 + 0.5) / m as f64;
|
||||
let fe = t.at(add(pt(s), scale(n, eo)));
|
||||
if fe != f {
|
||||
other = Some(fe);
|
||||
break 'edges;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(fo) = other {
|
||||
let (ca, cb) = (t.coef(f), t.coef(fo));
|
||||
let d = [ca[0] - cb[0], ca[1] - cb[1], ca[2] - cb[2]];
|
||||
let mid = pt((s0 + s1) / 2.0);
|
||||
let den = d[1] * n.x + d[2] * n.y;
|
||||
if den.abs() > 1e-9 {
|
||||
let o = -(d[0] + d[1] * mid.x + d[2] * mid.y) / den;
|
||||
if o.abs() < th / 2.0 - 1e-3 {
|
||||
for (lo_o, hi_o) in [(-th / 2.0, o), (o, th / 2.0)] {
|
||||
let c = off + (lo_o + hi_o) / 2.0;
|
||||
let sa = c0.and_then(|l| band_cut_distance(w, u, n, c, &l)).unwrap_or(s0);
|
||||
let sb = c1.and_then(|l| band_cut_distance(w, u, n, c, &l)).unwrap_or(s1);
|
||||
strip_tops(w, t, u, n, c, hi_o - lo_o, sa, sb, c0, c1, jt, depth + 1, out);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let (plane, top) = match f {
|
||||
Fac::Floor => continue,
|
||||
Fac::Free => (None, t.zt_free),
|
||||
Fac::Cap => (None, t.zt_cap),
|
||||
Fac::Roof(_) => {
|
||||
let c = t.coef(f);
|
||||
let zmax = strip_corners(w, u, n, off, th, s0, s1, c0, c1).iter().map(|q| c[0] + c[1] * q.x + c[2] * q.y).fold(f64::NEG_INFINITY, f64::max);
|
||||
(Some(c), zmax.min(t.zt_cap).max(t.zb))
|
||||
}
|
||||
};
|
||||
let (z0, z1) = (value_at(sa), value_at(sb));
|
||||
if z0.max(z1) - zb > EPS {
|
||||
emit(sa, sb, zb, z0, z1);
|
||||
out.push(TopPiece { a: s0, b: s1, cut_a: c0, cut_b: c1, off, th, top, plane, joint: jt });
|
||||
}
|
||||
}
|
||||
|
||||
/// Oberkante eines Bandstücks unter den Dächern; `None`, wenn kein Dach die Wand betrifft (dann
|
||||
/// unverändert ein Körper auf der Krone).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn roof_tops(w: &WallIn, ctx: &FloorContext, u: Vec2, n: Vec2, off: f64, th: f64, a: f64, b: f64, cut_a: Option<Line>, cut_b: Option<Line>, zb: f64, zt: f64) -> Option<Vec<TopPiece>> {
|
||||
if zt - zb <= EPS || b - a <= EPS {
|
||||
return None;
|
||||
}
|
||||
let t = roof_tops_ctx(w, ctx, zb, zt)?;
|
||||
let mut out = Vec::new();
|
||||
strip_tops(w, &t, u, n, off, th, a, b, cut_a, cut_b, [false; 2], 0, &mut out);
|
||||
// Nichts geteilt, nichts geneigt: wie ohne Dach.
|
||||
if out.len() == 1 && out[0].plane.is_none() && out[0].top == zt && out[0].th == th && out[0].a == a && out[0].b == b {
|
||||
return None;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Löcher eines Bandkörpers ab `a` (Achsmass) im Höhenbereich `[zb, zt]`, mit Schichteinzug.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn band_holes(w: &WallIn, li: usize, cutouts: &[OpeningIn], innermost: bool, recess: f64, a: f64, zb: f64, zt: f64) -> Vec<[f64; 4]> {
|
||||
let reveals = &w.reveals;
|
||||
cutouts
|
||||
.iter()
|
||||
.filter(|h| h.z_top > zb + EPS && h.z_bottom < zt - EPS)
|
||||
.map(|h| {
|
||||
if let Some(s) = reveals.iter().find(|r| r.of(h)).and_then(|r| r.shifts.get(li)) {
|
||||
[h.from - a - s[0], h.to - a + s[1], h.z_bottom - s[3], h.z_top + s[2]]
|
||||
} else if innermost && h.recess_inner_layer {
|
||||
[h.from - a - recess, h.to - a + recess, h.z_bottom - recess, h.z_top + recess]
|
||||
} else {
|
||||
[h.from - a, h.to - a, h.z_bottom, h.z_top]
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ein Körper aus einem Oberkanten-Stück: Achsmass `[x0, x1]` relativ zu `tp.a`, Höhe `[zb, top]`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn push_top_piece(em: &mut Emitter, li: usize, band_th: f64, tp: &TopPiece, x0: f64, x1: f64, zb: f64, top: f64, plane: Option<[f64; 3]>, holes: Vec<[f64; 4]>) {
|
||||
let len = tp.b - tp.a;
|
||||
let first = x0 <= EPS;
|
||||
let last = x1 >= len - EPS;
|
||||
let before = em.out.len();
|
||||
em.push(li, tp.a + x0, tp.a + x1, zb, top, tp.off, holes, [0.0, 0.0]);
|
||||
let Some(pc) = em.out.get_mut(before) else { return };
|
||||
pc.start_cut = if first { tp.cut_a } else { None };
|
||||
pc.end_cut = if last { tp.cut_b } else { None };
|
||||
pc.joint = [if first { tp.joint[0] } else { true }, if last { tp.joint[1] } else { true }];
|
||||
if (tp.th - band_th).abs() > 1e-12 {
|
||||
pc.thickness = Some(tp.th);
|
||||
}
|
||||
if let Some(c) = plane {
|
||||
pc.top_plane = Some(c);
|
||||
let at = |q: Vec2| c[0] + c[1] * q.x + c[2] * q.y;
|
||||
let d = [top - at(pc.start), top - at(pc.end)];
|
||||
pc.top_drop = (d[0] > EPS || d[1] > EPS).then_some(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Körper eines Oberkanten-Stücks; unter einer Dachfläche ohne Löcher (Pfeiler, Brüstung, Sturz je mit
|
||||
/// eigener ebener Oberkante statt Treppung).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn emit_top_piece(em: &mut Emitter, li: usize, band_th: f64, tp: &TopPiece, u: Vec2, n: Vec2, zb: f64, cutouts: &[OpeningIn], innermost: bool, recess: f64) {
|
||||
let w = em.w;
|
||||
let holes = if w.layered { band_holes(w, li, cutouts, innermost, recess, tp.a, zb, tp.top) } else { Vec::new() };
|
||||
let len = tp.b - tp.a;
|
||||
let Some(c) = tp.plane else {
|
||||
push_top_piece(em, li, band_th, tp, 0.0, len, zb, tp.top, None, holes);
|
||||
return;
|
||||
};
|
||||
if holes.is_empty() {
|
||||
push_top_piece(em, li, band_th, tp, 0.0, len, zb, tp.top, Some(c), holes);
|
||||
return;
|
||||
}
|
||||
let mut xs = vec![0.0, len];
|
||||
for h in &holes {
|
||||
for x in [h[0], h[1]] {
|
||||
if x > EPS && x < len - EPS {
|
||||
xs.push(x);
|
||||
}
|
||||
}
|
||||
}
|
||||
xs.sort_by(|p, q| p.total_cmp(q));
|
||||
xs.dedup_by(|p, q| (*p - *q).abs() <= EPS);
|
||||
for i in 0..xs.len() - 1 {
|
||||
let (x0, x1) = (xs[i], xs[i + 1]);
|
||||
if x1 - x0 <= EPS {
|
||||
continue;
|
||||
}
|
||||
let mid = (x0 + x1) / 2.0;
|
||||
let mut zs: Vec<[f64; 2]> = holes.iter().filter(|h| h[0] <= mid && h[1] >= mid).map(|h| [h[2], h[3]]).collect();
|
||||
zs.sort_by(|p, q| p[0].total_cmp(&q[0]));
|
||||
let mut cur = zb;
|
||||
for [h0, h1] in zs {
|
||||
if h0 > cur + EPS {
|
||||
push_top_piece(em, li, band_th, tp, x0, x1, cur, h0, None, Vec::new());
|
||||
}
|
||||
cur = cur.max(h1);
|
||||
}
|
||||
let ca = if x0 <= EPS { tp.cut_a } else { None };
|
||||
let cb = if x1 >= len - EPS { tp.cut_b } else { None };
|
||||
let zc: Vec<f64> = strip_corners(w, u, n, tp.off, tp.th, tp.a + x0, tp.a + x1, ca, cb).iter().map(|q| c[0] + c[1] * q.x + c[2] * q.y).collect();
|
||||
let (zmin, zmax) = (zc.iter().copied().fold(f64::INFINITY, f64::min), zc.iter().copied().fold(f64::NEG_INFINITY, f64::max));
|
||||
// Sturz/Pfeiler bis unter die Dachfläche (Fenster, das ins Dach ragt: der Rest entfällt).
|
||||
if zmin > cur + EPS {
|
||||
push_top_piece(em, li, band_th, tp, x0, x1, cur, zmax.min(tp.top), Some(c), Vec::new());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -599,9 +936,20 @@ pub fn wall_bands(w: &WallIn, ctx: &FloorContext) -> Vec<Piece> {
|
||||
|
||||
if !w.layered {
|
||||
// Schnitt-Pfad: Pfeiler/Brüstung/Sturz, je Segment alle Bänder.
|
||||
// Unter Dächern ([G2]) je Segment die exakte Oberkante.
|
||||
let u = Vec2::new((w.end.x - w.start.x) / axis_len, (w.end.y - w.start.y) / axis_len);
|
||||
let n = left_normal(u);
|
||||
let seg = |em: &mut Emitter, from: f64, to: f64, zb: f64, zt: f64| {
|
||||
for (i, &off) in offsets.iter().enumerate() {
|
||||
em.push(i, from, to, zb, zt, off, vec![], [0.0, 0.0]);
|
||||
let th = w.bands[i].thickness;
|
||||
match roof_tops(w, ctx, u, n, off, th, from, to, None, None, zb, zt) {
|
||||
None => em.push(i, from, to, zb, zt, off, vec![], [0.0, 0.0]),
|
||||
Some(tops) => {
|
||||
for tp in &tops {
|
||||
emit_top_piece(em, i, th, tp, u, n, zb, &[], false, 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if cutouts.is_empty() {
|
||||
@@ -696,8 +1044,14 @@ pub fn wall_bands(w: &WallIn, ctx: &FloorContext) -> Vec<Piece> {
|
||||
let recess = b.thickness;
|
||||
for ([a, bb], cut_a, cut_b) in axis_pieces {
|
||||
let n0 = em.out.len();
|
||||
let mut emit_piece = |a: f64, bb: f64, zb: f64, zt_start: f64, zt_end: f64| {
|
||||
emit_band_piece(&mut em, li, off, &cutouts, innermost, recess, a, bb, zb, zt_start, zt_end);
|
||||
let th = b.thickness;
|
||||
let mut emit_piece = |a: f64, bb: f64, ca: Option<Line>, cb: Option<Line>, zb: f64, zt: f64| match roof_tops(w, ctx, u, n, off, th, a, bb, ca, cb, zb, zt) {
|
||||
None => emit_band_piece(&mut em, li, off, &cutouts, innermost, recess, a, bb, zb, zt),
|
||||
Some(tops) => {
|
||||
for tp in &tops {
|
||||
emit_top_piece(&mut em, li, th, tp, u, n, zb, &cutouts, innermost, recess);
|
||||
}
|
||||
}
|
||||
};
|
||||
let local: Vec<[f64; 4]> = band_z_cuts
|
||||
.iter()
|
||||
@@ -705,7 +1059,7 @@ pub fn wall_bands(w: &WallIn, ctx: &FloorContext) -> Vec<Piece> {
|
||||
.filter(|c| c[1] > c[0] + EPS)
|
||||
.collect();
|
||||
if local.is_empty() {
|
||||
clip_to_roofs(w, ctx, u, n, off, a, bb, z_bottom, z_top, &mut emit_piece);
|
||||
emit_piece(a, bb, cut_a, cut_b, z_bottom, z_top);
|
||||
set_piece_cuts(&mut em.out[n0..], w, u, a, bb, cut_a, cut_b);
|
||||
continue;
|
||||
}
|
||||
@@ -724,7 +1078,7 @@ pub fn wall_bands(w: &WallIn, ctx: &FloorContext) -> Vec<Piece> {
|
||||
let mid = (xa + xb) / 2.0;
|
||||
let z_cutters: Vec<[f64; 2]> = local.iter().filter(|c| c[0] <= mid && c[1] >= mid).map(|c| [c[2], c[3]]).collect();
|
||||
for [zb, zt] in terminate_or_subtract(z_bottom, z_top, &z_cutters, w.termination) {
|
||||
clip_to_roofs(w, ctx, u, n, off, xa, xb, zb, zt, &mut emit_piece);
|
||||
emit_piece(xa, xb, if xa == a { cut_a } else { None }, if xb == bb { cut_b } else { None }, zb, zt);
|
||||
}
|
||||
}
|
||||
set_piece_cuts(&mut em.out[n0..], w, u, a, bb, cut_a, cut_b);
|
||||
@@ -781,35 +1135,11 @@ fn reveal_pieces(em: &mut Emitter, offsets: &[f64]) {
|
||||
/// Ein Körper eines Bands im layered-Pfad: Öffnungs-Löcher auf den Körper-Start umrechnen (an der
|
||||
/// innersten Schicht mit Laibungs-Rücksprung geweitet); schräge Oberkante mit Löchern geht in
|
||||
/// render3d nicht → gestuft annähern.
|
||||
/// Körper eines Bandstücks ohne Dach darüber (waagrechte Krone, Öffnungen als Löcher).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn emit_band_piece(em: &mut Emitter, li: usize, off: f64, cutouts: &[OpeningIn], innermost: bool, recess: f64, a: f64, bb: f64, zb: f64, zt_start: f64, zt_end: f64) {
|
||||
let zt = zt_start.max(zt_end);
|
||||
let reveals = &em.w.reveals;
|
||||
let holes: Vec<[f64; 4]> = cutouts
|
||||
.iter()
|
||||
.filter(|h| h.z_top > zb + EPS && h.z_bottom < zt - EPS)
|
||||
.map(|h| {
|
||||
if let Some(s) = reveals.iter().find(|r| r.of(h)).and_then(|r| r.shifts.get(li)) {
|
||||
// [106]: Schicht springt je Seite zurück.
|
||||
[h.from - a - s[0], h.to - a + s[1], h.z_bottom - s[3], h.z_top + s[2]]
|
||||
} else if innermost && h.recess_inner_layer {
|
||||
[h.from - a - recess, h.to - a + recess, h.z_bottom - recess, h.z_top + recess]
|
||||
} else {
|
||||
[h.from - a, h.to - a, h.z_bottom, h.z_top]
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if !holes.is_empty() && (zt_start - zt_end).abs() > EPS {
|
||||
let k = 1usize.max(((bb - a) / ROOF_CLIP_STEP).ceil() as usize);
|
||||
for i in 0..k {
|
||||
let sa = a + ((bb - a) * i as f64) / k as f64;
|
||||
let sb = a + ((bb - a) * (i + 1) as f64) / k as f64;
|
||||
let zm = zt_start + ((zt_end - zt_start) * (i as f64 + 0.5)) / k as f64;
|
||||
emit_band_piece(em, li, off, cutouts, innermost, recess, sa, sb, zb, zm, zm);
|
||||
}
|
||||
return;
|
||||
}
|
||||
em.push(li, a, bb, zb, zt, off, holes, [zt - zt_start, zt - zt_end]);
|
||||
fn emit_band_piece(em: &mut Emitter, li: usize, off: f64, cutouts: &[OpeningIn], innermost: bool, recess: f64, a: f64, bb: f64, zb: f64, zt: f64) {
|
||||
let holes = band_holes(em.w, li, cutouts, innermost, recess, a, zb, zt);
|
||||
em.push(li, a, bb, zb, zt, off, holes, [0.0, 0.0]);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -832,6 +1162,7 @@ mod tests {
|
||||
openings: vec![],
|
||||
cuts: WallCuts::default(),
|
||||
reveals: vec![],
|
||||
roof_attach: None,
|
||||
}
|
||||
}
|
||||
fn band(t: f64, p: f64) -> BandIn {
|
||||
@@ -844,9 +1175,6 @@ mod tests {
|
||||
wall_bands(w, &FloorContext::default())
|
||||
}
|
||||
/// Achsen-Länge eines Körpers.
|
||||
fn plen(p: &Piece) -> f64 {
|
||||
js_hypot(p.end.x - p.start.x, p.end.y - p.start.y)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schichten_gestapelt_und_referenzversetzt() {
|
||||
@@ -1093,7 +1421,7 @@ mod tests {
|
||||
w.z_top = 5.0;
|
||||
// Ebene z = 2 + 0.5·x über [−1, 5]².
|
||||
let plane = vec![[-1.0, -1.0, 1.5], [5.0, -1.0, 4.5], [5.0, 5.0, 4.5], [-1.0, 5.0, 1.5]];
|
||||
let roof = RoofIn { eaves_z: 1.5, total_thickness: 0.0, eaves: plane.iter().map(|p| [p[0], p[1]]).collect(), planes: vec![plane] };
|
||||
let roof = RoofIn::new(1.5, 0.0, plane.iter().map(|p| [p[0], p[1]]).collect(), vec![plane]);
|
||||
let ctx = FloorContext::new(vec![], vec![roof]);
|
||||
let p = wall_bands(&w, &ctx);
|
||||
assert_eq!(p.len(), 1, "{p:?}");
|
||||
@@ -1101,12 +1429,172 @@ mod tests {
|
||||
// Abtastung 1 mm innerhalb der Enden (wie TS) → Toleranz 1e-3.
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 1e-3;
|
||||
assert!(near(p[0].z_top, 4.0) && near(d[0], 2.0) && d[1] == 0.0, "{p:?}");
|
||||
// Mit Öffnung: gestuft, ohne top_drop.
|
||||
// Mit Öffnung ([G2]): Pfeiler und Sturz mit schräger Oberkante statt Treppung.
|
||||
w.openings.push(OpeningIn { from: 1.0, to: 2.0, z_bottom: 0.0, z_top: 2.0, recess_inner_layer: false });
|
||||
let p = wall_bands(&w, &ctx);
|
||||
assert!(p.len() > 10 && p.iter().all(|q| q.top_drop.is_none()));
|
||||
let total: f64 = p.iter().map(plen).sum();
|
||||
assert!(close(total, 4.0));
|
||||
assert!(p.len() == 3 && p.iter().all(|q| q.holes.is_empty() && q.top_plane.is_some()), "{p:?}");
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
assert!((vol - 2.0).abs() < 1e-9, "{vol}");
|
||||
}
|
||||
|
||||
// ── [G2] Wand an Dach: exakte Oberkante je Schicht ──────────────────────────
|
||||
|
||||
/// Satteldach über [-1, 9] × [-1, 7], First bei y = 3 (längs x), Traufe z = 3, Neigung 45°.
|
||||
fn gable(total: f64) -> RoofIn {
|
||||
let s = vec![[-1.0, -1.0, 3.0], [9.0, -1.0, 3.0], [9.0, 3.0, 7.0], [-1.0, 3.0, 7.0]];
|
||||
let n = vec![[-1.0, 3.0, 7.0], [9.0, 3.0, 7.0], [9.0, 7.0, 3.0], [-1.0, 7.0, 3.0]];
|
||||
RoofIn::new(3.0, total, vec![[-1.0, -1.0], [9.0, -1.0], [9.0, 7.0], [-1.0, 7.0]], vec![s, n])
|
||||
}
|
||||
|
||||
/// Unterkante des Satteldachs (Dicke `t` senkrecht zur Fläche, 45° ⇒ lotrecht t·√2).
|
||||
fn gable_under(t: f64, y: f64) -> f64 {
|
||||
7.0 - (y - 3.0).abs() - t * 2f64.sqrt()
|
||||
}
|
||||
|
||||
/// Ecken einer Band-Grundfläche (mit Schnittlinien, Eigendicke).
|
||||
fn corners(w: &WallIn, p: &Piece) -> [Vec2; 4] {
|
||||
let u = sub(w.end, w.start);
|
||||
let u = scale(u, 1.0 / js_hypot(u.x, u.y));
|
||||
let n = left_normal(u);
|
||||
let h = p.thickness.unwrap_or(w.bands[p.band].thickness) / 2.0;
|
||||
let clip = |base: Vec2, c: Option<Line>| c.and_then(|c| line_intersect(base, u, c.point, c.dir)).unwrap_or(base);
|
||||
[clip(add(p.start, scale(n, h)), p.start_cut), clip(add(p.end, scale(n, h)), p.end_cut), clip(add(p.end, scale(n, -h)), p.end_cut), clip(add(p.start, scale(n, -h)), p.start_cut)]
|
||||
}
|
||||
|
||||
fn top_at(p: &Piece, q: Vec2) -> f64 {
|
||||
p.top_plane.map_or(p.z_top, |c| c[0] + c[1] * q.x + c[2] * q.y)
|
||||
}
|
||||
|
||||
/// Volumen eines Körpers: Grundfläche × Höhe im Schwerpunkt (exakt bei ebener Oberkante), ohne Löcher.
|
||||
fn volume(w: &WallIn, p: &Piece) -> f64 {
|
||||
let q = corners(w, p);
|
||||
let mut a = 0.0;
|
||||
let (mut cx, mut cy) = (0.0, 0.0);
|
||||
for i in 0..4 {
|
||||
let (p0, p1) = (q[i], q[(i + 1) % 4]);
|
||||
let c = p0.x * p1.y - p1.x * p0.y;
|
||||
a += c;
|
||||
cx += (p0.x + p1.x) * c;
|
||||
cy += (p0.y + p1.y) * c;
|
||||
}
|
||||
if a.abs() < 1e-15 {
|
||||
return 0.0;
|
||||
}
|
||||
let c = Vec2::new(cx / (3.0 * a), cy / (3.0 * a));
|
||||
let holes: f64 = p.holes.iter().map(|h| (h[1] - h[0]) * (h[3] - h[2])).sum::<f64>() * p.thickness.unwrap_or(w.bands[p.band].thickness);
|
||||
(a / 2.0).abs() * (top_at(p, c) - p.z_bottom) - holes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn giebelwand_folgt_beiden_dachflaechen_je_schicht() {
|
||||
// Giebelwand quer zum First (x = 0, y 0 → 6), zwei Schichten, Oberkante weit über dem Dach.
|
||||
let mut w = base((0.0, 0.0), (0.0, 6.0), vec![band(0.1, 10.0), band(0.2, 50.0)]);
|
||||
w.z_top = 9.0;
|
||||
let ctx = FloorContext::new(vec![], vec![gable(0.2)]);
|
||||
let p = wall_bands(&w, &ctx);
|
||||
// Je Schicht zwei Körper (links/rechts vom First), beide mit ebener Oberkante.
|
||||
assert_eq!(p.len(), 4, "{p:?}");
|
||||
for q in &p {
|
||||
assert!(q.top_plane.is_some() && q.holes.is_empty(), "{q:?}");
|
||||
for c in corners(&w, q) {
|
||||
assert!((top_at(q, c) - gable_under(0.2, c.y)).abs() < 1e-9, "Ecke {c:?} {q:?}");
|
||||
}
|
||||
}
|
||||
// Volumen = Fläche unter der Unterkante × Dicke (Fünfeck), exakt.
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
let h0 = gable_under(0.2, 0.0);
|
||||
let h1 = gable_under(0.2, 3.0);
|
||||
let expect = 0.3 * (6.0 * h0 + 3.0 * (h1 - h0));
|
||||
assert!((vol - expect).abs() < 1e-9, "{vol} vs {expect}");
|
||||
// Innere Stossfuge am First: keine sichtbare Stirn.
|
||||
assert!(p.iter().filter(|q| q.joint[0] || q.joint[1]).count() == 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traufwand_schraeg_ueber_die_dicke_und_seitlich_geteilt() {
|
||||
// Traufwand längs x bei y = 0.5 (Dicke 0.3: y 0.35 … 0.65), Dach steigt quer zur Wand.
|
||||
let mut w = base((0.0, 0.5), (8.0, 0.5), vec![band(0.3, 50.0)]);
|
||||
w.z_top = 9.0;
|
||||
let ctx = FloorContext::new(vec![], vec![gable(0.0)]);
|
||||
let p = wall_bands(&w, &ctx);
|
||||
assert_eq!(p.len(), 1, "{p:?}");
|
||||
let c = p[0].top_plane.unwrap();
|
||||
assert!(c[1].abs() < 1e-12 && (c[2] - 1.0).abs() < 1e-12, "Oberkante steigt mit y: {c:?}");
|
||||
for k in corners(&w, &p[0]) {
|
||||
assert!((top_at(&p[0], k) - gable_under(0.0, k.y)).abs() < 1e-9);
|
||||
}
|
||||
// Wandkrone 4.5 schneidet die Unterkante in der Dicke (y = 0.5): zwei Streifen nebeneinander.
|
||||
w.z_top = 4.5;
|
||||
let p = wall_bands(&w, &ctx);
|
||||
assert_eq!(p.len(), 2, "{p:?}");
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
// Aussen (y 0.35 … 0.5) schräg 4.35 … 4.5, innen flach 4.5.
|
||||
let expect = 8.0 * (0.15 * (4.35 + 4.5) / 2.0 + 0.15 * 4.5);
|
||||
assert!((vol - expect).abs() < 1e-9, "{vol} vs {expect}");
|
||||
assert!(p.iter().all(|q| q.thickness.is_some_and(|t| (t - 0.15).abs() < 1e-9)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wand_mit_fenster_unter_dachschraege_ohne_treppung() {
|
||||
let mut w = base((0.0, 0.0), (0.0, 6.0), vec![band(0.2, 50.0)]);
|
||||
w.z_top = 9.0;
|
||||
w.openings.push(OpeningIn { from: 1.0, to: 2.0, z_bottom: 1.0, z_top: 2.5, recess_inner_layer: false });
|
||||
let ctx = FloorContext::new(vec![], vec![gable(0.0)]);
|
||||
let p = wall_bands(&w, &ctx);
|
||||
// Pfeiler, Brüstung, Sturz, Pfeiler bis zum First, Pfeiler danach: keine Treppen, keine Löcher.
|
||||
assert!(p.len() <= 6 && p.iter().all(|q| q.holes.is_empty()), "{p:?}");
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
let gross = 0.2 * (6.0 * 4.0 + 3.0 * 3.0);
|
||||
assert!((vol - (gross - 0.2 * 1.5)).abs() < 1e-9, "{vol}");
|
||||
for q in &p {
|
||||
for c in corners(&w, q) {
|
||||
assert!(top_at(q, c) <= gable_under(0.0, c.y) + 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_dach_anschliessen_verlaengert_oder_ignoriert() {
|
||||
// Wandkrone 2.5 unter der Traufe: automatisch unverändert.
|
||||
let mut w = base((0.0, 0.0), (0.0, 6.0), vec![band(0.2, 50.0)]);
|
||||
w.z_top = 2.5;
|
||||
let ctx = FloorContext::new(vec![], vec![gable(0.0)]);
|
||||
let p = wall_bands(&w, &ctx);
|
||||
assert!(p.len() == 1 && p[0].top_plane.is_none() && close(p[0].z_top, 2.5));
|
||||
// An Dach anschliessen: bis unter die Dachfläche verlängert.
|
||||
w.roof_attach = Some(true);
|
||||
let p = wall_bands(&w, &ctx);
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
assert!((vol - 0.2 * (6.0 * 4.0 + 9.0)).abs() < 1e-9, "{vol} {p:?}");
|
||||
// Nie: Wand bleibt durchgehend, auch wenn sie über das Dach ragt.
|
||||
w.roof_attach = Some(false);
|
||||
w.z_top = 9.0;
|
||||
let p = wall_bands(&w, &ctx);
|
||||
assert!(p.len() == 1 && close(p[0].z_top, 9.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kehle_zweier_daecher_nimmt_die_obere_huelle() {
|
||||
// Zwei Pultdächer überdecken sich: Unterkante = obere Hülle (Maximum) der beiden.
|
||||
let a = RoofIn::new(0.0, 0.0, vec![], vec![vec![[0.0, -1.0, 2.0], [6.0, -1.0, 5.0], [6.0, 1.0, 5.0], [0.0, 1.0, 2.0]]]);
|
||||
let b = RoofIn::new(0.0, 0.0, vec![], vec![vec![[0.0, -1.0, 5.0], [6.0, -1.0, 2.0], [6.0, 1.0, 2.0], [0.0, 1.0, 5.0]]]);
|
||||
let mut w = base((0.0, 0.0), (6.0, 0.0), vec![band(0.2, 50.0)]);
|
||||
w.z_top = 9.0;
|
||||
let p = wall_bands(&w, &FloorContext::new(vec![], vec![a, b]));
|
||||
assert_eq!(p.len(), 2, "{p:?}");
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
assert!((vol - 0.2 * 25.5).abs() < 1e-9, "{vol}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schnitt_pfad_schneidet_ebenfalls_am_dach() {
|
||||
let mut w = base((0.0, 0.0), (0.0, 6.0), vec![band(0.3, 50.0)]);
|
||||
w.z_top = 9.0;
|
||||
w.layered = false;
|
||||
w.openings.push(OpeningIn { from: 1.0, to: 2.0, z_bottom: 1.0, z_top: 2.5, recess_inner_layer: false });
|
||||
let p = wall_bands(&w, &FloorContext::new(vec![], vec![gable(0.0)]));
|
||||
let vol: f64 = p.iter().map(|q| volume(&w, q)).sum();
|
||||
assert!((vol - 0.3 * (6.0 * 4.0 + 9.0 - 1.5)).abs() < 1e-9, "{vol}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1122,7 +1610,7 @@ mod tests {
|
||||
w.bands.push(band(0.0, 1.0));
|
||||
let ctx = FloorContext::new(
|
||||
vec![CeilingIn { z_bottom: 0.5, z_top: 0.5, outline: vec![Vec2::new(0.0, 0.0); 3], layers: Some(vec![]) }],
|
||||
vec![RoofIn { eaves_z: 0.0, total_thickness: 0.0, eaves: vec![], planes: vec![vec![]] }],
|
||||
vec![RoofIn::new(0.0, 0.0, vec![], vec![vec![]]), RoofIn::new(0.0, f64::NAN, vec![], vec![vec![[0.0, 0.0, f64::NAN], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], vec![[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 2.0]]])],
|
||||
);
|
||||
let _ = wall_bands(&w, &ctx);
|
||||
|
||||
|
||||
@@ -70,3 +70,16 @@ pub fn terrain_from_contours_json(contours_json: &str, id: &str) -> String {
|
||||
let c: Value = serde_json::from_str(contours_json).unwrap_or(Value::Null);
|
||||
crate::cmd_solid::terrain_from_contours(c.as_array().map(Vec::as_slice).unwrap_or(&[]), id).to_string()
|
||||
}
|
||||
|
||||
/// Wie [`terrain_from_contours_json`] mit Optionen ([T6]): `smooth` Glättungsstufen (0–4), `max_edge` grösste
|
||||
/// Kante in m (≤ 0 automatisch), `breaklines` ≠ 0 erzwingt die Konturen als Bruchkanten.
|
||||
#[wasm_bindgen]
|
||||
pub fn terrain_from_contours_opts_json(contours_json: &str, id: &str, smooth: f64, max_edge: f64, breaklines: f64) -> String {
|
||||
let c: Value = serde_json::from_str(contours_json).unwrap_or(Value::Null);
|
||||
let o = crate::terrain::TerrainOpts {
|
||||
smooth: if smooth.is_finite() { smooth.clamp(0.0, 4.0) as u32 } else { 2 },
|
||||
max_edge: if max_edge.is_finite() { max_edge } else { 0.0 },
|
||||
breaklines: breaklines != 0.0,
|
||||
};
|
||||
crate::cmd_solid::terrain_from_contours_with(c.as_array().map(Vec::as_slice).unwrap_or(&[]), id, o).to_string()
|
||||
}
|
||||
Reference in new issue
Block a user