@neta-art/cohub-cli 10.19.0 → 10.21.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.
@@ -5947,6 +5947,7 @@ const itemEnvelope$1 = {
5947
5947
  visible: boolean().optional().describe("false hides the item and its children; key it on a timeline to show the item only for a span."),
5948
5948
  style: BoardStyleSchema$1.default({}),
5949
5949
  locked: boolean().optional(),
5950
+ autoplay: boolean().optional().describe("true shows live content as the Board opens: an app runs, a video loops muted, a 3D model renders. Ignored for other items and for a video whose props.time follows a timeline."),
5950
5951
  metadata: record(string(), unknown()).optional()
5951
5952
  };
5952
5953
  const boxed$1 = (size) => ({
@@ -7082,6 +7083,7 @@ const NOT_ANIMATABLE = /* @__PURE__ */ new Set([
7082
7083
  "parent",
7083
7084
  "z",
7084
7085
  "locked",
7086
+ "autoplay",
7085
7087
  "metadata",
7086
7088
  "script"
7087
7089
  ]);
@@ -7154,6 +7156,10 @@ function resolveBoardProperty(targetType, property) {
7154
7156
  ok: false,
7155
7157
  message: `Board scripts animate params.<name>, not ${property}`
7156
7158
  };
7159
+ if (/^script\.params\.[^.]+$/.test(property)) return {
7160
+ ok: true,
7161
+ spec: SCRIPT_PARAMETER
7162
+ };
7157
7163
  const path = property.split(".");
7158
7164
  if (path.some((segment) => !segment) || NOT_ANIMATABLE.has(path[0])) return {
7159
7165
  ok: false,
@@ -7509,6 +7515,7 @@ function validateTrack(path, animationId, value, item, animation, track, script,
7509
7515
  if (value.target === animationId || nestsInto(value.target, animationId, animation, track, state)) return [error(`${path}.target`, "ANIMATION_CYCLE", `${animationId} cannot contain itself through ${value.target}`)];
7510
7516
  } else if (script(value.target)) targetType = "script";
7511
7517
  else return [error(`${path}.target`, "TARGET_NOT_FOUND", `target ${value.target} is not an item, animation, Board script or camera`)];
7518
+ if (!keepUnknownProperty && value.property.startsWith("script.") && !item(value.target)?.script) return [error(`${path}.property`, "INVALID_PROPERTY", `${value.target} has no script to animate`)];
7512
7519
  const resolved = resolveBoardProperty(targetType, value.property);
7513
7520
  if (!resolved.ok) return keepUnknownProperty ? [] : [error(`${path}.property`, "INVALID_PROPERTY", resolved.message)];
7514
7521
  for (const [index, keyframe] of value.keyframes.entries()) {
@@ -7876,6 +7883,159 @@ function isBoardRootScript(document, id) {
7876
7883
  return Boolean(document.board?.scripts && Object.hasOwn(document.board.scripts, id));
7877
7884
  }
7878
7885
  //#endregion
7886
+ //#region ../sdk/src/board/model/json.ts
7887
+ function sameJson(a, b) {
7888
+ if (a === b) return true;
7889
+ if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
7890
+ if (Array.isArray(a) || Array.isArray(b)) {
7891
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
7892
+ for (let index = 0; index < a.length; index += 1) if (!sameJson(a[index], b[index])) return false;
7893
+ return true;
7894
+ }
7895
+ const left = a;
7896
+ const right = b;
7897
+ let members = 0;
7898
+ for (const key of Object.keys(left)) {
7899
+ if (left[key] === void 0) continue;
7900
+ members += 1;
7901
+ if (!sameJson(left[key], right[key])) return false;
7902
+ }
7903
+ for (const key of Object.keys(right)) if (right[key] !== void 0) members -= 1;
7904
+ return members === 0;
7905
+ }
7906
+ //#endregion
7907
+ //#region ../sdk/src/board/model/script-scope.ts
7908
+ const childrenByItems = /* @__PURE__ */ new WeakMap();
7909
+ const everyItem = /* @__PURE__ */ new WeakMap();
7910
+ function childIndex(items) {
7911
+ let index = childrenByItems.get(items);
7912
+ if (!index) {
7913
+ index = /* @__PURE__ */ new Map();
7914
+ for (const [id, item] of Object.entries(items)) {
7915
+ if (!item.parent) continue;
7916
+ const siblings = index.get(item.parent);
7917
+ if (siblings) siblings.push(id);
7918
+ else index.set(item.parent, [id]);
7919
+ }
7920
+ childrenByItems.set(items, index);
7921
+ }
7922
+ return index;
7923
+ }
7924
+ function boardScriptOf(document, id) {
7925
+ return isBoardRootScript(document, id) ? document.board?.scripts?.[id] : document.items[id]?.script;
7926
+ }
7927
+ function boardScriptScope(document, id) {
7928
+ if (isBoardRootScript(document, id)) {
7929
+ let all = everyItem.get(document.items);
7930
+ if (!all) {
7931
+ all = new Set(Object.keys(document.items));
7932
+ everyItem.set(document.items, all);
7933
+ }
7934
+ return all;
7935
+ }
7936
+ const item = document.items[id];
7937
+ const scope = /* @__PURE__ */ new Set([id]);
7938
+ for (const target of Object.values(item?.script?.targets ?? {})) if (document.items[target]) scope.add(target);
7939
+ if (item?.type !== "frame") return scope;
7940
+ const children = childIndex(document.items);
7941
+ const visited = /* @__PURE__ */ new Set([id]);
7942
+ const queue = [id];
7943
+ for (let depth = 0; queue.length && depth < 64; depth++) for (const parent of queue.splice(0)) for (const child of children.get(parent) ?? []) {
7944
+ if (visited.has(child)) continue;
7945
+ visited.add(child);
7946
+ scope.add(child);
7947
+ queue.push(child);
7948
+ }
7949
+ return scope;
7950
+ }
7951
+ function diffBoardScriptItems(copy, document, scope, note) {
7952
+ const changes = {};
7953
+ let changed = false;
7954
+ for (const id of scope) {
7955
+ const item = document.items[id];
7956
+ const previous = copy.get(id);
7957
+ if (!item || previous === item) continue;
7958
+ copy.set(id, item);
7959
+ if (previous && sameJson(previous, item)) continue;
7960
+ changes[id] = item;
7961
+ changed = true;
7962
+ note?.(id, previous ? "changed" : "added");
7963
+ }
7964
+ if (copy.size > scope.size) for (const id of copy.keys()) {
7965
+ if (scope.has(id)) continue;
7966
+ copy.delete(id);
7967
+ changes[id] = null;
7968
+ changed = true;
7969
+ note?.(id, "removed");
7970
+ }
7971
+ return changed ? changes : null;
7972
+ }
7973
+ function supersedes(pending, event) {
7974
+ if (pending.type !== event.type) return false;
7975
+ if (event.type === "viewchange" || event.type === "selectionchange") return true;
7976
+ if (event.type === "pointermove") return pending.pointerId === event.pointerId;
7977
+ if (event.type !== "gesture") return false;
7978
+ const a = pending.data;
7979
+ const b = event.data;
7980
+ return a.id === b.id && a.phase === "update" && b.phase === "update";
7981
+ }
7982
+ function boardScriptListens(output, event) {
7983
+ return !output || event.type === "viewchange" || output.listens.includes(event.type);
7984
+ }
7985
+ function queueBoardScriptEvent(queue, event) {
7986
+ let queued = queue.length - 1;
7987
+ while (queued >= 0 && !supersedes(queue[queued], event)) queued--;
7988
+ if (queued >= 0 && (event.type !== "pointermove" || queued === queue.length - 1)) queue.splice(queued, 1);
7989
+ if (queue.length >= 128) return false;
7990
+ queue.push(event);
7991
+ return true;
7992
+ }
7993
+ function boardScriptEmit(document, sender, input) {
7994
+ const message = input;
7995
+ if (!message || typeof message.target !== "string" || typeof message.type !== "string" || !message.type) throw new Error("emit() takes a target id and an event type.");
7996
+ const { target, type } = message;
7997
+ if (!isBoardRootScript(document, target) && !boardScriptScope(document, sender).has(target)) throw new Error(`emit() from ${sender} cannot reach ${target}: it is neither in scope nor a Board script.`);
7998
+ const depth = typeof message.depth === "number" && Number.isSafeInteger(message.depth) && message.depth > 0 ? message.depth : 1;
7999
+ if (depth > 16) throw new Error(`emit(${target}, "${type}") from ${sender} is ${depth} handlers deep, past the limit of 16: handlers keep answering each other. Emit from onFrame() to send it on the next step.`);
8000
+ return {
8001
+ target,
8002
+ event: {
8003
+ type,
8004
+ data: message.data,
8005
+ depth
8006
+ }
8007
+ };
8008
+ }
8009
+ function createBoardScriptOutbox(order) {
8010
+ let queued = [];
8011
+ let seq = 0;
8012
+ const waiting = /* @__PURE__ */ new Map();
8013
+ return {
8014
+ get size() {
8015
+ return queued.length;
8016
+ },
8017
+ push(sender, target, event) {
8018
+ const count = waiting.get(target) ?? 0;
8019
+ if (count >= 128) throw new Error(`emit(${target}, "${event.type}") from ${sender}: ${target} already has 128 events waiting.`);
8020
+ waiting.set(target, count + 1);
8021
+ queued.push({
8022
+ rank: order().get(sender) ?? Number.MAX_SAFE_INTEGER,
8023
+ seq: seq++,
8024
+ target,
8025
+ event
8026
+ });
8027
+ },
8028
+ take() {
8029
+ const batch = queued.sort((a, b) => a.rank - b.rank || a.seq - b.seq);
8030
+ queued = [];
8031
+ waiting.clear();
8032
+ const byTarget = /* @__PURE__ */ new Map();
8033
+ for (const { target, event } of batch) byTarget.set(target, [...byTarget.get(target) ?? [], event]);
8034
+ return byTarget;
8035
+ }
8036
+ };
8037
+ }
8038
+ //#endregion
7879
8039
  //#region ../sdk/src/board/model/geometry.ts
7880
8040
  function worldPoint(x, y) {
7881
8041
  return {
@@ -8016,100 +8176,13 @@ function cameraForFocus(focus, getFrame, surface, options = {}) {
8016
8176
  return rect ? cameraForRect(rect, surface, options) : null;
8017
8177
  }
8018
8178
  //#endregion
8019
- //#region ../sdk/src/board/model/json.ts
8020
- function sameJson(a, b) {
8021
- if (a === b) return true;
8022
- if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
8023
- if (Array.isArray(a) || Array.isArray(b)) {
8024
- if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
8025
- for (let index = 0; index < a.length; index += 1) if (!sameJson(a[index], b[index])) return false;
8026
- return true;
8027
- }
8028
- const left = a;
8029
- const right = b;
8030
- let members = 0;
8031
- for (const key of Object.keys(left)) {
8032
- if (left[key] === void 0) continue;
8033
- members += 1;
8034
- if (!sameJson(left[key], right[key])) return false;
8035
- }
8036
- for (const key of Object.keys(right)) if (right[key] !== void 0) members -= 1;
8037
- return members === 0;
8038
- }
8039
- //#endregion
8040
- //#region ../sdk/src/board/model/script-scope.ts
8041
- const childrenByItems = /* @__PURE__ */ new WeakMap();
8042
- const everyItem = /* @__PURE__ */ new WeakMap();
8043
- function childIndex(items) {
8044
- let index = childrenByItems.get(items);
8045
- if (!index) {
8046
- index = /* @__PURE__ */ new Map();
8047
- for (const [id, item] of Object.entries(items)) {
8048
- if (!item.parent) continue;
8049
- const siblings = index.get(item.parent);
8050
- if (siblings) siblings.push(id);
8051
- else index.set(item.parent, [id]);
8052
- }
8053
- childrenByItems.set(items, index);
8054
- }
8055
- return index;
8056
- }
8057
- function boardScriptOf(document, id) {
8058
- return isBoardRootScript(document, id) ? document.board?.scripts?.[id] : document.items[id]?.script;
8059
- }
8060
- function boardScriptScope(document, id) {
8061
- if (isBoardRootScript(document, id)) {
8062
- let all = everyItem.get(document.items);
8063
- if (!all) {
8064
- all = new Set(Object.keys(document.items));
8065
- everyItem.set(document.items, all);
8066
- }
8067
- return all;
8068
- }
8069
- const item = document.items[id];
8070
- const scope = /* @__PURE__ */ new Set([id]);
8071
- for (const target of Object.values(item?.script?.targets ?? {})) if (document.items[target]) scope.add(target);
8072
- if (item?.type !== "frame") return scope;
8073
- const children = childIndex(document.items);
8074
- const visited = /* @__PURE__ */ new Set([id]);
8075
- const queue = [id];
8076
- for (let depth = 0; queue.length && depth < 64; depth++) for (const parent of queue.splice(0)) for (const child of children.get(parent) ?? []) {
8077
- if (visited.has(child)) continue;
8078
- visited.add(child);
8079
- scope.add(child);
8080
- queue.push(child);
8081
- }
8082
- return scope;
8083
- }
8084
- function diffBoardScriptItems(copy, document, scope, note) {
8085
- const changes = {};
8086
- let changed = false;
8087
- for (const id of scope) {
8088
- const item = document.items[id];
8089
- const previous = copy.get(id);
8090
- if (!item || previous === item) continue;
8091
- copy.set(id, item);
8092
- if (previous && sameJson(previous, item)) continue;
8093
- changes[id] = item;
8094
- changed = true;
8095
- note?.(id, previous ? "changed" : "added");
8096
- }
8097
- if (copy.size > scope.size) for (const id of copy.keys()) {
8098
- if (scope.has(id)) continue;
8099
- copy.delete(id);
8100
- changes[id] = null;
8101
- changed = true;
8102
- note?.(id, "removed");
8103
- }
8104
- return changed ? changes : null;
8105
- }
8106
- //#endregion
8107
8179
  //#region ../sdk/src/board/model/shader.ts
8108
8180
  const BOARD_SHADER_LIMITS = {
8109
- passes: 8,
8181
+ passes: 16,
8110
8182
  source: 65536,
8111
8183
  sprites: 65536,
8112
8184
  stateEdge: 1024,
8185
+ texel: 1024,
8113
8186
  uniformSlots: 128
8114
8187
  };
8115
8188
  const COMPONENTS = {
@@ -8148,6 +8221,12 @@ function boardShaderUniformValue(uniform, value) {
8148
8221
  while (list.length < size) list.push(0);
8149
8222
  return list;
8150
8223
  }
8224
+ function boardShaderPassLayer(shader, pass) {
8225
+ return pass.layer ?? shader.layer ?? "above";
8226
+ }
8227
+ function boardShaderPassOn(pass, states) {
8228
+ return (pass.name !== void 0 ? states?.[pass.name] : void 0) ?? pass.enabled ?? true;
8229
+ }
8151
8230
  function boardShaderParameters(parameters) {
8152
8231
  const result = [];
8153
8232
  for (const [name, spec] of Object.entries(parameters ?? {})) {
@@ -8169,13 +8248,26 @@ function validateBoardShader(shader) {
8169
8248
  if (value.layer !== void 0 && !BOARD_SHADER_LAYERS.includes(value.layer)) throw new Error(`shader.layer must be ${BOARD_SHADER_LAYERS.join(", ")}.`);
8170
8249
  if (value.surfaces !== void 0 && typeof value.surfaces !== "boolean") throw new Error("shader.surfaces must be a boolean.");
8171
8250
  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.`);
8251
+ const names = /* @__PURE__ */ new Set();
8172
8252
  for (const pass of value.passes) {
8173
8253
  if (!pass || typeof pass.glsl !== "string" || !pass.glsl.trim()) throw new Error("Each shader pass needs glsl source.");
8174
8254
  if (pass.glsl.length > BOARD_SHADER_LIMITS.source) throw new Error("A shader pass exceeds 64 KB of source.");
8255
+ if (pass.layer !== void 0 && !BOARD_SHADER_LAYERS.includes(pass.layer)) throw new Error(`A pass layer must be ${BOARD_SHADER_LAYERS.join(", ")}.`);
8175
8256
  if (pass.sprites !== void 0) {
8176
8257
  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}.`);
8177
- if (value.layer === "filter") throw new Error("Filter passes draw over the owner's box; they cannot draw sprites.");
8258
+ if (boardShaderPassLayer(value, pass) === "filter") throw new Error("Filter passes draw over the owner's box; they cannot draw sprites.");
8259
+ }
8260
+ if (pass.texel !== void 0) {
8261
+ if (typeof pass.texel !== "number" || !(pass.texel > 0 && pass.texel <= BOARD_SHADER_LIMITS.texel)) throw new Error(`texel must be a number above 0 and up to ${BOARD_SHADER_LIMITS.texel}.`);
8262
+ if (pass.sprites !== void 0 || boardShaderPassLayer(value, pass) === "filter") throw new Error("texel shades a pass over its box; sprite and filter passes cannot take it.");
8263
+ }
8264
+ if (pass.name !== void 0) {
8265
+ if (typeof pass.name !== "string" || !IDENTIFIER.test(pass.name)) throw new Error(`Invalid pass name: ${String(pass.name)}`);
8266
+ if (names.has(pass.name)) throw new Error(`Pass names must be unique: ${pass.name}`);
8267
+ names.add(pass.name);
8178
8268
  }
8269
+ if (pass.enabled !== void 0 && typeof pass.enabled !== "boolean") throw new Error("A pass's enabled must be a boolean.");
8270
+ if (pass.enabled === false && pass.name === void 0) throw new Error("A pass that starts off needs a name to turn it on.");
8179
8271
  if (pass.blend !== void 0 && !BOARD_SHADER_BLENDS.includes(pass.blend)) throw new Error(`blend must be ${BOARD_SHADER_BLENDS.join(", ")}.`);
8180
8272
  }
8181
8273
  boardShaderUniforms(value.uniforms);
@@ -8213,6 +8305,33 @@ function parseBoardItem(value) {
8213
8305
  if (!parsed.ok) throw new Error(parsed.diagnostics[0]?.message ?? "Invalid script item.");
8214
8306
  return parsed.item;
8215
8307
  }
8308
+ function presentItem(base, patch) {
8309
+ return presentTransform(base, patch) ?? parseBoardItem(mergePatch(base, patch));
8310
+ }
8311
+ function presentTransform(base, patch) {
8312
+ const next = { ...base };
8313
+ for (const key in patch) {
8314
+ const value = patch[key];
8315
+ if (key === "position") {
8316
+ if (!value || typeof value !== "object") return null;
8317
+ const { x = base.position.x, y = base.position.y, ...rest } = value;
8318
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
8319
+ for (const _ in rest) return null;
8320
+ next.position = {
8321
+ x,
8322
+ y
8323
+ };
8324
+ continue;
8325
+ }
8326
+ if (key === "rotation" || key === "z") {
8327
+ if (!Number.isFinite(value)) return null;
8328
+ } else if (key === "opacity") {
8329
+ if (typeof value !== "number" || !(value >= 0 && value <= 1)) return null;
8330
+ } else if (key !== "visible" || typeof value !== "boolean") return null;
8331
+ next[key] = value;
8332
+ }
8333
+ return next;
8334
+ }
8216
8335
  const DISPLAY_FIELDS = /* @__PURE__ */ new Set([
8217
8336
  "position",
8218
8337
  "size",
@@ -8368,7 +8487,7 @@ function prepareBoardScriptOutput(document, owner, output) {
8368
8487
  const base = document.items[id];
8369
8488
  if (base && scope.has(id)) presented.set(id, {
8370
8489
  base,
8371
- item: parseBoardItem(mergePatch(base, patch))
8490
+ item: presentItem(base, patch)
8372
8491
  });
8373
8492
  }
8374
8493
  const prefix = scriptTemporaryPrefix(owner);
@@ -8400,7 +8519,7 @@ function composeBoardScriptItems(document, scene, outputs, incoming = /* @__PURE
8400
8519
  if (current.base !== base) {
8401
8520
  current = {
8402
8521
  base,
8403
- item: parseBoardItem(mergePatch(base, output.patches[id]))
8522
+ item: presentItem(base, output.patches[id] ?? {})
8404
8523
  };
8405
8524
  prepared.presented.set(id, current);
8406
8525
  }
@@ -8641,7 +8760,7 @@ function parameterKind(track) {
8641
8760
  function compileBoardTrack(animationId, id, track, targetType) {
8642
8761
  const resolved = resolveBoardProperty(targetType, track.property);
8643
8762
  if (!resolved.ok) return null;
8644
- const kind = targetType === "script" ? parameterKind(track) : resolved.spec.kind;
8763
+ const kind = targetType === "script" || track.property.startsWith("script.params.") ? parameterKind(track) : resolved.spec.kind;
8645
8764
  const times = new Float64Array(track.keyframes.length);
8646
8765
  const values = [];
8647
8766
  const eases = [];
@@ -8931,10 +9050,14 @@ function evaluateBoardAnimations(compiled, times, options = {}) {
8931
9050
  const ordered = [...groups.values()].sort((a, b) => a.path.length - b.path.length);
8932
9051
  for (const group of ordered) {
8933
9052
  const isCamera = group.target === BOARD_CAMERA_TARGET$1;
8934
- const script = isCamera ? void 0 : scripts.get(group.target) ?? compiled.document.board.scripts?.[group.target];
9053
+ const rootScript = isCamera ? void 0 : compiled.document.board.scripts?.[group.target];
9054
+ const itemScript = isCamera || rootScript || group.path[0] !== "script" ? void 0 : compiled.document.items[group.target]?.script;
9055
+ const script = rootScript || itemScript ? scripts.get(group.target) ?? rootScript ?? itemScript : void 0;
9056
+ if (group.path[0] === "script" && !itemScript) continue;
9057
+ const path = itemScript ? group.path.slice(1) : group.path;
8935
9058
  const base = isCamera || script ? void 0 : items.get(group.target) ?? compiled.document.items[group.target];
8936
9059
  if (!isCamera && !script && !base) continue;
8937
- let value = isCamera ? camera[group.path[0]] : readPath(script ?? base, group.path);
9060
+ let value = isCamera ? camera[path[0]] : readPath(script ?? base, path);
8938
9061
  let orientTrack = null;
8939
9062
  if (group.winner) {
8940
9063
  value = sampleBoardTrack(group.winner, group.winnerTime, resolveColor);
@@ -8949,7 +9072,7 @@ function evaluateBoardAnimations(compiled, times, options = {}) {
8949
9072
  continue;
8950
9073
  }
8951
9074
  if (script) {
8952
- scripts.set(group.target, writePath(script, group.path, value));
9075
+ scripts.set(group.target, writePath(script, path, value));
8953
9076
  continue;
8954
9077
  }
8955
9078
  let next = writePath(base, group.path, value);
@@ -8969,30 +9092,62 @@ function evaluateBoardAnimations(compiled, times, options = {}) {
8969
9092
  times: local
8970
9093
  };
8971
9094
  }
9095
+ const BOARD_SCRIPT_HISTORY_MS = 1e3 / 30;
9096
+ function boardScriptParamsKey(document) {
9097
+ const params = [];
9098
+ for (const script of Object.values(document.board.scripts ?? {})) params.push(script.params);
9099
+ for (const item of Object.values(document.items)) if (item.script) params.push(item.script.params);
9100
+ return JSON.stringify(params);
9101
+ }
9102
+ function boardAnimatesScriptParams(document) {
9103
+ return Object.values(document.animations).some((animation) => Object.values(animation.tracks).some((track) => /^(script\.)?params\./.test(track.property)));
9104
+ }
8972
9105
  function withBoardScripts(document, scripts) {
9106
+ if (scripts.size === 0) return document;
8973
9107
  const stored = document.board.scripts;
8974
- if (scripts.size === 0 || !stored) return document;
8975
- const next = { ...stored };
9108
+ let board = document.board;
9109
+ let items = document.items;
8976
9110
  for (const [id, script] of scripts) {
8977
- const base = stored[id];
8978
- if (base) next[id] = {
8979
- ...base,
8980
- params: script.params
9111
+ const root = stored?.[id];
9112
+ if (root) {
9113
+ if (board === document.board) board = {
9114
+ ...board,
9115
+ scripts: { ...stored }
9116
+ };
9117
+ board.scripts[id] = {
9118
+ ...root,
9119
+ params: script.params
9120
+ };
9121
+ continue;
9122
+ }
9123
+ const item = items[id];
9124
+ if (!item?.script) continue;
9125
+ if (items === document.items) items = { ...items };
9126
+ items[id] = {
9127
+ ...item,
9128
+ script: {
9129
+ ...item.script,
9130
+ params: script.params
9131
+ }
8981
9132
  };
8982
9133
  }
8983
- return {
9134
+ return board === document.board && items === document.items ? document : {
8984
9135
  ...document,
8985
- board: {
8986
- ...document.board,
8987
- scripts: next
8988
- }
9136
+ board,
9137
+ items
8989
9138
  };
8990
9139
  }
8991
9140
  function applyBoardEvaluation(document, evaluation) {
8992
9141
  const scripted = withBoardScripts(document, evaluation.scripts);
8993
9142
  if (evaluation.items.size === 0) return scripted;
8994
- const items = { ...document.items };
8995
- for (const [id, item] of evaluation.items) items[id] = item;
9143
+ const items = { ...scripted.items };
9144
+ for (const [id, item] of evaluation.items) {
9145
+ const script = scripted.items[id]?.script;
9146
+ items[id] = script && script !== document.items[id]?.script ? {
9147
+ ...item,
9148
+ script
9149
+ } : item;
9150
+ }
8996
9151
  return {
8997
9152
  ...scripted,
8998
9153
  items
@@ -9887,9 +10042,10 @@ function resolveRegion(scene, region) {
9887
10042
  };
9888
10043
  const rect = itemBounds(frame.frame);
9889
10044
  return {
9890
- items: scene.items.filter((item) => item.id !== region.id && visible(item, rect)),
10045
+ items: scene.items.filter((item) => item.id === region.id || visible(item, rect)),
9891
10046
  rect,
9892
- padding: 0
10047
+ padding: 0,
10048
+ page: region.id
9893
10049
  };
9894
10050
  }
9895
10051
  case "rect": {
@@ -9927,7 +10083,26 @@ function planBoardExport(input) {
9927
10083
  width: Math.max(1, Math.floor(world.width * scale)),
9928
10084
  height: Math.max(1, Math.floor(world.height * scale)),
9929
10085
  items: resolved.items,
9930
- clamped: scale < safeRequest - 1e-6
10086
+ clamped: scale < safeRequest - 1e-6,
10087
+ ...resolved.page ? { page: resolved.page } : {}
10088
+ };
10089
+ }
10090
+ function boardExportView(plan) {
10091
+ const { world, scale, width, height } = plan;
10092
+ return {
10093
+ camera: {
10094
+ x: -world.x * scale,
10095
+ y: -world.y * scale,
10096
+ zoom: scale
10097
+ },
10098
+ width,
10099
+ height,
10100
+ safeRect: {
10101
+ x: 0,
10102
+ y: 0,
10103
+ width,
10104
+ height
10105
+ }
9931
10106
  };
9932
10107
  }
9933
10108
  //#endregion
@@ -28153,15 +28328,15 @@ var init_defaultFilter_vert = __esmMin((() => {
28153
28328
  }));
28154
28329
  //#endregion
28155
28330
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/passthrough/passthrough.frag.mjs
28156
- var fragment$3;
28331
+ var fragment$4;
28157
28332
  var init_passthrough_frag = __esmMin((() => {
28158
- fragment$3 = "in vec2 vTextureCoord;\nout vec4 finalColor;\nuniform sampler2D uTexture;\nvoid main() {\n finalColor = texture(uTexture, vTextureCoord);\n}\n";
28333
+ fragment$4 = "in vec2 vTextureCoord;\nout vec4 finalColor;\nuniform sampler2D uTexture;\nvoid main() {\n finalColor = texture(uTexture, vTextureCoord);\n}\n";
28159
28334
  }));
28160
28335
  //#endregion
28161
28336
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/passthrough/passthrough.wgsl.mjs
28162
- var source$2;
28337
+ var source$3;
28163
28338
  var init_passthrough_wgsl = __esmMin((() => {
28164
- 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\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\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\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) -> @location(0) vec4<f32> {\n return textureSample(uTexture, uSampler, uv);\n}\n";
28339
+ source$3 = "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\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\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\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) -> @location(0) vec4<f32> {\n return textureSample(uTexture, uSampler, uv);\n}\n";
28165
28340
  }));
28166
28341
  //#endregion
28167
28342
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/passthrough/PassthroughFilter.mjs
@@ -28177,18 +28352,18 @@ var init_PassthroughFilter = __esmMin((() => {
28177
28352
  constructor() {
28178
28353
  const gpuProgram = GpuProgram.from({
28179
28354
  vertex: {
28180
- source: source$2,
28355
+ source: source$3,
28181
28356
  entryPoint: "mainVertex"
28182
28357
  },
28183
28358
  fragment: {
28184
- source: source$2,
28359
+ source: source$3,
28185
28360
  entryPoint: "mainFragment"
28186
28361
  },
28187
28362
  name: "passthrough-filter"
28188
28363
  });
28189
28364
  const glProgram = GlProgram.from({
28190
28365
  vertex: vertex$2,
28191
- fragment: fragment$3,
28366
+ fragment: fragment$4,
28192
28367
  name: "passthrough-filter"
28193
28368
  });
28194
28369
  super({
@@ -32496,9 +32671,9 @@ var init_BatcherPipe = __esmMin((() => {
32496
32671
  }));
32497
32672
  //#endregion
32498
32673
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/mask/mask.frag.mjs
32499
- var fragment$2;
32674
+ var fragment$3;
32500
32675
  var init_mask_frag = __esmMin((() => {
32501
- fragment$2 = "in vec2 vMaskCoord;\nin vec2 vTextureCoord;\n\nuniform sampler2D uTexture;\nuniform sampler2D uMaskTexture;\n\nuniform float uAlpha;\nuniform vec4 uMaskClamp;\nuniform float uInverse;\nuniform float uChannel;\n\nout vec4 finalColor;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(uMaskClamp.x, vMaskCoord.x) +\n step(uMaskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, uMaskClamp.z) +\n step(vMaskCoord.y, uMaskClamp.w));\n\n // TODO look into why this is needed\n float npmAlpha = uAlpha;\n vec4 original = texture(uTexture, vTextureCoord);\n vec4 masky = texture(uMaskTexture, vMaskCoord);\n\n float a;\n if (uChannel == 1.0) {\n a = masky.a * npmAlpha * clip;\n } else {\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n a = alphaMul * masky.r * npmAlpha * clip;\n }\n\n if (uInverse == 1.0) {\n a = 1.0 - a;\n }\n\n finalColor = original * a;\n}\n";
32676
+ fragment$3 = "in vec2 vMaskCoord;\nin vec2 vTextureCoord;\n\nuniform sampler2D uTexture;\nuniform sampler2D uMaskTexture;\n\nuniform float uAlpha;\nuniform vec4 uMaskClamp;\nuniform float uInverse;\nuniform float uChannel;\n\nout vec4 finalColor;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(uMaskClamp.x, vMaskCoord.x) +\n step(uMaskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, uMaskClamp.z) +\n step(vMaskCoord.y, uMaskClamp.w));\n\n // TODO look into why this is needed\n float npmAlpha = uAlpha;\n vec4 original = texture(uTexture, vTextureCoord);\n vec4 masky = texture(uMaskTexture, vMaskCoord);\n\n float a;\n if (uChannel == 1.0) {\n a = masky.a * npmAlpha * clip;\n } else {\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n a = alphaMul * masky.r * npmAlpha * clip;\n }\n\n if (uInverse == 1.0) {\n a = 1.0 - a;\n }\n\n finalColor = original * a;\n}\n";
32502
32677
  }));
32503
32678
  //#endregion
32504
32679
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/mask/mask.vert.mjs
@@ -32508,9 +32683,9 @@ var init_mask_vert = __esmMin((() => {
32508
32683
  }));
32509
32684
  //#endregion
32510
32685
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/mask/mask.wgsl.mjs
32511
- var source$1;
32686
+ var source$2;
32512
32687
  var init_mask_wgsl = __esmMin((() => {
32513
- source$1 = "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 MaskUniforms {\n uFilterMatrix:mat3x3<f32>,\n uMaskClamp:vec4<f32>,\n uAlpha:f32,\n uInverse:f32,\n uChannel: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> filterUniforms : MaskUniforms;\n@group(1) @binding(1) var uMaskTexture: texture_2d<f32>;\n\nstruct VSOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv : vec2<f32>,\n @location(1) filterUv : 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 getFilterCoord(aPosition:vec2<f32> ) -> vec2<f32>\n{\n return ( filterUniforms.uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0) ).xy;\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 getFilterCoord(aPosition)\n );\n}\n\n@fragment\nfn mainFragment(\n @location(0) uv: vec2<f32>,\n @location(1) filterUv: vec2<f32>,\n @builtin(position) position: vec4<f32>\n) -> @location(0) vec4<f32> {\n\n var maskClamp = filterUniforms.uMaskClamp;\n var uAlpha = filterUniforms.uAlpha;\n\n var clip = step(3.5,\n step(maskClamp.x, filterUv.x) +\n step(maskClamp.y, filterUv.y) +\n step(filterUv.x, maskClamp.z) +\n step(filterUv.y, maskClamp.w));\n\n var mask = textureSample(uMaskTexture, uSampler, filterUv);\n var source = textureSample(uTexture, uSampler, uv);\n\n var a: f32;\n if (filterUniforms.uChannel == 1.0) {\n a = mask.a * uAlpha * clip;\n } else {\n var alphaMul = 1.0 - uAlpha * (1.0 - mask.a);\n a = alphaMul * mask.r * uAlpha * clip;\n }\n\n if (filterUniforms.uInverse == 1.0) {\n a = 1.0 - a;\n }\n\n return source * a;\n}\n";
32688
+ 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 MaskUniforms {\n uFilterMatrix:mat3x3<f32>,\n uMaskClamp:vec4<f32>,\n uAlpha:f32,\n uInverse:f32,\n uChannel: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> filterUniforms : MaskUniforms;\n@group(1) @binding(1) var uMaskTexture: texture_2d<f32>;\n\nstruct VSOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv : vec2<f32>,\n @location(1) filterUv : 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 getFilterCoord(aPosition:vec2<f32> ) -> vec2<f32>\n{\n return ( filterUniforms.uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0) ).xy;\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 getFilterCoord(aPosition)\n );\n}\n\n@fragment\nfn mainFragment(\n @location(0) uv: vec2<f32>,\n @location(1) filterUv: vec2<f32>,\n @builtin(position) position: vec4<f32>\n) -> @location(0) vec4<f32> {\n\n var maskClamp = filterUniforms.uMaskClamp;\n var uAlpha = filterUniforms.uAlpha;\n\n var clip = step(3.5,\n step(maskClamp.x, filterUv.x) +\n step(maskClamp.y, filterUv.y) +\n step(filterUv.x, maskClamp.z) +\n step(filterUv.y, maskClamp.w));\n\n var mask = textureSample(uMaskTexture, uSampler, filterUv);\n var source = textureSample(uTexture, uSampler, uv);\n\n var a: f32;\n if (filterUniforms.uChannel == 1.0) {\n a = mask.a * uAlpha * clip;\n } else {\n var alphaMul = 1.0 - uAlpha * (1.0 - mask.a);\n a = alphaMul * mask.r * uAlpha * clip;\n }\n\n if (filterUniforms.uInverse == 1.0) {\n a = 1.0 - a;\n }\n\n return source * a;\n}\n";
32514
32689
  }));
32515
32690
  //#endregion
32516
32691
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/mask/MaskFilter.mjs
@@ -32555,17 +32730,17 @@ var init_MaskFilter = __esmMin((() => {
32555
32730
  });
32556
32731
  const gpuProgram = GpuProgram.from({
32557
32732
  vertex: {
32558
- source: source$1,
32733
+ source: source$2,
32559
32734
  entryPoint: "mainVertex"
32560
32735
  },
32561
32736
  fragment: {
32562
- source: source$1,
32737
+ source: source$2,
32563
32738
  entryPoint: "mainFragment"
32564
32739
  }
32565
32740
  });
32566
32741
  const glProgram = GlProgram.from({
32567
32742
  vertex: vertex$1,
32568
- fragment: fragment$2,
32743
+ fragment: fragment$3,
32569
32744
  name: "mask-filter"
32570
32745
  });
32571
32746
  super({
@@ -51013,6 +51188,96 @@ var init_getCanvasFillStyle = __esmMin((() => {
51013
51188
  PRECISION = 1e5;
51014
51189
  }));
51015
51190
  //#endregion
51191
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/alpha/alpha.frag.mjs
51192
+ var fragment$2 = "\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";
51193
+ //#endregion
51194
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/alpha/alpha.wgsl.mjs
51195
+ var source$1 = "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}";
51196
+ //#endregion
51197
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/alpha/AlphaFilter.mjs
51198
+ init_GlProgram();
51199
+ init_GpuProgram();
51200
+ init_UniformGroup();
51201
+ init_Filter();
51202
+ init_defaultFilter_vert();
51203
+ const _AlphaFilter = class _AlphaFilter extends Filter {
51204
+ constructor(options) {
51205
+ options = {
51206
+ ..._AlphaFilter.defaultOptions,
51207
+ ...options
51208
+ };
51209
+ const gpuProgram = GpuProgram.from({
51210
+ vertex: {
51211
+ source: source$1,
51212
+ entryPoint: "mainVertex"
51213
+ },
51214
+ fragment: {
51215
+ source: source$1,
51216
+ entryPoint: "mainFragment"
51217
+ }
51218
+ });
51219
+ const glProgram = GlProgram.from({
51220
+ vertex: vertex$2,
51221
+ fragment: fragment$2,
51222
+ name: "alpha-filter"
51223
+ });
51224
+ const { alpha, ...rest } = options;
51225
+ const alphaUniforms = new UniformGroup({ uAlpha: {
51226
+ value: alpha,
51227
+ type: "f32"
51228
+ } });
51229
+ super({
51230
+ ...rest,
51231
+ gpuProgram,
51232
+ glProgram,
51233
+ resources: { alphaUniforms }
51234
+ });
51235
+ }
51236
+ /**
51237
+ * The alpha value of the filter.
51238
+ * Controls the transparency of the filtered display object.
51239
+ * @example
51240
+ * ```ts
51241
+ * // Create filter with initial alpha
51242
+ * const filter = new AlphaFilter({ alpha: 0.5 });
51243
+ *
51244
+ * // Update alpha value dynamically
51245
+ * filter.alpha = 0.8;
51246
+ * ```
51247
+ * @default 1
51248
+ * @remarks
51249
+ * - 0 = fully transparent
51250
+ * - 1 = fully opaque
51251
+ * - Values are clamped between 0 and 1
51252
+ */
51253
+ get alpha() {
51254
+ return this.resources.alphaUniforms.uniforms.uAlpha;
51255
+ }
51256
+ set alpha(value) {
51257
+ this.resources.alphaUniforms.uniforms.uAlpha = value;
51258
+ }
51259
+ };
51260
+ /**
51261
+ * Default options for the AlphaFilter.
51262
+ * @example
51263
+ * ```ts
51264
+ * AlphaFilter.defaultOptions = {
51265
+ * alpha: 0.5, // Default alpha value
51266
+ * };
51267
+ * // Use default options
51268
+ * const filter = new AlphaFilter(); // Uses default alpha of 0.5
51269
+ * ```
51270
+ */
51271
+ _AlphaFilter.defaultOptions = {
51272
+ /**
51273
+ * Amount of alpha transparency to apply.
51274
+ * - 0 = fully transparent
51275
+ * - 1 = fully opaque (default)
51276
+ * @default 1
51277
+ */
51278
+ alpha: 1 };
51279
+ let AlphaFilter = _AlphaFilter;
51280
+ //#endregion
51016
51281
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/color-matrix/colorMatrixFilter.frag.mjs
51017
51282
  var fragment$1 = "\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";
51018
51283
  //#endregion
@@ -56051,6 +56316,11 @@ init_Filter();
56051
56316
  init_Matrix();
56052
56317
  init_Rectangle();
56053
56318
  init_GlProgram();
56319
+ init_GlProgramData();
56320
+ init_defaultValue();
56321
+ init_extractAttributesFromGlProgram();
56322
+ init_getUboData();
56323
+ init_getUniformData();
56054
56324
  init_Geometry();
56055
56325
  init_RenderTarget();
56056
56326
  init_Shader();
@@ -62162,6 +62432,7 @@ function shaderPasses() {
62162
62432
  return passes;
62163
62433
  }
62164
62434
  const TEXELS_PER_DEVIATION = 4;
62435
+ const SAMPLED_TEXELS_PER_DEVIATION = 8;
62165
62436
  const MAX_HALVINGS = 5;
62166
62437
  function gaussian(filters, input, output, deviation, clear, first) {
62167
62438
  const { horizontal, vertical, copy } = shaderPasses();
@@ -62207,6 +62478,7 @@ var BoardBlurFilter = class extends Filter {
62207
62478
  this.radius = radius;
62208
62479
  this.deviation = radius * zoom;
62209
62480
  this.padding = Math.ceil(radius * 3 * zoom);
62481
+ this.resolution = this.deviation > SAMPLED_TEXELS_PER_DEVIATION ? SAMPLED_TEXELS_PER_DEVIATION / this.deviation : "inherit";
62210
62482
  this.css = `blur(${radius * zoom}px)`;
62211
62483
  }
62212
62484
  apply(filters, input, output, clearMode) {
@@ -62271,7 +62543,9 @@ var BoardShadowFilter = class extends Filter {
62271
62543
  };
62272
62544
  const filtersByContainer = /* @__PURE__ */ new WeakMap();
62273
62545
  function hasBoardEffects(style) {
62274
- return Boolean(style && (style.filter || style.shadow || style.blend && style.blend !== "normal"));
62546
+ if (!style) return false;
62547
+ const shadow = style.shadow && (style.shadow.opacity ?? BOARD_SHADOW_DEFAULTS.opacity) > 0;
62548
+ return Boolean(shadow || style.filter && (style.filter.blur || colorSteps(style.filter).length) || style.blend && style.blend !== "normal");
62275
62549
  }
62276
62550
  function resolveShadow(shadow, context) {
62277
62551
  return {
@@ -62304,7 +62578,8 @@ function syncBoardEffects(container, style, context) {
62304
62578
  const filter = style?.filter;
62305
62579
  const blurs = context.blurs !== false;
62306
62580
  const blur = blurs ? filter?.blur ?? 0 : 0;
62307
- const shadow = blurs && style?.shadow ? resolveShadow(style.shadow, context) : null;
62581
+ const resolved = blurs && style?.shadow ? resolveShadow(style.shadow, context) : null;
62582
+ const shadow = resolved && resolved.alpha > 0 ? resolved : null;
62308
62583
  const colored = colorSteps(filter).length > 0;
62309
62584
  let parts = filtersByContainer.get(container);
62310
62585
  if (!colored && blur <= 0 && !shadow) {
@@ -62492,6 +62767,27 @@ function syncFrameGroup(entry, item, context) {
62492
62767
  function syncBoardItemEffects(container, item, context) {
62493
62768
  syncBoardEffects(container, item.type === "frame" ? void 0 : item.style, context);
62494
62769
  }
62770
+ const shaderClips = /* @__PURE__ */ new WeakMap();
62771
+ function clipFrameShaderLayer(layer, item) {
62772
+ const entry = shaderClips.get(layer);
62773
+ if (!isClippingFrame(item)) {
62774
+ if (!entry) return;
62775
+ layer.mask = null;
62776
+ entry.mask.destroy();
62777
+ shaderClips.delete(layer);
62778
+ return;
62779
+ }
62780
+ const { width, height } = item.frame;
62781
+ const sig = `${width},${height}`;
62782
+ if (entry?.sig === sig) return;
62783
+ const mask = entry?.mask ?? layer.addChild(new Graphics());
62784
+ mask.clear().rect(0, 0, width, height).fill(16777215);
62785
+ layer.mask = mask;
62786
+ shaderClips.set(layer, {
62787
+ mask,
62788
+ sig
62789
+ });
62790
+ }
62495
62791
  //#endregion
62496
62792
  //#region ../sdk/src/board/render/audio-waveform.ts
62497
62793
  const DEFAULT_BARS = 44;
@@ -63224,10 +63520,12 @@ function sync$13(container, item, context) {
63224
63520
  const failed = Boolean(key && !texture && context.hasError(key));
63225
63521
  const detailed = boardCardDetailed(context.zoom);
63226
63522
  const elevation = cardElevation(context, item.id);
63523
+ const covered = context.covered?.(item.id) ?? false;
63227
63524
  const sig = [
63228
63525
  key ?? "",
63229
63526
  texture?.uid ?? "none",
63230
63527
  failed,
63528
+ covered,
63231
63529
  width,
63232
63530
  height,
63233
63531
  elevation,
@@ -63248,7 +63546,11 @@ function sync$13(container, item, context) {
63248
63546
  elevation
63249
63547
  });
63250
63548
  if (texture && parts.sprite.texture !== texture) parts.sprite.texture = texture;
63251
- parts.sprite.visible = Boolean(texture);
63549
+ parts.sprite.visible = Boolean(texture) && !covered;
63550
+ if (covered) {
63551
+ parts.chrome.clear();
63552
+ return;
63553
+ }
63252
63554
  if (texture) {
63253
63555
  const inset = Math.min(width, height) * INSET_RATIO;
63254
63556
  const fitted = containRect(width - inset * 2, height - inset * 2, texture.width, texture.height);
@@ -63357,6 +63659,7 @@ const PLAY_HIT = {
63357
63659
  cursor: "pointer"
63358
63660
  };
63359
63661
  function mediaPlayHit(item, point, context) {
63662
+ if (context.covered?.(item.id) || context.mediaTexture?.(item.id)) return null;
63360
63663
  const key = context.assetKey(item);
63361
63664
  return boardMediaActionAt(item, point, context.zoom, {
63362
63665
  materialized: true,
@@ -64251,9 +64554,12 @@ function sync$8(container, item, context) {
64251
64554
  const alpha = (style.stroke ? 1 : .55) * itemAlpha(context, style.stroke);
64252
64555
  const radius = style.radius ?? 4;
64253
64556
  const strokeWidth = style.strokeWidth ?? 1.5;
64254
- const decorated = props.decoration !== "none";
64557
+ const page = context.page === item.id;
64558
+ const decorated = props.decoration !== "none" && (!page || style.fill !== void 0);
64559
+ const outlined = decorated && !page;
64255
64560
  const visualSig = [
64256
64561
  props.decoration,
64562
+ page,
64257
64563
  frame.width,
64258
64564
  frame.height,
64259
64565
  fill,
@@ -64274,7 +64580,7 @@ function sync$8(container, item, context) {
64274
64580
  });
64275
64581
  const pattern = dashPattern(style.dash, strokeWidth);
64276
64582
  const trim = style.trim ?? 1;
64277
- if (decorated && strokeWidth > 0 && trim > 0) {
64583
+ if (outlined && strokeWidth > 0 && trim > 0) {
64278
64584
  if (pattern || trim < 1) tracePolyline(parts.box, trimPolyline(roundRectPoints(frame.width, frame.height, radius), trim), pattern);
64279
64585
  else parts.box.roundRect(0, 0, frame.width, frame.height, radius);
64280
64586
  parts.box.stroke({
@@ -64286,7 +64592,7 @@ function sync$8(container, item, context) {
64286
64592
  });
64287
64593
  }
64288
64594
  }
64289
- parts.label.visible = decorated;
64595
+ parts.label.visible = outlined;
64290
64596
  const title = locked ? `🔒 ${props.label}`.trim() : props.label;
64291
64597
  const labelColor = style.stroke ? baseStroke : context.palette.muted;
64292
64598
  const size = context.style.frameLabelSize;
@@ -65389,7 +65695,8 @@ function sync$3(container, item, context) {
65389
65695
  parts.assetKey = key;
65390
65696
  if (key) context.acquireTexture(key, item);
65391
65697
  }
65392
- const texture = key ? context.getTexture(key) : null;
65698
+ const live = context.mediaTexture?.(item.id) ?? null;
65699
+ const texture = live ?? (key ? context.getTexture(key) : null);
65393
65700
  const previewFailed = Boolean(key && !texture && context.hasError(key));
65394
65701
  const artifact = featuredTaskArtifact(snapshot.artifacts);
65395
65702
  const kind = previewKindFor(artifact);
@@ -65497,7 +65804,7 @@ function sync$3(container, item, context) {
65497
65804
  height: Math.max(1, frame.height - 24 - bottomInset)
65498
65805
  }, context.colors.brand.stroke);
65499
65806
  }
65500
- if (full && (artifact?.type === "audio" || artifact?.type === "video" && texture)) drawPlayBadge(parts.previewArt, frame, context);
65807
+ if (full && (artifact?.type === "audio" || artifact?.type === "video" && texture && !live)) drawPlayBadge(parts.previewArt, frame, context);
65501
65808
  if (surface) {
65502
65809
  const markY = frame.y + frame.height / 2 - (full && label ? 18 : 0);
65503
65810
  drawStateMark(parts.previewArt, surface, frame.x + frame.width / 2, markY, surface === "failed" ? color : context.colors.neutral.stroke);
@@ -66061,7 +66368,7 @@ function sync(container, item, context) {
66061
66368
  } : context.style);
66062
66369
  }
66063
66370
  parts.chrome.clear();
66064
- if (boardCardDetailed(context.zoom) && item.props.time === void 0) drawMediaPlayKey(parts.chrome, screen.x + screen.width / 2, screen.y + screen.height / 2, Math.min(18, Math.min(screen.width, screen.height) * .16), context);
66371
+ if (boardCardDetailed(context.zoom) && !live && item.props.time === void 0) drawMediaPlayKey(parts.chrome, screen.x + screen.width / 2, screen.y + screen.height / 2, Math.min(18, Math.min(screen.width, screen.height) * .16), context);
66065
66372
  }
66066
66373
  function drawFilmRails(graphics, width, height, rail, hole) {
66067
66374
  const size = Math.min(FILM_HOLE, rail * .45);
@@ -66467,6 +66774,7 @@ const itemEnvelope = {
66467
66774
  visible: boolean().optional().describe("false hides the item and its children; key it on a timeline to show the item only for a span."),
66468
66775
  style: BoardStyleSchema.default({}),
66469
66776
  locked: boolean().optional(),
66777
+ autoplay: boolean().optional().describe("true shows live content as the Board opens: an app runs, a video loops muted, a 3D model renders. Ignored for other items and for a video whose props.time follows a timeline."),
66470
66778
  metadata: record(string(), unknown()).optional()
66471
66779
  };
66472
66780
  const boxed = (size) => ({
@@ -67044,65 +67352,118 @@ function resolveScriptImport(from, specifier) {
67044
67352
  } else parts.push(part);
67045
67353
  }
67046
67354
  const path = parts.join("/");
67047
- if (!isSafeBoardSourcePath(path) || !/\.m?js$/.test(path)) throw new Error(`Invalid module path: ${path}`);
67355
+ if (!isSafeBoardSourcePath(path) || !/\.(m?js|json)$/.test(path)) throw new Error(`Invalid module path: ${path}`);
67048
67356
  return path;
67049
67357
  }
67358
+ function isBoardScriptJson(path) {
67359
+ return path.endsWith(".json");
67360
+ }
67050
67361
  async function loadBoardScriptSources(src, read, timeoutMs = 15e3) {
67051
67362
  if (!isSafeBoardSourcePath(src) || !/\.m?js$/.test(src)) throw new Error("Invalid script entry path.");
67052
67363
  const { init, parse } = await Promise.resolve().then(() => (init_lexer(), lexer_exports));
67053
67364
  await init;
67054
67365
  const sources = {};
67055
- const visiting = /* @__PURE__ */ new Set();
67366
+ const loading = /* @__PURE__ */ new Map();
67367
+ const edges = /* @__PURE__ */ new Map();
67056
67368
  let bytes = 0;
67057
- async function visit(path) {
67058
- if (visiting.has(path)) throw new Error(`Circular module dependency: ${path}`);
67059
- if (sources[path]) return;
67060
- if (Object.keys(sources).length + visiting.size >= 64) throw new Error("A script may load at most 64 modules.");
67061
- visiting.add(path);
67062
- let timer;
67063
- const code = await Promise.race([Promise.resolve().then(() => read(path)), new Promise((_resolve, reject) => {
67064
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Module read timed out: ${path}`)), timeoutMs);
67065
- })]).finally(() => clearTimeout(timer));
67066
- bytes += new TextEncoder().encode(code).byteLength;
67067
- if (bytes > 2e6) throw new Error("Script modules exceed the 2 MB limit.");
67068
- const [imports] = parse(code, path);
67069
- const resolved = [];
67070
- for (const entry of imports) {
67071
- if (entry.d === -2) throw new Error("import.meta is not available in Board scripts.");
67072
- if (entry.n === void 0) throw new Error("Dynamic imports must use a literal relative path.");
67073
- const dependency = resolveScriptImport(path, entry.n);
67074
- await visit(dependency);
67075
- resolved.push({
67076
- start: entry.s,
67077
- end: entry.e,
67078
- path: dependency,
67079
- dynamic: entry.d >= 0
67080
- });
67081
- }
67082
- sources[path] = {
67083
- code,
67084
- imports: resolved
67085
- };
67086
- visiting.delete(path);
67369
+ function load(path) {
67370
+ let promise = loading.get(path);
67371
+ if (promise) return promise;
67372
+ if (loading.size >= 64) throw new Error("A script may load at most 64 modules.");
67373
+ promise = (async () => {
67374
+ let timer;
67375
+ const code = await Promise.race([Promise.resolve().then(() => read(path)), new Promise((_resolve, reject) => {
67376
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Module read timed out: ${path}`)), timeoutMs);
67377
+ })]).finally(() => clearTimeout(timer));
67378
+ bytes += new TextEncoder().encode(code).byteLength;
67379
+ if (bytes > 2e6) throw new Error("Script modules exceed the 2 MB limit.");
67380
+ if (isBoardScriptJson(path)) {
67381
+ try {
67382
+ JSON.parse(code);
67383
+ } catch {
67384
+ throw new Error(`${path} is not valid JSON.`);
67385
+ }
67386
+ sources[path] = {
67387
+ code,
67388
+ imports: []
67389
+ };
67390
+ return;
67391
+ }
67392
+ const [imports] = parse(code, path);
67393
+ const resolved = [];
67394
+ for (const entry of imports) {
67395
+ if (entry.d === -2) throw new Error("import.meta is not available in Board scripts.");
67396
+ if (entry.n === void 0) throw new Error("Dynamic imports must use a literal relative path.");
67397
+ const typed = entry.d >= 0 ? entry.a >= 0 && /\btype\s*:\s*["']json["']/.test(code.slice(entry.a, entry.se)) : Boolean(entry.at?.some(([key, value]) => key === "type" && value === "json"));
67398
+ if (typed !== isBoardScriptJson(entry.n)) throw new Error(typed ? `Only .json files import with type "json": ${entry.n}` : `Import ${entry.n} with { type: "json" }.`);
67399
+ resolved.push({
67400
+ start: entry.s,
67401
+ end: entry.e,
67402
+ path: resolveScriptImport(path, entry.n),
67403
+ dynamic: entry.d >= 0
67404
+ });
67405
+ }
67406
+ const dependencies = resolved.map((entry) => entry.path);
67407
+ edges.set(path, dependencies);
67408
+ if (dependencies.some((dependency) => importsReach(dependency, path))) throw new Error(`Circular module dependency: ${path}`);
67409
+ await Promise.all(dependencies.map(load));
67410
+ sources[path] = {
67411
+ code,
67412
+ imports: resolved
67413
+ };
67414
+ })();
67415
+ loading.set(path, promise);
67416
+ return promise;
67417
+ }
67418
+ function importsReach(from, target, seen = /* @__PURE__ */ new Set()) {
67419
+ if (from === target) return true;
67420
+ if (seen.has(from)) return false;
67421
+ seen.add(from);
67422
+ return (edges.get(from) ?? []).some((next) => importsReach(next, target, seen));
67087
67423
  }
67088
- await visit(src);
67424
+ await load(src);
67089
67425
  return sources;
67090
67426
  }
67091
- function scriptModuleUrls(sources) {
67427
+ function scriptModuleUrls(sources, shared = /* @__PURE__ */ new Map()) {
67092
67428
  const urls = {};
67429
+ const owned = [];
67430
+ const held = [];
67093
67431
  for (const [path, source] of Object.entries(sources)) {
67432
+ if (path.endsWith(".json")) {
67433
+ const key = `${path}\n${source.code}`;
67434
+ let json = shared.get(key);
67435
+ if (!json) {
67436
+ json = {
67437
+ url: URL.createObjectURL(new Blob([source.code], { type: "application/json" })),
67438
+ users: 0
67439
+ };
67440
+ shared.set(key, json);
67441
+ }
67442
+ json.users++;
67443
+ held.push(key);
67444
+ urls[path] = json.url;
67445
+ continue;
67446
+ }
67094
67447
  let code = source.code;
67095
67448
  for (const entry of [...source.imports].reverse()) {
67096
67449
  const url = urls[entry.path];
67097
67450
  if (!url) throw new Error(`Unresolved module: ${entry.path}`);
67098
67451
  code = code.slice(0, entry.start) + (entry.dynamic ? JSON.stringify(url) : url) + code.slice(entry.end);
67099
67452
  }
67100
- urls[path] = URL.createObjectURL(new Blob([`${code}\n//# sourceURL=cohub-script/${path.split("/").map(encodeURIComponent).join("/")}`], { type: "text/javascript" }));
67453
+ const url = URL.createObjectURL(new Blob([`${code}\n//# sourceURL=cohub-script/${path.split("/").map(encodeURIComponent).join("/")}`], { type: "text/javascript" }));
67454
+ urls[path] = url;
67455
+ owned.push(url);
67101
67456
  }
67102
67457
  return {
67103
67458
  urls,
67104
67459
  dispose: () => {
67105
- for (const url of Object.values(urls)) URL.revokeObjectURL(url);
67460
+ for (const url of owned) URL.revokeObjectURL(url);
67461
+ for (const key of held) {
67462
+ const json = shared.get(key);
67463
+ if (!json || --json.users > 0) continue;
67464
+ URL.revokeObjectURL(json.url);
67465
+ shared.delete(key);
67466
+ }
67106
67467
  }
67107
67468
  };
67108
67469
  }
@@ -67138,7 +67499,9 @@ function createScriptRuntime(module, initial, host) {
67138
67499
  let input = initial;
67139
67500
  let disposed = false;
67140
67501
  let stepping = false;
67502
+ let depth = 0;
67141
67503
  let revision = 0;
67504
+ let sceneRevision = 0;
67142
67505
  let randomState = 2166136261;
67143
67506
  for (const char of initial.script.seed ?? initial.id) randomState = Math.imul(randomState ^ char.charCodeAt(0), 16777619) >>> 0;
67144
67507
  const parameterDefaults = Object.fromEntries(Object.entries(module.parameters ?? {}).filter(([, spec]) => spec.default !== void 0).map(([key, spec]) => [key, spec.default]));
@@ -67173,9 +67536,11 @@ function createScriptRuntime(module, initial, host) {
67173
67536
  let view = null;
67174
67537
  let hits = effects?.hits ?? {};
67175
67538
  let uniforms = effects?.uniforms;
67176
- const invalidate = () => {
67539
+ let passes = effects?.passes;
67540
+ const invalidate = (scene = true) => {
67177
67541
  if (disposed) return;
67178
67542
  revision++;
67543
+ if (scene) sceneRevision++;
67179
67544
  host.invalidate();
67180
67545
  };
67181
67546
  const present = (id, patch) => {
@@ -67210,7 +67575,8 @@ function createScriptRuntime(module, initial, host) {
67210
67575
  await host.call("board.emit", {
67211
67576
  target,
67212
67577
  type,
67213
- data
67578
+ data,
67579
+ depth: depth + 1
67214
67580
  });
67215
67581
  },
67216
67582
  get items() {
@@ -67250,7 +67616,7 @@ function createScriptRuntime(module, initial, host) {
67250
67616
  };
67251
67617
  },
67252
67618
  onDispose: (handler) => cleanups.push(handler),
67253
- invalidate,
67619
+ invalidate: () => invalidate(),
67254
67620
  get: (id) => input.items[id],
67255
67621
  present,
67256
67622
  scene(next, options) {
@@ -67281,7 +67647,16 @@ function createScriptRuntime(module, initial, host) {
67281
67647
  ...uniforms,
67282
67648
  ...values
67283
67649
  };
67284
- invalidate();
67650
+ invalidate(false);
67651
+ },
67652
+ passes(next) {
67653
+ 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.");
67654
+ if (Object.entries(next).every(([name, on]) => passes?.[name] === on)) return;
67655
+ passes = {
67656
+ ...passes,
67657
+ ...next
67658
+ };
67659
+ invalidate(false);
67285
67660
  },
67286
67661
  async commit(patch) {
67287
67662
  return await host.call("board.commit", {
@@ -67297,7 +67672,16 @@ function createScriptRuntime(module, initial, host) {
67297
67672
  call: (name, value) => host.call(name, value)
67298
67673
  }
67299
67674
  };
67300
- const setup = module.default?.(context);
67675
+ const seeded = (run) => {
67676
+ const random = Math.random;
67677
+ Math.random = context.random;
67678
+ try {
67679
+ return run();
67680
+ } finally {
67681
+ Math.random = random;
67682
+ }
67683
+ };
67684
+ const setup = seeded(() => module.default?.(context));
67301
67685
  if (typeof setup === "function") cleanups.push(setup);
67302
67686
  return {
67303
67687
  get animated() {
@@ -67308,6 +67692,7 @@ function createScriptRuntime(module, initial, host) {
67308
67692
  for (const id of Object.keys(patches)) if (!next.items[id]) {
67309
67693
  delete patches[id];
67310
67694
  revision++;
67695
+ sceneRevision++;
67311
67696
  }
67312
67697
  params = {
67313
67698
  ...parameterDefaults,
@@ -67328,10 +67713,12 @@ function createScriptRuntime(module, initial, host) {
67328
67713
  };
67329
67714
  stepping = true;
67330
67715
  try {
67331
- for (const handler of frames) {
67332
- const result = handler(frame);
67333
- if (result && typeof result.then === "function") throw new Error("onFrame() handlers must be synchronous.");
67334
- }
67716
+ seeded(() => {
67717
+ for (const handler of frames) {
67718
+ const result = handler(frame);
67719
+ if (result && typeof result.then === "function") throw new Error("onFrame() handlers must be synchronous.");
67720
+ }
67721
+ });
67335
67722
  } finally {
67336
67723
  stepping = false;
67337
67724
  }
@@ -67359,11 +67746,19 @@ function createScriptRuntime(module, initial, host) {
67359
67746
  if (event.type === "viewchange") view = event.data;
67360
67747
  const listeners = handlers.get(event.type);
67361
67748
  if (!listeners?.size) return;
67362
- for (const handler of listeners) handler(event);
67749
+ const outer = depth;
67750
+ depth = event.depth ?? 0;
67751
+ try {
67752
+ seeded(() => {
67753
+ for (const handler of listeners) handler(event);
67754
+ });
67755
+ } finally {
67756
+ depth = outer;
67757
+ }
67363
67758
  invalidate();
67364
67759
  },
67365
67760
  draw(canvas) {
67366
- const result = module.draw?.(canvas, frame);
67761
+ const result = seeded(() => module.draw?.(canvas, frame));
67367
67762
  if (result && typeof result.then === "function") throw new Error("draw() must be synchronous.");
67368
67763
  },
67369
67764
  output() {
@@ -67376,13 +67771,15 @@ function createScriptRuntime(module, initial, host) {
67376
67771
  hits,
67377
67772
  shader: module.shader,
67378
67773
  uniforms,
67774
+ passes,
67379
67775
  listens: [...handlers].filter(([, callbacks]) => callbacks.size).map(([type]) => type),
67380
67776
  animated: this.animated,
67381
67777
  draws: typeof module.draw === "function",
67382
67778
  updating: frames.size > 0,
67383
67779
  frameRate: module.frameRate,
67384
67780
  pixelated: module.pixelated,
67385
- version: revision
67781
+ version: revision,
67782
+ sceneVersion: sceneRevision
67386
67783
  };
67387
67784
  },
67388
67785
  snapshot(includeEffects = true, clone = true) {
@@ -67396,7 +67793,8 @@ function createScriptRuntime(module, initial, host) {
67396
67793
  screen: layers.screen,
67397
67794
  anchor,
67398
67795
  hits,
67399
- uniforms
67796
+ uniforms,
67797
+ passes
67400
67798
  } : void 0
67401
67799
  };
67402
67800
  return clone ? structuredClone(snapshot) : snapshot;
@@ -67411,6 +67809,7 @@ function createScriptRuntime(module, initial, host) {
67411
67809
  layers.screen = {};
67412
67810
  hits = {};
67413
67811
  uniforms = void 0;
67812
+ passes = void 0;
67414
67813
  }
67415
67814
  };
67416
67815
  }
@@ -67418,6 +67817,7 @@ function createScriptRuntime(module, initial, host) {
67418
67817
  //#region ../sdk/src/board/render/script-sandbox.ts
67419
67818
  function scriptAgent(runtimeFactory, applyDelta, moduleUrls, load) {
67420
67819
  const graphs = /* @__PURE__ */ new Map();
67820
+ const json = /* @__PURE__ */ new Map();
67421
67821
  const instances = /* @__PURE__ */ new Map();
67422
67822
  const calls = /* @__PURE__ */ new Map();
67423
67823
  let callId = 0;
@@ -67431,6 +67831,16 @@ function scriptAgent(runtimeFactory, applyDelta, moduleUrls, load) {
67431
67831
  announced = false;
67432
67832
  send({ kind: "idle" });
67433
67833
  };
67834
+ const freeze = (value) => {
67835
+ if (!value || typeof value !== "object" || Object.isFrozen(value)) return;
67836
+ Object.freeze(value);
67837
+ for (const child of Object.values(value)) freeze(child);
67838
+ };
67839
+ let jsonReader = null;
67840
+ const readJson = async (url) => {
67841
+ jsonReader ??= load(URL.createObjectURL(new Blob(["export default (url) => import(url, { with: { type: \"json\" } });"], { type: "text/javascript" }))).then((module) => module.default);
67842
+ return (await (await jsonReader)(url)).default;
67843
+ };
67434
67844
  const describe = (error) => error instanceof Error ? error.stack ?? error.message : String(error);
67435
67845
  function destroy(token) {
67436
67846
  const instance = instances.get(token);
@@ -67464,10 +67874,11 @@ function scriptAgent(runtimeFactory, applyDelta, moduleUrls, load) {
67464
67874
  if (!instance.runtime) {
67465
67875
  const sources = data.graph ? graphs.get(data.graph) : void 0;
67466
67876
  if (!sources) throw new Error("Missing script modules.");
67467
- instance.urls = moduleUrls(sources);
67877
+ instance.urls = moduleUrls(sources, json);
67468
67878
  const src = input.script.src;
67469
67879
  const url = src ? instance.urls.urls[src] : void 0;
67470
67880
  if (!url) throw new Error("Missing entry module.");
67881
+ for (const [path, url] of Object.entries(instance.urls.urls)) if (path.endsWith(".json")) freeze(await readJson(url));
67471
67882
  instance.module = await load(url);
67472
67883
  if (instances.get(token) !== instance) throw new Error("Script stopped.");
67473
67884
  current = token;
@@ -67517,12 +67928,14 @@ function scriptAgent(runtimeFactory, applyDelta, moduleUrls, load) {
67517
67928
  }
67518
67929
  const output = runtime.output();
67519
67930
  const changed = output.version !== instance.outputVersion;
67931
+ const { shader: _shader, parameters: _parameters, ...repeat } = output;
67932
+ const sent = changed ? instance.outputVersion < 0 ? output : repeat : void 0;
67520
67933
  instance.outputVersion = output.version;
67521
67934
  send({
67522
67935
  token,
67523
67936
  kind: "frame",
67524
67937
  request: data.request,
67525
- output: changed ? output : void 0,
67938
+ output: sent,
67526
67939
  bitmap
67527
67940
  }, bitmap ? [bitmap] : []);
67528
67941
  } catch (error) {
@@ -67744,7 +68157,7 @@ function boardScriptFrameSource(options = {}) {
67744
68157
  const worker = `${prelude} (${scriptAgent.toString()})(${createScriptRuntime.toString()}, ${applyScriptInputDelta.toString()}, ${scriptModuleUrls.toString()}, url => import(url));`;
67745
68158
  const cores = typeof navigator === "undefined" ? 4 : navigator.hardwareConcurrency || 4;
67746
68159
  const poolSize = options.poolSize ?? Math.max(1, Math.min(4, cores - 1));
67747
- return `<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:; worker-src blob:; connect-src 'none'; form-action 'none'; base-uri 'none'"><script>
68160
+ return `<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:; worker-src blob:; connect-src blob:; form-action 'none'; base-uri 'none'"><script>
67748
68161
  ${prelude}
67749
68162
  (${scriptBroker.toString()})(URL.createObjectURL(new Blob([${JSON.stringify(worker)}], {type:'text/javascript'})), ${poolSize}, ${options.timeoutMs ?? 2e3});
67750
68163
  <\/script>`;
@@ -67753,14 +68166,15 @@ const NO_BOX = {
67753
68166
  width: 0,
67754
68167
  height: 0
67755
68168
  };
67756
- function supersedes(pending, event) {
67757
- if (pending.type !== event.type) return false;
67758
- if (event.type === "viewchange" || event.type === "selectionchange") return true;
67759
- if (event.type === "pointermove") return pending.pointerId === event.pointerId;
67760
- if (event.type !== "gesture") return false;
67761
- const a = pending.data;
67762
- const b = event.data;
67763
- return a.id === b.id && a.phase === "update" && b.phase === "update";
68169
+ const OFFSCREEN_FRAME_RATE = 4;
68170
+ const CALL_QUIET_MS = 1e3;
68171
+ function selfContained(entry, now) {
68172
+ const output = entry.output;
68173
+ if (!entry.item || !output || now - (entry.calledAt ?? -Infinity) < CALL_QUIET_MS) return false;
68174
+ for (const id in output.patches) if (id !== entry.id) return false;
68175
+ for (const _ in output.world) return false;
68176
+ for (const _ in output.screen) return false;
68177
+ return true;
67764
68178
  }
67765
68179
  function createBoardScriptHost(options) {
67766
68180
  const revisions = /* @__PURE__ */ new Map();
@@ -67979,6 +68393,7 @@ function createBoardScriptHost(options) {
67979
68393
  return;
67980
68394
  }
67981
68395
  if (data.kind === "call") {
68396
+ entry.calledAt = performance.now();
67982
68397
  const capability = typeof data.name === "string" && options.capabilities && Object.hasOwn(options.capabilities, data.name) ? options.capabilities[data.name] : void 0;
67983
68398
  Promise.resolve().then(() => {
67984
68399
  if (!capability) throw new Error(`Capability unavailable: ${data.name}`);
@@ -68019,11 +68434,15 @@ function createBoardScriptHost(options) {
68019
68434
  const acceptsBitmap = Boolean(data.bitmap) && (options.export || !options.isMaterialized || options.isMaterialized(entry.id)) && entry.draw;
68020
68435
  if (acceptsBitmap) entry.texture.update(data.bitmap, (output ?? entry.output)?.pixelated === true);
68021
68436
  else data.bitmap?.close?.();
68022
- const changed = acceptsBitmap || Boolean(output);
68023
- if (changed) revisions.set(entry.id, (revisions.get(entry.id) ?? 0) + 1);
68437
+ if (output && entry.output) {
68438
+ output.shader ??= entry.output.shader;
68439
+ output.parameters ??= entry.output.parameters;
68440
+ }
68441
+ let changed = acceptsBitmap;
68442
+ if (acceptsBitmap || output) revisions.set(entry.id, (revisions.get(entry.id) ?? 0) + 1);
68024
68443
  try {
68025
68444
  if (output) {
68026
- options.onOutput(entry.id, output);
68445
+ changed = options.onOutput(entry.id, output) !== false || changed;
68027
68446
  entry.output = output;
68028
68447
  }
68029
68448
  } catch (error) {
@@ -68031,7 +68450,7 @@ function createBoardScriptHost(options) {
68031
68450
  return;
68032
68451
  }
68033
68452
  if (changed || options.export) options.onFrame();
68034
- else if (needsTick(entry)) schedule();
68453
+ else if (output || needsTick(entry)) schedule();
68035
68454
  };
68036
68455
  window.addEventListener("message", onMessage);
68037
68456
  function focusTarget(id, target) {
@@ -68244,7 +68663,8 @@ function createBoardScriptHost(options) {
68244
68663
  }
68245
68664
  if (!brokerReady || !entry.graph || entry.pending) continue;
68246
68665
  const elapsed = time - entry.startedAt;
68247
- const tick = entry.output?.frameRate ? Math.floor(elapsed * entry.output.frameRate / 1e3) : elapsed;
68666
+ const rate = entry.visible || !selfContained(entry, now) ? entry.output?.frameRate : Math.min(entry.output?.frameRate ?? OFFSCREEN_FRAME_RATE, OFFSCREEN_FRAME_RATE);
68667
+ const tick = rate ? Math.floor(elapsed * rate / 1e3) : elapsed;
68248
68668
  if (!entry.dirty && (!moving(entry) || entry.tick === tick)) continue;
68249
68669
  entry.pending = true;
68250
68670
  entry.dirty = false;
@@ -68283,14 +68703,11 @@ function createBoardScriptHost(options) {
68283
68703
  },
68284
68704
  event(id, event) {
68285
68705
  const entry = entries.get(id);
68286
- if (!entry || entry.error || entry.output && !entry.output.listens.includes(event.type)) return;
68287
- let queued = entry.events.length - 1;
68288
- while (queued >= 0 && !supersedes(entry.events[queued], event)) queued--;
68289
- if (queued >= 0 && (event.type !== "pointermove" || queued === entry.events.length - 1)) entry.events.splice(queued, 1);
68290
- if (entry.events.length >= 128) return;
68291
- entry.events.push(event);
68706
+ if (!entry || entry.error || !boardScriptListens(entry.output, event)) return true;
68707
+ if (!queueBoardScriptEvent(entry.events, event)) return false;
68292
68708
  entry.dirty = true;
68293
68709
  options.onFrame();
68710
+ return true;
68294
68711
  },
68295
68712
  invalidate(path) {
68296
68713
  modules.invalidate(path);
@@ -68326,6 +68743,34 @@ function createBoardScriptHost(options) {
68326
68743
  };
68327
68744
  }
68328
68745
  //#endregion
68746
+ //#region ../sdk/src/board/model/script-calls.ts
68747
+ function layoutBoardScriptText(value) {
68748
+ const input = value;
68749
+ if (!input || typeof input.text !== "string" || input.text.length > 1e4) throw new Error("layoutText() needs text of at most 10000 characters.");
68750
+ for (const key of [
68751
+ "fontSize",
68752
+ "fontWeight",
68753
+ "lineHeight",
68754
+ "width"
68755
+ ]) if (input[key] !== void 0 && !(Number.isFinite(input[key]) && input[key] > 0)) throw new Error(`layoutText() ${key} must be a positive number.`);
68756
+ const { width, height } = layoutBoardText({
68757
+ fontSize: 24,
68758
+ fontWeight: 500,
68759
+ font: "sans",
68760
+ lineHeight: 4 / 3,
68761
+ ...input
68762
+ });
68763
+ return {
68764
+ width,
68765
+ height
68766
+ };
68767
+ }
68768
+ const BOARD_SCRIPT_EXPORT_CALLS = {
68769
+ "board.emit": () => void 0,
68770
+ "board.commit": () => false,
68771
+ "board.layoutText": layoutBoardScriptText
68772
+ };
68773
+ //#endregion
68329
68774
  //#region ../sdk/src/board/render/shader/library.ts
68330
68775
  const BOARD_SHADER_LIBRARY = {
68331
68776
  hash: `
@@ -68632,6 +69077,100 @@ function describeBoardShaderError(log, firstLine, label) {
68632
69077
  })).slice(0, 4).join("; ") || "the shader failed to compile"}`;
68633
69078
  }
68634
69079
  //#endregion
69080
+ //#region ../sdk/src/board/render/shader/compile.ts
69081
+ const READY = {
69082
+ poll: () => true,
69083
+ cancel() {}
69084
+ };
69085
+ const COMPLETION_STATUS = 37297;
69086
+ const failures = /* @__PURE__ */ new Map();
69087
+ const parallel = /* @__PURE__ */ new WeakMap();
69088
+ function programs(renderer) {
69089
+ return renderer.shader._programDataHash ?? null;
69090
+ }
69091
+ function adopt(gl, glProgram, program, cache) {
69092
+ glProgram._attributeData = extractAttributesFromGlProgram(program, gl, false);
69093
+ glProgram._uniformData = getUniformData(program, gl);
69094
+ glProgram._uniformBlockData = getUboData(program, gl);
69095
+ const uniforms = {};
69096
+ for (const [name, data] of Object.entries(glProgram._uniformData)) uniforms[name] = {
69097
+ location: gl.getUniformLocation(program, name),
69098
+ value: defaultValue(data.type, data.size)
69099
+ };
69100
+ cache[glProgram._key] = new GlProgramData(program, uniforms);
69101
+ }
69102
+ function lineShift(raw, final) {
69103
+ return final.split("\n").length - raw.split("\n").length;
69104
+ }
69105
+ function compileBoardProgram(renderer, glProgram, source, label, wait) {
69106
+ if (renderer.type !== RendererType.WEBGL) return READY;
69107
+ const failure = failures.get(glProgram._key);
69108
+ if (failure) throw new Error(failure);
69109
+ const cache = programs(renderer);
69110
+ if (cache?.[glProgram._key]) return READY;
69111
+ const gl = renderer.gl;
69112
+ if (!parallel.has(gl)) parallel.set(gl, Boolean(gl.getExtension("KHR_parallel_shader_compile")));
69113
+ const job = {
69114
+ gl,
69115
+ program: gl.createProgram(),
69116
+ shaders: [gl.createShader(gl.VERTEX_SHADER), gl.createShader(gl.FRAGMENT_SHADER)]
69117
+ };
69118
+ const vertex = glProgram.vertex;
69119
+ const fragment = glProgram.fragment;
69120
+ const stages = [{
69121
+ shader: job.shaders[0],
69122
+ code: vertex,
69123
+ first: source.firstLine.vertex + lineShift(source.vertex, vertex),
69124
+ name: "vertex"
69125
+ }, {
69126
+ shader: job.shaders[1],
69127
+ code: fragment,
69128
+ first: source.firstLine.fragment + lineShift(source.fragment, fragment),
69129
+ name: "fragment"
69130
+ }];
69131
+ for (const { shader, code } of stages) {
69132
+ gl.shaderSource(shader, code);
69133
+ gl.compileShader(shader);
69134
+ gl.attachShader(job.program, shader);
69135
+ }
69136
+ gl.linkProgram(job.program);
69137
+ let done = false;
69138
+ const finish = () => {
69139
+ done = true;
69140
+ let error = null;
69141
+ if (!gl.getProgramParameter(job.program, gl.LINK_STATUS) && !gl.isContextLost()) {
69142
+ for (const { shader, first, name } of stages) if (!error && !gl.getShaderParameter(shader, gl.COMPILE_STATUS)) error = describeBoardShaderError(gl.getShaderInfoLog(shader) ?? "", first, `${label} (${name})`);
69143
+ error ??= `${label}: ${gl.getProgramInfoLog(job.program) ?? "the shader failed to link"}`;
69144
+ }
69145
+ for (const shader of job.shaders) gl.deleteShader(shader);
69146
+ if (error || !cache || gl.isContextLost()) {
69147
+ gl.deleteProgram(job.program);
69148
+ if (error) {
69149
+ if (failures.size > 256) failures.clear();
69150
+ failures.set(glProgram._key, error);
69151
+ throw new Error(error);
69152
+ }
69153
+ return true;
69154
+ }
69155
+ if (cache[glProgram._key]) gl.deleteProgram(job.program);
69156
+ else adopt(gl, glProgram, job.program, cache);
69157
+ return true;
69158
+ };
69159
+ if (wait || !parallel.get(gl)) {
69160
+ finish();
69161
+ return READY;
69162
+ }
69163
+ return {
69164
+ poll: () => done || (gl.getProgramParameter(job.program, COMPLETION_STATUS) === true ? finish() : false),
69165
+ cancel() {
69166
+ if (done) return;
69167
+ done = true;
69168
+ for (const shader of job.shaders) gl.deleteShader(shader);
69169
+ gl.deleteProgram(job.program);
69170
+ }
69171
+ };
69172
+ }
69173
+ //#endregion
68635
69174
  //#region ../sdk/src/board/render/shader/quad.ts
68636
69175
  function boardQuadGeometry(instanceCount = 1) {
68637
69176
  return new Geometry({
@@ -68659,14 +69198,18 @@ function boardQuadGeometry(instanceCount = 1) {
68659
69198
  instanceCount
68660
69199
  });
68661
69200
  }
69201
+ function boardGlProgram(name, source) {
69202
+ return GlProgram.from({
69203
+ name,
69204
+ vertex: source.vertex,
69205
+ fragment: source.fragment,
69206
+ preferredFragmentPrecision: "highp"
69207
+ });
69208
+ }
68662
69209
  function boardShaderMesh(name, source, resources, geometry = boardQuadGeometry()) {
69210
+ const glProgram = source instanceof GlProgram ? source : boardGlProgram(name, source);
68663
69211
  const shader = new Shader({
68664
- glProgram: GlProgram.from({
68665
- name,
68666
- vertex: source.vertex,
68667
- fragment: source.fragment,
68668
- preferredFragmentPrecision: "highp"
68669
- }),
69212
+ glProgram,
68670
69213
  resources
68671
69214
  });
68672
69215
  return {
@@ -68709,6 +69252,8 @@ const STEP_MS = 1e3 / 60;
68709
69252
  const STEPS_PER_FRAME = 8;
68710
69253
  const MAX_LAG = 60;
68711
69254
  const MAX_REPLAY = 36e3;
69255
+ const CHECKPOINT_STEPS = 600;
69256
+ const CHECKPOINTS = 6;
68712
69257
  const PIXI_TYPES = {
68713
69258
  float: "f32",
68714
69259
  int: "i32",
@@ -68723,46 +69268,6 @@ const SIZES = {
68723
69268
  vec3: 3,
68724
69269
  vec4: 4
68725
69270
  };
68726
- const compiled = /* @__PURE__ */ new Map();
68727
- function check(renderer, program, label) {
68728
- if (renderer.type !== RendererType.WEBGL) return;
68729
- const key = `${program.vertex}\u0000${program.fragment}`;
68730
- let error = compiled.get(key);
68731
- if (error === void 0) {
68732
- const gl = renderer.gl;
68733
- error = null;
68734
- const shaders = [];
68735
- const glProgram = gl.createProgram();
68736
- for (const [stage, type, source, first] of [[
68737
- "vertex",
68738
- gl.VERTEX_SHADER,
68739
- program.vertex,
68740
- program.firstLine.vertex
68741
- ], [
68742
- "fragment",
68743
- gl.FRAGMENT_SHADER,
68744
- program.fragment,
68745
- program.firstLine.fragment
68746
- ]]) {
68747
- const shader = gl.createShader(type);
68748
- if (!shader) continue;
68749
- gl.shaderSource(shader, source);
68750
- gl.compileShader(shader);
68751
- shaders.push(shader);
68752
- if (!error && !gl.getShaderParameter(shader, gl.COMPILE_STATUS) && !gl.isContextLost()) error = describeBoardShaderError(gl.getShaderInfoLog(shader) ?? "", first, `${label} (${stage})`);
68753
- gl.attachShader(glProgram, shader);
68754
- }
68755
- if (!error) {
68756
- gl.linkProgram(glProgram);
68757
- if (!gl.getProgramParameter(glProgram, gl.LINK_STATUS) && !gl.isContextLost()) error = `${label}: ${gl.getProgramInfoLog(glProgram) ?? "the shader failed to link"}`;
68758
- }
68759
- for (const shader of shaders) gl.deleteShader(shader);
68760
- gl.deleteProgram(glProgram);
68761
- if (compiled.size > 256) compiled.clear();
68762
- compiled.set(key, error);
68763
- }
68764
- if (error) throw new Error(error);
68765
- }
68766
69271
  const placing = /* @__PURE__ */ new WeakMap();
68767
69272
  function canPlaceSprites(renderer) {
68768
69273
  let supported = placing.get(renderer);
@@ -68938,8 +69443,99 @@ function seedOf(value) {
68938
69443
  function boardShaderSeed(seed) {
68939
69444
  return seedOf(seed);
68940
69445
  }
68941
- function createBoardShaderLayer(renderer, shader, parameters, label) {
68942
- const layer = shader.layer ?? "above";
69446
+ const TEXEL_GROWTH = 128;
69447
+ function createTexels(drawn, pass) {
69448
+ const root = new Container();
69449
+ root.addChild(new Mesh({
69450
+ geometry: drawn.geometry,
69451
+ shader: drawn.shader
69452
+ }));
69453
+ const sprite = new Sprite({
69454
+ texture: Texture.EMPTY,
69455
+ label: "board-shader-texels"
69456
+ });
69457
+ sprite.blendMode = pass.blend ?? "normal";
69458
+ sprite.visible = false;
69459
+ return {
69460
+ size: pass.texel ?? 1,
69461
+ root,
69462
+ sprite,
69463
+ target: null,
69464
+ rect: null
69465
+ };
69466
+ }
69467
+ function texelRect(frame, size) {
69468
+ const [a, b] = frame.localToGlobal;
69469
+ if (Math.hypot(a, b) * frame.density * Math.min(1, frame.shading ?? 1) * size <= 1) return null;
69470
+ const { region, view } = frame;
69471
+ const left = Math.floor(Math.max(region.x, view.x) / size) * size;
69472
+ const top = Math.floor(Math.max(region.y, view.y) / size) * size;
69473
+ const right = Math.ceil(Math.min(region.x + region.width, view.x + view.width) / size) * size;
69474
+ const bottom = Math.ceil(Math.min(region.y + region.height, view.y + view.height) / size) * size;
69475
+ return right > left && bottom > top ? {
69476
+ x: left,
69477
+ y: top,
69478
+ width: right - left,
69479
+ height: bottom - top
69480
+ } : null;
69481
+ }
69482
+ function drawTexels(renderer, texels, rect) {
69483
+ const width = Math.round(rect.width / texels.size);
69484
+ const height = Math.round(rect.height / texels.size);
69485
+ let target = texels.target;
69486
+ if (!target || target.width < width || target.height < height) {
69487
+ releaseTexels(texels);
69488
+ const grow = (edge) => Math.ceil(edge / TEXEL_GROWTH) * TEXEL_GROWTH;
69489
+ target = RenderTexture.create({
69490
+ width: grow(width),
69491
+ height: grow(height),
69492
+ resolution: 1,
69493
+ scaleMode: "nearest",
69494
+ antialias: false,
69495
+ autoGenerateMipmaps: false
69496
+ });
69497
+ texels.target = target;
69498
+ texels.sprite.texture = new Texture({
69499
+ source: target.source,
69500
+ frame: new Rectangle(0, 0, width, height),
69501
+ dynamic: true
69502
+ });
69503
+ }
69504
+ const texture = texels.sprite.texture;
69505
+ if (texture.frame.width !== width || texture.frame.height !== height) {
69506
+ texture.frame.width = width;
69507
+ texture.frame.height = height;
69508
+ texture.update();
69509
+ }
69510
+ texels.root.scale.set(1 / texels.size);
69511
+ texels.root.position.set(-rect.x / texels.size, -rect.y / texels.size);
69512
+ renderer.render({
69513
+ container: texels.root,
69514
+ target,
69515
+ clear: true,
69516
+ clearColor: [
69517
+ 0,
69518
+ 0,
69519
+ 0,
69520
+ 0
69521
+ ]
69522
+ });
69523
+ texels.sprite.position.set(rect.x, rect.y);
69524
+ texels.sprite.scale.set(texels.size);
69525
+ }
69526
+ function releaseTexels(texels) {
69527
+ if (!texels.target) return;
69528
+ texels.sprite.texture.destroy();
69529
+ texels.sprite.texture = Texture.EMPTY;
69530
+ texels.target.destroy(true);
69531
+ texels.target = null;
69532
+ }
69533
+ function destroyTexels(texels) {
69534
+ releaseTexels(texels);
69535
+ texels.sprite.destroy();
69536
+ texels.root.destroy({ children: true });
69537
+ }
69538
+ function createBoardShaderLayer(renderer, shader, parameters, label, options = {}) {
68943
69539
  const uniforms = boardShaderUniforms(shader.uniforms);
68944
69540
  const surfaces = shader.surfaces === true;
68945
69541
  const hasState = shader.state !== void 0;
@@ -68949,19 +69545,21 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
68949
69545
  surfaces,
68950
69546
  state: hasState
68951
69547
  };
69548
+ const compiles = [];
68952
69549
  const program = (kind, glsl, name) => {
68953
- let built;
68954
69550
  try {
68955
- built = buildBoardShaderProgram({
69551
+ const built = buildBoardShaderProgram({
68956
69552
  ...base,
68957
69553
  kind,
68958
69554
  glsl
68959
69555
  });
69556
+ const glProgram = boardGlProgram(`board-shader-${kind}`, built);
69557
+ compiles.push(compileBoardProgram(renderer, glProgram, built, name, options.wait === true));
69558
+ return glProgram;
68960
69559
  } catch (error) {
68961
- throw new Error(`${name}: ${error instanceof Error ? error.message : String(error)}`);
69560
+ const message = error instanceof Error ? error.message : String(error);
69561
+ throw new Error(message.startsWith(name) ? message : `${name}: ${message}`);
68962
69562
  }
68963
- check(renderer, built, name);
68964
- return built;
68965
69563
  };
68966
69564
  const group = boardUniforms(parameters, uniforms);
68967
69565
  const textures = {};
@@ -68969,20 +69567,19 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
68969
69567
  if (hasState) textures.uCohubState = Texture.EMPTY.source;
68970
69568
  const meshes = [];
68971
69569
  const filters = [];
68972
- const container = layer === "filter" ? null : new Container({ label: `board-shader-${label}` });
69570
+ const containers = {
69571
+ below: null,
69572
+ above: null
69573
+ };
69574
+ const area = new Rectangle();
68973
69575
  const place = canPlaceSprites(renderer);
68974
69576
  let placementsStale = true;
68975
69577
  shader.passes.forEach((pass, index) => {
68976
69578
  const name = `${label} pass ${index + 1}`;
69579
+ const layer = boardShaderPassLayer(shader, pass);
68977
69580
  if (layer === "filter") {
68978
- const built = program("filter", pass.glsl, name);
68979
69581
  const filter = new Filter({
68980
- glProgram: GlProgram.from({
68981
- name: `board-shader-filter`,
68982
- vertex: built.vertex,
68983
- fragment: built.fragment,
68984
- preferredFragmentPrecision: "highp"
68985
- }),
69582
+ glProgram: program("filter", pass.glsl, name),
68986
69583
  resources: {
68987
69584
  cohubUniforms: group,
68988
69585
  ...textures
@@ -68990,7 +69587,10 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
68990
69587
  padding: 0,
68991
69588
  resolution: "inherit"
68992
69589
  });
68993
- filters.push(filter);
69590
+ filters.push({
69591
+ filter,
69592
+ pass
69593
+ });
68994
69594
  return;
68995
69595
  }
68996
69596
  const sprites = pass.sprites ?? 0;
@@ -69012,11 +69612,19 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
69012
69612
  });
69013
69613
  const drawn = boardShaderMesh("board-shader", program(kind, pass.glsl, name), resources, boardQuadGeometry(Math.max(1, sprites)));
69014
69614
  drawn.mesh.blendMode = pass.blend ?? "normal";
69015
- container?.addChild(drawn.mesh);
69615
+ containers[layer] ??= new Container({ label: `board-shader-${label}-${layer}` });
69616
+ const container = containers[layer];
69617
+ container.boundsArea = area;
69618
+ container.addChild(drawn.mesh);
69619
+ const texels = pass.texel ? createTexels(drawn, pass) : null;
69620
+ if (texels) container.addChild(texels.sprite);
69016
69621
  meshes.push({
69017
69622
  ...drawn,
69623
+ pass,
69018
69624
  sprites,
69019
- placement
69625
+ placement,
69626
+ scaler: null,
69627
+ texels
69020
69628
  });
69021
69629
  });
69022
69630
  let state = null;
@@ -69039,6 +69647,7 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
69039
69647
  const blank = new Container();
69040
69648
  let time = 0;
69041
69649
  let quality = 1;
69650
+ let compiled = compiles.length === 0;
69042
69651
  let last = null;
69043
69652
  const stateRegion = (frame) => shader.state?.bounds ?? frame.region;
69044
69653
  function fill(target, frame, geometry, step) {
@@ -69098,9 +69707,41 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
69098
69707
  }
69099
69708
  target.update();
69100
69709
  }
69710
+ const checkpoints = [];
69711
+ let surfaceKey = "";
69712
+ const copier = new Sprite();
69713
+ copier.blendMode = "none";
69714
+ const copy = (target, from, to) => {
69715
+ copier.texture = from;
69716
+ target.render({
69717
+ container: copier,
69718
+ target: to,
69719
+ clear: true,
69720
+ clearColor: [
69721
+ 0,
69722
+ 0,
69723
+ 0,
69724
+ 0
69725
+ ]
69726
+ });
69727
+ };
69728
+ const inputs = ({ time: _time, ...frame }) => JSON.stringify([frame, surfaceKey]);
69729
+ function checkpoint(target, state, key) {
69730
+ if (checkpoints.some((entry) => entry.steps === state.steps && entry.key === key)) return;
69731
+ const texture = (checkpoints.length >= CHECKPOINTS ? checkpoints.shift() : void 0)?.texture ?? boardRenderTarget(state.read.width, state.read.height, state.read.source.format);
69732
+ copy(target, state.read, texture);
69733
+ checkpoints.push({
69734
+ steps: state.steps,
69735
+ key,
69736
+ texture
69737
+ });
69738
+ }
69101
69739
  function advance(target, state, frame, catchUp) {
69102
69740
  const wanted = Math.floor(frame.time / STEP_MS);
69741
+ const key = catchUp ? inputs(frame) : "";
69742
+ let replaying = false;
69103
69743
  if (wanted < state.steps || state.steps < 0) {
69744
+ replaying = catchUp;
69104
69745
  for (const texture of [state.read, state.write]) target.render({
69105
69746
  container: blank,
69106
69747
  target: texture,
@@ -69113,6 +69754,11 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
69113
69754
  ]
69114
69755
  });
69115
69756
  state.steps = Math.max(0, wanted - MAX_REPLAY);
69757
+ const resume = catchUp ? checkpoints.reduce((best, entry) => entry.key === key && entry.steps <= wanted && entry.steps > (best?.steps ?? state.steps - 1) ? entry : best, null) : null;
69758
+ if (resume) {
69759
+ copy(target, resume.texture, state.read);
69760
+ state.steps = resume.steps;
69761
+ }
69116
69762
  }
69117
69763
  if (!catchUp && wanted - state.steps > MAX_LAG) state.steps = wanted - STEPS_PER_FRAME;
69118
69764
  const limit = catchUp ? Number.POSITIVE_INFINITY : STEPS_PER_FRAME;
@@ -69133,29 +69779,72 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
69133
69779
  [state.read, state.write] = [state.write, state.read];
69134
69780
  state.steps++;
69135
69781
  ran++;
69782
+ if (replaying && state.steps % CHECKPOINT_STEPS === 0) checkpoint(target, state, key);
69136
69783
  }
69137
69784
  const source = state.read.source;
69138
69785
  for (const { shader, placement } of meshes) {
69139
69786
  shader.resources.uCohubState = source;
69140
69787
  if (placement) placement.mesh.shader.resources.uCohubState = source;
69141
69788
  }
69142
- for (const filter of filters) filter.resources.uCohubState = source;
69789
+ for (const { filter } of filters) filter.resources.uCohubState = source;
69143
69790
  return {
69144
69791
  ran,
69145
69792
  behind: state.steps < wanted
69146
69793
  };
69147
69794
  }
69795
+ function shade(drawn, frame) {
69796
+ const resolution = frame.density * Math.min(1, frame.shading ?? 1);
69797
+ const blend = drawn.pass.blend ?? "normal";
69798
+ if (resolution >= frame.density * .99) {
69799
+ if (!drawn.scaler) return;
69800
+ drawn.mesh.filters = null;
69801
+ drawn.mesh.filterArea = null;
69802
+ drawn.mesh.blendMode = blend;
69803
+ drawn.scaler.destroy();
69804
+ drawn.scaler = null;
69805
+ return;
69806
+ }
69807
+ if (!drawn.scaler) {
69808
+ drawn.scaler = new AlphaFilter({
69809
+ alpha: 1,
69810
+ blendMode: blend
69811
+ });
69812
+ drawn.mesh.blendMode = "normal";
69813
+ drawn.mesh.filters = [drawn.scaler];
69814
+ drawn.mesh.filterArea = area;
69815
+ }
69816
+ drawn.scaler.resolution = resolution;
69817
+ }
69148
69818
  return {
69149
- layer,
69150
- container,
69151
- filters: layer === "filter" ? filters : null,
69819
+ below: containers.below,
69820
+ above: containers.above,
69821
+ filters: filters.length ? filters.map(({ filter }) => filter) : null,
69152
69822
  surfaces,
69153
69823
  animated: hasState,
69824
+ ready() {
69825
+ if (!compiled) compiled = compiles.every((compile) => compile.poll());
69826
+ return compiled;
69827
+ },
69154
69828
  update(frame) {
69155
69829
  if (frame.quality !== quality) {
69156
69830
  quality = frame.quality;
69157
69831
  for (const { geometry, sprites } of meshes) if (sprites) geometry.instanceCount = Math.max(1, Math.round(sprites * quality));
69158
69832
  }
69833
+ area.x = frame.region.x;
69834
+ area.y = frame.region.y;
69835
+ area.width = frame.region.width;
69836
+ area.height = frame.region.height;
69837
+ for (const drawn of meshes) {
69838
+ const on = boardShaderPassOn(drawn.pass, frame.passes);
69839
+ const texels = drawn.texels;
69840
+ if (texels) {
69841
+ texels.rect = on ? texelRect(frame, texels.size) : null;
69842
+ texels.sprite.visible = texels.rect !== null;
69843
+ }
69844
+ drawn.mesh.visible = on && !texels?.rect;
69845
+ if (drawn.mesh.visible && !drawn.sprites) shade(drawn, frame);
69846
+ }
69847
+ for (const { filter, pass } of filters) filter.enabled = boardShaderPassOn(pass, frame.passes);
69159
69848
  fill(group, frame, frame.region);
69160
69849
  for (const { geometry, placement } of meshes) {
69161
69850
  if (!placement) continue;
@@ -69177,8 +69866,9 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
69177
69866
  ran: 0,
69178
69867
  behind: false
69179
69868
  };
69869
+ for (const { texels } of meshes) if (texels?.rect) drawTexels(target, texels, texels.rect);
69180
69870
  if (placementsStale || stepped.ran) {
69181
- for (const { placement } of meshes) if (placement) target.render({
69871
+ for (const { placement, mesh } of meshes) if (placement && mesh.visible) target.render({
69182
69872
  container: placement.mesh.mesh,
69183
69873
  target: placement.target,
69184
69874
  clear: true,
@@ -69193,8 +69883,12 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
69193
69883
  }
69194
69884
  return stepped.behind;
69195
69885
  },
69196
- setSurfaces(texture, region) {
69197
- const shaders = [...meshes.flatMap(({ shader, placement }) => placement ? [shader, placement.mesh.shader] : [shader]), ...filters];
69886
+ rewind() {
69887
+ if (state) state.steps = -1;
69888
+ },
69889
+ setSurfaces(texture, region, key = "") {
69890
+ surfaceKey = key;
69891
+ const shaders = [...meshes.flatMap(({ shader, placement }) => placement ? [shader, placement.mesh.shader] : [shader]), ...filters.map(({ filter }) => filter)];
69198
69892
  if (state) shaders.push(state.simulate.shader);
69199
69893
  for (const target of shaders) target.resources.uCohubSurfaces = texture.source;
69200
69894
  const groups = [group, ...meshes.flatMap(({ placement }) => placement ? [placement.uniforms] : [])];
@@ -69211,18 +69905,24 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
69211
69905
  placementsStale = true;
69212
69906
  },
69213
69907
  destroy() {
69908
+ for (const compile of compiles) compile.cancel();
69214
69909
  for (const drawn of meshes) {
69910
+ drawn.scaler?.destroy();
69911
+ if (drawn.texels) destroyTexels(drawn.texels);
69215
69912
  destroyBoardShaderMesh(drawn);
69216
69913
  if (drawn.placement) destroyPlacement(renderer, drawn.placement);
69217
69914
  }
69218
- container?.destroy();
69219
- for (const filter of filters) filter.destroy();
69915
+ containers.below?.destroy();
69916
+ containers.above?.destroy();
69917
+ for (const { filter } of filters) filter.destroy();
69220
69918
  blank.destroy();
69221
69919
  if (state) {
69222
69920
  destroyBoardShaderMesh(state.simulate);
69223
69921
  state.read.destroy(true);
69224
69922
  state.write.destroy(true);
69225
69923
  }
69924
+ for (const { texture } of checkpoints) texture.destroy(true);
69925
+ copier.destroy();
69226
69926
  }
69227
69927
  };
69228
69928
  }
@@ -69455,6 +70155,15 @@ const LIGHT_BLENDS = /* @__PURE__ */ new Set(["screen", "add"]);
69455
70155
  const SURFACE_EDGE = 512;
69456
70156
  const SURFACE_MARGIN = .25;
69457
70157
  const SURFACE_COARSEN = 1.5;
70158
+ const SURFACE_INTERVAL_MS = 1e3 / 30;
70159
+ function grow(rect, margin) {
70160
+ return {
70161
+ x: rect.x - rect.width * margin,
70162
+ y: rect.y - rect.height * margin,
70163
+ width: rect.width * (1 + 2 * margin),
70164
+ height: rect.height * (1 + 2 * margin)
70165
+ };
70166
+ }
69458
70167
  function surfaceOutline(item) {
69459
70168
  const { width, height } = item.frame;
69460
70169
  const radius = item.style?.radius;
@@ -69481,15 +70190,10 @@ function boardSurfaceOutlines(scene, owner, world, worldToLocal, candidates) {
69481
70190
  }
69482
70191
  return outlines;
69483
70192
  }
69484
- function boardSurfaceRegion(previous, region, margin) {
69485
- if (!margin) return region;
69486
- 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;
69487
- return {
69488
- x: region.x - region.width * margin,
69489
- y: region.y - region.height * margin,
69490
- width: region.width * (1 + 2 * margin),
69491
- height: region.height * (1 + 2 * margin)
69492
- };
70193
+ function boardSurfaceRegion(previous, needed, margin) {
70194
+ const grown = grow(needed, margin);
70195
+ 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;
70196
+ return grown;
69493
70197
  }
69494
70198
  function parameterValues(parameters, params, color) {
69495
70199
  const values = {};
@@ -69501,18 +70205,26 @@ function parameterValues(parameters, params, color) {
69501
70205
  }
69502
70206
  return values;
69503
70207
  }
69504
- function sameOutlines(a, b) {
70208
+ function sameOutlines(a, b, tolerance) {
69505
70209
  if (a.length !== b.length) return false;
69506
70210
  for (let index = 0; index < a.length; index++) {
69507
70211
  const left = a[index];
69508
70212
  const right = b[index];
69509
70213
  if (left.length !== right.length) return false;
69510
- for (let point = 0; point < left.length; point++) if (Math.abs(left[point] - right[point]) > .001) return false;
70214
+ for (let point = 0; point < left.length; point++) if (Math.abs(left[point] - right[point]) > tolerance) return false;
69511
70215
  }
69512
70216
  return true;
69513
70217
  }
69514
- function createBoardShaderLayers() {
70218
+ function outlineHash(outlines) {
70219
+ let hash = 2166136261;
70220
+ for (const outline of outlines) for (const value of outline) hash = Math.imul(hash ^ Math.round(value * 8), 16777619) >>> 0;
70221
+ return `${outlines.length}.${hash.toString(36)}`;
70222
+ }
70223
+ function createBoardShaderLayers(options = {}) {
70224
+ const now = options.now ?? (() => performance.now());
70225
+ const interval = options.wait ? 0 : SURFACE_INTERVAL_MS;
69515
70226
  const entries = /* @__PURE__ */ new Map();
70227
+ const compiling = /* @__PURE__ */ new Map();
69516
70228
  const failed = /* @__PURE__ */ new Map();
69517
70229
  let animated = false;
69518
70230
  let pending = false;
@@ -69524,13 +70236,71 @@ function createBoardShaderLayers() {
69524
70236
  entry.layer.destroy();
69525
70237
  entry.surfaces?.destroy();
69526
70238
  }
70239
+ function dropCompiling(id) {
70240
+ compiling.get(id)?.layer.destroy();
70241
+ compiling.delete(id);
70242
+ }
70243
+ function surfaceField(entry, renderer, owner, placement, host, scene, candidates) {
70244
+ const { localToWorld } = placement;
70245
+ const region = owner.root ? boardSurfaceRegion(entry.surfaces?.region ?? null, placement.region, SURFACE_MARGIN) : placement.region;
70246
+ const corners = [
70247
+ applyMatrix$1(localToWorld, region),
70248
+ applyMatrix$1(localToWorld, {
70249
+ x: region.x + region.width,
70250
+ y: region.y + region.height
70251
+ }),
70252
+ applyMatrix$1(localToWorld, {
70253
+ x: region.x + region.width,
70254
+ y: region.y
70255
+ }),
70256
+ applyMatrix$1(localToWorld, {
70257
+ x: region.x,
70258
+ y: region.y + region.height
70259
+ })
70260
+ ];
70261
+ const xs = corners.map((point) => point.x);
70262
+ const ys = corners.map((point) => point.y);
70263
+ const world = {
70264
+ x: Math.min(...xs),
70265
+ y: Math.min(...ys),
70266
+ width: Math.max(...xs) - Math.min(...xs),
70267
+ height: Math.max(...ys) - Math.min(...ys)
70268
+ };
70269
+ const edge = Math.max(64, Math.round(SURFACE_EDGE * (owner.root ? 1.5 : 1) * host.quality));
70270
+ const key = `${[
70271
+ region.x,
70272
+ region.y,
70273
+ region.width,
70274
+ region.height,
70275
+ ...localToWorld
70276
+ ].map((n) => n.toFixed(3)).join(",")}|${edge}`;
70277
+ entry.surfaces ??= createBoardSurfaceField();
70278
+ const moved = key !== entry.surfaceKey;
70279
+ const at = now();
70280
+ if (moved || entry.surfaceScene !== scene && at - entry.surfaceAt >= interval) {
70281
+ entry.surfaceScene = scene;
70282
+ const outlines = boardSurfaceOutlines(scene, owner.id, world, invertMatrix(localToWorld), candidates?.(world));
70283
+ if (moved || !sameOutlines(outlines, entry.outlines, region.width / edge / 2)) {
70284
+ entry.surfaces.build(renderer, region, outlines, edge);
70285
+ entry.outlines = outlines;
70286
+ entry.surfaceAt = at;
70287
+ entry.surfaceSignature = `${key}|${outlineHash(outlines)}`;
70288
+ }
70289
+ entry.surfaceKey = key;
70290
+ } else if (entry.surfaceScene !== scene) pending = true;
70291
+ entry.layer.setSurfaces(entry.surfaces.texture, entry.surfaces.region, entry.surfaceSignature);
70292
+ }
69527
70293
  return {
69528
70294
  get animated() {
69529
70295
  return animated || pending;
69530
70296
  },
69531
70297
  get size() {
69532
- return entries.size;
70298
+ return entries.size + compiling.size;
69533
70299
  },
70300
+ get compiling() {
70301
+ return compiling.size > 0;
70302
+ },
70303
+ layer: (id) => entries.get(id)?.layer ?? null,
69534
70304
  sync(renderer, owners, host, scene, candidates) {
69535
70305
  const alive = /* @__PURE__ */ new Set();
69536
70306
  animated = false;
@@ -69541,31 +70311,44 @@ function createBoardShaderLayers() {
69541
70311
  if (!shader || !signature || failed.get(owner.id) === signature) continue;
69542
70312
  alive.add(owner.id);
69543
70313
  let entry = entries.get(owner.id);
69544
- if (entry && entry.signature !== signature) {
69545
- drop(owner.id, host);
69546
- entry = void 0;
69547
- }
69548
70314
  try {
69549
- if (!entry) {
69550
- entry = {
69551
- owner,
69552
- output,
69553
- signature,
69554
- layer: createBoardShaderLayer(renderer, shader, boardShaderParameters(output.parameters), owner.id),
69555
- surfaces: null,
69556
- surfaceKey: "",
69557
- surfaceScene: null,
69558
- outlines: [],
69559
- placed: false
69560
- };
69561
- entries.set(owner.id, entry);
70315
+ if (entry?.signature !== signature) {
70316
+ let next = compiling.get(owner.id);
70317
+ if (next?.signature !== signature) {
70318
+ dropCompiling(owner.id);
70319
+ next = {
70320
+ signature,
70321
+ layer: createBoardShaderLayer(renderer, shader, boardShaderParameters(output.parameters), owner.id, { wait: options.wait })
70322
+ };
70323
+ compiling.set(owner.id, next);
70324
+ }
70325
+ if (next.layer.ready()) {
70326
+ compiling.delete(owner.id);
70327
+ drop(owner.id, host);
70328
+ entry = {
70329
+ owner,
70330
+ output,
70331
+ signature,
70332
+ layer: next.layer,
70333
+ surfaces: null,
70334
+ surfaceKey: "",
70335
+ surfaceScene: null,
70336
+ surfaceAt: -Infinity,
70337
+ surfaceSignature: "",
70338
+ outlines: [],
70339
+ placed: false
70340
+ };
70341
+ entries.set(owner.id, entry);
70342
+ }
69562
70343
  }
70344
+ if (!entry) continue;
69563
70345
  entry.owner = owner;
69564
- entry.output = output;
70346
+ if (entry.signature === signature) entry.output = output;
70347
+ const drawn = entry.output;
69565
70348
  const placement = host.attach(owner, entry.layer);
69566
70349
  entry.placed = placement !== null;
69567
70350
  if (!placement) continue;
69568
- animated ||= output.animated || entry.layer.animated;
70351
+ animated ||= drawn.animated || entry.layer.animated;
69569
70352
  entry.layer.update({
69570
70353
  time: owner.time,
69571
70354
  region: placement.region,
@@ -69575,77 +70358,42 @@ function createBoardShaderLayers() {
69575
70358
  density: host.density,
69576
70359
  seed: boardShaderSeed(owner.seed),
69577
70360
  quality: host.quality,
70361
+ shading: host.shading,
69578
70362
  dark: host.dark,
69579
- params: parameterValues(output.parameters, owner.params, host.color),
69580
- uniforms: output.uniforms
70363
+ params: parameterValues(drawn.parameters, owner.params, host.color),
70364
+ uniforms: drawn.uniforms,
70365
+ passes: drawn.passes
69581
70366
  });
69582
- if (entry.layer.surfaces) {
69583
- const { localToWorld } = placement;
69584
- const margin = owner.root ? SURFACE_MARGIN : 0;
69585
- const region = boardSurfaceRegion(entry.surfaces?.region ?? null, placement.region, margin);
69586
- const corners = [
69587
- applyMatrix$1(localToWorld, region),
69588
- applyMatrix$1(localToWorld, {
69589
- x: region.x + region.width,
69590
- y: region.y + region.height
69591
- }),
69592
- applyMatrix$1(localToWorld, {
69593
- x: region.x + region.width,
69594
- y: region.y
69595
- }),
69596
- applyMatrix$1(localToWorld, {
69597
- x: region.x,
69598
- y: region.y + region.height
69599
- })
69600
- ];
69601
- const xs = corners.map((point) => point.x);
69602
- const ys = corners.map((point) => point.y);
69603
- const world = {
69604
- x: Math.min(...xs),
69605
- y: Math.min(...ys),
69606
- width: Math.max(...xs) - Math.min(...xs),
69607
- height: Math.max(...ys) - Math.min(...ys)
69608
- };
69609
- const edge = Math.max(64, Math.round(SURFACE_EDGE * (1 + 2 * margin) * host.quality));
69610
- const key = `${[
69611
- region.x,
69612
- region.y,
69613
- region.width,
69614
- region.height,
69615
- ...localToWorld
69616
- ].map((n) => n.toFixed(3)).join(",")}|${edge}`;
69617
- entry.surfaces ??= createBoardSurfaceField();
69618
- if (key !== entry.surfaceKey || entry.surfaceScene !== scene) {
69619
- entry.surfaceScene = scene;
69620
- const outlines = boardSurfaceOutlines(scene, owner.id, world, invertMatrix(localToWorld), candidates?.(world));
69621
- if (key !== entry.surfaceKey || !sameOutlines(outlines, entry.outlines)) entry.surfaces.build(renderer, region, outlines, edge);
69622
- entry.surfaceKey = key;
69623
- entry.outlines = outlines;
69624
- }
69625
- entry.layer.setSurfaces(entry.surfaces.texture, entry.surfaces.region);
69626
- }
70367
+ if (entry.layer.surfaces) surfaceField(entry, renderer, owner, placement, host, scene, candidates);
69627
70368
  } catch (error) {
69628
70369
  host.attach(owner, null);
69629
70370
  drop(owner.id, host);
70371
+ dropCompiling(owner.id);
69630
70372
  failed.set(owner.id, signature);
69631
70373
  host.fault(owner.id, error instanceof Error ? error.message : String(error));
69632
70374
  }
69633
70375
  }
69634
70376
  for (const id of [...entries.keys()]) if (!alive.has(id)) drop(id, host);
70377
+ for (const id of [...compiling.keys()]) if (!alive.has(id)) dropCompiling(id);
69635
70378
  for (const id of [...failed.keys()]) if (!owners.some((owner) => owner.id === id)) failed.delete(id);
69636
70379
  },
69637
70380
  prepare(renderer, catchUp = false) {
69638
70381
  pending = false;
69639
70382
  for (const entry of entries.values()) if (entry.placed && entry.layer.prepare(renderer, { catchUp })) pending = true;
69640
70383
  },
70384
+ rewind() {
70385
+ for (const entry of entries.values()) entry.layer.rewind();
70386
+ },
69641
70387
  detach() {
69642
70388
  for (const entry of entries.values()) {
69643
- entry.layer.container?.removeFromParent();
70389
+ entry.layer.below?.removeFromParent();
70390
+ entry.layer.above?.removeFromParent();
69644
70391
  entry.placed = false;
69645
70392
  }
69646
70393
  },
69647
70394
  destroy() {
69648
70395
  for (const id of [...entries.keys()]) drop(id);
70396
+ for (const id of [...compiling.keys()]) dropCompiling(id);
69649
70397
  failed.clear();
69650
70398
  }
69651
70399
  };
@@ -69659,10 +70407,17 @@ function createBrowserBoardScriptExport(readModule, options = {}) {
69659
70407
  element.style.cssText = "position:fixed;left:-10000px;top:0;width:1px;height:1px;visibility:hidden;pointer-events:none";
69660
70408
  globalThis.document.body.appendChild(element);
69661
70409
  const outputs = /* @__PURE__ */ new Map();
70410
+ const ranks = /* @__PURE__ */ new Map();
70411
+ const last = /* @__PURE__ */ new Map();
69662
70412
  const started = {
69663
70413
  element,
69664
70414
  outputs,
69665
70415
  time: 0,
70416
+ document: null,
70417
+ ranks,
70418
+ outbox: createBoardScriptOutbox(() => ranks),
70419
+ views: /* @__PURE__ */ new Map(),
70420
+ last,
69666
70421
  wake: () => {},
69667
70422
  host: createBoardScriptHost({
69668
70423
  host: element,
@@ -69671,6 +70426,15 @@ function createBrowserBoardScriptExport(readModule, options = {}) {
69671
70426
  shaders: options.shaders ?? true,
69672
70427
  snapshots: options.snapshots,
69673
70428
  timeoutMs: 15e3,
70429
+ capabilities: {
70430
+ ...Object.fromEntries(Object.entries(BOARD_SCRIPT_EXPORT_CALLS).map(([name, call]) => [name, async (_id, input) => call(input)])),
70431
+ "board.emit": async (id, input) => {
70432
+ if (!started.document) return;
70433
+ const { target, event } = boardScriptEmit(started.document, id, input);
70434
+ last.set(id, `emit(${target}, "${event.type}")`);
70435
+ started.outbox.push(id, target, event);
70436
+ }
70437
+ },
69674
70438
  onFrame: () => started.wake(),
69675
70439
  onOutput(id, output) {
69676
70440
  if (output) outputs.set(id, output);
@@ -69687,49 +70451,112 @@ function createBrowserBoardScriptExport(readModule, options = {}) {
69687
70451
  run.element.remove();
69688
70452
  run = null;
69689
70453
  }
70454
+ function settle(current, document, time, view) {
70455
+ current.time = time;
70456
+ current.document = document;
70457
+ const { host } = current;
70458
+ const scene = buildBoardScene(document);
70459
+ const ids = boardScriptAttachments(document).map(({ id }) => id);
70460
+ current.ranks.clear();
70461
+ for (const [index, id] of ids.entries()) current.ranks.set(id, index);
70462
+ const viewKey = view ? JSON.stringify(view) : null;
70463
+ let viewed = false;
70464
+ let rounds = 0;
70465
+ return new Promise((resolve, reject) => {
70466
+ const finish = (error) => {
70467
+ clearTimeout(timer);
70468
+ current.wake = () => {};
70469
+ if (error) reject(error);
70470
+ else resolve();
70471
+ };
70472
+ const timer = setTimeout(() => finish(new Error(["Scripts did not settle in 20 s.", ...status(current, ids)].join(" "))), 2e4);
70473
+ let queued = false;
70474
+ const sync = () => {
70475
+ queued = false;
70476
+ try {
70477
+ host.sync(document, scene, {
70478
+ x: 0,
70479
+ y: 0,
70480
+ zoom: 1
70481
+ }, time, false);
70482
+ if (viewKey && !viewed) {
70483
+ viewed = true;
70484
+ for (const id of ids) if (current.views.get(id) !== viewKey) {
70485
+ current.views.set(id, viewKey);
70486
+ host.event(id, {
70487
+ type: "viewchange",
70488
+ data: view
70489
+ });
70490
+ }
70491
+ }
70492
+ for (const id of ids) {
70493
+ const error = host.error(id);
70494
+ if (error) throw new Error(error);
70495
+ }
70496
+ if (!ids.every((id) => host.settled(id))) return;
70497
+ if (current.outbox.size && rounds++ <= 16) {
70498
+ for (const [target, events] of current.outbox.take()) {
70499
+ current.last.set(target, `event ${events.map((event) => event.type).join(", ")}`);
70500
+ for (const event of events) host.event(target, event);
70501
+ }
70502
+ current.wake();
70503
+ return;
70504
+ }
70505
+ current.outbox.take();
70506
+ finish();
70507
+ } catch (error) {
70508
+ finish(error);
70509
+ }
70510
+ };
70511
+ current.wake = () => {
70512
+ if (queued) return;
70513
+ queued = true;
70514
+ queueMicrotask(sync);
70515
+ };
70516
+ current.wake();
70517
+ });
70518
+ }
70519
+ function status(current, ids) {
70520
+ return ids.flatMap((id) => {
70521
+ if (current.host.settled(id)) return [];
70522
+ const state = current.host.output(id) ? "is still running" : "has not started";
70523
+ const last = current.last.get(id);
70524
+ return [`${id} ${state}${last ? `; last ${last}` : ""}.`];
70525
+ });
70526
+ }
69690
70527
  return {
69691
- async at(document, time) {
70528
+ async at(document, time, view) {
69692
70529
  if (!Number.isFinite(time) || time < 0 || time > 6e5) throw new Error("Script export time must be between 0 and 600000 ms.");
69693
70530
  if (run && time < run.time) stop();
70531
+ const fresh = !run;
69694
70532
  const current = run ?? start();
69695
70533
  run = current;
69696
- current.time = time;
69697
70534
  const { host, outputs } = current;
69698
- const scene = buildBoardScene(document);
69699
- const ids = boardScriptAttachments(document).map(({ id }) => id);
69700
- await new Promise((resolve, reject) => {
69701
- const finish = (error) => {
69702
- clearTimeout(timer);
69703
- current.wake = () => {};
69704
- if (error) reject(error);
69705
- else resolve();
70535
+ if (options.documentAt) {
70536
+ let before = {
70537
+ at: current.time,
70538
+ document: options.documentAt(current.time)
69706
70539
  };
69707
- const timer = setTimeout(() => finish(/* @__PURE__ */ new Error("Script export preparation timed out.")), 2e4);
69708
- let queued = false;
69709
- const sync = () => {
69710
- queued = false;
69711
- try {
69712
- host.sync(document, scene, {
69713
- x: 0,
69714
- y: 0,
69715
- zoom: 1
69716
- }, time, false);
69717
- for (const id of ids) {
69718
- const error = host.error(id);
69719
- if (error) throw new Error(error);
69720
- }
69721
- if (ids.every((id) => host.settled(id))) finish();
69722
- } catch (error) {
69723
- finish(error);
70540
+ let previous = boardScriptParamsKey(before.document);
70541
+ let ran = current.time;
70542
+ if (fresh) await settle(current, before.document, before.at);
70543
+ for (let at = current.time + BOARD_SCRIPT_HISTORY_MS; at < time; at += BOARD_SCRIPT_HISTORY_MS) {
70544
+ const sample = options.documentAt(at);
70545
+ const key = boardScriptParamsKey(sample);
70546
+ if (key !== previous) {
70547
+ if (before.at > ran) await settle(current, before.document, before.at);
70548
+ await settle(current, sample, at);
70549
+ previous = key;
70550
+ ran = at;
69724
70551
  }
69725
- };
69726
- current.wake = () => {
69727
- if (queued) return;
69728
- queued = true;
69729
- queueMicrotask(sync);
69730
- };
69731
- current.wake();
69732
- });
70552
+ before = {
70553
+ at,
70554
+ document: sample
70555
+ };
70556
+ }
70557
+ if (boardScriptParamsKey(document) !== previous && before.at > ran) await settle(current, before.document, before.at);
70558
+ }
70559
+ await settle(current, document, time, view);
69733
70560
  return {
69734
70561
  ...host,
69735
70562
  shaders: (input) => boardShaderOwners(input, outputs, (id) => host.clock(id)),
@@ -69897,6 +70724,7 @@ function buildContext(input) {
69897
70724
  scene: input.scene,
69898
70725
  time: input.time ?? 0,
69899
70726
  frameAt: input.frameAt,
70727
+ ...input.page ? { page: input.page } : {},
69900
70728
  selectedIds: /* @__PURE__ */ new Set(),
69901
70729
  hoveredId: null,
69902
70730
  resizingIds: /* @__PURE__ */ new Set(),
@@ -69990,7 +70818,7 @@ function createBoardExportScene(input) {
69990
70818
  }
69991
70819
  root.addChild(world);
69992
70820
  const shaderErrors = [];
69993
- const layers = input.shaders?.owners.length ? input.shaders.layers ?? createBoardShaderLayers() : null;
70821
+ const layers = input.shaders?.owners.length ? input.shaders.layers ?? createBoardShaderLayers({ wait: true }) : null;
69994
70822
  if (layers && input.shaders) {
69995
70823
  const toOutput = [
69996
70824
  input.scale,
@@ -70012,10 +70840,12 @@ function createBoardExportScene(input) {
70012
70840
  const attach = (owner, layer) => {
70013
70841
  if (!layer) return null;
70014
70842
  if (owner.root) {
70015
- if (layer.container) (layer.layer === "below" ? below : above).addChild(layer.container);
70843
+ if (layer.below) below.addChild(layer.below);
70844
+ if (layer.above) above.addChild(layer.above);
70016
70845
  if (layer.filters) {
70017
70846
  filters.set(owner.id, layer.filters);
70018
70847
  setBoardShaderFilters(world, [...filters.values()].flat());
70848
+ world.filterArea = new Rectangle(input.world.x, input.world.y, input.world.width, input.world.height);
70019
70849
  }
70020
70850
  return {
70021
70851
  region: input.world,
@@ -70035,15 +70865,26 @@ function createBoardExportScene(input) {
70035
70865
  const container = containers.get(owner.id);
70036
70866
  if (!item || !container) return null;
70037
70867
  const group = isSelfGroupedFrame(item) ? groups.get(item.id)?.group : void 0;
70038
- if (layer.layer === "below" && layer.container) container.addChildAt(layer.container, 0);
70039
- if (layer.layer === "above" && layer.container) {
70868
+ for (const part of [layer.below, layer.above]) if (part && item.type === "frame") clipFrameShaderLayer(part, item);
70869
+ if (layer.below) container.addChildAt(layer.below, 0);
70870
+ if (layer.above) {
70040
70871
  if (group) {
70041
- positionShell(layer.container, item);
70042
- layer.container.zIndex = Number.MAX_SAFE_INTEGER;
70872
+ positionShell(layer.above, item);
70873
+ layer.above.zIndex = Number.MAX_SAFE_INTEGER;
70043
70874
  }
70044
- (group ?? container).addChild(layer.container);
70875
+ (group ?? container).addChild(layer.above);
70876
+ }
70877
+ if (layer.filters) {
70878
+ const host = group ?? container;
70879
+ setBoardShaderFilters(host, layer.filters);
70880
+ const box = group ? itemBounds(item.frame) : {
70881
+ x: 0,
70882
+ y: 0,
70883
+ width: item.frame.width,
70884
+ height: item.frame.height
70885
+ };
70886
+ host.filterArea = new Rectangle(box.x, box.y, box.width, box.height);
70045
70887
  }
70046
- if (layer.filters) setBoardShaderFilters(group ?? container, layer.filters);
70047
70888
  const localToWorld = boardItemLocalToWorld(item.frame);
70048
70889
  return {
70049
70890
  region: {
@@ -70176,6 +71017,7 @@ function renderBoardExport(renderer, input, options = {}) {
70176
71017
  colorScheme
70177
71018
  }),
70178
71019
  backdropTexture: options.backgroundTexture,
71020
+ ...plan.page ? { page: plan.page } : {},
70179
71021
  ...gpu && owners.length ? { shaders: {
70180
71022
  renderer,
70181
71023
  owners,
@@ -70228,6 +71070,10 @@ function renderBoardExport(renderer, input, options = {}) {
70228
71070
  kind: "shader-failed",
70229
71071
  ...failure
70230
71072
  });
71073
+ if (gpu) for (const miss of boardShaderMisses(scene, plan, owners, exportScene.shaderErrors)) warnings.push({
71074
+ kind: "shader-hidden",
71075
+ ...miss
71076
+ });
70231
71077
  return {
70232
71078
  canvas,
70233
71079
  plan,
@@ -70238,6 +71084,38 @@ function renderBoardExport(renderer, input, options = {}) {
70238
71084
  flattened?.();
70239
71085
  }
70240
71086
  }
71087
+ function boardShaderMisses(scene, plan, owners, failed = []) {
71088
+ const planned = new Set(plan.items.map((item) => item.id));
71089
+ const misses = owners.flatMap(({ id, root, output }) => {
71090
+ if (failed.some((failure) => failure.id === id)) return [];
71091
+ const shader = output.shader;
71092
+ if (shader && !shader.state && shader.passes.every((pass) => !boardShaderPassOn(pass, output.passes))) return [{
71093
+ id,
71094
+ reason: "every pass is switched off (ctx.passes() or enabled: false)"
71095
+ }];
71096
+ if (root) return [];
71097
+ const item = scene.get(id);
71098
+ if (!item) return [{
71099
+ id,
71100
+ reason: "its item is not in the document"
71101
+ }];
71102
+ if (scene.opacity(id) <= 0) return [{
71103
+ id,
71104
+ reason: "its item is hidden (opacity 0 or invisible)"
71105
+ }];
71106
+ if (planned.has(id)) return [];
71107
+ return [{
71108
+ id,
71109
+ reason: exportItemBounds(item, scene) ? "its item is outside the exported area" : "its item is clipped away by a parent frame"
71110
+ }];
71111
+ });
71112
+ const grouped = /* @__PURE__ */ new Map();
71113
+ for (const { id, reason } of misses) grouped.set(reason, [...grouped.get(reason) ?? [], id]);
71114
+ return [...grouped].map(([reason, ids]) => ({
71115
+ ids,
71116
+ reason
71117
+ }));
71118
+ }
70241
71119
  //#endregion
70242
71120
  //#region src/board-gpu/page.ts
70243
71121
  let renderer = null;
@@ -70305,7 +71183,7 @@ globalThis.cohubBoardGpu = {
70305
71183
  const target = await ensureRenderer();
70306
71184
  const errors = {};
70307
71185
  for (const { id, shader, parameters } of shaders) try {
70308
- createBoardShaderLayer(target, shader, boardShaderParameters(parameters), id).destroy();
71186
+ createBoardShaderLayer(target, shader, boardShaderParameters(parameters), id, { wait: true }).destroy();
70309
71187
  } catch (error) {
70310
71188
  errors[id] = error instanceof Error ? error.message : String(error);
70311
71189
  }
@@ -70316,22 +71194,215 @@ globalThis.cohubBoardGpu = {
70316
71194
  await document.fonts.ready;
70317
71195
  const board = normalizeBoardDocument(init.document);
70318
71196
  session?.scripts.dispose();
70319
- session?.layers.destroy();
71197
+ const layers = session?.layers ?? createBoardShaderLayers({ wait: true });
71198
+ layers.rewind();
71199
+ for (const [key, entry] of textures) if (!/^([a-z]+-)?url:/.test(key)) {
71200
+ entry?.texture.destroy(true);
71201
+ textures.delete(key);
71202
+ }
71203
+ background?.destroy(true);
71204
+ background = void 0;
71205
+ const sampler = createBoardRenderSampler(board, init.animation, boardRenderTheme(init.theme));
70320
71206
  session = {
70321
71207
  init: {
70322
71208
  ...init,
70323
71209
  document: board
70324
71210
  },
70325
- sampler: createBoardRenderSampler(board, init.animation, boardRenderTheme(init.theme)),
71211
+ sampler,
70326
71212
  scripts: createBrowserBoardScriptExport(async (path) => {
70327
71213
  const response = await fetch(`module?path=${encodeURIComponent(path)}`);
70328
71214
  if (!response.ok) throw new Error(`${path} is not available.`);
70329
71215
  return response.text();
71216
+ }, {
71217
+ ...init.snapshots ? { snapshots: init.snapshots } : {},
71218
+ ...init.animation && boardAnimatesScriptParams(board) ? { documentAt: (time) => sampler.at(time).document } : {}
70330
71219
  }),
70331
- layers: createBoardShaderLayers()
71220
+ layers
70332
71221
  };
70333
71222
  return { renderer: renderer.name };
70334
71223
  },
71224
+ async profile(input) {
71225
+ if (!renderer || !session) throw new Error("The GPU exporter is not ready.");
71226
+ const started = performance.now();
71227
+ const target = renderer;
71228
+ const { document, animation, theme: themeId } = session.init;
71229
+ const theme = boardRenderTheme(themeId);
71230
+ const at = input.time === null ? void 0 : {
71231
+ animation: animation ?? void 0,
71232
+ time: input.time
71233
+ };
71234
+ const time = input.time ?? 0;
71235
+ const sampler = session.sampler;
71236
+ const options = {
71237
+ sampler,
71238
+ region: input.region,
71239
+ camera: input.camera,
71240
+ scale: input.scale,
71241
+ padding: 0,
71242
+ ...at ? { at } : {}
71243
+ };
71244
+ const planned = prepareBoardExport(document, options);
71245
+ if (!planned) throw new Error("Nothing to profile: the region contains no items.");
71246
+ const scripts = await session.scripts.at(at ? sampler.at(time).document : document, time, boardExportView(planned.plan));
71247
+ const gl = target.gl;
71248
+ const info = gl.getExtension("WEBGL_debug_renderer_info");
71249
+ const rendererName = String(info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER));
71250
+ const prepared = prepareBoardExport(document, {
71251
+ ...options,
71252
+ scripts
71253
+ });
71254
+ if (!prepared) throw new Error("Nothing to profile: the region contains no items.");
71255
+ const visible = prepared.plan.items.filter((item) => prepared.scene.opacity(item.id) > 0);
71256
+ const loaded = input.withImages ? await loadTextures(visible, prepared.plan.scale, input.imageMemory, {}) : /* @__PURE__ */ new Map();
71257
+ const inside = new Set(prepared.plan.items.map((item) => item.id));
71258
+ const owners = (scripts.shaders?.(prepared.document, time) ?? []).filter((owner) => owner.root || inside.has(owner.id));
71259
+ const layers = createBoardShaderLayers({ wait: true });
71260
+ const scene = createBoardExportScene({
71261
+ settings: prepared.document.board,
71262
+ scene: prepared.scene,
71263
+ items: prepared.plan.items,
71264
+ time,
71265
+ frameAt: sampler.frameAt,
71266
+ world: prepared.plan.world,
71267
+ scale: prepared.plan.scale,
71268
+ colorScheme: theme.colorScheme,
71269
+ palette: theme.palette,
71270
+ colors: theme.colors,
71271
+ style: theme.style,
71272
+ textures: loaded,
71273
+ scripts,
71274
+ assetKey: boardAssetKey,
71275
+ ...prepared.plan.page ? { page: prepared.plan.page } : {},
71276
+ ...owners.length ? { shaders: {
71277
+ renderer: target,
71278
+ owners,
71279
+ layers
71280
+ } } : {}
71281
+ });
71282
+ const pixel = /* @__PURE__ */ new Uint8Array(4);
71283
+ let size = {
71284
+ width: prepared.plan.width,
71285
+ height: prepared.plan.height
71286
+ };
71287
+ let output = RenderTexture.create(size);
71288
+ let transform;
71289
+ const resize = (factor) => {
71290
+ output.destroy(true);
71291
+ size = {
71292
+ width: Math.max(1, Math.round(prepared.plan.width * factor)),
71293
+ height: Math.max(1, Math.round(prepared.plan.height * factor))
71294
+ };
71295
+ output = RenderTexture.create(size);
71296
+ transform = new Matrix().scale(factor, factor);
71297
+ };
71298
+ const render = () => {
71299
+ const start = performance.now();
71300
+ layers.prepare(target);
71301
+ target.render({
71302
+ container: scene.root,
71303
+ target: output,
71304
+ clear: true,
71305
+ ...transform ? { transform } : {}
71306
+ });
71307
+ gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
71308
+ return performance.now() - start;
71309
+ };
71310
+ try {
71311
+ render();
71312
+ const renders = (frames) => frames * input.rounds * (1 + owners.length);
71313
+ let frames = input.frames;
71314
+ let frameMs = Math.max(render(), .1);
71315
+ let reduced = null;
71316
+ let factor = 1;
71317
+ const budget = Math.max(input.budgetMs / 4, input.budgetMs - (performance.now() - started));
71318
+ for (let attempt = 0; attempt < 3 && frameMs * renders(frames) > budget; attempt++) {
71319
+ reduced ??= {
71320
+ ...size,
71321
+ frames,
71322
+ frameMs
71323
+ };
71324
+ frames = Math.max(3, Math.min(frames, Math.floor(budget / (frameMs * renders(1)))));
71325
+ const next = Math.max(factor * Math.sqrt(Math.min(1, budget / (frameMs * renders(frames)))), Math.min(1, 320 / Math.max(prepared.plan.width, prepared.plan.height)));
71326
+ if (next > factor * .98) break;
71327
+ factor = next;
71328
+ resize(factor);
71329
+ render();
71330
+ frameMs = Math.max(render(), .1);
71331
+ }
71332
+ const measure = () => {
71333
+ const samples = [];
71334
+ for (let frame = 0; frame < frames; frame++) samples.push(render());
71335
+ return samples.sort((a, b) => a - b);
71336
+ };
71337
+ const median = (samples) => [...samples].sort((a, b) => a - b)[Math.floor(samples.length / 2)] ?? 0;
71338
+ const all = [];
71339
+ const costs = new Map(owners.map((owner) => [owner.id, []]));
71340
+ const measuring = performance.now();
71341
+ let rounds = 0;
71342
+ for (; rounds < input.rounds; rounds++) {
71343
+ if (rounds && (performance.now() - measuring) * (rounds + 1) / rounds > budget * 1.25) break;
71344
+ const samples = measure();
71345
+ all.push(...samples);
71346
+ const base = median(samples);
71347
+ for (const owner of owners) {
71348
+ const layer = layers.layer(owner.id);
71349
+ const parts = [layer?.below, layer?.above].filter((part) => part !== null && part !== void 0);
71350
+ const filters = layer?.filters ?? [];
71351
+ const shown = parts.map((part) => part.visible);
71352
+ const enabled = filters.map((filter) => filter.enabled);
71353
+ for (const part of parts) part.visible = false;
71354
+ for (const filter of filters) filter.enabled = false;
71355
+ const without = median(measure());
71356
+ parts.forEach((part, index) => {
71357
+ part.visible = shown[index];
71358
+ });
71359
+ filters.forEach((filter, index) => {
71360
+ filter.enabled = enabled[index];
71361
+ });
71362
+ costs.get(owner.id)?.push(Math.max(0, base - without));
71363
+ }
71364
+ }
71365
+ all.sort((a, b) => a - b);
71366
+ const p50 = median(all);
71367
+ const results = owners.map((owner) => {
71368
+ const shader = owner.output.shader;
71369
+ const rounds = costs.get(owner.id) ?? [0];
71370
+ const filterPasses = shader?.passes.filter((pass) => (pass.layer ?? shader.layer) === "filter") ?? [];
71371
+ return {
71372
+ id: owner.id,
71373
+ ms: median(rounds),
71374
+ range: [Math.min(...rounds), Math.max(...rounds)],
71375
+ filter: !filterPasses.length ? "none" : filterPasses.every((pass) => pass.name) ? "switchable" : "always",
71376
+ sprites: shader?.passes.reduce((sum, pass) => sum + (pass.sprites ?? 0), 0) ?? 0,
71377
+ boxes: shader?.passes.filter((pass) => !pass.sprites && !pass.texel && (pass.layer ?? shader.layer) !== "filter").length ?? 0,
71378
+ state: shader?.state ? {
71379
+ width: shader.state.width,
71380
+ height: shader.state.height
71381
+ } : null
71382
+ };
71383
+ });
71384
+ return {
71385
+ renderer: rendererName,
71386
+ gpu: /swiftshader|llvmpipe|softpipe|software|basic render/i.test(rendererName) ? "software" : "hardware",
71387
+ ...size,
71388
+ frames,
71389
+ rounds,
71390
+ reduced,
71391
+ elapsedMs: performance.now() - started,
71392
+ frame: {
71393
+ p50,
71394
+ p95: all[Math.min(all.length - 1, Math.floor(all.length * .95))] ?? p50
71395
+ },
71396
+ owners: results.sort((a, b) => b.ms - a.ms),
71397
+ effects: visible.filter((item) => hasBoardEffects(item.style)).length,
71398
+ items: visible.length
71399
+ };
71400
+ } finally {
71401
+ output.destroy(true);
71402
+ scene.destroy();
71403
+ layers.destroy();
71404
+ }
71405
+ },
70335
71406
  async render(frame) {
70336
71407
  if (!renderer || !session) throw new Error("The GPU exporter is not ready.");
70337
71408
  const { document, animation, theme: themeId } = session.init;
@@ -70342,7 +71413,15 @@ globalThis.cohubBoardGpu = {
70342
71413
  };
70343
71414
  const time = frame.time ?? 0;
70344
71415
  const sample = at ? session.sampler.at(time).document : document;
70345
- const scripts = await session.scripts.at(sample, time);
71416
+ const planned = prepareBoardExport(document, {
71417
+ sampler: session.sampler,
71418
+ region: frame.region,
71419
+ camera: frame.camera,
71420
+ scale: frame.scale,
71421
+ padding: frame.padding,
71422
+ ...at ? { at } : {}
71423
+ });
71424
+ const scripts = await session.scripts.at(sample, time, planned ? boardExportView(planned.plan) : void 0);
70346
71425
  const options = {
70347
71426
  sampler: session.sampler,
70348
71427
  region: frame.region,