Merge [BCF][27] Kamera-Bruecke im 3D-Viewport: BCF-Viewpoints setzen und aufnehmen (Kamera, Schnitt, Snapshot), Einpassen mit Punktwolken
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
14 files changed
+1388
-109
No files matched your search
@@ -336,10 +336,12 @@ Format · [90] Versionsvergleich · [91] Assistent · [92] Speckle.
|
||||
geprüft: Bild im Browser (Chromium präsentiert hier keine WebGPU-Frames, auch nicht headful unter
|
||||
Xvfb), Tauri-App/macOS-Metal, echte LAS/E57-Dateien, 2–5 Mio. Punkte (Zeit/Speicher), Achsrichtung
|
||||
gegen ein echtes swissALTI3D-Gelände desselben Bezugs.
|
||||
- **Einpassen (28.10.):** `set_view_preset` und der Orbit-Seed (`view_fit`) beziehen sichtbare Punktwolken in
|
||||
die Bounding-Box ein (`math::merge_bounds`/`fit_target_dist`, Rust-Test); die erste sichtbare Wolke passt
|
||||
die Kamera automatisch ein. Nicht im Browser mit Bild geprüft (leerer WebGPU-Frame im Container).
|
||||
- Offen: **beim Neuladen sind die Wolken weg** (kein Autosave) → Stufe 2 mit Modellfeld
|
||||
`Project.pointClouds` + Asset im IndexedDB/neben der Datei (Vorschlag unter [B9]); Speicher doppelt
|
||||
(JS-Store + Rust-CPU-Kopie für Farbwechsel + GPU); Kamera-Einpassen (`set_view_preset`) kennt die
|
||||
Wolke nicht; Grundriss/Schnitt (Punkte in Scheibe), Fang an Punkten, Clip-Box; sRGB-Ziel in
|
||||
(JS-Store + Rust-CPU-Kopie für Farbwechsel + GPU); Grundriss/Schnitt (Punkte in Scheibe), Fang an Punkten, Clip-Box; sRGB-Ziel in
|
||||
`render_png` hellt Punktfarben (wie alle Vertexfarben) auf.
|
||||
|
||||
## Übernahme aus BIMCraft [B]
|
||||
@@ -525,10 +527,26 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module
|
||||
alle 71 buildingSMART-Beispieldateien (Test Cases v2.1/v3.0, lokal; CC BY-ND, deshalb nicht im Repo,
|
||||
Test `buildingsmart_beispiele` über `BCF_TESTCASES`), vitest Fassade und GlobalId-Zuordnung gegen den
|
||||
IFC-Export des Demo-Hauses. Nicht geprüft: Austausch mit echter Solibri/BIMcollab-Software, Tauri-App.
|
||||
Offen: Kamera des Viewpoints setzen und für neue Themen aus dem 3D-Viewport lesen (`Wasm3DViewport` hält
|
||||
die Orbit-Kamera intern, ohne Setter/Getter; Achsen Z-oben wie IFC, Viewport vermutlich Y-oben);
|
||||
Snapshot aus dem Viewport; `extensions.xml` (3.0), Farbgruppen/Linien, BimSnippet, Dokument-Referenzen
|
||||
und verwandte Themen gehen beim Speichern verloren; Panel in den Standard-Dock aufnehmen. · M
|
||||
**Kamera (28.10.):** `viewport/cameraBridge.ts` (`getCamera`/`setCamera({animate})`/`captureSnapshot`/`setSection`/
|
||||
`fitView`; der Viewport meldet sich an, ohne Viewport null/false) in MODELL-Koordinaten (z oben); Achsen
|
||||
Modell (x, y, Höhe) → world (x, Höhe, y) (Tausch, belegt gegen `projectToModel3d`; Gelände/Punktwolken
|
||||
negieren y, s. [27]). `panels/bcfView.ts`: BCF-Weltkoordinaten = Modell + LV95-Versatz `projectGeoOrigin`
|
||||
(genau wie `exportIfcSpf`/`projectToWorldCoords`, Höhe unverändert). Klick auf Thema/Viewpoint-Vorschau
|
||||
setzt Kamera (perspektivisch + orthogonal, Fahrt 350 ms) und eine senkrechte Schnittebene (live,
|
||||
Knopf zum Aufheben), Auswahl wie zuvor; „Thema aus Auswahl", „Ansicht aufnehmen" und Kommentar
|
||||
(Häkchen „Aktuelle 3D-Ansicht anhängen") legen einen Viewpoint mit Kamera + PNG-Schnappschuss an.
|
||||
Annahmen: FieldOfView vertikal, ViewToWorldScale = sichtbare Breite, ClippingPlane.Direction zeigt auf
|
||||
die weggeschnittene Seite (wie `set_section_plane`). render3d additiv: `camera_state`, `view_fit`
|
||||
(`math::fit_target_dist`/`merge_bounds`). Geprüft: vitest Achsabbildung + Rundreisen (inkl. echter
|
||||
.bcfzip 2.1/3.0), Chromium-Build (`scripts/probe-bcf-camera.mjs`): Kamera setzen/lesen/aufnehmen
|
||||
per Debug-Handle `window.__dossierCamera`. NICHT geprüft: Schnappschuss mit echtem Bild (im Container
|
||||
ist der WebGPU-Frame leer → `captureSnapshot` liefert null, Viewpoint trägt dann nur die Kamera),
|
||||
nativer macOS-Pfad (Metal-Fenster `native.rs` hat eigene Orbit-Kamera, NICHT angebunden: dort nur Anzeige
|
||||
und Auswahl), Austausch mit echter Solibri/BIMcollab-Software (Achsen-/FOV-Annahmen oben).
|
||||
Offen: Kamera im nativen Metal-Fenster; Schnittebene beim Anlegen eines Themas aus dem Live-Schnitt
|
||||
übernehmen; Roll der Kamera (Orbit kennt keinen); schräge Schnittebenen nur angezeigt;
|
||||
`extensions.xml` (3.0), Farbgruppen/Linien, BimSnippet, Dokument-Referenzen und verwandte Themen gehen
|
||||
beim Speichern verloren; Panel in den Standard-Dock aufnehmen. · M
|
||||
- ○ **[B6] Wand unter Dach als Prismen zwischen Ebenen** (für [G2]). `walls.rs:413–472, 592–654`. · M
|
||||
- ○ **[B7] Dach-Verschneidung und Gauben in 2.5D** (für [G5]). · M · nach [B2]/[B6].
|
||||
- ○ **[B8] Bogenwände, schneller Weg** (für [T2]). · S/M–L
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
// Browser-Prüfung der BCF-Kamera ([BCF]): Panel öffnen, .bcfzip laden, Themen anklicken und den
|
||||
// Kamerazustand über das Debug-Handle `window.__dossierCamera` (s. `viewport/cameraBridge.ts`)
|
||||
// lesen. WebGPU-Frames sind im Container oft leer — deshalb zählt der Kamerazustand, nicht das Bild.
|
||||
//
|
||||
// Aufruf: PROBE_URL=http://localhost:5191/ BCF_FILE=pfad/test.bcfzip [PROJECT_FILE=pfad/demo.obp] node scripts/probe-bcf-camera.mjs
|
||||
// Die Datei hat zwei Themen: "Perspektive" (Position 12/10/8, Blick -12/-10/-7, Z oben, Schnittebene
|
||||
// y=2) und "Ortho Grundriss" (Position 2.5/2/30, Blick -Z, ViewToWorldScale 16).
|
||||
import { chromium } from "playwright";
|
||||
|
||||
const URL = process.env.PROBE_URL || "http://localhost:5191/";
|
||||
const FILE = process.env.BCF_FILE;
|
||||
if (!FILE) throw new Error("BCF_FILE fehlt");
|
||||
const OUT = process.env.PROBE_OUT || ".";
|
||||
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
executablePath: process.env.CHROMIUM_BIN || undefined,
|
||||
args: ["--no-sandbox", "--enable-unsafe-webgpu", "--enable-features=Vulkan", "--use-angle=swiftshader"],
|
||||
});
|
||||
const page = await browser.newPage({ viewport: { width: 1500, height: 900 } });
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
page.on("console", (m) => {
|
||||
if (m.type() === "error") errors.push(m.text());
|
||||
});
|
||||
await page.goto(URL, { waitUntil: "load" });
|
||||
// Startbildschirm: neues Projekt, danach (falls angegeben) das Demo-Projekt über das versteckte
|
||||
// .obp-Input der App laden (der Dateidialog des Startbildschirms ist nur in der Tauri-App aktiv).
|
||||
await page.getByText("Neues Projekt", { exact: true }).first().click();
|
||||
if (process.env.PROJECT_FILE) {
|
||||
await page.setInputFiles('input[accept="application/json,.json,.obp"]', process.env.PROJECT_FILE);
|
||||
await page.waitForTimeout(800);
|
||||
}
|
||||
await page.waitForSelector("canvas", { timeout: 30000 });
|
||||
await page.waitForTimeout(2500);
|
||||
|
||||
// 3D-Ansicht (Isometrie-Preset) einschalten; der Viewport meldet sich erst bei bereitem Renderer an.
|
||||
await page.locator('button[title^="Isometrie —"]').first().click().catch(() => {});
|
||||
await page.waitForFunction(() => window.__dossierCamera?.viewportAvailable() === true, null, { timeout: 15000 }).catch(() => {});
|
||||
console.log("INFO WebGPU im Browser:", await page.evaluate(async () => (navigator.gpu ? !!(await navigator.gpu.requestAdapter()) : false)));
|
||||
|
||||
const results = [];
|
||||
const check = (name, ok, detail = "") => {
|
||||
results.push({ name, ok });
|
||||
console.log(`${ok ? "OK " : "FAIL"} ${name}${detail ? " — " + detail : ""}`);
|
||||
};
|
||||
const cam = () => page.evaluate(() => window.__dossierCamera?.getCamera() ?? null);
|
||||
const near = (a, b, tol = 1e-3) => a.every((v, i) => Math.abs(v - b[i]) <= tol);
|
||||
const norm = (v) => {
|
||||
const l = Math.hypot(...v);
|
||||
return v.map((x) => x / l);
|
||||
};
|
||||
|
||||
check("Viewport meldet sich an", await page.evaluate(() => window.__dossierCamera?.viewportAvailable() === true));
|
||||
|
||||
// Panel öffnen: Menü Fenster > BCF-Themen
|
||||
await page.getByText("Fenster", { exact: true }).first().click();
|
||||
await page.getByText("BCF-Themen", { exact: true }).first().click();
|
||||
await page.waitForSelector(".bcf-panel", { timeout: 5000 });
|
||||
await page.setInputFiles(".bcf-panel input[type=file]", FILE);
|
||||
await page.waitForSelector(".bcf-topic", { timeout: 10000 });
|
||||
check("Datei geladen, 3 Themen", (await page.locator(".bcf-topic").count()) === 3);
|
||||
|
||||
// Perspektivisches Thema
|
||||
await page.locator(".bcf-topic", { hasText: "Perspektive" }).click();
|
||||
await page.waitForTimeout(900); // Kamerafahrt 350 ms
|
||||
let c = await cam();
|
||||
check("Perspektive: Kamera gesetzt", !!c && c.kind === "perspective", JSON.stringify(c && { p: c.position, d: c.direction, fov: c.fovDeg }));
|
||||
if (c) {
|
||||
check("Perspektive: Position 12/10/8", near(c.position, [12, 10, 8], 0.01), c.position.map((x) => x.toFixed(3)).join("/"));
|
||||
check("Perspektive: Blickrichtung", near(c.direction, norm([-12, -10, -7]), 1e-4));
|
||||
check("Perspektive: Sichtfeld 60°", Math.abs(c.fovDeg - 60) < 1e-6);
|
||||
check("Perspektive: Up zeigt nach oben (z)", c.up[2] > 0.5);
|
||||
}
|
||||
check("Schnittebene aus dem Viewpoint: Schnitt-Knopf sichtbar", (await page.locator('button[aria-label][title*="BCF"]').count()) >= 1);
|
||||
await page.screenshot({ path: `${OUT}/bcf-camera-perspective.png` });
|
||||
|
||||
// Orthogonales Thema
|
||||
await page.locator(".bcf-topic", { hasText: "Ortho" }).click();
|
||||
await page.waitForTimeout(900);
|
||||
c = await cam();
|
||||
check("Ortho: Kamera gesetzt", !!c && c.kind === "orthogonal", JSON.stringify(c && { p: c.position, d: c.direction, h: c.orthoHeight, a: c.aspect }));
|
||||
if (c) {
|
||||
check("Ortho: Position 2.5/2/30", near(c.position, [2.5, 2, 30], 0.01), c.position.map((x) => x.toFixed(4)).join("/"));
|
||||
check("Ortho: Blick nach unten", near(c.direction, [0, 0, -1], 1e-3));
|
||||
check("Ortho: Breite 16 m", Math.abs(c.orthoHeight * c.aspect - 16) < 0.01, `Höhe ${c.orthoHeight.toFixed(3)} · Aspekt ${c.aspect.toFixed(3)}`);
|
||||
}
|
||||
check("Ortho: Schnitt wieder aufgehoben", (await page.locator('button[aria-label][title*="BCF"]').count()) === 0);
|
||||
|
||||
// Rundreise: Kamera lesen → setzen → lesen
|
||||
const before = await cam();
|
||||
await page.evaluate((v) => window.__dossierCamera.setCamera(v, { animate: false }), before);
|
||||
await page.waitForTimeout(200);
|
||||
const after = await cam();
|
||||
check("getCamera → setCamera → getCamera unverändert", !!before && !!after && near(before.position, after.position, 1e-4) && near(before.direction, after.direction, 1e-4) && Math.abs(before.orthoHeight - after.orthoHeight) < 1e-4);
|
||||
|
||||
// Ansicht aufnehmen: aktuelle Kamera (+ Schnappschuss) als weiterer Viewpoint des Themas. (Die Auswahl
|
||||
// "Thema aus Auswahl" nutzt denselben Aufnahmeweg; hier ohne Auswahl, weil das Demo-Projekt im
|
||||
// Browser-Lauf keine passenden GlobalIds liefert.)
|
||||
await page.locator(".bcf-topic", { hasText: "Perspektive" }).click();
|
||||
await page.waitForTimeout(900);
|
||||
await page.locator('button[title^="Axonometrie"]').first().click().catch(() => {});
|
||||
await page.waitForTimeout(600);
|
||||
const atCapture = await cam();
|
||||
await page.getByRole("button", { name: "Ansicht aufnehmen" }).click();
|
||||
await page.waitForTimeout(1200);
|
||||
check("Ansicht aufnehmen: zweiter Viewpoint", (await page.locator(".bcf-vp").count()) === 2);
|
||||
const snaps = await page.locator(".bcf-vp img.bcf-snapshot").count();
|
||||
console.log(`INFO Schnappschuss im Viewpoint: ${snaps > 0 ? "ja" : "nein (Container: WebGPU-Frame leer, Kamera trotzdem gespeichert)"}`);
|
||||
// Zurück auf den ersten Viewpoint, dann auf den neuen: die aufgenommene Kamera kommt wieder.
|
||||
await page.locator(".bcf-vp").nth(0).click();
|
||||
await page.waitForTimeout(900);
|
||||
const first = await cam();
|
||||
check("Viewpoint 1 stellt die Perspektive wieder her", !!first && near(first.position, [12, 10, 8], 0.01));
|
||||
await page.locator(".bcf-vp").nth(1).click();
|
||||
await page.waitForTimeout(900);
|
||||
const restored = await cam();
|
||||
check("Viewpoint 2 stellt die aufgenommene Kamera wieder her", !!atCapture && !!restored && near(atCapture.position, restored.position, 0.01) && near(atCapture.direction, restored.direction, 1e-3) && atCapture.kind === restored.kind, restored ? restored.position.map((x) => x.toFixed(2)).join("/") : "");
|
||||
// Kommentar mit angehängter Ansicht (Häkchen ist voreingestellt)
|
||||
await page.locator(".bcf-input").fill("Prüfen bitte");
|
||||
await page.getByRole("button", { name: "Kommentieren" }).click();
|
||||
await page.waitForTimeout(1200);
|
||||
check("Kommentar mit Ansicht: dritter Viewpoint", (await page.locator(".bcf-vp").count()) === 3);
|
||||
await page.screenshot({ path: `${OUT}/bcf-camera-topic.png` });
|
||||
|
||||
console.log("Konsolenfehler:", errors.length ? errors.slice(0, 5) : "keine");
|
||||
await browser.close();
|
||||
process.exit(results.every((r) => r.ok) ? 0 : 1);
|
||||
@@ -286,3 +286,89 @@ pub fn preset_camera(preset: CameraPreset, target: [f32; 3], dist: f32) -> Camer
|
||||
}
|
||||
cam
|
||||
}
|
||||
|
||||
/// Achsparallele Bounding-Box (min, max) in world-Metern.
|
||||
pub type Bounds3 = ([f32; 3], [f32; 3]);
|
||||
|
||||
/// Vereinigung zweier Bounding-Boxen (Modell + sichtbare Punktwolken). `None` = leer;
|
||||
/// nicht endliche Boxen (NaN/Inf) zählen als leer — nie ein Panic, nie eine NaN-Kamera.
|
||||
pub fn merge_bounds(a: Option<Bounds3>, b: Option<Bounds3>) -> Option<Bounds3> {
|
||||
let finite = |x: &Option<Bounds3>| match x {
|
||||
Some((lo, hi)) => lo.iter().chain(hi.iter()).all(|v| v.is_finite()),
|
||||
None => false,
|
||||
};
|
||||
match (finite(&a), finite(&b)) {
|
||||
(true, true) => {
|
||||
let ((alo, ahi), (blo, bhi)) = (a.unwrap(), b.unwrap());
|
||||
let mut lo = alo;
|
||||
let mut hi = ahi;
|
||||
for i in 0..3 {
|
||||
lo[i] = lo[i].min(blo[i]);
|
||||
hi[i] = hi[i].max(bhi[i]);
|
||||
}
|
||||
Some((lo, hi))
|
||||
}
|
||||
(true, false) => a,
|
||||
(false, true) => b,
|
||||
(false, false) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Formatfüllendes Ziel + Abstand für eine Bounding-Box (Bounding-Kugel im vertikalen Sichtfeld
|
||||
/// plus 20 % Rand, mindestens 4 m). Ohne Box der neutrale Standpunkt wie im three.js-Start.
|
||||
pub fn fit_target_dist(bounds: Option<Bounds3>, fov_y: f32) -> ([f32; 3], f32) {
|
||||
match bounds {
|
||||
Some((min, max)) => {
|
||||
let center = [
|
||||
(min[0] + max[0]) * 0.5,
|
||||
(min[1] + max[1]) * 0.5,
|
||||
(min[2] + max[2]) * 0.5,
|
||||
];
|
||||
let (dx, dy, dz) = (max[0] - min[0], max[1] - min[1], max[2] - min[2]);
|
||||
let radius = (dx * dx + dy * dy + dz * dz).sqrt() * 0.5;
|
||||
let radius = if radius > 0.0 { radius } else { 1.0 };
|
||||
let dist = ((radius / (fov_y * 0.5).tan()) * 1.2).max(4.0);
|
||||
(center, dist)
|
||||
}
|
||||
None => ([2.5, 1.0, 2.0], 14.0),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod fit_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn merge_vereinigt_modell_und_punktwolke() {
|
||||
let m = ([0.0, 0.0, 0.0], [10.0, 3.0, 8.0]);
|
||||
let p = ([-5.0, 1.0, 2.0], [4.0, 20.0, 30.0]);
|
||||
assert_eq!(merge_bounds(Some(m), Some(p)), Some(([-5.0, 0.0, 0.0], [10.0, 20.0, 30.0])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_mit_leer_oder_unsinn_liefert_die_andere() {
|
||||
let m = ([0.0; 3], [1.0; 3]);
|
||||
assert_eq!(merge_bounds(Some(m), None), Some(m));
|
||||
assert_eq!(merge_bounds(None, Some(m)), Some(m));
|
||||
let nan = ([f32::NAN; 3], [1.0; 3]);
|
||||
assert_eq!(merge_bounds(Some(m), Some(nan)), Some(m));
|
||||
assert_eq!(merge_bounds(Some(nan), None), None);
|
||||
assert_eq!(merge_bounds(None, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_rahmt_die_vereinigte_box_ein() {
|
||||
let fov = 50.0_f32.to_radians();
|
||||
let modell = ([0.0, 0.0, 0.0], [10.0, 3.0, 8.0]);
|
||||
let wolke = ([200.0, 0.0, 0.0], [260.0, 20.0, 50.0]);
|
||||
let (_, d_modell) = fit_target_dist(Some(modell), fov);
|
||||
let (t, d_beide) = fit_target_dist(merge_bounds(Some(modell), Some(wolke)), fov);
|
||||
assert!(d_beide > d_modell * 5.0, "Wolke muss den Abstand vergrössern");
|
||||
assert!((t[0] - 130.0).abs() < 1e-4, "Ziel liegt in der Mitte beider Boxen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_ohne_box_ist_der_neutrale_standpunkt() {
|
||||
assert_eq!(fit_target_dist(None, 0.8), ([2.5, 1.0, 2.0], 14.0));
|
||||
}
|
||||
}
|
||||
@@ -436,29 +436,40 @@ impl WebModelRenderer {
|
||||
)))
|
||||
}
|
||||
};
|
||||
let (target, dist) = match self.bounds {
|
||||
Some((min, max)) => {
|
||||
let center = [
|
||||
(min[0] + max[0]) * 0.5,
|
||||
(min[1] + max[1]) * 0.5,
|
||||
(min[2] + max[2]) * 0.5,
|
||||
];
|
||||
let (dx, dy, dz) = (max[0] - min[0], max[1] - min[1], max[2] - min[2]);
|
||||
let radius = (dx * dx + dy * dy + dz * dz).sqrt() * 0.5;
|
||||
let radius = if radius > 0.0 { radius } else { 1.0 };
|
||||
// Abstand so, dass die Bounding-Kugel ins vertikale Sichtfeld
|
||||
// passt (+ Rand) — identische Formel wie `fitTargetDist`.
|
||||
let fov_y = crate::types::default_fov();
|
||||
let dist = ((radius / (fov_y * 0.5).tan()) * 1.2).max(4.0);
|
||||
(center, dist)
|
||||
}
|
||||
// Leeres Modell: neutraler Standpunkt (entspricht dem three.js-Start).
|
||||
None => ([2.5_f32, 1.0, 2.0], 14.0_f32),
|
||||
};
|
||||
// Modell UND sichtbare Punktwolken einpassen ([27]).
|
||||
let (target, dist) = self.fit_target_dist();
|
||||
self.camera = preset_camera(preset, target, dist);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bounding-Box aus Modell und sichtbaren Punktwolken → Ziel + Abstand (`math::fit_target_dist`).
|
||||
fn fit_target_dist(&self) -> ([f32; 3], f32) {
|
||||
let merged = crate::math::merge_bounds(self.bounds, self.renderer.point_cloud_bounds());
|
||||
crate::math::fit_target_dist(merged, crate::types::default_fov())
|
||||
}
|
||||
|
||||
/// Formatfüllendes Ziel + Abstand für Modell + sichtbare Punktwolken (dieselbe Rechnung wie
|
||||
/// `set_view_preset`). Liefert `[tx, ty, tz, dist]` (world, Y-up), damit die TS-Seite ihren
|
||||
/// Orbit-Zustand daraus setzt statt die Rechnung zu spiegeln.
|
||||
pub fn view_fit(&self) -> Vec<f32> {
|
||||
let (t, d) = self.fit_target_dist();
|
||||
vec![t[0], t[1], t[2], d]
|
||||
}
|
||||
|
||||
/// Aktuelle Kamera als `[eye(3), target(3), up(3), perspektivisch (1/0), fovY (rad), orthoHalbhöhe]`
|
||||
/// — 12 Werte, world Y-up. Für Lesezugriffe (BCF-Viewpoint, Orbit-Abgleich nach einem Preset).
|
||||
pub fn camera_state(&self) -> Vec<f32> {
|
||||
let c = &self.camera;
|
||||
vec![
|
||||
c.eye[0], c.eye[1], c.eye[2],
|
||||
c.target[0], c.target[1], c.target[2],
|
||||
c.up[0], c.up[1], c.up[2],
|
||||
if matches!(c.projection, Projection::Perspective) { 1.0 } else { 0.0 },
|
||||
c.fov_y,
|
||||
c.ortho_half_height,
|
||||
]
|
||||
}
|
||||
|
||||
/// Darstellungsart der Oberleiste setzen. Gueltige Werte:
|
||||
/// - `"shaded"` — beleuchtete Bauteilfarben (Default).
|
||||
/// - `"white"` — Clay-Look: einheitlich helles Material, beleuchtet
|
||||
|
||||
@@ -2147,6 +2147,7 @@ export const de = {
|
||||
"viewport3d.section.show": "Schnittebene ein",
|
||||
"viewport3d.section.hide": "Schnittebene aus",
|
||||
"viewport3d.section.bound": "3D-Schnitt aufheben (an Schnittlinie gebunden)",
|
||||
"viewport3d.section.bcf": "3D-Schnitt aufheben (aus BCF-Viewpoint)",
|
||||
"viewport3d.grip.vertex": "Wandende ziehen",
|
||||
"viewport3d.grip.height": "Höhe ziehen",
|
||||
"viewport3d.grip.move": "Verschieben",
|
||||
@@ -2335,6 +2336,20 @@ export const de = {
|
||||
"bcf.openFailed": "BCF-Datei nicht lesbar: {error}",
|
||||
"bcf.saved": "BCF gespeichert.",
|
||||
"bcf.saveFailed": "BCF nicht gespeichert: {error}",
|
||||
"bcf.viewpoints": "Ansichten",
|
||||
"bcf.viewpoint.go": "Ansicht {n} im 3D einstellen",
|
||||
"bcf.viewpoint.snapshot": "Ansicht {n}",
|
||||
"bcf.noViewport": "Keine 3D-Ansicht geöffnet: die Kamera des Viewpoints wurde nicht gesetzt.",
|
||||
"bcf.cameraSet": "Kamera aus dem Viewpoint gesetzt.",
|
||||
"bcf.cameraFailed": "Die Kamera des Viewpoints ist unbrauchbar und wurde nicht gesetzt.",
|
||||
"bcf.sectionSet": "Schnittebene aus dem Viewpoint im 3D gesetzt.",
|
||||
"bcf.sectionTilted": "Der Viewpoint enthält eine schräge Schnittebene: sie wird nur angezeigt, der 3D-Schnitt kann nur senkrechte Ebenen.",
|
||||
"bcf.clipping": "Schnittebenen",
|
||||
"bcf.clipping.item": "bei {x} / {y} / {z} m, Richtung {dx} / {dy} / {dz}",
|
||||
"bcf.attachView": "Aktuelle 3D-Ansicht anhängen",
|
||||
"bcf.addViewpoint": "Ansicht aufnehmen",
|
||||
"bcf.addViewpoint.hint": "Hängt die aktuelle 3D-Kamera mit Bild und der Auswahl als Viewpoint an das Thema.",
|
||||
"bcf.noSnapshot": "Kein Bild aufgenommen (3D-Bild nicht lesbar); die Kamera ist trotzdem gespeichert.",
|
||||
} as const;
|
||||
|
||||
export type TranslationKey = keyof typeof de;
|
||||
@@ -2134,6 +2134,7 @@ export const en: Record<TranslationKey, string> = {
|
||||
"viewport3d.section.show": "Section plane on",
|
||||
"viewport3d.section.hide": "Section plane off",
|
||||
"viewport3d.section.bound": "Clear 3D section (bound to section line)",
|
||||
"viewport3d.section.bcf": "Clear 3D section (from BCF viewpoint)",
|
||||
"viewport3d.grip.vertex": "Drag wall endpoint",
|
||||
"viewport3d.grip.edge": "Drag edge",
|
||||
"viewport3d.grip.height": "Drag height",
|
||||
@@ -2321,4 +2322,18 @@ export const en: Record<TranslationKey, string> = {
|
||||
"bcf.openFailed": "BCF file not readable: {error}",
|
||||
"bcf.saved": "BCF saved.",
|
||||
"bcf.saveFailed": "BCF not saved: {error}",
|
||||
"bcf.viewpoints": "Views",
|
||||
"bcf.viewpoint.go": "Go to view {n} in 3D",
|
||||
"bcf.viewpoint.snapshot": "View {n}",
|
||||
"bcf.noViewport": "No 3D view open: the viewpoint camera was not applied.",
|
||||
"bcf.cameraSet": "Camera set from the viewpoint.",
|
||||
"bcf.cameraFailed": "The viewpoint camera is unusable and was not applied.",
|
||||
"bcf.sectionSet": "Section plane from the viewpoint set in 3D.",
|
||||
"bcf.sectionTilted": "The viewpoint contains an inclined section plane: it is only listed, the 3D section supports vertical planes only.",
|
||||
"bcf.clipping": "Section planes",
|
||||
"bcf.clipping.item": "at {x} / {y} / {z} m, direction {dx} / {dy} / {dz}",
|
||||
"bcf.attachView": "Attach current 3D view",
|
||||
"bcf.addViewpoint": "Capture view",
|
||||
"bcf.addViewpoint.hint": "Attaches the current 3D camera with image and selection to the topic as a viewpoint.",
|
||||
"bcf.noSnapshot": "No image captured (3D image not readable); the camera is saved anyway.",
|
||||
};
|
||||
+101
-15
@@ -4,9 +4,11 @@
|
||||
// IFC-GlobalId, dieselbe Ableitung wie im IFC-Export: `io/bcfMatch.ts`). Kommentar hinzufügen,
|
||||
// Status ändern, neues Thema aus der Auswahl, als .bcfzip speichern.
|
||||
//
|
||||
// Die Themen gehören nicht zum Projekt (eigene Datei, `bcfSession.ts`). Die Kamera eines Viewpoints
|
||||
// wird angezeigt, aber noch nicht gesetzt: `Wasm3DViewport` hält seine Orbit-Kamera intern und bietet
|
||||
// keine Setz-Funktion (s. TODO.md [BCF]).
|
||||
// Die Themen gehören nicht zum Projekt (eigene Datei, `bcfSession.ts`). Kamera und Schnittebene
|
||||
// eines Viewpoints setzt die Kamera-Brücke des 3D-Viewports (`viewport/cameraBridge.ts`, Umrechnung
|
||||
// samt LV95-Versatz in `bcfView.ts`); neue Themen und Kommentare nehmen die aktuelle Kamera plus
|
||||
// Schnappschuss als Viewpoint auf. Ohne offenen WASM-3D-Viewport (kein 3D, nativer macOS-Pfad)
|
||||
// bleibt es bei Anzeige und Auswahl.
|
||||
//
|
||||
// Bezeichner englisch, UI-Text deutsch/englisch über t().
|
||||
|
||||
@@ -21,13 +23,13 @@ import {
|
||||
addTopic,
|
||||
emptyBcf,
|
||||
newTopic,
|
||||
newViewpoint,
|
||||
parseBcf,
|
||||
setTopicStatus,
|
||||
writeBcf,
|
||||
type BcfCamera,
|
||||
type BcfFile,
|
||||
type BcfTopic,
|
||||
type BcfViewpoint,
|
||||
type BcfVersion,
|
||||
} from "../io/bcf";
|
||||
import {
|
||||
@@ -39,6 +41,9 @@ import {
|
||||
type BcfSelection,
|
||||
} from "../io/bcfMatch";
|
||||
import { fileioLoaded, loadFileio } from "../engine/fileioWasm";
|
||||
import { projectGeoOrigin } from "../core";
|
||||
import { captureSnapshot, getCamera, setCamera, setSection, viewportAvailable } from "../viewport/cameraBridge";
|
||||
import { firstViewpointWithCamera, sectionFromBcfClipping, viewCameraFromBcf, viewpointForTopic } from "./bcfView";
|
||||
import { setBcfSession, useBcfSession } from "./bcfSession";
|
||||
|
||||
const AUTHOR_KEY = "dossier.bcf.author";
|
||||
@@ -109,6 +114,7 @@ export function BcfPanel() {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const authorRef = useRef<HTMLInputElement>(null);
|
||||
const commentRef = useRef<HTMLTextAreaElement>(null);
|
||||
const attachRef = useRef<HTMLInputElement>(null);
|
||||
const { file, selectedGuid } = session;
|
||||
const topic = file?.topics.find((x) => x.guid === selectedGuid) ?? null;
|
||||
|
||||
@@ -125,9 +131,29 @@ export function BcfPanel() {
|
||||
}
|
||||
};
|
||||
|
||||
const selectTopic = (tp: BcfTopic) => {
|
||||
setBcfSession({ selectedGuid: tp.guid });
|
||||
const guids = [...new Set(tp.viewpoints.flatMap(viewpointGuids))];
|
||||
/** Kamera, Schnittebene und Bauteile eines Viewpoints im Modell zeigen. */
|
||||
const showViewpoint = (vp: BcfViewpoint | null, topicGuids: string[]) => {
|
||||
const origin = projectGeoOrigin(host.project);
|
||||
if (vp?.camera || (vp && vp.clippingPlanes.length > 0)) {
|
||||
if (!viewportAvailable()) {
|
||||
notify(t("bcf.noViewport"), "warning");
|
||||
} else {
|
||||
if (vp.camera) {
|
||||
const vc = viewCameraFromBcf(vp.camera, origin, getCamera()?.aspect ?? 1);
|
||||
if (vc && setCamera(vc, { animate: true })) notify(t("bcf.cameraSet"), "info");
|
||||
else notify(t("bcf.cameraFailed"), "warning");
|
||||
}
|
||||
// Schnitt: die erste senkrechte Ebene wird live gesetzt; ohne Ebenen fällt ein früherer Schnitt weg.
|
||||
const planes = vp.clippingPlanes;
|
||||
const live = planes.map((c) => sectionFromBcfClipping(c, origin)).find((x) => x !== null) ?? null;
|
||||
setSection(live);
|
||||
if (live) notify(t("bcf.sectionSet"), "info");
|
||||
else if (planes.length > 0) notify(t("bcf.sectionTilted"), "warning");
|
||||
}
|
||||
} else if (vp && viewportAvailable()) {
|
||||
setSection(null);
|
||||
}
|
||||
const guids = vp ? viewpointGuids(vp) : topicGuids;
|
||||
if (guids.length === 0) return;
|
||||
// GlobalIds brauchen das Format-Modul (Rust-Hash); nach dem Öffnen ist es geladen.
|
||||
void loadFileio().then(() => {
|
||||
@@ -138,6 +164,26 @@ export function BcfPanel() {
|
||||
});
|
||||
};
|
||||
|
||||
const selectTopic = (tp: BcfTopic) => {
|
||||
setBcfSession({ selectedGuid: tp.guid });
|
||||
// Kamera/Schnitt vom ersten Viewpoint mit Kamera, sonst vom ersten überhaupt; die Auswahl
|
||||
// gilt dem ganzen Thema (alle Viewpoints).
|
||||
const topicGuids = [...new Set(tp.viewpoints.flatMap(viewpointGuids))];
|
||||
const vp = firstViewpointWithCamera(tp) ?? tp.viewpoints[0] ?? null;
|
||||
showViewpoint(vp, topicGuids);
|
||||
};
|
||||
|
||||
/** Neuer Viewpoint aus Auswahl + aktueller Kamera + Schnappschuss. */
|
||||
const captureViewpoint = async (): Promise<BcfViewpoint> => {
|
||||
await loadFileio();
|
||||
const sel = currentSelection();
|
||||
const guids = bcfSelectionSize(sel) > 0 ? selectionToGuids(host.project, sel) : [];
|
||||
const camera = getCamera();
|
||||
const png = camera ? await captureSnapshot() : null;
|
||||
if (camera && !png) notify(t("bcf.noSnapshot"), "info");
|
||||
return viewpointForTopic({ guid: uuid(), ifcGuids: guids, camera, snapshotPng: png, origin: projectGeoOrigin(host.project) });
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (!file) return;
|
||||
try {
|
||||
@@ -158,24 +204,40 @@ export function BcfPanel() {
|
||||
notify(t("bcf.needSelection"), "warning");
|
||||
return;
|
||||
}
|
||||
await loadFileio();
|
||||
const guids = selectionToGuids(host.project, sel);
|
||||
const vp = await captureViewpoint();
|
||||
const topicGuid = uuid();
|
||||
const tp = newTopic({
|
||||
guid: topicGuid,
|
||||
title: t("bcf.defaultTitle"),
|
||||
author: author(),
|
||||
now: now(),
|
||||
viewpoints: guids.length > 0 ? [newViewpoint(uuid(), guids)] : [],
|
||||
viewpoints: vp.selection.length > 0 || vp.camera ? [vp] : [],
|
||||
});
|
||||
const base = file ?? emptyBcf(host.project.id, host.project.name ?? "");
|
||||
setBcfSession({ file: addTopic(base, tp), dirty: true, selectedGuid: topicGuid });
|
||||
};
|
||||
|
||||
const submitComment = () => {
|
||||
/** Aktuelle 3D-Ansicht (Kamera + Bild + Auswahl) als weiteren Viewpoint ans gewählte Thema hängen. */
|
||||
const addViewpointToTopic = async () => {
|
||||
if (!file || !topic) return;
|
||||
if (!viewportAvailable()) {
|
||||
notify(t("bcf.noViewport"), "warning");
|
||||
return;
|
||||
}
|
||||
const vp = await captureViewpoint();
|
||||
update({ ...file, topics: file.topics.map((x) => (x.guid === topic.guid ? { ...x, viewpoints: [...x.viewpoints, vp], modifiedDate: now(), modifiedAuthor: author() } : x)) });
|
||||
};
|
||||
|
||||
const submitComment = async () => {
|
||||
const el = commentRef.current;
|
||||
if (!file || !topic || !el || el.value.trim() === "") return;
|
||||
update(addComment(file, topic.guid, { guid: uuid(), date: now(), author: author(), comment: el.value.trim(), viewpointGuid: "", modifiedDate: "", modifiedAuthor: "" }));
|
||||
const text = el.value.trim();
|
||||
// Optional die aktuelle 3D-Ansicht als Viewpoint des Kommentars.
|
||||
let vp: BcfViewpoint | null = null;
|
||||
if (attachRef.current?.checked && viewportAvailable()) vp = await captureViewpoint();
|
||||
const withVp = vp && (vp.camera || vp.selection.length > 0) ? vp : null;
|
||||
const next = addComment(file, topic.guid, { guid: uuid(), date: now(), author: author(), comment: text, viewpointGuid: withVp?.guid ?? "", modifiedDate: "", modifiedAuthor: "" });
|
||||
update(withVp ? { ...next, topics: next.topics.map((x) => (x.guid === topic.guid ? { ...x, viewpoints: [...x.viewpoints, withVp] } : x)) } : next);
|
||||
el.value = "";
|
||||
};
|
||||
|
||||
@@ -184,7 +246,7 @@ export function BcfPanel() {
|
||||
update({ ...file, topics: file.topics.map((x) => (x.guid === topic.guid ? { ...x, title, modifiedDate: now(), modifiedAuthor: author() } : x)) });
|
||||
};
|
||||
|
||||
const snapshot = topic?.viewpoints.find((v) => v.snapshot)?.snapshot;
|
||||
const clipping = topic?.viewpoints.flatMap((v) => v.clippingPlanes) ?? [];
|
||||
const camera = topic?.viewpoints.find((v) => v.camera)?.camera ?? null;
|
||||
const topicGuids = topic ? [...new Set(topic.viewpoints.flatMap(viewpointGuids))] : [];
|
||||
const project = host.project;
|
||||
@@ -250,8 +312,25 @@ export function BcfPanel() {
|
||||
{topic.labels.length > 0 && <div className="bcf-kv"><span>{t("bcf.labels")}</span>{topic.labels.join(", ")}</div>}
|
||||
</div>
|
||||
{topic.description && <div className="bcf-desc">{topic.description}</div>}
|
||||
{snapshot && <img className="bcf-snapshot" alt="" src={`data:image/png;base64,${snapshot}`} />}
|
||||
{topic.viewpoints.length > 0 && (
|
||||
<>
|
||||
<div className="bcf-sub">{t("bcf.viewpoints")}</div>
|
||||
<div className="bcf-vps">
|
||||
{topic.viewpoints.map((vp, i) => (
|
||||
<button key={vp.guid} type="button" className="bcf-vp" title={t("bcf.viewpoint.go", { n: i + 1 })} onClick={() => showViewpoint(vp, [])}>
|
||||
{vp.snapshot ? <img className="bcf-snapshot" alt="" src={`data:image/png;base64,${vp.snapshot}`} /> : <span>{t("bcf.viewpoint.snapshot", { n: i + 1 })}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{camera && <div className="bcf-info"><b>{t("bcf.camera")}:</b> {cameraText(camera)}</div>}
|
||||
{clipping.length > 0 && (
|
||||
<div className="bcf-info">
|
||||
<b>{t("bcf.clipping")}:</b>{" "}
|
||||
{clipping.map((c) => t("bcf.clipping.item", { x: f1(c.location[0]), y: f1(c.location[1]), z: f1(c.location[2]), dx: f1(c.direction[0]), dy: f1(c.direction[1]), dz: f1(c.direction[2]) })).join("; ")}
|
||||
</div>
|
||||
)}
|
||||
<div className="bcf-bar">
|
||||
<div className="bcf-info bcf-grow">{topicGuids.length > 0 ? t("bcf.components", { found: foundCount, total: topicGuids.length }) : t("bcf.components.none")}</div>
|
||||
{topicGuids.length > 0 && <button type="button" className="bcf-btn" onClick={() => selectTopic(topic)}>{t("bcf.selectElements")}</button>}
|
||||
@@ -264,7 +343,14 @@ export function BcfPanel() {
|
||||
</div>
|
||||
))}
|
||||
<textarea ref={commentRef} className="bcf-input" rows={2} placeholder={t("bcf.commentPlaceholder")} />
|
||||
<button type="button" className="bcf-btn" onClick={submitComment}>{t("bcf.addComment")}</button>
|
||||
<label className="bcf-check">
|
||||
<input ref={attachRef} type="checkbox" defaultChecked />
|
||||
<span>{t("bcf.attachView")}</span>
|
||||
</label>
|
||||
<div className="bcf-bar">
|
||||
<button type="button" className="bcf-btn" onClick={() => void submitComment()}>{t("bcf.addComment")}</button>
|
||||
<button type="button" className="bcf-btn" title={t("bcf.addViewpoint.hint")} onClick={() => void addViewpointToTopic()}>{t("bcf.addViewpoint")}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
// BCF-Kamera: Rundreise Viewport → BCF → Viewport, mit und ohne Standort-Bezug (LV95-Versatz).
|
||||
|
||||
import "../engine/fileioWasm.setup";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { BcfViewpoint } from "../io/bcf";
|
||||
import { addTopic, emptyBcf, newTopic, newViewpoint, parseBcf, writeBcf } from "../io/bcf";
|
||||
import {
|
||||
bcfCameraFromView,
|
||||
bcfClippingFromSection,
|
||||
firstViewpointWithCamera,
|
||||
sectionFromBcfClipping,
|
||||
viewCameraFromBcf,
|
||||
viewpointForTopic,
|
||||
} from "./bcfView";
|
||||
import { orbitCamera, orbitFromCamera3d, viewCameraFromCamera3d, camera3dFromViewCamera, type OrbitState, type ViewCamera } from "../viewport/cameraBridge";
|
||||
|
||||
const close = (a: readonly number[], b: readonly number[], digits = 6) => a.forEach((v, i) => expect(v).toBeCloseTo(b[i], digits));
|
||||
const origin = { e: 2_600_000, n: 1_200_000 };
|
||||
|
||||
const orbit: OrbitState = { yaw: 1.1, pitch: 0.45, dist: 18, target: [12, 3, -7], ortho: false, orthoHalfHeight: 8 };
|
||||
|
||||
describe("BCF-Kamera", () => {
|
||||
it("Modell → BCF addiert den LV95-Versatz auf x/y, nicht auf z", () => {
|
||||
const vc = viewCameraFromCamera3d(orbitCamera(orbit), 1.5)!;
|
||||
const bc = bcfCameraFromView(vc, origin);
|
||||
expect(bc.kind).toBe("perspective");
|
||||
expect(bc.position[0]).toBeCloseTo(vc.position[0] + origin.e, 6);
|
||||
expect(bc.position[1]).toBeCloseTo(vc.position[1] + origin.n, 6);
|
||||
expect(bc.position[2]).toBeCloseTo(vc.position[2], 9);
|
||||
// Richtungen werden nicht verschoben
|
||||
close(bc.direction, vc.direction, 12);
|
||||
close(bc.up, vc.up, 12);
|
||||
expect(bc.aspectRatio).toBeCloseTo(1.5, 9);
|
||||
expect(bc.fieldOfView).toBeCloseTo(50, 9);
|
||||
});
|
||||
|
||||
it("Rundreise perspektivisch mit Bezug: Viewport → BCF → Viewport gibt dieselbe Kamera", () => {
|
||||
const cam = orbitCamera(orbit);
|
||||
const vc = viewCameraFromCamera3d(cam, 1.78)!;
|
||||
// über die Datei-Grenze: JSON wie `bcf_write`/`bcf_read`
|
||||
const bc = JSON.parse(JSON.stringify(bcfCameraFromView(vc, origin)));
|
||||
const back = viewCameraFromBcf(bc, origin, 1.78)!;
|
||||
close(back.position, vc.position, 6);
|
||||
close(back.direction, vc.direction, 9);
|
||||
close(back.up, vc.up, 9);
|
||||
expect(back.fovDeg).toBeCloseTo(vc.fovDeg, 9);
|
||||
const cam2 = camera3dFromViewCamera(back, orbit.dist)!;
|
||||
close(cam2.eye, cam.eye, 6);
|
||||
close(cam2.target, cam.target, 6);
|
||||
const o2 = orbitFromCamera3d(cam2)!;
|
||||
expect(o2.yaw).toBeCloseTo(orbit.yaw, 7);
|
||||
expect(o2.pitch).toBeCloseTo(orbit.pitch, 7);
|
||||
});
|
||||
|
||||
it("Rundreise ohne Bezug (Versatz null)", () => {
|
||||
const vc = viewCameraFromCamera3d(orbitCamera(orbit), 1)!;
|
||||
const bc = bcfCameraFromView(vc, null);
|
||||
close(bc.position, vc.position, 12);
|
||||
close(viewCameraFromBcf(bc, null, 1)!.position, vc.position, 12);
|
||||
});
|
||||
|
||||
it("orthografisch: ViewToWorldScale ist die Breite, die Rückrechnung nimmt das Seitenverhältnis des Viewports", () => {
|
||||
const o: OrbitState = { ...orbit, ortho: true, orthoHalfHeight: 6 };
|
||||
const vc = viewCameraFromCamera3d(orbitCamera(o), 2)!;
|
||||
const bc = bcfCameraFromView(vc, origin);
|
||||
expect(bc.kind).toBe("orthogonal");
|
||||
expect(bc.viewToWorldScale).toBeCloseTo(12 * 2, 9); // Höhe 12 m × Seitenverhältnis 2
|
||||
// BCF schreibt für Ortho kein AspectRatio zurück (0) → Viewport-Verhältnis zählt
|
||||
const back = viewCameraFromBcf({ ...bc, aspectRatio: 0 }, origin, 2)!;
|
||||
expect(back.kind).toBe("orthogonal");
|
||||
expect(back.orthoHeight).toBeCloseTo(12, 9);
|
||||
// Anderes Fenster beim Empfänger (Breite bleibt, Höhe ändert sich)
|
||||
expect(viewCameraFromBcf({ ...bc, aspectRatio: 0 }, origin, 3)!.orthoHeight).toBeCloseTo(8, 9);
|
||||
});
|
||||
|
||||
it("fehlender oder unsinniger Öffnungswinkel fällt auf den Standard, Nullrichtung ergibt null", () => {
|
||||
const base = bcfCameraFromView(viewCameraFromCamera3d(orbitCamera(orbit), 1)!, null);
|
||||
expect(viewCameraFromBcf({ ...base, fieldOfView: 0 }, null, 1)!.fovDeg).toBe(60);
|
||||
expect(viewCameraFromBcf({ ...base, direction: [0, 0, 0] }, null, 1)).toBeNull();
|
||||
expect(viewCameraFromBcf({ ...base, position: [NaN, 0, 0] }, null, 1)).toBeNull();
|
||||
});
|
||||
|
||||
it("zu einer ViewCamera aus BCF passt dasselbe Objekt wieder zurück (Modell → BCF → Modell)", () => {
|
||||
const vc: ViewCamera = { kind: "perspective", position: [3, 4, 5], direction: [0, 1, 0], up: [0, 0, 1], fovDeg: 45, orthoHeight: 0, aspect: 1.2 };
|
||||
const back = viewCameraFromBcf(bcfCameraFromView(vc, origin), origin, 1.2)!;
|
||||
close(back.position, vc.position);
|
||||
close(back.direction, vc.direction);
|
||||
close(back.up, vc.up);
|
||||
expect(back.fovDeg).toBeCloseTo(45, 9);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BCF-Schnittebenen", () => {
|
||||
it("Modell ↔ BCF mit Versatz, schräge Ebenen werden nicht übernommen", () => {
|
||||
const bc = bcfClippingFromSection({ location: [1, 2, 3], direction: [0, 1, 0] }, origin);
|
||||
expect(bc.location).toEqual([1 + origin.e, 2 + origin.n, 3]);
|
||||
const back = sectionFromBcfClipping(bc, origin)!;
|
||||
close(back.location, [1, 2, 3]);
|
||||
expect(sectionFromBcfClipping({ location: [0, 0, 0], direction: [0, 0, 1] }, null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Viewpoint-Wahl", () => {
|
||||
const vp = (guid: string, withCam: boolean): BcfViewpoint => {
|
||||
const v = newViewpoint(guid, []);
|
||||
if (withCam) v.camera = { kind: "perspective", position: [0, 0, 0], direction: [1, 0, 0], up: [0, 0, 1], fieldOfView: 60, viewToWorldScale: 0, aspectRatio: 1 };
|
||||
return v;
|
||||
};
|
||||
it("erster Viewpoint mit Kamera; sonst null", () => {
|
||||
const topic = { viewpoints: [vp("a", false), vp("b", true), vp("c", true)] };
|
||||
expect(firstViewpointWithCamera(topic)?.guid).toBe("b");
|
||||
expect(firstViewpointWithCamera({ viewpoints: [vp("a", false)] })).toBeNull();
|
||||
});
|
||||
it("viewpointForTopic füllt Kamera, Snapshot und Auswahl", () => {
|
||||
const cam = viewCameraFromCamera3d(orbitCamera(orbit), 1)!;
|
||||
const v = viewpointForTopic({ guid: "g1", ifcGuids: ["AAAAAAAAAAAAAAAAAAAAAA"], camera: cam, snapshotPng: new Uint8Array([1, 2, 3]), origin });
|
||||
expect(v.guid).toBe("g1");
|
||||
expect(v.camera?.kind).toBe("perspective");
|
||||
expect(v.snapshot).toBe("AQID"); // Base64 von 01 02 03
|
||||
expect(v.selection.map((c) => c.ifcGuid)).toEqual(["AAAAAAAAAAAAAAAAAAAAAA"]);
|
||||
const none = viewpointForTopic({ guid: "g2", ifcGuids: [], camera: null, snapshotPng: null, origin: null });
|
||||
expect(none.camera).toBeNull();
|
||||
expect(none.snapshot).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Rundreise über die .bcfzip (Rust)", () => {
|
||||
it("Kamera + Schnittebene überstehen Schreiben und Lesen, auch mit LV95-Versatz", async () => {
|
||||
const cam = viewCameraFromCamera3d(orbitCamera(orbit), 1.6)!;
|
||||
const section = { location: [4, 2, 0] as [number, number, number], direction: [0, -1, 0] as [number, number, number] };
|
||||
const vp = viewpointForTopic({ guid: "11111111-1111-4111-8111-111111111111", ifcGuids: [], camera: cam, snapshotPng: null, origin, section });
|
||||
for (const version of ["2.1", "3.0"] as const) {
|
||||
const file = addTopic(emptyBcf("p", "T"), newTopic({ guid: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", title: "t", author: "a", now: "2026-10-28T10:00:00Z", viewpoints: [vp] }));
|
||||
const back = await parseBcf(await writeBcf(file, version));
|
||||
const v = back.topics[0].viewpoints[0];
|
||||
const restored = viewCameraFromBcf(v.camera!, origin, 1.6)!;
|
||||
close(restored.position, cam.position, 4); // Text-Zahlen der Datei: mm genügen
|
||||
close(restored.direction, cam.direction, 6);
|
||||
close(restored.up, cam.up, 6);
|
||||
expect(restored.fovDeg).toBeCloseTo(cam.fovDeg, 6);
|
||||
const sec = sectionFromBcfClipping(v.clippingPlanes[0], origin)!;
|
||||
close(sec.location, section.location, 4);
|
||||
close(sec.direction, section.direction, 6);
|
||||
}
|
||||
});
|
||||
|
||||
it("orthogonale Kamera: ViewToWorldScale kommt zurück, Seitenverhältnis liefert der Viewport", async () => {
|
||||
const o: OrbitState = { ...orbit, ortho: true, orthoHalfHeight: 5 };
|
||||
const cam = viewCameraFromCamera3d(orbitCamera(o), 2)!;
|
||||
const vp = viewpointForTopic({ guid: "22222222-2222-4222-8222-222222222222", ifcGuids: [], camera: cam, snapshotPng: null, origin: null });
|
||||
const file = addTopic(emptyBcf("p", "T"), newTopic({ guid: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", title: "t", author: "a", now: "2026-10-28T10:00:00Z", viewpoints: [vp] }));
|
||||
const back = await parseBcf(await writeBcf(file, "2.1"));
|
||||
const restored = viewCameraFromBcf(back.topics[0].viewpoints[0].camera!, null, 2)!;
|
||||
expect(restored.kind).toBe("orthogonal");
|
||||
expect(restored.orthoHeight).toBeCloseTo(10, 6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
// BCF ↔ 3D-Viewport: reine Umrechnung von Kamera und Schnittebene zwischen der Modell-Sicht der
|
||||
// Kamera-Brücke (`viewport/cameraBridge.ts`, Meter, z oben, lokale Modell-Koordinaten) und den
|
||||
// BCF-Koordinaten (IFC-Weltkoordinaten, Meter, Z oben).
|
||||
//
|
||||
// BEZUG ZUM IFC: `exportIfcSpf` schreibt mit Standort-Bezug alle Bauteile um den LV95-Ursprung
|
||||
// verschoben (`projectToWorldCoords`: x += e, y += n; die Höhe bleibt, `geoAnchor.height` ist nur
|
||||
// `RefElevation`). Ohne Bezug bleibt das Modell lokal. BCF-Viewpoints müssen dazu passen, sonst
|
||||
// zeigt die Kamera ins Leere: Modell → BCF addiert (e, n, 0), BCF → Modell zieht ab.
|
||||
//
|
||||
// Annahmen (BCF 2.1/3.0, Viewpoint):
|
||||
// · FieldOfView = vertikaler Öffnungswinkel in Grad (wie die Fassade `io/bcf.ts` führt);
|
||||
// · ViewToWorldScale (orthogonal) = sichtbare BREITE in Metern; die Höhe folgt aus dem
|
||||
// Seitenverhältnis (`aspectRatio`, fehlt es: das des Viewports);
|
||||
// · ClippingPlane.Direction zeigt auf die weggeschnittene Seite — wie `set_section_plane`.
|
||||
// Der Live-Schnitt kann nur senkrechte Ebenen (render3d); schräge zeigt das Panel nur an.
|
||||
|
||||
import { newViewpoint, type BcfCamera, type BcfClippingPlane, type BcfTopic, type BcfViewpoint, type Vec3 } from "../io/bcf";
|
||||
import { isVerticalSection, type ViewCamera, type ViewSection, type V3 } from "../viewport/cameraBridge";
|
||||
|
||||
/** LV95-Ursprung des Projekts (`projectGeoOrigin`) oder null ohne Standort-Bezug. */
|
||||
export interface GeoOffset {
|
||||
e: number;
|
||||
n: number;
|
||||
}
|
||||
|
||||
const off = (o: GeoOffset | null): [number, number, number] => [o?.e ?? 0, o?.n ?? 0, 0];
|
||||
const add = (p: readonly number[], d: readonly number[]): Vec3 => [p[0] + d[0], p[1] + d[1], p[2] + d[2]];
|
||||
const sub = (p: readonly number[], d: readonly number[]): V3 => [p[0] - d[0], p[1] - d[1], p[2] - d[2]];
|
||||
const ok3 = (v: readonly number[]): boolean => v.length >= 3 && v.every(Number.isFinite);
|
||||
const nonzero = (v: readonly number[]): boolean => Math.hypot(v[0], v[1], v[2]) > 1e-12;
|
||||
|
||||
/** Modell-Kamera → BCF-Kamera (Weltkoordinaten). */
|
||||
export function bcfCameraFromView(vc: ViewCamera, origin: GeoOffset | null): BcfCamera {
|
||||
const ortho = vc.kind === "orthogonal";
|
||||
return {
|
||||
kind: vc.kind,
|
||||
position: add(vc.position, off(origin)),
|
||||
direction: [...vc.direction] as Vec3,
|
||||
up: [...vc.up] as Vec3,
|
||||
fieldOfView: ortho ? 0 : vc.fovDeg,
|
||||
viewToWorldScale: ortho ? vc.orthoHeight * vc.aspect : 0,
|
||||
aspectRatio: vc.aspect,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* BCF-Kamera → Modell-Kamera. `viewportAspect` springt ein, wenn die Datei kein Seitenverhältnis
|
||||
* trägt (BCF schreibt es nur für perspektivische Kameras). Null bei Unsinn (NaN, Nullrichtung).
|
||||
*/
|
||||
export function viewCameraFromBcf(bc: BcfCamera, origin: GeoOffset | null, viewportAspect: number): ViewCamera | null {
|
||||
if (!ok3(bc.position) || !ok3(bc.direction) || !ok3(bc.up)) return null;
|
||||
if (!nonzero(bc.direction)) return null;
|
||||
const aspect = bc.aspectRatio > 0 && Number.isFinite(bc.aspectRatio) ? bc.aspectRatio : viewportAspect > 0 ? viewportAspect : 1;
|
||||
const ortho = bc.kind === "orthogonal";
|
||||
const scale = Number.isFinite(bc.viewToWorldScale) && bc.viewToWorldScale > 0 ? bc.viewToWorldScale : 0;
|
||||
// Zeigt der Up-Vektor entlang der Blickrichtung (oder fehlt er), nimmt die Brücke einen Ersatz.
|
||||
const up: V3 = nonzero(bc.up) ? [...bc.up] : [0, 0, 1];
|
||||
return {
|
||||
kind: bc.kind,
|
||||
position: sub(bc.position, off(origin)),
|
||||
direction: [...bc.direction] as V3,
|
||||
up,
|
||||
fovDeg: bc.fieldOfView > 0 && Number.isFinite(bc.fieldOfView) ? bc.fieldOfView : 60,
|
||||
// orthogonal: Breite → Höhe über das Seitenverhältnis der Datei, ersatzweise des Viewports
|
||||
orthoHeight: ortho ? (scale > 0 ? scale / aspect : 10) : 0,
|
||||
aspect: viewportAspect > 0 ? viewportAspect : aspect,
|
||||
};
|
||||
}
|
||||
|
||||
/** Schnittebene Modell → BCF. */
|
||||
export function bcfClippingFromSection(s: ViewSection, origin: GeoOffset | null): BcfClippingPlane {
|
||||
return { location: add(s.location, off(origin)), direction: [...s.direction] as Vec3 };
|
||||
}
|
||||
|
||||
/** BCF-Schnittebene → Modell; null, wenn nicht senkrecht (nicht live darstellbar) oder unbrauchbar. */
|
||||
export function sectionFromBcfClipping(c: BcfClippingPlane, origin: GeoOffset | null): ViewSection | null {
|
||||
if (!ok3(c.location) || !ok3(c.direction) || !nonzero(c.direction)) return null;
|
||||
const s: ViewSection = { location: sub(c.location, off(origin)), direction: [...c.direction] as V3 };
|
||||
return isVerticalSection(s) ? s : null;
|
||||
}
|
||||
|
||||
/** Erster Viewpoint des Themas mit Kamera (das Panel springt dorthin), sonst null. */
|
||||
export function firstViewpointWithCamera(topic: Pick<BcfTopic, "viewpoints">): BcfViewpoint | null {
|
||||
return topic.viewpoints.find((v) => v.camera !== null) ?? null;
|
||||
}
|
||||
|
||||
function toBase64(bytes: Uint8Array): string {
|
||||
let s = "";
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
||||
return btoa(s);
|
||||
}
|
||||
|
||||
/** Neuer Viewpoint aus Auswahl + aktueller Kamera (+ Schnitt) + Snapshot; fehlende Teile bleiben leer. */
|
||||
export function viewpointForTopic(init: {
|
||||
guid: string;
|
||||
ifcGuids: string[];
|
||||
camera: ViewCamera | null;
|
||||
snapshotPng: Uint8Array | null;
|
||||
origin: GeoOffset | null;
|
||||
section?: ViewSection | null;
|
||||
}): BcfViewpoint {
|
||||
const vp = newViewpoint(init.guid, init.ifcGuids, init.camera ? bcfCameraFromView(init.camera, init.origin) : null);
|
||||
if (init.snapshotPng && init.snapshotPng.length > 0) vp.snapshot = toBase64(init.snapshotPng);
|
||||
if (init.section) vp.clippingPlanes = [bcfClippingFromSection(init.section, init.origin)];
|
||||
return vp;
|
||||
}
|
||||
@@ -8429,3 +8429,36 @@ body {
|
||||
line-height: 1.5;
|
||||
color: var(--ink-2);
|
||||
}
|
||||
|
||||
.bcf-vps {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
.bcf-vp {
|
||||
flex: 0 1 96px;
|
||||
min-width: 64px;
|
||||
padding: 2px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel-2);
|
||||
color: var(--ink-2);
|
||||
cursor: pointer;
|
||||
font-size: 11px;
|
||||
}
|
||||
.bcf-vp:hover {
|
||||
background: var(--accent-dim);
|
||||
border-color: var(--accent-border);
|
||||
}
|
||||
.bcf-vp .bcf-snapshot {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
.bcf-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--ink-2);
|
||||
}
|
||||
+111
-69
@@ -42,7 +42,7 @@
|
||||
// Die Orbit-/Pan-Mathematik folgt den OrbitControls-Konventionen (Winkel je
|
||||
// Pixel an der Viewport-Höhe normiert), damit sich beide Pfade gleich anfühlen.
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { Project, Wall, Drawing2D, Ceiling, Roof, Vec2 } from "../model/types";
|
||||
import { ceilingVerticalExtent, wallVerticalExtent } from "../model/wall";
|
||||
import { roofBaseElevation, roofGeometry } from "../core";
|
||||
@@ -61,13 +61,22 @@ import {
|
||||
} from "./grip3dHud";
|
||||
import { t } from "../i18n";
|
||||
import { useWasm3dRenderer } from "./useWasm3dRenderer";
|
||||
import type { Camera3d } from "./useWasm3dRenderer";
|
||||
import { cameraRay, pickNearest, rayPlaneY, rayPlane, worldToScreen } from "./raycast3d";
|
||||
import type { Vec3 } from "../core";
|
||||
import { drawingGripVertices, drawingMoveAnchor } from "./drawingGrips";
|
||||
import { pointCloudSyncItems } from "./pointCloudSync";
|
||||
import { usePointClouds } from "../state/pointCloudStore";
|
||||
import { projectGeoOrigin } from "../core";
|
||||
import {
|
||||
FOV_Y,
|
||||
PITCH_LIMIT,
|
||||
lerpOrbit,
|
||||
orbitCamera,
|
||||
orbitFromCamera3d,
|
||||
registerViewportCamera,
|
||||
type OrbitState,
|
||||
type V3 as CamV3,
|
||||
} from "./cameraBridge";
|
||||
|
||||
/** Ein per 3D-Klick getroffenes Bauteil, oder null (Leerraum). */
|
||||
export type Pick3dHit =
|
||||
@@ -212,57 +221,7 @@ function computeGrips(
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Vertikaler Öffnungswinkel (Radiant) — wie die three.js-PerspectiveCamera (50°),
|
||||
* auch für die FREIE Orbit-Kamera hier (die Presets selbst nutzen den Rust-
|
||||
* seitigen Default-FOV, s. `types::default_fov`, denselben Wert). */
|
||||
const FOV_Y = (50 * Math.PI) / 180;
|
||||
/** Pitch-Klemme gegen den Gimbal-Flip (identisch zu render3d::math::orbit_eye). */
|
||||
const PITCH_LIMIT = Math.PI / 2 - 0.01;
|
||||
|
||||
/** Orbit-Zustand der Kamera: Kugelkoordinaten um ein Blickziel (world, Y-up). */
|
||||
interface OrbitState {
|
||||
/** Azimut um die Y-Achse (Radiant). */
|
||||
yaw: number;
|
||||
/** Erhebung über die XZ-Ebene (Radiant, geklemmt). */
|
||||
pitch: number;
|
||||
/** Abstand vom Ziel (Meter). */
|
||||
dist: number;
|
||||
/** Blickziel (world). */
|
||||
target: [number, number, number];
|
||||
/** Soll die freie Kamera orthografisch bleiben? (true fuer alle Presets ausser
|
||||
* `perspective`) — sonst kippt die erste Kamerabewegung fälschlich in
|
||||
* Perspektive („locked iso"). */
|
||||
ortho: boolean;
|
||||
/** Orthografische Bild-Halbhoehe (Meter), UNABHAENGIG von `dist` gefuehrt: eine
|
||||
* echte Ortho-Kamera skaliert ihr Bild ueber diese Groesse, nicht ueber den
|
||||
* Augabstand. Wird beim Preset aus `dist*tan(FOV_Y/2)` geseedet (perspektiv-
|
||||
* äquivalente Bildhoehe an der eingepassten Distanz → kein Sprung beim ersten
|
||||
* Move) und beim Zoom in Ortho-Modus multiplikativ skaliert. */
|
||||
orthoHalfHeight: number;
|
||||
}
|
||||
|
||||
/** Fertige (freie, perspektivische) Kamera aus dem Orbit-Zustand (Konvention
|
||||
* wie render3d::math::orbit_eye). Für die manuelle Navigation NACH einem
|
||||
* Praeset-Sprung — die Presets selbst zeichnen über `set_view_preset`. */
|
||||
function orbitCamera(o: OrbitState): Camera3d {
|
||||
const pitch = Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, o.pitch));
|
||||
const r = o.dist * Math.cos(pitch);
|
||||
return {
|
||||
eye: [
|
||||
o.target[0] + r * Math.cos(o.yaw),
|
||||
o.target[1] + o.dist * Math.sin(pitch),
|
||||
o.target[2] + r * Math.sin(o.yaw),
|
||||
],
|
||||
target: [o.target[0], o.target[1], o.target[2]],
|
||||
up: [0, 1, 0],
|
||||
// Projektion aus dem Orbit-Zustand (war hartkodiert `true`/`dist*0.5` — genau
|
||||
// DAS war der Locked-Iso-Bug: die erste Bewegung nach einem Ortho-Preset kippte
|
||||
// sofort in Perspektive). Ortho behaelt seine eigene, dist-unabhaengige Halbhoehe.
|
||||
perspective: !o.ortho,
|
||||
fovY: FOV_Y,
|
||||
orthoHalfHeight: o.orthoHalfHeight,
|
||||
};
|
||||
}
|
||||
// FOV_Y, PITCH_LIMIT, OrbitState und orbitCamera leben in `./cameraBridge` (testbar, auch für BCF).
|
||||
|
||||
/**
|
||||
* Formatfüllendes Ziel + Distanz: Bounding-Box des geflachten Modells (Wände +
|
||||
@@ -536,6 +495,9 @@ export function Wasm3DViewport({
|
||||
updateModel,
|
||||
setRenderStyle,
|
||||
applyViewPreset,
|
||||
viewFit,
|
||||
readRustCamera,
|
||||
snapshotPng,
|
||||
setGroundGrid,
|
||||
setSectionPlane,
|
||||
setHighlightLines,
|
||||
@@ -557,6 +519,12 @@ export function Wasm3DViewport({
|
||||
// Redraw-Strategie des zuletzt aktiven Kamera-Modus (Praeset ODER freier
|
||||
// Orbit) — Resize/Modell-Update ruft diese auf, ohne den Modus zu kennen.
|
||||
const redrawRef = useRef<() => void>(() => {});
|
||||
// Waren schon sichtbare Punktwolken eingepasst? (erste Wolke → Kamera einpassen)
|
||||
const hadCloudsRef = useRef(false);
|
||||
// Aktuelles Preset neu anwenden und den Orbit darauf einpassen (s. `applyPreset`).
|
||||
const fitCameraRef = useRef<() => void>(() => {});
|
||||
// Live-Schnitt von aussen (BCF-Schnittebene), hat Vorrang vor `section3d`; null = keiner.
|
||||
const [extSection, setExtSection] = useState<{ point: CamV3; normal: CamV3 } | null>(null);
|
||||
// Frisches Projekt für den (stabilen) Init-Effekt unten.
|
||||
const projectRef = useRef(project);
|
||||
projectRef.current = project;
|
||||
@@ -574,8 +542,15 @@ export function Wasm3DViewport({
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
const p = projectRef.current;
|
||||
if (syncPointClouds(pointCloudSyncItems(pointClouds, projectGeoOrigin(p), p.geoAnchor?.height))) {
|
||||
redrawRef.current();
|
||||
const items = pointCloudSyncItems(pointClouds, projectGeoOrigin(p), p.geoAnchor?.height);
|
||||
if (syncPointClouds(items)) {
|
||||
// Erste sichtbare Wolke: Kamera auf Modell + Wolke einpassen (sonst bleibt sie ausserhalb des
|
||||
// Bildes, besonders bei lagerichtigen LV95-Wolken weit vom Modell).
|
||||
const anyVisible = items.some((i) => i.visible && i.data.xyz.length > 0);
|
||||
const first = anyVisible && !hadCloudsRef.current;
|
||||
hadCloudsRef.current = anyVisible;
|
||||
if (first) fitCameraRef.current();
|
||||
else redrawRef.current();
|
||||
}
|
||||
}, [ready, pointClouds, geoKey, syncPointClouds]);
|
||||
|
||||
@@ -598,28 +573,89 @@ export function Wasm3DViewport({
|
||||
// ggf. orthografische Praeset-Kamera — „hinspringen, kein Lock", der
|
||||
// Orbit-Zustand wird nur als Startpunkt für spätere manuelle Navigation
|
||||
// nachgezogen (s. VIEW3D_ORBIT).
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
const applyPreset = useCallback(() => {
|
||||
applyViewPreset(view3d);
|
||||
const { yaw, pitch } = VIEW3D_ORBIT[view3d];
|
||||
const { target, dist } = fitTargetDist(projectRef.current);
|
||||
// Ziel + Abstand kommen aus Rust (Modell UND sichtbare Punktwolken, dieselbe Rechnung wie das
|
||||
// Preset selbst); nur ältere WASM-Builds fallen auf die TS-Spiegelung zurück.
|
||||
const fit = viewFit();
|
||||
const { target, dist } = fit ?? fitTargetDist(projectRef.current);
|
||||
// Alle Presets ausser `perspective` sind orthografisch (front/top/side/iso, wie
|
||||
// die Rust-Seite `preset_camera`) → die freie Kamera bleibt danach ebenfalls
|
||||
// ortho („locked iso"). orthoHalfHeight auf die perspektiv-aequivalente Bildhoehe
|
||||
// an der eingepassten Distanz seeden, damit der erste manuelle Move/Zoom groessen-
|
||||
// gleich an das von Rust gezeichnete Preset-Bild anschliesst (kein Sprung).
|
||||
// ortho („locked iso"). Die Bildhöhe liest der Orbit aus der Rust-Preset-Kamera, damit der
|
||||
// erste manuelle Move/Zoom grössengleich an das gezeichnete Bild anschliesst (kein Sprung);
|
||||
// ältere Builds: perspektiv-äquivalente Höhe an der eingepassten Distanz.
|
||||
const ortho = view3d !== "perspective";
|
||||
const rust = readRustCamera();
|
||||
orbitRef.current = {
|
||||
yaw,
|
||||
pitch,
|
||||
dist,
|
||||
target,
|
||||
ortho,
|
||||
orthoHalfHeight: dist * Math.tan(FOV_Y / 2),
|
||||
orthoHalfHeight: rust && !rust.perspective ? rust.orthoHalfHeight : dist * Math.tan(FOV_Y / 2),
|
||||
};
|
||||
redrawRef.current = () => render(null);
|
||||
redrawRef.current();
|
||||
}, [ready, view3d, applyViewPreset, render]);
|
||||
}, [view3d, applyViewPreset, viewFit, readRustCamera, render]);
|
||||
fitCameraRef.current = applyPreset;
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
applyPreset();
|
||||
}, [ready, applyPreset]);
|
||||
|
||||
// Kamera-Brücke ([BCF]): Lesen/Setzen der Orbit-Kamera, Schnappschuss und Schnitt von aussen
|
||||
// (`cameraBridge.ts`). Der Orbit-Zustand ist die Wahrheit; nach einem Preset ist er aus der
|
||||
// Rust-Preset-Kamera geseedet (s. `applyPreset`).
|
||||
const animRef = useRef(0);
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
const canvas = canvasRef.current;
|
||||
// Das Bild so zeichnen, wie es gerade angezeigt wird (Preset-Kamera oder Orbit).
|
||||
const draw = () => redrawRef.current();
|
||||
const off = registerViewportCamera({
|
||||
read: () => {
|
||||
const o = orbitRef.current;
|
||||
const rect = canvas?.getBoundingClientRect();
|
||||
if (!o || !rect || rect.width < 1 || rect.height < 1) return null;
|
||||
return { camera: orbitCamera(o), aspect: rect.width / rect.height };
|
||||
},
|
||||
write: (cam, animate) => {
|
||||
const to = orbitFromCamera3d(cam);
|
||||
if (!to) return false;
|
||||
cancelAnimationFrame(animRef.current);
|
||||
const from = orbitRef.current;
|
||||
// Ab jetzt zeichnet der Orbit (nicht mehr die Rust-Preset-Kamera).
|
||||
redrawRef.current = () => {
|
||||
if (orbitRef.current) render(orbitCamera(orbitRef.current));
|
||||
};
|
||||
if (!animate || !from) {
|
||||
orbitRef.current = to;
|
||||
redrawRef.current();
|
||||
return true;
|
||||
}
|
||||
const t0 = performance.now();
|
||||
const DURATION = 350;
|
||||
const step = (now: number) => {
|
||||
const k = Math.min(1, (now - t0) / DURATION);
|
||||
const e = k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2; // ease in-out
|
||||
orbitRef.current = k >= 1 ? to : lerpOrbit(from, to, e);
|
||||
redrawRef.current();
|
||||
if (k < 1) animRef.current = requestAnimationFrame(step);
|
||||
};
|
||||
animRef.current = requestAnimationFrame(step);
|
||||
return true;
|
||||
},
|
||||
snapshot: (maxEdge) => snapshotPng(draw, maxEdge),
|
||||
section: (plane) => setExtSection(plane),
|
||||
fit: () => fitCameraRef.current(),
|
||||
});
|
||||
return () => {
|
||||
cancelAnimationFrame(animRef.current);
|
||||
off();
|
||||
};
|
||||
}, [ready, render, snapshotPng, canvasRef]);
|
||||
|
||||
// Darstellungsart (volle RenderMode-Union) an den Renderer weiterreichen,
|
||||
// sobald sie wechselt oder der Renderer bereit wird — dann mit der aktuell
|
||||
@@ -650,14 +686,16 @@ export function Wasm3DViewport({
|
||||
// Ebene oder Modelländerung (Caps folgen dem aktuellen Modell).
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
if (!section3d) {
|
||||
// Eine von aussen gesetzte Ebene (BCF-Viewpoint) hat Vorrang vor der gebundenen Schnittlinie.
|
||||
const plane = extSection ?? section3d;
|
||||
if (!plane) {
|
||||
setSectionPlane(false, [0, 0, 0], [0, 0, 1]);
|
||||
redrawRef.current();
|
||||
return;
|
||||
}
|
||||
setSectionPlane(true, section3d.point, section3d.normal);
|
||||
setSectionPlane(true, plane.point, plane.normal);
|
||||
redrawRef.current();
|
||||
}, [ready, section3d, project, setSectionPlane]);
|
||||
}, [ready, section3d, extSection, project, setSectionPlane]);
|
||||
|
||||
// Auswahl-Hervorhebung ODER Zeichnen-Vorschau (derselbe Kanal, s. Datei-
|
||||
// Kommentar oben): läuft gerade ein Befehl (`commandActive`), hat die
|
||||
@@ -1668,12 +1706,16 @@ export function Wasm3DViewport({
|
||||
{/* Live-Schnitt-Knopf: nur sichtbar, wenn eine Schnittlinie den 3D-Schnitt
|
||||
treibt (`section3d` gebunden, Bindung im Objekt-Info gesetzt). Klick
|
||||
hebt die Bindung auf. Sitzt ueber dem Grid-Button (falls vorhanden). */}
|
||||
{section3d && (
|
||||
{(section3d || extSection) && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("viewport3d.section.label")}
|
||||
onClick={() => onClearSection3d?.()}
|
||||
title={t("viewport3d.section.bound")}
|
||||
onClick={() => {
|
||||
// Zuerst die von aussen gesetzte Ebene (BCF) aufheben, dann die gebundene Schnittlinie.
|
||||
if (extSection) setExtSection(null);
|
||||
else onClearSection3d?.();
|
||||
}}
|
||||
title={extSection ? t("viewport3d.section.bcf") : t("viewport3d.section.bound")}
|
||||
aria-pressed
|
||||
style={{
|
||||
position: "absolute",
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
// Achsabbildung und Kamera-Rundreisen der Viewport-Brücke. Die Abbildung wird gegen das ECHTE
|
||||
// geflachte Modell (`projectToModel3d`) belegt, nicht gegen eine Annahme.
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { projectToModel3d, sampleProject } from "../core";
|
||||
import {
|
||||
FOV_Y,
|
||||
camera3dFromViewCamera,
|
||||
captureSnapshot,
|
||||
getCamera,
|
||||
isVerticalSection,
|
||||
lerpOrbit,
|
||||
modelToWorld,
|
||||
orbitCamera,
|
||||
orbitFromCamera3d,
|
||||
registerViewportCamera,
|
||||
sectionToWorld,
|
||||
setCamera,
|
||||
setSection,
|
||||
viewCameraFromCamera3d,
|
||||
viewportAvailable,
|
||||
worldToModel,
|
||||
type OrbitState,
|
||||
type V3,
|
||||
type ViewCamera,
|
||||
type ViewportCameraApi,
|
||||
} from "./cameraBridge";
|
||||
import type { Camera3d } from "./useWasm3dRenderer";
|
||||
|
||||
const close = (a: readonly number[], b: readonly number[], digits = 9) => {
|
||||
expect(a.length).toBe(b.length);
|
||||
a.forEach((v, i) => expect(v).toBeCloseTo(b[i], digits));
|
||||
};
|
||||
|
||||
afterEach(() => registerViewportCamera(null));
|
||||
|
||||
describe("Achsabbildung Modell ↔ world", () => {
|
||||
it("tauscht y und z und ist ihre eigene Umkehrung", () => {
|
||||
expect(modelToWorld([1, 2, 3])).toEqual([1, 3, 2]);
|
||||
expect(worldToModel(modelToWorld([4.5, -2, 7]))).toEqual([4.5, -2, 7]);
|
||||
});
|
||||
|
||||
it("deckt sich mit der Lage der Wände im geflachten Modell (world = (x, Höhe, y), ohne Negation)", () => {
|
||||
const project = sampleProject;
|
||||
const model = projectToModel3d(project);
|
||||
const w2 = project.walls.find((w) => w.id === "W2")!; // von (5, 0) nach (5, 4): y wächst
|
||||
expect([w2.start.y, w2.end.y]).toEqual([0, 4]);
|
||||
// Die Schichtbänder weichen nur um die halbe Wanddicke von der Achse ab. Modell-y bleibt positiv:
|
||||
// render3d bekommt `end[1]` ≈ +4 und macht daraus world-z ≈ +4 (mesh.rs: `end[1] − start[1]`).
|
||||
const bands = model.walls.filter((m) => Math.abs(m.start[0] - 5) < 0.6 && Math.abs(m.end[0] - 5) < 0.6 && m.end[1] > 3.3 && m.start[1] < 0.6);
|
||||
expect(bands.length).toBeGreaterThan(0);
|
||||
for (const b of bands) {
|
||||
expect(Math.abs(b.start[1])).toBeLessThan(0.6);
|
||||
expect(Math.abs(b.end[1] - 4)).toBeLessThan(0.6);
|
||||
// Der Fusspunkt des Bandes im Modell (x, y, Höhe) ↔ world, wie ihn der Renderer aufbaut.
|
||||
expect(modelToWorld([b.end[0], b.end[1], b.baseElevation + b.height])).toEqual([b.end[0], b.baseElevation + b.height, b.end[1]]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Orbit ↔ Kamera ↔ Modell-Sicht", () => {
|
||||
const iso: OrbitState = { yaw: Math.PI / 4, pitch: Math.asin(1 / Math.sqrt(3)), dist: 20, target: [3, 1.5, -2], ortho: false, orthoHalfHeight: 9 };
|
||||
|
||||
it("Orbit → Kamera → Orbit ergibt denselben Zustand", () => {
|
||||
const back = orbitFromCamera3d(orbitCamera(iso))!;
|
||||
expect(back.yaw).toBeCloseTo(iso.yaw, 9);
|
||||
expect(back.pitch).toBeCloseTo(iso.pitch, 9);
|
||||
expect(back.dist).toBeCloseTo(iso.dist, 9);
|
||||
close(back.target, iso.target);
|
||||
expect(back.ortho).toBe(false);
|
||||
});
|
||||
|
||||
it("Blick aus Süd-Ost-oben in Modell-Koordinaten: Position und Richtung sind gespiegelte world-Werte", () => {
|
||||
const cam = orbitCamera(iso);
|
||||
const vc = viewCameraFromCamera3d(cam, 1.6)!;
|
||||
// eye (world) → Modell: y und z getauscht
|
||||
close(vc.position, [cam.eye[0], cam.eye[2], cam.eye[1]]);
|
||||
// Das Ziel liegt in Blickrichtung vor der Kamera: position + dir·dist = target (Modell).
|
||||
const t = [vc.position[0] + vc.direction[0] * iso.dist, vc.position[1] + vc.direction[1] * iso.dist, vc.position[2] + vc.direction[2] * iso.dist];
|
||||
close(t, [iso.target[0], iso.target[2], iso.target[1]]);
|
||||
// Der Blick geht abwärts (Modell-z der Richtung < 0), Up zeigt aufwärts.
|
||||
expect(vc.direction[2]).toBeLessThan(0);
|
||||
expect(vc.up[2]).toBeGreaterThan(0);
|
||||
// Up steht senkrecht auf der Blickrichtung, beide normiert.
|
||||
expect(vc.direction[0] * vc.up[0] + vc.direction[1] * vc.up[1] + vc.direction[2] * vc.up[2]).toBeCloseTo(0, 9);
|
||||
expect(Math.hypot(...vc.up)).toBeCloseTo(1, 9);
|
||||
expect(Math.hypot(...vc.direction)).toBeCloseTo(1, 9);
|
||||
expect(vc.fovDeg).toBeCloseTo(50, 9);
|
||||
expect(vc.aspect).toBe(1.6);
|
||||
});
|
||||
|
||||
it("getCamera → setCamera ergibt dieselbe Kamera (perspektivisch)", () => {
|
||||
const cam = orbitCamera(iso);
|
||||
const vc = viewCameraFromCamera3d(cam, 1.5)!;
|
||||
const back = camera3dFromViewCamera(vc, iso.dist)!;
|
||||
close(back.eye, cam.eye);
|
||||
close(back.target, cam.target);
|
||||
expect(back.perspective).toBe(true);
|
||||
expect(back.fovY).toBeCloseTo(FOV_Y, 9);
|
||||
// Up ist orthogonalisiert, steht aber in derselben Ebene wie (0,1,0) und die Blickrichtung.
|
||||
expect(back.up[0] * (cam.target[0] - cam.eye[0]) + back.up[1] * (cam.target[1] - cam.eye[1]) + back.up[2] * (cam.target[2] - cam.eye[2])).toBeCloseTo(0, 9);
|
||||
const o2 = orbitFromCamera3d(back)!;
|
||||
expect(o2.yaw).toBeCloseTo(iso.yaw, 9);
|
||||
expect(o2.pitch).toBeCloseTo(iso.pitch, 9);
|
||||
});
|
||||
|
||||
it("orthografisch: Sichthöhe wird als volle Höhe geführt und kommt als Halbhöhe zurück", () => {
|
||||
const o: OrbitState = { ...iso, ortho: true, orthoHalfHeight: 7.25 };
|
||||
const vc = viewCameraFromCamera3d(orbitCamera(o), 2)!;
|
||||
expect(vc.kind).toBe("orthogonal");
|
||||
expect(vc.orthoHeight).toBeCloseTo(14.5, 9);
|
||||
const back = camera3dFromViewCamera(vc, 20)!;
|
||||
expect(back.perspective).toBe(false);
|
||||
expect(back.orthoHalfHeight).toBeCloseTo(7.25, 9);
|
||||
});
|
||||
|
||||
it("Blick von oben (Grundriss): Up liegt in der Grundrissebene", () => {
|
||||
const top: OrbitState = { yaw: Math.PI / 2, pitch: Math.PI / 2, dist: 30, target: [5, 0, 5], ortho: true, orthoHalfHeight: 12 };
|
||||
const vc = viewCameraFromCamera3d(orbitCamera(top), 1)!;
|
||||
expect(vc.direction[2]).toBeLessThan(-0.9999999);
|
||||
expect(Math.abs(vc.up[2])).toBeLessThan(2e-4);
|
||||
expect(Math.hypot(vc.up[0], vc.up[1])).toBeGreaterThan(0.99);
|
||||
});
|
||||
|
||||
it("entartete Kameras ergeben null statt NaN", () => {
|
||||
const cam: Camera3d = { eye: [1, 1, 1], target: [1, 1, 1], up: [0, 1, 0], perspective: true, fovY: 0.8, orthoHalfHeight: 5 };
|
||||
expect(viewCameraFromCamera3d(cam, 1)).toBeNull();
|
||||
expect(orbitFromCamera3d(cam)).toBeNull();
|
||||
const nan: ViewCamera = { kind: "perspective", position: [NaN, 0, 0], direction: [1, 0, 0], up: [0, 0, 1], fovDeg: 50, orthoHeight: 5, aspect: 1 };
|
||||
expect(camera3dFromViewCamera(nan, 10)).toBeNull();
|
||||
const zero: ViewCamera = { ...nan, position: [0, 0, 0], direction: [0, 0, 0] };
|
||||
expect(camera3dFromViewCamera(zero, 10)).toBeNull();
|
||||
});
|
||||
|
||||
it("lerpOrbit nimmt den kurzen Weg über ±π", () => {
|
||||
const a: OrbitState = { ...iso, yaw: Math.PI - 0.1 };
|
||||
const b: OrbitState = { ...iso, yaw: -Math.PI + 0.1 };
|
||||
const mid = lerpOrbit(a, b, 0.5);
|
||||
expect(Math.cos(mid.yaw)).toBeCloseTo(-1, 6);
|
||||
expect(lerpOrbit(a, b, 1).ortho).toBe(b.ortho);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Schnittebene", () => {
|
||||
it("vertikale Ebene: Punkt und Normale wandern nach world, schräge wird abgelehnt", () => {
|
||||
const s = { location: [2, 3, 1] as V3, direction: [0, 2, 0] as V3 };
|
||||
expect(isVerticalSection(s)).toBe(true);
|
||||
const w = sectionToWorld(s)!;
|
||||
close(w.point, [2, 1, 3]);
|
||||
close(w.normal, [0, 0, 1]);
|
||||
expect(isVerticalSection({ location: [0, 0, 0], direction: [0, 0, 1] })).toBe(false);
|
||||
expect(sectionToWorld({ location: [0, 0, 0], direction: [0, 0, 0] })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Registrierung", () => {
|
||||
function fakeViewport() {
|
||||
const state = { cam: orbitCamera({ yaw: 0.4, pitch: 0.3, dist: 15, target: [1, 2, 3], ortho: false, orthoHalfHeight: 8 }), written: null as Camera3d | null, section: undefined as unknown };
|
||||
const a: ViewportCameraApi = {
|
||||
read: () => ({ camera: state.cam, aspect: 2 }),
|
||||
write: (c) => {
|
||||
state.written = c;
|
||||
state.cam = c;
|
||||
return true;
|
||||
},
|
||||
snapshot: async () => new Uint8Array([0x89, 0x50]),
|
||||
section: (p) => {
|
||||
state.section = p;
|
||||
},
|
||||
fit: () => {},
|
||||
};
|
||||
return { state, a };
|
||||
}
|
||||
|
||||
it("ohne Viewport: null/false, kein Fehler", async () => {
|
||||
expect(viewportAvailable()).toBe(false);
|
||||
expect(getCamera()).toBeNull();
|
||||
expect(await captureSnapshot()).toBeNull();
|
||||
expect(setSection(null)).toBe(false);
|
||||
const vc: ViewCamera = { kind: "perspective", position: [0, 0, 0], direction: [1, 0, 0], up: [0, 0, 1], fovDeg: 50, orthoHeight: 5, aspect: 1 };
|
||||
expect(setCamera(vc)).toBe(false);
|
||||
});
|
||||
|
||||
it("getCamera → setCamera am angemeldeten Viewport lässt die Kamera unverändert", () => {
|
||||
const { state, a } = fakeViewport();
|
||||
registerViewportCamera(a);
|
||||
expect(viewportAvailable()).toBe(true);
|
||||
const before = state.cam;
|
||||
const vc = getCamera()!;
|
||||
expect(vc.aspect).toBe(2);
|
||||
expect(setCamera(vc)).toBe(true);
|
||||
close(state.written!.eye, before.eye);
|
||||
// Blickrichtung identisch (das Ziel darf auf der Achse wandern)
|
||||
const dir = (c: Camera3d) => {
|
||||
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);
|
||||
return d.map((x) => x / l);
|
||||
};
|
||||
close(dir(state.written!), dir(before));
|
||||
});
|
||||
|
||||
it("Schnitt setzen und aufheben, Snapshot durchreichen", async () => {
|
||||
const { state, a } = fakeViewport();
|
||||
registerViewportCamera(a);
|
||||
expect(setSection({ location: [0, 5, 0], direction: [0, -1, 0] })).toBe(true);
|
||||
expect(state.section).toMatchObject({ point: [0, 0, 5] });
|
||||
expect(setSection({ location: [0, 0, 0], direction: [0, 0, 1] })).toBe(false);
|
||||
expect(setSection(null)).toBe(true);
|
||||
expect(state.section).toBeNull();
|
||||
expect(Array.from((await captureSnapshot())!)).toEqual([0x89, 0x50]);
|
||||
});
|
||||
|
||||
it("Abmelden entfernt nur die eigene Registrierung", () => {
|
||||
const { a } = fakeViewport();
|
||||
const off = registerViewportCamera(a);
|
||||
const { a: b } = fakeViewport();
|
||||
registerViewportCamera(b);
|
||||
off(); // a ist nicht mehr angemeldet → b bleibt
|
||||
expect(viewportAvailable()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,287 @@
|
||||
// Kamera-Brücke des 3D-Viewports (BCF-Viewpoints, später Szenen/Animation): Lesen und Setzen der
|
||||
// Orbit-Kamera von aussen, Schnappschuss des 3D-Bildes, Live-Schnittebene von aussen.
|
||||
//
|
||||
// AUSSENSICHT = MODELL-Koordinaten: x/y Grundriss, z = Höhe, Meter, rechtshändig wie das IFC im
|
||||
// Export (`exportIfc.ts` schreibt Modell-(x, y, Höhe) unverändert; mit Standort-Bezug kommt nur
|
||||
// der LV95-Versatz hinzu, s. `panels/bcfView.ts`). INNENSICHT = render3d-world, Y-oben.
|
||||
//
|
||||
// ACHSABBILDUNG: Wände, Decken, Dächer, Zeichnungs-Spuren, Treppen und Stützen liegen im Viewport
|
||||
// als world = (x, Höhe, y) (`fitTargetDist` in `Wasm3DViewport`, `emitDrawingLineVerts`,
|
||||
// render3d `mesh.rs`: `start[1]` wird zu world-z). Die Abbildung ist ein Tausch von y und z und
|
||||
// damit ihre eigene Umkehrung. Geo-Rohdaten (Gelände, Punktwolken) negieren dagegen y
|
||||
// (world = (x, z, −y), `append_context_mesh`) — für die Kamera zählt die Abbildung der
|
||||
// Bauteile, weil nur diese im IFC-Export stehen. `cameraBridge.test.ts` belegt die Abbildung
|
||||
// gegen `projectToModel3d`.
|
||||
//
|
||||
// Der Viewport (`Wasm3DViewport`) meldet sich beim Einhängen an (`registerViewportCamera`) und
|
||||
// ab, wenn er verschwindet. Ohne Viewport (kein 3D geöffnet, nativer macOS-Pfad) liefern
|
||||
// `getCamera`/`captureSnapshot` null und `setCamera` false — kein Fehler.
|
||||
|
||||
import type { Camera3d } from "./useWasm3dRenderer";
|
||||
|
||||
export type V3 = [number, number, number];
|
||||
|
||||
/** Vertikaler Öffnungswinkel der freien Orbit-Kamera (wie render3d `default_fov`: 50°). */
|
||||
export const FOV_Y = (50 * Math.PI) / 180;
|
||||
/** Pitch-Klemme gegen den Gimbal-Flip. Knapp unter dem Pol (0,006°), damit senkrechte Blicke von
|
||||
* oben/unten (Grundriss-Viewpoints aus BCF) praktisch exakt bleiben; ein Flip tritt erst AM Pol auf,
|
||||
* `look_at` mit Up (0,1,0) bleibt hier stabil (Querprodukt ~1e-4, weit über der f32-Genauigkeit).
|
||||
* (Das native `render3d::math::orbit_eye` klemmt weiter bei 0,01 rad — eigener Pfad.) */
|
||||
export const PITCH_LIMIT = Math.PI / 2 - 1e-4;
|
||||
|
||||
/** Orbit-Zustand der Kamera: Kugelkoordinaten um ein Blickziel (world, Y-oben). */
|
||||
export interface OrbitState {
|
||||
/** Azimut um die Y-Achse (Radiant). */
|
||||
yaw: number;
|
||||
/** Erhebung über die XZ-Ebene (Radiant, geklemmt). */
|
||||
pitch: number;
|
||||
/** Abstand vom Ziel (Meter). */
|
||||
dist: number;
|
||||
/** Blickziel (world). */
|
||||
target: V3;
|
||||
/** Soll die freie Kamera orthografisch bleiben? (Presets ausser `perspective`.) */
|
||||
ortho: boolean;
|
||||
/** Orthografische Bild-Halbhöhe (Meter), unabhängig von `dist` geführt. */
|
||||
orthoHalfHeight: number;
|
||||
/** Vertikaler Öffnungswinkel (Radiant); fehlt = `FOV_Y`. Gesetzt von `setCamera` (BCF). */
|
||||
fovY?: number;
|
||||
}
|
||||
|
||||
/** Kamera in MODELL-Koordinaten (Meter, z oben) — die Sprache der Aussenwelt (BCF u. a.). */
|
||||
export interface ViewCamera {
|
||||
kind: "perspective" | "orthogonal";
|
||||
position: V3;
|
||||
/** Blickrichtung, normiert. */
|
||||
direction: V3;
|
||||
/** Up-Vektor, normiert und senkrecht zur Blickrichtung. */
|
||||
up: V3;
|
||||
/** Vertikaler Öffnungswinkel in Grad (perspektivisch). */
|
||||
fovDeg: number;
|
||||
/** Sichthöhe in Metern (orthografisch; volle Höhe, nicht halbe). */
|
||||
orthoHeight: number;
|
||||
/** Bildverhältnis Breite/Höhe des Viewports. */
|
||||
aspect: number;
|
||||
}
|
||||
|
||||
/** Live-Schnittebene in MODELL-Koordinaten; `direction` zeigt auf die weggeschnittene Seite. */
|
||||
export interface ViewSection {
|
||||
location: V3;
|
||||
direction: V3;
|
||||
}
|
||||
|
||||
// ── Achsabbildung ───────────────────────────────────────────────────────────
|
||||
|
||||
/** Modell (x, y, z=Höhe) → render3d-world (x, Höhe, y). */
|
||||
export const modelToWorld = (p: readonly number[]): V3 => [p[0], p[2], p[1]];
|
||||
/** render3d-world → Modell; derselbe Tausch, also die eigene Umkehrung. */
|
||||
export const worldToModel = (p: readonly number[]): V3 => [p[0], p[2], p[1]];
|
||||
|
||||
const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
|
||||
const dot = (a: V3, b: V3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
const len = (a: V3): number => Math.hypot(a[0], a[1], a[2]);
|
||||
const scale = (a: V3, s: number): V3 => [a[0] * s, a[1] * s, a[2] * s];
|
||||
function norm(a: V3): V3 | null {
|
||||
const l = len(a);
|
||||
return l > 1e-12 && Number.isFinite(l) ? scale(a, 1 / l) : null;
|
||||
}
|
||||
const finite3 = (a: readonly number[]): boolean => a.length >= 3 && a.slice(0, 3).every(Number.isFinite);
|
||||
|
||||
// ── Orbit ↔ Kamera ──────────────────────────────────────────────────────────
|
||||
|
||||
/** Fertige Kamera aus dem Orbit-Zustand (Konvention wie render3d::math::orbit_eye). */
|
||||
export function orbitCamera(o: OrbitState): Camera3d {
|
||||
const pitch = Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, o.pitch));
|
||||
const r = o.dist * Math.cos(pitch);
|
||||
return {
|
||||
eye: [
|
||||
o.target[0] + r * Math.cos(o.yaw),
|
||||
o.target[1] + o.dist * Math.sin(pitch),
|
||||
o.target[2] + r * Math.sin(o.yaw),
|
||||
],
|
||||
target: [o.target[0], o.target[1], o.target[2]],
|
||||
up: [0, 1, 0],
|
||||
perspective: !o.ortho,
|
||||
fovY: o.fovY ?? FOV_Y,
|
||||
orthoHalfHeight: o.orthoHalfHeight,
|
||||
};
|
||||
}
|
||||
|
||||
/** Orbit-Zustand aus einer fertigen Kamera (Umkehrung von `orbitCamera`; Roll geht verloren). */
|
||||
export function orbitFromCamera3d(cam: Camera3d): OrbitState | null {
|
||||
const d = norm(sub(cam.target, cam.eye));
|
||||
if (!d || !finite3(cam.eye) || !finite3(cam.target)) return null;
|
||||
const dist = len(sub(cam.target, cam.eye));
|
||||
// eye = target − dist·d, und orbit_eye: eye − target = dist·(cos p·cos yaw, sin p, cos p·sin yaw)
|
||||
const pitch = Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, Math.asin(Math.max(-1, Math.min(1, -d[1])))));
|
||||
const yaw = Math.hypot(d[0], d[2]) < 1e-9 ? Math.PI / 2 : Math.atan2(-d[2], -d[0]);
|
||||
return {
|
||||
yaw,
|
||||
pitch,
|
||||
dist,
|
||||
target: [cam.target[0], cam.target[1], cam.target[2]],
|
||||
ortho: !cam.perspective,
|
||||
orthoHalfHeight: cam.orthoHalfHeight,
|
||||
fovY: cam.fovY,
|
||||
};
|
||||
}
|
||||
|
||||
/** Zwischenstand für sanfte Kamerafahrten: Winkel auf kürzestem Weg, Rest linear. */
|
||||
export function lerpOrbit(a: OrbitState, b: OrbitState, t: number): OrbitState {
|
||||
const l = (x: number, y: number) => x + (y - x) * t;
|
||||
let dyaw = b.yaw - a.yaw;
|
||||
dyaw = ((((dyaw + Math.PI) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI)) - Math.PI;
|
||||
return {
|
||||
yaw: a.yaw + dyaw * t,
|
||||
pitch: l(a.pitch, b.pitch),
|
||||
dist: l(a.dist, b.dist),
|
||||
target: [l(a.target[0], b.target[0]), l(a.target[1], b.target[1]), l(a.target[2], b.target[2])],
|
||||
ortho: t < 1 ? a.ortho : b.ortho,
|
||||
orthoHalfHeight: l(a.orthoHalfHeight, b.orthoHalfHeight),
|
||||
fovY: l(a.fovY ?? FOV_Y, b.fovY ?? FOV_Y),
|
||||
};
|
||||
}
|
||||
|
||||
// ── Kamera ↔ Modell-Sicht ───────────────────────────────────────────────────
|
||||
|
||||
/** Kamera des Viewports (world, Y-oben) → Modell-Koordinaten (z oben). Null bei entarteter Kamera. */
|
||||
export function viewCameraFromCamera3d(cam: Camera3d, aspect: number): ViewCamera | null {
|
||||
const dirW = norm(sub(cam.target, cam.eye));
|
||||
if (!dirW || !finite3(cam.eye) || !finite3(cam.up)) return null;
|
||||
// Up orthogonalisieren: der Orbit liefert (0,1,0), das ist bei geneigtem Blick nicht senkrecht.
|
||||
const upRaw = sub(cam.up, scale(dirW, dot(cam.up, dirW)));
|
||||
const upW = norm(upRaw) ?? norm(sub([0, 1, 0], scale(dirW, dirW[1])));
|
||||
if (!upW) return null;
|
||||
return {
|
||||
kind: cam.perspective ? "perspective" : "orthogonal",
|
||||
position: worldToModel(cam.eye),
|
||||
direction: worldToModel(dirW),
|
||||
up: worldToModel(upW),
|
||||
fovDeg: (cam.fovY * 180) / Math.PI,
|
||||
orthoHeight: cam.orthoHalfHeight * 2,
|
||||
aspect: Number.isFinite(aspect) && aspect > 0 ? aspect : 1,
|
||||
};
|
||||
}
|
||||
|
||||
/** Modell-Kamera → Kamera des Viewports; `dist` legt das Blickziel auf der Blickachse fest. */
|
||||
export function camera3dFromViewCamera(vc: ViewCamera, dist: number): Camera3d | null {
|
||||
const d = norm(modelToWorld(vc.direction));
|
||||
if (!d || !finite3(vc.position) || !finite3(vc.up)) return null;
|
||||
const eye = modelToWorld(vc.position);
|
||||
const up = modelToWorld(vc.up);
|
||||
const dd = Number.isFinite(dist) && dist > 0 ? dist : 10;
|
||||
return {
|
||||
eye,
|
||||
target: [eye[0] + d[0] * dd, eye[1] + d[1] * dd, eye[2] + d[2] * dd],
|
||||
up,
|
||||
perspective: vc.kind === "perspective",
|
||||
fovY: Number.isFinite(vc.fovDeg) && vc.fovDeg > 1 && vc.fovDeg < 170 ? (vc.fovDeg * Math.PI) / 180 : FOV_Y,
|
||||
orthoHalfHeight: Number.isFinite(vc.orthoHeight) && vc.orthoHeight > 0 ? vc.orthoHeight / 2 : 5,
|
||||
};
|
||||
}
|
||||
|
||||
/** Schnittebene Modell → world (Punkt und Normale, die Normale zeigt auf die weggeschnittene Seite). */
|
||||
export function sectionToWorld(s: ViewSection): { point: V3; normal: V3 } | null {
|
||||
const n = norm(modelToWorld(s.direction));
|
||||
if (!n || !finite3(s.location)) return null;
|
||||
return { point: modelToWorld(s.location), normal: n };
|
||||
}
|
||||
|
||||
/** Vertikal genug für den Live-Schnitt (render3d unterstützt nur senkrechte Ebenen)? */
|
||||
export function isVerticalSection(s: ViewSection): boolean {
|
||||
const n = norm(s.direction);
|
||||
return !!n && Math.abs(n[2]) < 0.02;
|
||||
}
|
||||
|
||||
// ── Registrierung des Viewports ─────────────────────────────────────────────
|
||||
|
||||
export interface ViewportCameraApi {
|
||||
/** Aktuelle Kamera (world) und Bildverhältnis, oder null (Renderer nicht bereit). */
|
||||
read(): { camera: Camera3d; aspect: number } | null;
|
||||
/** Kamera setzen (world); mit `animate` als kurze Fahrt. */
|
||||
write(cam: Camera3d, animate: boolean): boolean;
|
||||
/** Aktuelles 3D-Bild als PNG, höchstens `maxEdge` Pixel auf der langen Seite. */
|
||||
snapshot(maxEdge: number): Promise<Uint8Array | null>;
|
||||
/** Live-Schnitt von aussen setzen (world) oder aufheben (null). */
|
||||
section(plane: { point: V3; normal: V3 } | null): void;
|
||||
/** Kamera auf Modell und sichtbare Punktwolken einpassen (aktuelles Preset). */
|
||||
fit(): void;
|
||||
}
|
||||
|
||||
let api: ViewportCameraApi | null = null;
|
||||
|
||||
/** Der Viewport meldet sich an (und mit null wieder ab). Liefert die Abmeldefunktion. */
|
||||
export function registerViewportCamera(next: ViewportCameraApi | null): () => void {
|
||||
api = next;
|
||||
exposeForDebug(next !== null);
|
||||
return () => {
|
||||
if (api === next) {
|
||||
api = null;
|
||||
exposeForDebug(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Prüfzugriff für Browser-Tests (Playwright): WebGPU-Frames sind in Containern oft leer, der
|
||||
* Kamerazustand lässt sich so trotzdem lesen und setzen. Nur Lesen/Setzen, keine Modelldaten. */
|
||||
function exposeForDebug(on: boolean): void {
|
||||
try {
|
||||
const g = globalThis as { __dossierCamera?: unknown };
|
||||
if (on) g.__dossierCamera = { getCamera, setCamera, captureSnapshot, setSection, viewportAvailable };
|
||||
else delete g.__dossierCamera;
|
||||
} catch {
|
||||
/* ohne globalThis-Zugriff kein Debug-Handle */
|
||||
}
|
||||
}
|
||||
|
||||
/** Ist ein 3D-Viewport mit Kamera-Zugriff angemeldet? */
|
||||
export const viewportAvailable = (): boolean => api !== null;
|
||||
|
||||
/** Aktuelle Kamera in Modell-Koordinaten, oder null ohne Viewport. */
|
||||
export function getCamera(): ViewCamera | null {
|
||||
const r = api?.read();
|
||||
return r ? viewCameraFromCamera3d(r.camera, r.aspect) : null;
|
||||
}
|
||||
|
||||
/** Kamera setzen. `false` ohne Viewport oder bei unbrauchbarer Kamera (NaN, Nullvektor). */
|
||||
export function setCamera(cam: ViewCamera, opts: { animate?: boolean } = {}): boolean {
|
||||
if (!api) return false;
|
||||
const cur = api.read();
|
||||
// Abstand des Blickziels: Blickachse am bisherigen Ziel (so bleibt Zoom/Pan natürlich), sonst bisheriger Abstand.
|
||||
let dist = 10;
|
||||
if (cur) {
|
||||
const d = norm(modelToWorld(cam.direction));
|
||||
const along = d ? dot(sub(cur.camera.target, modelToWorld(cam.position)), d) : 0;
|
||||
dist = along >= 1 ? along : len(sub(cur.camera.target, cur.camera.eye)) || 10;
|
||||
}
|
||||
const c3 = camera3dFromViewCamera(cam, dist);
|
||||
return c3 ? api.write(c3, opts.animate === true) : false;
|
||||
}
|
||||
|
||||
/** PNG des aktuellen 3D-Bildes, oder null (kein Viewport, leeres/nicht lesbares Bild). */
|
||||
export async function captureSnapshot(opts: { maxEdge?: number } = {}): Promise<Uint8Array | null> {
|
||||
if (!api) return null;
|
||||
try {
|
||||
return await api.snapshot(opts.maxEdge ?? 1024);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Live-Schnitt aus einer Ebene in Modell-Koordinaten setzen; null hebt auf. `false` = nicht darstellbar. */
|
||||
export function setSection(section: ViewSection | null): boolean {
|
||||
if (!api) return false;
|
||||
if (!section) {
|
||||
api.section(null);
|
||||
return true;
|
||||
}
|
||||
if (!isVerticalSection(section)) return false;
|
||||
const w = sectionToWorld(section);
|
||||
if (!w) return false;
|
||||
api.section(w);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Kamera auf Modell und sichtbare Punktwolken einpassen. */
|
||||
export function fitView(): void {
|
||||
api?.fit();
|
||||
}
|
||||
@@ -47,6 +47,12 @@ interface WebModelRendererLike {
|
||||
* "textured" faellt engine-seitig vorerst auf "shaded" zurueck). */
|
||||
set_render_style(style: string): void;
|
||||
set_view_preset(preset: string): void;
|
||||
/** Formatfüllendes Ziel + Abstand für Modell UND sichtbare Punktwolken: `[tx, ty, tz, dist]`
|
||||
* (world, Y-oben; `web::view_fit`). Optional — ältere WASM-Builds. */
|
||||
view_fit?(): Float32Array | number[];
|
||||
/** Aktuelle Rust-Kamera: `[eye(3), target(3), up(3), perspektivisch 1/0, fovY rad, orthoHalbhöhe]`
|
||||
* (`web::camera_state`). Optional — ältere WASM-Builds. */
|
||||
camera_state?(): Float32Array | number[];
|
||||
/** Boden-Referenzraster in der Welt-XZ-Ebene ein-/ausblenden (Rust-seitig,
|
||||
* `web::set_ground_grid`). `visible=false` zeichnet kein Raster; sonst ein
|
||||
* Quadrat der Kantenlaenge `extent_m` (zentriert um den Ursprung, XZ) auf
|
||||
@@ -463,6 +469,71 @@ export function useWasm3dRenderer(
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** Formatfüllendes Ziel + Abstand (Modell + sichtbare Punktwolken) aus Rust, oder null (alter Build). */
|
||||
const viewFit = useCallback((): { target: [number, number, number]; dist: number } | null => {
|
||||
const r = rendererRef.current;
|
||||
if (!r || typeof r.view_fit !== "function") return null;
|
||||
try {
|
||||
const v = Array.from(r.view_fit());
|
||||
if (v.length < 4 || !v.every(Number.isFinite)) return null;
|
||||
return { target: [v[0], v[1], v[2]], dist: v[3] };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** Die Kamera, die Rust gerade zeichnet (Preset oder zuletzt gesetzt), oder null (alter Build). */
|
||||
const readRustCamera = useCallback((): Camera3d | null => {
|
||||
const r = rendererRef.current;
|
||||
if (!r || typeof r.camera_state !== "function") return null;
|
||||
try {
|
||||
const v = Array.from(r.camera_state());
|
||||
if (v.length < 12 || !v.every(Number.isFinite)) return null;
|
||||
return {
|
||||
eye: [v[0], v[1], v[2]],
|
||||
target: [v[3], v[4], v[5]],
|
||||
up: [v[6], v[7], v[8]],
|
||||
perspective: v[9] > 0.5,
|
||||
fovY: v[10],
|
||||
orthoHalfHeight: v[11],
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Schnappschuss des 3D-Bildes als PNG. `draw` zeichnet den Frame (muss synchron rendern): ein
|
||||
* WebGPU-Canvas liefert seinen Inhalt nur im selben Task wie das Zeichnen, danach ist er leer.
|
||||
* Das Bild wird sofort auf ein 2D-Canvas kopiert (höchstens `maxEdge` px lange Seite), dann
|
||||
* kodiert. Null bei leerem/nicht lesbarem Bild (z. B. Software-WebGPU ohne Präsentation).
|
||||
*/
|
||||
const snapshotPng = useCallback(
|
||||
async (draw: () => void, maxEdge: number): Promise<Uint8Array | null> => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas || !rendererRef.current || canvas.width < 1 || canvas.height < 1) return null;
|
||||
draw();
|
||||
const k = Math.min(1, Math.max(16, maxEdge) / Math.max(canvas.width, canvas.height));
|
||||
const w = Math.max(1, Math.round(canvas.width * k));
|
||||
const h = Math.max(1, Math.round(canvas.height * k));
|
||||
const out = document.createElement("canvas");
|
||||
out.width = w;
|
||||
out.height = h;
|
||||
const ctx = out.getContext("2d", { willReadFrequently: true });
|
||||
if (!ctx) return null;
|
||||
ctx.drawImage(canvas, 0, 0, w, h);
|
||||
// Leer = alles transparent oder schwarz (Stichprobe über ein Raster).
|
||||
const sample = ctx.getImageData(0, 0, w, h).data;
|
||||
let seen = false;
|
||||
const step = Math.max(1, Math.floor(sample.length / 4 / 400)) * 4;
|
||||
for (let i = 0; i < sample.length && !seen; i += step) seen = sample[i + 3] > 0 && (sample[i] | sample[i + 1] | sample[i + 2]) !== 0;
|
||||
if (!seen) return null;
|
||||
const blob: Blob | null = await new Promise((res) => out.toBlob(res, "image/png"));
|
||||
return blob ? new Uint8Array(await blob.arrayBuffer()) : null;
|
||||
},
|
||||
[canvasRef],
|
||||
);
|
||||
|
||||
/**
|
||||
* Einen Frame zeichnen (Canvas-Größe + DPR abgleichen). `cam` = null lässt
|
||||
* die zuletzt in Rust gesetzte Kamera unverändert — Fall für `render(null)`
|
||||
@@ -514,6 +585,9 @@ export function useWasm3dRenderer(
|
||||
updateModel,
|
||||
setRenderStyle,
|
||||
applyViewPreset,
|
||||
viewFit,
|
||||
readRustCamera,
|
||||
snapshotPng,
|
||||
setGroundGrid,
|
||||
setSectionPlane,
|
||||
setHighlightLines,
|
||||
|
||||
Reference in new issue
Block a user