Merge [C2] DXF/DWG-Export fuer Fachplaner: echte DIMENSION mit DIMSTYLE, Tueren/Fenster/Symbole als BLOCK+INSERT mit ATTRIB, Textstile, LTYPE aus Linienstilen, Raumstempel, Papierbereich-Layout
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
17 files changed
+2107
-60
No files matched your search
@@ -4001,6 +4001,7 @@ export default function App() {
|
||||
{exportDxfOpen && (
|
||||
<ExportDxfDialog
|
||||
planTitle={activeLevel.name}
|
||||
initialScale={scaleDenominator}
|
||||
selectionCount={selectionLockIds.length}
|
||||
onExport={onExportDxf}
|
||||
onClose={() => setExportDxfOpen(false)}
|
||||
|
||||
+7
-4
@@ -9,7 +9,7 @@
|
||||
// json = render2d-Szene (planToRenderScene)
|
||||
// dossier-cli <projekt.obp> section <Name> [--out schnitt.svg] (braucht render3d-WASM)
|
||||
// dossier-cli <projekt.obp> elevation <Name> [--out ansicht.svg]
|
||||
// dossier-cli <projekt.obp> dxf [--binary]|dwg|ifc|step|obj|stl|glb|gltf|schedule|kennzahlen|sun [--level EG] [--out datei]
|
||||
// dossier-cli <projekt.obp> dxf [--binary] [--scale 100] [--dim-unit cm] [--layout]|dwg|ifc|step|obj|stl|glb|gltf|schedule|kennzahlen|sun [--level EG] [--out datei]
|
||||
// glb/gltf = glTF 2.0 (Y-up, Meter, Geschoss als Eltern; --flat ohne Geschoss-Knoten)
|
||||
// dossier-cli convert <eingabe> <ausgabe> [--cmd "befehl"]… Format nach Endung: dxf/dwg/ifc/obp → obp-Import,
|
||||
// obp → dxf/dwg/ifc/obj/stl/glb/gltf/step; --cmd: weitere Befehle
|
||||
@@ -578,9 +578,12 @@ async function execute(project: Project, file: string, command: string, rest: st
|
||||
const world = projectToWorldCoords(project);
|
||||
const plan = generatePlan(world, lvl.id, allCodes);
|
||||
await loadFileio();
|
||||
if (command === "dxf" && args.flags.has("binary")) out(args, buildPlanDxfBinary(plan, world), `${lvl.name}.dxf`);
|
||||
else if (command === "dxf") out(args, buildPlanDxf(plan, world), `${lvl.name}.dxf`);
|
||||
else out(args, buildPlanDwg(plan, world), `${lvl.name}.dwg`);
|
||||
// --scale N (Massstabsnenner, Default 100): Bemassungsstil, Linientypen, Raumstempel, Ansichtsfenster.
|
||||
// --dim-unit cm: Masszahlen in Zentimetern; --layout: zusätzlich Papierbereich mit Ansichtsfenster.
|
||||
const cad = { scaleDenominator: scale, dimUnit: args.flags.get("dim-unit") === "cm" ? ("cm" as const) : ("m" as const), paperLayout: args.flags.has("layout") };
|
||||
if (command === "dxf" && args.flags.has("binary")) out(args, buildPlanDxfBinary(plan, world, cad), `${lvl.name}.dxf`);
|
||||
else if (command === "dxf") out(args, buildPlanDxf(plan, world, cad), `${lvl.name}.dxf`);
|
||||
else out(args, buildPlanDwg(plan, world, cad), `${lvl.name}.dwg`);
|
||||
return 0;
|
||||
}
|
||||
case "ifc":
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
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";
|
||||
|
||||
describe("fontNameOf", () => {
|
||||
it("erste echte Familie, ohne Anführungszeichen; generische/Variablen übersprungen", () => {
|
||||
expect(fontNameOf('"Helvetica Neue", Arial, sans-serif')).toBe("Helvetica Neue");
|
||||
expect(fontNameOf("var(--font-ui, sans-serif)")).toBeNull();
|
||||
expect(fontNameOf("sans-serif, Arial")).toBe("Arial");
|
||||
expect(fontNameOf("'Source Sans 3'")).toBe("Source Sans 3");
|
||||
expect(fontNameOf(undefined)).toBeNull();
|
||||
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<Primitive, { kind: "line" }>;
|
||||
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<Primitive, { kind: "drawingText" }>;
|
||||
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<Primitive, { kind: "drawingCircle" }>;
|
||||
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]));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
// 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";
|
||||
|
||||
/** 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 {
|
||||
if (!css) return null;
|
||||
// `var(--font-ui, sans-serif)` enthält selbst ein Komma: vor dem Teilen entfernen.
|
||||
for (const raw of css.replace(/var\([^)]*\)/g, "").split(",")) {
|
||||
const name = raw.trim().replace(/^["']|["']$/g, "").trim();
|
||||
if (!name) continue;
|
||||
if (/^(sans-serif|serif|monospace|cursive|fantasy|system-ui|ui-sans-serif|inherit|initial)$/i.test(name)) continue;
|
||||
return name;
|
||||
}
|
||||
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_<an>_<aus>…` (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" };
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
// Fachplaner-Export ([C2], 28.10.): DIMENSION mit Anonymblock und DIMSTYLE, BLOCK/INSERT/ATTRIB für Türen,
|
||||
// Fenster und Möbelblöcke, Linientypen, Textstile, Papierbereich — gegengelesen mit ezdxf (Auditor, wie
|
||||
// ein CAD-Programm die Datei sieht), libredwg (DWG) und dem eigenen DXF-Import. ezdxf-Teile werden ohne
|
||||
// `pip install ezdxf` übersprungen (Muster `exportDxf.ezdxf.test.ts`).
|
||||
|
||||
import "../engine/fileioWasm.setup";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { buildPlanDwg, buildPlanDxf, buildPlanDxfBinary, collectPlanDrawing } from "./exportDxf";
|
||||
import { countByType, libreDwgReader, readDxf } from "./cadReadBack.testutil";
|
||||
import { parseDxf } from "../io/dxfParser";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { generatePlan } from "../plan/generatePlan";
|
||||
import { flattenCategories } from "../model/types";
|
||||
import type { Drawing2D, Project } from "../model/types";
|
||||
|
||||
const hasEzdxf = spawnSync("python3", ["-c", "import ezdxf"]).status === 0;
|
||||
const allCodes = (p: Project) => new Set(flattenCategories(p.layers).map((l) => l.code));
|
||||
|
||||
/** Demo-Haus plus Bemassungskette, gestrichelte Linie, Möbelblock (2 Instanzen), Text mit Schrift. */
|
||||
function cadProject(): Project {
|
||||
const code = "90";
|
||||
const d = (id: string, geom: Drawing2D["geom"], extra: Partial<Drawing2D> = {}): Drawing2D =>
|
||||
({ id, type: "drawing2d", levelId: "eg", categoryCode: code, geom, ...extra }) as Drawing2D;
|
||||
return {
|
||||
...sampleProject,
|
||||
lineStyles: [...sampleProject.lineStyles, { id: "ls-dash", name: "Strichlinie 0.3/0.1", weight: 0.13, color: "#000000", dash: [3, 1] }],
|
||||
textStyles: [{ id: "body", label: "Text", marks: { font: '"Helvetica Neue", Arial, sans-serif' } }],
|
||||
blockDefs: [
|
||||
{
|
||||
id: "bd-sofa",
|
||||
name: "Sofa",
|
||||
geom2d: [
|
||||
{ shape: "rect", min: { x: -0.9, y: -0.4 }, max: { x: 0.9, y: 0.4 } },
|
||||
{ shape: "line", a: { x: -0.9, y: 0.2 }, b: { x: 0.9, y: 0.2 } },
|
||||
],
|
||||
},
|
||||
],
|
||||
drawings2d: [
|
||||
d("dim1", { shape: "dimension", pts: [{ x: 0, y: -1 }, { x: 2, y: -1 }, { x: 5, y: -1 }], offset: -0.8 }),
|
||||
d("dash1", { shape: "line", a: { x: 0, y: -2 }, b: { x: 4, y: -2 } }, { lineStyleId: "ls-dash" }),
|
||||
d("sofa1", { shape: "block", blockDefId: "bd-sofa", at: { x: 1.5, y: 1 }, rotation: 0 }),
|
||||
d("sofa2", { shape: "block", blockDefId: "bd-sofa", at: { x: 3.5, y: 2.5 }, rotation: Math.PI / 2, scale: 1.5 }),
|
||||
d("txt1", { shape: "text", at: { x: 1, y: 4 }, text: "Müller & Söhne", height: 0.2, angle: 0 }),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
interface Ez {
|
||||
version: string;
|
||||
errors: string[];
|
||||
entities: Array<Record<string, unknown> & { type: string; layer: string }>;
|
||||
blocks: Record<string, { entities: Record<string, number>; anonymous: boolean }>;
|
||||
styles: Record<string, string | null>;
|
||||
fonts: Record<string, string>;
|
||||
linetypes: Record<string, number[]>;
|
||||
dimstyles: Record<string, Record<string, unknown>>;
|
||||
layouts: Record<string, { viewports: Array<{ id: number; center: number[]; size: number[]; view_center: number[]; view_height: number }>; paper: number[] | null }>;
|
||||
}
|
||||
|
||||
function ezdxf(name: string, data: string | Uint8Array): { status: number | null; r: Ez; err: string } {
|
||||
const dir = mkdtempSync(join(tmpdir(), "dossier-cad-"));
|
||||
const file = join(dir, `${name}.dxf`);
|
||||
writeFileSync(file, data);
|
||||
const p = spawnSync("python3", ["scripts/validate-dxf.py", file], { encoding: "utf8", timeout: 60_000 });
|
||||
let r = null as unknown as Ez;
|
||||
try {
|
||||
r = JSON.parse(p.stdout) as Ez;
|
||||
} catch {
|
||||
/* Fehlertext unten */
|
||||
}
|
||||
return { status: p.status, r, err: `${p.stdout}\n${p.stderr}` };
|
||||
}
|
||||
|
||||
describe("Fachplaner-Export: Sammler", () => {
|
||||
const project = cadProject();
|
||||
const plan = generatePlan(project, "eg", allCodes(project));
|
||||
|
||||
it("Bemassung, Blöcke und Öffnungen werden zu CAD-Objekten statt zu losen Linien", () => {
|
||||
const { model, blocks } = collectPlanDrawing(plan, project).stats();
|
||||
expect(model.DIMENSION).toBe(2); // zwei Segmente der Kette
|
||||
expect(model.INSERT).toBe(3 + 2); // Tür + 2 Fenster des Demo-Hauses, 2 Sofas
|
||||
expect(blocks.LINE).toBeGreaterThan(0);
|
||||
// Bemassung: ihre Linien/Texte stehen nicht zusätzlich lose im Modellbereich.
|
||||
const dimPrims = plan.primitives.filter((p) => "drawingId" in p && p.drawingId === "dim1").length;
|
||||
expect(dimPrims).toBeGreaterThan(0);
|
||||
const loose = collectPlanDrawing({ ...plan, primitives: plan.primitives.filter((p) => !("drawingId" in p && p.drawingId === "dim1")) }, project).stats();
|
||||
expect(loose.model.LINE).toBe(model.LINE);
|
||||
expect(loose.model.TEXT).toBe(model.TEXT);
|
||||
});
|
||||
|
||||
it("Massstab und Einheit wirken auf Stil und Masszahl", () => {
|
||||
const [flat] = collectPlanDrawing(plan, project, { scaleDenominator: 50, dimUnit: "cm" }).args();
|
||||
expect(flat.length).toBeGreaterThan(0);
|
||||
const dxf = readDxf(buildPlanDxf(plan, project, { scaleDenominator: 50, dimUnit: "cm" }));
|
||||
expect(dxf.entities.filter((e) => e.type === "DIMENSION").length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!hasEzdxf)("Fachplaner-Export gegen ezdxf", { timeout: 60_000 }, () => {
|
||||
const project = cadProject();
|
||||
const plan = generatePlan(project, "eg", allCodes(project));
|
||||
const read = (opts = {}) => {
|
||||
const x = ezdxf("cad", buildPlanDxf(plan, project, opts));
|
||||
expect(x.r, x.err).not.toBeNull();
|
||||
expect(x.r.errors).toEqual([]);
|
||||
expect(x.status).toBe(0);
|
||||
return x.r;
|
||||
};
|
||||
|
||||
it("DIMENSION: ausgerichtet, mit *D-Block (Hilfslinien, Masslinie, 2 Striche, Zahl) und Stil 1:100", () => {
|
||||
const r = read();
|
||||
const dims = r.entities.filter((e) => e.type === "DIMENSION");
|
||||
expect(dims.map((d) => d.measurement as number)).toEqual([expect.closeTo(2, 9), expect.closeTo(3, 9)]);
|
||||
for (const d of dims) {
|
||||
expect((d.dimtype as number) & 7).toBe(1); // ausgerichtet
|
||||
expect(d.dimstyle).toBe("DOSSIER_1-100");
|
||||
const block = r.blocks[d.block as string];
|
||||
expect(block?.anonymous, String(d.block)).toBe(true);
|
||||
expect(block.entities).toEqual({ LINE: 5, TEXT: 1 });
|
||||
}
|
||||
const st = r.dimstyles["DOSSIER_1-100"];
|
||||
expect(st).toMatchObject({ dimscale: 100, dimtad: 1, dimdec: 2, dimlfac: 1, dimtxsty: "DOSSIER" });
|
||||
expect(st.dimtxt as number).toBeCloseTo(0.004, 9); // 4 mm Papier
|
||||
expect(st.dimtsz as number).toBeCloseTo(0.0015, 9); // Architekturstrich 3 mm
|
||||
});
|
||||
|
||||
it("Bemassungsstil im Massstab 1:50 und in cm", () => {
|
||||
const r = read({ scaleDenominator: 50, dimUnit: "cm" });
|
||||
const st = r.dimstyles["DOSSIER_1-50_cm"];
|
||||
expect(st).toMatchObject({ dimscale: 50, dimdec: 0, dimlfac: 100 });
|
||||
const block = r.blocks[r.entities.find((e) => e.type === "DIMENSION")!.block as string];
|
||||
expect(block.entities.TEXT).toBe(1);
|
||||
});
|
||||
|
||||
it("Türen/Fenster: INSERT in Wandrichtung mit Attributen, Block mit Geometrie", () => {
|
||||
const r = read();
|
||||
const ins = r.entities.filter((e) => e.type === "INSERT" && !(e.name as string).startsWith("Sofa"));
|
||||
expect(ins.length).toBe(3);
|
||||
const door = ins.find((i) => (i.attribs as Record<string, string>).TYP === "Tür")!;
|
||||
expect(door.name).toBe("Tuer_90x210");
|
||||
expect(door.attribs).toMatchObject({ ID: "D1", BREITE_M: "0.90", HOEHE_M: "2.10", TYPENAME: expect.any(String) });
|
||||
expect(door.layer).toMatch(/^21_/); // Ebene der Kategorie „Türen/Fenster“
|
||||
expect(r.blocks[door.name as string].entities.LINE).toBeGreaterThan(0);
|
||||
const win = ins.find((i) => (i.attribs as Record<string, string>).TYP === "Fenster")!;
|
||||
expect(win.attribs).toMatchObject({ BRUESTUNG_M: "0.90" });
|
||||
});
|
||||
|
||||
it("Möbelblock: ein BLOCK je Definition, zwei INSERTs mit Drehung und Skalierung", () => {
|
||||
const r = read();
|
||||
const sofas = r.entities.filter((e) => e.type === "INSERT" && e.name === "Sofa");
|
||||
expect(sofas.length).toBe(2);
|
||||
expect(sofas[0].at).toEqual([1.5, 1]);
|
||||
expect(sofas[1].rotation as number).toBeCloseTo(90, 9);
|
||||
expect(sofas[1].scale).toEqual([1.5, 1.5]);
|
||||
expect(r.blocks.Sofa.entities).toEqual({ LINE: 5 }); // Rechteck = 4 Linien + 1 Linie, lokal
|
||||
// Geometrie lokal um den Einfügepunkt (Rechteck −0.9…0.9), nicht an der Weltlage
|
||||
const sofaLines = r.entities.filter((e) => e.type === "LINE" && Math.abs((e.pts as number[][])[0][0] - 1.5) < 1.0 && Math.abs((e.pts as number[][])[0][1] - 1) < 0.5 && e.layer.startsWith("90_"));
|
||||
expect(sofaLines.length).toBe(0); // keine losen Linien an der Weltlage
|
||||
});
|
||||
|
||||
it("Strichmuster → Linientyp mit dem Namen des Projekt-Linienstils (Papier-mm × Massstab)", () => {
|
||||
const r = read();
|
||||
const lt = r.linetypes["Strichlinie_0.3_0.1"];
|
||||
expect(lt).toBeDefined();
|
||||
expect(lt.map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.3, -0.1]); // 3 mm / 1 mm Papier bei 1:100
|
||||
const line = r.entities.find((e) => e.type === "LINE" && e.linetype === "Strichlinie_0.3_0.1");
|
||||
expect(line).toBeDefined();
|
||||
// 1:50 halbiert die Längen
|
||||
const r50 = read({ scaleDenominator: 50 });
|
||||
expect(r50.linetypes["Strichlinie_0.3_0.1"].map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.15, -0.05]);
|
||||
});
|
||||
|
||||
it("Textstile: Schriftname aus dem Projekt, Fallback Arial; Umlaute", () => {
|
||||
const r = read();
|
||||
expect(r.fonts.DOSSIER).toBe("Helvetica Neue");
|
||||
const text = r.entities.find((e) => e.type === "TEXT" && e.text === "Müller & Söhne")!;
|
||||
expect(text).toBeDefined();
|
||||
expect(text.style).toBe("DOSSIER");
|
||||
expect(text.halign).toBe(0);
|
||||
const noFont = ezdxf("cad2", buildPlanDxf(plan, { ...project, textStyles: [] }));
|
||||
expect(noFont.status, noFont.err).toBe(0);
|
||||
expect(noFont.r.fonts.DOSSIER).toBe("Arial");
|
||||
});
|
||||
|
||||
it("Raumstempel: Name und Fläche als zentrierte TEXTe im Massstab (Punkt → Meter)", () => {
|
||||
const r = read();
|
||||
const stamps = r.entities.filter((e) => e.type === "TEXT" && e.halign === 1);
|
||||
expect(stamps.length).toBeGreaterThan(0);
|
||||
const texts = stamps.map((e) => e.text as string);
|
||||
expect(texts.some((t) => /m²/.test(t))).toBe(true);
|
||||
for (const s of stamps) expect(s.height as number).toBeGreaterThan(0.2); // 10 pt bei 1:100 ≈ 0.35 m
|
||||
});
|
||||
|
||||
it("Papierbereich: Layout mit Ansichtsfenster im Planmassstab", () => {
|
||||
const r = read({ paperLayout: true });
|
||||
const name = Object.keys(r.layouts).find((n) => n.startsWith("Plan_1-100"))!;
|
||||
expect(name).toBeDefined();
|
||||
const vp = r.layouts[name].viewports.find((v) => v.id === 2)!;
|
||||
expect(vp).toBeDefined();
|
||||
const [pw, ph] = r.layouts[name].paper!;
|
||||
expect(vp.center[0]).toBeCloseTo(pw / 2, 6);
|
||||
// Ausschnitt in Metern = Fenstergrösse (mm) / 10 (1:100)
|
||||
expect(vp.view_height).toBeCloseTo(vp.size[1] / 10, 6);
|
||||
expect(ph).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("Binär-DXF trägt dieselben Objekte", () => {
|
||||
const asc = ezdxf("asc", buildPlanDxf(plan, project));
|
||||
const bin = ezdxf("bin", buildPlanDxfBinary(plan, project));
|
||||
expect(bin.r.errors).toEqual([]);
|
||||
expect(bin.status, bin.err).toBe(0);
|
||||
expect(bin.r.entities).toEqual(asc.r.entities);
|
||||
expect(Object.keys(bin.r.blocks)).toEqual(Object.keys(asc.r.blocks));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Fachplaner-Export: DWG (libredwg) und eigener Import", () => {
|
||||
const project = cadProject();
|
||||
const plan = generatePlan(project, "eg", allCodes(project));
|
||||
|
||||
it("DWG R2018: DIMENSION, INSERT, Blöcke und Umlaute kommen an", async () => {
|
||||
const db = (await libreDwgReader())(buildPlanDwg(plan, project, { paperLayout: true }));
|
||||
const counts = countByType(db.entities);
|
||||
expect(counts.DIMENSION).toBe(2);
|
||||
expect(counts.INSERT).toBeGreaterThanOrEqual(5);
|
||||
const text = db.entities.find((e) => e.type === "TEXT" && e.text?.startsWith("Müller"));
|
||||
expect(text?.text).toBe("Müller & Söhne");
|
||||
});
|
||||
|
||||
it("DXF-Import: Masszahlen, Möbelgeometrie und Türgeometrie kommen wieder an", () => {
|
||||
const imp = parseDxf(buildPlanDxf(plan, project));
|
||||
const texts = (imp.texts ?? []).map((t) => t.text);
|
||||
expect(texts).toContain("2.00");
|
||||
expect(texts).toContain("3.00");
|
||||
expect(texts).toContain("Müller & Söhne");
|
||||
// Möbel + Türen/Fenster sind als Geometrie vorhanden (Blöcke werden aufgelöst)
|
||||
const lineCount = imp.contours.reduce((n, c) => n + c.contours.length, 0);
|
||||
expect(lineCount).toBeGreaterThan(50);
|
||||
expect(imp.diagnostics?.entityCounts.DIMENSION ?? imp.diagnostics?.entityCounts.INSERT).toBeDefined();
|
||||
});
|
||||
|
||||
it("DXF-Import: Papierbereich wird als Layout erkannt", () => {
|
||||
// Das Layout hat nur ein Ansichtsfenster (kein eigener Inhalt) und steht darum nicht in der Liste, ist aber lesbar.
|
||||
const dxf = buildPlanDxf(plan, project, { paperLayout: true });
|
||||
expect(() => parseDxf(dxf, "", "Plan_1-100")).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -66,7 +66,11 @@ describe.skipIf(!hasEzdxf)("DXF-Export gegen ezdxf", { timeout: 60_000 }, () =>
|
||||
expect(r.status).toBe(0);
|
||||
expect(r.result!.version).toBe("AC1032");
|
||||
expect(r.result!.insunits).toBe(6);
|
||||
const polys = plan.primitives.filter((p): p is Extract<Plan["primitives"][number], { kind: "polygon" }> => p.kind === "polygon");
|
||||
// Ohne unsichtbare Pick-Bänder und ohne Öffnungs-Polygone (Fensterrahmen liegen im Block, nicht im Modellbereich).
|
||||
const polys = plan.primitives.filter(
|
||||
(p): p is Extract<Plan["primitives"][number], { kind: "polygon" }> =>
|
||||
p.kind === "polygon" && !p.openingId && !(p.stroke === "none" && p.fill === "none" && p.hatch.pattern === "none"),
|
||||
);
|
||||
const ezPolys = r.result!.entities.filter((e) => e.type === "LWPOLYLINE");
|
||||
expect(ezPolys.length).toBe(polys.length);
|
||||
for (let i = 0; i < polys.length; i++) {
|
||||
|
||||
@@ -21,32 +21,15 @@ import { projectToWorldCoords } from "../model/geoRebase";
|
||||
|
||||
const allCodes = (p: Project) => new Set(flattenCategories(p.layers).map((l) => l.code));
|
||||
|
||||
/** Was die flache Zeichnung an Entitäten trägt (Zählung je Typ, aus dem Puffer). */
|
||||
/** Was die flache Zeichnung an Entitäten im Modellbereich trägt (Zählung je Typ, im Sammler mitgeführt). */
|
||||
function flatCounts(plan: Plan, project: Project): Record<string, number> {
|
||||
const [flat] = collectPlanDrawing(plan, project).args();
|
||||
const names: Record<number, [string, (i: number) => number]> = {
|
||||
1: ["", () => 4],
|
||||
2: ["LINE", () => 6],
|
||||
3: ["LWPOLYLINE", (i) => 4 + 2 * flat[i + 3]],
|
||||
4: ["ARC", () => 7],
|
||||
5: ["CIRCLE", () => 5],
|
||||
6: ["TEXT", () => 7],
|
||||
// HATCH: tag, layer, mode, rgb, n_dash, dash…, n_fam, (angle, spacing)…, n, pts…
|
||||
7: ["HATCH", (i) => {
|
||||
const nd = flat[i + 4];
|
||||
const nf = flat[i + 5 + nd];
|
||||
return 5 + nd + 1 + 2 * nf + 1 + 2 * flat[i + 5 + nd + 1 + 2 * nf];
|
||||
}],
|
||||
};
|
||||
const out: Record<string, number> = {};
|
||||
for (let i = 1; i < flat.length; ) {
|
||||
const [name, len] = names[flat[i]];
|
||||
if (name) out[name] = (out[name] ?? 0) + 1;
|
||||
i += len(i);
|
||||
}
|
||||
return out;
|
||||
return collectPlanDrawing(plan, project).stats().model;
|
||||
}
|
||||
|
||||
/** Polygone, die der Export schreibt: unsichtbare Pick-Bänder (weder Füllung noch Umriss noch Schraffur) entfallen. */
|
||||
const visiblePolys = (polys: Extract<Plan["primitives"][number], { kind: "polygon" }>[]) =>
|
||||
polys.filter((p) => !p.openingId && !(p.stroke === "none" && p.fill === "none" && p.hatch.pattern === "none" && p.hatch.kind !== "gradient"));
|
||||
|
||||
describe("DXF-Export (R2018 über acadrust)", () => {
|
||||
const plan = generatePlan(sampleProject, "eg", allCodes(sampleProject));
|
||||
|
||||
@@ -66,7 +49,11 @@ describe("DXF-Export (R2018 über acadrust)", () => {
|
||||
|
||||
it("jede übergebene Entität kommt an (Typ, Anzahl, Reihenfolge der Ebenen)", () => {
|
||||
const dxf = readDxf(buildPlanDxf(plan, sampleProject));
|
||||
expect(countByType(dxf.entities)).toEqual(flatCounts(plan, sampleProject));
|
||||
// ATTRIB/SEQEND hängen an den INSERTs (Türen/Fenster) und zählen nicht als eigene Entitäten des Plans.
|
||||
const { ATTRIB, SEQEND, ...entities } = countByType(dxf.entities);
|
||||
expect(ATTRIB ?? 0).toBeGreaterThanOrEqual(entities.INSERT ?? 0); // jede Tür/jedes Fenster trägt Attribute
|
||||
expect(SEQEND ?? 0).toBe(entities.INSERT ?? 0);
|
||||
expect(entities).toEqual(flatCounts(plan, sampleProject));
|
||||
expect(dxf.entities.every((e) => dxf.layers.has(e.layer))).toBe(true);
|
||||
});
|
||||
|
||||
@@ -104,7 +91,7 @@ describe("Georeferenz (LV95)", () => {
|
||||
};
|
||||
const world = projectToWorldCoords(anchored);
|
||||
const plan = generatePlan(world, "eg", allCodes(world));
|
||||
const polys = plan.primitives.filter((p): p is Extract<Plan["primitives"][number], { kind: "polygon" }> => p.kind === "polygon");
|
||||
const polys = visiblePolys(plan.primitives.filter((p): p is Extract<Plan["primitives"][number], { kind: "polygon" }> => p.kind === "polygon"));
|
||||
|
||||
it("DXF: Polylinien-Koordinaten bitgleich zum Plan (f64, keine Rundung)", () => {
|
||||
const ents = readDxf(buildPlanDxf(plan, world)).entities.filter((e) => e.type === "LWPOLYLINE");
|
||||
|
||||
+591
-26
@@ -14,13 +14,29 @@
|
||||
// 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`/
|
||||
// `buildPlanDwg` einmal `await loadFileio()` (savePlanDxf und die CLI tun das).
|
||||
//
|
||||
// Fachplaner-Export (28.10., [C2]): damit in AutoCAD/BricsCAD weitergearbeitet werden kann, entstehen
|
||||
// statt loser Linien dort, wo das Modell die Information trägt, CAD-Objekte:
|
||||
// - Bemassungen (`Drawing2D {shape:"dimension"}`) → je Segment eine DIMENSION samt Anonymblock `*D…` und
|
||||
// Bemassungsstil (DIMSTYLE: Texthöhe/Strich/Abstände in Papier-mm, DIMSCALE = Massstab);
|
||||
// - Türen/Fenster (Primitive mit `openingId`) → BLOCK + INSERT in der Wandrichtung, gleiche Geometrie
|
||||
// teilt sich einen Block, ATTRIBs (Breite, Höhe, Typ, ID);
|
||||
// - Blockinstanzen (`Drawing2D {shape:"block"}`, Möbel/Symbole/Nordpfeil) → BLOCK je Definition + INSERT;
|
||||
// - Strichmuster → Linientypen (Name des Projekt-Linienstils), Texte → Textstile mit Schriftname und
|
||||
// Ausrichtung (Raumstempel mit Fläche als TEXT, links/Mitte/rechts), optional Papierbereich.
|
||||
// Alles andere (Wände, Umrisse, Schraffuren) bleibt wie bisher Linie/Polylinie/HATCH.
|
||||
|
||||
import type { Plan, Primitive } from "../plan/generatePlan";
|
||||
import type { LayerCategory, Project, Vec2 } from "../model/types";
|
||||
import type { Drawing2D, LayerCategory, Opening, Project, Vec2 } 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 { 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";
|
||||
|
||||
export interface ExportDxfOptions {
|
||||
/** Titel/Geschossname (nur als Kommentar-freundlicher Dateiname genutzt). */
|
||||
@@ -29,6 +45,16 @@ export interface ExportDxfOptions {
|
||||
includeHatches?: boolean;
|
||||
/** Dateiname des Downloads (mit/ohne Endung). */
|
||||
fileName?: string;
|
||||
/**
|
||||
* Massstabsnenner (100 = 1:100): macht aus Papier-Millimetern Modell-Meter — Texthöhe/Striche der
|
||||
* Bemassung, Strichmuster der Linientypen, Schriftgrösse der Raumstempel, Massstab des Ansichtsfensters.
|
||||
* Default 1:100 (wie `generatePlan`).
|
||||
*/
|
||||
scaleDenominator?: number;
|
||||
/** Einheit der Masszahl: Meter (Default, wie im Plan „3.25") oder Zentimeter („325"). */
|
||||
dimUnit?: "m" | "cm";
|
||||
/** Zusätzlich ein Layout (Papierbereich) mit Ansichtsfenster im Planmassstab anlegen. */
|
||||
paperLayout?: boolean;
|
||||
}
|
||||
|
||||
/** Ausgabeformat des Modell-Space-Exports. */
|
||||
@@ -44,10 +70,14 @@ 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) ─────────
|
||||
|
||||
@@ -60,60 +90,180 @@ 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<string, number>;
|
||||
layers: Map<string, number>;
|
||||
ltypes: Map<string, number>;
|
||||
styles: Map<string, number>;
|
||||
dimStyles: Map<string, number>;
|
||||
blocks: Set<string>;
|
||||
/** Entitäten in Blockdefinitionen (Zählung für Tests). */
|
||||
blockCounts: Record<string, number>;
|
||||
}
|
||||
|
||||
/** 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 nums: number[] = [FLAT_VERSION];
|
||||
private strings: string[] = [];
|
||||
private layers = new Map<string, number>();
|
||||
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<string, number> = {};
|
||||
|
||||
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 {
|
||||
this.strings.push(s.replace(/\0/g, ""));
|
||||
return this.strings.length - 1;
|
||||
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;
|
||||
}
|
||||
|
||||
/** Anzahl Entitäten im Modellbereich je Typ (INSERT/DIMENSION zählen je als eine) und in Blöcken (Summe je Typ). */
|
||||
stats(): { model: Record<string, number>; blocks: Record<string, number> } {
|
||||
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.layers.get(name);
|
||||
const known = this.sh.layers.get(name);
|
||||
if (known !== undefined) return known;
|
||||
const idx = this.layers.size;
|
||||
this.layers.set(name, idx);
|
||||
this.nums.push(REC_LAYER, this.str(name), rgb ?? -1, lineWeight);
|
||||
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.layers.get(name) ?? this.addLayer(name, null, 25);
|
||||
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
|
||||
@@ -126,6 +276,7 @@ export class FlatDrawing {
|
||||
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);
|
||||
@@ -141,16 +292,117 @@ export class FlatDrawing {
|
||||
*/
|
||||
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.strings.join("\0")];
|
||||
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<string, string>;
|
||||
/** Kategorie-Code je Zeichen-Element / Raum (für Ebenen). */
|
||||
codeByDrawing: Map<string, string>;
|
||||
codeByRoom: Map<string, string>;
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/** Eine Zeile einer (Rich-)Text-Ausgabe. */
|
||||
interface OutLine {
|
||||
text: string;
|
||||
/** Schrifthöhe (Meter). */
|
||||
height: number;
|
||||
align: 0 | 1 | 2;
|
||||
marks?: Marks;
|
||||
/** Versatz der Grundlinie vom Anker nach unten (Meter, ≥ 0 für spätere Zeilen). */
|
||||
down: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut aus einem Plan + Projekt die flache Zeichnung (Meter-Modell-Space).
|
||||
* Reihenfolge der Primitive bleibt erhalten.
|
||||
@@ -161,6 +413,7 @@ export function collectPlanDrawing(
|
||||
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,
|
||||
@@ -177,8 +430,10 @@ export function collectPlanDrawing(
|
||||
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-
|
||||
@@ -189,6 +444,8 @@ export function collectPlanDrawing(
|
||||
for (const d of project.drawings2d) codeByDrawing.set(d.id, d.categoryCode);
|
||||
const codeByColumn = new Map<string, string>();
|
||||
for (const c of project.columns ?? []) codeByColumn.set(c.id, c.categoryCode);
|
||||
const codeByRoom = new Map<string, string>();
|
||||
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;
|
||||
|
||||
@@ -202,22 +459,250 @@ export function collectPlanDrawing(
|
||||
}
|
||||
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;
|
||||
};
|
||||
|
||||
// 3) Jedes Primitiv in Entities übersetzen.
|
||||
for (const p of plan.primitives) {
|
||||
emitPrimitive(dxf, p, layerFor(p), includeHatches);
|
||||
// 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<string, Drawing2D>();
|
||||
const blockById = new Map<string, Drawing2D>();
|
||||
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<string, Opening>();
|
||||
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<string, Primitive[]>();
|
||||
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<string>();
|
||||
|
||||
// 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<string, string>();
|
||||
private used = new Set<string>();
|
||||
/** 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 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut aus einem Plan + Projekt einen vollständigen DXF-String (R2018 ASCII, Meter-Modell-Space).
|
||||
* Verlangt das geladene Format-Modul (`await loadFileio()`).
|
||||
@@ -270,13 +755,70 @@ function layerName(c: LayerCategory): string {
|
||||
return `${c.code}_${c.name}`;
|
||||
}
|
||||
|
||||
/** Schreibt ein Plan-Primitiv als passende Entity(en). */
|
||||
/** 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<Primitive, { kind: "text" }>, scale: number): OutLine[] {
|
||||
const unitPerPt = (0.0254 / 72) * scale; // 1 pt Papier in Modell-Metern
|
||||
const baseFs = p.basePt * unitPerPt;
|
||||
const lineGap = baseFs * 1.3;
|
||||
const docLines = docToLines(p.doc, { x: 0, y: 0, lineHeight: lineGap, unitPerPt, basePt: p.basePt, color: p.color });
|
||||
const lines = [
|
||||
...docLines.map((l) => ({ align: l.align, lineHeight: l.lineHeight, ts: l.tspans })),
|
||||
...p.extraLines.map((l) => ({ align: l.align, lineHeight: lineGap, ts: [{ text: l.text, fontSize: baseFs * 0.8, fontFamily: undefined as string | undefined, fontWeight: undefined as string | undefined, fontStyle: undefined as string | undefined }] })),
|
||||
];
|
||||
if (lines.length === 0) return [];
|
||||
const totalH = baseFs + lines.slice(1).reduce((s, l) => s + l.lineHeight, 0);
|
||||
let down = -totalH / 2 + baseFs * 0.8;
|
||||
const out: OutLine[] = [];
|
||||
lines.forEach((l, k) => {
|
||||
if (k > 0) down += l.lineHeight;
|
||||
const text = l.ts.map((t) => t.text).join("");
|
||||
const first = l.ts[0];
|
||||
if (!text.trim() || !first) return;
|
||||
out.push({
|
||||
text,
|
||||
height: Math.max(...l.ts.map((t) => t.fontSize)),
|
||||
align: l.align === "center" ? 1 : l.align === "right" ? 2 : 0,
|
||||
marks: { font: first.fontFamily, bold: first.fontWeight === "700", italic: first.fontStyle === "italic" },
|
||||
down,
|
||||
});
|
||||
});
|
||||
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<Primitive, { kind: "drawingText" }>): 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,
|
||||
includeHatches: boolean,
|
||||
hatchLayer: string,
|
||||
): void {
|
||||
const includeHatches = ctx.includeHatches;
|
||||
switch (p.kind) {
|
||||
case "line":
|
||||
if (p.zigzag) {
|
||||
@@ -284,40 +826,61 @@ function emitPrimitive(
|
||||
// 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 (neu mit [C2]; der alte Writer liess Texte weg): einzeiliger TEXT,
|
||||
// Ankerpunkt = Einfügepunkt, Absätze eines Rich-Text-Felds mit Leerzeichen verbunden.
|
||||
// 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 value = p.doc ? plainText(p.doc) : p.text;
|
||||
if (value.trim() && p.heightM > 0) dxf.addText(layer, p.at, p.heightM, p.angle, value);
|
||||
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")
|
||||
@@ -331,33 +894,35 @@ function emitPrimitive(
|
||||
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(LAYER_HATCH, pts, { rgb1, rgb2, angle: (g.angle * Math.PI) / 180, radial: g.type === "radial" });
|
||||
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(LAYER_HATCH, pts, { solid: true, rgb: rgbOrNull(h.color) });
|
||||
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(LAYER_HATCH, d.a, d.b);
|
||||
for (const d of dashSeg(seg, cycle)) dxf.addLine(hatchLayer, d.a, d.b);
|
||||
} else {
|
||||
dxf.addLine(LAYER_HATCH, seg.a, seg.b);
|
||||
dxf.addLine(hatchLayer, seg.a, seg.b);
|
||||
}
|
||||
}
|
||||
} else if (h.pattern !== "none") {
|
||||
const families = hatchFamilies(h);
|
||||
if (families.length > 0) {
|
||||
dxf.addHatch(LAYER_HATCH, pts, { solid: false, rgb: rgbOrNull(h.color), families, dashes: dashCycleMeters(h.dash) ?? [] });
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1736,6 +1736,15 @@ export const de = {
|
||||
"exportDxf.failed": "Export fehlgeschlagen",
|
||||
"exportDxf.unitsNote":
|
||||
"Modell-Space in Metern (1:1). Layer entsprechen den Ebenen des Projekts; beim Plot beliebig skalierbar.",
|
||||
"exportDxf.scale": "Massstab (Bemassung, Strichmuster, Beschriftung)",
|
||||
"exportDxf.dimUnit": "Masszahlen in",
|
||||
"exportDxf.dimUnit.m": "Meter (3.25)",
|
||||
"exportDxf.dimUnit.cm": "Zentimeter (325)",
|
||||
"exportDxf.layout": "Papierbereich",
|
||||
"exportDxf.layout.no": "Nur Modellbereich",
|
||||
"exportDxf.layout.yes": "Zusätzlich Layout mit Ansichtsfenster im Massstab",
|
||||
"exportDxf.objectsNote":
|
||||
"Bemassungen als DIMENSION (mit Bemassungsstil), Türen, Fenster und Möbelblöcke als BLOCK/INSERT mit Attributen, Strichmuster als Linientypen, Texte mit Textstil.",
|
||||
|
||||
// ── Datei-Menü (Burger, ganz rechts der Oberleiste) ──────────────────────
|
||||
"file.menu": "Datei",
|
||||
|
||||
@@ -1724,6 +1724,15 @@ export const en: Record<TranslationKey, string> = {
|
||||
"exportDxf.failed": "Export failed",
|
||||
"exportDxf.unitsNote":
|
||||
"Model space in meters (1:1). Layers mirror the project's categories; scale freely on plot.",
|
||||
"exportDxf.scale": "Scale (dimensions, dash patterns, labels)",
|
||||
"exportDxf.dimUnit": "Dimension values in",
|
||||
"exportDxf.dimUnit.m": "Meters (3.25)",
|
||||
"exportDxf.dimUnit.cm": "Centimeters (325)",
|
||||
"exportDxf.layout": "Paper space",
|
||||
"exportDxf.layout.no": "Model space only",
|
||||
"exportDxf.layout.yes": "Add a layout with a viewport at the scale",
|
||||
"exportDxf.objectsNote":
|
||||
"Dimensions as DIMENSION entities (with dimension style), doors, windows and furniture blocks as BLOCK/INSERT with attributes, dash patterns as linetypes, text with text styles.",
|
||||
|
||||
// File menu (burger, far right of the top bar).
|
||||
"file.menu": "File",
|
||||
|
||||
@@ -125,7 +125,7 @@ export function useExportHandlers(opts: {
|
||||
referenceLines,
|
||||
planColorMode === "mono",
|
||||
true, // includeGlobal (Default)
|
||||
undefined, // scaleDenominator (Default)
|
||||
decision.scaleDenominator, // Export-Massstab (wie PDF): Strichstärken, Bemassung
|
||||
true, // forPrint: `Drawing2D.noPrint`-Elemente ausschliessen
|
||||
);
|
||||
try {
|
||||
@@ -133,6 +133,9 @@ export function useExportHandlers(opts: {
|
||||
title: activeLevelName,
|
||||
includeHatches: decision.includeHatches,
|
||||
format: decision.format,
|
||||
scaleDenominator: decision.scaleDenominator,
|
||||
dimUnit: decision.dimUnit,
|
||||
paperLayout: decision.paperLayout,
|
||||
fileName: `${project.name}-${activeLevelName}`,
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n";
|
||||
import { Dropdown } from "./Dropdown";
|
||||
import type { CadExportFormat } from "../export/exportDxf";
|
||||
import { SCALE_PRESETS } from "./TopBar";
|
||||
|
||||
/** Entscheidung, die der Dialog beim Bestätigen liefert. */
|
||||
export interface ExportDxfDecision {
|
||||
@@ -18,6 +19,12 @@ export interface ExportDxfDecision {
|
||||
includeHatches: boolean;
|
||||
/** „nur Auswahl" statt des ganzen Plans (nur relevant, wenn `selectionCount > 0`). */
|
||||
selectionOnly: boolean;
|
||||
/** Massstabsnenner für Bemassungsstil, Strichmuster, Raumstempel und Ansichtsfenster. */
|
||||
scaleDenominator: number;
|
||||
/** Einheit der Masszahlen. */
|
||||
dimUnit: "m" | "cm";
|
||||
/** Zusätzlich ein Layout (Papierbereich) mit Ansichtsfenster anlegen. */
|
||||
paperLayout: boolean;
|
||||
}
|
||||
|
||||
export interface ExportDxfDialogProps {
|
||||
@@ -25,6 +32,8 @@ export interface ExportDxfDialogProps {
|
||||
planTitle: string;
|
||||
/** s. `ExportPdfDialogProps.selectionCount`. */
|
||||
selectionCount?: number;
|
||||
/** Massstab der aktiven Ansicht (Vorgabe, Default 1:100). */
|
||||
initialScale?: number;
|
||||
onExport: (decision: ExportDxfDecision) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
@@ -32,6 +41,7 @@ export interface ExportDxfDialogProps {
|
||||
export function ExportDxfDialog({
|
||||
planTitle,
|
||||
selectionCount = 0,
|
||||
initialScale = 100,
|
||||
onExport,
|
||||
onClose,
|
||||
}: ExportDxfDialogProps) {
|
||||
@@ -46,9 +56,24 @@ export function ExportDxfDialog({
|
||||
const [format, setFormat] = useState<CadExportFormat>("dxf");
|
||||
const [includeHatches, setIncludeHatches] = useState(true);
|
||||
const [selectionOnly, setSelectionOnly] = useState(false);
|
||||
const [scale, setScale] = useState<number>(initialScale);
|
||||
const [dimUnit, setDimUnit] = useState<"m" | "cm">("m");
|
||||
const [paperLayout, setPaperLayout] = useState(false);
|
||||
|
||||
const scaleOptions = [
|
||||
...(SCALE_PRESETS.includes(scale) ? [] : [{ value: String(scale), label: `1:${scale}` }]),
|
||||
...SCALE_PRESETS.filter((n) => n > 1).map((n) => ({ value: String(n), label: `1:${n}` })),
|
||||
];
|
||||
|
||||
const onConfirm = () =>
|
||||
onExport({ format, includeHatches, selectionOnly: selectionCount > 0 && selectionOnly });
|
||||
onExport({
|
||||
format,
|
||||
includeHatches,
|
||||
selectionOnly: selectionCount > 0 && selectionOnly,
|
||||
scaleDenominator: scale,
|
||||
dimUnit,
|
||||
paperLayout,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="imp-overlay" onClick={onClose}>
|
||||
@@ -101,7 +126,39 @@ export function ExportDxfDialog({
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="imp-section">
|
||||
<div className="imp-section-title">{t("exportDxf.scale")}</div>
|
||||
<Dropdown value={String(scale)} onChange={(v) => setScale(Number(v))} title={t("exportDxf.scale")} options={scaleOptions} />
|
||||
</section>
|
||||
|
||||
<section className="imp-section">
|
||||
<div className="imp-section-title">{t("exportDxf.dimUnit")}</div>
|
||||
<Dropdown
|
||||
value={dimUnit}
|
||||
onChange={(v) => setDimUnit(v === "cm" ? "cm" : "m")}
|
||||
title={t("exportDxf.dimUnit")}
|
||||
options={[
|
||||
{ value: "m", label: t("exportDxf.dimUnit.m") },
|
||||
{ value: "cm", label: t("exportDxf.dimUnit.cm") },
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="imp-section">
|
||||
<div className="imp-section-title">{t("exportDxf.layout")}</div>
|
||||
<Dropdown
|
||||
value={paperLayout ? "yes" : "no"}
|
||||
onChange={(v) => setPaperLayout(v === "yes")}
|
||||
title={t("exportDxf.layout")}
|
||||
options={[
|
||||
{ value: "no", label: t("exportDxf.layout.no") },
|
||||
{ value: "yes", label: t("exportDxf.layout.yes") },
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<div className="imp-note">{t("exportDxf.unitsNote")}</div>
|
||||
<div className="imp-note">{t("exportDxf.objectsNote")}</div>
|
||||
|
||||
{selectionCount > 0 && (
|
||||
<section className="imp-section">
|
||||
|
||||
Reference in new issue
Block a user