diff --git a/TODO.md b/TODO.md index fb4ca898..843c02f3 100644 --- a/TODO.md +++ b/TODO.md @@ -10,7 +10,7 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `* stehen im Archiv („Bewusst nicht übernommen“). - **Grösse** (eine Person mit Agenten): S ≤ 1 Tag · M ≤ 1 Woche · L ≤ 1 Monat · XL > 1 Monat. Steht keine Grösse im Archiv, ist sie hier geschätzt. -- **IDs sind stabil.** Neue ID = nächste freie Zahl nach der höchsten im Archiv und hier (aktuell 202); +- **IDs sind stabil.** Neue ID = nächste freie Zahl nach der höchsten im Archiv und hier (aktuell 214); nie eine ID wiederverwenden oder umnummerieren. Präfix-IDs (`[K]`, `[G]`, `[T]`, `[B]`, `[C]`) bleiben. - **Pro Punkt:** was fehlt · wo im Code · Grösse. Höchstens ein bis drei Sätze je Punkt; Messwerte und Befunde gehören in den Commit. @@ -44,6 +44,18 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `* ## Grundriss +- ◐ **[213]** Kameras und Begehen im 3D (12.11., Wunsch Maintainer; ersetzt den offenen Eintrag in „Release 1.0“). Umgesetzt: Modell `Project.cameras` + (Rust `Camera`: Name, Geschoss, Standpunkt + Augenhöhe über Geschoss, Ziel + Zielhöhe, Bildwinkel/Brennweite, Perspektive/Axonometrie/Parallel, + Sichthöhe, Sonnenstand als ISO-Zeit; Klasse „Kameras“ Code 92, `standards::CAMERA_CATEGORY`); Ops über die gewöhnlichen Helfer. Grundriss-Symbol im Kern + (`plan/cameras.rs`: Gehäuse mit Objektiv, Sichtkegel bzw. Streifen, Ziel mit Blicklinie, Name; Pick-Bänder `@camera:`, nur Gehäuse/Kanten/Ziel, + nicht der ganze Kegel); Griffe im Kern (`camera.rs`/`grips.rs`: Standpunkt, Ziel, Bildwinkel bzw. Sichtbreite, `cameraGrip`/`cameraBy`); + Objekt-Info-Abschnitt `CameraSection` (Werte, Brennweite ↔ Bildwinkel, Sonne, „Kamera öffnen“, „Aus aktueller Ansicht“, „Isometrisch“); Liste mit Anlegen/Öffnen/Löschen im + Panel „Ausschnitte“ (`CamerasGroup`); 3D: Knopf „Kamera+“ legt aus der aktuellen Ansicht an, Doppelklick auf das Symbol im Grundriss bzw. „Kamera öffnen“ setzt die 3D-Ansicht + exakt (Reiterwechsel, Sonnenstudie übernimmt `sunWhen`); `viewport/cameraView.ts::cameraToView(project, camera)` liefert dieselbe `ViewCamera` wie `getCamera()` + (Anschluss für das Rendering [211]: `cameraToView` statt der Live-Ansicht). Begehen: Umschalt+F bzw. Knopf „Begehen“, darin W/A/S/D und Pfeile gehen (horizontal, Augenhöhe bleibt), + Q/E runter/hoch, Umschalt ×4, Alt ×0.25, Maus (links oder rechts) schaut um den Augpunkt, Esc beendet; die Tasten gelten nur im Modus (sonst kollidieren sie mit S/D/Q, [190]), pro Frame mit + gekapptem Zeitschritt (`viewport/walk.ts`). Beispiel: Kamera „Südost“ im Musterhaus komplex. Offen: nicht in der Tauri-App geprüft (3D headless leer, Kamera-Brücke nur per Zustand); nativer Mac-3D ohne + Begehen/Kameras (`native.rs` ist Linux/winit); Kameras fehlen in Verschieben/Kopieren/Gruppen/IFC/Zwischenablage; Stil „Sonne am Tag“ (Datum/Uhrzeit-Dialog) und Animation entlang mehrerer Kameras. · M - ○ **[205]** Pausfolie/Referenz wie Archicad „Trace & Reference“ (12.11., Wunsch Maintainer): hinter die aktive Ansicht (Grundriss, Schnitt, Ansicht, Zeichnungsblatt/Layout) eine beliebige andere Ansicht als halbtransparente Pause legen — anderes Geschoss, Schnitt, Ansicht, Detail, Blatt; Quelle frei wählbar (nicht nur „Andere grau“ aller Geschosse, [203]), Farbe/Deckkraft, verschieben/drehen der Pause (ohne das Modell zu ändern), ein/aus per Kürzel und in der Ansichtsleiste; Pause nicht anwählbar; auch umgekehrt Grundriss hinter Schnitt (Höhenbezug) prüfen. Opus. · L - ◐ **[182]** Tabs/Ansichten wie Archicad (11.11., Wunsch Maintainer). Umgesetzt: Reiter-Arten Grundriss · 3D · Schnitt · Ansicht · 2D-Zeichnung/Layout werden nie gemischt (`navigateToLevel`/`switchViewKind` in `state/viewTabs.ts`, Anwendung in diff --git a/doc/ARCHITEKTUR.md b/doc/ARCHITEKTUR.md index ad495679..b89d3148 100644 --- a/doc/ARCHITEKTUR.md +++ b/doc/ARCHITEKTUR.md @@ -833,7 +833,7 @@ Reines Verschieben, ohne Verhaltensänderung (gleiche Abhängigkeitslisten, glei |---|---| | `src/views/plan/PlanView.tsx` (3902 Zeilen) | rund 1400 Zeilen: Props, Zustand, Hook-Aufrufe, SVG-Ebene. Typen und Konstanten in `planView/types.ts`, `planView/constants.ts`; Hooks `usePlanEngine`, `usePlanCoords`, `usePlanPicking`, `usePlanPointer`, `usePlanPickCycle`, `usePlanZoomInput`, `usePlanHighlights` in `planView/` (je 130 bis 680 Zeilen) | | `src-tauri/core/src/plan/elevation.rs` (3226 Zeilen) | Ordner `plan/elevation/`: `mod.rs` (Konstanten, Orchestrierung, Abfrage), `face`, `cull`, `collect`, `mesh_cull`, `openings`, `silhouette`, `patterns`, `tests`; `fascia_quads()` und `corner_shifts()` bleiben über `plan::elevation::` erreichbar | -| `src/panels/ObjectInfoPanel.tsx` (2847 Zeilen) | rund 370 Zeilen; Abschnitte je Element-Art in `src/panels/objectInfo/` (`WallSection`, `CeilingSection`, `RoofSections`, `OpeningSections`, `StairSection`, `RoomSection`, `SolidSections`, `SectionLineSection`, `RefSections`, `TreeSection`, `fields`, `InfoBlocks`) | +| `src/panels/ObjectInfoPanel.tsx` (2847 Zeilen) | rund 370 Zeilen; Abschnitte je Element-Art in `src/panels/objectInfo/` (`WallSection`, `CeilingSection`, `RoofSections`, `OpeningSections`, `StairSection`, `RoomSection`, `SolidSections`, `SectionLineSection`, `RefSections`, `TreeSection`, `CameraSection`, `fields`, `InfoBlocks`) | Zwei Stellen in `PlanView` wurden dafür umgestellt, weil ein Hook nur zusammenhängende Anweisungen aufnimmt: der Aufräum-Effekt für den ausstehenden Pan steht jetzt bei `panRaf` (in `usePlanPointer`), die Hover-Teilpunkte (Zustand, Funktionen, zwei Effekte) bei den diff --git a/e2e/camera.spec.ts b/e2e/camera.spec.ts new file mode 100644 index 00000000..87793363 --- /dev/null +++ b/e2e/camera.spec.ts @@ -0,0 +1,89 @@ +// [213] Kameras: im Musterhaus komplex liegt die Kamera „Südost" — ihr Symbol (Gehäuse, Sichtkegel, Ziel) steht im +// EG-Grundriss, die Kamera lässt sich in der Liste wählen (Objekt-Info), „Kamera öffnen" wechselt in den 3D-Reiter. +// (Dass die Klasse „Kameras" das Symbol ausblendet, prüft der Kern-Test `plan::cameras`.) Aus der 3D-Ansicht lässt sich eine neue Kamera anlegen. +// WebGPU ist headless oft leer: ist der 3D-Viewport nicht bereit, wird auf Reiter und Hinweis geprüft statt auf die Kamera. +// Eigener Port: E2E_PORT=5191 npx playwright test e2e/camera.spec.ts +import type { Page } from "@playwright/test"; +import type {} from "../src/state/testHooks"; // Typ von window.__dossierTest +import { discardIfAsked, drawingTab, expect, fileMenu, openTab, showSnapshot, test } from "./app"; + +async function openKomplex(page: Page): Promise { + await page.goto("/?dossierTest"); + await page.getByRole("button", { name: /Neues Projekt/ }).first().click(); + await expect(page.getByRole("group", { name: "Befehlszeile" })).toBeVisible(); + await fileMenu(page, /Musterhaus \(komplex\)/); + await discardIfAsked(page); + await expect(page.locator(".project-name")).toHaveText("Musterhaus komplex", { timeout: 30_000 }); + await showSnapshot(page, "EG 1:100"); + await expect(page.locator("svg.plan-svg").first()).toBeVisible({ timeout: 30_000 }); +} + +test("Kamera im Grundriss sehen, wählen, öffnen", async ({ page }) => { + test.setTimeout(120_000); + await openKomplex(page); + + // Symbol im EG-Grundriss (Sichtkegel-Linien der Klasse „camera-cone"). + await expect.poll(() => page.evaluate(() => window.__dossierTest?.planLines("camera-cone") ?? 0), { timeout: 20_000 }).toBeGreaterThan(0); + + // Kameraliste im Panel „Ausschnitte"; Klick wählt, die Objekt-Info zeigt die Werte. + await openTab(page, "Ausschnitte"); + const row = page.getByTestId("camera-row-kamera-suedost"); + await expect(row).toContainText("Südost"); + await row.click(); + await openTab(page, "Objekt-Info"); + const section = page.getByTestId("camera-section"); + await expect(section).toBeVisible(); + await expect(section.getByTestId("camera-name")).toHaveValue("Südost"); + + // Name ändern und rückgängig machen. + await section.getByTestId("camera-name").fill("Abendblick"); + await section.getByTestId("camera-name").press("Enter"); + await expect(section.getByTestId("camera-name")).toHaveValue("Abendblick"); + await page.locator("body").click({ position: { x: 5, y: 5 } }); + await page.keyboard.press("ControlOrMeta+z"); + await expect(section.getByTestId("camera-name")).toHaveValue("Südost"); + + // Kamera öffnen → 3D-Reiter. + await section.getByTestId("camera-open").click(); + await expect(drawingTab(page, "3D · Erdgeschoss")).toHaveAttribute("aria-selected", "true", { timeout: 20_000 }); + const live = await page + .waitForFunction(() => (window as unknown as { __dossierCamera?: unknown }).__dossierCamera !== undefined, undefined, { timeout: 8_000 }) + .then(() => true, () => false); + if (live) { + // Der Viewport ist bereit: die Ansicht sitzt exakt auf der Kamera (Standpunkt 17 / −3, Augenhöhe 1.6 über OK EG). + await expect + .poll( + async () => + page.evaluate(() => { + const c = (window as unknown as { __dossierCamera: { getCamera: () => { position: number[]; kind: string } | null } }).__dossierCamera.getCamera(); + return c ? [...c.position.map((v) => Math.round(v * 100) / 100), c.kind] : null; + }), + { timeout: 10_000 }, + ) + .toEqual([17, -3, expect.any(Number), "perspective"]); + } +}); + +test("Kamera aus der 3D-Ansicht anlegen", async ({ page }) => { + test.setTimeout(120_000); + await openKomplex(page); + // In den 3D-Reiter und dort „Kamera aus aktueller Ansicht anlegen" (Knopf oben rechts). + await showSnapshot(page, "Axonometrie Südost"); + const create = page.getByTestId("camera-create-3d"); + await expect(create).toBeVisible({ timeout: 30_000 }); + await create.click(); + const ready = await page + .waitForFunction(() => (window as unknown as { __dossierCamera?: unknown }).__dossierCamera !== undefined, undefined, { timeout: 5_000 }) + .then(() => true, () => false); + await openTab(page, "Ausschnitte"); + if (ready) { + await expect(page.locator("[data-testid^=camera-row-]")).toHaveCount(2); + } else { + // Ohne WebGPU gibt es keine Kamera zum Lesen: der Hinweis sagt es, es entsteht nichts. + await expect(page.locator("[data-testid^=camera-row-]")).toHaveCount(1); + } + + // Zurück in den Grundriss: das Symbol ist da. + await showSnapshot(page, "EG 1:100"); + await expect.poll(() => page.evaluate(() => window.__dossierTest?.planLines("camera-cone") ?? 0), { timeout: 20_000 }).toBeGreaterThan(0); +}); diff --git a/src-tauri/core/src/README.md b/src-tauri/core/src/README.md index ae74a655..b5b09584 100644 --- a/src-tauri/core/src/README.md +++ b/src-tauri/core/src/README.md @@ -63,7 +63,7 @@ Neues Modul: `.rs` und `mod` in `lib.rs`, Bindungen in `web/.rs` u | `mesh_section.rs`, `mesh_view.rs`, `mesh_repair.rs` | Ebenenschnitt beliebiger Netze; importierte Netze; Netz-Reparatur | | `voids.rs` | Abzugskörper in Grundriss und Schnitt | | `surface_pattern.rs` | Ansichtsschraffur (Lattung, Verband, Schindeln …) | -| `grid.rs`, `tree.rs`, `auto_dimensions.rs` | Achsraster, Bäume, automatische Aussenbemassung | +| `grid.rs`, `tree.rs`, `camera.rs`, `auto_dimensions.rs` | Achsraster, Bäume, Kameras (Auflösung, Griffe, Brennweite), automatische Aussenbemassung | ## Befehle, Griffe, Auswahl, Verwaltung diff --git a/src-tauri/core/src/camera.rs b/src-tauri/core/src/camera.rs new file mode 100644 index 00000000..ba0d3ef8 --- /dev/null +++ b/src-tauri/core/src/camera.rs @@ -0,0 +1,236 @@ +//! [213] Kameras (`Project.cameras`): Auflösung zu Augpunkt, Ziel und Blickrichtung in Modell-Koordinaten +//! (z oben, Meter), Brennweite ↔ Bildwinkel. Das Planzeichen entsteht in `plan/cameras.rs`; die TS-Seite +//! (`src/model/cameraView.ts`) liefert daraus die Ansicht der 3D-Kamera (`cameraToView`). + +use crate::jsnum; +use crate::model::*; + +/// Präfix der Pick-Id im Feld `contextObjectId` der Plan-Primitive (`@` = keine Kontext-Element-Id). +pub const CAMERA_PICK_PREFIX: &str = "@camera:"; +/// Vorgabe der Augenhöhe über dem Geschoss (m) und des vertikalen Bildwinkels (Grad; wie `FOV_Y` des 3D). +pub const DEFAULT_EYE_HEIGHT: f64 = 1.6; +pub const DEFAULT_FOV_DEG: f64 = 50.0; +/// Sichthöhe bei Axonometrie/Parallel ohne Angabe (m). +pub const DEFAULT_ORTHO_HEIGHT: f64 = 10.0; +/// Bildverhältnis für den Sichtkegel im Grundriss (Breite/Höhe). +pub const ASPECT: f64 = 16.0 / 9.0; +/// Sensorhöhe für die Kleinbild-Brennweite (mm). +pub const SENSOR_HEIGHT_MM: f64 = 24.0; +/// Bildwinkel-Grenzen (Grad), wie `camera3dFromViewCamera`. +pub const MIN_FOV_DEG: f64 = 5.0; +pub const MAX_FOV_DEG: f64 = 120.0; + +/// Aufgelöste Kamera in Modell-Koordinaten. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CameraGeom { + pub eye: [f64; 3], + pub target: [f64; 3], + /// Grundriss-Richtung (Bogenmass, 0 = +x), aus Standpunkt → Ziel. + pub yaw: f64, + /// Abstand Standpunkt → Ziel im Grundriss (m, ≥ 0). + pub plan_dist: f64, + pub fov_deg: f64, + pub perspective: bool, + pub ortho_height: f64, +} + +/// Brennweite (mm, Kleinbild, 24 mm Sensorhöhe) zum vertikalen Bildwinkel. +pub fn focal_mm(fov_deg: f64) -> f64 { + SENSOR_HEIGHT_MM / 2.0 / jsnum::tan(fov_deg.to_radians() / 2.0) +} + +/// Vertikaler Bildwinkel (Grad) zur Brennweite (mm). +pub fn fov_deg_from_focal(mm: f64) -> f64 { + 2.0 * jsnum::atan(SENSOR_HEIGHT_MM / 2.0 / mm).to_degrees() +} + +/// Bildwinkel in den zulässigen Bereich (Vorgabe bei NaN/≤ 0). +pub fn clamp_fov(fov_deg: f64) -> f64 { + if fov_deg.is_finite() && fov_deg > 0.0 { + fov_deg.clamp(MIN_FOV_DEG, MAX_FOV_DEG) + } else { + DEFAULT_FOV_DEG + } +} + +impl CameraGeom { + /// Auflösung gegen das Projekt; `None` bei unbrauchbarer Lage (NaN). + pub fn of(p: &Project, c: &Camera) -> Option { + let floor_z = p.floor(&c.floor_id).and_then(|l| l.base_elevation).filter(|z| z.is_finite()).unwrap_or(0.0); + Self::at(c, floor_z) + } + + /// Wie [`CameraGeom::of`] mit gegebener Höhe der Geschoss-OK. + pub fn at(c: &Camera, floor_z: f64) -> Option { + let eye_h = if c.eye_height.is_finite() { c.eye_height } else { DEFAULT_EYE_HEIGHT }; + let (px, py, tx, ty, tz) = (c.position.x, c.position.y, c.target.x, c.target.y, c.target_height); + if ![px, py, tx, ty, tz].iter().all(|v| v.is_finite()) { + return None; + } + let (dx, dy) = (tx - px, ty - py); + let plan_dist = dx.hypot(dy); + let eye_z = floor_z + eye_h; + Some(CameraGeom { + eye: [px, py, eye_z], + target: [tx, ty, tz], + yaw: if plan_dist > 1e-9 { jsnum::atan2(dy, dx) } else { 0.0 }, + plan_dist, + fov_deg: clamp_fov(c.fov_deg), + perspective: c.projection == CameraProjection::Perspective || c.projection == CameraProjection::Unknown, + ortho_height: c.ortho_height.filter(|h| h.is_finite() && *h > 0.0).unwrap_or(DEFAULT_ORTHO_HEIGHT), + }) + } + + /// Blickrichtung (normiert); `None`, wenn Standpunkt und Ziel zusammenfallen. + pub fn direction(&self) -> Option<[f64; 3]> { + let d = [self.target[0] - self.eye[0], self.target[1] - self.eye[1], self.target[2] - self.eye[2]]; + let l = d[0].hypot(d[1]).hypot(d[2]); + (l > 1e-9).then(|| [d[0] / l, d[1] / l, d[2] / l]) + } +} + +/// Griffe im Grundriss (Modell-Meter) beim Massstab 1:`scale`: 0 Standpunkt, 1 Ziel, 2 rechter Rand der fernen +/// Sichtlinie (Perspektive: Bildwinkel, Axonometrie/Parallel: Sichtbreite). +pub fn grip_points(c: &Camera, scale: f64) -> Vec<(f64, f64)> { + let Some(g) = CameraGeom::at(c, 0.0) else { return vec![] }; + let a = crate::plan::cameras::view_area(&g, if scale.is_finite() && scale > 0.0 { scale / 1000.0 } else { 0.1 }); + vec![(g.eye[0], g.eye[1]), (g.target[0], g.target[1]), (a[2].x, a[2].y)] +} + +/// Kamera nach dem Ziehen des Griffs `index` an `(x, y)`; `None` bei unbekanntem Griff oder NaN. +/// 0 setzt den Standpunkt (Ziel bleibt), 1 das Ziel, 2 den Bildwinkel (Perspektive: aus dem Winkel zur Blickachse, +/// 5° bis 120° vertikal) bzw. die Sichtbreite (Axonometrie/Parallel: aus dem Abstand zur Blickachse). +pub fn grip_edit(c: &Camera, index: f64, x: f64, y: f64) -> Option { + if !(x.is_finite() && y.is_finite()) { + return None; + } + let g = CameraGeom::at(c, 0.0)?; + let mut n = c.clone(); + match index { + i if i == 0.0 => n.position = Vec2 { x, y }, + i if i == 1.0 => n.target = Vec2 { x, y }, + i if i == 2.0 => { + let (dx, dy) = (x - g.eye[0], y - g.eye[1]); + if g.perspective { + if dx.hypot(dy) < 1e-9 { + return None; + } + let mut a = jsnum::atan2(dy, dx) - g.yaw; + a = jsnum::atan2(jsnum::sin(a), jsnum::cos(a)).abs(); + let h = a.clamp(0.5_f64.to_radians(), 75.0_f64.to_radians()); + n.fov_deg = clamp_fov((2.0 * jsnum::atan(jsnum::tan(h) / ASPECT)).to_degrees()); + } else { + let side = (-jsnum::sin(g.yaw)) * dx + jsnum::cos(g.yaw) * dy; + n.ortho_height = Some((2.0 * side.abs() / ASPECT).max(0.1)); + } + } + _ => return None, + } + Some(n) +} + +/// Kamera um `(dx, dy)` verschoben (Standpunkt und Ziel). +pub fn moved(c: &Camera, dx: f64, dy: f64) -> Option { + if !(dx.is_finite() && dy.is_finite()) { + return None; + } + let mut n = c.clone(); + n.position = Vec2 { x: c.position.x + dx, y: c.position.y + dy }; + n.target = Vec2 { x: c.target.x + dx, y: c.target.y + dy }; + Some(n) +} + +/// Bezeichnung (Objekt-Info, Beschriftung): Name, sonst „Kamera". +pub fn label(c: &Camera) -> String { + let n = c.name.trim(); + if n.is_empty() { "Kamera".to_string() } else { n.to_string() } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn camera(json: serde_json::Value) -> Camera { + let mut base = serde_json::json!({ + "id": "k1", "type": "camera", "name": "Süd", "floorId": "eg", "categoryCode": "92", "position": {"x": 1, "y": 2}, + "eyeHeight": 1.6, "target": {"x": 1, "y": 12}, "targetHeight": 1.6, "fovDeg": 50, "projection": "perspective" + }); + for (k, v) in json.as_object().unwrap() { + base[k] = v.clone(); + } + serde_json::from_value(base).unwrap() + } + + fn project() -> Project { + serde_json::from_value(serde_json::json!({ + "id": "p", "name": "p", "walls": [], "layers": [], + "drawingLevels": [{"id": "eg", "name": "EG", "kind": "floor", "visible": true, "locked": false, "baseElevation": 3.0}] + })) + .unwrap() + } + + #[test] + fn augenhoehe_ueber_geschoss_und_richtung() { + let g = CameraGeom::of(&project(), &camera(serde_json::json!({}))).unwrap(); + assert_eq!(g.eye, [1.0, 2.0, 4.6]); + assert!((g.yaw - std::f64::consts::FRAC_PI_2).abs() < 1e-12); + assert!((g.plan_dist - 10.0).abs() < 1e-12); + assert!(g.perspective); + let d = g.direction().unwrap(); + assert!(d[1] > 0.9 && d[2] < 0.0, "Ziel liegt tiefer als das Auge"); + } + + #[test] + fn ohne_geschoss_null_und_nan_verworfen() { + let g = CameraGeom::of(&Project::default(), &camera(serde_json::json!({"projection": "parallel", "orthoHeight": 6}))).unwrap(); + assert_eq!(g.eye[2], 1.6); + assert!(!g.perspective); + assert_eq!(g.ortho_height, 6.0); + let mut c = camera(serde_json::json!({})); + c.position.x = f64::NAN; + assert!(CameraGeom::of(&project(), &c).is_none()); + } + + #[test] + fn brennweite_und_bildwinkel_umkehrbar() { + assert!((focal_mm(fov_deg_from_focal(35.0)) - 35.0).abs() < 1e-9); + // 24 mm Sensorhöhe, 35 mm Brennweite: rund 37.8°. + assert!((fov_deg_from_focal(35.0) - 37.85).abs() < 0.05); + assert_eq!(clamp_fov(f64::NAN), DEFAULT_FOV_DEG); + assert_eq!(clamp_fov(500.0), MAX_FOV_DEG); + } + + #[test] + fn griffe_standpunkt_ziel_winkel() { + let c = camera(serde_json::json!({})); + let pts = grip_points(&c, 100.0); + assert_eq!(pts.len(), 3); + assert_eq!(pts[0], (1.0, 2.0)); + assert_eq!(pts[1], (1.0, 12.0)); + // Ziehen des Winkel-Griffs auf den heutigen Punkt ändert den Bildwinkel nicht. + let same = grip_edit(&c, 2.0, pts[2].0, pts[2].1).unwrap(); + assert!((same.fov_deg - 50.0).abs() < 1e-9, "{}", same.fov_deg); + // Weiter öffnen: 45° zur Blickachse ergibt einen grösseren Bildwinkel. + let wide = grip_edit(&c, 2.0, 1.0 + 10.0, 2.0 + 10.0).unwrap(); + assert!(wide.fov_deg > 50.0); + assert_eq!(grip_edit(&c, 0.0, 5.0, 6.0).unwrap().position, Vec2 { x: 5.0, y: 6.0 }); + assert_eq!(grip_edit(&c, 1.0, 5.0, 6.0).unwrap().target, Vec2 { x: 5.0, y: 6.0 }); + assert!(grip_edit(&c, 7.0, 0.0, 0.0).is_none()); + assert!(grip_edit(&c, 0.0, f64::NAN, 0.0).is_none()); + // Parallelprojektion: Sichtbreite aus dem Abstand zur Achse. + let par = camera(serde_json::json!({"projection": "parallel", "orthoHeight": 4})); + let w = grip_points(&par, 100.0)[2]; + let edit = grip_edit(&par, 2.0, w.0 - 1.0, w.1).unwrap(); + assert!((edit.ortho_height.unwrap() - 2.0 * (4.0 * ASPECT / 2.0 + 1.0) / ASPECT).abs() < 1e-9); + let m = moved(&c, 1.0, -1.0).unwrap(); + assert_eq!((m.position, m.target), (Vec2 { x: 2.0, y: 1.0 }, Vec2 { x: 2.0, y: 11.0 })); + } + + #[test] + fn modell_aus_json_verlustfrei() { + let c = camera(serde_json::json!({"sunWhen": "2026-06-21T08:00:00Z", "orthoHeight": 8})); + let back: Camera = serde_json::from_value(serde_json::to_value(&c).unwrap()).unwrap(); + assert_eq!(back, c); + assert_eq!(label(&Camera::default()), "Kamera"); + } +} diff --git a/src-tauri/core/src/geo_rebase.rs b/src-tauri/core/src/geo_rebase.rs index 93273cdd..bd814a26 100644 --- a/src-tauri/core/src/geo_rebase.rs +++ b/src-tauri/core/src/geo_rebase.rs @@ -118,6 +118,10 @@ pub fn translate_project(p: &Project, dx: f64, dy: f64) -> Project { for t in out.trees.iter_mut().flatten() { t.position = shift(t.position, dx, dy); } + for c in out.cameras.iter_mut().flatten() { + c.position = shift(c.position, dx, dy); + c.target = shift(c.target, dx, dy); + } if let Some(r) = &mut out.site_rules { shift_all(&mut r.parcel, dx, dy); for l in r.building_lines.iter_mut().flatten() { diff --git a/src-tauri/core/src/geo_translate.rs b/src-tauri/core/src/geo_translate.rs index 49e2b4c8..a35a10a8 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; 11] = ["walls", "ceilings", "roofs", "stairs", "rooms", "columns", "extrudedSolids", "drawings2d", "context", "drawingLevels", "trees"]; +pub const TRANSLATED_LISTS: [&str; 12] = ["walls", "ceilings", "roofs", "stairs", "rooms", "columns", "extrudedSolids", "drawings2d", "context", "drawingLevels", "trees", "cameras"]; 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); @@ -164,6 +164,7 @@ fn shift_element(key: &str, e: &Value, dx: f64, dy: f64) -> (Value, bool) { } "columns" => shift_pts_fields(&mut m, &["position"], dx, dy, &[]), "trees" => shift_pts_fields(&mut m, &["position"], dx, dy, &[]), + "cameras" => shift_pts_fields(&mut m, &["position", "target"], 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/grips.rs b/src-tauri/core/src/grips.rs index 9e5c5c8b..4637eb7e 100644 --- a/src-tauri/core/src/grips.rs +++ b/src-tauri/core/src/grips.rs @@ -282,6 +282,19 @@ pub fn run(lk: &Lookup, req: &Request) -> Result { .into() } } + // [213] Kamera: Griff 0 Standpunkt, 1 Ziel, 2 Bildwinkel/Sichtbreite; `cameraBy` verschiebt Standpunkt und Ziel. + "cameraGrip" | "cameraBy" => { + let (index, (x, y), (dx, dy)) = (r.n("index"), r.p("pt"), r.p("delta")); + patch("cameras", r.s("id"), &|e| { + if truthy(field(e, "locked")) { + return None; + } + let cam: crate::model::Camera = serde_json::from_value(e.clone()).ok()?; + let next = if op == "cameraGrip" { crate::camera::grip_edit(&cam, index, x, y)? } else { crate::camera::moved(&cam, dx, dy)? }; + serde_json::to_value(next).ok() + }) + .into() + } "ceilingGrip" | "roomGrip" => { let (coll, field) = if op == "ceilingGrip" { ("ceilings", "outline") } else { ("rooms", "boundary") }; let (index, (x, y)) = (r.n("index"), r.p("pt")); diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 9e0e690e..cc4257d9 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -20,6 +20,7 @@ pub mod roof_parapet; pub mod flat_read; pub mod sun; pub mod tree; +pub mod camera; pub mod site_rules; pub mod auto_dimensions; pub mod kennzahlen; diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 3b9096eb..fcb546e4 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -4885,6 +4885,71 @@ pub struct Tree { pub extra: Extra, } +/// Projektion einer Kamera ([213]): Perspektive, Axonometrie (Parallelprojektion mit schrägem Blick, z. B. +/// Isometrie) oder Parallelprojektion (frei ausgerichtet). Axonometrie und Parallel zeichnen im 3D orthografisch. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)] +pub enum CameraProjection { + #[default] + #[serde(rename = "perspective")] + Perspective, + #[serde(rename = "axonometric")] + Axonometric, + #[serde(rename = "parallel")] + Parallel, + #[serde(other)] + #[ts(skip)] + Unknown, +} + +/// Eine Kamera ([213]) — gespeicherter Standpunkt für die 3D-Ansicht (und das Rendering): Standpunkt im +/// Grundriss mit Augenhöhe über dem Geschoss, Ziel (Grundriss und absolute Höhe), Bildwinkel, Projektion +/// und optional Datum/Uhrzeit für den Sonnenstand. Im Grundriss als Symbol mit Sichtkegel auf der Klasse +/// „Kameras" (Vorgabe "92"); „Kamera öffnen" setzt die 3D-Ansicht exakt. +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)] +#[serde(default)] +pub struct Camera { + pub id: String, + #[ts(type = "\"camera\"")] + pub r#type: String, + pub name: String, + /// Geschoss, auf dem das Symbol im Grundriss steht und auf das sich die Augenhöhe bezieht. + #[serde(rename = "floorId")] + pub floor_id: String, + /// Klasse (Ebene), Vorgabe "92" (Kameras). + #[serde(rename = "categoryCode")] + pub category_code: String, + /// Objekt-Sperre, analog `Wall.locked`. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub locked: Option, + /// Standpunkt im Grundriss (Meter). + pub position: Vec2, + /// Augenhöhe über OK Fertigboden des Geschosses (m). + #[serde(rename = "eyeHeight")] + pub eye_height: f64, + /// Ziel im Grundriss (Meter); der Abstand Standpunkt–Ziel ist die Länge des Sichtkegels. + pub target: Vec2, + /// Höhe des Ziels (m, absolut, z des Modells). + #[serde(rename = "targetHeight")] + pub target_height: f64, + /// Vertikaler Bildwinkel (Grad, perspektivisch). Die Kleinbild-Brennweite folgt daraus (24-mm-Sensorhöhe). + #[serde(rename = "fovDeg")] + pub fov_deg: f64, + pub projection: CameraProjection, + /// Sichthöhe in Metern (volle Bildhöhe) bei Axonometrie/Parallel; fehlt = 10 m. + #[serde(rename = "orthoHeight", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub ortho_height: Option, + /// Zeitpunkt für den Sonnenstand (ISO-8601 in UTC wie `SunStudy.when`); „Kamera öffnen" setzt ihn in der + /// Sonnenstudie. Fehlt er, bleibt die Sonne der Studie. + #[serde(rename = "sunWhen", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub sun_when: 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 @@ -5919,6 +5984,11 @@ pub struct Project { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub trees: Option>, + /// Kameras ([213]) — gespeicherte Standpunkte für 3D-Ansicht und Rendering, siehe {@link Camera}. Optional + /// (Default: leer behandeln). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub cameras: 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 diff --git a/src-tauri/core/src/model/items.rs b/src-tauri/core/src/model/items.rs index 9041744f..392a5bd8 100644 --- a/src-tauri/core/src/model/items.rs +++ b/src-tauri/core/src/model/items.rs @@ -37,6 +37,7 @@ impl Project { "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), + "cameras" => put_opt(&mut self.cameras, 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/plan/README.md b/src-tauri/core/src/plan/README.md index db5e2455..6849be2c 100644 --- a/src-tauri/core/src/plan/README.md +++ b/src-tauri/core/src/plan/README.md @@ -26,6 +26,7 @@ Herkunft, kein Wegweiser. | `floor_finish.rs` | Bodenbelag-Muster nach Massstab | | `model_view.rs` | Modelldarstellung ([173]): Optionen je Bauteilart über dem Detailgrad, Rangfolge Element > Typ > Stufe > Basis | | `trees.rs` | Bäume in Grundriss, Schnitt und Ansicht | +| `cameras.rs` | [213] Kameras im Grundriss: Gehäuse, Sichtkegel, Ziel, Name, Pick-Bänder (Klasse „Kameras“) | | `stamp_place.rs` | Hindernisse für die Lage der Raumstempel | | `view_range.rs` | Ansichtsbereich: Schnitthöhe, Ober- und Unterkante der Sicht | | `extras.rs` | Zutaten: Schatten und Baurecht, Abzugskörper, Strichstärken nach Massstab, Schwarz-Weiss, Ausmass | diff --git a/src-tauri/core/src/plan/cache.rs b/src-tauri/core/src/plan/cache.rs index 77f75696..592a1d63 100644 --- a/src-tauri/core/src/plan/cache.rs +++ b/src-tauri/core/src/plan/cache.rs @@ -30,6 +30,7 @@ pub const NOT_FOR_DRAWINGS: &[&str] = &[ "rooms", "columns", "trees", + "cameras", "extrudedSolids", // [157] `context` lesen die Zeichnungen: die Aussenbemassung rückt hinter die sichtbare Baugrube. "groups", diff --git a/src-tauri/core/src/plan/cameras.rs b/src-tauri/core/src/plan/cameras.rs new file mode 100644 index 00000000..ff3fdcf3 --- /dev/null +++ b/src-tauri/core/src/plan/cameras.rs @@ -0,0 +1,246 @@ +//! [213] Kameras im Grundriss: Kamerakörper (Gehäuse mit Objektiv) am Standpunkt, Sichtkegel mit dem +//! horizontalen Öffnungswinkel (Perspektive) bzw. parallele Sichtgrenzen (Axonometrie/Parallel), Ziel als +//! Kreuz mit gestrichelter Blicklinie, Name als Beschriftung. Grösse in fester Papiergrösse (unabhängig vom +//! Massstab). Alles liegt auf der Klasse der Kamera (Vorgabe „92", `standards::CAMERA_CATEGORY`); fehlt die +//! Klasse im Projekt, bleibt das Symbol sichtbar (wie die übrige abgeleitete Darstellung, [180]). +//! Pick: unsichtbare Fläche (Körper + Kegel) mit `contextObjectId = "@camera:"`. + +use super::domains::Ctx; +use super::prim::Primitive; +use super::style::MONO_INK; +use super::trees::{line, poly}; +use crate::camera::{CameraGeom, CAMERA_PICK_PREFIX}; +use crate::jsnum; +use crate::model::*; + +const BODY_MM: f64 = 0.25; +const CONE_MM: f64 = 0.18; +const AIM_MM: f64 = 0.13; +const AIM_DASH: [f64; 2] = [1.5, 1.0]; +/// Gehäuse: Länge entlang der Blickrichtung und Breite (Papier-mm), Objektiv davor. +const BODY_LEN: f64 = 4.0; +const BODY_WID: f64 = 3.2; +const LENS_LEN: f64 = 1.6; +const LENS_WID: f64 = 2.0; +/// Zielkreuz (Halbarm, Papier-mm). +const CROSS: f64 = 1.6; +/// Grösster Winkel zur Achse für den Kegel (Grad), damit sehr grosse Bildwinkel keine endlosen Kanten geben. +/// Halbe Breite der Pick-Bänder entlang der Linien (Papier-mm). +const PICK_BAND: f64 = 1.2; +const MAX_HALF_DEG: f64 = 75.0; + +fn v(x: f64, y: f64) -> Vec2 { + Vec2 { x, y } +} + +/// Pick-Id einer Kamera (Feld `contextObjectId`). +pub fn pick_id(id: &str) -> String { + format!("{CAMERA_PICK_PREFIX}{id}") +} + +/// Halber horizontaler Öffnungswinkel (Radiant) aus dem vertikalen Bildwinkel und dem Bildverhältnis. +pub fn half_h_angle(fov_deg: f64) -> f64 { + let h = jsnum::atan(jsnum::tan(fov_deg.to_radians() / 2.0) * crate::camera::ASPECT); + h.min(MAX_HALF_DEG.to_radians()) +} + +/// Ecken des Sichtkegels (Standpunkt, linke Ecke, rechte Ecke) bzw. des Streifens bei Parallelprojektion. +pub fn view_area(g: &CameraGeom, mm: f64) -> Vec { + let (px, py) = (g.eye[0], g.eye[1]); + // Mindestlänge: damit auch ein Ziel unmittelbar am Standpunkt ein sichtbares Symbol gibt. + let len = g.plan_dist.max(8.0 * mm); + let (u, n) = ((jsnum::cos(g.yaw), jsnum::sin(g.yaw)), (-jsnum::sin(g.yaw), jsnum::cos(g.yaw))); + if g.perspective { + let h = half_h_angle(g.fov_deg); + let edge = len / jsnum::cos(h); + let at = |s: f64| v(px + edge * jsnum::cos(g.yaw + s * h), py + edge * jsnum::sin(g.yaw + s * h)); + vec![v(px, py), at(-1.0), at(1.0)] + } else { + // Breite = Sichthöhe × Bildverhältnis. + let w = g.ortho_height * crate::camera::ASPECT / 2.0; + let q = |a: f64, b: f64| v(px + u.0 * a + n.0 * b, py + u.1 * a + n.1 * b); + vec![q(0.0, -w), q(len, -w), q(len, w), q(0.0, w)] + } +} + +/// Planzeichen einer Kamera: Pick-Fläche, Sichtgrenzen, Gehäuse mit Objektiv, Blicklinie und Zielkreuz. +pub fn camera_symbol(cam: &Camera, g: &CameraGeom, scale: f64, cat: Option<&LayerCategory>, greyed: Option) -> Vec { + let mm = scale / 1000.0; + let color = cat.map(|k| k.color.as_str()).filter(|c| !c.is_empty()).unwrap_or(MONO_INK).to_string(); + let (px, py) = (g.eye[0], g.eye[1]); + let (cs, sn) = (jsnum::cos(g.yaw), jsnum::sin(g.yaw)); + let at = |a: f64, b: f64| v(px + (cs * a - sn * b) * mm, py + (sn * a + cs * b) * mm); + // Gehäuse hinter dem Standpunkt, Objektiv davor: der Standpunkt liegt an der Vorderkante des Objektivs. + let (bw, lw) = (BODY_WID / 2.0, LENS_WID / 2.0); + let body = vec![at(-BODY_LEN - LENS_LEN, -bw), at(-LENS_LEN, -bw), at(-LENS_LEN, bw), at(-BODY_LEN - LENS_LEN, bw)]; + let lens = vec![at(-LENS_LEN, -lw), at(0.0, -lw * 1.5), at(0.0, lw * 1.5), at(-LENS_LEN, lw)]; + let area = view_area(g, mm); + // Pick-Flächen (unsichtbar): Gehäuse mit Objektiv, Zielkreuz und schmale Bänder entlang der Sichtgrenzen und der + // Blicklinie — nicht der ganze Kegel, sonst finge er jeden Klick auf Räume und Wände darin ab. + let id = pick_id(&cam.id); + let mut out = Vec::new(); + let mut pick = |pts: Vec| out.push(poly(pts, "none", "none", 0.0, Some(id.clone()), greyed)); + pick(vec![at(-BODY_LEN - LENS_LEN, -bw), at(0.0, -lw * 1.5), at(0.0, lw * 1.5), at(-BODY_LEN - LENS_LEN, bw)]); + let band = |a: Vec2, b: Vec2| -> Option> { + let (dx, dy) = (b.x - a.x, b.y - a.y); + let l = dx.hypot(dy); + if !(l > 1e-9) { + return None; + } + let (nx, ny) = (-dy / l * PICK_BAND * mm, dx / l * PICK_BAND * mm); + Some(vec![v(a.x + nx, a.y + ny), v(b.x + nx, b.y + ny), v(b.x - nx, b.y - ny), v(a.x - nx, a.y - ny)]) + }; + let m = area.len(); + for k in 0..m { + // Perspektive: Kanten 0–1, 0–2 und 1–2; Streifen: Umriss. + let (a, b) = if g.perspective { [(0, 1), (0, 2), (1, 2)][k.min(2)] } else { (k, (k + 1) % m) }; + if g.perspective && k > 2 { + break; + } + if let Some(b) = band(area[a], area[b]) { + pick(b); + } + } + if g.plan_dist > 1e-6 { + if let Some(b) = band(v(px, py), v(g.target[0], g.target[1])) { + pick(b); + } + } + let kk = CROSS * mm; + pick(vec![v(g.target[0] - kk, g.target[1] - kk), v(g.target[0] + kk, g.target[1] - kk), v(g.target[0] + kk, g.target[1] + kk), v(g.target[0] - kk, g.target[1] + kk)]); + // Sichtgrenzen: Kegel (zwei Kanten und die ferne Linie) bzw. Streifen (Umriss). + if g.perspective { + out.push(line(area[0], area[1], "camera-cone", CONE_MM, &color, None, greyed)); + out.push(line(area[0], area[2], "camera-cone", CONE_MM, &color, None, greyed)); + out.push(line(area[1], area[2], "camera-cone", CONE_MM, &color, Some(&AIM_DASH), greyed)); + } else { + for k in 0..m { + let dash = (k == 0).then_some(&AIM_DASH[..]); + out.push(line(area[k], area[(k + 1) % m], "camera-cone", CONE_MM, &color, dash, greyed)); + } + } + out.push(poly(body, "#ffffff", &color, BODY_MM, None, greyed)); + out.push(poly(lens, &color, &color, BODY_MM, None, greyed)); + // Blicklinie zum Ziel und Zielkreuz. + let (tx, ty) = (g.target[0], g.target[1]); + if g.plan_dist > 1e-6 { + out.push(line(v(px, py), v(tx, ty), "camera-aim", AIM_MM, &color, Some(&AIM_DASH), greyed)); + } + let k = CROSS * mm; + out.push(line(v(tx - k, ty), v(tx + k, ty), "camera-aim", CONE_MM, &color, None, greyed)); + out.push(line(v(tx, ty - k), v(tx, ty + k), "camera-aim", CONE_MM, &color, None, greyed)); + // Name hinter dem Gehäuse (Schrift bleibt waagrecht, der Block rückt so weit ab, dass er das Gehäuse nicht berührt). + let name = cam.name.trim(); + if !name.is_empty() && scale.is_finite() && scale > 0.0 { + let doc = super::domains::doc_from_text(name); + let pt = super::trees::label_pt(scale); + let (w, h) = crate::text_layout::stamp_block_size(&doc, &[], pt, crate::text_layout::PT_TO_MM * mm); + let back = (BODY_LEN + LENS_LEN + 1.0) * mm; + let reach = cs.abs() * w / 2.0 + sn.abs() * h / 2.0 + 0.5 * mm; + let c = v(px - cs * (back + reach), py - sn * (back + reach)); + out.push(Primitive::Text { at: c, doc, extra_lines: vec![], base_pt: pt, color: color.clone(), room_id: None, greyed, opacity: None }); + } + out +} + +/// Kamera-Symbole des Grundrisses (Kameras dieses Geschosses mit sichtbarer Klasse). +pub(super) fn plan_cameras(c: &Ctx, out: &mut Vec) { + let Some(cams) = c.p.cameras.as_deref() else { return }; + let scale = if c.a.scale.is_finite() && c.a.scale > 0.0 { c.a.scale } else { 100.0 }; + for cam in cams { + if cam.floor_id != c.a.floor || !c.derived_shown(&cam.category_code) || c.rule_hidden(&cam.id) { + continue; + } + let Some(g) = CameraGeom::of(c.p, cam) else { continue }; + let greyed = Some(c.greyed(&cam.category_code)); + out.extend(camera_symbol(cam, &g, scale, c.cat(&cam.category_code), greyed)); + } +} + +/// Ist `q` ein Planzeichen einer Kamera? +pub(super) fn is_symbol_part(q: &Primitive) -> bool { + match q { + Primitive::Line { cls, .. } => cls == "camera-cone" || cls == "camera-aim", + Primitive::Polygon { context_object_id: Some(id), .. } => id.starts_with(CAMERA_PICK_PREFIX), + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plan::domains::{plan_domains_buf, PlanArgs}; + use serde_json::{json, Value}; + + fn project(extra: Value) -> Project { + let mut v: Value = serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap(); + v["layers"].as_array_mut().unwrap().push(json!({"code": "92", "name": "Kameras", "color": "#123456", "lw": 0.18, "visible": true, "locked": false})); + v["cameras"] = json!([{"id": "k1", "type": "camera", "name": "Süd", "floorId": "eg", "categoryCode": "92", "position": {"x": 2, "y": -3}, + "eyeHeight": 1.6, "target": {"x": 2, "y": 3}, "targetHeight": 1.6, "fovDeg": 50, "projection": "perspective"}]); + if let Some(o) = extra.as_object() { + for (k, val) in o { + v["cameras"][0][k] = val.clone(); + } + } + serde_json::from_value(v).unwrap() + } + + fn plan(p: &Project, floor: &str, show: &[String]) -> Vec { + let a = PlanArgs::parse(1.0, &json!({"floor": floor, "show": show, "global": true, "scale": 100}).to_string()).unwrap(); + let buf = plan_domains_buf(p, &a).unwrap(); + crate::plan::buf::View::parse(&buf).unwrap().prims().unwrap() + } + + fn all_codes(p: &Project) -> Vec { + let mut c: Vec = p.flat_categories().iter().map(|c| c.code.clone()).collect(); + c.extend(p.walls.iter().map(|w| w.category_code.clone())); + c + } + + fn camera_prims(prims: &[Primitive]) -> Vec<&Primitive> { + prims.iter().filter(|q| is_symbol_part(q)).collect() + } + + #[test] + fn symbol_auf_der_klasse_der_kamera() { + let p = project(json!({})); + let all = all_codes(&p); + let prims = plan(&p, "eg", &all); + let mine = camera_prims(&prims); + assert!(mine.iter().any(|q| matches!(q, Primitive::Polygon { context_object_id: Some(id), .. } if id == "@camera:k1")), "Pick-Fläche"); + assert!(mine.iter().any(|q| matches!(q, Primitive::Line { cls, .. } if cls == "camera-cone")), "Sichtkegel"); + assert!(prims.iter().any(|q| matches!(q, Primitive::Text { color, .. } if color == "#123456")), "Name in der Klassenfarbe"); + // Klasse aus: nichts mehr. + let without: Vec = all.iter().filter(|c| *c != "92").cloned().collect(); + let prims = plan(&p, "eg", &without); + assert!(camera_prims(&prims).is_empty(), "Klasse 92 aus"); + assert!(!prims.iter().any(|q| matches!(q, Primitive::Text { color, .. } if color == "#123456")), "Name mit der Klasse aus"); + // Anderes Geschoss: nichts. + if let Some(o) = p.drawing_levels.iter().find(|l| l.id != "eg" && l.kind == DrawingLevelKind::Floor) { + assert!(camera_prims(&plan(&p, &o.id, &all)).is_empty(), "anderes Geschoss"); + } + } + + #[test] + fn kegel_oeffnet_sich_um_den_bildwinkel() { + let p = project(json!({"fovDeg": 40})); + let g = CameraGeom::of(&p, &p.cameras.as_ref().unwrap()[0]).unwrap(); + let a = view_area(&g, 0.1); + // Blick nach +y: die Ecken liegen links/rechts davon, symmetrisch. + assert!((a[1].x - 2.0 + (a[2].x - 2.0)).abs() < 1e-9); + let half = ((a[2].x - 2.0) / (a[2].y + 3.0)).atan().abs(); + assert!((half - half_h_angle(40.0)).abs() < 1e-9); + // Die ferne Kante geht durch das Ziel (Abstand 6 m). + assert!((a[1].y - 3.0).abs() < 1e-9); + } + + #[test] + fn parallelprojektion_zeichnet_streifen() { + let p = project(json!({"projection": "axonometric", "orthoHeight": 4})); + let g = CameraGeom::of(&p, &p.cameras.as_ref().unwrap()[0]).unwrap(); + let a = view_area(&g, 0.1); + assert_eq!(a.len(), 4); + // Breite = 4 m × 16/9. + assert!(((a[3].x - a[0].x).abs() - 4.0 * crate::camera::ASPECT).abs() < 1e-9); + } +} diff --git a/src-tauri/core/src/plan/domains.rs b/src-tauri/core/src/plan/domains.rs index fb526a61..868a1e11 100644 --- a/src-tauri/core/src/plan/domains.rs +++ b/src-tauri/core/src/plan/domains.rs @@ -1744,6 +1744,16 @@ fn domains_after(c: &Ctx, out: &mut DomainPrims, bounds: &mut Bounds) { } // Räume vor dem Kontext: Stempel ausserhalb ihres Raums (eigener Anker im Gelände) sind Hindernisse der // Höhenlinien-Beschriftungen; Stempel im Raum liegen im Fussabdruck, wo keine Beschriftung steht. + // [213] Kameras: Planzeichen mit Sichtkegel obenauf (Gruppe der Schnittführungen). + let first_camera = out.sections.len(); + super::cameras::plan_cameras(c, &mut out.sections); + // Das Symbol (Kegel, Ziel) gehört zum Ausmass, damit es beim Einpassen nicht abgeschnitten wird. + for q in &out.sections[first_camera..] { + if let Primitive::Line { a, b, .. } = q { + bounds.acc(a.x, a.y); + bounds.acc(b.x, b.y); + } + } let obstacles = stamp_obstacles_with(out, drawn.clone()); rooms(c, &mut out.rooms, bounds, &obstacles); if c.a.global { diff --git a/src-tauri/core/src/plan/mod.rs b/src-tauri/core/src/plan/mod.rs index a3113aed..8a04caf2 100644 --- a/src-tauri/core/src/plan/mod.rs +++ b/src-tauri/core/src/plan/mod.rs @@ -38,6 +38,7 @@ pub mod stamp_place; pub mod floor_finish; pub mod model_view; pub mod trees; +pub mod cameras; pub mod mesh_plan; pub mod arc_fit; pub(crate) mod seams; diff --git a/src-tauri/core/src/plan/trees.rs b/src-tauri/core/src/plan/trees.rs index 4636a153..32c86f74 100644 --- a/src-tauri/core/src/plan/trees.rs +++ b/src-tauri/core/src/plan/trees.rs @@ -43,7 +43,7 @@ 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 { +pub(super) fn poly(pts: Vec, fill: &str, stroke: &str, w: f64, pick: Option, greyed: Option) -> Primitive { Primitive::Polygon { pts, fill: fill.into(), @@ -67,7 +67,7 @@ fn poly(pts: Vec, fill: &str, stroke: &str, w: f64, pick: Option, } } -fn line(a: Vec2, b: Vec2, cls: &str, w: f64, color: &str, dash: Option<&[f64]>, greyed: Option) -> Primitive { +pub(super) fn line(a: Vec2, b: Vec2, cls: &str, w: f64, color: &str, dash: Option<&[f64]>, greyed: Option) -> Primitive { Primitive::Line { a, b, diff --git a/src-tauri/core/src/project_format.rs b/src-tauri/core/src/project_format.rs index 664eb513..40d44bb7 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; 56] = [ +const KNOWN_KEYS: [&str; 57] = [ "formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes", "ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens", "penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers", @@ -24,7 +24,7 @@ const KNOWN_KEYS: [&str; 56] = [ "viewSnapshotFolders", "viewTemplates", "layouts", "masterLayouts", "layoutFolders", "publishSets", "publishLog", "projectNumber", "referenceElevationMasl", "geoAnchor", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights", "lineCap", "lineJoin", "trees", "uiState", - "modelViewOptions", + "modelViewOptions", "cameras", ]; /// Ergebnis des Einlesens. diff --git a/src-tauri/core/src/project_refs.rs b/src-tauri/core/src/project_refs.rs index 94722a39..fb5412db 100644 --- a/src-tauri/core/src/project_refs.rs +++ b/src-tauri/core/src/project_refs.rs @@ -99,6 +99,9 @@ pub fn dangling_refs(p: &Project) -> Vec { for r in p.rooms.as_deref().unwrap_or(&[]) { miss(&mut out, "Raum", &r.id, "Geschoss", &r.floor_id, &levels); } + for c in p.cameras.as_deref().unwrap_or(&[]) { + miss(&mut out, "Kamera", &c.id, "Geschoss", &c.floor_id, &levels); + } for d in &p.drawings2d { miss(&mut out, "Zeichnung", &d.id, "Ebene", &d.level_id, &levels); miss(&mut out, "Zeichnung", &d.id, "Linienstil", d.line_style_id.as_deref().unwrap_or(""), &line_styles); diff --git a/src-tauri/core/src/standards.rs b/src-tauri/core/src/standards.rs index bc2c114f..5c960726 100644 --- a/src-tauri/core/src/standards.rs +++ b/src-tauri/core/src/standards.rs @@ -363,13 +363,16 @@ pub const AUTO_DIM_CATEGORY: &str = "81"; pub const LEVEL_MARK_CATEGORY: &str = "82"; /// Schnitt- und Ansichtsmarken im Grundriss (Schnittführung mit Pfeilen und Beschriftung). pub const SECTION_MARK_CATEGORY: &str = "91"; +/// Kameras ([213]): Symbol mit Sichtkegel im Grundriss (Element `Project.cameras`, Klasse je Element änderbar). +pub const CAMERA_CATEGORY: &str = "92"; /// Die Klassen der abgeleiteten Darstellung (Code, Name, Farbe, Strichstärke). -pub const DERIVED_CATEGORIES: [(&str, &str, &str, f64); 4] = [ +pub const DERIVED_CATEGORIES: [(&str, &str, &str, f64); 5] = [ (SHADOW_CATEGORY, "Schatten", "#707078", 0.13), (AUTO_DIM_CATEGORY, "Auto-Bemassung", "#303038", 0.13), (LEVEL_MARK_CATEGORY, "Höhenkoten", "#1a1a1a", 0.13), (SECTION_MARK_CATEGORY, "Schnittmarken", "#1a1a1a", 0.18), + (CAMERA_CATEGORY, "Kameras", "#1a1a1a", 0.18), ]; pub fn derived_categories() -> Vec { @@ -841,7 +844,7 @@ mod tests { // Andere Kategorien bleiben, die neue kommt ans Ende. own.insert("layers".into(), json!([{"code": "20", "name": "Wände", "color": "#000", "lw": 0.35, "visible": true, "locked": false}])); let op = merge_ops(&own).into_iter().find(|o| o["key"] == "layers").unwrap(); - assert_eq!(op["value"].as_array().unwrap().iter().map(|l| l["code"].as_str().unwrap()).collect::>(), ["20", "65", "08", "81", "82", "91"]); + assert_eq!(op["value"].as_array().unwrap().iter().map(|l| l["code"].as_str().unwrap()).collect::>(), ["20", "65", "08", "81", "82", "91", "92"]); } /// [180] Klassen der abgeleiteten Darstellung: „Standards laden" legt sie an, einmal; vorhandene (Code oder Name) bleiben. @@ -857,7 +860,7 @@ mod tests { own.insert("layers".into(), json!([{"code": "77", "name": "schatten", "color": "#000", "lw": 0.13, "visible": true, "locked": false}])); let op = merge_ops(&own).into_iter().find(|o| o["key"] == "layers").unwrap(); let codes: Vec<&str> = op["value"].as_array().unwrap().iter().map(|l| l["code"].as_str().unwrap()).collect(); - assert_eq!(codes, ["77", "65", "81", "82", "91"]); + assert_eq!(codes, ["77", "65", "81", "82", "91", "92"]); // Sichtbar, solange die Klasse fehlt; sonst nach der Klassen-Sichtbarkeit. assert!(derived_visible(&p, SHADOW_CATEGORY, |c| c == SHADOW_CATEGORY)); assert!(!derived_visible(&p, SHADOW_CATEGORY, |_| false)); diff --git a/src-tauri/core/src/web/grips.rs b/src-tauri/core/src/web/grips.rs index 00188f3e..9b04dc97 100644 --- a/src-tauri/core/src/web/grips.rs +++ b/src-tauri/core/src/web/grips.rs @@ -58,6 +58,14 @@ pub fn grip_vertices(drawing_json: &str, scale: f64) -> Vec { } } +/// [213] Griffe einer Kamera (JSON) beim Massstab 1:`scale`: `[x0, y0, x1, y1, x2, y2]` (Standpunkt, Ziel, +/// Bildwinkel/Sichtbreite), `[]` bei kaputtem JSON. +#[wasm_bindgen] +pub fn camera_grip_points(camera_json: &str, scale: f64) -> Vec { + let Ok(c) = serde_json::from_str::(camera_json) else { return vec![] }; + crate::camera::grip_points(&c, scale).into_iter().flat_map(|p| [p.0, p.1]).collect() +} + /// Editier-Griffe einer Polylinie aus flachen Puffern (grosse Kataster-Umrisse ohne JSON): `pts = [x0, y0, …]`, /// `bulge` je Segment (fehlend/NaN = gerade) → `[x0, y0, …]` (Eckpunkte, dann je Segment die Bogen-Mitte). #[wasm_bindgen] diff --git a/src/core/extra.ts b/src/core/extra.ts index 3175de05..ff330c4e 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -72,6 +72,7 @@ export { EMPTY_MEMBERSHIP, containingGroupId, expandToGroups, isInsideActiveGrou export type { GroupMembership, MemberKind } from "../model/groups"; export { arcApex, drawingVertices, gripPt, openEdges, polylineEdgeGrips, ringEdges } from "../geometry/grips"; export { verticalExtents } from "../geometry/grips"; +export { cameraGripPoints } from "../geometry/grips"; export type { VerticalExtent } from "../geometry/grips"; export type { GripRequest, RingKind } from "../geometry/grips"; export { edgeArcToggle, type ArcRingKind } from "../geometry/grips"; diff --git a/src/geometry/grips.ts b/src/geometry/grips.ts index da345846..b504bad8 100644 --- a/src/geometry/grips.ts +++ b/src/geometry/grips.ts @@ -7,7 +7,7 @@ // Bewusst TS: die Rahmen-Ecken einer Textspalte (`textFrameCorners` braucht die Schrift-Metrik der // Hülle) — der Kern meldet dafür nur „Textspalte". -import type { Ceiling, Drawing2D, Drawing2DGeom, EdgeGrip, Project, Vec2, Wall } from "../model/types"; +import type { Camera, Ceiling, Drawing2D, Drawing2DGeom, EdgeGrip, Project, Vec2, Wall } from "../model/types"; import { documentFor } from "../core/document"; import { core } from "../engine/coreWasm"; import { toMarkedJson } from "../core/ops"; @@ -46,6 +46,9 @@ export type GripRequest = // [176] Schnittlinie: 0 = Anfang, dann `bendPoints`, zuletzt das Ende. | { op: "sectionLineGrip"; id: string; index: number; pt: P } | { op: "sectionBendInsert"; id: string; seg: number; pt: P } + // [213] Kamera: 0 = Standpunkt, 1 = Ziel, 2 = Bildwinkel bzw. Sichtbreite (Kern `camera::grip_edit`); `cameraBy` verschiebt Standpunkt und Ziel. + | { op: "cameraGrip"; id: string; index: number; pt: P } + | { op: "cameraBy"; id: string; delta: P } | { op: "sectionBendDelete"; id: string; index: number } | { op: "sectionLineTidy"; id: string; tol?: number } // [26] Ecke an Umriss-Ringen einfügen (hinter Kante `seg`), löschen, aufräumen (Kern `ring_edit`); Dach: flacher Index. @@ -100,6 +103,14 @@ export function drawingVertices(d: Drawing2D, scaleDenominator: number = DEFAULT return out; } +/** [213] Griffe einer Kamera im Grundriss beim Massstab 1:`scaleDenominator`: Standpunkt, Ziel, Bildwinkel/Sichtbreite (Kern `camera::grip_points`). */ +export function cameraGripPoints(c: Camera, scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR): Vec2[] { + const f = core().camera_grip_points(JSON.stringify(c), scaleDenominator); + const out: Vec2[] = []; + for (let i = 0; i + 1 < f.length; i += 2) out.push({ x: f[i], y: f[i + 1] }); + return out; +} + type Owner = { drawingId?: string; wallId?: string }; function flat(verts: readonly Vec2[]): Float64Array { diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 1ac3ec41..1c77367e 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1026,6 +1026,7 @@ export const de = { "nav.categoryDerived.81": "Abgeleitete Darstellung: automatische Aussenbemassung (je Kette änderbar)", "nav.categoryDerived.82": "Abgeleitete Darstellung: automatische Höhenkoten in Schnitt und Ansicht", "nav.categoryDerived.91": "Abgeleitete Darstellung: Schnitt- und Ansichtsmarken im Grundriss", + "nav.categoryDerived.92": "Kameras: Symbol mit Sichtkegel im Grundriss (Element Kamera, je Kamera änderbar)", "nav.categorySettings": "Ebeneneinstellungen für {name}", "nav.drawingLevelsWindow": "Zeichnungsebenen als eigenes Fenster öffnen", @@ -2032,6 +2033,44 @@ export const de = { "cmd.circlestotrees.label": "Kreise in Bäume umwandeln", "objinfo.kind.tree": "Baum", "objinfo.tree.many": "{n} Bäume", + "camera.title": "Kameras", + "camera.defaultName": "Kamera", + "camera.empty": "Keine Kameras. Mit „+“ aus der aktuellen 3D-Ansicht anlegen.", + "camera.createFromView": "Kamera aus aktueller Ansicht anlegen", + "camera.created": "Kamera „{name}“ angelegt", + "camera.open": "Kamera öffnen", + "camera.rowHint": "Klick wählt die Kamera, Doppelklick öffnet sie im 3D", + "camera.delete": "Kamera löschen", + "camera.update": "Aus aktueller Ansicht", + "camera.updateHint": "Standpunkt, Ziel, Bildwinkel und Projektion mit der aktuellen 3D-Ansicht überschreiben", + "camera.updated": "Kamera „{name}“ aus der aktuellen Ansicht aktualisiert", + "camera.iso": "Isometrisch", + "camera.isoHint": "Standpunkt so legen, dass die Kamera das Ziel isometrisch (45°, 35,3° Neigung) ansieht", + "camera.noViewport": "Die 3D-Ansicht ist nicht geöffnet.", + "camera.invalid": "Kamera „{name}“ hat keinen gültigen Blick (Standpunkt gleich Ziel?).", + "objinfo.kind.camera": "Kamera", + "objinfo.camera.many": "{n} Kameras", + "objinfo.camera.section": "Kamera", + "objinfo.camera.name": "Name", + "objinfo.camera.projection": "Projektion", + "objinfo.camera.projection.perspective": "Perspektive", + "objinfo.camera.projection.axonometric": "Axonometrie", + "objinfo.camera.projection.parallel": "Parallelprojektion", + "objinfo.camera.stand": "Standpunkt", + "objinfo.camera.eyeHeight": "Augenhöhe über Geschoss", + "objinfo.camera.target": "Ziel", + "objinfo.camera.targetHeight": "Höhe Ziel", + "objinfo.camera.fov": "Bildwinkel (vertikal)", + "objinfo.camera.focal": "Brennweite (Kleinbild)", + "objinfo.camera.orthoHeight": "Sichthöhe", + "objinfo.camera.sun": "Sonnenstand", + "objinfo.camera.sunHint": "Datum und Uhrzeit (UTC); „Kamera öffnen“ stellt die Sonnenstudie darauf. Leer = Sonne bleibt.", + "objinfo.camera.locked": "Gesperrt: Die Kamera lässt sich nicht ändern.", + "pick.kind.camera": "Kamera", + "shortcut.walkMode": "Begehen im 3D ein/aus", + "walk.toggle": "Begehen", + "walk.hint": "Begehen (Umschalt+F): W/A/S/D oder Pfeile gehen, Q/E runter und hoch, Umschalt schneller, Alt langsamer, mit gedrückter Maustaste umschauen", + "viewport3d.camera.create": "Kamera aus aktueller Ansicht anlegen", "objinfo.tree.section": "Baum", "objinfo.tree.species": "Art", "objinfo.tree.speciesHint": "z. B. Quercus robur", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index d70b6c21..ecb7cf0e 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1021,6 +1021,7 @@ export const en: Record = { "nav.categoryDerived.81": "Derived display: automatic exterior dimensions (each chain can be reassigned)", "nav.categoryDerived.82": "Derived display: automatic level marks in sections and elevations", "nav.categoryDerived.91": "Derived display: section and elevation marks in plans", + "nav.categoryDerived.92": "Cameras: symbol with view cone in plans (camera element, each camera can be reassigned)", "nav.categorySettings": "Layer settings for {name}", "nav.drawingLevelsWindow": "Open drawing levels as its own window", @@ -2021,6 +2022,44 @@ export const en: Record = { "cmd.circlestotrees.label": "Convert circles to trees", "objinfo.kind.tree": "Tree", "objinfo.tree.many": "{n} trees", + "camera.title": "Cameras", + "camera.defaultName": "Camera", + "camera.empty": "No cameras. Use “+” to create one from the current 3D view.", + "camera.createFromView": "Create camera from current view", + "camera.created": "Camera “{name}” created", + "camera.open": "Open camera", + "camera.rowHint": "Click selects the camera, double-click opens it in 3D", + "camera.delete": "Delete camera", + "camera.update": "From current view", + "camera.updateHint": "Overwrite position, target, field of view and projection with the current 3D view", + "camera.updated": "Camera “{name}” updated from the current view", + "camera.iso": "Isometric", + "camera.isoHint": "Move the camera so it looks at the target isometrically (45°, 35.3° pitch)", + "camera.noViewport": "The 3D view is not open.", + "camera.invalid": "Camera “{name}” has no valid view (position equals target?).", + "objinfo.kind.camera": "Camera", + "objinfo.camera.many": "{n} cameras", + "objinfo.camera.section": "Camera", + "objinfo.camera.name": "Name", + "objinfo.camera.projection": "Projection", + "objinfo.camera.projection.perspective": "Perspective", + "objinfo.camera.projection.axonometric": "Axonometric", + "objinfo.camera.projection.parallel": "Parallel projection", + "objinfo.camera.stand": "Position", + "objinfo.camera.eyeHeight": "Eye height above floor", + "objinfo.camera.target": "Target", + "objinfo.camera.targetHeight": "Target height", + "objinfo.camera.fov": "Field of view (vertical)", + "objinfo.camera.focal": "Focal length (35 mm)", + "objinfo.camera.orthoHeight": "View height", + "objinfo.camera.sun": "Sun position", + "objinfo.camera.sunHint": "Date and time (UTC); “Open camera” sets the sun study to it. Empty = sun stays.", + "objinfo.camera.locked": "Locked: the camera cannot be changed.", + "pick.kind.camera": "Camera", + "shortcut.walkMode": "Walk through 3D on/off", + "walk.toggle": "Walk", + "walk.hint": "Walk (Shift+F): W/A/S/D or arrow keys move, Q/E down and up, Shift faster, Alt slower, hold a mouse button to look around", + "viewport3d.camera.create": "Create camera from current view", "objinfo.tree.section": "Tree", "objinfo.tree.species": "Species", "objinfo.tree.speciesHint": "e.g. Quercus robur", diff --git a/src/model/derivedCategories.ts b/src/model/derivedCategories.ts index 3ad64a3e..cdab647a 100644 --- a/src/model/derivedCategories.ts +++ b/src/model/derivedCategories.ts @@ -15,8 +15,10 @@ export const AUTO_DIM_CATEGORY = "81"; export const LEVEL_MARK_CATEGORY = "82"; /** Schnitt- und Ansichtsmarken im Grundriss. */ export const SECTION_MARK_CATEGORY = "91"; +/** Kameras ([213]): Symbol mit Sichtkegel im Grundriss. */ +export const CAMERA_CATEGORY = "92"; -export const DERIVED_CATEGORY_CODES: readonly string[] = [SHADOW_CATEGORY, AUTO_DIM_CATEGORY, LEVEL_MARK_CATEGORY, SECTION_MARK_CATEGORY]; +export const DERIVED_CATEGORY_CODES: readonly string[] = [SHADOW_CATEGORY, AUTO_DIM_CATEGORY, LEVEL_MARK_CATEGORY, SECTION_MARK_CATEGORY, CAMERA_CATEGORY]; /** Abgeleitete Darstellung der Klasse `code` sichtbar: Klasse eingeblendet (`shown`) oder im Projekt nicht vorhanden. */ export function derivedVisible(layers: LayerCategory[], code: string, shown: (code: string) => boolean): boolean { diff --git a/src/model/sampleProject.ts b/src/model/sampleProject.ts index 55b97e72..e0be67af 100644 --- a/src/model/sampleProject.ts +++ b/src/model/sampleProject.ts @@ -416,6 +416,7 @@ export const sampleProject: Project = { { code: "82", name: "Höhenkoten", color: "#1a1a1a", lw: 0.13, visible: true, locked: false }, { code: "90", name: "Referenzen", color: "#1a1a1a", lw: 0.13, visible: true, locked: false }, { code: "91", name: "Schnittmarken", color: "#1a1a1a", lw: 0.18, visible: true, locked: false }, + { code: "92", name: "Kameras", color: "#1a1a1a", lw: 0.18, visible: true, locked: false }, { code: "99", name: "Konstruktion", color: "#404040", lw: 0.13, visible: true, locked: false }, ], // [140] Strichstärken folgen dem Massstab (neue Projekte; bestehende behalten ihre Einstellung). diff --git a/src/model/sampleProjectComplex.ts b/src/model/sampleProjectComplex.ts index b467bde6..023b4866 100644 --- a/src/model/sampleProjectComplex.ts +++ b/src/model/sampleProjectComplex.ts @@ -857,6 +857,14 @@ export function buildComplexSampleProject(): Project { roomProgramTolerance: 0.1, parcelArea: 1540, sunStudy: { when: "2026-06-21T10:00:00Z", show: true }, + // [213] Kamera aus Südost auf das Haus (Standpunkt 1.6 m über OK EG, Sonne am Abend). + cameras: [ + { + id: "kamera-suedost", type: "camera", name: "Südost", floorId: "eg", categoryCode: "92", + position: P(17, -3), eyeHeight: 1.6, target: P(7.5, 5), targetHeight: 4, fovDeg: 50, projection: "perspective", + sunWhen: "2026-06-21T16:00:00Z", + }, + ], siteRules: { parcel: PARCEL, // Grenzabstände je Parzellenkante (Süd, Ost, Nord, West); Baulinie entlang der Strasse. diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index edddd884..fdf0a4cc 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -46,6 +46,50 @@ export type BlockDef = { id: string; name: string; geom2d: Array */ export type BuiltinPaletteBanks = { simple?: boolean; tango?: boolean; material?: boolean; ral?: boolean }; +/** + * Eine Kamera ([213]) — gespeicherter Standpunkt für die 3D-Ansicht (und das Rendering): Standpunkt im + * Grundriss mit Augenhöhe über dem Geschoss, Ziel (Grundriss und absolute Höhe), Bildwinkel, Projektion + * und optional Datum/Uhrzeit für den Sonnenstand. Im Grundriss als Symbol mit Sichtkegel auf der Klasse + * „Kameras" (Vorgabe "92"); „Kamera öffnen" setzt die 3D-Ansicht exakt. + */ +export type Camera = { + id: string; + type: "camera"; + name: string; + /** Geschoss, auf dem das Symbol im Grundriss steht und auf das sich die Augenhöhe bezieht. */ + floorId: string; + /** Klasse (Ebene), Vorgabe "92" (Kameras). */ + categoryCode: string; + /** Objekt-Sperre, analog `Wall.locked`. */ + locked?: boolean; + /** Standpunkt im Grundriss (Meter). */ + position: Vec2; + /** Augenhöhe über OK Fertigboden des Geschosses (m). */ + eyeHeight: number; + /** Ziel im Grundriss (Meter); der Abstand Standpunkt–Ziel ist die Länge des Sichtkegels. */ + target: Vec2; + /** Höhe des Ziels (m, absolut, z des Modells). */ + targetHeight: number; + /** + * Vertikaler Bildwinkel (Grad, perspektivisch). Die Kleinbild-Brennweite folgt daraus (24-mm-Sensorhöhe). + */ + fovDeg: number; + projection: CameraProjection; + /** Sichthöhe in Metern (volle Bildhöhe) bei Axonometrie/Parallel; fehlt = 10 m. */ + orthoHeight?: number; + /** + * Zeitpunkt für den Sonnenstand (ISO-8601 in UTC wie `SunStudy.when`); „Kamera öffnen" setzt ihn in der + * Sonnenstudie. Fehlt er, bleibt die Sonne der Studie. + */ + sunWhen?: string; +}; + +/** + * Projektion einer Kamera ([213]): Perspektive, Axonometrie (Parallelprojektion mit schrägem Blick, z. B. + * Isometrie) oder Parallelprojektion (frei ausgerichtet). Axonometrie und Parallel zeichnen im 3D orthografisch. + */ +export type CameraProjection = "perspective" | "axonometric" | "parallel"; + /** Bekleidung einer Tür ([105]): auf der Aufschlagseite, der Gegenseite, beidseitig oder keine. */ export type CasingSides = "beide" | "aufschlag" | "gegen" | "keine"; @@ -2851,6 +2895,11 @@ export type Project = { * bestehende Projekte ohne `trees` gültig bleiben (Default: leer behandeln). */ trees?: Array; + /** + * Kameras ([213]) — gespeicherte Standpunkte für 3D-Ansicht und Rendering, siehe {@link Camera}. Optional + * (Default: leer behandeln). + */ + cameras?: Array; /** * Gruppen (Vectorworks-artig: Cmd+G fasst die Auswahl zu einer Einheit * zusammen; Doppelklick betritt die Gruppe zum Bearbeiten, alles andere diff --git a/src/panels/CamerasGroup.tsx b/src/panels/CamerasGroup.tsx new file mode 100644 index 00000000..a075daf4 --- /dev/null +++ b/src/panels/CamerasGroup.tsx @@ -0,0 +1,75 @@ +// Gruppe „Kameras" im Ausschnitte-Panel ([213]): die gespeicherten Kameras des Projekts als Liste. Klick wählt die +// Kamera (Objekt-Info, Symbol im Grundriss), Doppelklick bzw. „↗" setzt die 3D-Ansicht exakt, „+" legt aus der +// aktuellen 3D-Ansicht eine neue an, „✕" löscht. Die Kameras selbst sind Modell-Elemente (`Project.cameras`). + +import { removeItems } from "../core"; +import { t } from "../i18n"; +import { createCameraFromView, openCamera } from "../state/cameraActions"; +import { getState, useStore } from "../state/appStore"; +import { fromIds } from "../state/selection"; + +export function CamerasGroup() { + const cameras = useStore((s) => s.project.cameras); + const levels = useStore((s) => s.project.drawingLevels); + const selected = useStore((s) => s.selection.cameras); + const list = cameras ?? []; + return ( +
+
+ {t("camera.title")} + + + +
+ {list.length === 0 ? ( +
{t("camera.empty")}
+ ) : ( +
+ {list.map((c) => ( +
getState().setSelection(fromIds("cameras", [c.id]))} + onDoubleClick={() => void openCamera(c.id)} + style={{ display: "flex", alignItems: "center", gap: 4, paddingLeft: 10 }} + > + + {c.name} + {levels.find((l) => l.id === c.floorId)?.name ?? ""} + + + +
+ ))} +
+ )} +
+ ); +} diff --git a/src/panels/ObjectInfoPanel.tsx b/src/panels/ObjectInfoPanel.tsx index f503a8e6..37e14ff8 100644 --- a/src/panels/ObjectInfoPanel.tsx +++ b/src/panels/ObjectInfoPanel.tsx @@ -31,6 +31,7 @@ import { ContextObjectProps } from "./ContextObjectProps"; import { SunStudySection } from "./SunStudySection"; import { SiteRulesSection } from "./SiteRulesSection"; import { TreeSection } from "./objectInfo/TreeSection"; +import { CameraSection } from "./objectInfo/CameraSection"; import { ViewShadowsInfo, MeasurementSection } from "./objectInfo/InfoBlocks"; import { DimensionField, RotateField } from "./objectInfo/fields"; import { InfoGroups, hasInfoGroups } from "./objectInfo/InfoGroups"; @@ -73,6 +74,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 cameraSel = useStore((s) => s.selection.cameras); const ctxObj = sel?.kind === "contextObject" ? (storeProject.context ?? []).find((o) => o.id === sel.id) : undefined; const quantities = useMemo( () => (ctxObj?.type === "excavation" ? excavationQuantities(storeProject) : []), @@ -82,6 +84,8 @@ export function ObjectInfoPanel() { // ── Leerzustand ─────────────────────────────────────────────────────────── // [149] Baum gewählt: eigene Felder (Lage, Masse, Form, Bestand). if (sel === null && treeSel.length > 0) return ; + // [213] Kamera gewählt: Standpunkt, Ziel, Bildwinkel, Projektion, Sonne und „Kamera öffnen". + if (sel === null && cameraSel.length > 0) return ; if (sel === null && site[0] === "viewShadows") return ; if (sel === null && site.length > 0) { const sun = site[0] === "sunStudy"; diff --git a/src/panels/ViewSnapshotsPanel.tsx b/src/panels/ViewSnapshotsPanel.tsx index 1c908aa5..994e40dc 100644 --- a/src/panels/ViewSnapshotsPanel.tsx +++ b/src/panels/ViewSnapshotsPanel.tsx @@ -39,6 +39,7 @@ import { applyToSnapshotOps } from "../state/viewTemplates"; import { getState } from "../state/appStore"; import { patchItem } from "../core"; import { t } from "../i18n"; +import { CamerasGroup } from "./CamerasGroup"; // ── Baum-Icons (inline-SVG im Panel-Stil: 14px, stroke currentColor 1.4) ────── @@ -518,6 +519,7 @@ export function ViewSnapshotsPanel() { tree.rootFolders.length === 0 && tree.rootSnapshots.length === 0; return ( + <>
{t("viewsnap.title")} @@ -687,6 +689,9 @@ export function ViewSnapshotsPanel() { )}
+ {/* [213] Kameras des Projekts (öffnen, anlegen, löschen). */} + + ); } diff --git a/src/panels/objectInfo/CameraSection.tsx b/src/panels/objectInfo/CameraSection.tsx new file mode 100644 index 00000000..10647342 --- /dev/null +++ b/src/panels/objectInfo/CameraSection.tsx @@ -0,0 +1,133 @@ +// Abschnitt „Kamera" der Objekt-Info ([213]): Standpunkt und Augenhöhe, Ziel, Bildwinkel/Brennweite, Projektion, +// Sonnenstand und die Aktionen „Kamera öffnen" / „Aus aktueller Ansicht" / „Isometrisch". Jede Änderung ein Undo-Schritt +// (der Kern prüft die Op); bei mehreren gewählten Kameras wirken die Auswahlfelder auf alle. + +import type { Camera, CameraProjection } from "../../model/types"; +import { useStore } from "../../state/appStore"; +import { openCamera, updateCameraFromView } from "../../state/cameraActions"; +import { t } from "../../i18n"; +import type { TranslationKey } from "../../i18n"; +import { patchItem } from "../../core"; +import { Dropdown } from "../../ui/Dropdown"; +import { clampFov, focalFromFov, fovFromFocal, isometricAim } from "../../viewport/cameraView"; +import { DimensionField } from "./fields"; + +const PROJECTIONS: CameraProjection[] = ["perspective", "axonometric", "parallel"]; + +/** ISO-UTC-Text → Wert für `` (UTC-Anzeige, ohne Zeitzonen-Überraschung). */ +function toLocalInput(iso: string | undefined): string { + if (!iso) return ""; + const d = new Date(iso); + return Number.isFinite(d.getTime()) ? d.toISOString().slice(0, 16) : ""; +} + +export function CameraSection({ ids }: { ids: readonly string[] }) { + const project = useStore((st) => st.project); + const applyChange = useStore((s) => s.applyChange); + const cams = (project.cameras ?? []).filter((x) => ids.includes(x.id)); + const cam = cams[0]; + if (!cam) return
{t("objinfo.empty")}
; + const locked = !!cam.locked; + const set = (patch: Partial, all = false) => + applyChange((p) => (all ? cams : [cam]).filter((x) => !x.locked).flatMap((x) => patchItem(p, "cameras", x.id, patch))); + const level = project.drawingLevels.find((l) => l.id === cam.floorId); + const parallel = cam.projection !== "perspective"; + return ( +
+
+ {cams.length > 1 ? t("objinfo.camera.many", { n: cams.length }) : t("objinfo.kind.camera")} +
+
{t("objinfo.camera.section")}
+ +
+ {t("objinfo.camera.projection")} + set({ projection: v as CameraProjection }, true)} + options={PROJECTIONS.map((v) => ({ value: v, label: t(`objinfo.camera.projection.${v}` as TranslationKey) }))} + title={t("objinfo.camera.projection")} + width={150} + /> +
+
{t("objinfo.camera.stand")}
+ set({ position: { x: v, y: cam.position.y } })} /> + set({ position: { x: cam.position.x, y: v } })} /> + set({ eyeHeight: v })} /> +
{t("objinfo.camera.target")}
+ set({ target: { x: v, y: cam.target.y } })} /> + set({ target: { x: cam.target.x, y: v } })} /> + set({ targetHeight: v })} /> + {parallel ? ( + set({ orthoHeight: v })} /> + ) : ( + <> + set({ fovDeg: clampFov(v) })} /> + set({ fovDeg: clampFov(fovFromFocal(v)) })} + /> + + )} + +
+ {t("objinfo.column.floor")} + {level?.name ?? cam.floorId} +
+
+ + + {parallel && ( + + )} +
+ {locked &&
{t("objinfo.camera.locked")}
} +
+ ); +} diff --git a/src/panels/objectSettings/ObjectSettingsPanel.tsx b/src/panels/objectSettings/ObjectSettingsPanel.tsx index 1127809a..499974f1 100644 --- a/src/panels/objectSettings/ObjectSettingsPanel.tsx +++ b/src/panels/objectSettings/ObjectSettingsPanel.tsx @@ -18,7 +18,7 @@ const AREA_TITLE = { object: "objsettings.area.object", appearance: "objsettings export function ObjectSettingsPanel() { const host = usePanelHost(); const sel = useSelectionInfo(); - const otherSelected = useStore((s) => s.selection.trees.length + s.selection.site.length > 0); + const otherSelected = useStore((s) => s.selection.trees.length + s.selection.cameras.length + s.selection.site.length > 0); const isGrid = useStore((s) => (sel?.kind === "drawing2d" ? s.project.drawings2d.find((d) => d.id === sel.id)?.geom.shape === "grid" : false)); const wanted = useSyncExternalStore(subscribeSettingsArea, getSettingsArea, getSettingsArea); diff --git a/src/plan/__golden__/komplex-grundriss-eg-100.txt b/src/plan/__golden__/komplex-grundriss-eg-100.txt index 73173e1e..398a945f 100644 --- a/src/plan/__golden__/komplex-grundriss-eg-100.txt +++ b/src/plan/__golden__/komplex-grundriss-eg-100.txt @@ -1,13 +1,13 @@ viewBox -41.5 0 95 63.6 -bytes 66756 +bytes 68392 circle 16 g 1 -line 137 +line 141 path 36 -polygon 93 -polyline 92 +polygon 101 +polyline 93 rect 1 svg 1 -text 115 -tspan 24 -hash 754df2040d980729 +text 116 +tspan 25 +hash f73dd9a2827e46a8 diff --git a/src/plan/__golden__/komplex-grundriss-eg-50.txt b/src/plan/__golden__/komplex-grundriss-eg-50.txt index c0779f08..5a86482e 100644 --- a/src/plan/__golden__/komplex-grundriss-eg-50.txt +++ b/src/plan/__golden__/komplex-grundriss-eg-50.txt @@ -1,13 +1,13 @@ viewBox -41.5 0 95 63.6 -bytes 107266 +bytes 108914 circle 16 g 1 -line 361 +line 365 path 67 -polygon 216 -polyline 101 +polygon 224 +polyline 102 rect 1 svg 1 -text 115 -tspan 24 -hash e0c7011ad7ac9ebe +text 116 +tspan 25 +hash 4e369fc245359944 diff --git a/src/plan/pickLabels.ts b/src/plan/pickLabels.ts index 60e2f362..5e13a063 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" - | "tree" | "ceiling" | "stair" | "room" | "roof" | "site" | "context"; + | "tree" | "camera" | "ceiling" | "stair" | "room" | "roof" | "site" | "context"; type WithCategory = { id: string; categoryCode?: string }; @@ -26,6 +26,7 @@ function collection(project: Project, kind: PickKind): readonly WithCategory[] { case "context": return p.context ?? []; case "solid": return p.extrudedSolids ?? []; case "tree": return p.trees ?? []; + case "camera": return p.cameras ?? []; case "section": case "site": return []; } diff --git a/src/state/cameraActions.ts b/src/state/cameraActions.ts new file mode 100644 index 00000000..282bce44 --- /dev/null +++ b/src/state/cameraActions.ts @@ -0,0 +1,108 @@ +// [213] Aktionen zu Kamera-Elementen (`Project.cameras`): aus der aktuellen 3D-Ansicht anlegen, eine Kamera im 3D +// öffnen (Ansicht exakt setzen, Sonne übernehmen), die Kamera mit der aktuellen Ansicht überschreiben. Die Umrechnung +// Kamera ↔ Ansicht steht rein in `viewport/cameraView.ts`; hier hängt sie am Store, an den Reitern und am Viewport. + +import { addItems, patchItem, setField } from "../core"; +import { t } from "../i18n"; +import type { Camera } from "../model/types"; +import { getCamera, getCameraTargetDistance, setCamera, viewportAvailable } from "../viewport/cameraBridge"; +import { cameraFromView, cameraToView, nextCameraName } from "../viewport/cameraView"; +import { getState } from "./appStore"; +import { fromIds } from "./selection"; +import { switchViewType } from "./tabNavigation"; + +function newCameraId(): string { + const r = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID().slice(0, 8) : Math.random().toString(36).slice(2, 10); + return `cam-${r}`; +} + +/** Kamera aus der aktuellen 3D-Ansicht anlegen und wählen. Gibt die id zurück, `null` ohne 3D-Ansicht. */ +export function createCameraFromView(): string | null { + const st = getState(); + const view = viewportAvailable() ? getCamera() : null; + if (!view) { + st.notify(t("camera.noViewport"), "warning"); + return null; + } + const cam = cameraFromView(st.project, view, { + id: newCameraId(), + name: nextCameraName(st.project, t("camera.defaultName")), + fallbackFloorId: st.activeLevelId, + distance: getCameraTargetDistance() ?? undefined, + }); + st.applyChange(addItems("cameras", [cam])); + st.setSelection(fromIds("cameras", [cam.id])); + st.notify(t("camera.created", { name: cam.name }), "info"); + return cam.id; +} + +/** Wartet (höchstens `timeoutMs`), bis der 3D-Viewport Kamera-Zugriff meldet — nach dem Wechsel in den 3D-Reiter. */ +function whenViewportReady(timeoutMs = 3000): Promise { + if (viewportAvailable()) return Promise.resolve(true); + return new Promise((resolve) => { + const t0 = performance.now(); + const poll = () => { + if (viewportAvailable()) resolve(true); + else if (performance.now() - t0 > timeoutMs) resolve(false); + else requestAnimationFrame(poll); + }; + requestAnimationFrame(poll); + }); +} + +/** + * Kamera im 3D öffnen: in den 3D-Reiter wechseln, die Ansicht exakt setzen (Standpunkt, Blickrichtung, Bildwinkel, + * Projektion) und — hat die Kamera einen Sonnenstand — die Sonnenstudie darauf stellen (Schatten im 3D an). + */ +export async function openCamera(id: string): Promise { + const st = getState(); + const cam = (st.project.cameras ?? []).find((c) => c.id === id); + if (!cam) return false; + const view = cameraToView(st.project, cam); + if (!view) { + st.notify(t("camera.invalid", { name: cam.name }), "warning"); + return false; + } + if (!viewportAvailable()) switchViewType("perspektive"); + if (!(await whenViewportReady())) { + st.notify(t("camera.noViewport"), "warning"); + return false; + } + // Seitenverhältnis des Viewports behalten (die Brücke füllt es aus der Live-Kamera). + const live = getCamera(); + const placed = setCamera({ ...view, aspect: live?.aspect ?? view.aspect }, { animate: true }); + if (!placed) { + st.notify(t("camera.invalid", { name: cam.name }), "warning"); + return false; + } + if (cam.sunWhen && Number.isFinite(new Date(cam.sunWhen).getTime())) { + const study = getState().project.sunStudy; + if (study?.when !== cam.sunWhen || study.shadows3d !== true) { + getState().applyChange([setField("sunStudy", { ...(study ?? { show: false }), when: cam.sunWhen, shadows3d: true } as NonNullable)]); + } + } + return true; +} + +/** Kamera mit der aktuellen 3D-Ansicht überschreiben (Standpunkt, Ziel, Bildwinkel, Projektion; Name und Klasse bleiben). */ +export function updateCameraFromView(id: string): boolean { + const st = getState(); + const old = (st.project.cameras ?? []).find((c) => c.id === id); + const view = viewportAvailable() ? getCamera() : null; + if (!old || !view) { + st.notify(t("camera.noViewport"), "warning"); + return false; + } + const fresh = cameraFromView(st.project, view, { + id: old.id, + name: old.name, + fallbackFloorId: old.floorId, + distance: getCameraTargetDistance() ?? undefined, + categoryCode: old.categoryCode, + }); + const next: Camera = { ...old, ...fresh, locked: old.locked, sunWhen: old.sunWhen }; + if (fresh.projection === "perspective") delete next.orthoHeight; + st.applyChange((p) => patchItem(p, "cameras", id, () => next)); + st.notify(t("camera.updated", { name: old.name }), "info"); + return true; +} diff --git a/src/state/keyboardShortcuts.ts b/src/state/keyboardShortcuts.ts index 2fa16d07..b75d34e2 100644 --- a/src/state/keyboardShortcuts.ts +++ b/src/state/keyboardShortcuts.ts @@ -60,7 +60,8 @@ export type ShortcutId = | "showAllLayers" | "fitAll" | "fitSelection" - | "isolateLayer"; + | "isolateLayer" + | "walkMode"; export type ShortcutCategory = | "general" @@ -233,6 +234,9 @@ export const SHORTCUT_DEFS: ShortcutDef[] = [ { id: "fitSelection", category: "navigation", labelKey: "shortcut.fitSelection", defaultCombo: "mod+shift+f" }, // [192] Ebenen schnell schalten (Cmd/Ctrl+Shift+I ist der Boolean-Schnitt, daher L = Layer). { id: "isolateLayer", category: "navigation", labelKey: "shortcut.isolateLayer", defaultCombo: "mod+shift+l" }, + // [213] Begehen im 3D (WASD): Umschalt+F schaltet den Begehen-Modus; die Bewegungstasten selbst (W/A/S/D, Q/E, Pfeile) gelten nur + // darin, damit sie nicht mit „s" (Spiegeln), „d" (Drehen) und „q" (Messen) kollidieren (`viewport/walk.ts`). + { id: "walkMode", category: "navigation", labelKey: "shortcut.walkMode", defaultCombo: "shift+f" }, ]; const DEFS_BY_ID = new Map(SHORTCUT_DEFS.map((d) => [d.id, d])); diff --git a/src/state/mixedValues.ts b/src/state/mixedValues.ts index 20dd2280..a9821a8f 100644 --- a/src/state/mixedValues.ts +++ b/src/state/mixedValues.ts @@ -34,7 +34,7 @@ export interface SelectionAppearance { /** Zahl der gewählten Elemente (ohne Gruppen, Schnittlinien, Lage-Darstellung, Bäume). */ export function selectedCount(sel: Selection): number { - return ELEMENT_KINDS.filter((k) => k !== "sectionLines" && k !== "site" && k !== "trees").reduce((n, k) => n + sel[k].length, 0); + return ELEMENT_KINDS.filter((k) => k !== "sectionLines" && k !== "site" && k !== "trees" && k !== "cameras").reduce((n, k) => n + sel[k].length, 0); } /** Effektive Strichstärke und Farbe über die gewählten Wände/Decken/2D-Elemente. */ diff --git a/src/state/objectSettings.ts b/src/state/objectSettings.ts index 1e86267c..33d7c1f7 100644 --- a/src/state/objectSettings.ts +++ b/src/state/objectSettings.ts @@ -23,7 +23,7 @@ export function openObjectSettings(deps: ObjectSettingsDeps): boolean { const sel = selectionInfoFor(project, selection); let target = objectSettingsTarget(sel, deps.activeTool, isGridDrawing(sel?.kind === "drawing2d" ? sel.id : undefined)); // Baum, Lage-Darstellung und Schnittlinie sind keine `SelectionInfo`, haben aber ihre Felder in der Objekt-Info. - if (!target && (selection.trees.length > 0 || selection.site.length > 0 || selection.sectionLines.length > 0)) { + if (!target && (selection.trees.length > 0 || selection.cameras.length > 0 || selection.site.length > 0 || selection.sectionLines.length > 0)) { target = { group: selection.sectionLines.length > 0 ? "sectionLine" : null }; } if (!target) return false; diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index d43f2e51..ad85586d 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -390,6 +390,8 @@ export interface ProjectSlice { moveExcavationGrip: (id: string, index: number, pt: Vec2) => void; /** [176] Griff einer Schnittlinie: 0 = Anfang, dann die Knickpunkte, zuletzt das Ende. */ moveSectionLineGrip: (id: string, index: number, pt: Vec2, coalesceKey?: string) => void; + /** [213] Griff einer Kamera: 0 = Standpunkt, 1 = Ziel, 2 = Bildwinkel/Sichtbreite. */ + moveCameraGrip: (id: string, index: number, pt: Vec2) => void; /** [176] Knick in Segment `seg` (Mittel-Griff) einfügen; `coalesceKey` fasst den anschliessenden Zug zusammen. */ insertSectionBend: (id: string, seg: number, pt: Vec2, coalesceKey?: string) => void; /** [176] Knick löschen (`index` wie bei {@link moveSectionLineGrip}; Anfang/Ende lassen sich nicht löschen). */ @@ -1296,6 +1298,7 @@ export function createProjectSlice( moveExcavationGrip: (id, index, pt) => applyGrip({ op: "excavationGrip", id, index, pt: gripPt(pt) }, `moveExcavationGrip:${id}:${index}`), moveSectionLineGrip: (id, index, pt, coalesceKey) => applyGrip({ op: "sectionLineGrip", id, index, pt: gripPt(pt) }, coalesceKey ?? `moveSectionLineGrip:${id}:${index}`), + moveCameraGrip: (id, index, pt) => applyGrip({ op: "cameraGrip", id, index, pt: gripPt(pt) }, `moveCameraGrip:${id}:${index}`), insertSectionBend: (id, seg, pt, coalesceKey) => applyGrip({ op: "sectionBendInsert", id, seg, pt: gripPt(pt) }, coalesceKey), deleteSectionBend: (id, index) => applyGrip({ op: "sectionBendDelete", id, index }), moveRingVertex: (kind, id, index, pt, coalesceKey) => { diff --git a/src/state/selection.ts b/src/state/selection.ts index f1ee3bd6..77d2d448 100644 --- a/src/state/selection.ts +++ b/src/state/selection.ts @@ -39,6 +39,8 @@ export interface Selection { site: string[]; /** [149] Bäume (`Project.trees`). */ trees: string[]; + /** [213] Kameras (`Project.cameras`). */ + cameras: string[]; /** * Gewählte Gruppen — rein informativ (Bounding-Box, Doppelklick-Ziel); die * Mitglieder stehen zusätzlich in den übrigen Arten (s. `groupActions.ts`). @@ -63,6 +65,7 @@ export const SELECTION_KINDS: readonly SelectionKind[] = [ "sectionLines", "site", "trees", + "cameras", "groups", ]; @@ -184,6 +187,8 @@ export interface SelectionIdLists { groupIds: string[]; /** [149] Bäume (nicht gruppierbar; Zwischenablage, Nachauswahl). */ treeIds?: string[]; + /** [213] Kameras (nicht gruppierbar). */ + cameraIds?: string[]; } const ID_LIST_KEYS: [SelectionKind, keyof SelectionIdLists][] = [ @@ -200,6 +205,7 @@ const ID_LIST_KEYS: [SelectionKind, keyof SelectionIdLists][] = [ ["sectionLines", "sectionLineIds"], ["groups", "groupIds"], ["trees", "treeIds"], + ["cameras", "cameraIds"], ]; /** Auswahl → `…Ids`-Listen (passt strukturell auf `GroupMembership` und `BcfSelection`). */ diff --git a/src/state/tabNavigation.ts b/src/state/tabNavigation.ts index 55c178c6..58f6cc3c 100644 --- a/src/state/tabNavigation.ts +++ b/src/state/tabNavigation.ts @@ -63,5 +63,5 @@ export function hideSelectionIn3d(): void { const ids = selectionIds3d(st.selection); if (!ids.length) return; setView3dFilter(hideSelection3d(getView3dFilter(), ids)); - st.setSelection(clearKinds("walls", "ceilings", "openings", "stairs", "solids", "columns", "roofs", "contextObjects", "trees", "drawings", "groups")); + st.setSelection(clearKinds("walls", "ceilings", "openings", "stairs", "solids", "columns", "roofs", "contextObjects", "trees", "cameras", "drawings", "groups")); } diff --git a/src/state/useGripEditing.ts b/src/state/useGripEditing.ts index e357bdd4..85f5ddda 100644 --- a/src/state/useGripEditing.ts +++ b/src/state/useGripEditing.ts @@ -51,6 +51,7 @@ import { getPlanViewport, subscribePlanViewport } from "./planViewport"; import { growRect, meshGripIndices } from "../core"; import { patchItem, verticalExtents } from "../core"; import { treeGripPatch, treeGripPoints } from "./treeGrips"; +import { cameraGripPoints } from "../core"; import type { Selection } from "./selection"; export interface GripEditFieldsState { @@ -209,6 +210,9 @@ export function useGripEditing(opts: { const meshViewport = useSyncExternalStore(subscribePlanViewport, () => (selectedMesh && selectedMesh.positions.length / 3 > 600 ? getPlanViewport() : null)); const selectedTreeId = single(selection, "trees"); const selectedTree = selectedTreeId ? (project.trees ?? []).find((x) => x.id === selectedTreeId) : undefined; + // [213] Kamera: Griffe an Standpunkt, Ziel und Sichtkegel-Rand (Bildwinkel); nur auf dem Geschoss der Kamera. + const selectedCameraId = single(selection, "cameras"); + const selectedCamera = selectedCameraId ? (project.cameras ?? []).find((x) => x.id === selectedCameraId && x.floorId === levelId) : undefined; // [176] Schnitt-/Ansichtslinie im Grundriss: Griffe an Anfang, Knickpunkten (`bendPoints`) und Ende. const selectedSectionLineId = single(selection, "sectionLines"); const selectedSectionLine = modelEditable && selectedSectionLineId @@ -510,6 +514,11 @@ export function useGripEditing(opts: { pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); }); return pts; } + if (selectedCamera && modelEditable && !selectedCamera.locked) { + const pts = cameraGripPoints(selectedCamera, scaleDenominator); + pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); }); + return pts; + } if (selectedTree && modelEditable && !selectedTree.locked) { const pts = treeGrips(selectedTree); pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); }); @@ -1238,6 +1247,11 @@ export function useGripEditing(opts: { else if (st) moveStairBy(st.id, sub(pt, stairMoveHandle(st))); return; } + // [213] Kamera: Standpunkt, Ziel bzw. Sichtkegel-Rand live (Kern `camera::grip_edit`), ein Undo-Schritt je Zug. + if (selectedCamera) { + if (!selectedCamera.locked) storeState().moveCameraGrip(selectedCamera.id, index, pt); + return; + } // [149] Baum: Stammmitte, Kronenrand bzw. Beschriftung live, ein Undo-Schritt je Zug (gleicher coalesceKey). if (selectedTree) { const tr = selectedTree; diff --git a/src/state/useMouseSelectionHandlers.ts b/src/state/useMouseSelectionHandlers.ts index d4843906..c30bfea1 100644 --- a/src/state/useMouseSelectionHandlers.ts +++ b/src/state/useMouseSelectionHandlers.ts @@ -215,6 +215,7 @@ export function useMouseSelectionHandlers(opts: { context: "contextObjects", site: "site", tree: "trees", + camera: "cameras", } as const satisfies Record; type Kind = keyof typeof channels; const target: { kind: Kind; id: string } | null = sel.sectionLineId @@ -235,6 +236,8 @@ export function useMouseSelectionHandlers(opts: { ? { kind: "solid", id: sel.extrudedSolidId } : sel.treeId ? { kind: "tree", id: sel.treeId } + : sel.cameraId + ? { kind: "camera", id: sel.cameraId } : sel.columnId ? { kind: "column", id: sel.columnId } : sel.roofId @@ -301,7 +304,9 @@ export function useMouseSelectionHandlers(opts: { ? ["site", sel.siteId] : sel.treeId ? ["trees", sel.treeId] - : null; + : sel.cameraId + ? ["cameras", sel.cameraId] + : null; setSelection({ ...clearKinds(), groups: [], ...(one ? { [one[0]]: [one[1]] } : {}) }); }; // Links-Drag (Marquee) im Grundriss: die getroffene Wand-MENGE übernehmen @@ -353,6 +358,7 @@ export function useMouseSelectionHandlers(opts: { stairs: expanded.stairIds, rooms: expanded.roomIds, trees: expanded.treeIds, + cameras: sel.cameraIds ?? [], groups: groupIds, }); }; diff --git a/src/state/useSelectionCommands.ts b/src/state/useSelectionCommands.ts index c3b54a55..7049e951 100644 --- a/src/state/useSelectionCommands.ts +++ b/src/state/useSelectionCommands.ts @@ -151,6 +151,8 @@ export function useSelectionCommands(opts: { 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)); + // [213] Kameras (gesperrte bleiben). + const camids = new Set(selection.cameras.filter((id) => !(project.cameras ?? []).find((c) => c.id === id)?.locked)); // [193] Abgeleitete Lage-Darstellung (Schatten, Baurecht) ist kein Element: Entf blendet sie aus // (`show: false`; über die Lage-Panels wieder einschaltbar). const siteHide: ReturnType = []; @@ -175,6 +177,7 @@ export function useSelectionCommands(opts: { ...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), + ...removeItems(p, "cameras", camids), ]), ); }; diff --git a/src/styles.css b/src/styles.css index 03bb8de4..349196c6 100644 --- a/src/styles.css +++ b/src/styles.css @@ -2077,6 +2077,36 @@ body { height: 100% !important; } +/* [213] Begehen und Kamera anlegen: kleine Knöpfe oben rechts im 3D-Viewport. */ +.viewport3d-tools { + position: absolute; + top: 8px; + right: 8px; + z-index: 6; + display: flex; + gap: 6px; +} +.viewport3d-tool { + padding: 3px 9px; + border: 1px solid var(--line); + border-radius: 999px; + background: var(--panel); + color: var(--label); + font-size: 11px; + cursor: pointer; + opacity: 0.85; +} +.viewport3d-tool:hover { + background: var(--panel-2); + opacity: 1; +} +.viewport3d-tool.is-on { + background: var(--active-dim); + border-color: var(--active-light); + color: var(--active-light); + opacity: 1; +} + .viewport-fallback { position: absolute; inset: 0; diff --git a/src/viewport/README.md b/src/viewport/README.md index a7719d23..bf5d5ca2 100644 --- a/src/viewport/README.md +++ b/src/viewport/README.md @@ -11,6 +11,8 @@ kommt als Teile aus dem Kern (`src/plan/toWalls3d.ts`). Weg eines Modells in den | `Wasm3DViewport.tsx` | die 3D-Ansicht: Canvas, Maus und Tastatur, Auswahl, Griffe, Cursor-HUD, Live-Schnitt | | `Viewport3D.tsx` | Zugang zur Ansicht (`Viewport3D = Wasm3DViewport`) und die geteilten Typen (`RenderDisplay`, `DisplayResolver`) | | `useWasm3dRenderer.ts` | Hook: lädt render3d, hält Modell, Kamera und Punktwolken, zeichnet; Typ `Camera3d` | +| `cameraView.ts` | [213] Kamera-Element (`Project.cameras`) ↔ Sicht des Viewports: `cameraToView`, `cameraFromView`, Brennweite, Geschoss zur Höhe | +| `walk.ts` | [213] Begehen (WASD): Bewegung und Umschauen als reine Funktionen auf dem Orbit-Zustand | | `cameraBridge.ts` | Kamera von aussen lesen und setzen, Bild-Schnappschuss, Live-Schnittebene (für BCF-Viewpoints) | ## Abgleich mit render3d diff --git a/src/viewport/Wasm3DViewport.tsx b/src/viewport/Wasm3DViewport.tsx index 2e6c549d..17a11a10 100644 --- a/src/viewport/Wasm3DViewport.tsx +++ b/src/viewport/Wasm3DViewport.tsx @@ -81,6 +81,9 @@ import { type OrbitState, type V3 as CamV3, } from "./cameraBridge"; +import { NO_KEYS, WALK_SPEED, anyKey, lookAround, speedFactor, stepWalk, walkKeyAllowed, walkKeyOf, type WalkKeys } from "./walk"; +import { loadShortcutOverrides, matchesShortcut } from "../state/keyboardShortcuts"; +import { createCameraFromView } from "../state/cameraActions"; /** Ein per 3D-Klick getroffenes Bauteil, oder null (Leerraum). */ export type Pick3dHit = @@ -594,6 +597,10 @@ export function Wasm3DViewport({ // stabile Pointer-Listener-Effekt stets den aktuellen Befehlszustand liest. const commandActiveRef = useRef(commandActive); commandActiveRef.current = commandActive; + // [213] Begehen-Modus (Umschalt+F / Knopf): WASD, Q/E und Pfeile bewegen die Kamera, Maus ziehen schaut um. + const [walkMode, setWalkMode] = useState(false); + const walkModeRef = useRef(false); + walkModeRef.current = walkMode; const onWorkplanePointRef = useRef(onWorkplanePoint); onWorkplanePointRef.current = onWorkplanePoint; const onWorkplaneConfirmRef = useRef(onWorkplaneConfirm); @@ -1381,6 +1388,89 @@ export function Wasm3DViewport({ return () => window.removeEventListener("keydown", onKey); }, []); + // [213] Begehen (WASD): Umschalt+F schaltet den Modus, darin bewegen W/A/S/D und die Pfeiltasten die Kamera + // (vor/zurück/seitlich in der Horizontalen, Augenhöhe bleibt), Q/E senken und heben, Umschalt = schneller, Alt = + // langsamer. Die Tasten gelten NUR im Modus — sonst kollidieren sie mit „s" (Spiegeln), „d" (Drehen), „q" (Messen). + // Pro Frame (rAF) mit gekapptem Zeitschritt; Textfelder und Befehls-Modifikatoren (Strg/Cmd) sperren. Rechnung rein + // in `walk.ts`. Die Handler laufen in der Capture-Phase und verbrauchen die Bewegungstasten, damit globale Kürzel + // nicht zusätzlich feuern. + useEffect(() => { + if (!ready) return; + const keys: WalkKeys = { ...NO_KEYS }; + const mods = { shift: false, alt: false }; + let raf = 0; + let last = 0; + const redrawOrbit = () => { + redrawRef.current = () => { + if (orbitRef.current) render(orbitCamera(orbitRef.current)); + }; + redrawRef.current(); + }; + const tick = (now: number) => { + raf = 0; + if (!walkModeRef.current || !anyKey(keys)) return; + const o = orbitRef.current; + if (o) { + const dt = last ? (now - last) / 1000 : 0; + orbitRef.current = stepWalk(o, keys, dt, WALK_SPEED * speedFactor(mods.shift, mods.alt)); + redrawOrbit(); + } + last = now; + raf = requestAnimationFrame(tick); + }; + const start = () => { + if (raf === 0) { + last = 0; + raf = requestAnimationFrame(tick); + } + }; + const release = () => { + Object.assign(keys, NO_KEYS); + }; + const onKeyDown = (e: KeyboardEvent) => { + mods.shift = e.shiftKey; + mods.alt = e.altKey; + if (!walkKeyAllowed(e, document.activeElement)) return; + if (!e.repeat && matchesShortcut(e, "walkMode", loadShortcutOverrides())) { + e.preventDefault(); + e.stopPropagation(); + setWalkMode((w) => !w); + release(); + return; + } + if (!walkModeRef.current || commandActiveRef.current || gripDragRef.current) return; + if (e.key === "Escape") { + setWalkMode(false); + release(); + return; + } + const k = walkKeyOf(e.code); + if (!k) return; + e.preventDefault(); + e.stopPropagation(); + keys[k] = true; + start(); + }; + const onKeyUp = (e: KeyboardEvent) => { + mods.shift = e.shiftKey; + mods.alt = e.altKey; + const k = walkKeyOf(e.code); + if (k && keys[k]) { + keys[k] = false; + e.stopPropagation(); + } + }; + window.addEventListener("keydown", onKeyDown, true); + window.addEventListener("keyup", onKeyUp, true); + window.addEventListener("blur", release); + return () => { + window.removeEventListener("keydown", onKeyDown, true); + window.removeEventListener("keyup", onKeyUp, true); + window.removeEventListener("blur", release); + cancelAnimationFrame(raf); + }; + }, [ready, render]); + // Maus-Navigation (LINKS = Orbit, MITTE/RECHTS = Pan, RAD = Zoom, s. // Datei-Kommentar MAUS-SCHEMA). Verlässt damit IMMER die Praeset-Kamera und // wechselt auf die freie perspektivische Orbit-Kamera (Kontinuität über den @@ -1398,7 +1488,7 @@ export function Wasm3DViewport({ }; let drag: { - mode: "orbit" | "pan"; + mode: "orbit" | "pan" | "look"; button: number; x: number; y: number; @@ -1469,7 +1559,8 @@ export function Wasm3DViewport({ }; const onPointerDown = (e: PointerEvent) => { - const mode = e.button === 0 ? "orbit" : e.button === 1 || e.button === 2 ? "pan" : null; + // [213] Im Begehen-Modus schaut auch die rechte Taste um (statt zu schwenken); die mittlere schwenkt weiter. + const mode = e.button === 0 ? "orbit" : e.button === 2 && walkModeRef.current ? "look" : e.button === 1 || e.button === 2 ? "pan" : null; if (!mode) return; e.preventDefault(); drag = { @@ -1525,7 +1616,10 @@ export function Wasm3DViewport({ return; } const h = canvas.clientHeight || 1; - if (drag.mode === "orbit") { + if (drag.mode === "look" || (drag.mode === "orbit" && walkModeRef.current)) { + // [213] Umschauen um den Augpunkt (Orbit-Zustand bleibt die Wahrheit, das Ziel wandert mit). + orbitRef.current = lookAround(o, dx, dy); + } else if (drag.mode === "orbit") { // Winkel je Pixel wie OrbitControls: voller Umlauf über die Viewport-Höhe. o.yaw += (2 * Math.PI * dx) / h; o.pitch = Math.max( @@ -1716,6 +1810,30 @@ export function Wasm3DViewport({ Darstellungsart kommen von der Oberleiste (TopBar); das Grid-Overlay unten ist der einzige eigene Umschalter hier. */} + {/* [213] Begehen (WASD) und Kamera aus der aktuellen Ansicht anlegen. */} +
+ + +
{/* Achsen-Lock-Führungslinie (Pfeiltasten während eines Endpunkt-/ Verschiebe-Griff-Drags, s. `axisLockRef`-Dateikommentar) — SketchUp- Vorbild: eine durchgezogene farbige Linie durch den Anker markiert diff --git a/src/viewport/cameraBridge.ts b/src/viewport/cameraBridge.ts index bf582df1..9b70b9e1 100644 --- a/src/viewport/cameraBridge.ts +++ b/src/viewport/cameraBridge.ts @@ -242,6 +242,14 @@ export function getCamera(): ViewCamera | null { return r ? viewCameraFromCamera3d(r.camera, r.aspect) : null; } +/** [213] Abstand zwischen Augpunkt und Blickziel der Live-Kamera (Meter), oder null ohne Viewport. */ +export function getCameraTargetDistance(): number | null { + const r = api?.read(); + if (!r) return null; + const d = len(sub(r.camera.target, r.camera.eye)); + return Number.isFinite(d) && d > 0 ? d : null; +} + /** Kamera setzen. `false` ohne Viewport oder bei unbrauchbarer Kamera (NaN, Nullvektor). */ /** [C10] Systemeinstellung „Bewegung reduzieren": Kamerafahrten springen dann direkt ans Ziel. */ export function prefersReducedMotion(): boolean { diff --git a/src/viewport/cameraView.test.ts b/src/viewport/cameraView.test.ts new file mode 100644 index 00000000..435a4b22 --- /dev/null +++ b/src/viewport/cameraView.test.ts @@ -0,0 +1,158 @@ +import { describe, expect, it } from "vitest"; +import type { Camera, Project } from "../model/types"; +import { emptyProject } from "../model/sampleProject"; +import { + cameraEye, + cameraFromView, + cameraToView, + clampFov, + floorForHeight, + focalFromFov, + fovFromFocal, + isometricAim, + nextCameraName, +} from "./cameraView"; +import { camera3dFromViewCamera, viewCameraFromCamera3d } from "./cameraBridge"; + +const level = (id: string, baseElevation: number, kind: "floor" | "section" = "floor") => + ({ id, name: id, kind, visible: true, locked: false, baseElevation, floorHeight: 2.8 }) as Project["drawingLevels"][number]; + +const project = (): Project => ({ + ...emptyProject, + drawingLevels: [level("eg", 0), level("og", 3), level("schnitt", 0, "section")], +}); + +const cam = (over: Partial = {}): Camera => ({ + id: "k1", + type: "camera", + name: "Süd", + floorId: "og", + categoryCode: "92", + position: { x: 2, y: -3 }, + eyeHeight: 1.6, + target: { x: 2, y: 7 }, + targetHeight: 4.6, + fovDeg: 50, + projection: "perspective", + ...over, +}); + +describe("[213] Kamera → Ansicht", () => { + it("Augenhöhe liegt über der Geschoss-OK; Blickrichtung zeigt zum Ziel", () => { + const p = project(); + expect(cameraEye(p, cam())).toEqual([2, -3, 4.6]); + const v = cameraToView(p, cam())!; + expect(v.kind).toBe("perspective"); + expect(v.position).toEqual([2, -3, 4.6]); + expect(v.direction[0]).toBeCloseTo(0, 12); + expect(v.direction[1]).toBeCloseTo(1, 12); + expect(v.direction[2]).toBeCloseTo(0, 12); + expect(v.fovDeg).toBe(50); + // Up steht senkrecht zur Blickrichtung und zeigt nach oben. + expect(v.up[2]).toBeCloseTo(1, 12); + expect(v.up[0] * v.direction[0] + v.up[1] * v.direction[1] + v.up[2] * v.direction[2]).toBeCloseTo(0, 12); + }); + + it("geneigter Blick: Up bleibt senkrecht und normiert", () => { + const v = cameraToView(project(), cam({ targetHeight: 0 }))!; + expect(v.direction[2]).toBeLessThan(0); + expect(Math.hypot(...v.up)).toBeCloseTo(1, 12); + expect(v.up[0] * v.direction[0] + v.up[1] * v.direction[1] + v.up[2] * v.direction[2]).toBeCloseTo(0, 12); + expect(v.up[2]).toBeGreaterThan(0); + }); + + it("senkrechter Blick nach unten: Up ist Norden (Grundriss-Lage)", () => { + const v = cameraToView(project(), cam({ target: { x: 2, y: -3 }, targetHeight: 0 }))!; + expect(v.direction[2]).toBeCloseTo(-1, 12); + expect(v.up[1]).toBeCloseTo(1, 9); + }); + + it("Axonometrie und Parallel sind orthogonal mit Sichthöhe; Bildwinkel wird geklemmt", () => { + const a = cameraToView(project(), cam({ projection: "axonometric", orthoHeight: 8 }))!; + expect(a.kind).toBe("orthogonal"); + expect(a.orthoHeight).toBe(8); + expect(cameraToView(project(), cam({ projection: "parallel" }))!.orthoHeight).toBe(10); + expect(cameraToView(project(), cam({ fovDeg: 500 }))!.fovDeg).toBe(120); + expect(clampFov(NaN)).toBe(50); + }); + + it("Standpunkt gleich Ziel oder NaN: keine Ansicht", () => { + expect(cameraToView(project(), cam({ target: { x: 2, y: -3 }, targetHeight: 4.6 }))).toBeNull(); + expect(cameraToView(project(), cam({ position: { x: NaN, y: 0 } }))).toBeNull(); + }); + + it("liefert dieselbe Struktur wie die aktive 3D-Ansicht: Umweg über die Viewport-Kamera ist verlustfrei", () => { + const v = cameraToView(project(), cam({ targetHeight: 2 }), 1.5)!; + const c3 = camera3dFromViewCamera(v, 10)!; + const back = viewCameraFromCamera3d(c3, 1.5)!; + expect(back.kind).toBe(v.kind); + back.position.forEach((x, i) => expect(x).toBeCloseTo(v.position[i], 9)); + back.direction.forEach((x, i) => expect(x).toBeCloseTo(v.direction[i], 9)); + back.up.forEach((x, i) => expect(x).toBeCloseTo(v.up[i], 9)); + expect(back.fovDeg).toBeCloseTo(v.fovDeg, 9); + expect(back.aspect).toBe(1.5); + }); +}); + +describe("[213] Ansicht → Kamera", () => { + it("Standpunkt bestimmt Geschoss und Augenhöhe; Ziel liegt auf der Blickachse", () => { + const p = project(); + const view = cameraToView(p, cam({ targetHeight: 3.6 }))!; + const made = cameraFromView(p, view, { id: "k2", name: "Neu", fallbackFloorId: "eg", distance: Math.hypot(10, 1) }); + expect(made.floorId).toBe("og"); + expect(made.eyeHeight).toBeCloseTo(1.6, 9); + expect(made.position).toEqual({ x: 2, y: -3 }); + expect(made.target.x).toBeCloseTo(2, 9); + expect(made.target.y).toBeCloseTo(7, 9); + expect(made.targetHeight).toBeCloseTo(3.6, 9); + expect(made.projection).toBe("perspective"); + expect(made.categoryCode).toBe("92"); + expect(made.type).toBe("camera"); + // Wieder in die Ansicht: dieselbe Kamera. + const again = cameraToView(p, made)!; + again.position.forEach((x, i) => expect(x).toBeCloseTo(view.position[i], 9)); + again.direction.forEach((x, i) => expect(x).toBeCloseTo(view.direction[i], 9)); + }); + + it("orthografische Ansicht wird zur Parallelprojektion mit Sichthöhe", () => { + const p = project(); + const view = cameraToView(p, cam({ projection: "axonometric", orthoHeight: 12 }))!; + const made = cameraFromView(p, view, { id: "k3", name: "Ortho", fallbackFloorId: "eg" }); + expect(made.projection).toBe("parallel"); + expect(made.orthoHeight).toBe(12); + }); + + it("Geschoss zu einer Höhe: höchstes mit OK ≤ z, sonst das unterste, Schnitte zählen nicht", () => { + const p = project(); + expect(floorForHeight(p, 4.6, "x")).toBe("og"); + expect(floorForHeight(p, 2.99, "x")).toBe("eg"); + expect(floorForHeight(p, -5, "x")).toBe("eg"); + expect(floorForHeight(p, NaN, "x")).toBe("x"); + expect(floorForHeight({ ...p, drawingLevels: [] }, 1, "fallback")).toBe("fallback"); + }); + + it("Namen zählen hoch", () => { + const p = { ...project(), cameras: [cam({ name: "Kamera 1" }), cam({ id: "k2", name: "Kamera 2" })] }; + expect(nextCameraName(p, "Kamera")).toBe("Kamera 3"); + expect(nextCameraName(project(), "Kamera")).toBe("Kamera 1"); + }); +}); + +describe("[213] Brennweite und Axonometrie", () => { + it("Brennweite ↔ Bildwinkel (24 mm Sensorhöhe)", () => { + expect(fovFromFocal(focalFromFov(50))).toBeCloseTo(50, 9); + expect(fovFromFocal(35)).toBeCloseTo(37.85, 1); + }); + + it("Isometrie-Ausrichtung behält das Ziel im Blick und neigt 35.264°", () => { + const p = project(); + const c = cam({ projection: "axonometric" }); + const aim = isometricAim(p, c); + const next = { ...c, ...aim }; + const v = cameraToView(p, next)!; + // Blick nach oben-rechts hinten: 45° im Grundriss, 35.264° nach unten. + expect(v.direction[0]).toBeCloseTo(Math.SQRT1_2 * Math.cos(Math.atan(1 / Math.SQRT2)), 6); + expect(v.direction[1]).toBeCloseTo(Math.SQRT1_2 * Math.cos(Math.atan(1 / Math.SQRT2)), 6); + expect(v.direction[2]).toBeCloseTo(-Math.sin(Math.atan(1 / Math.SQRT2)), 6); + }); +}); diff --git a/src/viewport/cameraView.ts b/src/viewport/cameraView.ts new file mode 100644 index 00000000..9f13cc51 --- /dev/null +++ b/src/viewport/cameraView.ts @@ -0,0 +1,152 @@ +// [213] Kamera-Element (`Project.cameras`) ↔ Sicht des 3D-Viewports. Reine Funktionen, ohne React und Engine. +// +// `cameraToView` liefert dieselbe Struktur wie die aktive 3D-Ansicht (`getCamera()` der `cameraBridge`: Modell- +// Koordinaten, z oben) — damit setzt „Kamera öffnen" den Viewport exakt, und das Rendering ([211]) kann eine +// gespeicherte Kamera wie die Live-Ansicht verwenden. `cameraFromView` legt umgekehrt aus der Live-Ansicht ein +// Kamera-Element an (Standpunkt → Geschoss + Augenhöhe). + +import type { Camera, DrawingLevel, Project, Vec2 } from "../model/types"; +import { CAMERA_CATEGORY } from "../model/derivedCategories"; +import type { V3, ViewCamera } from "./cameraBridge"; + +/** Vorgaben wie im Kern (`camera.rs`). */ +export const DEFAULT_EYE_HEIGHT = 1.6; +export const DEFAULT_FOV_DEG = 50; +export const DEFAULT_ORTHO_HEIGHT = 10; +export const MIN_FOV_DEG = 5; +export const MAX_FOV_DEG = 120; +/** Sensorhöhe für die Kleinbild-Brennweite (mm), wie im Kern. */ +export const SENSOR_HEIGHT_MM = 24; +/** Blickweite beim Anlegen aus einer Ansicht, wenn der Viewport keinen Zielabstand meldet (m). */ +export const DEFAULT_AIM_DISTANCE = 10; + +/** Kleinbild-Brennweite (mm) zum vertikalen Bildwinkel (Grad). */ +export function focalFromFov(fovDeg: number): number { + return SENSOR_HEIGHT_MM / 2 / Math.tan((fovDeg * Math.PI) / 360); +} + +/** Vertikaler Bildwinkel (Grad) zur Kleinbild-Brennweite (mm). */ +export function fovFromFocal(mm: number): number { + return (2 * Math.atan(SENSOR_HEIGHT_MM / 2 / mm) * 180) / Math.PI; +} + +export function clampFov(fovDeg: number): number { + return Number.isFinite(fovDeg) && fovDeg > 0 ? Math.min(MAX_FOV_DEG, Math.max(MIN_FOV_DEG, fovDeg)) : DEFAULT_FOV_DEG; +} + +const finite = (...v: number[]): boolean => v.every(Number.isFinite); + +/** Höhe der Geschoss-OK (m), 0 ohne Angabe. */ +export function floorBase(project: Project, floorId: string): number { + const z = project.drawingLevels.find((l) => l.id === floorId)?.baseElevation; + return typeof z === "number" && Number.isFinite(z) ? z : 0; +} + +/** Augpunkt der Kamera in Modell-Koordinaten (Meter, z oben). */ +export function cameraEye(project: Project, cam: Camera): V3 { + return [cam.position.x, cam.position.y, floorBase(project, cam.floorId) + (Number.isFinite(cam.eyeHeight) ? cam.eyeHeight : DEFAULT_EYE_HEIGHT)]; +} + +/** Ziel der Kamera in Modell-Koordinaten. */ +export function cameraTarget(cam: Camera): V3 { + return [cam.target.x, cam.target.y, cam.targetHeight]; +} + +/** + * Die Sicht der Kamera: Standpunkt, normierte Blickrichtung und Up-Vektor (senkrecht zur Blickrichtung, aus der + * Modell-Senkrechten; bei exakt senkrechtem Blick gilt die Grundriss-Richtung „oben = Norden"). Perspektive → + * `perspective`, Axonometrie und Parallel → `orthogonal`. Null bei Standpunkt = Ziel oder nicht endlichen Zahlen. + */ +export function cameraToView(project: Project, cam: Camera, aspect = 16 / 9): ViewCamera | null { + const eye = cameraEye(project, cam); + const tgt = cameraTarget(cam); + if (!finite(...eye, ...tgt)) return null; + const d: V3 = [tgt[0] - eye[0], tgt[1] - eye[1], tgt[2] - eye[2]]; + const len = Math.hypot(d[0], d[1], d[2]); + if (!(len > 1e-9)) return null; + const dir: V3 = [d[0] / len, d[1] / len, d[2] / len]; + // Up aus der Modell-Senkrechten; ist der Blick (fast) senkrecht, aus der Nordrichtung. + const ref: V3 = Math.abs(dir[2]) > 0.9999 ? [0, 1, 0] : [0, 0, 1]; + const k = ref[0] * dir[0] + ref[1] * dir[1] + ref[2] * dir[2]; + const upRaw: V3 = [ref[0] - dir[0] * k, ref[1] - dir[1] * k, ref[2] - dir[2] * k]; + const ul = Math.hypot(upRaw[0], upRaw[1], upRaw[2]); + const up: V3 = [upRaw[0] / ul, upRaw[1] / ul, upRaw[2] / ul]; + const ortho = cam.projection !== "perspective"; + return { + kind: ortho ? "orthogonal" : "perspective", + position: eye, + direction: dir, + up, + fovDeg: clampFov(cam.fovDeg), + orthoHeight: cam.orthoHeight && cam.orthoHeight > 0 ? cam.orthoHeight : DEFAULT_ORTHO_HEIGHT, + aspect: Number.isFinite(aspect) && aspect > 0 ? aspect : 16 / 9, + }; +} + +/** Geschoss, auf dem ein Standpunkt der Höhe `z` steht: das höchste Geschoss mit OK ≤ z (sonst das unterste, sonst `fallback`). */ +export function floorForHeight(project: Project, z: number, fallback: string): string { + const floors = project.drawingLevels.filter((l: DrawingLevel) => l.kind === "floor"); + if (!floors.length || !Number.isFinite(z)) return fallback; + const base = (l: DrawingLevel) => (typeof l.baseElevation === "number" && Number.isFinite(l.baseElevation) ? l.baseElevation : 0); + const sorted = [...floors].sort((a, b) => base(a) - base(b)); + let hit = sorted[0]; + for (const l of sorted) if (base(l) <= z + 1e-6) hit = l; + return hit.id; +} + +/** Nächster freier Name „Kamera 1", „Kamera 2" … (`label` = Namensstamm). */ +export function nextCameraName(project: Project, label: string): string { + const used = new Set((project.cameras ?? []).map((c) => c.name)); + for (let n = 1; ; n++) if (!used.has(`${label} ${n}`)) return `${label} ${n}`; +} + +export interface CameraFromViewOptions { + id: string; + name: string; + /** Geschoss des Symbols; fehlt = das Geschoss, auf dem der Standpunkt steht. */ + floorId?: string; + /** Rückfall-Geschoss, wenn das Projekt kein Geschoss kennt (aktive Ebene). */ + fallbackFloorId: string; + /** Abstand des Ziels vom Standpunkt (m); fehlt = 10 m (orthografisch: die Sichthöhe). */ + distance?: number; + categoryCode?: string; +} + +/** + * Kamera-Element aus der Sicht des Viewports (Modell-Koordinaten): Standpunkt → Geschoss + Augenhöhe, Ziel auf + * der Blickachse im Abstand `distance`. Orthografische Sichten werden zu „parallel" (das Preset-Verhalten der + * Axonometrie ist eine Ausrichtung, kein eigener Zustand der Sicht). + */ +export function cameraFromView(project: Project, view: ViewCamera, o: CameraFromViewOptions): Camera { + const [px, py, pz] = view.position; + const floorId = o.floorId ?? floorForHeight(project, pz, o.fallbackFloorId); + const ortho = view.kind === "orthogonal"; + const dist = o.distance !== undefined && Number.isFinite(o.distance) && o.distance > 0 ? o.distance : ortho ? Math.max(view.orthoHeight, 1) : DEFAULT_AIM_DISTANCE; + const target: Vec2 = { x: px + view.direction[0] * dist, y: py + view.direction[1] * dist }; + const cam: Camera = { + id: o.id, + type: "camera", + name: o.name, + floorId, + categoryCode: o.categoryCode ?? CAMERA_CATEGORY, + position: { x: px, y: py }, + eyeHeight: pz - floorBase(project, floorId), + target, + targetHeight: pz + view.direction[2] * dist, + fovDeg: clampFov(view.fovDeg), + projection: ortho ? "parallel" : "perspective", + }; + if (ortho) cam.orthoHeight = view.orthoHeight; + return cam; +} + +/** Axonometrie-Ausrichtung („Isometrie"): Blick aus Südwest von oben (45° Azimut, 35.264° Neigung) auf dasselbe Ziel. */ +export function isometricAim(project: Project, cam: Camera): Pick { + const eye = cameraEye(project, cam); + const tgt = cameraTarget(cam); + const dist = Math.max(Math.hypot(tgt[0] - eye[0], tgt[1] - eye[1], tgt[2] - eye[2]), 5); + const pitch = Math.atan(1 / Math.SQRT2); + const horiz = dist * Math.cos(pitch); + const from: V3 = [tgt[0] - horiz * Math.SQRT1_2, tgt[1] - horiz * Math.SQRT1_2, tgt[2] + dist * Math.sin(pitch)]; + return { position: { x: from[0], y: from[1] }, eyeHeight: from[2] - floorBase(project, cam.floorId) }; +} diff --git a/src/viewport/walk.test.ts b/src/viewport/walk.test.ts new file mode 100644 index 00000000..a910c602 --- /dev/null +++ b/src/viewport/walk.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from "vitest"; +import { orbitCamera } from "./cameraBridge"; +import type { OrbitState } from "./cameraBridge"; +import { NO_KEYS, lookAround, orbitEye, speedFactor, stepWalk, walkKeyAllowed, walkKeyOf, walkVelocity } from "./walk"; + +const orbit = (over: Partial = {}): OrbitState => ({ + yaw: 0, + pitch: 0.4, + dist: 10, + target: [0, 1.6, 0], + ortho: false, + orthoHalfHeight: 5, + ...over, +}); + +const near = (a: readonly number[], b: readonly number[], eps = 1e-9) => a.forEach((x, i) => expect(x).toBeCloseTo(b[i], -Math.log10(eps))); + +describe("[213] Begehen: Tasten", () => { + it("W/A/S/D, Pfeile und Q/E; alles andere ist keine Bewegung", () => { + expect(walkKeyOf("KeyW")).toBe("forward"); + expect(walkKeyOf("ArrowUp")).toBe("forward"); + expect(walkKeyOf("KeyS")).toBe("back"); + expect(walkKeyOf("ArrowLeft")).toBe("left"); + expect(walkKeyOf("KeyD")).toBe("right"); + expect(walkKeyOf("KeyQ")).toBe("down"); + expect(walkKeyOf("KeyE")).toBe("up"); + expect(walkKeyOf("KeyT")).toBeNull(); + expect(walkKeyOf("Digit3")).toBeNull(); + }); + + it("Shift schneller, Alt langsamer, beide gleichen sich teils aus", () => { + expect(speedFactor(false, false)).toBe(1); + expect(speedFactor(true, false)).toBe(4); + expect(speedFactor(false, true)).toBe(0.25); + expect(speedFactor(true, true)).toBe(1); + }); + + it("Befehls-Modifikator oder Textfeld sperren das Begehen", () => { + expect(walkKeyAllowed({ ctrlKey: false, metaKey: false }, null)).toBe(true); + expect(walkKeyAllowed({ ctrlKey: true, metaKey: false }, null)).toBe(false); + expect(walkKeyAllowed({ ctrlKey: false, metaKey: true }, null)).toBe(false); + const el = (tagName: string, isContentEditable = false) => ({ tagName, isContentEditable }) as unknown as Element; + expect(walkKeyAllowed({ ctrlKey: false, metaKey: false }, el("INPUT"))).toBe(false); + expect(walkKeyAllowed({ ctrlKey: false, metaKey: false }, el("TEXTAREA"))).toBe(false); + expect(walkKeyAllowed({ ctrlKey: false, metaKey: false }, el("DIV", true))).toBe(false); + expect(walkKeyAllowed({ ctrlKey: false, metaKey: false }, el("DIV"))).toBe(true); + expect(walkKeyAllowed({ ctrlKey: false, metaKey: false }, el("CANVAS"))).toBe(true); + }); +}); + +describe("[213] Begehen: Bewegung", () => { + it("vorwärts läuft in der Blickrichtung, waagrecht (Augenhöhe bleibt trotz Neigung)", () => { + // yaw 0: Augpunkt liegt bei +x vom Ziel, Blick geht nach −x. + const v = walkVelocity({ ...NO_KEYS, forward: true }, 0, 3); + near(v, [-3, 0, 0]); + const o = orbit({ pitch: 0.9 }); + const eye0 = orbitEye(o); + const n = stepWalk(o, { ...NO_KEYS, forward: true }, 1 / 60); + const eye1 = orbitEye(n); + expect(eye1[1]).toBeCloseTo(eye0[1], 12); + expect(eye1[0]).toBeLessThan(eye0[0]); + // Abstand, Winkel und Projektion bleiben. + expect(n.dist).toBe(o.dist); + expect(n.pitch).toBe(o.pitch); + expect(n.yaw).toBe(o.yaw); + }); + + it("seitwärts steht senkrecht auf der Blickrichtung; rechts ist rechts", () => { + // Blick nach −x (yaw 0), Weltoben +y: rechts ist −z. + near(walkVelocity({ ...NO_KEYS, right: true }, 0, 2), [0, 0, -2]); + near(walkVelocity({ ...NO_KEYS, left: true }, 0, 2), [0, 0, 2]); + // Gedreht um 90°: Blick nach −z, rechts ist +x. + near(walkVelocity({ ...NO_KEYS, forward: true }, Math.PI / 2, 2), [0, 0, -2]); + near(walkVelocity({ ...NO_KEYS, right: true }, Math.PI / 2, 2), [2, 0, 0]); + }); + + it("diagonal ist nicht schneller; Gegentasten heben sich auf; Q/E senkrecht", () => { + const d = walkVelocity({ ...NO_KEYS, forward: true, right: true }, 0.3, 3); + expect(Math.hypot(d[0], d[2])).toBeCloseTo(3, 12); + near(walkVelocity({ ...NO_KEYS, forward: true, back: true }, 0.3, 3), [0, 0, 0]); + near(walkVelocity({ ...NO_KEYS, up: true }, 0.3, 3), [0, 3, 0]); + near(walkVelocity({ ...NO_KEYS, down: true }, 0.3, 3), [0, -3, 0]); + }); + + it("Weg = Tempo × Zeit; langer Zeitschritt wird gekappt; ohne Taste oder dt bleibt der Zustand", () => { + const o = orbit(); + const n = stepWalk(o, { ...NO_KEYS, forward: true }, 0.05, 4); + expect(n.target[0]).toBeCloseTo(-0.2, 12); + const slow = stepWalk(o, { ...NO_KEYS, forward: true }, 5, 4); + expect(slow.target[0]).toBeCloseTo(-0.4, 12); // höchstens 0.1 s + expect(stepWalk(o, NO_KEYS, 1)).toBe(o); + expect(stepWalk(o, { ...NO_KEYS, forward: true }, 0)).toBe(o); + expect(stepWalk(o, { ...NO_KEYS, forward: true }, NaN)).toBe(o); + expect(stepWalk(o, { ...NO_KEYS, forward: true }, 1, 0)).toBe(o); + }); + + it("die Kamera zeigt nach dem Gehen weiter in dieselbe Richtung", () => { + const o = orbit({ yaw: 1.2, pitch: 0.3 }); + const c0 = orbitCamera(o); + const c1 = orbitCamera(stepWalk(o, { ...NO_KEYS, forward: true, right: true }, 0.08)); + const dir = (c: { eye: number[]; target: number[] }) => { + const d = [c.target[0] - c.eye[0], c.target[1] - c.eye[1], c.target[2] - c.eye[2]]; + const l = Math.hypot(d[0], d[1], d[2]); + return d.map((x) => x / l); + }; + near(dir(c1), dir(c0), 1e-9); + }); +}); + +describe("[213] Begehen: Umschauen", () => { + it("der Augpunkt bleibt stehen, die Blickrichtung dreht", () => { + const o = orbit({ yaw: 0.7, pitch: 0.2 }); + const eye = orbitEye(o); + const n = lookAround(o, 120, -40); + near(orbitEye(n), eye, 1e-9); + expect(n.yaw).toBeGreaterThan(o.yaw); // Maus nach rechts → Blick nach rechts + expect(n.pitch).toBeLessThan(o.pitch); // Maus nach oben → Blick hebt sich + expect(n.dist).toBe(o.dist); + }); + + it("Neigung ist geklemmt; ohne Bewegung bleibt der Zustand", () => { + const o = orbit(); + const steep = lookAround(o, 0, 1e6); + expect(steep.pitch).toBeLessThan(Math.PI / 2); + expect(steep.pitch).toBeGreaterThan(1.5); + expect(lookAround(o, 0, 0)).toBe(o); + expect(lookAround(o, NaN, 3)).toBe(o); + }); +}); diff --git a/src/viewport/walk.ts b/src/viewport/walk.ts new file mode 100644 index 00000000..77168a2e --- /dev/null +++ b/src/viewport/walk.ts @@ -0,0 +1,117 @@ +// [213] Begehen im 3D (WASD): reine Bewegungsrechnung auf dem Orbit-Zustand des Viewports, ohne React und Engine. +// +// Der Orbit-Zustand (`OrbitState`, world Y-oben) beschreibt die Kamera als Blickziel + Abstand + Winkel. Den Augpunkt +// verschieben heisst, das Blickziel um denselben Vektor verschieben — Abstand und Winkel bleiben. Vorwärts und +// seitwärts laufen in der Horizontalen (Augenhöhe bleibt, auch bei geneigtem Blick); Q/E bewegen senkrecht. +// Umschauen dreht die Blickrichtung um den Augpunkt (nicht um das Ziel wie der Orbit). + +import { PITCH_LIMIT } from "./cameraBridge"; +import type { OrbitState, V3 } from "./cameraBridge"; + +/** Gedrückte Bewegungstasten. */ +export interface WalkKeys { + forward: boolean; + back: boolean; + left: boolean; + right: boolean; + up: boolean; + down: boolean; +} + +export const NO_KEYS: WalkKeys = { forward: false, back: false, left: false, right: false, up: false, down: false }; + +/** Grundgeschwindigkeit (m/s), Shift ×4, Alt ×0.25. */ +export const WALK_SPEED = 3; +export const FAST_FACTOR = 4; +export const SLOW_FACTOR = 0.25; +/** Längster Zeitschritt (s): nach einem Hänger (Tab im Hintergrund) kein Sprung durchs Haus. */ +export const MAX_DT = 0.1; +/** Mausempfindlichkeit beim Umschauen (Radiant je Pixel). */ +export const LOOK_RAD_PER_PX = 0.0035; + +/** Taste (`KeyboardEvent.code`) → Bewegung; `null` für alle anderen. W/S/A/D und Pfeile vor/zurück/seitlich, Q/E runter/hoch. */ +export function walkKeyOf(code: string): keyof WalkKeys | null { + switch (code) { + case "KeyW": + case "ArrowUp": + return "forward"; + case "KeyS": + case "ArrowDown": + return "back"; + case "KeyA": + case "ArrowLeft": + return "left"; + case "KeyD": + case "ArrowRight": + return "right"; + case "KeyQ": + return "down"; + case "KeyE": + return "up"; + default: + return null; + } +} + +/** Ist irgendeine Bewegungstaste gedrückt? */ +export const anyKey = (k: WalkKeys): boolean => k.forward || k.back || k.left || k.right || k.up || k.down; + +/** Tempo-Faktor aus Shift (schneller) und Alt (langsamer); beide = Grundtempo. */ +export function speedFactor(shift: boolean, alt: boolean): number { + return (shift ? FAST_FACTOR : 1) * (alt ? SLOW_FACTOR : 1); +} + +/** + * Geschwindigkeit (world, m/s) aus den gedrückten Tasten. Vorwärts = horizontale Blickrichtung (die Höhe bleibt), + * seitwärts = rechts, hoch/runter = world Y. Gegensätzliche Tasten heben sich auf; diagonale Bewegung ist nicht + * schneller als geradeaus (die waagrechte Richtung wird normiert). + */ +export function walkVelocity(keys: WalkKeys, yaw: number, speed: number): V3 { + const fwd = (keys.forward ? 1 : 0) - (keys.back ? 1 : 0); + const side = (keys.right ? 1 : 0) - (keys.left ? 1 : 0); + const vert = (keys.up ? 1 : 0) - (keys.down ? 1 : 0); + // Horizontale Blickrichtung f = (−cos yaw, 0, −sin yaw), rechts s = (sin yaw, 0, −cos yaw) (wie im Pan des Viewports). + const hx = -Math.cos(yaw) * fwd + Math.sin(yaw) * side; + const hz = -Math.sin(yaw) * fwd - Math.cos(yaw) * side; + const hl = Math.hypot(hx, hz); + const k = hl > 1e-12 ? speed / hl : 0; + return [hx * k, vert * speed, hz * k]; +} + +/** Orbit-Zustand nach `dt` Sekunden Gehen; derselbe Zustand ohne Taste oder bei unbrauchbarem `dt`. */ +export function stepWalk(o: OrbitState, keys: WalkKeys, dt: number, speed: number = WALK_SPEED): OrbitState { + if (!anyKey(keys) || !(dt > 0) || !Number.isFinite(dt) || !(speed > 0)) return o; + const v = walkVelocity(keys, o.yaw, speed); + const s = Math.min(dt, MAX_DT); + return { ...o, target: [o.target[0] + v[0] * s, o.target[1] + v[1] * s, o.target[2] + v[2] * s] }; +} + +/** Augpunkt (world) des Orbit-Zustands. */ +export function orbitEye(o: OrbitState): V3 { + const pitch = Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, o.pitch)); + const r = o.dist * Math.cos(pitch); + return [o.target[0] + r * Math.cos(o.yaw), o.target[1] + o.dist * Math.sin(pitch), o.target[2] + r * Math.sin(o.yaw)]; +} + +/** + * Umschauen um den Augpunkt: Maus nach rechts (`dx` > 0) dreht den Blick nach rechts, Maus nach unten (`dy` > 0) + * senkt ihn. Der Augpunkt bleibt exakt stehen (das Blickziel wandert auf der neuen Blickachse mit); der Neigungswinkel + * ist wie beim Orbit geklemmt. + */ +export function lookAround(o: OrbitState, dx: number, dy: number, radPerPx: number = LOOK_RAD_PER_PX): OrbitState { + if (!Number.isFinite(dx) || !Number.isFinite(dy) || (dx === 0 && dy === 0)) return o; + const eye = orbitEye(o); + const yaw = o.yaw + dx * radPerPx; + const pitch = Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, o.pitch + dy * radPerPx)); + const r = o.dist * Math.cos(pitch); + return { ...o, yaw, pitch, target: [eye[0] - r * Math.cos(yaw), eye[1] - o.dist * Math.sin(pitch), eye[2] - r * Math.sin(yaw)] }; +} + +/** Darf die Taste das Begehen starten (kein Textfeld im Fokus, kein Befehls-Modifikator)? */ +export function walkKeyAllowed(e: { ctrlKey: boolean; metaKey: boolean }, active: Element | null): boolean { + if (e.ctrlKey || e.metaKey) return false; + if (!active) return true; + const tag = active.tagName; + if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return false; + return !(active as HTMLElement).isContentEditable; +} diff --git a/src/views/plan/PlanView.tsx b/src/views/plan/PlanView.tsx index 8700cab9..ef4b0763 100644 --- a/src/views/plan/PlanView.tsx +++ b/src/views/plan/PlanView.tsx @@ -153,6 +153,7 @@ export const PlanView = forwardRef( drawings: selectedDrawingIds, site: selectedSite, trees: selectedTreeIds, + cameras: selectedCameraIds, } = selection; const selectedDrawingId = single(selection, "drawings"); // Linke Maustaste liegt beim Werkzeug/der Transformation, wenn App das meldet @@ -299,6 +300,7 @@ export const PlanView = forwardRef( pickSectionLine, pickSiteAt, pickTree, + pickCamera, pickContextObject, pickExtrudedSolid, pickColumn, @@ -401,6 +403,7 @@ export const PlanView = forwardRef( pickColumn, pickExtrudedSolid, pickTree, + pickCamera, pickStair, pickRoof, pickSiteAt, @@ -437,6 +440,7 @@ export const PlanView = forwardRef( pickRoom, pickRoof, pickTree, + pickCamera, pickSiteAt, pickContextObject, pickSectionLine, @@ -492,6 +496,7 @@ export const PlanView = forwardRef( pickRoom, onOpenSectionLevel, pickSectionLine, + pickCamera, onContextMenu, view, viewToModel, @@ -533,6 +538,7 @@ export const PlanView = forwardRef( selectedContextObjectIds, selectedSite, selectedTreeIds, + selectedCameraIds, selectedSectionLineIds, selectedExtrudedSolidIds, selectedColumnIds, diff --git a/src/views/plan/pickCycle.ts b/src/views/plan/pickCycle.ts index 4ffffb87..7f5cdd7b 100644 --- a/src/views/plan/pickCycle.ts +++ b/src/views/plan/pickCycle.ts @@ -35,6 +35,7 @@ const KIND_FIELD: Record = { drawing: "drawings", solid: "solids", tree: "trees", + camera: "cameras", ceiling: "ceilings", stair: "stairs", room: "rooms", diff --git a/src/views/plan/planView/constants.ts b/src/views/plan/planView/constants.ts index da898221..cb457db2 100644 --- a/src/views/plan/planView/constants.ts +++ b/src/views/plan/planView/constants.ts @@ -71,7 +71,7 @@ export const GRIP_HIT_PX = 9; export const LINE_PICK_PX = 6; export const PICK_ORDER: readonly PickKind[] = [ - "section", "opening", "wall", "column", "drawing", "solid", "tree", + "section", "opening", "wall", "column", "drawing", "solid", "tree", "camera", "ceiling", "stair", "room", "roof", "site", "context", ]; @@ -90,11 +90,14 @@ export const EMPTY_PICK: PickIds = { contextObjectId: null, siteId: null, treeId: null, + cameraId: 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`). */ export const TREE_PICK = "@tree:"; +/** [213] Präfix der Kamera-Pick-Id im Feld `contextObjectId` (Kern `camera::CAMERA_PICK_PREFIX`). */ +export const CAMERA_PICK = "@camera:"; export const IS_MAC = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform); export const cycleModifier = (e: { metaKey: boolean; ctrlKey: boolean }): boolean => (IS_MAC ? e.metaKey : e.ctrlKey); diff --git a/src/views/plan/planView/types.ts b/src/views/plan/planView/types.ts index 24b2310f..fa60687e 100644 --- a/src/views/plan/planView/types.ts +++ b/src/views/plan/planView/types.ts @@ -156,6 +156,8 @@ export interface PlanSelection { * Öffnung/Wand/Stütze/2D-Element/Körper getroffen wurde; Vorrang vor Decke, Raum, Dach und Gelände. */ treeId?: string | null; + /** [213] Getroffene Kamera (Sichtkegel/Gehäuse, Pick-Id `@camera:` im Feld `contextObjectId`); Vorrang vor allem ausser Öffnung/Wand/Stütze/2D-Element/Körper/Baum. */ + cameraId?: 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 @@ -185,6 +187,8 @@ export interface MarqueeSelection { stairIds: string[]; /** [149] Getroffene Bäume (Kronenfläche, gleiche Konvention). */ treeIds?: string[]; + /** [213] Getroffene Kameras (Pick-Flächen von Gehäuse und Sichtgrenzen, gleiche Konvention). */ + cameraIds?: string[]; /** * Zieh-Richtung: `false` = links→rechts (positiv Δx) → nur VOLLSTÄNDIG * eingeschlossene Wände; `true` = rechts→links (negativ Δx) → auch berührte/ diff --git a/src/views/plan/planView/usePlanHighlights.ts b/src/views/plan/planView/usePlanHighlights.ts index deea6c14..6309329c 100644 --- a/src/views/plan/planView/usePlanHighlights.ts +++ b/src/views/plan/planView/usePlanHighlights.ts @@ -6,7 +6,7 @@ import type { Primitive, OwnerField, PickKind } from "../../../core"; import { useMemo, useEffect } from "react"; import { planPrimAt } from "../../../core"; import { textFrameCorners } from "../../../text/textFrame"; -import { TREE_PICK } from "./constants"; +import { CAMERA_PICK, TREE_PICK } from "./constants"; import { PlanPickIndex } from "../../../core"; import type { Plan } from "../../../core"; import type { UnderlayGroup } from "../../../core"; @@ -36,6 +36,7 @@ export interface UsePlanHighlightsArgs { selectedContextObjectIds: string[]; selectedSite: string[]; selectedTreeIds: string[]; + selectedCameraIds?: string[]; selectedSectionLineIds: string[]; selectedExtrudedSolidIds: string[]; selectedColumnIds: string[]; @@ -64,6 +65,7 @@ export function usePlanHighlights(inp: UsePlanHighlightsArgs) { selectedContextObjectIds, selectedSite, selectedTreeIds, + selectedCameraIds, selectedSectionLineIds, selectedExtrudedSolidIds, selectedColumnIds, @@ -238,10 +240,11 @@ export function usePlanHighlights(inp: UsePlanHighlightsArgs) { ...(selectedContextObjectIds ?? []), ...(selectedSite ?? []).map((s) => "@" + s), ...(selectedTreeIds ?? []).map((s) => TREE_PICK + s), + ...(selectedCameraIds ?? []).map((s) => CAMERA_PICK + s), ]; if (!ids.length) return []; return primsOwnedBy("contextObjectId", ids, (p): p is Extract => p.kind === "polygon"); - }, [plan, selectedContextObjectIds, selectedSite, selectedTreeIds]); + }, [plan, selectedContextObjectIds, selectedSite, selectedTreeIds, selectedCameraIds]); // Hervorhebung der selektierten Schnitt-/Ansichtslinie: das (unsichtbare) // Pick-Band (Polygon mit sectionLineId) mit Akzentkontur überzeichnen. @@ -280,7 +283,8 @@ export function usePlanHighlights(inp: UsePlanHighlightsArgs) { if (!hoverPick) return []; if (hoverPick.kind === "site") return primsOwnedBy("contextObjectId", ["@" + hoverPick.id], (_p): _p is Primitive => true); if (hoverPick.kind === "tree") return primsOwnedBy("contextObjectId", [TREE_PICK + hoverPick.id], (_p): _p is Primitive => true); - const field: Record, OwnerField> = { + if (hoverPick.kind === "camera") return primsOwnedBy("contextObjectId", [CAMERA_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/planView/usePlanPickCycle.ts b/src/views/plan/planView/usePlanPickCycle.ts index 745c0bdd..db732b05 100644 --- a/src/views/plan/planView/usePlanPickCycle.ts +++ b/src/views/plan/planView/usePlanPickCycle.ts @@ -10,7 +10,7 @@ import type { Vec2 } from "../../../model/types"; import type { PlainCycle } from "../pickCycle"; import { selectionHas, plainCycleNext, cycleHint } from "../pickCycle"; import { t } from "../../../i18n"; -import { LINE_PICK_PX, TREE_PICK, PICK_ORDER, EMPTY_PICK, MARQUEE_THRESHOLD_PX, cycleModifier } from "./constants"; +import { CAMERA_PICK, LINE_PICK_PX, TREE_PICK, PICK_ORDER, EMPTY_PICK, MARQUEE_THRESHOLD_PX, cycleModifier } from "./constants"; import { planPrimAt, drawingsWithinDistance } from "../../../core"; import type { ViewBox__plan_planView_geometry as ViewBox } from "../../../core"; import { PlanPickIndex } from "../../../core"; @@ -47,6 +47,7 @@ export interface UsePlanPickCycleArgs { pickRoom: (clientX: number, clientY: number) => string | null; pickRoof: (clientX: number, clientY: number) => string | null; pickTree: (clientX: number, clientY: number) => string | null; + pickCamera: (clientX: number, clientY: number) => string | null; pickSiteAt: (clientX: number, clientY: number) => string | null; pickContextObject: (clientX: number, clientY: number) => string | null; pickSectionLine: (clientX: number, clientY: number) => string | null; @@ -99,6 +100,7 @@ export function usePlanPickCycle(inp: UsePlanPickCycleArgs) { pickRoom, pickRoof, pickTree, + pickCamera, pickSiteAt, pickContextObject, pickSectionLine, @@ -256,6 +258,7 @@ export function usePlanPickCycle(inp: UsePlanPickCycleArgs) { add("drawing", dp.drawingId, dp.hitIndex); add("solid", dp.extrudedSolidId, dp.hitIndex); add("tree", dp.treeId, dp.hitIndex); + add("camera", dp.cameraId, dp.hitIndex); add("ceiling", dp.ceilingId, dp.hitIndex); add("stair", dp.stairId, dp.hitIndex); add("room", dp.roomId, dp.hitIndex); @@ -283,6 +286,7 @@ export function usePlanPickCycle(inp: UsePlanPickCycleArgs) { addRest("room", p.roomId, idx); addRest("roof", p.roofId, idx); if (p.contextObjectId?.startsWith(TREE_PICK)) addRest("tree", p.contextObjectId.slice(TREE_PICK.length), idx); + else if (p.contextObjectId?.startsWith(CAMERA_PICK)) addRest("camera", p.contextObjectId.slice(CAMERA_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); @@ -295,6 +299,7 @@ export function usePlanPickCycle(inp: UsePlanPickCycleArgs) { addRest("room", pickRoom(clientX, clientY), null); addRest("roof", pickRoof(clientX, clientY), null); addRest("tree", pickTree(clientX, clientY), null); + addRest("camera", pickCamera(clientX, clientY), null); addRest("site", pickSiteAt(clientX, clientY), null); addRest("context", pickContextObject(clientX, clientY), null); addRest("section", pickSectionLine(clientX, clientY), null); @@ -333,6 +338,7 @@ export function usePlanPickCycle(inp: UsePlanPickCycleArgs) { contextObjectId: c.kind === "context" ? c.id : null, siteId: c.kind === "site" ? c.id : null, treeId: c.kind === "tree" ? c.id : null, + cameraId: c.kind === "camera" ? c.id : null, }); }; @@ -532,6 +538,15 @@ export function usePlanPickCycle(inp: UsePlanPickCycleArgs) { .marquee("contextObjectId", rect, crossing) .filter((id) => id.startsWith(TREE_PICK)) .map((id) => id.slice(TREE_PICK.length)), + // [213] Kameras: Pick-Flächen (`contextObjectId = "@camera:"`). + cameraIds: [ + ...new Set( + getPick() + .marquee("contextObjectId", rect, crossing) + .filter((id) => id.startsWith(CAMERA_PICK)) + .map((id) => id.slice(CAMERA_PICK.length)), + ), + ], crossing, }); } diff --git a/src/views/plan/planView/usePlanPicking.ts b/src/views/plan/planView/usePlanPicking.ts index 89bf9751..14cdaf09 100644 --- a/src/views/plan/planView/usePlanPicking.ts +++ b/src/views/plan/planView/usePlanPicking.ts @@ -4,7 +4,7 @@ import type { GroupableHit, BodyTarget } from "./types"; import { planPrimAt, nearestInDrawings, marqueeHitUnderlay } from "../../../core"; -import { LINE_PICK_PX, TREE_PICK } from "./constants"; +import { CAMERA_PICK, LINE_PICK_PX, TREE_PICK } from "./constants"; import type { Primitive, ModelRect } from "../../../core"; import type { Vec2 } from "../../../model/types"; import { useState, useRef, useEffect } from "react"; @@ -257,7 +257,7 @@ export function usePlanPicking(inp: UsePlanPickingArgs) { // [137] Getroffene Lage-Darstellung: Quelle `"sunStudy"`/`"siteRules"` (Baurechtslinie vor Schatten) oder null. const pickSiteAt = (clientX: number, clientY: number): string | null => { - const all = contextIdsAt(clientX, clientY).filter((id) => !id.startsWith(TREE_PICK)); + const all = contextIdsAt(clientX, clientY).filter((id) => !id.startsWith(TREE_PICK) && !id.startsWith(CAMERA_PICK)); // [193] Liegt ein Kontext-Element (Baugrube, Netz) über der Schattenfläche, gehört der Klick ihm — sonst wäre // die Baugrube unter dem Schatten des Hauses nicht anzuwählen. Die Baurechtslinie (unsichtbares Band) gewinnt immer. if (all.includes("@siteRules")) return "siteRules"; @@ -271,6 +271,12 @@ export function usePlanPicking(inp: UsePlanPickingArgs) { return id ? id.slice(TREE_PICK.length) : null; }; + // [213] Getroffene Kamera (oberste Pickfläche aus Gehäuse und Sichtkegel) oder null. + const pickCamera = (clientX: number, clientY: number): string | null => { + const id = contextIdsAt(clientX, clientY).find((x) => x.startsWith(CAMERA_PICK)); + return id ? id.slice(CAMERA_PICK.length) : null; + }; + const pickContextObject = (clientX: number, clientY: number): string | null => contextIdsAt(clientX, clientY).find((id) => !id.startsWith("@")) ?? null; @@ -407,6 +413,7 @@ export function usePlanPicking(inp: UsePlanPickingArgs) { pickSectionLine, pickSiteAt, pickTree, + pickCamera, pickContextObject, pickExtrudedSolid, pickColumn, diff --git a/src/views/plan/planView/usePlanPointer.ts b/src/views/plan/planView/usePlanPointer.ts index 77aeff12..7fc46a65 100644 --- a/src/views/plan/planView/usePlanPointer.ts +++ b/src/views/plan/planView/usePlanPointer.ts @@ -76,6 +76,7 @@ export interface UsePlanPointerArgs { pickColumn: (clientX: number, clientY: number) => string | null; pickExtrudedSolid: (clientX: number, clientY: number) => string | null; pickTree: (clientX: number, clientY: number) => string | null; + pickCamera: (clientX: number, clientY: number) => string | null; pickStair: (clientX: number, clientY: number) => string | null; pickRoof: (clientX: number, clientY: number) => string | null; pickSiteAt: (clientX: number, clientY: number) => string | null; @@ -141,6 +142,7 @@ export function usePlanPointer(inp: UsePlanPointerArgs) { pickColumn, pickExtrudedSolid, pickTree, + pickCamera, pickStair, pickRoof, pickSiteAt, @@ -616,27 +618,30 @@ export function usePlanPointer(inp: UsePlanPointerArgs) { // [149] Baum (Kronenfläche) vor Decke, Raum, Dach und Gelände. const treeId = openingId || wallId || columnId || drawingId || extrudedSolidId ? null : pickTree(clientX, clientY); + // [213] Kamera (schmale Pickflächen von Gehäuse, Sichtgrenzen und Ziel) wie der Baum vor Decke, Raum, Dach. + const cameraId = + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId ? null : pickCamera(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 || treeId ? null : hitCeilingId; + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || cameraId ? null : hitCeilingId; // Treppe nur, wenn nichts anderes getroffen wurde (Tritte liegen frei). const stairId = - openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || cameraId || 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 || treeId || ceilingId || stairId + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || cameraId || 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 || treeId || ceilingId || stairId || roomId + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || cameraId || ceilingId || stairId || roomId ? null : pickRoof(clientX, clientY); // Kontext-Objekt (Gebäude/Terrain) als ALLERLETZTE Priorität — seine @@ -644,11 +649,11 @@ export function usePlanPointer(inp: UsePlanPointerArgs) { // nichts anderes getroffen wurde. // [137] Schatten/Baurechtslinien (Lage-Darstellung) über dem Gelände, unter allen Bauteilen. const siteId = - openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId || stairId || roomId || roofId + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || cameraId || ceilingId || stairId || roomId || roofId ? null : pickSiteAt(clientX, clientY); const contextObjectId = - openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId || stairId || roomId || roofId || siteId + openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || cameraId || ceilingId || stairId || roomId || roofId || siteId ? null : pickContextObject(clientX, clientY); return { @@ -666,6 +671,7 @@ export function usePlanPointer(inp: UsePlanPointerArgs) { contextObjectId, siteId, treeId, + cameraId, }; }; diff --git a/src/views/plan/planView/usePlanZoomInput.ts b/src/views/plan/planView/usePlanZoomInput.ts index 3407934e..3b11bda3 100644 --- a/src/views/plan/planView/usePlanZoomInput.ts +++ b/src/views/plan/planView/usePlanZoomInput.ts @@ -1,6 +1,7 @@ // Rad-Zoom, Doppelklick und Kontextmenü der Plan-Ansicht ([165] aus `PlanView.tsx`). Im GPU-Pfad zoomt // das Rad imperativ und schreibt den Ausschnitt nach kurzer Ruhe fest. Aufgerufen einmal von `PlanView`. +import { openCamera } from "../../../state/cameraActions"; import type { ViewBox__plan_planView_geometry as ViewBox } from "../../../core"; import type { Vec2 } from "../../../model/types"; import { clamp } from "../../../core"; @@ -32,6 +33,7 @@ export interface UsePlanZoomInputArgs { pickRoom: (clientX: number, clientY: number) => string | null; onOpenSectionLevel: ((levelId: string) => void) | undefined; pickSectionLine: (clientX: number, clientY: number) => string | null; + pickCamera: (clientX: number, clientY: number) => string | null; onContextMenu: ((info: { clientX: number; clientY: number; model: Vec2; }) => void) | undefined; view: ViewBox; viewToModel: (vbX: number, vbY: number) => Vec2; @@ -60,6 +62,7 @@ export function usePlanZoomInput(inp: UsePlanZoomInputArgs) { pickRoom, onOpenSectionLevel, pickSectionLine, + pickCamera, onContextMenu, view, viewToModel, @@ -163,6 +166,12 @@ export function usePlanZoomInput(inp: UsePlanZoomInputArgs) { return; } } + // [213] Doppelklick auf das Symbol einer Kamera → die Kamera im 3D öffnen (Reiter wechseln, Ansicht exakt setzen). + const cid = pickCamera(e.clientX, e.clientY); + if (cid) { + void openCamera(cid); + return; + } // Doppelklick auf eine Schnittlinie → in deren 2D-Schnittansicht springen. if (onOpenSectionLevel) { const sid = pickSectionLine(e.clientX, e.clientY);