import { Budget, Built, IDENTITY, Matrix, Shape, buildEntities, mul, newBudget, transform } from './dxf-geometry'; import { Drawing, Entity, all, has, num, str } from './dxf-read'; /** * A drawing as AutoCAD's tabs show it: the model, then each paper-space * layout in tab order. A layout is its own entities (title block, notes, the * sheet border) plus viewports, each a window onto the model at a scale, * clipped to its outline and with its own frozen layers. */ export interface Paper { /** The page in millimetres, as the layout's page setup turns it. */ widthMm: number; heightMm: number; /** Millimetres per paper-space unit: 1, or 25.4 for a layout set up in inches. */ mmPerUnit: number; /** Where the page's lower left corner is, in paper-space units. */ originX: number; originY: number; /** The page setup's paper name, as the file gives it ("ISO A1 (841.00 x 594.00 MM)"). */ name: string; } export interface Viewport { /** Model to paper space. */ m: Matrix; /** Paper-space units per model unit. */ scale: number; /** The outline it shows the model through, in paper space; one ring, or several for a clipping boundary with holes. */ clip: number[][]; /** Layer names frozen in this viewport only. */ frozen: string[]; } export interface Sheet { name: string; kind: 'model' | 'layout'; /** The model's shapes for the Model tab; the layout's own for a layout. */ space: Built; viewports: Viewport[]; paper: Paper | null; /** What the tab shows, in its own units: shapes, viewports and the page. */ minX: number; minY: number; maxX: number; maxY: number; } export interface Scene { sheets: Sheet[]; /** The tab the drawing was saved on: 0 (Model) unless it was saved showing a layout. */ initial: number; /** Viewports not drawn because they look at the model in 3D, with a count. */ viewports3d: number; /** The drawing expanded to more than the budget and only part of it was built (layouts past that point are left out). */ truncated: boolean; /** Some inserts nest more than 16 deep and are left out. */ tooDeep: boolean; } /** Viewport status flag (code 90): switched off. */ const VP_OFF = 0x20000; /** Viewport status flag (code 90): clipped by the entity named in code 340. */ const VP_NONRECT = 0x10000; export function buildScene(d: Drawing): Scene { // One budget for the whole drawing: a file with forty layouts each arraying // a heavy block must not get forty times the limit. const budget = newBudget(); const model = buildEntities(d, d.entities, 'model', budget); const sheets: Sheet[] = [sheetOf('Model', 'model', model, [], null)]; let initial = 0; let viewports3d = 0; const layouts = d.layouts .map((r) => layoutInfo(r, d)) .filter((l): l is LayoutInfo => !!l && l.block.toUpperCase() !== '*MODEL_SPACE') .sort((a, b) => a.tab - b.tab); for (const l of layouts) { // The layout shown when the file was saved keeps its entities in the // ENTITIES section, marked 67; every other layout's are in its own block. const active = l.block.toUpperCase() === '*PAPER_SPACE'; const ents: Entity[] = [...(d.blocks.get(l.block)?.entities ?? []), ...(active ? d.entities.filter((e) => num(e, 67) === 1) : [])]; const vpEnts = ents.filter((e) => e.type === 'VIEWPORT'); const space = buildEntities(d, ents.filter((e) => e.type !== 'VIEWPORT'), 'paper', budget); const viewports: Viewport[] = []; const byHandle = new Map(ents.filter((e) => has(e, 5)).map((e) => [str(e, 5).toUpperCase(), e])); // Viewport ID 1 is the sheet itself as seen on screen, not a window onto // the model. LibreDWG's DXF writes every ID and status as 0; there the // sheet's own is the first made, the one with the lowest handle, and // status 0 ("off") cannot be trusted either. const numbered = vpEnts.some((v) => num(v, 69) > 0); const sheetVp = numbered ? vpEnts.find((v) => num(v, 69) === 1) : [...vpEnts].sort((a, b) => parseInt(str(a, 5), 16) - parseInt(str(b, 5), 16))[0]; for (const v of vpEnts) { if (v === sheetVp || num(v, 90) & VP_OFF || (numbered && has(v, 68) && num(v, 68) === 0)) continue; if (Math.abs(num(v, 16)) > 1e-9 || Math.abs(num(v, 26)) > 1e-9 || num(v, 36, 1) <= 0) { viewports3d++; continue; } const vp = viewportOf(v, d, byHandle, budget); if (vp) { viewports.push(vp); // The viewport's edge, as AutoCAD draws it, on the viewport's layer; a clipping entity draws its own. if (!(num(v, 90) & VP_NONRECT && has(v, 340))) { const vl = str(v, 8) || '0'; space.shapes.push({ layer: vl, color: -1, kind: 'line', rings: vp.clip, closed: true, lw: d.lwDefault / 100 }); space.layerCounts.set(vl, (space.layerCounts.get(vl) ?? 0) + 1); } } } if (!space.shapes.length && !viewports.length) continue; if (d.onLayout && active) initial = sheets.length; sheets.push(sheetOf(l.name, 'layout', space, viewports, l.paper)); } return { sheets, initial, viewports3d, truncated: budget.spent, tooDeep: budget.tooDeep > 0 }; } interface LayoutInfo { name: string; tab: number; block: string; paper: Paper | null; } /** * A LAYOUT object: plot settings first (paper size 44/45 in millimetres, * margins 40-43, units 72, rotation 73), then after "AcDbLayout" its name, * tab order (71), limits (10/20, 11/21) and the block it draws (330). */ function layoutInfo(r: Entity, d: Drawing): LayoutInfo | null { const at = r.pairs.findIndex(([c, v]) => c === 100 && v === 'AcDbLayout'); if (at < 0) return null; const plot: Entity = { type: 'PLOT', pairs: r.pairs.slice(0, at), children: [] }; const lay: Entity = { type: 'LAYOUT', pairs: r.pairs.slice(at + 1), children: [] }; const handle = lay.pairs.filter(([c]) => c === 330).pop()?.[1] ?? ''; const block = d.blockRecords.get(handle.toUpperCase()) ?? ''; if (!block) return null; return { name: str(lay, 1, 'Layout'), tab: num(lay, 71), block, paper: paperOf(plot, lay) }; } function paperOf(plot: Entity, lay: Entity): Paper | null { let w = num(plot, 44), h = num(plot, 45); if (!(w > 0 && h > 0)) return null; // A page set up turned a quarter turn is printed with its long side the other way. if (num(plot, 73) % 2 === 1) [w, h] = [h, w]; const mmPerUnit = num(plot, 72, 1) === 0 ? 25.4 : 1; const lx0 = num(lay, 10), ly0 = num(lay, 20), lx1 = num(lay, 11), ly1 = num(lay, 21); // The layout's limits are the sheet's edges in paper units, when they agree with the paper size. const limitsFit = Math.abs((lx1 - lx0) * mmPerUnit - w) < 1 && Math.abs((ly1 - ly0) * mmPerUnit - h) < 1; return { widthMm: w, heightMm: h, mmPerUnit, // Otherwise paper-space 0,0 sits at the printable area's corner: the left and bottom margins in. originX: limitsFit ? lx0 : -num(plot, 40) / mmPerUnit, originY: limitsFit ? ly0 : -num(plot, 41) / mmPerUnit, name: str(plot, 4), }; } /** * A viewport's window onto the model. Its centre (10/20) and size (40/41) are * in paper space; the model point at its centre is the view target (17/27) * plus the view centre (12/22), turned by the twist angle (51); the scale is * its paper height over the model height it shows (45). */ function viewportOf(v: Entity, d: Drawing, byHandle: Map, budget: Budget): Viewport | null { const cx = num(v, 10), cy = num(v, 20); const w = num(v, 40), h = num(v, 41); const viewH = num(v, 45); if (!(w > 0 && h > 0 && viewH > 0)) return null; const scale = h / viewH; const twist = (num(v, 51) * Math.PI) / 180; const c = Math.cos(twist), s = Math.sin(twist); const tx = num(v, 17), ty = num(v, 27); const vx = num(v, 12), vy = num(v, 22); // Model to display coordinates: about the target, turned by the twist; then // the view centre to the viewport's centre, at the scale. const toDcs: Matrix = [c, s, -s, c, -(c * tx - s * ty), -(s * tx + c * ty)]; const m = mul([scale, 0, 0, scale, cx - scale * vx, cy - scale * vy], toDcs); let clip: number[][] = [[cx - w / 2, cy - h / 2, cx + w / 2, cy - h / 2, cx + w / 2, cy + h / 2, cx - w / 2, cy + h / 2]]; if (num(v, 90) & VP_NONRECT && has(v, 340)) { const e = byHandle.get(str(v, 340).toUpperCase()); if (e) { const rings = buildEntities(d, [e], 'paper', budget).shapes.flatMap((sh) => sh.rings ?? []).filter((r) => r.length >= 6); if (rings.length) clip = rings; } } const frozen = all(v, 331).length ? v.pairs.filter(([c]) => c === 331).map(([, h]) => d.layerHandles.get(h.toUpperCase()) ?? '').filter(Boolean) : []; return { m, scale, clip, frozen }; } function sheetOf(name: string, kind: Sheet['kind'], space: Built, viewports: Viewport[], paper: Paper | null): Sheet { let minX = space.minX, minY = space.minY, maxX = space.maxX, maxY = space.maxY; const grow = (x: number, y: number) => { if (!isFinite(x) || !isFinite(y)) return; minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); }; for (const v of viewports) for (const r of v.clip) for (let i = 0; i < r.length; i += 2) grow(r[i], r[i + 1]); if (paper) { grow(paper.originX, paper.originY); grow(paper.originX + paper.widthMm / paper.mmPerUnit, paper.originY + paper.heightMm / paper.mmPerUnit); } return { name, kind, space, viewports, paper, minX, minY, maxX, maxY }; } /** Where a sheet point falls: in which viewport (index), and the model point there; -1 and the same point when in paper space. */ export function pickViewport(sheet: Sheet, x: number, y: number): { index: number; mx: number; my: number } { for (let i = sheet.viewports.length - 1; i >= 0; i--) { const v = sheet.viewports[i]; if (insideRings(v.clip, x, y)) { const [mx, my] = transform(invert(v.m), [x, y]); return { index: i, mx, my }; } } return { index: -1, mx: x, my: y }; } /** Even-odd point in polygon over several rings. */ export function insideRings(rings: number[][], x: number, y: number): boolean { let inside = false; for (const r of rings) { const n = r.length / 2; for (let i = 0, j = n - 1; i < n; j = i++) { const xi = r[2 * i], yi = r[2 * i + 1], xj = r[2 * j], yj = r[2 * j + 1]; if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside; } } return inside; } export function invert(m: Matrix): Matrix { const det = m[0] * m[3] - m[1] * m[2] || 1e-300; const a = m[3] / det, b = -m[1] / det, c = -m[2] / det, d = m[0] / det; return [a, b, c, d, -(a * m[4] + c * m[5]), -(b * m[4] + d * m[5])]; } export { IDENTITY }; export type { Shape };