diff --git a/TODO.md b/TODO.md index 369dbd06..6c94141e 100644 --- a/TODO.md +++ b/TODO.md @@ -3265,6 +3265,45 @@ Format · [90] Versionsvergleich · [91] Assistent · [92] Speckle. `validate-ifc.py` (0 Befunde; Mengen 133.56 → 103.56 m²). **Offen:** Pult mit Höfen (Höfe weiter ignoriert); Pult auf schiefem Umriss neigt weiter nur entlang x/y (`ridgeAxis`); Attika/Gefälle fehlen im Modell; Dachfenster-Laibung genau auf einer Fuge doppelt; nicht in der Tauri-App/Metal angesehen. · M +- ◐ **[149] Baum als eigenes Objekt.** (6.11., Befund aus [142]: Bäume waren nur Kreise der Ebene 13 mit einer Höhe + `sunStudy.treeHeight` für alle.) **Modell** (Rust, `model/generated.rs`): `Tree` (Stammmitte `position`, `trunkDiameter`, + `crownDiameter`, `crownBase` = Kronenansatz, `height`, `shape` rund/oval/säulenförmig/kegelförmig, `status` + bestehend/neu/zu fällen, `foliage` Laub/Nadel, optional `species`, `baseOffset`, `color`, `locked`), `Project.trees` + (+ `KNOWN_KEYS`, `set_item`, Typen neu erzeugt); Ops/Prüfung wie die übrigen Listen. Geometrie `core/src/tree.rs`: + Vorgaben für Unsinn (NaN, ≤ 0, Ansatz ≤ 90 % der Höhe, Stamm ≤ Krone), Kronenprofil je Form (Ellipsoid, Eiform mit + breitester Stelle bei 40 %, Superellipse ^4, Kegel), Fuss auf dem sichtbaren Gelände (inkl. Baugruben, wie [142]) sonst + Geschoss-UK, + `baseOffset`. **Grundriss** (`plan/trees.rs`, mit den Stützen in einer Gruppe): Laubbaum Wellenkranz, + Nadelbaum Zackenkranz, Stamm als Kreis; bestehend Ebenenfarbe/Tusche mit gefülltem Stamm, neu rot (offener Stamm), zu + fällen gelb, gestrichelt und durchgekreuzt (Kreuz trägt die Aussage im Schwarz-Weiss-Druck). Pick: unsichtbare + Kronenfläche mit `contextObjectId = "@tree:"` (kein neues Id-Feld im Plan-Puffer). **Schnitt/Ansicht**: Silhouette + (Kronenprofil gespiegelt + Stamm), Ansicht in der Maler-Reihenfolge (Krone hellgrün bzw. weiss in Tusche, Kanten der + Bauteile bleiben darüber), Schnitt transparent unter dem Schnittbild (Bäume hinter der Ebene, Bounds erweitert). + **3D** (`model3d::emit_trees`, bei den Stützen-Meshes): Stamm-Zylinder (8 Seiten) + Krone als Rotationskörper (8 Ringe × + 12 Seiten, < 250 Dreiecke je Baum), wirft/empfängt im Shadow-Mapping ([64]) wie jedes Netz; Pick `pickGeometry.trees`, + Hervorhebung, Explosion, glTF/OBJ-Gruppe `Baum_`. **IFC**: Datensatz `TREE` (19) → IFC4 `IfcGeographicElement` + (ObjectType „Baum“, USERDEFINED), IFC2x3 `IfcBuildingElementProxy`; Netz Stamm + Krone, Pset `Dossier_Tree` + (Status, Foliage, Species) und `Dossier_Qto_Tree` (Height, CrownDiameter, TrunkDiameter, CrownBaseHeight). + **Schatten** (`sun.rs`): je Baum Stamm-Prisma + Kronen-Punktwolke nach eigener Höhe/Krone/Form; Kreise der Ebene 13 + bleiben Fallback mit `treeHeight`. **Werkzeug „Baum“** (`commands/cmds/tree.ts`, Kern `cmd_create.rs` „tree“; Werkzeug- + Palette, Kürzel `baum`): Klick setzt (mehrere nacheinander), Zahl = Kronendurchmesser, Optionen Form/Bestand/Laub-Nadel; + Objekt-Info `TreeSection` (Art, Bestand, Form, Laub/Nadel, Höhe, Kronen-Ø, Kronenansatz, Stamm-Ø, X/Y; je Änderung ein + Undo-Schritt); Griffe Stammmitte (verschieben) und Kronenrand (Durchmesser), je Zug ein Undo-Schritt. Auswahl-Art + `trees` (Plan, Klick-Zyklus, 3D), Verschieben/Kopieren/Spiegeln/Drehen (`cmd_transform`, `treeIds`), Löschen, + Zwischenablage (`cmd_paste`), Geo-Verschiebung. **Musterhaus komplex unverändert** (Kreise bleiben); Befehl „Kreise in + Bäume umwandeln“ (`circlestotrees`): gewählte Kreise, sonst alle Kreise der Baum-Ebene im aktiven Geschoss → Bäume + (Kronen-Ø = Kreis-Ø, Höhe `treeHeight`), Kreise entfallen, ein Undo-Schritt. + Tests: Rust `tree::tests` (Modell/Vorgaben, Netz dicht und aussen orientiert, Kegelvolumen, Silhouette), `plan::trees` + (Planzeichen je Bestand/Laub, Ebene aus, Ansicht-Silhouette), `sun::baum_objekt_schatten_nach_hoehe` (Länge nach + Höhe, Breite nach Krone), `model3d::baeume_im_3d_und_pick`, `ifc_data::baum_datensatz`, fileio + `baum_als_geografisches_element` (IFC4/2x3), `cmd_create::baum_setzen_und_kreise_umwandeln`, + `cmd_transform::baeume_verschieben_und_kopieren`; vitest `tree.test.ts` (Werkzeug, Umwandeln); e2e `tree.spec.ts` + (setzen, im Plan wählen, Höhe ändern, Undo, löschen). Geprüft: CLI Situation EG 1:200 (Tusche und Farbe, mit Schatten), + Ansicht Süd, Schnitt B-B (Linux/Chromium); 3D mit `render_png` (Linux/lavapipe, iso, Sonne SO: Bäume mit Schatten); + IFC mit `validate-ifc.py` (0 Befunde, 5 IfcGeographicElement). Goldens unverändert (Musterhäuser ohne Baum-Objekte). + **Offen:** nicht auf Metal und nicht in der Tauri-App geprüft (3D-Pick nur Unit-Test); Bäume nicht gruppierbar und + nicht im Auswahlrechteck; keine Art-Beschriftung im Plan; Krone im Schatten als konvexe Hülle; Schnitt durch die Krone zeigt die ganze Silhouette (kein Schnittbild); Fuss + am Gelände der Stammmitte (Hang unter der Krone nicht berücksichtigt); Kreise der Ebene 13 zusätzlich zum Baum-Objekt + werfen weiter Schatten (doppelt, wenn beide gezeichnet sind). · M - ◐ **[68] Baugrube / Geländebearbeitung.** (30.10.) Kontext-Objekt `excavation` (Rust-Modell, `ContextObject`): Sohle (`outline`, `bottom` m ±0.00), Böschung `slope` (Standard 45°, je Kante `edgeSlopes`), Schüttung `fillSlope` (33.7°), Bermen `bermWidth`/`bermHeight`. Neues Gelände = clamp(t, b − d·tan β, b + H(d)) mit d = Abstand zum diff --git a/e2e/tree.spec.ts b/e2e/tree.spec.ts new file mode 100644 index 00000000..216f6004 --- /dev/null +++ b/e2e/tree.spec.ts @@ -0,0 +1,57 @@ +// [149] Baum als eigenes Objekt: im Musterhaus mit dem Werkzeug „Baum" einen Baum setzen (Befehlszeile), +// im Plan anklicken (Kronenfläche, Pick im Kern), in der Objekt-Info die Höhe ändern und rückgängig machen. +import type { Page } from "@playwright/test"; +import { blurFocus, commandInput, expect, finishCommand, openSample, openTab, startNewProject, test, typeCommand } from "./app"; + +async function clickModel(page: Page, x: number, y: number): Promise { + const p = await page.locator("svg.plan-svg").first().evaluate( + (el, [x, y]) => { + const [vx, vy, vw, vh] = el.getAttribute("viewBox")!.split(/\s+/).map(Number); + const ox = Number(el.getAttribute("data-origin-x") ?? 0); + const oy = Number(el.getAttribute("data-origin-y") ?? 0); + const r = el.getBoundingClientRect(); + const s = Math.min(r.width / vw, r.height / vh); + return { x: r.left + (r.width - vw * s) / 2 + (x * 90 - ox - vx) * s, y: r.top + (r.height - vh * s) / 2 + (-y * 90 - oy - vy) * s }; + }, + [x, y], + ); + await page.mouse.click(p.x, p.y); +} + +test("Baum setzen, Höhe ändern, Undo", async ({ page }) => { + test.setTimeout(90_000); + await startNewProject(page); + await openSample(page); + await openTab(page, "Objekt-Info"); + + await commandInput(page).focus(); + await typeCommand(page, "baum"); + await expect(page.locator(".cmdline-prompt")).toHaveText("Baum setzen (Zahl = Kronendurchmesser):"); + await typeCommand(page, "6"); + await typeCommand(page, "4,-6"); + await finishCommand(page); + await blurFocus(page); + + const objInfo = page.locator(".objinfo-panel").first(); + const field = (name: string) => + objInfo.locator("label.objinfo-field").filter({ has: page.locator(".objinfo-flabel", { hasText: new RegExp(`^${name}$`) }) }).locator("input"); + const height = field("Höhe"); + await expect(async () => { + await page.keyboard.press("Escape"); + // Neben der Stammmitte in die Krone klicken (Kronenradius 3 m). + await clickModel(page, 5, -6); + await expect(height).toBeVisible({ timeout: 1000 }); + }).toPass({ timeout: 30_000 }); + await expect(objInfo).toContainText("Baum"); + await expect(field("Kronen-Ø")).toHaveValue("6.000"); + await expect(height).toHaveValue("10.000"); + await height.fill("15"); + await height.press("Enter"); + await expect(height).toHaveValue("15.000"); + await blurFocus(page); + await page.keyboard.press("ControlOrMeta+z"); + await expect(height).toHaveValue("10.000"); + // Löschen mit Entf: die Auswahl (und der Baum) ist weg. + await page.keyboard.press("Delete"); + await expect(height).toBeHidden(); +}); diff --git a/src-tauri/core/src/cmd_create.rs b/src-tauri/core/src/cmd_create.rs index a5a319d4..77687208 100644 --- a/src-tauri/core/src/cmd_create.rs +++ b/src-tauri/core/src/cmd_create.rs @@ -879,6 +879,81 @@ fn column_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { ) } +/// [149] Baum am Punkt `at`: Ebene „13" (Bäume), falls vorhanden, sonst die aktive; Abmessungen, Form, +/// Bestand und Laub/Nadel aus den Werkzeug-Vorgaben (fehlende/unsinnige Werte: Vorgaben aus `tree.rs`). +fn tree_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + use crate::tree::*; + let num = |k: &str, d: f64| opt_n(v, k).filter(|x| *x > 0.0 && x.is_finite()).unwrap_or(d); + let height = num("height", DEFAULT_HEIGHT); + let crown_base = opt_n(v, "crownBase").filter(|x| *x >= 0.0 && x.is_finite()).unwrap_or(DEFAULT_CROWN_BASE).min(0.9 * height); + let pick = |k: &str, allowed: &[&str]| -> Value { s(allowed.iter().copied().find(|a| *a == s_of(v, k)).unwrap_or(allowed[0])) }; + let cat = if p.layer_category(TREE_CATEGORY).is_some() { TREE_CATEGORY } else { ctx.cat }; + let mut f = vec![ + ("id", s(&ids.next("tree"))), + ("type", s("tree")), + ("floorId", s(ctx.level)), + ("categoryCode", s(cat)), + ("position", pv(p_of(v, "at"))), + ("trunkDiameter", js_num(num("trunkDiameter", DEFAULT_TRUNK_DIAMETER))), + ("crownDiameter", js_num(num("crownDiameter", DEFAULT_CROWN_DIAMETER))), + ("crownBase", js_num(crown_base)), + ("height", js_num(height)), + ("shape", pick("shape", &["round", "oval", "columnar", "conical"])), + ("status", pick("status", &["existing", "new", "remove"])), + ("foliage", pick("foliage", &["deciduous", "conifer"])), + ]; + let species = s_of(v, "species").trim(); + if !species.is_empty() { + f.push(("species", s(species))); + } + add_op("trees", vec![obj(f)]) +} + +/// [149] „Kreise in Bäume umwandeln": die gewählten Kreise (`ids`), sonst alle Kreise der Baum-Ebene auf der +/// aktiven Ebene, werden Baum-Objekte (Kronendurchmesser = Kreisdurchmesser, Höhe = `sunStudy.treeHeight` +/// bzw. Vorgabe, Ebene und Geschoss des Kreises); die Kreise entfallen. Ein Undo-Schritt. +fn circles_to_trees_ops(root: &Map, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + use crate::tree::*; + let chosen: Vec<&str> = arr(field(v, "ids")).iter().filter_map(Value::as_str).collect(); + let is_tree_cat = |code: &str| { + code == TREE_CATEGORY || p.layer_category(code).is_some_and(|c| { + let n = c.name.to_lowercase(); + n.contains("baum") || n.contains("bäume") || n.contains("tree") + }) + }; + let h = p.sun_study.as_ref().and_then(|s| s.tree_height).filter(|h| *h > 0.0 && h.is_finite()).unwrap_or(crate::sun::DEFAULT_TREE_HEIGHT); + let (mut src, mut out) = (Vec::new(), Vec::new()); + for d in &p.drawings2d { + let crate::model::Drawing2DGeom::Circle { center, r } = &d.geom else { continue }; + let pick = if chosen.is_empty() { d.level_id == ctx.level && is_tree_cat(&d.category_code) } else { chosen.contains(&d.id.as_str()) }; + if !pick || !(*r > 0.0 && r.is_finite() && center.x.is_finite() && center.y.is_finite()) { + continue; + } + let cat = if is_tree_cat(&d.category_code) { d.category_code.as_str() } else if p.layer_category(TREE_CATEGORY).is_some() { TREE_CATEGORY } else { d.category_code.as_str() }; + src.push(d.id.as_str()); + out.push(obj(vec![ + ("id", s(&ids.next("tree"))), + ("type", s("tree")), + ("floorId", s(&d.level_id)), + ("categoryCode", s(cat)), + ("position", pv((center.x, center.y))), + ("trunkDiameter", js_num(DEFAULT_TRUNK_DIAMETER.min(*r))), + ("crownDiameter", js_num(2.0 * r)), + ("crownBase", js_num(DEFAULT_CROWN_BASE.min(0.4 * h))), + ("height", js_num(h)), + ("shape", s("round")), + ("status", s("existing")), + ("foliage", s("deciduous")), + ])); + } + if out.is_empty() { + return vec![]; + } + let mut ops = remove_op(root, "drawings2d", &src); + ops.extend(add_op("trees", out)); + ops +} + /// Grundriss einer Stütze ohne Drehung (`columnFootprint`: rund 32 Punkte, sonst 4 Ecken). fn column_footprint(at: V, v: &Value) -> Vec { let size = n_of(v, "size"); @@ -988,6 +1063,8 @@ pub fn ops(root: &Map, p: &Project, v: &Value) -> Option> "opening" => opening_ops(root, p, v, &ctx, ids), "roof" => roof_ops(p, v, &ctx, ids), "column" => column_ops(v, &ctx, ids), + "tree" => tree_ops(p, v, &ctx, ids), + "circlesToTrees" => circles_to_trees_ops(root, p, v, &ctx, ids), "extrude" => extrude_ops(root, v, &ctx, ids), _ => return crate::cmd_draw::ops(root, p, v, &ctx, ids).or_else(|| crate::cmd_solid::ops(root, p, v, &ctx, ids)), }) @@ -1067,6 +1144,15 @@ pub fn preview_req(root: &Map, project: &Project, req: &Req, pts: out.poly(&column_footprint(*at, v)); } } + "tree" => { + // [149] Kronenkreis und Stamm am Cursor. + if let Some(at) = pts.first() { + let d = opt_n(v, "crownDiameter").filter(|x| *x > 0.0 && x.is_finite()).unwrap_or(crate::tree::DEFAULT_CROWN_DIAMETER); + let t = opt_n(v, "trunkDiameter").filter(|x| *x > 0.0 && x.is_finite()).unwrap_or(crate::tree::DEFAULT_TRUNK_DIAMETER); + out.poly(&circle_pts(*at, d / 2.0, 32)); + out.poly(&circle_pts(*at, t / 2.0, 12)); + } + } "rect4" => { // Aufgezogenes Rechteck (Dach, Deckenaussparung, Textrahmen …): erste Ecke + Cursor. if pts.len() >= 2 { @@ -1213,6 +1299,39 @@ mod tests { assert_eq!(items(&o, 1)[0]["wallTypeId"], "WT-s-1"); } + /// [149] Baum setzen (Ebene 13, Vorgaben, Unsinn verworfen) und Kreise in Bäume umwandeln. + #[test] + fn baum_setzen_und_kreise_umwandeln() { + let r = root(json!({"layers": [{"code": "13", "name": "Bäume", "color": "#000"}], "drawings2d": [ + {"id": "k1", "type": "drawing2d", "levelId": "F1", "categoryCode": "13", "geom": {"shape": "circle", "center": {"x": 3, "y": 4}, "r": 2.5}}, + {"id": "k2", "type": "drawing2d", "levelId": "F1", "categoryCode": "20", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}}, + {"id": "k3", "type": "drawing2d", "levelId": "F2", "categoryCode": "13", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}} + ], "sunStudy": {"when": "2026-06-21T10:00:00Z", "show": true, "treeHeight": 14}})); + let p = crate::model::lenient::typed_for_test(&r); + let o = ops(&r, &p, &req(json!({"cmd": "tree", "at": [1, 2], "crownDiameter": 7, "height": 15, "shape": "conical", "status": "new", "foliage": "conifer", "species": " Picea abies "}))).unwrap(); + let t = &items(&o, 0)[0]; + assert_eq!(t["categoryCode"], "13"); + assert_eq!((t["crownDiameter"].as_f64(), t["height"].as_f64(), t["trunkDiameter"].as_f64()), (Some(7.0), Some(15.0), Some(crate::tree::DEFAULT_TRUNK_DIAMETER))); + assert_eq!((t["shape"].as_str(), t["status"].as_str(), t["foliage"].as_str(), t["species"].as_str()), (Some("conical"), Some("new"), Some("conifer"), Some("Picea abies"))); + let _: crate::model::Tree = serde_json::from_value(t.clone()).unwrap(); + // Unsinn: Vorgaben, unbekannte Form → rund. + let o = ops(&r, &p, &req(json!({"cmd": "tree", "at": [0, 0], "height": -3, "shape": "weide"}))).unwrap(); + let t = &items(&o, 0)[0]; + assert_eq!((t["height"].as_f64(), t["shape"].as_str()), (Some(crate::tree::DEFAULT_HEIGHT), Some("round"))); + // Umwandeln ohne Auswahl: nur Kreise der Baum-Ebene auf der aktiven Ebene. + let o = ops(&r, &p, &req(json!({"cmd": "circlesToTrees"}))).unwrap(); + assert_eq!(o[0].to_json()["ids"], json!(["k1"])); + let t = &items(&o, 1)[0]; + assert_eq!((t["crownDiameter"].as_f64(), t["height"].as_f64(), t["floorId"].as_str()), (Some(5.0), Some(14.0), Some("F1"))); + assert_eq!(t["position"], json!({"x": 3, "y": 4})); + // Mit Auswahl: genau die gewählten Kreise (auch anderer Ebene). + let o = ops(&r, &p, &req(json!({"cmd": "circlesToTrees", "ids": ["k2", "k3"]}))).unwrap(); + assert_eq!(o[0].to_json()["ids"], json!(["k2", "k3"])); + assert_eq!(items(&o, 1)[1]["floorId"], "F2"); + // Nichts zu tun: keine Ops. + assert!(ops(&r, &p, &req(json!({"cmd": "circlesToTrees", "ids": ["fehlt"]}))).unwrap().is_empty()); + } + #[test] fn treppe_stufen_aus_auftritt() { assert_eq!(steps_from_tread(0.29, 3.0), 10.0); diff --git a/src-tauri/core/src/cmd_paste.rs b/src-tauri/core/src/cmd_paste.rs index d7ecdee1..f6923acc 100644 --- a/src-tauri/core/src/cmd_paste.rs +++ b/src-tauri/core/src/cmd_paste.rs @@ -20,7 +20,7 @@ use std::collections::HashMap; /// Listen der Zwischenablage: (Schlüssel in `clip`, Projekt-Liste, id-Präfix, Geschoss-Feld). /// Reihenfolge = Reihenfolge der ids und der Ops (Wände vor Öffnungen). -const LISTS: [(&str, &str, &str, &str); 9] = [ +const LISTS: [(&str, &str, &str, &str); 10] = [ ("walls", "walls", "W", "floorId"), ("drawings", "drawings2d", "dr2d", "levelId"), ("ceilings", "ceilings", "C", "floorId"), @@ -30,6 +30,7 @@ const LISTS: [(&str, &str, &str, &str); 9] = [ ("rooms", "rooms", "RM", "floorId"), ("extrudedSolids", "extrudedSolids", "extrude", "levelId"), ("columns", "columns", "column", "floorId"), + ("trees", "trees", "tree", "floorId"), ]; /// Ops des Einfügens: je Liste ein `add` (leere Listen ohne Op). diff --git a/src-tauri/core/src/cmd_transform.rs b/src-tauri/core/src/cmd_transform.rs index 26e585d8..6f8464ac 100644 --- a/src-tauri/core/src/cmd_transform.rs +++ b/src-tauri/core/src/cmd_transform.rs @@ -272,6 +272,13 @@ fn mv_column(c: &Value, xf: &Xf) -> Value { with_all(c, vec![("position", pt(nb.0, nb.1)), ("rotation", js_num(jsnum::atan2(nt.1 - nb.1, nt.0 - nb.0)))]) } +/// [149] Baum: nur die Stammmitte (die Krone ist rund). +fn mv_tree(t: &Value, xf: &Xf) -> Value { + let (x, y) = xy(field(t, "position").unwrap_or(&Value::Null)); + let n = xf.apply(x, y); + with(t, "position", pt(n.0, n.1)) +} + fn mv_ceiling(c: &Value, xf: &Xf) -> Value { let mut f = vec![("outline", xf.pts(field(c, "outline")))]; if truthy(field(c, "openings")) { @@ -532,6 +539,8 @@ pub struct Sel { pub room_ids: Option>, /// Gewählte Öffnungen ([144]): Wandöffnungen gleiten beim Verschieben entlang ihrer Wand. pub opening_ids: Option>, + /// [149] Gewählte Bäume. + pub tree_ids: Option>, } fn nonempty(s: &Option) -> Option<&str> { @@ -586,6 +595,7 @@ enum Kind { Roof, Stair, Room, + Tree, } /// Dächer nur bei Verschieben/Skalieren (der Umriss ist an die Weltachsen gebunden, der First folgt @@ -620,6 +630,7 @@ fn gather<'a>(root: &'a Map, sel: &Sel, op: &str, ignore_lock: bo } each("stairs", Ids::opt(&sel.stair_ids), Kind::Stair); each("rooms", Ids::opt(&sel.room_ids), Kind::Room); + each("trees", Ids::opt(&sel.tree_ids), Kind::Tree); out } @@ -794,6 +805,10 @@ pub fn transform_result(root: &Map, p: &Project, req: &TransformR if !rooms.is_empty() { patch("rooms", &|r| rooms.has(r) && !locked(r), &|r| mv_room(r, &xf)); } + let trees = Ids::opt(&sel.tree_ids); + if !trees.is_empty() { + patch("trees", &|t| trees.has(t) && !locked(t), &|t| mv_tree(t, &xf)); + } // Öffnungen in bewegten Dächern/Decken ([103]) folgen ihrem Wirt. let hosts: std::collections::HashSet<&str> = items.iter().filter(|(k, _)| matches!(k, Kind::Roof | Kind::Ceiling)).filter_map(|(_, e)| id_of(e)).collect(); @@ -809,7 +824,7 @@ pub fn transform_result(root: &Map, p: &Project, req: &TransformR // Kopien (Kopie/Reihe/Verteilen bzw. gespiegelte Kopie). let mut ids = IdGen::new(&req.stamp); - let mut new: [Vec; 8] = Default::default(); + let mut new: [Vec; 9] = Default::default(); let mut new_openings = Vec::new(); for t in copy_ts(op, &req.mode, req.count.0) { let xf = Xf::of(op, &pts, t); @@ -824,6 +839,7 @@ pub fn transform_result(root: &Map, p: &Project, req: &TransformR Kind::Roof => "RF", Kind::Stair => "ST", Kind::Room => "RM", + Kind::Tree => "tree", }) .collect(); let new_ids: Vec = prefixes.iter().map(|p| ids.next(p)).collect(); @@ -848,6 +864,7 @@ pub fn transform_result(root: &Map, p: &Project, req: &TransformR Kind::Roof => (5, mv_roof(e, &xf)), Kind::Stair => (6, mv_stair(e, &xf, k_at(t))), Kind::Room => (7, mv_room(e, &xf)), + Kind::Tree => (8, mv_tree(e, &xf)), }; new[slot].push(with(&v, "id", Value::String(new_id.clone()))); } @@ -869,7 +886,7 @@ pub fn transform_result(root: &Map, p: &Project, req: &TransformR } } } - let keys = ["walls", "drawings2d", "extrudedSolids", "columns", "ceilings", "roofs", "stairs", "rooms"]; + let keys = ["walls", "drawings2d", "extrudedSolids", "columns", "ceilings", "roofs", "stairs", "rooms", "trees"]; for (key, items) in keys.iter().zip(new) { ops.extend(add(key, items)); } @@ -1177,6 +1194,14 @@ fn item_preview(p: &Project, kind: Kind, e: &Value, xf: &Xf, out: &mut Pending) Kind::Ceiling | Kind::Roof => s.poly(&mapped(&pts_of(field(e, "outline")), xf)), Kind::Room => s.poly(&mapped(&pts_of(field(e, "boundary")), xf)), Kind::Stair => stair_preview(e, xf, s), + Kind::Tree => { + // [149] Kronenkreis um die verschobene Stammmitte. + let (x, y) = pt("position"); + let c = xf.apply(x, y); + let d = field(e, "crownDiameter").and_then(Value::as_f64).filter(|d| *d > 0.0 && d.is_finite()).unwrap_or(crate::tree::DEFAULT_CROWN_DIAMETER); + let ring: Vec<(f64, f64)> = crate::tree::circle([c.0, c.1], d / 2.0, 24).into_iter().map(|q| (q[0], q[1])).collect(); + s.poly(&ring); + } Kind::Drawing => { let at = s.buf.len(); out.drawings.push((at, with_geom(e, mv_geom(field(e, "geom").unwrap_or(&Value::Null), xf)))); @@ -1337,6 +1362,25 @@ mod tests { v.as_object().unwrap().clone() } + /// [149] Bäume: Verschieben (gesperrte bleiben), Kopieren mit neuer id. + #[test] + fn baeume_verschieben_und_kopieren() { + let r = root(json!({"trees":[{"id":"t","position":{"x":1,"y":2},"crownDiameter":5},{"id":"z","position":{"x":0,"y":0},"locked":true}]})); + let run = |mode: &str| { + let req: TransformReq = serde_json::from_value(json!({"sel":{"wallIds":[],"treeIds":["t","z"]},"op":"move","pts":[[0, 0], [3, 1]],"mode":mode,"count":1,"stamp":"s"})).unwrap(); + transform_ops(&r, &Project::default(), &req).iter().map(|o| o.to_json()).collect::>() + }; + let ops = run("move"); + assert_eq!(ops.len(), 1); + assert_eq!(ops[0]["entity"]["position"], json!({"x":4,"y":3})); + assert_eq!(ops[0]["entity"]["crownDiameter"], json!(5)); + let ops = run("copy"); + assert_eq!(ops.len(), 1); + assert_eq!(ops[0]["collection"], "trees"); + assert_eq!(ops[0]["items"][0]["id"], "tree-s-1"); + assert_eq!(ops[0]["items"][0]["position"], json!({"x":4,"y":3})); + } + /// [T2] Bogenwand: Verschieben/Drehen behalten den Bulge, Spiegeln kehrt ihn um. #[test] fn bogenwand_spiegeln_kehrt_bulge() { diff --git a/src-tauri/core/src/explode3d.rs b/src-tauri/core/src/explode3d.rs index 62a95dc3..ada1520f 100644 --- a/src-tauri/core/src/explode3d.rs +++ b/src-tauri/core/src/explode3d.rs @@ -48,6 +48,9 @@ impl<'a> Explode<'a> { for c in p.columns.as_deref().unwrap_or(&[]) { floor_of.insert(&c.id, &c.floor_id); } + for t in p.trees.as_deref().unwrap_or(&[]) { + floor_of.insert(&t.id, &t.floor_id); + } // [137] Freie Körper (Pick, Hervorhebung) folgen ihrem Geschoss. for s in p.extruded_solids.as_deref().unwrap_or(&[]) { floor_of.insert(&s.id, &s.level_id); @@ -151,10 +154,12 @@ pub fn parts(p: &Project, layered: bool, detail: f64, for_section: bool, gap: f6 for (g, dz) in groups { let pick = |fid: &str| ex.in_group(fid, g); q.columns = p.columns.as_ref().map(|v| v.iter().filter(|c| pick(&c.floor_id)).cloned().collect()); + q.trees = p.trees.as_ref().map(|v| v.iter().filter(|t| pick(&t.floor_id)).cloned().collect()); q.stairs = p.stairs.as_ref().map(|v| v.iter().filter(|s| pick(&s.floor_id)).cloned().collect()); q.roofs = p.roofs.as_ref().map(|v| v.iter().filter(|r| pick(&r.floor_id)).cloned().collect()); q.openings = p.openings.as_ref().map(|v| v.iter().filter(|o| pick(ex.floor_of.get(o.id.as_str()).copied().unwrap_or(""))).cloned().collect()); out.column_meshes.extend(shifted(model3d::emit_columns(&q), dz, shift_mesh)); + out.column_meshes.extend(shifted(model3d::emit_trees(&q), dz, shift_mesh)); out.stair_meshes.extend(shifted(model3d::emit_stair_meshes(&q), dz, shift_mesh)); out.stair_railings.extend(shifted(model3d::emit_stair_railings(&q), dz, shift_mesh)); out.roof_meshes.extend(shifted(model3d::emit_roofs(&q, None)?, dz, shift_mesh)); @@ -225,6 +230,12 @@ pub fn pick_geometry(p: &Project, gap: f64) -> Result { v[1] += dz; } } + for t in &mut g.trees { + let dz = ex.of(&t.tree_id); + for v in t.tris.iter_mut().flatten() { + v[1] += dz; + } + } for o in &mut g.opening_meshes { let dz = ex.of(&o.opening_id); for v in o.tris.iter_mut().flatten() { diff --git a/src-tauri/core/src/geo_translate.rs b/src-tauri/core/src/geo_translate.rs index c6f47052..895d8c04 100644 --- a/src-tauri/core/src/geo_translate.rs +++ b/src-tauri/core/src/geo_translate.rs @@ -9,7 +9,7 @@ use serde_json::{json, Map, Value}; /// Projekt-Listen, die verschoben werden (jedes Element hat eine `id`), in Op-Reihenfolge. -pub const TRANSLATED_LISTS: [&str; 10] = ["walls", "ceilings", "roofs", "stairs", "rooms", "columns", "extrudedSolids", "drawings2d", "context", "drawingLevels"]; +pub const TRANSLATED_LISTS: [&str; 11] = ["walls", "ceilings", "roofs", "stairs", "rooms", "columns", "extrudedSolids", "drawings2d", "context", "drawingLevels", "trees"]; fn shift(p: &Value, dx: f64, dy: f64) -> Value { let c = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(f64::NAN); @@ -161,6 +161,7 @@ fn shift_element(key: &str, e: &Value, dx: f64, dy: f64) -> (Value, bool) { set(&mut m, "stampAnchor", c); } "columns" => shift_pts_fields(&mut m, &["position"], dx, dy, &[]), + "trees" => shift_pts_fields(&mut m, &["position"], dx, dy, &[]), "extrudedSolids" => { shift_pts_fields(&mut m, &[], dx, dy, &["points"]); let c = if truthy(e.get("circle")) { diff --git a/src-tauri/core/src/highlight3d.rs b/src-tauri/core/src/highlight3d.rs index 416b99d0..f0b70095 100644 --- a/src-tauri/core/src/highlight3d.rs +++ b/src-tauri/core/src/highlight3d.rs @@ -26,6 +26,8 @@ pub struct Args { /// [137] Stützen und freie Körper (Prisma über dem Grundriss). pub columns: Vec, pub solids: Vec, + /// [149] Bäume (Umriss-Prisma Kronendurchmesser × Fuss bis Spitze). + pub trees: Vec, pub rgb: [f64; 3], /// Explosionsabstand ([65], `explode3d.rs`; fehlt/0 = aus): Linien folgen dem auseinandergezogenen Modell. #[serde(default)] @@ -214,6 +216,17 @@ pub fn selection_highlight_lines(p: &Project, a: &Args) -> Result, Stri lift(&mut out, n, &col.id); } } + let trees = set(&a.trees); + if !trees.is_empty() { + let list = p.trees.as_deref().unwrap_or(&[]); + for (i, g) in crate::tree::geoms(p) { + if trees.contains(list[i].id.as_str()) { + let n = out.v.len(); + out.prism_edges(&crate::tree::circle(g.c, g.crown_r, 12), g.base, g.top); + lift(&mut out, n, &list[i].id); + } + } + } for s in p.extruded_solids.as_deref().unwrap_or(&[]) { if solids.contains(s.id.as_str()) { let z0 = crate::model3d::solid_base_z(p, s); diff --git a/src-tauri/core/src/ifc_data.rs b/src-tauri/core/src/ifc_data.rs index aa75bf5b..cab7417c 100644 --- a/src-tauri/core/src/ifc_data.rs +++ b/src-tauri/core/src/ifc_data.rs @@ -50,6 +50,7 @@ const REC_OPENING_SOLID: f64 = 15.0; const REC_WALL_ARC: f64 = 16.0; const REC_WALL_ARC_SOLID: f64 = 17.0; const REC_GRID: f64 = 18.0; +const REC_TREE: f64 = 19.0; /// Toleranz des Kerns (`wall_bands.rs::EPS`) für „Öffnung trifft Band". const BAND_EPS: f64 = 1e-4; @@ -1354,6 +1355,46 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result } f.num(REC_END_COLUMNS); + // ── Bäume ([149]) → IfcGeographicElement (IFC2x3: IfcBuildingElementProxy), Netz Stamm + Krone ── + let trees = p.trees.as_deref().unwrap_or(&[]); + for (i, g) in crate::tree::geoms(&p) { + let t = &trees[i]; + let structure = structure_of(&t.floor_id); + let base = base_of(structure); + let (mut positions, mut indices) = g.trunk_mesh(8); + let (cp, ci) = g.crown_mesh(8, 12); + let at = (positions.len() / 3) as u32; + positions.extend(cp); + indices.extend(ci.iter().map(|k| at + k)); + for z in positions.iter_mut().skip(2).step_by(3) { + *z -= base; + } + let status = match t.status { + TreeStatus::New => "new", + TreeStatus::Remove => "remove", + _ => "existing", + }; + let mut props = vec![ident("Status", status), ident("Foliage", if t.foliage == TreeFoliage::Conifer { "conifer" } else { "deciduous" })]; + if let Some(sp) = t.species.as_deref().map(str::trim).filter(|s| !s.is_empty()) { + props.push(Prop::Label("Species", sp.to_string())); + } + let mut psets = vec![Pset { name: "Dossier_Tree", props }]; + psets.extend(qto( + "Dossier_Qto_Tree", + vec![ + Qty { name: "Height", kind: QtyKind::Length, value: g.top - g.base }, + Qty { name: "CrownDiameter", kind: QtyKind::Length, value: 2.0 * g.crown_r }, + Qty { name: "TrunkDiameter", kind: QtyKind::Length, value: 2.0 * g.trunk_r }, + Qty { name: "CrownBaseHeight", kind: QtyKind::Length, value: g.crown_bottom - g.base }, + ], + )); + let (id, name) = (f.str(&t.id), f.str(&crate::tree::label(t))); + f.nums(&[REC_TREE, structure, id, name]); + w_psets(&mut f, &psets); + // Zwei getrennte geschlossene Körper: nicht als ein dichtes Netz melden (IFC2x3: Flächenmodell). + w_mesh(&mut f, &positions, &indices, false); + } + // ── Achsraster ([112]) → IfcGrid (U-/V-Achsen als Linienzüge in Welt-XY) ── for d in &p.drawings2d { let Some(spec) = crate::grid::Spec::of(&d.geom) else { continue }; @@ -1475,6 +1516,24 @@ mod tests { text.split('\0').map(String::from).collect() } + /// [149] Baum als eigener Datensatz (nach den Stützen): Name = Art, Netz Stamm + Krone relativ zur + /// Geschoss-UK, Höhe als Menge. + #[test] + fn baum_datensatz() { + let mut p = sample(); + let floor = p.drawing_levels.iter().find(|l| l.kind == DrawingLevelKind::Floor).unwrap().id.clone(); + let mut t = Tree { id: "T1".into(), r#type: "tree".into(), floor_id: "eg".into(), category_code: "13".into(), position: Vec2 { x: 20.0, y: 5.0 }, trunk_diameter: 0.4, crown_diameter: 6.0, crown_base: 3.0, height: 12.0, species: Some("Quercus robur".into()), ..Default::default() }; + t.floor_id = floor; + p.trees = Some(vec![t]); + let f = ifc_export_data(&p, &IfcOptions::default()).unwrap(); + let s = strings(&f); + assert!(s.iter().any(|x| x == "T1") && s.iter().any(|x| x == "Quercus robur") && s.iter().any(|x| x == "Dossier_Qto_Tree")); + assert!(f.nums.windows(2).any(|w| w == [REC_END_COLUMNS, REC_TREE]), "Baum direkt nach den Stützen"); + // Ohne Bäume kein Datensatz. + p.trees = None; + assert!(!strings(&ifc_export_data(&p, &IfcOptions::default()).unwrap()).iter().any(|x| x == "Dossier_Qto_Tree")); + } + /// [G3]/[103] Formöffnung und Dachfenster als Öffnungskörper-Datensatz mit Wirt. #[test] fn formoeffnung_und_dachfenster() { diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 36b39197..2fd0db80 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -17,6 +17,7 @@ pub mod roof; pub mod roof_skeleton; pub mod flat_read; pub mod sun; +pub mod tree; pub mod site_rules; pub mod auto_dimensions; pub mod kennzahlen; diff --git a/src-tauri/core/src/mesh_data.rs b/src-tauri/core/src/mesh_data.rs index 563a8524..51065a59 100644 --- a/src-tauri/core/src/mesh_data.rs +++ b/src-tauri/core/src/mesh_data.rs @@ -438,6 +438,15 @@ pub fn mesh_export_data(src: &Project, opt: &MeshOptions) -> Result, + /// Stammmitte im Grundriss (Meter). + pub position: Vec2, + /// Stammdurchmesser (m, > 0). + #[serde(rename = "trunkDiameter")] + pub trunk_diameter: f64, + /// Kronendurchmesser (m, > 0). + #[serde(rename = "crownDiameter")] + pub crown_diameter: f64, + /// Höhe des Kronenansatzes über dem Fuss (m, ≥ 0, < `height`). + #[serde(rename = "crownBase")] + pub crown_base: f64, + /// Gesamthöhe über dem Fuss (m, > 0). + pub height: f64, + /// Kronenform. + pub shape: TreeShape, + /// Bestehend / neu / zu fällen. + pub status: TreeStatus, + /// Laub- oder Nadelbaum. + pub foliage: TreeFoliage, + /// Optionaler Art-Name (z. B. „Quercus robur"), erscheint als Beschriftung im Grundriss. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub species: Option, + /// Höhenversatz des Fusses gegenüber Gelände bzw. Geschoss-UK (m, Vorgabe 0). + #[serde(rename = "baseOffset", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub base_offset: Option, + /// Optionale Übersteuerung der Strichfarbe; sonst gilt die Kategorie-Farbe bzw. die Bestandsfarbe. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub color: Option, + #[serde(flatten)] + #[ts(skip)] + pub extra: Extra, +} + /// Gruppe (Vectorworks-artig) — reine Mitgliedschaft je Elementart, siehe /// {@link Project.groups}. Alle ID-Listen sind additiv; ein Element gehört /// NIE zu mehr als einer Gruppe auf derselben Ebene (das Werkzeug/der Befehl @@ -4892,6 +4999,11 @@ pub struct Project { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub columns: Option>, + /// Bäume ([149]) — eigene Objekte mit Stamm, Krone und Höhe, siehe {@link Tree}. Optional, damit + /// bestehende Projekte ohne `trees` gültig bleiben (Default: leer behandeln). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub trees: Option>, /// Gruppen (Vectorworks-artig: Cmd+G fasst die Auswahl zu einer Einheit /// zusammen; Doppelklick betritt die Gruppe zum Bearbeiten, alles andere /// wird dabei gedimmt/gesperrt — s. `state/useGroupState.ts`). Eine Gruppe @@ -5729,6 +5841,12 @@ impl Project { None => Default::default(), }; } + "trees" => { + self.trees = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } "groups" => { self.groups = match v { Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, diff --git a/src-tauri/core/src/model/items.rs b/src-tauri/core/src/model/items.rs index 3b47353a..9041744f 100644 --- a/src-tauri/core/src/model/items.rs +++ b/src-tauri/core/src/model/items.rs @@ -36,6 +36,7 @@ impl Project { "context" => put_opt(&mut self.context, i, v), "extrudedSolids" => put_opt(&mut self.extruded_solids, i, v), "columns" => put_opt(&mut self.columns, i, v), + "trees" => put_opt(&mut self.trees, i, v), "groups" => put_opt(&mut self.groups, i, v), "layouts" => put_opt(&mut self.layouts, i, v), _ => Ok(false), diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index dac14448..9469c968 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -313,6 +313,36 @@ pub fn emit_columns(p: &Project) -> Vec { out } +/// [149] Bäume als Meshes: je Baum Stamm (Zylinder, 8 Seiten) und Krone (Rotationskörper, 8 Ringe × 12 +/// Seiten; Form nach `shape`), Fuss auf dem Gelände (`tree::bases`). Im 3D bei den Stützen eingereiht. +pub fn emit_trees(p: &Project) -> Vec { + let mut out = Vec::new(); + let trees = p.trees.as_deref().unwrap_or(&[]); + for (i, g) in crate::tree::geoms(p) { + let (trunk_rgb, crown_rgb) = crate::tree::colors(&trees[i]); + let (positions, indices) = g.trunk_mesh(8); + out.push(RMesh { crease_angle: None, positions, indices, kind: "extrusion", color: trunk_rgb, vertex_colors: None, material_index: None }); + let (positions, indices) = g.crown_mesh(8, 12); + out.push(RMesh { crease_angle: None, positions, indices, kind: "extrusion", color: crown_rgb, vertex_colors: None, material_index: None }); + } + out +} + +/// [149] Bäume als Welt-Dreiecke (Stamm + Krone, wie [`emit_trees`]) für den 3D-Pick. +pub fn pick_trees(p: &Project) -> Vec { + let trees = p.trees.as_deref().unwrap_or(&[]); + crate::tree::geoms(p) + .into_iter() + .map(|(i, g)| { + let (tp, ti) = g.trunk_mesh(8); + let (cp, ci) = g.crown_mesh(8, 12); + let mut tris = extrusion_tris(&tp, &ti); + tris.extend(extrusion_tris(&cp, &ci)); + PickTree { tris, tree_id: trees[i].id.clone() } + }) + .collect() +} + // ── Wände ─────────────────────────────────────────────────────────────────── use crate::joins::{self, JoinLayer, JoinWall, Reference, WallCuts}; @@ -2378,7 +2408,7 @@ pub fn parts(p: &Project, layered: bool, detail: f64, for_section: bool) -> Resu walls: emit_walls(p, layered)?, slabs, context_meshes: emit_context_meshes(p), - column_meshes: emit_columns(p), + column_meshes: { let mut m = emit_columns(p); m.extend(emit_trees(p)); m }, opening_meshes: emit_opening_meshes(p, detail), stair_meshes: emit_stair_meshes(p), stair_railings: emit_stair_railings(p), @@ -2537,6 +2567,14 @@ pub struct PickColumn { pub column_id: String, } +/// [149] Baum für den 3D-Pick. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PickTree { + pub tris: Vec, + pub tree_id: String, +} + /// [137] Öffnung ohne Wand (Dach, Decke, Gaube) für den 3D-Pick: Welt-Dreiecke ihrer Teile. #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] @@ -2594,6 +2632,8 @@ pub struct PickGeometry { /// [137] Kreise, Bögen, Ellipsen und Texte als flache Pick-Flächen. #[serde(rename = "drawingMeshes")] pub drawing_meshes: Vec, + /// [149] Bäume (Stamm + Krone). + pub trees: Vec, } /// Öffnungen als Quader (Laibung zu Laibung, Wanddicke, Brüstung bis Sturz) für Pick und Hervorhebung. @@ -2747,6 +2787,7 @@ pub fn pick_geometry(p: &Project) -> Result { drawings: pick_drawing_segs(p, &HashMap::new()), stair_meshes: pick_stair_railings(p), drawing_meshes: pick_drawing_meshes(p, &HashMap::new()), + trees: pick_trees(p), }) } @@ -2900,6 +2941,32 @@ fn pick_columns(p: &Project) -> Vec { mod tests { use super::*; + /// [149] Bäume im 3D (Stamm + Krone bei den Stützen-Meshes), im Pick und mit Fuss auf dem Gelände. + #[test] + fn baeume_im_3d_und_pick() { + let mut p = sample(); + let n0 = parts(&p, true, 1.0, false).unwrap().column_meshes.len(); + p.trees = Some(vec![Tree { id: "T1".into(), r#type: "tree".into(), floor_id: "eg".into(), category_code: "13".into(), position: Vec2 { x: 20.0, y: 5.0 }, trunk_diameter: 0.4, crown_diameter: 6.0, crown_base: 3.0, height: 12.0, species: Some("Quercus robur".into()), ..Default::default() }, Tree { id: "T2".into(), shape: TreeShape::Conical, foliage: TreeFoliage::Conifer, base_offset: Some(0.5), ..Tree { id: "T1".into(), r#type: "tree".into(), floor_id: "eg".into(), category_code: "13".into(), position: Vec2 { x: 20.0, y: 5.0 }, trunk_diameter: 0.4, crown_diameter: 6.0, crown_base: 3.0, height: 12.0, species: Some("Quercus robur".into()), ..Default::default() } }]); + let m = parts(&p, true, 1.0, false).unwrap().column_meshes; + assert_eq!(m.len(), n0 + 4); + let crown = &m[n0 + 1]; + assert_eq!(crown.color, crate::tree::CROWN_RGB); + assert_eq!(m[n0 + 3].color, crate::tree::CONIFER_RGB); + let zmax = crown.positions.chunks_exact(3).map(|q| q[2]).fold(f64::NEG_INFINITY, f64::max); + let base = p.floor("eg").map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)); + assert!((zmax - (base + 12.0)).abs() < 1e-9, "{zmax}"); + let z2 = m[n0 + 2].positions.chunks_exact(3).map(|q| q[2]).fold(f64::INFINITY, f64::min); + assert!((z2 - (base + 0.5)).abs() < 1e-9, "Fuss mit Versatz: {z2}"); + // Wenige Dreiecke je Baum. + assert!(m[n0..].iter().map(|x| x.indices.len() / 3).sum::() < 2 * 250); + let g = pick_geometry(&p).unwrap(); + assert_eq!(g.trees.len(), 2); + assert_eq!(g.trees[0].tree_id, "T1"); + // Welt-Dreiecke (x, Höhe, y): Höhe bis zur Spitze. + let h = g.trees[0].tris.iter().flatten().map(|v| v[1]).fold(f64::NEG_INFINITY, f64::max); + assert!((h - (base + 12.0)).abs() < 1e-9); + } + /// [112] Achsraster mit `show3d` erscheint als Boden-Spur (eine Strecke je Achse), ohne Flag nicht. #[test] fn achsraster_im_3d_nur_mit_flag() { diff --git a/src-tauri/core/src/model3d_cache.rs b/src-tauri/core/src/model3d_cache.rs index 9140b045..81d17286 100644 --- a/src-tauri/core/src/model3d_cache.rs +++ b/src-tauri/core/src/model3d_cache.rs @@ -240,7 +240,7 @@ impl Model3dCache { walls: Vec::new(), slabs, context_meshes: model3d::emit_context_meshes(p), - column_meshes: model3d::emit_columns(p), + column_meshes: { let mut m = model3d::emit_columns(p); m.extend(model3d::emit_trees(p)); m }, opening_meshes: Vec::new(), stair_meshes: model3d::emit_stair_meshes(p), stair_railings: model3d::emit_stair_railings(p), diff --git a/src-tauri/core/src/plan/cache.rs b/src-tauri/core/src/plan/cache.rs index 68e7bb4d..579258bc 100644 --- a/src-tauri/core/src/plan/cache.rs +++ b/src-tauri/core/src/plan/cache.rs @@ -29,6 +29,7 @@ pub const NOT_FOR_DRAWINGS: &[&str] = &[ "stairs", "rooms", "columns", + "trees", "extrudedSolids", "context", "groups", diff --git a/src-tauri/core/src/plan/domains.rs b/src-tauri/core/src/plan/domains.rs index c62a095b..ebc71a42 100644 --- a/src-tauri/core/src/plan/domains.rs +++ b/src-tauri/core/src/plan/domains.rs @@ -1095,6 +1095,8 @@ fn domains_before(c: &Ctx, out: &mut DomainPrims, bounds: &mut Bounds) -> Result super::walls::plan_walls(c, c.a.reference_lines, &mut out.walls, bounds)?; super::stairs::plan_stairs(c, &mut out.stairs, bounds); columns(c, &mut out.columns); + // [149] Bäume (Planzeichen) mit den Stützen in einer Gruppe. + super::trees::plan_trees(c, &mut out.columns); solids(c, &mut out.solids); Ok(()) } diff --git a/src-tauri/core/src/plan/elevation.rs b/src-tauri/core/src/plan/elevation.rs index 5477ffab..36cd2ffd 100644 --- a/src-tauri/core/src/plan/elevation.rs +++ b/src-tauri/core/src/plan/elevation.rs @@ -1481,6 +1481,17 @@ pub fn elevation_primitives_with(p: &Project, level: &LevelSpec, shadows: bool, }; pending.push(Pending::Item { depth: f.depth, rank: Some(rank), prim }); } + // [149] Bäume: Silhouette (Krone gefüllt, Stamm) in der Maler-Reihenfolge; Bauteile davor verdecken sie. + for (depth, tree) in super::trees::view_trees(p, level, vis, Some(super::trees::view_crown_fill(mono))) { + for prim in tree { + if let Primitive::Polygon { pts, .. } = &prim { + for q in pts { + acc.add(q.x, q.y); + } + } + pending.push(Pending::Item { depth, rank: None, prim }); + } + } // Kanten exakt ([G4]): Umriss, Knicke und Silhouetten der Flächen, verdeckt durch Flächen und // Öffnungen davor; Facetten-Fugen der Bogenwände ([T2]) fallen über die Glättungsgruppe weg. let edges = elevation_edges(p, &faces, &openings, &frame, level.hidden_lines); diff --git a/src-tauri/core/src/plan/mod.rs b/src-tauri/core/src/plan/mod.rs index 83766875..53ef1da9 100644 --- a/src-tauri/core/src/plan/mod.rs +++ b/src-tauri/core/src/plan/mod.rs @@ -34,6 +34,7 @@ pub mod sketch; pub mod ceiling_plan; pub mod line_ends; pub mod stamp_place; +pub mod trees; pub(crate) mod wall_columns; #[cfg(test)] pub(crate) mod wall_join_tests; diff --git a/src-tauri/core/src/plan/section.rs b/src-tauri/core/src/plan/section.rs index 9d294acd..1a28ffe7 100644 --- a/src-tauri/core/src/plan/section.rs +++ b/src-tauri/core/src/plan/section.rs @@ -3282,6 +3282,12 @@ pub fn section_plan_buf(p: &Project, args: &[f64], text: &str) -> Result w.post = super::extras::sketch_post(Some(level.sketch), scale); // Strichstärken nach Massstab ([32]) wie im Grundriss. super::extras::scale_line_weights(p, scale, &mut prims); + // [149] Bäume hinter der Schnittebene: transparente Silhouette unter dem Schnitt (Bauteile verdecken sie). + let mut trees: Vec = super::trees::view_trees(p, &level, &vis, None).into_iter().flat_map(|(_, t)| t).collect(); + let bounds = super::trees::union_bounds(bounds, &trees); + super::extras::scale_line_weights(p, scale, &mut trees); + trees.extend(prims); + let prims = trees; w.group(&prims); let mut ops = if openings { section_opening_primitives(p, &level, &vis)? } else { Vec::new() }; super::extras::scale_line_weights(p, scale, &mut ops); diff --git a/src-tauri/core/src/plan/trees.rs b/src-tauri/core/src/plan/trees.rs new file mode 100644 index 00000000..9f2640c3 --- /dev/null +++ b/src-tauri/core/src/plan/trees.rs @@ -0,0 +1,292 @@ +//! [149] Bäume im Grundriss (Situation) und in Schnitt/Ansicht. Geometrie aus `crate::tree`. +//! +//! Grundriss (Tusche, übliche Plankonvention): Kronenumriss als Planzeichen — Laubbaum mit Wellenkranz, +//! Nadelbaum mit Zackenkranz —, Stamm als Kreis in Stammdicke. **Bestehend**: Strich in der Ebenenfarbe +//! (sonst Tusche), Stamm gefüllt. **Neu**: rot (Planungsfarbe), Stamm offen. **Zu fällen**: gelb, Krone +//! gestrichelt und durchgekreuzt (das Kreuz trägt die Aussage auch im Schwarz-Weiss-Druck). Eine eigene +//! Farbe (`color`) übersteuert. Pick: unsichtbare Kronenfläche mit `contextObjectId = "@tree:"`. +//! +//! Schnitt/Ansicht: vereinfachte Silhouette nach Form (Kronenprofil gespiegelt) und Stamm. + +use super::domains::Ctx; +use super::prim::Primitive; +use super::section::{LevelSpec, Visibility}; +use super::style::{no_hatch, MONO_INK}; +use crate::model::*; +use crate::tree::{TreeGeom, TREE_PICK_PREFIX}; + +/// Planungsfarbe „neu" und Abbruchfarbe „zu fällen". +pub const NEW_COLOR: &str = "#c8102e"; +pub const REMOVE_COLOR: &str = "#d4a017"; +const CROWN_MM: f64 = 0.18; +const TRUNK_MM: f64 = 0.25; +const REMOVE_DASH: [f64; 2] = [1.5, 1.0]; +/// Strich der Silhouette in Schnitt/Ansicht. +const VIEW_INK: &str = "#2b3039"; +const VIEW_CROWN_MM: f64 = 0.18; +const VIEW_TRUNK_MM: f64 = 0.13; +/// Füllung der Krone in der farbigen Ansicht (Tusche: weiss). +const VIEW_CROWN_FILL: &str = "#e3ead9"; +/// Füllung des Stamms in der farbigen Ansicht. +const VIEW_TRUNK_FILL: &str = "#d8cbb8"; + +fn v(x: f64, y: f64) -> Vec2 { + Vec2 { x, y } +} + +/// Pick-Id eines Baums (Feld `contextObjectId`). +pub fn pick_id(id: &str) -> String { + format!("{TREE_PICK_PREFIX}{id}") +} + +fn poly(pts: Vec, fill: &str, stroke: &str, w: f64, pick: Option, greyed: Option) -> Primitive { + Primitive::Polygon { + pts, + fill: fill.into(), + stroke: stroke.into(), + stroke_width_mm: w, + hatch: no_hatch(), + greyed, + opacity: None, + no_stroke_edges: None, + wall_id: None, + drawing_id: None, + ceiling_id: None, + opening_id: None, + stair_id: None, + room_id: None, + extruded_solid_id: None, + context_object_id: pick, + column_id: None, + roof_id: None, + section_line_id: None, + } +} + +fn line(a: Vec2, b: Vec2, cls: &str, w: f64, color: &str, dash: Option<&[f64]>, greyed: Option) -> Primitive { + Primitive::Line { + a, + b, + cls: cls.into(), + weight_mm: w, + dash: dash.map(|d| Some(d.to_vec())), + zigzag: None, + motif: None, + color: Some(color.into()), + drawing_id: None, + opening_id: None, + stair_id: None, + greyed, + opacity: None, + } +} + +/// Kronenumriss im Grundriss: Wellenkranz (Laub) bzw. Zackenkranz (Nadel) um `c` mit Radius `r`. +pub fn crown_outline(c: [f64; 2], r: f64, foliage: TreeFoliage) -> Vec<[f64; 2]> { + // Etwa ein Bogen je 0.9 m Umfang, 7 bis 28. + let n = ((std::f64::consts::TAU * r / 0.9).round() as usize).clamp(7, 28); + let tau = std::f64::consts::TAU; + let at = |t: f64, rr: f64| [c[0] + rr * crate::jsnum::cos(t), c[1] + rr * crate::jsnum::sin(t)]; + if foliage == TreeFoliage::Conifer { + (0..2 * n).map(|i| at(i as f64 / (2 * n) as f64 * tau, if i % 2 == 0 { r } else { 0.8 * r })).collect() + } else { + let k = 6; + (0..n * k) + .map(|i| { + let t = i as f64 / (n * k) as f64 * tau; + let s = crate::jsnum::sin(t * n as f64 / 2.0).abs(); + at(t, r * (0.88 + 0.12 * s)) + }) + .collect() + } +} + +/// Strichfarbe eines Baums im Grundriss. +fn ink(t: &Tree, cat: Option<&LayerCategory>) -> String { + if let Some(c) = t.color.as_deref().filter(|c| !c.is_empty()) { + return c.to_string(); + } + match t.status { + TreeStatus::New => NEW_COLOR.into(), + TreeStatus::Remove => REMOVE_COLOR.into(), + _ => cat.map(|k| k.color.as_str()).filter(|c| !c.is_empty()).unwrap_or(MONO_INK).to_string(), + } +} + +/// Baum-Symbole des Grundrisses (Bäume dieses Geschosses mit sichtbarer Ebene). +pub(super) fn plan_trees(c: &Ctx, out: &mut Vec) { + let p = c.p; + let Some(trees) = p.trees.as_deref() else { return }; + if trees.iter().all(|t| t.floor_id != c.a.floor) { + return; + } + for (i, g) in crate::tree::geoms(p) { + let t = &trees[i]; + if t.floor_id != c.a.floor || !c.vis(&t.category_code, &t.id) { + continue; + } + out.extend(tree_symbol(t, &g, c.cat(&t.category_code), Some(c.greyed(&t.category_code)))); + } +} + +/// Planzeichen eines Baums (Grundriss): Pick-Fläche, Kronenumriss, Stamm, ggf. Kreuz. +pub fn tree_symbol(t: &Tree, g: &TreeGeom, cat: Option<&LayerCategory>, greyed: Option) -> Vec { + let color = ink(t, cat); + let ring = crown_outline(g.c, g.crown_r, t.foliage); + let pts: Vec = ring.iter().map(|q| v(q[0], q[1])).collect(); + let mut out = vec![poly(pts.clone(), "none", "none", 0.0, Some(pick_id(&t.id)), greyed)]; + let remove = t.status == TreeStatus::Remove; + let dash = remove.then_some(&REMOVE_DASH[..]); + for k in 0..pts.len() { + out.push(line(pts[k], pts[(k + 1) % pts.len()], "tree-crown", CROWN_MM, &color, dash, greyed)); + } + let trunk: Vec = crate::tree::circle(g.c, g.trunk_r, 16).into_iter().map(|q| v(q[0], q[1])).collect(); + let fill = if t.status == TreeStatus::New { "#ffffff".to_string() } else { color.clone() }; + out.push(poly(trunk, &fill, &color, TRUNK_MM, None, greyed)); + if remove { + let d = g.crown_r * 0.9 * std::f64::consts::FRAC_1_SQRT_2; + let (x, y) = (g.c[0], g.c[1]); + out.push(line(v(x - d, y - d), v(x + d, y + d), "tree-remove", CROWN_MM, &color, None, greyed)); + out.push(line(v(x - d, y + d), v(x + d, y - d), "tree-remove", CROWN_MM, &color, None, greyed)); + } + out +} + +/// Bäume in Schnitt/Ansicht: je Baum (Tiefe der Stammmitte, Silhouette: Krone + Stamm). Nur Bäume vor der +/// Blickrichtung (Mitte höchstens einen Kronenradius vor der Ebene) und innerhalb der Ansichtstiefe. +/// `fill`: Kronenfüllung (`None` = transparent). +pub fn view_trees(p: &Project, level: &LevelSpec, vis: &Visibility, fill: Option<&str>) -> Vec<(f64, Vec)> { + let Some(trees) = p.trees.as_deref().filter(|t| !t.is_empty()) else { return vec![] }; + let Some(plane) = level.plane() else { return vec![] }; + let [nx, _, nz] = plane.normal; + let nl = nx.hypot(nz); + if !(nl > 0.0) { + return vec![]; + } + // Welt (x, Höhe, y): Ebene durch (p0.x, ·, p0.y); u = Blick-Rechts wie `elevation::frame_of`. + let (nx, nz) = (nx / nl, nz / nl); + let (ux, uz) = (nz, -nx); + let (px, pz) = (plane.point[0], plane.point[2]); + let mut out = Vec::new(); + for (i, g) in crate::tree::geoms(p) { + let t = &trees[i]; + if vis.has_vis && !vis.visible(&t.category_code) || vis.has_display && !vis.render(&t.category_code) { + continue; + } + let (rx, rz) = (g.c[0] - px, g.c[1] - pz); + let depth = rx * nx + rz * nz; + if depth < -g.crown_r || level.depth.is_some_and(|d| d > 0.0 && depth - g.crown_r > d) { + continue; + } + let s = rx * ux + rz * uz; + let (crown, trunk) = g.silhouette(s, 24); + let greyed = Some(vis.has_display && vis.greyed(&t.category_code)); + let pick = Some(pick_id(&t.id)); + let to = |r: &[[f64; 2]]| r.iter().map(|q| v(q[0], q[1])).collect::>(); + let stroke = t.color.as_deref().filter(|c| !c.is_empty()).unwrap_or(VIEW_INK); + let trunk_fill = fill.map(|f| if f == "#ffffff" { f } else { VIEW_TRUNK_FILL }); + let prims = vec![ + poly(to(&trunk), trunk_fill.unwrap_or("none"), stroke, VIEW_TRUNK_MM, pick.clone(), greyed), + poly(to(&crown), fill.unwrap_or("none"), stroke, VIEW_CROWN_MM, pick, greyed), + ]; + out.push((depth, prims)); + } + out +} + +/// Ausmass `bounds` vereinigt mit den Polygon-Ecken von `prims` (Silhouetten in Schnitt/Ansicht). +pub fn union_bounds(bounds: [f64; 4], prims: &[Primitive]) -> [f64; 4] { + let mut b = bounds; + for q in prims { + if let Primitive::Polygon { pts, .. } = q { + for v in pts.iter().filter(|v| v.x.is_finite() && v.y.is_finite()) { + b = [b[0].min(v.x), b[1].min(v.y), b[2].max(v.x), b[3].max(v.y)]; + } + } + } + b +} + +/// Füllung der Krone in der Ansicht. +pub fn view_crown_fill(mono: bool) -> &'static str { + if mono { + "#ffffff" + } else { + VIEW_CROWN_FILL + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plan::domains::{plan_domains, PlanArgs}; + + fn project(trees: serde_json::Value) -> Project { + serde_json::from_value(serde_json::json!({ + "id": "p", "name": "P", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], + "drawingLevels": [ + {"id": "eg", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "cutHeight": 1.0, "baseElevation": 0}, + {"id": "an", "name": "Ansicht Süd", "kind": "elevation", "visible": true, "locked": false, "floorHeight": 3.0, "linePoints": [{"x": -20, "y": -10}, {"x": 20, "y": -10}]} + ], + "layers": [{"code": "13", "name": "Bäume", "color": "#000000", "lw": 0.13, "visible": true, "locked": false}], + "walls": [], "openings": [], "drawings2d": [], "trees": trees + })) + .unwrap() + } + + fn tree(id: &str, x: f64, status: &str, foliage: &str) -> serde_json::Value { + serde_json::json!({"id": id, "type": "tree", "floorId": "eg", "categoryCode": "13", "position": {"x": x, "y": 0}, + "trunkDiameter": 0.4, "crownDiameter": 6, "crownBase": 3, "height": 12, "shape": "round", "status": status, "foliage": foliage}) + } + + fn plan(p: &Project, codes: &[&str]) -> Vec { + let text = serde_json::json!({"floor": "eg", "show": codes, "global": true}).to_string(); + let a = PlanArgs::parse(1.0, &text).unwrap(); + plan_domains(p, &a).unwrap().columns + } + + #[test] + fn planzeichen_nach_bestand_und_laub() { + let p = project(serde_json::json!([tree("a", 0.0, "existing", "deciduous"), tree("b", 10.0, "new", "conifer"), tree("c", 20.0, "remove", "deciduous")])); + let prims = plan(&p, &["13"]); + let pick = |id: &str| prims.iter().filter(|q| matches!(q, Primitive::Polygon { context_object_id: Some(c), .. } if *c == pick_id(id))).count(); + assert_eq!((pick("a"), pick("b"), pick("c")), (1, 1, 1)); + let lines = |color: &str, dashed: bool| prims.iter().filter(|q| matches!(q, Primitive::Line { color: Some(c), dash, .. } if c == color && dash.is_some() == dashed)).count(); + // Bestehend: Tusche, durchgezogen; neu: rot; zu fällen: gelb, gestrichelt + 2 Kreuzlinien. + assert!(lines("#000000", false) > 20); + assert!(lines(NEW_COLOR, false) > 10); + assert!(lines(REMOVE_COLOR, true) > 20 && lines(REMOVE_COLOR, false) == 2); + // Stamm: gefüllt (bestehend) bzw. weiss (neu). + let trunk_fill = |color: &str| prims.iter().filter(|q| matches!(q, Primitive::Polygon { fill, stroke, .. } if stroke == color && fill != "none")).map(|q| if let Primitive::Polygon { fill, .. } = q { fill.clone() } else { String::new() }).collect::>(); + assert_eq!(trunk_fill("#000000"), vec!["#000000".to_string()]); + assert_eq!(trunk_fill(NEW_COLOR), vec!["#ffffff".to_string()]); + // Kronenumriss im Kronenradius (Wellenkranz zwischen 0.88 r und r). + if let Some(Primitive::Polygon { pts, .. }) = prims.iter().find(|q| matches!(q, Primitive::Polygon { context_object_id: Some(c), .. } if *c == pick_id("a"))) { + let r: Vec = pts.iter().map(|q| q.x.hypot(q.y)).collect(); + assert!(r.iter().all(|&x| x <= 3.0 + 1e-9 && x >= 0.88 * 3.0 - 1e-9)); + } + // Ausgeblendete Ebene: nichts. + assert!(plan(&p, &["20"]).is_empty()); + } + + #[test] + fn silhouette_in_der_ansicht() { + let p = project(serde_json::json!([tree("a", 0.0, "existing", "deciduous"), tree("hinten", 5.0, "existing", "deciduous")])); + let l = p.drawing_levels.iter().find(|l| l.id == "an").unwrap(); + let level = LevelSpec::from_json(&serde_json::to_value(l).unwrap()); + let (prims, _) = crate::plan::elevation::elevation_primitives(&p, &level, false, true, &Visibility::default(), 100.0).unwrap().unwrap(); + let crowns: Vec<&Primitive> = prims.iter().filter(|q| matches!(q, Primitive::Polygon { context_object_id: Some(c), pts, .. } if *c == pick_id("a") && pts.len() > 4)).collect(); + assert_eq!(crowns.len(), 1); + if let Primitive::Polygon { pts, .. } = crowns[0] { + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + let (mut zl, mut zh) = (f64::INFINITY, f64::NEG_INFINITY); + for q in pts { + lo = lo.min(q.x); + hi = hi.max(q.x); + zl = zl.min(q.y); + zh = zh.max(q.y); + } + assert!((hi - lo - 6.0).abs() < 1e-6 && (zl - 3.0).abs() < 1e-9 && (zh - 12.0).abs() < 1e-9, "{lo} {hi} {zl} {zh}"); + } + } +} diff --git a/src-tauri/core/src/project_format.rs b/src-tauri/core/src/project_format.rs index 740e7ebb..5d43334b 100644 --- a/src-tauri/core/src/project_format.rs +++ b/src-tauri/core/src/project_format.rs @@ -15,7 +15,7 @@ const REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"]; const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"]; /// Bekannte Felder von `Project` (für die Meldung unbekannter Felder). -const KNOWN_KEYS: [&str; 53] = [ +const KNOWN_KEYS: [&str; 54] = [ "formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes", "ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens", "penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers", @@ -23,7 +23,7 @@ const KNOWN_KEYS: [&str; 53] = [ "extrudedSolids", "columns", "groups", "parametricWalls", "overrideRules", "viewSnapshots", "viewSnapshotFolders", "viewTemplates", "layouts", "masterLayouts", "layoutFolders", "publishSets", "publishLog", "projectNumber", "referenceElevationMasl", "geoAnchor", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights", - "lineCap", "lineJoin", + "lineCap", "lineJoin", "trees", ]; /// Ergebnis des Einlesens. diff --git a/src-tauri/core/src/sun.rs b/src-tauri/core/src/sun.rs index 8d23da15..ea5fca9a 100644 --- a/src-tauri/core/src/sun.rs +++ b/src-tauri/core/src/sun.rs @@ -917,6 +917,11 @@ fn collect(p: &Project, k: [f64; 2], cut: Option, ground: Option<&Ground>) clouds.push(crown); } } + // [149] Bäume als eigene Objekte: Stamm (Prisma) + Krone (Punktwolke) nach eigener Höhe, Krone und Form. + for (_, g) in crate::tree::geoms(p) { + prisms.push((Prism { footprint: g.trunk_ring(8), z_bottom: g.base, z_top: g.trunk_top() }, vec![])); + clouds.push(g.crown_points()); + } // Nur zur Sonne gewandte Dachflächen (Aussennormale): durch sie verlässt jeder Strahl den Körper. roof_faces.retain(|f| f.first().is_some_and(|r| { let n = newell(r); @@ -1312,4 +1317,31 @@ mod terrain_tests { })); assert!(shadow_polygons_project(&p4, sun, None).is_empty()); } + + /// [149] Baum-Objekt: Schattenlänge nach eigener Höhe und Krone (nicht `sunStudy.treeHeight`), Form zählt. + #[test] + fn baum_objekt_schatten_nach_hoehe() { + let sun = SunPosition { azimuth: 180.0, elevation: 45.0 }; + let mk = |h: f64, d: f64, shape: &str| { + project_json(serde_json::json!({ + "sunStudy": {"when": "2026-06-21T10:00:00Z", "show": true, "treeHeight": 30.0}, + "trees": [{"id": "t", "type": "tree", "floorId": "eg", "categoryCode": "13", "position": {"x": 0, "y": 0}, + "trunkDiameter": 0.4, "crownDiameter": d, "crownBase": 2.0, "height": h, "shape": shape, + "status": "existing", "foliage": "deciduous"}] + })) + }; + // 45°: Spitze (Kegel) wirft bis y = h, Kronenbreite ±r. + let b = bbox(&shadow_polygons_project(&mk(12.0, 4.0, "conical"), sun, None)); + assert!((b[3] - 12.0).abs() < 0.05 && (b[2] - 2.0).abs() < 0.05 && b[1] > -0.3, "{b:?}"); + let b6 = bbox(&shadow_polygons_project(&mk(6.0, 4.0, "conical"), sun, None)); + assert!((b6[3] - 6.0).abs() < 0.05, "{b6:?}"); + // Breitere Krone, breiterer Schatten; runde Krone endet vor der Spitze-Länge (Kugel: z_c + r·√2). + let wide = bbox(&shadow_polygons_project(&mk(12.0, 8.0, "round"), sun, None)); + assert!((wide[2] - 4.0).abs() < 0.05, "{wide:?}"); + let a_small = area(&shadow_polygons_project(&mk(12.0, 4.0, "round"), sun, None)); + let a_wide = area(&shadow_polygons_project(&mk(12.0, 8.0, "round"), sun, None)); + assert!(a_wide > 2.0 * a_small, "{a_small} {a_wide}"); + // Kein Baum: kein Schatten. + assert!(shadow_polygons_project(&project_json(serde_json::json!({"trees": []})), sun, None).is_empty()); + } } diff --git a/src-tauri/core/src/tree.rs b/src-tauri/core/src/tree.rs new file mode 100644 index 00000000..84676a09 --- /dev/null +++ b/src-tauri/core/src/tree.rs @@ -0,0 +1,314 @@ +//! [149] Baum als eigenes Objekt (`Project.trees`): Abmessungen mit Vorgaben, Kronenprofil nach Form +//! (rund, oval, säulenförmig, kegelförmig), Fusshöhe auf dem Gelände, 3D-Netz (Stamm-Zylinder + Krone als +//! Rotationskörper mit wenigen Polygonen), Schattenwerfer (Stamm-Prisma + Kronen-Punktwolke) und die +//! Silhouette für Schnitt/Ansicht. Das Grundriss-Symbol entsteht in `plan/trees.rs`. +//! +//! Lage: Fuss an `position` auf dem sichtbaren Gelände (inkl. Baugruben, wie der Schattenwurf [142]), +//! sonst auf der UK des Geschosses; dazu `baseOffset`. Höhen über dem Fuss: Kronenansatz `crownBase`, +//! Spitze `height`. + +use crate::jsnum; +use crate::model::*; + +/// Vorgaben (m), wenn ein Wert fehlt oder unsinnig ist. +pub const DEFAULT_TRUNK_DIAMETER: f64 = 0.3; +pub const DEFAULT_CROWN_DIAMETER: f64 = 5.0; +pub const DEFAULT_HEIGHT: f64 = 10.0; +pub const DEFAULT_CROWN_BASE: f64 = 2.5; +/// Ebene der Bäume (SIA-Ebenenliste). +pub const TREE_CATEGORY: &str = "13"; +/// Präfix der Pick-Id im Feld `contextObjectId` der Plan-Primitive (`@` = keine Kontext-Element-Id). +pub const TREE_PICK_PREFIX: &str = "@tree:"; + +/// Stamm- und Kronenfarbe im 3D (sRGB 0–1). +pub const TRUNK_RGB: [f64; 3] = [0.42, 0.32, 0.22]; +pub const CROWN_RGB: [f64; 3] = [0.45, 0.58, 0.33]; +pub const CONIFER_RGB: [f64; 3] = [0.29, 0.45, 0.30]; + +/// Aufgelöste Abmessungen eines Baums in absoluten Höhen. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct TreeGeom { + /// Stammmitte. + pub c: [f64; 2], + /// Fuss (absolute Höhe). + pub base: f64, + pub trunk_r: f64, + pub crown_r: f64, + /// Kronenansatz und Spitze (absolute Höhen), `crown_bottom < top`. + pub crown_bottom: f64, + pub top: f64, + pub shape: TreeShape, +} + +fn pos(v: f64, d: f64) -> f64 { + if v > 0.0 && v.is_finite() { + v + } else { + d + } +} + +impl TreeGeom { + /// Abmessungen des Baums mit Fuss `base`; `None` bei unbrauchbarer Lage. + pub fn of(t: &Tree, base: f64) -> Option { + if !(t.position.x.is_finite() && t.position.y.is_finite() && base.is_finite()) { + return None; + } + let h = pos(t.height, DEFAULT_HEIGHT); + let crown_r = pos(t.crown_diameter, DEFAULT_CROWN_DIAMETER) / 2.0; + // Stamm nie dicker als die Krone. + let trunk_r = jsnum::min(pos(t.trunk_diameter, DEFAULT_TRUNK_DIAMETER) / 2.0, crown_r * 0.8); + // Kronenansatz zwischen 0 und 90 % der Höhe. + let cb = if t.crown_base.is_finite() { t.crown_base.clamp(0.0, 0.9 * h) } else { jsnum::min(DEFAULT_CROWN_BASE, 0.5 * h) }; + Some(TreeGeom { c: [t.position.x, t.position.y], base, trunk_r, crown_r, crown_bottom: base + cb, top: base + h, shape: t.shape }) + } + + /// Kronenprofil als (z, r) von unten nach oben, `n` Abschnitte (≥ 2); an den Enden r = 0 (Pole). + pub fn profile(&self, n: usize) -> Vec<(f64, f64)> { + let n = n.max(2); + let (zb, zt, r) = (self.crown_bottom, self.top, self.crown_r); + let h = zt - zb; + let at = |u: f64| zb + u * h; + let half = |s: f64| -> f64 { (1.0 - s * s).max(0.0).sqrt() }; + match self.shape { + TreeShape::Conical => { + // Kegel: flache Unterseite (5 % der Kronenhöhe), dann gerade zur Spitze. + vec![(zb, 0.0), (at(0.05), r), (at(0.5), r * 0.5 / 0.95), (zt, 0.0)] + } + _ => (0..=n) + .map(|i| { + let u = i as f64 / n as f64; + let rr = match self.shape { + TreeShape::Oval => { + // Eiform: breiteste Stelle bei 40 % der Kronenhöhe. + let w = 0.4; + let s = if u < w { (u - w) / w } else { (u - w) / (1.0 - w) }; + r * half(s) + } + TreeShape::Columnar => { + // Superellipse (Exponent 4): fast senkrechte Flanken, gerundete Enden. + let s = 2.0 * u - 1.0; + r * (1.0 - s.powi(4)).max(0.0).powf(0.25) + } + _ => r * half(2.0 * u - 1.0), + }; + (at(u), if i == 0 || i == n { 0.0 } else { rr }) + }) + .collect(), + } + } + + /// Oberkante des Stamms: ein Stück in die Krone hinein (keine Lücke unter der Krone). + pub fn trunk_top(&self) -> f64 { + self.crown_bottom + 0.25 * (self.top - self.crown_bottom) + } + + /// Stamm-Querschnitt als Ring (`n` Ecken, gegen den Uhrzeigersinn). + pub fn trunk_ring(&self, n: usize) -> Vec<[f64; 2]> { + circle(self.c, self.trunk_r, n) + } + + /// Krone als Rotationskörper: Positionen (x, y, z) und Dreiecke (aussen gegen den Uhrzeigersinn). + pub fn crown_mesh(&self, rings: usize, seg: usize) -> (Vec, Vec) { + lathe(self.c, &self.profile(rings), seg) + } + + /// Stamm als Prisma: Positionen und Dreiecke. + pub fn trunk_mesh(&self, seg: usize) -> (Vec, Vec) { + crate::columns3d::prism(&self.trunk_ring(seg), self.base, self.trunk_top()) + } + + /// Punkte der Krone (für den Schatten als konvexe Hülle der projizierten Punkte). + pub fn crown_points(&self) -> Vec<[f64; 3]> { + let (pos, _) = self.crown_mesh(8, 16); + pos.chunks_exact(3).map(|q| [q[0], q[1], q[2]]).collect() + } + + /// Silhouette in einer lotrechten Ebene: Umriss der Krone und des Stamms als (s, z), wobei `s` die + /// Lage der Stammmitte entlang der Ebene ist. + pub fn silhouette(&self, s: f64, n: usize) -> (Vec<[f64; 2]>, Vec<[f64; 2]>) { + let prof = self.profile(n); + let mut crown: Vec<[f64; 2]> = prof.iter().map(|&(z, r)| [s + r, z]).collect(); + crown.extend(prof.iter().rev().skip(1).take(prof.len().saturating_sub(2)).map(|&(z, r)| [s - r, z])); + crown.dedup(); + let tr = self.trunk_r; + let trunk = vec![[s - tr, self.base], [s + tr, self.base], [s + tr, self.crown_bottom], [s - tr, self.crown_bottom]]; + (crown, trunk) + } +} + +/// Kreis als Ring mit `n` Ecken (gegen den Uhrzeigersinn). +pub fn circle(c: [f64; 2], r: f64, n: usize) -> Vec<[f64; 2]> { + (0..n) + .map(|i| { + let t = i as f64 / n as f64 * std::f64::consts::TAU; + [c[0] + r * jsnum::cos(t), c[1] + r * jsnum::sin(t)] + }) + .collect() +} + +/// Rotationskörper um die lotrechte Achse durch `c` aus dem Profil (z, r); r = 0 an einem Ende = Pol. +pub fn lathe(c: [f64; 2], prof: &[(f64, f64)], seg: usize) -> (Vec, Vec) { + let seg = seg.max(3); + let mut pos: Vec = Vec::new(); + // Je Profilpunkt: Index des ersten Eckpunkts und ob Pol (ein Punkt). + let mut rows: Vec<(u32, bool)> = Vec::new(); + for &(z, r) in prof { + let start = (pos.len() / 3) as u32; + if r <= 1e-9 { + pos.extend([c[0], c[1], z]); + rows.push((start, true)); + } else { + for q in circle(c, r, seg) { + pos.extend([q[0], q[1], z]); + } + rows.push((start, false)); + } + } + let mut idx: Vec = Vec::new(); + let s = seg as u32; + for w in rows.windows(2) { + let ((a0, pa), (b0, pb)) = (w[0], w[1]); + for j in 0..s { + let k = (j + 1) % s; + let (a, b) = if pa { (a0, a0) } else { (a0 + j, a0 + k) }; + let (cc, d) = if pb { (b0, b0) } else { (b0 + k, b0 + j) }; + if a != b && b != cc { + idx.extend([a, b, cc]); + } + if cc != d && a != d { + idx.extend([a, cc, d]); + } + } + } + (pos, idx) +} + +/// Fusshöhen aller Bäume (`Project.trees`, gleiche Reihenfolge): Gelände an der Stammmitte (sichtbares +/// Geländenetz inkl. Baugruben), sonst UK des Geschosses; plus `baseOffset`. +pub fn bases(p: &Project) -> Vec { + let trees = p.trees.as_deref().unwrap_or(&[]); + if trees.is_empty() { + return Vec::new(); + } + let site = crate::excavation::terrains(p).into_iter().find(|t| t.hidden != Some(true)).map(|t| crate::excavation::site_terrain(p, t)).filter(|st| !st.current().tris.is_empty()); + let idx = site.as_ref().map(|st| (crate::terrain::TinIndex::new(st.current()), st.datum)); + trees + .iter() + .map(|t| { + let floor = p.floor(&t.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)); + let ground = idx.as_ref().and_then(|(i, datum)| i.z_at(t.position.x, t.position.y).map(|z| z - datum)).filter(|z| z.is_finite()); + ground.unwrap_or(floor) + t.base_offset.filter(|o| o.is_finite()).unwrap_or(0.0) + }) + .collect() +} + +/// Abmessungen aller darstellbaren Bäume mit ihrem Index in `Project.trees`. +pub fn geoms(p: &Project) -> Vec<(usize, TreeGeom)> { + let b = bases(p); + p.trees.as_deref().unwrap_or(&[]).iter().zip(b).enumerate().filter_map(|(i, (t, base))| TreeGeom::of(t, base).map(|g| (i, g))).collect() +} + +/// Stamm- und Kronenfarbe eines Baums im 3D. +pub fn colors(t: &Tree) -> ([f64; 3], [f64; 3]) { + (TRUNK_RGB, if t.foliage == TreeFoliage::Conifer { CONIFER_RGB } else { CROWN_RGB }) +} + +/// Bezeichnung (Objekt-Info, IFC): Art-Name, sonst „Baum". +pub fn label(t: &Tree) -> String { + t.species.as_deref().map(str::trim).filter(|s| !s.is_empty()).map_or_else(|| "Baum".to_string(), str::to_string) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tree(shape: &str) -> Tree { + serde_json::from_value(serde_json::json!({ + "id": "t", "type": "tree", "floorId": "eg", "categoryCode": "13", "position": {"x": 1, "y": 2}, + "trunkDiameter": 0.4, "crownDiameter": 6, "crownBase": 3, "height": 12, "shape": shape, + "status": "existing", "foliage": "deciduous" + })) + .unwrap() + } + + /// Volumen eines geschlossenen Netzes (Divergenzsatz), positiv bei Aussennormalen. + fn volume(pos: &[f64], idx: &[u32]) -> f64 { + let p = |i: u32| [pos[i as usize * 3], pos[i as usize * 3 + 1], pos[i as usize * 3 + 2]]; + idx.chunks_exact(3) + .map(|t| { + let (a, b, c) = (p(t[0]), p(t[1]), p(t[2])); + (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0 + }) + .sum() + } + + #[test] + fn modell_mit_vorgaben_und_hin_und_zurueck() { + let t = tree("oval"); + assert_eq!(t.shape, TreeShape::Oval); + let back: Tree = serde_json::from_value(serde_json::to_value(&t).unwrap()).unwrap(); + assert_eq!(back, t); + // Fehlende/unsinnige Werte: Vorgaben. + let mut u = t.clone(); + u.height = f64::NAN; + u.crown_diameter = -1.0; + u.trunk_diameter = 0.0; + u.crown_base = 99.0; + let g = TreeGeom::of(&u, 0.0).unwrap(); + assert_eq!(g.top, DEFAULT_HEIGHT); + assert_eq!(g.crown_r, DEFAULT_CROWN_DIAMETER / 2.0); + assert_eq!(g.trunk_r, DEFAULT_TRUNK_DIAMETER / 2.0); + assert!((g.crown_bottom - 0.9 * DEFAULT_HEIGHT).abs() < 1e-12); + u.position.x = f64::NAN; + assert!(TreeGeom::of(&u, 0.0).is_none()); + // Unbekannte Form/Bestand lesen sich ohne Fehler. + let w: Tree = serde_json::from_value(serde_json::json!({"id": "x", "shape": "weide", "status": "?"})).unwrap(); + assert_eq!(w.shape, TreeShape::Unknown); + } + + #[test] + fn netz_geschlossen_aussen_und_flach() { + for shape in ["round", "oval", "columnar", "conical"] { + let g = TreeGeom::of(&tree(shape), 1.0).unwrap(); + let (pos, idx) = g.crown_mesh(8, 12); + assert!(crate::wall_mesh_cut::is_watertight(&pos, &idx, 1e-9), "{shape}: Krone nicht dicht"); + let v = volume(&pos, &idx); + assert!(v > 0.0, "{shape}: Krone innen nach aussen ({v})"); + // Niedrige Polygonzahl. + assert!(idx.len() / 3 <= 200, "{shape}: {} Dreiecke", idx.len() / 3); + // Ausdehnung: Kronenradius, Kronenansatz bis Spitze. + let zs: Vec = pos.chunks_exact(3).map(|q| q[2]).collect(); + assert!((zs.iter().cloned().fold(f64::INFINITY, f64::min) - 4.0).abs() < 1e-9); + assert!((zs.iter().cloned().fold(f64::NEG_INFINITY, f64::max) - 13.0).abs() < 1e-9); + let rmax = pos.chunks_exact(3).map(|q| (q[0] - 1.0).hypot(q[1] - 2.0)).fold(0.0, f64::max); + assert!(rmax <= 3.0 + 1e-9 && rmax > 2.5, "{shape}: {rmax}"); + let (tp, ti) = g.trunk_mesh(8); + assert!(volume(&tp, &ti).abs() > 0.0); + } + // Kegel: Volumen ≈ π r² h / 3 (unten flach). + let g = TreeGeom::of(&tree("conical"), 0.0).unwrap(); + let (pos, idx) = g.crown_mesh(8, 48); + let v = volume(&pos, &idx); + let cone = std::f64::consts::PI * 9.0 * 9.0 / 3.0; + assert!((v / cone - 1.0).abs() < 0.1, "{v} vs {cone}"); + } + + #[test] + fn silhouette_nach_form() { + let g = TreeGeom::of(&tree("columnar"), 0.0).unwrap(); + let (crown, trunk) = g.silhouette(5.0, 16); + let xs = |r: &[[f64; 2]]| (r.iter().map(|q| q[0]).fold(f64::INFINITY, f64::min), r.iter().map(|q| q[0]).fold(f64::NEG_INFINITY, f64::max)); + let (a, b) = xs(&crown); + assert!((a - 2.0).abs() < 1e-6 && (b - 8.0).abs() < 1e-6, "{a} {b}"); + assert!((xs(&trunk).0 - 4.8).abs() < 1e-12); + // Säule ist auf halber Höhe zwischen Viertel und Dreiviertel fast voll breit, die Kugel nicht. + let width_at = |g: &TreeGeom, u: f64| { + let z = g.crown_bottom + u * (g.top - g.crown_bottom); + let pr = g.profile(64); + pr.windows(2).find(|w| w[0].0 <= z && z <= w[1].0).map(|w| w[0].1.max(w[1].1)).unwrap() + }; + let round = TreeGeom::of(&tree("round"), 0.0).unwrap(); + assert!(width_at(&g, 0.25) > 0.95 * 3.0 && width_at(&round, 0.25) < 0.9 * 3.0); + } +} diff --git a/src-tauri/fileio/src/ifc_export.rs b/src-tauri/fileio/src/ifc_export.rs index c64bb480..71619a62 100644 --- a/src-tauri/fileio/src/ifc_export.rs +++ b/src-tauri/fileio/src/ifc_export.rs @@ -93,6 +93,9 @@ // IfcZone mit IfcRelAssignsToGroup der Räume (`space/`-Entitäten; unbekannte ids werden // übersprungen, ohne Raum keine Zone). GlobalId aus `zone/`; Psets/Mengen wie bei Bauteilen. // ATTACH = 14, key, PSETS (Psets/Mengen an ein schon geschriebenes Bauteil/Geschoss, Schlüssel wie oben) +// TREE = 19 ([149] Baum), structure, id, name, PSETS, MESH (Stamm + Krone, Welt rel. Geschoss-UK) +// IFC4: IfcGeographicElement (ObjectType „Baum", PredefinedType USERDEFINED); IFC2x3 (kennt die +// Klasse nicht): IfcBuildingElementProxy mit ObjectType „Baum". GlobalId aus `tree/`. // // Schema IFC2x3 (Coordination View 2.0, TC1; [B5] 28.10.): gleiche Datensätze, GUIDs, Psets und Mengen, aber // die Entitäten des Schemas — Netze als IfcFacetedBrep (dicht) bzw. IfcShellBasedSurfaceModel (offen) statt @@ -143,6 +146,7 @@ pub const REC_OPENING_SOLID: f64 = 15.0; pub const REC_WALL_ARC: f64 = 16.0; pub const REC_WALL_ARC_SOLID: f64 = 17.0; pub const REC_GRID: f64 = 18.0; +pub const REC_TREE: f64 = 19.0; // ── IFC-GUID (Kompression nach IfcOpenShell `guid.compress`) ──────────────── @@ -1351,6 +1355,7 @@ fn rec_name(code: f64) -> &'static str { c if c == REC_ZONE => "ZONE", c if c == REC_ATTACH => "ATTACH", c if c == REC_GRID => "GRID", + c if c == REC_TREE => "TREE", _ => "?", } } @@ -2078,6 +2083,26 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { ); } } + c if c == REC_TREE => { + let structure = r.structure(n_storeys)?; + let id = r.string()?; + let name = r.string()?; + let psets = r.psets()?; + let mesh = r.mesh()?; + let (placement, shape) = w.emit_triangulated_product(&mesh, w.placement_of(structure)); + let key = format!("tree/{id}"); + let g = w.gid(&key); + let entity = if w.v2() { + w.add("IFCBUILDINGELEMENTPROXY", format!("{g},#{},{},$,{},#{placement},#{shape},$,$", w.owner_history, ifc_string(&name), ifc_string("Baum"))) + } else { + w.add("IFCGEOGRAPHICELEMENT", format!("{g},#{},{},$,{},#{placement},#{shape},$,{}", w.owner_history, ifc_string(&name), ifc_string("Baum"), enum_("USERDEFINED"))) + }; + w.add_to_containment(structure, entity); + w.elements.insert(key.clone(), entity); + for p in &psets { + w.add_pset(p, entity, &key); + } + } c if c == REC_ROOF => { let structure = r.structure(n_storeys)?; let id = r.string()?; @@ -3457,6 +3482,33 @@ mod tests { assert_eq!(count(&ifc, "IFCFACETEDBREP"), 0); } + /// [149] Baum: IFC4 IfcGeographicElement (USERDEFINED, ObjectType „Baum"), IFC2x3 IfcBuildingElementProxy; + /// Netz und Höhe (Mengen) am Element, GlobalId aus `tree/`. + #[test] + fn baum_als_geografisches_element() { + for v2 in [false, true] { + let mut b = mini_in(if v2 { B::v2() } else { B::new() }); + b.n(&[REC_TREE, -1.0]); + b.str("T1"); + b.str("Quercus robur"); + b.qto("Dossier_Qto_Tree", &[("Height", 3.0, 12.0), ("CrownDiameter", 3.0, 6.0)]); + // Tetraeder (geschlossen). + b.n(&[4.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 12.0]); + b.n(&[4.0, 0.0, 2.0, 1.0, 0.0, 1.0, 3.0, 1.0, 2.0, 3.0, 0.0, 3.0, 2.0, 0.0]); + let ifc = build(&b).unwrap(); + check_structure(&ifc); + let (ty, other) = if v2 { ("IFCBUILDINGELEMENTPROXY", "IFCGEOGRAPHICELEMENT") } else { ("IFCGEOGRAPHICELEMENT", "IFCBUILDINGELEMENTPROXY") }; + assert_eq!(count(&ifc, ty), 1, "{ifc}"); + assert_eq!(count(&ifc, other), 0); + let line = ifc.lines().find(|l| l.contains(&format!("={ty}("))).unwrap(); + assert!(line.contains("'Quercus robur'") && line.contains("'Baum'"), "{line}"); + assert_eq!(line.ends_with(".USERDEFINED.);"), !v2, "{line}"); + assert!(line.contains(&ifc_guid("t/tree/T1")), "{line}"); + assert!(ifc.contains("'Height'") && ifc.contains("IFCQUANTITYLENGTH")); + assert_eq!(count(&ifc, "IFCRELCONTAINEDINSPATIALSTRUCTURE"), 1); + } + } + #[test] fn ifc2x3_fenster_stil_klassifikation_zone_treppe() { let mut b = full_house_in(B::v2(), false); diff --git a/src/App.tsx b/src/App.tsx index f582ab56..0aecd356 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -698,6 +698,8 @@ export default function App() { const colids = new Set(notLocked("columnIds", selection.columns)); const rfids = new Set(notLocked("roofIds", selection.roofs)); const ctxids = new Set(selection.contextObjects); + // [149] Bäume (gesperrte bleiben). + const treeids = new Set(selection.trees.filter((id) => !(project.trees ?? []).find((t) => t.id === id)?.locked)); setProject( opsMutation((p) => [ ...removeItems(p, "drawings2d", dids), @@ -711,6 +713,7 @@ export default function App() { // Öffnungen: eigene Auswahl löschen UND alle, deren Wirt (Wand, Dach, Decke [103]) entfällt. ...removeItems(p, "openings", (o) => oids.has(o.id) || wids.has(o.hostWallId) || (!!o.hostRoofId && rfids.has(o.hostRoofId)) || (!!o.hostCeilingId && cids.has(o.hostCeilingId))), ...removeItems(p, "context", ctxids), + ...removeItems(p, "trees", treeids), ]), ); }; diff --git a/src/commands/cmds/tree.test.ts b/src/commands/cmds/tree.test.ts new file mode 100644 index 00000000..6575a007 --- /dev/null +++ b/src/commands/cmds/tree.test.ts @@ -0,0 +1,102 @@ +/** + * [149] Werkzeug „Baum": Klick setzt einen Baum (Ebene 13, Vorgaben, Optionen), Zahl = Kronendurchmesser, + * mehrere Bäume nacheinander; „Kreise in Bäume umwandeln" ersetzt die Kreise der Baum-Ebene. + */ + +import { describe, it, expect, beforeEach } from "vitest"; +import { circlesToTreesCommand, treeCommand, treeDefaults } from "./tree"; +import type { CommandContext, Project } from "../types"; + +function project(): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [ + { code: "13", name: "Bäume", color: "#0a0a0a", lw: 0.13, visible: true, locked: false }, + { code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }, + ], + walls: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [ + { id: "k1", type: "drawing2d", levelId: "eg", categoryCode: "13", geom: { shape: "circle", center: { x: 3, y: 4 }, r: 2.5 } }, + { id: "k2", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "circle", center: { x: 0, y: 0 }, r: 1 } }, + ], + context: [], + }; +} + +function makeCtx(p: Project, drawingIds: string[] = []): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null, drawingIds }, + }; +} + +describe("treeCommand", () => { + beforeEach(() => { + Object.assign(treeDefaults, { shape: "round", status: "existing", foliage: "deciduous", crownDiameter: 5, height: 10 }); + }); + + it("Klick setzt einen Baum auf der Baum-Ebene; der Befehl bleibt für den nächsten", () => { + const p = project(); + const ctx = makeCtx(p); + let st = treeCommand.init(); + // Zahl = Kronendurchmesser, Optionen wechseln Bestand und Laub/Nadel (Nadel → Kegel). + [st] = treeCommand.onInput(st, { kind: "number", value: 7 }, ctx); + [st] = treeCommand.onInput(st, { kind: "option", id: "status" }, ctx); + [st] = treeCommand.onInput(st, { kind: "option", id: "foliage" }, ctx); + const [st2, r] = treeCommand.onInput(st, { kind: "point", point: { x: 4, y: 2 } }, ctx); + expect(r.done).toBeFalsy(); + expect(r.commit).toBeDefined(); + const next = r.commit!(p); + expect(next.trees?.length).toBe(1); + const t = next.trees![0]; + expect(t).toMatchObject({ + type: "tree", + floorId: "eg", + categoryCode: "13", + position: { x: 4, y: 2 }, + crownDiameter: 7, + height: 10, + status: "new", + foliage: "conifer", + shape: "conical", + }); + // Zweiter Klick: zweiter Baum mit eigener id. + const [, r2] = treeCommand.onInput(st2, { kind: "point", point: { x: 10, y: 2 } }, makeCtx(next)); + const n2 = r2.commit!(next); + expect(n2.trees?.length).toBe(2); + expect(n2.trees![1].id).not.toBe(t.id); + // Vorschau: Kronenkreis am Cursor. + const [, mv] = treeCommand.onMove!(st2, { x: 1, y: 1 }, null, ctx); + expect(mv.draft?.preview?.length).toBeGreaterThan(0); + }); + + it("Kreise in Bäume umwandeln: nur Kreise der Baum-Ebene, Kreise entfallen", () => { + const p = project(); + const r = circlesToTreesCommand.autoRun!(makeCtx(p)); + const next = r.commit!(p); + expect(next.drawings2d.map((d) => d.id)).toEqual(["k2"]); + expect(next.trees?.length).toBe(1); + expect(next.trees![0]).toMatchObject({ position: { x: 3, y: 4 }, crownDiameter: 5, categoryCode: "13" }); + // Mit Auswahl: genau die gewählten Kreise. + const n2 = circlesToTreesCommand.autoRun!(makeCtx(p, ["k2"])).commit!(p); + expect(n2.drawings2d.map((d) => d.id)).toEqual(["k1"]); + expect(n2.trees![0].crownDiameter).toBe(2); + }); +}); diff --git a/src/commands/cmds/tree.ts b/src/commands/cmds/tree.ts new file mode 100644 index 00000000..2184c0c4 --- /dev/null +++ b/src/commands/cmds/tree.ts @@ -0,0 +1,128 @@ +// [149] Baum als Engine-Befehl. Ablauf: „Baum setzen:" → Klick setzt die Stammmitte → nächster Baum +// (der Befehl bleibt aktiv, Esc/Enter beendet). Optionen (Klick wechselt): Form, Bestand, Laub/Nadel. +// Eine getippte Zahl setzt den Kronendurchmesser (bleibt über Aufrufe, wie das Leitmass der Stütze). +// Höhe, Kronenansatz, Stamm und Art danach in der Objekt-Info. +// +// Die Ops baut der Kern (`cmd_create.rs`, Befehl „tree"): Ebene „13" (Bäume), falls vorhanden, sonst +// die aktive; aktives Geschoss. +// +// Bezeichner englisch, sichtbarer Text via t(). + +import type { Command, CommandContext, CommandResult, CommandState, CmdOption, Vec2 } from "../types"; +import type { TreeFoliage, TreeShape, TreeStatus } from "../../model/types"; +import { createMutation, createPreview, xy } from "../createCore"; +import { t, type TranslationKey } from "../../i18n"; + +const SHAPES: TreeShape[] = ["round", "oval", "columnar", "conical"]; +const STATUS: TreeStatus[] = ["existing", "new", "remove"]; +const FOLIAGE: TreeFoliage[] = ["deciduous", "conifer"]; + +/** Vorgaben des Werkzeugs (modulweit, leben über Befehls-Instanzen hinweg). */ +export const treeDefaults: { + shape: TreeShape; + status: TreeStatus; + foliage: TreeFoliage; + crownDiameter: number; + height: number; + trunkDiameter: number; + crownBase: number; +} = { + shape: "round", + status: "existing", + foliage: "deciduous", + crownDiameter: 5, + height: 10, + trunkDiameter: 0.3, + crownBase: 2.5, +}; + +const next = (list: readonly T[], v: T): T => list[(list.indexOf(v) + 1) % list.length]; + +/** Anfrage an den Kern (Werkzeug-Vorgaben). */ +export const treeReq = () => ({ cmd: "tree", ...treeDefaults }); + +const appendTree = (at: Vec2, ctx: CommandContext) => createMutation(ctx, { ...treeReq(), at: xy(at) }); + +interface TreeState extends CommandState { + phase: "place" | "done"; +} + +const finish = (): [CommandState, CommandResult] => [{ phase: "done", lastPoint: null } as TreeState, { draft: null, done: true }]; + +function previewAt(pt: Vec2, ctx: CommandContext): CommandResult { + return { + draft: { + preview: createPreview(ctx, treeReq(), [pt]).shapes, + vertices: [], + hud: { at: pt, text: `Ø${treeDefaults.crownDiameter.toFixed(1)} m · ${treeDefaults.height.toFixed(1)} m` }, + }, + }; +} + +export const treeCommand: Command = { + name: "tree", + labelKey: "cmd.tree.label", + prompt: () => "cmd.tree.place", + accepts: () => ["point", "number", "option"], + options: (): CmdOption[] => [ + { id: "shape", labelKey: "cmd.tree.shape", value: t(`objinfo.tree.shape.${treeDefaults.shape}` as TranslationKey) }, + { id: "status", labelKey: "cmd.tree.status", value: t(`objinfo.tree.status.${treeDefaults.status}` as TranslationKey) }, + { id: "foliage", labelKey: "cmd.tree.foliage", value: t(`objinfo.tree.foliage.${treeDefaults.foliage}` as TranslationKey) }, + ], + floorOnly: true, + + init: (): TreeState => ({ phase: "place", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as TreeState; + if (s.phase === "done") return finish(); + if (input.kind === "number") { + const v = Math.abs(input.value); + if (v > 0.1 && Number.isFinite(v)) treeDefaults.crownDiameter = v; + return [s, { draft: null }]; + } + if (input.kind === "option") { + if (input.id === "shape") treeDefaults.shape = next(SHAPES, treeDefaults.shape); + if (input.id === "status") treeDefaults.status = next(STATUS, treeDefaults.status); + if (input.id === "foliage") { + treeDefaults.foliage = next(FOLIAGE, treeDefaults.foliage); + // Nadelbaum meist kegelförmig, Laubbaum rund (Form bleibt danach frei wählbar). + treeDefaults.shape = treeDefaults.foliage === "conifer" ? "conical" : "round"; + } + return [s, { draft: null }]; + } + if (input.kind === "point") { + // Mehrere Bäume nacheinander: der Befehl bleibt in der Setz-Phase. + return [s, { draft: null, commit: appendTree(input.point, ctx) }]; + } + return [s, { draft: null }]; + }, + + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { + const s = state as TreeState; + if (s.phase !== "place") return [s, { draft: null }]; + return [s, previewAt(point, ctx)]; + }, + + onConfirm: (): [CommandState, CommandResult] => finish(), + onCancel: (): [CommandState, CommandResult] => finish(), +}; + +/** [149] „Kreise in Bäume umwandeln": gewählte Kreise, sonst alle Kreise der Baum-Ebene im aktiven Geschoss. */ +export const circlesToTreesCommand: Command = { + name: "circlestotrees", + labelKey: "cmd.circlestotrees.label", + prompt: () => "cmd.circlestotrees.label", + accepts: () => [], + options: () => [], + floorOnly: true, + init: (): CommandState => ({ phase: "idle", lastPoint: null }), + autoRun: (ctx: CommandContext): CommandResult => { + const ids = ctx.selection.drawingIds?.length ? ctx.selection.drawingIds : ctx.selection.drawingId ? [ctx.selection.drawingId] : []; + return { draft: null, done: true, commit: createMutation(ctx, { cmd: "circlesToTrees", ids }) }; + }, + onInput: (): [CommandState, CommandResult] => finish(), + onMove: (state): [CommandState, CommandResult] => [state, { draft: null }], + onConfirm: (): [CommandState, CommandResult] => finish(), + onCancel: (): [CommandState, CommandResult] => finish(), +}; diff --git a/src/commands/registry.ts b/src/commands/registry.ts index 762c18dc..1e46e655 100644 --- a/src/commands/registry.ts +++ b/src/commands/registry.ts @@ -13,6 +13,7 @@ import { ceilingCommand } from "./cmds/ceiling"; import { openingCommand, fensterCommand, tuerCommand } from "./cmds/opening"; import { stairCommand } from "./cmds/stair"; import { columnCommand } from "./cmds/column"; +import { circlesToTreesCommand, treeCommand } from "./cmds/tree"; import { roofCommand } from "./cmds/roof"; import { solidCommand } from "./cmds/solid"; import { solidBoolCommand } from "./cmds/solidbool"; @@ -82,6 +83,8 @@ export const COMMANDS: Record = { tuer: tuerCommand, stair: stairCommand, column: columnCommand, + tree: treeCommand, + circlestotrees: circlesToTreesCommand, roof: roofCommand, solid: solidCommand, solidbool: solidBoolCommand, @@ -170,6 +173,8 @@ export const ALIASES: Record = { tp: "stair", stuetze: "column", stütze: "column", + baum: "tree", + kreiseinbaeume: "circlestotrees", dach: "roof", koerper: "solid", durchbruch: "voidbox", diff --git a/src/commands/types.ts b/src/commands/types.ts index 4d25f2e0..a76a6af7 100644 --- a/src/commands/types.ts +++ b/src/commands/types.ts @@ -86,6 +86,8 @@ export interface CommandSelection { roomIds?: string[]; /** Gewählte Öffnungen ([144]): Wandöffnungen gleiten beim Verschieben entlang ihrer Wand. */ openingIds?: string[]; + /** [149] Gewählte Bäume (Verschieben/Kopieren/Spiegeln/Drehen: Stammmitte). */ + treeIds?: string[]; } /** Live-Kontext, den ein Befehl bei jedem Schritt erhält (analog ToolContext). */ diff --git a/src/core/index.ts b/src/core/index.ts index 8a992f0f..ec66f67f 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -163,6 +163,7 @@ export { DRAWING_PICK_TOLERANCE, type PickContextMesh, type PickColumnMesh, + type PickTreeMesh, type PickSolidMesh, type PickOpeningMesh, type PickStairMesh, diff --git a/src/editors/elementClipboard.ts b/src/editors/elementClipboard.ts index 1efc6b52..0b2674ae 100644 --- a/src/editors/elementClipboard.ts +++ b/src/editors/elementClipboard.ts @@ -28,6 +28,7 @@ import type { Roof, Room, Stair, + Tree, Wall, } from "../model/types"; import { uniqueStamp } from "../tools/types"; @@ -45,6 +46,8 @@ export interface ElementSelectionIds { roomIds: string[]; extrudedSolidIds: string[]; columnIds: string[]; + /** [149] Bäume (optional: ältere Aufrufer kennen sie nicht). */ + treeIds?: string[]; } /** Tiefe Kopie der gewählten Elemente über alle Bauteil-Arten hinweg. */ @@ -58,6 +61,8 @@ export interface ElementClipboard { rooms: Room[]; extrudedSolids: ExtrudedSolid[]; columns: Column[]; + /** [149] Bäume (optional: Zwischenablagen älterer Fenster haben sie nicht). */ + trees?: Tree[]; } const EMPTY_CLIPBOARD: ElementClipboard = { @@ -83,7 +88,8 @@ export function isClipboardEmpty(c: ElementClipboard): boolean { c.stairs.length === 0 && c.rooms.length === 0 && c.extrudedSolids.length === 0 && - c.columns.length === 0 + c.columns.length === 0 && + (c.trees?.length ?? 0) === 0 ); } @@ -122,6 +128,8 @@ export function collectElementClipboard( const extrudedSolids = (project.extrudedSolids ?? []).filter((s) => extrudedSolidIds.has(s.id)); const columnIds = new Set(sel.columnIds); const columns = (project.columns ?? []).filter((c) => columnIds.has(c.id)); + const treeIds = new Set(sel.treeIds ?? []); + const trees = (project.trees ?? []).filter((t) => treeIds.has(t.id)); const clip: ElementClipboard = { walls: walls.map((w) => structuredClone(w)), @@ -133,6 +141,7 @@ export function collectElementClipboard( rooms: rooms.map((r) => structuredClone(r)), extrudedSolids: extrudedSolids.map((s) => structuredClone(s)), columns: columns.map((c) => structuredClone(c)), + trees: trees.map((t) => structuredClone(t)), }; return isClipboardEmpty(clip) ? null : clip; } @@ -148,6 +157,7 @@ export interface PastedIds { roomIds: string[]; extrudedSolidIds: string[]; columnIds: string[]; + treeIds: string[]; } /** Projekt-Liste → Feld in {@link PastedIds}. */ @@ -161,6 +171,7 @@ const PASTED_KEY: Record = { rooms: "roomIds", extrudedSolids: "extrudedSolidIds", columns: "columnIds", + trees: "treeIds", }; /** @@ -185,6 +196,7 @@ export function pasteElementClipboard( roomIds: [], extrudedSolidIds: [], columnIds: [], + treeIds: [], }; for (const op of ops) { const key = op.kind === "add" ? PASTED_KEY[op.collection] : undefined; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 214cb9a0..49d89973 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1797,6 +1797,35 @@ export const de = { "cmd.opening.dir": "Richtung", "cmd.opening.sillField": "Brüstung", "cmd.opening.swingField": "Winkel", + "cmd.tree.label": "Baum", + "cmd.tree.place": "Baum setzen (Zahl = Kronendurchmesser):", + "cmd.tree.shape": "Form", + "cmd.tree.status": "Bestand", + "cmd.tree.foliage": "Laub/Nadel", + "cmd.circlestotrees.label": "Kreise in Bäume umwandeln", + "objinfo.kind.tree": "Baum", + "objinfo.tree.many": "{n} Bäume", + "objinfo.tree.section": "Baum", + "objinfo.tree.species": "Art", + "objinfo.tree.speciesHint": "z. B. Quercus robur", + "objinfo.tree.status": "Bestand", + "objinfo.tree.status.existing": "bestehend", + "objinfo.tree.status.new": "neu", + "objinfo.tree.status.remove": "zu fällen", + "objinfo.tree.shape": "Form", + "objinfo.tree.shape.round": "rund", + "objinfo.tree.shape.oval": "oval", + "objinfo.tree.shape.columnar": "säulenförmig", + "objinfo.tree.shape.conical": "kegelförmig", + "objinfo.tree.foliage": "Laub/Nadel", + "objinfo.tree.foliage.deciduous": "Laubbaum", + "objinfo.tree.foliage.conifer": "Nadelbaum", + "objinfo.tree.height": "Höhe", + "objinfo.tree.crownDiameter": "Kronen-Ø", + "objinfo.tree.crownBase": "Kronenansatz", + "objinfo.tree.trunkDiameter": "Stamm-Ø", + "objinfo.tree.locked": "Gesperrt — Werte nicht änderbar.", + "pick.kind.tree": "Baum", "cmd.column.label": "Stütze", "cmd.column.place": "Stütze setzen:", "cmd.column.profile": "Profil", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 7f7e9489..93e49db9 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1786,6 +1786,35 @@ export const en: Record = { "cmd.opening.dir": "Direction", "cmd.opening.sillField": "Sill", "cmd.opening.swingField": "Angle", + "cmd.tree.label": "Tree", + "cmd.tree.place": "Place tree (number = crown diameter):", + "cmd.tree.shape": "Shape", + "cmd.tree.status": "Status", + "cmd.tree.foliage": "Foliage", + "cmd.circlestotrees.label": "Convert circles to trees", + "objinfo.kind.tree": "Tree", + "objinfo.tree.many": "{n} trees", + "objinfo.tree.section": "Tree", + "objinfo.tree.species": "Species", + "objinfo.tree.speciesHint": "e.g. Quercus robur", + "objinfo.tree.status": "Status", + "objinfo.tree.status.existing": "existing", + "objinfo.tree.status.new": "new", + "objinfo.tree.status.remove": "to be felled", + "objinfo.tree.shape": "Shape", + "objinfo.tree.shape.round": "round", + "objinfo.tree.shape.oval": "oval", + "objinfo.tree.shape.columnar": "columnar", + "objinfo.tree.shape.conical": "conical", + "objinfo.tree.foliage": "Foliage", + "objinfo.tree.foliage.deciduous": "deciduous", + "objinfo.tree.foliage.conifer": "conifer", + "objinfo.tree.height": "Height", + "objinfo.tree.crownDiameter": "Crown Ø", + "objinfo.tree.crownBase": "Crown base", + "objinfo.tree.trunkDiameter": "Trunk Ø", + "objinfo.tree.locked": "Locked — values cannot be changed.", + "pick.kind.tree": "Tree", "cmd.column.label": "Column", "cmd.column.place": "Place column:", "cmd.column.profile": "Profile", diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index a1fa1e52..fd910c93 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -2474,6 +2474,11 @@ export type Project = { * Projekte/Tests ohne `columns` gültig bleiben (Default: leer behandeln). */ columns?: Array; + /** + * Bäume ([149]) — eigene Objekte mit Stamm, Krone und Höhe, siehe {@link Tree}. Optional, damit + * bestehende Projekte ohne `trees` gültig bleiben (Default: leer behandeln). + */ + trees?: Array; /** * Gruppen (Vectorworks-artig: Cmd+G fasst die Auswahl zu einer Einheit * zusammen; Doppelklick betritt die Gruppe zum Bearbeiten, alles andere @@ -3246,6 +3251,62 @@ export type TextStylePreset = { marks: Marks; }; +/** + * Ein Baum ([149]) — eigenes Objekt der Umgebung mit Stamm, Krone und Höhe. Grundriss/Situation + * (Kronenkreis mit Planzeichen, Stamm), Schnitt/Ansicht (Silhouette nach Form), 3D (Stamm-Zylinder + + * Krone), Schatten (Sonnenstudie), IFC (IfcGeographicElement). Fuss auf dem Gelände an `position` + * (sonst auf der Geschoss-UK) plus `baseOffset`. + */ +export type Tree = { + id: string; + type: "tree"; + /** Zugehörige Zeichnungsebene (Geschoss), auf der der Baum im Grundriss erscheint. */ + floorId: string; + /** Grafik-Kategorie (Ebene), Vorgabe "13" (Bäume). */ + categoryCode: string; + /** Objekt-Sperre, analog `Wall.locked`. */ + locked?: boolean; + /** Stammmitte im Grundriss (Meter). */ + position: Vec2; + /** Stammdurchmesser (m, > 0). */ + trunkDiameter: number; + /** Kronendurchmesser (m, > 0). */ + crownDiameter: number; + /** Höhe des Kronenansatzes über dem Fuss (m, ≥ 0, < `height`). */ + crownBase: number; + /** Gesamthöhe über dem Fuss (m, > 0). */ + height: number; + /** Kronenform. */ + shape: TreeShape; + /** Bestehend / neu / zu fällen. */ + status: TreeStatus; + /** Laub- oder Nadelbaum. */ + foliage: TreeFoliage; + /** Optionaler Art-Name (z. B. „Quercus robur"), erscheint als Beschriftung im Grundriss. */ + species?: string; + /** Höhenversatz des Fusses gegenüber Gelände bzw. Geschoss-UK (m, Vorgabe 0). */ + baseOffset?: number; + /** + * Optionale Übersteuerung der Strichfarbe; sonst gilt die Kategorie-Farbe bzw. die Bestandsfarbe. + */ + color?: string; +}; + +/** Laub- oder Nadelbaum ([149]) — Planzeichen der Krone (Laub: Wellenkranz, Nadel: Zacken). */ +export type TreeFoliage = "deciduous" | "conifer"; + +/** + * Kronenform eines Baums ([149]): Grundform der Silhouette (Schnitt/Ansicht), des 3D-Körpers und + * des Schattenwerfers. + */ +export type TreeShape = "round" | "oval" | "columnar" | "conical"; + +/** + * Bestand eines Baums ([149]) nach Plankonvention: bestehend (schwarz), neu (rot/Planung), + * zu fällen (gelb bzw. durchgekreuzt). + */ +export type TreeStatus = "existing" | "new" | "remove"; + export type Vec2 = { x: number; y: number }; /** diff --git a/src/panels/ObjectInfoPanel.tsx b/src/panels/ObjectInfoPanel.tsx index ed392885..2ac7090d 100644 --- a/src/panels/ObjectInfoPanel.tsx +++ b/src/panels/ObjectInfoPanel.tsx @@ -37,6 +37,10 @@ import type { SiaCategory, SliceTermination, StairShape, + Tree, + TreeFoliage, + TreeShape, + TreeStatus, Vec2, VerticalAnchor, WallReferenceLine, @@ -99,6 +103,7 @@ export function ObjectInfoPanel() { // [137] Lage-Darstellung angeklickt (Schattenfläche / Baurechtslinie): Einstellungen der Quelle. const site = useStore((s) => s.selection.site); + const treeSel = useStore((s) => s.selection.trees); const ctxObj = sel?.kind === "contextObject" ? (host.project.context ?? []).find((o) => o.id === sel.id) : undefined; const quantities = useMemo( () => (ctxObj?.type === "excavation" ? excavationQuantities(host.project) : []), @@ -106,6 +111,8 @@ export function ObjectInfoPanel() { ); // ── Leerzustand ─────────────────────────────────────────────────────────── + // [149] Baum gewählt: eigene Felder (Lage, Masse, Form, Bestand). + if (sel === null && treeSel.length > 0) return ; if (sel === null && site[0] === "viewShadows") return ; if (sel === null && site.length > 0) { const sun = site[0] === "sunStudy"; @@ -2388,6 +2395,92 @@ function VerticalAnchorRow({ // Nach erfolgreichem Resize liefert der Host eine neue bbox → neuer `value` → // das Feld zeigt automatisch die aktualisierte Größe. `min` erlaubt negative // Werte (z. B. absolute Z-Höhen unter 0). +// ── Baum ([149]) ───────────────────────────────────────────────────────────── +// Lage (Stammmitte), Masse, Form, Bestand, Laub/Nadel und Art des ersten gewählten Baums; jede Änderung +// ein Undo-Schritt (Kern prüft die Op). Bei mehreren gewählten Bäumen wirken Form/Bestand/Laub auf alle. +const TREE_SHAPES: TreeShape[] = ["round", "oval", "columnar", "conical"]; +const TREE_STATUS: TreeStatus[] = ["existing", "new", "remove"]; +const TREE_FOLIAGE: TreeFoliage[] = ["deciduous", "conifer"]; + +export function TreeSection({ ids }: { ids: readonly string[] }) { + const host = usePanelHost(); + const applyChange = useStore((s) => s.applyChange); + const trees = (host.project.trees ?? []).filter((x) => ids.includes(x.id)); + const tree = trees[0]; + if (!tree) return
{t("objinfo.empty")}
; + const locked = !!tree.locked; + const set = (patch: Partial, all = false) => + applyChange((p) => (all ? trees : [tree]).filter((x) => !x.locked).flatMap((x) => patchItem(p, "trees", x.id, patch))); + const level = host.project.drawingLevels.find((l) => l.id === tree.floorId); + return ( +
+
+ {trees.length > 1 ? t("objinfo.tree.many", { n: trees.length }) : t("objinfo.kind.tree")} +
+
{t("objinfo.tree.section")}
+ +
+ {t("objinfo.tree.status")} + set({ status: v as TreeStatus }, true)} + options={TREE_STATUS.map((v) => ({ value: v, label: t(`objinfo.tree.status.${v}` as TranslationKey) }))} + title={t("objinfo.tree.status")} + width={130} + /> +
+
+ {t("objinfo.tree.shape")} + set({ shape: v as TreeShape }, true)} + options={TREE_SHAPES.map((v) => ({ value: v, label: t(`objinfo.tree.shape.${v}` as TranslationKey) }))} + title={t("objinfo.tree.shape")} + width={130} + /> +
+
+ {t("objinfo.tree.foliage")} + set({ foliage: v as TreeFoliage }, true)} + options={TREE_FOLIAGE.map((v) => ({ value: v, label: t(`objinfo.tree.foliage.${v}` as TranslationKey) }))} + title={t("objinfo.tree.foliage")} + width={130} + /> +
+ set({ height: v, crownBase: Math.min(tree.crownBase, 0.9 * v) })} /> + set({ crownDiameter: v })} /> + set({ crownBase: Math.min(v, 0.9 * tree.height) })} /> + set({ trunkDiameter: v })} /> + set({ position: { x: v, y: tree.position.y } })} /> + set({ position: { x: tree.position.x, y: v } })} /> +
+ {t("objinfo.column.floor")} + {level?.name ?? tree.floorId} +
+ {locked &&
{t("objinfo.tree.locked")}
} +
+ ); +} + function DimensionField({ label, value, diff --git a/src/panels/ToolsPanel.tsx b/src/panels/ToolsPanel.tsx index 54441534..9fcb0d14 100644 --- a/src/panels/ToolsPanel.tsx +++ b/src/panels/ToolsPanel.tsx @@ -379,7 +379,7 @@ const TOOLS_2D: ToolId[] = [ "image", ]; const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"]; -const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "revolve", "loft", "solid", "solidbool", "sectionline", "viewline", "autodim", "excavation"]; +const COMMANDS_3D = ["column", "tree", "circlestotrees", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "revolve", "loft", "solid", "solidbool", "sectionline", "viewline", "autodim", "excavation"]; const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "break", "split", "extend", "fillet", "chamfer", "join", "defblock", "measure"]; type ToolsView = "list" | "icons"; diff --git a/src/plan/pickLabels.ts b/src/plan/pickLabels.ts index cc28cc9f..60e2f362 100644 --- a/src/plan/pickLabels.ts +++ b/src/plan/pickLabels.ts @@ -8,7 +8,7 @@ import { flattenCategories } from "../model/types"; /** Art eines auswählbaren Objekts an einer Klickstelle (Reihenfolge = Standard-Priorität). */ export type PickKind = | "section" | "opening" | "wall" | "column" | "drawing" | "solid" - | "ceiling" | "stair" | "room" | "roof" | "site" | "context"; + | "tree" | "ceiling" | "stair" | "room" | "roof" | "site" | "context"; type WithCategory = { id: string; categoryCode?: string }; @@ -25,6 +25,7 @@ function collection(project: Project, kind: PickKind): readonly WithCategory[] { case "column": return p.columns ?? []; case "context": return p.context ?? []; case "solid": return p.extrudedSolids ?? []; + case "tree": return p.trees ?? []; case "section": case "site": return []; } diff --git a/src/plan/pickTypes.ts b/src/plan/pickTypes.ts index 9438e14f..9d4ffc9c 100644 --- a/src/plan/pickTypes.ts +++ b/src/plan/pickTypes.ts @@ -104,6 +104,12 @@ export interface PickColumnMesh { columnId: string; } +/** [149] Baum für den Raycast: WORLD-Dreiecke von Stamm und Krone (x, Höhe, y). */ +export interface PickTreeMesh { + tris: ReadonlyArray; + treeId: string; +} + /** * [137] Freier Körper (`extrudedSolids`, Loft/Rotation/Abzug/B-Rep) für den Raycast: WORLD-Dreiecke * (x, Höhe, y). Der Kern liefert das Prisma über dem Umriss; sobald das truck-Netz geladen ist, ersetzt diff --git a/src/plan/toWalls3d.ts b/src/plan/toWalls3d.ts index 4209f00e..7ab69fd5 100644 --- a/src/plan/toWalls3d.ts +++ b/src/plan/toWalls3d.ts @@ -44,7 +44,7 @@ import type { Project, Vec2 } from "../model/types"; import type { DetailLevel } from "../model/viewTypes"; import { documentFor } from "../core/document"; import { coreEpoch } from "../engine/coreWasm"; -import type { PickOpening, PickRoof, PickStair, PickContextMesh, PickColumnMesh, PickSolidMesh, PickOpeningMesh, PickDrawingSeg, PickStairMesh, PickDrawingMesh } from "./pickTypes"; +import type { PickOpening, PickRoof, PickStair, PickContextMesh, PickColumnMesh, PickSolidMesh, PickOpeningMesh, PickDrawingSeg, PickStairMesh, PickDrawingMesh, PickTreeMesh } from "./pickTypes"; import { type RMesh, type RModel3d, @@ -334,6 +334,8 @@ export function pickGeometry( drawings: PickDrawingSeg[]; stairMeshes: PickStairMesh[]; drawingMeshes: PickDrawingMesh[]; + /** [149] Bäume (Stamm + Krone). */ + trees: PickTreeMesh[]; } { const g = documentFor(project).query("pickGeometry", [explodeGap(explode)]) as ReturnType; // [137] Freie Körper: das geladene truck-Netz (Loft, Rotation, Verjüngung, Rundung) statt der Prisma-Näherung des Kerns. @@ -389,8 +391,10 @@ export function selectionHighlightLines( /** [137] Stützen und freie Körper (Prisma-Umriss). */ columnIds: string[] = [], solidIds: string[] = [], + /** [149] Bäume (Kronen-Zylinder vom Fuss bis zur Spitze). */ + treeIds: string[] = [], ): Float32Array { - const sel = { walls: wallIds, ceilings: ceilingIds, openings: openingIds, stairs: stairIds, roofs: roofIds, context: contextObjectIds, columns: columnIds, solids: solidIds }; + const sel = { walls: wallIds, ceilings: ceilingIds, openings: openingIds, stairs: stairIds, roofs: roofIds, context: contextObjectIds, columns: columnIds, solids: solidIds, trees: treeIds }; if (Object.values(sel).every((l) => l.length === 0)) return new Float32Array(0); // Gerechnet im Kern (`highlight3d.rs`); Antwort f32-LE. const b = documentFor(project).queryBin("selectionHighlight", [], JSON.stringify({ ...sel, rgb, explode: explodeGap(explode) })); diff --git a/src/state/selection.test.ts b/src/state/selection.test.ts index c5ec9827..b3ba4ca9 100644 --- a/src/state/selection.test.ts +++ b/src/state/selection.test.ts @@ -85,6 +85,7 @@ describe("Selection", () => { stairIds: [], roomIds: [], openingIds: [], + treeIds: [], }); expect(toTransformSelection(s)).toEqual(c); }); diff --git a/src/state/selection.ts b/src/state/selection.ts index dd09880c..6ca20d91 100644 --- a/src/state/selection.ts +++ b/src/state/selection.ts @@ -37,6 +37,8 @@ export interface Selection { * bzw. `"siteRules"` (Baurechtslinie) — die Objekt-Info zeigt die Einstellungen der Quelle. */ site: string[]; + /** [149] Bäume (`Project.trees`). */ + trees: string[]; /** * Gewählte Gruppen — rein informativ (Bounding-Box, Doppelklick-Ziel); die * Mitglieder stehen zusätzlich in den übrigen Arten (s. `groupActions.ts`). @@ -60,6 +62,7 @@ export const SELECTION_KINDS: readonly SelectionKind[] = [ "contextObjects", "sectionLines", "site", + "trees", "groups", ]; @@ -138,6 +141,7 @@ export function toCommandSelection(sel: Selection): CommandSelection { stairIds: sel.stairs, roomIds: sel.rooms, openingIds: sel.openings, + treeIds: sel.trees, }; } @@ -157,7 +161,8 @@ export function hasTransformable(sel: Selection): boolean { sel.roofs.length > 0 || sel.stairs.length > 0 || sel.rooms.length > 0 || - sel.openings.length > 0 + sel.openings.length > 0 || + sel.trees.length > 0 ); } @@ -175,6 +180,8 @@ export interface SelectionIdLists { contextObjectIds: string[]; sectionLineIds: string[]; groupIds: string[]; + /** [149] Bäume (nicht gruppierbar; Zwischenablage, Nachauswahl). */ + treeIds?: string[]; } const ID_LIST_KEYS: [SelectionKind, keyof SelectionIdLists][] = [ @@ -190,6 +197,7 @@ const ID_LIST_KEYS: [SelectionKind, keyof SelectionIdLists][] = [ ["contextObjects", "contextObjectIds"], ["sectionLines", "sectionLineIds"], ["groups", "groupIds"], + ["trees", "treeIds"], ]; /** Auswahl → `…Ids`-Listen (passt strukturell auf `GroupMembership` und `BcfSelection`). */ diff --git a/src/state/useGripEditing.ts b/src/state/useGripEditing.ts index de4b57d4..7996112e 100644 --- a/src/state/useGripEditing.ts +++ b/src/state/useGripEditing.ts @@ -37,6 +37,8 @@ import type { BodyTarget } from "../views/plan/PlanView"; import type { CommandLineHandle } from "../ui/CommandLine"; import type { CommandEngine } from "../commands/engine"; import { single } from "./selection"; +import { getState as storeState } from "./appStore"; +import { patchItem } from "../core"; import type { Selection } from "./selection"; export interface GripEditFieldsState { @@ -162,6 +164,13 @@ export function useGripEditing(opts: { } = opts; const selectedOpeningId = single(selection, "openings"); const selectedStairId = single(selection, "stairs"); + // [149] Baum: Griff in der Stammmitte (verschieben) und am Kronenrand (Kronendurchmesser). + const selectedTreeId = single(selection, "trees"); + const selectedTree = selectedTreeId ? (project.trees ?? []).find((x) => x.id === selectedTreeId) : undefined; + const treeGrips = (tr: NonNullable): Vec2[] => [ + tr.position, + { x: tr.position.x + tr.crownDiameter / 2, y: tr.position.y }, + ]; const selectedRoomId = single(selection, "rooms"); const selectedCeilingId = single(selection, "ceilings"); const selectedDrawingId = single(selection, "drawings"); @@ -293,6 +302,11 @@ export function useGripEditing(opts: { gripOwnerRange.push([0, 0]); return [stairMoveHandle(st)]; } + if (selectedTree && modelEditable && !selectedTree.locked) { + const pts = treeGrips(selectedTree); + pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); }); + return pts; + } // [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); @@ -833,6 +847,17 @@ export function useGripEditing(opts: { if (st) moveStairBy(st.id, sub(pt, stairMoveHandle(st))); return; } + // [149] Baum: Stammmitte bzw. Kronenrand live, ein Undo-Schritt je Zug (gleicher coalesceKey). + if (selectedTree) { + const tr = selectedTree; + if (tr.locked) return; + const patch = + index === 0 + ? { position: { x: pt.x, y: pt.y } } + : { crownDiameter: Math.max(0.2, 2 * Math.hypot(pt.x - tr.position.x, pt.y - tr.position.y)) }; + storeState().applyChange((p) => patchItem(p, "trees", tr.id, patch), `treeGrip:${tr.id}:${index}`); + return; + } // [68] Baugrube: Sohlen-Griff sofort (Höhe), Ecken als Vorschau bis zum Setzen. if (selectedExcavation && !selectedCeilingId && !selectedRoomId) { if (index >= selectedExcavation.outline.length) moveExcavationGrip(selectedExcavation.id, index, pt); diff --git a/src/state/useMouseSelectionHandlers.ts b/src/state/useMouseSelectionHandlers.ts index 39b708c9..064cfb0c 100644 --- a/src/state/useMouseSelectionHandlers.ts +++ b/src/state/useMouseSelectionHandlers.ts @@ -207,6 +207,7 @@ export function useMouseSelectionHandlers(opts: { roof: "roofs", context: "contextObjects", site: "site", + tree: "trees", } as const satisfies Record; type Kind = keyof typeof channels; const target: { kind: Kind; id: string } | null = sel.sectionLineId @@ -225,7 +226,9 @@ export function useMouseSelectionHandlers(opts: { ? { kind: "room", id: sel.roomId } : sel.extrudedSolidId ? { kind: "solid", id: sel.extrudedSolidId } - : sel.columnId + : sel.treeId + ? { kind: "tree", id: sel.treeId } + : sel.columnId ? { kind: "column", id: sel.columnId } : sel.roofId ? { kind: "roof", id: sel.roofId } @@ -289,7 +292,9 @@ export function useMouseSelectionHandlers(opts: { ? ["contextObjects", sel.contextObjectId] : sel.siteId ? ["site", sel.siteId] - : null; + : sel.treeId + ? ["trees", sel.treeId] + : null; setSelection({ ...clearKinds(), groups: [], ...(one ? { [one[0]]: [one[1]] } : {}) }); }; // Links-Drag (Marquee) im Grundriss: die getroffene Wand-MENGE übernehmen @@ -387,6 +392,11 @@ export function useMouseSelectionHandlers(opts: { setSelection({ ...clearKinds(), columns: [hit.id] }); return; } + // [149] Baum: Objekt-Info wie im Grundriss. + if (hit.kind === "tree") { + setSelection({ ...clearKinds(), trees: [hit.id] }); + return; + } // [137] Freier Körper (Loft, Rotation, Extrusion): Objekt-Info wie im Grundriss. if (hit.kind === "solid") { setSelection({ ...clearKinds(), solids: [hit.id] }); diff --git a/src/tools/transform.ts b/src/tools/transform.ts index 0bcb2d36..713718e3 100644 --- a/src/tools/transform.ts +++ b/src/tools/transform.ts @@ -53,6 +53,8 @@ export interface TransformSelection { roomIds?: string[]; /** Gewählte Öffnungen ([144]): nur Verschieben, entlang der Wirtswand (Kern `slide_opening`). */ openingIds?: string[]; + /** [149] Gewählte Bäume (Stammmitte wird transformiert). */ + treeIds?: string[]; } /** Auswahl (Befehlskontext) → TransformSelection (gleiche Form, alle Elementarten). */ @@ -68,6 +70,7 @@ export function toTransformSel(sel: CommandSelection): TransformSelection { stairIds: sel.stairIds, roomIds: sel.roomIds, openingIds: sel.openingIds, + treeIds: sel.treeIds, }; } @@ -87,7 +90,8 @@ export function hasTransformSelection(sel: CommandSelection, op?: string): boole (sel.ceilingIds?.length ?? 0) > 0 || (sel.roofIds?.length ?? 0) > 0 || (sel.stairIds?.length ?? 0) > 0 || - (sel.roomIds?.length ?? 0) > 0 + (sel.roomIds?.length ?? 0) > 0 || + (sel.treeIds?.length ?? 0) > 0 ); } diff --git a/src/ui/ribbon/CommandIcon.tsx b/src/ui/ribbon/CommandIcon.tsx index 081b8c50..7501b589 100644 --- a/src/ui/ribbon/CommandIcon.tsx +++ b/src/ui/ribbon/CommandIcon.tsx @@ -175,6 +175,24 @@ export const CommandIcon = memo(function CommandIcon({ name }: { name: string }) ); + case "tree": + // [149] Baum: Krone (Kreis) mit Stamm. + return ( + + + + + ); + case "circlestotrees": + // [149] Kreis → Baum. + return ( + + + + + + + ); case "column": // Stütze: Quadrat-Querschnitt mit vertikalen Kanten (Pfeiler). return ( diff --git a/src/viewport/Wasm3DViewport.tsx b/src/viewport/Wasm3DViewport.tsx index f15f17b6..8245d168 100644 --- a/src/viewport/Wasm3DViewport.tsx +++ b/src/viewport/Wasm3DViewport.tsx @@ -82,7 +82,7 @@ import { /** Ein per 3D-Klick getroffenes Bauteil, oder null (Leerraum). */ export type Pick3dHit = - | { kind: "wall" | "ceiling" | "opening" | "stair" | "roof" | "contextObject" | "drawing" | "column" | "solid"; id: string } + | { kind: "wall" | "ceiling" | "opening" | "stair" | "roof" | "contextObject" | "drawing" | "column" | "solid" | "tree"; id: string } | null; /** Klick-vs-Drag-Schwelle (Pixel): bleibt die Maus zwischen pointerdown und @@ -1422,7 +1422,7 @@ export function Wasm3DViewport({ const ndc = toNdc(clientX, clientY); if (!cb || !o || !ndc) return; const ray = cameraRay(orbitCamera(o), ndc.ndcX, ndc.ndcY, ndc.aspect); - const { walls, slabs, openings, stairs, roofs, contextMeshes, drawings, columns, solids, openingMeshes, stairMeshes, drawingMeshes } = pickGeometry( + const { walls, slabs, openings, stairs, roofs, contextMeshes, drawings, columns, solids, openingMeshes, stairMeshes, drawingMeshes, trees } = pickGeometry( projectRef.current, explodeRef.current, ); @@ -1430,7 +1430,7 @@ export function Wasm3DViewport({ // Meshes + freie 2D-Zeichnungen (Linie/Polylinie/Rechteck, s. // `pickDrawingSegs`) — sonst wären im WASM-Viewport 2D-Elemente NIE // anwählbar gewesen (Nutzer-Report). - const hit = pickNearest(ray, walls, slabs, openings, stairs, roofs, contextMeshes, drawings, columns, solids, openingMeshes, stairMeshes, drawingMeshes); + const hit = pickNearest(ray, walls, slabs, openings, stairs, roofs, contextMeshes, drawings, columns, solids, openingMeshes, stairMeshes, drawingMeshes, trees); cb(hit ? { kind: hit.kind, id: hit.id } : null, additive); }; diff --git a/src/viewport/raycast3d.ts b/src/viewport/raycast3d.ts index fcdc15d8..ee2cb10e 100644 --- a/src/viewport/raycast3d.ts +++ b/src/viewport/raycast3d.ts @@ -18,7 +18,7 @@ import { DRAWING_PICK_TOLERANCE } from "../core"; -import type { Vec3, PickWall, PickOpening, PickDrawingSeg, PickSlab, PickStair, PickRoof, PickContextMesh, PickColumnMesh, PickSolidMesh, PickOpeningMesh, PickStairMesh, PickDrawingMesh } from "../core"; +import type { Vec3, PickWall, PickOpening, PickDrawingSeg, PickSlab, PickStair, PickRoof, PickContextMesh, PickColumnMesh, PickSolidMesh, PickOpeningMesh, PickStairMesh, PickDrawingMesh, PickTreeMesh } from "../core"; /** Kamera-Parameter für den Pick-Strahl (Teilmenge von Camera3d). */ export interface RayCamera { @@ -42,7 +42,7 @@ export interface Ray { /** Ergebnis eines Picks: getroffenes Bauteil + Distanz entlang des Strahls. */ export interface PickHit { - kind: "wall" | "ceiling" | "opening" | "stair" | "roof" | "contextObject" | "drawing" | "column" | "solid"; + kind: "wall" | "ceiling" | "opening" | "stair" | "roof" | "contextObject" | "drawing" | "column" | "solid" | "tree"; id: string; t: number; /** Bei `kind:"opening"` dieselbe Id wie `id` (ausdrucksstärkerer Zugriff). */ @@ -362,6 +362,7 @@ export function pickNearest( openingMeshes?: readonly PickOpeningMesh[], stairMeshes?: readonly PickStairMesh[], drawingMeshes?: readonly PickDrawingMesh[], + trees?: readonly PickTreeMesh[], ): PickHit | null; /** * Nächstes getroffenes Bauteil (kleinstes t) über Wände, Decken, Öffnungen und @@ -386,6 +387,7 @@ export function pickNearest( openingMeshes: readonly PickOpeningMesh[] = [], stairMeshes: readonly PickStairMesh[] = [], drawingMeshes: readonly PickDrawingMesh[] = [], + trees: readonly PickTreeMesh[] = [], ): PickHit | null { const TIE_EPS = 1e-6; let hit: PickHit | null = null; @@ -441,6 +443,11 @@ export function pickNearest( const t = rayContextMeshTris(ray, { tris: c.tris, contextObjectId: c.columnId }); if (t !== null) consider({ kind: "column", id: c.columnId, t }, 1); } + // [149] Bäume (Stamm + Krone), Rang wie Wand/Decke. + for (const tr of trees) { + const t = rayContextMeshTris(ray, { tris: tr.tris, contextObjectId: tr.treeId }); + if (t !== null) consider({ kind: "tree", id: tr.treeId, t }, 1); + } // [137] Freie Körper (truck-Netz bzw. Prisma-Näherung), Rang wie Wand/Decke. for (const s of solids) { const t = rayContextMeshTris(ray, { tris: s.tris, contextObjectId: s.solidId }); diff --git a/src/views/plan/PlanView.tsx b/src/views/plan/PlanView.tsx index de601d49..13222b38 100644 --- a/src/views/plan/PlanView.tsx +++ b/src/views/plan/PlanView.tsx @@ -190,7 +190,7 @@ export interface PlanViewHandle { const PICK_ORDER: readonly PickKind[] = [ - "section", "opening", "wall", "column", "drawing", "solid", + "section", "opening", "wall", "column", "drawing", "solid", "tree", "ceiling", "stair", "room", "roof", "site", "context", ]; @@ -221,9 +221,13 @@ const EMPTY_PICK: PickIds = { sectionLineId: null, contextObjectId: null, siteId: null, + treeId: null, }; /** Mac: Cmd+Klick; sonst Strg+Klick (Alt+Klick ist die Schere, Ctrl+Klick unter macOS das Kontextmenü). */ +/** [149] Präfix der Baum-Pick-Id im Feld `contextObjectId` (Kern `tree::TREE_PICK_PREFIX`). */ +const TREE_PICK = "@tree:"; + const IS_MAC = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform); const cycleModifier = (e: { metaKey: boolean; ctrlKey: boolean }): boolean => (IS_MAC ? e.metaKey : e.ctrlKey); @@ -300,6 +304,11 @@ export interface PlanSelection { * wenn kein Element höherer Priorität getroffen wurde; Vorrang vor Kontext-Objekten (sie liegt darüber). */ siteId?: string | null; + /** + * [149] Getroffener Baum (Kronenfläche, Pick-Id `@tree:` im Feld `contextObjectId`), wenn keine + * Öffnung/Wand/Stütze/2D-Element/Körper getroffen wurde; Vorrang vor Decke, Raum, Dach und Gelände. + */ + treeId?: string | null; /** * War beim Klick Shift gedrückt? Dann ERWEITERT der Aufrufer (App) die * Auswahl um das getroffene Element (bzw. schaltet es ab/zu), statt sie zu @@ -687,6 +696,7 @@ export const PlanView = forwardRef( groups: selectedGroupIds, drawings: selectedDrawingIds, site: selectedSite, + trees: selectedTreeIds, } = selection; const selectedDrawingId = single(selection, "drawings"); // Linke Maustaste liegt beim Werkzeug/der Transformation, wenn App das meldet @@ -1613,11 +1623,17 @@ export const PlanView = forwardRef( // [137] Getroffene Lage-Darstellung: Quelle `"sunStudy"`/`"siteRules"` (Baurechtslinie vor Schatten) oder null. const pickSiteAt = (clientX: number, clientY: number): string | null => { - const ids = contextIdsAt(clientX, clientY).filter((id) => id.startsWith("@")); + const ids = contextIdsAt(clientX, clientY).filter((id) => id.startsWith("@") && !id.startsWith(TREE_PICK)); const id = ids.find((x) => x === "@siteRules") ?? ids[0]; return id ? id.slice(1) : null; }; + // [149] Getroffener Baum (oberste Kronenfläche) oder null. + const pickTree = (clientX: number, clientY: number): string | null => { + const id = contextIdsAt(clientX, clientY).find((x) => x.startsWith(TREE_PICK)); + return id ? id.slice(TREE_PICK.length) : null; + }; + const pickContextObject = (clientX: number, clientY: number): string | null => contextIdsAt(clientX, clientY).find((id) => !id.startsWith("@")) ?? null; @@ -2148,27 +2164,30 @@ export const PlanView = forwardRef( openingId || wallId || columnId || drawingId ? null : polyExtrudedSolidId ?? pickExtrudedSolid(clientX, clientY); + // [149] Baum (Kronenfläche) vor Decke, Raum, Dach und Gelände. + const treeId = + openingId || wallId || columnId || drawingId || extrudedSolidId ? null : pickTree(clientX, clientY); // Decke nur, wenn weder Öffnung/Wand noch 2D-Element getroffen wurde. Da die // Decken-Polygone UNTER der Wand-Poché liegen, trifft ein direkter Klick // auf die Wand zuerst die Wand; freie Deckenfläche trifft die Decke. const hitCeilingId = hit && hit.kind === "polygon" ? hit.ceilingId ?? null : null; const ceilingId = - openingId || wallId || columnId || drawingId || extrudedSolidId ? null : hitCeilingId; + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId ? null : hitCeilingId; // Treppe nur, wenn nichts anderes getroffen wurde (Tritte liegen frei). const stairId = - openingId || wallId || columnId || drawingId || extrudedSolidId || ceilingId + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId ? null : pickStair(clientX, clientY); // Raum als vorletzte Priorität: die Raum-Fläche liegt UNTER allem anderen. const roomId = - openingId || wallId || columnId || drawingId || extrudedSolidId || ceilingId || stairId + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId || stairId ? null : pickRoom(clientX, clientY); // Dach als LETZTE Priorität: die Traufe-Fläche deckt den ganzen Grundriss // ab, daher erst wählen, wenn wirklich nichts anderes getroffen wurde. const roofId = - openingId || wallId || columnId || drawingId || extrudedSolidId || ceilingId || stairId || roomId + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId || stairId || roomId ? null : pickRoof(clientX, clientY); // Kontext-Objekt (Gebäude/Terrain) als ALLERLETZTE Priorität — seine @@ -2176,11 +2195,11 @@ export const PlanView = forwardRef( // nichts anderes getroffen wurde. // [137] Schatten/Baurechtslinien (Lage-Darstellung) über dem Gelände, unter allen Bauteilen. const siteId = - openingId || wallId || columnId || drawingId || extrudedSolidId || ceilingId || stairId || roomId || roofId + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId || stairId || roomId || roofId ? null : pickSiteAt(clientX, clientY); const contextObjectId = - openingId || wallId || columnId || drawingId || extrudedSolidId || ceilingId || stairId || roomId || roofId || siteId + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId || stairId || roomId || roofId || siteId ? null : pickContextObject(clientX, clientY); return { @@ -2197,6 +2216,7 @@ export const PlanView = forwardRef( sectionLineId: null, contextObjectId, siteId, + treeId, }; }; @@ -2327,6 +2347,7 @@ export const PlanView = forwardRef( add("column", dp.columnId, dp.hitIndex); add("drawing", dp.drawingId, dp.hitIndex); add("solid", dp.extrudedSolidId, dp.hitIndex); + add("tree", dp.treeId, dp.hitIndex); add("ceiling", dp.ceilingId, dp.hitIndex); add("stair", dp.stairId, dp.hitIndex); add("room", dp.roomId, dp.hitIndex); @@ -2353,7 +2374,8 @@ export const PlanView = forwardRef( addRest("stair", p.stairId, idx); addRest("room", p.roomId, idx); addRest("roof", p.roofId, idx); - if (p.contextObjectId?.startsWith("@")) addRest("site", p.contextObjectId.slice(1), idx); + if (p.contextObjectId?.startsWith(TREE_PICK)) addRest("tree", p.contextObjectId.slice(TREE_PICK.length), idx); + else if (p.contextObjectId?.startsWith("@")) addRest("site", p.contextObjectId.slice(1), idx); else addRest("context", p.contextObjectId, idx); addRest("section", p.sectionLineId, idx); } @@ -2364,6 +2386,7 @@ export const PlanView = forwardRef( addRest("stair", pickStair(clientX, clientY), null); addRest("room", pickRoom(clientX, clientY), null); addRest("roof", pickRoof(clientX, clientY), null); + addRest("tree", pickTree(clientX, clientY), null); addRest("site", pickSiteAt(clientX, clientY), null); addRest("context", pickContextObject(clientX, clientY), null); addRest("section", pickSectionLine(clientX, clientY), null); @@ -2401,6 +2424,7 @@ export const PlanView = forwardRef( sectionLineId: c.kind === "section" ? c.id : null, contextObjectId: c.kind === "context" ? c.id : null, siteId: c.kind === "site" ? c.id : null, + treeId: c.kind === "tree" ? c.id : null, }); }; @@ -2930,10 +2954,14 @@ export const PlanView = forwardRef( // überzeichnen — analog zur Dach-/Raum-Auswahl. // [137] Gewählte Lage-Darstellung (Schatten/Baurecht): ihre Flächen bzw. Bänder (`@…`-Ids) ebenso. const highlightContextObjectPolys = useMemo(() => { - const ids = [...(selectedContextObjectIds ?? []), ...(selectedSite ?? []).map((s) => "@" + s)]; + const ids = [ + ...(selectedContextObjectIds ?? []), + ...(selectedSite ?? []).map((s) => "@" + s), + ...(selectedTreeIds ?? []).map((s) => TREE_PICK + s), + ]; if (!ids.length) return []; return primsOwnedBy("contextObjectId", ids, (p): p is Extract => p.kind === "polygon"); - }, [plan, selectedContextObjectIds, selectedSite]); + }, [plan, selectedContextObjectIds, selectedSite, selectedTreeIds]); // Hervorhebung der selektierten Schnitt-/Ansichtslinie: das (unsichtbare) // Pick-Band (Polygon mit sectionLineId) mit Akzentkontur überzeichnen. @@ -2971,7 +2999,8 @@ export const PlanView = forwardRef( const hoverPrims = useMemo((): Primitive[] => { if (!hoverPick) return []; if (hoverPick.kind === "site") return primsOwnedBy("contextObjectId", ["@" + hoverPick.id], (_p): _p is Primitive => true); - const field: Record, OwnerField> = { + if (hoverPick.kind === "tree") return primsOwnedBy("contextObjectId", [TREE_PICK + hoverPick.id], (_p): _p is Primitive => true); + const field: Record, OwnerField> = { wall: "wallId", drawing: "drawingId", ceiling: "ceilingId", opening: "openingId", stair: "stairId", room: "roomId", roof: "roofId", context: "contextObjectId", section: "sectionLineId", solid: "extrudedSolidId", column: "columnId", diff --git a/src/views/plan/pickCycle.ts b/src/views/plan/pickCycle.ts index 2e890692..4ffffb87 100644 --- a/src/views/plan/pickCycle.ts +++ b/src/views/plan/pickCycle.ts @@ -34,6 +34,7 @@ const KIND_FIELD: Record = { column: "columns", drawing: "drawings", solid: "solids", + tree: "trees", ceiling: "ceilings", stair: "stairs", room: "rooms", diff --git a/src/views/viewportContent.tsx b/src/views/viewportContent.tsx index 4089c6c8..c1c41728 100644 --- a/src/views/viewportContent.tsx +++ b/src/views/viewportContent.tsx @@ -280,7 +280,7 @@ export const Content = memo(function Content({ () => (explode > 0 ? (explodeFloorOffsets(project, explode)[level.id] ?? 0) : 0), [project, explode, level.id], ); - const { walls, ceilings, openings, stairs, roofs, contextObjects, columns, solids } = selection; + const { walls, ceilings, openings, stairs, roofs, contextObjects, columns, solids, trees } = selection; const selectionLines = useMemo( () => walls.length === 0 && @@ -290,10 +290,11 @@ export const Content = memo(function Content({ roofs.length === 0 && contextObjects.length === 0 && columns.length === 0 && - solids.length === 0 + solids.length === 0 && + trees.length === 0 ? null - : selectionHighlightLines(project, walls, ceilings, HIGHLIGHT_RGB, openings, stairs, roofs, contextObjects, explode, columns, solids), - [project, explode, walls, ceilings, openings, stairs, roofs, contextObjects, columns, solids], + : selectionHighlightLines(project, walls, ceilings, HIGHLIGHT_RGB, openings, stairs, roofs, contextObjects, explode, columns, solids, trees), + [project, explode, walls, ceilings, openings, stairs, roofs, contextObjects, columns, solids, trees], ); // Kollisionen der letzten Prüfung: rote Hüllquader zusätzlich zur Auswahl-Hervorhebung. const highlightLines = useMemo(() => {