[K3d] GPU-Chunk-Cache: Inhalts-Hash für Kern-Abschnitte, direkt aus dem Puffer kompiliert
Chunks innerhalb von Plan.bufRuns (Identität je Stelle geprüft) werden am Inhalts-Hash des Kerns wiedererkannt statt an der Objekt-Identität und direkt aus dem Puffer kompiliert; Chunk-Grenzen auch an Bauteil-Ids. Neu erzeugter Plan mit gleichem Inhalt: 0 Chunks neu (vorher alle), eine verschobene Wand: 1 von 69. Nativer Renderer reicht bufRuns durch (nicht auf macOS getestet). Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
3 files changed
+219
-16
No files matched your search
@@ -1,7 +1,11 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import type { Primitive, UnderlayGroup } from '../generatePlan';
|
||||
import type { Drawing2D } from '../../model/types';
|
||||
import { generatePlan } from '../generatePlan';
|
||||
import type { Drawing2D, Project } from '../../model/types';
|
||||
import { flattenCategories } from '../../model/types';
|
||||
import { bigSampleProject } from '../bigSampleProject.testing';
|
||||
import { GpuChunkCache, splitIntoChunks } from './glPlanChunks';
|
||||
import { compilePlanBufRange, compilePrimitivesToGpu } from './glPlanCompile';
|
||||
|
||||
const line = (x: number, drawingId: string): Primitive => ({
|
||||
kind: 'line',
|
||||
@@ -213,3 +217,83 @@ describe('GpuChunkCache: kompakte Unterlage', () => {
|
||||
expect(g.length).toBe(3); // 1 unten + 1 Primitiv-Chunk + 1 oben
|
||||
});
|
||||
});
|
||||
|
||||
describe('GpuChunkCache: Kern-Abschnitte (Plan-Puffer v2, Inhalts-Hash)', () => {
|
||||
const codes = (p: Project) => new Set(flattenCategories(p.layers).map((c) => c.code));
|
||||
/** GL, das die hochgeladenen Daten mitschreibt. */
|
||||
function recordingGl() {
|
||||
const uploads: number[][] = [];
|
||||
const gl = {
|
||||
createBuffer: () => ({}),
|
||||
bindBuffer: () => {},
|
||||
bufferData: (_t: number, d: ArrayBufferView) => uploads.push(Array.from(new Uint8Array(d.buffer, d.byteOffset, d.byteLength))),
|
||||
deleteBuffer: () => {},
|
||||
ARRAY_BUFFER: 1,
|
||||
ELEMENT_ARRAY_BUFFER: 2,
|
||||
STATIC_DRAW: 3,
|
||||
} as unknown as WebGL2RenderingContext;
|
||||
return { gl, uploads };
|
||||
}
|
||||
|
||||
it('neu erzeugter Plan (neue Objekte, gleicher Inhalt) kompiliert nichts neu', () => {
|
||||
const p = bigSampleProject(4);
|
||||
const { gl } = makeGl();
|
||||
const cache = new GpuChunkCache(gl);
|
||||
const a = generatePlan(p, 'eg', codes(p));
|
||||
expect(a.bufRuns?.length).toBe(2);
|
||||
cache.update(a.primitives, 90, 6, a.greyedRanges, a.underlay, a.bufRuns);
|
||||
expect(cache.lastStats.recompiled).toBe(cache.lastStats.chunks);
|
||||
const b = generatePlan(p, 'eg', codes(p));
|
||||
expect(b.primitives[0]).not.toBe(a.primitives[0]);
|
||||
cache.update(b.primitives, 90, 6, b.greyedRanges, b.underlay, b.bufRuns);
|
||||
expect(cache.lastStats.recompiled).toBe(0);
|
||||
// Ohne Abschnitte (Objekt-Identität) wäre alles neu.
|
||||
const c = generatePlan(p, 'eg', codes(p));
|
||||
cache.update(c.primitives, 90, 6, c.greyedRanges, c.underlay);
|
||||
expect(cache.lastStats.recompiled).toBe(cache.lastStats.chunks);
|
||||
});
|
||||
|
||||
it('eine verschobene Wand kompiliert nur wenige Chunks neu', () => {
|
||||
const p = bigSampleProject(8);
|
||||
const { gl } = makeGl();
|
||||
const cache = new GpuChunkCache(gl);
|
||||
const a = generatePlan(p, 'eg', codes(p));
|
||||
cache.update(a.primitives, 90, 6, a.greyedRanges, a.underlay, a.bufRuns);
|
||||
const total = cache.lastStats.chunks;
|
||||
expect(total).toBeGreaterThan(8);
|
||||
const walls = p.walls.slice();
|
||||
walls[200] = { ...walls[200], end: { x: walls[200].end.x + 0.05, y: walls[200].end.y } };
|
||||
const b = generatePlan({ ...p, walls }, 'eg', codes(p));
|
||||
cache.update(b.primitives, 90, 6, b.greyedRanges, b.underlay, b.bufRuns);
|
||||
expect(cache.lastStats.recompiled).toBeGreaterThan(0);
|
||||
expect(cache.lastStats.recompiled).toBeLessThanOrEqual(3);
|
||||
});
|
||||
|
||||
it('ersetzte Primitive (gedimmt geklont) fallen auf den Objekt-Weg zurück', () => {
|
||||
const p = bigSampleProject(2);
|
||||
const { gl } = makeGl();
|
||||
const cache = new GpuChunkCache(gl);
|
||||
const a = generatePlan(p, 'eg', codes(p));
|
||||
const prims = a.primitives.slice();
|
||||
prims[10] = { ...prims[10], greyed: true } as Primitive;
|
||||
cache.update(prims, 90, 6, a.greyedRanges, a.underlay, a.bufRuns);
|
||||
const n = cache.lastStats.chunks;
|
||||
cache.update(prims, 90, 6, a.greyedRanges, a.underlay, a.bufRuns);
|
||||
expect(cache.lastStats.recompiled).toBe(0);
|
||||
expect(cache.lastStats.chunks).toBe(n);
|
||||
});
|
||||
|
||||
it('direkt aus dem Puffer = über die Objekte (gleiche hochgeladene Daten)', () => {
|
||||
const p = bigSampleProject(2);
|
||||
const plan = generatePlan(p, 'eg', codes(p));
|
||||
const run = plan.bufRuns![0];
|
||||
for (const [from, to] of [[run.from, run.to], [run.from + 3, run.to - 5]]) {
|
||||
const x = recordingGl();
|
||||
const y = recordingGl();
|
||||
compilePlanBufRange(x.gl, run.buf, from, to, 120);
|
||||
compilePrimitivesToGpu(y.gl, run.buf.prims.slice(from, to), 120);
|
||||
expect(x.uploads.length).toBeGreaterThan(2);
|
||||
expect(x.uploads).toEqual(y.uploads);
|
||||
}
|
||||
});
|
||||
});
|
||||
+133
-15
@@ -10,21 +10,28 @@
|
||||
* Füllungen ebenfalls vor Linien kamen und innerhalb beider die Primitiv-
|
||||
* Reihenfolge galt.
|
||||
*
|
||||
* Chunk-Grenzen sind INHALTSBASIERT (Hash der `drawingId`), nicht
|
||||
* positionsbasiert: wird vorn ein Element eingefügt, verschieben sich alle
|
||||
* Indizes dahinter, die Grenzen bleiben aber an denselben Elementen — nur der
|
||||
* betroffene Chunk ändert sich.
|
||||
* Chunk-Grenzen sind INHALTSBASIERT (Hash der Element-Id: `drawingId`, sonst
|
||||
* die Pick-Id wie `wallId`), nicht positionsbasiert: wird vorn ein Element
|
||||
* eingefügt, verschieben sich alle Indizes dahinter, die Grenzen bleiben aber
|
||||
* an denselben Elementen — nur der betroffene Chunk ändert sich.
|
||||
*
|
||||
* Wiederverwendung: ein Chunk gilt als unverändert, wenn jede seiner
|
||||
* Primitive dasselbe OBJEKT ist wie beim letzten Lauf (Referenzvergleich) und,
|
||||
* falls er zoomabhängige Primitive (Bögen/Kreise) enthält, der LOD-Bucket
|
||||
* gleich ist. Beim blossen Zoomen werden dadurch nur die (wenigen) Chunks mit
|
||||
* Bögen neu tesselliert.
|
||||
*
|
||||
* Kern-Primitive ([K3d]): Abschnitte, die unverändert aus einem Plan-Puffer des
|
||||
* Kerns stammen (`Plan.bufRuns`), sind bei jeder Plan-Erzeugung neue Objekte —
|
||||
* dort gilt statt der Objekt-Identität der INHALTS-HASH je Primitiv (vom Kern
|
||||
* mitgeliefert), und kompiliert wird direkt aus dem Puffer
|
||||
* (`compilePlanBufRange`), ohne die Objekte erneut zu kodieren.
|
||||
*/
|
||||
|
||||
import type { Primitive, UnderlayGroup } from '../generatePlan';
|
||||
import type { PlanBufRun, Primitive, UnderlayGroup } from '../generatePlan';
|
||||
import type { Drawing2D } from '../../model/types';
|
||||
import { compilePrimitivesToGpu } from './glPlanCompile';
|
||||
import type { DecodedPlanBuf } from '../planBuf';
|
||||
import { compilePlanBufRange, compilePrimitivesToGpu } from './glPlanCompile';
|
||||
import type { BufferGl, GpuGeometry } from './glPlanTypes';
|
||||
|
||||
/** Ziel: im Mittel so viele Elemente (drawingIds) je Chunk = 2^BITS. */
|
||||
@@ -45,10 +52,42 @@ function hashId(id: string): number {
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
type Ids = {
|
||||
drawingId?: string;
|
||||
wallId?: string;
|
||||
openingId?: string;
|
||||
stairId?: string;
|
||||
ceilingId?: string;
|
||||
roomId?: string;
|
||||
columnId?: string;
|
||||
roofId?: string;
|
||||
extrudedSolidId?: string;
|
||||
contextObjectId?: string;
|
||||
sectionLineId?: string;
|
||||
};
|
||||
|
||||
/** Element eines Primitivs für die Chunk-Grenzen: `drawingId`, sonst die Pick-Id des Bauteils. */
|
||||
function elemId(p: Primitive): string | undefined {
|
||||
const q = p as Ids;
|
||||
return (
|
||||
q.drawingId ??
|
||||
q.wallId ??
|
||||
q.openingId ??
|
||||
q.stairId ??
|
||||
q.ceilingId ??
|
||||
q.roomId ??
|
||||
q.columnId ??
|
||||
q.roofId ??
|
||||
q.extrudedSolidId ??
|
||||
q.contextObjectId ??
|
||||
q.sectionLineId
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Index-Bereiche [start, end) der Chunks. `cuts` sind Indizes, an denen IMMER
|
||||
* geschnitten wird (Grenzen gedimmter Bereiche, damit ein Chunk entweder ganz
|
||||
* gedimmt ist oder gar nicht).
|
||||
* gedimmt ist oder gar nicht; Grenzen der Kern-Abschnitte).
|
||||
*/
|
||||
export function splitIntoChunks(
|
||||
prims: readonly Primitive[],
|
||||
@@ -57,9 +96,9 @@ export function splitIntoChunks(
|
||||
const out: Array<[number, number]> = [];
|
||||
const mask = (1 << BOUNDARY_BITS) - 1;
|
||||
let start = 0;
|
||||
let prevId: string | undefined = prims.length ? (prims[0] as { drawingId?: string }).drawingId : undefined;
|
||||
let prevId: string | undefined = prims.length ? elemId(prims[0]) : undefined;
|
||||
for (let i = 1; i < prims.length; i++) {
|
||||
const id = (prims[i] as { drawingId?: string }).drawingId;
|
||||
const id = elemId(prims[i]);
|
||||
if (cuts.has(i)) {
|
||||
out.push([start, i]);
|
||||
start = i;
|
||||
@@ -79,12 +118,48 @@ export function splitIntoChunks(
|
||||
}
|
||||
|
||||
interface Chunk {
|
||||
/** Primitive (Referenzvergleich) — leer bei Kern-Chunks, die `keys` tragen. */
|
||||
prims: Primitive[];
|
||||
/** Inhalts-Hashes der Primitive eines Kern-Chunks (sonst null). */
|
||||
keys: Float64Array | null;
|
||||
dynamic: boolean;
|
||||
bucket: number;
|
||||
geometry: GpuGeometry;
|
||||
}
|
||||
|
||||
/** Ein geprüfter Kern-Abschnitt: `primitives[start..end)` = `buf.prims[from..]`. */
|
||||
interface Segment {
|
||||
start: number;
|
||||
end: number;
|
||||
buf: DecodedPlanBuf;
|
||||
from: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kern-Abschnitte auf Objekt-Identität prüfen: nur Stellen, an denen noch genau das dekodierte
|
||||
* Objekt steht (nicht ersetzt durch Abzugskörper, Dimmen, Strichstärken-Massstab), gelten.
|
||||
*/
|
||||
function verifiedSegments(primitives: readonly Primitive[], runs: readonly PlanBufRun[] | undefined): Segment[] {
|
||||
const out: Segment[] = [];
|
||||
for (const r of runs ?? []) {
|
||||
if (!r.buf.hashes) continue;
|
||||
const n = Math.min(r.to - r.from, primitives.length - r.at);
|
||||
let k = 0;
|
||||
while (k < n) {
|
||||
while (k < n && primitives[r.at + k] !== r.buf.prims[r.from + k]) k++;
|
||||
const k0 = k;
|
||||
while (k < n && primitives[r.at + k] === r.buf.prims[r.from + k]) k++;
|
||||
if (k > k0) out.push({ start: r.at + k0, end: r.at + k, buf: r.buf, from: r.from + k0 });
|
||||
}
|
||||
}
|
||||
return out.sort((a, b) => a.start - b.start);
|
||||
}
|
||||
|
||||
function sameKeys(a: Float64Array, b: Float64Array, offset: number): boolean {
|
||||
for (let i = 0; i < a.length; i++) if (a[i] !== b[offset + i]) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function disposeGeometry(gl: BufferGl, g: GpuGeometry): void {
|
||||
gl.deleteBuffer(g.fill.positionBuffer);
|
||||
gl.deleteBuffer(g.fill.indexBuffer);
|
||||
@@ -229,35 +304,77 @@ export class GpuChunkCache {
|
||||
lodBucket: number,
|
||||
greyedRanges?: ReadonlyArray<[number, number]>,
|
||||
underlay?: readonly UnderlayGroup[],
|
||||
/** Abschnitte aus Kern-Puffern (`Plan.bufRuns`): Inhalts-Hash statt Objekt-Identität. */
|
||||
runs?: readonly PlanBufRun[],
|
||||
): void {
|
||||
const cuts = new Set<number>();
|
||||
for (const [a, b] of greyedRanges ?? []) {
|
||||
cuts.add(a);
|
||||
cuts.add(b);
|
||||
}
|
||||
// Aktuelle + vorherige Generation nach erstem Primitiv indizieren (Referenz-Identität).
|
||||
const segs = verifiedSegments(primitives, runs);
|
||||
for (const g of segs) {
|
||||
cuts.add(g.start);
|
||||
cuts.add(g.end);
|
||||
}
|
||||
// Aktuelle + vorherige Generation nach erstem Primitiv (Referenz) bzw. erstem Hash indizieren.
|
||||
const pool = [...this.chunks, ...this.previous];
|
||||
const old = new Map<Primitive, Chunk[]>();
|
||||
const old = new Map<unknown, Chunk[]>();
|
||||
for (const c of pool) {
|
||||
if (!c.prims.length) continue;
|
||||
const list = old.get(c.prims[0]);
|
||||
const first = c.keys ? (c.keys.length ? c.keys[0] : undefined) : c.prims[0];
|
||||
if (first === undefined) continue;
|
||||
const list = old.get(first);
|
||||
if (list) list.push(c);
|
||||
else old.set(c.prims[0], [c]);
|
||||
else old.set(first, [c]);
|
||||
}
|
||||
|
||||
const next: Chunk[] = [];
|
||||
const chunkStarts: number[] = [];
|
||||
const reused = new Set<Chunk>();
|
||||
let recompiled = 0;
|
||||
let si = 0;
|
||||
for (const [start, end] of splitIntoChunks(primitives, cuts)) {
|
||||
chunkStarts.push(start);
|
||||
while (si < segs.length && segs[si].end <= start) si++;
|
||||
const seg = si < segs.length && segs[si].start <= start && end <= segs[si].end ? segs[si] : null;
|
||||
if (seg) {
|
||||
// Kern-Chunk: Inhalts-Hashes vergleichen, direkt aus dem Puffer kompilieren.
|
||||
const hashes = seg.buf.hashes!;
|
||||
const from = seg.from + (start - seg.start);
|
||||
const n = end - start;
|
||||
const hit = old.get(hashes[from])?.find(
|
||||
(c) =>
|
||||
!reused.has(c) &&
|
||||
c.keys !== null &&
|
||||
c.keys.length === n &&
|
||||
(!c.dynamic || c.bucket === lodBucket) &&
|
||||
sameKeys(c.keys, hashes, from),
|
||||
);
|
||||
if (hit) {
|
||||
reused.add(hit);
|
||||
next.push(hit);
|
||||
continue;
|
||||
}
|
||||
let dynamic = false;
|
||||
for (let i = start; i < end && !dynamic; i++) dynamic = isLodDependent(primitives[i]);
|
||||
next.push({
|
||||
prims: [],
|
||||
keys: hashes.slice(from, from + n),
|
||||
dynamic,
|
||||
bucket: lodBucket,
|
||||
geometry: compilePlanBufRange(this.gl, seg.buf, from, from + n, pxPerMeter),
|
||||
});
|
||||
recompiled++;
|
||||
continue;
|
||||
}
|
||||
const hit = old.get(primitives[start])?.find(
|
||||
(c) =>
|
||||
!reused.has(c) &&
|
||||
c.keys === null &&
|
||||
c.prims.length === end - start &&
|
||||
(!c.dynamic || c.bucket === lodBucket) &&
|
||||
sameRefs(c.prims, primitives, start),
|
||||
);
|
||||
chunkStarts.push(start);
|
||||
if (hit) {
|
||||
reused.add(hit);
|
||||
next.push(hit);
|
||||
@@ -266,6 +383,7 @@ export class GpuChunkCache {
|
||||
const slice = primitives.slice(start, end);
|
||||
next.push({
|
||||
prims: slice,
|
||||
keys: null,
|
||||
dynamic: slice.some(isLodDependent),
|
||||
bucket: lodBucket,
|
||||
geometry: compilePrimitivesToGpu(this.gl, slice, pxPerMeter),
|
||||
|
||||
@@ -275,6 +275,7 @@ export function useNativePlanRenderer(
|
||||
pxPerMeter > 0 ? Math.round(Math.log2(pxPerMeter)) : -Infinity,
|
||||
plan.greyedRanges,
|
||||
plan.underlay,
|
||||
plan.bufRuns,
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn('Tessellierung fehlgeschlagen:', e);
|
||||
|
||||
Reference in new issue
Block a user