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(assets): a recipe is read wherever an image is, with its text, its figures and its surface maps - a ground's layers and a field's maps take an .esimage, a map of a picture is a two-line recipe that names it, text is set by the device's canvas and a figure is posed by the bones the pipeline poses, which moved into the SDK; a recipe ships with the pictures and fonts it names and is drawn again when one changes
yhh6aa67bb82e7f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8273aa057..dbcb84e93 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **A recipe is read wherever an image is, with its text, its figures and its surface maps.** A texture recipe (an `.esimage` shipped in place of its pixels) was a texture only, and one with text or a `figure` layer was refused on the device. Now what reads an image as numbers reads a recipe too (a ground's layers and splatmap, a field's density and scale maps). A source's normal map and its roughness-and-metal map are each a texture by a recipe of two lines, `{ "mapOf": "assets/wall.esimage", "map": "normal" }`, with import settings of its own. Text is set by the device's 2D canvas (on the worker where it has one), in a font file of the project where the layer names one; a host with no canvas refuses it and says to bake. A figure is posed on the device by the same bones the pipeline poses, which moved from the pipeline into the SDK (`pipeline/src/modeling` reads them from there). A recipe may lay in a PNG or another recipe; what it names ships with it (the cook follows a recipe's references now) and is part of what its kept pixels are kept under. An exported game with four such recipes drew all four on workers on the first visit and none on the second. `esengine/image` is 220 KB of a web package before compression (81 KB gzipped), up from 172. A ground reading a recipe is checked by a test and not yet in a game; nothing was timed on a phone.- **A texture recipe is drawn on a worker, once.** A recipe was drawn on the main thread when its texture loaded, every run. It is drawn on a worker thread now, and its pixels are kept in the content cache under a name made of the recipe and the raster's revision, so the next run reads them. An exported game with a 2048 pixel plate, opened twice in one browser: the first visit drew for 4.1 s on a worker with no main-thread task over 550 ms, the second drew nothing (0 jobs, 307 ms longest task). A browser had no content cache; it has one now, in IndexedDB, which also means files a web game downloads through hot update are kept between visits. Where there are no workers the recipe is drawn on the main thread. Carrying the raster for the worker as well takes `esengine/image` from 86 KB to 172 KB of a web package before compression (62 KB gzipped). Kept pixels are uncompressed and are removed only by `cleanDiskCache`. Not timed on a phone.- **A texture can ship as its recipe.** A package shipped every pixel of every picture. An `.esimage` (the layered source the image tools write, which until now was only ever baked to a `.png` beside it) can be named where a texture goes, and the package then carries the source: the texture is drawn on the device when it is first loaded. In a headless game a 512 pixel plate drawn from its 691 byte recipe matched its 351 KB PNG at every one of 921,600 pixels. The raster moved from the pipeline into the SDK as `esengine/image` (about 86 KB of a web package before compression), which an export adds when a recipe ships and no other package carries; the pipeline and the editor draw with the same code. It is drawn on the main thread at load and is not kept between runs, and a picture with a `figure` layer or text is still baked.- **A scale map.** `Foliage.densityMap` says how many of a field's plants stand where, and every one that stood was its full size: grass that thinned toward a beach ended in tufts as tall as the meadow's. `Foliage.scaleMap` is an image over the same area whose red is how large the plants stand: full size at white, smaller toward black, none at black. It is read as numbers, as the density map is, and on the workers with it. With both, a sward thins and shortens as it runs out and has a soft edge.diff --git a/docs/astro/src/content/docs/assets/textures.mdx b/docs/astro/src/content/docs/assets/textures.mdxindex 937608909..02d0931a4 100644--- a/docs/astro/src/content/docs/assets/textures.mdx+++ b/docs/astro/src/content/docs/assets/textures.mdx@@ -205,7 +205,7 @@ its `.png` has.```A 512 pixel plate of noise, rust, a stripe and rivets is 691 bytes as a recipe and 351 KB as a PNG. What draws recipes is the-`esengine/image` module, about 172 KB of a web package before compression (62 KB gzipped): an export adds it when a recipe ships, and a script that+`esengine/image` module, about 220 KB of a web package before compression (81 KB gzipped): an export adds it when a recipe ships, and a script thatloads one by code imports it where the game starts. A package with no recipe does not carry it.What a recipe costs is time, once. It is drawn on a worker thread, so the game keeps running while it draws, and the pixels are@@ -215,8 +215,28 @@ uncompressed (16 MB for that plate) and nothing removes them unasked: `assets.cllongest ago first, and a removed picture is drawn again. Where there are no workers the recipe is drawn on the main thread; where there is no cache it is drawn every run. A changed recipe, or a changed raster, is adifferent entry, so nothing stale is ever read.-A picture with a `figure` layer or text needs the authoring tools to draw and is baked to its `.png` instead; so is a source's-surface (its normal and roughness maps).+A recipe is read wherever an image is: as a texture, and by what reads an image as numbers (a ground's layers, its splatmap, a+field's density and scale maps).++**Surface maps.** A source with a `material` is a surface as well as a colour. Each of its maps is a texture of its own, so it is a+file of its own, two lines that name the picture:++```json+{ "mapOf": "assets/tex/wall.esimage", "map": "normal" }+```++`map` is `normal` or `surface` (roughness in green, metal in blue; one pixel where both are one value everywhere). Save it as an+`.esimage`, give it the import settings a map has (Use: Data or Normal map), and name it where the map goes. The picture it is a map+of ships with it, named anywhere else or not.++**What a recipe may name.** A picture it lays in (an `image` layer's `src`: a PNG, or another recipe), and a font file its text is+set in. They ship with the recipe, and a change in any of them draws it again.++**Text** is set by the device's own 2D canvas, on the worker where the worker has one. A `font` that is a file of the project is+drawn in that file's glyphs everywhere; a family name, or none, is whatever the device has, so the same recipe can come out+differently on two devices. A host with no 2D canvas (the native hosts) refuses a recipe with text and says to bake it.++**A `figure` layer** is posed and flattened on the device by the same code that draws it where it is authored.## Memory & residencydiff --git a/docs/astro/src/content/docs/zh-cn/assets/textures.mdx b/docs/astro/src/content/docs/zh-cn/assets/textures.mdxindex cc4132cc7..dbf6be29b 100644--- a/docs/astro/src/content/docs/zh-cn/assets/textures.mdx+++ b/docs/astro/src/content/docs/zh-cn/assets/textures.mdx@@ -179,14 +179,31 @@ sprite.uvScale = { x: 32 / 256, y: 32 / 256 };```一块 512 像素、带噪声、锈迹、色带和铆钉的钢板,作为配方是 691 字节,作为 PNG 是 351 KB。负责画配方的是 `esengine/image` 模块,压缩前约占-web 包 172 KB(gzip 后 62 KB):导出时只要包里有配方就会自动带上,用脚本按代码加载配方的话,在游戏启动处导入它。没有配方的包不会带它。+web 包 220 KB(gzip 后 81 KB):导出时只要包里有配方就会自动带上,用脚本按代码加载配方的话,在游戏启动处导入它。没有配方的包不会带它。配方的代价是时间,而且只付一次。它在工作线程上绘制,画的时候游戏照常运行;画出的像素存进设备的内容缓存,下次运行直接读取,什么都不画。一块 2048 像素的钢板第一次访问时在桌面工作线程上画了 4.1 秒,主线程的最长占用没有超过平常启动的水平;第二次访问一笔没画。存下来的像素没有压缩(那块钢板是 16 MB),也不会被自动清掉:`assets.cleanDiskCache(budget, true)` 先清最久没读过的,被清掉的图下次再画一遍。没有工作线程的环境里配方在主线程绘制;没有缓存的环境里每次运行都画。配方变了,或者光栅器变了,就是另一个缓存项,所以不会读到过期的像素。-带 `figure` 图层或文字的图需要创作工具才能画,仍然烘焙成 `.png`;源文件的表面贴图(法线和粗糙度)也是。+凡是读图片的地方都认配方:作为贴图,以及把图片当数值读的地方(地形图层、地形的 splatmap、植被的密度图和缩放图)。++**表面贴图。** 带 `material` 的源文件既是颜色也是表面。它的每张表面贴图都是独立的贴图,所以是独立的文件,两行,指向那张图:++```json+{ "mapOf": "assets/tex/wall.esimage", "map": "normal" }+```++`map` 是 `normal` 或 `surface`(绿通道粗糙度,蓝通道金属度;两者处处同值时只有一个像素)。存成 `.esimage`,给它贴图该有的导入设置+(用途:数据或法线贴图),在需要这张贴图的地方引用它。它所指向的那张图会随它一起进包,不管别处有没有引用。++**配方可以引用什么。** 铺进来的图片(`image` 图层的 `src`:PNG 或另一个配方),以及文字所用的字体文件。它们随配方一起进包,其中任何+一个变了,配方都会重画。++**文字**由设备自己的 2D 画布绘制,工作线程有画布时就在工作线程上画。`font` 写的是项目里的字体文件时,各处画出的字形一致;写字体族名+或不写时,用的是设备上的字体,所以同一个配方在两台设备上可能不一样。没有 2D 画布的宿主(原生宿主)会拒绝带文字的配方,并提示改为烘焙。++**`figure` 图层**在设备上摆姿势、压平,用的就是创作时画它的那份代码。## 内存与驻留diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 4882aaa5b..13ba3acca 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 117,"beta": 178,- "experimental": 3069,+ "experimental": 3075,"deprecated": 3},- "total": 3364,+ "total": 3370,"subsystems": [{"id": "mobile-controls",@@ -410,8 +410,8 @@"title": "Texture recipes","titleZh": "贴图配方","tier": "experimental",- "why": "a recipe draws on the device to the very pixels its baked picture has, checked in a headless game, and is drawn on a worker once and read from the content cache after, checked in a browser opened twice; but it has not been timed on a phone, and the surface maps of a source are still baked",- "whyZh": "配方在设备上画出来的像素与烘焙好的图片逐像素一致,已在无头游戏里检查过;它在工作线程上画一次,之后从内容缓存读取,已在浏览器里两次打开检查过;但没有在手机上计过时,源文件的表面贴图仍需烘焙",+ "why": "a recipe draws on the device to the very pixels its baked picture has, checked in a headless game, and is drawn on a worker once and read from the content cache after, checked in a browser opened twice, text, figures, laid-in pictures and surface maps included; but it has not been timed on a phone, text follows the fonts of the device unless a font file is named, and a ground reading a recipe as its layer is checked by a test and not in a game",+ "whyZh": "配方在设备上画出来的像素与烘焙好的图片逐像素一致,已在无头游戏里检查过;它在工作线程上画一次,之后从内容缓存读取,已在浏览器里两次打开检查过,文字、人物、铺入的图片和表面贴图都在内;但没有在手机上计过时,不指定字体文件时文字跟随设备字体,地形把配方当图层读只有测试检查过、没在游戏里检查过","entry": ["renderImage","validateImageSource"diff --git a/pipeline/src/assets/assetDb.ts b/pipeline/src/assets/assetDb.tsindex 695579662..69ce91f6a 100644--- a/pipeline/src/assets/assetDb.ts+++ b/pipeline/src/assets/assetDb.ts@@ -239,6 +239,8 @@ const JSON_REF_TYPES = new Set(['json', 'sound-event', 'world-rules', 'terrain-layer', 'terrain-tiles',]);+const isTextureRecipe = (e: { type: string; path: string }): boolean => e.type === 'texture' && e.path.toLowerCase().endsWith('.esimage');+/*** Collect every asset reference in a JSON document:* - `@uuid:<id>` refs (editor-serialized stable refs)@@ -375,7 +377,8 @@ async function computeDeps(const byPath = new Map(entries.map((e) => [e.path, e]));const uuids = new Set(entries.map((e) => e.uuid));const refEntries = (targets ?? entries).filter(- (e) => JSON_REF_TYPES.has(e.type) || e.type === BITMAP_FONT || e.type === 'mesh'+ // A texture that is a recipe names what it is drawn from: the pictures it lays in, its font files, the picture it is a map of.+ (e) => JSON_REF_TYPES.has(e.type) || e.type === BITMAP_FONT || e.type === 'mesh' || isTextureRecipe(e)|| SKELETAL_ATLAS_TYPES.has(getEditorType(e.path)),);type DepResult = { uuid: string; refs: string[] } | { warning: string };diff --git a/pipeline/src/image/imageFigure.ts b/pipeline/src/image/imageFigure.tsindex 37cbc4a32..e208a3ddc 100644--- a/pipeline/src/image/imageFigure.ts+++ b/pipeline/src/image/imageFigure.ts@@ -1,268 +1,4 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file imageFigure.ts- * @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.- *- * 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 type { HumanoidBuild } from '../modeling/humanoid';-import { poseFrames, poseJoints, type PoseParams } from '../modeling/pose';-import type { ImageLayer } from './imageSource';-import type { FlatFigure, ImageFigureDrawer } from './imageRaster';--export type { FlatFigure } from './imageRaster';--/** The bones' own height: they are built at it, and sized in the picture. */-const BODY_HEIGHT = 1.6;-const SUPERSAMPLE = 2;-const AROUND = 14;--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'],-];--interface Ring { at: V3; across: V3; deep: V3; a: number; d: number }-interface Volume { tag: (typeof FIGURE_TAGS)[number]; rings: Ring[] }--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]];--/** 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));- }- 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;-}---const normalized = (v: readonly number[]): [number, number, number] => {- const len = Math.hypot(v[0]!, v[1]!, v[2]!) || 1;- return [v[0]! / len, v[1]! / len, v[2]! / len];-};--/** Flattens a `figure` layer. @p project takes a point in the picture before any group's transform, and @p scale is that transform's size. */-export function flattenFigure(layer: ImageLayer, w: number, h: number, project: (p: readonly [number, number]) => readonly [number, number], scale: number): FlatFigure {- const [ax, ay] = project(layer.at!);- const s = ((layer.height as number) / BODY_HEIGHT) * scale;- const yaw = ((layer.yaw ?? 0) * Math.PI) / 180, pitch = ((layer.pitch ?? 0) * Math.PI) / 180;- const [cy, sy, cp, sp] = [Math.cos(yaw), Math.sin(yaw), Math.cos(pitch), Math.sin(pitch)];- /** Yaw about the body, then pitch toward the viewer: what the body's axes are in the view. */- const toView = (p: readonly number[]): [number, number, number] => {- const [x, y, z] = [p[0]! * cy + p[2]! * sy, p[1]!, -p[0]! * sy + p[2]! * cy];- return [x, y * cp - z * sp, y * sp + z * cp];- };- const fromView = (v: readonly number[]): [number, number, number] => {- 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 ?? {});- let resolved: PoseParams = held;- if (reach.length) {- const before = poseJoints(held);- 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 frames = poseFrames(resolved);- const joints: Record<string, readonly [number, number]> = {};- for (const name of FIGURE_JOINTS) {- 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);- 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 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);- const tag = tagAt[i]!;- const right = x + 1 < W ? depth[i + 1]! : -Infinity, below = y + 1 < H ? depth[i + W]! : -Infinity;- if (tag >= 0 || right > -Infinity || below > -Infinity) {- const here = depth[i]!;- if (Math.abs(here - right) > step || Math.abs(here - below) > step) contour[o] = Math.min(1, contour[o]! + share * 2);- }- if (tag < 0) continue;- mask[o]! += share;- parts[FIGURE_TAGS[tag]!]![o]! += share;- for (let k = 0; k < 3; k++) normals[o * 3 + k]! += nAt[i * 3 + k]! * share;- }- }- for (let o = 0; o < mask.length; o++) {- 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;- }-- // 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;--/** The drawer of figures the pipeline hands every picture it renders. */-export const FIGURE_DRAWER: ImageFigureDrawer = { flatten: flattenFigure };+// The picture code is the SDK's (sdk/src/image), so a game can evaluate a picture as the pipeline does; this is where the pipeline reaches it.+export * from '../../../sdk/src/image/imageFigure';diff --git a/pipeline/src/image/imageMaterial.ts b/pipeline/src/image/imageMaterial.tsindex cd980607f..f253e1040 100644--- a/pipeline/src/image/imageMaterial.ts+++ b/pipeline/src/image/imageMaterial.ts@@ -1,16 +1,4 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file imageMaterial.ts: the SDK's surface maps (sdk/src/image), drawn with the pipeline's drawer of figures.- */-import { renderMaterialMaps as render, type MaterialMaps } from '../../../sdk/src/image/imageMaterial';-import type { RgbaBitmap } from '../../../sdk/src/image/imageRaster';-import type { ImageSource } from '../../../sdk/src/image/imageSource';-import { FIGURE_DRAWER } from './imageFigure';-+// The picture code is the SDK's (sdk/src/image), so a game can evaluate a picture as the pipeline does; this is where the pipeline reaches it.export * from '../../../sdk/src/image/imageMaterial';--/** The maps a source's surface draws, figures and all. */-export function renderMaterialMaps(source: ImageSource, color: RgbaBitmap, options: Parameters<typeof render>[2] = {}): MaterialMaps {- return render(source, color, { figure: FIGURE_DRAWER, ...options });-}diff --git a/pipeline/src/image/imageRaster.ts b/pipeline/src/image/imageRaster.tsindex 64dc886a3..d3efe1875 100644--- a/pipeline/src/image/imageRaster.ts+++ b/pipeline/src/image/imageRaster.ts@@ -1,15 +1,4 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file imageRaster.ts: the SDK's raster (sdk/src/image), with the pipeline's own drawer of figures handed to every picture it renders.- */-import { renderImage as render, type RenderedImage } from '../../../sdk/src/image/imageRaster';-import type { ImageSource } from '../../../sdk/src/image/imageSource';-import { FIGURE_DRAWER } from './imageFigure';-+// The picture code is the SDK's (sdk/src/image), so a game can evaluate a picture as the pipeline does; this is where the pipeline reaches it.export * from '../../../sdk/src/image/imageRaster';--/** The picture a source draws, figures and all. */-export function renderImage(source: ImageSource, options: Parameters<typeof render>[1] = {}): RenderedImage {- return render(source, { figure: FIGURE_DRAWER, ...options });-}diff --git a/pipeline/src/modeling/humanoid.ts b/pipeline/src/modeling/humanoid.tsindex 11993d35b..f06884476 100644--- a/pipeline/src/modeling/humanoid.ts+++ b/pipeline/src/modeling/humanoid.ts@@ -10,21 +10,9 @@*/import { organic, type OrganicPart } from './organic';import type { PolyMesh, Vec3 } from './polyMesh';-import type { RigJointSource } from './rig';+import { humanoidFrame, TORSO, type HumanoidBuild, type Section } from '../../../sdk/src/image/figureSkeleton';-export interface HumanoidBuild {- /** From the floor to the crown. Default 1.6. */- height?: number;- /** Size of the head against the body. Default 1; above it younger or more stylised. */- head?: number;- /** Width of each, against the table. Default 1. */- shoulders?: number;- chest?: number;- waist?: number;- hips?: number;- /** Thickness of the arms and legs. Default 1. */- limbs?: number;-}+export { humanoidFrame, humanoidJoints, type HumanoidBuild, type HumanoidFrame } from '../../../sdk/src/image/figureSkeleton';export interface HumanoidParams extends HumanoidBuild {/** Grid cells along the height of the body. Default 240; the face and hands get finer faces anyway. */@@ -39,107 +27,6 @@ export interface HumanoidParams extends HumanoidBuild {tag?: string;}-interface Section { y: number; across: number; front: number; back: number; z: number; x?: number }--/** The table is for a body 1.6 tall. */-const TABLE_HEIGHT = 1.6;--const TORSO: readonly Section[] = [- { y: 1.345, across: 0.05, front: 0.05, back: 0.055, z: -0.018 },- { y: 1.315, across: 0.082, front: 0.058, back: 0.066, z: -0.022 },- { y: 1.285, across: 0.145, front: 0.068, back: 0.074, z: -0.022 },- { y: 1.25, across: 0.158, front: 0.08, back: 0.08, z: -0.018 },- { y: 1.2, across: 0.142, front: 0.094, back: 0.082, z: -0.012 },- { y: 1.145, across: 0.125, front: 0.098, back: 0.076, z: -0.006 },- { y: 1.09, across: 0.108, front: 0.08, back: 0.068, z: -0.004 },- { y: 1.03, across: 0.096, front: 0.066, back: 0.056, z: -0.002 },- { y: 0.975, across: 0.104, front: 0.068, back: 0.058, z: 0 },- { y: 0.915, across: 0.122, front: 0.074, back: 0.076, z: -0.004 },- { y: 0.85, across: 0.14, front: 0.076, back: 0.088, z: -0.006 },- { y: 0.79, across: 0.132, front: 0.07, back: 0.08, z: -0.004 },- { y: 0.745, across: 0.08, front: 0.06, back: 0.06, z: -0.004 },-];--const ARM_DROP = (62 * Math.PI) / 180;--export interface HumanoidFrame {- k: number;- shoulder: Vec3; elbow: Vec3; wrist: Vec3; knuckle: Vec3;- hip: Vec3; knee: Vec3; ankle: Vec3; ball: Vec3; toe: Vec3;- pelvis: Vec3; waist: Vec3; chest: Vec3; neck: Vec3; head: Vec3; crown: Vec3;- /** Along the arm, from the shoulder out and down. */- along: Vec3;- fingers: readonly { name: string; base: Vec3; length: number; radius: number }[];- thumb: { base: Vec3; mid: Vec3; tip: Vec3 };-}--/** Where everything is, in the table's own proportions times its height. Also what a skeleton is laid on. */-export function humanoidFrame(b: HumanoidBuild = {}): HumanoidFrame {- const k = (b.height ?? TABLE_HEIGHT) / TABLE_HEIGHT;- const s = (x: number, y: number, z: number): Vec3 => [x * k, y * k, z * k];- const along: Vec3 = [Math.sin(ARM_DROP), -Math.cos(ARM_DROP), 0];- const shoulderX = 0.158 * (b.shoulders ?? 1);- const at = (d: number): Vec3 => s(shoulderX + along[0] * d, 1.268 + along[1] * d, -0.018);- const palmAt = 0.27 + 0.235 + 0.09;- const fingers = [- { name: 'index', z: 0.027, length: 0.078, radius: 0.0085 },- { name: 'middle', z: 0.009, length: 0.086, radius: 0.0088 },- { name: 'ring', z: -0.009, length: 0.08, radius: 0.0082 },- { name: 'little', z: -0.026, length: 0.062, radius: 0.0072 },- ].map((f) => {- const base = at(palmAt);- return { name: f.name, base: [base[0], base[1], base[2] + f.z * k] as Vec3, length: f.length * k, radius: f.radius * k };- });- const wrist = at(0.27 + 0.235);- const thumbBase: Vec3 = [wrist[0] + along[0] * 0.022 * k, wrist[1] + along[1] * 0.022 * k - 0.004 * k, wrist[2] + 0.028 * k];- const thumbMid: Vec3 = [thumbBase[0] + along[0] * 0.038 * k, thumbBase[1] + along[1] * 0.038 * k - 0.006 * k, thumbBase[2] + 0.024 * k];- const thumbTip: Vec3 = [thumbMid[0] + along[0] * 0.036 * k, thumbMid[1] + along[1] * 0.036 * k - 0.006 * k, thumbMid[2] + 0.01 * k];- return {- k, along,- shoulder: at(0), elbow: at(0.27), wrist, knuckle: at(palmAt),- hip: s(0.08, 0.81, -0.004), knee: s(0.068, 0.445, 0.006), ankle: s(0.067, 0.078, -0.016), ball: s(0.072, 0.022, 0.09), toe: s(0.072, 0.018, 0.165),- pelvis: s(0, 0.86, -0.004), waist: s(0, 1.0, 0), chest: s(0, 1.16, -0.008), neck: s(0, 1.32, -0.022), head: s(0, 1.405, -0.01), crown: s(0, TABLE_HEIGHT, -0.012),- fingers, thumb: { base: thumbBase, mid: thumbMid, tip: thumbTip },- };-}--/** The bones of a humanoid of this build, named as a clip names them. `.L` is her left, on +x. */-export function humanoidJoints(b: HumanoidBuild = {}): RigJointSource[] {- const f = humanoidFrame(b);- const mid = (a: Vec3, c: Vec3, t: number): Vec3 => [a[0] + (c[0] - a[0]) * t, a[1] + (c[1] - a[1]) * t, a[2] + (c[2] - a[2]) * t];- const clavicle: Vec3 = [0.03 * f.k, 1.29 * f.k, -0.008 * f.k];- const joints: RigJointSource[] = [- { name: 'hips', at: f.pelvis },- { name: 'spine', at: f.waist, parent: 'hips' },- { name: 'chest', at: f.chest, parent: 'spine' },- { name: 'neck', at: f.neck, parent: 'chest' },- { name: 'head', at: f.head, parent: 'neck' },- { name: 'crown', at: f.crown, parent: 'head' },- { name: 'clavicle', at: clavicle, parent: 'chest', mirror: 'x' },- { name: 'upperArm', at: f.shoulder, parent: 'clavicle', mirror: 'x' },- { name: 'forearm', at: f.elbow, parent: 'upperArm', mirror: 'x' },- { name: 'hand', at: f.wrist, parent: 'forearm', mirror: 'x' },- { name: 'thumb1', at: f.thumb.base, parent: 'hand', mirror: 'x' },- { name: 'thumb2', at: f.thumb.mid, parent: 'thumb1', mirror: 'x' },- { name: 'thumb3', at: f.thumb.tip, parent: 'thumb2', mirror: 'x' },- { name: 'thigh', at: f.hip, parent: 'hips', mirror: 'x' },- { name: 'shin', at: f.knee, parent: 'thigh', mirror: 'x' },- { name: 'foot', at: f.ankle, parent: 'shin', mirror: 'x' },- { name: 'toes', at: f.ball, parent: 'foot', mirror: 'x' },- { name: 'toeTip', at: f.toe, parent: 'toes', mirror: 'x' },- ];- for (const finger of f.fingers) {- let parent = 'hand';- for (let i = 0; i < 4; i++) {- const name = `${finger.name}${i + 1}`;- const t = [0, 0.45, 0.75, 1][i]!;- joints.push({ name, at: mid(finger.base, [finger.base[0] + f.along[0] * finger.length, finger.base[1] + f.along[1] * finger.length, finger.base[2]], t), parent, mirror: 'x' });- parent = name;- }- }- return joints;-}-/** The tags a humanoid's own skin carries: what it wears is everything else. */export const HUMANOID_TAGS: readonly string[] = ['torso', 'arm', 'hand', 'leg', 'foot', 'neck', 'face', 'scalp', 'ear', 'lips', 'lid', 'eye', 'iris'];diff --git a/pipeline/src/modeling/pose.ts b/pipeline/src/modeling/pose.tsindex 58fc78612..f532ee430 100644--- a/pipeline/src/modeling/pose.ts+++ b/pipeline/src/modeling/pose.ts@@ -7,61 +7,12 @@* pressed into the surface, by the same weights, so a still and a game agree and a pose is an edit to some angles* rather than to a drawing.*/-import { HUMANOID_TAGS, humanoidJoints, type HumanoidBuild } from './humanoid';-import { compact, type PolyMesh, type Vec3 } from './polyMesh';-import { computeWornWeights, jointFrames, jointPositions, posedPositions, resolveJoints, type AnimationSource, type AnimationTrack, type RigJoint, type SkinWeights } from './rig';+import { HUMANOID_TAGS } from './humanoid';+import { poseClip, type PoseParams } from '../../../sdk/src/image/figureSkeleton';-export interface PoseParams {- /** The bones of a humanoid of this build; true for the default one. */- humanoid: HumanoidBuild | true;- /** joint name to [x, y, z] degrees from its rest, X then Y then Z. */- rotate?: Readonly<Record<string, readonly number[]>>;- /** joint name to [x, y, z] from where it rests: `hips` lowers a sitting body. */- move?: Readonly<Record<string, readonly number[]>>;- /** joint name to where it must be, in the model's own space: a hand on a bow, a foot on the ground. The two bones above it turn to put it there; `pole` is the way the middle one bends. */- reach?: Readonly<Record<string, { at: readonly number[]; pole?: readonly number[] }>>;- /** The whole mesh rides on this one joint, whole: hair cards, which have no skin between them for weights to spread over. */- rigid?: string;-}--/** A pose as the clip that holds it, on the bones it is for. */-function poseClip(p: PoseParams): { joints: RigJoint[]; animation: AnimationSource } {- if (p.humanoid === undefined) throw new Error('`humanoid` says whose bones: true, or the build it was given');- const joints: RigJoint[] = resolveJoints({ joints: humanoidJoints(p.humanoid === true ? {} : p.humanoid) });- const names = new Set(joints.map((j) => j.name));- const known = (name: string): void => {- if (!names.has(name)) throw new Error(`no joint "${name}"; there are ${[...names].join(', ')}`);- };- const tracks = new Map<string, { rotate?: number[][]; move?: number[][]; reach?: number[][]; pole?: readonly number[] }>();- for (const [name, r] of Object.entries(p.rotate ?? {})) {- known(name);- if (r.length !== 3) throw new Error(`rotate of "${name}" must be [x, y, z] degrees`);- tracks.set(name, { rotate: [[0, r[0]!, r[1]!, r[2]!]] });- }- for (const [name, m] of Object.entries(p.move ?? {})) {- known(name);- if (m.length !== 3) throw new Error(`move of "${name}" must be [x, y, z]`);- tracks.set(name, { ...tracks.get(name), move: [[0, m[0]!, m[1]!, m[2]!]] });- }- for (const [name, r] of Object.entries(p.reach ?? {})) {- known(name);- if (r.at?.length !== 3) throw new Error(`reach of "${name}" needs at: [x, y, z]`);- tracks.set(name, { ...tracks.get(name), reach: [[0, r.at[0]!, r.at[1]!, r.at[2]!]], ...(r.pole ? { pole: r.pole } : {}) });- }- return { joints, animation: { name: 'pose', duration: 1, loop: false, tracks: [...tracks].map(([joint, t]) => ({ joint, ...t })) as AnimationTrack[] } };-}--/** Where each joint is in a pose, without the seconds a surface takes. */-export function poseJoints(p: PoseParams): Record<string, Vec3> {- const { joints, animation } = poseClip(p);- 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 { poseJoints, poseFrames, type PoseParams } from '../../../sdk/src/image/figureSkeleton';+import { compact, type PolyMesh } from './polyMesh';+import { computeWornWeights, posedPositions, type SkinWeights } from './rig';export function poseStep(mesh: PolyMesh, p: PoseParams): PolyMesh {const { joints, animation } = poseClip(p);diff --git a/pipeline/src/modeling/rig.ts b/pipeline/src/modeling/rig.tsindex c1a9d714d..3f7929ae9 100644--- a/pipeline/src/modeling/rig.ts+++ b/pipeline/src/modeling/rig.ts@@ -9,21 +9,15 @@* whether one should drag the other.*/import { ANIMATOR_FORMAT_VERSION, PREFAB_FORMAT_VERSION, TIMELINE_FORMAT_VERSION } from 'esengine';+import { MAX_RIG_JOINTS, resolveJoints, jointPositions, jointFrames, poseAt, rotateBy, sample, type Quat, type RigJointSource, type AnimationTrack, type AnimationSource, type RigJoint, type PoseSolve, type PreviewGround, type RigGoal, type ControllerIk } from '../../../sdk/src/image/figureSkeleton';import { add, boundsOf, cross, dot, length, normalize, scale, selectFaces, sub, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';-export const MAX_RIG_JOINTS = 256;-const DEG = Math.PI / 180;const SAMPLE_RATE = 30;-export interface RigJointSource {- name: string;- at: Vec3;- parent?: string;- /** Also exists reflected across this axis: `arm` becomes `arm.L` on the positive side and `arm.R` on the other. */- mirror?: 'x' | 'y' | 'z';-}-/** Sets how much one joint moves some of the surface, where the weights found are wrong. Later ones win. */+export { MAX_RIG_JOINTS, resolveJoints, jointPositions, jointFrames };+export type { RigJointSource, AnimationTrack, AnimationSource, RigJoint, PoseSolve, PreviewGround, RigGoal, ControllerIk };+export interface WeightAdjust {joint: string;/** 0 frees the surface of this joint, 1 binds it wholly. */@@ -35,12 +29,6 @@ export interface WeightAdjust {}/** An entity in the rig that bends nothing: what an IK constraint reaches for or looks at, moved by a game. */-export interface RigGoal {- name: string;- at: Vec3;- parent?: string;-}-export interface RigSource {/** Hanging parts, as chains that swing. */drape?: DrapeSource[];@@ -53,94 +41,6 @@ export interface RigSource {goals?: readonly RigGoal[];}-export interface AnimationTrack {- joint: string;- /** [time, x, y, z] in degrees, X then Y then Z, from the bind pose. */- rotate?: readonly (readonly number[])[];- /** [time, x, y, z] from where the joint rests. */- move?: readonly (readonly number[])[];- /**- * [time, x, y, z] where this joint must be, in the model's own space: the foot of a two-bone limb,- * whose parent and grandparent turn to put it there. `rotate` on the same track then holds it at- * that orientation in the model's space, and left out it stays level with the ground.- */- reach?: readonly (readonly number[])[];- /** The way the middle joint of a `reach` bends: forward for a knee, back for an elbow. Default the way it already bends, else +Z. */- pole?: Vec3;- /** Straight lines between keys, for a foot sliding along the ground: a curve would dip through it. */- linear?: boolean;- /** Shifts the keys by this fraction of the clip: the other leg, half a stride behind. */- phase?: number;-}--export interface AnimationSource {- name: string;- duration: number;- /** Default true. */- loop?: boolean;- tracks?: readonly AnimationTrack[];- /** Weights of the model's `shapes` over the clip: a blink, a mouth. `value` is [time, weight]. */- shapes?: readonly { name: string; value: readonly (readonly number[])[]; phase?: number; linear?: boolean }[];-}--export interface RigJoint {- name: string;- at: Vec3;- parent: number;- children: number[];-}--/** Joints flattened, mirrored ones expanded, parents always before their children. */-export function resolveJoints(rig: RigSource): RigJoint[] {- const out: { name: string; at: Vec3; parentName: string | undefined }[] = [];- const mirrored = new Set(rig.joints.filter((j) => j.mirror).map((j) => j.name));- for (const j of rig.joints) {- if (!j.mirror) {- out.push({ name: j.name, at: j.at, parentName: j.parent });- continue;- }- const k = { x: 0, y: 1, z: 2 }[j.mirror];- const flip = [...j.at] as [number, number, number];- flip[k] = -flip[k];- const positive = j.at[k]! >= 0;- const side = (s: string): string | undefined => (j.parent === undefined ? undefined : mirrored.has(j.parent) ? `${j.parent}.${s}` : j.parent);- out.push({ name: `${j.name}.L`, at: positive ? j.at : flip, parentName: side('L') });- out.push({ name: `${j.name}.R`, at: positive ? flip : j.at, parentName: side('R') });- }- if (out.length === 0) throw new Error('a rig needs at least one joint');- if (out.length > MAX_RIG_JOINTS) throw new Error(`this rig has ${out.length} joints; a mesh can be posed by at most ${MAX_RIG_JOINTS}`);- const index = new Map<string, number>();- out.forEach((j, i) => {- if (index.has(j.name)) throw new Error(`there are two joints called "${j.name}"`);- index.set(j.name, i);- });- const parents = out.map((j) => {- if (j.parentName === undefined) return -1;- const p = index.get(j.parentName);- if (p === undefined) throw new Error(`joint "${j.name}" has parent "${j.parentName}", which is not a joint; there are ${out.map((o) => o.name).join(', ')}`);- return p;- });- if (parents.filter((p) => p < 0).length !== 1) {- throw new Error(`a rig has one root; these have no parent: ${out.filter((_, i) => parents[i]! < 0).map((j) => j.name).join(', ')}`);- }- // Parents first, which also proves there is no loop.- const order: number[] = [];- const placed = new Set<number>();- while (order.length < out.length) {- const before = order.length;- out.forEach((_, i) => {- if (!placed.has(i) && (parents[i]! < 0 || placed.has(parents[i]!))) { order.push(i); placed.add(i); }- });- if (order.length === before) throw new Error('the joints\' parents go round in a loop');- }- const newIndex = new Map(order.map((old, i) => [old, i]));- const joints: RigJoint[] = order.map((old) => ({- name: out[old]!.name, at: out[old]!.at, parent: parents[old]! < 0 ? -1 : newIndex.get(parents[old]!)!, children: [],- }));- joints.forEach((j, i) => { if (j.parent >= 0) joints[j.parent]!.children.push(i); });- return joints;-}-// ---- Weights --------------------------------------------------------------------function pointSegment(p: Vec3, a: Vec3, b: Vec3): number {@@ -814,253 +714,6 @@ export function checkAnimations(raw: unknown, rig: unknown, shapes?: unknown): sreturn null;}-// ---- Motion -----------------------------------------------------------------------type Quat = readonly [number, number, number, number];--const quatMul = (a: Quat, b: Quat): Quat => [- a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],- a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],- a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],- a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],-];--/** X, then Y, then Z. */-function eulerToQuat(x: number, y: number, z: number): Quat {- const axis = (i: number, deg: number): Quat => {- const h = (deg * DEG) / 2;- const q = [0, 0, 0, Math.cos(h)] as [number, number, number, number];- q[i] = Math.sin(h);- return q;- };- return quatMul(axis(2, z), quatMul(axis(1, y), axis(0, x)));-}--function rotateBy(q: Quat, v: Vec3): Vec3 {- const u: Vec3 = [q[0], q[1], q[2]];- const t = scale(cross(u, v), 2);- return add(add(v, scale(t, q[3])), cross(u, t));-}--/** A key track's value at @p time: a smooth line through the keys, passing through each exactly. */-function sample(keys: readonly (readonly number[])[], time: number, duration: number, loop: boolean, phase: number, linear = false): Vec3 {- const shifted = keys.map((k) => [k[0]! + phase * duration, k[1]!, k[2]!, k[3]!] as const);- const wrap = (t: number): number => ((t % duration) + duration) % duration;- const list = (loop ? shifted.map((k) => [wrap(k[0]), k[1], k[2], k[3]] as const) : shifted).slice().sort((a, b) => a[0] - b[0]);- const n = list.length;- if (n === 1) return [list[0]![1], list[0]![2], list[0]![3]];- if (!loop && time <= list[0]![0]) return [list[0]![1], list[0]![2], list[0]![3]];- if (!loop && time >= list[n - 1]![0]) return [list[n - 1]![1], list[n - 1]![2], list[n - 1]![3]];- const at = (i: number): readonly number[] => {- if (loop) {- const turns = Math.floor(i / n);- const k = list[((i % n) + n) % n]!;- return [k[0] + turns * duration, k[1], k[2], k[3]];- }- return list[Math.max(0, Math.min(n - 1, i))]!;- };- let i = loop ? -1 : 0;- const t = loop ? wrap(time) : time;- while (at(i + 1)[0]! <= t) i++;- const [p0, p1, p2, p3] = [at(i - 1), at(i), at(i + 1), at(i + 2)];- const span = p2[0]! - p1[0]!;- const u = span > 0 ? (t - p1[0]!) / span : 0;- if (linear) return [1, 2, 3].map((c) => p1[c]! + (p2[c]! - p1[c]!) * u) as unknown as Vec3;- const [u2, u3] = [u * u, u * u * u];- const v = [1, 2, 3].map((c) => {- const [a, b] = [p1[c]!, p2[c]!];- const m1 = ((b - p0[c]!) / Math.max(p2[0]! - p0[0]!, 1e-6)) * span;- const m2 = ((p3[c]! - a) / Math.max(p3[0]! - p1[0]!, 1e-6)) * span;- return (2 * u3 - 3 * u2 + 1) * a + (u3 - 2 * u2 + u) * m1 + (-2 * u3 + 3 * u2) * b + (u3 - u2) * m2;- });- return v as unknown as Vec3;-}--const conjugate = (q: Quat): Quat => [-q[0], -q[1], -q[2], q[3]];--/** The shortest rotation taking direction @p from onto @p to. */-function rotationBetween(from: Vec3, to: Vec3): Quat {- const a = normalize(from), b = normalize(to);- const d = dot(a, b);- if (d > 1 - 1e-9) return [0, 0, 0, 1];- if (d < -1 + 1e-9) {- const side = normalize(cross(a, Math.abs(a[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]));- return [side[0], side[1], side[2], 0];- }- const c = cross(a, b);- const w = 1 + d;- const len = Math.hypot(c[0], c[1], c[2], w);- return [c[0] / len, c[1] / len, c[2] / len, w / len];-}--interface Pose {- /** Relative to the parent: what a clip writes. */- local: { q: Quat; offset: Vec3 }[];- /** In the model's space: what skinning reads. */- world: { q: Quat; origin: Vec3 }[];-}--function toWorld(joints: readonly RigJoint[], local: Pose['local']): Pose['world'] {- const world: Pose['world'] = [];- joints.forEach((j, i) => {- const l = local[i]!;- if (j.parent < 0) world[i] = { q: l.q, origin: l.offset };- else {- const p = world[j.parent]!;- world[i] = { q: quatMul(p.q, l.q), origin: add(p.origin, rotateBy(p.q, l.offset)) };- }- });- return world;-}--/** Each joint at @p time, with every `reach` solved; the bind pose with no animation. */-function poseAt(joints: readonly RigJoint[], animation: AnimationSource | null, time: number, solve?: PoseSolve): Pose {- const loop = animation?.loop !== false;- const at = (keys: readonly (readonly number[])[], t: AnimationTrack): Vec3 => sample(keys, time, animation!.duration, loop, t.phase ?? 0, t.linear === true);- const local: Pose['local'] = joints.map((j) => {- const track = animation?.tracks?.find((t) => t.joint === j.name);- const euler = track?.rotate && !track.reach ? at(track.rotate, track) : [0, 0, 0] as Vec3;- const moved = track?.move ? at(track.move, track) : [0, 0, 0] as Vec3;- const rest = j.parent >= 0 ? sub(j.at, joints[j.parent]!.at) : j.at;- return { q: eulerToQuat(euler[0], euler[1], euler[2]), offset: add(rest, moved) };- });- let world = toWorld(joints, local);- for (const track of animation?.tracks ?? []) {- if (!track.reach) continue;- const foot = joints.findIndex((j) => j.name === track.joint);- const held = track.rotate ? at(track.rotate, track) : [0, 0, 0] as Vec3;- world = bendLimb(joints, local, world, foot, at(track.reach, track), track.pole, eulerToQuat(held[0], held[1], held[2]));- }- if (solve) world = applyConstraints(joints, local, world, solve);- return { local, world };-}--/**- * The two bones above @p foot turned to put it on @p target, leaving `local` changed and answering the world it makes.- * @p footWorld holds the foot at that orientation; left out it goes on as the clip had it, carried by the turn.- */-function bendLimb(joints: readonly RigJoint[], local: Pose['local'], world: Pose['world'], foot: number, target: Vec3, pole: Vec3 | undefined, footWorld?: Quat): Pose['world'] {- const lower = joints[foot]!.parent, upper = joints[lower]!.parent, above = joints[upper]!.parent;- const a = world[upper]!.origin, b = world[lower]!.origin, c = world[foot]!.origin;- const upperLen = length(sub(joints[lower]!.at, joints[upper]!.at)), lowerLen = length(sub(joints[foot]!.at, joints[lower]!.at));- const toTarget = sub(target, a);- const near = Math.abs(upperLen - lowerLen) + 1e-4, far = upperLen + lowerLen - 1e-4;- // Out of reach it stretches straight toward the target; the report cannot say so per frame, the strip shows it.- const span = Math.max(near, Math.min(far, length(toTarget)));- const along = normalize(toTarget);- const bent = sub(b, add(a, scale(along, dot(sub(b, a), along))));- const hint = pole ?? (length(bent) > upperLen * 0.01 ? bent : [0, 0, 1] as Vec3);- let side = sub(hint, scale(along, dot(hint, along)));- if (length(side) < 1e-6) side = sub([1, 0, 0], scale(along, along[0]));- const toKnee = (upperLen * upperLen - lowerLen * lowerLen + span * span) / (2 * span);- const out = Math.sqrt(Math.max(0, upperLen * upperLen - toKnee * toKnee));- const knee = add(add(a, scale(along, toKnee)), scale(normalize(side), out));- const end = add(a, scale(along, span));- const turn = rotationBetween(sub(b, a), sub(knee, a));- const upperWorld = quatMul(turn, world[upper]!.q);- // Where the foot would now be, carried by the upper bone, is what the lower bone turns from.- const lowerWorld = quatMul(rotationBetween(rotateBy(turn, sub(c, b)), sub(end, knee)), quatMul(turn, world[lower]!.q));- const parentWorld = above >= 0 ? world[above]!.q : [0, 0, 0, 1] as Quat;- const keptFoot = footWorld ?? quatMul(conjugate(world[lower]!.q), world[foot]!.q);- local[upper] = { ...local[upper]!, q: quatMul(conjugate(parentWorld), upperWorld) };- local[lower] = { ...local[lower]!, q: quatMul(conjugate(upperWorld), lowerWorld) };- local[foot] = { ...local[foot]!, q: footWorld ? quatMul(conjugate(lowerWorld), keptFoot) : local[foot]!.q };- return toWorld(joints, local);-}--/** A flat test ground for a preview: `height` at the rig's origin, rising by `slope` per unit of x and z. */-export interface PreviewGround {- height?: number;- slope?: readonly [number, number];-}--/** What the game does on top of the clips, for a preview: the controller's constraints, and the ground its foot-plants stand on. */-export interface PoseSolve {- ik: readonly ControllerIk[];- goals: readonly RigGoal[];- /** Foot-plants do nothing without one: the game asks physics, and here there is none. */- ground?: PreviewGround;-}--const MAX_FOOT_TILT = Math.PI / 4;--/** The engine's constraint pass, on the CPU: foot-plants first and together, the rest in order. Mirrors sdk/src/animation/animatorIK.ts. */-function applyConstraints(joints: readonly RigJoint[], local: Pose['local'], start: Pose['world'], solve: PoseSolve): Pose['world'] {- let world = start;- const index = (name: string | undefined): number => (name === undefined ? -1 : joints.findIndex((j) => j.name === name));- const placeOf = (name: string | undefined): Vec3 | null => {- if (name === undefined) return null;- const j = index(name);- if (j >= 0) return world[j]!.origin;- const goal = solve.goals.find((g) => g.name === name);- if (!goal) return null;- const parent = index(goal.parent);- if (parent < 0) return goal.at;- return add(world[parent]!.origin, rotateBy(world[parent]!.q, sub(goal.at, joints[parent]!.at)));- };- if (solve.ground) {- const height = solve.ground.height ?? 0;- const [sx, sz] = solve.ground.slope ?? [0, 0];- const normal = normalize([-sx, 1, -sz]);- const feet = solve.ik.filter((k) => k.kind === 'foot-plant').map((k) => {- const foot = index(k.tip);- const at_ = world[foot]!.origin;- return { k, foot, at: at_, q: world[foot]!.q, lift: height + sx * at_[0] + sz * at_[2] };- });- const drops = new Map<string, number>();- for (const f of feet) if (f.k.pelvis) drops.set(f.k.pelvis, Math.min(drops.get(f.k.pelvis) ?? 0, f.lift * (f.k.weight ?? 1)));- for (const [name, drop] of drops) {- if (drop >= 0) continue;- const p = index(name);- const parent = joints[p]!.parent;- const inParent = parent >= 0 ? rotateBy(conjugate(world[parent]!.q), [0, drop, 0]) : [0, drop, 0] as Vec3;- local[p] = { ...local[p]!, offset: add(local[p]!.offset, inParent) };- }- if (drops.size) world = toWorld(joints, local);- const tilt = Math.acos(Math.min(1, normal[1]));- const limited = tilt > MAX_FOOT_TILT ? normalize(add(scale([0, 1, 0], Math.sin(tilt - MAX_FOOT_TILT)), scale(normal, Math.sin(MAX_FOOT_TILT)))) : normal;- for (const f of feet) {- const weight = Math.min(1, Math.max(0, f.k.weight ?? 1));- const goal: Vec3 = [f.at[0], f.at[1] + f.lift * weight, f.at[2]];- const aligned = f.k.align === false ? undefined : quatMul(rotationBetween([0, 1, 0], limited), f.q);- world = bendLimb(joints, local, world, f.foot, goal, placeOf(f.k.pole) ?? undefined, aligned);- }- }- for (const k of solve.ik) {- if (k.kind === 'foot-plant') continue;- const tip = index(k.tip);- const target = placeOf(k.target);- if (tip < 0 || !target) continue;- if (k.kind === 'two-bone') {- const pole = placeOf(k.pole);- world = bendLimb(joints, local, world, tip, target, pole ? sub(pole, world[joints[joints[tip]!.parent]!.parent]!.origin) : undefined);- } else {- const axis: Vec3 = k.axis === 'x' ? [1, 0, 0] : k.axis === 'y' ? [0, 1, 0] : [0, 0, 1];- const facing = rotateBy(world[tip]!.q, axis);- const wanted = quatMul(rotationBetween(facing, sub(target, world[tip]!.origin)), world[tip]!.q);- const parent = joints[tip]!.parent;- local[tip] = { ...local[tip]!, q: quatMul(conjugate(parent >= 0 ? world[parent]!.q : [0, 0, 0, 1]), wanted) };- world = toWorld(joints, local);- }- }- return world;-}--/** Where each joint is in a pose: for checking a foot landed. */-export function jointPositions(joints: readonly RigJoint[], animation: AnimationSource | null, time: number, solve?: PoseSolve): Record<string, Vec3> {- const { world } = poseAt(joints, animation, time, solve);- return 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;@@ -1256,29 +909,6 @@ export interface ControllerSource {ik?: readonly ControllerIk[];}-export interface ControllerIk {- kind: 'two-bone' | 'look-at' | 'foot-plant';- /** The joint the chain ends at. */- tip: string;- /** A joint or a rig goal it reaches or looks at. A foot-plant has none: the ground is its target. */- target?: string;- /** foot-plant: the joint lowered so the leg can reach the lower foot. */- pelvis?: string;- /** foot-plant: lay the foot along the slope. Default true. */- align?: boolean;- /** foot-plant: how far up and down to look for ground, in the model's units. */- reach?: number;- /** foot-plant: seconds to settle on a new height. */- smooth?: number;- /** foot-plant: the physics layers that count as ground. */- layers?: number;- pole?: string;- weight?: number;- /** A float parameter scaling the weight, to fade it in. */- parameter?: string;- /** look-at: which of the tip's own axes points at the target. */- axis?: 'x' | 'y' | 'z';-}/** What is wrong with a source's `controller`, or null. */export function checkController(raw: unknown, animations: unknown, rig?: RigSource): string | null {diff --git a/sdk/etc/image.api.md b/sdk/etc/image.api.mdindex 4e8988504..e8431ed7e 100644--- a/sdk/etc/image.api.md+++ b/sdk/etc/image.api.md@@ -1,7 +1,7 @@# API surface — esengine/image<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 0 beta · 16 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 22 experimental · 0 deprecated## FlatFigure — interface @experimental```@@ -29,11 +29,6 @@ parts: Record<string, Float32Array<ArrayBufferLike>>1```-## ImageFigureDrawer — interface @experimental-```-flatten: (layer: ImageLayer, w: number, h: number, project: (p: readonly [number, number]) => readonly [number, number], scale: number) => FlatFigure-```-## ImageLayer — interface @experimental```adjust: ImageAdjust | undefined@@ -109,6 +104,13 @@ y: number | undefinedyaw: number | undefined```+## ImageMapSource — interface @experimental+```+map: "normal" | "surface"+mapOf: string+version: number | undefined+```+## ImageMaterial — interface @experimental```height: readonly ImageLayer[] | undefined@@ -147,6 +149,16 @@ roughness: numbersurface: RgbaBitmap | null```+## RECIPE_MAPS — const @experimental+```+readonly ["normal", "surface"]+```++## RecipeMap — type @experimental+```+(typeof RECIPE_MAPS)[number]+```+## RenderedImage — interface @experimental```blocks: Record<string, Record<string, readonly (readonly number[])[]>>@@ -168,9 +180,29 @@ rgba: Uint8Array<ArrayBufferLike>width: number```+## canvasTextDrawer — function @experimental+```+(canvas: (w: number, h: number) => TextCanvas, familyOf: (font: string) => string | undefined): ImageTextDrawer+```++## installTextureRecipes — function @experimental+```+(): void+```++## parseRecipe — function @experimental+```+(text: string): Recipe+```++## recipeNeeds — function @experimental+```+(text: string): string[]+```+## renderImage — function @experimental```-(source: ImageSource, options?: { guides?: boolean; pictures?: Readonly<Record<string, RgbaBitmap>>; text?: ImageTextDrawer; figure?: ImageFigureDrawer; }): RenderedImage+(source: ImageSource, options?: { guides?: boolean; pictures?: Readonly<Record<string, RgbaBitmap>>; text?: ImageTextDrawer; }): RenderedImage```## renderMaterialMaps — function @experimentaldiff --git a/sdk/src/asset/loaders/TextureLoader.ts b/sdk/src/asset/loaders/TextureLoader.tsindex 680fcc36a..6229df2e5 100644--- a/sdk/src/asset/loaders/TextureLoader.ts+++ b/sdk/src/asset/loaders/TextureLoader.ts@@ -306,7 +306,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {this.lastDecision_ = RAW_PAYLOAD_UPLOAD;// A recipe is drawn here, from its source, and is then a texture like any decoded one.if (isTextureRecipePath(buildPath)) {- const drawn = await renderTextureRecipe(await ctx.backend.fetchText(buildPath), path);+ const drawn = await renderTextureRecipe(path, (p) => ctx.backend.fetchBinary(p === path ? buildPath : ctx.catalog?.getBuildPath(p) ?? p));const handle = createTextureFromPixels(this.module_, drawn, TextureContent.Asset, flip, pixelParams(settings));return { handle, width: drawn.width, height: drawn.height };}diff --git a/sdk/src/asset/textureRecipe.ts b/sdk/src/asset/textureRecipe.tsindex d6f92d8d2..1663948cc 100644--- a/sdk/src/asset/textureRecipe.ts+++ b/sdk/src/asset/textureRecipe.ts@@ -5,22 +5,33 @@* @brief A texture that is a recipe: a picture's source (an `.esimage`) shipped in place of its pixels and drawn where it is loaded.** @details A package that ships a picture ships every pixel of it; one that ships how the picture is drawn ships a few hundred bytes- * and pays for the drawing once, on the device. The texture loader asks here for any path that is a recipe. What draws- * one is not in the core: importing `esengine/image` installs it, so a game with no recipe does not carry the raster.+ * and pays for the drawing once, on the device. Whoever reads an image (the texture loader, a ground reading its layers)+ * asks here for any path that is a recipe. What draws one is not in the core: importing `esengine/image` installs it, so a+ * game with no recipe does not carry the raster.*- * A drawn picture is kept in the platform's content cache under what it was drawn from (the source's own hash and the- * drawer's revision), so the next run reads it back and draws nothing. The key says what the bytes are, as every key of- * that cache does: a source that changes is another key, and so is a drawer that draws differently.+ * A recipe may need other files of the project: a picture it lays in, a font, the recipe it is a map of. The drawer says+ * which, they are read here, and a drawn picture is kept in the platform's content cache under all it was drawn from: the+ * source, those files' own bytes, and the drawer's revision. A change in any of them is another key.*/import { contentHashHex } from './contentHash';import { platformReadCacheFile, platformWriteCacheFile } from '../platform';-import { encodeUtf8 } from '../util/utf8';+import { decodeUtf8, encodeUtf8 } from '../util/utf8';/** The pixels a recipe draws: top row first, RGBA, as a decoded image is. */export interface RecipePixels { width: number; height: number; pixels: Uint8Array }-/** Draws a recipe from its source text. */-export type TextureRecipeRenderer = (source: string, path: string) => RecipePixels | Promise<RecipePixels>;+/** Reads a file of the project by its project path, as the asset layer would. */+export type RecipeFileReader = (path: string) => Promise<ArrayBuffer>;++/** What draws recipes. */+export interface TextureRecipeDrawer {+ /** How it draws, as a name: it changes whenever the same source would come out as other pixels. */+ revision: string;+ /** The project files a source needs beside itself, by project path. */+ needs(source: string): readonly string[];+ /** The picture of a source, with every file it needs (and those the recipes among them need) to hand. */+ draw(source: string, files: ReadonlyMap<string, ArrayBuffer>, path: string): RecipePixels | Promise<RecipePixels>;+}/** What recipes have cost since the game began (or since the counts were last cleared). */export interface TextureRecipeStats {@@ -34,8 +45,7 @@ export interface TextureRecipeStats {const RECIPE_EXTENSION = '.esimage';/** A kept picture's bytes: two sizes, then its pixels. */const KEPT_HEADER = 8;-let renderer: TextureRecipeRenderer | null = null;-let revision = '';+let drawer: TextureRecipeDrawer | null = null;const stats: TextureRecipeStats = { drawn: 0, drawMs: 0, reused: 0 };/** Whether a texture's path names a recipe and not an image. */@@ -44,17 +54,13 @@ export function isTextureRecipePath(path: string): boolean {return (end < 0 ? path : path.slice(0, end)).toLowerCase().endsWith(RECIPE_EXTENSION);}-/**- * Installs what draws recipes (null takes it out again). `esengine/image` does this on import. `drawerRevision` names how it draws:- * it changes whenever the same source would come out as other pixels, and a picture kept under another revision is not read.- */-export function setTextureRecipeRenderer(next: TextureRecipeRenderer | null, drawerRevision = ''): void {- renderer = next;- revision = drawerRevision;+/** Installs what draws recipes (null takes it out again). `esengine/image` does this on import. */+export function setTextureRecipeDrawer(next: TextureRecipeDrawer | null): void {+ drawer = next;}-export function hasTextureRecipeRenderer(): boolean {- return renderer !== null;+export function hasTextureRecipeDrawer(): boolean {+ return drawer !== null;}/** The counts so far; `clear` starts them again. */@@ -64,9 +70,10 @@ export function textureRecipeStats(clear = false): TextureRecipeStats {return now;}-/** The content cache's key for a recipe: the drawer's revision and the source's own hash. */-export function textureRecipeCacheKey(source: string, drawerRevision = revision): string {- return `estella:texture-recipe:${drawerRevision}:${contentHashHex(encodeUtf8(source))}`;+/** The content cache's key for a recipe: the drawer's revision, and the hash of the source with the files it was drawn from. */+export function textureRecipeCacheKey(source: string, files: ReadonlyMap<string, ArrayBuffer> = new Map(), revision = drawer?.revision ?? ''): string {+ const from = [...files.keys()].sort().map((path) => `\n${path}:${contentHashHex(new Uint8Array(files.get(path)!))}`).join('');+ return `estella:texture-recipe:${revision}:${contentHashHex(encodeUtf8(source + from))}`;}function unpack(bytes: ArrayBuffer): RecipePixels | null {@@ -87,15 +94,30 @@ function pack(drawn: RecipePixels): ArrayBuffer {return bytes;}-/** The pixels of the recipe at `path`, whose source is `source`: read back where an earlier run drew them, drawn and kept otherwise. */-export async function renderTextureRecipe(source: string, path: string): Promise<RecipePixels> {- if (!renderer) throw new Error(`texture "${path}" is a recipe, and nothing here draws recipes: import 'esengine/image' where the game starts`);- const key = textureRecipeCacheKey(source);+/** Reads what `source` needs into `files`, and what the recipes among those need, each file once. */+async function gather(by: TextureRecipeDrawer, source: string, read: RecipeFileReader, files: Map<string, ArrayBuffer>, root: string): Promise<void> {+ for (const need of by.needs(source)) {+ if (need === root) throw new Error(`recipe "${root}" needs itself`);+ if (files.has(need)) continue;+ const bytes = await read(need);+ files.set(need, bytes);+ if (isTextureRecipePath(need)) await gather(by, decodeUtf8(new Uint8Array(bytes)), read, files, root);+ }+}++/** The pixels of the recipe at `path`: read back where an earlier run drew them, drawn and kept otherwise. */+export async function renderTextureRecipe(path: string, read: RecipeFileReader): Promise<RecipePixels> {+ const by = drawer;+ if (!by) throw new Error(`texture "${path}" is a recipe, and nothing here draws recipes: import 'esengine/image' where the game starts`);+ const source = decodeUtf8(new Uint8Array(await read(path)));+ const files = new Map<string, ArrayBuffer>();+ await gather(by, source, read, files, path);+ const key = textureRecipeCacheKey(source, files, by.revision);const kept = await platformReadCacheFile(key);- const read = kept ? unpack(kept) : null;- if (read) { stats.reused++; return read; }+ const got = kept ? unpack(kept) : null;+ if (got) { stats.reused++; return got; }const began = Date.now();- const drawn = await renderer(source, path);+ const drawn = await by.draw(source, files, path);stats.drawn++;stats.drawMs += Date.now() - began;// Kept for the next run without holding this one up; a platform with no cache, or a full one, only means it is drawn again.diff --git a/sdk/src/image/figureSkeleton.ts b/sdk/src/image/figureSkeleton.tsnew file mode 100644index 000000000..782e51101--- /dev/null+++ b/sdk/src/image/figureSkeleton.ts@@ -0,0 +1,571 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file figureSkeleton.ts+ * @brief The bones of a humanoid and a pose of them: where each joint is and which way it has turned, for a figure layer to draw on.+ *+ * @details The authoring pipeline builds, skins and animates whole models on these same bones (pipeline/src/modeling reads them from+ * here), so a figure drawn in a picture stands as the model it is a sketch of does. Nothing here knows a surface.+ */++export type Vec3 = readonly [number, number, number];++const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];+const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+const scale = (a: Vec3, s: number): Vec3 => [a[0] * s, a[1] * s, a[2] * s];+const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+const cross = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+const length = (a: Vec3): number => Math.hypot(a[0], a[1], a[2]);+const normalize = (a: Vec3): Vec3 => {+ const l = length(a);+ return l > 0 ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 0];+};++export const MAX_RIG_JOINTS = 256;+const DEG = Math.PI / 180;++// ---- Joints ---------------------------------------------------------------------++export interface RigJointSource {+ name: string;+ at: Vec3;+ parent?: string;+ /** Also exists reflected across this axis: `arm` becomes `arm.L` on the positive side and `arm.R` on the other. */+ mirror?: 'x' | 'y' | 'z';+}++export interface AnimationTrack {+ joint: string;+ /** [time, x, y, z] in degrees, X then Y then Z, from the bind pose. */+ rotate?: readonly (readonly number[])[];+ /** [time, x, y, z] from where the joint rests. */+ move?: readonly (readonly number[])[];+ /**+ * [time, x, y, z] where this joint must be, in the model's own space: the foot of a two-bone limb,+ * whose parent and grandparent turn to put it there. `rotate` on the same track then holds it at+ * that orientation in the model's space, and left out it stays level with the ground.+ */+ reach?: readonly (readonly number[])[];+ /** The way the middle joint of a `reach` bends: forward for a knee, back for an elbow. Default the way it already bends, else +Z. */+ pole?: Vec3;+ /** Straight lines between keys, for a foot sliding along the ground: a curve would dip through it. */+ linear?: boolean;+ /** Shifts the keys by this fraction of the clip: the other leg, half a stride behind. */+ phase?: number;+}++export interface AnimationSource {+ name: string;+ duration: number;+ /** Default true. */+ loop?: boolean;+ tracks?: readonly AnimationTrack[];+ /** Weights of the model's `shapes` over the clip: a blink, a mouth. `value` is [time, weight]. */+ shapes?: readonly { name: string; value: readonly (readonly number[])[]; phase?: number; linear?: boolean }[];+}++export interface RigJoint {+ name: string;+ at: Vec3;+ parent: number;+ children: number[];+}++/** Joints flattened, mirrored ones expanded, parents always before their children. */+export function resolveJoints(rig: { joints: readonly RigJointSource[] }): RigJoint[] {+ const out: { name: string; at: Vec3; parentName: string | undefined }[] = [];+ const mirrored = new Set(rig.joints.filter((j) => j.mirror).map((j) => j.name));+ for (const j of rig.joints) {+ if (!j.mirror) {+ out.push({ name: j.name, at: j.at, parentName: j.parent });+ continue;+ }+ const k = { x: 0, y: 1, z: 2 }[j.mirror];+ const flip = [...j.at] as [number, number, number];+ flip[k] = -flip[k];+ const positive = j.at[k]! >= 0;+ const side = (s: string): string | undefined => (j.parent === undefined ? undefined : mirrored.has(j.parent) ? `${j.parent}.${s}` : j.parent);+ out.push({ name: `${j.name}.L`, at: positive ? j.at : flip, parentName: side('L') });+ out.push({ name: `${j.name}.R`, at: positive ? flip : j.at, parentName: side('R') });+ }+ if (out.length === 0) throw new Error('a rig needs at least one joint');+ if (out.length > MAX_RIG_JOINTS) throw new Error(`this rig has ${out.length} joints; a mesh can be posed by at most ${MAX_RIG_JOINTS}`);+ const index = new Map<string, number>();+ out.forEach((j, i) => {+ if (index.has(j.name)) throw new Error(`there are two joints called "${j.name}"`);+ index.set(j.name, i);+ });+ const parents = out.map((j) => {+ if (j.parentName === undefined) return -1;+ const p = index.get(j.parentName);+ if (p === undefined) throw new Error(`joint "${j.name}" has parent "${j.parentName}", which is not a joint; there are ${out.map((o) => o.name).join(', ')}`);+ return p;+ });+ if (parents.filter((p) => p < 0).length !== 1) {+ throw new Error(`a rig has one root; these have no parent: ${out.filter((_, i) => parents[i]! < 0).map((j) => j.name).join(', ')}`);+ }+ // Parents first, which also proves there is no loop.+ const order: number[] = [];+ const placed = new Set<number>();+ while (order.length < out.length) {+ const before = order.length;+ out.forEach((_, i) => {+ if (!placed.has(i) && (parents[i]! < 0 || placed.has(parents[i]!))) { order.push(i); placed.add(i); }+ });+ if (order.length === before) throw new Error('the joints\' parents go round in a loop');+ }+ const newIndex = new Map(order.map((old, i) => [old, i]));+ const joints: RigJoint[] = order.map((old) => ({+ name: out[old]!.name, at: out[old]!.at, parent: parents[old]! < 0 ? -1 : newIndex.get(parents[old]!)!, children: [],+ }));+ joints.forEach((j, i) => { if (j.parent >= 0) joints[j.parent]!.children.push(i); });+ return joints;+}++// ---- Motion ---------------------------------------------------------------------++export type Quat = readonly [number, number, number, number];++export const quatMul = (a: Quat, b: Quat): Quat => [+ a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],+ a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],+ a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],+ a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],+];++/** X, then Y, then Z. */+export function eulerToQuat(x: number, y: number, z: number): Quat {+ const axis = (i: number, deg: number): Quat => {+ const h = (deg * DEG) / 2;+ const q = [0, 0, 0, Math.cos(h)] as [number, number, number, number];+ q[i] = Math.sin(h);+ return q;+ };+ return quatMul(axis(2, z), quatMul(axis(1, y), axis(0, x)));+}++export function rotateBy(q: Quat, v: Vec3): Vec3 {+ const u: Vec3 = [q[0], q[1], q[2]];+ const t = scale(cross(u, v), 2);+ return add(add(v, scale(t, q[3])), cross(u, t));+}++/** A key track's value at @p time: a smooth line through the keys, passing through each exactly. */+export function sample(keys: readonly (readonly number[])[], time: number, duration: number, loop: boolean, phase: number, linear = false): Vec3 {+ const shifted = keys.map((k) => [k[0]! + phase * duration, k[1]!, k[2]!, k[3]!] as const);+ const wrap = (t: number): number => ((t % duration) + duration) % duration;+ const list = (loop ? shifted.map((k) => [wrap(k[0]), k[1], k[2], k[3]] as const) : shifted).slice().sort((a, b) => a[0] - b[0]);+ const n = list.length;+ if (n === 1) return [list[0]![1], list[0]![2], list[0]![3]];+ if (!loop && time <= list[0]![0]) return [list[0]![1], list[0]![2], list[0]![3]];+ if (!loop && time >= list[n - 1]![0]) return [list[n - 1]![1], list[n - 1]![2], list[n - 1]![3]];+ const at = (i: number): readonly number[] => {+ if (loop) {+ const turns = Math.floor(i / n);+ const k = list[((i % n) + n) % n]!;+ return [k[0] + turns * duration, k[1], k[2], k[3]];+ }+ return list[Math.max(0, Math.min(n - 1, i))]!;+ };+ let i = loop ? -1 : 0;+ const t = loop ? wrap(time) : time;+ while (at(i + 1)[0]! <= t) i++;+ const [p0, p1, p2, p3] = [at(i - 1), at(i), at(i + 1), at(i + 2)];+ const span = p2[0]! - p1[0]!;+ const u = span > 0 ? (t - p1[0]!) / span : 0;+ if (linear) return [1, 2, 3].map((c) => p1[c]! + (p2[c]! - p1[c]!) * u) as unknown as Vec3;+ const [u2, u3] = [u * u, u * u * u];+ const v = [1, 2, 3].map((c) => {+ const [a, b] = [p1[c]!, p2[c]!];+ const m1 = ((b - p0[c]!) / Math.max(p2[0]! - p0[0]!, 1e-6)) * span;+ const m2 = ((p3[c]! - a) / Math.max(p3[0]! - p1[0]!, 1e-6)) * span;+ return (2 * u3 - 3 * u2 + 1) * a + (u3 - 2 * u2 + u) * m1 + (-2 * u3 + 3 * u2) * b + (u3 - u2) * m2;+ });+ return v as unknown as Vec3;+}++export const conjugate = (q: Quat): Quat => [-q[0], -q[1], -q[2], q[3]];++/** The shortest rotation taking direction @p from onto @p to. */+export function rotationBetween(from: Vec3, to: Vec3): Quat {+ const a = normalize(from), b = normalize(to);+ const d = dot(a, b);+ if (d > 1 - 1e-9) return [0, 0, 0, 1];+ if (d < -1 + 1e-9) {+ const side = normalize(cross(a, Math.abs(a[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]));+ return [side[0], side[1], side[2], 0];+ }+ const c = cross(a, b);+ const w = 1 + d;+ const len = Math.hypot(c[0], c[1], c[2], w);+ return [c[0] / len, c[1] / len, c[2] / len, w / len];+}++export interface Pose {+ /** Relative to the parent: what a clip writes. */+ local: { q: Quat; offset: Vec3 }[];+ /** In the model's space: what skinning reads. */+ world: { q: Quat; origin: Vec3 }[];+}++export function toWorld(joints: readonly RigJoint[], local: Pose['local']): Pose['world'] {+ const world: Pose['world'] = [];+ joints.forEach((j, i) => {+ const l = local[i]!;+ if (j.parent < 0) world[i] = { q: l.q, origin: l.offset };+ else {+ const p = world[j.parent]!;+ world[i] = { q: quatMul(p.q, l.q), origin: add(p.origin, rotateBy(p.q, l.offset)) };+ }+ });+ return world;+}++/** Each joint at @p time, with every `reach` solved; the bind pose with no animation. */+export function poseAt(joints: readonly RigJoint[], animation: AnimationSource | null, time: number, solve?: PoseSolve): Pose {+ const loop = animation?.loop !== false;+ const at = (keys: readonly (readonly number[])[], t: AnimationTrack): Vec3 => sample(keys, time, animation!.duration, loop, t.phase ?? 0, t.linear === true);+ const local: Pose['local'] = joints.map((j) => {+ const track = animation?.tracks?.find((t) => t.joint === j.name);+ const euler = track?.rotate && !track.reach ? at(track.rotate, track) : [0, 0, 0] as Vec3;+ const moved = track?.move ? at(track.move, track) : [0, 0, 0] as Vec3;+ const rest = j.parent >= 0 ? sub(j.at, joints[j.parent]!.at) : j.at;+ return { q: eulerToQuat(euler[0], euler[1], euler[2]), offset: add(rest, moved) };+ });+ let world = toWorld(joints, local);+ for (const track of animation?.tracks ?? []) {+ if (!track.reach) continue;+ const foot = joints.findIndex((j) => j.name === track.joint);+ const held = track.rotate ? at(track.rotate, track) : [0, 0, 0] as Vec3;+ world = bendLimb(joints, local, world, foot, at(track.reach, track), track.pole, eulerToQuat(held[0], held[1], held[2]));+ }+ if (solve) world = applyConstraints(joints, local, world, solve);+ return { local, world };+}++/**+ * The two bones above @p foot turned to put it on @p target, leaving `local` changed and answering the world it makes.+ * @p footWorld holds the foot at that orientation; left out it goes on as the clip had it, carried by the turn.+ */+export function bendLimb(joints: readonly RigJoint[], local: Pose['local'], world: Pose['world'], foot: number, target: Vec3, pole: Vec3 | undefined, footWorld?: Quat): Pose['world'] {+ const lower = joints[foot]!.parent, upper = joints[lower]!.parent, above = joints[upper]!.parent;+ const a = world[upper]!.origin, b = world[lower]!.origin, c = world[foot]!.origin;+ const upperLen = length(sub(joints[lower]!.at, joints[upper]!.at)), lowerLen = length(sub(joints[foot]!.at, joints[lower]!.at));+ const toTarget = sub(target, a);+ const near = Math.abs(upperLen - lowerLen) + 1e-4, far = upperLen + lowerLen - 1e-4;+ // Out of reach it stretches straight toward the target; the report cannot say so per frame, the strip shows it.+ const span = Math.max(near, Math.min(far, length(toTarget)));+ const along = normalize(toTarget);+ const bent = sub(b, add(a, scale(along, dot(sub(b, a), along))));+ const hint = pole ?? (length(bent) > upperLen * 0.01 ? bent : [0, 0, 1] as Vec3);+ let side = sub(hint, scale(along, dot(hint, along)));+ if (length(side) < 1e-6) side = sub([1, 0, 0], scale(along, along[0]));+ const toKnee = (upperLen * upperLen - lowerLen * lowerLen + span * span) / (2 * span);+ const out = Math.sqrt(Math.max(0, upperLen * upperLen - toKnee * toKnee));+ const knee = add(add(a, scale(along, toKnee)), scale(normalize(side), out));+ const end = add(a, scale(along, span));+ const turn = rotationBetween(sub(b, a), sub(knee, a));+ const upperWorld = quatMul(turn, world[upper]!.q);+ // Where the foot would now be, carried by the upper bone, is what the lower bone turns from.+ const lowerWorld = quatMul(rotationBetween(rotateBy(turn, sub(c, b)), sub(end, knee)), quatMul(turn, world[lower]!.q));+ const parentWorld = above >= 0 ? world[above]!.q : [0, 0, 0, 1] as Quat;+ const keptFoot = footWorld ?? quatMul(conjugate(world[lower]!.q), world[foot]!.q);+ local[upper] = { ...local[upper]!, q: quatMul(conjugate(parentWorld), upperWorld) };+ local[lower] = { ...local[lower]!, q: quatMul(conjugate(upperWorld), lowerWorld) };+ local[foot] = { ...local[foot]!, q: footWorld ? quatMul(conjugate(lowerWorld), keptFoot) : local[foot]!.q };+ return toWorld(joints, local);+}++/** A flat test ground for a preview: `height` at the rig's origin, rising by `slope` per unit of x and z. */+export interface PreviewGround {+ height?: number;+ slope?: readonly [number, number];+}++export interface RigGoal {+ name: string;+ at: Vec3;+ parent?: string;+}++export interface ControllerIk {+ kind: 'two-bone' | 'look-at' | 'foot-plant';+ /** The joint the chain ends at. */+ tip: string;+ /** A joint or a rig goal it reaches or looks at. A foot-plant has none: the ground is its target. */+ target?: string;+ /** foot-plant: the joint lowered so the leg can reach the lower foot. */+ pelvis?: string;+ /** foot-plant: lay the foot along the slope. Default true. */+ align?: boolean;+ /** foot-plant: how far up and down to look for ground, in the model's units. */+ reach?: number;+ /** foot-plant: seconds to settle on a new height. */+ smooth?: number;+ /** foot-plant: the physics layers that count as ground. */+ layers?: number;+ pole?: string;+ weight?: number;+ /** A float parameter scaling the weight, to fade it in. */+ parameter?: string;+ /** look-at: which of the tip's own axes points at the target. */+ axis?: 'x' | 'y' | 'z';+}++/** What the game does on top of the clips, for a preview: the controller's constraints, and the ground its foot-plants stand on. */+export interface PoseSolve {+ ik: readonly ControllerIk[];+ goals: readonly RigGoal[];+ /** Foot-plants do nothing without one: the game asks physics, and here there is none. */+ ground?: PreviewGround;+}++export const MAX_FOOT_TILT = Math.PI / 4;++/** The engine's constraint pass, on the CPU: foot-plants first and together, the rest in order. Mirrors sdk/src/animation/animatorIK.ts. */+export function applyConstraints(joints: readonly RigJoint[], local: Pose['local'], start: Pose['world'], solve: PoseSolve): Pose['world'] {+ let world = start;+ const index = (name: string | undefined): number => (name === undefined ? -1 : joints.findIndex((j) => j.name === name));+ const placeOf = (name: string | undefined): Vec3 | null => {+ if (name === undefined) return null;+ const j = index(name);+ if (j >= 0) return world[j]!.origin;+ const goal = solve.goals.find((g) => g.name === name);+ if (!goal) return null;+ const parent = index(goal.parent);+ if (parent < 0) return goal.at;+ return add(world[parent]!.origin, rotateBy(world[parent]!.q, sub(goal.at, joints[parent]!.at)));+ };+ if (solve.ground) {+ const height = solve.ground.height ?? 0;+ const [sx, sz] = solve.ground.slope ?? [0, 0];+ const normal = normalize([-sx, 1, -sz]);+ const feet = solve.ik.filter((k) => k.kind === 'foot-plant').map((k) => {+ const foot = index(k.tip);+ const at_ = world[foot]!.origin;+ return { k, foot, at: at_, q: world[foot]!.q, lift: height + sx * at_[0] + sz * at_[2] };+ });+ const drops = new Map<string, number>();+ for (const f of feet) if (f.k.pelvis) drops.set(f.k.pelvis, Math.min(drops.get(f.k.pelvis) ?? 0, f.lift * (f.k.weight ?? 1)));+ for (const [name, drop] of drops) {+ if (drop >= 0) continue;+ const p = index(name);+ const parent = joints[p]!.parent;+ const inParent = parent >= 0 ? rotateBy(conjugate(world[parent]!.q), [0, drop, 0]) : [0, drop, 0] as Vec3;+ local[p] = { ...local[p]!, offset: add(local[p]!.offset, inParent) };+ }+ if (drops.size) world = toWorld(joints, local);+ const tilt = Math.acos(Math.min(1, normal[1]));+ const limited = tilt > MAX_FOOT_TILT ? normalize(add(scale([0, 1, 0], Math.sin(tilt - MAX_FOOT_TILT)), scale(normal, Math.sin(MAX_FOOT_TILT)))) : normal;+ for (const f of feet) {+ const weight = Math.min(1, Math.max(0, f.k.weight ?? 1));+ const goal: Vec3 = [f.at[0], f.at[1] + f.lift * weight, f.at[2]];+ const aligned = f.k.align === false ? undefined : quatMul(rotationBetween([0, 1, 0], limited), f.q);+ world = bendLimb(joints, local, world, f.foot, goal, placeOf(f.k.pole) ?? undefined, aligned);+ }+ }+ for (const k of solve.ik) {+ if (k.kind === 'foot-plant') continue;+ const tip = index(k.tip);+ const target = placeOf(k.target);+ if (tip < 0 || !target) continue;+ if (k.kind === 'two-bone') {+ const pole = placeOf(k.pole);+ world = bendLimb(joints, local, world, tip, target, pole ? sub(pole, world[joints[joints[tip]!.parent]!.parent]!.origin) : undefined);+ } else {+ const axis: Vec3 = k.axis === 'x' ? [1, 0, 0] : k.axis === 'y' ? [0, 1, 0] : [0, 0, 1];+ const facing = rotateBy(world[tip]!.q, axis);+ const wanted = quatMul(rotationBetween(facing, sub(target, world[tip]!.origin)), world[tip]!.q);+ const parent = joints[tip]!.parent;+ local[tip] = { ...local[tip]!, q: quatMul(conjugate(parent >= 0 ? world[parent]!.q : [0, 0, 0, 1]), wanted) };+ world = toWorld(joints, local);+ }+ }+ return world;+}++/** Where each joint is in a pose: for checking a foot landed. */+export function jointPositions(joints: readonly RigJoint[], animation: AnimationSource | null, time: number, solve?: PoseSolve): Record<string, Vec3> {+ const { world } = poseAt(joints, animation, time, solve);+ return 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]) }];+ }));+}++// ---- A humanoid's bones ---------------------------------------------------------++export interface HumanoidBuild {+ /** From the floor to the crown. Default 1.6. */+ height?: number;+ /** Size of the head against the body. Default 1; above it younger or more stylised. */+ head?: number;+ /** Width of each, against the table. Default 1. */+ shoulders?: number;+ chest?: number;+ waist?: number;+ hips?: number;+ /** Thickness of the arms and legs. Default 1. */+ limbs?: number;+}++export interface Section { y: number; across: number; front: number; back: number; z: number; x?: number }++/** The table is for a body 1.6 tall. */+export const TABLE_HEIGHT = 1.6;++export const TORSO: readonly Section[] = [+ { y: 1.345, across: 0.05, front: 0.05, back: 0.055, z: -0.018 },+ { y: 1.315, across: 0.082, front: 0.058, back: 0.066, z: -0.022 },+ { y: 1.285, across: 0.145, front: 0.068, back: 0.074, z: -0.022 },+ { y: 1.25, across: 0.158, front: 0.08, back: 0.08, z: -0.018 },+ { y: 1.2, across: 0.142, front: 0.094, back: 0.082, z: -0.012 },+ { y: 1.145, across: 0.125, front: 0.098, back: 0.076, z: -0.006 },+ { y: 1.09, across: 0.108, front: 0.08, back: 0.068, z: -0.004 },+ { y: 1.03, across: 0.096, front: 0.066, back: 0.056, z: -0.002 },+ { y: 0.975, across: 0.104, front: 0.068, back: 0.058, z: 0 },+ { y: 0.915, across: 0.122, front: 0.074, back: 0.076, z: -0.004 },+ { y: 0.85, across: 0.14, front: 0.076, back: 0.088, z: -0.006 },+ { y: 0.79, across: 0.132, front: 0.07, back: 0.08, z: -0.004 },+ { y: 0.745, across: 0.08, front: 0.06, back: 0.06, z: -0.004 },+];++export const ARM_DROP = (62 * Math.PI) / 180;++export interface HumanoidFrame {+ k: number;+ shoulder: Vec3; elbow: Vec3; wrist: Vec3; knuckle: Vec3;+ hip: Vec3; knee: Vec3; ankle: Vec3; ball: Vec3; toe: Vec3;+ pelvis: Vec3; waist: Vec3; chest: Vec3; neck: Vec3; head: Vec3; crown: Vec3;+ /** Along the arm, from the shoulder out and down. */+ along: Vec3;+ fingers: readonly { name: string; base: Vec3; length: number; radius: number }[];+ thumb: { base: Vec3; mid: Vec3; tip: Vec3 };+}++/** Where everything is, in the table's own proportions times its height. Also what a skeleton is laid on. */+export function humanoidFrame(b: HumanoidBuild = {}): HumanoidFrame {+ const k = (b.height ?? TABLE_HEIGHT) / TABLE_HEIGHT;+ const s = (x: number, y: number, z: number): Vec3 => [x * k, y * k, z * k];+ const along: Vec3 = [Math.sin(ARM_DROP), -Math.cos(ARM_DROP), 0];+ const shoulderX = 0.158 * (b.shoulders ?? 1);+ const at = (d: number): Vec3 => s(shoulderX + along[0] * d, 1.268 + along[1] * d, -0.018);+ const palmAt = 0.27 + 0.235 + 0.09;+ const fingers = [+ { name: 'index', z: 0.027, length: 0.078, radius: 0.0085 },+ { name: 'middle', z: 0.009, length: 0.086, radius: 0.0088 },+ { name: 'ring', z: -0.009, length: 0.08, radius: 0.0082 },+ { name: 'little', z: -0.026, length: 0.062, radius: 0.0072 },+ ].map((f) => {+ const base = at(palmAt);+ return { name: f.name, base: [base[0], base[1], base[2] + f.z * k] as Vec3, length: f.length * k, radius: f.radius * k };+ });+ const wrist = at(0.27 + 0.235);+ const thumbBase: Vec3 = [wrist[0] + along[0] * 0.022 * k, wrist[1] + along[1] * 0.022 * k - 0.004 * k, wrist[2] + 0.028 * k];+ const thumbMid: Vec3 = [thumbBase[0] + along[0] * 0.038 * k, thumbBase[1] + along[1] * 0.038 * k - 0.006 * k, thumbBase[2] + 0.024 * k];+ const thumbTip: Vec3 = [thumbMid[0] + along[0] * 0.036 * k, thumbMid[1] + along[1] * 0.036 * k - 0.006 * k, thumbMid[2] + 0.01 * k];+ return {+ k, along,+ shoulder: at(0), elbow: at(0.27), wrist, knuckle: at(palmAt),+ hip: s(0.08, 0.81, -0.004), knee: s(0.068, 0.445, 0.006), ankle: s(0.067, 0.078, -0.016), ball: s(0.072, 0.022, 0.09), toe: s(0.072, 0.018, 0.165),+ pelvis: s(0, 0.86, -0.004), waist: s(0, 1.0, 0), chest: s(0, 1.16, -0.008), neck: s(0, 1.32, -0.022), head: s(0, 1.405, -0.01), crown: s(0, TABLE_HEIGHT, -0.012),+ fingers, thumb: { base: thumbBase, mid: thumbMid, tip: thumbTip },+ };+}++/** The bones of a humanoid of this build, named as a clip names them. `.L` is her left, on +x. */+export function humanoidJoints(b: HumanoidBuild = {}): RigJointSource[] {+ const f = humanoidFrame(b);+ const mid = (a: Vec3, c: Vec3, t: number): Vec3 => [a[0] + (c[0] - a[0]) * t, a[1] + (c[1] - a[1]) * t, a[2] + (c[2] - a[2]) * t];+ const clavicle: Vec3 = [0.03 * f.k, 1.29 * f.k, -0.008 * f.k];+ const joints: RigJointSource[] = [+ { name: 'hips', at: f.pelvis },+ { name: 'spine', at: f.waist, parent: 'hips' },+ { name: 'chest', at: f.chest, parent: 'spine' },+ { name: 'neck', at: f.neck, parent: 'chest' },+ { name: 'head', at: f.head, parent: 'neck' },+ { name: 'crown', at: f.crown, parent: 'head' },+ { name: 'clavicle', at: clavicle, parent: 'chest', mirror: 'x' },+ { name: 'upperArm', at: f.shoulder, parent: 'clavicle', mirror: 'x' },+ { name: 'forearm', at: f.elbow, parent: 'upperArm', mirror: 'x' },+ { name: 'hand', at: f.wrist, parent: 'forearm', mirror: 'x' },+ { name: 'thumb1', at: f.thumb.base, parent: 'hand', mirror: 'x' },+ { name: 'thumb2', at: f.thumb.mid, parent: 'thumb1', mirror: 'x' },+ { name: 'thumb3', at: f.thumb.tip, parent: 'thumb2', mirror: 'x' },+ { name: 'thigh', at: f.hip, parent: 'hips', mirror: 'x' },+ { name: 'shin', at: f.knee, parent: 'thigh', mirror: 'x' },+ { name: 'foot', at: f.ankle, parent: 'shin', mirror: 'x' },+ { name: 'toes', at: f.ball, parent: 'foot', mirror: 'x' },+ { name: 'toeTip', at: f.toe, parent: 'toes', mirror: 'x' },+ ];+ for (const finger of f.fingers) {+ let parent = 'hand';+ for (let i = 0; i < 4; i++) {+ const name = `${finger.name}${i + 1}`;+ const t = [0, 0.45, 0.75, 1][i]!;+ joints.push({ name, at: mid(finger.base, [finger.base[0] + f.along[0] * finger.length, finger.base[1] + f.along[1] * finger.length, finger.base[2]], t), parent, mirror: 'x' });+ parent = name;+ }+ }+ return joints;+}++// ---- A pose ---------------------------------------------------------------------++export interface PoseParams {+ /** The bones of a humanoid of this build; true for the default one. */+ humanoid: HumanoidBuild | true;+ /** joint name to [x, y, z] degrees from its rest, X then Y then Z. */+ rotate?: Readonly<Record<string, readonly number[]>>;+ /** joint name to [x, y, z] from where it rests: `hips` lowers a sitting body. */+ move?: Readonly<Record<string, readonly number[]>>;+ /** joint name to where it must be, in the model's own space: a hand on a bow, a foot on the ground. The two bones above it turn to put it there; `pole` is the way the middle one bends. */+ reach?: Readonly<Record<string, { at: readonly number[]; pole?: readonly number[] }>>;+ /** The whole mesh rides on this one joint, whole: hair cards, which have no skin between them for weights to spread over. */+ rigid?: string;+}++/** A pose as the clip that holds it, on the bones it is for. */+export function poseClip(p: PoseParams): { joints: RigJoint[]; animation: AnimationSource } {+ if (p.humanoid === undefined) throw new Error('`humanoid` says whose bones: true, or the build it was given');+ const joints: RigJoint[] = resolveJoints({ joints: humanoidJoints(p.humanoid === true ? {} : p.humanoid) });+ const names = new Set(joints.map((j) => j.name));+ const known = (name: string): void => {+ if (!names.has(name)) throw new Error(`no joint "${name}"; there are ${[...names].join(', ')}`);+ };+ const tracks = new Map<string, { rotate?: number[][]; move?: number[][]; reach?: number[][]; pole?: readonly number[] }>();+ for (const [name, r] of Object.entries(p.rotate ?? {})) {+ known(name);+ if (r.length !== 3) throw new Error(`rotate of "${name}" must be [x, y, z] degrees`);+ tracks.set(name, { rotate: [[0, r[0]!, r[1]!, r[2]!]] });+ }+ for (const [name, m] of Object.entries(p.move ?? {})) {+ known(name);+ if (m.length !== 3) throw new Error(`move of "${name}" must be [x, y, z]`);+ tracks.set(name, { ...tracks.get(name), move: [[0, m[0]!, m[1]!, m[2]!]] });+ }+ for (const [name, r] of Object.entries(p.reach ?? {})) {+ known(name);+ if (r.at?.length !== 3) throw new Error(`reach of "${name}" needs at: [x, y, z]`);+ tracks.set(name, { ...tracks.get(name), reach: [[0, r.at[0]!, r.at[1]!, r.at[2]!]], ...(r.pole ? { pole: r.pole } : {}) });+ }+ return { joints, animation: { name: 'pose', duration: 1, loop: false, tracks: [...tracks].map(([joint, t]) => ({ joint, ...t })) as AnimationTrack[] } };+}++/** Where each joint is in a pose, without the seconds a surface takes. */+export function poseJoints(p: PoseParams): Record<string, Vec3> {+ const { joints, animation } = poseClip(p);+ 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);+}diff --git a/sdk/src/image/imageFigure.ts b/sdk/src/image/imageFigure.tsnew file mode 100644index 000000000..91a8bbed9--- /dev/null+++ b/sdk/src/image/imageFigure.ts@@ -0,0 +1,265 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file imageFigure.ts+ * @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.+ *+ * 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 { poseFrames, poseJoints, type HumanoidBuild, type PoseParams } from './figureSkeleton';+import type { ImageLayer } from './imageSource';+import type { FlatFigure } from './imageRaster';++export type { FlatFigure } from './imageRaster';++/** The bones' own height: they are built at it, and sized in the picture. */+const BODY_HEIGHT = 1.6;+const SUPERSAMPLE = 2;+const AROUND = 14;++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'],+];++interface Ring { at: V3; across: V3; deep: V3; a: number; d: number }+interface Volume { tag: (typeof FIGURE_TAGS)[number]; rings: Ring[] }++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]];++/** 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));+ }+ 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;+}+++const normalized = (v: readonly number[]): [number, number, number] => {+ const len = Math.hypot(v[0]!, v[1]!, v[2]!) || 1;+ return [v[0]! / len, v[1]! / len, v[2]! / len];+};++/** Flattens a `figure` layer. @p project takes a point in the picture before any group's transform, and @p scale is that transform's size. */+export function flattenFigure(layer: ImageLayer, w: number, h: number, project: (p: readonly [number, number]) => readonly [number, number], scale: number): FlatFigure {+ const [ax, ay] = project(layer.at!);+ const s = ((layer.height as number) / BODY_HEIGHT) * scale;+ const yaw = ((layer.yaw ?? 0) * Math.PI) / 180, pitch = ((layer.pitch ?? 0) * Math.PI) / 180;+ const [cy, sy, cp, sp] = [Math.cos(yaw), Math.sin(yaw), Math.cos(pitch), Math.sin(pitch)];+ /** Yaw about the body, then pitch toward the viewer: what the body's axes are in the view. */+ const toView = (p: readonly number[]): [number, number, number] => {+ const [x, y, z] = [p[0]! * cy + p[2]! * sy, p[1]!, -p[0]! * sy + p[2]! * cy];+ return [x, y * cp - z * sp, y * sp + z * cp];+ };+ const fromView = (v: readonly number[]): [number, number, number] => {+ 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 ?? {});+ let resolved: PoseParams = held;+ if (reach.length) {+ const before = poseJoints(held);+ 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 frames = poseFrames(resolved);+ const joints: Record<string, readonly [number, number]> = {};+ for (const name of FIGURE_JOINTS) {+ 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);+ 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 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);+ const tag = tagAt[i]!;+ const right = x + 1 < W ? depth[i + 1]! : -Infinity, below = y + 1 < H ? depth[i + W]! : -Infinity;+ if (tag >= 0 || right > -Infinity || below > -Infinity) {+ const here = depth[i]!;+ if (Math.abs(here - right) > step || Math.abs(here - below) > step) contour[o] = Math.min(1, contour[o]! + share * 2);+ }+ if (tag < 0) continue;+ mask[o]! += share;+ parts[FIGURE_TAGS[tag]!]![o]! += share;+ for (let k = 0; k < 3; k++) normals[o * 3 + k]! += nAt[i * 3 + k]! * share;+ }+ }+ for (let o = 0; o < mask.length; o++) {+ 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;+ }++ // 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/sdk/src/image/imageMaterial.ts b/sdk/src/image/imageMaterial.tsindex ab32cd54f..8582603ba 100644--- a/sdk/src/image/imageMaterial.ts+++ b/sdk/src/image/imageMaterial.ts@@ -13,7 +13,7 @@* cheap guess every texture tool makes, and it is right for mortar and wrong for a painted stripe, which is why* a relief can be drawn instead.*/-import { renderImage, type RenderedImage, type RgbaBitmap, type ImageFigureDrawer, type ImageTextDrawer } from './imageRaster';+import { renderImage, type RenderedImage, type RgbaBitmap, type ImageTextDrawer } from './imageRaster';import type { ImageLayer, ImageMaterial, ImageSource } from './imageSource';export type { ImageMaterial } from './imageSource';@@ -31,7 +31,7 @@ export interface MaterialMaps {notes: string[];}-type DrawOptions = { pictures?: Readonly<Record<string, RgbaBitmap>>; text?: ImageTextDrawer; figure?: ImageFigureDrawer };+type DrawOptions = { pictures?: Readonly<Record<string, RgbaBitmap>>; text?: ImageTextDrawer };const lightness = (p: Uint8Array, i: number): number => (p[i * 4]! * 0.2126 + p[i * 4 + 1]! * 0.7152 + p[i * 4 + 2]! * 0.0722) / 255;diff --git a/sdk/src/image/imageRaster.ts b/sdk/src/image/imageRaster.tsindex 58afe6e62..92d1d70d8 100644--- a/sdk/src/image/imageRaster.ts+++ b/sdk/src/image/imageRaster.ts@@ -7,6 +7,7 @@* effects, and this owns everything that has to be exact: antialiased edges, gradients, soft shadows.* On the CPU rather than through a canvas, so the same source makes the same bytes on any machine and a test can read them.*/+import { flattenFigure } from './imageFigure';import { applyAdjust, applyFilter, lightnessOf } from './imageAdjust';import { IMAGE_BRUSHES, isGuideLayer, MAX_MARK_STROKES } from './imageSource';import type { ImageFill, ImageLayer, ImageSource, ImageAlong, ImageBrushSettings, ImageEffect, ImageField, ImageMark, ImageStroke, ImageSweep, ImageTransform } from './imageSource';@@ -36,14 +37,6 @@ export interface FlatFigure {light: readonly [number, number, number];}-/**- * What draws a `figure` layer, handed to renderImage by whoever has a body to pose (the authoring pipeline). A game that evaluates a- * picture has none, and a picture with a figure in it is one to bake before it ships.- */-export interface ImageFigureDrawer {- flatten(layer: ImageLayer, w: number, h: number, project: (p: readonly [number, number]) => readonly [number, number], scale: number): FlatFigure;-}-const unit3 = (v: readonly number[]): [number, number, number] => {const len = Math.hypot(v[0]!, v[1]!, v[2]!) || 1;return [v[0]! / len, v[1]! / len, v[2]! / len];@@ -695,7 +688,7 @@ function effectLayers(effects: readonly ImageEffect[] | undefined, under: boolea}}-interface Drawn { figure?: ImageFigureDrawer; 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>; text: ImageTextDrawer | undefined; blocks: Map<string, Record<string, readonly (readonly number[])[]>> }+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>; text: ImageTextDrawer | undefined; blocks: Map<string, Record<string, readonly (readonly number[])[]>> }/** x, y, width and height in the picture's pixels. */export type ImageBox = readonly [number, number, number, number];@@ -1499,8 +1492,7 @@ function drawPaint(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn, o/** 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;- if (!drawn.figure) throw new Error('this picture has a figure layer, and nothing here draws figures: it is baked where it is authored');- const figure = drawn.figure.flatten(layer, w, h, (p) => apply(parent, p), drawnScale(parent));+ 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);@@ -1971,10 +1963,10 @@ export interface RenderedImage extends RgbaBitmap {}/** Draws a source that has been validated. */-export function renderImage(source: ImageSource, options: { guides?: boolean; pictures?: Readonly<Record<string, RgbaBitmap>>; text?: ImageTextDrawer; figure?: ImageFigureDrawer } = {}): RenderedImage {+export function renderImage(source: ImageSource, options: { guides?: boolean; pictures?: Readonly<Record<string, RgbaBitmap>>; text?: ImageTextDrawer } = {}): RenderedImage {const [w, h] = typeof source.size === 'number' ? [source.size, source.size] : source.size;const canvas = new Canvas(w, h);- const drawn: Drawn = { figure: options.figure, 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(), text: options.text, blocks: new Map() };+ 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(), text: options.text, blocks: new Map() };// What every layer so far amounts to, chained: a layer changed leaves the keys before it as they were.let key = textHash(JSON.stringify([w, h, source.background ?? null, options.guides === true, picturesDigest(options.pictures), source.tile === true]));const keys = source.layers.map((layer) => (key = textHash(key + JSON.stringify(layer))));diff --git a/sdk/src/image/imageText.ts b/sdk/src/image/imageText.tsnew file mode 100644index 000000000..a2cf7fe12--- /dev/null+++ b/sdk/src/image/imageText.ts@@ -0,0 +1,79 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file imageText.ts+ * @brief A picture's text, drawn by a 2D canvas: the one part of a picture that follows the fonts of the machine it is drawn on.+ *+ * @details The raster has no fonts. Whoever has a canvas (a browser, a worker with an OffscreenCanvas, a mini-game) hands it this+ * drawer, which sets the text and reads back how much of each pixel it covers. A `font` that is a file of the project is+ * drawn in that file's own glyphs wherever it is drawn; a family name is whatever the device has by that name.+ */+import type { ImageTextDrawer } from './imageRaster';++/** As much of a 2D canvas as setting text takes. */+export interface TextCanvasContext {+ font: string;+ textBaseline: string;+ textAlign: string;+ lineWidth: number;+ lineJoin: string;+ setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void;+ clearRect(x: number, y: number, w: number, h: number): void;+ measureText(text: string): { width: number };+ fillText(text: string, x: number, y: number): void;+ strokeText(text: string, x: number, y: number): void;+ getImageData(x: number, y: number, w: number, h: number): { data: ArrayLike<number> };+}++export interface TextCanvas { getContext(id: '2d', options?: { willReadFrequently?: boolean }): unknown }++/**+ * A drawer of text on canvases `canvas` makes. `familyOf` answers the family a font file was registered under, or nothing for a+ * font that is a family's own name.+ */+export function canvasTextDrawer(canvas: (w: number, h: number) => TextCanvas, familyOf: (font: string) => string | undefined): ImageTextDrawer {+ return (layer, m, w, h) => {+ const ctx = canvas(w, h).getContext('2d', { willReadFrequently: true }) as TextCanvasContext | null;+ if (!ctx) throw new Error('could not draw text here');+ const size = layer.fontSize as number;+ const family = layer.font ? `"${familyOf(layer.font) ?? layer.font}", sans-serif` : 'sans-serif';+ ctx.font = `${layer.weight ?? 'normal'} ${size}px ${family}`;+ ctx.textBaseline = 'alphabetic';+ ctx.setTransform(m[0]!, m[1]!, m[2]!, m[3]!, m[4]!, m[5]!);+ const [x, y] = layer.at as readonly [number, number];+ const chars = [...(layer.text as string)];+ const tracking = layer.tracking ?? 0;+ const put = (paint: (t: string, px: number, py: number) => void): void => {+ if (layer.vertical) {+ // One under the other, each centred on the column: at is the top of it.+ ctx.textAlign = 'center';+ chars.forEach((ch, i) => paint(ch, x, y + size * (i + 0.86) + (size * 0.08 + tracking) * i));+ return;+ }+ ctx.textAlign = 'left';+ const widths = chars.map((ch) => ctx.measureText(ch).width + tracking);+ const total = widths.reduce((a, b) => a + b, 0) - tracking;+ let at = x - (layer.align === 'center' ? total / 2 : layer.align === 'right' ? total : 0);+ chars.forEach((ch, i) => { paint(ch, at, y); at += widths[i]!; });+ };+ const read = (): Float32Array => {+ const data = ctx.getImageData(0, 0, w, h).data;+ const out = new Float32Array(w * h);+ for (let i = 0; i < out.length; i++) out[i] = data[i * 4 + 3]! / 255;+ return out;+ };+ put((t, px, py) => ctx.fillText(t, px, py));+ const fill = read();+ let line: Float32Array | null = null;+ if (layer.stroke) {+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.clearRect(0, 0, w, h);+ ctx.setTransform(m[0]!, m[1]!, m[2]!, m[3]!, m[4]!, m[5]!);+ ctx.lineWidth = layer.stroke.width;+ ctx.lineJoin = 'round';+ put((t, px, py) => ctx.strokeText(t, px, py));+ line = read();+ }+ return { fill, line };+ };+}diff --git a/sdk/src/image/index.ts b/sdk/src/image/index.tsindex 69311fd46..b1ae3e15d 100644--- a/sdk/src/image/index.ts+++ b/sdk/src/image/index.ts@@ -4,34 +4,82 @@* @file index.ts* @brief Pictures drawn from their source: the raster an `.esimage` is drawn by, for a game that ships recipes in place of pixels.*/-export { renderImage, type RenderedImage, type RgbaBitmap, type ImageFigureDrawer, type ImageTextDrawer, type FlatFigure } from './imageRaster';+export { renderImage, type RenderedImage, type RgbaBitmap, type ImageTextDrawer, type FlatFigure } from './imageRaster';export { validateImageSource, IMAGE_SOURCE_EXT, IMAGE_SOURCE_VERSION, MAX_IMAGE_SIZE, type ImageSource, type ImageLayer, type ImageMaterial } from './imageSource';export { renderMaterialMaps, type MaterialMaps } from './imageMaterial';+export { parseRecipe, recipeNeeds, RECIPE_MAPS, type ImageMapSource, type RecipeMap } from './recipeSource';+export { canvasTextDrawer } from './imageText';export { IMAGE_RASTER_REVISION } from './imageRaster';// Importing this subpath INSTALLS the drawer of texture recipes — see tilemap/index.ts.import { IMAGE_RASTER_REVISION } from './imageRaster';-import { drawRecipe } from './recipeWorker';+import { drawRecipe, NO_TEXT_CANVAS, type DrawnRecipe, type RecipeHost, type RecipeJob } from './recipeWorker';import { RECIPE_WORKER_SOURCE } from './recipeWorkerBundle.generated';-import { setTextureRecipeRenderer, type RecipePixels } from '../asset/textureRecipe';+import { isFontFile, recipeNeeds } from './recipeSource';+import { decodeImagePixels } from '../asset/imageDecode';+import { decodePngData } from '../asset/pngData';+import { isTextureRecipePath, setTextureRecipeDrawer, type TextureRecipeDrawer } from '../asset/textureRecipe';+import { getPlatform, platformCreateCanvas } from '../platform/base';import { createJobPool, type JobPool } from '../runtime/jobs';let pool: JobPool | null | undefined;let next = 0;-// Drawn on a worker where the host has workers, so a game goes on drawing frames while its pictures are made; in place where it has-// none, or once the workers have failed (a recipe is still a texture then, only a slower one to load).-setTextureRecipeRenderer(async (source): Promise<RecipePixels> => {- if (pool === undefined) pool = createJobPool(RECIPE_WORKER_SOURCE);- if (pool) {+/** The game's own thread as a place to draw: the platform's canvas, and its way of making a font file a family. */+const HERE: RecipeHost = {+ canvas: (w, h) => {try {- return await pool.run<RecipePixels>(next++, { source });- } catch (err) {- // What the source itself is refused for is the answer; only a worker that cannot run sends the job back here.- if (!/^(a job worker failed|the job workers have stopped|the job pool was disposed)/.test(err instanceof Error ? err.message : String(err))) throw err;- pool = null;+ return platformCreateCanvas(w, h);+ } catch {+ throw new Error('a picture with text needs a 2D canvas to draw it, and this host has none: bake it to its .png');+ }+ },+ async font(family, bytes) {+ const register = getPlatform().registerFont;+ if (!register) throw new Error('a picture set in a font file needs a host that takes font files, and this one does not: bake it to its .png');+ await register.call(getPlatform(), family, bytes);+ },+};++/** An image file's pixels as stored, for a recipe that lays the picture in. */+async function decoded(path: string, bytes: ArrayBuffer): Promise<DrawnRecipe> {+ const png = await decodePngData(new Uint8Array(bytes));+ if (png) return { width: png.width, height: png.height, pixels: png.pixels };+ if (typeof createImageBitmap !== 'function' || typeof Blob === 'undefined') throw new Error(`${path} is laid in a recipe and is not a PNG this host can read`);+ const image = await decodeImagePixels(new Blob([bytes]));+ return { width: image.width, height: image.height, pixels: image.pixels };+}++// Drawn on a worker where the host has workers, so a game goes on drawing frames while its pictures are made; in place where it has+// none, once the workers have failed, or for text where a worker has no canvas (a recipe is still a texture then, a slower one to load).+const DRAWER: TextureRecipeDrawer = {+ revision: IMAGE_RASTER_REVISION,+ needs: recipeNeeds,+ async draw(source, files): Promise<DrawnRecipe> {+ const job: RecipeJob = { source, files: {}, pictures: {} };+ for (const [path, bytes] of files) {+ if (isTextureRecipePath(path) || isFontFile(path)) job.files[path] = bytes;+ else job.pictures[path] = await decoded(path, bytes);+ }+ if (pool === undefined) pool = createJobPool(RECIPE_WORKER_SOURCE);+ if (pool) {+ try {+ return await pool.run<DrawnRecipe>(next++, { ...job });+ } catch (err) {+ const why = err instanceof Error ? err.message : String(err);+ // What the source itself is refused for is the answer; only a worker that cannot do the job sends it back here.+ if (/^(a job worker failed|the job workers have stopped|the job pool was disposed)/.test(why)) pool = null;+ else if (why !== NO_TEXT_CANVAS) throw err;+ }}- }- return drawRecipe(source);-}, IMAGE_RASTER_REVISION);+ return drawRecipe(job, HERE);+ },+};++/** Installs the drawer of texture recipes: what importing this module does, and a way back for whoever took it out. */+export function installTextureRecipes(): void {+ setTextureRecipeDrawer(DRAWER);+}++installTextureRecipes();diff --git a/sdk/src/image/recipeSource.ts b/sdk/src/image/recipeSource.tsnew file mode 100644index 000000000..f620c0a57--- /dev/null+++ b/sdk/src/image/recipeSource.ts@@ -0,0 +1,74 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file recipeSource.ts+ * @brief What an `.esimage` shipped as a texture says: a picture, or one of the surface maps of another picture.+ *+ * @details A picture with a `material` is a surface as well as a colour: a normal map and a roughness-and-metal map are drawn from+ * the same layers. A map is a texture of its own (it has its own import settings: data, not colour), so it is a file of+ * its own: `{ "mapOf": "assets/wall.esimage", "map": "normal" }`. Nothing is drawn twice in the source, and a wall whose+ * layers change changes its maps with it.+ */+import { validateImageSource, type ImageLayer, type ImageSource } from './imageSource';++/** The maps a picture with a `material` has beside its colour. */+export const RECIPE_MAPS = ['normal', 'surface'] as const;+export type RecipeMap = (typeof RECIPE_MAPS)[number];++/** A recipe that is a surface map of the picture at `mapOf` (a project path). */+export interface ImageMapSource { version?: number; mapOf: string; map: RecipeMap }++export type Recipe = { picture: ImageSource } | { map: ImageMapSource };++const FONT_FILE = /\.(ttf|otf|woff2?)$/i;++/** Whether a text layer's `font` names a file of the project and not a family the device has. */+export const isFontFile = (font: string): boolean => FONT_FILE.test(font);++/** A recipe from its text, checked: a wrong one says what is wrong. */+export function parseRecipe(text: string): Recipe {+ const raw = JSON.parse(text) as Record<string, unknown>;+ if (raw === null || typeof raw !== 'object' || !('mapOf' in raw)) return { picture: validateImageSource(raw) };+ const { mapOf, map } = raw;+ if (typeof mapOf !== 'string' || !mapOf.toLowerCase().endsWith('.esimage')) throw new Error('mapOf must be the project path of an .esimage');+ if (!RECIPE_MAPS.includes(map as RecipeMap)) throw new Error(`map must be one of ${RECIPE_MAPS.join(', ')}`);+ const extra = Object.keys(raw).filter((k) => k !== 'mapOf' && k !== 'map' && k !== 'version');+ if (extra.length > 0) throw new Error(`a map of a picture says only mapOf and map, and this one also says ${extra.join(', ')}`);+ return { map: { mapOf, map: map as RecipeMap } };+}++/** Every layer of a picture, those inside groups and those its material draws included. */+function* layersOf(source: ImageSource): Generator<ImageLayer> {+ function* within(layers: readonly ImageLayer[]): Generator<ImageLayer> {+ for (const l of layers) {+ yield l;+ yield* within(l.layers ?? []);+ }+ }+ yield* within(source.layers);+ for (const drawn of [source.material?.height, source.material?.roughness, source.material?.metal]) {+ if (Array.isArray(drawn)) yield* within(drawn as readonly ImageLayer[]);+ }+}++/** The pictures a source lays in and the font files its text is set in, by project path. */+export function pictureNeeds(source: ImageSource): { pictures: string[]; fonts: string[]; text: boolean } {+ const pictures = new Set<string>(), fonts = new Set<string>();+ let text = false;+ for (const l of layersOf(source)) {+ if (l.shape === 'image' && l.src) pictures.add(l.src);+ if (l.shape === 'text') {+ text = true;+ if (l.font && isFontFile(l.font)) fonts.add(l.font);+ }+ }+ return { pictures: [...pictures], fonts: [...fonts], text };+}++/** The project files a recipe needs beside itself. */+export function recipeNeeds(text: string): string[] {+ const recipe = parseRecipe(text);+ if ('map' in recipe) return [recipe.map.mapOf];+ const { pictures, fonts } = pictureNeeds(recipe.picture);+ return [...pictures, ...fonts];+}diff --git a/sdk/src/image/recipeWorker.ts b/sdk/src/image/recipeWorker.tsindex c8dd5cc1e..90cd4a427 100644--- a/sdk/src/image/recipeWorker.ts+++ b/sdk/src/image/recipeWorker.ts@@ -2,32 +2,123 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file recipeWorker.ts- * @brief The worker that draws texture recipes: a picture's source in, its pixels out, off the thread the game runs on.+ * @brief The worker that draws texture recipes: a recipe and the files it needs in, its pixels out, off the thread the game runs on.** @details This file is bundled on its own (sdk/scripts/build-worker.mjs) into text `esengine/image` starts its workers from, as the- * planning worker is. A job is `{ id, source }`; its answer is `{ id, result: { width, height, pixels } }` with the pixels'- * own buffer handed over, or `{ id, error }`.+ * planning worker is. A job is `{ id, ...RecipeJob }`; its answer is `{ id, result: { width, height, pixels } }` with the+ * pixels' own buffer handed over, or `{ id, error }`. The same drawRecipe runs on the main thread where there is no worker.*/-import { renderImage } from './imageRaster';-import { validateImageSource } from './imageSource';--/** The pixels a source draws, in a buffer of their own (one a worker can hand over whole). */-export function drawRecipe(source: string): { width: number; height: number; pixels: Uint8Array } {- const picture = renderImage(validateImageSource(JSON.parse(source)));- const whole = picture.rgba.byteOffset === 0 && picture.rgba.byteLength === picture.rgba.buffer.byteLength;- return { width: picture.width, height: picture.height, pixels: whole ? picture.rgba : picture.rgba.slice() };+import { renderImage, type ImageTextDrawer, type RgbaBitmap } from './imageRaster';+import { renderMaterialMaps } from './imageMaterial';+import type { ImageSource } from './imageSource';+import { canvasTextDrawer, type TextCanvas } from './imageText';+import { parseRecipe, pictureNeeds } from './recipeSource';+import { decodeUtf8 } from '../util/utf8';++export interface DrawnRecipe { width: number; height: number; pixels: Uint8Array }++/** A recipe to draw, with what it needs to hand. */+export interface RecipeJob {+ source: string;+ /** The recipes and the font files it needs (and those they need), by project path. */+ files: Record<string, ArrayBuffer>;+ /** The pictures it lays in that are images and not recipes, decoded. */+ pictures: Record<string, DrawnRecipe>;}-declare const self: { onmessage: ((e: { data: { id: number; source: string } }) => void) | null; postMessage(m: unknown, transfer?: ArrayBuffer[]): void } | undefined;+/** What the thread a recipe is drawn on has for text: a canvas, and a way to make a font file a family. */+export interface RecipeHost {+ canvas: ((w: number, h: number) => TextCanvas) | null;+ font(family: string, bytes: ArrayBuffer): Promise<void>;+}-if (typeof self !== 'undefined' && typeof (self as { document?: unknown }).document === 'undefined') {- self.onmessage = (e) => {- const job = e.data;- try {- const drawn = drawRecipe(job.source);- self!.postMessage({ id: job.id, result: drawn }, [drawn.pixels.buffer as ArrayBuffer]);- } catch (err) {- self!.postMessage({ id: job.id, error: err instanceof Error ? err.message : String(err) });+/** What a job with text says where there is no canvas: whoever sent it draws it where there is one. */+export const NO_TEXT_CANVAS = 'this thread has no canvas to draw text on';+/** A recipe may lay in a recipe that lays in a recipe, this deep. */+const MAX_NESTING = 8;++const families = new Map<string, string>();+const textOf = (bytes: ArrayBuffer): string => decodeUtf8(new Uint8Array(bytes));++const whole = (rgba: Uint8Array): Uint8Array => (rgba.byteOffset === 0 && rgba.byteLength === rgba.buffer.byteLength ? rgba : rgba.slice());++function fileOf(job: RecipeJob, path: string): ArrayBuffer {+ const bytes = job.files[path];+ if (!bytes) throw new Error(`there is no file at ${path}`);+ return bytes;+}++/** A picture source drawn, and the options it was drawn with (its surface maps are drawn with the same). */+async function drawPicture(source: ImageSource, job: RecipeJob, host: RecipeHost, depth: number): Promise<{ picture: RgbaBitmap; options: { pictures: Record<string, RgbaBitmap>; text?: ImageTextDrawer } }> {+ const needs = pictureNeeds(source);+ const pictures: Record<string, RgbaBitmap> = {};+ for (const src of needs.pictures) {+ const decoded = job.pictures[src];+ if (decoded) { pictures[src] = { width: decoded.width, height: decoded.height, rgba: decoded.pixels }; continue; }+ if (depth >= MAX_NESTING) throw new Error(`recipes laid in recipes go ${MAX_NESTING} deep at most`);+ const inner = parseRecipe(textOf(fileOf(job, src)));+ if (!('picture' in inner)) throw new Error(`${src} is a map of a picture, and a layer lays in a picture`);+ pictures[src] = (await drawPicture(inner.picture, job, host, depth + 1)).picture;+ }+ let text: ImageTextDrawer | undefined;+ if (needs.text) {+ if (!host.canvas) throw new Error(NO_TEXT_CANVAS);+ for (const font of needs.fonts) {+ if (families.has(font)) continue;+ const family = `esimage-font-${families.size}`;+ await host.font(family, fileOf(job, font));+ families.set(font, family);}+ text = canvasTextDrawer(host.canvas, (font) => families.get(font));+ }+ const options = { pictures, ...(text ? { text } : {}) };+ return { picture: renderImage(source, options), options };+}++/** The pixels a recipe draws, in a buffer of their own (one a worker can hand over whole). */+export async function drawRecipe(job: RecipeJob, host: RecipeHost): Promise<DrawnRecipe> {+ const recipe = parseRecipe(job.source);+ if ('picture' in recipe) {+ const { picture } = await drawPicture(recipe.picture, job, host, 0);+ return { width: picture.width, height: picture.height, pixels: whole(picture.rgba) };+ }+ const { mapOf, map } = recipe.map;+ const base = parseRecipe(textOf(fileOf(job, mapOf)));+ if (!('picture' in base)) throw new Error(`${mapOf} is itself a map of a picture`);+ const { picture, options } = await drawPicture(base.picture, job, host, 1);+ const maps = renderMaterialMaps(base.picture, picture, options);+ if (map === 'normal') return { width: maps.normal.width, height: maps.normal.height, pixels: whole(maps.normal.rgba) };+ if (maps.surface) return { width: maps.surface.width, height: maps.surface.height, pixels: whole(maps.surface.rgba) };+ // One roughness and one metal everywhere is one pixel of them, in the layout a drawn map has.+ return { width: 1, height: 1, pixels: new Uint8Array([255, Math.round(maps.roughness * 255), Math.round(maps.metal * 255), 255]) };+}++interface WorkerScope {+ document?: unknown;+ fonts?: { add(face: unknown): void };+ onmessage: ((e: { data: RecipeJob & { id: number } }) => void) | null;+ postMessage(m: unknown, transfer?: ArrayBuffer[]): void;+}+declare const self: WorkerScope | undefined;+declare const OffscreenCanvas: (new (w: number, h: number) => TextCanvas) | undefined;+declare const FontFace: (new (family: string, bytes: ArrayBuffer) => { load(): Promise<unknown> }) | undefined;++if (typeof self !== 'undefined' && typeof self.document === 'undefined') {+ const scope = self;+ const host: RecipeHost = {+ canvas: typeof OffscreenCanvas !== 'undefined' ? (w, h) => new OffscreenCanvas!(w, h) : null,+ async font(family, bytes) {+ if (typeof FontFace === 'undefined' || !scope.fonts) throw new Error(NO_TEXT_CANVAS);+ const face = new FontFace(family, bytes);+ await face.load();+ scope.fonts.add(face);+ },+ };+ scope.onmessage = (e) => {+ const job = e.data;+ drawRecipe(job, host).then(+ (drawn) => scope.postMessage({ id: job.id, result: drawn }, [drawn.pixels.buffer as ArrayBuffer]),+ (err: unknown) => scope.postMessage({ id: job.id, error: err instanceof Error ? err.message : String(err) }),+ );};}diff --git a/sdk/src/image/recipeWorkerBundle.generated.ts b/sdk/src/image/recipeWorkerBundle.generated.tsindex 600f1c382..363e515fe 100644--- a/sdk/src/image/recipeWorkerBundle.generated.ts+++ b/sdk/src/image/recipeWorkerBundle.generated.ts@@ -2,4 +2,4 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team// Generated by sdk/scripts/build-worker.mjs from src/image/recipeWorker.ts: do not edit./** The recipe worker's script: what the workers that draw texture recipes are started from. */-export const RECIPE_WORKER_SOURCE = "(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){let t=/^#([0-9a-fA-F]+)$/.exec(e)?.[1];if(!t||![3,4,6,8].includes(t.length))throw Error(`color ${JSON.stringify(e)} must be #rgb, #rgba, #rrggbb or #rrggbbaa`);let n=t.length<=4?[...t].map(e=>e+e).join(``):t,r=e=>parseInt(n.slice(e,e+2),16)/255;return[r(0),r(2),r(4),n.length===8?r(6):1]}let n=!1,r=e=>{n=e},i=()=>n;function a(e,t,n,r){let i=Math.max(1,Math.round(r*1.2)),a=e;for(let e=0;e<3;e++){let e=new Float32Array(t*n);for(let r=0;r<n;r++){let n=0;for(let e=-i;e<=i;e++)n+=a[r*t+(e%t+t)%t];for(let o=0;o<t;o++)e[r*t+o]=n/(2*i+1),n+=a[r*t+(o+i+1)%t]-a[r*t+((o-i)%t+t)%t]}let r=new Float32Array(t*n);for(let a=0;a<t;a++){let o=0;for(let r=-i;r<=i;r++)o+=e[(r%n+n)%n*t+a];for(let s=0;s<n;s++)r[s*t+a]=o/(2*i+1),o+=e[(s+i+1)%n*t+a]-e[((s-i)%n+n)%n*t+a]}a=r}return a}function o(e,t,r,i){if(i<=0)return e;if(n)return a(e,t,r,i);let o=Math.max(1,Math.round(i*1.2)),s=e;for(let e=0;e<3;e++){let e=new Float32Array(t*r);for(let n=0;n<r;n++){let r=0;for(let e=-o;e<=o;e++)r+=s[n*t+Math.max(0,Math.min(t-1,e))];for(let i=0;i<t;i++)e[n*t+i]=r/(2*o+1),r+=s[n*t+Math.min(t-1,i+o+1)]-s[n*t+Math.max(0,i-o)]}let n=new Float32Array(t*r);for(let i=0;i<t;i++){let a=0;for(let n=-o;n<=o;n++)a+=e[Math.max(0,Math.min(r-1,n))*t+i];for(let s=0;s<r;s++)n[s*t+i]=a/(2*o+1),a+=e[Math.min(r-1,s+o+1)*t+i]-e[Math.max(0,s-o)*t+i]}s=n}return s}let s=[[1,0],[.9239,.3827],[.7071,.7071],[.3827,.9239],[0,1],[-.3827,.9239],[-.7071,.7071],[-.9239,.3827],[-1,0],[-.9239,-.3827],[-.7071,-.7071],[-.3827,-.9239],[0,-1],[.3827,-.9239],[.7071,-.7071],[.9239,-.3827]];function c(e,t,n,r,i){let a=Math.imul(e,374761393)+Math.imul(t,668265263)+Math.imul(n,1442968193);a=Math.imul(a^a>>>13,1274126177),a=Math.imul(a^a>>>16,2246822519);let o=s[((a^a>>>16)>>>0)%s.length];return o[0]*r+o[1]*i}let l=e=>e*e*e*(e*(e*6-15)+10);function u(e,t,n,r=0,i=0){let[a,o]=[Math.floor(e),Math.floor(t)],[s,u]=[e-a,t-o],[d,f]=[l(s),l(u)],p=e=>r>0?(e%r+r)%r:e,m=e=>i>0?(e%i+i)%i:e,h=c(p(a),m(o),n,s,u)*(1-d)+c(p(a+1),m(o),n,s-1,u)*d,g=c(p(a),m(o+1),n,s,u-1)*(1-d)+c(p(a+1),m(o+1),n,s-1,u-1)*d;return h*(1-f)+g*f}let d=[1.15,1.3,1.4,1.45,1.45,1.45,1.45,1.45];function f(e,t,n,r,i=0,a=0){let[o,s,c,l]=[0,0,1,1];for(let d=0;d<n;d++)o+=u(e*l+.37,t*l+.61,r+d*101,i*l,a*l)*c,s+=c,c*=.5,l*=2;return Math.max(0,Math.min(1,.5+o/s*d[n-1]))}let p=e=>Math.max(0,Math.min(1,e)),m=e=>e*e*(3-2*e),h=(e,t,n)=>e*.2126+t*.7152+n*.0722;function g(e,t,n){let[r,i]=[Math.max(e,t,n),Math.min(e,t,n)],a=(r+i)/2;if(r===i)return[0,0,a];let o=r-i,s=a>.5?o/(2-r-i):o/(r+i);return[(r===e?(t-n)/o+(t<n?6:0):r===t?(n-e)/o+2:(e-t)/o+4)/6,s,a]}function _(e,t,n){if(t===0)return[n,n,n];let r=n<.5?n*(1+t):n+t-n*t,i=2*n-r,a=e=>{let t=e<0?e+1:e>1?e-1:e;return t<1/6?i+(r-i)*6*t:t<1/2?r:t<2/3?i+(r-i)*(2/3-t)*6:i};return[a(e+1/3),a(e),a(e-1/3)]}function v(e){let t=[...e].sort((e,t)=>e[0]-t[0]),n=t.map(e=>e[0]),r=t.map(e=>e[1]),i=n.length,a=n.slice(0,-1).map((e,t)=>(r[t+1]-r[t])/Math.max(1e-6,n[t+1]-e)),o=n.map((e,t)=>t===0?a[0]??0:t===i-1?a[i-2]??0:a[t-1]*a[t]<=0?0:(a[t-1]+a[t])/2),s=new Float32Array(1024);for(let e=0;e<s.length;e++){let t=e/(s.length-1);if(t<=n[0]){s[e]=r[0];continue}if(t>=n[i-1]){s[e]=r[i-1];continue}let a=0;for(;t>n[a+1];)a++;let c=n[a+1]-n[a],l=(t-n[a])/c,[u,d]=[l*l,l*l*l];s[e]=p((2*d-3*u+1)*r[a]+(d-2*u+l)*c*o[a]+(3*u-2*d)*r[a+1]+(d-u)*c*o[a+1])}return s}let y=(e,t)=>e[Math.round(p(t)*(e.length-1))];function b(e){let n=[...e].sort((e,t)=>e[0]-t[0]).map(([e,n])=>[e,t(n)]),r=new Float32Array(768);for(let e=0;e<256;e++){let t=e/255,i=0;for(;i+2<n.length&&t>n[i+1][0];)i++;let[a,o]=[n[i],n[Math.min(n.length-1,i+1)]],s=p((t-a[0])/Math.max(1e-6,o[0]-a[0]));for(let t=0;t<3;t++)r[e*3+t]=a[1][t]+(o[1][t]-a[1][t])*s}return r}function x(e,t,n,r){let i=new Float32Array(e.length),a=r.levels,[o,s]=a?.input??[0,1],[c,l]=a?.output??[0,1],u=a?.gamma??1,d=r.curves?Array.isArray(r.curves)?{all:v(r.curves)}:Object.fromEntries(Object.entries(r.curves).map(([e,t])=>[e,v(t)])):null,f=r.exposure===void 0?1:2**r.exposure,[x,S]=[r.brightness??0,r.contrast??0],C=S>=0?1/Math.max(.01,1-S*.98):1+S,[w,T]=[r.temperature??0,r.tint??0],[E,D,O]=[(r.hue??0)/360,r.saturation??0,r.lightness??0],k=r.vibrance??0,A=r.gradientMap?b(r.gradientMap):null,j=r.posterize===void 0?0:Math.max(2,Math.round(r.posterize)),M=r.balance;for(let v=0;v<t*n;v++){let t=v*4,n=e[t+3];if(n<=0)continue;let[b,N,P]=[e[t]/n,e[t+1]/n,e[t+2]/n];if(f!==1&&(b*=f,N*=f,P*=f),a){let e=e=>c+(l-c)*p((e-o)/Math.max(1e-6,s-o))**(1/u);b=e(b),N=e(N),P=e(P)}if(d&&(d.all&&(b=y(d.all,b),N=y(d.all,N),P=y(d.all,P)),d.r&&(b=y(d.r,b)),d.g&&(N=y(d.g,N)),d.b&&(P=y(d.b,P))),x||S){let e=e=>(e+x-.5)*C+.5;b=e(b),N=e(N),P=e(P)}if((w||T)&&(b+=w*.2+T*.1,N-=T*.2,P+=-w*.2+T*.1),M){let e=p(h(b,N,P)),[t,n,r]=[m(p(1-e*2.5)),1-Math.abs(e-.5)*2,m(p((e-.6)*2.5))];for(let[e,i]of[[t,M.shadows],[n,M.midtones],[r,M.highlights]])i&&(b+=i[0]*e*.5,N+=i[1]*e*.5,P+=i[2]*e*.5)}if(E||D||O){let[e,t,n]=g(p(b),p(N),p(P)),r=D>=0?t+(1-t)*D*(t>0):t*(1+D),i=O>=0?n+(1-n)*O:n*(1+O);[b,N,P]=_((e+E+1)%1,p(r),p(i))}if(k){let[e,t]=[Math.max(b,N,P),Math.min(b,N,P)],n=k*(1-p(e-t)),r=h(b,N,P);b=r+(b-r)*(1+n),N=r+(N-r)*(1+n),P=r+(P-r)*(1+n)}if(r.blackWhite){let[e,t,n]=Array.isArray(r.blackWhite)?r.blackWhite:[.2126,.7152,.0722];b=N=P=b*e+N*t+P*n}if(A){let e=Math.round(p(h(b,N,P))*255)*3;[b,N,P]=[A[e],A[e+1],A[e+2]]}if(r.invert&&(b=1-b,N=1-N,P=1-P),j){let e=e=>Math.round(p(e)*(j-1))/(j-1);b=e(b),N=e(N),P=e(P)}r.threshold!==void 0&&(b=N=P=+(h(b,N,P)>=r.threshold)),i[t]=p(b)*n,i[t+1]=p(N)*n,i[t+2]=p(P)*n,i[t+3]=n}return i}let S=(e,t,n,r,i,a,o)=>{let[s,c]=[Math.max(0,Math.min(t-1.001,r-.5)),Math.max(0,Math.min(n-1.001,i-.5))],[l,u]=[Math.floor(s),Math.floor(c)],[d,f]=[s-l,c-u],[p,m,h,g]=[(u*t+l)*4,(u*t+l+1)*4,((u+1)*t+l)*4,((u+1)*t+l+1)*4];for(let t=0;t<4;t++)a[o+t]=(e[p+t]*(1-d)+e[m+t]*d)*(1-f)+(e[h+t]*(1-d)+e[g+t]*d)*f},C=(e,t,n,r)=>{let i=new Float32Array(e.length);for(let a=0;a<4;a++){let s=new Float32Array(t*n);for(let t=0;t<s.length;t++)s[t]=e[t*4+a];let c=o(s,t,n,r);for(let e=0;e<s.length;e++)i[e*4+a]=c[e]}return i};function w(e,t,n,r){let i=new Float32Array(e.length);for(let a=0;a<n;a++)for(let o=0;o<t;o++){let[s,c]=r(o+.5,a+.5);S(e,t,n,s,c,i,(a*t+o)*4)}return i}function T(e,t,n,r,i){let a=new Float32Array(e.length),o=new Float32Array(4);for(let s=0;s<n;s++)for(let c=0;c<t;c++){let l=(s*t+c)*4;for(let u=0;u<r;u++){let[d,f]=i(c+.5,s+.5,r===1?0:u/(r-1));S(e,t,n,d,f,o,0);for(let e=0;e<4;e++)a[l+e]+=o[e]}for(let e=0;e<4;e++)a[l+e]/=r}return a}function E(e,t,n,r){let i=new Float32Array(e),a=new Float32Array(3);for(let e=0;e<n;e++)for(let n=0;n<t;n++){a.fill(0),r(n+.5,e+.5,a);let o=(e*t+n)*4,s=i[o+3];for(let e=0;e<3;e++)i[o+e]=i[o+e]+(1-i[o+e])*p(a[e]),s=Math.max(s,i[o+e]);i[o+3]=s}return i}let D=(e,t,n)=>e[t]??n,O=(e,t,n)=>e[t]??n;function k(e,n,r,i,a,o){let s=[i/(2*o),a/(2*o)],c=(e=`at`)=>{let t=O(n,e,s);return[t[0]*o,t[1]*o]};switch(e){case`gaussian`:return C(r,i,a,D(n,`radius`,4)*o);case`motion`:{let e=D(n,`angle`,0)*Math.PI/180,t=D(n,`distance`,16)*o,[s,c]=[Math.cos(e)*t,Math.sin(e)*t];return T(r,i,a,Math.max(2,Math.min(64,Math.ceil(t))),(e,t,n)=>[e+s*(n-.5),t+c*(n-.5)])}case`spin`:{let[e,t]=c(),o=D(n,`angle`,10)*Math.PI/180;return T(r,i,a,24,(n,r,i)=>{let a=o*(i-.5),[s,c]=[n-e,r-t];return[e+s*Math.cos(a)-c*Math.sin(a),t+s*Math.sin(a)+c*Math.cos(a)]})}case`zoom`:{let[e,t]=c(),o=D(n,`amount`,.1);return T(r,i,a,24,(n,r,i)=>{let a=1+o*(i-.5);return[e+(n-e)*a,t+(r-t)*a]})}case`lens`:{let e=D(n,`radius`,6)*o,t=D(n,`highlights`,1),s=Math.max(2,Math.min(6,Math.ceil(e/2))),c=[[0,0]];for(let t=1;t<=s;t++){let n=t*7;for(let r=0;r<n;r++){let i=r/n*Math.PI*2+t;c.push([e*t*Math.cos(i)/s,e*t*Math.sin(i)/s])}}let l=new Float32Array(r.length),u=new Float32Array(4);for(let e=0;e<a;e++)for(let n=0;n<i;n++){let o=(e*i+n)*4,s=0;for(let[d,f]of c){S(r,i,a,n+.5+d,e+.5+f,u,0);let c=h(u[0],u[1],u[2]),p=1+t*2*c*c*c*c;for(let e=0;e<4;e++)l[o+e]+=u[e]*p;s+=p}for(let e=0;e<4;e++)l[o+e]/=s}return l}case`sharpen`:{let e=C(r,i,a,D(n,`radius`,1.5)*o),[t,s]=[D(n,`amount`,.8),D(n,`threshold`,0)],c=new Float32Array(r);for(let n=0;n<i*a;n++){let i=n*4,a=r[i+3];for(let n=0;n<3;n++){let o=r[i+n]-e[i+n];Math.abs(o)>=s&&(c[i+n]=Math.max(0,Math.min(a,r[i+n]+o*t)))}}return c}case`highPass`:{let e=C(r,i,a,D(n,`radius`,6)*o),t=new Float32Array(r.length);for(let n=0;n<i*a;n++){let i=n*4,a=r[i+3];t[i+3]=a;for(let n=0;n<3;n++)t[i+n]=p(.5+r[i+n]-e[i+n])*a}return t}case`noise`:{let[e,t,s,c]=[D(n,`amount`,.08),D(n,`scale`,1)*o,D(n,`seed`,1),n.mono!==!1],l=new Float32Array(r);for(let n=0;n<a;n++)for(let a=0;a<i;a++){let o=(n*i+a)*4,u=r[o+3];for(let i=0;i<3;i++){let d=f(a/t,n/t,1,c?s:s+i*13)-.5;l[o+i]=Math.max(0,Math.min(u,r[o+i]+d*e*2*u))}}return l}case`median`:{let e=Math.max(1,Math.min(6,Math.round(D(n,`radius`,1)*o))),t=new Float32Array(r.length),s=[];for(let n=0;n<a;n++)for(let o=0;o<i;o++){s.length=0;for(let t=-e;t<=e;t++)for(let c=-e;c<=e;c++){let e=(Math.max(0,Math.min(a-1,n+t))*i+Math.max(0,Math.min(i-1,o+c)))*4;s.push([h(r[e],r[e+1],r[e+2]),e])}s.sort((e,t)=>e[0]-t[0]);let c=s[s.length>>1][1],l=(n*i+o)*4;for(let e=0;e<4;e++)t[l+e]=r[c+e]}return t}case`emboss`:{let e=D(n,`angle`,135)*Math.PI/180,t=D(n,`height`,2)*o,s=D(n,`amount`,2),[c,l]=[Math.round(Math.cos(e)*t),Math.round(Math.sin(e)*t)],u=new Float32Array(r.length);for(let e=0;e<a;e++)for(let t=0;t<i;t++){let n=(e*i+t)*4,o=(Math.max(0,Math.min(a-1,e+l))*i+Math.max(0,Math.min(i-1,t+c)))*4,d=h(r[n],r[n+1],r[n+2])-h(r[o],r[o+1],r[o+2]),f=p(.5+d*s),m=r[n+3];u[n]=u[n+1]=u[n+2]=f*m,u[n+3]=m}return u}case`ripple`:{let[e,t,s]=[D(n,`amount`,4)*o,D(n,`size`,24)*o,D(n,`seed`,1)];return w(r,i,a,(n,r)=>[n+Math.sin(r/t*Math.PI*2+s)*e,r+Math.sin(n/t*Math.PI*2+s*1.7)*e])}case`displace`:{let[e,t,s]=[D(n,`amount`,8)*o,D(n,`size`,40)*o,D(n,`seed`,1)];return w(r,i,a,(n,r)=>[n+(f(n/t,r/t,3,s)-.5)*e*2,r+(f(n/t,r/t,3,s+7)-.5)*e*2])}case`twirl`:{let[e,t]=c(),[s,l]=[D(n,`radius`,Math.min(i,a)/(2*o))*o,D(n,`angle`,45)*Math.PI/180];return w(r,i,a,(n,r)=>{let[i,a]=[n-e,r-t],o=Math.hypot(i,a);if(o>=s)return[n,r];let c=l*(1-o/s)**2;return[e+i*Math.cos(c)-a*Math.sin(c),t+i*Math.sin(c)+a*Math.cos(c)]})}case`pixelate`:{let e=Math.max(2,Math.round(D(n,`cell`,8)*o)),t=new Float32Array(r.length);for(let n=0;n<a;n+=e)for(let o=0;o<i;o+=e){let s=[0,0,0,0],c=0;for(let t=n;t<Math.min(a,n+e);t++)for(let n=o;n<Math.min(i,o+e);n++){let e=(t*i+n)*4;for(let t=0;t<4;t++)s[t]+=r[e+t];c++}for(let r=n;r<Math.min(a,n+e);r++)for(let n=o;n<Math.min(i,o+e);n++){let e=(r*i+n)*4;for(let n=0;n<4;n++)t[e+n]=s[n]/c}}return t}case`chromatic`:{let[e,t]=c(),s=D(n,`amount`,2)*o/Math.max(i,a),l=new Float32Array(r),u=new Float32Array(4);for(let n=0;n<a;n++)for(let o=0;o<i;o++){let c=(n*i+o)*4,[d,f]=[o+.5-e,n+.5-t];S(r,i,a,e+d*(1+s),t+f*(1+s),u,0),l[c]=u[0],S(r,i,a,e+d*(1-s),t+f*(1-s),u,0),l[c+2]=u[2]}return l}case`vignette`:{let[e,o]=c(),[s,l,u]=[D(n,`amount`,.6),D(n,`radius`,.55),D(n,`outer`,1.05)],d=t(n.color??`#000000`),f=Math.hypot(i,a)/2,h=new Float32Array(r);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let a=(t*i+n)*4,c=s*m(p((Math.hypot(n+.5-e,t+.5-o)/f-l)/Math.max(.01,u-l)));for(let e=0;e<3;e++)h[a+e]=r[a+e]+(d[e]*r[a+3]-r[a+e])*c}return h}case`fog`:{let e=t(n.color??`#c8d0e0`),[s,c]=[O(n,`from`,[0,0])[0]*o,O(n,`from`,[0,0])[1]*o],[l,u]=[O(n,`to`,[0,a/o])[0]*o,O(n,`to`,[0,a/o])[1]*o],[d,h]=[l-s,u-c],g=d*d+h*h||1,[_,v,y,b]=[D(n,`density`,.6),D(n,`patchiness`,.5),D(n,`size`,120)*o,D(n,`seed`,1)],x=new Float32Array(r);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let a=(t*i+n)*4,o=p(((n+.5-s)*d+(t+.5-c)*h)/g),l=v>0?1-v+v*2*f(n/(y*2),t/y,4,b):1,u=p(m(o)*_*l)*e[3];for(let t=0;t<3;t++)x[a+t]=r[a+t]*(1-u)+e[t]*u;x[a+3]=r[a+3]*(1-u)+u}return x}case`rays`:{let[e,t]=c(),[o,s,l,u]=[D(n,`threshold`,.6),D(n,`length`,.6),D(n,`strength`,.8),D(n,`decay`,.96)],d=new Float32Array(r.length);for(let e=0;e<i*a;e++){let t=e*4,n=p((Math.max(r[t],r[t+1],r[t+2])-o)/Math.max(.01,1-o));for(let e=0;e<3;e++)d[t+e]=r[t+e]*n;d[t+3]=1}let f=new Float32Array(4);return E(r,i,a,(n,r,o)=>{let c=1;for(let p=0;p<48;p++){let m=1-p/48*s;S(d,i,a,e+(n-e)*m,t+(r-t)*m,f,0);for(let e=0;e<3;e++)o[e]+=f[e]*c*l/48;c*=u}})}case`flare`:{let[e,s]=c(),l=t(n.color??`#ffe0b0`),[u,d]=[D(n,`size`,60)*o,D(n,`strength`,1)],[f,p]=[i/2,a/2],m=[[-.4,.22,.14],[-.8,.12,.2],[-1.3,.34,.09],[-1.7,.17,.13]];return E(r,i,a,(t,n,r)=>{let i=Math.hypot(t-e,n-s),a=.9*Math.exp(-((i/u)**2))+.25*Math.exp(-i/(u*2.5));a+=.5*Math.exp(-Math.abs(n-s)/(u*.05))*Math.exp(-Math.abs(t-e)/(u*3.5));for(let[r,i,o]of m){let[c,l]=[e+(f-e)*(1-r),s+(p-s)*(1-r)],d=Math.hypot(t-c,n-l)/(u*i*2.2);d<1&&(a+=o*(1-d*d*d*d))}for(let e=0;e<3;e++)r[e]+=l[e]*a*d})}case`texture`:{let[e,t,s]=[D(n,`scale`,3)*o,D(n,`amount`,.3),D(n,`seed`,1)],c=D(n,`angle`,135)*Math.PI/180,[l,u]=[Math.cos(c),Math.sin(c)],d=new Float32Array(r);for(let n=0;n<a;n++)for(let a=0;a<i;a++){let o=(n*i+a)*4,c=1+(f(a/e,n/e,3,s)-f((a+l)/e,(n+u)/e,3,s))*t*3,p=r[o+3];for(let e=0;e<3;e++)d[o+e]=Math.max(0,Math.min(p,r[o+e]*c))}return d}default:throw Error(`no filter \"${String(e)}\"`)}}function A(e){let t=e.match(/[a-zA-Z]|-?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][-+]?\\d+)?/g)??[],n=[],r=null,[i,a,o,s,c,l]=[0,0,0,0,0,0],u=``,d=``,f=0,p=()=>{let n=t[f++];if(n===void 0||/[a-zA-Z]/.test(n))throw Error(`path ${JSON.stringify(e.slice(0,60))}: command ${u} is short of numbers`);return Number(n)},m=()=>{r||(r=[[i,a]],n.push({points:r,closed:!1}))},h=e=>{m();for(let t=1;t<=20;t++)r.push(e(t/20))};for(;f<t.length;){if(/[a-zA-Z]/.test(t[f]))u=t[f++];else if(!u)throw Error(`path ${JSON.stringify(e.slice(0,60))} must start with a command`);let g=u===u.toLowerCase(),[_,v]=g?[i,a]:[0,0];switch(u.toUpperCase()){case`M`:i=_+p(),a=v+p(),o=i,s=a,r=[[i,a]],n.push({points:r,closed:!1}),u=g?`l`:`L`;break;case`L`:i=_+p(),a=v+p(),m(),r.push([i,a]);break;case`H`:i=_+p(),m(),r.push([i,a]);break;case`V`:a=v+p(),m(),r.push([i,a]);break;case`C`:case`S`:{let[e,t]=u.toUpperCase()===`S`?d===`C`||d===`S`?[2*i-c,2*a-l]:[i,a]:[_+p(),v+p()],[n,r,o,s]=[_+p(),v+p(),_+p(),v+p()],[f,m]=[i,a];h(i=>{let a=1-i;return[a*a*a*f+3*a*a*i*e+3*a*i*i*n+i*i*i*o,a*a*a*m+3*a*a*i*t+3*a*i*i*r+i*i*i*s]}),[i,a,c,l]=[o,s,n,r];break}case`Q`:case`T`:{let[e,t]=u.toUpperCase()===`T`?d===`Q`||d===`T`?[2*i-c,2*a-l]:[i,a]:[_+p(),v+p()],[n,r]=[_+p(),v+p()],[o,s]=[i,a];h(i=>{let a=1-i;return[a*a*o+2*a*i*e+i*i*n,a*a*s+2*a*i*t+i*i*r]}),[i,a,c,l]=[n,r,e,t];break}case`Z`:n.length&&(n[n.length-1].closed=!0),i=o,a=s,r=null,u=``;break;default:throw Error(`path command ${u} is not one this draws; there are M L H V C S Q T Z`)}d=u.toUpperCase()===`L`&&d===`M`?`L`:u.toUpperCase()}return n}let j=[`normal`,`multiply`,`screen`,`overlay`,`add`,`softLight`,`hardLight`,`vividLight`,`linearLight`,`pinLight`,`colorDodge`,`colorBurn`,`linearBurn`,`darken`,`lighten`,`difference`,`exclusion`,`subtract`,`divide`,`hue`,`saturation`,`color`,`luminosity`],M={exposure:[-8,8],brightness:[-1,1],contrast:[-1,1],temperature:[-1,1],tint:[-1,1],hue:[-360,360],saturation:[-1,1],lightness:[-1,1],vibrance:[-1,1],posterize:[2,256],threshold:[0,1]};function N(e){if(typeof e!=`object`||!e)return`must be an object of what to change`;let t=e,n=[...Object.keys(M),`levels`,`curves`,`balance`,`blackWhite`,`gradientMap`,`invert`];for(let e of Object.keys(t))if(!n.includes(e))return`has unknown \"${e}\"; there are ${n.join(`, `)}`;if(Object.keys(t).length===0)return`changes nothing`;for(let[e,[n,r]]of Object.entries(M))if(t[e]!==void 0&&!(L(t[e])&&t[e]>=n&&t[e]<=r))return`${e} must be ${n}..${r}`;let r=e=>R(e)&&e.every(e=>e>=0&&e<=1),i=e=>Array.isArray(e)&&e.length>=2&&e.every(r);if(t.levels!==void 0){let e=t.levels;if(typeof e!=`object`||!e)return`levels must be { input?, gamma?, output? }`;for(let t of Object.keys(e))if(![`input`,`gamma`,`output`].includes(t))return`levels has unknown \"${t}\"; there are input, gamma, output`;for(let t of[`input`,`output`])if(e[t]!==void 0&&!r(e[t]))return`levels ${t} must be [low, high], each 0..1`;if(e.gamma!==void 0&&!(L(e.gamma)&&e.gamma>0))return`levels gamma must be positive`}if(t.curves!==void 0)if(Array.isArray(t.curves)){if(!i(t.curves))return`curves must be two or more [in, out], each 0..1`}else{let e=t.curves;if(typeof e!=`object`||!e)return`curves must be [[in, out]...] or { r, g, b }`;for(let[t,n]of Object.entries(e)){if(![`r`,`g`,`b`].includes(t))return`curves has unknown \"${t}\"; there are r, g, b`;if(!i(n))return`curves ${t} must be two or more [in, out], each 0..1`}}if(t.balance!==void 0)for(let[e,n]of Object.entries(t.balance)){if(![`shadows`,`midtones`,`highlights`].includes(e))return`balance has unknown \"${e}\"; there are shadows, midtones, highlights`;if(!(Array.isArray(n)&&n.length===3&&n.every(L)))return`balance ${e} must be [r, g, b]`}return t.blackWhite!==void 0&&typeof t.blackWhite!=`boolean`&&!(Array.isArray(t.blackWhite)&&t.blackWhite.length===3&&t.blackWhite.every(L))?`blackWhite must be true or [r, g, b]`:t.invert!==void 0&&typeof t.invert!=`boolean`?`invert must be true or false`:t.gradientMap!==void 0&&!(Array.isArray(t.gradientMap)&&t.gradientMap.length>=2&&t.gradientMap.every(e=>Array.isArray(e)&&e.length===2&&L(e[0])&&z(e[1])))?`gradientMap must be two or more [0..1, colour]`:null}let P={gaussian:[`radius`],motion:[`angle`,`distance`],spin:[`at`,`angle`],zoom:[`at`,`amount`],lens:[`radius`,`highlights`],sharpen:[`amount`,`radius`,`threshold`],highPass:[`radius`],noise:[`amount`,`scale`,`mono`,`seed`],median:[`radius`],emboss:[`angle`,`height`,`amount`],ripple:[`amount`,`size`,`seed`],displace:[`amount`,`size`,`seed`],twirl:[`at`,`radius`,`angle`],pixelate:[`cell`],chromatic:[`at`,`amount`],vignette:[`at`,`amount`,`radius`,`outer`,`color`],fog:[`color`,`density`,`from`,`to`,`patchiness`,`size`,`seed`],rays:[`at`,`threshold`,`length`,`strength`,`decay`],flare:[`at`,`size`,`color`,`strength`],texture:[`scale`,`amount`,`angle`,`seed`]};function ee(e,t){if(typeof e!=`string`||!Object.prototype.hasOwnProperty.call(P,e))return`filter ${JSON.stringify(e)} must be one of ${Object.keys(P).join(`, `)}`;if(t===void 0)return null;if(typeof t!=`object`||!t)return`params must be an object`;let n=P[e];for(let[r,i]of Object.entries(t)){if(!n.includes(r))return`filter ${e} has unknown \"${r}\"; it takes ${n.join(`, `)}`;if(r===`color`){if(!z(i))return`filter ${e}: color must be #rgb..#rrggbbaa`}else if(r===`at`||r===`from`||r===`to`){if(!R(i))return`filter ${e}: ${r} must be [x, y]`}else if(r===`mono`){if(typeof i!=`boolean`)return`filter ${e}: mono must be true or false`}else if(!L(i))return`filter ${e}: ${r} must be a number`}return null}let F={ink:{hardness:1,taper:[.12,.3]},pen:{hardness:1,roundness:.25,angle:-45},pencil:{hardness:.6,grain:.35,grainScale:1.2,opacity:.75},charcoal:{hardness:.35,grain:.5,grainScale:2.2,dry:.12,opacity:.95},chalk:{hardness:.7,grain:.55,grainScale:6,opacity:.95},flat:{hardness:.85,roundness:.3,dry:.3},oil:{hardness:.65,roundness:.55,dry:.22,wet:.55,opacity:.95},gouache:{hardness:.8,roundness:.5,wet:.2,dry:.08,opacity:.95},watercolor:{hardness:.2,wet:.45,edge:.5,opacity:.45,grain:.05,grainScale:5},marker:{hardness:.9,roundness:.45,angle:-30,opacity:.72},airbrush:{hardness:0,flow:.05},spray:{hardness:.7,dab:.07,scatter:1,spacing:.5,opacity:.9},dry:{hardness:.75,roundness:.35,dry:.65,opacity:.95}},I=[`brush`,`roundness`,`angle`,`grain`,`grainScale`,`dry`,`wet`,`edge`,`scatter`,`dab`,`spacing`,`flow`,`fade`],L=e=>typeof e==`number`&&Number.isFinite(e),R=e=>Array.isArray(e)&&e.length===2&&e.every(L),z=e=>typeof e==`string`&&/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(e);function B(e){if(typeof e==`string`)return z(e)?null:`${JSON.stringify(e)} must be #rgb, #rgba, #rrggbb or #rrggbbaa`;let t=e;if(typeof t!=`object`||!t)return`must be a colour or a gradient`;if(t.type!==`linear`&&t.type!==`radial`&&t.type!==`noise`&&t.type!==`form`&&t.type!==`image`&&t.type!==`grid`)return`a gradient has type linear, radial, noise, form, image or grid`;if(t.type===`grid`){if(!Array.isArray(t.colors)||t.colors.length===0||!t.colors.every(z))return`a grid needs colors: one or more`;for(let e of[`ground`,`off`])if(t[e]!==void 0&&!z(t[e]))return`a grid's ${e} must be a colour`;let e=t.quad;if(e!==void 0&&!(Array.isArray(e)&&e.length===4&&e.every(R)))return`a grid's quad must be four [x, y], in order round from the top left`;if(t.cell===void 0&&t.cells===void 0)return`a grid needs cell: [w, h] in pixels, or cells: [columns, rows]`;for(let e of[`cell`,`cells`])if(t[e]!==void 0&&!(R(t[e])&&t[e].every(e=>e>0)))return`a grid's ${e} must be two positive numbers`;return t.cell!==void 0&&e!==void 0?`a grid on a quad is counted in cells: [columns, rows]`:t.mark!==void 0&&!(R(t.mark)&&t.mark.every(e=>e>0&&e<=1))?`a grid's mark must be [w, h], each above 0 and up to 1`:t.lit!==void 0&&!(L(t.lit)&&t.lit>=0&&t.lit<=1)?`a grid's lit must be 0..1`:t.seed!==void 0&&!Number.isInteger(t.seed)?`a grid's seed must be a whole number`:null}if(t.type===`image`)return typeof t.image==`string`&&t.image?null:`an image fill needs image, the id of an image layer drawn before it`;if(t.type===`form`){if(typeof t.figure!=`string`||!t.figure)return`a form needs figure, the id of a figure drawn before it`;if(t.light!==void 0&&!(Array.isArray(t.light)&&t.light.length===3&&t.light.every(L)))return`a form's light must be [x, y, z], x right, y up, z toward the viewer`}if(t.type===`noise`){if(t.scale!==void 0&&!(L(t.scale)&&t.scale>0))return`noise scale must be a positive number of pixels`;if(t.octaves!==void 0&&!(Number.isInteger(t.octaves)&&t.octaves>=1&&t.octaves<=8))return`noise octaves must be a whole number from 1 to 8`;if(t.seed!==void 0&&!Number.isInteger(t.seed))return`noise seed must be a whole number`}if(t.type===`linear`&&!(R(t.from)&&R(t.to)))return`a linear gradient needs from and to, each [x, y]`;if(t.type===`linear`&&t.from[0]===t.to[0]&&t.from[1]===t.to[1])return`a linear gradient needs from and to apart: at one point it draws a single flat colour`;if(t.type===`radial`&&!(R(t.at)&&L(t.radius)&&t.radius>0))return`a radial gradient needs at: [x, y] and a positive radius`;if(!Array.isArray(t.stops)||t.stops.length<2)return`a gradient needs two stops or more, each [0..1, colour]`;for(let e of t.stops)if(!Array.isArray(e)||e.length!==2||!L(e[0])||!z(e[1]))return`a stop ${JSON.stringify(e)} must be [0..1, colour]`;return null}let te=`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.text.fontSize.font.weight.align.vertical.tracking.vanish.depth.faces.roof.y.edge.reach.ripple.smear.quad.threshold.strength.thin.grain.grainScale.dry.face.within.feather.clipFeather.clipGrow.clipInvert.blendIf.adjust.filter.params`.split(`.`),ne=e=>e.guide??(e.shape===`figure`||e.shape===`image`||e.shape===`perspective`),V=[`rect`,`circle`,`ellipse`,`ring`,`polygon`,`line`,`star`,`gear`,`path`,`pixels`,`paint`,`figure`,`image`,`text`,`block`,`perspective`,`reflect`,`bloom`,`adjust`,`filter`,`group`],re=[`points`,`color`,`to`,`size`,`hardness`,`opacity`,`taper`,`bristles`,`strand`,`spread`,`vary`,`wobble`,`seed`,`smudge`,`erase`,`blend`,...I];function ie(e){if(e.brush!==void 0&&!(typeof e.brush==`string`&&Object.prototype.hasOwnProperty.call(F,e.brush)))return`brush ${JSON.stringify(e.brush)} must be one of ${Object.keys(F).join(`, `)}`;for(let t of[`roundness`,`grain`,`dry`,`wet`,`edge`,`dab`,`flow`])if(e[t]!==void 0&&!(L(e[t])&&e[t]>=0&&e[t]<=1))return`${t} must be 0..1`;if(e.roundness===0||e.dab===0)return`${e.roundness===0?`roundness`:`dab`} must be above 0`;for(let t of[`grainScale`,`spacing`])if(e[t]!==void 0&&!(L(e[t])&&e[t]>0))return`${t} must be positive`;return e.scatter!==void 0&&!(L(e.scatter)&&e.scatter>=0)?`scatter must be 0 or more`:e.angle!==void 0&&!L(e.angle)?`angle must be degrees`:e.fade!==void 0&&!(Array.isArray(e.fade)&&e.fade.length===2&&e.fade.every(e=>L(e)&&e>=0&&e<=1))?`fade must be [start, end], each 0..1`:null}let ae=[`type`,`guides`,`colors`,`count`,`tip`,`size`,`clumps`,`gather`,`flyaway`,`vary`,`wobble`,`opacity`,`taper`,`seed`,`hardness`,...I],oe=[`type`,`line`,`count`,`strokes`,`scale`,`turn`,`both`,`jitter`,`seed`],se=[`type`,`region`,`guides`,`angle`,`tone`,`smudge`,`size`,`length`,`coverage`,`spread`,`vary`,`opacity`,`hardness`,`seed`,`taper`,...I],ce=e=>Array.isArray(e)&&e.length>=2&&e.every(e=>Array.isArray(e)&&(e.length===2||e.length===3)&&e.every(L)),H=3e4;function U(e){let t=t=>{for(let n of t)if(e[n]!==void 0&&!(L(e[n])&&e[n]>=0&&e[n]<=1))return`${n} must be 0..1`;return null},n=e.type===`sweep`?ae:e.type===`along`?oe:se;for(let t of Object.keys(e))if(!n.includes(t))return`has unknown field \"${t}\"; a ${String(e.type)} takes ${n.join(`, `)}`;if(e.seed!==void 0&&!Number.isInteger(e.seed))return`seed must be a whole number`;if(e.type!==`along`){let t=ie(e);if(t)return t}if(e.type===`sweep`){if(!Array.isArray(e.guides)||e.guides.length<2||!e.guides.every(ce))return`needs guides: two or more lines, each two or more [x, y]`;if(!Array.isArray(e.colors)||e.colors.length===0||!e.colors.every(z))return`needs colors: one or more, across the guides`;if(e.tip!==void 0&&!z(e.tip))return`tip must be a colour`;if(!(Number.isInteger(e.count)&&e.count>=1&&e.count<=3e4))return`count must be a whole number from 1 to ${H}`;if(e.clumps!==void 0&&!(Number.isInteger(e.clumps)&&e.clumps>=1))return`clumps must be a whole number of 1 or more`;for(let t of[`size`,`wobble`])if(e[t]!==void 0&&!(L(e[t])&&e[t]>=0))return`${t} must be 0 or more`;return e.taper!==void 0&&!(Array.isArray(e.taper)&&e.taper.length===2&&e.taper.every(e=>L(e)&&e>=0&&e<=1))?`taper must be [start, end], each 0..1`:t([`gather`,`flyaway`,`vary`,`opacity`])}if(e.type===`along`){if(!ce(e.line))return`needs a line: two or more [x, y]`;if(!(Number.isInteger(e.count)&&e.count>=1&&e.count<=2e3))return`count must be a whole number from 1 to 2000`;if(!Array.isArray(e.strokes)||e.strokes.length===0)return`needs strokes, drawn about [0, 0]`;for(let[t,n]of e.strokes.entries()){if(n?.type!==void 0)return`strokes[${t}] must be a plain stroke`;let e=le(n);if(e)return`strokes[${t}] ${e}`}let t=e.scale;if(t!==void 0&&!(L(t)&&t>0)&&!(R(t)&&t.every(e=>e>0)))return`scale must be a positive number, or [start, end]`;for(let t of[`turn`,`jitter`])if(e[t]!==void 0&&!L(e[t]))return`${t} must be a number`;return null}if(e.region!==void 0){if(typeof e.region!=`string`)return`region must be an SVG path or \"@id\"`;if(!e.region.startsWith(`@`))try{A(e.region)}catch(e){return`region: ${e.message}`}}if(e.guides!==void 0&&!(Array.isArray(e.guides)&&e.guides.length>0&&e.guides.every(ce)))return`guides must be one or more lines, each two or more [x, y]`;if(e.angle!==void 0&&!L(e.angle))return`angle must be degrees`;if(e.tone===void 0&&!e.smudge)return`needs a tone, unless it smudges`;if(e.tone!==void 0){let t=B(e.tone);if(t)return`tone ${t}`}for(let t of[`size`,`length`,`coverage`])if(e[t]!==void 0&&!(L(e[t])&&e[t]>0))return`${t} must be positive`;return e.size===void 0?`needs a positive size`:e.spread!==void 0&&!(L(e.spread)&&e.spread>=0)?`spread must be 0 or more degrees`:t([`vary`,`opacity`,`hardness`,`smudge`])}function le(e){if(typeof e!=`object`||!e)return`must be an object`;if(e.type===void 0){let t=ie(e);if(t)return t}if(e.type===`sweep`||e.type===`field`||e.type===`along`)return U(e);if(e.type!==void 0)return`has type \"${String(e.type)}\"; there are sweep, field and along, or none for one stroke`;for(let t of Object.keys(e))if(!re.includes(t))return`has unknown field \"${t}\"; a stroke takes ${re.join(`, `)}`;if(!Array.isArray(e.points)||e.points.length===0||!e.points.every(e=>Array.isArray(e)&&(e.length===2||e.length===3)&&e.every(L)))return`needs points, each [x, y] or [x, y, pressure]`;if(!(L(e.size)&&e.size>0))return`needs a positive size`;if(!e.erase&&!e.smudge&&e.color===void 0)return`needs a color, unless it erases or smudges`;for(let t of[`color`,`to`])if(e[t]!==void 0&&!z(e[t]))return`${t} must be #rgb, #rgba, #rrggbb or #rrggbbaa`;for(let t of[`hardness`,`opacity`,`vary`,`smudge`])if(e[t]!==void 0&&!(L(e[t])&&e[t]>=0&&e[t]<=1))return`${t} must be 0..1`;for(let t of[`strand`,`spread`,`wobble`])if(e[t]!==void 0&&!(L(e[t])&&e[t]>=0))return`${t} must be 0 or more`;return e.bristles!==void 0&&!(Number.isInteger(e.bristles)&&e.bristles>=1&&e.bristles<=200)?`bristles must be a whole number from 1 to 200`:e.seed!==void 0&&!Number.isInteger(e.seed)?`seed must be a whole number`:e.taper!==void 0&&!(Array.isArray(e.taper)&&e.taper.length===2&&e.taper.every(e=>L(e)&&e>=0&&e<=1))?`taper must be [start, end], each 0..1`:e.blend!==void 0&&!j.includes(e.blend)?`blend must be one of ${j.join(`, `)}`:null}function ue(e,t,n){let r=e=>{throw Error(`${t}: ${e}`)};(typeof e!=`object`||!e)&&r(`must be an object`);for(let t of Object.keys(e))te.includes(t)||r(`unknown field \"${t}\"; a layer takes ${te.join(`, `)}`);V.includes(e.shape)||r(`shape ${JSON.stringify(e.shape)} must be one of ${V.join(`, `)}`),e.id!==void 0&&((typeof e.id!=`string`||!e.id)&&r(`id must be a string`),n.has(e.id)&&r(`the id \"${String(e.id)}\" is already used`),n.add(e.id));let i=(t,n=()=>!0)=>{(!L(e[t])||!n(e[t]))&&r(`${t} must be a number${n===o?` above 0`:``}`)},a=t=>{R(e[t])||r(`${t} must be [a, b]`)},o=e=>e>0;switch(e.shape){case`rect`:e.face===void 0&&(a(`at`),a(`size`)),e.radius!==void 0&&!L(e.radius)&&!(Array.isArray(e.radius)&&e.radius.length===4&&e.radius.every(L))&&r(`radius must be a number or four corners`);break;case`circle`:a(`at`),i(`radius`,o);break;case`ellipse`:a(`at`),a(`radii`);break;case`ring`:a(`at`),i(`radius`,o),i(`inner`,o),e.inner>=e.radius&&r(`inner must be less than radius`);break;case`polygon`:case`line`:(!Array.isArray(e.points)||e.points.length<(e.shape===`line`?2:3)||!e.points.every(R))&&r(`points must be ${e.shape===`line`?`two`:`three`} or more [x, y]`),e.shape===`line`&&!e.stroke&&r(`a line needs a stroke: { color, width }`);break;case`star`:case`gear`:a(`at`),i(`radius`,o),i(`inner`,o),(!Number.isInteger(e.count)||e.count<3)&&r(`count must be 3 or more`);break;case`path`:(typeof e.d!=`string`||!e.d.trim())&&r(`d must be an SVG path: M L H V C S Q T Z`);try{A(e.d).every(e=>e.points.length===0)&&r(`d draws nothing`)}catch(e){r(e.message)}break;case`figure`:{R(e.at)||r(`at must be [x, y]: the place on the floor under her`),L(e.height)&&e.height>0||r(`height must be pixels from floor to crown`);for(let t of[`yaw`,`pitch`])e[t]!==void 0&&!L(e[t])&&r(`${t} must be degrees`);e.light!==void 0&&!(Array.isArray(e.light)&&e.light.length===3&&e.light.every(L))&&r(`light must be [x, y, z], x right, y up, z toward the viewer`);let t=e.build;for(let[e,n]of Object.entries(t??{}))[`head`,`shoulders`,`chest`,`waist`,`hips`,`limbs`].includes(e)||r(`build has unknown \"${e}\"; it takes head, shoulders, chest, waist, hips, limbs`),L(n)&&n>0||r(`build ${e} must be positive`);let n=e.pose;for(let e of Object.keys(n??{}))[`rotate`,`move`,`reach`].includes(e)||r(`pose has unknown \"${e}\"; it takes rotate, move, reach`);for(let[e,t]of Object.entries(n??{}))for(let[n,i]of Object.entries(t)){let t=e===`reach`?i.at:i,a=e===`reach`?[2,3]:[3];Array.isArray(t)&&a.includes(t.length)&&t.every(L)||r(`pose ${e} \"${n}\" must be ${e===`reach`?`{ at: [x, y] or [x, y, z] }`:`[x, y, z]`}`)}break}case`text`:(typeof e.text!=`string`||!e.text)&&r(`text must say something`),e.within!==void 0&&!(Array.isArray(e.within)&&e.within.length===4&&e.within.every(e=>L(e)&&e>=0&&e<=1))&&r(`within must be [left, top, right, bottom], each 0..1`),e.face===void 0?e.quad===void 0?(a(`at`),L(e.fontSize)&&e.fontSize>0||r(`fontSize must be positive, in pixels`)):Array.isArray(e.quad)&&e.quad.length===4&&e.quad.every(R)||r(`quad must be four [x, y], in order round from the top left`):typeof e.face!=`string`&&r(`face must name a face of a block, as \"id.a\"`),e.font!==void 0&&typeof e.font!=`string`&&r(`font must be a family name or a font file in the project`),e.align!==void 0&&![`left`,`center`,`right`].includes(e.align)&&r(`align must be left, center or right`),e.tracking!==void 0&&!L(e.tracking)&&r(`tracking must be pixels`),e.thin!==void 0&&!(L(e.thin)&&e.thin>=0)&&r(`thin must be 0 or more pixels`);for(let t of[`grain`,`dry`])e[t]!==void 0&&!(L(e[t])&&e[t]>=0&&e[t]<=1)&&r(`${t} must be 0..1`);e.grainScale!==void 0&&!(L(e.grainScale)&&e.grainScale>0)&&r(`grainScale must be positive`),e.fill===void 0&&e.stroke===void 0&&r(`it needs a fill or a stroke, or it draws nothing`);break;case`adjust`:{let t=N(e.adjust);t&&r(`adjust ${t}`);break}case`filter`:{let t=ee(e.filter,e.params);t&&r(t);break}case`bloom`:for(let t of[`threshold`,`strength`])e[t]!==void 0&&!(L(e[t])&&e[t]>=0)&&r(`${t} must be 0 or more`);e.threshold!==void 0&&e.threshold>1&&r(`threshold must be 0..1`),e.radius!==void 0&&!(L(e.radius)&&e.radius>0)&&r(`radius must be positive, in pixels`);break;case`perspective`:(!Array.isArray(e.vanish)||e.vanish.length===0||!e.vanish.every(R))&&r(`vanish must be one or more [x, y]`);break;case`block`:a(`at`),L(e.height)&&e.height>0||r(`height must be pixels, from the corner at its foot up to its top`),(!Array.isArray(e.vanish)||e.vanish.length<1||e.vanish.length>2||!e.vanish.every(R))&&r(`vanish must be one or two [x, y], where its faces recede to`),(!Array.isArray(e.depth)||e.depth.length!==e.vanish.length||!e.depth.every(e=>L(e)&&e>0&&e<=1))&&r(`depth must give each vanishing point how far the face runs toward it, each above 0 and up to 1`),(!Array.isArray(e.faces)||e.faces.length!==e.vanish.length)&&r(`faces must give one fill for each vanishing point`);for(let t of e.faces){let e=B(t);e&&r(`face ${e}`)}if(e.roof!==void 0){let t=B(e.roof);t&&r(`roof ${t}`)}break;case`reflect`:!L(e.y)&&!(Array.isArray(e.edge)&&e.edge.length>=2&&e.edge.every(R))&&r(`y must be the line it mirrors about, or edge two or more [x, y] along where things meet the ground`);for(let t of[`reach`,`ripple`,`smear`])e[t]!==void 0&&!(L(e[t])&&e[t]>=0)&&r(`${t} must be 0 or more pixels`);break;case`image`:(typeof e.src!=`string`||!e.src)&&r(`src must be the path of a picture in the project`),e.at!==void 0&&!R(e.at)&&r(`at must be [x, y]`),e.size!==void 0&&!R(e.size)&&r(`size must be [w, h]`);break;case`paint`:Array.isArray(e.strokes)||r(`strokes must be an array, which may start empty`),e.face!==void 0&&typeof e.face!=`string`&&r(`face must name a face of a block, as \"id.a\"`),e.from!==void 0&&e.from!==`below`&&r(`from must be \"below\"`),e.from!==void 0&&(e.fill!==void 0||e.effects!==void 0||e.blend!==void 0)&&r(`from \"below\" works on the picture itself, and takes no fill, effects or blend`),e.strokes.forEach((e,t)=>{let n=le(e);n&&r(`stroke ${t} ${n}`)});break;case`pixels`:{(!Array.isArray(e.rows)||e.rows.length===0||!e.rows.every(e=>typeof e==`string`))&&r(`rows must be strings, one character a pixel`);let t=e.palette;(typeof t!=`object`||!t)&&r(`palette must be { character: colour }`);for(let[e,n]of Object.entries(t))[...e].length!==1&&r(`palette key ${JSON.stringify(e)} must be one character`),z(n)||r(`palette \"${e}\" ${JSON.stringify(n)} must be a colour`);let n=new Set(Object.keys(t)),s=e.rows[0].length;e.rows.forEach((e,t)=>{[...e].length!==s&&r(`row ${t} is ${[...e].length} wide and row 0 is ${s}: a slip here shifts everything after it`);for(let i of e)i!==`.`&&i!==` `&&!n.has(i)&&r(`row ${t} has \"${i}\", which is not in the palette; \".\" and \" \" are nothing`)}),e.scale!==void 0&&i(`scale`,o),e.at!==void 0&&a(`at`);break}case`group`:Array.isArray(e.layers)||r(`a group needs layers`),e.layers.forEach((e,r)=>ue(e,`${t}.layers[${r}]`,n))}if(e.fill!==void 0){let t=B(e.fill);t&&r(`fill ${t}`)}if(e.stroke!==void 0){let t=e.stroke;(typeof t!=`object`||!t||!L(t.width)||t.width<=0)&&r(`stroke must be { color, width, align? }`);let n=B(t.color);n&&r(`stroke color ${n}`),t.align!==void 0&&![`center`,`inside`,`outside`].includes(t.align)&&r(`stroke align must be center, inside or outside`),t.join!==void 0&&![`round`,`miter`,`bevel`].includes(t.join)&&r(`stroke join must be round, miter or bevel`),t.cap!==void 0&&![`round`,`butt`,`square`].includes(t.cap)&&r(`stroke cap must be round, butt or square`)}![`group`,`pixels`,`paint`,`figure`,`image`,`text`,`block`,`perspective`,`reflect`,`bloom`,`adjust`,`filter`,`line`].includes(e.shape)&&e.fill===void 0&&e.stroke===void 0&&!e.erase&&r(`it needs a fill or a stroke, or it draws nothing`),e.from!==void 0&&e.shape!==`paint`&&r(`from is for a paint layer`),e.guide!==void 0&&typeof e.guide!=`boolean`&&r(`guide must be true or false`),e.blur!==void 0&&!(L(e.blur)&&e.blur>=0)&&r(`blur must be 0 or more, in pixels`),e.blur&&e.erase&&r(`blur does not go with erase; put what cuts in a group with what it cuts, and blur the group`),e.opacity!==void 0&&!(L(e.opacity)&&e.opacity>=0&&e.opacity<=1)&&r(`opacity must be 0..1`),e.blend!==void 0&&!j.includes(e.blend)&&r(`blend must be one of ${j.join(`, `)}`);for(let t of[`feather`,`clipFeather`])e[t]!==void 0&&!(L(e[t])&&e[t]>=0)&&r(`${t} must be 0 or more pixels`);if(e.clipGrow!==void 0&&!L(e.clipGrow)&&r(`clipGrow must be pixels, more to grow what it clips to and less to shrink it`),e.clipInvert!==void 0&&typeof e.clipInvert!=`boolean`&&r(`clipInvert must be true or false`),e.blendIf!==void 0&&!(Array.isArray(e.blendIf)&&(e.blendIf.length===2||e.blendIf.length===3)&&e.blendIf.every(e=>L(e)&&e>=0&&e<=1))&&r(`blendIf must be [low, high] or [low, high, softness], each 0..1`),e.mirror!==void 0&&e.mirror!==`x`&&e.mirror!==`y`&&r(`mirror must be x or y`),e.clip!==void 0&&typeof e.clip!=`string`&&r(`clip must be a layer id`),e.transform!==void 0){let t=e.transform;for(let e of Object.keys(t))[`translate`,`rotate`,`scale`,`origin`].includes(e)||r(`transform has an unknown field \"${e}\"`);t.translate!==void 0&&!R(t.translate)&&r(`transform.translate must be [x, y]`),t.origin!==void 0&&!R(t.origin)&&r(`transform.origin must be [x, y]`),t.rotate!==void 0&&!L(t.rotate)&&r(`transform.rotate must be degrees`),t.scale!==void 0&&!L(t.scale)&&!R(t.scale)&&r(`transform.scale must be a number or [x, y]`)}if(e.effects!==void 0){Array.isArray(e.effects)||r(`effects must be an array`);for(let t of e.effects){if([`shadow`,`glow`,`innerShadow`,`innerGlow`,`bevel`,`overlay`].includes(t?.type)||r(`an effect has type ${JSON.stringify(t?.type)}; there are shadow, glow, innerShadow, innerGlow, bevel, overlay`),t.type===`overlay`){let e=B(t.fill);e&&r(`effect overlay: fill ${e}`)}t.blend!==void 0&&!j.includes(t.blend)&&r(`effect ${String(t.type)}: blend must be one of ${j.join(`, `)}`),t.shade!==void 0&&!z(t.shade)&&r(`effect ${String(t.type)}: shade must be #rgb..#rrggbbaa`);for(let e of Object.keys(t))[`type`,`color`,`x`,`y`,`blur`,`opacity`,`size`,`angle`,`depth`,`shade`,`fill`,`blend`].includes(e)||r(`effect ${String(t.type)} has an unknown field \"${e}\"`);t.color!==void 0&&!z(t.color)&&r(`effect ${String(t.type)}: color must be #rgb..#rrggbbaa`);for(let e of[`x`,`y`,`blur`,`opacity`,`size`,`angle`,`depth`])t[e]!==void 0&&!L(t[e])&&r(`effect ${String(t.type)}: ${e} must be a number`)}}}function de(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`an image source must be { size, layers }`);let t=e;for(let e of Object.keys(t))if(![`version`,`size`,`background`,`tile`,`material`,`layers`].includes(e))throw Error(`unknown field \"${e}\"; an image has version, size, background, tile, material, layers`);if(t.tile!==void 0&&typeof t.tile!=`boolean`)throw Error(`tile must be true or false`);if(t.version!==void 0&&t.version!==1)throw Error(`version ${String(t.version)} is not one this editor reads (1)`);let[n,r]=typeof t.size==`number`?[t.size,t.size]:R(t.size)?t.size:[NaN,NaN];if(!Number.isInteger(n)||!Number.isInteger(r)||n<1||r<1||n>2048||r>2048)throw Error(`size must be a whole number or [width, height], 1..2048`);if(t.background!==void 0&&!z(t.background))throw Error(`background must be a colour; leave it out for a transparent picture`);if(!Array.isArray(t.layers))throw Error(`layers must be an array`);let i=new Set;if(t.layers.forEach((e,t)=>ue(e,`layer ${t}${e?.id?` \"${String(e.id)}\"`:``}`,i)),t.material!==void 0){let e=t.material;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`material must be { relief?, height?, roughness?, metal? }`);for(let t of Object.keys(e))if(![`relief`,`height`,`roughness`,`metal`].includes(t))throw Error(`material has unknown \"${t}\"; it takes relief, height, roughness, metal`);if(e.relief!==void 0&&!(L(e.relief)&&e.relief>=0&&e.relief<=64))throw Error(`material.relief must be 0..64, in pixels`);let n=(e,t)=>{if(!Array.isArray(t)||t.length===0)throw Error(`material.${e} must be layers, one or more`);t.forEach((t,n)=>ue(t,`material.${e} layer ${n}${t?.id?` \"${String(t.id)}\"`:``}`,i))};e.height!==void 0&&n(`height`,e.height);for(let t of[`roughness`,`metal`]){let r=e[t];if(r!==void 0)if(L(r)){if(r<0||r>1)throw Error(`material.${t} must be 0..1, or layers`)}else n(t,r)}}return{version:1,...t}}let fe=e=>{let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]},W=[1,0,0,1,0,0],pe=0,me=0,G=(e,t)=>[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]],K=(e,[t,n])=>[e[0]*t+e[2]*n+e[4],e[1]*t+e[3]*n+e[5]];function he(e){let t=e[0]*e[3]-e[1]*e[2]||1e-12;return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[3]*e[4])/t,(e[1]*e[4]-e[0]*e[5])/t]}function ge(e,t){if(!e)return W;let[n,r]=e.origin??t,i=(e.rotate??0)*Math.PI/180,[a,o]=typeof e.scale==`number`?[e.scale,e.scale]:e.scale??[1,1],[s,c]=e.translate??[0,0],l=[1,0,0,1,s+n,c+r];return l=G(l,[Math.cos(i),Math.sin(i),-Math.sin(i),Math.cos(i),0,0]),l=G(l,[a,0,0,o,0,0]),G(l,[1,0,0,1,-n,-r])}function _e(e,t,n,r){let i=Math.max(48,Math.ceil(Math.max(n,r)*2));return Array.from({length:i},(a,o)=>[e+n*Math.cos(o/i*Math.PI*2),t+r*Math.sin(o/i*Math.PI*2)])}function ve(e,t,n,r,i){let a=typeof i==`number`?[i,i,i,i]:i,o=Math.min(n,r)/2,[s,c,l,u]=[0,1,2,3].map(e=>Math.max(0,Math.min(o,a[e]??0))),d=[],f=(e,t,n,r)=>{if(n<=0){d.push([e,t]);return}let i=Math.max(4,Math.ceil(n));for(let a=0;a<=i;a++){let o=r+a/i*(Math.PI/2);d.push([e+n*Math.cos(o),t+n*Math.sin(o)])}};return f(e+s,t+s,s,Math.PI),f(e+n-c,t+c,c,-Math.PI/2),f(e+n-l,t+r-l,l,0),f(e+u,t+r-u,u,Math.PI/2),d}function ye(e){let t=e=>[{points:e,closed:!0}];switch(e.shape){case`rect`:{let[n,r]=e.at,[i,a]=e.size;return{runs:t(ve(n,r,i,a,e.radius??0)),middle:[n+i/2,r+a/2]}}case`circle`:{let[n,r]=e.at;return{runs:t(_e(n,r,e.radius,e.radius)),middle:[n,r]}}case`ellipse`:{let[n,r]=e.at,[i,a]=e.radii;return{runs:t(_e(n,r,i,a)),middle:[n,r]}}case`ring`:{let[n,r]=e.at,i=_e(n,r,e.inner,e.inner).reverse();return{runs:[...t(_e(n,r,e.radius,e.radius)),...t(i)],middle:[n,r]}}case`polygon`:case`line`:{let t=e.points,n=t.reduce((e,n)=>[e[0]+n[0]/t.length,e[1]+n[1]/t.length],[0,0]);return{runs:[{points:t,closed:e.shape===`polygon`}],middle:n}}case`star`:case`gear`:{let[n,r]=e.at,i=e.count,a=e.radius,o=e.inner,s=[],c=(e.turn??-90)*Math.PI/180;if(e.shape===`star`)for(let e=0;e<i*2;e++){let t=e%2==0?a:o,l=c+e/(i*2)*Math.PI*2;s.push([n+t*Math.cos(l),r+t*Math.sin(l)])}else{let t=Math.PI*2/i,l=(e.tooth??.3)*t,u=l*1.5;for(let e=0;e<i;e++){let i=c+e*t;for(let[e,t]of[[o,-u],[a,-l],[a,l],[o,u]])s.push([n+e*Math.cos(i+t),r+e*Math.sin(i+t)])}}return{runs:t(s),middle:[n,r]}}case`path`:{let t=A(e.d),n=t.flatMap(e=>e.points);if(n.length===0)throw Error(`path draws nothing`);return{runs:t,middle:n.reduce((e,t)=>[e[0]+t[0]/n.length,e[1]+t[1]/n.length],[0,0])}}default:return{runs:[],middle:[0,0]}}}let be=[[0,0],[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[1,-1],[-1,1],[1,1]];function xe(e,t,n,r,i,a){let[o,s,c,l]=[1/0,1/0,-1/0,-1/0];for(let t of e)t[0]<o&&(o=t[0]),t[0]>c&&(c=t[0]),t[1]<s&&(s=t[1]),t[1]>l&&(l=t[1]);return c+t+r>0&&o+t-r<i&&l+n+r>0&&s+n-r<a}function Se(e,t,n,r,a){if(!i())return a(0,0);let o=null;for(let[i,s]of be){let[c,l]=[i*n,s*r];if((i!==0||s!==0)&&!xe(e(),c,l,t,n,r))continue;let u=a(c,l);if(!o){o=u;continue}for(let e=0;e<o.length;e++)u[e]>o[e]&&(o[e]=u[e])}return o??new Float32Array(n*r)}function Ce(e,t,n){return Se(()=>e.flat(),1,t,n,(r,i)=>we(r===0&&i===0?e:e.map(e=>e.map(([e,t])=>[e+r,t+i])),t,n))}function we(e,t,n){let r=new Float32Array(t*n),i=[],a=1/0,o=-1/0;for(let t of e)for(let e=0;e<t.length;e++){let[n,r]=[t[e],t[(e+1)%t.length]];if(n[1]===r[1])continue;let s=n[1]<r[1];i.push(s?{x0:n[0],y0:n[1],x1:r[0],y1:r[1],dir:1}:{x0:r[0],y0:r[1],x1:n[0],y1:n[1],dir:-1}),a=Math.min(a,n[1],r[1]),o=Math.max(o,n[1],r[1])}if(i.length===0)return r;let s=1/8,c=Math.max(0,Math.floor(a)),l=Math.min(n-1,Math.ceil(o)),u=[];for(let e=c;e<=l;e++)for(let n=0;n<8;n++){let a=e+(n+.5)*s;u.length=0;for(let e of i)a<e.y0||a>=e.y1||u.push({x:e.x0+(a-e.y0)/(e.y1-e.y0)*(e.x1-e.x0),dir:e.dir});if(u.length<2)continue;u.sort((e,t)=>e.x-t.x);let o=0;for(let n=0;n+1<u.length;n++){if(o+=u[n].dir,o===0)continue;let[i,a]=[Math.max(0,u[n].x),Math.min(t,u[n+1].x)];if(a<=i)continue;let[c,l]=[Math.floor(i),Math.min(t-1,Math.floor(a))],d=e*t;if(c===l){r[d+c]+=(a-i)*s;continue}r[d+c]+=(c+1-i)*s;for(let e=c+1;e<l;e++)r[d+e]+=s;r[d+l]+=(a-l)*s}}for(let e=0;e<r.length;e++)r[e]>1&&(r[e]=1);return r}function Te(e,t,n,r,i=`round`,a=`round`){return Se(()=>e.flatMap(e=>e.points),t*(i===`miter`?10:1)+2,n,r,(o,s)=>Ee(o===0&&s===0?e:e.map(e=>({closed:e.closed,points:e.points.map(([e,t])=>[e+o,t+s])})),t,n,r,i,a))}function Ee(e,t,n,r,i=`round`,a=`round`){let o=new Float32Array(n*r),s=t/2,c=(e,t)=>{let[i,a]=[Math.max(0,Math.floor(Math.min(e[0],t[0])-s-1)),Math.min(n-1,Math.ceil(Math.max(e[0],t[0])+s+1))],[c,l]=[Math.max(0,Math.floor(Math.min(e[1],t[1])-s-1)),Math.min(r-1,Math.ceil(Math.max(e[1],t[1])+s+1))],[u,d]=[t[0]-e[0],t[1]-e[1]],f=u*u+d*d;for(let t=c;t<=l;t++)for(let r=i;r<=a;r++){let[i,a]=[r+.5-e[0],t+.5-e[1]],c=f>0?Math.max(0,Math.min(1,(i*u+a*d)/f)):0,l=Math.max(0,Math.min(1,s-Math.hypot(i-u*c,a-d*c)+.5));l>o[t*n+r]&&(o[t*n+r]=l)}},l=e=>{let t=0;for(let n=0;n<e.length;n++){let[r,i]=[e[n],e[(n+1)%e.length]];t+=r[0]*i[1]-i[0]*r[1]}if(t===0)return;let i=e.map((n,r)=>{let i=e[(r+1)%e.length],a=Math.hypot(i[0]-n[0],i[1]-n[1])||1;return{x:n[0],y:n[1],nx:-(i[1]-n[1])/a*Math.sign(t),ny:(i[0]-n[0])/a*Math.sign(t)}}),[a,s]=[e.map(e=>e[0]),e.map(e=>e[1])],[c,l]=[Math.max(0,Math.floor(Math.min(...a)-1)),Math.min(n-1,Math.ceil(Math.max(...a)+1))],[u,d]=[Math.max(0,Math.floor(Math.min(...s)-1)),Math.min(r-1,Math.ceil(Math.max(...s)+1))];for(let e=u;e<=d;e++)for(let t=c;t<=l;t++){let r=1/0;for(let n of i)r=Math.min(r,(t+.5-n.x)*n.nx+(e+.5-n.y)*n.ny);if(r<=-.75)continue;let a=1;if(r<.75){let n=0;for(let r=0;r<6;r++)for(let a=0;a<6;a++){let[o,s]=[t+(a+.5)/6,e+(r+.5)/6];i.every(e=>(o-e.x)*e.nx+(s-e.y)*e.ny>=0)&&n++}a=n/36}a>o[e*n+t]&&(o[e*n+t]=a)}};for(let t of e){if(i===`round`&&a===`round`){let e=t.closed?t.points.length:t.points.length-1;for(let n=0;n<e;n++)c(t.points[n],t.points[(n+1)%t.points.length]);continue}let e=t.points.filter((e,t,n)=>t===0||Math.hypot(e[0]-n[t-1][0],e[1]-n[t-1][1])>1e-6);if(t.closed&&e.length>1&&Math.hypot(e[0][0]-e[e.length-1][0],e[0][1]-e[e.length-1][1])<=1e-6&&e.pop(),e.length<2){e[0]&&a!==`butt`&&c(e[0],e[0]);continue}let n=t.closed?e.length:e.length-1,r=t=>{let[n,r]=[e[t],e[(t+1)%e.length]],i=Math.hypot(r[0]-n[0],r[1]-n[1]);return[(r[0]-n[0])/i,(r[1]-n[1])/i]};for(let i=0;i<n;i++){let[o,c]=[e[i],e[(i+1)%e.length]],u=r(i),[d,f]=[-u[1]*s,u[0]*s],p=e=>e?a===`square`?s:0:.75,[m,h]=[p(!t.closed&&i===0),p(!t.closed&&i===n-1)],[g,_,v,y]=[o[0]-u[0]*m,o[1]-u[1]*m,c[0]+u[0]*h,c[1]+u[1]*h];l([[g+d,_+f],[v+d,y+f],[v-d,y-f],[g-d,_-f]])}!t.closed&&a===`round`&&(c(e[0],e[0]),c(e[e.length-1],e[e.length-1]));for(let n=+!t.closed;n<(t.closed?e.length:e.length-1);n++){let t=e[n],[a,o]=[r((n-1+e.length)%e.length),r(n)],u=a[0]*o[1]-a[1]*o[0];if(i===`round`){c(t,t);continue}if(Math.abs(u)<1e-6)continue;let d=u>0?-1:1,[f,p]=[[-a[1]*d,a[0]*d],[-o[1]*d,o[0]*d]],[m,h]=[[t[0]+f[0]*s,t[1]+f[1]*s],[t[0]+p[0]*s,t[1]+p[1]*s]],[g,_]=[f[0]+p[0],f[1]+p[1]],v=Math.hypot(g,_),y=v>0?2/v:1/0;l(i===`miter`&&y<=10?[t,m,[t[0]+g/v*s*y,t[1]+_/v*s*y],h]:[t,m,h])}}return o}function De(e,t,n,r,a){let[o,s]=[Math.round(r),Math.round(a)];if(o===0&&s===0)return e;let c=new Float32Array(t*n);if(i()){for(let r=0;r<n;r++){let i=((r-s)%n+n)%n;for(let n=0;n<t;n++)c[r*t+n]=e[i*t+((n-o)%t+t)%t]}return c}for(let r=0;r<n;r++){let i=r-s;if(!(i<0||i>=n))for(let n=0;n<t;n++){let a=n-o;a>=0&&a<t&&(c[r*t+n]=e[i*t+a])}}return c}function Oe(e){let[[t,n],[r,i],[a,o],[s,c]]=e,[l,u,d,f,p,m]=[r-a,s-a,t-r+a-s,i-o,c-o,n-i+o-c],h=l*p-u*f;if(Math.abs(h)<1e-9)return null;let g=(d*p-u*m)/h,_=(l*m-d*f)/h,[v,y,b,x,S,C]=[r-t+g*r,s-t+_*s,t,i-n+g*i,c-n+_*c,n],[w,T,E,D,O,k,A,j,M]=[S-C*_,b*_-y,y*C-b*S,C*g-x,v-b*g,b*x-v*C,x*_-S*g,y*g-v*_,v*S-y*x];return(e,t)=>{let n=A*e+j*t+M;return[(w*e+T*t+E)/n,(D*e+O*t+k)/n]}}function ke(e){let[[t,n],[r,i],[a,o],[s,c]]=e,[l,u,d,f,p,m]=[r-a,s-a,t-r+a-s,i-o,c-o,n-i+o-c],h=l*p-u*f||1e-9,g=(d*p-u*m)/h,_=(l*m-d*f)/h,[v,y,b,x,S,C]=[r-t+g*r,s-t+_*s,t,i-n+g*i,c-n+_*c,n];return(e,t)=>{let n=g*e+_*t+1;return[(v*e+y*t+b)/n,(x*e+S*t+C)/n]}}function Ae(e,t){let[n,r]=e.face.replace(/^@/,``).split(`.`),i=r?t.blocks.get(n)?.[r]:void 0;if(!i)return t.notes.push(`layer ${e.id??e.shape}: face \"${e.face}\" names no face of a block drawn before it, so it drew nothing`),null;if(!e.within)return i;let a=ke(i),[o,s,c,l]=e.within;return[a(o,s),a(c,s),a(c,l),a(o,l)]}function je(e,n){let r=e.colors.map(t),i=e.ground?t(e.ground):[0,0,0,0],a=e.off?t(e.off):i,[o,s]=e.mark??[.6,.6],[c,l]=[e.lit??1,e.seed??1],u=he(n),d=e.quad?Oe(e.quad):null,[f,p]=e.cells??[1,1],[m,h]=e.cell??[1,1],g=(e,t)=>{let n,g;if(d){let r=d(e,t);if(r[0]<0||r[1]<0||r[0]>1||r[1]>1)return i;[n,g]=[r[0]*f,r[1]*p]}else{let r=K(u,[e,t]);[n,g]=[r[0]/m,r[1]/h]}let[_,v]=[Math.floor(n),Math.floor(g)];return Math.abs(n-_-.5)>o/2||Math.abs(g-v-.5)>s/2?i:$(l*41+_,v)>=c?a:r[Math.floor($(l*43+v,_)*r.length)%r.length]};return(e,t)=>{let n=[0,0,0,0];for(let r=0;r<3;r++)for(let i=0;i<3;i++){let a=g(e-.5+(i+.5)/3,t-.5+(r+.5)/3);n[0]+=a[0]*a[3],n[1]+=a[1]*a[3],n[2]+=a[2]*a[3],n[3]+=a[3]}let r=n[3];return r>0?[n[0]/r,n[1]/r,n[2]/r,r/9]:[0,0,0,0]}}function q(e,n,r,a=0){if(typeof e==`string`){let n=t(e);return()=>n}let o=[...e.type===`image`||e.type===`grid`?[]:e.stops].map(([e,n])=>[e,t(n)]).sort((e,t)=>e[0]-t[0]),s=he(n),c=e=>{if(e<=o[0][0])return o[0][1];for(let t=1;t<o.length;t++)if(e<=o[t][0]){let[n,r]=o[t-1],[i,a]=o[t],s=(e-n)/Math.max(1e-6,i-n);return[r[0]+(a[0]-r[0])*s,r[1]+(a[1]-r[1])*s,r[2]+(a[2]-r[2])*s,r[3]+(a[3]-r[3])*s]}return o[o.length-1][1]};if(e.type===`image`){let t=r?.images.get(e.image);return t?(e,n)=>{let r=(Math.floor(n)*a+Math.floor(e))*4;return[t[r]??0,t[r+1]??0,t[r+2]??0,t[r+3]??0]}:(r?.notes.push(`a fill names image \"${e.image}\", which was not drawn before it`),()=>[0,0,0,0])}if(e.type===`grid`)return je(e,n);if(e.type===`form`){let t=r?.figures.get(e.figure);if(!t)return r?.notes.push(`a form names figure \"${e.figure}\", which was not drawn before it`),()=>c(0);let n=e.light?fe(e.light):t.light;return(e,r)=>{let i=Math.floor(r)*a+Math.floor(e),[o,s,l]=[t.normals[i*3]??0,t.normals[i*3+1]??0,t.normals[i*3+2]??0];return c(.5+.5*(o*n[0]+s*n[1]+l*n[2]))}}if(e.type===`noise`){let[t,n,r]=[e.scale??32,e.octaves??4,e.seed??0];if(i()&&pe>0){let[e,i]=[Math.max(1,Math.round(pe/t)),Math.max(1,Math.round(me/t))];return(t,a)=>c(f((t-.5)/pe*e,(a-.5)/me*i,n,r,e,i))}return(e,i)=>{let a=K(s,[e-.5,i-.5]);return c(f(a[0]/t,a[1]/t,n,r))}}if(e.type===`linear`){let[t,n]=[e.from,e.to],[r,i]=[n[0]-t[0],n[1]-t[1]],a=r*r+i*i||1;return(e,n)=>{let o=K(s,[e,n]);return c(((o[0]-t[0])*r+(o[1]-t[1])*i)/a)}}let[l,u]=e.at,d=e.radius;return(e,t)=>{let n=K(s,[e,t]);return c(Math.hypot(n[0]-l,n[1]-u)/d)}}var Me=class{constructor(e,t){this.w=e,this.h=t,this.px=new Float32Array(e*t*4)}};let Ne=(e,t)=>{if(t<=.5)return e-(1-2*t)*e*(1-e);let n=e<=.25?((16*e-12)*e+4)*e:Math.sqrt(e);return e+(2*t-1)*(n-e)},Pe=(e,t)=>e<=0?0:t>=1?1:Math.min(1,e/(1-t)),Fe=(e,t)=>e>=1?1:t<=0?0:1-Math.min(1,(1-e)/t),Ie=(e,t)=>t<.5?2*e*t:1-2*(1-e)*(1-t),Le=(e,t,n)=>{switch(e){case`multiply`:return t*n;case`screen`:return t+n-t*n;case`overlay`:return Ie(n,t);case`add`:return Math.min(1,t+n);case`softLight`:return Ne(t,n);case`hardLight`:return Ie(t,n);case`vividLight`:return n<.5?Fe(t,2*n):Pe(t,2*n-1);case`linearLight`:return Math.max(0,Math.min(1,t+2*n-1));case`pinLight`:return n<.5?Math.min(t,2*n):Math.max(t,2*n-1);case`colorDodge`:return Pe(t,n);case`colorBurn`:return Fe(t,n);case`linearBurn`:return Math.max(0,t+n-1);case`darken`:return Math.min(t,n);case`lighten`:return Math.max(t,n);case`difference`:return Math.abs(t-n);case`exclusion`:return t+n-2*t*n;case`subtract`:return Math.max(0,t-n);case`divide`:return n<=0?1:Math.min(1,t/n);default:return n}};function Re(e,t){let n=t-h(e[0],e[1],e[2]),r=[e[0]+n,e[1]+n,e[2]+n],i=h(r[0],r[1],r[2]),[a,o]=[Math.min(...r),Math.max(...r)];if(a<0)for(let e=0;e<3;e++)r[e]=i+(r[e]-i)*i/(i-a);if(o>1)for(let e=0;e<3;e++)r[e]=i+(r[e]-i)*(1-i)/(o-i);return r}let ze=e=>Math.max(...e)-Math.min(...e);function Be(e,t){let[n,r]=[Math.min(...e),Math.max(...e)];return r===n?[0,0,0]:[(e[0]-n)*t/(r-n),(e[1]-n)*t/(r-n),(e[2]-n)*t/(r-n)]}function Ve(e,t,n){switch(e){case`hue`:return Re(Be(n,ze(t)),h(t[0],t[1],t[2]));case`saturation`:return Re(Be(t,ze(n)),h(t[0],t[1],t[2]));case`color`:return Re(n,h(t[0],t[1],t[2]));default:return Re(t,h(n[0],n[1],n[2]))}}let He=new Set([`hue`,`saturation`,`color`,`luminosity`]);function J(e,t,n,r,i,a,o){if(a<=0)return;let s=e.px,c=t*4,l=s[c+3];if(o===`normal`||l<=0)s[c]=s[c]*(1-a)+n*a,s[c+1]=s[c+1]*(1-a)+r*a,s[c+2]=s[c+2]*(1-a)+i*a;else{let[e,t,u]=[s[c]/l,s[c+1]/l,s[c+2]/l];if(He.has(o)){let d=Ve(o,[e,t,u],[n,r,i]),[f,p,m]=[(1-l)*n+l*d[0],(1-l)*r+l*d[1],(1-l)*i+l*d[2]];s[c]=s[c]*(1-a)+f*a,s[c+1]=s[c+1]*(1-a)+p*a,s[c+2]=s[c+2]*(1-a)+m*a,s[c+3]=l+a-l*a;return}let d=(e,t)=>(1-l)*t+l*Le(o,e,t);s[c]=s[c]*(1-a)+d(e,n)*a,s[c+1]=s[c+1]*(1-a)+d(t,r)*a,s[c+2]=s[c+2]*(1-a)+d(u,i)*a}s[c+3]=l+a-l*a}function Ue(e,n,r){let{w:i,h:a}=n,s=o(r,i,a,Math.max(.5,(e.size??4)/2)),c=(e.angle??225)*Math.PI/180,[l,u]=[Math.cos(c),Math.sin(c)],[d,f,p,m]=t(e.color??`#ffffff`),[h,g,_,v]=t(e.shade??`#000000`),y=(e.depth??1)*(e.size??4)*2,b=e.opacity??.8;for(let e=1;e<a-1;e++)for(let t=1;t<i-1;t++){let a=e*i+t;if(r[a]<=0)continue;let o=-((s[a+1]-s[a-1])*l+(s[a+i]-s[a-i])*u)*y;o>0?J(n,a,d,f,p,Math.min(1,o)*b*m*r[a],`screen`):o<0&&J(n,a,h,g,_,Math.min(1,-o)*b*v*r[a],`multiply`)}}function Y(e,n,r,i){let{w:a,h:s}=r;for(let c of e??[]){let e=c.type===`shadow`||c.type===`glow`;if(e!==n)continue;if(c.type===`bevel`){Ue(c,r,i);continue}if(c.type===`overlay`){let e=q(c.fill,W);for(let t=0;t<s;t++)for(let n=0;n<a;n++){let o=t*a+n;if(i[o]<=0)continue;let s=e(n+.5,t+.5);J(r,o,s[0],s[1],s[2],s[3]*i[o]*(c.opacity??1),c.blend??`normal`)}continue}let[l,u,d,f]=t(c.color??(c.type===`glow`||c.type===`innerGlow`?`#ffffff`:`#000000`)),p=(c.opacity??1)*f,m=c.blur??(c.type===`glow`?8:4);if(e){let e=De(i,a,s,c.x??0,c.y??0);c.type===`glow`&&(e=e.map(e=>Math.min(1,e*1.6)));let t=o(e,a,s,m);for(let e=0;e<t.length;e++)J(r,e,l,u,d,Math.min(1,t[e]*p),c.type===`glow`?`screen`:`normal`)}else{let e=o(De(i.map(e=>1-e),a,s,c.x??0,c.y??0),a,s,m),t=c.type===`innerGlow`?`screen`:`normal`;for(let n=0;n<e.length;n++)J(r,n,l,u,d,Math.min(1,e[n]*i[n]*p),t)}}}function We(e,t,n){let[r,i,a,o]=[e,t,-1,-1];for(let s=0;s<t;s++)for(let t=0;t<e;t++)n(s*e+t)&&(t<r&&(r=t),t>a&&(a=t),s<i&&(i=s),o=s);return a<0?null:[r,i,a-r+1,o-i+1]}function X(e,t,n,r,i){if(!t)return;let a=0;for(let e=0;e<n.length;e++)n[e]>a&&(a=n[e]);if(a<=.004)return;let o=We(r,i,e=>n[e]>=Math.min(.5,a/2));o&&e.bounds.set(t,o)}function Z(e,t,n,r){let{w:i,h:a}=e;if(t.visible===!1){if(ne(t)){let{visible:e,...o}=t;Z(new Me(i,a),{...o,guide:!1},n,r)}return}if(!r.showGuides&&ne(t)){Z(new Me(i,a),{...t,guide:!1},n,r);return}if(t.mirror){let{mirror:o,...s}=t,c=(o===`x`?{x:-1,y:1}:{x:1,y:-1}).x<0?[-1,0,0,1,i/Q(n),0]:[1,0,0,-1,0,a/Q(n)];Z(e,s,n,r),Z(e,{...s,...t.id?{id:`${t.id}.mirrored`}:{}},G(n,c),r);return}let s=t.opacity??1,c=t.blend??`normal`,l=e=>r.masks.get(e.replace(/^@/,``)),u=t.clip?l(t.clip):void 0;if(u&&=(e=>{let r=e;return t.clipGrow&&(r=pt(r,t.clipGrow*Q(n),i,a)),t.clipFeather&&(r=o(r,i,a,t.clipFeather*Q(n))),t.clipInvert?r.map(e=>1-e):r})(u),t.clip&&!u){r.notes.push(`layer ${t.id??t.shape}: clip \"${t.clip}\" names no layer drawn before it, so it drew nothing`);return}if(t.except){let e=l(t.except);e?u=e.map((e,t)=>(1-e)*(u?u[t]:1)):r.notes.push(`layer ${t.id??t.shape}: except \"${t.except}\" names no layer drawn before it`)}if(t.blendIf){let[n,r,o=.1]=t.blendIf,s=new Float32Array(i*a);for(let t=0;t<s.length;t++){let i=e.px[t*4+3],a=i>0?h(e.px[t*4]/i,e.px[t*4+1]/i,e.px[t*4+2]/i):0,c=Math.min(o>0?(a-n)/o+1:+(a>=n),o>0?(r-a)/o+1:+(a<=r));s[t]=Math.max(0,Math.min(1,c))*(u?u[t]:1)}u=s}if(t.feather){let{feather:l,opacity:d,blend:f,clip:p,except:m,blendIf:h,clipFeather:g,clipGrow:_,clipInvert:v,...y}=t,b=new Me(i,a);Z(b,y,n,r);let x=new Float32Array(i*a);for(let e=0;e<x.length;e++)x[e]=b.px[e*4+3];let S=o(x,i,a,l*Q(n)),C=new Float32Array(i*a);for(let t=0;t<x.length;t++){let n=x[t];if(n<=0)continue;let r=n*Ge(Math.max(0,Math.min(1,(S[t]/n-.5)*2.5)));C[t]=r*(u?u[t]:1),J(e,t,b.px[t*4]/n,b.px[t*4+1]/n,b.px[t*4+2]/n,C[t]*s,c)}t.id&&r.masks.set(t.id,C);return}if(t.shape===`adjust`||t.shape===`filter`){let r=Q(n),o=t.shape===`adjust`?x(e.px,i,a,t.adjust):k(t.filter,t.params??{},e.px,i,a,r);for(let t=0;t<i*a;t++){let n=s*(u?u[t]:1);if(n<=0)continue;let r=t*4;if(c!==`normal`){let i=o[r+3];i>0&&J(e,t,o[r]/i,o[r+1]/i,o[r+2]/i,i*n,c);continue}for(let t=0;t<4;t++)e.px[r+t]=e.px[r+t]+(o[r+t]-e.px[r+t])*n}return}if(t.blur){let{blur:l,opacity:d,blend:f,clip:p,except:m,blendIf:h,clipFeather:g,clipGrow:_,clipInvert:v,...y}=t,b=new Me(i,a);Z(b,y,n,r);let[x,S,C,w]=[0,1,2,3].map(e=>{let t=new Float32Array(i*a);for(let n=0;n<t.length;n++)t[n]=b.px[n*4+e];return o(t,i,a,l*Q(n))});t.id&&r.masks.set(t.id,u?w.map((e,t)=>e*u[t]):w);for(let t=0;t<w.length;t++){let n=w[t];n<=0||J(e,t,x[t]/n,S[t]/n,C[t]/n,n*s*(u?u[t]:1),c)}return}if(t.shape===`group`){let o=new Me(i,a),l=G(n,ge(t.transform,[i/2,a/2]));for(let e of t.layers??[])Z(o,e,l,r);let d=new Float32Array(i*a);for(let e=0;e<d.length;e++)d[e]=o.px[e*4+3];t.id&&r.masks.set(t.id,d),X(r,t.id,d,i,a),Y(t.effects,!0,e,d);for(let t=0;t<d.length;t++){let n=d[t]*s*(u?u[t]:1);if(n<=0)continue;let r=o.px[t*4+3]||1;J(e,t,o.px[t*4]/r,o.px[t*4+1]/r,o.px[t*4+2]/r,n,c)}Y(t.effects,!1,e,d);return}if(t.shape===`pixels`){yt(e,t,n,r,s,c,u);return}if(t.shape===`paint`){st(e,t,n,r,s,c,u);return}if(t.shape===`figure`){ct(e,t,n,r,s,c,u);return}if(t.shape===`image`){vt(e,t,n,r,s,c,u);return}if(t.shape===`text`){mt(e,t,n,r,s,c,u);return}if(t.shape===`block`){ht(e,t,n,r);return}if(t.shape===`perspective`){gt(e,t,n,s);return}if(t.shape===`reflect`){_t(e,t,n,r,s,u);return}if(t.shape===`bloom`){ut(e,t,n,s,u);return}if(t.face&&t.shape===`rect`){let i=Ae(t,r);if(!i)return;let{face:a,within:o,at:s,size:c,radius:l,...u}=t,d=u.fill&&typeof u.fill!=`string`&&u.fill.type===`grid`&&!u.fill.quad?{...u.fill,quad:i}:u.fill;Z(e,{...u,...d?{fill:d}:{},shape:`polygon`,points:i},n,r);return}let{runs:d,middle:f}=ye(t),p=G(n,ge(t.transform,f)),m=d.map(e=>({closed:e.closed,points:e.points.map(e=>K(p,e))})),g=Math.sqrt(Math.abs(p[0]*p[3]-p[1]*p[2])),_=t.fill!==void 0&&t.shape!==`line`,v=t.shape===`line`?new Float32Array(i*a):Ce(m.map(e=>e.points),i,a),y=t.stroke?.align??`center`,b=t.stroke?Te(m,t.stroke.width*g*(y===`outside`?2:1),i,a,t.stroke.join,t.stroke.cap):null;if(b&&y===`inside`)for(let e=0;e<b.length;e++)b[e]*=v[e];if(b&&y===`outside`)for(let e=0;e<b.length;e++)v[e]>=.999&&(b[e]=0);let S=new Float32Array(i*a),C=0;for(let e=0;e<S.length;e++){let t=Math.max(_?v[e]:0,b?b[e]:0)*(u?u[e]:1);S[e]=t,C+=t}if(X(r,t.id,S,i,a),t.id){let e=y===`outside`?null:b;r.masks.set(t.id,t.shape===`line`?S:v.map((t,n)=>t*(e?1-e[n]:1)*(u?u[n]:1)))}if(C===0&&r.notes.push(`layer ${t.id??t.shape} draws nothing inside the picture${u?`, or nothing inside its clip`:``}`),t.erase){for(let t=0;t<S.length;t++){let n=1-S[t]*s;for(let r=0;r<4;r++)e.px[t*4+r]*=n}return}Y(t.effects,!0,e,S);let w=()=>{let n=q(t.stroke.color,p,r,i);for(let t=0;t<a;t++)for(let r=0;r<i;r++){let a=t*i+r,o=b[a]*(u?u[a]:1);if(o<=0)continue;let l=n(r+.5,t+.5);J(e,a,l[0],l[1],l[2],o*l[3]*s,c)}};if(b&&y===`outside`&&w(),_){let n=q(t.fill,p,r,i);for(let t=0;t<a;t++)for(let r=0;r<i;r++){let a=t*i+r,o=v[a]*(u?u[a]:1);if(o<=0)continue;let l=n(r+.5,t+.5);J(e,a,l[0],l[1],l[2],o*l[3]*s,c)}}Y(t.effects,!1,e,S),b&&y!==`outside`&&w()}let Q=e=>Math.sqrt(Math.abs(e[0]*e[3]-e[1]*e[2]))||1,$=(e,t)=>{let n=Math.imul(e,374761393)+Math.imul(t,668265263);return n=Math.imul(n^n>>>13,1274126177),n=Math.imul(n^n>>>16,2246822519),((n^n>>>16)>>>0)/4294967295},Ge=e=>e*e*(3-2*e),Ke=null;function qe(e,t,n){let r=`${e}x${t}:${n}`;if(Ke?.key===r)return Ke.values;let i=new Float32Array(e*t);for(let r=0;r<t;r++)for(let t=0;t<e;t++)i[r*e+t]=f((t+.5)/n,(r+.5)/n,3,77);return Ke={key:r,values:i},i}function Je(e,t){let n=e.map(e=>{let n=K(t,[e[0],e[1]]);return[n[0],n[1],e[2]??1]}),r=[{x:n[0][0],y:n[0][1],pressure:n[0][2],along:0}];for(let e=0;e+1<n.length;e++){let[t,i,a,o]=[n[Math.max(0,e-1)],n[e],n[e+1],n[Math.min(n.length-1,e+2)]],s=Math.max(1,Math.ceil(Math.hypot(a[0]-i[0],a[1]-i[1])));for(let e=1;e<=s;e++){let n=e/s,c=n*n,l=c*n,u=e=>.5*(2*i[e]+(a[e]-t[e])*n+(2*t[e]-5*i[e]+4*a[e]-o[e])*c+(3*i[e]-t[e]-3*a[e]+o[e])*l),[d,f]=[u(0),u(1)],p=r[r.length-1];r.push({x:d,y:f,pressure:i[2]+(a[2]-i[2])*n,along:p.along+Math.hypot(d-p.x,f-p.y)})}}return r}function Ye(e,n,r,i,a,o){let{w:s,h:c}=e,l=r[r.length-1].along,[d,f]=[t(n.color??`#000000`),t(n.to??n.color??`#000000`)],[p,m]=n.taper??[0,0],[h,g]=n.fade??[0,0],_=n.roundness??1,v=n.angle===void 0?null:[Math.cos(n.angle*Math.PI/180),Math.sin(n.angle*Math.PI/180)],[y,b,x,S,C,w]=[n.grain??0,(n.grainScale??2)*a,n.dry??0,n.wet??0,n.edge??0,n.flow??0],[T,E,D]=[n.scatter??0,n.dab??1,n.spacing],O=null,k=0,A=n.hardness??.5,j=n.size*a,M=n.smudge??0,N=(n.wobble??0)*a,P=(t,n)=>{let[r,i]=[Math.max(0,Math.min(s-1,Math.floor(t))),Math.max(0,Math.min(c-1,Math.floor(n)))],a=(i*s+r)*4;return[e.px[a],e.px[a+1],e.px[a+2],e.px[a+3]]},ee=null,F=0,I=l*i.from,L=l*i.to;for(;;){for(;F+1<r.length-1&&r[F+1].along<I;)F++;let[t,a]=[r[F],r[Math.min(r.length-1,F+1)]],C=a.along-t.along,R=C>0?Math.max(0,Math.min(1,(I-t.along)/C)):0,z=l>0?I/l:0,B=1;l>0&&p>0&&z<p&&(B*=Ge(z/p)),l>0&&m>0&&z>1-m&&(B*=Ge((1-z)/m));let te=j*(t.pressure+(a.pressure-t.pressure)*R)*B,ne=i.radius===null?te/2:Math.min(i.radius,Math.max(te,i.radius*.4)),V=ne*E,[re,ie]=C>0?[-(a.y-t.y)/C,(a.x-t.x)/C]:[0,0],ae=N>0?u(I/(j*3+8),i.seed*.37+.5,i.seed)*2*N:0,oe=i.offset*te+ae;k++;let[se,ce]=T>0?[($(i.seed*3+1,k)-.5)*2,($(i.seed*3+2,k)-.5)*2]:[0,0],[H,U]=[t.x+(a.x-t.x)*R+re*oe+se*T*ne,t.y+(a.y-t.y)*R+ie*oe+ce*T*ne],le=1;if(l>0&&h>0&&z<h&&(le*=z/h),l>0&&g>0&&z>1-g&&(le*=(1-z)/g),V>=.12){let t=Math.max(1,V*(1-A)),r=Math.min(1,V*2),a=e=>{let n=Math.max(0,Math.min(1,(V+.5-e)/t));return t>1?Ge(n):n},[p,m]=v??[re,ie],h=(e,t)=>_>=1?Math.hypot(e,t):Math.hypot(e*p+t*m,(e*m-t*p)/_),g=(e,t)=>{if(y<=0&&x<=0)return 1;let n=1;if(y>0&&(n*=Math.max(0,Math.min(1,(qe(s,c,b)[Math.floor(t)*s+Math.floor(e)]-(.12+y*.62))/.34+.5))),x>0){let r=(e-H)*re+(t-U)*ie+oe,a=u(r/Math.max(.8,j*.045),I/(j*3+8),i.seed+5),o=u(r/Math.max(1.5,j*.17),I/(j*5+12),i.seed+9),s=.5+.8*a+1.1*o;n*=Math.max(0,Math.min(1,(s-(.12+x*.68))/.22+.5))}return n},[C,T]=[Math.max(0,Math.floor(H-V-1)),Math.min(s-1,Math.ceil(H+V+1))],[E,D]=[Math.max(0,Math.floor(U-V-1)),Math.min(c-1,Math.ceil(U+V+1))];if(M>0){ee??=P(H,U);for(let t=E;t<=D;t++)for(let i=C;i<=T;i++){let o=a(h(i+.5-H,t+.5-U))*r*M*(n.opacity??1)*g(i+.5,t+.5);if(o<=0)continue;let c=(t*s+i)*4;for(let t=0;t<4;t++)e.px[c+t]=e.px[c+t]+(ee[t]-e.px[c+t])*o*.5}let t=P(H,U);for(let e=0;e<4;e++)ee[e]=ee[e]+(t[e]-ee[e])*(1-M)*.5}else{let e=l>0?I/l:0,t=t=>Math.max(0,Math.min(1,(d[t]+(f[t]-d[t])*e)*i.shade)),[c,u,p]=[t(0),t(1),t(2)];if(S>0){let e=P(H,U),t=e[3]>.02?[e[0]/e[3],e[1]/e[3],e[2]/e[3]]:null,n=t?O?S*.09:S*.45:0,r=O??[c,u,p],i=[c,u,p];O=[0,1,2].map(e=>{let a=r[e]+(i[e]-r[e])*.012;return a+((t?t[e]:a)-a)*n}),[c,u,p]=O}let m=(d[3]+(f[3]-d[3])*e)*(n.opacity??1)*i.strength*le;for(let e=E;e<=D;e++)for(let t=C;t<=T;t++){let n=a(h(t+.5-H,e+.5-U))*r*m*g(t+.5,e+.5),i=e*s+t,l=o.mask[i],d=w>0?l+n*w*(1-l):n;d<=l||(l===0&&o.touched.push(i),o.mask[i]=d,o.rgb[i*3]=c,o.rgb[i*3+1]=u,o.rgb[i*3+2]=p)}}}if(I>=L||l===0)break;I=Math.min(L,I+(D===void 0?Math.max(.4,V*.1*_):Math.max(.3,V*2*D)))}let R=n.blend??`normal`;for(let t of o.touched){let r=o.mask[t],i=C>0?Math.min(1,r*(1-C*.45*Ge(Math.min(1,r/(n.opacity??1)))+C*1.1*Math.max(0,1-Math.abs(r/(n.opacity??1)-.4)*3))):r;if(n.erase)for(let n=0;n<4;n++)e.px[t*4+n]*=1-i;else J(e,t,o.rgb[t*3],o.rgb[t*3+1],o.rgb[t*3+2],i,R);o.mask[t]=0}o.touched.length=0}function Xe(e,t,n,r,a,o){if(!i()){Ze(e,t,n,r,a,o);return}let s=t.points.map(e=>K(n,[e[0],e[1]])),c=(t.size??24)*r*2+4;for(let[i,l]of be){let[u,d]=[i*e.w,l*e.h];(i!==0||l!==0)&&!xe(s,u,d,c,e.w,e.h)||Ze(e,t,G([1,0,0,1,u,d],n),r,a,o)}}function Ze(e,t,n,r,i,a){let o=t.brush?{...F[t.brush],...t}:t,s=Je(o.points,n),c=o.seed??i+1,l=o.bristles??1;if(l===1){Ye(e,o,s,{offset:0,radius:null,from:0,to:1,shade:1,strength:1,seed:c},r,a);return}let u=o.spread??1,d=o.vary??.15,f=(o.strand??Math.max(.8,o.size/l*2.2))*r/2;for(let t=0;t<l;t++){let n=e=>$(c*131+t,e);Ye(e,o,s,{offset:((t+n(1))/l-.5)*u,radius:f,from:n(2)*.06,to:1-n(3)*.1,shade:1+(n(4)-.5)*2*d,strength:1-n(5)*d*1.5,seed:c*31+t},r,a)}}let Qe=e=>Math.max(0,Math.min(255,Math.round(e*255))).toString(16).padStart(2,`0`),$e=(e,t=1)=>`#${Qe(e[0]*t)}${Qe(e[1]*t)}${Qe(e[2]*t)}${Qe(e[3])}`;function et(e,t){let n=Je(e,W),r=n[n.length-1].along,i=0;return Array.from({length:t},(e,a)=>{let o=r*a/(t-1);for(;i+1<n.length-1&&n[i+1].along<o;)i++;let[s,c]=[n[i],n[i+1]??n[i]],l=c.along>s.along?Math.min(1,(o-s.along)/(c.along-s.along)):0;return{x:s.x+(c.x-s.x)*l,y:s.y+(c.y-s.y)*l,pressure:s.pressure+(c.pressure-s.pressure)*l}})}let tt=e=>{let t={};for(let n of[`brush`,`roundness`,`angle`,`grain`,`grainScale`,`dry`,`wet`,`edge`,`scatter`,`dab`,`spacing`,`flow`,`fade`])e[n]!==void 0&&(t[n]=e[n]);return t};function nt(e){let n=e.guides.map(e=>et(e,14)),r=e.seed??1,i=e.colors.map(t),a=e.tip?t(e.tip):null,o=e.clumps??Math.max(2,Math.round(e.count/14)),[s,c,l,d]=[e.gather??.6,e.flyaway??.02,e.vary??.12,e.wobble??1.5],f=e=>{let t=Math.max(0,Math.min(.9999,e))*(i.length-1),[n,r]=[Math.floor(t),t-Math.floor(t)],[a,o]=[i[n],i[Math.min(i.length-1,n+1)]];return[a[0]+(o[0]-a[0])*r,a[1]+(o[1]-a[1])*r,a[2]+(o[2]-a[2])*r,a[3]+(o[3]-a[3])*r]},p=Array.from({length:o},(e,t)=>(t+.2+$(r*7+t,1)*.6)/o),m=Array.from({length:o},(e,t)=>1+($(r*7+t,2)-.5)*l*2.5),h=[];for(let t=0;t<e.count;t++){let i=e=>$(r*131+t,e),g=(t+i(1))/e.count,_=Math.min(o-1,Math.floor(g*o)),v=i(2)<c,[y,b]=[i(3)<.5?-1:1,.6+i(4)*1.4],x=1-i(5)*(v?.05:.16),S=[];for(let i=0;i<14;i++){let a=i/13*x,o=v?0:s*a*a,c=(g+(p[_]-g)*o)*(n.length-1),[l,f]=[Math.min(n.length-2,Math.floor(c)),c-Math.min(n.length-2,Math.floor(c))],m=e=>{let t=a*13,[n,r]=[Math.min(12,Math.floor(t)),t-Math.min(12,Math.floor(t))];return[e[n].x+(e[n+1].x-e[n].x)*r,e[n].y+(e[n+1].y-e[n].y)*r]},[h,C]=m(n[l]),[w,T]=m(n[l+1]),[E,D]=[h+(w-h)*f,C+(T-C)*f],[O,k]=[w-h,T-C],A=Math.hypot(O,k)||1,j=u(a*3.1,t*.73+.5,r)*d*2*a,M=v?y*b*a*a*(A*.5+(e.size??1.2)*14):0;S.push([Math.round((E+O/A*(j+M))*100)/100,Math.round((D+k/A*(j+M))*100)/100])}let C=m[_]*(1+(i(6)-.5)*l),w=f(g+(i(7)-.5)*.08),T=(e.size??1.2)*(.7+i(8)*.6);h.push({...tt(e),points:S,size:T,...e.brush&&e.hardness===void 0?{}:{hardness:e.hardness??.7},color:$e(w,C),...a?{to:$e([w[0]+(a[0]-w[0])*.8,w[1]+(a[1]-w[1])*.8,w[2]+(a[2]-w[2])*.8,w[3]],C)}:{},opacity:(e.opacity??(e.brush?F[e.brush].opacity??1:1))*(v?.55:.75+i(9)*.25),taper:e.taper??[.04,.45]})}return h}function rt(e,t,n,r,i,a){let o=e.seed??1,s=e.region?.startsWith(`@`)?e.region.slice(1):null,c=s?i.masks.get(s):void 0;if(s&&!c)return i.notes.push(`${a}: a field's region \"@${s}\" names no layer drawn before it, so it drew nothing`),[];let l=c?We(t,n,e=>c[e]>=.5):null;if(c&&!l)return[];let u=e.region&&!s?A(e.region).map(e=>e.points):null,d=(e,i)=>{if(c){let a=K(r,[e,i]),[o,s]=[Math.floor(a[0]),Math.floor(a[1])];return o>=0&&s>=0&&o<t&&s<n&&c[s*t+o]>=.5}if(!u)return!0;let a=0;for(let t of u)for(let n=0;n<t.length;n++){let[r,o]=[t[n],t[(n+1)%t.length]];if(r[1]<=i==o[1]<=i)continue;let s=(o[0]-r[0])*(i-r[1])-(e-r[0])*(o[1]-r[1]);(o[1]>r[1]?s>0:s<0)&&(a+=o[1]>r[1]?1:-1)}return a!==0},f=he(r),p=l?[[l[0],l[1]],[l[0]+l[2],l[1]],[l[0],l[1]+l[3]],[l[0]+l[2],l[1]+l[3]]].map(e=>K(f,e)):u?u.flat():[[0,0],[t,n]],[m,h]=[Math.min(...p.map(e=>e[0])),Math.max(...p.map(e=>e[0]))],[g,_]=[Math.min(...p.map(e=>e[1])),Math.max(...p.map(e=>e[1]))],v=(e.guides??[]).flatMap(e=>{let t=et(e,24);return t.slice(0,-1).map((e,n)=>{let r=t[n+1],i=Math.hypot(r.x-e.x,r.y-e.y)||1;return{x:e.x,y:e.y,dx:(r.x-e.x)/i,dy:(r.y-e.y)/i}})}),y=(t,n)=>{if(v.length===0){let t=(e.angle??0)*Math.PI/180;return[Math.cos(t),Math.sin(t)]}let[r,i]=[0,0];for(let e of v){let a=1/(1+((t-e.x)**2+(n-e.y)**2)**1.5);r+=e.dx*a,i+=e.dy*a}let a=Math.hypot(r,i)||1;return[r/a,i/a]},b=e.tone!==void 0&&typeof e.tone!=`string`&&(e.tone.type===`form`||e.tone.type===`image`)?q(e.tone,W,i,t):null,x=b?(e,t)=>{let n=K(r,[e,t]);return b(n[0],n[1])}:e.tone===void 0?null:q(e.tone,W),S=e.length??e.size*3,C=Math.min(H,Math.ceil((e.coverage??4)*Math.max(1,(h-m)*(_-g))/(e.size*S))),w=(e.spread??12)*Math.PI/180,T=e.vary??.05,E=[],D=Math.max(1,Math.round(Math.sqrt(C*(h-m||1)/(_-g||1)))),O=Math.max(1,Math.ceil(C/D)),k=Array.from({length:D*O},(e,t)=>t).sort((e,t)=>$(o*53+e,9)-$(o*53+t,9));for(let t of k){let n=e=>$(o*197+t,e),[r,i]=[m+(t%D+n(1))/D*(h-m),g+(Math.floor(t/D)+n(2))/O*(_-g)];if(!d(r,i))continue;let a=(n(3)-.5)*2*w,s=[],[c,l]=[-S/2,S/5],[u,f]=[r,i],[p,v]=y(r,i);u+=p*c,f+=v*c;for(let e=0;e<=5;e++){s.push([Math.round(u*100)/100,Math.round(f*100)/100]);let[e,t]=y(u,f),[n,r]=[e*Math.cos(a)-t*Math.sin(a),e*Math.sin(a)+t*Math.cos(a)];u+=n*l,f+=r*l}E.push({...tt(e),points:s,size:e.size*(.75+n(4)*.5),...e.brush?{}:{hardness:e.hardness??.25,opacity:e.opacity??.6},...e.brush&&e.hardness!==void 0?{hardness:e.hardness}:{},...e.brush&&e.opacity!==void 0?{opacity:e.opacity}:{},...e.smudge?{smudge:e.smudge}:{color:$e(x(r,i),1+(n(5)-.5)*2*T)},taper:e.taper??[.12,.3]})}return E}function it(e){let t=e.seed??1,n=et(e.line,Math.max(2,e.count)),[r,i]=typeof e.scale==`number`?[e.scale,e.scale]:e.scale??[1,1],a=e.jitter??0,o=[];for(let s=0;s<e.count;s++){let c=e.count===1?0:s/(e.count-1),l=n[s],[u,d]=s+1<n.length?[l,n[s+1]]:[n[s-1],l],f=e=>($(t*89+s,e)-.5)*2*a,p=r+(i-r)*c,m=Math.atan2(d.y-u.y,d.x-u.x);for(let t of e.both?[1,-1]:[1]){let n=m+((e.turn??0)*t+f(1)*.1)*Math.PI/180,[r,i]=[Math.cos(n),Math.sin(n)],[a,s]=[l.x+f(2),l.y+f(3)];for(let n of e.strokes)o.push({...n,size:n.size*p,points:n.points.map(e=>{let[n,o]=[e[0]*p,e[1]*p*t];return[a+n*r-o*i,s+n*i+o*r,...e[2]===void 0?[]:[e[2]]]})})}}return o}function at(e,t,n){let r=e.size??1.2,i=e.guides.map(e=>et(e,3)[1]),a=0;for(let e=0;e+1<i.length;e++)a+=Math.hypot(i[e+1].x-i[e].x,i[e+1].y-i[e].y);(a<r*4||e.count*r>a*8*Math.max(1,e.guides.length))&&t.notes.push(`${n}: a sweep lays ${e.count} hairs of size ${r} across ${Math.round(a)} pixels, which fills it as a flat band; use fewer, thinner hairs or set the guides further apart`)}let ot=(e,t,n,r,i,a)=>`type`in e?e.type===`sweep`?(at(e,i,a),nt(e)):e.type===`along`?it(e):rt(e,t,n,r,i,a):[e];function st(e,t,n,r,i,a,o){let{w:s,h:c}=e,l=G(n,ge(t.transform,[s/2,c/2])),u=new Me(s,c);if(t.from===`below`&&u.px.set(e.px),t.fill!==void 0){let e=q(t.fill,l,r,s);for(let t=0;t<c;t++)for(let n=0;n<s;n++){let r=e(n+.5,t+.5);J(u,t*s+n,r[0],r[1],r[2],r[3],`normal`)}}let d={mask:new Float32Array(s*c),rgb:new Float32Array(s*c*3),touched:[]},f=0,p=t.face?Ae(t,r):null;if(t.face&&!p)return;let m=p?ke(p):null,h=e=>e.map(e=>[...m(e[0],e[1]),...e.slice(2)]);(t.strokes??[]).map(e=>m?`type`in e?e.type===`sweep`?{...e,guides:e.guides.map(h)}:e.type===`along`?{...e,line:h(e.line)}:e:{...e,points:h(e.points)}:e).forEach(e=>{for(let n of ot(e,s,c,l,r,`layer ${t.id??`paint`}`))Xe(u,n,l,Q(l),f++,d)}),t.id&&r.painted.set(t.id,{entries:(t.strokes??[]).length,strokes:f});let g=new Float32Array(s*c);for(let e=0;e<g.length;e++)g[e]=u.px[e*4+3];let _=o?g.map((e,t)=>e*o[t]):g;if(t.id&&r.masks.set(t.id,_),X(r,t.id,_,s,c),t.from===`below`){for(let t=0;t<g.length*4;t++){let n=i*(o?o[Math.floor(t/4)]:1);e.px[t]=e.px[t]+(u.px[t]-e.px[t])*n}return}Y(t.effects,!0,e,g);for(let t=0;t<g.length;t++){let n=g[t];n<=0||J(e,t,u.px[t*4]/n,u.px[t*4+1]/n,u.px[t*4+2]/n,n*i*(o?o[t]:1),a)}Y(t.effects,!1,e,g)}function ct(e,t,n,r,i,a,s){let{w:c,h:l}=e;if(!r.figure)throw Error(`this picture has a figure layer, and nothing here draws figures: it is baked where it is authored`);let u=r.figure.flatten(t,c,l,e=>K(n,e),Q(n)),d=Math.max(2,t.height*.03),f=o(u.mask,c,l,d),p=new Float32Array(u.normals);for(let e=0;e<3;e++){let t=new Float32Array(c*l);for(let n=0;n<t.length;n++)t[n]=u.normals[n*3+e]*u.mask[n];let n=o(t,c,l,d);for(let r=0;r<t.length;r++)u.mask[r]<.5&&f[r]>.01&&(p[r*3+e]=n[r]/f[r])}if(t.id){r.figures.set(t.id,{...u,normals:p});let e=e=>s?e.map((e,t)=>e*s[t]):e;r.masks.set(t.id,e(u.mask)),X(r,t.id,e(u.mask),c,l);for(let[n,i]of Object.entries(u.parts))r.masks.set(`${t.id}.${n}`,e(i)),X(r,`${t.id}.${n}`,e(i),c,l)}let[m,h,g]=u.light;for(let t=0;t<u.mask.length;t++){let n=u.mask[t];if(n<=0)continue;let r=.25+.7*Math.max(0,.5+.5*(u.normals[t*3]*m+u.normals[t*3+1]*h+u.normals[t*3+2]*g)),o=1-u.contour[t]*.85;J(e,t,r*o*.92,r*o*.94,r*o,n*i*(s?s[t]:1),a)}let _=Te(u.lines.map(e=>({closed:!1,points:e})),1.5,c,l);for(let t=0;t<_.length;t++)J(e,t,.95,.35,.3,_[t]*.8*i,`normal`);for(let[t,n]of Object.values(u.joints))for(let r=-2;r<=2;r++)for(let a=-2;a<=2;a++)t+a<0||n+r<0||t+a>=c||n+r>=l||a*a+r*r>5||J(e,(n+r)*c+t+a,.95,.2,.25,.85*i,`normal`);t.id&&r.figureJoints.set(t.id,u.joints)}function lt(e,t,n,r,i){let a=[...e.text].length,o=96/(e.fontSize??96),s=Math.ceil(96*1.4*(a+1)+Math.abs(e.tracking??0)*o*a),[c,l]=e.vertical?[192,s]:[s,192],u=i({...e,fontSize:96,align:`left`,at:e.vertical?[192/2,96*.2]:[96*.2,96*1.3],...e.tracking?{tracking:e.tracking*o}:{},...e.stroke?{stroke:{...e.stroke,width:e.stroke.width*o}}:{}},W,c,l),d=We(c,l,e=>u.fill[e]>=.5||(u.line?u.line[e]>=.5:!1)),f={fill:new Float32Array(n*r),line:u.line?new Float32Array(n*r):null},p=e.quad.map(e=>K(t,e)),m=Oe(p);if(!d||!m)return f;let[h,g]=[Math.max(0,Math.floor(Math.min(...p.map(e=>e[0])))),Math.min(n-1,Math.ceil(Math.max(...p.map(e=>e[0]))))],[_,v]=[Math.max(0,Math.floor(Math.min(...p.map(e=>e[1])))),Math.min(r-1,Math.ceil(Math.max(...p.map(e=>e[1]))))];for(let e=_;e<=v;e++)for(let t=h;t<=g;t++){let[r,i]=[0,0];for(let n=0;n<3;n++)for(let a=0;a<3;a++){let[o,s]=m(t+(a+.5)/3,e+(n+.5)/3);if(o<0||s<0||o>=1||s>=1)continue;let l=Math.floor(d[1]+s*d[3])*c+Math.floor(d[0]+o*d[2]);r+=u.fill[l],u.line&&(i+=u.line[l])}f.fill[e*n+t]=r/9,f.line&&(f.line[e*n+t]=i/9)}return f}function ut(e,t,n,r,i){let{w:a,h:s}=e,c=t.threshold??.6,l=(t.strength??1)*r,u=(t.radius??10)*Q(n),d=[new Float32Array(a*s),new Float32Array(a*s),new Float32Array(a*s)],f=Math.max(.001,1-c);for(let t=0;t<a*s;t++){let[n,r,i]=[e.px[t*4],e.px[t*4+1],e.px[t*4+2]],a=Math.max(n,r,i);if(a<=c)continue;let o=Ge(Math.min(1,(a-c)/f));d[0][t]=n*o,d[1][t]=r*o,d[2][t]=i*o}for(let t=0;t<3;t++){let[n,r]=[o(d[t],a,s,u*.5),o(d[t],a,s,u*2.5)];for(let o=0;o<a*s;o++){let a=Math.min(1,(n[o]*.7+r[o]*.9)*l)*(i?i[o]:1);if(a<=0)continue;let s=o*4;e.px[s+t]=e.px[s+t]+(1-e.px[s+t])*a,a>e.px[s+3]&&(e.px[s+3]=a)}}}function dt(e,t,n,r){let i=Math.round(t);if(i<=0)return e;let a=new Float32Array(n*r);for(let t=0;t<r;t++)for(let r=0;r<n;r++){let o=1;for(let a=-i;a<=i;a++){let i=r+a,s=i<0||i>=n?0:e[t*n+i];s<o&&(o=s)}a[t*n+r]=o}let o=new Float32Array(n*r);for(let e=0;e<n;e++)for(let t=0;t<r;t++){let s=1;for(let o=-i;o<=i;o++){let i=t+o,c=i<0||i>=r?0:a[i*n+e];c<s&&(s=c)}o[t*n+e]=s}return o}function ft(e,t,n){let[r,i]=[t.grain??0,t.dry??0];if(r<=0&&i<=0)return e;let a=t.grainScale??2;return e.map((e,t)=>{if(e<=0)return 0;let[o,s]=[t%n+.5,Math.floor(t/n)+.5],c=e;return r>0&&(c*=Math.max(0,Math.min(1,(f(o/a,s/a,3,77)-(.12+r*.62))/.34+.5))),i>0&&(c*=Math.max(0,Math.min(1,(.5+1.3*u(o/40,s/1.8,9)-(.12+i*.68))/.22+.5))),c})}function pt(e,t,n,r){let i=Math.round(Math.abs(t));if(i===0)return e;let a=t>0?Math.max:Math.min,o=new Float32Array(n*r);for(let s=0;s<r;s++)for(let r=0;r<n;r++){let c=e[s*n+r];for(let o=-i;o<=i;o++){let i=r+o;c=a(c,i<0||i>=n?t>0?0:c:e[s*n+i])}o[s*n+r]=c}let s=new Float32Array(n*r);for(let e=0;e<n;e++)for(let c=0;c<r;c++){let l=o[c*n+e];for(let s=-i;s<=i;s++){let i=c+s;l=a(l,i<0||i>=r?t>0?0:l:o[i*n+e])}s[c*n+e]=l}return s}function mt(e,t,n,r,i,a,o){let{w:s,h:c}=e;if(!r.text)throw Error(`layer ${t.id??`text`}: text needs the editor's fonts, and this render has none`);let l=G(n,ge(t.transform,t.at??[0,0])),u=t.face?Ae(t,r):t.quad;if(t.face&&!u)return;let d=u?lt({...t,quad:u},l,s,c,r.text):r.text(t,l,s,c),f=d.line,p=ft(dt(d.fill,(t.thin??0)*Q(l),s,c),t,s),m=new Float32Array(s*c);for(let e=0;e<m.length;e++)m[e]=Math.max(t.fill===void 0?0:p[e],f?f[e]:0)*(o?o[e]:1);t.id&&r.masks.set(t.id,m),X(r,t.id,m,s,c),Y(t.effects,!0,e,m);let h=(t,n)=>{for(let r=0;r<c;r++)for(let c=0;c<s;c++){let l=r*s+c,u=t[l]*(o?o[l]:1);if(u<=0)continue;let d=n(c+.5,r+.5);J(e,l,d[0],d[1],d[2],u*d[3]*i,a)}};f&&t.stroke&&h(f,q(t.stroke.color,l,r,s)),t.fill!==void 0&&h(p,q(t.fill,l,r,s)),Y(t.effects,!1,e,m)}function ht(e,t,n,r){let[i,a]=t.at,o=a-t.height,s=(e,t,n,r)=>[e+(n[0]-e)*r,t+(n[1]-t)*r],c={},l=[`a`,`b`],u={...t.opacity===void 0?{}:{opacity:t.opacity},...t.blend?{blend:t.blend}:{},...t.clip?{clip:t.clip}:{},...t.except?{except:t.except}:{},...t.stroke?{stroke:t.stroke}:{}},d=(t.vanish??[]).map((e,n)=>{let r=t.depth[n],[d,f]=s(i,o,e,r),[p,m]=s(i,a,e,r),h=e[0]<i?[[d,f],[i,o],[i,a],[p,m]]:[[i,o],[d,f],[p,m],[i,a]];c[l[n]]=h;let g=t.faces[n],_=typeof g!=`string`&&g.type===`grid`&&!g.quad?{...g,quad:h}:g;return{...u,...t.id?{id:`${t.id}.${l[n]}`}:{},shape:`polygon`,points:h,fill:_}}),f=t.vanish??[];if(t.roof!==void 0&&f[0][1]<o){let e=[i,o],[n,r]=[s(i,o,f[0],t.depth[0]),f[1]?s(i,o,f[1],t.depth[1]):null],a=r&&f[1]?[e,n,(()=>{let[e,t,i,a]=[n,f[1],r,f[0]],o=(e[0]-t[0])*(i[1]-a[1])-(e[1]-t[1])*(i[0]-a[0]);if(Math.abs(o)<1e-6)return e;let s=((e[0]-i[0])*(i[1]-a[1])-(e[1]-i[1])*(i[0]-a[0]))/o;return[e[0]+s*(t[0]-e[0]),e[1]+s*(t[1]-e[1])]})(),r]:null;a&&(c.top=a,d.unshift({...u,...t.id?{id:`${t.id}.top`}:{},shape:`polygon`,points:a,fill:t.roof}))}for(let t of d)Z(e,t,n,r);if(t.id){r.blocks.set(t.id,Object.fromEntries(Object.entries(c).map(([e,t])=>[e,t.map(e=>{let t=K(n,e);return[Math.round(t[0]),Math.round(t[1])]})])));let i=new Float32Array(e.w*e.h);for(let e of Object.keys(c)){let n=r.masks.get(`${t.id}.${e}`);if(n)for(let e=0;e<i.length;e++)i[e]=Math.max(i[e],n[e])}r.masks.set(t.id,i),X(r,t.id,i,e.w,e.h)}}function gt(e,t,n,r){let{w:i,h:a}=e,o=Math.hypot(i,a),s=(t.vanish??[]).flatMap(e=>Array.from({length:24},(t,r)=>{let i=r/24*Math.PI*2,a=K(n,[e[0],e[1]]);return{closed:!1,points:[a,[a[0]+Math.cos(i)*o,a[1]+Math.sin(i)*o]]}})),c=(t.vanish??[])[0];c&&s.push({closed:!1,points:[K(n,[-i,c[1]]),K(n,[i*2,c[1]])]});let l=Te(s,1,i,a);for(let t=0;t<l.length;t++)J(e,t,.3,.9,1,l[t]*.55*r,`normal`)}function _t(e,t,n,r,i,a){let{w:s,h:c}=e,l=Q(n),d=new Float32Array(s),f=t.edge?.map(e=>K(n,e)).sort((e,t)=>e[0]-t[0]);for(let e=0;e<s;e++){if(!f){d[e]=K(n,[0,t.y])[1];continue}let r=0;for(;r+2<f.length&&f[r+1][0]<e+.5;)r++;let[i,a]=[f[r],f[r+1]],o=a[0]===i[0]?0:Math.max(0,Math.min(1,(e+.5-i[0])/(a[0]-i[0])));d[e]=i[1]+(a[1]-i[1])*o}let p=(t.reach??c)*l,m=(t.ripple??3)*l,h=new Float32Array(s*c*4);for(let t=0;t<c;t++)for(let n=0;n<s;n++){let r=t+.5-d[n];if(r<0||r>=p)continue;let i=Math.floor(d[n]-r);if(i<0)continue;let a=m*(r/p+.2),o=u(n/90,t/3.5,11)*a*2.4+u(n/22,t/1.6,12)*a,c=Math.max(0,Math.min(s-1,Math.round(n+o))),[l,f]=[(t*s+n)*4,(i*s+c)*4];for(let t=0;t<4;t++)h[l+t]=e.px[f+t]}let g=(t.smear??2)*l,_=[0,1,2,3].map(e=>{let t=new Float32Array(s*c);for(let n=0;n<t.length;n++)t[n]=h[n*4+e];return g>0?o(t,s,c,g):t}),v=new Float32Array(s*c);for(let n=0;n<c;n++)for(let r=0;r<s;r++){let o=n+.5-d[r];if(o<0)continue;let c=Math.max(0,1-o/p),l=n*s+r,u=_[3][l];v[l]=u*c*(a?a[l]:1),!(u<=0||v[l]<=0)&&J(e,l,_[0][l]/u,_[1][l]/u,_[2][l]/u,v[l]*i,t.blend??`normal`)}t.id&&r.masks.set(t.id,v),X(r,t.id,v,s,c)}function vt(e,t,n,r,i,a,o){let{w:s,h:c}=e,l=r.pictures[t.src];if(!l)throw Error(`there is no picture at ${t.src}`);let[u,d]=K(n,t.at??[0,0]),f=Q(n),[p,m]=(t.size??[l.width,l.height]).map(e=>e*f),h=new Float32Array(s*c*4),g=new Float32Array(s*c);for(let e=Math.max(0,Math.floor(d));e<Math.min(c,Math.ceil(d+m));e++)for(let t=Math.max(0,Math.floor(u));t<Math.min(s,Math.ceil(u+p));t++){let[n,r]=[(t+.5-u)/p*l.width-.5,(e+.5-d)/m*l.height-.5];if(n<-.5||r<-.5||n>l.width-.5||r>l.height-.5)continue;let[i,a]=[Math.max(0,Math.floor(n)),Math.max(0,Math.floor(r))],[o,c]=[Math.min(l.width-1,i+1),Math.min(l.height-1,a+1)],[f,_]=[Math.max(0,n-i),Math.max(0,r-a)],v=e*s+t;for(let e=0;e<4;e++){let t=(t,n)=>l.rgba[(n*l.width+t)*4+e]/255;h[v*4+e]=(t(i,a)*(1-f)+t(o,a)*f)*(1-_)+(t(i,c)*(1-f)+t(o,c)*f)*_}g[v]=h[v*4+3]}if(t.id){r.images.set(t.id,h);let e=o?g.map((e,t)=>e*o[t]):g;r.masks.set(t.id,e),X(r,t.id,e,s,c)}for(let t=0;t<g.length;t++)g[t]>0&&J(e,t,h[t*4],h[t*4+1],h[t*4+2],g[t]*i*(o?o[t]:1),a)}function yt(e,n,r,i,a,o,s){let{w:c,h:l}=e,u=n.rows,d=Math.max(...u.map(e=>e.length)),f=(n.scale??Math.max(1,Math.floor(Math.min(c/d,l/u.length))))*Q(r),[p,m]=n.at?K(r,n.at):[(c-d*f)/2,(l-u.length*f)/2],h=new Map(Object.entries(n.palette??{}).map(([e,n])=>[e,t(n)])),g=new Float32Array(c*l),_=new Float32Array(c*l*3);u.forEach((e,t)=>{[...e].forEach((e,n)=>{let r=h.get(e);if(r)for(let e=Math.max(0,Math.round(m+t*f));e<Math.min(l,Math.round(m+(t+1)*f));e++)for(let t=Math.max(0,Math.round(p+n*f));t<Math.min(c,Math.round(p+(n+1)*f));t++)g[e*c+t]=r[3]*(s?s[e*c+t]:1),_[(e*c+t)*3]=r[0],_[(e*c+t)*3+1]=r[1],_[(e*c+t)*3+2]=r[2]})}),n.id&&i.masks.set(n.id,g),X(i,n.id,g,c,l),Y(n.effects,!0,e,g);for(let t=0;t<g.length;t++)J(e,t,_[t*3],_[t*3+1],_[t*3+2],g[t]*a,o);Y(n.effects,!1,e,g)}let bt=new Map,xt={drawn:0,reused:0};function St(e){let[t,n]=[3735928559,1103547991];for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return((t^t>>>16)>>>0).toString(36)+((n^n>>>13)>>>0).toString(36)+e.length.toString(36)}function Ct(e){return e?Object.entries(e).map(([e,t])=>{let n=0;for(let e=0;e<t.rgba.length;e+=97)n=Math.imul(n,31)+t.rgba[e]|0;return`${e}:${t.width}x${t.height}:${n}`}).join(`|`):``}function wt(e,t,n){bt.set(e,{px:t.px.slice(),drawn:{masks:new Map(n.masks),notes:[...n.notes],bounds:new Map(n.bounds),painted:new Map(n.painted),figures:new Map(n.figures),figureJoints:new Map(n.figureJoints),images:new Map(n.images),blocks:new Map(n.blocks)}});let r=0;for(let e of bt.values())r+=e.px.byteLength;for(let[e,t]of bt){if(r<=536870912)break;bt.delete(e),r-=t.px.byteLength}}function Tt(e,t,n){t.px.set(e.px),n.masks=new Map(e.drawn.masks),n.notes=[...e.drawn.notes],n.bounds=new Map(e.drawn.bounds),n.painted=new Map(e.drawn.painted),n.figures=new Map(e.drawn.figures),n.figureJoints=new Map(e.drawn.figureJoints),n.images=new Map(e.drawn.images),n.blocks=new Map(e.drawn.blocks)}function Et(e,n={}){let[i,a]=typeof e.size==`number`?[e.size,e.size]:e.size,o=new Me(i,a),s={figure:n.figure,masks:new Map,notes:[],bounds:new Map,painted:new Map,figures:new Map,figureJoints:new Map,showGuides:n.guides===!0,pictures:n.pictures??{},images:new Map,text:n.text,blocks:new Map},c=St(JSON.stringify([i,a,e.background??null,n.guides===!0,Ct(n.pictures),e.tile===!0])),l=e.layers.map(e=>c=St(c+JSON.stringify(e))),u=0;for(let e=l.length-1;e>=0;e--){let t=bt.get(l[e]);if(t){Tt(t,o,s),bt.delete(l[e]),bt.set(l[e],t),u=e+1,xt.reused+=u;break}}if(u===0&&e.background){let[n,r,s,c]=t(e.background);for(let e=0;e<i*a;e++)J(o,e,n,r,s,c,`normal`)}let d=Date.now();r(e.tile===!0),[pe,me]=[i,a];try{for(let t=u;t<e.layers.length;t++)Z(o,e.layers[t],W,s),xt.drawn++,(t===e.layers.length-1||Date.now()-d>=150)&&(wt(l[t],o,s),d=Date.now())}finally{r(!1)}let f=new Uint8Array(i*a*4);for(let e=0;e<i*a;e++){let t=o.px[e*4+3],n=t>1e-5?1/t:0;f[e*4]=Math.round(Math.min(1,o.px[e*4]*n)*255),f[e*4+1]=Math.round(Math.min(1,o.px[e*4+1]*n)*255),f[e*4+2]=Math.round(Math.min(1,o.px[e*4+2]*n)*255),f[e*4+3]=Math.round(Math.min(1,t)*255)}let p=0;for(let e=0;e<i*a;e++)f[e*4+3]>=128&&p++;return{width:i,height:a,rgba:f,notes:s.notes,bounds:We(i,a,e=>f[e*4+3]>=128),covers:Math.round(p/(i*a)*1e3)/1e3,layerBounds:Object.fromEntries(s.bounds),painted:Object.fromEntries(s.painted),figures:Object.fromEntries(s.figureJoints),blocks:Object.fromEntries(s.blocks)}}function Dt(e){let t=Et(de(JSON.parse(e))),n=t.rgba.byteOffset===0&&t.rgba.byteLength===t.rgba.buffer.byteLength;return{width:t.width,height:t.height,pixels:n?t.rgba:t.rgba.slice()}}return typeof self<`u`&&self.document===void 0&&(self.onmessage=e=>{let t=e.data;try{let e=Dt(t.source);self.postMessage({id:t.id,result:e},[e.pixels.buffer])}catch(e){self.postMessage({id:t.id,error:e instanceof Error?e.message:String(e)})}}),e.drawRecipe=Dt,e})({});";+export const RECIPE_WORKER_SOURCE = "(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=(e,t)=>[e[0]+t[0],e[1]+t[1],e[2]+t[2]],n=(e,t)=>[e[0]-t[0],e[1]-t[1],e[2]-t[2]],r=(e,t)=>[e[0]*t,e[1]*t,e[2]*t],i=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],a=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],o=e=>Math.hypot(e[0],e[1],e[2]),s=e=>{let t=o(e);return t>0?[e[0]/t,e[1]/t,e[2]/t]:[0,0,0]},c=Math.PI/180;function l(e){let t=[],n=new Set(e.joints.filter(e=>e.mirror).map(e=>e.name));for(let r of e.joints){if(!r.mirror){t.push({name:r.name,at:r.at,parentName:r.parent});continue}let e={x:0,y:1,z:2}[r.mirror],i=[...r.at];i[e]=-i[e];let a=r.at[e]>=0,o=e=>r.parent===void 0?void 0:n.has(r.parent)?`${r.parent}.${e}`:r.parent;t.push({name:`${r.name}.L`,at:a?r.at:i,parentName:o(`L`)}),t.push({name:`${r.name}.R`,at:a?i:r.at,parentName:o(`R`)})}if(t.length===0)throw Error(`a rig needs at least one joint`);if(t.length>256)throw Error(`this rig has ${t.length} joints; a mesh can be posed by at most 256`);let r=new Map;t.forEach((e,t)=>{if(r.has(e.name))throw Error(`there are two joints called \"${e.name}\"`);r.set(e.name,t)});let i=t.map(e=>{if(e.parentName===void 0)return-1;let n=r.get(e.parentName);if(n===void 0)throw Error(`joint \"${e.name}\" has parent \"${e.parentName}\", which is not a joint; there are ${t.map(e=>e.name).join(`, `)}`);return n});if(i.filter(e=>e<0).length!==1)throw Error(`a rig has one root; these have no parent: ${t.filter((e,t)=>i[t]<0).map(e=>e.name).join(`, `)}`);let a=[],o=new Set;for(;a.length<t.length;){let e=a.length;if(t.forEach((e,t)=>{!o.has(t)&&(i[t]<0||o.has(i[t]))&&(a.push(t),o.add(t))}),a.length===e)throw Error(`the joints' parents go round in a loop`)}let s=new Map(a.map((e,t)=>[e,t])),c=a.map(e=>({name:t[e].name,at:t[e].at,parent:i[e]<0?-1:s.get(i[e]),children:[]}));return c.forEach((e,t)=>{e.parent>=0&&c[e.parent].children.push(t)}),c}let u=(e,t)=>[e[3]*t[0]+e[0]*t[3]+e[1]*t[2]-e[2]*t[1],e[3]*t[1]-e[0]*t[2]+e[1]*t[3]+e[2]*t[0],e[3]*t[2]+e[0]*t[1]-e[1]*t[0]+e[2]*t[3],e[3]*t[3]-e[0]*t[0]-e[1]*t[1]-e[2]*t[2]];function d(e,t,n){let r=(e,t)=>{let n=t*c/2,r=[0,0,0,Math.cos(n)];return r[e]=Math.sin(n),r};return u(r(2,n),u(r(1,t),r(0,e)))}function f(e,n){let i=[e[0],e[1],e[2]],o=r(a(i,n),2);return t(t(n,r(o,e[3])),a(i,o))}function p(e,t,n,r,i,a=!1){let o=e.map(e=>[e[0]+i*n,e[1],e[2],e[3]]),s=e=>(e%n+n)%n,c=(r?o.map(e=>[s(e[0]),e[1],e[2],e[3]]):o).slice().sort((e,t)=>e[0]-t[0]),l=c.length;if(l===1||!r&&t<=c[0][0])return[c[0][1],c[0][2],c[0][3]];if(!r&&t>=c[l-1][0])return[c[l-1][1],c[l-1][2],c[l-1][3]];let u=e=>{if(r){let t=Math.floor(e/l),r=c[(e%l+l)%l];return[r[0]+t*n,r[1],r[2],r[3]]}return c[Math.max(0,Math.min(l-1,e))]},d=r?-1:0,f=r?s(t):t;for(;u(d+1)[0]<=f;)d++;let[p,m,h,g]=[u(d-1),u(d),u(d+1),u(d+2)],_=h[0]-m[0],v=_>0?(f-m[0])/_:0;if(a)return[1,2,3].map(e=>m[e]+(h[e]-m[e])*v);let[y,b]=[v*v,v*v*v];return[1,2,3].map(e=>{let[t,n]=[m[e],h[e]],r=(n-p[e])/Math.max(h[0]-p[0],1e-6)*_,i=(g[e]-t)/Math.max(g[0]-m[0],1e-6)*_;return(2*b-3*y+1)*t+(b-2*y+v)*r+(-2*b+3*y)*n+(b-y)*i})}let m=e=>[-e[0],-e[1],-e[2],e[3]];function h(e,t){let n=s(e),r=s(t),o=i(n,r);if(o>1-1e-9)return[0,0,0,1];if(o<-1+1e-9){let e=s(a(n,Math.abs(n[0])<.9?[1,0,0]:[0,1,0]));return[e[0],e[1],e[2],0]}let c=a(n,r),l=1+o,u=Math.hypot(c[0],c[1],c[2],l);return[c[0]/u,c[1]/u,c[2]/u,l/u]}function g(e,n){let r=[];return e.forEach((e,i)=>{let a=n[i];if(e.parent<0)r[i]={q:a.q,origin:a.offset};else{let n=r[e.parent];r[i]={q:u(n.q,a.q),origin:t(n.origin,f(n.q,a.offset))}}}),r}function _(e,r,i,a){let o=r?.loop!==!1,s=(e,t)=>p(e,i,r.duration,o,t.phase??0,t.linear===!0),c=e.map(i=>{let a=r?.tracks?.find(e=>e.joint===i.name),o=a?.rotate&&!a.reach?s(a.rotate,a):[0,0,0],c=a?.move?s(a.move,a):[0,0,0],l=i.parent>=0?n(i.at,e[i.parent].at):i.at;return{q:d(o[0],o[1],o[2]),offset:t(l,c)}}),l=g(e,c);for(let t of r?.tracks??[]){if(!t.reach)continue;let n=e.findIndex(e=>e.name===t.joint),r=t.rotate?s(t.rotate,t):[0,0,0];l=v(e,c,l,n,s(t.reach,t),t.pole,d(r[0],r[1],r[2]))}return a&&(l=b(e,c,l,a)),{local:c,world:l}}function v(e,a,c,l,d,p,_){let v=e[l].parent,y=e[v].parent,b=e[y].parent,x=c[y].origin,S=c[v].origin,C=c[l].origin,w=o(n(e[v].at,e[y].at)),T=o(n(e[l].at,e[v].at)),E=n(d,x),D=Math.abs(w-T)+1e-4,O=w+T-1e-4,k=Math.max(D,Math.min(O,o(E))),A=s(E),ee=n(S,t(x,r(A,i(n(S,x),A)))),te=p??(o(ee)>w*.01?ee:[0,0,1]),j=n(te,r(A,i(te,A)));o(j)<1e-6&&(j=n([1,0,0],r(A,A[0])));let M=(w*w-T*T+k*k)/(2*k),N=Math.sqrt(Math.max(0,w*w-M*M)),ne=t(t(x,r(A,M)),r(s(j),N)),re=t(x,r(A,k)),ie=h(n(S,x),n(ne,x)),P=u(ie,c[y].q),F=u(h(f(ie,n(C,S)),n(re,ne)),u(ie,c[v].q)),I=b>=0?c[b].q:[0,0,0,1],ae=_??u(m(c[v].q),c[l].q);return a[y]={...a[y],q:u(m(I),P)},a[v]={...a[v],q:u(m(P),F)},a[l]={...a[l],q:_?u(m(F),ae):a[l].q},g(e,a)}let y=Math.PI/4;function b(e,i,a,o){let c=a,l=t=>t===void 0?-1:e.findIndex(e=>e.name===t),d=r=>{if(r===void 0)return null;let i=l(r);if(i>=0)return c[i].origin;let a=o.goals.find(e=>e.name===r);if(!a)return null;let s=l(a.parent);return s<0?a.at:t(c[s].origin,f(c[s].q,n(a.at,e[s].at)))};if(o.ground){let n=o.ground.height??0,[a,p]=o.ground.slope??[0,0],_=s([-a,1,-p]),b=o.ik.filter(e=>e.kind===`foot-plant`).map(e=>{let t=l(e.tip),r=c[t].origin;return{k:e,foot:t,at:r,q:c[t].q,lift:n+a*r[0]+p*r[2]}}),x=new Map;for(let e of b)e.k.pelvis&&x.set(e.k.pelvis,Math.min(x.get(e.k.pelvis)??0,e.lift*(e.k.weight??1)));for(let[n,r]of x){if(r>=0)continue;let a=l(n),o=e[a].parent,s=o>=0?f(m(c[o].q),[0,r,0]):[0,r,0];i[a]={...i[a],offset:t(i[a].offset,s)}}x.size&&(c=g(e,i));let S=Math.acos(Math.min(1,_[1])),C=S>y?s(t(r([0,1,0],Math.sin(S-y)),r(_,Math.sin(y)))):_;for(let t of b){let n=Math.min(1,Math.max(0,t.k.weight??1)),r=[t.at[0],t.at[1]+t.lift*n,t.at[2]],a=t.k.align===!1?void 0:u(h([0,1,0],C),t.q);c=v(e,i,c,t.foot,r,d(t.k.pole)??void 0,a)}}for(let t of o.ik){if(t.kind===`foot-plant`)continue;let r=l(t.tip),a=d(t.target);if(!(r<0||!a))if(t.kind===`two-bone`){let o=d(t.pole);c=v(e,i,c,r,a,o?n(o,c[e[e[r].parent].parent].origin):void 0)}else{let o=t.axis===`x`?[1,0,0]:t.axis===`y`?[0,1,0]:[0,0,1],s=f(c[r].q,o),l=u(h(s,n(a,c[r].origin)),c[r].q),d=e[r].parent;i[r]={...i[r],q:u(m(d>=0?c[d].q:[0,0,0,1]),l)},c=g(e,i)}}return c}function x(e,t,n,r){let{world:i}=_(e,t,n,r);return Object.fromEntries(e.map((e,t)=>[e.name,i[t].origin]))}function S(e,t,n,r){let{world:i}=_(e,t,n,r);return Object.fromEntries(e.map((e,t)=>{let{origin:n,q:r}=i[t];return[e.name,{at:n,x:f(r,[1,0,0]),y:f(r,[0,1,0]),z:f(r,[0,0,1])}]}))}let C=1.6,w=62*Math.PI/180;function T(e={}){let t=(e.height??1.6)/C,n=(e,n,r)=>[e*t,n*t,r*t],r=[Math.sin(w),-Math.cos(w),0],i=.158*(e.shoulders??1),a=e=>n(i+r[0]*e,1.268+r[1]*e,-.018),o=.595,s=[{name:`index`,z:.027,length:.078,radius:.0085},{name:`middle`,z:.009,length:.086,radius:.0088},{name:`ring`,z:-.009,length:.08,radius:.0082},{name:`little`,z:-.026,length:.062,radius:.0072}].map(e=>{let n=a(o);return{name:e.name,base:[n[0],n[1],n[2]+e.z*t],length:e.length*t,radius:e.radius*t}}),c=a(.505),l=[c[0]+r[0]*.022*t,c[1]+r[1]*.022*t-.004*t,c[2]+.028*t],u=[l[0]+r[0]*.038*t,l[1]+r[1]*.038*t-.006*t,l[2]+.024*t],d=[u[0]+r[0]*.036*t,u[1]+r[1]*.036*t-.006*t,u[2]+.01*t];return{k:t,along:r,shoulder:a(0),elbow:a(.27),wrist:c,knuckle:a(o),hip:n(.08,.81,-.004),knee:n(.068,.445,.006),ankle:n(.067,.078,-.016),ball:n(.072,.022,.09),toe:n(.072,.018,.165),pelvis:n(0,.86,-.004),waist:n(0,1,0),chest:n(0,1.16,-.008),neck:n(0,1.32,-.022),head:n(0,1.405,-.01),crown:n(0,C,-.012),fingers:s,thumb:{base:l,mid:u,tip:d}}}function E(e={}){let t=T(e),n=(e,t,n)=>[e[0]+(t[0]-e[0])*n,e[1]+(t[1]-e[1])*n,e[2]+(t[2]-e[2])*n],r=[.03*t.k,1.29*t.k,-.008*t.k],i=[{name:`hips`,at:t.pelvis},{name:`spine`,at:t.waist,parent:`hips`},{name:`chest`,at:t.chest,parent:`spine`},{name:`neck`,at:t.neck,parent:`chest`},{name:`head`,at:t.head,parent:`neck`},{name:`crown`,at:t.crown,parent:`head`},{name:`clavicle`,at:r,parent:`chest`,mirror:`x`},{name:`upperArm`,at:t.shoulder,parent:`clavicle`,mirror:`x`},{name:`forearm`,at:t.elbow,parent:`upperArm`,mirror:`x`},{name:`hand`,at:t.wrist,parent:`forearm`,mirror:`x`},{name:`thumb1`,at:t.thumb.base,parent:`hand`,mirror:`x`},{name:`thumb2`,at:t.thumb.mid,parent:`thumb1`,mirror:`x`},{name:`thumb3`,at:t.thumb.tip,parent:`thumb2`,mirror:`x`},{name:`thigh`,at:t.hip,parent:`hips`,mirror:`x`},{name:`shin`,at:t.knee,parent:`thigh`,mirror:`x`},{name:`foot`,at:t.ankle,parent:`shin`,mirror:`x`},{name:`toes`,at:t.ball,parent:`foot`,mirror:`x`},{name:`toeTip`,at:t.toe,parent:`toes`,mirror:`x`}];for(let e of t.fingers){let r=`hand`;for(let a=0;a<4;a++){let o=`${e.name}${a+1}`,s=[0,.45,.75,1][a];i.push({name:o,at:n(e.base,[e.base[0]+t.along[0]*e.length,e.base[1]+t.along[1]*e.length,e.base[2]],s),parent:r,mirror:`x`}),r=o}}return i}function D(e){if(e.humanoid===void 0)throw Error(\"`humanoid` says whose bones: true, or the build it was given\");let t=l({joints:E(e.humanoid===!0?{}:e.humanoid)}),n=new Set(t.map(e=>e.name)),r=e=>{if(!n.has(e))throw Error(`no joint \"${e}\"; there are ${[...n].join(`, `)}`)},i=new Map;for(let[t,n]of Object.entries(e.rotate??{})){if(r(t),n.length!==3)throw Error(`rotate of \"${t}\" must be [x, y, z] degrees`);i.set(t,{rotate:[[0,n[0],n[1],n[2]]]})}for(let[t,n]of Object.entries(e.move??{})){if(r(t),n.length!==3)throw Error(`move of \"${t}\" must be [x, y, z]`);i.set(t,{...i.get(t),move:[[0,n[0],n[1],n[2]]]})}for(let[t,n]of Object.entries(e.reach??{})){if(r(t),n.at?.length!==3)throw Error(`reach of \"${t}\" needs at: [x, y, z]`);i.set(t,{...i.get(t),reach:[[0,n.at[0],n.at[1],n.at[2]]],...n.pole?{pole:n.pole}:{}})}return{joints:t,animation:{name:`pose`,duration:1,loop:!1,tracks:[...i].map(([e,t])=>({joint:e,...t}))}}}function O(e){let{joints:t,animation:n}=D(e);return x(t,n,0)}function k(e){let{joints:t,animation:n}=D(e);return S(t,n,0)}let A=[`torso`,`arm`,`hand`,`leg`,`foot`,`neck`,`head`],ee=[`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`],te=[[`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`]],j=(e,t,n)=>[e[0]+t[0]*n,e[1]+t[1]*n,e[2]+t[2]*n],M=(e,t,n)=>[e[0]+(t[0]-e[0])*n,e[1]+(t[1]-e[1])*n,e[2]+(t[2]-e[2])*n],N=e=>{let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]},ne=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]];function re(e,t){let n=t=>e[t],[r,i,a,o,s]=[n(`hips`),n(`spine`),n(`chest`),n(`neck`),n(`head`)],[c,l,u,d,f,p]=[t.hips??1,t.waist??1,t.chest??1,t.shoulders??1,t.limbs??1,t.head??1],m=[{tag:`torso`,rings:[{at:j(r.at,r.y,-.1),across:r.x,deep:r.z,a:.09*c,d:.06},{at:j(r.at,r.y,-.02),across:r.x,deep:r.z,a:.135*c,d:.085},{at:M(r.at,i.at,.6),across:i.x,deep:i.z,a:.112*l,d:.07},{at:i.at,across:i.x,deep:i.z,a:.1*l,d:.064},{at:a.at,across:a.x,deep:a.z,a:.128*u,d:.09},{at:M(a.at,o.at,.62),across:a.x,deep:a.z,a:.15*d,d:.078},{at:M(a.at,o.at,.92),across:a.x,deep:a.z,a:.075,d:.06}]}],h=(e,t,n)=>{let r=N(ne(t,Math.abs(t[1])>.9?[1,0,0]:[0,1,0]));return{at:e,across:r,deep:N(ne(t,r)),a:n*f,d:n*f}},g=(e,t,r)=>{let i=t.map(e=>n(e).at),a=[];for(let e=0;e<i.length;e++){let t=N(e+1<i.length?[i[e+1][0]-i[e][0],i[e+1][1]-i[e][1],i[e+1][2]-i[e][2]]:[i[e][0]-i[e-1][0],i[e][1]-i[e-1][1],i[e][2]-i[e-1][2]]);e===0&&a.push(h(j(i[0],t,-r[0]*.8),t,r[0]*.55)),a.push(h(i[e],t,r[e])),e===i.length-1&&a.push(h(j(i[e],t,r[e]*.8),t,r[e]*.55))}m.push({tag:e,rings:a})};for(let e of[`L`,`R`]){g(`arm`,[`upperArm.${e}`,`forearm.${e}`,`hand.${e}`],[.038,.029,.021]),g(`leg`,[`thigh.${e}`,`shin.${e}`,`foot.${e}`],[.072,.046,.03]);let[t,r]=[n(`hand.${e}`),n(`middle4.${e}`)];m.push({tag:`hand`,rings:[{at:t.at,across:t.z,deep:t.y,a:.026,d:.016},{at:M(t.at,r.at,.45),across:t.z,deep:t.y,a:.04,d:.017},{at:r.at,across:t.z,deep:t.y,a:.022,d:.01}]});let[i,a]=[n(`foot.${e}`),n(`toeTip.${e}`)],o=N([a.at[0]-i.at[0],a.at[1]-i.at[1],a.at[2]-i.at[2]]),s=N(ne(o,[1,0,0]));m.push({tag:`foot`,rings:[{at:j(i.at,o,-.05),across:[1,0,0],deep:s,a:.022,d:.026},{at:i.at,across:[1,0,0],deep:s,a:.034,d:.04},{at:M(i.at,a.at,.7),across:[1,0,0],deep:s,a:.04,d:.022},{at:a.at,across:[1,0,0],deep:s,a:.022,d:.01}]})}g(`neck`,[`neck`,`head`],[.042,.038]);let _=M(s.at,n(`crown`).at,.46),v=[];for(let e=0;e<=8;e++){let t=e/8*2-1,n=Math.sqrt(Math.max(1e-4,1-t*t));v.push({at:j(j(_,s.y,t*.108*p),s.z,.006),across:s.x,deep:s.z,a:.074*p*n,d:.09*p*n})}return m.push({tag:`head`,rings:v}),m}let ie=e=>{let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]};function P(e,t,n,r,i){let[a,o]=r(e.at),s=e.height/1.6*i,c=(e.yaw??0)*Math.PI/180,l=(e.pitch??0)*Math.PI/180,[u,d,f,p]=[Math.cos(c),Math.sin(c),Math.cos(l),Math.sin(l)],m=e=>{let[t,n,r]=[e[0]*u+e[2]*d,e[1],-e[0]*d+e[2]*u];return[t,n*f-r*p,n*p+r*f]},h=e=>{let[t,n]=[e[1]*f+e[2]*p,-e[1]*p+e[2]*f];return[e[0]*u-n*d,t,e[0]*d+n*u]},g=e=>{let t=m(e);return[a+t[0]*s,o-t[1]*s]},_=e.build??{},v=e.pose??{},y={humanoid:_,...v.rotate?{rotate:v.rotate}:{},...v.move?{move:v.move}:{}},b=Object.entries(v.reach??{}),x=y;if(b.length){let e=O(y);x={...y,reach:Object.fromEntries(b.map(([t,n])=>{if(!e[t])throw Error(`no joint \"${t}\"; there are ${Object.keys(e).join(`, `)}`);return[t,{at:n.at.length===3?n.at:h([(n.at[0]-a)/s,(o-n.at[1])/s,m(e[t])[2]]),...n.pole?{pole:n.pole}:{}}]}))}}let S=k(x),C={};for(let e of ee){let t=g(S[e].at);C[e]=[Math.round(t[0]),Math.round(t[1])]}let[w,T]=[t*2,n*2],E=new Float32Array(w*T).fill(-1/0),D=new Int8Array(w*T).fill(-1),P=new Float32Array(w*T*3);for(let e of re(S,_)){let t=A.indexOf(e.tag),n=[];for(let t of e.rings)for(let e=0;e<14;e++){let r=e/14*Math.PI*2;n.push(j(j(t.at,t.across,Math.cos(r)*t.a),t.deep,Math.sin(r)*t.d))}let r=[];for(let t=0;t+1<e.rings.length;t++)for(let e=0;e<14;e++){let[n,i]=[t*14+e,t*14+(e+1)%14];r.push([n,i,i+14,n+14])}let i=e.rings.reduce((t,n)=>j(t,n.at,1/e.rings.length),[0,0,0]),c=n.map(()=>[0,0,0]);for(let[e,t,a,o]of r){let[r,s,l]=[n[e],n[t],n[a]],u=ne([s[0]-r[0],s[1]-r[1],s[2]-r[2]],[l[0]-r[0],l[1]-r[1],l[2]-r[2]]),d=[r[0]-i[0],r[1]-i[1],r[2]-i[2]];u[0]*d[0]+u[1]*d[1]+u[2]*d[2]<0&&(u=[-u[0],-u[1],-u[2]]);for(let n of[e,t,a,o])c[n][0]+=u[0],c[n][1]+=u[1],c[n][2]+=u[2]}let l=n.map(e=>{let t=m(e);return[(a+t[0]*s)*2,(o-t[1]*s)*2,t[2]]}),u=c.map(e=>m(N(e))),d=(e,n,r)=>{let[i,a,o]=[l[e],l[n],l[r]],s=(a[0]-i[0])*(o[1]-i[1])-(o[0]-i[0])*(a[1]-i[1]);if(s===0)return;let[c,d]=[Math.max(0,Math.floor(Math.min(i[0],a[0],o[0]))),Math.min(w-1,Math.ceil(Math.max(i[0],a[0],o[0])))],[f,p]=[Math.max(0,Math.floor(Math.min(i[1],a[1],o[1]))),Math.min(T-1,Math.ceil(Math.max(i[1],a[1],o[1])))];for(let l=f;l<=p;l++)for(let f=c;f<=d;f++){let[c,d]=[f+.5,l+.5],p=((c-i[0])*(o[1]-i[1])-(o[0]-i[0])*(d-i[1]))/s,m=((a[0]-i[0])*(d-i[1])-(c-i[0])*(a[1]-i[1]))/s,h=1-p-m;if(h<0||p<0||m<0)continue;let g=h*i[2]+p*a[2]+m*o[2],_=l*w+f;if(!(g<=E[_])){E[_]=g,D[_]=t;for(let t=0;t<3;t++)P[_*3+t]=h*u[e][t]+p*u[n][t]+m*u[r][t]}}};for(let[e,t,n,i]of r)d(e,t,n),d(e,n,i);for(let t of[0,e.rings.length-1])for(let e=1;e+1<14;e++)d(t*14,t*14+e,t*14+e+1)}let F=new Float32Array(t*n),I=new Float32Array(t*n*3),ae=new Float32Array(t*n),L=Object.fromEntries(A.map(e=>[e,new Float32Array(t*n)])),oe=1/4,R=.02;for(let e=0;e<T;e++)for(let n=0;n<w;n++){let r=e*w+n,i=(e>>1)*t+(n>>1),a=D[r],o=n+1<w?E[r+1]:-1/0,s=e+1<T?E[r+w]:-1/0;if(a>=0||o>-1/0||s>-1/0){let e=E[r];(Math.abs(e-o)>R||Math.abs(e-s)>R)&&(ae[i]=Math.min(1,ae[i]+oe*2))}if(!(a<0)){F[i]+=oe,L[A[a]][i]+=oe;for(let e=0;e<3;e++)I[i*3+e]+=P[r*3+e]*oe}}for(let e=0;e<F.length;e++){let t=Math.hypot(I[e*3],I[e*3+1],I[e*3+2]);if(t>0)for(let n=0;n<3;n++)I[e*3+n]/=t}let se=S.head,ce=S.crown,le=M(se.at,ce.at,.46),z=_.head??1,ue=e=>Array.from({length:13},(t,n)=>g(e(n/12*Math.PI-Math.PI/2)));return{mask:F,parts:L,normals:I,contour:ae,joints:C,lines:[...te.map(([e,t])=>[g(S[e].at),g(S[t].at)]),ue(e=>j(j(le,se.y,Math.sin(e)*.108*z),se.z,Math.cos(e)*.09*z+.006)),ue(e=>j(j(j(le,se.y,-.018*z),se.x,Math.sin(e)*.074*z),se.z,Math.cos(e)*.088*z+.006))],light:ie(e.light??[-.5,.6,.6])}}function F(e){let t=/^#([0-9a-fA-F]+)$/.exec(e)?.[1];if(!t||![3,4,6,8].includes(t.length))throw Error(`color ${JSON.stringify(e)} must be #rgb, #rgba, #rrggbb or #rrggbbaa`);let n=t.length<=4?[...t].map(e=>e+e).join(``):t,r=e=>parseInt(n.slice(e,e+2),16)/255;return[r(0),r(2),r(4),n.length===8?r(6):1]}let I=!1,ae=e=>{I=e},L=()=>I;function oe(e,t,n,r){let i=Math.max(1,Math.round(r*1.2)),a=e;for(let e=0;e<3;e++){let e=new Float32Array(t*n);for(let r=0;r<n;r++){let n=0;for(let e=-i;e<=i;e++)n+=a[r*t+(e%t+t)%t];for(let o=0;o<t;o++)e[r*t+o]=n/(2*i+1),n+=a[r*t+(o+i+1)%t]-a[r*t+((o-i)%t+t)%t]}let r=new Float32Array(t*n);for(let a=0;a<t;a++){let o=0;for(let r=-i;r<=i;r++)o+=e[(r%n+n)%n*t+a];for(let s=0;s<n;s++)r[s*t+a]=o/(2*i+1),o+=e[(s+i+1)%n*t+a]-e[((s-i)%n+n)%n*t+a]}a=r}return a}function R(e,t,n,r){if(r<=0)return e;if(I)return oe(e,t,n,r);let i=Math.max(1,Math.round(r*1.2)),a=e;for(let e=0;e<3;e++){let e=new Float32Array(t*n);for(let r=0;r<n;r++){let n=0;for(let e=-i;e<=i;e++)n+=a[r*t+Math.max(0,Math.min(t-1,e))];for(let o=0;o<t;o++)e[r*t+o]=n/(2*i+1),n+=a[r*t+Math.min(t-1,o+i+1)]-a[r*t+Math.max(0,o-i)]}let r=new Float32Array(t*n);for(let a=0;a<t;a++){let o=0;for(let r=-i;r<=i;r++)o+=e[Math.max(0,Math.min(n-1,r))*t+a];for(let s=0;s<n;s++)r[s*t+a]=o/(2*i+1),o+=e[Math.min(n-1,s+i+1)*t+a]-e[Math.max(0,s-i)*t+a]}a=r}return a}let se=[[1,0],[.9239,.3827],[.7071,.7071],[.3827,.9239],[0,1],[-.3827,.9239],[-.7071,.7071],[-.9239,.3827],[-1,0],[-.9239,-.3827],[-.7071,-.7071],[-.3827,-.9239],[0,-1],[.3827,-.9239],[.7071,-.7071],[.9239,-.3827]];function ce(e,t,n,r,i){let a=Math.imul(e,374761393)+Math.imul(t,668265263)+Math.imul(n,1442968193);a=Math.imul(a^a>>>13,1274126177),a=Math.imul(a^a>>>16,2246822519);let o=se[((a^a>>>16)>>>0)%se.length];return o[0]*r+o[1]*i}let le=e=>e*e*e*(e*(e*6-15)+10);function z(e,t,n,r=0,i=0){let[a,o]=[Math.floor(e),Math.floor(t)],[s,c]=[e-a,t-o],[l,u]=[le(s),le(c)],d=e=>r>0?(e%r+r)%r:e,f=e=>i>0?(e%i+i)%i:e,p=ce(d(a),f(o),n,s,c)*(1-l)+ce(d(a+1),f(o),n,s-1,c)*l,m=ce(d(a),f(o+1),n,s,c-1)*(1-l)+ce(d(a+1),f(o+1),n,s-1,c-1)*l;return p*(1-u)+m*u}let ue=[1.15,1.3,1.4,1.45,1.45,1.45,1.45,1.45];function B(e,t,n,r,i=0,a=0){let[o,s,c,l]=[0,0,1,1];for(let u=0;u<n;u++)o+=z(e*l+.37,t*l+.61,r+u*101,i*l,a*l)*c,s+=c,c*=.5,l*=2;return Math.max(0,Math.min(1,.5+o/s*ue[n-1]))}let V=e=>Math.max(0,Math.min(1,e)),de=e=>e*e*(3-2*e),H=(e,t,n)=>e*.2126+t*.7152+n*.0722;function fe(e,t,n){let[r,i]=[Math.max(e,t,n),Math.min(e,t,n)],a=(r+i)/2;if(r===i)return[0,0,a];let o=r-i,s=a>.5?o/(2-r-i):o/(r+i);return[(r===e?(t-n)/o+(t<n?6:0):r===t?(n-e)/o+2:(e-t)/o+4)/6,s,a]}function pe(e,t,n){if(t===0)return[n,n,n];let r=n<.5?n*(1+t):n+t-n*t,i=2*n-r,a=e=>{let t=e<0?e+1:e>1?e-1:e;return t<1/6?i+(r-i)*6*t:t<1/2?r:t<2/3?i+(r-i)*(2/3-t)*6:i};return[a(e+1/3),a(e),a(e-1/3)]}function me(e){let t=[...e].sort((e,t)=>e[0]-t[0]),n=t.map(e=>e[0]),r=t.map(e=>e[1]),i=n.length,a=n.slice(0,-1).map((e,t)=>(r[t+1]-r[t])/Math.max(1e-6,n[t+1]-e)),o=n.map((e,t)=>t===0?a[0]??0:t===i-1?a[i-2]??0:a[t-1]*a[t]<=0?0:(a[t-1]+a[t])/2),s=new Float32Array(1024);for(let e=0;e<s.length;e++){let t=e/(s.length-1);if(t<=n[0]){s[e]=r[0];continue}if(t>=n[i-1]){s[e]=r[i-1];continue}let a=0;for(;t>n[a+1];)a++;let c=n[a+1]-n[a],l=(t-n[a])/c,[u,d]=[l*l,l*l*l];s[e]=V((2*d-3*u+1)*r[a]+(d-2*u+l)*c*o[a]+(3*u-2*d)*r[a+1]+(d-u)*c*o[a+1])}return s}let he=(e,t)=>e[Math.round(V(t)*(e.length-1))];function ge(e){let t=[...e].sort((e,t)=>e[0]-t[0]).map(([e,t])=>[e,F(t)]),n=new Float32Array(768);for(let e=0;e<256;e++){let r=e/255,i=0;for(;i+2<t.length&&r>t[i+1][0];)i++;let[a,o]=[t[i],t[Math.min(t.length-1,i+1)]],s=V((r-a[0])/Math.max(1e-6,o[0]-a[0]));for(let t=0;t<3;t++)n[e*3+t]=a[1][t]+(o[1][t]-a[1][t])*s}return n}function _e(e,t,n,r){let i=new Float32Array(e.length),a=r.levels,[o,s]=a?.input??[0,1],[c,l]=a?.output??[0,1],u=a?.gamma??1,d=r.curves?Array.isArray(r.curves)?{all:me(r.curves)}:Object.fromEntries(Object.entries(r.curves).map(([e,t])=>[e,me(t)])):null,f=r.exposure===void 0?1:2**r.exposure,[p,m]=[r.brightness??0,r.contrast??0],h=m>=0?1/Math.max(.01,1-m*.98):1+m,[g,_]=[r.temperature??0,r.tint??0],[v,y,b]=[(r.hue??0)/360,r.saturation??0,r.lightness??0],x=r.vibrance??0,S=r.gradientMap?ge(r.gradientMap):null,C=r.posterize===void 0?0:Math.max(2,Math.round(r.posterize)),w=r.balance;for(let T=0;T<t*n;T++){let t=T*4,n=e[t+3];if(n<=0)continue;let[E,D,O]=[e[t]/n,e[t+1]/n,e[t+2]/n];if(f!==1&&(E*=f,D*=f,O*=f),a){let e=e=>c+(l-c)*V((e-o)/Math.max(1e-6,s-o))**(1/u);E=e(E),D=e(D),O=e(O)}if(d&&(d.all&&(E=he(d.all,E),D=he(d.all,D),O=he(d.all,O)),d.r&&(E=he(d.r,E)),d.g&&(D=he(d.g,D)),d.b&&(O=he(d.b,O))),p||m){let e=e=>(e+p-.5)*h+.5;E=e(E),D=e(D),O=e(O)}if((g||_)&&(E+=g*.2+_*.1,D-=_*.2,O+=-g*.2+_*.1),w){let e=V(H(E,D,O)),[t,n,r]=[de(V(1-e*2.5)),1-Math.abs(e-.5)*2,de(V((e-.6)*2.5))];for(let[e,i]of[[t,w.shadows],[n,w.midtones],[r,w.highlights]])i&&(E+=i[0]*e*.5,D+=i[1]*e*.5,O+=i[2]*e*.5)}if(v||y||b){let[e,t,n]=fe(V(E),V(D),V(O)),r=y>=0?t+(1-t)*y*(t>0):t*(1+y),i=b>=0?n+(1-n)*b:n*(1+b);[E,D,O]=pe((e+v+1)%1,V(r),V(i))}if(x){let[e,t]=[Math.max(E,D,O),Math.min(E,D,O)],n=x*(1-V(e-t)),r=H(E,D,O);E=r+(E-r)*(1+n),D=r+(D-r)*(1+n),O=r+(O-r)*(1+n)}if(r.blackWhite){let[e,t,n]=Array.isArray(r.blackWhite)?r.blackWhite:[.2126,.7152,.0722];E=D=O=E*e+D*t+O*n}if(S){let e=Math.round(V(H(E,D,O))*255)*3;[E,D,O]=[S[e],S[e+1],S[e+2]]}if(r.invert&&(E=1-E,D=1-D,O=1-O),C){let e=e=>Math.round(V(e)*(C-1))/(C-1);E=e(E),D=e(D),O=e(O)}r.threshold!==void 0&&(E=D=O=+(H(E,D,O)>=r.threshold)),i[t]=V(E)*n,i[t+1]=V(D)*n,i[t+2]=V(O)*n,i[t+3]=n}return i}let ve=(e,t,n,r,i,a,o)=>{let[s,c]=[Math.max(0,Math.min(t-1.001,r-.5)),Math.max(0,Math.min(n-1.001,i-.5))],[l,u]=[Math.floor(s),Math.floor(c)],[d,f]=[s-l,c-u],[p,m,h,g]=[(u*t+l)*4,(u*t+l+1)*4,((u+1)*t+l)*4,((u+1)*t+l+1)*4];for(let t=0;t<4;t++)a[o+t]=(e[p+t]*(1-d)+e[m+t]*d)*(1-f)+(e[h+t]*(1-d)+e[g+t]*d)*f},ye=(e,t,n,r)=>{let i=new Float32Array(e.length);for(let a=0;a<4;a++){let o=new Float32Array(t*n);for(let t=0;t<o.length;t++)o[t]=e[t*4+a];let s=R(o,t,n,r);for(let e=0;e<o.length;e++)i[e*4+a]=s[e]}return i};function be(e,t,n,r){let i=new Float32Array(e.length);for(let a=0;a<n;a++)for(let o=0;o<t;o++){let[s,c]=r(o+.5,a+.5);ve(e,t,n,s,c,i,(a*t+o)*4)}return i}function xe(e,t,n,r,i){let a=new Float32Array(e.length),o=new Float32Array(4);for(let s=0;s<n;s++)for(let c=0;c<t;c++){let l=(s*t+c)*4;for(let u=0;u<r;u++){let[d,f]=i(c+.5,s+.5,r===1?0:u/(r-1));ve(e,t,n,d,f,o,0);for(let e=0;e<4;e++)a[l+e]+=o[e]}for(let e=0;e<4;e++)a[l+e]/=r}return a}function Se(e,t,n,r){let i=new Float32Array(e),a=new Float32Array(3);for(let e=0;e<n;e++)for(let n=0;n<t;n++){a.fill(0),r(n+.5,e+.5,a);let o=(e*t+n)*4,s=i[o+3];for(let e=0;e<3;e++)i[o+e]=i[o+e]+(1-i[o+e])*V(a[e]),s=Math.max(s,i[o+e]);i[o+3]=s}return i}let U=(e,t,n)=>e[t]??n,Ce=(e,t,n)=>e[t]??n;function we(e,t,n,r,i,a){let o=[r/(2*a),i/(2*a)],s=(e=`at`)=>{let n=Ce(t,e,o);return[n[0]*a,n[1]*a]};switch(e){case`gaussian`:return ye(n,r,i,U(t,`radius`,4)*a);case`motion`:{let e=U(t,`angle`,0)*Math.PI/180,o=U(t,`distance`,16)*a,[s,c]=[Math.cos(e)*o,Math.sin(e)*o];return xe(n,r,i,Math.max(2,Math.min(64,Math.ceil(o))),(e,t,n)=>[e+s*(n-.5),t+c*(n-.5)])}case`spin`:{let[e,a]=s(),o=U(t,`angle`,10)*Math.PI/180;return xe(n,r,i,24,(t,n,r)=>{let i=o*(r-.5),[s,c]=[t-e,n-a];return[e+s*Math.cos(i)-c*Math.sin(i),a+s*Math.sin(i)+c*Math.cos(i)]})}case`zoom`:{let[e,a]=s(),o=U(t,`amount`,.1);return xe(n,r,i,24,(t,n,r)=>{let i=1+o*(r-.5);return[e+(t-e)*i,a+(n-a)*i]})}case`lens`:{let e=U(t,`radius`,6)*a,o=U(t,`highlights`,1),s=Math.max(2,Math.min(6,Math.ceil(e/2))),c=[[0,0]];for(let t=1;t<=s;t++){let n=t*7;for(let r=0;r<n;r++){let i=r/n*Math.PI*2+t;c.push([e*t*Math.cos(i)/s,e*t*Math.sin(i)/s])}}let l=new Float32Array(n.length),u=new Float32Array(4);for(let e=0;e<i;e++)for(let t=0;t<r;t++){let a=(e*r+t)*4,s=0;for(let[d,f]of c){ve(n,r,i,t+.5+d,e+.5+f,u,0);let c=H(u[0],u[1],u[2]),p=1+o*2*c*c*c*c;for(let e=0;e<4;e++)l[a+e]+=u[e]*p;s+=p}for(let e=0;e<4;e++)l[a+e]/=s}return l}case`sharpen`:{let e=ye(n,r,i,U(t,`radius`,1.5)*a),[o,s]=[U(t,`amount`,.8),U(t,`threshold`,0)],c=new Float32Array(n);for(let t=0;t<r*i;t++){let r=t*4,i=n[r+3];for(let t=0;t<3;t++){let a=n[r+t]-e[r+t];Math.abs(a)>=s&&(c[r+t]=Math.max(0,Math.min(i,n[r+t]+a*o)))}}return c}case`highPass`:{let e=ye(n,r,i,U(t,`radius`,6)*a),o=new Float32Array(n.length);for(let t=0;t<r*i;t++){let r=t*4,i=n[r+3];o[r+3]=i;for(let t=0;t<3;t++)o[r+t]=V(.5+n[r+t]-e[r+t])*i}return o}case`noise`:{let[e,o,s,c]=[U(t,`amount`,.08),U(t,`scale`,1)*a,U(t,`seed`,1),t.mono!==!1],l=new Float32Array(n);for(let t=0;t<i;t++)for(let i=0;i<r;i++){let a=(t*r+i)*4,u=n[a+3];for(let r=0;r<3;r++){let d=B(i/o,t/o,1,c?s:s+r*13)-.5;l[a+r]=Math.max(0,Math.min(u,n[a+r]+d*e*2*u))}}return l}case`median`:{let e=Math.max(1,Math.min(6,Math.round(U(t,`radius`,1)*a))),o=new Float32Array(n.length),s=[];for(let t=0;t<i;t++)for(let a=0;a<r;a++){s.length=0;for(let o=-e;o<=e;o++)for(let c=-e;c<=e;c++){let e=(Math.max(0,Math.min(i-1,t+o))*r+Math.max(0,Math.min(r-1,a+c)))*4;s.push([H(n[e],n[e+1],n[e+2]),e])}s.sort((e,t)=>e[0]-t[0]);let c=s[s.length>>1][1],l=(t*r+a)*4;for(let e=0;e<4;e++)o[l+e]=n[c+e]}return o}case`emboss`:{let e=U(t,`angle`,135)*Math.PI/180,o=U(t,`height`,2)*a,s=U(t,`amount`,2),[c,l]=[Math.round(Math.cos(e)*o),Math.round(Math.sin(e)*o)],u=new Float32Array(n.length);for(let e=0;e<i;e++)for(let t=0;t<r;t++){let a=(e*r+t)*4,o=(Math.max(0,Math.min(i-1,e+l))*r+Math.max(0,Math.min(r-1,t+c)))*4,d=H(n[a],n[a+1],n[a+2])-H(n[o],n[o+1],n[o+2]),f=V(.5+d*s),p=n[a+3];u[a]=u[a+1]=u[a+2]=f*p,u[a+3]=p}return u}case`ripple`:{let[e,o,s]=[U(t,`amount`,4)*a,U(t,`size`,24)*a,U(t,`seed`,1)];return be(n,r,i,(t,n)=>[t+Math.sin(n/o*Math.PI*2+s)*e,n+Math.sin(t/o*Math.PI*2+s*1.7)*e])}case`displace`:{let[e,o,s]=[U(t,`amount`,8)*a,U(t,`size`,40)*a,U(t,`seed`,1)];return be(n,r,i,(t,n)=>[t+(B(t/o,n/o,3,s)-.5)*e*2,n+(B(t/o,n/o,3,s+7)-.5)*e*2])}case`twirl`:{let[e,o]=s(),[c,l]=[U(t,`radius`,Math.min(r,i)/(2*a))*a,U(t,`angle`,45)*Math.PI/180];return be(n,r,i,(t,n)=>{let[r,i]=[t-e,n-o],a=Math.hypot(r,i);if(a>=c)return[t,n];let s=l*(1-a/c)**2;return[e+r*Math.cos(s)-i*Math.sin(s),o+r*Math.sin(s)+i*Math.cos(s)]})}case`pixelate`:{let e=Math.max(2,Math.round(U(t,`cell`,8)*a)),o=new Float32Array(n.length);for(let t=0;t<i;t+=e)for(let a=0;a<r;a+=e){let s=[0,0,0,0],c=0;for(let o=t;o<Math.min(i,t+e);o++)for(let t=a;t<Math.min(r,a+e);t++){let e=(o*r+t)*4;for(let t=0;t<4;t++)s[t]+=n[e+t];c++}for(let n=t;n<Math.min(i,t+e);n++)for(let t=a;t<Math.min(r,a+e);t++){let e=(n*r+t)*4;for(let t=0;t<4;t++)o[e+t]=s[t]/c}}return o}case`chromatic`:{let[e,o]=s(),c=U(t,`amount`,2)*a/Math.max(r,i),l=new Float32Array(n),u=new Float32Array(4);for(let t=0;t<i;t++)for(let a=0;a<r;a++){let s=(t*r+a)*4,[d,f]=[a+.5-e,t+.5-o];ve(n,r,i,e+d*(1+c),o+f*(1+c),u,0),l[s]=u[0],ve(n,r,i,e+d*(1-c),o+f*(1-c),u,0),l[s+2]=u[2]}return l}case`vignette`:{let[e,a]=s(),[o,c,l]=[U(t,`amount`,.6),U(t,`radius`,.55),U(t,`outer`,1.05)],u=F(t.color??`#000000`),d=Math.hypot(r,i)/2,f=new Float32Array(n);for(let t=0;t<i;t++)for(let i=0;i<r;i++){let s=(t*r+i)*4,p=o*de(V((Math.hypot(i+.5-e,t+.5-a)/d-c)/Math.max(.01,l-c)));for(let e=0;e<3;e++)f[s+e]=n[s+e]+(u[e]*n[s+3]-n[s+e])*p}return f}case`fog`:{let e=F(t.color??`#c8d0e0`),[o,s]=[Ce(t,`from`,[0,0])[0]*a,Ce(t,`from`,[0,0])[1]*a],[c,l]=[Ce(t,`to`,[0,i/a])[0]*a,Ce(t,`to`,[0,i/a])[1]*a],[u,d]=[c-o,l-s],f=u*u+d*d||1,[p,m,h,g]=[U(t,`density`,.6),U(t,`patchiness`,.5),U(t,`size`,120)*a,U(t,`seed`,1)],_=new Float32Array(n);for(let t=0;t<i;t++)for(let i=0;i<r;i++){let a=(t*r+i)*4,c=V(((i+.5-o)*u+(t+.5-s)*d)/f),l=m>0?1-m+m*2*B(i/(h*2),t/h,4,g):1,v=V(de(c)*p*l)*e[3];for(let t=0;t<3;t++)_[a+t]=n[a+t]*(1-v)+e[t]*v;_[a+3]=n[a+3]*(1-v)+v}return _}case`rays`:{let[e,a]=s(),[o,c,l,u]=[U(t,`threshold`,.6),U(t,`length`,.6),U(t,`strength`,.8),U(t,`decay`,.96)],d=new Float32Array(n.length);for(let e=0;e<r*i;e++){let t=e*4,r=V((Math.max(n[t],n[t+1],n[t+2])-o)/Math.max(.01,1-o));for(let e=0;e<3;e++)d[t+e]=n[t+e]*r;d[t+3]=1}let f=new Float32Array(4);return Se(n,r,i,(t,n,o)=>{let s=1;for(let p=0;p<48;p++){let m=1-p/48*c;ve(d,r,i,e+(t-e)*m,a+(n-a)*m,f,0);for(let e=0;e<3;e++)o[e]+=f[e]*s*l/48;s*=u}})}case`flare`:{let[e,o]=s(),c=F(t.color??`#ffe0b0`),[l,u]=[U(t,`size`,60)*a,U(t,`strength`,1)],[d,f]=[r/2,i/2],p=[[-.4,.22,.14],[-.8,.12,.2],[-1.3,.34,.09],[-1.7,.17,.13]];return Se(n,r,i,(t,n,r)=>{let i=Math.hypot(t-e,n-o),a=.9*Math.exp(-((i/l)**2))+.25*Math.exp(-i/(l*2.5));a+=.5*Math.exp(-Math.abs(n-o)/(l*.05))*Math.exp(-Math.abs(t-e)/(l*3.5));for(let[r,i,s]of p){let[c,u]=[e+(d-e)*(1-r),o+(f-o)*(1-r)],p=Math.hypot(t-c,n-u)/(l*i*2.2);p<1&&(a+=s*(1-p*p*p*p))}for(let e=0;e<3;e++)r[e]+=c[e]*a*u})}case`texture`:{let[e,o,s]=[U(t,`scale`,3)*a,U(t,`amount`,.3),U(t,`seed`,1)],c=U(t,`angle`,135)*Math.PI/180,[l,u]=[Math.cos(c),Math.sin(c)],d=new Float32Array(n);for(let t=0;t<i;t++)for(let i=0;i<r;i++){let a=(t*r+i)*4,c=1+(B(i/e,t/e,3,s)-B((i+l)/e,(t+u)/e,3,s))*o*3,f=n[a+3];for(let e=0;e<3;e++)d[a+e]=Math.max(0,Math.min(f,n[a+e]*c))}return d}default:throw Error(`no filter \"${String(e)}\"`)}}function Te(e){let t=e.match(/[a-zA-Z]|-?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][-+]?\\d+)?/g)??[],n=[],r=null,[i,a,o,s,c,l]=[0,0,0,0,0,0],u=``,d=``,f=0,p=()=>{let n=t[f++];if(n===void 0||/[a-zA-Z]/.test(n))throw Error(`path ${JSON.stringify(e.slice(0,60))}: command ${u} is short of numbers`);return Number(n)},m=()=>{r||(r=[[i,a]],n.push({points:r,closed:!1}))},h=e=>{m();for(let t=1;t<=20;t++)r.push(e(t/20))};for(;f<t.length;){if(/[a-zA-Z]/.test(t[f]))u=t[f++];else if(!u)throw Error(`path ${JSON.stringify(e.slice(0,60))} must start with a command`);let g=u===u.toLowerCase(),[_,v]=g?[i,a]:[0,0];switch(u.toUpperCase()){case`M`:i=_+p(),a=v+p(),o=i,s=a,r=[[i,a]],n.push({points:r,closed:!1}),u=g?`l`:`L`;break;case`L`:i=_+p(),a=v+p(),m(),r.push([i,a]);break;case`H`:i=_+p(),m(),r.push([i,a]);break;case`V`:a=v+p(),m(),r.push([i,a]);break;case`C`:case`S`:{let[e,t]=u.toUpperCase()===`S`?d===`C`||d===`S`?[2*i-c,2*a-l]:[i,a]:[_+p(),v+p()],[n,r,o,s]=[_+p(),v+p(),_+p(),v+p()],[f,m]=[i,a];h(i=>{let a=1-i;return[a*a*a*f+3*a*a*i*e+3*a*i*i*n+i*i*i*o,a*a*a*m+3*a*a*i*t+3*a*i*i*r+i*i*i*s]}),[i,a,c,l]=[o,s,n,r];break}case`Q`:case`T`:{let[e,t]=u.toUpperCase()===`T`?d===`Q`||d===`T`?[2*i-c,2*a-l]:[i,a]:[_+p(),v+p()],[n,r]=[_+p(),v+p()],[o,s]=[i,a];h(i=>{let a=1-i;return[a*a*o+2*a*i*e+i*i*n,a*a*s+2*a*i*t+i*i*r]}),[i,a,c,l]=[n,r,e,t];break}case`Z`:n.length&&(n[n.length-1].closed=!0),i=o,a=s,r=null,u=``;break;default:throw Error(`path command ${u} is not one this draws; there are M L H V C S Q T Z`)}d=u.toUpperCase()===`L`&&d===`M`?`L`:u.toUpperCase()}return n}let Ee=[`normal`,`multiply`,`screen`,`overlay`,`add`,`softLight`,`hardLight`,`vividLight`,`linearLight`,`pinLight`,`colorDodge`,`colorBurn`,`linearBurn`,`darken`,`lighten`,`difference`,`exclusion`,`subtract`,`divide`,`hue`,`saturation`,`color`,`luminosity`],De={exposure:[-8,8],brightness:[-1,1],contrast:[-1,1],temperature:[-1,1],tint:[-1,1],hue:[-360,360],saturation:[-1,1],lightness:[-1,1],vibrance:[-1,1],posterize:[2,256],threshold:[0,1]};function Oe(e){if(typeof e!=`object`||!e)return`must be an object of what to change`;let t=e,n=[...Object.keys(De),`levels`,`curves`,`balance`,`blackWhite`,`gradientMap`,`invert`];for(let e of Object.keys(t))if(!n.includes(e))return`has unknown \"${e}\"; there are ${n.join(`, `)}`;if(Object.keys(t).length===0)return`changes nothing`;for(let[e,[n,r]]of Object.entries(De))if(t[e]!==void 0&&!(W(t[e])&&t[e]>=n&&t[e]<=r))return`${e} must be ${n}..${r}`;let r=e=>G(e)&&e.every(e=>e>=0&&e<=1),i=e=>Array.isArray(e)&&e.length>=2&&e.every(r);if(t.levels!==void 0){let e=t.levels;if(typeof e!=`object`||!e)return`levels must be { input?, gamma?, output? }`;for(let t of Object.keys(e))if(![`input`,`gamma`,`output`].includes(t))return`levels has unknown \"${t}\"; there are input, gamma, output`;for(let t of[`input`,`output`])if(e[t]!==void 0&&!r(e[t]))return`levels ${t} must be [low, high], each 0..1`;if(e.gamma!==void 0&&!(W(e.gamma)&&e.gamma>0))return`levels gamma must be positive`}if(t.curves!==void 0)if(Array.isArray(t.curves)){if(!i(t.curves))return`curves must be two or more [in, out], each 0..1`}else{let e=t.curves;if(typeof e!=`object`||!e)return`curves must be [[in, out]...] or { r, g, b }`;for(let[t,n]of Object.entries(e)){if(![`r`,`g`,`b`].includes(t))return`curves has unknown \"${t}\"; there are r, g, b`;if(!i(n))return`curves ${t} must be two or more [in, out], each 0..1`}}if(t.balance!==void 0)for(let[e,n]of Object.entries(t.balance)){if(![`shadows`,`midtones`,`highlights`].includes(e))return`balance has unknown \"${e}\"; there are shadows, midtones, highlights`;if(!(Array.isArray(n)&&n.length===3&&n.every(W)))return`balance ${e} must be [r, g, b]`}return t.blackWhite!==void 0&&typeof t.blackWhite!=`boolean`&&!(Array.isArray(t.blackWhite)&&t.blackWhite.length===3&&t.blackWhite.every(W))?`blackWhite must be true or [r, g, b]`:t.invert!==void 0&&typeof t.invert!=`boolean`?`invert must be true or false`:t.gradientMap!==void 0&&!(Array.isArray(t.gradientMap)&&t.gradientMap.length>=2&&t.gradientMap.every(e=>Array.isArray(e)&&e.length===2&&W(e[0])&&K(e[1])))?`gradientMap must be two or more [0..1, colour]`:null}let ke={gaussian:[`radius`],motion:[`angle`,`distance`],spin:[`at`,`angle`],zoom:[`at`,`amount`],lens:[`radius`,`highlights`],sharpen:[`amount`,`radius`,`threshold`],highPass:[`radius`],noise:[`amount`,`scale`,`mono`,`seed`],median:[`radius`],emboss:[`angle`,`height`,`amount`],ripple:[`amount`,`size`,`seed`],displace:[`amount`,`size`,`seed`],twirl:[`at`,`radius`,`angle`],pixelate:[`cell`],chromatic:[`at`,`amount`],vignette:[`at`,`amount`,`radius`,`outer`,`color`],fog:[`color`,`density`,`from`,`to`,`patchiness`,`size`,`seed`],rays:[`at`,`threshold`,`length`,`strength`,`decay`],flare:[`at`,`size`,`color`,`strength`],texture:[`scale`,`amount`,`angle`,`seed`]};function Ae(e,t){if(typeof e!=`string`||!Object.prototype.hasOwnProperty.call(ke,e))return`filter ${JSON.stringify(e)} must be one of ${Object.keys(ke).join(`, `)}`;if(t===void 0)return null;if(typeof t!=`object`||!t)return`params must be an object`;let n=ke[e];for(let[r,i]of Object.entries(t)){if(!n.includes(r))return`filter ${e} has unknown \"${r}\"; it takes ${n.join(`, `)}`;if(r===`color`){if(!K(i))return`filter ${e}: color must be #rgb..#rrggbbaa`}else if(r===`at`||r===`from`||r===`to`){if(!G(i))return`filter ${e}: ${r} must be [x, y]`}else if(r===`mono`){if(typeof i!=`boolean`)return`filter ${e}: mono must be true or false`}else if(!W(i))return`filter ${e}: ${r} must be a number`}return null}let je={ink:{hardness:1,taper:[.12,.3]},pen:{hardness:1,roundness:.25,angle:-45},pencil:{hardness:.6,grain:.35,grainScale:1.2,opacity:.75},charcoal:{hardness:.35,grain:.5,grainScale:2.2,dry:.12,opacity:.95},chalk:{hardness:.7,grain:.55,grainScale:6,opacity:.95},flat:{hardness:.85,roundness:.3,dry:.3},oil:{hardness:.65,roundness:.55,dry:.22,wet:.55,opacity:.95},gouache:{hardness:.8,roundness:.5,wet:.2,dry:.08,opacity:.95},watercolor:{hardness:.2,wet:.45,edge:.5,opacity:.45,grain:.05,grainScale:5},marker:{hardness:.9,roundness:.45,angle:-30,opacity:.72},airbrush:{hardness:0,flow:.05},spray:{hardness:.7,dab:.07,scatter:1,spacing:.5,opacity:.9},dry:{hardness:.75,roundness:.35,dry:.65,opacity:.95}},Me=[`brush`,`roundness`,`angle`,`grain`,`grainScale`,`dry`,`wet`,`edge`,`scatter`,`dab`,`spacing`,`flow`,`fade`],W=e=>typeof e==`number`&&Number.isFinite(e),G=e=>Array.isArray(e)&&e.length===2&&e.every(W),K=e=>typeof e==`string`&&/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(e);function Ne(e){if(typeof e==`string`)return K(e)?null:`${JSON.stringify(e)} must be #rgb, #rgba, #rrggbb or #rrggbbaa`;let t=e;if(typeof t!=`object`||!t)return`must be a colour or a gradient`;if(t.type!==`linear`&&t.type!==`radial`&&t.type!==`noise`&&t.type!==`form`&&t.type!==`image`&&t.type!==`grid`)return`a gradient has type linear, radial, noise, form, image or grid`;if(t.type===`grid`){if(!Array.isArray(t.colors)||t.colors.length===0||!t.colors.every(K))return`a grid needs colors: one or more`;for(let e of[`ground`,`off`])if(t[e]!==void 0&&!K(t[e]))return`a grid's ${e} must be a colour`;let e=t.quad;if(e!==void 0&&!(Array.isArray(e)&&e.length===4&&e.every(G)))return`a grid's quad must be four [x, y], in order round from the top left`;if(t.cell===void 0&&t.cells===void 0)return`a grid needs cell: [w, h] in pixels, or cells: [columns, rows]`;for(let e of[`cell`,`cells`])if(t[e]!==void 0&&!(G(t[e])&&t[e].every(e=>e>0)))return`a grid's ${e} must be two positive numbers`;return t.cell!==void 0&&e!==void 0?`a grid on a quad is counted in cells: [columns, rows]`:t.mark!==void 0&&!(G(t.mark)&&t.mark.every(e=>e>0&&e<=1))?`a grid's mark must be [w, h], each above 0 and up to 1`:t.lit!==void 0&&!(W(t.lit)&&t.lit>=0&&t.lit<=1)?`a grid's lit must be 0..1`:t.seed!==void 0&&!Number.isInteger(t.seed)?`a grid's seed must be a whole number`:null}if(t.type===`image`)return typeof t.image==`string`&&t.image?null:`an image fill needs image, the id of an image layer drawn before it`;if(t.type===`form`){if(typeof t.figure!=`string`||!t.figure)return`a form needs figure, the id of a figure drawn before it`;if(t.light!==void 0&&!(Array.isArray(t.light)&&t.light.length===3&&t.light.every(W)))return`a form's light must be [x, y, z], x right, y up, z toward the viewer`}if(t.type===`noise`){if(t.scale!==void 0&&!(W(t.scale)&&t.scale>0))return`noise scale must be a positive number of pixels`;if(t.octaves!==void 0&&!(Number.isInteger(t.octaves)&&t.octaves>=1&&t.octaves<=8))return`noise octaves must be a whole number from 1 to 8`;if(t.seed!==void 0&&!Number.isInteger(t.seed))return`noise seed must be a whole number`}if(t.type===`linear`&&!(G(t.from)&&G(t.to)))return`a linear gradient needs from and to, each [x, y]`;if(t.type===`linear`&&t.from[0]===t.to[0]&&t.from[1]===t.to[1])return`a linear gradient needs from and to apart: at one point it draws a single flat colour`;if(t.type===`radial`&&!(G(t.at)&&W(t.radius)&&t.radius>0))return`a radial gradient needs at: [x, y] and a positive radius`;if(!Array.isArray(t.stops)||t.stops.length<2)return`a gradient needs two stops or more, each [0..1, colour]`;for(let e of t.stops)if(!Array.isArray(e)||e.length!==2||!W(e[0])||!K(e[1]))return`a stop ${JSON.stringify(e)} must be [0..1, colour]`;return null}let Pe=`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.text.fontSize.font.weight.align.vertical.tracking.vanish.depth.faces.roof.y.edge.reach.ripple.smear.quad.threshold.strength.thin.grain.grainScale.dry.face.within.feather.clipFeather.clipGrow.clipInvert.blendIf.adjust.filter.params`.split(`.`),Fe=e=>e.guide??(e.shape===`figure`||e.shape===`image`||e.shape===`perspective`),Ie=[`rect`,`circle`,`ellipse`,`ring`,`polygon`,`line`,`star`,`gear`,`path`,`pixels`,`paint`,`figure`,`image`,`text`,`block`,`perspective`,`reflect`,`bloom`,`adjust`,`filter`,`group`],Le=[`points`,`color`,`to`,`size`,`hardness`,`opacity`,`taper`,`bristles`,`strand`,`spread`,`vary`,`wobble`,`seed`,`smudge`,`erase`,`blend`,...Me];function Re(e){if(e.brush!==void 0&&!(typeof e.brush==`string`&&Object.prototype.hasOwnProperty.call(je,e.brush)))return`brush ${JSON.stringify(e.brush)} must be one of ${Object.keys(je).join(`, `)}`;for(let t of[`roundness`,`grain`,`dry`,`wet`,`edge`,`dab`,`flow`])if(e[t]!==void 0&&!(W(e[t])&&e[t]>=0&&e[t]<=1))return`${t} must be 0..1`;if(e.roundness===0||e.dab===0)return`${e.roundness===0?`roundness`:`dab`} must be above 0`;for(let t of[`grainScale`,`spacing`])if(e[t]!==void 0&&!(W(e[t])&&e[t]>0))return`${t} must be positive`;return e.scatter!==void 0&&!(W(e.scatter)&&e.scatter>=0)?`scatter must be 0 or more`:e.angle!==void 0&&!W(e.angle)?`angle must be degrees`:e.fade!==void 0&&!(Array.isArray(e.fade)&&e.fade.length===2&&e.fade.every(e=>W(e)&&e>=0&&e<=1))?`fade must be [start, end], each 0..1`:null}let ze=[`type`,`guides`,`colors`,`count`,`tip`,`size`,`clumps`,`gather`,`flyaway`,`vary`,`wobble`,`opacity`,`taper`,`seed`,`hardness`,...Me],Be=[`type`,`line`,`count`,`strokes`,`scale`,`turn`,`both`,`jitter`,`seed`],Ve=[`type`,`region`,`guides`,`angle`,`tone`,`smudge`,`size`,`length`,`coverage`,`spread`,`vary`,`opacity`,`hardness`,`seed`,`taper`,...Me],He=e=>Array.isArray(e)&&e.length>=2&&e.every(e=>Array.isArray(e)&&(e.length===2||e.length===3)&&e.every(W)),Ue=3e4;function We(e){let t=t=>{for(let n of t)if(e[n]!==void 0&&!(W(e[n])&&e[n]>=0&&e[n]<=1))return`${n} must be 0..1`;return null},n=e.type===`sweep`?ze:e.type===`along`?Be:Ve;for(let t of Object.keys(e))if(!n.includes(t))return`has unknown field \"${t}\"; a ${String(e.type)} takes ${n.join(`, `)}`;if(e.seed!==void 0&&!Number.isInteger(e.seed))return`seed must be a whole number`;if(e.type!==`along`){let t=Re(e);if(t)return t}if(e.type===`sweep`){if(!Array.isArray(e.guides)||e.guides.length<2||!e.guides.every(He))return`needs guides: two or more lines, each two or more [x, y]`;if(!Array.isArray(e.colors)||e.colors.length===0||!e.colors.every(K))return`needs colors: one or more, across the guides`;if(e.tip!==void 0&&!K(e.tip))return`tip must be a colour`;if(!(Number.isInteger(e.count)&&e.count>=1&&e.count<=3e4))return`count must be a whole number from 1 to ${Ue}`;if(e.clumps!==void 0&&!(Number.isInteger(e.clumps)&&e.clumps>=1))return`clumps must be a whole number of 1 or more`;for(let t of[`size`,`wobble`])if(e[t]!==void 0&&!(W(e[t])&&e[t]>=0))return`${t} must be 0 or more`;return e.taper!==void 0&&!(Array.isArray(e.taper)&&e.taper.length===2&&e.taper.every(e=>W(e)&&e>=0&&e<=1))?`taper must be [start, end], each 0..1`:t([`gather`,`flyaway`,`vary`,`opacity`])}if(e.type===`along`){if(!He(e.line))return`needs a line: two or more [x, y]`;if(!(Number.isInteger(e.count)&&e.count>=1&&e.count<=2e3))return`count must be a whole number from 1 to 2000`;if(!Array.isArray(e.strokes)||e.strokes.length===0)return`needs strokes, drawn about [0, 0]`;for(let[t,n]of e.strokes.entries()){if(n?.type!==void 0)return`strokes[${t}] must be a plain stroke`;let e=Ge(n);if(e)return`strokes[${t}] ${e}`}let t=e.scale;if(t!==void 0&&!(W(t)&&t>0)&&!(G(t)&&t.every(e=>e>0)))return`scale must be a positive number, or [start, end]`;for(let t of[`turn`,`jitter`])if(e[t]!==void 0&&!W(e[t]))return`${t} must be a number`;return null}if(e.region!==void 0){if(typeof e.region!=`string`)return`region must be an SVG path or \"@id\"`;if(!e.region.startsWith(`@`))try{Te(e.region)}catch(e){return`region: ${e.message}`}}if(e.guides!==void 0&&!(Array.isArray(e.guides)&&e.guides.length>0&&e.guides.every(He)))return`guides must be one or more lines, each two or more [x, y]`;if(e.angle!==void 0&&!W(e.angle))return`angle must be degrees`;if(e.tone===void 0&&!e.smudge)return`needs a tone, unless it smudges`;if(e.tone!==void 0){let t=Ne(e.tone);if(t)return`tone ${t}`}for(let t of[`size`,`length`,`coverage`])if(e[t]!==void 0&&!(W(e[t])&&e[t]>0))return`${t} must be positive`;return e.size===void 0?`needs a positive size`:e.spread!==void 0&&!(W(e.spread)&&e.spread>=0)?`spread must be 0 or more degrees`:t([`vary`,`opacity`,`hardness`,`smudge`])}function Ge(e){if(typeof e!=`object`||!e)return`must be an object`;if(e.type===void 0){let t=Re(e);if(t)return t}if(e.type===`sweep`||e.type===`field`||e.type===`along`)return We(e);if(e.type!==void 0)return`has type \"${String(e.type)}\"; there are sweep, field and along, or none for one stroke`;for(let t of Object.keys(e))if(!Le.includes(t))return`has unknown field \"${t}\"; a stroke takes ${Le.join(`, `)}`;if(!Array.isArray(e.points)||e.points.length===0||!e.points.every(e=>Array.isArray(e)&&(e.length===2||e.length===3)&&e.every(W)))return`needs points, each [x, y] or [x, y, pressure]`;if(!(W(e.size)&&e.size>0))return`needs a positive size`;if(!e.erase&&!e.smudge&&e.color===void 0)return`needs a color, unless it erases or smudges`;for(let t of[`color`,`to`])if(e[t]!==void 0&&!K(e[t]))return`${t} must be #rgb, #rgba, #rrggbb or #rrggbbaa`;for(let t of[`hardness`,`opacity`,`vary`,`smudge`])if(e[t]!==void 0&&!(W(e[t])&&e[t]>=0&&e[t]<=1))return`${t} must be 0..1`;for(let t of[`strand`,`spread`,`wobble`])if(e[t]!==void 0&&!(W(e[t])&&e[t]>=0))return`${t} must be 0 or more`;return e.bristles!==void 0&&!(Number.isInteger(e.bristles)&&e.bristles>=1&&e.bristles<=200)?`bristles must be a whole number from 1 to 200`:e.seed!==void 0&&!Number.isInteger(e.seed)?`seed must be a whole number`:e.taper!==void 0&&!(Array.isArray(e.taper)&&e.taper.length===2&&e.taper.every(e=>W(e)&&e>=0&&e<=1))?`taper must be [start, end], each 0..1`:e.blend!==void 0&&!Ee.includes(e.blend)?`blend must be one of ${Ee.join(`, `)}`:null}function Ke(e,t,n){let r=e=>{throw Error(`${t}: ${e}`)};(typeof e!=`object`||!e)&&r(`must be an object`);for(let t of Object.keys(e))Pe.includes(t)||r(`unknown field \"${t}\"; a layer takes ${Pe.join(`, `)}`);Ie.includes(e.shape)||r(`shape ${JSON.stringify(e.shape)} must be one of ${Ie.join(`, `)}`),e.id!==void 0&&((typeof e.id!=`string`||!e.id)&&r(`id must be a string`),n.has(e.id)&&r(`the id \"${String(e.id)}\" is already used`),n.add(e.id));let i=(t,n=()=>!0)=>{(!W(e[t])||!n(e[t]))&&r(`${t} must be a number${n===o?` above 0`:``}`)},a=t=>{G(e[t])||r(`${t} must be [a, b]`)},o=e=>e>0;switch(e.shape){case`rect`:e.face===void 0&&(a(`at`),a(`size`)),e.radius!==void 0&&!W(e.radius)&&!(Array.isArray(e.radius)&&e.radius.length===4&&e.radius.every(W))&&r(`radius must be a number or four corners`);break;case`circle`:a(`at`),i(`radius`,o);break;case`ellipse`:a(`at`),a(`radii`);break;case`ring`:a(`at`),i(`radius`,o),i(`inner`,o),e.inner>=e.radius&&r(`inner must be less than radius`);break;case`polygon`:case`line`:(!Array.isArray(e.points)||e.points.length<(e.shape===`line`?2:3)||!e.points.every(G))&&r(`points must be ${e.shape===`line`?`two`:`three`} or more [x, y]`),e.shape===`line`&&!e.stroke&&r(`a line needs a stroke: { color, width }`);break;case`star`:case`gear`:a(`at`),i(`radius`,o),i(`inner`,o),(!Number.isInteger(e.count)||e.count<3)&&r(`count must be 3 or more`);break;case`path`:(typeof e.d!=`string`||!e.d.trim())&&r(`d must be an SVG path: M L H V C S Q T Z`);try{Te(e.d).every(e=>e.points.length===0)&&r(`d draws nothing`)}catch(e){r(e.message)}break;case`figure`:{G(e.at)||r(`at must be [x, y]: the place on the floor under her`),W(e.height)&&e.height>0||r(`height must be pixels from floor to crown`);for(let t of[`yaw`,`pitch`])e[t]!==void 0&&!W(e[t])&&r(`${t} must be degrees`);e.light!==void 0&&!(Array.isArray(e.light)&&e.light.length===3&&e.light.every(W))&&r(`light must be [x, y, z], x right, y up, z toward the viewer`);let t=e.build;for(let[e,n]of Object.entries(t??{}))[`head`,`shoulders`,`chest`,`waist`,`hips`,`limbs`].includes(e)||r(`build has unknown \"${e}\"; it takes head, shoulders, chest, waist, hips, limbs`),W(n)&&n>0||r(`build ${e} must be positive`);let n=e.pose;for(let e of Object.keys(n??{}))[`rotate`,`move`,`reach`].includes(e)||r(`pose has unknown \"${e}\"; it takes rotate, move, reach`);for(let[e,t]of Object.entries(n??{}))for(let[n,i]of Object.entries(t)){let t=e===`reach`?i.at:i,a=e===`reach`?[2,3]:[3];Array.isArray(t)&&a.includes(t.length)&&t.every(W)||r(`pose ${e} \"${n}\" must be ${e===`reach`?`{ at: [x, y] or [x, y, z] }`:`[x, y, z]`}`)}break}case`text`:(typeof e.text!=`string`||!e.text)&&r(`text must say something`),e.within!==void 0&&!(Array.isArray(e.within)&&e.within.length===4&&e.within.every(e=>W(e)&&e>=0&&e<=1))&&r(`within must be [left, top, right, bottom], each 0..1`),e.face===void 0?e.quad===void 0?(a(`at`),W(e.fontSize)&&e.fontSize>0||r(`fontSize must be positive, in pixels`)):Array.isArray(e.quad)&&e.quad.length===4&&e.quad.every(G)||r(`quad must be four [x, y], in order round from the top left`):typeof e.face!=`string`&&r(`face must name a face of a block, as \"id.a\"`),e.font!==void 0&&typeof e.font!=`string`&&r(`font must be a family name or a font file in the project`),e.align!==void 0&&![`left`,`center`,`right`].includes(e.align)&&r(`align must be left, center or right`),e.tracking!==void 0&&!W(e.tracking)&&r(`tracking must be pixels`),e.thin!==void 0&&!(W(e.thin)&&e.thin>=0)&&r(`thin must be 0 or more pixels`);for(let t of[`grain`,`dry`])e[t]!==void 0&&!(W(e[t])&&e[t]>=0&&e[t]<=1)&&r(`${t} must be 0..1`);e.grainScale!==void 0&&!(W(e.grainScale)&&e.grainScale>0)&&r(`grainScale must be positive`),e.fill===void 0&&e.stroke===void 0&&r(`it needs a fill or a stroke, or it draws nothing`);break;case`adjust`:{let t=Oe(e.adjust);t&&r(`adjust ${t}`);break}case`filter`:{let t=Ae(e.filter,e.params);t&&r(t);break}case`bloom`:for(let t of[`threshold`,`strength`])e[t]!==void 0&&!(W(e[t])&&e[t]>=0)&&r(`${t} must be 0 or more`);e.threshold!==void 0&&e.threshold>1&&r(`threshold must be 0..1`),e.radius!==void 0&&!(W(e.radius)&&e.radius>0)&&r(`radius must be positive, in pixels`);break;case`perspective`:(!Array.isArray(e.vanish)||e.vanish.length===0||!e.vanish.every(G))&&r(`vanish must be one or more [x, y]`);break;case`block`:a(`at`),W(e.height)&&e.height>0||r(`height must be pixels, from the corner at its foot up to its top`),(!Array.isArray(e.vanish)||e.vanish.length<1||e.vanish.length>2||!e.vanish.every(G))&&r(`vanish must be one or two [x, y], where its faces recede to`),(!Array.isArray(e.depth)||e.depth.length!==e.vanish.length||!e.depth.every(e=>W(e)&&e>0&&e<=1))&&r(`depth must give each vanishing point how far the face runs toward it, each above 0 and up to 1`),(!Array.isArray(e.faces)||e.faces.length!==e.vanish.length)&&r(`faces must give one fill for each vanishing point`);for(let t of e.faces){let e=Ne(t);e&&r(`face ${e}`)}if(e.roof!==void 0){let t=Ne(e.roof);t&&r(`roof ${t}`)}break;case`reflect`:!W(e.y)&&!(Array.isArray(e.edge)&&e.edge.length>=2&&e.edge.every(G))&&r(`y must be the line it mirrors about, or edge two or more [x, y] along where things meet the ground`);for(let t of[`reach`,`ripple`,`smear`])e[t]!==void 0&&!(W(e[t])&&e[t]>=0)&&r(`${t} must be 0 or more pixels`);break;case`image`:(typeof e.src!=`string`||!e.src)&&r(`src must be the path of a picture in the project`),e.at!==void 0&&!G(e.at)&&r(`at must be [x, y]`),e.size!==void 0&&!G(e.size)&&r(`size must be [w, h]`);break;case`paint`:Array.isArray(e.strokes)||r(`strokes must be an array, which may start empty`),e.face!==void 0&&typeof e.face!=`string`&&r(`face must name a face of a block, as \"id.a\"`),e.from!==void 0&&e.from!==`below`&&r(`from must be \"below\"`),e.from!==void 0&&(e.fill!==void 0||e.effects!==void 0||e.blend!==void 0)&&r(`from \"below\" works on the picture itself, and takes no fill, effects or blend`),e.strokes.forEach((e,t)=>{let n=Ge(e);n&&r(`stroke ${t} ${n}`)});break;case`pixels`:{(!Array.isArray(e.rows)||e.rows.length===0||!e.rows.every(e=>typeof e==`string`))&&r(`rows must be strings, one character a pixel`);let t=e.palette;(typeof t!=`object`||!t)&&r(`palette must be { character: colour }`);for(let[e,n]of Object.entries(t))[...e].length!==1&&r(`palette key ${JSON.stringify(e)} must be one character`),K(n)||r(`palette \"${e}\" ${JSON.stringify(n)} must be a colour`);let n=new Set(Object.keys(t)),s=e.rows[0].length;e.rows.forEach((e,t)=>{[...e].length!==s&&r(`row ${t} is ${[...e].length} wide and row 0 is ${s}: a slip here shifts everything after it`);for(let i of e)i!==`.`&&i!==` `&&!n.has(i)&&r(`row ${t} has \"${i}\", which is not in the palette; \".\" and \" \" are nothing`)}),e.scale!==void 0&&i(`scale`,o),e.at!==void 0&&a(`at`);break}case`group`:Array.isArray(e.layers)||r(`a group needs layers`),e.layers.forEach((e,r)=>Ke(e,`${t}.layers[${r}]`,n))}if(e.fill!==void 0){let t=Ne(e.fill);t&&r(`fill ${t}`)}if(e.stroke!==void 0){let t=e.stroke;(typeof t!=`object`||!t||!W(t.width)||t.width<=0)&&r(`stroke must be { color, width, align? }`);let n=Ne(t.color);n&&r(`stroke color ${n}`),t.align!==void 0&&![`center`,`inside`,`outside`].includes(t.align)&&r(`stroke align must be center, inside or outside`),t.join!==void 0&&![`round`,`miter`,`bevel`].includes(t.join)&&r(`stroke join must be round, miter or bevel`),t.cap!==void 0&&![`round`,`butt`,`square`].includes(t.cap)&&r(`stroke cap must be round, butt or square`)}![`group`,`pixels`,`paint`,`figure`,`image`,`text`,`block`,`perspective`,`reflect`,`bloom`,`adjust`,`filter`,`line`].includes(e.shape)&&e.fill===void 0&&e.stroke===void 0&&!e.erase&&r(`it needs a fill or a stroke, or it draws nothing`),e.from!==void 0&&e.shape!==`paint`&&r(`from is for a paint layer`),e.guide!==void 0&&typeof e.guide!=`boolean`&&r(`guide must be true or false`),e.blur!==void 0&&!(W(e.blur)&&e.blur>=0)&&r(`blur must be 0 or more, in pixels`),e.blur&&e.erase&&r(`blur does not go with erase; put what cuts in a group with what it cuts, and blur the group`),e.opacity!==void 0&&!(W(e.opacity)&&e.opacity>=0&&e.opacity<=1)&&r(`opacity must be 0..1`),e.blend!==void 0&&!Ee.includes(e.blend)&&r(`blend must be one of ${Ee.join(`, `)}`);for(let t of[`feather`,`clipFeather`])e[t]!==void 0&&!(W(e[t])&&e[t]>=0)&&r(`${t} must be 0 or more pixels`);if(e.clipGrow!==void 0&&!W(e.clipGrow)&&r(`clipGrow must be pixels, more to grow what it clips to and less to shrink it`),e.clipInvert!==void 0&&typeof e.clipInvert!=`boolean`&&r(`clipInvert must be true or false`),e.blendIf!==void 0&&!(Array.isArray(e.blendIf)&&(e.blendIf.length===2||e.blendIf.length===3)&&e.blendIf.every(e=>W(e)&&e>=0&&e<=1))&&r(`blendIf must be [low, high] or [low, high, softness], each 0..1`),e.mirror!==void 0&&e.mirror!==`x`&&e.mirror!==`y`&&r(`mirror must be x or y`),e.clip!==void 0&&typeof e.clip!=`string`&&r(`clip must be a layer id`),e.transform!==void 0){let t=e.transform;for(let e of Object.keys(t))[`translate`,`rotate`,`scale`,`origin`].includes(e)||r(`transform has an unknown field \"${e}\"`);t.translate!==void 0&&!G(t.translate)&&r(`transform.translate must be [x, y]`),t.origin!==void 0&&!G(t.origin)&&r(`transform.origin must be [x, y]`),t.rotate!==void 0&&!W(t.rotate)&&r(`transform.rotate must be degrees`),t.scale!==void 0&&!W(t.scale)&&!G(t.scale)&&r(`transform.scale must be a number or [x, y]`)}if(e.effects!==void 0){Array.isArray(e.effects)||r(`effects must be an array`);for(let t of e.effects){if([`shadow`,`glow`,`innerShadow`,`innerGlow`,`bevel`,`overlay`].includes(t?.type)||r(`an effect has type ${JSON.stringify(t?.type)}; there are shadow, glow, innerShadow, innerGlow, bevel, overlay`),t.type===`overlay`){let e=Ne(t.fill);e&&r(`effect overlay: fill ${e}`)}t.blend!==void 0&&!Ee.includes(t.blend)&&r(`effect ${String(t.type)}: blend must be one of ${Ee.join(`, `)}`),t.shade!==void 0&&!K(t.shade)&&r(`effect ${String(t.type)}: shade must be #rgb..#rrggbbaa`);for(let e of Object.keys(t))[`type`,`color`,`x`,`y`,`blur`,`opacity`,`size`,`angle`,`depth`,`shade`,`fill`,`blend`].includes(e)||r(`effect ${String(t.type)} has an unknown field \"${e}\"`);t.color!==void 0&&!K(t.color)&&r(`effect ${String(t.type)}: color must be #rgb..#rrggbbaa`);for(let e of[`x`,`y`,`blur`,`opacity`,`size`,`angle`,`depth`])t[e]!==void 0&&!W(t[e])&&r(`effect ${String(t.type)}: ${e} must be a number`)}}}function qe(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`an image source must be { size, layers }`);let t=e;for(let e of Object.keys(t))if(![`version`,`size`,`background`,`tile`,`material`,`layers`].includes(e))throw Error(`unknown field \"${e}\"; an image has version, size, background, tile, material, layers`);if(t.tile!==void 0&&typeof t.tile!=`boolean`)throw Error(`tile must be true or false`);if(t.version!==void 0&&t.version!==1)throw Error(`version ${String(t.version)} is not one this editor reads (1)`);let[n,r]=typeof t.size==`number`?[t.size,t.size]:G(t.size)?t.size:[NaN,NaN];if(!Number.isInteger(n)||!Number.isInteger(r)||n<1||r<1||n>2048||r>2048)throw Error(`size must be a whole number or [width, height], 1..2048`);if(t.background!==void 0&&!K(t.background))throw Error(`background must be a colour; leave it out for a transparent picture`);if(!Array.isArray(t.layers))throw Error(`layers must be an array`);let i=new Set;if(t.layers.forEach((e,t)=>Ke(e,`layer ${t}${e?.id?` \"${String(e.id)}\"`:``}`,i)),t.material!==void 0){let e=t.material;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`material must be { relief?, height?, roughness?, metal? }`);for(let t of Object.keys(e))if(![`relief`,`height`,`roughness`,`metal`].includes(t))throw Error(`material has unknown \"${t}\"; it takes relief, height, roughness, metal`);if(e.relief!==void 0&&!(W(e.relief)&&e.relief>=0&&e.relief<=64))throw Error(`material.relief must be 0..64, in pixels`);let n=(e,t)=>{if(!Array.isArray(t)||t.length===0)throw Error(`material.${e} must be layers, one or more`);t.forEach((t,n)=>Ke(t,`material.${e} layer ${n}${t?.id?` \"${String(t.id)}\"`:``}`,i))};e.height!==void 0&&n(`height`,e.height);for(let t of[`roughness`,`metal`]){let r=e[t];if(r!==void 0)if(W(r)){if(r<0||r>1)throw Error(`material.${t} must be 0..1, or layers`)}else n(t,r)}}return{version:1,...t}}let Je=e=>{let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]},Ye=[1,0,0,1,0,0],Xe=0,Ze=0,Qe=(e,t)=>[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]],q=(e,[t,n])=>[e[0]*t+e[2]*n+e[4],e[1]*t+e[3]*n+e[5]];function $e(e){let t=e[0]*e[3]-e[1]*e[2]||1e-12;return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[3]*e[4])/t,(e[1]*e[4]-e[0]*e[5])/t]}function et(e,t){if(!e)return Ye;let[n,r]=e.origin??t,i=(e.rotate??0)*Math.PI/180,[a,o]=typeof e.scale==`number`?[e.scale,e.scale]:e.scale??[1,1],[s,c]=e.translate??[0,0],l=[1,0,0,1,s+n,c+r];return l=Qe(l,[Math.cos(i),Math.sin(i),-Math.sin(i),Math.cos(i),0,0]),l=Qe(l,[a,0,0,o,0,0]),Qe(l,[1,0,0,1,-n,-r])}function tt(e,t,n,r){let i=Math.max(48,Math.ceil(Math.max(n,r)*2));return Array.from({length:i},(a,o)=>[e+n*Math.cos(o/i*Math.PI*2),t+r*Math.sin(o/i*Math.PI*2)])}function nt(e,t,n,r,i){let a=typeof i==`number`?[i,i,i,i]:i,o=Math.min(n,r)/2,[s,c,l,u]=[0,1,2,3].map(e=>Math.max(0,Math.min(o,a[e]??0))),d=[],f=(e,t,n,r)=>{if(n<=0){d.push([e,t]);return}let i=Math.max(4,Math.ceil(n));for(let a=0;a<=i;a++){let o=r+a/i*(Math.PI/2);d.push([e+n*Math.cos(o),t+n*Math.sin(o)])}};return f(e+s,t+s,s,Math.PI),f(e+n-c,t+c,c,-Math.PI/2),f(e+n-l,t+r-l,l,0),f(e+u,t+r-u,u,Math.PI/2),d}function rt(e){let t=e=>[{points:e,closed:!0}];switch(e.shape){case`rect`:{let[n,r]=e.at,[i,a]=e.size;return{runs:t(nt(n,r,i,a,e.radius??0)),middle:[n+i/2,r+a/2]}}case`circle`:{let[n,r]=e.at;return{runs:t(tt(n,r,e.radius,e.radius)),middle:[n,r]}}case`ellipse`:{let[n,r]=e.at,[i,a]=e.radii;return{runs:t(tt(n,r,i,a)),middle:[n,r]}}case`ring`:{let[n,r]=e.at,i=tt(n,r,e.inner,e.inner).reverse();return{runs:[...t(tt(n,r,e.radius,e.radius)),...t(i)],middle:[n,r]}}case`polygon`:case`line`:{let t=e.points,n=t.reduce((e,n)=>[e[0]+n[0]/t.length,e[1]+n[1]/t.length],[0,0]);return{runs:[{points:t,closed:e.shape===`polygon`}],middle:n}}case`star`:case`gear`:{let[n,r]=e.at,i=e.count,a=e.radius,o=e.inner,s=[],c=(e.turn??-90)*Math.PI/180;if(e.shape===`star`)for(let e=0;e<i*2;e++){let t=e%2==0?a:o,l=c+e/(i*2)*Math.PI*2;s.push([n+t*Math.cos(l),r+t*Math.sin(l)])}else{let t=Math.PI*2/i,l=(e.tooth??.3)*t,u=l*1.5;for(let e=0;e<i;e++){let i=c+e*t;for(let[e,t]of[[o,-u],[a,-l],[a,l],[o,u]])s.push([n+e*Math.cos(i+t),r+e*Math.sin(i+t)])}}return{runs:t(s),middle:[n,r]}}case`path`:{let t=Te(e.d),n=t.flatMap(e=>e.points);if(n.length===0)throw Error(`path draws nothing`);return{runs:t,middle:n.reduce((e,t)=>[e[0]+t[0]/n.length,e[1]+t[1]/n.length],[0,0])}}default:return{runs:[],middle:[0,0]}}}let it=[[0,0],[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[1,-1],[-1,1],[1,1]];function at(e,t,n,r,i,a){let[o,s,c,l]=[1/0,1/0,-1/0,-1/0];for(let t of e)t[0]<o&&(o=t[0]),t[0]>c&&(c=t[0]),t[1]<s&&(s=t[1]),t[1]>l&&(l=t[1]);return c+t+r>0&&o+t-r<i&&l+n+r>0&&s+n-r<a}function ot(e,t,n,r,i){if(!L())return i(0,0);let a=null;for(let[o,s]of it){let[c,l]=[o*n,s*r];if((o!==0||s!==0)&&!at(e(),c,l,t,n,r))continue;let u=i(c,l);if(!a){a=u;continue}for(let e=0;e<a.length;e++)u[e]>a[e]&&(a[e]=u[e])}return a??new Float32Array(n*r)}function st(e,t,n){return ot(()=>e.flat(),1,t,n,(r,i)=>ct(r===0&&i===0?e:e.map(e=>e.map(([e,t])=>[e+r,t+i])),t,n))}function ct(e,t,n){let r=new Float32Array(t*n),i=[],a=1/0,o=-1/0;for(let t of e)for(let e=0;e<t.length;e++){let[n,r]=[t[e],t[(e+1)%t.length]];if(n[1]===r[1])continue;let s=n[1]<r[1];i.push(s?{x0:n[0],y0:n[1],x1:r[0],y1:r[1],dir:1}:{x0:r[0],y0:r[1],x1:n[0],y1:n[1],dir:-1}),a=Math.min(a,n[1],r[1]),o=Math.max(o,n[1],r[1])}if(i.length===0)return r;let s=1/8,c=Math.max(0,Math.floor(a)),l=Math.min(n-1,Math.ceil(o)),u=[];for(let e=c;e<=l;e++)for(let n=0;n<8;n++){let a=e+(n+.5)*s;u.length=0;for(let e of i)a<e.y0||a>=e.y1||u.push({x:e.x0+(a-e.y0)/(e.y1-e.y0)*(e.x1-e.x0),dir:e.dir});if(u.length<2)continue;u.sort((e,t)=>e.x-t.x);let o=0;for(let n=0;n+1<u.length;n++){if(o+=u[n].dir,o===0)continue;let[i,a]=[Math.max(0,u[n].x),Math.min(t,u[n+1].x)];if(a<=i)continue;let[c,l]=[Math.floor(i),Math.min(t-1,Math.floor(a))],d=e*t;if(c===l){r[d+c]+=(a-i)*s;continue}r[d+c]+=(c+1-i)*s;for(let e=c+1;e<l;e++)r[d+e]+=s;r[d+l]+=(a-l)*s}}for(let e=0;e<r.length;e++)r[e]>1&&(r[e]=1);return r}function lt(e,t,n,r,i=`round`,a=`round`){return ot(()=>e.flatMap(e=>e.points),t*(i===`miter`?10:1)+2,n,r,(o,s)=>ut(o===0&&s===0?e:e.map(e=>({closed:e.closed,points:e.points.map(([e,t])=>[e+o,t+s])})),t,n,r,i,a))}function ut(e,t,n,r,i=`round`,a=`round`){let o=new Float32Array(n*r),s=t/2,c=(e,t)=>{let[i,a]=[Math.max(0,Math.floor(Math.min(e[0],t[0])-s-1)),Math.min(n-1,Math.ceil(Math.max(e[0],t[0])+s+1))],[c,l]=[Math.max(0,Math.floor(Math.min(e[1],t[1])-s-1)),Math.min(r-1,Math.ceil(Math.max(e[1],t[1])+s+1))],[u,d]=[t[0]-e[0],t[1]-e[1]],f=u*u+d*d;for(let t=c;t<=l;t++)for(let r=i;r<=a;r++){let[i,a]=[r+.5-e[0],t+.5-e[1]],c=f>0?Math.max(0,Math.min(1,(i*u+a*d)/f)):0,l=Math.max(0,Math.min(1,s-Math.hypot(i-u*c,a-d*c)+.5));l>o[t*n+r]&&(o[t*n+r]=l)}},l=e=>{let t=0;for(let n=0;n<e.length;n++){let[r,i]=[e[n],e[(n+1)%e.length]];t+=r[0]*i[1]-i[0]*r[1]}if(t===0)return;let i=e.map((n,r)=>{let i=e[(r+1)%e.length],a=Math.hypot(i[0]-n[0],i[1]-n[1])||1;return{x:n[0],y:n[1],nx:-(i[1]-n[1])/a*Math.sign(t),ny:(i[0]-n[0])/a*Math.sign(t)}}),[a,s]=[e.map(e=>e[0]),e.map(e=>e[1])],[c,l]=[Math.max(0,Math.floor(Math.min(...a)-1)),Math.min(n-1,Math.ceil(Math.max(...a)+1))],[u,d]=[Math.max(0,Math.floor(Math.min(...s)-1)),Math.min(r-1,Math.ceil(Math.max(...s)+1))];for(let e=u;e<=d;e++)for(let t=c;t<=l;t++){let r=1/0;for(let n of i)r=Math.min(r,(t+.5-n.x)*n.nx+(e+.5-n.y)*n.ny);if(r<=-.75)continue;let a=1;if(r<.75){let n=0;for(let r=0;r<6;r++)for(let a=0;a<6;a++){let[o,s]=[t+(a+.5)/6,e+(r+.5)/6];i.every(e=>(o-e.x)*e.nx+(s-e.y)*e.ny>=0)&&n++}a=n/36}a>o[e*n+t]&&(o[e*n+t]=a)}};for(let t of e){if(i===`round`&&a===`round`){let e=t.closed?t.points.length:t.points.length-1;for(let n=0;n<e;n++)c(t.points[n],t.points[(n+1)%t.points.length]);continue}let e=t.points.filter((e,t,n)=>t===0||Math.hypot(e[0]-n[t-1][0],e[1]-n[t-1][1])>1e-6);if(t.closed&&e.length>1&&Math.hypot(e[0][0]-e[e.length-1][0],e[0][1]-e[e.length-1][1])<=1e-6&&e.pop(),e.length<2){e[0]&&a!==`butt`&&c(e[0],e[0]);continue}let n=t.closed?e.length:e.length-1,r=t=>{let[n,r]=[e[t],e[(t+1)%e.length]],i=Math.hypot(r[0]-n[0],r[1]-n[1]);return[(r[0]-n[0])/i,(r[1]-n[1])/i]};for(let i=0;i<n;i++){let[o,c]=[e[i],e[(i+1)%e.length]],u=r(i),[d,f]=[-u[1]*s,u[0]*s],p=e=>e?a===`square`?s:0:.75,[m,h]=[p(!t.closed&&i===0),p(!t.closed&&i===n-1)],[g,_,v,y]=[o[0]-u[0]*m,o[1]-u[1]*m,c[0]+u[0]*h,c[1]+u[1]*h];l([[g+d,_+f],[v+d,y+f],[v-d,y-f],[g-d,_-f]])}!t.closed&&a===`round`&&(c(e[0],e[0]),c(e[e.length-1],e[e.length-1]));for(let n=+!t.closed;n<(t.closed?e.length:e.length-1);n++){let t=e[n],[a,o]=[r((n-1+e.length)%e.length),r(n)],u=a[0]*o[1]-a[1]*o[0];if(i===`round`){c(t,t);continue}if(Math.abs(u)<1e-6)continue;let d=u>0?-1:1,[f,p]=[[-a[1]*d,a[0]*d],[-o[1]*d,o[0]*d]],[m,h]=[[t[0]+f[0]*s,t[1]+f[1]*s],[t[0]+p[0]*s,t[1]+p[1]*s]],[g,_]=[f[0]+p[0],f[1]+p[1]],v=Math.hypot(g,_),y=v>0?2/v:1/0;l(i===`miter`&&y<=10?[t,m,[t[0]+g/v*s*y,t[1]+_/v*s*y],h]:[t,m,h])}}return o}function dt(e,t,n,r,i){let[a,o]=[Math.round(r),Math.round(i)];if(a===0&&o===0)return e;let s=new Float32Array(t*n);if(L()){for(let r=0;r<n;r++){let i=((r-o)%n+n)%n;for(let n=0;n<t;n++)s[r*t+n]=e[i*t+((n-a)%t+t)%t]}return s}for(let r=0;r<n;r++){let i=r-o;if(!(i<0||i>=n))for(let n=0;n<t;n++){let o=n-a;o>=0&&o<t&&(s[r*t+n]=e[i*t+o])}}return s}function ft(e){let[[t,n],[r,i],[a,o],[s,c]]=e,[l,u,d,f,p,m]=[r-a,s-a,t-r+a-s,i-o,c-o,n-i+o-c],h=l*p-u*f;if(Math.abs(h)<1e-9)return null;let g=(d*p-u*m)/h,_=(l*m-d*f)/h,[v,y,b,x,S,C]=[r-t+g*r,s-t+_*s,t,i-n+g*i,c-n+_*c,n],[w,T,E,D,O,k,A,ee,te]=[S-C*_,b*_-y,y*C-b*S,C*g-x,v-b*g,b*x-v*C,x*_-S*g,y*g-v*_,v*S-y*x];return(e,t)=>{let n=A*e+ee*t+te;return[(w*e+T*t+E)/n,(D*e+O*t+k)/n]}}function pt(e){let[[t,n],[r,i],[a,o],[s,c]]=e,[l,u,d,f,p,m]=[r-a,s-a,t-r+a-s,i-o,c-o,n-i+o-c],h=l*p-u*f||1e-9,g=(d*p-u*m)/h,_=(l*m-d*f)/h,[v,y,b,x,S,C]=[r-t+g*r,s-t+_*s,t,i-n+g*i,c-n+_*c,n];return(e,t)=>{let n=g*e+_*t+1;return[(v*e+y*t+b)/n,(x*e+S*t+C)/n]}}function mt(e,t){let[n,r]=e.face.replace(/^@/,``).split(`.`),i=r?t.blocks.get(n)?.[r]:void 0;if(!i)return t.notes.push(`layer ${e.id??e.shape}: face \"${e.face}\" names no face of a block drawn before it, so it drew nothing`),null;if(!e.within)return i;let a=pt(i),[o,s,c,l]=e.within;return[a(o,s),a(c,s),a(c,l),a(o,l)]}function ht(e,t){let n=e.colors.map(F),r=e.ground?F(e.ground):[0,0,0,0],i=e.off?F(e.off):r,[a,o]=e.mark??[.6,.6],[s,c]=[e.lit??1,e.seed??1],l=$e(t),u=e.quad?ft(e.quad):null,[d,f]=e.cells??[1,1],[p,m]=e.cell??[1,1],h=(e,t)=>{let h,g;if(u){let n=u(e,t);if(n[0]<0||n[1]<0||n[0]>1||n[1]>1)return r;[h,g]=[n[0]*d,n[1]*f]}else{let n=q(l,[e,t]);[h,g]=[n[0]/p,n[1]/m]}let[_,v]=[Math.floor(h),Math.floor(g)];return Math.abs(h-_-.5)>a/2||Math.abs(g-v-.5)>o/2?r:$(c*41+_,v)>=s?i:n[Math.floor($(c*43+v,_)*n.length)%n.length]};return(e,t)=>{let n=[0,0,0,0];for(let r=0;r<3;r++)for(let i=0;i<3;i++){let a=h(e-.5+(i+.5)/3,t-.5+(r+.5)/3);n[0]+=a[0]*a[3],n[1]+=a[1]*a[3],n[2]+=a[2]*a[3],n[3]+=a[3]}let r=n[3];return r>0?[n[0]/r,n[1]/r,n[2]/r,r/9]:[0,0,0,0]}}function gt(e,t,n,r=0){if(typeof e==`string`){let t=F(e);return()=>t}let i=[...e.type===`image`||e.type===`grid`?[]:e.stops].map(([e,t])=>[e,F(t)]).sort((e,t)=>e[0]-t[0]),a=$e(t),o=e=>{if(e<=i[0][0])return i[0][1];for(let t=1;t<i.length;t++)if(e<=i[t][0]){let[n,r]=i[t-1],[a,o]=i[t],s=(e-n)/Math.max(1e-6,a-n);return[r[0]+(o[0]-r[0])*s,r[1]+(o[1]-r[1])*s,r[2]+(o[2]-r[2])*s,r[3]+(o[3]-r[3])*s]}return i[i.length-1][1]};if(e.type===`image`){let t=n?.images.get(e.image);return t?(e,n)=>{let i=(Math.floor(n)*r+Math.floor(e))*4;return[t[i]??0,t[i+1]??0,t[i+2]??0,t[i+3]??0]}:(n?.notes.push(`a fill names image \"${e.image}\", which was not drawn before it`),()=>[0,0,0,0])}if(e.type===`grid`)return ht(e,t);if(e.type===`form`){let t=n?.figures.get(e.figure);if(!t)return n?.notes.push(`a form names figure \"${e.figure}\", which was not drawn before it`),()=>o(0);let i=e.light?Je(e.light):t.light;return(e,n)=>{let a=Math.floor(n)*r+Math.floor(e),[s,c,l]=[t.normals[a*3]??0,t.normals[a*3+1]??0,t.normals[a*3+2]??0];return o(.5+.5*(s*i[0]+c*i[1]+l*i[2]))}}if(e.type===`noise`){let[t,n,r]=[e.scale??32,e.octaves??4,e.seed??0];if(L()&&Xe>0){let[e,i]=[Math.max(1,Math.round(Xe/t)),Math.max(1,Math.round(Ze/t))];return(t,a)=>o(B((t-.5)/Xe*e,(a-.5)/Ze*i,n,r,e,i))}return(e,i)=>{let s=q(a,[e-.5,i-.5]);return o(B(s[0]/t,s[1]/t,n,r))}}if(e.type===`linear`){let[t,n]=[e.from,e.to],[r,i]=[n[0]-t[0],n[1]-t[1]],s=r*r+i*i||1;return(e,n)=>{let c=q(a,[e,n]);return o(((c[0]-t[0])*r+(c[1]-t[1])*i)/s)}}let[s,c]=e.at,l=e.radius;return(e,t)=>{let n=q(a,[e,t]);return o(Math.hypot(n[0]-s,n[1]-c)/l)}}var _t=class{constructor(e,t){this.w=e,this.h=t,this.px=new Float32Array(e*t*4)}};let vt=(e,t)=>{if(t<=.5)return e-(1-2*t)*e*(1-e);let n=e<=.25?((16*e-12)*e+4)*e:Math.sqrt(e);return e+(2*t-1)*(n-e)},yt=(e,t)=>e<=0?0:t>=1?1:Math.min(1,e/(1-t)),bt=(e,t)=>e>=1?1:t<=0?0:1-Math.min(1,(1-e)/t),xt=(e,t)=>t<.5?2*e*t:1-2*(1-e)*(1-t),St=(e,t,n)=>{switch(e){case`multiply`:return t*n;case`screen`:return t+n-t*n;case`overlay`:return xt(n,t);case`add`:return Math.min(1,t+n);case`softLight`:return vt(t,n);case`hardLight`:return xt(t,n);case`vividLight`:return n<.5?bt(t,2*n):yt(t,2*n-1);case`linearLight`:return Math.max(0,Math.min(1,t+2*n-1));case`pinLight`:return n<.5?Math.min(t,2*n):Math.max(t,2*n-1);case`colorDodge`:return yt(t,n);case`colorBurn`:return bt(t,n);case`linearBurn`:return Math.max(0,t+n-1);case`darken`:return Math.min(t,n);case`lighten`:return Math.max(t,n);case`difference`:return Math.abs(t-n);case`exclusion`:return t+n-2*t*n;case`subtract`:return Math.max(0,t-n);case`divide`:return n<=0?1:Math.min(1,t/n);default:return n}};function Ct(e,t){let n=t-H(e[0],e[1],e[2]),r=[e[0]+n,e[1]+n,e[2]+n],i=H(r[0],r[1],r[2]),[a,o]=[Math.min(...r),Math.max(...r)];if(a<0)for(let e=0;e<3;e++)r[e]=i+(r[e]-i)*i/(i-a);if(o>1)for(let e=0;e<3;e++)r[e]=i+(r[e]-i)*(1-i)/(o-i);return r}let wt=e=>Math.max(...e)-Math.min(...e);function Tt(e,t){let[n,r]=[Math.min(...e),Math.max(...e)];return r===n?[0,0,0]:[(e[0]-n)*t/(r-n),(e[1]-n)*t/(r-n),(e[2]-n)*t/(r-n)]}function Et(e,t,n){switch(e){case`hue`:return Ct(Tt(n,wt(t)),H(t[0],t[1],t[2]));case`saturation`:return Ct(Tt(t,wt(n)),H(t[0],t[1],t[2]));case`color`:return Ct(n,H(t[0],t[1],t[2]));default:return Ct(t,H(n[0],n[1],n[2]))}}let Dt=new Set([`hue`,`saturation`,`color`,`luminosity`]);function J(e,t,n,r,i,a,o){if(a<=0)return;let s=e.px,c=t*4,l=s[c+3];if(o===`normal`||l<=0)s[c]=s[c]*(1-a)+n*a,s[c+1]=s[c+1]*(1-a)+r*a,s[c+2]=s[c+2]*(1-a)+i*a;else{let[e,t,u]=[s[c]/l,s[c+1]/l,s[c+2]/l];if(Dt.has(o)){let d=Et(o,[e,t,u],[n,r,i]),[f,p,m]=[(1-l)*n+l*d[0],(1-l)*r+l*d[1],(1-l)*i+l*d[2]];s[c]=s[c]*(1-a)+f*a,s[c+1]=s[c+1]*(1-a)+p*a,s[c+2]=s[c+2]*(1-a)+m*a,s[c+3]=l+a-l*a;return}let d=(e,t)=>(1-l)*t+l*St(o,e,t);s[c]=s[c]*(1-a)+d(e,n)*a,s[c+1]=s[c+1]*(1-a)+d(t,r)*a,s[c+2]=s[c+2]*(1-a)+d(u,i)*a}s[c+3]=l+a-l*a}function Ot(e,t,n){let{w:r,h:i}=t,a=R(n,r,i,Math.max(.5,(e.size??4)/2)),o=(e.angle??225)*Math.PI/180,[s,c]=[Math.cos(o),Math.sin(o)],[l,u,d,f]=F(e.color??`#ffffff`),[p,m,h,g]=F(e.shade??`#000000`),_=(e.depth??1)*(e.size??4)*2,v=e.opacity??.8;for(let e=1;e<i-1;e++)for(let i=1;i<r-1;i++){let o=e*r+i;if(n[o]<=0)continue;let y=-((a[o+1]-a[o-1])*s+(a[o+r]-a[o-r])*c)*_;y>0?J(t,o,l,u,d,Math.min(1,y)*v*f*n[o],`screen`):y<0&&J(t,o,p,m,h,Math.min(1,-y)*v*g*n[o],`multiply`)}}function Y(e,t,n,r){let{w:i,h:a}=n;for(let o of e??[]){let e=o.type===`shadow`||o.type===`glow`;if(e!==t)continue;if(o.type===`bevel`){Ot(o,n,r);continue}if(o.type===`overlay`){let e=gt(o.fill,Ye);for(let t=0;t<a;t++)for(let a=0;a<i;a++){let s=t*i+a;if(r[s]<=0)continue;let c=e(a+.5,t+.5);J(n,s,c[0],c[1],c[2],c[3]*r[s]*(o.opacity??1),o.blend??`normal`)}continue}let[s,c,l,u]=F(o.color??(o.type===`glow`||o.type===`innerGlow`?`#ffffff`:`#000000`)),d=(o.opacity??1)*u,f=o.blur??(o.type===`glow`?8:4);if(e){let e=dt(r,i,a,o.x??0,o.y??0);o.type===`glow`&&(e=e.map(e=>Math.min(1,e*1.6)));let t=R(e,i,a,f);for(let e=0;e<t.length;e++)J(n,e,s,c,l,Math.min(1,t[e]*d),o.type===`glow`?`screen`:`normal`)}else{let e=R(dt(r.map(e=>1-e),i,a,o.x??0,o.y??0),i,a,f),t=o.type===`innerGlow`?`screen`:`normal`;for(let i=0;i<e.length;i++)J(n,i,s,c,l,Math.min(1,e[i]*r[i]*d),t)}}}function kt(e,t,n){let[r,i,a,o]=[e,t,-1,-1];for(let s=0;s<t;s++)for(let t=0;t<e;t++)n(s*e+t)&&(t<r&&(r=t),t>a&&(a=t),s<i&&(i=s),o=s);return a<0?null:[r,i,a-r+1,o-i+1]}function X(e,t,n,r,i){if(!t)return;let a=0;for(let e=0;e<n.length;e++)n[e]>a&&(a=n[e]);if(a<=.004)return;let o=kt(r,i,e=>n[e]>=Math.min(.5,a/2));o&&e.bounds.set(t,o)}function Z(e,t,n,r){let{w:i,h:a}=e;if(t.visible===!1){if(Fe(t)){let{visible:e,...o}=t;Z(new _t(i,a),{...o,guide:!1},n,r)}return}if(!r.showGuides&&Fe(t)){Z(new _t(i,a),{...t,guide:!1},n,r);return}if(t.mirror){let{mirror:o,...s}=t,c=(o===`x`?{x:-1,y:1}:{x:1,y:-1}).x<0?[-1,0,0,1,i/Q(n),0]:[1,0,0,-1,0,a/Q(n)];Z(e,s,n,r),Z(e,{...s,...t.id?{id:`${t.id}.mirrored`}:{}},Qe(n,c),r);return}let o=t.opacity??1,s=t.blend??`normal`,c=e=>r.masks.get(e.replace(/^@/,``)),l=t.clip?c(t.clip):void 0;if(l&&=(e=>{let r=e;return t.clipGrow&&(r=Qt(r,t.clipGrow*Q(n),i,a)),t.clipFeather&&(r=R(r,i,a,t.clipFeather*Q(n))),t.clipInvert?r.map(e=>1-e):r})(l),t.clip&&!l){r.notes.push(`layer ${t.id??t.shape}: clip \"${t.clip}\" names no layer drawn before it, so it drew nothing`);return}if(t.except){let e=c(t.except);e?l=e.map((e,t)=>(1-e)*(l?l[t]:1)):r.notes.push(`layer ${t.id??t.shape}: except \"${t.except}\" names no layer drawn before it`)}if(t.blendIf){let[n,r,o=.1]=t.blendIf,s=new Float32Array(i*a);for(let t=0;t<s.length;t++){let i=e.px[t*4+3],a=i>0?H(e.px[t*4]/i,e.px[t*4+1]/i,e.px[t*4+2]/i):0,c=Math.min(o>0?(a-n)/o+1:+(a>=n),o>0?(r-a)/o+1:+(a<=r));s[t]=Math.max(0,Math.min(1,c))*(l?l[t]:1)}l=s}if(t.feather){let{feather:c,opacity:u,blend:d,clip:f,except:p,blendIf:m,clipFeather:h,clipGrow:g,clipInvert:_,...v}=t,y=new _t(i,a);Z(y,v,n,r);let b=new Float32Array(i*a);for(let e=0;e<b.length;e++)b[e]=y.px[e*4+3];let x=R(b,i,a,c*Q(n)),S=new Float32Array(i*a);for(let t=0;t<b.length;t++){let n=b[t];if(n<=0)continue;let r=n*At(Math.max(0,Math.min(1,(x[t]/n-.5)*2.5)));S[t]=r*(l?l[t]:1),J(e,t,y.px[t*4]/n,y.px[t*4+1]/n,y.px[t*4+2]/n,S[t]*o,s)}t.id&&r.masks.set(t.id,S);return}if(t.shape===`adjust`||t.shape===`filter`){let r=Q(n),c=t.shape===`adjust`?_e(e.px,i,a,t.adjust):we(t.filter,t.params??{},e.px,i,a,r);for(let t=0;t<i*a;t++){let n=o*(l?l[t]:1);if(n<=0)continue;let r=t*4;if(s!==`normal`){let i=c[r+3];i>0&&J(e,t,c[r]/i,c[r+1]/i,c[r+2]/i,i*n,s);continue}for(let t=0;t<4;t++)e.px[r+t]=e.px[r+t]+(c[r+t]-e.px[r+t])*n}return}if(t.blur){let{blur:c,opacity:u,blend:d,clip:f,except:p,blendIf:m,clipFeather:h,clipGrow:g,clipInvert:_,...v}=t,y=new _t(i,a);Z(y,v,n,r);let[b,x,S,C]=[0,1,2,3].map(e=>{let t=new Float32Array(i*a);for(let n=0;n<t.length;n++)t[n]=y.px[n*4+e];return R(t,i,a,c*Q(n))});t.id&&r.masks.set(t.id,l?C.map((e,t)=>e*l[t]):C);for(let t=0;t<C.length;t++){let n=C[t];n<=0||J(e,t,b[t]/n,x[t]/n,S[t]/n,n*o*(l?l[t]:1),s)}return}if(t.shape===`group`){let c=new _t(i,a),u=Qe(n,et(t.transform,[i/2,a/2]));for(let e of t.layers??[])Z(c,e,u,r);let d=new Float32Array(i*a);for(let e=0;e<d.length;e++)d[e]=c.px[e*4+3];t.id&&r.masks.set(t.id,d),X(r,t.id,d,i,a),Y(t.effects,!0,e,d);for(let t=0;t<d.length;t++){let n=d[t]*o*(l?l[t]:1);if(n<=0)continue;let r=c.px[t*4+3]||1;J(e,t,c.px[t*4]/r,c.px[t*4+1]/r,c.px[t*4+2]/r,n,s)}Y(t.effects,!1,e,d);return}if(t.shape===`pixels`){an(e,t,n,r,o,s,l);return}if(t.shape===`paint`){Kt(e,t,n,r,o,s,l);return}if(t.shape===`figure`){qt(e,t,n,r,o,s,l);return}if(t.shape===`image`){rn(e,t,n,r,o,s,l);return}if(t.shape===`text`){$t(e,t,n,r,o,s,l);return}if(t.shape===`block`){en(e,t,n,r);return}if(t.shape===`perspective`){tn(e,t,n,o);return}if(t.shape===`reflect`){nn(e,t,n,r,o,l);return}if(t.shape===`bloom`){Yt(e,t,n,o,l);return}if(t.face&&t.shape===`rect`){let i=mt(t,r);if(!i)return;let{face:a,within:o,at:s,size:c,radius:l,...u}=t,d=u.fill&&typeof u.fill!=`string`&&u.fill.type===`grid`&&!u.fill.quad?{...u.fill,quad:i}:u.fill;Z(e,{...u,...d?{fill:d}:{},shape:`polygon`,points:i},n,r);return}let{runs:u,middle:d}=rt(t),f=Qe(n,et(t.transform,d)),p=u.map(e=>({closed:e.closed,points:e.points.map(e=>q(f,e))})),m=Math.sqrt(Math.abs(f[0]*f[3]-f[1]*f[2])),h=t.fill!==void 0&&t.shape!==`line`,g=t.shape===`line`?new Float32Array(i*a):st(p.map(e=>e.points),i,a),_=t.stroke?.align??`center`,v=t.stroke?lt(p,t.stroke.width*m*(_===`outside`?2:1),i,a,t.stroke.join,t.stroke.cap):null;if(v&&_===`inside`)for(let e=0;e<v.length;e++)v[e]*=g[e];if(v&&_===`outside`)for(let e=0;e<v.length;e++)g[e]>=.999&&(v[e]=0);let y=new Float32Array(i*a),b=0;for(let e=0;e<y.length;e++){let t=Math.max(h?g[e]:0,v?v[e]:0)*(l?l[e]:1);y[e]=t,b+=t}if(X(r,t.id,y,i,a),t.id){let e=_===`outside`?null:v;r.masks.set(t.id,t.shape===`line`?y:g.map((t,n)=>t*(e?1-e[n]:1)*(l?l[n]:1)))}if(b===0&&r.notes.push(`layer ${t.id??t.shape} draws nothing inside the picture${l?`, or nothing inside its clip`:``}`),t.erase){for(let t=0;t<y.length;t++){let n=1-y[t]*o;for(let r=0;r<4;r++)e.px[t*4+r]*=n}return}Y(t.effects,!0,e,y);let x=()=>{let n=gt(t.stroke.color,f,r,i);for(let t=0;t<a;t++)for(let r=0;r<i;r++){let a=t*i+r,c=v[a]*(l?l[a]:1);if(c<=0)continue;let u=n(r+.5,t+.5);J(e,a,u[0],u[1],u[2],c*u[3]*o,s)}};if(v&&_===`outside`&&x(),h){let n=gt(t.fill,f,r,i);for(let t=0;t<a;t++)for(let r=0;r<i;r++){let a=t*i+r,c=g[a]*(l?l[a]:1);if(c<=0)continue;let u=n(r+.5,t+.5);J(e,a,u[0],u[1],u[2],c*u[3]*o,s)}}Y(t.effects,!1,e,y),v&&_!==`outside`&&x()}let Q=e=>Math.sqrt(Math.abs(e[0]*e[3]-e[1]*e[2]))||1,$=(e,t)=>{let n=Math.imul(e,374761393)+Math.imul(t,668265263);return n=Math.imul(n^n>>>13,1274126177),n=Math.imul(n^n>>>16,2246822519),((n^n>>>16)>>>0)/4294967295},At=e=>e*e*(3-2*e),jt=null;function Mt(e,t,n){let r=`${e}x${t}:${n}`;if(jt?.key===r)return jt.values;let i=new Float32Array(e*t);for(let r=0;r<t;r++)for(let t=0;t<e;t++)i[r*e+t]=B((t+.5)/n,(r+.5)/n,3,77);return jt={key:r,values:i},i}function Nt(e,t){let n=e.map(e=>{let n=q(t,[e[0],e[1]]);return[n[0],n[1],e[2]??1]}),r=[{x:n[0][0],y:n[0][1],pressure:n[0][2],along:0}];for(let e=0;e+1<n.length;e++){let[t,i,a,o]=[n[Math.max(0,e-1)],n[e],n[e+1],n[Math.min(n.length-1,e+2)]],s=Math.max(1,Math.ceil(Math.hypot(a[0]-i[0],a[1]-i[1])));for(let e=1;e<=s;e++){let n=e/s,c=n*n,l=c*n,u=e=>.5*(2*i[e]+(a[e]-t[e])*n+(2*t[e]-5*i[e]+4*a[e]-o[e])*c+(3*i[e]-t[e]-3*a[e]+o[e])*l),[d,f]=[u(0),u(1)],p=r[r.length-1];r.push({x:d,y:f,pressure:i[2]+(a[2]-i[2])*n,along:p.along+Math.hypot(d-p.x,f-p.y)})}}return r}function Pt(e,t,n,r,i,a){let{w:o,h:s}=e,c=n[n.length-1].along,[l,u]=[F(t.color??`#000000`),F(t.to??t.color??`#000000`)],[d,f]=t.taper??[0,0],[p,m]=t.fade??[0,0],h=t.roundness??1,g=t.angle===void 0?null:[Math.cos(t.angle*Math.PI/180),Math.sin(t.angle*Math.PI/180)],[_,v,y,b,x,S]=[t.grain??0,(t.grainScale??2)*i,t.dry??0,t.wet??0,t.edge??0,t.flow??0],[C,w,T]=[t.scatter??0,t.dab??1,t.spacing],E=null,D=0,O=t.hardness??.5,k=t.size*i,A=t.smudge??0,ee=(t.wobble??0)*i,te=(t,n)=>{let[r,i]=[Math.max(0,Math.min(o-1,Math.floor(t))),Math.max(0,Math.min(s-1,Math.floor(n)))],a=(i*o+r)*4;return[e.px[a],e.px[a+1],e.px[a+2],e.px[a+3]]},j=null,M=0,N=c*r.from,ne=c*r.to;for(;;){for(;M+1<n.length-1&&n[M+1].along<N;)M++;let[i,x]=[n[M],n[Math.min(n.length-1,M+1)]],re=x.along-i.along,ie=re>0?Math.max(0,Math.min(1,(N-i.along)/re)):0,P=c>0?N/c:0,F=1;c>0&&d>0&&P<d&&(F*=At(P/d)),c>0&&f>0&&P>1-f&&(F*=At((1-P)/f));let I=k*(i.pressure+(x.pressure-i.pressure)*ie)*F,ae=r.radius===null?I/2:Math.min(r.radius,Math.max(I,r.radius*.4)),L=ae*w,[oe,R]=re>0?[-(x.y-i.y)/re,(x.x-i.x)/re]:[0,0],se=ee>0?z(N/(k*3+8),r.seed*.37+.5,r.seed)*2*ee:0,ce=r.offset*I+se;D++;let[le,ue]=C>0?[($(r.seed*3+1,D)-.5)*2,($(r.seed*3+2,D)-.5)*2]:[0,0],[B,V]=[i.x+(x.x-i.x)*ie+oe*ce+le*C*ae,i.y+(x.y-i.y)*ie+R*ce+ue*C*ae],de=1;if(c>0&&p>0&&P<p&&(de*=P/p),c>0&&m>0&&P>1-m&&(de*=(1-P)/m),L>=.12){let n=Math.max(1,L*(1-O)),i=Math.min(1,L*2),d=e=>{let t=Math.max(0,Math.min(1,(L+.5-e)/n));return n>1?At(t):t},[f,p]=g??[oe,R],m=(e,t)=>h>=1?Math.hypot(e,t):Math.hypot(e*f+t*p,(e*p-t*f)/h),x=(e,t)=>{if(_<=0&&y<=0)return 1;let n=1;if(_>0&&(n*=Math.max(0,Math.min(1,(Mt(o,s,v)[Math.floor(t)*o+Math.floor(e)]-(.12+_*.62))/.34+.5))),y>0){let i=(e-B)*oe+(t-V)*R+ce,a=z(i/Math.max(.8,k*.045),N/(k*3+8),r.seed+5),o=z(i/Math.max(1.5,k*.17),N/(k*5+12),r.seed+9),s=.5+.8*a+1.1*o;n*=Math.max(0,Math.min(1,(s-(.12+y*.68))/.22+.5))}return n},[C,w]=[Math.max(0,Math.floor(B-L-1)),Math.min(o-1,Math.ceil(B+L+1))],[T,D]=[Math.max(0,Math.floor(V-L-1)),Math.min(s-1,Math.ceil(V+L+1))];if(A>0){j??=te(B,V);for(let n=T;n<=D;n++)for(let r=C;r<=w;r++){let a=d(m(r+.5-B,n+.5-V))*i*A*(t.opacity??1)*x(r+.5,n+.5);if(a<=0)continue;let s=(n*o+r)*4;for(let t=0;t<4;t++)e.px[s+t]=e.px[s+t]+(j[t]-e.px[s+t])*a*.5}let n=te(B,V);for(let e=0;e<4;e++)j[e]=j[e]+(n[e]-j[e])*(1-A)*.5}else{let e=c>0?N/c:0,n=t=>Math.max(0,Math.min(1,(l[t]+(u[t]-l[t])*e)*r.shade)),[s,f,p]=[n(0),n(1),n(2)];if(b>0){let e=te(B,V),t=e[3]>.02?[e[0]/e[3],e[1]/e[3],e[2]/e[3]]:null,n=t?E?b*.09:b*.45:0,r=E??[s,f,p],i=[s,f,p];E=[0,1,2].map(e=>{let a=r[e]+(i[e]-r[e])*.012;return a+((t?t[e]:a)-a)*n}),[s,f,p]=E}let h=(l[3]+(u[3]-l[3])*e)*(t.opacity??1)*r.strength*de;for(let e=T;e<=D;e++)for(let t=C;t<=w;t++){let n=d(m(t+.5-B,e+.5-V))*i*h*x(t+.5,e+.5),r=e*o+t,c=a.mask[r],l=S>0?c+n*S*(1-c):n;l<=c||(c===0&&a.touched.push(r),a.mask[r]=l,a.rgb[r*3]=s,a.rgb[r*3+1]=f,a.rgb[r*3+2]=p)}}}if(N>=ne||c===0)break;N=Math.min(ne,N+(T===void 0?Math.max(.4,L*.1*h):Math.max(.3,L*2*T)))}let re=t.blend??`normal`;for(let n of a.touched){let r=a.mask[n],i=x>0?Math.min(1,r*(1-x*.45*At(Math.min(1,r/(t.opacity??1)))+x*1.1*Math.max(0,1-Math.abs(r/(t.opacity??1)-.4)*3))):r;if(t.erase)for(let t=0;t<4;t++)e.px[n*4+t]*=1-i;else J(e,n,a.rgb[n*3],a.rgb[n*3+1],a.rgb[n*3+2],i,re);a.mask[n]=0}a.touched.length=0}function Ft(e,t,n,r,i,a){if(!L()){It(e,t,n,r,i,a);return}let o=t.points.map(e=>q(n,[e[0],e[1]])),s=(t.size??24)*r*2+4;for(let[c,l]of it){let[u,d]=[c*e.w,l*e.h];(c!==0||l!==0)&&!at(o,u,d,s,e.w,e.h)||It(e,t,Qe([1,0,0,1,u,d],n),r,i,a)}}function It(e,t,n,r,i,a){let o=t.brush?{...je[t.brush],...t}:t,s=Nt(o.points,n),c=o.seed??i+1,l=o.bristles??1;if(l===1){Pt(e,o,s,{offset:0,radius:null,from:0,to:1,shade:1,strength:1,seed:c},r,a);return}let u=o.spread??1,d=o.vary??.15,f=(o.strand??Math.max(.8,o.size/l*2.2))*r/2;for(let t=0;t<l;t++){let n=e=>$(c*131+t,e);Pt(e,o,s,{offset:((t+n(1))/l-.5)*u,radius:f,from:n(2)*.06,to:1-n(3)*.1,shade:1+(n(4)-.5)*2*d,strength:1-n(5)*d*1.5,seed:c*31+t},r,a)}}let Lt=e=>Math.max(0,Math.min(255,Math.round(e*255))).toString(16).padStart(2,`0`),Rt=(e,t=1)=>`#${Lt(e[0]*t)}${Lt(e[1]*t)}${Lt(e[2]*t)}${Lt(e[3])}`;function zt(e,t){let n=Nt(e,Ye),r=n[n.length-1].along,i=0;return Array.from({length:t},(e,a)=>{let o=r*a/(t-1);for(;i+1<n.length-1&&n[i+1].along<o;)i++;let[s,c]=[n[i],n[i+1]??n[i]],l=c.along>s.along?Math.min(1,(o-s.along)/(c.along-s.along)):0;return{x:s.x+(c.x-s.x)*l,y:s.y+(c.y-s.y)*l,pressure:s.pressure+(c.pressure-s.pressure)*l}})}let Bt=e=>{let t={};for(let n of[`brush`,`roundness`,`angle`,`grain`,`grainScale`,`dry`,`wet`,`edge`,`scatter`,`dab`,`spacing`,`flow`,`fade`])e[n]!==void 0&&(t[n]=e[n]);return t};function Vt(e){let t=e.guides.map(e=>zt(e,14)),n=e.seed??1,r=e.colors.map(F),i=e.tip?F(e.tip):null,a=e.clumps??Math.max(2,Math.round(e.count/14)),[o,s,c,l]=[e.gather??.6,e.flyaway??.02,e.vary??.12,e.wobble??1.5],u=e=>{let t=Math.max(0,Math.min(.9999,e))*(r.length-1),[n,i]=[Math.floor(t),t-Math.floor(t)],[a,o]=[r[n],r[Math.min(r.length-1,n+1)]];return[a[0]+(o[0]-a[0])*i,a[1]+(o[1]-a[1])*i,a[2]+(o[2]-a[2])*i,a[3]+(o[3]-a[3])*i]},d=Array.from({length:a},(e,t)=>(t+.2+$(n*7+t,1)*.6)/a),f=Array.from({length:a},(e,t)=>1+($(n*7+t,2)-.5)*c*2.5),p=[];for(let r=0;r<e.count;r++){let m=e=>$(n*131+r,e),h=(r+m(1))/e.count,g=Math.min(a-1,Math.floor(h*a)),_=m(2)<s,[v,y]=[m(3)<.5?-1:1,.6+m(4)*1.4],b=1-m(5)*(_?.05:.16),x=[];for(let i=0;i<14;i++){let a=i/13*b,s=_?0:o*a*a,c=(h+(d[g]-h)*s)*(t.length-1),[u,f]=[Math.min(t.length-2,Math.floor(c)),c-Math.min(t.length-2,Math.floor(c))],p=e=>{let t=a*13,[n,r]=[Math.min(12,Math.floor(t)),t-Math.min(12,Math.floor(t))];return[e[n].x+(e[n+1].x-e[n].x)*r,e[n].y+(e[n+1].y-e[n].y)*r]},[m,S]=p(t[u]),[C,w]=p(t[u+1]),[T,E]=[m+(C-m)*f,S+(w-S)*f],[D,O]=[C-m,w-S],k=Math.hypot(D,O)||1,A=z(a*3.1,r*.73+.5,n)*l*2*a,ee=_?v*y*a*a*(k*.5+(e.size??1.2)*14):0;x.push([Math.round((T+D/k*(A+ee))*100)/100,Math.round((E+O/k*(A+ee))*100)/100])}let S=f[g]*(1+(m(6)-.5)*c),C=u(h+(m(7)-.5)*.08),w=(e.size??1.2)*(.7+m(8)*.6);p.push({...Bt(e),points:x,size:w,...e.brush&&e.hardness===void 0?{}:{hardness:e.hardness??.7},color:Rt(C,S),...i?{to:Rt([C[0]+(i[0]-C[0])*.8,C[1]+(i[1]-C[1])*.8,C[2]+(i[2]-C[2])*.8,C[3]],S)}:{},opacity:(e.opacity??(e.brush?je[e.brush].opacity??1:1))*(_?.55:.75+m(9)*.25),taper:e.taper??[.04,.45]})}return p}function Ht(e,t,n,r,i,a){let o=e.seed??1,s=e.region?.startsWith(`@`)?e.region.slice(1):null,c=s?i.masks.get(s):void 0;if(s&&!c)return i.notes.push(`${a}: a field's region \"@${s}\" names no layer drawn before it, so it drew nothing`),[];let l=c?kt(t,n,e=>c[e]>=.5):null;if(c&&!l)return[];let u=e.region&&!s?Te(e.region).map(e=>e.points):null,d=(e,i)=>{if(c){let a=q(r,[e,i]),[o,s]=[Math.floor(a[0]),Math.floor(a[1])];return o>=0&&s>=0&&o<t&&s<n&&c[s*t+o]>=.5}if(!u)return!0;let a=0;for(let t of u)for(let n=0;n<t.length;n++){let[r,o]=[t[n],t[(n+1)%t.length]];if(r[1]<=i==o[1]<=i)continue;let s=(o[0]-r[0])*(i-r[1])-(e-r[0])*(o[1]-r[1]);(o[1]>r[1]?s>0:s<0)&&(a+=o[1]>r[1]?1:-1)}return a!==0},f=$e(r),p=l?[[l[0],l[1]],[l[0]+l[2],l[1]],[l[0],l[1]+l[3]],[l[0]+l[2],l[1]+l[3]]].map(e=>q(f,e)):u?u.flat():[[0,0],[t,n]],[m,h]=[Math.min(...p.map(e=>e[0])),Math.max(...p.map(e=>e[0]))],[g,_]=[Math.min(...p.map(e=>e[1])),Math.max(...p.map(e=>e[1]))],v=(e.guides??[]).flatMap(e=>{let t=zt(e,24);return t.slice(0,-1).map((e,n)=>{let r=t[n+1],i=Math.hypot(r.x-e.x,r.y-e.y)||1;return{x:e.x,y:e.y,dx:(r.x-e.x)/i,dy:(r.y-e.y)/i}})}),y=(t,n)=>{if(v.length===0){let t=(e.angle??0)*Math.PI/180;return[Math.cos(t),Math.sin(t)]}let[r,i]=[0,0];for(let e of v){let a=1/(1+((t-e.x)**2+(n-e.y)**2)**1.5);r+=e.dx*a,i+=e.dy*a}let a=Math.hypot(r,i)||1;return[r/a,i/a]},b=e.tone!==void 0&&typeof e.tone!=`string`&&(e.tone.type===`form`||e.tone.type===`image`)?gt(e.tone,Ye,i,t):null,x=b?(e,t)=>{let n=q(r,[e,t]);return b(n[0],n[1])}:e.tone===void 0?null:gt(e.tone,Ye),S=e.length??e.size*3,C=Math.min(Ue,Math.ceil((e.coverage??4)*Math.max(1,(h-m)*(_-g))/(e.size*S))),w=(e.spread??12)*Math.PI/180,T=e.vary??.05,E=[],D=Math.max(1,Math.round(Math.sqrt(C*(h-m||1)/(_-g||1)))),O=Math.max(1,Math.ceil(C/D)),k=Array.from({length:D*O},(e,t)=>t).sort((e,t)=>$(o*53+e,9)-$(o*53+t,9));for(let t of k){let n=e=>$(o*197+t,e),[r,i]=[m+(t%D+n(1))/D*(h-m),g+(Math.floor(t/D)+n(2))/O*(_-g)];if(!d(r,i))continue;let a=(n(3)-.5)*2*w,s=[],[c,l]=[-S/2,S/5],[u,f]=[r,i],[p,v]=y(r,i);u+=p*c,f+=v*c;for(let e=0;e<=5;e++){s.push([Math.round(u*100)/100,Math.round(f*100)/100]);let[e,t]=y(u,f),[n,r]=[e*Math.cos(a)-t*Math.sin(a),e*Math.sin(a)+t*Math.cos(a)];u+=n*l,f+=r*l}E.push({...Bt(e),points:s,size:e.size*(.75+n(4)*.5),...e.brush?{}:{hardness:e.hardness??.25,opacity:e.opacity??.6},...e.brush&&e.hardness!==void 0?{hardness:e.hardness}:{},...e.brush&&e.opacity!==void 0?{opacity:e.opacity}:{},...e.smudge?{smudge:e.smudge}:{color:Rt(x(r,i),1+(n(5)-.5)*2*T)},taper:e.taper??[.12,.3]})}return E}function Ut(e){let t=e.seed??1,n=zt(e.line,Math.max(2,e.count)),[r,i]=typeof e.scale==`number`?[e.scale,e.scale]:e.scale??[1,1],a=e.jitter??0,o=[];for(let s=0;s<e.count;s++){let c=e.count===1?0:s/(e.count-1),l=n[s],[u,d]=s+1<n.length?[l,n[s+1]]:[n[s-1],l],f=e=>($(t*89+s,e)-.5)*2*a,p=r+(i-r)*c,m=Math.atan2(d.y-u.y,d.x-u.x);for(let t of e.both?[1,-1]:[1]){let n=m+((e.turn??0)*t+f(1)*.1)*Math.PI/180,[r,i]=[Math.cos(n),Math.sin(n)],[a,s]=[l.x+f(2),l.y+f(3)];for(let n of e.strokes)o.push({...n,size:n.size*p,points:n.points.map(e=>{let[n,o]=[e[0]*p,e[1]*p*t];return[a+n*r-o*i,s+n*i+o*r,...e[2]===void 0?[]:[e[2]]]})})}}return o}function Wt(e,t,n){let r=e.size??1.2,i=e.guides.map(e=>zt(e,3)[1]),a=0;for(let e=0;e+1<i.length;e++)a+=Math.hypot(i[e+1].x-i[e].x,i[e+1].y-i[e].y);(a<r*4||e.count*r>a*8*Math.max(1,e.guides.length))&&t.notes.push(`${n}: a sweep lays ${e.count} hairs of size ${r} across ${Math.round(a)} pixels, which fills it as a flat band; use fewer, thinner hairs or set the guides further apart`)}let Gt=(e,t,n,r,i,a)=>`type`in e?e.type===`sweep`?(Wt(e,i,a),Vt(e)):e.type===`along`?Ut(e):Ht(e,t,n,r,i,a):[e];function Kt(e,t,n,r,i,a,o){let{w:s,h:c}=e,l=Qe(n,et(t.transform,[s/2,c/2])),u=new _t(s,c);if(t.from===`below`&&u.px.set(e.px),t.fill!==void 0){let e=gt(t.fill,l,r,s);for(let t=0;t<c;t++)for(let n=0;n<s;n++){let r=e(n+.5,t+.5);J(u,t*s+n,r[0],r[1],r[2],r[3],`normal`)}}let d={mask:new Float32Array(s*c),rgb:new Float32Array(s*c*3),touched:[]},f=0,p=t.face?mt(t,r):null;if(t.face&&!p)return;let m=p?pt(p):null,h=e=>e.map(e=>[...m(e[0],e[1]),...e.slice(2)]);(t.strokes??[]).map(e=>m?`type`in e?e.type===`sweep`?{...e,guides:e.guides.map(h)}:e.type===`along`?{...e,line:h(e.line)}:e:{...e,points:h(e.points)}:e).forEach(e=>{for(let n of Gt(e,s,c,l,r,`layer ${t.id??`paint`}`))Ft(u,n,l,Q(l),f++,d)}),t.id&&r.painted.set(t.id,{entries:(t.strokes??[]).length,strokes:f});let g=new Float32Array(s*c);for(let e=0;e<g.length;e++)g[e]=u.px[e*4+3];let _=o?g.map((e,t)=>e*o[t]):g;if(t.id&&r.masks.set(t.id,_),X(r,t.id,_,s,c),t.from===`below`){for(let t=0;t<g.length*4;t++){let n=i*(o?o[Math.floor(t/4)]:1);e.px[t]=e.px[t]+(u.px[t]-e.px[t])*n}return}Y(t.effects,!0,e,g);for(let t=0;t<g.length;t++){let n=g[t];n<=0||J(e,t,u.px[t*4]/n,u.px[t*4+1]/n,u.px[t*4+2]/n,n*i*(o?o[t]:1),a)}Y(t.effects,!1,e,g)}function qt(e,t,n,r,i,a,o){let{w:s,h:c}=e,l=P(t,s,c,e=>q(n,e),Q(n)),u=Math.max(2,t.height*.03),d=R(l.mask,s,c,u),f=new Float32Array(l.normals);for(let e=0;e<3;e++){let t=new Float32Array(s*c);for(let n=0;n<t.length;n++)t[n]=l.normals[n*3+e]*l.mask[n];let n=R(t,s,c,u);for(let r=0;r<t.length;r++)l.mask[r]<.5&&d[r]>.01&&(f[r*3+e]=n[r]/d[r])}if(t.id){r.figures.set(t.id,{...l,normals:f});let e=e=>o?e.map((e,t)=>e*o[t]):e;r.masks.set(t.id,e(l.mask)),X(r,t.id,e(l.mask),s,c);for(let[n,i]of Object.entries(l.parts))r.masks.set(`${t.id}.${n}`,e(i)),X(r,`${t.id}.${n}`,e(i),s,c)}let[p,m,h]=l.light;for(let t=0;t<l.mask.length;t++){let n=l.mask[t];if(n<=0)continue;let r=.25+.7*Math.max(0,.5+.5*(l.normals[t*3]*p+l.normals[t*3+1]*m+l.normals[t*3+2]*h)),s=1-l.contour[t]*.85;J(e,t,r*s*.92,r*s*.94,r*s,n*i*(o?o[t]:1),a)}let g=lt(l.lines.map(e=>({closed:!1,points:e})),1.5,s,c);for(let t=0;t<g.length;t++)J(e,t,.95,.35,.3,g[t]*.8*i,`normal`);for(let[t,n]of Object.values(l.joints))for(let r=-2;r<=2;r++)for(let a=-2;a<=2;a++)t+a<0||n+r<0||t+a>=s||n+r>=c||a*a+r*r>5||J(e,(n+r)*s+t+a,.95,.2,.25,.85*i,`normal`);t.id&&r.figureJoints.set(t.id,l.joints)}function Jt(e,t,n,r,i){let a=[...e.text].length,o=96/(e.fontSize??96),s=Math.ceil(96*1.4*(a+1)+Math.abs(e.tracking??0)*o*a),[c,l]=e.vertical?[192,s]:[s,192],u=i({...e,fontSize:96,align:`left`,at:e.vertical?[192/2,96*.2]:[96*.2,96*1.3],...e.tracking?{tracking:e.tracking*o}:{},...e.stroke?{stroke:{...e.stroke,width:e.stroke.width*o}}:{}},Ye,c,l),d=kt(c,l,e=>u.fill[e]>=.5||(u.line?u.line[e]>=.5:!1)),f={fill:new Float32Array(n*r),line:u.line?new Float32Array(n*r):null},p=e.quad.map(e=>q(t,e)),m=ft(p);if(!d||!m)return f;let[h,g]=[Math.max(0,Math.floor(Math.min(...p.map(e=>e[0])))),Math.min(n-1,Math.ceil(Math.max(...p.map(e=>e[0]))))],[_,v]=[Math.max(0,Math.floor(Math.min(...p.map(e=>e[1])))),Math.min(r-1,Math.ceil(Math.max(...p.map(e=>e[1]))))];for(let e=_;e<=v;e++)for(let t=h;t<=g;t++){let[r,i]=[0,0];for(let n=0;n<3;n++)for(let a=0;a<3;a++){let[o,s]=m(t+(a+.5)/3,e+(n+.5)/3);if(o<0||s<0||o>=1||s>=1)continue;let l=Math.floor(d[1]+s*d[3])*c+Math.floor(d[0]+o*d[2]);r+=u.fill[l],u.line&&(i+=u.line[l])}f.fill[e*n+t]=r/9,f.line&&(f.line[e*n+t]=i/9)}return f}function Yt(e,t,n,r,i){let{w:a,h:o}=e,s=t.threshold??.6,c=(t.strength??1)*r,l=(t.radius??10)*Q(n),u=[new Float32Array(a*o),new Float32Array(a*o),new Float32Array(a*o)],d=Math.max(.001,1-s);for(let t=0;t<a*o;t++){let[n,r,i]=[e.px[t*4],e.px[t*4+1],e.px[t*4+2]],a=Math.max(n,r,i);if(a<=s)continue;let o=At(Math.min(1,(a-s)/d));u[0][t]=n*o,u[1][t]=r*o,u[2][t]=i*o}for(let t=0;t<3;t++){let[n,r]=[R(u[t],a,o,l*.5),R(u[t],a,o,l*2.5)];for(let s=0;s<a*o;s++){let a=Math.min(1,(n[s]*.7+r[s]*.9)*c)*(i?i[s]:1);if(a<=0)continue;let o=s*4;e.px[o+t]=e.px[o+t]+(1-e.px[o+t])*a,a>e.px[o+3]&&(e.px[o+3]=a)}}}function Xt(e,t,n,r){let i=Math.round(t);if(i<=0)return e;let a=new Float32Array(n*r);for(let t=0;t<r;t++)for(let r=0;r<n;r++){let o=1;for(let a=-i;a<=i;a++){let i=r+a,s=i<0||i>=n?0:e[t*n+i];s<o&&(o=s)}a[t*n+r]=o}let o=new Float32Array(n*r);for(let e=0;e<n;e++)for(let t=0;t<r;t++){let s=1;for(let o=-i;o<=i;o++){let i=t+o,c=i<0||i>=r?0:a[i*n+e];c<s&&(s=c)}o[t*n+e]=s}return o}function Zt(e,t,n){let[r,i]=[t.grain??0,t.dry??0];if(r<=0&&i<=0)return e;let a=t.grainScale??2;return e.map((e,t)=>{if(e<=0)return 0;let[o,s]=[t%n+.5,Math.floor(t/n)+.5],c=e;return r>0&&(c*=Math.max(0,Math.min(1,(B(o/a,s/a,3,77)-(.12+r*.62))/.34+.5))),i>0&&(c*=Math.max(0,Math.min(1,(.5+1.3*z(o/40,s/1.8,9)-(.12+i*.68))/.22+.5))),c})}function Qt(e,t,n,r){let i=Math.round(Math.abs(t));if(i===0)return e;let a=t>0?Math.max:Math.min,o=new Float32Array(n*r);for(let s=0;s<r;s++)for(let r=0;r<n;r++){let c=e[s*n+r];for(let o=-i;o<=i;o++){let i=r+o;c=a(c,i<0||i>=n?t>0?0:c:e[s*n+i])}o[s*n+r]=c}let s=new Float32Array(n*r);for(let e=0;e<n;e++)for(let c=0;c<r;c++){let l=o[c*n+e];for(let s=-i;s<=i;s++){let i=c+s;l=a(l,i<0||i>=r?t>0?0:l:o[i*n+e])}s[c*n+e]=l}return s}function $t(e,t,n,r,i,a,o){let{w:s,h:c}=e;if(!r.text)throw Error(`layer ${t.id??`text`}: text needs the editor's fonts, and this render has none`);let l=Qe(n,et(t.transform,t.at??[0,0])),u=t.face?mt(t,r):t.quad;if(t.face&&!u)return;let d=u?Jt({...t,quad:u},l,s,c,r.text):r.text(t,l,s,c),f=d.line,p=Zt(Xt(d.fill,(t.thin??0)*Q(l),s,c),t,s),m=new Float32Array(s*c);for(let e=0;e<m.length;e++)m[e]=Math.max(t.fill===void 0?0:p[e],f?f[e]:0)*(o?o[e]:1);t.id&&r.masks.set(t.id,m),X(r,t.id,m,s,c),Y(t.effects,!0,e,m);let h=(t,n)=>{for(let r=0;r<c;r++)for(let c=0;c<s;c++){let l=r*s+c,u=t[l]*(o?o[l]:1);if(u<=0)continue;let d=n(c+.5,r+.5);J(e,l,d[0],d[1],d[2],u*d[3]*i,a)}};f&&t.stroke&&h(f,gt(t.stroke.color,l,r,s)),t.fill!==void 0&&h(p,gt(t.fill,l,r,s)),Y(t.effects,!1,e,m)}function en(e,t,n,r){let[i,a]=t.at,o=a-t.height,s=(e,t,n,r)=>[e+(n[0]-e)*r,t+(n[1]-t)*r],c={},l=[`a`,`b`],u={...t.opacity===void 0?{}:{opacity:t.opacity},...t.blend?{blend:t.blend}:{},...t.clip?{clip:t.clip}:{},...t.except?{except:t.except}:{},...t.stroke?{stroke:t.stroke}:{}},d=(t.vanish??[]).map((e,n)=>{let r=t.depth[n],[d,f]=s(i,o,e,r),[p,m]=s(i,a,e,r),h=e[0]<i?[[d,f],[i,o],[i,a],[p,m]]:[[i,o],[d,f],[p,m],[i,a]];c[l[n]]=h;let g=t.faces[n],_=typeof g!=`string`&&g.type===`grid`&&!g.quad?{...g,quad:h}:g;return{...u,...t.id?{id:`${t.id}.${l[n]}`}:{},shape:`polygon`,points:h,fill:_}}),f=t.vanish??[];if(t.roof!==void 0&&f[0][1]<o){let e=[i,o],[n,r]=[s(i,o,f[0],t.depth[0]),f[1]?s(i,o,f[1],t.depth[1]):null],a=r&&f[1]?[e,n,(()=>{let[e,t,i,a]=[n,f[1],r,f[0]],o=(e[0]-t[0])*(i[1]-a[1])-(e[1]-t[1])*(i[0]-a[0]);if(Math.abs(o)<1e-6)return e;let s=((e[0]-i[0])*(i[1]-a[1])-(e[1]-i[1])*(i[0]-a[0]))/o;return[e[0]+s*(t[0]-e[0]),e[1]+s*(t[1]-e[1])]})(),r]:null;a&&(c.top=a,d.unshift({...u,...t.id?{id:`${t.id}.top`}:{},shape:`polygon`,points:a,fill:t.roof}))}for(let t of d)Z(e,t,n,r);if(t.id){r.blocks.set(t.id,Object.fromEntries(Object.entries(c).map(([e,t])=>[e,t.map(e=>{let t=q(n,e);return[Math.round(t[0]),Math.round(t[1])]})])));let i=new Float32Array(e.w*e.h);for(let e of Object.keys(c)){let n=r.masks.get(`${t.id}.${e}`);if(n)for(let e=0;e<i.length;e++)i[e]=Math.max(i[e],n[e])}r.masks.set(t.id,i),X(r,t.id,i,e.w,e.h)}}function tn(e,t,n,r){let{w:i,h:a}=e,o=Math.hypot(i,a),s=(t.vanish??[]).flatMap(e=>Array.from({length:24},(t,r)=>{let i=r/24*Math.PI*2,a=q(n,[e[0],e[1]]);return{closed:!1,points:[a,[a[0]+Math.cos(i)*o,a[1]+Math.sin(i)*o]]}})),c=(t.vanish??[])[0];c&&s.push({closed:!1,points:[q(n,[-i,c[1]]),q(n,[i*2,c[1]])]});let l=lt(s,1,i,a);for(let t=0;t<l.length;t++)J(e,t,.3,.9,1,l[t]*.55*r,`normal`)}function nn(e,t,n,r,i,a){let{w:o,h:s}=e,c=Q(n),l=new Float32Array(o),u=t.edge?.map(e=>q(n,e)).sort((e,t)=>e[0]-t[0]);for(let e=0;e<o;e++){if(!u){l[e]=q(n,[0,t.y])[1];continue}let r=0;for(;r+2<u.length&&u[r+1][0]<e+.5;)r++;let[i,a]=[u[r],u[r+1]],o=a[0]===i[0]?0:Math.max(0,Math.min(1,(e+.5-i[0])/(a[0]-i[0])));l[e]=i[1]+(a[1]-i[1])*o}let d=(t.reach??s)*c,f=(t.ripple??3)*c,p=new Float32Array(o*s*4);for(let t=0;t<s;t++)for(let n=0;n<o;n++){let r=t+.5-l[n];if(r<0||r>=d)continue;let i=Math.floor(l[n]-r);if(i<0)continue;let a=f*(r/d+.2),s=z(n/90,t/3.5,11)*a*2.4+z(n/22,t/1.6,12)*a,c=Math.max(0,Math.min(o-1,Math.round(n+s))),[u,m]=[(t*o+n)*4,(i*o+c)*4];for(let t=0;t<4;t++)p[u+t]=e.px[m+t]}let m=(t.smear??2)*c,h=[0,1,2,3].map(e=>{let t=new Float32Array(o*s);for(let n=0;n<t.length;n++)t[n]=p[n*4+e];return m>0?R(t,o,s,m):t}),g=new Float32Array(o*s);for(let n=0;n<s;n++)for(let r=0;r<o;r++){let s=n+.5-l[r];if(s<0)continue;let c=Math.max(0,1-s/d),u=n*o+r,f=h[3][u];g[u]=f*c*(a?a[u]:1),!(f<=0||g[u]<=0)&&J(e,u,h[0][u]/f,h[1][u]/f,h[2][u]/f,g[u]*i,t.blend??`normal`)}t.id&&r.masks.set(t.id,g),X(r,t.id,g,o,s)}function rn(e,t,n,r,i,a,o){let{w:s,h:c}=e,l=r.pictures[t.src];if(!l)throw Error(`there is no picture at ${t.src}`);let[u,d]=q(n,t.at??[0,0]),f=Q(n),[p,m]=(t.size??[l.width,l.height]).map(e=>e*f),h=new Float32Array(s*c*4),g=new Float32Array(s*c);for(let e=Math.max(0,Math.floor(d));e<Math.min(c,Math.ceil(d+m));e++)for(let t=Math.max(0,Math.floor(u));t<Math.min(s,Math.ceil(u+p));t++){let[n,r]=[(t+.5-u)/p*l.width-.5,(e+.5-d)/m*l.height-.5];if(n<-.5||r<-.5||n>l.width-.5||r>l.height-.5)continue;let[i,a]=[Math.max(0,Math.floor(n)),Math.max(0,Math.floor(r))],[o,c]=[Math.min(l.width-1,i+1),Math.min(l.height-1,a+1)],[f,_]=[Math.max(0,n-i),Math.max(0,r-a)],v=e*s+t;for(let e=0;e<4;e++){let t=(t,n)=>l.rgba[(n*l.width+t)*4+e]/255;h[v*4+e]=(t(i,a)*(1-f)+t(o,a)*f)*(1-_)+(t(i,c)*(1-f)+t(o,c)*f)*_}g[v]=h[v*4+3]}if(t.id){r.images.set(t.id,h);let e=o?g.map((e,t)=>e*o[t]):g;r.masks.set(t.id,e),X(r,t.id,e,s,c)}for(let t=0;t<g.length;t++)g[t]>0&&J(e,t,h[t*4],h[t*4+1],h[t*4+2],g[t]*i*(o?o[t]:1),a)}function an(e,t,n,r,i,a,o){let{w:s,h:c}=e,l=t.rows,u=Math.max(...l.map(e=>e.length)),d=(t.scale??Math.max(1,Math.floor(Math.min(s/u,c/l.length))))*Q(n),[f,p]=t.at?q(n,t.at):[(s-u*d)/2,(c-l.length*d)/2],m=new Map(Object.entries(t.palette??{}).map(([e,t])=>[e,F(t)])),h=new Float32Array(s*c),g=new Float32Array(s*c*3);l.forEach((e,t)=>{[...e].forEach((e,n)=>{let r=m.get(e);if(r)for(let e=Math.max(0,Math.round(p+t*d));e<Math.min(c,Math.round(p+(t+1)*d));e++)for(let t=Math.max(0,Math.round(f+n*d));t<Math.min(s,Math.round(f+(n+1)*d));t++)h[e*s+t]=r[3]*(o?o[e*s+t]:1),g[(e*s+t)*3]=r[0],g[(e*s+t)*3+1]=r[1],g[(e*s+t)*3+2]=r[2]})}),t.id&&r.masks.set(t.id,h),X(r,t.id,h,s,c),Y(t.effects,!0,e,h);for(let t=0;t<h.length;t++)J(e,t,g[t*3],g[t*3+1],g[t*3+2],h[t]*i,a);Y(t.effects,!1,e,h)}let on=new Map,sn={drawn:0,reused:0};function cn(e){let[t,n]=[3735928559,1103547991];for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return((t^t>>>16)>>>0).toString(36)+((n^n>>>13)>>>0).toString(36)+e.length.toString(36)}function ln(e){return e?Object.entries(e).map(([e,t])=>{let n=0;for(let e=0;e<t.rgba.length;e+=97)n=Math.imul(n,31)+t.rgba[e]|0;return`${e}:${t.width}x${t.height}:${n}`}).join(`|`):``}function un(e,t,n){on.set(e,{px:t.px.slice(),drawn:{masks:new Map(n.masks),notes:[...n.notes],bounds:new Map(n.bounds),painted:new Map(n.painted),figures:new Map(n.figures),figureJoints:new Map(n.figureJoints),images:new Map(n.images),blocks:new Map(n.blocks)}});let r=0;for(let e of on.values())r+=e.px.byteLength;for(let[e,t]of on){if(r<=536870912)break;on.delete(e),r-=t.px.byteLength}}function dn(e,t,n){t.px.set(e.px),n.masks=new Map(e.drawn.masks),n.notes=[...e.drawn.notes],n.bounds=new Map(e.drawn.bounds),n.painted=new Map(e.drawn.painted),n.figures=new Map(e.drawn.figures),n.figureJoints=new Map(e.drawn.figureJoints),n.images=new Map(e.drawn.images),n.blocks=new Map(e.drawn.blocks)}function fn(e,t={}){let[n,r]=typeof e.size==`number`?[e.size,e.size]:e.size,i=new _t(n,r),a={masks:new Map,notes:[],bounds:new Map,painted:new Map,figures:new Map,figureJoints:new Map,showGuides:t.guides===!0,pictures:t.pictures??{},images:new Map,text:t.text,blocks:new Map},o=cn(JSON.stringify([n,r,e.background??null,t.guides===!0,ln(t.pictures),e.tile===!0])),s=e.layers.map(e=>o=cn(o+JSON.stringify(e))),c=0;for(let e=s.length-1;e>=0;e--){let t=on.get(s[e]);if(t){dn(t,i,a),on.delete(s[e]),on.set(s[e],t),c=e+1,sn.reused+=c;break}}if(c===0&&e.background){let[t,a,o,s]=F(e.background);for(let e=0;e<n*r;e++)J(i,e,t,a,o,s,`normal`)}let l=Date.now();ae(e.tile===!0),[Xe,Ze]=[n,r];try{for(let t=c;t<e.layers.length;t++)Z(i,e.layers[t],Ye,a),sn.drawn++,(t===e.layers.length-1||Date.now()-l>=150)&&(un(s[t],i,a),l=Date.now())}finally{ae(!1)}let u=new Uint8Array(n*r*4);for(let e=0;e<n*r;e++){let t=i.px[e*4+3],n=t>1e-5?1/t:0;u[e*4]=Math.round(Math.min(1,i.px[e*4]*n)*255),u[e*4+1]=Math.round(Math.min(1,i.px[e*4+1]*n)*255),u[e*4+2]=Math.round(Math.min(1,i.px[e*4+2]*n)*255),u[e*4+3]=Math.round(Math.min(1,t)*255)}let d=0;for(let e=0;e<n*r;e++)u[e*4+3]>=128&&d++;return{width:n,height:r,rgba:u,notes:a.notes,bounds:kt(n,r,e=>u[e*4+3]>=128),covers:Math.round(d/(n*r)*1e3)/1e3,layerBounds:Object.fromEntries(a.bounds),painted:Object.fromEntries(a.painted),figures:Object.fromEntries(a.figureJoints),blocks:Object.fromEntries(a.blocks)}}let pn=(e,t)=>(e[t*4]*.2126+e[t*4+1]*.7152+e[t*4+2]*.0722)/255;function mn(e,t,n){let r=fn({size:e.size,background:`#000000`,...e.tile?{tile:!0}:{},layers:t},n),i=new Float32Array(r.width*r.height);for(let e=0;e<i.length;e++)i[e]=pn(r.rgba,e);return{values:i,picture:r}}function hn(e,t,n,r,i){let a=(r,a)=>{let[o,s]=i?[(r%t+t)%t,(a%n+n)%n]:[Math.max(0,Math.min(t-1,r)),Math.max(0,Math.min(n-1,a))];return e[s*t+o]},o=new Uint8Array(t*n*4);for(let e=0;e<n;e++)for(let n=0;n<t;n++){let i=(a(n+1,e-1)+2*a(n+1,e)+a(n+1,e+1)-(a(n-1,e-1)+2*a(n-1,e)+a(n-1,e+1)))/8,s=(a(n-1,e-1)+2*a(n,e-1)+a(n+1,e-1)-(a(n-1,e+1)+2*a(n,e+1)+a(n+1,e+1)))/8,[c,l]=[-i*r,-s*r],u=Math.hypot(c,l,1),d=(e*t+n)*4;o[d]=Math.round((c/u*.5+.5)*255),o[d+1]=Math.round((l/u*.5+.5)*255),o[d+2]=Math.round((1/u*.5+.5)*255),o[d+3]=255}return{width:t,height:n,rgba:o}}function gn(e,t,n={}){let r=e.material??{},[i,a]=[t.width,t.height],o=[],s,c;if(r.height){let t=mn(e,r.height,n);[s,c]=[t.values,t.picture],o.push(...t.picture.notes.map(e=>`height: ${e}`))}else{s=new Float32Array(i*a);let e=new Uint8Array(i*a*4);for(let n=0;n<i*a;n++){s[n]=pn(t.rgba,n);let r=Math.round(s[n]*255);e.set([r,r,r,255],n*4)}c={width:i,height:a,rgba:e}}let[l,u]=[1,0];for(let e of s)e<l&&(l=e),e>u&&(u=e);u-l<1/255&&o.push(`the relief is flat: its height is one value everywhere, so the normal map says nothing`);let d=(e,t)=>typeof e==`number`?e:t,f=(t,r)=>{if(!Array.isArray(t))return null;let i=mn(e,t,n);return o.push(...i.picture.notes.map(e=>`${r}: ${e}`)),i.values},[p,m]=[f(r.roughness,`roughness`),f(r.metal,`metal`)],h=null;if(p||m){let e=new Uint8Array(i*a*4),[t,n]=[Math.round(d(r.roughness,.8)*255),Math.round(d(r.metal,0)*255)];for(let r=0;r<i*a;r++)e[r*4]=255,e[r*4+1]=p?Math.round(p[r]*255):t,e[r*4+2]=m?Math.round(m[r]*255):n,e[r*4+3]=255;h={width:i,height:a,rgba:e}}return{normal:hn(s,i,a,r.relief??4,e.tile===!0),surface:h,roughness:d(r.roughness,.8),metal:d(r.metal,0),height:c,notes:o}}function _n(e,t){return(n,r,i,a)=>{let o=e(i,a).getContext(`2d`,{willReadFrequently:!0});if(!o)throw Error(`could not draw text here`);let s=n.fontSize,c=n.font?`\"${t(n.font)??n.font}\", sans-serif`:`sans-serif`;o.font=`${n.weight??`normal`} ${s}px ${c}`,o.textBaseline=`alphabetic`,o.setTransform(r[0],r[1],r[2],r[3],r[4],r[5]);let[l,u]=n.at,d=[...n.text],f=n.tracking??0,p=e=>{if(n.vertical){o.textAlign=`center`,d.forEach((t,n)=>e(t,l,u+s*(n+.86)+(s*.08+f)*n));return}o.textAlign=`left`;let t=d.map(e=>o.measureText(e).width+f),r=t.reduce((e,t)=>e+t,0)-f,i=l-(n.align===`center`?r/2:n.align===`right`?r:0);d.forEach((n,r)=>{e(n,i,u),i+=t[r]})},m=()=>{let e=o.getImageData(0,0,i,a).data,t=new Float32Array(i*a);for(let n=0;n<t.length;n++)t[n]=e[n*4+3]/255;return t};p((e,t,n)=>o.fillText(e,t,n));let h=m(),g=null;return n.stroke&&(o.setTransform(1,0,0,1,0,0),o.clearRect(0,0,i,a),o.setTransform(r[0],r[1],r[2],r[3],r[4],r[5]),o.lineWidth=n.stroke.width,o.lineJoin=`round`,p((e,t,n)=>o.strokeText(e,t,n)),g=m()),{fill:h,line:g}}}let vn=[`normal`,`surface`],yn=/\\.(ttf|otf|woff2?)$/i,bn=e=>yn.test(e);function xn(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||!(`mapOf`in t))return{picture:qe(t)};let{mapOf:n,map:r}=t;if(typeof n!=`string`||!n.toLowerCase().endsWith(`.esimage`))throw Error(`mapOf must be the project path of an .esimage`);if(!vn.includes(r))throw Error(`map must be one of ${vn.join(`, `)}`);let i=Object.keys(t).filter(e=>e!==`mapOf`&&e!==`map`&&e!==`version`);if(i.length>0)throw Error(`a map of a picture says only mapOf and map, and this one also says ${i.join(`, `)}`);return{map:{mapOf:n,map:r}}}function*Sn(e){function*t(e){for(let n of e)yield n,yield*t(n.layers??[])}yield*t(e.layers);for(let n of[e.material?.height,e.material?.roughness,e.material?.metal])Array.isArray(n)&&(yield*t(n))}function Cn(e){let t=new Set,n=new Set,r=!1;for(let i of Sn(e))i.shape===`image`&&i.src&&t.add(i.src),i.shape===`text`&&(r=!0,i.font&&bn(i.font)&&n.add(i.font));return{pictures:[...t],fonts:[...n],text:r}}typeof TextEncoder<`u`&&new TextEncoder;let wn=typeof TextDecoder<`u`?new TextDecoder:null;function Tn(e){if(wn)return wn.decode(e);let t=[],n=[];for(let r=0;r<e.length;){let i=e[r],a,o;if(i<128?(a=i,o=1):(i&224)==192?(a=i&31,o=2):(i&240)==224?(a=i&15,o=3):(i&248)==240?(a=i&7,o=4):(a=65533,o=1),o>1)if(r+o>e.length)a=65533,o=1;else for(let t=1;t<o;t++){let n=e[r+t];if((n&192)!=128){a=65533,o=1;break}a=a<<6|n&63}if(r+=o,a>65535){let e=a-65536;n.push(55296|e>>10,56320|e&1023)}else n.push(a);n.length>=4096&&(t.push(String.fromCharCode(...n)),n=[])}return n.length&&t.push(String.fromCharCode(...n)),t.join(``)}let En=`this thread has no canvas to draw text on`,Dn=new Map,On=e=>Tn(new Uint8Array(e)),kn=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e:e.slice();function An(e,t){let n=e.files[t];if(!n)throw Error(`there is no file at ${t}`);return n}async function jn(e,t,n,r){let i=Cn(e),a={};for(let e of i.pictures){let i=t.pictures[e];if(i){a[e]={width:i.width,height:i.height,rgba:i.pixels};continue}if(r>=8)throw Error(`recipes laid in recipes go 8 deep at most`);let o=xn(On(An(t,e)));if(!(`picture`in o))throw Error(`${e} is a map of a picture, and a layer lays in a picture`);a[e]=(await jn(o.picture,t,n,r+1)).picture}let o;if(i.text){if(!n.canvas)throw Error(En);for(let e of i.fonts){if(Dn.has(e))continue;let r=`esimage-font-${Dn.size}`;await n.font(r,An(t,e)),Dn.set(e,r)}o=_n(n.canvas,e=>Dn.get(e))}let s={pictures:a,...o?{text:o}:{}};return{picture:fn(e,s),options:s}}async function Mn(e,t){let n=xn(e.source);if(`picture`in n){let{picture:r}=await jn(n.picture,e,t,0);return{width:r.width,height:r.height,pixels:kn(r.rgba)}}let{mapOf:r,map:i}=n.map,a=xn(On(An(e,r)));if(!(`picture`in a))throw Error(`${r} is itself a map of a picture`);let{picture:o,options:s}=await jn(a.picture,e,t,1),c=gn(a.picture,o,s);return i===`normal`?{width:c.normal.width,height:c.normal.height,pixels:kn(c.normal.rgba)}:c.surface?{width:c.surface.width,height:c.surface.height,pixels:kn(c.surface.rgba)}:{width:1,height:1,pixels:new Uint8Array([255,Math.round(c.roughness*255),Math.round(c.metal*255),255])}}if(typeof self<`u`&&self.document===void 0){let e=self,t={canvas:typeof OffscreenCanvas<`u`?(e,t)=>new OffscreenCanvas(e,t):null,async font(t,n){if(typeof FontFace>`u`||!e.fonts)throw Error(En);let r=new FontFace(t,n);await r.load(),e.fonts.add(r)}};e.onmessage=n=>{let r=n.data;Mn(r,t).then(t=>e.postMessage({id:r.id,result:t},[t.pixels.buffer]),t=>e.postMessage({id:r.id,error:t instanceof Error?t.message:String(t)}))}}return e.NO_TEXT_CANVAS=En,e.drawRecipe=Mn,e})({});";diff --git a/sdk/src/terrain/layerArrays.ts b/sdk/src/terrain/layerArrays.tsindex fd29427ba..d8eee2a95 100644--- a/sdk/src/terrain/layerArrays.ts+++ b/sdk/src/terrain/layerArrays.ts@@ -9,6 +9,7 @@ import { Assets } from '../asset/AssetPlugin';import { platformLoadImagePixels } from '../platform/base';import { decodeImagePixels } from '../asset/imageDecode';import { decodePngData } from '../asset/pngData';+import { isTextureRecipePath, renderTextureRecipe } from '../asset/textureRecipe';import { isMiniGame } from '../platform';import { createTextureArrayFromPixels } from '../runtime/runtimeAssets';import { getResourceManager, provideTextureContent, withdrawTextureContent } from '../wasm/resourceManager';@@ -21,6 +22,8 @@ export async function imagePixelsAt(app: App, path: string): Promise<{ width: nuif (!app.hasResource(Assets)) return null;const assets = app.getResource(Assets);try {+ // A recipe is drawn, and is then pixels as a decoded image's are.+ if (isTextureRecipePath(path)) return await renderTextureRecipe(path, (p) => assets.fetchBinary(p));// The bytes the asset layer would load, decoded unmodified (no premultiply, no colour conversion): a height is data.if (typeof createImageBitmap === 'function' && typeof Blob !== 'undefined') {const bytes = new Uint8Array(await assets.fetchBinary(path));diff --git a/sdk/tests/texture-recipe.test.ts b/sdk/tests/texture-recipe.test.tsindex 5dfa6ea91..8054b8c57 100644--- a/sdk/tests/texture-recipe.test.ts+++ b/sdk/tests/texture-recipe.test.ts@@ -2,15 +2,33 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file texture-recipe.test.ts- * @brief A texture that is a recipe: which paths are one, what draws them, and that what is drawn is the picture its source says.+ * @brief A texture that is a recipe: which paths are one, what draws them, what a recipe may need, and that what is drawn is kept.*/import { afterEach, describe, expect, it } from 'vitest';-import { hasTextureRecipeRenderer, isTextureRecipePath, renderTextureRecipe, setTextureRecipeRenderer, textureRecipeCacheKey, textureRecipeStats } from '../src/asset/textureRecipe';+import {+ hasTextureRecipeDrawer, isTextureRecipePath, renderTextureRecipe, setTextureRecipeDrawer, textureRecipeCacheKey, textureRecipeStats,+ type RecipeFileReader,+} from '../src/asset/textureRecipe';+import { Assets } from '../src/asset/AssetPlugin';+import type { App } from '../src/app/app';import { setPlatform } from '../src/platform/base';import type { PlatformAdapter } from '../src/platform/types';import { getAddressableType } from '../src/assetTypes';+import { imagePixelsAt } from '../src/terrain/layerArrays';+import { encodeUtf8 } from '../src/util/utf8';-afterEach(() => setTextureRecipeRenderer(null));+afterEach(() => setTextureRecipeDrawer(null));++/** A project that is a few files by path. */+const project = (files: Record<string, unknown>): RecipeFileReader => async (path) => {+ if (!(path in files)) throw new Error(`there is no file at ${path}`);+ const file = files[path];+ const bytes = file instanceof Uint8Array ? file : encodeUtf8(typeof file === 'string' ? file : JSON.stringify(file));+ return bytes.slice().buffer as ArrayBuffer;+};++const FLAG = { size: [8, 4], background: '#0000ff', layers: [{ shape: 'rect', at: [0, 0], size: [4, 4], fill: '#ff0000' }] };+const pixel = (drawn: { width: number; pixels: Uint8Array }, x: number, y: number): number[] => Array.from(drawn.pixels.subarray((y * drawn.width + x) * 4, (y * drawn.width + x) * 4 + 4));describe('a texture recipe', () => {it('is a path that ends in .esimage, whatever its case or its query', () => {@@ -25,27 +43,132 @@ describe('a texture recipe', () => {});it('is refused by name where nothing draws recipes, and says what to import', async () => {- expect(hasTextureRecipeRenderer()).toBe(false);- await expect(renderTextureRecipe('{}', 'assets/wall.esimage')).rejects.toThrow(/assets\/wall\.esimage.*esengine\/image/);+ expect(hasTextureRecipeDrawer()).toBe(false);+ await expect(renderTextureRecipe('assets/wall.esimage', project({ 'assets/wall.esimage': FLAG }))).rejects.toThrow(/assets\/wall\.esimage.*esengine\/image/);});it('is drawn by the raster once esengine/image is imported: the pixels are the picture its source says', async () => {- await import('../src/image/index');- expect(hasTextureRecipeRenderer()).toBe(true);- const source = JSON.stringify({ size: [8, 4], background: '#0000ff', layers: [{ shape: 'rect', at: [0, 0], size: [4, 4], fill: '#ff0000' }] });- const drawn = await renderTextureRecipe(source, 'assets/flag.esimage');+ (await import('../src/image/index')).installTextureRecipes();+ expect(hasTextureRecipeDrawer()).toBe(true);+ const drawn = await renderTextureRecipe('assets/flag.esimage', project({ 'assets/flag.esimage': FLAG }));expect([drawn.width, drawn.height, drawn.pixels.length]).toEqual([8, 4, 8 * 4 * 4]);- const at = (x: number, y: number): number[] => Array.from(drawn.pixels.subarray((y * 8 + x) * 4, (y * 8 + x) * 4 + 4));- expect(at(1, 1)).toEqual([255, 0, 0, 255]);- expect(at(6, 2)).toEqual([0, 0, 255, 255]);+ expect(pixel(drawn, 1, 1)).toEqual([255, 0, 0, 255]);+ expect(pixel(drawn, 6, 2)).toEqual([0, 0, 255, 255]);+ });++ it('refuses a source that is not a picture, by what is wrong with it', async () => {+ (await import('../src/image/index')).installTextureRecipes();+ await expect(renderTextureRecipe('a.esimage', project({ 'a.esimage': '{"size":8}' }))).rejects.toThrow();+ await expect(renderTextureRecipe('a.esimage', project({ 'a.esimage': { mapOf: 'b.esimage', map: 'height' } }))).rejects.toThrow(/normal, surface/);+ await expect(renderTextureRecipe('a.esimage', project({ 'a.esimage': { mapOf: 'b.png', map: 'normal' } }))).rejects.toThrow(/mapOf/);+ });+});++describe('what a recipe draws on the device', () => {+ const install = async (): Promise<typeof import('../src/image/index')> => {+ const image = await import('../src/image/index');+ // The entry installs its drawer once, on import, and every test here ends by taking it out.+ image.installTextureRecipes();+ return image;+ };++ it('a figure: the body a picture is drawn over is posed here as it is where it is authored', async () => {+ const { renderImage, validateImageSource } = await install();+ const source = { size: 64, background: '#ffffff', layers: [+ { id: 'f', shape: 'figure', at: [32, 60], height: 50 },+ { shape: 'rect', at: [0, 0], size: [64, 64], fill: '#ff0000', clip: 'f' },+ ] };+ const drawn = await renderTextureRecipe('a.esimage', project({ 'a.esimage': source }));+ const direct = renderImage(validateImageSource(source));+ expect(Array.from(drawn.pixels)).toEqual(Array.from(direct.rgba));+ // The red is clipped to the body: there is some of it, and the corner is still paper.+ let red = 0;+ for (let i = 0; i < drawn.pixels.length; i += 4) if (drawn.pixels[i]! > 200 && drawn.pixels[i + 1]! < 80) red++;+ expect(red).toBeGreaterThan(40);+ expect(pixel(drawn, 1, 1)).toEqual([255, 255, 255, 255]);+ });++ it('a picture laid in a picture, where the one laid in is a recipe too', async () => {+ await install();+ const outer = { size: [8, 4], background: '#000000', layers: [{ shape: 'image', src: 'assets/flag.esimage', at: [0, 0], guide: false }] };+ const drawn = await renderTextureRecipe('assets/outer.esimage', project({ 'assets/outer.esimage': outer, 'assets/flag.esimage': FLAG }));+ expect(pixel(drawn, 1, 1)).toEqual([255, 0, 0, 255]);+ expect(pixel(drawn, 6, 2)).toEqual([0, 0, 255, 255]);+ await expect(renderTextureRecipe('assets/outer.esimage', project({ 'assets/outer.esimage': outer }))).rejects.toThrow(/assets\/flag\.esimage/);+ const loop = { size: 4, layers: [{ shape: 'image', src: 'a.esimage', at: [0, 0] }] };+ await expect(renderTextureRecipe('a.esimage', project({ 'a.esimage': loop }))).rejects.toThrow(/needs itself/);+ });++ it('the surface maps of a picture, each a recipe of its own that names the picture', async () => {+ const { renderImage, renderMaterialMaps, validateImageSource } = await install();+ const wall = {+ size: 16, background: '#808080', layers: [{ shape: 'rect', at: [4, 4], size: [8, 8], fill: '#ffffff' }],+ material: { relief: 6, height: [{ shape: 'rect', at: [4, 4], size: [8, 8], fill: '#ffffff' }], roughness: [{ shape: 'rect', at: [0, 0], size: [16, 8], fill: '#ffffff' }] },+ };+ const files = { 'w.esimage': wall, 'w_normal.esimage': { mapOf: 'w.esimage', map: 'normal' }, 'w_surface.esimage': { mapOf: 'w.esimage', map: 'surface' } };+ const source = validateImageSource(wall);+ const maps = renderMaterialMaps(source, renderImage(source));+ const normal = await renderTextureRecipe('w_normal.esimage', project(files));+ expect(Array.from(normal.pixels)).toEqual(Array.from(maps.normal.rgba));+ // The block's left edge leans left: less red than a flat pixel's 128, which the middle of the block is.+ expect(pixel(normal, 4, 8)[0]).toBeLessThan(110);+ expect(pixel(normal, 8, 8).slice(0, 3)).toEqual([128, 128, 255]);+ const surface = await renderTextureRecipe('w_surface.esimage', project(files));+ expect(Array.from(surface.pixels)).toEqual(Array.from(maps.surface!.rgba));+ expect([pixel(surface, 2, 2)[1], pixel(surface, 2, 12)[1]]).toEqual([255, 0]);+ });++ it('one roughness and one metal everywhere is a surface map of one pixel', async () => {+ await install();+ const files = { 'p.esimage': { ...FLAG, material: { roughness: 0.4, metal: 1 } }, 's.esimage': { mapOf: 'p.esimage', map: 'surface' } };+ const surface = await renderTextureRecipe('s.esimage', project(files));+ expect([surface.width, surface.height, Array.from(surface.pixels)]).toEqual([1, 1, [255, 102, 255, 255]]);});- it('refuses a source that is not a picture, and a picture that needs a body to pose', async () => {- const { renderImage, validateImageSource } = await import('../src/image/index');- setTextureRecipeRenderer((source) => { const p = renderImage(validateImageSource(JSON.parse(source))); return { width: p.width, height: p.height, pixels: p.rgba }; });- await expect(renderTextureRecipe('{"size":8}', 'a.esimage')).rejects.toThrow();- const figure = JSON.stringify({ size: 64, layers: [{ id: 'f', shape: 'figure', at: [32, 60], height: 50 }] });- await expect(renderTextureRecipe(figure, 'a.esimage')).rejects.toThrow(/figure/);+ /** A canvas that covers a square of 4 pixels where each character is set, and remembers the font it was set in. */+ const fakeCanvas = (seen: { fonts: string[] }) => (w: number, h: number) => {+ const alpha = new Uint8Array(w * h * 4);+ const ctx = {+ font: '', textBaseline: '', textAlign: '', lineWidth: 1, lineJoin: '',+ setTransform() {}, clearRect() { alpha.fill(0); }, measureText: () => ({ width: 6 }), strokeText() {},+ fillText(_t: string, x: number, y: number) {+ seen.fonts.push(ctx.font);+ for (let dy = -4; dy < 0; dy++) for (let dx = 0; dx < 4; dx++) alpha[((Math.round(y) + dy) * w + Math.round(x) + dx) * 4 + 3] = 255;+ },+ getImageData: () => ({ data: alpha }),+ };+ return { width: w, height: h, getContext: () => ctx };+ };++ it('text, set by the canvas the platform has, in a font file of the project where it names one', async () => {+ await install();+ const seen = { fonts: [] as string[] };+ const registered: [string, number][] = [];+ setPlatform({ name: 'web', createCanvas: fakeCanvas(seen), registerFont: async (family: string, bytes: ArrayBuffer) => { registered.push([family, bytes.byteLength]); } } as unknown as PlatformAdapter);+ const sign = { size: [32, 16], background: '#000000', layers: [{ shape: 'text', text: 'ab', at: [4, 12], fontSize: 8, font: 'assets/fonts/sign.ttf', fill: '#ffff00' }] };+ const drawn = await renderTextureRecipe('sign.esimage', project({ 'sign.esimage': sign, 'assets/fonts/sign.ttf': new Uint8Array(12) }));+ expect(pixel(drawn, 5, 10)).toEqual([255, 255, 0, 255]);+ expect(pixel(drawn, 11, 10)).toEqual([255, 255, 0, 255]);+ expect(pixel(drawn, 20, 10)).toEqual([0, 0, 0, 255]);+ expect(registered).toHaveLength(1);+ expect(registered[0]![1]).toBe(12);+ expect(seen.fonts[0]).toContain(`"${registered[0]![0]}"`);+ });++ it('text where the host has no canvas is refused by what to do about it', async () => {+ await install();+ setPlatform({ name: 'native', createCanvas: () => { throw new Error('no canvas'); } } as unknown as PlatformAdapter);+ const sign = { size: [32, 16], layers: [{ shape: 'text', text: 'a', at: [4, 12], fontSize: 8, fill: '#ffff00' }] };+ await expect(renderTextureRecipe('sign.esimage', project({ 'sign.esimage': sign }))).rejects.toThrow(/2D canvas.*bake/);+ });++ it('whatever reads an image as numbers reads a recipe as its pixels', async () => {+ await install();+ const read = project({ 'assets/flag.esimage': FLAG });+ const app = { hasResource: (r: unknown) => r === Assets, getResource: () => ({ fetchBinary: read }) } as unknown as App;+ const image = await imagePixelsAt(app, 'assets/flag.esimage');+ expect([image!.width, image!.height]).toEqual([8, 4]);+ expect(Array.from(image!.pixels.subarray(0, 4))).toEqual([255, 0, 0, 255]);});});@@ -62,12 +185,17 @@ describe('a drawn recipe is kept', () => {return { adapter, files, asked };};const SOURCE = JSON.stringify({ size: [4, 2], background: '#00ff00', layers: [] });+ const at = (source = SOURCE, more: Record<string, unknown> = {}): RecipeFileReader => project({ 'a.esimage': source, ...more });const settle = (): Promise<void> => new Promise((r) => setTimeout(r, 0));let drawn = 0;- const install = (revision: string): void => setTextureRecipeRenderer(() => {- drawn++;- return { width: 4, height: 2, pixels: new Uint8Array(32).fill(7) };- }, revision);+ const install = (revision: string, needs: readonly string[] = []): void => setTextureRecipeDrawer({+ revision,+ needs: () => needs,+ draw: () => {+ drawn++;+ return { width: 4, height: 2, pixels: new Uint8Array(32).fill(7) };+ },+ });it('is drawn once and read back after, by the same source and the same drawer', async () => {const { adapter, files, asked } = cachePlatform();@@ -75,10 +203,10 @@ describe('a drawn recipe is kept', () => {textureRecipeStats(true);drawn = 0;install('r1');- const first = await renderTextureRecipe(SOURCE, 'a.esimage');+ const first = await renderTextureRecipe('a.esimage', at());await settle();expect([drawn, asked.writes, files.size]).toEqual([1, 1, 1]);- const second = await renderTextureRecipe(SOURCE, 'a.esimage');+ const second = await renderTextureRecipe('a.esimage', at());expect(drawn).toBe(1);expect([second.width, second.height]).toEqual([4, 2]);expect(Array.from(second.pixels)).toEqual(Array.from(first.pixels));@@ -90,15 +218,28 @@ describe('a drawn recipe is kept', () => {setPlatform(adapter);drawn = 0;install('r1');- await renderTextureRecipe(SOURCE, 'a.esimage');+ await renderTextureRecipe('a.esimage', at());await settle();- await renderTextureRecipe(SOURCE.replace('#00ff00', '#00ff01'), 'a.esimage');+ await renderTextureRecipe('a.esimage', at(SOURCE.replace('#00ff00', '#00ff01')));expect(drawn).toBe(2);await settle();install('r2');- await renderTextureRecipe(SOURCE, 'a.esimage');+ await renderTextureRecipe('a.esimage', at());expect(drawn).toBe(3);- expect(textureRecipeCacheKey(SOURCE, 'r1')).not.toBe(textureRecipeCacheKey(SOURCE, 'r2'));+ expect(textureRecipeCacheKey(SOURCE, new Map(), 'r1')).not.toBe(textureRecipeCacheKey(SOURCE, new Map(), 'r2'));+ });++ it('is drawn again when a file it was drawn from is another file, and not when it is the same', async () => {+ const { adapter } = cachePlatform();+ setPlatform(adapter);+ drawn = 0;+ install('r1', ['assets/photo.png']);+ await renderTextureRecipe('a.esimage', at(SOURCE, { 'assets/photo.png': new Uint8Array([1, 2, 3]) }));+ await settle();+ await renderTextureRecipe('a.esimage', at(SOURCE, { 'assets/photo.png': new Uint8Array([1, 2, 3]) }));+ expect(drawn).toBe(1);+ await renderTextureRecipe('a.esimage', at(SOURCE, { 'assets/photo.png': new Uint8Array([1, 2, 4]) }));+ expect(drawn).toBe(2);});it('is drawn again where what was kept is not the size it says, and where nothing is kept at all', async () => {@@ -106,15 +247,15 @@ describe('a drawn recipe is kept', () => {setPlatform(adapter);drawn = 0;install('r1');- await renderTextureRecipe(SOURCE, 'a.esimage');+ await renderTextureRecipe('a.esimage', at());await settle();for (const key of files.keys()) files.set(key, files.get(key)!.slice(0, 20));- await renderTextureRecipe(SOURCE, 'a.esimage');+ await renderTextureRecipe('a.esimage', at());expect(drawn).toBe(2);// A platform with no cache: every run draws, and nothing is thrown for the want of one.setPlatform({ name: 'web' } as unknown as PlatformAdapter);- await renderTextureRecipe(SOURCE, 'a.esimage');- await renderTextureRecipe(SOURCE, 'a.esimage');+ await renderTextureRecipe('a.esimage', at());+ await renderTextureRecipe('a.esimage', at());expect(drawn).toBe(4);});});diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjsindex fe8aa6645..68cf7b489 100644--- a/tools/apiSubsystems.mjs+++ b/tools/apiSubsystems.mjs@@ -352,8 +352,8 @@ export const SUBSYSTEMS = [titleZh: '贴图配方',source: ['image'],tier: 'experimental',- why: 'a recipe draws on the device to the very pixels its baked picture has, checked in a headless game, and is drawn on a worker once and read from the content cache after, checked in a browser opened twice; but it has not been timed on a phone, and the surface maps of a source are still baked',- whyZh: '配方在设备上画出来的像素与烘焙好的图片逐像素一致,已在无头游戏里检查过;它在工作线程上画一次,之后从内容缓存读取,已在浏览器里两次打开检查过;但没有在手机上计过时,源文件的表面贴图仍需烘焙',+ why: 'a recipe draws on the device to the very pixels its baked picture has, checked in a headless game, and is drawn on a worker once and read from the content cache after, checked in a browser opened twice, text, figures, laid-in pictures and surface maps included; but it has not been timed on a phone, text follows the fonts of the device unless a font file is named, and a ground reading a recipe as its layer is checked by a test and not in a game',+ whyZh: '配方在设备上画出来的像素与烘焙好的图片逐像素一致,已在无头游戏里检查过;它在工作线程上画一次,之后从内容缓存读取,已在浏览器里两次打开检查过,文字、人物、铺入的图片和表面贴图都在内;但没有在手机上计过时,不指定字体文件时文字跟随设备字体,地形把配方当图层读只有测试检查过、没在游戏里检查过',entry: ['renderImage', 'validateImageSource'],},{diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex c0b59ffc4..d26e6936d 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4678,6 +4678,8 @@ export const NOTED = {{"note": "A texture can ship as its recipe."},"feat(assets): a texture recipe is drawn on a worker, once - the picture is drawn off the main thread and its pixels are kept in the content cache, so the next run reads them and draws nothing; a browser has a content cache now, in IndexedDB, and a changed recipe or raster is a different entry":{"note": "A texture recipe is drawn on a worker, once."},+ "feat(assets): a recipe is read wherever an image is, with its text, its figures and its surface maps - a ground's layers and a field's maps take an .esimage, a map of a picture is a two-line recipe that names it, text is set by the device's canvas and a figure is posed by the bones the pipeline poses, which moved into the SDK; a recipe ships with the pictures and fonts it names and is drawn again when one changes":+ {"note": "A recipe is read wherever an image is, with its text, its figures and its surface maps."},"fix(terrain): a detail the pages cannot hold no longer cracks the ground - a tree that wanted more nodes than the atlas has pages was drawn in part by coarser pages standing in, which do not meet their finer neighbours' edges, and the pages were fought over every frame; the ground is now drawn at the share of its detail's range that fits, and says so once":{"note": "A detail the pages cannot hold no longer cracks the ground."},"fix(foliage): a far plant grows across the ground, not taller - a mesh plant kept in a far version was grown the same every way to cover the ground of those left out, so a flower that stood for ten stood ten times as high and a far meadow was a field of poles; it now grows across the ground only, and Foliage.farGrowUp gives its height a share of the growth back":