vizmatic 0.7.2 → 0.8.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.
@@ -1,3 +1,7 @@
1
+ import {
2
+ decodePng
3
+ } from "./chunk-YOP55T6W.js";
4
+
1
5
  // src/stage/look.ts
2
6
  var midnight = {
3
7
  name: "midnight",
@@ -981,869 +985,450 @@ var Track = class {
981
985
  }
982
986
  };
983
987
 
984
- // src/stage/display.ts
985
- var clockNow = () => clock.now;
986
- var ALONG_PIECE_LENGTH = 14;
987
- var MAX_ALONG_PIECES = 96;
988
- function worldPaint(paint, m) {
989
- if (!paint || !isGradient(paint)) return paint;
990
- if (paint.type === "linear") {
991
- return { ...paint, from: apply(m, paint.from[0], paint.from[1]), to: apply(m, paint.to[0], paint.to[1]) };
988
+ // src/stage/morph.ts
989
+ function growTo(r, target) {
990
+ const count = segmentCount(r);
991
+ if (count >= target || count === 0) return r;
992
+ const segments = [];
993
+ for (let i = 0; i < count; i++) {
994
+ const o = i * 6;
995
+ const pts = Array.from(r.p.subarray(o, o + 8));
996
+ segments.push({ pts, length: chord(pts) });
992
997
  }
993
- if (paint.type === "radial") {
994
- return { ...paint, center: apply(m, paint.center[0], paint.center[1]), radius: paint.radius * matScale(m) };
998
+ while (segments.length < target) {
999
+ let longest = 0;
1000
+ for (let i = 1; i < segments.length; i++) if (segments[i].length > segments[longest].length) longest = i;
1001
+ const [a, b] = bisect(segments[longest].pts);
1002
+ segments.splice(longest, 1, { pts: a, length: chord(a) }, { pts: b, length: chord(b) });
995
1003
  }
996
- return paint;
997
- }
998
- function sameMatrix(a, b) {
999
- return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5];
1000
- }
1001
- var worldCache = /* @__PURE__ */ new WeakMap();
1002
- function toWorld(node, path, m) {
1003
- const cached = worldCache.get(node);
1004
- if (cached && cached.path === path && sameMatrix(cached.matrix, m)) return cached.world;
1005
- const world = transformPath(path, m);
1006
- worldCache.set(node, { path, matrix: m, world });
1007
- return world;
1004
+ const out = new Float64Array(2 + target * 6);
1005
+ out[0] = r.p[0];
1006
+ out[1] = r.p[1];
1007
+ for (let i = 0; i < target; i++) {
1008
+ const pts = segments[i].pts;
1009
+ for (let k = 0; k < 6; k++) out[2 + i * 6 + k] = pts[2 + k];
1010
+ }
1011
+ return { p: out, closed: r.closed };
1008
1012
  }
1009
- function emit(node, path, m, alpha, ops) {
1010
- const fill = node.get("fill");
1011
- const stroke = node.get("stroke");
1012
- const fillAlpha = fill ? alpha * node.get("fillOpacity") : 0;
1013
- const strokeAlpha = stroke ? alpha * node.get("strokeOpacity") : 0;
1014
- const glow = node.get("glow");
1015
- if (fillAlpha <= 2e-3 && strokeAlpha <= 2e-3 && glow <= 0) return;
1016
- const world = toWorld(node, path, m);
1017
- const scale = matScale(m);
1018
- const trimFrom = node.get("trimFrom"), trimTo = node.get("trimTo");
1019
- let strokePath = world;
1020
- if (trimFrom > 0 || trimTo < 1) strokePath = trimPath(world, trimFrom, trimTo, node.get("trimEach"));
1021
- if (strokePath.length === 0 && fillAlpha <= 2e-3) return;
1022
- const dash = node.get("dash");
1023
- const op = {
1024
- kind: "path",
1025
- path: world,
1026
- strokePath,
1027
- fill: fillAlpha > 2e-3 ? worldPaint(fill, m) : null,
1028
- fillAlpha,
1029
- stroke: strokeAlpha > 2e-3 ? worldPaint(stroke, m) : null,
1030
- strokeAlpha,
1031
- strokeWidth: node.get("strokeWidth") * scale,
1032
- cap: node.get("cap"),
1033
- join: node.get("join"),
1034
- dash: dash ? dash.map((value) => value * scale) : null,
1035
- dashOffset: node.get("dashOffset") * scale,
1036
- glow: glow * scale,
1037
- glowColor: node.get("glowColor"),
1038
- blend: node.get("blend"),
1039
- node
1040
- };
1041
- if (op.stroke && isGradient(op.stroke) && op.stroke.type === "along") splitAlong(op, op.stroke, ops);
1042
- else ops.push(op);
1013
+ function chord(pts) {
1014
+ return Math.hypot(pts[2] - pts[0], pts[3] - pts[1]) + Math.hypot(pts[4] - pts[2], pts[5] - pts[3]) + Math.hypot(pts[6] - pts[4], pts[7] - pts[5]);
1043
1015
  }
1044
- function splitAlong(op, paint, ops) {
1045
- ops.push({ ...op, stroke: null, strokeAlpha: 0 });
1046
- const glowless = { ...op, fill: null, fillAlpha: 0, glow: 0 };
1047
- const length = pathLength(op.strokePath);
1048
- const full = pathLength(op.path);
1049
- if (length === 0) return;
1050
- const fraction = full > 0 ? Math.min(1, length / full) : 1;
1051
- const pieces = Math.min(MAX_ALONG_PIECES, Math.max(2, Math.ceil(length / ALONG_PIECE_LENGTH)));
1052
- const overlap = 0.6 / pieces;
1053
- for (let i = 0; i < pieces; i++) {
1054
- const from = i / pieces, to2 = Math.min(1, (i + 1) / pieces + overlap);
1055
- const piece = trimPath(op.strokePath, from, to2);
1056
- if (piece.length === 0) continue;
1057
- ops.push({
1058
- ...glowless,
1059
- strokePath: piece,
1060
- path: piece,
1061
- stroke: sampleStops(paint.stops, (i + 0.5) / pieces * fraction),
1062
- cap: i === 0 || i === pieces - 1 ? op.cap : "butt"
1063
- });
1064
- }
1016
+ function bisect(p) {
1017
+ const ax = (p[0] + p[2]) / 2, ay = (p[1] + p[3]) / 2;
1018
+ const bx = (p[2] + p[4]) / 2, by = (p[3] + p[5]) / 2;
1019
+ const cx = (p[4] + p[6]) / 2, cy = (p[5] + p[7]) / 2;
1020
+ const dx = (ax + bx) / 2, dy = (ay + by) / 2;
1021
+ const ex = (bx + cx) / 2, ey = (by + cy) / 2;
1022
+ const fx = (dx + ex) / 2, fy = (dy + ey) / 2;
1023
+ return [[p[0], p[1], ax, ay, dx, dy, fx, fy], [fx, fy, ex, ey, cx, cy, p[6], p[7]]];
1065
1024
  }
1066
- function walk(node, parent, screen, alpha, ops) {
1067
- if (!node.get("visible")) return;
1068
- const opacity = node.get("opacity") * alpha;
1069
- if (opacity <= 2e-3) return;
1070
- const base = node.get("fixed") ? screen : parent;
1071
- const m = mul(base, node.localMatrix());
1072
- const path = node.get("path");
1073
- if (path && path.length > 0) emit(node, path, m, opacity, ops);
1074
- const image = node.get("image");
1075
- if (image) ops.push({ kind: "image", image, matrix: m, alpha: opacity });
1076
- if (node.rawOps) node.rawOps(m, opacity, ops);
1077
- if (node.draw) {
1078
- const built = node.draw(clockNow());
1079
- if (built) {
1080
- const list2 = Array.isArray(built) ? built : [built];
1081
- for (const child of list2) walk(child, m, screen, opacity, ops);
1025
+ function bestRotation(a, b) {
1026
+ const count = segmentCount(b);
1027
+ if (!a.closed || !b.closed || count < 2) return b;
1028
+ const [ax, ay] = ringCenter(a), [bx, by] = ringCenter(b);
1029
+ const stride = Math.max(1, Math.floor(count / 48));
1030
+ let best = 0, bestCost = Infinity;
1031
+ for (let shift2 = 0; shift2 < count; shift2 += stride) {
1032
+ let cost = 0;
1033
+ for (let i = 0; i < count; i += stride) {
1034
+ const j = (i + shift2) % count;
1035
+ const dx = a.p[i * 6] - ax - (b.p[j * 6] - bx);
1036
+ const dy = a.p[i * 6 + 1] - ay - (b.p[j * 6 + 1] - by);
1037
+ cost += dx * dx + dy * dy;
1082
1038
  }
1083
- }
1084
- const children = node.children;
1085
- if (children.length === 0) return;
1086
- let sorted = false;
1087
- for (let i = 0; i < children.length; i++) {
1088
- if (children[i].get("z") !== 0) {
1089
- sorted = true;
1090
- break;
1039
+ if (cost < bestCost) {
1040
+ bestCost = cost;
1041
+ best = shift2;
1091
1042
  }
1092
1043
  }
1093
- const ordered = sorted ? children.map((child, index) => ({ child, index, z: child.get("z") })).sort((a, b) => a.z - b.z || a.index - b.index).map((entry) => entry.child) : children;
1094
- for (const child of ordered) walk(child, m, screen, opacity, ops);
1095
- }
1096
- function buildOps(root, camera, width, height) {
1097
- const screen = [1, 0, 0, 1, width / 2, height / 2];
1098
- const view = mul(screen, compose(0, 0, -camera.rotation, camera.zoom, camera.zoom, camera.x, camera.y));
1099
- const ops = [];
1100
- walk(root, view, screen, 1, ops);
1101
- return ops;
1102
- }
1103
- var GLOW_PASSES = 7;
1104
- function glowPasses(glow, width) {
1105
- const out = [];
1106
- for (let i = GLOW_PASSES; i >= 1; i--) {
1107
- const k = i / GLOW_PASSES;
1108
- out.push({ width: width + glow * 2 * k, alpha: 0.16 * (1 - k) * (1 - k) + 0.018 });
1044
+ if (best === 0) return b;
1045
+ const out = new Float64Array(b.p.length);
1046
+ out[0] = b.p[best * 6];
1047
+ out[1] = b.p[best * 6 + 1];
1048
+ for (let i = 0; i < count; i++) {
1049
+ const j = (i + best) % count;
1050
+ for (let k = 0; k < 6; k++) out[2 + i * 6 + k] = b.p[2 + j * 6 + k];
1109
1051
  }
1110
- return out;
1111
- }
1112
- function glowOf(op) {
1113
- if (op.glowColor) return op.glowColor;
1114
- const paint = op.stroke ?? op.fill;
1115
- if (!paint) return null;
1116
- return isGradient(paint) ? sampleStops(paint.stops, 0.5) : paint;
1052
+ return { p: out, closed: b.closed };
1117
1053
  }
1118
- var dCache = /* @__PURE__ */ new WeakMap();
1119
- function pathData(path) {
1120
- let d = dCache.get(path);
1121
- if (d === void 0) {
1122
- d = pathToD(path);
1123
- dCache.set(path, d);
1054
+ function pointRing(x, y, count, closed) {
1055
+ const out = new Float64Array(2 + count * 6);
1056
+ for (let i = 0; i < out.length; i += 2) {
1057
+ out[i] = x;
1058
+ out[i + 1] = y;
1124
1059
  }
1125
- return d;
1126
- }
1127
- function fmt2(value) {
1128
- return String(Math.round(value * 1e3) / 1e3);
1060
+ return { p: out, closed };
1129
1061
  }
1130
- function gradientDef(id, paint) {
1131
- const stops = paint.stops.map(([at, color]) => `<stop offset="${fmt2(at)}" stop-color="${css([color[0], color[1], color[2], 1])}"${color[3] < 1 ? ` stop-opacity="${fmt2(color[3])}"` : ""}/>`).join("");
1132
- if (paint.type === "linear") {
1133
- return `<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${fmt2(paint.from[0])}" y1="${fmt2(paint.from[1])}" x2="${fmt2(paint.to[0])}" y2="${fmt2(paint.to[1])}">${stops}</linearGradient>`;
1062
+ function pairRings(from, to2) {
1063
+ const rank = (path) => [...path].sort((a2, b2) => Math.abs(signedArea(b2)) + ringLength(b2) * 0.01 - (Math.abs(signedArea(a2)) + ringLength(a2) * 0.01));
1064
+ const a = rank(from), b = rank(to2);
1065
+ const pairs = [];
1066
+ const free = b.slice();
1067
+ for (const ringA of a) {
1068
+ if (free.length === 0) {
1069
+ const [x, y] = ringCenter(ringA);
1070
+ pairs.push([ringA, pointRing(x, y, segmentCount(ringA), ringA.closed)]);
1071
+ continue;
1072
+ }
1073
+ const [ax, ay] = ringCenter(ringA);
1074
+ let bestIndex = 0, bestCost = Infinity;
1075
+ for (let i = 0; i < Math.min(free.length, 3); i++) {
1076
+ const [bx, by] = ringCenter(free[i]);
1077
+ const cost = Math.hypot(ax - bx, ay - by) + i * 40;
1078
+ if (cost < bestCost) {
1079
+ bestCost = cost;
1080
+ bestIndex = i;
1081
+ }
1082
+ }
1083
+ pairs.push([ringA, free[bestIndex]]);
1084
+ free.splice(bestIndex, 1);
1134
1085
  }
1135
- if (paint.type === "radial") {
1136
- return `<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${fmt2(paint.center[0])}" cy="${fmt2(paint.center[1])}" r="${fmt2(paint.radius)}">${stops}</radialGradient>`;
1086
+ for (const ringB of free) {
1087
+ const [x, y] = ringCenter(ringB);
1088
+ pairs.push([pointRing(x, y, segmentCount(ringB), ringB.closed), ringB]);
1137
1089
  }
1138
- return "";
1090
+ return pairs;
1139
1091
  }
1140
- function strokeAttrs(op) {
1141
- let attrs = ` stroke-linecap="${op.cap}" stroke-linejoin="${op.join}"`;
1142
- if (op.dash) attrs += ` stroke-dasharray="${op.dash.map(fmt2).join(" ")}" stroke-dashoffset="${fmt2(op.dashOffset)}"`;
1143
- return attrs;
1092
+ function alignPaths(from, to2, minSegments = 12) {
1093
+ const pairs = pairRings(from, to2);
1094
+ const a = [], b = [], closed = [];
1095
+ for (const [ra, rb] of pairs) {
1096
+ const target = Math.max(segmentCount(ra), segmentCount(rb), ra.closed && rb.closed ? minSegments : 1);
1097
+ let x = growTo(ra, target);
1098
+ let y = growTo(rb, target);
1099
+ if (x.closed && y.closed) {
1100
+ if (Math.sign(signedArea(x)) !== Math.sign(signedArea(y)) && signedArea(x) !== 0 && signedArea(y) !== 0) y = reverseRing(y);
1101
+ y = bestRotation(x, y);
1102
+ } else if (!x.closed && !y.closed) {
1103
+ const n = x.p.length;
1104
+ const straight = Math.hypot(x.p[0] - y.p[0], x.p[1] - y.p[1]) + Math.hypot(x.p[n - 2] - y.p[n - 2], x.p[n - 1] - y.p[n - 1]);
1105
+ const flipped = Math.hypot(x.p[0] - y.p[n - 2], x.p[1] - y.p[n - 1]) + Math.hypot(x.p[n - 2] - y.p[0], x.p[n - 1] - y.p[1]);
1106
+ if (flipped < straight) y = reverseRing(y);
1107
+ }
1108
+ a.push(x.p);
1109
+ b.push(y.p);
1110
+ closed.push(x.closed && y.closed);
1111
+ }
1112
+ return { from: a, to: b, closed };
1144
1113
  }
1145
- function escapeAttr(value) {
1146
- return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
1147
- }
1148
- function frameToSvg(frame, options = {}) {
1149
- const scale = options.scale ?? 1;
1150
- const w = frame.width, h = frame.height;
1151
- const defs = [];
1152
- const body = [];
1153
- let gradientCount = 0;
1154
- const paintAttr = (paint, attr, alpha) => {
1155
- if (isGradient(paint)) {
1156
- const id = `g${gradientCount++}`;
1157
- defs.push(gradientDef(id, paint));
1158
- return `${attr}="url(#${id})"${alpha < 1 ? ` ${attr}-opacity="${fmt2(alpha)}"` : ""}`;
1114
+ function pathMixer(from, to2) {
1115
+ if (from === to2) return () => to2;
1116
+ if (pathLength(from) === 0 && from.length === 0) return (alpha) => alpha >= 1 ? to2 : from;
1117
+ const aligned = alignPaths(from, to2);
1118
+ return (alpha) => {
1119
+ if (alpha <= 0) return from;
1120
+ if (alpha >= 1) return to2;
1121
+ const rings = new Array(aligned.from.length);
1122
+ for (let r = 0; r < rings.length; r++) {
1123
+ const a = aligned.from[r], b = aligned.to[r];
1124
+ const out = new Float64Array(a.length);
1125
+ for (let i = 0; i < a.length; i++) out[i] = a[i] + (b[i] - a[i]) * alpha;
1126
+ rings[r] = { p: out, closed: aligned.closed[r] };
1159
1127
  }
1160
- const rgba = paint;
1161
- const a = rgba[3] * alpha;
1162
- return `${attr}="${css([rgba[0], rgba[1], rgba[2], 1])}"${a < 1 ? ` ${attr}-opacity="${fmt2(a)}"` : ""}`;
1128
+ return rings;
1163
1129
  };
1164
- if (frame.background && !options.transparent) body.push(`<rect width="${w}" height="${h}" fill="${frame.background}"/>`);
1165
- for (const op of frame.ops) {
1166
- if (op.kind === "image") {
1167
- const m = op.matrix;
1168
- body.push(`<image href="${escapeAttr(op.image.src)}" width="${op.image.width}" height="${op.image.height}" transform="matrix(${m.map(fmt2).join(" ")})"${op.alpha < 1 ? ` opacity="${fmt2(op.alpha)}"` : ""} preserveAspectRatio="none"/>`);
1169
- continue;
1170
- }
1171
- const style = op.blend !== "normal" ? ` style="mix-blend-mode:${op.blend}"` : "";
1172
- if (op.glow > 0) {
1173
- const color = glowOf(op);
1174
- const glowD = pathData(op.strokePath.length ? op.strokePath : op.path);
1175
- if (color && glowD) {
1176
- const base = Math.max(op.fillAlpha, op.strokeAlpha);
1177
- const mode = frame.dark ? ' style="mix-blend-mode:screen"' : "";
1178
- const passes = glowPasses(op.glow, op.stroke ? op.strokeWidth : 0).map((pass) => `<path d="${glowD}" fill="none" stroke="${css([color[0], color[1], color[2], 1])}" stroke-opacity="${fmt2(pass.alpha * base)}" stroke-width="${fmt2(pass.width)}" stroke-linecap="round" stroke-linejoin="round"/>`).join("");
1179
- body.push(`<g${mode}>${passes}</g>`);
1180
- }
1181
- }
1182
- if (op.fill && op.stroke && op.strokePath === op.path) {
1183
- body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill, "fill", op.fillAlpha)} ${paintAttr(op.stroke, "stroke", op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`);
1184
- continue;
1130
+ }
1131
+ function matchSequence(a, b) {
1132
+ const n = a.length, m = b.length;
1133
+ const table = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
1134
+ for (let i2 = n - 1; i2 >= 0; i2--) {
1135
+ for (let j2 = m - 1; j2 >= 0; j2--) {
1136
+ table[i2][j2] = a[i2] === b[j2] ? table[i2 + 1][j2 + 1] + 1 : Math.max(table[i2 + 1][j2], table[i2][j2 + 1]);
1185
1137
  }
1186
- if (op.fill) body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill, "fill", op.fillAlpha)}${style}/>`);
1187
- if (op.stroke && op.strokePath.length) {
1188
- body.push(`<path d="${pathData(op.strokePath)}" fill="none" ${paintAttr(op.stroke, "stroke", op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`);
1138
+ }
1139
+ const pairs = [];
1140
+ let i = 0, j = 0;
1141
+ while (i < n && j < m) {
1142
+ if (a[i] === b[j]) {
1143
+ pairs.push([i++, j++]);
1144
+ } else if (table[i + 1][j] >= table[i][j + 1]) {
1145
+ i++;
1146
+ } else {
1147
+ j++;
1189
1148
  }
1190
1149
  }
1191
- const defsBlock = defs.length ? `<defs>${defs.join("")}</defs>` : "";
1192
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${w * scale}" height="${h * scale}" viewBox="0 0 ${w} ${h}">${defsBlock}${body.join("")}</svg>`;
1150
+ return pairs;
1193
1151
  }
1194
- var path2dCache = /* @__PURE__ */ new WeakMap();
1195
- function ringsToPath2D(path) {
1196
- let cached = path2dCache.get(path);
1197
- if (cached) return cached;
1198
- cached = new Path2D();
1199
- for (const r of path) {
1200
- const p = r.p;
1201
- if (p.length < 2) continue;
1202
- cached.moveTo(p[0], p[1]);
1203
- if (r.straight) for (let o = 2; o + 5 < p.length; o += 6) cached.lineTo(p[o + 4], p[o + 5]);
1204
- else for (let o = 2; o + 5 < p.length; o += 6) cached.bezierCurveTo(p[o], p[o + 1], p[o + 2], p[o + 3], p[o + 4], p[o + 5]);
1205
- if (r.closed) cached.closePath();
1152
+
1153
+ // src/stage/node.ts
1154
+ var DEFAULT_PROPS = {
1155
+ x: 0,
1156
+ y: 0,
1157
+ rotation: 0,
1158
+ sx: 1,
1159
+ sy: 1,
1160
+ px: 0,
1161
+ py: 0,
1162
+ opacity: 1,
1163
+ visible: true,
1164
+ z: 0,
1165
+ path: null,
1166
+ fill: null,
1167
+ fillOpacity: 1,
1168
+ stroke: null,
1169
+ strokeOpacity: 1,
1170
+ strokeWidth: 3,
1171
+ cap: "round",
1172
+ join: "round",
1173
+ dash: null,
1174
+ dashOffset: 0,
1175
+ trimFrom: 0,
1176
+ trimTo: 1,
1177
+ trimEach: false,
1178
+ glow: 0,
1179
+ glowColor: null,
1180
+ blend: "normal",
1181
+ fixed: false,
1182
+ image: null
1183
+ };
1184
+ var NUMERIC = /* @__PURE__ */ new Set([
1185
+ "x",
1186
+ "y",
1187
+ "rotation",
1188
+ "sx",
1189
+ "sy",
1190
+ "px",
1191
+ "py",
1192
+ "opacity",
1193
+ "z",
1194
+ "fillOpacity",
1195
+ "strokeOpacity",
1196
+ "strokeWidth",
1197
+ "dashOffset",
1198
+ "trimFrom",
1199
+ "trimTo",
1200
+ "glow"
1201
+ ]);
1202
+ function mixer(prop, from, to2) {
1203
+ if (NUMERIC.has(prop)) {
1204
+ const a = from, b = to2;
1205
+ return ((alpha) => a + (b - a) * alpha);
1206
1206
  }
1207
- path2dCache.set(path, cached);
1208
- return cached;
1209
- }
1210
- function canvasPaint(ctx, paint) {
1211
- if (!isGradient(paint)) return css(paint);
1212
- const gradient = paint.type === "linear" ? ctx.createLinearGradient(paint.from[0], paint.from[1], paint.to[0], paint.to[1]) : paint.type === "radial" ? ctx.createRadialGradient(paint.center[0], paint.center[1], 0, paint.center[0], paint.center[1], paint.radius) : null;
1213
- if (!gradient) return css(sampleStops(paint.stops, 0.5));
1214
- for (const [at, color] of paint.stops) gradient.addColorStop(at, css(color));
1215
- return gradient;
1207
+ if (prop === "fill" || prop === "stroke") {
1208
+ const a = from, b = to2;
1209
+ if (a && b) return ((alpha) => mixPaint(a, b, alpha));
1210
+ return null;
1211
+ }
1212
+ if (prop === "glowColor") {
1213
+ const a = from, b = to2;
1214
+ if (a && b) return ((alpha) => mixColor(a, b, alpha));
1215
+ return null;
1216
+ }
1217
+ if (prop === "path") {
1218
+ const a = from, b = to2;
1219
+ if (a && b) return pathMixer(a, b);
1220
+ return null;
1221
+ }
1222
+ return null;
1216
1223
  }
1217
- var BLEND = {
1218
- normal: "source-over",
1219
- screen: "screen",
1220
- multiply: "multiply",
1221
- overlay: "overlay"
1222
- };
1223
- function paintFrame(ctx, frame, scale = 1, images) {
1224
- ctx.setTransform(1, 0, 0, 1, 0, 0);
1225
- ctx.globalAlpha = 1;
1226
- ctx.globalCompositeOperation = "source-over";
1227
- ctx.clearRect(0, 0, frame.width * scale, frame.height * scale);
1228
- ctx.setTransform(scale, 0, 0, scale, 0, 0);
1229
- if (frame.background) {
1230
- ctx.fillStyle = frame.background;
1231
- ctx.fillRect(0, 0, frame.width, frame.height);
1224
+ var nextId = 1;
1225
+ var Node = class _Node {
1226
+ id = nextId++;
1227
+ parent = null;
1228
+ children = [];
1229
+ /** Free-form metadata, such as the source character of a glyph. */
1230
+ data = {};
1231
+ /** Label shown in timelines and diagnostics. */
1232
+ label = "";
1233
+ base = Object.create(DEFAULT_PROPS);
1234
+ tracks = null;
1235
+ overlay = null;
1236
+ overlayFrame = -1;
1237
+ /** On stage: writes become timeline keys instead of initial state. */
1238
+ mounted = false;
1239
+ /** Rebuilt on every frame from timeline values. */
1240
+ draw = null;
1241
+ /** Emits draw operations directly, for objects with thousands of marks such as 3D meshes. */
1242
+ rawOps = null;
1243
+ constructor(path) {
1244
+ if (path) this.base.path = path;
1232
1245
  }
1233
- for (const op of frame.ops) {
1234
- if (op.kind === "image") {
1235
- const source = images?.(op.image);
1236
- if (!source) continue;
1237
- const m = op.matrix;
1238
- ctx.save();
1239
- ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
1240
- ctx.globalAlpha = op.alpha;
1241
- ctx.drawImage(source, 0, 0, op.image.width, op.image.height);
1242
- ctx.restore();
1243
- continue;
1246
+ // ── Raw property access ───────────────────────────────────────────────
1247
+ get(prop) {
1248
+ const overlay = this.overlay;
1249
+ if (overlay !== null && overlay.has(prop) && (this.overlayFrame === clock.frame || clock.capture !== null)) {
1250
+ return overlay.get(prop);
1244
1251
  }
1245
- ctx.globalCompositeOperation = BLEND[op.blend];
1246
- if (op.glow > 0) {
1247
- const color = glowOf(op);
1248
- if (color) {
1249
- const base = Math.max(op.fillAlpha, op.strokeAlpha);
1250
- const previous = ctx.globalCompositeOperation;
1251
- if (frame.dark) ctx.globalCompositeOperation = "screen";
1252
- ctx.strokeStyle = css([color[0], color[1], color[2], 1]);
1253
- ctx.lineCap = "round";
1254
- ctx.lineJoin = "round";
1255
- ctx.setLineDash([]);
1256
- const glowPath = ringsToPath2D(op.strokePath.length ? op.strokePath : op.path);
1257
- for (const pass of glowPasses(op.glow, op.stroke ? op.strokeWidth : 0)) {
1258
- ctx.globalAlpha = pass.alpha * base;
1259
- ctx.lineWidth = pass.width;
1260
- ctx.stroke(glowPath);
1261
- }
1262
- ctx.globalCompositeOperation = previous;
1263
- }
1252
+ const track = this.tracks?.get(prop);
1253
+ if (track) return track.sample(clock.now);
1254
+ return this.base[prop];
1255
+ }
1256
+ set(prop, value) {
1257
+ if (clock.capture) {
1258
+ this.overlay ??= /* @__PURE__ */ new Map();
1259
+ this.overlay.set(prop, value);
1260
+ clock.capture.add(this);
1261
+ return this;
1264
1262
  }
1265
- if (op.fill) {
1266
- ctx.globalAlpha = op.fillAlpha;
1267
- ctx.fillStyle = canvasPaint(ctx, op.fill);
1268
- ctx.fill(ringsToPath2D(op.path));
1263
+ if (!this.mounted) {
1264
+ this.base[prop] = value;
1265
+ return this;
1269
1266
  }
1270
- if (op.stroke && op.strokePath.length) {
1271
- ctx.globalAlpha = op.strokeAlpha;
1272
- ctx.strokeStyle = canvasPaint(ctx, op.stroke);
1273
- ctx.lineWidth = op.strokeWidth;
1274
- ctx.lineCap = op.cap;
1275
- ctx.lineJoin = op.join;
1276
- ctx.setLineDash(op.dash ? [...op.dash] : []);
1277
- ctx.lineDashOffset = op.dashOffset;
1278
- ctx.stroke(ringsToPath2D(op.strokePath));
1267
+ if (clock.mode === "render") {
1268
+ this.overlay ??= /* @__PURE__ */ new Map();
1269
+ if (this.overlayFrame !== clock.frame) {
1270
+ this.overlay.clear();
1271
+ this.overlayFrame = clock.frame;
1272
+ }
1273
+ this.overlay.set(prop, value);
1274
+ return this;
1279
1275
  }
1276
+ this.track(prop).step(clock.now, value);
1277
+ return this;
1280
1278
  }
1281
- ctx.globalAlpha = 1;
1282
- ctx.globalCompositeOperation = "source-over";
1283
- }
1284
- function frameInkBounds(frame) {
1285
- let result = null;
1286
- for (const op of frame.ops) {
1287
- if (op.kind !== "path") continue;
1288
- const b = pathBounds(op.path);
1289
- if (!b) continue;
1290
- const pad = op.stroke ? op.strokeWidth / 2 : 0;
1291
- const next = { x: b.x - pad, y: b.y - pad, width: b.width + pad * 2, height: b.height + pad * 2 };
1292
- if (!result) result = next;
1293
- else {
1294
- const x = Math.min(result.x, next.x), y = Math.min(result.y, next.y);
1295
- result = { x, y, width: Math.max(result.x + result.width, next.x + next.width) - x, height: Math.max(result.y + result.height, next.y + next.height) - y };
1279
+ track(prop) {
1280
+ this.tracks ??= /* @__PURE__ */ new Map();
1281
+ let track = this.tracks.get(prop);
1282
+ if (!track) {
1283
+ track = new Track(this.base[prop]);
1284
+ this.tracks.set(prop, track);
1296
1285
  }
1286
+ return track;
1297
1287
  }
1298
- return result;
1299
- }
1300
-
1301
- // src/stage/ease.ts
1302
- var clamp01 = (t) => t <= 0 ? 0 : t >= 1 ? 1 : t;
1303
- var linear = (t) => t;
1304
- function sigmoid(x) {
1305
- return 1 / (1 + Math.exp(-x));
1306
- }
1307
- function smoothBy(inflection) {
1308
- const low = sigmoid(-inflection / 2);
1309
- const high = sigmoid(inflection / 2);
1310
- return (t) => {
1311
- if (t <= 0) return 0;
1312
- if (t >= 1) return 1;
1313
- return (sigmoid(inflection * (t - 0.5)) - low) / (high - low);
1314
- };
1315
- }
1316
- var smooth = smoothBy(10);
1317
- var smoother = (t) => {
1318
- const x = clamp01(t);
1319
- return x * x * x * (x * (x * 6 - 15) + 10);
1320
- };
1321
- var easeInQuad = (t) => t * t;
1322
- var easeOutQuad = (t) => 1 - (1 - t) * (1 - t);
1323
- var easeInCubic = (t) => t * t * t;
1324
- var easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
1325
- var easeInOutCubic = (t) => t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
1326
- var easeOutQuint = (t) => 1 - Math.pow(1 - t, 5);
1327
- var easeInOutQuint = (t) => t < 0.5 ? 16 * t * t * t * t * t : 1 - Math.pow(-2 * t + 2, 5) / 2;
1328
- var easeOutExpo = (t) => t >= 1 ? 1 : 1 - Math.pow(2, -10 * t);
1329
- var easeInExpo = (t) => t <= 0 ? 0 : Math.pow(2, 10 * t - 10);
1330
- var rushInto = (t) => 2 * smooth(t / 2);
1331
- var rushFrom = (t) => 2 * smooth(t / 2 + 0.5) - 1;
1332
- var slowInto = (t) => Math.sqrt(Math.max(0, 1 - (1 - t) * (1 - t)));
1333
- function overshoot(amount = 1.70158) {
1334
- return (t) => {
1335
- const x = t - 1;
1336
- return x * x * ((amount + 1) * x + amount) + 1;
1337
- };
1338
- }
1339
- function spring(options = {}) {
1340
- const bounce2 = options.bounce ?? 0.28;
1341
- const frequency = options.frequency ?? 2.2;
1342
- const decay = -Math.log(Math.max(1e-4, bounce2)) * 2.4;
1343
- return (t) => {
1344
- if (t <= 0) return 0;
1345
- if (t >= 1) return 1;
1346
- return 1 - Math.exp(-decay * t) * Math.cos(frequency * Math.PI * 2 * t) * (1 - t);
1347
- };
1348
- }
1349
- var bounce = (t) => {
1350
- const n = 7.5625, d = 2.75;
1351
- if (t < 1 / d) return n * t * t;
1352
- if (t < 2 / d) return n * (t -= 1.5 / d) * t + 0.75;
1353
- if (t < 2.5 / d) return n * (t -= 2.25 / d) * t + 0.9375;
1354
- return n * (t -= 2.625 / d) * t + 0.984375;
1355
- };
1356
- var thereAndBack = (t) => smooth(t < 0.5 ? 2 * t : 2 * (1 - t));
1357
- function thereAndBackWithPause(pause = 1 / 3) {
1358
- const a = (1 - pause) / 2;
1359
- return (t) => {
1360
- if (t < a) return smooth(t / a);
1361
- if (t < 1 - a) return 1;
1362
- return smooth((1 - t) / a);
1363
- };
1364
- }
1365
- function wiggle(cycles = 2) {
1366
- return (t) => thereAndBack(t) * Math.sin(cycles * Math.PI * 2 * t);
1367
- }
1368
- function notQuiteThere(amount = 0.7, inner = smooth) {
1369
- return (t) => amount * inner(t);
1370
- }
1371
- function lingering(hold = 0.25, inner = smooth) {
1372
- return (t) => inner(clamp01(t / (1 - hold)));
1373
- }
1374
- function runningStart(pull = -0.5) {
1375
- return (t) => {
1376
- const u = 1 - t;
1377
- return 15 * u ** 4 * t ** 2 * pull + 20 * u ** 3 * t ** 3 * pull + 15 * u ** 2 * t ** 4 + 6 * u * t ** 5 + t ** 6;
1378
- };
1379
- }
1380
- function during(from, to2, inner = smooth) {
1381
- return (t) => inner(clamp01((t - from) / (to2 - from)));
1382
- }
1383
- function cubicBezier(x1, y1, x2, y2) {
1384
- const cx = 3 * x1, bx = 3 * (x2 - x1) - cx, ax = 1 - cx - bx;
1385
- const cy = 3 * y1, by = 3 * (y2 - y1) - cy, ay = 1 - cy - by;
1386
- const sampleX = (t) => ((ax * t + bx) * t + cx) * t;
1387
- const sampleY = (t) => ((ay * t + by) * t + cy) * t;
1388
- const slope = (t) => (3 * ax * t + 2 * bx) * t + cx;
1389
- return (x) => {
1390
- if (x <= 0) return 0;
1391
- if (x >= 1) return 1;
1392
- let t = x;
1393
- for (let i = 0; i < 8; i++) {
1394
- const dx = sampleX(t) - x;
1395
- const d = slope(t);
1396
- if (Math.abs(dx) < 1e-5 || Math.abs(d) < 1e-6) break;
1397
- t -= dx / d;
1288
+ /** Record a change from the current value to `to` over [t0, t1]. */
1289
+ tween(prop, to2, t0, t1, ease) {
1290
+ const previous = clock.now;
1291
+ clock.now = t0;
1292
+ const from = this.get(prop);
1293
+ clock.now = previous;
1294
+ const at = t1 > t0 ? mixer(prop, from, to2) : null;
1295
+ const key = { t0, t1, ease, to: to2, at };
1296
+ this.track(prop).add(key);
1297
+ }
1298
+ // ── Tree ──────────────────────────────────────────────────────────────
1299
+ add(...nodes) {
1300
+ for (const child of nodes) {
1301
+ if (child.parent === this) continue;
1302
+ child.parent?.drop(child);
1303
+ child.parent = this;
1304
+ this.children.push(child);
1305
+ if (this.mounted) mountTree(child, clock.now);
1398
1306
  }
1399
- return sampleY(t);
1400
- };
1401
- }
1402
-
1403
- // src/stage/morph.ts
1404
- function growTo(r, target) {
1405
- const count = segmentCount(r);
1406
- if (count >= target || count === 0) return r;
1407
- const segments = [];
1408
- for (let i = 0; i < count; i++) {
1409
- const o = i * 6;
1410
- const pts = Array.from(r.p.subarray(o, o + 8));
1411
- segments.push({ pts, length: chord(pts) });
1307
+ return this;
1412
1308
  }
1413
- while (segments.length < target) {
1414
- let longest = 0;
1415
- for (let i = 1; i < segments.length; i++) if (segments[i].length > segments[longest].length) longest = i;
1416
- const [a, b] = bisect(segments[longest].pts);
1417
- segments.splice(longest, 1, { pts: a, length: chord(a) }, { pts: b, length: chord(b) });
1309
+ drop(child) {
1310
+ const index = this.children.indexOf(child);
1311
+ if (index >= 0) this.children.splice(index, 1);
1312
+ child.parent = null;
1313
+ return this;
1418
1314
  }
1419
- const out = new Float64Array(2 + target * 6);
1420
- out[0] = r.p[0];
1421
- out[1] = r.p[1];
1422
- for (let i = 0; i < target; i++) {
1423
- const pts = segments[i].pts;
1424
- for (let k = 0; k < 6; k++) out[2 + i * 6 + k] = pts[2 + k];
1315
+ /** Self and all descendants, parents first. */
1316
+ all() {
1317
+ const out = [];
1318
+ const visit = (node) => {
1319
+ out.push(node);
1320
+ for (const child of node.children) visit(child);
1321
+ };
1322
+ visit(this);
1323
+ return out;
1425
1324
  }
1426
- return { p: out, closed: r.closed };
1427
- }
1428
- function chord(pts) {
1429
- return Math.hypot(pts[2] - pts[0], pts[3] - pts[1]) + Math.hypot(pts[4] - pts[2], pts[5] - pts[3]) + Math.hypot(pts[6] - pts[4], pts[7] - pts[5]);
1430
- }
1431
- function bisect(p) {
1432
- const ax = (p[0] + p[2]) / 2, ay = (p[1] + p[3]) / 2;
1433
- const bx = (p[2] + p[4]) / 2, by = (p[3] + p[5]) / 2;
1434
- const cx = (p[4] + p[6]) / 2, cy = (p[5] + p[7]) / 2;
1435
- const dx = (ax + bx) / 2, dy = (ay + by) / 2;
1436
- const ex = (bx + cx) / 2, ey = (by + cy) / 2;
1437
- const fx = (dx + ex) / 2, fy = (dy + ey) / 2;
1438
- return [[p[0], p[1], ax, ay, dx, dy, fx, fy], [fx, fy, ex, ey, cx, cy, p[6], p[7]]];
1439
- }
1440
- function bestRotation(a, b) {
1441
- const count = segmentCount(b);
1442
- if (!a.closed || !b.closed || count < 2) return b;
1443
- const [ax, ay] = ringCenter(a), [bx, by] = ringCenter(b);
1444
- const stride = Math.max(1, Math.floor(count / 48));
1445
- let best = 0, bestCost = Infinity;
1446
- for (let shift2 = 0; shift2 < count; shift2 += stride) {
1447
- let cost = 0;
1448
- for (let i = 0; i < count; i += stride) {
1449
- const j = (i + shift2) % count;
1450
- const dx = a.p[i * 6] - ax - (b.p[j * 6] - bx);
1451
- const dy = a.p[i * 6 + 1] - ay - (b.p[j * 6 + 1] - by);
1452
- cost += dx * dx + dy * dy;
1453
- }
1454
- if (cost < bestCost) {
1455
- bestCost = cost;
1456
- best = shift2;
1325
+ /** Descendants that draw something. A leaf group returns itself if it draws. */
1326
+ leaves() {
1327
+ return this.all().filter((node) => node.get("path") !== null || node.draw !== null || node.get("image") !== null);
1328
+ }
1329
+ /** A static copy of the current state, off stage. */
1330
+ clone() {
1331
+ const copy = Object.create(Object.getPrototypeOf(this));
1332
+ Object.assign(copy, this);
1333
+ copy.id = nextId++;
1334
+ copy.parent = null;
1335
+ copy.mounted = false;
1336
+ copy.tracks = null;
1337
+ copy.overlay = null;
1338
+ copy.overlayFrame = -1;
1339
+ copy.data = { ...this.data };
1340
+ copy.base = Object.create(DEFAULT_PROPS);
1341
+ for (const key of Object.keys(DEFAULT_PROPS)) {
1342
+ ;
1343
+ copy.base[key] = this.get(key);
1457
1344
  }
1345
+ copy.children = this.children.map((child) => {
1346
+ const next = child.clone();
1347
+ next.parent = copy;
1348
+ return next;
1349
+ });
1350
+ return copy;
1458
1351
  }
1459
- if (best === 0) return b;
1460
- const out = new Float64Array(b.p.length);
1461
- out[0] = b.p[best * 6];
1462
- out[1] = b.p[best * 6 + 1];
1463
- for (let i = 0; i < count; i++) {
1464
- const j = (i + best) % count;
1465
- for (let k = 0; k < 6; k++) out[2 + i * 6 + k] = b.p[2 + j * 6 + k];
1352
+ // ── Transforms ────────────────────────────────────────────────────────
1353
+ localMatrix() {
1354
+ return compose(this.get("x"), this.get("y"), this.get("rotation"), this.get("sx"), this.get("sy"), this.get("px"), this.get("py"));
1466
1355
  }
1467
- return { p: out, closed: b.closed };
1468
- }
1469
- function pointRing(x, y, count, closed) {
1470
- const out = new Float64Array(2 + count * 6);
1471
- for (let i = 0; i < out.length; i += 2) {
1472
- out[i] = x;
1473
- out[i + 1] = y;
1356
+ worldMatrix() {
1357
+ let m = this.localMatrix();
1358
+ for (let node = this.parent; node; node = node.parent) m = mul(node.localMatrix(), m);
1359
+ return m;
1474
1360
  }
1475
- return { p: out, closed };
1476
- }
1477
- function pairRings(from, to2) {
1478
- const rank = (path) => [...path].sort((a2, b2) => Math.abs(signedArea(b2)) + ringLength(b2) * 0.01 - (Math.abs(signedArea(a2)) + ringLength(a2) * 0.01));
1479
- const a = rank(from), b = rank(to2);
1480
- const pairs = [];
1481
- const free = b.slice();
1482
- for (const ringA of a) {
1483
- if (free.length === 0) {
1484
- const [x, y] = ringCenter(ringA);
1485
- pairs.push([ringA, pointRing(x, y, segmentCount(ringA), ringA.closed)]);
1486
- continue;
1361
+ toWorld(x, y) {
1362
+ return apply(this.worldMatrix(), x, y);
1363
+ }
1364
+ /** Stage-space bounds of this node and its descendants. */
1365
+ bounds() {
1366
+ return this.boundsFrom(this.parent ? this.parent.worldMatrix() : IDENTITY) ?? { x: 0, y: 0, width: 0, height: 0 };
1367
+ }
1368
+ boundsFrom(parent) {
1369
+ const m = mul(parent, this.localMatrix());
1370
+ let result = null;
1371
+ const path = this.get("path");
1372
+ if (path) result = pathBounds(transformPath(path, m));
1373
+ const image = this.get("image");
1374
+ if (image) result = unionBounds(result, boundsOfRect(m, image.width, image.height));
1375
+ if (this.draw) {
1376
+ const built = this.draw(clock.now);
1377
+ const list2 = built === null ? [] : Array.isArray(built) ? built : [built];
1378
+ for (const child of list2) result = unionBounds(result, child.boundsFrom(m));
1487
1379
  }
1488
- const [ax, ay] = ringCenter(ringA);
1489
- let bestIndex = 0, bestCost = Infinity;
1490
- for (let i = 0; i < Math.min(free.length, 3); i++) {
1491
- const [bx, by] = ringCenter(free[i]);
1492
- const cost = Math.hypot(ax - bx, ay - by) + i * 40;
1493
- if (cost < bestCost) {
1494
- bestCost = cost;
1495
- bestIndex = i;
1496
- }
1380
+ for (const child of this.children) {
1381
+ if (child.get("visible")) result = unionBounds(result, child.boundsFrom(m));
1497
1382
  }
1498
- pairs.push([ringA, free[bestIndex]]);
1499
- free.splice(bestIndex, 1);
1383
+ return result;
1500
1384
  }
1501
- for (const ringB of free) {
1502
- const [x, y] = ringCenter(ringB);
1503
- pairs.push([pointRing(x, y, segmentCount(ringB), ringB.closed), ringB]);
1385
+ get center() {
1386
+ const b = this.bounds();
1387
+ return [b.x + b.width / 2, b.y + b.height / 2];
1504
1388
  }
1505
- return pairs;
1506
- }
1507
- function alignPaths(from, to2, minSegments = 12) {
1508
- const pairs = pairRings(from, to2);
1509
- const a = [], b = [], closed = [];
1510
- for (const [ra, rb] of pairs) {
1511
- const target = Math.max(segmentCount(ra), segmentCount(rb), ra.closed && rb.closed ? minSegments : 1);
1512
- let x = growTo(ra, target);
1513
- let y = growTo(rb, target);
1514
- if (x.closed && y.closed) {
1515
- if (Math.sign(signedArea(x)) !== Math.sign(signedArea(y)) && signedArea(x) !== 0 && signedArea(y) !== 0) y = reverseRing(y);
1516
- y = bestRotation(x, y);
1517
- } else if (!x.closed && !y.closed) {
1518
- const n = x.p.length;
1519
- const straight = Math.hypot(x.p[0] - y.p[0], x.p[1] - y.p[1]) + Math.hypot(x.p[n - 2] - y.p[n - 2], x.p[n - 1] - y.p[n - 1]);
1520
- const flipped = Math.hypot(x.p[0] - y.p[n - 2], x.p[1] - y.p[n - 1]) + Math.hypot(x.p[n - 2] - y.p[0], x.p[n - 1] - y.p[1]);
1521
- if (flipped < straight) y = reverseRing(y);
1522
- }
1523
- a.push(x.p);
1524
- b.push(y.p);
1525
- closed.push(x.closed && y.closed);
1389
+ get top() {
1390
+ const b = this.bounds();
1391
+ return [b.x + b.width / 2, b.y];
1526
1392
  }
1527
- return { from: a, to: b, closed };
1528
- }
1529
- function pathMixer(from, to2) {
1530
- if (from === to2) return () => to2;
1531
- if (pathLength(from) === 0 && from.length === 0) return (alpha) => alpha >= 1 ? to2 : from;
1532
- const aligned = alignPaths(from, to2);
1533
- return (alpha) => {
1534
- if (alpha <= 0) return from;
1535
- if (alpha >= 1) return to2;
1536
- const rings = new Array(aligned.from.length);
1537
- for (let r = 0; r < rings.length; r++) {
1538
- const a = aligned.from[r], b = aligned.to[r];
1539
- const out = new Float64Array(a.length);
1540
- for (let i = 0; i < a.length; i++) out[i] = a[i] + (b[i] - a[i]) * alpha;
1541
- rings[r] = { p: out, closed: aligned.closed[r] };
1542
- }
1543
- return rings;
1544
- };
1545
- }
1546
- function matchSequence(a, b) {
1547
- const n = a.length, m = b.length;
1548
- const table = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
1549
- for (let i2 = n - 1; i2 >= 0; i2--) {
1550
- for (let j2 = m - 1; j2 >= 0; j2--) {
1551
- table[i2][j2] = a[i2] === b[j2] ? table[i2 + 1][j2 + 1] + 1 : Math.max(table[i2 + 1][j2], table[i2][j2 + 1]);
1552
- }
1393
+ get bottom() {
1394
+ const b = this.bounds();
1395
+ return [b.x + b.width / 2, b.y + b.height];
1553
1396
  }
1554
- const pairs = [];
1555
- let i = 0, j = 0;
1556
- while (i < n && j < m) {
1557
- if (a[i] === b[j]) {
1558
- pairs.push([i++, j++]);
1559
- } else if (table[i + 1][j] >= table[i][j + 1]) {
1560
- i++;
1561
- } else {
1562
- j++;
1563
- }
1397
+ get left() {
1398
+ const b = this.bounds();
1399
+ return [b.x, b.y + b.height / 2];
1564
1400
  }
1565
- return pairs;
1566
- }
1567
-
1568
- // src/stage/node.ts
1569
- var DEFAULT_PROPS = {
1570
- x: 0,
1571
- y: 0,
1572
- rotation: 0,
1573
- sx: 1,
1574
- sy: 1,
1575
- px: 0,
1576
- py: 0,
1577
- opacity: 1,
1578
- visible: true,
1579
- z: 0,
1580
- path: null,
1581
- fill: null,
1582
- fillOpacity: 1,
1583
- stroke: null,
1584
- strokeOpacity: 1,
1585
- strokeWidth: 3,
1586
- cap: "round",
1587
- join: "round",
1588
- dash: null,
1589
- dashOffset: 0,
1590
- trimFrom: 0,
1591
- trimTo: 1,
1592
- trimEach: false,
1593
- glow: 0,
1594
- glowColor: null,
1595
- blend: "normal",
1596
- fixed: false,
1597
- image: null
1598
- };
1599
- var NUMERIC = /* @__PURE__ */ new Set([
1600
- "x",
1601
- "y",
1602
- "rotation",
1603
- "sx",
1604
- "sy",
1605
- "px",
1606
- "py",
1607
- "opacity",
1608
- "z",
1609
- "fillOpacity",
1610
- "strokeOpacity",
1611
- "strokeWidth",
1612
- "dashOffset",
1613
- "trimFrom",
1614
- "trimTo",
1615
- "glow"
1616
- ]);
1617
- function mixer(prop, from, to2) {
1618
- if (NUMERIC.has(prop)) {
1619
- const a = from, b = to2;
1620
- return ((alpha) => a + (b - a) * alpha);
1401
+ get right() {
1402
+ const b = this.bounds();
1403
+ return [b.x + b.width, b.y + b.height / 2];
1621
1404
  }
1622
- if (prop === "fill" || prop === "stroke") {
1623
- const a = from, b = to2;
1624
- if (a && b) return ((alpha) => mixPaint(a, b, alpha));
1625
- return null;
1405
+ get width() {
1406
+ return this.bounds().width;
1626
1407
  }
1627
- if (prop === "glowColor") {
1628
- const a = from, b = to2;
1629
- if (a && b) return ((alpha) => mixColor(a, b, alpha));
1630
- return null;
1408
+ get height() {
1409
+ return this.bounds().height;
1631
1410
  }
1632
- if (prop === "path") {
1633
- const a = from, b = to2;
1634
- if (a && b) return pathMixer(a, b);
1635
- return null;
1411
+ /** Set the local position of the origin. */
1412
+ at(x, y) {
1413
+ const [px, py] = typeof x === "number" ? [x, y ?? 0] : x;
1414
+ this.set("x", px);
1415
+ this.set("y", py);
1416
+ return this;
1636
1417
  }
1637
- return null;
1638
- }
1639
- var nextId = 1;
1640
- var Node = class _Node {
1641
- id = nextId++;
1642
- parent = null;
1643
- children = [];
1644
- /** Free-form metadata, such as the source character of a glyph. */
1645
- data = {};
1646
- /** Label shown in timelines and diagnostics. */
1647
- label = "";
1648
- base = Object.create(DEFAULT_PROPS);
1649
- tracks = null;
1650
- overlay = null;
1651
- overlayFrame = -1;
1652
- /** On stage: writes become timeline keys instead of initial state. */
1653
- mounted = false;
1654
- /** Rebuilt on every frame from timeline values. */
1655
- draw = null;
1656
- /** Emits draw operations directly, for objects with thousands of marks such as 3D meshes. */
1657
- rawOps = null;
1658
- constructor(path) {
1659
- if (path) this.base.path = path;
1418
+ shift(dx, dy) {
1419
+ const [ox, oy] = typeof dx === "number" ? [dx, dy ?? 0] : dx;
1420
+ this.set("x", this.get("x") + ox);
1421
+ this.set("y", this.get("y") + oy);
1422
+ return this;
1660
1423
  }
1661
- // ── Raw property access ───────────────────────────────────────────────
1662
- get(prop) {
1663
- const overlay = this.overlay;
1664
- if (overlay !== null && overlay.has(prop) && (this.overlayFrame === clock.frame || clock.capture !== null)) {
1665
- return overlay.get(prop);
1666
- }
1667
- const track = this.tracks?.get(prop);
1668
- if (track) return track.sample(clock.now);
1669
- return this.base[prop];
1670
- }
1671
- set(prop, value) {
1672
- if (clock.capture) {
1673
- this.overlay ??= /* @__PURE__ */ new Map();
1674
- this.overlay.set(prop, value);
1675
- clock.capture.add(this);
1676
- return this;
1677
- }
1678
- if (!this.mounted) {
1679
- this.base[prop] = value;
1680
- return this;
1681
- }
1682
- if (clock.mode === "render") {
1683
- this.overlay ??= /* @__PURE__ */ new Map();
1684
- if (this.overlayFrame !== clock.frame) {
1685
- this.overlay.clear();
1686
- this.overlayFrame = clock.frame;
1687
- }
1688
- this.overlay.set(prop, value);
1689
- return this;
1690
- }
1691
- this.track(prop).step(clock.now, value);
1692
- return this;
1693
- }
1694
- track(prop) {
1695
- this.tracks ??= /* @__PURE__ */ new Map();
1696
- let track = this.tracks.get(prop);
1697
- if (!track) {
1698
- track = new Track(this.base[prop]);
1699
- this.tracks.set(prop, track);
1700
- }
1701
- return track;
1702
- }
1703
- /** Record a change from the current value to `to` over [t0, t1]. */
1704
- tween(prop, to2, t0, t1, ease) {
1705
- const previous = clock.now;
1706
- clock.now = t0;
1707
- const from = this.get(prop);
1708
- clock.now = previous;
1709
- const at = t1 > t0 ? mixer(prop, from, to2) : null;
1710
- const key = { t0, t1, ease, to: to2, at };
1711
- this.track(prop).add(key);
1712
- }
1713
- // ── Tree ──────────────────────────────────────────────────────────────
1714
- add(...nodes) {
1715
- for (const child of nodes) {
1716
- if (child.parent === this) continue;
1717
- child.parent?.drop(child);
1718
- child.parent = this;
1719
- this.children.push(child);
1720
- if (this.mounted) mountTree(child, clock.now);
1721
- }
1722
- return this;
1723
- }
1724
- drop(child) {
1725
- const index = this.children.indexOf(child);
1726
- if (index >= 0) this.children.splice(index, 1);
1727
- child.parent = null;
1728
- return this;
1729
- }
1730
- /** Self and all descendants, parents first. */
1731
- all() {
1732
- const out = [];
1733
- const visit = (node) => {
1734
- out.push(node);
1735
- for (const child of node.children) visit(child);
1736
- };
1737
- visit(this);
1738
- return out;
1739
- }
1740
- /** Descendants that draw something. A leaf group returns itself if it draws. */
1741
- leaves() {
1742
- return this.all().filter((node) => node.get("path") !== null || node.draw !== null || node.get("image") !== null);
1743
- }
1744
- /** A static copy of the current state, off stage. */
1745
- clone() {
1746
- const copy = Object.create(Object.getPrototypeOf(this));
1747
- Object.assign(copy, this);
1748
- copy.id = nextId++;
1749
- copy.parent = null;
1750
- copy.mounted = false;
1751
- copy.tracks = null;
1752
- copy.overlay = null;
1753
- copy.overlayFrame = -1;
1754
- copy.data = { ...this.data };
1755
- copy.base = Object.create(DEFAULT_PROPS);
1756
- for (const key of Object.keys(DEFAULT_PROPS)) {
1757
- ;
1758
- copy.base[key] = this.get(key);
1759
- }
1760
- copy.children = this.children.map((child) => {
1761
- const next = child.clone();
1762
- next.parent = copy;
1763
- return next;
1764
- });
1765
- return copy;
1766
- }
1767
- // ── Transforms ────────────────────────────────────────────────────────
1768
- localMatrix() {
1769
- return compose(this.get("x"), this.get("y"), this.get("rotation"), this.get("sx"), this.get("sy"), this.get("px"), this.get("py"));
1770
- }
1771
- worldMatrix() {
1772
- let m = this.localMatrix();
1773
- for (let node = this.parent; node; node = node.parent) m = mul(node.localMatrix(), m);
1774
- return m;
1775
- }
1776
- toWorld(x, y) {
1777
- return apply(this.worldMatrix(), x, y);
1778
- }
1779
- /** Stage-space bounds of this node and its descendants. */
1780
- bounds() {
1781
- return this.boundsFrom(this.parent ? this.parent.worldMatrix() : IDENTITY) ?? { x: 0, y: 0, width: 0, height: 0 };
1782
- }
1783
- boundsFrom(parent) {
1784
- const m = mul(parent, this.localMatrix());
1785
- let result = null;
1786
- const path = this.get("path");
1787
- if (path) result = pathBounds(transformPath(path, m));
1788
- const image = this.get("image");
1789
- if (image) result = unionBounds(result, boundsOfRect(m, image.width, image.height));
1790
- if (this.draw) {
1791
- const built = this.draw(clock.now);
1792
- const list2 = built === null ? [] : Array.isArray(built) ? built : [built];
1793
- for (const child of list2) result = unionBounds(result, child.boundsFrom(m));
1794
- }
1795
- for (const child of this.children) {
1796
- if (child.get("visible")) result = unionBounds(result, child.boundsFrom(m));
1797
- }
1798
- return result;
1799
- }
1800
- get center() {
1801
- const b = this.bounds();
1802
- return [b.x + b.width / 2, b.y + b.height / 2];
1803
- }
1804
- get top() {
1805
- const b = this.bounds();
1806
- return [b.x + b.width / 2, b.y];
1807
- }
1808
- get bottom() {
1809
- const b = this.bounds();
1810
- return [b.x + b.width / 2, b.y + b.height];
1811
- }
1812
- get left() {
1813
- const b = this.bounds();
1814
- return [b.x, b.y + b.height / 2];
1815
- }
1816
- get right() {
1817
- const b = this.bounds();
1818
- return [b.x + b.width, b.y + b.height / 2];
1819
- }
1820
- get width() {
1821
- return this.bounds().width;
1822
- }
1823
- get height() {
1824
- return this.bounds().height;
1825
- }
1826
- /** Set the local position of the origin. */
1827
- at(x, y) {
1828
- const [px, py] = typeof x === "number" ? [x, y ?? 0] : x;
1829
- this.set("x", px);
1830
- this.set("y", py);
1831
- return this;
1832
- }
1833
- shift(dx, dy) {
1834
- const [ox, oy] = typeof dx === "number" ? [dx, dy ?? 0] : dx;
1835
- this.set("x", this.get("x") + ox);
1836
- this.set("y", this.get("y") + oy);
1837
- return this;
1838
- }
1839
- /** Move so the center of the bounds lands on a stage point or on another node's center. */
1840
- moveTo(target) {
1841
- const destination = target instanceof _Node ? target.center : target;
1842
- const [cx, cy] = this.center;
1843
- const inverse = this.parent ? invert(this.parent.worldMatrix()) : IDENTITY;
1844
- const [lx0, ly0] = apply(inverse, cx, cy);
1845
- const [lx1, ly1] = apply(inverse, destination[0], destination[1]);
1846
- return this.shift(lx1 - lx0, ly1 - ly0);
1424
+ /** Move so the center of the bounds lands on a stage point or on another node's center. */
1425
+ moveTo(target) {
1426
+ const destination = target instanceof _Node ? target.center : target;
1427
+ const [cx, cy] = this.center;
1428
+ const inverse = this.parent ? invert(this.parent.worldMatrix()) : IDENTITY;
1429
+ const [lx0, ly0] = apply(inverse, cx, cy);
1430
+ const [lx1, ly1] = apply(inverse, destination[0], destination[1]);
1431
+ return this.shift(lx1 - lx0, ly1 - ly0);
1847
1432
  }
1848
1433
  /** Move the origin to a stage point without changing how anything looks. */
1849
1434
  pivotAt(point) {
@@ -1947,59 +1532,972 @@ var Node = class _Node {
1947
1532
  const paint = toPaint(color);
1948
1533
  this.set("glowColor", isGradient(paint) ? null : paint);
1949
1534
  }
1950
- return this;
1951
- }
1952
- dash(pattern, offset = 0) {
1953
- this.set("dash", pattern);
1954
- return this.set("dashOffset", offset);
1955
- }
1956
- zIndex(value) {
1957
- return this.set("z", value);
1535
+ return this;
1536
+ }
1537
+ dash(pattern, offset = 0) {
1538
+ this.set("dash", pattern);
1539
+ return this.set("dashOffset", offset);
1540
+ }
1541
+ zIndex(value) {
1542
+ return this.set("z", value);
1543
+ }
1544
+ /** Pin to the screen so the camera does not move this node. */
1545
+ pin() {
1546
+ return this.set("fixed", true);
1547
+ }
1548
+ hide() {
1549
+ return this.set("visible", false);
1550
+ }
1551
+ show() {
1552
+ return this.set("visible", true);
1553
+ }
1554
+ named(label) {
1555
+ this.label = label;
1556
+ return this;
1557
+ }
1558
+ };
1559
+ function boundsOfRect(m, width, height) {
1560
+ const corners = [apply(m, 0, 0), apply(m, width, 0), apply(m, width, height), apply(m, 0, height)];
1561
+ const xs = corners.map((c) => c[0]), ys = corners.map((c) => c[1]);
1562
+ const x = Math.min(...xs), y = Math.min(...ys);
1563
+ return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y };
1564
+ }
1565
+ function direction(side) {
1566
+ if (typeof side !== "string") return side;
1567
+ if (side === "left") return [-1, 0];
1568
+ if (side === "right") return [1, 0];
1569
+ if (side === "top" || side === "up") return [0, -1];
1570
+ return [0, 1];
1571
+ }
1572
+ function mountTree(node, time) {
1573
+ const wasVisible = node.base.visible;
1574
+ for (const entry of node.all()) entry.mounted = true;
1575
+ if (time > 0 || !wasVisible) {
1576
+ const track = node.track("visible");
1577
+ track.initial = false;
1578
+ if (wasVisible) track.step(time, true);
1579
+ }
1580
+ }
1581
+ function group(...children) {
1582
+ return new Node().add(...children);
1583
+ }
1584
+ function dynamic(build) {
1585
+ const node = new Node();
1586
+ node.draw = build;
1587
+ return node;
1588
+ }
1589
+
1590
+ // src/stage/image.ts
1591
+ import { Unzlib } from "fflate";
1592
+ var ImageAssetError = class extends Error {
1593
+ constructor(message) {
1594
+ super(message);
1595
+ this.name = "ImageAssetError";
1596
+ }
1597
+ };
1598
+ var MAX_BYTES = 16 * 1024 * 1024;
1599
+ var MAX_PIXELS = 16 * 1024 * 1024;
1600
+ var PREFIX = "data:image/png;base64,";
1601
+ var RUNTIME = /* @__PURE__ */ Symbol.for("vizmatic.stage.image.runtime.v1");
1602
+ var host = globalThis;
1603
+ var runtime = host[RUNTIME] ?? Object.freeze({ prepared: /* @__PURE__ */ new WeakSet(), browserSources: /* @__PURE__ */ new WeakMap() });
1604
+ if (!host[RUNTIME]) Object.defineProperty(host, RUNTIME, { value: runtime });
1605
+ var { prepared, browserSources } = runtime;
1606
+ var visibility = /* @__PURE__ */ new WeakMap();
1607
+ var VISIBILITY = /* @__PURE__ */ Symbol.for("vizmatic.stage.image.visibility.v1");
1608
+ function freezeAsset(fields, alpha) {
1609
+ if (alpha !== void 0) {
1610
+ const carried = typeof alpha === "boolean" ? alpha : Object.freeze({ width: alpha.width, height: alpha.height, bits: base64(alpha.mask) });
1611
+ Object.defineProperty(fields, VISIBILITY, { value: carried });
1612
+ visibility.set(fields, alpha);
1613
+ }
1614
+ return Object.freeze(fields);
1615
+ }
1616
+ function fail(message) {
1617
+ throw new ImageAssetError(message);
1618
+ }
1619
+ function base64(bytes) {
1620
+ const chunks = [];
1621
+ for (let at = 0; at < bytes.length; at += 8192) chunks.push(String.fromCharCode(...bytes.subarray(at, at + 8192)));
1622
+ return btoa(chunks.join(""));
1623
+ }
1624
+ function dataUri(bytes, mediaType = "image/png") {
1625
+ return `data:${mediaType};base64,${base64(bytes)}`;
1626
+ }
1627
+ async function sourceBytes(source, options) {
1628
+ if (source instanceof Uint8Array) {
1629
+ if (source.byteLength > MAX_BYTES) fail(`Image asset exceeds ${MAX_BYTES} encoded bytes.`);
1630
+ return Uint8Array.from(source);
1631
+ }
1632
+ if (typeof source !== "string" || !source) fail("Image asset needs encoded bytes, a PNG data URI, or a local filename.");
1633
+ if (source.startsWith("data:")) {
1634
+ if (!source.startsWith(PREFIX)) fail("Image assets currently support only image/png base64 data URIs.");
1635
+ const encoded = source.slice(PREFIX.length);
1636
+ if (!encoded.length || encoded.length > Math.ceil(MAX_BYTES / 3) * 4 || encoded.length % 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) fail("Image asset contains invalid or oversized base64 data.");
1637
+ const bytes = Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0));
1638
+ if (bytes.length > MAX_BYTES) fail(`Image asset exceeds ${MAX_BYTES} encoded bytes.`);
1639
+ return bytes;
1640
+ }
1641
+ if (/^[a-z][\w+.-]*:/i.test(source) || source.startsWith("//")) fail("Image assets must use local files or embedded bytes; remote URLs are not loaded.");
1642
+ if (typeof process === "undefined" || !process.versions?.node) fail("Resolve browser image assets from embedded bytes or a data URI before compiling.");
1643
+ const fsModule = "node:fs/promises", pathModule = "node:path";
1644
+ const [fs, path] = await Promise.all([import(fsModule), import(pathModule)]);
1645
+ const filename = path.resolve(options.baseDir ?? process.cwd(), source);
1646
+ try {
1647
+ if ((await fs.stat(filename)).size > MAX_BYTES) fail(`Image asset exceeds ${MAX_BYTES} encoded bytes: ${filename}`);
1648
+ const bytes = await fs.readFile(filename);
1649
+ if (bytes.length > MAX_BYTES) fail(`Image asset exceeds ${MAX_BYTES} encoded bytes: ${filename}`);
1650
+ return Uint8Array.from(bytes);
1651
+ } catch (error) {
1652
+ if (error instanceof ImageAssetError) throw error;
1653
+ fail(`Could not read image asset ${JSON.stringify(filename)}: ${error.message}`);
1654
+ }
1655
+ }
1656
+ function inspectPng(bytes, strict = true) {
1657
+ const signature = [137, 80, 78, 71, 13, 10, 26, 10];
1658
+ if (bytes.length < 33 || signature.some((value, i) => bytes[i] !== value)) fail("Image asset is not a PNG.");
1659
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1660
+ const name = (at) => String.fromCharCode(...bytes.subarray(at + 4, at + 8));
1661
+ if (view.getUint32(8) !== 13 || name(8) !== "IHDR") fail("Image PNG must begin with one IHDR chunk.");
1662
+ const width = view.getUint32(16), height = view.getUint32(20);
1663
+ if (!width || !height || width * height > MAX_PIXELS) fail(`Image PNG must contain at most ${MAX_PIXELS} pixels with positive dimensions.`);
1664
+ const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[bytes[25]];
1665
+ const depth = bytes[24], interlace = bytes[28];
1666
+ if (strict && (depth !== 8 || interlace !== 0)) {
1667
+ fail("Image assets support noninterlaced 8-bit PNGs, including RGB, RGBA, grayscale and palette images.");
1668
+ }
1669
+ const depths = bytes[25] === 0 ? [1, 2, 4, 8, 16] : bytes[25] === 3 ? [1, 2, 4, 8] : [8, 16];
1670
+ if (!channels || !depths.includes(depth) || bytes[26] !== 0 || bytes[27] !== 0 || interlace > 1) fail("Image PNG has unsupported header fields.");
1671
+ const passes = interlace ? [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]] : [[0, 0, 1, 1]];
1672
+ const expected = passes.reduce((sum, [x, y, dx, dy]) => {
1673
+ const w = Math.max(0, Math.ceil((width - x) / dx)), h = Math.max(0, Math.ceil((height - y) / dy));
1674
+ return sum + (w && h ? h * (1 + Math.ceil(w * channels * depth / 8)) : 0);
1675
+ }, 0);
1676
+ let expanded = 0, data = false, dataEnded = false, ended = false;
1677
+ const inflater = new Unzlib((chunk) => {
1678
+ expanded += chunk.length;
1679
+ if (expanded > expected) fail("Image PNG expands beyond its declared dimensions.");
1680
+ });
1681
+ for (let at = 8; at + 12 <= bytes.length; ) {
1682
+ const length = view.getUint32(at), type = name(at), end = at + length + 12;
1683
+ if (end > bytes.length) fail("Image PNG chunk exceeds the encoded bytes.");
1684
+ if (type === "IHDR" && at !== 8) fail("Image PNG has more than one IHDR chunk.");
1685
+ if (strict && ["iCCP", "acTL", "fcTL", "fdAT"].includes(type)) fail("Image assets do not support compressed color profiles or animated PNGs.");
1686
+ if (type === "iCCP") {
1687
+ let start = at + 8;
1688
+ while (start < end - 4 && bytes[start] !== 0) start++;
1689
+ if (start + 2 >= end - 4 || bytes[start + 1] !== 0) fail("Image PNG color profile is invalid.");
1690
+ let profileSize = 0;
1691
+ const profile = new Unzlib((chunk) => {
1692
+ profileSize += chunk.length;
1693
+ if (profileSize > MAX_BYTES) fail("Image PNG color profile exceeds the decoded byte limit.");
1694
+ });
1695
+ for (let part = start + 2; part < end - 4; part += 1024) profile.push(bytes.subarray(part, Math.min(part + 1024, end - 4)), false);
1696
+ profile.push(new Uint8Array(0), true);
1697
+ }
1698
+ if (type === "IDAT") {
1699
+ if (dataEnded) fail("Image PNG data chunks must be consecutive.");
1700
+ data = true;
1701
+ for (let part = at + 8; part < end - 4; part += 1024) inflater.push(bytes.subarray(part, Math.min(part + 1024, end - 4)), false);
1702
+ } else if (data) dataEnded = true;
1703
+ if (type === "IEND") {
1704
+ if (length || end !== bytes.length) fail("Image PNG has an invalid end chunk.");
1705
+ ended = true;
1706
+ break;
1707
+ }
1708
+ at = end;
1709
+ }
1710
+ if (!data || !ended) fail("Image PNG is missing its data or end chunk.");
1711
+ inflater.push(new Uint8Array(0), true);
1712
+ if (expanded !== expected) fail("Image PNG scanlines do not match its dimensions.");
1713
+ return { width, height };
1714
+ }
1715
+ async function resolveImageAsset(source, options = {}) {
1716
+ if (options.mediaType !== void 0 && options.mediaType !== "image/png") fail(`Unsupported image asset media type: ${options.mediaType}. Use image/png.`);
1717
+ if (options.sha256 !== void 0 && (typeof options.sha256 !== "string" || !/^[a-f\d]{64}$/i.test(options.sha256))) fail("Image asset SHA-256 must contain 64 hexadecimal digits.");
1718
+ if (options.id !== void 0 && (typeof options.id !== "string" || !options.id.trim())) fail("Image asset ID must be a nonempty string.");
1719
+ const bytes = await sourceBytes(source, options);
1720
+ let dimensions;
1721
+ let visible;
1722
+ try {
1723
+ dimensions = inspectPng(bytes);
1724
+ const decoded = decodePng(bytes, { checkCrc: true });
1725
+ visible = pngVisibility(decoded);
1726
+ if (decoded.width !== dimensions.width || decoded.height !== dimensions.height) fail("Decoded image dimensions differ from the PNG header.");
1727
+ } catch (error) {
1728
+ if (error instanceof ImageAssetError) throw error;
1729
+ fail(`Could not decode image asset: ${error.message}`);
1730
+ }
1731
+ for (const key of ["width", "height"]) {
1732
+ if (options[key] !== void 0 && options[key] !== dimensions[key]) fail(`Image asset ${key} is ${dimensions[key]}, not the declared ${options[key]}.`);
1733
+ }
1734
+ const hash = await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(bytes).buffer);
1735
+ const sha256 = Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, "0")).join("");
1736
+ if (options.sha256 !== void 0 && sha256 !== options.sha256.toLowerCase()) fail(`Image asset SHA-256 mismatch: expected ${options.sha256.toLowerCase()}, received ${sha256}.`);
1737
+ const asset = freezeAsset({ ...options.id ? { id: options.id } : {}, src: dataUri(bytes), mediaType: "image/png", ...dimensions, sha256 }, visible);
1738
+ await preloadBrowserImage(asset, bytes);
1739
+ prepared.add(asset);
1740
+ return asset;
1741
+ }
1742
+ async function preloadBrowserImage(asset, bytes) {
1743
+ const swapped = asset.mediaType === "image/jpeg" && jpegOrientation(bytes) >= 5;
1744
+ const width = swapped ? asset.height : asset.width, height = swapped ? asset.width : asset.height;
1745
+ if (asset.mediaType === "image/gif" && typeof createImageBitmap !== "undefined") {
1746
+ try {
1747
+ const bitmap = await createImageBitmap(new Blob([Uint8Array.from(bytes).buffer], { type: asset.mediaType }));
1748
+ if (bitmap.width !== width || bitmap.height !== height) fail("Browser image dimensions differ from the validated asset.");
1749
+ browserSources.set(asset, bitmap);
1750
+ } catch (error) {
1751
+ if (error instanceof ImageAssetError) throw error;
1752
+ fail(`Browser could not decode image asset: ${error.message}`);
1753
+ }
1754
+ } else if (typeof Image !== "undefined") {
1755
+ const element = new Image();
1756
+ element.src = asset.src;
1757
+ try {
1758
+ await element.decode();
1759
+ } catch (error) {
1760
+ fail(`Browser could not decode image asset: ${error.message}`);
1761
+ }
1762
+ if (element.naturalWidth !== width || element.naturalHeight !== height) fail("Browser image dimensions differ from the validated asset.");
1763
+ if (asset.mediaType === "image/gif") {
1764
+ const canvas = document.createElement("canvas");
1765
+ canvas.width = asset.width;
1766
+ canvas.height = asset.height;
1767
+ canvas.getContext("2d").drawImage(element, 0, 0);
1768
+ browserSources.set(asset, canvas);
1769
+ } else browserSources.set(asset, element);
1770
+ } else if (typeof createImageBitmap !== "undefined") {
1771
+ try {
1772
+ const bitmap = await createImageBitmap(new Blob([Uint8Array.from(bytes).buffer], { type: asset.mediaType }));
1773
+ if (bitmap.width !== width || bitmap.height !== height) fail("Browser image dimensions differ from the validated asset.");
1774
+ browserSources.set(asset, bitmap);
1775
+ } catch (error) {
1776
+ if (error instanceof ImageAssetError) throw error;
1777
+ fail(`Browser could not decode image asset: ${error.message}`);
1778
+ }
1779
+ }
1780
+ }
1781
+ function jpegOrientation(bytes) {
1782
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1783
+ for (let at = 2; at + 4 <= bytes.length; ) {
1784
+ if (bytes[at++] !== 255) break;
1785
+ while (bytes[at] === 255) at++;
1786
+ const marker = bytes[at++];
1787
+ if (marker === 218 || marker === 217 || at + 2 > bytes.length) break;
1788
+ const length = view.getUint16(at), start = at + 2, end = at + length;
1789
+ if (length < 2 || end > bytes.length) break;
1790
+ if (marker === 225 && end - start >= 14 && String.fromCharCode(...bytes.subarray(start, start + 6)) === "Exif\0\0") {
1791
+ const tiff = start + 6, order = view.getUint16(tiff), little = order === 18761;
1792
+ if (![18761, 19789].includes(order) || view.getUint16(tiff + 2, little) !== 42) return 1;
1793
+ const ifd = tiff + view.getUint32(tiff + 4, little);
1794
+ if (ifd < tiff + 8 || ifd + 2 > end) return 1;
1795
+ const count = view.getUint16(ifd, little);
1796
+ for (let entry = ifd + 2; entry + 12 <= end && entry < ifd + 2 + count * 12; entry += 12) {
1797
+ if (view.getUint16(entry, little) === 274 && view.getUint16(entry + 2, little) === 3 && view.getUint32(entry + 4, little) === 1) {
1798
+ const orientation = view.getUint16(entry + 8, little);
1799
+ return orientation >= 1 && orientation <= 8 ? orientation : 1;
1800
+ }
1801
+ }
1802
+ }
1803
+ at = end;
1804
+ }
1805
+ return 1;
1806
+ }
1807
+ async function resolveLegacyImage(source, allowNetwork) {
1808
+ let bytes, declared;
1809
+ if (source.startsWith("data:")) {
1810
+ const match = /^data:(image\/(?:png|jpe?g|gif));base64,([A-Za-z0-9+/]+={0,2})$/.exec(source);
1811
+ if (!match || match[2].length % 4 || match[2].length > Math.ceil(MAX_BYTES / 3) * 4) fail("Image contains invalid, unsupported or oversized base64 data.");
1812
+ declared = match[1] === "image/jpg" ? "image/jpeg" : match[1];
1813
+ bytes = Uint8Array.from(atob(match[2]), (character) => character.charCodeAt(0));
1814
+ } else if (/^https?:\/\//i.test(source) || source.startsWith("//") || typeof window !== "undefined") {
1815
+ const offline = typeof process !== "undefined" && (process.env?.VIZMATIC_DISABLE_NETWORK === "1" || process.env?.VIZMATIC_OFFLINE === "1");
1816
+ if (!allowNetwork || offline) fail("Network image loading is disabled by imageNetwork: deny or the offline environment.");
1817
+ try {
1818
+ const url = typeof document !== "undefined" ? new URL(source, document.baseURI).href : source;
1819
+ if (!/^https?:\/\//i.test(url)) fail("Network images require an HTTP or HTTPS URL.");
1820
+ const response = await fetch(url, { signal: AbortSignal.timeout(1e4) });
1821
+ if (!response.ok) fail(`Image request failed with HTTP ${response.status}: ${url}`);
1822
+ const length = response.headers.get("content-length");
1823
+ if (length && Number(length) > MAX_BYTES) fail(`Image exceeds ${MAX_BYTES} encoded bytes.`);
1824
+ declared = response.headers.get("content-type")?.split(";")[0].trim();
1825
+ const reader = response.body?.getReader();
1826
+ if (!reader) fail("Image request returned no body.");
1827
+ const chunks = [];
1828
+ let total = 0;
1829
+ for (; ; ) {
1830
+ const { value, done } = await reader.read();
1831
+ if (done) break;
1832
+ total += value.length;
1833
+ if (total > MAX_BYTES) {
1834
+ await reader.cancel();
1835
+ fail(`Image exceeds ${MAX_BYTES} encoded bytes.`);
1836
+ }
1837
+ chunks.push(value);
1838
+ }
1839
+ bytes = new Uint8Array(total);
1840
+ let at = 0;
1841
+ for (const chunk of chunks) {
1842
+ bytes.set(chunk, at);
1843
+ at += chunk.length;
1844
+ }
1845
+ } catch (error) {
1846
+ if (error instanceof ImageAssetError) throw error;
1847
+ fail(`Could not load image ${JSON.stringify(source)}: ${error.message}`);
1848
+ }
1849
+ } else bytes = await sourceBytes(source, {});
1850
+ const { visible, ...info } = legacyImageHeader(bytes);
1851
+ if (declared?.startsWith("image/") && declared !== info.mediaType) fail(`Image MIME type ${declared} does not match ${info.mediaType} bytes.`);
1852
+ const hash = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes).buffer);
1853
+ const sha256 = Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, "0")).join("");
1854
+ const asset = freezeAsset({ src: dataUri(bytes, info.mediaType), sha256, ...info }, visible);
1855
+ if (typeof process !== "undefined" && process.versions?.node) {
1856
+ const moduleName = "@resvg/resvg-js";
1857
+ const { Resvg } = await import(moduleName);
1858
+ try {
1859
+ const raster = new Resvg(`<svg xmlns="http://www.w3.org/2000/svg" width="${asset.width}" height="${asset.height}"><image width="${asset.width}" height="${asset.height}" href="${asset.src}"/></svg>`, { font: { loadSystemFonts: false } });
1860
+ if (!raster.innerBBox()) fail("Image decoder rejected the encoded image.");
1861
+ const rendered = raster.render();
1862
+ if (asset.mediaType === "image/jpeg" && !rendered.pixels.some((alpha, i) => i % 4 === 3 && alpha > 0)) fail("Image decoder rejected the JPEG pixel data.");
1863
+ } catch (error) {
1864
+ if (error instanceof ImageAssetError) throw error;
1865
+ fail(`Could not decode image: ${error.message}`);
1866
+ }
1867
+ }
1868
+ await preloadBrowserImage(asset, bytes);
1869
+ prepared.add(asset);
1870
+ return asset;
1871
+ }
1872
+ function legacyImageHeader(bytes) {
1873
+ if (!bytes.length || bytes.length > MAX_BYTES) fail("Image bytes are empty or oversized.");
1874
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1875
+ let width = 0, height = 0, mediaType;
1876
+ let visible;
1877
+ if (bytes.length >= 33 && [137, 80, 78, 71, 13, 10, 26, 10].every((v, i) => bytes[i] === v)) {
1878
+ mediaType = "image/png";
1879
+ try {
1880
+ ;
1881
+ ({ width, height } = inspectPng(bytes, false));
1882
+ visible = pngVisibility(decodePng(bytes, { checkCrc: true }));
1883
+ } catch (error) {
1884
+ if (error instanceof ImageAssetError) throw error;
1885
+ fail(`Could not decode image PNG: ${error.message}`);
1886
+ }
1887
+ } else if (bytes.length >= 14 && /^GIF8[79]a$/.test(String.fromCharCode(...bytes.subarray(0, 6)))) {
1888
+ width = view.getUint16(6, true);
1889
+ height = view.getUint16(8, true);
1890
+ mediaType = "image/gif";
1891
+ let at = 13 + (bytes[10] & 128 ? 3 * 2 ** ((bytes[10] & 7) + 1) : 0), frames = 0, ended = false;
1892
+ const blocks = (capture = false) => {
1893
+ const chunks = [];
1894
+ let total = 0;
1895
+ for (; ; ) {
1896
+ if (at >= bytes.length) fail("Image GIF data is truncated.");
1897
+ const length = bytes[at++];
1898
+ if (!length) break;
1899
+ if (capture) {
1900
+ chunks.push(bytes.subarray(at, at + length));
1901
+ total += length;
1902
+ }
1903
+ at += length;
1904
+ if (at > bytes.length) fail("Image GIF block exceeds the encoded bytes.");
1905
+ }
1906
+ const out = new Uint8Array(total);
1907
+ let offset = 0;
1908
+ for (const chunk of chunks) {
1909
+ out.set(chunk, offset);
1910
+ offset += chunk.length;
1911
+ }
1912
+ return out;
1913
+ };
1914
+ while (at < bytes.length) {
1915
+ const tag = bytes[at++];
1916
+ if (tag === 59) {
1917
+ ended = true;
1918
+ break;
1919
+ }
1920
+ if (tag === 33) {
1921
+ at++;
1922
+ blocks();
1923
+ } else if (tag === 44) {
1924
+ if (at + 9 > bytes.length) fail("Image GIF descriptor is truncated.");
1925
+ const fw = view.getUint16(at + 4, true), fh = view.getUint16(at + 6, true), flags = bytes[at + 8];
1926
+ if (!fw || !fh || fw * fh > MAX_PIXELS) fail("Image GIF frame dimensions are invalid.");
1927
+ at += 9 + (flags & 128 ? 3 * 2 ** ((flags & 7) + 1) : 0);
1928
+ if (bytes[at] < 2 || bytes[at] > 8) fail("Image GIF compression code size is invalid.");
1929
+ const codeSize = bytes[at++];
1930
+ validateGifData(blocks(true), codeSize, fw * fh);
1931
+ frames++;
1932
+ } else fail("Image GIF contains an invalid block.");
1933
+ }
1934
+ if (!frames || !ended) fail("Image GIF is missing its frame data or trailer.");
1935
+ } else if (bytes[0] === 255 && bytes[1] === 216) {
1936
+ mediaType = "image/jpeg";
1937
+ for (let at = 2; at + 3 < bytes.length; ) {
1938
+ if (bytes[at++] !== 255) fail("Image JPEG contains an invalid marker.");
1939
+ while (bytes[at] === 255) at++;
1940
+ if (at + 3 > bytes.length) fail("Image JPEG marker is truncated.");
1941
+ const marker = bytes[at++];
1942
+ if (marker === 218 || marker === 217) break;
1943
+ const length = view.getUint16(at);
1944
+ if (length < 2 || at + length > bytes.length) fail("Image JPEG segment is truncated.");
1945
+ if (marker >= 192 && marker <= 207 && ![196, 200, 204].includes(marker)) {
1946
+ if (length < 8) fail("Image JPEG frame is truncated.");
1947
+ height = view.getUint16(at + 3);
1948
+ width = view.getUint16(at + 5);
1949
+ }
1950
+ at += length;
1951
+ }
1952
+ if (!bytes.some((value, i) => i > 0 && value === 217 && bytes[i - 1] === 255)) fail("Image JPEG is missing its end marker.");
1953
+ } else fail("Image bytes are not a supported PNG, JPEG or GIF.");
1954
+ if (!width || !height || width * height > MAX_PIXELS) fail(`Image must contain at most ${MAX_PIXELS} pixels with positive dimensions.`);
1955
+ return { width, height, mediaType, visible };
1956
+ }
1957
+ function pngVisibility(png) {
1958
+ const { width, height, channels, depth, data, palette, transparency } = png;
1959
+ if (channels !== 2 && channels !== 4 && !palette && !transparency) return true;
1960
+ const mask = new Uint8Array(Math.ceil(width * height / 8));
1961
+ const sample = (x, y, channel = 0) => depth >= 8 ? data[(y * width + x) * channels + channel] : data[y * Math.ceil(width * depth / 8) + (x * depth >> 3)] >> 8 - depth - x * depth % 8 & (1 << depth) - 1;
1962
+ let count = 0;
1963
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
1964
+ let visible;
1965
+ if (channels === 2 || channels === 4) visible = sample(x, y, channels - 1) > 0;
1966
+ else if (palette) {
1967
+ const color = palette[sample(x, y)];
1968
+ if (!color) fail("Image PNG references a missing palette color.");
1969
+ visible = (color[3] ?? 255) > 0;
1970
+ } else visible = !transparency.every((value, channel) => sample(x, y, channel) === value);
1971
+ if (visible) {
1972
+ const index = y * width + x;
1973
+ mask[index >> 3] |= 1 << (index & 7);
1974
+ count++;
1975
+ }
1976
+ }
1977
+ return count === 0 ? false : count === width * height ? true : { width, height, mask, crops: /* @__PURE__ */ new Map() };
1978
+ }
1979
+ function imageHasVisiblePixels(asset, crop) {
1980
+ let value = asset ? visibility.get(asset) : void 0;
1981
+ if (value === void 0 && asset) {
1982
+ const carried = asset[VISIBILITY];
1983
+ value = typeof carried === "boolean" ? carried : carried ? { width: carried.width, height: carried.height, mask: Uint8Array.from(atob(carried.bits), (c) => c.charCodeAt(0)), crops: /* @__PURE__ */ new Map() } : void 0;
1984
+ if (value !== void 0) visibility.set(asset, value);
1985
+ }
1986
+ if (value === void 0) return true;
1987
+ if (typeof value === "boolean") return value;
1988
+ if (!crop || crop.x === 0 && crop.y === 0 && crop.width === value.width && crop.height === value.height) return true;
1989
+ const key = `${crop.x},${crop.y},${crop.width},${crop.height}`, cached = value.crops.get(key);
1990
+ if (cached !== void 0) return cached;
1991
+ for (let y = Math.floor(crop.y); y < Math.ceil(crop.y + crop.height); y++) for (let x = Math.floor(crop.x); x < Math.ceil(crop.x + crop.width); x++) {
1992
+ const index = y * value.width + x;
1993
+ if (value.mask[index >> 3] & 1 << (index & 7)) {
1994
+ value.crops.set(key, true);
1995
+ return true;
1996
+ }
1997
+ }
1998
+ value.crops.set(key, false);
1999
+ return false;
2000
+ }
2001
+ function validateGifData(data, minimum, pixels) {
2002
+ const clear = 1 << minimum, end = clear + 1, lengths = new Uint16Array(4096);
2003
+ let bits = minimum + 1, next = end + 1, previous = 0, offset = 0, written = 0;
2004
+ for (; ; ) {
2005
+ if (offset + bits > data.length * 8) fail("Image GIF compressed data is truncated.");
2006
+ let code = 0;
2007
+ for (let bit = 0; bit < bits; bit++) code |= (data[offset + bit >> 3] >> (offset + bit & 7) & 1) << bit;
2008
+ offset += bits;
2009
+ if (code === clear) {
2010
+ bits = minimum + 1;
2011
+ next = end + 1;
2012
+ previous = 0;
2013
+ continue;
2014
+ }
2015
+ if (code === end) {
2016
+ if (written !== pixels) fail("Image GIF decoded length does not match its frame dimensions.");
2017
+ return;
2018
+ }
2019
+ const length = code < clear ? 1 : code < next ? lengths[code] : code === next && previous ? previous + 1 : 0;
2020
+ if (!length) fail("Image GIF contains an invalid compression reference.");
2021
+ written += length;
2022
+ if (written > pixels) fail("Image GIF expands beyond its frame dimensions.");
2023
+ if (previous && next < 4096) {
2024
+ lengths[next++] = previous + 1;
2025
+ if (next === 1 << bits && bits < 12) bits++;
2026
+ }
2027
+ previous = length;
2028
+ }
2029
+ }
2030
+ function isImageAsset(value) {
2031
+ return !!value && typeof value === "object" && prepared.has(value);
2032
+ }
2033
+ function browserImageSource(asset) {
2034
+ return asset ? browserSources.get(asset) : void 0;
2035
+ }
2036
+ function validateStageImage(value, asset) {
2037
+ if (![value.width, value.height].every((n) => Number.isFinite(n) && n > 0)) fail("Image destination dimensions must be positive finite numbers.");
2038
+ const crop = value.crop;
2039
+ if (crop && (![crop.x, crop.y, crop.width, crop.height].every(Number.isFinite) || crop.x < 0 || crop.y < 0 || crop.width <= 0 || crop.height <= 0 || crop.x + crop.width > asset.width || crop.y + crop.height > asset.height)) {
2040
+ fail("Image crop must be a nonempty region inside the intrinsic image pixels.");
2041
+ }
2042
+ }
2043
+ function imageFromAsset(asset, options = {}) {
2044
+ if (!isImageAsset(asset)) fail("Call and await resolveImageAsset before creating an image node.");
2045
+ if (options.fit !== void 0 && options.fit !== "contain" && options.fit !== "cover") fail("Image fit must be contain or cover.");
2046
+ let crop = { ...options.crop ?? { x: 0, y: 0, width: asset.width, height: asset.height } };
2047
+ let width = options.width ?? (options.height === void 0 ? crop.width : options.height * crop.width / crop.height);
2048
+ let height = options.height ?? width * crop.height / crop.width;
2049
+ validateStageImage({ src: asset.src, width, height, crop }, asset);
2050
+ if (options.fit === "cover") {
2051
+ const ratio = width / height, sourceRatio = crop.width / crop.height;
2052
+ if (sourceRatio > ratio) {
2053
+ const next = crop.height * ratio;
2054
+ crop = { ...crop, x: crop.x + (crop.width - next) / 2, width: next };
2055
+ } else {
2056
+ const next = crop.width / ratio;
2057
+ crop = { ...crop, y: crop.y + (crop.height - next) / 2, height: next };
2058
+ }
2059
+ } else {
2060
+ const scale = Math.min(width / crop.width, height / crop.height);
2061
+ width = crop.width * scale;
2062
+ height = crop.height * scale;
2063
+ }
2064
+ const node = new Node().set("image", Object.freeze({ src: asset.src, width, height, crop: Object.freeze(crop), asset }));
2065
+ node.set("px", width / 2).set("py", height / 2);
2066
+ node.label = asset.id ?? "image";
2067
+ return node;
2068
+ }
2069
+
2070
+ // src/stage/display.ts
2071
+ var clockNow = () => clock.now;
2072
+ var ALONG_PIECE_LENGTH = 14;
2073
+ var MAX_ALONG_PIECES = 96;
2074
+ function worldPaint(paint, m) {
2075
+ if (!paint || !isGradient(paint)) return paint;
2076
+ if (paint.type === "linear") {
2077
+ return { ...paint, from: apply(m, paint.from[0], paint.from[1]), to: apply(m, paint.to[0], paint.to[1]) };
2078
+ }
2079
+ if (paint.type === "radial") {
2080
+ return { ...paint, center: apply(m, paint.center[0], paint.center[1]), radius: paint.radius * matScale(m) };
2081
+ }
2082
+ return paint;
2083
+ }
2084
+ function sameMatrix(a, b) {
2085
+ return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5];
2086
+ }
2087
+ var worldCache = /* @__PURE__ */ new WeakMap();
2088
+ function toWorld(node, path, m) {
2089
+ const cached = worldCache.get(node);
2090
+ if (cached && cached.path === path && sameMatrix(cached.matrix, m)) return cached.world;
2091
+ const world = transformPath(path, m);
2092
+ worldCache.set(node, { path, matrix: m, world });
2093
+ return world;
2094
+ }
2095
+ function emit(node, path, m, alpha, ops) {
2096
+ const fill = node.get("fill");
2097
+ const stroke = node.get("stroke");
2098
+ const fillAlpha = fill ? alpha * node.get("fillOpacity") : 0;
2099
+ const strokeAlpha = stroke ? alpha * node.get("strokeOpacity") : 0;
2100
+ const glow = node.get("glow");
2101
+ if (fillAlpha <= 2e-3 && strokeAlpha <= 2e-3 && glow <= 0) return;
2102
+ const world = toWorld(node, path, m);
2103
+ const scale = matScale(m);
2104
+ const trimFrom = node.get("trimFrom"), trimTo = node.get("trimTo");
2105
+ let strokePath = world;
2106
+ if (trimFrom > 0 || trimTo < 1) strokePath = trimPath(world, trimFrom, trimTo, node.get("trimEach"));
2107
+ if (strokePath.length === 0 && fillAlpha <= 2e-3) return;
2108
+ const dash = node.get("dash");
2109
+ const op = {
2110
+ kind: "path",
2111
+ path: world,
2112
+ strokePath,
2113
+ fill: fillAlpha > 2e-3 ? worldPaint(fill, m) : null,
2114
+ fillAlpha,
2115
+ stroke: strokeAlpha > 2e-3 ? worldPaint(stroke, m) : null,
2116
+ strokeAlpha,
2117
+ strokeWidth: node.get("strokeWidth") * scale,
2118
+ cap: node.get("cap"),
2119
+ join: node.get("join"),
2120
+ dash: dash ? dash.map((value) => value * scale) : null,
2121
+ dashOffset: node.get("dashOffset") * scale,
2122
+ glow: glow * scale,
2123
+ glowColor: node.get("glowColor"),
2124
+ blend: node.get("blend"),
2125
+ node
2126
+ };
2127
+ if (op.stroke && isGradient(op.stroke) && op.stroke.type === "along") splitAlong(op, op.stroke, ops);
2128
+ else ops.push(op);
2129
+ }
2130
+ function splitAlong(op, paint, ops) {
2131
+ ops.push({ ...op, stroke: null, strokeAlpha: 0 });
2132
+ const glowless = { ...op, fill: null, fillAlpha: 0, glow: 0 };
2133
+ const length = pathLength(op.strokePath);
2134
+ const full = pathLength(op.path);
2135
+ if (length === 0) return;
2136
+ const fraction = full > 0 ? Math.min(1, length / full) : 1;
2137
+ const pieces = Math.min(MAX_ALONG_PIECES, Math.max(2, Math.ceil(length / ALONG_PIECE_LENGTH)));
2138
+ const overlap = 0.6 / pieces;
2139
+ for (let i = 0; i < pieces; i++) {
2140
+ const from = i / pieces, to2 = Math.min(1, (i + 1) / pieces + overlap);
2141
+ const piece = trimPath(op.strokePath, from, to2);
2142
+ if (piece.length === 0) continue;
2143
+ ops.push({
2144
+ ...glowless,
2145
+ strokePath: piece,
2146
+ path: piece,
2147
+ stroke: sampleStops(paint.stops, (i + 0.5) / pieces * fraction),
2148
+ cap: i === 0 || i === pieces - 1 ? op.cap : "butt"
2149
+ });
2150
+ }
2151
+ }
2152
+ function walk(node, parent, screen, alpha, ops) {
2153
+ if (!node.get("visible")) return;
2154
+ const opacity = node.get("opacity") * alpha;
2155
+ if (opacity <= 2e-3) return;
2156
+ const base = node.get("fixed") ? screen : parent;
2157
+ const m = mul(base, node.localMatrix());
2158
+ const path = node.get("path");
2159
+ if (path && path.length > 0) emit(node, path, m, opacity, ops);
2160
+ const image = node.get("image");
2161
+ if (image) ops.push({ kind: "image", image, matrix: m, alpha: opacity, node });
2162
+ if (node.rawOps) node.rawOps(m, opacity, ops);
2163
+ if (node.draw) {
2164
+ const built = node.draw(clockNow());
2165
+ if (built) {
2166
+ const list2 = Array.isArray(built) ? built : [built];
2167
+ for (const child of list2) walk(child, m, screen, opacity, ops);
2168
+ }
2169
+ }
2170
+ const children = node.children;
2171
+ if (children.length === 0) return;
2172
+ let sorted = false;
2173
+ for (let i = 0; i < children.length; i++) {
2174
+ if (children[i].get("z") !== 0) {
2175
+ sorted = true;
2176
+ break;
2177
+ }
2178
+ }
2179
+ const ordered = sorted ? children.map((child, index) => ({ child, index, z: child.get("z") })).sort((a, b) => a.z - b.z || a.index - b.index).map((entry) => entry.child) : children;
2180
+ for (const child of ordered) walk(child, m, screen, opacity, ops);
2181
+ }
2182
+ function buildOps(root, camera, width, height) {
2183
+ const screen = [1, 0, 0, 1, width / 2, height / 2];
2184
+ const view = mul(screen, compose(0, 0, -camera.rotation, camera.zoom, camera.zoom, camera.x, camera.y));
2185
+ const ops = [];
2186
+ walk(root, view, screen, 1, ops);
2187
+ return ops;
2188
+ }
2189
+ var GLOW_PASSES = 7;
2190
+ function glowPasses(glow, width) {
2191
+ const out = [];
2192
+ for (let i = GLOW_PASSES; i >= 1; i--) {
2193
+ const k = i / GLOW_PASSES;
2194
+ out.push({ width: width + glow * 2 * k, alpha: 0.16 * (1 - k) * (1 - k) + 0.018 });
2195
+ }
2196
+ return out;
2197
+ }
2198
+ function glowOf(op) {
2199
+ if (op.glowColor) return op.glowColor;
2200
+ const paint = op.stroke ?? op.fill;
2201
+ if (!paint) return null;
2202
+ return isGradient(paint) ? sampleStops(paint.stops, 0.5) : paint;
2203
+ }
2204
+ var dCache = /* @__PURE__ */ new WeakMap();
2205
+ function pathData(path) {
2206
+ let d = dCache.get(path);
2207
+ if (d === void 0) {
2208
+ d = pathToD(path);
2209
+ dCache.set(path, d);
2210
+ }
2211
+ return d;
2212
+ }
2213
+ function fmt2(value) {
2214
+ return String(Math.round(value * 1e3) / 1e3);
2215
+ }
2216
+ function gradientDef(id, paint) {
2217
+ const stops = paint.stops.map(([at, color]) => `<stop offset="${fmt2(at)}" stop-color="${css([color[0], color[1], color[2], 1])}"${color[3] < 1 ? ` stop-opacity="${fmt2(color[3])}"` : ""}/>`).join("");
2218
+ if (paint.type === "linear") {
2219
+ return `<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${fmt2(paint.from[0])}" y1="${fmt2(paint.from[1])}" x2="${fmt2(paint.to[0])}" y2="${fmt2(paint.to[1])}">${stops}</linearGradient>`;
2220
+ }
2221
+ if (paint.type === "radial") {
2222
+ return `<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${fmt2(paint.center[0])}" cy="${fmt2(paint.center[1])}" r="${fmt2(paint.radius)}">${stops}</radialGradient>`;
2223
+ }
2224
+ return "";
2225
+ }
2226
+ function strokeAttrs(op) {
2227
+ let attrs = ` stroke-linecap="${op.cap}" stroke-linejoin="${op.join}"`;
2228
+ if (op.dash) attrs += ` stroke-dasharray="${op.dash.map(fmt2).join(" ")}" stroke-dashoffset="${fmt2(op.dashOffset)}"`;
2229
+ return attrs;
2230
+ }
2231
+ function escapeAttr(value) {
2232
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
2233
+ }
2234
+ function frameToSvg(frame, options = {}) {
2235
+ const scale = options.scale ?? 1;
2236
+ const w = frame.width, h = frame.height;
2237
+ const defs = [];
2238
+ const body = [];
2239
+ let gradientCount = 0;
2240
+ const paintAttr = (paint, attr, alpha) => {
2241
+ if (isGradient(paint)) {
2242
+ const id = `g${gradientCount++}`;
2243
+ defs.push(gradientDef(id, paint));
2244
+ return `${attr}="url(#${id})"${alpha < 1 ? ` ${attr}-opacity="${fmt2(alpha)}"` : ""}`;
2245
+ }
2246
+ const rgba = paint;
2247
+ const a = rgba[3] * alpha;
2248
+ return `${attr}="${css([rgba[0], rgba[1], rgba[2], 1])}"${a < 1 ? ` ${attr}-opacity="${fmt2(a)}"` : ""}`;
2249
+ };
2250
+ if (frame.background && !options.transparent) body.push(`<rect width="${w}" height="${h}" fill="${frame.background}"/>`);
2251
+ for (const op of frame.ops) {
2252
+ if (op.kind === "image") {
2253
+ const m = op.matrix;
2254
+ const { image } = op, crop = image.crop;
2255
+ if (crop && !image.asset) throw new ImageAssetError("Cropped image SVG needs a prepared image asset.");
2256
+ const picture = `<image href="${escapeAttr(image.src)}" width="${crop ? image.asset.width : image.width}" height="${crop ? image.asset.height : image.height}" preserveAspectRatio="none"/>`;
2257
+ const content = crop ? `<svg width="${fmt2(image.width)}" height="${fmt2(image.height)}" viewBox="${[crop.x, crop.y, crop.width, crop.height].map(fmt2).join(" ")}" preserveAspectRatio="none" overflow="hidden">${picture}</svg>` : picture;
2258
+ body.push(`<g transform="matrix(${m.map(fmt2).join(" ")})"${op.alpha < 1 ? ` opacity="${fmt2(op.alpha)}"` : ""}>${content}</g>`);
2259
+ continue;
2260
+ }
2261
+ const style = op.blend !== "normal" ? ` style="mix-blend-mode:${op.blend}"` : "";
2262
+ if (op.glow > 0) {
2263
+ const color = glowOf(op);
2264
+ const glowD = pathData(op.strokePath.length ? op.strokePath : op.path);
2265
+ if (color && glowD) {
2266
+ const base = Math.max(op.fillAlpha, op.strokeAlpha);
2267
+ const mode = frame.dark ? ' style="mix-blend-mode:screen"' : "";
2268
+ const passes = glowPasses(op.glow, op.stroke ? op.strokeWidth : 0).map((pass) => `<path d="${glowD}" fill="none" stroke="${css([color[0], color[1], color[2], 1])}" stroke-opacity="${fmt2(pass.alpha * base)}" stroke-width="${fmt2(pass.width)}" stroke-linecap="round" stroke-linejoin="round"/>`).join("");
2269
+ body.push(`<g${mode}>${passes}</g>`);
2270
+ }
2271
+ }
2272
+ if (op.fill && op.stroke && op.strokePath === op.path) {
2273
+ body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill, "fill", op.fillAlpha)} ${paintAttr(op.stroke, "stroke", op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`);
2274
+ continue;
2275
+ }
2276
+ if (op.fill) body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill, "fill", op.fillAlpha)}${style}/>`);
2277
+ if (op.stroke && op.strokePath.length) {
2278
+ body.push(`<path d="${pathData(op.strokePath)}" fill="none" ${paintAttr(op.stroke, "stroke", op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`);
2279
+ }
1958
2280
  }
1959
- /** Pin to the screen so the camera does not move this node. */
1960
- pin() {
1961
- return this.set("fixed", true);
2281
+ const defsBlock = defs.length ? `<defs>${defs.join("")}</defs>` : "";
2282
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${w * scale}" height="${h * scale}" viewBox="0 0 ${w} ${h}">${defsBlock}${body.join("")}</svg>`;
2283
+ }
2284
+ var path2dCache = /* @__PURE__ */ new WeakMap();
2285
+ function ringsToPath2D(path) {
2286
+ let cached = path2dCache.get(path);
2287
+ if (cached) return cached;
2288
+ cached = new Path2D();
2289
+ for (const r of path) {
2290
+ const p = r.p;
2291
+ if (p.length < 2) continue;
2292
+ cached.moveTo(p[0], p[1]);
2293
+ if (r.straight) for (let o = 2; o + 5 < p.length; o += 6) cached.lineTo(p[o + 4], p[o + 5]);
2294
+ else for (let o = 2; o + 5 < p.length; o += 6) cached.bezierCurveTo(p[o], p[o + 1], p[o + 2], p[o + 3], p[o + 4], p[o + 5]);
2295
+ if (r.closed) cached.closePath();
1962
2296
  }
1963
- hide() {
1964
- return this.set("visible", false);
2297
+ path2dCache.set(path, cached);
2298
+ return cached;
2299
+ }
2300
+ function canvasPaint(ctx, paint) {
2301
+ if (!isGradient(paint)) return css(paint);
2302
+ const gradient = paint.type === "linear" ? ctx.createLinearGradient(paint.from[0], paint.from[1], paint.to[0], paint.to[1]) : paint.type === "radial" ? ctx.createRadialGradient(paint.center[0], paint.center[1], 0, paint.center[0], paint.center[1], paint.radius) : null;
2303
+ if (!gradient) return css(sampleStops(paint.stops, 0.5));
2304
+ for (const [at, color] of paint.stops) gradient.addColorStop(at, css(color));
2305
+ return gradient;
2306
+ }
2307
+ var BLEND = {
2308
+ normal: "source-over",
2309
+ screen: "screen",
2310
+ multiply: "multiply",
2311
+ overlay: "overlay"
2312
+ };
2313
+ function paintFrame(ctx, frame, scale = 1, images) {
2314
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
2315
+ ctx.globalAlpha = 1;
2316
+ ctx.globalCompositeOperation = "source-over";
2317
+ ctx.clearRect(0, 0, frame.width * scale, frame.height * scale);
2318
+ ctx.setTransform(scale, 0, 0, scale, 0, 0);
2319
+ if (frame.background) {
2320
+ ctx.fillStyle = frame.background;
2321
+ ctx.fillRect(0, 0, frame.width, frame.height);
1965
2322
  }
1966
- show() {
1967
- return this.set("visible", true);
2323
+ for (const op of frame.ops) {
2324
+ if (op.kind === "image") {
2325
+ const source = images?.(op.image) ?? browserImageSource(op.image.asset);
2326
+ if (!source) throw new ImageAssetError("Image pixels are unavailable. Await image preparation and provide an ImageLookup outside the browser.");
2327
+ const m = op.matrix;
2328
+ ctx.save();
2329
+ ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
2330
+ ctx.globalAlpha = op.alpha;
2331
+ ctx.globalCompositeOperation = "source-over";
2332
+ const crop = op.image.crop;
2333
+ if (crop) ctx.drawImage(source, crop.x, crop.y, crop.width, crop.height, 0, 0, op.image.width, op.image.height);
2334
+ else ctx.drawImage(source, 0, 0, op.image.width, op.image.height);
2335
+ ctx.restore();
2336
+ continue;
2337
+ }
2338
+ ctx.globalCompositeOperation = BLEND[op.blend];
2339
+ if (op.glow > 0) {
2340
+ const color = glowOf(op);
2341
+ if (color) {
2342
+ const base = Math.max(op.fillAlpha, op.strokeAlpha);
2343
+ const previous = ctx.globalCompositeOperation;
2344
+ if (frame.dark) ctx.globalCompositeOperation = "screen";
2345
+ ctx.strokeStyle = css([color[0], color[1], color[2], 1]);
2346
+ ctx.lineCap = "round";
2347
+ ctx.lineJoin = "round";
2348
+ ctx.setLineDash([]);
2349
+ const glowPath = ringsToPath2D(op.strokePath.length ? op.strokePath : op.path);
2350
+ for (const pass of glowPasses(op.glow, op.stroke ? op.strokeWidth : 0)) {
2351
+ ctx.globalAlpha = pass.alpha * base;
2352
+ ctx.lineWidth = pass.width;
2353
+ ctx.stroke(glowPath);
2354
+ }
2355
+ ctx.globalCompositeOperation = previous;
2356
+ }
2357
+ }
2358
+ if (op.fill) {
2359
+ ctx.globalAlpha = op.fillAlpha;
2360
+ ctx.fillStyle = canvasPaint(ctx, op.fill);
2361
+ ctx.fill(ringsToPath2D(op.path));
2362
+ }
2363
+ if (op.stroke && op.strokePath.length) {
2364
+ ctx.globalAlpha = op.strokeAlpha;
2365
+ ctx.strokeStyle = canvasPaint(ctx, op.stroke);
2366
+ ctx.lineWidth = op.strokeWidth;
2367
+ ctx.lineCap = op.cap;
2368
+ ctx.lineJoin = op.join;
2369
+ ctx.setLineDash(op.dash ? [...op.dash] : []);
2370
+ ctx.lineDashOffset = op.dashOffset;
2371
+ ctx.stroke(ringsToPath2D(op.strokePath));
2372
+ }
1968
2373
  }
1969
- named(label) {
1970
- this.label = label;
1971
- return this;
2374
+ ctx.globalAlpha = 1;
2375
+ ctx.globalCompositeOperation = "source-over";
2376
+ }
2377
+ function frameInkBounds(frame) {
2378
+ let result = null;
2379
+ for (const op of frame.ops) {
2380
+ if (op.kind === "image" && !imageHasVisiblePixels(op.image.asset, op.image.crop)) continue;
2381
+ const b = op.kind === "image" ? imageOpBounds(op) : pathBounds(op.path);
2382
+ if (!b) continue;
2383
+ const pad = op.kind === "path" && op.stroke ? op.strokeWidth / 2 : 0;
2384
+ const next = { x: b.x - pad, y: b.y - pad, width: b.width + pad * 2, height: b.height + pad * 2 };
2385
+ if (!result) result = next;
2386
+ else {
2387
+ const x = Math.min(result.x, next.x), y = Math.min(result.y, next.y);
2388
+ result = { x, y, width: Math.max(result.x + result.width, next.x + next.width) - x, height: Math.max(result.y + result.height, next.y + next.height) - y };
2389
+ }
1972
2390
  }
1973
- };
1974
- function boundsOfRect(m, width, height) {
1975
- const corners = [apply(m, 0, 0), apply(m, width, 0), apply(m, width, height), apply(m, 0, height)];
1976
- const xs = corners.map((c) => c[0]), ys = corners.map((c) => c[1]);
2391
+ return result;
2392
+ }
2393
+ function imageOpBounds(op) {
2394
+ const { width, height } = op.image;
2395
+ const corners = [[0, 0], [width, 0], [0, height], [width, height]].map(([x2, y2]) => apply(op.matrix, x2, y2));
2396
+ const xs = corners.map((p) => p[0]), ys = corners.map((p) => p[1]);
1977
2397
  const x = Math.min(...xs), y = Math.min(...ys);
1978
2398
  return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y };
1979
2399
  }
1980
- function direction(side) {
1981
- if (typeof side !== "string") return side;
1982
- if (side === "left") return [-1, 0];
1983
- if (side === "right") return [1, 0];
1984
- if (side === "top" || side === "up") return [0, -1];
1985
- return [0, 1];
2400
+
2401
+ // src/stage/ease.ts
2402
+ var clamp01 = (t) => t <= 0 ? 0 : t >= 1 ? 1 : t;
2403
+ var linear = (t) => t;
2404
+ function sigmoid(x) {
2405
+ return 1 / (1 + Math.exp(-x));
1986
2406
  }
1987
- function mountTree(node, time) {
1988
- const wasVisible = node.base.visible;
1989
- for (const entry of node.all()) entry.mounted = true;
1990
- if (time > 0 || !wasVisible) {
1991
- const track = node.track("visible");
1992
- track.initial = false;
1993
- if (wasVisible) track.step(time, true);
1994
- }
2407
+ function smoothBy(inflection) {
2408
+ const low = sigmoid(-inflection / 2);
2409
+ const high = sigmoid(inflection / 2);
2410
+ return (t) => {
2411
+ if (t <= 0) return 0;
2412
+ if (t >= 1) return 1;
2413
+ return (sigmoid(inflection * (t - 0.5)) - low) / (high - low);
2414
+ };
1995
2415
  }
1996
- function group(...children) {
1997
- return new Node().add(...children);
2416
+ var smooth = smoothBy(10);
2417
+ var smoother = (t) => {
2418
+ const x = clamp01(t);
2419
+ return x * x * x * (x * (x * 6 - 15) + 10);
2420
+ };
2421
+ var easeInQuad = (t) => t * t;
2422
+ var easeOutQuad = (t) => 1 - (1 - t) * (1 - t);
2423
+ var easeInCubic = (t) => t * t * t;
2424
+ var easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
2425
+ var easeInOutCubic = (t) => t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
2426
+ var easeOutQuint = (t) => 1 - Math.pow(1 - t, 5);
2427
+ var easeInOutQuint = (t) => t < 0.5 ? 16 * t * t * t * t * t : 1 - Math.pow(-2 * t + 2, 5) / 2;
2428
+ var easeOutExpo = (t) => t >= 1 ? 1 : 1 - Math.pow(2, -10 * t);
2429
+ var easeInExpo = (t) => t <= 0 ? 0 : Math.pow(2, 10 * t - 10);
2430
+ var rushInto = (t) => 2 * smooth(t / 2);
2431
+ var rushFrom = (t) => 2 * smooth(t / 2 + 0.5) - 1;
2432
+ var slowInto = (t) => Math.sqrt(Math.max(0, 1 - (1 - t) * (1 - t)));
2433
+ function overshoot(amount = 1.70158) {
2434
+ return (t) => {
2435
+ const x = t - 1;
2436
+ return x * x * ((amount + 1) * x + amount) + 1;
2437
+ };
1998
2438
  }
1999
- function dynamic(build) {
2000
- const node = new Node();
2001
- node.draw = build;
2002
- return node;
2439
+ function spring(options = {}) {
2440
+ const bounce2 = options.bounce ?? 0.28;
2441
+ const frequency = options.frequency ?? 2.2;
2442
+ const decay = -Math.log(Math.max(1e-4, bounce2)) * 2.4;
2443
+ return (t) => {
2444
+ if (t <= 0) return 0;
2445
+ if (t >= 1) return 1;
2446
+ return 1 - Math.exp(-decay * t) * Math.cos(frequency * Math.PI * 2 * t) * (1 - t);
2447
+ };
2448
+ }
2449
+ var bounce = (t) => {
2450
+ const n = 7.5625, d = 2.75;
2451
+ if (t < 1 / d) return n * t * t;
2452
+ if (t < 2 / d) return n * (t -= 1.5 / d) * t + 0.75;
2453
+ if (t < 2.5 / d) return n * (t -= 2.25 / d) * t + 0.9375;
2454
+ return n * (t -= 2.625 / d) * t + 0.984375;
2455
+ };
2456
+ var thereAndBack = (t) => smooth(t < 0.5 ? 2 * t : 2 * (1 - t));
2457
+ function thereAndBackWithPause(pause = 1 / 3) {
2458
+ const a = (1 - pause) / 2;
2459
+ return (t) => {
2460
+ if (t < a) return smooth(t / a);
2461
+ if (t < 1 - a) return 1;
2462
+ return smooth((1 - t) / a);
2463
+ };
2464
+ }
2465
+ function wiggle(cycles = 2) {
2466
+ return (t) => thereAndBack(t) * Math.sin(cycles * Math.PI * 2 * t);
2467
+ }
2468
+ function notQuiteThere(amount = 0.7, inner = smooth) {
2469
+ return (t) => amount * inner(t);
2470
+ }
2471
+ function lingering(hold = 0.25, inner = smooth) {
2472
+ return (t) => inner(clamp01(t / (1 - hold)));
2473
+ }
2474
+ function runningStart(pull = -0.5) {
2475
+ return (t) => {
2476
+ const u = 1 - t;
2477
+ return 15 * u ** 4 * t ** 2 * pull + 20 * u ** 3 * t ** 3 * pull + 15 * u ** 2 * t ** 4 + 6 * u * t ** 5 + t ** 6;
2478
+ };
2479
+ }
2480
+ function during(from, to2, inner = smooth) {
2481
+ return (t) => inner(clamp01((t - from) / (to2 - from)));
2482
+ }
2483
+ function cubicBezier(x1, y1, x2, y2) {
2484
+ const cx = 3 * x1, bx = 3 * (x2 - x1) - cx, ax = 1 - cx - bx;
2485
+ const cy = 3 * y1, by = 3 * (y2 - y1) - cy, ay = 1 - cy - by;
2486
+ const sampleX = (t) => ((ax * t + bx) * t + cx) * t;
2487
+ const sampleY = (t) => ((ay * t + by) * t + cy) * t;
2488
+ const slope = (t) => (3 * ax * t + 2 * bx) * t + cx;
2489
+ return (x) => {
2490
+ if (x <= 0) return 0;
2491
+ if (x >= 1) return 1;
2492
+ let t = x;
2493
+ for (let i = 0; i < 8; i++) {
2494
+ const dx = sampleX(t) - x;
2495
+ const d = slope(t);
2496
+ if (Math.abs(dx) < 1e-5 || Math.abs(d) < 1e-6) break;
2497
+ t -= dx / d;
2498
+ }
2499
+ return sampleY(t);
2500
+ };
2003
2501
  }
2004
2502
 
2005
2503
  // src/stage/anim.ts
@@ -2823,12 +3321,12 @@ var Stage = class {
2823
3321
  return new Value(initial);
2824
3322
  }
2825
3323
  /** Re-run a function each frame while the node shows. It can set any property on the node. */
2826
- update(node, fn, window = {}) {
3324
+ update(node, fn, window2 = {}) {
2827
3325
  this.updaters.push({
2828
3326
  node,
2829
3327
  fn,
2830
- from: window.from ?? this.time,
2831
- to: window.to ?? Infinity
3328
+ from: window2.from ?? this.time,
3329
+ to: window2.to ?? Infinity
2832
3330
  });
2833
3331
  return node;
2834
3332
  }
@@ -2863,6 +3361,9 @@ function isSuspend(error) {
2863
3361
  return typeof error === "object" && error !== null && error.isVizmaticSuspend === true;
2864
3362
  }
2865
3363
  var CompiledFilm = class {
3364
+ allowImageNetwork;
3365
+ imageAssets = /* @__PURE__ */ new Map();
3366
+ imageLoads = /* @__PURE__ */ new Map();
2866
3367
  width;
2867
3368
  height;
2868
3369
  fps;
@@ -2880,6 +3381,7 @@ var CompiledFilm = class {
2880
3381
  captions;
2881
3382
  stage;
2882
3383
  constructor(stage, options, overrides) {
3384
+ this.allowImageNetwork = (overrides.imageNetwork ?? options.imageNetwork ?? "allow") === "allow";
2883
3385
  this.stage = stage;
2884
3386
  this.width = stage.width;
2885
3387
  this.height = stage.height;
@@ -2900,6 +3402,32 @@ var CompiledFilm = class {
2900
3402
  get frameCount() {
2901
3403
  return Math.max(1, Math.round(this.duration * this.fps));
2902
3404
  }
3405
+ async prepareImage(image) {
3406
+ if (image.asset) {
3407
+ if (!isImageAsset(image.asset)) throw new ImageAssetError("Image asset was not prepared by resolveImageAsset.");
3408
+ validateStageImage(image, image.asset);
3409
+ return image.asset;
3410
+ }
3411
+ let pending2 = this.imageLoads.get(image.src);
3412
+ if (!pending2) {
3413
+ pending2 = resolveLegacyImage(image.src, this.allowImageNetwork).then((asset2) => {
3414
+ this.imageAssets.set(image.src, asset2);
3415
+ return asset2;
3416
+ });
3417
+ this.imageLoads.set(image.src, pending2);
3418
+ }
3419
+ const asset = await pending2;
3420
+ validateStageImage(image, asset);
3421
+ return asset;
3422
+ }
3423
+ /** Preload static and keyed images, including those not visible in the first frame. */
3424
+ async preloadImages() {
3425
+ for (const node of this.stage.root.all()) {
3426
+ const track = node.tracks?.get("image");
3427
+ const images = [node.base.image, track?.initial, ...track?.keys.map((key) => key.to) ?? []];
3428
+ for (const image of images) if (image) await this.prepareImage(image);
3429
+ }
3430
+ }
2903
3431
  /** The draw list at a time in seconds. May throw Suspend if a drawing needs a new asset. */
2904
3432
  frame(time) {
2905
3433
  const t = Math.max(0, Math.min(this.duration, time));
@@ -2920,7 +3448,15 @@ var CompiledFilm = class {
2920
3448
  zoom: camera.get("sx"),
2921
3449
  rotation: camera.get("rotation")
2922
3450
  }, stage.width, stage.height);
2923
- return { width: stage.width, height: stage.height, background: this.background, bloom: this.bloom, dark: stage.look.dark, ops };
3451
+ const preparedOps = ops.map((op) => {
3452
+ if (op.kind !== "image") return op;
3453
+ const asset = op.image.asset ?? this.imageAssets.get(op.image.src);
3454
+ if (!asset) throw new Suspend(this.prepareImage(op.image));
3455
+ if (!isImageAsset(asset)) throw new ImageAssetError("Image asset was not prepared by resolveImageAsset.");
3456
+ validateStageImage(op.image, asset);
3457
+ return { ...op, image: { ...op.image, src: asset.src, asset } };
3458
+ });
3459
+ return { width: stage.width, height: stage.height, background: this.background, bloom: this.bloom, dark: stage.look.dark, ops: preparedOps };
2924
3460
  } finally {
2925
3461
  clock.mode = previous.mode;
2926
3462
  clock.now = previous.now;
@@ -2944,6 +3480,7 @@ async function compileFilm(definition, overrides = {}) {
2944
3480
  clock.mode = saved.mode;
2945
3481
  clock.now = saved.now;
2946
3482
  const compiled = new CompiledFilm(stage, options, overrides);
3483
+ await compiled.preloadImages();
2947
3484
  await probe(compiled);
2948
3485
  return compiled;
2949
3486
  } catch (error) {
@@ -4144,10 +4681,20 @@ export {
4144
4681
  parseSvgPath,
4145
4682
  pathToD,
4146
4683
  clock,
4684
+ matchSequence,
4685
+ Node,
4686
+ direction,
4687
+ group,
4688
+ dynamic,
4689
+ ImageAssetError,
4690
+ resolveImageAsset,
4691
+ imageHasVisiblePixels,
4692
+ imageFromAsset,
4147
4693
  buildOps,
4148
4694
  frameToSvg,
4149
4695
  paintFrame,
4150
4696
  frameInkBounds,
4697
+ imageOpBounds,
4151
4698
  linear,
4152
4699
  smoothBy,
4153
4700
  smooth,
@@ -4175,11 +4722,6 @@ export {
4175
4722
  runningStart,
4176
4723
  during,
4177
4724
  cubicBezier,
4178
- matchSequence,
4179
- Node,
4180
- direction,
4181
- group,
4182
- dynamic,
4183
4725
  par,
4184
4726
  seq,
4185
4727
  lagged,