Kompakte Linien-Unterlage: Kataster-Linien nicht mehr als 3,7 Mio. Objekte
Die 'line'-Primitive einer Zeichnung ändern sich beim Bearbeiten nie, wurden aber bei jedem Plan-Aufbau als 3,7 Mio. dauerhafte JS-Objekte gehalten (~0,5 GB, GC-Last, mehrere O(N)-Durchgänge je Änderung). Plan.underlay: Zeichnungen, deren Primitive nur aus Linien-Segmenten (plus dem Polygon geschlossener Konturen) bestehen — Linie, Polylinie ohne Bogen/ Linienenden —, bleiben als Drawing2D. Ihre Linien entstehen erst beim Kompilieren eines GPU-Chunks (kurzlebig, über dieselbe addDrawing2D-Logik, also bitgleich zum normalen Pfad: Test vergleicht die Primitive als Menge) und werden nie dauerhaft gehalten. Das Polygon bleibt normales Primitiv (Auswahl/Füllung/Schraffur). Aus bei mono und Export. - GpuChunkCache: Unterlagen-Chunks aus Zeichnungen (Wiederverwendung bei gleichen Objekten + gleichem Kontext), Reihenfolge Referenz-Ebenen unten / Primitive / aktive Ebene oben, Dimmen weiter per Zeichen-Tönung. - Hover, Klick-Auswahl und Marquee arbeiten direkt auf den Zeichnungen (Raster über Bounding-Boxen, planView/underlayAccess.ts); Ergebnisse sind in Zufallstests identisch zu den Primitiv-Varianten. Hervorhebung erzeugt die Linien nur für die gewählten Zeichnungen. - Alle anderen Verbraucher (SVG-Fallback, WASM, natives Fenster, Gruppen- Isolation) rufen materializeUnderlay. - computeBounds nutzt eine je Zeichnung gecachte Bounding-Box statt aller Punkte. Headless-Chromium mit der echten Datei: Bild pixelgleich (Gesamtansicht 0,2 %, Zoom 8 Pixel), Klick-Auswahl und Marquee wie vorher. Gemessen (Luzern): Plan-Primitive 3,78 Mio. → 106 k; je Änderung Plan ~280 → ~30 ms, GPU-Chunks ~25 ms (2 Chunks neu).
This commit is contained in:
1 parent
ec8c51a2af
commit
31d46e8c8c
13 files changed
+911
-33
No files matched your search
+98
-18
@@ -15,8 +15,8 @@ import {
|
||||
} from "react";
|
||||
import type { ComponentProps, CSSProperties } from "react";
|
||||
import type { HatchRender, Plan, PlanImage, Primitive } from "./generatePlan";
|
||||
import { materializeGreyed } from "./generatePlan";
|
||||
import type { EdgeGrip, Vec2 } from "../model/types";
|
||||
import { materializeGreyed, materializeUnderlay, type UnderlayGroup } from "./generatePlan";
|
||||
import type { Drawing2D, EdgeGrip, Vec2 } from "../model/types";
|
||||
import type { ToolHandlers, ToolId, ToolMods } from "../tools/types";
|
||||
import type { HudFieldsState } from "../tools/hudFormat";
|
||||
import type { RichTextDoc } from "../text/richText";
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
pointSegDistPx,
|
||||
marqueeHit,
|
||||
marqueeHitDrawings,
|
||||
type ModelRect,
|
||||
marqueeHitCeilings,
|
||||
marqueeHitRooms,
|
||||
marqueeHitStairs,
|
||||
@@ -60,6 +61,12 @@ import { PlanGrid } from "./planView/PlanGrid";
|
||||
import { expandRegion, indexedInRegion, regionContains, type Bounds } from "./planView/cullPrimitives";
|
||||
import { buildSegmentIndex, nearestSegment, pointSegDist } from "./planView/segmentIndex";
|
||||
import { buildOwnerIndex, ownedBy, type OwnerField, type OwnerIndex } from "./planView/ownerIndex";
|
||||
import {
|
||||
buildDrawingIndex,
|
||||
marqueeHitUnderlay,
|
||||
nearestInDrawings,
|
||||
type DrawingIndex,
|
||||
} from "./planView/underlayAccess";
|
||||
import { endBusyAfterPaint } from "../state/busyStore";
|
||||
import { createCursorStore, useCursorValue, type CursorStore } from "../state/cursorStore";
|
||||
|
||||
@@ -777,10 +784,47 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
// übrigen Verbraucher (SVG-Overlay, Schraffur-Muster, WASM) lesen `greyed`
|
||||
// direkt am Primitiv und bekommen deshalb diese materialisierte Variante.
|
||||
// Linien werden nur geklont, wenn sie NICHT der WebGL-Pfad zeichnet.
|
||||
const plan = useMemo(
|
||||
() => materializeGreyed(planRaw, !useGpuRenderer || wantWasm),
|
||||
[planRaw, useGpuRenderer, wantWasm],
|
||||
);
|
||||
const plan = useMemo(() => {
|
||||
// Die kompakte Linien-Unterlage (planRaw.underlay) zeichnet nur der WebGL-Pfad
|
||||
// selbst; alle anderen Wege brauchen echte 'line'-Primitive.
|
||||
const lines = !useGpuRenderer || wantWasm;
|
||||
return materializeGreyed(lines ? materializeUnderlay(planRaw) : planRaw, lines);
|
||||
}, [planRaw, useGpuRenderer, wantWasm]);
|
||||
|
||||
// Kompakte Linien-Unterlage (nur im reinen WebGL-Modus noch als `plan.underlay`
|
||||
// vorhanden): Hover/Pick/Marquee/Hervorhebung greifen direkt auf die Zeichnungen
|
||||
// zu, Strukturen entstehen LAZY je Plan (s. planView/underlayAccess.ts).
|
||||
const underlayRef = useRef<{
|
||||
key: UnderlayGroup[];
|
||||
drawings: Drawing2D[];
|
||||
index?: DrawingIndex | null;
|
||||
ids?: Map<string, UnderlayGroup>;
|
||||
} | null>(null);
|
||||
const getUnderlay = () => {
|
||||
const groups = plan.underlay;
|
||||
if (!groups || groups.length === 0) return null;
|
||||
let c = underlayRef.current;
|
||||
if (!c || c.key !== groups) {
|
||||
c = { key: groups, drawings: groups.flatMap((g) => g.drawings) };
|
||||
underlayRef.current = c;
|
||||
}
|
||||
return c;
|
||||
};
|
||||
const getUnderlayIndex = (): DrawingIndex | null => {
|
||||
const c = getUnderlay();
|
||||
if (!c) return null;
|
||||
if (c.index === undefined) c.index = buildDrawingIndex(c.drawings);
|
||||
return c.index;
|
||||
};
|
||||
const getUnderlayIds = (): Map<string, UnderlayGroup> | null => {
|
||||
const c = getUnderlay();
|
||||
if (!c) return null;
|
||||
if (!c.ids) {
|
||||
c.ids = new Map();
|
||||
for (const g of c.key) for (const d of g.drawings) c.ids.set(d.id, g);
|
||||
}
|
||||
return c.ids;
|
||||
};
|
||||
|
||||
// Nur die Primitive, die das SVG überhaupt selbst zeichnet (der Rest kommt aus
|
||||
// WebGL/WASM bzw. — ohne GPU — aus `drawingRuns`), einmal je Plan/Modus
|
||||
@@ -1376,6 +1420,15 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
bestDist = pointSegDist(m, p.a, p.b) * pxPerM;
|
||||
}
|
||||
}
|
||||
const uIndex = getUnderlayIndex();
|
||||
if (uIndex) {
|
||||
const pxPerM = currentPxPerMeter();
|
||||
const hit = nearestInDrawings(uIndex, rawModelAt(clientX, clientY), 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);
|
||||
@@ -1397,17 +1450,25 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
// (eins je Segment, gleiche drawingId), unterteilt werden soll nur das
|
||||
// konkret gehoverte Segment, nicht das ganze Element.
|
||||
const nearestLineSegment = (clientX: number, clientY: number): { a: Vec2; b: Vec2 } | null => {
|
||||
const m = rawModelAt(clientX, clientY);
|
||||
const maxDist = LINE_PICK_PX / currentPxPerMeter();
|
||||
let best: { a: Vec2; b: Vec2 } | null = null;
|
||||
let bestDist = maxDist;
|
||||
const segmentIndex = getSegmentIndex();
|
||||
if (!segmentIndex) return null;
|
||||
const i = nearestSegment(
|
||||
segmentIndex,
|
||||
plan.primitives,
|
||||
rawModelAt(clientX, clientY),
|
||||
LINE_PICK_PX / currentPxPerMeter(),
|
||||
);
|
||||
if (i === null) return null;
|
||||
const p = plan.primitives[i] as Extract<Primitive, { kind: "line" }>;
|
||||
return { a: p.a, b: p.b };
|
||||
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 uIndex = getUnderlayIndex();
|
||||
if (uIndex) {
|
||||
const hit = nearestInDrawings(uIndex, m, bestDist);
|
||||
if (hit) best = { a: hit.a, b: hit.b };
|
||||
}
|
||||
return best;
|
||||
};
|
||||
|
||||
// Trifft der Klick ein Text-2D-Element (kind "drawingText")? Grosszügige Modell-
|
||||
@@ -1626,6 +1687,15 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
return null;
|
||||
};
|
||||
|
||||
// Marquee über Zeichnungen: Primitive (ohne die der kompakten Unterlage, deren
|
||||
// Polygon-Punkte allein sonst ein anderes Ergebnis lieferten) + Unterlage.
|
||||
const marqueeHitAll = (rect: ModelRect, crossing: boolean): string[] => {
|
||||
const ids = getUnderlayIds();
|
||||
const fromPrims = marqueeHitDrawings(plan.primitives, rect, crossing, ids ?? undefined);
|
||||
const u = getUnderlay();
|
||||
return u ? [...fromPrims, ...marqueeHitUnderlay(u.drawings, rect, crossing)] : fromPrims;
|
||||
};
|
||||
|
||||
// Maus-Schema (docs/design/context-menu.md): MITTE = schwenken (Pan),
|
||||
// LINKS = Auswahl, RECHTS = Kontextmenü, RAD = Zoom.
|
||||
const onPointerDown = (e: React.PointerEvent<SVGSVGElement>) => {
|
||||
@@ -2079,7 +2149,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
if (onMarquee) {
|
||||
onMarquee({
|
||||
wallIds: marqueeHit(plan.primitives, rect, crossing),
|
||||
drawingIds: marqueeHitDrawings(plan.primitives, rect, crossing),
|
||||
drawingIds: marqueeHitAll(rect, crossing),
|
||||
ceilingIds: marqueeHitCeilings(plan.primitives, rect, crossing),
|
||||
roomIds: marqueeHitRooms(plan.primitives, rect, crossing),
|
||||
stairIds: marqueeHitStairs(plan.primitives, rect, crossing),
|
||||
@@ -2346,7 +2416,17 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
? new Set(selectedDrawingIds)
|
||||
: null;
|
||||
if (!ids) return [];
|
||||
return primsOwnedBy("drawingId", selectedDrawingIds, (p): p is Extract<Primitive, { kind: "line" | "polygon" }> => p.kind === "line" || p.kind === "polygon");
|
||||
const fromPrims = primsOwnedBy("drawingId", selectedDrawingIds, (p): p is Extract<Primitive, { kind: "line" | "polygon" }> => p.kind === "line" || p.kind === "polygon");
|
||||
// Linien kompakt gehaltener Zeichnungen entstehen nur für die gewählten (wenige).
|
||||
const underIds = getUnderlayIds();
|
||||
if (!underIds || !selectedDrawingIds) return fromPrims;
|
||||
const extra: Array<Extract<Primitive, { kind: "line" | "polygon" }>> = [];
|
||||
for (const id of selectedDrawingIds) {
|
||||
const g = underIds.get(id);
|
||||
const d = g?.drawings.find((x) => x.id === id);
|
||||
if (g && d) for (const pr of g.build([d])) if (pr.kind === "line") extra.push(pr);
|
||||
}
|
||||
return extra.length ? [...fromPrims, ...extra] : fromPrims;
|
||||
}, [plan, selectedDrawingIds]);
|
||||
|
||||
// Hervorhebung ausgewählter TEXT-Objekte (Auswahl-Rahmen, Nutzer-Wunsch):
|
||||
|
||||
+121
-6
@@ -72,7 +72,13 @@ import {
|
||||
import { addCeilingPoche } from "./generatePlan/ceilings";
|
||||
import { addContextContours } from "./generatePlan/context";
|
||||
import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension";
|
||||
import { addDrawing2D } from "./generatePlan/drawing2d";
|
||||
import {
|
||||
addDrawing2D,
|
||||
addDrawing2DWithoutLines,
|
||||
drawingLinePrims,
|
||||
isCompactUnderlayEligible,
|
||||
} from "./generatePlan/drawing2d";
|
||||
import { drawingBox } from "./generatePlan/drawingBounds";
|
||||
import { addDoorSymbol, addOpeningSymbol } from "./generatePlan/openings";
|
||||
import { addRoof } from "./generatePlan/roofs";
|
||||
import { addRoomArea } from "./generatePlan/rooms";
|
||||
@@ -200,6 +206,65 @@ export interface Plan {
|
||||
* {@link materializeGreyed} auf.
|
||||
*/
|
||||
greyedRanges?: Array<[number, number]>;
|
||||
/**
|
||||
* KOMPAKTE Linien-Unterlage (nur in der interaktiven Ansicht, s.
|
||||
* {@link UnderlayGroup}): Zeichnungen, deren 'line'-Primitive NICHT in
|
||||
* `primitives` stehen. Alle Verbraucher, die diese Linien als Primitive
|
||||
* brauchen (SVG-Fallback, WASM, nativ, Gruppen-Isolation), rufen
|
||||
* {@link materializeUnderlay}.
|
||||
*/
|
||||
underlay?: UnderlayGroup[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Gruppe kompakt gehaltener Zeichnungen. Ihre Linien entstehen erst beim
|
||||
* Kompilieren eines GPU-Chunks (kurzlebig, `build`), nicht als dauerhafte
|
||||
* Primitive: bei einem Kataster-Import 3,7 Mio. Objekte weniger im Speicher und
|
||||
* keine O(N)-Durchgänge mehr bei jeder Änderung.
|
||||
*/
|
||||
export interface UnderlayGroup {
|
||||
drawings: Drawing2D[];
|
||||
/** Linien dieser Zeichnungen sind per Kategorie gedimmt (in `build` eingebacken). */
|
||||
catGreyed: boolean;
|
||||
/** Ganze Gruppe gedimmt darstellen (andere Ebene als Referenz) — beim Zeichnen. */
|
||||
tint: boolean;
|
||||
/** true = über den übrigen Primitiven zeichnen (aktive Ebene), false = darunter (Referenz-Ebene). */
|
||||
above: boolean;
|
||||
/** Referenzen, von denen die erzeugten Linien abhängen (Cache-Schlüssel des GPU-Chunks). */
|
||||
ctx: readonly unknown[];
|
||||
/** Erzeugt die 'line'-Primitive der gegebenen Zeichnungen (Teilmenge dieser Gruppe). */
|
||||
build: (drawings: Drawing2D[]) => Primitive[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Macht aus `plan.underlay` wieder gewöhnliche 'line'-Primitive (für Verbraucher,
|
||||
* die Primitive brauchen). Reihenfolge: Referenz-Ebenen unten, aktive oben;
|
||||
* gedimmte Referenz-Linien werden über `greyedRanges` markiert.
|
||||
*/
|
||||
export function materializeUnderlay(plan: Plan): Plan {
|
||||
const groups = plan.underlay;
|
||||
if (!groups || groups.length === 0) return plan;
|
||||
const below: Primitive[] = [];
|
||||
const above: Primitive[] = [];
|
||||
const belowGreyed: Array<[number, number]> = [];
|
||||
for (const g of groups) {
|
||||
const target = g.above ? above : below;
|
||||
const from = target.length;
|
||||
for (const pr of g.build(g.drawings)) target.push(pr);
|
||||
if (!g.above && g.tint && target.length > from) belowGreyed.push([from, target.length]);
|
||||
}
|
||||
const primitives: Primitive[] = [];
|
||||
for (const pr of below) primitives.push(pr);
|
||||
for (const pr of plan.primitives) primitives.push(pr);
|
||||
for (const pr of above) primitives.push(pr);
|
||||
const shifted = (plan.greyedRanges ?? []).map(([a, b]): [number, number] => [a + below.length, b + below.length]);
|
||||
const ranges = [...belowGreyed, ...shifted];
|
||||
return {
|
||||
...plan,
|
||||
primitives,
|
||||
underlay: undefined,
|
||||
greyedRanges: ranges.length ? ranges : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/** Ob Index `i` in einem der (sortierten, disjunkten) Bereiche liegt. */
|
||||
@@ -268,6 +333,12 @@ export function generatePlan(
|
||||
* bestehende Aufrufstelle mit positionalen Argumenten verrutscht.
|
||||
*/
|
||||
forPrint = false,
|
||||
/**
|
||||
* Kompakte Linien-Unterlage statt dauerhafter 'line'-Primitive (s.
|
||||
* {@link UnderlayGroup}) — NUR für die interaktive GPU-Ansicht. Aus bei
|
||||
* Export/mono (toMono mutiert Linienfarben).
|
||||
*/
|
||||
compactUnderlay = false,
|
||||
): Plan {
|
||||
const primitives: Primitive[] = [];
|
||||
// Aktives Geschoss (für die Grundriss-Schnitthöhe der Treppen).
|
||||
@@ -523,10 +594,37 @@ export function generatePlan(
|
||||
}
|
||||
|
||||
// 2D-Zeichengeometrie zuletzt (über der Poché).
|
||||
const compact = compactUnderlay && !mono && !forPrint;
|
||||
const underNormal: Drawing2D[] = [];
|
||||
const underGreyed: Drawing2D[] = [];
|
||||
for (const d of drawings) {
|
||||
const greyed = categoryDisplay(d.categoryCode).greyed;
|
||||
addDrawing2D(primitives, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator, !mono);
|
||||
if (compact && isCompactUnderlayEligible(d)) {
|
||||
addDrawing2DWithoutLines(primitives, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator);
|
||||
(greyed ? underGreyed : underNormal).push(d);
|
||||
} else {
|
||||
addDrawing2D(primitives, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator, !mono);
|
||||
}
|
||||
}
|
||||
const underlay: UnderlayGroup[] = [];
|
||||
const mkGroup = (ds: Drawing2D[], catGreyed: boolean): UnderlayGroup => ({
|
||||
drawings: ds,
|
||||
catGreyed,
|
||||
tint: false,
|
||||
above: true,
|
||||
// Alles, wovon `build` abhängt (s. drawingPrimCache): ändert sich eine davon,
|
||||
// müssen die GPU-Chunks dieser Gruppe neu erzeugt werden.
|
||||
ctx: [project.lineStyles, project.hatches, project.layers, scaleDenominator],
|
||||
build: (list) => {
|
||||
const out: Primitive[] = [];
|
||||
for (const d of list) {
|
||||
drawingLinePrims(out, project, d, catGreyed, lwByCode, colorByCode, catByCode, scaleDenominator);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
});
|
||||
if (underNormal.length) underlay.push(mkGroup(underNormal, false));
|
||||
if (underGreyed.length) underlay.push(mkGroup(underGreyed, true));
|
||||
|
||||
// Extrudierte Körper (truck-Integration): das Quell-Profil wurde beim
|
||||
// Extrudieren aus `drawings2d` entfernt (s. `extrude.ts` appendExtrudedSolid)
|
||||
@@ -574,6 +672,7 @@ export function generatePlan(
|
||||
primitives,
|
||||
bounds: computeBounds(project, walls, drawings, ceilings, stairs, rooms, roofs),
|
||||
backgroundImages,
|
||||
...(underlay.length ? { underlay } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -613,6 +712,8 @@ export function generateVisibleLevelsPlan(
|
||||
mono = false,
|
||||
levelDisplay: CategoryDisplayResolver = SHOW_ALL,
|
||||
scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR,
|
||||
/** Kompakte Linien-Unterlage (s. `UnderlayGroup`) — nur die interaktive GPU-Ansicht. */
|
||||
compactUnderlay = false,
|
||||
): Plan {
|
||||
const active = project.drawingLevels.find((l) => l.id === activeLevelId);
|
||||
const siblings =
|
||||
@@ -622,6 +723,7 @@ export function generateVisibleLevelsPlan(
|
||||
|
||||
const primitives: Primitive[] = [];
|
||||
const greyedRanges: Array<[number, number]> = [];
|
||||
const underlay: UnderlayGroup[] = [];
|
||||
const bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
|
||||
const extend = (b: Plan["bounds"]) => {
|
||||
bounds.minX = Math.min(bounds.minX, b.minX);
|
||||
@@ -645,7 +747,10 @@ export function generateVisibleLevelsPlan(
|
||||
mono,
|
||||
false, // includeGlobal: Schnittlinien/Kontext/Luftbilder nur einmal (aktiv)
|
||||
scaleDenominator,
|
||||
false,
|
||||
compactUnderlay,
|
||||
);
|
||||
for (const g of p.underlay ?? []) underlay.push({ ...g, tint: d.greyed, above: false });
|
||||
// KEIN `primitives.push(...p.primitives)`: bei grossen Importen (z. B. ein
|
||||
// Kataster-DXF einer ganzen Stadt, hunderttausende Drawing2D-Elemente →
|
||||
// ebenso viele Primitives) sprengt der Spread-Operator die Argumentzahl-
|
||||
@@ -658,7 +763,7 @@ export function generateVisibleLevelsPlan(
|
||||
// Leere Ebenen melden als Platzhalter (0,0)–(1,1) — NICHT mitzählen: sonst zog
|
||||
// jede leere Nachbar-Ebene den Ausschnitt bis zum Ursprung (bei Landes-
|
||||
// koordinaten ~2,7 Mio. m daneben → "Einpassen" zeigte nichts).
|
||||
if (p.primitives.length > 0) extend(p.bounds);
|
||||
if (p.primitives.length > 0 || p.underlay) extend(p.bounds);
|
||||
}
|
||||
|
||||
const activePlan = generatePlan(
|
||||
@@ -671,16 +776,20 @@ export function generateVisibleLevelsPlan(
|
||||
mono,
|
||||
true,
|
||||
scaleDenominator,
|
||||
false,
|
||||
compactUnderlay,
|
||||
);
|
||||
for (const pr of activePlan.primitives) primitives.push(pr);
|
||||
for (const g of activePlan.underlay ?? []) underlay.push(g);
|
||||
// Aktive Ebene leer UND keine Nachbar-Ebene mit Inhalt → Platzhalter-Ausmass.
|
||||
if (activePlan.primitives.length > 0 || bounds.minX === Infinity) extend(activePlan.bounds);
|
||||
if (activePlan.primitives.length > 0 || activePlan.underlay || bounds.minX === Infinity) extend(activePlan.bounds);
|
||||
|
||||
return {
|
||||
primitives,
|
||||
bounds,
|
||||
backgroundImages: activePlan.backgroundImages,
|
||||
...(greyedRanges.length ? { greyedRanges } : {}),
|
||||
...(underlay.length ? { underlay } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -926,8 +1035,14 @@ function computeBounds(
|
||||
}
|
||||
for (const d of drawings) {
|
||||
const g = d.geom;
|
||||
if (g.shape === "line") { acc(g.a); acc(g.b); }
|
||||
else if (g.shape === "polyline") g.pts.forEach(acc);
|
||||
if (g.shape === "line" || g.shape === "polyline") {
|
||||
// Box je Zeichnung gecacht (drawingBounds.ts) statt über alle Punkte.
|
||||
const b = drawingBox(d);
|
||||
if (isFinite(b.minX)) {
|
||||
acc({ x: b.minX, y: b.minY });
|
||||
acc({ x: b.maxX, y: b.maxY });
|
||||
}
|
||||
}
|
||||
else if (g.shape === "rect") { acc(g.min); acc(g.max); }
|
||||
else if (g.shape === "circle" || g.shape === "arc") {
|
||||
acc({ x: g.center.x - g.r, y: g.center.y - g.r });
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// Kompakte Linien-Unterlage (Plan.underlay): materialisiert muss sie EXAKT
|
||||
// dieselben Primitive ergeben wie der gewöhnliche Pfad (nur anders angeordnet).
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { generatePlan, generateVisibleLevelsPlan, materializeUnderlay, materializeGreyed } from "./generatePlan";
|
||||
import type { Drawing2D, DrawingLevel, Project } from "../model/types";
|
||||
|
||||
const level = (id: string): DrawingLevel =>
|
||||
({ id, name: id, kind: "drawing", visible: true, locked: false }) as unknown as DrawingLevel;
|
||||
|
||||
const SHARED = {
|
||||
lineStyles: [] as Project["lineStyles"],
|
||||
hatches: [{ id: "none", name: "Ohne", pattern: "none", scale: 1, angle: 0, color: "#111" }] as Project["hatches"],
|
||||
layers: [
|
||||
{ code: "60", name: "Zeichnung", color: "#0a0a0a", lw: 0.25, visible: true, locked: false },
|
||||
{ code: "61", name: "Rot", color: "#ff0000", lw: 0.5, visible: true, locked: false },
|
||||
] as Project["layers"],
|
||||
};
|
||||
|
||||
const poly = (id: string, cat: string, pts: [number, number][], closed: boolean, extra: object = {}): Drawing2D =>
|
||||
({
|
||||
id,
|
||||
type: "drawing2d",
|
||||
levelId: "L1",
|
||||
categoryCode: cat,
|
||||
geom: { shape: "polyline", pts: pts.map(([x, y]) => ({ x, y })), closed },
|
||||
...extra,
|
||||
}) as Drawing2D;
|
||||
|
||||
function project(drawings: Drawing2D[], levels = [level("L1")]): Project {
|
||||
return {
|
||||
id: "t",
|
||||
name: "T",
|
||||
...SHARED,
|
||||
components: [],
|
||||
wallTypes: [],
|
||||
drawingLevels: levels,
|
||||
walls: [],
|
||||
doors: [],
|
||||
openings: [],
|
||||
ceilings: [],
|
||||
stairs: [],
|
||||
rooms: [],
|
||||
drawings2d: drawings,
|
||||
context: [],
|
||||
} as unknown as Project;
|
||||
}
|
||||
|
||||
const drawings: Drawing2D[] = [
|
||||
poly("open", "60", [[0, 0], [1, 0], [2, 1], [3, 1]], false),
|
||||
poly("closed", "61", [[10, 10], [12, 10], [12, 12], [10, 12]], true),
|
||||
poly("filled", "60", [[20, 20], [22, 20], [22, 22]], true, { fillColor: "#000000" }),
|
||||
poly("bulge", "60", [[30, 0], [32, 0], [32, 2]], false, { geom: { shape: "polyline", pts: [{ x: 30, y: 0 }, { x: 32, y: 0 }, { x: 32, y: 2 }], closed: false, bulge: [0.5, 0] } }),
|
||||
{ id: "ln", type: "drawing2d", levelId: "L1", categoryCode: "60", geom: { shape: "line", a: { x: 0, y: 5 }, b: { x: 4, y: 5 } } } as Drawing2D,
|
||||
{ id: "ci", type: "drawing2d", levelId: "L1", categoryCode: "60", geom: { shape: "circle", center: { x: 5, y: 5 }, r: 1 } } as Drawing2D,
|
||||
];
|
||||
const visible = new Set(["60", "61"]);
|
||||
const key = (p: unknown) => JSON.stringify(p);
|
||||
|
||||
describe("kompakte Linien-Unterlage", () => {
|
||||
it("materialisiert ergibt dieselben Primitive wie der normale Pfad (als Menge)", () => {
|
||||
const p = project(drawings);
|
||||
const normal = generatePlan(p, "L1", visible);
|
||||
const compact = generatePlan(p, "L1", visible, undefined, "mittel", false, false, true, 100, false, true);
|
||||
expect(compact.underlay?.length).toBeGreaterThan(0);
|
||||
// Die kompakten Plan-Primitive enthalten KEINE Linien der berechtigten Zeichnungen …
|
||||
const compactLineIds = new Set(compact.primitives.filter((q) => q.kind === "line").map((q) => (q as any).drawingId));
|
||||
expect(compactLineIds.has("open")).toBe(false);
|
||||
expect(compactLineIds.has("closed")).toBe(false);
|
||||
// … aber Bogen-Polylinien, Kreise etc. bleiben unverändert im Plan.
|
||||
expect(compact.primitives.some((q) => (q as any).drawingId === "ci")).toBe(true);
|
||||
const mat = materializeUnderlay(compact);
|
||||
expect(mat.underlay).toBeUndefined();
|
||||
expect(mat.primitives.map(key).sort()).toEqual(normal.primitives.map(key).sort());
|
||||
expect(mat.bounds).toEqual(normal.bounds);
|
||||
});
|
||||
|
||||
it("Zeichnung geschlossener Kontur behält ihr Polygon im Plan (Auswahl/Füllung)", () => {
|
||||
const compact = generatePlan(project(drawings), "L1", visible, undefined, "mittel", false, false, true, 100, false, true);
|
||||
expect(compact.primitives.some((q) => q.kind === "polygon" && (q as any).drawingId === "closed")).toBe(true);
|
||||
expect(compact.primitives.some((q) => q.kind === "polygon" && (q as any).drawingId === "filled")).toBe(true);
|
||||
});
|
||||
|
||||
it("mono und Export (forPrint) bleiben beim normalen Pfad", () => {
|
||||
const p = project(drawings);
|
||||
expect(generatePlan(p, "L1", visible, undefined, "mittel", false, true, true, 100, false, true).underlay).toBeUndefined();
|
||||
expect(generatePlan(p, "L1", visible, undefined, "mittel", false, false, true, 100, true, true).underlay).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Kategorie-Dimmung: gedimmte Zeichnungen landen in eigener Gruppe, Linien tragen greyed", () => {
|
||||
const p = project(drawings);
|
||||
const display = (code: string) => ({ render: true, greyed: code === "61", locked: false });
|
||||
const compact = generatePlan(p, "L1", visible, display, "mittel", false, false, true, 100, false, true);
|
||||
const greyedGroup = compact.underlay!.find((g) => g.catGreyed)!;
|
||||
expect(greyedGroup.drawings.map((d) => d.id)).toEqual(["closed"]);
|
||||
expect(greyedGroup.build(greyedGroup.drawings).every((q) => (q as any).greyed === true)).toBe(true);
|
||||
});
|
||||
|
||||
it("Referenz-Ebene: Gruppe liegt unterhalb und ist als Tönung markiert; Materialisierung markiert sie in greyedRanges", () => {
|
||||
const sibling = { ...poly("sib", "60", [[0, 0], [5, 0], [5, 5]], false), levelId: "L2" } as Drawing2D;
|
||||
const p = project([drawings[0], sibling], [level("L1"), level("L2")]);
|
||||
const display = (id: string) => ({ render: true, greyed: id !== "L1", locked: false });
|
||||
const plan = generateVisibleLevelsPlan(p, "L1", visible, undefined, "mittel", false, false, display, 100, true);
|
||||
const below = plan.underlay!.filter((g) => !g.above);
|
||||
const above = plan.underlay!.filter((g) => g.above);
|
||||
expect(below.map((g) => g.drawings[0].id)).toEqual(["sib"]);
|
||||
expect(below[0].tint).toBe(true);
|
||||
expect(above.map((g) => g.drawings[0].id)).toEqual(["open"]);
|
||||
const mat = materializeGreyed(materializeUnderlay(plan), true);
|
||||
const sibLines = mat.primitives.filter((q) => (q as any).drawingId === "sib");
|
||||
const openLines = mat.primitives.filter((q) => (q as any).drawingId === "open");
|
||||
expect(sibLines.length).toBeGreaterThan(0);
|
||||
expect(sibLines.every((q) => (q as any).greyed === true)).toBe(true);
|
||||
expect(openLines.every((q) => !(q as any).greyed)).toBe(true);
|
||||
});
|
||||
|
||||
it("leere Ebene ohne Primitive aber mit Unterlage zählt zum Ausmass", () => {
|
||||
const only = [poly("far", "60", [[2_665_000, 1_211_000], [2_665_010, 1_211_000]], false)];
|
||||
const p = project(only, [level("L1"), level("L2")]);
|
||||
const plan = generateVisibleLevelsPlan(p, "L1", visible, undefined, "mittel", false, false, undefined, 100, true);
|
||||
expect(plan.primitives.length).toBe(0);
|
||||
expect(plan.bounds.minX).toBeGreaterThan(2_000_000);
|
||||
});
|
||||
});
|
||||
@@ -219,6 +219,95 @@ export function addDrawing2D(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* KOMPAKTER Unterlagen-Pfad (s. `Plan.underlay`): Zeichnungen, deren Primitive
|
||||
* nur aus Linien-Segmenten (plus ggf. einem Flächen-Polygon bei geschlossenen
|
||||
* Konturen) bestehen. Bei einem Kataster-Import sind das 3,7 Mio. 'line'-
|
||||
* Primitive, die sich beim Bearbeiten NIE ändern — als dauerhafte JS-Objekte
|
||||
* kosteten sie ~0,5 GB, GC-Last und bei jeder Änderung mehrere O(N)-Durchgänge.
|
||||
* Statt dessen bleiben diese Zeichnungen als `Drawing2D` und ihre Linien werden
|
||||
* nur bei Bedarf (GPU-Chunk neu zu kompilieren) kurzlebig erzeugt.
|
||||
*
|
||||
* Ausgeschlossen: Bogen-Segmente (Bulge → `drawingArc`), Linienenden (Pfeile/
|
||||
* Kreise → eigene Primitive). `line`/offene und geschlossene Polylinien sonst
|
||||
* immer.
|
||||
*/
|
||||
export function isCompactUnderlayEligible(d: Drawing2D): boolean {
|
||||
const g = d.geom;
|
||||
if (g.shape === "line") return !d.endMarks?.start && !d.endMarks?.end;
|
||||
if (g.shape !== "polyline") return false;
|
||||
if (d.endMarks?.start || d.endMarks?.end) return false;
|
||||
return !g.bulge || g.bulge.every((b) => !b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wie {@link addDrawing2D}, aber OHNE die 'line'-Primitive (die liefert
|
||||
* {@link drawingLinePrims} bei Bedarf): übrig bleiben z. B. das Polygon einer
|
||||
* geschlossenen Kontur (Auswahl/Füllung/Schraffur). Gecacht je Drawing2D-Objekt.
|
||||
*/
|
||||
export function addDrawing2DWithoutLines(
|
||||
out: Primitive[],
|
||||
project: Project,
|
||||
d: Drawing2D,
|
||||
greyed: boolean,
|
||||
lwByCode: Map<string, number>,
|
||||
colorByCode: Map<string, string>,
|
||||
catByCode: Map<string, LayerCategory>,
|
||||
scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR,
|
||||
): void {
|
||||
const hit = withoutLinesCache.get(d);
|
||||
if (
|
||||
hit &&
|
||||
hit.lineStyles === project.lineStyles &&
|
||||
hit.hatches === project.hatches &&
|
||||
hit.layers === project.layers &&
|
||||
hit.greyed === greyed &&
|
||||
hit.scaleDenominator === scaleDenominator
|
||||
) {
|
||||
for (const p of hit.prims) out.push(p);
|
||||
return;
|
||||
}
|
||||
const tmp: Primitive[] = [];
|
||||
addDrawing2D(tmp, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator);
|
||||
const kept = tmp.filter((p) => p.kind !== "line");
|
||||
withoutLinesCache.set(d, {
|
||||
lineStyles: project.lineStyles,
|
||||
hatches: project.hatches,
|
||||
layers: project.layers,
|
||||
greyed,
|
||||
scaleDenominator,
|
||||
prims: kept,
|
||||
});
|
||||
for (const p of kept) out.push(p);
|
||||
}
|
||||
const withoutLinesCache = new WeakMap<
|
||||
Drawing2D,
|
||||
{
|
||||
lineStyles: Project["lineStyles"];
|
||||
hatches: Project["hatches"];
|
||||
layers: Project["layers"];
|
||||
greyed: boolean;
|
||||
scaleDenominator: number;
|
||||
prims: Primitive[];
|
||||
}
|
||||
>();
|
||||
|
||||
/** Nur die 'line'-Primitive einer Zeichnung (kurzlebig, für GPU-Chunk-Kompilierung). */
|
||||
export function drawingLinePrims(
|
||||
out: Primitive[],
|
||||
project: Project,
|
||||
d: Drawing2D,
|
||||
greyed: boolean,
|
||||
lwByCode: Map<string, number>,
|
||||
colorByCode: Map<string, string>,
|
||||
catByCode: Map<string, LayerCategory>,
|
||||
scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR,
|
||||
): void {
|
||||
const tmp: Primitive[] = [];
|
||||
addDrawing2D(tmp, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator);
|
||||
for (const p of tmp) if (p.kind === "line") out.push(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache der erzeugten Primitive je Drawing2D-OBJEKT. Projekt-Updates sind
|
||||
* immutabel mit Structural Sharing — ein unveränderte Zeichnung bleibt dasselbe
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// Bounding-Box je Drawing2D-OBJEKT (gecacht). Projekt-Updates teilen unveränderte
|
||||
// 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";
|
||||
|
||||
export interface Box {
|
||||
minX: number;
|
||||
minY: number;
|
||||
maxX: number;
|
||||
maxY: number;
|
||||
}
|
||||
|
||||
const boxCache = new WeakMap<Drawing2D, Box>();
|
||||
|
||||
/** Punkte einer Linie/Polylinie; andere Formen: leer. */
|
||||
export function linePointsOf(d: Drawing2D): readonly Vec2[] {
|
||||
const g = d.geom;
|
||||
if (g.shape === "line") return [g.a, g.b];
|
||||
if (g.shape === "polyline") return g.pts;
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Box über die Punkte einer Linie/Polylinie (Infinity-Box, wenn keine Punkte). */
|
||||
export function drawingBox(d: Drawing2D): Box {
|
||||
let b = boxCache.get(d);
|
||||
if (b) return b;
|
||||
b = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
|
||||
for (const p of linePointsOf(d)) {
|
||||
if (p.x < b.minX) b.minX = p.x;
|
||||
if (p.x > b.maxX) b.maxX = p.x;
|
||||
if (p.y < b.minY) b.minY = p.y;
|
||||
if (p.y > b.maxY) b.maxY = p.y;
|
||||
}
|
||||
boxCache.set(d, b);
|
||||
return b;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import type { Primitive } from '../generatePlan';
|
||||
import type { Primitive, UnderlayGroup } from '../generatePlan';
|
||||
import type { Drawing2D } from '../../model/types';
|
||||
import { GpuChunkCache, splitIntoChunks } from './glPlanChunks';
|
||||
|
||||
const line = (x: number, drawingId: string): Primitive => ({
|
||||
@@ -158,3 +159,57 @@ describe('GpuChunkCache', () => {
|
||||
expect(cache.geometries).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GpuChunkCache: kompakte Unterlage', () => {
|
||||
const drawing = (id: string, x: number) =>
|
||||
({ id, type: 'drawing2d', levelId: 'L', categoryCode: '60', geom: { shape: 'line', a: { x, y: 0 }, b: { x: x + 1, y: 0 } } }) as unknown as Drawing2D;
|
||||
const many = (n: number): Drawing2D[] => Array.from({ length: n }, (_, i) => drawing(`u${i}`, i));
|
||||
const group = (drawings: Drawing2D[], over: Partial<UnderlayGroup> = {}): UnderlayGroup => ({
|
||||
drawings,
|
||||
catGreyed: false,
|
||||
tint: false,
|
||||
above: true,
|
||||
ctx: [1],
|
||||
build: (ds) => ds.map((d) => line((d.geom as any).a.x, d.id)),
|
||||
...over,
|
||||
});
|
||||
|
||||
it('kompiliert beim zweiten Lauf nichts neu; eine geänderte Zeichnung nur ihren Chunk', () => {
|
||||
const { gl, deleted } = makeGl();
|
||||
const cache = new GpuChunkCache(gl);
|
||||
const ds = many(2000);
|
||||
cache.update([], 90, 6, undefined, [group(ds)]);
|
||||
const total = cache.lastStats.chunks;
|
||||
expect(total).toBeGreaterThan(2);
|
||||
cache.update([], 90, 6, undefined, [group(ds)]);
|
||||
expect(cache.lastStats.recompiled).toBe(0);
|
||||
const edited = ds.slice();
|
||||
edited[1000] = drawing('u1000', 5000);
|
||||
cache.update([], 90, 6, undefined, [group(edited)]);
|
||||
expect(cache.lastStats.recompiled).toBe(1);
|
||||
cache.update([], 90, 6, undefined, [group(edited)]);
|
||||
expect(deleted.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('geänderter Kontext (ctx) erzwingt Neukompilierung aller Chunks', () => {
|
||||
const { gl } = makeGl();
|
||||
const cache = new GpuChunkCache(gl);
|
||||
const ds = many(2000);
|
||||
cache.update([], 90, 6, undefined, [group(ds, { ctx: [1] })]);
|
||||
const total = cache.lastStats.chunks;
|
||||
cache.update([], 90, 6, undefined, [group(ds, { ctx: [2] })]);
|
||||
expect(cache.lastStats.recompiled).toBe(total);
|
||||
});
|
||||
|
||||
it('Reihenfolge: Referenz-Ebenen unten, Primitive, aktive Ebene oben; Tönung nur bei tint', () => {
|
||||
const { gl } = makeGl();
|
||||
const cache = new GpuChunkCache(gl);
|
||||
const below = group(many(3), { above: false, tint: true });
|
||||
const above = group([0, 1, 2].map((i) => drawing(`a${i}`, i)), { above: true });
|
||||
cache.update(scene().slice(0, 6), 90, 6, undefined, [above, below]);
|
||||
const g = cache.geometries;
|
||||
expect(g[0].greyed).toBe(true); // unten, getönt
|
||||
expect(g[g.length - 1].greyed).toBeFalsy(); // oben, normal
|
||||
expect(g.length).toBe(3); // 1 unten + 1 Primitiv-Chunk + 1 oben
|
||||
});
|
||||
});
|
||||
@@ -22,7 +22,8 @@
|
||||
* Bögen neu tesselliert.
|
||||
*/
|
||||
|
||||
import type { Primitive } from '../generatePlan';
|
||||
import type { Primitive, UnderlayGroup } from '../generatePlan';
|
||||
import type { Drawing2D } from '../../model/types';
|
||||
import { compilePrimitivesToGpu } from './glPlanCompile';
|
||||
import type { GpuGeometry } from './glPlanTypes';
|
||||
|
||||
@@ -96,6 +97,110 @@ export interface ChunkStats {
|
||||
recompiled: number;
|
||||
}
|
||||
|
||||
/** Chunk-Grenzen für Zeichnungen (inhaltsbasiert über Hash der `id`). */
|
||||
export function splitDrawingsIntoChunks(drawings: readonly Drawing2D[]): Array<[number, number]> {
|
||||
const out: Array<[number, number]> = [];
|
||||
const mask = (1 << BOUNDARY_BITS) - 1;
|
||||
let start = 0;
|
||||
for (let i = 1; i < drawings.length; i++) {
|
||||
if ((hashId(drawings[i].id) & mask) === 0) {
|
||||
out.push([start, i]);
|
||||
start = i;
|
||||
}
|
||||
}
|
||||
if (drawings.length) out.push([start, drawings.length]);
|
||||
return out;
|
||||
}
|
||||
|
||||
interface UnderChunk {
|
||||
drawings: Drawing2D[];
|
||||
catGreyed: boolean;
|
||||
ctx: readonly unknown[];
|
||||
geometry: GpuGeometry;
|
||||
}
|
||||
|
||||
function sameDrawings(a: readonly Drawing2D[], b: readonly Drawing2D[], offset: number): boolean {
|
||||
for (let i = 0; i < a.length; i++) if (a[i] !== b[offset + i]) return false;
|
||||
return true;
|
||||
}
|
||||
function sameCtx(a: readonly unknown[], b: readonly unknown[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* GPU-Chunks der kompakten Linien-Unterlage (`Plan.underlay`): jeder Chunk ist
|
||||
* eine Folge von Zeichnungen; seine Linien-Primitive entstehen erst beim
|
||||
* Kompilieren (kurzlebig) und werden nie dauerhaft gehalten. Wiederverwendung,
|
||||
* wenn jede Zeichnung dasselbe OBJEKT ist und der Kontext (`ctx`) gleich blieb.
|
||||
* Gleiche Zwei-Generationen-Aufbewahrung wie {@link GpuChunkCache}.
|
||||
*/
|
||||
class UnderlayChunkCache {
|
||||
private chunks: UnderChunk[] = [];
|
||||
private previous: UnderChunk[] = [];
|
||||
recompiled = 0;
|
||||
|
||||
constructor(private readonly gl: WebGL2RenderingContext) {}
|
||||
|
||||
/** Liefert je Gruppe die Geometrien ihrer Chunks (in Reihenfolge). */
|
||||
update(groups: readonly UnderlayGroup[]): GpuGeometry[][] {
|
||||
const pool = [...this.chunks, ...this.previous];
|
||||
const old = new Map<Drawing2D, UnderChunk[]>();
|
||||
for (const c of pool) {
|
||||
const list = old.get(c.drawings[0]);
|
||||
if (list) list.push(c);
|
||||
else old.set(c.drawings[0], [c]);
|
||||
}
|
||||
const next: UnderChunk[] = [];
|
||||
const reused = new Set<UnderChunk>();
|
||||
const perGroup: GpuGeometry[][] = [];
|
||||
this.recompiled = 0;
|
||||
for (const g of groups) {
|
||||
const geoms: GpuGeometry[] = [];
|
||||
for (const [start, end] of splitDrawingsIntoChunks(g.drawings)) {
|
||||
const hit = old.get(g.drawings[start])?.find(
|
||||
(c) =>
|
||||
!reused.has(c) &&
|
||||
c.drawings.length === end - start &&
|
||||
c.catGreyed === g.catGreyed &&
|
||||
sameCtx(c.ctx, g.ctx) &&
|
||||
sameDrawings(c.drawings, g.drawings, start),
|
||||
);
|
||||
let chunk = hit;
|
||||
if (chunk) reused.add(chunk);
|
||||
else {
|
||||
const slice = g.drawings.slice(start, end);
|
||||
chunk = {
|
||||
drawings: slice,
|
||||
catGreyed: g.catGreyed,
|
||||
ctx: g.ctx,
|
||||
// Linien nur kurzlebig erzeugen; sie sind nach dem Kompilieren Garbage.
|
||||
geometry: compilePrimitivesToGpu(this.gl, g.build(slice), 0),
|
||||
};
|
||||
this.recompiled++;
|
||||
}
|
||||
next.push(chunk);
|
||||
geoms.push(g.tint ? { ...chunk.geometry, greyed: true } : chunk.geometry);
|
||||
}
|
||||
perGroup.push(geoms);
|
||||
}
|
||||
const nextSet = new Set(next);
|
||||
const keepPrevious = this.chunks.filter((c) => !nextSet.has(c));
|
||||
const keep = new Set<UnderChunk>([...next, ...keepPrevious]);
|
||||
for (const c of pool) if (!keep.has(c)) disposeGeometry(this.gl, c.geometry);
|
||||
this.chunks = next;
|
||||
this.previous = keepPrevious;
|
||||
return perGroup;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const c of [...this.chunks, ...this.previous]) disposeGeometry(this.gl, c.geometry);
|
||||
this.chunks = [];
|
||||
this.previous = [];
|
||||
}
|
||||
}
|
||||
|
||||
export class GpuChunkCache {
|
||||
private chunks: Chunk[] = [];
|
||||
/**
|
||||
@@ -109,7 +214,11 @@ export class GpuChunkCache {
|
||||
/** Statistik des letzten `update`-Laufs (Tests/Diagnose). */
|
||||
lastStats: ChunkStats = { chunks: 0, recompiled: 0 };
|
||||
|
||||
constructor(private readonly gl: WebGL2RenderingContext) {}
|
||||
private readonly under: UnderlayChunkCache;
|
||||
|
||||
constructor(private readonly gl: WebGL2RenderingContext) {
|
||||
this.under = new UnderlayChunkCache(gl);
|
||||
}
|
||||
|
||||
/** Geometrien in Zeichenreihenfolge (nur bei `update`/`dispose` neu aufgebaut). */
|
||||
geometries: GpuGeometry[] = [];
|
||||
@@ -119,6 +228,7 @@ export class GpuChunkCache {
|
||||
pxPerMeter: number,
|
||||
lodBucket: number,
|
||||
greyedRanges?: ReadonlyArray<[number, number]>,
|
||||
underlay?: readonly UnderlayGroup[],
|
||||
): void {
|
||||
const cuts = new Set<number>();
|
||||
for (const [a, b] of greyedRanges ?? []) {
|
||||
@@ -172,16 +282,25 @@ export class GpuChunkCache {
|
||||
this.previous = keepPrevious;
|
||||
// Gedimmt wird erst beim Zeichnen: dieselbe kompilierte Geometrie dient der
|
||||
// normalen UND der gedimmten Darstellung. Der Wrapper teilt die Puffer.
|
||||
this.geometries = next.map((c, i) =>
|
||||
const primGeoms = next.map((c, i) =>
|
||||
inRanges(greyedRanges, chunkStarts[i]) ? { ...c.geometry, greyed: true } : c.geometry,
|
||||
);
|
||||
this.lastStats = { chunks: next.length, recompiled };
|
||||
// Kompakte Unterlage: Referenz-Ebenen darunter, aktive Ebene darüber.
|
||||
const groups = underlay ?? [];
|
||||
const underGeoms = this.under.update(groups);
|
||||
const below: GpuGeometry[] = [];
|
||||
const above: GpuGeometry[] = [];
|
||||
groups.forEach((g, i) => (g.above ? above : below).push(...underGeoms[i]));
|
||||
this.geometries = [...below, ...primGeoms, ...above];
|
||||
recompiled += this.under.recompiled;
|
||||
this.lastStats = { chunks: this.geometries.length, recompiled };
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const c of [...this.chunks, ...this.previous]) disposeGeometry(this.gl, c.geometry);
|
||||
this.chunks = [];
|
||||
this.previous = [];
|
||||
this.under.dispose();
|
||||
this.geometries = [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
// geschluckt (console.debug), damit die App nie daran scheitert.
|
||||
|
||||
import type { Plan } from "./generatePlan";
|
||||
import { materializeGreyed } from "./generatePlan";
|
||||
import { materializeGreyed, materializeUnderlay } from "./generatePlan";
|
||||
import type { Project } from "../model/types";
|
||||
import { planToRenderScene } from "./toRenderScene";
|
||||
import { projectToModel3d, TRUCK_MESH_READY_EVENT } from "./toWalls3d";
|
||||
@@ -72,7 +72,7 @@ export function pushNativeScene(plan: Plan): void {
|
||||
sceneTimer = setTimeout(async () => {
|
||||
if (!(await isNativeEnabled())) return;
|
||||
// planToRenderScene liest `greyed` am Primitiv → gedimmte Referenz-Ebenen materialisieren.
|
||||
void invokeNative("push_native_scene", { scene: planToRenderScene(materializeGreyed(plan, true)) });
|
||||
void invokeNative("push_native_scene", { scene: planToRenderScene(materializeGreyed(materializeUnderlay(plan), true)) });
|
||||
}, DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
|
||||
@@ -333,6 +333,8 @@ export function marqueeHitDrawings(
|
||||
prims: Primitive[],
|
||||
rect: ModelRect,
|
||||
crossing: boolean,
|
||||
/** Zeichnungen, die der Aufrufer selbst prüft (kompakte Unterlage) — hier überspringen. */
|
||||
skipIds?: ReadonlyMap<string, unknown>,
|
||||
): string[] {
|
||||
const byDrawing = new Map<string, Vec2[]>();
|
||||
const collect = (id: string, pts: Vec2[]) => {
|
||||
@@ -341,6 +343,7 @@ export function marqueeHitDrawings(
|
||||
else byDrawing.set(id, [...pts]);
|
||||
};
|
||||
for (const p of prims) {
|
||||
if (skipIds && "drawingId" in p && p.drawingId && skipIds.has(p.drawingId)) continue;
|
||||
if (p.kind === "line" && p.drawingId) collect(p.drawingId, [p.a, p.b]);
|
||||
else if (p.kind === "polygon" && p.drawingId) collect(p.drawingId, p.pts);
|
||||
else if (p.kind === "drawingCircle" && p.drawingId) collect(p.drawingId, ringSamplePoints(p.center, p.r));
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
// Die Zugriffe auf die kompakte Unterlage müssen dasselbe liefern wie die
|
||||
// bisherigen Primitiv-basierten Varianten (Zufallsdaten als Gegenprobe).
|
||||
|
||||
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 { buildDrawingIndex, marqueeHitUnderlay, nearestInDrawings } from "./underlayAccess";
|
||||
|
||||
let seed = 7;
|
||||
const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
|
||||
|
||||
function makeDrawings(n: number): Drawing2D[] {
|
||||
const out: Drawing2D[] = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const x = rnd() * 500, y = rnd() * 500;
|
||||
const k = 2 + Math.floor(rnd() * 6);
|
||||
const pts = Array.from({ length: k }, () => ({ x: x + rnd() * 20, y: y + rnd() * 20 }));
|
||||
const closed = k > 2 && rnd() < 0.5;
|
||||
out.push(
|
||||
i % 7 === 0
|
||||
? ({ id: `d${i}`, type: "drawing2d", levelId: "L", categoryCode: "60", geom: { shape: "line", a: pts[0], b: pts[1] } } as Drawing2D)
|
||||
: ({ id: `d${i}`, type: "drawing2d", levelId: "L", categoryCode: "60", geom: { shape: "polyline", pts, closed } } as Drawing2D),
|
||||
);
|
||||
}
|
||||
// Eine riesige Zeichnung (landet in der Überlauf-Liste).
|
||||
out.push({ id: "huge", type: "drawing2d", levelId: "L", categoryCode: "60", geom: { shape: "line", a: { x: -9000, y: -9000 }, b: { x: 9000, y: 9000 } } } as Drawing2D);
|
||||
return out;
|
||||
}
|
||||
|
||||
const project = (drawings: Drawing2D[]) =>
|
||||
({
|
||||
id: "t", name: "T", lineStyles: [], hatches: [{ id: "none", name: "Ohne", pattern: "none", scale: 1, angle: 0, color: "#111" }],
|
||||
components: [], wallTypes: [],
|
||||
drawingLevels: [{ id: "L", name: "L", kind: "drawing", visible: true, locked: false }],
|
||||
layers: [{ code: "60", name: "Z", color: "#000", lw: 0.25, visible: true, locked: false }],
|
||||
walls: [], doors: [], openings: [], ceilings: [], stairs: [], rooms: [], drawings2d: drawings, context: [],
|
||||
}) as unknown as Project;
|
||||
|
||||
describe("underlayAccess == Primitiv-Varianten", () => {
|
||||
const drawings = makeDrawings(1500);
|
||||
const p = project(drawings);
|
||||
const vis = new Set(["60"]);
|
||||
const normal = generatePlan(p, "L", vis);
|
||||
const compact = generatePlan(p, "L", vis, undefined, "mittel", false, false, true, 100, false, true);
|
||||
const under = compact.underlay!.flatMap((g) => g.drawings);
|
||||
const mat = materializeUnderlay(compact);
|
||||
|
||||
it("alle berechtigten Zeichnungen stecken in der Unterlage", () => {
|
||||
expect(under.length).toBe(drawings.length);
|
||||
});
|
||||
|
||||
it("nächstes Segment == Segment-Index der Primitive", () => {
|
||||
const idx = buildDrawingIndex(under)!;
|
||||
const segIdx = buildSegmentIndex(normal.primitives)!;
|
||||
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);
|
||||
expect(a?.drawing.id ?? null).toBe(b?.drawingId ?? null);
|
||||
}
|
||||
});
|
||||
|
||||
it("Marquee (crossing + window) == marqueeHitDrawings über die Primitive", () => {
|
||||
for (const crossing of [true, false]) {
|
||||
for (let k = 0; k < 40; k++) {
|
||||
const x = rnd() * 450, y = rnd() * 450, w = 5 + rnd() * 120, h = 5 + rnd() * 120;
|
||||
const rect = { minX: x, minY: y, maxX: x + w, maxY: y + h };
|
||||
const a = new Set(marqueeHitUnderlay(under, rect, crossing));
|
||||
const b = new Set(marqueeHitDrawings(mat.primitives, rect, crossing));
|
||||
expect([...a].sort()).toEqual([...b].sort());
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
// Zugriff auf die kompakte Linien-Unterlage (`Plan.underlay`) für Hover, Klick-
|
||||
// Auswahl und Marquee. Die Linien existieren dort nicht als Primitive, deshalb
|
||||
// arbeiten diese Funktionen direkt auf den `Drawing2D`-Geometrien — mit einem
|
||||
// Raster über die Zeichnungs-Bounding-Boxen, damit eine Abfrage nur die
|
||||
// Zeichnungen in Cursornähe prüft (nicht alle ~10^5).
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// ── Marquee ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Punktliste einer Zeichnung EXAKT wie `marqueeHitDrawings` sie aus den
|
||||
* Primitiven sammelt (Polygon-Punkte einer geschlossenen Kontur zuerst, dann je
|
||||
* Segment a, b) — damit Ergebnis und Semantik identisch bleiben.
|
||||
*/
|
||||
function marqueePoints(d: Drawing2D): Vec2[] {
|
||||
const g = d.geom;
|
||||
const pts: Vec2[] = [];
|
||||
if (g.shape === "polyline" && g.closed && g.pts.length > 2) for (const p of g.pts) pts.push(p);
|
||||
forEachSegment(d, (a, b) => {
|
||||
pts.push(a, b);
|
||||
});
|
||||
return pts;
|
||||
}
|
||||
|
||||
/** Marquee über kompakt gehaltene Zeichnungen; liefert deren IDs. */
|
||||
export function marqueeHitUnderlay(
|
||||
drawings: readonly Drawing2D[],
|
||||
rect: ModelRect,
|
||||
crossing: boolean,
|
||||
): string[] {
|
||||
const out: string[] = [];
|
||||
for (const d of drawings) {
|
||||
const b = drawingBox(d);
|
||||
if (!isFinite(b.minX)) continue;
|
||||
const disjoint = b.maxX < rect.minX || b.minX > rect.maxX || b.maxY < rect.minY || b.minY > rect.maxY;
|
||||
if (disjoint) continue; // weder berühren noch einschliessen möglich
|
||||
if (!crossing && !(b.minX >= rect.minX && b.maxX <= rect.maxX && b.minY >= rect.minY && b.maxY <= rect.maxY)) continue;
|
||||
const pts = marqueePoints(d);
|
||||
if (crossing ? polyTouchesRect(pts, rect) : polyEnclosedByRect(pts, rect)) out.push(d.id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -105,6 +105,7 @@ export function useGlPlanRenderer(
|
||||
pxPerMeter,
|
||||
pxPerMeter > 0 ? Math.round(Math.log2(pxPerMeter)) : -Infinity,
|
||||
plan.greyedRanges,
|
||||
plan.underlay,
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn('Tessellierung fehlgeschlagen:', e);
|
||||
|
||||
@@ -19,7 +19,7 @@ import type {
|
||||
Vec2,
|
||||
Wall,
|
||||
} from "../model/types";
|
||||
import { generatePlan, generateSectionPlan, generateVisibleLevelsPlan } from "../plan/generatePlan";
|
||||
import { generatePlan, generateSectionPlan, generateVisibleLevelsPlan, materializeUnderlay } from "../plan/generatePlan";
|
||||
import type { CategoryDisplayResolver, Primitive } from "../plan/generatePlan";
|
||||
import type { RichTextDoc } from "../text/richText";
|
||||
import { computeSection } from "../plan/toSection";
|
||||
@@ -824,6 +824,9 @@ function LevelPlanView({
|
||||
mono,
|
||||
floorDisplay,
|
||||
scaleDenominator,
|
||||
// Kompakte Linien-Unterlage (s. Plan.underlay): hält Kataster-Importe
|
||||
// handhabbar; PlanView materialisiert sie, wo echte Primitive nötig sind.
|
||||
true,
|
||||
);
|
||||
const withOverlay =
|
||||
overlayPrimitives.length === 0
|
||||
@@ -831,9 +834,13 @@ function LevelPlanView({
|
||||
: { ...p, primitives: [...p.primitives, ...overlayPrimitives] };
|
||||
// Gruppen-Isolation ("Gruppe betreten"): alles ausserhalb der aktiven
|
||||
// Gruppe gedimmt, s. state/groupActions.ts::applyGroupDimming.
|
||||
// applyGroupDimming arbeitet auf Primitiven → Unterlage vorher materialisieren.
|
||||
return groupPath.length === 0
|
||||
? withOverlay
|
||||
: { ...withOverlay, primitives: applyGroupDimming(withOverlay.primitives, project, groupPath) };
|
||||
: (() => {
|
||||
const full = materializeUnderlay(withOverlay);
|
||||
return { ...full, primitives: applyGroupDimming(full.primitives, project, groupPath) };
|
||||
})();
|
||||
}, [
|
||||
project,
|
||||
level.id,
|
||||
|
||||
Reference in new issue
Block a user