Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(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

yhh6dd880a4f00f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3cf902b8..924af0f54 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ published separately; it ships inside the editor.
### Added
+- **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.
- **The grade has a gain and an offset, and the vignette a radius and a roundness.** Color Grade could add to the blacks (Lift) and never take from them, and its contrast in a linear project is a power curve about 0.18, which leaves black where it was. A look graded elsewhere with a contrast that is a line through 0.5 sinks its blacks: without that, a meadow that measures 0.77 saturation there measured 0.50 here, with a film of blue over every dark green. **Gain** (`u_gain`) multiplies every tone and **Offset** (`u_offset`, which may be under zero) is added after it, as a grade's slope and offset are; `(c - 0.5) * k + 0.5` is a gain of `k` and an offset of `0.5 - 0.5 * k`. The Vignette was full at the middle of every edge whatever its numbers: **Radius** (`u_radius`) is where it is full, and **Roundness** (`u_roundness`) takes it from the frame's own ellipse to a circle whose 1 is the corner, the usual lens vignette. Every default is the picture as it was.
diff --git a/docs/astro/src/content/docs/assets/textures.mdx b/docs/astro/src/content/docs/assets/textures.mdx
index af27ab8b9..937608909 100644
--- a/docs/astro/src/content/docs/assets/textures.mdx
+++ b/docs/astro/src/content/docs/assets/textures.mdx
@@ -205,12 +205,18 @@ 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 86 KB of a web package before compression: an export adds it when a recipe ships, and a script that
+`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
loads one by code imports it where the game starts. A package with no recipe does not carry it.
-What a recipe costs is time: it is drawn on the main thread when it loads, every run. Draw large ones behind a loading screen. 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).
+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
+kept in the device's content cache: the next run reads them and draws nothing. A 2048 pixel plate took 4.1 s on a desktop worker
+the first visit, with the main thread never held longer than its usual start-up; the second visit drew nothing. The kept pixels are
+uncompressed (16 MB for that plate) and nothing removes them unasked: `assets.cleanDiskCache(budget, true)` gives up what was read
+longest 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 a
+different 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).
## Memory & residency
diff --git a/docs/astro/src/content/docs/zh-cn/assets/textures.mdx b/docs/astro/src/content/docs/zh-cn/assets/textures.mdx
index 6c4a06146..cc4132cc7 100644
--- a/docs/astro/src/content/docs/zh-cn/assets/textures.mdx
+++ b/docs/astro/src/content/docs/zh-cn/assets/textures.mdx
@@ -179,10 +179,14 @@ sprite.uvScale = { x: 32 / 256, y: 32 / 256 };
```
一块 512 像素、带噪声、锈迹、色带和铆钉的钢板,作为配方是 691 字节,作为 PNG 是 351 KB。负责画配方的是 `esengine/image` 模块,压缩前约占
-web 包 86 KB:导出时只要包里有配方就会自动带上,用脚本按代码加载配方的话,在游戏启动处导入它。没有配方的包不会带它。
+web 包 172 KB(gzip 后 62 KB):导出时只要包里有配方就会自动带上,用脚本按代码加载配方的话,在游戏启动处导入它。没有配方的包不会带它。
-配方的代价是时间:它在加载时于主线程绘制,每次运行都要画。大的配方放在加载画面后面画。带 `figure` 图层或文字的图需要创作工具才能画,仍然
-烘焙成 `.png`;源文件的表面贴图(法线和粗糙度)也是。
+配方的代价是时间,而且只付一次。它在工作线程上绘制,画的时候游戏照常运行;画出的像素存进设备的内容缓存,下次运行直接读取,什么都不画。
+一块 2048 像素的钢板第一次访问时在桌面工作线程上画了 4.1 秒,主线程的最长占用没有超过平常启动的水平;第二次访问一笔没画。存下来的像素
+没有压缩(那块钢板是 16 MB),也不会被自动清掉:`assets.cleanDiskCache(budget, true)` 先清最久没读过的,被清掉的图下次再画一遍。没有工作线程的环境里配方在主线程绘制;没有缓存的环境里每次运行都画。配方变了,
+或者光栅器变了,就是另一个缓存项,所以不会读到过期的像素。
+
+带 `figure` 图层或文字的图需要创作工具才能画,仍然烘焙成 `.png`;源文件的表面贴图(法线和粗糙度)也是。
## 内存与驻留
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 701f5ebb2..4882aaa5b 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": 3068,
+ "experimental": 3069,
"deprecated": 3
},
- "total": 3363,
+ "total": 3364,
"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, but it is drawn on the main thread at load, is not kept between runs, and has not been timed on a phone",
- "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; but it has not been timed on a phone, and the surface maps of a source are still baked",
+ "whyZh": "配方在设备上画出来的像素与烘焙好的图片逐像素一致,已在无头游戏里检查过;它在工作线程上画一次,之后从内容缓存读取,已在浏览器里两次打开检查过;但没有在手机上计过时,源文件的表面贴图仍需烘焙",
"entry": [
"renderImage",
"validateImageSource"
diff --git a/sdk/etc/image.api.md b/sdk/etc/image.api.md
index bce4597f0..4e8988504 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 · 15 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 16 experimental · 0 deprecated
## FlatFigure — interface @experimental
```
@@ -14,6 +14,11 @@ normals: Float32Array<ArrayBufferLike>
parts: Record<string, Float32Array<ArrayBufferLike>>
```
+## IMAGE_RASTER_REVISION — const @experimental
+```
+"1"
+```
+
## IMAGE_SOURCE_EXT — const @experimental
```
".esimage"
diff --git a/sdk/scripts/build-worker.mjs b/sdk/scripts/build-worker.mjs
index fa2644119..af856bace 100644
--- a/sdk/scripts/build-worker.mjs
+++ b/sdk/scripts/build-worker.mjs
@@ -1,14 +1,19 @@
-// Bundles the worlds' planning worker (src/worldgen/planWorker.ts) into the text the engine starts its workers from, and writes it as a module:
+// Bundles the engine's workers (the worlds' planning worker, the texture recipes' drawing worker) into the text they are started from, and writes each as a module:
// node scripts/build-worker.mjs [--check]
-// `--check` writes nothing and exits 1 when the committed text is not what the source makes now.
+// `--check` writes nothing and exits 1 when a committed text is not what its source makes now.
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
-import { workerModule } from './worker-source.mjs';
+import { basename } from 'node:path';
+import { workerModules } from './worker-source.mjs';
-const { path, source, bytes } = await workerModule();
-if (process.argv.includes('--check')) {
- if ((existsSync(path) ? readFileSync(path, 'utf8') : '') !== source) { console.error('planWorkerBundle.generated.ts is not what src/worldgen/planWorker.ts makes now: run node scripts/build-worker.mjs'); process.exit(1); }
- console.log('planWorkerBundle.generated.ts is current');
-} else {
- writeFileSync(path, source);
- console.log(`planWorkerBundle.generated.ts: ${bytes} bytes of worker`);
+let stale = false;
+for (const { path, source, bytes, entry } of await workerModules()) {
+ const name = basename(path);
+ if (process.argv.includes('--check')) {
+ if ((existsSync(path) ? readFileSync(path, 'utf8') : '') !== source) { console.error(`${name} is not what ${entry} makes now: run node scripts/build-worker.mjs`); stale = true; }
+ else console.log(`${name} is current`);
+ } else {
+ writeFileSync(path, source);
+ console.log(`${name}: ${bytes} bytes of worker`);
+ }
}
+if (stale) process.exit(1);
diff --git a/sdk/scripts/worker-source.mjs b/sdk/scripts/worker-source.mjs
index c195aca63..45b28a081 100644
--- a/sdk/scripts/worker-source.mjs
+++ b/sdk/scripts/worker-source.mjs
@@ -1,24 +1,42 @@
-// The planning worker (src/worldgen/planWorker.ts) bundled into one script, and the module that carries its text.
+// The engine's workers, each bundled into one script, and the module that carries its text.
import { rolldown } from 'rolldown';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
const root = `${resolve(dirname(fileURLToPath(import.meta.url)), '..')}/`;
-/** The path of the generated module, and its source for the script the bundler makes now. */
-export async function workerModule() {
- const bundle = await rolldown({ input: `${root}src/worldgen/planWorker.ts`, platform: 'browser', treeshake: { moduleSideEffects: () => true }, logLevel: 'silent' });
+/** Every worker: where its source is, the module its text is written to, and the name and the words that module gives it. */
+const WORKERS = [
+ { entry: 'src/worldgen/planWorker.ts', out: 'src/runtime/planWorkerBundle.generated.ts', name: 'PLAN_WORKER_SOURCE',
+ doc: "The planning worker's script: what a pool of planning workers is started from." },
+ { entry: 'src/image/recipeWorker.ts', out: 'src/image/recipeWorkerBundle.generated.ts', name: 'RECIPE_WORKER_SOURCE',
+ doc: "The recipe worker's script: what the workers that draw texture recipes are started from." },
+];
+
+async function build(worker) {
+ const bundle = await rolldown({ input: `${root}${worker.entry}`, platform: 'browser', treeshake: { moduleSideEffects: () => true }, logLevel: 'silent' });
const { output } = await bundle.generate({ format: 'iife', minify: true, codeSplitting: false });
await bundle.close();
const text = output.find((c) => c.type === 'chunk').code;
return {
- path: `${root}src/runtime/planWorkerBundle.generated.ts`,
+ entry: worker.entry,
+ path: `${root}${worker.out}`,
bytes: text.length,
source: `// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-// Generated by sdk/scripts/build-worker.mjs from src/worldgen/planWorker.ts: do not edit.
-/** The planning worker's script: what a pool of planning workers is started from. */
-export const PLAN_WORKER_SOURCE = ${JSON.stringify(text)};
+// Generated by sdk/scripts/build-worker.mjs from ${worker.entry}: do not edit.
+/** ${worker.doc} */
+export const ${worker.name} = ${JSON.stringify(text)};
`,
};
}
+
+/** The path of each generated module, and its source for the script the bundler makes now. */
+export async function workerModules() {
+ return Promise.all(WORKERS.map(build));
+}
+
+/** The planning worker's alone (the first of them). */
+export async function workerModule() {
+ return build(WORKERS[0]);
+}
diff --git a/sdk/src/asset/textureRecipe.ts b/sdk/src/asset/textureRecipe.ts
index e0cf6c648..d6f92d8d2 100644
--- a/sdk/src/asset/textureRecipe.ts
+++ b/sdk/src/asset/textureRecipe.ts
@@ -7,7 +7,14 @@
* @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.
+ *
+ * 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.
*/
+import { contentHashHex } from './contentHash';
+import { platformReadCacheFile, platformWriteCacheFile } from '../platform';
+import { 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 }
@@ -15,8 +22,21 @@ export interface RecipePixels { width: number; height: number; pixels: Uint8Arra
/** Draws a recipe from its source text. */
export type TextureRecipeRenderer = (source: string, path: string) => RecipePixels | Promise<RecipePixels>;
+/** What recipes have cost since the game began (or since the counts were last cleared). */
+export interface TextureRecipeStats {
+ /** Recipes drawn, and how long the drawing took in all, in milliseconds of the clock on the wall. */
+ drawn: number;
+ drawMs: number;
+ /** Recipes read back from the content cache, drawn by an earlier run. */
+ reused: number;
+}
+
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 = '';
+const stats: TextureRecipeStats = { drawn: 0, drawMs: 0, reused: 0 };
/** Whether a texture's path names a recipe and not an image. */
export function isTextureRecipePath(path: string): boolean {
@@ -24,17 +44,61 @@ 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. */
-export function setTextureRecipeRenderer(next: TextureRecipeRenderer | null): void {
+/**
+ * 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;
}
export function hasTextureRecipeRenderer(): boolean {
return renderer !== null;
}
-/** The pixels of the recipe at `path`, whose source is `source`. */
+/** The counts so far; `clear` starts them again. */
+export function textureRecipeStats(clear = false): TextureRecipeStats {
+ const now = { ...stats };
+ if (clear) { stats.drawn = 0; stats.drawMs = 0; stats.reused = 0; }
+ 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))}`;
+}
+
+function unpack(bytes: ArrayBuffer): RecipePixels | null {
+ if (bytes.byteLength < KEPT_HEADER) return null;
+ const head = new DataView(bytes);
+ const width = head.getUint32(0, true), height = head.getUint32(4, true);
+ // A kept picture that is not the size it says is not read: it is drawn again and written over.
+ if (width === 0 || height === 0 || bytes.byteLength !== KEPT_HEADER + width * height * 4) return null;
+ return { width, height, pixels: new Uint8Array(bytes, KEPT_HEADER) };
+}
+
+function pack(drawn: RecipePixels): ArrayBuffer {
+ const bytes = new ArrayBuffer(KEPT_HEADER + drawn.pixels.byteLength);
+ const head = new DataView(bytes);
+ head.setUint32(0, drawn.width, true);
+ head.setUint32(4, drawn.height, true);
+ new Uint8Array(bytes, KEPT_HEADER).set(drawn.pixels);
+ 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`);
- return renderer(source, path);
+ const key = textureRecipeCacheKey(source);
+ const kept = await platformReadCacheFile(key);
+ const read = kept ? unpack(kept) : null;
+ if (read) { stats.reused++; return read; }
+ const began = Date.now();
+ const drawn = await renderer(source, 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.
+ void platformWriteCacheFile(key, pack(drawn));
+ return drawn;
}
diff --git a/sdk/src/image/imageRaster.ts b/sdk/src/image/imageRaster.ts
index e9a2d1906..58afe6e62 100644
--- a/sdk/src/image/imageRaster.ts
+++ b/sdk/src/image/imageRaster.ts
@@ -13,6 +13,12 @@ import type { ImageFill, ImageLayer, ImageSource, ImageAlong, ImageBrushSettings
import { type Pt, parsePath } from './imagePath';
import { type Rgba, blurMask, fractalNoise, gradientNoise, isWrapping, parseColor, setWrapping } from './imageNoise';
+/**
+ * How this raster draws, as a name: what a picture drawn and kept (a texture recipe in the content cache) is kept under. It changes
+ * whenever the same source would come out as other pixels; tests/image-raster-revision.test.ts fails until it does.
+ */
+export const IMAGE_RASTER_REVISION = '1';
+
export interface RgbaBitmap { width: number; height: number; rgba: Uint8Array }
/** A `figure` layer flattened into the picture: what the drawer of figures hands the raster. */
diff --git a/sdk/src/image/index.ts b/sdk/src/image/index.ts
index bf9d5f6df..69311fd46 100644
--- a/sdk/src/image/index.ts
+++ b/sdk/src/image/index.ts
@@ -8,12 +8,30 @@ export { renderImage, type RenderedImage, type RgbaBitmap, type ImageFigureDrawe
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 { IMAGE_RASTER_REVISION } from './imageRaster';
+
// Importing this subpath INSTALLS the drawer of texture recipes — see tilemap/index.ts.
-import { renderImage } from './imageRaster';
-import { validateImageSource } from './imageSource';
-import { setTextureRecipeRenderer } from '../asset/textureRecipe';
+import { IMAGE_RASTER_REVISION } from './imageRaster';
+import { drawRecipe } from './recipeWorker';
+import { RECIPE_WORKER_SOURCE } from './recipeWorkerBundle.generated';
+import { setTextureRecipeRenderer, type RecipePixels } from '../asset/textureRecipe';
+import { createJobPool, type JobPool } from '../runtime/jobs';
+
+let pool: JobPool | null | undefined;
+let next = 0;
-setTextureRecipeRenderer((source) => {
- const picture = renderImage(validateImageSource(JSON.parse(source)));
- return { width: picture.width, height: picture.height, pixels: picture.rgba };
-});
+// 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) {
+ 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 drawRecipe(source);
+}, IMAGE_RASTER_REVISION);
diff --git a/sdk/src/image/recipeWorker.ts b/sdk/src/image/recipeWorker.ts
new file mode 100644
index 000000000..c8dd5cc1e
--- /dev/null
+++ b/sdk/src/image/recipeWorker.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: Apache-2.0
+// 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.
+ *
+ * @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 }`.
+ */
+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() };
+}
+
+declare const self: { onmessage: ((e: { data: { id: number; source: string } }) => void) | null; postMessage(m: unknown, transfer?: ArrayBuffer[]): void } | undefined;
+
+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) });
+ }
+ };
+}
diff --git a/sdk/src/image/recipeWorkerBundle.generated.ts b/sdk/src/image/recipeWorkerBundle.generated.ts
new file mode 100644
index 000000000..600f1c382
--- /dev/null
+++ b/sdk/src/image/recipeWorkerBundle.generated.ts
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0
+// 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})({});";
diff --git a/sdk/src/platform/web.ts b/sdk/src/platform/web.ts
index b4ded3a2b..97e2b614b 100644
--- a/sdk/src/platform/web.ts
+++ b/sdk/src/platform/web.ts
@@ -29,6 +29,8 @@ import { GameSocket } from '../net/GameSocket';
import { createPrimaryPointer } from './primaryPointer';
import { createWebRecorder } from './webRecorder';
import { WebDevice } from '../device/web';
+import { cacheEntryName } from './cacheEntryName';
+import { webCacheAvailable, webCacheList, webCacheRead, webCacheRemove, webCacheWrite } from './webCacheStore';
const WHEEL_LINE_HEIGHT = 16;
@@ -341,6 +343,18 @@ class WebPlatformAdapter implements PlatformAdapter {
return new GameSocket(options);
}
+ // The content cache, in IndexedDB (webCacheStore.ts): what a page makes and would make again each visit, and what a hot
+ // update downloads, kept under the cache's own names.
+ hasCacheStorage(): boolean { return webCacheAvailable(); }
+ canManageCache(): boolean { return webCacheAvailable(); }
+ readCacheFile(key: string): Promise<ArrayBuffer | null> { return webCacheRead(cacheEntryName(key)); }
+ writeCacheFile(key: string, bytes: ArrayBuffer): Promise<void> { return webCacheWrite(cacheEntryName(key), bytes); }
+ listCacheFiles(): Promise<{ name: string; size: number; lastAccess: number }[]> { return webCacheList(); }
+ removeCacheFile(name: string): Promise<void> {
+ if (!/^[0-9a-f]{16}$/.test(name)) throw Error('invalid cache entry');
+ return webCacheRemove(name);
+ }
+
getStorageItem(key: string): string | null {
return localStorage.getItem(key);
}
diff --git a/sdk/src/platform/webCacheStore.ts b/sdk/src/platform/webCacheStore.ts
new file mode 100644
index 000000000..5952bf8a7
--- /dev/null
+++ b/sdk/src/platform/webCacheStore.ts
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file webCacheStore.ts
+ * @brief The browser's content cache: files by name in IndexedDB, behind the platform's cache-file methods.
+ *
+ * @details The content cache holds bytes that never go stale (a key says what the bytes are). A browser keeps what a page
+ * downloads itself, but not what the page makes: a texture drawn from its recipe is made again every visit unless it is
+ * kept here. Entries are stored under the cache's own file names (cacheEntryName), with the time each was last read.
+ */
+
+const DATABASE = 'estella-content-cache';
+const STORE = 'files';
+
+interface Stored { bytes: ArrayBuffer; size: number; lastAccess: number }
+
+let opening: Promise<IDBDatabase> | null = null;
+
+/** Whether this browser has a store at all (a worker-less or storage-less realm has none). */
+export function webCacheAvailable(): boolean {
+ return typeof indexedDB !== 'undefined';
+}
+
+function database(): Promise<IDBDatabase> {
+ opening ??= new Promise<IDBDatabase>((resolve, reject) => {
+ const request = indexedDB.open(DATABASE, 1);
+ request.onupgradeneeded = () => { request.result.createObjectStore(STORE); };
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => { opening = null; reject(request.error ?? new Error('the content cache cannot be opened')); };
+ request.onblocked = () => { opening = null; reject(new Error('the content cache is held by another page')); };
+ });
+ return opening;
+}
+
+/** One request against the store, settled when its transaction is. */
+async function ask<T>(mode: IDBTransactionMode, run: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
+ const db = await database();
+ return new Promise<T>((resolve, reject) => {
+ const transaction = db.transaction(STORE, mode);
+ const request = run(transaction.objectStore(STORE));
+ transaction.oncomplete = () => resolve(request.result);
+ transaction.onerror = () => reject(transaction.error ?? new Error('the content cache refused a request'));
+ transaction.onabort = () => reject(transaction.error ?? new Error('the content cache gave up a request'));
+ });
+}
+
+export async function webCacheRead(name: string): Promise<ArrayBuffer | null> {
+ const entry = await ask<Stored | undefined>('readonly', (s) => s.get(name) as IDBRequest<Stored | undefined>);
+ return entry ? entry.bytes : null;
+}
+
+export async function webCacheWrite(name: string, bytes: ArrayBuffer): Promise<void> {
+ await ask('readwrite', (s) => s.put({ bytes, size: bytes.byteLength, lastAccess: Date.now() } satisfies Stored, name));
+}
+
+export async function webCacheList(): Promise<{ name: string; size: number; lastAccess: number }[]> {
+ const db = await database();
+ return new Promise((resolve, reject) => {
+ const out: { name: string; size: number; lastAccess: number }[] = [];
+ const transaction = db.transaction(STORE, 'readonly');
+ const cursor = transaction.objectStore(STORE).openCursor();
+ cursor.onsuccess = () => {
+ const at = cursor.result;
+ if (!at) return;
+ const entry = at.value as Stored;
+ out.push({ name: String(at.key), size: entry.size, lastAccess: entry.lastAccess });
+ at.continue();
+ };
+ transaction.oncomplete = () => resolve(out);
+ transaction.onerror = () => reject(transaction.error ?? new Error('the content cache cannot be listed'));
+ });
+}
+
+export async function webCacheRemove(name: string): Promise<void> {
+ await ask('readwrite', (s) => s.delete(name));
+}
diff --git a/sdk/tests/image-raster-revision.test.ts b/sdk/tests/image-raster-revision.test.ts
new file mode 100644
index 000000000..0fa233ef3
--- /dev/null
+++ b/sdk/tests/image-raster-revision.test.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file image-raster-revision.test.ts
+ * @brief The raster's revision names how it draws: the same sources come out as the same pixels for as long as the revision stands.
+ *
+ * @details A texture recipe drawn on a device is kept there under the raster's revision. If a change to the raster moves a pixel and the
+ * revision stays, every device goes on showing the picture the old raster drew. So the pixels of a few sources are pinned
+ * here beside the revision: when they move, raise IMAGE_RASTER_REVISION and pin them again.
+ */
+import { describe, expect, it } from 'vitest';
+import { contentHashHex } from '../src/asset/contentHash';
+import { IMAGE_RASTER_REVISION, renderImage } from '../src/image/imageRaster';
+import { validateImageSource } from '../src/image/imageSource';
+
+const SOURCES: Record<string, unknown> = {
+ shapes: { size: 64, background: '#102030', layers: [
+ { shape: 'rect', at: [6, 6], size: [30, 20], radius: 5, fill: '#e04030', stroke: { color: '#ffffff', width: 2 } },
+ { shape: 'circle', at: [44, 40], radius: 14, fill: { type: 'radial', at: [40, 36], radius: 16, stops: [[0, '#ffe080'], [1, '#804000']] } },
+ { shape: 'star', at: [18, 46], radius: 12, inner: 5, count: 5, fill: '#40c0ff', opacity: 0.8 },
+ ] },
+ noise: { size: 64, tile: true, layers: [
+ { shape: 'rect', at: [0, 0], size: [64, 64], fill: { type: 'noise', scale: 20, octaves: 4, seed: 9, stops: [[0, '#203040'], [1, '#c0d0e0']] } },
+ { shape: 'rect', at: [0, 24], size: [64, 12], fill: { type: 'linear', from: [0, 24], to: [0, 36], stops: [[0, '#ffcc00'], [1, '#aa6600']] }, blur: 1.5 },
+ ] },
+ grid: { size: [96, 48], background: '#181818', layers: [
+ { shape: 'rect', at: [0, 0], size: [96, 48], fill: { type: 'grid', cell: [12, 12], mark: [0.5, 0.5], colors: ['#f0f0f0', '#909090'], lit: 0.7, off: '#303030', seed: 4 } },
+ ] },
+};
+
+/** The pixels of each source as revision 1 draws them (their XXH64). */
+const PINNED: Record<string, Record<string, string>> = {
+ '1': { shapes: 'bfd5719385b5613f', noise: 'b437c52dead56ad9', grid: '01b167b54446f44c' },
+};
+
+describe('the image raster\'s revision', () => {
+ it('has its pixels pinned: a change that moves one raises IMAGE_RASTER_REVISION', () => {
+ const pinned = PINNED[IMAGE_RASTER_REVISION];
+ expect(pinned, `no pixels are pinned for revision ${IMAGE_RASTER_REVISION}`).toBeDefined();
+ const drawn = Object.fromEntries(Object.entries(SOURCES).map(([name, source]) => [name, contentHashHex(renderImage(validateImageSource(source)).rgba)]));
+ expect(drawn).toEqual(pinned);
+ });
+});
diff --git a/sdk/tests/texture-recipe.test.ts b/sdk/tests/texture-recipe.test.ts
index 8685e4034..5dfa6ea91 100644
--- a/sdk/tests/texture-recipe.test.ts
+++ b/sdk/tests/texture-recipe.test.ts
@@ -5,7 +5,9 @@
* @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.
*/
import { afterEach, describe, expect, it } from 'vitest';
-import { hasTextureRecipeRenderer, isTextureRecipePath, renderTextureRecipe, setTextureRecipeRenderer } from '../src/asset/textureRecipe';
+import { hasTextureRecipeRenderer, isTextureRecipePath, renderTextureRecipe, setTextureRecipeRenderer, textureRecipeCacheKey, textureRecipeStats } from '../src/asset/textureRecipe';
+import { setPlatform } from '../src/platform/base';
+import type { PlatformAdapter } from '../src/platform/types';
import { getAddressableType } from '../src/assetTypes';
afterEach(() => setTextureRecipeRenderer(null));
@@ -46,3 +48,73 @@ describe('a texture recipe', () => {
await expect(renderTextureRecipe(figure, 'a.esimage')).rejects.toThrow(/figure/);
});
});
+
+describe('a drawn recipe is kept', () => {
+ /** A platform that is nothing but a content cache, and counts what is asked of it. */
+ const cachePlatform = () => {
+ const files = new Map<string, ArrayBuffer>();
+ const asked = { reads: 0, writes: 0 };
+ const adapter = {
+ name: 'web',
+ readCacheFile: async (key: string) => { asked.reads++; return files.get(key) ?? null; },
+ writeCacheFile: async (key: string, bytes: ArrayBuffer) => { asked.writes++; files.set(key, bytes.slice(0)); },
+ } as unknown as PlatformAdapter;
+ return { adapter, files, asked };
+ };
+ const SOURCE = JSON.stringify({ size: [4, 2], background: '#00ff00', layers: [] });
+ 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);
+
+ it('is drawn once and read back after, by the same source and the same drawer', async () => {
+ const { adapter, files, asked } = cachePlatform();
+ setPlatform(adapter);
+ textureRecipeStats(true);
+ drawn = 0;
+ install('r1');
+ const first = await renderTextureRecipe(SOURCE, 'a.esimage');
+ await settle();
+ expect([drawn, asked.writes, files.size]).toEqual([1, 1, 1]);
+ const second = await renderTextureRecipe(SOURCE, 'a.esimage');
+ expect(drawn).toBe(1);
+ expect([second.width, second.height]).toEqual([4, 2]);
+ expect(Array.from(second.pixels)).toEqual(Array.from(first.pixels));
+ expect(textureRecipeStats()).toMatchObject({ drawn: 1, reused: 1 });
+ });
+
+ it('is drawn again for another source, and for a drawer that draws differently', async () => {
+ const { adapter } = cachePlatform();
+ setPlatform(adapter);
+ drawn = 0;
+ install('r1');
+ await renderTextureRecipe(SOURCE, 'a.esimage');
+ await settle();
+ await renderTextureRecipe(SOURCE.replace('#00ff00', '#00ff01'), 'a.esimage');
+ expect(drawn).toBe(2);
+ await settle();
+ install('r2');
+ await renderTextureRecipe(SOURCE, 'a.esimage');
+ expect(drawn).toBe(3);
+ expect(textureRecipeCacheKey(SOURCE, 'r1')).not.toBe(textureRecipeCacheKey(SOURCE, 'r2'));
+ });
+
+ it('is drawn again where what was kept is not the size it says, and where nothing is kept at all', async () => {
+ const { adapter, files } = cachePlatform();
+ setPlatform(adapter);
+ drawn = 0;
+ install('r1');
+ await renderTextureRecipe(SOURCE, 'a.esimage');
+ await settle();
+ for (const key of files.keys()) files.set(key, files.get(key)!.slice(0, 20));
+ await renderTextureRecipe(SOURCE, 'a.esimage');
+ 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');
+ expect(drawn).toBe(4);
+ });
+});
diff --git a/sdk/tests/worker-bundle-fresh.test.ts b/sdk/tests/worker-bundle-fresh.test.ts
index 62aaa4397..b581b0859 100644
--- a/sdk/tests/worker-bundle-fresh.test.ts
+++ b/sdk/tests/worker-bundle-fresh.test.ts
@@ -3,11 +3,12 @@
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
// @ts-expect-error a build script, plain JavaScript
-import { workerModule } from '../scripts/worker-source.mjs';
+import { workerModules } from '../scripts/worker-source.mjs';
-describe('the planning worker\'s script', () => {
- it('is what src/worldgen/planWorker.ts makes now (run node scripts/build-worker.mjs after changing it)', async () => {
- const made = await workerModule() as { path: string; source: string };
- expect(readFileSync(made.path, 'utf8')).toBe(made.source);
+describe('the scripts the engine starts its workers from', () => {
+ it('are what their sources make now (run node scripts/build-worker.mjs after changing a worker or what it draws with)', async () => {
+ const made = await workerModules() as { path: string; source: string; entry: string }[];
+ expect(made.map((m) => m.entry)).toEqual(['src/worldgen/planWorker.ts', 'src/image/recipeWorker.ts']);
+ for (const m of made) expect(readFileSync(m.path, 'utf8'), m.entry).toBe(m.source);
});
});
diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjs
index 8df82ebdf..fe8aa6645 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, but it is drawn on the main thread at load, is not kept between runs, and has not been timed on a phone',
- 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; but it has not been timed on a phone, and the surface maps of a source are still baked',
+ whyZh: '配方在设备上画出来的像素与烘焙好的图片逐像素一致,已在无头游戏里检查过;它在工作线程上画一次,之后从内容缓存读取,已在浏览器里两次打开检查过;但没有在手机上计过时,源文件的表面贴图仍需烘焙',
entry: ['renderImage', 'validateImageSource'],
},
{
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 74a148e2e..036a518fd 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -4672,6 +4672,8 @@ export const NOTED = {
{"note": "A splatmap is read between its pixels."},
"feat(assets): a texture can ship as its recipe - an .esimage named where a texture goes is carried as its source and drawn on the device when it loads, to the pixels its png has; the raster that draws it moved from the pipeline into the SDK as esengine/image, which an export adds when a recipe ships":
{"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."},
"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":