[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

+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(() => {