From 1ea0c980692f3d307153363a4a08d47d6a8784ca Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 23:17:51 +0000 Subject: [PATCH] =?UTF-8?q?[77]=20Zauberstab:=20Inseln=20als=20L=C3=B6cher?= =?UTF-8?q?=20der=20Fl=C3=A4che?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Geschlossene Formen ganz in der Masche, die ihren Rand nicht berühren, werden Löcher (neues optionales Polylinien-Feld holes; kernel2d::region_with_islands, nur äusserste Inseln). Plan: Füllung/Schraffur sparen die Löcher aus (Ring mit Brücken), Loch-Umrisse gezeichnet; Vorschau, Transformieren, Griff-Verschieben, Geo-Verschiebung nehmen holes mit. --- TODO.md | 11 +++- src-tauri/core/src/cmd_create.rs | 15 ++++- src-tauri/core/src/cmd_draw.rs | 2 +- src-tauri/core/src/cmd_transform.rs | 12 ++++ src-tauri/core/src/cmd_wall_edit.rs | 9 ++- src-tauri/core/src/geo_rebase.rs | 8 ++- src-tauri/core/src/geo_translate.rs | 8 ++- src-tauri/core/src/grips.rs | 4 ++ src-tauri/core/src/magic_wand.rs | 66 +++++++++++++++++++--- src-tauri/core/src/model/manual.rs | 6 ++ src-tauri/core/src/plan/drawings.rs | 47 +++++++++++++-- src-tauri/kernel2d/src/lib.rs | 88 +++++++++++++++++++++++++++-- src/model/types.generated.ts | 6 ++ 13 files changed, 254 insertions(+), 28 deletions(-) diff --git a/TODO.md b/TODO.md index 26c3485d..bfaffb1a 100644 --- a/TODO.md +++ b/TODO.md @@ -1758,8 +1758,15 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). 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. Option S - wählt die Schraffur (alle der Reihe nach, dann „keine" = nur Umriss); Knopf in der Werkzeugleiste (2D). Offen: Inseln - (Löcher) in der Fläche; nicht in der App geklickt. + wählt die Schraffur (alle der Reihe nach, dann „keine" = nur Umriss); Knopf in der Werkzeugleiste (2D). + 4.11. Inseln: geschlossene Formen ganz in der Masche, die ihren Rand nicht berühren (eigene Graph-Komponente, + z. B. Stütze im Raum), werden Löcher — neues optionales Feld `holes` der Polylinie (nur geschlossen, gerade Ringe; + `kernel2d::region_with_islands`); nur äusserste Inseln (Insel im Loch einer Insel bleibt unberücksichtigt). + Plan: Füllung/Schraffur als Ring mit Brücken (`merge_holes`, wie Decken) → SVG/PDF/DXF/Render sparen aus, + Loch-Umrisse gezeichnet; Vorschau zeigt sie. Verschieben/Kopieren/Drehen/Spiegeln/Skalieren, Griff „ganz + verschieben", Geo-Verschiebung und Wand-Begrenzung nehmen `holes` mit. Offen: Fläche in der Objekt-Info (gibt + es für Polylinien nicht), Auflösen/Versetzen/Trennen/Booleans ignorieren `holes` (Loch geht verloren), Griffe an + Lochpunkten; 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 220c357f..8fb50015 100644 --- a/src-tauri/core/src/cmd_create.rs +++ b/src-tauri/core/src/cmd_create.rs @@ -493,8 +493,12 @@ 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 Some(r) = opt_p(v, "at").and_then(|at| crate::magic_wand::region_at(p, ctx.level, at)) else { return Vec::new() }; + let mut f = vec![("shape", s("polyline")), ("pts", pvs(&r.outer)), ("closed", Value::Bool(true))]; + if !r.holes.is_empty() { + f.push(("holes", Value::Array(r.holes.iter().map(|h| pvs(h)).collect()))); + } + let g = obj(f); 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)); @@ -1047,7 +1051,12 @@ pub fn preview_req(root: &Map, project: &Project, req: &Req, pts: "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), + Some(r) => { + out.poly(&r.outer); + for h in &r.holes { + out.poly(h); + } + } None => p.ok = false, }, "column" => { diff --git a/src-tauri/core/src/cmd_draw.rs b/src-tauri/core/src/cmd_draw.rs index 2089d1a9..9504f2f3 100644 --- a/src-tauri/core/src/cmd_draw.rs +++ b/src-tauri/core/src/cmd_draw.rs @@ -368,7 +368,7 @@ fn straight_edges(g: &Drawing2DGeom) -> Vec<(V, V)> { match g { Drawing2DGeom::Line { a, b } => vec![(v(a), v(b))], Drawing2DGeom::Rect { min, max } => polyline_edges(&corners_of(v(min), v(max)), true), - Drawing2DGeom::Polyline { pts, closed, bulge } => { + Drawing2DGeom::Polyline { pts, closed, bulge, .. } => { let pts: Vec = pts.iter().map(v).collect(); polyline_edges(&pts, *closed) .into_iter() diff --git a/src-tauri/core/src/cmd_transform.rs b/src-tauri/core/src/cmd_transform.rs index 5198ae6c..606fbfad 100644 --- a/src-tauri/core/src/cmd_transform.rs +++ b/src-tauri/core/src/cmd_transform.rs @@ -134,6 +134,8 @@ pub fn mv_geom(g: &Value, xf: &Xf) -> Option { "line" | "xline" | "ray" => with_all(g, vec![("a", p("a")), ("b", p("b"))]), "polyline" => { let pts = ps("pts"); + // Inseln ([77]) wandern mit. + let g = &if truthy(field(g, "holes")) { with(g, "holes", Value::Array(arr(field(g, "holes")).iter().map(|h| xf.pts(Some(h))).collect())) } else { g.clone() }; if !truthy(field(g, "bulge")) { return Some(with(g, "pts", pts)); } @@ -1097,6 +1099,16 @@ mod tests { assert!(mv_geom(&json!({"shape":"?"}), &xf).is_none()); } + /// [77] Inseln einer Polylinie wandern mit (Verschieben, Skalieren). + #[test] + fn inseln_wandern_mit() { + let g = json!({"shape":"polyline","closed":true,"pts":[{"x":0,"y":0},{"x":4,"y":0},{"x":4,"y":4}],"holes":[[{"x":1,"y":1},{"x":2,"y":1},{"x":2,"y":2}]]}); + let m = mv_geom(&g, &Xf::translate(1.0, 0.0)).unwrap(); + assert_eq!(m["holes"], json!([[{"x":2,"y":1},{"x":3,"y":1},{"x":3,"y":2}]])); + let s = scale_geom(&g, &Xf::of("scale", &[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)], 1.0), 2.0).unwrap(); + assert_eq!(s["holes"][0][2], json!({"x":4,"y":4}), "{s}"); + } + #[test] fn skalieren_zieht_groessen_nach() { let g = json!({"shape":"circle","center":{"x":1,"y":0},"r":1}); diff --git a/src-tauri/core/src/cmd_wall_edit.rs b/src-tauri/core/src/cmd_wall_edit.rs index cbb66f77..46e83f18 100644 --- a/src-tauri/core/src/cmd_wall_edit.rs +++ b/src-tauri/core/src/cmd_wall_edit.rs @@ -244,7 +244,14 @@ fn drawing_bounds(d: &Drawing2D, out: &mut Vec) { out.push(Bound::Seg(c[i], c[(i + 1) % 4])); } } - Drawing2DGeom::Polyline { pts, closed, bulge } => { + Drawing2DGeom::Polyline { pts, closed, bulge, holes } => { + // Inseln ([77]) begrenzen wie der Umriss. + for h in holes.iter().flatten() { + let h: Vec

= h.iter().map(p_of).collect(); + for i in 0..h.len() { + out.push(Bound::Seg(h[i], h[(i + 1) % h.len()])); + } + } let pts: Vec

= pts.iter().map(p_of).collect(); let n = pts.len(); let segs = if *closed && n > 2 { n } else { n.saturating_sub(1) }; diff --git a/src-tauri/core/src/geo_rebase.rs b/src-tauri/core/src/geo_rebase.rs index 8a97f684..073d96ae 100644 --- a/src-tauri/core/src/geo_rebase.rs +++ b/src-tauri/core/src/geo_rebase.rs @@ -24,7 +24,13 @@ fn shift_geom(g: &mut Drawing2DGeom, dx: f64, dy: f64) { *a = shift(*a, dx, dy); *b = shift(*b, dx, dy); } - Polyline { pts, .. } | Bezier { pts } | Spline { pts, .. } | Dimension { pts, .. } => shift_all(pts, dx, dy), + Polyline { pts, holes, .. } => { + shift_all(pts, dx, dy); + for h in holes.iter_mut().flatten() { + shift_all(h, dx, dy); + } + } + Bezier { pts } | Spline { pts, .. } | Dimension { pts, .. } => shift_all(pts, dx, dy), Rect { min, max } | Image { min, max, .. } => { *min = shift(*min, dx, dy); *max = shift(*max, dx, dy); diff --git a/src-tauri/core/src/geo_translate.rs b/src-tauri/core/src/geo_translate.rs index 68866d77..c6f47052 100644 --- a/src-tauri/core/src/geo_translate.rs +++ b/src-tauri/core/src/geo_translate.rs @@ -59,7 +59,13 @@ fn shift_geom(g: &Value, dx: f64, dy: f64) -> Value { let mut m = obj(g); match g.get("shape").and_then(Value::as_str).unwrap_or("") { "line" | "xline" | "ray" => shift_pts_fields(&mut m, &["a", "b"], dx, dy, &[]), - "polyline" | "bezier" | "spline" | "dimension" => shift_pts_fields(&mut m, &[], dx, dy, &["pts"]), + "polyline" | "bezier" | "spline" | "dimension" => { + shift_pts_fields(&mut m, &[], dx, dy, &["pts"]); + // Inseln ([77]). + if let Some(Value::Array(hs)) = g.get("holes") { + m.insert("holes".into(), Value::Array(hs.iter().map(|h| shift_all(Some(h), dx, dy)).collect())); + } + } "rect" | "image" => shift_pts_fields(&mut m, &["min", "max"], dx, dy, &[]), "circle" | "arc" | "ellipse" => shift_pts_fields(&mut m, &["center"], dx, dy, &[]), "kote" | "detailref" | "scalebar" | "pointmarker" | "block" => shift_pts_fields(&mut m, &["at"], dx, dy, &[]), diff --git a/src-tauri/core/src/grips.rs b/src-tauri/core/src/grips.rs index e2b11ac6..c177f32b 100644 --- a/src-tauri/core/src/grips.rs +++ b/src-tauri/core/src/grips.rs @@ -649,6 +649,10 @@ fn drawing_moved(d: &Value, dx: f64, dy: f64) -> Option { 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" if truthy(field(g, "holes")) => { + let holes = Value::Array(arr(field(g, "holes")).iter().map(|h| moved_all(arr(Some(h)), dx, dy)).collect()); + with_all(g, vec![("pts", moved_all(arr(field(g, "pts")), dx, dy)), ("holes", holes)]) + } "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), diff --git a/src-tauri/core/src/magic_wand.rs b/src-tauri/core/src/magic_wand.rs index 5eddcb6f..df246e2b 100644 --- a/src-tauri/core/src/magic_wand.rs +++ b/src-tauri/core/src/magic_wand.rs @@ -2,6 +2,11 @@ //! 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). +//! +//! Inseln: geschlossene Formen ganz in der Masche, die ihren Rand nicht berühren (eigene Zusammenhangs- +//! komponente des Graphen, z. B. Stütze im Raum), werden Löcher (wie Schraffur-Inseln in CAD). Nur die +//! äussersten: eine Insel im Loch einer Insel bleibt unberücksichtigt. Eine Form, die den Rand berührt, +//! gehört zum Graphen der Masche und formt deren Umriss selbst. use crate::model::Project; use crate::snap_model::Circle; @@ -31,9 +36,16 @@ fn arc_segments(c: &Circle, out: &mut Vec<[f64; 4]>) { } } -/// Umriss (gegen den Uhrzeigersinn) der kleinsten geschlossenen Fläche um `at` auf dem Geschoss `level`; +/// Gefundene Fläche: Umriss (gegen den Uhrzeigersinn) und Inseln (im Uhrzeigersinn). +#[derive(Debug, Clone, PartialEq)] +pub struct Region { + pub outer: Vec<(f64, f64)>, + pub holes: Vec>, +} + +/// Kleinste geschlossene Fläche um `at` auf dem Geschoss `level` samt Inseln; /// `None`, wenn der Punkt in keiner geschlossenen Masche liegt. -pub fn region_at(p: &Project, level: &str, at: (f64, f64)) -> Option> { +pub fn region_at(p: &Project, level: &str, at: (f64, f64)) -> Option { if !(at.0.is_finite() && at.1.is_finite()) { return None; } @@ -53,8 +65,9 @@ pub fn region_at(p: &Project, level: &str, at: (f64, f64)) -> Option = 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()) + let (ring, holes) = kernel2d::region_with_islands(Vec2::new(at.0, at.1), &faces, GAP_TOL)?; + let pl = |r: &[Vec2]| r.iter().map(|q| (q.x, q.y)).collect::>(); + (ring.len() >= 3).then(|| Region { outer: pl(&ring), holes: holes.iter().filter(|h| h.len() >= 3).map(|h| pl(h)).collect() }) } #[cfg(test)] @@ -86,9 +99,9 @@ mod tests { 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(); + let r = region_at(&p, "L", (1.0, 1.0)).unwrap().outer; assert!((area(&r) - 6.0).abs() < 1e-9, "{r:?}"); - let r = region_at(&p, "L", (3.0, 2.0)).unwrap(); + let r = region_at(&p, "L", (3.0, 2.0)).unwrap().outer; 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()); @@ -113,11 +126,50 @@ mod tests { assert!(crate::cmd_create::ops(root, &p, &out).unwrap().is_empty()); } + fn rect(id: &str, a: (f64, f64), b: (f64, f64)) -> Vec { + let c = [a, (b.0, a.1), b, (a.0, b.1)]; + (0..4).map(|i| line(&format!("{id}{i}"), c[i], c[(i + 1) % 4])).collect() + } + + /// [77] Inseln: Raum aus Linien mit quadratischer Stütze und runder Stütze darin → Umriss + 2 Löcher; + /// ein Quadrat in der Stütze (Insel in der Insel) zählt nicht; ein Quadrat am Rand formt den Umriss. + #[test] + fn inseln_werden_loecher() { + let mut d = rect("r", (0.0, 0.0), (10.0, 6.0)); + d.extend(rect("s", (2.0, 2.0), (3.0, 3.0))); + d.extend(rect("t", (2.3, 2.3), (2.7, 2.7))); + d.push(serde_json::json!({"id": "k", "levelId": "L", "categoryCode": "20", "geom": {"shape": "circle", "center": {"x": 6, "y": 3}, "r": 0.5}})); + // Am Rand: Nische (berührt die rechte Kante). + d.extend(rect("n", (9.0, 4.0), (10.0, 5.0))); + let p = project(serde_json::Value::Array(d)); + let r = region_at(&p, "L", (1.0, 1.0)).unwrap(); + assert_eq!(r.holes.len(), 2, "{:?}", r.holes); + // Umriss ohne Nische: 60 - 1; Löcher im Uhrzeigersinn. + assert!((area(&r.outer) - 59.0).abs() < 1e-9, "{}", area(&r.outer)); + let ha: f64 = r.holes.iter().map(|h| area(h)).sum(); + assert!((ha + 1.0 + std::f64::consts::PI * 0.25).abs() < 0.01, "{ha}"); + // Klick in die Stütze: deren Ring mit dem inneren Quadrat als Loch. + let s = region_at(&p, "L", (2.1, 2.1)).unwrap(); + assert!((area(&s.outer) - 1.0).abs() < 1e-9); + assert_eq!(s.holes.len(), 1); + // Befehl schreibt `holes`. + let root = serde_json::to_value(&p).unwrap(); + let v = serde_json::json!({"cmd": "wand", "at": {"x": 1, "y": 1}, "stamp": "s", "ctx": {"level": "L", "cat": "20"}}); + let ops = crate::cmd_create::ops(root.as_object().unwrap(), &p, &v).unwrap(); + let item = &ops[0].to_json()["items"][0]; + assert_eq!(item["geom"]["holes"].as_array().unwrap().len(), 2); + // Ohne Inseln kein Feld. + let q = project(serde_json::Value::Array(rect("r", (0.0, 0.0), (2.0, 2.0)))); + let root = serde_json::to_value(&q).unwrap(); + let ops = crate::cmd_create::ops(root.as_object().unwrap(), &q, &v).unwrap(); + assert!(ops[0].to_json()["items"][0]["geom"].get("holes").is_none()); + } + /// 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(); + let r = region_at(&p, "L", (0.1, 0.1)).unwrap().outer; assert!((area(&r) - std::f64::consts::PI).abs() < 0.01, "{}", area(&r)); } } diff --git a/src-tauri/core/src/model/manual.rs b/src-tauri/core/src/model/manual.rs index 01badbba..71f9df3b 100644 --- a/src-tauri/core/src/model/manual.rs +++ b/src-tauri/core/src/model/manual.rs @@ -276,6 +276,12 @@ pub enum Drawing2DGeom { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] bulge: Option>, + /// Inseln/Löcher ([77], Zauberstab): nur bei `closed`, je ein gerader Ring (ohne Bögen). + /// Füllung und Schraffur sparen sie aus, ihre Umrisse werden mitgezeichnet; fehlt das Feld, + /// verhält sich die Polylinie exakt wie bisher. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + holes: Option>>, }, #[serde(rename = "rect")] Rect { min: Vec2, max: Vec2 }, diff --git a/src-tauri/core/src/plan/drawings.rs b/src-tauri/core/src/plan/drawings.rs index d7586266..1e82c9f3 100644 --- a/src-tauri/core/src/plan/drawings.rs +++ b/src-tauri/core/src/plan/drawings.rs @@ -309,7 +309,9 @@ pub fn compact_eligible(d: &Drawing2D) -> bool { let marks = d.end_marks.as_ref().is_some_and(|m| m.start.is_some() || m.end.is_some()); match &d.geom { Drawing2DGeom::Line { .. } => !marks, - Drawing2DGeom::Polyline { bulge, .. } => !marks && bulge.as_ref().is_none_or(|b| b.iter().all(|v| *v == 0.0 || v.is_nan())), + Drawing2DGeom::Polyline { bulge, holes, .. } => { + !marks && holes.as_ref().is_none_or(Vec::is_empty) && bulge.as_ref().is_none_or(|b| b.iter().all(|v| *v == 0.0 || v.is_nan())) + } _ => false, } } @@ -651,13 +653,28 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed em.line(from, v(b.x + ux * XLINE_EXTEND_M, b.y + uy * XLINE_EXTEND_M), w, Some(&XLINE_DASH), DASH_REF_XLINE); } } - Drawing2DGeom::Polyline { pts, closed, bulge } => { + Drawing2DGeom::Polyline { pts, closed, bulge, holes } => { let n = pts.len(); let bl = bulge.as_deref(); let closed_ring = *closed && n > 2; + // Inseln ([77]): gültige Ringe (≥ 3 Punkte), nur bei geschlossener Kontur. + let holes: Vec<&Vec> = if closed_ring { holes.iter().flatten().filter(|h| h.len() >= 3).collect() } else { Vec::new() }; if closed_ring { let ring = bulge_polyline_points(pts, bl, true); - fill_poly(&mut em, ring)?; + if holes.is_empty() { + fill_poly(&mut em, ring)?; + } else { + // Ein Ring mit Brücken zu den Löchern (wie Decken): Füllung/Schraffur sparen sie aus. + let outer: Vec<[f64; 2]> = ring.iter().map(|q| [q.x, q.y]).collect(); + let hs: Vec> = holes.iter().map(|h| h.iter().map(|q| [q.x, q.y]).collect()).collect(); + let merged = crate::polygon_holes::merge_holes(&outer, &hs, 1e-4); + fill_poly(&mut em, merged.ring.iter().map(|q| v(q[0], q[1])).collect())?; + } + } + for h in &holes { + for i in 0..h.len() { + em.seg(h[i], h[(i + 1) % h.len()]); + } } let bulge_at = |i: usize| bl.and_then(|b| b.get(i)).copied(); let open = !closed_ring; @@ -1160,10 +1177,11 @@ pub fn mv_geom(g: &Drawing2DGeom, f: &dyn Fn(Vec2) -> Vec2) -> Drawing2DGeom { G::Line { a, b } => G::Line { a: f(*a), b: f(*b) }, G::Xline { a, b } => G::Xline { a: f(*a), b: f(*b) }, G::Ray { a, b } => G::Ray { a: f(*a), b: f(*b) }, - G::Polyline { pts, closed, bulge } => { + G::Polyline { pts, closed, bulge, holes } => { let pts = map(pts); let bulge = bulge.as_ref().map(|b| if reverses_orientation(f) { b.iter().map(|x| -x).collect() } else { b.clone() }); - G::Polyline { pts, closed: *closed, bulge } + let holes = holes.as_ref().map(|hs| hs.iter().map(map).collect()); + G::Polyline { pts, closed: *closed, bulge, holes } } G::Rect { min, max } => { let c = [*min, v(max.x, min.y), *max, v(min.x, max.y)].map(f); @@ -1172,7 +1190,7 @@ pub fn mv_geom(g: &Drawing2DGeom, f: &dyn Fn(Vec2) -> Vec2) -> Drawing2DGeom { let fold = |k: fn(f64, f64) -> f64, s: fn(&Vec2) -> f64| c.iter().map(s).reduce(k).unwrap_or(f64::NAN); G::Rect { min: v(fold(jsnum::min, |q| q.x), fold(jsnum::min, |q| q.y)), max: v(fold(jsnum::max, |q| q.x), fold(jsnum::max, |q| q.y)) } } else { - G::Polyline { pts: c.to_vec(), closed: true, bulge: None } + G::Polyline { pts: c.to_vec(), closed: true, bulge: None, holes: None } } } G::Circle { center, r } => G::Circle { center: f(*center), r: *r }, @@ -1891,6 +1909,23 @@ mod tests { assert_eq!(texts, vec!["-2.80".to_string(), "±0.00 = 512.40".into(), "+3.00".into()]); } + /// [77] Polylinie mit Insel: die Fläche (Füllung/Schraffur) spart das Loch aus, sein Umriss wird gezeichnet. + #[test] + fn insel_wird_ausgespart() { + let p = project(serde_json::json!({})); + let mut d = drawing(serde_json::json!({"shape": "polyline", "closed": true, + "pts": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}, {"x": 0, "y": 4}], + "holes": [[{"x": 1, "y": 1}, {"x": 1, "y": 2}, {"x": 2, "y": 2}, {"x": 2, "y": 1}]]})); + d["fillColor"] = "#ff0000".into(); + let out = render(&p, d.clone(), 100.0); + let Primitive::Polygon { pts, .. } = &out[0] else { panic!("{:?}", out[0]) }; + let k: Vec = pts.iter().map(|q| kernel2d::Vec2::new(q.x, q.y)).collect(); + assert!(!kernel2d::rb_point_in_polygon(kernel2d::Vec2::new(1.5, 1.5), &k), "{pts:?}"); + assert!(kernel2d::rb_point_in_polygon(kernel2d::Vec2::new(3.0, 3.0), &k)); + assert_eq!(out.len(), 1 + 4 + 4); + assert!(!compact_eligible(&serde_json::from_value(d).unwrap())); + } + #[test] fn kompakt_nur_ohne_enden_und_boegen() { let mk = |g: serde_json::Value| -> Drawing2D { serde_json::from_value(drawing(g)).unwrap() }; diff --git a/src-tauri/kernel2d/src/lib.rs b/src-tauri/kernel2d/src/lib.rs index f5e1d4ce..eaec3d56 100644 --- a/src-tauri/kernel2d/src/lib.rs +++ b/src-tauri/kernel2d/src/lib.rs @@ -1931,6 +1931,15 @@ struct RbHalfEdge { /// Extrahiert die minimalen geschlossenen Maschen (Port von `extractFaces`). fn extract_faces(nodes: &[RbNode], edges: &[RbUEdge]) -> Vec> { + // Aussenmaschen verwerfen: nur CCW (positive Flaeche) behalten. + extract_all_faces(nodes, edges).into_iter().filter(|f| { + let poly: Vec = f.iter().map(|&n| nodes[n].p).collect(); + signed_area(&poly) > RB_EPS + }).collect() +} + +/// Alle Maschen-Umläufe: innere CCW, die Aussenränder je Zusammenhangskomponente CW. +fn extract_all_faces(nodes: &[RbNode], edges: &[RbUEdge]) -> Vec> { let mut half_edges: Vec = Vec::new(); let mut outgoing: Vec> = (0..nodes.len()).map(|_| Vec::new()).collect(); @@ -1992,12 +2001,7 @@ fn extract_faces(nodes: &[RbNode], edges: &[RbUEdge]) -> Vec> { faces.push(face_nodes); } } - - // Aussenmaschen verwerfen: nur CCW (positive Flaeche) behalten. - faces.into_iter().filter(|f| { - let poly: Vec = f.iter().map(|&n| nodes[n].p).collect(); - signed_area(&poly) > RB_EPS - }).collect() + faces } // ── Innen-Offset ────────────────────────────────────────────────────────────── @@ -2249,6 +2253,78 @@ pub fn room_from_point_inside_faces( best } +/// Zauberstab ([77]): kleinste Masche um `point` wie [`room_from_point_inside_faces`] (CCW), dazu ihre +/// Inseln (CW): Aussenränder der Zusammenhangskomponenten des Graphen, die die Masche nicht berühren und +/// ganz in ihr liegen. Nur die äussersten Inseln (eine Insel in einer Insel ist kein Loch des Lochs). +pub fn region_with_islands(point: Vec2, wall_faces: &[WallFace], gap_tol: f64) -> Option<(Vec, Vec>)> { + if wall_faces.len() < 3 { + return None; + } + let segs: Vec<(Vec2, Vec2)> = wall_faces.iter().map(|f| (f.a, f.b)).collect(); + let (nodes, edges) = build_planar_graph(&segs, gap_tol); + if edges.len() < 3 { + return None; + } + // Zusammenhangskomponenten (Union-Find über die Kanten). + let mut parent: Vec = (0..nodes.len()).collect(); + fn root(p: &mut [usize], mut i: usize) -> usize { + while p[i] != i { + p[i] = p[p[i]]; + i = p[i]; + } + i + } + for e in &edges { + let (a, b) = (root(&mut parent, e.u), root(&mut parent, e.v)); + parent[a] = b; + } + let faces = extract_all_faces(&nodes, &edges); + let ring_of = |f: &[usize]| dedupe_ring_rb(&f.iter().map(|&n| nodes[n].p).collect::>()); + + let mut best: Option<(Vec, usize)> = None; + let mut best_area = f64::INFINITY; + // Aussenrand je Komponente: der CW-Umlauf mit der grössten Fläche. + let mut outer: std::collections::HashMap)> = std::collections::HashMap::new(); + for f in &faces { + let poly = ring_of(f); + if poly.len() < 3 { + continue; + } + let comp = root(&mut parent, f[0]); + let sa = signed_area(&poly); + if sa > RB_EPS { + if rb_point_in_polygon(point, &poly) { + let area = polygon_area(&poly); + if area < best_area { + best_area = area; + best = Some((poly, comp)); + } + } + } else if sa < -RB_EPS && outer.get(&comp).is_none_or(|(a, _)| -sa > *a) { + outer.insert(comp, (-sa, poly)); + } + } + let (ring, comp) = best?; + let mut cands: Vec> = outer + .into_iter() + .filter(|(c, (_, r))| *c != comp && rb_point_in_polygon(r[0], &ring) && !rb_point_in_polygon(point, r)) + .map(|(_, (_, r))| r) + .collect(); + // Stabile Reihenfolge (HashMap): nach erstem Punkt. + cands.sort_by(|a, b| (a[0].x, a[0].y).partial_cmp(&(b[0].x, b[0].y)).unwrap_or(std::cmp::Ordering::Equal)); + let holes: Vec> = cands + .iter() + .enumerate() + .filter(|(i, r)| !cands.iter().enumerate().any(|(j, o)| j != *i && rb_point_in_polygon(r[0], o))) + .map(|(_, r)| r.clone()) + .collect(); + let mut out = ring; + if signed_area(&out) < 0.0 { + out.reverse(); + } + Some((out, holes)) +} + // --- Oeffnungs-Geometrie (Port von src/geometry/opening.ts, Slice 4) -------- // `Wall`/`Opening`/`Project`-Kopplung durch Vec2/number-Parameter ersetzt // (PORT_PLAN §1 "Teilweise im Scope"): `thickness`/`refOffset` werden hier als diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index 9ff96c13..277afd23 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -839,6 +839,12 @@ export type Drawing2DGeom = * Bogen (kein eigenes SVG-Arc-Primitiv, analog Ellipse/Spline/Bezier). */ bulge?: Array; + /** + * Inseln/Löcher ([77], Zauberstab): nur bei `closed`, je ein gerader Ring (ohne Bögen). + * Füllung und Schraffur sparen sie aus, ihre Umrisse werden mitgezeichnet; fehlt das Feld, + * verhält sich die Polylinie exakt wie bisher. + */ + holes?: Array>; } | { shape: "rect"; min: Vec2; max: Vec2 } | { shape: "circle"; center: Vec2; r: number }