native2d: Vektor-Text (Glyph-Umrisse als Dreiecke, instanziert, drehbar) statt SVG-Overlay fuer einfache Texte

This commit is contained in:
karim committed 2026-10-20 00:01:13 +02:00
1 parent 8c3655956c
commit d663d6615c
11 files changed
+783 -5

No files matched your search

+9 -1
View File
@@ -27,6 +27,7 @@ import { textFrameCorners } from "../text/textFrame";
import { RichTextEditor } from "../text/RichTextEditor";
import { useGlPlanRenderer } from "./useGlPlanRenderer";
import { useNativeAvailable, useNativePlanRenderer } from "./useNativePlanRenderer";
import { isGpuText } from "./nativeText";
import { useWasmPlanRenderer } from "./useWasmPlanRenderer";
import { DEFAULT_MARQUEE_COLOR, DEFAULT_SNAP_COLOR } from "../theme/accents";
import {
@@ -810,6 +811,11 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
const wasmHook = useWasmPlanRenderer(canvasRef, wantWasm);
const nativeHook = useNativePlanRenderer(canvasRef, wantNative);
const activeEngine = wantWasm ? wasmHook : wantNative ? nativeHook : glHook;
// Text im Inline-Editor nicht zusätzlich nativ zeichnen.
const setNativeExcludedText = nativeHook.setExcludedText;
useEffect(() => {
setNativeExcludedText(editTextId ?? null);
}, [editTextId, setNativeExcludedText]);
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).
@@ -896,10 +902,12 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
? p.kind !== "drawingText"
: p.kind !== "text" && p.kind !== "drawingText"
: p.kind === "line" && !!p.drawingId;
// Einfache Texte zeichnet die native Fläche selbst (Vektor-Glyphen, auch gedreht).
if (useGpuRenderer && wantNative && nativeHook.gpuTexts && isGpuText(p)) continue;
if (!drawnElsewhere) out.push({ p, i });
}
return out;
}, [plan.primitives, useGpuRenderer, wantWasm]);
}, [plan.primitives, useGpuRenderer, wantWasm, wantNative, nativeHook.gpuTexts]);
const needsCull = svgCandidates.length > CULL_THRESHOLD;
const [cullState, setCullState] = useState<CullState | null>(() => {
if (!needsCull) return null;
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest';
import type { Primitive } from './generatePlan';
import { NativeTextSync, cssColorToRgba, isGpuText } from './nativeText';
const txt = (id: string, over: Record<string, unknown> = {}) =>
({ kind: 'drawingText', drawingId: id, at: { x: 1, y: 2 }, text: 'A', heightM: 2, angle: 0.5, color: '#ff0000', ...over }) as unknown as Primitive;
describe('isGpuText', () => {
it('einfacher Text ja, Textfeld/Mehrzeiler/ohne Id nein', () => {
expect(isGpuText(txt('a'))).toBe(true);
expect(isGpuText(txt('a', { doc: {} }))).toBe(false);
expect(isGpuText(txt('a', { wrapWidth: 3 }))).toBe(false);
expect(isGpuText(txt('a', { text: 'x\ny' }))).toBe(false);
expect(isGpuText(txt('', {}))).toBe(false);
});
});
describe('cssColorToRgba', () => {
it('versteht #rgb, #rrggbb, rgb()', () => {
expect(cssColorToRgba('#f00')).toEqual([1, 0, 0, 1]);
expect(cssColorToRgba('#00ff00', 0.5)).toEqual([0, 1, 0, 0.5]);
expect(cssColorToRgba('rgb(0, 0, 255)')).toEqual([0, 0, 1, 1]);
expect(cssColorToRgba('banane')).toEqual([0, 0, 0, 1]);
});
});
describe('NativeTextSync.delta', () => {
it('sendet nur Neues/Geändertes und meldet Entferntes', () => {
const s = new NativeTextSync();
const a = txt('a'), b = txt('b');
let d = s.delta([a, b]);
expect(d.upsert).toHaveLength(2);
expect(d.upsert[0]).toMatchObject({ x: 90, y: -180, size: 180, angle: -0.5 });
d = s.delta([a, b]);
expect(d.upsert).toHaveLength(0);
expect(d.remove).toHaveLength(0);
d = s.delta([a, txt('b', { text: 'neu' })]);
expect(d.upsert.map((u) => u.text)).toEqual(['neu']);
d = s.delta([a]);
expect(d.remove).toHaveLength(1);
});
it('schliesst den Editor-Text aus', () => {
const s = new NativeTextSync();
s.delta([txt('a'), txt('b')]);
const d = s.delta([txt('a'), txt('b')], 'b');
expect(d.remove).toHaveLength(1);
});
});
+117
View File
@@ -0,0 +1,117 @@
/**
* Texte für die NATIVE 2D-Engine (Vektor-Text in Rust, src-tauri/render2d/src/vtext.rs).
*
* Einfache, einzeilige `drawingText`-Primitive (auch gedrehte) zeichnet die native
* Fläche; alles Reichere (Textfelder mit `doc`, Spaltenumbruch, Mehrzeiler) bleibt
* im SVG-Overlay. Die Webview schickt nur DELTAS: je Text eine Signatur, nur neue
* oder geänderte Texte gehen über die Schnittstelle.
*/
import type { Primitive } from './generatePlan';
type DrawingText = Extract<Primitive, { kind: 'drawingText' }>;
/** Zeichnet die native Fläche diesen Text (statt des SVG-Overlays)? */
export function isGpuText(p: Primitive): p is DrawingText {
return (
p.kind === 'drawingText' &&
!!p.drawingId &&
!p.doc &&
!p.wrapWidth &&
p.text.length > 0 &&
!p.text.includes('\n')
);
}
/** CSS-Farbe (#rgb, #rrggbb, rgb()/rgba()) → [r,g,b,a] in 0..1; sonst Schwarz. */
export function cssColorToRgba(css: string, alpha = 1): [number, number, number, number] {
const s = css.trim();
let m = /^#([0-9a-f]{3})$/i.exec(s);
if (m) {
const h = m[1];
return [parseInt(h[0] + h[0], 16) / 255, parseInt(h[1] + h[1], 16) / 255, parseInt(h[2] + h[2], 16) / 255, alpha];
}
m = /^#([0-9a-f]{6})([0-9a-f]{2})?$/i.exec(s);
if (m) {
const n = parseInt(m[1], 16);
const a = m[2] ? parseInt(m[2], 16) / 255 : 1;
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255, alpha * a];
}
m = /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,/\s]+([\d.]+%?))?\s*\)$/i.exec(s);
if (m) {
const a = m[4] ? (m[4].endsWith('%') ? parseFloat(m[4]) / 100 : parseFloat(m[4])) : 1;
return [parseFloat(m[1]) / 255, parseFloat(m[2]) / 255, parseFloat(m[3]) / 255, alpha * a];
}
return [0, 0, 0, alpha];
}
/** Bildschirm-Einheiten je Meter (== PX_PER_M in PlanView/toScreen). */
const PX_PER_M = 90;
export interface NativeTextEntry {
id: number;
x: number;
y: number;
size: number;
angle: number;
color: [number, number, number, number];
text: string;
}
interface Known {
id: number;
sig: string;
}
/** Verwaltet die IDs/Signaturen der bereits an Rust geschickten Texte. */
export class NativeTextSync {
private known = new Map<string, Known>();
private nextId = 1;
private sigCache = new WeakMap<Primitive, string>();
/** Rust hat alles vergessen (z. B. neue Fläche): beim nächsten Delta alles neu senden. */
reset(): void {
this.known.clear();
}
/**
* Delta gegenüber dem zuletzt gesendeten Stand. `excludeDrawingId`: Text, der
* gerade im Editor liegt (wird nicht nativ gezeichnet).
*/
delta(prims: readonly Primitive[], excludeDrawingId?: string | null): { upsert: NativeTextEntry[]; remove: number[] } {
const upsert: NativeTextEntry[] = [];
const seen = new Set<string>();
for (const p of prims) {
if (!isGpuText(p)) continue;
const key = p.drawingId!;
if (key === excludeDrawingId) continue;
seen.add(key);
let sig = this.sigCache.get(p);
if (sig === undefined) {
sig = `${p.at.x}|${p.at.y}|${p.heightM}|${p.angle}|${p.color}|${p.greyed ? 1 : 0}|${p.text}`;
this.sigCache.set(p, sig);
}
const k = this.known.get(key);
if (k && k.sig === sig) continue;
const id = k?.id ?? this.nextId++;
this.known.set(key, { id, sig });
upsert.push({
id,
x: p.at.x * PX_PER_M,
y: -p.at.y * PX_PER_M,
size: p.heightM * PX_PER_M,
angle: -p.angle,
color: cssColorToRgba(p.color, p.greyed ? 0.45 : 1),
text: p.text,
});
}
const remove: number[] = [];
for (const [key, k] of this.known) {
if (!seen.has(key)) {
remove.push(k.id);
this.known.delete(key);
}
}
return { upsert, remove };
}
}
+46 -2
View File
@@ -13,6 +13,7 @@ import type { Plan } from './generatePlan';
import { GpuChunkCache, type ViewBox } from './glPlan';
import { NativeGl, type NativeInvoke } from './glPlan/nativeGl';
import { readCssColor } from './useGlPlanRenderer';
import { NativeTextSync } from './nativeText';
/** Läuft die App in einer Tauri-Webview? */
const isTauri = (): boolean => typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
@@ -71,6 +72,43 @@ export function useNativePlanRenderer(
const invokeRef = useRef<NativeInvoke | null>(null);
const rectRef = useRef('');
const [ready, setReady] = useState(false);
// Texte: Rust zeichnet einfache Texte als Vektor-Glyphen (nativeText.ts). Solange
// das nicht bestätigt ist (oder keine Schrift gefunden wurde), bleibt es beim SVG.
const [gpuTexts, setGpuTexts] = useState(false);
const textSync = useRef(new NativeTextSync());
const textsDisabled = useRef(false);
const lastPlan = useRef<Plan | null>(null);
const excludedText = useRef<string | null>(null);
const pushTexts = useCallback((plan: Plan | null) => {
const invoke = invokeRef.current;
if (!invoke || !plan || textsDisabled.current) return;
const { upsert, remove } = textSync.current.delta(plan.primitives, excludedText.current);
if (upsert.length === 0 && remove.length === 0) return;
void invoke('native2d_texts', { upsert, remove })
.then((ok) => {
if (ok === true) setGpuTexts(true);
else {
textsDisabled.current = true;
textSync.current.reset();
setGpuTexts(false);
}
})
.catch(() => {
textsDisabled.current = true;
setGpuTexts(false);
});
}, []);
/** Text, der gerade im Editor liegt: nicht nativ zeichnen (der Editor zeigt ihn). */
const setExcludedText = useCallback(
(id: string | null) => {
if (excludedText.current === id) return;
excludedText.current = id;
pushTexts(lastPlan.current);
},
[pushTexts],
);
// Frame-Aufrufe zusammenfassen: höchstens einer in der Luft, der letzte gewinnt.
const frameBusy = useRef(false);
@@ -147,6 +185,10 @@ export function useNativePlanRenderer(
const invoke = invokeRef.current;
// Layout leeren + Fläche ausblenden (Plan-Ansicht verschwindet).
if (glRef.current && invoke) {
const { remove } = textSync.current.delta([]);
if (remove.length) void invoke('native2d_texts', { upsert: [], remove }).catch(() => {});
lastPlan.current = null;
setGpuTexts(false);
const { delete: del } = glRef.current.takeLayout([]);
void invoke('native2d_layout', { layout: [], delete: del }).catch(() => {});
void invoke('native2d_embed_hide').catch(() => {});
@@ -176,11 +218,13 @@ export function useNativePlanRenderer(
cache.dispose();
}
const { layout, delete: del } = gl.takeLayout(cache.geometries);
lastPlan.current = plan;
// 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),
);
}, []);
pushTexts(plan);
}, [pushTexts]);
const render = useCallback(
(viewBox: ViewBox, paperScaleN = 100) => {
@@ -199,5 +243,5 @@ export function useNativePlanRenderer(
[sendFrame, syncRect],
);
return { render, updateGeometry, ready };
return { render, updateGeometry, ready, gpuTexts, setExcludedText };
}