Objektfang: bei grossen Projekten nur Strecken in Cursornähe (Hänger beim Zeichnen)

Reproduziert headless mit der Luzerner Kataster-DXF: nach Anwählen des
Rechteck-Werkzeugs blockierte bereits der erste Klick die Seite (Renderer
dauerhaft 100 % CPU). computeSnap baute bei JEDER Mausbewegung aus allen
Zeichnungen die Liste aller Strecken (3,7 Mio. Tupel) und prüfte beim
Schnittpunkt-Fang alle Paare — O(N²).

Ab 2000 Zeichnungen: Raster-Index über die Bounding-Boxen (geometry/
drawingIndex.ts, je drawings2d-Array gecacht) liefert nur die Zeichnungen in
Cursornähe; Kreise/Bögen/Ellipsen kommen aus der kleinen Nicht-Linien-Liste;
der Schnittpunkt-Fang prüft nur die 64 nächsten Strecken (Radius 6×
Toleranz). Kleine Projekte bleiben exakt wie bisher. Tests: gleiche
Ergebnisse wie im kleinen Projekt in Cursornähe, 60'000 Linien < 50 ms je
Aufruf (vorher praktisch endlos). Spatial-Index und Bounding-Box-Cache von
plan/ nach geometry/ verschoben (gemeinsam genutzt von Plan-Ansicht und Fang).
This commit is contained in:
karim committed 2026-10-19 20:52:52 +02:00
1 parent 31d46e8c8c
commit db8e0b2c42
6 files changed
+349 -182

No files matched your search

@@ -2,7 +2,7 @@
// Zeichnungen (Structural Sharing) — ihre Box muss nicht bei jedem Plan-Aufbau
// neu über alle Punkte berechnet werden (bei einem Kataster-Import 3,7 Mio.).
import type { Drawing2D, Vec2 } from "../../model/types";
import type { Drawing2D, Vec2 } from "../model/types";
export interface Box {
minX: number;
+155
View File
@@ -0,0 +1,155 @@
// Raster-Index über die Bounding-Boxen von Linien-/Polylinien-Zeichnungen
// (Drawing2D). Abfragen prüfen nur die Zeichnungen in Cursornähe statt alle —
// bei einem Kataster-Import ~10^5 Zeichnungen / 3,7 Mio. Strecken. Genutzt für
// Hover/Pick/Marquee (plan/planView/underlayAccess.ts) und den Objektfang
// (tools/snapping.ts).
import type { Drawing2D, Vec2 } from "../model/types";
import { drawingBox } from "./drawingBounds";
/** Abstand Punkt–Strecke (Modell-Einheiten). */
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));
}
/** Segmente einer Linie/Polylinie, genau wie sie als 'line'-Primitive entstünden. */
export function forEachSegment(d: Drawing2D, fn: (a: Vec2, b: Vec2) => void): void {
const g = d.geom;
if (g.shape === "line") {
fn(g.a, g.b);
return;
}
if (g.shape !== "polyline") return;
const pts = g.pts;
const n = pts.length;
for (let i = 0; i < n - 1; i++) fn(pts[i], pts[i + 1]);
if (g.closed && n > 2) fn(pts[n - 1], pts[0]);
}
export interface DrawingIndex {
minX: number;
minY: number;
cell: number;
cols: number;
rows: number;
cellStart: Uint32Array;
items: Uint32Array;
/** Zeichnungen mit riesiger Bounding-Box: immer geprüft. */
long: Uint32Array;
drawings: readonly Drawing2D[];
}
const TARGET_PER_CELL = 4;
const MAX_CELLS = 2_000_000;
const MAX_CELLS_PER_DRAWING = 256;
/** Ob eine Zeichnung vom Index erfasst wird (Linie/Polylinie mit Punkten). */
export const isIndexable = (d: Drawing2D): boolean =>
d.geom.shape === "line" || d.geom.shape === "polyline";
export function buildDrawingIndex(drawings: readonly Drawing2D[]): DrawingIndex | null {
if (drawings.length === 0) return null;
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const d of drawings) {
const b = drawingBox(d);
if (b.minX < minX) minX = b.minX;
if (b.minY < minY) minY = b.minY;
if (b.maxX > maxX) maxX = b.maxX;
if (b.maxY > maxY) maxY = b.maxY;
}
if (!isFinite(minX)) 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(drawings.length / 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)));
const counts = new Uint32Array(cols * rows + 1);
const long: number[] = [];
const longSet = new Set<number>();
for (let i = 0; i < drawings.length; i++) {
const b = drawingBox(drawings[i]);
if (!isFinite(b.minX)) continue;
const x0 = cx(b.minX), x1 = cx(b.maxX), y0 = cy(b.minY), y1 = cy(b.maxY);
if ((x1 - x0 + 1) * (y1 - y0 + 1) > MAX_CELLS_PER_DRAWING) {
long.push(i);
longSet.add(i);
continue;
}
for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) counts[y * cols + x + 1]++;
}
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 < drawings.length; i++) {
if (longSet.has(i)) continue;
const b = drawingBox(drawings[i]);
if (!isFinite(b.minX)) continue;
const x0 = cx(b.minX), x1 = cx(b.maxX), y0 = cy(b.minY), y1 = cy(b.maxY);
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), drawings };
}
/**
* Indizes der Zeichnungen, deren Bounding-Box (um `r` erweitert) den Punkt `m`
* enthält — Kandidaten, jede höchstens einmal.
*/
export function drawingsNear(index: DrawingIndex, m: Vec2, r: number): number[] {
const { minX, minY, cell, cols, rows, cellStart, items, long, drawings } = index;
const out: number[] = [];
const seen = new Set<number>();
const take = (i: number) => {
if (seen.has(i)) return;
seen.add(i);
const b = drawingBox(drawings[i]);
if (m.x < b.minX - r || m.x > b.maxX + r || m.y < b.minY - r || m.y > b.maxY + r) return;
out.push(i);
};
for (const i of long) take(i);
const x0 = Math.floor((m.x - r - minX) / cell);
const x1 = Math.floor((m.x + r - minX) / cell);
const y0 = Math.floor((m.y - r - minY) / cell);
const y1 = Math.floor((m.y + r - minY) / cell);
if (x1 < 0 || y1 < 0 || x0 >= cols || y0 >= rows) return out;
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++) take(items[k]);
}
}
return out;
}
export interface NearestHit {
drawing: Drawing2D;
a: Vec2;
b: Vec2;
dist: number;
}
/** Nächstes Segment (Modell-Meter) mit Abstand < `maxDist`, oder null. */
export function nearestInDrawings(index: DrawingIndex, m: Vec2, maxDist: number): NearestHit | null {
let best: NearestHit | null = null;
let bestDist = maxDist;
for (const i of drawingsNear(index, m, maxDist)) {
const d = index.drawings[i];
forEachSegment(d, (a, b) => {
const dist = pointSegDist(m, a, b);
if (dist < bestDist) {
bestDist = dist;
best = { drawing: d, a, b, dist };
}
});
}
return best;
}
+1 -1
View File
@@ -78,7 +78,7 @@ import {
drawingLinePrims,
isCompactUnderlayEligible,
} from "./generatePlan/drawing2d";
import { drawingBox } from "./generatePlan/drawingBounds";
import { drawingBox } from "../geometry/drawingBounds";
import { addDoorSymbol, addOpeningSymbol } from "./generatePlan/openings";
import { addRoof } from "./generatePlan/roofs";
import { addRoomArea } from "./generatePlan/rooms";
+3 -126
View File
@@ -7,132 +7,9 @@
import type { Drawing2D, Vec2 } from "../../model/types";
import type { ModelRect } from "./geometry";
import { polyEnclosedByRect, polyTouchesRect } from "./geometry";
import { pointSegDist } from "./segmentIndex";
import { drawingBox } from "../generatePlan/drawingBounds";
/** Segmente einer Zeichnung, genau wie sie als 'line'-Primitive entstünden. */
export function forEachSegment(d: Drawing2D, fn: (a: Vec2, b: Vec2) => void): void {
const g = d.geom;
if (g.shape === "line") {
fn(g.a, g.b);
return;
}
if (g.shape !== "polyline") return;
const pts = g.pts;
const n = pts.length;
for (let i = 0; i < n - 1; i++) fn(pts[i], pts[i + 1]);
if (g.closed && n > 2) fn(pts[n - 1], pts[0]);
}
// ── Raster-Index ────────────────────────────────────────────────────────────
export interface DrawingIndex {
minX: number;
minY: number;
cell: number;
cols: number;
rows: number;
cellStart: Uint32Array;
items: Uint32Array;
/** Zeichnungen mit riesiger Bounding-Box: immer geprüft. */
long: Uint32Array;
drawings: readonly Drawing2D[];
}
const TARGET_PER_CELL = 4;
const MAX_CELLS = 2_000_000;
const MAX_CELLS_PER_DRAWING = 256;
export function buildDrawingIndex(drawings: readonly Drawing2D[]): DrawingIndex | null {
if (drawings.length === 0) return null;
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const d of drawings) {
const b = drawingBox(d);
if (b.minX < minX) minX = b.minX;
if (b.minY < minY) minY = b.minY;
if (b.maxX > maxX) maxX = b.maxX;
if (b.maxY > maxY) maxY = b.maxY;
}
if (!isFinite(minX)) 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(drawings.length / 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)));
const counts = new Uint32Array(cols * rows + 1);
const long: number[] = [];
const longSet = new Set<number>();
for (let i = 0; i < drawings.length; i++) {
const b = drawingBox(drawings[i]);
if (!isFinite(b.minX)) continue;
const x0 = cx(b.minX), x1 = cx(b.maxX), y0 = cy(b.minY), y1 = cy(b.maxY);
if ((x1 - x0 + 1) * (y1 - y0 + 1) > MAX_CELLS_PER_DRAWING) {
long.push(i);
longSet.add(i);
continue;
}
for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) counts[y * cols + x + 1]++;
}
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 < drawings.length; i++) {
if (longSet.has(i)) continue;
const b = drawingBox(drawings[i]);
if (!isFinite(b.minX)) continue;
const x0 = cx(b.minX), x1 = cx(b.maxX), y0 = cy(b.minY), y1 = cy(b.maxY);
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), drawings };
}
export interface NearestHit {
drawing: Drawing2D;
a: Vec2;
b: Vec2;
dist: number;
}
/** Nächstes Segment (Modell-Meter) mit Abstand < `maxDist`, oder null. */
export function nearestInDrawings(index: DrawingIndex, m: Vec2, maxDist: number): NearestHit | null {
const { minX, minY, cell, cols, rows, cellStart, items, long, drawings } = index;
let best: NearestHit | null = null;
let bestDist = maxDist;
const seen = new Set<number>();
const check = (i: number) => {
if (seen.has(i)) return;
seen.add(i);
const d = drawings[i];
const bx = drawingBox(d);
if (m.x < bx.minX - bestDist || m.x > bx.maxX + bestDist || m.y < bx.minY - bestDist || m.y > bx.maxY + bestDist) return;
forEachSegment(d, (a, b) => {
const dist = pointSegDist(m, a, b);
if (dist < bestDist) {
bestDist = dist;
best = { drawing: d, a, b, dist };
}
});
};
for (const i of long) check(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++) check(items[k]);
}
}
return best;
}
import { drawingBox } from "../../geometry/drawingBounds";
import { forEachSegment } from "../../geometry/drawingIndex";
export { buildDrawingIndex, nearestInDrawings, type DrawingIndex } from "../../geometry/drawingIndex";
// ── Marquee ─────────────────────────────────────────────────────────────────
+58
View File
@@ -707,3 +707,61 @@ describe("computeSnap — Spline (fit- vs. control-Modus)", () => {
expect(r?.point.y).toBeCloseTo(0, 6);
});
});
// ── Grosse Projekte (Kataster-Import): Fang nur in Cursornähe ────────────────
// Regression: bei ~10^5 Zeichnungen baute computeSnap bei JEDER Mausbewegung die
// Liste aller Strecken und prüfte beim Schnittpunkt-Fang alle Paare (O(N²)) —
// die Seite blockierte beim ersten Klick eines Zeichenwerkzeugs.
describe("computeSnap — grosse Projekte", () => {
const ALL = { ...DEFAULT_SNAP, endpoint: true, midpoint: true, onEdge: true, intersection: true, perpendicular: true };
/** Gemeinsame Geometrie nahe am Ursprung + (optional) viele weit entfernte Linien. */
const geoms = (far: number): Drawing2D["geom"][] => {
const near: Drawing2D["geom"][] = [
{ shape: "line", a: { x: 0, y: 0 }, b: { x: 4, y: 0 } },
{ shape: "line", a: { x: 2, y: -2 }, b: { x: 2, y: 2 } },
{ shape: "polyline", pts: [{ x: 6, y: 0 }, { x: 8, y: 1 }, { x: 8, y: 3 }], closed: false },
{ shape: "circle", center: { x: -3, y: 0 }, r: 1 },
];
for (let i = 0; i < far; i++) {
const x = 1000 + (i % 200) * 5, y = 1000 + Math.floor(i / 200) * 5;
near.push({ shape: "line", a: { x, y }, b: { x: x + 3, y: y + 2 } });
}
return near;
};
it("liefert in Cursornähe dasselbe wie das kleine Projekt (End-/Mittel-/Schnitt-/Randpunkt)", () => {
const small = drawProject(geoms(0));
const large = drawProject(geoms(3000)); // > Schwelle → Nähe-Modus
const probes: Vec2[] = [
{ x: 0.02, y: 0.03 }, // Endpunkt
{ x: 2.01, y: 0.02 }, // Schnittpunkt der beiden Linien
{ x: 1.0, y: 0.015 }, // Rand der ersten Linie
{ x: 8.01, y: 2.0 }, // Polylinie
{ x: -2.0, y: 0.01 }, // Kreis (Quadrant)
{ x: 3.0, y: 0.02 },
];
for (const raw of probes) {
const a = snapAt(small, raw, ALL);
const b = snapAt(large, raw, ALL);
expect(b?.kind).toBe(a?.kind);
expect(b?.point.x ?? NaN).toBeCloseTo(a?.point.x ?? NaN, 9);
expect(b?.point.y ?? NaN).toBeCloseTo(a?.point.y ?? NaN, 9);
}
});
it("fängt auch zwischen den vielen entfernten Linien (Endpunkt) und bleibt schnell", () => {
const big = drawProject(geoms(60000)); // ~ Grössenordnung eines Kataster-Imports
const t = performance.now();
const r = snapAt(big, { x: 1000.01, y: 1000.01 }, ALL);
const first = performance.now() - t; // inkl. einmaligem Aufbau des Index
expect(r?.kind).toBe("endpoint");
expect(r!.point.x).toBeCloseTo(1000, 6);
const t2 = performance.now();
for (let i = 0; i < 20; i++) snapAt(big, { x: 1000.01 + i * 0.001, y: 1000.01 }, ALL);
const perCall = (performance.now() - t2) / 20;
expect(first).toBeLessThan(3000);
expect(perCall).toBeLessThan(50);
});
});
+131 -54
View File
@@ -6,7 +6,7 @@
// Prioritäts-Reihenfolge (Vorrang bei nahem Abstand): endpoint > intersection >
// midpoint > onEdge > grid; ortho/Winkelraster ist eine Projektion (überlagert).
import type { Project, Vec2, Wall } from "../model/types";
import type { Drawing2D, Project, Vec2, Wall } from "../model/types";
import { getWallType, wallTypeThickness } from "../model/types";
import { add, leftNormal, lineIntersect, normalize, scale, sub } from "../model/geometry";
import { wallReferenceOffset } from "../model/wall";
@@ -15,6 +15,7 @@ import { columnFootprint } from "../geometry/column";
import { stairOutline } from "../geometry/stair";
import type { SnapKind, SnapResult, SnapSettings } from "./types";
import { sampleBezierChain, sampleCatmullRom, sampleUniformBSpline } from "./curves";
import { buildDrawingIndex, drawingsNear, isIndexable, pointSegDist, type DrawingIndex } from "../geometry/drawingIndex";
const dist = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);
const mid = (a: Vec2, b: Vec2): Vec2 => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
@@ -94,8 +95,105 @@ function closedPolySegs(pts: Vec2[]): Seg[] {
return segs;
}
/** Strecken EINER Zeichnung (Fangkandidaten), je nach Form. */
function drawingSegs(d: Drawing2D, segs: Seg[]): void {
const g = d.geom;
if (g.shape === "line") segs.push([g.a, g.b]);
else if (g.shape === "xline") {
// Weit verlängert (wie beim Rendern) — Lot-/Nächster-Punkt-Snap soll
// entlang der ganzen (optisch unendlichen) Linie greifen, nicht nur
// zwischen den beiden gesetzten Punkten.
const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y;
const len = Math.hypot(dx, dy);
if (len > 1e-6) {
const ux = dx / len, uy = dy / len, ext = 1000;
segs.push([
{ x: g.a.x - ux * ext, y: g.a.y - uy * ext },
{ x: g.b.x + ux * ext, y: g.b.y + uy * ext },
]);
}
}
else if (g.shape === "ray") {
// Wie xline, aber NUR über `b` hinaus verlängert (Anker `a` bleibt fest).
const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y;
const len = Math.hypot(dx, dy);
if (len > 1e-6) {
const ux = dx / len, uy = dy / len, ext = 1000;
segs.push([g.a, { x: g.b.x + ux * ext, y: g.b.y + uy * ext }]);
}
}
else if (g.shape === "polyline") {
for (let i = 0; i < g.pts.length - 1; i++) segs.push([g.pts[i], g.pts[i + 1]]);
if (g.closed && g.pts.length > 2) segs.push([g.pts[g.pts.length - 1], g.pts[0]]);
} else if (g.shape === "rect") {
const c1 = g.min, c3 = g.max;
const c2 = { x: g.max.x, y: g.min.y }, c4 = { x: g.min.x, y: g.max.y };
segs.push([c1, c2], [c2, c3], [c3, c4], [c4, c1]);
} else if (g.shape === "bezier") {
const pts = sampleBezierChain(g.pts);
for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]);
} else if (g.shape === "spline") {
const closed = g.closed && g.pts.length > 2;
const pts = g.mode === "control" ? sampleUniformBSpline(g.pts, closed) : sampleCatmullRom(g.pts, closed);
for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]);
if (closed) segs.push([pts[pts.length - 1], pts[0]]);
}
}
/** Kreise/Bögen/Ellipsen & Co.: bei grossen Projekten ohne die vielen Linien. */
function nonLineDrawings(all: readonly Drawing2D[]): readonly Drawing2D[] {
return all.length > LARGE_DRAWINGS ? getSnapIndex(all).others : all;
}
/** Ab so vielen Zeichnungen: nur Strecken in Cursornähe (Raster-Index) statt aller. */
const LARGE_DRAWINGS = 2000;
interface SnapDrawingIndex {
/** Linien/Polylinien (Massenfall), räumlich indiziert. */
index: DrawingIndex | null;
/** Alle übrigen Formen (Kreis, Bogen, Rechteck, Spline, …) — wenige, immer geprüft. */
others: Drawing2D[];
}
const snapIndexCache = new WeakMap<readonly Drawing2D[], SnapDrawingIndex>();
/** Index je `drawings2d`-Array-Identität (Projekt-Updates teilen unveränderte Arrays). */
function getSnapIndex(drawings: readonly Drawing2D[]): SnapDrawingIndex {
let c = snapIndexCache.get(drawings);
if (!c) {
const indexable: Drawing2D[] = [];
const others: Drawing2D[] = [];
for (const d of drawings) (isIndexable(d) ? indexable : others).push(d);
c = { index: buildDrawingIndex(indexable), others };
snapIndexCache.set(drawings, c);
}
return c;
}
/**
* Zeichnungen des Geschosses, die für den Fang in Frage kommen: bei grossen
* Projekten (Kataster-Import, ~10^5 Zeichnungen) nur die in `r` Umkreis von `at`
* (+ alle Nicht-Linien-Formen), sonst alle.
*/
function snapDrawings(input: SnapInput, near?: { at: Vec2; r: number }): Drawing2D[] {
const all = input.project.drawings2d;
const ok = (d: Drawing2D) => d.levelId === input.levelId && input.visibleCodes.has(d.categoryCode);
const out: Drawing2D[] = [];
if (near && all.length > LARGE_DRAWINGS) {
const c = getSnapIndex(all);
if (c.index) {
for (const i of drawingsNear(c.index, near.at, near.r)) {
const d = c.index.drawings[i];
if (ok(d)) out.push(d);
}
}
for (const d of c.others) if (ok(d)) out.push(d);
return out;
}
for (const d of all) if (ok(d)) out.push(d);
return out;
}
/** Sammelt alle sichtbaren Strecken des Geschosses (Wandachsen + 2D-Segmente). */
function collectSegments(input: SnapInput): Seg[] {
function collectSegments(input: SnapInput, near?: { at: Vec2; r: number }): Seg[] {
const segs: Seg[] = [];
for (const w of input.project.walls) {
if (w.floorId !== input.levelId) continue;
@@ -135,51 +233,7 @@ function collectSegments(input: SnapInput): Seg[] {
if (col.profile.kind === "rect") segs.push(...closedPolySegs(columnFootprint(col)));
// Runde Stützen: s. collectCircles (Zentrum/Quadranten statt Vieleck-Kanten).
}
for (const d of input.project.drawings2d) {
if (d.levelId !== input.levelId) continue;
if (!input.visibleCodes.has(d.categoryCode)) continue;
const g = d.geom;
if (g.shape === "line") segs.push([g.a, g.b]);
else if (g.shape === "xline") {
// Weit verlängert (wie beim Rendern) — Lot-/Nächster-Punkt-Snap soll
// entlang der ganzen (optisch unendlichen) Linie greifen, nicht nur
// zwischen den beiden gesetzten Punkten.
const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y;
const len = Math.hypot(dx, dy);
if (len > 1e-6) {
const ux = dx / len, uy = dy / len, ext = 1000;
segs.push([
{ x: g.a.x - ux * ext, y: g.a.y - uy * ext },
{ x: g.b.x + ux * ext, y: g.b.y + uy * ext },
]);
}
}
else if (g.shape === "ray") {
// Wie xline, aber NUR über `b` hinaus verlängert (Anker `a` bleibt fest).
const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y;
const len = Math.hypot(dx, dy);
if (len > 1e-6) {
const ux = dx / len, uy = dy / len, ext = 1000;
segs.push([g.a, { x: g.b.x + ux * ext, y: g.b.y + uy * ext }]);
}
}
else if (g.shape === "polyline") {
for (let i = 0; i < g.pts.length - 1; i++) segs.push([g.pts[i], g.pts[i + 1]]);
if (g.closed && g.pts.length > 2) segs.push([g.pts[g.pts.length - 1], g.pts[0]]);
} else if (g.shape === "rect") {
const c1 = g.min, c3 = g.max;
const c2 = { x: g.max.x, y: g.min.y }, c4 = { x: g.min.x, y: g.max.y };
segs.push([c1, c2], [c2, c3], [c3, c4], [c4, c1]);
} else if (g.shape === "bezier") {
const pts = sampleBezierChain(g.pts);
for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]);
} else if (g.shape === "spline") {
const closed = g.closed && g.pts.length > 2;
const pts = g.mode === "control" ? sampleUniformBSpline(g.pts, closed) : sampleCatmullRom(g.pts, closed);
for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]);
if (closed) segs.push([pts[pts.length - 1], pts[0]]);
}
}
for (const d of snapDrawings(input, near)) drawingSegs(d, segs);
// Bereits gesetzte Draft-Segmente (Polylinie/Wand im Bau).
for (let i = 0; i < input.draftPoints.length - 1; i++) {
segs.push([input.draftPoints[i], input.draftPoints[i + 1]]);
@@ -202,7 +256,7 @@ interface CircleGeom {
*/
function collectCircles(input: SnapInput): CircleGeom[] {
const out: CircleGeom[] = [];
for (const d of input.project.drawings2d) {
for (const d of nonLineDrawings(input.project.drawings2d)) {
if (d.levelId !== input.levelId) continue;
if (!input.visibleCodes.has(d.categoryCode)) continue;
const g = d.geom;
@@ -333,7 +387,30 @@ export function computeSnap(input: SnapInput): SnapResult | null {
settings.endpoint ||
settings.perpendicular ||
settings.parallel;
const segs = needSegs ? collectSegments(input) : [];
// Bei grossen Projekten (Kataster-Import: ~10^5 Zeichnungen, Mio. Strecken) NUR
// die Strecken in Cursornähe — vorher wurde bei JEDER Mausbewegung die ganze
// Liste gebaut und der Schnittpunkt-Fang prüfte ALLE Paare (O(N²): die Seite
// blockierte beim ersten Klick eines Zeichenwerkzeugs). Kleine Projekte bleiben
// exakt wie bisher.
const nearMode = input.project.drawings2d.length > LARGE_DRAWINGS;
const intRadius = tolM * 6;
let segs: Seg[] = [];
let intSegs: Seg[] = [];
if (needSegs) {
if (nearMode) {
const cand = collectSegments(input, { at: raw, r: intRadius });
const withDist = cand
.map((seg) => ({ seg, d: pointSegDist(raw, seg[0], seg[1]) }))
.filter((e) => e.d <= intRadius)
.sort((x, y) => x.d - y.d);
segs = withDist.filter((e) => e.d <= tolM).map((e) => e.seg);
// Schnittpunkte nur unter den nächsten Strecken (paarweise → quadratisch).
intSegs = withDist.slice(0, 64).map((e) => e.seg);
} else {
segs = collectSegments(input);
intSegs = segs;
}
}
// Teilpunkt-Verweilerkennung: braucht dieselben Strecken wie oben. Ohne sie
// (alle Objekt-Snap-Arten aus) bleiben "divide"/"parallel" ebenfalls inaktiv
@@ -407,10 +484,10 @@ export function computeSnap(input: SnapInput): SnapResult | null {
}
// intersection (paarweise Geraden-Schnitt der Strecken, nahe am Cursor).
if (settings.intersection) {
for (let i = 0; i < segs.length; i++) {
for (let j = i + 1; j < segs.length; j++) {
const [a, b] = segs[i];
const [c, d] = segs[j];
for (let i = 0; i < intSegs.length; i++) {
for (let j = i + 1; j < intSegs.length; j++) {
const [a, b] = intSegs[i];
const [c, d] = intSegs[j];
const x = lineIntersect(a, { x: b.x - a.x, y: b.y - a.y }, c, {
x: d.x - c.x,
y: d.y - c.y,
@@ -475,7 +552,7 @@ export function computeSnap(input: SnapInput): SnapResult | null {
// Ellipse: nur der Mittelpunkt (keine Quadranten — bei gedrehter Ellipse
// wären die "Achsenpunkte" ohnehin keine Kreis-Quadranten mehr).
if (settings.center) {
for (const d of input.project.drawings2d) {
for (const d of nonLineDrawings(input.project.drawings2d)) {
if (d.levelId !== input.levelId) continue;
if (!input.visibleCodes.has(d.categoryCode)) continue;
if (d.geom.shape === "ellipse") consider(d.geom.center, "center");