[36][34][38] Merge: View Range je Geschoss, Ansichtsvorlagen, assoziative Bemassung

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-30 06:16:00 +00:00
commit 31caeea299
29 files changed
+1281 -40

No files matched your search

+12 -1
View File
@@ -1419,7 +1419,17 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
(nur ausblenden), Dächer (nur ausblenden) und Extrusionen. Ohne Grenzen unverändert. CLI-Plan geprüft (Linux).
Offen: Dach/Decke über/unter gestrichelt statt nur ausblenden, Schnitt/Ansicht, Raum/Fenster eigenständig. · M
- ○ **[37] Beschriftung in Papiergrösse.** · M
- ○ **[38] Assoziative Bemassung.** · L · nach [10].
- ✅ **[38] Assoziative Bemassung.** (30.10.) Rust `dim_assoc.rs`: gefangene Bemassungspunkte tragen
`Dimension.refs` (je Punkt `DimRef`: Wand-Linie/-Ende, Wandecke = Schnitt zweier Wandlinien, Öffnungs-
Leibung/-Mitte, Stütze/Decke/Dach/Raum Ecke/Kante/Mitte, 2D-Eckpunkt/-Kante/-Mittelpunkt; Anhängen über
Deckungsgleichheit des Fangpunkts). `Document::commit` führt `pts` im selben Undo-Schritt nach
(`doc_last_extra` → TS-Leseansicht), Plan/DXF/Griffe lesen damit die aufgelöste Lage. Ungültiger Bezug →
Punkt bleibt, `lost` + rote Marke nur am Bildschirm, Objekt-Info listet die Punkte; „Bemassung lösen"
(Befehl `dimdetach`, Kürzel `bml`, Kontextmenü, Objekt-Info). Autodim [81] hängt an Ecken/Leibungen.
Transformieren: Bezüge bleiben bei Verschieben/Drehen zusammen mit den Elementen, sonst (allein, Spiegeln,
Skalieren) gelöst; Kopien hängen an mitkopierten Elementen; ein von Hand gezogener Punkt ist frei.
Offen: Bogenwände/Treppen nicht anhängbar, Achsraster fehlt im Modell; nur Linux/Chromium geprüft (Marke
am Bildschirm nicht auf macOS/Metal angesehen). · L
- ○ **[39] Auswahl gehört zum Modell.** · M
- ◐ **[40] Ansichten duplizieren.** Ebenen duplizieren vorhanden. · S
- ◐ **[76] Vektorfang auf PDF.** (28.10.) Rust `fileio/pdf_object.rs` + `pdf_vector.rs` (eigener Leser:
@@ -1549,6 +1559,7 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
- ○ **[80] PDF mit Ebenen.** · M
- ◐ **[81] Automatische Aussenbemassung.** (27.10.) Befehl `autodim` (Kürzel `ab`): je Seite Öffnungs-,
Vor-/Rücksprung- und Gesamtkette. Offen: schiefe Wände, Massstab aus der Ansicht statt fest 1:100.
(30.10.) Ketten assoziativ [38] (Ecken/Leibungen, nur mittige Wände).
- ○ **[82] Grafische Legenden.** · M
- ○ **[65] Explosionsaxonometrie.** · S–M
- ○ **[66] Präsentationspläne mit einem Klick.** · M
+78
View File
@@ -0,0 +1,78 @@
// [38] Assoziative Bemassung: Wand zeichnen, ihre Länge mit Fang bemassen, Wand am Anfangsgriff strecken →
// die Masszahl folgt.
import { blurFocus, commandInput, expect, finishCommand, openTab, startNewProject, test, typeCommand } from "./app";
import type { Page } from "@playwright/test";
/** Modellpunkt (m) → Client-Pixel (wie `kataster.spec.ts::screenOf`). */
async function screenOf(page: Page, x: number, y: number): Promise<{ x: number; y: number }> {
return page.locator("svg.plan-svg").evaluate(
(el, [mx, my]) => {
const [vx, vy, vw, vh] = el.getAttribute("viewBox")!.split(/\s+/).map(Number);
const ox = Number(el.getAttribute("data-origin-x") ?? 0);
const oy = Number(el.getAttribute("data-origin-y") ?? 0);
const r = el.getBoundingClientRect();
const s = Math.min(r.width / vw, r.height / vh);
return {
x: r.left + (r.width - vw * s) / 2 + (mx * 90 - ox - vx) * s,
y: r.top + (r.height - vh * s) / 2 + (-my * 90 - oy - vy) * s,
};
},
[x, y],
);
}
async function clickModel(page: Page, x: number, y: number): Promise<void> {
const p = await screenOf(page, x, y);
await page.mouse.move(p.x, p.y);
await page.mouse.click(p.x, p.y);
}
/** Zahlen-Texte des Plans (Masszahlen). */
const numbers = (page: Page) =>
page.locator("svg.plan-svg text").evaluateAll((els) => els.map((e) => e.textContent ?? "").filter((s) => /^\d+\.\d\d$/.test(s)));
test("Bemassung an Wandenden folgt dem Strecken der Wand per Griff", async ({ page }) => {
await startNewProject(page);
await openTab(page, "Elemente");
await page.getByRole("button", { name: "Wand", exact: true }).click();
await commandInput(page).focus();
await typeCommand(page, "0,0");
await typeCommand(page, "5,0");
await finishCommand(page);
await blurFocus(page);
await page.getByTitle("Auf Plan einpassen").click();
// Bemassung: beide Wandenden mit der Maus anklicken (Endpunkt-Fang), Abstand 1 m.
await commandInput(page).focus();
await typeCommand(page, "dim");
await expect(page.locator(".cmdline-prompt")).toHaveText(/Erster Punkt/);
await clickModel(page, 0, 0);
await clickModel(page, 5, 0);
await commandInput(page).press("Enter");
await expect(page.locator(".cmdline-prompt")).toHaveText(/Lage der Masslinie/);
await typeCommand(page, "1");
await expect.poll(() => numbers(page)).toContain("5.00");
// Wand wählen, Anfangsgriff 0.5 m nach links ziehen (Griff folgt bis zum zweiten Klick).
await blurFocus(page);
await page.keyboard.press("Escape");
await clickModel(page, 2.5, 0);
await expect.poll(() => page.locator(".plan-grip").count()).toBeGreaterThan(1);
const from = await screenOf(page, 0, 0);
const to = await screenOf(page, -0.5, 0);
await page.mouse.move(from.x, from.y);
await page.mouse.down();
await page.mouse.move((from.x + to.x) / 2, from.y, { steps: 4 });
await page.mouse.move(to.x, to.y, { steps: 4 });
await page.mouse.up();
await page.mouse.click(to.x, to.y);
await expect.poll(() => numbers(page)).not.toContain("5.00");
const after = (await numbers(page)).map(Number);
expect(after.some((v) => Math.abs(v - 5.5) < 0.05)).toBe(true);
// Rückgängig: Wand und Masszahl zurück (ein Schritt).
await blurFocus(page);
await page.keyboard.press("ControlOrMeta+z");
await expect.poll(() => numbers(page)).toContain("5.00");
});
+18 -2
View File
@@ -48,6 +48,9 @@ pub struct DimChain {
pub pts: Vec<Vec2>,
/// Abstand der Masslinie (Modell-Meter, positiv = aussen).
pub offset: f64,
/// Je Punkt das Merkmal, aus dem er stammt (Grundriss-Ecke bzw. Leibung auf der Aussenfläche;
/// das äusserste bei gleicher Lage) — für die assoziative Bemassung ([38]).
pub src: Vec<Vec2>,
}
const EPS: f64 = 1e-6;
@@ -141,10 +144,13 @@ pub fn auto_exterior_dimensions(walls: &[WallIn], openings: &[OpeningIn], scale_
let u = [n[1], -n[0]];
let (mut s_max, mut t_min, mut t_max) = (f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
let mut corners = vec![];
// Merkmale (Lage entlang u, Punkt, Tiefe entlang n) für `src`.
let mut feats: Vec<(f64, Vec2, f64)> = vec![];
// Kanten, die nach `n` schauen: Aussennormale (rechte Normale eines CCW-Rings) ≈ n.
let mut faces: Vec<(f64, f64, f64)> = vec![];
for ring in &rings {
for &p in ring {
feats.push((dot(p, u), p, dot(p, n)));
s_max = s_max.max(dot(p, n));
t_min = t_min.min(dot(p, u));
t_max = t_max.max(dot(p, u));
@@ -190,6 +196,10 @@ pub fn auto_exterior_dimensions(walls: &[WallIn], openings: &[OpeningIn], scale_
if on_face {
jambs.push(ja);
jambs.push(jb);
for j in [o.jamb_start, o.jamb_end] {
let k = outer_s - dot(j, n);
feats.push((dot(j, u), [j[0] + n[0] * k, j[1] + n[1] * k], outer_s + 1.0));
}
}
}
@@ -209,8 +219,14 @@ pub fn auto_exterior_dimensions(walls: &[WallIn], openings: &[OpeningIn], scale_
if ts.len() < 2 {
continue;
}
let pts = ts.iter().map(|&t| [u[0] * t + n[0] * s_max, u[1] * t + n[1] * s_max]).collect();
out.push(DimChain { side, chain, pts, offset: CHAIN_MM[chain] / 1000.0 * scale });
let pts: Vec<Vec2> = ts.iter().map(|&t| [u[0] * t + n[0] * s_max, u[1] * t + n[1] * s_max]).collect();
// Leibungen vor Ecken (Tiefe + 1), sonst die äusserste Ecke gleicher Lage.
let src = ts
.iter()
.zip(&pts)
.map(|(&t, &p)| feats.iter().filter(|f| (f.0 - t).abs() <= 1e-3).max_by(|a, b| a.2.total_cmp(&b.2)).map_or(p, |f| f.1))
.collect();
out.push(DimChain { side, chain, pts, offset: CHAIN_MM[chain] / 1000.0 * scale, src });
}
}
out
+23 -2
View File
@@ -938,7 +938,20 @@ fn dimension_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGe
if cleaned.len() < 2 {
return Vec::new();
}
let geom = obj(vec![("shape", s("dimension")), ("pts", Value::Array(cleaned)), ("offset", js_num(offset))]);
// Assoziativ ([38]): Punkte, die auf einem gefangenen Merkmal liegen, hängen daran; beim Ergänzen
// behalten die alten Punkte ihre Bezüge.
let chain: Vec<V> = cleaned.iter().map(pair).collect();
let snaps: Vec<V> = arr(v.get("snaps")).iter().map(pair).collect();
let old = v.get("editId").and_then(Value::as_str).and_then(|id| find(root, "drawings2d", id)).and_then(|d| field(d, "geom"));
let old_pts: Vec<V> = old.map(|g| arr(field(g, "pts")).iter().map(pair).collect()).unwrap_or_default();
let old_refs: Vec<Option<crate::model::DimRef>> = old.and_then(|g| field(g, "refs")).and_then(|r| serde_json::from_value(r.clone()).ok()).unwrap_or_default();
let keep = |q: V| old_pts.iter().position(|o| dist(*o, q) < 1e-9).and_then(|i| old_refs.get(i).cloned().flatten());
let refs = crate::dim_assoc::refs_for_chain(&crate::document::Lookup::plain(root), ctx.level, &chain, &snaps, &keep);
let mut fields = vec![("shape", s("dimension")), ("pts", Value::Array(cleaned)), ("offset", js_num(offset))];
if let Some(r) = refs {
fields.push(("refs", serde_json::to_value(r).unwrap_or(Value::Null)));
}
let geom = obj(fields);
match v.get("editId").and_then(Value::as_str) {
Some(id) => match find(root, "drawings2d", id) {
Some(d) => vec![Op::Replace { collection: "drawings2d".into(), entity: with(d, "geom", geom) }],
@@ -1024,12 +1037,20 @@ fn auto_dims(root: &Map<String, Value>, ctx: &Ctx, prefix: &str, scale: f64) ->
}
const SIDES: [&str; 4] = ["south", "east", "north", "west"];
const CHAINS: [&str; 3] = ["openings", "steps", "total"];
let lk = crate::document::Lookup::plain(root);
auto_exterior_dimensions(&win, &oin, scale)
.into_iter()
.map(|c| {
let id = format!("{prefix}-{}-{}-{}", ctx.level, SIDES[c.side as usize], CHAINS[c.chain as usize]);
let pts = Value::Array(c.pts.iter().map(|q| crate::grips::pt(q[0], q[1])).collect());
drawing(id, ctx, obj(vec![("shape", s("dimension")), ("pts", pts), ("offset", js_num(c.offset))]))
let mut fields = vec![("shape", s("dimension")), ("pts", pts), ("offset", js_num(c.offset))];
// Assoziativ ([38]): je Punkt das Merkmal (Ecke, Leibung), aus dem er stammt.
let chain: Vec<V> = c.pts.iter().map(|q| (q[0], q[1])).collect();
let src: Vec<V> = c.src.iter().map(|q| (q[0], q[1])).collect();
if let Some(r) = crate::dim_assoc::refs_for_chain(&lk, ctx.level, &chain, &src, &|_| None) {
fields.push(("refs", serde_json::to_value(r).unwrap_or(Value::Null)));
}
drawing(id, ctx, obj(fields))
})
.collect()
}
+1
View File
@@ -868,6 +868,7 @@ pub fn ops(root: &Map<String, Value>, v: &Value) -> Option<Vec<Op>> {
"offset" => offset_ops(root, s_arg(v, "id"), n_arg(v, "d"), &mut ids),
"join" => join_ops(root, &list("ids"), &mut ids),
"explode" => explode_ops(root, &list("ids"), &mut ids),
"dimdetach" => crate::dim_assoc::detach_ops(root, &list("ids")),
_ => return None,
})
}
+44 -12
View File
@@ -522,6 +522,21 @@ pub fn transform_ops(root: &Map<String, Value>, req: &TransformReq) -> Vec<Op> {
let k_at = |t: f64| if scaling { scale_factor(&pts, t) } else { 1.0 };
let geom_at = |g: &Value, xf: &Xf, t: f64| if scaling { scale_geom(g, xf, scale_factor(&pts, t)) } else { mv_geom(g, xf) };
let mut ops = Vec::new();
// Assoziative Bemassung ([38]): Bezüge bleiben nur bei starren Bewegungen (Verschieben, Drehen)
// und nur auf Elemente, die mittransformiert werden (Öffnungen mit ihrer Wand).
let rigid = op == "move" || op == "rotate";
let moved: std::collections::HashSet<&str> = items.iter().filter_map(|(_, e)| id_of(e)).collect();
let moved_openings: std::collections::HashSet<&str> =
list(root, "openings").iter().filter(|o| field(o, "hostWallId").and_then(Value::as_str).is_some_and(|h| moved.contains(h))).filter_map(id_of).collect();
let fix_refs = |d: Value, map: &dyn Fn(&str) -> Option<String>| -> Value {
let Some(g) = field(&d, "geom") else { return d };
let keep = |id: &str| if rigid { map(id) } else { None };
match crate::dim_assoc::transformed_refs(g, &keep) {
Some(Some(r)) => with(&d, "geom", with(g, "refs", r)),
Some(None) => with(&d, "geom", crate::dim_assoc::without_ref(g, None)),
None => d,
}
};
if req.mode == "move" {
let xf = Xf::of(op, &pts, 1.0);
@@ -532,7 +547,8 @@ pub fn transform_ops(root: &Map<String, Value>, req: &TransformReq) -> Vec<Op> {
patch("walls", &|w| walls.has(w) && !locked(w), &|w| mv_wall(w, &xf));
let draw = Ids::of(sel.drawings());
if !draw.is_empty() {
patch("drawings2d", &|d| draw.has(d) && !locked(d), &|d| with_geom(d, geom_at(field(d, "geom").unwrap_or(&Value::Null), &xf, 1.0)));
let same = |id: &str| (moved.contains(id) || moved_openings.contains(id)).then(|| id.to_owned());
patch("drawings2d", &|d| draw.has(d) && !locked(d), &|d| fix_refs(with_geom(d, geom_at(field(d, "geom").unwrap_or(&Value::Null), &xf, 1.0)), &same));
}
if let Some(id) = nonempty(&sel.extruded_solid_id) {
patch("extrudedSolids", &|s| id_of(s) == Some(id), &|s| mv_solid(s, &xf, k_at(1.0)));
@@ -560,18 +576,34 @@ pub fn transform_ops(root: &Map<String, Value>, req: &TransformReq) -> Vec<Op> {
let mut new: [Vec<Value>; 8] = Default::default();
for t in copy_ts(op, &req.mode, req.count.0) {
let xf = Xf::of(op, &pts, t);
for (kind, e) in &items {
let (slot, prefix, v) = match kind {
Kind::Wall => (0, "W", mv_wall(e, &xf)),
Kind::Drawing => (1, "dr2d", with_geom(e, geom_at(field(e, "geom").unwrap_or(&Value::Null), &xf, t))),
Kind::Solid => (2, "extrude", mv_solid(e, &xf, k_at(t))),
Kind::Column => (3, "column", mv_column(e, &xf)),
Kind::Ceiling => (4, "C", mv_ceiling(e, &xf)),
Kind::Roof => (5, "RF", mv_roof(e, &xf)),
Kind::Stair => (6, "ST", mv_stair(e, &xf, k_at(t))),
Kind::Room => (7, "RM", mv_room(e, &xf)),
let prefixes: Vec<&str> = items
.iter()
.map(|(k, _)| match k {
Kind::Wall => "W",
Kind::Drawing => "dr2d",
Kind::Solid => "extrude",
Kind::Column => "column",
Kind::Ceiling => "C",
Kind::Roof => "RF",
Kind::Stair => "ST",
Kind::Room => "RM",
})
.collect();
let new_ids: Vec<String> = prefixes.iter().map(|p| ids.next(p)).collect();
let copied: std::collections::HashMap<&str, &str> = items.iter().zip(&new_ids).filter_map(|((_, e), n)| Some((id_of(e)?, n.as_str()))).collect();
let to_copy = |id: &str| copied.get(id).map(|n| (*n).to_owned());
for ((kind, e), new_id) in items.iter().zip(&new_ids) {
let (slot, v) = match kind {
Kind::Wall => (0, mv_wall(e, &xf)),
Kind::Drawing => (1, fix_refs(with_geom(e, geom_at(field(e, "geom").unwrap_or(&Value::Null), &xf, t)), &to_copy)),
Kind::Solid => (2, mv_solid(e, &xf, k_at(t))),
Kind::Column => (3, mv_column(e, &xf)),
Kind::Ceiling => (4, mv_ceiling(e, &xf)),
Kind::Roof => (5, mv_roof(e, &xf)),
Kind::Stair => (6, mv_stair(e, &xf, k_at(t))),
Kind::Room => (7, mv_room(e, &xf)),
};
new[slot].push(with(&v, "id", Value::String(ids.next(prefix))));
new[slot].push(with(&v, "id", Value::String(new_id.clone())));
}
}
let keys = ["walls", "drawings2d", "extrudedSolids", "columns", "ceilings", "roofs", "stairs", "rooms"];
+713
View File
@@ -0,0 +1,713 @@
//! Assoziative Bemassung ([38]): Bemassungspunkte, die beim Zeichnen auf ein Merkmal eines Elements
//! gefangen wurden, tragen einen Bezug ([`DimRef`], `Dimension.refs`) und folgen dem Element.
//!
//! - **Anhängen** ([`attach`]): ein gefangener Punkt wird über Deckungsgleichheit (Toleranz [`TOL`])
//! einem Merkmal zugeordnet — Öffnungs-Leibung/-Mitte, Wandende, Wandecke (Schnitt zweier
//! Wandlinien), Punkt auf Wandachse/Schichtgrenze, Stütze (Mitte, Ecken, Kanten), Decken-/Dach-/
//! Raum-Umriss (Ecken, Kanten), 2D-Zeichnung (Eckpunkte, Mittelpunkte, Kanten). Bogenwände
//! werden nicht angehängt. Freie Klicks decken sich praktisch nie und bleiben frei.
//! - **Nachführen** ([`sync_ops`]): nach jeder Benutzer-Änderung (`Document::commit`) löst der Kern
//! die Bezüge auf und schreibt die Lage in `pts` zurück (dieselbe Undo-Stufe). Damit lesen alle
//! Ableitungen (Plan, DXF, Griffe, Auswahl-Info) einfach `pts`, und `pts` ist immer die zuletzt
//! aufgelöste Lage. Ein ungültiger Bezug (Element gelöscht, Eckpunkt weg) behält den Punkt an
//! dieser Lage und wird `lost` markiert (Bildschirm: Marke, Druck: nichts; Objekt-Info: Hinweis).
//! - **Kette**: Masspunkte bleiben kollinear. Richtung = aufgelöster Punkt 0 → 1, wenn beide hängen,
//! sonst die gespeicherte; Lage der Linie durch Punkt 0 (bzw. den ersten hängenden Punkt); jeder
//! Punkt wird darauf projiziert. `d` (Normalabstand Merkmal → Masslinie) hält Ketten wie die
//! Aussenbemassung, deren Punkte nicht auf dem Merkmal liegen, in ihrer Flucht.
//! - **Transformieren** ([`transformed_refs`]): wird die Bemassung zusammen mit allen Elementen ihrer
//! Bezüge verschoben/gedreht/gespiegelt, bleiben die Bezüge; Bezüge auf nicht mittransformierte
//! Elemente werden gelöst (sonst zöge das Nachführen den Punkt sofort zurück). Kopien behalten
//! Bezüge nur, wenn das Element mitkopiert wird (auf die Kopie umgeschrieben).
//! - **Lösen** ([`detach_ops`], Befehl „Bemassung lösen"): `refs` weg, `pts` bleibt.
use crate::document::Lookup;
use crate::model::{DimFeature, DimRef};
use crate::ops::Op;
use serde_json::{Map, Value};
type P = (f64, f64);
/// Toleranz der Deckungsgleichheit beim Anhängen (Meter).
pub const TOL: f64 = 1e-5;
/// Änderungen unterhalb davon schreibt das Nachführen nicht zurück.
const MOVE_EPS: f64 = 1e-9;
fn num(v: Option<&Value>) -> Option<f64> {
v.and_then(Value::as_f64).filter(|x| x.is_finite())
}
fn pt(v: Option<&Value>) -> Option<P> {
let v = v?;
Some((num(v.get("x"))?, num(v.get("y"))?))
}
fn str_of<'a>(v: &'a Value, k: &str) -> Option<&'a str> {
v.get(k).and_then(Value::as_str)
}
fn dist(a: P, b: P) -> f64 {
(b.0 - a.0).hypot(b.1 - a.1)
}
fn lerp(a: P, b: P, t: f64) -> P {
(a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t)
}
fn unit(a: P, b: P) -> Option<P> {
let l = dist(a, b);
(l > 1e-12 && l.is_finite()).then(|| ((b.0 - a.0) / l, (b.1 - a.1) / l))
}
fn dot(a: P, b: P) -> f64 {
a.0 * b.0 + a.1 * b.1
}
fn sub(a: P, b: P) -> P {
(a.0 - b.0, a.1 - b.1)
}
fn add(a: P, b: P, k: f64) -> P {
(a.0 + b.0 * k, a.1 + b.1 * k)
}
fn left(u: P) -> P {
(-u.1, u.0)
}
fn finite(p: P) -> bool {
p.0.is_finite() && p.1.is_finite()
}
// ── Element-Geometrie aus dem JSON-Dokument ─────────────────────────────────
/// Wand: Achse und Abstände der Schichtgrenzen (linke Normale, wie `snap_model::wall_layer_segments`).
struct WallGeo {
a: P,
b: P,
offs: Vec<f64>,
total: f64,
arc: bool,
}
fn wall_geo(lk: &Lookup, w: &Value) -> Option<WallGeo> {
let (a, b) = (pt(w.get("start"))?, pt(w.get("end"))?);
let layers: Vec<f64> = str_of(w, "wallTypeId")
.and_then(|id| lk.find("wallTypes", id))
.and_then(|t| t.get("layers"))
.and_then(Value::as_array)
.map(|ls| ls.iter().map(|l| num(l.get("thickness")).unwrap_or(0.0)).collect())
.unwrap_or_default();
let total: f64 = layers.iter().sum();
let half = total / 2.0;
let ref_off = match (num(w.get("referenceOffset")), str_of(w, "referenceLine")) {
(Some(v), _) => v.clamp(-half, half),
(None, Some("left")) => half,
(None, Some("right")) => -half,
_ => 0.0,
};
let mut offs = Vec::new();
if !layers.is_empty() {
let mut off = ref_off - half;
offs.push(off);
for t in &layers {
off += t;
offs.push(off);
}
}
let arc = crate::wall_arc::is_arc_bulge(num(w.get("bulge")));
Some(WallGeo { a, b, offs, total, arc })
}
impl WallGeo {
/// Linie `index` (fehlt = Achse): Anfang und Ende.
fn line(&self, index: Option<u32>) -> Option<(P, P)> {
let o = match index {
None => 0.0,
Some(k) => *self.offs.get(k as usize)?,
};
let n = left(unit(self.a, self.b)?);
Some((add(self.a, n, o), add(self.b, n, o)))
}
/// Alle Linien: Achse, dann die Schichtgrenzen.
fn lines(&self) -> Vec<(Option<u32>, P, P)> {
std::iter::once(None).chain((0..self.offs.len() as u32).map(Some)).filter_map(|k| self.line(k).map(|(a, b)| (k, a, b))).collect()
}
}
/// Leibungs-/Mittelpunkt einer Öffnung auf der Linie `layer` der Wirtswand (wie `autodim`).
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 (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);
let s = match side {
0 => from,
1 => to,
2 => (from + to) / 2.0,
_ => return None,
};
let u = unit(a, b)?;
Some(add(a, u, s))
}
/// Punkte (Umriss/Kette), geschlossen?, Mittelpunkt eines Elements für Ecke/Kante/Mitte.
struct Shape {
pts: Vec<P>,
closed: bool,
center: Option<P>,
}
fn pts_list(v: Option<&Value>) -> Vec<P> {
v.and_then(Value::as_array).map(|l| l.iter().filter_map(|p| pt(Some(p))).collect()).unwrap_or_default()
}
fn column_shape(c: &Value) -> Option<Shape> {
let at = pt(c.get("position"))?;
let prof = c.get("profile")?;
if str_of(prof, "kind") == Some("rect") {
let (hw, hd) = (num(prof.get("width"))? / 2.0, num(prof.get("depth"))? / 2.0);
let rot = num(c.get("rotation")).unwrap_or(0.0);
let (co, si) = (crate::jsnum::cos(rot), crate::jsnum::sin(rot));
let pts = [(-hw, -hd), (hw, -hd), (hw, hd), (-hw, hd)].iter().map(|&(x, y)| (at.0 + x * co - y * si, at.1 + x * si + y * co)).collect();
return Some(Shape { pts, closed: true, center: Some(at) });
}
Some(Shape { pts: Vec::new(), closed: false, center: Some(at) })
}
fn drawing_shape(d: &Value) -> Option<Shape> {
let g = d.get("geom")?;
let p = |k: &str| pt(g.get(k));
Some(match str_of(g, "shape")? {
"line" => Shape { pts: vec![p("a")?, p("b")?], closed: false, center: None },
"polyline" => Shape { pts: pts_list(g.get("pts")), closed: g.get("closed").and_then(Value::as_bool).unwrap_or(false), center: None },
"rect" => {
let (lo, hi) = (p("min")?, p("max")?);
Shape { pts: vec![lo, (hi.0, lo.1), hi, (lo.0, hi.1)], closed: true, center: None }
}
"circle" | "arc" | "ellipse" => Shape { pts: Vec::new(), closed: false, center: Some(p("center")?) },
_ => return None,
})
}
/// Listen, in denen Ecke/Kante/Mitte ihr Element suchen (in dieser Reihenfolge).
const SHAPE_LISTS: [&str; 5] = ["columns", "ceilings", "roofs", "rooms", "drawings2d"];
fn shape_of(coll: &str, e: &Value) -> Option<Shape> {
match coll {
"columns" => column_shape(e),
"ceilings" | "roofs" => Some(Shape { pts: pts_list(e.get("outline")), closed: true, center: None }),
"rooms" => Some(Shape { pts: pts_list(e.get("boundary")), closed: true, center: None }),
"drawings2d" => drawing_shape(e),
_ => None,
}
}
fn find_shape(lk: &Lookup, id: &str) -> Option<Shape> {
SHAPE_LISTS.iter().find_map(|c| lk.find(c, id).map(|e| (*c, e))).and_then(|(c, e)| shape_of(c, e))
}
fn edge(s: &Shape, i: usize) -> Option<(P, P)> {
let n = s.pts.len();
if i + 1 < n {
Some((s.pts[i], s.pts[i + 1]))
} else if s.closed && n > 2 && i + 1 == n {
Some((s.pts[i], s.pts[0]))
} else {
None
}
}
/// Schnitt zweier unendlicher Geraden (parallel → `None`).
fn intersect(a: (P, P), b: (P, P)) -> Option<P> {
let r = sub(a.1, a.0);
let s = sub(b.1, b.0);
let den = r.0 * s.1 - r.1 * s.0;
let scale = dist(a.0, a.1) * dist(b.0, b.1);
if den.abs() <= 1e-9 * scale || scale == 0.0 {
return None;
}
let q = sub(b.0, a.0);
let t = (q.0 * s.1 - q.1 * s.0) / den;
Some(add(a.0, r, t))
}
/// Lage des Merkmals eines Bezugs (`None` = ungültig).
pub fn resolve(lk: &Lookup, r: &DimRef) -> Option<P> {
let wall_line = |id: &str, idx: Option<u32>| -> Option<(P, P)> { wall_geo(lk, lk.find("walls", id)?)?.line(idx) };
let p = match r.feature {
DimFeature::Wall => {
let (a, b) = wall_line(&r.id, r.index)?;
lerp(a, b, r.t?)
}
DimFeature::Opening => opening_point(lk, lk.find("openings", &r.id)?, r.index?, r.index2)?,
DimFeature::Vertex => *find_shape(lk, &r.id)?.pts.get(r.index? as usize)?,
DimFeature::Edge => {
let (a, b) = edge(&find_shape(lk, &r.id)?, r.index? as usize)?;
lerp(a, b, r.t?)
}
DimFeature::Center => find_shape(lk, &r.id)?.center?,
DimFeature::Intersection => intersect(wall_line(&r.id, r.index)?, wall_line(r.id2.as_deref()?, r.index2)?)?,
};
finite(p).then_some(p)
}
// ── Anhängen ────────────────────────────────────────────────────────────────
fn on_level(e: &Value, key: &str, level: &str) -> bool {
str_of(e, key) == Some(level)
}
fn list<'a>(lk: &Lookup<'a>, key: &str) -> &'a [Value] {
lk.root.get(key).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[])
}
fn rf(id: &str, feature: DimFeature) -> DimRef {
DimRef { id: id.to_owned(), feature, index: None, t: None, id2: None, index2: None, d: None, lost: None }
}
/// Parameter von `s` auf a→b und Normalabstand zur Geraden.
fn param(a: P, b: P, s: P) -> Option<(f64, f64)> {
let u = unit(a, b)?;
let l = dist(a, b);
let q = sub(s, a);
Some((dot(q, u) / l, dot(q, left(u)).abs()))
}
/// Merkmal des Geschosses `level`, auf dem `s` liegt (Toleranz `tol`), sonst `None`.
pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
if !finite(s) {
return None;
}
let walls: Vec<(&str, WallGeo)> = list(lk, "walls")
.iter()
.filter(|w| on_level(w, "floorId", level))
.filter_map(|w| Some((str_of(w, "id")?, wall_geo(lk, w)?)))
.filter(|(_, g)| !g.arc)
.collect();
// 1) Öffnungen: Leibungen und Mitte auf jeder Linie der Wirtswand.
for o in list(lk, "openings") {
let (Some(id), Some(host)) = (str_of(o, "id"), str_of(o, "hostWallId")) else { continue };
let Some((_, g)) = walls.iter().find(|(wid, _)| *wid == host) else { continue };
for (layer, _, _) in g.lines() {
for side in 0..3 {
if opening_point(lk, o, side, layer).is_some_and(|p| dist(p, s) <= tol) {
return Some(DimRef { index: Some(side), index2: layer, ..rf(id, DimFeature::Opening) });
}
}
}
}
// 2) Wandenden.
for (id, g) in &walls {
for (k, a, b) in g.lines() {
for (t, p) in [(0.0, a), (1.0, b)] {
if dist(p, s) <= tol {
return Some(DimRef { index: k, t: Some(t), ..rf(id, DimFeature::Wall) });
}
}
}
}
// 3) Wandecken: auf den Linien zweier Wände (Verlängerung bis zur Wanddicke über das Ende).
let mut hits: Vec<(&str, Option<u32>, P, P, f64)> = Vec::new();
for (id, g) in &walls {
let len = dist(g.a, g.b);
let m = (g.total.max(0.3) + tol) / len;
for (k, a, b) in g.lines() {
if let Some((t, d)) = param(a, b, s) {
if d <= tol && t >= -m && t <= 1.0 + m {
hits.push((id, k, a, b, t));
}
}
}
}
for (i, h) in hits.iter().enumerate() {
for h2 in &hits[i + 1..] {
if h2.0 != h.0 && intersect((h.2, h.3), (h2.2, h2.3)).is_some_and(|p| dist(p, s) <= tol) {
return Some(DimRef { index: h.1, id2: Some(h2.0.to_owned()), index2: h2.1, ..rf(h.0, DimFeature::Intersection) });
}
}
}
// 4) Punkt auf einer Wandlinie.
if let Some(h) = hits.iter().find(|h| (0.0..=1.0).contains(&h.4)) {
return Some(DimRef { index: h.1, t: Some(h.4), ..rf(h.0, DimFeature::Wall) });
}
// 5) Stützen, Decken, Dächer, Räume, 2D-Zeichnungen: Mitte, Ecken, Kanten.
for coll in SHAPE_LISTS {
let key = if coll == "drawings2d" { "levelId" } else { "floorId" };
for e in list(lk, coll).iter().filter(|e| on_level(e, key, level)) {
let (Some(id), Some(sh)) = (str_of(e, "id"), shape_of(coll, e)) else { continue };
if sh.center.is_some_and(|c| dist(c, s) <= tol) {
return Some(rf(id, DimFeature::Center));
}
if let Some(i) = sh.pts.iter().position(|p| dist(*p, s) <= tol) {
return Some(DimRef { index: Some(i as u32), ..rf(id, DimFeature::Vertex) });
}
for i in 0..sh.pts.len() {
let Some((a, b)) = edge(&sh, i) else { continue };
if let Some((t, d)) = param(a, b, s) {
if d <= tol && (0.0..=1.0).contains(&t) {
return Some(DimRef { index: Some(i as u32), t: Some(t), ..rf(id, DimFeature::Edge) });
}
}
}
}
}
None
}
/// Bezüge einer neuen Kette `pts`: je Punkt der erste Fangpunkt aus `snaps`, der auf ihn projiziert
/// (Kette = Gerade pts[0]→pts[1]) und an einem Merkmal hängt; `d` = Normalabstand Fangpunkt → Punkt.
/// `keep(i)` liefert einen schon bekannten Bezug (Ergänzen einer Kette). Kein Bezug → `None`.
pub fn refs_for_chain(lk: &Lookup, level: &str, pts: &[P], snaps: &[P], keep: &dyn Fn(P) -> Option<DimRef>) -> Option<Vec<Option<DimRef>>> {
if pts.len() < 2 {
return None;
}
let u = unit(pts[0], pts[1])?;
let n = left(u);
let refs: Vec<Option<DimRef>> = pts
.iter()
.map(|&p| {
if let Some(r) = keep(p) {
return Some(r);
}
snaps.iter().chain(std::iter::once(&p)).find_map(|&s| {
let along = add(pts[0], u, dot(sub(s, pts[0]), u));
if dist(along, p) > 1e-6 {
return None;
}
let mut r = attach(lk, level, s, TOL)?;
let d = dot(sub(s, p), n);
r.d = (d.abs() > 1e-9).then_some(d);
Some(r)
})
})
.collect();
refs.iter().any(Option::is_some).then_some(refs)
}
// ── Auflösen einer Kette ────────────────────────────────────────────────────
/// Aufgelöste Kette: neue Punkte und je Bezug „ungültig".
pub fn resolve_chain(lk: &Lookup, pts: &[P], refs: &[Option<DimRef>]) -> (Vec<P>, Vec<bool>) {
let q: Vec<Option<P>> = (0..pts.len()).map(|i| refs.get(i).and_then(Option::as_ref).and_then(|r| resolve(lk, r))).collect();
let lost: Vec<bool> = (0..refs.len()).map(|i| refs[i].is_some() && q.get(i).copied().flatten().is_none()).collect();
let Some(mut u) = (pts.len() >= 2).then(|| unit(pts[0], pts[1])).flatten() else { return (pts.to_vec(), lost) };
let d_of = |i: usize| refs.get(i).and_then(Option::as_ref).and_then(|r| r.d).unwrap_or(0.0);
let base = |u: P, i: usize| q[i].map(|p| add(p, left(u), -d_of(i)));
if let (Some(_), Some(_)) = (q[0], q[1]) {
for _ in 0..2 {
if let (Some(b0), Some(b1)) = (base(u, 0), base(u, 1)) {
if let Some(nu) = unit(b0, b1) {
u = nu;
}
}
}
}
let n = left(u);
let origin = match (0..pts.len()).find_map(|i| base(u, i).map(|b| (i, b))) {
Some((0, b)) => b,
Some((_, b)) => add(pts[0], n, dot(sub(b, pts[0]), n)),
None => pts[0],
};
let out = (0..pts.len())
.map(|i| {
let target = base(u, i).unwrap_or(pts[i]);
add(origin, u, dot(sub(target, origin), u))
})
.collect();
(out, lost)
}
fn refs_of(g: &Value) -> Option<Vec<Option<DimRef>>> {
let r = g.get("refs")?;
let refs: Vec<Option<DimRef>> = serde_json::from_value(r.clone()).ok()?;
refs.iter().any(Option::is_some).then_some(refs)
}
fn pv(p: P) -> Value {
crate::grips::pt(p.0, p.1)
}
fn with(v: &Value, key: &str, x: Value) -> Value {
let mut m = v.as_object().cloned().unwrap_or_default();
m.insert(key.to_owned(), x);
Value::Object(m)
}
/// Felder, deren Änderung Bezüge verschieben kann.
pub const SOURCE_FIELDS: [&str; 8] = ["walls", "wallTypes", "openings", "columns", "ceilings", "roofs", "rooms", "drawings2d"];
/// Nachführ-Ops: je Bemassung mit Bezügen, deren aufgelöste Lage oder Gültigkeit sich geändert hat,
/// ein `replace` mit neuen `pts`/`refs`.
pub fn sync_ops(lk: &Lookup) -> Vec<Op> {
let mut ops = Vec::new();
for d in list(lk, "drawings2d") {
let Some(g) = d.get("geom").filter(|g| str_of(g, "shape") == Some("dimension")) else { continue };
let Some(refs) = refs_of(g) else { continue };
let pts = pts_list(g.get("pts"));
if pts.len() != g.get("pts").and_then(Value::as_array).map_or(0, Vec::len) {
continue;
}
let (np, lost) = resolve_chain(lk, &pts, &refs);
let moved = np.iter().zip(&pts).any(|(a, b)| dist(*a, *b) > MOVE_EPS);
let flags_changed = refs.iter().zip(&lost).any(|(r, l)| r.as_ref().is_some_and(|r| r.lost.unwrap_or(false) != *l));
if !moved && !flags_changed {
continue;
}
let mut ng = g.clone();
if moved {
ng = with(&ng, "pts", Value::Array(np.iter().map(|p| pv(*p)).collect()));
}
if flags_changed {
let nr: Vec<Option<DimRef>> = refs.into_iter().zip(&lost).map(|(r, l)| r.map(|r| DimRef { lost: l.then_some(true), ..r })).collect();
ng = with(&ng, "refs", serde_json::to_value(nr).unwrap_or(Value::Null));
}
ops.push(Op::Replace { collection: "drawings2d".into(), entity: with(d, "geom", ng) });
}
ops
}
/// Betrifft eine der Ops ein Feld, aus dem Bezüge lesen?
pub fn touches_sources(ops: &[Op]) -> bool {
ops.iter().any(|o| SOURCE_FIELDS.contains(&o.key()))
}
/// „Bemassung lösen": `refs` der gewählten Bemassungen entfernen (Punkte bleiben, wo sie sind).
pub fn detach_ops(root: &Map<String, Value>, ids: &[String]) -> Vec<Op> {
let lk = Lookup::plain(root);
list(&lk, "drawings2d")
.iter()
.filter(|d| str_of(d, "id").is_some_and(|id| ids.iter().any(|x| x == id)))
.filter_map(|d| {
let g = d.get("geom")?.as_object()?;
g.get("refs")?;
let mut ng = g.clone();
ng.remove("refs");
Some(Op::Replace { collection: "drawings2d".into(), entity: with(d, "geom", Value::Object(ng)) })
})
.collect()
}
/// Bemassungs-Geometrie `g` ohne den Bezug von Punkt `i` (`None` = alle); ohne verbleibenden Bezug
/// entfällt das Feld. Für Griffe: ein von Hand gezogener Punkt ist frei.
pub fn without_ref(g: &Value, i: Option<usize>) -> Value {
let Some(mut refs) = refs_of(g) else { return g.clone() };
match i {
Some(i) if i < refs.len() => refs[i] = None,
Some(_) => return g.clone(),
None => refs.clear(),
}
let mut m = g.as_object().cloned().unwrap_or_default();
if refs.iter().any(Option::is_some) {
m.insert("refs".into(), serde_json::to_value(refs).unwrap_or(Value::Null));
} else {
m.remove("refs");
}
Value::Object(m)
}
/// Bezüge einer transformierten Bemassung: Bezüge, deren Element(e) `map` kennt, bleiben (id auf die
/// Kopie umgeschrieben); die übrigen fallen weg. Kein Bezug mehr → `None` (Feld entfällt).
pub fn transformed_refs(g: &Value, map: &dyn Fn(&str) -> Option<String>) -> Option<Option<Value>> {
let refs = refs_of(g)?;
let host_ok = |r: &DimRef| -> Option<DimRef> {
let id = map(&r.id)?;
let id2 = match &r.id2 {
Some(x) => Some(map(x)?),
None => None,
};
Some(DimRef { id, id2, ..r.clone() })
};
let nr: Vec<Option<DimRef>> = refs.iter().map(|r| r.as_ref().and_then(host_ok)).collect();
Some(nr.iter().any(Option::is_some).then(|| serde_json::to_value(nr).unwrap_or(Value::Null)))
}
/// Indizes der Punkte mit ungültigem Bezug einer Bemassung (für Marke und Objekt-Info).
pub fn lost_points(refs: Option<&Vec<Option<DimRef>>>) -> Vec<usize> {
refs.map(|r| r.iter().enumerate().filter(|(_, r)| r.as_ref().is_some_and(|r| r.lost == Some(true))).map(|(i, _)| i).collect()).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn root(v: Value) -> Map<String, Value> {
v.as_object().unwrap().clone()
}
/// Zwei Wände (0.3 m, zwei Schichten 0.1/0.2) im L, Öffnung, Stütze, Decke, Zeichnungen.
fn project() -> Map<String, Value> {
root(json!({
"wallTypes": [{"id": "T", "layers": [{"thickness": 0.1}, {"thickness": 0.2}]}],
"walls": [
{"id": "A", "floorId": "eg", "wallTypeId": "T", "start": {"x": 0, "y": 0}, "end": {"x": 10, "y": 0}},
{"id": "B", "floorId": "eg", "wallTypeId": "T", "start": {"x": 10, "y": 0}, "end": {"x": 10, "y": 6}}
],
"openings": [{"id": "O", "hostWallId": "A", "position": 2, "width": 1.5}],
"columns": [{"id": "S", "floorId": "eg", "position": {"x": 5, "y": 3}, "profile": {"kind": "rect", "width": 0.4, "depth": 0.2}, "rotation": 0}],
"ceilings": [{"id": "C", "floorId": "eg", "outline": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}]}],
"drawings2d": [
{"id": "L", "levelId": "eg", "geom": {"shape": "line", "a": {"x": 20, "y": 0}, "b": {"x": 24, "y": 0}}},
{"id": "K", "levelId": "eg", "geom": {"shape": "circle", "center": {"x": 30, "y": 0}, "r": 1}}
]
}))
}
fn at(r: &Map<String, Value>, s: P) -> DimRef {
attach(&Lookup::plain(r), "eg", s, TOL).unwrap_or_else(|| panic!("kein Merkmal bei {s:?}"))
}
fn close(a: P, b: P) {
assert!(dist(a, b) < 1e-9, "{a:?} != {b:?}");
}
#[test]
fn anhaengen_und_aufloesen_je_merkmal() {
let r = project();
let lk = Lookup::plain(&r);
// Fläche rechts der Achse (Grenze 0 bei −0.15), Ende → Wandende.
let cases: Vec<(P, DimFeature)> = vec![
((0.0, 0.0), DimFeature::Wall),
((10.0, -0.15), DimFeature::Wall),
((3.0, 0.15), DimFeature::Wall),
((2.0, -0.15), DimFeature::Opening),
((2.75, 0.0), DimFeature::Opening),
((10.15, -0.15), DimFeature::Intersection),
((5.0, 3.0), DimFeature::Center),
((5.2, 3.1), DimFeature::Vertex),
((5.0, 2.9), DimFeature::Edge),
((4.0, 2.0), DimFeature::Edge),
((24.0, 0.0), DimFeature::Vertex),
((22.0, 0.0), DimFeature::Edge),
((30.0, 0.0), DimFeature::Center),
];
for (s, f) in cases {
let rf = at(&r, s);
assert_eq!(rf.feature, f, "{s:?}: {rf:?}");
close(resolve(&lk, &rf).unwrap(), s);
}
assert!(attach(&lk, "eg", (7.0, 7.0), TOL).is_none());
assert!(attach(&lk, "og", (0.0, 0.0), TOL).is_none());
}
fn set(r: &mut Map<String, Value>, coll: &str, id: &str, key: &str, v: Value) {
let e = r.get_mut(coll).unwrap().as_array_mut().unwrap().iter_mut().find(|e| e["id"] == id).unwrap();
e[key] = v;
}
#[test]
fn folgt_dem_element() {
let mut r = project();
let refs = {
let lk = Lookup::plain(&r);
vec![attach(&lk, "eg", (0.0, -0.15), TOL), attach(&lk, "eg", (2.0, -0.15), TOL), attach(&lk, "eg", (10.15, -0.15), TOL)]
};
// Wand A strecken: Ende nach x = 12 (Ecke folgt dem Schnitt, Wand B mitverschoben).
set(&mut r, "walls", "A", "end", json!({"x": 12, "y": 0}));
set(&mut r, "walls", "B", "start", json!({"x": 12, "y": 0}));
set(&mut r, "walls", "B", "end", json!({"x": 12, "y": 6}));
set(&mut r, "openings", "O", "position", json!(3));
let (np, lost) = resolve_chain(&Lookup::plain(&r), &[(0.0, -0.15), (2.0, -0.15), (10.15, -0.15)], &refs);
assert_eq!(lost, vec![false; 3]);
close(np[1], (3.0, -0.15));
close(np[2], (12.15, -0.15));
// Wand drehen (beide Punkte an derselben Wand): Kette dreht mit.
set(&mut r, "walls", "A", "end", json!({"x": 0, "y": 5}));
let (np, _) = resolve_chain(&Lookup::plain(&r), &[(0.0, 0.0), (10.0, 0.0)], &[Some(at(&project(), (0.0, 0.0))), Some(at(&project(), (10.0, 0.0)))]);
close(np[0], (0.0, 0.0));
close(np[1], (0.0, 5.0));
}
#[test]
fn ungueltig_faellt_zurueck_und_wird_markiert() {
let mut r = project();
let pts = vec![(0.0, 0.0), (24.0, 0.0)];
let refs = vec![Some(at(&r, (0.0, 0.0))), Some(at(&r, (24.0, 0.0)))];
r.insert("drawings2d".into(), json!([
{"id": "D", "levelId": "eg", "geom": {"shape": "dimension", "pts": [{"x": 0, "y": 0}, {"x": 24, "y": 0}], "offset": 1, "refs": refs}}
]));
// Linie L weg: Punkt 1 bleibt, wird markiert; nochmals nachführen ändert nichts.
let ops = sync_ops(&Lookup::plain(&r));
assert_eq!(ops.len(), 1);
let Op::Replace { entity, .. } = &ops[0] else { panic!() };
assert_eq!(entity["geom"]["refs"][1]["lost"], json!(true));
assert!(entity["geom"]["refs"][0].get("lost").is_none());
assert_eq!(pts_list(entity["geom"].get("pts")), pts);
r.insert("drawings2d".into(), json!([entity]));
assert!(sync_ops(&Lookup::plain(&r)).is_empty());
assert_eq!(lost_points(refs_of(&r["drawings2d"][0]["geom"]).as_ref()), vec![1]);
// Wand weg, Vertex-Index ausserhalb, Schichtgrenze weg: ungültig.
let lk = Lookup::plain(&r);
assert!(resolve(&lk, &DimRef { index: Some(9), ..rf("C", DimFeature::Vertex) }).is_none());
assert!(resolve(&lk, &DimRef { index: Some(7), t: Some(0.0), ..rf("A", DimFeature::Wall) }).is_none());
assert!(resolve(&lk, &DimRef { t: Some(0.0), ..rf("X", DimFeature::Wall) }).is_none());
// Parallele Linien schneiden sich nicht.
assert!(resolve(&lk, &DimRef { id2: Some("A".into()), ..rf("A", DimFeature::Intersection) }).is_none());
}
#[test]
fn kette_mit_abstand_bleibt_in_flucht() {
let mut r = project();
// Kette auf y = −2 (Aussenbemassung), Merkmale auf der Wandfläche: d = +1.85.
let pts = [(0.0, -2.0), (2.0, -2.0)];
let refs = refs_for_chain(&Lookup::plain(&r), "eg", &pts, &[(0.0, -0.15), (2.0, -0.15)], &|_| None).unwrap();
assert!((refs[0].as_ref().unwrap().d.unwrap() - 1.85).abs() < 1e-12);
let (np, _) = resolve_chain(&Lookup::plain(&r), &pts, &refs);
close(np[0], pts[0]);
close(np[1], pts[1]);
// Öffnung verschoben → Punkt 1 wandert entlang, die Linie bleibt auf y = −2.
set(&mut r, "openings", "O", "position", json!(4));
let (np, _) = resolve_chain(&Lookup::plain(&r), &pts, &refs);
close(np[1], (4.0, -2.0));
}
#[test]
fn loesen_und_transformieren() {
let r = root(json!({"drawings2d": [{"id": "D", "geom": {"shape": "dimension", "pts": [], "offset": 0, "refs": [{"id": "A", "feature": "wall", "t": 0}, null]}}]}));
let ops = detach_ops(&r, &["D".into()]);
let Op::Replace { entity, .. } = &ops[0] else { panic!() };
assert!(entity["geom"].get("refs").is_none());
let g = &r["drawings2d"][0]["geom"];
assert_eq!(transformed_refs(g, &|_| None), Some(None));
let kept = transformed_refs(g, &|id| Some(format!("{id}2"))).unwrap().unwrap();
assert_eq!(kept[0]["id"], json!("A2"));
}
#[test]
fn commit_fuehrt_nach_ein_undo_schritt() {
use crate::document::Document;
let mut r = project();
let refs = vec![Some(at(&r, (0.0, 0.0))), Some(at(&r, (10.0, 0.0)))];
r.insert("drawings2d".into(), json!([{"id": "D", "levelId": "eg", "geom": {"shape": "dimension", "pts": [{"x": 0, "y": 0}, {"x": 10, "y": 0}], "offset": 1, "refs": refs}}]));
let mut d = Document::from_json(&Value::Object(r).to_string()).unwrap();
let mut w = d.lookup().find("walls", "A").unwrap().clone();
w["end"] = json!({"x": 13, "y": 0});
let ops = crate::ops::ops_from_json(&json!([{"kind": "replace", "collection": "walls", "entity": w}])).unwrap();
d.commit(ops, None, 0.0, false).unwrap();
assert_eq!(d.last_extra().len(), 1);
let x = |d: &Document| d.lookup().find("drawings2d", "D").unwrap()["geom"]["pts"][1]["x"].as_f64().unwrap();
assert_eq!(x(&d), 13.0);
d.undo().unwrap();
assert_eq!(x(&d), 10.0);
d.redo().unwrap();
assert_eq!(x(&d), 13.0);
// Ohne Bezugsänderung (Feld ausserhalb): nichts nachzuführen.
d.commit(crate::ops::ops_from_json(&json!([{"kind": "setField", "key": "name", "value": "X"}])).unwrap(), None, 1.0, false).unwrap();
assert!(d.last_extra().is_empty());
}
#[test]
fn befehl_bemassung_haengt_gefangene_punkte_an() {
let r = project();
let req = json!({"cmd": "dimension", "pts": [[0, -2], [2, -2], [5, -2]], "snaps": [[0, -0.15], [2, -0.15]], "offset": -0.5, "ctx": {"level": "eg"}, "stamp": "s"});
let ops = crate::commands::ops(&r, &req.to_string()).unwrap();
let Op::Add { items, .. } = &ops[0] else { panic!("{ops:?}") };
let refs = &items[0]["geom"]["refs"];
assert_eq!(refs[0]["feature"], json!("wall"));
assert_eq!(refs[1]["feature"], json!("opening"));
assert_eq!(refs[2], Value::Null);
// Aussenbemassung: Ketten hängen an Ecken und Leibungen.
let ops = crate::commands::ops(&r, &json!({"cmd": "autodim", "ctx": {"level": "eg"}, "stamp": "s"}).to_string()).unwrap();
let n_refs: usize = ops
.iter()
.filter_map(|o| if let Op::Add { items, .. } = o { Some(items) } else { None })
.flatten()
.map(|d| d["geom"]["refs"].as_array().map_or(0, |a| a.iter().filter(|x| !x.is_null()).count()))
.sum();
assert!(n_refs >= 4, "{n_refs}");
}
}
+24 -1
View File
@@ -35,6 +35,9 @@ pub struct Document {
/// Je Op der zuletzt angewendeten Folge (Commit, Abgleich, Undo/Redo) die Position des von `replace`
/// getroffenen Elements: TS führt die Leseansicht damit ohne Suche nach ([`Document::last_hits`]).
last_hits: Vec<Option<usize>>,
/// Nachführ-Ops der assoziativen Bemassung ([38], `dim_assoc`) des letzten Commits: im selben
/// Undo-Schritt angewendet; TS führt seine Leseansicht damit nach ([`Document::last_extra`]).
last_extra: Vec<Op>,
}
/// Änderungsstände ([K4], Caches der Ableitungen): ein globaler Zähler; jede Op vergibt ihrem Feld
@@ -347,6 +350,11 @@ impl Document {
&self.last_hits
}
/// Zusatz-Ops des letzten Commits (assoziative Bemassung nachgeführt, [38]); leer = keine.
pub fn last_extra(&self) -> &[Op] {
&self.last_extra
}
/// Die Wurzel mit dem Positions-Index des Dokuments (Suche per id, s. [`Lookup`]).
pub fn lookup(&self) -> Lookup<'_> {
Lookup { root: &self.root, pos: Some(&self.pos) }
@@ -659,7 +667,22 @@ impl Document {
/// Dokument über; der Verlauf hält nur die inversen Ops (den Redo-Schritt liefert das Rückgängig-
/// machen selbst: die Inverse der Inversen, s. [`Document::undo`]).
pub fn commit(&mut self, ops: Vec<Op>, key: Option<&str>, now: f64, sanitize: bool) -> Result<(), Vec<String>> {
let inverse = self.apply_checked(ops, sanitize)?;
let touches = crate::dim_assoc::touches_sources(&ops);
let mut inverse = self.apply_checked(ops, sanitize)?;
self.last_extra.clear();
if touches {
// Assoziative Bemassung nachführen ([38]): gleicher Undo-Schritt, Treffer bleiben die der Benutzer-Ops.
let extra = crate::dim_assoc::sync_ops(&self.lookup());
if !extra.is_empty() {
let hits = std::mem::take(&mut self.last_hits);
if let Ok(mut inv) = self.apply_checked(extra.clone(), false) {
inv.extend(inverse);
inverse = inv;
self.last_extra = extra;
}
self.last_hits = hits;
}
}
self.history.record(inverse, key, now);
Ok(())
}
+6 -2
View File
@@ -609,7 +609,9 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option<Val
let pts = arr(field(g, "pts"));
let n = pts.len();
if index < n as f64 {
return set("pts", replace_at(pts, index, &p));
// Von Hand gezogener Punkt ist frei ([38]).
let ng = with(g, "pts", replace_at(pts, index, &p));
return Some(with_geom(d, crate::dim_assoc::without_ref(&ng, index_in(index, n))));
}
if index == n as f64 {
// Griff auf der Masslinie: nur `offset` (Normalabstand zur Punktreihe).
@@ -750,7 +752,9 @@ fn drawing_moved(d: &Value, dx: f64, dy: f64) -> Option<Value> {
let mv = |k: &str| moved(g.get(k).unwrap_or(&Value::Null), dx, dy);
let ng = match shape(g) {
"line" => with_all(g, vec![("a", mv("a")), ("b", mv("b"))]),
"polyline" | "bezier" | "spline" | "dimension" => with(g, "pts", moved_all(arr(field(g, "pts")), dx, dy)),
"polyline" | "bezier" | "spline" => with(g, "pts", moved_all(arr(field(g, "pts")), dx, dy)),
// Allein verschobene Bemassung löst ihre Bezüge ([38]).
"dimension" => crate::dim_assoc::without_ref(&with(g, "pts", moved_all(arr(field(g, "pts")), dx, dy)), None),
"rect" | "image" => with_all(g, vec![("min", mv("min")), ("max", mv("max"))]),
"circle" | "arc" | "ellipse" => with(g, "center", mv("center")),
"kote" | "detailref" | "scalebar" | "pointmarker" | "text" => with(g, "at", mv("at")),
+1
View File
@@ -119,6 +119,7 @@ pub mod opening_presets;
pub mod surface_pattern;
pub mod surface_pattern3d;
pub mod standards;
pub mod dim_assoc;
#[cfg(feature = "web")]
mod web;
+60
View File
@@ -102,6 +102,59 @@ pub enum ColumnProfile {
Round { radius: f64 },
}
/// Merkmal, an dem ein Bemassungspunkt hängt ([38], `dim_assoc.rs`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
pub enum DimFeature {
/// Punkt auf einer Wandlinie: `index` = Schichtgrenze (0 = erste Fläche, wie die Fanglinien;
/// fehlt = Achse), `t` = Anteil entlang Anfang→Ende (0/1 = Wandende).
#[serde(rename = "wall")]
Wall,
/// Öffnung: `index` 0 = Leibung Anfang, 1 = Leibung Ende, 2 = Mitte; `index2` = Schichtgrenze
/// der Wirtswand (fehlt = Achse).
#[serde(rename = "opening")]
Opening,
/// Eckpunkt `index` (Stützen-Umriss, Decken-/Dach-/Raum-Umriss, Punkte einer 2D-Zeichnung).
#[serde(rename = "vertex")]
Vertex,
/// Punkt auf Kante `index` (Anfang→nächster Eckpunkt) beim Anteil `t` (0.5 = Mitte).
#[serde(rename = "edge")]
Edge,
/// Mittelpunkt (Stütze, Kreis, Bogen, Ellipse).
#[serde(rename = "center")]
Center,
/// Schnittpunkt der Wandlinie (`id`, `index`) mit der Wandlinie (`id2`, `index2`) — Ecken.
#[serde(rename = "intersection")]
Intersection,
}
/// Bezug eines Bemassungspunkts auf ein Element ([38]).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
pub struct DimRef {
/// Element-id (Wand, Öffnung, Stütze, Decke, Dach, Raum oder 2D-Zeichnung).
pub id: String,
pub feature: DimFeature,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub index: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub t: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub id2: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub index2: Option<u32>,
/// Normalabstand Merkmal → Masslinie (Modell-Meter, links der Masslinie positiv); fehlt = 0.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub d: Option<f64>,
/// Bezug ungültig (Element/Punkt weg): der Punkt bleibt an der zuletzt gespeicherten Lage.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub lost: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
pub struct Offset2 {
pub along: f64,
@@ -272,6 +325,13 @@ pub enum Drawing2DGeom {
#[serde(rename = "textOffsetsMm", default, skip_serializing_if = "Option::is_none")]
#[ts(optional, inline)]
text_offsets_mm: Option<Vec<Offset2>>,
/// Assoziative Bemassung ([38]): je Punkt (Index wie `pts`) der Bezug auf ein Merkmal eines
/// Elements (`null` = freier Punkt). Der Kern führt `pts` nach jeder Änderung nach
/// (`dim_assoc.rs`); `pts` ist damit immer die zuletzt aufgelöste Lage und der Rückfall,
/// wenn ein Bezug ungültig wird. Fehlt das Feld, ist die Bemassung frei wie bisher.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
refs: Option<Vec<Option<DimRef>>>,
},
/// Höhenkote (SIA 400 B.5.4, Figur 18): Dreieck-Symbol + Höhenwert (Meter,
/// ±0.00-Referenz frei wählbar, s. Norm) an einem Punkt. `kind` bestimmt
+17 -1
View File
@@ -76,6 +76,10 @@ const MAX_BLOCK_DEPTH: u32 = 32;
const DASH_REF_STYLE: u32 = 1_000_000;
const DASH_REF_XLINE: u32 = 999_999;
/// Marke eines Bemassungspunkts mit ungültigem Bezug ([38], nur Bildschirm): Radius in Papier-mm, Farbe.
const LOST_MARK_MM: f64 = 1.2;
const LOST_MARK_COLOR: &str = "#e0301e";
/// Papier-mm → Modell-Meter beim Massstab 1:`scale` (`mmToModel`).
pub fn mm_to_model(mm: f64, scale: f64) -> f64 {
(mm / 1000.0) * scale
@@ -734,7 +738,7 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed
em.seg(q[q.len() - 1], q[0]);
}
}
Drawing2DGeom::Dimension { pts, offset, gap_mm, overshoot_mm, tick_len_mm, text_height_mm, line_weight_mm, ext_weight_mm, tick_weight_mm, text_offsets_mm } => {
Drawing2DGeom::Dimension { pts, offset, gap_mm, overshoot_mm, tick_len_mm, text_height_mm, line_weight_mm, ext_weight_mm, tick_weight_mm, text_offsets_mm, refs } => {
let mm = |x: f64| mm_to_model(x, scale);
for i in 0..pts.len().saturating_sub(1) {
let st = DimStyle {
@@ -752,6 +756,18 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed
};
dimension_segment(&mut em, pts[i], pts[i + 1], *offset, &st);
}
// Ungültiger Bezug ([38]): nur am Bildschirm eine rote Marke am Punkt.
if !c.a.for_print {
for i in crate::dim_assoc::lost_points(refs.as_ref()) {
if let Some(q) = pts.get(i) {
let r = mm(LOST_MARK_MM);
em.sink.push(
Primitive::DrawingCircle { center: *q, r, fill: LOST_MARK_COLOR.into(), stroke: LOST_MARK_COLOR.into(), weight_mm: em.weight, dash: None, drawing_id: Some(em.id.into()), greyed: Some(em.greyed), opacity: None },
0,
);
}
}
}
}
Drawing2DGeom::Kote { at, value, kind, .. } => {
push_kote(em.sink, *at, *value, *kind, em.color, em.weight, em.greyed, Some(em.id), symbol_factor(p, &d.level_id));
+3
View File
@@ -1176,6 +1176,8 @@ fn drawing_selection(root: &Map<String, Value>, d: &Value) -> J {
(None, None, Some(Value::Null))
};
let is_image = str_of(field(g, "shape")) == Some("image");
// Assoziative Bemassung ([38]): Bezug je Punkt (`null` = frei) für die Objekt-Info.
let dim_refs = if str_of(field(g, "shape")) == Some("dimension") { field(g, "refs").filter(|r| r.is_array()).cloned() } else { None };
let detail = (str_of(field(g, "shape")) == Some("detailref")).then(|| {
let layouts = J::arr(arr(root.get("layouts")).iter().map(|l| O::default().raw("id", l, "id").raw("name", l, "name").done()));
O::default().raw("label", g, "label").raw("sheetLayoutId", g, "sheetLayoutId").raw("sheetLabel", g, "sheetLabel").v("availableLayouts", layouts).done()
@@ -1207,6 +1209,7 @@ fn drawing_selection(root: &Map<String, Value>, d: &Value) -> J {
.o("opacity", if is_image { Some(nn(field(g, "opacity")).cloned().unwrap_or_else(|| Value::from(1u64))) } else { field(d, "opacity").cloned() })
.v("bbox", bbox_value(geom_bbox(g)))
.o("detailRef", detail)
.o("dimRefs", dim_refs)
.done()
}
+14
View File
@@ -292,6 +292,20 @@ pub fn doc_query_bin(h: u32, name: &str, args: &[f64], text: &str) -> Vec<u8> {
/// Je Op der zuletzt angewendeten Folge (`doc_commit`, `doc_apply`, `doc_grip_commit`, `doc_undo`,
/// `doc_redo`) die Position des von `replace` getroffenen Elements, −1 = keine (TS führt die
/// Leseansicht damit ohne Suche nach, `applyOps`).
/// Zusatz-Ops des letzten Commits (assoziative Bemassung nachgeführt, [38]) als JSON-Array; leer = keine.
#[wasm_bindgen]
pub fn doc_last_extra(h: u32) -> String {
with_doc(h, |d| {
if d.last_extra().is_empty() {
return String::new();
}
let mut out = Vec::new();
crate::ops::write_ops(&mut out, d.last_extra());
String::from_utf8(out).unwrap_or_default()
})
.unwrap_or_default()
}
#[wasm_bindgen]
pub fn doc_last_hits(h: u32) -> Vec<f64> {
with_doc(h, |d| d.last_hits().iter().map(|p| p.map_or(-1.0, |i| i as f64)).collect()).unwrap_or_default()
+11
View File
@@ -1435,6 +1435,15 @@ export default function App() {
applyChange((p) => patchItems(p, "drawings2d", selectedDrawingIds, (d) => ({ ...d, noPrint: next })));
};
// „Bemassung lösen" ([38]): gewählte Bemassungen mit Bezügen auf Modell-Elemente.
const attachedDimensionIds = selectedDrawingIds.filter((id) => {
const g = project.drawings2d.find((d) => d.id === id)?.geom;
return g?.shape === "dimension" && !!g.refs?.some(Boolean);
});
const detachDimensions = () => {
if (attachedDimensionIds.length) applyChange((p) => cmdMutation({ cmd: "dimdetach", ids: attachedDimensionIds }).toOps(p));
};
// Ctrl/Cmd+G / Ctrl/Cmd+Shift+G = Gruppieren/Auflösen (Vectorworks-artig,
// s. state/groupActions.ts). `applyGroupSelection` setzt nach dem Gruppieren/
// Auflösen alle betroffenen Auswahl-Kanäle auf einen Schlag.
@@ -4164,6 +4173,8 @@ export default function App() {
isolateSelectionLayers,
selectionAllNoPrint: !!selectionAllNoPrint,
toggleSelectionNoPrint,
attachedDimensionCount: attachedDimensionIds.length,
detachDimensions,
bringToFront: () => reorderDrawings(selectedDrawingIds, "front"),
bringForward: () => reorderDrawings(selectedDrawingIds, "forward"),
sendBackward: () => reorderDrawings(selectedDrawingIds, "backward"),
+32
View File
@@ -0,0 +1,32 @@
// Bemassung lösen ([38]) — entfernt die Bezüge der gewählten Bemassungen auf Modell-Elemente
// (assoziative Bemassung, `dim_assoc.rs`): die Punkte bleiben, wo sie sind, folgen aber nicht mehr.
// Sofort-Befehl ohne Punkt-Eingabe (wie Auflösen): wirkt auf die bestehende Auswahl.
import { cmdMutation } from "../../core";
import type { Command, CommandContext, CommandResult, CommandState } from "../types";
const done = (): [CommandState, CommandResult] => [
{ phase: "idle", lastPoint: null },
{ draft: null, done: true },
];
export const dimdetachCommand: Command = {
name: "dimdetach",
labelKey: "cmd.dimdetach.label",
prompt: () => "cmd.dimdetach.label",
accepts: () => [],
options: () => [],
init: (): CommandState => ({ phase: "idle", lastPoint: null }),
autoRun: (ctx: CommandContext): CommandResult => {
const sel = ctx.selection;
const ids = sel.drawingIds?.length ? sel.drawingIds : sel.drawingId ? [sel.drawingId] : [];
if (ids.length === 0) return { draft: null, done: true };
return { draft: null, done: true, commit: cmdMutation({ cmd: "dimdetach", ids }) };
},
onInput: (): [CommandState, CommandResult] => done(),
onMove: (state): [CommandState, CommandResult] => [state, { draft: null }],
onConfirm: (): [CommandState, CommandResult] => done(),
onCancel: (): [CommandState, CommandResult] => done(),
};
+17 -9
View File
@@ -24,6 +24,7 @@
import { segmentHud } from "../../tools/types";
import type {
CmdInput,
Command,
CommandContext,
CommandField,
@@ -76,6 +77,8 @@ interface DimStart extends CommandState {
interface DimNext extends CommandState {
phase: "next";
pts: Vec2[];
/** Gefangene Klickpunkte (roh, vor der Projektion) — daran hängt die Kette assoziativ ([38]). */
snaps?: Vec2[];
cursor: Vec2 | null;
/** ID der bearbeiteten Kette (Ergänzen-Modus) — null = neue Kette. */
editId: string | null;
@@ -83,6 +86,7 @@ interface DimNext extends CommandState {
interface DimOffset extends CommandState {
phase: "offset";
pts: Vec2[];
snaps?: Vec2[];
cursor: Vec2 | null;
editId: string | null;
}
@@ -117,8 +121,12 @@ function offsetDraft(ctx: CommandContext, pts: Vec2[], at: Vec2 | null): ToolDra
}
/** Commit (Kern): Kette (Nullstrecken entfernt) mit Abstand bzw. Seite eines Punkts; `editId` ändert eine bestehende. */
const commitChain = (ctx: CommandContext, pts: Vec2[], offset: number | null, side: Vec2 | null, editId: string | null) =>
createMutation(ctx, { cmd: "dimension", pts, offset, side, editId });
const commitChain = (ctx: CommandContext, pts: Vec2[], offset: number | null, side: Vec2 | null, editId: string | null, snaps: Vec2[] = []) =>
createMutation(ctx, { cmd: "dimension", pts, offset, side, editId, snaps });
/** Gefangene Punkte samt neuem Klick (nur wenn er gefangen wurde). */
const withSnap = (snaps: Vec2[] | undefined, input: CmdInput): Vec2[] =>
input.kind === "point" && input.snap ? [...(snaps ?? []), input.point] : (snaps ?? []);
const idle = (): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null },
@@ -147,11 +155,11 @@ export const dimensionCommand: Command = {
if (input.id === "undo") {
const pts = s.pts.slice(0, -1);
if (pts.length === 0) return [{ phase: "start", lastPoint: null }, { draft: null }];
const ns: DimNext = { phase: "next", pts, cursor: s.cursor, editId: s.editId, lastPoint: pts[pts.length - 1] };
const ns: DimNext = { phase: "next", pts, cursor: s.cursor, editId: s.editId, lastPoint: pts[pts.length - 1], snaps: s.snaps };
return [ns, { draft: chainDraft(pts, s.cursor) }];
}
if (input.id === "finish" && s.pts.length >= 2) {
const ns: DimOffset = { phase: "offset", pts: s.pts, cursor: s.cursor, editId: s.editId, lastPoint: s.lastPoint };
const ns: DimOffset = { phase: "offset", pts: s.pts, cursor: s.cursor, editId: s.editId, lastPoint: s.lastPoint, snaps: s.snaps };
return [ns, { draft: offsetDraft(ctx, s.pts, null) }];
}
return [s, { draft: chainDraft(s.pts, s.cursor) }];
@@ -166,13 +174,13 @@ export const dimensionCommand: Command = {
const existing = selectedChain(ctx);
const pts = existing ? insertIntoChain(ctx, existing.pts, pt) : [pt];
const editId = existing ? existing.id : null;
const ns: DimNext = { phase: "next", pts, cursor: pt, editId, lastPoint: pt };
const ns: DimNext = { phase: "next", pts, cursor: pt, editId, lastPoint: pt, snaps: withSnap([], input) };
return [ns, { draft: chainDraft(pts, pt) }];
}
// Ab dem dritten Punkt (bzw. jedem weiteren Klick im Ergänzen-Modus):
// auf die durch Punkt 1/2 festgelegte Gerade projizieren/einsortieren.
const pts = s.pts.length >= 2 ? insertIntoChain(ctx, s.pts, pt) : [...s.pts, pt];
const ns: DimNext = { phase: "next", pts, cursor: pt, editId: s.editId, lastPoint: pt };
const ns: DimNext = { phase: "next", pts, cursor: pt, editId: s.editId, lastPoint: pt, snaps: withSnap(s.snaps, input) };
return [ns, { draft: chainDraft(pts, pt) }];
}
@@ -180,8 +188,8 @@ export const dimensionCommand: Command = {
if (input.kind !== "number" && input.kind !== "point") return [s, { draft: offsetDraft(ctx, s.pts, null) }];
const commit =
input.kind === "number"
? commitChain(ctx, s.pts, input.value, null, s.editId)
: commitChain(ctx, s.pts, null, input.point, s.editId);
? commitChain(ctx, s.pts, input.value, null, s.editId, s.snaps)
: commitChain(ctx, s.pts, null, input.point, s.editId, s.snaps);
return [{ phase: "start", lastPoint: null }, { draft: null, done: true, commit }];
},
@@ -210,7 +218,7 @@ export const dimensionCommand: Command = {
onConfirm: (state, ctx): [CommandState, CommandResult] => {
const s = state as DimState;
if (s.phase === "next" && s.pts.length >= 2) {
const ns: DimOffset = { phase: "offset", pts: s.pts, cursor: s.cursor, editId: s.editId, lastPoint: s.lastPoint };
const ns: DimOffset = { phase: "offset", pts: s.pts, cursor: s.cursor, editId: s.editId, lastPoint: s.lastPoint, snaps: s.snaps };
return [ns, { draft: offsetDraft(ctx, s.pts, null) }];
}
return idle();
+4
View File
@@ -45,6 +45,7 @@ import { mirrorCommand } from "./cmds/mirror";
import { rotateCommand } from "./cmds/rotate";
import { scaleCommand } from "./cmds/scale";
import { explodeCommand } from "./cmds/explode";
import { dimdetachCommand } from "./cmds/dimdetach";
import { autodimCommand } from "./cmds/autodim";
import { alignCommand } from "./cmds/align";
import { joinCommand } from "./cmds/join";
@@ -111,6 +112,7 @@ export const COMMANDS: Record<string, Command> = {
rotate: rotateCommand,
scale: scaleCommand,
explode: explodeCommand,
dimdetach: dimdetachCommand,
autodim: autodimCommand,
align: alignCommand,
join: joinCommand,
@@ -229,6 +231,8 @@ export const ALIASES: Record<string, string> = {
skalieren: "scale",
x: "explode",
aufloesen: "explode",
bml: "dimdetach",
bemassungloesen: "dimdetach",
ab: "autodim",
aussenbemassung: "autodim",
al: "align",
+27 -9
View File
@@ -286,9 +286,10 @@ export class ProjectDocument {
}
return { problems };
}
const project = applyOps(base, ops, core().doc_last_hits(this.handle));
const extra = this.lastExtra();
const project = this.withExtra(applyOps(base, ops, core().doc_last_hits(this.handle)), extra);
this.mirror = project;
this.rememberCommit(base, project, ops);
this.rememberCommit(base, project, extra.length ? [...ops, ...extra] : ops);
return { project };
}
@@ -306,9 +307,10 @@ export class ProjectDocument {
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, notice: r.notice };
const project = applyOps(base, r.ops, core().doc_last_hits(this.handle));
const extra = this.lastExtra();
const project = this.withExtra(applyOps(base, r.ops, core().doc_last_hits(this.handle)), extra);
this.mirror = project;
return { project, ops: r.ops, notice: r.notice };
return { project, ops: extra.length ? [...r.ops, ...extra] : r.ops, notice: r.notice };
}
/**
@@ -354,9 +356,10 @@ export class ProjectDocument {
const r = fromMarkedJson<{ ops: CoreOp[] } | { problems: string[] }>(out);
if ("problems" in r) return r;
if (r.ops.length === 0) return { project: base, ops: r.ops };
const project = applyOps(base, r.ops);
const extra = this.lastExtra();
const project = this.withExtra(applyOps(base, r.ops), extra);
this.mirror = project;
return { project, ops: r.ops };
return { project, ops: extra.length ? [...r.ops, ...extra] : r.ops };
}
/**
@@ -371,10 +374,12 @@ export class ProjectDocument {
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
const r = fromMarkedJson<({ ops: CoreOp[] } & R) | { problems: string[] }>(out);
if ("problems" in r) return r;
const project = r.ops.length ? applyOps(base, r.ops) : base;
const extra = r.ops.length ? this.lastExtra() : [];
const project = r.ops.length ? this.withExtra(applyOps(base, r.ops), extra) : base;
this.mirror = project;
this.rememberCommit(base, project, r.ops);
return { ...r, project };
const ops = extra.length ? [...r.ops, ...extra] : r.ops;
this.rememberCommit(base, project, ops);
return { ...r, ops, project };
}
/**
@@ -504,6 +509,19 @@ export class ProjectDocument {
}
/** Nach einer angenommenen Änderung: grossen, eigenen (nicht verschmolzenen) Schritt merken. */
/**
* Nachführ-Ops des letzten Commits ([38], assoziative Bemassung): der Kern hat sie im selben
* Undo-Schritt angewendet, die Leseansicht übernimmt sie hinter den eigenen Ops.
*/
private lastExtra(): CoreOp[] {
const json = this.handle ? core().doc_last_extra(this.handle) : "";
return json ? (JSON.parse(json) as CoreOp[]) : [];
}
private withExtra(project: Project, extra: readonly CoreOp[]): Project {
return extra.length ? applyOps(project, extra) : project;
}
private rememberCommit(base: Project, project: Project, ops: readonly CoreOp[]): void {
const [seq, , merged] = this.historySeqs();
if (!merged) this.steps.remember(seq, base, project, ops);
+13
View File
@@ -826,6 +826,17 @@ export const de = {
// ── Extrusions-Attribute (truck-Integration, Object-Info-Panel) ─────────
"objinfo.sectionLine.section": "Schnittlinie",
"objinfo.detailRef.section": "Detail-/Schnitt-Verweis",
"objinfo.dimRefs.section": "Assoziative Bemassung",
"objinfo.dimRefs.point": "Punkt {n}",
"objinfo.dimRefs.free": "frei",
"objinfo.dimRefs.lost": "Bezug verloren ({id})",
"objinfo.dimRefs.lostHint": "Rot markierte Punkte haben ihren Bezug verloren und bleiben an der letzten Lage.",
"objinfo.dimRefs.feature.wall": "Wand",
"objinfo.dimRefs.feature.opening": "Öffnung",
"objinfo.dimRefs.feature.vertex": "Eckpunkt",
"objinfo.dimRefs.feature.edge": "Kante",
"objinfo.dimRefs.feature.center": "Mittelpunkt",
"objinfo.dimRefs.feature.intersection": "Wandecke",
"objinfo.detailRef.label": "Bezeichner",
"objinfo.detailRef.sheet": "Blatt",
"objinfo.detailRef.sheet.none": "Kein Verweis",
@@ -1797,6 +1808,7 @@ export const de = {
"cmd.align.distX": "waagrecht verteilen",
"cmd.align.distY": "senkrecht verteilen",
"cmd.explode.label": "Auflösen",
"cmd.dimdetach.label": "Bemassung lösen",
"cmd.autodim.label": "Aussenbemassung",
"cmd.scale.label": "Skalieren",
"cmd.scale.base": "Basispunkt:",
@@ -2851,6 +2863,7 @@ export const de = {
"history.cmd.dimension": "Bemassung",
"history.cmd.ellipse": "Ellipse zeichnen",
"history.cmd.explode": "Auflösen",
"history.cmd.dimdetach": "Bemassung lösen",
"history.cmd.extend": "Verlängern",
"history.cmd.extrude": "Extrusion",
"history.cmd.fillet": "Verrundung",
+13
View File
@@ -822,6 +822,17 @@ export const en: Record<TranslationKey, string> = {
// ── Extruded solid attributes (truck integration, object info panel) ────
"objinfo.sectionLine.section": "Section line",
"objinfo.detailRef.section": "Detail/section reference",
"objinfo.dimRefs.section": "Associative dimension",
"objinfo.dimRefs.point": "Point {n}",
"objinfo.dimRefs.free": "free",
"objinfo.dimRefs.lost": "Reference lost ({id})",
"objinfo.dimRefs.lostHint": "Points marked red lost their reference and stay at their last position.",
"objinfo.dimRefs.feature.wall": "Wall",
"objinfo.dimRefs.feature.opening": "Opening",
"objinfo.dimRefs.feature.vertex": "Vertex",
"objinfo.dimRefs.feature.edge": "Edge",
"objinfo.dimRefs.feature.center": "Centre",
"objinfo.dimRefs.feature.intersection": "Wall corner",
"objinfo.detailRef.label": "Label",
"objinfo.detailRef.sheet": "Sheet",
"objinfo.detailRef.sheet.none": "No link",
@@ -1785,6 +1796,7 @@ export const en: Record<TranslationKey, string> = {
"cmd.align.distX": "Distribute horizontally",
"cmd.align.distY": "Distribute vertically",
"cmd.explode.label": "Explode",
"cmd.dimdetach.label": "Detach dimension",
"cmd.autodim.label": "Exterior dimensions",
"cmd.scale.label": "Scale",
"cmd.scale.base": "Base point:",
@@ -2837,6 +2849,7 @@ export const en: Record<TranslationKey, string> = {
"history.cmd.dimension": "Dimension",
"history.cmd.ellipse": "Draw ellipse",
"history.cmd.explode": "Explode",
"history.cmd.dimdetach": "Detach dimension",
"history.cmd.extend": "Extend",
"history.cmd.extrude": "Extrude",
"history.cmd.fillet": "Fillet",
+11
View File
@@ -117,6 +117,9 @@ export interface MenuActions {
selectionAllNoPrint: boolean;
/** Setzt/löscht `noPrint` für die gesamte aktuelle 2D-Auswahl in einem Zug. */
toggleSelectionNoPrint: () => void;
/** Gewählte Bemassungen mit Bezügen ([38]); ab 1 erscheint „Bemassung lösen". */
attachedDimensionCount?: number;
detachDimensions?: () => void;
}
/**
@@ -377,6 +380,12 @@ function planMenuItems(
]
: [];
// „Bemassung lösen" ([38]) — nur wenn gewählte Bemassungen an Elementen hängen.
const dimDetachItems: ContextMenuItem[] =
a.attachedDimensionCount && a.detachDimensions
? [{ label: t("cmd.dimdetach.label"), icon: <MenuIcon name="link_off" />, onClick: a.detachDimensions }]
: [];
// Boolean-Einträge (Vereinigen/Subtrahieren/Schneiden) auf die 2D-Auswahl.
// Aktiv ab 2 geschlossenen Flächen; sonst deaktiviert mit erklärendem Tooltip.
const boolEnabled = a.closedSelectionCount >= 2;
@@ -452,6 +461,7 @@ function planMenuItems(
...layerItems,
...(layerItems.length ? [{ divider: true } as ContextMenuItem] : []),
...noPrintItems,
...dimDetachItems,
...(noPrintItems.length ? [{ divider: true } as ContextMenuItem] : []),
{
label: t("ctx.fitSelection"),
@@ -485,6 +495,7 @@ function planMenuItems(
...layerItems,
...(layerItems.length ? [{ divider: true } as ContextMenuItem] : []),
...noPrintItems,
...dimDetachItems,
...(noPrintItems.length ? [{ divider: true } as ContextMenuItem] : []),
...booleanItems,
{ divider: true },
+25
View File
@@ -520,6 +520,24 @@ export type CustomPalette = {
*/
export type DetailLevel = "grob" | "mittel" | "fein";
/** Merkmal, an dem ein Bemassungspunkt hängt ([38], `dim_assoc.rs`). */
export type DimFeature = "wall" | "opening" | "vertex" | "edge" | "center" | "intersection";
/** Bezug eines Bemassungspunkts auf ein Element ([38]). */
export type DimRef = {
/** Element-id (Wand, Öffnung, Stütze, Decke, Dach, Raum oder 2D-Zeichnung). */
id: string;
feature: DimFeature;
index?: number;
t?: number;
id2?: string;
index2?: number;
/** Normalabstand Merkmal → Masslinie (Modell-Meter, links der Masslinie positiv); fehlt = 0. */
d?: number;
/** Bezug ungültig (Element/Punkt weg): der Punkt bleibt an der zuletzt gespeicherten Lage. */
lost?: boolean;
};
/** Masse einer Türzarge/eines Türrahmens ([105]); Bedeutung je `frameKind`. Fehlt ⇒ Vorgabe. */
export type DoorFrameDetail = {
/** Falzbreite (parallel zur Wandfläche: Überdeckung Blatt/Rahmen), Vorgabe 0.015. */
@@ -862,6 +880,13 @@ export type Drawing2DGeom =
* Index = Segmentnummer.
*/
textOffsetsMm?: Array<{ along: number; perp: number }>;
/**
* Assoziative Bemassung ([38]): je Punkt (Index wie `pts`) der Bezug auf ein Merkmal eines
* Elements (`null` = freier Punkt). Der Kern führt `pts` nach jeder Änderung nach
* (`dim_assoc.rs`); `pts` ist damit immer die zuletzt aufgelöste Lage und der Rückfall,
* wenn ein Bezug ungültig wird. Fehlt das Feld, ist die Bemassung frei wie bisher.
*/
refs?: Array<DimRef | null>;
}
| {
shape: "kote";
+2
View File
@@ -52,6 +52,7 @@ import {
ColumnSection,
SectionLineSection,
DetailRefSection,
DimRefsSection,
} from "./ObjectInfoPanel";
import { SurfacePatternPlacement } from "./SurfacePatternPlacement";
@@ -793,6 +794,7 @@ export function AttributesPanel() {
{sel.extrudedSolid && <ExtrudedSolidSection solid={sel.extrudedSolid} host={host} />}
{sel.column && <ColumnSection column={sel.column} host={host} />}
{sel.detailRef && <DetailRefSection detailRef={sel.detailRef} drawingId={sel.id} host={host} />}
{sel.dimRefs && <DimRefsSection refs={sel.dimRefs} drawingId={sel.id} host={host} />}
</div>
);
}
+39
View File
@@ -27,6 +27,7 @@ import { t } from "../i18n";
import type { TranslationKey } from "../i18n";
import { flattenCategories, formatM } from "../model/types";
import type {
DimRef,
Dormer,
DormerKind,
DrawingLevel,
@@ -586,6 +587,44 @@ export function SectionLineSection({
);
}
// ── Assoziative Bemassung ([38]) ────────────────────────────────────────────
// Je Punkt: frei, angehängt (Merkmal + Element) oder Bezug verloren; „Bemassung lösen" entfernt alle.
export function DimRefsSection({
refs,
drawingId,
host,
}: {
refs: (DimRef | null)[];
drawingId: string;
host: ReturnType<typeof usePanelHost>;
}) {
const lost = refs.some((r) => r?.lost);
return (
<>
<div className="objinfo-sep" />
<div className="objinfo-section-label">{t("objinfo.dimRefs.section")}</div>
{refs.map((r, i) => (
<div className="objinfo-field" key={i} data-testid="dim-ref">
<span className="objinfo-flabel">{t("objinfo.dimRefs.point", { n: i + 1 })}</span>
<span className="objinfo-fval">
{!r
? t("objinfo.dimRefs.free")
: r.lost
? t("objinfo.dimRefs.lost", { id: r.id })
: `${t(`objinfo.dimRefs.feature.${r.feature}` as TranslationKey)} · ${r.id}${r.id2 ? ` / ${r.id2}` : ""}`}
</span>
</div>
))}
{lost && <div className="objinfo-measure-hint">{t("objinfo.dimRefs.lostHint")}</div>}
<div className="objinfo-field">
<button type="button" className="objinfo-btn" onClick={() => host.onDetachDimension(drawingId)}>
{t("cmd.dimdetach.label")}
</button>
</div>
</>
);
}
// ── Detail-/Schnitt-Verweis-Attribut-Abschnitt ──────────────────────────────
// Bezeichner (obere Zeile) + Blattverknüpfung (Dropdown der Project.layouts,
// „kein Verweis" löst sie); ohne Verknüpfung zusätzlich ein manueller
+2
View File
@@ -285,6 +285,8 @@ export interface PanelHostValue {
onSetDetailRefSheetLayout: (drawingId: string, sheetLayoutId: string | undefined) => void;
/** Manueller Blattname-Platzhalter, nur relevant OHNE Blattverknüpfung. */
onSetDetailRefSheetLabel: (drawingId: string, sheetLabel: string) => void;
/** „Bemassung lösen" ([38]): Bezüge der Bemassung entfernen, Punkte bleiben. */
onDetachDimension: (drawingId: string) => void;
onSetHatchPlacement: (
drawingId: string,
patch: { angleDeg?: number | null; scale?: number | null; origin?: Vec2 | null },
+63
View File
@@ -0,0 +1,63 @@
// [38] Assoziative Bemassung im Store: eine an Wandenden gefangene Bemassung folgt der Wand (Kern
// führt `pts` im selben Undo-Schritt nach), „Bemassung lösen" macht sie wieder frei.
import { describe, it, expect, beforeEach } from "vitest";
import { getState, setState } from "./appStore";
import { emptyProject } from "../model/sampleProject";
import { addItems, cmdMutation, patchItem } from "../core";
import type { Drawing2D, Wall } from "../model/types";
const wall: Wall = {
id: "W1",
type: "wall",
floorId: "eg",
categoryCode: "21",
start: { x: 0, y: 0 },
end: { x: 5, y: 0 },
wallTypeId: "aw",
height: 2.6,
} as Wall;
const dim = (): Drawing2D | undefined => getState().project.drawings2d.find((d) => d.geom.shape === "dimension");
const len = (d: Drawing2D | undefined): number => {
if (d?.geom.shape !== "dimension") return NaN;
const [a, b] = d.geom.pts;
return Math.hypot(b.x - a.x, b.y - a.y);
};
beforeEach(() => {
setState({ project: emptyProject, undoDepth: 0, redoDepth: 0, canUndo: false, canRedo: false });
getState().clearHistory();
getState().applyChange(addItems("walls", [wall]));
});
describe("assoziative Bemassung [38]", () => {
it("Wand strecken → Masszahl folgt, ein Undo-Schritt", () => {
getState().setProject(
cmdMutation({ cmd: "dimension", pts: [[0, 0], [5, 0]], snaps: [[0, 0], [5, 0]], offset: 1, ctx: { level: "eg" }, stamp: "t" }),
);
const d0 = dim();
expect(d0?.geom.shape === "dimension" && d0.geom.refs?.map((r) => r?.feature)).toEqual(["wall", "wall"]);
expect(len(d0)).toBeCloseTo(5, 9);
getState().applyChange((p) => patchItem(p, "walls", "W1", { end: { x: 7.25, y: 0 } }));
expect(len(dim())).toBeCloseTo(7.25, 9);
getState().undo();
expect(len(dim())).toBeCloseTo(5, 9);
expect(getState().project.walls[0].end.x).toBe(5);
getState().redo();
expect(len(dim())).toBeCloseTo(7.25, 9);
});
it("freie Punkte bleiben frei; Lösen entfernt die Bezüge", () => {
getState().setProject(cmdMutation({ cmd: "dimension", pts: [[0, 0], [3, 3]], offset: 1, ctx: { level: "eg" }, stamp: "t" }));
const free = dim();
// Punkt (0, 0) deckt sich mit dem Wandanfang, (3, 3) ist frei.
expect(free?.geom.shape === "dimension" && free.geom.refs?.map((r) => r?.feature ?? null)).toEqual(["wall", null]);
getState().setProject(cmdMutation({ cmd: "dimdetach", ids: [free!.id] }));
const d = dim();
expect(d?.geom.shape === "dimension" && d.geom.refs).toBeUndefined();
getState().applyChange((p) => patchItem(p, "walls", "W1", { start: { x: -1, y: 0 } }));
expect(dim()?.geom).toEqual(d?.geom);
});
});
+6
View File
@@ -19,6 +19,7 @@ import type { SolidSpec } from "../engine/truckSolid";
import { documentFor } from "../core/document";
import type {
AttributeSource,
DimRef,
ColumnProfile,
ContextImage,
ContextObject,
@@ -486,6 +487,11 @@ export interface Selection {
* `geom.shape === "detailref"`).
*/
detailRef?: DetailRefInfo;
/**
* Assoziative Bemassung ([38]): Bezug je Punkt der Kette (`null` = freier Punkt), nur bei
* `geom.shape === "dimension"` mit Bezügen.
*/
dimRefs?: (DimRef | null)[];
}
/**
+2 -1
View File
@@ -8,7 +8,7 @@
// Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { applyFillMode } from "./fillMode";
import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, removeRoofHole, setFieldIfChanged, setRoofEdge } from "../core";
import { addItems, cmdMutation, fieldOps, opsMutation, patchItem, patchItems, removeItems, removeRoofHole, setFieldIfChanged, setRoofEdge } from "../core";
import type { CoreOp, ProjectMutation } from "../core";
import { useMemo, type RefObject } from "react";
import type { DrawingLevel, Project } from "../model/types";
@@ -548,6 +548,7 @@ export function usePanelHostBase(opts: {
onAddColorToCustomPalette: (paletteId, hex) => addColorToCustomPalette(paletteId, hex),
onSetDashScale: (drawingId, scale) =>
setProject(opsMutation((p) => patchItem(p, "drawings2d", drawingId, { dashScale: scale }))),
onDetachDimension: (drawingId) => setProject(cmdMutation({ cmd: "dimdetach", ids: [drawingId] })),
onSetDetailRefLabel: (drawingId, label) =>
setProject(
opsMutation((p) =>