[144] Öffnungen verschieben (Zwischenstand): Kern opening_slide (Bogenwand, Überlappung, Dach-/Deckenöffnung), Hinweis aus Befehlen, Bemassung auf Bogen-Leibungen
This commit is contained in:
10 files changed
+603
-72
No files matched your search
@@ -344,59 +344,87 @@ fn free_openings<'a>(root: &'a Map<String, Value>, sel: &Sel, op: &str, walls: &
|
||||
}
|
||||
|
||||
/// Wandöffnung um `d` verschieben ([144]): die Öffnungsmitte geht nach `Mitte + d`. Liegt das Ziel in
|
||||
/// einer anderen geraden Wand desselben Geschosses (innerhalb der halben Dicke + 5 cm) und nicht mehr in
|
||||
/// der eigenen, wechselt die Öffnung dorthin; sonst gleitet sie um die auf die Wandachse projizierte
|
||||
/// Strecke. `position` auf [0, Wandlänge − Breite] geklemmt. `None`: Wirt fehlt, Bogenwand oder die
|
||||
/// Öffnung passt nicht in die Wand.
|
||||
fn slide_opening(root: &Map<String, Value>, p: &Project, o: &Value, d: (f64, f64)) -> Option<Value> {
|
||||
/// einer anderen Wand desselben Geschosses (innerhalb der halben Dicke + 5 cm) und nicht mehr in der
|
||||
/// eigenen, wechselt die Öffnung dorthin; sonst gleitet sie entlang der Achse (gerade Wand: um die
|
||||
/// projizierte Strecke; Bogenwand [T2]: zum Lotfuss auf dem Bogen, `position` = Bogenlänge). Geklemmt auf
|
||||
/// die Wand und vor Nachbaröffnungen (`opening_slide::place`, Steg 5 cm). `skip`: mitbewegte Öffnungen.
|
||||
/// `None`: Wirt fehlt, die Öffnung passt nicht in die Wand oder dort ist kein Platz. Das `bool` meldet,
|
||||
/// dass eine Nachbaröffnung die Lage begrenzt hat.
|
||||
fn slide_opening(root: &Map<String, Value>, p: &Project, o: &Value, d: (f64, f64), copy: bool, skip: &dyn Fn(&str) -> bool) -> Option<(Value, bool)> {
|
||||
use crate::opening_slide::{place, Axis};
|
||||
let walls = list(root, "walls");
|
||||
let host = walls.iter().find(|w| id_of(w) == wall_host(o))?;
|
||||
let width = num_of(field(o, "width"));
|
||||
let frame = |w: &Value| {
|
||||
let (s, e) = straight_wall(w)?;
|
||||
let len = hypot2(e.0 - s.0, e.1 - s.1);
|
||||
(len > 1e-9 && len.is_finite()).then(|| (s, ((e.0 - s.0) / len, (e.1 - s.1) / len), len))
|
||||
};
|
||||
let (s, u, len) = frame(host)?;
|
||||
let c = (s.0 + u.0 * (num_of(field(o, "position")) + width / 2.0), s.1 + u.1 * (num_of(field(o, "position")) + width / 2.0));
|
||||
let axis = Axis::of(host)?;
|
||||
let pos0 = num_of(field(o, "position"));
|
||||
let c = axis.point(pos0 + width / 2.0, 0.0);
|
||||
let target = (c.0 + d.0, c.1 + d.1);
|
||||
if !(target.0.is_finite() && target.1.is_finite() && width.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
// Abstand des Ziels zur Wandachse (Strecke) und Lage entlang der Achse.
|
||||
let reach = |w: &Value| -> Option<(f64, f64, f64)> {
|
||||
let (s, u, len) = frame(w)?;
|
||||
let t = (target.0 - s.0) * u.0 + (target.1 - s.1) * u.1;
|
||||
let tc = jsnum::max(0.0, jsnum::min(len, t));
|
||||
let dist = hypot2(target.0 - (s.0 + u.0 * tc), target.1 - (s.1 + u.1 * tc));
|
||||
Some((dist, t, len))
|
||||
};
|
||||
let tol = |w: &Value| wall_thickness(p, w) / 2.0 + 0.05;
|
||||
let in_host = reach(host).is_some_and(|(dist, _, _)| dist <= tol(host));
|
||||
let (t_host, dist_host) = axis.local(target);
|
||||
let in_host = dist_host <= tol(host);
|
||||
let floor = field(host, "floorId");
|
||||
let other = (!in_host)
|
||||
.then(|| {
|
||||
walls
|
||||
.iter()
|
||||
.filter(|w| id_of(w) != id_of(host) && field(w, "floorId") == floor)
|
||||
.filter_map(|w| reach(w).filter(|(dist, _, _)| *dist <= tol(w)).map(|r| (w, r)))
|
||||
.min_by(|a, b| a.1 .0.total_cmp(&b.1 .0))
|
||||
.filter_map(|w| {
|
||||
let ax = Axis::of(w)?;
|
||||
let (t, dist) = ax.local(target);
|
||||
(dist <= tol(w)).then_some((w, ax, t, dist))
|
||||
})
|
||||
.min_by(|a, b| a.3.total_cmp(&b.3))
|
||||
})
|
||||
.flatten();
|
||||
// Neue Lage des ersten Pfostens; in der eigenen Wand direkt `position + d·u` (ohne Rundung über die Mitte).
|
||||
let (wall, start, wlen) = match other {
|
||||
Some((w, (_, t, l))) => (w, t - width / 2.0, l),
|
||||
None => (host, num_of(field(o, "position")) + d.0 * u.0 + d.1 * u.1, len),
|
||||
let me = id_of(o).unwrap_or("");
|
||||
// Kopie: Originale bleiben stehen und sind Nachbarn wie jede andere (Kopie rückt an die nächste freie Stelle).
|
||||
let skip_me = |id: &str| !copy && (id == me || skip(id));
|
||||
let from = (!copy && pos0.is_finite()).then_some(pos0);
|
||||
// Neue Lage des ersten Pfostens; gerade eigene Wand direkt `position + d·u` (ohne Rundung über die Mitte).
|
||||
let (wall, placed) = match other {
|
||||
Some((w, ax, t, _)) => (w, place(root, id_of(w)?, ax.len(), width, None, t - width / 2.0, &skip_me)?),
|
||||
None => {
|
||||
let want = match &axis {
|
||||
Axis::Line { u, .. } => pos0 + d.0 * u.0 + d.1 * u.1,
|
||||
Axis::Arc(_) => t_host - width / 2.0,
|
||||
};
|
||||
(host, place(root, id_of(host)?, axis.len(), width, from, want, &skip_me)?)
|
||||
}
|
||||
};
|
||||
if width > wlen + 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let pos = jsnum::max(0.0, jsnum::min(wlen - width, start));
|
||||
let mut v = with(o, "position", js_num(pos));
|
||||
let mut v = with(o, "position", js_num(placed.position));
|
||||
if id_of(wall) != id_of(host) {
|
||||
v = with(&v, "hostWallId", Value::String(id_of(wall)?.to_owned()));
|
||||
}
|
||||
Some(v)
|
||||
Some((v, placed.clamped))
|
||||
}
|
||||
|
||||
/// Frei gewählte Dach-/Deckenöffnungen ([144]): gewählt, nicht gesperrt, Wirt nicht mitbewegt; nur
|
||||
/// beim Verschieben. Sie gleiten in der Wirtsfläche (Mitte im Umriss gehalten).
|
||||
fn free_surface_openings<'a>(root: &'a Map<String, Value>, sel: &Sel, op: &str, hosts: &std::collections::HashSet<&str>, ignore_lock: bool) -> Vec<&'a Value> {
|
||||
let ids = Ids::opt(&sel.opening_ids);
|
||||
if op != "move" || ids.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
list(root, "openings")
|
||||
.iter()
|
||||
.filter(|o| ids.has(o) && (ignore_lock || !locked(o)))
|
||||
.filter(|o| surface_host(o).is_some_and(|(_, h)| !hosts.contains(h)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Dach-/Deckenöffnung um `d` verschieben: `hostPoint + d`, im Umriss des Wirts gehalten
|
||||
/// (`opening_slide::clamp_inside`). `None`: Wirt fehlt.
|
||||
fn slide_surface_opening(root: &Map<String, Value>, o: &Value, d: (f64, f64)) -> Option<Value> {
|
||||
let (key, h) = surface_host(o)?;
|
||||
let coll = if key == "hostRoofId" { "roofs" } else { "ceilings" };
|
||||
let host = list(root, coll).iter().find(|e| id_of(e) == Some(h))?;
|
||||
let ring = pts_of(field(host, "outline"));
|
||||
let (bx, by) = xy(field(o, "hostPoint").unwrap_or(&Value::Null));
|
||||
let q = crate::opening_slide::clamp_inside((bx + d.0, by + d.1), &ring);
|
||||
(q.0.is_finite() && q.1.is_finite()).then(|| with(o, "hostPoint", pt(q.0, q.1)))
|
||||
}
|
||||
|
||||
/// Verschiebung der Klickpunkte zum Anteil `t` (Bewegen).
|
||||
@@ -665,14 +693,47 @@ fn add(collection: &str, items: Vec<Value>) -> Option<Op> {
|
||||
/// Die Transformation als Ops: `replace` je bewegtem Original (Modus „move“), dann `add` der Kopien je
|
||||
/// Liste (Wände, 2D, Körper, Stützen, Decken, Dächer, Treppen, Räume).
|
||||
pub fn transform_ops(root: &Map<String, Value>, p: &Project, req: &TransformReq) -> Vec<Op> {
|
||||
transform_result(root, p, req).ops
|
||||
}
|
||||
|
||||
/// Gemeinsame Mengen von Ops und Vorschau: (bewegte Wände, Wirte von Dach-/Deckenöffnungen) → frei
|
||||
/// gewählte Wand- und Flächenöffnungen ([144]).
|
||||
fn free_sets<'a>(root: &'a Map<String, Value>, sel: &Sel, op: &str, items: &[(Kind, &'a Value)], ignore_lock: bool) -> (Vec<&'a Value>, Vec<&'a Value>) {
|
||||
let ids_of = |f: &dyn Fn(&Kind) -> bool| -> std::collections::HashSet<&'a str> { items.iter().filter(|(k, _)| f(k)).filter_map(|(_, e)| id_of(e)).collect() };
|
||||
let walls = ids_of(&|k| matches!(k, Kind::Wall));
|
||||
let hosts = ids_of(&|k| matches!(k, Kind::Roof | Kind::Ceiling));
|
||||
(free_openings(root, sel, op, &walls, ignore_lock), free_surface_openings(root, sel, op, &hosts, ignore_lock))
|
||||
}
|
||||
|
||||
/// Wie [`transform_ops`], mit Hinweis ([144]: eine Öffnung hielt an der Nachbaröffnung an bzw. fand in
|
||||
/// der Zielwand keinen Platz).
|
||||
pub fn transform_result(root: &Map<String, Value>, p: &Project, req: &TransformReq) -> crate::grips::GripResult {
|
||||
let (sel, op) = (&req.sel, req.op.as_str());
|
||||
let items = gather(root, sel, op, false);
|
||||
let moved_walls: std::collections::HashSet<&str> =
|
||||
items.iter().filter(|(k, _)| matches!(k, Kind::Wall)).filter_map(|(_, e)| id_of(e)).collect();
|
||||
let free = free_openings(root, sel, op, &moved_walls, false);
|
||||
if items.is_empty() && free.is_empty() {
|
||||
return vec![];
|
||||
let (free, free_surf) = free_sets(root, sel, op, &items, false);
|
||||
if items.is_empty() && free.is_empty() && free_surf.is_empty() {
|
||||
return Default::default();
|
||||
}
|
||||
let notice: std::cell::Cell<Option<&'static str>> = Default::default();
|
||||
let free_ids: std::collections::HashSet<&str> = free.iter().filter_map(|o| id_of(o)).collect();
|
||||
let skip = |id: &str| free_ids.contains(id);
|
||||
// Gleiten mit Hinweis: Anschlag an der Nachbaröffnung bzw. kein Platz.
|
||||
let slide = |o: &Value, d: (f64, f64), copy: bool| -> Option<Value> {
|
||||
match slide_opening(root, p, o, d, copy, &skip) {
|
||||
Some((v, clamped)) => {
|
||||
if clamped {
|
||||
notice.set(Some(crate::opening_slide::NOTICE_OVERLAP));
|
||||
}
|
||||
Some(v)
|
||||
}
|
||||
None => {
|
||||
if d != (0.0, 0.0) && wall_host(o).is_some() {
|
||||
notice.set(notice.get().or(Some(crate::opening_slide::NOTICE_NO_ROOM)));
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let pts = req.points();
|
||||
let scaling = op == "scale";
|
||||
let k_at = |t: f64| if scaling { scale_factor(&pts, t) } else { 1.0 };
|
||||
@@ -741,7 +802,9 @@ pub fn transform_ops(root: &Map<String, Value>, p: &Project, req: &TransformReq)
|
||||
}
|
||||
// Frei gewählte Wandöffnungen ([144]) gleiten entlang ihrer Wand (bzw. wechseln die Wand).
|
||||
let d = move_delta(&pts, 1.0);
|
||||
ops.extend(free.iter().filter_map(|o| slide_opening(root, p, o, d).filter(|v| v != *o)).map(|v| replace("openings", v)));
|
||||
ops.extend(free.iter().filter_map(|o| slide(o, d, false).filter(|v| v != *o)).map(|v| replace("openings", v)));
|
||||
// Frei gewählte Dach-/Deckenöffnungen ([144]) gleiten in ihrer Fläche.
|
||||
ops.extend(free_surf.iter().filter_map(|o| slide_surface_opening(root, o, d).filter(|v| v != *o)).map(|v| replace("openings", v)));
|
||||
}
|
||||
|
||||
// Kopien (Kopie/Reihe/Verteilen bzw. gespiegelte Kopie).
|
||||
@@ -796,7 +859,12 @@ pub fn transform_ops(root: &Map<String, Value>, p: &Project, req: &TransformReq)
|
||||
}
|
||||
// Kopien frei gewählter Wandöffnungen ([144]) in der Wand versetzt.
|
||||
for o in &free {
|
||||
if let Some(v) = slide_opening(root, p, o, move_delta(&pts, t)) {
|
||||
if let Some(v) = slide(o, move_delta(&pts, t), true) {
|
||||
new_openings.push(with(&v, "id", Value::String(ids.next("O"))));
|
||||
}
|
||||
}
|
||||
for o in &free_surf {
|
||||
if let Some(v) = slide_surface_opening(root, o, move_delta(&pts, t)) {
|
||||
new_openings.push(with(&v, "id", Value::String(ids.next("O"))));
|
||||
}
|
||||
}
|
||||
@@ -806,7 +874,7 @@ pub fn transform_ops(root: &Map<String, Value>, p: &Project, req: &TransformReq)
|
||||
ops.extend(add(key, items));
|
||||
}
|
||||
ops.extend(add("openings", new_openings));
|
||||
ops
|
||||
crate::grips::GripResult { ops, notice: notice.get() }
|
||||
}
|
||||
|
||||
// ── Ausrichten/Verteilen, Block definieren ───────────────────────────────────
|
||||
@@ -1155,9 +1223,9 @@ pub fn preview_pending(root: &Map<String, Value>, p: &Project, req: &TransformRe
|
||||
if req.mode == "move" {
|
||||
ts.push(1.0);
|
||||
}
|
||||
let moved_walls: std::collections::HashSet<&str> =
|
||||
items.iter().filter(|(k, _)| matches!(k, Kind::Wall)).filter_map(|(_, e)| id_of(e)).collect();
|
||||
let free = free_openings(root, &req.sel, op, &moved_walls, req.ignore_lock);
|
||||
let (free, free_surf) = free_sets(root, &req.sel, op, &items, req.ignore_lock);
|
||||
let free_ids: std::collections::HashSet<&str> = free.iter().filter_map(|o| id_of(o)).collect();
|
||||
let skip = |id: &str| free_ids.contains(id);
|
||||
let mut out = Pending::default();
|
||||
for t in ts {
|
||||
let xf = Xf::of(op, &pts, t);
|
||||
@@ -1165,7 +1233,12 @@ pub fn preview_pending(root: &Map<String, Value>, p: &Project, req: &TransformRe
|
||||
item_preview(p, *kind, e, &xf, &mut out);
|
||||
}
|
||||
for o in &free {
|
||||
if let Some(q) = slide_opening(root, p, o, move_delta(&pts, t)).and_then(|v| opening_quad(root, p, &v)) {
|
||||
if let Some(q) = slide_opening(root, p, o, move_delta(&pts, t), req.mode != "move", &skip).and_then(|(v, _)| opening_quad(root, p, &v)) {
|
||||
out.shapes.poly(&q);
|
||||
}
|
||||
}
|
||||
for o in &free_surf {
|
||||
if let Some(q) = slide_surface_opening(root, o, move_delta(&pts, t)).map(|v| surface_quad(&v)) {
|
||||
out.shapes.poly(&q);
|
||||
}
|
||||
}
|
||||
@@ -1173,10 +1246,30 @@ pub fn preview_pending(root: &Map<String, Value>, p: &Project, req: &TransformRe
|
||||
out
|
||||
}
|
||||
|
||||
/// Lücke einer Wandöffnung (Vorschau, [144]): Rechteck über die volle Wanddicke um die Achse.
|
||||
/// Dach-/Deckenöffnung als Rechteck um `hostPoint` (Vorschau, [144]; Breite quer, Höhe im Grundriss
|
||||
/// ungekürzt, gedreht um `hostAngle`).
|
||||
fn surface_quad(o: &Value) -> Vec<(f64, f64)> {
|
||||
let (cx, cy) = xy(field(o, "hostPoint").unwrap_or(&Value::Null));
|
||||
let (w, h) = (num_or(field(o, "width"), 1.0) / 2.0, num_or(field(o, "height"), 1.0) / 2.0);
|
||||
let a = field(o, "hostAngle").and_then(Value::as_f64).unwrap_or(0.0);
|
||||
let (c, s) = (jsnum::cos(a), jsnum::sin(a));
|
||||
[(-w, -h), (w, -h), (w, h), (-w, h)].iter().map(|(x, y)| (cx + x * c - y * s, cy + x * s + y * c)).collect()
|
||||
}
|
||||
|
||||
/// Lücke einer Wandöffnung (Vorschau, [144]): Rechteck über die volle Wanddicke um die Achse; in einer
|
||||
/// Bogenwand der Ringsektor-Abschnitt (Sehnen).
|
||||
fn opening_quad(root: &Map<String, Value>, p: &Project, o: &Value) -> Option<Vec<(f64, f64)>> {
|
||||
use crate::opening_geom::{opening_gap_quad, v, WallRef};
|
||||
let w = list(root, "walls").iter().find(|w| id_of(w) == wall_host(o))?;
|
||||
if let Some(ax @ crate::opening_slide::Axis::Arc(_)) = crate::opening_slide::Axis::of(w) {
|
||||
let (a, b) = (num_of(field(o, "position")), num_of(field(o, "width")));
|
||||
let half = wall_thickness(p, w) / 2.0;
|
||||
let n = 8;
|
||||
let ts: Vec<f64> = (0..=n).map(|i| a + b * i as f64 / n as f64).collect();
|
||||
let mut q: Vec<(f64, f64)> = ts.iter().map(|t| ax.point(*t, half)).collect();
|
||||
q.extend(ts.iter().rev().map(|t| ax.point(*t, -half)));
|
||||
return q.iter().all(|c| c.0.is_finite() && c.1.is_finite()).then_some(q);
|
||||
}
|
||||
let (s, e) = straight_wall(w)?;
|
||||
let wr = WallRef { start: v(s.0, s.1), end: v(e.0, e.1), total: wall_thickness(p, w), ref_off: 0.0 };
|
||||
let q = opening_gap_quad(&wr, num_of(field(o, "position")), num_of(field(o, "width")))?;
|
||||
@@ -1396,8 +1489,17 @@ mod tests {
|
||||
assert_eq!((&o["hostWallId"], &o["position"]), (&json!("v"), &json!(1.55)));
|
||||
// Wand im anderen Geschoss zählt nicht: ausserhalb jeder Wand → nur Gleiten (projiziert).
|
||||
assert_eq!(one(&run(json!([[1.45, 0], [2.45, 3]]), "move", sel.clone()))["hostWallId"], json!("w"));
|
||||
// Gesperrte Öffnung und Öffnung in Bogenwand bleiben.
|
||||
assert!(run(json!([[0, 0], [1, 0]]), "move", json!({"wallIds":[],"openingIds":["z","a"]})).is_empty());
|
||||
// Gesperrte Öffnung bleibt.
|
||||
assert!(run(json!([[0, 0], [1, 0]]), "move", json!({"wallIds":[],"openingIds":["z"]})).is_empty());
|
||||
// Bogenwand ([T2]): Ziel = Lotfuss auf dem Bogen, `position` = Bogenlänge; geklemmt an den Bogenenden.
|
||||
let arc = crate::opening_slide::Axis::of(&r["walls"][3]).unwrap();
|
||||
let (c, tg) = (arc.point(1.5, 0.0), arc.tangent(1.5));
|
||||
let mv = |k: f64| json!([[c.0, c.1], [c.0 + tg.0 * k, c.1 + tg.1 * k]]);
|
||||
let pos = one(&run(mv(0.3), "move", json!({"wallIds":[],"openingIds":["a"]})))["position"].as_f64().unwrap();
|
||||
assert!((pos - 1.3).abs() < 0.01, "{pos}");
|
||||
let o = one(&run(mv(20.0), "move", json!({"wallIds":[],"openingIds":["a"]})));
|
||||
assert!((o["position"].as_f64().unwrap() - (arc.len() - 1.0)).abs() < 1e-9 && o["hostWallId"] == "b");
|
||||
assert_eq!(one(&run(mv(-20.0), "move", json!({"wallIds":[],"openingIds":["a"]})))["position"], json!(0));
|
||||
// Drehen einer Öffnung allein: nichts.
|
||||
let req: TransformReq = serde_json::from_value(json!({"sel":sel,"op":"rotate","pts":[[0,0],[1,0],[0,1]],"mode":"move","count":1,"stamp":"s"})).unwrap();
|
||||
assert!(transform_ops(&r, &Project::default(), &req).is_empty());
|
||||
@@ -1415,6 +1517,115 @@ mod tests {
|
||||
assert!(!preview_pending(&r, &Project::default(), &req).shapes.buf.is_empty());
|
||||
}
|
||||
|
||||
/// [144] Überlappung: gleitend hält die Öffnung 5 cm vor der Nachbaröffnung an (mit Hinweis), Kopie
|
||||
/// rückt an die nächste freie Stelle; Bestand bleibt; mitbewegte Öffnungen zählen nicht.
|
||||
#[test]
|
||||
fn oeffnung_haelt_vor_der_nachbaroeffnung() {
|
||||
let r = root(json!({
|
||||
"walls":[{"id":"w","floorId":"eg","start":{"x":0,"y":0},"end":{"x":10,"y":0}}],
|
||||
"openings":[
|
||||
{"id":"d","hostWallId":"w","kind":"door","position":1,"width":1},
|
||||
{"id":"f","hostWallId":"w","kind":"window","position":4,"width":1}
|
||||
]}));
|
||||
let run = |pts: Value, mode: &str, ids: Value| {
|
||||
let req: TransformReq = serde_json::from_value(json!({"sel":{"wallIds":[],"openingIds":ids},"op":"move","pts":pts,"mode":mode,"count":1,"stamp":"s"})).unwrap();
|
||||
transform_result(&r, &Project::default(), &req)
|
||||
};
|
||||
let res = run(json!([[0, 0], [5, 0]]), "move", json!(["d"]));
|
||||
assert_eq!(res.notice, Some(crate::opening_slide::NOTICE_OVERLAP));
|
||||
assert_eq!(res.ops[0].to_json()["entity"]["position"], json!(2.95));
|
||||
// Frei: kein Hinweis.
|
||||
let res = run(json!([[0, 0], [1, 0]]), "move", json!(["d"]));
|
||||
assert_eq!((res.notice, res.ops[0].to_json()["entity"]["position"].clone()), (None, json!(2)));
|
||||
// Beide gewählt: gleiten zusammen, ohne Anschlag aneinander.
|
||||
let res = run(json!([[0, 0], [2.5, 0]]), "move", json!(["d", "f"]));
|
||||
assert_eq!(res.notice, None);
|
||||
let pos: Vec<Value> = res.ops.iter().map(|o| o.to_json()["entity"]["position"].clone()).collect();
|
||||
assert_eq!(pos, vec![json!(3.5), json!(6.5)]);
|
||||
// Kopie um 0.5 überlappte das Original: rückt an die nächste freie Stelle (2.05).
|
||||
let res = run(json!([[0, 0], [0.5, 0]]), "copy", json!(["d"]));
|
||||
let items = res.ops[0].to_json()["items"].clone();
|
||||
assert_eq!(items[0]["position"], json!(2.05));
|
||||
assert_eq!(res.notice, Some(crate::opening_slide::NOTICE_OVERLAP));
|
||||
}
|
||||
|
||||
/// [144] Bemassungs-Bezüge auf eine gleitende Öffnung (Leibung, gerade und Bogenwand) folgen über das
|
||||
/// Nachführen im Dokument — beim Verschieben-Befehl, beim Griff-Zug und bei der Objekt-Info-Position.
|
||||
#[test]
|
||||
fn bemassung_folgt_der_gleitenden_oeffnung() {
|
||||
use crate::document::Document;
|
||||
let r = json!({
|
||||
"walls":[{"id":"w","floorId":"eg","start":{"x":0,"y":0},"end":{"x":10,"y":0}},
|
||||
{"id":"b","floorId":"eg","start":{"x":0,"y":5},"end":{"x":4,"y":5},"bulge":1}],
|
||||
"openings":[{"id":"d","hostWallId":"w","kind":"door","position":1,"width":1},
|
||||
{"id":"a","hostWallId":"b","kind":"window","position":1,"width":1}],
|
||||
"drawings2d":[
|
||||
{"id":"m","levelId":"eg","geom":{"shape":"dimension","pts":[{"x":0,"y":-1},{"x":1,"y":-1},{"x":2,"y":-1}],"offset":0,
|
||||
"refs":[{"id":"w","feature":"wall","t":0,"d":1},{"id":"d","feature":"opening","index":0,"d":1},{"id":"d","feature":"opening","index":1,"d":1}]}},
|
||||
{"id":"k","levelId":"eg","geom":{"shape":"dimension","pts":[{"x":0,"y":5},{"x":1,"y":6}],"offset":0,
|
||||
"refs":[{"id":"a","feature":"opening","index":0},{"id":"a","feature":"opening","index":1}]}}
|
||||
]});
|
||||
let mut doc = Document::from_json(&r.to_string()).unwrap();
|
||||
let pts = |doc: &Document, id: &str| -> Vec<(f64, f64)> {
|
||||
let d = doc.root()["drawings2d"].as_array().unwrap().iter().find(|d| d["id"] == id).unwrap().clone();
|
||||
d["geom"]["pts"].as_array().unwrap().iter().map(|p| (p["x"].as_f64().unwrap(), p["y"].as_f64().unwrap())).collect()
|
||||
};
|
||||
let close = |a: (f64, f64), b: (f64, f64)| assert!((a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9, "{a:?} != {b:?}");
|
||||
// Bogen-Leibungen: erst einmal nachführen (Bogenpunkte statt Sehne).
|
||||
let arc = crate::opening_slide::Axis::of(&r["walls"][1]).unwrap();
|
||||
doc.commit(crate::dim_assoc::sync_ops(&doc.lookup()), None, 0.0, false).unwrap();
|
||||
close(pts(&doc, "k")[0], arc.point(1.0, 0.0));
|
||||
close(pts(&doc, "k")[1], arc.point(2.0, 0.0));
|
||||
// Verschieben-Befehl: Tür um 2 m → Kette folgt (Wandende bleibt).
|
||||
let req = json!({"cmd":"transform","sel":{"wallIds":[],"drawingId":null,"openingIds":["d"]},"op":"move","pts":[[0,0],[2,0]],"mode":"move","count":1,"stamp":"s"});
|
||||
let res = { let (p, lk) = doc.project_lookup().unwrap(); crate::commands::result(lk.root, p, &req.to_string()).unwrap() };
|
||||
doc.commit(res.ops, None, 1.0, false).unwrap();
|
||||
let q = pts(&doc, "m");
|
||||
close(q[0], (0.0, -1.0));
|
||||
close(q[1], (3.0, -1.0));
|
||||
close(q[2], (4.0, -1.0));
|
||||
// Griff-Zug und Objekt-Info-Position (grips.rs): gleicher Weg.
|
||||
let grip = |doc: &mut Document, req: Value| {
|
||||
let req: crate::grips::Request = serde_json::from_value(req).unwrap();
|
||||
let res = crate::grips::run(&doc.lookup(), &req).unwrap();
|
||||
doc.commit(res.ops, None, 2.0, false).unwrap();
|
||||
};
|
||||
grip(&mut doc, json!({"op":"openingSlide","id":"d","pt":[6.5,0.3]}));
|
||||
close(pts(&doc, "m")[1], (6.0, -1.0));
|
||||
grip(&mut doc, json!({"op":"openingPosition","id":"d","a":5}));
|
||||
close(pts(&doc, "m")[2], (6.0, -1.0));
|
||||
// Bogenwand: Fenster entlang des Bogens → Leibungen auf dem Bogen.
|
||||
grip(&mut doc, json!({"op":"openingPosition","id":"a","a":2.5}));
|
||||
close(pts(&doc, "k")[0], arc.point(2.5, 0.0));
|
||||
close(pts(&doc, "k")[1], arc.point(3.5, 0.0));
|
||||
// Rückgängig: Kette wieder bei der alten Lage.
|
||||
doc.undo();
|
||||
close(pts(&doc, "k")[0], arc.point(1.0, 0.0));
|
||||
}
|
||||
|
||||
/// [144] Dach-/Deckenöffnung allein verschieben: `hostPoint` wandert, im Umriss des Wirts gehalten.
|
||||
#[test]
|
||||
fn dachoeffnung_allein_verschieben() {
|
||||
let r = root(json!({
|
||||
"roofs":[{"id":"rf","outline":[{"x":0,"y":0},{"x":6,"y":0},{"x":6,"y":4},{"x":0,"y":4}]}],
|
||||
"openings":[{"id":"o","hostWallId":"","hostRoofId":"rf","hostPoint":{"x":1,"y":1},"width":0.8,"height":1.2}]}));
|
||||
let run = |pts: Value, mode: &str| {
|
||||
let req: TransformReq = serde_json::from_value(json!({"sel":{"wallIds":[],"openingIds":["o"]},"op":"move","pts":pts,"mode":mode,"count":1,"stamp":"s"})).unwrap();
|
||||
transform_ops(&r, &Project::default(), &req).iter().map(|o| o.to_json()).collect::<Vec<_>>()
|
||||
};
|
||||
let ops = run(json!([[0, 0], [2, 1]]), "move");
|
||||
assert_eq!(ops[0]["entity"]["hostPoint"], json!({"x":3,"y":2}));
|
||||
// Ausserhalb: an den Rand, 5 cm nach innen.
|
||||
let hp = run(json!([[0, 0], [20, 0]]), "move")[0]["entity"]["hostPoint"].clone();
|
||||
assert!((hp["x"].as_f64().unwrap() - 5.95).abs() < 0.02 && (hp["y"].as_f64().unwrap() - 1.0).abs() < 0.05, "{hp}");
|
||||
// Kopie: neue Öffnung im selben Dach.
|
||||
let ops = run(json!([[0, 0], [2, 0]]), "copy");
|
||||
assert_eq!((&ops[0]["items"][0]["hostRoofId"], &ops[0]["items"][0]["hostPoint"]), (&json!("rf"), &json!({"x":3,"y":1})));
|
||||
// Vorschau zeigt sie.
|
||||
let req: TransformReq = serde_json::from_value(json!({"sel":{"wallIds":[],"openingIds":["o"]},"op":"move","pts":[[0,0],[1,0]],"mode":"move","count":1,"stamp":"s"})).unwrap();
|
||||
assert!(!preview_pending(&r, &Project::default(), &req).shapes.buf.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verschieben_und_kopieren() {
|
||||
let r = root(json!({"walls":[{"id":"a","start":{"x":0,"y":0},"end":{"x":1,"y":0},"locked":false},{"id":"b","start":{"x":0,"y":0},"end":{"x":1,"y":0},"locked":true}]}));
|
||||
|
||||
@@ -47,9 +47,19 @@ pub fn ops(root: &Map<String, Value>, p: &Project, text: &str) -> Result<Vec<Op>
|
||||
})
|
||||
}
|
||||
|
||||
/// Wie [`ops`], als Antwort-JSON `{"ops": […]}` (Zahlen mit Nicht-endlich-Marken).
|
||||
/// Wie [`ops`], mit Hinweis-Schlüssel (i18n) für die Hülle; bisher nur Verschieben ([144]: Öffnung an
|
||||
/// der Nachbaröffnung angehalten).
|
||||
pub fn result(root: &Map<String, Value>, p: &Project, text: &str) -> Result<GripResult, String> {
|
||||
let v: Value = serde_json::from_str(text).map_err(|e| format!("cmdOps: {e}"))?;
|
||||
if v.get("group").is_none() && v.get("cmd").and_then(Value::as_str) == Some("transform") {
|
||||
return Ok(crate::cmd_transform::transform_result(root, p, &parse(&v, "transform")?));
|
||||
}
|
||||
Ok(GripResult { ops: ops(root, p, text)?, notice: None })
|
||||
}
|
||||
|
||||
/// Wie [`result`], als Antwort-JSON `{"ops": […], "notice": …}` (Zahlen mit Nicht-endlich-Marken).
|
||||
pub fn ops_json(root: &Map<String, Value>, p: &Project, text: &str) -> Result<String, String> {
|
||||
Ok(result_json(&GripResult { ops: ops(root, p, text)?, notice: None }))
|
||||
Ok(result_json(&result(root, p, text)?))
|
||||
}
|
||||
|
||||
/// Schneller Hasher für id-Mengen der Befehle (FNV-1a; je Mausschritt werden Tausende ids geprüft,
|
||||
|
||||
@@ -154,12 +154,13 @@ impl WallGeo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Leibungs-/Mittelpunkt einer Öffnung auf der Linie `layer` der Wirtswand (wie `autodim`).
|
||||
/// Leibungs-/Mittelpunkt einer Öffnung auf der Linie `layer` der Wirtswand (wie `autodim`). Bogenwand
|
||||
/// ([T2], [144]): `position` ist Bogenlänge auf der Achse, der Punkt liegt auf dem Versatzbogen.
|
||||
fn opening_point(lk: &Lookup, o: &Value, side: u32, layer: Option<u32>) -> Option<P> {
|
||||
let w = lk.find("walls", str_of(o, "hostWallId")?)?;
|
||||
let g = wall_geo(lk, w)?;
|
||||
let (a, b) = g.line(layer)?;
|
||||
let axis = dist(g.a, g.b);
|
||||
let axis = g.warc.as_ref().map_or_else(|| dist(g.a, g.b), |w| w.length());
|
||||
let (pos, width) = (num(o.get("position"))?, num(o.get("width"))?);
|
||||
let from = pos.min(axis).max(0.0);
|
||||
let to = (pos + width).min(axis).max(from);
|
||||
@@ -169,6 +170,10 @@ fn opening_point(lk: &Lookup, o: &Value, side: u32, layer: Option<u32>) -> Optio
|
||||
2 => (from + to) / 2.0,
|
||||
_ => return None,
|
||||
};
|
||||
if let Some(w) = &g.warc {
|
||||
let q = w.point(s, g.offset(layer)?);
|
||||
return Some((q.x, q.y));
|
||||
}
|
||||
let u = unit(a, b)?;
|
||||
Some(add(a, u, s))
|
||||
}
|
||||
|
||||
@@ -358,6 +358,18 @@ pub fn run(lk: &Lookup, req: &Request) -> Result<GripResult, String> {
|
||||
}
|
||||
"wallThickness" => wall_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.new_name.clone()).into(),
|
||||
"ceilingThickness" => ceiling_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.new_name.clone()).into(),
|
||||
// [144] Wandöffnung gleiten lassen: Griff-Zug nach `pt` bzw. Objekt-Info-Position `a` (ab
|
||||
// Wandanfang; Bogenwand: Bogenlänge). Geklemmt auf die Wand und vor der Nachbaröffnung.
|
||||
"openingSlide" | "openingPosition" => {
|
||||
let Some(o) = r.s("id").and_then(|id| lk.find("openings", id)).filter(|o| !crate::json_util::truthy(field(o, "locked"))) else {
|
||||
return Ok(GripResult::default());
|
||||
};
|
||||
let want = if op == "openingSlide" { crate::opening_slide::grip_want(root, o, r.p("pt")) } else { Some(r.n("a")).filter(|v| v.is_finite()) };
|
||||
let Some(placed) = want.and_then(|w| crate::opening_slide::slide_to(root, o, w)) else { return Ok(GripResult::default()) };
|
||||
let v = with(o, "position", js_num(placed.position));
|
||||
let ops = if v == *o { vec![] } else { vec![replace("openings", v)] };
|
||||
GripResult { ops, notice: placed.clamped.then_some(crate::opening_slide::NOTICE_OVERLAP) }
|
||||
}
|
||||
other => return Err(format!("Unbekannte Griff-Änderung: {other}")),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -120,6 +120,7 @@ pub mod surface_pattern;
|
||||
pub mod surface_pattern3d;
|
||||
pub mod standards;
|
||||
pub mod dim_assoc;
|
||||
pub mod opening_slide;
|
||||
|
||||
#[cfg(feature = "web")]
|
||||
mod web;
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
//! Wandöffnungen in ihrer Wand verschieben ([144]): gemeinsamer Weg für den Verschieben-Befehl
|
||||
//! (`cmd_transform`), den Griff-Zug und das Objekt-Info-Feld „Position" (`grips.rs`).
|
||||
//!
|
||||
//! - **Wandachse** gerade oder als Bogen ([T2]): `position` ist bei Bogenwänden die Bogenlänge auf der
|
||||
//! Achse ab `start` (wie die abgewickelte Wand im Grundriss), die Wandlänge die Bogenlänge.
|
||||
//! - **Überlappung**: eine gleitende Öffnung hält vor der Nachbaröffnung derselben Wand an und lässt
|
||||
//! einen Steg von [`MIN_WEB`]; schon überlappende Daten (Bestand) bleiben, wie sie sind.
|
||||
//! - **Dach-/Deckenöffnungen**: Mittelpunkt im Umriss des Wirts halten ([`clamp_inside`]).
|
||||
|
||||
use crate::json_util::{field, num_of};
|
||||
use crate::ops::id_of;
|
||||
use crate::wall_arc::WallArc;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
type P = (f64, f64);
|
||||
|
||||
/// Kleinster Steg zwischen zwei Öffnungen derselben Wand (Meter).
|
||||
pub const MIN_WEB: f64 = 0.05;
|
||||
/// Hinweis-Schlüssel (i18n), wenn eine Öffnung an der Nachbaröffnung anhält.
|
||||
pub const NOTICE_OVERLAP: &str = "opening.overlapClamped";
|
||||
/// Hinweis-Schlüssel, wenn in der Zielwand kein Platz ist.
|
||||
pub const NOTICE_NO_ROOM: &str = "opening.noRoom";
|
||||
|
||||
const EPS: f64 = 1e-9;
|
||||
|
||||
/// Wandachse: Strecke oder Bogen.
|
||||
pub enum Axis {
|
||||
Line { s: P, u: P, len: f64 },
|
||||
Arc(WallArc),
|
||||
}
|
||||
|
||||
impl Axis {
|
||||
/// Achse der Wand `w` (`start`, `end`, `bulge`); `None` bei entarteter Wand.
|
||||
pub fn of(w: &Value) -> Option<Axis> {
|
||||
let pt = |k: &str| -> Option<P> {
|
||||
let v = field(w, k)?;
|
||||
let (x, y) = (field(v, "x")?.as_f64()?, field(v, "y")?.as_f64()?);
|
||||
(x.is_finite() && y.is_finite()).then_some((x, y))
|
||||
};
|
||||
let (s, e) = (pt("start")?, pt("end")?);
|
||||
let bulge = field(w, "bulge").and_then(Value::as_f64);
|
||||
if crate::wall_arc::is_arc_bulge(bulge) {
|
||||
let a = WallArc::of(kernel2d::Vec2::new(s.0, s.1), kernel2d::Vec2::new(e.0, e.1), bulge)?;
|
||||
return Some(Axis::Arc(a));
|
||||
}
|
||||
let len = crate::jsmath::hypot2(e.0 - s.0, e.1 - s.1);
|
||||
(len > EPS && len.is_finite()).then(|| Axis::Line { s, u: ((e.0 - s.0) / len, (e.1 - s.1) / len), len })
|
||||
}
|
||||
|
||||
/// Länge der Achse (Bogen: Bogenlänge).
|
||||
pub fn len(&self) -> f64 {
|
||||
match self {
|
||||
Axis::Line { len, .. } => *len,
|
||||
Axis::Arc(a) => a.length(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Punkt auf der Achse bei Lauflänge `t`, quer um `n` (linke Normale) versetzt.
|
||||
pub fn point(&self, t: f64, n: f64) -> P {
|
||||
match self {
|
||||
Axis::Line { s, u, .. } => (s.0 + u.0 * t - u.1 * n, s.1 + u.1 * t + u.0 * n),
|
||||
Axis::Arc(a) => {
|
||||
let q = a.point(t, n);
|
||||
(q.x, q.y)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Einheits-Tangente (Laufrichtung) bei `t`.
|
||||
pub fn tangent(&self, t: f64) -> P {
|
||||
match self {
|
||||
Axis::Line { u, .. } => *u,
|
||||
Axis::Arc(a) => {
|
||||
let v = a.tangent(t);
|
||||
(v.x, v.y)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lauflänge des Lotfusspunkts von `p` (ungeklemmt) und Abstand von `p` zur Achse (Lotfuss auf die
|
||||
/// Achse geklemmt).
|
||||
pub fn local(&self, p: P) -> (f64, f64) {
|
||||
let t = match self {
|
||||
Axis::Line { s, u, .. } => (p.0 - s.0) * u.0 + (p.1 - s.1) * u.1,
|
||||
Axis::Arc(a) => a.local(kernel2d::Vec2::new(p.0, p.1)).0,
|
||||
};
|
||||
let q = self.point(t.clamp(0.0, self.len()), 0.0);
|
||||
(t, crate::jsmath::hypot2(p.0 - q.0, p.1 - q.1))
|
||||
}
|
||||
}
|
||||
|
||||
/// Belegte Abschnitte `[Anfang, Ende]` der übrigen Öffnungen in Wand `host` (ohne `skip`).
|
||||
fn neighbours(root: &Map<String, Value>, host: &str, skip: &dyn Fn(&str) -> bool) -> Vec<(f64, f64)> {
|
||||
root.get("openings")
|
||||
.and_then(Value::as_array)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter(|o| field(o, "hostWallId").and_then(Value::as_str) == Some(host))
|
||||
.filter(|o| !id_of(o).is_some_and(skip))
|
||||
.filter_map(|o| {
|
||||
let (a, w) = (num_of(field(o, "position")), num_of(field(o, "width")));
|
||||
(a.is_finite() && w.is_finite() && w > 0.0).then_some((a, a + w))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ergebnis der Überlappungs-Regel: neue `position` und ob eine Nachbaröffnung sie begrenzt hat.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Placed {
|
||||
pub position: f64,
|
||||
pub clamped: bool,
|
||||
}
|
||||
|
||||
/// `want` (Anfang einer Öffnung der Breite `width` in Wand `host` mit Länge `len`) gegen die Nachbarn
|
||||
/// prüfen. Gleitet die Öffnung von `from` aus (gleiche Wand), hält sie vor dem ersten Nachbarn in
|
||||
/// Laufrichtung mit Steg [`MIN_WEB`] an; Nachbarn, mit denen sie schon bei `from` überlappt (Bestand),
|
||||
/// zählen nicht. Ohne `from` (neue Wand, Kopie) rückt sie an die nächste freie Stelle; `None`, wenn
|
||||
/// keine passt. `skip`: Öffnungen, die nicht zählen (die Öffnung selbst, mitbewegte).
|
||||
pub fn place(root: &Map<String, Value>, host: &str, len: f64, width: f64, from: Option<f64>, want: f64, skip: &dyn Fn(&str) -> bool) -> Option<Placed> {
|
||||
let max = len - width;
|
||||
if !(max > -EPS && want.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let max = max.max(0.0);
|
||||
let want = want.clamp(0.0, max);
|
||||
// Gesperrte Anfangslagen je Nachbar: offenes Intervall (lo, hi).
|
||||
let blocked: Vec<(f64, f64)> = neighbours(root, host, skip).into_iter().map(|(a, b)| (a - width - MIN_WEB, b + MIN_WEB)).collect();
|
||||
let inside = |x: f64, (lo, hi): (f64, f64)| x > lo + EPS && x < hi - EPS;
|
||||
if let Some(from) = from.filter(|f| f.is_finite()) {
|
||||
let ahead = blocked.iter().filter(|b| !inside(from, **b));
|
||||
let pos = if want > from {
|
||||
ahead.filter(|(lo, _)| *lo >= from - EPS).map(|(lo, _)| *lo).fold(want, f64::min)
|
||||
} else {
|
||||
ahead.filter(|(_, hi)| *hi <= from + EPS).map(|(_, hi)| *hi).fold(want, f64::max)
|
||||
};
|
||||
return Some(Placed { position: pos, clamped: (pos - want).abs() > EPS });
|
||||
}
|
||||
let free = |x: f64| x >= -EPS && x <= max + EPS && !blocked.iter().any(|b| inside(x, *b));
|
||||
std::iter::once(want)
|
||||
.chain(blocked.iter().flat_map(|(lo, hi)| [*lo, *hi]))
|
||||
.filter(|x| free(*x))
|
||||
.min_by(|a, b| (a - want).abs().total_cmp(&(b - want).abs()))
|
||||
.map(|x| Placed { position: x.clamp(0.0, max), clamped: (x - want).abs() > EPS })
|
||||
}
|
||||
|
||||
/// Öffnung `o` in ihrer Wand auf den Anfang `want` setzen (gleitend ab ihrer jetzigen Lage; geklemmt auf
|
||||
/// die Wand und vor den Nachbarn). `None`: Wirt fehlt oder die Öffnung passt nicht in die Wand.
|
||||
pub fn slide_to(root: &Map<String, Value>, o: &Value, want: f64) -> Option<Placed> {
|
||||
let host = field(o, "hostWallId").and_then(Value::as_str).filter(|h| !h.is_empty())?;
|
||||
let w = root.get("walls")?.as_array()?.iter().find(|w| id_of(w) == Some(host))?;
|
||||
let axis = Axis::of(w)?;
|
||||
let width = num_of(field(o, "width"));
|
||||
let from = num_of(field(o, "position"));
|
||||
let me = id_of(o).unwrap_or("");
|
||||
place(root, host, axis.len(), width, from.is_finite().then_some(from), want, &|id| id == me)
|
||||
}
|
||||
|
||||
/// Neuer Anfang, wenn der Mittelpunkt-Griff von `o` nach `pt` gezogen wird (Lotfuss auf die Achse,
|
||||
/// Bogenwand: nächster Punkt auf dem Bogen).
|
||||
pub fn grip_want(root: &Map<String, Value>, o: &Value, pt: P) -> Option<f64> {
|
||||
let host = field(o, "hostWallId").and_then(Value::as_str)?;
|
||||
let w = root.get("walls")?.as_array()?.iter().find(|w| id_of(w) == Some(host))?;
|
||||
let axis = Axis::of(w)?;
|
||||
let t = axis.local(pt).0 - num_of(field(o, "width")) / 2.0;
|
||||
t.is_finite().then_some(t)
|
||||
}
|
||||
|
||||
/// Punkt im Umriss lassen: ausserhalb → nächster Randpunkt, 5 cm nach innen gerückt (zum Schwerpunkt der
|
||||
/// Ecken). Wie `clampInside` (`src/plan/surfaceOpening.ts`, Griff-Zug der Dach-/Deckenöffnung).
|
||||
pub fn clamp_inside(p: P, ring: &[P]) -> P {
|
||||
if ring.len() < 3 {
|
||||
return p;
|
||||
}
|
||||
let mut inside = false;
|
||||
let mut j = ring.len() - 1;
|
||||
for i in 0..ring.len() {
|
||||
let (a, b) = (ring[i], ring[j]);
|
||||
if (a.1 > p.1) != (b.1 > p.1) && p.0 < (b.0 - a.0) * (p.1 - a.1) / (b.1 - a.1) + a.0 {
|
||||
inside = !inside;
|
||||
}
|
||||
j = i;
|
||||
}
|
||||
if inside {
|
||||
return p;
|
||||
}
|
||||
let mut best = ring[0];
|
||||
let mut best_d = f64::INFINITY;
|
||||
for i in 0..ring.len() {
|
||||
let (a, b) = (ring[i], ring[(i + 1) % ring.len()]);
|
||||
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
|
||||
let l2 = dx * dx + dy * dy;
|
||||
let t = if l2 > 0.0 { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let q = (a.0 + dx * t, a.1 + dy * t);
|
||||
let dd = (q.0 - p.0).powi(2) + (q.1 - p.1).powi(2);
|
||||
if dd < best_d {
|
||||
best_d = dd;
|
||||
best = q;
|
||||
}
|
||||
}
|
||||
let n = ring.len() as f64;
|
||||
let (cx, cy) = (ring.iter().map(|q| q.0).sum::<f64>() / n, ring.iter().map(|q| q.1).sum::<f64>() / n);
|
||||
let l = crate::jsmath::hypot2(cx - best.0, cy - best.1);
|
||||
if l > 0.05 {
|
||||
(best.0 + (cx - best.0) / l * 0.05, best.1 + (cy - best.1) / l * 0.05)
|
||||
} else {
|
||||
best
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn root(v: Value) -> Map<String, Value> {
|
||||
v.as_object().unwrap().clone()
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64) {
|
||||
assert!((a - b).abs() < 1e-9, "{a} != {b}");
|
||||
}
|
||||
|
||||
/// Nachbar bei 2..3 in einer 10-m-Wand, Breite 1: gleitend hält die Öffnung mit 5 cm Steg an.
|
||||
#[test]
|
||||
fn haelt_vor_dem_nachbarn() {
|
||||
let r = root(json!({"walls":[{"id":"w","start":{"x":0,"y":0},"end":{"x":10,"y":0}}],
|
||||
"openings":[{"id":"a","hostWallId":"w","position":0,"width":1},{"id":"n","hostWallId":"w","position":2,"width":1},
|
||||
{"id":"x","hostWallId":"w","position":2.5,"width":1}]}));
|
||||
let skip_a = |id: &str| id == "a" || id == "x";
|
||||
let p = place(&r, "w", 10.0, 1.0, Some(0.0), 5.0, &skip_a).unwrap();
|
||||
near(p.position, 0.95);
|
||||
assert!(p.clamped);
|
||||
// Frei davor: kein Anschlag.
|
||||
let p = place(&r, "w", 10.0, 1.0, Some(0.0), 0.5, &skip_a).unwrap();
|
||||
assert_eq!(p, Placed { position: 0.5, clamped: false });
|
||||
// Von rechts kommend: hält bei 3.05.
|
||||
let p = place(&r, "w", 10.0, 1.0, Some(6.0), 0.0, &skip_a).unwrap();
|
||||
near(p.position, 3.05);
|
||||
// Bestand: „x" überlappt „n" schon — beim Wegziehen kein Anschlag an „n".
|
||||
let p = place(&r, "w", 10.0, 1.0, Some(2.5), 6.0, &|id| id == "x").unwrap();
|
||||
assert_eq!(p, Placed { position: 6.0, clamped: false });
|
||||
// Ohne Ausgang (Wandwechsel): nächste freie Stelle.
|
||||
let p = place(&r, "w", 10.0, 1.0, None, 2.2, &skip_a).unwrap();
|
||||
near(p.position, 3.05);
|
||||
let p = place(&r, "w", 10.0, 1.0, None, 1.5, &skip_a).unwrap();
|
||||
near(p.position, 0.95);
|
||||
// Kein Platz: 3.2-m-Wand, Breite 2.5, Nachbar bei 2..3.
|
||||
assert!(place(&r, "w", 3.2, 2.5, None, 0.0, &skip_a).is_none());
|
||||
}
|
||||
|
||||
/// Bogenwand: Lauflänge = Bogenlänge, Griff-Punkt auf dem Bogen, Klemmen am Bogenende.
|
||||
#[test]
|
||||
fn bogenwand_bogenlaenge() {
|
||||
// Halbkreis von (0,0) nach (4,0), bulge 1 → Radius 2, Länge 2π.
|
||||
let r = root(json!({"walls":[{"id":"b","start":{"x":0,"y":0},"end":{"x":4,"y":0},"bulge":1}],
|
||||
"openings":[{"id":"o","hostWallId":"b","position":1,"width":1}]}));
|
||||
let w = &r["walls"][0];
|
||||
let ax = Axis::of(w).unwrap();
|
||||
near(ax.len(), 2.0 * std::f64::consts::PI);
|
||||
let o = &r["openings"][0];
|
||||
// Scheitel (2, 2), Griff ausserhalb gezogen: Lotfuss auf dem Bogen.
|
||||
let m = ax.point(std::f64::consts::PI, 0.0);
|
||||
near(m.0, 2.0);
|
||||
near(m.1.abs(), 2.0);
|
||||
let want = grip_want(&r, o, (m.0, m.1 * 1.15)).unwrap();
|
||||
near(want, std::f64::consts::PI - 0.5);
|
||||
let p = slide_to(&r, o, 99.0).unwrap();
|
||||
near(p.position, 2.0 * std::f64::consts::PI - 1.0);
|
||||
assert_eq!(slide_to(&r, o, -3.0).unwrap().position, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn im_umriss_halten() {
|
||||
let ring = [(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)];
|
||||
assert_eq!(clamp_inside((1.0, 1.0), &ring), (1.0, 1.0));
|
||||
let q = clamp_inside((6.0, 2.0), &ring);
|
||||
near(q.0, 3.95);
|
||||
near(q.1, 2.0);
|
||||
}
|
||||
}
|
||||
@@ -840,7 +840,7 @@ fn opening_selection(lk: &Lookup, o: &Value) -> Result<J, String> {
|
||||
.o("hostWallName", floor.map_or_else(|| field(o, "hostWallId").cloned(), |f| Some(Value::from(field(f, "name").map_or("undefined".into(), js_text)))))
|
||||
.raw("position", o, "position")
|
||||
// Länge der (geraden) Wirtswand ([144]): Objekt-Info rechnet „Abstand ab Wandende“ und klemmt.
|
||||
.o("wallLength", wall.and_then(straight_len).map(js_num))
|
||||
.o("wallLength", wall.and_then(axis_len).map(js_num))
|
||||
.raw("width", o, "width")
|
||||
.raw("height", o, "height")
|
||||
.raw("sillHeight", o, "sillHeight")
|
||||
@@ -873,13 +873,8 @@ fn opening_selection(lk: &Lookup, o: &Value) -> Result<J, String> {
|
||||
}
|
||||
|
||||
/// Achslänge einer geraden Wand; `None` bei Bogenwänden (dort ist `position` keine Sehnenlänge).
|
||||
fn straight_len(w: &Value) -> Option<f64> {
|
||||
if field(w, "bulge").and_then(Value::as_f64).is_some_and(|b| b.abs() > 1e-12) {
|
||||
return None;
|
||||
}
|
||||
let (s, e) = (xy(field(w, "start")?), xy(field(w, "end")?));
|
||||
let len = crate::jsmath::hypot2(e.0 - s.0, e.1 - s.1);
|
||||
len.is_finite().then_some(len)
|
||||
fn axis_len(w: &Value) -> Option<f64> {
|
||||
crate::opening_slide::Axis::of(w).map(|a| a.len()).filter(|l| l.is_finite())
|
||||
}
|
||||
|
||||
/// Achsversatz der Schichtstapelung (`wallReferenceOffset`): freier Versatz (auf die Dicke geklemmt),
|
||||
@@ -1380,12 +1375,14 @@ mod tests {
|
||||
// Unbekannter Wandtyp: dieselbe Meldung wie TS.
|
||||
let mut bad = r.clone();
|
||||
bad["walls"][0]["wallTypeId"] = json!("x");
|
||||
assert_eq!(sel(&bad, json!({"wallIds": ["w"]})).unwrap_err(), "Unbekannter Wandtyp: x"); // [144] Öffnung: Länge der Wirtswand für „Abstand ab Wandende“ (Bogenwand: keine).
|
||||
assert_eq!(sel(&bad, json!({"wallIds": ["w"]})).unwrap_err(), "Unbekannter Wandtyp: x"); // [144] Öffnung: Länge der Wirtswand für „Abstand ab Wandende“ (Bogenwand: Bogenlänge).
|
||||
let o = sel(&r, json!({"openingId": "o"})).unwrap();
|
||||
assert_eq!(o["opening"]["wallLength"], json!(5));
|
||||
let mut arc = r.clone();
|
||||
arc["walls"][0]["bulge"] = json!(0.4);
|
||||
assert!(sel(&arc, json!({"openingId": "o"})).unwrap()["opening"].get("wallLength").is_none());
|
||||
let len = sel(&arc, json!({"openingId": "o"})).unwrap()["opening"]["wallLength"].as_f64().unwrap();
|
||||
let a = crate::wall_arc::WallArc::of(kernel2d::Vec2::new(0.0, 0.0), kernel2d::Vec2::new(4.0, 3.0), Some(0.4)).unwrap();
|
||||
assert!(len > 5.0 && (len - a.length()).abs() < 1e-9, "{len}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -13,11 +13,10 @@ pub fn doc_cmd_commit(h: u32, req_json: &str, key: &str, now_ms: f64) -> String
|
||||
let key = (!key.is_empty()).then_some(key);
|
||||
let now = if now_ms.is_finite() { now_ms } else { 0.0 };
|
||||
let out = with_doc(h, |d| -> Result<String, String> {
|
||||
let ops = {
|
||||
let res = {
|
||||
let (p, lk) = d.project_lookup()?;
|
||||
crate::commands::ops(lk.root, p, req_json)?
|
||||
crate::commands::result(lk.root, p, req_json)?
|
||||
};
|
||||
let res = crate::grips::GripResult { ops, notice: None };
|
||||
let text = crate::grips::result_json(&res);
|
||||
if res.ops.is_empty() {
|
||||
return Ok(text);
|
||||
|
||||
@@ -458,20 +458,21 @@ export class ProjectDocument {
|
||||
/**
|
||||
* Befehl rechnen und anwenden ([K4] S3, `doc_cmd_commit`): wie {@link commitGrip} — ein Kern-Aufruf
|
||||
* statt Ops hin (Rechnung) und zurück (Commit). Ergebnis: neues Projekt und die angewendeten Ops (leer
|
||||
* = nichts zu tun, dann `project === base`) oder die Meldungen der Prüfung.
|
||||
* = nichts zu tun, dann `project === base`), ein Hinweis-Schlüssel (i18n, z. B. [144] Öffnung an der
|
||||
* Nachbaröffnung angehalten) oder die Meldungen der Prüfung.
|
||||
*/
|
||||
commitCmd(base: Project, req: object, coalesceKey: string | undefined, now: number): { project: Project; ops: CoreOp[] } | { problems: string[] } {
|
||||
commitCmd(base: Project, req: object, coalesceKey: string | undefined, now: number): { project: Project; ops: CoreOp[]; notice?: string } | { problems: string[] } {
|
||||
this.ensure(base);
|
||||
if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] };
|
||||
const out = core().doc_cmd_commit(this.handle, toMarkedJson(req), coalesceKey ?? "", now);
|
||||
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
|
||||
const r = fromMarkedJson<{ ops: CoreOp[] } | { problems: string[] }>(out);
|
||||
const r = fromMarkedJson<{ ops: CoreOp[]; notice?: string } | { problems: string[] }>(out);
|
||||
if ("problems" in r) return r;
|
||||
if (r.ops.length === 0) return { project: base, ops: r.ops };
|
||||
if (r.ops.length === 0) return { project: base, ops: r.ops, notice: r.notice };
|
||||
const extra = this.lastExtra();
|
||||
const project = this.withExtra(applyOps(base, r.ops), extra);
|
||||
this.setMirror(project);
|
||||
return { project, ops: extra.length ? [...r.ops, ...extra] : r.ops };
|
||||
return { project, ops: extra.length ? [...r.ops, ...extra] : r.ops, notice: r.notice };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -522,7 +522,8 @@ export function createProjectSlice(
|
||||
|
||||
// Befehl ([K4] S3, `commands.rs`): der Kern rechnet ihn auf dem Dokument und wendet ihn im selben
|
||||
// Aufruf an (`cmdMutation`); Prüfung, Verlauf und Meldungen wie `commitOps`.
|
||||
const applyCmd = (req: object, coalesceKey?: string) =>
|
||||
const applyCmd = (req: object, coalesceKey?: string) => {
|
||||
let notice: string | undefined;
|
||||
set((s) => {
|
||||
const doc = storeDocument(s.project);
|
||||
const cmd = (req as { cmd?: unknown }).cmd;
|
||||
@@ -535,11 +536,14 @@ export function createProjectSlice(
|
||||
queueMicrotask(() => get().notify(`${t("project.change.rejected")} ${problems[0]}`, "error"));
|
||||
return {};
|
||||
}
|
||||
notice = res.notice;
|
||||
if (res.ops.length === 0) return {};
|
||||
opLog.push(res.ops);
|
||||
if (opLog.length > OP_LOG_LIMIT) opLog.shift();
|
||||
return { project: res.project, ...historyPatch(doc) };
|
||||
});
|
||||
noticeOnce(notice);
|
||||
};
|
||||
|
||||
// Änderung direkt als Ops (ohne Differenz), s. `ProjectSlice.applyChange`.
|
||||
const applyChange = (
|
||||
@@ -547,6 +551,16 @@ export function createProjectSlice(
|
||||
coalesceKey?: string,
|
||||
) => set((s) => commitOps(s, typeof ops === "function" ? ops(s.project) : ops, coalesceKey));
|
||||
|
||||
// Hinweis aus dem Kern (i18n-Schlüssel) melden — derselbe höchstens alle 2 s (Griff-Zug: je Mausschritt).
|
||||
let lastNotice = { key: "", at: 0 };
|
||||
const noticeOnce = (notice: string | undefined) => {
|
||||
if (!notice) return;
|
||||
const now = Date.now();
|
||||
if (notice === lastNotice.key && now - lastNotice.at < 2000) return;
|
||||
lastNotice = { key: notice, at: now };
|
||||
get().notify(t(notice as Parameters<typeof t>[0]), "warning");
|
||||
};
|
||||
|
||||
// Griff-Änderung ([K4] S3): der Kern rechnet sie auf dem Dokument und wendet sie im selben Aufruf an
|
||||
// (`grips.rs`, ein WASM-Aufruf je Mausschritt); Prüfung, Verlauf und Meldungen wie `commitOps`.
|
||||
const applyGrip = (req: GripRequest, coalesceKey?: string) => {
|
||||
@@ -566,7 +580,7 @@ export function createProjectSlice(
|
||||
if (opLog.length > OP_LOG_LIMIT) opLog.shift();
|
||||
return { project: res.project, ...historyPatch(doc) };
|
||||
});
|
||||
if (notice) get().notify(t(notice as Parameters<typeof t>[0]), "warning");
|
||||
noticeOnce(notice);
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
Reference in new issue
Block a user