Skip to content

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.

feat(look): layers moved and wrapped, one pixel changed, a set and a close look drawn

yhh99a08ec57d82
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d31c91a6b..e3ba74f4a 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 dark and light grounds and at 96, 64, 48 and 32 pixels, to look at and correct; `image_edit` changes one layer without restating the rest. 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 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 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/desktop
index b6e7cbd93..72dc23c8a 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit b6e7cbd9367beeb57577794b4b440c37f85dba39
+Subproject commit 72dc23c8a17a780fb4b0f388a6742355f1b06c9b
diff --git a/pipeline/src/image/imageRaster.ts b/pipeline/src/image/imageRaster.ts
index 60f850176..cde973d67 100644
--- a/pipeline/src/image/imageRaster.ts
+++ b/pipeline/src/image/imageRaster.ts
@@ -467,11 +467,12 @@ function drawLayer(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn):
const scale = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
const hasFill = layer.fill !== undefined && layer.shape !== 'line';
const body = layer.shape === 'line' ? new Float32Array(w * h) : fillMask(placed.map((r) => r.points), w, h);
- const line = layer.stroke ? strokeMask(placed, layer.stroke.width * scale, w, h) : null;
- if (line && layer.stroke!.align && layer.stroke!.align !== 'center') {
- const inside = layer.stroke!.align === 'inside';
- for (let i = 0; i < line.length; i++) line[i]! *= inside ? body[i]! : 1 - body[i]!;
- }
+ 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;
+ 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;
const whole = new Float32Array(w * h);
let any = 0;
for (let i = 0; i < whole.length; i++) {
@@ -479,7 +480,12 @@ function drawLayer(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn):
whole[i] = v;
any += v;
}
- if (layer.id) drawn.masks.set(layer.id, whole);
+ // 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.
+ const covering = align === 'outside' ? null : line;
+ drawn.masks.set(layer.id, layer.shape === 'line' ? whole : body.map((v, i) => v * (covering ? 1 - covering[i]! : 1) * (clip ? clip[i]! : 1)));
+ }
if (any === 0) drawn.notes.push(`layer ${layer.id ?? layer.shape} draws nothing inside the picture${clip ? ', or nothing inside its clip' : ''}`);
if (layer.erase) {
for (let i = 0; i < whole.length; i++) {
@@ -489,31 +495,33 @@ function drawLayer(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn):
return;
}
effectLayers(layer.effects, true, c, whole);
- if (hasFill) {
- const paint = paintOf(layer.fill!, m);
+ const paintLine = (): void => {
+ const paint = paintOf(layer.stroke!.color, m);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const i = y * w + x;
- const v = body[i]! * (clip ? clip[i]! : 1);
+ const v = line![i]! * (clip ? clip[i]! : 1);
if (v <= 0) continue;
const col = paint(x + 0.5, y + 0.5);
put(c, i, col[0], col[1], col[2], v * col[3] * opacity, blend);
}
}
- }
- effectLayers(layer.effects, false, c, whole);
- if (line) {
- const paint = paintOf(layer.stroke!.color, m);
+ };
+ if (line && align === 'outside') paintLine();
+ if (hasFill) {
+ const paint = paintOf(layer.fill!, m);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const i = y * w + x;
- const v = line[i]! * (clip ? clip[i]! : 1);
+ const v = body[i]! * (clip ? clip[i]! : 1);
if (v <= 0) continue;
const col = paint(x + 0.5, y + 0.5);
put(c, i, col[0], col[1], col[2], v * col[3] * opacity, blend);
}
}
}
+ effectLayers(layer.effects, false, c, whole);
+ if (line && align !== 'outside') paintLine();
}
const drawnScale = (m: Matrix): number => Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2])) || 1;
@@ -593,7 +601,75 @@ function shrink(src: RgbaBitmap, width: number, height: number): RgbaBitmap {
return { width, height, rgba };
}
-/** Something to look at: the picture on dark and on a light check, as a transparent image needs both, and at the sizes an icon is really seen. */
+type Ground = (x: number, y: number) => readonly [number, number, number];
+/** Between dark and light, so a dark outline and a pale highlight both show. On a near-black ground the outline a small icon wants disappears. */
+const midGround: Ground = () => [104, 112, 128];
+const checkGround: Ground = (x, y) => ((Math.floor(x / 12) + Math.floor(y / 12)) % 2 ? [226, 226, 230] : [250, 250, 252]);
+
+function layOn(rgba: Uint8Array, W: number, pic: RgbaBitmap, ox: number, oy: number, ground: Ground): void {
+ for (let y = 0; y < pic.height; y++) {
+ for (let x = 0; x < pic.width; x++) {
+ const from = (y * pic.width + x) * 4;
+ const a = pic.rgba[from + 3]! / 255;
+ const g = ground(x, y);
+ const to = ((oy + y) * W + ox + x) * 4;
+ rgba[to] = pic.rgba[from]! * a + g[0] * (1 - a);
+ rgba[to + 1] = pic.rgba[from + 1]! * a + g[1] * (1 - a);
+ rgba[to + 2] = pic.rgba[from + 2]! * a + g[2] * (1 - a);
+ rgba[to + 3] = 255;
+ }
+ }
+}
+
+const SHEET_GROUND = [64, 64, 68, 255] as const;
+
+function solidSheet(W: number, H: number): Uint8Array {
+ const rgba = new Uint8Array(W * H * 4);
+ for (let i = 0; i < W * H; i++) rgba.set(SHEET_GROUND, i * 4);
+ return rgba;
+}
+
+const fitted = (image: RgbaBitmap, size: number): RgbaBitmap => {
+ const k = size / Math.max(image.width, image.height);
+ const [w, h] = [Math.max(1, Math.round(image.width * k)), Math.max(1, Math.round(image.height * k))];
+ return k >= 1 ? nearestScale(image, w, h) : shrink(image, w, h);
+};
+
+/** Several pictures on one sheet, to be judged as a set: each on the mid ground and the check, then at 64 and 32, column by column. */
+export function setSheet(images: readonly RgbaBitmap[], cell = 128): RgbaBitmap {
+ if (images.length === 0) throw new Error('a set needs at least one picture');
+ const gap = 8;
+ const columns = Math.min(8, images.length);
+ const rows = Math.ceil(images.length / columns);
+ const tall = cell * 2 + 64 + 32 + gap * 5;
+ const W = columns * (cell + gap) + gap, H = rows * tall;
+ const rgba = solidSheet(W, H);
+ images.forEach((image, n) => {
+ const [ox, oy] = [gap + (n % columns) * (cell + gap), Math.floor(n / columns) * tall + gap];
+ const big = fitted(image, cell);
+ layOn(rgba, W, big, ox, oy, midGround);
+ layOn(rgba, W, big, ox, oy + cell + gap, checkGround);
+ layOn(rgba, W, fitted(image, 64), ox, oy + cell * 2 + gap * 2, midGround);
+ layOn(rgba, W, fitted(image, 32), ox, oy + cell * 2 + 64 + gap * 3, midGround);
+ });
+ return { width: W, height: H, rgba };
+}
+
+/** A part of a picture enlarged with hard pixels on the check, to see what the whole hides: a seam one pixel wide. */
+export function zoomImage(image: RgbaBitmap, region: { x: number; y: number; w: number; h: number }, longest = 640): RgbaBitmap {
+ const [x0, y0] = [Math.max(0, Math.floor(region.x)), Math.max(0, Math.floor(region.y))];
+ const [w, h] = [Math.min(image.width - x0, Math.round(region.w)), Math.min(image.height - y0, Math.round(region.h))];
+ if (!(w > 0 && h > 0)) throw new Error(`region ${JSON.stringify(region)} is outside the picture, ${image.width} by ${image.height}`);
+ const cut = new Uint8Array(w * h * 4);
+ for (let y = 0; y < h; y++) cut.set(image.rgba.subarray(((y0 + y) * image.width + x0) * 4, ((y0 + y) * image.width + x0 + w) * 4), y * w * 4);
+ const k = Math.max(1, Math.floor(longest / Math.max(w, h)));
+ const big = nearestScale({ width: w, height: h, rgba: cut }, w * k, h * k);
+ const rgba = solidSheet(big.width, big.height);
+ layOn(rgba, big.width, big, 0, 0, checkGround);
+ return { width: big.width, height: big.height, rgba };
+}
+
+/** Something to look at: the picture on a mid ground and on a light check, as a transparent image needs both, and at the sizes an icon is really seen. */
export function imageSheet(image: RgbaBitmap, sizes: readonly number[] = [96, 64, 48, 32]): RgbaBitmap {
const big = Math.max(image.width, image.height);
const k = big < 384 ? Math.max(1, Math.floor(384 / big)) : Math.min(1, 512 / big);
@@ -605,28 +681,13 @@ export function imageSheet(image: RgbaBitmap, sizes: readonly number[] = [96, 64
const rgba = new Uint8Array(W * H * 4);
for (let i = 0; i < W * H; i++) rgba.set([64, 64, 68, 255], i * 4);
const scaled = k >= 1 ? nearestScale(image, pw, ph) : shrink(image, pw, ph);
- const lay = (pic: RgbaBitmap, ox: number, oy: number, ground: (x: number, y: number) => readonly [number, number, number]): void => {
- for (let y = 0; y < pic.height; y++) {
- for (let x = 0; x < pic.width; x++) {
- const from = (y * pic.width + x) * 4;
- const a = pic.rgba[from + 3]! / 255;
- const g = ground(x, y);
- const to = ((oy + y) * W + ox + x) * 4;
- rgba[to] = pic.rgba[from]! * a + g[0] * (1 - a);
- rgba[to + 1] = pic.rgba[from + 1]! * a + g[1] * (1 - a);
- rgba[to + 2] = pic.rgba[from + 2]! * a + g[2] * (1 - a);
- rgba[to + 3] = 255;
- }
- }
- };
- const dark = (): readonly [number, number, number] => [24, 26, 32];
- const check = (x: number, y: number): readonly [number, number, number] => ((Math.floor(x / 12) + Math.floor(y / 12)) % 2 ? [226, 226, 230] : [250, 250, 252]);
- lay(scaled, gap, gap, dark);
- lay(scaled, gap * 2 + pw, gap, check);
+ const lay = (pic: RgbaBitmap, ox: number, oy: number, ground: Ground): void => layOn(rgba, W, pic, ox, oy, ground);
+ lay(scaled, gap, gap, midGround);
+ lay(scaled, gap * 2 + pw, gap, checkGround);
let oy = gap;
for (const s of sizes) {
const small = shrink(image, s, Math.max(1, Math.round((s * image.height) / image.width)));
- lay(small, gap * 3 + pw * 2, oy, dark);
+ lay(small, gap * 3 + pw * 2, oy, midGround);
oy += small.height + gap;
}
return { width: W, height: H, rgba };
diff --git a/pipeline/src/image/imageSource.ts b/pipeline/src/image/imageSource.ts
index cac4b318d..55fecbb9c 100644
--- a/pipeline/src/image/imageSource.ts
+++ b/pipeline/src/image/imageSource.ts
@@ -3,6 +3,8 @@
/**
* @file imageSource.ts — `.esimage`: a picture as a list of layers, what a model writes and edits, and what is wrong with one.
*/
+import { parsePath } from './imageRaster';
+
export const IMAGE_SOURCE_EXT = '.esimage';
export const IMAGE_SOURCE_VERSION = 1;
export const MAX_IMAGE_SIZE = 2048;
@@ -111,7 +113,15 @@ function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>)
if (l.shape === 'line' && !l.stroke) fail('a line needs a stroke: { color, width }');
break;
case 'star': case 'gear': pair('at'); num('radius', positive); num('inner', positive); if (!Number.isInteger(l.count) || (l.count as number) < 3) fail('count must be 3 or more'); break;
- case 'path': if (typeof l.d !== 'string' || !l.d.trim()) fail('d must be an SVG path: M L H V C S Q T Z'); break;
+ case 'path':
+ if (typeof l.d !== 'string' || !l.d.trim()) fail('d must be an SVG path: M L H V C S Q T Z');
+ // Here and not when it is drawn: a hidden layer is not drawn, and an error waits until it is shown.
+ try {
+ if (parsePath(l.d as string).every((run) => run.points.length === 0)) fail('d draws nothing');
+ } catch (e) {
+ fail((e as Error).message);
+ }
+ break;
case 'pixels': {
if (!Array.isArray(l.rows) || l.rows.length === 0 || !l.rows.every((r) => typeof r === 'string')) fail('rows must be strings, one character a pixel');
const pal = l.palette as Record<string, unknown> | undefined;
@@ -187,8 +197,25 @@ export type ImageEdit =
| { op: 'set'; layer: string; fields: Record<string, unknown> }
| { op: 'insert'; layer: ImageLayer; before?: string; after?: string; into?: string }
| { op: 'remove'; layer: string }
+ | { 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: '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. */
+export function strokeWidths(source: ImageSource): Record<string, number> {
+ const out: Record<string, number> = {};
+ const walk = (layers: readonly ImageLayer[]): void => {
+ for (const l of layers) {
+ if (l.stroke) out[String(l.stroke.width)] = (out[String(l.stroke.width)] ?? 0) + 1;
+ if (l.layers) walk(l.layers);
+ }
+ };
+ walk(source.layers);
+ return out;
+}
+
/** A source with @p edits applied in order, where layers are named by id at any depth. Throws, naming what it could not find. */
export function applyImageEdits(source: ImageSource, edits: readonly ImageEdit[]): ImageSource {
const clone = JSON.parse(JSON.stringify(source)) as { size: ImageSource['size']; background?: string; version?: number; layers: (ImageLayer & Record<string, unknown>)[] };
@@ -242,13 +269,74 @@ export function applyImageEdits(source: ImageSource, edits: readonly ImageEdit[]
list.splice(index, 1);
break;
}
+ case 'move': {
+ const given = [edit.before, edit.after, edit.into].filter((v) => v !== undefined);
+ if (given.length > 1) throw new Error('move takes one of before, after and into');
+ const { list, index } = need(edit.layer);
+ const [row] = list.splice(index, 1);
+ const within = (l: Row): boolean => l.id === given[0] || ((l.layers as Row[] | undefined) ?? []).some(within);
+ if (given.length && within(row!)) {
+ list.splice(index, 0, row!);
+ throw new Error(`layer "${edit.layer}" cannot move next to or into "${String(given[0])}", which is itself or inside it`);
+ }
+ if (edit.into !== undefined) {
+ const target = need(edit.into);
+ const group = target.list[target.index]!;
+ if (group.shape !== 'group') throw new Error(`layer "${edit.into}" is not a group`);
+ (group.layers as Row[]).push(row!);
+ } else if (edit.before !== undefined) {
+ const target = need(edit.before);
+ target.list.splice(target.index, 0, row!);
+ } else if (edit.after !== undefined) {
+ const target = need(edit.after);
+ target.list.splice(target.index + 1, 0, row!);
+ } else clone.layers.push(row!);
+ break;
+ }
+ case 'wrap': {
+ if (!Array.isArray(edit.layers) || edit.layers.length === 0) throw new Error('wrap needs layers, the ids to put in the group');
+ const found = edit.layers.map((id) => ({ id, ...need(id) }));
+ if (found.some((f) => f.list !== found[0]!.list)) throw new Error(`wrap takes layers side by side, and ${edit.layers.join(', ')} are not all in one list`);
+ const list = found[0]!.list;
+ // Kept in the order they draw, whatever order they were named in: wrapping must not change what is over what.
+ const indices = found.map((f) => f.index).sort((a, b) => a - b);
+ const children = indices.map((i) => list[i]!);
+ for (const i of [...indices].reverse()) list.splice(i, 1);
+ list.splice(indices[0]!, 0, { ...edit.group, shape: 'group', layers: children } as Row);
+ break;
+ }
+ case 'unwrap': {
+ const { list, index } = need(edit.layer);
+ const group = list[index]!;
+ if (group.shape !== 'group') throw new Error(`layer "${edit.layer}" is not a group`);
+ const kept = ['transform', 'effects', 'opacity', 'blend', 'clip', 'mirror', 'visible'].filter((k) => group[k] !== undefined);
+ if (kept.length) throw new Error(`group "${edit.layer}" has ${kept.join(', ')}, which its layers would lose; set them to null first`);
+ list.splice(index, 1, ...(group.layers as Row[]));
+ break;
+ }
+ case 'pixels': {
+ const { list, index } = need(edit.layer);
+ const layer = list[index]!;
+ if (layer.shape !== 'pixels') throw new Error(`layer "${edit.layer}" is not pixels`);
+ const rows = [...(layer.rows as string[])];
+ 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}`);
+ const chars = [...row], text = [...change.text], at = change.at ?? 0;
+ if (at < 0 || at + text.length > chars.length) throw new Error(`row ${change.row} of "${edit.layer}" is ${chars.length} wide: ${text.length} at ${at} does not fit`);
+ chars.splice(at, text.length, ...text);
+ rows[change.row] = chars.join('');
+ }
+ layer.rows = rows;
+ break;
+ }
case 'settings':
if (edit.fields?.size !== undefined) clone.size = edit.fields.size;
if (edit.fields?.background === null) delete clone.background;
else if (edit.fields?.background !== undefined) clone.background = edit.fields.background;
break;
default:
- throw new Error(`an edit has op ${JSON.stringify((edit as { op?: unknown })?.op)}; there are set, insert, remove, settings`);
+ throw new Error(`an edit has op ${JSON.stringify((edit as { op?: unknown })?.op)}; there are set, insert, remove, move, wrap, unwrap, pixels, settings`);
}
}
return validateImageSource(clone);
diff --git a/pipeline/tests/image-raster.test.ts b/pipeline/tests/image-raster.test.ts
index a4aeb606f..b8acd1707 100644
--- a/pipeline/tests/image-raster.test.ts
+++ b/pipeline/tests/image-raster.test.ts
@@ -2,8 +2,8 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/** A picture from layers: each draws what it says and where, edges are antialiased, and what is wrong with a source is said before anything is drawn. */
import { describe, expect, it } from 'vitest';
-import { imageSheet, parseColor, parsePath, renderImage } from '../src/image/imageRaster';
-import { applyImageEdits, validateImageSource, type ImageLayer } from '../src/image/imageSource';
+import { imageSheet, parseColor, parsePath, renderImage, setSheet, zoomImage } from '../src/image/imageRaster';
+import { applyImageEdits, strokeWidths, validateImageSource, type ImageLayer } from '../src/image/imageSource';
const draw = (layers: unknown[], size: number | [number, number] = 64, background?: string): ReturnType<typeof renderImage> => renderImage(validateImageSource({ size, layers, ...(background ? { background } : {}) }));
const px = (img: { width: number; rgba: Uint8Array }, x: number, y: number): number[] => Array.from(img.rgba.subarray((y * img.width + x) * 4, (y * img.width + x) * 4 + 4));
@@ -137,6 +137,20 @@ describe('fills and strokes', () => {
expect(px(outside, 18, 32)[2]).toBeGreaterThan(200);
expect(px(outside, 21, 32)).toEqual([255, 0, 0, 255]);
});
+
+ 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++) {
+ const a = (i / 128) * Math.PI * 2;
+ const [x, y] = [Math.floor(32 + 20.3 * Math.cos(a)), Math.floor(32 + 20.3 * Math.sin(a))];
+ expect(px(img, x, y)[3]).toBeGreaterThan(250);
+ }
+ });
+
+ it('does not show an outside stroke through a see-through fill', () => {
+ const img = draw([{ shape: 'circle', at: [32, 32], radius: 20, fill: '#ff000040', stroke: { color: BLUE, width: 4, align: 'outside' } }]);
+ expect(px(img, 32, 20)[2]).toBe(0);
+ });
});
describe('layers', () => {
@@ -190,6 +204,51 @@ describe('layers', () => {
expect(px(img, 5, 50)[3]).toBe(0);
});
+ it('a clip stays inside the other layer\'s stroke, which still shows', () => {
+ const img = draw([
+ { id: 'glass', shape: 'circle', at: [32, 32], radius: 20, fill: '#ffffff', stroke: { color: BLUE, width: 4 } },
+ { shape: 'rect', at: [0, 0], size: [64, 64], fill: RED, clip: 'glass' },
+ ]);
+ expect(px(img, 32, 32)).toEqual([255, 0, 0, 255]);
+ // On the stroke, a little in from the edge of the fill: blue, not red.
+ expect(px(img, 32, 13)[2]).toBe(255);
+ expect(px(img, 32, 13)[0]).toBe(0);
+ });
+
+ it('a clip keeps to the fill when the stroke is outside it, and a stroke-only shape has an inside too', () => {
+ const outside = draw([
+ { id: 'glass', shape: 'circle', at: [32, 32], radius: 20, fill: '#ffffff', stroke: { color: BLUE, width: 4, align: 'outside' } },
+ { shape: 'rect', at: [0, 0], size: [64, 64], fill: RED, clip: 'glass' },
+ ]);
+ expect(px(outside, 32, 14)).toEqual([255, 0, 0, 255]);
+ expect(px(outside, 32, 10)[2]).toBe(255);
+ const hollow = draw([
+ { id: 'o', shape: 'circle', at: [32, 32], radius: 20, stroke: { color: BLUE, width: 4 } },
+ { shape: 'rect', at: [0, 0], size: [64, 64], fill: RED, clip: 'o' },
+ ]);
+ expect(px(hollow, 32, 32)).toEqual([255, 0, 0, 255]);
+ });
+
+ it('a clip inside a clip stays inside both', () => {
+ const img = draw([
+ { id: 'left', shape: 'rect', at: [0, 0], size: [32, 64], fill: BLUE },
+ { id: 'top', shape: 'rect', at: [0, 0], size: [64, 32], fill: BLUE, clip: 'left' },
+ { shape: 'rect', at: [0, 0], size: [64, 64], fill: RED, clip: 'top' },
+ ]);
+ expect(px(img, 10, 10)).toEqual([255, 0, 0, 255]);
+ expect(px(img, 50, 10)[0]).toBe(0);
+ expect(px(img, 10, 50)[0]).toBe(0);
+ });
+
+ it('a line has no inside: what clips to it keeps to the line', () => {
+ const img = draw([
+ { id: 'l', shape: 'line', points: [[0, 32], [64, 32]], stroke: { color: BLUE, width: 6 } },
+ { shape: 'rect', at: [0, 0], size: [64, 64], fill: RED, clip: 'l' },
+ ]);
+ expect(px(img, 32, 32)).toEqual([255, 0, 0, 255]);
+ expect(px(img, 32, 10)[3]).toBe(0);
+ });
+
it('says when a clip names nothing, and when a layer draws nothing', () => {
expect(draw([{ shape: 'rect', at: [0, 0], size: [10, 10], fill: RED, clip: 'gone' }]).notes.join()).toMatch(/clip "gone"/);
expect(draw([{ shape: 'rect', at: [500, 500], size: [10, 10], fill: RED, id: 'away' }]).notes.join()).toMatch(/away draws nothing/);
@@ -309,6 +368,16 @@ describe('a picture', () => {
describe('the sheet to look at', () => {
const img = draw([{ shape: 'rect', at: [0, 0], size: [64, 64], fill: '#ff000080' }]);
+ it('shows a dark outline and a pale one alike on its ground', () => {
+ const pic = draw([{ shape: 'circle', at: [32, 32], radius: 20, stroke: { color: '#1b1f2e', width: 6 } }, { shape: 'circle', at: [32, 32], radius: 8, fill: '#ffffff' }]);
+ const sheet = imageSheet(pic, []);
+ const sample = (x: number, y: number): number => sheet.rgba[(y * sheet.width + x) * 4 + 1]!;
+ // 64 x 6 = 384 across; the ground, the dark ring and the white middle, each well apart.
+ const [ground, ring, middle] = [sample(8 + 30, 8 + 30), sample(8 + 192, 8 + 72), sample(8 + 192, 8 + 192)];
+ expect(ground - ring).toBeGreaterThan(50);
+ expect(middle - ground).toBeGreaterThan(50);
+ });
+
it('is opaque, with the picture over two grounds and at small sizes', () => {
const sheet = imageSheet(img, [32, 16]);
for (let i = 3; i < sheet.rgba.length; i += 4) expect(sheet.rgba[i]).toBe(255);
@@ -327,6 +396,37 @@ describe('the sheet to look at', () => {
});
});
+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]);
+
+ it('lays pictures out in columns, in order, each whole, whatever its shape', () => {
+ const sheet = setSheet([a, b], 128);
+ expect(sheet.width).toBe(8 + (128 + 8) * 2);
+ const at = (x: number, y: number): number[] => Array.from(sheet.rgba.subarray((y * sheet.width + x) * 4, (y * sheet.width + x) * 4 + 3));
+ expect(at(8 + 64, 8 + 64)).toEqual([255, 0, 0]);
+ expect(at(8 + 136 + 32, 8 + 64)).toEqual([0, 0, 255]);
+ for (let i = 3; i < sheet.rgba.length; i += 4) expect(sheet.rgba[i]).toBe(255);
+ expect(() => setSheet([])).toThrow(/at least one/);
+ });
+
+ it('goes on to another row past eight', () => {
+ const sheet = setSheet(Array.from({ length: 9 }, () => a), 32);
+ expect(sheet.height).toBe(setSheet([a], 32).height * 2);
+ });
+
+ it('enlarges a part with hard pixels, on the check where it is clear', () => {
+ const half = draw([{ shape: 'rect', at: [10, 0], size: [54, 64], fill: RED }]);
+ const big = zoomImage(half, { x: 8, y: 8, w: 4, h: 4 });
+ expect(big.width).toBe(640);
+ const at = (x: number, y: number): number[] => Array.from(big.rgba.subarray((y * big.width + x) * 4, (y * big.width + x) * 4 + 3));
+ // Two pixels of nothing and two of red, each 160 wide, and no blur between.
+ expect(at(321, 80)).toEqual([255, 0, 0]);
+ expect(at(319, 80)[1]).toBeGreaterThan(200);
+ expect(() => zoomImage(half, { x: 500, y: 0, w: 4, h: 4 })).toThrow(/outside the picture/);
+ });
+});
+
describe('the source', () => {
const ok = (layers: unknown[]): unknown => ({ size: 16, layers });
@@ -347,6 +447,16 @@ describe('the source', () => {
expect(() => validateImageSource(ok([{ id: 'a', shape: 'circle', at: [0, 0], radius: 1, fill: RED }, { id: 'a', shape: 'circle', at: [0, 0], radius: 1, fill: RED }]))).toThrow(/already used/);
expect(() => validateImageSource(ok([{ shape: 'group', layers: [{ shape: 'blob' }] }]))).toThrow(/layers\[0\]/);
});
+
+ it('finds a bad path before it is drawn, in a hidden layer too, and names the layer', () => {
+ expect(() => validateImageSource(ok([{ id: 'p', shape: 'path', d: 'M0 0 A5 5 0 0 1 9 9', fill: RED, visible: false }]))).toThrow(/layer 0 "p".*M L H V C S Q T Z/);
+ expect(() => validateImageSource(ok([{ shape: 'group', layers: [{ shape: 'path', d: 'M0', fill: RED }] }]))).toThrow(/layers\[0\].*short of numbers/);
+ });
+
+ it('counts the stroke widths in it, at any depth', () => {
+ const s = validateImageSource(ok([{ shape: 'circle', at: [1, 1], radius: 1, stroke: { color: RED, width: 4 } }, { shape: 'group', layers: [{ shape: 'circle', at: [1, 1], radius: 1, stroke: { color: RED, width: 4 } }, { shape: 'circle', at: [1, 1], radius: 1, stroke: { color: RED, width: 2 } }] }]));
+ expect(strokeWidths(s)).toEqual({ 4: 2, 2: 1 });
+ });
});
describe('edits', () => {
@@ -374,10 +484,62 @@ describe('edits', () => {
expect(applyImageEdits(base, [{ op: 'settings', fields: { background: '#000' } }, { op: 'settings', fields: { background: null } }]).background).toBeUndefined();
});
+ const row = validateImageSource({ size: 16, layers: [1, 2, 3, 4].map((n) => ({ id: `l${n}`, shape: 'circle', at: [n, n], radius: 1, fill: RED })) });
+
+ it('moves a layer where it is told', () => {
+ expect(ids(applyImageEdits(row, [{ op: 'move', layer: 'l4', before: 'l1' }]).layers)).toEqual(['l4', 'l1', 'l2', 'l3']);
+ expect(ids(applyImageEdits(row, [{ op: 'move', layer: 'l1', after: 'l3' }]).layers)).toEqual(['l2', 'l3', 'l1', 'l4']);
+ expect(ids(applyImageEdits(row, [{ op: 'move', layer: 'l1' }]).layers)).toEqual(['l2', 'l3', 'l4', 'l1']);
+ expect(ids(applyImageEdits(base, [{ op: 'move', layer: 'a', into: 'g' }]).layers)).toEqual(['g']);
+ expect(ids(applyImageEdits(base, [{ op: 'move', layer: 'b', before: 'a' }]).layers)).toEqual(['b', 'a', 'g']);
+ });
+
+ it('will not move a group into itself', () => {
+ expect(() => applyImageEdits(base, [{ op: 'move', layer: 'g', into: 'b' }])).toThrow(/itself or inside it/);
+ expect(() => applyImageEdits(base, [{ op: 'move', layer: 'a', before: 'l9' }])).toThrow(/no layer "l9"/);
+ expect(() => applyImageEdits(base, [{ op: 'move', layer: 'a', before: 'g', after: 'b' }])).toThrow(/one of/);
+ });
+
+ it('wraps layers into a group where the first was, in drawing order however they were named', () => {
+ const next = applyImageEdits(row, [{ op: 'wrap', layers: ['l3', 'l2'], group: { id: 'g', transform: { rotate: 10 } } }]);
+ expect(ids(next.layers)).toEqual(['l1', 'g', 'l4']);
+ expect(ids(next.layers[1]!.layers!)).toEqual(['l2', 'l3']);
+ expect(next.layers[1]!.transform?.rotate).toBe(10);
+ });
+
+ it('wrapping changes nothing drawn until the group is given something', () => {
+ const before = renderImage(validateImageSource({ size: 32, layers: [{ id: 'a', shape: 'circle', at: [16, 16], radius: 9, fill: RED }, { id: 'b', shape: 'circle', at: [20, 16], radius: 9, fill: BLUE }] }));
+ const after = renderImage(applyImageEdits(validateImageSource({ size: 32, layers: [{ id: 'a', shape: 'circle', at: [16, 16], radius: 9, fill: RED }, { id: 'b', shape: 'circle', at: [20, 16], radius: 9, fill: BLUE }] }), [{ op: 'wrap', layers: ['a', 'b'], group: { id: 'g' } }]));
+ let worst = 0;
+ for (let i = 0; i < before.rgba.length; i++) worst = Math.max(worst, Math.abs(before.rgba[i]! - after.rgba[i]!));
+ expect(worst).toBeLessThanOrEqual(2);
+ });
+
+ it('wraps only what lies side by side', () => {
+ expect(() => applyImageEdits(base, [{ op: 'wrap', layers: ['a', 'b'], group: {} }])).toThrow(/not all in one list/);
+ expect(() => applyImageEdits(base, [{ op: 'wrap', layers: [], group: {} }])).toThrow(/needs layers/);
+ });
+
+ it('unwraps a group back into its place, and will not lose what it holds', () => {
+ expect(ids(applyImageEdits(base, [{ op: 'unwrap', layer: 'g' }]).layers)).toEqual(['a', 'b']);
+ const tilted = applyImageEdits(base, [{ op: 'set', layer: 'g', fields: { transform: { rotate: 5 } } }]);
+ expect(() => applyImageEdits(tilted, [{ op: 'unwrap', layer: 'g' }])).toThrow(/transform, which its layers would lose/);
+ expect(() => applyImageEdits(base, [{ op: 'unwrap', layer: 'a' }])).toThrow(/not a group/);
+ });
+
+ it('changes a pixel without restating the rows', () => {
+ const art = validateImageSource({ size: 8, layers: [{ id: 'art', shape: 'pixels', palette: { r: RED, b: BLUE }, rows: ['rrrr', 'rrrr'] }] });
+ expect(applyImageEdits(art, [{ op: 'pixels', layer: 'art', set: [{ row: 1, at: 2, text: 'bb' }, { row: 0, text: 'b' }] }]).layers[0]!.rows).toEqual(['brrr', 'rrbb']);
+ expect(() => applyImageEdits(art, [{ op: 'pixels', layer: 'art', set: [{ row: 5, text: 'b' }] }])).toThrow(/rows 0\.\.1/);
+ expect(() => applyImageEdits(art, [{ op: 'pixels', layer: 'art', set: [{ row: 0, at: 3, text: 'bb' }] }])).toThrow(/does not fit/);
+ expect(() => applyImageEdits(art, [{ op: 'pixels', layer: 'art', set: [{ row: 0, text: 'x' }] }])).toThrow(/not in the palette/);
+ expect(() => applyImageEdits(base, [{ op: 'pixels', layer: 'a', set: [] }])).toThrow(/not pixels/);
+ });
+
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/);
expect(() => applyImageEdits(base, [{ op: 'set', layer: 'a', fields: { radius: -1 } }])).toThrow(/radius/);
- expect(() => applyImageEdits(base, [{ op: 'spin' } as never])).toThrow(/set, insert, remove, settings/);
+ expect(() => applyImageEdits(base, [{ op: 'spin' } as never])).toThrow(/set, insert, remove, move, wrap, unwrap, pixels, settings/);
});
});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 307125c16..13e937f16 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3886,6 +3886,10 @@ export const NOTED = {
{"note":"A WeChat mini-game opens in WeChat DevTools."},
"feat(look): layers and pixels drawn to a picture, on the CPU":
{"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(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":
{"note":"An AI can draw 2D pictures."},
"feat(modeling): a whole person from a few numbers, clothes from the body's own surface, and a pose by where a hand should be":