import { BACKGROUND, Built, Matrix, Shape } from './dxf-geometry'; import { CAP_TO_EM, ColorMode, cssColor } from './render'; import { Sheet } from './scene'; /** * A tab of the drawing as SVG: the model, or a layout with its viewports * (each a group clipped to its outline, with the model inside at its scale). * The SVG download, the PDF and the batch all draw from this. */ /** Line width on paper when lineweights are off: AutoCAD's usual default lineweight. */ export const THIN_MM = 0.25; /** The thinnest line drawn on paper, for lineweight 0 ("as thin as the printer can"). */ export const HAIRLINE_MM = 0.05; export interface Box { minX: number; minY: number; maxX: number; maxY: number; } export interface SvgOptions { /** For svg2pdf: text placed by an explicit shift rather than dominant-baseline, which it does not follow. */ pdf?: boolean; /** Millimetres of paper per sheet unit: what turns lineweights (millimetres) into stroke widths. */ mmPerUnit: number; lineweights: boolean; mode: ColorMode; /** Layers switched off. */ hidden: Set; /** The area shown, in sheet units. */ box: Box; /** Width and height attributes, for a picture drawn at a size. */ size?: { w: number; h: number }; } /** * The area a tab exports: a layout with a page setup is its page; anything * else is what is drawn, with a 2% margin. */ export function exportBox(sheet: Sheet): Box { const p = sheet.paper; if (p) return { minX: p.originX, minY: p.originY, maxX: p.originX + p.widthMm / p.mmPerUnit, maxY: p.originY + p.heightMm / p.mmPerUnit }; return paddedBox(sheet); } export function paddedBox(b: Box): Box { const w = b.maxX - b.minX || 1; const h = b.maxY - b.minY || 1; const pad = Math.max(w, h) * 0.02; return { minX: b.minX - pad, minY: b.minY - pad, maxX: b.minX + w + pad, maxY: b.minY + h + pad }; } /** * Decimal places that keep every coordinate within a millionth of the * drawing's extent of where it is: far below a pixel at any zoom a viewer * offers. Places after the point, not significant digits, so a survey * drawing's large coordinates (500000.1234) keep what they need. */ export function coordDigits(extent: number): number { if (!(extent > 0) || !Number.isFinite(extent)) return 6; return Math.min(12, Math.max(0, Math.ceil(-Math.log10(extent * 1e-6)))); } /** A coordinate written to `digits` places, as short as it goes (no trailing zeros). */ export type Fmt = (n: number) => string; export function coordFormat(digits: number): Fmt { const k = 10 ** digits; return (n) => { const x = n * k; // Past what a double holds exactly as a whole number, it is written as it is. if (!(Math.abs(x) < 2 ** 53)) return String(n); const r = Math.round(x) / k; return String(r === 0 ? 0 : r); }; } export function sheetSvg(sheet: Sheet, model: Built, o: SvgOptions): string { const { box } = o; const w = box.maxX - box.minX, h = box.maxY - box.minY; const thin = THIN_MM / o.mmPerUnit; const parts: string[] = []; // Coordinates rounded to the area shown; inside a viewport, to that area in model units. const extent = Math.max(w, h); const f = coordFormat(coordDigits(extent)); shapesSvg(sheet.space.shapes, o.hidden, o.mmPerUnit, o, parts, f); sheet.viewports.forEach((v, i) => { const d = v.clip.map((r) => ringPath(r, true, f)).join(''); parts.push(``); parts.push(``); const hidden = v.frozen.length ? new Set([...o.hidden, ...v.frozen]) : o.hidden; // Model units inside: a lineweight in millimetres is that many divided by the paper per model unit. shapesSvg(model.shapes, hidden, o.mmPerUnit * v.scale, o, parts, coordFormat(coordDigits(extent / Math.abs(v.scale))), thin / v.scale); parts.push(''); }); const sized = o.size ? ` width="${o.size.w}" height="${o.size.h}"` : ''; return `` + `${parts.join('')}`; } /** The SVG transform for a model-to-sheet matrix, with y turned down on both sides. */ function svgMatrix(m: Matrix): string { return `matrix(${m[0]} ${-m[1]} ${-m[2]} ${m[3]} ${m[4]} ${-m[5]})`; } function ringPath(r: number[], close: boolean, f: Fmt): string { let p = `M${f(r[0])} ${f(-r[1])}`; for (let i = 2; i < r.length; i += 2) p += `L${f(r[i])} ${f(-r[i + 1])}`; return p + (close ? 'Z' : ''); } function shapesSvg(shapes: Shape[], hidden: Set, mmPerUnit: number, o: SvgOptions, parts: string[], f: Fmt, inherited?: number): void { const forPdf = !!o.pdf; const thin = THIN_MM / mmPerUnit; // Inside a viewport group the root's stroke-width (in sheet units) would be inherited unscaled; say it again. if (inherited !== undefined) parts.push(``); for (const s of shapes) { if (hidden.has(s.layer) || s.ghost) continue; // In black and white a mask stays the paper's colour rather than turning into a black box. const col = cssColor(s.mask && o.mode === 'mono' ? BACKGROUND : s.color, false, o.mode); if (s.kind === 'text') { const t = s.text!; const size = t.height * CAP_TO_EM; const anchor = t.align === 'center' ? 'middle' : t.align === 'right' ? 'end' : 'start'; const base = forPdf ? 'auto' : t.baseline === 'top' ? 'hanging' : t.baseline === 'middle' ? 'middle' : 'auto'; // The same placement as hanging or middle, measured in cap heights (t.height). const shift = forPdf ? (t.baseline === 'top' ? t.height : t.baseline === 'middle' ? t.height / 2 : 0) : 0; const rot = (-t.rotation * 180) / Math.PI; const tspans = t.lines.map((l, i) => `${xml(l)}`).join(''); parts.push(`${tspans}`); continue; } const d = (s.rings ?? []).map((r) => { if (s.segs) { let p = ''; for (let i = 0; i + 3 < r.length; i += 4) p += `M${f(r[i])} ${f(-r[i + 1])}L${f(r[i + 2])} ${f(-r[i + 3])}`; return p; } return ringPath(r, !!s.closed || s.kind === 'fill', f); }).join(''); if (s.kind === 'fill') parts.push(``); else if (s.kind === 'point') parts.push(``); else { const sw = s.width || (o.lineweights ? Math.max(s.lw ?? 0, HAIRLINE_MM) / mmPerUnit : thin); parts.push(``); } } if (inherited !== undefined) parts.push(''); } /** Whether any text is outside what the PDF's built-in font can write (Western European letters). */ export function needsRasterText(sheet: Sheet, model: Built): boolean { const re = /[^\u0000-ÿ–—‘’“”…]/; const test = (b: Built) => b.shapes.some((sh) => sh.kind === 'text' && re.test(sh.text!.lines.join(' '))); return test(sheet.space) || (sheet.viewports.length > 0 && test(model)); } /** * Text for an SVG: escaped, and without the characters XML 1.0 does not * allow at all (control characters, as a \U+0001 escape in DWG text gives, * and halves of broken surrogate pairs), which would make the file unreadable. */ export function xml(s: string): string { return s .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F￾￿]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!); }