Merge [K3b] Plan-Puffer v1 und GPU-Kompilierung in Rust (plan_buf.rs, gpu_compile.rs, hatch.rs); K3b abgeschlossen
Laut Agent bitgleich (Vertex-/Index-Puffer, Batches; Beispielprojekt, 30 Zufallsprojekte, 460 Zufallslisten, Landeskoordinaten). Trigonometrie im Web-Build ueber Math der JS-Engine (musl-libm wich ab). Schraffur ~2x, 100k Linien + 3000 Schraffurflaechen 3.9 -> 1.8 s, Beispiel-EG 1.5 -> 0.8 ms. Browser-Build startet geprueft. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
17 files changed
+3426
-1445
No files matched your search
@@ -1,802 +1,109 @@
|
||||
/**
|
||||
* Tessellierung: wandelt Plan-`Primitive` in GPU-fertige Puffer.
|
||||
* • Polygone → echtes Ear-Clipping (konkav-fähig), Bildschirm-Raum-Dreiecke
|
||||
* • Linien → Quad mit Normale + Seiten-Flag (bildschirmkonstante Breite)
|
||||
* Tessellierung: wandelt Plan-`Primitive` in GPU-fertige Puffer — Fassade über den Rust-Kern
|
||||
* ([K3b], `src-tauri/core/src/gpu_compile.rs`). TS kodiert die Primitive eines Chunks in den
|
||||
* Plan-Puffer (`../planBuf.ts`), Rust tesselliert (Ear-Clipping, Striche mit runden Kappen/Ecken,
|
||||
* Schraffur, Zickzack, Motive, Bögen, Kreise) und liefert Vertex-/Index-/Batch-Daten flach zurück;
|
||||
* hier werden sie nur noch hochgeladen.
|
||||
*
|
||||
* Koordinaten: alles wird in BILDSCHIRM-Raum abgelegt (wie `toScreen`):
|
||||
* sx = mx·PX_PER_M, sy = -my·PX_PER_M.
|
||||
* Damit ist die Projektion eine reine viewBox-Orthografie (siehe glPlanRender).
|
||||
* Koordinaten: alles in BILDSCHIRM-Raum (wie `toScreen`): sx = mx·PX_PER_M, sy = -my·PX_PER_M,
|
||||
* relativ zum lokalen Ursprung (`origin`, erster abgelegter Punkt).
|
||||
*/
|
||||
|
||||
import type { Primitive } from '../generatePlan';
|
||||
import type { Vec2 } from '../../model/types';
|
||||
import type { BufferGl, GpuGeometry, Rgba } from './glPlanTypes';
|
||||
import { applyDashRuns, buildHatchRuns, zigzagPoints, motifPoints, DASH_MM_TO_M } from './glPlanHatch';
|
||||
|
||||
const PX_PER_M = 90;
|
||||
import { encodePlanBuf } from '../planBuf';
|
||||
import { core } from '../../engine/coreWasm';
|
||||
|
||||
/**
|
||||
* Wachsender Typed-Array-Puffer statt `number[]` für die Vertex-/Index-Daten.
|
||||
* Normale JS-Arrays sind in V8/JSC praktisch auf ~134 Mio. Elemente begrenzt
|
||||
* (`FixedArray::kMaxLength`) — ein ganzer Kataster-Import (3,7 Mio. Linien-
|
||||
* Segmente, reproduziert mit der 439-MB-Luzerner-DXF) überschreitet das beim
|
||||
* Linien-Vertexpuffer (`RangeError: Invalid array length`). Typed Arrays haben
|
||||
* diese Grenze nicht und brauchen nur 4 statt 8 Byte je Wert. Die hochgeladenen
|
||||
* Daten sind identisch: der Upload hat schon bisher nach Float32/Uint32 gewandelt.
|
||||
*/
|
||||
class GrowBuffer<T extends Float32Array | Uint32Array> {
|
||||
private buf: T;
|
||||
length = 0;
|
||||
constructor(private readonly make: (n: number) => T) {
|
||||
this.buf = make(1024);
|
||||
}
|
||||
private ensure(extra: number): void {
|
||||
const need = this.length + extra;
|
||||
if (need <= this.buf.length) return;
|
||||
let cap = this.buf.length * 2;
|
||||
while (cap < need) cap *= 2;
|
||||
const next = this.make(cap);
|
||||
next.set(this.buf.subarray(0, this.length));
|
||||
this.buf = next;
|
||||
}
|
||||
push1(a: number): void {
|
||||
this.ensure(1);
|
||||
this.buf[this.length++] = a;
|
||||
}
|
||||
push2(a: number, b: number): void {
|
||||
this.ensure(2);
|
||||
const o = this.length;
|
||||
this.buf[o] = a;
|
||||
this.buf[o + 1] = b;
|
||||
this.length = o + 2;
|
||||
}
|
||||
push3(a: number, b: number, c: number): void {
|
||||
this.ensure(3);
|
||||
const o = this.length;
|
||||
this.buf[o] = a;
|
||||
this.buf[o + 1] = b;
|
||||
this.buf[o + 2] = c;
|
||||
this.length = o + 3;
|
||||
}
|
||||
push6(a: number, b: number, c: number, d: number, e: number, f: number): void {
|
||||
this.ensure(6);
|
||||
const o = this.length;
|
||||
this.buf[o] = a;
|
||||
this.buf[o + 1] = b;
|
||||
this.buf[o + 2] = c;
|
||||
this.buf[o + 3] = d;
|
||||
this.buf[o + 4] = e;
|
||||
this.buf[o + 5] = f;
|
||||
this.length = o + 6;
|
||||
}
|
||||
/** Gefüllter Bereich (View, keine Kopie). */
|
||||
view(): T {
|
||||
return this.buf.subarray(0, this.length) as T;
|
||||
}
|
||||
}
|
||||
|
||||
/** Modell-Meter → Bildschirm-Raum (identisch zu PlanView.toScreen). */
|
||||
function toScreen(p: Vec2): Vec2 {
|
||||
return { x: p.x * PX_PER_M, y: -p.y * PX_PER_M };
|
||||
}
|
||||
|
||||
/** Signierte Fläche (Shoelace); >0 = CCW (Modell-Y nach oben). */
|
||||
function signedArea(pts: Vec2[]): number {
|
||||
let a = 0;
|
||||
for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {
|
||||
a += pts[j].x * pts[i].y - pts[i].x * pts[j].y;
|
||||
}
|
||||
return a / 2;
|
||||
}
|
||||
|
||||
/** Kreuzprodukt (b-a)×(c-a). */
|
||||
function cross(a: Vec2, b: Vec2, c: Vec2): number {
|
||||
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
|
||||
}
|
||||
|
||||
/** Liegt p im (a,b,c)-Dreieck? (CCW-orientiert). */
|
||||
function pointInTri(a: Vec2, b: Vec2, c: Vec2, p: Vec2): boolean {
|
||||
const d1 = cross(a, b, p);
|
||||
const d2 = cross(b, c, p);
|
||||
const d3 = cross(c, a, p);
|
||||
const hasNeg = d1 < 0 || d2 < 0 || d3 < 0;
|
||||
const hasPos = d1 > 0 || d2 > 0 || d3 > 0;
|
||||
return !(hasNeg && hasPos);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ear-Clipping-Triangulierung eines einfachen (lochfreien) Polygons. Robust für
|
||||
* konvexe UND konkave Ringe. Gibt Dreiecks-Indizes (0-basiert auf `pts`)
|
||||
* zurück; [] bei <3 Ecken oder Degeneration.
|
||||
*
|
||||
* PERFORMANCE (Nutzer-Report 2026-10: App hängt nach Import einer grossen
|
||||
* Kataster-DXF, 69k Konturen): die naive Fassung war O(n) Ohren × O(n)
|
||||
* Kandidatensuche × O(n) Enthalten-Test (plus O(n) `Array.splice` pro Ohr)
|
||||
* — für ein paar Dutzend Handzeichnungs-Ecken unmerklich, aber bei einem
|
||||
* einzelnen gefüllten Polygon mit tausenden Stützpunkten (z. B. eine
|
||||
* detaillierte Parzellen-/Flächen-HATCH-Kontur aus einer amtlichen
|
||||
* Vermessung) effektiv O(n³) — EIN solches Polygon konnte die App für
|
||||
* Minuten einfrieren. Fix, ohne das Ergebnis zu ändern: nur REFLEXE (konkave)
|
||||
* Ecken können in einem Ohr liegen (Standard-Resultat der Ear-Clipping-
|
||||
* Literatur) — der Enthalten-Test scannt daher nur die (meist kleine)
|
||||
* Reflex-Menge statt aller Ecken, und das Abschneiden eines Ohrs läuft über
|
||||
* eine verkettete Liste (O(1)) statt `splice` (O(n)). Für überwiegend konvexe
|
||||
* Polygone (die Mehrheit realer Gebäude-/Parzellen-Umrisse) sinkt die
|
||||
* Gesamtkosten dadurch von O(n³) auf nahe O(n · r) mit r = Anzahl Reflex-
|
||||
* Ecken (oft einstellig, unabhängig von n); echter Worst-Case (ALLE Ecken
|
||||
* reflex, z. B. ein Zickzack) bleibt bei O(n²) — nie schlechter als vorher.
|
||||
* Ear-Clipping-Triangulierung eines einfachen (lochfreien) Polygons, konvex oder konkav.
|
||||
* Dreiecks-Indizes (0-basiert auf `pts`); [] bei <3 Ecken oder Degeneration.
|
||||
*/
|
||||
export function triangulate(pts: Vec2[]): number[] {
|
||||
const n = pts.length;
|
||||
if (n < 3) return [];
|
||||
|
||||
// Ohr-Test unten nutzt cross>0 = konvex, was CCW voraussetzt. Bei CW-Polygonen
|
||||
// die Reihenfolge umdrehen (Triangulierung ist raum-affin-invariant, die
|
||||
// Indizes gelten danach auch für die Bildschirm-Raum-Vertices).
|
||||
const order: number[] = [];
|
||||
for (let i = 0; i < n; i++) order.push(i);
|
||||
if (signedArea(pts) < 0) order.reverse(); // <0 = CW → auf CCW drehen
|
||||
|
||||
// Doppelt verkettete Liste über die (ggf. gedrehte) Reihenfolge — macht das
|
||||
// Entfernen eines abgeschnittenen Ohrs O(1) (Nachbarn neu verknüpfen statt
|
||||
// Array-splice).
|
||||
const next = new Int32Array(n);
|
||||
const prev = new Int32Array(n);
|
||||
for (let i = 0; i < n; i++) {
|
||||
next[order[i]] = order[(i + 1) % n];
|
||||
prev[order[i]] = order[(i - 1 + n) % n];
|
||||
if (pts.length < 3) return [];
|
||||
const flat = new Float64Array(pts.length * 2);
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
flat[2 * i] = pts[i].x;
|
||||
flat[2 * i + 1] = pts[i].y;
|
||||
}
|
||||
|
||||
const isReflex = (i: number): boolean => cross(pts[prev[i]], pts[i], pts[next[i]]) <= 0;
|
||||
const reflex = new Set<number>();
|
||||
for (const i of order) if (isReflex(i)) reflex.add(i);
|
||||
|
||||
const tris: number[] = [];
|
||||
let remaining = n;
|
||||
let i = order[0];
|
||||
let noEarStreak = 0;
|
||||
let guard = 0;
|
||||
const maxGuard = n * n + 16;
|
||||
|
||||
while (remaining > 3 && guard++ < maxGuard) {
|
||||
const a = prev[i];
|
||||
const b = i;
|
||||
const c = next[i];
|
||||
// Konvexe Ecke (nicht reflex) UND kein anderer (notwendig reflexer)
|
||||
// Vertex im Ohr-Dreieck → gültiges Ohr.
|
||||
let isEar = !reflex.has(b);
|
||||
if (isEar) {
|
||||
for (const vi of reflex) {
|
||||
if (vi === a || vi === b || vi === c) continue;
|
||||
if (pointInTri(pts[a], pts[b], pts[c], pts[vi])) {
|
||||
isEar = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isEar) {
|
||||
tris.push(a, b, c);
|
||||
next[a] = c;
|
||||
prev[c] = a;
|
||||
reflex.delete(b);
|
||||
remaining--;
|
||||
// Nachbarn können durch die neue Kante ihre Konvexität wechseln (in
|
||||
// beide Richtungen) — Reflex-Menge entsprechend nachführen.
|
||||
if (isReflex(a)) reflex.add(a); else reflex.delete(a);
|
||||
if (isReflex(c)) reflex.add(c); else reflex.delete(c);
|
||||
i = a; // nach einem Schnitt zuerst den Vorgänger erneut prüfen (üblich)
|
||||
noEarStreak = 0;
|
||||
} else {
|
||||
i = c;
|
||||
// Kein Ohr nach einer vollen Runde über den Restring gefunden →
|
||||
// degeneriert (z. B. selbstüberschneidend). Abbrechen statt endlos
|
||||
// weiterzusuchen (kein Crash, wie zuvor).
|
||||
if (++noEarStreak > remaining) break;
|
||||
}
|
||||
}
|
||||
if (remaining === 3) tris.push(prev[i], i, next[i]);
|
||||
return tris;
|
||||
return Array.from(core().triangulate_flat(flat));
|
||||
}
|
||||
|
||||
/**
|
||||
* Farbe → RGBA[0..1]; ungültig/"none"/"transparent" → null.
|
||||
* Unterstützt "#rgb", "#rrggbb", "#rrggbbaa" und "rgb()/rgba()".
|
||||
*/
|
||||
function parseColor(hex: string | undefined): Rgba | null {
|
||||
if (!hex) return null;
|
||||
const s = hex.trim().toLowerCase();
|
||||
if (s === 'none' || s === 'transparent') return null;
|
||||
|
||||
if (s.startsWith('rgb')) {
|
||||
const m = s.match(/[\d.]+/g);
|
||||
if (!m || m.length < 3) return null;
|
||||
const a = m.length >= 4 ? parseFloat(m[3]) : 1;
|
||||
return [+m[0] / 255, +m[1] / 255, +m[2] / 255, a > 1 ? a / 255 : a];
|
||||
}
|
||||
|
||||
let h = s[0] === '#' ? s.slice(1) : s;
|
||||
if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];
|
||||
if (h.length !== 6 && h.length !== 8) return null;
|
||||
const r = parseInt(h.slice(0, 2), 16);
|
||||
const g = parseInt(h.slice(2, 4), 16);
|
||||
const b = parseInt(h.slice(4, 6), 16);
|
||||
const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1;
|
||||
if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
|
||||
return [r / 255, g / 255, b / 255, a];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fester Grauton gedimmter (greyed) Primitive — ECHTE Umfärbung statt
|
||||
* Deckkraft (dünne Haarlinien auf dem hellen Zeichenblatt wären bei reiner
|
||||
* Transparenz kaum erkennbar gedimmt). Gleicher Ton wie GREYED_COLOR in
|
||||
* PlanView.tsx / GREY_RGB in toRenderScene.ts (#8c8c8c ≈ 0.549).
|
||||
*/
|
||||
export const GREY_RGB = 0.549;
|
||||
|
||||
/**
|
||||
* Färbt auf den festen Grauton um, wenn das Primitiv im Darstellungsmodus
|
||||
* „grau" ist, und multipliziert die Objekt-Transparenz (`Drawing2D.opacity`)
|
||||
* in den Alphakanal. Beides ist unabhängig: gedimmt wird UMGEFÄRBT (damit
|
||||
* dünne Linien erkennbar bleiben), transparent wird über Alpha.
|
||||
*/
|
||||
function dim(color: Rgba, greyed: boolean | undefined, opacity?: number): Rgba {
|
||||
const c: Rgba = greyed ? [GREY_RGB, GREY_RGB, GREY_RGB, color[3]] : color;
|
||||
if (opacity === undefined || opacity >= 1) return c;
|
||||
return [c[0], c[1], c[2], c[3] * Math.max(0, opacity)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Wie `dim`, aber für FLÄCHEN-Füllung: gedimmte Flächen bleiben WEISS statt
|
||||
* grau eingefärbt — nur der Umriss (weiterhin `dim`) macht das Element als
|
||||
* gedimmt erkennbar (Nutzer-Wunsch: "im Hintergrund nicht als graue Fläche
|
||||
* gefüllt, sondern weiss mit nur den Linien sichtbar").
|
||||
*/
|
||||
function dimFill(color: Rgba, greyed: boolean | undefined, opacity?: number): Rgba {
|
||||
const c: Rgba = greyed ? [1, 1, 1, color[3]] : color;
|
||||
if (opacity === undefined || opacity >= 1) return c;
|
||||
return [c[0], c[1], c[2], c[3] * Math.max(0, opacity)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tessellliert Plan-Primitive zu GPU-Geometrie (MVP: gefüllte Polygone +
|
||||
* bildschirmkonstante Striche). Text/Bögen bleiben im SVG-Overlay.
|
||||
* Tesselliert Plan-Primitive zu GPU-Geometrie (Füllungen + bildschirmkonstante Striche).
|
||||
* Text/Bilder bleiben im Overlay.
|
||||
*/
|
||||
export function compilePrimitivesToGpu(
|
||||
gl: BufferGl,
|
||||
primitives: Primitive[],
|
||||
// Bildschirm-Massstab (Geräte-px je Modell-Meter) beim aktuellen Zoom. Steuert
|
||||
// NUR die adaptive Bogen-Tessellierung (siehe 'arc'-Zweig): je stärker
|
||||
// hineingezoomt, desto mehr Segmente, damit der Bogen rund statt facettiert
|
||||
// erscheint. 0 → zoom-unabhängiger Rückfall (fixe 16 Segmente je 90°), z. B.
|
||||
// wenn der Aufrufer den Massstab (noch) nicht kennt.
|
||||
// Bildschirm-Massstab (Geräte-px je Modell-Meter) beim aktuellen Zoom. Steuert NUR die
|
||||
// adaptive Bogen-Tessellierung; 0 → zoom-unabhängiger Rückfall (16 Segmente je 90°).
|
||||
pxPerMeter = 0,
|
||||
): GpuGeometry {
|
||||
// Füll-Puffer (Bildschirm-Raum Positionen + Indizes).
|
||||
const fillPos = new GrowBuffer((n) => new Float32Array(n));
|
||||
const fillIdx = new GrowBuffer((n) => new Uint32Array(n));
|
||||
const packed = gl.packedLineVertices === true;
|
||||
const out = core().gpu_compile_flat(encodePlanBuf(primitives), pxPerMeter, packed);
|
||||
return uploadCompiled(gl, out);
|
||||
}
|
||||
|
||||
/** Flache Kern-Ausgabe (Layout s. `gpu_compile.rs`) → hochgeladene `GpuGeometry`. */
|
||||
function uploadCompiled(gl: BufferGl, out: Uint32Array): GpuGeometry {
|
||||
if (out.length < 2) {
|
||||
return {
|
||||
fill: { positionBuffer: null, indexBuffer: null, batches: [] },
|
||||
line: { vertexBuffer: null, indexBuffer: null, batches: [] },
|
||||
origin: { x: 0, y: 0 },
|
||||
bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 },
|
||||
};
|
||||
}
|
||||
const m = out[0];
|
||||
const meta = new Float64Array(out.buffer, out.byteOffset + 8, m);
|
||||
const [originX, originY, minX, minY, maxX, maxY, nFillPos, nFillIdx, nLineVerts, nLineIdx, nFill, nLine] = meta;
|
||||
let k = 12;
|
||||
const fillBatches: GpuGeometry['fill']['batches'] = [];
|
||||
|
||||
// Linien-Puffer: interleaved [x,y, nx,ny, side, miter] (6 Float32) — oder, wenn
|
||||
// der Aufrufer es verlangt (nativer Renderer), kompakt 3 Wörter je Vertex:
|
||||
// [x, y (float32-Bits), nx|ny|side|miter als 4 × snorm8].
|
||||
const packedLines = gl.packedLineVertices === true;
|
||||
const lineVerts = new GrowBuffer((n) => new Float32Array(n));
|
||||
const lineVertsPacked = new GrowBuffer((n) => new Uint32Array(n));
|
||||
const bitsF32 = new Float32Array(1);
|
||||
const bitsU32 = new Uint32Array(bitsF32.buffer);
|
||||
const f2u = (v: number): number => {
|
||||
bitsF32[0] = v;
|
||||
return bitsU32[0];
|
||||
};
|
||||
const snorm8 = (v: number): number => Math.round(Math.max(-1, Math.min(1, v)) * 127) & 0xff;
|
||||
const lineIdx = new GrowBuffer((n) => new Uint32Array(n));
|
||||
|
||||
// LOKALER URSPRUNG dieser Geometrie: alle Vertices werden relativ zum ersten
|
||||
// Punkt abgelegt, der Renderer zieht den Ursprung beim Zeichnen in doppelter
|
||||
// Genauigkeit von der Ansicht ab (s. glPlanRender.ts). Hintergrund: Vertices
|
||||
// sind float32; bei Landeskoordinaten (~2,7 Mio. m × 90 px/m = 2,4·10⁸) beträgt
|
||||
// die Auflösung dort ~16 Einheiten → Linien sprangen/verzerrten beim
|
||||
// Hineinzoomen ("Ansicht bugt"). Relativ zu einem Punkt im Chunk bleiben die
|
||||
// Werte klein, auch wenn die Zeichnung weit vom Nullpunkt liegt.
|
||||
let originX = 0;
|
||||
let originY = 0;
|
||||
let originSet = false;
|
||||
const scr = (p: Vec2): Vec2 => {
|
||||
const s = toScreen(p);
|
||||
if (!originSet) {
|
||||
originX = s.x;
|
||||
originY = s.y;
|
||||
originSet = true;
|
||||
}
|
||||
return { x: s.x - originX, y: s.y - originY };
|
||||
};
|
||||
for (let i = 0; i < nFill; i++, k += 6) {
|
||||
fillBatches.push({
|
||||
startIndex: meta[k],
|
||||
indexCount: meta[k + 1],
|
||||
color: [meta[k + 2], meta[k + 3], meta[k + 4], meta[k + 5]] as Rgba,
|
||||
});
|
||||
}
|
||||
const lineBatches: GpuGeometry['line']['batches'] = [];
|
||||
|
||||
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
||||
const track = (mx: number, my: number) => {
|
||||
if (mx < minX) minX = mx;
|
||||
if (my < minY) minY = my;
|
||||
if (mx > maxX) maxX = mx;
|
||||
if (my > maxY) maxY = my;
|
||||
};
|
||||
|
||||
const sameRgba = (a: Rgba, b: Rgba): boolean =>
|
||||
a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];
|
||||
|
||||
// Ordnungserhaltendes Batch-Merging: aufeinanderfolgende Indizes gleicher Farbe
|
||||
// (+ Breite bei Linien) werden zu EINEM Draw-Call zusammengefasst (Reihenfolge
|
||||
// bleibt exakt → korrekte Z-/Alpha-Überlagerung, nur viel weniger State-Wechsel).
|
||||
const addFillBatch = (count: number, color: Rgba) => {
|
||||
const last = fillBatches[fillBatches.length - 1];
|
||||
if (last && sameRgba(last.color, color)) last.indexCount += count;
|
||||
else fillBatches.push({ startIndex: fillIdx.length - count, indexCount: count, color });
|
||||
};
|
||||
const addLineBatch = (count: number, color: Rgba, strokeMm: number, screenPx: boolean) => {
|
||||
const last = lineBatches[lineBatches.length - 1];
|
||||
if (last && last.strokeMm === strokeMm && !!last.screenPx === screenPx && sameRgba(last.color, color))
|
||||
last.indexCount += count;
|
||||
else
|
||||
lineBatches.push({
|
||||
startIndex: lineIdx.length - count,
|
||||
indexCount: count,
|
||||
color,
|
||||
strokeMm,
|
||||
screenPx,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Zeichnet einen zusammenhängenden Linienzug (Bildschirm-Raum) mit ECHTEN
|
||||
* RUNDEN Kappen/Ecken (wie SVG `stroke-linecap/linejoin: round` und der
|
||||
* Vektor-PDF-Pfad) statt eckigem Butt-Cap/Gehrung:
|
||||
* • jedes Segment ist ein eigenständiges Quad mit BUTT-Enden (eigene
|
||||
* Segment-Normale, keine Miter-Verlängerung);
|
||||
* • an jedem inneren Stützpunkt füllt ein Dreiecksfächer (Radius = halbe
|
||||
* Strichbreite) die Außenseite der Ecke rund auf (Innenseite überlappt
|
||||
* unsichtbar, wie bei jedem Disjoint-Segment-Liniendicken-Ansatz);
|
||||
* • an offenen Enden (nicht `closed`) sitzt ein Halbkreis-Fächer als runde
|
||||
* Kappe.
|
||||
* Die tatsächliche Pixel-Breite bleibt bildschirmkonstant: alle Fächer-/Quad-
|
||||
* Vertices tragen nur eine EINHEITS-Richtung (`normal`) + `side`-Skalar; der
|
||||
* Vertex-Shader multipliziert im Clip-Raum mit der aktuellen Strichbreite
|
||||
* (`strokePx*strokeScale`) — die Tessellierung selbst kennt keine Pixelmasse.
|
||||
* `closed` schließt den Ring (letzter↔erster Punkt). Vertex-Layout unverändert:
|
||||
* [x,y, bx,by, side, miter] (miter bleibt hier immer 1, s. Shader-Vertrag).
|
||||
*/
|
||||
const strokePolyline = (
|
||||
ptsM: Vec2[],
|
||||
closed: boolean,
|
||||
color: Rgba,
|
||||
strokeMm: number,
|
||||
screenPx = false,
|
||||
) => {
|
||||
// Auf Bildschirm-Raum abbilden + aufeinanderfolgende Duplikate entfernen.
|
||||
const S: Vec2[] = [];
|
||||
for (const p of ptsM) {
|
||||
const s = scr(p);
|
||||
if (S.length && Math.abs(S[S.length - 1].x - s.x) < 1e-6 && Math.abs(S[S.length - 1].y - s.y) < 1e-6)
|
||||
continue;
|
||||
S.push(s);
|
||||
track(p.x, p.y);
|
||||
}
|
||||
if (closed && S.length > 1) {
|
||||
const f = S[0], l = S[S.length - 1];
|
||||
if (Math.abs(f.x - l.x) < 1e-6 && Math.abs(f.y - l.y) < 1e-6) S.pop();
|
||||
}
|
||||
const k = S.length;
|
||||
if (k < 2) return;
|
||||
|
||||
const dir = (from: Vec2, to: Vec2): Vec2 | null => {
|
||||
const dx = to.x - from.x, dy = to.y - from.y;
|
||||
const len = Math.hypot(dx, dy);
|
||||
return len < 1e-9 ? null : { x: dx / len, y: dy / len };
|
||||
};
|
||||
const leftNormal = (d: Vec2): Vec2 => ({ x: -d.y, y: d.x });
|
||||
|
||||
const startIdxLen = lineIdx.length;
|
||||
const vBase = packedLines ? lineVertsPacked.length / 3 : lineVerts.length / 6;
|
||||
let vcount = 0;
|
||||
const pushVert = (p: Vec2, nx: number, ny: number, side: number): number => {
|
||||
if (packedLines) {
|
||||
lineVertsPacked.push3(
|
||||
f2u(p.x),
|
||||
f2u(p.y),
|
||||
(snorm8(nx) | (snorm8(ny) << 8) | (snorm8(side) << 16) | (127 << 24)) >>> 0,
|
||||
);
|
||||
} else {
|
||||
lineVerts.push6(p.x, p.y, nx, ny, side, 1);
|
||||
}
|
||||
vcount++;
|
||||
return vBase + vcount - 1;
|
||||
};
|
||||
|
||||
const segs = closed ? k : k - 1;
|
||||
const segDir: (Vec2 | null)[] = [];
|
||||
for (let i = 0; i < segs; i++) segDir.push(dir(S[i], S[(i + 1) % k]));
|
||||
|
||||
// Segment-Quads: butt-endig, jedes mit seiner EIGENEN Normale (kein
|
||||
// gemeinsamer Bisektor mehr — Ecken werden separat durch Fächer geschlossen).
|
||||
for (let i = 0; i < segs; i++) {
|
||||
const d = segDir[i];
|
||||
if (!d) continue; // entartetes (Länge-0) Segment
|
||||
const n = leftNormal(d);
|
||||
const a = S[i], b = S[(i + 1) % k];
|
||||
const i0 = pushVert(a, n.x, n.y, +1);
|
||||
const i1 = pushVert(a, n.x, n.y, -1);
|
||||
const i2 = pushVert(b, n.x, n.y, +1);
|
||||
const i3 = pushVert(b, n.x, n.y, -1);
|
||||
lineIdx.push6(i0, i1, i2, i1, i3, i2);
|
||||
}
|
||||
|
||||
// Kreisbogen-Fächer (Zentrum = Vertex, Radius = halbe Strichbreite, per
|
||||
// Shader skaliert): `side=0` am Zentrum (kein Versatz), `side=1` an den
|
||||
// Randpunkten (voller Versatz in Richtung (cosθ,sinθ)).
|
||||
const addFanArc = (p: Vec2, aFrom: number, aTo: number) => {
|
||||
const delta = aTo - aFrom;
|
||||
// Dünne Striche (≤ 0.35 mm, nur wenige Pixel breit): grobe Rundung genügt
|
||||
// und spart ~3× Vertices je Kappe/Ecke (Speicher bei Kataster-Importen).
|
||||
const stepAngle = strokeMm <= 0.35 ? Math.PI / 3 : Math.PI / 10;
|
||||
const steps = Math.max(1, Math.ceil(Math.abs(delta) / stepAngle));
|
||||
const iCenter = pushVert(p, 1, 0, 0);
|
||||
let prev = pushVert(p, Math.cos(aFrom), Math.sin(aFrom), 1);
|
||||
for (let s = 1; s <= steps; s++) {
|
||||
const t = aFrom + (delta * s) / steps;
|
||||
const cur = pushVert(p, Math.cos(t), Math.sin(t), 1);
|
||||
lineIdx.push3(iCenter, prev, cur);
|
||||
prev = cur;
|
||||
}
|
||||
};
|
||||
|
||||
// Runder Join an einem inneren Stützpunkt: Fächer NUR auf der konvexen
|
||||
// (äußeren) Seite der Ecke — die konkave Seite überlappt bereits durch die
|
||||
// beiden Segment-Quads (kein Loch, keine zusätzliche Geometrie nötig).
|
||||
const addRoundJoin = (p: Vec2, d1: Vec2, d2: Vec2) => {
|
||||
const turn = d1.x * d2.y - d1.y * d2.x;
|
||||
const dot = d1.x * d2.x + d1.y * d2.y;
|
||||
if (Math.abs(turn) < 1e-6 && dot > 0) return; // praktisch gerade
|
||||
const n1 = leftNormal(d1), n2 = leftNormal(d2);
|
||||
if (dot < -0.9999) {
|
||||
// ~180°-Umkehr: Außenseite mehrdeutig → voller Kreis (robust, entspricht
|
||||
// zwei gestapelten Rund-Kappen an derselben Stelle).
|
||||
const a0 = Math.atan2(n1.y, n1.x);
|
||||
addFanArc(p, a0, a0 + 2 * Math.PI);
|
||||
return;
|
||||
}
|
||||
const outer = turn > 0 ? -1 : 1;
|
||||
const u1 = { x: outer * n1.x, y: outer * n1.y };
|
||||
const u2 = { x: outer * n2.x, y: outer * n2.y };
|
||||
const a1 = Math.atan2(u1.y, u1.x);
|
||||
let a2 = Math.atan2(u2.y, u2.x);
|
||||
let delta = a2 - a1;
|
||||
while (delta <= -Math.PI) delta += 2 * Math.PI;
|
||||
while (delta > Math.PI) delta -= 2 * Math.PI;
|
||||
if (Math.abs(delta) < 1e-4) return;
|
||||
addFanArc(p, a1, a1 + delta);
|
||||
};
|
||||
|
||||
// Runde Kappe an einem offenen Ende: Halbkreis, der auf der Außenseite
|
||||
// (weg von der Linie) bulgt.
|
||||
const addRoundCap = (p: Vec2, n: Vec2, sweepSign: 1 | -1) => {
|
||||
const a0 = Math.atan2(n.y, n.x);
|
||||
addFanArc(p, a0, a0 + sweepSign * Math.PI);
|
||||
};
|
||||
|
||||
for (let v = 0; v < k; v++) {
|
||||
const hasIn = closed || v > 0;
|
||||
const hasOut = closed || v < k - 1;
|
||||
const dIn = hasIn ? segDir[(v - 1 + segs) % segs] : null;
|
||||
const dOut = hasOut ? segDir[v % segs] : null;
|
||||
if (dIn && dOut) {
|
||||
addRoundJoin(S[v], dIn, dOut);
|
||||
} else if (dOut && !dIn) {
|
||||
// Start-Kappe: bulgt rückwärts (weg vom ersten Segment).
|
||||
addRoundCap(S[v], leftNormal(dOut), 1);
|
||||
} else if (dIn && !dOut) {
|
||||
// End-Kappe: bulgt vorwärts (weg vom letzten Segment).
|
||||
addRoundCap(S[v], leftNormal(dIn), -1);
|
||||
}
|
||||
}
|
||||
|
||||
addLineBatch(lineIdx.length - startIdxLen, color, strokeMm, screenPx);
|
||||
};
|
||||
|
||||
/** Einzelnes Segment als (ungehrter, rund gekapptes) 2-Punkt-Zug. */
|
||||
const pushLine = (aM: Vec2, bM: Vec2, color: Rgba, strokeMm: number) =>
|
||||
strokePolyline([aM, bM], false, color, strokeMm);
|
||||
|
||||
/**
|
||||
* Strichelt den Umriss eines Polygons, wobei die Kanten in `noStroke`
|
||||
* ÜBERSPRUNGEN werden (Kante `i` = pts[i]→pts[i+1]). Die Füllung bleibt das
|
||||
* volle Polygon; nur innere Gehrungs-Stirnkanten am Wandknoten entfallen. Die
|
||||
* sichtbaren Kanten werden als zusammenhängende OFFENE Züge gestrichelt → an
|
||||
* den weggelassenen Kanten laufen die Enden gerade aus (keine Gehrung über die
|
||||
* Naht = keine überschießende Barbe). Leeres `noStroke` ⇒ geschlossener,
|
||||
* gehrter Umriss wie bisher.
|
||||
*/
|
||||
const strokePolygonOutline = (
|
||||
ptsM: Vec2[],
|
||||
color: Rgba,
|
||||
strokeMm: number,
|
||||
noStroke: number[] | undefined,
|
||||
) => {
|
||||
const n = ptsM.length;
|
||||
if (!noStroke || noStroke.length === 0 || n < 2) {
|
||||
strokePolyline(ptsM, true, color, strokeMm);
|
||||
return;
|
||||
}
|
||||
const skip = new Set(noStroke.map((i) => ((i % n) + n) % n));
|
||||
if (skip.size >= n) return; // alle Kanten unterdrückt → nichts zeichnen
|
||||
// Sichtbare Kanten zu zusammenhängenden Läufen bündeln; ein Lauf beginnt an
|
||||
// einer sichtbaren Kante, deren Vorgänger übersprungen ist.
|
||||
const visible = (i: number) => !skip.has(((i % n) + n) % n);
|
||||
for (let s = 0; s < n; s++) {
|
||||
if (!visible(s) || visible(s - 1 + n)) continue; // kein Lauf-Anfang
|
||||
const run: Vec2[] = [ptsM[s]];
|
||||
let j = s;
|
||||
while (visible(j)) {
|
||||
run.push(ptsM[(j + 1) % n]);
|
||||
j++;
|
||||
if (j - s >= n) break; // voller Umlauf (kann bei skip.size≥1 nicht sein)
|
||||
}
|
||||
strokePolyline(run, false, color, strokeMm);
|
||||
}
|
||||
};
|
||||
|
||||
// Zusammenhängende, gleich gestylte 'line'-Primitive (typischerweise die
|
||||
// EINZELNEN Segmente einer importierten Polylinie/Kontur — s. `seg()` in
|
||||
// `generatePlan/drawing2d.ts`, das pro Punktpaar ein eigenes 'line'-Primitiv
|
||||
// erzeugt) werden hier VOR dem Stricheln zu EINEM zusammenhängenden Zug
|
||||
// zusammengefasst. Grund: `strokePolyline` setzt an jedem OFFENEN Ende einen
|
||||
// vollen Rundkappen-Fächer (`addRoundCap`, s. u.); bei N unabhängigen
|
||||
// 2-Punkt-Segmenten macht das aus einer durchgehenden Kontur 2N teure
|
||||
// Kappen statt der 2 echten Enden + (N-1) günstigerer Rund-ÜBERGÄNGE
|
||||
// (`addRoundJoin`, nur auf der Aussenseite). Bei einem Kataster-Import mit
|
||||
// Millionen solcher Segmente (reproduziert mit der echten 439-MB-Luzerner-
|
||||
// Datei: 69'107 Konturen, Ø ~53 Punkte → 3,68 Mio. 'line'-Primitive) hat das
|
||||
// den Linien-Vertexpuffer bis zur `RangeError: Invalid array length`
|
||||
// aufgebläht. NUR eine Rendering-Optimierung — `primitives[i]` bleibt für
|
||||
// Auswahl/Hit-Testing (PlanView.tsx indiziert direkt in `plan.primitives`)
|
||||
// unverändert einzeln adressierbar; am Primitiv-Modell ändert sich nichts,
|
||||
// nur daran, wie die GPU-Geometrie daraus kompiliert wird.
|
||||
const mergedLineRun = new Set<number>();
|
||||
{
|
||||
let i = 0;
|
||||
while (i < primitives.length) {
|
||||
const p0 = primitives[i];
|
||||
if (p0.kind !== 'line' || p0.zigzag || p0.motif) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
const pts: Vec2[] = [p0.a, p0.b];
|
||||
let j = i + 1;
|
||||
while (j < primitives.length) {
|
||||
const pj = primitives[j];
|
||||
if (
|
||||
pj.kind !== 'line' ||
|
||||
pj.zigzag ||
|
||||
pj.motif ||
|
||||
// `drawingId` MUSS übereinstimmen: ohne das verketten sich sonst
|
||||
// ZWEI VERSCHIEDENE (gleich gestylte) Drawing2D-Elemente, die
|
||||
// zufällig einen Eckpunkt teilen (bei Kataster-Daten der Normalfall
|
||||
// — Nachbarparzellen teilen Grenzpunkte) zu EINEM künstlichen,
|
||||
// potenziell riesigen Polylinienzug — genau das hat beim echten
|
||||
// Luzerner Import einen einzelnen `strokePolyline`-Aufruf auf
|
||||
// Milliarden Vertices aufgebläht (`RangeError: Invalid array
|
||||
// length`, reproduziert).
|
||||
pj.drawingId !== p0.drawingId ||
|
||||
pj.color !== p0.color ||
|
||||
pj.weightMm !== p0.weightMm ||
|
||||
pj.greyed !== p0.greyed ||
|
||||
pj.opacity !== p0.opacity ||
|
||||
pj.dash !== p0.dash ||
|
||||
pj.a.x !== pts[pts.length - 1].x ||
|
||||
pj.a.y !== pts[pts.length - 1].y
|
||||
) {
|
||||
break;
|
||||
}
|
||||
pts.push(pj.b);
|
||||
j++;
|
||||
}
|
||||
if (j - i > 1) {
|
||||
const color = dim(parseColor(p0.color) ?? [0.1, 0.1, 0.1, 1], p0.greyed, p0.opacity);
|
||||
strokePolyline(pts, false, color, p0.weightMm || 0.18);
|
||||
for (let k = i; k < j; k++) mergedLineRun.add(k);
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
for (let i = 0; i < nLine; i++, k += 8) {
|
||||
lineBatches.push({
|
||||
startIndex: meta[k],
|
||||
indexCount: meta[k + 1],
|
||||
color: [meta[k + 2], meta[k + 3], meta[k + 4], meta[k + 5]] as Rgba,
|
||||
strokeMm: meta[k + 6],
|
||||
screenPx: meta[k + 7] === 1,
|
||||
});
|
||||
}
|
||||
let off = out.byteOffset + 8 + m * 8;
|
||||
const fillPos = new Float32Array(out.buffer, off, nFillPos);
|
||||
off += nFillPos * 4;
|
||||
const fillIdx = new Uint32Array(out.buffer, off, nFillIdx);
|
||||
off += nFillIdx * 4;
|
||||
// Gepackte Linien-Vertices sind Wörter, ungepackte f32 — die Bytes sind dieselben.
|
||||
const lineVerts = new Uint32Array(out.buffer, off, nLineVerts);
|
||||
off += nLineVerts * 4;
|
||||
const lineIdx = new Uint32Array(out.buffer, off, nLineIdx);
|
||||
|
||||
for (let primIdx = 0; primIdx < primitives.length; primIdx++) {
|
||||
const prim = primitives[primIdx];
|
||||
if (mergedLineRun.has(primIdx)) continue;
|
||||
if (prim.kind === 'polygon') {
|
||||
// Füllung (falls vorhanden).
|
||||
const fill = parseColor(prim.fill);
|
||||
if (fill) {
|
||||
const tris = triangulate(prim.pts);
|
||||
if (tris.length) {
|
||||
const base = fillPos.length / 2;
|
||||
for (const pt of prim.pts) {
|
||||
const s = scr(pt);
|
||||
fillPos.push2(s.x, s.y);
|
||||
track(pt.x, pt.y);
|
||||
}
|
||||
for (const t of tris) fillIdx.push1(base + t);
|
||||
addFillBatch(tris.length, dimFill(fill, prim.greyed, prim.opacity));
|
||||
}
|
||||
}
|
||||
// Schraffur (nach der Füllung, vor/passend zum Umriss — wie der SVG stapelt):
|
||||
// das Muster wird in echte Linien-Geometrie (Modell-Meter) tesselliert und
|
||||
// aufs Polygon geclippt (konkav-fähig, even-odd). Musterlinien fließen als
|
||||
// zusammenhängende Läufe in `strokePolyline` → glatte, RUND gekappte/
|
||||
// -verbundene Übergänge (insb. die Dämmungswelle bleibt spitzenfrei).
|
||||
// BREITE — die Schraffur ist jetzt ein GEWÖHNLICHER Papier-mm-Stift, mit
|
||||
// derselben LineStyle-Stärke (0.02 mm) wie die Wand-Schichtfugen, und
|
||||
// läuft durch dieselbe STANDARD-Pipeline wie jede andere Linie
|
||||
// (screenPx=false). `paperScaleForGl` liefert im Bildschirm-/Haarlinien-
|
||||
// Modus den reziproken `meet`-Massstab, wodurch `mmToDevicePx` dort
|
||||
// zoomunabhängig konstant bleibt — die Schraffur erscheint als konstante
|
||||
// Haarlinie wie jede Wandlinie, und im Druckmodus als echte 0.02 mm,
|
||||
// deckungsgleich mit den Schichtfugen in beiden Modi.
|
||||
// `hatch.dash` wird geometrisch (Strich/Lücke) aufgelöst, da die GL-
|
||||
// Linien-Pipeline kein Dash kennt.
|
||||
// Bild-/Verlauf-Schraffur (kind==="image"/"gradient"): WebGL2-Ebene kennt
|
||||
// weder Muster-Textur noch echten Farbverlauf → FALLBACK auf die neutrale
|
||||
// Poché-Füllung (oben), keine Musterlinien. Der Random-Untermodus läuft
|
||||
// transparent über `buildHatchRuns` (Streu-Striche).
|
||||
if (
|
||||
prim.hatch &&
|
||||
prim.hatch.kind !== 'image' &&
|
||||
prim.hatch.kind !== 'gradient' &&
|
||||
prim.hatch.pattern !== 'none' &&
|
||||
prim.hatch.pattern !== 'solid'
|
||||
) {
|
||||
const hatchColor = dim(parseColor(prim.hatch.color) ?? [0.1, 0.1, 0.1, 1], prim.greyed, prim.opacity);
|
||||
const hatchMm = prim.hatch.lineWeight > 0 ? prim.hatch.lineWeight : 0.13;
|
||||
const runs = applyDashRuns(buildHatchRuns(prim.pts, prim.hatch), prim.hatch.dash);
|
||||
for (const run of runs) strokePolyline(run, false, hatchColor, hatchMm, false);
|
||||
}
|
||||
// Umriss (crispe Kante) — geschlossener Ring, GEHRT (kein Stufen-Cap an
|
||||
// Ecken). Breite = ECHTE Papier-mm; der Renderer rechnet massstabs-/
|
||||
// zoomrichtig in px (wie SVG-printStrokeVb → GL == SVG).
|
||||
const stroke = parseColor(prim.stroke);
|
||||
if (stroke && prim.strokeWidthMm > 0 && prim.pts.length >= 2) {
|
||||
strokePolygonOutline(prim.pts, dim(stroke, prim.greyed, prim.opacity), prim.strokeWidthMm, prim.noStrokeEdges);
|
||||
}
|
||||
} else if (prim.kind === 'line') {
|
||||
const color = dim(parseColor(prim.color) ?? [0.1, 0.1, 0.1, 1], prim.greyed, prim.opacity);
|
||||
if (prim.zigzag) {
|
||||
// Zickzack-Linie → gehrter Polylinienzug (amplitude/wavelength Papier-mm
|
||||
// → Modell-Meter über dieselbe Kopplung wie Strichmuster).
|
||||
const amp = prim.zigzag.amplitude * DASH_MM_TO_M;
|
||||
const wav = prim.zigzag.wavelength * DASH_MM_TO_M;
|
||||
const zpts = zigzagPoints(prim.a, prim.b, amp, wav);
|
||||
strokePolyline(zpts, false, color, prim.weightMm || 0.18);
|
||||
} else if (prim.motif) {
|
||||
// Custom-Motiv → gehrter Polylinienzug (Papier-mm → Modell-Meter, wie Zickzack).
|
||||
const mpts = motifPoints(prim.a, prim.b, prim.motif, DASH_MM_TO_M);
|
||||
strokePolyline(mpts, false, color, prim.weightMm || 0.18);
|
||||
} else {
|
||||
pushLine(prim.a, prim.b, color, prim.weightMm || 0.18);
|
||||
}
|
||||
} else if (prim.kind === 'arc') {
|
||||
// Bogen → ein gehrter Polylinienzug (glatt, keine Segment-Stufen).
|
||||
const color = dim(
|
||||
parseColor((prim as { color?: string }).color) ?? [0.1, 0.1, 0.1, 1],
|
||||
prim.greyed,
|
||||
prim.opacity,
|
||||
);
|
||||
const strokeMm = prim.weightMm || 0.18;
|
||||
const c = prim.center;
|
||||
const a0 = Math.atan2(prim.from.y - c.y, prim.from.x - c.x);
|
||||
const a1 = Math.atan2(prim.to.y - c.y, prim.to.x - c.x);
|
||||
// Kürzeste Drehrichtung (Delta nach (-π, π]).
|
||||
let d = a1 - a0;
|
||||
while (d <= -Math.PI) d += 2 * Math.PI;
|
||||
while (d > Math.PI) d -= 2 * Math.PI;
|
||||
// Bildschirm-adaptive Tessellierung (LOD): der Bogen-Radius in Geräte-px
|
||||
// ist rPx = r · pxPerMeter. Der Segment-Winkel θ wird so gewählt, dass die
|
||||
// Sagitta (Sehnen-Ausbauchung) rPx·(1−cos(θ/2)) unter ~0.5 px bleibt →
|
||||
// θ = 2·acos(1 − 0.5/rPx). Weit weg (kleiner rPx) = wenige Segmente (billig,
|
||||
// Facetten unsichtbar); hineingezoomt = viele Segmente = runder Bogen — wie
|
||||
// im CAD. Geklammert auf [8, 2048]. pxPerMeter=0 → fixer Rückfall (16/90°).
|
||||
// Der Aufrufer (PlanView) re-tesselliert nur bei LOD-Bucket-Wechseln, nicht
|
||||
// je Frame; Pan/Zoom bleibt reines Matrix-Update.
|
||||
let segs: number;
|
||||
if (pxPerMeter > 0) {
|
||||
const rPx = prim.r * pxPerMeter;
|
||||
// Für sehr kleine rPx ist 0.5/rPx ≥ 1 (kein realer acos) → Minimum greift.
|
||||
const theta = rPx > 0.5 ? 2 * Math.acos(1 - 0.5 / rPx) : Math.PI;
|
||||
segs = Math.min(2048, Math.max(8, Math.ceil(Math.abs(d) / theta)));
|
||||
} else {
|
||||
segs = Math.max(4, Math.ceil((Math.abs(d) / (Math.PI / 2)) * 16));
|
||||
}
|
||||
const arcPts: Vec2[] = [prim.from];
|
||||
for (let i = 1; i <= segs; i++) {
|
||||
const t = a0 + (d * i) / segs;
|
||||
arcPts.push({ x: c.x + prim.r * Math.cos(t), y: c.y + prim.r * Math.sin(t) });
|
||||
}
|
||||
strokePolyline(arcPts, false, color, strokeMm);
|
||||
} else if (prim.kind === 'drawingCircle' || prim.kind === 'drawingArc') {
|
||||
// 2D-Zeichnungs-Kreis/-Bogen (Kreis-/Bogen-Werkzeug ODER DXF-Import). Der
|
||||
// SVG-Pfad zeichnet sie als glattes <circle>/<path>; die WebGL-Ebene kennt
|
||||
// kein Kreis-Primitiv → hier bildschirm-adaptiv tessellieren (wie 'arc').
|
||||
// Kreis = voller Umlauf (geschlossen, optional gefüllt), Bogen = a0..a1 (CCW,
|
||||
// offen). OHNE diesen Zweig blieben gezeichnete Kreise/Bögen im GL unsichtbar.
|
||||
const stroke = dim(parseColor(prim.stroke) ?? [0.1, 0.1, 0.1, 1], prim.greyed, prim.opacity);
|
||||
const strokeMm = prim.weightMm || 0.18;
|
||||
const c = prim.center;
|
||||
const TAU = Math.PI * 2;
|
||||
const a0 = prim.kind === 'drawingArc' ? prim.a0 : 0;
|
||||
const sweep =
|
||||
prim.kind === 'drawingArc'
|
||||
? ((prim.a1 - prim.a0) % TAU + TAU) % TAU || TAU
|
||||
: TAU;
|
||||
// Segmentzahl wie im 'arc'-Zweig: Sagitta < ~0.5 px (LOD über pxPerMeter).
|
||||
let segs: number;
|
||||
if (pxPerMeter > 0) {
|
||||
const rPx = prim.r * pxPerMeter;
|
||||
const theta = rPx > 0.5 ? 2 * Math.acos(1 - 0.5 / rPx) : Math.PI;
|
||||
segs = Math.min(2048, Math.max(8, Math.ceil(sweep / theta)));
|
||||
} else {
|
||||
segs = Math.max(8, Math.ceil((sweep / (Math.PI / 2)) * 16));
|
||||
}
|
||||
const pts: Vec2[] = [];
|
||||
for (let i = 0; i <= segs; i++) {
|
||||
const t = a0 + (sweep * i) / segs;
|
||||
pts.push({ x: c.x + prim.r * Math.cos(t), y: c.y + prim.r * Math.sin(t) });
|
||||
}
|
||||
// Vollton-Füllung nur beim geschlossenen Kreis (Bogen ist offen).
|
||||
if (prim.kind === 'drawingCircle') {
|
||||
const fill = parseColor(prim.fill);
|
||||
if (fill) {
|
||||
const ring = pts.slice(0, segs); // ohne den doppelten Schlusspunkt
|
||||
const tris = triangulate(ring);
|
||||
if (tris.length) {
|
||||
const base = fillPos.length / 2;
|
||||
for (const pt of ring) {
|
||||
const s = scr(pt);
|
||||
fillPos.push2(s.x, s.y);
|
||||
track(pt.x, pt.y);
|
||||
}
|
||||
for (const t of tris) fillIdx.push1(base + t);
|
||||
addFillBatch(tris.length, dimFill(fill, prim.greyed, prim.opacity));
|
||||
}
|
||||
}
|
||||
}
|
||||
strokePolyline(pts, prim.kind === 'drawingCircle', stroke, strokeMm);
|
||||
}
|
||||
// Text: bleibt im SVG-Overlay (scharfe Schrift, DOM-Hit-Test).
|
||||
}
|
||||
|
||||
// Puffer hochladen.
|
||||
const uploadArray = (data: GrowBuffer<Float32Array> | GrowBuffer<Uint32Array>): WebGLBuffer | null => {
|
||||
const upload = (target: number, data: ArrayBufferView & { length: number }): WebGLBuffer | null => {
|
||||
if (!data.length) return null;
|
||||
const buf = gl.createBuffer();
|
||||
if (!buf) return null;
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, data.view(), gl.STATIC_DRAW);
|
||||
gl.bindBuffer(target, buf);
|
||||
gl.bufferData(target, data, gl.STATIC_DRAW);
|
||||
return buf;
|
||||
};
|
||||
const uploadIndex = (data: GrowBuffer<Uint32Array>): WebGLBuffer | null => {
|
||||
if (!data.length) return null;
|
||||
const buf = gl.createBuffer();
|
||||
if (!buf) return null;
|
||||
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buf);
|
||||
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data.view(), gl.STATIC_DRAW);
|
||||
return buf;
|
||||
};
|
||||
|
||||
return {
|
||||
fill: {
|
||||
positionBuffer: uploadArray(fillPos),
|
||||
indexBuffer: uploadIndex(fillIdx),
|
||||
positionBuffer: upload(gl.ARRAY_BUFFER, fillPos),
|
||||
indexBuffer: upload(gl.ELEMENT_ARRAY_BUFFER, fillIdx),
|
||||
batches: fillBatches,
|
||||
},
|
||||
line: {
|
||||
vertexBuffer: uploadArray(packedLines ? lineVertsPacked : lineVerts),
|
||||
indexBuffer: uploadIndex(lineIdx),
|
||||
vertexBuffer: upload(gl.ARRAY_BUFFER, gl.packedLineVertices === true ? lineVerts : new Float32Array(lineVerts.buffer, lineVerts.byteOffset, lineVerts.length)),
|
||||
indexBuffer: upload(gl.ELEMENT_ARRAY_BUFFER, lineIdx),
|
||||
batches: lineBatches,
|
||||
},
|
||||
origin: { x: originX, y: originY },
|
||||
|
||||
+104
-677
@@ -1,33 +1,23 @@
|
||||
/**
|
||||
* Schraffur-Tessellierung für den GPU-Grundriss: wandelt ein Polygon mit
|
||||
* aufgelöster {@link HatchRender} in eine Schar echter Linien-Segmente (Modell-
|
||||
* Meter), die anschließend über `strokePolyline`/`pushLine` in die Linien-Puffer
|
||||
* fließen. Damit rendert die GPU-Ebene dieselben Muster wie der SVG-`<pattern>`-
|
||||
* Renderer, nur als tessellierte Geometrie statt als Kachel-Füllung.
|
||||
* Schraffur- und Linienmuster-Geometrie des Grundrisses — Fassade über den Rust-Kern ([K3b],
|
||||
* `src-tauri/core/src/hatch.rs`). Wandelt ein Polygon mit aufgelöster {@link HatchRender} in eine
|
||||
* Schar echter Linienzüge (Modell-Meter), die die GPU-Kompilierung, `toRenderScene`, der Druck-
|
||||
* SVG- und der DXF-Export zeichnen; dazu Strichmuster, Zickzack und Motiv-Kachelung.
|
||||
*
|
||||
* KOORDINATEN & MASSSTAB (muss deckungsgleich zum SVG sein):
|
||||
* • Der SVG-`<pattern>` ist in BILDSCHIRM-Raum (viewBox-px, `sx = mx·PX_PER_M`)
|
||||
* definiert; Kachelgröße = `8·scale` px (diagonal/cross) bzw. `14×10·scale` px
|
||||
* (insulation), gedreht per `rotate(angle)` (im Uhrzeigersinn, Bildschirm-Y
|
||||
* nach unten). Die Muster-GEOMETRIE skaliert also mit dem Zoom (Papier).
|
||||
* • Wir erzeugen die Muster direkt in MODELL-Metern: ein px in Bildschirm-Raum
|
||||
* entspricht `1/PX_PER_M` m. So passen Abstand/Winkel exakt zum SVG, und die
|
||||
* Segmente lassen sich unverändert an `strokePolyline` (Papier-mm-Breite)
|
||||
* übergeben.
|
||||
* • Die STRICHBREITE bleibt in Papier-mm (`hatch.lineWeight`) — genau wie beim
|
||||
* SVG-Muster, das `hatchStrokePx(lineWeight)` als non-scaling-artige Breite
|
||||
* zeichnet.
|
||||
* KOORDINATEN & MASSSTAB (deckungsgleich zum SVG-`<pattern>`): die Muster entstehen direkt in
|
||||
* Modell-Metern (1 px Bildschirm-Raum = 1/90 m), Kachel 8·scale px (diagonal/kreuz) bzw.
|
||||
* 14×10·scale px (Dämmung), Raster-Anker = Modellursprung bzw. `hatch.origin`. Strichstärken
|
||||
* bleiben Papier-mm.
|
||||
*/
|
||||
|
||||
import type { Vec2 } from '../../model/types';
|
||||
import type { HatchRender } from '../generatePlan';
|
||||
import { encodeHatch } from '../planBuf';
|
||||
import { core } from '../../engine/coreWasm';
|
||||
|
||||
/** Bildschirm-Einheiten (viewBox-px) je Meter — identisch zu PlanView.toScreen. */
|
||||
const PX_PER_M = 90;
|
||||
|
||||
/** px (Bildschirm-Raum) → Meter (Modell-Raum). */
|
||||
const PX_TO_M = 1 / PX_PER_M;
|
||||
|
||||
/** Ein Linien-Segment in Modell-Metern. */
|
||||
export interface HatchSegment {
|
||||
a: Vec2;
|
||||
@@ -35,553 +25,128 @@ export interface HatchSegment {
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein zusammenhängender Linienzug in Modell-Metern (≥2 Punkte). Gerade
|
||||
* Musterlinien (diagonal/crosshatch) sind 2-Punkt-Läufe; die Dämmungs-Welle ist
|
||||
* ein langer, an den Polygonkanten geclippter Lauf. Läufe fließen als EIN gehrter
|
||||
* Streifen in `strokePolyline` → glatte Übergänge statt Butt-Cap-Stufen.
|
||||
* Ein zusammenhängender Linienzug in Modell-Metern (≥2 Punkte). Gerade Musterlinien sind
|
||||
* 2-Punkt-Läufe; die Dämmungs-Welle ist ein langer, an den Polygonkanten geclippter Lauf.
|
||||
*/
|
||||
export type HatchRun = Vec2[];
|
||||
|
||||
/**
|
||||
* Achsen-ausgerichtetes Bounding-Rechteck eines Polygons (Modell-Meter).
|
||||
* Leeres Polygon → degeneriert (min>max), der Aufrufer erzeugt dann keine Linien.
|
||||
* Faktor mm-Papier → Modell-Meter des Musterraums, identisch zum SVG-`dashArray` (dort
|
||||
* `dash·(1/0.13)` px).
|
||||
*/
|
||||
function bbox(poly: Vec2[]): { minX: number; minY: number; maxX: number; maxY: number } {
|
||||
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
||||
for (const p of poly) {
|
||||
if (p.x < minX) minX = p.x;
|
||||
if (p.y < minY) minY = p.y;
|
||||
if (p.x > maxX) maxX = p.x;
|
||||
if (p.y > maxY) maxY = p.y;
|
||||
export const DASH_MM_TO_M = (1 / 0.13) * (1 / PX_PER_M);
|
||||
|
||||
function flat(pts: readonly Vec2[]): Float64Array {
|
||||
const out = new Float64Array(pts.length * 2);
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
out[2 * i] = pts[i].x;
|
||||
out[2 * i + 1] = pts[i].y;
|
||||
}
|
||||
return { minX, minY, maxX, maxY };
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schneidet eine UNENDLICHE Linie (Aufpunkt `p0`, Einheits-Richtung `dir`) mit
|
||||
* einem einfachen (auch KONKAVEN) Polygon und liefert die INNERHALB liegenden
|
||||
* Segmente. Vorgehen (robustes Even-Odd-Scanline-Prinzip):
|
||||
* 1. Für jede Polygon-Kante den Schnitt-Parameter `t` (entlang `dir`) berechnen,
|
||||
* bei dem die Linie die Kante quert.
|
||||
* 2. Alle `t` sortieren; aufeinanderfolgende Paare (t0,t1),(t2,t3),… liegen im
|
||||
* Inneren (even-odd) → als Segmente zurückgeben.
|
||||
* Das ist für beliebige konkave Polygone korrekt, weil eine Gerade ein einfaches
|
||||
* Polygon stets in eine gerade Anzahl Kanten schneidet und die Innen-Intervalle
|
||||
* sich mit jeder Kreuzung ein-/ausschalten.
|
||||
*
|
||||
* Robustheit an Ecken: Ein Schnitt wird nur gezählt, wenn die Linie die Kante
|
||||
* ECHT quert (die beiden Endpunkte liegen auf verschiedenen Seiten). Berührungen
|
||||
* genau am Eckpunkt werden über eine halb-offene Kanten-Konvention (das untere
|
||||
* Kanten-Ende zählt, das obere nicht) vermieden, sodass keine doppelten oder
|
||||
* fehlenden Kreuzungen entstehen.
|
||||
*/
|
||||
export function clipLineToPolygon(p0: Vec2, dir: Vec2, poly: Vec2[]): HatchSegment[] {
|
||||
const n = poly.length;
|
||||
if (n < 3) return [];
|
||||
|
||||
// Senkrechte zur Richtung: side(p) = vorzeichenbehaftete Distanz zur Linie.
|
||||
const nx = -dir.y;
|
||||
const ny = dir.x;
|
||||
const side = (p: Vec2) => (p.x - p0.x) * nx + (p.y - p0.y) * ny;
|
||||
|
||||
const ts: number[] = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const a = poly[i];
|
||||
const b = poly[(i + 1) % n];
|
||||
const sa = side(a);
|
||||
const sb = side(b);
|
||||
|
||||
// Beide echt auf derselben Seite → keine Kreuzung.
|
||||
if (sa > 0 && sb > 0) continue;
|
||||
if (sa < 0 && sb < 0) continue;
|
||||
|
||||
// Halb-offene Konvention gegen Doppel-/Fehlzählung an Eckpunkten:
|
||||
// • Kante liegt exakt AUF der Linie → ignorieren.
|
||||
// • Berührung genau an einem Endpunkt (side==0) zählt nur, wenn der ANDERE
|
||||
// Endpunkt echt oberhalb (>0) liegt. So gehört ein Eckpunkt eindeutig zur
|
||||
// Kante darunter und wird genau EINMAL gezählt.
|
||||
if (sa === 0 && sb === 0) continue;
|
||||
if (sa === 0 && sb < 0) continue;
|
||||
if (sb === 0 && sa < 0) continue;
|
||||
|
||||
// Parameter `t` entlang `dir` am Schnittpunkt: Nullstelle von side auf der
|
||||
// Kante interpolieren, dann auf `dir` projizieren.
|
||||
const denom = sa - sb;
|
||||
const u = denom !== 0 ? sa / denom : 0; // Anteil a→b bis side==0
|
||||
const ix = a.x + (b.x - a.x) * u;
|
||||
const iy = a.y + (b.y - a.y) * u;
|
||||
const t = (ix - p0.x) * dir.x + (iy - p0.y) * dir.y;
|
||||
ts.push(t);
|
||||
}
|
||||
|
||||
if (ts.length < 2) return [];
|
||||
ts.sort((x, y) => x - y);
|
||||
|
||||
const segs: HatchSegment[] = [];
|
||||
for (let i = 0; i + 1 < ts.length; i += 2) {
|
||||
const t0 = ts[i];
|
||||
const t1 = ts[i + 1];
|
||||
if (t1 - t0 < 1e-9) continue; // entartetes Intervall (Tangente an Ecke)
|
||||
segs.push({
|
||||
a: { x: p0.x + dir.x * t0, y: p0.y + dir.y * t0 },
|
||||
b: { x: p0.x + dir.x * t1, y: p0.y + dir.y * t1 },
|
||||
});
|
||||
}
|
||||
return segs;
|
||||
function toPts(f: Float64Array): Vec2[] {
|
||||
const out: Vec2[] = new Array(f.length >> 1);
|
||||
for (let i = 0; i < out.length; i++) out[i] = { x: f[2 * i], y: f[2 * i + 1] };
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schneidet ein ENDLICHES Segment [a,b] gegen ein (konkaves) Polygon und liefert
|
||||
* die innenliegenden Teilstücke. Baut auf {@link clipLineToPolygon} auf: erst die
|
||||
* Innen-Intervalle der Trägergeraden bestimmen, dann mit [a,b] (Parameterbereich
|
||||
* [0,len]) verschneiden.
|
||||
*/
|
||||
export function clipSegmentToPolygon(a: Vec2, b: Vec2, poly: Vec2[]): HatchSegment[] {
|
||||
const dx = b.x - a.x;
|
||||
const dy = b.y - a.y;
|
||||
const len = Math.hypot(dx, dy);
|
||||
if (len < 1e-12) return [];
|
||||
const dir: Vec2 = { x: dx / len, y: dy / len };
|
||||
const full = clipLineToPolygon(a, dir, poly);
|
||||
function toSegs(f: Float64Array): HatchSegment[] {
|
||||
const out: HatchSegment[] = [];
|
||||
for (const seg of full) {
|
||||
// Parameter der Innen-Intervall-Enden entlang `dir` (ab Aufpunkt a).
|
||||
const t0 = (seg.a.x - a.x) * dir.x + (seg.a.y - a.y) * dir.y;
|
||||
const t1 = (seg.b.x - a.x) * dir.x + (seg.b.y - a.y) * dir.y;
|
||||
const lo = Math.max(0, Math.min(t0, t1));
|
||||
const hi = Math.min(len, Math.max(t0, t1));
|
||||
if (hi - lo < 1e-9) continue;
|
||||
out.push({
|
||||
a: { x: a.x + dir.x * lo, y: a.y + dir.y * lo },
|
||||
b: { x: a.x + dir.x * hi, y: a.y + dir.y * hi },
|
||||
});
|
||||
for (let i = 0; i + 3 < f.length; i += 4) out.push({ a: { x: f[i], y: f[i + 1] }, b: { x: f[i + 2], y: f[i + 3] } });
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `[n, x, y, …, n, …]` → Läufe. */
|
||||
function toRuns(f: Float64Array): HatchRun[] {
|
||||
const out: HatchRun[] = [];
|
||||
let i = 0;
|
||||
while (i < f.length) {
|
||||
const n = f[i++];
|
||||
const run: Vec2[] = new Array(n);
|
||||
for (let k = 0; k < n; k++, i += 2) run[k] = { x: f[i], y: f[i + 1] };
|
||||
out.push(run);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function runsFlat(runs: readonly HatchRun[]): Float64Array {
|
||||
let n = 0;
|
||||
for (const r of runs) n += 1 + 2 * r.length;
|
||||
const out = new Float64Array(n);
|
||||
let i = 0;
|
||||
for (const r of runs) {
|
||||
out[i++] = r.length;
|
||||
for (const p of r) {
|
||||
out[i++] = p.x;
|
||||
out[i++] = p.y;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schneidet eine ZUSAMMENHÄNGENDE Polylinie `pts` gegen ein (auch KONKAVES)
|
||||
* einfaches Polygon und liefert die innenliegenden Teile als CONTINUOUS runs
|
||||
* (jeder Lauf = Vec2[] mit ≥2 Punkten). Anders als segmentweises Clippen bleiben
|
||||
* aufeinanderfolgende Innen-Segmente in EINEM Lauf verbunden — die interne
|
||||
* Tessellierung (z. B. Sinus-Stützpunkte) wird NICHT an jedem Vertex zerrissen.
|
||||
* Nur ein echtes Austreten aus dem Polygon (bzw. eine Lücke) beginnt einen neuen
|
||||
* Lauf. Nutzt dieselbe Even-Odd-/halb-offene-Kanten-Konvention wie
|
||||
* {@link clipLineToPolygon} via {@link clipSegmentToPolygon}.
|
||||
*
|
||||
* Verfahren: jede Polylinien-Kante wird geclippt; die (in Laufrichtung
|
||||
* sortierten) Innenstücke werden an den laufenden Lauf angehängt, solange ihr
|
||||
* Anfang bündig ans bisherige Lauf-Ende anschließt. Sobald ein Innenstück nicht
|
||||
* am Lauf-Ende beginnt (Wiedereintritt nach einem Austritt) oder die Kante gar
|
||||
* kein Innenstück liefert (komplett außen), wird der Lauf abgeschlossen.
|
||||
* Schneidet eine UNENDLICHE Linie (Aufpunkt `p0`, Einheits-Richtung `dir`) mit einem einfachen
|
||||
* (auch konkaven) Polygon und liefert die innenliegenden Segmente (even-odd, halb-offene
|
||||
* Kantenkonvention an Ecken).
|
||||
*/
|
||||
export function clipPolylineToPolygon(pts: Vec2[], poly: Vec2[]): HatchRun[] {
|
||||
if (pts.length < 2 || poly.length < 3) return [];
|
||||
const EPS = 1e-9;
|
||||
const near = (p: Vec2, q: Vec2) => Math.abs(p.x - q.x) < EPS && Math.abs(p.y - q.y) < EPS;
|
||||
export function clipLineToPolygon(p0: Vec2, dir: Vec2, poly: Vec2[]): HatchSegment[] {
|
||||
if (poly.length < 3) return [];
|
||||
return toSegs(core().clip_line_to_polygon_flat(p0.x, p0.y, dir.x, dir.y, flat(poly)));
|
||||
}
|
||||
|
||||
const runs: HatchRun[] = [];
|
||||
let cur: HatchRun | null = null;
|
||||
|
||||
const closeRun = () => {
|
||||
if (cur && cur.length >= 2) runs.push(cur);
|
||||
cur = null;
|
||||
};
|
||||
|
||||
for (let i = 0; i + 1 < pts.length; i++) {
|
||||
const a = pts[i];
|
||||
const b = pts[i + 1];
|
||||
// Innenstücke dieser Kante, in Laufrichtung a→b sortiert (clipSegment liefert
|
||||
// sie bereits entlang der Trägergeraden geordnet; a→b ist die positive Richtung).
|
||||
const pieces = clipSegmentToPolygon(a, b, poly);
|
||||
for (const seg of pieces) {
|
||||
// Kante in Laufrichtung orientieren (clipSegment kann a/b vertauschen).
|
||||
const dx = b.x - a.x, dy = b.y - a.y;
|
||||
const ta = (seg.a.x - a.x) * dx + (seg.a.y - a.y) * dy;
|
||||
const tb = (seg.b.x - a.x) * dx + (seg.b.y - a.y) * dy;
|
||||
const s = ta <= tb ? seg.a : seg.b;
|
||||
const e = ta <= tb ? seg.b : seg.a;
|
||||
|
||||
if (cur && near(cur[cur.length - 1], s)) {
|
||||
// Nahtloser Anschluss ans Lauf-Ende → nur den neuen Endpunkt anhängen.
|
||||
cur.push(e);
|
||||
} else {
|
||||
// Neuer Lauf (erster Innenteil oder Wiedereintritt nach Austritt).
|
||||
closeRun();
|
||||
cur = [s, e];
|
||||
}
|
||||
}
|
||||
// Endete diese Kante NICHT genau am Polygonrand-Innenstück bis b (d. h. das
|
||||
// letzte Innenstück reicht nicht bis zum Kantenende b), so tritt der Lauf hier
|
||||
// aus dem Polygon → beim nächsten Innenteil beginnt ein neuer Lauf.
|
||||
if (cur && !near(cur[cur.length - 1], b)) closeRun();
|
||||
}
|
||||
closeRun();
|
||||
return runs;
|
||||
/** Schneidet ein ENDLICHES Segment [a,b] gegen ein (konkaves) Polygon. */
|
||||
export function clipSegmentToPolygon(a: Vec2, b: Vec2, poly: Vec2[]): HatchSegment[] {
|
||||
return toSegs(core().clip_segment_to_polygon_flat(a.x, a.y, b.x, b.y, flat(poly)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Erzeugt eine Schar paralleler, aufs Polygon geclippter Linien-Segmente:
|
||||
* Richtung `angleRad` (Modell-Raum, gegen den Uhrzeigersinn), Abstand `spacingM`
|
||||
* (Meter) senkrecht zur Richtung, Phasen-Versatz `offsetM` (Meter, entlang der
|
||||
* Normalen). Deckt das Polygon vollständig ab (über dessen projizierte Ausdehnung).
|
||||
* Schneidet eine zusammenhängende Polylinie gegen ein (konkaves) Polygon; die Innenteile bleiben
|
||||
* zusammenhängende Läufe (nur ein echtes Austreten beginnt einen neuen Lauf).
|
||||
*/
|
||||
export function clipPolylineToPolygon(pts: Vec2[], poly: Vec2[]): HatchRun[] {
|
||||
if (pts.length < 2 || poly.length < 3) return [];
|
||||
return toRuns(core().clip_polyline_to_polygon_flat(flat(pts), flat(poly)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Schar paralleler, aufs Polygon geclippter Linien: Richtung `angleRad` (Modell, CCW), Abstand
|
||||
* `spacingM`, Phasen-Versatz `offsetM`, Raster-Anker `anchor` (Default Modellursprung — wie das
|
||||
* SVG-`userSpaceOnUse`-Muster; ein Objekt verschiebt ihn über `Drawing2D.hatchOrigin`).
|
||||
*/
|
||||
export function hatchLineFamily(
|
||||
poly: Vec2[],
|
||||
angleRad: number,
|
||||
spacingM: number,
|
||||
offsetM = 0,
|
||||
/**
|
||||
* Ankerpunkt des Rasters. Default ist der MODELL-URSPRUNG (s. Kommentar
|
||||
* unten); ein Objekt kann ihn über `Drawing2D.hatchOrigin` verschieben,
|
||||
* um das Muster z. B. an einer Raumecke ansetzen zu lassen.
|
||||
*/
|
||||
anchor: Vec2 = { x: 0, y: 0 },
|
||||
): HatchSegment[] {
|
||||
if (poly.length < 3 || spacingM <= 1e-9) return [];
|
||||
const bb = bbox(poly);
|
||||
if (!(bb.maxX > bb.minX) && !(bb.maxY > bb.minY)) return [];
|
||||
|
||||
const dir: Vec2 = { x: Math.cos(angleRad), y: Math.sin(angleRad) };
|
||||
const nrm: Vec2 = { x: -dir.y, y: dir.x }; // Linien-Normale (Scan-Richtung)
|
||||
|
||||
// Rechtwinklige Projektion aller Ecken auf die Normale → Abdeckungsbereich.
|
||||
// ANKER = MODELL-URSPRUNG (nicht die Polygon-Mitte): der SVG-`<pattern>` ist
|
||||
// `userSpaceOnUse`, sein Kachelgitter liegt global im viewBox-Raum fest
|
||||
// (Ursprung (0,0) = Modell-Ursprung). Nur mit demselben Anker liegen die
|
||||
// Musterlinien deckungsgleich zum SVG-Referenzpfad — und benachbarte Polygone
|
||||
// teilen dieselbe Muster-Phase statt je eigener (bbox-abhängiger) Versätze.
|
||||
const center: Vec2 = anchor;
|
||||
let dMin = Infinity, dMax = -Infinity;
|
||||
for (const p of poly) {
|
||||
const d = (p.x - center.x) * nrm.x + (p.y - center.y) * nrm.y;
|
||||
if (d < dMin) dMin = d;
|
||||
if (d > dMax) dMax = d;
|
||||
}
|
||||
|
||||
const segs: HatchSegment[] = [];
|
||||
// Raster so wählen, dass es den Bereich (inkl. Versatz) sicher deckt.
|
||||
const first = Math.floor((dMin - offsetM) / spacingM) - 1;
|
||||
const last = Math.ceil((dMax - offsetM) / spacingM) + 1;
|
||||
for (let k = first; k <= last; k++) {
|
||||
const d = offsetM + k * spacingM;
|
||||
const p0: Vec2 = { x: center.x + nrm.x * d, y: center.y + nrm.y * d };
|
||||
for (const s of clipLineToPolygon(p0, dir, poly)) segs.push(s);
|
||||
}
|
||||
return segs;
|
||||
}
|
||||
|
||||
/** 2D-Vektor um `rad` drehen (gegen den Uhrzeigersinn, Modell-Konvention). */
|
||||
function rotate(v: Vec2, rad: number): Vec2 {
|
||||
const c = Math.cos(rad), s = Math.sin(rad);
|
||||
return { x: v.x * c - v.y * s, y: v.x * s + v.y * c };
|
||||
return toSegs(core().hatch_line_family_flat(flat(poly), angleRad, spacingM, offsetM, anchor.x, anchor.y));
|
||||
}
|
||||
|
||||
/**
|
||||
* Faktor mm-Papier → px-Musterraum, identisch zum SVG-`dashArray` (dort
|
||||
* `dash·(1/0.13)`). Ein 0.13-mm-Strich entspricht ~1 px Kachelmaß; dividiert man
|
||||
* mit `PX_TO_M`, ergeben sich die Strichlängen in Modell-Metern (skalieren mit
|
||||
* dem Zoom wie die Kachel selbst — genau wie die SVG-Schraffur).
|
||||
*/
|
||||
export const DASH_MM_TO_M = (1 / 0.13) * PX_TO_M;
|
||||
|
||||
/**
|
||||
* Zerlegt zusammenhängende Läufe entlang eines Strichmusters (`dash`, in mm-
|
||||
* Papier) in die durchgezogenen Teil-Läufe. `dash` ist eine Sequenz
|
||||
* [an, aus, an, …]; ungerade Längen werden (wie SVG/Canvas) verdoppelt. Leeres/
|
||||
* ungültiges Muster → Läufe unverändert (durchgezogen). Die Phase läuft ENTLANG
|
||||
* DES GESAMTEN LAUFS durch (über Stützpunkt-Ecken hinweg), sodass die Striche
|
||||
* einer gekrümmten Musterlinie (Dämmungswelle) gleichmäßig und ecken-übergreifend
|
||||
* verteilt sind. Jedes „an"-Stück wird als eigener (kurzer) Lauf ausgegeben und
|
||||
* kann selbst über mehrere Stützpunkt-Segmente reichen.
|
||||
* Zerlegt zusammenhängende Läufe entlang eines Strichmusters (`dash` in mm-Papier, [an, aus, …];
|
||||
* ungerade Längen werden verdoppelt). Die Phase läuft über Stützpunkte hinweg durch. Leeres/
|
||||
* ungültiges Muster → Läufe unverändert.
|
||||
*/
|
||||
export function applyDashRuns(runs: HatchRun[], dash: number[] | null): HatchRun[] {
|
||||
if (!dash || dash.length === 0) return runs;
|
||||
// Musterlängen in Meter; nicht-positive/ungültige Werte verwerfen.
|
||||
const pat = dash.map((d) => Math.max(0, d) * DASH_MM_TO_M).filter((d) => d > 0);
|
||||
if (pat.length === 0) return runs;
|
||||
// Ungerade Länge → verdoppeln (Standard-Dash-Semantik).
|
||||
const cycle = pat.length % 2 === 0 ? pat : pat.concat(pat);
|
||||
const total = cycle.reduce((s, d) => s + d, 0);
|
||||
if (total <= 1e-9) return runs;
|
||||
|
||||
const out: HatchRun[] = [];
|
||||
for (const run of runs) {
|
||||
if (run.length < 2) continue;
|
||||
// Bogenlänge je Stützpunkt vorab, um Dash-Positionen auf Segmente abzubilden.
|
||||
let idx = 0; // gerade Index = „an", ungerade = „aus"
|
||||
let dashLeft = cycle[0]; // verbleibende Länge im aktuellen Dash-Zustand
|
||||
let on = true;
|
||||
let piece: Vec2[] | null = [run[0]]; // aktuell offenes „an"-Stück
|
||||
|
||||
const flush = () => {
|
||||
if (piece && piece.length >= 2) out.push(piece);
|
||||
piece = null;
|
||||
};
|
||||
|
||||
for (let i = 0; i + 1 < run.length; i++) {
|
||||
let a = run[i];
|
||||
const b = run[i + 1];
|
||||
let segLen = Math.hypot(b.x - a.x, b.y - a.y);
|
||||
if (segLen < 1e-12) continue;
|
||||
let ux = (b.x - a.x) / segLen, uy = (b.y - a.y) / segLen;
|
||||
// Segment ggf. an Dash-Grenzen zerschneiden.
|
||||
while (segLen > 1e-9) {
|
||||
const step = Math.min(segLen, dashLeft);
|
||||
const mid: Vec2 = { x: a.x + ux * step, y: a.y + uy * step };
|
||||
if (on) {
|
||||
if (!piece) piece = [a];
|
||||
piece.push(mid);
|
||||
}
|
||||
// Vorrücken.
|
||||
a = mid;
|
||||
segLen -= step;
|
||||
dashLeft -= step;
|
||||
if (dashLeft <= 1e-9) {
|
||||
// Dash-Zustand wechseln.
|
||||
if (on) flush();
|
||||
on = !on;
|
||||
idx++;
|
||||
dashLeft = cycle[idx % cycle.length];
|
||||
if (on) piece = [a]; // neues „an"-Stück beginnt hier
|
||||
}
|
||||
}
|
||||
}
|
||||
flush();
|
||||
}
|
||||
return out;
|
||||
return toRuns(core().dash_runs_flat(runsFlat(runs), Float64Array.from(dash)));
|
||||
}
|
||||
|
||||
/**
|
||||
* SVG-`rotate(angleDeg)` (im Uhrzeigersinn, Bildschirm-Y nach unten) → Winkel im
|
||||
* MODELL-Raum (gegen den Uhrzeigersinn, Modell-Y nach oben). Da die Bildschirm-
|
||||
* Abbildung Y spiegelt (`sy=-my`), kehrt sich der Drehsinn um: eine im Bildschirm
|
||||
* um +angle (CW) gedrehte Musterrichtung entspricht im Modell −angle relativ zur
|
||||
* gewählten Basisrichtung.
|
||||
*/
|
||||
function toModelAngleRad(screenDeg: number): number {
|
||||
return (-screenDeg * Math.PI) / 180;
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut die Schraffur eines Polygons als zusammenhängende Läufe ({@link HatchRun},
|
||||
* Modell-Meter). Bildet die SVG-`<pattern>`-Geometrie 1:1 nach:
|
||||
* • diagonal — eine Schar; SVG-Kachel 8·scale px mit senkrechter Musterlinie
|
||||
* (x-konstant), gedreht um `angle`. Abstand = 8·scale px. Jede
|
||||
* Musterlinie ist ein gerader 2-Punkt-Lauf.
|
||||
* • crosshatch — zwei Scharen (90° versetzt), gleicher Abstand.
|
||||
* • insulation — weiche Wellenlinie, Kachel 14×10·scale px, gedreht um `angle`;
|
||||
* als DURCHGEHENDE Polylinie tesselliert und in kontinuierliche
|
||||
* Läufe geclippt (glatte gehrte Übergänge statt Butt-Cap-Stufen).
|
||||
* • solid/none — keine Linien (Vollfüllung/Umriss übernimmt der Aufrufer).
|
||||
*
|
||||
* Skala 0/negativ wird auf 1 geklemmt (kein Division-durch-Null, keine leere
|
||||
* Kachel), damit degeneriert konfigurierte Hatches trotzdem sichtbar bleiben.
|
||||
* Schraffur eines Polygons als zusammenhängende Läufe (Modell-Meter): diagonal (eine Schar),
|
||||
* crosshatch (zwei Scharen), insulation (Welle), custom (Motiv je Musterlinie), Random-Untermodus
|
||||
* (gestreute Striche); solid/none sowie Bild/Verlauf liefern keine Linien-Geometrie des Musters.
|
||||
*/
|
||||
export function buildHatchRuns(poly: Vec2[], hatch: HatchRender): HatchRun[] {
|
||||
if (poly.length < 3) return [];
|
||||
const pattern = hatch.pattern;
|
||||
if (pattern === 'none' || pattern === 'solid') return [];
|
||||
|
||||
const scale = hatch.scale > 1e-6 ? hatch.scale : 1;
|
||||
|
||||
// Random-Vektor-Untermodus (Kies/Splitt): kurze, deterministisch gestreute
|
||||
// Striche statt der regelmäßigen Parallel-/Kreuzschar. Bild-/Verlauf-
|
||||
// Schraffuren (kind==="image"/"gradient") werden hier NICHT als Vektorlinien
|
||||
// erzeugt — sie fallen im Aufrufer auf eine neutrale Füllung zurück
|
||||
// (RScene/GL kennen weder Textur noch echten Farbverlauf).
|
||||
if (hatch.kind !== 'image' && hatch.kind !== 'gradient' && hatch.lines === 'random') {
|
||||
return buildRandomHatchRuns(poly, hatch, scale);
|
||||
}
|
||||
|
||||
if (pattern === 'insulation') {
|
||||
return insulationRuns(poly, hatch, scale);
|
||||
}
|
||||
|
||||
// diagonal / crosshatch: parallele Geradenscharen.
|
||||
// Die SVG-Kachel ist 8·scale px; die Musterlinie läuft senkrecht (y-Achse der
|
||||
// Kachel), Abstand also 8·scale px in x. In Metern: (8·scale)/PX_PER_M.
|
||||
const spacingM = 8 * scale * PX_TO_M;
|
||||
|
||||
// Kachel-Basisrichtung: die Linie läuft in der SVG-Kachel entlang +Y
|
||||
// (Bildschirm, nach unten). Im Modell (Y gespiegelt) entspricht das (0,-1).
|
||||
// Zusätzlich um `angle` (SVG-CW) gedreht → Modell-CCW um −angle.
|
||||
const rot = toModelAngleRad(hatch.angle);
|
||||
const dir1 = rotate({ x: 0, y: -1 }, rot);
|
||||
const a1 = Math.atan2(dir1.y, dir1.x);
|
||||
// Gerade Musterlinien → 2-Punkt-Läufe (visuell identisch zu Butt-Cap-Segmenten).
|
||||
// „custom" mit gesetztem Motiv: jede Musterlinie wird per `motifPoints` entlang
|
||||
// ihrer eigenen Länge tesselliert (Papier-mm → Modell-Meter über dieselbe
|
||||
// Kopplung wie bei Linien-Motiven, DASH_MM_TO_M, zusätzlich mit `scale`
|
||||
// verknüpft — konsistent zur Zeilenabstand-Formel oben). Ohne Motiv (frisch
|
||||
// angelegter Hatch) fällt „custom" auf gerade Linien zurück (kein Absturz).
|
||||
const anchor = hatch.origin ?? { x: 0, y: 0 };
|
||||
const runs: HatchRun[] = hatchLineFamily(poly, a1, spacingM, 0, anchor).map((s) =>
|
||||
pattern === 'custom' && hatch.motif
|
||||
? motifPoints(s.a, s.b, hatch.motif, scale * DASH_MM_TO_M)
|
||||
: [s.a, s.b],
|
||||
);
|
||||
|
||||
if (pattern === 'crosshatch') {
|
||||
// Zweite Schar: die SVG-Kachel trägt zusätzlich eine horizontale Linie
|
||||
// (x-Achse der Kachel) → 90° zur ersten, gleicher Abstand.
|
||||
for (const s of hatchLineFamily(poly, a1 + Math.PI / 2, spacingM, 0, anchor)) runs.push([s.a, s.b]);
|
||||
}
|
||||
return runs;
|
||||
if (poly.length < 3 || hatch.pattern === 'none' || hatch.pattern === 'solid') return [];
|
||||
return toRuns(core().hatch_runs_flat(flat(poly), encodeHatch(hatch)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Dämmungs-Schraffur (Wellenlinie): die SVG-Kachel ist 14×10·scale px und trägt
|
||||
* pro Kachel eine weiche Bézier-Welle. Wir bilden sie als Scharwellen nach: eine
|
||||
* Schar paralleler „Musterachsen" im Abstand der Kachelhöhe (10·scale px), auf
|
||||
* jeder Achse eine tessellierte Sinuswelle mit Wellenlänge = Kachelbreite
|
||||
* (14·scale px) und weicher Amplitude. Jede Wellen-Polylinie wird als
|
||||
* DURCHGEHENDER Zug aufs Polygon geclippt ({@link clipPolylineToPolygon}), sodass
|
||||
* benachbarte Wellen-Stützpunkte in EINEM Lauf verbunden bleiben. Der Compiler
|
||||
* strokt den Lauf als gehrten Streifen → glatte, spitzenfreie Welle. Die Welle
|
||||
* endet exakt an den Polygonkanten (even-odd-Clipping, konkav-fähig).
|
||||
*/
|
||||
function insulationRuns(poly: Vec2[], hatch: HatchRender, scale: number): HatchRun[] {
|
||||
const rot = toModelAngleRad(hatch.angle);
|
||||
|
||||
// Muster-Parameter in Metern (aus den SVG-px-Werten der Kachel).
|
||||
const wavelength = 14 * scale * PX_TO_M; // Kachelbreite
|
||||
const rowGap = 10 * scale * PX_TO_M; // Kachelhöhe → Zeilenabstand
|
||||
|
||||
// Lokales Muster-Koordinatensystem: u entlang der Welle, v quer (Zeilen).
|
||||
// ANKER = MODELL-URSPRUNG, wie beim SVG-`userSpaceOnUse`-Pattern (siehe
|
||||
// hatchLineFamily): so liegen Wellen-Phase UND Zeilenraster deckungsgleich
|
||||
// zum SVG-Referenzpfad und über alle Polygone hinweg in EINEM Gitter.
|
||||
const uDir = rotate({ x: 1, y: 0 }, rot);
|
||||
const vDir = rotate({ x: 0, y: 1 }, rot);
|
||||
|
||||
// Abdeckungsbereich in (u,v) über die Polygon-Ecken bestimmen.
|
||||
let uMin = Infinity, uMax = -Infinity, vMin = Infinity, vMax = -Infinity;
|
||||
for (const p of poly) {
|
||||
const u = p.x * uDir.x + p.y * uDir.y;
|
||||
const v = p.x * vDir.x + p.y * vDir.y;
|
||||
if (u < uMin) uMin = u;
|
||||
if (u > uMax) uMax = u;
|
||||
if (v < vMin) vMin = v;
|
||||
if (v > vMax) vMax = v;
|
||||
}
|
||||
if (!(uMax > uMin) || !(vMax > vMin)) return [];
|
||||
|
||||
// Feinheit der Wellen-Tessellierung (Segmente je Wellenlänge). Höher als beim
|
||||
// segmentweisen Ansatz, da die Läufe jetzt glatt gehrt werden → weichere Welle.
|
||||
const STEPS = 22;
|
||||
const du = wavelength / STEPS;
|
||||
|
||||
const runs: HatchRun[] = [];
|
||||
const toWorld = (u: number, v: number): Vec2 => ({
|
||||
x: uDir.x * u + vDir.x * v,
|
||||
y: uDir.y * u + vDir.y * v,
|
||||
});
|
||||
|
||||
// Die Wellen-Mittellinie liegt in der SVG-Kachel bei y = h/2 (my = 5·scale),
|
||||
// die Zeilen also auf HALBEN Rasterlinien: v = (r + 0.5)·rowGap.
|
||||
const firstRow = Math.floor(vMin / rowGap - 0.5) - 1;
|
||||
const lastRow = Math.ceil(vMax / rowGap - 0.5) + 1;
|
||||
const uStart = Math.floor((uMin - wavelength) / du) * du;
|
||||
const uEnd = uMax + wavelength;
|
||||
|
||||
// EXAKT die SVG-Wellenform: die Kachel zeichnet zwei quadratische Béziers
|
||||
// `M0 5s Q 3.5s -1s 7s 5s Q 10.5s 11s 14s 5s`. Deren x(t) ist LINEAR (7s·t je
|
||||
// Halbwelle), die Auslenkung eine Parabel ±12s·t(1−t) (Scheitel ±3s) — also
|
||||
// Halbwellen-Parabeln statt einer Sinuskurve (flachere Kämme, steilere
|
||||
// Nulldurchgänge). Erste Halbwelle: Kamm nach OBEN (Bildschirm) = +v (Modell).
|
||||
const half = wavelength / 2;
|
||||
const waveAt = (u: number): number => {
|
||||
const phase = ((u % wavelength) + wavelength) % wavelength;
|
||||
const t = (phase % half) / half;
|
||||
const mag = 12 * scale * PX_TO_M * t * (1 - t);
|
||||
return phase < half ? mag : -mag;
|
||||
};
|
||||
|
||||
for (let r = firstRow; r <= lastRow; r++) {
|
||||
const vBase = (r + 0.5) * rowGap;
|
||||
// Ganze Welle als EINE Polylinie tessellieren, dann DURCHGEHEND clippen.
|
||||
// Das u-Raster ist an Vielfachen von du = λ/22 ausgerichtet → die Null-
|
||||
// durchgänge (Vielfache von λ/2 = 11·du) liegen exakt auf Stützpunkten.
|
||||
const wavePts: Vec2[] = [];
|
||||
for (let u = uStart; u <= uEnd + 1e-9; u += du) {
|
||||
wavePts.push(toWorld(u, vBase + waveAt(u)));
|
||||
}
|
||||
for (const run of clipPolylineToPolygon(wavePts, poly)) runs.push(run);
|
||||
}
|
||||
return runs;
|
||||
}
|
||||
|
||||
// ── Random-Vektor-Schraffur (deterministisch) ────────────────────────────────
|
||||
|
||||
/**
|
||||
* Deterministischer 32-bit-PRNG (mulberry32). Gleicher Seed ⇒ gleiche Folge —
|
||||
* KEIN `Math.random()`: die Random-Schraffur muss über Re-Renders/Print
|
||||
* reproduzierbar sein (sonst flackert der Splitt und der Druck ist nicht
|
||||
* deterministisch).
|
||||
*/
|
||||
function mulberry32(seed: number): () => number {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
a |= 0;
|
||||
a = (a + 0x6d2b79f5) | 0;
|
||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Faltet mehrere Fließkomma-Kennwerte zu einem stabilen 32-bit-Seed. Die Werte
|
||||
* werden gequantelt (·1000, gerundet), damit numerisches Rauschen den Seed nicht
|
||||
* verschiebt — gleiche Fläche/gleiche Hatch-Parameter ⇒ gleicher Seed ⇒ gleiche
|
||||
* Streuung.
|
||||
*/
|
||||
function hashSeed(...vals: number[]): number {
|
||||
let h = 0x811c9dc5;
|
||||
for (const v of vals) {
|
||||
const q = Math.round(v * 1000) | 0;
|
||||
h ^= q & 0xffff;
|
||||
h = Math.imul(h, 0x01000193);
|
||||
h ^= (q >>> 16) & 0xffff;
|
||||
h = Math.imul(h, 0x01000193);
|
||||
}
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministischer Hash EINER Modellraum-Zelle (`ix`,`iy` = absolute Zell-Indizes
|
||||
* `floor(x/cell)`/`floor(y/cell)`) plus `seed`. Ergebnis ist ein 32-bit-Seed für
|
||||
* {@link mulberry32}. Zentraler Baustein der modellraum-stabilen Streuung: der
|
||||
* Zell-Inhalt hängt NUR an den absoluten Zell-Indizes + Seed — NICHT an der
|
||||
* Bounding-Box der Fläche. Dadurch bleibt ein Strich beim Vergrößern/Verschieben
|
||||
* der Fläche an derselben Zelle „verankert".
|
||||
*/
|
||||
function hashCell(ix: number, iy: number, seed: number): number {
|
||||
let h = (0x811c9dc5 ^ (seed | 0)) >>> 0;
|
||||
h = Math.imul(h ^ (ix | 0), 0x01000193);
|
||||
h = Math.imul(h ^ (iy | 0), 0x01000193);
|
||||
h ^= h >>> 15;
|
||||
h = Math.imul(h, 0x2c1b3c6d);
|
||||
h ^= h >>> 12;
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Streut kurze Striche gleichmäßig-zufällig (aber DETERMINISTISCH) über ein
|
||||
* Polygon — MODELLRAUM-STABIL: Der Modellraum wird in ein regelmäßiges Gitter der
|
||||
* Zellgröße `cell` gekachelt (absolutes Gitter, Ursprung = Modell-Ursprung). Über
|
||||
* die Zellen, die die Polygon-Bounding-Box überdecken, wird iteriert (nur aus
|
||||
* Performance-Gründen); PRO Zelle liefert {@link hashCell}(ix,iy,seed) einen festen
|
||||
* PRNG, aus dem Lage (innerhalb der Zelle), Orientierung (um `baseAngleRad` ± π)
|
||||
* und Länge folgen. Jeder Strich wird aufs Polygon geclippt
|
||||
* ({@link clipSegmentToPolygon}, konkav-fähig).
|
||||
*
|
||||
* Folge: Beim Vergrößern der Fläche bleiben bestehende Striche STEHEN (gleiche
|
||||
* Zelle ⇒ gleicher Strich), am Rand kommen neue dazu; die Dichte (Striche pro
|
||||
* Fläche) bleibt konstant; beim Verschieben wandert nichts. „Neu würfeln" (neuer
|
||||
* `seed`) verschiebt das ganze Feld. Einheiten-agnostisch (Aufrufer gibt `cell`/
|
||||
* `strokeLen` in Modell-Metern bzw. Papier-mm). Ausgabe = 2-Punkt-Läufe.
|
||||
* Streut kurze Striche deterministisch und MODELLRAUM-STABIL über ein Polygon (eine Zelle des
|
||||
* absoluten Gitters je Strich, Lage/Winkel/Länge aus `hash(ix, iy, seed)`), aufs Polygon geclippt.
|
||||
*/
|
||||
export function scatterStrokes(
|
||||
poly: Vec2[],
|
||||
@@ -592,132 +157,32 @@ export function scatterStrokes(
|
||||
lenMin?: number,
|
||||
lenMax?: number,
|
||||
): HatchRun[] {
|
||||
if (poly.length < 3 || cell <= 1e-9 || strokeLen <= 1e-9) return [];
|
||||
const bb = bbox(poly);
|
||||
if (!(bb.maxX > bb.minX) || !(bb.maxY > bb.minY)) return [];
|
||||
|
||||
// Absolute Zell-Indizes, die die Bounding-Box überdecken (Modell-Ursprung als
|
||||
// Gitter-Anker → verschiebe-invariant).
|
||||
let eff = cell;
|
||||
let ix0 = Math.floor(bb.minX / eff);
|
||||
let ix1 = Math.floor(bb.maxX / eff);
|
||||
let iy0 = Math.floor(bb.minY / eff);
|
||||
let iy1 = Math.floor(bb.maxY / eff);
|
||||
// Sicherheits-Cap gegen pathologisch große Flächen / winzige Zellen: Zellgröße
|
||||
// gröber machen, bis die Zellzahl unter dem Limit liegt (uniform, nur grober).
|
||||
const MAX_CELLS = 250000;
|
||||
let cells = (ix1 - ix0 + 1) * (iy1 - iy0 + 1);
|
||||
if (cells > MAX_CELLS) {
|
||||
eff = cell * Math.sqrt(cells / MAX_CELLS);
|
||||
ix0 = Math.floor(bb.minX / eff);
|
||||
ix1 = Math.floor(bb.maxX / eff);
|
||||
iy0 = Math.floor(bb.minY / eff);
|
||||
iy1 = Math.floor(bb.maxY / eff);
|
||||
}
|
||||
|
||||
// Explizite Längen-Spanne (falls gesetzt) validieren; sonst die scale-abhängige
|
||||
// Variation (±40 % um `strokeLen`) beibehalten.
|
||||
const hasRange =
|
||||
lenMin != null && lenMax != null && lenMin > 1e-9 && lenMax >= lenMin;
|
||||
|
||||
const runs: HatchRun[] = [];
|
||||
for (let iy = iy0; iy <= iy1; iy++) {
|
||||
for (let ix = ix0; ix <= ix1; ix++) {
|
||||
const rnd = mulberry32(hashCell(ix, iy, seed));
|
||||
// Strich-Mittelpunkt innerhalb der Zelle (absolutes Gitter).
|
||||
const cx = (ix + rnd()) * eff;
|
||||
const cy = (iy + rnd()) * eff;
|
||||
// Orientierung frei (± π um die Basisrichtung).
|
||||
const ang = baseAngleRad + (rnd() * 2 - 1) * Math.PI;
|
||||
// Länge: explizite Spanne [lenMin,lenMax] oder Default (±40 % um strokeLen).
|
||||
const len = hasRange
|
||||
? lenMin! + rnd() * (lenMax! - lenMin!)
|
||||
: strokeLen * (0.6 + 0.8 * rnd());
|
||||
const half = len * 0.5;
|
||||
const dx = Math.cos(ang) * half;
|
||||
const dy = Math.sin(ang) * half;
|
||||
const a: Vec2 = { x: cx - dx, y: cy - dy };
|
||||
const b: Vec2 = { x: cx + dx, y: cy + dy };
|
||||
for (const seg of clipSegmentToPolygon(a, b, poly)) runs.push([seg.a, seg.b]);
|
||||
}
|
||||
}
|
||||
return runs;
|
||||
return toRuns(
|
||||
core().scatter_strokes_flat(flat(poly), cell, baseAngleRad, seed, strokeLen, lenMin ?? NaN, lenMax ?? NaN),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Random-Vektor-Schraffur eines Polygons in Modell-Metern (Kies/Splitt). Dichte
|
||||
* und Strichlänge sind — wie die Parallelschar — an die Kachelgröße (`8·scale` px)
|
||||
* gekoppelt, damit `scale`/`density` die Streudichte steuern. Die Streuung ist
|
||||
* MODELLRAUM-STABIL (siehe {@link scatterStrokes}): der Seed hängt NUR an den
|
||||
* Muster-Parametern (Winkel/Scale/Dichte) plus dem expliziten `hatch.seed` — NICHT
|
||||
* an der Bounding-Box. Dadurch verankern sich die Striche im Modellraum; beim
|
||||
* Vergrößern der Fläche bleiben sie stehen und die Dichte bleibt konstant.
|
||||
* Random-Vektor-Schraffur eines Polygons (Kies/Splitt): Dichte und Strichlänge an die Kachel
|
||||
* (8·scale px) gekoppelt, Seed nur aus Muster-Parametern + `hatch.seed`.
|
||||
*/
|
||||
export function buildRandomHatchRuns(poly: Vec2[], hatch: HatchRender, scale?: number): HatchRun[] {
|
||||
const s = scale ?? (hatch.scale > 1e-6 ? hatch.scale : 1);
|
||||
// Dichte: Multiplikator auf den Grundabstand (>1 = dichter → kleinere Zelle).
|
||||
// Fehlt/ungültig ⇒ 1 ⇒ heutiges Verhalten.
|
||||
const density = hatch.density != null && hatch.density > 1e-6 ? hatch.density : 1;
|
||||
const cell = (8 * s * PX_TO_M) / density; // Meter, wie der Parallel-Schar-Abstand
|
||||
const strokeLen = cell * 1.1; // Default-Strich ~ Kachelmaß (wenn keine Längenspanne)
|
||||
// Fester Seed NUR aus Muster-Parametern + explizitem `hatch.seed` (KEINE bbox):
|
||||
// „Neu würfeln" (neuer seed) ⇒ anderes Feld, aber gleicher seed + gleiche
|
||||
// Muster-Parameter ⇒ identisches, modellraum-verankertes Feld über alle
|
||||
// Renderpfade — unabhängig von Lage/Größe der Fläche.
|
||||
const seed = hashSeed(hatch.angle, s, density, hatch.seed ?? 0);
|
||||
const base = toModelAngleRad(hatch.angle);
|
||||
// Explizite Längenspanne (mm-Papier → Modell-Meter, wie das Dash-Muster).
|
||||
const lenMin = hatch.lengthMin != null ? hatch.lengthMin * DASH_MM_TO_M : undefined;
|
||||
const lenMax = hatch.lengthMax != null ? hatch.lengthMax * DASH_MM_TO_M : undefined;
|
||||
return scatterStrokes(poly, cell, base, seed, strokeLen, lenMin, lenMax);
|
||||
return toRuns(core().random_hatch_runs_flat(flat(poly), encodeHatch(hatch), scale ?? NaN));
|
||||
}
|
||||
|
||||
// ── Zickzack-/Wellen-Linie ───────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Tesselliert die Strecke [a,b] zu einem Zickzack (Dreieckswelle) mit `amplitude`
|
||||
* (Ausschlag quer, Einheit wie a/b) und `wavelength` (Periodenlänge längs). Rein
|
||||
* geometrisch, einheiten-agnostisch: der Aufrufer übergibt amplitude/wavelength
|
||||
* in der Zielkoordinaten-Einheit. Die Auslenkung folgt dem Muster [0,+A,0,−A] je
|
||||
* Viertel-Wellenlänge; Start liegt auf der Achse, das Ende exakt auf `b`.
|
||||
* Zickzack (Dreieckswelle [0,+A,0,−A] je Viertel-Wellenlänge) entlang [a,b]; Einheiten wie
|
||||
* a/b. Start auf der Achse, Ende exakt auf `b`.
|
||||
*/
|
||||
export function zigzagPoints(a: Vec2, b: Vec2, amplitude: number, wavelength: number): Vec2[] {
|
||||
const dx = b.x - a.x;
|
||||
const dy = b.y - a.y;
|
||||
const L = Math.hypot(dx, dy);
|
||||
if (L < 1e-12 || wavelength <= 1e-9 || amplitude <= 0) return [a, b];
|
||||
const ux = dx / L;
|
||||
const uy = dy / L;
|
||||
const nx = -uy; // linke Normale (Ausschlagachse)
|
||||
const ny = ux;
|
||||
const quarter = wavelength / 4;
|
||||
const steps = Math.max(1, Math.round(L / quarter));
|
||||
const tri = [0, 1, 0, -1];
|
||||
const pts: Vec2[] = [];
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const t = Math.min(L, i * quarter);
|
||||
const off = amplitude * tri[i % 4];
|
||||
pts.push({ x: a.x + ux * t + nx * off, y: a.y + uy * t + ny * off });
|
||||
}
|
||||
const last = pts[pts.length - 1];
|
||||
if (Math.abs(last.x - b.x) > 1e-9 || Math.abs(last.y - b.y) > 1e-9) {
|
||||
pts.push({ x: b.x, y: b.y });
|
||||
}
|
||||
return pts;
|
||||
const f = core().zigzag_points_flat(a.x, a.y, b.x, b.y, amplitude, wavelength);
|
||||
return f.length ? toPts(f) : [a, b];
|
||||
}
|
||||
|
||||
/**
|
||||
* Kachelt ein frei gezeichnetes Motiv (offene Polylinie in einer Einheitszelle)
|
||||
* entlang der Strecke [a,b] und liefert die zusammenhängende Polylinie. Rein
|
||||
* geometrisch/einheiten-agnostisch (die Verallgemeinerung von {@link zigzagPoints}):
|
||||
* • `motif.points` sind die Stützpunkte der Zelle; `x` läuft 0..`motif.length`
|
||||
* ENTLANG der Linie (= Wiederhollänge), `y` = Versatz quer zur Linie (linke
|
||||
* Normale `n = (-u.y, u.x)`).
|
||||
* • `scale` skaliert Punkte UND Länge in die Zielkoordinaten-Einheit (z. B.
|
||||
* Papier-mm → Modell-Meter via `DASH_MM_TO_M`); der Print-SVG-Pfad übergibt 1.
|
||||
* Das Motiv wird alle `length·scale` wiederholt; am Segment-Ende exakt bei `L`
|
||||
* geclippt (letztes Segment interpoliert), sodass die Linie nicht über `b`
|
||||
* hinausläuft. Degeneriert (leeres Motiv, Länge 0, Nullstrecke) → `[a, b]`.
|
||||
* Kachelt ein frei gezeichnetes Motiv (`points` in der Einheitszelle: x entlang, y quer;
|
||||
* Wiederhollänge `length`, beides ·`scale`) entlang [a,b], am Ende exakt geclippt. Entartet →
|
||||
* `[a, b]`.
|
||||
*/
|
||||
export function motifPoints(
|
||||
a: Vec2,
|
||||
@@ -725,44 +190,6 @@ export function motifPoints(
|
||||
motif: { points: Vec2[]; length: number },
|
||||
scale = 1,
|
||||
): Vec2[] {
|
||||
const dx = b.x - a.x;
|
||||
const dy = b.y - a.y;
|
||||
const L = Math.hypot(dx, dy);
|
||||
const cell = motif.length * scale;
|
||||
if (L < 1e-12 || cell <= 1e-9 || motif.points.length < 2) return [a, b];
|
||||
const ux = dx / L;
|
||||
const uy = dy / L;
|
||||
const nx = -uy; // linke Normale (Ausschlagachse)
|
||||
const ny = ux;
|
||||
const toWorld = (ax: number, off: number): Vec2 => ({
|
||||
x: a.x + ux * ax + nx * off,
|
||||
y: a.y + uy * ax + ny * off,
|
||||
});
|
||||
|
||||
const out: Vec2[] = [];
|
||||
const reps = Math.ceil(L / cell) + 1;
|
||||
let last: { ax: number; off: number } | null = null;
|
||||
for (let r = 0; r < reps; r++) {
|
||||
const base = r * cell;
|
||||
for (let i = 0; i < motif.points.length; i++) {
|
||||
const p = motif.points[i];
|
||||
const ax = base + p.x * scale;
|
||||
const off = p.y * scale;
|
||||
// Naht-Duplikat (Zellenende r == Zellenanfang r+1) überspringen.
|
||||
if (last && Math.abs(ax - last.ax) < 1e-9 && Math.abs(off - last.off) < 1e-9) {
|
||||
continue;
|
||||
}
|
||||
if (ax > L + 1e-9) {
|
||||
// Letztes Segment am Segmentende clippen: last→p bei ax = L interpolieren.
|
||||
if (last && ax > last.ax + 1e-12 && L - last.ax > 1e-9) {
|
||||
const tt = (L - last.ax) / (ax - last.ax);
|
||||
out.push(toWorld(L, last.off + (off - last.off) * tt));
|
||||
}
|
||||
return out.length >= 2 ? out : [a, b];
|
||||
}
|
||||
out.push(toWorld(ax, off));
|
||||
last = { ax, off };
|
||||
}
|
||||
}
|
||||
return out.length >= 2 ? out : [a, b];
|
||||
const f = core().motif_points_flat(a.x, a.y, b.x, b.y, flat(motif.points), motif.length, scale);
|
||||
return f.length ? toPts(f) : [a, b];
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// Plan-Puffer [K3b]: TS kodiert, Rust liest und schreibt neu — Hin und zurück muss jede Zahl
|
||||
// erhalten (je Primitiv-Typ), fremde Versionen werden sauber abgelehnt.
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { encodePlanBuf, encodeHatch, parseColor, PLAN_BUF_MAGIC, PLAN_BUF_VERSION } from "./planBuf";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import type { HatchRender, Primitive } from "./generatePlan";
|
||||
|
||||
const hatch: HatchRender = {
|
||||
pattern: "custom",
|
||||
scale: 2,
|
||||
angle: 30,
|
||||
color: "#336699",
|
||||
lineWeight: 0.13,
|
||||
dash: [0.35, 0.3],
|
||||
kind: "vector",
|
||||
lines: "random",
|
||||
origin: { x: 1, y: -2 },
|
||||
seed: 7,
|
||||
density: 1.5,
|
||||
lengthMin: 0.5,
|
||||
lengthMax: 2,
|
||||
motif: { points: [{ x: 0, y: 0 }, { x: 1, y: 1 }], length: 2 },
|
||||
};
|
||||
|
||||
const dash = [1, 0.5];
|
||||
|
||||
const PRIMS: Record<string, Primitive> = {
|
||||
polygon: {
|
||||
kind: "polygon",
|
||||
pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 1, y: 1.5 }],
|
||||
fill: "#ffcc00",
|
||||
stroke: "rgba(10, 20, 30, 0.5)",
|
||||
strokeWidthMm: 0.35,
|
||||
hatch,
|
||||
greyed: true,
|
||||
opacity: 0.4,
|
||||
noStrokeEdges: [0, 2],
|
||||
wallId: "w1",
|
||||
},
|
||||
line: { kind: "line", a: { x: 0, y: 0 }, b: { x: 3, y: 4 }, cls: "c", weightMm: 0.25, color: "#000", dash, drawingId: "d" },
|
||||
zigzag: { kind: "line", a: { x: 0, y: 0 }, b: { x: 3, y: 4 }, cls: "c", weightMm: 0.25, zigzag: { amplitude: 1, wavelength: 4 } },
|
||||
motif: {
|
||||
kind: "line",
|
||||
a: { x: 0, y: 0 },
|
||||
b: { x: 3, y: 4 },
|
||||
cls: "c",
|
||||
weightMm: undefined as unknown as number,
|
||||
motif: { points: [{ x: 0, y: 0 }, { x: 2, y: 1 }], length: 4 },
|
||||
},
|
||||
arc: { kind: "arc", center: { x: 0, y: 0 }, from: { x: 1, y: 0 }, to: { x: 0, y: 1 }, r: 1, cls: "c", weightMm: 0.18, opacity: 0.5 },
|
||||
drawingCircle: { kind: "drawingCircle", center: { x: 5, y: 5 }, r: 2, fill: "none", stroke: "#123", weightMm: 0.18, dash: [2] },
|
||||
drawingArc: { kind: "drawingArc", center: { x: 5, y: 5 }, r: 2, a0: 0, a1: 3, stroke: "#123", weightMm: 0.5, greyed: true },
|
||||
text: { kind: "drawingText", at: { x: 0, y: 0 }, text: "x", heightM: 1, angle: 0, color: "#000" },
|
||||
image: { kind: "drawingImage", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, src: "", opacity: 1 },
|
||||
};
|
||||
|
||||
/** Gleichheit Zahl für Zahl (NaN = NaN, −0 ≠ +0). */
|
||||
function sameBits(a: Float64Array, b: Float64Array): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) if (!Object.is(a[i], b[i])) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
describe("Plan-Puffer", () => {
|
||||
for (const [name, prim] of Object.entries(PRIMS)) {
|
||||
it(`Hin und zurück: ${name}`, () => {
|
||||
const buf = encodePlanBuf([prim]);
|
||||
expect(buf[0]).toBe(PLAN_BUF_MAGIC);
|
||||
expect(buf[1]).toBe(PLAN_BUF_VERSION);
|
||||
expect(buf[4]).toBe(1);
|
||||
expect(sameBits(core().plan_buf_recode(buf), buf)).toBe(true);
|
||||
});
|
||||
}
|
||||
|
||||
it("Hin und zurück: alle Typen gemischt, ein Eintrag je Primitiv", () => {
|
||||
const prims = Object.values(PRIMS);
|
||||
const buf = encodePlanBuf(prims);
|
||||
expect(buf[4]).toBe(prims.length);
|
||||
expect(sameBits(core().plan_buf_recode(buf), buf)).toBe(true);
|
||||
});
|
||||
|
||||
it("Texte und Bilder sind Platzhalter (nur der Typ-Eintrag 0)", () => {
|
||||
expect(Array.from(encodePlanBuf([PRIMS.text, PRIMS.image]))).toEqual([PLAN_BUF_MAGIC, PLAN_BUF_VERSION, 0, 0, 2, 0, 0]);
|
||||
});
|
||||
|
||||
it("Farben werden einmal geparst und geteilt, ungültige ergeben −1", () => {
|
||||
const a = { ...PRIMS.line, color: "#ff0000" } as Primitive;
|
||||
const b = { ...PRIMS.line, color: "nonsense" } as Primitive;
|
||||
const buf = encodePlanBuf([a, a, b]);
|
||||
expect(buf[2]).toBe(1);
|
||||
expect(Array.from(buf.subarray(5, 9))).toEqual(parseColor("#ff0000"));
|
||||
});
|
||||
|
||||
it("Linienzug-Flag: nur gleiches Element, gleicher Stil und lückenlos", () => {
|
||||
const seg = (ax: number, bx: number, extra: object = {}): Primitive =>
|
||||
({ kind: "line", a: { x: ax, y: 0 }, b: { x: bx, y: 0 }, cls: "c", weightMm: 0.18, color: "#000", drawingId: "d", ...extra }) as Primitive;
|
||||
const flagsOf = (prims: Primitive[]) => {
|
||||
const buf = encodePlanBuf(prims);
|
||||
const out: number[] = [];
|
||||
let i = 5 + buf[2] * 4;
|
||||
for (let k = 0; k < prims.length; k++) {
|
||||
out.push(buf[i + 1] & 4);
|
||||
i += 9 + 1 + buf[i + 9];
|
||||
}
|
||||
return out;
|
||||
};
|
||||
expect(flagsOf([seg(0, 1), seg(1, 2), seg(2, 3)])).toEqual([0, 4, 4]);
|
||||
expect(flagsOf([seg(0, 1), seg(1.5, 2)])).toEqual([0, 0]);
|
||||
expect(flagsOf([seg(0, 1), seg(1, 2, { drawingId: "e" })])).toEqual([0, 0]);
|
||||
expect(flagsOf([seg(0, 1), seg(1, 2, { weightMm: 0.5 })])).toEqual([0, 0]);
|
||||
expect(flagsOf([seg(0, 1), seg(1, 2, { greyed: false })])).toEqual([0, 0]);
|
||||
expect(flagsOf([seg(0, 1, { dash: [1] }), seg(1, 2, { dash: [1] })])).toEqual([0, 0]);
|
||||
});
|
||||
|
||||
it("fremde Version oder kaputter Puffer → leeres Ergebnis, kein Absturz", () => {
|
||||
const buf = encodePlanBuf(Object.values(PRIMS));
|
||||
const wrong = buf.slice();
|
||||
wrong[1] = PLAN_BUF_VERSION + 1;
|
||||
expect(core().plan_buf_recode(wrong).length).toBe(0);
|
||||
expect(core().gpu_compile_flat(wrong, 90, true).length).toBe(0);
|
||||
expect(core().plan_buf_recode(buf.subarray(0, buf.length - 3)).length).toBe(0);
|
||||
expect(core().gpu_compile_flat(new Float64Array([1, 2, 3]), 90, false).length).toBe(0);
|
||||
// Danach arbeitet der Kern normal weiter.
|
||||
expect(sameBits(core().plan_buf_recode(buf), buf)).toBe(true);
|
||||
});
|
||||
|
||||
it("Einzel-Schraffur hat dasselbe Format wie ein Hatch-Eintrag", () => {
|
||||
const h = encodeHatch(hatch);
|
||||
const buf = encodePlanBuf([PRIMS.polygon]);
|
||||
const colors = buf[2];
|
||||
// Im Plan-Puffer steht der Farbindex statt −1.
|
||||
const inPlan = buf.slice(5 + colors * 4, 5 + colors * 4 + h.length);
|
||||
expect(inPlan[5]).toBeGreaterThanOrEqual(0);
|
||||
inPlan[5] = -1;
|
||||
expect(sameBits(inPlan, h)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,356 @@
|
||||
/**
|
||||
* Plan-Puffer ([K3b]): kompakte Binärkodierung der zeichnungsrelevanten Plan-Primitive als
|
||||
* flacher `Float64Array`. TS schreibt ihn vorerst aus `Plan.primitives`, der Rust-Kern liest ihn
|
||||
* (`src-tauri/core/src/plan_buf.rs`, dort dieselbe Formatbeschreibung) — heute für die GPU-
|
||||
* Kompilierung (`glPlan/glPlanCompile.ts`), ab [K3a] erzeugt Rust ihn direkt.
|
||||
*
|
||||
* ```text
|
||||
* Kopf [MAGIC, VERSION, nColors, nHatches, nPrims]
|
||||
* MAGIC = 0x504C4231 ("PLB1"), VERSION = 1 — Rust lehnt fremde Werte ab (leeres Ergebnis)
|
||||
* Farben nColors × [r, g, b, a] (0..1, hier aus dem Farbtext geparst)
|
||||
* Schraffuren nHatches × Hatch
|
||||
* Primitive nPrims × Prim (genau ein Eintrag je Primitiv → Indizes bleiben gleich)
|
||||
*
|
||||
* Hatch [pattern, kind, flags, scale, angle, colorIdx, lineWeight, originX, originY,
|
||||
* seed, density, lengthMin, lengthMax, nDash, dash…, (Motiv: length, nPts, x,y…)]
|
||||
* pattern 0 none · 1 solid · 2 diagonal (auch unbekannt) · 3 crosshatch · 4 insulation · 5 custom
|
||||
* kind 0 vector · 1 image · 2 gradient (Bild/Verlauf: GPU fällt auf die Füllung zurück)
|
||||
* flags 1 random · 2 origin · 4 seed · 8 density · 16 lengthMin · 32 lengthMax · 64 Motiv
|
||||
* (Felder ohne Flag stehen auf 0 und gelten als „nicht gesetzt")
|
||||
*
|
||||
* Prim [tag, flags, …] flags 1 greyed · 2 opacity gesetzt · 4 setzt den Linienzug der
|
||||
* vorigen Linie fort · 8 Zickzack · 16 Motiv
|
||||
* 0 Platzhalter [0] (Text, Bild … — zeichnet die GPU nicht)
|
||||
* 1 polygon [1, flags, fillIdx, strokeIdx, strokeWidthMm, hatchIdx, opacity,
|
||||
* nPts, x,y…, nNoStroke, kante…]
|
||||
* 2 line [2, flags, colorIdx, weightMm, opacity, ax, ay, bx, by, nDash, dash…,
|
||||
* (Zickzack: amplitude, wavelength), (Motiv: length, nPts, x,y…)]
|
||||
* 3 arc [3, flags, colorIdx, weightMm, opacity, cx, cy, fromX, fromY, toX, toY, r,
|
||||
* nDash, dash…]
|
||||
* 4 drawingCircle [4, flags, fillIdx, strokeIdx, weightMm, opacity, cx, cy, r, nDash, dash…]
|
||||
* 5 drawingArc [5, flags, strokeIdx, weightMm, opacity, cx, cy, r, a0, a1, nDash, dash…]
|
||||
* ```
|
||||
* Farb-/Schraffur-Index −1 = keine (Farbtext ungültig, "none", fehlende Schraffur). Längen in
|
||||
* Metern, Strichstärken/Strichmuster/Zickzack/Motiv in Papier-mm, Winkel von drawingArc in
|
||||
* Bogenmass, Schraffur-Winkel in Grad (SVG-Drehsinn). Ohne opacity-Flag steht 1 im Feld; fehlende
|
||||
* Zahlen (`undefined`) werden NaN, der Verbraucher nimmt dann wie bisher seinen Standard.
|
||||
* Flag 4 (Linienzug): gleiches Element (`drawingId`), gleiche Farbe/Stärke/greyed/opacity/
|
||||
* Strichmuster (Referenz) und Anfang = Ende der vorigen Linie — dann zeichnet die GPU die
|
||||
* Einzelsegmente als EINEN Zug (zwei echte Kappen statt 2N). Pick-IDs stehen NICHT im Puffer
|
||||
* (Picken bleibt vorerst TS).
|
||||
*/
|
||||
|
||||
import type { HatchRender, Primitive } from "./generatePlan";
|
||||
import type { Vec2 } from "../model/types";
|
||||
|
||||
export const PLAN_BUF_MAGIC = 0x504c4231;
|
||||
export const PLAN_BUF_VERSION = 1;
|
||||
|
||||
/** RGBA-Farbe, Komponenten in [0,1]. */
|
||||
export type PlanRgba = [number, number, number, number];
|
||||
|
||||
const FLAG_GREYED = 1;
|
||||
const FLAG_OPACITY = 2;
|
||||
const FLAG_CHAIN = 4;
|
||||
const FLAG_ZIGZAG = 8;
|
||||
const FLAG_MOTIF = 16;
|
||||
|
||||
/**
|
||||
* Farbe → RGBA[0..1]; ungültig/"none"/"transparent" → null.
|
||||
* Unterstützt "#rgb", "#rrggbb", "#rrggbbaa" und "rgb()/rgba()".
|
||||
*/
|
||||
export function parseColor(hex: string | undefined): PlanRgba | null {
|
||||
if (!hex) return null;
|
||||
const s = hex.trim().toLowerCase();
|
||||
if (s === "none" || s === "transparent") return null;
|
||||
|
||||
if (s.startsWith("rgb")) {
|
||||
const m = s.match(/[\d.]+/g);
|
||||
if (!m || m.length < 3) return null;
|
||||
const a = m.length >= 4 ? parseFloat(m[3]) : 1;
|
||||
return [+m[0] / 255, +m[1] / 255, +m[2] / 255, a > 1 ? a / 255 : a];
|
||||
}
|
||||
|
||||
let h = s[0] === "#" ? s.slice(1) : s;
|
||||
if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];
|
||||
if (h.length !== 6 && h.length !== 8) return null;
|
||||
const r = parseInt(h.slice(0, 2), 16);
|
||||
const g = parseInt(h.slice(2, 4), 16);
|
||||
const b = parseInt(h.slice(4, 6), 16);
|
||||
const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1;
|
||||
if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
|
||||
return [r / 255, g / 255, b / 255, a];
|
||||
}
|
||||
|
||||
/** Wachsender `Float64Array`-Schreiber. */
|
||||
class F64Writer {
|
||||
buf = new Float64Array(1024);
|
||||
length = 0;
|
||||
private grow(need: number): void {
|
||||
let cap = this.buf.length * 2;
|
||||
while (cap < need) cap *= 2;
|
||||
const next = new Float64Array(cap);
|
||||
next.set(this.buf.subarray(0, this.length));
|
||||
this.buf = next;
|
||||
}
|
||||
push(v: number): void {
|
||||
if (this.length + 1 > this.buf.length) this.grow(this.length + 1);
|
||||
this.buf[this.length++] = v;
|
||||
}
|
||||
/** Platz für `n` weitere Werte; liefert den Startindex (danach direkt in `buf` schreiben). */
|
||||
reserve(n: number): number {
|
||||
if (this.length + n > this.buf.length) this.grow(this.length + n);
|
||||
const o = this.length;
|
||||
this.length += n;
|
||||
return o;
|
||||
}
|
||||
list(l: readonly number[] | null | undefined): void {
|
||||
const n = l ? l.length : 0;
|
||||
const o = this.reserve(n + 1);
|
||||
this.buf[o] = n;
|
||||
for (let i = 0; i < n; i++) this.buf[o + 1 + i] = l![i];
|
||||
}
|
||||
pts(p: readonly Vec2[]): void {
|
||||
const n = p.length;
|
||||
const o = this.reserve(2 * n + 1);
|
||||
const b = this.buf;
|
||||
b[o] = n;
|
||||
for (let i = 0; i < n; i++) {
|
||||
b[o + 1 + 2 * i] = p[i].x;
|
||||
b[o + 2 + 2 * i] = p[i].y;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const PATTERN_CODE: Record<string, number> = {
|
||||
none: 0,
|
||||
solid: 1,
|
||||
diagonal: 2,
|
||||
crosshatch: 3,
|
||||
insulation: 4,
|
||||
custom: 5,
|
||||
};
|
||||
|
||||
/** Eine Schraffur im Hatch-Format (auch Eingabe der Einzel-Bindungen in `glPlanHatch.ts`). */
|
||||
function writeHatch(w: F64Writer, h: HatchRender, colorIdx: number): void {
|
||||
let flags = 0;
|
||||
if (h.lines === "random") flags |= 1;
|
||||
if (h.origin != null) flags |= 2;
|
||||
if (h.seed != null) flags |= 4;
|
||||
if (h.density != null) flags |= 8;
|
||||
if (h.lengthMin != null) flags |= 16;
|
||||
if (h.lengthMax != null) flags |= 32;
|
||||
if (h.motif) flags |= 64;
|
||||
const o = w.reserve(13);
|
||||
const b = w.buf;
|
||||
b[o] = PATTERN_CODE[h.pattern] ?? 2;
|
||||
b[o + 1] = h.kind === "image" ? 1 : h.kind === "gradient" ? 2 : 0;
|
||||
b[o + 2] = flags;
|
||||
b[o + 3] = h.scale;
|
||||
b[o + 4] = h.angle;
|
||||
b[o + 5] = colorIdx;
|
||||
b[o + 6] = h.lineWeight;
|
||||
b[o + 7] = h.origin != null ? h.origin.x : 0;
|
||||
b[o + 8] = h.origin != null ? h.origin.y : 0;
|
||||
b[o + 9] = h.seed ?? 0;
|
||||
b[o + 10] = h.density ?? 0;
|
||||
b[o + 11] = h.lengthMin ?? 0;
|
||||
b[o + 12] = h.lengthMax ?? 0;
|
||||
w.list(h.dash);
|
||||
if (h.motif) {
|
||||
w.push(h.motif.length);
|
||||
w.pts(h.motif.points);
|
||||
}
|
||||
}
|
||||
|
||||
/** Einzelne Schraffur kodieren (Farbe −1) — Eingabe der Schraffur-Bindungen des Kerns. */
|
||||
export function encodeHatch(h: HatchRender): Float64Array {
|
||||
const w = new F64Writer();
|
||||
writeHatch(w, h, -1);
|
||||
return w.buf.subarray(0, w.length);
|
||||
}
|
||||
|
||||
/** Zwischenspeicher Farbtext → Farbindex-Eintrag (geparste Farbe oder null). */
|
||||
const colorCache = new Map<string, PlanRgba | null>();
|
||||
|
||||
type LinePrim = Extract<Primitive, { kind: "line" }>;
|
||||
|
||||
const isPlainLine = (p: Primitive | undefined): p is LinePrim =>
|
||||
p !== undefined && p.kind === "line" && !p.zigzag && !p.motif;
|
||||
|
||||
/** Setzt `p` den Linienzug von `prev` fort (gleiches Element und gleicher Stil, lückenlos)? */
|
||||
function chainsPrev(prev: Primitive | undefined, p: LinePrim): boolean {
|
||||
return (
|
||||
isPlainLine(prev) &&
|
||||
p.drawingId === prev.drawingId &&
|
||||
p.color === prev.color &&
|
||||
p.weightMm === prev.weightMm &&
|
||||
p.greyed === prev.greyed &&
|
||||
p.opacity === prev.opacity &&
|
||||
p.dash === prev.dash &&
|
||||
p.a.x === prev.b.x &&
|
||||
p.a.y === prev.b.y
|
||||
);
|
||||
}
|
||||
|
||||
/** Primitive → Plan-Puffer (Format s. Dateikopf). */
|
||||
export function encodePlanBuf(prims: readonly Primitive[]): Float64Array {
|
||||
const colors: PlanRgba[] = [];
|
||||
const colorIdx = new Map<string, number>();
|
||||
let lastColor: string | undefined;
|
||||
let lastColorIdx = -1;
|
||||
const color = (s: string | undefined): number => {
|
||||
if (!s) return -1;
|
||||
if (s === lastColor) return lastColorIdx;
|
||||
let i = colorIdx.get(s);
|
||||
if (i !== undefined) {
|
||||
lastColor = s;
|
||||
lastColorIdx = i;
|
||||
return i;
|
||||
}
|
||||
let c = colorCache.get(s);
|
||||
if (c === undefined) {
|
||||
c = parseColor(s);
|
||||
if (colorCache.size > 4096) colorCache.clear();
|
||||
colorCache.set(s, c);
|
||||
}
|
||||
i = c ? colors.push(c) - 1 : -1;
|
||||
colorIdx.set(s, i);
|
||||
return i;
|
||||
};
|
||||
const hatchW = new F64Writer();
|
||||
const hatchIdx = new Map<HatchRender, number>();
|
||||
const hatch = (h: HatchRender | undefined): number => {
|
||||
if (!h) return -1;
|
||||
let i = hatchIdx.get(h);
|
||||
if (i === undefined) {
|
||||
i = hatchIdx.size;
|
||||
writeHatch(hatchW, h, color(h.color));
|
||||
hatchIdx.set(h, i);
|
||||
}
|
||||
return i;
|
||||
};
|
||||
const style = (greyed: boolean | undefined, opacity: number | undefined): number =>
|
||||
(greyed ? FLAG_GREYED : 0) | (opacity !== undefined ? FLAG_OPACITY : 0);
|
||||
const op = (opacity: number | undefined): number => (opacity !== undefined ? opacity : 1);
|
||||
|
||||
const w = new F64Writer();
|
||||
for (let i = 0; i < prims.length; i++) {
|
||||
const p = prims[i];
|
||||
switch (p.kind) {
|
||||
case "polygon": {
|
||||
const fill = color(p.fill);
|
||||
const stroke = color(p.stroke);
|
||||
const h = hatch(p.hatch);
|
||||
const o = w.reserve(7);
|
||||
const b = w.buf;
|
||||
b[o] = 1;
|
||||
b[o + 1] = style(p.greyed, p.opacity);
|
||||
b[o + 2] = fill;
|
||||
b[o + 3] = stroke;
|
||||
b[o + 4] = p.strokeWidthMm;
|
||||
b[o + 5] = h;
|
||||
b[o + 6] = op(p.opacity);
|
||||
w.pts(p.pts);
|
||||
w.list(p.noStrokeEdges);
|
||||
break;
|
||||
}
|
||||
case "line": {
|
||||
let flags = style(p.greyed, p.opacity);
|
||||
if (isPlainLine(p) && chainsPrev(prims[i - 1], p)) flags |= FLAG_CHAIN;
|
||||
if (p.zigzag) flags |= FLAG_ZIGZAG;
|
||||
if (p.motif) flags |= FLAG_MOTIF;
|
||||
const c = color(p.color);
|
||||
const o = w.reserve(9);
|
||||
const b = w.buf;
|
||||
b[o] = 2;
|
||||
b[o + 1] = flags;
|
||||
b[o + 2] = c;
|
||||
b[o + 3] = p.weightMm;
|
||||
b[o + 4] = op(p.opacity);
|
||||
b[o + 5] = p.a.x;
|
||||
b[o + 6] = p.a.y;
|
||||
b[o + 7] = p.b.x;
|
||||
b[o + 8] = p.b.y;
|
||||
w.list(p.dash);
|
||||
if (p.zigzag) {
|
||||
w.push(p.zigzag.amplitude);
|
||||
w.push(p.zigzag.wavelength);
|
||||
}
|
||||
if (p.motif) {
|
||||
w.push(p.motif.length);
|
||||
w.pts(p.motif.points);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "arc": {
|
||||
const c = color((p as { color?: string }).color);
|
||||
const o = w.reserve(12);
|
||||
const b = w.buf;
|
||||
b[o] = 3;
|
||||
b[o + 1] = style(p.greyed, p.opacity);
|
||||
b[o + 2] = c;
|
||||
b[o + 3] = p.weightMm;
|
||||
b[o + 4] = op(p.opacity);
|
||||
b[o + 5] = p.center.x;
|
||||
b[o + 6] = p.center.y;
|
||||
b[o + 7] = p.from.x;
|
||||
b[o + 8] = p.from.y;
|
||||
b[o + 9] = p.to.x;
|
||||
b[o + 10] = p.to.y;
|
||||
b[o + 11] = p.r;
|
||||
w.list(p.dash);
|
||||
break;
|
||||
}
|
||||
case "drawingCircle": {
|
||||
const fill = color(p.fill);
|
||||
const stroke = color(p.stroke);
|
||||
const o = w.reserve(9);
|
||||
const b = w.buf;
|
||||
b[o] = 4;
|
||||
b[o + 1] = style(p.greyed, p.opacity);
|
||||
b[o + 2] = fill;
|
||||
b[o + 3] = stroke;
|
||||
b[o + 4] = p.weightMm;
|
||||
b[o + 5] = op(p.opacity);
|
||||
b[o + 6] = p.center.x;
|
||||
b[o + 7] = p.center.y;
|
||||
b[o + 8] = p.r;
|
||||
w.list(p.dash);
|
||||
break;
|
||||
}
|
||||
case "drawingArc": {
|
||||
const stroke = color(p.stroke);
|
||||
const o = w.reserve(10);
|
||||
const b = w.buf;
|
||||
b[o] = 5;
|
||||
b[o + 1] = style(p.greyed, p.opacity);
|
||||
b[o + 2] = stroke;
|
||||
b[o + 3] = p.weightMm;
|
||||
b[o + 4] = op(p.opacity);
|
||||
b[o + 5] = p.center.x;
|
||||
b[o + 6] = p.center.y;
|
||||
b[o + 7] = p.r;
|
||||
b[o + 8] = p.a0;
|
||||
b[o + 9] = p.a1;
|
||||
w.list(p.dash);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
// Text, Bild …: Platzhalter, damit Indizes/Bereiche gleich bleiben.
|
||||
w.push(0);
|
||||
}
|
||||
}
|
||||
|
||||
const head = 5 + colors.length * 4;
|
||||
const out = new Float64Array(head + hatchW.length + w.length);
|
||||
out[0] = PLAN_BUF_MAGIC;
|
||||
out[1] = PLAN_BUF_VERSION;
|
||||
out[2] = colors.length;
|
||||
out[3] = hatchIdx.size;
|
||||
out[4] = prims.length;
|
||||
for (let i = 0; i < colors.length; i++) out.set(colors[i], 5 + i * 4);
|
||||
out.set(hatchW.buf.subarray(0, hatchW.length), head);
|
||||
out.set(w.buf.subarray(0, w.length), head + hatchW.length);
|
||||
return out;
|
||||
}
|
||||
Reference in new issue
Block a user