A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(look): stroke joins and ends, what a picture measures, pixels by the block
yhhe2b8379c3c49
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e3ba74f4a..433f7957f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,7 +22,7 @@ published separately; it ships inside the editor.- **Glyphs can be put on the atlas before they are shown.** The first page of a novel is hundreds of new characters, all landing in one frame. `preloadGlyphs(app, label, text, { budgetMs })` makes them ahead of time, a slice a frame, drawn as that `Text` will draw them, and returns `progress`, `done` and `release()`. On a Snapdragon 8 Elite a book's 2992 characters at 28 px took 145 ms over 25 frames with the worst frame at 9.5 ms, after which the first page's frame went from 49 to 11 ms and no page made a new glyph. Preloaded glyphs hold their atlas pages (4 MB each, a few hundred characters at that size) until `release()`.- **Voxel GI lights what the camera does not see, and bounces light more than once.** The cache now reads the sun's shadow map back into the world, so a surface the sun lights behind or beside the camera still sends light into the view. Each surface also gives off again the bounce light it received, so a corner or a floor in shade gets light that took two or more bounces to reach it. A ray now brings what it meets at full strength however far it went (it used to fade with distance, 40% at 4 m with 12 cm voxels). Each voxel is weighed by how much of it a surface covers, so a bright patch no longer lights like the whole voxel around it. Together these keep the result close to a path tracer's whatever the voxel size. In a sunlit test room the whole frame carries 0.95 of Cycles' light at the default size and 0.74 at 12 cm voxels; before, it was 0.54 at the default and darker the finer the grid. With the lit patch behind the camera, the walls went from no bounce light to 25–57%. A closed room the sun only lights from outside stays dark. Two inspector controls tune it: **Off-screen Sun Albedo** (the colour the shadow map cannot give, assumed) and **Multi-bounce**. A fine grid no longer drops every voxel: a count truncated by the cache's ageing had kept them below the two samples a ray asks for. The WebGL2 fallback does the same in its own passes: each voxel asks the sun's map whether a sunlit surface stands in it, and traces two rays through last frame's grid for the light it is given. In the test room it carries 1.00 of Cycles' light at the default size (it was 0.56) and 0.80 at 12 cm; with the lit patch behind the camera 0.20 (it was 0). Its voxel pass costs about 1.3 ms more at 720p on a desktop.-- **An AI can draw 2D pictures.** `image_write` turns layers into a `.png` beside an `.esimage`: shapes and SVG paths, gradients, strokes, shadows and glows, clipping and cutting, or pixel art as rows of characters. It answers with the picture on a mid ground and a light check and at 96, 64, 48 and 32 pixels, to look at and correct; `image_edit` changes one layer or one pixel without restating the rest, and moves layers or wraps them in a group. `image_read` enlarges a part, and `image_set` shows several together with the stroke widths each uses. Drawn on the CPU, so a source makes the same picture on any machine.+- **An AI can draw 2D pictures.** `image_write` turns layers into a `.png` beside an `.esimage`: shapes and SVG paths, gradients, strokes, shadows and glows, clipping and cutting, or pixel art as rows of characters. It answers with the picture on a mid ground and a light check and at 96, 64, 48 and 32 pixels, to look at and correct; `image_edit` changes one layer, a row or a block of pixels without restating the rest, and moves layers or wraps them in a group. Strokes can keep sharp corners, and the reply measures where each layer ended up. `image_read` enlarges a part, and `image_set` shows several together with the stroke widths and size of each. Drawn on the CPU, so a source makes the same picture on any machine.- **An AI can build a person, and not a picture of one.** The `humanoid` step makes a whole body from a few numbers, with fingers, a face and ears, seen right from every side, and `rig: { humanoid: true }` gives it bones that fit. `garment` makes clothes from the body's own surface: loose or tight, a bell sleeve that hangs, a clean hem, a thickness; what a body wears now takes its weights from the skin under it, so an arm stays in its sleeve. `pose` holds a body in a pose by angles, or with `reach` by where a hand should be. `organic` gains `limb`, cross-sections along a path, and `fine`, regions split finer on one skin. `displace` gains `folds`, running the way cloth hangs. `scene_views` no longer takes on a shot's lens blur and grade.diff --git a/desktop b/desktopindex 72dc23c8a..aa1d00a21 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 72dc23c8a17a780fb4b0f388a6742355f1b06c9b+Subproject commit aa1d00a214af68ab5cf6311d0709583dd62c01addiff --git a/pipeline/src/image/imageRaster.ts b/pipeline/src/image/imageRaster.tsindex cde973d67..6dc329a70 100644--- a/pipeline/src/image/imageRaster.ts+++ b/pipeline/src/image/imageRaster.ts@@ -256,26 +256,114 @@ function fillMask(runs: readonly (readonly Pt[])[], w: number, h: number): Floatreturn mask;}-/** What each pixel has of a stroke: by its distance from the line, so joins and ends come out round. */-function strokeMask(runs: readonly { points: readonly Pt[]; closed: boolean }[], width: number, w: number, h: number): Float32Array {+/** Past this a mitre is bevelled: a point of about 11 degrees still comes out sharp, and a thinner one does not throw a long spike. */+const MITER_LIMIT = 10;+const STROKE_SAMPLES = 6;++/** What each pixel has of a stroke. Round joins and ends come from the distance to the line; the others are built of convex pieces, sampled where a pixel crosses an edge: a distance from the edges would trail a faint tail off a sharp point. */+function strokeMask(runs: readonly { points: readonly Pt[]; closed: boolean }[], width: number, w: number, h: number, join: 'round' | 'miter' | 'bevel' = 'round', cap: 'round' | 'butt' | 'square' = 'round'): Float32Array {const mask = new Float32Array(w * h);const half = width / 2;+ const capsule = (a: Pt, b: Pt): void => {+ const [x0, x1] = [Math.max(0, Math.floor(Math.min(a[0], b[0]) - half - 1)), Math.min(w - 1, Math.ceil(Math.max(a[0], b[0]) + half + 1))];+ const [y0, y1] = [Math.max(0, Math.floor(Math.min(a[1], b[1]) - half - 1)), Math.min(h - 1, Math.ceil(Math.max(a[1], b[1]) + half + 1))];+ const [ex, ey] = [b[0] - a[0], b[1] - a[1]];+ const len = ex * ex + ey * ey;+ for (let y = y0; y <= y1; y++) {+ for (let x = x0; x <= x1; x++) {+ const [px, py] = [x + 0.5 - a[0], y + 0.5 - a[1]];+ const t = len > 0 ? Math.max(0, Math.min(1, (px * ex + py * ey) / len)) : 0;+ const v = Math.max(0, Math.min(1, half - Math.hypot(px - ex * t, py - ey * t) + 0.5));+ if (v > mask[y * w + x]!) mask[y * w + x] = v;+ }+ }+ };+ const convex = (poly: readonly Pt[]): void => {+ let area = 0;+ for (let i = 0; i < poly.length; i++) {+ const [a, b] = [poly[i]!, poly[(i + 1) % poly.length]!];+ area += a[0] * b[1] - b[0] * a[1];+ }+ if (area === 0) return;+ const edges = poly.map((a, i) => {+ const b = poly[(i + 1) % poly.length]!;+ const len = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;+ return { x: a[0], y: a[1], nx: (-(b[1] - a[1]) / len) * Math.sign(area), ny: ((b[0] - a[0]) / len) * Math.sign(area) };+ });+ const [xs, ys] = [poly.map((p) => p[0]), poly.map((p) => p[1])];+ const [x0, x1] = [Math.max(0, Math.floor(Math.min(...xs) - 1)), Math.min(w - 1, Math.ceil(Math.max(...xs) + 1))];+ const [y0, y1] = [Math.max(0, Math.floor(Math.min(...ys) - 1)), Math.min(h - 1, Math.ceil(Math.max(...ys) + 1))];+ for (let y = y0; y <= y1; y++) {+ for (let x = x0; x <= x1; x++) {+ let inside = Infinity;+ for (const e of edges) inside = Math.min(inside, (x + 0.5 - e.x) * e.nx + (y + 0.5 - e.y) * e.ny);+ if (inside <= -0.75) continue;+ let v = 1;+ if (inside < 0.75) {+ let hits = 0;+ for (let sy = 0; sy < STROKE_SAMPLES; sy++) {+ for (let sx = 0; sx < STROKE_SAMPLES; sx++) {+ const [px, py] = [x + (sx + 0.5) / STROKE_SAMPLES, y + (sy + 0.5) / STROKE_SAMPLES];+ if (edges.every((e) => (px - e.x) * e.nx + (py - e.y) * e.ny >= 0)) hits++;+ }+ }+ v = hits / (STROKE_SAMPLES * STROKE_SAMPLES);+ }+ if (v > mask[y * w + x]!) mask[y * w + x] = v;+ }+ }+ };for (const run of runs) {- const count = run.closed ? run.points.length : run.points.length - 1;+ if (join === 'round' && cap === 'round') {+ const count = run.closed ? run.points.length : run.points.length - 1;+ for (let i = 0; i < count; i++) capsule(run.points[i]!, run.points[(i + 1) % run.points.length]!);+ continue;+ }+ // A point repeated has no direction to join from.+ const pts = run.points.filter((p, i, all) => i === 0 || Math.hypot(p[0] - all[i - 1]![0], p[1] - all[i - 1]![1]) > 1e-6);+ if (run.closed && pts.length > 1 && Math.hypot(pts[0]![0] - pts[pts.length - 1]![0], pts[0]![1] - pts[pts.length - 1]![1]) <= 1e-6) pts.pop();+ if (pts.length < 2) {+ if (pts[0] && cap !== 'butt') capsule(pts[0], pts[0]);+ continue;+ }+ const count = run.closed ? pts.length : pts.length - 1;+ const direction = (i: number): Pt => {+ const [a, b] = [pts[i]!, pts[(i + 1) % pts.length]!];+ const len = Math.hypot(b[0] - a[0], b[1] - a[1]);+ return [(b[0] - a[0]) / len, (b[1] - a[1]) / len];+ };for (let i = 0; i < count; i++) {- const [a, b] = [run.points[i]!, run.points[(i + 1) % run.points.length]!];- const [x0, x1] = [Math.max(0, Math.floor(Math.min(a[0], b[0]) - half - 1)), Math.min(w - 1, Math.ceil(Math.max(a[0], b[0]) + half + 1))];- const [y0, y1] = [Math.max(0, Math.floor(Math.min(a[1], b[1]) - half - 1)), Math.min(h - 1, Math.ceil(Math.max(a[1], b[1]) + half + 1))];- const [ex, ey] = [b[0] - a[0], b[1] - a[1]];- const len = ex * ex + ey * ey;- for (let y = y0; y <= y1; y++) {- for (let x = x0; x <= x1; x++) {- const [px, py] = [x + 0.5 - a[0], y + 0.5 - a[1]];- const t = len > 0 ? Math.max(0, Math.min(1, (px * ex + py * ey) / len)) : 0;- const v = Math.max(0, Math.min(1, half - Math.hypot(px - ex * t, py - ey * t) + 0.5));- if (v > mask[y * w + x]!) mask[y * w + x] = v;- }+ const [a, b] = [pts[i]!, pts[(i + 1) % pts.length]!];+ const u = direction(i);+ const [nx, ny] = [-u[1] * half, u[0] * half];+ // A joined end runs on by a pixel's half diagonal, or two pieces half covering a pixel leave a notch across the line.+ const end = (open: boolean): number => (open ? (cap === 'square' ? half : 0) : 0.75);+ const [s, e] = [end(!run.closed && i === 0), end(!run.closed && i === count - 1)];+ const [ax, ay, bx, by] = [a[0] - u[0] * s, a[1] - u[1] * s, b[0] + u[0] * e, b[1] + u[1] * e];+ convex([[ax + nx, ay + ny], [bx + nx, by + ny], [bx - nx, by - ny], [ax - nx, ay - ny]]);+ }+ if (!run.closed && cap === 'round') {+ capsule(pts[0]!, pts[0]!);+ capsule(pts[pts.length - 1]!, pts[pts.length - 1]!);+ }+ for (let i = run.closed ? 0 : 1; i < (run.closed ? pts.length : pts.length - 1); i++) {+ const p = pts[i]!;+ const [u0, u1] = [direction((i - 1 + pts.length) % pts.length), direction(i)];+ const cross = u0[0] * u1[1] - u0[1] * u1[0];+ if (join === 'round') {+ capsule(p, p);+ continue;}+ if (Math.abs(cross) < 1e-6) continue;+ // Turning toward +normal, the outside of the corner is the other side.+ const side = cross > 0 ? -1 : 1;+ const [n0, n1]: [Pt, Pt] = [[-u0[1] * side, u0[0] * side], [-u1[1] * side, u1[0] * side]];+ const [A, B]: [Pt, Pt] = [[p[0] + n0[0] * half, p[1] + n0[1] * half], [p[0] + n1[0] * half, p[1] + n1[1] * half]];+ const [mx, my] = [n0[0] + n1[0], n0[1] + n1[1]];+ const length = Math.hypot(mx, my);+ const ratio = length > 0 ? 2 / length : Infinity;+ if (join === 'miter' && ratio <= MITER_LIMIT) convex([p, A, [p[0] + (mx / length) * half * ratio, p[1] + (my / length) * half * ratio], B]);+ else convex([p, A, B]);}}return mask;@@ -419,7 +507,31 @@ function effectLayers(effects: readonly ImageEffect[] | undefined, under: boolea}}-interface Drawn { masks: Map<string, Float32Array>; notes: string[] }+interface Drawn { masks: Map<string, Float32Array>; notes: string[]; bounds: Map<string, ImageBox> }++/** x, y, width and height in the picture's pixels. */+export type ImageBox = readonly [number, number, number, number];++/** The box of whatever covers at least half a pixel: where a shape's edge is, and not the last faint pixel of a glow. */+function boxOf(w: number, h: number, covers: (i: number) => boolean): ImageBox | null {+ let [x0, y0, x1, y1] = [w, h, -1, -1];+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ if (!covers(y * w + x)) continue;+ if (x < x0) x0 = x;+ if (x > x1) x1 = x;+ if (y < y0) y0 = y;+ y1 = y;+ }+ }+ return x1 < 0 ? null : [x0, y0, x1 - x0 + 1, y1 - y0 + 1];+}++function noteBox(drawn: Drawn, id: string | undefined, mask: Float32Array, w: number, h: number): void {+ if (!id) return;+ const box = boxOf(w, h, (i) => mask[i]! >= 0.5);+ if (box) drawn.bounds.set(id, box);+}function drawLayer(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn): void {if (layer.visible === false) return;@@ -445,6 +557,7 @@ function drawLayer(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn):const alpha = new Float32Array(w * h);for (let i = 0; i < alpha.length; i++) alpha[i] = inner.px[i * 4 + 3]!;if (layer.id) drawn.masks.set(layer.id, alpha);+ noteBox(drawn, layer.id, alpha, w, h);effectLayers(layer.effects, true, c, alpha);for (let i = 0; i < alpha.length; i++) {const a = alpha[i]! * opacity * (clip ? clip[i]! : 1);@@ -469,7 +582,7 @@ function drawLayer(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn):const body = layer.shape === 'line' ? new Float32Array(w * h) : fillMask(placed.map((r) => r.points), w, h);const align = layer.stroke?.align ?? 'center';// An outside stroke is as wide again and goes under the fill. Cut to meet the fill's edge, each would cover part of the same edge pixel and the ground would show between them.- const line = layer.stroke ? strokeMask(placed, layer.stroke.width * scale * (align === 'outside' ? 2 : 1), w, h) : null;+ const line = layer.stroke ? strokeMask(placed, layer.stroke.width * scale * (align === 'outside' ? 2 : 1), w, h, layer.stroke.join, layer.stroke.cap) : null;if (line && align === 'inside') for (let i = 0; i < line.length; i++) line[i]! *= body[i]!;// Under a see-through fill it must not show, so only the edge pixels keep it.if (line && align === 'outside') for (let i = 0; i < line.length; i++) if (body[i]! >= 0.999) line[i] = 0;@@ -480,6 +593,7 @@ function drawLayer(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn):whole[i] = v;any += v;}+ noteBox(drawn, layer.id, whole, w, h);// What clips to this stays inside its stroke: liquid in a flask must not paint over the flask's outline.if (layer.id) {// A line has no inside but itself.@@ -549,12 +663,20 @@ function drawPixels(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn,});});if (layer.id) drawn.masks.set(layer.id, whole);+ noteBox(drawn, layer.id, whole, w, h);effectLayers(layer.effects, true, c, whole);for (let i = 0; i < whole.length; i++) put(c, i, colors[i * 3]!, colors[i * 3 + 1]!, colors[i * 3 + 2]!, whole[i]! * opacity, blend);effectLayers(layer.effects, false, c, whole);}-export interface RenderedImage extends RgbaBitmap { notes: string[] }+export interface RenderedImage extends RgbaBitmap {+ notes: string[];+ /** Where the picture is solid, null if nowhere, and how much of its area that is, 0..1: how large it looks beside others. */+ bounds: ImageBox | null;+ covers: number;+ /** The same box for each layer with an id, after every transform, without its effects. */+ layerBounds: Record<string, ImageBox>;+}/** Draws a source that has been validated. */export function renderImage(source: ImageSource): RenderedImage {@@ -564,7 +686,7 @@ export function renderImage(source: ImageSource): RenderedImage {const [r, g, b, a] = parseColor(source.background);for (let i = 0; i < w * h; i++) put(canvas, i, r, g, b, a, 'normal');}- const drawn: Drawn = { masks: new Map(), notes: [] };+ const drawn: Drawn = { masks: new Map(), notes: [], bounds: new Map() };for (const layer of source.layers) drawLayer(canvas, layer, IDENTITY, drawn);const rgba = new Uint8Array(w * h * 4);for (let i = 0; i < w * h; i++) {@@ -575,7 +697,14 @@ export function renderImage(source: ImageSource): RenderedImage {rgba[i * 4 + 2] = Math.round(Math.min(1, canvas.px[i * 4 + 2]! * d) * 255);rgba[i * 4 + 3] = Math.round(Math.min(1, a) * 255);}- return { width: w, height: h, rgba, notes: drawn.notes };+ let solid = 0;+ for (let i = 0; i < w * h; i++) if (rgba[i * 4 + 3]! >= 128) solid++;+ return {+ width: w, height: h, rgba, notes: drawn.notes,+ bounds: boxOf(w, h, (i) => rgba[i * 4 + 3]! >= 128),+ covers: Math.round((solid / (w * h)) * 1000) / 1000,+ layerBounds: Object.fromEntries(drawn.bounds),+ };}function shrink(src: RgbaBitmap, width: number, height: number): RgbaBitmap {diff --git a/pipeline/src/image/imageSource.ts b/pipeline/src/image/imageSource.tsindex 55fecbb9c..01d00b5df 100644--- a/pipeline/src/image/imageSource.ts+++ b/pipeline/src/image/imageSource.ts@@ -51,7 +51,7 @@ export interface ImageLayer {scale?: number;layers?: readonly ImageLayer[];fill?: ImageFill;- stroke?: { color: ImageFill; width: number; align?: 'center' | 'inside' | 'outside' };+ stroke?: { color: ImageFill; width: number; align?: 'center' | 'inside' | 'outside'; join?: 'round' | 'miter' | 'bevel'; cap?: 'round' | 'butt' | 'square' };opacity?: number;blend?: 'normal' | 'multiply' | 'screen' | 'overlay' | 'add';transform?: ImageTransform;@@ -153,6 +153,8 @@ function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>)const bad = checkFill(s.color);if (bad) fail(`stroke color ${bad}`);if (s.align !== undefined && !['center', 'inside', 'outside'].includes(s.align as string)) fail('stroke align must be center, inside or outside');+ if (s.join !== undefined && !['round', 'miter', 'bevel'].includes(s.join as string)) fail('stroke join must be round, miter or bevel');+ if (s.cap !== undefined && !['round', 'butt', 'square'].includes(s.cap as string)) fail('stroke cap must be round, butt or square');}if (!['group', 'pixels', 'line'].includes(l.shape as string) && l.fill === undefined && l.stroke === undefined && !l.erase) fail('it needs a fill or a stroke, or it draws nothing');if (l.opacity !== undefined && !(isNum(l.opacity) && l.opacity >= 0 && l.opacity <= 1)) fail('opacity must be 0..1');@@ -200,7 +202,13 @@ export type ImageEdit =| { op: 'move'; layer: string; before?: string; after?: string; into?: string }| { op: 'wrap'; layers: readonly string[]; group: Partial<ImageLayer> }| { op: 'unwrap'; layer: string }- | { op: 'pixels'; layer: string; set: readonly { row: number; at?: number; text: string }[] }+ | {+ op: 'pixels';+ layer: string;+ set?: readonly { row: number; at?: number; text: string }[];+ rect?: readonly { x: number; y: number; w?: number; h?: number; text: string }[];+ palette?: Readonly<Record<string, string | null>>;+ }| { op: 'settings'; fields: { size?: ImageSource['size']; background?: string | null } };/** Every stroke width a source draws with, and how many layers use each: what drifts first across a set of icons. */@@ -319,6 +327,27 @@ export function applyImageEdits(source: ImageSource, edits: readonly ImageEdit[]const layer = list[index]!;if (layer.shape !== 'pixels') throw new Error(`layer "${edit.layer}" is not pixels`);const rows = [...(layer.rows as string[])];+ if (edit.palette) {+ const palette = { ...(layer.palette as Record<string, string>) };+ for (const [key, value] of Object.entries(edit.palette)) {+ if (value === null) delete palette[key];+ else palette[key] = value;+ }+ layer.palette = palette;+ }+ for (const area of edit.rect ?? []) {+ const [w, h, char] = [area.w ?? 1, area.h ?? 1, [...(area.text ?? '')]];+ if (char.length !== 1) throw new Error(`a rect in "${edit.layer}" paints one character, not "${area.text}"`);+ const width = [...rows[0]!].length;+ if (!(Number.isInteger(area.x) && Number.isInteger(area.y) && Number.isInteger(w) && Number.isInteger(h) && area.x >= 0 && area.y >= 0 && w > 0 && h > 0 && area.x + w <= width && area.y + h <= rows.length)) {+ throw new Error(`layer "${edit.layer}" is ${width} by ${rows.length}: a rect of ${w} by ${h} at ${area.x}, ${area.y} does not fit`);+ }+ for (let y = area.y; y < area.y + h; y++) {+ const chars = [...rows[y]!];+ chars.fill(char[0]!, area.x, area.x + w);+ rows[y] = chars.join('');+ }+ }for (const change of edit.set ?? []) {const row = rows[change.row];if (row === undefined) throw new Error(`layer "${edit.layer}" has rows 0..${rows.length - 1}, not ${change.row}`);diff --git a/pipeline/tests/image-raster.test.ts b/pipeline/tests/image-raster.test.tsindex b8acd1707..c84ab8949 100644--- a/pipeline/tests/image-raster.test.ts+++ b/pipeline/tests/image-raster.test.ts@@ -138,6 +138,81 @@ describe('fills and strokes', () => {expect(px(outside, 21, 32)).toEqual([255, 0, 0, 255]);});+ describe('joins and ends', () => {+ const box = (join?: 'round' | 'miter' | 'bevel'): ImageLayer => ({ shape: 'rect', at: [16, 16], size: [32, 32], stroke: { color: BLUE, width: 8, ...(join ? { join } : {}) } });++ it('rounds a corner unless told otherwise', () => {+ expect(px(draw([box()]), 12, 12)[3]).toBe(0);+ expect(px(draw([box('round')]), 12, 12)[3]).toBe(0);+ });++ it('keeps a corner square when mitred, and cuts it when bevelled', () => {+ expect(px(draw([box('miter')]), 12, 12)).toEqual([0, 0, 255, 255]);+ const cut = draw([box('bevel')]);+ expect(px(cut, 12, 12)[3]).toBe(0);+ expect(px(cut, 15, 15)[3]).toBe(255);+ });++ it('brings a thin tip to a point, sharper than the round one', () => {+ const tip = (join: 'round' | 'miter'): number => {+ const img = draw([{ shape: 'polygon', points: [[32, 30], [40, 60], [24, 60]], stroke: { color: BLUE, width: 4, join } }]);+ for (let y = 0; y < 64; y++) if (px(img, 32, y)[3]! > 128) return y;+ return 64;+ };+ expect(tip('round')).toBeGreaterThanOrEqual(27);+ expect(tip('miter')).toBeLessThanOrEqual(25);+ });++ it('does not throw a long spike off a needle', () => {+ const img = draw([{ shape: 'polygon', points: [[32, 40], [33, 60], [31, 60]], stroke: { color: BLUE, width: 4, join: 'miter' } }]);+ for (let y = 0; y < 30; y++) expect(px(img, 32, y)[3]).toBe(0);+ });++ it('leaves no notch where a straight line has points along it, or round a curve', () => {+ const many: [number, number][] = Array.from({ length: 41 }, (_, i) => [12 + i + 0.3, 32.5]);+ const line = draw([{ shape: 'line', points: many, stroke: { color: BLUE, width: 5, cap: 'butt', join: 'miter' } }]);+ for (let x = 14; x < 50; x++) expect(px(line, x, 32)).toEqual([0, 0, 255, 255]);+ const round = draw([{ shape: 'circle', at: [32, 32], radius: 20.3, stroke: { color: BLUE, width: 4 } }]);+ const mitred = draw([{ shape: 'circle', at: [32, 32], radius: 20.3, stroke: { color: BLUE, width: 4, join: 'miter' } }]);+ let worst = 0;+ for (let i = 3; i < round.rgba.length; i += 4) worst = Math.max(worst, Math.abs(round.rgba[i]! - mitred.rgba[i]!));+ expect(worst).toBeLessThan(64);+ });++ it('leaves no faint tail past a sharp point', () => {+ const img = draw([{ shape: 'polygon', points: [[32, 30], [36, 60], [28, 60]], stroke: { color: BLUE, width: 4, join: 'miter' } }]);+ // The outer point is half the width over the sine of half the angle above the corner.+ const tip = 30 - 2 / Math.sin(Math.atan(4 / 30));+ for (let y = 0; y < Math.floor(tip) - 1; y++) expect(px(img, 32, y)[3]).toBe(0);+ expect(px(img, 32, Math.ceil(tip) + 2)[3]).toBeGreaterThan(0);+ });++ it('ends a line as it is told', () => {+ const end = (cap: 'round' | 'butt' | 'square'): ReturnType<typeof draw> => draw([{ shape: 'line', points: [[20, 32], [44, 32]], stroke: { color: BLUE, width: 8, cap } }]);+ expect(px(end('butt'), 18, 32)[3]).toBe(0);+ expect(px(end('butt'), 21, 32)[3]).toBe(255);+ expect(px(end('square'), 16, 28)[3]).toBe(255);+ expect(px(end('round'), 16, 28)[3]).toBe(0);+ expect(px(end('round'), 17, 32)[3]).toBe(255);+ });++ it('joins where a closed path repeats its first point', () => {+ const img = draw([{ shape: 'path', d: 'M16 16 L48 16 L48 48 L16 48 L16 16 Z', stroke: { color: BLUE, width: 8, join: 'miter' } }]);+ expect(px(img, 12, 12)).toEqual([0, 0, 255, 255]);+ });++ it('keeps an outside stroke\'s corner sharp too', () => {+ const img = draw([{ shape: 'rect', at: [16, 16], size: [32, 32], fill: RED, stroke: { color: BLUE, width: 4, align: 'outside', join: 'miter' } }]);+ expect(px(img, 13, 13)).toEqual([0, 0, 255, 255]);+ });++ it('refuses what is not one', () => {+ const bad = (stroke: object): unknown => validateImageSource({ size: 8, layers: [{ shape: 'circle', at: [4, 4], radius: 2, stroke: { color: RED, width: 1, ...stroke } }] });+ expect(() => bad({ join: 'sharp' })).toThrow(/join must be round, miter or bevel/);+ expect(() => bad({ cap: 'flat' })).toThrow(/cap must be round, butt or square/);+ });+ });+it('leaves no gap between a fill and its outside stroke, along a curve where edge pixels are partly each', () => {const img = draw([{ shape: 'circle', at: [32, 32], radius: 20.3, fill: RED, stroke: { color: BLUE, width: 4, align: 'outside' } }]);for (let i = 0; i < 128; i++) {@@ -396,6 +471,36 @@ describe('the sheet to look at', () => {});});+describe('what it measures', () => {+ it('finds where the picture is solid and how much of it that is', () => {+ const img = draw([{ shape: 'rect', at: [10, 20], size: [16, 8], fill: RED }]);+ expect(img.bounds).toEqual([10, 20, 16, 8]);+ expect(img.covers).toBeCloseTo((16 * 8) / (64 * 64), 2);+ expect(draw([{ shape: 'rect', at: [10, 20], size: [16, 8], fill: '#ff000020' }]).bounds).toBeNull();+ });++ it('leaves a faint glow out of it', () => {+ const img = draw([{ shape: 'rect', at: [20, 20], size: [24, 24], fill: RED, effects: [{ type: 'glow', blur: 6 }] }]);+ const [x, , w] = img.bounds!;+ expect(x).toBeGreaterThanOrEqual(16);+ expect(w).toBeLessThanOrEqual(32);+ });++ it('gives each named layer its box after transforms, stroke in and effects out, at any depth', () => {+ const img = draw([+ { shape: 'group', id: 'g', transform: { translate: [10, 0] }, layers: [{ id: 'r', shape: 'rect', at: [0, 0], size: [10, 10], fill: RED, stroke: { color: BLUE, width: 2 } }] },+ { shape: 'circle', at: [50, 50], radius: 4, fill: RED },+ { id: 'off', shape: 'rect', at: [100, 100], size: [4, 4], fill: RED },+ { id: 'hidden', shape: 'rect', at: [0, 0], size: [4, 4], fill: RED, visible: false },+ { id: 'p', shape: 'pixels', at: [0, 40], scale: 2, palette: { r: RED }, rows: ['r.', '.r'] },+ ]);+ expect(img.layerBounds.r).toEqual([9, 0, 12, 11]);+ expect(img.layerBounds.g).toEqual(img.layerBounds.r);+ expect(img.layerBounds.p).toEqual([0, 40, 4, 4]);+ expect(Object.keys(img.layerBounds).sort()).toEqual(['g', 'p', 'r']);+ });+});+describe('a set and a close look', () => {const a = draw([{ shape: 'rect', at: [0, 0], size: [64, 64], fill: RED }]);const b = draw([{ shape: 'rect', at: [0, 0], size: [32, 64], fill: BLUE }], [32, 64]);@@ -536,6 +641,25 @@ describe('edits', () => {expect(() => applyImageEdits(base, [{ op: 'pixels', layer: 'a', set: [] }])).toThrow(/not pixels/);});+ it('paints a column or an area, counting from 0', () => {+ const art = validateImageSource({ size: 8, layers: [{ id: 'art', shape: 'pixels', palette: { r: RED, b: BLUE }, rows: ['rrrr', 'rrrr', 'rrrr'] }] });+ expect(applyImageEdits(art, [{ op: 'pixels', layer: 'art', rect: [{ x: 1, y: 0, h: 3, text: 'b' }] }]).layers[0]!.rows).toEqual(['rbrr', 'rbrr', 'rbrr']);+ expect(applyImageEdits(art, [{ op: 'pixels', layer: 'art', rect: [{ x: 2, y: 1, w: 2, h: 2, text: '.' }] }]).layers[0]!.rows).toEqual(['rrrr', 'rr..', 'rr..']);+ expect(applyImageEdits(art, [{ op: 'pixels', layer: 'art', rect: [{ x: 3, y: 2, text: 'b' }] }]).layers[0]!.rows).toEqual(['rrrr', 'rrrr', 'rrrb']);+ expect(() => applyImageEdits(art, [{ op: 'pixels', layer: 'art', rect: [{ x: 3, y: 0, w: 2, text: 'b' }] }])).toThrow(/is 4 by 3.*does not fit/);+ expect(() => applyImageEdits(art, [{ op: 'pixels', layer: 'art', rect: [{ x: 0, y: 0, text: 'bb' }] }])).toThrow(/one character/);+ expect(() => applyImageEdits(art, [{ op: 'pixels', layer: 'art', rect: [{ x: 0, y: 0, text: 'x' }] }])).toThrow(/not in the palette/);+ });++ it('adds and removes a colour without restating the others', () => {+ const art = validateImageSource({ size: 8, layers: [{ id: 'art', shape: 'pixels', palette: { r: RED, b: BLUE }, rows: ['rr'] }] });+ const added = applyImageEdits(art, [{ op: 'pixels', layer: 'art', palette: { g: '#00ff00' }, rect: [{ x: 0, y: 0, text: 'g' }] }]).layers[0]!;+ expect(added.palette).toEqual({ r: RED, b: BLUE, g: '#00ff00' });+ expect(added.rows).toEqual(['gr']);+ expect(applyImageEdits(art, [{ op: 'pixels', layer: 'art', palette: { b: null } }]).layers[0]!.palette).toEqual({ r: RED });+ expect(() => applyImageEdits(art, [{ op: 'pixels', layer: 'art', palette: { r: null } }])).toThrow(/not in the palette/);+ });+it('says what it could not find, and refuses what would not be valid', () => {expect(() => applyImageEdits(base, [{ op: 'remove', layer: 'zz' }])).toThrow(/no layer "zz"; ids: a, g, b/);expect(() => applyImageEdits(base, [{ op: 'insert', layer: {} as never, into: 'a' }])).toThrow(/not a group/);diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 13e937f16..7ad361384 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -3888,6 +3888,10 @@ export const NOTED = {{"note":"An AI can draw 2D pictures."},"feat(look): layers moved and wrapped, one pixel changed, a set and a close look drawn":{"note":"An AI can draw 2D pictures."},+ "feat(look): stroke joins and ends, what a picture measures, pixels by the block":+ {"note":"An AI can draw 2D pictures."},+ "feat(mcp): a picture's reply measures it; stroke join and cap, pixel blocks":+ {"note":"An AI can draw 2D pictures."},"feat(mcp): image_set, a region in image_read, and what image_edit can now do":{"note":"An AI can draw 2D pictures."},"feat(mcp): image_write, image_edit and image_read":