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): a figure is bones and blocks, and a picture from the project can be drawn over
yhhc69c18e9abde
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c8cc5c39f..d3da58580 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, 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. A layer or group can be blurred, for depth of field, and a fill can be noise for cloud, texture and film grain, the same picture from the same seed. A `paint` layer is a canvas of brush strokes with pressure, softness, tapering, bristles and smudging, added to round by round, for what shapes cannot do; one `sweep` instruction lays a mass of hair gathered into locks, one `field` covers a region in strokes along a flow, and one `along` repeats strokes along a line. A layer can work across everything under it, to fuse separate parts into one painting, and `image_read` shows lightness alone and reads colours. A `figure` layer is a real posed body from any angle to draw over: left out of the `.png`, it reports where each joint landed, offers each body part as a region, and lets light follow the form. `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 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. A layer or group can be blurred, for depth of field, and a fill can be noise for cloud, texture and film grain, the same picture from the same seed. A `paint` layer is a canvas of brush strokes with pressure, softness, tapering, bristles and smudging, added to round by round, for what shapes cannot do; one `sweep` instruction lays a mass of hair gathered into locks, one `field` covers a region in strokes along a flow, and one `along` repeats strokes along a line. A layer can work across everything under it, to fuse separate parts into one painting, and `image_read` shows lightness alone and reads colours. A `figure` layer is a posed skeleton in plain blocks from any angle to draw over, and an `image` layer brings in the team's own art: both stay out of the `.png`, and the figure reports where each joint landed and lets broad light follow the form. `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 33505a82d..0e7c6081f 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 33505a82d2ce560078c993d74a8bf3e0f92b3e65+Subproject commit 0e7c6081f88be99a355ca03bb6991e50a628aac7diff --git a/pipeline/src/image/imageFigure.ts b/pipeline/src/image/imageFigure.tsindex 90e71f6d9..279f3140d 100644--- a/pipeline/src/image/imageFigure.ts+++ b/pipeline/src/image/imageFigure.ts@@ -2,87 +2,122 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file imageFigure.ts- * @brief A real human body, posed and seen from an angle, flattened to what a 2D picture can draw over.+ * @brief A posed skeleton with plain volumes on it, seen from an angle: a figure drawing's first lines, for a 2D picture to build on.*- * Coordinates typed blind drift: a body comes out wide or stiff and nothing says so. This is the 3D body the modeling tools build,- * so its proportions and its foreshortening are right from any side, and what is reported is where each joint landed in the picture.+ * Bones and blocks on purpose. They give gesture, proportion and foreshortening, which coordinates typed blind get wrong, and no look:+ * no face, no skin, no hair, as whatever a model is handed it copies, and a coloured mannequin is what comes back.*/-import { humanoid, type HumanoidBuild } from '../modeling/humanoid';-import { poseJoints, poseStep, type PoseParams } from '../modeling/pose';-import type { PolyMesh, Vec3 } from '../modeling/polyMesh';+import type { HumanoidBuild } from '../modeling/humanoid';+import { poseFrames, poseJoints, type PoseParams } from '../modeling/pose';import type { ImageLayer } from './imageSource';-/** The table's own height: figures are built at it, and sized in the picture. */+/** The bones' own height: they are built at it, and sized in the picture. */const BODY_HEIGHT = 1.6;-/** The lowest the body builds at. Finer costs seconds and shows nothing at picture scale. */-const BODY_RESOLUTION = 160;const SUPERSAMPLE = 2;-const KEPT = 6;+const AROUND = 14;-export const FIGURE_TAGS = ['torso', 'arm', 'hand', 'leg', 'foot', 'neck', 'face', 'scalp', 'ear', 'lips', 'lid', 'eye', 'iris'] as const;+type V3 = readonly [number, number, number];++export const FIGURE_TAGS = ['torso', 'arm', 'hand', 'leg', 'foot', 'neck', 'head'] as const;export const FIGURE_JOINTS = ['crown', 'head', 'neck', 'chest', 'spine', 'hips','upperArm.L', 'forearm.L', 'hand.L', 'middle4.L', 'upperArm.R', 'forearm.R', 'hand.R', 'middle4.R','thigh.L', 'shin.L', 'foot.L', 'toeTip.L', 'thigh.R', 'shin.R', 'foot.R', 'toeTip.R',] as const;+const BONES: readonly (readonly [string, string])[] = [+ ['hips', 'spine'], ['spine', 'chest'], ['chest', 'neck'], ['neck', 'head'], ['head', 'crown'],+ ['chest', 'upperArm.L'], ['upperArm.L', 'forearm.L'], ['forearm.L', 'hand.L'], ['hand.L', 'middle4.L'],+ ['chest', 'upperArm.R'], ['upperArm.R', 'forearm.R'], ['forearm.R', 'hand.R'], ['hand.R', 'middle4.R'],+ ['hips', 'thigh.L'], ['thigh.L', 'shin.L'], ['shin.L', 'foot.L'], ['foot.L', 'toeTip.L'],+ ['hips', 'thigh.R'], ['thigh.R', 'shin.R'], ['shin.R', 'foot.R'], ['foot.R', 'toeTip.R'],+];-/** Most recently used last, as building takes seconds and the same body is drawn again on every edit. */-const cache = new Map<string, unknown>();-function remembered<T>(key: string, make: () => T): T {- if (cache.has(key)) {- const value = cache.get(key) as T;- cache.delete(key);- cache.set(key, value);- return value;- }- const value = make();- cache.set(key, value);- if (cache.size > KEPT) cache.delete(cache.keys().next().value as string);- return value;-}+interface Ring { at: V3; across: V3; deep: V3; a: number; d: number }+interface Volume { tag: (typeof FIGURE_TAGS)[number]; rings: Ring[] }-interface PosedBody { positions: readonly Vec3[]; normals: Float32Array; triangles: Uint32Array; tags: Uint8Array }+const plus = (p: V3, v: V3, k: number): V3 => [p[0] + v[0] * k, p[1] + v[1] * k, p[2] + v[2] * k];+const between = (a: V3, b: V3, t: number): V3 => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];+const unit = (v: V3): V3 => {+ const len = Math.hypot(v[0], v[1], v[2]) || 1;+ return [v[0] / len, v[1] / len, v[2] / len];+};+const crossed = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];-function bodyOf(build: HumanoidBuild, eyes: 'open' | 'closed' | undefined, pose: PoseParams): PosedBody {- const buildKey = JSON.stringify({ build, eyes });- return remembered(`posed:${buildKey}:${JSON.stringify(pose)}`, () => {- const rest = remembered(`rest:${buildKey}`, () => humanoid({ positions: [], faces: [] } as PolyMesh, { ...build, height: BODY_HEIGHT, resolution: BODY_RESOLUTION, ...(eyes ? { eyes } : {}) }));- const mesh = poseStep(rest, pose);- let count = 0;- for (const f of mesh.faces) count += f.v.length - 2;- const triangles = new Uint32Array(count * 3);- const tags = new Uint8Array(count);- const normals = new Float32Array(mesh.positions.length * 3);- let t = 0;- for (const f of mesh.faces) {- const tag = Math.max(0, FIGURE_TAGS.indexOf(f.tag as (typeof FIGURE_TAGS)[number]));- for (let i = 1; i + 1 < f.v.length; i++, t++) {- const [a, b, c] = [f.v[0]!, f.v[i]!, f.v[i + 1]!];- triangles[t * 3] = a; triangles[t * 3 + 1] = b; triangles[t * 3 + 2] = c;- tags[t] = tag;- const [pa, pb, pc] = [mesh.positions[a]!, mesh.positions[b]!, mesh.positions[c]!];- const [ux, uy, uz, vx, vy, vz] = [pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2], pc[0] - pa[0], pc[1] - pa[1], pc[2] - pa[2]];- const [nx, ny, nz] = [uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx];- for (const v of [a, b, c]) { normals[v * 3]! += nx; normals[v * 3 + 1]! += ny; normals[v * 3 + 2]! += nz; }- }- }- for (let v = 0; v < mesh.positions.length; v++) {- const len = Math.hypot(normals[v * 3]!, normals[v * 3 + 1]!, normals[v * 3 + 2]!) || 1;- normals[v * 3]! /= len; normals[v * 3 + 1]! /= len; normals[v * 3 + 2]! /= len;+/** The blocks a figure drawing starts from, widths on a body 1.6 tall. */+function volumesOf(frames: ReturnType<typeof poseFrames>, build: HumanoidBuild): Volume[] {+ const f = (name: string) => frames[name]!;+ const [hips, spine, chest, neck, head] = [f('hips'), f('spine'), f('chest'), f('neck'), f('head')];+ const [wHips, wWaist, wChest, wShoulders, wLimbs, wHead] = [build.hips ?? 1, build.waist ?? 1, build.chest ?? 1, build.shoulders ?? 1, build.limbs ?? 1, build.head ?? 1];+ const volumes: Volume[] = [{+ tag: 'torso',+ rings: [+ { at: plus(hips.at, hips.y, -0.1), across: hips.x, deep: hips.z, a: 0.09 * wHips, d: 0.06 },+ { at: plus(hips.at, hips.y, -0.02), across: hips.x, deep: hips.z, a: 0.135 * wHips, d: 0.085 },+ { at: between(hips.at, spine.at, 0.6), across: spine.x, deep: spine.z, a: 0.112 * wWaist, d: 0.07 },+ { at: spine.at, across: spine.x, deep: spine.z, a: 0.1 * wWaist, d: 0.064 },+ { at: chest.at, across: chest.x, deep: chest.z, a: 0.128 * wChest, d: 0.09 },+ { at: between(chest.at, neck.at, 0.62), across: chest.x, deep: chest.z, a: 0.15 * wShoulders, d: 0.078 },+ { at: between(chest.at, neck.at, 0.92), across: chest.x, deep: chest.z, a: 0.075, d: 0.06 },+ ],+ }];+ const round = (at: V3, axis: V3, r: number): Ring => {+ const side = unit(crossed(axis, Math.abs(axis[1]) > 0.9 ? [1, 0, 0] : [0, 1, 0]));+ return { at, across: side, deep: unit(crossed(axis, side)), a: r * wLimbs, d: r * wLimbs };+ };+ const limb = (tag: Volume['tag'], names: readonly string[], radii: readonly number[]): void => {+ const points = names.map((n) => f(n).at);+ const rings: Ring[] = [];+ for (let i = 0; i < points.length; i++) {+ const axis = unit(i + 1 < points.length ? [points[i + 1]![0] - points[i]![0], points[i + 1]![1] - points[i]![1], points[i + 1]![2] - points[i]![2]] : [points[i]![0] - points[i - 1]![0], points[i]![1] - points[i - 1]![1], points[i]![2] - points[i - 1]![2]]);+ if (i === 0) rings.push(round(plus(points[0]!, axis, -radii[0]! * 0.8), axis, radii[0]! * 0.55));+ rings.push(round(points[i]!, axis, radii[i]!));+ if (i === points.length - 1) rings.push(round(plus(points[i]!, axis, radii[i]! * 0.8), axis, radii[i]! * 0.55));}- return { positions: mesh.positions, normals, triangles, tags };- });+ volumes.push({ tag, rings });+ };+ for (const side of ['L', 'R']) {+ limb('arm', [`upperArm.${side}`, `forearm.${side}`, `hand.${side}`], [0.038, 0.029, 0.021]);+ limb('leg', [`thigh.${side}`, `shin.${side}`, `foot.${side}`], [0.072, 0.046, 0.03]);+ // A mitten and a wedge: where a hand and a foot go, and no fingers to copy.+ const [hand, tip] = [f(`hand.${side}`), f(`middle4.${side}`)];+ volumes.push({ tag: 'hand', rings: [+ { at: hand.at, across: hand.z, deep: hand.y, a: 0.026, d: 0.016 },+ { at: between(hand.at, tip.at, 0.45), across: hand.z, deep: hand.y, a: 0.04, d: 0.017 },+ { at: tip.at, across: hand.z, deep: hand.y, a: 0.022, d: 0.01 },+ ] });+ const [foot, toe] = [f(`foot.${side}`), f(`toeTip.${side}`)];+ const along = unit([toe.at[0] - foot.at[0], toe.at[1] - foot.at[1], toe.at[2] - foot.at[2]]);+ const flat = unit(crossed(along, [1, 0, 0]));+ volumes.push({ tag: 'foot', rings: [+ { at: plus(foot.at, along, -0.05), across: [1, 0, 0], deep: flat, a: 0.022, d: 0.026 },+ { at: foot.at, across: [1, 0, 0], deep: flat, a: 0.034, d: 0.04 },+ { at: between(foot.at, toe.at, 0.7), across: [1, 0, 0], deep: flat, a: 0.04, d: 0.022 },+ { at: toe.at, across: [1, 0, 0], deep: flat, a: 0.022, d: 0.01 },+ ] });+ }+ limb('neck', ['neck', 'head'], [0.042, 0.038]);+ // An egg, turned as the head is turned.+ const centre = between(head.at, f('crown').at, 0.46);+ const rings: Ring[] = [];+ for (let i = 0; i <= 8; i++) {+ const t = (i / 8) * 2 - 1, r = Math.sqrt(Math.max(0.0001, 1 - t * t));+ rings.push({ at: plus(plus(centre, head.y, t * 0.108 * wHead), head.z, 0.006), across: head.x, deep: head.z, a: 0.074 * wHead * r, d: 0.09 * wHead * r });+ }+ volumes.push({ tag: 'head', rings });+ return volumes;}export interface FlatFigure {- /** Coverage of the whole body in picture pixels, then of each kind of part as it shows. */+ /** Coverage of the whole body in picture pixels, then of each kind of block as it shows. */mask: Float32Array;parts: Record<string, Float32Array>;/** Which way the surface faces at each pixel, x right, y up, z toward the viewer; zero off the body. */normals: Float32Array;- /** Dark where one surface passes in front of another, for seeing the form through a guide. */+ /** Dark where one block passes in front of another. */contour: Float32Array;+ /** In the picture: where each joint landed, and the bones and the head's cross as lines. */joints: Record<string, readonly [number, number]>;+ lines: readonly (readonly (readonly [number, number])[])[];light: readonly [number, number, number];}@@ -106,74 +141,104 @@ export function flattenFigure(layer: ImageLayer, w: number, h: number, project:const [y, z] = [v[1]! * cp + v[2]! * sp, -v[1]! * sp + v[2]! * cp];return [v[0]! * cy - z * sy, y, v[0]! * sy + z * cy];};+ const toPicture = (p: readonly number[]): [number, number] => {+ const v = toView(p);+ return [ax + v[0] * s, ay - v[1] * s];+ };const build = (layer.build ?? {}) as HumanoidBuild;const pose = layer.pose ?? {};const held = { humanoid: build, ...(pose.rotate ? { rotate: pose.rotate } : {}), ...(pose.move ? { move: pose.move } : {}) } as PoseParams;// A reach given by two numbers is a place in the picture: where along the line of sight is where the joint already is.- const reach = Object.entries(pose.reach ?? {}).map(([name, r]) => [name, r] as const);+ const reach = Object.entries(pose.reach ?? {});let resolved: PoseParams = held;if (reach.length) {const before = poseJoints(held);- const entries = reach.map(([name, r]) => {- if (!before[name]) throw new Error(`no joint "${name}"; there are ${Object.keys(before).join(', ')}`);- const at = r.at.length === 3 ? r.at : fromView([(r.at[0]! - ax) / s, (ay - r.at[1]!) / s, toView(before[name]!)[2]]);- return [name, { at, ...(r.pole ? { pole: r.pole } : {}) }] as const;- });- resolved = { ...held, reach: Object.fromEntries(entries) };+ resolved = {+ ...held,+ reach: Object.fromEntries(reach.map(([name, r]) => {+ if (!before[name]) throw new Error(`no joint "${name}"; there are ${Object.keys(before).join(', ')}`);+ const at = r.at.length === 3 ? r.at : fromView([(r.at[0]! - ax) / s, (ay - r.at[1]!) / s, toView(before[name]!)[2]]);+ return [name, { at, ...(r.pole ? { pole: r.pole } : {}) }];+ })),+ };}- const body = bodyOf(build, layer.eyes, resolved);- const placed = poseJoints(resolved);+ const frames = poseFrames(resolved);const joints: Record<string, readonly [number, number]> = {};for (const name of FIGURE_JOINTS) {- const v = toView(placed[name]!);- joints[name] = [Math.round(ax + v[0] * s), Math.round(ay - v[1] * s)];+ const p = toPicture(frames[name]!.at);+ joints[name] = [Math.round(p[0]), Math.round(p[1])];}const [W, H] = [w * SUPERSAMPLE, h * SUPERSAMPLE];const depth = new Float32Array(W * H).fill(-Infinity);const tagAt = new Int8Array(W * H).fill(-1);const nAt = new Float32Array(W * H * 3);- const count = body.positions.length;- const [sxs, sys, szs] = [new Float32Array(count), new Float32Array(count), new Float32Array(count)];- for (let i = 0; i < count; i++) {- const v = toView(body.positions[i]!);- sxs[i] = (ax + v[0] * s) * SUPERSAMPLE; sys[i] = (ay - v[1] * s) * SUPERSAMPLE; szs[i] = v[2];- }- const viewNormals = new Float32Array(count * 3);- for (let i = 0; i < count; i++) {- const v = toView([body.normals[i * 3]!, body.normals[i * 3 + 1]!, body.normals[i * 3 + 2]!]);- viewNormals[i * 3] = v[0]; viewNormals[i * 3 + 1] = v[1]; viewNormals[i * 3 + 2] = v[2];- }- for (let t = 0; t < body.tags.length; t++) {- const [a, b, c] = [body.triangles[t * 3]!, body.triangles[t * 3 + 1]!, body.triangles[t * 3 + 2]!];- const [x0, y0, x1, y1, x2, y2] = [sxs[a]!, sys[a]!, sxs[b]!, sys[b]!, sxs[c]!, sys[c]!];- const area = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0);- if (area === 0) continue;- const [left, right] = [Math.max(0, Math.floor(Math.min(x0, x1, x2))), Math.min(W - 1, Math.ceil(Math.max(x0, x1, x2)))];- const [top, bottom] = [Math.max(0, Math.floor(Math.min(y0, y1, y2))), Math.min(H - 1, Math.ceil(Math.max(y0, y1, y2)))];- for (let y = top; y <= bottom; y++) {- for (let x = left; x <= right; x++) {- const [px, py] = [x + 0.5, y + 0.5];- const w1 = ((px - x0) * (y2 - y0) - (x2 - x0) * (py - y0)) / area;- const w2 = ((x1 - x0) * (py - y0) - (px - x0) * (y1 - y0)) / area;- const w0 = 1 - w1 - w2;- if (w0 < 0 || w1 < 0 || w2 < 0) continue;- const z = w0 * szs[a]! + w1 * szs[b]! + w2 * szs[c]!;- const i = y * W + x;- if (z <= depth[i]!) continue;- depth[i] = z;- tagAt[i] = body.tags[t]!;- for (let k = 0; k < 3; k++) nAt[i * 3 + k] = w0 * viewNormals[a * 3 + k]! + w1 * viewNormals[b * 3 + k]! + w2 * viewNormals[c * 3 + k]!;+ for (const volume of volumesOf(frames, build)) {+ const tag = FIGURE_TAGS.indexOf(volume.tag);+ const points: V3[] = [];+ for (const r of volume.rings) {+ for (let i = 0; i < AROUND; i++) {+ const t = (i / AROUND) * Math.PI * 2;+ points.push(plus(plus(r.at, r.across, Math.cos(t) * r.a), r.deep, Math.sin(t) * r.d));+ }+ }+ const quads: [number, number, number, number][] = [];+ for (let k = 0; k + 1 < volume.rings.length; k++) {+ for (let i = 0; i < AROUND; i++) {+ const [a, b] = [k * AROUND + i, k * AROUND + (i + 1) % AROUND];+ quads.push([a, b, b + AROUND, a + AROUND]);}}+ // Smooth across the block, whichever way the rings wind.+ const middle = volume.rings.reduce<V3>((m, r) => plus(m, r.at, 1 / volume.rings.length), [0, 0, 0]);+ const normals = points.map(() => [0, 0, 0] as [number, number, number]);+ for (const [a, b, c, d] of quads) {+ const [pa, pb, pc] = [points[a]!, points[b]!, points[c]!];+ let n = crossed([pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]], [pc[0] - pa[0], pc[1] - pa[1], pc[2] - pa[2]]);+ const out: V3 = [pa[0] - middle[0], pa[1] - middle[1], pa[2] - middle[2]];+ if (n[0] * out[0] + n[1] * out[1] + n[2] * out[2] < 0) n = [-n[0], -n[1], -n[2]];+ for (const v of [a, b, c, d]) { normals[v]![0] += n[0]; normals[v]![1] += n[1]; normals[v]![2] += n[2]; }+ }+ const picture = points.map((p) => {+ const v = toView(p);+ return [(ax + v[0] * s) * SUPERSAMPLE, (ay - v[1] * s) * SUPERSAMPLE, v[2]] as const;+ });+ const facing = normals.map((n) => toView(unit(n)));+ const triangle = (a: number, b: number, c: number): void => {+ const [p0, p1, p2] = [picture[a]!, picture[b]!, picture[c]!];+ const area = (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (p1[1] - p0[1]);+ if (area === 0) return;+ const [left, right] = [Math.max(0, Math.floor(Math.min(p0[0], p1[0], p2[0]))), Math.min(W - 1, Math.ceil(Math.max(p0[0], p1[0], p2[0])))];+ const [top, bottom] = [Math.max(0, Math.floor(Math.min(p0[1], p1[1], p2[1]))), Math.min(H - 1, Math.ceil(Math.max(p0[1], p1[1], p2[1])))];+ for (let y = top; y <= bottom; y++) {+ for (let x = left; x <= right; x++) {+ const [px, py] = [x + 0.5, y + 0.5];+ const w1 = ((px - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (py - p0[1])) / area;+ const w2 = ((p1[0] - p0[0]) * (py - p0[1]) - (px - p0[0]) * (p1[1] - p0[1])) / area;+ const w0 = 1 - w1 - w2;+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;+ const z = w0 * p0[2] + w1 * p1[2] + w2 * p2[2];+ const i = y * W + x;+ if (z <= depth[i]!) continue;+ depth[i] = z;+ tagAt[i] = tag;+ for (let k = 0; k < 3; k++) nAt[i * 3 + k] = w0 * facing[a]![k]! + w1 * facing[b]![k]! + w2 * facing[c]![k]!;+ }+ }+ };+ for (const [a, b, c, d] of quads) { triangle(a, b, c); triangle(a, c, d); }+ // Ends closed flat: they are hidden in the block they meet, or small enough not to matter.+ for (const k of [0, volume.rings.length - 1]) {+ for (let i = 1; i + 1 < AROUND; i++) triangle(k * AROUND, k * AROUND + i, k * AROUND + i + 1);+ }}const mask = new Float32Array(w * h);const normals = new Float32Array(w * h * 3);const contour = new Float32Array(w * h);const parts: Record<string, Float32Array> = Object.fromEntries(FIGURE_TAGS.map((tag) => [tag, new Float32Array(w * h)]));const share = 1 / (SUPERSAMPLE * SUPERSAMPLE);- // How far one surface must stand in front of the next, in body units, to count as an edge of the form.- const step = 0.012;+ // How far one block must stand in front of the next, in body units, to count as an edge.+ const step = 0.02;for (let y = 0; y < H; y++) {for (let x = 0; x < W; x++) {const i = y * W + x, o = (y >> 1) * w + (x >> 1);@@ -193,7 +258,18 @@ export function flattenFigure(layer: ImageLayer, w: number, h: number, project:const len = Math.hypot(normals[o * 3]!, normals[o * 3 + 1]!, normals[o * 3 + 2]!);if (len > 0) for (let k = 0; k < 3; k++) normals[o * 3 + k]! /= len;}- return { mask, parts, normals, contour, joints, light: normalized(layer.light ?? [-0.5, 0.6, 0.6]) };++ // The head's cross on the side it faces: its middle line, and the line the eyes sit on.+ const head = frames.head!, crown = frames.crown!;+ const centre = between(head.at, crown.at, 0.46);+ const wHead = build.head ?? 1;+ const cross = (at: (t: number) => V3): (readonly [number, number])[] => Array.from({ length: 13 }, (_, i) => toPicture(at((i / 12) * Math.PI - Math.PI / 2)));+ const lines = [+ ...BONES.map(([a, b]) => [toPicture(frames[a]!.at), toPicture(frames[b]!.at)]),+ cross((t) => plus(plus(centre, head.y, Math.sin(t) * 0.108 * wHead), head.z, Math.cos(t) * 0.09 * wHead + 0.006)),+ cross((t) => plus(plus(plus(centre, head.y, -0.018 * wHead), head.x, Math.sin(t) * 0.074 * wHead), head.z, Math.cos(t) * 0.088 * wHead + 0.006)),+ ];+ return { mask, parts, normals, contour, joints, lines, light: normalized(layer.light ?? [-0.5, 0.6, 0.6]) };}export const figureLight = normalized;diff --git a/pipeline/src/image/imageRaster.ts b/pipeline/src/image/imageRaster.tsindex ddf2b2635..7bfd8c233 100644--- a/pipeline/src/image/imageRaster.ts+++ b/pipeline/src/image/imageRaster.ts@@ -465,7 +465,7 @@ function paintOf(fill: ImageFill, m: Matrix, drawn?: Drawn, w = 0): (x: number,const c = parseColor(fill);return () => c;}- const stops = [...fill.stops].map(([t, c]) => [t, parseColor(c)] as const).sort((a, b) => a[0] - b[0]);+ const stops = [...(fill.type === 'image' ? [] : fill.stops)].map(([t, c]) => [t, parseColor(c)] as const).sort((a, b) => a[0] - b[0]);const inverse = invert(m);const at = (t: number): Rgba => {if (t <= stops[0]![0]) return stops[0]![1];@@ -478,6 +478,17 @@ function paintOf(fill: ImageFill, m: Matrix, drawn?: Drawn, w = 0): (x: number,}return stops[stops.length - 1]![1];};+ if (fill.type === 'image') {+ const image = drawn?.images.get(fill.image);+ if (!image) {+ drawn?.notes.push(`a fill names image "${fill.image}", which was not drawn before it`);+ return () => [0, 0, 0, 0];+ }+ return (x, y) => {+ const i = (Math.floor(y) * w + Math.floor(x)) * 4;+ return [image[i] ?? 0, image[i + 1] ?? 0, image[i + 2] ?? 0, image[i + 3] ?? 0];+ };+ }if (fill.type === 'form') {const figure = drawn?.figures.get(fill.figure);if (!figure) {@@ -571,7 +582,7 @@ function effectLayers(effects: readonly ImageEffect[] | undefined, under: boolea}}-interface Drawn { masks: Map<string, Float32Array>; notes: string[]; bounds: Map<string, ImageBox>; painted: Map<string, { entries: number; strokes: number }>; figures: Map<string, FlatFigure>; figureJoints: Map<string, Record<string, readonly [number, number]>>; showGuides: boolean }+interface Drawn { masks: Map<string, Float32Array>; notes: string[]; bounds: Map<string, ImageBox>; painted: Map<string, { entries: number; strokes: number }>; figures: Map<string, FlatFigure>; figureJoints: Map<string, Record<string, readonly [number, number]>>; showGuides: boolean; pictures: Readonly<Record<string, RgbaBitmap>>; images: Map<string, Float32Array> }/** x, y, width and height in the picture's pixels. */export type ImageBox = readonly [number, number, number, number];@@ -601,7 +612,7 @@ function drawLayer(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn):if (layer.visible === false) return;const { w, h } = c;// What a guide masks is still wanted when it is not seen, so it draws somewhere that is thrown away.- if (!drawn.showGuides && (layer.guide ?? layer.shape === 'figure')) {+ if (!drawn.showGuides && (layer.guide ?? (layer.shape === 'figure' || layer.shape === 'image'))) {drawLayer(new Canvas(w, h), { ...layer, guide: false }, parent, drawn);return;}@@ -616,11 +627,21 @@ function drawLayer(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn):}const opacity = layer.opacity ?? 1;const blend: Blend = layer.blend ?? 'normal';- const clip = layer.clip ? drawn.masks.get(layer.clip) : undefined;- if (layer.clip && !clip) drawn.notes.push(`layer ${layer.id ?? layer.shape}: clip "${layer.clip}" names no layer drawn before it`);+ const named = (id: string): Float32Array | undefined => drawn.masks.get(id.replace(/^@/, ''));+ let clip = layer.clip ? named(layer.clip) : undefined;+ // Nothing, and not everything: a clip that failed would otherwise cover the picture in what it was meant to hold in.+ if (layer.clip && !clip) {+ drawn.notes.push(`layer ${layer.id ?? layer.shape}: clip "${layer.clip}" names no layer drawn before it, so it drew nothing`);+ return;+ }+ if (layer.except) {+ const out = named(layer.except);+ if (!out) drawn.notes.push(`layer ${layer.id ?? layer.shape}: except "${layer.except}" names no layer drawn before it`);+ else clip = out.map((v, i) => (1 - v) * (clip ? clip[i]! : 1));+ }if (layer.blur) {- const { blur, opacity: _o, blend: _b, clip: _c, ...sharp } = layer;+ const { blur, opacity: _o, blend: _b, clip: _c, except: _e, ...sharp } = layer;const inner = new Canvas(w, h);drawLayer(inner, sharp, parent, drawn);// Blurred as stored, colour already times alpha: blurring straight colour would bring the black of empty pixels in round the edge.@@ -672,6 +693,11 @@ function drawLayer(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn):return;}+ if (layer.shape === 'image') {+ drawPicture(c, layer, parent, drawn, opacity, blend, clip);+ return;+ }+const { runs, middle } = outlinesOf(layer);const m = times(parent, transformOf(layer.transform, middle));const placed = runs.map((run) => ({ closed: run.closed, points: run.points.map((p) => apply(m, p)) }));@@ -1024,7 +1050,7 @@ function fieldStrokes(s: ImageField, w: number, h: number, m: Matrix, drawn: Draconst len = Math.hypot(dx, dy) || 1;return [dx / len, dy / len];};- const toned = s.tone !== undefined && typeof s.tone !== 'string' && s.tone.type === 'form' ? paintOf(s.tone, IDENTITY, drawn, w) : null;+ const toned = s.tone !== undefined && typeof s.tone !== 'string' && (s.tone.type === 'form' || s.tone.type === 'image') ? paintOf(s.tone, IDENTITY, drawn, w) : null;const paint = toned ? (x: number, y: number): Rgba => { const p = apply(m, [x, y]); return toned(p[0], p[1]); } : s.tone !== undefined ? paintOf(s.tone, IDENTITY) : null;const length = s.length ?? s.size * 3;const count = Math.min(MAX_MARK_STROKES, Math.ceil(((s.coverage ?? 4) * Math.max(1, (x1 - x0) * (y1 - y0))) / (s.size * length)));@@ -1155,12 +1181,22 @@ function drawPaint(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn, oeffectLayers(layer.effects, false, c, alpha);}-/** The body in clay, with the edges of its form and a mark on each joint: enough to draw over, and nothing to be mistaken for the drawing. */+/** The blocks in plain grey, with the bones and a mark on each joint: enough to draw over, and nothing to be mistaken for the drawing. */function drawFigure(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn, opacity: number, blend: Blend, clip: Float32Array | undefined): void {const { w, h } = c;const figure = flattenFigure(layer, w, h, (p) => apply(parent, p), drawnScale(parent));+ // Past the blocks a little way, so cloth that hangs off them is lit as what it hangs from.+ const reach = Math.max(2, (layer.height as number) * 0.03);+ const spread = blurMask(figure.mask, w, h, reach);+ const extended = new Float32Array(figure.normals);+ for (let k = 0; k < 3; k++) {+ const channel = new Float32Array(w * h);+ for (let i = 0; i < channel.length; i++) channel[i] = figure.normals[i * 3 + k]! * figure.mask[i]!;+ const soft = blurMask(channel, w, h, reach);+ for (let i = 0; i < channel.length; i++) if (figure.mask[i]! < 0.5 && spread[i]! > 0.01) extended[i * 3 + k] = soft[i]! / spread[i]!;+ }if (layer.id) {- drawn.figures.set(layer.id, figure);+ drawn.figures.set(layer.id, { ...figure, normals: extended });drawn.masks.set(layer.id, figure.mask);noteBox(drawn, layer.id, figure.mask, w, h);for (const [tag, mask] of Object.entries(figure.parts)) {@@ -1174,8 +1210,10 @@ function drawFigure(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn,if (a <= 0) continue;const lit = 0.25 + 0.7 * Math.max(0, 0.5 + 0.5 * (figure.normals[i * 3]! * lx + figure.normals[i * 3 + 1]! * ly + figure.normals[i * 3 + 2]! * lz));const line = 1 - figure.contour[i]! * 0.85;- put(c, i, lit * line, lit * line * 0.96, lit * line * 0.92, a * (layer.opacity ?? opacity) * (clip ? clip[i]! : 1), blend);+ put(c, i, lit * line * 0.92, lit * line * 0.94, lit * line, a * (layer.opacity ?? opacity) * (clip ? clip[i]! : 1), blend);}+ const bones = strokeMask(figure.lines.map((points) => ({ closed: false, points })), 1.5, w, h);+ for (let i = 0; i < bones.length; i++) put(c, i, 0.95, 0.35, 0.3, bones[i]! * 0.8, 'normal');for (const [x, y] of Object.values(figure.joints)) {for (let dy = -2; dy <= 2; dy++) {for (let dx = -2; dx <= 2; dx++) {@@ -1187,6 +1225,41 @@ function drawFigure(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn,if (layer.id) drawn.figureJoints.set(layer.id, figure.joints);}+/** A picture from the project, smoothly scaled to where it goes. */+function drawPicture(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn, opacity: number, blend: Blend, clip: Float32Array | undefined): void {+ const { w, h } = c;+ const picture = drawn.pictures[layer.src!];+ if (!picture) throw new Error(`there is no picture at ${layer.src}`);+ const [ox, oy] = apply(parent, layer.at ?? [0, 0]);+ const k = drawnScale(parent);+ const [dw, dh] = (layer.size ?? [picture.width, picture.height]).map((v) => v * k) as [number, number];+ const out = new Float32Array(w * h * 4);+ const mask = new Float32Array(w * h);+ for (let y = Math.max(0, Math.floor(oy)); y < Math.min(h, Math.ceil(oy + dh)); y++) {+ for (let x = Math.max(0, Math.floor(ox)); x < Math.min(w, Math.ceil(ox + dw)); x++) {+ const [u, v] = [((x + 0.5 - ox) / dw) * picture.width - 0.5, ((y + 0.5 - oy) / dh) * picture.height - 0.5];+ if (u < -0.5 || v < -0.5 || u > picture.width - 0.5 || v > picture.height - 0.5) continue;+ const [x0, y0] = [Math.max(0, Math.floor(u)), Math.max(0, Math.floor(v))];+ const [x1, y1] = [Math.min(picture.width - 1, x0 + 1), Math.min(picture.height - 1, y0 + 1)];+ const [fx, fy] = [Math.max(0, u - x0), Math.max(0, v - y0)];+ const i = y * w + x;+ for (let n = 0; n < 4; n++) {+ const at = (px: number, py: number): number => picture.rgba[(py * picture.width + px) * 4 + n]! / 255;+ out[i * 4 + n] = (at(x0, y0) * (1 - fx) + at(x1, y0) * fx) * (1 - fy) + (at(x0, y1) * (1 - fx) + at(x1, y1) * fx) * fy;+ }+ mask[i] = out[i * 4 + 3]!;+ }+ }+ if (layer.id) {+ drawn.images.set(layer.id, out);+ drawn.masks.set(layer.id, mask);+ noteBox(drawn, layer.id, mask, w, h);+ }+ for (let i = 0; i < mask.length; i++) {+ if (mask[i]! > 0) put(c, i, out[i * 4]!, out[i * 4 + 1]!, out[i * 4 + 2]!, mask[i]! * opacity * (clip ? clip[i]! : 1), blend);+ }+}+function drawPixels(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn, opacity: number, blend: Blend, clip: Float32Array | undefined): void {const { w, h } = c;const rows = layer.rows!;@@ -1229,14 +1302,14 @@ export interface RenderedImage extends RgbaBitmap {}/** Draws a source that has been validated. */-export function renderImage(source: ImageSource, options: { guides?: boolean } = {}): RenderedImage {+export function renderImage(source: ImageSource, options: { guides?: boolean; pictures?: Readonly<Record<string, RgbaBitmap>> } = {}): RenderedImage {const [w, h] = typeof source.size === 'number' ? [source.size, source.size] : source.size;const canvas = new Canvas(w, h);if (source.background) {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: [], bounds: new Map(), painted: new Map(), figures: new Map(), figureJoints: new Map(), showGuides: options.guides === true };+ const drawn: Drawn = { masks: new Map(), notes: [], bounds: new Map(), painted: new Map(), figures: new Map(), figureJoints: new Map(), showGuides: options.guides === true, pictures: options.pictures ?? {}, images: 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++) {diff --git a/pipeline/src/image/imageSource.ts b/pipeline/src/image/imageSource.tsindex bdf6e3f7d..b0b1ac46a 100644--- a/pipeline/src/image/imageSource.ts+++ b/pipeline/src/image/imageSource.ts@@ -15,7 +15,9 @@ export type ImageFill = string/** The same picture on every machine: it comes from `seed` and never from a random number. */| { type: 'noise'; scale?: number; octaves?: number; seed?: number; stops: readonly (readonly [number, string])[] }/** By which way a figure's surface faces: 1 toward the light, 0.5 side on, 0 away. So light turns the form and does not sit on its edge. */- | { type: 'form'; figure: string; light?: readonly number[]; stops: readonly (readonly [number, string])[] };+ | { type: 'form'; figure: string; light?: readonly number[]; stops: readonly (readonly [number, string])[] }+ /** The colour of an `image` layer at each place. */+ | { type: 'image'; image: string };export interface ImageEffect {type: 'shadow' | 'glow' | 'innerShadow' | 'innerGlow';@@ -35,7 +37,7 @@ export interface ImageTransform {origin?: readonly [number, number];}-export type ImageShape = 'rect' | 'circle' | 'ellipse' | 'ring' | 'polygon' | 'line' | 'star' | 'gear' | 'path' | 'pixels' | 'paint' | 'figure' | 'group';+export type ImageShape = 'rect' | 'circle' | 'ellipse' | 'ring' | 'polygon' | 'line' | 'star' | 'gear' | 'path' | 'pixels' | 'paint' | 'figure' | 'image' | 'group';/** One movement of a brush. Replayed in order on a `paint` layer, so the same list is the same picture. */export interface ImageStroke {@@ -169,7 +171,10 @@ export interface ImageLayer {/** A joint and where it must be: [x, y] in the picture, or [x, y, z] on the body's own axes. */reach?: Readonly<Record<string, { at: readonly number[]; pole?: readonly number[] }>>;};- eyes?: 'open' | 'closed';+ /** An image: a picture in the project. */+ src?: string;+ /** Drawn everywhere but inside this earlier layer. */+ except?: string;/** A figure: where the light is, x right, y up, z toward the viewer. */light?: readonly number[];fill?: ImageFill;@@ -201,7 +206,8 @@ function checkFill(v: unknown): string | null {if (typeof v === 'string') return isColor(v) ? null : `${JSON.stringify(v)} must be #rgb, #rgba, #rrggbb or #rrggbbaa`;const f = v as Record<string, unknown> | null;if (typeof f !== 'object' || f === null) return 'must be a colour or a gradient';- if (f.type !== 'linear' && f.type !== 'radial' && f.type !== 'noise' && f.type !== 'form') return 'a gradient has type linear, radial, noise or form';+ if (f.type !== 'linear' && f.type !== 'radial' && f.type !== 'noise' && f.type !== 'form' && f.type !== 'image') return 'a gradient has type linear, radial, noise, form or image';+ if (f.type === 'image') return typeof f.image === 'string' && f.image ? null : 'an image fill needs image, the id of an image layer drawn before it';if (f.type === 'form') {if (typeof f.figure !== 'string' || !f.figure) return 'a form needs figure, the id of a figure drawn before it';if (f.light !== undefined && !(Array.isArray(f.light) && f.light.length === 3 && f.light.every(isNum))) return 'a form\'s light must be [x, y, z], x right, y up, z toward the viewer';@@ -221,8 +227,8 @@ function checkFill(v: unknown): string | null {return null;}-const FIELDS = ['id', 'shape', 'at', 'size', 'radius', 'radii', 'inner', 'count', 'tooth', 'turn', 'points', 'd', 'rows', 'palette', 'scale', 'layers', 'fill', 'stroke', 'opacity', 'blend', 'transform', 'mirror', 'effects', 'clip', 'erase', 'visible', 'blur', 'strokes', 'from', 'guide', 'height', 'yaw', 'pitch', 'build', 'pose', 'eyes', 'light'];-const SHAPES: readonly ImageShape[] = ['rect', 'circle', 'ellipse', 'ring', 'polygon', 'line', 'star', 'gear', 'path', 'pixels', 'paint', 'figure', 'group'];+const FIELDS = ['id', 'shape', 'at', 'size', 'radius', 'radii', 'inner', 'count', 'tooth', 'turn', 'points', 'd', 'rows', 'palette', 'scale', 'layers', 'fill', 'stroke', 'opacity', 'blend', 'transform', 'mirror', 'effects', 'clip', 'erase', 'visible', 'blur', 'strokes', 'from', 'guide', 'height', 'yaw', 'pitch', 'build', 'pose', 'light', 'src', 'except'];+const SHAPES: readonly ImageShape[] = ['rect', 'circle', 'ellipse', 'ring', 'polygon', 'line', 'star', 'gear', 'path', 'pixels', 'paint', 'figure', 'image', 'group'];const STROKE_FIELDS = ['points', 'color', 'to', 'size', 'hardness', 'opacity', 'taper', 'bristles', 'strand', 'spread', 'vary', 'wobble', 'seed', 'smudge', 'erase', 'blend'];const SWEEP_FIELDS = ['type', 'guides', 'colors', 'count', 'tip', 'size', 'clumps', 'gather', 'flyaway', 'vary', 'wobble', 'opacity', 'taper', 'seed'];@@ -339,7 +345,6 @@ function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>)if (!isPair(l.at)) fail('at must be [x, y]: the place on the floor under her');if (!(isNum(l.height) && (l.height as number) > 0)) fail('height must be pixels from floor to crown');for (const key of ['yaw', 'pitch']) if (l[key] !== undefined && !isNum(l[key])) fail(`${key} must be degrees`);- if (l.eyes !== undefined && l.eyes !== 'open' && l.eyes !== 'closed') fail('eyes must be open or closed');if (l.light !== undefined && !(Array.isArray(l.light) && l.light.length === 3 && l.light.every(isNum))) fail('light must be [x, y, z], x right, y up, z toward the viewer');const build = l.build as Record<string, unknown> | undefined;for (const [key, value] of Object.entries(build ?? {})) {@@ -357,6 +362,11 @@ function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>)}break;}+ case 'image':+ if (typeof l.src !== 'string' || !l.src) fail('src must be the path of a picture in the project');+ if (l.at !== undefined && !isPair(l.at)) fail('at must be [x, y]');+ if (l.size !== undefined && !isPair(l.size)) fail('size must be [w, h]');+ break;case 'paint': {if (!Array.isArray(l.strokes)) fail('strokes must be an array, which may start empty');if (l.from !== undefined && l.from !== 'below') fail('from must be "below"');@@ -401,7 +411,7 @@ function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>)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', 'paint', 'figure', '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 (!['group', 'pixels', 'paint', 'figure', 'image', '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.from !== undefined && l.shape !== 'paint') fail('from is for a paint layer');if (l.guide !== undefined && typeof l.guide !== 'boolean') fail('guide must be true or false');if (l.blur !== undefined && !(isNum(l.blur) && (l.blur as number) >= 0)) fail('blur must be 0 or more, in pixels');@@ -449,7 +459,7 @@ export type ImageEdit =| { 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: 'paint'; layer: string; strokes?: readonly ImageMark[]; drop?: number }+ | { op: 'paint'; layer: string; strokes?: readonly ImageMark[]; drop?: number; at?: number; remove?: number }| { op: 'wrap'; layers: readonly string[]; group: Partial<ImageLayer> }| { op: 'unwrap'; layer: string }| {@@ -558,7 +568,12 @@ export function applyImageEdits(source: ImageSource, edits: readonly ImageEdit[]const had = layer.strokes as readonly ImageMark[];const drop = edit.drop ?? 0;if (!Number.isInteger(drop) || drop < 0 || drop > had.length) throw new Error(`layer "${edit.layer}" has ${had.length} strokes: cannot drop ${String(edit.drop)}`);- layer.strokes = [...had.slice(0, had.length - drop), ...(edit.strokes ?? [])];+ const kept = had.slice(0, had.length - drop);+ const at = edit.at ?? kept.length;+ const remove = edit.remove ?? 0;+ if (!Number.isInteger(at) || at < 0 || at > kept.length || !Number.isInteger(remove) || remove < 0 || at + remove > kept.length) throw new Error(`layer "${edit.layer}" has ${kept.length} strokes: cannot replace ${remove} at ${at}`);+ kept.splice(at, remove, ...(edit.strokes ?? []));+ layer.strokes = kept;break;}case 'wrap': {diff --git a/pipeline/src/modeling/modelSource.ts b/pipeline/src/modeling/modelSource.tsindex be037fa8b..4fbb66ef3 100644--- a/pipeline/src/modeling/modelSource.ts+++ b/pipeline/src/modeling/modelSource.ts@@ -618,8 +618,12 @@ export function applyModelEdits(source: ModelSource, edits: readonly ModelEdit[]return validateModelSource(next);}+const UNOFFERED_OPS: ReadonlySet<string> = new Set(['humanoid', 'garment']);+/** The op vocabulary as text, for what a tool tells its caller. */export const describeModelOps = (): string => Object.entries(MODEL_OPS)+ // They still run for what uses them. A model handed a ready body copies it, and a coloured mannequin comes back.+ .filter(([name]) => !UNOFFERED_OPS.has(name)).map(([name, spec]) => `${name}(${Object.keys(spec.params).map((p) => (spec.required.includes(p) ? p : `${p}?`)).join(', ')}): ${spec.says}`).join('; ');diff --git a/pipeline/src/modeling/pose.ts b/pipeline/src/modeling/pose.tsindex cb77c7fb0..58fc78612 100644--- a/pipeline/src/modeling/pose.ts+++ b/pipeline/src/modeling/pose.ts@@ -9,7 +9,7 @@*/import { HUMANOID_TAGS, humanoidJoints, type HumanoidBuild } from './humanoid';import { compact, type PolyMesh, type Vec3 } from './polyMesh';-import { computeWornWeights, jointPositions, posedPositions, resolveJoints, type AnimationSource, type AnimationTrack, type RigJoint, type SkinWeights } from './rig';+import { computeWornWeights, jointFrames, jointPositions, posedPositions, resolveJoints, type AnimationSource, type AnimationTrack, type RigJoint, type SkinWeights } from './rig';export interface PoseParams {/** The bones of a humanoid of this build; true for the default one. */@@ -57,6 +57,12 @@ export function poseJoints(p: PoseParams): Record<string, Vec3> {return jointPositions(joints, animation, 0);}+/** The same, with which way each joint has turned. */+export function poseFrames(p: PoseParams): ReturnType<typeof jointFrames> {+ const { joints, animation } = poseClip(p);+ return jointFrames(joints, animation, 0);+}+export function poseStep(mesh: PolyMesh, p: PoseParams): PolyMesh {const { joints, animation } = poseClip(p);if (mesh.positions.length === 0) throw new Error('there is nothing yet to pose');diff --git a/pipeline/src/modeling/rig.ts b/pipeline/src/modeling/rig.tsindex e7544fe74..c1a9d714d 100644--- a/pipeline/src/modeling/rig.ts+++ b/pipeline/src/modeling/rig.ts@@ -1052,6 +1052,15 @@ export function jointPositions(joints: readonly RigJoint[], animation: Animationreturn Object.fromEntries(joints.map((j, i) => [j.name, world[i]!.origin]));}+/** Where each joint is in a pose, and which way its own axes have turned from rest. */+export function jointFrames(joints: readonly RigJoint[], animation: AnimationSource | null, time: number, solve?: PoseSolve): Record<string, { at: Vec3; x: Vec3; y: Vec3; z: Vec3 }> {+ const { world } = poseAt(joints, animation, time, solve);+ return Object.fromEntries(joints.map((j, i) => {+ const { origin, q } = world[i]!;+ return [j.name, { at: origin, x: rotateBy(q, [1, 0, 0]), y: rotateBy(q, [0, 1, 0]), z: rotateBy(q, [0, 0, 1]) }];+ }));+}+/** The surface's positions in a pose, skinned as the engine skins it. */export function posedPositions(mesh: PolyMesh, joints: readonly RigJoint[], skin: SkinWeights, animation: AnimationSource | null, time: number, solve?: PoseSolve): Vec3[] {const pose = poseAt(joints, animation, time, solve).world;diff --git a/pipeline/tests/image-raster.test.ts b/pipeline/tests/image-raster.test.tsindex f333e3c51..15d897d17 100644--- a/pipeline/tests/image-raster.test.ts+++ b/pipeline/tests/image-raster.test.ts@@ -608,7 +608,7 @@ describe('noise', () => {expect(() => bad({ scale: 0 })).toThrow(/scale must be a positive/);expect(() => bad({ octaves: 9 })).toThrow(/octaves must be/);expect(() => bad({ seed: 1.5 })).toThrow(/seed must be/);- expect(() => validateImageSource({ size: 8, layers: [{ shape: 'rect', at: [0, 0], size: [8, 8], fill: { type: 'wavy', stops: [] } }] })).toThrow(/linear, radial, noise or form/);+ expect(() => validateImageSource({ size: 8, layers: [{ shape: 'rect', at: [0, 0], size: [8, 8], fill: { type: 'wavy', stops: [] } }] })).toThrow(/linear, radial, noise, form or image/);});});@@ -1037,6 +1037,7 @@ describe('a figure to draw over', () => {it('says what is wrong with one', () => {const bad = (l: object): unknown => validateImageSource({ size: 64, layers: [{ shape: 'figure', at: [4, 4], height: 40, ...l }] });+ expect(() => bad({ eyes: 'closed' })).toThrow(/unknown field "eyes"/);expect(() => bad({ height: undefined })).toThrow(/height must be pixels/);expect(() => bad({ build: { nose: 2 } })).toThrow(/build has unknown "nose"/);expect(() => bad({ pose: { twist: {} } })).toThrow(/pose has unknown "twist"/);@@ -1045,6 +1046,113 @@ describe('a figure to draw over', () => {}, LONG);});+describe('bones and blocks, and no look', () => {+ const person = { id: 'f', shape: 'figure', at: [128, 240], height: 220 } as ImageLayer;+ const shown = (fields: object = {}): ReturnType<typeof renderImage> => renderImage(validateImageSource({ size: 256, layers: [{ ...person, ...fields }] }), { guides: true });++ it('has blocks and no face, hair or fingers to copy', () => {+ const out = shown();+ expect(Object.keys(out.layerBounds).sort()).toEqual(['f', 'f.arm', 'f.foot', 'f.hand', 'f.head', 'f.leg', 'f.neck', 'f.torso']);+ });++ it('takes no time to speak of, as it builds no surface', () => {+ const began = Date.now();+ shown({ yaw: 33, pose: { rotate: { neck: [20, 0, 0] } } });+ expect(Date.now() - began).toBeLessThan(1500);+ });++ it('stays in proportion, narrower through the waist than the shoulders, and takes a build', () => {+ const width = (fields: object, y: number): number => { const img = shown(fields); let n = 0; for (let x = 0; x < 256; x++) if (img.rgba[(y * 256 + x) * 4 + 3]! > 128) n++; return n; };+ const m = shown().figures.f!;+ expect(width({ pose: { rotate: { 'upperArm.L': [0, 0, 60], 'upperArm.R': [0, 0, -60] } } }, m.spine![1])).toBeLessThan(width({}, m.chest![1]) * 1.2);+ expect(width({ build: { waist: 1.6 } }, m.spine![1])).toBeGreaterThan(width({}, m.spine![1]));+ const big = shown({ build: { head: 1.4 } }).layerBounds['f.head']!;+ expect(big[2]).toBeGreaterThan(shown().layerBounds['f.head']![2]);+ });++ it('turns the cross on the head with the head', () => {+ const lit = (fields: object): Uint8Array => shown(fields).rgba;+ expect(lit({ pose: { rotate: { neck: [40, 0, 0] } } })).not.toEqual(lit({}));+ });++ it('lets a form carry on past the blocks, for cloth', () => {+ const img = renderImage(validateImageSource({ size: 256, layers: [person, { shape: 'rect', at: [0, 0], size: [256, 256], fill: { type: 'form', figure: 'f', light: [-1, 0, 0], stops: [[0, '#000000'], [1, '#ffffff']] } } as never] }));+ const m = img.figures.f!;+ const box = img.layerBounds['f.torso']!;+ const y = m.spine![1];+ expect(px(img as never, box[0] + 6, y)[0]).toBeGreaterThan(px(img as never, box[0] + box[2] - 6, y)[0]! + 30);+ });+});++describe('a picture to draw over', () => {+ const picture = { width: 2, height: 1, rgba: new Uint8Array([255, 0, 0, 255, 0, 0, 255, 255]) };+ const image = { id: 'ref', shape: 'image', src: 'a.png', at: [0, 0], size: [64, 64] } as ImageLayer;+ const render = (layers: ImageLayer[], guides = false): ReturnType<typeof renderImage> => renderImage(validateImageSource({ size: 64, layers }), { guides, pictures: { 'a.png': picture } });++ it('is seen when looking and stays out of the picture, unless told', () => {+ expect(px(render([image], true), 4, 32)[0]).toBe(255);+ expect(px(render([image]), 4, 32)[3]).toBe(0);+ expect(px(render([{ ...image, guide: false }]), 4, 32)[0]).toBe(255);+ });++ it('scales to its size, smoothly', () => {+ const img = render([image], true);+ expect(px(img, 60, 32)[2]).toBe(255);+ expect(px(img, 32, 32)[0]).toBeGreaterThan(90);+ expect(px(img, 32, 32)[2]).toBeGreaterThan(90);+ });++ it('gives its colours to a fill and to a field', () => {+ const img = render([image, { shape: 'rect', at: [0, 0], size: [64, 64], fill: { type: 'image', image: 'ref' } } as never]);+ expect(px(img, 4, 32)[0]).toBe(255);+ expect(px(img, 60, 32)[2]).toBe(255);+ const field = render([image, { shape: 'paint', strokes: [{ type: 'field', tone: { type: 'image', image: 'ref' }, size: 4, length: 8, hardness: 1, opacity: 1, vary: 0, seed: 1 }] } as never]);+ expect(px(field, 10, 32)[0]).toBeGreaterThan(px(field, 10, 32)[2]!);+ expect(px(field, 54, 32)[2]).toBeGreaterThan(px(field, 54, 32)[0]!);+ });++ it('says when it is not there', () => {+ expect(() => renderImage(validateImageSource({ size: 8, layers: [{ shape: 'image', src: 'gone.png' }] }))).toThrow(/no picture at gone.png/);+ expect(() => validateImageSource({ size: 8, layers: [{ shape: 'image' }] })).toThrow(/src must be/);+ });+});++describe('what the second trial tripped on', () => {+ const halves: ImageLayer[] = [{ id: 'a', shape: 'rect', at: [0, 0], size: [32, 64], fill: BLUE }];+ it('takes a clip with @ as well, and a clip of nothing draws nothing', () => {+ const over: ImageLayer = { shape: 'rect', at: [0, 0], size: [64, 64], fill: RED };+ expect(px(draw([...halves, { ...over, clip: '@a' }]), 10, 10)[0]).toBe(255);+ expect(px(draw([...halves, { ...over, clip: '@a' }]), 50, 10)[3]).toBe(0);+ const lost = draw([{ ...over, clip: 'nothing' }]);+ expect(px(lost, 10, 10)[3]).toBe(0);+ expect(lost.notes.join()).toMatch(/so it drew nothing/);+ });++ it('draws everywhere except a layer, and inside a clip too', () => {+ const over: ImageLayer = { shape: 'rect', at: [0, 0], size: [64, 64], fill: RED, except: 'a' };+ const img = draw([...halves, over]);+ expect(px(img, 10, 10)[0]).toBe(0);+ expect(px(img, 50, 10)[0]).toBe(255);+ expect(draw([{ ...over, except: 'none' }]).notes.join()).toMatch(/except "none"/);+ });++ it('keeps a face out of a pass across the picture', () => {+ const under: ImageLayer[] = [{ id: 'l', shape: 'rect', at: [0, 0], size: [32, 64], fill: RED }, { id: 'r', shape: 'rect', at: [32, 0], size: [32, 64], fill: BLUE }, { id: 'kept', shape: 'rect', at: [36, 26], size: [12, 12], fill: '#00000000' }];+ const pass = { shape: 'paint', from: 'below', except: 'kept', strokes: [{ points: [[8, 32], [56, 32]], size: 12, smudge: 0.9 }] };+ const img = draw([...under, pass as never]);+ expect(px(img, 42, 32)).toEqual([0, 0, 255, 255]);+ expect(px(img, 54, 32)[0]).toBeGreaterThan(5);+ });++ it('changes one entry in the middle of a paint layer', () => {+ const dab = (x: number): object => ({ points: [[x, 5]], color: RED, size: 2 });+ const start = validateImageSource({ size: 64, layers: [{ id: 'p', shape: 'paint', strokes: [dab(1), dab(2), dab(3)] }] });+ const next = applyImageEdits(start, [{ op: 'paint', layer: 'p', at: 1, remove: 1, strokes: [dab(9) as never, dab(10) as never] }]);+ expect(next.layers[0]!.strokes!.map((s) => (s as unknown as { points: number[][] }).points[0]![0])).toEqual([1, 9, 10, 3]);+ expect(() => applyImageEdits(start, [{ op: 'paint', layer: 'p', at: 2, remove: 5 }])).toThrow(/cannot replace 5 at 2/);+ });+});+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 }]);diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 42e5e2199..f37e0e67b 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): a figure is bones and blocks, and a picture from the project can be drawn over":+ {"note":"An AI can draw 2D pictures."},+ "feat(mcp): a picture as a reference, and the body no longer offered to build a character on":+ {"note":"An AI can draw 2D pictures."},"feat(look): a posed body to draw over, its joints in the picture and light by its form":{"note":"An AI can draw 2D pictures."},"feat(mcp): image_write takes a figure as a guide":