From 6715ed826fc74a76f132a6c09985557035d0defc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 01:15:42 +0000 Subject: [PATCH 1/5] =?UTF-8?q?[K3d]=20Plan=20lazy:=20St=C3=BCcke=20aus=20?= =?UTF-8?q?Kern-Abschnitten=20und=20TS-Listen,=20Puffer-Eintr=C3=A4ge=20er?= =?UTF-8?q?st=20bei=20Bedarf=20gelesen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit generatePlan/generateVisibleLevelsPlan/materializeUnderlay setzen den Plan aus Stücken zusammen (planLazy.ts); plan.primitives entsteht erst beim ersten Zugriff. planParts liest die Stücke direkt. decodePlanBuf liest Einträge, Texte und Schraffur-JSON bei Bedarf (prim(i), tag(i)). Abzugskörper, Mono und Strichstärken-Massstab bleiben auf der Liste. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src/plan/generatePlan.ts | 139 +++++++++++++------------ src/plan/planBuf.test.ts | 2 +- src/plan/planBuf.ts | 69 ++++++++++--- src/plan/planLazy.ts | 216 +++++++++++++++++++++++++++++++++++++++ src/plan/planParts.ts | 55 ++++++++-- 5 files changed, 391 insertions(+), 90 deletions(-) create mode 100644 src/plan/planLazy.ts diff --git a/src/plan/generatePlan.ts b/src/plan/generatePlan.ts index 8b7bd202..36968eec 100644 --- a/src/plan/generatePlan.ts +++ b/src/plan/generatePlan.ts @@ -53,7 +53,8 @@ import { type HatchRender, type Primitive, } from "./generatePlan/shared"; -import { subtractVoidsInPlan } from "./voids"; +import { subtractVoidsInPlan, voidPrisms } from "./voids"; +import { isBufPiece, lazyPlan, piecesOf, planCount, planFields, type PlanPiece } from "./planLazy"; import { addSunShadow } from "./generatePlan/sunShadow"; import { addSiteRules, addSiteViolations } from "./generatePlan/siteRules"; import { lineWeightFactor, scalePrimitiveWeights } from "./lineWeightScale"; @@ -211,11 +212,6 @@ export interface PlanBufRun { to: number; } -/** Kern-Abschnitte um `shift` verschieben (beim Zusammensetzen mehrerer Pläne). */ -function shiftRuns(runs: readonly PlanBufRun[] | undefined, shift: number, into: PlanBufRun[]): void { - for (const r of runs ?? []) into.push({ ...r, at: r.at + shift }); -} - /** * Eine Gruppe kompakt gehaltener Zeichnungen. Ihre Linien entstehen erst beim * Kompilieren eines GPU-Chunks (kurzlebig, `build`), nicht als dauerhafte @@ -254,26 +250,17 @@ export function materializeUnderlay(plan: Plan): Plan { for (const pr of g.build(g.drawings)) target.push(pr); if (g.tint && target.length > from) (g.above ? aboveGreyed : belowGreyed).push([from, target.length]); } - const primitives: Primitive[] = []; - for (const pr of below) primitives.push(pr); - for (const pr of plan.primitives) primitives.push(pr); - for (const pr of above) primitives.push(pr); + // Stücke statt Kopie (s. `planLazy.ts`): die Primitive des Plans werden dabei nicht gelesen. + const n = planCount(plan); const shifted = (plan.greyedRanges ?? []).map(([a, b]): [number, number] => [a + below.length, b + below.length]); - const aboveShift = below.length + plan.primitives.length; + const aboveShift = below.length + n; const ranges = [ ...belowGreyed, ...shifted, ...aboveGreyed.map(([a, b]): [number, number] => [a + aboveShift, b + aboveShift]), ]; - const bufRuns: PlanBufRun[] = []; - shiftRuns(plan.bufRuns, below.length, bufRuns); - return { - ...plan, - primitives, - underlay: undefined, - greyedRanges: ranges.length ? ranges : undefined, - bufRuns: bufRuns.length ? bufRuns : undefined, - }; + const { underlay: _u, greyedRanges: _g, ...fields } = planFields(plan); + return lazyPlan({ ...fields, ...(ranges.length ? { greyedRanges: ranges } : {}) }, [below, ...piecesOf(plan), above]); } /** Ob Index `i` in einem der (sortierten, disjunkten) Bereiche liegt. */ @@ -412,15 +399,14 @@ export function generatePlan( // Der Kern liefert alles in EINEM Plan-Puffer (Gruppen in dieser Reihenfolge); die Abschnitte // merkt sich der Plan (`bufRuns`), damit die GPU sie direkt aus dem Puffer kompiliert. const dom = planDomains(project, floorId, visibleCodes, categoryDisplay, detail, showReferenceLines, includeGlobal); - const runs: PlanBufRun[] = []; + // Der Plan entsteht aus Stücken ([K3d], `planLazy.ts`): TS-Listen und Kern-Abschnitte; die + // Kern-Primitive werden erst gelesen, wenn ein Verbraucher sie als Objekte braucht. + const pieces: PlanPiece[] = [primitives]; const pushGroups = (first: number, last: number): void => { if (!dom.buf) return; const from = dom.buf.groups[first][0]; const to = dom.buf.groups[last][1]; - const at = primitives.length; - const src = dom.buf.prims; - for (let i = from; i < to; i++) primitives.push(src[i]); - if (to > from) runs.push({ at, buf: dom.buf, from, to }); + if (to > from) pieces.push({ buf: dom.buf, from, to }); }; // Decken, Dächer, Räume; Wände (Poché, Referenzlinie) mit ihren Öffnungs-Symbolen, je Wand // nacheinander; Treppen (Tritte + Lauflinie + Auf-/Abpfeil mit dem Grundriss-Schnitt, über der @@ -428,6 +414,8 @@ export function generatePlan( pushGroups(G_CEILINGS, G_COLUMNS); // 2D-Zeichengeometrie zuletzt (über der Poché). + const drawingPrims: Primitive[] = []; + pieces.push(drawingPrims); const compact = compactUnderlay && !mono && !forPrint; // Kompakte Unterlage PRO KATEGORIE gruppiert: das Ein-/Ausblenden einer Ebene // entfernt dann nur deren Gruppe — die Chunks aller anderen Ebenen bleiben @@ -437,13 +425,13 @@ export function generatePlan( for (const d of drawings) { const greyed = categoryDisplay(d.categoryCode).greyed; if (compact && isCompactUnderlayEligible(d)) { - addDrawing2DWithoutLines(primitives, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator); + addDrawing2DWithoutLines(drawingPrims, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator); const key = `${greyed ? 1 : 0}:${d.categoryCode}`; const grp = underGroups.get(key); if (grp) grp.ds.push(d); else underGroups.set(key, { ds: [d], greyed }); } else { - addDrawing2D(primitives, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator, !mono); + addDrawing2D(drawingPrims, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator, !mono); } } const underlay: UnderlayGroup[] = []; @@ -474,18 +462,10 @@ export function generatePlan( // Sichtbarkeit über die Kategorie "90" (Referenzen). pushGroups(G_SOLIDS, G_SECTIONS); - // Schwarz-Weiss (mono): nachträglich alle Farben auf reine Tinte zwingen. - // Element-/Kategorie-/Hatch-Farben werden ignoriert, Füllungen werden weiss, - // Musterlinien/Striche schwarz — so entsteht ein reiner S/W-Plan. - // Abzugskörper (Aussparungen/Durchbrüche): von Wand-/Stützen-/Decken-Poché abziehen. - // Ersetzte Primitive erkennt der GPU-Pfad selbst (Identität); verschiebt das Zerlegen die - // Indizes, werden die Kern-Abschnitte neu ausgerichtet. - if (subtractVoidsInPlan(primitives, project, (floor?.baseElevation ?? 0) + (floor?.cutHeight ?? 1.0))) realignRuns(primitives, runs); - // Baurechts-Verstösse über allem (Signal, soll nicht unter der Wand-Poché verschwinden). - if (includeGlobal) addSiteViolations(primitives, project, floorId); - - if (mono) toMono(primitives); + const violations: Primitive[] = []; + if (includeGlobal) addSiteViolations(violations, project, floorId); + pieces.push(violations); // Georeferenzierte Luftbilder als Hintergrund-Ebenen (nur interaktive Ansicht, // nicht Teil der Vektor-Primitive) — im Mono-Modus ausgeblendet (reiner S/W-Plan). @@ -514,13 +494,41 @@ export function generatePlan( ctx: [...g.ctx, lwf], build: (ds: Drawing2D[]) => g.build(ds).map((p) => scalePrimitiveWeights(p, lwf)), })); - // Mono färbt die Objekte um, der Massstab ersetzt sie: dann gilt der Puffer nicht mehr. - const keepRuns = !mono && lwf === 1 && runs.length > 0; - return { - primitives: lwf === 1 ? primitives : primitives.map((p) => scalePrimitiveWeights(p, lwf)), + const rest = { bounds: computeBounds(project, drawings, dom.buf?.bounds, primitives.slice(0, underlayCount)), backgroundImages, ...(scaledUnderlay.length ? { underlay: scaledUnderlay } : {}), + }; + const hasVoids = voidPrisms(project).length > 0; + // Ohne Abzugskörper, Mono und Strichstärken-Massstab bleibt der Plan lazy: die Kern-Primitive + // werden erst bei Bedarf gelesen. + if (!hasVoids && !mono && lwf === 1) return lazyPlan(rest, pieces); + + // Sonst wie bisher als Liste: die Schritte unten verändern Primitive. + const all: Primitive[] = []; + const runs: PlanBufRun[] = []; + for (const pc of pieces) { + if (isBufPiece(pc)) { + runs.push({ at: all.length, buf: pc.buf, from: pc.from, to: pc.to }); + for (let i = pc.from; i < pc.to; i++) all.push(pc.buf.prim(i)); + } else for (const pr of pc) all.push(pr); + } + // Abzugskörper (Aussparungen/Durchbrüche): von Wand-/Stützen-/Decken-Poché abziehen. + // Ersetzte Primitive erkennt der GPU-Pfad selbst (Identität); verschiebt das Zerlegen die + // Indizes, werden die Kern-Abschnitte neu ausgerichtet. Die Baurechts-Verstösse liegen über + // allem und haben keine Bauteil-Id — das Abziehen lässt sie unverändert. + if (hasVoids && subtractVoidsInPlan(all, project, (floor?.baseElevation ?? 0) + (floor?.cutHeight ?? 1.0))) realignRuns(all, runs); + + // Schwarz-Weiss (mono): nachträglich alle Farben auf reine Tinte zwingen. + // Element-/Kategorie-/Hatch-Farben werden ignoriert, Füllungen werden weiss, + // Musterlinien/Striche schwarz — so entsteht ein reiner S/W-Plan. + if (mono) toMono(all); + + // Mono färbt die Objekte um, der Massstab ersetzt sie: dann gilt der Puffer nicht mehr. + const keepRuns = !mono && lwf === 1 && runs.length > 0; + return { + primitives: lwf === 1 ? all : all.map((p) => scalePrimitiveWeights(p, lwf)), + ...rest, ...(keepRuns ? { bufRuns: runs } : {}), }; } @@ -593,10 +601,13 @@ export function generateVisibleLevelsPlan( ? project.drawingLevels.filter((l) => l.kind === active.kind && l.id !== activeLevelId) : []; - const primitives: Primitive[] = []; + // Stücke der Ebenen hintereinander (lazy, s. `planLazy.ts`): die Primitive werden dabei nicht + // gelesen. Früher eine `for`-Schleife statt `push(...p.primitives)` (Argumentzahl-Grenze bei + // Kataster-Importen) — die Stücke umgehen beides. + const pieces: PlanPiece[] = []; + let count = 0; const greyedRanges: Array<[number, number]> = []; const underlay: UnderlayGroup[] = []; - const bufRuns: PlanBufRun[] = []; const bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }; const extend = (b: Plan["bounds"]) => { bounds.minX = Math.min(bounds.minX, b.minX); @@ -624,20 +635,15 @@ export function generateVisibleLevelsPlan( compactUnderlay, ); for (const g of p.underlay ?? []) underlay.push({ ...g, tint: d.greyed, above: false }); - // KEIN `primitives.push(...p.primitives)`: bei grossen Importen (z. B. ein - // Kataster-DXF einer ganzen Stadt, hunderttausende Drawing2D-Elemente → - // ebenso viele Primitives) sprengt der Spread-Operator die Argumentzahl- - // Grenze von `push` (RangeError "Maximum call stack size exceeded") — s. - // dieselbe, bereits dokumentierte Falle in `swissBuildings3d.ts::concatMeshes`/ - // `dwgParser.ts`. Reine `for`-Schleife ist unbegrenzt sicher. - const from = primitives.length; - for (const pr of p.primitives) primitives.push(pr); - shiftRuns(p.bufRuns, from, bufRuns); - if (d.greyed && primitives.length > from) greyedRanges.push([from, primitives.length]); + const from = count; + const n = planCount(p); + for (const pc of piecesOf(p)) pieces.push(pc); + count += n; + if (d.greyed && n > 0) greyedRanges.push([from, count]); // Leere Ebenen melden als Platzhalter (0,0)–(1,1) — NICHT mitzählen: sonst zog // jede leere Nachbar-Ebene den Ausschnitt bis zum Ursprung (bei Landes- // koordinaten ~2,7 Mio. m daneben → "Einpassen" zeigte nichts). - if (p.primitives.length > 0 || p.underlay) extend(p.bounds); + if (n > 0 || p.underlay) extend(p.bounds); } const activePlan = generatePlan( @@ -653,20 +659,21 @@ export function generateVisibleLevelsPlan( false, compactUnderlay, ); - shiftRuns(activePlan.bufRuns, primitives.length, bufRuns); - for (const pr of activePlan.primitives) primitives.push(pr); + const activeCount = planCount(activePlan); + for (const pc of piecesOf(activePlan)) pieces.push(pc); for (const g of activePlan.underlay ?? []) underlay.push(g); // Aktive Ebene leer UND keine Nachbar-Ebene mit Inhalt → Platzhalter-Ausmass. - if (activePlan.primitives.length > 0 || activePlan.underlay || bounds.minX === Infinity) extend(activePlan.bounds); + if (activeCount > 0 || activePlan.underlay || bounds.minX === Infinity) extend(activePlan.bounds); - return { - primitives, - bounds, - backgroundImages: activePlan.backgroundImages, - ...(greyedRanges.length ? { greyedRanges } : {}), - ...(underlay.length ? { underlay } : {}), - ...(bufRuns.length ? { bufRuns } : {}), - }; + return lazyPlan( + { + bounds, + backgroundImages: activePlan.backgroundImages, + ...(greyedRanges.length ? { greyedRanges } : {}), + ...(underlay.length ? { underlay } : {}), + }, + pieces, + ); } // ── Schnitt/Ansicht (abgeleitete Projektion aus render3d::section) ────────────── diff --git a/src/plan/planBuf.test.ts b/src/plan/planBuf.test.ts index 3c739fc4..f33e1283 100644 --- a/src/plan/planBuf.test.ts +++ b/src/plan/planBuf.test.ts @@ -140,7 +140,7 @@ describe("Plan-Puffer v2", () => { const prims = Object.values(PRIMS); const lean = encodePlanBuf(prims, { lean: true }); expect(lean.byteLength).toBeLessThan(encodePlanBuf(prims).byteLength); - expect(() => decodePlanBuf(lean)).toThrow(); + expect(() => decodePlanBuf(lean).prims).toThrow(); // Die GPU-Kompilierung liest beide gleich. const a = core().gpu_compile_flat(lean, 0, prims.length, 90, true); const b = core().gpu_compile_flat(encodePlanBuf(prims), 0, prims.length, 90, true); diff --git a/src/plan/planBuf.ts b/src/plan/planBuf.ts index c5ca8575..f6106c2a 100644 --- a/src/plan/planBuf.ts +++ b/src/plan/planBuf.ts @@ -446,10 +446,21 @@ export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions = return new Uint8Array(out); } -/** Gelesener Plan-Puffer (Kern-Ergebnis); `bytes` bleibt für die GPU-Kompilierung erhalten. */ +/** + * Gelesener Plan-Puffer (Kern-Ergebnis); `bytes` bleibt für die GPU-Kompilierung erhalten. + * Die Primitive entstehen erst bei Bedarf ([K3d]): `prim(i)` liest einen Eintrag, `prims` alle + * (dieselben Objekte — einmal gelesen, bleibt ein Eintrag dasselbe Objekt). + */ export interface DecodedPlanBuf { bytes: Uint8Array; - prims: Primitive[]; + /** Alle Primitive (beim ersten Zugriff gelesen). */ + readonly prims: Primitive[]; + /** Anzahl Einträge. */ + count: number; + /** Eintrag `i` als Primitiv (gelesen bei Bedarf, danach gemerkt). */ + prim(i: number): Primitive; + /** Typ-Kennung des Eintrags `i` (1 polygon · 2 line · … · 6 text · 7 drawingText · 8 drawingTextPath · 9 drawingImage). */ + tag(i: number): number; groups: Array<[number, number]>; bounds?: [number, number, number, number]; /** Inhalts-Hash je Primitiv (vom Kern; Schlüssel des GPU-Chunk-Caches) oder null. */ @@ -458,7 +469,6 @@ export interface DecodedPlanBuf { hold: number; } -/** UTF-16-Einheiten → ein String (exakt, auch einzelne Surrogate). */ function unitsToString(u: Uint16Array): string { let s = ""; for (let i = 0; i < u.length; i += 8192) { @@ -499,11 +509,13 @@ export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf { const nF64 = poolAt + nPool; if (!Number.isInteger(nF64) || bytes.byteLength !== nF64 * 8 + nUnits * 2) bad("Länge"); const f = new Float64Array(bytes.buffer, bytes.byteOffset, nF64); - const all = unitsToString(new Uint16Array(bytes.buffer, bytes.byteOffset + nF64 * 8, nUnits)); + // Texte erst beim ersten Zugriff als ein String gelesen. + let all: string | null = null; const strs: Array = new Array(nStrings); const S = (i: number): string => { let s = strs[i]; if (s === undefined) { + all ??= unitsToString(new Uint16Array(bytes.buffer, bytes.byteOffset + nF64 * 8, nUnits)); const o = f[strAt + 2 * i]; s = all.slice(o, o + f[strAt + 2 * i + 1]); strs[i] = s; @@ -511,13 +523,23 @@ export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf { return s; }; // Schraffuren: einmal je Eintrag aus dem JSON (geteilt von allen Polygonen). - const hatchList: HatchRender[] = []; + // JSON je Schraffur erst beim ersten Polygon, das sie braucht (dann geteilt). + const hatchJs: number[] = []; + const hatchObjs: Array = new Array(nHatches); + const hatchAtIdx = (h: number): HatchRender => { + let o = hatchObjs[h]; + if (o === undefined) { + const js = hatchJs[h]; + o = js >= 0 ? (JSON.parse(S(js)) as HatchRender) : (undefined as unknown as HatchRender); + hatchObjs[h] = o; + } + return o; + }; let k = hatchAt; for (let i = 0; i < nHatches; i++) { // [jsonStr, pattern, kind, flags, scale, angle, color, lineWeight, ox, oy, seed, density, // lengthMin, lengthMax, nDash, dash…, (Motiv: length, nPts, x,y…)] - const js = f[k]; - hatchList.push(js >= 0 ? (JSON.parse(S(js)) as HatchRender) : (undefined as unknown as HatchRender)); + hatchJs.push(f[k]); const hf = f[k + 3]; k += 15 + f[k + 14]; if (hf & 64) k += 2 + 2 * f[k + 1]; @@ -551,8 +573,7 @@ export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf { found.sort((a, b) => a[0] - b[0]); for (const [kk, id] of found) o[PICK_KEYS[kk - 1]] = id; }; - const prims: Primitive[] = new Array(nPrims); - for (let i = 0; i < nPrims; i++) { + const read = (i: number): Primitive => { let r = recAt + f[offAt + i]; const tag = f[r]; const fl = f[r + 1]; @@ -563,7 +584,7 @@ export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf { switch (tag) { case 1: { o = { kind: "polygon", pts: pts(f[r + 5], f[r + 6]), fill: S(f[r]), stroke: S(f[r + 1]), strokeWidthMm: f[r + 2] }; - if (f[r + 3] >= 0) o.hatch = hatchList[f[r + 3]]; + if (f[r + 3] >= 0) o.hatch = hatchAtIdx(f[r + 3]); if (fl & F_GREYED_SET) o.greyed = (fl & F_GREYED) !== 0; if (fl & F_OPACITY) o.opacity = f[r + 4]; let t = r + 7; @@ -653,11 +674,33 @@ export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf { default: bad(`Primitiv-Typ ${tag}`); } - prims[i] = o as unknown as Primitive; - } + return o as unknown as Primitive; + }; + // Einmal gelesene Einträge bleiben dieselben Objekte (Identität zählt für `Plan.bufRuns`). + const cache: Array = new Array(nPrims); + const prim = (i: number): Primitive => { + if (!(i >= 0 && i < nPrims)) bad(`Eintrag ${i}`); + let p = cache[i]; + if (p === undefined) { + p = read(i); + cache[i] = p; + } + return p; + }; + let allPrims: Primitive[] | null = null; return { bytes, - prims, + get prims(): Primitive[] { + if (!allPrims) { + const out: Primitive[] = new Array(nPrims); + for (let i = 0; i < nPrims; i++) out[i] = prim(i); + allPrims = out; + } + return allPrims; + }, + count: nPrims, + prim, + tag: (i: number): number => f[recAt + f[offAt + i]], groups, bounds: flags & 2 ? [hd[12], hd[13], hd[14], hd[15]] : undefined, hashes: hashes ? new Float64Array(bytes.buffer, bytes.byteOffset + hashAt * 8, nPrims) : null, diff --git a/src/plan/planLazy.ts b/src/plan/planLazy.ts new file mode 100644 index 00000000..5374cace --- /dev/null +++ b/src/plan/planLazy.ts @@ -0,0 +1,216 @@ +/** + * Plan mit lazy gelesenen Primitiven ([K3d]): `generatePlan` setzt einen Plan aus Stücken zusammen + * — Abschnitten eines Kern-Plan-Puffers (`planDomains`) und Listen, die TS selbst erzeugt + * (2D-Zeichnungen, Schatten, Baurecht). `plan.primitives` entsteht erst beim ersten Zugriff; die + * Verbraucher im Kern (Szene, Auswahl, Fang, SVG, DXF) lesen die Stücke direkt (`planParts.ts`), + * Einzelzugriffe gehen über {@link planPrimAt}, Texte/Bilder über {@link planTextEntries}. + * + * Wer einen Plan umbaut (`{ ...plan, primitives: … }`), bekommt einen gewöhnlichen Plan; die + * Stücke gelten nur für das Objekt, das {@link lazyPlan} erzeugt hat. Die gelesene Liste + * `primitives` eines solchen Plans wird nicht verändert (Konvention wie bei allen Plänen). + */ + +import type { Plan, PlanBufRun, Primitive } from "./generatePlan"; +import type { DecodedPlanBuf } from "./planBuf"; + +/** Abschnitt `[from, to)` eines Kern-Puffers. */ +export interface BufPiece { + buf: DecodedPlanBuf; + from: number; + to: number; +} + +/** Ein Stück: Kern-Abschnitt oder eine Liste von TS-Primitiven. */ +export type PlanPiece = BufPiece | readonly Primitive[]; + +export function isBufPiece(p: PlanPiece): p is BufPiece { + return !Array.isArray(p); +} + +const pieceLen = (p: PlanPiece): number => (isBufPiece(p) ? p.to - p.from : p.length); + +interface LazyState { + pieces: PlanPiece[]; + /** Erster Plan-Index je Stück. */ + starts: number[]; + count: number; +} + +const lazyState = new WeakMap(); +/** Lazy Pläne, deren `primitives` schon gelesen wurden. */ +const readPlans = new WeakSet(); + +/** + * Plan aus Stücken; `primitives` wird beim ersten Zugriff gelesen (und bleibt dann dieselbe + * Liste). `bufRuns` folgen aus den Kern-Abschnitten. + */ +export function lazyPlan(rest: Omit, pieces: readonly PlanPiece[]): Plan { + const ps: PlanPiece[] = []; + for (const p of pieces) { + // Leere Stücke weglassen; Kern-Abschnitte bleiben getrennt wie erzeugt (Chunk-Grenzen der GPU). + if (pieceLen(p) > 0) ps.push(p); + } + const starts: number[] = []; + const runs: PlanBufRun[] = []; + let count = 0; + for (const p of ps) { + starts.push(count); + if (isBufPiece(p)) runs.push({ at: count, buf: p.buf, from: p.from, to: p.to }); + count += pieceLen(p); + } + const plan = {} as Plan; + let mat: Primitive[] | null = null; + Object.defineProperty(plan, "primitives", { + enumerable: true, + configurable: true, + get(): Primitive[] { + if (!mat) { + const out: Primitive[] = new Array(count); + let k = 0; + for (const p of ps) { + if (isBufPiece(p)) { + for (let i = p.from; i < p.to; i++) out[k++] = p.buf.prim(i); + } else { + for (const q of p) out[k++] = q; + } + } + mat = out; + readPlans.add(plan); + } + return mat; + }, + set(v: Primitive[]) { + // Ersetzt: ab jetzt ein gewöhnlicher Plan. + Object.defineProperty(plan, "primitives", { value: v, writable: true, enumerable: true, configurable: true }); + lazyState.delete(plan); + }, + }); + Object.assign(plan, rest); + if (runs.length) plan.bufRuns = runs; + else delete plan.bufRuns; + lazyState.set(plan, { pieces: ps, starts, count }); + return plan; +} + +/** Stücke eines lazy Plans (oder null bei einem gewöhnlichen Plan). */ +export function lazyPieces(plan: Plan): readonly PlanPiece[] | null { + return lazyState.get(plan)?.pieces ?? null; +} + +/** Ist `plan` ein lazy Plan, dessen `primitives` noch nicht gelesen wurden? (Messung/Tests.) */ +export function isLazyUnread(plan: Plan): boolean { + return lazyState.has(plan) && !readPlans.has(plan); +} + +/** + * Stücke eines beliebigen Plans: lazy → seine Stücke; sonst die Liste, an den (per + * Objekt-Identität geprüften) Kern-Abschnitten `bufRuns` zerlegt. + */ +export function piecesOf(plan: Plan): readonly PlanPiece[] { + const lazy = lazyPieces(plan); + if (lazy) return lazy; + const prims = plan.primitives; + const out: PlanPiece[] = []; + let at = 0; + const runs = [...(plan.bufRuns ?? [])].sort((a, b) => a.at - b.at); + for (const r of runs) { + if (r.at < at) continue; + const n = Math.min(r.to - r.from, prims.length - r.at); + let ok = n > 0; + for (let k = 0; ok && k < n; k++) ok = prims[r.at + k] === r.buf.prims[r.from + k]; + if (!ok) continue; + if (r.at > at) out.push(prims.slice(at, r.at)); + out.push({ buf: r.buf, from: r.from, to: r.from + n }); + at = r.at + n; + } + if (at < prims.length) out.push(at === 0 ? prims : prims.slice(at)); + return out; +} + +/** Anzahl Primitive (ohne sie zu lesen). */ +export function planCount(plan: Plan): number { + const s = lazyState.get(plan); + return s ? s.count : plan.primitives.length; +} + +/** Primitiv `i` (bei einem lazy Plan nur dieser Eintrag gelesen); `undefined` ausserhalb. */ +export function planPrimAt(plan: Plan, i: number): Primitive | undefined { + const s = lazyState.get(plan); + if (!s) return plan.primitives[i]; + if (!(i >= 0 && i < s.count) || !Number.isInteger(i)) return undefined; + // Letztes Stück mit Start ≤ i. + let lo = 0; + let hi = s.starts.length - 1; + while (lo < hi) { + const mid = (lo + hi + 1) >> 1; + if (s.starts[mid] <= i) lo = mid; + else hi = mid - 1; + } + const p = s.pieces[lo]; + const k = i - s.starts[lo]; + return isBufPiece(p) ? p.buf.prim(p.from + k) : p[k]; +} + +/** Text-/Bild-Primitive (`text`, `drawingText`, `drawingTextPath`, `drawingImage`). */ +export type TextEntryPrim = Extract; + +/** Typ-Kennungen der Text-/Bild-Einträge im Plan-Puffer (6…9, s. `plan_buf.rs`). */ +const TEXT_TAG_MIN = 6; +const TEXT_TAG_MAX = 9; + +const isTextKind = (p: Primitive): p is TextEntryPrim => + p.kind === "text" || p.kind === "drawingText" || p.kind === "drawingTextPath" || p.kind === "drawingImage"; + +const textCache = new WeakMap>(); + +/** + * Text- und Bild-Einträge eines Plans in Zeichenreihenfolge mit ihrem Plan-Index — bei einem + * lazy Plan aus den Typ-Kennungen der Puffer gelesen (nur diese Einträge werden dekodiert). + * Einmal je Plan. + */ +export function planTextEntries(plan: Plan): ReadonlyArray<{ i: number; p: TextEntryPrim }> { + let out = textCache.get(plan); + if (out) return out; + const list: Array<{ i: number; p: TextEntryPrim }> = []; + const s = lazyState.get(plan); + if (s) { + s.pieces.forEach((pc, n) => { + const at = s.starts[n]; + if (isBufPiece(pc)) { + for (let j = pc.from; j < pc.to; j++) { + const t = pc.buf.tag(j); + if (t >= TEXT_TAG_MIN && t <= TEXT_TAG_MAX) list.push({ i: at + j - pc.from, p: pc.buf.prim(j) as TextEntryPrim }); + } + } else { + pc.forEach((p, k) => { + if (isTextKind(p)) list.push({ i: at + k, p }); + }); + } + }); + } else { + plan.primitives.forEach((p, i) => { + if (isTextKind(p)) list.push({ i, p }); + }); + } + out = list; + textCache.set(plan, out); + return out; +} + +/** + * Plan um Primitive davor/danach ergänzt, ohne die Primitive des Plans zu lesen (Überlagerungen + * der Ansicht). Gedimmte Bereiche wandern mit. + */ +export function planWithExtra(plan: Plan, before: readonly Primitive[], after: readonly Primitive[], patch: Partial> = {}): Plan { + const rest = planFields(plan); + const shift = before.length; + const greyed = plan.greyedRanges?.map(([a, b]): [number, number] => [a + shift, b + shift]); + return lazyPlan({ ...rest, ...(greyed ? { greyedRanges: greyed } : {}), ...patch }, [before, ...piecesOf(plan), after]); +} + +/** Alle Felder eines Plans ausser `primitives` und `bufRuns`, ohne den Getter auszulösen. */ +export function planFields(plan: Plan): Omit { + const out: Record = {}; + for (const k of Object.keys(plan)) if (k !== "primitives" && k !== "bufRuns") out[k] = (plan as unknown as Record)[k]; + return out as unknown as Omit; +} diff --git a/src/plan/planParts.ts b/src/plan/planParts.ts index 29b56eb9..509fff7a 100644 --- a/src/plan/planParts.ts +++ b/src/plan/planParts.ts @@ -13,6 +13,7 @@ import type { Plan, PlanBufRun, Primitive } from "./generatePlan"; import { encodePlanBuf } from "./planBuf"; +import { isBufPiece, lazyPieces, type PlanPiece } from "./planLazy"; import { core } from "../engine/coreWasm"; /** Ein im Kern ablegbarer Puffer (Kern-Ergebnis `DecodedPlanBuf` oder eigener). */ @@ -54,21 +55,58 @@ function verifiedRuns(primitives: readonly Primitive[], runs: readonly PlanBufRu return clean; } -const cache = new WeakMap(); +const cache = new WeakMap(); /** - * Abschnitte eines Plans; einmal je `plan.primitives` (und Modus) gebaut. `texts`: der eigene - * Puffer trägt Texte/Bilder mit JSON (SVG-Export) — sonst nur deren Typ (Szene, Auswahl). + * Abschnitte eines Plans; einmal je Plan (lazy, s. `planLazy.ts`) bzw. je `plan.primitives` (und + * Modus) gebaut. `texts`: der eigene Puffer trägt Texte/Bilder mit JSON (SVG-Export, Auswahl) — + * sonst nur deren Typ (Szene). Ein lazy Plan wird dabei nicht gelesen. */ export function planParts(plan: Plan, texts = false): PlanParts { - const prims = plan.primitives; - let c = cache.get(prims); + const lazy = lazyPieces(plan); + const key: object = lazy ? plan : plan.primitives; + let c = cache.get(key); if (!c) { c = { text: null, noText: null }; - cache.set(prims, c); + cache.set(key, c); } const hit = texts ? c.text : c.noText; if (hit) return hit; + const out = lazy ? partsFromPieces(lazy, texts) : partsFromRuns(plan, texts); + if (texts) c.text = out; + else c.noText = out; + return out; +} + +/** Abschnitte aus den Stücken eines lazy Plans: TS-Listen zusammen in einen eigenen Puffer. */ +function partsFromPieces(pieces: readonly PlanPiece[], texts: boolean): PlanParts { + const rest: Primitive[] = []; + for (const pc of pieces) if (!isBufPiece(pc)) for (const p of pc) rest.push(p); + const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: false }), hold: 0 } : null; + const bufs: HoldableBuf[] = []; + const segs: number[] = []; + let ownAt = 0; + let count = 0; + for (const pc of pieces) { + if (isBufPiece(pc)) { + let i = bufs.indexOf(pc.buf); + if (i < 0) i = bufs.push(pc.buf) - 1; + segs.push(i, pc.from, pc.to); + count += pc.to - pc.from; + } else if (pc.length) { + let i = bufs.indexOf(own!); + if (i < 0) i = bufs.push(own!) - 1; + segs.push(i, ownAt, ownAt + pc.length); + ownAt += pc.length; + count += pc.length; + } + } + return { bufs, segs, count }; +} + +/** Abschnitte eines gewöhnlichen Plans über die (per Objekt-Identität geprüften) `bufRuns`. */ +function partsFromRuns(plan: Plan, texts: boolean): PlanParts { + const prims = plan.primitives; const runs = verifiedRuns(prims, plan.bufRuns); const bufs: HoldableBuf[] = []; const bufIdx = new Map(); @@ -111,10 +149,7 @@ export function planParts(plan: Plan, texts = false): PlanParts { ri++; } } - const out: PlanParts = { bufs, segs, count: prims.length }; - if (texts) c.text = out; - else c.noText = out; - return out; + return { bufs, segs, count: prims.length }; } /** Gedimmte Bereiche flach (`Plan.greyedRanges`). */ From 70bb23f2bce5e306a5762eb465e79490a02915d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 01:30:21 +0000 Subject: [PATCH 2/5] =?UTF-8?q?[K3d]=20Rahmen-Auswahl,=20Text-/Bild-Treffe?= =?UTF-8?q?r=20im=20Kern;=20PlanView-Overlay=20liest=20nur=20Text-Eintr?= =?UTF-8?q?=C3=A4ge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit plan_pick.rs: Rahmen-Auswahl über Polygone je Pick-Art und über 2D-Zeichnungen (Linien, Polygone, abgetastete Kreise/Bögen, Text-/Bild-Rahmen, Unterlage ausgenommen), Einzeltext-/Bild-Treffer und Form einer Zeichnung (drawingLabel). Gleichheit gegen die alte TS-Fassung (temporärer Test, 53 870 Vergleiche: 200 Zufallspläne, Beispiel EG/OG/UG, Überlagerung, bigSample(6)). TS-Fassungen marqueeHit*/marqueeHitDrawings gelöscht, Tests auf den Kern umgestellt. PlanView: Einzelzugriffe über planPrimAt, SVG-Kandidaten/Culling mit GPU nur aus den Text-Einträgen (planTextEntries), Schraffur-Muster nur ohne GPU; planSceneTexts und native Text-Sync lesen nur Text-Einträge; Überlagerung in viewportContent ohne Lesen (planWithExtra). Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src-tauri/core/src/plan_pick.rs | 302 ++++++++++++++++++++++- src-tauri/core/src/web/plan_pick.rs | 42 +++- src/core/index.ts | 13 +- src/plan/planLazy.test.ts | 75 ++++++ src/plan/planView/geometry.test.ts | 15 +- src/plan/planView/geometry.ts | 140 +---------- src/plan/planView/marquee.test.ts | 20 +- src/plan/planView/planPick.ts | 68 ++++- src/plan/planView/underlayAccess.test.ts | 6 +- src/plan/toRenderScene.ts | 6 +- src/views/plan/PlanView.tsx | 160 +++++------- src/views/plan/useNativePlanRenderer.ts | 4 +- src/views/viewportContent.tsx | 7 +- 13 files changed, 594 insertions(+), 264 deletions(-) create mode 100644 src/plan/planLazy.test.ts diff --git a/src-tauri/core/src/plan_pick.rs b/src-tauri/core/src/plan_pick.rs index 3f4efd69..876a9a41 100644 --- a/src-tauri/core/src/plan_pick.rs +++ b/src-tauri/core/src/plan_pick.rs @@ -19,8 +19,9 @@ use crate::jsmath::hypot; use crate::jsnum; -use crate::plan_buf::{whole, View, F_IDS, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_LINE, T_POLYGON}; +use crate::plan_buf::{whole, View, F_IDS, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_IMAGE, T_LINE, T_POLYGON, T_TEXT_PATH}; use crate::plan_parts::pick_ids; +use std::cell::OnceCell; use std::collections::HashMap; use std::rc::Rc; @@ -294,6 +295,31 @@ pub struct PickIndex { /// (Art, Id) → Indizes aufsteigend. owners: HashMap<(u32, u32), Vec>, interned: HashMap, + /// Einträge mit nicht-leerer `drawingId` (Linie, Polygon, Kreis, Bogen, Text, Textpfad, Bild): + /// (Index, Typ, Id-Nummer) in Plan-Reihenfolge — Rahmen-Auswahl und Text-/Bild-Treffer. + draw_items: Vec<(u32, u32, u32)>, + /// Rahmen von `drawingText`/`drawingImage` mit `drawingId` (aus dem Text-JSON, bei Bedarf). + text_boxes: OnceCell>, +} + +/// Rahmen eines Einzeltexts (wie die Einzelklick-Box in PlanView) bzw. eines Bilds. +#[derive(Clone, Copy)] +struct TextBox { + gi: u32, + image: bool, + min_x: f64, + min_y: f64, + max_x: f64, + max_y: f64, +} + +/// Achsenparalleles Rechteck (Modell-Meter) der Rahmen-Auswahl. +#[derive(Clone, Copy)] +pub struct Rect { + pub min_x: f64, + pub min_y: f64, + pub max_x: f64, + pub max_y: f64, } /// Bounding-Box, NaN ausgelassen (wie `f64::min`). @@ -328,6 +354,8 @@ impl PickIndex { ring_ix: BoxIndex::default(), owners: HashMap::new(), interned: HashMap::new(), + draw_items: Vec::new(), + text_boxes: OnceCell::new(), }; // Segment-Raster wie `buildSegmentIndex` (Ausmass mit Math.min/max, NaN steckt an). let mut seg_boxes: Vec<(u32, f64, f64, f64, f64)> = Vec::new(); @@ -394,6 +422,11 @@ impl PickIndex { } } } + if let Some(id) = drawing { + if mask & (1 << 2) != 0 && matches!(tag, T_LINE | T_POLYGON | T_CIRCLE | T_DRAWING_ARC | T_DRAWING_TEXT | T_TEXT_PATH | T_IMAGE) { + ix.draw_items.push((g, tag, id)); + } + } let f = |k: usize| view.word(at + 4 + k); match tag { T_LINE => { @@ -676,6 +709,249 @@ impl PickIndex { hits.sort_unstable(); hits } + + /// Text-JSON eines Eintrags (Texte, Textpfade, Bilder); `None` ohne JSON oder kaputt. + fn json(&self, gi: u32) -> Option { + let (v, i) = self.locate(gi)?; + let si = v.word(v.rec_at(i)? + 4)?; + serde_json::from_str(&v.string(whole(si)?)?).ok() + } + + /// Text-/Bild-Rahmen (einmal je Index, beim ersten Gebrauch aus dem JSON gelesen). + fn boxes(&self) -> &[TextBox] { + self.text_boxes.get_or_init(|| { + let mut out = Vec::new(); + for &(gi, tag, _) in &self.draw_items { + if tag != T_DRAWING_TEXT && tag != T_IMAGE { + continue; + } + let Some(j) = self.json(gi) else { continue }; + let num = |o: &serde_json::Value, k: &str| o.get(k).and_then(|x| x.as_f64()).unwrap_or(f64::NAN); + let pt = |k: &str| j.get(k).map_or((f64::NAN, f64::NAN), |o| (num(o, "x"), num(o, "y"))); + if tag == T_IMAGE { + let (a, b) = pt("min"); + let (c, d) = pt("max"); + out.push(TextBox { gi, image: true, min_x: a, min_y: b, max_x: c, max_y: d }); + } else { + let (ax, ay) = pt("at"); + let h = num(&j, "heightM"); + let len = j.get("text").and_then(|t| t.as_str()).map_or(0, |t| t.encode_utf16().count()) as f64; + // `p.wrapWidth && p.wrapWidth > 0` (fehlend/0/NaN → keine Spalte). + let wrap = j.get("wrapWidth").and_then(|x| x.as_f64()).filter(|w| *w > 0.0); + let single_w = jsnum::max(1.0, len) * h * 0.6; + let w = wrap.unwrap_or(single_w); + let lines = match wrap { + Some(ww) => jsnum::max(1.0, (single_w / ww).ceil()), + None => 1.0, + }; + let pad = h * 0.6; + out.push(TextBox { + gi, + image: false, + min_x: ax - pad, + min_y: ay - lines * h * 1.25 - pad, + max_x: ax + w + pad, + max_y: ay + h * 0.4 + pad, + }); + } + } + out + }) + } + + /// Erster `drawingText` (mit `drawingId`) in Plan-Reihenfolge, dessen Rahmen `(x, y)` enthält + /// (wie `pickDrawingText` in PlanView). + pub fn drawing_text_at(&self, x: f64, y: f64) -> Option { + self.boxes().iter().find(|b| !b.image && x >= b.min_x && x <= b.max_x && y >= b.min_y && y <= b.max_y).map(|b| b.gi) + } + + /// Oberstes (zuletzt gezeichnetes) Bild mit `drawingId`, das `(x, y)` enthält. + pub fn drawing_image_at(&self, x: f64, y: f64) -> Option { + self.boxes().iter().rev().find(|b| b.image && x >= b.min_x && x <= b.max_x && y >= b.min_y && y <= b.max_y).map(|b| b.gi) + } + + /// Typ des ersten Eintrags einer Zeichnung, der eine Form benennt (Linie, Polygon, Text, + /// Textpfad, Kreis, Bogen, Bild — wie `drawingLabel`); `None` ohne solchen. + pub fn drawing_kind(&self, id: &str) -> Option { + let n = self.interned.get(id)?; + for &gi in self.owners.get(&(2, *n))? { + let (v, i) = self.locate(gi)?; + let tag = whole(v.word(v.rec_at(i)?)?)? as u32; + if matches!(tag, T_LINE | T_POLYGON | T_DRAWING_TEXT | T_TEXT_PATH | T_CIRCLE | T_DRAWING_ARC | T_IMAGE) { + return Some(tag); + } + } + None + } + + /// Rahmen-Auswahl über Polygone mit einer Id der Pick-Art `kind` (wie `marqueeHitByField`): + /// `crossing` = ein Band berührt das Rechteck, sonst alle Bänder ganz darin. Ids in der + /// Reihenfolge ihres ersten Auftretens. + pub fn marquee_polygons(&self, kind: u32, rect: Rect, crossing: bool) -> Vec { + let mut order: Vec<(String, bool)> = Vec::new(); + let mut at: HashMap = HashMap::new(); + for p in &self.polys { + let Some((v, i)) = self.locate(p.gi) else { continue }; + let Some(rec) = v.rec(i) else { continue }; + let Some(ids) = pick_ids(&v, &rec) else { continue }; + let Some(&(_, si)) = ids.iter().find(|e| e.0 == kind) else { continue }; + let Some(id) = whole(si).and_then(|k| v.string(k)) else { continue }; + let Some(pts) = self.polygon_pts(p.gi) else { continue }; + let hit = if crossing { poly_touches_rect(&pts, rect) } else { poly_enclosed_by_rect(&pts, rect) }; + match at.get(&id) { + // crossing: irgendein Band; Fenster: alle Bänder. + Some(&k) => order[k].1 = if crossing { order[k].1 || hit } else { order[k].1 && hit }, + None => { + at.insert(id.clone(), order.len()); + order.push((id, hit)); + } + } + } + order.into_iter().filter(|e| e.1).map(|e| e.0).collect() + } + + /// Rahmen-Auswahl über 2D-Zeichnungen (wie `marqueeHitDrawings`): je Zeichnung alle Punkte + /// (Linien-Enden, Polygon-Ecken, abgetastete Kreise/Bögen, Text-/Bild-Rahmen); `skip` = + /// Zeichnungen, die der Aufrufer selbst prüft. Ids in der Reihenfolge ihres ersten Auftretens. + pub fn marquee_drawings(&self, rect: Rect, crossing: bool, skip: &[&str]) -> Vec { + let skip_n: Vec = skip.iter().filter_map(|s| self.interned.get(*s).copied()).collect(); + let names: HashMap = self.interned.iter().map(|(k, v)| (*v, k.as_str())).collect(); + let boxes: HashMap = if self.draw_items.iter().any(|e| e.1 == T_DRAWING_TEXT || e.1 == T_IMAGE) { + self.boxes().iter().map(|b| (b.gi, *b)).collect() + } else { + HashMap::new() + }; + let mut order: Vec<(u32, Vec)> = Vec::new(); + let mut at: HashMap = HashMap::new(); + for &(gi, tag, id) in &self.draw_items { + if skip_n.contains(&id) { + continue; + } + let pts: Vec = match tag { + T_LINE => match self.line(gi) { + Some(l) => l.to_vec(), + None => continue, + }, + T_POLYGON => match self.polygon_pts(gi) { + Some(p) => p, + None => continue, + }, + T_CIRCLE => match self.fields::<3>(gi, 4) { + Some([cx, cy, r]) => ring_sample_points(cx, cy, r, None), + None => continue, + }, + T_DRAWING_ARC => match self.fields::<5>(gi, 3) { + Some([cx, cy, r, a0, a1]) => ring_sample_points(cx, cy, r, Some((a0, a1))), + None => continue, + }, + // Bild: min, (max.x, min.y), max, (min.x, max.y) — Text: dieselbe Umlaufrichtung. + T_DRAWING_TEXT | T_IMAGE => match boxes.get(&gi) { + Some(b) => vec![b.min_x, b.min_y, b.max_x, b.min_y, b.max_x, b.max_y, b.min_x, b.max_y], + None => continue, + }, + _ => continue, + }; + match at.get(&id) { + Some(&k) => order[k].1.extend_from_slice(&pts), + None => { + at.insert(id, order.len()); + order.push((id, pts)); + } + } + } + order + .into_iter() + .filter(|(_, pts)| if crossing { poly_touches_rect(pts, rect) } else { poly_enclosed_by_rect(pts, rect) }) + .filter_map(|(id, _)| names.get(&id).map(|s| s.to_string())) + .collect() + } +} + +/// Punkte auf einem Kreis-/Bogen-Ring (wie `ringSamplePoints`): Vollkreis 32 Schritte, Bogen +/// anteilig (mindestens 4), Endpunkt inklusive. +fn ring_sample_points(cx: f64, cy: f64, r: f64, arc: Option<(f64, f64)>) -> Vec { + let tau = std::f64::consts::PI * 2.0; + let (start, sweep, steps) = match arc { + None => (0.0, tau, 32.0), + Some((a0, a1)) => { + let mut sw = (((a1 - a0) % tau) + tau) % tau; + if sw == 0.0 || sw.is_nan() { + sw = tau; + } + (a0, sw, jsnum::max(4.0, jsnum::round((sw / tau) * 32.0))) + } + }; + let mut out = Vec::new(); + let mut i = 0.0; + while i <= steps { + let a = start + (sweep * i) / steps; + out.push(cx + r * jsnum::cos(a)); + out.push(cy + r * jsnum::sin(a)); + i += 1.0; + } + out +} + +/// Alle Ecken im Rechteck (`polyEnclosedByRect`); leer → nein. +fn poly_enclosed_by_rect(poly: &[f64], r: Rect) -> bool { + if poly.len() < 2 { + return false; + } + poly.chunks_exact(2).all(|p| p[0] >= r.min_x && p[0] <= r.max_x && p[1] >= r.min_y && p[1] <= r.max_y) +} + +/// Orientierung (b − a) × (c − a) (`cross3`). +fn cross3(a: (f64, f64), b: (f64, f64), c: (f64, f64)) -> f64 { + (b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0) +} + +/// `onSegment` bei kollinearen Punkten. +fn on_segment(a: (f64, f64), b: (f64, f64), p: (f64, f64)) -> bool { + jsnum::min(a.0, b.0) <= p.0 && p.0 <= jsnum::max(a.0, b.0) && jsnum::min(a.1, b.1) <= p.1 && p.1 <= jsnum::max(a.1, b.1) +} + +/// `segmentsIntersect` (inkl. Berührung). +fn segments_intersect(a: (f64, f64), b: (f64, f64), c: (f64, f64), d: (f64, f64)) -> bool { + let d1 = cross3(c, d, a); + let d2 = cross3(c, d, b); + let d3 = cross3(a, b, c); + let d4 = cross3(a, b, d); + if ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0)) && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0)) { + return true; + } + (d1 == 0.0 && on_segment(c, d, a)) || (d2 == 0.0 && on_segment(c, d, b)) || (d3 == 0.0 && on_segment(a, b, c)) || (d4 == 0.0 && on_segment(a, b, d)) +} + +/// Polygon und Rechteck berühren sich (`polyTouchesRect`): Ecke im Rechteck, Rechteck-Ecke im +/// Polygon oder Kantenschnitt. +fn poly_touches_rect(poly: &[f64], r: Rect) -> bool { + for p in poly.chunks_exact(2) { + if p[0] >= r.min_x && p[0] <= r.max_x && p[1] >= r.min_y && p[1] <= r.max_y { + return true; + } + } + let corners = [(r.min_x, r.min_y), (r.max_x, r.min_y), (r.max_x, r.max_y), (r.min_x, r.max_y)]; + for c in corners { + if point_in_polygon(c.0, c.1, poly) { + return true; + } + } + let n = poly.len() / 2; + if n == 0 { + return false; + } + let mut j = n - 1; + for i in 0..n { + let a = (poly[2 * j], poly[2 * j + 1]); + let b = (poly[2 * i], poly[2 * i + 1]); + for k in 0..4 { + if segments_intersect(a, b, corners[k], corners[(k + 1) % 4]) { + return true; + } + } + j = i; + } + false } #[cfg(test)] @@ -690,4 +966,28 @@ mod tests { assert_eq!(point_seg_dist(0.5, 1.0, 0.0, 0.0, 1.0, 0.0), 1.0); assert_eq!(point_seg_dist_px(3.0, 4.0, 0.0, 0.0, 0.0, 0.0), 5.0); } + + #[test] + fn rechteck_beruehrt_und_umschliesst() { + let r = Rect { min_x: 0.0, min_y: 0.0, max_x: 2.0, max_y: 2.0 }; + let inner = [0.5, 0.5, 1.5, 0.5, 1.5, 1.5]; + let around = [-1.0, -1.0, 3.0, -1.0, 3.0, 3.0, -1.0, 3.0]; + let crossing = [-1.0, 1.0, 3.0, 1.0]; + assert!(poly_enclosed_by_rect(&inner, r) && poly_touches_rect(&inner, r)); + // Rechteck ganz im Polygon: Ecke im Polygon. + assert!(!poly_enclosed_by_rect(&around, r) && poly_touches_rect(&around, r)); + // Strecke quer durch: nur Kantenschnitt. + assert!(poly_touches_rect(&crossing, r)); + assert!(!poly_touches_rect(&[5.0, 5.0, 6.0, 6.0], r)); + assert!(!poly_enclosed_by_rect(&[], r)); + } + + #[test] + fn ring_abtastung_vollkreis_und_bogen() { + assert_eq!(ring_sample_points(0.0, 0.0, 1.0, None).len(), 2 * 33); + // Viertelbogen: 8 Schritte, Endpunkt inklusive. + let q = ring_sample_points(0.0, 0.0, 2.0, Some((0.0, std::f64::consts::FRAC_PI_2))); + assert_eq!(q.len(), 2 * 9); + assert!(q.chunks_exact(2).all(|p| p[0] >= -1e-12 && p[1] >= -1e-12)); + } } diff --git a/src-tauri/core/src/web/plan_pick.rs b/src-tauri/core/src/web/plan_pick.rs index 3f45177c..4937cbb3 100644 --- a/src-tauri/core/src/web/plan_pick.rs +++ b/src-tauri/core/src/web/plan_pick.rs @@ -3,7 +3,7 @@ //! (`pick_index_release`); er hält seine Puffer selbst, Verdrängen im Puffer-Speicher stört ihn //! nicht. Unbekannter Index oder kaputte Eingabe → leeres Ergebnis bzw. −1, nie Panic. -use crate::plan_pick::{ClientMap, PickIndex}; +use crate::plan_pick::{ClientMap, PickIndex, Rect}; use std::cell::RefCell; use wasm_bindgen::prelude::wasm_bindgen; @@ -74,3 +74,43 @@ pub fn pick_owned_by(id: u32, kind: u32, ids: &str) -> Vec { let list: Vec<&str> = ids.split('\0').skip(1).collect(); with(id, |ix| ix.owned_by(kind, &list)).unwrap_or_default() } + +/// Erster Einzeltext (`drawingText` mit `drawingId`) unter dem Punkt oder −1. +#[wasm_bindgen] +pub fn pick_drawing_text(id: u32, x: f64, y: f64) -> f64 { + with(id, |ix| ix.drawing_text_at(x, y)).flatten().map_or(-1.0, |i| i as f64) +} + +/// Oberstes Bild (`drawingImage` mit `drawingId`) unter dem Punkt oder −1. +#[wasm_bindgen] +pub fn pick_drawing_image(id: u32, x: f64, y: f64) -> f64 { + with(id, |ix| ix.drawing_image_at(x, y)).flatten().map_or(-1.0, |i| i as f64) +} + +/// Typ-Kennung des ersten formgebenden Eintrags der Zeichnung `drawing` oder 0. +#[wasm_bindgen] +pub fn pick_drawing_kind(id: u32, drawing: &str) -> u32 { + with(id, |ix| ix.drawing_kind(drawing)).flatten().unwrap_or(0) +} + +fn rect_of(r: &[f64]) -> Option { + let [min_x, min_y, max_x, max_y] = <[f64; 4]>::try_from(r).ok()?; + Some(Rect { min_x, min_y, max_x, max_y }) +} + +/// Rahmen-Auswahl über Polygone der Pick-Art `kind` (`rect` = `[minX, minY, maxX, maxY]`): +/// Ids, jede mit `\0` davor. +#[wasm_bindgen] +pub fn pick_marquee_polygons(id: u32, kind: u32, rect: &[f64], crossing: bool) -> String { + let Some(r) = rect_of(rect) else { return String::new() }; + with(id, |ix| ix.marquee_polygons(kind, r, crossing)).unwrap_or_default().iter().map(|s| format!("\0{s}")).collect() +} + +/// Rahmen-Auswahl über 2D-Zeichnungen; `skip` = Ids (jede mit `\0` davor), die der Aufrufer +/// selbst prüft. Ergebnis wie [`pick_marquee_polygons`]. +#[wasm_bindgen] +pub fn pick_marquee_drawings(id: u32, rect: &[f64], crossing: bool, skip: &str) -> String { + let Some(r) = rect_of(rect) else { return String::new() }; + let skip: Vec<&str> = skip.split('\0').skip(1).collect(); + with(id, |ix| ix.marquee_drawings(r, crossing, &skip)).unwrap_or_default().iter().map(|s| format!("\0{s}")).collect() +} diff --git a/src/core/index.ts b/src/core/index.ts index c1e9ab95..e94cad46 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -254,11 +254,6 @@ export { type ViewBox as ViewBox__plan_planView_geometry, clamp, fitBoxFor, - marqueeHit, - marqueeHitCeilings, - marqueeHitDrawings, - marqueeHitRooms, - marqueeHitStairs, meetScale, mmToPx, pointInPolygon, @@ -277,6 +272,14 @@ export { PlanPickIndex, } from "../plan/planView/planPick"; +export { + planCount, + planPrimAt, + planTextEntries, + planWithExtra, + type TextEntryPrim, +} from "../plan/planLazy"; + export { marqueeHitUnderlay, } from "../plan/planView/underlayAccess"; diff --git a/src/plan/planLazy.test.ts b/src/plan/planLazy.test.ts new file mode 100644 index 00000000..2c89745c --- /dev/null +++ b/src/plan/planLazy.test.ts @@ -0,0 +1,75 @@ +// Lazy Plan ([K3d], `planLazy.ts`): `generatePlan` liest die Kern-Primitive erst bei Bedarf; die +// Verbraucher im Kern (Szene, Auswahl, SVG) und die Text-Einträge kommen ohne aus. + +import { describe, expect, it } from "vitest"; +import { generatePlan, generateVisibleLevelsPlan, materializeUnderlay, type Primitive } from "./generatePlan"; +import { isLazyUnread, planCount, planPrimAt, planTextEntries, planWithExtra } from "./planLazy"; +import { planSceneBin, planToRenderScene } from "./toRenderScene"; +import { planToSvgString } from "../export/planToSvgString"; +import { PlanPickIndex } from "./planView/planPick"; +import { sampleProject } from "../model/sampleProject"; +import { flattenCategories, type Project } from "../model/types"; + +const codes = (p: Project) => new Set(flattenCategories(p.layers).map((c) => c.code)); + +const withText: Project = { + ...sampleProject, + drawings2d: [ + ...sampleProject.drawings2d, + { id: "t1", type: "drawing2d", levelId: "eg", categoryCode: "60", geom: { shape: "text", at: { x: 1, y: 2 }, text: "Hallo", height: 0.3, angle: 0 } }, + { id: "l1", type: "drawing2d", levelId: "eg", categoryCode: "60", geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 3, y: 1 } } }, + ] as Project["drawings2d"], +}; + +describe("lazy Plan", () => { + it("Verbraucher im Kern lesen die Primitive nicht", () => { + const plan = generatePlan(withText, "eg", codes(withText)); + expect(isLazyUnread(plan)).toBe(true); + planSceneBin(plan); + planToRenderScene(plan); + planToSvgString(plan); + const ix = new PlanPickIndex(plan); + ix.topPolygon({ x: 2, y: 2 }); + ix.marquee("wallId", { minX: -100, minY: -100, maxX: 100, maxY: 100 }, false); + ix.drawingTextAt({ x: 1.2, y: 2 }); + ix.release(); + expect(planTextEntries(plan).length).toBeGreaterThan(0); + expect(planPrimAt(plan, 0)).toBeDefined(); + expect(isLazyUnread(plan)).toBe(true); + }); + + it("Einzelzugriff, Text-Einträge und Anzahl == gelesene Liste (dieselben Objekte)", () => { + for (const l of ["eg", "og"]) { + const plan = generatePlan(withText, l, codes(withText)); + const n = planCount(plan); + const single = Array.from({ length: n }, (_, i) => planPrimAt(plan, i)); + const texts = planTextEntries(plan); + expect(plan.primitives.length).toBe(n); + single.forEach((p, i) => expect(p).toBe(plan.primitives[i])); + const want = plan.primitives + .map((p, i) => ({ p, i })) + .filter((e) => e.p.kind === "text" || e.p.kind === "drawingText" || e.p.kind === "drawingTextPath" || e.p.kind === "drawingImage"); + expect(texts.map((e) => e.i)).toEqual(want.map((e) => e.i)); + texts.forEach((e, k) => expect(e.p).toBe(want[k].p)); + expect(planPrimAt(plan, n)).toBeUndefined(); + } + }); + + it("Überlagerung, kompakte Unterlage und Anhängen bleiben lazy und gleich", () => { + const plan = generateVisibleLevelsPlan(withText, "og", codes(withText), undefined, "mittel", false, false, undefined, 100, true); + expect(isLazyUnread(plan)).toBe(true); + const mat = materializeUnderlay(plan); + const extra: Primitive = { kind: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 1 }, cls: "x", weightMm: 0.1 }; + const ext = planWithExtra(mat, [extra], [extra]); + expect(isLazyUnread(mat) && isLazyUnread(ext)).toBe(true); + expect(ext.primitives).toEqual([extra, ...mat.primitives, extra]); + expect(ext.greyedRanges).toEqual(mat.greyedRanges?.map(([a, b]) => [a + 1, b + 1])); + // Eager zum Vergleich: dieselbe Liste wie die gelesene. + expect(plan.primitives.length).toBe(planCount(plan)); + }); + + it("Mono bleibt eine gewöhnliche Liste", () => { + const plan = generatePlan(sampleProject, "eg", codes(sampleProject), undefined, "mittel", false, true); + expect(isLazyUnread(plan)).toBe(false); + }); +}); diff --git a/src/plan/planView/geometry.test.ts b/src/plan/planView/geometry.test.ts index 6cb20cb7..cc27b89c 100644 --- a/src/plan/planView/geometry.test.ts +++ b/src/plan/planView/geometry.test.ts @@ -1,13 +1,24 @@ /** - * `marqueeHitDrawings` — Rahmenauswahl von 2D-Zeichenelementen. Vorher fehlten + * Rahmenauswahl von 2D-Zeichenelementen (`PlanPickIndex.marqueeDrawings`). Vorher fehlten * drawingCircle/drawingArc/drawingText/drawingImage komplett (nur line/polygon * abgedeckt) — Regressionsschutz für den Nachzieh-Fix (2D-Vervollständigung, * Fund A). */ import { describe, it, expect } from "vitest"; -import { marqueeHitDrawings, type ModelRect } from "./geometry"; +import type { ModelRect } from "./geometry"; import type { Primitive } from "../generatePlan"; +import { PlanPickIndex } from "./planPick"; + +/** Rahmen-Auswahl über 2D-Zeichnungen im Kern ([K3d], `PlanPickIndex.marqueeDrawings`). */ +function marqueeHitDrawings(prims: Primitive[], rect: ModelRect, crossing: boolean): string[] { + const ix = new PlanPickIndex({ primitives: prims, bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 } }); + try { + return ix.marqueeDrawings(rect, crossing); + } finally { + ix.release(); + } +} const encloseRect: ModelRect = { minX: -10, minY: -10, maxX: 10, maxY: 10 }; const missRect: ModelRect = { minX: 20, minY: 20, maxX: 30, maxY: 30 }; diff --git a/src/plan/planView/geometry.ts b/src/plan/planView/geometry.ts index 402361e1..0a822882 100644 --- a/src/plan/planView/geometry.ts +++ b/src/plan/planView/geometry.ts @@ -3,7 +3,6 @@ // Keine JSX, kein Komponenten-/Closure-Zugriff — pure Funktionen + Konstanten. import type { Vec2 } from "../../model/types"; -import type { Primitive } from "../generatePlan"; /** Rechteckiger Ausschnitt in SVG-Benutzerkoordinaten (viewBox-Einheiten). */ export interface ViewBox { @@ -231,142 +230,9 @@ export interface ModelRect { maxY: number; } -/** - * Bestimmt die vom Auswahl-Rechteck getroffenen Wand-IDs nach CAD-Konvention: - * • crossing = false (links→rechts): nur Wände, deren Polygone VOLLSTÄNDIG im - * Rechteck liegen (jeder Eckpunkt enthalten). - * • crossing = true (rechts→links): zusätzlich Wände, die das Rechteck nur - * BERÜHREN/kreuzen (Überlappung der Polygone mit dem Rechteck). - * Getestet wird je Wand über ALLE ihre Polygon-Bänder; ein Treffer eines Bandes - * genügt. Liefert eindeutige IDs in Auftreten-Reihenfolge. - */ -export function marqueeHit( - prims: Primitive[], - rect: ModelRect, - crossing: boolean, -): string[] { - return marqueeHitByField(prims, "wallId", rect, crossing); -} - -/** - * Generische Variante von {@link marqueeHit} für ein beliebiges Polygon-ID- - * Feld (`ceilingId`/`roomId`/`stairId`/`columnId`/`roofId`/…) — dieselbe - * window/crossing-Konvention, nur auf ein anderes Element bezogen. Deckt - * Nutzer-Report: „Auswahlrahmen kann Decken/Räume/Treppen nicht anwählen" - * (bisher nur Wände über `marqueeHit`, alles andere fehlte komplett). - */ -function marqueeHitByField( - prims: Primitive[], - field: "wallId" | "ceilingId" | "roomId" | "stairId" | "columnId" | "roofId", - rect: ModelRect, - crossing: boolean, -): string[] { - const byId = new Map(); - for (const p of prims) { - if (p.kind !== "polygon") continue; - const id = p[field]; - if (id == null) continue; - const list = byId.get(id); - if (list) list.push(p.pts); - else byId.set(id, [p.pts]); - } - const out: string[] = []; - for (const [id, polys] of byId) { - const hit = crossing - ? polys.some((poly) => polyTouchesRect(poly, rect)) - : polys.every((poly) => polyEnclosedByRect(poly, rect)); - if (hit) out.push(id); - } - return out; -} - -/** Vom Auswahl-Rechteck getroffene Decken-IDs (gleiche Konvention wie {@link marqueeHit}). */ -export function marqueeHitCeilings(prims: Primitive[], rect: ModelRect, crossing: boolean): string[] { - return marqueeHitByField(prims, "ceilingId", rect, crossing); -} - -/** Vom Auswahl-Rechteck getroffene Raum-IDs (gleiche Konvention wie {@link marqueeHit}). */ -export function marqueeHitRooms(prims: Primitive[], rect: ModelRect, crossing: boolean): string[] { - return marqueeHitByField(prims, "roomId", rect, crossing); -} - -/** Vom Auswahl-Rechteck getroffene Treppen-IDs (gleiche Konvention wie {@link marqueeHit}). */ -export function marqueeHitStairs(prims: Primitive[], rect: ModelRect, crossing: boolean): string[] { - return marqueeHitByField(prims, "stairId", rect, crossing); -} - -/** - * Vom Auswahl-Rechteck getroffene 2D-Zeichenelement-IDs (gleiche window/crossing- - * Konvention wie {@link marqueeHit}). Sammelt je Drawing2D ALLE seine Punkte aus - * den Linien-/Polygon-Primitiven; crossing = irgendein Punkt/Kante im Rechteck, - * window = alle Punkte vollständig eingeschlossen. - */ -/** Punkte auf einem Kreis-/Bogen-Ring (Modell-Meter), für Marquee-Zwecke abgetastet. */ -function ringSamplePoints(center: Vec2, r: number, a0?: number, a1?: number): Vec2[] { - const TAU = Math.PI * 2; - const full = a0 === undefined || a1 === undefined; - const start = full ? 0 : a0; - const sweep = full ? TAU : (((a1 - a0) % TAU) + TAU) % TAU || TAU; - const steps = full ? 32 : Math.max(4, Math.round((sweep / TAU) * 32)); - const pts: Vec2[] = []; - for (let i = 0; i <= steps; i++) { - const a = start + (sweep * i) / steps; - pts.push({ x: center.x + r * Math.cos(a), y: center.y + r * Math.sin(a) }); - } - return pts; -} - -/** Bounding-Box-Eckpunkte eines `drawingText`-Primitivs, analog zur Einzelklick-Bbox in PlanView.tsx. */ -function drawingTextBboxPoints(p: Extract): Vec2[] { - const singleW = Math.max(1, p.text.length) * p.heightM * 0.6; - const w = p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth : singleW; - const lines = p.wrapWidth && p.wrapWidth > 0 ? Math.max(1, Math.ceil(singleW / p.wrapWidth)) : 1; - const pad = p.heightM * 0.6; - const minX = p.at.x - pad; - const maxX = p.at.x + w + pad; - const minY = p.at.y - lines * p.heightM * 1.25 - pad; - const maxY = p.at.y + p.heightM * 0.4 + pad; - return [{ x: minX, y: minY }, { x: maxX, y: minY }, { x: maxX, y: maxY }, { x: minX, y: maxY }]; -} - -export function marqueeHitDrawings( - prims: Primitive[], - rect: ModelRect, - crossing: boolean, - /** Zeichnungen, die der Aufrufer selbst prüft (kompakte Unterlage) — hier überspringen. */ - skipIds?: ReadonlyMap, -): string[] { - const byDrawing = new Map(); - const collect = (id: string, pts: Vec2[]) => { - const list = byDrawing.get(id); - if (list) list.push(...pts); - else byDrawing.set(id, [...pts]); - }; - for (const p of prims) { - if (skipIds && "drawingId" in p && p.drawingId && skipIds.has(p.drawingId)) continue; - if (p.kind === "line" && p.drawingId) collect(p.drawingId, [p.a, p.b]); - else if (p.kind === "polygon" && p.drawingId) collect(p.drawingId, p.pts); - else if (p.kind === "drawingCircle" && p.drawingId) collect(p.drawingId, ringSamplePoints(p.center, p.r)); - else if (p.kind === "drawingArc" && p.drawingId) collect(p.drawingId, ringSamplePoints(p.center, p.r, p.a0, p.a1)); - else if (p.kind === "drawingText" && p.drawingId) collect(p.drawingId, drawingTextBboxPoints(p)); - else if (p.kind === "drawingImage" && p.drawingId) { - collect(p.drawingId, [ - p.min, - { x: p.max.x, y: p.min.y }, - p.max, - { x: p.min.x, y: p.max.y }, - ]); - } - } - const out: string[] = []; - for (const [id, pts] of byDrawing) { - const hit = crossing - ? polyTouchesRect(pts, rect) - : polyEnclosedByRect(pts, rect); - if (hit) out.push(id); - } - return out; -} +// Rahmen-Auswahl über Plan-Primitive (Wände, Decken, Räume, Treppen, 2D-Zeichnungen) läuft im +// Kern ([K3d], `PlanPickIndex.marquee`/`marqueeDrawings`, `plan_pick.rs`); hier bleiben die +// Rechteck-Tests für die kompakte Unterlage (`underlayAccess.ts`). /** Orientierung des Tripels (a,b,c): >0 CCW, <0 CW, 0 kollinear. */ function cross3(a: Vec2, b: Vec2, c: Vec2): number { diff --git a/src/plan/planView/marquee.test.ts b/src/plan/planView/marquee.test.ts index 613c65f0..2d55e486 100644 --- a/src/plan/planView/marquee.test.ts +++ b/src/plan/planView/marquee.test.ts @@ -1,5 +1,5 @@ /** - * `marqueeHitCeilings`/`marqueeHitRooms`/`marqueeHitStairs` — Nutzer-Report: + * Rahmen-Auswahl über Decken/Räume/Treppen (`PlanPickIndex.marquee`) — Nutzer-Report: * "Auswahlrahmen kann nicht alle Elemente anwählen, z.B. Decken, Räume und * Treppen nicht". Vorher las das Auswahl-Rechteck nur `wallId`/`drawingId` * aus den Polygon-Primitiven; die anderen ID-Felder (die dieselben @@ -7,8 +7,24 @@ */ import { describe, it, expect } from "vitest"; -import { marqueeHit, marqueeHitCeilings, marqueeHitRooms, marqueeHitStairs } from "./geometry"; import type { Primitive } from "../generatePlan"; +import type { ModelRect } from "./geometry"; +import { PlanPickIndex } from "./planPick"; + +// Rahmen-Auswahl im Kern ([K3d], `plan_pick.rs`) über einen Plan aus diesen Primitiven. +type Field = "wallId" | "ceilingId" | "roomId" | "stairId"; +const hit = (field: Field) => (prims: Primitive[], rect: ModelRect, crossing: boolean): string[] => { + const ix = new PlanPickIndex({ primitives: prims, bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 } }); + try { + return ix.marquee(field, rect, crossing); + } finally { + ix.release(); + } +}; +const marqueeHit = hit("wallId"); +const marqueeHitCeilings = hit("ceilingId"); +const marqueeHitRooms = hit("roomId"); +const marqueeHitStairs = hit("stairId"); const NO_HATCH = { pattern: "none" as const, color: "#000" }; diff --git a/src/plan/planView/planPick.ts b/src/plan/planView/planPick.ts index ce1b4b51..865b807e 100644 --- a/src/plan/planView/planPick.ts +++ b/src/plan/planView/planPick.ts @@ -10,7 +10,9 @@ import type { Vec2 } from "../../model/types"; import type { Plan, Primitive } from "../generatePlan"; import { heldSegs, planParts } from "../planParts"; +import { planPrimAt } from "../planLazy"; import { core } from "../../engine/coreWasm"; +import type { ModelRect } from "./geometry"; /** Pick-Felder eines Primitivs (Besitzer-Ids). */ export const OWNER_FIELDS = [ @@ -57,19 +59,37 @@ export interface ClientMap { scale: number; } +/** Typ-Kennung im Plan-Puffer → `kind` (s. `plan_buf.rs`). */ +const TAG_KIND: Record = { + 1: "polygon", + 2: "line", + 3: "arc", + 4: "drawingCircle", + 5: "drawingArc", + 6: "text", + 7: "drawingText", + 8: "drawingTextPath", + 9: "drawingImage", +}; + +/** Ids aus einer Kern-Antwort (jede mit `\0` davor). */ +const splitIds = (s: string): string[] => (s ? s.split("\0").slice(1) : []); + export class PlanPickIndex { private id = 0; - readonly prims: readonly Primitive[]; - constructor(private readonly plan: Plan) { - this.prims = plan.primitives; + constructor(readonly plan: Plan) {} + + /** Primitiv `i` des Plans (bei einem lazy Plan nur dieser Eintrag gelesen). */ + prim(i: number): Primitive | undefined { + return planPrimAt(this.plan, i); } - /** Kern-Index (lazy beim ersten Abfragen gebaut). */ + /** Kern-Index (lazy beim ersten Abfragen gebaut). Texte/Bilder mit JSON (Rahmen-Treffer). */ private ix(): number { if (this.id) return this.id; const c = core(); - const parts = planParts(this.plan); + const parts = planParts(this.plan, true); this.id = c.pick_index_build(heldSegs(parts, false)); if (!this.id) this.id = c.pick_index_build(heldSegs(parts, true)); return this.id; @@ -144,6 +164,42 @@ export class PlanPickIndex { const list = [...ids]; if (list.length === 0) return []; const hits = core().pick_owned_by(this.ix(), KIND[field], list.map((s) => "\u0000" + s).join("")); - return Array.from(hits, (i) => this.prims[i]); + return Array.from(hits, (i) => planPrimAt(this.plan, i)!); + } + + /** Erster Einzeltext (`drawingText` mit `drawingId`), dessen Rahmen `m` enthält, oder null. */ + drawingTextAt(m: Vec2): number | null { + const i = core().pick_drawing_text(this.ix(), m.x, m.y); + return i >= 0 ? i : null; + } + + /** Oberstes Bild (`drawingImage` mit `drawingId`) unter `m` oder null. */ + drawingImageAt(m: Vec2): number | null { + const i = core().pick_drawing_image(this.ix(), m.x, m.y); + return i >= 0 ? i : null; + } + + /** Art des ersten formgebenden Primitivs einer Zeichnung (Linie, Polygon, Text, …) oder null. */ + drawingKind(drawingId: string): Primitive["kind"] | null { + return TAG_KIND[core().pick_drawing_kind(this.ix(), drawingId)] ?? null; + } + + /** + * Rahmen-Auswahl über Polygone mit Id im Feld `field` (CAD-Konvention): `crossing` = ein Band + * berührt das Rechteck, sonst liegen alle Bänder ganz darin. Ids in Auftreten-Reihenfolge. + */ + marquee(field: "wallId" | "ceilingId" | "roomId" | "stairId" | "columnId" | "roofId", rect: ModelRect, crossing: boolean): string[] { + const r = Float64Array.of(rect.minX, rect.minY, rect.maxX, rect.maxY); + return splitIds(core().pick_marquee_polygons(this.ix(), KIND[field], r, crossing)); + } + + /** + * Rahmen-Auswahl über 2D-Zeichnungen (alle Punkte je Zeichnung: Linien, Polygone, abgetastete + * Kreise/Bögen, Text-/Bild-Rahmen); `skipIds` prüft der Aufrufer selbst (kompakte Unterlage). + */ + marqueeDrawings(rect: ModelRect, crossing: boolean, skipIds?: Iterable): string[] { + const r = Float64Array.of(rect.minX, rect.minY, rect.maxX, rect.maxY); + const skip = skipIds ? [...skipIds].map((s) => "\0" + s).join("") : ""; + return splitIds(core().pick_marquee_drawings(this.ix(), r, crossing, skip)); } } diff --git a/src/plan/planView/underlayAccess.test.ts b/src/plan/planView/underlayAccess.test.ts index 32235861..d8be8f47 100644 --- a/src/plan/planView/underlayAccess.test.ts +++ b/src/plan/planView/underlayAccess.test.ts @@ -4,7 +4,6 @@ import { describe, it, expect } from "vitest"; import type { Drawing2D, Project } from "../../model/types"; import { generatePlan, materializeUnderlay } from "../generatePlan"; -import { marqueeHitDrawings } from "./geometry"; import { PlanPickIndex } from "./planPick"; import { buildDrawingIndex, marqueeHitUnderlay, nearestInDrawings } from "./underlayAccess"; @@ -63,13 +62,14 @@ describe("underlayAccess == Primitiv-Varianten", () => { } }); - it("Marquee (crossing + window) == marqueeHitDrawings über die Primitive", () => { + it("Marquee (crossing + window) == Rahmen-Auswahl im Kern über die Primitive", () => { + const matIx = new PlanPickIndex(mat); for (const crossing of [true, false]) { for (let k = 0; k < 40; k++) { const x = rnd() * 450, y = rnd() * 450, w = 5 + rnd() * 120, h = 5 + rnd() * 120; const rect = { minX: x, minY: y, maxX: x + w, maxY: y + h }; const a = new Set(marqueeHitUnderlay(under, rect, crossing)); - const b = new Set(marqueeHitDrawings(mat.primitives, rect, crossing)); + const b = new Set(matIx.marqueeDrawings(rect, crossing)); expect([...a].sort()).toEqual([...b].sort()); } } diff --git a/src/plan/toRenderScene.ts b/src/plan/toRenderScene.ts index 0c7cd1c4..ca14294c 100644 --- a/src/plan/toRenderScene.ts +++ b/src/plan/toRenderScene.ts @@ -19,6 +19,7 @@ import { docToLines, wrapDocToLines } from "../text/renderHtml"; import { docFromText } from "../text/richText"; import { core } from "../engine/coreWasm"; import { greyedFlat, planParts, withPlanParts } from "./planParts"; +import { planTextEntries } from "./planLazy"; export type RPoint = [number, number]; export type RRgba = [number, number, number, number]; @@ -194,9 +195,8 @@ export function planSceneTexts(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N const texts: RText[] = []; const images: RImage[] = []; const ranges = plan.greyedRanges; - const prims = plan.primitives; - for (let i = 0; i < prims.length; i++) { - const p = prims[i]; + // Nur die Text-/Bild-Einträge ([K3d], aus den Typ-Kennungen des Plan-Puffers). + for (const { i, p } of planTextEntries(plan)) { if (p.kind === "text") { const greyed = p.greyed || inGreyedRange(ranges, i); const defCol = greyedColor(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], greyed); diff --git a/src/views/plan/PlanView.tsx b/src/views/plan/PlanView.tsx index 4a5fc7dc..44e058a4 100644 --- a/src/views/plan/PlanView.tsx +++ b/src/views/plan/PlanView.tsx @@ -31,7 +31,7 @@ import { isGpuText } from "../../core"; import { LiveMeet, LiveValue, createMeetStore, createValueStore } from "./planView/liveMeet"; import { useWasmPlanRenderer } from "./useWasmPlanRenderer"; import { DEFAULT_MARQUEE_COLOR, DEFAULT_SNAP_COLOR } from "../../theme/accents"; -import { type ViewBox__plan_planView_geometry as ViewBox, PX_PER_M, PAD, toScreen, clamp, meetScale, scaleFromView, viewForScale, viewForCamera, fitBoxFor, marqueeHit, marqueeHitDrawings, type ModelRect, marqueeHitCeilings, marqueeHitRooms, marqueeHitStairs } from "../../core"; +import { type ViewBox__plan_planView_geometry as ViewBox, PX_PER_M, PAD, toScreen, clamp, meetScale, scaleFromView, viewForScale, viewForCamera, fitBoxFor, type ModelRect } from "../../core"; import { polyUsesPattern, HatchPattern, @@ -45,6 +45,7 @@ import { PlanRulers } from "./planView/PlanRulers"; import { PlanGrid } from "./planView/PlanGrid"; import { expandRegion, indexedInRegion, regionContains, type Bounds } from "../../core"; import { PlanPickIndex, type ClientMap, type OwnerField } from "../../core"; +import { planPrimAt, planTextEntries } from "../../core"; import { buildDrawingIndex, drawingsWithinDistance, marqueeHitUnderlay, nearestInDrawings, type DrawingIndex } from "../../core"; import { endBusyAfterPaint } from "../../state/busyStore"; import { createCursorStore, useCursorValue, type CursorStore } from "../../state/cursorStore"; @@ -765,7 +766,7 @@ export const PlanView = forwardRef( const pickIndexRef = useRef(null); const getPick = (): PlanPickIndex => { const cached = pickIndexRef.current; - if (cached && cached.prims === plan.primitives) return cached; + if (cached && cached.plan === plan) return cached; cached?.release(); const ix = new PlanPickIndex(plan); pickIndexRef.current = ix; @@ -813,9 +814,10 @@ export const PlanView = forwardRef( // Primitiv in render2d, s. toRenderScene.ts `RImage`-Kommentar) — dieselbe // SVG-Fallback-Regel wie bei georeferenzierten Luftbildern. // useMemo: lief sonst bei JEDEM Render über alle Primitive (3,7 Mio. bei Kataster). + // Texte/Bilder aus den Typ-Kennungen des Plan-Puffers (`planTextEntries`), ohne alle Primitive zu lesen. const hasDrawingImages = useMemo( - () => planRaw.primitives.some((p) => p.kind === "drawingImage"), - [planRaw.primitives], + () => planTextEntries(planRaw).some((e) => e.p.kind === "drawingImage"), + [planRaw], ); // Engine WIRKLICH aktiv? Steuert das Umschalten SVG↔GPU: bei false rendert der // volle SVG-Pfad (Fallback), bei true übernimmt die GPU-Ebene + Text-Overlay. @@ -832,18 +834,6 @@ export const PlanView = forwardRef( const lines = !useGpuRenderer || wantWasm; return materializeGreyed(lines ? materializeUnderlay(planRaw) : planRaw, lines); }, [planRaw, useGpuRenderer, wantWasm]); - // Einzeltexte und Bilder (eigene Bbox-Treffer): einmal je Plan gesammelt statt bei jeder - // Mausbewegung über alle Primitive zu laufen. - const textImageIdx = useMemo(() => { - const texts: number[] = []; - const images: number[] = []; - plan.primitives.forEach((p, i) => { - if (p.kind === "drawingText") texts.push(i); - else if (p.kind === "drawingImage") images.push(i); - }); - return { texts, images }; - }, [plan.primitives]); - // Kompakte Linien-Unterlage (nur im reinen WebGL-Modus noch als `plan.underlay` // vorhanden): Hover/Pick/Marquee/Hervorhebung greifen direkt auf die Zeichnungen // zu, Strukturen entstehen LAZY je Plan (s. planView/underlayAccess.ts). @@ -885,11 +875,12 @@ export const PlanView = forwardRef( // bei jedem Render über ALLE Primitive — bei einem Kataster-Import 3,7 Mio. // GL-Linien, von denen das SVG keine einzige zeichnet (gemessen: 120–170 ms // je Zoom-Schritt allein fürs Culling, für am Ende ~500 sichtbare Texte). + // Mit GPU zeichnet das SVG nur Texte: dann kommen die Kandidaten aus den Text-Einträgen des + // Plan-Puffers (`planTextEntries`, [K3d]) — die übrigen Primitive werden nicht gelesen. const svgCandidates = useMemo(() => { const out: Array<{ p: Primitive; i: number }> = []; - const prims = plan.primitives; - for (let i = 0; i < prims.length; i++) { - const p = prims[i]; + const items: ReadonlyArray<{ p: Primitive; i: number }> = useGpuRenderer ? planTextEntries(plan) : plan.primitives.map((p, i) => ({ p, i })); + for (const { p, i } of items) { const drawnElsewhere = useGpuRenderer ? wantWasm ? p.kind !== "drawingText" @@ -900,7 +891,7 @@ export const PlanView = forwardRef( if (!drawnElsewhere) out.push({ p, i }); } return out; - }, [plan.primitives, useGpuRenderer, wantWasm, wantNative, nativeHook.gpuTexts]); + }, [plan, useGpuRenderer, wantWasm, wantNative, nativeHook.gpuTexts]); const needsCull = svgCandidates.length > CULL_THRESHOLD; const [cullState, setCullState] = useState(() => { if (!needsCull) return null; @@ -1116,7 +1107,7 @@ export const PlanView = forwardRef( }, fitSelection: () => { const sel = selectedRef.current; - const prim = sel !== null ? planRef.current.primitives[sel] : undefined; + const prim = sel !== null ? planPrimAt(planRef.current, sel) : undefined; if (prim && prim.kind === "polygon") { setView(fitBoxFor(prim.pts, toScreenRef.current)); } else { @@ -1439,8 +1430,8 @@ export const PlanView = forwardRef( const anyGroupableHit = (clientX: number, clientY: number): GroupableHit | null => { const idx = hitTest(clientX, clientY); if (idx !== null) { - const p = plan.primitives[idx]; - if (p.kind === "polygon") { + const p = planPrimAt(plan, idx); + if (p?.kind === "polygon") { if (p.wallId) return { wallId: p.wallId }; if (p.ceilingId) return { ceilingId: p.ceilingId }; if (p.roomId) return { roomId: p.roomId }; @@ -1464,7 +1455,7 @@ export const PlanView = forwardRef( const m = rawModelAt(clientX, clientY); const seg = pick.nearestSegment(m, LINE_PICK_PX / pxPerM); if (seg) { - bestId = (plan.primitives[seg.i] as Extract).drawingId!; + bestId = (planPrimAt(plan, seg.i) as Extract).drawingId!; bestDist = seg.dist * pxPerM; } const uIndex = getUnderlayIndex(); @@ -1479,7 +1470,7 @@ export const PlanView = forwardRef( for (const { i, dpx } of pick.ringsNear(m, pxPerM, LINE_PICK_PX)) { if (dpx < bestDist) { bestDist = dpx; - bestId = (plan.primitives[i] as Extract).drawingId!; + bestId = (planPrimAt(plan, i) as Extract).drawingId!; } } if (bestId) return bestId; @@ -1500,7 +1491,7 @@ export const PlanView = forwardRef( let bestDist = maxDist; const seg = getPick().nearestSegment(m, maxDist); if (seg) { - const p = plan.primitives[seg.i] as Extract; + const p = planPrimAt(plan, seg.i) as Extract; best = { a: p.a, b: p.b }; bestDist = seg.dist; } @@ -1513,44 +1504,20 @@ export const PlanView = forwardRef( }; // Trifft der Klick ein Text-2D-Element (kind "drawingText")? Grosszügige Modell- - // Bounding-Box um den Ankerpunkt (Text hat keine Linien-Geometrie zum Anfassen); - // Winkel wird vernachlässigt (meist waagrecht). Liefert die drawingId oder null. + // Bounding-Box um den Ankerpunkt (Text hat keine Linien-Geometrie zum Anfassen; Winkel + // vernachlässigt) — im Kern (`plan_pick.rs`). Liefert die drawingId oder null. const pickDrawingText = (clientX: number, clientY: number): string | null => { - const m = rawModelAt(clientX, clientY); - for (const i of textImageIdx.texts) { - const p = plan.primitives[i]; - if (p.kind !== "drawingText" || !p.drawingId) continue; - const singleW = Math.max(1, p.text.length) * p.heightM * 0.6; - // Textspalte: Breite = wrapWidth, Höhe = geschätzte Zeilenzahl · Zeilenhöhe. - const w = p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth : singleW; - const lines = - p.wrapWidth && p.wrapWidth > 0 ? Math.max(1, Math.ceil(singleW / p.wrapWidth)) : 1; - const pad = p.heightM * 0.6; - const minX = p.at.x - pad; - const maxX = p.at.x + w + pad; - // Baseline am Anker; Text läuft nach unten (Zeilen) und etwas nach oben (Oberlängen). - const minY = p.at.y - lines * p.heightM * 1.25 - pad; - const maxY = p.at.y + p.heightM * 0.4 + pad; - if (m.x >= minX && m.x <= maxX && m.y >= minY && m.y <= maxY) { - return p.drawingId; - } - } - return null; + const pick = getPick(); + const i = pick.drawingTextAt(rawModelAt(clientX, clientY)); + return i === null ? null : ((pick.prim(i) as { drawingId?: string }).drawingId ?? null); }; - // Trifft der Klick ein Bild-2D-Element (kind "drawingImage")? Reine - // Bounding-Box-Prüfung (achsparallel, keine Rotation). Liefert die drawingId - // oder null. + // Trifft der Klick ein Bild-2D-Element (kind "drawingImage")? Reine Bounding-Box-Prüfung + // (achsparallel, oberstes zuerst). Liefert die drawingId oder null. const pickDrawingImage = (clientX: number, clientY: number): string | null => { - const m = rawModelAt(clientX, clientY); - for (let k = textImageIdx.images.length - 1; k >= 0; k--) { - const p = plan.primitives[textImageIdx.images[k]]; - if (p.kind !== "drawingImage" || !p.drawingId) continue; - if (m.x >= p.min.x && m.x <= p.max.x && m.y >= p.min.y && m.y <= p.max.y) { - return p.drawingId; - } - } - return null; + const pick = getPick(); + const i = pick.drawingImageAt(rawModelAt(clientX, clientY)); + return i === null ? null : ((pick.prim(i) as { drawingId?: string }).drawingId ?? null); }; // Nächstgelegene Öffnung (Fenster/Tür) zum Cursor: Linien-/Bogen-Primitive mit @@ -1562,9 +1529,9 @@ export const PlanView = forwardRef( const pick = getPick(); // Getroffener Rahmen (das zuerst gezeichnete Polygon) hat Vorrang vor Symbol-Linien. const hit = pick.bottomPolygon(m, "openingId"); - if (hit !== null) return (plan.primitives[hit] as { openingId?: string }).openingId!; + if (hit !== null) return (planPrimAt(plan, hit) as { openingId?: string }).openingId!; const i = pick.nearestSymbolPx(["openingId"], ["openingId"], clientMap(), { x: clientX, y: clientY }, LINE_PICK_PX); - return i === null ? null : (plan.primitives[i] as { openingId?: string }).openingId!; + return i === null ? null : (planPrimAt(plan, i) as { openingId?: string }).openingId!; }; // Nächstgelegene Treppe zum Cursor: getroffenes Tritt-/Podest-Polygon (per @@ -1574,9 +1541,9 @@ export const PlanView = forwardRef( const m = viewToModel(v.x, v.y); const pick = getPick(); const hit = pick.bottomPolygon(m, "stairId"); - if (hit !== null) return (plan.primitives[hit] as { stairId?: string }).stairId!; + if (hit !== null) return (planPrimAt(plan, hit) as { stairId?: string }).stairId!; const i = pick.nearestSymbolPx(["stairId"], [], clientMap(), { x: clientX, y: clientY }, LINE_PICK_PX); - return i === null ? null : (plan.primitives[i] as { stairId?: string }).stairId!; + return i === null ? null : (planPrimAt(plan, i) as { stairId?: string }).stairId!; }; // Getroffener Raum: die Raum-Fläche (Polygon mit `roomId`) per Punkt-in-Polygon. @@ -1584,7 +1551,7 @@ export const PlanView = forwardRef( const pickRoom = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); const i = getPick().topPolygon(viewToModel(v.x, v.y), "roomId"); - return i === null ? null : (plan.primitives[i] as { roomId?: string }).roomId!; + return i === null ? null : (planPrimAt(plan, i) as { roomId?: string }).roomId!; }; // Getroffenes Dach: das unsichtbare Traufe-Pick-Polygon per Punkt-in-Polygon @@ -1592,7 +1559,7 @@ export const PlanView = forwardRef( const pickRoof = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); const i = getPick().topPolygon(viewToModel(v.x, v.y), "roofId"); - return i === null ? null : (plan.primitives[i] as { roofId?: string }).roofId!; + return i === null ? null : (planPrimAt(plan, i) as { roofId?: string }).roofId!; }; // Getroffene Schnitt-/Ansichtslinie: ihr schmales, unsichtbares Pick-Band @@ -1600,7 +1567,7 @@ export const PlanView = forwardRef( const pickSectionLine = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); const i = getPick().topPolygon(viewToModel(v.x, v.y), "sectionLineId"); - return i === null ? null : (plan.primitives[i] as { sectionLineId?: string }).sectionLineId!; + return i === null ? null : (planPrimAt(plan, i) as { sectionLineId?: string }).sectionLineId!; }; // Getroffenes Kontext-Objekt (importiertes Gebäude/Terrain): sein unsichtbares @@ -1610,7 +1577,7 @@ export const PlanView = forwardRef( const pickContextObject = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); const i = getPick().topPolygon(viewToModel(v.x, v.y), "contextObjectId"); - return i === null ? null : (plan.primitives[i] as { contextObjectId?: string }).contextObjectId!; + return i === null ? null : (planPrimAt(plan, i) as { contextObjectId?: string }).contextObjectId!; }; // Getroffener extrudierter Körper (truck-Integration): der Footprint-Umriss @@ -1619,7 +1586,7 @@ export const PlanView = forwardRef( const pickExtrudedSolid = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); const i = getPick().topPolygon(viewToModel(v.x, v.y), "extrudedSolidId"); - return i === null ? null : (plan.primitives[i] as { extrudedSolidId?: string }).extrudedSolidId!; + return i === null ? null : (planPrimAt(plan, i) as { extrudedSolidId?: string }).extrudedSolidId!; }; // Getroffene Stütze (Tragwerk): ihr Querschnitt ist eine gefüllte Poché @@ -1627,7 +1594,7 @@ export const PlanView = forwardRef( const pickColumn = (clientX: number, clientY: number): string | null => { const v = clientToView(clientX, clientY, view); const i = getPick().topPolygon(viewToModel(v.x, v.y), "columnId"); - return i === null ? null : (plan.primitives[i] as { columnId?: string }).columnId!; + return i === null ? null : (planPrimAt(plan, i) as { columnId?: string }).columnId!; }; // Liegt der Cursor auf dem KÖRPER eines GEWÄHLTEN Elements (Wand-Poché bzw. @@ -1642,7 +1609,7 @@ export const PlanView = forwardRef( // der Wirtswand, die im Blatt dahinter liegt). if (sheetBodies) { const hi = hitTest(clientX, clientY); - const p = hi !== null ? plan.primitives[hi] : null; + const p = hi !== null ? planPrimAt(plan, hi) ?? null : null; if (p && "openingId" in p && p.openingId && selectedOpeningIds?.includes(p.openingId)) { return { openingId: p.openingId }; } @@ -1657,8 +1624,8 @@ export const PlanView = forwardRef( if (selWalls.size) { const hi = hitTest(clientX, clientY); if (hi !== null) { - const p = plan.primitives[hi]; - if (p.kind === "polygon" && p.wallId && selWalls.has(p.wallId)) { + const p = planPrimAt(plan, hi); + if (p?.kind === "polygon" && p.wallId && selWalls.has(p.wallId)) { return { wallId: p.wallId }; } } @@ -1679,7 +1646,7 @@ export const PlanView = forwardRef( // Polygon-Punkte allein sonst ein anderes Ergebnis lieferten) + Unterlage. const marqueeHitAll = (rect: ModelRect, crossing: boolean): string[] => { const ids = getUnderlayIds(); - const fromPrims = marqueeHitDrawings(plan.primitives, rect, crossing, ids ?? undefined); + const fromPrims = getPick().marqueeDrawings(rect, crossing, ids?.keys()); const u = getUnderlay(); return u ? [...fromPrims, ...marqueeHitUnderlay(u.drawings, rect, crossing)] : fromPrims; }; @@ -2096,7 +2063,7 @@ export const PlanView = forwardRef( // Kontext). Liefert nur die Ids + Polygon-Index; `model`/`shift` ergänzt der Aufrufer. const defaultPick = (clientX: number, clientY: number): PickIds => { const hitIndex = hitTest(clientX, clientY); - const hit = hitIndex !== null ? plan.primitives[hitIndex] : undefined; + const hit = hitIndex !== null ? planPrimAt(plan, hitIndex) : undefined; // Öffnung (Fenster/Tür) zuerst: ihr Symbol sitzt in der ausgesparten Lücke // bzw. schlägt über die Wand — ein Klick nahe am Symbol wählt die Öffnung. // Schnitt-/Ansichtslinie zuerst: ihr schmales Band liegt über allem, ein @@ -2195,7 +2162,7 @@ export const PlanView = forwardRef( const cycleRef = useRef<{ x: number; y: number; - prims: readonly Primitive[]; + plan: Plan; items: PickCandidate[]; idx: number; model: Vec2; @@ -2232,9 +2199,7 @@ export const PlanView = forwardRef( ? t("pick.shape.area") : t("pick.shape.polyline"); } - for (const p of plan.primitives) { - if (!("drawingId" in p) || p.drawingId !== id) continue; - switch (p.kind) { + switch (getPick().drawingKind(id)) { case "line": return t("pick.shape.line"); case "polygon": return t("pick.shape.area"); case "drawingText": @@ -2242,10 +2207,8 @@ export const PlanView = forwardRef( case "drawingCircle": return t("pick.shape.circle"); case "drawingArc": return t("pick.shape.arc"); case "drawingImage": return t("pick.shape.image"); - default: break; - } + default: return t("pick.kind.drawing"); } - return t("pick.kind.drawing"); }; /** IDs ALLER 2D-Elemente nahe am Cursor (nächste zuerst). */ @@ -2256,13 +2219,13 @@ export const PlanView = forwardRef( const found: Array<{ id: string; d: number }> = []; const pick = getPick(); for (const { i, dist } of pick.segmentsNear(m, tol)) { - const id = (plan.primitives[i] as Extract).drawingId; + const id = (planPrimAt(plan, i) as Extract).drawingId; if (id) found.push({ id, d: dist }); } const uIdx = getUnderlayIndex(); if (uIdx) for (const h of drawingsWithinDistance(uIdx, m, tol)) found.push({ id: h.drawing.id, d: h.dist }); for (const { i, dpx } of pick.ringsNear(m, pxPerM, LINE_PICK_PX)) { - found.push({ id: (plan.primitives[i] as Extract).drawingId!, d: dpx / pxPerM }); + found.push({ id: (planPrimAt(plan, i) as Extract).drawingId!, d: dpx / pxPerM }); } const textId = pickDrawingText(clientX, clientY); if (textId) found.push({ id: textId, d: tol * 2 }); @@ -2306,8 +2269,8 @@ export const PlanView = forwardRef( if (out.length > before) rest.push(out.pop()!); }; for (const idx of hitTestAll(clientX, clientY)) { - const p = plan.primitives[idx]; - if (p.kind !== "polygon") continue; + const p = planPrimAt(plan, idx); + if (p?.kind !== "polygon") continue; addRest("opening", p.openingId, idx); addRest("wall", p.wallId, idx); addRest("column", p.columnId, idx); @@ -2373,7 +2336,7 @@ export const PlanView = forwardRef( const prev = cycleRef.current; const same = prev && - prev.prims === plan.primitives && + prev.plan === plan && Math.hypot(e.clientX - prev.x, e.clientY - prev.y) <= 5; let items: PickCandidate[]; let idx: number; @@ -2396,7 +2359,7 @@ export const PlanView = forwardRef( cycleRef.current = { x: e.clientX, y: e.clientY, - prims: plan.primitives, + plan, items, idx, model, @@ -2511,11 +2474,11 @@ export const PlanView = forwardRef( }; if (onMarquee) { onMarquee({ - wallIds: marqueeHit(plan.primitives, rect, crossing), + wallIds: getPick().marquee("wallId", rect, crossing), drawingIds: marqueeHitAll(rect, crossing), - ceilingIds: marqueeHitCeilings(plan.primitives, rect, crossing), - roomIds: marqueeHitRooms(plan.primitives, rect, crossing), - stairIds: marqueeHitStairs(plan.primitives, rect, crossing), + ceilingIds: getPick().marquee("ceilingId", rect, crossing), + roomIds: getPick().marquee("roomId", rect, crossing), + stairIds: getPick().marquee("stairId", rect, crossing), crossing, }); } @@ -2689,7 +2652,7 @@ export const PlanView = forwardRef( return primsOwnedBy("wallId", selectedWallIds, (p): p is Extract => p.kind === "polygon"); } if (selected !== null) { - const p = plan.primitives[selected]; + const p = planPrimAt(plan, selected); if (p && p.kind === "polygon") return [p]; } return []; @@ -2955,8 +2918,8 @@ export const PlanView = forwardRef( // sonst weiterhin in der ORIGINAL-Bauteilfarbe erscheinen. const hatched = useMemo(() => { const list: HatchedPoly[] = []; - // Im WebGL-Modus zeichnet das SVG nur Texte (keine Polygone → keine Muster). - if (useGpuRenderer && !wantWasm) return list; + // Mit GPU (nativ oder WASM) zeichnet das SVG nur Texte (keine Polygone → keine Muster). + if (useGpuRenderer) return list; plan.primitives.forEach((p, i) => { if (p.kind === "polygon" && polyUsesPattern(p.hatch)) { // Verlauf-Schraffuren tragen ihre eigentliche Farbe in `gradient.color1/ @@ -3596,10 +3559,9 @@ export const PlanView = forwardRef( Layout stimmt. */} {editTextId && (() => { - const prim = plan.primitives.find( - (p): p is Extract => - p.kind === "drawingText" && p.drawingId === editTextId, - ); + const prim = planTextEntries(plan) + .map((e) => e.p) + .find((p): p is Extract => p.kind === "drawingText" && p.drawingId === editTextId); if (!prim) return null; const doc = prim.doc ?? docFromText(prim.text, prim.marks ?? {}); // WYSIWYG: Position, Breite, Feldhöhe UND Schriftgrösse folgen alle dem diff --git a/src/views/plan/useNativePlanRenderer.ts b/src/views/plan/useNativePlanRenderer.ts index 0e835a5b..687a1656 100644 --- a/src/views/plan/useNativePlanRenderer.ts +++ b/src/views/plan/useNativePlanRenderer.ts @@ -17,6 +17,7 @@ import type { Primitive } from "../../core"; import { NativeGl, type NativeInvoke } from './nativeGl'; import { readCssColor } from './cssColor'; import { NativeTextSync } from "../../core"; +import { planTextEntries } from "../../core"; /** Läuft die App in einer Tauri-Webview? */ const isTauri = (): boolean => typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window; @@ -89,7 +90,8 @@ export function useNativePlanRenderer( 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); + // Nur die Text-Einträge (`planTextEntries`, [K3d]) — nicht alle Primitive. + const { upsert, remove } = textSync.current.delta(planTextEntries(plan).map((e) => e.p), excludedText.current); if (upsert.length === 0 && remove.length === 0) return; void invoke('native2d_texts', { upsert, remove }) .then((ok) => { diff --git a/src/views/viewportContent.tsx b/src/views/viewportContent.tsx index 568016ca..55c2bf97 100644 --- a/src/views/viewportContent.tsx +++ b/src/views/viewportContent.tsx @@ -22,6 +22,7 @@ import type { import { categoryNameForPick } from "../core"; import type { PickKind } from "../core"; import { generatePlan, generateSectionPlan, generateVisibleLevelsPlan } from "../core"; +import { planWithExtra } from "../core"; import type { CategoryDisplayResolver, Plan, Primitive } from "../core"; import type { RichTextDoc } from "../text/richText"; import { computeSection, sameSectionInputs, sameSectionLine } from "../core"; @@ -818,10 +819,8 @@ function LevelPlanView({ // handhabbar; PlanView materialisiert sie, wo echte Primitive nötig sind. true, ); - const withOverlay = - overlayPrimitives.length === 0 - ? p - : { ...p, primitives: [...p.primitives, ...overlayPrimitives] }; + // Überlagerung anhängen, ohne die Primitive des Plans zu lesen (lazy, [K3d]). + const withOverlay = overlayPrimitives.length === 0 ? p : planWithExtra(p, [], overlayPrimitives); // Gruppen-Isolation ("Gruppe betreten"): alles ausserhalb der aktiven // Gruppe gedimmt, s. state/groupActions.ts::applyGroupDimmingToPlan (die // kompakte Linien-Unterlage bleibt dabei kompakt). From 9a3d07158b1ea5dbc1eb875b1cfea723f1501b7a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 01:49:28 +0000 Subject: [PATCH 3/5] [K3d] DXF-/DWG-Sammler im Kern: plan_dxf.rs liest Plan-Puffer und Projekt-Dokument MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ebenen, Linientypen, Textstile, Bemassungen (DIMSTYLE/DIMENSION), Türen/Fenster und Blockinstanzen (BLOCK/INSERT/ATTRIB), Schraffuren (HATCH, Verlauf, Zufallsstriche), Papierbereich: die flache Zeichnung entsteht im Kern und geht über TS an fileio (Schreibung unverändert dort). TS behält das Text-Layout (Zeilen der Raumstempel, Absätze/Wörter der Einzeltexte, Schriftfamilie) und schickt es flach mit; der Spaltenumbruch läuft im Kern (blocklokale Grösse). FlatDrawing-Klasse, Sammler und dxfCadParts (ausser fontNameOf) in TS gelöscht, Tests nach Rust. Gleichheit (temporärer Test gegen die alte TS-Fassung): flache Zeichnung Zahl für Zahl und Zeichenketten gleich über 451 Fälle (Beispiel + Fachplaner-Projekt, 3 Geschosse × 3 Detailgrade × mono × 3 Optionssätze, 300 Zufallspläne mit allen Primitiv-/Schraffur-Arten, Zusatz-Primitive, bigSample(8)); DXF/Binär byte-gleich; CLI dxf/dwg (--binary, --scale, --dim-unit cm, --layout) 36 Dateien byte-gleich zur CLI des Hauptstands. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/plan_dxf.rs | 1449 ++++++++++++++++++++++++++++ src-tauri/core/src/web/document.rs | 2 +- src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/plan_dxf.rs | 36 + src/export/dxfCadParts.test.ts | 65 +- src/export/dxfCadParts.ts | 119 +-- src/export/exportDxf.ts | 1002 +++---------------- src/plan/planParts.ts | 6 +- 9 files changed, 1609 insertions(+), 1072 deletions(-) create mode 100644 src-tauri/core/src/plan_dxf.rs create mode 100644 src-tauri/core/src/web/plan_dxf.rs diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 49737a2c..1f1263cd 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -63,6 +63,7 @@ pub mod plan_scene; pub mod plan_pick; pub mod snap; pub mod plan_svg; +pub mod plan_dxf; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_dxf.rs b/src-tauri/core/src/plan_dxf.rs new file mode 100644 index 00000000..eb6b2ad8 --- /dev/null +++ b/src-tauri/core/src/plan_dxf.rs @@ -0,0 +1,1449 @@ +//! DXF-/DWG-Sammler des Grundrisses ([K3d], früher `src/export/exportDxf.ts::collectPlanDrawing` +//! und `dxfCadParts.ts`): liest den zusammengesetzten Plan ([`crate::plan_parts`]) und das Projekt +//! und schreibt die flache Zeichnung, die `src-tauri/fileio/src/export.rs` zur Datei macht +//! (Kodierung dort; Gegenstück der früheren TS-Klasse `FlatDrawing`). Modell-Space in echten +//! Metern, Ebenen aus den Kategorien, Bemassungen als DIMENSION, Türen/Fenster und Blockinstanzen +//! als BLOCK + INSERT, Schraffuren als HATCH, Strichmuster als Linientypen. +//! +//! Gleiche Eingabe ⇒ dieselben Zahlen und Zeichenketten in derselben Reihenfolge wie die TS-Fassung +//! (Zeichenketten-Indizes nach erstem Gebrauch, Definitionen an der Stelle ihres ersten Gebrauchs). +//! Text-Layout bleibt TS: die Zeilen der Raumstempel und die Absätze/Wörter der Einzeltexte kommen +//! fertig mit ([`TextIn`]); der Zeilenumbruch nach Spaltenbreite läuft hier (er hängt in Blöcken +//! an der blocklokalen Grösse). + +use crate::hatch::{self, Hatch, HatchKind, Motif, Pattern, V2}; +use crate::js_fmt::{js_number, to_fixed}; +use crate::jsmath::hypot; +use crate::jsnum; +use crate::model::{Drawing2D, Drawing2DGeom, ElementKind, LayerCategory, LineStyle, LineStyleKind, Opening, OpeningDoorType, Project}; +use crate::plan::overrides::js_trim; +use crate::plan_buf::{whole, View, F_DASH_NULL, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_LINE, T_POLYGON, T_TEXT}; +use crate::plan_parts::{pick_ids, Part}; +use std::collections::{HashMap, HashSet}; +use std::f64::consts::PI; + +const FLAT_VERSION: f64 = 1.0; +const REC_LAYER: f64 = 1.0; +const REC_LINE: f64 = 2.0; +const REC_POLYLINE: f64 = 3.0; +const REC_ARC: f64 = 4.0; +const REC_CIRCLE: f64 = 5.0; +const REC_HATCH: f64 = 7.0; +const REC_GRADIENT: f64 = 8.0; +const REC_LTYPE: f64 = 9.0; +const REC_PEN: f64 = 11.0; +const REC_STYLE: f64 = 12.0; +const REC_TEXT2: f64 = 13.0; +const REC_DIMSTYLE: f64 = 14.0; +const REC_DIM: f64 = 15.0; +const REC_BLOCK: f64 = 16.0; +const REC_BLOCK_END: f64 = 17.0; +const REC_INSERT: f64 = 18.0; +const REC_LAYOUT: f64 = 19.0; + +/// Sammel-Ebenen für Primitive ohne eigene Kategorie. +const LAYER_HATCH: &str = "HATCH"; +const LAYER_SYMBOLS: &str = "SYMBOLS"; +const LAYER_CONTEXT: &str = "CONTEXT"; +const LAYER_DEFAULT: &str = "PLAN"; +const LAYER_SECTIONS: &str = "SECTIONS"; +const LAYER_EXTRUSION: &str = "EXTRUSION"; +/// Ebene „0": Inhalt von Blöcken (erbt die Ebene des INSERT). +const LAYER_ZERO: &str = "0"; + +/// Entitäten-Arten der Statistik (Tests): LINE, LWPOLYLINE, ARC, CIRCLE, TEXT, HATCH, DIMENSION, INSERT. +pub const KINDS: [&str; 8] = ["LINE", "LWPOLYLINE", "ARC", "CIRCLE", "TEXT", "HATCH", "DIMENSION", "INSERT"]; +const K_LINE: usize = 0; +const K_POLY: usize = 1; +const K_ARC: usize = 2; +const K_CIRCLE: usize = 3; +const K_TEXT: usize = 4; +const K_HATCH: usize = 5; +const K_DIM: usize = 6; +const K_INSERT: usize = 7; + +/// Bemassungs-Standards in Papier-mm (`DIM_DEFAULTS_MM`). +const DIM_GAP: f64 = 1.0; +const DIM_OVERSHOOT: f64 = 1.0; +const DIM_TICK: f64 = 3.0; +const DIM_TEXT: f64 = 4.0; + +/// Optionen des Exports. +pub struct DxfOptions { + /// Massstabsnenner (schon geprüft: endlich und > 0). + pub scale: f64, + pub include_hatches: bool, + /// Masszahl in Zentimetern statt Metern. + pub dim_cm: bool, + pub paper_layout: bool, + /// Ausmass des Plans (`Plan.bounds`) für den Papierbereich. + pub bounds: [f64; 4], + /// Standard-Schrift (erste Schrift der Projekt-Textstile, sonst Arial; in TS aufgelöst). + pub default_font: String, +} + +/// Schrift eines Texts (in TS aufgelöst: Familie nach `fontNameOf`, sonst Standard-Schrift). +#[derive(Clone, Debug, PartialEq)] +pub struct TextStyleIn { + pub family: String, + pub bold: bool, + pub italic: bool, +} + +/// Eine fertig gesetzte Zeile eines Raumstempels. +#[derive(Clone, Debug, PartialEq)] +pub struct StampLine { + pub text: String, + pub height: f64, + /// 0 links, 1 Mitte, 2 rechts. + pub align: f64, + pub style: TextStyleIn, + /// Versatz der Grundlinie vom Anker nach unten (Meter). + pub down: f64, +} + +/// Text-Eingabe aus TS je Plan-Index (Layout bleibt TS). +#[derive(Clone, Debug, PartialEq)] +pub enum TextIn { + /// `text` (Raumstempel): Anker und Zeilen. + Stamp { at: V2, lines: Vec }, + /// `drawingText`: Anker, Winkel, Höhe, Spaltenbreite (NaN = keine), Schrift und Absätze + /// (Text des Absatzes, Wörter nach `split(/\s+/)`). + Single { at: V2, angle: f64, height: f64, wrap: f64, style: TextStyleIn, paras: Vec<(String, Vec)> }, +} + +/// Ergebnis: Zahlen und Zeichenketten der flachen Zeichnung, Entitäten je Art (Modell, Blöcke). +pub struct FlatDxf { + pub nums: Vec, + pub strings: Vec, + pub model: [u32; 8], + pub blocks: [u32; 8], +} + +// ── Flache Zeichnung ─────────────────────────────────────────────────────── + +/// Zahlenpuffer einer Zeichnung (`None` = die Hauptzeichnung, deren Puffer `root` ist) bzw. eines +/// Blockinhalts, mit eigenem Linientyp-Zustand und Zählern. +struct Buf { + nums: Option>, + pen: f64, + counts: [u32; 8], +} + +impl Buf { + fn main() -> Buf { + Buf { nums: None, pen: -1.0, counts: [0; 8] } + } + fn block() -> Buf { + Buf { nums: Some(Vec::new()), pen: -1.0, counts: [0; 8] } + } +} + +/// Was Hauptzeichnung und Blockinhalte teilen (Definitionen landen immer in `root`). +struct Flat { + root: Vec, + strings: Vec, + str_idx: HashMap, + layers: HashMap, + ltypes: HashMap, + styles: HashMap, + dim_styles: HashMap, + blocks: HashSet, + block_counts: [u32; 8], +} + +impl Flat { + fn new() -> Flat { + Flat { + root: vec![FLAT_VERSION], + strings: Vec::new(), + str_idx: HashMap::new(), + layers: HashMap::new(), + ltypes: HashMap::new(), + styles: HashMap::new(), + dim_styles: HashMap::new(), + blocks: HashSet::new(), + block_counts: [0; 8], + } + } + + fn push(&mut self, b: &mut Buf, v: &[f64]) { + match b.nums.as_mut() { + Some(n) => n.extend_from_slice(v), + None => self.root.extend_from_slice(v), + } + } + + fn str(&mut self, s: &str) -> f64 { + let clean: String = s.chars().filter(|c| *c != '\0').collect(); + if let Some(&i) = self.str_idx.get(&clean) { + return i as f64; + } + self.strings.push(clean.clone()); + let i = self.strings.len() - 1; + self.str_idx.insert(clean, i); + i as f64 + } + + /// Ebene (`rgb` 0xRRGGBB oder None = ACI 7, `lw` in 1/100 mm), idempotent über den Namen. + fn add_layer(&mut self, name: &str, rgb: Option, lw: f64) -> f64 { + if let Some(&i) = self.layers.get(name) { + return i as f64; + } + let idx = self.layers.len(); + self.layers.insert(name.to_string(), idx); + let s = self.str(name); + self.root.extend_from_slice(&[REC_LAYER, s, rgb.unwrap_or(-1.0), lw]); + idx as f64 + } + + fn layer(&mut self, name: &str) -> f64 { + match self.layers.get(name) { + Some(&i) => i as f64, + None => self.add_layer(name, None, 25.0), + } + } + + fn add_linetype(&mut self, name: &str, el: &[f64]) -> f64 { + if let Some(&i) = self.ltypes.get(name) { + return i as f64; + } + let idx = self.ltypes.len(); + self.ltypes.insert(name.to_string(), idx); + let s = self.str(name); + self.root.extend_from_slice(&[REC_LTYPE, s, el.len() as f64]); + self.root.extend_from_slice(el); + idx as f64 + } + + fn set_pen(&mut self, b: &mut Buf, ltype: f64) { + if ltype == b.pen { + return; + } + b.pen = ltype; + self.push(b, &[REC_PEN, ltype]); + } + + fn add_text_style(&mut self, name: &str, font: &str, bold: bool, italic: bool) -> f64 { + if let Some(&i) = self.styles.get(name) { + return i as f64; + } + let idx = self.styles.len(); + self.styles.insert(name.to_string(), idx); + let s = self.str(name); + let f = self.str(font); + self.root.extend_from_slice(&[REC_STYLE, s, f, b01(bold), b01(italic), 1.0]); + idx as f64 + } + + fn add_line(&mut self, b: &mut Buf, layer: &str, p: V2, q: V2) { + b.counts[K_LINE] += 1; + let l = self.layer(layer); + self.push(b, &[REC_LINE, l, p.x, p.y, q.x, q.y]); + } + + fn add_polyline(&mut self, b: &mut Buf, layer: &str, pts: &[V2], closed: bool) { + if pts.len() < 2 { + return; + } + b.counts[K_POLY] += 1; + let l = self.layer(layer); + self.push(b, &[REC_POLYLINE, l, b01(closed), pts.len() as f64]); + for p in pts { + self.push(b, &[p.x, p.y]); + } + } + + fn add_arc(&mut self, b: &mut Buf, layer: &str, c: V2, r: f64, start: f64, end: f64) { + b.counts[K_ARC] += 1; + let l = self.layer(layer); + self.push(b, &[REC_ARC, l, c.x, c.y, r, start, end]); + } + + fn add_circle(&mut self, b: &mut Buf, layer: &str, c: V2, r: f64) { + b.counts[K_CIRCLE] += 1; + let l = self.layer(layer); + self.push(b, &[REC_CIRCLE, l, c.x, c.y, r]); + } + + #[allow(clippy::too_many_arguments)] + fn add_text2(&mut self, b: &mut Buf, layer: &str, at: V2, height: f64, rot: f64, value: &str, halign: f64, style: f64) { + b.counts[K_TEXT] += 1; + let l = self.layer(layer); + let s = self.str(value); + self.push(b, &[REC_TEXT2, l, s, at.x, at.y, height, rot, halign, style]); + } + + fn add_hatch(&mut self, b: &mut Buf, layer: &str, pts: &[V2], solid: bool, rgb: Option, families: &[(f64, f64)], dashes: &[f64]) { + if pts.len() < 3 { + return; + } + b.counts[K_HATCH] += 1; + let (families, dashes): (&[(f64, f64)], &[f64]) = if solid { (&[], &[]) } else { (families, dashes) }; + let l = self.layer(layer); + self.push(b, &[REC_HATCH, l, if solid { 0.0 } else { 1.0 }, rgb.unwrap_or(-1.0), dashes.len() as f64]); + self.push(b, dashes); + self.push(b, &[families.len() as f64]); + for f in families { + self.push(b, &[f.0, f.1]); + } + self.push(b, &[pts.len() as f64]); + for p in pts { + self.push(b, &[p.x, p.y]); + } + } + + #[allow(clippy::too_many_arguments)] + fn add_gradient(&mut self, b: &mut Buf, layer: &str, pts: &[V2], rgb1: f64, rgb2: f64, angle: f64, radial: bool) { + if pts.len() < 3 { + return; + } + b.counts[K_HATCH] += 1; + let l = self.layer(layer); + self.push(b, &[REC_GRADIENT, l, rgb1, rgb2, angle, b01(radial), pts.len() as f64]); + for p in pts { + self.push(b, &[p.x, p.y]); + } + } + + /// Bemassungsstil `d` = `[textStyle, scale, txt, tick, exo, exe, gap, dec, lfac]`. + fn add_dim_style(&mut self, name: &str, d: [f64; 9]) -> f64 { + if let Some(&i) = self.dim_styles.get(name) { + return i as f64; + } + let idx = self.dim_styles.len(); + self.dim_styles.insert(name.to_string(), idx); + let s = self.str(name); + self.root.extend_from_slice(&[REC_DIMSTYLE, s]); + self.root.extend_from_slice(&d); + self.root.push(-1.0); + idx as f64 + } + + #[allow(clippy::too_many_arguments)] + fn add_dimension(&mut self, b: &mut Buf, layer: &str, style: f64, p1: V2, p2: V2, on: V2, text_at: Option) { + b.counts[K_DIM] += 1; + let l = self.layer(layer); + let t = text_at.unwrap_or(V2 { x: 0.0, y: 0.0 }); + self.push(b, &[REC_DIM, l, style, p1.x, p1.y, p2.x, p2.y, on.x, on.y, b01(text_at.is_some()), t.x, t.y]); + } + + /// Blockdefinition mit dem Inhalt `content` (blocklokal) an dieser Stelle. + fn define_block(&mut self, b: &mut Buf, name: &str, description: &str, atts: &[(&str, &str, &str)], content: Buf) { + if self.blocks.contains(name) { + return; + } + self.blocks.insert(name.to_string()); + let s = self.str(name); + let d = if description.is_empty() { -1.0 } else { self.str(description) }; + self.push(b, &[REC_BLOCK, s, d, atts.len() as f64]); + for (tag, prompt, def) in atts { + let t = self.str(tag); + let p = self.str(prompt); + let v = self.str(def); + self.push(b, &[t, p, v, 0.0, 0.0, 0.1]); + } + // Der Block beginnt mit „nach Ebene“; danach gilt der Linientyp, mit dem sein Inhalt endete. + self.push(b, &[REC_PEN, -1.0]); + self.push(b, content.nums.as_deref().unwrap_or(&[])); + self.push(b, &[REC_BLOCK_END]); + b.pen = content.pen; + for k in 0..8 { + self.block_counts[k] += content.counts[k]; + } + } + + #[allow(clippy::too_many_arguments)] + fn add_insert(&mut self, b: &mut Buf, layer: &str, name: &str, at: V2, rot: f64, scale: f64, values: &[(&str, String)]) { + b.counts[K_INSERT] += 1; + let l = self.layer(layer); + let s = self.str(name); + self.push(b, &[REC_INSERT, l, s, at.x, at.y, rot, scale, scale, values.len() as f64]); + for (tag, v) in values { + let t = self.str(tag); + let v = self.str(v); + self.push(b, &[t, v]); + } + } +} + +fn b01(v: bool) -> f64 { + if v { + 1.0 + } else { + 0.0 + } +} + +/// Inhalt eines Blocks als Schlüssel (`roundKey`): Zahlen auf 1 mm gerundet. +pub fn round_key(nums: &[f64]) -> String { + let mut out = String::new(); + for v in nums { + out.push_str(&js_number(jsnum::round(v * 1000.0))); + out.push(','); + } + out +} + +// ── Hilfsfunktionen (früher `dxfCadParts.ts`) ────────────────────────────── + +/// Strichmuster (Papier-mm) → Linientyp-Elemente in Modell-Metern (Strich +, Lücke −); `None` ohne Strich. +pub fn dash_to_ltype_meters(dash_mm: &[f64], scale: f64) -> Option> { + let mut pat: Vec = dash_mm.iter().map(|d| if d.is_finite() { jsnum::max(0.0, *d) } else { 0.0 }).collect(); + if pat.is_empty() || pat.iter().all(|d| *d == 0.0) { + return None; + } + if pat.len() % 2 == 1 { + pat.extend_from_within(..); + } + let k = scale / 1000.0; + Some( + pat.iter() + .enumerate() + .map(|(i, p)| { + let len = p * k; + if i % 2 == 0 { + len + } else { + -jsnum::max(len, 1e-6) + } + }) + .collect(), + ) +} + +/// `String(Math.round(v * 100) / 100)`. +fn n2(v: f64) -> String { + js_number(jsnum::round(v * 100.0) / 100.0) +} + +/// Linientyp-Name zu einem Strichmuster: Projekt-Linienstil mit gleichem Muster, sonst +/// `DOSSIER_STRICH__…`. +pub fn ltype_name_for(dash_mm: &[f64], styles: &[LineStyle]) -> String { + let same = |a: &[f64], b: &[f64]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9); + let hit = styles.iter().find(|s| { + let dash_kind = matches!(s.kind, None | Some(LineStyleKind::Dash)); + s.dash.as_ref().is_some_and(|d| !d.is_empty() && dash_kind && same(d, dash_mm)) + }); + if let Some(h) = hit { + let t = js_trim(&h.name); + if !t.is_empty() { + return t.to_string(); + } + } + let parts: Vec = dash_mm.iter().map(|v| n2(*v)).collect(); + format!("DOSSIER_STRICH_{}", parts.join("_")) +} + +/// Papier und Ansichtsfenster (`paperFor`): (paperW, paperH, vpW, vpH). +pub fn paper_for(w: f64, h: f64, scale: f64, margin: f64) -> (f64, f64, f64, f64) { + const SIZES: [(f64, f64); 5] = [(297.0, 210.0), (420.0, 297.0), (594.0, 420.0), (841.0, 594.0), (1189.0, 841.0)]; + let need_w = (w * 1000.0) / scale + 2.0 * margin; + let need_h = (h * 1000.0) / scale + 2.0 * margin; + for (pw, ph) in SIZES { + if need_w <= pw && need_h <= ph { + return (pw, ph, pw - 2.0 * margin, ph - 2.0 * margin); + } + if need_w <= ph && need_h <= pw { + return (ph, pw, ph - 2.0 * margin, pw - 2.0 * margin); + } + } + let pw = (need_w / 10.0).ceil() * 10.0; + let ph = (need_h / 10.0).ceil() * 10.0; + (pw, ph, pw - 2.0 * margin, ph - 2.0 * margin) +} + +/// `/^#?([0-9a-f]{6})$/i` nach JS-`trim` → 0xRRGGBB, sonst dunkelgrau. +fn rgb_from_hex(hex: &str) -> f64 { + let t = js_trim(hex); + let h = t.strip_prefix('#').unwrap_or(t); + if h.len() == 6 && h.bytes().all(|c| c.is_ascii_hexdigit()) { + return i64::from_str_radix(h, 16).map_or(0x111111 as f64, |v| v as f64); + } + 0x111111 as f64 +} + +/// `/^#?([0-9a-f]{6}|[0-9a-f]{3})$/i` → 0xRRGGBB, sonst `None` (Farbe der Ebene). +fn rgb_or_null(hex: &str) -> Option { + let t = js_trim(hex); + let h = t.strip_prefix('#').unwrap_or(t); + if !h.bytes().all(|c| c.is_ascii_hexdigit()) { + return None; + } + let full: String = match h.len() { + 6 => h.to_string(), + 3 => h.chars().flat_map(|c| [c, c]).collect(), + _ => return None, + }; + i64::from_str_radix(&full, 16).ok().map(|v| v as f64) +} + +/// Millimeter → DXF-LWEIGHT (1/100 mm). +fn mm_to_lwe(mm: f64) -> f64 { + jsnum::max(0.0, jsnum::round(mm * 100.0)) +} + +/// Strichmuster (mm) → Zyklus in Welt-Metern; ungerade Länge verdoppelt; `None` = durchgezogen. +fn dash_cycle_meters(dash: &[f64]) -> Option> { + let pat: Vec = dash.iter().map(|d| jsnum::max(0.0, *d) * hatch::DASH_MM_TO_M).filter(|d| *d > 0.0).collect(); + if pat.is_empty() { + return None; + } + Some(if pat.len() % 2 == 0 { pat } else { [pat.clone(), pat].concat() }) +} + +/// Eine Schraffurlinie in durchgezogene Teilstücke nach `cycle` (`dashSeg`). +fn dash_seg(a: V2, b: V2, cycle: &[f64]) -> Vec<(V2, V2)> { + let mut out = Vec::new(); + let len = hypot(&[b.x - a.x, b.y - a.y]); + if len < 1e-9 { + return out; + } + let ux = (b.x - a.x) / len; + let uy = (b.y - a.y) / len; + let mut pos = 0.0; + let mut idx = 0usize; + let mut on = true; + while pos < len - 1e-9 { + let step = jsnum::min(cycle[idx % cycle.len()], len - pos); + if on && step > 1e-9 { + out.push((V2 { x: a.x + ux * pos, y: a.y + uy * pos }, V2 { x: a.x + ux * (pos + step), y: a.y + uy * (pos + step) })); + } + pos += step; + idx += 1; + on = !on; + } + out +} + +/// Linienscharen einer Vektor-Schraffur als (Winkel rad, Abstand m) (`hatchFamilies`). +fn hatch_families(h: &Hatch) -> Vec<(f64, f64)> { + let unit_m = 1.0 / 90.0; + let tile_m = (if h.pattern == Pattern::Insulation { 10.0 } else { 8.0 }) * h.scale * unit_m; + let spacing = jsnum::max(0.02, tile_m); + if !spacing.is_finite() { + return Vec::new(); + } + let angle = (h.angle * PI) / 180.0; + let mut out = vec![(angle, spacing)]; + if h.pattern == Pattern::Crosshatch { + out.push((angle + PI / 2.0, spacing)); + } + if h.pattern == Pattern::Insulation { + out.push((angle - PI / 4.0, spacing)); + } + out +} + +/// Winkel (0..2π) von `c` nach `p`. +fn angle_rad(c: V2, p: V2) -> f64 { + let a = jsnum::atan2(p.y - c.y, p.x - c.x); + if a < 0.0 { + a + 2.0 * PI + } else { + a + } +} + +/// `v.toFixed(2)` für Attribute, nicht endlich → leer. +fn m2(v: f64) -> String { + if v.is_finite() { + to_fixed(v, 2) + } else { + String::new() + } +} + +// ── Primitive des Plans ───────────────────────────────────────────────────── + +/// Verlauf einer Schraffur (aus ihrem JSON). +#[derive(Clone, Debug)] +struct Gradient { + color1: String, + color2: String, + angle: f64, + radial: bool, +} + +#[derive(Clone, Debug)] +struct HatchIn { + h: Hatch, + color: String, + /// `None`: kein Verlauf (oder JSON fehlt/kaputt — dann ohne Verlauf, wie unlesbare Farben). + gradient: Option, +} + +/// Ein Plan-Primitiv in der Form, die der Sammler braucht. +#[derive(Clone, Debug)] +enum Prim { + Line { a: V2, b: V2, cls: String, dash: Vec, zigzag: Option<(f64, f64)>, motif: Option }, + Arc { center: V2, from: V2, to: V2, r: f64, dash: Vec }, + Polygon { pts: Vec, fill: String, stroke: String, hatch: Option }, + Circle { center: V2, r: f64, dash: Vec }, + DrawingArc { center: V2, r: f64, a0: f64, a1: f64, dash: Vec }, + Single { at: V2, angle: f64, height: f64, wrap: f64, style: TextStyleIn, paras: Vec<(String, Vec)> }, + Stamp { at: V2, lines: Vec }, + /// Textpfad, Bild, Platzhalter: nichts zu schreiben. + Other, +} + +/// Ids eines Primitivs (nicht leer = gesetzt, wie die JS-Wahrheitsprüfung). +#[derive(Clone, Debug, Default)] +struct Ids { + wall: Option, + drawing: Option, + column: Option, + solid: Option, + room: Option, + opening: Option, +} + +struct Entry { + prim: Prim, + ids: Ids, + /// `cls` einer Linie bzw. Typ-Kennung (für die Ebene). + tag: u32, +} + +fn pts_of(v: &[f64]) -> Vec { + v.chunks_exact(2).map(|c| V2 { x: c[0], y: c[1] }).collect() +} + +/// Eintrag `i` eines Abschnitts lesen; Hatch-Tabelle des Puffers gecacht. +fn read_entry(part: &mut Part, i: usize, hatches: &[(i32, Hatch, i32)], text: Option<&TextIn>) -> Option { + let view: &View = &part.view; + let rec = view.rec(i)?; + let f = &rec.f; + let mut ids = Ids::default(); + for (kind, si) in pick_ids(view, &rec)? { + let s = view.string(whole(si)?)?; + if s.is_empty() { + continue; + } + match kind { + 1 => ids.wall = Some(s), + 2 => ids.drawing = Some(s), + 4 => ids.opening = Some(s), + 6 => ids.room = Some(s), + 7 => ids.solid = Some(s), + 9 => ids.column = Some(s), + _ => {} + } + } + let dash = |rec: &crate::plan_buf::Rec| -> Option> { + if rec.flags & F_DASH_NULL != 0 { + return Some(Vec::new()); + } + match rec.dash { + Some((o, n)) => view.pool(o, n), + None => Some(Vec::new()), + } + }; + let v = |x: f64, y: f64| V2 { x, y }; + let s = |idx: f64| -> Option { + if idx == -1.0 { + Some(String::new()) + } else { + view.string(whole(idx)?) + } + }; + let prim = match rec.tag { + T_POLYGON => { + let pts = pts_of(&view.pool(whole(f[5])?, whole(f[6])?.checked_mul(2)?)?); + let hatch = if f[3] >= 0.0 { + let (json, h, color) = hatches.get(whole(f[3])?)?.clone(); + let color = if color >= 0 { view.string(color as usize)? } else { String::new() }; + let gradient = if h.kind == HatchKind::Gradient && json >= 0 { + view.string(json as usize).and_then(|j| serde_json::from_str::(&j).ok()).and_then(|j| { + let g = j.get("gradient")?; + Some(Gradient { + color1: g.get("color1")?.as_str()?.to_string(), + color2: g.get("color2")?.as_str()?.to_string(), + angle: g.get("angle").and_then(|a| a.as_f64()).unwrap_or(f64::NAN), + radial: g.get("type").and_then(|t| t.as_str()) == Some("radial"), + }) + }) + } else { + None + }; + Some(HatchIn { h, color, gradient }) + } else { + None + }; + Prim::Polygon { pts, fill: s(f[0])?, stroke: s(f[1])?, hatch } + } + T_LINE => Prim::Line { + a: v(f[4], f[5]), + b: v(f[6], f[7]), + cls: s(f[0])?, + dash: dash(&rec)?, + zigzag: rec.zigzag, + motif: match rec.motif { + Some((length, o, n)) => Some(Motif { points: pts_of(&view.pool(o, n.checked_mul(2)?)?), length }), + None => None, + }, + }, + T_ARC => Prim::Arc { center: v(f[4], f[5]), from: v(f[6], f[7]), to: v(f[8], f[9]), r: f[10], dash: dash(&rec)? }, + T_CIRCLE => Prim::Circle { center: v(f[4], f[5]), r: f[6], dash: dash(&rec)? }, + T_DRAWING_ARC => Prim::DrawingArc { center: v(f[3], f[4]), r: f[5], a0: f[6], a1: f[7], dash: dash(&rec)? }, + T_TEXT => match text { + Some(TextIn::Stamp { at, lines }) => Prim::Stamp { at: *at, lines: lines.clone() }, + _ => Prim::Other, + }, + T_DRAWING_TEXT => match text { + Some(TextIn::Single { at, angle, height, wrap, style, paras }) => { + Prim::Single { at: *at, angle: *angle, height: *height, wrap: *wrap, style: style.clone(), paras: paras.clone() } + } + _ => Prim::Other, + }, + _ => Prim::Other, + }; + Some(Entry { prim, ids, tag: rec.tag }) +} + +/// Blocklokales System: Verschiebung `-origin`, Drehung `-rot`, Skalierung `1/scale`. +#[derive(Clone, Copy)] +struct Frame { + origin: V2, + rot: f64, + scale: f64, +} + +impl Frame { + fn local(&self, p: V2) -> V2 { + let c = jsnum::cos(self.rot); + let s = jsnum::sin(self.rot); + let dx = p.x - self.origin.x; + let dy = p.y - self.origin.y; + V2 { x: (dx * c + dy * s) / self.scale, y: (-dx * s + dy * c) / self.scale } + } +} + +/// Primitiv im lokalen System des Blocks (`primitiveToLocal`); andere Arten → `None`. +fn to_local(p: &Prim, f: Frame) -> Option { + let rot_deg = (f.rot * 180.0) / PI; + Some(match p { + Prim::Line { a, b, cls, dash, zigzag, .. } => Prim::Line { + a: f.local(*a), + b: f.local(*b), + cls: cls.clone(), + dash: dash.clone(), + zigzag: zigzag.map(|(amp, wav)| (amp / f.scale, wav / f.scale)), + motif: None, + }, + Prim::Arc { center, from, to, r, dash } => Prim::Arc { center: f.local(*center), from: f.local(*from), to: f.local(*to), r: r / f.scale, dash: dash.clone() }, + Prim::Polygon { pts, fill, stroke, hatch } => Prim::Polygon { + pts: pts.iter().map(|q| f.local(*q)).collect(), + fill: fill.clone(), + stroke: stroke.clone(), + hatch: hatch.as_ref().map(|h| { + let mut h = h.clone(); + h.h.angle -= rot_deg; + h + }), + }, + Prim::Circle { center, r, dash } => Prim::Circle { center: f.local(*center), r: r / f.scale, dash: dash.clone() }, + Prim::DrawingArc { center, r, a0, a1, dash } => Prim::DrawingArc { center: f.local(*center), r: r / f.scale, a0: a0 - f.rot, a1: a1 - f.rot, dash: dash.clone() }, + Prim::Single { at, angle, height, wrap, style, paras } => Prim::Single { + at: f.local(*at), + angle: angle - f.rot, + height: height / f.scale, + // `p.wrapWidth && p.wrapWidth / f.scale`: 0/NaN bleiben. + wrap: if *wrap != 0.0 && !wrap.is_nan() { wrap / f.scale } else { *wrap }, + style: style.clone(), + paras: paras.clone(), + }, + _ => return None, + }) +} + +/// Zeilen eines Einzeltexts (`drawingTextLines`): Absätze, bei Spaltenbreite wortweise umbrochen +/// (Zeichenzahl in UTF-16-Einheiten wie `String.length`); Zeilenabstand 1.25 × Höhe. +fn single_lines(height: f64, wrap: f64, paras: &[(String, Vec)]) -> Vec<(String, f64)> { + let mut lines: Vec = Vec::new(); + if wrap > 0.0 { + let max_chars = jsnum::max(1.0, (wrap / (height * 0.55)).floor()); + let ulen = |s: &str| s.encode_utf16().count() as f64; + for (_, words) in paras { + let mut line = String::new(); + for word in words { + if line.is_empty() { + line = word.clone(); + } else if ulen(&line) + 1.0 + ulen(word) <= max_chars { + line.push(' '); + line.push_str(word); + } else { + lines.push(std::mem::replace(&mut line, word.clone())); + } + } + lines.push(line); + } + } else { + lines.extend(paras.iter().map(|p| p.0.clone())); + } + lines.into_iter().enumerate().map(|(k, t)| (t, k as f64 * height * 1.25)).collect() +} + +/// Eindeutige Blocknamen: gleiche Schlüssel teilen einen Namen, gleiche Wunschnamen werden nummeriert. +#[derive(Default)] +struct BlockNames { + by_key: HashMap, + used: HashSet, +} + +impl BlockNames { + fn name(&mut self, key: &str, wish: &str) -> (String, bool) { + if let Some(n) = self.by_key.get(key) { + return (n.clone(), false); + } + let mut name = wish.to_string(); + let mut i = 2; + while self.used.contains(&name.to_lowercase()) { + name = format!("{wish}_{i}"); + i += 1; + } + self.used.insert(name.to_lowercase()); + self.by_key.insert(key.to_string(), name.clone()); + (name, true) + } +} + +/// Gemeinsamer Zustand beim Sammeln. +struct Ctx<'a> { + project: &'a Project, + o: &'a DxfOptions, + flat: Flat, +} + +impl Ctx<'_> { + fn ltype_of(&mut self, dash: &[f64]) -> f64 { + if dash.is_empty() { + return -1.0; + } + match dash_to_ltype_meters(dash, self.o.scale) { + Some(el) => { + let name = ltype_name_for(dash, &self.project.line_styles); + self.flat.add_linetype(&name, &el) + } + None => -1.0, + } + } + + fn style_of(&mut self, s: Option<&TextStyleIn>) -> f64 { + let (family, bold, italic) = match s { + Some(s) => (s.family.clone(), s.bold, s.italic), + None => (self.o.default_font.clone(), false, false), + }; + let plain = family == self.o.default_font && !bold && !italic; + let name = if plain { "DOSSIER".to_string() } else { format!("DOSSIER_{family}{}{}", if bold { "_B" } else { "" }, if italic { "_I" } else { "" }) }; + self.flat.add_text_style(&name, &family, bold, italic) + } + + /// Ein Primitiv als Entität(en) (`emitPrimitive`); `hatch_layer` = Ebene der Schraffuren. + fn emit(&mut self, b: &mut Buf, p: &Prim, layer: &str, hatch_layer: &str) { + match p { + Prim::Line { a, b: q, dash, zigzag, motif, .. } => { + if let Some((amp, wav)) = zigzag { + let pts = hatch::zigzag_points(*a, *q, amp * hatch::DASH_MM_TO_M, wav * hatch::DASH_MM_TO_M).unwrap_or_else(|| vec![*a, *q]); + self.flat.set_pen(b, -1.0); + self.flat.add_polyline(b, layer, &pts, false); + } else if let Some(m) = motif { + let pts = hatch::motif_points_opt(*a, *q, m, hatch::DASH_MM_TO_M).unwrap_or_else(|| vec![*a, *q]); + self.flat.set_pen(b, -1.0); + self.flat.add_polyline(b, layer, &pts, false); + } else { + let lt = self.ltype_of(dash); + self.flat.set_pen(b, lt); + self.flat.add_line(b, layer, *a, *q); + } + } + Prim::Arc { center, from, to, r, dash } => { + let lt = self.ltype_of(dash); + self.flat.set_pen(b, lt); + let a1 = angle_rad(*center, *from); + let a2 = angle_rad(*center, *to); + let v1 = (from.x - center.x, from.y - center.y); + let v2 = (to.x - center.x, to.y - center.y); + let cross = v1.0 * v2.1 - v1.1 * v2.0; + if cross >= 0.0 { + self.flat.add_arc(b, layer, *center, *r, a1, a2); + } else { + self.flat.add_arc(b, layer, *center, *r, a2, a1); + } + } + Prim::Circle { center, r, dash } => { + let lt = self.ltype_of(dash); + self.flat.set_pen(b, lt); + self.flat.add_circle(b, layer, *center, *r); + } + Prim::DrawingArc { center, r, a0, a1, dash } => { + let lt = self.ltype_of(dash); + self.flat.set_pen(b, lt); + self.flat.add_arc(b, layer, *center, *r, *a0, *a1); + } + Prim::Single { at, angle, height, wrap, style, paras } => { + let dir = V2 { x: jsnum::sin(*angle), y: -jsnum::cos(*angle) }; + for (text, down) in single_lines(*height, *wrap, paras) { + if js_trim(&text).is_empty() || !(*height > 0.0) { + continue; + } + let p = V2 { x: at.x + dir.x * down, y: at.y + dir.y * down }; + let st = self.style_of(Some(style)); + self.flat.add_text2(b, layer, p, *height, *angle, &text, 0.0, st); + } + } + Prim::Stamp { at, lines } => { + for l in lines { + let st = self.style_of(Some(&l.style)); + self.flat.add_text2(b, layer, V2 { x: at.x, y: at.y - l.down }, l.height, 0.0, &l.text, l.align, st); + } + } + Prim::Polygon { pts, fill, stroke, hatch } => { + if pts.len() < 2 { + return; + } + let (pattern, kind) = hatch.as_ref().map_or((Pattern::None, HatchKind::Vector), |h| (h.h.pattern, h.h.kind)); + // Unsichtbare Pick-Bänder: weder Füllung noch Umriss noch Schraffur. + if stroke == "none" && fill == "none" && pattern == Pattern::None && kind != HatchKind::Gradient { + return; + } + let include = self.o.include_hatches; + if let (true, Some(h)) = (include && kind == HatchKind::Gradient && pts.len() >= 3, hatch) { + if let Some(g) = &h.gradient { + if let (Some(c1), Some(c2)) = (rgb_or_null(&g.color1), rgb_or_null(&g.color2)) { + if g.angle.is_finite() { + self.flat.add_gradient(b, hatch_layer, pts, c1, c2, (g.angle * PI) / 180.0, g.radial); + } + } + } + } else if let (true, Some(h)) = (include && kind != HatchKind::Image && pts.len() >= 3, hatch) { + if pattern == Pattern::Solid { + self.flat.add_hatch(b, hatch_layer, pts, true, rgb_or_null(&h.color), &[], &[]); + } else if pattern != Pattern::None && h.h.random { + let cycle = dash_cycle_meters(&h.h.dash); + let segs: Vec<(V2, V2)> = + hatch::build_random_hatch_runs(pts, &h.h, None).into_iter().filter(|r| r.len() >= 2).map(|r| (r[0], r[r.len() - 1])).collect(); + self.flat.set_pen(b, -1.0); + for (a, q) in segs { + match &cycle { + Some(c) => { + for (x, y) in dash_seg(a, q, c) { + self.flat.add_line(b, hatch_layer, x, y); + } + } + None => self.flat.add_line(b, hatch_layer, a, q), + } + } + } else if pattern != Pattern::None { + let families = hatch_families(&h.h); + if !families.is_empty() { + let dashes = dash_cycle_meters(&h.h.dash).unwrap_or_default(); + self.flat.add_hatch(b, hatch_layer, pts, false, rgb_or_null(&h.color), &families, &dashes); + } + } + } + self.flat.set_pen(b, -1.0); + self.flat.add_polyline(b, layer, pts, true); + } + Prim::Other => {} + } + } + + /// Bemassungskette → je Segment eine DIMENSION (`emitDimensions`). + fn dimensions(&mut self, b: &mut Buf, d: &Drawing2D, layer: &str) { + let Drawing2DGeom::Dimension { pts, offset, gap_mm, overshoot_mm, tick_len_mm, text_height_mm, text_offsets_mm, .. } = &d.geom else { return }; + let th = text_height_mm.unwrap_or(DIM_TEXT); + let tick = tick_len_mm.unwrap_or(DIM_TICK); + let gap = gap_mm.unwrap_or(DIM_GAP); + let over = overshoot_mm.unwrap_or(DIM_OVERSHOOT); + if ![th, tick, gap, over].iter().all(|v| v.is_finite() && *v >= 0.0) || th <= 0.0 { + return; + } + let scale = self.o.scale; + let cm = self.o.dim_cm; + let is_default = th == DIM_TEXT && tick == DIM_TICK && gap == DIM_GAP && over == DIM_OVERSHOOT; + let variant = if is_default { String::new() } else { format!("_{}-{}-{}-{}", js_number(th), js_number(tick), js_number(gap), js_number(over)).replace('.', ",") }; + let name = format!("DOSSIER_1-{}{}{}", js_number(scale), if cm { "_cm" } else { "" }, variant); + let ts = self.style_of(None); + let style = self.flat.add_dim_style( + &name, + [ts, scale, th / 1000.0, tick / 1000.0, gap / 1000.0, over / 1000.0, (th * 0.6) / 1000.0, if cm { 0.0 } else { 2.0 }, if cm { 100.0 } else { 1.0 }], + ); + let mm = |v: f64| (v / 1000.0) * scale; + let text_h = mm(th); + for i in 0..pts.len().saturating_sub(1) { + let a = V2 { x: pts[i].x, y: pts[i].y }; + let q = V2 { x: pts[i + 1].x, y: pts[i + 1].y }; + let len = hypot(&[q.x - a.x, q.y - a.y]); + if len < 1e-6 { + continue; + } + let nx = -(q.y - a.y) / len; + let ny = (q.x - a.x) / len; + let on = V2 { x: a.x + nx * offset, y: a.y + ny * offset }; + let text_at = text_offsets_mm.as_ref().and_then(|l| l.get(i)).filter(|o| o.along != 0.0 || o.perp != 0.0).map(|o| { + let (base, read, up) = dim_text_frame(a, q, *offset, text_h); + let (al, pe) = (mm(o.along), mm(o.perp)); + let pos = V2 { x: base.x + read.x * al + up.x * pe, y: base.y + read.y * al + up.y * pe }; + V2 { x: pos.x + up.x * (text_h / 2.0), y: pos.y + up.y * (text_h / 2.0) } + }); + self.flat.add_dimension(b, layer, style, a, q, on, text_at); + } + } + + /// Blockinstanz → BLOCK je Definition + INSERT (`emitBlockInstance`); `false` = als lose Primitive. + fn block_instance(&mut self, b: &mut Buf, d: &Drawing2D, prims: &[&Prim], layer: &str, names: &mut BlockNames) -> bool { + let Drawing2DGeom::Block { block_def_id, at, rotation, scale, .. } = &d.geom else { return false }; + let Some(def) = self.project.block_defs.as_ref().and_then(|l| l.iter().find(|x| &x.id == block_def_id)) else { return false }; + let s = scale.unwrap_or(1.0); + if !(s > 0.0) || !s.is_finite() || !rotation.is_finite() || !at.x.is_finite() || !at.y.is_finite() { + return false; + } + let trimmed = js_trim(&def.name); + let wish = if trimmed.is_empty() { "Block" } else { trimmed }; + let (name, fresh) = names.name(&format!("blockdef:{}", def.id), wish); + let at = V2 { x: at.x, y: at.y }; + if fresh { + let frame = Frame { origin: at, rot: *rotation, scale: s }; + let mut content = Buf::block(); + for p in prims { + if let Some(lp) = to_local(p, frame) { + self.emit(&mut content, &lp, LAYER_ZERO, LAYER_ZERO); + } + } + self.flat.set_pen(&mut content, -1.0); + let desc = def.name.clone(); + self.flat.define_block(b, &name, &desc, &[], content); + } + self.flat.add_insert(b, layer, &name, at, *rotation, s, &[]); + true + } + + /// Tür/Fenster → BLOCK in Wandrichtung + INSERT mit Attributen (`emitOpening`). + fn opening(&mut self, b: &mut Buf, o: &Opening, prims: &[&Prim], layer: &str, names: &mut BlockNames) -> bool { + let Some(wall) = self.project.walls.iter().find(|w| w.id == o.host_wall_id) else { return false }; + let len = hypot(&[wall.end.x - wall.start.x, wall.end.y - wall.start.y]); + if len < 1e-6 || !o.position.is_finite() { + return false; + } + let ux = (wall.end.x - wall.start.x) / len; + let uy = (wall.end.y - wall.start.y) / len; + let origin = V2 { x: wall.start.x + ux * o.position, y: wall.start.y + uy * o.position }; + let rot = jsnum::atan2(uy, ux); + let frame = Frame { origin, rot, scale: 1.0 }; + let mut content = Buf::block(); + for p in prims { + if let Some(lp) = to_local(p, frame) { + self.emit(&mut content, &lp, LAYER_ZERO, LAYER_ZERO); + } + } + self.flat.set_pen(&mut content, -1.0); + let is_door = o.kind == ElementKind::Door; + let wall_opening = o.door_type == Some(OpeningDoorType::Wandoeffnung); + let kind_name = if !is_door { + "Fenster" + } else if wall_opening { + "Wandoeffnung" + } else { + "Tuer" + }; + let cm = |v: f64| js_number(jsnum::round(v * 100.0)); + let wish = format!("{kind_name}_{}x{}", cm(o.width), cm(o.height)); + let key = format!("{kind_name}:{}", round_key(content.nums.as_deref().unwrap_or(&[]))); + let (name, fresh) = names.name(&key, &wish); + let mut atts: Vec<(&str, &str, &str)> = + vec![("ID", "Kennung", ""), ("TYP", "Art", kind_name), ("TYPENAME", "Typ", ""), ("BREITE_M", "Breite [m]", ""), ("HOEHE_M", "Hoehe [m]", "")]; + if !is_door { + atts.push(("BRUESTUNG_M", "Bruestung [m]", "")); + } + let label = if !is_door { + "Fenster" + } else if wall_opening { + "Wandöffnung" + } else { + "Tür" + }; + if fresh { + let desc = format!("{label} {} × {} m", m2(o.width), m2(o.height)); + self.flat.define_block(b, &name, &desc, &atts, content); + } + let type_name = o + .type_id + .as_ref() + .and_then(|tid| { + if is_door { + self.project.door_types.as_ref()?.iter().find(|t| &t.id == tid).map(|t| t.name.clone()) + } else { + self.project.window_types.as_ref()?.iter().find(|t| &t.id == tid).map(|t| t.name.clone()) + } + }) + .unwrap_or_default(); + let mut values: Vec<(&str, String)> = + vec![("ID", o.id.clone()), ("TYP", label.to_string()), ("TYPENAME", type_name), ("BREITE_M", m2(o.width)), ("HOEHE_M", m2(o.height))]; + if !is_door { + values.push(("BRUESTUNG_M", m2(o.sill_height))); + } + self.flat.add_insert(b, layer, &name, origin, rot, 1.0, &values); + true + } +} + +/// `dimTextFrame`: (Grundpunkt, Leserichtung, quer dazu). +fn dim_text_frame(a: V2, b: V2, offset: f64, text_height: f64) -> (V2, V2, V2) { + let dx = b.x - a.x; + let dy = b.y - a.y; + let h = hypot(&[dx, dy]); + let len = if h == 0.0 || h.is_nan() { 1.0 } else { h }; + let nx = -dy / len; + let ny = dx / len; + let mid = V2 { x: (a.x + b.x) / 2.0 + nx * offset, y: (a.y + b.y) / 2.0 + ny * offset }; + let mut angle = jsnum::atan2(dy, dx); + if jsnum::cos(angle) < 0.0 { + angle += PI; + } + let read = V2 { x: jsnum::cos(angle), y: jsnum::sin(angle) }; + let up = V2 { x: -jsnum::sin(angle), y: jsnum::cos(angle) }; + (V2 { x: mid.x + up.x * text_height * 0.6, y: mid.y + up.y * text_height * 0.6 }, read, up) +} + +fn flatten<'a>(cats: &'a [LayerCategory], out: &mut Vec<&'a LayerCategory>) { + for c in cats { + out.push(c); + if let Some(ch) = &c.children { + flatten(ch, out); + } + } +} + +/// Sammelt die flache Zeichnung aus den Abschnitten des Plans (`texts`: Text-Eingabe je +/// Plan-Index). `None` bei kaputtem Puffer. +pub fn collect(parts: &mut [Part], texts: &HashMap, project: &Project, o: &DxfOptions) -> Option { + // Primitive in Plan-Reihenfolge lesen. + let mut entries: Vec = Vec::new(); + let mut gi = 0usize; + for part in parts.iter_mut() { + let hatches = part.view.hatch_table()?; + for i in part.from..part.to { + entries.push(read_entry(part, i, &hatches, texts.get(&gi))?); + gi += 1; + } + } + + let mut cx = Ctx { project, o, flat: Flat::new() }; + let mut main = Buf::main(); + + // 1) Ebenen aus den Kategorien (Code_Name, Farbe, Strichstärke), dann die Sammel-Ebenen. + let mut cats = Vec::new(); + flatten(&project.layers, &mut cats); + let mut layer_by_code: HashMap<&str, String> = HashMap::new(); + for c in &cats { + let name = format!("{}_{}", c.code, c.name); + cx.flat.add_layer(&name, Some(rgb_from_hex(&c.color)), mm_to_lwe(c.lw)); + layer_by_code.insert(c.code.as_str(), name); + } + cx.flat.add_layer(LAYER_SYMBOLS, Some(0x111111 as f64), 18.0); + cx.flat.add_layer(LAYER_HATCH, Some(0x888888 as f64), 13.0); + cx.flat.add_layer(LAYER_CONTEXT, Some(0x9aa3ad as f64), 10.0); + cx.flat.add_layer(LAYER_DEFAULT, Some(0x111111 as f64), 18.0); + cx.flat.add_layer(LAYER_SECTIONS, Some(0x111111 as f64), 18.0); + cx.flat.add_layer(LAYER_EXTRUSION, Some(rgb_from_hex("#d98c40")), 13.0); + cx.flat.add_layer(LAYER_ZERO, None, 25.0); + + // 2) Rückverweise Primitiv → Kategorie. + let code_by_wall: HashMap<&str, &str> = project.walls.iter().map(|w| (w.id.as_str(), w.category_code.as_str())).collect(); + let code_by_drawing: HashMap<&str, &str> = project.drawings2d.iter().map(|d| (d.id.as_str(), d.category_code.as_str())).collect(); + let code_by_column: HashMap<&str, &str> = project.columns.iter().flatten().map(|c| (c.id.as_str(), c.category_code.as_str())).collect(); + let code_by_room: HashMap<&str, &str> = project.rooms.iter().flatten().map(|r| (r.id.as_str(), r.category_code.as_str())).collect(); + let layer_of_code = |m: &HashMap<&str, &str>, id: &str| -> Option { layer_by_code.get(m.get(id).copied().unwrap_or("")).cloned() }; + let drawing_layer = |id: Option<&String>, fallback: &str| -> String { + match id { + Some(id) => layer_of_code(&code_by_drawing, id).unwrap_or_else(|| LAYER_DEFAULT.to_string()), + None => fallback.to_string(), + } + }; + let layer_for = |e: &Entry| -> String { + match e.tag { + T_POLYGON => { + if let Some(w) = &e.ids.wall { + return layer_of_code(&code_by_wall, w).unwrap_or_else(|| LAYER_DEFAULT.to_string()); + } + if e.ids.drawing.is_some() { + return drawing_layer(e.ids.drawing.as_ref(), LAYER_DEFAULT); + } + if let Some(c) = &e.ids.column { + return layer_of_code(&code_by_column, c).unwrap_or_else(|| LAYER_DEFAULT.to_string()); + } + if e.ids.solid.is_some() { + return LAYER_EXTRUSION.to_string(); + } + LAYER_DEFAULT.to_string() + } + T_LINE => { + let cls = match &e.prim { + Prim::Line { cls, .. } => cls.as_str(), + _ => "", + }; + if cls == "context-line" { + return LAYER_CONTEXT.to_string(); + } + if cls == "section-line" { + return LAYER_SECTIONS.to_string(); + } + drawing_layer(e.ids.drawing.as_ref(), LAYER_SYMBOLS) + } + T_DRAWING_TEXT => drawing_layer(e.ids.drawing.as_ref(), LAYER_SYMBOLS), + T_TEXT => match &e.ids.room { + Some(r) => layer_of_code(&code_by_room, r).unwrap_or_else(|| LAYER_SYMBOLS.to_string()), + None => LAYER_SYMBOLS.to_string(), + }, + _ => LAYER_SYMBOLS.to_string(), + } + }; + + // 3) Gruppen: Bemassungen, Blockinstanzen und Öffnungen werden CAD-Objekte. + let mut dim_by_id: HashMap<&str, &Drawing2D> = HashMap::new(); + let mut block_by_id: HashMap<&str, &Drawing2D> = HashMap::new(); + for d in &project.drawings2d { + match d.geom { + Drawing2DGeom::Dimension { .. } => { + dim_by_id.insert(d.id.as_str(), d); + } + Drawing2DGeom::Block { .. } => { + block_by_id.insert(d.id.as_str(), d); + } + _ => {} + } + } + let opening_by_id: HashMap<&str, &Opening> = project.openings.iter().flatten().map(|x| (x.id.as_str(), x)).collect(); + let group_key = |e: &Entry| -> Option<(u8, String)> { + if let Some(did) = &e.ids.drawing { + if dim_by_id.contains_key(did.as_str()) { + return Some((b'd', did.clone())); + } + if block_by_id.contains_key(did.as_str()) { + return Some((b'b', did.clone())); + } + } + if let Some(oid) = &e.ids.opening { + if opening_by_id.contains_key(oid.as_str()) { + return Some((b'o', oid.clone())); + } + } + None + }; + let keys: Vec> = entries.iter().map(group_key).collect(); + let mut groups: HashMap<&(u8, String), Vec> = HashMap::new(); + for (i, k) in keys.iter().enumerate() { + if let Some(k) = k { + groups.entry(k).or_default().push(i); + } + } + let mut names = BlockNames::default(); + let mut done: HashSet<&(u8, String)> = HashSet::new(); + + // 4) Jedes Primitiv in Entitäten übersetzen. + for (i, e) in entries.iter().enumerate() { + if let Some(key) = &keys[i] { + if !done.insert(key) { + continue; + } + let members: Vec<&Entry> = groups.get(key).map(|l| l.iter().map(|&k| &entries[k]).collect()).unwrap_or_default(); + let prims: Vec<&Prim> = members.iter().map(|m| &m.prim).collect(); + let id = key.1.as_str(); + match key.0 { + b'd' => { + let d = dim_by_id[id]; + let layer = drawing_layer(Some(&key.1), LAYER_DEFAULT); + cx.dimensions(&mut main, d, &layer); + } + b'b' => { + let d = block_by_id[id]; + let layer = drawing_layer(Some(&d.id), LAYER_DEFAULT); + if !cx.block_instance(&mut main, d, &prims, &layer, &mut names) { + for m in &members { + let l = layer_for(m); + cx.emit(&mut main, &m.prim, &l, LAYER_HATCH); + } + } + } + _ => { + let op = opening_by_id[id]; + let layer = layer_by_code.get(op.category_code.as_str()).cloned().unwrap_or_else(|| LAYER_SYMBOLS.to_string()); + if !cx.opening(&mut main, op, &prims, &layer, &mut names) { + for m in &members { + let l = layer_for(m); + cx.emit(&mut main, &m.prim, &l, LAYER_HATCH); + } + } + } + } + continue; + } + let l = layer_for(e); + cx.emit(&mut main, &e.prim, &l, LAYER_HATCH); + } + cx.flat.set_pen(&mut main, -1.0); + + // 5) Papierbereich (optional): Layout mit Ansichtsfenster im Planmassstab. + if o.paper_layout { + let [min_x, min_y, max_x, max_y] = o.bounds; + let w = max_x - min_x; + let h = max_y - min_y; + if [min_x, min_y, max_x, max_y].iter().all(|v| v.is_finite()) && w > 0.0 && h > 0.0 { + let (pw, ph, vw, vh) = paper_for(w, h, o.scale, 10.0); + let s = cx.flat.str(&format!("Plan 1-{}", js_number(o.scale))); + cx.flat.push(&mut main, &[REC_LAYOUT, s, pw, ph, pw / 2.0, ph / 2.0, vw, vh, (min_x + max_x) / 2.0, (min_y + max_y) / 2.0, o.scale]); + } + } + let Flat { root, strings, block_counts, .. } = cx.flat; + Some(FlatDxf { nums: root, strings, model: main.counts, blocks: block_counts }) +} + +/// Text-Eingabe aus TS lesen: Zahlen `[Index, Art, …]` (s. `src/export/exportDxf.ts`), Texte. +/// Art 6 (Raumstempel): `[x, y, nZeilen, (Text, Höhe, Ausrichtung, Schrift, fett, kursiv, ab)*]`; +/// Art 7 (Einzeltext): `[x, y, Winkel, Höhe, Spalte, Schrift, fett, kursiv, nAbsätze, +/// (Absatz, nWörter, Wort*)*]`. Schrift/Text = Index in `strs`. +pub fn texts_from(nums: &[f64], strs: &[&str]) -> Option> { + let mut out = HashMap::new(); + let mut k = 0usize; + let mut next = || -> Option { + let v = *nums.get(k)?; + k += 1; + Some(v) + }; + let s_of = |v: f64| -> Option { strs.get(whole(v)?).map(|s| s.to_string()) }; + loop { + let Some(idx) = next() else { break }; + let idx = whole(idx)?; + let kind = next()?; + let at = V2 { x: next()?, y: next()? }; + if kind == 6.0 { + let n = whole(next()?)?; + let mut lines = Vec::with_capacity(n.min(1024)); + for _ in 0..n { + let text = s_of(next()?)?; + let height = next()?; + let align = next()?; + let family = s_of(next()?)?; + let bold = next()? != 0.0; + let italic = next()? != 0.0; + let down = next()?; + lines.push(StampLine { text, height, align, style: TextStyleIn { family, bold, italic }, down }); + } + out.insert(idx, TextIn::Stamp { at, lines }); + } else if kind == 7.0 { + let angle = next()?; + let height = next()?; + let wrap = next()?; + let family = s_of(next()?)?; + let bold = next()? != 0.0; + let italic = next()? != 0.0; + let n = whole(next()?)?; + let mut paras = Vec::with_capacity(n.min(1024)); + for _ in 0..n { + let para = s_of(next()?)?; + let nw = whole(next()?)?; + let mut words = Vec::with_capacity(nw.min(1024)); + for _ in 0..nw { + words.push(s_of(next()?)?); + } + paras.push((para, words)); + } + out.insert(idx, TextIn::Single { at, angle, height, wrap, style: TextStyleIn { family, bold, italic }, paras }); + } else { + return None; + } + } + Some(out) +} + +/// Ergebnis als Bytes: f64-Teil `[MAGIC "DXF1", nZahlen, nTexte, 8 Modell-, 8 Block-Zähler, +/// Zahlen…, Länge je Text…]`, danach die Texte als UTF-16. +pub fn encode(f: &FlatDxf) -> Vec { + let mut head: Vec = vec![DXF_MAGIC, f.nums.len() as f64, f.strings.len() as f64]; + head.extend(f.model.iter().map(|v| *v as f64)); + head.extend(f.blocks.iter().map(|v| *v as f64)); + head.extend_from_slice(&f.nums); + let units: Vec> = f.strings.iter().map(|s| s.encode_utf16().collect()).collect(); + head.extend(units.iter().map(|u| u.len() as f64)); + let mut out = Vec::with_capacity(head.len() * 8 + units.iter().map(|u| u.len() * 2).sum::()); + for v in head { + out.extend_from_slice(&v.to_le_bytes()); + } + for u in units { + for c in u { + out.extend_from_slice(&c.to_le_bytes()); + } + } + out +} + +/// Kennung der Antwort (`"DXF1"`). +pub const DXF_MAGIC: f64 = 0x4458_4631 as f64; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn linientyp_aus_strichmuster() { + assert_eq!(dash_to_ltype_meters(&[2.0, 1.0], 100.0), Some(vec![0.2, -0.1])); + // Ungerade Länge wird verdoppelt, Lücke 0 → 1 µm. + assert_eq!(dash_to_ltype_meters(&[3.0], 50.0).map(|v| v.len()), Some(2)); + assert_eq!(dash_to_ltype_meters(&[1.0, 0.0], 100.0), Some(vec![0.1, -1e-6])); + assert_eq!(dash_to_ltype_meters(&[0.0, 0.0], 100.0), None); + assert_eq!(dash_to_ltype_meters(&[], 100.0), None); + assert_eq!(ltype_name_for(&[2.0, 0.5], &[]), "DOSSIER_STRICH_2_0.5"); + let r6 = |v: Vec| v.iter().map(|x| (x * 1e6).round() / 1e6).collect::>(); + assert_eq!(r6(dash_to_ltype_meters(&[2.0, 1.0, 0.5], 50.0).unwrap()), vec![0.1, -0.05, 0.025, -0.1, 0.05, -0.025]); + // Punkt (Strich 0) bleibt 0. + assert_eq!(dash_to_ltype_meters(&[0.0, 1.0], 100.0).unwrap()[0], 0.0); + // Projekt-Linienstil mit gleichem Muster (Name getrimmt); andere Arten zählen nicht. + let st = |name: &str, kind: Option| LineStyle { name: name.into(), dash: Some(vec![3.0, 1.0]), kind, ..Default::default() }; + assert_eq!(ltype_name_for(&[3.0, 1.0], &[st(" Strichlinie ", None)]), "Strichlinie"); + assert_eq!(ltype_name_for(&[3.0, 1.0], &[st("Zz", Some(LineStyleKind::Zigzag)), st(" ", None)]), "DOSSIER_STRICH_3_1"); + } + + #[test] + fn blocklokal_verschoben_gedreht_skaliert() { + let f = Frame { origin: V2 { x: 10.0, y: 5.0 }, rot: PI / 2.0, scale: 2.0 }; + let Some(Prim::Line { a, b, .. }) = to_local(&Prim::Line { a: V2 { x: 10.0, y: 5.0 }, b: V2 { x: 10.0, y: 9.0 }, cls: "x".into(), dash: vec![], zigzag: None, motif: None }, f) else { panic!() }; + assert!(a.x.abs() < 1e-12 && a.y.abs() < 1e-12); + // 4 m in Richtung +y = lokale +x, durch Skalierung 2. + assert!((b.x - 2.0).abs() < 1e-12 && b.y.abs() < 1e-12); + let style = TextStyleIn { family: "Arial".into(), bold: false, italic: false }; + let Some(Prim::Single { height, angle, wrap, .. }) = to_local(&Prim::Single { at: V2 { x: 10.0, y: 5.0 }, angle: PI / 2.0, height: 0.4, wrap: 0.0, style, paras: vec![] }, f) else { panic!() }; + assert!((height - 0.2).abs() < 1e-12 && angle.abs() < 1e-12 && wrap == 0.0); + let Some(Prim::Circle { center, r, .. }) = to_local(&Prim::Circle { center: V2 { x: 10.0, y: 7.0 }, r: 1.0, dash: vec![] }, f) else { panic!() }; + assert!((r - 0.5).abs() < 1e-12 && (center.x - 1.0).abs() < 1e-12); + assert!(to_local(&Prim::Other, f).is_none()); + assert_eq!(round_key(&[1.0001, 2.0]), round_key(&[1.0004, 2.0])); + assert_ne!(round_key(&[1.0001, 2.0]), round_key(&[1.002, 2.0])); + } + + #[test] + fn papierformat_und_schluessel() { + // 20 × 10 m bei 1:100 → 220 × 120 mm passt auf A4 quer. + assert_eq!(paper_for(20.0, 10.0, 100.0, 10.0), (297.0, 210.0, 277.0, 190.0)); + // Hochformat-Ausschnitt → A4 hoch. + assert_eq!(paper_for(10.0, 20.0, 100.0, 10.0), (210.0, 297.0, 190.0, 277.0)); + // Zu gross für A0 → Sonderformat in 10-mm-Schritten. + assert_eq!(paper_for(200.0, 100.0, 100.0, 10.0).0, 2020.0); + // 30 × 18 m bei 1:100 → A3. + assert_eq!(paper_for(30.0, 18.0, 100.0, 10.0).0, 420.0); + assert_eq!(round_key(&[0.0004, -0.0004, 1.2345]), "0,0,1235,"); + } + + #[test] + fn farben_und_zeilen() { + assert_eq!(rgb_from_hex(" #A0b1C2 "), 0xa0b1c2 as f64); + assert_eq!(rgb_from_hex("rot"), 0x111111 as f64); + assert_eq!(rgb_or_null("#abc"), Some(0xaabbcc as f64)); + assert_eq!(rgb_or_null("none"), None); + let words = |s: &str| s.split(' ').map(|w| w.to_string()).collect::>(); + let lines = single_lines(1.0, 3.0, &[("aa bb cc".into(), words("aa bb cc"))]); + // maxChars = floor(3 / 0.55) = 5 → "aa bb", "cc". + assert_eq!(lines.iter().map(|l| l.0.as_str()).collect::>(), vec!["aa bb", "cc"]); + assert_eq!(lines[1].1, 1.25); + } +} diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index 5e147ebe..1b7ef8c3 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -11,7 +11,7 @@ thread_local! { static DOCS: RefCell>> = const { RefCell::new(Vec::new()) }; } -fn with_doc(h: u32, f: impl FnOnce(&mut Document) -> R) -> Option { +pub(crate) fn with_doc(h: u32, f: impl FnOnce(&mut Document) -> R) -> Option { DOCS.with(|d| d.borrow_mut().get_mut((h as usize).checked_sub(1)?)?.as_mut().map(f)) } diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index a4d1f583..6d66501e 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -36,6 +36,7 @@ mod plan_scene; mod plan_pick; mod snap; mod plan_svg; +mod plan_dxf; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/plan_dxf.rs b/src-tauri/core/src/web/plan_dxf.rs new file mode 100644 index 00000000..96933435 --- /dev/null +++ b/src-tauri/core/src/web/plan_dxf.rs @@ -0,0 +1,36 @@ +//! Bindung des DXF-Sammlers (`crate::plan_dxf`) auf gehaltenen Plan-Puffern (Abschnitte wie +//! `plan_parts`) und dem Projekt-Dokument. Leeres Ergebnis = Puffer fehlt (TS legt neu ab und +//! fragt nochmals), Dokument nicht offen/unpassend oder kaputte Eingabe — nie Panic. + +use crate::plan_dxf::{collect, encode, texts_from, DxfOptions}; +use crate::plan_parts::parts_from; +use wasm_bindgen::prelude::wasm_bindgen; + +/// Flache Zeichnung (Format `plan_dxf::encode`). `opts` = `[Massstab, Schraffuren 0/1, cm 0/1, +/// Papierbereich 0/1, minX, minY, maxX, maxY]`; `text_nums`/`text_strs` = Text-Eingabe +/// (`plan_dxf::texts_from`, Texte je mit `\0` davor); `default_font` = Standard-Schrift. +#[wasm_bindgen] +pub fn plan_dxf_flat(doc: u32, segs: &[f64], text_nums: &[f64], text_strs: &str, opts: &[f64], default_font: &str) -> Vec { + let Ok([scale, hatches, cm, layout, min_x, min_y, max_x, max_y]) = <[f64; 8]>::try_from(opts) else { return Vec::new() }; + if !(scale.is_finite() && scale > 0.0) { + return Vec::new(); + } + let strs: Vec<&str> = text_strs.split('\0').skip(1).collect(); + let Some(texts) = texts_from(text_nums, &strs) else { return Vec::new() }; + let Some(held) = super::plan_buf::held_for_segs(segs) else { return Vec::new() }; + let Some(mut parts) = parts_from(segs, |nr| held.iter().find(|e| e.0 == nr).map(|e| &*e.1)) else { return Vec::new() }; + let o = DxfOptions { + scale, + include_hatches: hatches != 0.0, + dim_cm: cm != 0.0, + paper_layout: layout != 0.0, + bounds: [min_x, min_y, max_x, max_y], + default_font: default_font.to_string(), + }; + super::document::with_doc(doc, |d| { + let p = d.project().ok()?; + collect(&mut parts, &texts, p, &o).map(|f| encode(&f)) + }) + .flatten() + .unwrap_or_default() +} diff --git a/src/export/dxfCadParts.test.ts b/src/export/dxfCadParts.test.ts index 71c2e85b..2e7ce4ce 100644 --- a/src/export/dxfCadParts.test.ts +++ b/src/export/dxfCadParts.test.ts @@ -1,7 +1,5 @@ import { describe, expect, it } from "vitest"; -import { dashToLtypeMeters, fontNameOf, ltypeNameFor, paperFor, primitiveToLocal, roundKey } from "./dxfCadParts"; -import type { LineStyle } from "../model/types"; -import type { Primitive } from "../plan/generatePlan"; +import { fontNameOf } from "./dxfCadParts"; describe("fontNameOf", () => { it("erste echte Familie, ohne Anführungszeichen; generische/Variablen übersprungen", () => { @@ -13,64 +11,3 @@ describe("fontNameOf", () => { expect(fontNameOf("")).toBeNull(); }); }); - -describe("Linientypen", () => { - it("Papier-mm × Massstab → Meter (Strich +, Lücke −); ungerade Muster werden verdoppelt", () => { - expect(dashToLtypeMeters([3, 1], 100)!.map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.3, -0.1]); - expect(dashToLtypeMeters([2, 1, 0.5], 50)!.map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.1, -0.05, 0.025, -0.1, 0.05, -0.025]); - expect(dashToLtypeMeters([], 100)).toBeNull(); - expect(dashToLtypeMeters([0, 0], 100)).toBeNull(); - // Punkt (Strich 0) bleibt 0, Lücke nie 0 - const dot = dashToLtypeMeters([0, 0], 100); - expect(dot).toBeNull(); - expect(dashToLtypeMeters([0, 1], 100)![0]).toBe(0); - }); - - it("Name: Projekt-Linienstil mit gleichem Muster, sonst DOSSIER_STRICH_…", () => { - const styles = [{ id: "a", name: " Strichlinie ", weight: 0.1, color: "#000", dash: [3, 1] }] as LineStyle[]; - expect(ltypeNameFor([3, 1], styles)).toBe("Strichlinie"); - expect(ltypeNameFor([2, 0.5], styles)).toBe("DOSSIER_STRICH_2_0.5"); - }); -}); - -describe("Papierbereich", () => { - it("kleinstes Format, das den Ausschnitt samt Rand aufnimmt", () => { - // 20 m × 12 m bei 1:100 = 200 × 120 mm + 20 mm Rand → A4 quer - expect(paperFor(20, 12, 100)).toMatchObject({ name: "A4", paperW: 297, paperH: 210, vpW: 277, vpH: 190 }); - // 30 m × 18 m bei 1:100 → 300 × 180 (+20): A3 - expect(paperFor(30, 18, 100).name).toBe("A3"); - // Hochformat, wenn nur so passend - expect(paperFor(12, 20, 100)).toMatchObject({ name: "A4", paperW: 210, paperH: 297 }); - // grösser als A0: Sonderformat in 10-mm-Schritten - const big = paperFor(200, 100, 50); - expect(big.name).toBe("Sonder"); - expect(big.paperW % 10).toBe(0); - }); -}); - -describe("primitiveToLocal", () => { - const frame = { origin: { x: 10, y: 5 }, rot: Math.PI / 2, scale: 2 }; - it("Linie, Bogen, Kreis, Text: verschoben, gedreht, skaliert", () => { - const line = { kind: "line", a: { x: 10, y: 5 }, b: { x: 10, y: 9 }, cls: "x", weightMm: 0.1 } as Primitive; - const l = primitiveToLocal(line, frame) as Extract; - expect(l.a.x).toBeCloseTo(0, 12); - expect(l.a.y).toBeCloseTo(0, 12); - expect(l.b.x).toBeCloseTo(2, 12); // 4 m in Richtung +y = lokale +x, durch Skalierung 2 - expect(l.b.y).toBeCloseTo(0, 12); - const text = { kind: "drawingText", at: { x: 10, y: 5 }, text: "a", heightM: 0.4, angle: Math.PI / 2, color: "#000" } as Primitive; - const t = primitiveToLocal(text, frame) as Extract; - expect(t.heightM).toBeCloseTo(0.2, 12); - expect(t.angle).toBeCloseTo(0, 12); - const circle = { kind: "drawingCircle", center: { x: 10, y: 7 }, r: 1, fill: "none", stroke: "#000", weightMm: 0.1 } as Primitive; - const c = primitiveToLocal(circle, frame) as Extract; - expect(c.r).toBeCloseTo(0.5, 12); - expect(c.center.x).toBeCloseTo(1, 12); - }); - it("andere Primitivarten (Raumstempel, Bild) gehören nicht in Blöcke", () => { - expect(primitiveToLocal({ kind: "drawingImage" } as Primitive, frame)).toBeNull(); - }); - it("roundKey: auf 1 mm gerundet", () => { - expect(roundKey([1.0001, 2])).toBe(roundKey([1.0004, 2])); - expect(roundKey([1.0001, 2])).not.toBe(roundKey([1.002, 2])); - }); -}); diff --git a/src/export/dxfCadParts.ts b/src/export/dxfCadParts.ts index 94c24a2e..ff2beb33 100644 --- a/src/export/dxfCadParts.ts +++ b/src/export/dxfCadParts.ts @@ -1,9 +1,6 @@ -// Bausteine des Fachplaner-Exports ([C2], 28.10.): reine Hilfsfunktionen für `exportDxf.ts` — -// Schriftname aus CSS-Familie, Linientyp-Namen aus Strichmustern, Umrechnung von Plan-Primitiven in ein -// lokales Koordinatensystem (für Blöcke) und Papierformate. Keine Abhängigkeit vom Writer. - -import type { Primitive } from "../plan/generatePlan"; -import type { LineStyle, Vec2 } from "../model/types"; +// Baustein des Fachplaner-Exports ([C2], 28.10.): Schriftname aus CSS-Familie (Text-Layout bleibt TS). +// Linientypen, blocklokale Primitive, Papierformate und der Sammler selbst liegen seit [K3d] im Kern +// (`src-tauri/core/src/plan_dxf.rs`). /** Erste Schriftfamilie aus einem CSS-`font-family`-Wert ohne Anführungszeichen; generische Familien/CSS-Variablen → null. */ export function fontNameOf(css: string | undefined | null): string | null { @@ -17,113 +14,3 @@ export function fontNameOf(css: string | undefined | null): string | null { } return null; } - -/** Strichmuster (Papier-mm, an/aus/…) → DXF-Linientyp-Elemente in Modell-Metern (Strich +, Lücke −, Punkt 0). */ -export function dashToLtypeMeters(dashMm: number[], scaleDenominator: number): number[] | null { - let pat = dashMm.map((d) => (Number.isFinite(d) ? Math.max(0, d) : 0)); - if (pat.length === 0 || pat.every((d) => d === 0)) return null; - if (pat.length % 2 === 1) pat = pat.concat(pat); - const k = scaleDenominator / 1000; - const out: number[] = []; - for (let i = 0; i < pat.length; i++) { - const len = pat[i] * k; - out.push(i % 2 === 0 ? len : -Math.max(len, 1e-6)); - } - // Eine Lücke von 0 ergäbe ein Muster ohne Unterbrechung; mindestens 1 µm. - return out; -} - -/** Zahl für Namen: höchstens 2 Nachkommastellen, ohne Nullen am Ende. */ -function n2(v: number): string { - return String(Math.round(v * 100) / 100); -} - -/** - * Name des Linientyps zu einem Strichmuster: der Name des Projekt-Linienstils mit demselben Muster, sonst - * `DOSSIER_STRICH__…` (Papier-mm). - */ -export function ltypeNameFor(dashMm: number[], styles: readonly LineStyle[]): string { - const same = (a: number[], b: number[]) => a.length === b.length && a.every((v, i) => Math.abs(v - b[i]) < 1e-9); - const hit = styles.find((s) => s.dash && s.dash.length > 0 && (s.kind ?? "dash") === "dash" && same(s.dash, dashMm)); - if (hit && hit.name.trim()) return hit.name.trim(); - return `DOSSIER_STRICH_${dashMm.map(n2).join("_")}`; -} - -// ── Lokales Koordinatensystem (Blöcke) ──────────────────────────────────────── - -/** Abbildung Modell → blocklokal: Verschiebung `-origin`, Drehung `-rot`, Skalierung `1/scale`. */ -export interface LocalFrame { - origin: Vec2; - /** Drehung des Blocks im Modell (Radiant). */ - rot: number; - scale: number; -} - -function toLocal(f: LocalFrame, p: Vec2): Vec2 { - const c = Math.cos(f.rot); - const s = Math.sin(f.rot); - const dx = p.x - f.origin.x; - const dy = p.y - f.origin.y; - return { x: (dx * c + dy * s) / f.scale, y: (-dx * s + dy * c) / f.scale }; -} - -/** Primitive im lokalen System des Blocks (nur Geometrie-Arten, die in Blöcken vorkommen); andere → null. */ -export function primitiveToLocal(p: Primitive, f: LocalFrame): Primitive | null { - const rotDeg = (f.rot * 180) / Math.PI; - switch (p.kind) { - case "line": - return { ...p, a: toLocal(f, p.a), b: toLocal(f, p.b), motif: undefined, zigzag: p.zigzag && { amplitude: p.zigzag.amplitude / f.scale, wavelength: p.zigzag.wavelength / f.scale } }; - case "arc": - return { ...p, center: toLocal(f, p.center), from: toLocal(f, p.from), to: toLocal(f, p.to), r: p.r / f.scale }; - case "polygon": - return { ...p, pts: p.pts.map((q) => toLocal(f, q)), hatch: { ...p.hatch, angle: p.hatch.angle - rotDeg } }; - case "drawingCircle": - return { ...p, center: toLocal(f, p.center), r: p.r / f.scale }; - case "drawingArc": - return { ...p, center: toLocal(f, p.center), r: p.r / f.scale, a0: p.a0 - f.rot, a1: p.a1 - f.rot }; - case "drawingText": - return { ...p, at: toLocal(f, p.at), heightM: p.heightM / f.scale, angle: p.angle - f.rot, wrapWidth: p.wrapWidth && p.wrapWidth / f.scale }; - default: - return null; - } -} - -/** Schlüssel gleicher lokaler Geometrie: Zahlen auf 1 mm gerundet (Blöcke teilen sich nur identische Inhalte). */ -export function roundKey(nums: readonly number[]): string { - let out = ""; - for (const v of nums) out += `${Math.round(v * 1000)},`; - return out; -} - -// ── Papierbereich ──────────────────────────────────────────────────────────── - -/** Papierformate (mm, quer) in aufsteigender Grösse. */ -const PAPER_SIZES: [string, number, number][] = [ - ["A4", 297, 210], - ["A3", 420, 297], - ["A2", 594, 420], - ["A1", 841, 594], - ["A0", 1189, 841], -]; - -/** - * Papier und Ansichtsfenster für einen Ausschnitt der Grösse `w` × `h` Meter im Massstab 1:`scale`: - * kleinstes A-Format (quer, sonst hoch), das den Ausschnitt mit `margin` mm Rand aufnimmt; ist keines - * gross genug, ein Sonderformat in Vielfachen von 10 mm. Das Fenster füllt das Papier abzüglich Rand. - */ -export function paperFor( - w: number, - h: number, - scale: number, - margin = 10, -): { paperW: number; paperH: number; vpW: number; vpH: number; name: string } { - const needW = (w * 1000) / scale + 2 * margin; - const needH = (h * 1000) / scale + 2 * margin; - for (const [name, pw, ph] of PAPER_SIZES) { - if (needW <= pw && needH <= ph) return { paperW: pw, paperH: ph, vpW: pw - 2 * margin, vpH: ph - 2 * margin, name }; - if (needW <= ph && needH <= pw) return { paperW: ph, paperH: pw, vpW: ph - 2 * margin, vpH: pw - 2 * margin, name }; - } - const pw = Math.ceil(needW / 10) * 10; - const ph = Math.ceil(needH / 10) * 10; - return { paperW: pw, paperH: ph, vpW: pw - 2 * margin, vpH: ph - 2 * margin, name: "Sonder" }; -} diff --git a/src/export/exportDxf.ts b/src/export/exportDxf.ts index 12003f3a..a9a0b6c0 100644 --- a/src/export/exportDxf.ts +++ b/src/export/exportDxf.ts @@ -1,5 +1,5 @@ // DXF-/DWG-Export des Grundrisses. Nutzt DIESELBE Quelle wie der PDF-Export — den -// Vektor-Plan (generatePlan → Primitive) — schreibt aber MODELL-SPACE-Geometrie +// Vektor-Plan (generatePlan → Plan-Puffer) — schreibt aber MODELL-SPACE-Geometrie // in ECHTEN Metern (kein Papier-mm, keine Y-Spiegelung). So können nachgelagerte // CAD-Nutzer beim Plot beliebig skalieren; die Datei ist masshaltig 1:1 in Metern. // @@ -8,11 +8,12 @@ // direkten Kategorie-Bezug (Tür-Symbole, Kontext, Schraffuren) landen auf // sprechenden Sammel-Layern. // -// Seit [C1]/[C2] (28.10.) schreibt Rust (acadrust, `src-tauri/fileio/src/export.rs`) die Datei: -// dieses Modul sammelt nur Ebenen und Entitäten aus dem `Plan` in eine flache Zeichnung -// (`FlatDrawing`, Kodierung s. export.rs) und übergibt sie. DXF = R2018 ASCII (UTF-8), -// DWG = R2018 — Begründung im Kopf von export.rs. Der frühere TS-Text-Writer -// (`dxfWriter.ts`) ist gelöscht. Das Format-Modul wird nachgeladen: vor `buildPlanDxf`/ +// Seit [K3d] (29.10.) sammelt der Kern (`src-tauri/core/src/plan_dxf.rs`) Ebenen und Entitäten +// direkt aus den Plan-Puffern und dem Projekt-Dokument in die flache Zeichnung (Kodierung s. +// `src-tauri/fileio/src/export.rs`); Rust (acadrust, fileio) schreibt die Datei ([C1]/[C2]). +// DXF = R2018 ASCII (UTF-8), DWG = R2018. Hier bleibt das Text-Layout (Zeilen der Raumstempel, +// Absätze/Wörter der Einzeltexte, Schriftfamilien) — es geht als flache Eingabe an den Kern — +// und die Übergabe an fileio. Das Format-Modul wird nachgeladen: vor `buildPlanDxf`/ // `buildPlanDwg` einmal `await loadFileio()` (savePlanDxf und die CLI tun das). // // Fachplaner-Export (28.10., [C2]): damit in AutoCAD/BricsCAD weitergearbeitet werden kann, entstehen @@ -27,16 +28,17 @@ // Alles andere (Wände, Umrisse, Schraffuren) bleibt wie bisher Linie/Polylinie/HATCH. import type { Plan, Primitive } from "../plan/generatePlan"; -import type { Drawing2D, LayerCategory, Opening, Project, Vec2 } from "../model/types"; +import type { Project } from "../model/types"; import type { Marks } from "../text/richText"; -import { flattenCategories } from "../model/types"; -import { DEFAULT_SCALE_DENOMINATOR, DIM_DEFAULTS_MM, dimTextFrame, dimTextPos, mmToModel } from "../model/dimension"; -import { buildRandomHatchRuns, zigzagPoints, motifPoints } from "../plan/glPlan/glPlanHatch"; +import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension"; import { plainText } from "../text/richText"; import { docToLines } from "../text/renderHtml"; import { fileio, loadFileio } from "../engine/fileioWasm"; -import { dashToLtypeMeters, fontNameOf, ltypeNameFor, paperFor, primitiveToLocal, roundKey } from "./dxfCadParts"; -import type { LocalFrame } from "./dxfCadParts"; +import { core } from "../engine/coreWasm"; +import { documentFor } from "../core/document"; +import { planParts, withPlanParts } from "../plan/planParts"; +import { planTextEntries } from "../plan/planLazy"; +import { fontNameOf } from "./dxfCadParts"; export interface ExportDxfOptions { /** Titel/Geschossname (nur als Kommentar-freundlicher Dateiname genutzt). */ @@ -65,331 +67,19 @@ export function cadExtension(format: CadExportFormat): "dxf" | "dwg" { return format === "dwg" ? "dwg" : "dxf"; } -/** Sammel-Layer-Namen für Primitive ohne eigene Kategorie. */ -const LAYER_HATCH = "HATCH"; -const LAYER_SYMBOLS = "SYMBOLS"; -const LAYER_CONTEXT = "CONTEXT"; -const LAYER_DEFAULT = "PLAN"; -/** Schnittführungs-Symbole (Primitive mit `cls === "section-line"`). */ -const LAYER_SECTIONS = "SECTIONS"; -/** Sammel-Layer für Extrusions-Footprints (truck-Integration) — die Quell- - * Drawing2D wird beim Extrudieren entfernt, es gibt also keine categoryCode - * mehr nachzuschlagen; eigener Layer statt Absturz in LAYER_DEFAULT. */ -const LAYER_EXTRUSION = "EXTRUSION"; -/** Ebene „0": Inhalt von Blöcken (erbt die Ebene des INSERT). */ -const LAYER_ZERO = "0"; - -// ── Flache Zeichnung (Gegenstück zu src-tauri/fileio/src/export.rs) ───────── - -const FLAT_VERSION = 1; -const REC_LAYER = 1; -const REC_LINE = 2; -const REC_POLYLINE = 3; -const REC_ARC = 4; -const REC_CIRCLE = 5; -const REC_TEXT = 6; -const REC_HATCH = 7; -const REC_GRADIENT = 8; -const REC_LTYPE = 9; -const REC_LAYER_LTYPE = 10; -const REC_PEN = 11; -const REC_STYLE = 12; -const REC_TEXT2 = 13; -const REC_DIMSTYLE = 14; -const REC_DIM = 15; -const REC_BLOCK = 16; -const REC_BLOCK_END = 17; -const REC_INSERT = 18; -const REC_LAYOUT = 19; - -/** Zustand, den eine Zeichnung und die Blockinhalte, die in sie hineingespleisst werden, teilen. */ -interface FlatShared { - /** Der Zahlenpuffer der Hauptzeichnung: Definitionen (Ebenen, Linientypen, Stile) landen immer hier, in Reihenfolge ihrer Indizes. */ - root: number[]; - strings: string[]; - strIdx: Map; - layers: Map; - ltypes: Map; - styles: Map; - dimStyles: Map; - blocks: Set; - /** Entitäten in Blockdefinitionen (Zählung für Tests). */ - blockCounts: Record; -} - -/** Eine Textzeile der Raumstempel/Textfelder für `addText2`. */ -export interface TextAlignOpts { - /** 0 links, 1 Mitte, 2 rechts (Anker = Einfügepunkt). */ - halign?: 0 | 1 | 2; - /** Textstil-Index aus {@link FlatDrawing.addTextStyle}; −1 = Standard. */ - style?: number; -} - -/** - * Sammelt Ebenen und Entitäten als flachen Zahlenpuffer + Zeichenkettenliste. Ebenen sind - * idempotent über den Namen; eine unbekannte Ebene wird mit Standardwerten (ACI 7, 0.25 mm) - * angelegt — wie beim früheren Writer. Namen bereinigt Rust (`sanitize_layer_name`). - * - * `new FlatDrawing(parent)` ist ein Blockinhalt: er teilt Ebenen, Linientypen, Stile und Zeichenketten - * (dedupliziert, gleiche Eingabe ⇒ gleiche Indizes) mit der Hauptzeichnung, hat aber einen eigenen - * Entitätspuffer, der mit {@link defineBlock} an die Stelle der Blockdefinition kommt. - */ -export class FlatDrawing { - private sh: FlatShared; - private nums: number[]; - /** Aktueller Linientyp (PEN) dieses Puffers; −1 = nach Ebene. */ - private pen = -1; - /** Entitäten dieses Puffers je Typ (Tests). */ - private counts: Record = {}; - - constructor(parent?: FlatDrawing) { - if (parent) { - this.sh = parent.sh; - this.nums = []; - } else { - this.nums = [FLAT_VERSION]; - this.sh = { - root: this.nums, - strings: [], - strIdx: new Map(), - layers: new Map(), - ltypes: new Map(), - styles: new Map(), - dimStyles: new Map(), - blocks: new Set(), - blockCounts: {}, - }; - } - } - - private str(s: string): number { - const clean = s.replace(/\0/g, ""); - const known = this.sh.strIdx.get(clean); - if (known !== undefined) return known; - this.sh.strings.push(clean); - this.sh.strIdx.set(clean, this.sh.strings.length - 1); - return this.sh.strings.length - 1; - } - - private bump(kind: string): void { - this.counts[kind] = (this.counts[kind] ?? 0) + 1; - } +/** Entitäten-Arten der Statistik (Reihenfolge wie `plan_dxf::KINDS`). */ +const KINDS = ["LINE", "LWPOLYLINE", "ARC", "CIRCLE", "TEXT", "HATCH", "DIMENSION", "INSERT"] as const; +/** Kennung der Kern-Antwort ("DXF1"). */ +const DXF_MAGIC = 0x44584631; +/** Kopf der Kern-Antwort: Kennung, nZahlen, nTexte, 8 Modell-, 8 Block-Zähler. */ +const HEAD = 19; +/** Flache Zeichnung (Zahlen + Zeichenketten) für die fileio-Bindungen, wie der Kern sie liefert. */ +export interface FlatDrawing { + /** Argumente für die Rust-Bindungen von fileio. */ + args(): [Float64Array, string]; /** Anzahl Entitäten im Modellbereich je Typ (INSERT/DIMENSION zählen je als eine) und in Blöcken (Summe je Typ). */ - stats(): { model: Record; blocks: Record } { - return { model: { ...this.counts }, blocks: { ...this.sh.blockCounts } }; - } - - /** Legt eine Ebene an (`rgb` 0xRRGGBB oder null = ACI 7, `lineWeight` in 1/100 mm). */ - addLayer(name: string, rgb: number | null, lineWeight: number): number { - const known = this.sh.layers.get(name); - if (known !== undefined) return known; - const idx = this.sh.layers.size; - this.sh.layers.set(name, idx); - this.sh.root.push(REC_LAYER, this.str(name), rgb ?? -1, lineWeight); - return idx; - } - - private layer(name: string): number { - return this.sh.layers.get(name) ?? this.addLayer(name, null, 25); - } - - /** - * Linientyp (Elemente in Metern: Strich +, Lücke −, Punkt 0; mindestens zwei Elemente), idempotent - * über den Namen. Gibt den Index für {@link setPen}/{@link setLayerLinetype} zurück. - */ - addLinetype(name: string, elements: number[]): number { - const known = this.sh.ltypes.get(name); - if (known !== undefined) return known; - const idx = this.sh.ltypes.size; - this.sh.ltypes.set(name, idx); - this.sh.root.push(REC_LTYPE, this.str(name), elements.length, ...elements); - return idx; - } - - /** Standard-Linientyp einer bereits angelegten Ebene. */ - setLayerLinetype(layerName: string, ltype: number): void { - this.sh.root.push(REC_LAYER_LTYPE, this.layer(layerName), ltype); - } - - /** Linientyp für die folgenden Linien/Bögen/Kreise/Polylinien (−1 = nach Ebene). Schreibt nur bei Änderung. */ - setPen(ltype: number): void { - if (ltype === this.pen) return; - this.pen = ltype; - this.nums.push(REC_PEN, ltype); - } - - /** Textstil mit TrueType-Schriftname (CAD löst ihn über das Betriebssystem auf), idempotent über den Namen. */ - addTextStyle(name: string, font: string, bold = false, italic = false): number { - const known = this.sh.styles.get(name); - if (known !== undefined) return known; - const idx = this.sh.styles.size; - this.sh.styles.set(name, idx); - this.sh.root.push(REC_STYLE, this.str(name), this.str(font), bold ? 1 : 0, italic ? 1 : 0, 1); - return idx; - } - - addLine(layer: string, a: Vec2, b: Vec2): void { - this.bump("LINE"); - this.nums.push(REC_LINE, this.layer(layer), a.x, a.y, b.x, b.y); - } - - addPolyline(layer: string, pts: Vec2[], closed: boolean): void { - if (pts.length < 2) return; - this.bump("LWPOLYLINE"); - this.nums.push(REC_POLYLINE, this.layer(layer), closed ? 1 : 0, pts.length); - for (const p of pts) this.nums.push(p.x, p.y); - } - - /** Bogen gegen den Uhrzeigersinn von `start` nach `end` (Radiant). */ - addArc(layer: string, center: Vec2, r: number, start: number, end: number): void { - this.bump("ARC"); - this.nums.push(REC_ARC, this.layer(layer), center.x, center.y, r, start, end); - } - - addCircle(layer: string, center: Vec2, r: number): void { - this.bump("CIRCLE"); - this.nums.push(REC_CIRCLE, this.layer(layer), center.x, center.y, r); - } - - /** Einzeiliger Text (Höhe in Metern, Drehung in Radiant). */ - addText(layer: string, at: Vec2, height: number, rotation: number, value: string): void { - this.bump("TEXT"); - this.nums.push(REC_TEXT, this.layer(layer), this.str(value), at.x, at.y, height, rotation); - } - - /** Einzeiliger Text mit Ausrichtung (Anker = Einfügepunkt, Grundlinie) und Textstil. */ - addText2(layer: string, at: Vec2, height: number, rotation: number, value: string, o: TextAlignOpts = {}): void { - this.bump("TEXT"); - this.nums.push(REC_TEXT2, this.layer(layer), this.str(value), at.x, at.y, height, rotation, o.halign ?? 0, o.style ?? -1); - } - - /** - * Schraffur als echte HATCH-Entität (äusserer Rand `pts`, geschlossen). `solid` = Vollfüllung; - * sonst Linienmuster aus `families` (Winkel in Radiant, Linienabstand in Metern; je Schar eine - * Musterzeile) mit optionalem Strichmuster `dashes` (Meter: an, aus, …; leer = durchgezogen). - * `rgb` null = Farbe der Ebene. - */ - addHatch( - layer: string, - pts: Vec2[], - opts: { solid: boolean; rgb: number | null; families?: { angle: number; spacing: number }[]; dashes?: number[] }, - ): void { - if (pts.length < 3) return; - this.bump("HATCH"); - const families = opts.solid ? [] : (opts.families ?? []); - const dashes = opts.solid ? [] : (opts.dashes ?? []); - this.nums.push(REC_HATCH, this.layer(layer), opts.solid ? 0 : 1, opts.rgb ?? -1, dashes.length, ...dashes, families.length); - for (const f of families) this.nums.push(f.angle, f.spacing); - this.nums.push(pts.length); - for (const p of pts) this.nums.push(p.x, p.y); - } - - /** - * Zweifarben-Verlauf als echte Gradient-HATCH-Entität (Rand `pts`, geschlossen). `rgb1`/`rgb2` = - * 0xRRGGBB; `angle` (Radiant) = Richtung von `rgb1` nach `rgb2` (nur linear); `radial`: `rgb1` in der - * Mitte, `rgb2` am Rand. - */ - addGradient(layer: string, pts: Vec2[], g: { rgb1: number; rgb2: number; angle: number; radial: boolean }): void { - if (pts.length < 3) return; - this.bump("HATCH"); - this.nums.push(REC_GRADIENT, this.layer(layer), g.rgb1, g.rgb2, g.angle, g.radial ? 1 : 0, pts.length); - for (const p of pts) this.nums.push(p.x, p.y); - } - - /** - * Bemassungsstil (Papier-Meter, s. `export_dim.rs`), idempotent über `name`. `textStyle` = Index aus - * {@link addTextStyle} oder −1; `post` = Format mit `<>` als Platzhalter der Zahl (oder leer). - */ - addDimStyle( - name: string, - d: { textStyle: number; scale: number; txt: number; tick: number; exo: number; exe: number; gap: number; dec: number; lfac: number; post?: string }, - ): number { - const known = this.sh.dimStyles.get(name); - if (known !== undefined) return known; - const idx = this.sh.dimStyles.size; - this.sh.dimStyles.set(name, idx); - this.sh.root.push( - REC_DIMSTYLE, this.str(name), d.textStyle, d.scale, d.txt, d.tick, d.exo, d.exe, d.gap, d.dec, d.lfac, - d.post ? this.str(d.post) : -1, - ); - return idx; - } - - /** - * Ausgerichtete Bemassung (DIMENSION + Anonymblock `*D…`) zwischen `p1` und `p2`; `onLine` = ein Punkt - * auf der Masslinie (legt Seite und Abstand fest), `textAt` = freie Lage der Masszahl (Mitte). - */ - addDimension(layer: string, dimStyle: number, p1: Vec2, p2: Vec2, onLine: Vec2, textAt?: Vec2): void { - this.bump("DIMENSION"); - this.nums.push(REC_DIM, this.layer(layer), dimStyle, p1.x, p1.y, p2.x, p2.y, onLine.x, onLine.y, textAt ? 1 : 0, textAt?.x ?? 0, textAt?.y ?? 0); - } - - /** Ob ein Block dieses Namens schon definiert ist. */ - hasBlock(name: string): boolean { - return this.sh.blocks.has(name); - } - - /** - * Blockdefinition: der Inhalt `content` (ein `new FlatDrawing(this)`) kommt mit blocklokalen Koordinaten - * an diese Stelle. `atts` = Attributdefinitionen (unsichtbar; Wert je INSERT). - */ - defineBlock(name: string, description: string, atts: { tag: string; prompt: string; def: string }[], content: FlatDrawing): void { - if (this.sh.blocks.has(name)) return; - this.sh.blocks.add(name); - this.nums.push(REC_BLOCK, this.str(name), description ? this.str(description) : -1, atts.length); - for (const a of atts) this.nums.push(this.str(a.tag), this.str(a.prompt), this.str(a.def), 0, 0, 0.1); - // Der Block beginnt mit „nach Ebene“; danach gilt der Linientyp, mit dem sein Inhalt endete. - this.nums.push(REC_PEN, -1); - for (const v of content.nums) this.nums.push(v); - this.nums.push(REC_BLOCK_END); - this.pen = content.pen; - for (const [k, n] of Object.entries(content.counts)) this.sh.blockCounts[k] = (this.sh.blockCounts[k] ?? 0) + n; - } - - /** Inhalt eines Blocks als Schlüssel: gleiche Zahlen (auf 1 mm gerundet) ⇒ gleicher Block. */ - contentKey(): string { - return roundKey(this.nums); - } - - /** Blockeinfügung mit Attributwerten (`tag` → Wert). */ - addInsert(layer: string, name: string, at: Vec2, rotation: number, scale: number, values: { tag: string; value: string }[] = []): void { - this.bump("INSERT"); - this.nums.push(REC_INSERT, this.layer(layer), this.str(name), at.x, at.y, rotation, scale, scale, values.length); - for (const v of values) this.nums.push(this.str(v.tag), this.str(v.value)); - } - - /** - * Papierbereich: Layout `name` (Papier in mm) mit einem Ansichtsfenster auf den Modellbereich. - * `vp` = Mittelpunkt und Grösse des Fensters auf dem Papier (mm), `view` = Mittelpunkt des Ausschnitts im Modell. - */ - addLayout(name: string, paperW: number, paperH: number, vp: { cx: number; cy: number; w: number; h: number }, view: Vec2, scaleDenominator: number): void { - this.nums.push(REC_LAYOUT, this.str(name), paperW, paperH, vp.cx, vp.cy, vp.w, vp.h, view.x, view.y, scaleDenominator); - } - - /** Argumente für die Rust-Bindungen. */ - args(): [Float64Array, string] { - return [Float64Array.from(this.nums), this.sh.strings.join("\0")]; - } -} - -// ── Plan → flache Zeichnung ───────────────────────────────────────────────── - -/** Gemeinsamer Zustand beim Sammeln eines Plans. */ -interface Ctx { - project: Project; - scale: number; - includeHatches: boolean; - dimUnit: "m" | "cm"; - /** Ebenenname je Kategorie-Code. */ - layerNameByCode: Map; - /** Kategorie-Code je Zeichen-Element / Raum (für Ebenen). */ - codeByDrawing: Map; - codeByRoom: Map; - /** Linientyp-Index zu einem Strichmuster (−1 = durchgezogen). */ - ltypeOf: (dxf: FlatDrawing, dash: number[] | null | undefined) => number; - /** Textstil-Index zu einer Formatierung. */ - styleOf: (dxf: FlatDrawing, marks?: Marks) => number; + stats(): { model: Record; blocks: Record }; } /** Eine Zeile einer (Rich-)Text-Ausgabe. */ @@ -403,8 +93,89 @@ interface OutLine { down: number; } +/** Massstab des Exports (endlich und > 0, sonst 1:100). */ +function scaleOf(opts: ExportDxfOptions): number { + return opts.scaleDenominator && Number.isFinite(opts.scaleDenominator) && opts.scaleDenominator > 0 ? opts.scaleDenominator : DEFAULT_SCALE_DENOMINATOR; +} + /** - * Baut aus einem Plan + Projekt die flache Zeichnung (Meter-Modell-Space). + * Text-Eingabe für den Kern (`plan_dxf::texts_from`): je Raumstempel die gesetzten Zeilen, je + * Einzeltext Anker/Winkel/Höhe/Spalte, Schrift und Absätze mit ihren Wörtern (`split(/\s+/)`). + * Nur die Text-Einträge des Plans werden gelesen. + */ +function textInput(plan: Plan, scale: number, defaultFont: string): { nums: Float64Array; strs: string } { + const nums: number[] = []; + const strs: string[] = []; + const idx = new Map(); + const S = (s: string): number => { + let i = idx.get(s); + if (i === undefined) { + i = strs.length; + strs.push(s); + idx.set(s, i); + } + return i; + }; + const family = (marks: Marks | undefined): number => S(fontNameOf(marks?.font) ?? defaultFont); + for (const { i, p } of planTextEntries(plan)) { + if (p.kind === "text") { + const lines = stampLines(p, scale); + nums.push(i, 6, p.at.x, p.at.y, lines.length); + for (const l of lines) nums.push(S(l.text), l.height, l.align, family(l.marks), l.marks?.bold ? 1 : 0, l.marks?.italic ? 1 : 0, l.down); + } else if (p.kind === "drawingText") { + const paragraphs = p.doc ? plainText(p.doc).split("\n") : p.text.split(/\r?\n/); + const marks = p.marks ?? p.doc?.paragraphs[0]?.runs[0]?.marks; + const wrap = typeof p.wrapWidth === "number" ? p.wrapWidth : NaN; + nums.push(i, 7, p.at.x, p.at.y, p.angle, p.heightM, wrap, family(marks), marks?.bold ? 1 : 0, marks?.italic ? 1 : 0, paragraphs.length); + for (const para of paragraphs) { + const words = para.split(/\s+/); + nums.push(S(para), words.length); + for (const w of words) nums.push(S(w)); + } + } + } + return { nums: Float64Array.from(nums), strs: strs.map((s) => "\0" + s).join("") }; +} + +/** Kern-Antwort (`plan_dxf::encode`) → flache Zeichnung; leer = Fehler. */ +function decodeFlat(bytes: Uint8Array): FlatDrawing { + const b = bytes.byteOffset % 8 === 0 ? bytes : bytes.slice(); + if (b.byteLength < HEAD * 8) throw new Error("DXF-Export fehlgeschlagen: Plan oder Projekt im Kern unlesbar"); + const h = new Float64Array(b.buffer, b.byteOffset, HEAD); + if (h[0] !== DXF_MAGIC) throw new Error("DXF-Export fehlgeschlagen: unerwartete Antwort des Kerns"); + const nNums = h[1]; + const nStr = h[2]; + const nF64 = HEAD + nNums + nStr; + const f = new Float64Array(b.buffer, b.byteOffset, nF64); + const nums = f.slice(HEAD, HEAD + nNums); + const units = new Uint16Array(b.buffer, b.byteOffset + nF64 * 8, (b.byteLength - nF64 * 8) >> 1); + const strings: string[] = new Array(nStr); + let o = 0; + for (let k = 0; k < nStr; k++) { + const n = f[HEAD + nNums + k]; + let s = ""; + for (let j = 0; j < n; j += 8192) s += String.fromCharCode.apply(null, units.subarray(o + j, o + Math.min(n, j + 8192)) as unknown as number[]); + strings[k] = s; + o += n; + } + const counts = (at: number): Record => { + const r: Record = {}; + KINDS.forEach((k, j) => { + if (h[at + j] > 0) r[k] = h[at + j]; + }); + return r; + }; + const model = counts(3); + const blocks = counts(11); + const joined = strings.join("\0"); + return { + args: () => [nums, joined], + stats: () => ({ model: { ...model }, blocks: { ...blocks } }), + }; +} + +/** + * Baut aus einem Plan + Projekt die flache Zeichnung (Meter-Modell-Space) im Kern. * Reihenfolge der Primitive bleibt erhalten. */ export function collectPlanDrawing( @@ -412,295 +183,16 @@ export function collectPlanDrawing( project: Project, opts: ExportDxfOptions = {}, ): FlatDrawing { - const includeHatches = opts.includeHatches ?? true; - const scale = opts.scaleDenominator && Number.isFinite(opts.scaleDenominator) && opts.scaleDenominator > 0 ? opts.scaleDenominator : DEFAULT_SCALE_DENOMINATOR; - const dxf = new FlatDrawing(); - - // 1) Layer aus den Kategorie-Ebenen anlegen (Code+Name als Layer-Name, Farbe, - // Linienstärke). So trägt die Datei echte, benannte Layer statt eines Flachs. - const cats = flattenCategories(project.layers); - const layerNameByCode = new Map(); - for (const c of cats) { - const name = layerName(c); - layerNameByCode.set(c.code, name); - dxf.addLayer(name, rgbFromHex(c.color), mmToLwe(c.lw)); - } - // Sammel-Layer für kategorielose Primitive. - dxf.addLayer(LAYER_SYMBOLS, 0x111111, 18); - dxf.addLayer(LAYER_HATCH, 0x888888, 13); - dxf.addLayer(LAYER_CONTEXT, 0x9aa3ad, 10); - dxf.addLayer(LAYER_DEFAULT, 0x111111, 18); - dxf.addLayer(LAYER_SECTIONS, 0x111111, 18); - // Warmes Orange, identisch zum 3D-/Grundriss-Footprint der Extrusionen (EXTRUSION_STROKE/EXTRUSION_RGB). - dxf.addLayer(LAYER_EXTRUSION, rgbFromHex("#d98c40"), 13); - dxf.addLayer(LAYER_ZERO, null, 25); // Blockinhalt; „0" gibt es in jeder Datei, der Eintrag legt nur den Index fest - - // 2) Rückverweise Primitiv → Kategorie: Wände/2D-Elemente tragen nur ihre ID im - // Plan; die Kategorie liegt am Projekt-Objekt. Damit landet jede Wand-/Drawing- - // Entity auf dem richtigen Layer. - const codeByWall = new Map(); - for (const w of project.walls) codeByWall.set(w.id, w.categoryCode); - const codeByDrawing = new Map(); - for (const d of project.drawings2d) codeByDrawing.set(d.id, d.categoryCode); - const codeByColumn = new Map(); - for (const c of project.columns ?? []) codeByColumn.set(c.id, c.categoryCode); - const codeByRoom = new Map(); - for (const r of project.rooms ?? []) codeByRoom.set(r.id, r.categoryCode); - const drawingLayer = (id: string | undefined, fallback: string): string => - id ? (layerNameByCode.get(codeByDrawing.get(id) ?? "") ?? LAYER_DEFAULT) : fallback; - - const layerFor = (p: Primitive): string => { - if (p.kind === "polygon") { - if (p.wallId) return layerNameByCode.get(codeByWall.get(p.wallId) ?? "") ?? LAYER_DEFAULT; - if (p.drawingId) return drawingLayer(p.drawingId, LAYER_DEFAULT); - if (p.columnId) return layerNameByCode.get(codeByColumn.get(p.columnId) ?? "") ?? LAYER_DEFAULT; - if (p.extrudedSolidId) return LAYER_EXTRUSION; - return LAYER_DEFAULT; - } - if (p.kind === "line") { - if (p.cls === "context-line") return LAYER_CONTEXT; - if (p.cls === "section-line") return LAYER_SECTIONS; - // Tür-Blatt/-Rahmen und Wand-Achsen: Symbol-Sammellayer. - return drawingLayer(p.drawingId, LAYER_SYMBOLS); - } - // Texte von 2D-Elementen: Ebene ihrer Kategorie. - if (p.kind === "drawingText") return drawingLayer(p.drawingId, LAYER_SYMBOLS); - if (p.kind === "text") return p.roomId ? (layerNameByCode.get(codeByRoom.get(p.roomId) ?? "") ?? LAYER_SYMBOLS) : LAYER_SYMBOLS; - // Bögen: Tür-Schwenkbogen → Symbole. - return LAYER_SYMBOLS; - }; - + const scale = scaleOf(opts); // Standard-Schrift: erste im Projekt hinterlegte Schrift der Textstile, sonst Arial. const defaultFont = (project.textStyles ?? []).map((s) => fontNameOf(s.marks.font)).find((f) => f) ?? "Arial"; - const ctx: Ctx = { - project, - scale, - includeHatches, - dimUnit: opts.dimUnit ?? "m", - layerNameByCode, - codeByDrawing, - codeByRoom, - ltypeOf: (d, dash) => { - if (!dash || dash.length === 0) return -1; - const el = dashToLtypeMeters(dash, scale); - return el ? d.addLinetype(ltypeNameFor(dash, project.lineStyles), el) : -1; - }, - styleOf: (d, marks) => { - const family = fontNameOf(marks?.font) ?? defaultFont; - const bold = !!marks?.bold; - const italic = !!marks?.italic; - const plain = family === defaultFont && !bold && !italic; - const name = plain ? "DOSSIER" : `DOSSIER_${family}${bold ? "_B" : ""}${italic ? "_I" : ""}`; - return d.addTextStyle(name, family, bold, italic); - }, - }; - - // 3) Gruppen: Bemassungen, Blockinstanzen und Öffnungen werden zu CAD-Objekten statt zu losen Primitiven. - const dimById = new Map(); - const blockById = new Map(); - for (const d of project.drawings2d) { - if (d.geom?.shape === "dimension") dimById.set(d.id, d); - else if (d.geom?.shape === "block") blockById.set(d.id, d); - } - const openingById = new Map(); - for (const o of project.openings ?? []) openingById.set(o.id, o); - const groupKeyOf = (p: Primitive): string | null => { - const did = "drawingId" in p ? p.drawingId : undefined; - if (did && dimById.has(did)) return `d:${did}`; - if (did && blockById.has(did)) return `b:${did}`; - const oid = "openingId" in p ? p.openingId : undefined; - if (oid && openingById.has(oid)) return `o:${oid}`; - return null; - }; - const groups = new Map(); - for (const p of plan.primitives) { - const k = groupKeyOf(p); - if (!k) continue; - const g = groups.get(k); - if (g) g.push(p); - else groups.set(k, [p]); - } - const blockNames = new BlockNames(); - const doneGroups = new Set(); - - // 4) Jedes Primitiv in Entities übersetzen. - for (const p of plan.primitives) { - const key = groupKeyOf(p); - if (key) { - if (doneGroups.has(key)) continue; - doneGroups.add(key); - const prims = groups.get(key) ?? []; - if (key.startsWith("d:")) emitDimensions(dxf, ctx, dimById.get(key.slice(2))!, drawingLayer(key.slice(2), LAYER_DEFAULT)); - else if (key.startsWith("b:")) { - const d = blockById.get(key.slice(2))!; - if (!emitBlockInstance(dxf, ctx, d, prims, drawingLayer(d.id, LAYER_DEFAULT), blockNames)) for (const q of prims) emitPrimitive(dxf, ctx, q, layerFor(q), LAYER_HATCH); - } else { - const o = openingById.get(key.slice(2))!; - if (!emitOpening(dxf, ctx, o, prims, layerNameByCode.get(o.categoryCode) ?? LAYER_SYMBOLS, blockNames)) for (const q of prims) emitPrimitive(dxf, ctx, q, layerFor(q), LAYER_HATCH); - } - continue; - } - emitPrimitive(dxf, ctx, p, layerFor(p), LAYER_HATCH); - } - dxf.setPen(-1); - - // 5) Papierbereich (optional): ein Layout mit Ansichtsfenster im Planmassstab auf die Plan-Ausdehnung. - if (opts.paperLayout) addPaperLayout(dxf, plan, scale); - return dxf; -} - -/** Eindeutige Blocknamen: gleiche Schlüssel teilen sich einen Namen, verschiedene Inhalte mit gleichem Wunschnamen werden nummeriert. */ -class BlockNames { - private byKey = new Map(); - private used = new Set(); - /** Name zum Schlüssel; `fresh` = der Block muss noch definiert werden. */ - name(key: string, wish: string): { name: string; fresh: boolean } { - const known = this.byKey.get(key); - if (known) return { name: known, fresh: false }; - let name = wish; - for (let i = 2; this.used.has(name.toLowerCase()); i++) name = `${wish}_${i}`; - this.used.add(name.toLowerCase()); - this.byKey.set(key, name); - return { name, fresh: true }; - } -} - -/** Papierbereich auf die Ausdehnung des Plans (Meter) im Massstab `scale`. */ -function addPaperLayout(dxf: FlatDrawing, plan: Plan, scale: number): void { + const { nums, strs } = textInput(plan, scale, defaultFont); const b = plan.bounds; - const w = b.maxX - b.minX; - const h = b.maxY - b.minY; - if (![b.minX, b.minY, b.maxX, b.maxY].every(Number.isFinite) || w <= 0 || h <= 0) return; - const margin = 10; - const paper = paperFor(w, h, scale, margin); - dxf.addLayout( - `Plan 1-${scale}`, - paper.paperW, - paper.paperH, - { cx: paper.paperW / 2, cy: paper.paperH / 2, w: paper.vpW, h: paper.vpH }, - { x: (b.minX + b.maxX) / 2, y: (b.minY + b.maxY) / 2 }, - scale, - ); -} - -/** Format einer Länge für Attribute: Meter, 2 Nachkommastellen. */ -function m2(v: number): string { - return Number.isFinite(v) ? v.toFixed(2) : ""; -} - -/** Bemassungskette → je Segment eine DIMENSION; Stil aus den Papier-mm-Feinheiten und dem Massstab. */ -function emitDimensions(dxf: FlatDrawing, ctx: Ctx, d: Drawing2D, layer: string): void { - const g = d.geom; - if (g.shape !== "dimension") return; - const th = g.textHeightMm ?? DIM_DEFAULTS_MM.textHeight; - const tick = g.tickLenMm ?? DIM_DEFAULTS_MM.tickLen; - const gap = g.gapMm ?? DIM_DEFAULTS_MM.gap; - const over = g.overshootMm ?? DIM_DEFAULTS_MM.overshoot; - if (![th, tick, gap, over].every((v) => Number.isFinite(v) && v >= 0) || th <= 0) return; - const cm = ctx.dimUnit === "cm"; - const isDefault = th === DIM_DEFAULTS_MM.textHeight && tick === DIM_DEFAULTS_MM.tickLen && gap === DIM_DEFAULTS_MM.gap && over === DIM_DEFAULTS_MM.overshoot; - const variant = isDefault ? "" : `_${th}-${tick}-${gap}-${over}`.replace(/\./g, ","); - const name = `DOSSIER_1-${ctx.scale}${cm ? "_cm" : ""}${variant}`; - const style = dxf.addDimStyle(name, { - textStyle: ctx.styleOf(dxf), - scale: ctx.scale, - txt: th / 1000, - tick: tick / 1000, - exo: gap / 1000, - exe: over / 1000, - gap: (th * 0.6) / 1000, // Unterkante der Zahl 0.6 × Texthöhe über der Masslinie, wie im Plan - dec: cm ? 0 : 2, - lfac: cm ? 100 : 1, - }); - const mm = (v: number) => mmToModel(v, ctx.scale); - const textH = mm(th); - for (let i = 0; i + 1 < g.pts.length; i++) { - const a = g.pts[i]; - const b = g.pts[i + 1]; - const len = Math.hypot(b.x - a.x, b.y - a.y); - if (len < 1e-6) continue; - const nx = -(b.y - a.y) / len; - const ny = (b.x - a.x) / len; - const onLine = { x: a.x + nx * g.offset, y: a.y + ny * g.offset }; - // Von Hand verschobene Masszahl: Mitte = Grundlinienpunkt des Plans + halbe Texthöhe quer zur Linie. - const o = g.textOffsetsMm?.[i]; - let textAt: Vec2 | undefined; - if (o && (o.along !== 0 || o.perp !== 0)) { - const base = dimTextPos(a, b, g.offset, textH, { along: mm(o.along), perp: mm(o.perp) }); - const up = dimTextFrame(a, b, g.offset, textH).up; - textAt = { x: base.x + up.x * (textH / 2), y: base.y + up.y * (textH / 2) }; - } - dxf.addDimension(layer, style, a, b, onLine, textAt); - } -} - -/** Blockinstanz (`Drawing2D {shape:"block"}`) → BLOCK je Definition (lokale Geometrie) + INSERT. */ -function emitBlockInstance(dxf: FlatDrawing, ctx: Ctx, d: Drawing2D, prims: Primitive[], layer: string, names: BlockNames): boolean { - const g = d.geom; - if (g.shape !== "block") return false; - const def = ctx.project.blockDefs?.find((b) => b.id === g.blockDefId); - const s = g.scale ?? 1; - if (!def || !(s > 0) || !Number.isFinite(s) || !Number.isFinite(g.rotation) || !Number.isFinite(g.at.x) || !Number.isFinite(g.at.y)) return false; - const { name, fresh } = names.name(`blockdef:${def.id}`, def.name.trim() || "Block"); - if (fresh) { - const frame: LocalFrame = { origin: g.at, rot: g.rotation, scale: s }; - const content = new FlatDrawing(dxf); - for (const p of prims) { - const lp = primitiveToLocal(p, frame); - if (lp) emitPrimitive(content, ctx, lp, LAYER_ZERO, LAYER_ZERO); - } - content.setPen(-1); - dxf.defineBlock(name, def.name, [], content); - } - dxf.addInsert(layer, name, g.at, g.rotation, s); - return true; -} - -/** Tür/Fenster → BLOCK (Geometrie in der Wandrichtung, am ersten Pfosten verankert) + INSERT mit Attributen. */ -function emitOpening(dxf: FlatDrawing, ctx: Ctx, o: Opening, prims: Primitive[], layer: string, names: BlockNames): boolean { - const wall = ctx.project.walls.find((w) => w.id === o.hostWallId); - if (!wall) return false; - const len = Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y); - if (len < 1e-6 || !Number.isFinite(o.position)) return false; - const ux = (wall.end.x - wall.start.x) / len; - const uy = (wall.end.y - wall.start.y) / len; - const origin = { x: wall.start.x + ux * o.position, y: wall.start.y + uy * o.position }; - const rot = Math.atan2(uy, ux); - const frame: LocalFrame = { origin, rot, scale: 1 }; - const content = new FlatDrawing(dxf); - for (const p of prims) { - const lp = primitiveToLocal(p, frame); - if (lp) emitPrimitive(content, ctx, lp, LAYER_ZERO, LAYER_ZERO); - } - content.setPen(-1); - const isDoor = o.kind === "door"; - const kindName = !isDoor ? "Fenster" : o.doorType === "wandoeffnung" ? "Wandoeffnung" : "Tuer"; - const cm = (v: number) => String(Math.round(v * 100)); - const wish = `${kindName}_${cm(o.width)}x${cm(o.height)}`; - const { name, fresh } = names.name(`${kindName}:${content.contentKey()}`, wish); - const atts = [ - { tag: "ID", prompt: "Kennung", def: "" }, - { tag: "TYP", prompt: "Art", def: kindName }, - { tag: "TYPENAME", prompt: "Typ", def: "" }, - { tag: "BREITE_M", prompt: "Breite [m]", def: "" }, - { tag: "HOEHE_M", prompt: "Hoehe [m]", def: "" }, - ...(isDoor ? [] : [{ tag: "BRUESTUNG_M", prompt: "Bruestung [m]", def: "" }]), - ]; - if (fresh) { - const label = !isDoor ? "Fenster" : o.doorType === "wandoeffnung" ? "Wandöffnung" : "Tür"; - dxf.defineBlock(name, `${label} ${m2(o.width)} × ${m2(o.height)} m`, atts, content); - } - const typeName = (isDoor ? ctx.project.doorTypes : ctx.project.windowTypes)?.find((t) => t.id === o.typeId)?.name ?? ""; - const label = !isDoor ? "Fenster" : o.doorType === "wandoeffnung" ? "Wandöffnung" : "Tür"; - dxf.addInsert(layer, name, origin, rot, 1, [ - { tag: "ID", value: o.id }, - { tag: "TYP", value: label }, - { tag: "TYPENAME", value: typeName }, - { tag: "BREITE_M", value: m2(o.width) }, - { tag: "HOEHE_M", value: m2(o.height) }, - ...(isDoor ? [] : [{ tag: "BRUESTUNG_M", value: m2(o.sillHeight) }]), - ]); - return true; + const o = Float64Array.of(scale, (opts.includeHatches ?? true) ? 1 : 0, opts.dimUnit === "cm" ? 1 : 0, opts.paperLayout ? 1 : 0, b.minX, b.minY, b.maxX, b.maxY); + const doc = documentFor(project).id; + // Eigener Puffer mit Schraffur-JSON (Verlauf-Schraffuren brauchen ihre Farben). + const bytes = withPlanParts(planParts(plan, true), (segs) => core().plan_dxf_flat(doc, segs, nums, strs, o, defaultFont)); + return decodeFlat(bytes); } /** @@ -750,11 +242,6 @@ function writeCad(format: CadExportFormat, drawing: FlatDrawing): Uint8Array { return bytes; } -/** Layer-Name aus einer Kategorie: "Code_Name" (bereinigt Rust selbst). */ -function layerName(c: LayerCategory): string { - return `${c.code}_${c.name}`; -} - /** Stempel-/Textzeilen eines Primitivs `text` (Raumstempel): Rich-Text-Doc + Live-Zeilen, vertikal um den Anker zentriert wie in der Plan-Ansicht. */ function stampLines(p: Extract, scale: number): OutLine[] { const unitPerPt = (0.0254 / 72) * scale; // 1 pt Papier in Modell-Metern @@ -785,267 +272,6 @@ function stampLines(p: Extract, scale: number): Out return out; } -/** Zeilen eines `drawingText`: Absätze bzw. Zeilenumbrüche, bei Spaltenbreite wortweise umbrochen; Zeilenabstand wie die Plan-Ansicht (1.25 × Höhe). */ -function drawingTextLines(p: Extract): OutLine[] { - const paragraphs = p.doc ? plainText(p.doc).split("\n") : p.text.split(/\r?\n/); - const lines: string[] = []; - if (p.wrapWidth && p.wrapWidth > 0) { - const maxChars = Math.max(1, Math.floor(p.wrapWidth / (p.heightM * 0.55))); - for (const para of paragraphs) { - let line = ""; - for (const word of para.split(/\s+/)) { - if (line === "") line = word; - else if (line.length + 1 + word.length <= maxChars) line += ` ${word}`; - else { - lines.push(line); - line = word; - } - } - lines.push(line); - } - } else { - lines.push(...paragraphs); - } - const marks = p.marks ?? p.doc?.paragraphs[0]?.runs[0]?.marks; - return lines.map((text, k) => ({ text, height: p.heightM, align: 0 as const, marks, down: k * p.heightM * 1.25 })); -} - -/** Schreibt ein Plan-Primitiv als passende Entity(en). `hatchLayer` = Ebene der Schraffuren (in Blöcken „0"). */ -function emitPrimitive( - dxf: FlatDrawing, - ctx: Ctx, - p: Primitive, - layer: string, - hatchLayer: string, -): void { - const includeHatches = ctx.includeHatches; - switch (p.kind) { - case "line": - if (p.zigzag) { - // Zickzack-Linie → offene Polylinie (amplitude/wavelength Papier-mm → - // Modell-Meter über dieselbe Kopplung wie das Strichmuster unten). - const amp = p.zigzag.amplitude * DASH_MM_TO_M; - const wav = p.zigzag.wavelength * DASH_MM_TO_M; - dxf.setPen(-1); - dxf.addPolyline(layer, zigzagPoints(p.a, p.b, amp, wav), false); - } else if (p.motif) { - // Custom-Motiv → offene Polylinie (Papier-mm → Modell-Meter, wie unten). - dxf.setPen(-1); - dxf.addPolyline(layer, motifPoints(p.a, p.b, p.motif, DASH_MM_TO_M), false); - } else { - dxf.setPen(ctx.ltypeOf(dxf, p.dash)); - dxf.addLine(layer, p.a, p.b); - } - break; - - case "arc": - dxf.setPen(ctx.ltypeOf(dxf, p.dash)); - emitArc(dxf, p, layer); - break; - - // Gezeichnete Kreise/Bögen (2D-Elemente). `drawingArc` läuft per Konvention - // immer CCW von a0 nach a1 (s. planView/primitives), genau wie DXF-Bögen. - case "drawingCircle": - dxf.setPen(ctx.ltypeOf(dxf, p.dash)); - dxf.addCircle(layer, p.center, p.r); - break; - - case "drawingArc": - dxf.setPen(ctx.ltypeOf(dxf, p.dash)); - dxf.addArc(layer, p.center, p.r, p.a0, p.a1); - break; - - // 2D-Text: TEXT mit Textstil (Schriftname aus den Formatierungen, sonst Projekt-Schrift/Arial), linksbündig an - // der Grundlinie wie in der Plan-Ansicht; mehrere Absätze/Spaltenbreite als mehrere Zeilen darunter. - case "drawingText": { - const lines = drawingTextLines(p); - const dir = { x: Math.sin(p.angle), y: -Math.cos(p.angle) }; // „nach unten“ im gedrehten Text - for (const l of lines) { - if (!l.text.trim() || !(l.height > 0)) continue; - const at = { x: p.at.x + dir.x * l.down, y: p.at.y + dir.y * l.down }; - dxf.addText2(layer, at, l.height, p.angle, l.text, { style: ctx.styleOf(dxf, l.marks) }); - } - break; - } - - // Raumstempel (Name, Nutzung, Fläche): je Zeile ein TEXT, links/Mitte/rechts wie im Plan, um den Anker zentriert. - case "text": { - for (const l of stampLines(p, ctx.scale)) { - dxf.addText2(layer, { x: p.at.x, y: p.at.y - l.down }, l.height, 0, l.text, { halign: l.align, style: ctx.styleOf(dxf, l.marks) }); - } - break; - } - - case "polygon": { - const pts = p.pts; - if (pts.length < 2) break; - // Unsichtbare Pick-Bänder (Dach-Traufe, Kontext-Hülle, Schnittlinie): weder Füllung noch Umriss noch Schraffur. - if (p.stroke === "none" && p.fill === "none" && p.hatch.pattern === "none" && p.hatch.kind !== "gradient") break; - // Schraffur ([C2], 28.10.) als echte HATCH-Entität UNTER dem Umriss (Zeichenreihenfolge der - // Datei): Vollfüllung bzw. Linienmuster (diagonal/Kreuz/Dämmung/frei, auch gestrichelt) mit dem - // Polygon als Rand und der aufgelösten Vordergrundfarbe. Verlauf-Schraffur (kind==="gradient") - // als echte Gradient-HATCH (zwei Farben, linear/radial); ohne lesbare Farben oder Bild- - // Schraffur (kind==="image") trägt DXF das nicht → FALLBACK ohne Muster (nur der Umriss). Random-Vektor - // (deterministische Streu-Striche, Modell-Meter, identischer Seed wie Bildschirm/PDF) hat kein - // Musteräquivalent → bleibt als einzelne Linien auf dem HATCH-Layer. - if (includeHatches && p.hatch.kind === "gradient" && pts.length >= 3) { - const g = p.hatch.gradient; - const rgb1 = g ? rgbOrNull(g.color1) : null; - const rgb2 = g ? rgbOrNull(g.color2) : null; - if (g && rgb1 !== null && rgb2 !== null && Number.isFinite(g.angle)) { - // Richtung wie der SVG-Verlauf der Ansicht: Vektor (cos, sin) in Plan-Koordinaten = DXF-Winkel. - dxf.addGradient(hatchLayer, pts, { rgb1, rgb2, angle: (g.angle * Math.PI) / 180, radial: g.type === "radial" }); - } - } else if (includeHatches && p.hatch.kind !== "image" && pts.length >= 3) { - const h = p.hatch; - if (h.pattern === "solid") { - dxf.addHatch(hatchLayer, pts, { solid: true, rgb: rgbOrNull(h.color) }); - } else if (h.pattern !== "none" && h.lines === "random") { - const cycle = dashCycleMeters(h.dash); - const segs: Seg[] = buildRandomHatchRuns(pts, h) - .filter((r) => r.length >= 2) - .map((r) => ({ a: r[0], b: r[r.length - 1] })); - dxf.setPen(-1); - for (const seg of segs) { - if (cycle) { - for (const d of dashSeg(seg, cycle)) dxf.addLine(hatchLayer, d.a, d.b); - } else { - dxf.addLine(hatchLayer, seg.a, seg.b); - } - } - } else if (h.pattern !== "none") { - const families = hatchFamilies(h); - if (families.length > 0) { - dxf.addHatch(hatchLayer, pts, { solid: false, rgb: rgbOrNull(h.color), families, dashes: dashCycleMeters(h.dash) ?? [] }); - } - } - } - // Kreis-Approximationen (viele Segmente) bleiben als geschlossene Polylinie — - // masshaltig und robust. Geschlossene Ringe bekommen das Ring-Flag. - dxf.setPen(-1); - dxf.addPolyline(layer, pts, true); - break; - } - } -} - -/** - * Bogen-Primitiv → ARC. DXF-Bögen laufen gegen den Uhrzeigersinn von - * Start- nach Endwinkel. Der Plan-Bogen ist über from/to definiert; die - * Drehrichtung folgt dem Kreuzprodukt (positiv = CCW). Bei CW werden Start/Ende - * getauscht, damit der kurze Bogen in der richtigen Richtung entsteht. - */ -function emitArc( - dxf: FlatDrawing, - p: Extract, - layer: string, -): void { - const a1 = angleRad(p.center, p.from); - const a2 = angleRad(p.center, p.to); - const v1 = { x: p.from.x - p.center.x, y: p.from.y - p.center.y }; - const v2 = { x: p.to.x - p.center.x, y: p.to.y - p.center.y }; - const cross = v1.x * v2.y - v1.y * v2.x; - if (cross >= 0) { - dxf.addArc(layer, p.center, p.r, a1, a2); - } else { - dxf.addArc(layer, p.center, p.r, a2, a1); - } -} - -/** Winkel (Radiant, 0..2π) von `c` nach `p`, gegen den Uhrzeigersinn. */ -function angleRad(c: Vec2, p: Vec2): number { - const a = Math.atan2(p.y - c.y, p.x - c.x); - return a < 0 ? a + 2 * Math.PI : a; -} - -// ── Schraffur-Muster in Metern ─────────────────────────────────────────────── -// Die Kachelgrösse der Bildschirm-PlanView (8 bzw. 10 Einheiten × scale, 1 Einheit = 1/90 m) wird -// direkt in einen Meter-Linienabstand übersetzt (`hatchFamilies`); die Zufallsstriche und das -// Strichmuster laufen weiter über geklippte Segmente (`dashSeg`). - -interface Seg { - a: Vec2; - b: Vec2; -} - -// Strichmuster (`dash`, mm-Papier) → Zyklus in WELT-Metern. Gleiche Umrechnung -// wie der Bildschirm/GL-Pfad: 1 mm ≙ (1/0.13) Kachel-Einheiten, 1 Einheit = 1/90 m. -// `null` = durchgezogen (keine Zerlegung). Ungerade Musterlängen werden verdoppelt. -const DASH_MM_TO_M = (1 / 0.13) * (1 / 90); -function dashCycleMeters(dash: number[] | null): number[] | null { - if (!dash || dash.length === 0) return null; - const pat = dash.map((d) => Math.max(0, d) * DASH_MM_TO_M).filter((d) => d > 0); - if (pat.length === 0) return null; - return pat.length % 2 === 0 ? pat : pat.concat(pat); -} - -// Zerlegt EINE Schraffurlinie in ihre durchgezogenen Teilstücke gemäß `cycle` -// ([an, aus, …], Meter). Die Phase startet je Linie neu — visuell identisch zum -// SVG-``, das das Muster je Kachellinie zurücksetzt. -function dashSeg(seg: Seg, cycle: number[]): Seg[] { - const out: Seg[] = []; - const len = Math.hypot(seg.b.x - seg.a.x, seg.b.y - seg.a.y); - if (len < 1e-9) return out; - const ux = (seg.b.x - seg.a.x) / len; - const uy = (seg.b.y - seg.a.y) / len; - let pos = 0; - let idx = 0; - let on = true; - while (pos < len - 1e-9) { - const step = Math.min(cycle[idx % cycle.length], len - pos); - if (on && step > 1e-9) { - out.push({ - a: { x: seg.a.x + ux * pos, y: seg.a.y + uy * pos }, - b: { x: seg.a.x + ux * (pos + step), y: seg.a.y + uy * (pos + step) }, - }); - } - pos += step; - idx++; - on = !on; - } - return out; -} - -/** - * Linienscharen einer Vektor-Schraffur als (Winkel in Radiant, Abstand in Metern): wie Bildschirm - * und PDF eine Schar (diagonal, frei), Kreuzschraffur zusätzlich um 90° gedreht, Dämmung zusätzlich - * bei −45°. Kachelgrösse wie `hatchSegments` früher: (8 bzw. 10) × scale / 90 m, mindestens 2 cm. - */ -function hatchFamilies(hatch: Extract["hatch"]): { angle: number; spacing: number }[] { - const unitM = 1 / 90; - const tileM = (hatch.pattern === "insulation" ? 10 : 8) * hatch.scale * unitM; - const spacing = Math.max(0.02, tileM); // Mindestabstand in Metern - if (!Number.isFinite(spacing)) return []; - const angle = (hatch.angle * Math.PI) / 180; - const out = [{ angle, spacing }]; - if (hatch.pattern === "crosshatch") out.push({ angle: angle + Math.PI / 2, spacing }); - if (hatch.pattern === "insulation") out.push({ angle: angle - Math.PI / 4, spacing }); - return out; -} - -// ── Farb-/Strich-Umrechnung ───────────────────────────────────────────────── -// (Die nächste ACI zur True-Color bestimmt acadrust mit der vollen 255er-Palette.) - -/** "#rrggbb" → 0xRRGGBB (24-Bit True-Color). Fallback dunkelgrau. */ -export function rgbFromHex(hex: string): number { - const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim()); - if (!m) return 0x111111; - return parseInt(m[1], 16); -} - -/** "#rrggbb" → 0xRRGGBB, bei unlesbarer Farbe (z. B. "none") null = Farbe der Ebene. */ -function rgbOrNull(hex: string): number | null { - const m = /^#?([0-9a-f]{6}|[0-9a-f]{3})$/i.exec(hex.trim()); - if (!m) return null; - const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1]; - return parseInt(h, 16); -} - -/** Millimeter → DXF-LWEIGHT (1/100 mm), gerundet auf gültige Stufen ≥ 0. */ -export function mmToLwe(mm: number): number { - return Math.max(0, Math.round(mm * 100)); -} - /** Baut die Datei und löst den Download aus (Browser). Lädt das Format-Modul bei Bedarf. */ export async function savePlanDxf( plan: Plan, diff --git a/src/plan/planParts.ts b/src/plan/planParts.ts index 509fff7a..48de85e9 100644 --- a/src/plan/planParts.ts +++ b/src/plan/planParts.ts @@ -59,7 +59,7 @@ const cache = new WeakMap Date: Thu, 29 Oct 2026 01:58:20 +0000 Subject: [PATCH 4/5] [K3d] Druck-SVG (Layout-Viewport) aus dem Plan-Puffer im Kern: plan_print_svg.rs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Der Kern rechnet die SVG-Knoten in Papier-mm (Polygone mit Grundfüllung/Schraffurlinien/Umriss, Zufallsstriche, Linien, Zickzack/Motiv, Bögen, Kreise, Bilder, Deckkraft/Dimmen) als flache Anweisungsliste; TS legt sie als DOM-Knoten an und behält Rahmen, Bild- und Einzeltexte (Text-Layout). Nicht auf sceneToPrintSvg umgestellt — die Ausgabe bleibt so unverändert. TS-Fassungen (appendPrimitive, Polygon/Linie/Bogen-Knoten, hatchLines/fillParallel) gelöscht. Gleichheit (temporärer Test gegen die alte TS-Fassung, DOM über Stub serialisiert): 475 Pläne gleich (Beispiel + Projekt mit 2D-Elementen, 3 Geschosse × 3 Detailgrade × mono × 2 Blätter, Überlagerung, 400 Zufallspläne mit allen Primitiv-/Schraffur-Arten, bigSample(6)). Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/plan_print_svg.rs | 500 +++++++++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/plan_print_svg.rs | 20 + src/export/planToPrintSvg.ts | 481 +++------------------- src/plan/planLazy.test.ts | 17 +- 6 files changed, 591 insertions(+), 429 deletions(-) create mode 100644 src-tauri/core/src/plan_print_svg.rs create mode 100644 src-tauri/core/src/web/plan_print_svg.rs diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 1f1263cd..86366c92 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -64,6 +64,7 @@ pub mod plan_pick; pub mod snap; pub mod plan_svg; pub mod plan_dxf; +pub mod plan_print_svg; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_print_svg.rs b/src-tauri/core/src/plan_print_svg.rs new file mode 100644 index 00000000..d7384bcf --- /dev/null +++ b/src-tauri/core/src/plan_print_svg.rs @@ -0,0 +1,500 @@ +//! Druck-SVG eines Plans für Layout-Viewports und den PDF-Altpfad ([K3d], früher der Primitiv-Teil +//! von `src/export/planToPrintSvg.ts`): liest den zusammengesetzten Plan ([`crate::plan_parts`]) und +//! liefert die SVG-Knoten in Papier-Millimetern als flache Anweisungsliste, die TS 1:1 als DOM-Knoten +//! anlegt (gleiche Elemente, Attribute und Reihenfolge wie die TS-Fassung — die Zahlen formatiert wie +//! `String(Math.round(v * 1000) / 1000)`). Schraffuren als geklippte Vektorlinien, Zickzack/Motiv als +//! Polylinie, Bögen als ``. +//! +//! In TS bleiben: der ``-Rahmen und das weisse Blatt, die Bild-Schraffur-`` (laufende +//! Ids im Dokument) und die Einzeltexte (Text-Layout `wrapDocToLines`). Dafür stehen Anweisungen in +//! der Liste. +//! +//! Format: Datensätze getrennt durch `\x1e`, Felder durch `\x1f`: +//! - `E`, Ebene (0 = ins ``, 1 = in die offene Gruppe), Tag, dann Name/Wert-Paare; +//! - `G`, Deckkraft (leer = keine) — öffnet eine ``; `g` schliesst sie (hängt sie ans ``); +//! - `I`, Punkte-Attribut, Bild-JSON — Bild-Schraffur: `` anlegen und ein Polygon damit füllen; +//! - `T`, Plan-Index, Deckkraft — Einzeltext an dieser Stelle. + +use crate::hatch::{self, Hatch, Motif, Pattern, V2}; +use crate::js_fmt::js_number; +use crate::jsnum; +use crate::plan_buf::{whole, Rec, View, F_COLOR, F_DASH_NULL, F_OPACITY, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_IMAGE, T_LINE, T_POLYGON}; +use crate::plan_parts::{greyed_of, Part}; +use std::f64::consts::PI; + +/// Optionen: Massstab-Nenner, Blatt (mm) und Ausmass des Plans (`Plan.bounds`). +pub struct PrintOptions { + pub scale_denominator: f64, + pub page_w: f64, + pub page_h: f64, + pub bounds: [f64; 4], +} + +/// Standard-Stift-Stufen (mm). +const PEN_STEPS: [f64; 7] = [0.13, 0.18, 0.25, 0.35, 0.5, 0.7, 1.0]; +const MIN_PEN_MM: f64 = 0.13; + +/// Mm-Strichstärke auf die nächste Stift-Stufe (`quantizePen`). +fn quantize_pen(mm: f64) -> f64 { + let w = jsnum::max(MIN_PEN_MM, mm); + for s in PEN_STEPS { + if w <= s + 1e-6 { + return s; + } + } + PEN_STEPS[PEN_STEPS.len() - 1] +} + +/// `String(Math.round(v * 1000) / 1000)`. +fn r3(v: f64) -> String { + js_number(jsnum::round(v * 1000.0) / 1000.0) +} + +/// Strichmuster als Attribut (`dash.map(round).join(" ")`). +fn dash_attr(d: &[f64]) -> String { + d.iter().map(|v| r3(*v)).collect::>().join(" ") +} + +/// Anweisungsliste. +struct Out { + s: String, + first: bool, +} + +impl Out { + fn rec(&mut self, fields: &[&str]) { + if !self.first { + self.s.push('\u{1e}'); + } + self.first = false; + self.s.push_str(&fields.join("\u{1f}")); + } + + fn el(&mut self, depth: u8, tag: &str, attrs: &[(&str, String)]) { + let d = depth.to_string(); + let mut f: Vec<&str> = vec!["E", &d, tag]; + for (k, v) in attrs { + f.push(k); + f.push(v); + } + self.rec(&f); + } +} + +/// Papier-Abbildung (Welt-Meter → mm, Y gespiegelt, zentriert). +#[derive(Clone, Copy)] +struct Map { + off_x: f64, + off_y: f64, + min_x: f64, + max_y: f64, + k: f64, +} + +impl Map { + fn at(&self, x: f64, y: f64) -> V2 { + V2 { x: self.off_x + (x - self.min_x) * self.k, y: self.off_y + (self.max_y - y) * self.k } + } +} + +fn pts_attr(p: &[V2]) -> String { + p.iter().map(|q| format!("{},{}", r3(q.x), r3(q.y))).collect::>().join(" ") +} + +fn poly_node(pts: &str, fill: &str, stroke: &str, stroke_mm: f64) -> Vec<(&'static str, String)> { + let mut a = vec![("points", pts.to_string()), ("fill", fill.to_string())]; + if stroke != "none" && stroke_mm > 0.0 { + a.push(("stroke", stroke.to_string())); + a.push(("stroke-width", js_number(stroke_mm))); + a.push(("stroke-linejoin", "round".to_string())); + } else { + a.push(("stroke", "none".to_string())); + } + a +} + +fn line_attrs(a: V2, b: V2, color: &str, stroke_mm: f64, dash: Option<&[f64]>) -> Vec<(&'static str, String)> { + let mut v = vec![ + ("x1", r3(a.x)), + ("y1", r3(a.y)), + ("x2", r3(b.x)), + ("y2", r3(b.y)), + ("stroke", color.to_string()), + ("stroke-width", js_number(stroke_mm)), + ("stroke-linecap", "round".to_string()), + ]; + if let Some(d) = dash.filter(|d| !d.is_empty()) { + v.push(("stroke-dasharray", dash_attr(d))); + } + v +} + +fn polyline_attrs(pts: &[V2], color: &str, stroke_mm: f64, dash: Option<&[f64]>) -> Vec<(&'static str, String)> { + let mut v = vec![ + ("points", pts_attr(pts)), + ("fill", "none".to_string()), + ("stroke", color.to_string()), + ("stroke-width", js_number(stroke_mm)), + ("stroke-linecap", "round".to_string()), + ("stroke-linejoin", "round".to_string()), + ]; + if let Some(d) = dash.filter(|d| !d.is_empty()) { + v.push(("stroke-dasharray", dash_attr(d))); + } + v +} + +/// Strichmuster + runde Kappe bei Punkten (Bögen, Kreise). +fn push_dash(v: &mut Vec<(&'static str, String)>, dash: Option<&[f64]>) { + if let Some(d) = dash.filter(|d| !d.is_empty()) { + v.push(("stroke-dasharray", dash_attr(d))); + if d.iter().any(|x| *x == 0.0) { + v.push(("stroke-linecap", "round".to_string())); + } + } +} + +/// Parallele Linien im Winkel/Abstand, aufs Polygon geklippt (`fillParallel`). +fn fill_parallel(poly: &[V2], angle: f64, spacing: f64, out: &mut Vec<(V2, V2)>) { + if poly.len() < 3 || spacing <= 0.0 { + return; + } + let dir = V2 { x: jsnum::cos(angle), y: jsnum::sin(angle) }; + let nrm = V2 { x: -dir.y, y: dir.x }; + let mut t_min = f64::INFINITY; + let mut t_max = f64::NEG_INFINITY; + for p in poly { + let t = p.x * nrm.x + p.y * nrm.y; + if t < t_min { + t_min = t; + } + if t > t_max { + t_max = t; + } + } + let mut t = (t_min / spacing).ceil() * spacing; + while t <= t_max { + let mut xs: Vec = Vec::new(); + let n = poly.len(); + let mut j = n - 1; + for i in 0..n { + let a = poly[j]; + let b = poly[i]; + j = i; + let ta = a.x * nrm.x + a.y * nrm.y; + let tb = b.x * nrm.x + b.y * nrm.y; + if ta == tb { + continue; + } + let f = (t - ta) / (tb - ta); + if f < 0.0 || f > 1.0 { + continue; + } + let px = a.x + (b.x - a.x) * f; + let py = a.y + (b.y - a.y) * f; + xs.push(px * dir.x + py * dir.y); + } + if xs.len() >= 2 { + // `xs.sort((u, v) => u - v)`: stabil; NaN zählt als gleich. + xs.sort_by(|u, v| (u - v).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal)); + let mut k = 0; + while k + 1 < xs.len() { + let (u0, u1) = (xs[k], xs[k + 1]); + k += 2; + if u1 - u0 < 1e-6 { + continue; + } + out.push((V2 { x: nrm.x * t + dir.x * u0, y: nrm.y * t + dir.y * u0 }, V2 { x: nrm.x * t + dir.x * u1, y: nrm.y * t + dir.y * u1 })); + } + } + t += spacing; + } +} + +/// Schraffurlinien in Papier-mm (`hatchLines`). +fn hatch_lines(poly_mm: &[V2], h: &Hatch, mm_per_m: f64) -> Vec<(V2, V2)> { + let unit_mm = (1.0 / 90.0) * mm_per_m; + let tile_mm = (if h.pattern == Pattern::Insulation { 10.0 } else { 8.0 }) * h.scale * unit_mm; + let spacing = jsnum::max(0.5, tile_mm); + let angle = (h.angle * PI) / 180.0; + let mut segs = Vec::new(); + fill_parallel(poly_mm, angle, spacing, &mut segs); + if h.pattern == Pattern::Crosshatch { + fill_parallel(poly_mm, angle + PI / 2.0, spacing, &mut segs); + } + if h.pattern == Pattern::Insulation { + fill_parallel(poly_mm, angle - PI / 4.0, spacing, &mut segs); + } + segs +} + +fn num(o: &serde_json::Value, k: &str) -> f64 { + o.get(k).and_then(|x| x.as_f64()).unwrap_or(f64::NAN) +} + +/// Deckkraft-Attribut (`dim · max(0, objOpacity)`, nur unter 1). +fn opacity_of(greyed: bool, obj: f64) -> String { + let combined = (if greyed { 0.3 } else { 1.0 }) * jsnum::max(0.0, obj); + if combined < 1.0 { + js_number(combined) + } else { + String::new() + } +} + +/// Ein Eintrag als Knoten. +fn entry(out: &mut Out, view: &View, i: usize, gi: usize, hatches: &[(i32, Hatch, i32)], m: Map) -> Option<()> { + let rec: Rec = view.rec(i)?; + let f = &rec.f; + let k = m.k; + let s = |idx: f64| -> Option { + if idx == -1.0 { + Some("undefined".to_string()) + } else { + view.string(whole(idx)?) + } + }; + let dash = |rec: &Rec| -> Option>> { + if rec.flags & F_DASH_NULL != 0 { + return Some(None); + } + match rec.dash { + Some((o, n)) => Some(Some(view.pool(o, n)?)), + None => Some(None), + } + }; + let greyed = greyed_of(&rec, false) == Some(true); + let obj = |at: usize| if rec.flags & F_OPACITY != 0 { f[at] } else { 1.0 }; + match rec.tag { + T_POLYGON => { + let pts: Vec = view.pool(whole(f[5])?, whole(f[6])?.checked_mul(2)?)?.chunks_exact(2).map(|c| V2 { x: c[0], y: c[1] }).collect(); + let opacity = opacity_of(greyed, obj(4)); + let pts_mm: Vec = pts.iter().map(|p| m.at(p.x, p.y)).collect(); + let attr = pts_attr(&pts_mm); + let sw = f[2]; + let stroke_mm = if sw > 0.0 { quantize_pen(sw) } else { 0.0 }; + let fill = s(f[0])?; + let stroke = s(f[1])?; + out.rec(&["G", &opacity]); + // Ohne Schraffur-Eintrag wie „none“. + let (json, h, color) = if f[3] >= 0.0 { hatches.get(whole(f[3])?)?.clone() } else { (-1, empty_hatch(), -1) }; + let image: Option = if h.kind == hatch::HatchKind::Image && json >= 0 { + let j: serde_json::Value = serde_json::from_str(&view.string(json as usize)?).ok()?; + j.get("image").filter(|v| v.is_object()).map(|v| v.to_string()) + } else { + None + }; + let hatch_color = if color >= 0 { view.string(color as usize)? } else { "undefined".to_string() }; + if let Some(img) = image { + if fill != "none" { + out.el(1, "polygon", &poly_node(&attr, &fill, "none", 0.0)); + } + out.rec(&["I", &attr, &img]); + if stroke_mm > 0.0 { + out.el(1, "polygon", &poly_node(&attr, "none", &stroke, stroke_mm)); + } + } else if h.pattern == Pattern::None { + out.el(1, "polygon", &poly_node(&attr, &fill, &stroke, stroke_mm)); + } else if h.pattern == Pattern::Solid { + out.el(1, "polygon", &poly_node(&attr, &hatch_color, &stroke, stroke_mm)); + } else { + if fill != "none" { + out.el(1, "polygon", &poly_node(&attr, &fill, "none", 0.0)); + } + let pen = quantize_pen(h.line_weight); + if h.random { + for run in hatch::build_random_hatch_runs(&pts, &h, None) { + if run.len() < 2 { + continue; + } + let (a, b) = (run[0], run[run.len() - 1]); + out.el(1, "line", &line_attrs(m.at(a.x, a.y), m.at(b.x, b.y), &hatch_color, pen, None)); + } + } else { + // Strichmuster der Schraffur (null und [] gleich: keins). + for (a, b) in hatch_lines(&pts_mm, &h, k) { + out.el(1, "line", &line_attrs(a, b, &hatch_color, pen, Some(&h.dash))); + } + } + if stroke_mm > 0.0 { + out.el(1, "polygon", &poly_node(&attr, "none", &stroke, stroke_mm)); + } + } + out.rec(&["g"]); + } + T_LINE => { + let a = m.at(f[4], f[5]); + let b = m.at(f[6], f[7]); + let color = if rec.flags & F_COLOR != 0 { s(f[1])? } else { "#111111".to_string() }; + let pen = quantize_pen(f[2]); + let d = dash(&rec)?; + let mut attrs = if let Some((amp, wav)) = rec.zigzag { + let p = hatch::zigzag_points(a, b, amp, wav).unwrap_or_else(|| vec![a, b]); + polyline_attrs(&p, &color, pen, d.as_deref()) + } else if let Some((length, o, n)) = rec.motif { + let pts: Vec = view.pool(o, n.checked_mul(2)?)?.chunks_exact(2).map(|c| V2 { x: c[0], y: c[1] }).collect(); + let p = hatch::motif_points_opt(a, b, &Motif { points: pts, length }, 1.0).unwrap_or_else(|| vec![a, b]); + polyline_attrs(&p, &color, pen, d.as_deref()) + } else { + line_attrs(a, b, &color, pen, d.as_deref()) + }; + let tag = if rec.zigzag.is_some() || rec.motif.is_some() { "polyline" } else { "line" }; + let o = opacity_of(greyed, obj(3)); + if !o.is_empty() { + attrs.push(("opacity", o)); + } + out.el(0, tag, &attrs); + } + T_ARC => { + let c = m.at(f[4], f[5]); + let from = m.at(f[6], f[7]); + let to = m.at(f[8], f[9]); + let r = f[10] * k; + let cross = (from.x - c.x) * (to.y - c.y) - (from.y - c.y) * (to.x - c.x); + let sweep = if cross > 0.0 { 1 } else { 0 }; + let d = format!("M {} {} A {} {} 0 0 {} {} {}", r3(from.x), r3(from.y), r3(r), r3(r), sweep, r3(to.x), r3(to.y)); + let mut attrs = vec![("d", d), ("fill", "none".to_string()), ("stroke", "#111111".to_string()), ("stroke-width", js_number(quantize_pen(f[2])))]; + push_dash(&mut attrs, dash(&rec)?.as_deref()); + let o = opacity_of(greyed, obj(3)); + if !o.is_empty() { + attrs.push(("opacity", o)); + } + out.el(0, "path", &attrs); + } + T_CIRCLE => { + let c = m.at(f[4], f[5]); + let fill = s(f[0])?; + let mut attrs = vec![ + ("cx", r3(c.x)), + ("cy", r3(c.y)), + ("r", r3(f[6] * k)), + ("fill", if !fill.is_empty() && fill != "none" { fill } else { "none".to_string() }), + ("stroke", s(f[1])?), + ("stroke-width", js_number(quantize_pen(f[2]))), + ]; + push_dash(&mut attrs, dash(&rec)?.as_deref()); + let o = opacity_of(greyed, obj(3)); + if !o.is_empty() { + attrs.push(("opacity", o)); + } + out.el(0, "circle", &attrs); + } + T_DRAWING_ARC => { + let tau = PI * 2.0; + let (cx, cy, r, a0, a1) = (f[3], f[4], f[5], f[6], f[7]); + let from = m.at(cx + r * jsnum::cos(a0), cy + r * jsnum::sin(a0)); + let to = m.at(cx + r * jsnum::cos(a1), cy + r * jsnum::sin(a1)); + let rr = r * k; + let sweep = (((a1 - a0) % tau) + tau) % tau; + let large = if sweep > PI { 1 } else { 0 }; + let d = format!("M {} {} A {} {} 0 {} 1 {} {}", r3(from.x), r3(from.y), r3(rr), r3(rr), large, r3(to.x), r3(to.y)); + let mut attrs = vec![("d", d), ("fill", "none".to_string()), ("stroke", s(f[0])?), ("stroke-width", js_number(quantize_pen(f[1])))]; + push_dash(&mut attrs, dash(&rec)?.as_deref()); + let o = opacity_of(greyed, obj(2)); + if !o.is_empty() { + attrs.push(("opacity", o)); + } + out.el(0, "path", &attrs); + } + T_DRAWING_TEXT | T_IMAGE => { + let j: serde_json::Value = serde_json::from_str(&view.string(whole(f[0])?)?).ok()?; + let jg = j.get("greyed").and_then(|g| g.as_bool()).unwrap_or(false); + if rec.tag == T_DRAWING_TEXT { + let obj = j.get("opacity").and_then(|o| o.as_f64()).unwrap_or(1.0); + out.rec(&["T", &gi.to_string(), &opacity_of(jg, obj)]); + } else { + let (min, max) = (j.get("min")?, j.get("max")?); + let (x0, y0, x1, y1) = (num(min, "x"), num(min, "y"), num(max, "x"), num(max, "y")); + let w = (x1 - x0) * k; + let h = (y1 - y0) * k; + if w <= 0.0 || h <= 0.0 { + return Some(()); + } + let tl = m.at(x0, y1); + let mut attrs = vec![ + ("href", j.get("src").and_then(|v| v.as_str()).unwrap_or("undefined").to_string()), + ("x", r3(tl.x)), + ("y", r3(tl.y)), + ("width", r3(w)), + ("height", r3(h)), + ("preserveAspectRatio", "none".to_string()), + ]; + // Bilder: eigene Deckkraft getrennt (gedimmt × 0.45), sonst nur das Dimmen. + let op = num(&j, "opacity"); + if op < 1.0 { + attrs.push(("opacity", js_number(op * if jg { 0.45 } else { 1.0 }))); + } else { + let o = opacity_of(jg, 1.0); + if !o.is_empty() { + attrs.push(("opacity", o)); + } + } + out.el(0, "image", &attrs); + } + } + _ => {} + } + Some(()) +} + +fn empty_hatch() -> Hatch { + Hatch { + pattern: Pattern::None, + kind: hatch::HatchKind::Vector, + random: false, + scale: 1.0, + angle: 0.0, + line_weight: 0.0, + origin: None, + seed: None, + density: None, + length_min: None, + length_max: None, + dash: Vec::new(), + motif: None, + } +} + +/// Anweisungsliste des Druck-SVG (Format s. Modulkopf); `None` bei kaputtem Puffer. +pub fn print_svg_ops(parts: &mut [Part], o: &PrintOptions) -> Option { + let k = 1000.0 / o.scale_denominator; + let [min_x, min_y, max_x, max_y] = o.bounds; + let content_w = (max_x - min_x) * k; + let content_h = (max_y - min_y) * k; + let m = Map { off_x: (o.page_w - content_w) / 2.0, off_y: (o.page_h - content_h) / 2.0, min_x, max_y, k }; + let mut out = Out { s: String::new(), first: true }; + let mut gi = 0usize; + for part in parts.iter_mut() { + let hatches = part.view.hatch_table()?; + for i in part.from..part.to { + entry(&mut out, &part.view, i, gi, &hatches, m)?; + gi += 1; + } + } + Some(out.s) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stift_stufen_und_runden() { + assert_eq!(quantize_pen(0.0), 0.13); + assert_eq!(quantize_pen(0.2), 0.25); + assert_eq!(quantize_pen(3.0), 1.0); + assert_eq!(r3(1.23456), "1.235"); + assert_eq!(r3(-0.0001), "0"); + assert_eq!(dash_attr(&[2.0, 0.5]), "2 0.5"); + } + + #[test] + fn schraffur_parallel_geklippt() { + let sq = [V2 { x: 0.0, y: 0.0 }, V2 { x: 10.0, y: 0.0 }, V2 { x: 10.0, y: 10.0 }, V2 { x: 0.0, y: 10.0 }]; + let mut segs = Vec::new(); + fill_parallel(&sq, 0.0, 2.0, &mut segs); + // Waagrechte Linien bei y = 0, 2, …, 10 über die volle Breite. + assert_eq!(segs.len(), 6); + assert!(segs.iter().all(|(a, b)| (b.x - a.x - 10.0).abs() < 1e-9 || (a.x - b.x - 10.0).abs() < 1e-9)); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 6d66501e..abb96b4b 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -37,6 +37,7 @@ mod plan_pick; mod snap; mod plan_svg; mod plan_dxf; +mod plan_print_svg; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/plan_print_svg.rs b/src-tauri/core/src/web/plan_print_svg.rs new file mode 100644 index 00000000..80fc9a3a --- /dev/null +++ b/src-tauri/core/src/web/plan_print_svg.rs @@ -0,0 +1,20 @@ +//! Bindung des Druck-SVG (`crate::plan_print_svg`) auf gehaltenen Plan-Puffern (Abschnitte wie +//! `plan_parts`). Ergebnis `"1"` + Anweisungsliste; leer = Puffer fehlt (TS legt neu ab und fragt +//! nochmals) oder kaputte Eingabe — nie Panic. + +use crate::plan_parts::parts_from; +use crate::plan_print_svg::{print_svg_ops, PrintOptions}; +use wasm_bindgen::prelude::wasm_bindgen; + +/// `opts` = `[Massstab-Nenner, Blattbreite mm, Blatthöhe mm, minX, minY, maxX, maxY]`. +#[wasm_bindgen] +pub fn plan_print_svg_ops(segs: &[f64], opts: &[f64]) -> String { + let Ok([n, w, h, min_x, min_y, max_x, max_y]) = <[f64; 7]>::try_from(opts) else { return String::new() }; + let Some(held) = super::plan_buf::held_for_segs(segs) else { return String::new() }; + let Some(mut parts) = parts_from(segs, |nr| held.iter().find(|e| e.0 == nr).map(|e| &*e.1)) else { return String::new() }; + let o = PrintOptions { scale_denominator: n, page_w: w, page_h: h, bounds: [min_x, min_y, max_x, max_y] }; + match print_svg_ops(&mut parts, &o) { + Some(s) => format!("1{s}"), + None => String::new(), + } +} diff --git a/src/export/planToPrintSvg.ts b/src/export/planToPrintSvg.ts index 3e3793ff..140f36db 100644 --- a/src/export/planToPrintSvg.ts +++ b/src/export/planToPrintSvg.ts @@ -19,14 +19,20 @@ // Pattern oft nicht sauber), sondern als echte, auf das Polygon geklippte // Vektorlinien direkt ins SVG. So bleibt das PDF rein vektoriell und scharf. // +// Seit [K3d] (29.10.) rechnet der Kern die Knoten aus den Plan-Puffern +// (`src-tauri/core/src/plan_print_svg.rs`, Anweisungsliste); hier bleiben der +// -Rahmen, die Bild- (laufende Ids) und die Einzeltexte +// (Text-Layout `wrapDocToLines`). Ausgabe unverändert (gleiche Knoten/Attribute). +// // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import type { HatchRender, Plan, Primitive } from "../plan/generatePlan"; import type { Vec2 } from "../model/types"; -import { buildRandomHatchRuns, zigzagPoints, motifPoints } from "../plan/glPlan/glPlanHatch"; -import { dashHasDot } from "../geometry/lineSegments"; import { wrapDocToLines, type SvgLine } from "../text/renderHtml"; import { docFromText } from "../text/richText"; +import { core } from "../engine/coreWasm"; +import { planParts, withPlanParts } from "../plan/planParts"; +import { planPrimAt } from "../plan/planLazy"; /** SVG-Namespace für die programmatisch erzeugten Knoten. */ const SVG_NS = "http://www.w3.org/2000/svg"; @@ -77,41 +83,6 @@ function ensureImagePattern( return id; } -/** ``-Knoten (mm-Koordinaten) — für Zickzack-Linien/-Läufe. */ -function polylineNode( - pts: Vec2[], - color: string, - strokeMm: number, - dash: number[] | null | undefined, -): SVGElement { - const el = document.createElementNS(SVG_NS, "polyline"); - el.setAttribute("points", pts.map((p) => `${round(p.x)},${round(p.y)}`).join(" ")); - el.setAttribute("fill", "none"); - el.setAttribute("stroke", color); - el.setAttribute("stroke-width", String(strokeMm)); - el.setAttribute("stroke-linecap", "round"); - el.setAttribute("stroke-linejoin", "round"); - if (dash && dash.length) el.setAttribute("stroke-dasharray", dash.map((d) => round(d)).join(" ")); - return el; -} - -/** - * Standard-Stift-Stufen (mm). Beliebige Kategorie-Strichstärken werden auf die - * NÄCHSTHÖHERE dieser ISO-nahen Stufen gequantelt, damit der Plan saubere, - * unterscheidbare Linienstärken trägt (dünne Hilfslinien ≠ dicke Umrisse). - */ -const PEN_STEPS = [0.13, 0.18, 0.25, 0.35, 0.5, 0.7, 1.0] as const; - -/** Untergrenze einer sichtbaren Druck-Strichstärke (mm) — vermeidet 0-Linien. */ -const MIN_PEN_MM = 0.13; - -/** Quantelt eine mm-Strichstärke auf die nächste Stift-Stufe (≥ MIN_PEN_MM). */ -function quantizePen(mm: number): number { - const w = Math.max(MIN_PEN_MM, mm); - for (const step of PEN_STEPS) if (w <= step + 1e-6) return step; - return PEN_STEPS[PEN_STEPS.length - 1]; -} - /** Ergebnis des Print-SVG-Aufbaus: das Element + Blattmasse (mm). */ export interface PrintSvg { /** Das fertige, in mm bemaßte -Element (für svg2pdf). */ @@ -200,10 +171,11 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg { bg.setAttribute("fill", "#ffffff"); svg.appendChild(bg); - // Jedes Primitiv in mm-Knoten übersetzen. - for (const p of plan.primitives) { - appendPrimitive(svg, p, map, k); - } + // Jedes Primitiv in mm-Knoten übersetzen (Kern, Anweisungsliste s. `plan_print_svg.rs`). + const o = Float64Array.of(n, opts.pageWidthMm, opts.pageHeightMm, b.minX, b.minY, b.maxX, b.maxY); + const ops = withPlanParts(planParts(plan, true), (segs) => core().plan_print_svg_ops(segs, o)); + if (!ops) throw new Error("Druck-SVG: Plan im Kern unlesbar"); + applyOps(svg, ops.slice(1), plan, map, k); return { svg, @@ -213,93 +185,50 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg { }; } -/** Schreibt ein einzelnes Primitiv (mit ggf. Schraffur) in das SVG. */ -function appendPrimitive( - svg: SVGSVGElement, - p: Primitive, - map: Mapper, - mmPerM: number, -): void { - // Gedimmt (0.3) und Objekt-Transparenz multiplizieren sich; Bilder tragen - // ihre eigene Deckkraft separat (s. dortiger Zweig). - const objOpacity = p.kind === "drawingImage" ? 1 : (p.opacity ?? 1); - const dim = p.greyed ? 0.3 : 1; - const combined = dim * Math.max(0, objOpacity); - const opacity = combined < 1 ? String(combined) : undefined; - switch (p.kind) { - case "polygon": - appendPolygon(svg, p, map, mmPerM, opacity); - break; - case "line": { - const a = map(p.a); - const b = map(p.b); - // Zickzack-Linie (amplitude/wavelength sind Papier-mm = mm-Zielraum) → - // Polylinie; sonst gerade (ggf. gestrichelte) Linie wie bisher. - // Zickzack/Custom-Motiv sind in Papier-mm definiert = mm-Zielraum (scale 1). - const ln = p.zigzag - ? polylineNode( - zigzagPoints(a, b, p.zigzag.amplitude, p.zigzag.wavelength), - p.color ?? "#111111", - quantizePen(p.weightMm), - p.dash, - ) - : p.motif - ? polylineNode( - motifPoints(a, b, p.motif), - p.color ?? "#111111", - quantizePen(p.weightMm), - p.dash, - ) - : lineNode(a, b, p.color ?? "#111111", quantizePen(p.weightMm), p.dash, mmPerM); - if (opacity) ln.setAttribute("opacity", opacity); - svg.appendChild(ln); - break; - } - case "arc": { - const node = arcNode(p, map, mmPerM); - if (opacity) node.setAttribute("opacity", opacity); - svg.appendChild(node); - break; - } - case "drawingCircle": { - const c = map(p.center); - const el = document.createElementNS(SVG_NS, "circle"); - el.setAttribute("cx", String(round(c.x))); - el.setAttribute("cy", String(round(c.y))); - el.setAttribute("r", String(round(p.r * mmPerM))); - el.setAttribute("fill", p.fill && p.fill !== "none" ? p.fill : "none"); - el.setAttribute("stroke", p.stroke); - el.setAttribute("stroke-width", String(quantizePen(p.weightMm))); - if (p.dash && p.dash.length) { - el.setAttribute("stroke-dasharray", p.dash.map((x) => round(x)).join(" ")); - if (dashHasDot(p.dash)) el.setAttribute("stroke-linecap", "round"); +/** + * Legt die Knoten der Kern-Anweisungsliste an (Format s. `plan_print_svg.rs`): Elemente mit ihren + * Attributen in Reihenfolge, Gruppen, Bild-Schraffuren (`` hier) und Einzeltexte (Layout hier). + */ +function applyOps(svg: SVGSVGElement, ops: string, plan: Plan, map: Mapper, mmPerM: number): void { + if (!ops) return; + let g: SVGElement | null = null; + for (const rec of ops.split("\u001e")) { + const f = rec.split("\u001f"); + switch (f[0]) { + case "E": { + const el = document.createElementNS(SVG_NS, f[2]) as SVGElement; + for (let i = 3; i + 1 < f.length; i += 2) el.setAttribute(f[i], f[i + 1]); + (f[1] === "1" && g ? g : svg).appendChild(el); + break; } - if (opacity) el.setAttribute("opacity", opacity); - svg.appendChild(el); - break; - } - case "drawingArc": { - const node = drawingArcNode(p, map, mmPerM); - if (opacity) node.setAttribute("opacity", opacity); - svg.appendChild(node); - break; - } - case "drawingText": { - const node = drawingTextNode(p, map, mmPerM); - if (node) { - if (opacity) node.setAttribute("opacity", opacity); - svg.appendChild(node); + case "G": + g = document.createElementNS(SVG_NS, "g") as SVGElement; + if (f[1]) g.setAttribute("opacity", f[1]); + break; + case "g": + if (g) svg.appendChild(g); + g = null; + break; + case "I": { + // Bild-Schraffur: gekacheltes über die Fläche. + const patId = ensureImagePattern(svg, JSON.parse(f[2]) as NonNullable); + const el = document.createElementNS(SVG_NS, "polygon"); + el.setAttribute("points", f[1]); + el.setAttribute("fill", `url(#${patId})`); + el.setAttribute("stroke", "none"); + g?.appendChild(el); + break; } - break; - } - case "drawingImage": { - const node = drawingImageNode(p, map, mmPerM); - if (node) { - if (p.opacity < 1) node.setAttribute("opacity", String(p.opacity * (p.greyed ? 0.45 : 1))); - else if (opacity) node.setAttribute("opacity", opacity); - svg.appendChild(node); + case "T": { + const p = planPrimAt(plan, Number(f[1])); + if (p?.kind !== "drawingText") break; + const node = drawingTextNode(p, map, mmPerM); + if (node) { + if (f[2]) node.setAttribute("opacity", f[2]); + svg.appendChild(node); + } + break; } - break; } } } @@ -371,309 +300,7 @@ function drawingTextNode( return el; } -/** Eingebettetes Rasterbild (Data-URL) als achsparalleles ``. */ -function drawingImageNode( - p: Extract, - map: Mapper, - mmPerM: number, -): SVGImageElement | null { - const w = (p.max.x - p.min.x) * mmPerM; - const h = (p.max.y - p.min.y) * mmPerM; - if (w <= 0 || h <= 0) return null; - const topLeft = map({ x: p.min.x, y: p.max.y }); - const el = document.createElementNS(SVG_NS, "image"); - el.setAttribute("href", p.src); - el.setAttribute("x", String(round(topLeft.x))); - el.setAttribute("y", String(round(topLeft.y))); - el.setAttribute("width", String(round(w))); - el.setAttribute("height", String(round(h))); - el.setAttribute("preserveAspectRatio", "none"); - return el; -} - -/** - * Polygon mit Füllung/Umriss/Schraffur. Reihenfolge wie in der PlanView: - * • pattern "none" → reine Füllung (oder „none") + Umriss. - * • pattern "solid" → Vollfüllung in der Hatch-Farbe + Umriss. - * • Linien/Kreuz/Dämmung → Grundfüllung, dann geklippte Schraffurlinien, dann Umriss. - */ -function appendPolygon( - svg: SVGSVGElement, - p: Extract, - map: Mapper, - mmPerM: number, - opacity: string | undefined, -): void { - const ptsMm = p.pts.map(map); - const ptsAttr = ptsMm.map((s) => `${round(s.x)},${round(s.y)}`).join(" "); - const strokeMm = p.strokeWidthMm > 0 ? quantizePen(p.strokeWidthMm) : 0; - - const g = document.createElementNS(SVG_NS, "g"); - if (opacity) g.setAttribute("opacity", opacity); - - const pattern = p.hatch.pattern; - if (p.hatch.kind === "image" && p.hatch.image) { - // Bild-Schraffur: gekacheltes mit (scaleX/scaleY/rotation) - // über die Fläche, unabhängig vom `pattern`-Feld. Grundfüllung darunter, - // Umriss obenauf. - if (p.fill !== "none") g.appendChild(polyNode(ptsAttr, p.fill, "none", 0)); - const patId = ensureImagePattern(svg, p.hatch.image); - g.appendChild(polyNode(ptsAttr, `url(#${patId})`, "none", 0)); - if (strokeMm > 0) g.appendChild(polyNode(ptsAttr, "none", p.stroke, strokeMm)); - } else if (pattern === "none") { - g.appendChild(polyNode(ptsAttr, p.fill, p.stroke, strokeMm)); - } else if (pattern === "solid") { - g.appendChild(polyNode(ptsAttr, p.hatch.color, p.stroke, strokeMm)); - } else { - // Grundfüllung (ohne Umriss), dann die geklippten Schraffurlinien, dann der - // Umriss obenauf (separat, damit er die Schraffur-Enden überdeckt). - if (p.fill !== "none") { - g.appendChild(polyNode(ptsAttr, p.fill, "none", 0)); - } - if (p.hatch.lines === "random") { - // Random-Vektor (Kies/Splitt): deterministische Streu-Striche. Wird im - // MODELL-Raum erzeugt (identischer Seed/Geometrie wie Bildschirm/GL/PDF) - // und dann nach Papier-mm abgebildet. - for (const run of buildRandomHatchRuns(p.pts, p.hatch)) { - if (run.length < 2) continue; - g.appendChild( - lineNode( - map(run[0]), - map(run[run.length - 1]), - p.hatch.color, - quantizePen(p.hatch.lineWeight), - null, - mmPerM, - ), - ); - } - } else { - for (const seg of hatchLines(ptsMm, p.hatch, mmPerM)) { - g.appendChild( - lineNode( - seg.a, - seg.b, - p.hatch.color, - quantizePen(p.hatch.lineWeight), - p.hatch.dash, - mmPerM, - ), - ); - } - } - if (strokeMm > 0) { - g.appendChild(polyNode(ptsAttr, "none", p.stroke, strokeMm)); - } - } - - svg.appendChild(g); -} - -/** Erzeugt einen -Knoten (mm-Koordinaten als Attribut-String). */ -function polyNode( - ptsAttr: string, - fill: string, - stroke: string, - strokeMm: number, -): SVGElement { - const el = document.createElementNS(SVG_NS, "polygon"); - el.setAttribute("points", ptsAttr); - el.setAttribute("fill", fill); - if (stroke !== "none" && strokeMm > 0) { - el.setAttribute("stroke", stroke); - el.setAttribute("stroke-width", String(strokeMm)); - el.setAttribute("stroke-linejoin", "round"); - } else { - el.setAttribute("stroke", "none"); - } - return el; -} - -/** Erzeugt einen -Knoten in mm; Strichmuster (mm Welt → mm Papier). */ -function lineNode( - a: Vec2, - b: Vec2, - color: string, - strokeMm: number, - dash: number[] | null | undefined, - _mmPerM: number, -): SVGElement { - const el = document.createElementNS(SVG_NS, "line"); - el.setAttribute("x1", String(round(a.x))); - el.setAttribute("y1", String(round(a.y))); - el.setAttribute("x2", String(round(b.x))); - el.setAttribute("y2", String(round(b.y))); - el.setAttribute("stroke", color); - el.setAttribute("stroke-width", String(strokeMm)); - el.setAttribute("stroke-linecap", "round"); - if (dash && dash.length) { - // Strichmuster ist in mm Papier definiert (wie weightMm), daher direkt. - el.setAttribute("stroke-dasharray", dash.map((d) => round(d)).join(" ")); - } - return el; -} - -/** - * Erzeugt einen Bogen als (A-Kommando). Der Bogen-Radius ist in Metern → - * Papier-mm. Drehrichtung aus dem Kreuzprodukt im Papier-Raum (Y nach unten). - */ -function arcNode( - p: Extract, - map: Mapper, - mmPerM: number, -): SVGElement { - const c = map(p.center); - const from = map(p.from); - const to = map(p.to); - const r = p.r * mmPerM; - const v1 = { x: from.x - c.x, y: from.y - c.y }; - const v2 = { x: to.x - c.x, y: to.y - c.y }; - const cross = v1.x * v2.y - v1.y * v2.x; - const sweep = cross > 0 ? 1 : 0; - const d = `M ${round(from.x)} ${round(from.y)} A ${round(r)} ${round(r)} 0 0 ${sweep} ${round(to.x)} ${round(to.y)}`; - const el = document.createElementNS(SVG_NS, "path"); - el.setAttribute("d", d); - el.setAttribute("fill", "none"); - el.setAttribute("stroke", "#111111"); - el.setAttribute("stroke-width", String(quantizePen(p.weightMm))); - if (p.dash && p.dash.length) { - el.setAttribute("stroke-dasharray", p.dash.map((x) => round(x)).join(" ")); - // Punktmuster (dash enthält eine 0): runde Kappe → Dots am Bogen. - if (dashHasDot(p.dash)) el.setAttribute("stroke-linecap", "round"); - } - return el; -} - -/** - * `drawingArc` → glatter SVG-Bogen. Konvention wie im Bildschirm-Renderer - * (`planView/primitives.tsx`): die Winkel laufen im MODELL immer gegen den - * Uhrzeigersinn von `a0` nach `a1`; da die Ziel-Y-Achse gespiegelt ist, wird - * daraus am Papier ein Uhrzeigersinn-Bogen (sweep-flag 1). `large-arc` aus - * der normierten Spannweite. - */ -function drawingArcNode( - p: Extract, - map: Mapper, - mmPerM: number, -): SVGElement { - const TAU = Math.PI * 2; - const from = map({ x: p.center.x + p.r * Math.cos(p.a0), y: p.center.y + p.r * Math.sin(p.a0) }); - const to = map({ x: p.center.x + p.r * Math.cos(p.a1), y: p.center.y + p.r * Math.sin(p.a1) }); - const r = p.r * mmPerM; - const sweep = (((p.a1 - p.a0) % TAU) + TAU) % TAU; - const largeArc = sweep > Math.PI ? 1 : 0; - const el = document.createElementNS(SVG_NS, "path"); - el.setAttribute( - "d", - `M ${round(from.x)} ${round(from.y)} A ${round(r)} ${round(r)} 0 ${largeArc} 1 ${round(to.x)} ${round(to.y)}`, - ); - el.setAttribute("fill", "none"); - el.setAttribute("stroke", p.stroke); - el.setAttribute("stroke-width", String(quantizePen(p.weightMm))); - if (p.dash && p.dash.length) { - el.setAttribute("stroke-dasharray", p.dash.map((x) => round(x)).join(" ")); - if (dashHasDot(p.dash)) el.setAttribute("stroke-linecap", "round"); - } - return el; -} - /** Auf 3 Nachkommastellen runden (kompaktes, exaktes SVG). */ function round(v: number): number { return Math.round(v * 1000) / 1000; } - -// ── Schraffur als geklippte Vektorlinien ───────────────────────────────────── - -interface Seg { - a: Vec2; - b: Vec2; -} - -/** - * Erzeugt die Schraffurlinien eines Polygons (in Papier-mm), auf das Polygon - * geklippt. Die Kachelgrösse der Bildschirm-PlanView (8 px bzw. 14 px bei - * „insulation", × Maßstab) wird hier in einen mm-Linienabstand übersetzt, damit - * der Druck der Bildschirm-Dichte nahekommt: - * • diagonal/crosshatch: parallele Linienscharen im Winkel `angle`. - * • crosshatch: zusätzlich die um 90° gedrehte Schar. - * • insulation: vereinfacht als eine dichtere diagonale Schar (echte Wellen- - * linie wäre als Pfad möglich; eine Linienschar liest sich im Druck sauber - * und bleibt rein vektoriell — offener Punkt im Report). - */ -function hatchLines(polyMm: Vec2[], hatch: HatchRender, mmPerM: number): Seg[] { - // Kachel der PlanView: 8 viewBox-Einheiten (= px bei dpi-Bezug) × scale. In der - // PlanView ist 1 viewBox-Einheit = 1/PX_PER_M m = 1/90 m. Auf Papier sind das - // (1/90)·mmPerM mm. So bleibt die Strich-Dichte massstäblich konsistent. - const unitMm = (1 / 90) * mmPerM; - const tileMm = (hatch.pattern === "insulation" ? 10 : 8) * hatch.scale * unitMm; - const spacing = Math.max(0.5, tileMm); // Mindestabstand, sonst zu dicht - - const angle = (hatch.angle * Math.PI) / 180; - const segs: Seg[] = []; - fillParallel(polyMm, angle, spacing, segs); - if (hatch.pattern === "crosshatch") { - fillParallel(polyMm, angle + Math.PI / 2, spacing, segs); - } - if (hatch.pattern === "insulation") { - // Zweite, gegenläufige Schar deutet die Dämmungs-Textur an (dichter Filz). - fillParallel(polyMm, angle - Math.PI / 4, spacing, segs); - } - return segs; -} - -/** - * Füllt das Polygon mit parallelen Linien im gegebenen Winkel/Abstand und klippt - * jede Linie auf das Polygon (Scanline über die Polygon-Schnittpunkte). Robust - * für konvexe wie konkave (einfache) Polygone. - */ -function fillParallel( - poly: Vec2[], - angle: number, - spacing: number, - out: Seg[], -): void { - if (poly.length < 3 || spacing <= 0) return; - // Linienrichtung d und Normale nrm (Projektionsachse). - const dir = { x: Math.cos(angle), y: Math.sin(angle) }; - const nrm = { x: -dir.y, y: dir.x }; - - // Projektion der Polygonpunkte auf die Normale → [tMin, tMax]-Band der Linien. - let tMin = Infinity; - let tMax = -Infinity; - for (const p of poly) { - const t = p.x * nrm.x + p.y * nrm.y; - if (t < tMin) tMin = t; - if (t > tMax) tMax = t; - } - // Linien an t = tMin + i·spacing; für jede die Schnitt-Intervalle ermitteln. - const start = Math.ceil(tMin / spacing) * spacing; - for (let t = start; t <= tMax; t += spacing) { - const xs: number[] = []; // Parameter entlang dir der Schnittpunkte - for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { - const a = poly[j]; - const b = poly[i]; - const ta = a.x * nrm.x + a.y * nrm.y; - const tb = b.x * nrm.x + b.y * nrm.y; - // Schneidet die Kante das Niveau t? - if (ta === tb) continue; - const f = (t - ta) / (tb - ta); - if (f < 0 || f > 1) continue; - const px = a.x + (b.x - a.x) * f; - const py = a.y + (b.y - a.y) * f; - xs.push(px * dir.x + py * dir.y); // Position entlang dir - } - if (xs.length < 2) continue; - xs.sort((u, v) => u - v); - // Paarweise Intervalle = Polygon-Inneres entlang der Linie. - for (let k = 0; k + 1 < xs.length; k += 2) { - const u0 = xs[k]; - const u1 = xs[k + 1]; - if (u1 - u0 < 1e-6) continue; - // Punkt = t·nrm + u·dir. - out.push({ - a: { x: nrm.x * t + dir.x * u0, y: nrm.y * t + dir.y * u0 }, - b: { x: nrm.x * t + dir.x * u1, y: nrm.y * t + dir.y * u1 }, - }); - } - } -} diff --git a/src/plan/planLazy.test.ts b/src/plan/planLazy.test.ts index 2c89745c..f597543b 100644 --- a/src/plan/planLazy.test.ts +++ b/src/plan/planLazy.test.ts @@ -1,5 +1,5 @@ // Lazy Plan ([K3d], `planLazy.ts`): `generatePlan` liest die Kern-Primitive erst bei Bedarf; die -// Verbraucher im Kern (Szene, Auswahl, SVG) und die Text-Einträge kommen ohne aus. +// Verbraucher im Kern (Szene, Auswahl, SVG, DXF, Druck-SVG) und die Text-Einträge kommen ohne aus. import { describe, expect, it } from "vitest"; import { generatePlan, generateVisibleLevelsPlan, materializeUnderlay, type Primitive } from "./generatePlan"; @@ -7,6 +7,8 @@ import { isLazyUnread, planCount, planPrimAt, planTextEntries, planWithExtra } f import { planSceneBin, planToRenderScene } from "./toRenderScene"; import { planToSvgString } from "../export/planToSvgString"; import { PlanPickIndex } from "./planView/planPick"; +import { collectPlanDrawing } from "../export/exportDxf"; +import { planToPrintSvg } from "../export/planToPrintSvg"; import { sampleProject } from "../model/sampleProject"; import { flattenCategories, type Project } from "../model/types"; @@ -31,8 +33,19 @@ describe("lazy Plan", () => { const ix = new PlanPickIndex(plan); ix.topPolygon({ x: 2, y: 2 }); ix.marquee("wallId", { minX: -100, minY: -100, maxX: 100, maxY: 100 }, false); - ix.drawingTextAt({ x: 1.2, y: 2 }); + expect(ix.drawingTextAt({ x: 1.2, y: 2 })).not.toBeNull(); ix.release(); + expect(collectPlanDrawing(plan, withText).stats().model.TEXT).toBeGreaterThan(0); + // Druck-SVG mit minimalem DOM-Ersatz (Node ohne DOM). + const el = (): Record => ({ setAttribute() {}, appendChild: (c: unknown) => c, insertBefore: (c: unknown) => c, querySelector: () => null, firstChild: null }); + const g = globalThis as { document?: unknown }; + const prev = g.document; + g.document = { createElementNS: () => el() }; + try { + planToPrintSvg(plan, { scaleDenominator: 100, pageWidthMm: 420, pageHeightMm: 297 }); + } finally { + g.document = prev; + } expect(planTextEntries(plan).length).toBeGreaterThan(0); expect(planPrimAt(plan, 0)).toBeDefined(); expect(isLazyUnread(plan)).toBe(true); From c83b5fcb821f71cdd83d44f54d6bbfce7e5eeb4d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 02:09:21 +0000 Subject: [PATCH 5/5] [K3d] TODO: letzte Primitive[]-Verbraucher auf den Puffer, generatePlan lazy, Messung, Rest Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- TODO.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/TODO.md b/TODO.md index 80cde8e0..a07076ee 100644 --- a/TODO.md +++ b/TODO.md @@ -205,6 +205,36 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern (`exportDxf.ts`, 1000 Zeilen Stil/Layer-Logik) und `planToPrintSvg.ts` (Layout-PDF/LayoutSheet; nicht auf `sceneToPrintSvg` umgestellt, weil die Ausgabe dann nicht mehr byte-gleich wäre). `generatePlan` dekodiert den Kern-Puffer weiter vollständig (für diese Verbraucher); fällt, wenn sie den Puffer lesen bzw. das Modell nach Rust zieht [K4]. + ✅ (29.10.) **Letzte Verbraucher lesen den Puffer, `generatePlan` liest lazy.** + - Lazy Plan (`src/plan/planLazy.ts`): `generatePlan`, `generateVisibleLevelsPlan`, `materializeUnderlay` und + `planWithExtra` (Überlagerungen in `viewportContent`) setzen den Plan aus Stücken zusammen (Kern-Abschnitte + + TS-Listen); `plan.primitives` entsteht erst beim ersten Zugriff. `decodePlanBuf` liest Einträge, Texte und + Schraffur-JSON bei Bedarf (`prim(i)`, `tag(i)`); `planPrimAt` (ein Eintrag), `planTextEntries` (nur Texte/Bilder, + aus den Typ-Kennungen), `planCount`. `planParts` nimmt die Stücke direkt (keine Identitätsprüfung). Abzugskörper, + Mono und Strichstärken-Massstab bleiben auf der Liste (sie ändern Primitive). + - Auswahl (`plan_pick.rs`): Rahmen-Auswahl über Polygone je Pick-Art und über 2D-Zeichnungen (Linien, Polygone, + abgetastete Kreise/Bögen, Text-/Bild-Rahmen, Unterlage ausgenommen), Einzeltext-/Bild-Treffer, Form einer + Zeichnung (`drawingLabel`). `marqueeHit*`/`marqueeHitDrawings` in TS gelöscht. + - PlanView: Einzelzugriffe über `planPrimAt`; mit GPU kommen SVG-Kandidaten/Culling nur aus den Text-Einträgen + (Culling selbst bleibt TS über diese wenigen); `planSceneTexts` und die native Text-Sync lesen nur Text-Einträge. + - DXF/DWG (`plan_dxf.rs`): Sammler (Ebenen, Linientypen, Textstile, DIMENSION, BLOCK/INSERT/ATTRIB, HATCH, Verlauf, + Zufallsstriche, Papierbereich) im Kern aus Puffer + Projekt-Dokument; TS liefert nur das Text-Layout flach mit und + gibt die flache Zeichnung an fileio. `FlatDrawing`-Klasse und `dxfCadParts` (ausser `fontNameOf`) gelöscht. + - Druck-SVG/Layout-Viewport (`plan_print_svg.rs`): Knoten als Anweisungsliste, TS legt sie als DOM an (Rahmen, + Bild-``, Einzeltexte bleiben TS). Nicht auf `sceneToPrintSvg` umgestellt (Ausgabe bliebe nicht gleich) — + nicht nötig, der Puffer-Weg ist gleich. + Gleichheit (temporäre Paritätstests gegen die alten TS-Fassungen, danach entfernt): Rahmen-/Text-Treffer 53 870 + Abfragen (200 Zufallspläne, Beispiel EG/OG/UG, Überlagerung, bigSample(6)); DXF-Zeichnung Zahl für Zahl in 451 Fällen + (Beispiel + Fachplaner-Projekt × Geschosse × Detailgrade × mono × Optionen, 300 Zufallspläne, bigSample(8)), DXF/ + Binär byte-gleich, CLI `dxf`/`dwg` (--binary, --scale, --dim-unit cm, --layout) 36 Dateien byte-gleich zur CLI des + Hauptstands; Druck-SVG 475 Pläne gleich (DOM serialisiert). Bleibende Tests: `planLazy.test.ts` (Kern-Verbraucher + lesen nicht), Marquee-/Text-Tests über den Kern, Rust-Tests für Rechteck-Treffer, Linientypen, Papier, blocklokal. + Messung (Node, Linux-Container, `--no-opt`, Min/Median, alt und neu im selben Lauf): `generatePlan` Beispiel-EG + 0,38–0,42/0,43–0,65 → 0,30–0,33/0,35–0,40 ms; grosses Projekt (bigSampleProject 20×20) 228–241/285–294 → + 158–160/166–176 ms; mit Render-Szene (`planSceneBin`, WASM-Ansicht) 396–472 → 324–352 ms. + Bleibt: der native macOS-Pfad (`useNativePlanRenderer`/`GpuChunkCache`) liest die Liste weiter (nicht in der Tauri-App + geprüft); SVG-Rückfall ohne GPU, Geschoss-Überlagerung mit gedimmten Ebenen (`materializeGreyed`), Gruppen-Isolation, + Schnitt/Ansicht-Overlays in `viewportContent` und Abzugskörper/Mono/Massstab lesen die Liste (dann wie bisher). Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben (Versionsnummer + Hin-und-zurück-Tests), Text-Layout bleibt bis [K4] in TS. - ◐ **[K4] Modell und Ops in Rust** [2]; TS bekommt die Typen generiert (z. B. `ts-rs`). · XL @@ -240,6 +270,8 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern noch die dekodierten `Primitive[]`. Nachtrag 28.10.: render2d-Szene, Auswahl, Fang und SVG-Text-Export lesen den Puffer im Kern ([K3d]); Overlay/Texte, DXF und Layout-PDF noch über `Primitive[]`. + Nachtrag 29.10.: auch Rahmen-Auswahl, Text-/Bild-Treffer, Overlay-Texte, DXF/DWG und Druck-SVG lesen den Puffer im + Kern; `generatePlan` liest die Kern-Primitive nur noch bei Bedarf ([K3d]). - ◐ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung (`validateOps`) und Gruppen/Ebenen-Logik wandern nach Rust; `diffToOps` entfällt, TS hält nur noch eine Leseansicht. **Erste Etappe (28.10.): Ops, Prüfung, Undo/Redo im Kern.** `core/src/ops.rs` (Op, Prüfung bitgleich zur TS-Fassung — gleiche