Skip to content

An agent skill for creating detailed, interactive isometric illustrations of real-world machines and complex systems. Generates polished SVGs with optional WebGL shaders and 3D effects.

fix(audit): preserve affine SVG primitive bounds

Rudy Celekli3e1e1ab77d51
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bf7b18d..19e6769 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -25,6 +25,9 @@ jobs:
with:
node-version: 22
+ - name: Native affine SVG bounds
+ run: node --test scripts/audit-affine-bounds.test.mjs
+
- name: Dial indicator
run: |
node examples/dial-indicator/build.mjs
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8152ae2..a0514f0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,8 @@ All notable changes to Anatomy are recorded here. The format follows [Keep a Cha
### Fixed
+- Measure transformed rectangular and round SVG primitives through their true affine bounds.
+
- `examples/test-rig/` drew its glass button dark in the light theme. `stretch.css` now has light values for its own colours.
### Changed
diff --git a/kit/audit.mjs b/kit/audit.mjs
index f52d06c..6c0bf42 100644
--- a/kit/audit.mjs
+++ b/kit/audit.mjs
@@ -1357,7 +1357,7 @@ const multiply = (m, n) => [m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1]
function matrixOf(text) {
let m = [1, 0, 0, 1, 0, 0];
if (!text) return m;
- for (const [, kind, args] of text.matchAll(/(matrix|translate|scale|rotate)\s*\(([^)]*)\)/g)) {
+ for (const [, kind, args] of text.matchAll(/(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g)) {
const v = (args.match(/-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi) ?? []).map(Number);
let n = [1, 0, 0, 1, 0, 0];
if (kind === "matrix" && v.length === 6) n = v;
@@ -1368,6 +1368,8 @@ function matrixOf(text) {
const [cx, cy] = [v[1] ?? 0, v[2] ?? 0];
n = multiply(multiply([1, 0, 0, 1, cx, cy], [Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]), [1, 0, 0, 1, -cx, -cy]);
}
+ else if (kind === "skewX") n = [1, 0, Math.tan((v[0] ?? 0) * Math.PI / 180), 1, 0, 0];
+ else if (kind === "skewY") n = [1, Math.tan((v[0] ?? 0) * Math.PI / 180), 0, 1, 0, 0];
m = multiply(m, n);
}
return m;
@@ -1414,7 +1416,7 @@ function pointsOfShape(tag, attrs) {
return [[num("cx") - r, num("cy") - ry], [num("cx") + r, num("cy") + ry]];
}
if (tag === "line") return [[num("x1"), num("y1")], [num("x2"), num("y2")]];
- if (tag === "rect") return [[num("x"), num("y")], [num("x") + num("width"), num("y") + num("height")]];
+ if (tag === "rect") return cornersOfBox([num("x"), num("y"), num("x") + num("width"), num("y") + num("height")]);
if (tag === "polyline" || tag === "polygon") {
const v = (get("points") ?? "").match(NUMBER)?.map(Number) ?? [];
const out = [];
@@ -1433,6 +1435,18 @@ const boxOfPoints = (points, m) => {
}
return box;
};
+const cornersOfBox = ([x0, y0, x1, y1]) => [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
+const boxOfShape = (tag, attrs, m) => {
+ if (tag !== "circle" && tag !== "ellipse") return boxOfPoints(pointsOfShape(tag, attrs), m);
+ const num = (name) => Number((attrs.match(new RegExp(`(?:^|\\s)${name}="([^"]*)"`)) ?? [])[1] ?? 0);
+ const rx = tag === "circle" ? num("r") : num("rx");
+ const ry = tag === "circle" ? rx : num("ry");
+ const x = m[0] * num("cx") + m[2] * num("cy") + m[4];
+ const y = m[1] * num("cx") + m[3] * num("cy") + m[5];
+ const dx = Math.hypot(m[0] * rx, m[2] * ry);
+ const dy = Math.hypot(m[1] * rx, m[3] * ry);
+ return [x - dx, y - dy, x + dx, y + dy];
+};
const unionBox = (a, b) => (!a ? b : !b ? a : [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[2], b[2]), Math.max(a[3], b[3])]);
const meetBox = (a, b) => (!a || !b ? a ?? null : [Math.max(a[0], b[0]), Math.max(a[1], b[1]), Math.min(a[2], b[2]), Math.min(a[3], b[3])]);
const areaOf = (box) => (box ? Math.max(0, box[2] - box[0]) * Math.max(0, box[3] - box[1]) : 0);
@@ -1451,7 +1465,7 @@ export function markupBox(svg) {
clipId = null;
continue;
}
- clips.set(clipId, unionBox(clips.get(clipId), boxOfPoints(pointsOfShape(tag, attrs), matrixOf((attrs.match(/transform="([^"]*)"/) ?? [])[1]))));
+ clips.set(clipId, unionBox(clips.get(clipId), boxOfShape(tag, attrs, matrixOf((attrs.match(/transform="([^"]*)"/) ?? [])[1]))));
}
}
const stack = [{ m: [1, 0, 0, 1, 0, 0], clip: null, skip: false }];
@@ -1464,10 +1478,10 @@ export function markupBox(svg) {
}
const m = multiply(top.m, matrixOf((attrs.match(/transform="([^"]*)"/) ?? [])[1]));
const ref = (attrs.match(/clip-path="url\(#([^)]*)\)"/) ?? [])[1];
- const own = ref && clips.get(ref) ? boxOfPoints([[clips.get(ref)[0], clips.get(ref)[1]], [clips.get(ref)[2], clips.get(ref)[3]]], m) : null;
+ const own = ref && clips.get(ref) ? boxOfPoints(cornersOfBox(clips.get(ref)), m) : null;
const frame = { m, clip: own ? meetBox(top.clip ?? own, own) : top.clip, skip: top.skip || ["defs", "clipPath", "mask", "linearGradient", "radialGradient", "pattern", "text", "title"].includes(tag) || /class="[^"]*iso-halo/.test(attrs) };
if (!frame.skip) {
- const shape = boxOfPoints(pointsOfShape(tag, attrs), m);
+ const shape = boxOfShape(tag, attrs, m);
if (shape) box = unionBox(box, frame.clip ? meetBox(shape, frame.clip) : shape);
}
if (!self) stack.push(frame);
diff --git a/scripts/audit-affine-bounds.test.mjs b/scripts/audit-affine-bounds.test.mjs
new file mode 100644
index 0000000..10d40a1
--- /dev/null
+++ b/scripts/audit-affine-bounds.test.mjs
@@ -0,0 +1,54 @@
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import test from "node:test";
+import * as A from "../kit/audit.mjs";
+import { turning } from "../kit/turn-build.mjs";
+const P = { origin: [0, 0], scale: 1, azimuth: 45, elevation: 30 };
+const fixtures = [
+ ["rotated rectangle", '<rect width="10" height="10" transform="rotate(45)"/>'],
+ ["rotated circle", '<circle r="10" transform="rotate(45)"/>'],
+ ["rotated ellipse", '<ellipse rx="10" ry="2" transform="rotate(45)"/>'],
+ ["nested affine ellipse", '<g transform="translate(10 5) scale(2 .5)"><ellipse cx="2" cy="3" rx="7" ry="2" transform="rotate(30)"/></g>'],
+ ["horizontal skew", '<rect x="2" y="3" width="10" height="10" transform="skewX(45)"/>'],
+ ["vertical skew", '<rect x="2" y="3" width="10" height="10" transform="skewY(-30)"/>'],
+ ["ordinary rectangle", '<rect x="2" y="3" width="10" height="4"/>'],
+ ["ordinary circle", '<circle cx="2" cy="3" r="4"/>'],
+ ["ordinary transformed line", '<line x1="2" y1="3" x2="10" y2="7" transform="rotate(30)"/>'],
+];
+let native;
+const directory = await mkdtemp(join(tmpdir(), "anatomy-affine-bounds-"));
+try {
+ const page = join(directory, "figure.html");
+ await writeFile(page, `<!doctype html><div class="iso-plate"><svg width="400" height="400">${fixtures.map(([,markup],i)=>`<g id="fixture-${i}">${markup}</g>`).join("")}</svg></div>`);
+ const expression = `Array.from({length:${fixtures.length}},(_,i)=>{const group=document.querySelector('#fixture-'+i),shape=group.querySelector('rect,circle,ellipse,line'),matrix=shape.getCTM(),points=[];if(shape.tagName==='rect'){const b=shape.getBBox();for(const [x,y] of [[b.x,b.y],[b.x+b.width,b.y],[b.x+b.width,b.y+b.height],[b.x,b.y+b.height]])points.push(new DOMPoint(x,y).matrixTransform(matrix));}else{const length=shape.getTotalLength();for(let j=0;j<=4096;j++)points.push(shape.getPointAtLength(length*j/4096).matrixTransform(matrix));}const b=group.getBBox();return{geometry:[Math.min(...points.map(p=>p.x)),Math.min(...points.map(p=>p.y)),Math.max(...points.map(p=>p.x)),Math.max(...points.map(p=>p.y))],groupBox:[b.x,b.y,b.x+b.width,b.y+b.height]}})`;
+ const result = await promisify(execFile)(process.execPath, ["scripts/drive.mjs", page, JSON.stringify([["eval",expression]])], { timeout: 30000 });
+ const observations = JSON.parse(result.stdout.match(/eval: (.*)/)[1]);
+ console.log("native SVG group bounds:", JSON.stringify(observations.map(v=>v.groupBox)));
+ native = observations.map(v=>v.geometry);
+} finally { await rm(directory, { recursive: true, force: true }); }
+fixtures.forEach(([name,markup],i)=>test(`public bounds and fixed parts match native SVG geometry for ${name}`,()=>{
+ const expected = native[i];
+ const observed = A.markupBox(markup);
+ for(let j=0;j<4;j++)assert.ok(Math.abs(observed[j]-expected[j])<.002, `${name} bound ${j}: ${observed[j]} != ${expected[j]}`);
+ const T = turning(P);T.layer("figure");
+ const part = T.fixed({name:"authored",svg:markup,anchor:[0,0,0],shapes:[A.ball([0,0,0],20)]});
+ for(let j=0;j<4;j++)assert.ok(Math.abs(part.spec.box[j]-(expected[j]+(j<2?-.5:.5)))<.002);
+}));
+test("coverage rejects a narrow stand-in for a rotated rectangle",()=>{
+ const cam=A.cameraBasis(P);
+ const end=cam.D.map(v=>v*Math.sqrt(200)/cam.k);
+ const standIn=A.tube([[0,0,0],end],.15);
+ const item={name:"plate",svg:fixtures[0][1],shapes:[standIn]};
+ const result=A.coverage([item],P,{pad:0});
+ assert.equal(result.length,1);assert.ok(result[0].share<.1);
+ assert.equal(A.coverage([{...item,shapes:[A.ball([0,0,0],20)]}],P,{pad:0}).length,0);
+});
+test("transformed rectangular clips keep every corner",()=>{
+ const clipped='<defs><clipPath id="cut"><rect width="10" height="10"/></clipPath></defs><g transform="rotate(45)" clip-path="url(#cut)"><rect x="-100" y="-100" width="200" height="200"/></g>';
+ const observed=A.markupBox(clipped),root=Math.sqrt(50);
+ for(const [i,v] of [-root,0,root,2*root].entries())assert.ok(Math.abs(observed[i]-v)<1e-8);
+});