From 6de25d7ebb60d0b2e472f59a89b9b8cac6598d3d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 22:15:22 +0000 Subject: [PATCH] [124] Kern: Zeichenbefehle lesen das Projekt typisiert (erste Charge) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit commands::ops/cmd_create::ops/preview_req und cmd_solid::ops bekommen die typisierte Sicht (Document::project_lookup, cmdOps über queries::run_root_doc). Typisiert gelesen: Kategorie-Suche (has_category/category_or/category_color), aktiver Wandtyp, Wände des Geschosses für die Raumerkennung (floor_walls_flat), Raumzahl, erster Tür-/Fenstertyp. Betrifft Decke, Raum, Treppe, Öffnung, Dach, Dachfenster, Gaube; neue Elemente entstehen weiter als JSON. --- src-tauri/core/src/cmd_create.rs | 170 +++++++++++++-------------- src-tauri/core/src/cmd_solid.rs | 21 ++-- src-tauri/core/src/commands.rs | 14 ++- src-tauri/core/src/dim_assoc.rs | 4 +- src-tauri/core/src/document.rs | 8 ++ src-tauri/core/src/model/lenient.rs | 7 ++ src-tauri/core/src/queries.rs | 11 +- src-tauri/core/src/web/cmd_create.rs | 7 +- src-tauri/core/src/web/commands.rs | 6 +- src-tauri/core/src/web/document.rs | 2 +- 10 files changed, 142 insertions(+), 108 deletions(-) diff --git a/src-tauri/core/src/cmd_create.rs b/src-tauri/core/src/cmd_create.rs index accad8e3..e2c3c078 100644 --- a/src-tauri/core/src/cmd_create.rs +++ b/src-tauri/core/src/cmd_create.rs @@ -19,6 +19,7 @@ use crate::cmd_transform::{IdGen, Shapes}; use crate::json_util::{arr, field, js_num, num_of, pt, truthy, xy}; use crate::jsmath::hypot2; use crate::jsnum; +use crate::model::{LayerCategory, Project}; use crate::ops::{id_of, Op}; use kernel2d::{self as k, Vec2 as P}; use serde_json::{json, Map, Value}; @@ -226,35 +227,38 @@ pub(crate) fn point_segment_distance(p: V, a: V, b: V) -> f64 { // ── Projekt lesen ──────────────────────────────────────────────────────────── -/// Gibt es die Kategorie `code` irgendwo im Ebenen-Baum (`layers`, rekursiv über `children`)? -pub(crate) fn has_category(root: &Map, code: &str) -> bool { - fn walk(list: &[Value], code: &str) -> bool { - list.iter().any(|c| field(c, "code").and_then(Value::as_str) == Some(code) || walk(arr(field(c, "children")), code)) +// Lesen über die typisierte Sicht (`&Project`, [124]): Muster für die weiteren Befehle. Neue Elemente +// entstehen weiter als JSON (Schlüsselreihenfolge der früheren Objekt-Literale). + +/// Erste Kategorie `code` im Ebenen-Baum (Tiefensuche über `children`, wie `flat.find`). +fn find_category<'a>(list: &'a [LayerCategory], code: &str) -> Option<&'a LayerCategory> { + for c in list { + if c.code == code { + return Some(c); + } + if let Some(f) = c.children.as_deref().and_then(|ch| find_category(ch, code)) { + return Some(f); + } } - walk(arr(root.get("layers")), code) + None +} + +/// Gibt es die Kategorie `code` irgendwo im Ebenen-Baum (`layers`, rekursiv über `children`)? +pub(crate) fn has_category(p: &Project, code: &str) -> bool { + find_category(&p.layers, code).is_some() } /// Kategorie `code`, falls vorhanden, sonst die aktive. -pub(crate) fn category_or(root: &Map, code: &str, ctx: &Ctx) -> Value { - s(if has_category(root, code) { code } else { ctx.cat }) +pub(crate) fn category_or(p: &Project, code: &str, ctx: &Ctx) -> Value { + s(if has_category(p, code) { code } else { ctx.cat }) } -/// Farbe der Kategorie `code` (erste im Baum, Tiefensuche wie `flat.find`), sonst `def`. -fn category_color(root: &Map, code: &str, def: &str) -> Value { - fn walk<'a>(list: &'a [Value], code: &str) -> Option<&'a Value> { - for c in list { - if field(c, "code").and_then(Value::as_str) == Some(code) { - return Some(c); - } - if let Some(f) = walk(arr(field(c, "children")), code) { - return Some(f); - } - } - None - } - match walk(arr(root.get("layers")), code).and_then(|c| field(c, "color")) { - None | Some(Value::Null) => s(def), - Some(c) => c.clone(), +/// Farbe der Kategorie `code` (erste im Baum), sonst `def` (auch bei leerer Farbe: fehlt sie in der +/// Datei, liest die typisierte Sicht ""). +fn category_color(p: &Project, code: &str, def: &str) -> Value { + match find_category(&p.layers, code) { + Some(c) if !c.color.is_empty() => s(&c.color), + _ => s(def), } } @@ -268,12 +272,10 @@ fn active_wall_type<'a>(root: &'a Map, ctx: &Ctx) -> Option<&'a V list.iter().find(|t| id_of(t) == Some(ctx.wall_type)).or(list.first()) } -/// id des aktiven Wandtyps (Fallback: die id aus dem Kontext). -fn active_wall_type_id(root: &Map, ctx: &Ctx) -> Value { - match active_wall_type(root, ctx) { - Some(t) => field(t, "id").cloned().unwrap_or(Value::Null), - None => s(ctx.wall_type), - } +/// id des aktiven Wandtyps (Fallback: erster Typ, sonst die id aus dem Kontext). +fn active_wall_type_id(p: &Project, ctx: &Ctx) -> Value { + let t = p.wall_types.iter().find(|t| t.id == ctx.wall_type).or(p.wall_types.first()); + s(t.map_or(ctx.wall_type, |t| t.id.as_str())) } /// Gesamtdicke eines Wand-/Deckentyps (`wallTypeThickness`: Summe der Schichten). @@ -351,11 +353,11 @@ fn wall_type_for_thickness(root: &Map, base: &Value, thickness: f /// Wand-Befehl: je Achssegment eine Wand des aktiven Typs (Null-Strecken übersprungen); eine gelockte /// Dicke (einschichtig) wählt/erzeugt den passenden Wandtyp. -fn wall_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { +fn wall_ops(root: &Map, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let pts = pts_of(v, "pts"); let height = ctx.floor_height.unwrap_or(DEF_HEIGHT); let mut type_ops = Vec::new(); - let mut type_id = active_wall_type_id(root, ctx); + let mut type_id = active_wall_type_id(p, ctx); if let (Some(base), Some(t)) = (active_wall_type(root, ctx), opt_n(v, "thick")) { if layers_len(base) == 1 && t >= MIN_THICKNESS && (t - type_thickness(base)).abs() > 1e-4 { let (o, id) = wall_type_for_thickness(root, base, t, ids); @@ -441,7 +443,7 @@ fn abs_area(pts: &[V]) -> f64 { } /// Decke aus einem geschlossenen Umriss (entartet → nichts). -fn ceiling_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { +fn ceiling_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let Some(outline) = normalize_outline(&pts_of(v, "pts")) else { return Vec::new() }; if abs_area(&outline) < 1e-4 { return Vec::new(); @@ -452,28 +454,23 @@ fn ceiling_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) ("id", s(&ids.next("C"))), ("type", s("ceiling")), ("floorId", s(ctx.level)), - ("categoryCode", category_or(root, "30", ctx)), + ("categoryCode", category_or(p, "30", ctx)), ("outline", pvs(&outline)), - ("wallTypeId", active_wall_type_id(root, ctx)), + ("wallTypeId", active_wall_type_id(p, ctx)), ])], ) } /// Wände des Geschosses als `[n, (ax, ay, bx, by, dicke)…]` für die Raumerkennung. -fn floor_walls_flat(root: &Map, level: &str) -> Vec { - let types = wall_types(root); +fn floor_walls_flat(p: &Project, level: &str) -> Vec { let mut out = vec![0.0]; let mut n = 0; - for w in arr(root.get("walls")) { - if floor_of(w) != Some(level) { - continue; - } - let tid = field(w, "wallTypeId").and_then(Value::as_str); - let wt = types.iter().find(|t| id_of(t) == tid); - let (a, b) = (xy(field(w, "start").unwrap_or(&Value::Null)), xy(field(w, "end").unwrap_or(&Value::Null))); - let t = wt.map_or(0.2, type_thickness); + for w in p.walls.iter().filter(|w| w.floor_id == level) { + let wt = p.wall_types.iter().find(|t| t.id == w.wall_type_id); + // Summe der Schichten wie `type_thickness` (Startwert 0, Reihenfolge der Liste). + let t = wt.map_or(0.2, |t| t.layers.iter().fold(0.0, |sum, l| sum + l.thickness)); // Bogenwand ([T2]): als Sehnenzug. - let pts = crate::wall_arc::axis_polyline(a, b, bulge_of(w), 0.0, t); + let pts = crate::wall_arc::axis_polyline((w.start.x, w.start.y), (w.end.x, w.end.y), w.bulge, 0.0, t); for q in pts.windows(2) { out.extend([q[0].0, q[0].1, q[1].0, q[1].1, t]); n += 1; @@ -484,8 +481,8 @@ fn floor_walls_flat(root: &Map, level: &str) -> Vec { } /// Lichter Umriss der Zelle um `at` (Raum „innen“), `None` = keine geschlossene Zelle. -fn room_inside(root: &Map, level: &str, at: V) -> Option> { - let f = crate::room_boundary::from_point(at.0, at.1, &floor_walls_flat(root, level), 0.05, true); +fn room_inside(p: &Project, level: &str, at: V) -> Option> { + let f = crate::room_boundary::from_point(at.0, at.1, &floor_walls_flat(p, level), 0.05, true); if f.is_empty() { return None; } @@ -494,9 +491,9 @@ fn room_inside(root: &Map, level: &str, at: V) -> Option> } /// Raum aus Umriss (Modus „manuell“: `pts`; „innen“: `at` → Zelle). -fn room_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { +fn room_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let boundary = match opt_p(v, "at") { - Some(at) => match room_inside(root, ctx.level, at) { + Some(at) => match room_inside(p, ctx.level, at) { Some(b) if b.len() >= 3 => b, _ => return Vec::new(), }, @@ -507,8 +504,8 @@ fn room_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> if boundary.len() < 3 || e.gross < 1e-4 { return Vec::new(); } - let code = if has_category(root, "60") { "60" } else { ctx.cat }; - let name = format!("Raum {}", arr(root.get("rooms")).len() + 1); + let code = if has_category(p, "60") { "60" } else { ctx.cat }; + let name = format!("Raum {}", p.rooms.as_ref().map_or(0, Vec::len) + 1); let doc = json!({ "version": 1, "paragraphs": [{ "runs": [{ "text": name, "marks": {} }], "align": "center" }] }); add_op( "rooms", @@ -520,7 +517,7 @@ fn room_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> ("siaCategory", s("HNF")), ("name", s(&name)), ("boundary", pvs(&boundary)), - ("color", category_color(root, code, "#5a7a9a")), + ("color", category_color(p, code, "#5a7a9a")), ("stampAnchor", pt(e.centroid[0], e.centroid[1])), ("stampDoc", doc), ])], @@ -547,7 +544,7 @@ struct StairBuilt { steps: f64, } -fn build_stair(root: &Map, v: &Value, ctx: &Ctx, id: Value) -> StairBuilt { +fn build_stair(p: &Project, v: &Value, ctx: &Ctx, id: Value) -> StairBuilt { let shape = s_of(v, "shape"); let start = p_of(v, "start"); let cursor = p_of(v, "cursor"); @@ -574,7 +571,7 @@ fn build_stair(root: &Map, v: &Value, ctx: &Ctx, id: Value) -> St ("id", id), ("type", s("stair")), ("floorId", s(ctx.level)), - ("categoryCode", category_or(root, "40", ctx)), + ("categoryCode", category_or(p, "40", ctx)), ("shape", s(shape)), ("start", pv(start)), ("dir", pv(dir)), @@ -618,14 +615,14 @@ fn build_stair(root: &Map, v: &Value, ctx: &Ctx, id: Value) -> St StairBuilt { fields: f, params, rise, steps } } -fn stair_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { - let b = build_stair(root, v, ctx, s(&ids.next("ST"))); +fn stair_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let b = build_stair(p, v, ctx, s(&ids.next("ST"))); add_op("stairs", vec![obj(b.fields)]) } /// Treppen-Vorschau: Tritte, Podest, Lauflinie; `info = [Stufenzahl]`. -fn stair_preview(root: &Map, v: &Value, ctx: &Ctx, out: &mut Shapes, info: &mut Vec) { - let b = build_stair(root, v, ctx, Value::Null); +fn stair_preview(p: &Project, v: &Value, ctx: &Ctx, out: &mut Shapes, info: &mut Vec) { + let b = build_stair(p, v, ctx, Value::Null); info.push(b.steps); let f = crate::stair::geometry(&b.params, b.rise); if f.len() < 4 { @@ -709,7 +706,7 @@ fn pick_wall<'a>(root: &'a Map, level: &str, p: V) -> Option<(&'a } /// Öffnung in eine Wand (`start`/`end` der Host-Wand beim Picken, `pos` = Abstand vom Wandanfang). -fn opening_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { +fn opening_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let (st, en) = (p_of(v, "start"), p_of(v, "end")); let len = match arc_of(st, en, opt_n(v, "bulge")) { Some(a) => a.length(), @@ -718,13 +715,14 @@ fn opening_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) let width = jsnum::max(0.1, jsnum::min(n_of(v, "width"), len)); let position = jsnum::max(0.0, jsnum::min(n_of(v, "pos"), jsnum::max(0.0, len - width))); let door = s_of(v, "kind") == "door"; - let lib = arr(root.get(if door { "doorTypes" } else { "windowTypes" })); - let type_id = lib.first().and_then(|t| field(t, "id")).filter(|id| truthy(Some(id))); + // Erster Typ der Bibliothek (leere id = keiner, JS-Wahrheitswert). + let first = if door { p.door_types.as_ref().and_then(|l| l.first()).map(|t| &t.id) } else { p.window_types.as_ref().and_then(|l| l.first()).map(|t| &t.id) }; + let type_id = first.filter(|id| !id.is_empty()); let mut f = vec![ ("id", s(&ids.next("O"))), ("type", s("opening")), ("hostWallId", s(s_of(v, "wall"))), - ("categoryCode", category_or(root, "21", ctx)), + ("categoryCode", category_or(p, "21", ctx)), ("kind", s(s_of(v, "kind"))), ("position", js_num(position)), ("width", js_num(width)), @@ -732,7 +730,7 @@ fn opening_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) ("sillHeight", js_num(if door { 0.0 } else { n_of(v, "sill") })), ]; if let Some(t) = type_id { - f.push(("typeId", t.clone())); + f.push(("typeId", s(t))); } if door { f.push(("hinge", s(s_of(v, "hinge")))); @@ -813,7 +811,7 @@ fn opening_preview(v: &Value, cursor: Option, out: &mut Shapes, info: &mut Ve // ── Dach, Stütze ───────────────────────────────────────────────────────────── -fn roof_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { +fn roof_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let (a, b) = (p_of(v, "a"), p_of(v, "b")); let (w, d) = ((b.0 - a.0).abs(), (b.1 - a.1).abs()); if w < 0.1 || d < 0.1 { @@ -826,7 +824,7 @@ fn roof_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> ("id", s(&ids.next("RF"))), ("type", s("roof")), ("floorId", s(ctx.level)), - ("categoryCode", category_or(root, "31", ctx)), + ("categoryCode", category_or(p, "31", ctx)), ("outline", pvs(&rect_corners(a, b))), ("shape", s(shape)), ("pitchDeg", js_num(if shape == "flach" { 0.0 } else { 30.0 })), @@ -959,20 +957,20 @@ fn extrude_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) // ═════════════════════════════════════════════════════════════════════════════ /// Ops eines Zeichenbefehls (`None` = kein Zeichenbefehl). -pub fn ops(root: &Map, v: &Value) -> Option> { +pub fn ops(root: &Map, p: &Project, v: &Value) -> Option> { let ctx = ctx_of(v); let mut ids = IdGen::new(s_of(v, "stamp")); let ids = &mut ids; Some(match s_of(v, "cmd") { - "wall" => wall_ops(root, v, &ctx, ids), - "ceiling" => ceiling_ops(root, v, &ctx, ids), - "room" => room_ops(root, v, &ctx, ids), - "stair" => stair_ops(root, v, &ctx, ids), - "opening" => opening_ops(root, v, &ctx, ids), - "roof" => roof_ops(root, v, &ctx, ids), + "wall" => wall_ops(root, p, v, &ctx, ids), + "ceiling" => ceiling_ops(p, v, &ctx, ids), + "room" => room_ops(p, v, &ctx, ids), + "stair" => stair_ops(p, v, &ctx, ids), + "opening" => opening_ops(p, v, &ctx, ids), + "roof" => roof_ops(p, v, &ctx, ids), "column" => column_ops(v, &ctx, ids), "extrude" => extrude_ops(root, v, &ctx, ids), - _ => return crate::cmd_draw::ops(root, v, &ctx, ids).or_else(|| crate::cmd_solid::ops(root, v, &ctx, ids)), + _ => return crate::cmd_draw::ops(root, v, &ctx, ids).or_else(|| crate::cmd_solid::ops(root, p, v, &ctx, ids)), }) } @@ -998,8 +996,8 @@ impl Preview { /// Vorschau eines Zeichenbefehls: `v` = Optionen (`cmd`, …, `ctx`), `pts` = die Punkte flach (je Befehl /// die gesetzten Punkte und zuletzt der Cursor). -pub fn preview(root: &Map, v: &Value, pts: &[f64]) -> Preview { - preview_req(root, &Req::new(v.clone()), pts) +pub fn preview(root: &Map, project: &Project, v: &Value, pts: &[f64]) -> Preview { + preview_req(root, project, &Req::new(v.clone()), pts) } /// Gelesene Vorschau-Anfrage: die Optionen und, für den Mausschritt ohne Hash-Suchen, Befehl und Kontext. @@ -1024,7 +1022,7 @@ impl Req { } /// Wie [`preview`] mit gelesener Anfrage (Mausschritt: dieselbe Anfrage, neue Punkte). -pub fn preview_req(root: &Map, req: &Req, pts: &[f64]) -> Preview { +pub fn preview_req(root: &Map, project: &Project, req: &Req, pts: &[f64]) -> Preview { let v = &req.v; let ctx = Ctx { level: &req.level, floor_height: req.floor_height, cat: &req.cat, wall_type: &req.wall_type, text_height: req.text_height, symbol: req.symbol }; let pts = flat_pts(pts); @@ -1032,9 +1030,9 @@ pub fn preview_req(root: &Map, req: &Req, pts: &[f64]) -> Preview let out = &mut p.shapes; match req.cmd.as_str() { "wall" => wall_preview(root, v, &ctx, &pts, out), - "stair" => stair_preview(root, v, &ctx, out, &mut p.info), + "stair" => stair_preview(project, v, &ctx, out, &mut p.info), "opening" => opening_preview(v, pts.first().copied(), out, &mut p.info), - "roomInside" => p.ok = pts.first().and_then(|at| room_inside(root, ctx.level, *at)).is_some_and(|b| b.len() >= 3), + "roomInside" => p.ok = pts.first().and_then(|at| room_inside(project, ctx.level, *at)).is_some_and(|b| b.len() >= 3), "column" => { if let Some(at) = pts.first() { out.poly(&column_footprint(*at, v)); @@ -1161,7 +1159,7 @@ mod tests { fn bogenwand_drei_punkt_und_tangential() { let r = root(json!({"wallTypes": [{"id": "WT1", "name": "Beton", "layers": [{"componentId": "c", "thickness": 0.2}]}]})); // (0,0)→(4,0) durch (2,2): Halbkreis, Scheitel links → Modell-Bulge +1; dann tangential weiter nach (4,-4)? - let o = ops(&r, &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0], [8, 0]], "segs": [{"x": 2, "y": 2}, 1], "thick": null}))).unwrap(); + let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0], [8, 0]], "segs": [{"x": 2, "y": 2}, 1], "thick": null}))).unwrap(); let w = items(&o, 0); let b0 = w[0]["bulge"].as_f64().unwrap(); assert!((b0 - 1.0).abs() < 1e-9, "{b0}"); @@ -1169,19 +1167,19 @@ mod tests { let b1 = w[1]["bulge"].as_f64().unwrap(); assert!((b1 + 1.0).abs() < 1e-9, "{b1}"); // Gerade Wand ohne `bulge`-Feld. - let o = ops(&r, &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0]], "segs": [0], "thick": null}))).unwrap(); + let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0]], "segs": [0], "thick": null}))).unwrap(); assert!(items(&o, 0)[0].get("bulge").is_none()); } #[test] fn waende_je_segment_mit_typ_und_hoehe() { let r = root(json!({"wallTypes": [{"id": "WT1", "name": "Beton", "layers": [{"componentId": "c", "thickness": 0.2}]}]})); - let o = ops(&r, &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0], [4, 0], [4, 3]], "thick": null}))).unwrap(); + let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0], [4, 0], [4, 3]], "thick": null}))).unwrap(); let w = items(&o, 0); assert_eq!(w.as_array().unwrap().len(), 2); assert_eq!(w[0], json!({"id": "W-s-1", "type": "wall", "floorId": "F1", "categoryCode": "20", "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 0}, "wallTypeId": "WT1", "height": 3})); // Gelockte Dicke → neuer einschichtiger Typ vor den Wänden. - let o = ops(&r, &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0]], "thick": 0.3}))).unwrap(); + let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0]], "thick": 0.3}))).unwrap(); assert_eq!(items(&o, 0)[0], json!({"id": "WT-s-1", "name": "Beton 30 cm", "layers": [{"componentId": "c", "thickness": 0.3}]})); assert_eq!(items(&o, 1)[0]["wallTypeId"], "WT-s-1"); } @@ -1206,7 +1204,7 @@ mod tests { let r = root(json!({"wallTypes": wt, "rooms": [], "layers": [{"code": "60", "color": "#abc"}], "walls": [ wall("a", (0.0, 0.0), (5.0, 0.0)), wall("b", (5.0, 0.0), (5.0, 4.0)), wall("c", (5.0, 4.0), (0.0, 4.0)), wall("d", (0.0, 4.0), (0.0, 0.0))], "groups": [{"id": "g", "name": "G", "wallIds": ["a"], "drawingIds": []}]})); - let o = ops(&r, &req(json!({"cmd": "room", "at": [2, 2]}))).unwrap(); + let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "room", "at": [2, 2]}))).unwrap(); let room = &items(&o, 0)[0]; assert_eq!(room["name"], "Raum 1"); assert_eq!(room["color"], "#abc"); @@ -1228,7 +1226,7 @@ mod tests { assert_eq!(q["hit"]["id"], "w"); assert!((q["hit"]["t"].as_f64().unwrap() - std::f64::consts::PI).abs() < 1e-9); assert_eq!(q["hit"]["bulge"], 1); - let o = ops(&r, &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [4, 0], "bulge": 1, "kind": "window", "pos": 6.0, "width": 1.2, "height": 1.2, "sill": 0.9}))).unwrap(); + let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [4, 0], "bulge": 1, "kind": "window", "pos": 6.0, "width": 1.2, "height": 1.2, "sill": 0.9}))).unwrap(); let pos = items(&o, 0)[0]["position"].as_f64().unwrap(); assert!((pos - (2.0 * std::f64::consts::PI - 1.2)).abs() < 1e-9, "{pos}"); } @@ -1239,11 +1237,11 @@ mod tests { let q = query(&r, &json!({"q": "pickWall", "level": "F1", "pt": [2, 0.3]})).unwrap().unwrap(); assert_eq!(q["hit"]["id"], "w"); assert_eq!(q["hit"]["t"], 2); - let o = ops(&r, &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [6, 0], "kind": "window", "pos": 5.5, "width": 1.2, "height": 1.2, "sill": 0.9}))).unwrap(); + let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [6, 0], "kind": "window", "pos": 5.5, "width": 1.2, "height": 1.2, "sill": 0.9}))).unwrap(); let op = &items(&o, 0)[0]; assert_eq!(op["position"], 4.8); assert_eq!(op["typeId"], "FT"); - let p = preview(&r, &json!({"cmd": "opening", "start": [0, 0], "end": [6, 0], "kind": "window", "width": 1.2, "pos": null}), &[2.0, 1.0]); + let p = preview(&r, &crate::model::lenient::typed_for_test(&r), &json!({"cmd": "opening", "start": [0, 0], "end": [6, 0], "kind": "window", "width": 1.2, "pos": null}), &[2.0, 1.0]); assert_eq!(p.info[0], 2.0); assert_eq!(p.shapes.count, 2); } diff --git a/src-tauri/core/src/cmd_solid.rs b/src-tauri/core/src/cmd_solid.rs index 201e07c3..cfb044ea 100644 --- a/src-tauri/core/src/cmd_solid.rs +++ b/src-tauri/core/src/cmd_solid.rs @@ -10,6 +10,7 @@ use crate::cmd_transform::{IdGen, Shapes}; use crate::json_util::{arr, field, js_num, num_of, num_or, truthy, with, xy}; use crate::jsmath::hypot2; use crate::jsnum; +use crate::model::Project; use crate::ops::{id_of, Op}; use serde_json::{json, Map, Value}; @@ -554,7 +555,7 @@ fn ceiling_opening_ops(root: &Map, v: &Value, ctx: &Ctx) -> Vec, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { +fn roof_window_ops(root: &Map, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let at = p_of(v, "p"); if !(at.0.is_finite() && at.1.is_finite()) { return Vec::new(); @@ -581,7 +582,7 @@ fn roof_window_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut Id ("hostWallId", s("")), (key, s(host_id)), ("hostPoint", pv(at)), - ("categoryCode", crate::cmd_create::category_or(root, "21", ctx)), + ("categoryCode", crate::cmd_create::category_or(p, "21", ctx)), ("kind", s("window")), ("position", js_num(0.0)), ("width", js_num(width)), @@ -596,7 +597,7 @@ fn roof_window_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut Id /// Gaube ([G5]): ein Klick in eine geneigte Dachfläche setzt die Gaube (Stirnmitte am Punkt) und ein /// Fenster in ihre Stirn (`hostDormerId`). Art über `kind` (schlepp/sattel/flach/walm). -fn dormer_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { +fn dormer_ops(root: &Map, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let at = p_of(v, "p"); if !(at.0.is_finite() && at.1.is_finite()) { return Vec::new(); @@ -634,7 +635,7 @@ fn dormer_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) ("hostWallId", s("")), ("hostRoofId", s(roof_id)), ("hostDormerId", s(&did)), - ("categoryCode", crate::cmd_create::category_or(root, "21", ctx)), + ("categoryCode", crate::cmd_create::category_or(p, "21", ctx)), ("kind", s("window")), ("position", js_num(0.0)), ("width", js_num(jsnum::round(width * 0.6 * 100.0) / 100.0)), @@ -766,7 +767,7 @@ fn direction_arrow(a: V, b: V, sign: f64, out: &mut Shapes) { // Einstiege (über `cmd_create`) // ═════════════════════════════════════════════════════════════════════════════ -pub fn ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option> { +pub fn ops(root: &Map, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option> { Some(match s_of(v, "cmd") { "solid" => solid_ops(v, ctx, ids), "revolve" => revolve_ops(root, v, ctx, ids), @@ -777,8 +778,8 @@ pub fn ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> "excavation" => excavation_ops(root, v, ctx, ids), "ceilingOpening" => ceiling_opening_ops(root, v, ctx), "roofHole" => roof_hole_ops(root, v, ctx), - "roofWindow" => roof_window_ops(root, v, ctx, ids), - "dormer" => dormer_ops(root, v, ctx, ids), + "roofWindow" => roof_window_ops(root, p, v, ctx, ids), + "dormer" => dormer_ops(root, p, v, ctx, ids), "sectionline" => sectionline_ops(root, v, ids), _ => return None, }) @@ -854,7 +855,7 @@ mod tests { let run = |x: f64, y: f64, kind: &str| { let mut ids = IdGen::new("s"); let ctx = Ctx { level: "dg", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 }; - ops(root, &json!({"cmd": "dormer", "p": {"x": x, "y": y}, "kind": kind}), &ctx, &mut ids).unwrap() + ops(root, &crate::model::lenient::typed_for_test(root), &json!({"cmd": "dormer", "p": {"x": x, "y": y}, "kind": kind}), &ctx, &mut ids).unwrap() }; let o = run(4.0, 1.5, "sattel"); assert_eq!(o.len(), 2); @@ -878,7 +879,7 @@ mod tests { let run = |level: &str, x: f64| { let mut ids = IdGen::new("s"); let ctx = Ctx { level, floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 }; - ops(root, &json!({"cmd": "roofWindow", "p": {"x": x, "y": 1.0}}), &ctx, &mut ids).unwrap() + ops(root, &crate::model::lenient::typed_for_test(root), &json!({"cmd": "roofWindow", "p": {"x": x, "y": 1.0}}), &ctx, &mut ids).unwrap() }; let item = |o: &[Op]| match &o[0] { Op::Add { items, .. } => items[0].clone(), @@ -900,7 +901,7 @@ mod tests { let run = |pts: Value| { let mut ids = IdGen::new("s"); let ctx = Ctx { level: "ug", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 }; - ops(root, &json!({"cmd": "excavation", "pts": pts}), &ctx, &mut ids).unwrap() + ops(root, &crate::model::lenient::typed_for_test(root), &json!({"cmd": "excavation", "pts": pts}), &ctx, &mut ids).unwrap() }; let o = run(json!([{"x": 0, "y": 0}, {"x": 10, "y": 8}])); let Op::Add { collection, items, .. } = &o[0] else { panic!() }; diff --git a/src-tauri/core/src/commands.rs b/src-tauri/core/src/commands.rs index 75c3ab8e..a6f70d9e 100644 --- a/src-tauri/core/src/commands.rs +++ b/src-tauri/core/src/commands.rs @@ -5,6 +5,7 @@ //! (Verschieben/Drehen/Spiegeln/Skalieren/Reihe, Ausrichten/Verteilen, Block definieren). use crate::grips::{result_json, GripResult}; +use crate::model::Project; use crate::ops::Op; use serde_json::{Map, Value}; @@ -12,14 +13,15 @@ fn parse(v: &Value, what: &str) -> Result, text: &str) -> Result, String> { +/// Ops eines Befehls (`text` = JSON `{cmd, …}`, Zahlen dürfen Nicht-endlich-Marken sein). `p` = typisierte +/// Sicht derselben Wurzel (Lesen, [124]); geänderte Elemente entstehen verlustfrei aus `root`. +pub fn ops(root: &Map, p: &Project, text: &str) -> Result, String> { let v: Value = serde_json::from_str(text).map_err(|e| format!("cmdOps: {e}"))?; // Zeichnen in einer betretenen Gruppe: neue Elemente werden ihr Mitglied (`cmd_create::group_ops`). if let Some(group) = v.get("group").and_then(Value::as_str) { let mut inner = v.clone(); inner.as_object_mut().map(|m| m.remove("group")); - let mut out = ops(root, &inner.to_string())?; + let mut out = ops(root, p, &inner.to_string())?; let extra = crate::cmd_create::group_ops(root, &out, group); out.extend(extra); return Ok(out); @@ -30,7 +32,7 @@ pub fn ops(root: &Map, text: &str) -> Result, String> { if let Some(ops) = crate::cmd_edit::ops(root, &v) { return Ok(ops); } - if let Some(ops) = crate::cmd_create::ops(root, &v) { + if let Some(ops) = crate::cmd_create::ops(root, p, &v) { return Ok(ops); } Ok(match cmd { @@ -46,8 +48,8 @@ pub fn ops(root: &Map, text: &str) -> Result, String> { } /// Wie [`ops`], als Antwort-JSON `{"ops": […]}` (Zahlen mit Nicht-endlich-Marken). -pub fn ops_json(root: &Map, text: &str) -> Result { - Ok(result_json(&GripResult { ops: ops(root, text)?, notice: None })) +pub fn ops_json(root: &Map, p: &Project, text: &str) -> Result { + Ok(result_json(&GripResult { ops: ops(root, p, text)?, notice: None })) } /// Schneller Hasher für id-Mengen der Befehle (FNV-1a; je Mausschritt werden Tausende ids geprüft, diff --git a/src-tauri/core/src/dim_assoc.rs b/src-tauri/core/src/dim_assoc.rs index bb65bbaa..da69dfb8 100644 --- a/src-tauri/core/src/dim_assoc.rs +++ b/src-tauri/core/src/dim_assoc.rs @@ -1062,14 +1062,14 @@ mod tests { 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 ops = crate::commands::ops(&r, &crate::model::lenient::typed_for_test(&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 ops = crate::commands::ops(&r, &crate::model::lenient::typed_for_test(&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 }) diff --git a/src-tauri/core/src/document.rs b/src-tauri/core/src/document.rs index 195b3de6..5ef6fc53 100644 --- a/src-tauri/core/src/document.rs +++ b/src-tauri/core/src/document.rs @@ -350,6 +350,14 @@ impl Document { Ok(self.typed.as_ref().expect("gerade gesetzt")) } + /// Typisierte Sicht und die Wurzel samt Positions-Index (getrennte Ausleihen): Befehle lesen das Projekt + /// typisiert und bauen geänderte Elemente verlustfrei aus dem rohen Baum ([124]). + pub fn project_lookup(&mut self) -> Result<(&Project, Lookup<'_>), String> { + self.project()?; + let p = self.typed.as_ref().expect("gerade gelesen"); + Ok((p, Lookup { root: &self.root, pos: Some(&self.pos) })) + } + /// Die Projekt-Wurzel als JSON (für Abfragen, die auf dem rohen Baum rechnen, s. `queries::run_root`). pub fn root(&self) -> &Map { &self.root diff --git a/src-tauri/core/src/model/lenient.rs b/src-tauri/core/src/model/lenient.rs index a0b08d94..dcd11abe 100644 --- a/src-tauri/core/src/model/lenient.rs +++ b/src-tauri/core/src/model/lenient.rs @@ -271,6 +271,13 @@ pub fn project_lenient(root: &Map) -> (Project, Vec) { (p, dropped) } +/// Typisierte Sicht einer Test-Wurzel (tolerant, unbekannte Felder erlaubt): für Tests von Funktionen, +/// die Wurzel und Sicht zugleich lesen ([124]). +#[cfg(test)] +pub fn typed_for_test(root: &Map) -> Project { + super::allowing_extra(|| project_lenient(root).0) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 436fa5d3..fe88ea5f 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -83,6 +83,16 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result Result { + if name == "cmdOps" { + let (p, lk) = d.project_lookup()?; + return crate::commands::ops_json(lk.root, p, text); + } + run_root(&d.lookup(), name, text) +} + /// Abfragen auf der rohen Projekt-Wurzel (JSON-Baum, verlustfrei; Antwort JSON). `text`: Argument als Text/JSON. /// Elemente per id sucht `lk` (im Dokument über dessen Positions-Index). pub fn run_root(lk: &crate::document::Lookup, name: &str, text: &str) -> Result { @@ -132,7 +142,6 @@ pub fn run_root(lk: &crate::document::Lookup, name: &str, text: &str) -> Result< } // Griff-Änderungen ([K4] S3, `grips.rs`): `text` = JSON der Anfrage; Antwort `{ops, notice}` (ohne Commit). // Befehle ([K4] S3, `commands.rs`): `text` = JSON `{cmd, …}`; Antwort `{ops}`. - "cmdOps" => crate::commands::ops_json(root, text), "gripOps" => { let req: crate::grips::Request = serde_json::from_str(text).map_err(|e| format!("gripOps: {e}"))?; Ok(crate::grips::result_json(&crate::grips::run(lk, &req)?)) diff --git a/src-tauri/core/src/web/cmd_create.rs b/src-tauri/core/src/web/cmd_create.rs index 543dbc9f..ee11c0bc 100644 --- a/src-tauri/core/src/web/cmd_create.rs +++ b/src-tauri/core/src/web/cmd_create.rs @@ -19,7 +19,12 @@ fn run(h: u32, req: &Req, pts: &[f64]) -> Vec { if pts.len() % 2 != 0 { return Vec::new(); } - with_doc(h, |d| crate::cmd_create::preview_req(d.root(), req, pts).flat()).unwrap_or_default() + with_doc(h, |d| { + let (p, lk) = d.project_lookup().ok()?; + Some(crate::cmd_create::preview_req(lk.root, p, req, pts).flat()) + }) + .flatten() + .unwrap_or_default() } /// Vorschau eines Zeichenbefehls auf dem Dokument `h`: `[ok, nInfo, info…, Formen…]` (Formen wie diff --git a/src-tauri/core/src/web/commands.rs b/src-tauri/core/src/web/commands.rs index a5fbf1c6..20bcd350 100644 --- a/src-tauri/core/src/web/commands.rs +++ b/src-tauri/core/src/web/commands.rs @@ -13,7 +13,11 @@ 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 { - let res = crate::grips::GripResult { ops: crate::commands::ops(d.root(), req_json)?, notice: None }; + let ops = { + let (p, lk) = d.project_lookup()?; + crate::commands::ops(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); diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index a13dfdee..375009fb 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -254,7 +254,7 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64], text: &str) -> String { /// Abfrage auf der rohen Projekt-Wurzel (`crate::queries::run_root`); Fehler wie bei [`doc_query_args`]. #[wasm_bindgen] pub fn doc_query_root(h: u32, name: &str, text: &str) -> String { - let result = with_doc(h, |d| crate::queries::run_root(&d.lookup(), name, text)).unwrap_or_else(|| Err("Dokument nicht offen".to_string())); + let result = with_doc(h, |d| crate::queries::run_root_doc(d, name, text)).unwrap_or_else(|| Err("Dokument nicht offen".to_string())); match result { Ok(json) => json, Err(e) => format!("\u{1}{e}"),