[T3][T7][T8][T5] Merge: Wendelfläche + Handlauf-Wendel + Mittelsäule, Rotation/Loft-Befehle, Kollisionen im 3D, Import-Reparatur
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
36 files changed
+1413
-56
No files matched your search
@@ -1389,9 +1389,9 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
der Tauri-App. Offen: Schichteinzug [106], Formöffnungen [G3] und Ansichtsschraffur im 3D ([100]) in Bogenwänden; Wände teilen/trimmen (fehlt
|
||||
auch für gerade); echte Polar-Schraffur; IFC-Körper als extrudiertes Bogenprofil statt Netz; Griff-Vorschau
|
||||
zeigt nur die Achse; automatische Aussenbemassung misst Bogenwände als Sehne.
|
||||
- ○ **[T3] Wendeltreppe/Wendelfläche** + Handlauf-Sweep. · M
|
||||
- ○ **[T4] Import-Meshes glätten oder kantig** (`add_smooth_normals`). · S
|
||||
- ○ **[T5] Import reparieren** (`put_together_same_attrs`, Healing). · S
|
||||
- ◐ **[T3] Wendeltreppe/Wendelfläche** + Handlauf-Sweep. · M — 30.10.: Ortbeton-Wendeltreppe mit echter Wendelfläche (Schraubenuntersicht, ebene Tritte, `stairs3d::spiral_mesh`), Handlauf als Schraubensweep samt Pfosten (links/rechts/beide nach Drehsinn), Mittelsäule `Stair.centerColumn` (Radius, Objekt-Info; als Block in 3D/Schnitt). Tests Rust (Volumen, Punkte auf der Schraube, Sweep-Radius, Säule). Plansymbol (Bögen, Schnittlinie, Pfeil) war schon da und im CLI-SVG geprüft; nicht in der Tauri-App. Offen: Säule im Grundriss, IFC/Mengen der Wendelfläche, Handlauf-Profil rund.
|
||||
- ○ **[T4] Import-Meshes glätten oder kantig** (`add_smooth_normals`). · S — Stand 30.10.: nicht begonnen. Braucht Renderer-Änderung (`render3d::append_context_mesh` rechnet nur Flächennormalen) + Feld an `ImportedMesh`/`RMesh`/`MeshInput` + WASM/Metal-Neubau; Verschweissen ([T5]) als Voraussetzung ist da.
|
||||
- ✅ **[T5] Import reparieren** (`put_together_same_attrs`, Healing). · S — 30.10.: `mesh_repair.rs` im Mesh-Import (`decode_mesh`): Ecken verschweissen (0.01 mm), entartete Dreiecke entfernen, Löcher bis 8 Randkanten in fast geschlossenen Netzen (Randanteil ≤ 5 %) per Fächer schliessen, Orientierung nach aussen; Zähler im Importbericht (`repaired`, Meldung). Tests Rust (Suppe, Entartete, Loch/Orientierung, offene Fläche bleibt, Bericht). Gilt für OBJ/STL/glTF/PLY, nicht für IFC/DXF/STEP. Nicht in der App getestet. Offen: Verschweissen über Zellgrenzen, Schalter/Schwellen im Import-Dialog, Normalen-Ausrichtung widersprüchlich orientierter Flächen.
|
||||
- ◐ **[T6] Glattes Gelände aus Höhenlinien** + Gelände-Prisma für Aushub (= [68]). (30.10.) Kern `terrain.rs`:
|
||||
Konturen verdichtet und als Bruchkanten erzwungen (constrained Delaunay: Sloan-Kantentausch auf `delaunay.rs`,
|
||||
danach Lawson nur an freien Kanten; konkave Ränder: lange Randsplitter weg), flache Dreiecke (Kuppen/Mulden/
|
||||
@@ -1412,8 +1412,8 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
Offen: swissALTI3D-Raster wird nicht geglättet (nur Äquidistanz 1 m gesetzt); Natural-Neighbour/Clough-Tocher statt
|
||||
Hermite-Teilung; Höhenlinien unter der Beschriftung nicht unterbrochen; Luftbild-Farben fallen auf geändertem
|
||||
Gelände weg; Erdreich-Band fest 1.5 m (nicht bis zur Planunterkante). · L
|
||||
- ○ **[T7] Rotationskörper/Loft im UI** (API besteht). · S–M
|
||||
- ○ **[T8] Kollisionsprüfung im 3D zeigen** (heute nur Marker im Grundriss). · S
|
||||
- ✅ **[T7] Rotationskörper/Loft im UI** (API besteht). · S–M — 30.10.: Befehle `revolve` (Profil + Achse aus 2 Plan-Punkten + Winkel; Achse waagrecht auf Höhe r_max, Profil auf einer Seite) und `loft` (≥ 2 Profile der Reihe nach, gleichmässig über die Höhe; Punktzahl durch Kantenteilung angeglichen) in `cmd_solid.rs`/`cmds/{revolve,loft}.ts`, Körper als `ExtrudedSolid.brep` (Objekt-Info, STEP, Kennwerte wie die Grundkörper); Kürzel `rev`/`lf`, Werkzeugpalette 3D. Tests Rust (Spezifikation, Ops, truck-Volumen/STEP), vitest (Befehlsablauf). Nicht in der Tauri-App getestet. Offen: Achse senkrecht/beliebig im Raum, Loft mit Führungskurve, Profil-Startpunkt-Ausrichtung beim Loft.
|
||||
- ✅ **[T8] Kollisionsprüfung im 3D zeigen** (heute nur Marker im Grundriss). · S — 30.10.: Treffer in Sitzung (`panels/clashSession.ts`), Panel „Kollisionen" (`ClashPanel`: Liste, Klick wählt beide Bauteile und fährt die 3D-Kamera auf die Durchdringung, `cameraBridge.focusCamera`), im 3D rote Hüllquader aller Treffer (`clashHighlightLines` in `viewportContent`); Prüflauf öffnet das Panel, Marker im Grundriss bleiben. Tests vitest (Linien, Auswahl, Kamera-Fokus). Nicht im echten WebGPU-Viewport/Tauri geprüft. Offen: Hüllquader statt exakter Durchdringungsgeometrie, Panel-Name zeigt Ids statt Bauteilnamen, Wiederholung/Ignorieren einzelner Treffer.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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" => {
|
||||
|
||||
@@ -150,6 +150,130 @@ pub fn solid_from_inputs(shape: &str, p0: V, p1: Option<V>, nums: &[f64]) -> Opt
|
||||
}
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Rotationskörper und Loft aus Plan-Profilen ([T7])
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Rotationskörper: das Plan-Profil (geschlossen, in der Zeichenebene) dreht sich um die Achse
|
||||
/// `a → b` (liegt waagrecht im Plan, auf Höhe des grössten Profilabstands, damit ein voller Körper auf
|
||||
/// der Geschoss-UK steht). Das Profil muss ganz auf einer Seite der Achse liegen; es wird als
|
||||
/// (r = Abstand, z = Lage entlang der Achse) an `revolve` von truck gegeben und per `transform` ins
|
||||
/// Modell gesetzt (lokal x → Querrichtung, y → oben, z → Achse). `angle_deg` in (0, 360]; positive
|
||||
/// Drehung hebt das Profil nach oben. Ergebnis: Grundriss-Rechteck, Höhe, B-Rep-Beschreibung, Label.
|
||||
pub fn revolve_from_profile(profile: &[V], a: V, b: V, angle_deg: f64) -> Option<(Vec<V>, f64, Value, String)> {
|
||||
let len = hypot2(b.0 - a.0, b.1 - a.1);
|
||||
if profile.len() < 3 || !(len > 1e-6) || !angle_deg.is_finite() || !(angle_deg > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let mut d = ((b.0 - a.0) / len, (b.1 - a.1) / len);
|
||||
let side = |d: V, p: V| (p.0 - a.0) * -d.1 + (p.1 - a.1) * d.0;
|
||||
let (lo, hi) = profile.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(side(d, *p)), hi.max(side(d, *p))));
|
||||
if !(lo.is_finite() && hi.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
if lo < -1e-6 {
|
||||
if hi > 1e-6 {
|
||||
return None; // Profil überquert die Achse
|
||||
}
|
||||
d = (-d.0, -d.1); // Profil liegt rechts: Achse umdrehen, damit r >= 0
|
||||
}
|
||||
let n = (-d.1, d.0);
|
||||
let ring: Vec<(f64, f64)> = profile.iter().map(|p| (side(d, *p).max(0.0), (p.0 - a.0) * d.0 + (p.1 - a.1) * d.1)).collect();
|
||||
let r_max = ring.iter().fold(0.0_f64, |m, q| m.max(q.0));
|
||||
if !(r_max > 1e-6) {
|
||||
return None;
|
||||
}
|
||||
let (z_min, z_max) = ring.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q.1), hi.max(q.1)));
|
||||
if !(z_max - z_min > 1e-6) {
|
||||
return None;
|
||||
}
|
||||
let angle = angle_deg.min(360.0);
|
||||
let flat: Vec<Value> = ring.iter().flat_map(|q| [js_num(q.0), js_num(q.1)]).collect();
|
||||
let inner = obj(vec![("kind", s("revolve")), ("profile", Value::Array(flat)), ("angleDeg", js_num(angle))]);
|
||||
let m = [n.0, 0.0, d.0, a.0, n.1, 0.0, d.1, a.1, 0.0, 1.0, 0.0, r_max];
|
||||
let spec = obj(vec![("kind", s("transform")), ("m", Value::Array(m.iter().map(|x| js_num(*x)).collect())), ("solid", inner)]);
|
||||
let at = |along: f64, perp: f64| (a.0 + d.0 * along + n.0 * perp, a.1 + d.1 * along + n.1 * perp);
|
||||
let pts = vec![at(z_min, -r_max), at(z_max, -r_max), at(z_max, r_max), at(z_min, r_max)];
|
||||
Some((pts, 2.0 * r_max, spec, format!("Rotationskörper {}°", fixed2(angle))))
|
||||
}
|
||||
|
||||
fn ring_area(r: &[V]) -> f64 {
|
||||
let n = r.len();
|
||||
(0..n).map(|i| r[i].0 * r[(i + 1) % n].1 - r[(i + 1) % n].0 * r[i].1).sum::<f64>() / 2.0
|
||||
}
|
||||
|
||||
/// Gleiche Punktzahl für alle Ringe: kürzere Ringe teilen ihre längste Kante, bis sie so viele Punkte
|
||||
/// haben wie der längste (Ecken bleiben erhalten); alle gegen den Uhrzeigersinn.
|
||||
fn match_rings(rings: &[Vec<V>]) -> Vec<Vec<V>> {
|
||||
let target = rings.iter().map(Vec::len).max().unwrap_or(0);
|
||||
rings
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let mut r = r.clone();
|
||||
if ring_area(&r) < 0.0 {
|
||||
r.reverse();
|
||||
}
|
||||
while r.len() < target {
|
||||
let n = r.len();
|
||||
let len = |k: usize| hypot2(r[(k + 1) % n].0 - r[k].0, r[(k + 1) % n].1 - r[k].1);
|
||||
let Some(i) = (0..n).max_by(|&i, &j| len(i).partial_cmp(&len(j)).unwrap_or(std::cmp::Ordering::Equal)) else { break };
|
||||
let (p, q) = (r[i], r[(i + 1) % n]);
|
||||
r.insert(i + 1, ((p.0 + q.0) / 2.0, (p.1 + q.1) / 2.0));
|
||||
}
|
||||
r
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Loft durch >= 2 Plan-Profile, gleichmässig über `height` verteilt (erstes Profil unten).
|
||||
pub fn loft_from_rings(rings: &[Vec<V>], height: f64) -> Option<(Vec<V>, f64, Value, String)> {
|
||||
if rings.len() < 2 || !(height > 1e-6) || rings.iter().any(|r| r.len() < 3 || r.iter().any(|p| !(p.0.is_finite() && p.1.is_finite()))) {
|
||||
return None;
|
||||
}
|
||||
let rings = match_rings(rings);
|
||||
let last = (rings.len() - 1) as f64;
|
||||
let sections: Vec<Value> = rings
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, r)| obj(vec![("z", js_num(height * i as f64 / last)), ("points", Value::Array(r.iter().flat_map(|p| [js_num(p.0), js_num(p.1)]).collect()))]))
|
||||
.collect();
|
||||
let spec = obj(vec![("kind", s("loft")), ("sections", Value::Array(sections))]);
|
||||
Some((rings[0].clone(), height, spec, format!("Loft {} Profile h={}", rings.len(), fixed2(height))))
|
||||
}
|
||||
|
||||
fn profile_ring(root: &Map<String, Value>, id: &str) -> Option<Vec<V>> {
|
||||
let (pts, _) = find(root, "drawings2d", id).and_then(crate::cmd_create::profile_of)?;
|
||||
Some(pts.iter().map(xy).collect())
|
||||
}
|
||||
|
||||
fn brep_solid_ops(root: &Map<String, Value>, ctx: &Ctx, ids: &mut IdGen, sources: &[&str], made: Option<(Vec<V>, f64, Value, String)>) -> Vec<Op> {
|
||||
let Some((pts, height, spec, label)) = made else { return Vec::new() };
|
||||
let solid = obj(vec![
|
||||
("id", s(&ids.next("body"))),
|
||||
("type", s("extrudedSolid")),
|
||||
("levelId", s(ctx.level)),
|
||||
("points", pvs(&pts)),
|
||||
("height", js_num(height)),
|
||||
("brep", obj(vec![("spec", spec), ("origin", pv(pts[0])), ("label", s(&label))])),
|
||||
]);
|
||||
let mut ops = crate::cmd_create::remove_op(root, "drawings2d", sources);
|
||||
ops.extend(add_op("extrudedSolids", vec![solid]));
|
||||
ops
|
||||
}
|
||||
|
||||
fn revolve_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
let src = s_of(v, "source");
|
||||
let made = profile_ring(root, src).and_then(|ring| revolve_from_profile(&ring, p_of(v, "a"), p_of(v, "b"), num_or(field(v, "angle"), 360.0)));
|
||||
brep_solid_ops(root, ctx, ids, &[src], made)
|
||||
}
|
||||
|
||||
fn loft_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
let sources: Vec<&str> = arr(v.get("sources")).iter().filter_map(Value::as_str).collect();
|
||||
let rings: Option<Vec<Vec<V>>> = sources.iter().map(|id| profile_ring(root, id)).collect();
|
||||
let made = rings.and_then(|r| loft_from_rings(&r, n_of(v, "height")));
|
||||
brep_solid_ops(root, ctx, ids, &sources, made)
|
||||
}
|
||||
|
||||
fn solid_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
let nums: Vec<f64> = arr(v.get("nums")).iter().map(|x| num_of(Some(x))).collect();
|
||||
let Some((pts, height, spec, label)) = solid_from_inputs(s_of(v, "shape"), p_of(v, "p0"), opt_p(v, "p1"), &nums) else {
|
||||
@@ -645,6 +769,8 @@ fn direction_arrow(a: V, b: V, sign: f64, out: &mut Shapes) {
|
||||
pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option<Vec<Op>> {
|
||||
Some(match s_of(v, "cmd") {
|
||||
"solid" => solid_ops(v, ctx, ids),
|
||||
"revolve" => revolve_ops(root, v, ctx, ids),
|
||||
"loft" => loft_ops(root, v, ctx, ids),
|
||||
"solidbool" => solidbool_ops(root, v, ids),
|
||||
"voidbox" => voidbox_ops(v, ctx, ids),
|
||||
"terrain" => terrain_ops(root, ids),
|
||||
@@ -798,4 +924,57 @@ mod tests {
|
||||
assert!(pos.iter().skip(2).step_by(3).all(|z| (1.0..=2.0).contains(&z.as_f64().unwrap())));
|
||||
assert!(terrain_from_contours(&[], "t")["indices"].as_array().unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// [T7] Rotationskörper: Achse waagrecht im Plan, Profil auf einer Seite, Matrix bildet lokal x → Quer, z → Achse ab.
|
||||
#[test]
|
||||
fn rotationskoerper_aus_profil() {
|
||||
let prof = [(0.0, 0.0), (2.0, 0.0), (2.0, 1.0), (0.0, 1.0)];
|
||||
let (pts, h, spec, label) = revolve_from_profile(&prof, (0.0, 0.0), (5.0, 0.0), 360.0).unwrap();
|
||||
assert_eq!(h, 2.0);
|
||||
assert_eq!(label, "Rotationskörper 360.00°");
|
||||
assert_eq!(spec["kind"], "transform");
|
||||
assert_eq!(spec["solid"]["profile"], json!([0, 0, 0, 2, 1, 2, 1, 0]));
|
||||
let m: Vec<f64> = spec["m"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
|
||||
let w = |l: [f64; 3]| [m[0] * l[0] + m[1] * l[1] + m[2] * l[2] + m[3], m[4] * l[0] + m[5] * l[1] + m[6] * l[2] + m[7], m[8] * l[0] + m[9] * l[1] + m[10] * l[2] + m[11]];
|
||||
assert_eq!(w([1.0, 0.0, 2.0]), [2.0, 1.0, 1.0]);
|
||||
assert_eq!(w([0.0, 1.0, 0.0]), [0.0, 0.0, 2.0]);
|
||||
assert_eq!(pts.len(), 4);
|
||||
let rechts = [(0.0, 0.0), (2.0, 0.0), (2.0, -1.0), (0.0, -1.0)];
|
||||
let (_, _, spec2, _) = revolve_from_profile(&rechts, (0.0, 0.0), (5.0, 0.0), 90.0).unwrap();
|
||||
assert_eq!(spec2["solid"]["angleDeg"], 90.0);
|
||||
assert!(revolve_from_profile(&[(0.0, -1.0), (2.0, -1.0), (2.0, 1.0), (0.0, 1.0)], (0.0, 0.0), (5.0, 0.0), 360.0).is_none());
|
||||
assert!(revolve_from_profile(&prof, (0.0, 0.0), (0.0, 0.0), 360.0).is_none());
|
||||
assert!(revolve_from_profile(&prof, (0.0, 0.0), (5.0, 0.0), f64::NAN).is_none());
|
||||
}
|
||||
|
||||
/// [T7] Loft: gleiche Punktzahl (Kante teilen), Höhen gleichmässig, Ringe gegen den Uhrzeigersinn.
|
||||
#[test]
|
||||
fn loft_aus_profilen() {
|
||||
let quad = vec![(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)];
|
||||
let tri_cw = vec![(0.5, 0.5), (0.5, 1.5), (1.5, 0.5)];
|
||||
let (pts, h, spec, label) = loft_from_rings(&[quad.clone(), tri_cw, quad.clone()], 3.0).unwrap();
|
||||
assert_eq!((pts.len(), h), (4, 3.0));
|
||||
assert_eq!(label, "Loft 3 Profile h=3.00");
|
||||
let secs = spec["sections"].as_array().unwrap();
|
||||
assert_eq!(secs.len(), 3);
|
||||
assert_eq!(secs[1]["z"], 1.5);
|
||||
assert!(secs.iter().all(|s| s["points"].as_array().unwrap().len() == 8));
|
||||
assert!(loft_from_rings(&[quad.clone()], 3.0).is_none());
|
||||
assert!(loft_from_rings(&[quad.clone(), quad], 0.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_und_loft_befehle_legen_koerper_an_und_entfernen_quellen() {
|
||||
let d = |id: &str, pts: Value| json!({"id": id, "type": "drawing2d", "levelId": "eg", "geom": {"shape": "polyline", "closed": true, "pts": pts}});
|
||||
let sq = |x: f64, s: f64| json!([{"x": x, "y": 0}, {"x": x + s, "y": 0}, {"x": x + s, "y": s}, {"x": x, "y": s}]);
|
||||
let root = json!({"drawings2d": [d("A", sq(0.0, 2.0)), d("B", sq(10.0, 1.0))]});
|
||||
let root = root.as_object().unwrap();
|
||||
let ctx = Ctx { level: "eg", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 };
|
||||
let mut ids = IdGen::new("t");
|
||||
let ops = loft_ops(root, &json!({"sources": ["A", "B"], "height": 2.0}), &ctx, &mut ids);
|
||||
assert_eq!(ops.len(), 2);
|
||||
let ops = revolve_ops(root, &json!({"source": "A", "a": {"x": -1, "y": -1}, "b": {"x": 5, "y": -1}, "angle": 180}), &ctx, &mut ids);
|
||||
assert_eq!(ops.len(), 2);
|
||||
assert!(revolve_ops(root, &json!({"source": "ZZ", "a": {"x": 0, "y": 0}, "b": {"x": 1, "y": 0}}), &ctx, &mut ids).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ pub mod js_fmt;
|
||||
pub use dossier_hatch::jsmath;
|
||||
pub mod stairs3d;
|
||||
pub mod mesh3d;
|
||||
pub mod mesh_repair;
|
||||
pub mod ceilings3d;
|
||||
pub mod columns3d;
|
||||
pub mod drawing2d_3d;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -3127,6 +3127,11 @@ pub struct Stair {
|
||||
#[serde(rename = "arrowStyle", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional, inline)]
|
||||
pub arrow_style: Option<StairArrowStyle>,
|
||||
/// Nur Wendel: Radius (Meter) der Mittelsäule (Spindel) im Zentrum. Fehlt er oder ist er
|
||||
/// ≤ 0, gibt es keine Säule.
|
||||
#[serde(rename = "centerColumn", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub center_column: Option<f64>,
|
||||
#[serde(flatten)]
|
||||
#[ts(skip)]
|
||||
pub extra: Extra,
|
||||
|
||||
@@ -1132,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();
|
||||
@@ -1167,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))
|
||||
}
|
||||
@@ -1197,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![],
|
||||
}
|
||||
|
||||
@@ -914,6 +914,7 @@ fn stair_selection(root: &Map<String, Value>, s: &Value) -> Result<J, String> {
|
||||
.v("up", Value::Bool(field(s, "up") != Some(&Value::Bool(false))))
|
||||
.raw("arrowStyle", s, "arrowStyle")
|
||||
.raw("referenz", s, "referenz")
|
||||
.raw("centerColumn", s, "centerColumn")
|
||||
.raw("typeId", s, "typeId")
|
||||
.raw("floorId", s, "floorId")
|
||||
.o("floorName", floor_name(floor, field(s, "floorId")))
|
||||
|
||||
+266
-10
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -1127,6 +1127,32 @@ mod dbg_step {
|
||||
assert!((vol(&mir) - 6.0).abs() < 1e-6, "mir {}", vol(&mir));
|
||||
}
|
||||
|
||||
/// [T7] Rotationskörper um eine waagrechte Planachse (Befehl `revolve`, `cmd_solid.rs`): Zylinder r=1, l=2
|
||||
/// auf dem Boden; Halbdrehung = halbes Volumen; STEP-Export klappt.
|
||||
#[test]
|
||||
fn revolve_um_waagrechte_achse_steht_auf_dem_boden() {
|
||||
let spec = |angle: f64| SolidSpec::Transform {
|
||||
m: [-1.0, 0.0, 0.0, 3.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0],
|
||||
solid: Box::new(SolidSpec::Revolve { profile: vec![0.0, 0.0, 0.0, 2.0, 1.0, 2.0, 1.0, 0.0], cx: 0.0, cy: 0.0, angle_deg: angle }),
|
||||
};
|
||||
let vol_zmin = |sp: &SolidSpec| {
|
||||
let m = solid_mesh_core(sp, 0.005).unwrap();
|
||||
let p: Vec<[f64; 3]> = m.positions.chunks(3).map(|c| [c[0] as f64, c[1] as f64, c[2] as f64]).collect();
|
||||
let v: f64 = m.indices.chunks(3).map(|t| {
|
||||
let (a, b, c) = (p[t[0] as usize], p[t[1] as usize], p[t[2] as usize]);
|
||||
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
|
||||
}).sum();
|
||||
(v, p.iter().map(|q| q[2]).fold(f64::INFINITY, f64::min), p.iter().map(|q| q[2]).fold(f64::NEG_INFINITY, f64::max))
|
||||
};
|
||||
let (v, z0, z1) = vol_zmin(&spec(360.0));
|
||||
assert!((v - 2.0 * std::f64::consts::PI).abs() < 0.02, "Volumen {v}");
|
||||
assert!(z0.abs() < 1e-3 && (z1 - 2.0).abs() < 1e-3, "z {z0}..{z1}");
|
||||
let (vh, h0, _) = vol_zmin(&spec(180.0));
|
||||
assert!((vh - std::f64::consts::PI).abs() < 0.02, "halb {vh}");
|
||||
assert!(h0 > 0.99, "Halbdrehung steigt nach oben: {h0}");
|
||||
assert!(export_step_core(&[spec(360.0)], &StepHeader::default()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bool_result_step_dump() {
|
||||
let dir = std::env::var("STEP_DUMP_DIR").unwrap_or_default();
|
||||
|
||||
+3
-18
@@ -66,7 +66,7 @@ import { IfcImportDialog, type IfcImportMode } from "./ui/IfcImportDialog";
|
||||
import { MeshImportHost } from "./ui/MeshImportDialog";
|
||||
import { openMeshFileDialog, requestMeshImport, splitMeshFiles } from "./state/meshImportStore";
|
||||
import { formatMeshReport, isMeshFile } from "./io/meshImport";
|
||||
import { clashMarkerOps, runClashCheck } from "./analysis/clash";
|
||||
import { runClashAndStore } from "./panels/clashSession";
|
||||
import { checkForUpdate } from "./update/checkForUpdate";
|
||||
import type { PlanViewHandle } from "./views/plan/PlanView";
|
||||
import type { DisplayResolver } from "./viewport/Viewport3D";
|
||||
@@ -2376,23 +2376,8 @@ export default function App() {
|
||||
onImportPointCloud: () => openPointCloudFileDialog(),
|
||||
onImportMesh: () => openMeshFileDialog(),
|
||||
onClashCheck: () => {
|
||||
const p0 = project;
|
||||
runClashCheck(p0)
|
||||
.then((clashes) => {
|
||||
applyChange((p) => clashMarkerOps(p, clashes, activeCategoryCode));
|
||||
// window.alert ist im Tauri-WKWebView wirkungslos → Toast.
|
||||
notify(
|
||||
clashes.length === 0
|
||||
? t("clash.none")
|
||||
: `${t("clash.found")}: ${clashes.length} — ` +
|
||||
clashes
|
||||
.slice(0, 5)
|
||||
.map((c, k) => `K${k + 1} ${c.a.kind}↔${c.b.kind}${c.volume !== null ? ` ${c.volume.toFixed(3)} m³` : ""}`)
|
||||
.join(", "),
|
||||
clashes.length === 0 ? "info" : "warning",
|
||||
);
|
||||
})
|
||||
.catch((err) => notify(`${t("clash.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"));
|
||||
setLayout((l) => revealPanel(l, "clash"));
|
||||
void runClashAndStore();
|
||||
},
|
||||
onKennzahlen: () => {
|
||||
const k = computeKennzahlen(project);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { candidatePairs, clashItems, clashMarkerOps, CLASH_MARKER_PREFIX } from "./clash";
|
||||
import { candidatePairs, clashHighlightLines, clashItems, clashMarkerOps, clashSelection, CLASH_MARKER_PREFIX } from "./clash";
|
||||
import { applyOps } from "../core/ops";
|
||||
import type { Project } from "../model/types";
|
||||
import type { Clash } from "./clash";
|
||||
@@ -22,11 +22,28 @@ describe("Kollisionspruefung", () => {
|
||||
expect(items.some((i) => i.kind === "wall")).toBe(true);
|
||||
});
|
||||
it("Marker ersetzen alte Marker", () => {
|
||||
const clash = { a: it0("a", "solid"), b: it0("b", "wall"), volume: 0.12, center: [1, 2, 0.5] as [number, number, number] };
|
||||
const clash = { a: it0("a", "solid"), b: it0("b", "wall"), volume: 0.12, center: [1, 2, 0.5] as [number, number, number], min: [0.5, 1.5, 0] as [number, number, number], max: [1.5, 2.5, 1] as [number, number, number] };
|
||||
const p1 = applyClashMarkers(sampleProject, [clash, clash], "A");
|
||||
const n1 = p1.drawings2d.filter((d) => d.id.startsWith(CLASH_MARKER_PREFIX)).length;
|
||||
expect(n1).toBe(4);
|
||||
const p2 = applyClashMarkers(p1, [clash], "A");
|
||||
expect(p2.drawings2d.filter((d) => d.id.startsWith(CLASH_MARKER_PREFIX)).length).toBe(2);
|
||||
});
|
||||
it("3D-Hervorhebung: 12 Kanten je Kollision als Linienpaare im Viewport-Raum (y/z getauscht)", () => {
|
||||
const clash = { a: it0("a", "solid"), b: it0("b", "wall"), volume: 0.12, center: [1, 2, 0.5] as [number, number, number], min: [0.5, 1.5, 0] as [number, number, number], max: [1.5, 2.5, 1] as [number, number, number] };
|
||||
const lines = clashHighlightLines([clash], [1, 0, 0]);
|
||||
expect(lines.length).toBe(12 * 2 * 6);
|
||||
// erster Eckpunkt: Modell (min.x, min.y, min.z) → world (x, Höhe, y), Farbe rot
|
||||
const verts = [];
|
||||
for (let k = 0; k < lines.length; k += 6) verts.push([...lines.slice(k, k + 6)]);
|
||||
expect(verts.every((v) => v[3] === 1 && v[4] === 0 && v[5] === 0)).toBe(true);
|
||||
expect(verts.every((v) => v[0] >= 0.5 && v[0] <= 1.5 && v[1] >= 0 && v[1] <= 1 && v[2] >= 1.5 && v[2] <= 2.5)).toBe(true);
|
||||
expect(clashHighlightLines([], [1, 0, 0]).length).toBe(0);
|
||||
});
|
||||
it("Auswahl eines Paars je Bauteilart", () => {
|
||||
const clash = { a: it0("s1", "solid"), b: it0("w1", "wall"), volume: null, center: [0, 0, 0] as [number, number, number], min: [0, 0, 0] as [number, number, number], max: [1, 1, 1] as [number, number, number] };
|
||||
expect(clashSelection(clash)).toEqual({ wallIds: ["w1"], ceilingIds: [], extrudedSolidIds: ["s1"], contextObjectIds: [] });
|
||||
const m = { ...clash, a: it0("m1", "mesh"), b: it0("c1", "slab") };
|
||||
expect(clashSelection(m)).toEqual({ wallIds: [], ceilingIds: ["c1"], extrudedSolidIds: [], contextObjectIds: ["m1"] });
|
||||
});
|
||||
});
|
||||
+53
-5
@@ -30,8 +30,11 @@ export interface Clash {
|
||||
b: ClashItem;
|
||||
/** Durchdringungsvolumen (m³), `null` wenn nicht berechenbar. */
|
||||
volume: number | null;
|
||||
/** Mittelpunkt der Durchdringungslinien (Welt-Meter). */
|
||||
/** Mittelpunkt der Durchdringungslinien (Modell-Meter, z = Höhe). */
|
||||
center: [number, number, number];
|
||||
/** Hüllquader der Durchdringungslinien (Modell-Meter) — für Hervorhebung und Zoom. */
|
||||
min: [number, number, number];
|
||||
max: [number, number, number];
|
||||
}
|
||||
|
||||
/** Prefix der Marker-Ids (ein neuer Lauf ersetzt die alten Marker). */
|
||||
@@ -127,13 +130,17 @@ export async function runClashCheck(
|
||||
if (!r.colliding || r.lines.length === 0) continue;
|
||||
if (r.overlapVolume !== null && r.overlapVolume < MIN_VOLUME) continue;
|
||||
const c: [number, number, number] = [0, 0, 0];
|
||||
const min: [number, number, number] = [Infinity, Infinity, Infinity];
|
||||
const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
|
||||
for (const l of r.lines) {
|
||||
c[0] += (l[0] + l[3]) / 2;
|
||||
c[1] += (l[1] + l[4]) / 2;
|
||||
c[2] += (l[2] + l[5]) / 2;
|
||||
for (let k = 0; k < 3; k++) {
|
||||
c[k] += (l[k] + l[k + 3]) / 2;
|
||||
min[k] = Math.min(min[k], l[k], l[k + 3]);
|
||||
max[k] = Math.max(max[k], l[k], l[k + 3]);
|
||||
}
|
||||
}
|
||||
const n = r.lines.length;
|
||||
const clash: Clash = { a: items[i], b: items[j], volume: r.overlapVolume, center: [c[0] / n, c[1] / n, c[2] / n] };
|
||||
const clash: Clash = { a: items[i], b: items[j], volume: r.overlapVolume, center: [c[0] / n, c[1] / n, c[2] / n], min, max };
|
||||
// Mehrere Wandschichten derselben Wand → eine Kollision (grösstes Volumen).
|
||||
const key = [items[i].id, items[j].id].sort().join("|");
|
||||
const prev = found.get(key);
|
||||
@@ -175,3 +182,44 @@ export function clashMarkerOps(project: Project, clashes: Clash[], categoryCode:
|
||||
...addItems("drawings2d", markers),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Rote Hüllquader der Kollisionen als Linienliste für den 3D-Viewport (`set_highlight_lines`):
|
||||
* `[x, y, z, r, g, b]` je Vertex, 2 Vertices je Kante, 12 Kanten je Kollision. Modell (x, y, Höhe)
|
||||
* → Viewport-Welt (x, Höhe, y). Mindestkantenlänge 0.1 m, damit hauchdünne Durchdringungen sichtbar bleiben.
|
||||
*/
|
||||
export function clashHighlightLines(clashes: Clash[], rgb: readonly [number, number, number]): Float32Array {
|
||||
const out = new Float32Array(clashes.length * 12 * 2 * 6);
|
||||
let o = 0;
|
||||
const vert = (p: readonly number[]) => {
|
||||
out[o++] = p[0];
|
||||
out[o++] = p[2];
|
||||
out[o++] = p[1];
|
||||
out[o++] = rgb[0];
|
||||
out[o++] = rgb[1];
|
||||
out[o++] = rgb[2];
|
||||
};
|
||||
for (const c of clashes) {
|
||||
const lo = [0, 1, 2].map((k) => Math.min(c.min[k], c.center[k] - 0.05));
|
||||
const hi = [0, 1, 2].map((k) => Math.max(c.max[k], c.center[k] + 0.05));
|
||||
const corner = (i: number) => [i & 1 ? hi[0] : lo[0], i & 2 ? hi[1] : lo[1], i & 4 ? hi[2] : lo[2]];
|
||||
for (let i = 0; i < 8; i++) {
|
||||
for (const bit of [1, 2, 4]) {
|
||||
if (i & bit) continue;
|
||||
vert(corner(i));
|
||||
vert(corner(i | bit));
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Bauteile einer Kollision je Auswahlkanal (Wand, Decke, Körper, Import). */
|
||||
export function clashSelection(c: Clash): { wallIds: string[]; ceilingIds: string[]; extrudedSolidIds: string[]; contextObjectIds: string[] } {
|
||||
const sel = { wallIds: [] as string[], ceilingIds: [] as string[], extrudedSolidIds: [] as string[], contextObjectIds: [] as string[] };
|
||||
for (const it of [c.a, c.b]) {
|
||||
const list = it.kind === "wall" ? sel.wallIds : it.kind === "slab" ? sel.ceilingIds : it.kind === "solid" ? sel.extrudedSolidIds : sel.contextObjectIds;
|
||||
if (!list.includes(it.id)) list.push(it.id);
|
||||
}
|
||||
return sel;
|
||||
}
|
||||
@@ -32,25 +32,25 @@ let lastTaper = 0;
|
||||
// ── Profil (Kern, `cmd_create.rs`): geschlossene polyline/rect/circle → Punktliste ─
|
||||
|
||||
/** Profil eines extrudierbaren 2D-Elements (Kreis: 48-Eck + Mittelpunkt/Radius). */
|
||||
interface Profile {
|
||||
export interface Profile {
|
||||
pts: Vec2[];
|
||||
circle?: { center: Vec2; r: number };
|
||||
}
|
||||
|
||||
type ProfileHit = { id: string } & Profile;
|
||||
export type ProfileHit = { id: string } & Profile;
|
||||
|
||||
function profileQuery(project: Project, req: { q: string } & Record<string, unknown>): ProfileHit | null {
|
||||
return createQuery<{ hit: (ProfileHit & { circle: Profile["circle"] | null }) | null }>(project, req).hit ?? null;
|
||||
}
|
||||
|
||||
/** Genau EIN geeignetes Profil vorgewählt (sonst null). */
|
||||
function singleSelectedProfile(project: Project, sel: CommandSelection): ProfileHit | null {
|
||||
export function singleSelectedProfile(project: Project, sel: CommandSelection): ProfileHit | null {
|
||||
if (!sel.drawingId || sel.wallIds.length > 0) return null;
|
||||
return profileQuery(project, { q: "profile", id: sel.drawingId });
|
||||
}
|
||||
|
||||
/** Nächstes Profil der Ebene am Klickpunkt (Kanten-Abstand < 0.25 m). */
|
||||
const pickProfileAt = (project: Project, levelId: string, pt: Vec2): ProfileHit | null =>
|
||||
export const pickProfileAt = (project: Project, levelId: string, pt: Vec2): ProfileHit | null =>
|
||||
profileQuery(project, { q: "pickProfile", level: levelId, pt: xy(pt) });
|
||||
|
||||
/** Commit (Kern): Quelle entfernen, Körper (Punkte + Höhe + Verjüngung) anlegen. */
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// Loft ([T7]): ≥ 2 geschlossene Plan-Profile nacheinander anklicken (erstes = unten), Enter, dann die
|
||||
// Gesamthöhe. Die Profile werden gleichmässig über die Höhe verteilt (Kern `cmd_solid.rs`: gleiche
|
||||
// Punktzahl durch Kantenteilung, Drehsinn angeglichen) und zu einem truck-`loft`-B-Rep-Körper
|
||||
// (`ExtrudedSolid.brep`) verbunden; die Quellprofile entfallen wie beim Extrudieren.
|
||||
|
||||
import type { Command, CommandContext, CommandResult, CommandState, Vec2 } from "../types";
|
||||
import { createMutation } from "../createCore";
|
||||
import { pickProfileAt, type ProfileHit } from "./extrude";
|
||||
|
||||
let lastHeight = 3;
|
||||
|
||||
interface LoftState extends CommandState {
|
||||
phase: "pick" | "height" | "done";
|
||||
picks: ProfileHit[];
|
||||
}
|
||||
|
||||
const draft = (s: LoftState, cursor: Vec2 | null): CommandResult["draft"] => ({
|
||||
preview: s.picks.map((p) => ({ kind: "poly" as const, pts: p.pts, closed: true })),
|
||||
vertices: [],
|
||||
hud: cursor ? { at: cursor, text: s.phase === "height" ? `${lastHeight.toFixed(2)} m` : `${s.picks.length}` } : undefined,
|
||||
});
|
||||
|
||||
const finished = (): LoftState => ({ phase: "done", picks: [], lastPoint: null });
|
||||
const done = (): [CommandState, CommandResult] => [finished(), { draft: null, done: true }];
|
||||
|
||||
function commit(s: LoftState, height: number, ctx: CommandContext): [CommandState, CommandResult] {
|
||||
lastHeight = height;
|
||||
return [
|
||||
finished(),
|
||||
{ draft: null, done: true, commit: createMutation(ctx, { cmd: "loft", sources: s.picks.map((p) => p.id), height }) },
|
||||
];
|
||||
}
|
||||
|
||||
export const loftCommand: Command = {
|
||||
name: "loft",
|
||||
labelKey: "cmd.loft.label",
|
||||
prompt: (st) => ((st as LoftState).phase === "height" ? "cmd.loft.height" : (st as LoftState).picks.length < 2 ? "cmd.loft.pick" : "cmd.loft.pickMore"),
|
||||
accepts: (st) => ((st as LoftState).phase === "height" ? ["number"] : ["point"]),
|
||||
options: () => [],
|
||||
floorOnly: true,
|
||||
|
||||
init: (): LoftState => ({ phase: "pick", picks: [], lastPoint: null }),
|
||||
|
||||
onInput: (state, input, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as LoftState;
|
||||
if (s.phase === "done") return done();
|
||||
if (s.phase === "pick") {
|
||||
if (input.kind !== "point") return [s, { draft: draft(s, null) }];
|
||||
const hit = pickProfileAt(ctx.project, ctx.level.id, input.point);
|
||||
if (!hit || s.picks.some((p) => p.id === hit.id)) return [s, { draft: draft(s, null) }];
|
||||
const ns: LoftState = { ...s, picks: [...s.picks, hit] };
|
||||
return [ns, { draft: draft(ns, input.point) }];
|
||||
}
|
||||
if (input.kind !== "number" || !(input.value > 0)) return [s, { draft: draft(s, null) }];
|
||||
return commit(s, input.value, ctx);
|
||||
},
|
||||
|
||||
onMove: (state, point): [CommandState, CommandResult] => [state, { draft: draft(state as LoftState, point) }],
|
||||
|
||||
// Enter: mit ≥ 2 Profilen zur Höhe; bei der Höhe die zuletzt benutzte übernehmen.
|
||||
onConfirm: (state, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as LoftState;
|
||||
if (s.phase === "pick") {
|
||||
if (s.picks.length < 2) return [s, { draft: draft(s, null) }];
|
||||
const ns: LoftState = { ...s, phase: "height" };
|
||||
return [ns, { draft: draft(ns, null) }];
|
||||
}
|
||||
return s.phase === "height" ? commit(s, lastHeight, ctx) : done();
|
||||
},
|
||||
onCancel: () => done(),
|
||||
};
|
||||
@@ -0,0 +1,98 @@
|
||||
// Rotationskörper ([T7]): geschlossenes Plan-Profil + Drehachse (2 Punkte im Plan) + Winkel → truck-
|
||||
// `revolve` als B-Rep-Körper (`ExtrudedSolid.brep`, Kern `cmd_solid.rs`). Das Profil muss ganz auf einer
|
||||
// Seite der Achse liegen; die Achse liegt waagrecht auf Höhe des grössten Profilabstands, ein voller
|
||||
// Körper steht also auf der Geschoss-UK. Die Quelle (Profil) wird ersetzt wie beim Extrudieren.
|
||||
//
|
||||
// Schritte: Profil wählen (oder vorselektiert) → Achse Anfang → Achse Ende → Winkel (Zahl oder Enter = zuletzt, 360).
|
||||
|
||||
import type { Command, CommandContext, CommandResult, CommandState, Vec2 } from "../types";
|
||||
import { createMutation } from "../createCore";
|
||||
import { pickProfileAt, singleSelectedProfile, type Profile } from "./extrude";
|
||||
|
||||
let lastAngle = 360;
|
||||
|
||||
interface RevState extends CommandState {
|
||||
phase: "pick" | "axisA" | "axisB" | "angle" | "done";
|
||||
profile: Profile | null;
|
||||
sourceId: string | null;
|
||||
a: Vec2 | null;
|
||||
b: Vec2 | null;
|
||||
cursor: Vec2 | null;
|
||||
}
|
||||
|
||||
const draft = (s: RevState, cursor: Vec2 | null): CommandResult["draft"] => {
|
||||
const preview: NonNullable<CommandResult["draft"]>["preview"] = [];
|
||||
if (s.profile) preview.push({ kind: "poly", pts: s.profile.pts, closed: true });
|
||||
const end = s.b ?? cursor;
|
||||
if (s.a && end) preview.push({ kind: "line", a: s.a, b: end });
|
||||
return { preview, vertices: s.a ? [s.a] : [], hud: cursor && s.phase === "angle" ? { at: cursor, text: `${lastAngle}°` } : undefined };
|
||||
};
|
||||
|
||||
const finished = (): RevState => ({ phase: "done", profile: null, sourceId: null, a: null, b: null, cursor: null, lastPoint: null });
|
||||
|
||||
const done = (): [CommandState, CommandResult] => [finished(), { draft: null, done: true }];
|
||||
|
||||
function commit(s: RevState, angle: number, ctx: CommandContext): [CommandState, CommandResult] {
|
||||
lastAngle = angle;
|
||||
return [
|
||||
finished(),
|
||||
{ draft: null, done: true, commit: createMutation(ctx, { cmd: "revolve", source: s.sourceId, a: s.a, b: s.b, angle }) },
|
||||
];
|
||||
}
|
||||
|
||||
export const revolveCommand: Command = {
|
||||
name: "revolve",
|
||||
labelKey: "cmd.revolve.label",
|
||||
prompt: (st) => {
|
||||
const p = (st as RevState).phase;
|
||||
return p === "axisA" ? "cmd.revolve.axisA" : p === "axisB" ? "cmd.revolve.axisB" : p === "angle" ? "cmd.revolve.angle" : "cmd.revolve.pick";
|
||||
},
|
||||
accepts: (st) => ((st as RevState).phase === "angle" ? ["number"] : ["point"]),
|
||||
options: () => [],
|
||||
floorOnly: true,
|
||||
|
||||
init: (): RevState => ({ phase: "pick", profile: null, sourceId: null, a: null, b: null, cursor: null, lastPoint: null }),
|
||||
|
||||
onInput: (state, input, ctx): [CommandState, CommandResult] => {
|
||||
let s = state as RevState;
|
||||
if (s.phase === "done") return done();
|
||||
if (s.phase === "pick") {
|
||||
if (input.kind !== "point") return [s, { draft: null }];
|
||||
// Vorselektiertes Profil: der erste Punkt ist gleich der Achsenanfang.
|
||||
const pre = singleSelectedProfile(ctx.project, ctx.selection);
|
||||
if (pre) {
|
||||
s = { ...s, phase: "axisA", profile: pre, sourceId: pre.id };
|
||||
} else {
|
||||
const hit = pickProfileAt(ctx.project, ctx.level.id, input.point);
|
||||
if (!hit) return [s, { draft: null }];
|
||||
const ns: RevState = { ...s, phase: "axisA", profile: hit, sourceId: hit.id };
|
||||
return [ns, { draft: draft(ns, null) }];
|
||||
}
|
||||
}
|
||||
if (s.phase === "axisA") {
|
||||
if (input.kind !== "point") return [s, { draft: draft(s, s.cursor) }];
|
||||
const ns: RevState = { ...s, phase: "axisB", a: input.point, lastPoint: input.point };
|
||||
return [ns, { draft: draft(ns, input.point) }];
|
||||
}
|
||||
if (s.phase === "axisB") {
|
||||
if (input.kind !== "point" || !s.a || Math.hypot(input.point.x - s.a.x, input.point.y - s.a.y) < 1e-6) return [s, { draft: draft(s, s.cursor) }];
|
||||
const ns: RevState = { ...s, phase: "angle", b: input.point, lastPoint: input.point };
|
||||
return [ns, { draft: draft(ns, input.point) }];
|
||||
}
|
||||
// angle
|
||||
if (input.kind !== "number" || !(input.value > 0)) return [s, { draft: draft(s, s.cursor) }];
|
||||
return commit(s, Math.min(360, input.value), ctx);
|
||||
},
|
||||
|
||||
onMove: (state, point): [CommandState, CommandResult] => {
|
||||
const s = { ...(state as RevState), cursor: point };
|
||||
return [s, { draft: draft(s, point) }];
|
||||
},
|
||||
|
||||
// Enter beim Winkel: zuletzt benutzten Winkel übernehmen.
|
||||
onConfirm: (state, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as RevState;
|
||||
return s.phase === "angle" ? commit(s, lastAngle, ctx) : done();
|
||||
},
|
||||
onCancel: () => done(),
|
||||
};
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* [T7] `revolveCommand` (Profil + Achse + Winkel) und `loftCommand` (≥ 2 Profile + Höhe): beide legen
|
||||
* einen B-Rep-Körper (`ExtrudedSolid.brep`) an und entfernen die Quellprofile.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { revolveCommand } from "./revolve";
|
||||
import { loftCommand } from "./loft";
|
||||
import type { CommandContext, CmdInput, Project } from "../types";
|
||||
|
||||
const rect = (id: string, x: number, y: number, w: number, h: number) => ({
|
||||
id,
|
||||
type: "drawing2d" as const,
|
||||
levelId: "eg",
|
||||
categoryCode: "20",
|
||||
geom: { shape: "rect" as const, min: { x, y }, max: { x: x + w, y: y + h } },
|
||||
});
|
||||
|
||||
function project(): Project {
|
||||
return {
|
||||
id: "t",
|
||||
name: "T",
|
||||
lineStyles: [],
|
||||
hatches: [],
|
||||
components: [],
|
||||
wallTypes: [],
|
||||
drawingLevels: [{ id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }],
|
||||
layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }],
|
||||
walls: [],
|
||||
openings: [],
|
||||
ceilings: [],
|
||||
stairs: [],
|
||||
rooms: [],
|
||||
drawings2d: [rect("A", 0, 1, 2, 1), rect("B", 10, 0, 1, 1)],
|
||||
extrudedSolids: [],
|
||||
context: [],
|
||||
} as unknown as Project;
|
||||
}
|
||||
|
||||
function makeCtx(p: Project, drawingId: string | null = null): CommandContext {
|
||||
return {
|
||||
project: p,
|
||||
level: p.drawingLevels[0],
|
||||
defaultCategoryCode: "20",
|
||||
activeLineStyleId: "solid",
|
||||
activeWallTypeId: "aw",
|
||||
lastPoint: null,
|
||||
selection: { wallIds: [], drawingId },
|
||||
} as CommandContext;
|
||||
}
|
||||
|
||||
/** Spielt Eingaben ab; liefert das Projekt nach dem Commit (oder null). */
|
||||
function run(cmd: typeof revolveCommand, p: Project, inputs: Array<CmdInput | "confirm">, selected: string | null = null) {
|
||||
const ctx = makeCtx(p, selected);
|
||||
let state = cmd.init();
|
||||
let commit: ((p: Project) => Project) | undefined;
|
||||
for (const i of inputs) {
|
||||
const [ns, res] = i === "confirm" ? cmd.onConfirm(state, ctx) : cmd.onInput(state, i, ctx);
|
||||
state = ns;
|
||||
if (res.commit) commit = res.commit as typeof commit;
|
||||
}
|
||||
return commit ? commit(p) : null;
|
||||
}
|
||||
|
||||
const pt = (x: number, y: number): CmdInput => ({ kind: "point", point: { x, y } });
|
||||
|
||||
describe("revolveCommand", () => {
|
||||
it("Profil wählen, Achse (2 Punkte), Winkel → Rotationskörper, Quelle entfernt", () => {
|
||||
const next = run(revolveCommand, project(), [pt(1, 1), pt(-1, 0), pt(5, 0), { kind: "number", value: 180 }])!;
|
||||
expect(next.drawings2d.map((d) => d.id)).toEqual(["B"]);
|
||||
const s = next.extrudedSolids![0];
|
||||
expect(s.brep!.spec).toMatchObject({ kind: "transform", solid: { kind: "revolve", angleDeg: 180 } });
|
||||
expect(s.height).toBeCloseTo(4, 9); // Profil 1 … 2 m neben der Achse y=0 → r_max = 2
|
||||
});
|
||||
|
||||
it("Enter beim Winkel übernimmt den zuletzt benutzten; vorgewähltes Profil überspringt die Wahl", () => {
|
||||
run(revolveCommand, project(), [pt(1, 1), pt(-1, 0), pt(5, 0), { kind: "number", value: 90 }]);
|
||||
const next = run(revolveCommand, project(), [pt(-1, 0), pt(5, 0), "confirm"], "A")!;
|
||||
expect(next.extrudedSolids![0].brep!.spec).toMatchObject({ solid: { angleDeg: 90 } });
|
||||
});
|
||||
|
||||
it("Profil, das die Achse überquert, ergibt keinen Körper", () => {
|
||||
const next = run(revolveCommand, project(), [pt(1, 1), pt(-1, 1.5), pt(5, 1.5), "confirm"]);
|
||||
expect(next?.extrudedSolids ?? []).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("loftCommand", () => {
|
||||
it("zwei Profile wählen, Enter, Höhe → Loft-Körper, Quellen entfernt", () => {
|
||||
const next = run(loftCommand, project(), [pt(1, 1), pt(10.5, 0), "confirm", { kind: "number", value: 3 }])!;
|
||||
expect(next.drawings2d).toHaveLength(0);
|
||||
const s = next.extrudedSolids![0];
|
||||
expect(s.height).toBe(3);
|
||||
expect(s.brep!.spec).toMatchObject({ kind: "loft" });
|
||||
expect((s.brep!.spec as { sections: unknown[] }).sections).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("mit nur einem Profil bleibt Enter wirkungslos", () => {
|
||||
const next = run(loftCommand, project(), [pt(1, 1), "confirm", { kind: "number", value: 3 }]);
|
||||
expect(next?.extrudedSolids ?? []).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -53,6 +53,8 @@ import { copyCommand } from "./cmds/copy";
|
||||
import { arrayCommand } from "./cmds/array";
|
||||
import { offsetCommand } from "./cmds/offset";
|
||||
import { extrudeCommand } from "./cmds/extrude";
|
||||
import { revolveCommand } from "./cmds/revolve";
|
||||
import { loftCommand } from "./cmds/loft";
|
||||
import { trimCommand } from "./cmds/trim";
|
||||
import { breakCommand } from "./cmds/break";
|
||||
import { extendCommand } from "./cmds/extend";
|
||||
@@ -121,6 +123,8 @@ export const COMMANDS: Record<string, Command> = {
|
||||
array: arrayCommand,
|
||||
offset: offsetCommand,
|
||||
extrude: extrudeCommand,
|
||||
revolve: revolveCommand,
|
||||
loft: loftCommand,
|
||||
trim: trimCommand,
|
||||
break: breakCommand,
|
||||
extend: extendCommand,
|
||||
@@ -246,6 +250,9 @@ export const ALIASES: Record<string, string> = {
|
||||
feld: "array",
|
||||
o: "offset",
|
||||
ex: "extrude",
|
||||
rev: "revolve",
|
||||
rotation: "revolve",
|
||||
lf: "loft",
|
||||
tr: "trim",
|
||||
br: "break",
|
||||
unterbrechen: "break",
|
||||
|
||||
@@ -802,6 +802,7 @@ export const de = {
|
||||
"objinfo.stair.shape.L": "L-Treppe",
|
||||
"objinfo.stair.shape.spiral": "Wendel",
|
||||
"objinfo.stair.width": "Laufbreite",
|
||||
"objinfo.stair.column": "Mittelsäule (Radius)",
|
||||
"objinfo.stair.steps": "Stufenanzahl",
|
||||
"objinfo.stair.rise": "Steighöhe (gesamt)",
|
||||
"objinfo.stair.riser": "Steigungshöhe",
|
||||
@@ -1846,6 +1847,17 @@ export const de = {
|
||||
"cmd.offset.label": "Versatz",
|
||||
"cmd.offset.pick": "Kurve wählen:",
|
||||
"cmd.offset.side": "Seite oder Distanz:",
|
||||
"cmd.revolve.label": "Rotationskörper",
|
||||
"cmd.revolve.pick": "Geschlossenes Profil wählen:",
|
||||
"cmd.revolve.axisA": "Drehachse: Anfangspunkt:",
|
||||
"cmd.revolve.axisB": "Drehachse: Endpunkt:",
|
||||
"cmd.revolve.angle": "Drehwinkel (°, Enter = zuletzt):",
|
||||
"cmd.loft.label": "Loft",
|
||||
"cmd.loft.pick": "Profile der Reihe nach wählen (unten zuerst):",
|
||||
"cmd.loft.pickMore": "Weiteres Profil wählen oder Enter:",
|
||||
"cmd.loft.height": "Gesamthöhe:",
|
||||
"history.cmd.revolve": "Rotationskörper",
|
||||
"history.cmd.loft": "Loft",
|
||||
"cmd.extrude.label": "Extrudieren",
|
||||
"cmd.extrude.pick": "Geschlossenes Profil wählen:",
|
||||
"cmd.extrude.height": "Höhe:",
|
||||
@@ -2260,6 +2272,7 @@ export const de = {
|
||||
"mesh.import.upUncertain": "Achse unsicher, angenommen: {axis} oben (im Import-Dialog wählbar)",
|
||||
"mesh.import.dropped": "{n} ungültige oder entartete Flächen verworfen",
|
||||
"mesh.import.truncated": "abgebrochen: zu viele Dreiecke",
|
||||
"mesh.import.repaired": "repariert: {welded} Ecken verschweisst, {tris} entartete Dreiecke entfernt, {holes} Löcher geschlossen",
|
||||
"mesh.import.noFaces": "Die PLY-Datei enthält keine Flächen (Punktwolke): sie wird als Punktwolke geöffnet.",
|
||||
"mesh.import.missingExternal": "Zusätzliche Dateien fehlen: {list}. Wählen Sie sie zusammen mit dem Modell aus (oder ziehen Sie alle Dateien gemeinsam ins Fenster).",
|
||||
"mesh.importDialog.files": "Begleitdateien: {list}",
|
||||
@@ -2444,6 +2457,15 @@ export const de = {
|
||||
"siteRules.addLine.hint": "Eine Linie wählen; das Gebäude bleibt auf der Seite der Parzelle.",
|
||||
"siteRules.clearLines": "Alle Baulinien entfernen",
|
||||
"clash.none": "Keine Kollisionen gefunden.",
|
||||
"clash.run": "Prüfung starten",
|
||||
"clash.running": "Prüfung läuft …",
|
||||
"clash.clear": "Leeren",
|
||||
"clash.empty": "Keine Treffer. Die Prüfung vergleicht freie Körper und Importe mit Wänden, Decken und anderen Körpern.",
|
||||
"clash.kind.wall": "Wand",
|
||||
"clash.kind.slab": "Decke",
|
||||
"clash.kind.solid": "Körper",
|
||||
"clash.kind.mesh": "Import",
|
||||
"nav.clash": "Kollisionen",
|
||||
"clash.found": "Kollisionen gefunden",
|
||||
"clash.failed": "Kollisionsprüfung fehlgeschlagen",
|
||||
"about.title": "Über dossier",
|
||||
|
||||
@@ -799,6 +799,7 @@ export const en: Record<TranslationKey, string> = {
|
||||
"objinfo.stair.shape.L": "L-shaped",
|
||||
"objinfo.stair.shape.spiral": "Spiral",
|
||||
"objinfo.stair.width": "Run width",
|
||||
"objinfo.stair.column": "Centre column (radius)",
|
||||
"objinfo.stair.steps": "Step count",
|
||||
"objinfo.stair.rise": "Total rise",
|
||||
"objinfo.stair.riser": "Riser height",
|
||||
@@ -1834,6 +1835,17 @@ export const en: Record<TranslationKey, string> = {
|
||||
"cmd.offset.label": "Offset",
|
||||
"cmd.offset.pick": "Select curve:",
|
||||
"cmd.offset.side": "Side or distance:",
|
||||
"cmd.revolve.label": "Revolve",
|
||||
"cmd.revolve.pick": "Select closed profile:",
|
||||
"cmd.revolve.axisA": "Revolve axis: start point:",
|
||||
"cmd.revolve.axisB": "Revolve axis: end point:",
|
||||
"cmd.revolve.angle": "Revolve angle (°, Enter = last):",
|
||||
"cmd.loft.label": "Loft",
|
||||
"cmd.loft.pick": "Select profiles in order (bottom first):",
|
||||
"cmd.loft.pickMore": "Select another profile or Enter:",
|
||||
"cmd.loft.height": "Total height:",
|
||||
"history.cmd.revolve": "Revolve",
|
||||
"history.cmd.loft": "Loft",
|
||||
"cmd.extrude.label": "Extrude",
|
||||
"cmd.extrude.pick": "Select closed profile:",
|
||||
"cmd.extrude.height": "Height:",
|
||||
@@ -2210,6 +2222,7 @@ export const en: Record<TranslationKey, string> = {
|
||||
"mesh.import.upUncertain": "Axis uncertain, assumed: {axis} up (selectable in the import dialog)",
|
||||
"mesh.import.dropped": "{n} invalid or degenerate faces dropped",
|
||||
"mesh.import.truncated": "aborted: too many triangles",
|
||||
"mesh.import.repaired": "repaired: {welded} vertices welded, {tris} degenerate triangles removed, {holes} holes closed",
|
||||
"mesh.import.noFaces": "The PLY file has no faces (point cloud): opening it as a point cloud.",
|
||||
"mesh.import.missingExternal": "Additional files are missing: {list}. Select them together with the model (or drop all files into the window together).",
|
||||
"mesh.importDialog.files": "Companion files: {list}",
|
||||
@@ -2393,6 +2406,15 @@ export const en: Record<TranslationKey, string> = {
|
||||
"siteRules.addLine": "Building line from selection",
|
||||
"siteRules.addLine.hint": "Select a line; the building stays on the parcel side.",
|
||||
"siteRules.clearLines": "Remove all building lines",
|
||||
"clash.run": "Run check",
|
||||
"clash.running": "Checking …",
|
||||
"clash.clear": "Clear",
|
||||
"clash.empty": "No results. The check compares free solids and imports with walls, slabs and other solids.",
|
||||
"clash.kind.wall": "Wall",
|
||||
"clash.kind.slab": "Slab",
|
||||
"clash.kind.solid": "Solid",
|
||||
"clash.kind.mesh": "Import",
|
||||
"nav.clash": "Clashes",
|
||||
"clash.none": "No clashes found.",
|
||||
"clash.found": "Clashes found",
|
||||
"clash.failed": "Clash detection failed",
|
||||
|
||||
@@ -192,6 +192,13 @@ describe("Mesh-Import: Abbildung auf Kontext-Meshes", () => {
|
||||
expect(text).toContain("mesh.import.done");
|
||||
expect(text).toContain("mesh.import.up");
|
||||
});
|
||||
|
||||
it("Bericht nennt die Reparatur ([T5]) nur, wenn etwas repariert wurde", () => {
|
||||
const base = { format: "stl" as const, up: "z" as const, upAuto: false, upCertain: true, unitScale: 1, triangles: 12, degenerate: 0, badFaces: 0, truncated: false, warnings: [] as string[], objects: 1 };
|
||||
const tr = (k: string, v?: Record<string, string | number>) => `${k}${v ? JSON.stringify(v) : ""}`;
|
||||
expect(formatMeshReport({ ...base, repaired: { welded: 0, degenerate: 0, holes: 0 } }, tr)).not.toContain("repaired");
|
||||
expect(formatMeshReport({ ...base, repaired: { welded: 28, degenerate: 1, holes: 2 } }, tr)).toContain('mesh.import.repaired{"welded":28,"tris":1,"holes":2}');
|
||||
});
|
||||
});
|
||||
|
||||
describe("Mesh-Import: Fehler", () => {
|
||||
|
||||
@@ -64,6 +64,8 @@ export interface MeshImportReport {
|
||||
truncated: boolean;
|
||||
warnings: string[];
|
||||
objects: number;
|
||||
/** Reparatur beim Import ([T5]): zusammengelegte Ecken, entfernte entartete Dreiecke, geschlossene Löcher. */
|
||||
repaired?: { welded: number; degenerate: number; holes: number };
|
||||
}
|
||||
|
||||
/** Rohergebnis aus Rust: Zahlenpuffer + Zeichenketten. */
|
||||
@@ -198,7 +200,7 @@ export async function readMesh(bytes: Uint8Array, name: string, opts?: MeshReadO
|
||||
export function formatMeshReport(
|
||||
r: MeshImportReport,
|
||||
tr: (
|
||||
key: "mesh.import.done" | "mesh.import.up" | "mesh.import.upUncertain" | "mesh.import.dropped" | "mesh.import.truncated",
|
||||
key: "mesh.import.done" | "mesh.import.up" | "mesh.import.upUncertain" | "mesh.import.dropped" | "mesh.import.truncated" | "mesh.import.repaired",
|
||||
vars?: Record<string, string | number>,
|
||||
) => string,
|
||||
): string {
|
||||
@@ -206,6 +208,8 @@ export function formatMeshReport(
|
||||
if (r.upAuto) parts.push(tr(r.upCertain ? "mesh.import.up" : "mesh.import.upUncertain", { axis: r.up.toUpperCase() }));
|
||||
const dropped = r.degenerate + r.badFaces;
|
||||
if (dropped) parts.push(tr("mesh.import.dropped", { n: dropped }));
|
||||
const fixed = r.repaired ? r.repaired.degenerate + r.repaired.holes : 0;
|
||||
if (r.repaired && (r.repaired.welded || fixed)) parts.push(tr("mesh.import.repaired", { welded: r.repaired.welded, tris: r.repaired.degenerate, holes: r.repaired.holes }));
|
||||
if (r.truncated) parts.push(tr("mesh.import.truncated"));
|
||||
return parts.join(" · ");
|
||||
}
|
||||
@@ -2874,6 +2874,11 @@ export type Stair = {
|
||||
* Dreieck als SIA-Vollpfeil). Fehlt sie, gilt "line".
|
||||
*/
|
||||
arrowStyle?: "line" | "filled";
|
||||
/**
|
||||
* Nur Wendel: Radius (Meter) der Mittelsäule (Spindel) im Zentrum. Fehlt er oder ist er
|
||||
* ≤ 0, gibt es keine Säule.
|
||||
*/
|
||||
centerColumn?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// Kollisionen ([T8]): Liste der Treffer der letzten Prüfung. Klick wählt beide beteiligten Bauteile
|
||||
// (Auswahl-Umriss im 3D) und fährt die 3D-Kamera auf die Durchdringung; im 3D sind alle Treffer als
|
||||
// rote Hüllquader markiert (`clashHighlightLines`, `views/viewportContent.tsx`).
|
||||
|
||||
import { t } from "../i18n";
|
||||
import { getState } from "../state/appStore";
|
||||
import { clashSelection, type Clash } from "../analysis/clash";
|
||||
import { focusCamera, viewportAvailable } from "../viewport/cameraBridge";
|
||||
import { runClashAndStore, setClashSession, useClashSession } from "./clashSession";
|
||||
|
||||
/** Klick auf einen Treffer: Bauteile wählen, Kamera auf die Durchdringung. */
|
||||
export function focusClash(c: Clash, index: number): void {
|
||||
const s = getState();
|
||||
const sel = clashSelection(c);
|
||||
s.clearSelection();
|
||||
s.setSelectedWallIds(sel.wallIds);
|
||||
s.setSelectedCeilingIds(sel.ceilingIds);
|
||||
s.setSelectedExtrudedSolidIds(sel.extrudedSolidIds);
|
||||
s.setSelectedContextObjectIds(sel.contextObjectIds);
|
||||
setClashSession({ selected: index });
|
||||
const radius = Math.hypot(c.max[0] - c.min[0], c.max[1] - c.min[1], c.max[2] - c.min[2]) / 2;
|
||||
if (viewportAvailable()) focusCamera(c.center, radius);
|
||||
}
|
||||
|
||||
const itemText = (it: Clash["a"]) => `${t(`clash.kind.${it.kind}`)} ${it.id}`;
|
||||
|
||||
export function ClashPanel() {
|
||||
const session = useClashSession();
|
||||
return (
|
||||
<div className="bcf-panel">
|
||||
<div className="bcf-bar">
|
||||
<button type="button" className="bcf-btn" disabled={session.running} onClick={() => void runClashAndStore()}>
|
||||
{session.running ? t("clash.running") : t("clash.run")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="bcf-btn"
|
||||
disabled={session.clashes.length === 0}
|
||||
onClick={() => setClashSession({ clashes: [], selected: null })}
|
||||
>
|
||||
{t("clash.clear")}
|
||||
</button>
|
||||
</div>
|
||||
{session.clashes.length === 0 && <div className="bcf-empty">{t("clash.empty")}</div>}
|
||||
<ul className="bcf-list">
|
||||
{session.clashes.map((c, k) => (
|
||||
<li key={`${c.a.id}|${c.b.id}`}>
|
||||
<button type="button" className={`bcf-topic${k === session.selected ? " is-active" : ""}`} onClick={() => focusClash(c, k)}>
|
||||
<span className="bcf-status">{`K${k + 1}`}</span>
|
||||
<span className="bcf-topic-title">{`${itemText(c.a)} ↔ ${itemText(c.b)}`}</span>
|
||||
{c.volume !== null && <span className="bcf-count">{`${c.volume.toFixed(3)} m³`}</span>}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1461,6 +1461,13 @@ export function StairSection({
|
||||
value={stair.width}
|
||||
onCommit={(v) => host.onSetStairWidth(v)}
|
||||
/>
|
||||
{stair.shape === "spiral" && (
|
||||
<DimensionField
|
||||
label={t("objinfo.stair.column")}
|
||||
value={stair.centerColumn ?? 0}
|
||||
onCommit={(v) => host.onSetStairColumn(v)}
|
||||
/>
|
||||
)}
|
||||
<DimensionField
|
||||
label={t("objinfo.stair.steps")}
|
||||
value={stair.stepCount}
|
||||
|
||||
@@ -355,7 +355,7 @@ const TOOLS_2D: ToolId[] = [
|
||||
"image",
|
||||
];
|
||||
const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"];
|
||||
const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "solid", "solidbool", "sectionline", "viewline", "autodim", "excavation"];
|
||||
const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "revolve", "loft", "solid", "solidbool", "sectionline", "viewline", "autodim", "excavation"];
|
||||
const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "break", "extend", "fillet", "chamfer", "join", "defblock", "measure"];
|
||||
|
||||
type ToolsView = "list" | "icons";
|
||||
|
||||
@@ -26,6 +26,7 @@ import { ElementTreePanel, ElementsTabIcon } from "./ElementTreePanel";
|
||||
import { ViewSnapshotsPanel, ViewSnapshotsTabIcon } from "./ViewSnapshotsPanel";
|
||||
import { LayoutsPanel, LayoutsTabIcon } from "./LayoutsPanel";
|
||||
import { BcfPanel } from "./BcfPanel";
|
||||
import { ClashPanel } from "./ClashPanel";
|
||||
import { HistoryPanel } from "./HistoryPanel";
|
||||
import {
|
||||
ToolsTabIcon,
|
||||
@@ -52,6 +53,7 @@ export const BUILTIN_PANEL_IDS = {
|
||||
viewSnapshots: "view-snapshots",
|
||||
layouts: "layouts",
|
||||
bcf: "bcf",
|
||||
clash: "clash",
|
||||
history: "history",
|
||||
} as const;
|
||||
|
||||
@@ -162,6 +164,16 @@ registerPanel({
|
||||
render: () => <BcfPanel />,
|
||||
});
|
||||
|
||||
// Kollisionen ([T8]) — Treffer der Kollisionsprüfung, Klick zoomt im 3D auf die Durchdringung. Nicht im
|
||||
// Standard-Layout; öffnet sich beim Prüflauf („Modell > Kollisionsprüfung") bzw. über „Fenster > Panels".
|
||||
registerPanel({
|
||||
id: BUILTIN_PANEL_IDS.clash,
|
||||
title: "nav.clash",
|
||||
icon: <BcfTabIcon />,
|
||||
hasDisplayMode: false,
|
||||
render: () => <ClashPanel />,
|
||||
});
|
||||
|
||||
// Verlauf ([84]) — Undo-Schritte als Liste, Klick springt zum Schritt. Nicht im Standard-Layout,
|
||||
// erreichbar über „Bearbeiten > Verlauf" bzw. „Fenster > Panels".
|
||||
registerPanel({
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// Sitzungszustand der Kollisionsprüfung ([T8]): die Ergebnisse der letzten Prüfung leben ausserhalb des
|
||||
// Projekts (Marker im Grundriss kommen weiterhin als Zeichnungs-Elemente), damit Liste (ClashPanel) und
|
||||
// 3D-Hervorhebung (viewportContent) dieselben Treffer zeigen. Kleiner Modul-Speicher wie `bcfSession`.
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { clashMarkerOps, runClashCheck, type Clash } from "../analysis/clash";
|
||||
import { t } from "../i18n";
|
||||
import { getState } from "../state/appStore";
|
||||
|
||||
export interface ClashSession {
|
||||
clashes: Clash[];
|
||||
/** Index des gewählten Treffers (Liste/Zoom) oder null. */
|
||||
selected: number | null;
|
||||
/** Prüfung läuft. */
|
||||
running: boolean;
|
||||
}
|
||||
|
||||
let state: ClashSession = { clashes: [], selected: null, running: false };
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
export const getClashSession = (): ClashSession => state;
|
||||
|
||||
export function setClashSession(patch: Partial<ClashSession>): void {
|
||||
state = { ...state, ...patch };
|
||||
for (const l of listeners) l();
|
||||
}
|
||||
|
||||
export function useClashSession(): ClashSession {
|
||||
return useSyncExternalStore(
|
||||
(cb) => {
|
||||
listeners.add(cb);
|
||||
return () => listeners.delete(cb);
|
||||
},
|
||||
getClashSession,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüfung ausführen: Ergebnis in die Sitzung (Liste + 3D-Hervorhebung), Marker in den Grundriss, Meldung.
|
||||
* Läuft auf dem aktuellen Projektstand des Stores.
|
||||
*/
|
||||
export async function runClashAndStore(): Promise<void> {
|
||||
if (state.running) return;
|
||||
const st = getState();
|
||||
setClashSession({ running: true });
|
||||
try {
|
||||
const clashes = await runClashCheck(st.project);
|
||||
st.applyChange((p) => clashMarkerOps(p, clashes, st.activeCategoryCode));
|
||||
setClashSession({ clashes, selected: null, running: false });
|
||||
// window.alert ist im Tauri-WKWebView wirkungslos → Toast.
|
||||
st.notify(
|
||||
clashes.length === 0
|
||||
? t("clash.none")
|
||||
: `${t("clash.found")}: ${clashes.length} — ` +
|
||||
clashes
|
||||
.slice(0, 5)
|
||||
.map((c, k) => `K${k + 1} ${c.a.kind}↔${c.b.kind}${c.volume !== null ? ` ${c.volume.toFixed(3)} m³` : ""}`)
|
||||
.join(", "),
|
||||
clashes.length === 0 ? "info" : "warning",
|
||||
);
|
||||
} catch (err) {
|
||||
setClashSession({ running: false });
|
||||
st.notify(`${t("clash.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error");
|
||||
}
|
||||
}
|
||||
@@ -530,6 +530,8 @@ export interface PanelHostValue {
|
||||
onSetStairArrowStyle: (style: "line" | "filled") => void;
|
||||
/** Setzt den Referenzpunkt der Laufbreite (links/mitte/rechts). */
|
||||
onSetStairReferenz: (referenz: "links" | "mitte" | "rechts") => void;
|
||||
/** Radius der Mittelsäule (Wendel) in Metern; ≤ 0 entfernt sie. */
|
||||
onSetStairColumn: (radius: number) => void;
|
||||
/** Weist der Treppe einen Treppentyp (Bibliothek) zu; "" löst die Zuweisung. */
|
||||
onSetStairType: (typeId: string) => void;
|
||||
|
||||
|
||||
@@ -259,6 +259,8 @@ export interface StairInfo {
|
||||
arrowStyle?: "line" | "filled";
|
||||
/** Referenzpunkt der Laufbreite (links/mitte/rechts). Fehlt → "mitte". */
|
||||
referenz?: "links" | "mitte" | "rechts";
|
||||
/** Nur Wendel: Radius der Mittelsäule (Meter); fehlt → keine Säule. */
|
||||
centerColumn?: number;
|
||||
/** Zugewiesener Treppentyp (Bibliothek, `Stair.typeId`) oder undefined. */
|
||||
typeId?: string;
|
||||
/** Geschoss, dem die Treppe zugeordnet ist. */
|
||||
|
||||
@@ -974,6 +974,10 @@ export function usePanelHostBase(opts: {
|
||||
onSetStairArrowStyle: (arrowStyle) => {
|
||||
if (selection?.kind === "stair") updateStair(selection.id, { arrowStyle });
|
||||
},
|
||||
onSetStairColumn: (radius) => {
|
||||
if (selection?.kind === "stair")
|
||||
updateStair(selection.id, { centerColumn: radius > 0 ? radius : undefined });
|
||||
},
|
||||
onSetStairReferenz: (referenz) => {
|
||||
if (selection?.kind === "stair") updateStair(selection.id, { referenz });
|
||||
},
|
||||
|
||||
@@ -234,6 +234,24 @@ export function CommandIcon({ name }: { name: string }) {
|
||||
<path d="M9.5 12.5 L12.5 9.5 L12.5 4.5" />
|
||||
</svg>
|
||||
);
|
||||
case "revolve":
|
||||
// Rotationskörper: Profil neben einer Achse, Drehbogen.
|
||||
return (
|
||||
<svg {...common}>
|
||||
<path d="M8 2.5 V13.5" strokeDasharray="1.4 1.2" />
|
||||
<path d="M9.5 4.5 H13 V11.5 H9.5 Z" />
|
||||
<path d="M6.5 4.5 H3 V11.5 H6.5" />
|
||||
</svg>
|
||||
);
|
||||
case "loft":
|
||||
// Loft: grosses Profil unten, kleines oben, verbunden.
|
||||
return (
|
||||
<svg {...common}>
|
||||
<rect x="2.5" y="9.5" width="11" height="3" />
|
||||
<rect x="5.5" y="3.5" width="5" height="2" />
|
||||
<path d="M2.5 9.5 L5.5 5.5 M13.5 9.5 L10.5 5.5" />
|
||||
</svg>
|
||||
);
|
||||
case "voidbox":
|
||||
// Durchbruch: Wand mit gestricheltem, durchkreuztem Ausschnitt.
|
||||
return (
|
||||
|
||||
@@ -5,6 +5,8 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import { projectToModel3d, sampleProject } from "../core";
|
||||
import {
|
||||
FOV_Y,
|
||||
focusCamera,
|
||||
focusedCamera,
|
||||
camera3dFromViewCamera,
|
||||
captureSnapshot,
|
||||
getCamera,
|
||||
@@ -153,6 +155,25 @@ describe("Schnittebene", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Fokus auf einen Punkt (Kollisionsliste)", () => {
|
||||
it("zentriert das Ziel auf den Modellpunkt, behält die Blickrichtung, Abstand folgt dem Radius", () => {
|
||||
const cam = orbitCamera({ yaw: 0.4, pitch: 0.3, dist: 15, target: [1, 2, 3], ortho: false, orthoHalfHeight: 8 });
|
||||
const f = focusedCamera(cam, [4, 5, 6], 2);
|
||||
close(f.target, modelToWorld([4, 5, 6]));
|
||||
const d = (c: Camera3d) => {
|
||||
const v = [c.target[0] - c.eye[0], c.target[1] - c.eye[1], c.target[2] - c.eye[2]];
|
||||
const l = Math.hypot(...v);
|
||||
return v.map((x) => x / l);
|
||||
};
|
||||
close(d(f), d(cam));
|
||||
const near = Math.hypot(...f.target.map((t, i) => t - f.eye[i]));
|
||||
expect(near).toBeGreaterThan(2);
|
||||
expect(near).toBeLessThan(15);
|
||||
const ortho = focusedCamera({ ...cam, perspective: false, orthoHalfHeight: 8 }, [0, 0, 0], 2);
|
||||
expect(ortho.orthoHalfHeight).toBeLessThan(8);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Registrierung", () => {
|
||||
function fakeViewport() {
|
||||
const state = { cam: orbitCamera({ yaw: 0.4, pitch: 0.3, dist: 15, target: [1, 2, 3], ortho: false, orthoHalfHeight: 8 }), written: null as Camera3d | null, section: undefined as unknown };
|
||||
@@ -181,6 +202,14 @@ describe("Registrierung", () => {
|
||||
expect(setCamera(vc)).toBe(false);
|
||||
});
|
||||
|
||||
it("focusCamera schreibt die fokussierte Kamera in den Viewport (false ohne Viewport)", () => {
|
||||
expect(focusCamera([1, 2, 3], 1)).toBe(false);
|
||||
const { state, a } = fakeViewport();
|
||||
registerViewportCamera(a);
|
||||
expect(focusCamera([5, 6, 7], 1)).toBe(true);
|
||||
close(state.written!.target, modelToWorld([5, 6, 7]));
|
||||
});
|
||||
|
||||
it("getCamera → setCamera am angemeldeten Viewport lässt die Kamera unverändert", () => {
|
||||
const { state, a } = fakeViewport();
|
||||
registerViewportCamera(a);
|
||||
|
||||
@@ -257,6 +257,29 @@ export function setCamera(cam: ViewCamera, opts: { animate?: boolean } = {}): bo
|
||||
return c3 ? api.write(c3, opts.animate === true) : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kamera, die einen Modellpunkt (x, y, Höhe) ins Ziel nimmt: gleiche Blickrichtung, Abstand so, dass eine
|
||||
* Kugel vom Radius `radius` (Meter) bequem ins Bild passt; orthografisch schrumpft die Sichthöhe.
|
||||
*/
|
||||
export function focusedCamera(cam: Camera3d, centerModel: readonly number[], radius: number): Camera3d {
|
||||
const target = modelToWorld(centerModel);
|
||||
const d = norm(sub(cam.target, cam.eye)) ?? ([0, 0, -1] as V3);
|
||||
const r = Math.max(radius, 0.5);
|
||||
const dist = Math.max((r * 2.2) / Math.tan((cam.fovY || FOV_Y) / 2), 1.5);
|
||||
return {
|
||||
...cam,
|
||||
target,
|
||||
eye: [target[0] - d[0] * dist, target[1] - d[1] * dist, target[2] - d[2] * dist],
|
||||
orthoHalfHeight: cam.perspective ? cam.orthoHalfHeight : r * 2.2,
|
||||
};
|
||||
}
|
||||
|
||||
/** Fokus der Live-Kamera auf einen Modellpunkt; `false` ohne Viewport. */
|
||||
export function focusCamera(centerModel: readonly number[], radius: number, opts: { animate?: boolean } = {}): boolean {
|
||||
const cur = api?.read();
|
||||
return api && cur ? api.write(focusedCamera(cur.camera, centerModel, radius), opts.animate !== false) : false;
|
||||
}
|
||||
|
||||
/** PNG des aktuellen 3D-Bildes, oder null (kein Viewport, leeres/nicht lesbares Bild). */
|
||||
export async function captureSnapshot(opts: { maxEdge?: number } = {}): Promise<Uint8Array | null> {
|
||||
if (!api) return null;
|
||||
|
||||
@@ -37,6 +37,8 @@ import { unitsForLevel } from "../tools/displayUnits";
|
||||
import { setSheetOwnerOutlines, setSheetSnapSegments, snapSegmentsFromPrimitives } from "../tools/sheetSnapGeometry";
|
||||
import { pushNativeScene, pushNativeWalls } from "./plan/nativeSync";
|
||||
import { selectionHighlightLines } from "../core";
|
||||
import { clashHighlightLines } from "../analysis/clash";
|
||||
import { useClashSession } from "../panels/clashSession";
|
||||
import { applyGroupDimmingToPlan } from "../state/groupActions";
|
||||
import { PlanView } from "./plan/PlanView";
|
||||
import type {
|
||||
@@ -61,6 +63,8 @@ import type { DetailLevel, RenderMode, View3d, ViewType } from "../model/viewTyp
|
||||
* grauen Wand-/Deckenton, dem hellen Hidden-Line-Weiss und dem Bodenraster ab.
|
||||
*/
|
||||
const HIGHLIGHT_RGB: [number, number, number] = [1.0, 0.5, 0.1];
|
||||
/** Rot der Kollisions-Hüllquader im 3D ([T8]). */
|
||||
const CLASH_RGB: [number, number, number] = [0.88, 0.14, 0.16];
|
||||
|
||||
/** Hauptinhalt — abhängig von der aktiven Zeichnungsebene und dem Ansichtstyp. */
|
||||
export function Content({
|
||||
@@ -285,7 +289,8 @@ export function Content({
|
||||
// im WASM-Zweig (Viewport3D reicht sie nur dort an Wasm3DViewport durch);
|
||||
// die three.js-Sicht hebt die Auswahl weiterhin über ihr eigenes Material
|
||||
// hervor. Leere Auswahl → null (kein Highlight).
|
||||
const highlightLines = useMemo(
|
||||
const clashes = useClashSession().clashes;
|
||||
const selectionLines = useMemo(
|
||||
() =>
|
||||
selectedWallIds.length === 0 &&
|
||||
selectedCeilingIds.length === 0 &&
|
||||
@@ -314,6 +319,16 @@ export function Content({
|
||||
selectedContextObjectIds,
|
||||
],
|
||||
);
|
||||
// Kollisionen der letzten Prüfung: rote Hüllquader zusätzlich zur Auswahl-Hervorhebung.
|
||||
const highlightLines = useMemo(() => {
|
||||
if (clashes.length === 0) return selectionLines;
|
||||
const clashLines = clashHighlightLines(clashes, CLASH_RGB);
|
||||
if (!selectionLines) return clashLines;
|
||||
const merged = new Float32Array(selectionLines.length + clashLines.length);
|
||||
merged.set(selectionLines, 0);
|
||||
merged.set(clashLines, selectionLines.length);
|
||||
return merged;
|
||||
}, [selectionLines, clashes]);
|
||||
|
||||
if (level.kind === "section" || level.kind === "elevation") {
|
||||
return (
|
||||
|
||||
Reference in new issue
Block a user