@neta-art/cohub-cli 10.19.0 → 10.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7199,6 +7199,10 @@ function resolveBoardProperty(targetType, property) {
7199
7199
  ok: false,
7200
7200
  message: `Board scripts animate params.<name>, not ${property}`
7201
7201
  };
7202
+ if (/^script\.params\.[^.]+$/.test(property)) return {
7203
+ ok: true,
7204
+ spec: SCRIPT_PARAMETER
7205
+ };
7202
7206
  const path = property.split(".");
7203
7207
  if (path.some((segment) => !segment) || NOT_ANIMATABLE.has(path[0])) return {
7204
7208
  ok: false,
@@ -7588,6 +7592,7 @@ function validateTrack(path, animationId, value, item, animation, track, script,
7588
7592
  if (value.target === animationId || nestsInto(value.target, animationId, animation, track, state)) return [error(`${path}.target`, "ANIMATION_CYCLE", `${animationId} cannot contain itself through ${value.target}`)];
7589
7593
  } else if (script(value.target)) targetType = "script";
7590
7594
  else return [error(`${path}.target`, "TARGET_NOT_FOUND", `target ${value.target} is not an item, animation, Board script or camera`)];
7595
+ if (!keepUnknownProperty && value.property.startsWith("script.") && !item(value.target)?.script) return [error(`${path}.property`, "INVALID_PROPERTY", `${value.target} has no script to animate`)];
7591
7596
  const resolved = resolveBoardProperty(targetType, value.property);
7592
7597
  if (!resolved.ok) return keepUnknownProperty ? [] : [error(`${path}.property`, "INVALID_PROPERTY", resolved.message)];
7593
7598
  for (const [index, keyframe] of value.keyframes.entries()) {
@@ -8534,6 +8539,12 @@ function boardShaderUniformValue(uniform, value) {
8534
8539
  while (list.length < size) list.push(0);
8535
8540
  return list;
8536
8541
  }
8542
+ function boardShaderPassLayer(shader, pass) {
8543
+ return pass.layer ?? shader.layer ?? "above";
8544
+ }
8545
+ function boardShaderPassOn(pass, states) {
8546
+ return (pass.name !== void 0 ? states?.[pass.name] : void 0) ?? pass.enabled ?? true;
8547
+ }
8537
8548
  function boardShaderParameters(parameters) {
8538
8549
  const result = [];
8539
8550
  for (const [name, spec] of Object.entries(parameters ?? {})) {
@@ -8555,13 +8566,22 @@ function validateBoardShader(shader) {
8555
8566
  if (value.layer !== void 0 && !BOARD_SHADER_LAYERS.includes(value.layer)) throw new Error(`shader.layer must be ${BOARD_SHADER_LAYERS.join(", ")}.`);
8556
8567
  if (value.surfaces !== void 0 && typeof value.surfaces !== "boolean") throw new Error("shader.surfaces must be a boolean.");
8557
8568
  if (!Array.isArray(value.passes) || value.passes.length < 1 || value.passes.length > BOARD_SHADER_LIMITS.passes) throw new Error(`shader.passes takes 1 to ${BOARD_SHADER_LIMITS.passes} passes.`);
8569
+ const names = /* @__PURE__ */ new Set();
8558
8570
  for (const pass of value.passes) {
8559
8571
  if (!pass || typeof pass.glsl !== "string" || !pass.glsl.trim()) throw new Error("Each shader pass needs glsl source.");
8560
8572
  if (pass.glsl.length > BOARD_SHADER_LIMITS.source) throw new Error("A shader pass exceeds 64 KB of source.");
8573
+ if (pass.layer !== void 0 && !BOARD_SHADER_LAYERS.includes(pass.layer)) throw new Error(`A pass layer must be ${BOARD_SHADER_LAYERS.join(", ")}.`);
8561
8574
  if (pass.sprites !== void 0) {
8562
8575
  if (!Number.isSafeInteger(pass.sprites) || pass.sprites < 1 || pass.sprites > BOARD_SHADER_LIMITS.sprites) throw new Error(`sprites must be an integer from 1 to ${BOARD_SHADER_LIMITS.sprites}.`);
8563
- if (value.layer === "filter") throw new Error("Filter passes draw over the owner's box; they cannot draw sprites.");
8576
+ if (boardShaderPassLayer(value, pass) === "filter") throw new Error("Filter passes draw over the owner's box; they cannot draw sprites.");
8564
8577
  }
8578
+ if (pass.name !== void 0) {
8579
+ if (typeof pass.name !== "string" || !IDENTIFIER.test(pass.name)) throw new Error(`Invalid pass name: ${String(pass.name)}`);
8580
+ if (names.has(pass.name)) throw new Error(`Pass names must be unique: ${pass.name}`);
8581
+ names.add(pass.name);
8582
+ }
8583
+ if (pass.enabled !== void 0 && typeof pass.enabled !== "boolean") throw new Error("A pass's enabled must be a boolean.");
8584
+ if (pass.enabled === false && pass.name === void 0) throw new Error("A pass that starts off needs a name to turn it on.");
8565
8585
  if (pass.blend !== void 0 && !BOARD_SHADER_BLENDS.includes(pass.blend)) throw new Error(`blend must be ${BOARD_SHADER_BLENDS.join(", ")}.`);
8566
8586
  }
8567
8587
  boardShaderUniforms(value.uniforms);
@@ -8978,42 +8998,46 @@ function bindingsFor(owner, output) {
8978
8998
  function boardScriptTarget(scene, candidates, point, outputs, hitTest) {
8979
8999
  const declared = [...outputs].map(([owner, output]) => bindingsFor(owner, output));
8980
9000
  const prefixes = [...outputs.keys()].map(scriptTemporaryPrefix);
8981
- for (const id of [...candidates].sort((a, b) => scene.indexOf(b) - scene.indexOf(a))) {
8982
- const item = scene.get(id);
8983
- if (!item || scene.opacity(id) <= 0) continue;
8984
- let parent = item.parent;
8985
- let clipped = false;
8986
- for (let depth = 0; parent && depth < 64; depth++) {
8987
- const ancestor = scene.get(parent);
8988
- if (!ancestor) break;
8989
- if (ancestor.type === "frame" && ancestor.props.clip && !frameContainsPoint(ancestor.frame, point)) {
8990
- clipped = true;
8991
- break;
8992
- }
8993
- parent = ancestor.parent;
8994
- }
8995
- if (clipped) continue;
8996
- for (const byItem of declared) {
8997
- const hits = byItem.get(id);
8998
- if (!hits) continue;
8999
- const local = applyMatrix$1(invertMatrix(scene.layout.matrix(id)), point);
9000
- for (let i = hits.length - 1; i >= 0; i--) {
9001
- const binding = hits[i];
9002
- if (!binding) continue;
9003
- const resolved = resolveBoardScriptHit(scene, binding.owner, binding.hit);
9004
- if (!resolved) continue;
9005
- const r = resolved.rect;
9006
- if (local.x >= r.x && local.y >= r.y && local.x <= r.x + r.width && local.y <= r.y + r.height && ("x" in binding.hit || hitTest(item, point))) return {
9007
- owner: binding.owner,
9008
- target: binding.target
9009
- };
9001
+ const ordered = [...candidates].sort((a, b) => scene.indexOf(b) - scene.indexOf(a));
9002
+ const scan = (over) => {
9003
+ for (const id of ordered) {
9004
+ const item = scene.get(id);
9005
+ if (!item || scene.opacity(id) <= 0) continue;
9006
+ let parent = item.parent;
9007
+ let clipped = false;
9008
+ for (let depth = 0; parent && depth < 64; depth++) {
9009
+ const ancestor = scene.get(parent);
9010
+ if (!ancestor) break;
9011
+ if (ancestor.type === "frame" && ancestor.props.clip && !frameContainsPoint(ancestor.frame, point)) {
9012
+ clipped = true;
9013
+ break;
9014
+ }
9015
+ parent = ancestor.parent;
9016
+ }
9017
+ if (clipped) continue;
9018
+ for (const byItem of declared) {
9019
+ const hits = byItem.get(id);
9020
+ if (!hits) continue;
9021
+ const local = applyMatrix$1(invertMatrix(scene.layout.matrix(id)), point);
9022
+ for (let i = hits.length - 1; i >= 0; i--) {
9023
+ const binding = hits[i];
9024
+ if (!binding || over && !binding.hit.over) continue;
9025
+ const resolved = resolveBoardScriptHit(scene, binding.owner, binding.hit);
9026
+ if (!resolved) continue;
9027
+ const r = resolved.rect;
9028
+ if (local.x >= r.x && local.y >= r.y && local.x <= r.x + r.width && local.y <= r.y + r.height && ("x" in binding.hit || hitTest(item, point))) return {
9029
+ owner: binding.owner,
9030
+ target: binding.target
9031
+ };
9032
+ }
9010
9033
  }
9034
+ if (over || prefixes.some((prefix) => id.startsWith(prefix))) continue;
9035
+ if (item.type === "frame" && item.props.decoration === "none") continue;
9036
+ if (hitTest(item, point)) return null;
9011
9037
  }
9012
- if (prefixes.some((prefix) => id.startsWith(prefix))) continue;
9013
- if (item.type === "frame" && item.props.decoration === "none") continue;
9014
- if (hitTest(item, point)) return null;
9015
- }
9016
- return null;
9038
+ return null;
9039
+ };
9040
+ return ([...outputs.values()].some((output) => Object.values(output.hits).some((hit) => hit.over)) ? scan(true) : null) ?? scan(false);
9017
9041
  }
9018
9042
  //#endregion
9019
9043
  //#region ../sdk/src/board/model/script-example.ts
@@ -9224,7 +9248,7 @@ function parameterKind(track) {
9224
9248
  function compileBoardTrack(animationId, id, track, targetType) {
9225
9249
  const resolved = resolveBoardProperty(targetType, track.property);
9226
9250
  if (!resolved.ok) return null;
9227
- const kind = targetType === "script" ? parameterKind(track) : resolved.spec.kind;
9251
+ const kind = targetType === "script" || track.property.startsWith("script.params.") ? parameterKind(track) : resolved.spec.kind;
9228
9252
  const times = new Float64Array(track.keyframes.length);
9229
9253
  const values = [];
9230
9254
  const eases = [];
@@ -9514,10 +9538,14 @@ function evaluateBoardAnimations(compiled, times, options = {}) {
9514
9538
  const ordered = [...groups.values()].sort((a, b) => a.path.length - b.path.length);
9515
9539
  for (const group of ordered) {
9516
9540
  const isCamera = group.target === BOARD_CAMERA_TARGET$1;
9517
- const script = isCamera ? void 0 : scripts.get(group.target) ?? compiled.document.board.scripts?.[group.target];
9541
+ const rootScript = isCamera ? void 0 : compiled.document.board.scripts?.[group.target];
9542
+ const itemScript = isCamera || rootScript || group.path[0] !== "script" ? void 0 : compiled.document.items[group.target]?.script;
9543
+ const script = rootScript || itemScript ? scripts.get(group.target) ?? rootScript ?? itemScript : void 0;
9544
+ if (group.path[0] === "script" && !itemScript) continue;
9545
+ const path = itemScript ? group.path.slice(1) : group.path;
9518
9546
  const base = isCamera || script ? void 0 : items.get(group.target) ?? compiled.document.items[group.target];
9519
9547
  if (!isCamera && !script && !base) continue;
9520
- let value = isCamera ? camera[group.path[0]] : readPath$1(script ?? base, group.path);
9548
+ let value = isCamera ? camera[path[0]] : readPath$1(script ?? base, path);
9521
9549
  let orientTrack = null;
9522
9550
  if (group.winner) {
9523
9551
  value = sampleBoardTrack(group.winner, group.winnerTime, resolveColor);
@@ -9532,7 +9560,7 @@ function evaluateBoardAnimations(compiled, times, options = {}) {
9532
9560
  continue;
9533
9561
  }
9534
9562
  if (script) {
9535
- scripts.set(group.target, writePath$1(script, group.path, value));
9563
+ scripts.set(group.target, writePath$1(script, path, value));
9536
9564
  continue;
9537
9565
  }
9538
9566
  let next = writePath$1(base, group.path, value);
@@ -9552,30 +9580,56 @@ function evaluateBoardAnimations(compiled, times, options = {}) {
9552
9580
  times: local
9553
9581
  };
9554
9582
  }
9583
+ const BOARD_SCRIPT_HISTORY_MS = 1e3 / 30;
9584
+ function boardAnimatesScriptParams(document) {
9585
+ return Object.values(document.animations).some((animation) => Object.values(animation.tracks).some((track) => /^(script\.)?params\./.test(track.property)));
9586
+ }
9555
9587
  function withBoardScripts(document, scripts) {
9588
+ if (scripts.size === 0) return document;
9556
9589
  const stored = document.board.scripts;
9557
- if (scripts.size === 0 || !stored) return document;
9558
- const next = { ...stored };
9590
+ let board = document.board;
9591
+ let items = document.items;
9559
9592
  for (const [id, script] of scripts) {
9560
- const base = stored[id];
9561
- if (base) next[id] = {
9562
- ...base,
9563
- params: script.params
9593
+ const root = stored?.[id];
9594
+ if (root) {
9595
+ if (board === document.board) board = {
9596
+ ...board,
9597
+ scripts: { ...stored }
9598
+ };
9599
+ board.scripts[id] = {
9600
+ ...root,
9601
+ params: script.params
9602
+ };
9603
+ continue;
9604
+ }
9605
+ const item = items[id];
9606
+ if (!item?.script) continue;
9607
+ if (items === document.items) items = { ...items };
9608
+ items[id] = {
9609
+ ...item,
9610
+ script: {
9611
+ ...item.script,
9612
+ params: script.params
9613
+ }
9564
9614
  };
9565
9615
  }
9566
- return {
9616
+ return board === document.board && items === document.items ? document : {
9567
9617
  ...document,
9568
- board: {
9569
- ...document.board,
9570
- scripts: next
9571
- }
9618
+ board,
9619
+ items
9572
9620
  };
9573
9621
  }
9574
9622
  function applyBoardEvaluation(document, evaluation) {
9575
9623
  const scripted = withBoardScripts(document, evaluation.scripts);
9576
9624
  if (evaluation.items.size === 0) return scripted;
9577
- const items = { ...document.items };
9578
- for (const [id, item] of evaluation.items) items[id] = item;
9625
+ const items = { ...scripted.items };
9626
+ for (const [id, item] of evaluation.items) {
9627
+ const script = scripted.items[id]?.script;
9628
+ items[id] = script && script !== document.items[id]?.script ? {
9629
+ ...item,
9630
+ script
9631
+ } : item;
9632
+ }
9579
9633
  return {
9580
9634
  ...scripted,
9581
9635
  items
@@ -20516,6 +20570,91 @@ function pointInTriangle(px, py, x1, y1, x2, y2, x3, y3) {
20516
20570
  return u >= 0 && v >= 0 && u + v < 1;
20517
20571
  }
20518
20572
  //#endregion
20573
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/alpha/alpha.frag.mjs
20574
+ var fragment$3 = "\nin vec2 vTextureCoord;\n\nout vec4 finalColor;\n\nuniform float uAlpha;\nuniform sampler2D uTexture;\n\nvoid main()\n{\n finalColor = texture(uTexture, vTextureCoord) * uAlpha;\n}\n";
20575
+ //#endregion
20576
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/alpha/alpha.wgsl.mjs
20577
+ var source$2 = "struct GlobalFilterUniforms {\n uInputSize:vec4<f32>,\n uInputPixel:vec4<f32>,\n uInputClamp:vec4<f32>,\n uOutputFrame:vec4<f32>,\n uGlobalFrame:vec4<f32>,\n uOutputTexture:vec4<f32>,\n};\n\nstruct AlphaUniforms {\n uAlpha:f32,\n};\n\n@group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;\n@group(0) @binding(1) var uTexture: texture_2d<f32>;\n@group(0) @binding(2) var uSampler : sampler;\n\n@group(1) @binding(0) var<uniform> alphaUniforms : AlphaUniforms;\n\nstruct VSOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv : vec2<f32>\n };\n\nfn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32>\n{\n var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;\n\n position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;\n position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;\n\n return vec4(position, 0.0, 1.0);\n}\n\nfn filterTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>\n{\n return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);\n}\n\nfn globalTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>\n{\n return (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw); \n}\n\nfn getSize() -> vec2<f32>\n{\n return gfu.uGlobalFrame.zw;\n}\n \n@vertex\nfn mainVertex(\n @location(0) aPosition : vec2<f32>, \n) -> VSOutput {\n return VSOutput(\n filterVertexPosition(aPosition),\n filterTextureCoord(aPosition)\n );\n}\n\n@fragment\nfn mainFragment(\n @location(0) uv: vec2<f32>,\n @builtin(position) position: vec4<f32>\n) -> @location(0) vec4<f32> {\n \n var sample = textureSample(uTexture, uSampler, uv);\n \n return sample * alphaUniforms.uAlpha;\n}";
20578
+ //#endregion
20579
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/alpha/AlphaFilter.mjs
20580
+ const _AlphaFilter = class _AlphaFilter extends Filter {
20581
+ constructor(options) {
20582
+ options = {
20583
+ ..._AlphaFilter.defaultOptions,
20584
+ ...options
20585
+ };
20586
+ const gpuProgram = GpuProgram.from({
20587
+ vertex: {
20588
+ source: source$2,
20589
+ entryPoint: "mainVertex"
20590
+ },
20591
+ fragment: {
20592
+ source: source$2,
20593
+ entryPoint: "mainFragment"
20594
+ }
20595
+ });
20596
+ const glProgram = GlProgram.from({
20597
+ vertex: vertex$2,
20598
+ fragment: fragment$3,
20599
+ name: "alpha-filter"
20600
+ });
20601
+ const { alpha, ...rest } = options;
20602
+ const alphaUniforms = new UniformGroup({ uAlpha: {
20603
+ value: alpha,
20604
+ type: "f32"
20605
+ } });
20606
+ super({
20607
+ ...rest,
20608
+ gpuProgram,
20609
+ glProgram,
20610
+ resources: { alphaUniforms }
20611
+ });
20612
+ }
20613
+ /**
20614
+ * The alpha value of the filter.
20615
+ * Controls the transparency of the filtered display object.
20616
+ * @example
20617
+ * ```ts
20618
+ * // Create filter with initial alpha
20619
+ * const filter = new AlphaFilter({ alpha: 0.5 });
20620
+ *
20621
+ * // Update alpha value dynamically
20622
+ * filter.alpha = 0.8;
20623
+ * ```
20624
+ * @default 1
20625
+ * @remarks
20626
+ * - 0 = fully transparent
20627
+ * - 1 = fully opaque
20628
+ * - Values are clamped between 0 and 1
20629
+ */
20630
+ get alpha() {
20631
+ return this.resources.alphaUniforms.uniforms.uAlpha;
20632
+ }
20633
+ set alpha(value) {
20634
+ this.resources.alphaUniforms.uniforms.uAlpha = value;
20635
+ }
20636
+ };
20637
+ /**
20638
+ * Default options for the AlphaFilter.
20639
+ * @example
20640
+ * ```ts
20641
+ * AlphaFilter.defaultOptions = {
20642
+ * alpha: 0.5, // Default alpha value
20643
+ * };
20644
+ * // Use default options
20645
+ * const filter = new AlphaFilter(); // Uses default alpha of 0.5
20646
+ * ```
20647
+ */
20648
+ _AlphaFilter.defaultOptions = {
20649
+ /**
20650
+ * Amount of alpha transparency to apply.
20651
+ * - 0 = fully transparent
20652
+ * - 1 = fully opaque (default)
20653
+ * @default 1
20654
+ */
20655
+ alpha: 1 };
20656
+ let AlphaFilter = _AlphaFilter;
20657
+ //#endregion
20519
20658
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/color-matrix/colorMatrixFilter.frag.mjs
20520
20659
  var fragment$2 = "\nin vec2 vTextureCoord;\nin vec4 vColor;\n\nout vec4 finalColor;\n\nuniform float uColorMatrix[20];\nuniform float uAlpha;\n\nuniform sampler2D uTexture;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture(uTexture, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * 0.2);\n float diff = (randomValue - 0.5) * 0.5;\n\n if (uAlpha == 0.0) {\n finalColor = color;\n return;\n }\n\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n vec4 result;\n\n result.r = (uColorMatrix[0] * color.r);\n result.r += (uColorMatrix[1] * color.g);\n result.r += (uColorMatrix[2] * color.b);\n result.r += (uColorMatrix[3] * color.a);\n result.r += uColorMatrix[4];\n\n result.g = (uColorMatrix[5] * color.r);\n result.g += (uColorMatrix[6] * color.g);\n result.g += (uColorMatrix[7] * color.b);\n result.g += (uColorMatrix[8] * color.a);\n result.g += uColorMatrix[9];\n\n result.b = (uColorMatrix[10] * color.r);\n result.b += (uColorMatrix[11] * color.g);\n result.b += (uColorMatrix[12] * color.b);\n result.b += (uColorMatrix[13] * color.a);\n result.b += uColorMatrix[14];\n\n result.a = (uColorMatrix[15] * color.r);\n result.a += (uColorMatrix[16] * color.g);\n result.a += (uColorMatrix[17] * color.b);\n result.a += (uColorMatrix[18] * color.a);\n result.a += uColorMatrix[19];\n\n vec3 rgb = mix(color.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n finalColor = vec4(rgb, result.a);\n}\n";
20521
20660
  //#endregion
@@ -31677,6 +31816,230 @@ var CanvasRenderer = class extends AbstractRenderer {
31677
31816
  }
31678
31817
  };
31679
31818
  //#endregion
31819
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/GlProgramData.mjs
31820
+ var GlProgramData = class {
31821
+ /**
31822
+ * Makes a new Pixi program.
31823
+ * @param program - webgl program
31824
+ * @param uniformData - uniforms
31825
+ */
31826
+ constructor(program, uniformData) {
31827
+ this.program = program;
31828
+ this.uniformData = uniformData;
31829
+ this.uniformGroups = {};
31830
+ this.uniformDirtyGroups = {};
31831
+ this.uniformBlockBindings = {};
31832
+ }
31833
+ /** Destroys this program. */
31834
+ destroy() {
31835
+ this.uniformData = null;
31836
+ this.uniformGroups = null;
31837
+ this.uniformDirtyGroups = null;
31838
+ this.uniformBlockBindings = null;
31839
+ this.program = null;
31840
+ }
31841
+ };
31842
+ //#endregion
31843
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/defaultValue.mjs
31844
+ function booleanArray(size) {
31845
+ const array = new Array(size);
31846
+ for (let i = 0; i < array.length; i++) array[i] = false;
31847
+ return array;
31848
+ }
31849
+ function defaultValue(type, size) {
31850
+ switch (type) {
31851
+ case "float": return 0;
31852
+ case "vec2": return new Float32Array(2 * size);
31853
+ case "vec3": return new Float32Array(3 * size);
31854
+ case "vec4": return new Float32Array(4 * size);
31855
+ case "int":
31856
+ case "uint":
31857
+ case "sampler2D":
31858
+ case "sampler2DArray": return 0;
31859
+ case "ivec2": return new Int32Array(2 * size);
31860
+ case "ivec3": return new Int32Array(3 * size);
31861
+ case "ivec4": return new Int32Array(4 * size);
31862
+ case "uvec2": return new Uint32Array(2 * size);
31863
+ case "uvec3": return new Uint32Array(3 * size);
31864
+ case "uvec4": return new Uint32Array(4 * size);
31865
+ case "bool": return false;
31866
+ case "bvec2": return booleanArray(2 * size);
31867
+ case "bvec3": return booleanArray(3 * size);
31868
+ case "bvec4": return booleanArray(4 * size);
31869
+ case "mat2": return new Float32Array([
31870
+ 1,
31871
+ 0,
31872
+ 0,
31873
+ 1
31874
+ ]);
31875
+ case "mat3": return new Float32Array([
31876
+ 1,
31877
+ 0,
31878
+ 0,
31879
+ 0,
31880
+ 1,
31881
+ 0,
31882
+ 0,
31883
+ 0,
31884
+ 1
31885
+ ]);
31886
+ case "mat4": return new Float32Array([
31887
+ 1,
31888
+ 0,
31889
+ 0,
31890
+ 0,
31891
+ 0,
31892
+ 1,
31893
+ 0,
31894
+ 0,
31895
+ 0,
31896
+ 0,
31897
+ 1,
31898
+ 0,
31899
+ 0,
31900
+ 0,
31901
+ 0,
31902
+ 1
31903
+ ]);
31904
+ }
31905
+ return null;
31906
+ }
31907
+ //#endregion
31908
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/mapType.mjs
31909
+ let GL_TABLE = null;
31910
+ const GL_TO_GLSL_TYPES = {
31911
+ FLOAT: "float",
31912
+ FLOAT_VEC2: "vec2",
31913
+ FLOAT_VEC3: "vec3",
31914
+ FLOAT_VEC4: "vec4",
31915
+ INT: "int",
31916
+ INT_VEC2: "ivec2",
31917
+ INT_VEC3: "ivec3",
31918
+ INT_VEC4: "ivec4",
31919
+ UNSIGNED_INT: "uint",
31920
+ UNSIGNED_INT_VEC2: "uvec2",
31921
+ UNSIGNED_INT_VEC3: "uvec3",
31922
+ UNSIGNED_INT_VEC4: "uvec4",
31923
+ BOOL: "bool",
31924
+ BOOL_VEC2: "bvec2",
31925
+ BOOL_VEC3: "bvec3",
31926
+ BOOL_VEC4: "bvec4",
31927
+ FLOAT_MAT2: "mat2",
31928
+ FLOAT_MAT3: "mat3",
31929
+ FLOAT_MAT4: "mat4",
31930
+ SAMPLER_2D: "sampler2D",
31931
+ INT_SAMPLER_2D: "sampler2D",
31932
+ UNSIGNED_INT_SAMPLER_2D: "sampler2D",
31933
+ SAMPLER_2D_SHADOW: "sampler2DShadow",
31934
+ SAMPLER_CUBE: "samplerCube",
31935
+ INT_SAMPLER_CUBE: "samplerCube",
31936
+ UNSIGNED_INT_SAMPLER_CUBE: "samplerCube",
31937
+ SAMPLER_CUBE_SHADOW: "samplerCubeShadow",
31938
+ SAMPLER_2D_ARRAY: "sampler2DArray",
31939
+ INT_SAMPLER_2D_ARRAY: "sampler2DArray",
31940
+ UNSIGNED_INT_SAMPLER_2D_ARRAY: "sampler2DArray",
31941
+ SAMPLER_2D_ARRAY_SHADOW: "sampler2DArrayShadow"
31942
+ };
31943
+ const GLSL_TO_VERTEX_TYPES = {
31944
+ float: "float32",
31945
+ vec2: "float32x2",
31946
+ vec3: "float32x3",
31947
+ vec4: "float32x4",
31948
+ int: "sint32",
31949
+ ivec2: "sint32x2",
31950
+ ivec3: "sint32x3",
31951
+ ivec4: "sint32x4",
31952
+ uint: "uint32",
31953
+ uvec2: "uint32x2",
31954
+ uvec3: "uint32x3",
31955
+ uvec4: "uint32x4",
31956
+ bool: "uint32",
31957
+ bvec2: "uint32x2",
31958
+ bvec3: "uint32x3",
31959
+ bvec4: "uint32x4"
31960
+ };
31961
+ function mapType(gl, type) {
31962
+ if (!GL_TABLE) {
31963
+ const typeNames = Object.keys(GL_TO_GLSL_TYPES);
31964
+ GL_TABLE = {};
31965
+ for (let i = 0; i < typeNames.length; ++i) {
31966
+ const tn = typeNames[i];
31967
+ GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn];
31968
+ }
31969
+ }
31970
+ return GL_TABLE[type];
31971
+ }
31972
+ function mapGlToVertexFormat(gl, type) {
31973
+ const typeValue = mapType(gl, type);
31974
+ return GLSL_TO_VERTEX_TYPES[typeValue] || "float32";
31975
+ }
31976
+ //#endregion
31977
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/extractAttributesFromGlProgram.mjs
31978
+ function extractAttributesFromGlProgram(program, gl, sortAttributes = false) {
31979
+ const attributes = {};
31980
+ const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
31981
+ for (let i = 0; i < totalAttributes; i++) {
31982
+ const attribData = gl.getActiveAttrib(program, i);
31983
+ if (attribData.name.startsWith("gl_")) continue;
31984
+ const format = mapGlToVertexFormat(gl, attribData.type);
31985
+ attributes[attribData.name] = {
31986
+ location: 0,
31987
+ format,
31988
+ stride: getAttributeInfoFromFormat(format).stride,
31989
+ offset: 0,
31990
+ instance: false,
31991
+ start: 0
31992
+ };
31993
+ }
31994
+ const keys = Object.keys(attributes);
31995
+ if (sortAttributes) {
31996
+ keys.sort((a, b) => a > b ? 1 : -1);
31997
+ for (let i = 0; i < keys.length; i++) {
31998
+ attributes[keys[i]].location = i;
31999
+ gl.bindAttribLocation(program, i, keys[i]);
32000
+ }
32001
+ gl.linkProgram(program);
32002
+ } else for (let i = 0; i < keys.length; i++) attributes[keys[i]].location = gl.getAttribLocation(program, keys[i]);
32003
+ return attributes;
32004
+ }
32005
+ //#endregion
32006
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/getUboData.mjs
32007
+ function getUboData(program, gl) {
32008
+ if (!gl.ACTIVE_UNIFORM_BLOCKS) return {};
32009
+ const uniformBlocks = {};
32010
+ const totalUniformsBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
32011
+ for (let i = 0; i < totalUniformsBlocks; i++) {
32012
+ const name = gl.getActiveUniformBlockName(program, i);
32013
+ uniformBlocks[name] = {
32014
+ name,
32015
+ index: gl.getUniformBlockIndex(program, name),
32016
+ size: gl.getActiveUniformBlockParameter(program, i, gl.UNIFORM_BLOCK_DATA_SIZE)
32017
+ };
32018
+ }
32019
+ return uniformBlocks;
32020
+ }
32021
+ //#endregion
32022
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/getUniformData.mjs
32023
+ function getUniformData(program, gl) {
32024
+ const uniforms = {};
32025
+ const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
32026
+ for (let i = 0; i < totalUniforms; i++) {
32027
+ const uniformData = gl.getActiveUniform(program, i);
32028
+ const name = uniformData.name.replace(/\[.*?\]$/, "");
32029
+ const isArray = !!uniformData.name.match(/\[.*?\]$/);
32030
+ const type = mapType(gl, uniformData.type);
32031
+ uniforms[name] = {
32032
+ name,
32033
+ index: i,
32034
+ type,
32035
+ size: uniformData.size,
32036
+ isArray,
32037
+ value: defaultValue(type, uniformData.size)
32038
+ };
32039
+ }
32040
+ return uniforms;
32041
+ }
32042
+ //#endregion
31680
32043
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/scene/particle-container/canvas/CanvasParticleContainerAdaptor.mjs
31681
32044
  var CanvasParticleContainerAdaptor = class {
31682
32045
  execute(particleContainerPipe, container) {
@@ -39057,7 +39420,9 @@ var BoardShadowFilter = class extends Filter {
39057
39420
  };
39058
39421
  const filtersByContainer = /* @__PURE__ */ new WeakMap();
39059
39422
  function hasBoardEffects(style) {
39060
- return Boolean(style && (style.filter || style.shadow || style.blend && style.blend !== "normal"));
39423
+ if (!style) return false;
39424
+ const shadow = style.shadow && (style.shadow.opacity ?? BOARD_SHADOW_DEFAULTS.opacity) > 0;
39425
+ return Boolean(shadow || style.filter && (style.filter.blur || colorSteps(style.filter).length) || style.blend && style.blend !== "normal");
39061
39426
  }
39062
39427
  function resolveShadow(shadow, context) {
39063
39428
  return {
@@ -39090,7 +39455,8 @@ function syncBoardEffects(container, style, context) {
39090
39455
  const filter = style?.filter;
39091
39456
  const blurs = context.blurs !== false;
39092
39457
  const blur = blurs ? filter?.blur ?? 0 : 0;
39093
- const shadow = blurs && style?.shadow ? resolveShadow(style.shadow, context) : null;
39458
+ const resolved = blurs && style?.shadow ? resolveShadow(style.shadow, context) : null;
39459
+ const shadow = resolved && resolved.alpha > 0 ? resolved : null;
39094
39460
  const colored = colorSteps(filter).length > 0;
39095
39461
  let parts = filtersByContainer.get(container);
39096
39462
  if (!colored && blur <= 0 && !shadow) {
@@ -43688,40 +44054,51 @@ async function loadBoardScriptSources(src, read, timeoutMs = 15e3) {
43688
44054
  const { init, parse } = await import("./board-kernel/lexer.js");
43689
44055
  await init;
43690
44056
  const sources = {};
43691
- const visiting = /* @__PURE__ */ new Set();
44057
+ const loading = /* @__PURE__ */ new Map();
44058
+ const edges = /* @__PURE__ */ new Map();
43692
44059
  let bytes = 0;
43693
- async function visit(path) {
43694
- if (visiting.has(path)) throw new Error(`Circular module dependency: ${path}`);
43695
- if (sources[path]) return;
43696
- if (Object.keys(sources).length + visiting.size >= 64) throw new Error("A script may load at most 64 modules.");
43697
- visiting.add(path);
43698
- let timer;
43699
- const code = await Promise.race([Promise.resolve().then(() => read(path)), new Promise((_resolve, reject) => {
43700
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Module read timed out: ${path}`)), timeoutMs);
43701
- })]).finally(() => clearTimeout(timer));
43702
- bytes += new TextEncoder().encode(code).byteLength;
43703
- if (bytes > 2e6) throw new Error("Script modules exceed the 2 MB limit.");
43704
- const [imports] = parse(code, path);
43705
- const resolved = [];
43706
- for (const entry of imports) {
43707
- if (entry.d === -2) throw new Error("import.meta is not available in Board scripts.");
43708
- if (entry.n === void 0) throw new Error("Dynamic imports must use a literal relative path.");
43709
- const dependency = resolveScriptImport(path, entry.n);
43710
- await visit(dependency);
43711
- resolved.push({
43712
- start: entry.s,
43713
- end: entry.e,
43714
- path: dependency,
43715
- dynamic: entry.d >= 0
43716
- });
43717
- }
43718
- sources[path] = {
43719
- code,
43720
- imports: resolved
43721
- };
43722
- visiting.delete(path);
44060
+ function load(path) {
44061
+ let promise = loading.get(path);
44062
+ if (promise) return promise;
44063
+ if (loading.size >= 64) throw new Error("A script may load at most 64 modules.");
44064
+ promise = (async () => {
44065
+ let timer;
44066
+ const code = await Promise.race([Promise.resolve().then(() => read(path)), new Promise((_resolve, reject) => {
44067
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Module read timed out: ${path}`)), timeoutMs);
44068
+ })]).finally(() => clearTimeout(timer));
44069
+ bytes += new TextEncoder().encode(code).byteLength;
44070
+ if (bytes > 2e6) throw new Error("Script modules exceed the 2 MB limit.");
44071
+ const [imports] = parse(code, path);
44072
+ const resolved = [];
44073
+ for (const entry of imports) {
44074
+ if (entry.d === -2) throw new Error("import.meta is not available in Board scripts.");
44075
+ if (entry.n === void 0) throw new Error("Dynamic imports must use a literal relative path.");
44076
+ resolved.push({
44077
+ start: entry.s,
44078
+ end: entry.e,
44079
+ path: resolveScriptImport(path, entry.n),
44080
+ dynamic: entry.d >= 0
44081
+ });
44082
+ }
44083
+ const dependencies = resolved.map((entry) => entry.path);
44084
+ edges.set(path, dependencies);
44085
+ if (dependencies.some((dependency) => importsReach(dependency, path))) throw new Error(`Circular module dependency: ${path}`);
44086
+ await Promise.all(dependencies.map(load));
44087
+ sources[path] = {
44088
+ code,
44089
+ imports: resolved
44090
+ };
44091
+ })();
44092
+ loading.set(path, promise);
44093
+ return promise;
43723
44094
  }
43724
- await visit(src);
44095
+ function importsReach(from, target, seen = /* @__PURE__ */ new Set()) {
44096
+ if (from === target) return true;
44097
+ if (seen.has(from)) return false;
44098
+ seen.add(from);
44099
+ return (edges.get(from) ?? []).some((next) => importsReach(next, target, seen));
44100
+ }
44101
+ await load(src);
43725
44102
  return sources;
43726
44103
  }
43727
44104
  //#endregion
@@ -43746,6 +44123,7 @@ function createScriptRuntime(module, initial, host) {
43746
44123
  let disposed = false;
43747
44124
  let stepping = false;
43748
44125
  let revision = 0;
44126
+ let sceneRevision = 0;
43749
44127
  let randomState = 2166136261;
43750
44128
  for (const char of initial.script.seed ?? initial.id) randomState = Math.imul(randomState ^ char.charCodeAt(0), 16777619) >>> 0;
43751
44129
  const parameterDefaults = Object.fromEntries(Object.entries(module.parameters ?? {}).filter(([, spec]) => spec.default !== void 0).map(([key, spec]) => [key, spec.default]));
@@ -43780,9 +44158,11 @@ function createScriptRuntime(module, initial, host) {
43780
44158
  let view = null;
43781
44159
  let hits = effects?.hits ?? {};
43782
44160
  let uniforms = effects?.uniforms;
43783
- const invalidate = () => {
44161
+ let passes = effects?.passes;
44162
+ const invalidate = (scene = true) => {
43784
44163
  if (disposed) return;
43785
44164
  revision++;
44165
+ if (scene) sceneRevision++;
43786
44166
  host.invalidate();
43787
44167
  };
43788
44168
  const present = (id, patch) => {
@@ -43857,7 +44237,7 @@ function createScriptRuntime(module, initial, host) {
43857
44237
  };
43858
44238
  },
43859
44239
  onDispose: (handler) => cleanups.push(handler),
43860
- invalidate,
44240
+ invalidate: () => invalidate(),
43861
44241
  get: (id) => input.items[id],
43862
44242
  present,
43863
44243
  scene(next, options) {
@@ -43888,7 +44268,16 @@ function createScriptRuntime(module, initial, host) {
43888
44268
  ...uniforms,
43889
44269
  ...values
43890
44270
  };
43891
- invalidate();
44271
+ invalidate(false);
44272
+ },
44273
+ passes(next) {
44274
+ if (!next || typeof next !== "object" || Object.values(next).some((on) => typeof on !== "boolean")) throw new Error("passes() takes a record of pass names and booleans.");
44275
+ if (Object.entries(next).every(([name, on]) => passes?.[name] === on)) return;
44276
+ passes = {
44277
+ ...passes,
44278
+ ...next
44279
+ };
44280
+ invalidate(false);
43892
44281
  },
43893
44282
  async commit(patch) {
43894
44283
  return await host.call("board.commit", {
@@ -43904,7 +44293,16 @@ function createScriptRuntime(module, initial, host) {
43904
44293
  call: (name, value) => host.call(name, value)
43905
44294
  }
43906
44295
  };
43907
- const setup = module.default?.(context);
44296
+ const seeded = (run) => {
44297
+ const random = Math.random;
44298
+ Math.random = context.random;
44299
+ try {
44300
+ return run();
44301
+ } finally {
44302
+ Math.random = random;
44303
+ }
44304
+ };
44305
+ const setup = seeded(() => module.default?.(context));
43908
44306
  if (typeof setup === "function") cleanups.push(setup);
43909
44307
  return {
43910
44308
  get animated() {
@@ -43915,6 +44313,7 @@ function createScriptRuntime(module, initial, host) {
43915
44313
  for (const id of Object.keys(patches)) if (!next.items[id]) {
43916
44314
  delete patches[id];
43917
44315
  revision++;
44316
+ sceneRevision++;
43918
44317
  }
43919
44318
  params = {
43920
44319
  ...parameterDefaults,
@@ -43935,10 +44334,12 @@ function createScriptRuntime(module, initial, host) {
43935
44334
  };
43936
44335
  stepping = true;
43937
44336
  try {
43938
- for (const handler of frames) {
43939
- const result = handler(frame);
43940
- if (result && typeof result.then === "function") throw new Error("onFrame() handlers must be synchronous.");
43941
- }
44337
+ seeded(() => {
44338
+ for (const handler of frames) {
44339
+ const result = handler(frame);
44340
+ if (result && typeof result.then === "function") throw new Error("onFrame() handlers must be synchronous.");
44341
+ }
44342
+ });
43942
44343
  } finally {
43943
44344
  stepping = false;
43944
44345
  }
@@ -43966,11 +44367,13 @@ function createScriptRuntime(module, initial, host) {
43966
44367
  if (event.type === "viewchange") view = event.data;
43967
44368
  const listeners = handlers.get(event.type);
43968
44369
  if (!listeners?.size) return;
43969
- for (const handler of listeners) handler(event);
44370
+ seeded(() => {
44371
+ for (const handler of listeners) handler(event);
44372
+ });
43970
44373
  invalidate();
43971
44374
  },
43972
44375
  draw(canvas) {
43973
- const result = module.draw?.(canvas, frame);
44376
+ const result = seeded(() => module.draw?.(canvas, frame));
43974
44377
  if (result && typeof result.then === "function") throw new Error("draw() must be synchronous.");
43975
44378
  },
43976
44379
  output() {
@@ -43983,13 +44386,15 @@ function createScriptRuntime(module, initial, host) {
43983
44386
  hits,
43984
44387
  shader: module.shader,
43985
44388
  uniforms,
44389
+ passes,
43986
44390
  listens: [...handlers].filter(([, callbacks]) => callbacks.size).map(([type]) => type),
43987
44391
  animated: this.animated,
43988
44392
  draws: typeof module.draw === "function",
43989
44393
  updating: frames.size > 0,
43990
44394
  frameRate: module.frameRate,
43991
44395
  pixelated: module.pixelated,
43992
- version: revision
44396
+ version: revision,
44397
+ sceneVersion: sceneRevision
43993
44398
  };
43994
44399
  },
43995
44400
  snapshot(includeEffects = true, clone = true) {
@@ -44003,7 +44408,8 @@ function createScriptRuntime(module, initial, host) {
44003
44408
  screen: layers.screen,
44004
44409
  anchor,
44005
44410
  hits,
44006
- uniforms
44411
+ uniforms,
44412
+ passes
44007
44413
  } : void 0
44008
44414
  };
44009
44415
  return clone ? structuredClone(snapshot) : snapshot;
@@ -44018,10 +44424,39 @@ function createScriptRuntime(module, initial, host) {
44018
44424
  layers.screen = {};
44019
44425
  hits = {};
44020
44426
  uniforms = void 0;
44427
+ passes = void 0;
44021
44428
  }
44022
44429
  };
44023
44430
  }
44024
44431
  //#endregion
44432
+ //#region ../sdk/src/board/model/script-calls.ts
44433
+ function layoutBoardScriptText(value) {
44434
+ const input = value;
44435
+ if (!input || typeof input.text !== "string" || input.text.length > 1e4) throw new Error("layoutText() needs text of at most 10000 characters.");
44436
+ for (const key of [
44437
+ "fontSize",
44438
+ "fontWeight",
44439
+ "lineHeight",
44440
+ "width"
44441
+ ]) if (input[key] !== void 0 && !(Number.isFinite(input[key]) && input[key] > 0)) throw new Error(`layoutText() ${key} must be a positive number.`);
44442
+ const { width, height } = layoutBoardText({
44443
+ fontSize: 24,
44444
+ fontWeight: 500,
44445
+ font: "sans",
44446
+ lineHeight: 4 / 3,
44447
+ ...input
44448
+ });
44449
+ return {
44450
+ width,
44451
+ height
44452
+ };
44453
+ }
44454
+ const BOARD_SCRIPT_EXPORT_CALLS = {
44455
+ "board.emit": () => void 0,
44456
+ "board.commit": () => false,
44457
+ "board.layoutText": layoutBoardScriptText
44458
+ };
44459
+ //#endregion
44025
44460
  //#region ../sdk/src/board/render/shader/library.ts
44026
44461
  const BOARD_SHADER_LIBRARY = {
44027
44462
  hash: `
@@ -44330,7 +44765,7 @@ function describeBoardShaderError(log, firstLine, label) {
44330
44765
  function boardShaderStages(shader, label) {
44331
44766
  const stages = shader.passes.flatMap((pass, index) => {
44332
44767
  const name = `${label} pass ${index + 1}`;
44333
- if (shader.layer === "filter") return [{
44768
+ if (boardShaderPassLayer(shader, pass) === "filter") return [{
44334
44769
  name,
44335
44770
  kind: "filter",
44336
44771
  glsl: pass.glsl
@@ -44376,6 +44811,100 @@ function checkBoardShader(shader, parameters, label) {
44376
44811
  }
44377
44812
  }
44378
44813
  //#endregion
44814
+ //#region ../sdk/src/board/render/shader/compile.ts
44815
+ const READY = {
44816
+ poll: () => true,
44817
+ cancel() {}
44818
+ };
44819
+ const COMPLETION_STATUS = 37297;
44820
+ const failures = /* @__PURE__ */ new Map();
44821
+ const parallel = /* @__PURE__ */ new WeakMap();
44822
+ function programs(renderer) {
44823
+ return renderer.shader._programDataHash ?? null;
44824
+ }
44825
+ function adopt(gl, glProgram, program, cache) {
44826
+ glProgram._attributeData = extractAttributesFromGlProgram(program, gl, false);
44827
+ glProgram._uniformData = getUniformData(program, gl);
44828
+ glProgram._uniformBlockData = getUboData(program, gl);
44829
+ const uniforms = {};
44830
+ for (const [name, data] of Object.entries(glProgram._uniformData)) uniforms[name] = {
44831
+ location: gl.getUniformLocation(program, name),
44832
+ value: defaultValue(data.type, data.size)
44833
+ };
44834
+ cache[glProgram._key] = new GlProgramData(program, uniforms);
44835
+ }
44836
+ function lineShift(raw, final) {
44837
+ return final.split("\n").length - raw.split("\n").length;
44838
+ }
44839
+ function compileBoardProgram(renderer, glProgram, source, label, wait) {
44840
+ if (renderer.type !== RendererType.WEBGL) return READY;
44841
+ const failure = failures.get(glProgram._key);
44842
+ if (failure) throw new Error(failure);
44843
+ const cache = programs(renderer);
44844
+ if (cache?.[glProgram._key]) return READY;
44845
+ const gl = renderer.gl;
44846
+ if (!parallel.has(gl)) parallel.set(gl, Boolean(gl.getExtension("KHR_parallel_shader_compile")));
44847
+ const job = {
44848
+ gl,
44849
+ program: gl.createProgram(),
44850
+ shaders: [gl.createShader(gl.VERTEX_SHADER), gl.createShader(gl.FRAGMENT_SHADER)]
44851
+ };
44852
+ const vertex = glProgram.vertex;
44853
+ const fragment = glProgram.fragment;
44854
+ const stages = [{
44855
+ shader: job.shaders[0],
44856
+ code: vertex,
44857
+ first: source.firstLine.vertex + lineShift(source.vertex, vertex),
44858
+ name: "vertex"
44859
+ }, {
44860
+ shader: job.shaders[1],
44861
+ code: fragment,
44862
+ first: source.firstLine.fragment + lineShift(source.fragment, fragment),
44863
+ name: "fragment"
44864
+ }];
44865
+ for (const { shader, code } of stages) {
44866
+ gl.shaderSource(shader, code);
44867
+ gl.compileShader(shader);
44868
+ gl.attachShader(job.program, shader);
44869
+ }
44870
+ gl.linkProgram(job.program);
44871
+ let done = false;
44872
+ const finish = () => {
44873
+ done = true;
44874
+ let error = null;
44875
+ if (!gl.getProgramParameter(job.program, gl.LINK_STATUS) && !gl.isContextLost()) {
44876
+ for (const { shader, first, name } of stages) if (!error && !gl.getShaderParameter(shader, gl.COMPILE_STATUS)) error = describeBoardShaderError(gl.getShaderInfoLog(shader) ?? "", first, `${label} (${name})`);
44877
+ error ??= `${label}: ${gl.getProgramInfoLog(job.program) ?? "the shader failed to link"}`;
44878
+ }
44879
+ for (const shader of job.shaders) gl.deleteShader(shader);
44880
+ if (error || !cache || gl.isContextLost()) {
44881
+ gl.deleteProgram(job.program);
44882
+ if (error) {
44883
+ if (failures.size > 256) failures.clear();
44884
+ failures.set(glProgram._key, error);
44885
+ throw new Error(error);
44886
+ }
44887
+ return true;
44888
+ }
44889
+ if (cache[glProgram._key]) gl.deleteProgram(job.program);
44890
+ else adopt(gl, glProgram, job.program, cache);
44891
+ return true;
44892
+ };
44893
+ if (wait || !parallel.get(gl)) {
44894
+ finish();
44895
+ return READY;
44896
+ }
44897
+ return {
44898
+ poll: () => done || (gl.getProgramParameter(job.program, COMPLETION_STATUS) === true ? finish() : false),
44899
+ cancel() {
44900
+ if (done) return;
44901
+ done = true;
44902
+ for (const shader of job.shaders) gl.deleteShader(shader);
44903
+ gl.deleteProgram(job.program);
44904
+ }
44905
+ };
44906
+ }
44907
+ //#endregion
44379
44908
  //#region ../sdk/src/board/render/shader/quad.ts
44380
44909
  function boardQuadGeometry(instanceCount = 1) {
44381
44910
  return new Geometry({
@@ -44403,14 +44932,18 @@ function boardQuadGeometry(instanceCount = 1) {
44403
44932
  instanceCount
44404
44933
  });
44405
44934
  }
44935
+ function boardGlProgram(name, source) {
44936
+ return GlProgram.from({
44937
+ name,
44938
+ vertex: source.vertex,
44939
+ fragment: source.fragment,
44940
+ preferredFragmentPrecision: "highp"
44941
+ });
44942
+ }
44406
44943
  function boardShaderMesh(name, source, resources, geometry = boardQuadGeometry()) {
44944
+ const glProgram = source instanceof GlProgram ? source : boardGlProgram(name, source);
44407
44945
  const shader = new Shader({
44408
- glProgram: GlProgram.from({
44409
- name,
44410
- vertex: source.vertex,
44411
- fragment: source.fragment,
44412
- preferredFragmentPrecision: "highp"
44413
- }),
44946
+ glProgram,
44414
44947
  resources
44415
44948
  });
44416
44949
  return {
@@ -44453,6 +44986,8 @@ const STEP_MS = 1e3 / 60;
44453
44986
  const STEPS_PER_FRAME = 8;
44454
44987
  const MAX_LAG = 60;
44455
44988
  const MAX_REPLAY = 36e3;
44989
+ const CHECKPOINT_STEPS = 600;
44990
+ const CHECKPOINTS = 6;
44456
44991
  const PIXI_TYPES = {
44457
44992
  float: "f32",
44458
44993
  int: "i32",
@@ -44467,46 +45002,6 @@ const SIZES = {
44467
45002
  vec3: 3,
44468
45003
  vec4: 4
44469
45004
  };
44470
- const compiled = /* @__PURE__ */ new Map();
44471
- function check(renderer, program, label) {
44472
- if (renderer.type !== RendererType.WEBGL) return;
44473
- const key = `${program.vertex}\u0000${program.fragment}`;
44474
- let error = compiled.get(key);
44475
- if (error === void 0) {
44476
- const gl = renderer.gl;
44477
- error = null;
44478
- const shaders = [];
44479
- const glProgram = gl.createProgram();
44480
- for (const [stage, type, source, first] of [[
44481
- "vertex",
44482
- gl.VERTEX_SHADER,
44483
- program.vertex,
44484
- program.firstLine.vertex
44485
- ], [
44486
- "fragment",
44487
- gl.FRAGMENT_SHADER,
44488
- program.fragment,
44489
- program.firstLine.fragment
44490
- ]]) {
44491
- const shader = gl.createShader(type);
44492
- if (!shader) continue;
44493
- gl.shaderSource(shader, source);
44494
- gl.compileShader(shader);
44495
- shaders.push(shader);
44496
- if (!error && !gl.getShaderParameter(shader, gl.COMPILE_STATUS) && !gl.isContextLost()) error = describeBoardShaderError(gl.getShaderInfoLog(shader) ?? "", first, `${label} (${stage})`);
44497
- gl.attachShader(glProgram, shader);
44498
- }
44499
- if (!error) {
44500
- gl.linkProgram(glProgram);
44501
- if (!gl.getProgramParameter(glProgram, gl.LINK_STATUS) && !gl.isContextLost()) error = `${label}: ${gl.getProgramInfoLog(glProgram) ?? "the shader failed to link"}`;
44502
- }
44503
- for (const shader of shaders) gl.deleteShader(shader);
44504
- gl.deleteProgram(glProgram);
44505
- if (compiled.size > 256) compiled.clear();
44506
- compiled.set(key, error);
44507
- }
44508
- if (error) throw new Error(error);
44509
- }
44510
45005
  const placing = /* @__PURE__ */ new WeakMap();
44511
45006
  function canPlaceSprites(renderer) {
44512
45007
  let supported = placing.get(renderer);
@@ -44682,8 +45177,7 @@ function seedOf(value) {
44682
45177
  function boardShaderSeed(seed) {
44683
45178
  return seedOf(seed);
44684
45179
  }
44685
- function createBoardShaderLayer(renderer, shader, parameters, label) {
44686
- const layer = shader.layer ?? "above";
45180
+ function createBoardShaderLayer(renderer, shader, parameters, label, options = {}) {
44687
45181
  const uniforms = boardShaderUniforms(shader.uniforms);
44688
45182
  const surfaces = shader.surfaces === true;
44689
45183
  const hasState = shader.state !== void 0;
@@ -44693,19 +45187,21 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44693
45187
  surfaces,
44694
45188
  state: hasState
44695
45189
  };
45190
+ const compiles = [];
44696
45191
  const program = (kind, glsl, name) => {
44697
- let built;
44698
45192
  try {
44699
- built = buildBoardShaderProgram({
45193
+ const built = buildBoardShaderProgram({
44700
45194
  ...base,
44701
45195
  kind,
44702
45196
  glsl
44703
45197
  });
45198
+ const glProgram = boardGlProgram(`board-shader-${kind}`, built);
45199
+ compiles.push(compileBoardProgram(renderer, glProgram, built, name, options.wait === true));
45200
+ return glProgram;
44704
45201
  } catch (error) {
44705
- throw new Error(`${name}: ${error instanceof Error ? error.message : String(error)}`);
45202
+ const message = error instanceof Error ? error.message : String(error);
45203
+ throw new Error(message.startsWith(name) ? message : `${name}: ${message}`);
44706
45204
  }
44707
- check(renderer, built, name);
44708
- return built;
44709
45205
  };
44710
45206
  const group = boardUniforms(parameters, uniforms);
44711
45207
  const textures = {};
@@ -44713,20 +45209,19 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44713
45209
  if (hasState) textures.uCohubState = Texture.EMPTY.source;
44714
45210
  const meshes = [];
44715
45211
  const filters = [];
44716
- const container = layer === "filter" ? null : new Container({ label: `board-shader-${label}` });
45212
+ const containers = {
45213
+ below: null,
45214
+ above: null
45215
+ };
45216
+ const area = new Rectangle();
44717
45217
  const place = canPlaceSprites(renderer);
44718
45218
  let placementsStale = true;
44719
45219
  shader.passes.forEach((pass, index) => {
44720
45220
  const name = `${label} pass ${index + 1}`;
45221
+ const layer = boardShaderPassLayer(shader, pass);
44721
45222
  if (layer === "filter") {
44722
- const built = program("filter", pass.glsl, name);
44723
45223
  const filter = new Filter({
44724
- glProgram: GlProgram.from({
44725
- name: `board-shader-filter`,
44726
- vertex: built.vertex,
44727
- fragment: built.fragment,
44728
- preferredFragmentPrecision: "highp"
44729
- }),
45224
+ glProgram: program("filter", pass.glsl, name),
44730
45225
  resources: {
44731
45226
  cohubUniforms: group,
44732
45227
  ...textures
@@ -44734,7 +45229,10 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44734
45229
  padding: 0,
44735
45230
  resolution: "inherit"
44736
45231
  });
44737
- filters.push(filter);
45232
+ filters.push({
45233
+ filter,
45234
+ pass
45235
+ });
44738
45236
  return;
44739
45237
  }
44740
45238
  const sprites = pass.sprites ?? 0;
@@ -44756,11 +45254,16 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44756
45254
  });
44757
45255
  const drawn = boardShaderMesh("board-shader", program(kind, pass.glsl, name), resources, boardQuadGeometry(Math.max(1, sprites)));
44758
45256
  drawn.mesh.blendMode = pass.blend ?? "normal";
44759
- container?.addChild(drawn.mesh);
45257
+ containers[layer] ??= new Container({ label: `board-shader-${label}-${layer}` });
45258
+ const container = containers[layer];
45259
+ container.boundsArea = area;
45260
+ container.addChild(drawn.mesh);
44760
45261
  meshes.push({
44761
45262
  ...drawn,
45263
+ pass,
44762
45264
  sprites,
44763
- placement
45265
+ placement,
45266
+ scaler: null
44764
45267
  });
44765
45268
  });
44766
45269
  let state = null;
@@ -44783,6 +45286,7 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44783
45286
  const blank = new Container();
44784
45287
  let time = 0;
44785
45288
  let quality = 1;
45289
+ let compiled = compiles.length === 0;
44786
45290
  let last = null;
44787
45291
  const stateRegion = (frame) => shader.state?.bounds ?? frame.region;
44788
45292
  function fill(target, frame, geometry, step) {
@@ -44842,9 +45346,41 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44842
45346
  }
44843
45347
  target.update();
44844
45348
  }
45349
+ const checkpoints = [];
45350
+ let surfaceKey = "";
45351
+ const copier = new Sprite();
45352
+ copier.blendMode = "none";
45353
+ const copy = (target, from, to) => {
45354
+ copier.texture = from;
45355
+ target.render({
45356
+ container: copier,
45357
+ target: to,
45358
+ clear: true,
45359
+ clearColor: [
45360
+ 0,
45361
+ 0,
45362
+ 0,
45363
+ 0
45364
+ ]
45365
+ });
45366
+ };
45367
+ const inputs = ({ time: _time, ...frame }) => JSON.stringify([frame, surfaceKey]);
45368
+ function checkpoint(target, state, key) {
45369
+ if (checkpoints.some((entry) => entry.steps === state.steps && entry.key === key)) return;
45370
+ const texture = (checkpoints.length >= CHECKPOINTS ? checkpoints.shift() : void 0)?.texture ?? boardRenderTarget(state.read.width, state.read.height, state.read.source.format);
45371
+ copy(target, state.read, texture);
45372
+ checkpoints.push({
45373
+ steps: state.steps,
45374
+ key,
45375
+ texture
45376
+ });
45377
+ }
44845
45378
  function advance(target, state, frame, catchUp) {
44846
45379
  const wanted = Math.floor(frame.time / STEP_MS);
45380
+ const key = catchUp ? inputs(frame) : "";
45381
+ let replaying = false;
44847
45382
  if (wanted < state.steps || state.steps < 0) {
45383
+ replaying = catchUp;
44848
45384
  for (const texture of [state.read, state.write]) target.render({
44849
45385
  container: blank,
44850
45386
  target: texture,
@@ -44857,6 +45393,11 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44857
45393
  ]
44858
45394
  });
44859
45395
  state.steps = Math.max(0, wanted - MAX_REPLAY);
45396
+ const resume = catchUp ? checkpoints.reduce((best, entry) => entry.key === key && entry.steps <= wanted && entry.steps > (best?.steps ?? state.steps - 1) ? entry : best, null) : null;
45397
+ if (resume) {
45398
+ copy(target, resume.texture, state.read);
45399
+ state.steps = resume.steps;
45400
+ }
44860
45401
  }
44861
45402
  if (!catchUp && wanted - state.steps > MAX_LAG) state.steps = wanted - STEPS_PER_FRAME;
44862
45403
  const limit = catchUp ? Number.POSITIVE_INFINITY : STEPS_PER_FRAME;
@@ -44877,29 +45418,66 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44877
45418
  [state.read, state.write] = [state.write, state.read];
44878
45419
  state.steps++;
44879
45420
  ran++;
45421
+ if (replaying && state.steps % CHECKPOINT_STEPS === 0) checkpoint(target, state, key);
44880
45422
  }
44881
45423
  const source = state.read.source;
44882
45424
  for (const { shader, placement } of meshes) {
44883
45425
  shader.resources.uCohubState = source;
44884
45426
  if (placement) placement.mesh.shader.resources.uCohubState = source;
44885
45427
  }
44886
- for (const filter of filters) filter.resources.uCohubState = source;
45428
+ for (const { filter } of filters) filter.resources.uCohubState = source;
44887
45429
  return {
44888
45430
  ran,
44889
45431
  behind: state.steps < wanted
44890
45432
  };
44891
45433
  }
45434
+ function shade(drawn, frame) {
45435
+ const resolution = frame.density * Math.min(1, frame.shading ?? 1);
45436
+ const blend = drawn.pass.blend ?? "normal";
45437
+ if (resolution >= frame.density * .99) {
45438
+ if (!drawn.scaler) return;
45439
+ drawn.mesh.filters = null;
45440
+ drawn.mesh.filterArea = null;
45441
+ drawn.mesh.blendMode = blend;
45442
+ drawn.scaler.destroy();
45443
+ drawn.scaler = null;
45444
+ return;
45445
+ }
45446
+ if (!drawn.scaler) {
45447
+ drawn.scaler = new AlphaFilter({
45448
+ alpha: 1,
45449
+ blendMode: blend
45450
+ });
45451
+ drawn.mesh.blendMode = "normal";
45452
+ drawn.mesh.filters = [drawn.scaler];
45453
+ drawn.mesh.filterArea = area;
45454
+ }
45455
+ drawn.scaler.resolution = resolution;
45456
+ }
44892
45457
  return {
44893
- layer,
44894
- container,
44895
- filters: layer === "filter" ? filters : null,
45458
+ below: containers.below,
45459
+ above: containers.above,
45460
+ filters: filters.length ? filters.map(({ filter }) => filter) : null,
44896
45461
  surfaces,
44897
45462
  animated: hasState,
45463
+ ready() {
45464
+ if (!compiled) compiled = compiles.every((compile) => compile.poll());
45465
+ return compiled;
45466
+ },
44898
45467
  update(frame) {
44899
45468
  if (frame.quality !== quality) {
44900
45469
  quality = frame.quality;
44901
45470
  for (const { geometry, sprites } of meshes) if (sprites) geometry.instanceCount = Math.max(1, Math.round(sprites * quality));
44902
45471
  }
45472
+ area.x = frame.region.x;
45473
+ area.y = frame.region.y;
45474
+ area.width = frame.region.width;
45475
+ area.height = frame.region.height;
45476
+ for (const drawn of meshes) {
45477
+ drawn.mesh.visible = boardShaderPassOn(drawn.pass, frame.passes);
45478
+ if (!drawn.sprites) shade(drawn, frame);
45479
+ }
45480
+ for (const { filter, pass } of filters) filter.enabled = boardShaderPassOn(pass, frame.passes);
44903
45481
  fill(group, frame, frame.region);
44904
45482
  for (const { geometry, placement } of meshes) {
44905
45483
  if (!placement) continue;
@@ -44922,7 +45500,7 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44922
45500
  behind: false
44923
45501
  };
44924
45502
  if (placementsStale || stepped.ran) {
44925
- for (const { placement } of meshes) if (placement) target.render({
45503
+ for (const { placement, mesh } of meshes) if (placement && mesh.visible) target.render({
44926
45504
  container: placement.mesh.mesh,
44927
45505
  target: placement.target,
44928
45506
  clear: true,
@@ -44937,8 +45515,12 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44937
45515
  }
44938
45516
  return stepped.behind;
44939
45517
  },
44940
- setSurfaces(texture, region) {
44941
- const shaders = [...meshes.flatMap(({ shader, placement }) => placement ? [shader, placement.mesh.shader] : [shader]), ...filters];
45518
+ rewind() {
45519
+ if (state) state.steps = -1;
45520
+ },
45521
+ setSurfaces(texture, region, key = "") {
45522
+ surfaceKey = key;
45523
+ const shaders = [...meshes.flatMap(({ shader, placement }) => placement ? [shader, placement.mesh.shader] : [shader]), ...filters.map(({ filter }) => filter)];
44942
45524
  if (state) shaders.push(state.simulate.shader);
44943
45525
  for (const target of shaders) target.resources.uCohubSurfaces = texture.source;
44944
45526
  const groups = [group, ...meshes.flatMap(({ placement }) => placement ? [placement.uniforms] : [])];
@@ -44955,18 +45537,23 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44955
45537
  placementsStale = true;
44956
45538
  },
44957
45539
  destroy() {
45540
+ for (const compile of compiles) compile.cancel();
44958
45541
  for (const drawn of meshes) {
45542
+ drawn.scaler?.destroy();
44959
45543
  destroyBoardShaderMesh(drawn);
44960
45544
  if (drawn.placement) destroyPlacement(renderer, drawn.placement);
44961
45545
  }
44962
- container?.destroy();
44963
- for (const filter of filters) filter.destroy();
45546
+ containers.below?.destroy();
45547
+ containers.above?.destroy();
45548
+ for (const { filter } of filters) filter.destroy();
44964
45549
  blank.destroy();
44965
45550
  if (state) {
44966
45551
  destroyBoardShaderMesh(state.simulate);
44967
45552
  state.read.destroy(true);
44968
45553
  state.write.destroy(true);
44969
45554
  }
45555
+ for (const { texture } of checkpoints) texture.destroy(true);
45556
+ copier.destroy();
44970
45557
  }
44971
45558
  };
44972
45559
  }
@@ -45199,6 +45786,15 @@ const LIGHT_BLENDS = /* @__PURE__ */ new Set(["screen", "add"]);
45199
45786
  const SURFACE_EDGE = 512;
45200
45787
  const SURFACE_MARGIN = .25;
45201
45788
  const SURFACE_COARSEN = 1.5;
45789
+ const SURFACE_INTERVAL_MS = 1e3 / 30;
45790
+ function grow(rect, margin) {
45791
+ return {
45792
+ x: rect.x - rect.width * margin,
45793
+ y: rect.y - rect.height * margin,
45794
+ width: rect.width * (1 + 2 * margin),
45795
+ height: rect.height * (1 + 2 * margin)
45796
+ };
45797
+ }
45202
45798
  function surfaceOutline(item) {
45203
45799
  const { width, height } = item.frame;
45204
45800
  const radius = item.style?.radius;
@@ -45225,15 +45821,10 @@ function boardSurfaceOutlines(scene, owner, world, worldToLocal, candidates) {
45225
45821
  }
45226
45822
  return outlines;
45227
45823
  }
45228
- function boardSurfaceRegion(previous, region, margin) {
45229
- if (!margin) return region;
45230
- if (previous && previous.x <= region.x && previous.y <= region.y && previous.x + previous.width >= region.x + region.width && previous.y + previous.height >= region.y + region.height && previous.width <= region.width * (1 + 2 * margin) * SURFACE_COARSEN) return previous;
45231
- return {
45232
- x: region.x - region.width * margin,
45233
- y: region.y - region.height * margin,
45234
- width: region.width * (1 + 2 * margin),
45235
- height: region.height * (1 + 2 * margin)
45236
- };
45824
+ function boardSurfaceRegion(previous, needed, margin) {
45825
+ const grown = grow(needed, margin);
45826
+ if (previous && previous.x <= needed.x && previous.y <= needed.y && previous.x + previous.width >= needed.x + needed.width && previous.y + previous.height >= needed.y + needed.height && previous.width <= grown.width * SURFACE_COARSEN && previous.height <= grown.height * SURFACE_COARSEN) return previous;
45827
+ return grown;
45237
45828
  }
45238
45829
  function parameterValues(parameters, params, color) {
45239
45830
  const values = {};
@@ -45245,18 +45836,26 @@ function parameterValues(parameters, params, color) {
45245
45836
  }
45246
45837
  return values;
45247
45838
  }
45248
- function sameOutlines(a, b) {
45839
+ function sameOutlines(a, b, tolerance) {
45249
45840
  if (a.length !== b.length) return false;
45250
45841
  for (let index = 0; index < a.length; index++) {
45251
45842
  const left = a[index];
45252
45843
  const right = b[index];
45253
45844
  if (left.length !== right.length) return false;
45254
- for (let point = 0; point < left.length; point++) if (Math.abs(left[point] - right[point]) > .001) return false;
45845
+ for (let point = 0; point < left.length; point++) if (Math.abs(left[point] - right[point]) > tolerance) return false;
45255
45846
  }
45256
45847
  return true;
45257
45848
  }
45258
- function createBoardShaderLayers() {
45849
+ function outlineHash(outlines) {
45850
+ let hash = 2166136261;
45851
+ for (const outline of outlines) for (const value of outline) hash = Math.imul(hash ^ Math.round(value * 8), 16777619) >>> 0;
45852
+ return `${outlines.length}.${hash.toString(36)}`;
45853
+ }
45854
+ function createBoardShaderLayers(options = {}) {
45855
+ const now = options.now ?? (() => performance.now());
45856
+ const interval = options.wait ? 0 : SURFACE_INTERVAL_MS;
45259
45857
  const entries = /* @__PURE__ */ new Map();
45858
+ const compiling = /* @__PURE__ */ new Map();
45260
45859
  const failed = /* @__PURE__ */ new Map();
45261
45860
  let animated = false;
45262
45861
  let pending = false;
@@ -45268,13 +45867,71 @@ function createBoardShaderLayers() {
45268
45867
  entry.layer.destroy();
45269
45868
  entry.surfaces?.destroy();
45270
45869
  }
45870
+ function dropCompiling(id) {
45871
+ compiling.get(id)?.layer.destroy();
45872
+ compiling.delete(id);
45873
+ }
45874
+ function surfaceField(entry, renderer, owner, placement, host, scene, candidates) {
45875
+ const { localToWorld } = placement;
45876
+ const region = owner.root ? boardSurfaceRegion(entry.surfaces?.region ?? null, placement.region, SURFACE_MARGIN) : placement.region;
45877
+ const corners = [
45878
+ applyMatrix$1(localToWorld, region),
45879
+ applyMatrix$1(localToWorld, {
45880
+ x: region.x + region.width,
45881
+ y: region.y + region.height
45882
+ }),
45883
+ applyMatrix$1(localToWorld, {
45884
+ x: region.x + region.width,
45885
+ y: region.y
45886
+ }),
45887
+ applyMatrix$1(localToWorld, {
45888
+ x: region.x,
45889
+ y: region.y + region.height
45890
+ })
45891
+ ];
45892
+ const xs = corners.map((point) => point.x);
45893
+ const ys = corners.map((point) => point.y);
45894
+ const world = {
45895
+ x: Math.min(...xs),
45896
+ y: Math.min(...ys),
45897
+ width: Math.max(...xs) - Math.min(...xs),
45898
+ height: Math.max(...ys) - Math.min(...ys)
45899
+ };
45900
+ const edge = Math.max(64, Math.round(SURFACE_EDGE * (owner.root ? 1.5 : 1) * host.quality));
45901
+ const key = `${[
45902
+ region.x,
45903
+ region.y,
45904
+ region.width,
45905
+ region.height,
45906
+ ...localToWorld
45907
+ ].map((n) => n.toFixed(3)).join(",")}|${edge}`;
45908
+ entry.surfaces ??= createBoardSurfaceField();
45909
+ const moved = key !== entry.surfaceKey;
45910
+ const at = now();
45911
+ if (moved || entry.surfaceScene !== scene && at - entry.surfaceAt >= interval) {
45912
+ entry.surfaceScene = scene;
45913
+ const outlines = boardSurfaceOutlines(scene, owner.id, world, invertMatrix(localToWorld), candidates?.(world));
45914
+ if (moved || !sameOutlines(outlines, entry.outlines, region.width / edge / 2)) {
45915
+ entry.surfaces.build(renderer, region, outlines, edge);
45916
+ entry.outlines = outlines;
45917
+ entry.surfaceAt = at;
45918
+ entry.surfaceSignature = `${key}|${outlineHash(outlines)}`;
45919
+ }
45920
+ entry.surfaceKey = key;
45921
+ } else if (entry.surfaceScene !== scene) pending = true;
45922
+ entry.layer.setSurfaces(entry.surfaces.texture, entry.surfaces.region, entry.surfaceSignature);
45923
+ }
45271
45924
  return {
45272
45925
  get animated() {
45273
45926
  return animated || pending;
45274
45927
  },
45275
45928
  get size() {
45276
- return entries.size;
45929
+ return entries.size + compiling.size;
45277
45930
  },
45931
+ get compiling() {
45932
+ return compiling.size > 0;
45933
+ },
45934
+ layer: (id) => entries.get(id)?.layer ?? null,
45278
45935
  sync(renderer, owners, host, scene, candidates) {
45279
45936
  const alive = /* @__PURE__ */ new Set();
45280
45937
  animated = false;
@@ -45285,31 +45942,44 @@ function createBoardShaderLayers() {
45285
45942
  if (!shader || !signature || failed.get(owner.id) === signature) continue;
45286
45943
  alive.add(owner.id);
45287
45944
  let entry = entries.get(owner.id);
45288
- if (entry && entry.signature !== signature) {
45289
- drop(owner.id, host);
45290
- entry = void 0;
45291
- }
45292
45945
  try {
45293
- if (!entry) {
45294
- entry = {
45295
- owner,
45296
- output,
45297
- signature,
45298
- layer: createBoardShaderLayer(renderer, shader, boardShaderParameters(output.parameters), owner.id),
45299
- surfaces: null,
45300
- surfaceKey: "",
45301
- surfaceScene: null,
45302
- outlines: [],
45303
- placed: false
45304
- };
45305
- entries.set(owner.id, entry);
45946
+ if (entry?.signature !== signature) {
45947
+ let next = compiling.get(owner.id);
45948
+ if (next?.signature !== signature) {
45949
+ dropCompiling(owner.id);
45950
+ next = {
45951
+ signature,
45952
+ layer: createBoardShaderLayer(renderer, shader, boardShaderParameters(output.parameters), owner.id, { wait: options.wait })
45953
+ };
45954
+ compiling.set(owner.id, next);
45955
+ }
45956
+ if (next.layer.ready()) {
45957
+ compiling.delete(owner.id);
45958
+ drop(owner.id, host);
45959
+ entry = {
45960
+ owner,
45961
+ output,
45962
+ signature,
45963
+ layer: next.layer,
45964
+ surfaces: null,
45965
+ surfaceKey: "",
45966
+ surfaceScene: null,
45967
+ surfaceAt: -Infinity,
45968
+ surfaceSignature: "",
45969
+ outlines: [],
45970
+ placed: false
45971
+ };
45972
+ entries.set(owner.id, entry);
45973
+ }
45306
45974
  }
45975
+ if (!entry) continue;
45307
45976
  entry.owner = owner;
45308
- entry.output = output;
45977
+ if (entry.signature === signature) entry.output = output;
45978
+ const drawn = entry.output;
45309
45979
  const placement = host.attach(owner, entry.layer);
45310
45980
  entry.placed = placement !== null;
45311
45981
  if (!placement) continue;
45312
- animated ||= output.animated || entry.layer.animated;
45982
+ animated ||= drawn.animated || entry.layer.animated;
45313
45983
  entry.layer.update({
45314
45984
  time: owner.time,
45315
45985
  region: placement.region,
@@ -45319,77 +45989,42 @@ function createBoardShaderLayers() {
45319
45989
  density: host.density,
45320
45990
  seed: boardShaderSeed(owner.seed),
45321
45991
  quality: host.quality,
45992
+ shading: host.shading,
45322
45993
  dark: host.dark,
45323
- params: parameterValues(output.parameters, owner.params, host.color),
45324
- uniforms: output.uniforms
45994
+ params: parameterValues(drawn.parameters, owner.params, host.color),
45995
+ uniforms: drawn.uniforms,
45996
+ passes: drawn.passes
45325
45997
  });
45326
- if (entry.layer.surfaces) {
45327
- const { localToWorld } = placement;
45328
- const margin = owner.root ? SURFACE_MARGIN : 0;
45329
- const region = boardSurfaceRegion(entry.surfaces?.region ?? null, placement.region, margin);
45330
- const corners = [
45331
- applyMatrix$1(localToWorld, region),
45332
- applyMatrix$1(localToWorld, {
45333
- x: region.x + region.width,
45334
- y: region.y + region.height
45335
- }),
45336
- applyMatrix$1(localToWorld, {
45337
- x: region.x + region.width,
45338
- y: region.y
45339
- }),
45340
- applyMatrix$1(localToWorld, {
45341
- x: region.x,
45342
- y: region.y + region.height
45343
- })
45344
- ];
45345
- const xs = corners.map((point) => point.x);
45346
- const ys = corners.map((point) => point.y);
45347
- const world = {
45348
- x: Math.min(...xs),
45349
- y: Math.min(...ys),
45350
- width: Math.max(...xs) - Math.min(...xs),
45351
- height: Math.max(...ys) - Math.min(...ys)
45352
- };
45353
- const edge = Math.max(64, Math.round(SURFACE_EDGE * (1 + 2 * margin) * host.quality));
45354
- const key = `${[
45355
- region.x,
45356
- region.y,
45357
- region.width,
45358
- region.height,
45359
- ...localToWorld
45360
- ].map((n) => n.toFixed(3)).join(",")}|${edge}`;
45361
- entry.surfaces ??= createBoardSurfaceField();
45362
- if (key !== entry.surfaceKey || entry.surfaceScene !== scene) {
45363
- entry.surfaceScene = scene;
45364
- const outlines = boardSurfaceOutlines(scene, owner.id, world, invertMatrix(localToWorld), candidates?.(world));
45365
- if (key !== entry.surfaceKey || !sameOutlines(outlines, entry.outlines)) entry.surfaces.build(renderer, region, outlines, edge);
45366
- entry.surfaceKey = key;
45367
- entry.outlines = outlines;
45368
- }
45369
- entry.layer.setSurfaces(entry.surfaces.texture, entry.surfaces.region);
45370
- }
45998
+ if (entry.layer.surfaces) surfaceField(entry, renderer, owner, placement, host, scene, candidates);
45371
45999
  } catch (error) {
45372
46000
  host.attach(owner, null);
45373
46001
  drop(owner.id, host);
46002
+ dropCompiling(owner.id);
45374
46003
  failed.set(owner.id, signature);
45375
46004
  host.fault(owner.id, error instanceof Error ? error.message : String(error));
45376
46005
  }
45377
46006
  }
45378
46007
  for (const id of [...entries.keys()]) if (!alive.has(id)) drop(id, host);
46008
+ for (const id of [...compiling.keys()]) if (!alive.has(id)) dropCompiling(id);
45379
46009
  for (const id of [...failed.keys()]) if (!owners.some((owner) => owner.id === id)) failed.delete(id);
45380
46010
  },
45381
46011
  prepare(renderer, catchUp = false) {
45382
46012
  pending = false;
45383
46013
  for (const entry of entries.values()) if (entry.placed && entry.layer.prepare(renderer, { catchUp })) pending = true;
45384
46014
  },
46015
+ rewind() {
46016
+ for (const entry of entries.values()) entry.layer.rewind();
46017
+ },
45385
46018
  detach() {
45386
46019
  for (const entry of entries.values()) {
45387
- entry.layer.container?.removeFromParent();
46020
+ entry.layer.below?.removeFromParent();
46021
+ entry.layer.above?.removeFromParent();
45388
46022
  entry.placed = false;
45389
46023
  }
45390
46024
  },
45391
46025
  destroy() {
45392
46026
  for (const id of [...entries.keys()]) drop(id);
46027
+ for (const id of [...compiling.keys()]) dropCompiling(id);
45393
46028
  failed.clear();
45394
46029
  }
45395
46030
  };
@@ -45638,7 +46273,7 @@ function createBoardExportScene(input) {
45638
46273
  }
45639
46274
  root.addChild(world);
45640
46275
  const shaderErrors = [];
45641
- const layers = input.shaders?.owners.length ? input.shaders.layers ?? createBoardShaderLayers() : null;
46276
+ const layers = input.shaders?.owners.length ? input.shaders.layers ?? createBoardShaderLayers({ wait: true }) : null;
45642
46277
  if (layers && input.shaders) {
45643
46278
  const toOutput = [
45644
46279
  input.scale,
@@ -45660,10 +46295,12 @@ function createBoardExportScene(input) {
45660
46295
  const attach = (owner, layer) => {
45661
46296
  if (!layer) return null;
45662
46297
  if (owner.root) {
45663
- if (layer.container) (layer.layer === "below" ? below : above).addChild(layer.container);
46298
+ if (layer.below) below.addChild(layer.below);
46299
+ if (layer.above) above.addChild(layer.above);
45664
46300
  if (layer.filters) {
45665
46301
  filters.set(owner.id, layer.filters);
45666
46302
  setBoardShaderFilters(world, [...filters.values()].flat());
46303
+ world.filterArea = new Rectangle(input.world.x, input.world.y, input.world.width, input.world.height);
45667
46304
  }
45668
46305
  return {
45669
46306
  region: input.world,
@@ -45683,15 +46320,25 @@ function createBoardExportScene(input) {
45683
46320
  const container = containers.get(owner.id);
45684
46321
  if (!item || !container) return null;
45685
46322
  const group = isSelfGroupedFrame(item) ? groups.get(item.id)?.group : void 0;
45686
- if (layer.layer === "below" && layer.container) container.addChildAt(layer.container, 0);
45687
- if (layer.layer === "above" && layer.container) {
46323
+ if (layer.below) container.addChildAt(layer.below, 0);
46324
+ if (layer.above) {
45688
46325
  if (group) {
45689
- positionShell(layer.container, item);
45690
- layer.container.zIndex = Number.MAX_SAFE_INTEGER;
46326
+ positionShell(layer.above, item);
46327
+ layer.above.zIndex = Number.MAX_SAFE_INTEGER;
45691
46328
  }
45692
- (group ?? container).addChild(layer.container);
46329
+ (group ?? container).addChild(layer.above);
46330
+ }
46331
+ if (layer.filters) {
46332
+ const host = group ?? container;
46333
+ setBoardShaderFilters(host, layer.filters);
46334
+ const box = group ? itemBounds(item.frame) : {
46335
+ x: 0,
46336
+ y: 0,
46337
+ width: item.frame.width,
46338
+ height: item.frame.height
46339
+ };
46340
+ host.filterArea = new Rectangle(box.x, box.y, box.width, box.height);
45693
46341
  }
45694
- if (layer.filters) setBoardShaderFilters(group ?? container, layer.filters);
45695
46342
  const localToWorld = boardItemLocalToWorld(item.frame);
45696
46343
  return {
45697
46344
  region: {
@@ -46138,8 +46785,11 @@ function createNodeScriptLanes(renderer, options) {
46138
46785
  });
46139
46786
  };
46140
46787
  Promise.resolve().then(() => {
46141
- if (!options.call) throw new Error("Capabilities are unavailable during export.");
46142
- return options.call(message.id ?? "", message.name ?? "", message.input);
46788
+ const name = message.name ?? "";
46789
+ if (options.call) return options.call(message.id ?? "", name, message.input);
46790
+ const call = BOARD_SCRIPT_EXPORT_CALLS[name];
46791
+ if (!call) throw new Error("Capabilities are unavailable during export.");
46792
+ return call(message.input);
46143
46793
  }).then((value) => answer(value), (error) => answer(void 0, error instanceof Error ? error.message : String(error)));
46144
46794
  });
46145
46795
  return worker;
@@ -46255,6 +46905,7 @@ function createNodeBoardScriptHost(renderer, options) {
46255
46905
  const textures = /* @__PURE__ */ new Map();
46256
46906
  const outputs = /* @__PURE__ */ new Map();
46257
46907
  const errors = /* @__PURE__ */ new Map();
46908
+ const sampled = /* @__PURE__ */ new Map();
46258
46909
  const key = (id, time) => `${id}|${time}`;
46259
46910
  let disposed = false;
46260
46911
  return {
@@ -46280,11 +46931,11 @@ function createNodeBoardScriptHost(renderer, options) {
46280
46931
  errors.clear();
46281
46932
  },
46282
46933
  async prepare(items, times, zoom, board, options) {
46283
- const all = Object.fromEntries(items.map(({ id, frame: _frame, ...item }) => [id, item]));
46284
- const document = {
46934
+ const documentOf = (list) => ({
46285
46935
  board: { scripts: board?.scripts },
46286
- items: all
46287
- };
46936
+ items: Object.fromEntries(list.map(({ id, frame: _frame, ...item }) => [id, item]))
46937
+ });
46938
+ const document = documentOf(items);
46288
46939
  const scripted = boardScriptAttachments(document);
46289
46940
  const alive = new Set(scripted.map(({ id }) => id));
46290
46941
  for (const id of [...lanes.assigned()]) if (!alive.has(id)) lanes.release(id);
@@ -46303,6 +46954,51 @@ function createNodeBoardScriptHost(renderer, options) {
46303
46954
  height
46304
46955
  });
46305
46956
  for (const time of times) {
46957
+ const last = sampled.get(id) ?? 0;
46958
+ if (options?.history) {
46959
+ const from = last <= time ? last : 0;
46960
+ const run = async (at, document) => {
46961
+ const script = boardScriptOf(document, id);
46962
+ if (script) await lanes.sample({
46963
+ input: scopedInput(document, {
46964
+ ...attachment,
46965
+ script
46966
+ }, {
46967
+ width,
46968
+ height
46969
+ }),
46970
+ graph,
46971
+ time: at,
46972
+ scale,
46973
+ draw: false,
46974
+ shaders: options.shaders
46975
+ });
46976
+ };
46977
+ let before = {
46978
+ at: from,
46979
+ document: options.history(from)
46980
+ };
46981
+ let previous = JSON.stringify(boardScriptOf(before.document, id)?.params);
46982
+ let ran = from;
46983
+ if (from === 0) await run(from, before.document);
46984
+ for (let at = from + BOARD_SCRIPT_HISTORY_MS; at < time; at += BOARD_SCRIPT_HISTORY_MS) {
46985
+ const sample = options.history(at);
46986
+ const key = JSON.stringify(boardScriptOf(sample, id)?.params);
46987
+ if (key !== previous) {
46988
+ if (before.at > ran) await run(before.at, before.document);
46989
+ await run(at, sample);
46990
+ previous = key;
46991
+ ran = at;
46992
+ if (disposed) return;
46993
+ }
46994
+ before = {
46995
+ at,
46996
+ document: sample
46997
+ };
46998
+ }
46999
+ if (JSON.stringify(input.script.params) !== previous && before.at > ran) await run(before.at, before.document);
47000
+ }
47001
+ sampled.set(id, time);
46306
47002
  const result = await lanes.sample({
46307
47003
  input,
46308
47004
  graph,
@@ -51831,7 +52527,7 @@ function createBoardScriptController(options) {
51831
52527
  ...options.capabilities,
51832
52528
  "board.emit": async (id, value) => {
51833
52529
  const message = value;
51834
- if (!message || typeof message.target !== "string" || typeof message.type !== "string" || !boardScriptScope(editor.document, id).has(message.target)) throw new Error("Invalid script event target.");
52530
+ if (!message || typeof message.target !== "string" || typeof message.type !== "string" || !(isBoardRootScript(editor.document, message.target) || boardScriptScope(editor.document, id).has(message.target))) throw new Error("Invalid script event target.");
51835
52531
  if (activated(id)) activations.set(message.target, activations.get(id) ?? now());
51836
52532
  host?.event(message.target, {
51837
52533
  type: message.type,
@@ -51842,29 +52538,18 @@ function createBoardScriptController(options) {
51842
52538
  const { patch, frame } = value;
51843
52539
  return commits.commit(id, patch, !frame && activated(id));
51844
52540
  },
51845
- "board.layoutText": async (_id, value) => {
51846
- const input = value;
51847
- if (!input || typeof input.text !== "string" || input.text.length > 1e4) throw new Error("layoutText() needs text of at most 10000 characters.");
51848
- for (const key of [
51849
- "fontSize",
51850
- "fontWeight",
51851
- "lineHeight",
51852
- "width"
51853
- ]) if (input[key] !== void 0 && !(Number.isFinite(input[key]) && input[key] > 0)) throw new Error(`layoutText() ${key} must be a positive number.`);
51854
- const { width, height } = layoutBoardText({
51855
- fontSize: 24,
51856
- fontWeight: 500,
51857
- font: "sans",
51858
- lineHeight: 4 / 3,
51859
- ...input
51860
- });
51861
- return {
51862
- width,
51863
- height
51864
- };
51865
- }
52541
+ "board.layoutText": async (_id, value) => layoutBoardScriptText(value)
51866
52542
  },
51867
52543
  onOutput: (id, output) => {
52544
+ const previous = outputs.get(id);
52545
+ if (output && previous && output.sceneVersion !== void 0 && output.sceneVersion === previous.sceneVersion) {
52546
+ Object.assign(previous, {
52547
+ uniforms: output.uniforms,
52548
+ passes: output.passes,
52549
+ version: output.version
52550
+ });
52551
+ return false;
52552
+ }
51868
52553
  if (output) {
51869
52554
  prepareBoardScriptOutput(editor.document, id, output);
51870
52555
  cancelPointers(id, output.hits);
@@ -52241,7 +52926,7 @@ async function createBoardScriptHarness(options) {
52241
52926
  if (!runTimers() && !runtime?.queued) break;
52242
52927
  }
52243
52928
  }
52244
- function pointerEvent(point, phase, input = {}) {
52929
+ function pointerEvent(point, phase, input = {}, pressed = phase !== "up") {
52245
52930
  const { x, y, zoom } = editor.camera;
52246
52931
  return {
52247
52932
  pointerId: input.pointerId ?? 1,
@@ -52252,14 +52937,14 @@ async function createBoardScriptHarness(options) {
52252
52937
  ctrlKey: input.ctrlKey ?? false,
52253
52938
  metaKey: input.metaKey ?? false,
52254
52939
  button: 0,
52255
- buttons: phase === "up" ? 0 : 1,
52940
+ buttons: pressed ? 1 : 0,
52256
52941
  pointerType: input.pointerType ?? "mouse",
52257
52942
  cancelled: false,
52258
52943
  pressure: .5
52259
52944
  };
52260
52945
  }
52261
- async function pointer(phase, point, input) {
52262
- const event = pointerEvent(point, phase, input);
52946
+ async function pointer(phase, point, input, pressed) {
52947
+ const event = pointerEvent(point, phase, input, pressed);
52263
52948
  if (!controller.pointer(phase, event)) {
52264
52949
  if (phase === "down") editor.pointerDown(event);
52265
52950
  else if (phase === "move") editor.pointerMove(event);
@@ -52301,6 +52986,10 @@ async function createBoardScriptHarness(options) {
52301
52986
  for (const point of rest) await pointer("move", point, input);
52302
52987
  await pointer("up", points.at(-1) ?? first, input);
52303
52988
  },
52989
+ async move(points, input) {
52990
+ for (const point of points) await pointer("move", point, input, false);
52991
+ },
52992
+ snapshot: () => controller.snapshot(),
52304
52993
  async key(type, key) {
52305
52994
  controller.key({
52306
52995
  type,
@@ -52353,4 +53042,4 @@ async function createBoardScriptHarness(options) {
52353
53042
  };
52354
53043
  }
52355
53044
  //#endregion
52356
- export { BOARD_SCRIPT_DRAWING_EXAMPLE, BOARD_SCRIPT_RAIN_EXAMPLE, boardAssetKey, boardAssetKeySource, boardFrameRegions, boardMediaRate, boardMediaSpans, boardPathTrack, boardPlacePatch, boardRegionStep, boardRenderTheme, boardScriptAttachments, boardSequence, boardSequencePatch, boardShaderParameters, boardTextureEdge, boardTexturePixels, boardTimedMedia, buildBoardScene, checkBoardShader, createBoardAnimationSampler, createBoardRenderSampler, createBoardScriptHarness, createNodeBoardRenderer, createNodeBoardScriptHost, describeBoardExportWarning, exportBoardImageBytes, hasBoardScripts, inspectBoardItems, inspectBoardScene, measureBoardText, parseBoardDocument, planBoardExport, prepareBoardExport, selectBoardExportAssets };
53045
+ export { BOARD_SCRIPT_DRAWING_EXAMPLE, BOARD_SCRIPT_RAIN_EXAMPLE, boardAnimatesScriptParams, boardAssetKey, boardAssetKeySource, boardFrameRegions, boardMediaRate, boardMediaSpans, boardPathTrack, boardPlacePatch, boardRegionStep, boardRenderTheme, boardScriptAttachments, boardSequence, boardSequencePatch, boardShaderParameters, boardTextureEdge, boardTexturePixels, boardTimedMedia, buildBoardScene, checkBoardShader, createBoardAnimationSampler, createBoardRenderSampler, createBoardScriptHarness, createNodeBoardRenderer, createNodeBoardScriptHost, describeBoardExportWarning, exportBoardImageBytes, hasBoardScripts, inspectBoardItems, inspectBoardScene, itemBounds, measureBoardText, parseBoardDocument, planBoardExport, prepareBoardExport, rectsIntersect, selectBoardExportAssets };