[26] Ecke einfügen/löschen an Umrissen: Dach (Umriss + Höfe), Decke, Raum, Baugrube, geschlossene Polylinie; Einfüge-Raute, Kontextmenü, Aufräumen

This commit is contained in:
Claude committed 2026-11-11 06:26:43 +00:00
1 parent abdd251fc9
commit 52e2b4efe0
15 files changed
+628 -15

No files matched your search

+6 -1
View File
@@ -233,7 +233,12 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `*
- ◐ **[26]** Dächer über beliebige Grundrisse (`core/src/roof*.rs`). Grundriss-Griffe (11.11.): am einzeln gewählten Dach
Eck-Griffe und Kanten-Anfasser an Umriss UND Höfen (Kern-Ops `roofVertex`/`roofEdge`, flacher Index Umriss→Höfe,
Umriss bleibt frei, Vorschau + ein Undo-Schritt je Zug), Kante unter dem Anfasser wird hervorgehoben (`plan-edge-hover`,
auch bei Decke/Raum/Baugrube). Offen: Eck einfügen/löschen (Mittel-Raute) am Dach, Kanten-Neigung/Giebel per Kontextmenü am
auch bei Decke/Raum/Baugrube). Ecke einfügen/löschen (11.11.), einheitlich für Dach (Umriss + Höfe), Decke, Raum, Baugrube und
geschlossene Polylinie: Kern-Ops `ringInsert`/`ringDelete`/`ringTidy` (`grips.rs`, `ring_edit`; Polylinie nutzt `insertPoint`/`deletePoint`,
Aufräumen nur an geraden Segmenten); Raute (`plan-grip-insert`) bei 25 % der Kante (die Mitte gehört dem Kanten-Anfasser), Ziehen fügt
die Ecke ein, auf der Geraden/auf dem Nachbarn entfällt sie (auch nach normalem Eck-Zug), Kontextmenü „Ecke löschen" (mind. 3 bleiben),
ein Undo-Schritt je Aktion; `edgePitchDeg` (Dach) bzw. `edgeSlopes`/`edgeShoring` (Baugrube) laufen mit (neue Kante erbt die geteilte).
Offen: Raute an Decken-`openings`; Kanten-Neigung/Giebel per Kontextmenü am
Griff (heute im Objekt-Info), Hover-Hervorhebung in der App nicht angesehen; Mansarde mit Hof und verschieden geneigten Kanten (zweite Schicht nicht geschlossen);
Schattenwurf nimmt die Hülle der Dachfläche. · M
- ◐ **[137]** Alles Sichtbare anwählbar. (10.11. bewusst nicht anwählbar, mit Begründung: Punktwolken sind kein
+8 -8
View File
@@ -54,7 +54,7 @@ async function clickModel(page: Page, dx: number, dy: number): Promise<void> {
/** Abstand (px) des nächsten gezeichneten Griffs zum Bildschirmort des Modellpunkts. */
async function gripOffset(page: Page, dx: number, dy: number): Promise<number> {
const want = await screenOf(page, dx, dy);
const boxes = await page.locator(".plan-grip").evaluateAll((els) =>
const boxes = await page.locator(".plan-grip:not(.plan-grip-insert)").evaluateAll((els) =>
els.map((e) => {
const r = e.getBoundingClientRect();
return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
@@ -127,7 +127,7 @@ test("Kataster-DXF in LV95: Parzelle anklicken, Eckgriff ziehen, Rückgängig",
await clickModel(page, 38, 53);
await expect(widthField(page)).toHaveValue("30.000");
// 4 Eckgriffe (gerade Kanten: keine Bogen-Mitten-Griffe).
await expect(page.locator(".plan-grip")).toHaveCount(4);
await expect(page.locator(".plan-grip:not(.plan-grip-insert)")).toHaveCount(4);
// Die Griffe liegen sichtbar auf den Ecken (früher: `<circle cx>` mit LV95-Koordinaten, vom
// Browser als CSS-Länge auf ±33.5 Mio. geklemmt → weit ausserhalb des Bildes).
await expectGripAt(page, 68, 68);
@@ -158,7 +158,7 @@ test("Kataster: Strassenparzelle mit Bögen bleibt Bogen-Polylinie und hat Griff
await clickModel(page, -6 + 3 * 8, -3);
await expect(widthField(page)).toHaveValue("80.000");
// 22 Ecken + 22 Bogen-Mitten (früher: über 100 zerlegte Punkte, ohne Bogen-Griffe).
await expect(page.locator(".plan-grip")).toHaveCount(44);
await expect(page.locator(".plan-grip:not(.plan-grip-insert)")).toHaveCount(44);
});
test("Kataster: einzeln gewähltes Element mit über 600 Stützpunkten bekommt Griffe", async ({ page }) => {
@@ -177,7 +177,7 @@ test("Kataster: einzeln gewähltes Element mit über 600 Stützpunkten bekommt G
await clickModel(page, 140 + 20, 30); // Stützpunkt k = 0 des Waldrands
await expect(widthField(page)).toHaveValue(/^4\d\.\d{3}$/);
const grips = page.locator(".plan-grip");
const grips = page.locator(".plan-grip:not(.plan-grip-insert)");
await expect.poll(() => grips.count()).toBeGreaterThan(50);
// Gezeichnet werden nur die sichtbaren, je Bildschirmzelle einer (gripCull.ts) — nie alle 1400.
expect(await grips.count()).toBeLessThanOrEqual(1400);
@@ -187,7 +187,7 @@ test("Kataster in LV95: Griffe auf den Ecken auch stark hineingezoomt, Lineal st
await startNewProject(page);
await importDxf(page, "kataster.dxf", await readFile(KATASTER_DXF, "utf8"));
await clickModel(page, 38, 53);
await expect(page.locator(".plan-grip")).toHaveCount(4);
await expect(page.locator(".plan-grip:not(.plan-grip-insert)")).toHaveCount(4);
await expectGripAt(page, 68, 68);
// Bisher (Overlay in absoluten viewBox-Einheiten, Browser rechnet f32): ~6 px bei 11 m,
@@ -222,16 +222,16 @@ test("Kataster: geschlossene Bogen-Polylinie hat keine Kanten-Griffe im Innern",
// Strassenparzelle: jedes Segment ein Bogen → Bogen-Mitten-Griffe, keine Kanten-Dreiecke
// (früher liefen die Kanten-Griffe auch über die Bogen-Mitten: Dreiecke quer durchs Innere).
await clickModel(page, -6 + 3 * 8, -3);
await expect(page.locator(".plan-grip")).toHaveCount(44);
await expect(page.locator(".plan-grip:not(.plan-grip-insert)")).toHaveCount(44);
await expect(page.locator(".plan-edge-grip")).toHaveCount(0);
// Parzelle mit geraden Kanten: genau 4 Kanten-Griffe, je auf der Kantenmitte.
await clickModel(page, 38, 53);
await expect(page.locator(".plan-grip")).toHaveCount(4);
await expect(page.locator(".plan-grip:not(.plan-grip-insert)")).toHaveCount(4);
await expect(page.locator(".plan-edge-grip")).toHaveCount(4);
// Parzelle 0..30 m mit zwei Bogen- und zwei geraden Seiten: 4 Ecken + 2 Bogen-Mitten,
// Kanten-Griffe nur an den geraden Seiten (rechts bei x = 30, links bei x = 0).
await clickModel(page, 30, 15);
await expect(page.locator(".plan-grip")).toHaveCount(6);
await expect(page.locator(".plan-grip:not(.plan-grip-insert)")).toHaveCount(6);
const edges = page.locator(".plan-edge-grip");
await expect(edges).toHaveCount(2);
const right = await screenOf(page, 30, 15);
+75
View File
@@ -0,0 +1,75 @@
// [26] Ecke einfügen/löschen am Umriss (Dach im Beispielprojekt): Einfüge-Raute ziehen → eine Ecke mehr, ein Undo-Schritt;
// Ecke zurück auf die Gerade ziehen → entfällt; Kontextmenü am Eck-Griff „Ecke löschen". Bildschirm-Punkte wie in roofGrips.spec.ts.
import type { Page } from "@playwright/test";
import { blurFocus, elementRows, expect, openSample, openTab, startNewProject, test } from "./app";
const CORNERS = ".plan-grip:not(.plan-grip-insert)";
const DIAMONDS = ".plan-grip-insert";
async function centres(page: Page, selector: string): Promise<{ x: number; y: number }[]> {
const c = await page.locator(selector).evaluateAll((els) =>
els.map((e) => {
const r = e.getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) };
}),
);
return c.sort((a, b) => a.x - b.x || a.y - b.y);
}
/** Griff ziehen: ein Griff bleibt nach dem Loslassen „bewaffnet" und folgt dem Zeiger, bis ein Klick ihn setzt. */
async function dragGrip(page: Page, from: { x: number; y: number }, to: { x: number; y: number }): Promise<void> {
await page.mouse.move(from.x, from.y);
await page.mouse.down();
await page.mouse.move(to.x, to.y, { steps: 6 });
await page.mouse.up();
await page.mouse.click(to.x, to.y);
}
async function selectRoof(page: Page): Promise<void> {
await startNewProject(page);
await openSample(page);
await openTab(page, "Elemente");
await elementRows(page).filter({ hasText: "RF1" }).first().click();
await expect(page.getByText("Dachform")).toBeVisible();
await expect.poll(() => page.locator(CORNERS).count()).toBe(4);
}
test("Dach: Einfüge-Raute ziehen fügt eine Ecke ein, Rückgängig, Zurückziehen entfernt sie ([26])", async ({ page }) => {
await selectRoof(page);
await expect(page.locator(DIAMONDS)).toHaveCount(4);
const corners = await centres(page, CORNERS);
const diamonds = await centres(page, DIAMONDS);
// Die Raute mit dem kleinsten y (Nordkante) senkrecht herausziehen: Ecke mehr, Umriss bleibt sonst gleich.
const top = [...diamonds].sort((a, b) => a.y - b.y)[0];
await dragGrip(page, top, { x: top.x, y: top.y - 40 });
await expect.poll(() => page.locator(CORNERS).count()).toBe(5);
await expect(page.locator(DIAMONDS)).toHaveCount(5);
// Ein Undo-Schritt nimmt Einfügen und Zug zusammen weg.
await blurFocus(page);
await page.keyboard.press("ControlOrMeta+z");
await expect.poll(() => page.locator(CORNERS).count()).toBe(4);
expect(await centres(page, CORNERS)).toEqual(corners);
// Wieder einfügen, dann die neue Ecke auf die Kante zurückziehen: sie entfällt.
await dragGrip(page, top, { x: top.x, y: top.y - 40 });
await expect.poll(() => page.locator(CORNERS).count()).toBe(5);
const added = (await centres(page, CORNERS)).find((g) => Math.abs(g.x - top.x) < 3 && g.y < top.y - 20)!;
await dragGrip(page, added, { x: top.x, y: top.y });
await expect.poll(() => page.locator(CORNERS).count()).toBe(4);
});
test("Dach: Kontextmenü am Eck-Griff löscht die Ecke, Rückgängig ([26])", async ({ page }) => {
await selectRoof(page);
const before = await centres(page, CORNERS);
await page.mouse.click(before[0].x, before[0].y, { button: "right" });
await page.getByRole("menuitem", { name: "Ecke löschen" }).click();
await expect.poll(() => page.locator(CORNERS).count()).toBe(3);
await blurFocus(page);
await page.keyboard.press("ControlOrMeta+z");
await expect.poll(() => page.locator(CORNERS).count()).toBe(4);
expect(await centres(page, CORNERS)).toEqual(before);
});
+2 -2
View File
@@ -4,7 +4,7 @@ import type { Page } from "@playwright/test";
import { blurFocus, elementRows, expect, openSample, openTab, startNewProject, test } from "./app";
async function gripCentres(page: Page): Promise<{ x: number; y: number }[]> {
const c = await page.locator(".plan-grip").evaluateAll((els) =>
const c = await page.locator(".plan-grip:not(.plan-grip-insert)").evaluateAll((els) =>
els.map((e) => {
const r = e.getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) };
@@ -29,7 +29,7 @@ test("Dach: Eckgriff im Grundriss ziehen, Rückgängig ([26])", async ({ page })
await elementRows(page).filter({ hasText: "RF1" }).first().click();
await expect(page.getByText("Dachform")).toBeVisible();
await expect.poll(() => page.locator(".plan-grip").count()).toBe(4);
await expect.poll(() => page.locator(".plan-grip:not(.plan-grip-insert)").count()).toBe(4);
// Kanten-Anfasser je Seite.
await expect(page.locator(".plan-edge-grip")).toHaveCount(4);
const before = await gripCentres(page);
+240
View File
@@ -339,6 +339,30 @@ pub fn run(lk: &Lookup, req: &Request) -> Result<GripResult, String> {
})
.into()
}
// [26] Ecke einfügen/löschen/aufräumen an Umriss-Ringen (Dach samt Höfen, Decke, Raum, Baugrube, geschlossene
// Polylinie), ein Kern für alle: `kind` = "roof" | "ceiling" | "room" | "excavation" | "polyline", `seg`/`index`
// wie bei den Eck-Griffen (Dach: flacher Index über Umriss + Höfe). Kanten-Eigenschaften laufen mit.
"ringInsert" | "ringDelete" | "ringTidy" => {
let (index, (x, y)) = (if op == "ringInsert" { r.n("seg") } else { r.n("index") }, r.p("pt"));
let edit = match op {
"ringInsert" => RingEdit::Insert(x, y),
"ringDelete" => RingEdit::Delete,
_ => {
let tol = r.n("tol");
RingEdit::Tidy(if tol.is_finite() { tol.clamp(BEND_TIDY_M, 1.0) } else { BEND_TIDY_M })
}
};
let coll = match r.s("kind") {
Some("roof") => "roofs",
Some("ceiling") => "ceilings",
Some("room") => "rooms",
Some("excavation") => "context",
Some("polyline") => "drawings2d",
_ => return Ok(GripResult::default()),
};
let kind = r.s("kind").unwrap_or("");
patch(coll, r.s("id"), &|e| ring_edit(e, kind, index, &edit)).into()
}
"stairBy" => {
let (dx, dy) = r.p("delta");
patch("stairs", r.s("id"), &|s| {
@@ -1211,6 +1235,153 @@ fn roof_ring_edit(r: &Value, a: f64, b: Option<f64>, f: &dyn Fn(&[Value], usize)
None
}
enum RingEdit {
/// Ecke hinter Ecke `i` einfügen (Mittel-Griff der Kante i → i+1).
Insert(f64, f64),
Delete,
/// Ecke `i` entfernen, wenn sie (fast) auf dem Nachbarpunkt oder der Geraden zwischen den Nachbarn liegt.
Tidy(f64),
}
/// Was mit den Kanten-Einträgen (Neigung, Böschung …) geschieht: Eintrag `i` verdoppeln bzw. streichen.
enum EdgeShift {
Dup(usize),
Drop(usize),
}
/// Neuer Ring nach `edit` an Ecke/Kante `i`; mindestens 3 Ecken bleiben.
fn ring_apply(ring: &[Value], i: usize, edit: &RingEdit) -> Option<(Vec<Value>, EdgeShift)> {
let n = ring.len();
let mut v = ring.to_vec();
match *edit {
RingEdit::Insert(x, y) => {
if !(x.is_finite() && y.is_finite()) {
return None;
}
v.insert(i + 1, pt(x, y));
Some((v, EdgeShift::Dup(i)))
}
RingEdit::Delete => {
if n <= 3 {
return None;
}
v.remove(i);
Some((v, EdgeShift::Drop(i)))
}
RingEdit::Tidy(tol) => {
if n <= 3 || !point_near_neighbors(ring, i, tol) {
return None;
}
v.remove(i);
Some((v, EdgeShift::Drop(i)))
}
}
}
/// Liegt Ecke `i` des Rings näher als `tol` an der Strecke zwischen ihren Nachbarn (Nachbarpunkt eingeschlossen)?
fn point_near_neighbors(ring: &[Value], i: usize, tol: f64) -> bool {
let n = ring.len();
let (a, b, c) = (xy(&ring[(i + n - 1) % n]), xy(&ring[i]), xy(&ring[(i + 1) % n]));
let (dx, dy) = (c.0 - a.0, c.1 - a.1);
let len2 = dx * dx + dy * dy;
let t = if len2 > 0.0 { ((b.0 - a.0) * dx + (b.1 - a.1) * dy) / len2 } else { 0.0 };
let (qx, qy) = (a.0 + t.clamp(0.0, 1.0) * dx, a.1 + t.clamp(0.0, 1.0) * dy);
(b.0 - qx).hypot(b.1 - qy) < tol
}
/// Kanten-Einträge `field` (ab Kante `off`) nachführen: die neue Kante erbt die geteilte, beim Löschen bleibt die
/// vorherige Kante (Nachbar → Nachbar). Fehlende Einträge (kürzere Liste) bleiben fehlend = Standard.
fn shift_edge_list(e: Value, field_name: &str, off: usize, shift: &EdgeShift) -> Value {
let Some(list) = field(&e, field_name).and_then(Value::as_array) else { return e };
let mut v = list.clone();
match *shift {
EdgeShift::Dup(i) => {
if v.len() > off + i {
let c = v[off + i].clone();
v.insert(off + i + 1, c);
}
}
EdgeShift::Drop(i) => {
if v.len() > off + i {
v.remove(off + i);
}
}
}
with(&e, field_name, Value::Array(v))
}
/// [26] Ecke einfügen/löschen/aufräumen an einem Umriss-Element (s. `ringInsert`).
fn ring_edit(e: &Value, kind: &str, flat: f64, edit: &RingEdit) -> Option<Value> {
if truthy(field(e, "locked")) {
return None;
}
let simple = |name: &str| -> Option<Value> {
let ring = field(e, name)?.as_array()?;
let (v, shift) = ring_apply(ring, index_in(flat, ring.len())?, edit)?;
let out = with(e, name, Value::Array(v));
Some(if kind == "excavation" {
shift_edge_list(shift_edge_list(out, "edgeSlopes", 0, &shift), "edgeShoring", 0, &shift)
} else {
out
})
};
match kind {
"ceiling" => simple("outline"),
"excavation" => simple("outline"),
"room" => simple("boundary"),
"polyline" => polyline_ring_edit(e, flat, edit),
"roof" => {
let outline = field(e, "outline")?.as_array()?;
let holes: Vec<&Vec<Value>> = arr(field(e, "holes")).iter().filter_map(|h| h.as_array()).collect();
let mut off = 0usize;
for ring_no in 0..=holes.len() {
let ring: &[Value] = if ring_no == 0 { outline } else { holes[ring_no - 1] };
if let Some(i) = index_in(flat - off as f64, ring.len()) {
let (v, shift) = ring_apply(ring, i, edit)?;
let out = if ring_no == 0 {
with(e, "outline", Value::Array(v))
} else {
let mut hs: Vec<Value> = arr(field(e, "holes")).to_vec();
hs[ring_no - 1] = Value::Array(v);
with(e, "holes", Value::Array(hs))
};
return Some(shift_edge_list(out, "edgePitchDeg", off, &shift));
}
off += ring.len();
}
None
}
_ => None,
}
}
/// Geschlossene Polylinie: nur Aufräumen (Einfügen/Löschen laufen über `insertPoint`/`deletePoint`, die Bögen
/// kennen). Ecke entfällt, wenn beide anliegenden Segmente gerade sind und sie auf der Nachbargeraden liegt.
fn polyline_ring_edit(d: &Value, index: f64, edit: &RingEdit) -> Option<Value> {
let RingEdit::Tidy(tol) = *edit else { return None };
let g = field(d, "geom")?;
if shape(g) != "polyline" || !truthy(field(g, "closed")) {
return None;
}
let pts = arr(field(g, "pts"));
let n = pts.len();
let k = index_in(index, n)?;
if n <= 3 || !point_near_neighbors(pts, k, tol) {
return None;
}
let bulge = arr(field(g, "bulge"));
let straight = |i: usize| num_or(bulge.get(i), 0.0).abs() < 1e-9;
if !(straight(k) && straight((k + n - 1) % n)) {
return None;
}
let drop = |l: &[Value]| Value::Array(l.iter().enumerate().filter(|(i, _)| *i != k).map(|(_, v)| v.clone()).collect());
let mut fields = vec![("pts", drop(pts))];
if truthy(field(g, "bulge")) {
fields.push(("bulge", drop(bulge)));
}
Some(with_geom(d, with_all(g, fields)))
}
/// Dach-Eckgriff: die gegenüberliegende Ecke bleibt fix, der Umriss bleibt ein achsparalleles Rechteck.
fn roof_grip(r: &Value, index: f64, x: f64, y: f64) -> Option<Value> {
if index >= DORMER_GRIP_BASE {
@@ -1735,6 +1906,75 @@ mod tests {
assert!(ent(json!({"op": "roofVertex", "id": "R", "index": -1, "pt": [0, 0]})).is_none());
}
/// [26] Ecke einfügen/löschen/aufräumen an Umriss-Ringen; Kanten-Neigung des Dachs läuft mit.
#[test]
fn ring_ecken_einfuegen_loeschen() {
let roof = json!({"id": "R", "type": "roof", "shape": "walm",
"outline": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 8}, {"x": 0, "y": 8}],
"holes": [[{"x": 3, "y": 2}, {"x": 5, "y": 2}, {"x": 5, "y": 4}]],
"edgePitchDeg": [30, null, 40, 50, 20, 21, 22]});
let r = root(json!({"roofs": [roof],
"ceilings": [{"id": "C", "outline": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}]}],
"rooms": [{"id": "Rm", "boundary": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}, {"x": 0, "y": 4}]}],
"context": [{"id": "bg", "type": "excavation", "outline": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}, {"x": 0, "y": 4}],
"edgeSlopes": [1, 2, 3, 4], "edgeShoring": [true, false, false, true]}],
"drawings2d": [{"id": "pl", "geom": {"shape": "polyline", "closed": true, "bulge": [0, 0, 0, 0.5],
"pts": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}, {"x": 0, "y": 4}]}}]}));
let ent = |v: Value| run(&Lookup::plain(&r), &rq(v)).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
// Dach: Kante 1 (Umriss) teilen -> neue Ecke 2, beide Hälften erben `null` (Giebel); Hof-Einträge rücken nach.
let e = ent(json!({"op": "ringInsert", "kind": "roof", "id": "R", "seg": 1, "pt": [11, 4]})).unwrap();
assert_eq!(e["outline"].as_array().unwrap().len(), 5);
assert_eq!(e["outline"][2], json!({"x": 11, "y": 4}));
assert_eq!(e["edgePitchDeg"], json!([30, null, null, 40, 50, 20, 21, 22]));
// Hof-Kante (flacher Index 5) teilen: Eintrag 21 verdoppelt, Umriss unberührt.
let e = ent(json!({"op": "ringInsert", "kind": "roof", "id": "R", "seg": 5, "pt": [5, 3]})).unwrap();
assert_eq!(e["holes"][0].as_array().unwrap().len(), 4);
assert_eq!(e["edgePitchDeg"], json!([30, null, 40, 50, 20, 21, 21, 22]));
// Löschen: Umriss-Ecke 2 -> Kante 1 (Nachbar -> Nachbar) bleibt, Eintrag 2 entfällt.
let e = ent(json!({"op": "ringDelete", "kind": "roof", "id": "R", "index": 2})).unwrap();
assert_eq!(e["outline"].as_array().unwrap().len(), 3);
assert_eq!(e["edgePitchDeg"], json!([30, null, 50, 20, 21, 22]));
// Ecke 0: die Schlusskante bleibt, Eintrag 0 entfällt.
let e = ent(json!({"op": "ringDelete", "kind": "roof", "id": "R", "index": 0})).unwrap();
assert_eq!(e["edgePitchDeg"], json!([null, 40, 50, 20, 21, 22]));
// Hof hat nur 3 Ecken, Index ausserhalb, falsche Art: nichts.
assert!(ent(json!({"op": "ringDelete", "kind": "roof", "id": "R", "index": 5})).is_none());
assert!(ent(json!({"op": "ringDelete", "kind": "roof", "id": "R", "index": 9})).is_none());
assert!(ent(json!({"op": "ringDelete", "kind": "ceiling", "id": "C", "index": 0})).is_none());
assert!(ent(json!({"op": "ringInsert", "kind": "wand", "id": "C", "seg": 0, "pt": [1, 1]})).is_none());
// Decke, Raum.
let e = ent(json!({"op": "ringInsert", "kind": "ceiling", "id": "C", "seg": 2, "pt": [1, 3]})).unwrap();
assert_eq!(e["outline"].as_array().unwrap().len(), 4);
assert_eq!(e["outline"][3], json!({"x": 1, "y": 3}));
let e = ent(json!({"op": "ringDelete", "kind": "room", "id": "Rm", "index": 1})).unwrap();
assert_eq!(e["boundary"].as_array().unwrap().len(), 3);
// Baugrube: Böschung/Verbau laufen mit.
let e = ent(json!({"op": "ringInsert", "kind": "excavation", "id": "bg", "seg": 3, "pt": [-1, 2]})).unwrap();
assert_eq!((e["edgeSlopes"].clone(), e["edgeShoring"].clone()), (json!([1, 2, 3, 4, 4]), json!([true, false, false, true, true])));
let e = ent(json!({"op": "ringDelete", "kind": "excavation", "id": "bg", "index": 1})).unwrap();
assert_eq!((e["edgeSlopes"].clone(), e["edgeShoring"].clone()), (json!([1, 3, 4]), json!([true, false, true])));
// Aufräumen: Ecke 1 auf der Geraden bzw. auf dem Nachbarn entfällt, eine echte Ecke bleibt.
let tidy = |kind: &str, id: &str, ring: Value, index: u32| {
let key = if kind == "ceiling" { "ceilings" } else { "rooms" };
let field = if kind == "ceiling" { "outline" } else { "boundary" };
let r2 = root(json!({ key: [{"id": id, field: ring}] }));
run(&Lookup::plain(&r2), &rq(json!({"op": "ringTidy", "kind": kind, "id": id, "index": index}))).unwrap().ops.first().map(|o| o.to_json()["entity"].clone())
};
let p = |x: f64, y: f64| json!({"x": x, "y": y});
assert_eq!(tidy("ceiling", "c", json!([p(0.0, 0.0), p(2.0, 0.001), p(4.0, 0.0), p(4.0, 4.0)]), 1).unwrap()["outline"].as_array().unwrap().len(), 3);
assert_eq!(tidy("room", "c", json!([p(0.0, 0.0), p(0.0, 0.0), p(4.0, 0.0), p(4.0, 4.0)]), 1).unwrap()["boundary"].as_array().unwrap().len(), 3);
assert!(tidy("room", "c", json!([p(0.0, 0.0), p(2.0, 1.0), p(4.0, 0.0), p(4.0, 4.0)]), 1).is_none());
assert!(tidy("room", "c", json!([p(0.0, 0.0), p(2.0, 0.001), p(4.0, 0.0)]), 1).is_none());
// Polylinie: Aufräumen entfernt die Ecke samt Bulge-Eintrag, aber nicht an einem Bogen-Segment.
let r3 = root(json!({"drawings2d": [
{"id": "a", "geom": {"shape": "polyline", "closed": true, "bulge": [0, 0.5, 0, 0], "pts": [p(0.0, 0.0), p(2.0, 0.0), p(4.0, 0.0), p(4.0, 4.0)]}},
{"id": "b", "geom": {"shape": "polyline", "closed": true, "bulge": [0, 0, 0, 0.5], "pts": [p(0.0, 0.0), p(2.0, 0.0), p(4.0, 0.0), p(4.0, 4.0)]}}]}));
let t3 = |id: &str| run(&Lookup::plain(&r3), &rq(json!({"op": "ringTidy", "kind": "polyline", "id": id, "index": 1}))).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
assert!(t3("a").is_none());
let g = &t3("b").unwrap()["geom"];
assert_eq!((g["pts"].as_array().unwrap().len(), g["bulge"].clone()), (3, json!([0, 0, 0.5])));
}
/// [176] Schnittlinie: Endpunkte und Knickpunkte als Griffe.
#[test]
fn schnittlinie_griffe() {
+1 -1
View File
@@ -73,7 +73,7 @@ export type { GroupMembership, MemberKind } from "../model/groups";
export { drawingVertices, gripPt, openEdges, polylineEdgeGrips, ringEdges } from "../geometry/grips";
export { verticalExtents } from "../geometry/grips";
export type { VerticalExtent } from "../geometry/grips";
export type { GripRequest } from "../geometry/grips";
export type { GripRequest, RingKind } from "../geometry/grips";
export { clampInside, coincidentGripPoints, excavationGripPoints, gripArcWallRadius, gripArcWallResize, gripArcWallTarget, gripAxisLock, gripEdgeTarget, gripPolar, gripPolarPoint, openingGripPoint, openingSheetSlide, openingTypedPosition, sheetHeightDrag, stairMoveHandle, stairParamPoints, wallGripPoints } from "../geometry/gripDrag";
export type { EdgeDrive, GripLocks, SheetHeightKind } from "../geometry/gripDrag";
export { openingPreviewProject, openingPreviewSvgs } from "../plan/openingPreview";
+7
View File
@@ -17,6 +17,9 @@ import { textFrameCorners } from "../text/textFrame";
/** Punkt als `[x, y]` (Anfragen an den Kern). */
type P = [number, number];
/** Elemente mit Umriss-Ring, an denen sich Ecken einfügen/löschen lassen (geschlossene Polylinie eingeschlossen). */
export type RingKind = "roof" | "ceiling" | "room" | "excavation" | "polyline";
/** Eine Griff-Änderung für den Kern (`grips.rs::run`); Zahlen dürfen NaN/±∞ sein (Marken). */
export type GripRequest =
| { op: "moveGrip"; drawingId: string | null; wallId: string | null; index: number; pt: P; scale: number; free?: boolean; arcLength?: number }
@@ -37,6 +40,10 @@ export type GripRequest =
| { op: "sectionBendInsert"; id: string; seg: number; pt: P }
| { op: "sectionBendDelete"; id: string; index: number }
| { op: "sectionLineTidy"; id: string; tol?: number }
// [26] Ecke an Umriss-Ringen einfügen (hinter Kante `seg`), löschen, aufräumen (Kern `ring_edit`); Dach: flacher Index.
| { op: "ringInsert"; kind: RingKind; id: string; seg: number; pt: P }
| { op: "ringDelete"; kind: RingKind; id: string; index: number }
| { op: "ringTidy"; kind: RingKind; id: string; index: number; tol?: number }
// [151] Parameter-Griff einer Podesttreppe (Kern `grip_drag::stair_param_drag`).
| { op: "stairParam"; id: string; index: number; pt: P }
| { op: "excavationEdge"; id: string; a: number; b: number; delta: P }
+3
View File
@@ -1044,6 +1044,9 @@ export const de = {
"ctx.deletePoint": "Punkt löschen",
"ctx.insertBend": "Knick einfügen",
"ctx.deleteBend": "Knick löschen",
"ctx.insertCorner": "Ecke einfügen",
"ctx.deleteCorner": "Ecke löschen",
"ctx.deleteCorner.min": "Mindestens drei Ecken bleiben.",
"ctx.vertexType.corner": "Eckpunkt",
"ctx.vertexType.arc": "Bogenpunkt",
"ctx.vertexType.spline": "Splinepunkt",
+3
View File
@@ -1039,6 +1039,9 @@ export const en: Record<TranslationKey, string> = {
"ctx.deletePoint": "Delete point",
"ctx.insertBend": "Insert bend",
"ctx.deleteBend": "Delete bend",
"ctx.insertCorner": "Insert corner",
"ctx.deleteCorner": "Delete corner",
"ctx.deleteCorner.min": "At least three corners remain.",
"ctx.vertexType.corner": "Corner point",
"ctx.vertexType.arc": "Arc point",
"ctx.vertexType.spline": "Spline point",
+22
View File
@@ -7,6 +7,7 @@
import type { RefObject } from "react";
import { useStore } from "../state/appStore";
import { ContextMenu } from "../ui/ContextMenu";
import type { Vec2 } from "../model/types";
import type { PlanViewHandle } from "../views/plan/PlanView";
import { countClosedAreas, differenceDrawings, intersectionDrawings, unionDrawings } from "../editors/booleanOps";
import { categoryNames } from "../state/selectionLayers";
@@ -59,6 +60,8 @@ export function AppContextMenu(props: {
insertDrawingPoint,
insertSectionBend,
deleteSectionBend,
insertRingVertex,
deleteRingVertex,
deleteDrawingPoint,
setPolylineVertexType,
reorderDrawingLevels,
@@ -149,6 +152,25 @@ export function AppContextMenu(props: {
})(),
insertSectionBend,
deleteSectionBend,
// [26] Umriss-Ecken: genau ein Element mit Umriss gewählt (sonst kein Bezug für den Klick).
selectedRing: (() => {
const total = Object.values(selection).reduce((n, v) => n + (Array.isArray(v) ? v.length : 0), 0);
if (total !== 1) return null;
const roof = selection.roofs.length === 1 ? (project.roofs ?? []).find((x) => x.id === selection.roofs[0]) : undefined;
if (roof && !roof.locked) {
return { kind: "roof" as const, id: roof.id, rings: [roof.outline, ...(roof.holes ?? [])].reduce<{ pts: Vec2[]; off: number }[]>(
(acc, pts) => [...acc, { pts, off: acc.reduce((n, r) => n + r.pts.length, 0) }], []) };
}
const ceiling = selection.ceilings.length === 1 ? (project.ceilings ?? []).find((x) => x.id === selection.ceilings[0]) : undefined;
if (ceiling && !ceiling.locked) return { kind: "ceiling" as const, id: ceiling.id, rings: [{ pts: ceiling.outline, off: 0 }] };
const room = selection.rooms.length === 1 ? (project.rooms ?? []).find((x) => x.id === selection.rooms[0]) : undefined;
if (room && !room.locked) return { kind: "room" as const, id: room.id, rings: [{ pts: room.boundary, off: 0 }] };
const ctx = selection.contextObjects.length === 1 ? (project.context ?? []).find((x) => x.id === selection.contextObjects[0]) : undefined;
if (ctx && ctx.type === "excavation") return { kind: "excavation" as const, id: ctx.id, rings: [{ pts: ctx.outline, off: 0 }] };
return null;
})(),
insertRingVertex,
deleteRingVertex,
insertPolylinePoint: insertDrawingPoint,
deletePolylinePoint: deleteDrawingPoint,
setPolylineVertexType,
+32 -1
View File
@@ -8,7 +8,7 @@
// Kommentare deutsch (CONVENTIONS.md).
import { t } from "../i18n";
import { canSetVertexType, vertexTypeOf, type PolylineVertexType } from "../core";
import { canSetVertexType, vertexTypeOf, type PolylineVertexType, type RingKind } from "../core";
import { nearestPolylineTarget, toleranceFor } from "../core";
import type { LayerCategory, Project, Vec2 } from "../model/types";
import { flattenCategories } from "../model/types";
@@ -89,6 +89,10 @@ export interface MenuActions {
/** [176] Einzeln gewählte Schnittlinie: Anfang, Knickpunkte, Ende (für „Knick einfügen/löschen"). */
selectedSectionLine?: { id: string; pts: Vec2[] } | null;
insertSectionBend?: (id: string, seg: number, pt: Vec2) => void;
/** [26] Einzeln gewähltes Element mit Umriss (Dach samt Höfen, Decke, Raum, Baugrube): Ringe mit Start-Index im flachen Ecken-Index. */
selectedRing?: { kind: RingKind; id: string; rings: { pts: Vec2[]; off: number }[] } | null;
insertRingVertex?: (kind: RingKind, id: string, seg: number, pt: Vec2) => void;
deleteRingVertex?: (kind: RingKind, id: string, index: number) => void;
deleteSectionBend?: (id: string, index: number) => void;
/** Ob eine Element-Stil-Zwischenablage gefüllt ist (aktiviert „Einfügen"). */
hasDrawingStyleClipboard: boolean;
@@ -336,6 +340,33 @@ function planMenuItems(
onClick: () => a.deleteSectionBend?.(sec.id, secTarget.index),
});
}
// [26] Umriss-Element: Ecke am Klick einfügen bzw. die getroffene Ecke löschen (mindestens drei bleiben).
const ring = a.selectedRing;
if (ring) {
for (const { pts, off } of ring.rings) {
const geom = { pts, closed: true };
const hit = nearestPolylineTarget(geom, model, toleranceFor(geom));
if (!hit) continue;
if (hit.kind === "segment" && a.insertRingVertex) {
pointItems.push({
label: t("ctx.insertCorner"),
icon: <MenuIcon name="add_circle" />,
onClick: () => a.insertRingVertex?.(ring.kind, ring.id, off + hit.segIndex, hit.at),
});
}
if (hit.kind === "vertex" && a.deleteRingVertex) {
const enabled = pts.length > 3;
pointItems.push({
label: t("ctx.deleteCorner"),
icon: <MenuIcon name="do_not_disturb_on" />,
disabled: !enabled,
title: enabled ? undefined : t("ctx.deleteCorner.min"),
onClick: () => a.deleteRingVertex?.(ring.kind, ring.id, off + hit.index),
});
}
break;
}
}
// Eigenschaften übertragen — dasselbe Muster wie im Ebenen-Menü, nur für
// 2D-Elemente. Kopieren ab einem gewählten Element, Einfügen sobald etwas
// in der Zwischenablage liegt.
+25 -1
View File
@@ -63,7 +63,7 @@ import { reorderByIds } from "../model/reorder";
import { transformMutation } from "../tools/transform";
import type { CopyMode, TransformOp, TransformSelection } from "../tools/transform";
import { uniqueId } from "../tools/types";
import { gripPt, type GripRequest } from "../core";
import { gripPt, type GripRequest, type RingKind } from "../core";
import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension";
import { DEFAULT_PRESETS, type TextStylePreset } from "../text/richText";
import { t } from "../i18n";
@@ -394,6 +394,14 @@ export interface ProjectSlice {
deleteSectionBend: (id: string, index: number) => void;
/** [176] Nach dem Ziehen: Knicke auf einem Nachbarpunkt oder auf der Geraden entfernen. */
tidySectionLine: (id: string, coalesceKey?: string, tol?: number) => void;
/** [26] Ecke von Dach/Decke/Raum/Baugrube/geschlossener Polylinie ziehen (Kern wählt den Op je `kind`); `coalesceKey` fasst Einfügen + Zug zusammen. */
moveRingVertex: (kind: RingKind, id: string, index: number, pt: Vec2, coalesceKey?: string) => void;
/** [26] Ecke hinter Ecke `seg` (Dach: flacher Index) einfügen; Kanten-Eigenschaften erbt die neue Kante. */
insertRingVertex: (kind: RingKind, id: string, seg: number, pt: Vec2, coalesceKey?: string) => void;
/** [26] Ecke löschen (mind. 3 bleiben); ein Undo-Schritt. */
deleteRingVertex: (kind: RingKind, id: string, index: number) => void;
/** [26] Nach dem Ziehen: Ecke auf Nachbar bzw. Gerade zwischen den Nachbarn entfällt. */
tidyRingVertex: (kind: RingKind, id: string, index: number, coalesceKey?: string, tol?: number) => void;
moveExcavationEdge: (id: string, aIndex: number, bIndex: number, delta: Vec2) => void;
/** Verschiebt eine Decke (ganzer Umriss) um `delta`. */
moveCeilingBy: (ceilingId: string, delta: Vec2) => void;
@@ -1256,6 +1264,22 @@ export function createProjectSlice(
applyGrip({ op: "sectionLineGrip", id, index, pt: gripPt(pt) }, coalesceKey ?? `moveSectionLineGrip:${id}:${index}`),
insertSectionBend: (id, seg, pt, coalesceKey) => applyGrip({ op: "sectionBendInsert", id, seg, pt: gripPt(pt) }, coalesceKey),
deleteSectionBend: (id, index) => applyGrip({ op: "sectionBendDelete", id, index }),
moveRingVertex: (kind, id, index, pt, coalesceKey) => {
const p = gripPt(pt);
const req: GripRequest =
kind === "roof" ? { op: "roofVertex", id, index, pt: p }
: kind === "ceiling" ? { op: "ceilingGrip", id, index, pt: p }
: kind === "room" ? { op: "roomGrip", id, index, pt: p }
: kind === "excavation" ? { op: "excavationGrip", id, index, pt: p }
: { op: "moveGrip", drawingId: id, wallId: null, index, pt: p, scale: DEFAULT_SCALE_DENOMINATOR };
applyGrip(req, coalesceKey ?? `moveRingVertex:${kind}:${id}:${index}`);
},
insertRingVertex: (kind, id, seg, pt, coalesceKey) =>
applyGrip(kind === "polyline" ? { op: "insertPoint", id, seg, pt: gripPt(pt) } : { op: "ringInsert", kind, id, seg, pt: gripPt(pt) }, coalesceKey),
deleteRingVertex: (kind, id, index) =>
applyGrip(kind === "polyline" ? { op: "deletePoint", id, index } : { op: "ringDelete", kind, id, index }),
tidyRingVertex: (kind, id, index, coalesceKey, tol) =>
applyGrip({ op: "ringTidy", kind, id, index, ...(tol != null ? { tol } : {}) }, coalesceKey),
tidySectionLine: (id, coalesceKey, tol) => applyGrip({ op: "sectionLineTidy", id, ...(tol != null ? { tol } : {}) }, coalesceKey),
moveExcavationEdge: (id, aIndex, bIndex, delta) =>
+125
View File
@@ -0,0 +1,125 @@
// [26] Ecke einfügen/löschen an Umriss-Ringen (Dach samt Hof, Decke, geschlossene Polylinie) über den Store:
// ein Undo-Schritt je Aktion, Einfügen + Zug + Aufräumen mit gleichem Schlüssel ebenso; Kanten-Neigung des Dachs läuft mit.
import { beforeEach, describe, expect, it } from "vitest";
import { getState, setState } from "./appStore";
import type { Project, Roof } from "../model/types";
const roof: Roof = {
id: "RF1",
type: "roof",
floorId: "eg",
categoryCode: "31",
outline: [
{ x: 0, y: 0 },
{ x: 12, y: 0 },
{ x: 12, y: 8 },
{ x: 0, y: 8 },
],
holes: [
[
{ x: 4, y: 2 },
{ x: 4, y: 6 },
{ x: 8, y: 6 },
],
],
edgePitchDeg: [30, null, 40, 50, 20, 21, 22],
shape: "walm",
pitchDeg: 35,
overhang: 0,
ridgeAxis: "x",
thickness: 0.2,
};
const baseProject = {
id: "p",
name: "T",
layers: [],
drawingLevels: [{ id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, baseElevation: 0 }],
walls: [],
drawings2d: [
{
id: "pl",
type: "drawing2d",
levelId: "eg",
categoryCode: "20",
geom: { shape: "polyline", closed: true, pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }] },
},
],
roofs: [roof],
} as unknown as Project;
const current = (): Roof => getState().project.roofs![0];
const poly = () => {
const g = getState().project.drawings2d.find((d) => d.id === "pl")!.geom;
if (g.shape !== "polyline") throw new Error("keine Polylinie");
return g;
};
beforeEach(() => {
setState({ project: JSON.parse(JSON.stringify(baseProject)), undoDepth: 0, redoDepth: 0, canUndo: false, canRedo: false });
getState().clearHistory();
});
describe("Ecken am Dach", () => {
it("Einfügen erbt die geteilte Kante, ein Undo-Schritt", () => {
getState().insertRingVertex("roof", "RF1", 1, { x: 13, y: 4 });
expect(current().outline).toHaveLength(5);
expect(current().outline[2]).toEqual({ x: 13, y: 4 });
expect(current().edgePitchDeg).toEqual([30, null, null, 40, 50, 20, 21, 22]);
expect(getState().undoDepth).toBe(1);
getState().undo();
expect(current().outline).toHaveLength(4);
expect(current().edgePitchDeg).toEqual([30, null, 40, 50, 20, 21, 22]);
});
it("Einfügen, Ziehen und Aufräumen mit gleichem Schlüssel sind ein Schritt; auf die Gerade zurück entfällt die Ecke", () => {
const key = "ringInsert:RF1:1";
getState().insertRingVertex("roof", "RF1", 0, { x: 6, y: 1 }, key);
getState().moveRingVertex("roof", "RF1", 1, { x: 6, y: 3 }, key);
getState().moveRingVertex("roof", "RF1", 1, { x: 6, y: 0.001 }, key);
getState().tidyRingVertex("roof", "RF1", 1, key, 0.01);
expect(current().outline).toHaveLength(4);
expect(current().edgePitchDeg).toEqual([30, null, 40, 50, 20, 21, 22]);
getState().undo();
expect(current().outline).toHaveLength(4);
expect(getState().canUndo).toBe(false);
});
it("gezogene Ecke bleibt, solange sie nicht auf der Geraden liegt (ein Undo-Schritt)", () => {
const key = "ringInsert:RF1:2";
getState().insertRingVertex("roof", "RF1", 0, { x: 6, y: 1 }, key);
getState().moveRingVertex("roof", "RF1", 1, { x: 6, y: -2 }, key);
getState().tidyRingVertex("roof", "RF1", 1, key, 0.01);
expect(current().outline).toHaveLength(5);
expect(current().outline[1]).toEqual({ x: 6, y: -2 });
expect(getState().undoDepth).toBe(1);
});
it("Löschen: Hof-Ecke geht nicht unter drei, Umriss-Ecke schon, Kanten-Eintrag entfällt", () => {
getState().deleteRingVertex("roof", "RF1", 4); // Hof hat 3 Ecken
expect(current().holes![0]).toHaveLength(3);
expect(getState().canUndo).toBe(false);
getState().deleteRingVertex("roof", "RF1", 2);
expect(current().outline).toHaveLength(3);
expect(current().edgePitchDeg).toEqual([30, null, 50, 20, 21, 22]);
expect(getState().undoDepth).toBe(1);
});
});
describe("Ecken an der geschlossenen Polylinie", () => {
it("Einfügen, Aufräumen auf der Geraden, Löschen", () => {
const key = "ringInsert:pl:1";
getState().insertRingVertex("polyline", "pl", 0, { x: 2, y: 1 }, key);
expect(poly().pts).toHaveLength(5);
getState().moveRingVertex("polyline", "pl", 1, { x: 2, y: 0.002 }, key);
getState().tidyRingVertex("polyline", "pl", 1, key, 0.01);
expect(poly().pts).toHaveLength(4);
expect(getState().undoDepth).toBe(1);
getState().deleteRingVertex("polyline", "pl", 2);
expect(poly().pts).toHaveLength(3);
// Mindestens drei Ecken bleiben.
getState().deleteRingVertex("polyline", "pl", 0);
expect(poly().pts).toHaveLength(3);
});
});
+75 -1
View File
@@ -8,6 +8,7 @@
import { useRef, useState, type RefObject } from "react";
import { useEventBundle, useSameData } from "./useEvent";
import { leftNormal, normalize, scale, sub, wallCorners } from "../model/geometry";
import type { RingKind } from "../core";
import type { Ceiling, Drawing2D, EdgeGrip, Excavation, Project, Roof, Room, Vec2, Wall } from "../model/types";
import { wallTypeThickness } from "../model/types";
import { bulgeArcPoints, drawingVertices, surfaceOpeningGripPatch, surfaceOpeningGrips, surfaceOpeningInfo, wallArcBand } from "../core";
@@ -199,6 +200,8 @@ export function useGripEditing(opts: {
/** Pixel je Meter beim letzten Zug (Aufräum-Toleranz). */
const sectionPxRef = useRef(0);
const sectionDragRef = useRef<{ id: string; key: string; midIndex: number; bendIndex: number } | null>(null);
/** [26] Laufender Zug an einer Einfüge-Raute: gemeinsamer Undo-Schlüssel, Raute-Index und Index der eingefügten Ecke. */
const ringDragRef = useRef<{ kind: RingKind; id: string; key: string; midIndex: number; vertex: number } | null>(null);
// Mit gezeigter Beschriftung dazu ihr Griff (`labelOffset`, s. `treeGrips.ts`).
const treeGrips = (tr: NonNullable<typeof selectedTree>): Vec2[] => treeGripPoints(tr, scaleDenominator);
const selectedRoomId = single(selection, "rooms");
@@ -220,6 +223,9 @@ export function useGripEditing(opts: {
drawingId?: string;
wallId?: string;
localIndex: number;
/** [26] Einfüge-Griff (Raute) in Kante `insertSeg` des Umriss-Rings `ring` (Dach: flacher Index). */
insertSeg?: number;
ring?: { kind: RingKind; id: string };
}
const gripOwners: GripOwner[] = [];
// [ersterFlachIndex, letzterFlachIndex] DESSELBEN Elements — für die Anker-
@@ -310,6 +316,32 @@ export function useGripEditing(opts: {
return [];
})();
const MAX_INSERT_GRIP_POINTS = 100; // Kataster-Umrisse mit tausenden Punkten: keine Rauten
/** Anteil entlang der Kante, an dem der Einfüge-Griff sitzt (neben dem Kanten-Anfasser in der Mitte). */
const INSERT_AT = 0.25;
/**
* [26] Einfüge-Griffe (Rauten) je Kante der Ringe hinter die Ecken-Griffe in `out` hängen: Ziehen fügt dort eine
* Ecke ein. `rings` mit Start-Index im flachen Ecken-Index (Dach: Umriss, dann Höfe).
*/
const pushInsertGrips = (
out: Vec2[],
rings: { pts: Vec2[]; off: number }[],
ring: { kind: RingKind; id: string },
owner: { drawingId?: string } = {},
keep?: (seg: number) => boolean,
) => {
const start = out.length;
for (const { pts, off } of rings) {
pts.forEach((a, i) => {
if (keep && !keep(off + i)) return;
const b = pts[(i + 1) % pts.length];
out.push({ x: a.x + (b.x - a.x) * INSERT_AT, y: a.y + (b.y - a.y) * INSERT_AT, insert: true } as Vec2);
gripOwners.push({ ...owner, localIndex: -1, insertSeg: off + i, ring });
});
}
for (let i = start; i < out.length; i++) gripOwnerRange.push([start, out.length - 1]);
};
const grips: Vec2[] = (() => {
// Öffnung (Fenster/Tür): EIN Mittelpunkt-Griff auf der Wandachse. Ziehen
// verschiebt die Öffnung entlang der Wirts-Wand (siehe applyGrip →
@@ -364,12 +396,14 @@ export function useGripEditing(opts: {
for (const { pts, off } of roofRings(selectedRoof)) {
pts.forEach((q, i) => { out.push(q); gripOwners.push({ localIndex: off + i }); gripOwnerRange.push([off, off + pts.length - 1]); });
}
pushInsertGrips(out, roofRings(selectedRoof), { kind: "roof", id: selectedRoof.id });
return out;
}
// [68] Baugrube: Umriss-Ecken + Sohlen-Griff (Lage: Schwerpunkt, y um die Sohlenhöhe versetzt).
if (modelEditable && selectedExcavation && !selectedCeiling && effectiveDrawingIds.length === 0 && selectedWallIds.length === 0) {
const pts = excavationGripPoints(selectedExcavation);
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
pushInsertGrips(pts, [{ pts: selectedExcavation.outline, off: 0 }], { kind: "excavation", id: selectedExcavation.id });
return pts;
}
// Decke: die Umriss-Vertices als Griffe (nur bei genau einer gewählten Decke,
@@ -377,6 +411,7 @@ export function useGripEditing(opts: {
if (modelEditable && selectedCeiling && effectiveDrawingIds.length === 0 && selectedWallIds.length === 0) {
const pts = [...selectedCeiling.outline];
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
if (!selectedCeiling.locked) pushInsertGrips(pts, [{ pts: selectedCeiling.outline, off: 0 }], { kind: "ceiling", id: selectedCeiling.id });
return pts;
}
// Raum: die Umriss-Vertices als Griffe (nur bei genau einem gewählten Raum).
@@ -389,6 +424,7 @@ export function useGripEditing(opts: {
) {
const pts = [...selectedRoom.boundary];
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
if (!selectedRoom.locked) pushInsertGrips(pts, [{ pts: selectedRoom.boundary, off: 0 }], { kind: "room", id: selectedRoom.id });
return pts;
}
// Mehrfachauswahl (Regel- UND Standardfall): je gewähltem 2D-Element bzw.
@@ -425,6 +461,10 @@ export function useGripEditing(opts: {
? (i: number) => i < g.pts.length || Math.abs(g.bulge?.[i - g.pts.length] ?? 0) > 1e-9
: undefined;
pushGroup(drawingVertices(d, scaleDenominator), { drawingId: id }, keep);
// [26] Geschlossene Polylinie: Einfüge-Raute auf jedem geraden Segment (Bogen-Segmente haben ihren Mitten-Griff).
if (g.shape === "polyline" && g.closed && !d.locked && g.pts.length >= 3 && g.pts.length <= MAX_INSERT_GRIP_POINTS) {
pushInsertGrips(out, [{ pts: g.pts, off: 0 }], { kind: "polyline", id }, { drawingId: id }, (seg) => Math.abs(g.bulge?.[seg] ?? 0) < 1e-9);
}
}
if (modelEditable && effectiveDrawingIds.length === 0) {
for (const id of selectedWallIds) {
@@ -716,6 +756,7 @@ export function useGripEditing(opts: {
// Wand/Öffnung/Treppe haben keine Polygon-Nachbarn → null.
const resolvePolygonRing = (index: number): { pts: Vec2[]; index: number; closed: boolean } | null => {
const owner = gripOwners[index];
if (owner?.insertSeg != null) return null;
if (roofGripsOn && selectedRoof && !owner?.drawingId && !owner?.wallId) {
const ring = roofRings(selectedRoof).find((rg) => index >= rg.off && index < rg.off + rg.pts.length);
return ring ? { pts: ring.pts, index: index - ring.off, closed: true } : null;
@@ -935,6 +976,20 @@ export function useGripEditing(opts: {
// Editier-Dispatch: bei gewählter Decke auf die Decken-Aktionen umleiten, sonst
// auf die Wand/2D-Aktionen. So teilen Plan- UND 3D-Griffe denselben Pfad.
const applyGrip = (index: number, pt: Vec2, arcLength?: number) => {
// [26] Einfüge-Raute am Umriss (Dach, Decke, Raum, Baugrube, geschlossene Polylinie): der erste Zug fügt die Ecke
// ein, danach folgt sie dem Zeiger; Einfügen, Zug und Aufräumen sind ein Undo-Schritt (gleicher Schlüssel).
const rd = ringDragRef.current;
if (rd && rd.midIndex === index) {
storeState().moveRingVertex(rd.kind, rd.id, rd.vertex, pt, rd.key);
return;
}
const ins = gripOwners[index];
if (modelEditable && ins?.insertSeg != null && ins.ring) {
const key = `ringInsert:${ins.ring.id}:${Date.now()}`;
ringDragRef.current = { ...ins.ring, key, midIndex: index, vertex: ins.insertSeg + 1 };
storeState().insertRingVertex(ins.ring.kind, ins.ring.id, ins.insertSeg, pt, key);
return;
}
// Öffnung: den gezogenen Punkt auf die Wandachse projizieren → neue
// `position` (Abstand des ersten Pfostens vom Wand-Start), sodass die
// Öffnung entlang der Wand gleitet. Griff sitzt in der Öffnungsmitte, daher
@@ -1112,13 +1167,18 @@ export function useGripEditing(opts: {
else if (pa.kind === "excavation") moveExcavationGrip(pa.id, pa.index, pa.pt);
else if (pa.kind === "roof") opts.moveRoofVertex?.(pa.id, pa.index, pa.pt);
else moveCeilingGrip(pa.id, pa.index, pa.pt);
// [26] Ecke auf einem Nachbarn bzw. auf der Geraden zwischen den Nachbarn entfällt (im selben Undo-Schritt).
storeState().tidyRingVertex(pa.kind, pa.id, pa.index, undefined, ringTidyTol());
}
const pw = pendingWallGripRef.current;
pendingWallGripRef.current = null;
if (pw) moveGripOf(null, pw.wallId, pw.localIndex, pw.pt, scaleDenominator, undefined, pw.arcLength);
const pend = pendingGripRef.current;
pendingGripRef.current = null;
if (pend) moveGripOf(pend.drawingId, null, pend.localIndex, pend.pt, scaleDenominator);
if (pend) {
moveGripOf(pend.drawingId, null, pend.localIndex, pend.pt, scaleDenominator);
storeState().tidyRingVertex("polyline", pend.drawingId, pend.localIndex, undefined, ringTidyTol());
}
};
/** Polylinien-Element (nicht gesperrt), dessen Änderung aufgeschoben werden darf. */
@@ -1254,8 +1314,16 @@ export function useGripEditing(opts: {
// Zeiger-Genauigkeit: ca. 6 Pixel der Ansicht.
if (drag) storeState().tidySectionLine(drag.id, drag.key, sectionPxRef.current > 0 ? 6 / sectionPxRef.current : undefined);
};
/** Aufräum-Abstand (m) der Ecken: ca. 6 Pixel der Ansicht (unbekannt = Kern-Vorgabe). */
const ringTidyTol = (): number | undefined => (sectionPxRef.current > 0 ? 6 / sectionPxRef.current : undefined);
/** [26] Nach einem Zug an einer Einfüge-Raute: die eingefügte Ecke entfällt, wenn sie auf der Geraden liegt. */
const tidyRingDrag = () => {
const rd = ringDragRef.current;
if (rd) storeState().tidyRingVertex(rd.kind, rd.id, rd.vertex, rd.key, ringTidyTol());
};
const endEditing = () => {
sectionDragRef.current = null;
ringDragRef.current = null;
setDraft(null);
edgeAppliedDeltaRef.current = null; // Kanten-Drag beendet → Anker zurücksetzen
moveCoincidentRef.current = null; // Körper-Koinzidenz-Gruppe verwerfen
@@ -1377,6 +1445,7 @@ export function useGripEditing(opts: {
// verankern (s. Kommentar an gripOriginRef).
if (gripDragInfoRef.current === null) {
sectionDragRef.current = null; // [176] neuer Zug: eigener Undo-Schlüssel, kein eingefügter Knick
ringDragRef.current = null; // [26] dito für eingefügte Ecken
gripOriginRef.current = grips[index];
const op0 = selectedOpeningId ? (project.openings ?? []).find((o) => o.id === selectedOpeningId) : undefined;
const dir0 = op0 ? openingWallDir() : null;
@@ -1609,6 +1678,7 @@ export function useGripEditing(opts: {
commitPendingGrip();
commitPendingBody();
tidySectionDrag();
tidyRingDrag();
endEditing();
},
// Bewaffneten Punkt-Griff verwerfen (Escape): exakt auf `origin`
@@ -1625,6 +1695,10 @@ export function useGripEditing(opts: {
} else if (sectionDragRef.current) {
applyGrip(index, origin);
tidySectionDrag();
} else if (ringDragRef.current) {
// Eingefügte Ecke zurück auf die Kante: das Aufräumen entfernt sie wieder.
applyGrip(index, origin);
tidyRingDrag();
} else if (!selectedSectionLine) applyGrip(index, origin);
endEditing();
},
+4
View File
@@ -128,6 +128,8 @@ export function useProjectActions(
const insertDrawingPoint = useStore((s) => s.insertDrawingPoint);
const insertSectionBend = useStore((s) => s.insertSectionBend);
const deleteSectionBend = useStore((s) => s.deleteSectionBend);
const insertRingVertex = useStore((s) => s.insertRingVertex);
const deleteRingVertex = useStore((s) => s.deleteRingVertex);
const deleteDrawingPoint = useStore((s) => s.deleteDrawingPoint);
const setPolylineVertexType = useStore((s) => s.setPolylineVertexType);
// Wandstile: immutable Patch eines Wandtyps (z. B. Schichtfugen-Stile). Kein
@@ -448,6 +450,8 @@ export function useProjectActions(
insertDrawingPoint,
insertSectionBend,
deleteSectionBend,
insertRingVertex,
deleteRingVertex,
deleteDrawingPoint,
setPolylineVertexType,
patchWallType,