import { Matrix } from './dxf-geometry'; import { exportBox } from './export-svg'; import { PagePlan } from './pdf'; import { Sheet } from './scene'; /** * A whole tab as a PNG or JPG: its size in pixels, and the matrix that puts * the tab's units on them. Sized either by its long side in pixels, or by * dots per inch on the page the PDF options describe. */ /** The largest picture made: browsers refuse canvases much past this, some (Safari on a phone) well before. */ export const MAX_SIDE = 10000; export const MAX_PIXELS = 50_000_000; export type PictureSize = { mode: 'px'; long: number } | { mode: 'dpi'; dpi: number; page: PagePlan }; export interface PicturePlan { w: number; h: number; /** Tab units to pixels (y down). */ m: Matrix; /** Pixels per millimetre of paper, which turns lineweights into pixels. */ pxPerMm: number; } export function planPicture(sheet: Sheet, size: PictureSize): PicturePlan | { error: string } { let w: number, h: number, m: Matrix, pxPerMm: number; if (size.mode === 'px') { const box = exportBox(sheet); const bw = box.maxX - box.minX, bh = box.maxY - box.minY; const k = size.long / Math.max(bw, bh); w = Math.max(1, Math.round(bw * k)); h = Math.max(1, Math.round(bh * k)); m = [k, 0, 0, -k, -box.minX * k, box.maxY * k]; // A layout's units are paper; the model is taken as printed 420 mm (A3) along its long side, as the SVG is. pxPerMm = sheet.paper ? k / sheet.paper.mmPerUnit : size.long / 420; } else { const p = size.page; pxPerMm = size.dpi / 25.4; w = Math.round(p.pageW * pxPerMm); h = Math.round(p.pageH * pxPerMm); const k = p.mmPerUnit * pxPerMm; m = [k, 0, 0, -k, p.x * pxPerMm - p.box.minX * k, p.y * pxPerMm + p.box.maxY * k]; } if (w > MAX_SIDE || h > MAX_SIDE || w * h > MAX_PIXELS) { const at = size.mode === 'dpi' ? `At ${size.dpi} dpi the page` : 'The picture'; return { error: `${at} would be ${w.toLocaleString('en')} × ${h.toLocaleString('en')} pixels, more than this page makes (${MAX_SIDE.toLocaleString('en')} pixels a side and ${MAX_PIXELS / 1e6} megapixels in all). Choose a smaller size${size.mode === 'dpi' ? ', a lower dpi or smaller paper' : ''}.` }; } return { w, h, m, pxPerMm }; }