From 369d8a81b34afe96f10e9e8e0cea838bd725929e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 14:00:12 +0000 Subject: [PATCH] =?UTF-8?q?[77]=20Zauberstab:=20Klick=20in=20umschlossene?= =?UTF-8?q?=20Fl=C3=A4che=20=E2=86=92=20schraffierte=20Polylinie=20(Kern?= =?UTF-8?q?=20magic=5Fwand.rs)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- TODO.md | 6 +- src-tauri/core/src/cmd_create.rs | 17 +++++ src-tauri/core/src/cmd_draw.rs | 2 +- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/magic_wand.rs | 123 +++++++++++++++++++++++++++++++ src/commands/cmds/wand.test.ts | 43 +++++++++++ src/commands/cmds/wand.ts | 34 +++++++++ src/commands/registry.ts | 4 + src/i18n/de.ts | 2 + src/i18n/en.ts | 2 + 10 files changed, 232 insertions(+), 2 deletions(-) create mode 100644 src-tauri/core/src/magic_wand.rs create mode 100644 src/commands/cmds/wand.test.ts create mode 100644 src/commands/cmds/wand.ts diff --git a/TODO.md b/TODO.md index ec171228..a2b05224 100644 --- a/TODO.md +++ b/TODO.md @@ -1736,7 +1736,11 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). → Massstab; `io/pdfCalibrate.ts`, `ui/PdfCalibrate.tsx`). Offen: Muster/Schattierungen und Soft-Masks, Clip-Pfade mit Text (Tr 7), Kreise in Linienzügen (Rundungen als Bogen abspalten), Strichphase; Kalibrierung nicht in der Tauri-App geprüft. · M -- ○ **[77] Zauberstab.** · M +- ◐ **[77] Zauberstab.** · M — 4.11.: Befehl `wand` (Kürzel `zs`/`zauberstab`): Klick in eine von Linien umschlossene + Fläche (2D-Zeichnungen + Modellkanten des Geschosses, Kreise/Bögen als Sehnenzüge, Kreuzungen werden geteilt) → + geschlossene Polylinie mit der ersten Projekt-Schraffur; Vorschau beim Überfahren. Kern `magic_wand.rs` + (planarer Graph, kleinste Masche, `kernel2d::room_from_point_inside_faces`), Tests Rust + vitest. Offen: Wahl der + Schraffur/Option „nur Umriss", Inseln (Löcher) in der Fläche, Knopf in der Werkzeugleiste; nicht in der App geklickt. - ✅ **[78] Autotext im Plankopf.** Titelblock löst Projekt/Blatt/Massstab/Datum auf; Plannummer laufend oder `Layout.planNumber` (27.10.). - ◐ **[79] Publikationssätze.** (30.10.) Modell (Rust, optional): `Project.publishSets` (`PublishSet`: Layouts in Reihenfolge, diff --git a/src-tauri/core/src/cmd_create.rs b/src-tauri/core/src/cmd_create.rs index e2c3c078..fde2889a 100644 --- a/src-tauri/core/src/cmd_create.rs +++ b/src-tauri/core/src/cmd_create.rs @@ -491,6 +491,17 @@ fn room_inside(p: &Project, level: &str, at: V) -> Option> { } /// Raum aus Umriss (Modus „manuell“: `pts`; „innen“: `at` → Zelle). +/// Zauberstab ([77]): geschlossene Polylinie um die Masche unter `at` (mit `hatchId`, falls angegeben: Schraffur). +fn wand_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let Some(ring) = opt_p(v, "at").and_then(|at| crate::magic_wand::region_at(p, ctx.level, at)) else { return Vec::new() }; + let g = obj(vec![("shape", s("polyline")), ("pts", pvs(&ring)), ("closed", Value::Bool(true))]); + let mut d = crate::cmd_draw::drawing(ids.next("dr2d"), ctx, g); + if let (Some(m), Some(h)) = (d.as_object_mut(), v.get("hatchId").and_then(Value::as_str).filter(|h| !h.is_empty())) { + m.insert("hatchId".into(), s(h)); + } + add_op("drawings2d", vec![d]) +} + 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(p, ctx.level, at) { @@ -965,6 +976,7 @@ pub fn ops(root: &Map, p: &Project, v: &Value) -> Option> "wall" => wall_ops(root, p, v, &ctx, ids), "ceiling" => ceiling_ops(p, v, &ctx, ids), "room" => room_ops(p, v, &ctx, ids), + "wand" => wand_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), @@ -1033,6 +1045,11 @@ pub fn preview_req(root: &Map, project: &Project, req: &Req, pts: "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(project, ctx.level, *at)).is_some_and(|b| b.len() >= 3), + // Zauberstab ([77]): die gefundene Masche unter dem Cursor. + "wand" => match pts.first().and_then(|at| crate::magic_wand::region_at(project, ctx.level, *at)) { + Some(ring) => out.poly(&ring), + None => p.ok = false, + }, "column" => { if let Some(at) = pts.first() { out.poly(&column_footprint(*at, v)); diff --git a/src-tauri/core/src/cmd_draw.rs b/src-tauri/core/src/cmd_draw.rs index 05de9d0f..8d6c6644 100644 --- a/src-tauri/core/src/cmd_draw.rs +++ b/src-tauri/core/src/cmd_draw.rs @@ -36,7 +36,7 @@ fn angle(c: V, p: V) -> f64 { } /// Neue 2D-Zeichnung `{id, type, levelId, categoryCode, geom}` (Farbe/Strich erbt die Ebene). -fn drawing(id: String, ctx: &Ctx, geom: Value) -> Value { +pub(crate) fn drawing(id: String, ctx: &Ctx, geom: Value) -> Value { obj(vec![("id", s(&id)), ("type", s("drawing2d")), ("levelId", s(ctx.level)), ("categoryCode", s(ctx.cat)), ("geom", geom)]) } diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index a2bce28f..5f3b2d01 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -33,6 +33,7 @@ pub mod wall_arc; pub mod grid; pub mod room_area; pub mod room_boundary; +pub mod magic_wand; pub mod polygon_holes; pub mod js_fmt; pub use dossier_hatch::jsmath; diff --git a/src-tauri/core/src/magic_wand.rs b/src-tauri/core/src/magic_wand.rs new file mode 100644 index 00000000..5eddcb6f --- /dev/null +++ b/src-tauri/core/src/magic_wand.rs @@ -0,0 +1,123 @@ +//! Zauberstab ([77]): Klick in eine von Linien umschlossene Fläche → ihr Umriss. Grundlage sind dieselben +//! Strecken wie beim Fang (`snap_model`: 2D-Zeichnungen und Modell-Kanten des Geschosses, Kreise/Bögen als +//! Sehnenzüge), daraus der planare Graph und die kleinste Masche um den Punkt (`kernel2d`, +//! `room_from_point_inside_faces`, wie die Raumerkennung aus Wandflächen). + +use crate::model::Project; +use crate::snap_model::Circle; +use kernel2d::{Vec2, WallFace}; +use std::collections::HashSet; + +/// Lücken bis zu dieser Weite (m) gelten als geschlossen. +const GAP_TOL: f64 = 1e-3; +/// Schutz vor quadratischem Aufwand (Kataster mit zehntausenden Linien). +const MAX_SEGMENTS: usize = 20_000; +/// Sehnen je Vollkreis. +const CIRCLE_STEPS: usize = 64; + +fn arc_segments(c: &Circle, out: &mut Vec<[f64; 4]>) { + let (a0, a1) = c.arc.unwrap_or((0.0, std::f64::consts::TAU)); + let mut span = a1 - a0; + while span <= 0.0 { + span += std::f64::consts::TAU; + } + let n = ((span / std::f64::consts::TAU) * CIRCLE_STEPS as f64).ceil().max(2.0) as usize; + let pt = |t: f64| (c.cx + c.r * crate::jsnum::cos(t), c.cy + c.r * crate::jsnum::sin(t)); + let mut prev = pt(a0); + for i in 1..=n { + let q = pt(a0 + span * i as f64 / n as f64); + out.push([prev.0, prev.1, q.0, q.1]); + prev = q; + } +} + +/// Umriss (gegen den Uhrzeigersinn) der kleinsten geschlossenen Fläche um `at` auf dem Geschoss `level`; +/// `None`, wenn der Punkt in keiner geschlossenen Masche liegt. +pub fn region_at(p: &Project, level: &str, at: (f64, f64)) -> Option> { + if !(at.0.is_finite() && at.1.is_finite()) { + return None; + } + // Alle Kategorien (auch ausgeblendete Ebenen zählen als Begrenzung, wie beim Schraffieren in CAD). + let mut codes: HashSet = p.drawings2d.iter().map(|d| d.category_code.clone()).collect(); + codes.extend(p.walls.iter().map(|w| w.category_code.clone())); + let skip = HashSet::new(); + let mut segs: Vec<[f64; 4]> = Vec::new(); + for part in [crate::snap_model::collect_drawings(p, level, &codes, &skip), crate::snap_model::collect_model(p, level, &codes, &skip)] { + segs.extend(part.segs.segs.iter().copied()); + for c in &part.circles { + arc_segments(c, &mut segs); + } + } + segs.retain(|s| s.iter().all(|v| v.is_finite()) && (s[0] - s[2]).abs() + (s[1] - s[3]).abs() > 1e-9); + if segs.len() < 3 || segs.len() > MAX_SEGMENTS { + return None; + } + let faces: Vec = segs.iter().map(|s| WallFace { a: Vec2::new(s[0], s[1]), b: Vec2::new(s[2], s[3]) }).collect(); + let ring = kernel2d::room_from_point_inside_faces(Vec2::new(at.0, at.1), &faces, GAP_TOL)?; + (ring.len() >= 3).then(|| ring.iter().map(|q| (q.x, q.y)).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn project(drawings: serde_json::Value) -> Project { + serde_json::from_value(serde_json::json!({ + "id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], + "openings": [], "walls": [], "drawingLevels": [{"id": "L", "name": "L", "kind": "floor", "visible": true, "locked": false}], + "drawings2d": drawings + })) + .unwrap() + } + + fn line(id: &str, a: (f64, f64), b: (f64, f64)) -> serde_json::Value { + serde_json::json!({"id": id, "levelId": "L", "categoryCode": "20", "geom": {"shape": "line", "a": {"x": a.0, "y": a.1}, "b": {"x": b.0, "y": b.1}}}) + } + + fn area(r: &[(f64, f64)]) -> f64 { + r.iter().enumerate().map(|(i, a)| { let c = r[(i + 1) % r.len()]; a.0 * c.1 - c.0 * a.1 }).sum::() / 2.0 + } + + /// Vier Linien, die sich über die Ecken hinaus kreuzen, und eine Teilungslinie: der Klick findet die + /// richtige Hälfte; ausserhalb nichts. + #[test] + fn masche_um_den_punkt() { + let p = project(serde_json::json!([ + line("a", (-1.0, 0.0), (5.0, 0.0)), line("b", (4.0, -1.0), (4.0, 4.0)), line("c", (5.0, 3.0), (-1.0, 3.0)), + line("d", (0.0, 4.0), (0.0, -1.0)), line("e", (2.0, 0.0), (2.0, 3.0)) + ])); + let r = region_at(&p, "L", (1.0, 1.0)).unwrap(); + assert!((area(&r) - 6.0).abs() < 1e-9, "{r:?}"); + let r = region_at(&p, "L", (3.0, 2.0)).unwrap(); + assert!((area(&r) - 6.0).abs() < 1e-9); + assert!(region_at(&p, "L", (10.0, 10.0)).is_none()); + assert!(region_at(&p, "L", (f64::NAN, 0.0)).is_none()); + } + + /// Befehl `wand`: geschlossene Polylinie mit Schraffur um die Masche; ausserhalb keine Ops. + #[test] + fn befehl_erzeugt_schraffur() { + let p = project(serde_json::json!([ + line("a", (0.0, 0.0), (2.0, 0.0)), line("b", (2.0, 0.0), (2.0, 2.0)), line("c", (2.0, 2.0), (0.0, 2.0)), line("d", (0.0, 2.0), (0.0, 0.0)) + ])); + let root = serde_json::to_value(&p).unwrap(); + let root = root.as_object().unwrap(); + let v = serde_json::json!({"cmd": "wand", "at": {"x": 1, "y": 1}, "hatchId": "h1", "stamp": "s", "ctx": {"level": "L", "cat": "20"}}); + let ops = crate::cmd_create::ops(root, &p, &v).unwrap(); + let item = &ops[0].to_json()["items"][0]; + assert_eq!(item["geom"]["shape"], "polyline"); + assert_eq!(item["geom"]["closed"], true); + assert_eq!(item["hatchId"], "h1"); + assert_eq!(item["geom"]["pts"].as_array().unwrap().len(), 4); + let out = serde_json::json!({"cmd": "wand", "at": {"x": 9, "y": 9}, "stamp": "s", "ctx": {"level": "L", "cat": "20"}}); + assert!(crate::cmd_create::ops(root, &p, &out).unwrap().is_empty()); + } + + /// Kreis als Begrenzung (Sehnenzug). + #[test] + fn kreis_als_rand() { + let p = project(serde_json::json!([{"id": "k", "levelId": "L", "categoryCode": "20", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}}])); + let r = region_at(&p, "L", (0.1, 0.1)).unwrap(); + assert!((area(&r) - std::f64::consts::PI).abs() < 0.01, "{}", area(&r)); + } +} diff --git a/src/commands/cmds/wand.test.ts b/src/commands/cmds/wand.test.ts new file mode 100644 index 00000000..8ccd6405 --- /dev/null +++ b/src/commands/cmds/wand.test.ts @@ -0,0 +1,43 @@ +/** `wandCommand` ([77]): Klick in ein Rechteck aus vier Linien → geschlossene Polylinie mit Schraffur; daneben nichts. */ +import { describe, expect, it } from "vitest"; +import { wandCommand } from "./wand"; +import type { CommandContext, Project } from "../types"; +import type { Drawing2D } from "../../model/types"; + +const line = (id: string, a: [number, number], b: [number, number]): Drawing2D => + ({ id, levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: a[0], y: a[1] }, b: { x: b[0], y: b[1] } } }) as Drawing2D; + +function project(): Project { + return { + id: "t", name: "T", lineStyles: [], components: [], wallTypes: [], + hatches: [{ id: "h1", name: "Beton", pattern: "diagonal", spacing: 0.1, angle: 45 } as unknown as Project["hatches"][number]], + drawingLevels: [{ id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], openings: [], ceilings: [], stairs: [], rooms: [], context: [], + drawings2d: [line("a", [0, 0], [3, 0]), line("b", [3, 0], [3, 2]), line("c", [3, 2], [0, 2]), line("d", [0, 2], [0, 0])], + }; +} + +const ctxOf = (p: Project): CommandContext => + ({ project: p, level: p.drawingLevels[0], defaultCategoryCode: "20", activeLineStyleId: "solid", activeWallTypeId: "aw", lastPoint: null, selection: { wallIds: [], drawingId: null } }) as CommandContext; + +describe("wandCommand", () => { + it("Klick in die Fläche: geschlossene Polylinie mit der ersten Schraffur", () => { + const p = project(); + const ctx = ctxOf(p); + const [, r] = wandCommand.onInput(wandCommand.init(), { kind: "point", point: { x: 1, y: 1 } }, ctx); + expect(r.commit).toBeDefined(); + const next = r.commit!(p); + const d = next.drawings2d[next.drawings2d.length - 1]; + expect(d.geom.shape).toBe("polyline"); + expect(d.hatchId).toBe("h1"); + if (d.geom.shape === "polyline") expect(d.geom.closed).toBe(true); + }); + + it("Klick ausserhalb: kein Commit, Befehl bleibt aktiv", () => { + const p = project(); + const [, r] = wandCommand.onInput(wandCommand.init(), { kind: "point", point: { x: 9, y: 9 } }, ctxOf(p)); + expect(r.commit).toBeUndefined(); + expect(r.done).toBeFalsy(); + }); +}); diff --git a/src/commands/cmds/wand.ts b/src/commands/cmds/wand.ts new file mode 100644 index 00000000..e2ed750f --- /dev/null +++ b/src/commands/cmds/wand.ts @@ -0,0 +1,34 @@ +// Zauberstab ([77]): EIN Klick in eine von Linien umschlossene Fläche (2D-Zeichnungen und Modellkanten des +// Geschosses) → geschlossene Polylinie mit Schraffur. Die Masche sucht der Kern (`magic_wand.rs`); die Vorschau +// zeigt sie schon beim Überfahren. Schraffur: die erste Schraffur des Projekts (ohne Schraffuren nur der Umriss). + +import type { Command, CommandContext, CommandResult, CommandState, Vec2 } from "../types"; +import { createMutation, createPreview } from "../createCore"; + +const idle = (): [CommandState, CommandResult] => [{ phase: "point", lastPoint: null }, { draft: null, done: true }]; + +const hatchOf = (ctx: CommandContext): string | undefined => ctx.project.hatches[0]?.id; + +export const wandCommand: Command = { + name: "wand", + labelKey: "cmd.wand.label", + prompt: () => "cmd.wand.point", + accepts: () => ["point"], + options: () => [], + init: () => ({ phase: "point", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + if (input.kind !== "point") return [state, { draft: null }]; + const at: Vec2 = input.point; + // Kein Treffer: Befehl bleibt aktiv (nächster Klick), nichts wird angelegt. + if (!createPreview(ctx, { cmd: "wand" }, [at]).ok) return [state, { draft: null }]; + return [state, { draft: null, commit: createMutation(ctx, { cmd: "wand", at, hatchId: hatchOf(ctx) }) }]; + }, + + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { + const pv = createPreview(ctx, { cmd: "wand" }, [point]); + return [state, { draft: { preview: pv.ok ? pv.shapes : [], vertices: [point] } }]; + }, + onConfirm: () => idle(), + onCancel: () => idle(), +}; diff --git a/src/commands/registry.ts b/src/commands/registry.ts index e81a3681..f03d8c4f 100644 --- a/src/commands/registry.ts +++ b/src/commands/registry.ts @@ -35,6 +35,7 @@ import { detailrefCommand } from "./cmds/detailref"; import { scalebarCommand } from "./cmds/scalebar"; import { revcloudCommand } from "./cmds/revcloud"; import { pointmarkerCommand } from "./cmds/pointmarker"; +import { wandCommand } from "./cmds/wand"; import { wipeoutCommand } from "./cmds/wipeout"; import { textCommand } from "./cmds/text"; import { leaderCommand } from "./cmds/leader"; @@ -106,6 +107,7 @@ export const COMMANDS: Record = { scalebar: scalebarCommand, revcloud: revcloudCommand, pointmarker: pointmarkerCommand, + wand: wandCommand, wipeout: wipeoutCommand, text: textCommand, leader: leaderCommand, @@ -221,6 +223,8 @@ export const ALIASES: Record = { wolke: "revcloud", revisionswolke: "revcloud", pm: "pointmarker", + zs: "wand", + zauberstab: "wand", punkt: "pointmarker", knoten: "pointmarker", wo: "wipeout", diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 5616b7cb..4585ffb8 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1799,6 +1799,8 @@ export const de = { "cmd.revcloud.arcSize": "Beulengrösse", "cmd.pointmarker.label": "Punktmarker", "cmd.pointmarker.point": "Punkt:", + "cmd.wand.label": "Zauberstab", + "cmd.wand.point": "In eine umschlossene Fläche klicken:", "cmd.grid.label": "Achsraster", "cmd.grid.origin": "Ursprung des Achsrasters ( Radial ):", "cmd.grid.radial": "Radial", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index b0acaeac..e3fd4344 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1788,6 +1788,8 @@ export const en: Record = { "cmd.revcloud.arcSize": "Arc size", "cmd.pointmarker.label": "Point marker", "cmd.pointmarker.point": "Point:", + "cmd.wand.label": "Magic wand", + "cmd.wand.point": "Click inside an enclosed area:", "cmd.grid.label": "Structural grid", "cmd.grid.origin": "Grid origin ( Radial ):", "cmd.grid.radial": "Radial",