import { IDENTITY, Matrix, Shape, ringDepths, transform } from './dxf-geometry'; import { Sheet, insideRings, invert } from './scene'; /** * Areas, lengths and picking for the Area and Info tools. Everything is * worked out in the units of the space a shape lives in: the model's for * the Model tab and inside a viewport, the sheet's for a layout's own lines. */ /** Signed area of a closed ring (shoelace); positive when anticlockwise. */ export function signedArea(r: number[]): number { let a = 0; const n = r.length / 2; for (let i = 0, j = n - 1; i < n; j = i++) a += r[2 * j] * r[2 * i + 1] - r[2 * i] * r[2 * j + 1]; return a / 2; } /** Length along a ring, back to its start when closed. */ export function ringLength(r: number[], closed: boolean): number { let l = 0; for (let i = 2; i < r.length; i += 2) l += Math.hypot(r[i] - r[i - 2], r[i + 1] - r[i - 1]); if (closed && r.length >= 4) l += Math.hypot(r[0] - r[r.length - 2], r[1] - r[r.length - 1]); return l; } /** * The area inside a shape's rings read even-odd, as a hatch is filled: an * island inside the outline is taken away, an island inside that added back. */ export function evenOddArea(rings: number[][]): number { return evenOddAreaOf(rings).area; } /** * The even-odd area, and whether it is exact. How many other rings each * sits inside decides whether it adds or takes away; when that is too much * work to sort out (ringDepths gives up), the loops are taken as separate * areas side by side, and the figure is only an estimate. */ export function evenOddAreaOf(rings: number[][]): { area: number; exact: boolean } { const shown = rings.filter((r) => r.length >= 6); const depth = ringDepths(shown); let total = 0; if (depth) { shown.forEach((r, i) => (total += (depth[i] % 2 ? -1 : 1) * Math.abs(signedArea(r)))); return { area: Math.abs(total), exact: true }; } for (const r of shown) total += Math.abs(signedArea(r)); return { area: total, exact: false }; } /** The area inside a shape's largest loop: its outline, islands not taken away. */ export function outlineArea(rings: number[][]): number { let best = 0; for (const r of rings) if (r.length >= 6) best = Math.max(best, Math.abs(signedArea(r))); return best; } /** Whether a shape is a closed outline: something with an area. */ export function isClosed(s: Shape): boolean { if (s.segs || !s.rings?.length) return false; if (s.kind === 'fill' && !s.mask) return true; if (s.kind !== 'line') return false; if (s.closed) return true; // An open polyline that ends where it starts is closed in all but name. const r = s.rings[0]; return r.length >= 8 && Math.hypot(r[0] - r[r.length - 2], r[1] - r[r.length - 1]) < 1e-9 * (1 + Math.abs(r[0]) + Math.abs(r[1])); } /** * A circle's area and circumference come from its radius exactly (a circle * in an unevenly scaled block is an ellipse: pi a b, and Ramanujan's * perimeter, within a few parts per million even at 10:1); anything * else curved (arcs in polylines, ellipses, splines, hatch edges) is * measured along the short straight pieces it is drawn with, within about * 0.1% of the true curve. */ export function shapeArea(s: Shape): number { return shapeAreaOf(s).area; } export function shapeAreaOf(s: Shape): { area: number; exact: boolean } { if (s.info?.type === 'CIRCLE' && s.info.radius) return { area: Math.PI * s.info.radius ** 2, exact: true }; if (s.info?.type === 'CIRCLE' && s.info.axes) return { area: Math.PI * s.info.axes[0] * s.info.axes[1], exact: true }; return isClosed(s) ? evenOddAreaOf(s.rings!) : { area: 0, exact: true }; } /** What a reader is told when an area could only be estimated. */ export const ROUGH_AREA = 'too many loops to work out which are holes, so each counts as area'; export function shapeLength(s: Shape): number { if (s.info?.type === 'CIRCLE' && s.info.radius) return 2 * Math.PI * s.info.radius; if (s.info?.type === 'CIRCLE' && s.info.axes) return ellipsePerimeter(s.info.axes[0], s.info.axes[1]); return (s.rings ?? []).reduce((a, r) => a + (s.segs ? segsLength(r) : ringLength(r, isClosed(s))), 0); } /** Ramanujan's second approximation to an ellipse's perimeter, from its semi-axes. */ export function ellipsePerimeter(a: number, b: number): number { const h = ((a - b) / (a + b)) ** 2; return Math.PI * (a + b) * (1 + (3 * h) / (10 + Math.sqrt(4 - 3 * h))); } function segsLength(r: number[]): number { let l = 0; for (let i = 0; i + 3 < r.length; i += 4) l += Math.hypot(r[i + 2] - r[i], r[i + 3] - r[i + 1]); return l; } /** Distance from a point to a shape's lines, in the shape's own units. */ export function distanceTo(s: Shape, x: number, y: number): number { let best = Infinity; const seg = (ax: number, ay: number, bx: number, by: number) => { const dx = bx - ax, dy = by - ay; const len = dx * dx + dy * dy; const t = len ? Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / len)) : 0; best = Math.min(best, Math.hypot(ax + t * dx - x, ay + t * dy - y)); }; if (s.kind === 'text' && s.text) return Math.hypot(s.text.x - x, s.text.y - y); for (const r of s.rings ?? []) { if (r.length === 2) best = Math.min(best, Math.hypot(r[0] - x, r[1] - y)); if (s.segs) { for (let i = 0; i + 3 < r.length; i += 4) seg(r[i], r[i + 1], r[i + 2], r[i + 3]); continue; } for (let i = 2; i < r.length; i += 2) seg(r[i - 2], r[i - 1], r[i], r[i + 1]); if ((s.closed || s.kind === 'fill') && r.length >= 4) seg(r[r.length - 2], r[r.length - 1], r[0], r[1]); } return best; } export interface Picked { shape: Shape; /** The shape's units to the tab's: identity, or a viewport's matrix. */ m: Matrix; /** The viewport it was seen through, or -1. */ vp: number; } /** * The shapes under a point of a tab, as candidates: the tab's own, then the * model's through the viewport the point is in (clipped, with its frozen * layers left out). */ function* candidates(sheet: Sheet, model: Shape[], hidden: Set, x: number, y: number): Generator<{ shape: Shape; m: Matrix; vp: number; px: number; py: number; k: number }> { for (const s of sheet.space.shapes) if (!hidden.has(s.layer)) yield { shape: s, m: IDENTITY, vp: -1, px: x, py: y, k: 1 }; for (let i = 0; i < sheet.viewports.length; i++) { const v = sheet.viewports[i]; if (!insideRings(v.clip, x, y)) continue; const [mx, my] = transform(invert(v.m), [x, y]); for (const s of model) if (!hidden.has(s.layer) && !v.frozen.includes(s.layer)) yield { shape: s, m: v.m, vp: i, px: mx, py: my, k: v.scale }; } } /** The shape nearest a click, within `tol` sheet units; texts count by their anchor. */ export function pickNearest(sheet: Sheet, model: Shape[], hidden: Set, x: number, y: number, tol: number): Picked | null { let best: Picked | null = null; let bestD = tol; for (const c of candidates(sheet, model, hidden, x, y)) { if (c.shape.mask) continue; // A fill counts when the click is inside it, at a little more than zero so an outline on top wins. let d = distanceTo(c.shape, c.px, c.py) * c.k; if (d > bestD && c.shape.kind === 'fill' && insideRings(c.shape.rings ?? [], c.px, c.py)) d = tol * 0.9; if (d <= bestD) { bestD = d; best = { shape: c.shape, m: c.m, vp: c.vp }; } } return best; } /** * The smallest closed shape round a click; only when the click is inside * none, the closed shape whose outline is nearest within `tol`. */ export function pickClosed(sheet: Sheet, model: Shape[], hidden: Set, x: number, y: number, tol: number): Picked | null { let inside: Picked | null = null; let insideArea = Infinity; let near: Picked | null = null; let nearD = tol; for (const c of candidates(sheet, model, hidden, x, y)) { if (!isClosed(c.shape)) continue; const rings = c.shape.rings!; if (insideRings(rings, c.px, c.py)) { // Which is smallest is judged by its largest loop, the outline, in one // pass over its vertices; the full even-odd area is worked out once, // for the shape picked. const a = outlineArea(rings) * c.k * c.k; if (a < insideArea) { insideArea = a; inside = { shape: c.shape, m: c.m, vp: c.vp }; } } else { const d = distanceTo(c.shape, c.px, c.py) * c.k; if (d <= nearD) { nearD = d; near = { shape: c.shape, m: c.m, vp: c.vp }; } } } return inside ?? near; } /** Square-unit names, and a larger unit to restate a big area in. */ export function areaText(a: number, units: number): string { const short: Record = { 1: 'in', 2: 'ft', 4: 'mm', 5: 'cm', 6: 'm', 7: 'km', 10: 'yd', 14: 'dm' }; const u = short[units]; const f = (v: number) => (+v.toPrecision(7)).toLocaleString('en', { maximumFractionDigits: 6 }); if (!u) return `${f(a)} square units`; let more = ''; if (units === 4) more = ` (${f(a / 1e6)} m²)`; else if (units === 5) more = ` (${f(a / 1e4)} m²)`; else if (units === 14) more = ` (${f(a / 100)} m²)`; else if (units === 1) more = ` (${f(a / 144)} ft²)`; else if (units === 2) more = ` (${f(a / 43560)} acres)`; else if (units === 6 && a >= 10000) more = ` (${f(a / 10000)} ha)`; return `${f(a)} ${u}²${more}`; }