3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Draw icons as sketches, turnarounds and breakdowns (#2031)
Nguyen Xuan An3705d7c35f68
diff --git a/changes/2031.md b/changes/2031.mdindex f3de52e6..f2753c90 100644--- a/changes/2031.md+++ b/changes/2031.md@@ -1 +1 @@-- `scene_render_submit` takes `kind: "icons"`: render up to 256 GLBs as matching transparent icons (clean or toon, fit or relative scale), with an atlas and `icons.json`, in one job (#2031)+- `scene_render_submit` takes `kind: "icons"`: render up to 256 GLBs as matching transparent icons (clean, toon or sketch, fit or relative scale), with an atlas and `icons.json`, in one job. `style: "sketch"` inks the outline and hatches the shadow with pencil lines that still read at 64 px, `angles: 4|8` draws a turnaround sheet per item, and `breakdown: true` writes a shaded, outline, hatching, final strip per item (#2031)diff --git a/changes/2031.size.md b/changes/2031.size.mdindex 8013b7e1..2dd82370 100644--- a/changes/2031.size.md+++ b/changes/2031.size.md@@ -1,2 +1,2 @@-- tool:scene_render_submit: the `icons` job kind adds `items`, `size`, `style`, `viewpoint`, `scale` and `padding` so an agent can ask for a whole icon set in one call; the detail stays in `scene_capabilities` topic `jobs` under `icons`, and the new code sits in the MCP server bundle only.-- tool-total: the same 1125 bytes, all in `scene_render_submit`; no new tool.+- tool:scene_render_submit: the `icons` job kind adds `items`, `size`, `style`, `viewpoint`, `scale`, `padding`, `angles`, `breakdown`, `seed` and `sketch` so an agent can ask for a whole icon set, a turnaround or a breakdown in one call; the detail stays in `scene_capabilities` topic `jobs` under `icons`, and the new code sits in the MCP server bundle only.+- tool-total: grows by the four sketch fields (`angles`, `breakdown`, `seed`, `sketch`) of `scene_render_submit`; no new tool.diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.mdindex c54dbb25..b7979945 100644--- a/docs/agent-render-jobs.md+++ b/docs/agent-render-jobs.md@@ -192,28 +192,36 @@ A `png16` or `exr` frame is up to four times the 8-bit frame limit (48 MiB). A r| Field | Meaning || --- | --- || `items` | 1 to 256 catalog GLB names (as `scene_asset_catalog` lists them, inside `--assets` or `--packs`) or 64 character asset ids. Names are pinned to their asset id at submit. No paths outside the catalog and no URLs. |-| `size` | 64, 128, 256 (default) or 512 pixels per icon side. The atlas side is at most 4096 px, so 512 takes up to 64 items. |-| `style` | `clean` (default, the shaded render) or `toon` (outlines and three light bands, from [line art](line-art.md)). `sketch` is refused until it ships. |+| `size` | 64, 128, 256 (default) or 512 pixels per icon side. The atlas side is at most 4096 px, so 512 takes up to 64 single-angle items. |+| `style` | `clean` (default, the shaded render), `toon` (outlines and three light bands, from [line art](line-art.md)) or `sketch` (ink outline, pencil hatching that follows the light, paper fill; see below). || `viewpoint` | `"three-quarter"` (default: azimuth 35, elevation 25 degrees) or `{ azimuth, elevation }` in degrees, from the front of the model (+Z in glTF). || `scale` | `fit` (default): every item fills its icon. `relative`: one view height for the set, so the largest item fills its icon and a sword stays smaller than a chest. || `padding` | The empty border as a fraction of the icon side, 0.02 to 0.4 (default 0.08), the same for every item. |+| `angles` | 1 (default), 4 or 8: a turnaround per item, with that many views spaced evenly round the model starting at the viewpoint azimuth. The atlas gets one row per item and one column per angle. Items times `angles` is at most 256 and `angles` times `size` at most 4096. Each item keeps one view height across its views (under `relative`, the whole set shares one). |+| `breakdown` | `true` (sketch only): per item, a strip of four steps (shaded, outline, hatching, final) drawn from the camera of the item's first view. |+| `seed` | 0 to 65535 (sketch only, default 0): the line wobble. The same items, settings and seed give the same bytes. |+| `sketch` | `{ inkColor, paperColor, hatchDensity, jitter }` (sketch only): ink `#rrggbb` (default `#2b2a33`), paper `#rrggbb` (`#f4ecd8`), hatch density 0.5 to 2 (1) and line jitter 0 to 1 (0.35). |-The camera is orthographic, so an item's size does not depend on its distance, and the light is a fixed three-point rig that turns with the view, so every icon is lit from the same side. There is no ground and no sky: the background is transparent.+The camera is orthographic, so an item's size does not depend on its distance, and the light is a fixed three-point rig that turns with the view, so every icon is lit from the same side. There is no ground and no sky: the background is transparent (a sketch icon is filled with its paper colour where the model is).Framing fits the silhouette, not the bounding sphere. The job draws the item once from a bounding sphere, measures the alpha box of what was drawn and moves the camera until that box is centred and spans the icon minus its padding (up to four draws per item). A thin or flat item such as a sword or a coin therefore fills its icon instead of drawing small. An item that draws nothing, or cannot be framed in four draws, fails the job and names the item.-Output, all in the job's folder: `icon-0.png` to `icon-<n-1>.png` (one per item, in order), `atlas.png` (a near square grid, row by row, transparent where unused) and `icons.json`:+### The sketch style++Sketch is a [user pass](user-passes.md) on the shaded frame, so it has the same scene, camera and framing as the other styles. It inks the outline from the silhouette, the depth steps and the creases, hatches the shadow with pencil lines in three directions chosen by how dark the light is, and fills the model with paper. Hatch spacing is laid out in whole pixels (3 px at 64, growing with the icon) so the lines do not beat against the pixel grid. A test renders a model at 64 px and checks that the sketch stays a line pattern: the outline is inked along at least 95 percent of the silhouette, and in the hatched band at least 80 percent of the pixels are clearly paper or ink, not grey, with a contrast of at least 0.7 of the ink to paper range. [Icon sheets](learn/icon-sheets.md) (the docs guide page) shows the three styles and a breakdown.++Output, all in the job's folder: `icon-0.png` to `icon-<n-1>.png` (one per frame, items first and then angles), `breakdown-<item>.png` (one strip per item, with `breakdown`), `atlas.png` (a near square grid, row by row, transparent where unused) and `icons.json`:```json{ "version": 1, "size": 256, "style": "toon", "scale": "relative", "padding": 0.08, "viewpoint": { "azimuth": 35, "elevation": 25 },"atlas": { "file": "atlas.png", "width": 512, "height": 512, "columns": 2, "rows": 2 },- "icons": [{ "name": "sword", "file": "icon-0.png", "source": "sword.glb", "asset": "<id>", "angle": 35,+ "icons": [{ "name": "sword", "file": "icon-0.png", "source": "sword.glb", "asset": "<id>", "item": 0, "turn": 0, "angle": 35, "breakdown": "breakdown-0.png","rect": { "x": 0, "y": 0, "width": 256, "height": 256 }, "bounds": { "x": 70, "y": 21, "width": 116, "height": 214 }, "viewHeight": 2.1 }] }```-`rect` is the icon's cell in the atlas, `bounds` the box of its pixels inside the icon, and `viewHeight` the metres the icon's height spans. The JSON is plain, so Godot, Unity, Phaser and web code read it without a converter. The same items and settings give byte-identical files on the `cpu` backend.+A sketch job adds `angles`, `seed` and `sketch` at the top level. `item` is the item's index, `turn` the view's index and `angle` its azimuth in degrees; `breakdown` names the item's strip and appears on its first view only. `rect` is the icon's cell in the atlas, `bounds` the box of its pixels inside the icon, and `viewHeight` the metres the icon's height spans. The JSON is plain, so Godot, Unity, Phaser and web code read it without a converter. The same items and settings give byte-identical files on the `cpu` backend.-Not in this release: `style: "sketch"`, turnaround sheets (`angles`), the `breakdown` strip, HDRI lighting, `background` and `outline` (issue #2031; each is refused by name), and scene node ids as items. `scene_capabilities` topic `jobs` lists the limits under `icons`. `node scripts/smoke-icons.mjs --assets <folder> --out <folder> --style toon` renders a folder of GLBs and checks every icon's frame.+Not in this release: HDRI lighting, `background` and `outline` (issue #2031; each is refused by name), and scene node ids as items. The job's deadline grows with the frame count: about 4 s per frame (twice when the scale is shared across views) and 6 s per breakdown strip. `scene_capabilities` topic `jobs` lists the limits under `icons`. `node scripts/smoke-icons.mjs --assets <folder> --out <folder> --style toon` renders a folder of GLBs and checks every icon's frame.## Path tracerdiff --git a/docs/learn/icon-sheets.md b/docs/learn/icon-sheets.mdnew file mode 100644index 00000000..4705a68c--- /dev/null+++ b/docs/learn/icon-sheets.md@@ -0,0 +1,35 @@+# Icon sheets++++One call turns a folder of 3D models into matching 2D icons: an inventory sheet, an asset browser or a set of docs pictures. It is available from version `0.22.0`. The sketch style draws every model as ink and pencil hatching, and the strip above shows how: the shaded frame, the ink outline, the hatching that follows the light, then the finished icon.++## The call++Ask an MCP server started with `--assets <folder>` for an icon job. The scene you submit it with is not drawn, so an empty one will do.++```json+{ "kind": "icons", "items": ["boat.glb", "robot.glb", "chair.glb"], "size": 128, "style": "sketch", "breakdown": true, "seed": 1 }+```++Each icon is a transparent square PNG with the model framed to fill it. `atlas.png` packs them in a grid and `icons.json` says where each one sits. `angles: 4` or `8` draws every model from that many sides in a row of the atlas, which makes a turnaround sheet. The same items, settings and seed give the same files. [Render jobs](https://github.com/codepawl/crucible/blob/main/docs/agent-render-jobs.md) lists every field.++## Three styles++The same nine models in each style, at 128 px. `clean` is the shaded render, `toon` adds outlines and light bands, and `sketch` is ink and pencil.++++++++## Sketch settings++Sketch takes four knobs under `sketch`, and every one is bounded: `inkColor` and `paperColor` as `#rrggbb`, `hatchDensity` from 0.5 to 2 and `jitter` from 0 to 1, which wobbles the lines. `seed` picks the wobble. Hatching is laid out in whole pixels, so it stays a pattern of lines at 64 px instead of turning into grey.++## A turnaround++`angles: 8` gives every model a row of eight views, each 45 degrees apart, at one scale per model. Here are three models.++diff --git a/public/docs-media/icon-sheet-clean.png b/public/docs-media/icon-sheet-clean.pngnew file mode 100644index 00000000..96c18f58Binary files /dev/null and b/public/docs-media/icon-sheet-clean.png differdiff --git a/public/docs-media/icon-sheet-sketch.png b/public/docs-media/icon-sheet-sketch.pngnew file mode 100644index 00000000..bd4e313bBinary files /dev/null and b/public/docs-media/icon-sheet-sketch.png differdiff --git a/public/docs-media/icon-sheet-toon.png b/public/docs-media/icon-sheet-toon.pngnew file mode 100644index 00000000..da512079Binary files /dev/null and b/public/docs-media/icon-sheet-toon.png differdiff --git a/public/docs-media/icon-sheet-turnaround.png b/public/docs-media/icon-sheet-turnaround.pngnew file mode 100644index 00000000..bbb9ce20Binary files /dev/null and b/public/docs-media/icon-sheet-turnaround.png differdiff --git a/public/docs-media/icon-sketch-breakdown.png b/public/docs-media/icon-sketch-breakdown.pngnew file mode 100644index 00000000..d4cd7759Binary files /dev/null and b/public/docs-media/icon-sketch-breakdown.png differdiff --git a/scripts/agent-icon-job.mjs b/scripts/agent-icon-job.mjsindex 262d32bb..62802db3 100644--- a/scripts/agent-icon-job.mjs+++ b/scripts/agent-icon-job.mjs@@ -1,102 +1,146 @@-// The `icons` render job: draws each item as a transparent square icon, frames its silhouette, and writes one PNG per item,-// an atlas of all of them and icons.json. The browser side is passed in as `openItem`, so the loop runs without a page.+// The `icons` render job: draws each item as a transparent square icon (at one or more angles), frames its silhouette, and writes one+// PNG per frame, an optional breakdown strip per item, an atlas of all the frames and icons.json. The browser side is passed in as+// `openItem`, so the loop runs without a page.import { writeFile } from 'node:fs/promises';import { join } from 'node:path';-import { ICON_ARTIFACTS, alphaBounds, cameraForFraming, iconArtifactName, iconManifest, isFramed, layoutAtlas, refineFraming, relativeScale, sphereFraming } from '../src/icon-sheet.js';+import { ICON_ARTIFACTS, alphaBounds, breakdownArtifactName, cameraForFraming, iconArtifactName, iconFrames, iconManifest, isFramed, layoutAtlas, refineFraming, relativeScale, sphereFraming, BREAKDOWN_STEPS } from '../src/icon-sheet.js';import { blankImage, copyIntoAtlas, decodePng, encodePng } from './agent-icon-png.mjs';-/** Draws and measures at most this many times per item: the sphere guess, then up to three refinements. */+/** Draws and measures at most this many times per frame: the sphere guess, then up to three refinements. */const MAXIMUM_DRAWS = 4;const PNG_MIME = 'image/png';-function drewNothingError(settings, index) {- const { source } = settings.items[index];- return new Error(`items[${index}] (${source}) drew no pixels. Check that the GLB has visible, opaque geometry in front of the camera.`);+function describeFrame(settings, frame) {+ const { source } = settings.items[frame.itemIndex];+ return settings.angles > 1 ? `items[${frame.itemIndex}] (${source}) at ${frame.view.azimuth} degrees` : `items[${frame.itemIndex}] (${source})`;}-function tooSmallForRelativeError(settings, index, sizeRatio) {- const { source } = settings.items[index];- return new Error(`items[${index}] (${source}) is too small for scale "relative": the largest item of the set is about ${Math.round(sizeRatio)} times its size, so it draws under one pixel. Use scale "fit", or give the set consistent units.`);+function drewNothingError(settings, frame) {+ return new Error(`${describeFrame(settings, frame)} drew no pixels. Check that the GLB has visible, opaque geometry in front of the camera.`);}-function notFramedError(settings, index, box) {- const { source } = settings.items[index];- return new Error(`items[${index}] (${source}) could not be framed in ${MAXIMUM_DRAWS} draws: its silhouette spans ${box.left},${box.top} to ${box.right},${box.bottom} of ${settings.size} px. Try a smaller padding or another view.`);+function tooSmallForSharedScaleError(settings, frame, sizeRatio) {+ if (settings.scale === 'relative') {+ return new Error(`${describeFrame(settings, frame)} is too small for scale "relative": the largest item of the set is about ${Math.round(sizeRatio)} times its size, so it draws under one pixel. Use scale "fit", or give the set consistent units.`);+ }+ return new Error(`${describeFrame(settings, frame)} is too small next to the largest view of its item: that view is about ${Math.round(sizeRatio)} times its size, so it draws under one pixel. Use fewer angles, or a viewpoint that shows the item more evenly.`);+}++function notFramedError(settings, frame, box) {+ return new Error(`${describeFrame(settings, frame)} could not be framed in ${MAXIMUM_DRAWS} draws: its silhouette spans ${box.left},${box.top} to ${box.right},${box.bottom} of ${settings.size} px. Try a smaller padding or another view.`);}/**- * Draws one item until its silhouette is centred and inside the icon: a first guess from the bounding sphere, then each measured- * box moves the camera. With `fixedScale` the view height stays, so a set keeps one scale.+ * Draws one frame until its silhouette is centred and inside the icon: a first guess from the bounding sphere, then each measured+ * box moves the camera. With `fixedScale` the view height stays, so a set (or the views of one item) keeps one scale.*/-async function frameItem({ item, index, settings, startFraming, fixedScale, signal }) {- const { size, viewpoint: view, padding } = settings;+async function frameItem({ item, frame, settings, startFraming, fixedScale, signal }) {+ const { size, padding } = settings;let framing = startFraming;for (let draw = 1; draw <= MAXIMUM_DRAWS; draw++) {signal.throwIfAborted();- const image = decodePng(await item.draw(cameraForFraming(framing, view)));- if (image.width !== size || image.height !== size) throw new Error(`items[${index}] was drawn at ${image.width}x${image.height}, not ${size}x${size}. The render budget may have reduced the frame; raise --memory.`);+ const image = decodePng(await item.draw(cameraForFraming(framing, frame.view)));+ if (image.width !== size || image.height !== size) throw new Error(`${describeFrame(settings, frame)} was drawn at ${image.width}x${image.height}, not ${size}x${size}. The render budget may have reduced the frame; raise --memory.`);const box = alphaBounds(image.data, size, size);- if (!box) throw fixedScale === undefined ? drewNothingError(settings, index) : tooSmallForRelativeError(settings, index, fixedScale / startFraming.fittedScale);+ if (!box) throw fixedScale === undefined ? drewNothingError(settings, frame) : tooSmallForSharedScaleError(settings, frame, fixedScale / startFraming.fittedScale);if (isFramed(box, { size, padding, fit: fixedScale === undefined })) return { framing, image, box };- if (draw === MAXIMUM_DRAWS) throw notFramedError(settings, index, box);- framing = refineFraming(framing, box, { size, view, padding, fixedScale });+ if (draw === MAXIMUM_DRAWS) throw notFramedError(settings, frame, box);+ framing = refineFraming(framing, box, { size, view: frame.view, padding, fixedScale });}- throw notFramedError(settings, index, { left: 0, top: 0, right: 0, bottom: 0 });+ throw notFramedError(settings, frame, { left: 0, top: 0, right: 0, bottom: 0 });}function entryOf({ framing, box }) {return { bounds: { x: box.left, y: box.top, width: box.right - box.left, height: box.bottom - box.top }, viewHeight: Number(framing.orthoScale.toPrecision(7)) };}+/** The strip of one item: shaded, outline, hatching, final side by side, each drawn from the camera the final icon used. */+async function drawBreakdownStrip({ item, framed, settings }) {+ const { size } = settings;+ const strip = blankImage(size * BREAKDOWN_STEPS.length, size);+ const camera = cameraForFraming(framed.framing, framed.view);+ for (const [position, step] of BREAKDOWN_STEPS.entries()) {+ const panel = step === 'final' ? framed.image : decodePng(await item.drawStep(camera, step));+ copyIntoAtlas(strip, panel, position * size, 0);+ }+ return strip;+}+/**- * Runs the job. `openItem(item, index)` resolves to `{ bounds, draw(camera), close() }`: the item's world bounds, a function that- * draws it with a camera and returns a transparent PNG of the icon size, and a release. Returns the runner result the job store reads.+ * Runs the job. `openItem(item, index, frame)` resolves to `{ bounds, draw(camera), drawStep(camera, step), close() }`: the item's+ * world bounds, a function that draws it with a camera and returns a transparent PNG of the icon size, one that draws a step of the+ * sketch (outline, hatching or shaded) the same way, and a release. Returns the runner result the job store reads.*/export async function renderIconJob({ settings, directory, signal, progress, openItem }) {- const layout = layoutAtlas(settings.items.length, settings.size);+ const frames = iconFrames(settings);+ const layout = layoutAtlas(frames.length, settings.size, settings.angles > 1 ? settings.angles : undefined);const atlas = blankImage(layout.width, layout.height);const artifacts = [];+ const strips = [];const entries = [];const fitted = [];- async function withItem(index, work) {- const item = await openItem(settings.items[index], index);+ async function withItem(frame, work) {+ const item = await openItem(settings.items[frame.itemIndex], frame.itemIndex, frame);try { return await work(item); }finally { await item.close(); }}- async function keep(index, image, framed) {- copyIntoAtlas(atlas, image, layout.rectangles[index].x, layout.rectangles[index].y);- const filename = iconArtifactName(index);- await writeFile(join(directory, `${filename}.partial`), encodePng(image), { flag: 'wx' });- artifacts.push({ temporary: `${filename}.partial`, filename, mimeType: PNG_MIME });- entries[index] = entryOf(framed);+ async function writeArtifact(filename, bytes, mimeType = PNG_MIME) {+ await writeFile(join(directory, `${filename}.partial`), bytes, { flag: 'wx' });+ artifacts.push({ temporary: `${filename}.partial`, filename, mimeType });}- for (let index = 0; index < settings.items.length; index++) {+ async function keep(frameIndex, framed) {+ copyIntoAtlas(atlas, framed.image, layout.rectangles[frameIndex].x, layout.rectangles[frameIndex].y);+ await writeArtifact(iconArtifactName(frameIndex), encodePng(framed.image));+ entries[frameIndex] = entryOf(framed);+ }++ /** Frames one frame and, when it is the one a strip hangs on, draws the strip while its scene is still open. */+ async function drawFinal(frameIndex, startFor, fixedScale) {+ const frame = frames[frameIndex];+ return withItem(frame, async item => {+ const startFraming = startFor(item);+ const framed = { ...(await frameItem({ item, frame, settings, startFraming, fixedScale, signal })), view: frame.view };+ if (settings.breakdown && frame.angleIndex === 0) strips[frame.itemIndex] = await drawBreakdownStrip({ item, framed, settings });+ return framed;+ });+ }++ // One shared scale needs every frame measured first: the set's largest for relative, the item's largest view for a turnaround.+ const sharesScale = settings.scale === 'relative' || settings.angles > 1;+ for (let frameIndex = 0; frameIndex < frames.length; frameIndex++) {signal.throwIfAborted();- const framed = await withItem(index, async item => frameItem({ item, index, settings, startFraming: sphereFraming(item.bounds), signal }));- fitted[index] = framed.framing;- if (settings.scale === 'fit') await keep(index, framed.image, framed);- await progress({ frames: index + 1, maximumPendingFrames: 0 });+ const frame = frames[frameIndex];+ if (sharesScale) {+ const measured = await withItem(frame, item => frameItem({ item, frame, settings, startFraming: sphereFraming(item.bounds), signal }));+ fitted[frameIndex] = measured.framing;+ } else {+ await keep(frameIndex, await drawFinal(frameIndex, item => sphereFraming(item.bounds)));+ }+ await progress({ frames: frameIndex + 1, maximumPendingFrames: 0 });}- if (settings.scale === 'relative') {- const fixedScale = relativeScale(fitted.map(framing => framing.orthoScale));- for (let index = 0; index < settings.items.length; index++) {+ if (sharesScale) {+ const setScale = relativeScale(fitted.map(framing => framing.orthoScale));+ const itemScales = new Map();+ for (const [frameIndex, frame] of frames.entries()) {+ itemScales.set(frame.itemIndex, Math.max(itemScales.get(frame.itemIndex) ?? 0, fitted[frameIndex].orthoScale));+ }+ for (const [frameIndex, frame] of frames.entries()) {signal.throwIfAborted();- const startFraming = { ...fitted[index], fittedScale: fitted[index].orthoScale, orthoScale: fixedScale };- const framed = await withItem(index, item => frameItem({ item, index, settings, startFraming, fixedScale, signal }));- await keep(index, framed.image, framed);+ const fixedScale = settings.scale === 'relative' ? setScale : itemScales.get(frame.itemIndex);+ const startFraming = { ...fitted[frameIndex], fittedScale: fitted[frameIndex].orthoScale, orthoScale: fixedScale };+ await keep(frameIndex, await drawFinal(frameIndex, () => startFraming, fixedScale));}}- const atlasName = ICON_ARTIFACTS.atlas;- await writeFile(join(directory, `${atlasName}.partial`), encodePng(atlas), { flag: 'wx' });- artifacts.push({ temporary: `${atlasName}.partial`, filename: atlasName, mimeType: PNG_MIME });- const manifestName = ICON_ARTIFACTS.manifest;- await writeFile(join(directory, `${manifestName}.partial`), `${JSON.stringify(iconManifest({ settings, layout, entries }), null, 2)}\n`, { flag: 'wx' });- artifacts.push({ temporary: `${manifestName}.partial`, filename: manifestName, mimeType: 'application/json' });- return { artifacts, metrics: { icons: settings.items.length, atlasWidth: layout.width, atlasHeight: layout.height } };+ for (const [itemIndex, strip] of strips.entries()) {+ if (strip) await writeArtifact(breakdownArtifactName(itemIndex), encodePng(strip));+ }+ await writeArtifact(ICON_ARTIFACTS.atlas, encodePng(atlas));+ await writeArtifact(ICON_ARTIFACTS.manifest, `${JSON.stringify(iconManifest({ settings, layout, entries }), null, 2)}\n`, 'application/json');+ return { artifacts, metrics: { icons: frames.length, items: settings.items.length, atlasWidth: layout.width, atlasHeight: layout.height } };}diff --git a/scripts/agent-icon-page.mjs b/scripts/agent-icon-page.mjsindex 053b467e..7e5042d6 100644--- a/scripts/agent-icon-page.mjs+++ b/scripts/agent-icon-page.mjs@@ -1,5 +1,5 @@// The browser side of the `icons` job: one scene per item in the job page, drawn through the same preview API as every other job.-import { iconRecipe } from '../src/icon-sheet.js';+import { iconRecipe, sketchStagePass } from '../src/icon-sheet.js';import { renderIconJob } from './agent-icon-job.mjs';const SCREENSHOT_OPTIONS = { fromSurface: true, format: 'png', optimizeForSpeed: true };@@ -18,9 +18,9 @@ export async function renderIconsInPage({ jobPage, jobId, settings, directory, s});const metrics = { backend, requestedWidth: settings.size, requestedHeight: settings.size, drawCount: 0 };- async function openItem(item, index) {+ async function openItem(item, index, frame) {if (!item.asset) throw new Error(`items[${index}] (${item.source}) has no pinned asset id. The runtime pins catalog names when the job is submitted.`);- const recipe = iconRecipe({ assetId: item.asset, style: settings.style, view: settings.viewpoint, size: settings.size });+ const recipe = iconRecipe({ assetId: item.asset, style: settings.style, view: frame.view, size: settings.size, sketch: settings.sketch, seed: settings.seed });const input = { sessionId: jobId, recipe, memoryBudgetMiB, backend, transparent: true, ...(tier ? { tier } : {}), ...(await assetData(recipe)) };const created = await jobPage.evaluate(createInput => window.__agentPreview.create(createInput), input).catch(error => { throw new Error(`items[${index}] (${item.source}) could not be loaded: ${String(error.message).split('\n')[0]}`); });@@ -31,18 +31,27 @@ export async function renderIconsInPage({ jobPage, jobId, settings, directory, sconst inspected = await jobPage.evaluate(sessionId => window.__agentPreview.inspect({ sessionId }), jobId);const bounds = inspected.assets?.[0]?.bounds;if (!bounds) throw new Error(`items[${index}] (${item.source}) placed no geometry. Check that the GLB holds meshes.`);+ let revision = created.revision;+ async function draw(camera) {+ signal.throwIfAborted();+ const drawn = await jobPage.evaluate(drawInput => window.__agentPreview.frame(drawInput), { sessionId: jobId, camera });+ if (backend === 'cpu' && !/swiftshader/i.test(drawn.graphics)) throw new Error('CPU job did not select SwiftShader.');+ metrics.graphics = drawn.graphics;+ metrics.drawCount++;+ metrics.width = drawn.width;+ metrics.height = drawn.height;+ const captured = await cdp.send('Page.captureScreenshot', SCREENSHOT_OPTIONS);+ return Buffer.from(captured.data, 'base64');+ }return {bounds,- async draw(camera) {- signal.throwIfAborted();- const frame = await jobPage.evaluate(drawInput => window.__agentPreview.frame(drawInput), { sessionId: jobId, camera });- if (backend === 'cpu' && !/swiftshader/i.test(frame.graphics)) throw new Error('CPU job did not select SwiftShader.');- metrics.graphics = frame.graphics;- metrics.drawCount++;- metrics.width = frame.width;- metrics.height = frame.height;- const captured = await cdp.send('Page.captureScreenshot', SCREENSHOT_OPTIONS);- return Buffer.from(captured.data, 'base64');+ draw,+ // A step of the sketch changes the pass's stage value, which is a uniform, so nothing recompiles.+ async drawStep(camera, step) {+ const operations = [{ type: 'set-post-passes', postPasses: [sketchStagePass({ sketch: settings.sketch, seed: settings.seed, size: settings.size, stage: step })] }];+ const applied = await jobPage.evaluate(applyInput => window.__agentPreview.apply(applyInput), { sessionId: jobId, operations, expectedRevision: revision });+ revision = applied.revision;+ return draw(camera);},async close() {await jobPage.evaluate(sessionId => window.__agentPreview.dispose({ sessionId }), jobId);diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjsindex 31f92bbf..877d67e2 100644--- a/scripts/agent-render-jobs.mjs+++ b/scripts/agent-render-jobs.mjs@@ -28,11 +28,25 @@ const DEFAULT_LIMITS = Object.freeze({ maxRecords: 32, maxStoreBytes: 512 * 1024/** Time the page needs to start, draw the scene and encode the PNG around a path trace that runs for its whole maxSeconds. */const PATH_TRACE_OVERHEAD_MS = 60 * 1000;+const ICON_FRAME_ALLOWANCE_MS = 4000;+const ICON_BREAKDOWN_ALLOWANCE_MS = 6000;++/**+ * An icon is its own scene: the job loads the GLB and draws it up to four times to frame it, and draws it all again when the+ * set shares one scale (relative, or several angles). A breakdown adds three draws of each item. Measured on the cpu backend+ * at about 5 s per icon with a breakdown and 3 s without.+ */+function iconDeadlineMs({ frameCount, scale, angles, breakdown, items }) {+ const passes = scale === 'relative' || angles > 1 ? 2 : 1;+ return BASE_DEADLINE_MS + frameCount * ICON_FRAME_ALLOWANCE_MS * passes + (breakdown ? items.length * ICON_BREAKDOWN_ALLOWANCE_MS : 0);+}+/*** 60 s plus 2 s per frame, scaled up for frames larger than 1024x576, never above the ceiling. A path trace may run for* its own maxSeconds on every frame, so its deadline also reaches that plus the overhead and the trace stops itself first.*/-export function jobDeadlineMs({ frameCount, width, height, renderer }, maximumMs = MAXIMUM_JOB_DEADLINE_MS) {+export function jobDeadlineMs({ kind, frameCount, width, height, renderer, scale, angles, breakdown, items }, maximumMs = MAXIMUM_JOB_DEADLINE_MS) {+ if (kind === 'icons') return Math.min(maximumMs, iconDeadlineMs({ frameCount, scale, angles, breakdown, items }));const sizeScale = Math.max(1, (width * height) / REFERENCE_FRAME_PIXELS);const frameDeadline = Math.ceil(BASE_DEADLINE_MS + frameCount * FRAME_ALLOWANCE_MS * sizeScale);const traceDeadline = renderer?.type === 'pathTracer' ? Math.ceil(renderer.maxSeconds * 1000 * frameCount) + PATH_TRACE_OVERHEAD_MS : 0;@@ -304,10 +318,10 @@ function passesFrom(passes, kind) {}/** Every artifact filename of a job, lit image first and then each requested pass, frame by frame. */-export function artifactNames(kind, passes = [], format = 'png', multilayer = false, stillCount = 8) {+export function artifactNames(kind, passes = [], format = 'png', multilayer = false, stillCount = 8, iconSettings = {}) {if (kind === 'video') return ['render.mp4'];- // An icons job has one frame per item, so its frame count is its item count.- if (kind === 'icons') return iconArtifactNames(stillCount);+ // An icons job has one frame per icon (an item at one angle); a breakdown adds one strip per item.+ if (kind === 'icons') return iconArtifactNames(stillCount, { itemCount: iconSettings.breakdown ? iconSettings.items.length : 0 });const extension = format === 'exr' ? 'exr' : 'png';const stems = kind === 'image' ? ['render'] : Array.from({ length: stillCount }, (_, index) => `frame-${index}`);if (multilayer) return stems.map(stem => `${stem}.${extension}`);@@ -354,7 +368,7 @@ function artifactByteLimit(settings, limits) {function allowedFile(name) {const passNames = RENDER_PASS_NAMES.join('|');- const artifact = new RegExp(`^(?:render\\.(?:png|mp4|exr)|(?:icon-\\d{1,3}|atlas)\\.png|icons\\.json|(?:render|frame-\\d{1,3})(?:-(?:${passNames}))?\\.(?:png|exr))(?:\\.partial)?$`);+ const artifact = new RegExp(`^(?:render\\.(?:png|mp4|exr)|(?:icon-\\d{1,3}|breakdown-\\d{1,3}|atlas)\\.png|icons\\.json|(?:render|frame-\\d{1,3})(?:-(?:${passNames}))?\\.(?:png|exr))(?:\\.partial)?$`);return INTERNAL_FILES.has(name) || artifact.test(name);}@@ -842,7 +856,7 @@ export async function createAgentRenderJobs({ root, run, acquireGpu, limits: inpboundedNumber(record.progress.maximumPendingFrames, 0, 1, 'persisted pending frames', true);if (record.metrics !== undefined) record.metrics = jsonCopy(record.metrics, 65536);if (record.reason !== undefined && (typeof record.reason !== 'string' || record.reason.length > 2048)) throw new Error('Invalid persisted job reason.');- const namesAllowed = artifactNames(settings.kind, settings.passes, settings.format, settings.multilayer, settings.frameCount);+ const namesAllowed = artifactNames(settings.kind, settings.passes, settings.format, settings.multilayer, settings.frameCount, settings);if (!Array.isArray(record.artifacts) || record.artifacts.length > namesAllowed.length) throw new Error('Invalid persisted artifacts.');const seen = new Set();for (const artifact of record.artifacts) {@@ -925,7 +939,7 @@ export async function createAgentRenderJobs({ root, run, acquireGpu, limits: inprecord.state = 'finalizing';await persist(job);objectKeys(completed, ['artifacts', 'metrics'], 'runner result');- const expected = artifactNames(record.settings.kind, record.settings.passes, record.settings.format, record.settings.multilayer, record.settings.frameCount);+ const expected = artifactNames(record.settings.kind, record.settings.passes, record.settings.format, record.settings.multilayer, record.settings.frameCount, record.settings);if (!Array.isArray(completed.artifacts) || completed.artifacts.length !== expected.length) throw new Error('Runner did not return the required fixed artifacts.');const directory = await directoryFor(record.jobId);const metrics = jsonCopy(completed.metrics ?? {}, 65536);diff --git a/scripts/icons-mcp-client.mjs b/scripts/icons-mcp-client.mjsnew file mode 100644index 00000000..7a63c2bc--- /dev/null+++ b/scripts/icons-mcp-client.mjs@@ -0,0 +1,64 @@+// Runs `icons` render jobs through the MCP server on the cpu backend, for the smoke script and the tests that need real pixels.+// const server = await startIconsServer({ assets: '<folder of .glb files>' });+// const { artifacts, manifest } = await server.runJob({ items: ['a.glb'], size: 64, style: 'sketch' });+// await server.close();+import assert from 'node:assert/strict';+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';++const COMMAND_LINE_INTERFACE = fileURLToPath(new URL('../bin/crucible-mcp.mjs', import.meta.url));+const FINISHED_STATES = ['completed', 'failed', 'cancelled'];+const JOB_TIMEOUT_MS = 580000;+const EMPTY_SCENE = { format: 'crucible.scene', schemaVersion: 1, geometries: [{ id: 'g', type: 'box' }], materials: [{ id: 'm' }], nodes: [{ id: 'n', geometry: 'g', material: 'm' }] };++/** Starts the MCP server on the cpu backend over a folder of GLB files. `close()` stops it and removes its job folder. */+export async function startIconsServer({ assets, memory = 256 }) {+ const workFolder = await mkdtemp(join(tmpdir(), 'crucible-icons-'));+ const transport = new StdioClientTransport({+ command: process.execPath,+ args: [COMMAND_LINE_INTERFACE, '--backend', 'cpu', '--memory', String(memory), '--assets', resolve(assets), '--jobs', join(workFolder, 'jobs')],+ stderr: 'pipe',+ });+ let diagnostics = '';+ transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-4096); });+ const client = new Client({ name: 'crucible-icons-proof', version: '1' });+ await client.connect(transport);++ async function call(name, argumentsValue = {}) {+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: JOB_TIMEOUT_MS });+ assert.equal(result.isError, undefined, `${result.content?.find(item => item.type === 'text')?.text}\n${diagnostics}`);+ return result.structuredContent;+ }++ async function runJob(settings) {+ const created = await call('scene_create', { recipe: EMPTY_SCENE });+ const submitted = await call('scene_render_submit', { sessionId: created.sessionId, expectedRevision: 0, settings: { kind: 'icons', ...settings } });+ const deadline = Date.now() + JOB_TIMEOUT_MS;+ for (;;) {+ const record = await call('scene_render_status', { jobId: submitted.jobId });+ if (FINISHED_STATES.includes(record.state)) {+ assert.equal(record.state, 'completed', `${record.reason}\n${diagnostics}`);+ break;+ }+ assert.ok(Date.now() < deadline, 'The icons job did not finish in time.');+ await new Promise(done => setTimeout(done, 300));+ }+ const result = await call('scene_render_result', { jobId: submitted.jobId });+ const artifacts = new Map(result.artifacts.map(artifact => [artifact.filename, artifact.path]));+ const manifest = JSON.parse(await readFile(artifacts.get('icons.json'), 'utf8'));+ return { jobId: submitted.jobId, artifacts, manifest, metrics: result.metrics };+ }++ return {+ runJob,+ call,+ async close() {+ await client.close();+ await rm(workFolder, { recursive: true, force: true });+ },+ };+}diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 5a14a528..aa006e42 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -871,10 +871,14 @@ const renderSettings = z.strictObject({height: z.number().int().min(64).max(MAXIMUM_JOB_SIDE).optional(),items: z.array(z.string().max(260)).min(1).max(256).optional().describe('icons: 1 to 256 catalog GLB names or asset ids; one transparent PNG each, plus atlas.png and icons.json. scene_capabilities jobs.icons.'),size: z.union([z.literal(64), z.literal(128), z.literal(256), z.literal(512)]).optional().describe('icons: pixels per icon side (default 256).'),- style: z.enum(['clean', 'toon', 'sketch']).optional().describe('icons: clean (default) or toon; sketch is coming.'),+ style: z.enum(['clean', 'toon', 'sketch']).optional().describe('icons: clean (default), toon or sketch (ink outline and pencil hatching).'),viewpoint: z.union([z.literal('three-quarter'), z.strictObject({ azimuth: z.number().optional(), elevation: z.number().optional() })]).optional().describe('icons: three-quarter (default) or azimuth and elevation in degrees.'),scale: z.enum(['fit', 'relative']).optional().describe('icons: fit fills every icon; relative keeps one scale for the set.'),padding: z.number().optional().describe('icons: border as a fraction of the icon, 0.02 to 0.4 (default 0.08).'),+ angles: z.union([z.literal(1), z.literal(4), z.literal(8)]).optional().describe('icons: views around each item; 4 or 8 give a turnaround row per item.'),+ breakdown: z.boolean().optional().describe('icons, sketch: also write breakdown-<item>.png, the steps side by side.'),+ seed: z.number().int().min(0).max(65535).optional().describe('icons, sketch: seed of the pencil wobble (default 0).'),+ sketch: z.strictObject({ inkColor: z.string().max(7).optional(), paperColor: z.string().max(7).optional(), hatchDensity: z.number().optional(), jitter: z.number().optional() }).optional().describe('icons, sketch: #rrggbb colours, hatchDensity 0.5 to 2, jitter 0 to 1.'),fps: z.number().int().min(1).max(MAXIMUM_JOB_FPS).optional(),duration: z.number().min(0.1).max(60).optional(),animation: z.strictObject({ clip: z.number().int().min(0), start: z.number().min(0).max(3600).optional() }).optional(),diff --git a/scripts/smoke-icons.mjs b/scripts/smoke-icons.mjsindex e786eb9f..2983a144 100644--- a/scripts/smoke-icons.mjs+++ b/scripts/smoke-icons.mjs@@ -1,14 +1,15 @@// Renders every GLB of a folder as icons through the MCP server on the cpu backend and copies the files to --out.-// node scripts/smoke-icons.mjs --assets <folder of .glb files> --out <folder> [--style clean|toon] [--scale fit|relative] [--size 128] [--twice]+// node scripts/smoke-icons.mjs --assets <folder of .glb files> --out <folder> [--style clean|toon|sketch] [--scale fit|relative]+// [--size 128] [--angles 1|4|8] [--breakdown] [--seed 0] [--only a.glb,b.glb] [--twice]// Checks each icon's alpha box against the frame (inside it, centred) and, with --twice, that a second job writes the same bytes.+// With --breakdown it measures the outline and the hatching of every strip (src/icon-sketch.js) and prints them.import assert from 'node:assert/strict';import { createHash } from 'node:crypto';import { copyFile, mkdir, readdir, readFile } from 'node:fs/promises';-import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';-import { Client } from '@modelcontextprotocol/client';-import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';-import { mkdtemp } from 'node:fs/promises';+import { decodePng } from './agent-icon-png.mjs';+import { startIconsServer } from './icons-mcp-client.mjs';+import { hexLuma, measureHatchBand, measureOutline } from '../src/icon-sketch.js';const argumentsGiven = process.argv.slice(2);function option(name, fallback) {@@ -20,63 +21,60 @@ const output = resolve(option('out', 'artifacts/icons'));const style = option('style', 'clean');const scale = option('scale', 'fit');const size = Number(option('size', 128));+const angles = Number(option('angles', 1));+const seed = Number(option('seed', 0));+const breakdown = argumentsGiven.includes('--breakdown');const runTwice = argumentsGiven.includes('--twice');-const names = (await readdir(assets)).filter(name => name.endsWith('.glb')).sort();+const only = option('only', undefined)?.split(',');+const names = (await readdir(assets)).filter(name => name.endsWith('.glb') && (!only || only.includes(name))).sort();assert.ok(names.length, `No .glb files in ${assets}.`);-const jobs = join(await mkdtemp(join(tmpdir(), 'crucible-icons-')), 'jobs');-const cli = resolve('bin/crucible-mcp.mjs');-const transport = new StdioClientTransport({ command: process.execPath, args: [cli, '--backend', 'cpu', '--memory', '256', '--assets', assets, '--jobs', jobs], stderr: 'pipe' });-let diagnostics = '';-transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-4096); });-const client = new Client({ name: 'crucible-icons-proof', version: '1' });-async function call(name, argumentsValue = {}) {- const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 600000 });- assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);- return result.structuredContent;+const settings = { items: names, size, style, scale, ...(angles > 1 ? { angles } : {}), ...(breakdown ? { breakdown } : {}), ...(style === 'sketch' ? { seed } : {}) };+const digest = async path => createHash('sha256').update(await readFile(path)).digest('hex');+const server = await startIconsServer({ assets });++async function printSketchMeasures(manifest, artifacts) {+ const paperLuma = hexLuma(manifest.sketch.paperColor);+ const inkLuma = hexLuma(manifest.sketch.inkColor);+ for (const icon of manifest.icons.filter(entry => entry.breakdown)) {+ const strip = decodePng(await readFile(artifacts.get(icon.breakdown)));+ const panel = position => ({ width: size, height: size, data: panelPixels(strip, position), paperLuma, inkLuma });+ const outline = measureOutline(panel(1));+ const hatch = measureHatchBand(panel(2));+ console.log(icon.name.padEnd(24), `outline inked ${outline.inkedShare.toFixed(2)}`, hatch ? `hatch contrast ${hatch.contrast.toFixed(2)} bimodal ${hatch.bimodal.toFixed(2)} coverage ${hatch.coverage.toFixed(2)} (${hatch.pixels} px)` : 'no hatching');+ }}-async function runJob() {- const created = await call('scene_create', { recipe: { format: 'crucible.scene', schemaVersion: 1, geometries: [{ id: 'g', type: 'box' }], materials: [{ id: 'm' }], nodes: [{ id: 'n', geometry: 'g', material: 'm' }] } });- const submitted = await call('scene_render_submit', { sessionId: created.sessionId, expectedRevision: 0, settings: { kind: 'icons', items: names, size, style, scale } });- const deadline = Date.now() + 580000;- for (;;) {- const record = await call('scene_render_status', { jobId: submitted.jobId });- if (['completed', 'failed', 'cancelled'].includes(record.state)) {- assert.equal(record.state, 'completed', record.reason);- break;- }- assert.ok(Date.now() < deadline, 'The icons job did not finish in time.');- await new Promise(done => setTimeout(done, 500));+/** The RGBA bytes of the n-th square panel of a strip. */+function panelPixels(strip, position) {+ const data = Buffer.alloc(size * size * 4);+ for (let row = 0; row < size; row++) {+ strip.data.copy(data, row * size * 4, (row * strip.width + position * size) * 4, (row * strip.width + (position + 1) * size) * 4);}- const result = await call('scene_render_result', { jobId: submitted.jobId });- return { jobId: submitted.jobId, artifacts: result.artifacts };+ return data;}-const digest = async path => createHash('sha256').update(await readFile(path)).digest('hex');try {- await client.connect(transport);- const first = await runJob();+ const first = await server.runJob(settings);await mkdir(output, { recursive: true });- for (const artifact of first.artifacts) await copyFile(artifact.path, join(output, artifact.filename));- const manifest = JSON.parse(await readFile(join(output, 'icons.json'), 'utf8'));- for (const icon of manifest.icons) {+ for (const [filename, path] of first.artifacts) await copyFile(path, join(output, filename));+ for (const icon of first.manifest.icons) {const { x, y, width, height } = icon.bounds;assert.ok(x >= 1 && y >= 1 && x + width <= size - 1 && y + height <= size - 1, `${icon.name} touches the frame edge: ${JSON.stringify(icon.bounds)}`);- console.log(icon.name.padEnd(28), JSON.stringify(icon.bounds), `view height ${icon.viewHeight}`);+ console.log(icon.name.padEnd(24), String(icon.angle).padStart(5), JSON.stringify(icon.bounds), `view height ${icon.viewHeight}`);}+ if (breakdown) await printSketchMeasures(first.manifest, first.artifacts);if (runTwice) {- const second = await runJob();- for (const artifact of first.artifacts) {- const other = second.artifacts.find(candidate => candidate.filename === artifact.filename);- assert.equal(await digest(artifact.path), await digest(other.path), `${artifact.filename} differs between two runs`);+ const second = await server.runJob(settings);+ for (const [filename, path] of first.artifacts) {+ assert.equal(await digest(path), await digest(second.artifacts.get(filename)), `${filename} differs between two runs`);}- console.log(`${first.artifacts.length} files are byte-identical across two jobs`);+ console.log(`${first.artifacts.size} files are byte-identical across two jobs`);}- console.log(`wrote ${first.artifacts.length} files to ${output}`);+ console.log(`wrote ${first.artifacts.size} files to ${output}`);} catch (error) {- console.error(error.message, diagnostics);+ console.error(error.message);process.exitCode = 1;} finally {- await client.close();+ await server.close();}diff --git a/src/documentation-topics.js b/src/documentation-topics.jsindex db1d479a..e97489f5 100644--- a/src/documentation-topics.js+++ b/src/documentation-topics.js@@ -6,7 +6,7 @@ export const documentationGroups = [{ title: 'Model and fit surfaces', icon: 'cube', ids: ['procedural-modeling', 'sculpt-brushes', 'contact-detection', 'shrinkwrap-and-surface-patches', 'retained-surface-attachments'] },{ title: 'Worlds', icon: 'world', ids: ['terrain-and-ground-textures', 'trees-and-grass', 'grass-fields', 'wheeled-vehicles', 'baked-liquid'] },{ title: 'Animate and interact', icon: 'motion', ids: ['deterministic-animation', 'animation-curves-and-mixing', 'skeletal-and-morph-animation', 'humanoid-retargeting-and-crowds', 'recorded-physics', 'assemblies-and-interaction'] },- { title: 'Assets and media', icon: 'image', ids: ['import-and-export-models', 'images-and-films', 'render-a-png-from-a-script-without-mcp'] },+ { title: 'Assets and media', icon: 'image', ids: ['import-and-export-models', 'images-and-films', 'icon-sheets', 'render-a-png-from-a-script-without-mcp'] },{ title: 'Reference and workflows', icon: 'book', ids: ['api-reference', 'performance-and-memory', 'lifecycle-and-troubleshooting', 'connect-mcp', 'agent-workflows', 'optimize-for-agents', 'models-and-ai-agents', 'addons-and-limits', 'release-and-source-availability', 'resources'] },];diff --git a/src/icon-sheet.js b/src/icon-sheet.jsindex ead1f800..22a1190e 100644--- a/src/icon-sheet.js+++ b/src/icon-sheet.js@@ -1,12 +1,15 @@// Icon sheets: the pure part of the `icons` render job (docs/agent-render-jobs.md, "Icons"). Validation of the job settings, the camera// and light rig, the framing arithmetic that fits one silhouette, the atlas layout and the icons.json manifest. No browser, no files.import { invalidField } from './field-error.js';+import { BREAKDOWN_ORDER, SKETCH_CAPABILITIES, normalizeSketchSettings, seedFrom, sketchPass } from './icon-sketch.js';export const ICON_LIMITS = Object.freeze({maximumItems: 256,sizes: Object.freeze([64, 128, 256, 512]),- styles: Object.freeze(['clean', 'toon']),+ styles: Object.freeze(['clean', 'toon', 'sketch']),scales: Object.freeze(['fit', 'relative']),+ angles: Object.freeze([1, 4, 8]),+ maximumFrames: 256,maximumAtlasSide: 4096,minimumPadding: 0.02,maximumPadding: 0.4,@@ -17,8 +20,6 @@ export const ICON_LIMITS = Object.freeze({/** What `icons` leaves out of this release, named so an error can say it is coming and not that it is unknown. */const COMING_FIELDS = Object.freeze({- angles: 'turnaround sheets (angles 4 or 8)',- breakdown: 'the step-by-step strip',lighting: 'an HDRI rig (the three-point rig is fixed)',background: 'a background colour (icons are transparent)',outline: 'an outline colour and width',@@ -27,7 +28,8 @@ const COMING_FIELDS = Object.freeze({const ASSET_ID = /^[0-9a-f]{64}$/;const URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;const DERIVED_FIELDS = ['width', 'height', 'fps', 'duration', 'transparent'];-const SETTING_FIELDS = ['kind', 'items', 'size', 'style', 'viewpoint', 'scale', 'padding', ...DERIVED_FIELDS];+const SETTING_FIELDS = ['kind', 'items', 'size', 'style', 'viewpoint', 'scale', 'padding', 'angles', 'breakdown', 'seed', 'sketch', ...DERIVED_FIELDS];+const SKETCH_ONLY_FIELDS = ['sketch', 'seed'];const MAXIMUM_ITEM_LENGTH = 260;export const ICON_ARTIFACTS = Object.freeze({ atlas: 'atlas.png', manifest: 'icons.json' });@@ -36,9 +38,19 @@ export function iconArtifactName(index) {return `icon-${index}.png`;}-/** Every artifact of an icons job, in the order the runner writes them: one PNG per item, the atlas, then icons.json. */-export function iconArtifactNames(itemCount) {- return [...Array.from({ length: itemCount }, (_, index) => iconArtifactName(index)), ICON_ARTIFACTS.atlas, ICON_ARTIFACTS.manifest];+/** The breakdown strip of one item. The job folder is flat, so the item number is in the name and not in a folder. */+export function breakdownArtifactName(itemIndex) {+ return `breakdown-${itemIndex}.png`;+}++/**+ * Every artifact of an icons job, in the order the runner writes them: one PNG per frame (an item at one angle), the breakdown+ * strip of each item when asked, the atlas, then icons.json. `options.itemCount` names how many items get a strip; leave it out for none.+ */+export function iconArtifactNames(frameCount, options = {}) {+ const frames = Array.from({ length: frameCount }, (_, index) => iconArtifactName(index));+ const strips = Array.from({ length: options.itemCount ?? 0 }, (_, index) => breakdownArtifactName(index));+ return [...frames, ...strips, ICON_ARTIFACTS.atlas, ICON_ARTIFACTS.manifest];}/** How many items fit one atlas at this size: a square grid no wider than the atlas limit. */@@ -46,6 +58,16 @@ export function atlasCapacity(size) {return (ICON_LIMITS.maximumAtlasSide / size) ** 2;}+/**+ * How many items one job takes at this size and angle count. One angle packs a square grid. More angles give each item a row+ * of its own (one cell per angle), so the rows must fit the atlas side, and so must the cells of a row.+ */+export function itemCapacity(size, angles) {+ if (angles === 1) return Math.min(ICON_LIMITS.maximumFrames, atlasCapacity(size));+ if (angles * size > ICON_LIMITS.maximumAtlasSide) return 0;+ return Math.min(Math.floor(ICON_LIMITS.maximumFrames / angles), Math.floor(ICON_LIMITS.maximumAtlasSide / size));+}+function itemFrom(item, position) {const label = `items[${position}]`;if (typeof item === 'string') item = { source: item };@@ -103,13 +125,25 @@ export function normalizeIconSettings(input) {}const size = input.size ?? 256;if (!ICON_LIMITS.sizes.includes(size)) throw invalidField('size', size, `one of ${ICON_LIMITS.sizes.join(', ')} (pixels per icon side)`, RangeError);- const capacity = atlasCapacity(size);+ const angles = input.angles ?? 1;+ if (!ICON_LIMITS.angles.includes(angles)) throw invalidField('angles', String(angles), `one of ${ICON_LIMITS.angles.join(', ')} (views around the item; 4 and 8 give a turnaround row per item)`, RangeError);+ const capacity = itemCapacity(size, angles);if (input.items.length > capacity) {- throw invalidField('items', input.items.length, `at most ${capacity} items at size ${size} (the atlas side is capped at ${ICON_LIMITS.maximumAtlasSide} px), or a smaller size`, RangeError);+ const reason = angles === 1 ? `the atlas side is capped at ${ICON_LIMITS.maximumAtlasSide} px` : `${angles} angles make one row of ${angles} icons per item, and a job holds ${ICON_LIMITS.maximumFrames} icons and an atlas side of ${ICON_LIMITS.maximumAtlasSide} px`;+ throw invalidField('items', input.items.length, `at most ${capacity} items at size ${size} with ${angles} angle${angles === 1 ? '' : 's'} (${reason}), or a smaller size or fewer angles`, RangeError);}const style = input.style ?? 'clean';- if (style === 'sketch') throw invalidField('style', 'sketch', 'clean or toon: the sketch style is coming (issue #2031)', RangeError);if (!ICON_LIMITS.styles.includes(style)) throw invalidField('style', String(style), `one of ${ICON_LIMITS.styles.join(', ')}`, RangeError);+ if (style !== 'sketch') {+ for (const field of SKETCH_ONLY_FIELDS) {+ if (input[field] !== undefined) throw invalidField(field, 'a field of the sketch style', `no ${field} unless style is "sketch" (the style is ${style})`, RangeError);+ }+ }+ if (input.breakdown !== undefined && typeof input.breakdown !== 'boolean') throw invalidField('breakdown', typeof input.breakdown, 'true or false', TypeError);+ const breakdown = input.breakdown ?? false;+ if (breakdown && style !== 'sketch') {+ throw invalidField('breakdown', 'true', `a style that is drawn in steps: set style to "sketch" (the style is ${style}); clean and toon have no steps to show`, RangeError);+ }const scale = input.scale ?? 'fit';if (!ICON_LIMITS.scales.includes(scale)) throw invalidField('scale', String(scale), `fit (every item fills its frame) or relative (one scale for the set)`, RangeError);const padding = input.padding ?? ICON_LIMITS.defaultPadding;@@ -117,7 +151,31 @@ export function normalizeIconSettings(input) {throw invalidField('padding', padding, `a fraction of the icon side from ${ICON_LIMITS.minimumPadding} to ${ICON_LIMITS.maximumPadding}`, RangeError);}const items = input.items.map(itemFrom);- return { kind: 'icons', size, width: size, height: size, fps: 1, duration: 1, frameCount: items.length, transparent: true, items, style, viewpoint: viewFrom(input.viewpoint), scale, padding };+ const settings = {+ kind: 'icons', size, width: size, height: size, fps: 1, duration: 1, frameCount: items.length * angles, transparent: true,+ items, style, viewpoint: viewFrom(input.viewpoint), scale, padding, angles,+ };+ if (breakdown) settings.breakdown = true;+ if (style === 'sketch') Object.assign(settings, { sketch: normalizeSketchSettings(input.sketch), seed: seedFrom(input.seed) });+ return settings;+}++/** The azimuth of the k-th of `angles` views around the item, in degrees from -180 to 180, starting at the base azimuth. */+export function turnaroundAzimuth(baseAzimuth, angleIndex, angles) {+ const turned = (baseAzimuth + angleIndex * 360 / angles) % 360;+ return turned > 180 ? turned - 360 : turned <= -180 ? turned + 360 : turned;+}++/**+ * Every icon the job draws, item by item and angle by angle (the order of icon-<n>.png and of the atlas): the item, the angle+ * number and the view. An item at one angle is one frame.+ */+export function iconFrames(settings) {+ return settings.items.flatMap((item, itemIndex) => Array.from({ length: settings.angles }, (_, angleIndex) => ({+ itemIndex,+ angleIndex,+ view: { azimuth: turnaroundAzimuth(settings.viewpoint.azimuth, angleIndex, settings.angles), elevation: settings.viewpoint.elevation },+ })));}/** The lowercase unit vector from the subject toward the camera, and the camera's right and up axes, for a azimuth and elevation in degrees. */@@ -173,13 +231,26 @@ export function toonLineWidth(size) {return Math.max(0.75, size / 128);}-/** The scene recipe that draws one catalog asset as an icon: the asset at the origin, the light rig, and line art for toon. */-export function iconRecipe({ assetId, style, view, size }) {+/**+ * The scene recipe that draws one catalog asset as an icon: the asset at the origin, the light rig, line art for toon, and for+ * sketch the sketch user pass. `sketch` and `seed` are the job's normalized settings; `stage` is a step of the breakdown strip.+ */+export function iconRecipe({ assetId, style, view, size, sketch, seed = 0, stage = 'final' }) {const environment = lightRigEnvironment(view);if (style === 'toon') environment.lines = { width: toonLineWidth(size), toon: 3 };- return { format: 'crucible.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [{ id: 'icon', asset: { id: assetId } }], environment };+ const recipe = { format: 'crucible.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [{ id: 'icon', asset: { id: assetId } }], environment };+ if (style === 'sketch') recipe.postPasses = [sketchPass({ settings: { sketch, seed }, size, stage })];+ return recipe;}+/** The sketch pass of one breakdown step, for `set-post-passes` on a session that already holds the item. */+export function sketchStagePass({ sketch, seed, size, stage }) {+ return sketchPass({ settings: { sketch, seed }, size, stage });+}++/** The steps of a breakdown strip, left to right. */+export const BREAKDOWN_STEPS = BREAKDOWN_ORDER;+/** The pixel box of the pixels whose alpha passes `threshold`, with exclusive right and bottom, or null when nothing is drawn. */export function alphaBounds(rgba, width, height, threshold = 1) {let left = width;@@ -230,9 +301,8 @@ export function relativeScale(fittedScales) {return Math.max(...fittedScales);}-/** A square grid of cells, row by row: the atlas rectangle of every item. */-export function layoutAtlas(count, size) {- const columns = Math.ceil(Math.sqrt(count));+/** A grid of cells, row by row: the atlas rectangle of every frame. Near square unless `columns` is given (a turnaround sheet has one column per angle). */+export function layoutAtlas(count, size, columns = Math.ceil(Math.sqrt(count))) {const rows = Math.ceil(count / columns);const rectangles = Array.from({ length: count }, (_, index) => ({ x: index % columns * size, y: Math.floor(index / columns) * size, width: size, height: size }));return { columns, rows, width: columns * size, height: rows * size, rectangles };@@ -256,16 +326,23 @@ export function iconManifest({ settings, layout, entries }) {scale: settings.scale,padding: settings.padding,viewpoint: settings.viewpoint,+ angles: settings.angles,+ ...(settings.style === 'sketch' ? { sketch: settings.sketch, seed: settings.seed } : {}),atlas: { file: ICON_ARTIFACTS.atlas, width: layout.width, height: layout.height, columns: layout.columns, rows: layout.rows },- icons: settings.items.map((item, index) => ({- name: names[index],- file: iconArtifactName(index),- source: item.source,- asset: item.asset,- angle: settings.viewpoint.azimuth,- rect: layout.rectangles[index],- bounds: entries[index].bounds,- viewHeight: entries[index].viewHeight,+ // One entry per frame. `angle` is the azimuth in degrees the frame is drawn from; `item` and `turn` say which item and which+ // of its views it is. The strip of an item hangs on its first view (turn 0).+ icons: iconFrames(settings).map(({ itemIndex, angleIndex, view }, frameIndex) => ({+ name: names[itemIndex],+ file: iconArtifactName(frameIndex),+ source: settings.items[itemIndex].source,+ asset: settings.items[itemIndex].asset,+ item: itemIndex,+ turn: angleIndex,+ angle: view.azimuth,+ rect: layout.rectangles[frameIndex],+ bounds: entries[frameIndex].bounds,+ viewHeight: entries[frameIndex].viewHeight,+ ...(settings.breakdown && angleIndex === 0 ? { breakdown: breakdownArtifactName(itemIndex) } : {}),})),};}@@ -273,15 +350,18 @@ export function iconManifest({ settings, layout, entries }) {/** What `scene_capabilities` jobs reports for kind icons: the limits the validator enforces and the files a job writes. */export const ICON_CAPABILITIES = Object.freeze({kind: 'icons',- note: 'settings.kind icons draws each item (a catalog GLB name or asset id from scene_asset_catalog) as a transparent square icon with an orthographic three-quarter view, a fixed three-point light rig and a silhouette fit. Writes icon-<n>.png per item, atlas.png and icons.json (name, atlas rect, source, bounds). The submitted scene is not drawn.',+ note: 'settings.kind icons draws each item (a catalog GLB name or asset id from scene_asset_catalog) as a transparent square icon with an orthographic three-quarter view, a fixed three-point light rig and a silhouette fit. Writes icon-<n>.png per item and angle, atlas.png and icons.json (name, angle, atlas rect, source, bounds). angles 4 or 8 turns each item around into a row of the atlas. The submitted scene is not drawn.',maximumItems: ICON_LIMITS.maximumItems,+ maximumIcons: ICON_LIMITS.maximumFrames,sizes: ICON_LIMITS.sizes,styles: ICON_LIMITS.styles,- comingStyles: Object.freeze(['sketch']),+ angles: ICON_LIMITS.angles,+ sketch: SKETCH_CAPABILITIES,scales: ICON_LIMITS.scales,viewpoint: Object.freeze({ default: 'three-quarter', azimuth: ICON_LIMITS.defaultView.azimuth, elevation: ICON_LIMITS.defaultView.elevation, maximumElevation: ICON_LIMITS.maximumElevation }),padding: Object.freeze({ default: ICON_LIMITS.defaultPadding, minimum: ICON_LIMITS.minimumPadding, maximum: ICON_LIMITS.maximumPadding }),maximumAtlasSide: ICON_LIMITS.maximumAtlasSide,- itemsPerSize: Object.freeze(Object.fromEntries(ICON_LIMITS.sizes.map(size => [size, Math.min(ICON_LIMITS.maximumItems, atlasCapacity(size))]))),+ itemsPerSize: Object.freeze(Object.fromEntries(ICON_LIMITS.sizes.map(size => [size, itemCapacity(size, 1)]))),+ itemsPerSizeAndAngles: Object.freeze(Object.fromEntries(ICON_LIMITS.angles.filter(angles => angles > 1).map(angles => [angles, Object.freeze(Object.fromEntries(ICON_LIMITS.sizes.map(size => [size, itemCapacity(size, angles)])))]))),notYet: Object.freeze(Object.keys(COMING_FIELDS)),});diff --git a/src/icon-sketch.js b/src/icon-sketch.jsnew file mode 100644index 00000000..cb6e5052--- /dev/null+++ b/src/icon-sketch.js@@ -0,0 +1,279 @@+// The sketch look of the `icons` render job (docs/agent-render-jobs.md, "Icons"): a user post pass (docs/user-passes.md) that draws an+// ink outline from the alpha, depth and normal edges, pencil hatching whose density follows the light, and a paper-coloured fill.+// This file holds the knobs and their limits, the GLSL, the numbers the GLSL gets at each icon size, and the measurements the tests+// and the smoke script use to check that the look still reads at 64 px. No browser, no files.+import { invalidField } from './field-error.js';++export const SKETCH_LIMITS = Object.freeze({+ densities: Object.freeze({ minimum: 0.5, maximum: 2, default: 1 }),+ jitters: Object.freeze({ minimum: 0, maximum: 1, default: 0.35 }),+ maximumSeed: 65535,+ defaultInkColor: '#2b2a33',+ defaultPaperColor: '#f4ecd8',+});++/** The steps a breakdown strip shows, left to right, and the value of the pass's `stage` uniform that draws each. */+export const SKETCH_STAGES = Object.freeze({ final: 0, outline: 1, hatching: 2, shaded: 3 });+export const BREAKDOWN_ORDER = Object.freeze(['shaded', 'outline', 'hatching', 'final']);++const SKETCH_FIELDS = ['inkColor', 'paperColor', 'hatchDensity', 'jitter'];+const HEX_COLOR = /^#[0-9a-fA-F]{6}$/;+const TONE_BANDS = Object.freeze([0.68, 0.48, 0.3]);+const CREASE_ANGLE_DEGREES = 40;+const DEPTH_STEP = 0.02;+const HATCH_LINES_ACROSS_ICON = 24;+const MINIMUM_HATCH_PERIOD = 3;++function colorFrom(value, field, fallback) {+ if (value === undefined) return fallback;+ if (typeof value !== 'string' || !HEX_COLOR.test(value)) {+ throw invalidField(`sketch.${field}`, typeof value === 'string' ? value.slice(0, 20) : typeof value, 'a colour as "#rrggbb", for example "#2b2a33"', RangeError);+ }+ return value.toLowerCase();+}++function numberFrom(value, field, { minimum, maximum, default: fallback }) {+ if (value === undefined) return fallback;+ if (!Number.isFinite(value) || value < minimum || value > maximum) {+ throw invalidField(`sketch.${field}`, value, `a number from ${minimum} to ${maximum} (default ${fallback})`, RangeError);+ }+ return value;+}++/** The sketch knobs with every default filled in and every limit checked. */+export function normalizeSketchSettings(input) {+ if (input === undefined) input = {};+ if (!input || Object.getPrototypeOf(input) !== Object.prototype) {+ throw invalidField('sketch', typeof input, `an object with any of ${SKETCH_FIELDS.join(', ')}`, TypeError);+ }+ for (const key of Object.keys(input)) {+ if (!SKETCH_FIELDS.includes(key)) throw invalidField(`sketch.${key}`, 'an unknown field', `only ${SKETCH_FIELDS.join(', ')}`, TypeError);+ }+ return {+ inkColor: colorFrom(input.inkColor, 'inkColor', SKETCH_LIMITS.defaultInkColor),+ paperColor: colorFrom(input.paperColor, 'paperColor', SKETCH_LIMITS.defaultPaperColor),+ hatchDensity: numberFrom(input.hatchDensity, 'hatchDensity', SKETCH_LIMITS.densities),+ jitter: numberFrom(input.jitter, 'jitter', SKETCH_LIMITS.jitters),+ };+}++/** The seed of the pencil wobble: a whole number, so the same seed always draws the same lines. */+export function seedFrom(value) {+ if (value === undefined) return 0;+ if (!Number.isInteger(value) || value < 0 || value > SKETCH_LIMITS.maximumSeed) {+ throw invalidField('seed', value, `a whole number from 0 to ${SKETCH_LIMITS.maximumSeed}`, RangeError);+ }+ return value;+}++function displayColor(hex) {+ return [1, 3, 5].map(offset => Number((parseInt(hex.slice(offset, offset + 2), 16) / 255).toFixed(4)));+}++/** The numbers the GLSL gets at one icon size: line reach, hatch spacing and weight, and the wobble, all in output pixels. */+export function sketchMetrics({ size, hatchDensity, jitter }) {+ const hatchPeriod = Math.max(MINIMUM_HATCH_PERIOD, Math.round(size / (HATCH_LINES_ACROSS_ICON * hatchDensity)));+ const reach = Math.max(1, Math.round(size / 128));+ return {+ reach,+ outlineWobble: Number((jitter * Math.max(0.5, reach * 0.6)).toFixed(4)),+ hatchPeriod,+ hatchWeight: Number(Math.max(1, hatchPeriod * 0.2).toFixed(4)),+ hatchShift: Number((jitter * hatchPeriod * 0.3).toFixed(4)),+ };+}++// The pass is one function per idea so people who tune it can find the part they want: inkEdge (outline), hatchAmount (pencil).+// Hatching is laid out in whole pixel steps (x + y for the 45 degree layer), so at 64 px it is a clean pattern and not a moire.+const SKETCH_FRAGMENT = `+const vec2 directions[4] = vec2[4](vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(0.7071, 0.7071), vec2(0.7071, -0.7071));++float hash(vec2 cell) { return fract(sin(dot(cell, vec2(127.1, 311.7)) + seed * 17.31) * 43758.5453); }++float smoothNoise(vec2 point) {+ vec2 cell = floor(point);+ vec2 blend = fract(point);+ blend = blend * blend * (3.0 - 2.0 * blend);+ float low = mix(hash(cell), hash(cell + vec2(1.0, 0.0)), blend.x);+ float high = mix(hash(cell + vec2(0.0, 1.0)), hash(cell + vec2(1.0, 1.0)), blend.x);+ return mix(low, high, blend.y);+}++// 1 where this pixel is within the line's reach of a silhouette, a surface that sits behind a nearer one, or a crease.+float inkEdge(vec2 uv) {+ vec2 pixel = 1.0 / resolution;+ float lineReach = reach + outlineWobble * smoothNoise(uv * resolution / 7.0);+ float depthHere = depthAt(uv);+ float edge = 0.0;+ for (int i = 0; i < 4; i++) {+ vec2 offset = directions[i] * lineReach * pixel;+ if (texture(sceneColor, uv + offset).a < 0.5 || texture(sceneColor, uv - offset).a < 0.5) {+ edge = 1.0;+ } else {+ float depthBend = depthAt(uv + offset) + depthAt(uv - offset) - 2.0 * depthHere;+ float creased = dot(worldNormalAt(uv + offset), worldNormalAt(uv - offset)) < creaseCosine ? 1.0 : 0.0;+ if (depthBend < -depthStep || (abs(depthBend) < depthStep && creased > 0.0)) edge = 1.0;+ }+ }+ return edge;+}++// One set of parallel pencil lines. across runs perpendicular to the lines in whole pixel steps, along runs the other way.+float pencilLines(float across, float along, float layer) {+ float wobble = (smoothNoise(vec2(along / (hatchPeriod * 4.0), floor(across / hatchPeriod) + layer * 17.0)) - 0.5) * 2.0 * hatchShift;+ float position = (across + wobble) / hatchPeriod;+ float lineDistance = abs(position - floor(position + 0.5)) * hatchPeriod;+ return 1.0 - smoothstep(hatchWeight * 0.5 - 0.5, hatchWeight * 0.5 + 0.5, lineDistance);+}++// The darker the light, the more layers: one set of lines, then a crossing set, then a third.+float hatchAmount(float tone) {+ float x = gl_FragCoord.x;+ float y = gl_FragCoord.y;+ float edgeNoise = (smoothNoise(gl_FragCoord.xy / 9.0) - 0.5) * 0.08 * (hatchShift / hatchPeriod + 0.1);+ float amount = 0.0;+ if (tone < bands.x + edgeNoise) amount = max(amount, pencilLines(x + y, x - y, 0.0));+ if (tone < bands.y + edgeNoise) amount = max(amount, pencilLines(x - y, x + y, 1.0));+ if (tone < bands.z + edgeNoise) amount = max(amount, pencilLines(y, x, 2.0));+ return amount;+}++vec4 userPass(vec2 uv) {+ vec4 source = texture(sceneColor, uv);+ if (stage == 3 || source.a < 0.002) return source;+ float tone = dot(source.rgb / source.a, vec3(0.299, 0.587, 0.114));+ float outline = (stage == 0 || stage == 1) ? inkEdge(uv) : 0.0;+ float hatching = (stage == 0 || stage == 2) ? hatchAmount(tone) : 0.0;+ vec3 color = mix(paperColor, inkColor, max(outline, hatching * 0.85));+ return vec4(color * source.a, source.a);+}+`;++/**+ * The user pass (the `postPasses` entry of the icon's recipe) for one icon size and one step. Stage `final` draws the sketch,+ * `outline` and `hatching` draw one half of it on paper, and `shaded` passes the clean render through, for the breakdown strip.+ */+export function sketchPass({ settings, size, stage = 'final' }) {+ const { sketch, seed } = settings;+ const metrics = sketchMetrics({ size, hatchDensity: sketch.hatchDensity, jitter: sketch.jitter });+ return {+ name: 'icon-sketch',+ scale: 1,+ fragment: SKETCH_FRAGMENT,+ uniforms: {+ inkColor: displayColor(sketch.inkColor),+ paperColor: displayColor(sketch.paperColor),+ reach: metrics.reach,+ outlineWobble: metrics.outlineWobble,+ hatchPeriod: metrics.hatchPeriod,+ hatchWeight: metrics.hatchWeight,+ hatchShift: metrics.hatchShift,+ creaseCosine: Number(Math.cos(CREASE_ANGLE_DEGREES * Math.PI / 180).toFixed(4)),+ depthStep: DEPTH_STEP,+ bands: [...TONE_BANDS],+ seed,+ stage: { type: 'int', value: SKETCH_STAGES[stage] },+ },+ };+}++/** What `scene_capabilities` jobs reports for the sketch style. */+export const SKETCH_CAPABILITIES = Object.freeze({+ note: 'style sketch is a user post pass: ink outline from alpha, depth and normal edges, pencil hatching (up to three crossing layers) that gets denser as the light gets darker, a paper fill and a seeded wobble. Same input and seed give the same pixels on the cpu backend. breakdown: true writes breakdown-<item>.png, four steps side by side.',+ inkColor: Object.freeze({ default: SKETCH_LIMITS.defaultInkColor, format: '#rrggbb' }),+ paperColor: Object.freeze({ default: SKETCH_LIMITS.defaultPaperColor, format: '#rrggbb' }),+ hatchDensity: SKETCH_LIMITS.densities,+ jitter: SKETCH_LIMITS.jitters,+ seed: Object.freeze({ default: 0, maximum: SKETCH_LIMITS.maximumSeed }),+ breakdownSteps: BREAKDOWN_ORDER,+});++function luma(data, pixel) {+ return (0.299 * data[pixel * 4] + 0.587 * data[pixel * 4 + 1] + 0.114 * data[pixel * 4 + 2]) / 255;+}++function isOpaque(data, pixel) {+ return data[pixel * 4 + 3] >= 250;+}++/** Pixels that are opaque and have only opaque pixels within `margin` pixels: the inside of the silhouette, away from its outline. */+function interiorPixels(data, width, height, margin) {+ const inside = [];+ for (let row = margin; row < height - margin; row++) {+ for (let column = margin; column < width - margin; column++) {+ let allOpaque = true;+ for (let rowOffset = -margin; rowOffset <= margin && allOpaque; rowOffset++) {+ for (let columnOffset = -margin; columnOffset <= margin; columnOffset++) {+ if (!isOpaque(data, (row + rowOffset) * width + column + columnOffset)) { allOpaque = false; break; }+ }+ }+ if (allOpaque) inside.push(row * width + column);+ }+ }+ return inside;+}++function percentile(sortedValues, fraction) {+ return sortedValues[Math.min(sortedValues.length - 1, Math.floor(sortedValues.length * fraction))];+}++/**+ * Measures the pencil hatching in the hatching step of a breakdown strip (hatching alone on paper). The hatched band is every+ * interior pixel with ink within `window` pixels, which leaves out the bright parts of the item where no line is drawn.+ * Returns `contrast` (the 90th to the 10th percentile of luma in the band, as a share of the paper to ink range: 1 is full ink+ * against full paper), `bimodal` (the share of band pixels that are within a quarter of the range of paper or ink; grey noise+ * scores low here) and `coverage` (the share of the band that is ink), or null when the item has no hatching at all.+ */+export function measureHatchBand({ data, width, height, paperLuma, inkLuma, window = 3 }) {+ const range = paperLuma - inkLuma;+ const interior = interiorPixels(data, width, height, 2);+ const isInk = pixel => luma(data, pixel) < inkLuma + range * 0.5;+ const interiorSet = new Set(interior);+ const band = interior.filter(pixel => {+ const row = Math.floor(pixel / width);+ const column = pixel % width;+ for (let rowOffset = -window; rowOffset <= window; rowOffset++) {+ for (let columnOffset = -window; columnOffset <= window; columnOffset++) {+ const neighbour = (row + rowOffset) * width + column + columnOffset;+ if (interiorSet.has(neighbour) && isInk(neighbour)) return true;+ }+ }+ return false;+ });+ if (band.length === 0) return null;+ const lumas = band.map(pixel => luma(data, pixel)).sort((first, second) => first - second);+ const nearExtreme = lumas.filter(value => value <= inkLuma + range * 0.25 || value >= paperLuma - range * 0.25).length;+ return {+ pixels: band.length,+ contrast: (percentile(lumas, 0.9) - percentile(lumas, 0.1)) / range,+ bimodal: nearExtreme / band.length,+ coverage: band.filter(isInk).length / band.length,+ };+}++/**+ * Measures the outline in the outline step of a breakdown strip: of the opaque pixels that touch a see-through pixel (the+ * silhouette), the share drawn in ink. 1 means the whole contour is inked.+ */+export function measureOutline({ data, width, height, paperLuma, inkLuma }) {+ const range = paperLuma - inkLuma;+ let contour = 0;+ let inked = 0;+ for (let row = 1; row < height - 1; row++) {+ for (let column = 1; column < width - 1; column++) {+ const pixel = row * width + column;+ if (!isOpaque(data, pixel)) continue;+ const touchesBackground = [pixel - 1, pixel + 1, pixel - width, pixel + width].some(neighbour => data[neighbour * 4 + 3] < 128);+ if (!touchesBackground) continue;+ contour++;+ if (luma(data, pixel) < inkLuma + range * 0.35) inked++;+ }+ }+ return { contourPixels: contour, inkedShare: contour === 0 ? 0 : inked / contour };+}++/** The luma (0 to 1) of a `#rrggbb` colour, as the measurements above weigh it. */+export function hexLuma(hex) {+ const [red, green, blue] = displayColor(hex);+ return 0.299 * red + 0.587 * green + 0.114 * blue;+}diff --git a/tests/agent-icon-job.test.js b/tests/agent-icon-job.test.jsindex 5fc2c865..bb0eab35 100644--- a/tests/agent-icon-job.test.js+++ b/tests/agent-icon-job.test.js@@ -6,7 +6,7 @@ import { join } from 'node:path';import { renderIconJob } from '../scripts/agent-icon-job.mjs';import { decodePng, encodePng } from '../scripts/agent-icon-png.mjs';import { alphaBounds, normalizeIconSettings } from '../src/icon-sheet.js';-import { artifactNames, normalizeJobSettings } from '../scripts/agent-render-jobs.mjs';+import { artifactNames, jobDeadlineMs, normalizeJobSettings } from '../scripts/agent-render-jobs.mjs';const subtract = (a, b) => a.map((value, axis) => value - b[axis]);const dot = (a, b) => a.reduce((sum, value, axis) => sum + value * b[axis], 0);@@ -18,7 +18,7 @@ function boxItem(dimensions, size, centerOffset = [0, 0, 0]) {const bounds = { min: centerOffset.map((value, axis) => value - dimensions[axis] / 2), max: centerOffset.map((value, axis) => value + dimensions[axis] / 2) };return {bounds,- async draw(camera) {+ async draw(camera, color = [200, 90, 40, 255]) {const forward = normalize(subtract(camera.target, camera.eye));const right = normalize(cross(forward, camera.up));const up = cross(right, forward);@@ -35,15 +35,20 @@ function boxItem(dimensions, size, centerOffset = [0, 0, 0]) {for (let row = 0; row < size; row++) {for (let column = 0; column < size; column++) {if (column + 0.5 < left || column + 0.5 > right2 || row + 0.5 < top || row + 0.5 > bottom) continue;- data.set([200, 90, 40, 255], (row * size + column) * 4);+ data.set(color, (row * size + column) * 4);}}return encodePng({ width: size, height: size, data });},+ // A step of the sketch: the same silhouette in a colour of its own, so a test can tell the panels of a strip apart.+ async drawStep(camera, step) {+ return this.draw(camera, STEP_COLORS[step]);+ },async close() {},};}+const STEP_COLORS = { shaded: [10, 20, 30, 255], outline: [40, 50, 60, 255], hatching: [70, 80, 90, 255] };const SHAPES = { coin: [0.5, 0.04, 0.5], sword: [0.08, 1.6, 0.03], chest: [2.4, 1.8, 1.6] };async function runJob(sources, overrides = {}) {@@ -51,15 +56,19 @@ async function runJob(sources, overrides = {}) {const settings = normalizeIconSettings({ kind: 'icons', items: sources, size, ...overrides });const directory = await mkdtemp(join(tmpdir(), 'crucible-icons-test-'));const progressCalls = [];+ const openedViews = [];const result = await renderIconJob({settings, directory, signal: new AbortController().signal,progress: async update => { progressCalls.push(update.frames); },- openItem: async item => boxItem(SHAPES[item.source], size),+ openItem: async (item, index, frame) => {+ openedViews.push([index, frame.view.azimuth]);+ return boxItem(SHAPES[item.source], size);+ },});const files = {};for (const artifact of result.artifacts) files[artifact.filename] = await readFile(join(directory, artifact.temporary));await rm(directory, { recursive: true, force: true });- return { settings, result, files, progressCalls };+ return { settings, result, files, progressCalls, openedViews };}function iconBox(png) {@@ -166,3 +175,68 @@ test('the job store knows the icons settings and artifact names', () => {const { frameCount, ...stored } = settings;assert.deepEqual(normalizeJobSettings(stored, [], {}), settings, 'stored settings normalise to themselves');});++test('a turnaround draws every item from each angle at one view height per item, one row per item in the atlas', async () => {+ const { files, settings, result, openedViews } = await runJob(['coin', 'chest'], { angles: 4, size: 64 });+ const manifest = JSON.parse(files['icons.json']);+ assert.equal(settings.frameCount, 8);+ assert.deepEqual(manifest.atlas, { file: 'atlas.png', width: 256, height: 128, columns: 4, rows: 2 });+ assert.deepEqual(manifest.icons.map(icon => [icon.item, icon.turn, icon.angle]), [[0, 0, 35], [0, 1, 125], [0, 2, -145], [0, 3, -55], [1, 0, 35], [1, 1, 125], [1, 2, -145], [1, 3, -55]]);+ const coinHeights = new Set(manifest.icons.slice(0, 4).map(icon => icon.viewHeight));+ const chestHeights = new Set(manifest.icons.slice(4).map(icon => icon.viewHeight));+ assert.equal(coinHeights.size, 1, 'the four views of the coin share one scale');+ assert.equal(chestHeights.size, 1, 'the four views of the chest share one scale');+ assert.notEqual([...coinHeights][0], [...chestHeights][0], 'each item keeps its own scale under fit');+ for (const icon of manifest.icons) {+ const box = iconBox(files[icon.file]);+ assert.ok(box.left >= 1 && box.top >= 1 && box.right <= 63 && box.bottom <= 63, `${icon.file} is clipped`);+ assert.ok(Math.abs((box.left + box.right) / 2 - 32) <= 1 && Math.abs((box.top + box.bottom) / 2 - 32) <= 1, `${icon.file} is off centre`);+ }+ assert.equal(result.artifacts.length, 10, 'eight icons, the atlas and icons.json');+ assert.deepEqual(openedViews.slice(0, 4), [[0, 35], [0, 125], [0, -145], [0, -55]], 'the first pass measures every angle of the first item');+});++test('a turnaround under relative scale keeps one scale for the whole set', async () => {+ const { files } = await runJob(['coin', 'chest'], { angles: 4, size: 64, scale: 'relative' });+ const manifest = JSON.parse(files['icons.json']);+ assert.equal(new Set(manifest.icons.map(icon => icon.viewHeight)).size, 1);+});++test('a breakdown strip shows shaded, outline, hatching and the final icon side by side, and is listed in icons.json', async () => {+ const { files, result, settings } = await runJob(['coin', 'chest'], { style: 'sketch', breakdown: true, size: 64, angles: 4 });+ const manifest = JSON.parse(files['icons.json']);+ assert.deepEqual(result.artifacts.map(artifact => artifact.filename).filter(name => name.startsWith('breakdown')), ['breakdown-0.png', 'breakdown-1.png']);+ assert.deepEqual(manifest.icons.filter(icon => icon.breakdown).map(icon => [icon.item, icon.turn, icon.breakdown]), [[0, 0, 'breakdown-0.png'], [1, 0, 'breakdown-1.png']]);+ assert.equal(result.artifacts.length, 8 + 2 + 2);+ for (const itemIndex of [0, 1]) {+ const strip = decodePng(files[`breakdown-${itemIndex}.png`]);+ assert.deepEqual([strip.width, strip.height], [settings.size * 4, settings.size]);+ const finalIcon = decodePng(files[`icon-${itemIndex * 4}.png`]);+ const colorOf = position => [...strip.data.subarray((32 * strip.width + position * settings.size + 32) * 4, (32 * strip.width + position * settings.size + 32) * 4 + 4)];+ assert.deepEqual([0, 1, 2].map(colorOf), [STEP_COLORS.shaded, STEP_COLORS.outline, STEP_COLORS.hatching], 'the first three panels are the steps in order');+ for (let row = 0; row < settings.size; row++) {+ const panel = strip.data.subarray((row * strip.width + 3 * settings.size) * 4, (row * strip.width + 4 * settings.size) * 4);+ assert.ok(panel.equals(finalIcon.data.subarray(row * settings.size * 4, (row + 1) * settings.size * 4)), `the last panel is the final icon (row ${row})`);+ }+ }+});++test('the same sketch job with a breakdown writes byte-identical files', async () => {+ const options = { style: 'sketch', breakdown: true, size: 64, angles: 4, seed: 3 };+ const first = await runJob(['coin', 'sword'], options);+ const second = await runJob(['coin', 'sword'], options);+ assert.deepEqual(Object.keys(first.files), Object.keys(second.files));+ for (const name of Object.keys(first.files)) assert.ok(first.files[name].equals(second.files[name]), `${name} differs between runs`);+});++test('the job store lists the breakdown strips among the artifacts it expects, and a longer deadline for icons', () => {+ const settings = normalizeJobSettings({ kind: 'icons', items: ['a.glb', 'b.glb'], size: 64, style: 'sketch', breakdown: true, angles: 4 }, [], {});+ assert.deepEqual(artifactNames('icons', [], 'png', false, settings.frameCount, settings).slice(8, 10), ['breakdown-0.png', 'breakdown-1.png']);+ assert.equal(artifactNames('icons', [], 'png', false, settings.frameCount, settings).length, 8 + 2 + 2);+ const { frameCount, ...stored } = settings;+ assert.deepEqual(normalizeJobSettings(stored, [], {}), settings);+ assert.ok(jobDeadlineMs(settings) > 60000 + 8 * 4000 * 2, 'two passes of eight frames and two strips fit the deadline');+ const plain = normalizeJobSettings({ kind: 'icons', items: ['a.glb'], size: 64 }, [], {});+ assert.equal(jobDeadlineMs(plain), 60000 + 4000);+ assert.equal(jobDeadlineMs(normalizeJobSettings({ kind: 'icons', items: Array.from({ length: 256 }, (_, index) => `i${index}.glb`), size: 64, scale: 'relative' }, [], {})), 30 * 60 * 1000);+});diff --git a/tests/icon-sheet.test.js b/tests/icon-sheet.test.jsindex c8f66e4d..87438f0c 100644--- a/tests/icon-sheet.test.js+++ b/tests/icon-sheet.test.js@@ -1,6 +1,7 @@import test from 'node:test';import assert from 'node:assert/strict';-import { ICON_CAPABILITIES, ICON_LIMITS, atlasCapacity, cameraBasis, cameraForFraming, iconNames, iconRecipe, layoutAtlas, lightRigEnvironment, normalizeIconSettings, sphereFraming } from '../src/icon-sheet.js';+import { ICON_CAPABILITIES, ICON_LIMITS, atlasCapacity, cameraBasis, cameraForFraming, iconArtifactNames, iconFrames, iconManifest, iconNames, iconRecipe, itemCapacity, layoutAtlas, lightRigEnvironment, normalizeIconSettings, sphereFraming, turnaroundAzimuth } from '../src/icon-sheet.js';+import { normalizeUserPasses } from '../src/user-pass.js';const valid = { kind: 'icons', items: ['sword.glb'] };@@ -13,13 +14,12 @@ test('defaults: 256 px, clean, fit, three-quarter view and the padding', () => {assert.equal(settings.transparent, true);});-test('sketch is refused as coming, not as unknown', () => {- assert.throws(() => normalizeIconSettings({ ...valid, style: 'sketch' }), /style: got "sketch"; expected clean or toon: the sketch style is coming/);- assert.throws(() => normalizeIconSettings({ ...valid, style: 'pencil' }), /style: got "pencil"; expected one of clean, toon/);+test('an unknown style is named with the styles to pass', () => {+ assert.throws(() => normalizeIconSettings({ ...valid, style: 'pencil' }), /style: got "pencil"; expected one of clean, toon, sketch/);});test('fields left for later releases say they are coming', () => {- for (const field of ['angles', 'breakdown', 'lighting', 'background', 'outline']) {+ for (const field of ['lighting', 'background', 'outline']) {assert.throws(() => normalizeIconSettings({ ...valid, [field]: 4 }), new RegExp(`settings.${field}: .*is coming`));}assert.throws(() => normalizeIconSettings({ ...valid, bogus: 1 }), /Unknown settings field: bogus/);@@ -103,7 +103,103 @@ test('the atlas is a near square grid and names stay unique', () => {test('scene_capabilities reports the limits the validator enforces', () => {assert.equal(ICON_CAPABILITIES.maximumItems, 256);- assert.deepEqual(ICON_CAPABILITIES.styles, ['clean', 'toon']);+ assert.deepEqual(ICON_CAPABILITIES.styles, ['clean', 'toon', 'sketch']);+ assert.deepEqual(ICON_CAPABILITIES.angles, [1, 4, 8]);+ assert.equal(ICON_CAPABILITIES.maximumIcons, 256);+ assert.deepEqual(ICON_CAPABILITIES.itemsPerSizeAndAngles, { 4: { 64: 64, 128: 32, 256: 16, 512: 8 }, 8: { 64: 32, 128: 32, 256: 16, 512: 8 } });+ assert.equal(ICON_CAPABILITIES.sketch.hatchDensity.maximum, 2);assert.deepEqual(ICON_CAPABILITIES.itemsPerSize, { 64: 256, 128: 256, 256: 256, 512: 64 });- assert.ok(ICON_CAPABILITIES.notYet.includes('breakdown'));+ assert.ok(!ICON_CAPABILITIES.notYet.includes('breakdown'));+ assert.ok(ICON_CAPABILITIES.notYet.includes('lighting'));+});++test('sketch is a style with its own defaults, and its fields belong to it alone', () => {+ const settings = normalizeIconSettings({ ...valid, style: 'sketch' });+ assert.deepEqual(settings.sketch, { inkColor: '#2b2a33', paperColor: '#f4ecd8', hatchDensity: 1, jitter: 0.35 });+ assert.equal(settings.seed, 0);+ const tuned = normalizeIconSettings({ ...valid, style: 'sketch', seed: 7, sketch: { inkColor: '#102030', hatchDensity: 2 } });+ assert.deepEqual([tuned.seed, tuned.sketch.inkColor, tuned.sketch.hatchDensity, tuned.sketch.paperColor], [7, '#102030', 2, '#f4ecd8']);+ assert.throws(() => normalizeIconSettings({ ...valid, seed: 3 }), /seed: got "a field of the sketch style"; expected no seed unless style is "sketch" \(the style is clean\)/);+ assert.throws(() => normalizeIconSettings({ ...valid, style: 'toon', sketch: {} }), /sketch: .*no sketch unless style is "sketch"/);+});++test('every sketch knob is bounded and the error says what to pass', () => {+ const sketchStyle = { ...valid, style: 'sketch' };+ const cases = [+ [{ sketch: { inkColor: 'black' } }, /sketch.inkColor: got "black"; expected a colour as "#rrggbb"/],+ [{ sketch: { paperColor: '#fff' } }, /sketch.paperColor: got "#fff"; expected a colour as "#rrggbb"/],+ [{ sketch: { hatchDensity: 3 } }, /sketch.hatchDensity: got 3; expected a number from 0.5 to 2/],+ [{ sketch: { hatchDensity: 0 } }, /sketch.hatchDensity: got 0;/],+ [{ sketch: { jitter: 1.5 } }, /sketch.jitter: got 1.5; expected a number from 0 to 1/],+ [{ sketch: { jitter: Number.NaN } }, /sketch.jitter: got NaN/],+ [{ sketch: { pressure: 1 } }, /sketch.pressure: got "an unknown field"; expected only inkColor, paperColor, hatchDensity, jitter/],+ [{ sketch: 'rough' }, /sketch: got "string"; expected an object with any of/],+ [{ seed: 1.5 }, /seed: got 1.5; expected a whole number from 0 to 65535/],+ [{ seed: 70000 }, /seed: got 70000;/],+ ];+ for (const [overrides, pattern] of cases) assert.throws(() => normalizeIconSettings({ ...sketchStyle, ...overrides }), pattern, JSON.stringify(overrides));+});++test('the sketch recipe carries a user pass the user-pass checker accepts, and the stage picks a breakdown step', () => {+ const settings = normalizeIconSettings({ ...valid, style: 'sketch', seed: 5 });+ const view = { azimuth: 35, elevation: 25 };+ const recipe = iconRecipe({ assetId: 'ab'.repeat(32), style: 'sketch', view, size: 64, sketch: settings.sketch, seed: settings.seed });+ const [pass] = normalizeUserPasses(recipe.postPasses);+ assert.equal(pass.name, 'icon-sketch');+ assert.equal(pass.uniforms.seed.value, 5);+ assert.equal(pass.uniforms.stage.value, 0);+ assert.equal(pass.uniforms.hatchPeriod.value, 3, 'a 64 px icon hatches in whole 3 px steps so the lines do not beat against the pixels');+ assert.equal(recipe.environment.lines, undefined, 'the outline is the pass, not line art');+ const outline = iconRecipe({ assetId: 'ab'.repeat(32), style: 'sketch', view, size: 64, sketch: settings.sketch, stage: 'outline' });+ assert.equal(normalizeUserPasses(outline.postPasses)[0].uniforms.stage.value, 1);+ assert.equal(iconRecipe({ assetId: 'ab'.repeat(32), style: 'clean', view, size: 64 }).postPasses, undefined);+});++test('angles take 1, 4 or 8 and the job must fit the atlas and the icon count', () => {+ assert.equal(normalizeIconSettings({ ...valid, angles: 8 }).frameCount, 8);+ assert.throws(() => normalizeIconSettings({ ...valid, angles: 3 }), /angles: got "3"; expected one of 1, 4, 8/);+ assert.equal(itemCapacity(256, 1), 256);+ assert.equal(itemCapacity(512, 8), 8);+ assert.equal(itemCapacity(64, 8), 32);+ const items = count => Array.from({ length: count }, (_, index) => `item-${index}.glb`);+ assert.equal(normalizeIconSettings({ kind: 'icons', items: items(32), angles: 8, size: 64 }).frameCount, 256);+ assert.throws(() => normalizeIconSettings({ kind: 'icons', items: items(33), angles: 8, size: 64 }), /items: got 33; expected at most 32 items at size 64 with 8 angles/);+ assert.throws(() => normalizeIconSettings({ kind: 'icons', items: items(9), angles: 4, size: 512 }), /items: got 9; expected at most 8 items at size 512 with 4 angles/);+});++test('a turnaround starts at the viewpoint azimuth and walks round in equal steps, wrapped to -180 to 180', () => {+ assert.deepEqual([0, 1, 2, 3].map(index => turnaroundAzimuth(35, index, 4)), [35, 125, -145, -55]);+ assert.deepEqual([0, 1, 2, 3, 4, 5, 6, 7].map(index => turnaroundAzimuth(0, index, 8)), [0, 45, 90, 135, 180, -135, -90, -45]);+ const settings = normalizeIconSettings({ kind: 'icons', items: ['a.glb', 'b.glb'], angles: 4, viewpoint: { azimuth: 0, elevation: 10 } });+ const frames = iconFrames(settings);+ assert.deepEqual(frames.map(frame => [frame.itemIndex, frame.angleIndex, frame.view.azimuth, frame.view.elevation]), [+ [0, 0, 0, 10], [0, 1, 90, 10], [0, 2, 180, 10], [0, 3, -90, 10], [1, 0, 0, 10], [1, 1, 90, 10], [1, 2, 180, 10], [1, 3, -90, 10]]);+});++test('breakdown needs the sketch style, which is drawn in steps', () => {+ assert.throws(() => normalizeIconSettings({ ...valid, breakdown: true }), /breakdown: got "true"; expected a style that is drawn in steps: set style to "sketch" \(the style is clean\)/);+ assert.throws(() => normalizeIconSettings({ ...valid, style: 'sketch', breakdown: 'yes' }), /breakdown: got "string"; expected true or false/);+ assert.equal(normalizeIconSettings({ ...valid, style: 'sketch', breakdown: false }).breakdown, undefined);+ assert.equal(normalizeIconSettings({ ...valid, style: 'sketch', breakdown: true }).breakdown, true);+});++test('a turnaround sheet has one row per item and one column per angle, and every entry names its angle', () => {+ const settings = normalizeIconSettings({ kind: 'icons', items: [{ source: 'sword.glb', asset: 'ab'.repeat(32) }, 'coin.glb'], angles: 4, size: 64, style: 'sketch', breakdown: true });+ const layout = layoutAtlas(settings.frameCount, 64, settings.angles);+ assert.deepEqual([layout.columns, layout.rows, layout.width, layout.height], [4, 2, 256, 128]);+ assert.deepEqual(layout.rectangles[5], { x: 64, y: 64, width: 64, height: 64 });+ const entries = Array.from({ length: 8 }, (_, index) => ({ bounds: { x: 1, y: 1, width: 5, height: 5 }, viewHeight: index + 1 }));+ const manifest = iconManifest({ settings, layout, entries });+ assert.equal(manifest.angles, 4);+ assert.equal(manifest.seed, 0);+ assert.deepEqual(manifest.sketch, settings.sketch);+ assert.deepEqual(manifest.icons.map(icon => [icon.name, icon.item, icon.turn, icon.angle, icon.file]).slice(2, 6), [+ ['sword', 0, 2, -145, 'icon-2.png'], ['sword', 0, 3, -55, 'icon-3.png'], ['coin', 1, 0, 35, 'icon-4.png'], ['coin', 1, 1, 125, 'icon-5.png']]);+ assert.deepEqual(manifest.icons.filter(icon => icon.breakdown).map(icon => [icon.name, icon.breakdown]), [['sword', 'breakdown-0.png'], ['coin', 'breakdown-1.png']]);+ assert.deepEqual(manifest.icons[4].rect, { x: 0, y: 64, width: 64, height: 64 });+});++test('the artifact list is one PNG per frame, a strip per item when asked, then the atlas and icons.json', () => {+ assert.deepEqual(iconArtifactNames(2), ['icon-0.png', 'icon-1.png', 'atlas.png', 'icons.json']);+ assert.deepEqual(iconArtifactNames(4, { itemCount: 2 }), ['icon-0.png', 'icon-1.png', 'icon-2.png', 'icon-3.png', 'breakdown-0.png', 'breakdown-1.png', 'atlas.png', 'icons.json']);});diff --git a/tests/icon-sketch-render.test.js b/tests/icon-sketch-render.test.jsnew file mode 100644index 00000000..f0568bef--- /dev/null+++ b/tests/icon-sketch-render.test.js@@ -0,0 +1,100 @@+// The sketch look drawn for real: the MCP server on the cpu backend (SwiftShader) renders the Kenney boat fixture, and the pictures are+// measured. These pin what the issue asks of sketch: the outline and the hatching still read at 64 px, the same seed gives the same+// bytes, and the knobs change the picture. Needs Chrome, like the other MCP tests.+import test, { after, before } from 'node:test';+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { decodePng } from '../scripts/agent-icon-png.mjs';+import { startIconsServer } from '../scripts/icons-mcp-client.mjs';+import { alphaBounds } from '../src/icon-sheet.js';+import { hexLuma, measureHatchBand, measureOutline } from '../src/icon-sketch.js';++const FIXTURES = fileURLToPath(new URL('./fixtures/kenney-boat/', import.meta.url));+const SIZE = 64;+const JOB = { items: ['boat-fishing-small.glb'], size: SIZE, style: 'sketch', breakdown: true, seed: 1 };+const RENDER_TEST_TIMEOUT_MS = 240000;++let server;+before(async () => { server = await startIconsServer({ assets: FIXTURES }); });+after(async () => { await server?.close(); });++async function readAll(artifacts) {+ const files = new Map();+ for (const [filename, path] of artifacts) files.set(filename, await readFile(path));+ return files;+}++/** The n-th square panel of a strip as its own picture. */+function panelOf(strip, position, extra) {+ const data = Buffer.alloc(SIZE * SIZE * 4);+ for (let row = 0; row < SIZE; row++) {+ strip.data.copy(data, row * SIZE * 4, (row * strip.width + position * SIZE) * 4, (row * strip.width + (position + 1) * SIZE) * 4);+ }+ return { width: SIZE, height: SIZE, data, ...extra };+}++test('sketch at 64 px keeps its outline and its hatching readable: ink on the contour, bimodal hatching with real contrast', { timeout: RENDER_TEST_TIMEOUT_MS }, async () => {+ const { artifacts, manifest } = await server.runJob(JOB);+ const files = await readAll(artifacts);+ const strip = decodePng(files.get('breakdown-0.png'));+ assert.deepEqual([strip.width, strip.height], [SIZE * 4, SIZE]);+ const luma = { paperLuma: hexLuma(manifest.sketch.paperColor), inkLuma: hexLuma(manifest.sketch.inkColor) };+ const outline = measureOutline(panelOf(strip, 1, luma));+ assert.ok(outline.contourPixels > 100, 'the boat has a contour to ink');+ assert.ok(outline.inkedShare >= 0.95, `the outline is inked along ${outline.inkedShare} of the contour`);+ const hatching = measureHatchBand(panelOf(strip, 2, luma));+ assert.ok(hatching, 'the shaded side of the boat is hatched');+ assert.ok(hatching.pixels >= 300, `${hatching.pixels} px of hatching`);+ assert.ok(hatching.contrast >= 0.7, `hatching contrast ${hatching.contrast}: lines are as dark against the paper as ${hatching.contrast} of the ink to paper range`);+ assert.ok(hatching.bimodal >= 0.8, `${hatching.bimodal} of the hatched pixels are paper or ink: the rest is grey noise`);+ assert.ok(hatching.coverage > 0.08 && hatching.coverage < 0.7, `ink covers ${hatching.coverage} of the hatched band`);+});++test('the sketch fills the item with paper, keeps the frame clean and writes the strip, outline and hatching panels apart', { timeout: RENDER_TEST_TIMEOUT_MS }, async () => {+ const { artifacts, manifest } = await server.runJob(JOB);+ const files = await readAll(artifacts);+ assert.deepEqual([...files.keys()], ['icon-0.png', 'breakdown-0.png', 'atlas.png', 'icons.json']);+ assert.equal(manifest.icons[0].breakdown, 'breakdown-0.png');+ const icon = decodePng(files.get('icon-0.png'));+ const box = alphaBounds(icon.data, SIZE, SIZE);+ assert.ok(box.left >= 1 && box.top >= 1 && box.right <= SIZE - 1 && box.bottom <= SIZE - 1, 'the ink does not clip the frame');+ const paper = [0xf4, 0xec, 0xd8];+ let paperPixels = 0;+ let opaquePixels = 0;+ for (let pixel = 0; pixel < SIZE * SIZE; pixel++) {+ if (icon.data[pixel * 4 + 3] < 250) continue;+ opaquePixels++;+ if (paper.every((value, channel) => Math.abs(icon.data[pixel * 4 + channel] - value) <= 6)) paperPixels++;+ }+ assert.ok(paperPixels / opaquePixels > 0.3, `${paperPixels} of ${opaquePixels} opaque pixels are paper`);+ const strip = decodePng(files.get('breakdown-0.png'));+ const panels = [0, 1, 2, 3].map(position => panelOf(strip, position));+ const distinct = new Set(panels.map(panel => panel.data.toString('base64')));+ assert.equal(distinct.size, 4, 'shaded, outline, hatching and final differ');+ assert.ok(panels[3].data.equals(icon.data), 'the last panel is the final icon');+});++test('the same input and seed give byte-identical files, and another seed or knob gives another picture', { timeout: RENDER_TEST_TIMEOUT_MS }, async () => {+ const first = await readAll((await server.runJob(JOB)).artifacts);+ const second = await readAll((await server.runJob(JOB)).artifacts);+ for (const [filename, bytes] of first) assert.ok(bytes.equals(second.get(filename)), `${filename} differs between two runs`);+ const otherSeed = await readAll((await server.runJob({ ...JOB, seed: 2 })).artifacts);+ assert.ok(!first.get('icon-0.png').equals(otherSeed.get('icon-0.png')), 'a new seed wobbles the lines differently');+ const steady = await readAll((await server.runJob({ ...JOB, sketch: { jitter: 0 } })).artifacts);+ assert.ok(!first.get('icon-0.png').equals(steady.get('icon-0.png')), 'jitter 0 draws straight lines');+ const blue = await readAll((await server.runJob({ ...JOB, sketch: { inkColor: '#1030a0', paperColor: '#e0f0ff' } })).artifacts);+ const bluePixels = decodePng(blue.get('icon-0.png'));+ const [red, green, blueChannel] = bluePixels.data.subarray((32 * SIZE + 32) * 4, (32 * SIZE + 32) * 4 + 3);+ assert.ok(blueChannel > red, `the interior takes the paper colour: ${[red, green, blueChannel]}`);+});++test('a turnaround sheet of sketches has a row per item, a column per angle, and four different views', { timeout: RENDER_TEST_TIMEOUT_MS }, async () => {+ const { artifacts, manifest } = await server.runJob({ items: ['boat-fishing-small.glb'], size: SIZE, style: 'sketch', angles: 4, seed: 1 });+ const files = await readAll(artifacts);+ assert.deepEqual([...files.keys()], ['icon-0.png', 'icon-1.png', 'icon-2.png', 'icon-3.png', 'atlas.png', 'icons.json']);+ assert.deepEqual(manifest.atlas, { file: 'atlas.png', width: SIZE * 4, height: SIZE, columns: 4, rows: 1 });+ assert.deepEqual(manifest.icons.map(icon => icon.angle), [35, 125, -145, -55]);+ assert.equal(new Set(manifest.icons.map(icon => icon.viewHeight)).size, 1, 'one scale for the four views of the item');+ assert.equal(new Set(['icon-0.png', 'icon-1.png', 'icon-2.png', 'icon-3.png'].map(name => files.get(name).toString('base64'))).size, 4);+});diff --git a/tests/icon-sketch.test.js b/tests/icon-sketch.test.jsnew file mode 100644index 00000000..4b3906dd--- /dev/null+++ b/tests/icon-sketch.test.js@@ -0,0 +1,92 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { BREAKDOWN_ORDER, SKETCH_CAPABILITIES, SKETCH_STAGES, hexLuma, measureHatchBand, measureOutline, normalizeSketchSettings, seedFrom, sketchMetrics, sketchPass } from '../src/icon-sketch.js';+import { normalizeUserPasses } from '../src/user-pass.js';++const PAPER = '#f4ecd8';+const INK = '#2b2a33';++/** A `side` px square picture with a see-through border of `margin` px; `paint(column, row)` returns the luma 0 to 1 of an opaque pixel. */+function picture(side, margin, paint) {+ const data = new Uint8Array(side * side * 4);+ for (let row = margin; row < side - margin; row++) {+ for (let column = margin; column < side - margin; column++) {+ const value = Math.round(paint(column, row) * 255);+ data.set([value, value, value, 255], (row * side + column) * 4);+ }+ }+ return { data, width: side, height: side, paperLuma: hexLuma(PAPER), inkLuma: hexLuma(INK) };+}++const paperLuma = hexLuma(PAPER);+const inkLuma = hexLuma(INK);++test('hatching of crisp diagonal lines measures as strong, bimodal contrast with a share of ink', () => {+ const lines = picture(48, 4, (column, row) => ((column + row) % 3 === 0 ? inkLuma : paperLuma));+ const band = measureHatchBand(lines);+ assert.ok(band.contrast >= 0.9, `contrast ${band.contrast}`);+ assert.ok(band.bimodal >= 0.99, `bimodal ${band.bimodal}`);+ assert.ok(Math.abs(band.coverage - 1 / 3) < 0.02, `coverage ${band.coverage}`);+});++test('grey noise fails the same measure, so a regression to mush would be caught', () => {+ let state = 12345;+ const randomLuma = () => {+ state = (state * 1103515245 + 12345) % 2147483648;+ return inkLuma + (paperLuma - inkLuma) * (0.35 + 0.3 * (state / 2147483648));+ };+ const mush = picture(48, 4, () => randomLuma());+ const band = measureHatchBand({ ...mush, window: 3 });+ assert.ok(band === null || band.bimodal < 0.2 || band.contrast < 0.35, `mush scored ${JSON.stringify(band)}`);+});++test('a picture with no hatching has no hatched band, and the outline measure sees an inked or a bare contour', () => {+ assert.equal(measureHatchBand(picture(48, 4, () => paperLuma)), null);+ const inked = picture(48, 4, (column, row) => (column <= 4 || row <= 4 || column >= 43 || row >= 43 ? inkLuma : paperLuma));+ const bare = picture(48, 4, () => paperLuma);+ assert.equal(measureOutline(inked).inkedShare, 1);+ assert.equal(measureOutline(bare).inkedShare, 0);+ assert.ok(measureOutline(bare).contourPixels > 100);+});++test('the pass is valid for the user-pass checker at every size and every step, and fits the 4096 byte budget', () => {+ const settings = { sketch: normalizeSketchSettings(undefined), seed: 0 };+ for (const size of [64, 128, 256, 512]) {+ for (const stage of Object.keys(SKETCH_STAGES)) {+ const [pass] = normalizeUserPasses([sketchPass({ settings, size, stage })]);+ assert.equal(pass.uniforms.stage.value, SKETCH_STAGES[stage]);+ }+ }+});++test('hatching is laid out in whole pixels at 64 px and grows with the icon, so the look stays the same across sizes', () => {+ const base = { hatchDensity: 1, jitter: 0.35 };+ assert.deepEqual([64, 128, 256, 512].map(size => sketchMetrics({ size, ...base }).hatchPeriod), [3, 5, 11, 21]);+ assert.deepEqual([64, 128, 256, 512].map(size => sketchMetrics({ size, ...base }).reach), [1, 1, 2, 4]);+ assert.equal(sketchMetrics({ size: 64, hatchDensity: 2, jitter: 0 }).hatchPeriod, 3, 'never finer than 3 px, where lines stop reading');+ assert.ok(Number.isInteger(sketchMetrics({ size: 200, hatchDensity: 0.7, jitter: 0 }).hatchPeriod));+ assert.equal(sketchMetrics({ size: 256, hatchDensity: 1, jitter: 0 }).hatchShift, 0, 'no jitter means straight lines');+ assert.ok(sketchMetrics({ size: 256, hatchDensity: 1, jitter: 1 }).hatchShift < sketchMetrics({ size: 256, hatchDensity: 1, jitter: 1 }).hatchPeriod / 2, 'a line never wobbles into the next one');+});++test('the colours reach the pass as display values, the seed as a number, and a new seed is a new pass', () => {+ const settings = { sketch: normalizeSketchSettings({ inkColor: '#ff0000', paperColor: '#00ff00' }), seed: 9 };+ const pass = sketchPass({ settings, size: 128 });+ assert.deepEqual(pass.uniforms.inkColor, [1, 0, 0]);+ assert.deepEqual(pass.uniforms.paperColor, [0, 1, 0]);+ assert.equal(pass.uniforms.seed, 9);+ assert.notDeepEqual(pass.uniforms, sketchPass({ settings: { ...settings, seed: 10 }, size: 128 }).uniforms);+});++test('the seed is a whole number from 0 to 65535, and colours accept upper case hex', () => {+ assert.equal(seedFrom(undefined), 0);+ assert.equal(seedFrom(65535), 65535);+ assert.throws(() => seedFrom(-1), /seed: got -1/);+ assert.equal(normalizeSketchSettings({ inkColor: '#ABCDEF' }).inkColor, '#abcdef');+});++test('the breakdown shows four steps in a fixed order, and scene_capabilities lists them', () => {+ assert.deepEqual(BREAKDOWN_ORDER, ['shaded', 'outline', 'hatching', 'final']);+ assert.deepEqual(SKETCH_CAPABILITIES.breakdownSteps, BREAKDOWN_ORDER);+ assert.equal(SKETCH_CAPABILITIES.seed.maximum, 65535);+});