/** * Vector drawings (SVG, as the CorelDRAW viewer draws its pages) to DXF for * laser cutters, vinyl cutters, CNC routers and CAD. * * Every outline becomes a polyline: straight runs stay exact, curves (cubic, * quadratic and elliptical arcs) are flattened finely enough that no point is * more than a hundredth of a millimetre off the true curve. Each element's * full transform comes from the browser (getCTM), so groups, rotations and * scaling land where the drawing shows them. DXF's y axis points up, so the * page is flipped. Polylines go on one layer per colour (the outline's, else * the fill's), named after it, because laser and cutter software assigns cut, * score and engrave settings by colour or layer. Text elements and pictures * are left out: a cutter needs outlines (the CorelDRAW viewer turns text into * outline paths first, revenge/text-outlines.ts). * * The file is AutoCAD R12 ASCII DXF, the version every cutter and CAD program * reads, in millimetres ($INSUNITS 4). A caller that has text as text (the * DWG viewer's R12 copy) can add it as R12 TEXT entities (DxfText). */ export type Pt = [number, number]; /** A 2D affine matrix as SVG writes it: x' = a x + c y + e, y' = b x + d y + f. */ export interface Matrix { a: number; b: number; c: number; d: number; e: number; f: number; } export interface Outline { points: Pt[]; closed: boolean; color: string; /** Its DXF layer's name, when not the colour's (letters, digits, - and _ only). */ layer?: string; } /** A line of text as an R12 TEXT entity: where it stands, in the drawing's own units, how tall, turned how far. */ export interface DxfText { text: string; x: number; y: number; /** Letter height (the capitals' height), drawing units. */ height: number; /** Degrees anticlockwise. */ rotation: number; /** Letters wider (over 1) or narrower than the font draws them. */ widthFactor?: number; align: 'left' | 'center' | 'right'; /** Which part of the text the point is on: the baseline, the bottom of the descenders, the middle, or the top. */ valign: 'baseline' | 'bottom' | 'middle' | 'top'; /** Written backwards (mirrored left to right). */ mirrored?: boolean; color: string; layer?: string; } /** The most characters an R12 TEXT string may hold here (AutoCAD R12 takes 256). */ export const DXF_TEXT_MAX = 250; /** * A text string as R12 DXF holds it, and whether it had to be cut: one * line, plain ASCII, with every other character as AutoCAD's \U+XXXX escape * (which AutoCAD, BricsCAD, LibreCAD and QCAD read) and control characters * left out. AutoCAD reads %% as the start of a code (%%d is a degree sign) * and %%% as a percent sign, so in text holding %% every % is written as * %%%. Cut at whole characters (an escape is never split) to DXF_TEXT_MAX. */ export function dxfText(s: string): { text: string; cut: boolean } { const pct = s.includes('%%'); let out = ''; let cut = false; for (const ch of s.replace(/[\r\n]+/g, ' ')) { const c = ch.codePointAt(0)!; if (c < 32 || c === 127) continue; const piece = c === 37 && pct ? '%%%' : c < 127 ? ch : c <= 0xffff ? `\\U+${c.toString(16).toUpperCase().padStart(4, '0')}` : '?'; // Past the Basic Multilingual Plane (emoji) there is no escape R12 readers know: '?' above. if (out.length + piece.length > DXF_TEXT_MAX) { cut = true; break; } out += piece; } return { text: out, cut }; } export function dxfTextString(s: string): string { return dxfText(s).text; } /** How far a flattened curve may stray from the true one, in the drawing's own units. */ const DEFAULT_TOLERANCE = 0.01; /* ── Path data ─────────────────────────────────────────────────────────── */ /** Splits SVG path data into commands with their numbers ("M10 20l5-5" -> [["M",10,20],["l",5,-5]]). */ export function tokenize(d: string): (string | number)[][] { const out: (string | number)[][] = []; const re = /([MmLlHhVvCcSsQqTtAaZz])|(-?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?)/g; let m: RegExpExecArray | null; let cur: (string | number)[] | null = null; while ((m = re.exec(d))) { if (m[1]) { cur = [m[1]]; out.push(cur); } else if (cur) cur.push(parseFloat(m[2])); } return out; } /** Arc flags may be written run together ("a1 1 0 011 1"): re-split them before reading numbers. */ export function arcArgs(d: string): string { return d.replace(/([Aa])([^MmLlHhVvCcSsQqTtAaZz]*)/g, (_, cmd: string, body: string) => { const nums: string[] = []; const re = /-?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g; let m: RegExpExecArray | null; let i = 0; while ((m = re.exec(body))) { const k = i % 7; // Flags (the 4th and 5th numbers of each arc) are single digits that may be glued to what follows. if ((k === 3 || k === 4) && m[0].length > 1 && /^[01]/.test(m[0])) { nums.push(m[0][0]); re.lastIndex = m.index + 1; } else nums.push(m[0]); i++; } return cmd + ' ' + nums.join(' ') + ' '; }); } function dist(a: Pt, b: Pt): number { return Math.hypot(a[0] - b[0], a[1] - b[1]); } function finite(p: Pt): boolean { return Number.isFinite(p[0]) && Number.isFinite(p[1]); } /** * The most points one export makes from curves. Far beyond any real drawing; * stops coordinates like 1e300 (every curve split 18 deep, 262,144 points * each) from filling memory. Past it, curves become straight lines. */ export const MAX_POINTS = 2_000_000; export interface PointBudget { left: number; } /** Flattens a cubic Bézier into points after p0 (p0 itself is not repeated), by recursive subdivision. */ export function flattenCubic(p0: Pt, p1: Pt, p2: Pt, p3: Pt, tol: number, out: Pt[], depth = 0): void { // A curve with an infinite or NaN point never comes out flat: every branch would go 18 deep. if (depth === 0 && !(finite(p0) && finite(p1) && finite(p2) && finite(p3))) { if (finite(p3)) out.push(p3); return; } // Flat enough when both control points lie within the tolerance of the chord. const dx = p3[0] - p0[0]; const dy = p3[1] - p0[1]; const len = Math.hypot(dx, dy); const d1 = len > 1e-12 ? Math.abs((p1[0] - p3[0]) * dy - (p1[1] - p3[1]) * dx) / len : dist(p1, p0); const d2 = len > 1e-12 ? Math.abs((p2[0] - p3[0]) * dy - (p2[1] - p3[1]) * dx) / len : dist(p2, p0); if (depth >= 18 || Math.max(d1, d2) <= tol) { out.push(p3); return; } const m = (a: Pt, b: Pt): Pt => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]; const p01 = m(p0, p1), p12 = m(p1, p2), p23 = m(p2, p3); const p012 = m(p01, p12), p123 = m(p12, p23); const mid = m(p012, p123); flattenCubic(p0, p01, p012, mid, tol, out, depth + 1); flattenCubic(mid, p123, p23, p3, tol, out, depth + 1); } /** An SVG elliptical arc as cubic Béziers (each covering at most 45°), per the SVG spec's endpoint-to-centre conversion. */ export function arcToCubics(p0: Pt, rx: number, ry: number, rotDeg: number, large: boolean, sweep: boolean, p1: Pt): [Pt, Pt, Pt][] { if (dist(p0, p1) < 1e-12) return []; rx = Math.abs(rx); ry = Math.abs(ry); if (rx < 1e-12 || ry < 1e-12) return [[p0, p1, p1]]; const phi = (rotDeg * Math.PI) / 180; const cos = Math.cos(phi), sin = Math.sin(phi); const dx = (p0[0] - p1[0]) / 2, dy = (p0[1] - p1[1]) / 2; const x1 = cos * dx + sin * dy; const y1 = -sin * dx + cos * dy; const lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry); if (lambda > 1) { rx *= Math.sqrt(lambda); ry *= Math.sqrt(lambda); } const num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1; const den = rx * rx * y1 * y1 + ry * ry * x1 * x1; let k = Math.sqrt(Math.max(0, num / den)); if (large === sweep) k = -k; const cx1 = (k * rx * y1) / ry; const cy1 = (-k * ry * x1) / rx; const cx = cos * cx1 - sin * cy1 + (p0[0] + p1[0]) / 2; const cy = sin * cx1 + cos * cy1 + (p0[1] + p1[1]) / 2; const angle = (ux: number, uy: number, vx: number, vy: number) => { const a = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy); return a; }; const t1 = angle(1, 0, (x1 - cx1) / rx, (y1 - cy1) / ry); let dt = angle((x1 - cx1) / rx, (y1 - cy1) / ry, (-x1 - cx1) / rx, (-y1 - cy1) / ry); if (!sweep && dt > 0) dt -= 2 * Math.PI; if (sweep && dt < 0) dt += 2 * Math.PI; // 45° per cubic: a cubic strays at most about 4e-6 of the radius from such an arc (a 90° one, 2.7e-4). const n = Math.max(1, Math.ceil(Math.abs(dt) / (Math.PI / 4) - 1e-9)); const step = dt / n; const alpha = (4 / 3) * Math.tan(step / 4); const pt = (t: number): Pt => [cx + rx * Math.cos(t) * cos - ry * Math.sin(t) * sin, cy + rx * Math.cos(t) * sin + ry * Math.sin(t) * cos]; const der = (t: number): Pt => [-rx * Math.sin(t) * cos - ry * Math.cos(t) * sin, -rx * Math.sin(t) * sin + ry * Math.cos(t) * cos]; const out: [Pt, Pt, Pt][] = []; for (let i = 0; i < n; i++) { const a = t1 + i * step, b = a + step; const pa = pt(a), pb = i === n - 1 ? p1 : pt(b); const da = der(a), db = der(b); out.push([[pa[0] + alpha * da[0], pa[1] + alpha * da[1]], [pb[0] - alpha * db[0], pb[1] - alpha * db[1]], pb]); } return out; } /** * Path data to polylines in the path's own coordinates: one per subpath, * closed when it ends with Z (or comes back to where it started). */ export function pathToPolylines(d: string, tol = DEFAULT_TOLERANCE, budget: PointBudget = { left: MAX_POINTS }): { points: Pt[]; closed: boolean }[] { const out: { points: Pt[]; closed: boolean }[] = []; let pts: Pt[] = []; let cur: Pt = [0, 0]; let start: Pt = [0, 0]; let lastCtrl: Pt | null = null; let lastQuad: Pt | null = null; const finish = (closed: boolean) => { // Points that are not numbers (1e999 in the path data) have no place in a DXF. pts = pts.filter(finite); if (pts.length > 1) { // A subpath that returns to its start is closed even without Z. const back = dist(pts[0], pts[pts.length - 1]) < tol / 10; if (back && pts.length > 2) pts.pop(); out.push({ points: pts, closed: closed || back }); } pts = []; }; const cubic = (c1: Pt, c2: Pt, p: Pt) => { if (!pts.length) pts.push(cur); const before = pts.length; if (budget.left > 0) flattenCubic(cur, c1, c2, p, tol, pts); else pts.push(p); budget.left -= pts.length - before; cur = p; }; for (const cmd of tokenize(arcArgs(d))) { const c = cmd[0] as string; const n = cmd.slice(1) as number[]; const rel = c === c.toLowerCase() && c !== 'z' ? true : false; const C = c.toUpperCase(); const abs = (x: number, y: number): Pt => (rel ? [cur[0] + x, cur[1] + y] : [x, y]); if (C === 'Z') { finish(true); cur = start; lastCtrl = lastQuad = null; continue; } if (C === 'M') { for (let i = 0; i + 1 < n.length; i += 2) { const p = abs(n[i], n[i + 1]); if (i === 0) { finish(false); start = p; pts = [p]; } else pts.push(p); cur = p; } lastCtrl = lastQuad = null; continue; } if (!pts.length) pts = [cur]; if (C === 'L') { for (let i = 0; i + 1 < n.length; i += 2) pts.push((cur = abs(n[i], n[i + 1]))); lastCtrl = lastQuad = null; } else if (C === 'H') { for (const x of n) pts.push((cur = [rel ? cur[0] + x : x, cur[1]])); lastCtrl = lastQuad = null; } else if (C === 'V') { for (const y of n) pts.push((cur = [cur[0], rel ? cur[1] + y : y])); lastCtrl = lastQuad = null; } else if (C === 'C') { for (let i = 0; i + 5 < n.length; i += 6) { const c1 = abs(n[i], n[i + 1]), c2 = abs(n[i + 2], n[i + 3]), p = abs(n[i + 4], n[i + 5]); cubic(c1, c2, p); lastCtrl = c2; } lastQuad = null; } else if (C === 'S') { for (let i = 0; i + 3 < n.length; i += 4) { const c1: Pt = lastCtrl ? [2 * cur[0] - lastCtrl[0], 2 * cur[1] - lastCtrl[1]] : cur; const c2 = abs(n[i], n[i + 1]), p = abs(n[i + 2], n[i + 3]); cubic(c1, c2, p); lastCtrl = c2; } lastQuad = null; } else if (C === 'Q' || C === 'T') { const stepN = C === 'Q' ? 4 : 2; for (let i = 0; i + stepN - 1 < n.length; i += stepN) { const q: Pt = C === 'Q' ? abs(n[i], n[i + 1]) : lastQuad ? [2 * cur[0] - lastQuad[0], 2 * cur[1] - lastQuad[1]] : cur; const p = C === 'Q' ? abs(n[i + 2], n[i + 3]) : abs(n[i], n[i + 1]); const c1: Pt = [cur[0] + (2 / 3) * (q[0] - cur[0]), cur[1] + (2 / 3) * (q[1] - cur[1])]; const c2: Pt = [p[0] + (2 / 3) * (q[0] - p[0]), p[1] + (2 / 3) * (q[1] - p[1])]; cubic(c1, c2, p); lastQuad = q; } lastCtrl = null; } else if (C === 'A') { for (let i = 0; i + 6 < n.length; i += 7) { const p = abs(n[i + 5], n[i + 6]); for (const [c1, c2, e] of arcToCubics(cur, n[i], n[i + 1], n[i + 2], !!n[i + 3], !!n[i + 4], p)) cubic(c1, c2, e); cur = p; } lastCtrl = lastQuad = null; } } finish(false); return out; } /* ── The SVG, read through the browser ─────────────────────────────────── */ const SHAPES = 'path, rect, circle, ellipse, line, polyline, polygon'; /** An element's outline as path data, in its own coordinates. */ function shapePath(el: SVGGraphicsElement): string { const n = (name: string) => parseFloat(el.getAttribute(name) || '0') || 0; switch (el.tagName.toLowerCase()) { case 'path': return el.getAttribute('d') || ''; case 'rect': { const x = n('x'), y = n('y'), w = n('width'), h = n('height'); let rx = n('rx'), ry = n('ry'); if (!el.hasAttribute('ry')) ry = rx; if (!el.hasAttribute('rx')) rx = ry; rx = Math.min(rx, w / 2); ry = Math.min(ry, h / 2); if (w <= 0 || h <= 0) return ''; if (!rx || !ry) return `M${x} ${y}H${x + w}V${y + h}H${x}Z`; return `M${x + rx} ${y}H${x + w - rx}A${rx} ${ry} 0 0 1 ${x + w} ${y + ry}V${y + h - ry}A${rx} ${ry} 0 0 1 ${x + w - rx} ${y + h}H${x + rx}A${rx} ${ry} 0 0 1 ${x} ${y + h - ry}V${y + ry}A${rx} ${ry} 0 0 1 ${x + rx} ${y}Z`; } case 'circle': case 'ellipse': { const cx = n('cx'), cy = n('cy'); const rx = el.tagName.toLowerCase() === 'circle' ? n('r') : n('rx'); const ry = el.tagName.toLowerCase() === 'circle' ? n('r') : n('ry'); if (rx <= 0 || ry <= 0) return ''; return `M${cx + rx} ${cy}A${rx} ${ry} 0 1 1 ${cx - rx} ${cy}A${rx} ${ry} 0 1 1 ${cx + rx} ${cy}Z`; } case 'line': return `M${n('x1')} ${n('y1')}L${n('x2')} ${n('y2')}`; case 'polyline': case 'polygon': { const p = (el.getAttribute('points') || '').trim(); return p ? `M${p}${el.tagName.toLowerCase() === 'polygon' ? 'Z' : ''}` : ''; } } return ''; } /** The colour an outline is filed under: its stroke, else its fill, as #rrggbb; black when neither reads. */ function outlineColor(el: Element): string { const cs = getComputedStyle(el); const pick = (v: string) => { const m = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/.exec(v.trim()); if (!m || (m[4] !== undefined && +m[4] === 0)) return ''; return '#' + [m[1], m[2], m[3]].map((x) => (+x).toString(16).padStart(2, '0')).join(''); }; return (cs.stroke !== 'none' && pick(cs.stroke)) || (cs.fill !== 'none' && pick(cs.fill)) || '#000000'; } /** * Every outline in an SVG drawing, in its user units with the page flipped so * y points up. The SVG is put in the page out of sight for a moment, so the * browser can say each element's transform and colour. Skipped: anything in * or a clip path, text, pictures, and elements marked data-dxf="skip" * (page background, shadows, placeholders). Repeats of the same outline * (a fill and its stroke drawn separately) are kept once, so nothing is cut twice. * `stats.simplified` is set when the point budget ran out and later curves became straight lines. */ export function svgOutlines( svg: string | { fragment: DocumentFragment; sweep(root: ParentNode): void }, pageHeight: number, tol = DEFAULT_TOLERANCE, stats?: { simplified: boolean }, ): Outline[] { const host = document.createElement('div'); host.style.cssText = 'position:absolute;left:-100000px;top:0;width:10px;height:10px;overflow:hidden;visibility:hidden'; // In a shadow root, so a