Merge [27] Punktwolken im 3D: Punkt-Pipeline in render3d (WebGPU/nativ), Import-Dialog, Panel, LV95-Einpassung; Cap-Shader-Fix (fwidth)
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
25 files changed
+2287
-22
No files matched your search
@@ -291,13 +291,49 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
|
||||
## Priorität 4 — später
|
||||
|
||||
Alle ○: [27] Punktwolken (Leser ✅ [B9], Anzeige/Modell offen) · [28] Phasen · [29] Bauteillisten (◐, Export vorhanden) · [43] Verknüpfte
|
||||
Alle ○: [27] Punktwolken (Leser ✅ [B9], Anzeige ◐ s. u., Modell offen) · [28] Phasen · [29] Bauteillisten (◐, Export vorhanden) · [43] Verknüpfte
|
||||
Modelle · [44] Aus Datei einfügen · [45] Favoriten · [68] Gelände mit Baugrube (= [T6]) · [71] U-Werte ·
|
||||
[72] Graue Energie KBOB · [73] eBKP-H · [74] SIA 500 · [75] Fluchtwege VKF · [83] Befehlspalette ·
|
||||
[84] Undo-Verlauf · [85] Makro-Rekorder · [86] Pipette · [87] Fang mit Begründung · [48] Web-Worker
|
||||
(◐, DXF-Parser, IFC-Import) · [52] Icons (◐, `CommandIcon.tsx`) · [56] Startparameter · [89] Git-freundliches
|
||||
Format · [90] Versionsvergleich · [91] Assistent · [92] Speckle.
|
||||
|
||||
- ◐ **[27] Punktwolken — Stufe 1: Anzeige im 3D.** (28.10.) render3d: eigene Punkt-Pipeline
|
||||
(`render3d/src/points.rs` GPU-frei: Puffer-Aufbau, Farbabbildung, WGSL; `gpu_points.rs`: Pipeline im
|
||||
selben Pass/Tiefen-/MSAA-Ziel wie das Modell). Ein Instanz-Quad je Punkt (6 Vertices aus
|
||||
`vertex_index`, Position 12 B + RGBA8 4 B je Punkt), feste Grösse in Bildschirm-Pixeln (ab 3 px rund),
|
||||
tiefengetestet gegen das Modell, vom Live-Schnitt gekappt. Puffer zu höchstens 4 Mio. Punkten (ein
|
||||
Draw je Puffer). Farbmodi rgb / Intensität (1.–99. Perzentil) / ASPRS-Klasse / Höhe (fehlt das Attribut →
|
||||
Höhe), auf der CPU berechnet; Moduswechsel schreibt nur den Farbpuffer. Eingabe `xyz` f32 relativ zum
|
||||
Ursprung + Modellversatz f64, Summe in f64 (LV95-fest). Achsen wie Gelände/Import (`MeshKind::Terrain`):
|
||||
Modell (x, y, z) → world (x, z, −y). Bindungen `web.rs` (`set_point_cloud`, `set_point_cloud_style`,
|
||||
`remove_point_cloud`, `clear_point_clouds`; Unsinn → 0 Punkte, kein Panic); derselbe `Renderer` im
|
||||
Browser (WebGPU) und nativ (`render_png --points wolke.txt [--point-size] [--point-color]`; das native Fenster `native.rs` hat
|
||||
denselben Renderer, bekommt aber noch keine Wolken geschoben).
|
||||
UI: Menü „Punktwolke importieren …" (Datei-Menü im Browser + natives App-Menü), Drag & Drop
|
||||
`.las/.laz/.e57/.ply/.xyz/.pts`, Dialog mit Voxel/Budget und Bericht (Anzahl, Ausdehnung, tiefste Ecke,
|
||||
EPSG, Attribute, Lage), Abschnitt „Punktwolken" im Gelände-Panel (Sichtbarkeit, Farbmodus, Punktgrösse,
|
||||
Entfernen). Lage (`state/pointCloudPlacement.ts`): mit `geoAnchor` und LV95 (EPSG 2056 oder ohne EPSG mit
|
||||
LV95-Koordinaten) lagerichtig, Höhe aus `geoAnchor.height` (sonst tiefster Punkt auf 0); sonst lokale
|
||||
Koordinaten wie in der Datei bzw. Landeskoordinaten mittig auf den Nullpunkt — jeweils mit Hinweis.
|
||||
Wolken leben im UI-Store `state/pointCloudStore.ts` (kein Projektfeld). Tests: 14 Rust (Puffer, Farben,
|
||||
WGSL) + 2 GPU-Render in eine Textur (Tiefe gegen Wand, Sichtbarkeit, Farbwechsel, feste Pixelgrösse;
|
||||
`cargo test --features render`, im Container Vulkan/lavapipe) + 12 vitest (Lage, Store, Abgleich).
|
||||
Nebenbei behoben: `CAP_WGSL` rief `fwidth` in nicht-uniformem Kontrollfluss → Chrome/Tint verwarf die
|
||||
Cap-Pipeline und damit JEDEN 3D-Frame (im Browser-Build gesehen); Ableitungen jetzt vor den Verzweigungen,
|
||||
Regressionstest `shaders::uniformity_tests`.
|
||||
- Geprüft: Linux-Container — cargo test (lavapipe), `render_png` mit Demo-Haus + synthetischer Wolke
|
||||
(110 000 Punkte; Tiefe, Klassen-/RGB-Farben sichtbar richtig), Browser-Build in Chromium (WebGPU über
|
||||
SwiftShader): Import-Dialog, Bericht, Panel, Moduswechsel ohne WebGPU-Validierungsfehler. NICHT
|
||||
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.
|
||||
- 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
|
||||
`render_png` hellt Punktfarben (wie alle Vertexfarben) auf.
|
||||
|
||||
## Übernahme aus BIMCraft [B]
|
||||
|
||||
Quelle: github.com/IPedrax/BIMCraft v0.9. Lizenz `MIT OR Apache-2.0` (`crates/rvt` nur Apache-2.0),
|
||||
|
||||
@@ -3,12 +3,18 @@
|
||||
// Dient Referenzbildern und der Prüfung des 3D ohne Nutzer-App.
|
||||
//
|
||||
// cargo run --release --features png --bin render_png -- modell.json aus.png [--view iso] [--style shaded] [--size 1200x800] [--target x,y,z] [--dist 12]
|
||||
// [--points wolke.txt] [--point-size 3] [--point-color rgb|intensity|class|height]
|
||||
//
|
||||
// `--points` ([27]): Textdatei mit einem Punkt je Zeile `x y z [r g b [intensitaet [klasse]]]` in
|
||||
// Modell-Metern (x = Ost, y = Nord, z = Hoehe) — dieselbe Punkt-Pipeline wie im Browser-Viewport.
|
||||
//
|
||||
// `modell.json` ist das Modell wie `set_model` es bekommt (`dossier-cli … model3d`).
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use render3d::gpu::{RenderStyle, Renderer};
|
||||
use render3d::gpu_points::PointStyle;
|
||||
use render3d::points::{PointCloudCpu, PointColorMode};
|
||||
use render3d::math::preset_camera;
|
||||
use render3d::types::{CameraPreset, MeshInput, SlabInput, WallInput};
|
||||
use serde::Deserialize;
|
||||
@@ -56,6 +62,46 @@ fn bounds(m: &ModelInput) -> Option<([f32; 3], [f32; 3])> {
|
||||
any.then_some((min, max))
|
||||
}
|
||||
|
||||
/// Liest `x y z [r g b [i [k]]]` je Zeile (Leerzeichen/Komma/Semikolon); unlesbare Zeilen fallen weg.
|
||||
/// Attribute nur, wenn JEDE Zeile sie hat.
|
||||
fn read_points_txt(path: &str) -> Option<PointCloudCpu> {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
let (mut xyz, mut rgb, mut int, mut cls) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
|
||||
let (mut all_rgb, mut all_int, mut all_cls) = (true, true, true);
|
||||
for line in text.lines() {
|
||||
let v: Vec<f64> = line
|
||||
.split(|c: char| c.is_whitespace() || c == ',' || c == ';')
|
||||
.filter(|s| !s.is_empty())
|
||||
.map_while(|s| s.parse::<f64>().ok())
|
||||
.collect();
|
||||
if v.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
xyz.extend_from_slice(&[v[0] as f32, v[1] as f32, v[2] as f32]);
|
||||
all_rgb &= v.len() >= 6;
|
||||
all_int &= v.len() >= 7;
|
||||
all_cls &= v.len() >= 8;
|
||||
if v.len() >= 6 {
|
||||
rgb.extend(v[3..6].iter().map(|c| c.clamp(0.0, 255.0) as u8));
|
||||
}
|
||||
if v.len() >= 7 {
|
||||
int.push(v[6].clamp(0.0, 65535.0) as u16);
|
||||
}
|
||||
if v.len() >= 8 {
|
||||
cls.push(v[7].clamp(0.0, 255.0) as u8);
|
||||
}
|
||||
}
|
||||
let pick = |ok: bool, len: usize, want: usize| ok && len == want;
|
||||
let n = xyz.len() / 3;
|
||||
PointCloudCpu::from_raw(
|
||||
&xyz,
|
||||
if pick(all_rgb, rgb.len(), n * 3) { &rgb } else { &[] },
|
||||
if pick(all_int, int.len(), n) { &int } else { &[] },
|
||||
if pick(all_cls, cls.len(), n) { &cls } else { &[] },
|
||||
[0.0; 3],
|
||||
)
|
||||
}
|
||||
|
||||
fn preset(name: &str) -> CameraPreset {
|
||||
match name {
|
||||
"front" => CameraPreset::Front,
|
||||
@@ -175,6 +221,18 @@ fn main() {
|
||||
let mut renderer = Renderer::new(&device, format);
|
||||
renderer.set_render_style(RenderStyle::from_str_or_shaded(&flag("--style", "shaded")));
|
||||
renderer.upload_model(&device, &model.walls, &model.slabs, &model.meshes);
|
||||
let points_path = flag("--points", "");
|
||||
if !points_path.is_empty() {
|
||||
let cloud = read_points_txt(&points_path);
|
||||
let n = cloud.as_ref().map_or(0, |c| c.len());
|
||||
let style = PointStyle {
|
||||
mode: PointColorMode::from_str_or_rgb(&flag("--point-color", "rgb")),
|
||||
size_px: flag("--point-size", "3").parse().unwrap_or(3.0),
|
||||
visible: true,
|
||||
};
|
||||
renderer.set_point_cloud(&device, 1, cloud, style);
|
||||
eprintln!("Punktwolke: {n} Punkte aus {points_path}");
|
||||
}
|
||||
|
||||
let (target, dist) = match bounds(&model) {
|
||||
Some((min, max)) => {
|
||||
|
||||
@@ -16,6 +16,8 @@ use crate::edges::{
|
||||
build_edge_adjacency, build_mesh_edges, build_silhouette_edges, EdgeAdj, EDGE_FLOATS_PER_VERTEX,
|
||||
};
|
||||
use crate::grid::{build_ground_grid, GRID_FLOATS_PER_VERTEX};
|
||||
use crate::gpu_points::{PointRenderer, PointStyle};
|
||||
use crate::points::PointCloudCpu;
|
||||
use crate::math::{view_projection, Mat4};
|
||||
use crate::mesh::{
|
||||
build_free_wall_end_caps, build_scene_mesh, build_scene_mesh_textured, build_terrain_mesh,
|
||||
@@ -388,6 +390,9 @@ pub struct Renderer {
|
||||
/// Farbformat des Render-Ziels (Surface), fuer die MSAA-Zwischentextur.
|
||||
color_format: wgpu::TextureFormat,
|
||||
globals: Globals,
|
||||
/// Punktwolken ([27], `gpu_points.rs`): eigene Instanz-Quad-Pipeline, tiefengetestet im
|
||||
/// selben Pass wie das Modell.
|
||||
points: PointRenderer,
|
||||
/// Loeschfarbe (Hintergrund). Default heller Grauton wie die three.js-Sicht.
|
||||
pub clear_color: wgpu::Color,
|
||||
}
|
||||
@@ -973,7 +978,11 @@ impl Renderer {
|
||||
}],
|
||||
});
|
||||
|
||||
let points =
|
||||
PointRenderer::new(device, &bind_group_layout, color_format, DEPTH_FORMAT, SAMPLE_COUNT);
|
||||
|
||||
Self {
|
||||
points,
|
||||
pipeline,
|
||||
hidden_face_pipeline,
|
||||
grid_pipeline,
|
||||
@@ -1022,6 +1031,43 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Setzt/ersetzt die Punktwolke `id` ([27]); `None` (unbrauchbare Eingabe) entfernt sie.
|
||||
pub fn set_point_cloud(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
id: u32,
|
||||
cloud: Option<PointCloudCpu>,
|
||||
style: PointStyle,
|
||||
) {
|
||||
self.points.set_cloud(device, id, cloud, style);
|
||||
}
|
||||
|
||||
/// Nur die Darstellung einer Punktwolke aendern (Farbmodus/Groesse/Sichtbarkeit).
|
||||
/// `false`, wenn die Wolke unbekannt ist.
|
||||
pub fn set_point_cloud_style(&mut self, queue: &wgpu::Queue, id: u32, style: PointStyle) -> bool {
|
||||
self.points.set_style(queue, id, style)
|
||||
}
|
||||
|
||||
/// Entfernt die Punktwolke `id` (unbekannt = nichts).
|
||||
pub fn remove_point_cloud(&mut self, id: u32) {
|
||||
self.points.remove(id);
|
||||
}
|
||||
|
||||
/// Entfernt alle Punktwolken.
|
||||
pub fn clear_point_clouds(&mut self) {
|
||||
self.points.clear();
|
||||
}
|
||||
|
||||
/// Punktzahl der Wolke `id` (0 = unbekannt).
|
||||
pub fn point_cloud_len(&self, id: u32) -> usize {
|
||||
self.points.point_count(id)
|
||||
}
|
||||
|
||||
/// World-Bounding-Box aller sichtbaren Punktwolken.
|
||||
pub fn point_cloud_bounds(&self) -> Option<([f32; 3], [f32; 3])> {
|
||||
self.points.bounds()
|
||||
}
|
||||
|
||||
/// Erzeugt das Mesh aus geflachten Waenden und laedt die Puffer hoch.
|
||||
pub fn upload_walls(&mut self, device: &wgpu::Device, walls: &[WallInput]) {
|
||||
self.upload_mesh(device, build_walls_mesh(walls), build_walls_mesh_textured(walls));
|
||||
@@ -1713,6 +1759,9 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
// Punktwolken: Viewport/Punktgroesse in die Uniforms (feste Pixelgroesse).
|
||||
self.points.prepare(queue, (w, h));
|
||||
|
||||
let depth_view = &self.depth.as_ref().unwrap().view;
|
||||
let msaa_view = &self.msaa.as_ref().unwrap().view;
|
||||
|
||||
@@ -1890,6 +1939,10 @@ impl Renderer {
|
||||
pass.draw(0..dl.vertex_count, 0..1);
|
||||
}
|
||||
|
||||
// 2d) Punktwolken ([27]): Instanz-Quads, tiefengetestet gegen Modell/Unterlage —
|
||||
// stilunabhaengig (gemessene Bestandsdaten gehoeren in jede Darstellung).
|
||||
self.points.draw(&mut pass, &self.bind_group);
|
||||
|
||||
// 3) Bodengitter NACH dem Modell zeichnen (gemeinsamer Tiefenpuffer ->
|
||||
// das Modell verdeckt das Gitter korrekt). Unabhaengig vom Stil, nur
|
||||
// wenn sichtbar + vorhanden.
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
// GPU-Teil der Punktwolken ([27]): eigene Pipeline neben Mesh/Grid im selben Render-Pass,
|
||||
// dasselbe Tiefen-/MSAA-/Farbziel (sonst inkompatibler Pass) und dieselbe `Globals`-Bind-Group.
|
||||
// Läuft unverändert auf WebGPU (Browser) und nativ (Metal/Vulkan) — `Renderer` ruft nur
|
||||
// `prepare` vor und `draw` im Pass auf.
|
||||
//
|
||||
// Je Punkt ein Instanz-Eintrag (Position 12 B + RGBA8 4 B); das Quad entsteht im Vertex-Shader
|
||||
// aus `vertex_index` (6 Vertices je Instanz, kein Index-/Geometriepuffer je Punkt). Grosse Wolken
|
||||
// liegen in Puffern zu höchstens `MAX_POINTS_PER_CHUNK` Punkten (je ein Draw-Call).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::points::{chunk_ranges, clamp_point_size, PointCloudCpu, PointColorMode, POINT_WGSL};
|
||||
|
||||
/// Uniform je Wolke, 1:1 zu `PointParams` im WGSL.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
struct PointParams {
|
||||
/// x = Grösse px, y/z = Viewport px, w = runde Punkte (1/0).
|
||||
params: [f32; 4],
|
||||
}
|
||||
|
||||
struct PointChunk {
|
||||
positions: wgpu::Buffer,
|
||||
colors: wgpu::Buffer,
|
||||
start: usize,
|
||||
count: u32,
|
||||
}
|
||||
|
||||
struct PointCloudGpu {
|
||||
cpu: PointCloudCpu,
|
||||
chunks: Vec<PointChunk>,
|
||||
uniform: wgpu::Buffer,
|
||||
bind_group: wgpu::BindGroup,
|
||||
mode: PointColorMode,
|
||||
size_px: f32,
|
||||
visible: bool,
|
||||
}
|
||||
|
||||
/// Darstellungs-Einstellungen einer Wolke.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PointStyle {
|
||||
pub mode: PointColorMode,
|
||||
pub size_px: f32,
|
||||
pub visible: bool,
|
||||
}
|
||||
|
||||
/// Alle Punktwolken des Renderers + ihre Pipeline.
|
||||
pub struct PointRenderer {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
params_layout: wgpu::BindGroupLayout,
|
||||
clouds: BTreeMap<u32, PointCloudGpu>,
|
||||
}
|
||||
|
||||
impl PointRenderer {
|
||||
/// `globals_layout` = group(0) der übrigen Pipelines; Ziel-Format, Tiefenformat und Samples
|
||||
/// müssen mit dem Haupt-Pass übereinstimmen.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
globals_layout: &wgpu::BindGroupLayout,
|
||||
color_format: wgpu::TextureFormat,
|
||||
depth_format: wgpu::TextureFormat,
|
||||
sample_count: u32,
|
||||
) -> Self {
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("points.wgsl"),
|
||||
source: wgpu::ShaderSource::Wgsl(POINT_WGSL.into()),
|
||||
});
|
||||
let params_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("points.params.layout"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: wgpu::BufferSize::new(std::mem::size_of::<PointParams>() as u64),
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("points.layout"),
|
||||
bind_group_layouts: &[Some(globals_layout), Some(¶ms_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
let pos_layout = wgpu::VertexBufferLayout {
|
||||
array_stride: 12,
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &wgpu::vertex_attr_array![0 => Float32x3],
|
||||
};
|
||||
let col_layout = wgpu::VertexBufferLayout {
|
||||
array_stride: 4,
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &wgpu::vertex_attr_array![1 => Unorm8x4],
|
||||
};
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("points.pipeline"),
|
||||
layout: Some(&layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &module,
|
||||
entry_point: Some("vs_main"),
|
||||
buffers: &[pos_layout, col_layout],
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &module,
|
||||
entry_point: Some("fs_main"),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: color_format,
|
||||
blend: Some(wgpu::BlendState::REPLACE),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
// Bildschirm-Quads, immer zur Kamera gewandt — kein Culling nötig.
|
||||
cull_mode: None,
|
||||
..Default::default()
|
||||
},
|
||||
// Tiefentest gegen das Modell (Wände verdecken Punkte dahinter) und Tiefe schreiben
|
||||
// (Punkte verdecken Gitter/Kanten dahinter).
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: depth_format,
|
||||
depth_write_enabled: Some(true),
|
||||
depth_compare: Some(wgpu::CompareFunction::Less),
|
||||
stencil: wgpu::StencilState::default(),
|
||||
bias: wgpu::DepthBiasState::default(),
|
||||
}),
|
||||
multisample: wgpu::MultisampleState {
|
||||
count: sample_count,
|
||||
mask: !0,
|
||||
alpha_to_coverage_enabled: false,
|
||||
},
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
Self {
|
||||
pipeline,
|
||||
params_layout,
|
||||
clouds: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Setzt/ersetzt die Wolke `id`. `None`-Daten (unbrauchbare Eingabe) entfernen sie.
|
||||
pub fn set_cloud(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
id: u32,
|
||||
cpu: Option<PointCloudCpu>,
|
||||
style: PointStyle,
|
||||
) {
|
||||
let Some(cpu) = cpu else {
|
||||
self.clouds.remove(&id);
|
||||
return;
|
||||
};
|
||||
let size_px = clamp_point_size(style.size_px);
|
||||
let colors = cpu.colors(style.mode);
|
||||
let chunks = chunk_ranges(cpu.len())
|
||||
.into_iter()
|
||||
.map(|(start, count)| PointChunk {
|
||||
positions: device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("points.positions"),
|
||||
contents: bytemuck::cast_slice(&cpu.positions[start * 3..(start + count) * 3]),
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
}),
|
||||
colors: device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("points.colors"),
|
||||
contents: bytemuck::cast_slice(&colors[start..start + count]),
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
}),
|
||||
start,
|
||||
count: count as u32,
|
||||
})
|
||||
.collect();
|
||||
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("points.params"),
|
||||
size: std::mem::size_of::<PointParams>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("points.params.bind"),
|
||||
layout: &self.params_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: uniform.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
self.clouds.insert(
|
||||
id,
|
||||
PointCloudGpu {
|
||||
cpu,
|
||||
chunks,
|
||||
uniform,
|
||||
bind_group,
|
||||
mode: style.mode,
|
||||
size_px,
|
||||
visible: style.visible,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Ändert nur die Darstellung (Farbmodus, Grösse, Sichtbarkeit). Bei neuem Farbmodus wird nur
|
||||
/// der Farbpuffer überschrieben (Positionen bleiben). `false`, wenn `id` unbekannt ist.
|
||||
pub fn set_style(&mut self, queue: &wgpu::Queue, id: u32, style: PointStyle) -> bool {
|
||||
let Some(c) = self.clouds.get_mut(&id) else {
|
||||
return false;
|
||||
};
|
||||
c.size_px = clamp_point_size(style.size_px);
|
||||
c.visible = style.visible;
|
||||
if c.cpu.effective_mode(style.mode) != c.cpu.effective_mode(c.mode) {
|
||||
let colors = c.cpu.colors(style.mode);
|
||||
for ch in &c.chunks {
|
||||
let end = ch.start + ch.count as usize;
|
||||
queue.write_buffer(&ch.colors, 0, bytemuck::cast_slice(&colors[ch.start..end]));
|
||||
}
|
||||
}
|
||||
c.mode = style.mode;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, id: u32) {
|
||||
self.clouds.remove(&id);
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.clouds.clear();
|
||||
}
|
||||
|
||||
/// Anzahl Punkte der Wolke `id` (0 = unbekannt), für Bindungen/Tests.
|
||||
pub fn point_count(&self, id: u32) -> usize {
|
||||
self.clouds.get(&id).map_or(0, |c| c.cpu.len())
|
||||
}
|
||||
|
||||
/// World-Bounding-Box aller sichtbaren Wolken (für das Einpassen der Kamera).
|
||||
pub fn bounds(&self) -> Option<([f32; 3], [f32; 3])> {
|
||||
let mut min = [f32::INFINITY; 3];
|
||||
let mut max = [f32::NEG_INFINITY; 3];
|
||||
for c in self.clouds.values().filter(|c| c.visible) {
|
||||
for p in c.cpu.positions.chunks_exact(3) {
|
||||
for i in 0..3 {
|
||||
min[i] = min[i].min(p[i]);
|
||||
max[i] = max[i].max(p[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
min[0].is_finite().then_some((min, max))
|
||||
}
|
||||
|
||||
/// Je Frame vor dem Pass: Viewport/Grösse in die Uniforms schreiben.
|
||||
pub fn prepare(&self, queue: &wgpu::Queue, viewport: (u32, u32)) {
|
||||
for c in self.clouds.values().filter(|c| c.visible) {
|
||||
let round = if c.size_px >= 3.0 { 1.0 } else { 0.0 };
|
||||
let p = PointParams {
|
||||
params: [c.size_px, viewport.0.max(1) as f32, viewport.1.max(1) as f32, round],
|
||||
};
|
||||
queue.write_buffer(&c.uniform, 0, bytemuck::bytes_of(&p));
|
||||
}
|
||||
}
|
||||
|
||||
/// Im Haupt-Pass: alle sichtbaren Wolken zeichnen (ein Draw-Call je Puffer).
|
||||
pub fn draw<'a>(&'a self, pass: &mut wgpu::RenderPass<'a>, globals: &'a wgpu::BindGroup) {
|
||||
let mut bound = false;
|
||||
for c in self.clouds.values().filter(|c| c.visible) {
|
||||
if !bound {
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, globals, &[]);
|
||||
bound = true;
|
||||
}
|
||||
pass.set_bind_group(1, &c.bind_group, &[]);
|
||||
for ch in &c.chunks {
|
||||
pass.set_vertex_buffer(0, ch.positions.slice(..));
|
||||
pass.set_vertex_buffer(1, ch.colors.slice(..));
|
||||
pass.draw(0..6, 0..ch.count);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Headless-Render in eine Textur (Vulkan/lavapipe im Linux-Container, Metal auf macOS). Ohne
|
||||
// GPU-Adapter wird der Test übersprungen (Meldung auf stderr) statt rot.
|
||||
#[cfg(test)]
|
||||
mod gpu_tests {
|
||||
use super::PointStyle;
|
||||
use crate::gpu::Renderer;
|
||||
use crate::points::{PointCloudCpu, PointColorMode};
|
||||
use crate::types::{Camera, WallInput};
|
||||
|
||||
const W: u32 = 64;
|
||||
const H: u32 = 64;
|
||||
const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
|
||||
|
||||
fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
|
||||
let instance = wgpu::Instance::default();
|
||||
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::default(),
|
||||
force_fallback_adapter: false,
|
||||
compatible_surface: None,
|
||||
}))
|
||||
.ok()?;
|
||||
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
label: Some("points.test"),
|
||||
required_features: wgpu::Features::empty(),
|
||||
required_limits: wgpu::Limits::default(),
|
||||
experimental_features: wgpu::ExperimentalFeatures::disabled(),
|
||||
memory_hints: wgpu::MemoryHints::Performance,
|
||||
trace: wgpu::Trace::Off,
|
||||
}))
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Rendert und liefert RGBA8 aller Pixel.
|
||||
fn render(device: &wgpu::Device, queue: &wgpu::Queue, r: &mut Renderer, cam: &Camera) -> Vec<u8> {
|
||||
let tex = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: FORMAT,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
r.render(device, queue, &view, cam, (W, H));
|
||||
let padded = (W * 4).div_ceil(256) * 256;
|
||||
let buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: (padded * H) as u64,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
||||
enc.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &tex,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buf,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(padded),
|
||||
rows_per_image: Some(H),
|
||||
},
|
||||
},
|
||||
wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
|
||||
);
|
||||
queue.submit([enc.finish()]);
|
||||
let slice = buf.slice(..);
|
||||
slice.map_async(wgpu::MapMode::Read, |r| r.expect("Readback"));
|
||||
let _ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
let data = slice.get_mapped_range();
|
||||
let mut out = Vec::with_capacity((W * H * 4) as usize);
|
||||
for y in 0..H as usize {
|
||||
out.extend_from_slice(&data[y * padded as usize..y * padded as usize + W as usize * 4]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn pixel(img: &[u8], x: u32, y: u32) -> [u8; 3] {
|
||||
let i = ((y * W + x) * 4) as usize;
|
||||
[img[i], img[i + 1], img[i + 2]]
|
||||
}
|
||||
|
||||
fn is_red(c: [u8; 3]) -> bool {
|
||||
c[0] > 200 && c[1] < 40 && c[2] < 40
|
||||
}
|
||||
|
||||
/// Senkrechte Punkt-Fläche 2 × 2 m (Modell x −1..1, Höhe 0..2) auf Modell-y = `y`, rot.
|
||||
fn red_sheet(y: f64) -> PointCloudCpu {
|
||||
let mut xyz = Vec::new();
|
||||
let mut rgb = Vec::new();
|
||||
for i in 0..=40 {
|
||||
for k in 0..=40 {
|
||||
xyz.extend_from_slice(&[-1.0 + i as f32 * 0.05, 0.0, k as f32 * 0.05]);
|
||||
rgb.extend_from_slice(&[255, 0, 0]);
|
||||
}
|
||||
}
|
||||
PointCloudCpu::from_raw(&xyz, &rgb, &[], &[], [0.0, y, 0.0]).unwrap()
|
||||
}
|
||||
|
||||
fn camera() -> Camera {
|
||||
// Blick von world +z (Modell-Süd, Nord-Achse negiert) auf den Nullpunkt, 1 m hoch.
|
||||
Camera { eye: [0.0, 1.0, 10.0], target: [0.0, 1.0, 0.0], ..Camera::default() }
|
||||
}
|
||||
|
||||
const STYLE: PointStyle = PointStyle { mode: PointColorMode::Rgb, size_px: 4.0, visible: true };
|
||||
|
||||
#[test]
|
||||
fn points_render_visible_and_respect_depth_of_model() {
|
||||
let Some((device, queue)) = device() else {
|
||||
eprintln!("kein GPU-Adapter — Punkt-Render-Test übersprungen");
|
||||
return;
|
||||
};
|
||||
let mut r = Renderer::new(&device, FORMAT);
|
||||
let wall: WallInput =
|
||||
serde_json::from_str(r#"{"start":[-3,0],"end":[3,0],"thickness":0.2,"height":3}"#).unwrap();
|
||||
r.upload_model(&device, &[wall], &[], &[]);
|
||||
let cam = camera();
|
||||
|
||||
// Wolke VOR der Wand (Modell-y = −3 → world z = +3): rot in der Bildmitte.
|
||||
r.set_point_cloud(&device, 1, Some(red_sheet(-3.0)), STYLE);
|
||||
assert_eq!(r.point_cloud_len(1), 41 * 41);
|
||||
let img = render(&device, &queue, &mut r, &cam);
|
||||
let c = pixel(&img, W / 2, H / 2);
|
||||
assert!(is_red(c), "Mitte sollte rot sein: {c:?}");
|
||||
|
||||
// Wolke HINTER der Wand (Modell-y = +5 → world z = −5): Wand verdeckt sie.
|
||||
r.set_point_cloud(&device, 1, Some(red_sheet(5.0)), STYLE);
|
||||
let img = render(&device, &queue, &mut r, &cam);
|
||||
let c = pixel(&img, W / 2, H / 2);
|
||||
assert!(!is_red(c), "Wand muss Punkte verdecken: {c:?}");
|
||||
|
||||
// Unsichtbar geschaltet: auch vor der Wand nichts Rotes.
|
||||
r.set_point_cloud(&device, 1, Some(red_sheet(-3.0)), STYLE);
|
||||
assert!(r.set_point_cloud_style(&queue, 1, PointStyle { visible: false, ..STYLE }));
|
||||
let img = render(&device, &queue, &mut r, &cam);
|
||||
assert!(!is_red(pixel(&img, W / 2, H / 2)), "unsichtbare Wolke gezeichnet");
|
||||
|
||||
// Farbmodus Höhe: nur der Farbpuffer wird ersetzt → Mitte nicht mehr Rot, nicht Hintergrund.
|
||||
let height = PointStyle { mode: PointColorMode::Height, ..STYLE };
|
||||
assert!(r.set_point_cloud_style(&queue, 1, height));
|
||||
let img = render(&device, &queue, &mut r, &cam);
|
||||
let c = pixel(&img, W / 2, H / 2);
|
||||
assert!(!is_red(c) && c != pixel(&img, 0, 0), "Höhenfarbe erwartet: {c:?}");
|
||||
|
||||
// Entfernen + unbekannte id.
|
||||
r.remove_point_cloud(1);
|
||||
assert_eq!(r.point_cloud_len(1), 0);
|
||||
assert!(!r.set_point_cloud_style(&queue, 1, STYLE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_pixel_size_independent_of_distance() {
|
||||
let Some((device, queue)) = device() else {
|
||||
eprintln!("kein GPU-Adapter — Punkt-Render-Test übersprungen");
|
||||
return;
|
||||
};
|
||||
let mut r = Renderer::new(&device, FORMAT);
|
||||
let one = PointCloudCpu::from_raw(&[0.0, 0.0, 1.0], &[0, 0, 255], &[], &[], [0.0; 3]).unwrap();
|
||||
let count_blue =
|
||||
|img: &[u8]| img.chunks_exact(4).filter(|p| p[2] > 200 && p[0] < 60 && p[1] < 60).count();
|
||||
r.set_point_cloud(&device, 7, Some(one), PointStyle { size_px: 8.0, ..STYLE });
|
||||
let near = render(&device, &queue, &mut r, &Camera { eye: [0.0, 1.0, 5.0], ..camera() });
|
||||
let far = render(&device, &queue, &mut r, &Camera { eye: [0.0, 1.0, 50.0], ..camera() });
|
||||
let (a, b) = (count_blue(&near), count_blue(&far));
|
||||
// Runder Punkt Ø 8 px ≈ 50 px Fläche, unabhängig vom Abstand.
|
||||
assert!(a > 25 && a < 80, "nah: {a}");
|
||||
assert!((a as i32 - b as i32).abs() <= 6, "nah {a} vs fern {b}");
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ pub mod edges;
|
||||
pub mod grid;
|
||||
pub mod math;
|
||||
pub mod mesh;
|
||||
pub mod points;
|
||||
pub(crate) mod openings;
|
||||
pub mod roof_cut;
|
||||
pub mod section;
|
||||
@@ -28,6 +29,8 @@ pub mod types;
|
||||
|
||||
#[cfg(feature = "render")]
|
||||
pub mod gpu;
|
||||
#[cfg(feature = "render")]
|
||||
pub mod gpu_points;
|
||||
|
||||
// Browser-Bindings (wasm32 + WebGPU), nur mit Feature "web". Setzt "render" voraus
|
||||
// (dieselbe GPU-Schicht wie das native Fenster), fuegt aber KEINE winit-Abhaengigkeit
|
||||
|
||||
@@ -0,0 +1,528 @@
|
||||
// Punktwolken für den 3D-Viewport ([27], Stufe 1): GPU-freie Schicht (Puffer-Aufbau, Farbabbildung,
|
||||
// WGSL-Quelle). Die Pipeline selbst liegt in `gpu_points.rs` (Feature "render") und läuft so
|
||||
// unverändert im Browser (WebGPU, `web.rs`) wie nativ (Metal/Vulkan: `render_png`, `native.rs`).
|
||||
//
|
||||
// Eingabe: wie der Leser sie liefert (`src/io/pointCloud.ts`, `fileio/pointcloud*.rs`) — `xyz` als
|
||||
// f32 RELATIV zu einem Ursprung, dazu der Modellversatz dieses Ursprungs als f64 (Modell-Meter,
|
||||
// x = Ost, y = Nord, z = Höhe). Die Summe wird hier in f64 gebildet und erst danach auf f32
|
||||
// gerundet: LV95-Koordinaten (2,6 Mio. m) kippen so nie in f32 (dort nur ~0,25 m Auflösung).
|
||||
//
|
||||
// Achsen: wie die übrigen ECHTEN Geo-Rohdaten (Gelände/Import, `mesh::append_context_mesh`,
|
||||
// `MeshKind::Terrain`): Modell (x, y, z) → world (x, z, −y). So liegt eine Punktwolke deckungsgleich
|
||||
// auf einem swissALTI3D-Gelände desselben Standort-Bezugs.
|
||||
//
|
||||
// Darstellung: ein Instanz-Quad je Punkt (6 Vertices aus `vertex_index`, keine Geometrie je Punkt
|
||||
// im Puffer), feste Grösse in Bildschirm-Pixeln, tiefengetestet gegen das Modell. Farben werden auf
|
||||
// der CPU berechnet (eine Quelle der Wahrheit, testbar) und als eigener RGBA8-Puffer neben den
|
||||
// Positionen gehalten — ein Wechsel des Farbmodus lädt nur diesen kleinen Puffer neu.
|
||||
|
||||
/// Farbmodus einer Punktwolke.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PointColorMode {
|
||||
/// Gemessene Farbe (RGB aus der Datei); ohne Farbe → Höhe.
|
||||
Rgb,
|
||||
/// Intensität als Grauwert (robuster Bereich 1.–99. Perzentil); ohne Intensität → Höhe.
|
||||
Intensity,
|
||||
/// ASPRS-Klassifikation (Boden, Vegetation, Gebäude …); ohne Klassen → Höhe.
|
||||
Class,
|
||||
/// Höhe als Farbverlauf (blau → grün → gelb → rot).
|
||||
Height,
|
||||
}
|
||||
|
||||
impl PointColorMode {
|
||||
/// Parst den API-String ("rgb" | "intensity" | "class" | "height"); Unbekanntes → `Rgb`.
|
||||
pub fn from_str_or_rgb(s: &str) -> Self {
|
||||
match s {
|
||||
"intensity" => PointColorMode::Intensity,
|
||||
"class" => PointColorMode::Class,
|
||||
"height" => PointColorMode::Height,
|
||||
_ => PointColorMode::Rgb,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Höchstzahl Punkte je GPU-Puffer. 4 Mio. × 12 Byte = 48 MB — sicher unter dem WebGPU-Standard-
|
||||
/// limit `maxBufferSize` (256 MB) und `maxStorageBufferBindingSize`; grössere Wolken werden auf
|
||||
/// mehrere Puffer (je ein Draw-Call) verteilt, nie ein Draw je Punkt.
|
||||
pub const MAX_POINTS_PER_CHUNK: usize = 4_000_000;
|
||||
|
||||
/// Grenzen der Punktgrösse in Bildschirm-Pixeln (Klemmung aller Eingaben).
|
||||
pub const MIN_POINT_SIZE_PX: f32 = 1.0;
|
||||
pub const MAX_POINT_SIZE_PX: f32 = 32.0;
|
||||
|
||||
/// Klemmt eine Punktgrösse (NaN → 2 px).
|
||||
pub fn clamp_point_size(px: f32) -> f32 {
|
||||
if px.is_finite() {
|
||||
px.clamp(MIN_POINT_SIZE_PX, MAX_POINT_SIZE_PX)
|
||||
} else {
|
||||
2.0
|
||||
}
|
||||
}
|
||||
|
||||
/// CPU-Seite einer Punktwolke: world-Positionen (f32, bereits mit Versatz) und die optionalen
|
||||
/// Attribute, gefiltert auf gültige Punkte (NaN/∞ fliegen raus, Attribute bleiben ausgerichtet).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PointCloudCpu {
|
||||
/// world x, y (= Höhe), z (= −Nord) je Punkt.
|
||||
pub positions: Vec<f32>,
|
||||
pub rgb: Option<Vec<u8>>,
|
||||
pub intensity: Option<Vec<u16>>,
|
||||
pub classification: Option<Vec<u8>>,
|
||||
/// Höhenbereich (world y) aller Punkte, für den Höhen-Farbverlauf.
|
||||
pub height_range: [f32; 2],
|
||||
}
|
||||
|
||||
impl PointCloudCpu {
|
||||
/// Baut die world-Positionen aus `xyz` (relativ, f32) + `offset` (Modell-Meter des Ursprungs, f64).
|
||||
/// Attribute mit falscher Länge werden ignoriert (nicht abgeschnitten — lieber keine Farbe als
|
||||
/// verrutschte). `None` bei unbrauchbarer Eingabe (kein vollständiger Punkt, Versatz nicht endlich).
|
||||
pub fn from_raw(
|
||||
xyz: &[f32],
|
||||
rgb: &[u8],
|
||||
intensity: &[u16],
|
||||
classification: &[u8],
|
||||
offset: [f64; 3],
|
||||
) -> Option<Self> {
|
||||
if !offset.iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let n = xyz.len() / 3;
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
let rgb = (rgb.len() == n * 3).then_some(rgb);
|
||||
let intensity = (intensity.len() == n).then_some(intensity);
|
||||
let classification = (classification.len() == n).then_some(classification);
|
||||
|
||||
let mut positions = Vec::with_capacity(n * 3);
|
||||
let mut out_rgb = rgb.map(|_| Vec::with_capacity(n * 3));
|
||||
let mut out_int = intensity.map(|_| Vec::with_capacity(n));
|
||||
let mut out_cls = classification.map(|_| Vec::with_capacity(n));
|
||||
let mut hmin = f32::INFINITY;
|
||||
let mut hmax = f32::NEG_INFINITY;
|
||||
for i in 0..n {
|
||||
let (x, y, z) = (xyz[i * 3], xyz[i * 3 + 1], xyz[i * 3 + 2]);
|
||||
if !(x.is_finite() && y.is_finite() && z.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
// In f64 addieren, erst dann runden (LV95-fest).
|
||||
let wx = (offset[0] + x as f64) as f32;
|
||||
let wy = (offset[2] + z as f64) as f32;
|
||||
let wz = -((offset[1] + y as f64) as f32);
|
||||
if !(wx.is_finite() && wy.is_finite() && wz.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
positions.extend_from_slice(&[wx, wy, wz]);
|
||||
hmin = hmin.min(wy);
|
||||
hmax = hmax.max(wy);
|
||||
if let (Some(o), Some(src)) = (out_rgb.as_mut(), rgb) {
|
||||
o.extend_from_slice(&src[i * 3..i * 3 + 3]);
|
||||
}
|
||||
if let (Some(o), Some(src)) = (out_int.as_mut(), intensity) {
|
||||
o.push(src[i]);
|
||||
}
|
||||
if let (Some(o), Some(src)) = (out_cls.as_mut(), classification) {
|
||||
o.push(src[i]);
|
||||
}
|
||||
}
|
||||
if positions.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
positions,
|
||||
rgb: out_rgb,
|
||||
intensity: out_int,
|
||||
classification: out_cls,
|
||||
height_range: [hmin, hmax],
|
||||
})
|
||||
}
|
||||
|
||||
/// Anzahl Punkte.
|
||||
pub fn len(&self) -> usize {
|
||||
self.positions.len() / 3
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.positions.is_empty()
|
||||
}
|
||||
|
||||
/// Welcher Modus tatsächlich gezeichnet wird (fehlt das Attribut, fällt er auf Höhe zurück).
|
||||
pub fn effective_mode(&self, mode: PointColorMode) -> PointColorMode {
|
||||
let has = match mode {
|
||||
PointColorMode::Rgb => self.rgb.is_some(),
|
||||
PointColorMode::Intensity => self.intensity.is_some(),
|
||||
PointColorMode::Class => self.classification.is_some(),
|
||||
PointColorMode::Height => true,
|
||||
};
|
||||
if has {
|
||||
mode
|
||||
} else {
|
||||
PointColorMode::Height
|
||||
}
|
||||
}
|
||||
|
||||
/// RGBA8 je Punkt (Alpha 255) für den Farbmodus — der Inhalt des Farb-Vertex-Puffers.
|
||||
pub fn colors(&self, mode: PointColorMode) -> Vec<[u8; 4]> {
|
||||
let n = self.len();
|
||||
match self.effective_mode(mode) {
|
||||
PointColorMode::Rgb => {
|
||||
let rgb = self.rgb.as_deref().unwrap_or(&[]);
|
||||
(0..n).map(|i| [rgb[i * 3], rgb[i * 3 + 1], rgb[i * 3 + 2], 255]).collect()
|
||||
}
|
||||
PointColorMode::Intensity => {
|
||||
let it = self.intensity.as_deref().unwrap_or(&[]);
|
||||
let [lo, hi] = intensity_window(it);
|
||||
let span = (hi as f32 - lo as f32).max(1.0);
|
||||
it.iter()
|
||||
.map(|&v| {
|
||||
let t = ((v as f32 - lo as f32) / span).clamp(0.0, 1.0);
|
||||
// Leicht angehoben (nie ganz schwarz) — dunkle Punkte bleiben auf dem
|
||||
// dunklen Hintergrund/Modell sichtbar.
|
||||
let g = (30.0 + t * 225.0).round() as u8;
|
||||
[g, g, g, 255]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
PointColorMode::Class => {
|
||||
let cls = self.classification.as_deref().unwrap_or(&[]);
|
||||
cls.iter()
|
||||
.map(|&c| {
|
||||
let [r, g, b] = class_color(c);
|
||||
[r, g, b, 255]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
PointColorMode::Height => {
|
||||
let [lo, hi] = self.height_range;
|
||||
let span = (hi - lo).max(1e-6);
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let t = (self.positions[i * 3 + 1] - lo) / span;
|
||||
let [r, g, b] = height_ramp(t);
|
||||
[r, g, b, 255]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Robuster Intensitätsbereich: 1.–99. Perzentil (Histogramm über u16), damit einzelne Ausreisser
|
||||
/// (Reflektoren) nicht die ganze Wolke grau in grau machen. Leer → [0, 65535].
|
||||
pub fn intensity_window(values: &[u16]) -> [u16; 2] {
|
||||
if values.is_empty() {
|
||||
return [0, u16::MAX];
|
||||
}
|
||||
let mut hist = vec![0u32; 65_536];
|
||||
for &v in values {
|
||||
hist[v as usize] += 1;
|
||||
}
|
||||
let n = values.len() as u64;
|
||||
let lo_rank = n / 100;
|
||||
let hi_rank = n - 1 - n / 100;
|
||||
let mut acc: u64 = 0;
|
||||
let mut lo = None;
|
||||
let mut hi = u16::MAX;
|
||||
for (v, &c) in hist.iter().enumerate() {
|
||||
if c == 0 {
|
||||
continue;
|
||||
}
|
||||
let next = acc + c as u64;
|
||||
if lo.is_none() && next > lo_rank {
|
||||
lo = Some(v as u16);
|
||||
}
|
||||
if next > hi_rank {
|
||||
hi = v as u16;
|
||||
break;
|
||||
}
|
||||
acc = next;
|
||||
}
|
||||
let lo = lo.unwrap_or(0);
|
||||
[lo, hi.max(lo)]
|
||||
}
|
||||
|
||||
/// Farben der ASPRS-Standardklassen (LAS 1.4, Tabelle 17). Unbekannte/benutzerdefinierte Klassen →
|
||||
/// neutrales Grau.
|
||||
pub fn class_color(c: u8) -> [u8; 3] {
|
||||
match c {
|
||||
0 | 1 => [170, 170, 170], // nie klassifiziert / nicht zugeordnet
|
||||
2 => [166, 120, 72], // Boden
|
||||
3 => [170, 210, 120], // niedrige Vegetation
|
||||
4 => [96, 170, 72], // mittlere Vegetation
|
||||
5 => [40, 120, 50], // hohe Vegetation
|
||||
6 => [214, 90, 70], // Gebäude
|
||||
7 => [255, 0, 255], // Rauschen (tief)
|
||||
8 => [240, 220, 60], // Modell-Schlüsselpunkt (LAS 1.0–1.3)
|
||||
9 => [70, 130, 220], // Wasser
|
||||
10 => [120, 80, 160], // Schiene
|
||||
11 => [90, 90, 90], // Strassenoberfläche
|
||||
13 => [250, 160, 40], // Leitungsschutz
|
||||
14 => [250, 200, 40], // Leitung
|
||||
15 => [200, 60, 160], // Mast
|
||||
17 => [130, 110, 100], // Brücke
|
||||
18 => [255, 80, 255], // Rauschen (hoch)
|
||||
_ => [140, 140, 140],
|
||||
}
|
||||
}
|
||||
|
||||
/// Höhen-Farbverlauf (t ∈ [0,1], ausserhalb geklemmt): blau → cyan → grün → gelb → rot.
|
||||
pub fn height_ramp(t: f32) -> [u8; 3] {
|
||||
const STOPS: [[f32; 3]; 5] = [
|
||||
[40.0, 70.0, 200.0],
|
||||
[40.0, 180.0, 220.0],
|
||||
[80.0, 190.0, 80.0],
|
||||
[240.0, 220.0, 60.0],
|
||||
[220.0, 60.0, 40.0],
|
||||
];
|
||||
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let f = t * (STOPS.len() - 1) as f32;
|
||||
let i = (f.floor() as usize).min(STOPS.len() - 2);
|
||||
let u = f - i as f32;
|
||||
let a = STOPS[i];
|
||||
let b = STOPS[i + 1];
|
||||
[
|
||||
(a[0] + (b[0] - a[0]) * u).round() as u8,
|
||||
(a[1] + (b[1] - a[1]) * u).round() as u8,
|
||||
(a[2] + (b[2] - a[2]) * u).round() as u8,
|
||||
]
|
||||
}
|
||||
|
||||
/// Teilt `n` Punkte in Puffer-Bereiche von höchstens `MAX_POINTS_PER_CHUNK` (Start, Anzahl).
|
||||
pub fn chunk_ranges(n: usize) -> Vec<(usize, usize)> {
|
||||
let mut out = Vec::new();
|
||||
let mut s = 0;
|
||||
while s < n {
|
||||
let c = (n - s).min(MAX_POINTS_PER_CHUNK);
|
||||
out.push((s, c));
|
||||
s += c;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Vertex-Shader-Ecken des Instanz-Quads (zwei Dreiecke, CCW), in Einheiten der halben Punktgrösse.
|
||||
pub const QUAD_CORNERS: [[f32; 2]; 6] = [
|
||||
[-1.0, -1.0],
|
||||
[1.0, -1.0],
|
||||
[1.0, 1.0],
|
||||
[-1.0, -1.0],
|
||||
[1.0, 1.0],
|
||||
[-1.0, 1.0],
|
||||
];
|
||||
|
||||
/// WGSL der Punkt-Pipeline. group(0) = dasselbe `Globals` wie Mesh/Grid (View-Projektion,
|
||||
/// Live-Schnitt); group(1) = Punkt-Parameter (`params.x` = Grösse px, `yz` = Viewport px,
|
||||
/// `w` > 0.5 = runde Punkte). Instanz-Attribute: Position (world) + RGBA8-Farbe.
|
||||
pub const POINT_WGSL: &str = r#"
|
||||
struct Globals {
|
||||
view_proj : mat4x4<f32>,
|
||||
light_dir : vec4<f32>,
|
||||
sky_color : vec4<f32>,
|
||||
ground_color : vec4<f32>,
|
||||
sun_color : vec4<f32>,
|
||||
mode : vec4<f32>,
|
||||
section_plane : vec4<f32>,
|
||||
};
|
||||
@group(0) @binding(0) var<uniform> globals : Globals;
|
||||
|
||||
struct PointParams {
|
||||
params : vec4<f32>,
|
||||
};
|
||||
@group(1) @binding(0) var<uniform> point : PointParams;
|
||||
|
||||
struct VsIn {
|
||||
@builtin(vertex_index) vi : u32,
|
||||
@location(0) position : vec3<f32>,
|
||||
@location(1) color : vec4<f32>,
|
||||
};
|
||||
|
||||
struct VsOut {
|
||||
@builtin(position) clip_pos : vec4<f32>,
|
||||
@location(0) color : vec3<f32>,
|
||||
@location(1) world_pos : vec3<f32>,
|
||||
@location(2) corner : vec2<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(in : VsIn) -> VsOut {
|
||||
var corners = array<vec2<f32>, 6>(
|
||||
vec2<f32>(-1.0, -1.0), vec2<f32>(1.0, -1.0), vec2<f32>(1.0, 1.0),
|
||||
vec2<f32>(-1.0, -1.0), vec2<f32>(1.0, 1.0), vec2<f32>(-1.0, 1.0),
|
||||
);
|
||||
let c = corners[in.vi % 6u];
|
||||
var clip = globals.view_proj * vec4<f32>(in.position, 1.0);
|
||||
// Feste Bildschirmgrösse: Versatz in NDC (2 / Viewport je Pixel), mit w multipliziert, damit
|
||||
// die Perspektiv-Division ihn nicht wieder verkleinert.
|
||||
let vp = max(point.params.yz, vec2<f32>(1.0, 1.0));
|
||||
let half_px = 0.5 * point.params.x;
|
||||
clip = vec4<f32>(clip.xy + c * half_px * 2.0 / vp * clip.w, clip.zw);
|
||||
var out : VsOut;
|
||||
out.clip_pos = clip;
|
||||
out.color = in.color.rgb;
|
||||
out.world_pos = in.position;
|
||||
out.corner = c;
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
|
||||
// Live-Schnitt wie Mesh/Grid: was hinter der Ebene liegt, fällt weg.
|
||||
if (globals.mode.y > 0.5) {
|
||||
if (dot(in.world_pos, globals.section_plane.xyz) + globals.section_plane.w > 0.0) {
|
||||
discard;
|
||||
}
|
||||
}
|
||||
if (point.params.w > 0.5 && dot(in.corner, in.corner) > 1.0) {
|
||||
discard;
|
||||
}
|
||||
return vec4<f32>(in.color, 1.0);
|
||||
}
|
||||
"#;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn color_mode_parses_api_strings() {
|
||||
assert_eq!(PointColorMode::from_str_or_rgb("rgb"), PointColorMode::Rgb);
|
||||
assert_eq!(PointColorMode::from_str_or_rgb("intensity"), PointColorMode::Intensity);
|
||||
assert_eq!(PointColorMode::from_str_or_rgb("class"), PointColorMode::Class);
|
||||
assert_eq!(PointColorMode::from_str_or_rgb("height"), PointColorMode::Height);
|
||||
assert_eq!(PointColorMode::from_str_or_rgb("quatsch"), PointColorMode::Rgb);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positions_map_model_to_world_like_terrain() {
|
||||
// Modell (x, y, z) → world (x, z, −y), Versatz addiert.
|
||||
let c = PointCloudCpu::from_raw(&[1.0, 2.0, 3.0], &[], &[], &[], [10.0, 20.0, 30.0]).unwrap();
|
||||
assert_eq!(c.positions, vec![11.0, 33.0, -22.0]);
|
||||
assert_eq!(c.height_range, [33.0, 33.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lv95_offset_is_added_in_f64() {
|
||||
// Ursprung in LV95 (2,6 Mio. m), Projekt-Nullpunkt 2 600 000 / 1 200 000: Versatz klein,
|
||||
// aber die Summe Ursprung + Punkt darf nicht über f32 laufen. Hier: Versatz −0,5 (aus
|
||||
// f64-Differenz), Punkt 0,123 → 0,623 mm-genau.
|
||||
let off = [2_600_123.0_f64 - 2_600_123.5, 1_200_000.0 - 1_200_000.25, 0.0];
|
||||
let c = PointCloudCpu::from_raw(&[0.123, 0.001, 0.0], &[], &[], &[], off).unwrap();
|
||||
assert!((c.positions[0] - (-0.377)).abs() < 1e-6);
|
||||
assert!((c.positions[2] - 0.249).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_points_are_dropped_and_attributes_stay_aligned() {
|
||||
let xyz = [0.0, 0.0, 0.0, f32::NAN, 0.0, 0.0, 1.0, 1.0, 1.0];
|
||||
let rgb = [1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
let it = [10u16, 20, 30];
|
||||
let cls = [2u8, 6, 9];
|
||||
let c = PointCloudCpu::from_raw(&xyz, &rgb, &it, &cls, [0.0; 3]).unwrap();
|
||||
assert_eq!(c.len(), 2);
|
||||
assert_eq!(c.rgb.as_deref(), Some(&[1, 2, 3, 7, 8, 9][..]));
|
||||
assert_eq!(c.intensity.as_deref(), Some(&[10, 30][..]));
|
||||
assert_eq!(c.classification.as_deref(), Some(&[2, 9][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_input_yields_none_not_panic() {
|
||||
assert!(PointCloudCpu::from_raw(&[], &[], &[], &[], [0.0; 3]).is_none());
|
||||
assert!(PointCloudCpu::from_raw(&[1.0, 2.0], &[], &[], &[], [0.0; 3]).is_none());
|
||||
assert!(PointCloudCpu::from_raw(&[1.0, 2.0, 3.0], &[], &[], &[], [f64::NAN, 0.0, 0.0]).is_none());
|
||||
assert!(PointCloudCpu::from_raw(&[f32::INFINITY, 0.0, 0.0], &[], &[], &[], [0.0; 3]).is_none());
|
||||
// Überzählige xyz-Werte (kein ganzer Punkt) werden ignoriert.
|
||||
let c = PointCloudCpu::from_raw(&[1.0, 2.0, 3.0, 4.0], &[], &[], &[], [0.0; 3]).unwrap();
|
||||
assert_eq!(c.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_with_wrong_length_are_ignored() {
|
||||
let c = PointCloudCpu::from_raw(&[0.0; 6], &[1, 2, 3], &[5], &[1, 2, 3], [0.0; 3]).unwrap();
|
||||
assert!(c.rgb.is_none() && c.intensity.is_none() && c.classification.is_none());
|
||||
// Ohne Attribut fällt jeder Modus auf Höhe zurück.
|
||||
assert_eq!(c.effective_mode(PointColorMode::Rgb), PointColorMode::Height);
|
||||
assert_eq!(c.effective_mode(PointColorMode::Class), PointColorMode::Height);
|
||||
assert_eq!(c.colors(PointColorMode::Intensity).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgb_colors_pass_through() {
|
||||
let c = PointCloudCpu::from_raw(&[0.0; 6], &[255, 0, 0, 0, 128, 255], &[], &[], [0.0; 3]).unwrap();
|
||||
assert_eq!(c.colors(PointColorMode::Rgb), vec![[255, 0, 0, 255], [0, 128, 255, 255]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn class_colors_follow_asprs() {
|
||||
let c = PointCloudCpu::from_raw(&[0.0; 9], &[], &[], &[2, 6, 200], [0.0; 3]).unwrap();
|
||||
let col = c.colors(PointColorMode::Class);
|
||||
assert_eq!(col[0], [166, 120, 72, 255]); // Boden
|
||||
assert_eq!(col[1], [214, 90, 70, 255]); // Gebäude
|
||||
assert_eq!(col[2], [140, 140, 140, 255]); // unbekannt
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn height_ramp_runs_from_blue_to_red_by_world_height() {
|
||||
// Modell-z 0 / 5 / 10 → world y; tiefster Punkt blau, höchster rot.
|
||||
let xyz = [0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 0.0, 0.0, 10.0];
|
||||
let c = PointCloudCpu::from_raw(&xyz, &[], &[], &[], [0.0; 3]).unwrap();
|
||||
let col = c.colors(PointColorMode::Height);
|
||||
assert_eq!(&col[0][..3], &height_ramp(0.0)[..]);
|
||||
assert_eq!(&col[2][..3], &height_ramp(1.0)[..]);
|
||||
assert_eq!(height_ramp(0.0), [40, 70, 200]);
|
||||
assert_eq!(height_ramp(1.0), [220, 60, 40]);
|
||||
assert_eq!(height_ramp(f32::NAN), [40, 70, 200]);
|
||||
assert_eq!(height_ramp(7.0), [220, 60, 40]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intensity_uses_robust_window() {
|
||||
// 1000 Punkte 100..1099 plus ein Ausreisser 65535: der Ausreisser setzt den Bereich NICHT.
|
||||
let mut it: Vec<u16> = (100..1100).collect();
|
||||
it.push(65_535);
|
||||
let w = intensity_window(&it);
|
||||
assert!(w[0] >= 100 && w[0] < 120, "{w:?}");
|
||||
assert!(w[1] > 1000 && w[1] < 1100, "{w:?}");
|
||||
let xyz = vec![0.0f32; it.len() * 3];
|
||||
let c = PointCloudCpu::from_raw(&xyz, &[], &it, &[], [0.0; 3]).unwrap();
|
||||
let col = c.colors(PointColorMode::Intensity);
|
||||
assert_eq!(col[0], [30, 30, 30, 255]); // dunkelstes Ende (nie schwarz)
|
||||
assert_eq!(col[col.len() - 1], [255, 255, 255, 255]); // Ausreisser geklemmt
|
||||
assert_eq!(intensity_window(&[]), [0, 65_535]);
|
||||
assert_eq!(intensity_window(&[7, 7, 7]), [7, 7]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunking_splits_large_clouds() {
|
||||
assert!(chunk_ranges(0).is_empty());
|
||||
assert_eq!(chunk_ranges(10), vec![(0, 10)]);
|
||||
let r = chunk_ranges(MAX_POINTS_PER_CHUNK * 2 + 5);
|
||||
assert_eq!(r.len(), 3);
|
||||
assert_eq!(r[2], (MAX_POINTS_PER_CHUNK * 2, 5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_size_is_clamped() {
|
||||
assert_eq!(clamp_point_size(0.0), MIN_POINT_SIZE_PX);
|
||||
assert_eq!(clamp_point_size(100.0), MAX_POINT_SIZE_PX);
|
||||
assert_eq!(clamp_point_size(f32::NAN), 2.0);
|
||||
assert_eq!(clamp_point_size(3.5), 3.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_wgsl_validates() {
|
||||
use naga::valid::{Capabilities, ValidationFlags, Validator};
|
||||
let module = naga::front::wgsl::parse_str(POINT_WGSL)
|
||||
.unwrap_or_else(|e| panic!("points: WGSL-Parse-Fehler: {e:?}"));
|
||||
Validator::new(ValidationFlags::all(), Capabilities::all())
|
||||
.validate(&module)
|
||||
.unwrap_or_else(|e| panic!("points: WGSL-Validierung fehlgeschlagen: {e:?}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quad_corners_match_shader() {
|
||||
// Die Ecken im WGSL müssen dieselben sein wie die Rust-Konstante (zwei CCW-Dreiecke).
|
||||
for c in QUAD_CORNERS {
|
||||
let s = format!("vec2<f32>({:.1}, {:.1})", c[0], c[1]);
|
||||
assert!(POINT_WGSL.contains(&s), "fehlt im Shader: {s}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -414,11 +414,13 @@ fn vs_main(in : VsIn) -> VsOut {
|
||||
}
|
||||
|
||||
// Ein AA-gekantetes Linienband entlang der Koordinate `s` (in Einheiten von
|
||||
// `spacing`): 1 auf der Linie, 0 dazwischen. `fwidth` glaettet blickwinkelrichtig.
|
||||
fn line_band(s : f32, half_s : f32) -> f32 {
|
||||
// `spacing`): 1 auf der Linie, 0 dazwischen. `fw` = fwidth von `s` glaettet blickwinkelrichtig;
|
||||
// vom Aufrufer VOR jeder Verzweigung berechnet (Ableitungen nur in uniformem Kontrollfluss —
|
||||
// Chrome/Tint verwirft den Shader sonst, und mit ihm den ganzen 3D-Pass).
|
||||
fn line_band(s : f32, half_s : f32, fw : f32) -> f32 {
|
||||
let frac = fract(s);
|
||||
let dist = min(frac, 1.0 - frac);
|
||||
let aa = max(fwidth(s), 1e-5);
|
||||
let aa = max(fw, 1e-5);
|
||||
return 1.0 - smoothstep(half_s, half_s + aa, dist);
|
||||
}
|
||||
|
||||
@@ -431,15 +433,6 @@ fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
|
||||
let angle = in.hatch.y;
|
||||
let scale = max(in.hatch.z, 0.05);
|
||||
|
||||
// none (0): leere (weisse) Schnittflaeche — wie „keine Schraffur" im 2D.
|
||||
if (pattern == 0) {
|
||||
return vec4<f32>(paper, 1.0);
|
||||
}
|
||||
// solid (1): Vollton (Poché) — z. B. Beton.
|
||||
if (pattern == 1) {
|
||||
return vec4<f32>(ink, 1.0);
|
||||
}
|
||||
|
||||
// Muster-Koordinaten: (u,v) in Modell-Metern, um `angle` gedreht. Konvention
|
||||
// wie die 2D-Schraffur (`hatchPreview.parallelLines`): `angle == 0` ergibt
|
||||
// HORIZONTALE Linien (Phasen-Achse = dv), `+angle` dreht die Schar gegen den
|
||||
@@ -461,28 +454,42 @@ fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
|
||||
let half = max(in.hatch.w * 0.005, 0.0001);
|
||||
let half_s = half / spacing;
|
||||
|
||||
// Alle Ableitungen hier, vor jeder Verzweigung nach `pattern` (uniformer Kontrollfluss).
|
||||
let su = du / spacing;
|
||||
let sv = dv / spacing;
|
||||
let fw_u = fwidth(su);
|
||||
let fw_v = fwidth(sv);
|
||||
let cell = spacing * 2.0;
|
||||
let tri = abs(fract(du / cell) - 0.5) * 2.0; // 0..1 Dreieckswelle (Daemmung)
|
||||
let fb = fract(dv / cell);
|
||||
let fw_zig = fwidth(fb) + fwidth(tri);
|
||||
|
||||
// none (0): leere (weisse) Schnittflaeche — wie „keine Schraffur" im 2D.
|
||||
if (pattern == 0) {
|
||||
return vec4<f32>(paper, 1.0);
|
||||
}
|
||||
// solid (1): Vollton (Poché) — z. B. Beton.
|
||||
if (pattern == 1) {
|
||||
return vec4<f32>(ink, 1.0);
|
||||
}
|
||||
|
||||
var line = 0.0;
|
||||
if (pattern == 2) {
|
||||
// diagonal: EINE Linienschar quer zur Phasen-Achse (dv). angle==0 →
|
||||
// horizontal; `hatch.angle` (z. B. 45° bei Backstein) dreht sie wie im 2D.
|
||||
line = line_band(dv / spacing, half_s);
|
||||
line = line_band(sv, half_s, fw_v);
|
||||
} else if (pattern == 3) {
|
||||
// crosshatch: zwei Scharen ueber Kreuz (Phase dv + Phase du = +90°). Bei
|
||||
// angle==0 horizontal+vertikal, bei 45° (Beton) das gekippte Kreuz — wie 2D.
|
||||
line = max(
|
||||
line_band(dv / spacing, half_s),
|
||||
line_band(du / spacing, half_s)
|
||||
line_band(sv, half_s, fw_v),
|
||||
line_band(su, half_s, fw_u)
|
||||
);
|
||||
} else {
|
||||
// insulation (4, Daemmung): Zickzack. Die Quer-Position (dv) folgt einer
|
||||
// Dreieckswelle entlang der Lauf-Achse (du) — ein durchgehender Zickzack.
|
||||
let cell = spacing * 2.0;
|
||||
let a = du / cell;
|
||||
let b = dv / cell;
|
||||
let tri = abs(fract(a) - 0.5) * 2.0; // 0..1 Dreieckswelle
|
||||
let fb = fract(b);
|
||||
let d = min(abs(fb - tri), min(abs(fb - tri + 1.0), abs(fb - tri - 1.0)));
|
||||
let aa = max(fwidth(fb) + fwidth(tri), 1e-5);
|
||||
let aa = max(fw_zig, 1e-5);
|
||||
let hw = half / cell;
|
||||
line = 1.0 - smoothstep(hw, hw + aa, d);
|
||||
}
|
||||
@@ -491,3 +498,20 @@ fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
|
||||
return vec4<f32>(color, 1.0);
|
||||
}
|
||||
"#;
|
||||
|
||||
#[cfg(test)]
|
||||
mod uniformity_tests {
|
||||
/// Chrome/Tint verwirft Ableitungen (`fwidth`) in nicht-uniformem Kontrollfluss — und mit dem
|
||||
/// Cap-Shader die ganze Cap-Pipeline, deren Fehler den GESAMTEN 3D-Pass ungültig macht (28.10.
|
||||
/// im Browser-Build gesehen). naga prüft das nicht; darum hier: jedes `fwidth` im Cap-Shader
|
||||
/// steht vor der ersten Verzweigung nach `pattern` und nicht in einer Hilfsfunktion.
|
||||
#[test]
|
||||
fn cap_shader_derivatives_before_pattern_branches() {
|
||||
let src = super::CAP_WGSL;
|
||||
let fs = src.find("fn fs_main").expect("fs_main");
|
||||
let first_branch = src[fs..].find("if (pattern").expect("Verzweigung") + fs;
|
||||
for (i, _) in src.match_indices("fwidth(") {
|
||||
assert!(i > fs && i < first_branch, "fwidth an Stelle {i} ausserhalb des uniformen Teils");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -584,6 +584,58 @@ impl WebModelRenderer {
|
||||
self.renderer.clear_aerial();
|
||||
}
|
||||
|
||||
/// Setzt/ersetzt die Punktwolke `id` ([27], `points.rs`/`gpu_points.rs`). `xyz` = f32 je Punkt
|
||||
/// RELATIV zum Ursprung, `ox/oy/oz` = Modell-Meter dieses Ursprungs (f64; x = Ost, y = Nord,
|
||||
/// z = Hoehe) — die Summe bildet Rust in f64. `rgb`/`intensity`/`classification` leer = fehlt
|
||||
/// (falsche Laenge = ignoriert). `color_mode` ∈ rgb|intensity|class|height, `point_size` in
|
||||
/// Bildschirm-Pixeln. Gibt die Anzahl gezeichneter Punkte zurueck; 0 = Eingabe unbrauchbar
|
||||
/// (die Wolke `id` ist dann entfernt) — nie ein Panic.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn set_point_cloud(
|
||||
&mut self,
|
||||
id: u32,
|
||||
xyz: &[f32],
|
||||
rgb: &[u8],
|
||||
intensity: &[u16],
|
||||
classification: &[u8],
|
||||
ox: f64,
|
||||
oy: f64,
|
||||
oz: f64,
|
||||
color_mode: &str,
|
||||
point_size: f32,
|
||||
visible: bool,
|
||||
) -> u32 {
|
||||
let cpu = crate::points::PointCloudCpu::from_raw(xyz, rgb, intensity, classification, [ox, oy, oz]);
|
||||
let style = crate::gpu_points::PointStyle {
|
||||
mode: crate::points::PointColorMode::from_str_or_rgb(color_mode),
|
||||
size_px: point_size,
|
||||
visible,
|
||||
};
|
||||
self.renderer.set_point_cloud(&self.device, id, cpu, style);
|
||||
self.renderer.point_cloud_len(id) as u32
|
||||
}
|
||||
|
||||
/// Nur Darstellung der Punktwolke `id` aendern (ohne Neu-Hochladen der Positionen).
|
||||
/// `false`, wenn die Wolke unbekannt ist (dann `set_point_cloud` aufrufen).
|
||||
pub fn set_point_cloud_style(&mut self, id: u32, color_mode: &str, point_size: f32, visible: bool) -> bool {
|
||||
let style = crate::gpu_points::PointStyle {
|
||||
mode: crate::points::PointColorMode::from_str_or_rgb(color_mode),
|
||||
size_px: point_size,
|
||||
visible,
|
||||
};
|
||||
self.renderer.set_point_cloud_style(&self.queue, id, style)
|
||||
}
|
||||
|
||||
/// Entfernt die Punktwolke `id` (unbekannt = nichts).
|
||||
pub fn remove_point_cloud(&mut self, id: u32) {
|
||||
self.renderer.remove_point_cloud(id);
|
||||
}
|
||||
|
||||
/// Entfernt alle Punktwolken.
|
||||
pub fn clear_point_clouds(&mut self) {
|
||||
self.renderer.clear_point_clouds();
|
||||
}
|
||||
|
||||
/// Surface an eine neue Pixelgroesse anpassen (DPR beachtet der Aufrufer).
|
||||
pub fn resize(&mut self, width: u32, height: u32) {
|
||||
let (w, h) = (width.max(1), height.max(1));
|
||||
|
||||
@@ -90,6 +90,9 @@ import {
|
||||
import { HatchSwatch } from "./ui/hatchPreview";
|
||||
import { TopBar, ViewRibbonTab } from "./ui/TopBar";
|
||||
import { AppMenuBar } from "./ui/AppMenuBar";
|
||||
import { PointCloudImportHost } from "./ui/PointCloudImportDialog";
|
||||
import { openPointCloudFileDialog, requestPointCloudImport } from "./state/pointCloudStore";
|
||||
import { isPointCloudFile } from "./io/pointCloud";
|
||||
import { EditorField } from "./ui/EditorField";
|
||||
import { useNativeAppMenu } from "./native/appMenu";
|
||||
import { openResourceWindowNative, useResourceWindowHost } from "./native/resourceWindow";
|
||||
@@ -1745,6 +1748,7 @@ export default function App() {
|
||||
};
|
||||
/** Datei aus Import-Dialog oder Drag & Drop: IFC direkt, sonst DXF/DWG-Dialog. */
|
||||
const openImportForAnyFile = (f: File) => {
|
||||
if (isPointCloudFile(f.name)) return requestPointCloudImport(f);
|
||||
if (/\.ifc$/i.test(f.name)) importIfcFile(f);
|
||||
else openImportForFile(f);
|
||||
};
|
||||
@@ -2450,6 +2454,7 @@ export default function App() {
|
||||
onExportStep,
|
||||
onImportStep: () => stepInputRef.current?.click(),
|
||||
onImportIfc: () => ifcInputRef.current?.click(),
|
||||
onImportPointCloud: () => openPointCloudFileDialog(),
|
||||
onClashCheck: () => {
|
||||
const p0 = project;
|
||||
runClashCheck(p0)
|
||||
@@ -3342,6 +3347,8 @@ export default function App() {
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{/* Punktwolken-Import ([27]): verstecktes Datei-Feld + Dialog (UI-Store, nicht im Projekt). */}
|
||||
<PointCloudImportHost project={project} />
|
||||
{/* Verstecktes IFC-Datei-Input (Menü Datei, IFC importieren). */}
|
||||
<input
|
||||
ref={ifcInputRef}
|
||||
@@ -3428,6 +3435,7 @@ export default function App() {
|
||||
onOpenProject={onOpenProject}
|
||||
onSaveProject={onSaveProject}
|
||||
onImport={() => dxfInputRef.current?.click()}
|
||||
onImportPointCloud={() => openPointCloudFileDialog()}
|
||||
onUndo={undo}
|
||||
onRedo={redo}
|
||||
canUndo={canUndo}
|
||||
|
||||
@@ -1765,6 +1765,52 @@ export const de = {
|
||||
"step.import.done": "STEP importiert: {n} Körper",
|
||||
"menu.native.importStep": "STEP importieren …",
|
||||
"menu.native.importIfc": "IFC importieren …",
|
||||
"menu.native.importPointCloud": "Punktwolke importieren …",
|
||||
"pointCloud.title": "Punktwolke importieren",
|
||||
"pointCloud.file": "Datei",
|
||||
"pointCloud.voxel": "Voxel-Raster in m (0 = aus)",
|
||||
"pointCloud.budget": "Höchstzahl Punkte",
|
||||
"pointCloud.budget.unlimited": "unbegrenzt",
|
||||
"pointCloud.budget.millions": "{n} Mio.",
|
||||
"pointCloud.read": "Lesen",
|
||||
"pointCloud.reading": "Punktwolke wird gelesen …",
|
||||
"pointCloud.add": "Hinzufügen",
|
||||
"pointCloud.cancel": "Abbrechen",
|
||||
"pointCloud.error": "Punktwolke nicht lesbar: {message}",
|
||||
"pointCloud.report": "Bericht",
|
||||
"pointCloud.report.format": "Format",
|
||||
"pointCloud.report.points": "{kept} von {read} Punkten werden angezeigt",
|
||||
"pointCloud.report.voxel": "Voxel {v} m",
|
||||
"pointCloud.report.bbox": "Ausdehnung",
|
||||
"pointCloud.report.bboxValue": "{dx} × {dy} × {dz} m",
|
||||
"pointCloud.report.min": "Tiefste Ecke (O / N / H)",
|
||||
"pointCloud.report.epsg": "Koordinatensystem",
|
||||
"pointCloud.report.epsgNone": "nicht angegeben",
|
||||
"pointCloud.report.attrs": "Attribute",
|
||||
"pointCloud.report.truncated": "Datei unvollständig — gelesen, soweit möglich.",
|
||||
"pointCloud.attr.rgb": "Farbe",
|
||||
"pointCloud.attr.intensity": "Intensität",
|
||||
"pointCloud.attr.class": "Klassen",
|
||||
"pointCloud.attr.none": "nur Lage",
|
||||
"pointCloud.placement.georef": "Lage: über den Standort-Bezug eingepasst (LV95).",
|
||||
"pointCloud.placement.georefAssumed": "Lage: LV95 aus den Koordinaten angenommen und über den Standort-Bezug eingepasst.",
|
||||
"pointCloud.placement.noHeight": "Höhe: Standort-Bezug ohne Höhe — tiefster Punkt auf 0.",
|
||||
"pointCloud.placement.local": "Lage: Ursprung der Wolke = Projekt-Nullpunkt (kein LV95-Bezug).",
|
||||
"pointCloud.placement.centered": "Lage: kein passender Standort-Bezug — Wolke mittig auf den Projekt-Nullpunkt gelegt, tiefster Punkt auf 0.",
|
||||
"pointCloud.sessionHint": "Punktwolken werden noch nicht im Projekt gespeichert und sind nach dem Neuladen weg.",
|
||||
"pointCloud.section": "Punktwolken",
|
||||
"pointCloud.empty": "Keine Punktwolke geladen.",
|
||||
"pointCloud.import": "Importieren …",
|
||||
"pointCloud.visible": "Sichtbar",
|
||||
"pointCloud.color": "Farbmodus",
|
||||
"pointCloud.color.rgb": "Farbe (RGB)",
|
||||
"pointCloud.color.intensity": "Intensität",
|
||||
"pointCloud.color.class": "Klasse",
|
||||
"pointCloud.color.height": "Höhe",
|
||||
"pointCloud.size": "Punktgrösse",
|
||||
"pointCloud.remove": "Punktwolke entfernen",
|
||||
"pointCloud.count": "{n} Punkte",
|
||||
"pointCloud.only3d": "Anzeige nur in der 3D-Ansicht.",
|
||||
"ifc.import.failed": "IFC-Import fehlgeschlagen",
|
||||
"ifc.import.done": "{schema} importiert: {n} Bauteile als Kontext-Meshes",
|
||||
"ifc.import.skipped": "{n} Bauteile ohne lesbare Geometrie, übersprungen: {list}",
|
||||
|
||||
@@ -1724,6 +1724,52 @@ export const en: Record<TranslationKey, string> = {
|
||||
"step.import.done": "STEP imported: {n} solids",
|
||||
"menu.native.importStep": "Import STEP …",
|
||||
"menu.native.importIfc": "Import IFC …",
|
||||
"menu.native.importPointCloud": "Import point cloud …",
|
||||
"pointCloud.title": "Import point cloud",
|
||||
"pointCloud.file": "File",
|
||||
"pointCloud.voxel": "Voxel grid in m (0 = off)",
|
||||
"pointCloud.budget": "Maximum points",
|
||||
"pointCloud.budget.unlimited": "unlimited",
|
||||
"pointCloud.budget.millions": "{n} M",
|
||||
"pointCloud.read": "Read",
|
||||
"pointCloud.reading": "Reading point cloud …",
|
||||
"pointCloud.add": "Add",
|
||||
"pointCloud.cancel": "Cancel",
|
||||
"pointCloud.error": "Point cloud not readable: {message}",
|
||||
"pointCloud.report": "Report",
|
||||
"pointCloud.report.format": "Format",
|
||||
"pointCloud.report.points": "Showing {kept} of {read} points",
|
||||
"pointCloud.report.voxel": "voxel {v} m",
|
||||
"pointCloud.report.bbox": "Extent",
|
||||
"pointCloud.report.bboxValue": "{dx} × {dy} × {dz} m",
|
||||
"pointCloud.report.min": "Lowest corner (E / N / H)",
|
||||
"pointCloud.report.epsg": "Coordinate system",
|
||||
"pointCloud.report.epsgNone": "not specified",
|
||||
"pointCloud.report.attrs": "Attributes",
|
||||
"pointCloud.report.truncated": "File incomplete — read as far as possible.",
|
||||
"pointCloud.attr.rgb": "colour",
|
||||
"pointCloud.attr.intensity": "intensity",
|
||||
"pointCloud.attr.class": "classes",
|
||||
"pointCloud.attr.none": "position only",
|
||||
"pointCloud.placement.georef": "Position: fitted via the site reference (LV95).",
|
||||
"pointCloud.placement.georefAssumed": "Position: LV95 assumed from the coordinates and fitted via the site reference.",
|
||||
"pointCloud.placement.noHeight": "Height: site reference has no elevation — lowest point at 0.",
|
||||
"pointCloud.placement.local": "Position: cloud origin = project origin (no LV95 reference).",
|
||||
"pointCloud.placement.centered": "Position: no matching site reference — cloud centred on the project origin, lowest point at 0.",
|
||||
"pointCloud.sessionHint": "Point clouds are not yet saved in the project and are gone after reloading.",
|
||||
"pointCloud.section": "Point clouds",
|
||||
"pointCloud.empty": "No point cloud loaded.",
|
||||
"pointCloud.import": "Import …",
|
||||
"pointCloud.visible": "Visible",
|
||||
"pointCloud.color": "Colour mode",
|
||||
"pointCloud.color.rgb": "Colour (RGB)",
|
||||
"pointCloud.color.intensity": "Intensity",
|
||||
"pointCloud.color.class": "Class",
|
||||
"pointCloud.color.height": "Height",
|
||||
"pointCloud.size": "Point size",
|
||||
"pointCloud.remove": "Remove point cloud",
|
||||
"pointCloud.count": "{n} points",
|
||||
"pointCloud.only3d": "Shown in the 3D view only.",
|
||||
"ifc.import.failed": "IFC import failed",
|
||||
"ifc.import.done": "{schema} imported: {n} elements as context meshes",
|
||||
"ifc.import.skipped": "{n} elements without readable geometry, skipped: {list}",
|
||||
|
||||
@@ -36,6 +36,8 @@ export interface NativeAppMenuHandlers {
|
||||
onExportStep: () => void;
|
||||
onImportStep: () => void;
|
||||
onImportIfc: () => void;
|
||||
/** Punktwolke importieren ([27]); optional für ältere Aufrufer. */
|
||||
onImportPointCloud?: () => void;
|
||||
onClashCheck: () => void;
|
||||
onKennzahlen: () => void;
|
||||
|
||||
@@ -180,6 +182,10 @@ export function useNativeAppMenu(
|
||||
text: t("menu.native.importIfc"),
|
||||
action: () => handlersRef.current.onImportIfc(),
|
||||
}),
|
||||
await MenuItem.new({
|
||||
text: t("menu.native.importPointCloud"),
|
||||
action: () => handlersRef.current.onImportPointCloud?.(),
|
||||
}),
|
||||
await Submenu.new({
|
||||
text: t("menu.native.export"),
|
||||
items: [
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// Punktwolken im Lage-Panel ([27] Stufe 1): Liste der geladenen Wolken mit Sichtbarkeit,
|
||||
// Farbmodus, Punktgrösse und Entfernen, dazu „Importieren …". Die Wolken liegen im UI-Store
|
||||
// (`state/pointCloudStore.ts`), nicht im Projekt — Änderungen hier sind kein Undo-Schritt.
|
||||
|
||||
import { t } from "../i18n";
|
||||
import type { TranslationKey } from "../i18n";
|
||||
import { usePanelHost } from "./host";
|
||||
import {
|
||||
MAX_POINT_SIZE,
|
||||
MIN_POINT_SIZE,
|
||||
POINT_COLOR_MODES,
|
||||
colorModeAvailable,
|
||||
openPointCloudFileDialog,
|
||||
removePointCloud,
|
||||
updatePointCloud,
|
||||
usePointClouds,
|
||||
} from "../state/pointCloudStore";
|
||||
import type { PointColorMode } from "../state/pointCloudStore";
|
||||
import { placementHints, placementOf } from "../ui/PointCloudImportDialog";
|
||||
|
||||
const MODE_KEY: Record<PointColorMode, TranslationKey> = {
|
||||
rgb: "pointCloud.color.rgb",
|
||||
intensity: "pointCloud.color.intensity",
|
||||
class: "pointCloud.color.class",
|
||||
height: "pointCloud.color.height",
|
||||
};
|
||||
|
||||
export function PointCloudSection() {
|
||||
const host = usePanelHost();
|
||||
const clouds = usePointClouds();
|
||||
return (
|
||||
<div className="site-rules" data-testid="pointcloud-section">
|
||||
<div className="site-rules-head">
|
||||
<span>{t("pointCloud.section")}</span>
|
||||
<button type="button" className="site-btn" onClick={() => openPointCloudFileDialog()}>
|
||||
{t("pointCloud.import")}
|
||||
</button>
|
||||
</div>
|
||||
{clouds.length === 0 && <div className="sun-readout">{t("pointCloud.empty")}</div>}
|
||||
{clouds.map((c) => (
|
||||
<div key={c.id} className="site-rules">
|
||||
<div className="sun-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={c.visible}
|
||||
title={t("pointCloud.visible")}
|
||||
aria-label={t("pointCloud.visible")}
|
||||
onChange={(e) => updatePointCloud(c.id, { visible: e.target.checked })}
|
||||
/>
|
||||
<span className="site-name" title={c.name}>
|
||||
{c.name}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="site-remove"
|
||||
title={t("pointCloud.remove")}
|
||||
aria-label={t("pointCloud.remove")}
|
||||
onClick={() => removePointCloud(c.id)}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<div className="sun-row">
|
||||
<select
|
||||
className="kz-input"
|
||||
value={c.colorMode}
|
||||
title={t("pointCloud.color")}
|
||||
aria-label={t("pointCloud.color")}
|
||||
onChange={(e) => updatePointCloud(c.id, { colorMode: e.target.value as PointColorMode })}
|
||||
>
|
||||
{POINT_COLOR_MODES.map((m) => (
|
||||
<option key={m} value={m} disabled={!colorModeAvailable(c.data.report, m)}>
|
||||
{t(MODE_KEY[m])}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input
|
||||
type="range"
|
||||
className="sun-slider"
|
||||
min={MIN_POINT_SIZE}
|
||||
max={MAX_POINT_SIZE}
|
||||
step={1}
|
||||
value={c.pointSize}
|
||||
title={t("pointCloud.size")}
|
||||
aria-label={t("pointCloud.size")}
|
||||
onChange={(e) => updatePointCloud(c.id, { pointSize: Number(e.target.value) })}
|
||||
/>
|
||||
<span className="sun-time">{c.pointSize} px</span>
|
||||
</div>
|
||||
<div className="sun-readout">
|
||||
{t("pointCloud.count", { n: c.data.report.pointsKept.toLocaleString("de-CH") })}
|
||||
{c.data.report.epsg !== null && <> · EPSG {c.data.report.epsg}</>}
|
||||
{" · "}
|
||||
{placementHints(placementOf(c.data, host.project))
|
||||
.map((k) => t(k))
|
||||
.join(" ")}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{clouds.length > 0 && <div className="sun-readout">{t("pointCloud.only3d")} {t("pointCloud.sessionHint")}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import { isTauriRuntime } from "../native/projectFile";
|
||||
import { openContextImportWindowNative } from "../native/contextImportWindow";
|
||||
import { SunStudySection } from "./SunStudySection";
|
||||
import { SiteRulesSection } from "./SiteRulesSection";
|
||||
import { PointCloudSection } from "./PointCloudSection";
|
||||
|
||||
/** Typ-spezifisches Badge-Label (i18n-Key) je Kontext-Objekt-Art. */
|
||||
function typeBadgeKey(obj: ContextObject): TranslationKey {
|
||||
@@ -163,6 +164,8 @@ export function SitePanel() {
|
||||
<div className="site-sep" />
|
||||
<SiteRulesSection />
|
||||
<div className="site-sep" />
|
||||
<PointCloudSection />
|
||||
<div className="site-sep" />
|
||||
|
||||
{/* Kontext-Objekte nach Ebene (`layer`) gruppiert: importierte Gebäude
|
||||
liegen als EINZELNE, getrennt lösch-/anwählbare Elemente unter ihrer
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { looksLikeLv95, placePointCloud } from "./pointCloudPlacement";
|
||||
|
||||
const lv95Cloud = {
|
||||
origin: [2_600_100, 1_200_050, 450] as [number, number, number],
|
||||
bboxMin: [2_600_090, 1_200_040, 440] as [number, number, number],
|
||||
bboxMax: [2_600_120, 1_200_070, 470] as [number, number, number],
|
||||
};
|
||||
|
||||
describe("placePointCloud", () => {
|
||||
it("passt eine LV95-Wolke über den Standort-Bezug ein (Höhe aus dem Anker)", () => {
|
||||
const p = placePointCloud({ ...lv95Cloud, epsg: 2056 }, { e: 2_600_000, n: 1_200_000 }, 445);
|
||||
expect(p.mode).toBe("georef");
|
||||
expect(p.offset).toEqual([100, 50, 5]);
|
||||
expect(p.heightFromAnchor).toBe(true);
|
||||
expect(p.epsgAssumed).toBe(false);
|
||||
});
|
||||
|
||||
it("ohne Ankerhöhe: tiefster Punkt auf 0", () => {
|
||||
const p = placePointCloud({ ...lv95Cloud, epsg: 2056 }, { e: 2_600_000, n: 1_200_000 });
|
||||
expect(p.offset).toEqual([100, 50, 10]);
|
||||
expect(p.heightFromAnchor).toBe(false);
|
||||
});
|
||||
|
||||
it("ohne EPSG, aber mit LV95-Koordinaten: LV95 angenommen", () => {
|
||||
const p = placePointCloud({ ...lv95Cloud, epsg: null }, { e: 2_600_000, n: 1_200_000 }, 440);
|
||||
expect(p.mode).toBe("georef");
|
||||
expect(p.epsgAssumed).toBe(true);
|
||||
});
|
||||
|
||||
it("anderes EPSG mit Bezug: nicht georeferenziert, sondern zentriert", () => {
|
||||
const p = placePointCloud({ ...lv95Cloud, epsg: 4326 }, { e: 2_600_000, n: 1_200_000 });
|
||||
expect(p.mode).toBe("centered");
|
||||
});
|
||||
|
||||
it("ohne Bezug: Landeskoordinaten werden mittig auf den Nullpunkt gelegt", () => {
|
||||
const p = placePointCloud({ ...lv95Cloud, epsg: 2056 }, null);
|
||||
expect(p.mode).toBe("centered");
|
||||
// Mitte (2 600 105 / 1 200 055) → 0, tiefster Punkt 440 → 0.
|
||||
expect(p.offset).toEqual([-5, -5, 10]);
|
||||
});
|
||||
|
||||
it("lokale Koordinaten bleiben wie in der Datei", () => {
|
||||
const p = placePointCloud(
|
||||
{ origin: [3, 4, 0], bboxMin: [-5, -5, -1], bboxMax: [12, 9, 6], epsg: null },
|
||||
{ e: 2_600_000, n: 1_200_000 },
|
||||
);
|
||||
expect(p.mode).toBe("local");
|
||||
expect(p.offset).toEqual([3, 4, 0]);
|
||||
});
|
||||
|
||||
it("erkennt LV95-Bereich", () => {
|
||||
expect(looksLikeLv95(lv95Cloud.bboxMin, lv95Cloud.bboxMax)).toBe(true);
|
||||
expect(looksLikeLv95([600_000, 200_000, 0], [600_100, 200_100, 0])).toBe(false); // LV03
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
// Lage einer importierten Punktwolke im Projekt ([27] Stufe 1). Rein rechnend, ohne UI.
|
||||
//
|
||||
// Der Leser liefert `xyz` (f32) relativ zu `origin` (f64, Dateikoordinaten). Hier entsteht der
|
||||
// Modellversatz dieses Ursprungs (f64, Modell-Meter x = Ost, y = Nord, z = Höhe); render3d bildet
|
||||
// `versatz + xyz` in f64 und rundet erst danach auf f32 (LV95-fest, s. `render3d/src/points.rs`).
|
||||
//
|
||||
// • Projekt hat einen Standort-Bezug (`geoAnchor`) und die Wolke liegt in LV95 (EPSG 2056, oder
|
||||
// ohne EPSG-Angabe mit LV95-typischen Koordinaten): lagerichtig einpassen. Höhe: mit
|
||||
// `geoAnchor.height` (m ü. M. des Bezugspunkts) absolut, sonst tiefster Punkt auf 0 + Hinweis.
|
||||
// • Sonst: Ursprung der Wolke = Projekt-Nullpunkt. Kleine (lokale) Koordinaten bleiben wie in
|
||||
// der Datei; grosse (Landeskoordinaten ohne Bezug) werden mit der Mitte auf den Nullpunkt und
|
||||
// dem tiefsten Punkt auf 0 gelegt. Immer mit Hinweis.
|
||||
|
||||
export type PointCloudPlacementMode = "georef" | "local" | "centered";
|
||||
|
||||
export interface PointCloudPlacement {
|
||||
/** Modell-Meter des Wolken-Ursprungs (x = Ost, y = Nord, z = Höhe); Punkt = offset + xyz. */
|
||||
offset: [number, number, number];
|
||||
mode: PointCloudPlacementMode;
|
||||
/** Höhe absolut übernommen (sonst tiefster Punkt auf 0 bzw. Dateihöhe). */
|
||||
heightFromAnchor: boolean;
|
||||
/** Ohne EPSG-Angabe wurde LV95 aus den Koordinaten erschlossen. */
|
||||
epsgAssumed: boolean;
|
||||
}
|
||||
|
||||
export interface PointCloudPlacementInput {
|
||||
origin: [number, number, number];
|
||||
bboxMin: [number, number, number];
|
||||
bboxMax: [number, number, number];
|
||||
epsg: number | null;
|
||||
}
|
||||
|
||||
/** LV95-Bereich der Schweiz (grosszügig): E 2,45–2,85 Mio., N 1,05–1,32 Mio. m. */
|
||||
export function looksLikeLv95(min: [number, number, number], max: [number, number, number]): boolean {
|
||||
return min[0] >= 2_450_000 && max[0] <= 2_850_000 && min[1] >= 1_050_000 && max[1] <= 1_320_000;
|
||||
}
|
||||
|
||||
/** Ab dieser Ausdehnung vom Nullpunkt gelten Koordinaten als „Landeskoordinaten" (nicht lokal). */
|
||||
const LOCAL_LIMIT_M = 50_000;
|
||||
|
||||
export function placePointCloud(
|
||||
cloud: PointCloudPlacementInput,
|
||||
geoOrigin: { e: number; n: number } | null,
|
||||
geoHeight?: number,
|
||||
): PointCloudPlacement {
|
||||
const [ox, oy, oz] = cloud.origin;
|
||||
const isLv95 = cloud.epsg === 2056;
|
||||
const assumeLv95 = cloud.epsg === null && looksLikeLv95(cloud.bboxMin, cloud.bboxMax);
|
||||
if (geoOrigin && (isLv95 || assumeLv95)) {
|
||||
const heightFromAnchor = geoHeight !== undefined && Number.isFinite(geoHeight);
|
||||
return {
|
||||
offset: [ox - geoOrigin.e, oy - geoOrigin.n, heightFromAnchor ? oz - geoHeight : oz - cloud.bboxMin[2]],
|
||||
mode: "georef",
|
||||
heightFromAnchor,
|
||||
epsgAssumed: assumeLv95,
|
||||
};
|
||||
}
|
||||
const far = [...cloud.bboxMin, ...cloud.bboxMax].some((v) => Math.abs(v) > LOCAL_LIMIT_M);
|
||||
if (!far) return { offset: [ox, oy, oz], mode: "local", heightFromAnchor: false, epsgAssumed: false };
|
||||
const cx = (cloud.bboxMin[0] + cloud.bboxMax[0]) / 2;
|
||||
const cy = (cloud.bboxMin[1] + cloud.bboxMax[1]) / 2;
|
||||
return {
|
||||
offset: [ox - cx, oy - cy, oz - cloud.bboxMin[2]],
|
||||
mode: "centered",
|
||||
heightFromAnchor: false,
|
||||
epsgAssumed: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { PointCloudData, PointCloudReport } from "../io/pointCloud";
|
||||
import {
|
||||
addPointCloud,
|
||||
clearPointClouds,
|
||||
defaultColorMode,
|
||||
getPointClouds,
|
||||
removePointCloud,
|
||||
resetPointCloudStoreForTests,
|
||||
updatePointCloud,
|
||||
} from "./pointCloudStore";
|
||||
|
||||
function report(p: Partial<PointCloudReport> = {}): PointCloudReport {
|
||||
return {
|
||||
format: "las",
|
||||
version: "1.4",
|
||||
pointFormat: 3,
|
||||
pointsDeclared: 2,
|
||||
pointsRead: 2,
|
||||
pointsKept: 2,
|
||||
pointsInvalid: 0,
|
||||
voxel: 0,
|
||||
bboxMin: [0, 0, 0],
|
||||
bboxMax: [1, 1, 1],
|
||||
origin: [0, 0, 0],
|
||||
hasColor: false,
|
||||
hasIntensity: false,
|
||||
hasClassification: false,
|
||||
intensityRange: null,
|
||||
classCounts: [],
|
||||
epsg: null,
|
||||
truncated: false,
|
||||
warnings: [],
|
||||
...p,
|
||||
};
|
||||
}
|
||||
|
||||
function cloud(p: Partial<PointCloudReport> = {}): PointCloudData {
|
||||
return {
|
||||
origin: [0, 0, 0],
|
||||
xyz: new Float32Array(6),
|
||||
rgb: null,
|
||||
intensity: null,
|
||||
classification: null,
|
||||
report: report(p),
|
||||
};
|
||||
}
|
||||
|
||||
describe("pointCloudStore", () => {
|
||||
beforeEach(() => resetPointCloudStoreForTests());
|
||||
|
||||
it("wählt den Farbmodus nach vorhandenen Attributen", () => {
|
||||
expect(defaultColorMode(report({ hasColor: true, hasIntensity: true }))).toBe("rgb");
|
||||
expect(defaultColorMode(report({ hasIntensity: true }))).toBe("intensity");
|
||||
expect(defaultColorMode(report({ hasClassification: true }))).toBe("class");
|
||||
expect(defaultColorMode(report())).toBe("height");
|
||||
});
|
||||
|
||||
it("fügt hinzu, ändert und entfernt", () => {
|
||||
const a = addPointCloud("a.las", cloud({ hasColor: true }));
|
||||
const b = addPointCloud("b.xyz", cloud());
|
||||
expect(getPointClouds().map((c) => c.id)).toEqual([a, b]);
|
||||
expect(getPointClouds()[0]).toMatchObject({ visible: true, colorMode: "rgb", pointSize: 2 });
|
||||
|
||||
const before = getPointClouds();
|
||||
updatePointCloud(a, { visible: false, pointSize: 99 });
|
||||
expect(getPointClouds()).not.toBe(before); // neue Referenz → React rendert neu
|
||||
expect(getPointClouds()[0]).toMatchObject({ visible: false, pointSize: 10 });
|
||||
updatePointCloud(a, { pointSize: Number.NaN, colorMode: "quatsch" as never });
|
||||
expect(getPointClouds()[0]).toMatchObject({ pointSize: 10, colorMode: "rgb" });
|
||||
|
||||
removePointCloud(a);
|
||||
expect(getPointClouds().map((c) => c.id)).toEqual([b]);
|
||||
const same = getPointClouds();
|
||||
removePointCloud(12345);
|
||||
expect(getPointClouds()).toBe(same);
|
||||
clearPointClouds();
|
||||
expect(getPointClouds()).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
// Punktwolken im UI-Zustand ([27] Stufe 1). Bewusst KEIN `Project`-Feld: die Punkte (Millionen,
|
||||
// zig MB) gehören nicht ins .obp, und das Modellfeld (`Project.pointClouds`, Vorschlag in TODO.md
|
||||
// [27]) kommt erst mit dem Asset-Speicher. Bis dahin leben die Wolken nur in dieser Sitzung —
|
||||
// nach dem Neuladen sind sie weg (bekannt, s. TODO).
|
||||
//
|
||||
// Kleiner externer Store (Muster `busyStore.ts`, `useSyncExternalStore`), weil Viewport (Anzeige),
|
||||
// Lage-Panel (Liste/Einstellungen) und der Import-Dialog in getrennten Teilbäumen sitzen.
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import type { PointCloudData, PointCloudReport } from "../io/pointCloud";
|
||||
|
||||
export type PointColorMode = "rgb" | "intensity" | "class" | "height";
|
||||
|
||||
export const POINT_COLOR_MODES: readonly PointColorMode[] = ["rgb", "intensity", "class", "height"];
|
||||
|
||||
export interface PointCloudEntry {
|
||||
/** Laufnummer (auch die id im Renderer). */
|
||||
id: number;
|
||||
name: string;
|
||||
data: PointCloudData;
|
||||
visible: boolean;
|
||||
colorMode: PointColorMode;
|
||||
/** Punktgrösse in Bildschirm-Pixeln. */
|
||||
pointSize: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_POINT_SIZE = 2;
|
||||
export const MIN_POINT_SIZE = 1;
|
||||
export const MAX_POINT_SIZE = 10;
|
||||
|
||||
/** Ist der Farbmodus mit den Attributen der Wolke möglich? (Höhe immer.) */
|
||||
export function colorModeAvailable(report: PointCloudReport, mode: PointColorMode): boolean {
|
||||
if (mode === "rgb") return report.hasColor;
|
||||
if (mode === "intensity") return report.hasIntensity;
|
||||
if (mode === "class") return report.hasClassification;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Voreinstellung: gemessene Farbe, sonst Intensität, sonst Klassen, sonst Höhe. */
|
||||
export function defaultColorMode(report: PointCloudReport): PointColorMode {
|
||||
return POINT_COLOR_MODES.find((m) => colorModeAvailable(report, m)) ?? "height";
|
||||
}
|
||||
|
||||
let clouds: readonly PointCloudEntry[] = [];
|
||||
let nextId = 1;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function emit(): void {
|
||||
for (const l of listeners) l();
|
||||
}
|
||||
|
||||
function subscribe(l: () => void): () => void {
|
||||
listeners.add(l);
|
||||
return () => listeners.delete(l);
|
||||
}
|
||||
|
||||
export function getPointClouds(): readonly PointCloudEntry[] {
|
||||
return clouds;
|
||||
}
|
||||
|
||||
/** Fügt eine gelesene Wolke hinzu (sichtbar, Voreinstellungen aus dem Bericht); liefert die id. */
|
||||
export function addPointCloud(name: string, data: PointCloudData): number {
|
||||
const id = nextId++;
|
||||
clouds = [
|
||||
...clouds,
|
||||
{ id, name, data, visible: true, colorMode: defaultColorMode(data.report), pointSize: DEFAULT_POINT_SIZE },
|
||||
];
|
||||
emit();
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Ändert Sichtbarkeit/Farbmodus/Punktgrösse/Name (Unbekanntes wird ignoriert, Grösse geklemmt). */
|
||||
export function updatePointCloud(
|
||||
id: number,
|
||||
patch: Partial<Pick<PointCloudEntry, "visible" | "colorMode" | "pointSize" | "name">>,
|
||||
): void {
|
||||
let changed = false;
|
||||
clouds = clouds.map((c) => {
|
||||
if (c.id !== id) return c;
|
||||
changed = true;
|
||||
const next = { ...c, ...patch };
|
||||
if (!Number.isFinite(next.pointSize)) next.pointSize = c.pointSize;
|
||||
next.pointSize = Math.min(MAX_POINT_SIZE, Math.max(MIN_POINT_SIZE, next.pointSize));
|
||||
if (!POINT_COLOR_MODES.includes(next.colorMode)) next.colorMode = c.colorMode;
|
||||
return next;
|
||||
});
|
||||
if (changed) emit();
|
||||
}
|
||||
|
||||
export function removePointCloud(id: number): void {
|
||||
const next = clouds.filter((c) => c.id !== id);
|
||||
if (next.length === clouds.length) return;
|
||||
clouds = next;
|
||||
emit();
|
||||
}
|
||||
|
||||
export function clearPointClouds(): void {
|
||||
if (clouds.length === 0) return;
|
||||
clouds = [];
|
||||
emit();
|
||||
}
|
||||
|
||||
export function usePointClouds(): readonly PointCloudEntry[] {
|
||||
return useSyncExternalStore(subscribe, getPointClouds, getPointClouds);
|
||||
}
|
||||
|
||||
// ── Import-Anfrage (Menü, Drag & Drop, Panel-Knopf → Dialog) ────────────────────────────────
|
||||
|
||||
let pendingFile: File | null = null;
|
||||
const importListeners = new Set<() => void>();
|
||||
let fileInput: HTMLInputElement | null = null;
|
||||
|
||||
function emitImport(): void {
|
||||
for (const l of importListeners) l();
|
||||
}
|
||||
|
||||
/** Öffnet den Import-Dialog für `file` (Drag & Drop, Datei-Auswahl). */
|
||||
export function requestPointCloudImport(file: File): void {
|
||||
pendingFile = file;
|
||||
emitImport();
|
||||
}
|
||||
|
||||
/** Schliesst den Import-Dialog. */
|
||||
export function closePointCloudImport(): void {
|
||||
if (pendingFile === null) return;
|
||||
pendingFile = null;
|
||||
emitImport();
|
||||
}
|
||||
|
||||
export function usePointCloudImportRequest(): File | null {
|
||||
return useSyncExternalStore(
|
||||
(l) => {
|
||||
importListeners.add(l);
|
||||
return () => importListeners.delete(l);
|
||||
},
|
||||
() => pendingFile,
|
||||
() => pendingFile,
|
||||
);
|
||||
}
|
||||
|
||||
/** Der Dialog-Host meldet sein verstecktes Datei-Feld an (oder ab mit `null`). */
|
||||
export function registerPointCloudFileInput(el: HTMLInputElement | null): void {
|
||||
fileInput = el;
|
||||
}
|
||||
|
||||
/** Datei-Auswahl öffnen (Menü „Punktwolke importieren …"). Synchron im Klick, sonst blockt WebKit. */
|
||||
export function openPointCloudFileDialog(): void {
|
||||
fileInput?.click();
|
||||
}
|
||||
|
||||
/** Nur für Tests: Zustand zurücksetzen. */
|
||||
export function resetPointCloudStoreForTests(): void {
|
||||
clouds = [];
|
||||
nextId = 1;
|
||||
pendingFile = null;
|
||||
fileInput = null;
|
||||
}
|
||||
@@ -8422,3 +8422,10 @@ body {
|
||||
color: var(--ink-2);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* Punktwolken-Import ([27]): Bericht im Dialog kompakt wie die übrigen Hinweise. */
|
||||
.pc-report {
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--ink-2);
|
||||
}
|
||||
@@ -19,6 +19,8 @@ export interface AppMenuBarProps {
|
||||
onOpenProject: () => void;
|
||||
onSaveProject: () => void;
|
||||
onImport: () => void;
|
||||
/** Datei: Punktwolke importieren ([27]). */
|
||||
onImportPointCloud?: () => void;
|
||||
|
||||
/** Bearbeiten: Undo/Redo (Store) + Löschen der aktuellen Auswahl. */
|
||||
onUndo: () => void;
|
||||
@@ -53,6 +55,7 @@ export function AppMenuBar({
|
||||
onOpenProject,
|
||||
onSaveProject,
|
||||
onImport,
|
||||
onImportPointCloud,
|
||||
onUndo,
|
||||
onRedo,
|
||||
canUndo,
|
||||
@@ -79,6 +82,7 @@ export function AppMenuBar({
|
||||
{ label: t("file.save"), onSelect: onSaveProject },
|
||||
{ divider: true },
|
||||
{ label: t("file.import"), onSelect: onImport },
|
||||
...(onImportPointCloud ? [{ label: t("menu.native.importPointCloud"), onSelect: onImportPointCloud }] : []),
|
||||
];
|
||||
|
||||
const editItems: DropdownItem[] = [
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
// Punktwolken-Import ([27] Stufe 1): verstecktes Datei-Feld + Dialog mit Voxel/Budget-Wahl und
|
||||
// Bericht (Anzahl, Ausdehnung, EPSG, Lage). Einmal in App eingehängt (`PointCloudImportHost`);
|
||||
// geöffnet über Menü (`openPointCloudFileDialog`), Drag & Drop oder das Lage-Panel
|
||||
// (`requestPointCloudImport`). Gelesen wird im Web-Worker (`readPointCloud`), die fertige Wolke
|
||||
// landet im UI-Store (`pointCloudStore.ts`), NICHT im Projekt.
|
||||
//
|
||||
// Muster: ExportDxfDialog (abgedunkeltes Overlay, Esc/Hintergrund schliessen).
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n";
|
||||
import type { TranslationKey } from "../i18n";
|
||||
import { Dropdown } from "./Dropdown";
|
||||
import { DEFAULT_MAX_POINTS, POINT_CLOUD_EXTENSIONS, readPointCloud } from "../io/pointCloud";
|
||||
import type { PointCloudData } from "../io/pointCloud";
|
||||
import {
|
||||
addPointCloud,
|
||||
closePointCloudImport,
|
||||
registerPointCloudFileInput,
|
||||
requestPointCloudImport,
|
||||
usePointCloudImportRequest,
|
||||
} from "../state/pointCloudStore";
|
||||
import { placePointCloud } from "../state/pointCloudPlacement";
|
||||
import type { PointCloudPlacement } from "../state/pointCloudPlacement";
|
||||
import { projectGeoOrigin } from "../core";
|
||||
import type { Project } from "../model/types";
|
||||
|
||||
const BUDGETS = [1_000_000, 2_000_000, DEFAULT_MAX_POINTS, 10_000_000, 0];
|
||||
|
||||
const fmtInt = (n: number) => Math.round(n).toLocaleString("de-CH");
|
||||
const fmtM = (n: number) => (Math.abs(n) >= 1000 ? n.toFixed(1) : n.toFixed(2));
|
||||
|
||||
/** Hinweistexte zur Lage (für Dialog und Panel). */
|
||||
export function placementHints(p: PointCloudPlacement): TranslationKey[] {
|
||||
if (p.mode === "georef") {
|
||||
const keys: TranslationKey[] = [
|
||||
p.epsgAssumed ? "pointCloud.placement.georefAssumed" : "pointCloud.placement.georef",
|
||||
];
|
||||
if (!p.heightFromAnchor) keys.push("pointCloud.placement.noHeight");
|
||||
return keys;
|
||||
}
|
||||
return [p.mode === "local" ? "pointCloud.placement.local" : "pointCloud.placement.centered"];
|
||||
}
|
||||
|
||||
export function placementOf(data: PointCloudData, project: Project): PointCloudPlacement {
|
||||
const r = data.report;
|
||||
return placePointCloud(
|
||||
{ origin: data.origin, bboxMin: r.bboxMin, bboxMax: r.bboxMax, epsg: r.epsg },
|
||||
projectGeoOrigin(project),
|
||||
project.geoAnchor?.height,
|
||||
);
|
||||
}
|
||||
|
||||
function PointCloudImportDialog({ file, project }: { file: File; project: Project }) {
|
||||
const [voxel, setVoxel] = useState("0");
|
||||
const [budget, setBudget] = useState(DEFAULT_MAX_POINTS);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [result, setResult] = useState<PointCloudData | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") closePointCloudImport();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, []);
|
||||
|
||||
const onRead = async () => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setResult(null);
|
||||
try {
|
||||
const v = Number(voxel.replace(",", "."));
|
||||
const data = await readPointCloud(await file.arrayBuffer(), file.name, {
|
||||
voxel: Number.isFinite(v) && v > 0 ? v : 0,
|
||||
maxPoints: budget,
|
||||
});
|
||||
setResult(data);
|
||||
} catch (e) {
|
||||
setError(t("pointCloud.error", { message: e instanceof Error ? e.message : String(e) }));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onAdd = () => {
|
||||
if (!result) return;
|
||||
addPointCloud(file.name, result);
|
||||
closePointCloudImport();
|
||||
};
|
||||
|
||||
const r = result?.report;
|
||||
const placement = result ? placementOf(result, project) : null;
|
||||
const attrs = r
|
||||
? [
|
||||
r.hasColor && t("pointCloud.attr.rgb"),
|
||||
r.hasIntensity && t("pointCloud.attr.intensity"),
|
||||
r.hasClassification && t("pointCloud.attr.class"),
|
||||
].filter(Boolean)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="imp-overlay" onClick={() => closePointCloudImport()}>
|
||||
<div
|
||||
className="imp-dialog"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t("pointCloud.title")}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<header className="imp-head">
|
||||
<span className="imp-head-title">{t("pointCloud.title")}</span>
|
||||
<button className="imp-close" onClick={() => closePointCloudImport()} aria-label={t("pointCloud.cancel")}>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="imp-body">
|
||||
<div className="imp-file">
|
||||
<span className="imp-file-label">{t("pointCloud.file")}</span>
|
||||
<span className="imp-file-name" title={file.name}>
|
||||
{file.name} · {fmtInt(file.size / 1e6)} MB
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<section className="imp-section">
|
||||
<div className="imp-section-title">{t("pointCloud.voxel")}</div>
|
||||
<input
|
||||
className="kz-input"
|
||||
type="number"
|
||||
min={0}
|
||||
step={0.05}
|
||||
value={voxel}
|
||||
aria-label={t("pointCloud.voxel")}
|
||||
onChange={(e) => setVoxel(e.target.value)}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="imp-section">
|
||||
<div className="imp-section-title">{t("pointCloud.budget")}</div>
|
||||
<Dropdown
|
||||
value={String(budget)}
|
||||
onChange={(v) => setBudget(Number(v))}
|
||||
title={t("pointCloud.budget")}
|
||||
options={BUDGETS.map((b) => ({
|
||||
value: String(b),
|
||||
label: b === 0 ? t("pointCloud.budget.unlimited") : t("pointCloud.budget.millions", { n: b / 1e6 }),
|
||||
}))}
|
||||
/>
|
||||
</section>
|
||||
|
||||
{busy && <div className="imp-note">{t("pointCloud.reading")}</div>}
|
||||
{error && <div className="imp-warn">{error}</div>}
|
||||
|
||||
{r && placement && (
|
||||
<section className="imp-section pc-report" data-testid="pointcloud-report">
|
||||
<div className="imp-section-title">{t("pointCloud.report")}</div>
|
||||
<div>
|
||||
{t("pointCloud.report.format")}: {r.format.toUpperCase()} {r.version}
|
||||
</div>
|
||||
<div>
|
||||
{t("pointCloud.report.points", { kept: fmtInt(r.pointsKept), read: fmtInt(r.pointsRead) })}
|
||||
{r.voxel > 0 && <> · {t("pointCloud.report.voxel", { v: fmtM(r.voxel) })}</>}
|
||||
</div>
|
||||
<div>
|
||||
{t("pointCloud.report.bbox")}:{" "}
|
||||
{t("pointCloud.report.bboxValue", {
|
||||
dx: fmtM(r.bboxMax[0] - r.bboxMin[0]),
|
||||
dy: fmtM(r.bboxMax[1] - r.bboxMin[1]),
|
||||
dz: fmtM(r.bboxMax[2] - r.bboxMin[2]),
|
||||
})}
|
||||
</div>
|
||||
<div>
|
||||
{t("pointCloud.report.min")}: {r.bboxMin.map(fmtM).join(" / ")}
|
||||
</div>
|
||||
<div>
|
||||
{t("pointCloud.report.epsg")}: {r.epsg !== null ? `EPSG ${r.epsg}` : t("pointCloud.report.epsgNone")}
|
||||
</div>
|
||||
<div>
|
||||
{t("pointCloud.report.attrs")}: {attrs.length ? attrs.join(", ") : t("pointCloud.attr.none")}
|
||||
</div>
|
||||
{r.truncated && <div className="imp-warn">{t("pointCloud.report.truncated")}</div>}
|
||||
{r.warnings.map((w) => (
|
||||
<div key={w} className="imp-note">
|
||||
{w}
|
||||
</div>
|
||||
))}
|
||||
{placementHints(placement).map((k) => (
|
||||
<div key={k} className="imp-note">
|
||||
{t(k)}
|
||||
</div>
|
||||
))}
|
||||
<div className="imp-note">{t("pointCloud.sessionHint")}</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<footer className="imp-foot">
|
||||
<button className="imp-btn" onClick={() => closePointCloudImport()}>
|
||||
{t("pointCloud.cancel")}
|
||||
</button>
|
||||
<button className="imp-btn" onClick={() => void onRead()} disabled={busy}>
|
||||
{t("pointCloud.read")}
|
||||
</button>
|
||||
<button className="imp-btn primary" onClick={onAdd} disabled={!result || busy}>
|
||||
{t("pointCloud.add")}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Verstecktes Datei-Feld + Dialog; einmal in der App einhängen. */
|
||||
export function PointCloudImportHost({ project }: { project: Project }) {
|
||||
const file = usePointCloudImportRequest();
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
ref={registerPointCloudFileInput}
|
||||
type="file"
|
||||
accept={POINT_CLOUD_EXTENSIONS.map((e) => "." + e).join(",")}
|
||||
style={{ display: "none" }}
|
||||
data-testid="pointcloud-input"
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (f) requestPointCloudImport(f);
|
||||
}}
|
||||
/>
|
||||
{file && <PointCloudImportDialog key={file.name + file.size + file.lastModified} file={file} project={project} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -65,6 +65,9 @@ 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";
|
||||
|
||||
/** Ein per 3D-Klick getroffenes Bauteil, oder null (Leerraum). */
|
||||
export type Pick3dHit =
|
||||
@@ -536,9 +539,14 @@ export function Wasm3DViewport({
|
||||
setGroundGrid,
|
||||
setSectionPlane,
|
||||
setHighlightLines,
|
||||
syncPointClouds,
|
||||
ready,
|
||||
failed,
|
||||
} = useWasm3dRenderer(canvasRef, true);
|
||||
// Punktwolken ([27]) aus dem UI-Store (nicht im Projekt). Die Lage folgt dem Standort-Bezug.
|
||||
const pointClouds = usePointClouds();
|
||||
const geoOrigin = projectGeoOrigin(project);
|
||||
const geoKey = geoOrigin ? `${geoOrigin.e},${geoOrigin.n},${project.geoAnchor?.height ?? ""}` : "";
|
||||
// Live-Schnitt: die aktive Ebene kommt jetzt aus `section3d` (App-State, an
|
||||
// eine Schnittlinie gebunden — `sectionPlaneFromLevel`) statt aus einem
|
||||
// lokalen Hardcode-Toggle. `null` = kein Schnitt.
|
||||
@@ -562,6 +570,15 @@ export function Wasm3DViewport({
|
||||
redrawRef.current();
|
||||
}, [ready, project, detail, updateModel]);
|
||||
|
||||
// Punktwolken abgleichen (neu/umgestellt/entfernt) und neu zeichnen, wenn sich etwas tat.
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
const p = projectRef.current;
|
||||
if (syncPointClouds(pointCloudSyncItems(pointClouds, projectGeoOrigin(p), p.geoAnchor?.height))) {
|
||||
redrawRef.current();
|
||||
}
|
||||
}, [ready, pointClouds, geoKey, syncPointClouds]);
|
||||
|
||||
// truck-Extrusionen (s. toWalls3d.ts emitExtrudedSolids): die WASM-Extrusion
|
||||
// läuft asynchron und ist beim ersten `updateModel` oben typischerweise noch
|
||||
// nicht fertig — ohne diesen Re-Push bliebe sie trotz erfolgreichen Ladens
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { PointCloudData } from "../io/pointCloud";
|
||||
import { planPointCloudSync } from "./pointCloudSync";
|
||||
import type { PointCloudSyncItem, UploadedPointCloud } from "./pointCloudSync";
|
||||
|
||||
const data = (): PointCloudData => ({
|
||||
origin: [0, 0, 0],
|
||||
xyz: new Float32Array(3),
|
||||
rgb: null,
|
||||
intensity: null,
|
||||
classification: null,
|
||||
report: {} as PointCloudData["report"],
|
||||
});
|
||||
|
||||
function item(id: number, d: PointCloudData, p: Partial<PointCloudSyncItem> = {}): PointCloudSyncItem {
|
||||
return { id, data: d, offset: [0, 0, 0], colorMode: "rgb", pointSize: 2, visible: true, ...p };
|
||||
}
|
||||
|
||||
const asUploaded = (i: PointCloudSyncItem): UploadedPointCloud => ({
|
||||
data: i.data,
|
||||
offset: [...i.offset],
|
||||
colorMode: i.colorMode,
|
||||
pointSize: i.pointSize,
|
||||
visible: i.visible,
|
||||
});
|
||||
|
||||
describe("planPointCloudSync", () => {
|
||||
it("lädt neue Wolken hoch und entfernt verschwundene", () => {
|
||||
const d1 = data();
|
||||
const prev = new Map([[9, asUploaded(item(9, data()))]]);
|
||||
expect(planPointCloudSync(prev, [item(1, d1)])).toEqual([
|
||||
{ kind: "remove", id: 9 },
|
||||
{ kind: "set", item: item(1, d1) },
|
||||
]);
|
||||
});
|
||||
|
||||
it("nur Darstellung geändert → style, unverändert → nichts", () => {
|
||||
const d = data();
|
||||
const prev = new Map([[1, asUploaded(item(1, d))]]);
|
||||
expect(planPointCloudSync(prev, [item(1, d)])).toEqual([]);
|
||||
const ops = planPointCloudSync(prev, [item(1, d, { colorMode: "height", visible: false })]);
|
||||
expect(ops.map((o) => o.kind)).toEqual(["style"]);
|
||||
});
|
||||
|
||||
it("neue Daten oder neue Lage → neu hochladen", () => {
|
||||
const d = data();
|
||||
const prev = new Map([[1, asUploaded(item(1, d))]]);
|
||||
expect(planPointCloudSync(prev, [item(1, data())]).map((o) => o.kind)).toEqual(["set"]);
|
||||
expect(planPointCloudSync(prev, [item(1, d, { offset: [0, 0, 1] })]).map((o) => o.kind)).toEqual(["set"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
// Abgleich Punktwolken-Store → render3d ([27]): welche Wolken neu hochgeladen, nur umgestellt
|
||||
// (Farbmodus/Grösse/Sichtbarkeit) oder entfernt werden müssen. Rein rechnend (testbar); der Hook
|
||||
// `useWasm3dRenderer.syncPointClouds` führt die Schritte aus.
|
||||
//
|
||||
// Neu hochladen (teuer: Millionen Punkte über die WASM-Grenze) nur, wenn sich die DATEN (Objekt-
|
||||
// identität) oder die LAGE (Versatz, z. B. neuer Standort-Bezug) geändert haben — Darstellungs-
|
||||
// änderungen gehen über den kleinen `set_point_cloud_style`-Weg.
|
||||
|
||||
import type { PointCloudData } from "../io/pointCloud";
|
||||
import type { PointCloudEntry, PointColorMode } from "../state/pointCloudStore";
|
||||
import { placePointCloud } from "../state/pointCloudPlacement";
|
||||
|
||||
export interface PointCloudSyncItem {
|
||||
id: number;
|
||||
data: PointCloudData;
|
||||
/** Modell-Meter des Wolken-Ursprungs (s. `placePointCloud`). */
|
||||
offset: [number, number, number];
|
||||
colorMode: PointColorMode;
|
||||
pointSize: number;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
/** Was im Renderer liegt (je id). */
|
||||
export interface UploadedPointCloud {
|
||||
data: PointCloudData;
|
||||
offset: [number, number, number];
|
||||
colorMode: PointColorMode;
|
||||
pointSize: number;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
export type PointCloudSyncOp =
|
||||
| { kind: "set"; item: PointCloudSyncItem }
|
||||
| { kind: "style"; item: PointCloudSyncItem }
|
||||
| { kind: "remove"; id: number };
|
||||
|
||||
export function planPointCloudSync(
|
||||
uploaded: ReadonlyMap<number, UploadedPointCloud>,
|
||||
items: readonly PointCloudSyncItem[],
|
||||
): PointCloudSyncOp[] {
|
||||
const ops: PointCloudSyncOp[] = [];
|
||||
const ids = new Set(items.map((i) => i.id));
|
||||
for (const id of uploaded.keys()) if (!ids.has(id)) ops.push({ kind: "remove", id });
|
||||
for (const item of items) {
|
||||
const prev = uploaded.get(item.id);
|
||||
const sameData =
|
||||
prev !== undefined &&
|
||||
prev.data === item.data &&
|
||||
prev.offset[0] === item.offset[0] &&
|
||||
prev.offset[1] === item.offset[1] &&
|
||||
prev.offset[2] === item.offset[2];
|
||||
if (!sameData) {
|
||||
ops.push({ kind: "set", item });
|
||||
} else if (
|
||||
prev.colorMode !== item.colorMode ||
|
||||
prev.pointSize !== item.pointSize ||
|
||||
prev.visible !== item.visible
|
||||
) {
|
||||
ops.push({ kind: "style", item });
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
/** Store-Einträge → Abgleich-Einträge, Lage aus dem aktuellen Standort-Bezug (nur gelesen). */
|
||||
export function pointCloudSyncItems(
|
||||
clouds: readonly PointCloudEntry[],
|
||||
geoOrigin: { e: number; n: number } | null,
|
||||
geoHeight: number | undefined,
|
||||
): PointCloudSyncItem[] {
|
||||
return clouds.map((c) => {
|
||||
const r = c.data.report;
|
||||
const placement = placePointCloud(
|
||||
{ origin: c.data.origin, bboxMin: r.bboxMin, bboxMax: r.bboxMax, epsg: r.epsg },
|
||||
geoOrigin,
|
||||
geoHeight,
|
||||
);
|
||||
return {
|
||||
id: c.id,
|
||||
data: c.data,
|
||||
offset: placement.offset,
|
||||
colorMode: c.colorMode,
|
||||
pointSize: c.pointSize,
|
||||
visible: c.visible,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -23,6 +23,8 @@ import type { DetailLevel } from "../model/viewTypes";
|
||||
import { loadEngine3d } from "../engine/engine3d";
|
||||
import { decodeMaterialTextures } from "./materialTextures";
|
||||
import { decodeImageToRgba } from "../io/swissImage";
|
||||
import { planPointCloudSync } from "./pointCloudSync";
|
||||
import type { PointCloudSyncItem, UploadedPointCloud } from "./pointCloudSync";
|
||||
|
||||
/** Fertige Kamera für einen Frame (world-Meter, Y-up — wie render3d::types::Camera). */
|
||||
export interface Camera3d {
|
||||
@@ -108,6 +110,25 @@ interface WebModelRendererLike {
|
||||
): void;
|
||||
/** Drapiertes Luftbild löschen (Gelände wieder einfarbig/shaded). Optional. */
|
||||
clear_aerial?(): void;
|
||||
/** Punktwolke setzen ([27], `web::set_point_cloud`): `xyz` relativ zum Ursprung, `ox/oy/oz` =
|
||||
* Modell-Meter des Ursprungs (f64, Rust addiert in f64). Leere Attribut-Arrays = fehlt.
|
||||
* Liefert die gezeichnete Punktzahl (0 = verworfen). Optional — ältere WASM-Builds. */
|
||||
set_point_cloud?(
|
||||
id: number,
|
||||
xyz: Float32Array,
|
||||
rgb: Uint8Array,
|
||||
intensity: Uint16Array,
|
||||
classification: Uint8Array,
|
||||
ox: number,
|
||||
oy: number,
|
||||
oz: number,
|
||||
colorMode: string,
|
||||
pointSize: number,
|
||||
visible: boolean,
|
||||
): number;
|
||||
/** Nur Darstellung ändern; `false` = Wolke unbekannt. */
|
||||
set_point_cloud_style?(id: number, colorMode: string, pointSize: number, visible: boolean): boolean;
|
||||
remove_point_cloud?(id: number): void;
|
||||
set_camera(
|
||||
eyeX: number,
|
||||
eyeY: number,
|
||||
@@ -157,6 +178,8 @@ export function useWasm3dRenderer(
|
||||
enabled: boolean,
|
||||
) {
|
||||
const rendererRef = useRef<WebModelRendererLike | null>(null);
|
||||
// Was an Punktwolken im Renderer liegt ([27], s. pointCloudSync.ts).
|
||||
const pointCloudsRef = useRef<Map<number, UploadedPointCloud>>(new Map());
|
||||
const [ready, setReady] = useState(false);
|
||||
const [failed, setFailed] = useState(false);
|
||||
|
||||
@@ -173,6 +196,8 @@ export function useWasm3dRenderer(
|
||||
const renderer = await getRenderer(canvas);
|
||||
if (disposed) return;
|
||||
rendererRef.current = renderer;
|
||||
// Neuer (oder wiederverwendeter) Renderer: Punktwolken neu abgleichen.
|
||||
pointCloudsRef.current = new Map();
|
||||
setReady(true);
|
||||
setFailed(false);
|
||||
} catch (e) {
|
||||
@@ -281,6 +306,60 @@ export function useWasm3dRenderer(
|
||||
})();
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Punktwolken abgleichen ([27]): neue/geänderte Daten hochladen, Darstellung umstellen,
|
||||
* entfernte löschen. Gibt `true` zurück, wenn sich etwas geändert hat (→ neu zeichnen).
|
||||
*/
|
||||
const syncPointClouds = useCallback((items: readonly PointCloudSyncItem[]): boolean => {
|
||||
const r = rendererRef.current;
|
||||
if (!r || typeof r.set_point_cloud !== "function") return false;
|
||||
const uploaded = pointCloudsRef.current;
|
||||
const ops = planPointCloudSync(uploaded, items);
|
||||
const empty8 = new Uint8Array(0);
|
||||
const upload = (it: PointCloudSyncItem) => {
|
||||
const d = it.data;
|
||||
r.set_point_cloud!(
|
||||
it.id,
|
||||
d.xyz,
|
||||
d.rgb ?? empty8,
|
||||
d.intensity ?? new Uint16Array(0),
|
||||
d.classification ?? empty8,
|
||||
it.offset[0],
|
||||
it.offset[1],
|
||||
it.offset[2],
|
||||
it.colorMode,
|
||||
it.pointSize,
|
||||
it.visible,
|
||||
);
|
||||
};
|
||||
for (const op of ops) {
|
||||
try {
|
||||
if (op.kind === "remove") {
|
||||
r.remove_point_cloud?.(op.id);
|
||||
uploaded.delete(op.id);
|
||||
continue;
|
||||
}
|
||||
const it = op.item;
|
||||
if (op.kind === "style") {
|
||||
const ok = r.set_point_cloud_style?.(it.id, it.colorMode, it.pointSize, it.visible) === true;
|
||||
if (!ok) upload(it);
|
||||
} else {
|
||||
upload(it);
|
||||
}
|
||||
uploaded.set(it.id, {
|
||||
data: it.data,
|
||||
offset: [...it.offset],
|
||||
colorMode: it.colorMode,
|
||||
pointSize: it.pointSize,
|
||||
visible: it.visible,
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn("render3d Punktwolke fehlgeschlagen:", e);
|
||||
}
|
||||
}
|
||||
return ops.length > 0;
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Darstellungsart umschalten — reicht die volle `RenderMode`-Union der
|
||||
* Oberleiste ("shaded"/"white"/"textured"/"wireframe"/"hidden") an Rust
|
||||
@@ -438,6 +517,7 @@ export function useWasm3dRenderer(
|
||||
setGroundGrid,
|
||||
setSectionPlane,
|
||||
setHighlightLines,
|
||||
syncPointClouds,
|
||||
ready,
|
||||
failed,
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user