[K3d] Auswahl/Picken im Kern auf dem Plan-Puffer (räumlicher Index)

core/src/plan_pick.rs (+ web/plan_pick.rs, TS-Fassade src/plan/planView/planPick.ts):
Index je Plan über die Abschnitte gehaltener Plan-Puffer — Raster der 2D-Zeichenlinien (gleiche
Zellen/Reihenfolge wie segmentIndex.ts → gleiche Treffer), Polygone unter dem Punkt (oberstes/
unterstes, mit Pick-Feld), Symbol-Linien/-Bögen in Client-Pixeln, Kreis-/Bogen-Ringe, Besitzer
(ownedBy). PlanView fragt nur noch ab (hitTest, pickRoom/Roof/Stair/Opening/…, pickDrawing,
nearDrawingIds, Hervorhebung); segmentIndex.ts, ownerIndex.ts und die Schleifen über alle
Primitive je Mausbewegung gelöscht. Gleich zur alten Fassung (25k Abfragen: Beispielprojekt
+ Überlagerung, 150 Zufallspläne, grosses Projekt). Grosses Projekt + 100k 2D-Linien:
alle Hover-Abfragen zusammen 90 ms → 30 µs je Mausbewegung, Aufbau ~100 ms (lazy).
Kern-only-Puffer ohne Schraffur-JSON (hatchJson: false).

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 23:14:48 +00:00
1 parent b2e63822d4
commit 1a90f954da
17 files changed
+1173 -567

No files matched your search

+1
View File
@@ -60,6 +60,7 @@ pub mod curves;
pub mod skeleton;
pub mod plan_parts;
pub mod plan_scene;
pub mod plan_pick;
#[cfg(feature = "web")]
mod web;
+17
View File
@@ -648,6 +648,23 @@ impl<'a> View<'a> {
Some(out)
}
/// Absoluter Wortindex des Eintrags `i` (Kopf `[tag, flags, pickKind, pickStr]`, danach die
/// festen Felder) — für Leser, die nur wenige Wörter brauchen ([`View::word`]).
pub(crate) fn rec_at(&self, i: usize) -> Option<usize> {
if i >= self.n_prims {
return None;
}
let off = whole(self.w.get(self.offsets_at + i)?)?;
let at = self.recs_at.checked_add(off)?;
(at < self.recs_end).then_some(at)
}
/// Wort `k` des `f64`-Teils (s. [`View::rec_at`]).
#[inline]
pub(crate) fn word(&self, k: usize) -> Option<f64> {
self.w.get(k)
}
pub(crate) fn rec(&self, i: usize) -> Option<Rec> {
if i >= self.n_prims {
return None;
+693
View File
@@ -0,0 +1,693 @@
//! Auswahl/Picken im Grundriss ([K3d], früher `segmentIndex.ts`, `ownerIndex.ts` und die
//! Schleifen über `plan.primitives` in `PlanView.tsx`): ein räumlicher Index über einem
//! zusammengesetzten Plan ([`crate::plan_parts`]), den TS nur noch abfragt. Ergebnisse sind
//! Indizes in `plan.primitives`.
//!
//! - 2D-Zeichenlinien (`line` mit nicht-leerer `drawingId`): gleichförmiges Raster wie die frühere
//! TS-Fassung (gleiche Zellgrösse, gleiche Reihenfolge → gleiche Treffer, auch bei Gleichstand):
//! nächstes Segment bzw. alle Segmente im Umkreis.
//! - Polygone (Punkt-in-Polygon wie `pointInPolygon`): oberstes bzw. unterstes Polygon unter dem
//! Punkt, wahlweise nur mit einer bestimmten Pick-Id (Raum, Dach, Treppe, …), oder alle.
//! - Symbol-Linien und -Bögen mit Öffnungs-/Treppen-Id: nächste in Bildschirm-Pixeln (dieselbe
//! Abbildung Modell → Client wie `toScreen` + `vbToClient` in PlanView).
//! - Kreise/Bögen der 2D-Zeichnung: Abstand zum Ring wie `distToDrawingRing`.
//! - Besitzer: alle Primitive einer Id (wie `ownedBy`).
//!
//! Pick-Arten (Bit `1 << art`): 1 wall · 2 drawing · 3 ceiling · 4 opening · 5 stair · 6 room ·
//! 7 extrudedSolid · 8 contextObject · 9 column · 10 roof · 11 sectionLine. Das Bit einer Art ist
//! gesetzt, wenn ihre Id nicht leer ist (TS: `p.roomId && …`).
use crate::jsmath::hypot;
use crate::jsnum;
use crate::plan_buf::{whole, View, F_IDS, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_LINE, T_POLYGON};
use crate::plan_parts::pick_ids;
use std::collections::HashMap;
use std::rc::Rc;
const TARGET_PER_CELL: f64 = 8.0;
const MAX_CELLS: f64 = 4_000_000.0;
const MAX_CELLS_PER_ITEM: f64 = 1024.0;
/// Gleichförmiges Raster (CSR) über Bounding-Boxen; Einträge sind Index-Werte.
#[derive(Default)]
struct Grid {
min_x: f64,
min_y: f64,
cell: f64,
cols: f64,
rows: f64,
cell_start: Vec<u32>,
items: Vec<u32>,
/// Einträge mit zu vielen Zellen — immer geprüft.
long: Vec<u32>,
}
impl Grid {
/// Wie `buildSegmentIndex`: `boxes` = (Wert, minX, minY, maxX, maxY) in Einfüge-Reihenfolge.
fn build(boxes: &[(u32, f64, f64, f64, f64)], n: usize, min_x: f64, min_y: f64, max_x: f64, max_y: f64) -> Grid {
let w = jsnum::max(max_x - min_x, 1e-6);
let h = jsnum::max(max_y - min_y, 1e-6);
let cell_count = jsnum::min(MAX_CELLS, jsnum::max(1.0, (n as f64 / TARGET_PER_CELL).ceil()));
let mut cell = ((w * h) / cell_count).sqrt();
if !(cell > 0.0) {
cell = jsnum::max(w, h);
}
let cols = jsnum::max(1.0, (w / cell).ceil());
let rows = jsnum::max(1.0, (h / cell).ceil());
let mut g = Grid { min_x, min_y, cell, cols, rows, ..Default::default() };
let total = cols * rows;
if !(total.is_finite() && total <= 1e8) {
// Entartet (NaN/riesig): alles in die immer geprüfte Liste.
g.cols = 1.0;
g.rows = 1.0;
g.cell_start = vec![0, 0];
g.long = boxes.iter().map(|b| b.0).collect();
return g;
}
let n_cells = total as usize;
let cx = |x: f64| jsnum::min(cols - 1.0, jsnum::max(0.0, ((x - min_x) / cell).floor()));
let cy = |y: f64| jsnum::min(rows - 1.0, jsnum::max(0.0, ((y - min_y) / cell).floor()));
let range = |b: &(u32, f64, f64, f64, f64)| (cx(b.1), cx(b.3), cy(b.2), cy(b.4));
let mut counts = vec![0u32; n_cells + 1];
let mut is_long = vec![false; boxes.len()];
for (k, b) in boxes.iter().enumerate() {
let (x0, x1, y0, y1) = range(b);
if (x1 - x0 + 1.0) * (y1 - y0 + 1.0) > MAX_CELLS_PER_ITEM {
g.long.push(b.0);
is_long[k] = true;
continue;
}
let mut y = y0;
while y <= y1 {
let mut x = x0;
while x <= x1 {
counts[(y * cols + x) as usize + 1] += 1;
x += 1.0;
}
y += 1.0;
}
}
for c in 1..counts.len() {
counts[c] += counts[c - 1];
}
let mut fill: Vec<u32> = counts[..n_cells].to_vec();
let mut items = vec![0u32; counts[n_cells] as usize];
for (k, b) in boxes.iter().enumerate() {
if is_long[k] {
continue;
}
let (x0, x1, y0, y1) = range(b);
let mut y = y0;
while y <= y1 {
let mut x = x0;
while x <= x1 {
let c = (y * cols + x) as usize;
items[fill[c] as usize] = b.0;
fill[c] += 1;
x += 1.0;
}
y += 1.0;
}
}
g.cell_start = counts;
g.items = items;
g
}
/// Alle Einträge der Zellen um `(x, y)` im Umkreis `r` (zuerst `long`), wie `nearestSegment`.
fn visit(&self, x: f64, y: f64, r: f64, mut f: impl FnMut(u32)) {
for &i in &self.long {
f(i);
}
if self.items.is_empty() {
return;
}
let x0 = ((x - r - self.min_x) / self.cell).floor();
let x1 = ((x + r - self.min_x) / self.cell).floor();
let y0 = ((y - r - self.min_y) / self.cell).floor();
let y1 = ((y + r - self.min_y) / self.cell).floor();
if x1 < 0.0 || y1 < 0.0 || x0 >= self.cols || y0 >= self.rows {
return;
}
let mut yy = jsnum::max(0.0, y0);
let ye = jsnum::min(self.rows - 1.0, y1);
while yy <= ye {
let mut xx = jsnum::max(0.0, x0);
let xe = jsnum::min(self.cols - 1.0, x1);
while xx <= xe {
let c = (yy * self.cols + xx) as usize;
for k in self.cell_start[c]..self.cell_start[c + 1] {
f(self.items[k as usize]);
}
xx += 1.0;
}
yy += 1.0;
}
}
}
/// Raster über Bounding-Boxen (Einträge mit nicht endlicher Box werden immer geprüft) — nur
/// Vorauswahl, die genaue Prüfung macht der Aufrufer in Index-Reihenfolge.
#[derive(Default)]
struct BoxIndex {
grid: Option<Grid>,
wild: Vec<u32>,
}
impl BoxIndex {
fn build(boxes: Vec<(u32, f64, f64, f64, f64)>) -> BoxIndex {
let mut wild = Vec::new();
let mut fin = Vec::with_capacity(boxes.len());
let (mut a, mut b, mut c, mut d) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for e in boxes {
if e.1.is_finite() && e.2.is_finite() && e.3.is_finite() && e.4.is_finite() {
a = a.min(e.1);
b = b.min(e.2);
c = c.max(e.3);
d = d.max(e.4);
fin.push(e);
} else if !(e.3 < e.1 || e.4 < e.2) {
// NaN/unendlich (nicht leer): immer prüfen.
wild.push(e.0);
}
}
let grid = (!fin.is_empty()).then(|| Grid::build(&fin, fin.len(), a, b, c, d));
BoxIndex { grid, wild }
}
/// Einträge, deren Box den Kreis `(x, y, r)` berühren kann — aufsteigend, ohne Doppel.
fn candidates(&self, x: f64, y: f64, r: f64) -> Vec<u32> {
let mut out = self.wild.clone();
if let Some(g) = &self.grid {
g.visit(x, y, r, |k| out.push(k));
}
out.sort_unstable();
out.dedup();
out
}
}
/// Rand für Rundung bei Box-Tests: relativ zur Koordinatengrösse.
fn pad(v: &[f64]) -> f64 {
1e-9 * (1.0 + v.iter().fold(0.0f64, |m, x| m.max(x.abs())))
}
/// `pointSegDist` (Modell-Meter).
pub fn point_seg_dist(px: f64, py: f64, ax: f64, ay: f64, bx: f64, by: f64) -> f64 {
let dx = bx - ax;
let dy = by - ay;
let len2 = dx * dx + dy * dy;
let mut t = if len2 > 0.0 { ((px - ax) * dx + (py - ay) * dy) / len2 } else { 0.0 };
t = jsnum::max(0.0, jsnum::min(1.0, t));
hypot(&[px - (ax + t * dx), py - (ay + t * dy)])
}
/// `pointSegDistPx` (Client-Pixel).
pub fn point_seg_dist_px(px: f64, py: f64, ax: f64, ay: f64, bx: f64, by: f64) -> f64 {
let dx = bx - ax;
let dy = by - ay;
let len2 = dx * dx + dy * dy;
if len2 < 1e-9 {
return hypot(&[px - ax, py - ay]);
}
let mut t = ((px - ax) * dx + (py - ay) * dy) / len2;
t = jsnum::max(0.0, jsnum::min(1.0, t));
hypot(&[px - (ax + dx * t), py - (ay + dy * t)])
}
/// `pointInPolygon` (gerade/ungerade, wie `planView/geometry.ts`).
pub fn point_in_polygon(x: f64, y: f64, poly: &[f64]) -> bool {
let n = poly.len() / 2;
let mut inside = false;
let mut j = n.wrapping_sub(1);
for i in 0..n {
let (xi, yi, xj, yj) = (poly[2 * i], poly[2 * i + 1], poly[2 * j], poly[2 * j + 1]);
if (yi > y) != (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi {
inside = !inside;
}
j = i;
}
inside
}
/// Abbildung Modell → Client-Pixel: `toScreen` (·90, Y gespiegelt), dann `vbToClient`.
#[derive(Clone, Copy)]
pub struct ClientMap {
/// `left + offX`
pub left: f64,
/// `top + offY`
pub top: f64,
pub view_x: f64,
pub view_y: f64,
pub scale: f64,
}
impl ClientMap {
#[inline]
fn at(&self, x: f64, y: f64) -> (f64, f64) {
let vx = x * 90.0;
let vy = -y * 90.0;
(self.left + (vx - self.view_x) * self.scale, self.top + (vy - self.view_y) * self.scale)
}
}
struct Sym {
gi: u32,
mask: u16,
arc: bool,
seg: [f64; 4],
}
struct Ring {
gi: u32,
arc: bool,
cx: f64,
cy: f64,
r: f64,
a0: f64,
a1: f64,
filled: bool,
}
struct PolyEntry {
gi: u32,
mask: u16,
}
/// Index über einen zusammengesetzten Plan (besitzt seine Puffer).
pub struct PickIndex {
bufs: Vec<Rc<[u8]>>,
/// Abschnitte: (Puffer, von, erster Index im Plan).
parts: Vec<(usize, usize, usize)>,
count: usize,
segs: Option<Grid>,
polys: Vec<PolyEntry>,
poly_grid: Option<Grid>,
/// Polygone mit nicht endlichem Ausmass (immer geprüft).
poly_wild: Vec<u32>,
/// Symbol-Linien/-Bögen mit Pick-Id (Bogen: Sehne `from → to`).
sym: Vec<Sym>,
sym_ix: BoxIndex,
/// Kreise/Bögen der 2D-Zeichnung (nicht-leere `drawingId`).
rings: Vec<Ring>,
ring_ix: BoxIndex,
/// (Art, Id) → Indizes aufsteigend.
owners: HashMap<(u32, u32), Vec<u32>>,
interned: HashMap<String, u32>,
}
/// Bounding-Box, NaN ausgelassen (wie `f64::min`).
fn bbox(pts: &[f64]) -> (f64, f64, f64, f64) {
let (mut a, mut b, mut c, mut d) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for q in pts.chunks_exact(2) {
a = a.min(q[0]);
b = b.min(q[1]);
c = c.max(q[0]);
d = d.max(q[1]);
}
(a, b, c, d)
}
impl PickIndex {
/// Index bauen; `segs` = `[Puffer-Nr, von, bis, …]`, `bufs` = (Nr, Bytes). `None` bei Unsinn.
pub fn build(segs: &[f64], bufs: Vec<(u32, Rc<[u8]>)>) -> Option<PickIndex> {
if segs.len() % 3 != 0 {
return None;
}
let mut ix = PickIndex {
bufs: bufs.iter().map(|b| b.1.clone()).collect(),
parts: Vec::new(),
count: 0,
segs: None,
polys: Vec::new(),
poly_grid: None,
poly_wild: Vec::new(),
sym: Vec::new(),
sym_ix: BoxIndex::default(),
rings: Vec::new(),
ring_ix: BoxIndex::default(),
owners: HashMap::new(),
interned: HashMap::new(),
};
// Segment-Raster wie `buildSegmentIndex` (Ausmass mit Math.min/max, NaN steckt an).
let mut seg_boxes: Vec<(u32, f64, f64, f64, f64)> = Vec::new();
let (mut sminx, mut sminy, mut smaxx, mut smaxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
let mut poly_boxes: Vec<(u32, f64, f64, f64, f64)> = Vec::new();
let (mut pminx, mut pminy, mut pmaxx, mut pmaxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
let mut gi = 0usize;
for s in segs.chunks_exact(3) {
let nr = whole(s[0])? as u32;
let bi = bufs.iter().position(|b| b.0 == nr)?;
let (from, to) = (whole(s[1])?, whole(s[2])?);
let view = View::parse(&bufs[bi].1)?;
if from > to || to > view.len() {
return None;
}
ix.parts.push((bi, from, gi));
// String-Index → (Id-Nummer, nicht leer); einmal je Abschnitt.
let mut strs: HashMap<i64, (u32, bool)> = HashMap::new();
for i in from..to {
let g = gi as u32;
gi += 1;
let at = view.rec_at(i)?;
let tag = whole(view.word(at)?)? as u32;
let flags = whole(view.word(at + 1)?)? as u32;
let pk = whole(view.word(at + 2)?)? as u32;
// Pick-Ids: (Art, String-Index).
let ids: Vec<(u32, f64)> = if flags & F_IDS != 0 {
pick_ids(&view, &view.rec(i)?)?
} else if pk > 0 {
vec![(pk, view.word(at + 3)?)]
} else {
Vec::new()
};
let mut mask: u16 = 0;
let mut drawing: Option<u32> = None;
let mut owned: Vec<(u32, u32)> = Vec::with_capacity(ids.len());
for &(kind, si) in &ids {
let key = si as i64;
let (id, non_empty) = match strs.get(&key) {
Some(&v) => v,
None => {
let text = view.string(whole(si)?)?;
let ne = !text.is_empty();
let n = ix.interned.len() as u32;
let id = *ix.interned.entry(text).or_insert(n);
strs.insert(key, (id, ne));
(id, ne)
}
};
if non_empty {
mask |= 1 << kind;
}
if kind == 2 {
drawing = Some(id);
}
owned.push((kind, id));
}
// Besitzer (wie `buildOwnerIndex`: mit drawingId nur diese).
match drawing {
Some(id) => ix.owners.entry((2, id)).or_default().push(g),
None => {
for (kind, id) in owned {
ix.owners.entry((kind, id)).or_default().push(g);
}
}
}
let f = |k: usize| view.word(at + 4 + k);
match tag {
T_LINE => {
if mask & (1 << 2) != 0 {
let (ax, ay, bx, by) = (f(4)?, f(5)?, f(6)?, f(7)?);
sminx = jsnum::min(sminx, jsnum::min(ax, bx));
smaxx = jsnum::max(smaxx, jsnum::max(ax, bx));
sminy = jsnum::min(sminy, jsnum::min(ay, by));
smaxy = jsnum::max(smaxy, jsnum::max(ay, by));
seg_boxes.push((g, jsnum::min(ax, bx), jsnum::min(ay, by), jsnum::max(ax, bx), jsnum::max(ay, by)));
}
let m = mask & ((1 << 4) | (1 << 5));
if m != 0 {
ix.sym.push(Sym { gi: g, mask: m, arc: false, seg: [f(4)?, f(5)?, f(6)?, f(7)?] });
}
}
T_ARC => {
let m = mask & ((1 << 4) | (1 << 5));
if m != 0 {
ix.sym.push(Sym { gi: g, mask: m, arc: true, seg: [f(6)?, f(7)?, f(8)?, f(9)?] });
}
}
T_CIRCLE => {
if mask & (1 << 2) != 0 {
// `fill !== "none"` (fehlende Füllung zählt als gefüllt, wie in TS).
let fi = f(0)?;
let filled = !(fi >= 0.0 && view.string(whole(fi)?)? == "none");
ix.rings.push(Ring { gi: g, arc: false, cx: f(4)?, cy: f(5)?, r: f(6)?, a0: 0.0, a1: 0.0, filled });
}
}
T_DRAWING_ARC => {
if mask & (1 << 2) != 0 {
ix.rings.push(Ring { gi: g, arc: true, cx: f(3)?, cy: f(4)?, r: f(5)?, a0: f(6)?, a1: f(7)?, filled: false });
}
}
T_POLYGON => {
let pts = view.pool(whole(f(5)?)?, whole(f(6)?)?.checked_mul(2)?)?;
let (a, b, c, d) = bbox(&pts);
ix.polys.push(PolyEntry { gi: g, mask });
let k = (ix.polys.len() - 1) as u32;
if a.is_finite() && b.is_finite() && c.is_finite() && d.is_finite() {
pminx = pminx.min(a);
pminy = pminy.min(b);
pmaxx = pmaxx.max(c);
pmaxy = pmaxy.max(d);
// Etwas Rand: Punkt-in-Polygon rechnet mit Rundung.
let e = 1e-9 * (1.0 + a.abs().max(b.abs()).max(c.abs()).max(d.abs()));
poly_boxes.push((k, a - e, b - e, c + e, d + e));
} else if c >= a && d >= b {
ix.poly_wild.push(k);
}
}
_ => {}
}
}
}
ix.count = gi;
if !seg_boxes.is_empty() {
ix.segs = Some(Grid::build(&seg_boxes, seg_boxes.len(), sminx, sminy, smaxx, smaxy));
}
if !poly_boxes.is_empty() {
ix.poly_grid = Some(Grid::build(&poly_boxes, poly_boxes.len(), pminx, pminy, pmaxx, pmaxy));
}
ix.sym_ix = BoxIndex::build(
ix.sym
.iter()
.enumerate()
.map(|(k, s)| {
let [ax, ay, bx, by] = s.seg;
let e = pad(&s.seg);
(k as u32, ax.min(bx) - e, ay.min(by) - e, ax.max(bx) + e, ay.max(by) + e)
})
.collect(),
);
ix.ring_ix = BoxIndex::build(
ix.rings
.iter()
.enumerate()
.map(|(k, g)| {
let r = g.r.abs();
let e = pad(&[g.cx, g.cy, r]);
(k as u32, g.cx - r - e, g.cy - r - e, g.cx + r + e, g.cy + r + e)
})
.collect(),
);
Some(ix)
}
pub fn len(&self) -> usize {
self.count
}
pub fn is_empty(&self) -> bool {
self.count == 0
}
/// Puffer und Eintrag zu einem Plan-Index.
fn locate(&self, gi: u32) -> Option<(View<'_>, usize)> {
let gi = gi as usize;
let p = match self.parts.binary_search_by(|e| e.2.cmp(&gi)) {
Ok(k) => {
// Leere Abschnitte überspringen: der letzte mit diesem Start.
let mut k = k;
while k + 1 < self.parts.len() && self.parts[k + 1].2 == gi {
k += 1;
}
k
}
Err(k) => k.checked_sub(1)?,
};
let (bi, from, start) = self.parts[p];
Some((View::parse(&self.bufs[bi])?, from + gi - start))
}
/// Feste Felder ab `k` eines Eintrags.
fn fields<const N: usize>(&self, gi: u32, k: usize) -> Option<[f64; N]> {
let (v, i) = self.locate(gi)?;
let at = v.rec_at(i)? + 4 + k;
let mut out = [0.0; N];
for (j, o) in out.iter_mut().enumerate() {
*o = v.word(at + j)?;
}
Some(out)
}
fn line(&self, gi: u32) -> Option<[f64; 4]> {
self.fields::<4>(gi, 4)
}
fn polygon_pts(&self, gi: u32) -> Option<Vec<f64>> {
let (v, i) = self.locate(gi)?;
let at = v.rec_at(i)? + 4;
v.pool(whole(v.word(at + 5)?)?, whole(v.word(at + 6)?)?.checked_mul(2)?)
}
/// Nächstes Segment einer 2D-Zeichnung zu `(x, y)` mit Abstand < `max_dist` (wie `nearestSegment`).
pub fn nearest_segment(&self, x: f64, y: f64, max_dist: f64) -> Option<(u32, f64)> {
let g = self.segs.as_ref()?;
let mut best = None;
let mut best_d = max_dist;
g.visit(x, y, max_dist, |i| {
if let Some([ax, ay, bx, by]) = self.line(i) {
let d = point_seg_dist(x, y, ax, ay, bx, by);
if d < best_d {
best_d = d;
best = Some(i);
}
}
});
best.map(|i| (i, best_d))
}
/// Alle Segmente mit Abstand < `max_dist`, nächste zuerst (wie `segmentsNear`).
pub fn segments_near(&self, x: f64, y: f64, max_dist: f64) -> Vec<(u32, f64)> {
let Some(g) = self.segs.as_ref() else { return Vec::new() };
let mut found: Vec<(u32, f64)> = Vec::new();
let mut pos: HashMap<u32, usize> = HashMap::new();
g.visit(x, y, max_dist, |i| {
if let Some([ax, ay, bx, by]) = self.line(i) {
let d = point_seg_dist(x, y, ax, ay, bx, by);
if d < max_dist {
match pos.get(&i) {
Some(&k) => found[k].1 = d,
None => {
pos.insert(i, found.len());
found.push((i, d));
}
}
}
}
});
// Stabil nach Abstand (Gleichstand: Einfüge-Reihenfolge, wie `Array.sort`).
found.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
found
}
/// Polygone, die `(x, y)` enthalten, mit Pick-Maske (0 = alle Polygone), absteigend nach Index.
pub fn polygons_at(&self, x: f64, y: f64, mask: u16) -> Vec<u32> {
let mut cand: Vec<u32> = self.poly_wild.clone();
if let Some(g) = &self.poly_grid {
g.visit(x, y, 0.0, |k| cand.push(k));
}
cand.sort_unstable();
cand.dedup();
let mut out: Vec<u32> = Vec::new();
for k in cand {
let p = &self.polys[k as usize];
if mask != 0 && p.mask & mask == 0 {
continue;
}
if let Some(pts) = self.polygon_pts(p.gi) {
if point_in_polygon(x, y, &pts) {
out.push(p.gi);
}
}
}
out.sort_unstable_by(|a, b| b.cmp(a));
out
}
/// Nächste Symbol-Linie (bzw. Bogen über die Sehne `from → to`) mit einer Pick-Id aus
/// `line_mask` bzw. `arc_mask`, in Client-Pixeln < `max_px` (erster bei Gleichstand).
pub fn nearest_symbol_px(&self, line_mask: u16, arc_mask: u16, map: ClientMap, cx: f64, cy: f64, max_px: f64) -> Option<u32> {
let mut best = None;
let mut best_d = max_px;
// Vorauswahl im Modell: `max_px` Pixel = `max_px / (90·scale)` Meter (grosszügig).
let cand: Vec<u32> = {
let (mx, my) = ((cx - map.left) / map.scale / 90.0 + map.view_x / 90.0, -((cy - map.top) / map.scale + map.view_y) / 90.0);
let r = max_px / (90.0 * map.scale.abs());
if mx.is_finite() && my.is_finite() && r.is_finite() {
self.sym_ix.candidates(mx, my, r * (1.0 + 1e-6) + pad(&[mx, my]))
} else {
(0..self.sym.len() as u32).collect()
}
};
for k in cand {
let s = &self.sym[k as usize];
if s.mask & (if s.arc { arc_mask } else { line_mask }) == 0 {
continue;
}
let gi = s.gi;
let [ax, ay, bx, by] = s.seg;
let (a0, a1) = map.at(ax, ay);
let (b0, b1) = map.at(bx, by);
let d = point_seg_dist_px(cx, cy, a0, a1, b0, b1);
if d < best_d {
best_d = d;
best = Some(gi);
}
}
best
}
/// Kreise/Bögen der 2D-Zeichnung mit Ring-Abstand < `tol_px` (Pixel), in Plan-Reihenfolge:
/// (Index, Abstand in Pixeln) — wie `distToDrawingRing`.
pub fn rings_near(&self, x: f64, y: f64, px_per_m: f64, tol_px: f64) -> Vec<(u32, f64)> {
let tau = std::f64::consts::PI * 2.0;
let mut out = Vec::new();
// Vorauswahl: Ring-Abstand < `tol_px` Pixel liegt innerhalb der Kreis-Box + `tol_px/px_per_m`.
let rq = tol_px / px_per_m;
let cand: Vec<u32> = if rq.is_finite() && rq >= 0.0 && x.is_finite() && y.is_finite() {
self.ring_ix.candidates(x, y, rq * (1.0 + 1e-6) + pad(&[x, y]))
} else {
(0..self.rings.len() as u32).collect()
};
for k in cand {
let g = &self.rings[k as usize];
let dist_c = hypot(&[x - g.cx, y - g.cy]);
if g.arc {
let mut sweep = (((g.a1 - g.a0) % tau) + tau) % tau;
if sweep == 0.0 || sweep.is_nan() {
sweep = tau;
}
let ang = jsnum::atan2(y - g.cy, x - g.cx);
let rel = (((ang - g.a0) % tau) + tau) % tau;
let ang_tol = if dist_c > 1e-6 { tol_px / (px_per_m * jsnum::max(dist_c, 0.05)) } else { f64::INFINITY };
if rel > sweep + ang_tol && tau - rel > ang_tol {
continue;
}
}
let dm = if g.filled { jsnum::max(0.0, dist_c - g.r) } else { (dist_c - g.r).abs() };
let d = dm * px_per_m;
if d < tol_px {
out.push((g.gi, d));
}
}
out
}
/// Alle Primitive, deren Id der Art `kind` in `ids` liegt, aufsteigend (wie `ownedBy`).
pub fn owned_by(&self, kind: u32, ids: &[&str]) -> Vec<u32> {
let mut hits: Vec<u32> = Vec::new();
for id in ids {
if let Some(n) = self.interned.get(*id) {
if let Some(l) = self.owners.get(&(kind, *n)) {
hits.extend_from_slice(l);
}
}
}
hits.sort_unstable();
hits
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn punkt_in_polygon_und_abstand() {
let sq = [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0];
assert!(point_in_polygon(0.5, 0.5, &sq));
assert!(!point_in_polygon(1.5, 0.5, &sq));
assert_eq!(point_seg_dist(0.5, 1.0, 0.0, 0.0, 1.0, 0.0), 1.0);
assert_eq!(point_seg_dist_px(3.0, 4.0, 0.0, 0.0, 0.0, 0.0), 5.0);
}
}
+1
View File
@@ -33,6 +33,7 @@ mod curves;
mod hatch;
mod skeleton;
mod plan_scene;
mod plan_pick;
use wasm_bindgen::prelude::wasm_bindgen;
+76
View File
@@ -0,0 +1,76 @@
//! Bindungen der Auswahl (`crate::plan_pick`). Ein Index wird einmal je Plan gebaut
//! (`pick_index_build`, Abschnitte wie `plan_parts`) und bleibt, bis TS ihn freigibt
//! (`pick_index_release`); er hält seine Puffer selbst, Verdrängen im Puffer-Speicher stört ihn
//! nicht. Unbekannter Index oder kaputte Eingabe → leeres Ergebnis bzw. −1, nie Panic.
use crate::plan_pick::{ClientMap, PickIndex};
use std::cell::RefCell;
use wasm_bindgen::prelude::wasm_bindgen;
thread_local! {
static INDEXES: RefCell<(u32, Vec<(u32, PickIndex)>)> = const { RefCell::new((0, Vec::new())) };
}
fn with<R>(id: u32, f: impl FnOnce(&PickIndex) -> R) -> Option<R> {
INDEXES.with(|h| h.borrow().1.iter().find(|e| e.0 == id).map(|e| f(&e.1)))
}
/// Index über die Abschnitte `[Puffer-Nr, von, bis, …]` bauen; Nummer ≥ 1, 0 = Fehler (Puffer
/// fehlt oder kaputt — TS legt neu ab und baut nochmals).
#[wasm_bindgen]
pub fn pick_index_build(segs: &[f64]) -> u32 {
let Some(bufs) = super::plan_buf::held_for_segs(segs) else { return 0 };
let Some(ix) = PickIndex::build(segs, bufs) else { return 0 };
INDEXES.with(|h| {
let mut h = h.borrow_mut();
h.0 = h.0.wrapping_add(1).max(1);
let id = h.0;
h.1.push((id, ix));
id
})
}
#[wasm_bindgen]
pub fn pick_index_release(id: u32) {
INDEXES.with(|h| h.borrow_mut().1.retain(|e| e.0 != id));
}
/// Nächstes 2D-Zeichnungs-Segment als `[Index, Abstand]`, leer ohne Treffer.
#[wasm_bindgen]
pub fn pick_nearest_segment(id: u32, x: f64, y: f64, max_dist: f64) -> Vec<f64> {
with(id, |ix| ix.nearest_segment(x, y, max_dist)).flatten().map_or(Vec::new(), |(i, d)| vec![i as f64, d])
}
/// Segmente im Umkreis als `[Index, Abstand, …]`, nächste zuerst.
#[wasm_bindgen]
pub fn pick_segments_near(id: u32, x: f64, y: f64, max_dist: f64) -> Vec<f64> {
with(id, |ix| ix.segments_near(x, y, max_dist).into_iter().flat_map(|(i, d)| [i as f64, d]).collect()).unwrap_or_default()
}
/// Polygone unter dem Punkt (Maske der Pick-Arten, 0 = alle), oberstes zuerst.
#[wasm_bindgen]
pub fn pick_polygons_at(id: u32, x: f64, y: f64, mask: u32) -> Vec<u32> {
with(id, |ix| ix.polygons_at(x, y, mask as u16)).unwrap_or_default()
}
/// Nächste Symbol-Linie/-Bogen in Client-Pixeln (Abbildung `left+offX, top+offY, view.x,
/// view.y, scale`) oder −1.
#[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
pub fn pick_nearest_symbol_px(id: u32, line_mask: u32, arc_mask: u32, left: f64, top: f64, view_x: f64, view_y: f64, scale: f64, cx: f64, cy: f64, max_px: f64) -> f64 {
let map = ClientMap { left, top, view_x, view_y, scale };
with(id, |ix| ix.nearest_symbol_px(line_mask as u16, arc_mask as u16, map, cx, cy, max_px)).flatten().map_or(-1.0, |i| i as f64)
}
/// Kreise/Bögen der 2D-Zeichnung nahe am Punkt: `[Index, Abstand px, …]` in Plan-Reihenfolge.
#[wasm_bindgen]
pub fn pick_rings_near(id: u32, x: f64, y: f64, px_per_m: f64, tol_px: f64) -> Vec<f64> {
with(id, |ix| ix.rings_near(x, y, px_per_m, tol_px).into_iter().flat_map(|(i, d)| [i as f64, d]).collect()).unwrap_or_default()
}
/// Primitive der Ids (jede mit `\0` davor) der Pick-Art `kind`, aufsteigend.
#[wasm_bindgen]
pub fn pick_owned_by(id: u32, kind: u32, ids: &str) -> Vec<u32> {
let list: Vec<&str> = ids.split('\0').skip(1).collect();
with(id, |ix| ix.owned_by(kind, &list)).unwrap_or_default()
}
+3 -11
View File
@@ -264,18 +264,10 @@ export {
} from "../plan/planView/geometry";
export {
type ClientMap,
type OwnerField,
type OwnerIndex,
buildOwnerIndex,
ownedBy,
} from "../plan/planView/ownerIndex";
export {
buildSegmentIndex,
nearestSegment,
pointSegDist as pointSegDist__plan_planView_segmentIndex,
segmentsNear,
} from "../plan/planView/segmentIndex";
PlanPickIndex,
} from "../plan/planView/planPick";
export {
marqueeHitUnderlay,
+4 -1
View File
@@ -184,6 +184,8 @@ export interface EncodeOptions {
* einen Puffer nicht lesen. Standard `true`.
*/
textJson?: boolean;
/** `false`: Schraffuren ohne JSON (nur das Hatch-Format, wie `lean`). Standard `true`. */
hatchJson?: boolean;
/** Gruppen `[start, end)` in den Kopf schreiben. */
groups?: ReadonlyArray<readonly [number, number]>;
bounds?: readonly [number, number, number, number];
@@ -193,6 +195,7 @@ export interface EncodeOptions {
export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions = {}): Uint8Array {
const lean = opts.lean === true;
const textJson = opts.textJson !== false;
const hatchJson = !lean && opts.hatchJson !== false;
const strParts: string[] = [];
const strTab = new F64Writer(64);
const strIdx = new Map<string, number>();
@@ -217,7 +220,7 @@ export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions =
let i = hatchIdx.get(h);
if (i === undefined) {
i = hatchIdx.size;
hatchW.push(lean ? -1 : str(JSON.stringify(h)));
hatchW.push(hatchJson ? str(JSON.stringify(h)) : -1);
writeHatch(hatchW, h, str(h.color));
hatchIdx.set(h, i);
}
+5 -3
View File
@@ -95,7 +95,7 @@ export function planParts(plan: Plan, texts = false): PlanParts {
at = r.end;
}
gap(prims.length);
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts }), hold: 0 } : null;
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: false }), hold: 0 } : null;
const segs: number[] = [];
let gi = 0;
let ri = 0;
@@ -128,8 +128,10 @@ export function greyedFlat(plan: Plan): Float64Array {
return out;
}
/** Abschnitte mit den Kern-Nummern der Puffer (legt fehlende ab). */
function heldSegs(parts: PlanParts, fresh: boolean): Float64Array {
/**
* Abschnitte mit den Kern-Nummern der Puffer; legt fehlende ab (`fresh`: auch verdrängte).
*/
export function heldSegs(parts: PlanParts, fresh: boolean): Float64Array {
const c = core();
for (const b of parts.bufs) if (!b.hold || (fresh && !c.plan_buf_is_held(b.hold))) b.hold = c.plan_buf_hold(b.bytes);
const s = new Float64Array(parts.segs.length);
-44
View File
@@ -1,44 +0,0 @@
import { describe, it, expect } from "vitest";
import type { Primitive } from "../generatePlan";
import { buildOwnerIndex, ownedBy } from "./ownerIndex";
const line = (drawingId: string): Primitive =>
({ kind: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 }, cls: "draw2d", weightMm: 0.1, drawingId }) as Primitive;
const poly = (extra: Record<string, string>): Primitive =>
({ kind: "polygon", pts: [], fill: "#fff", stroke: "#000", strokeWidthMm: 0.1, ...extra }) as unknown as Primitive;
describe("ownerIndex", () => {
const prims: Primitive[] = [
poly({ wallId: "w1" }),
line("d1"),
poly({ roomId: "r1" }),
line("d2"),
poly({ wallId: "w2", openingId: "o1" }),
line("d1"),
];
const idx = buildOwnerIndex(prims);
it("findet Primitive je Besitzer-ID in Plan-Reihenfolge", () => {
expect(ownedBy(idx, prims, "drawingId", ["d1"])).toEqual([prims[1], prims[5]]);
expect(ownedBy(idx, prims, "wallId", ["w2", "w1"])).toEqual([prims[0], prims[4]]);
expect(ownedBy(idx, prims, "roomId", ["r1"])).toEqual([prims[2]]);
});
it("ein Primitiv kann mehrere Besitzer-Felder tragen (ausser Zeichnungs-Primitive)", () => {
expect(ownedBy(idx, prims, "openingId", ["o1"])).toEqual([prims[4]]);
expect(ownedBy(idx, prims, "wallId", ["w2"])).toEqual([prims[4]]);
});
it("liefert nichts für unbekannte IDs/leere Mengen und gleicht dem früheren filter()", () => {
expect(ownedBy(idx, prims, "drawingId", ["x"])).toEqual([]);
expect(ownedBy(idx, prims, "wallId", [])).toEqual([]);
const ids = new Set(["d2", "w1"]);
const viaFilter = prims.filter(
(p) => ids.has((p as any).drawingId) || ids.has((p as any).wallId),
);
const viaIndex = [...ownedBy(idx, prims, "drawingId", ids), ...ownedBy(idx, prims, "wallId", ids)].sort(
(a, b) => prims.indexOf(a) - prims.indexOf(b),
);
expect(viaIndex).toEqual(viaFilter);
});
});
-66
View File
@@ -1,66 +0,0 @@
// Besitzer-Index über die Primitive eines Plans: welche Primitive gehören zu
// Wand/Decke/Raum/Zeichnung/…-ID X? Die Auswahl-Hervorhebung in PlanView hat
// das bisher mit je einem `plan.primitives.filter(...)` PRO Elementart gelöst —
// zehn Durchgänge über alle Primitive bei jeder Plan-Änderung (bei einem
// Kataster-Import 3,7 Mio. → ~300 ms pro Änderung). Der Index braucht EINEN
// Durchgang je Plan; danach kostet jede Abfrage nur die Treffer.
import type { Primitive } from "../generatePlan";
export const OWNER_FIELDS = [
"wallId",
"drawingId",
"ceilingId",
"openingId",
"stairId",
"roomId",
"roofId",
"contextObjectId",
"sectionLineId",
"extrudedSolidId",
"columnId",
] as const;
export type OwnerField = (typeof OWNER_FIELDS)[number];
export type OwnerIndex = Record<OwnerField, Map<string, number[]>>;
export function buildOwnerIndex(prims: readonly Primitive[]): OwnerIndex {
const index = Object.fromEntries(OWNER_FIELDS.map((f) => [f, new Map<string, number[]>()])) as OwnerIndex;
const add = (field: OwnerField, id: string, i: number) => {
const m = index[field];
const list = m.get(id);
if (list) list.push(i);
else m.set(id, [i]);
};
for (let i = 0; i < prims.length; i++) {
const rec = prims[i] as unknown as Record<OwnerField, unknown>;
// Schnellpfad: Primitive aus 2D-Zeichnungen (der Massenfall) tragen NUR eine
// drawingId, nie eine andere Besitzer-ID (s. generatePlan/drawing2d.ts).
const did = rec.drawingId;
if (typeof did === "string") {
add("drawingId", did, i);
continue;
}
for (const f of OWNER_FIELDS) {
const v = rec[f];
if (typeof v === "string") add(f, v, i);
}
}
return index;
}
/** Primitive, deren `field` in `ids` liegt — in Plan-Reihenfolge (wie `filter`). */
export function ownedBy(
index: OwnerIndex,
prims: readonly Primitive[],
field: OwnerField,
ids: Iterable<string>,
): Primitive[] {
const hits: number[] = [];
for (const id of ids) {
const list = index[field].get(id);
if (list) for (const i of list) hits.push(i);
}
hits.sort((a, b) => a - b);
return hits.map((i) => prims[i]);
}
+132
View File
@@ -0,0 +1,132 @@
// Auswahl über den Kern ([K3d], `core/src/plan_pick.rs`): nächstes Segment, Segmente im Umkreis,
// Polygone unter dem Punkt (mit Pick-Feld), Symbol-Linien in Pixeln, Kreis-/Bogen-Ringe und
// Besitzer — gegen einfache lineare Suchen. (Gleichheit zur früheren TS-Fassung — segmentIndex,
// ownerIndex, PlanView-Schleifen — mit Beispielprojekt, 150 Zufallsplänen und grossem Projekt
// geprüft, s. TODO [K3d].)
import { describe, it, expect } from "vitest";
import type { Plan, Primitive } from "../generatePlan";
import { generatePlan } from "../generatePlan";
import { PlanPickIndex } from "./planPick";
import { pointInPolygon } from "./geometry";
import { sampleProject } from "../../model/sampleProject";
import { flattenCategories } from "../../model/types";
const plan = (primitives: Primitive[]): Plan => ({ primitives, bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 } });
const line = (ax: number, ay: number, bx: number, by: number, drawingId: string | undefined = "d"): Primitive =>
({ kind: "line", a: { x: ax, y: ay }, b: { x: bx, y: by }, cls: "draw2d", weightMm: 0.18, drawingId }) as Primitive;
const poly = (pts: Array<[number, number]>, extra: Record<string, string> = {}): Primitive =>
({ kind: "polygon", pts: pts.map(([x, y]) => ({ x, y })), fill: "#fff", stroke: "#000", strokeWidthMm: 0.1, ...extra }) as unknown as Primitive;
function bruteForce(prims: Primitive[], m: { x: number; y: number }, maxDist: number): number | null {
let best: number | null = null;
let bestDist = maxDist;
prims.forEach((p, i) => {
if (p.kind !== "line" || !p.drawingId) return;
const dx = p.b.x - p.a.x, dy = p.b.y - p.a.y;
const len2 = dx * dx + dy * dy;
const t = len2 > 0 ? Math.max(0, Math.min(1, ((m.x - p.a.x) * dx + (m.y - p.a.y) * dy) / len2)) : 0;
const d = Math.hypot(m.x - (p.a.x + t * dx), m.y - (p.a.y + t * dy));
if (d < bestDist) {
bestDist = d;
best = i;
}
});
return best;
}
describe("PlanPickIndex: Segmente", () => {
it("nächstes Segment wie die lineare Suche (Zufallsdaten, Überlauf-Segment, Nicht-2D-Strich)", () => {
let seed = 1;
const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
const prims: Primitive[] = [];
for (let i = 0; i < 20000; i++) {
const x = rnd() * 1000, y = rnd() * 1000;
prims.push(line(x, y, x + (rnd() - 0.5) * 20, y + (rnd() - 0.5) * 20));
}
prims.push(line(-5000, -5000, 5000, 5000));
prims.push(line(500, 500, 501, 501, undefined));
const ix = new PlanPickIndex(plan(prims));
for (let k = 0; k < 500; k++) {
const m = { x: rnd() * 1100 - 50, y: rnd() * 1100 - 50 };
expect(ix.nearestSegment(m, 3)?.i ?? null).toBe(bruteForce(prims, m, 3));
}
ix.release();
});
it("nichts ausserhalb der Toleranz, nichts ohne 2D-Linien", () => {
const ix = new PlanPickIndex(plan([line(0, 0, 10, 0)]));
expect(ix.nearestSegment({ x: 5, y: 0.5 }, 1)).toEqual({ i: 0, dist: 0.5 });
expect(ix.nearestSegment({ x: 5, y: 2 }, 1)).toBeNull();
expect(ix.nearestSegment({ x: 500, y: 500 }, 1)).toBeNull();
expect(new PlanPickIndex(plan([])).nearestSegment({ x: 0, y: 0 }, 1)).toBeNull();
});
it("alle Segmente in Reichweite, nächste zuerst", () => {
const prims: Primitive[] = [line(0, 0, 10, 0, "a"), line(0, 0.5, 10, 0.5, "b"), line(0, 5, 10, 5, "c"), line(-2000, -2000, 2000, 2000, "long")];
for (let i = 0; i < 300; i++) prims.push(line(50 + i, 50, 51 + i, 51, `f${i}`));
const hits = new PlanPickIndex(plan(prims)).segmentsNear({ x: 5, y: 0.2 }, 1);
expect(hits.map((h) => (prims[h.i] as { drawingId?: string }).drawingId)).toEqual(["a", "b"]);
expect(hits[0].dist).toBeLessThanOrEqual(hits[1].dist);
});
});
describe("PlanPickIndex: Polygone, Symbole, Ringe, Besitzer", () => {
const prims: Primitive[] = [
poly([[0, 0], [4, 0], [4, 4], [0, 4]], { roomId: "r1" }),
poly([[1, 1], [3, 1], [3, 3], [1, 3]], { wallId: "w1", openingId: "o1" }),
line(0, 0, 1, 0, "d1"),
poly([[2, 2], [5, 2], [5, 5], [2, 5]], { stairId: "s1" }),
{ kind: "line", a: { x: 10, y: 0 }, b: { x: 10, y: 5 }, cls: "door-leaf", weightMm: 0.25, openingId: "o2" } as Primitive,
{ kind: "drawingCircle", center: { x: 20, y: 0 }, r: 1, fill: "none", stroke: "#000", weightMm: 0.25, drawingId: "c1" } as Primitive,
{ kind: "drawingCircle", center: { x: 30, y: 0 }, r: 1, fill: "#f00", stroke: "#000", weightMm: 0.25, drawingId: "c2" } as Primitive,
line(0, 0, 1, 0, "d1"),
poly([[0, 0], [1, 0], [1, 1]], { roomId: "" }),
];
const ix = new PlanPickIndex(plan(prims));
it("Polygone unter dem Punkt: oberstes zuerst, mit Feld-Filter (leere Id zählt nicht)", () => {
const m = { x: 2.5, y: 2.5 };
const all = prims.flatMap((p, i) => (p.kind === "polygon" && pointInPolygon(m, p.pts) ? [i] : [])).reverse();
expect(ix.polygonsAt(m)).toEqual(all);
expect(ix.topPolygon(m)).toBe(3);
expect(ix.topPolygon(m, "roomId")).toBe(0);
expect(ix.bottomPolygon(m, "openingId")).toBe(1);
expect(ix.topPolygon({ x: 0.8, y: 0.2 }, "roomId")).toBe(0);
expect(ix.topPolygon({ x: 50, y: 50 })).toBeNull();
});
it("Symbol-Linie in Client-Pixeln", () => {
const map = { left: 0, top: 0, viewX: 0, viewY: 0, scale: 1 };
// Linie bei x = 10 m → 900 px; Punkt 3 px daneben.
expect(ix.nearestSymbolPx(["openingId"], [], map, { x: 903, y: -200 }, 6)).toBe(4);
expect(ix.nearestSymbolPx(["openingId"], [], map, { x: 910, y: -200 }, 6)).toBeNull();
expect(ix.nearestSymbolPx(["stairId"], [], map, { x: 903, y: -200 }, 6)).toBeNull();
});
it("Ringe: leerer Kreis nur am Rand, gefüllter auch innen", () => {
expect(ix.ringsNear({ x: 21.01, y: 0 }, 100, 6).map((r) => r.i)).toEqual([5]);
expect(ix.ringsNear({ x: 20, y: 0 }, 100, 6)).toEqual([]);
expect(ix.ringsNear({ x: 30, y: 0 }, 100, 6)).toEqual([{ i: 6, dpx: 0 }]);
});
it("Besitzer in Plan-Reihenfolge (Zeichnungs-Primitive nur über drawingId)", () => {
expect(ix.ownedBy("drawingId", ["d1"])).toEqual([prims[2], prims[7]]);
expect(ix.ownedBy("wallId", ["w1"])).toEqual([prims[1]]);
expect(ix.ownedBy("openingId", ["o1", "o2"])).toEqual([prims[1], prims[4]]);
expect(ix.ownedBy("roomId", [""])).toEqual([prims[8]]);
expect(ix.ownedBy("roomId", ["x"])).toEqual([]);
expect(ix.ownedBy("wallId", [])).toEqual([]);
});
it("Beispielprojekt: Kern-Abschnitte und eigener Puffer gemischt", () => {
const codes = new Set(flattenCategories(sampleProject.layers).map((c) => c.code));
const p = generatePlan(sampleProject, "eg", codes);
const pi = new PlanPickIndex(p);
const wall = p.primitives.findIndex((q) => q.kind === "polygon" && !!q.wallId);
const w = p.primitives[wall] as Extract<Primitive, { kind: "polygon" }>;
expect(pi.ownedBy("wallId", [w.wallId!])).toEqual(p.primitives.filter((q) => (q as { wallId?: string }).wallId === w.wallId));
pi.release();
});
});
+149
View File
@@ -0,0 +1,149 @@
// Auswahl/Picken im Grundriss über den Kern ([K3d], `src-tauri/core/src/plan_pick.rs`): ein
// räumlicher Index je Plan (2D-Zeichenlinien, Polygone, Symbol-Linien, Kreise/Bögen, Besitzer),
// gebaut direkt aus den Plan-Puffern (`planParts.ts`). TS fragt nur ab; Ergebnisse sind Indizes in
// `plan.primitives`. Ersetzt `segmentIndex.ts`, `ownerIndex.ts` und die Schleifen über alle
// Primitive bei jeder Mausbewegung (Treffer, Raum/Dach/Treppe/Öffnung …).
//
// Lebensdauer: der Index liegt im Kern, bis {@link PlanPickIndex.release} ihn freigibt (PlanView
// gibt den alten frei, sobald ein neuer Plan einen neuen braucht).
import type { Vec2 } from "../../model/types";
import type { Plan, Primitive } from "../generatePlan";
import { heldSegs, planParts } from "../planParts";
import { core } from "../../engine/coreWasm";
/** Pick-Felder eines Primitivs (Besitzer-Ids). */
export const OWNER_FIELDS = [
"wallId",
"drawingId",
"ceilingId",
"openingId",
"stairId",
"roomId",
"roofId",
"contextObjectId",
"sectionLineId",
"extrudedSolidId",
"columnId",
] as const;
export type OwnerField = (typeof OWNER_FIELDS)[number];
/** Pick-Art im Plan-Puffer (s. `plan_buf.rs`). */
const KIND: Record<OwnerField, number> = {
wallId: 1,
drawingId: 2,
ceilingId: 3,
openingId: 4,
stairId: 5,
roomId: 6,
extrudedSolidId: 7,
contextObjectId: 8,
columnId: 9,
roofId: 10,
sectionLineId: 11,
};
/** Bit-Maske der Felder (0 = keine Einschränkung). */
const mask = (fields: readonly OwnerField[]): number => fields.reduce((m, f) => m | (1 << KIND[f]), 0);
/** Abbildung Modell → Client-Pixel (`toScreen` + `vbToClient` der PlanView). */
export interface ClientMap {
/** `rect.left + offX` */
left: number;
/** `rect.top + offY` */
top: number;
viewX: number;
viewY: number;
scale: number;
}
export class PlanPickIndex {
private id = 0;
readonly prims: readonly Primitive[];
constructor(private readonly plan: Plan) {
this.prims = plan.primitives;
}
/** Kern-Index (lazy beim ersten Abfragen gebaut). */
private ix(): number {
if (this.id) return this.id;
const c = core();
const parts = planParts(this.plan);
this.id = c.pick_index_build(heldSegs(parts, false));
if (!this.id) this.id = c.pick_index_build(heldSegs(parts, true));
return this.id;
}
/** Kern-Index freigeben (danach baut eine Abfrage ihn neu). */
release(): void {
if (this.id) core().pick_index_release(this.id);
this.id = 0;
}
/**
* Nächstes Segment einer 2D-Zeichnung (`line` mit `drawingId`) mit Abstand < `maxDist` (Meter):
* Index und Abstand, oder null.
*/
nearestSegment(m: Vec2, maxDist: number): { i: number; dist: number } | null {
const f = core().pick_nearest_segment(this.ix(), m.x, m.y, maxDist);
return f.length === 2 ? { i: f[0], dist: f[1] } : null;
}
/** Alle solchen Segmente mit Abstand < `maxDist`, nächste zuerst. */
segmentsNear(m: Vec2, maxDist: number): Array<{ i: number; dist: number }> {
const f = core().pick_segments_near(this.ix(), m.x, m.y, maxDist);
const out: Array<{ i: number; dist: number }> = [];
for (let k = 0; k + 1 < f.length; k += 2) out.push({ i: f[k], dist: f[k + 1] });
return out;
}
/**
* Polygone, die `m` enthalten, oberstes (zuletzt gezeichnetes) zuerst; mit `fields` nur solche
* mit einer nicht-leeren Id eines dieser Felder.
*/
polygonsAt(m: Vec2, ...fields: OwnerField[]): number[] {
return Array.from(core().pick_polygons_at(this.ix(), m.x, m.y, mask(fields)));
}
/** Oberstes Polygon unter `m` (s. {@link polygonsAt}) oder null. */
topPolygon(m: Vec2, ...fields: OwnerField[]): number | null {
const l = this.polygonsAt(m, ...fields);
return l.length ? l[0] : null;
}
/** Unterstes (zuerst gezeichnetes) Polygon unter `m` oder null. */
bottomPolygon(m: Vec2, ...fields: OwnerField[]): number | null {
const l = this.polygonsAt(m, ...fields);
return l.length ? l[l.length - 1] : null;
}
/**
* Nächste Symbol-Linie mit einer Id aus `lineFields` (bzw. Bogen über die Sehne `from → to` mit
* `arcFields`) zum Client-Punkt, Abstand in Pixeln < `maxPx`; erster bei Gleichstand.
*/
nearestSymbolPx(lineFields: OwnerField[], arcFields: OwnerField[], map: ClientMap, client: { x: number; y: number }, maxPx: number): number | null {
const i = core().pick_nearest_symbol_px(this.ix(), mask(lineFields), mask(arcFields), map.left, map.top, map.viewX, map.viewY, map.scale, client.x, client.y, maxPx);
return i >= 0 ? i : null;
}
/**
* Kreise/Bögen der 2D-Zeichnung (`drawingCircle`/`drawingArc` mit `drawingId`), deren Ring
* näher als `tolPx` Pixel liegt (gefüllte Kreise auch innen; Bögen nur in ihrer Spanne mit
* `tolPx`-Saum) — in Plan-Reihenfolge, Abstand in Pixeln.
*/
ringsNear(m: Vec2, pxPerM: number, tolPx: number): Array<{ i: number; dpx: number }> {
const f = core().pick_rings_near(this.ix(), m.x, m.y, pxPerM, tolPx);
const out: Array<{ i: number; dpx: number }> = [];
for (let k = 0; k + 1 < f.length; k += 2) out.push({ i: f[k], dpx: f[k + 1] });
return out;
}
/** Primitive, deren `field` in `ids` liegt — in Plan-Reihenfolge. */
ownedBy(field: OwnerField, ids: Iterable<string>): Primitive[] {
const list = [...ids];
if (list.length === 0) return [];
const hits = core().pick_owned_by(this.ix(), KIND[field], list.map((s) => "\u0000" + s).join(""));
return Array.from(hits, (i) => this.prims[i]);
}
}
-75
View File
@@ -1,75 +0,0 @@
import { describe, it, expect } from "vitest";
import type { Primitive } from "../generatePlan";
import { buildSegmentIndex, nearestSegment } from "./segmentIndex";
const line = (ax: number, ay: number, bx: number, by: number, drawingId = "d"): Primitive => ({
kind: "line",
a: { x: ax, y: ay },
b: { x: bx, y: by },
cls: "draw2d",
weightMm: 0.18,
drawingId,
});
function bruteForce(prims: Primitive[], m: { x: number; y: number }, maxDist: number): number | null {
let best: number | null = null;
let bestDist = maxDist;
prims.forEach((p, i) => {
if (p.kind !== "line" || !p.drawingId) return;
const dx = p.b.x - p.a.x, dy = p.b.y - p.a.y;
const len2 = dx * dx + dy * dy;
const t = len2 > 0 ? Math.max(0, Math.min(1, ((m.x - p.a.x) * dx + (m.y - p.a.y) * dy) / len2)) : 0;
const d = Math.hypot(m.x - (p.a.x + t * dx), m.y - (p.a.y + t * dy));
if (d < bestDist) {
bestDist = d;
best = i;
}
});
return best;
}
describe("segmentIndex", () => {
it("liefert dasselbe Ergebnis wie die lineare Suche (Zufallsdaten)", () => {
let seed = 1;
const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
const prims: Primitive[] = [];
for (let i = 0; i < 20000; i++) {
const x = rnd() * 1000, y = rnd() * 1000;
prims.push(line(x, y, x + (rnd() - 0.5) * 20, y + (rnd() - 0.5) * 20));
}
// Ein sehr langes Segment (landet in der Überlauf-Liste) + ein Nicht-2D-Strich.
prims.push(line(-5000, -5000, 5000, 5000));
prims.push({ ...line(500, 500, 501, 501), drawingId: undefined } as Primitive);
const idx = buildSegmentIndex(prims)!;
expect(idx.long.length).toBe(1);
for (let k = 0; k < 500; k++) {
const m = { x: rnd() * 1100 - 50, y: rnd() * 1100 - 50 };
expect(nearestSegment(idx, prims, m, 3)).toBe(bruteForce(prims, m, 3));
}
});
it("null ohne indizierbare Linien", () => {
expect(buildSegmentIndex([])).toBeNull();
});
it("findet nichts ausserhalb der Toleranz", () => {
const prims = [line(0, 0, 10, 0)];
const idx = buildSegmentIndex(prims)!;
expect(nearestSegment(idx, prims, { x: 5, y: 0.5 }, 1)).toBe(0);
expect(nearestSegment(idx, prims, { x: 5, y: 2 }, 1)).toBeNull();
expect(nearestSegment(idx, prims, { x: 500, y: 500 }, 1)).toBeNull();
});
});
describe("segmentsNear (alle Treffer, nächster zuerst)", () => {
it("liefert alle Segmente in Reichweite, sortiert, und entspricht der linearen Suche", async () => {
const { segmentsNear } = await import("./segmentIndex");
const prims: Primitive[] = [line(0, 0, 10, 0, "a"), line(0, 0.5, 10, 0.5, "b"), line(0, 5, 10, 5, "c"), line(-2000, -2000, 2000, 2000, "long")];
for (let i = 0; i < 300; i++) prims.push(line(50 + i, 50, 51 + i, 51, `f${i}`));
const idx = buildSegmentIndex(prims)!;
const hits = segmentsNear(idx, prims, { x: 5, y: 0.2 }, 1);
expect(hits.map((h) => (prims[h.i] as any).drawingId)).toEqual(["a", "b"].concat(hits.length > 2 ? ["long"] : []).slice(0, hits.length));
expect(hits[0].dist).toBeLessThanOrEqual(hits[1].dist);
expect(hits.every((h) => h.dist < 1)).toBe(true);
});
});
-163
View File
@@ -1,163 +0,0 @@
// Uniformes Raster über die 'line'-Primitive eines Plans (Modell-Meter), damit
// Nächstes-Segment-Abfragen unter dem Cursor nur die Segmente der umliegenden
// Zellen prüfen statt ALLE Primitive. Ein Kataster-Import liefert 3,7 Mio.
// Segmente; die frühere lineare Suche lief bei JEDER Mausbewegung über alle.
//
// Speicher als CSR (Zell-Offsets + flacher Index-Array, Typed Arrays) statt
// eines Arrays pro Zelle: Millionen kleiner JS-Arrays wären selbst teuer.
import type { Vec2 } from "../../model/types";
import type { Primitive } from "../generatePlan";
export interface SegmentIndex {
minX: number;
minY: number;
cell: number;
cols: number;
rows: number;
/** cellStart[c]..cellStart[c+1] = Bereich in `items` für Zelle c. */
cellStart: Uint32Array;
/** Primitiv-Indizes, nach Zelle gruppiert. */
items: Uint32Array;
/** Segmente, deren Bounding-Box zu viele Zellen überdeckt — immer geprüft. */
long: Uint32Array;
}
/** Ziel: im Mittel so viele Segmente je Zelle. */
const TARGET_PER_CELL = 8;
/** Obergrenze der Zellzahl (Speicher für `cellStart`). */
const MAX_CELLS = 4_000_000;
/** Ab so vielen überdeckten Zellen landet ein Segment in `long` statt im Raster. */
const MAX_CELLS_PER_SEGMENT = 1024;
/** Ob ein Primitiv in den Index gehört (2D-Zeichenlinien, s. Hover-Teilpunkte). */
const indexed = (p: Primitive): p is Extract<Primitive, { kind: "line" }> =>
p.kind === "line" && !!p.drawingId;
export function buildSegmentIndex(prims: readonly Primitive[]): SegmentIndex | null {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
let n = 0;
for (const p of prims) {
if (!indexed(p)) continue;
n++;
minX = Math.min(minX, p.a.x, p.b.x);
maxX = Math.max(maxX, p.a.x, p.b.x);
minY = Math.min(minY, p.a.y, p.b.y);
maxY = Math.max(maxY, p.a.y, p.b.y);
}
if (n === 0) return null;
const w = Math.max(maxX - minX, 1e-6);
const h = Math.max(maxY - minY, 1e-6);
const cellCount = Math.min(MAX_CELLS, Math.max(1, Math.ceil(n / TARGET_PER_CELL)));
let cell = Math.sqrt((w * h) / cellCount);
if (!(cell > 0)) cell = Math.max(w, h);
const cols = Math.max(1, Math.ceil(w / cell));
const rows = Math.max(1, Math.ceil(h / cell));
const cx = (x: number) => Math.min(cols - 1, Math.max(0, Math.floor((x - minX) / cell)));
const cy = (y: number) => Math.min(rows - 1, Math.max(0, Math.floor((y - minY) / cell)));
// Zwei Durchläufe (zählen, dann füllen) — jedes Segment landet in jeder Zelle,
// die seine Bounding-Box berührt.
const counts = new Uint32Array(cols * rows + 1);
const long: number[] = [];
for (let i = 0; i < prims.length; i++) {
const p = prims[i];
if (!indexed(p)) continue;
const x0 = cx(Math.min(p.a.x, p.b.x)), x1 = cx(Math.max(p.a.x, p.b.x));
const y0 = cy(Math.min(p.a.y, p.b.y)), y1 = cy(Math.max(p.a.y, p.b.y));
if ((x1 - x0 + 1) * (y1 - y0 + 1) > MAX_CELLS_PER_SEGMENT) {
long.push(i);
continue;
}
for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) counts[y * cols + x + 1]++;
}
const longSet = new Set(long);
for (let c = 1; c < counts.length; c++) counts[c] += counts[c - 1];
const cellStart = counts;
const fill = cellStart.slice(0, cols * rows);
const items = new Uint32Array(cellStart[cols * rows]);
for (let i = 0; i < prims.length; i++) {
const p = prims[i];
if (!indexed(p) || longSet.has(i)) continue;
const x0 = cx(Math.min(p.a.x, p.b.x)), x1 = cx(Math.max(p.a.x, p.b.x));
const y0 = cy(Math.min(p.a.y, p.b.y)), y1 = cy(Math.max(p.a.y, p.b.y));
for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) items[fill[y * cols + x]++] = i;
}
return { minX, minY, cell, cols, rows, cellStart, items, long: Uint32Array.from(long) };
}
export function pointSegDist(p: Vec2, a: Vec2, b: Vec2): number {
const dx = b.x - a.x, dy = b.y - a.y;
const len2 = dx * dx + dy * dy;
let t = len2 > 0 ? ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2 : 0;
t = Math.max(0, Math.min(1, t));
return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
}
/**
* Nächstes indiziertes Segment zu `m` (Modell-Meter) mit Abstand < `maxDist`
* (Modell-Meter), oder null. Liefert den Primitiv-Index.
*/
export function nearestSegment(
index: SegmentIndex,
prims: readonly Primitive[],
m: Vec2,
maxDist: number,
): number | null {
const { minX, minY, cell, cols, rows, cellStart, items, long } = index;
let best: number | null = null;
let bestDist = maxDist;
const consider = (i: number) => {
const p = prims[i] as Extract<Primitive, { kind: "line" }>;
const d = pointSegDist(m, p.a, p.b);
if (d < bestDist) {
bestDist = d;
best = i;
}
};
for (const i of long) consider(i);
const x0 = Math.floor((m.x - maxDist - minX) / cell);
const x1 = Math.floor((m.x + maxDist - minX) / cell);
const y0 = Math.floor((m.y - maxDist - minY) / cell);
const y1 = Math.floor((m.y + maxDist - minY) / cell);
if (x1 < 0 || y1 < 0 || x0 >= cols || y0 >= rows) return best;
for (let y = Math.max(0, y0); y <= Math.min(rows - 1, y1); y++) {
for (let x = Math.max(0, x0); x <= Math.min(cols - 1, x1); x++) {
const c = y * cols + x;
for (let k = cellStart[c]; k < cellStart[c + 1]; k++) consider(items[k]);
}
}
return best;
}
/** ALLE indizierten Segmente mit Abstand < `maxDist` (Modell-Einheiten), nächste zuerst. */
export function segmentsNear(
index: SegmentIndex,
prims: readonly Primitive[],
m: Vec2,
maxDist: number,
): Array<{ i: number; dist: number }> {
const { minX, minY, cell, cols, rows, cellStart, items, long } = index;
const found = new Map<number, number>();
const consider = (i: number) => {
const p = prims[i] as Extract<Primitive, { kind: "line" }>;
const d = pointSegDist(m, p.a, p.b);
if (d < maxDist) found.set(i, d);
};
for (const i of long) consider(i);
const x0 = Math.floor((m.x - maxDist - minX) / cell);
const x1 = Math.floor((m.x + maxDist - minX) / cell);
const y0 = Math.floor((m.y - maxDist - minY) / cell);
const y1 = Math.floor((m.y + maxDist - minY) / cell);
if (!(x1 < 0 || y1 < 0 || x0 >= cols || y0 >= rows)) {
for (let y = Math.max(0, y0); y <= Math.min(rows - 1, y1); y++) {
for (let x = Math.max(0, x0); x <= Math.min(cols - 1, x1); x++) {
const c = y * cols + x;
for (let k = cellStart[c]; k < cellStart[c + 1]; k++) consider(items[k]);
}
}
}
return [...found].map(([i, dist]) => ({ i, dist })).sort((a, b) => a.dist - b.dist);
}
+4 -4
View File
@@ -5,7 +5,7 @@ import { describe, it, expect } from "vitest";
import type { Drawing2D, Project } from "../../model/types";
import { generatePlan, materializeUnderlay } from "../generatePlan";
import { marqueeHitDrawings } from "./geometry";
import { buildSegmentIndex, nearestSegment } from "./segmentIndex";
import { PlanPickIndex } from "./planPick";
import { buildDrawingIndex, marqueeHitUnderlay, nearestInDrawings } from "./underlayAccess";
let seed = 7;
@@ -53,12 +53,12 @@ describe("underlayAccess == Primitiv-Varianten", () => {
it("nächstes Segment == Segment-Index der Primitive", () => {
const idx = buildDrawingIndex(under)!;
const segIdx = buildSegmentIndex(normal.primitives)!;
const segIdx = new PlanPickIndex(normal);
for (let k = 0; k < 400; k++) {
const m = { x: rnd() * 540 - 20, y: rnd() * 540 - 20 };
const a = nearestInDrawings(idx, m, 2);
const bi = nearestSegment(segIdx, normal.primitives, m, 2);
const b = bi === null ? null : (normal.primitives[bi] as any);
const bi = segIdx.nearestSegment(m, 2);
const b = bi === null ? null : (normal.primitives[bi.i] as any);
expect(a?.drawing.id ?? null).toBe(b?.drawingId ?? null);
}
});
+2 -2
View File
@@ -29,8 +29,8 @@ describe("planToRenderScene (Kern)", () => {
});
it("näht unterdrückte Kanten zweier Polygone zu einem Ring", () => {
const a: Primitive = { kind: "polygon", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [1] };
const b: Primitive = { kind: "polygon", pts: [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 1 }, { x: 1, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [3] };
const a: Primitive = { kind: "polygon", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [1] } as Primitive;
const b: Primitive = { kind: "polygon", pts: [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 1 }, { x: 1, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [3] } as Primitive;
const s = planToRenderScene(planOf([a, b]));
expect(s.fills.length).toBe(2);
expect(s.outlines.length).toBe(1);
+86 -198
View File
@@ -31,7 +31,7 @@ import { isGpuText } from "../../core";
import { LiveMeet, LiveValue, createMeetStore, createValueStore } from "./planView/liveMeet";
import { useWasmPlanRenderer } from "./useWasmPlanRenderer";
import { DEFAULT_MARQUEE_COLOR, DEFAULT_SNAP_COLOR } from "../../theme/accents";
import { type ViewBox__plan_planView_geometry as ViewBox, PX_PER_M, PAD, toScreen, clamp, meetScale, scaleFromView, viewForScale, viewForCamera, fitBoxFor, pointInPolygon, pointSegDistPx, marqueeHit, marqueeHitDrawings, type ModelRect, marqueeHitCeilings, marqueeHitRooms, marqueeHitStairs } from "../../core";
import { type ViewBox__plan_planView_geometry as ViewBox, PX_PER_M, PAD, toScreen, clamp, meetScale, scaleFromView, viewForScale, viewForCamera, fitBoxFor, marqueeHit, marqueeHitDrawings, type ModelRect, marqueeHitCeilings, marqueeHitRooms, marqueeHitStairs } from "../../core";
import {
polyUsesPattern,
HatchPattern,
@@ -44,8 +44,7 @@ import { DraftOverlay } from "./planView/overlays";
import { PlanRulers } from "./planView/PlanRulers";
import { PlanGrid } from "./planView/PlanGrid";
import { expandRegion, indexedInRegion, regionContains, type Bounds } from "../../core";
import { buildSegmentIndex, nearestSegment, pointSegDist__plan_planView_segmentIndex as pointSegDist, segmentsNear } from "../../core";
import { buildOwnerIndex, ownedBy, type OwnerField, type OwnerIndex } from "../../core";
import { PlanPickIndex, type ClientMap, type OwnerField } from "../../core";
import { buildDrawingIndex, drawingsWithinDistance, marqueeHitUnderlay, nearestInDrawings, type DrawingIndex } from "../../core";
import { endBusyAfterPaint } from "../../state/busyStore";
import { createCursorStore, useCursorValue, type CursorStore } from "../../state/cursorStore";
@@ -760,17 +759,19 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// zoomen (view schrumpft stark — reines "liegt noch drin" reicht hier
// NICHT, ein View, der nur kleiner wird, bleibt sonst fälschlich innerhalb
// der alten, zu grosszügigen Region) wird neu gerechnet.
// Raster-Index der 2D-Zeichenlinien für Hover-/Pick-Abfragen (s. segmentIndex.ts).
// LAZY (erst beim ersten Hover/Klick je Plan): der Aufbau kostet bei 3,7 Mio.
// Segmenten ~250 ms und lief sonst bei JEDEM Plan-/Ebenenwechsel.
const segmentIndexRef = useRef<{ prims: readonly Primitive[]; index: ReturnType<typeof buildSegmentIndex> } | null>(null);
const getSegmentIndex = () => {
const cached = segmentIndexRef.current;
if (cached && cached.prims === planRaw.primitives) return cached.index;
const index = buildSegmentIndex(planRaw.primitives);
segmentIndexRef.current = { prims: planRaw.primitives, index };
return index;
// Auswahl-Index im Kern (s. planView/planPick.ts): 2D-Zeichenlinien, Polygone, Symbol-Linien,
// Kreise/Bögen und Besitzer über `plan.primitives` (dieselben Indizes). LAZY: der Kern baut ihn
// erst bei der ersten Abfrage je Plan; der vorige wird dann freigegeben.
const pickIndexRef = useRef<PlanPickIndex | null>(null);
const getPick = (): PlanPickIndex => {
const cached = pickIndexRef.current;
if (cached && cached.prims === plan.primitives) return cached;
cached?.release();
const ix = new PlanPickIndex(plan);
pickIndexRef.current = ix;
return ix;
};
useEffect(() => () => pickIndexRef.current?.release(), []);
const svgRef = useRef<SVGSVGElement | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
@@ -831,6 +832,17 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
const lines = !useGpuRenderer || wantWasm;
return materializeGreyed(lines ? materializeUnderlay(planRaw) : planRaw, lines);
}, [planRaw, useGpuRenderer, wantWasm]);
// Einzeltexte und Bilder (eigene Bbox-Treffer): einmal je Plan gesammelt statt bei jeder
// Mausbewegung über alle Primitive zu laufen.
const textImageIdx = useMemo(() => {
const texts: number[] = [];
const images: number[] = [];
plan.primitives.forEach((p, i) => {
if (p.kind === "drawingText") texts.push(i);
else if (p.kind === "drawingImage") images.push(i);
});
return { texts, images };
}, [plan.primitives]);
// Kompakte Linien-Unterlage (nur im reinen WebGL-Modus noch als `plan.underlay`
// vorhanden): Hover/Pick/Marquee/Hervorhebung greifen direkt auf die Zeichnungen
@@ -1347,6 +1359,11 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
const top = rect?.top ?? 0;
return { x: left + offX + (vbX - view.x) * scale, y: top + offY + (vbY - view.y) * scale };
};
// Abbildung Modell → Client-Pixel (toScreen + vbToClient) für Pixel-Abfragen im Kern.
const clientMap = (): ClientMap => {
const { rect, scale, offX, offY } = measure(view);
return { left: (rect?.left ?? 0) + offX, top: (rect?.top ?? 0) + offY, viewX: view.x, viewY: view.y, scale };
};
// Index des Griffs unter dem Cursor (Bildschirm-Pixel) oder null.
const gripAt = (clientX: number, clientY: number): number | null => {
if (!grips) return null;
@@ -1410,13 +1427,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// Reihenfolge testen, damit das zuletzt gezeichnete (oberste) zuerst trifft.
const hitTest = (clientX: number, clientY: number): number | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
const prims = plan.primitives;
for (let i = prims.length - 1; i >= 0; i--) {
const p = prims[i];
if (p.kind === "polygon" && pointInPolygon(m, p.pts)) return i;
}
return null;
return getPick().topPolygon(viewToModel(v.x, v.y));
};
// Irgendein Element (Wand/Decke/Raum/Treppe/Stütze/Dach/2D) unter dem
@@ -1443,64 +1454,32 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
return did ? { drawingId: did } : null;
};
// Abstand (Bildschirm-Pixel) eines Klicks vom Ring eines Kreis/Bogen-2D-
// Elements — bei gefüllten Kreisen zählt auch INNERHALB als Treffer (d=0).
// Bögen zusätzlich auf ihre Winkel-Spanne begrenzt (CCW, Modell-Radiant, s.
// toRenderScene.ts für dieselbe Normalisierung).
const distToDrawingRing = (
clientX: number,
clientY: number,
p: Extract<Primitive, { kind: "drawingCircle" | "drawingArc" }>,
): number => {
const m = rawModelAt(clientX, clientY);
const distFromCenter = Math.hypot(m.x - p.center.x, m.y - p.center.y);
if (p.kind === "drawingArc") {
const TAU = Math.PI * 2;
const sweep = (((p.a1 - p.a0) % TAU) + TAU) % TAU || TAU;
const ang = Math.atan2(m.y - p.center.y, m.x - p.center.x);
const rel = (((ang - p.a0) % TAU) + TAU) % TAU;
// Kleiner Winkel-Toleranzsaum (in Bogenmass, radiusabhängig), damit die
// Enden eines kurzen Bogens nicht unerreichbar schmal werden.
const angTolRad = distFromCenter > 1e-6 ? LINE_PICK_PX / (currentPxPerMeter() * Math.max(distFromCenter, 0.05)) : Infinity;
if (rel > sweep + angTolRad && TAU - rel > angTolRad) return Infinity;
}
const filled = p.kind === "drawingCircle" && p.fill !== "none";
const dMeters = filled ? Math.max(0, distFromCenter - p.r) : Math.abs(distFromCenter - p.r);
return dMeters * currentPxPerMeter();
};
// Nächstgelegenes 2D-Zeichenelement (Drawing2D) zum Cursor per Linien-Nähe in
// Bildschirm-Pixeln (zoom-unabhängige Toleranz). Liefert die drawingId oder null.
const pickDrawing = (clientX: number, clientY: number): string | null => {
let bestId: string | null = null;
let bestDist = LINE_PICK_PX;
const segmentIndex = getSegmentIndex();
if (segmentIndex) {
const pxPerM = currentPxPerMeter();
const m = rawModelAt(clientX, clientY);
const i = nearestSegment(segmentIndex, plan.primitives, m, LINE_PICK_PX / pxPerM);
if (i !== null) {
const p = plan.primitives[i] as Extract<Primitive, { kind: "line" }>;
bestId = p.drawingId!;
bestDist = pointSegDist(m, p.a, p.b) * pxPerM;
}
const pick = getPick();
const pxPerM = currentPxPerMeter();
const m = rawModelAt(clientX, clientY);
const seg = pick.nearestSegment(m, LINE_PICK_PX / pxPerM);
if (seg) {
bestId = (plan.primitives[seg.i] as Extract<Primitive, { kind: "line" }>).drawingId!;
bestDist = seg.dist * pxPerM;
}
const uIndex = getUnderlayIndex();
if (uIndex) {
const pxPerM = currentPxPerMeter();
const hit = nearestInDrawings(uIndex, rawModelAt(clientX, clientY), bestDist / pxPerM);
const hit = nearestInDrawings(uIndex, m, bestDist / pxPerM);
if (hit) {
bestId = hit.drawing.id;
bestDist = hit.dist * pxPerM;
}
}
for (const p of plan.primitives) {
if ((p.kind === "drawingCircle" || p.kind === "drawingArc") && p.drawingId) {
const d = distToDrawingRing(clientX, clientY, p);
if (d < bestDist) {
bestDist = d;
bestId = p.drawingId;
}
// Kreise/Bögen (Ring-Abstand wie früher `distToDrawingRing`), in Plan-Reihenfolge.
for (const { i, dpx } of pick.ringsNear(m, pxPerM, LINE_PICK_PX)) {
if (dpx < bestDist) {
bestDist = dpx;
bestId = (plan.primitives[i] as Extract<Primitive, { kind: "drawingCircle" | "drawingArc" }>).drawingId!;
}
}
if (bestId) return bestId;
@@ -1519,14 +1498,11 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
const maxDist = LINE_PICK_PX / currentPxPerMeter();
let best: { a: Vec2; b: Vec2 } | null = null;
let bestDist = maxDist;
const segmentIndex = getSegmentIndex();
if (segmentIndex) {
const i = nearestSegment(segmentIndex, plan.primitives, m, maxDist);
if (i !== null) {
const p = plan.primitives[i] as Extract<Primitive, { kind: "line" }>;
best = { a: p.a, b: p.b };
bestDist = pointSegDist(m, p.a, p.b);
}
const seg = getPick().nearestSegment(m, maxDist);
if (seg) {
const p = plan.primitives[seg.i] as Extract<Primitive, { kind: "line" }>;
best = { a: p.a, b: p.b };
bestDist = seg.dist;
}
const uIndex = getUnderlayIndex();
if (uIndex) {
@@ -1541,7 +1517,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// Winkel wird vernachlässigt (meist waagrecht). Liefert die drawingId oder null.
const pickDrawingText = (clientX: number, clientY: number): string | null => {
const m = rawModelAt(clientX, clientY);
for (const p of plan.primitives) {
for (const i of textImageIdx.texts) {
const p = plan.primitives[i];
if (p.kind !== "drawingText" || !p.drawingId) continue;
const singleW = Math.max(1, p.text.length) * p.heightM * 0.6;
// Textspalte: Breite = wrapWidth, Höhe = geschätzte Zeilenzahl · Zeilenhöhe.
@@ -1566,8 +1543,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// oder null.
const pickDrawingImage = (clientX: number, clientY: number): string | null => {
const m = rawModelAt(clientX, clientY);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
for (let k = textImageIdx.images.length - 1; k >= 0; k--) {
const p = plan.primitives[textImageIdx.images[k]];
if (p.kind !== "drawingImage" || !p.drawingId) continue;
if (m.x >= p.min.x && m.x <= p.max.x && m.y >= p.min.y && m.y <= p.max.y) {
return p.drawingId;
@@ -1580,33 +1557,14 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// `openingId` per Bildschirm-Nähe, plus getroffene Fenster-Rahmen (Polygon mit
// openingId, per Punkt-in-Polygon). Liefert die openingId oder null.
const pickOpening = (clientX: number, clientY: number): string | null => {
let bestId: string | null = null;
let bestDist = LINE_PICK_PX;
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (const p of plan.primitives) {
if (p.kind === "line" && p.openingId) {
const a = vbToClient(toScreen(p.a).x, toScreen(p.a).y);
const b = vbToClient(toScreen(p.b).x, toScreen(p.b).y);
const d = pointSegDistPx({ x: clientX, y: clientY }, a, b);
if (d < bestDist) {
bestDist = d;
bestId = p.openingId;
}
} else if (p.kind === "arc" && p.openingId) {
// Bogen: über from→to als Sehne annähern (ausreichend für die Auswahl).
const a = vbToClient(toScreen(p.from).x, toScreen(p.from).y);
const b = vbToClient(toScreen(p.to).x, toScreen(p.to).y);
const d = pointSegDistPx({ x: clientX, y: clientY }, a, b);
if (d < bestDist) {
bestDist = d;
bestId = p.openingId;
}
} else if (p.kind === "polygon" && p.openingId && pointInPolygon(m, p.pts)) {
return p.openingId;
}
}
return bestId;
const pick = getPick();
// Getroffener Rahmen (das zuerst gezeichnete Polygon) hat Vorrang vor Symbol-Linien.
const hit = pick.bottomPolygon(m, "openingId");
if (hit !== null) return (plan.primitives[hit] as { openingId?: string }).openingId!;
const i = pick.nearestSymbolPx(["openingId"], ["openingId"], clientMap(), { x: clientX, y: clientY }, LINE_PICK_PX);
return i === null ? null : (plan.primitives[i] as { openingId?: string }).openingId!;
};
// Nächstgelegene Treppe zum Cursor: getroffenes Tritt-/Podest-Polygon (per
@@ -1614,67 +1572,35 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
const pickStair = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (const p of plan.primitives) {
if (p.kind === "polygon" && p.stairId && pointInPolygon(m, p.pts)) {
return p.stairId;
}
}
let bestId: string | null = null;
let bestDist = LINE_PICK_PX;
for (const p of plan.primitives) {
if (p.kind === "line" && p.stairId) {
const a = vbToClient(toScreen(p.a).x, toScreen(p.a).y);
const b = vbToClient(toScreen(p.b).x, toScreen(p.b).y);
const d = pointSegDistPx({ x: clientX, y: clientY }, a, b);
if (d < bestDist) {
bestDist = d;
bestId = p.stairId;
}
}
}
return bestId;
const pick = getPick();
const hit = pick.bottomPolygon(m, "stairId");
if (hit !== null) return (plan.primitives[hit] as { stairId?: string }).stairId!;
const i = pick.nearestSymbolPx(["stairId"], [], clientMap(), { x: clientX, y: clientY }, LINE_PICK_PX);
return i === null ? null : (plan.primitives[i] as { stairId?: string }).stairId!;
};
// Getroffener Raum: die Raum-Fläche (Polygon mit `roomId`) per Punkt-in-Polygon.
// Bei überlappenden Räumen gewinnt der zuletzt gezeichnete (oberste).
const pickRoom = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
if (p.kind === "polygon" && p.roomId && pointInPolygon(m, p.pts)) {
return p.roomId;
}
}
return null;
const i = getPick().topPolygon(viewToModel(v.x, v.y), "roomId");
return i === null ? null : (plan.primitives[i] as { roomId?: string }).roomId!;
};
// Getroffenes Dach: das unsichtbare Traufe-Pick-Polygon per Punkt-in-Polygon
// (die sichtbaren Dachlinien allein wären schwer exakt zu treffen).
const pickRoof = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
if (p.kind === "polygon" && p.roofId && pointInPolygon(m, p.pts)) {
return p.roofId;
}
}
return null;
const i = getPick().topPolygon(viewToModel(v.x, v.y), "roofId");
return i === null ? null : (plan.primitives[i] as { roofId?: string }).roofId!;
};
// Getroffene Schnitt-/Ansichtslinie: ihr schmales, unsichtbares Pick-Band
// (Polygon mit sectionLineId) per Punkt-in-Polygon.
const pickSectionLine = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
if (p.kind === "polygon" && p.sectionLineId && pointInPolygon(m, p.pts)) {
return p.sectionLineId;
}
}
return null;
const i = getPick().topPolygon(viewToModel(v.x, v.y), "sectionLineId");
return i === null ? null : (plan.primitives[i] as { sectionLineId?: string }).sectionLineId!;
};
// Getroffenes Kontext-Objekt (importiertes Gebäude/Terrain): sein unsichtbares
@@ -1683,14 +1609,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// dünnen Umrisslinie.
const pickContextObject = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
if (p.kind === "polygon" && p.contextObjectId && pointInPolygon(m, p.pts)) {
return p.contextObjectId;
}
}
return null;
const i = getPick().topPolygon(viewToModel(v.x, v.y), "contextObjectId");
return i === null ? null : (plan.primitives[i] as { contextObjectId?: string }).contextObjectId!;
};
// Getroffener extrudierter Körper (truck-Integration): der Footprint-Umriss
@@ -1698,28 +1618,16 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// trotzdem als FLÄCHE anklickbar (analog Raum, nicht nur auf der Linie).
const pickExtrudedSolid = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
if (p.kind === "polygon" && p.extrudedSolidId && pointInPolygon(m, p.pts)) {
return p.extrudedSolidId;
}
}
return null;
const i = getPick().topPolygon(viewToModel(v.x, v.y), "extrudedSolidId");
return i === null ? null : (plan.primitives[i] as { extrudedSolidId?: string }).extrudedSolidId!;
};
// Getroffene Stütze (Tragwerk): ihr Querschnitt ist eine gefüllte Poché
// (Polygon mit columnId) — per Punkt-in-Polygon als FLÄCHE anklickbar.
const pickColumn = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
if (p.kind === "polygon" && p.columnId && pointInPolygon(m, p.pts)) {
return p.columnId;
}
}
return null;
const i = getPick().topPolygon(viewToModel(v.x, v.y), "columnId");
return i === null ? null : (plan.primitives[i] as { columnId?: string }).columnId!;
};
// Liegt der Cursor auf dem KÖRPER eines GEWÄHLTEN Elements (Wand-Poché bzw.
@@ -2311,16 +2219,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
}, [pickList]);
/** Alle Polygone unter dem Cursor, oberstes zuerst. */
const hitTestAll = (clientX: number, clientY: number): number[] => {
const m = rawModelAt(clientX, clientY);
const prims = plan.primitives;
const out: number[] = [];
for (let i = prims.length - 1; i >= 0; i--) {
const p = prims[i];
if (p.kind === "polygon" && pointInPolygon(m, p.pts)) out.push(i);
}
return out;
};
const hitTestAll = (clientX: number, clientY: number): number[] => getPick().polygonsAt(rawModelAt(clientX, clientY));
/** Bezeichnung eines 2D-Elements nach Form (Linie/Fläche/Text/Kreis/…). */
const drawingLabel = (id: string): string => {
@@ -2355,20 +2254,15 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
const m = rawModelAt(clientX, clientY);
const tol = LINE_PICK_PX / pxPerM;
const found: Array<{ id: string; d: number }> = [];
const segIdx = getSegmentIndex();
if (segIdx) {
for (const { i, dist } of segmentsNear(segIdx, plan.primitives, m, tol)) {
const id = (plan.primitives[i] as Extract<Primitive, { kind: "line" }>).drawingId;
if (id) found.push({ id, d: dist });
}
const pick = getPick();
for (const { i, dist } of pick.segmentsNear(m, tol)) {
const id = (plan.primitives[i] as Extract<Primitive, { kind: "line" }>).drawingId;
if (id) found.push({ id, d: dist });
}
const uIdx = getUnderlayIndex();
if (uIdx) for (const h of drawingsWithinDistance(uIdx, m, tol)) found.push({ id: h.drawing.id, d: h.dist });
for (const p of plan.primitives) {
if ((p.kind === "drawingCircle" || p.kind === "drawingArc") && p.drawingId) {
const dpx = distToDrawingRing(clientX, clientY, p);
if (dpx < LINE_PICK_PX) found.push({ id: p.drawingId, d: dpx / pxPerM });
}
for (const { i, dpx } of pick.ringsNear(m, pxPerM, LINE_PICK_PX)) {
found.push({ id: (plan.primitives[i] as Extract<Primitive, { kind: "drawingCircle" | "drawingArc" }>).drawingId!, d: dpx / pxPerM });
}
const textId = pickDrawingText(clientX, clientY);
if (textId) found.push({ id: textId, d: tol * 2 });
@@ -2779,21 +2673,15 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// gewählten Wand umrandet. Ohne Wand-Auswahl greift die lokale Klick-
// Hervorhebung (ein einzelnes Polygon per hitIndex), z. B. für Polygone ohne
// Wandbezug.
// Besitzer-Index (s. planView/ownerIndex.ts): EIN Durchgang je Plan, lazy beim
// ersten Bedarf — statt je Elementart ein `plan.primitives.filter`.
const ownerIndexRef = useRef<{ prims: readonly Primitive[]; index: OwnerIndex } | null>(null);
// Besitzer über den Auswahl-Index im Kern (s. planView/planPick.ts) — statt je Elementart ein
// `plan.primitives.filter`.
const primsOwnedBy = <K extends Primitive>(
field: OwnerField,
ids: ReadonlyArray<string> | undefined,
keep: (p: Primitive) => p is K,
): K[] => {
if (!ids || ids.length === 0) return [];
let cached = ownerIndexRef.current;
if (!cached || cached.prims !== plan.primitives) {
cached = { prims: plan.primitives, index: buildOwnerIndex(plan.primitives) };
ownerIndexRef.current = cached;
}
return ownedBy(cached.index, plan.primitives, field, ids).filter(keep);
return getPick().ownedBy(field, ids).filter(keep);
};
const highlightPolys = useMemo(() => {