[K4] Zeichenbefehle im Kern: Elemente, Vorschauen, Gruppen-Zuordnung

Alle Erzeuge-Befehle bauen ihre Elemente im Kern: cmd_create.rs (Wand, Decke,
Raum, Treppe, Öffnung, Dach, Stütze, Extrusion), cmd_draw.rs (2D-Formen,
Texte, Bemassung, autodim), cmd_solid.rs (solid, solidbool, voidbox, terrain,
Deckenöffnung, Dachhof, Schnittlinie). Vorschauen über doc_create_preview(_again)
ohne JSON je Mausschritt, Abfragen über doc_create_query; Gruppen-Zuordnung als
`group` im Request ersetzt activeGroupOps. TS hält nur die Zustandsautomaten
(commands/createCore.ts). Ersetzte TS-Geometrie und alte Werkzeug-Commits in
tools/tools.ts gelöscht. Gleichheit alt/neu mit zeitweiligen Zufallstests
geprüft (s. TODO.md). Die drei Gruppen hängen über den gemeinsamen Dispatcher
zusammen und sind deshalb ein Commit.
This commit is contained in:
Claude committed 2026-10-29 15:21:04 +00:00
1 parent 23993e9607
commit 61263efe13
92 files changed
+4169 -4744

No files matched your search

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+600
View File
@@ -0,0 +1,600 @@
//! Körper, Gelände und Sonderbefehle im Kern ([K4] S3, vorher `commands/cmds/{solid,solidbool,voidbox,
//! terrain,ceilingOpening,roofHole,sectionline}.ts`): Grundkörper (B-Rep-Beschreibung für truck),
//! Boolesche Körper, Aussparungs-Quader, Gelände-TIN aus Höhenlinien, Decken-Aussparung, Dach-Hof und
//! Schnitt-/Ansichtslinie — Ops, Vorschau und Treffer. Dazu die B-Rep-Beschreibung eines Körpers
//! (`extrudedSolidSpec`, auch für 3D, Schnitt und STEP) und das Gelände aus Höhenlinien
//! (`generateTerrainFromContours`, auch für das Lage-Panel). Einstieg über `cmd_create`.
use crate::cmd_create::{add_op, circle_pts, find, n_of, obj, opt_p, p_of, pts_of, pv, pvs, rect_corners, s, s_of, Ctx, Preview, V};
use crate::cmd_transform::{IdGen, Shapes};
use crate::grips::{arr, field, js_num, num_of, num_or, truthy, with, xy};
use crate::jsmath::hypot2;
use crate::jsnum;
use crate::ops::{id_of, Op};
use serde_json::{json, Map, Value};
fn fixed2(x: f64) -> String {
crate::js_fmt::to_fixed(x, 2)
}
fn level_of(e: &Value) -> Option<&str> {
field(e, "levelId").and_then(Value::as_str)
}
// ═════════════════════════════════════════════════════════════════════════════
// B-Rep-Beschreibung eines Körpers (`extrudedSolidSpec`)
// ═════════════════════════════════════════════════════════════════════════════
/// B-Rep-Beschreibung (`SolidSpec`) eines Körpers mit UK auf Geschoss-Höhe `floor_z` (+ `baseOffset`);
/// `None`, wenn truck dafür keine Beschreibung hat (Pyramide, entartet).
pub fn extruded_solid_spec(solid: &Value, floor_z: f64) -> Option<Value> {
let base_z = floor_z + num_or(field(solid, "baseOffset"), 0.0);
let points = arr(field(solid, "points"));
if let Some(brep) = field(solid, "brep").filter(|b| truthy(Some(b))) {
let (dx, dy) = match points.first() {
Some(p0) => {
let (o, p) = (xy(field(brep, "origin").unwrap_or(&Value::Null)), xy(p0));
(p.0 - o.0, p.1 - o.1)
}
None => (0.0, 0.0),
};
let spec = field(brep, "spec").cloned().unwrap_or(Value::Null);
return Some(obj(vec![("kind", s("translate")), ("v", json!([js_num(dx), js_num(dy), js_num(base_z)])), ("solid", spec)]));
}
let height = num_of(field(solid, "height"));
if points.len() < 3 || height <= 0.0 {
return None;
}
let taper = jsnum::min(1.0, jsnum::max(0.0, num_or(field(solid, "taper"), 0.0)));
let circle = field(solid, "circle").filter(|c| truthy(Some(c)));
if let Some(c) = circle {
if taper < 1e-6 || taper >= 1.0 - 1e-6 {
let ctr = xy(field(c, "center").unwrap_or(&Value::Null));
let kind = if taper < 1e-6 { "cylinder" } else { "cone" };
return Some(obj(vec![
("kind", s(kind)),
("cx", js_num(ctr.0)),
("cy", js_num(ctr.1)),
("z0", js_num(base_z)),
("r", js_num(num_of(field(c, "r")))),
("height", js_num(height)),
]));
}
}
let pts: Vec<V> = points.iter().map(xy).collect();
let flat = |ps: &[V]| Value::Array(ps.iter().flat_map(|p| [js_num(p.0), js_num(p.1)]).collect());
if taper < 1e-6 {
let mut f = vec![("kind", s("extrude")), ("points", flat(&pts)), ("height", js_num(height)), ("z0", js_num(base_z))];
let cr = num_or(field(solid, "cornerRadius"), 0.0);
if cr > 0.0 {
f.push(("cornerRadius", field(solid, "cornerRadius").cloned().unwrap_or(Value::Null)));
}
let ch = num_or(field(solid, "chamfer"), 0.0);
if ch > 0.0 {
f.push(("chamfer", field(solid, "chamfer").cloned().unwrap_or(Value::Null)));
}
return Some(obj(f));
}
if taper < 1.0 - 1e-6 {
let n = pts.len() as f64;
let cx = pts.iter().fold(0.0, |a, p| a + p.0) / n;
let cy = pts.iter().fold(0.0, |a, p| a + p.1) / n;
let top: Vec<V> = pts.iter().map(|p| (cx + (p.0 - cx) * (1.0 - taper), cy + (p.1 - cy) * (1.0 - taper))).collect();
return Some(obj(vec![
("kind", s("loft")),
(
"sections",
Value::Array(vec![
obj(vec![("z", js_num(base_z)), ("points", flat(&pts))]),
obj(vec![("z", js_num(base_z + height)), ("points", flat(&top))]),
]),
),
]));
}
None
}
// ═════════════════════════════════════════════════════════════════════════════
// Grundkörper, Boolesche Körper, Aussparung
// ═════════════════════════════════════════════════════════════════════════════
/// Grundkörper aus den Eingaben (`solidFromInputs`): Grundriss-Punkte, Höhe, B-Rep-Beschreibung, Label.
pub fn solid_from_inputs(shape: &str, p0: V, p1: Option<V>, nums: &[f64]) -> Option<(Vec<V>, f64, Value, String)> {
let num = |i: usize| nums.get(i).copied().unwrap_or(f64::NAN);
let ok = |x: f64| x > 1e-6;
match shape {
"sphere" => {
let r = num(0);
ok(r).then(|| {
(circle_pts(p0, r, 48), 2.0 * r, json!({ "kind": "sphere", "center": [js_num(p0.0), js_num(p0.1), js_num(r)], "r": js_num(r) }), format!("Kugel r={}", fixed2(r)))
})
}
"cylinder" | "cone" => {
let (r, h) = (num(0), num(1));
(ok(r) && ok(h)).then(|| {
let label = format!("{} r={} h={}", if shape == "cone" { "Kegel" } else { "Zylinder" }, fixed2(r), fixed2(h));
let spec = obj(vec![("kind", s(shape)), ("cx", js_num(p0.0)), ("cy", js_num(p0.1)), ("z0", js_num(0.0)), ("r", js_num(r)), ("height", js_num(h))]);
(circle_pts(p0, r, 48), h, spec, label)
})
}
"frustum" => {
let (r, rt, h) = (num(0), num(1), num(2));
(ok(r) && ok(rt) && ok(h)).then(|| {
let profile: Vec<Value> = [0.0, 0.0, r, 0.0, rt, h, 0.0, h].iter().map(|x| js_num(*x)).collect();
let spec = obj(vec![("kind", s("revolve")), ("cx", js_num(p0.0)), ("cy", js_num(p0.1)), ("profile", Value::Array(profile))]);
(circle_pts(p0, jsnum::max(r, rt), 48), h, spec, format!("Kegelstumpf r={}/{} h={}", fixed2(r), fixed2(rt), fixed2(h)))
})
}
"torus" => {
let (major, minor) = (num(0), num(1));
(ok(minor) && major > minor).then(|| {
let spec = json!({ "kind": "torus", "center": [js_num(p0.0), js_num(p0.1), js_num(minor)], "major": js_num(major), "minor": js_num(minor) });
(circle_pts(p0, major + minor, 48), 2.0 * minor, spec, format!("Torus R={} r={}", fixed2(major), fixed2(minor)))
})
}
"cuboid" => {
let h = num(0);
let p1 = p1?;
if !ok(h) {
return None;
}
let pts = rect_corners(p0, p1);
let (w, d) = ((p1.0 - p0.0).abs(), (p1.1 - p0.1).abs());
if w < 1e-6 || d < 1e-6 {
return None;
}
let spec = json!({ "kind": "cuboid", "min": [js_num(pts[0].0), js_num(pts[0].1), 0], "max": [js_num(pts[2].0), js_num(pts[2].1), js_num(h)] });
Some((pts.to_vec(), h, spec, format!("Quader {}×{}×{}", fixed2(w), fixed2(d), fixed2(h))))
}
_ => None,
}
}
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 {
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))])),
]);
add_op("extrudedSolids", vec![solid])
}
/// Grundkörper-Vorschau: `pts = [p0, p1?, Cursor?]` (`p1`/`cursor` Flags), `step`, `nums`.
fn solid_preview(v: &Value, pts: &[V], out: &mut Shapes) {
let Some(p0) = pts.first().copied() else { return };
let mut rest = pts[1..].iter().copied();
let p1 = if truthy(v.get("p1")) { rest.next() } else { None };
let cur = if truthy(v.get("cursor")) { rest.next().unwrap_or(p0) } else { p0 };
let nums: Vec<f64> = arr(v.get("nums")).iter().map(|x| num_of(Some(x))).collect();
let num = |i: usize, d: f64| nums.get(i).copied().unwrap_or(d);
let dist = hypot2(cur.0 - p0.0, cur.1 - p0.1);
let step = s_of(v, "step");
let shape = s_of(v, "shape");
if shape == "cuboid" {
out.poly(&rect_corners(p0, p1.unwrap_or(cur)));
return;
}
let r = if step == "radius" || step == "major" { dist } else { num(0, dist) };
if shape == "frustum" && step != "radius" {
out.poly(&circle_pts(p0, jsnum::max(if step == "topRadius" { dist } else { num(1, dist) }, 0.01), 48));
}
out.poly(&circle_pts(p0, jsnum::max(r, 0.01), 48));
if shape == "torus" && step == "minor" {
out.poly(&circle_pts(p0, num(0, 0.0) + dist, 48));
}
}
/// Punkt im Polygon (Strahl-Test, `|| 1e-12` gegen waagrechte Kanten).
fn point_in_polygon(p: V, poly: &[V]) -> bool {
let mut inside = false;
let n = poly.len();
let mut j = n.wrapping_sub(1);
for i in 0..n {
let (a, b) = (poly[i], poly[j]);
let dy = b.1 - a.1;
let dy = if dy == 0.0 || dy.is_nan() { 1e-12 } else { dy };
if (a.1 > p.1) != (b.1 > p.1) && p.0 < ((b.0 - a.0) * (p.1 - a.1)) / dy + a.0 {
inside = !inside;
}
j = i;
}
inside
}
struct BBox {
x0: f64,
y0: f64,
x1: f64,
y1: f64,
}
fn bbox(pts: &[V]) -> BBox {
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for p in pts {
x0 = jsnum::min(x0, p.0);
y0 = jsnum::min(y0, p.1);
x1 = jsnum::max(x1, p.0);
y1 = jsnum::max(y1, p.1);
}
BBox { x0, y0, x1, y1 }
}
fn solid_pts(s: &Value) -> Vec<V> {
arr(field(s, "points")).iter().map(xy).collect()
}
/// Kleinster Körper der Ebene, dessen Grundriss den Punkt enthält.
fn pick_solid<'a>(root: &'a Map<String, Value>, level: &str, at: V) -> Option<&'a Value> {
let mut best = None;
let mut best_area = f64::INFINITY;
for sd in arr(root.get("extrudedSolids")) {
let pts = solid_pts(sd);
if level_of(sd) != Some(level) || !point_in_polygon(at, &pts) {
continue;
}
let b = bbox(&pts);
let area = (b.x1 - b.x0) * (b.y1 - b.y0);
if area < best_area {
best = Some(sd);
best_area = area;
}
}
best
}
/// Boolesche Verknüpfung zweier Körper (`combineSolids`): Grundriss als Hüllrechteck (Vereinigung,
/// Durchschnitt) bzw. der des ersten (Differenz), B-Rep `boolean` aus beiden Beschreibungen.
pub fn combine_solids(a: &Value, b: &Value, op: &str, id: String) -> Option<Value> {
let sa = extruded_solid_spec(a, 0.0)?;
let sb = extruded_solid_spec(b, 0.0)?;
let (pa, pb) = (solid_pts(a), solid_pts(b));
let (ba, bb) = (bbox(&pa), bbox(&pb));
let (ha, hb) = (num_of(field(a, "height")), num_of(field(b, "height")));
let rect = |x0: f64, y0: f64, x1: f64, y1: f64| vec![pv((x0, y0)), pv((x1, y0)), pv((x1, y1)), pv((x0, y1))];
let (points, height, label) = match op {
"union" => (rect(jsnum::min(ba.x0, bb.x0), jsnum::min(ba.y0, bb.y0), jsnum::max(ba.x1, bb.x1), jsnum::max(ba.y1, bb.y1)), jsnum::max(ha, hb), "Vereinigung"),
"difference" => (arr(field(a, "points")).to_vec(), ha, "Differenz"),
_ => {
let (x0, y0) = (jsnum::max(ba.x0, bb.x0), jsnum::max(ba.y0, bb.y0));
let (x1, y1) = (jsnum::min(ba.x1, bb.x1), jsnum::min(ba.y1, bb.y1));
if x1 - x0 < 1e-6 || y1 - y0 < 1e-6 {
return None;
}
(rect(x0, y0, x1, y1), jsnum::min(ha, hb), "Durchschnitt")
}
};
let origin = points.first().cloned().unwrap_or(Value::Null);
Some(obj(vec![
("id", s(&id)),
("type", s("extrudedSolid")),
("levelId", field(a, "levelId").cloned().unwrap_or(Value::Null)),
("points", Value::Array(points)),
("height", js_num(height)),
(
"brep",
obj(vec![
("spec", obj(vec![("kind", s("boolean")), ("op", s(op)), ("a", sa), ("b", sb)])),
("origin", origin),
("label", s(label)),
]),
),
]))
}
fn solidbool_ops(root: &Map<String, Value>, v: &Value, ids: &mut IdGen) -> Vec<Op> {
let (Some(a), Some(b)) = (find(root, "extrudedSolids", s_of(v, "a")), find(root, "extrudedSolids", s_of(v, "b"))) else {
return Vec::new();
};
let Some(merged) = combine_solids(a, b, s_of(v, "op"), ids.next("body")) else { return Vec::new() };
let ids_ab: Vec<&str> = [id_of(a), id_of(b)].into_iter().flatten().collect();
let mut ops = crate::cmd_create::remove_op(root, "extrudedSolids", &ids_ab);
ops.extend(add_op("extrudedSolids", vec![merged]));
ops
}
/// Aussparungs-Quader (`voidFromInputs`): Grundriss-Rechteck, Höhe, Versatz über der UK.
fn voidbox_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let (a, b) = (p_of(v, "a"), p_of(v, "b"));
let (height, offset) = (n_of(v, "height"), n_of(v, "offset"));
if (b.0 - a.0).abs() < 1e-6 || (b.1 - a.1).abs() < 1e-6 || !(height > 1e-6) {
return Vec::new();
}
let mut f = vec![
("id", s(&ids.next("void"))),
("type", s("extrudedSolid")),
("levelId", s(ctx.level)),
("points", pvs(&rect_corners(a, b))),
("height", js_num(height)),
("operation", s("subtract")),
];
if offset.abs() > 1e-9 {
f.push(("baseOffset", js_num(offset)));
}
add_op("extrudedSolids", vec![obj(f)])
}
// ═════════════════════════════════════════════════════════════════════════════
// Gelände aus Höhenlinien
// ═════════════════════════════════════════════════════════════════════════════
/// Gelände-TIN aus Höhenlinien (`generateTerrainFromContours`): alle endlichen Stützpunkte, Delaunay
/// über (x, y), Höhe der Kontur je Punkt; Null-Flächen-Dreiecke verworfen.
pub fn terrain_from_contours(contours: &[Value], id: &str) -> Value {
let (mut xs, mut ys, mut zs) = (Vec::new(), Vec::new(), Vec::new());
for c in contours {
let z = num_of(field(c, "z"));
let z = if z.is_finite() { z } else { 0.0 };
for p in arr(field(c, "pts")) {
let (x, y) = xy(p);
if !x.is_finite() || !y.is_finite() {
continue;
}
xs.push(x);
ys.push(y);
zs.push(z);
}
}
if xs.len() < 3 {
return json!({ "id": id, "type": "terrainMesh", "name": "Gelände", "categoryCode": "02", "positions": [], "indices": [] });
}
let coords: Vec<f64> = xs.iter().zip(&ys).flat_map(|(x, y)| [*x, *y]).collect();
let tri = crate::delaunay::triangulate(&coords);
let positions: Vec<Value> = (0..xs.len()).flat_map(|i| [js_num(xs[i]), js_num(ys[i]), js_num(zs[i])]).collect();
let mut indices = Vec::new();
for t in tri.chunks_exact(3) {
let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize);
let area2 = ((xs[b] - xs[a]) * (ys[c] - ys[a]) - (xs[c] - xs[a]) * (ys[b] - ys[a])).abs();
if area2 <= 1e-9 {
continue;
}
indices.extend([Value::from(t[0]), Value::from(t[1]), Value::from(t[2])]);
}
obj(vec![
("id", s(id)),
("type", s("terrainMesh")),
("name", s("Gelände")),
("layer", s("Terrain")),
("categoryCode", s("02")),
("positions", Value::Array(positions)),
("indices", Value::Array(indices)),
])
}
fn terrain_ops(root: &Map<String, Value>, ids: &mut IdGen) -> Vec<Op> {
let Some(set) = arr(root.get("context")).iter().find(|o| field(o, "type").and_then(Value::as_str) == Some("contourSet")) else {
return Vec::new();
};
let t = terrain_from_contours(arr(field(set, "contours")), &ids.next("terrain"));
if arr(field(&t, "indices")).is_empty() {
return Vec::new();
}
add_op("context", vec![t])
}
// ═════════════════════════════════════════════════════════════════════════════
// Decken-Aussparung, Dach-Hof, Schnitt-/Ansichtslinie
// ═════════════════════════════════════════════════════════════════════════════
fn ring_of(o: &Value) -> Vec<V> {
arr(field(o, "outline")).iter().map(xy).collect()
}
/// Rechteckige Aussparung in die Decke des Geschosses, die alle vier Ecken enthält.
fn ceiling_opening_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx) -> Vec<Op> {
let (a, b) = (p_of(v, "a"), p_of(v, "b"));
if (b.0 - a.0).abs() < 0.05 || (b.1 - a.1).abs() < 0.05 {
return Vec::new();
}
let corners = rect_corners(a, b);
let host = arr(root.get("ceilings")).iter().find(|c| {
let ring = ring_of(c);
crate::cmd_create::floor_of(c) == Some(ctx.level) && ring.len() >= 3 && corners.iter().all(|p| point_in_polygon(*p, &ring))
});
let Some(host) = host else { return Vec::new() };
let mut openings = arr(field(host, "openings")).to_vec();
openings.push(pvs(&corners));
vec![Op::Replace { collection: "ceilings".into(), entity: with(host, "openings", Value::Array(openings)) }]
}
/// Hof-Ring des Dach-Hof-Befehls: ≥ 3 Punkte wie gezeichnet, 2 Punkte als Rechteck.
fn hole_ring(points: &[V]) -> Option<Vec<V>> {
match points {
[a, b] => {
if (a.0 - b.0).abs() < 0.05 || (a.1 - b.1).abs() < 0.05 {
None
} else {
Some(rect_corners(*a, *b).to_vec())
}
}
p if p.len() >= 3 => Some(p.to_vec()),
_ => None,
}
}
/// Lässt das Dach-Skelett den Hof zu (eigene Traufe je Hof)?
fn roof_hole_works(roof: &Value, ring: &[V]) -> bool {
if ring.len() < 3 {
return false;
}
let mut holes = arr(field(roof, "holes")).to_vec();
holes.push(pvs(ring));
let n = holes.len();
let probe = with(roof, "holes", Value::Array(holes));
match serde_json::from_value::<crate::model::Roof>(probe) {
Ok(r) => crate::roof::roof_geometry(&r.params(), 0.0).eaves_holes.len() == n,
Err(_) => false,
}
}
/// Hof in das Dach des Geschosses, das den Ring enthält und ihn zulässt.
fn roof_hole_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx) -> Vec<Op> {
let Some(ring) = hole_ring(&pts_of(v, "pts")) else { return Vec::new() };
let host = arr(root.get("roofs")).iter().find(|r| {
let outline = ring_of(r);
crate::cmd_create::floor_of(r) == Some(ctx.level)
&& outline.len() >= 3
&& ring.iter().all(|p| point_in_polygon(*p, &outline))
&& roof_hole_works(r, &ring)
});
let Some(host) = host else { return Vec::new() };
let mut holes = arr(field(host, "holes")).to_vec();
holes.push(pvs(&ring));
vec![Op::Replace { collection: "roofs".into(), entity: with(host, "holes", Value::Array(holes)) }]
}
/// Buchstaben der nächsten Linie (A … Z, AA …) aus der Zahl vorhandener Ebenen dieser Art.
fn level_letters(count: usize) -> String {
let mut n = count as i64;
let mut letters = String::new();
loop {
letters.insert(0, (b'A' + (n % 26) as u8) as char);
n = n / 26 - 1;
if n < 0 {
break;
}
}
letters
}
/// Schnitt-/Ansichtslinie: eine verwaiste Ebene dieser Art bekommt die Linie, sonst eine neue Ebene
/// (`name` = Vorlage der Hülle mit `\u{1}` für die Buchstaben).
fn sectionline_ops(root: &Map<String, Value>, v: &Value, ids: &mut IdGen) -> Vec<Op> {
let (a, b) = (p_of(v, "a"), p_of(v, "b"));
if hypot2(b.0 - a.0, b.1 - a.1) < 0.1 {
return Vec::new();
}
let kind = s_of(v, "kind");
let line = Value::Array(vec![pv(a), pv(b)]);
let levels = arr(root.get("drawingLevels"));
let of_kind: Vec<&Value> = levels.iter().filter(|z| field(z, "kind").and_then(Value::as_str) == Some(kind)).collect();
let orphans: Vec<&&Value> = of_kind.iter().filter(|z| !truthy(field(z, "linePoints"))).collect();
if orphans.len() == 1 {
let z = *orphans[0];
let sign = match field(z, "directionSign") {
None | Some(Value::Null) => js_num(1.0),
Some(x) => x.clone(),
};
return vec![Op::Replace { collection: "drawingLevels".into(), entity: crate::grips::with_all(z, vec![("linePoints", line), ("directionSign", sign)]) }];
}
let name = s_of(v, "name").replace('\u{1}', &level_letters(of_kind.len()));
add_op(
"drawingLevels",
vec![obj(vec![
("id", s(&ids.next(kind))),
("name", s(&name)),
("kind", s(kind)),
("visible", Value::Bool(true)),
("locked", Value::Bool(false)),
("linePoints", line),
("directionSign", js_num(1.0)),
])],
)
}
/// Richtungspfeil der Schnittlinie (Mitte → Blickrichtung, zwei Flügel).
fn direction_arrow(a: V, b: V, sign: f64, out: &mut Shapes) {
let d = (b.0 - a.0, b.1 - a.1);
let len = hypot2(d.0, d.1);
if len < 1e-6 {
return;
}
let u = crate::cmd_create::normalize(d);
let (nx, ny) = (-u.1 * sign, u.0 * sign);
let m = ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0);
let arrow = jsnum::min(1.0, len / 4.0);
let tip = (m.0 + nx * arrow, m.1 + ny * arrow);
let wing = arrow * 0.35;
let back = (tip.0 - nx * wing * 2.0, tip.1 - ny * wing * 2.0);
out.line(m, tip);
out.line(tip, (back.0 + u.0 * wing, back.1 + u.1 * wing));
out.line(tip, (back.0 - u.0 * wing, back.1 - u.1 * wing));
}
// ═════════════════════════════════════════════════════════════════════════════
// Einstiege (über `cmd_create`)
// ═════════════════════════════════════════════════════════════════════════════
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),
"solidbool" => solidbool_ops(root, v, ids),
"voidbox" => voidbox_ops(v, ctx, ids),
"terrain" => terrain_ops(root, ids),
"ceilingOpening" => ceiling_opening_ops(root, v, ctx),
"roofHole" => roof_hole_ops(root, v, ctx),
"sectionline" => sectionline_ops(root, v, ids),
_ => return None,
})
}
pub fn preview(root: &Map<String, Value>, v: &Value, pts: &[V], p: &mut Preview) -> bool {
match s_of(v, "cmd") {
"solid" => solid_preview(v, pts, &mut p.shapes),
"solidOutline" => match find(root, "extrudedSolids", s_of(v, "id")) {
Some(sd) => p.shapes.poly(&solid_pts(sd)),
None => p.ok = false,
},
"voidbox" => {
if let [a, b] = pts {
let c = rect_corners(*a, *b);
p.shapes.poly(&c);
p.shapes.line(c[0], c[2]);
p.shapes.line(c[1], c[3]);
}
}
"sectionline" => {
if let [a, c] = pts {
p.shapes.line(*a, *c);
direction_arrow(*a, *c, 1.0, &mut p.shapes);
}
}
_ => return false,
}
true
}
pub fn query(root: &Map<String, Value>, v: &Value) -> Option<Value> {
Some(match s_of(v, "q") {
"pickSolid" => json!({ "hit": pick_solid(root, s_of(v, "level"), p_of(v, "pt")).and_then(id_of) }),
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn buchstaben_der_ebenen() {
assert_eq!(level_letters(0), "A");
assert_eq!(level_letters(25), "Z");
assert_eq!(level_letters(26), "AA");
assert_eq!(level_letters(27), "AB");
}
#[test]
fn grundkoerper_und_spezifikation() {
assert!(solid_from_inputs("torus", (0.0, 0.0), None, &[0.3, 0.5]).is_none());
let (_, h, spec, label) = solid_from_inputs("frustum", (1.0, 2.0), None, &[2.0, 1.0, 3.0]).unwrap();
assert_eq!(h, 3.0);
assert_eq!(spec["kind"], "revolve");
assert_eq!(label, "Kegelstumpf r=2.00/1.00 h=3.00");
let solid = json!({"points": [{"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 1, "y": 1}], "height": 2, "taper": 0.5});
assert_eq!(extruded_solid_spec(&solid, 1.0).unwrap()["kind"], "loft");
}
#[test]
fn gelaende_aus_hoehenlinien() {
let c = json!([{"z": 1, "pts": [{"x": 0, "y": 0}, {"x": 4, "y": 0}]}, {"z": 2, "pts": [{"x": 0, "y": 3}, {"x": 4, "y": 3}]}]);
let t = terrain_from_contours(c.as_array().unwrap(), "t");
assert_eq!(t["indices"].as_array().unwrap().len(), 6);
assert_eq!(t["positions"][2], 1);
}
}
+12
View File
@@ -15,12 +15,24 @@ fn parse<T: serde::de::DeserializeOwned>(v: &Value, what: &str) -> Result<T, Str
/// Ops eines Befehls (`text` = JSON `{cmd, …}`, Zahlen dürfen Nicht-endlich-Marken sein).
pub fn ops(root: &Map<String, Value>, text: &str) -> Result<Vec<Op>, String> {
let v: Value = serde_json::from_str(text).map_err(|e| format!("cmdOps: {e}"))?;
// Zeichnen in einer betretenen Gruppe: neue Elemente werden ihr Mitglied (`cmd_create::group_ops`).
if let Some(group) = v.get("group").and_then(Value::as_str) {
let mut inner = v.clone();
inner.as_object_mut().map(|m| m.remove("group"));
let mut out = ops(root, &inner.to_string())?;
let extra = crate::cmd_create::group_ops(root, &out, group);
out.extend(extra);
return Ok(out);
}
let cmd = v.get("cmd").and_then(Value::as_str).unwrap_or("");
let ids = |k: &str| -> Vec<String> { v.get(k).and_then(|x| serde_json::from_value(x.clone()).ok()).unwrap_or_default() };
let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string();
if let Some(ops) = crate::cmd_edit::ops(root, &v) {
return Ok(ops);
}
if let Some(ops) = crate::cmd_create::ops(root, &v) {
return Ok(ops);
}
Ok(match cmd {
"transform" => crate::cmd_transform::transform_ops(root, &parse(&v, cmd)?),
"align" => crate::cmd_transform::align_ops(root, &ids("ids"), &s("mode")),
+12 -2
View File
@@ -3,7 +3,7 @@
//! - `Math.min/max` liefern bei NaN NaN (Rust `f64::min/max` ignorieren NaN).
//! - `Math.round` rundet halbe Werte Richtung +∞ (Rust `round` weg von 0).
//! - `x | 0` ist ToInt32 (Rest modulo 2³², Rust `as i32` sättigt).
//! - `Math.pow` (`x ** 3`) und Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/tan/atan2/acos`
//! - `Math.pow` (`x ** 3`) und Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/tan/atan/atan2/acos`
//! der laufenden JS-Engine. Nur so sind die Werte bitgleich zur bisherigen TS-Fassung — V8
//! (glibc-abgeleitete sin/cos), JavaScriptCore (System-libm von macOS) und Rusts libm (musl)
//! unterscheiden sich in einzelnen Fällen in der letzten Stelle. Nativ (`cargo test`, Tauri)
@@ -27,6 +27,12 @@ mod trig {
fn js_pow(x: f64, y: f64) -> f64;
#[wasm_bindgen(js_namespace = Math, js_name = tan)]
fn js_tan(x: f64) -> f64;
#[wasm_bindgen(js_namespace = Math, js_name = atan)]
fn js_atan(x: f64) -> f64;
}
#[inline]
pub fn atan(x: f64) -> f64 {
js_atan(x)
}
#[inline]
pub fn tan(x: f64) -> f64 {
@@ -81,9 +87,13 @@ mod trig {
pub fn tan(x: f64) -> f64 {
x.tan()
}
#[inline]
pub fn atan(x: f64) -> f64 {
x.atan()
}
}
pub use trig::{acos, atan2, cos, pow, sin, tan};
pub use trig::{acos, atan, atan2, cos, pow, sin, tan};
/// Endliche Zahl oder 0 (NaN/±∞ → 0; Summen der Kennzahlen/Flächen).
#[inline]
+3
View File
@@ -91,6 +91,9 @@ pub mod project_refs;
pub mod commands;
pub mod cmd_transform;
pub mod cmd_edit;
pub mod cmd_create;
pub mod cmd_draw;
pub mod cmd_solid;
pub mod polyline_vertex;
#[cfg(feature = "web")]
-41
View File
@@ -1,41 +0,0 @@
//! Bindungen der automatischen Aussenbemassung (`crate::auto_dimensions`).
use crate::auto_dimensions::{self, OpeningIn, WallIn};
use crate::flat_read::Reader;
use wasm_bindgen::prelude::wasm_bindgen;
fn read_walls(buf: &[f64]) -> Option<Vec<WallIn>> {
let mut r = Reader::new(buf);
let n = r.count()?;
let mut out = Vec::with_capacity(n.min(1 << 16));
for _ in 0..n {
out.push(WallIn { start: [r.num()?, r.num()?], end: [r.num()?, r.num()?], thickness: r.num()? });
}
Some(out)
}
fn read_openings(buf: &[f64]) -> Option<Vec<OpeningIn>> {
let mut r = Reader::new(buf);
let n = r.count()?;
let mut out = Vec::with_capacity(n.min(1 << 16));
for _ in 0..n {
let wall = r.count()?;
out.push(OpeningIn { wall, jamb_start: [r.num()?, r.num()?], jamb_end: [r.num()?, r.num()?] });
}
Some(out)
}
/// Wände `[n, (x0, y0, x1, y1, dicke)…]`, Öffnungen `[n, (wandIndex, ax, ay, bx, by)…]`
/// → `[n, (seite, kette, abstand, nPkt, x, y, …)…]` (Seite 0..3 = Süd/Ost/Nord/West,
/// Kette 0..2 = Öffnungen/Vor-Rücksprünge/Gesamt).
#[wasm_bindgen]
pub fn autodim_chains(walls: &[f64], openings: &[f64], scale_denominator: f64) -> Vec<f64> {
let (Some(w), Some(o)) = (read_walls(walls), read_openings(openings)) else { return vec![0.0] };
let chains = auto_dimensions::auto_exterior_dimensions(&w, &o, scale_denominator);
let mut out = vec![chains.len() as f64];
for c in chains {
out.extend([c.side as f64, c.chain as f64, c.offset, c.pts.len() as f64]);
out.extend(c.pts.into_iter().flatten());
}
out
}
-21
View File
@@ -32,24 +32,3 @@ pub fn bulge_from_sagitta_point(ax: f64, ay: f64, bx: f64, by: f64, px: f64, py:
pub fn bulge_point_at(ax: f64, ay: f64, bx: f64, by: f64, bulge: f64, t: f64) -> Vec<f64> {
b::point_at(ax, ay, bx, by, bulge, t)
}
#[wasm_bindgen]
pub fn bulge_through_point(ax: f64, ay: f64, tx: f64, ty: f64, bx: f64, by: f64) -> f64 {
b::through_point(ax, ay, tx, ty, bx, by)
}
/// `[cx, cy, r, a0, a1]` (CCW) oder leer.
#[wasm_bindgen]
pub fn arc_through_points(ax: f64, ay: f64, tx: f64, ty: f64, bx: f64, by: f64) -> Vec<f64> {
b::arc_through_points(ax, ay, tx, ty, bx, by)
}
#[wasm_bindgen]
pub fn arc_from_start_end_radius(ax: f64, ay: f64, bx: f64, by: f64, r: f64, nx: f64, ny: f64) -> Vec<f64> {
b::arc_from_start_end_radius(ax, ay, bx, by, r, nx, ny)
}
#[wasm_bindgen]
pub fn arc_from_start_end_direction(ax: f64, ay: f64, bx: f64, by: f64, dx: f64, dy: f64) -> Vec<f64> {
b::arc_from_start_end_direction(ax, ay, bx, by, dx, dy)
}
+72
View File
@@ -0,0 +1,72 @@
//! Bindungen der Zeichenbefehle (`crate::cmd_create`): Vorschau je Mausschritt (Optionen als JSON, die
//! Punkte flach) und Treffer-Abfragen zwischen den Schritten. Der Commit läuft über `doc_cmd_commit`.
//!
//! Je Mausschritt ändern sich meist nur die Punkte: die zuletzt gelesenen Optionen bleiben hier liegen,
//! `doc_create_preview_again` rechnet mit ihnen (kein JSON hin und kein Parsen je Mausschritt — die
//! Wand-Vorschau ist sonst langsamer als die frühere TS-Fassung).
use super::document::with_doc;
use crate::cmd_create::Req;
use serde_json::Value;
use std::cell::RefCell;
use wasm_bindgen::prelude::wasm_bindgen;
thread_local! {
static LAST_REQ: RefCell<Option<Req>> = const { RefCell::new(None) };
}
fn run(h: u32, req: &Req, pts: &[f64]) -> Vec<f64> {
if pts.len() % 2 != 0 {
return Vec::new();
}
with_doc(h, |d| crate::cmd_create::preview_req(d.root(), req, pts).flat()).unwrap_or_default()
}
/// Vorschau eines Zeichenbefehls auf dem Dokument `h`: `[ok, nInfo, info…, Formen…]` (Formen wie
/// `doc_cmd_preview`); leer bei Fehler. Merkt sich die Optionen für [`doc_create_preview_again`].
#[wasm_bindgen]
pub fn doc_create_preview(h: u32, req_json: &str, pts: &[f64]) -> Vec<f64> {
let req = serde_json::from_str::<Value>(req_json).ok().filter(Value::is_object).map(Req::new);
let out = req.as_ref().map_or_else(Vec::new, |r| run(h, r, pts));
LAST_REQ.with(|l| *l.borrow_mut() = req);
out
}
/// Wie [`doc_create_preview`] mit den zuletzt übergebenen Optionen (nur neue Punkte).
#[wasm_bindgen]
pub fn doc_create_preview_again(h: u32, pts: &[f64]) -> Vec<f64> {
LAST_REQ.with(|l| l.borrow().as_ref().map_or_else(Vec::new, |r| run(h, r, pts)))
}
/// Treffer-Abfrage eines Zeichenbefehls (`crate::cmd_create::query`), Antwort-JSON (Zahlen mit
/// Nicht-endlich-Marken); Fehler als Text mit `\u{1}` vorn.
#[wasm_bindgen]
pub fn doc_create_query(h: u32, req_json: &str) -> String {
let v: Value = match serde_json::from_str(req_json) {
Ok(v) => v,
Err(e) => return format!("\u{1}Zeichen-Abfrage: {e}"),
};
match with_doc(h, |d| crate::cmd_create::query(d.root(), &v)) {
Some(Some(Ok(v))) => v.to_string(),
Some(Some(Err(e))) => format!("\u{1}{e}"),
Some(None) => "\u{1}Unbekannte Zeichen-Abfrage".to_string(),
None => "\u{1}Dokument nicht offen".to_string(),
}
}
/// B-Rep-Beschreibung eines Körpers (`crate::cmd_solid::extruded_solid_spec`) als JSON (Zahlen mit
/// Nicht-endlich-Marken); leer = keine Beschreibung oder kein Körper.
#[wasm_bindgen]
pub fn extruded_solid_spec_json(solid_json: &str, floor_z: f64) -> String {
serde_json::from_str::<Value>(solid_json)
.ok()
.and_then(|s| crate::cmd_solid::extruded_solid_spec(&s, floor_z))
.map_or_else(String::new, |v| v.to_string())
}
/// Gelände-TIN aus Höhenlinien (`crate::cmd_solid::terrain_from_contours`) als JSON; `id` des Netzes.
#[wasm_bindgen]
pub fn terrain_from_contours_json(contours_json: &str, id: &str) -> String {
let c: Value = serde_json::from_str(contours_json).unwrap_or(Value::Null);
crate::cmd_solid::terrain_from_contours(c.as_array().map(Vec::as_slice).unwrap_or(&[]), id).to_string()
}
-6
View File
@@ -2,12 +2,6 @@
use wasm_bindgen::prelude::wasm_bindgen;
/// Punkte einer (gedrehten) Ellipse, `n` gleichverteilte Parameterschritte.
#[wasm_bindgen]
pub fn curves_ellipse_flat(cx: f64, cy: f64, rx: f64, ry: f64, rotation: f64, n: f64) -> Vec<f64> {
crate::curves::ellipse(cx, cy, rx, ry, rotation, n)
}
/// Kubische Bezier-Kette (Anker·Griff·Griff·Anker …); unter 4 Punkten unverändert.
#[wasm_bindgen]
pub fn curves_bezier_chain_flat(pts: &[f64], segs_per_curve: f64) -> Vec<f64> {
+1 -57
View File
@@ -8,7 +8,7 @@
//! Kaputte Eingaben (ungerade Längen, falsche Zählungen, ungültige Indizes) ergeben ein
//! leeres Ergebnis statt eines Panics.
use kernel2d::{self as k, TangentTarget, Vec2};
use kernel2d::{self as k, Vec2};
use wasm_bindgen::prelude::wasm_bindgen;
// --- Lesen -------------------------------------------------------------------
@@ -61,16 +61,6 @@ fn pt_lists(buf: &[f64]) -> Option<Vec<Vec<Vec2>>> {
(0..n).map(|_| r.count().and_then(|m| r.pts(m))).collect()
}
fn tangent_target(buf: &[f64]) -> Option<TangentTarget> {
match *buf {
[kind, ax, ay, bx, by] if kind == 0.0 => {
Some(TangentTarget::Line { a: Vec2::new(ax, ay), b: Vec2::new(bx, by) })
}
[kind, cx, cy, r, _] if kind == 1.0 => Some(TangentTarget::Circle { center: Vec2::new(cx, cy), r }),
_ => None,
}
}
// --- Schreiben ---------------------------------------------------------------
fn push_pts(out: &mut Vec<f64>, pts: &[Vec2]) {
@@ -107,40 +97,13 @@ const EMPTY_LIST: [f64; 1] = [0.0];
// --- Punkt/Strecke, Fläche, Kreise ---------------------------------------------
#[wasm_bindgen]
pub fn k2_point_segment_distance(px: f64, py: f64, ax: f64, ay: f64, bx: f64, by: f64) -> f64 {
k::point_segment_distance(Vec2::new(px, py), Vec2::new(ax, ay), Vec2::new(bx, by))
}
#[wasm_bindgen]
pub fn k2_signed_area(p: &[f64]) -> f64 {
pts(p).map_or(0.0, |p| k::signed_area(&p))
}
#[wasm_bindgen]
pub fn k2_is_ccw(p: &[f64]) -> bool {
pts(p).is_some_and(|p| k::is_ccw(&p))
}
#[wasm_bindgen]
pub fn k2_circle_circle_intersect(c1x: f64, c1y: f64, r1: f64, c2x: f64, c2y: f64, r2: f64) -> Vec<f64> {
enc_pts(&k::circle_circle_intersect(Vec2::new(c1x, c1y), r1, Vec2::new(c2x, c2y), r2))
}
#[wasm_bindgen]
pub fn k2_tangent_circle_centers(t1: &[f64], t2: &[f64], r: f64) -> Vec<f64> {
let (Some(t1), Some(t2)) = (tangent_target(t1), tangent_target(t2)) else { return Vec::new() };
enc_pts(&k::tangent_circle_centers(t1, t2, r))
}
// --- Offset ------------------------------------------------------------------
#[wasm_bindgen]
pub fn k2_offset_segment(ax: f64, ay: f64, bx: f64, by: f64, d: f64) -> Vec<f64> {
let (a, b) = k::offset_segment(Vec2::new(ax, ay), Vec2::new(bx, by), d);
vec![a.x, a.y, b.x, b.y]
}
// --- Trim / Extend -----------------------------------------------------------
@@ -151,25 +114,6 @@ pub fn k2_offset_segment(ax: f64, ay: f64, bx: f64, by: f64, d: f64) -> Vec<f64>
// --- Ecken -------------------------------------------------------------------
/// `[cx, cy, radius, tAx, tAy, tBx, tBy, startAngle, endAngle]` oder leer.
#[wasm_bindgen]
pub fn k2_fillet_corner(cx: f64, cy: f64, p1x: f64, p1y: f64, p2x: f64, p2y: f64, r: f64) -> Vec<f64> {
match k::fillet_corner(Vec2::new(cx, cy), Vec2::new(p1x, p1y), Vec2::new(p2x, p2y), r) {
Some(f) => vec![
f.center.x,
f.center.y,
f.radius,
f.tangent_a.x,
f.tangent_a.y,
f.tangent_b.x,
f.tangent_b.y,
f.start_angle,
f.end_angle,
],
None => Vec::new(),
}
}
// --- Split / Join / Segment löschen / Bruch ----------------------------------------
+1 -1
View File
@@ -8,7 +8,6 @@ mod polygon;
mod roof;
mod sun;
mod site_rules;
mod auto_dimensions;
mod kennzahlen;
mod bulge;
mod stair;
@@ -40,6 +39,7 @@ mod text_layout;
mod grips;
mod project_refs;
mod commands;
mod cmd_create;
use wasm_bindgen::prelude::wasm_bindgen;
-12
View File
@@ -8,15 +8,3 @@ use wasm_bindgen::prelude::wasm_bindgen;
pub fn rooms_detect(walls: &[f64], gap_tol: f64, min_area: f64, offset_to_inner: bool) -> Vec<f64> {
rb::detect(walls, gap_tol, min_area, offset_to_inner)
}
/// Umriss der Zelle um den Punkt `[nPkt, x, y, …]`, leer = keine.
#[wasm_bindgen]
pub fn room_from_point(px: f64, py: f64, walls: &[f64], gap_tol: f64, offset_to_inner: bool) -> Vec<f64> {
rb::from_point(px, py, walls, gap_tol, offset_to_inner)
}
/// Wie `room_from_point`, aber auf fertigen Wand-Innenflächen (ohne Offset).
#[wasm_bindgen]
pub fn room_from_point_faces(px: f64, py: f64, faces: &[f64], gap_tol: f64) -> Vec<f64> {
rb::from_point_faces(px, py, faces, gap_tol)
}
-18
View File
@@ -3,26 +3,8 @@
use crate::stair as s;
use wasm_bindgen::prelude::wasm_bindgen;
/// Parameter (16 Zahlen) + Gesamt-Steighöhe → flache Treppengeometrie; Unsinn → leer.
#[wasm_bindgen]
pub fn stair_geometry_flat(params: &[f64], total_rise: f64) -> Vec<f64> {
s::geometry(params, total_rise)
}
/// Plan-Aussenlinie: `[0, n, x, y …]` (Polygon) oder `[1, …]` (Wendel).
#[wasm_bindgen]
pub fn stair_outline_flat(params: &[f64]) -> Vec<f64> {
s::outline(params)
}
/// Schnittaufteilung aus flacher Geometrie und Schnitthöhe über der Treppen-UK.
#[wasm_bindgen]
pub fn stair_cut_flat(geometry: &[f64], cut_rise: f64) -> Vec<f64> {
s::cut(geometry, cut_rise)
}
/// Vorgabe-Stufenzahl aus Steighöhe und Lauflänge.
#[wasm_bindgen]
pub fn stair_default_step_count(total_rise: f64, run_length: f64) -> u32 {
s::default_step_count(total_rise, run_length)
}