native2d Stufe 2: Plan-Ansicht rendert in eingebetteter Metal-Flaeche (Chunk-Upload binaer, Frame = nur Ausschnitt); altes Diagnose-Fenster entfernt
This commit is contained in:
1 parent
aad15fa8c0
commit
ef3dfd8a6b
9 files changed
+412
-41
No files matched your search
+15
-9
@@ -26,6 +26,7 @@ import { contentFontBaselineFromTop, TEXT_LINE_HEIGHT_MULT } from "../text/fontM
|
||||
import { textFrameCorners } from "../text/textFrame";
|
||||
import { RichTextEditor } from "../text/RichTextEditor";
|
||||
import { useGlPlanRenderer } from "./useGlPlanRenderer";
|
||||
import { useNativeAvailable, useNativePlanRenderer } from "./useNativePlanRenderer";
|
||||
import { useWasmPlanRenderer } from "./useWasmPlanRenderer";
|
||||
import { DEFAULT_MARQUEE_COLOR, DEFAULT_SNAP_COLOR } from "../theme/accents";
|
||||
import {
|
||||
@@ -793,20 +794,25 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
console.warn("engine=wasm angefragt, aber navigator.gpu fehlt → WebGL2-Fallback");
|
||||
}
|
||||
}, [engineParam, hasWebGpu]);
|
||||
// WebGL2 nur, wenn NICHT der WASM-Pfad aktiv ist (und `?gl!=0`).
|
||||
const wantGl =
|
||||
!wantWasm &&
|
||||
(typeof window === "undefined"
|
||||
? true
|
||||
: new URLSearchParams(window.location.search).get("gl") !== "0");
|
||||
// Beide Hooks unbedingt aufrufen (Hook-Regeln); je nach Flag ist genau einer aktiv.
|
||||
// NATIVE Metal-Fläche hinter der Webview (macOS-Tauri mit Feature native2d,
|
||||
// s. useNativePlanRenderer.ts): STANDARD, wo verfügbar; `?native=0` schaltet auf
|
||||
// WebGL2 zurück. Solange die Verfügbarkeit noch erfragt wird (null), startet
|
||||
// KEINE Engine — sonst würde kurz ein WebGL-Kontext aufgebaut und wieder verworfen.
|
||||
const nativeAvail = useNativeAvailable();
|
||||
const glParam = typeof window === "undefined" ? null : new URLSearchParams(window.location.search).get("gl");
|
||||
const nativeOptOut = typeof window !== "undefined" && new URLSearchParams(window.location.search).get("native") === "0";
|
||||
const wantNative = nativeAvail === true && !wantWasm && !nativeOptOut && glParam !== "0";
|
||||
// WebGL2 nur, wenn weder der WASM- noch der native Pfad aktiv ist (und `?gl!=0`).
|
||||
const wantGl = !wantWasm && !wantNative && nativeAvail !== null && glParam !== "0";
|
||||
// Alle Hooks unbedingt aufrufen (Hook-Regeln); je nach Flag ist genau einer aktiv.
|
||||
const glHook = useGlPlanRenderer(canvasRef, wantGl);
|
||||
const wasmHook = useWasmPlanRenderer(canvasRef, wantWasm);
|
||||
const activeEngine = wantWasm ? wasmHook : glHook;
|
||||
const nativeHook = useNativePlanRenderer(canvasRef, wantNative);
|
||||
const activeEngine = wantWasm ? wasmHook : wantNative ? nativeHook : glHook;
|
||||
const { render: renderGl, updateGeometry, ready: glReady } = activeEngine;
|
||||
// „GPU-Canvas montieren?" — beide GPU-Pfade brauchen das Canvas (an der ABSICHT
|
||||
// montiert, nicht am ready, sonst könnte die Engine mangels Canvas nie starten).
|
||||
const wantGpu = wantGl || wantWasm;
|
||||
const wantGpu = wantGl || wantWasm || wantNative;
|
||||
// Georeferenzierte Hintergrund-Rasterbilder (Luftbild) vorhanden? Der GPU-
|
||||
// Canvas löscht das Blatt UNDURCHSICHTIG (clearColor …,1) und würde ein
|
||||
// dahinterliegendes Bild verdecken. Daher bei aktivem Luftbild bewusst den
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
import type { Primitive, UnderlayGroup } from '../generatePlan';
|
||||
import type { Drawing2D } from '../../model/types';
|
||||
import { compilePrimitivesToGpu } from './glPlanCompile';
|
||||
import type { GpuGeometry } from './glPlanTypes';
|
||||
import type { BufferGl, GpuGeometry } from './glPlanTypes';
|
||||
|
||||
/** Ziel: im Mittel so viele Elemente (drawingIds) je Chunk = 2^BITS. */
|
||||
const BOUNDARY_BITS = 8;
|
||||
@@ -85,7 +85,7 @@ interface Chunk {
|
||||
geometry: GpuGeometry;
|
||||
}
|
||||
|
||||
function disposeGeometry(gl: WebGL2RenderingContext, g: GpuGeometry): void {
|
||||
function disposeGeometry(gl: BufferGl, g: GpuGeometry): void {
|
||||
gl.deleteBuffer(g.fill.positionBuffer);
|
||||
gl.deleteBuffer(g.fill.indexBuffer);
|
||||
gl.deleteBuffer(g.line.vertexBuffer);
|
||||
@@ -141,7 +141,7 @@ class UnderlayChunkCache {
|
||||
private previous: UnderChunk[] = [];
|
||||
recompiled = 0;
|
||||
|
||||
constructor(private readonly gl: WebGL2RenderingContext) {}
|
||||
constructor(private readonly gl: BufferGl) {}
|
||||
|
||||
/** Liefert je Gruppe die Geometrien ihrer Chunks (in Reihenfolge). */
|
||||
update(groups: readonly UnderlayGroup[]): GpuGeometry[][] {
|
||||
@@ -216,7 +216,7 @@ export class GpuChunkCache {
|
||||
|
||||
private readonly under: UnderlayChunkCache;
|
||||
|
||||
constructor(private readonly gl: WebGL2RenderingContext) {
|
||||
constructor(private readonly gl: BufferGl) {
|
||||
this.under = new UnderlayChunkCache(gl);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
import type { Primitive } from '../generatePlan';
|
||||
import type { Vec2 } from '../../model/types';
|
||||
import type { GpuGeometry, Rgba } from './glPlanTypes';
|
||||
import type { BufferGl, GpuGeometry, Rgba } from './glPlanTypes';
|
||||
import { applyDashRuns, buildHatchRuns, zigzagPoints, motifPoints, DASH_MM_TO_M } from './glPlanHatch';
|
||||
|
||||
const PX_PER_M = 90;
|
||||
@@ -263,7 +263,7 @@ function dimFill(color: Rgba, greyed: boolean | undefined, opacity?: number): Rg
|
||||
* bildschirmkonstante Striche). Text/Bögen bleiben im SVG-Overlay.
|
||||
*/
|
||||
export function compilePrimitivesToGpu(
|
||||
gl: WebGL2RenderingContext,
|
||||
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
|
||||
|
||||
@@ -110,3 +110,18 @@ export interface ViewBox {
|
||||
w: number;
|
||||
h: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Der Teil des GL-Kontexts, den Kompilierung + Chunk-Cache wirklich brauchen:
|
||||
* Puffer anlegen/befüllen/freigeben. WebGL2 erfüllt das direkt; der native
|
||||
* Renderer (nativeGl.ts) liefert eine Attrappe, die die Bytes an Rust schickt.
|
||||
*/
|
||||
export interface BufferGl {
|
||||
readonly ARRAY_BUFFER: number;
|
||||
readonly ELEMENT_ARRAY_BUFFER: number;
|
||||
readonly STATIC_DRAW: number;
|
||||
createBuffer(): WebGLBuffer | null;
|
||||
bindBuffer(target: number, buffer: WebGLBuffer | null): void;
|
||||
bufferData(target: number, data: ArrayBufferView, usage: number): void;
|
||||
deleteBuffer(buffer: WebGLBuffer | null): void;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Puffer-Attrappe für den NATIVEN Plan-Renderer (macOS, src-tauri/src/native_embed.rs).
|
||||
*
|
||||
* Kompilierung (`compilePrimitivesToGpu`) und Chunk-Cache (`GpuChunkCache`) laufen
|
||||
* unverändert in TypeScript und sprechen nur diese vier Puffer-Funktionen an
|
||||
* (`BufferGl`). Statt eines GL-Kontexts liegen die Bytes danach in Rust: jeder
|
||||
* Puffer geht EINMAL als Rohdaten über die Tauri-Schnittstelle (kein JSON); pro
|
||||
* Frame wandert danach nur noch der Ausschnitt.
|
||||
*/
|
||||
|
||||
import type { BufferGl, GpuGeometry } from './glPlanTypes';
|
||||
|
||||
export type NativeInvoke = (cmd: string, args?: unknown, options?: unknown) => Promise<unknown>;
|
||||
|
||||
interface NativeBuffer {
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** Layout-Eintrag einer Geometrie (Spiegel von `ChunkGeom` in render2d/chunks.rs). */
|
||||
export interface NativeChunkLayout {
|
||||
fill_pos: number | null;
|
||||
fill_idx: number | null;
|
||||
fill_batches: { start: number; count: number; color: number[] }[];
|
||||
line_vtx: number | null;
|
||||
line_idx: number | null;
|
||||
line_batches: { start: number; count: number; color: number[]; stroke_mm: number; screen_px: boolean }[];
|
||||
origin: [number, number];
|
||||
greyed: boolean;
|
||||
}
|
||||
|
||||
export class NativeGl implements BufferGl {
|
||||
readonly ARRAY_BUFFER = 0x8892;
|
||||
readonly ELEMENT_ARRAY_BUFFER = 0x8893;
|
||||
readonly STATIC_DRAW = 0x88e4;
|
||||
|
||||
private nextId = 1;
|
||||
private bound: NativeBuffer | null = null;
|
||||
private pendingDelete: number[] = [];
|
||||
|
||||
constructor(private readonly invoke: NativeInvoke) {}
|
||||
|
||||
createBuffer(): WebGLBuffer {
|
||||
return { id: this.nextId++ } as unknown as WebGLBuffer;
|
||||
}
|
||||
|
||||
bindBuffer(_target: number, buffer: WebGLBuffer | null): void {
|
||||
this.bound = buffer as unknown as NativeBuffer | null;
|
||||
}
|
||||
|
||||
bufferData(_target: number, data: ArrayBufferView, _usage: number): void {
|
||||
const buf = this.bound;
|
||||
if (!buf) return;
|
||||
// KOPIE: die Quelle ist ein wiederverwendeter Wachstumspuffer, der Aufruf
|
||||
// serialisiert asynchron.
|
||||
const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice();
|
||||
void this.invoke('native2d_upload', bytes, { headers: { 'x-buf-id': String(buf.id) } }).catch((e) =>
|
||||
console.debug('native2d_upload fehlgeschlagen', e),
|
||||
);
|
||||
}
|
||||
|
||||
deleteBuffer(buffer: WebGLBuffer | null): void {
|
||||
if (buffer) this.pendingDelete.push((buffer as unknown as NativeBuffer).id);
|
||||
}
|
||||
|
||||
/** Geometrien (in Zeichenreihenfolge) → Layout für Rust, plus freizugebende Puffer. */
|
||||
takeLayout(geometries: readonly GpuGeometry[]): { layout: NativeChunkLayout[]; delete: number[] } {
|
||||
const id = (b: WebGLBuffer | null): number | null => (b ? (b as unknown as NativeBuffer).id : null);
|
||||
const layout = geometries.map((g) => ({
|
||||
fill_pos: id(g.fill.positionBuffer),
|
||||
fill_idx: id(g.fill.indexBuffer),
|
||||
fill_batches: g.fill.batches.map((b) => ({ start: b.startIndex, count: b.indexCount, color: b.color })),
|
||||
line_vtx: id(g.line.vertexBuffer),
|
||||
line_idx: id(g.line.indexBuffer),
|
||||
line_batches: g.line.batches.map((b) => ({
|
||||
start: b.startIndex,
|
||||
count: b.indexCount,
|
||||
color: b.color,
|
||||
stroke_mm: b.strokeMm,
|
||||
screen_px: !!b.screenPx,
|
||||
})),
|
||||
origin: [g.origin?.x ?? 0, g.origin?.y ?? 0] as [number, number],
|
||||
greyed: !!g.greyed,
|
||||
}));
|
||||
const del = this.pendingDelete;
|
||||
this.pendingDelete = [];
|
||||
return { layout, delete: del };
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
} from './glPlan';
|
||||
|
||||
/** Liest eine CSS-Custom-Property (z. B. "--sheet") als RGB[0..1] oder null. */
|
||||
function readCssColor(varName: string): [number, number, number] | null {
|
||||
export function readCssColor(varName: string): [number, number, number] | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
const raw = getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
|
||||
let h = raw.startsWith('#') ? raw.slice(1) : raw;
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* Nativer Plan-Renderer (macOS/Tauri): dieselbe Schnittstelle wie
|
||||
* `useGlPlanRenderer` ({render, updateGeometry, ready}), aber die Pixel entstehen
|
||||
* in einer Metal-Fläche HINTER der transparenten Webview (src-tauri/src/native_embed.rs).
|
||||
*
|
||||
* Kompilierung + Chunk-Cache bleiben TypeScript (`GpuChunkCache` mit `NativeGl`);
|
||||
* Rust hält die Puffer. Pan/Zoom kostet nur noch einen kleinen Frame-Aufruf.
|
||||
* Eingaben, Auswahl, Griffe, Text bleiben im SVG-Overlay darüber.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { Plan } from './generatePlan';
|
||||
import { GpuChunkCache, type ViewBox } from './glPlan';
|
||||
import { NativeGl, type NativeInvoke } from './glPlan/nativeGl';
|
||||
import { readCssColor } from './useGlPlanRenderer';
|
||||
|
||||
/** Läuft die App in einer Tauri-Webview? */
|
||||
const isTauri = (): boolean => typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
|
||||
|
||||
let invokePromise: Promise<NativeInvoke | null> | null = null;
|
||||
function loadInvoke(): Promise<NativeInvoke | null> {
|
||||
invokePromise ??= (async () => {
|
||||
if (!isTauri()) return null;
|
||||
try {
|
||||
// @ts-ignore optionales Paket
|
||||
const mod = await import(/* @vite-ignore */ '@tauri-apps/api/core').catch(() => null);
|
||||
return mod && typeof (mod as any).invoke === 'function' ? ((mod as any).invoke as NativeInvoke) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
return invokePromise;
|
||||
}
|
||||
|
||||
let availablePromise: Promise<boolean> | null = null;
|
||||
/** Gibt es in diesem Build die eingebettete native 2D-Fläche? (einmal erfragt) */
|
||||
export function nativeEmbedAvailable(): Promise<boolean> {
|
||||
availablePromise ??= (async () => {
|
||||
const invoke = await loadInvoke();
|
||||
if (!invoke) return false;
|
||||
try {
|
||||
return (await invoke('native2d_embed_available')) === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
return availablePromise;
|
||||
}
|
||||
|
||||
/** Wahr, sobald klar ist, dass die native Fläche verfügbar ist (null = noch offen). */
|
||||
export function useNativeAvailable(): boolean | null {
|
||||
const [avail, setAvail] = useState<boolean | null>(null);
|
||||
useEffect(() => {
|
||||
let off = false;
|
||||
void nativeEmbedAvailable().then((v) => {
|
||||
if (!off) setAvail(v);
|
||||
});
|
||||
return () => {
|
||||
off = true;
|
||||
};
|
||||
}, []);
|
||||
return avail;
|
||||
}
|
||||
|
||||
export function useNativePlanRenderer(
|
||||
canvasRef: React.RefObject<HTMLCanvasElement | null>,
|
||||
enabled: boolean,
|
||||
) {
|
||||
const glRef = useRef<NativeGl | null>(null);
|
||||
const cacheRef = useRef<GpuChunkCache | null>(null);
|
||||
const invokeRef = useRef<NativeInvoke | null>(null);
|
||||
const rectRef = useRef('');
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
// Frame-Aufrufe zusammenfassen: höchstens einer in der Luft, der letzte gewinnt.
|
||||
const frameBusy = useRef(false);
|
||||
const frameNext = useRef<(() => Promise<unknown>) | null>(null);
|
||||
const sendFrame = useCallback((job: () => Promise<unknown>) => {
|
||||
if (frameBusy.current) {
|
||||
frameNext.current = job;
|
||||
return;
|
||||
}
|
||||
frameBusy.current = true;
|
||||
const run = (j: () => Promise<unknown>) => {
|
||||
void j()
|
||||
.catch((e) => console.debug('native2d_frame fehlgeschlagen', e))
|
||||
.finally(() => {
|
||||
const next = frameNext.current;
|
||||
frameNext.current = null;
|
||||
if (next) run(next);
|
||||
else frameBusy.current = false;
|
||||
});
|
||||
};
|
||||
run(job);
|
||||
}, []);
|
||||
|
||||
const syncRect = useCallback((force = false) => {
|
||||
const invoke = invokeRef.current;
|
||||
const canvas = canvasRef.current;
|
||||
if (!invoke || !canvas) return;
|
||||
const r = canvas.getBoundingClientRect();
|
||||
const key = `${r.left},${r.top},${r.width},${r.height}`;
|
||||
if (!force && key === rectRef.current) return;
|
||||
rectRef.current = key;
|
||||
void invoke('native2d_embed_rect', { x: r.left, y: r.top, w: r.width, h: r.height }).catch(() => {});
|
||||
}, [canvasRef]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
setReady(false);
|
||||
return;
|
||||
}
|
||||
let disposed = false;
|
||||
let ro: ResizeObserver | null = null;
|
||||
const holes: Element[] = [];
|
||||
const onWin = () => syncRect();
|
||||
void (async () => {
|
||||
const invoke = await loadInvoke();
|
||||
if (!invoke || disposed || !(await nativeEmbedAvailable())) return;
|
||||
invokeRef.current = invoke;
|
||||
const gl = new NativeGl(invoke);
|
||||
glRef.current = gl;
|
||||
cacheRef.current = new GpuChunkCache(gl);
|
||||
syncRect(true);
|
||||
if (canvasRef.current && typeof ResizeObserver !== 'undefined') {
|
||||
ro = new ResizeObserver(() => syncRect());
|
||||
ro.observe(canvasRef.current);
|
||||
}
|
||||
window.addEventListener('resize', onWin);
|
||||
// Webview über der Fläche durchsichtig machen: alle Vorfahren des Canvas
|
||||
// verlieren ihren Hintergrund (Geschwister behalten ihren eigenen).
|
||||
for (let el = canvasRef.current?.parentElement; el; el = el.parentElement) {
|
||||
el.setAttribute('data-native-hole', '');
|
||||
holes.push(el);
|
||||
}
|
||||
document.documentElement.setAttribute('data-native-hole', '');
|
||||
setReady(true);
|
||||
})();
|
||||
return () => {
|
||||
disposed = true;
|
||||
ro?.disconnect();
|
||||
for (const el of holes) el.removeAttribute('data-native-hole');
|
||||
document.documentElement.removeAttribute('data-native-hole');
|
||||
window.removeEventListener('resize', onWin);
|
||||
cacheRef.current?.dispose();
|
||||
cacheRef.current = null;
|
||||
const invoke = invokeRef.current;
|
||||
// Layout leeren + Fläche ausblenden (Plan-Ansicht verschwindet).
|
||||
if (glRef.current && invoke) {
|
||||
const { delete: del } = glRef.current.takeLayout([]);
|
||||
void invoke('native2d_layout', { layout: [], delete: del }).catch(() => {});
|
||||
void invoke('native2d_embed_hide').catch(() => {});
|
||||
}
|
||||
glRef.current = null;
|
||||
invokeRef.current = null;
|
||||
rectRef.current = '';
|
||||
setReady(false);
|
||||
};
|
||||
}, [enabled, canvasRef, syncRect]);
|
||||
|
||||
const updateGeometry = useCallback((plan: Plan, pxPerMeter = 0) => {
|
||||
const cache = cacheRef.current;
|
||||
const gl = glRef.current;
|
||||
const invoke = invokeRef.current;
|
||||
if (!cache || !gl || !invoke || !plan) return;
|
||||
try {
|
||||
cache.update(
|
||||
plan.primitives,
|
||||
pxPerMeter,
|
||||
pxPerMeter > 0 ? Math.round(Math.log2(pxPerMeter)) : -Infinity,
|
||||
plan.greyedRanges,
|
||||
plan.underlay,
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn('Tessellierung fehlgeschlagen:', e);
|
||||
cache.dispose();
|
||||
}
|
||||
const { layout, delete: del } = gl.takeLayout(cache.geometries);
|
||||
// Direkt (nicht über sendFrame): Reihenfolge nach den Puffer-Uploads ist wichtig.
|
||||
void invoke('native2d_layout', { layout, delete: del }).catch((e) =>
|
||||
console.debug('native2d_layout fehlgeschlagen', e),
|
||||
);
|
||||
}, []);
|
||||
|
||||
const render = useCallback(
|
||||
(viewBox: ViewBox, paperScaleN = 100) => {
|
||||
const invoke = invokeRef.current;
|
||||
if (!invoke) return;
|
||||
syncRect();
|
||||
const sheet = readCssColor('--sheet');
|
||||
sendFrame(() =>
|
||||
invoke('native2d_frame', {
|
||||
view: viewBox,
|
||||
paperScale: paperScaleN,
|
||||
clear: sheet ? [sheet[0], sheet[1], sheet[2]] : null,
|
||||
}),
|
||||
);
|
||||
},
|
||||
[sendFrame, syncRect],
|
||||
);
|
||||
|
||||
return { render, updateGeometry, ready };
|
||||
}
|
||||
Reference in new issue
Block a user