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.
@@ -1247,11 +1247,11 @@ function fittedTree(element, geometry) {
1247
1247
  return children === void 0 ? element : import_react2.default.cloneElement(element, {}, fittedTree(children, geometry));
1248
1248
  }
1249
1249
  async function renderWithCanvasChartFit(render, element, options) {
1250
- const prepared = prepareChartFits(element);
1251
- if (!prepared.sizes.size) return render(prepared.element, options);
1250
+ const prepared2 = prepareChartFits(element);
1251
+ if (!prepared2.sizes.size) return render(prepared2.element, options);
1252
1252
  const viewports = /* @__PURE__ */ new Map();
1253
1253
  const bounds = /* @__PURE__ */ new Map();
1254
- await render(prepared.element, { ...options, onNodeDetected(node) {
1254
+ await render(prepared2.element, { ...options, onNodeDetected(node) {
1255
1255
  const viewport = node.props[VIEWPORT_PROP];
1256
1256
  if (typeof viewport === "string") viewports.set(viewport, node);
1257
1257
  const id = node.props[SCOPE_PROP];
@@ -1265,7 +1265,7 @@ async function renderWithCanvasChartFit(render, element, options) {
1265
1265
  });
1266
1266
  } });
1267
1267
  const geometry = /* @__PURE__ */ new Map();
1268
- for (const [id, size] of prepared.sizes) {
1268
+ for (const [id, size] of prepared2.sizes) {
1269
1269
  const viewport = viewports.get(id);
1270
1270
  const measured = bounds.get(id);
1271
1271
  if (!viewport || !measured) throw new Error("Could not measure the chart inside CanvasItem.");
@@ -1280,7 +1280,7 @@ async function renderWithCanvasChartFit(render, element, options) {
1280
1280
  });
1281
1281
  }
1282
1282
  const finalViewports = /* @__PURE__ */ new Map();
1283
- return render(fittedTree(prepared.element, geometry), { ...options, onNodeDetected(node) {
1283
+ return render(fittedTree(prepared2.element, geometry), { ...options, onNodeDetected(node) {
1284
1284
  const viewport = node.props[VIEWPORT_PROP];
1285
1285
  if (typeof viewport === "string") finalViewports.set(viewport, node);
1286
1286
  const id = node.props[SCOPE_PROP];
@@ -1737,9 +1737,9 @@ async function renderToSvgInContext(element, width, height, options) {
1737
1737
  options.theme ?? "dark",
1738
1738
  watermark
1739
1739
  ) : element;
1740
- const prepared = prepareAccessibleSvg(outputElement);
1740
+ const prepared2 = prepareAccessibleSvg(outputElement);
1741
1741
  const layoutNodes = [];
1742
- const svg = await satori(prepared.element, {
1742
+ const svg = await satori(prepared2.element, {
1743
1743
  width,
1744
1744
  height,
1745
1745
  fonts: fonts2,
@@ -1749,7 +1749,7 @@ async function renderToSvgInContext(element, width, height, options) {
1749
1749
  options.onNodeDetected?.(node);
1750
1750
  }
1751
1751
  });
1752
- return addSvgAccessibility(sanitizeSvg(svg), prepared.graphs, layoutNodes);
1752
+ return addSvgAccessibility(sanitizeSvg(svg), prepared2.graphs, layoutNodes);
1753
1753
  }
1754
1754
 
1755
1755
  // src/video.ts
@@ -2732,450 +2732,151 @@ var Track = class {
2732
2732
  }
2733
2733
  };
2734
2734
 
2735
- // src/stage/display.ts
2736
- var GLOW_PASSES = 7;
2737
- function glowPasses(glow, width) {
2738
- const out = [];
2739
- for (let i = GLOW_PASSES; i >= 1; i--) {
2740
- const k = i / GLOW_PASSES;
2741
- out.push({ width: width + glow * 2 * k, alpha: 0.16 * (1 - k) * (1 - k) + 0.018 });
2735
+ // src/stage/image.ts
2736
+ var import_fflate3 = require("fflate");
2737
+
2738
+ // src/stage/morph.ts
2739
+ function growTo(r, target) {
2740
+ const count = segmentCount(r);
2741
+ if (count >= target || count === 0) return r;
2742
+ const segments = [];
2743
+ for (let i = 0; i < count; i++) {
2744
+ const o = i * 6;
2745
+ const pts = Array.from(r.p.subarray(o, o + 8));
2746
+ segments.push({ pts, length: chord(pts) });
2742
2747
  }
2743
- return out;
2744
- }
2745
- function glowOf(op) {
2746
- if (op.glowColor) return op.glowColor;
2747
- const paint = op.stroke ?? op.fill;
2748
- if (!paint) return null;
2749
- return isGradient(paint) ? sampleStops(paint.stops, 0.5) : paint;
2750
- }
2751
- var dCache = /* @__PURE__ */ new WeakMap();
2752
- function pathData(path) {
2753
- let d = dCache.get(path);
2754
- if (d === void 0) {
2755
- d = pathToD(path);
2756
- dCache.set(path, d);
2748
+ while (segments.length < target) {
2749
+ let longest = 0;
2750
+ for (let i = 1; i < segments.length; i++) if (segments[i].length > segments[longest].length) longest = i;
2751
+ const [a, b] = bisect(segments[longest].pts);
2752
+ segments.splice(longest, 1, { pts: a, length: chord(a) }, { pts: b, length: chord(b) });
2757
2753
  }
2758
- return d;
2754
+ const out = new Float64Array(2 + target * 6);
2755
+ out[0] = r.p[0];
2756
+ out[1] = r.p[1];
2757
+ for (let i = 0; i < target; i++) {
2758
+ const pts = segments[i].pts;
2759
+ for (let k = 0; k < 6; k++) out[2 + i * 6 + k] = pts[2 + k];
2760
+ }
2761
+ return { p: out, closed: r.closed };
2759
2762
  }
2760
- function fmt2(value) {
2761
- return String(Math.round(value * 1e3) / 1e3);
2763
+ function chord(pts) {
2764
+ 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]);
2762
2765
  }
2763
- function gradientDef(id, paint) {
2764
- 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("");
2765
- if (paint.type === "linear") {
2766
- 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>`;
2766
+ function bisect(p) {
2767
+ const ax = (p[0] + p[2]) / 2, ay = (p[1] + p[3]) / 2;
2768
+ const bx = (p[2] + p[4]) / 2, by = (p[3] + p[5]) / 2;
2769
+ const cx = (p[4] + p[6]) / 2, cy = (p[5] + p[7]) / 2;
2770
+ const dx = (ax + bx) / 2, dy = (ay + by) / 2;
2771
+ const ex = (bx + cx) / 2, ey = (by + cy) / 2;
2772
+ const fx = (dx + ex) / 2, fy = (dy + ey) / 2;
2773
+ return [[p[0], p[1], ax, ay, dx, dy, fx, fy], [fx, fy, ex, ey, cx, cy, p[6], p[7]]];
2774
+ }
2775
+ function bestRotation(a, b) {
2776
+ const count = segmentCount(b);
2777
+ if (!a.closed || !b.closed || count < 2) return b;
2778
+ const [ax, ay] = ringCenter(a), [bx, by] = ringCenter(b);
2779
+ const stride = Math.max(1, Math.floor(count / 48));
2780
+ let best = 0, bestCost = Infinity;
2781
+ for (let shift = 0; shift < count; shift += stride) {
2782
+ let cost = 0;
2783
+ for (let i = 0; i < count; i += stride) {
2784
+ const j = (i + shift) % count;
2785
+ const dx = a.p[i * 6] - ax - (b.p[j * 6] - bx);
2786
+ const dy = a.p[i * 6 + 1] - ay - (b.p[j * 6 + 1] - by);
2787
+ cost += dx * dx + dy * dy;
2788
+ }
2789
+ if (cost < bestCost) {
2790
+ bestCost = cost;
2791
+ best = shift;
2792
+ }
2767
2793
  }
2768
- if (paint.type === "radial") {
2769
- return `<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${fmt2(paint.center[0])}" cy="${fmt2(paint.center[1])}" r="${fmt2(paint.radius)}">${stops}</radialGradient>`;
2794
+ if (best === 0) return b;
2795
+ const out = new Float64Array(b.p.length);
2796
+ out[0] = b.p[best * 6];
2797
+ out[1] = b.p[best * 6 + 1];
2798
+ for (let i = 0; i < count; i++) {
2799
+ const j = (i + best) % count;
2800
+ for (let k = 0; k < 6; k++) out[2 + i * 6 + k] = b.p[2 + j * 6 + k];
2770
2801
  }
2771
- return "";
2772
- }
2773
- function strokeAttrs(op) {
2774
- let attrs = ` stroke-linecap="${op.cap}" stroke-linejoin="${op.join}"`;
2775
- if (op.dash) attrs += ` stroke-dasharray="${op.dash.map(fmt2).join(" ")}" stroke-dashoffset="${fmt2(op.dashOffset)}"`;
2776
- return attrs;
2802
+ return { p: out, closed: b.closed };
2777
2803
  }
2778
- function escapeAttr(value) {
2779
- return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
2804
+ function pointRing(x, y, count, closed) {
2805
+ const out = new Float64Array(2 + count * 6);
2806
+ for (let i = 0; i < out.length; i += 2) {
2807
+ out[i] = x;
2808
+ out[i + 1] = y;
2809
+ }
2810
+ return { p: out, closed };
2780
2811
  }
2781
- function frameToSvg(frame, options = {}) {
2782
- const scale = options.scale ?? 1;
2783
- const w = frame.width, h = frame.height;
2784
- const defs = [];
2785
- const body = [];
2786
- let gradientCount = 0;
2787
- const paintAttr = (paint, attr, alpha) => {
2788
- if (isGradient(paint)) {
2789
- const id = `g${gradientCount++}`;
2790
- defs.push(gradientDef(id, paint));
2791
- return `${attr}="url(#${id})"${alpha < 1 ? ` ${attr}-opacity="${fmt2(alpha)}"` : ""}`;
2792
- }
2793
- const rgba = paint;
2794
- const a = rgba[3] * alpha;
2795
- return `${attr}="${css([rgba[0], rgba[1], rgba[2], 1])}"${a < 1 ? ` ${attr}-opacity="${fmt2(a)}"` : ""}`;
2796
- };
2797
- if (frame.background && !options.transparent) body.push(`<rect width="${w}" height="${h}" fill="${frame.background}"/>`);
2798
- for (const op of frame.ops) {
2799
- if (op.kind === "image") {
2800
- const m = op.matrix;
2801
- 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"/>`);
2812
+ function pairRings(from, to) {
2813
+ const rank = (path) => [...path].sort((a2, b2) => Math.abs(signedArea(b2)) + ringLength(b2) * 0.01 - (Math.abs(signedArea(a2)) + ringLength(a2) * 0.01));
2814
+ const a = rank(from), b = rank(to);
2815
+ const pairs = [];
2816
+ const free = b.slice();
2817
+ for (const ringA of a) {
2818
+ if (free.length === 0) {
2819
+ const [x, y] = ringCenter(ringA);
2820
+ pairs.push([ringA, pointRing(x, y, segmentCount(ringA), ringA.closed)]);
2802
2821
  continue;
2803
2822
  }
2804
- const style = op.blend !== "normal" ? ` style="mix-blend-mode:${op.blend}"` : "";
2805
- if (op.glow > 0) {
2806
- const color = glowOf(op);
2807
- const glowD = pathData(op.strokePath.length ? op.strokePath : op.path);
2808
- if (color && glowD) {
2809
- const base = Math.max(op.fillAlpha, op.strokeAlpha);
2810
- const mode = frame.dark ? ' style="mix-blend-mode:screen"' : "";
2811
- 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("");
2812
- body.push(`<g${mode}>${passes}</g>`);
2823
+ const [ax, ay] = ringCenter(ringA);
2824
+ let bestIndex = 0, bestCost = Infinity;
2825
+ for (let i = 0; i < Math.min(free.length, 3); i++) {
2826
+ const [bx, by] = ringCenter(free[i]);
2827
+ const cost = Math.hypot(ax - bx, ay - by) + i * 40;
2828
+ if (cost < bestCost) {
2829
+ bestCost = cost;
2830
+ bestIndex = i;
2813
2831
  }
2814
2832
  }
2815
- if (op.fill && op.stroke && op.strokePath === op.path) {
2816
- 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}/>`);
2817
- continue;
2818
- }
2819
- if (op.fill) body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill, "fill", op.fillAlpha)}${style}/>`);
2820
- if (op.stroke && op.strokePath.length) {
2821
- body.push(`<path d="${pathData(op.strokePath)}" fill="none" ${paintAttr(op.stroke, "stroke", op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`);
2822
- }
2833
+ pairs.push([ringA, free[bestIndex]]);
2834
+ free.splice(bestIndex, 1);
2823
2835
  }
2824
- const defsBlock = defs.length ? `<defs>${defs.join("")}</defs>` : "";
2825
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${w * scale}" height="${h * scale}" viewBox="0 0 ${w} ${h}">${defsBlock}${body.join("")}</svg>`;
2826
- }
2827
-
2828
- // src/stage/raster.ts
2829
- var import_node_module = require("module");
2830
- var import_node_os = require("os");
2831
- var import_node_worker_threads = require("worker_threads");
2832
- var import_node_url = require("url");
2833
- var RASTER_WORKER_SOURCE = String.raw`
2834
- const { parentPort, workerData } = require('node:worker_threads')
2835
- const { Resvg } = require(workerData.resvgPath)
2836
-
2837
- function downsample(src, w, h, factor) {
2838
- const dw = Math.max(1, Math.floor(w / factor)), dh = Math.max(1, Math.floor(h / factor))
2839
- const out = new Float32Array(dw * dh * 3)
2840
- const norm = 1 / (factor * factor)
2841
- for (let y = 0; y < dh; y++) {
2842
- for (let x = 0; x < dw; x++) {
2843
- let r = 0, g = 0, b = 0
2844
- for (let yy = 0; yy < factor; yy++) {
2845
- let o = ((y * factor + yy) * w + x * factor) * 4
2846
- for (let xx = 0; xx < factor; xx++) { r += src[o]; g += src[o + 1]; b += src[o + 2]; o += 4 }
2847
- }
2848
- const i = (y * dw + x) * 3
2849
- out[i] = r * norm; out[i + 1] = g * norm; out[i + 2] = b * norm
2850
- }
2836
+ for (const ringB of free) {
2837
+ const [x, y] = ringCenter(ringB);
2838
+ pairs.push([pointRing(x, y, segmentCount(ringB), ringB.closed), ringB]);
2851
2839
  }
2852
- return { data: out, w: dw, h: dh }
2840
+ return pairs;
2853
2841
  }
2854
-
2855
- function boxBlur(img, radius) {
2856
- const { data, w, h } = img
2857
- const tmp = new Float32Array(data.length)
2858
- const norm = 1 / (radius * 2 + 1)
2859
- for (let y = 0; y < h; y++) {
2860
- for (let c = 0; c < 3; c++) {
2861
- let sum = 0
2862
- for (let k = -radius; k <= radius; k++) sum += data[(y * w + Math.min(w - 1, Math.max(0, k))) * 3 + c]
2863
- for (let x = 0; x < w; x++) {
2864
- tmp[(y * w + x) * 3 + c] = sum * norm
2865
- sum += data[(y * w + Math.min(w - 1, x + radius + 1)) * 3 + c] - data[(y * w + Math.max(0, x - radius)) * 3 + c]
2866
- }
2842
+ function alignPaths(from, to, minSegments = 12) {
2843
+ const pairs = pairRings(from, to);
2844
+ const a = [], b = [], closed = [];
2845
+ for (const [ra, rb] of pairs) {
2846
+ const target = Math.max(segmentCount(ra), segmentCount(rb), ra.closed && rb.closed ? minSegments : 1);
2847
+ let x = growTo(ra, target);
2848
+ let y = growTo(rb, target);
2849
+ if (x.closed && y.closed) {
2850
+ if (Math.sign(signedArea(x)) !== Math.sign(signedArea(y)) && signedArea(x) !== 0 && signedArea(y) !== 0) y = reverseRing(y);
2851
+ y = bestRotation(x, y);
2852
+ } else if (!x.closed && !y.closed) {
2853
+ const n = x.p.length;
2854
+ 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]);
2855
+ 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]);
2856
+ if (flipped < straight) y = reverseRing(y);
2867
2857
  }
2858
+ a.push(x.p);
2859
+ b.push(y.p);
2860
+ closed.push(x.closed && y.closed);
2868
2861
  }
2869
- for (let x = 0; x < w; x++) {
2870
- for (let c = 0; c < 3; c++) {
2871
- let sum = 0
2872
- for (let k = -radius; k <= radius; k++) sum += tmp[(Math.min(h - 1, Math.max(0, k)) * w + x) * 3 + c]
2873
- for (let y = 0; y < h; y++) {
2874
- data[(y * w + x) * 3 + c] = sum * norm
2875
- sum += tmp[(Math.min(h - 1, y + radius + 1) * w + x) * 3 + c] - tmp[(Math.max(0, y - radius) * w + x) * 3 + c]
2876
- }
2862
+ return { from: a, to: b, closed };
2863
+ }
2864
+ function pathMixer(from, to) {
2865
+ if (from === to) return () => to;
2866
+ if (pathLength(from) === 0 && from.length === 0) return (alpha) => alpha >= 1 ? to : from;
2867
+ const aligned = alignPaths(from, to);
2868
+ return (alpha) => {
2869
+ if (alpha <= 0) return from;
2870
+ if (alpha >= 1) return to;
2871
+ const rings = new Array(aligned.from.length);
2872
+ for (let r = 0; r < rings.length; r++) {
2873
+ const a = aligned.from[r], b = aligned.to[r];
2874
+ const out = new Float64Array(a.length);
2875
+ for (let i = 0; i < a.length; i++) out[i] = a[i] + (b[i] - a[i]) * alpha;
2876
+ rings[r] = { p: out, closed: aligned.closed[r] };
2877
2877
  }
2878
- }
2879
- }
2880
-
2881
- // Bloom: bright marks spill soft light. Blurred layers add on top of the sharp image.
2882
- function bloom(pixels, w, h, amount, background) {
2883
- const [br, bg, bb] = background
2884
- const layers = []
2885
- // The spread follows output width, so a small preview and a 4K master look alike.
2886
- const k = w / 1920
2887
- for (const [base, radius, weight] of [[4, 3, 0.55], [8, 4, 0.3], [16, 4, 0.15]]) {
2888
- const factor = Math.max(1, Math.round(base * k))
2889
- const layer = downsample(pixels, w, h, factor)
2890
- const d = layer.data
2891
- for (let i = 0; i < d.length; i += 3) {
2892
- // Only light above the background contributes, so the page never lifts or fogs.
2893
- d[i] = Math.max(0, d[i] - br); d[i + 1] = Math.max(0, d[i + 1] - bg); d[i + 2] = Math.max(0, d[i + 2] - bb)
2894
- }
2895
- boxBlur(layer, radius); boxBlur(layer, radius)
2896
- layers.push({ ...layer, factor, weight })
2897
- }
2898
- for (let y = 0; y < h; y++) {
2899
- for (let x = 0; x < w; x++) {
2900
- const o = (y * w + x) * 4
2901
- let r = 0, g = 0, b = 0
2902
- for (const layer of layers) {
2903
- const fx = (x + 0.5) / layer.factor - 0.5, fy = (y + 0.5) / layer.factor - 0.5
2904
- const x0 = Math.max(0, Math.floor(fx)), y0 = Math.max(0, Math.floor(fy))
2905
- const x1 = Math.min(layer.w - 1, x0 + 1), y1 = Math.min(layer.h - 1, y0 + 1)
2906
- const tx = Math.max(0, fx - x0), ty = Math.max(0, fy - y0)
2907
- const d = layer.data, lw = layer.w
2908
- for (let c = 0; c < 3; c++) {
2909
- const v = (d[(y0 * lw + x0) * 3 + c] * (1 - tx) + d[(y0 * lw + x1) * 3 + c] * tx) * (1 - ty)
2910
- + (d[(y1 * lw + x0) * 3 + c] * (1 - tx) + d[(y1 * lw + x1) * 3 + c] * tx) * ty
2911
- if (c === 0) r += v * layer.weight
2912
- else if (c === 1) g += v * layer.weight
2913
- else b += v * layer.weight
2914
- }
2915
- }
2916
- // Screen blend keeps highlights from clipping harshly.
2917
- pixels[o] = 255 - (255 - pixels[o]) * (255 - Math.min(255, r * amount * 2.4)) / 255
2918
- pixels[o + 1] = 255 - (255 - pixels[o + 1]) * (255 - Math.min(255, g * amount * 2.4)) / 255
2919
- pixels[o + 2] = 255 - (255 - pixels[o + 2]) * (255 - Math.min(255, b * amount * 2.4)) / 255
2920
- }
2921
- }
2922
- }
2923
-
2924
- function raster(svg, width, height) {
2925
- const image = new Resvg(svg, { fitTo: { mode: 'width', value: width }, font: { loadSystemFonts: false } }).render()
2926
- if (image.height === height) return image.pixels
2927
- // Rounding can differ by a row at unusual sizes. Keep the requested size exactly.
2928
- const out = new Uint8Array(width * height * 4)
2929
- for (let y = 0; y < height; y++) {
2930
- const row = Math.min(image.height - 1, y) * width * 4
2931
- out.set(image.pixels.subarray(row, row + width * 4), y * width * 4)
2932
- }
2933
- return out
2934
- }
2935
-
2936
- parentPort.on('message', (job) => {
2937
- try {
2938
- let out
2939
- if (job.svgs.length === 1) {
2940
- out = new Uint8Array(raster(job.svgs[0], job.width, job.height))
2941
- } else {
2942
- // Motion blur: average sub-frames across the shutter.
2943
- const n = job.svgs.length
2944
- // Sixteen bits hold 257 full-white sub-frames, at half the memory of thirty-two.
2945
- let sum = null
2946
- for (const svg of job.svgs) {
2947
- const px = raster(svg, job.width, job.height)
2948
- if (!sum) sum = n <= 257 ? new Uint16Array(px.length) : new Uint32Array(px.length)
2949
- for (let i = 0; i < px.length; i++) sum[i] += px[i]
2950
- }
2951
- out = new Uint8Array(sum.length)
2952
- for (let i = 0; i < sum.length; i++) out[i] = sum[i] / n + 0.5
2953
- }
2954
- if (job.bloom > 0) bloom(out, job.width, job.height, job.bloom, job.background)
2955
- parentPort.postMessage({ id: job.id, pixels: out }, [out.buffer])
2956
- } catch (error) {
2957
- parentPort.postMessage({ id: job.id, error: String(error && error.message || error) })
2958
- }
2959
- })
2960
- `;
2961
- function resolveResvg() {
2962
- const here = typeof __filename !== "undefined" ? __filename : (0, import_node_url.fileURLToPath)(void 0);
2963
- return (0, import_node_module.createRequire)(here).resolve("@resvg/resvg-js");
2964
- }
2965
- var RasterPool = class {
2966
- workers = [];
2967
- idle = [];
2968
- queue = [];
2969
- pending = /* @__PURE__ */ new Map();
2970
- nextId = 1;
2971
- failure = null;
2972
- constructor(size = defaultPoolSize()) {
2973
- const resvgPath = resolveResvg();
2974
- for (let i = 0; i < size; i++) {
2975
- const worker = new import_node_worker_threads.Worker(RASTER_WORKER_SOURCE, { eval: true, workerData: { resvgPath } });
2976
- worker.on("message", (message) => {
2977
- const entry = this.pending.get(message.id);
2978
- this.pending.delete(message.id);
2979
- this.idle.push(worker);
2980
- this.pump();
2981
- if (!entry) return;
2982
- if (message.error || !message.pixels) entry.reject(new Error(`Frame rasterization failed: ${message.error}`));
2983
- else entry.resolve(message.pixels);
2984
- });
2985
- worker.on("error", (error) => this.fail(error instanceof Error ? error : new Error(String(error))));
2986
- this.workers.push(worker);
2987
- this.idle.push(worker);
2988
- }
2989
- }
2990
- get size() {
2991
- return this.workers.length;
2992
- }
2993
- fail(error) {
2994
- this.failure = error;
2995
- for (const entry of this.pending.values()) entry.reject(error);
2996
- this.pending.clear();
2997
- }
2998
- pump() {
2999
- while (this.idle.length > 0 && this.queue.length > 0) {
3000
- const worker = this.idle.pop();
3001
- const { job, id } = this.queue.shift();
3002
- worker.postMessage({ id, ...job });
3003
- }
3004
- }
3005
- run(job) {
3006
- if (this.failure) return Promise.reject(this.failure);
3007
- const id = this.nextId++;
3008
- return new Promise((resolve3, reject) => {
3009
- this.pending.set(id, { resolve: resolve3, reject });
3010
- this.queue.push({ job, id });
3011
- this.pump();
3012
- });
3013
- }
3014
- async close() {
3015
- this.failure ??= new Error("The raster pool was closed.");
3016
- for (const entry of this.pending.values()) entry.reject(this.failure);
3017
- this.pending.clear();
3018
- this.queue.length = 0;
3019
- await Promise.all(this.workers.map((worker) => worker.terminate()));
3020
- }
3021
- };
3022
- function defaultPoolSize() {
3023
- return Math.max(1, Math.min(12, (0, import_node_os.cpus)().length - 2));
3024
- }
3025
- function framesToJob(frames, width, parseBackground, height) {
3026
- const first = frames[0];
3027
- const scale = width / first.width;
3028
- return {
3029
- svgs: frames.map((frame) => frameToSvg(frame)),
3030
- width,
3031
- height: height ?? Math.round(first.height * scale),
3032
- bloom: first.dark ? first.bloom : 0,
3033
- background: parseBackground(first.background)
3034
- };
3035
- }
3036
-
3037
- // src/stage/morph.ts
3038
- function growTo(r, target) {
3039
- const count = segmentCount(r);
3040
- if (count >= target || count === 0) return r;
3041
- const segments = [];
3042
- for (let i = 0; i < count; i++) {
3043
- const o = i * 6;
3044
- const pts = Array.from(r.p.subarray(o, o + 8));
3045
- segments.push({ pts, length: chord(pts) });
3046
- }
3047
- while (segments.length < target) {
3048
- let longest = 0;
3049
- for (let i = 1; i < segments.length; i++) if (segments[i].length > segments[longest].length) longest = i;
3050
- const [a, b] = bisect(segments[longest].pts);
3051
- segments.splice(longest, 1, { pts: a, length: chord(a) }, { pts: b, length: chord(b) });
3052
- }
3053
- const out = new Float64Array(2 + target * 6);
3054
- out[0] = r.p[0];
3055
- out[1] = r.p[1];
3056
- for (let i = 0; i < target; i++) {
3057
- const pts = segments[i].pts;
3058
- for (let k = 0; k < 6; k++) out[2 + i * 6 + k] = pts[2 + k];
3059
- }
3060
- return { p: out, closed: r.closed };
3061
- }
3062
- function chord(pts) {
3063
- 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]);
3064
- }
3065
- function bisect(p) {
3066
- const ax = (p[0] + p[2]) / 2, ay = (p[1] + p[3]) / 2;
3067
- const bx = (p[2] + p[4]) / 2, by = (p[3] + p[5]) / 2;
3068
- const cx = (p[4] + p[6]) / 2, cy = (p[5] + p[7]) / 2;
3069
- const dx = (ax + bx) / 2, dy = (ay + by) / 2;
3070
- const ex = (bx + cx) / 2, ey = (by + cy) / 2;
3071
- const fx = (dx + ex) / 2, fy = (dy + ey) / 2;
3072
- return [[p[0], p[1], ax, ay, dx, dy, fx, fy], [fx, fy, ex, ey, cx, cy, p[6], p[7]]];
3073
- }
3074
- function bestRotation(a, b) {
3075
- const count = segmentCount(b);
3076
- if (!a.closed || !b.closed || count < 2) return b;
3077
- const [ax, ay] = ringCenter(a), [bx, by] = ringCenter(b);
3078
- const stride = Math.max(1, Math.floor(count / 48));
3079
- let best = 0, bestCost = Infinity;
3080
- for (let shift = 0; shift < count; shift += stride) {
3081
- let cost = 0;
3082
- for (let i = 0; i < count; i += stride) {
3083
- const j = (i + shift) % count;
3084
- const dx = a.p[i * 6] - ax - (b.p[j * 6] - bx);
3085
- const dy = a.p[i * 6 + 1] - ay - (b.p[j * 6 + 1] - by);
3086
- cost += dx * dx + dy * dy;
3087
- }
3088
- if (cost < bestCost) {
3089
- bestCost = cost;
3090
- best = shift;
3091
- }
3092
- }
3093
- if (best === 0) return b;
3094
- const out = new Float64Array(b.p.length);
3095
- out[0] = b.p[best * 6];
3096
- out[1] = b.p[best * 6 + 1];
3097
- for (let i = 0; i < count; i++) {
3098
- const j = (i + best) % count;
3099
- for (let k = 0; k < 6; k++) out[2 + i * 6 + k] = b.p[2 + j * 6 + k];
3100
- }
3101
- return { p: out, closed: b.closed };
3102
- }
3103
- function pointRing(x, y, count, closed) {
3104
- const out = new Float64Array(2 + count * 6);
3105
- for (let i = 0; i < out.length; i += 2) {
3106
- out[i] = x;
3107
- out[i + 1] = y;
3108
- }
3109
- return { p: out, closed };
3110
- }
3111
- function pairRings(from, to) {
3112
- const rank = (path) => [...path].sort((a2, b2) => Math.abs(signedArea(b2)) + ringLength(b2) * 0.01 - (Math.abs(signedArea(a2)) + ringLength(a2) * 0.01));
3113
- const a = rank(from), b = rank(to);
3114
- const pairs = [];
3115
- const free = b.slice();
3116
- for (const ringA of a) {
3117
- if (free.length === 0) {
3118
- const [x, y] = ringCenter(ringA);
3119
- pairs.push([ringA, pointRing(x, y, segmentCount(ringA), ringA.closed)]);
3120
- continue;
3121
- }
3122
- const [ax, ay] = ringCenter(ringA);
3123
- let bestIndex = 0, bestCost = Infinity;
3124
- for (let i = 0; i < Math.min(free.length, 3); i++) {
3125
- const [bx, by] = ringCenter(free[i]);
3126
- const cost = Math.hypot(ax - bx, ay - by) + i * 40;
3127
- if (cost < bestCost) {
3128
- bestCost = cost;
3129
- bestIndex = i;
3130
- }
3131
- }
3132
- pairs.push([ringA, free[bestIndex]]);
3133
- free.splice(bestIndex, 1);
3134
- }
3135
- for (const ringB of free) {
3136
- const [x, y] = ringCenter(ringB);
3137
- pairs.push([pointRing(x, y, segmentCount(ringB), ringB.closed), ringB]);
3138
- }
3139
- return pairs;
3140
- }
3141
- function alignPaths(from, to, minSegments = 12) {
3142
- const pairs = pairRings(from, to);
3143
- const a = [], b = [], closed = [];
3144
- for (const [ra, rb] of pairs) {
3145
- const target = Math.max(segmentCount(ra), segmentCount(rb), ra.closed && rb.closed ? minSegments : 1);
3146
- let x = growTo(ra, target);
3147
- let y = growTo(rb, target);
3148
- if (x.closed && y.closed) {
3149
- if (Math.sign(signedArea(x)) !== Math.sign(signedArea(y)) && signedArea(x) !== 0 && signedArea(y) !== 0) y = reverseRing(y);
3150
- y = bestRotation(x, y);
3151
- } else if (!x.closed && !y.closed) {
3152
- const n = x.p.length;
3153
- 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]);
3154
- 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]);
3155
- if (flipped < straight) y = reverseRing(y);
3156
- }
3157
- a.push(x.p);
3158
- b.push(y.p);
3159
- closed.push(x.closed && y.closed);
3160
- }
3161
- return { from: a, to: b, closed };
3162
- }
3163
- function pathMixer(from, to) {
3164
- if (from === to) return () => to;
3165
- if (pathLength(from) === 0 && from.length === 0) return (alpha) => alpha >= 1 ? to : from;
3166
- const aligned = alignPaths(from, to);
3167
- return (alpha) => {
3168
- if (alpha <= 0) return from;
3169
- if (alpha >= 1) return to;
3170
- const rings = new Array(aligned.from.length);
3171
- for (let r = 0; r < rings.length; r++) {
3172
- const a = aligned.from[r], b = aligned.to[r];
3173
- const out = new Float64Array(a.length);
3174
- for (let i = 0; i < a.length; i++) out[i] = a[i] + (b[i] - a[i]) * alpha;
3175
- rings[r] = { p: out, closed: aligned.closed[r] };
3176
- }
3177
- return rings;
3178
- };
2878
+ return rings;
2879
+ };
3179
2880
  }
3180
2881
 
3181
2882
  // src/stage/node.ts
@@ -3512,99 +3213,420 @@ var Node = class _Node {
3512
3213
  if (edge === "top") return this.shift(0, b.y - own.y);
3513
3214
  return this.shift(0, b.y + b.height - own.y - own.height);
3514
3215
  }
3515
- /** Lay out children in a row or column, keeping the group's center. */
3516
- arrange(side = "right", gap = 24) {
3517
- const [dx, dy] = direction(side);
3518
- const center = this.center;
3519
- let previous = null;
3520
- for (const child of this.children) {
3521
- if (previous) {
3522
- const b = previous.bounds(), own = child.bounds();
3523
- const px = b.x + b.width / 2 + dx * (b.width / 2 + gap + own.width / 2);
3524
- const py = b.y + b.height / 2 + dy * (b.height / 2 + gap + own.height / 2);
3525
- child.moveTo([dx === 0 ? b.x + b.width / 2 : px, dy === 0 ? b.y + b.height / 2 : py]);
3216
+ /** Lay out children in a row or column, keeping the group's center. */
3217
+ arrange(side = "right", gap = 24) {
3218
+ const [dx, dy] = direction(side);
3219
+ const center = this.center;
3220
+ let previous = null;
3221
+ for (const child of this.children) {
3222
+ if (previous) {
3223
+ const b = previous.bounds(), own = child.bounds();
3224
+ const px = b.x + b.width / 2 + dx * (b.width / 2 + gap + own.width / 2);
3225
+ const py = b.y + b.height / 2 + dy * (b.height / 2 + gap + own.height / 2);
3226
+ child.moveTo([dx === 0 ? b.x + b.width / 2 : px, dy === 0 ? b.y + b.height / 2 : py]);
3227
+ }
3228
+ previous = child;
3229
+ }
3230
+ return this.moveTo(center);
3231
+ }
3232
+ // ── Paint ─────────────────────────────────────────────────────────────
3233
+ fill(color, opacity) {
3234
+ this.set("fill", color === null ? null : toPaint(color));
3235
+ if (opacity !== void 0) this.set("fillOpacity", opacity);
3236
+ return this;
3237
+ }
3238
+ stroke(color, width, opacity) {
3239
+ this.set("stroke", color === null ? null : toPaint(color));
3240
+ if (width !== void 0) this.set("strokeWidth", width);
3241
+ if (opacity !== void 0) this.set("strokeOpacity", opacity);
3242
+ return this;
3243
+ }
3244
+ /** Recolor this node and its descendants, keeping whichever paints exist. */
3245
+ color(color) {
3246
+ const paint = toPaint(color);
3247
+ for (const node of this.all()) {
3248
+ if (node.get("stroke")) node.set("stroke", paint);
3249
+ if (node.get("fill")) node.set("fill", paint);
3250
+ if (node.get("glowColor") && !isGradient(paint)) node.set("glowColor", paint);
3251
+ }
3252
+ return this;
3253
+ }
3254
+ opacity(value) {
3255
+ return this.set("opacity", value);
3256
+ }
3257
+ /** Soft light around the shape. The radius is in stage pixels. */
3258
+ glow(radius, color) {
3259
+ this.set("glow", radius);
3260
+ if (color !== void 0) {
3261
+ const paint = toPaint(color);
3262
+ this.set("glowColor", isGradient(paint) ? null : paint);
3263
+ }
3264
+ return this;
3265
+ }
3266
+ dash(pattern, offset = 0) {
3267
+ this.set("dash", pattern);
3268
+ return this.set("dashOffset", offset);
3269
+ }
3270
+ zIndex(value) {
3271
+ return this.set("z", value);
3272
+ }
3273
+ /** Pin to the screen so the camera does not move this node. */
3274
+ pin() {
3275
+ return this.set("fixed", true);
3276
+ }
3277
+ hide() {
3278
+ return this.set("visible", false);
3279
+ }
3280
+ show() {
3281
+ return this.set("visible", true);
3282
+ }
3283
+ named(label) {
3284
+ this.label = label;
3285
+ return this;
3286
+ }
3287
+ };
3288
+ function boundsOfRect(m, width, height) {
3289
+ const corners = [apply(m, 0, 0), apply(m, width, 0), apply(m, width, height), apply(m, 0, height)];
3290
+ const xs = corners.map((c) => c[0]), ys = corners.map((c) => c[1]);
3291
+ const x = Math.min(...xs), y = Math.min(...ys);
3292
+ return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y };
3293
+ }
3294
+ function direction(side) {
3295
+ if (typeof side !== "string") return side;
3296
+ if (side === "left") return [-1, 0];
3297
+ if (side === "right") return [1, 0];
3298
+ if (side === "top" || side === "up") return [0, -1];
3299
+ return [0, 1];
3300
+ }
3301
+ function mountTree(node, time) {
3302
+ const wasVisible = node.base.visible;
3303
+ for (const entry of node.all()) entry.mounted = true;
3304
+ if (time > 0 || !wasVisible) {
3305
+ const track = node.track("visible");
3306
+ track.initial = false;
3307
+ if (wasVisible) track.step(time, true);
3308
+ }
3309
+ }
3310
+
3311
+ // src/stage/image.ts
3312
+ var ImageAssetError = class extends Error {
3313
+ constructor(message) {
3314
+ super(message);
3315
+ this.name = "ImageAssetError";
3316
+ }
3317
+ };
3318
+ var MAX_BYTES = 16 * 1024 * 1024;
3319
+ var MAX_PIXELS = 16 * 1024 * 1024;
3320
+ var RUNTIME = /* @__PURE__ */ Symbol.for("vizmatic.stage.image.runtime.v1");
3321
+ var host = globalThis;
3322
+ var runtime = host[RUNTIME] ?? Object.freeze({ prepared: /* @__PURE__ */ new WeakSet(), browserSources: /* @__PURE__ */ new WeakMap() });
3323
+ if (!host[RUNTIME]) Object.defineProperty(host, RUNTIME, { value: runtime });
3324
+ var { prepared, browserSources } = runtime;
3325
+
3326
+ // src/stage/display.ts
3327
+ var GLOW_PASSES = 7;
3328
+ function glowPasses(glow, width) {
3329
+ const out = [];
3330
+ for (let i = GLOW_PASSES; i >= 1; i--) {
3331
+ const k = i / GLOW_PASSES;
3332
+ out.push({ width: width + glow * 2 * k, alpha: 0.16 * (1 - k) * (1 - k) + 0.018 });
3333
+ }
3334
+ return out;
3335
+ }
3336
+ function glowOf(op) {
3337
+ if (op.glowColor) return op.glowColor;
3338
+ const paint = op.stroke ?? op.fill;
3339
+ if (!paint) return null;
3340
+ return isGradient(paint) ? sampleStops(paint.stops, 0.5) : paint;
3341
+ }
3342
+ var dCache = /* @__PURE__ */ new WeakMap();
3343
+ function pathData(path) {
3344
+ let d = dCache.get(path);
3345
+ if (d === void 0) {
3346
+ d = pathToD(path);
3347
+ dCache.set(path, d);
3348
+ }
3349
+ return d;
3350
+ }
3351
+ function fmt2(value) {
3352
+ return String(Math.round(value * 1e3) / 1e3);
3353
+ }
3354
+ function gradientDef(id, paint) {
3355
+ 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("");
3356
+ if (paint.type === "linear") {
3357
+ 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>`;
3358
+ }
3359
+ if (paint.type === "radial") {
3360
+ return `<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${fmt2(paint.center[0])}" cy="${fmt2(paint.center[1])}" r="${fmt2(paint.radius)}">${stops}</radialGradient>`;
3361
+ }
3362
+ return "";
3363
+ }
3364
+ function strokeAttrs(op) {
3365
+ let attrs = ` stroke-linecap="${op.cap}" stroke-linejoin="${op.join}"`;
3366
+ if (op.dash) attrs += ` stroke-dasharray="${op.dash.map(fmt2).join(" ")}" stroke-dashoffset="${fmt2(op.dashOffset)}"`;
3367
+ return attrs;
3368
+ }
3369
+ function escapeAttr(value) {
3370
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
3371
+ }
3372
+ function frameToSvg(frame, options = {}) {
3373
+ const scale = options.scale ?? 1;
3374
+ const w = frame.width, h = frame.height;
3375
+ const defs = [];
3376
+ const body = [];
3377
+ let gradientCount = 0;
3378
+ const paintAttr = (paint, attr, alpha) => {
3379
+ if (isGradient(paint)) {
3380
+ const id = `g${gradientCount++}`;
3381
+ defs.push(gradientDef(id, paint));
3382
+ return `${attr}="url(#${id})"${alpha < 1 ? ` ${attr}-opacity="${fmt2(alpha)}"` : ""}`;
3383
+ }
3384
+ const rgba = paint;
3385
+ const a = rgba[3] * alpha;
3386
+ return `${attr}="${css([rgba[0], rgba[1], rgba[2], 1])}"${a < 1 ? ` ${attr}-opacity="${fmt2(a)}"` : ""}`;
3387
+ };
3388
+ if (frame.background && !options.transparent) body.push(`<rect width="${w}" height="${h}" fill="${frame.background}"/>`);
3389
+ for (const op of frame.ops) {
3390
+ if (op.kind === "image") {
3391
+ const m = op.matrix;
3392
+ const { image } = op, crop = image.crop;
3393
+ if (crop && !image.asset) throw new ImageAssetError("Cropped image SVG needs a prepared image asset.");
3394
+ const picture = `<image href="${escapeAttr(image.src)}" width="${crop ? image.asset.width : image.width}" height="${crop ? image.asset.height : image.height}" preserveAspectRatio="none"/>`;
3395
+ 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;
3396
+ body.push(`<g transform="matrix(${m.map(fmt2).join(" ")})"${op.alpha < 1 ? ` opacity="${fmt2(op.alpha)}"` : ""}>${content}</g>`);
3397
+ continue;
3398
+ }
3399
+ const style = op.blend !== "normal" ? ` style="mix-blend-mode:${op.blend}"` : "";
3400
+ if (op.glow > 0) {
3401
+ const color = glowOf(op);
3402
+ const glowD = pathData(op.strokePath.length ? op.strokePath : op.path);
3403
+ if (color && glowD) {
3404
+ const base = Math.max(op.fillAlpha, op.strokeAlpha);
3405
+ const mode = frame.dark ? ' style="mix-blend-mode:screen"' : "";
3406
+ 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("");
3407
+ body.push(`<g${mode}>${passes}</g>`);
3408
+ }
3409
+ }
3410
+ if (op.fill && op.stroke && op.strokePath === op.path) {
3411
+ 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}/>`);
3412
+ continue;
3413
+ }
3414
+ if (op.fill) body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill, "fill", op.fillAlpha)}${style}/>`);
3415
+ if (op.stroke && op.strokePath.length) {
3416
+ body.push(`<path d="${pathData(op.strokePath)}" fill="none" ${paintAttr(op.stroke, "stroke", op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`);
3417
+ }
3418
+ }
3419
+ const defsBlock = defs.length ? `<defs>${defs.join("")}</defs>` : "";
3420
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${w * scale}" height="${h * scale}" viewBox="0 0 ${w} ${h}">${defsBlock}${body.join("")}</svg>`;
3421
+ }
3422
+
3423
+ // src/stage/raster.ts
3424
+ var import_node_module = require("module");
3425
+ var import_node_os = require("os");
3426
+ var import_node_worker_threads = require("worker_threads");
3427
+ var import_node_url = require("url");
3428
+ var RASTER_WORKER_SOURCE = String.raw`
3429
+ const { parentPort, workerData } = require('node:worker_threads')
3430
+ const { Resvg } = require(workerData.resvgPath)
3431
+
3432
+ function downsample(src, w, h, factor) {
3433
+ const dw = Math.max(1, Math.floor(w / factor)), dh = Math.max(1, Math.floor(h / factor))
3434
+ const out = new Float32Array(dw * dh * 3)
3435
+ const norm = 1 / (factor * factor)
3436
+ for (let y = 0; y < dh; y++) {
3437
+ for (let x = 0; x < dw; x++) {
3438
+ let r = 0, g = 0, b = 0
3439
+ for (let yy = 0; yy < factor; yy++) {
3440
+ let o = ((y * factor + yy) * w + x * factor) * 4
3441
+ for (let xx = 0; xx < factor; xx++) { r += src[o]; g += src[o + 1]; b += src[o + 2]; o += 4 }
3442
+ }
3443
+ const i = (y * dw + x) * 3
3444
+ out[i] = r * norm; out[i + 1] = g * norm; out[i + 2] = b * norm
3445
+ }
3446
+ }
3447
+ return { data: out, w: dw, h: dh }
3448
+ }
3449
+
3450
+ function boxBlur(img, radius) {
3451
+ const { data, w, h } = img
3452
+ const tmp = new Float32Array(data.length)
3453
+ const norm = 1 / (radius * 2 + 1)
3454
+ for (let y = 0; y < h; y++) {
3455
+ for (let c = 0; c < 3; c++) {
3456
+ let sum = 0
3457
+ for (let k = -radius; k <= radius; k++) sum += data[(y * w + Math.min(w - 1, Math.max(0, k))) * 3 + c]
3458
+ for (let x = 0; x < w; x++) {
3459
+ tmp[(y * w + x) * 3 + c] = sum * norm
3460
+ sum += data[(y * w + Math.min(w - 1, x + radius + 1)) * 3 + c] - data[(y * w + Math.max(0, x - radius)) * 3 + c]
3526
3461
  }
3527
- previous = child;
3528
3462
  }
3529
- return this.moveTo(center);
3530
3463
  }
3531
- // ── Paint ─────────────────────────────────────────────────────────────
3532
- fill(color, opacity) {
3533
- this.set("fill", color === null ? null : toPaint(color));
3534
- if (opacity !== void 0) this.set("fillOpacity", opacity);
3535
- return this;
3464
+ for (let x = 0; x < w; x++) {
3465
+ for (let c = 0; c < 3; c++) {
3466
+ let sum = 0
3467
+ for (let k = -radius; k <= radius; k++) sum += tmp[(Math.min(h - 1, Math.max(0, k)) * w + x) * 3 + c]
3468
+ for (let y = 0; y < h; y++) {
3469
+ data[(y * w + x) * 3 + c] = sum * norm
3470
+ sum += tmp[(Math.min(h - 1, y + radius + 1) * w + x) * 3 + c] - tmp[(Math.max(0, y - radius) * w + x) * 3 + c]
3471
+ }
3472
+ }
3536
3473
  }
3537
- stroke(color, width, opacity) {
3538
- this.set("stroke", color === null ? null : toPaint(color));
3539
- if (width !== void 0) this.set("strokeWidth", width);
3540
- if (opacity !== void 0) this.set("strokeOpacity", opacity);
3541
- return this;
3474
+ }
3475
+
3476
+ // Bloom: bright marks spill soft light. Blurred layers add on top of the sharp image.
3477
+ function bloom(pixels, w, h, amount, background) {
3478
+ const [br, bg, bb] = background
3479
+ const layers = []
3480
+ // The spread follows output width, so a small preview and a 4K master look alike.
3481
+ const k = w / 1920
3482
+ for (const [base, radius, weight] of [[4, 3, 0.55], [8, 4, 0.3], [16, 4, 0.15]]) {
3483
+ const factor = Math.max(1, Math.round(base * k))
3484
+ const layer = downsample(pixels, w, h, factor)
3485
+ const d = layer.data
3486
+ for (let i = 0; i < d.length; i += 3) {
3487
+ // Only light above the background contributes, so the page never lifts or fogs.
3488
+ d[i] = Math.max(0, d[i] - br); d[i + 1] = Math.max(0, d[i + 1] - bg); d[i + 2] = Math.max(0, d[i + 2] - bb)
3489
+ }
3490
+ boxBlur(layer, radius); boxBlur(layer, radius)
3491
+ layers.push({ ...layer, factor, weight })
3542
3492
  }
3543
- /** Recolor this node and its descendants, keeping whichever paints exist. */
3544
- color(color) {
3545
- const paint = toPaint(color);
3546
- for (const node of this.all()) {
3547
- if (node.get("stroke")) node.set("stroke", paint);
3548
- if (node.get("fill")) node.set("fill", paint);
3549
- if (node.get("glowColor") && !isGradient(paint)) node.set("glowColor", paint);
3493
+ for (let y = 0; y < h; y++) {
3494
+ for (let x = 0; x < w; x++) {
3495
+ const o = (y * w + x) * 4
3496
+ let r = 0, g = 0, b = 0
3497
+ for (const layer of layers) {
3498
+ const fx = (x + 0.5) / layer.factor - 0.5, fy = (y + 0.5) / layer.factor - 0.5
3499
+ const x0 = Math.max(0, Math.floor(fx)), y0 = Math.max(0, Math.floor(fy))
3500
+ const x1 = Math.min(layer.w - 1, x0 + 1), y1 = Math.min(layer.h - 1, y0 + 1)
3501
+ const tx = Math.max(0, fx - x0), ty = Math.max(0, fy - y0)
3502
+ const d = layer.data, lw = layer.w
3503
+ for (let c = 0; c < 3; c++) {
3504
+ const v = (d[(y0 * lw + x0) * 3 + c] * (1 - tx) + d[(y0 * lw + x1) * 3 + c] * tx) * (1 - ty)
3505
+ + (d[(y1 * lw + x0) * 3 + c] * (1 - tx) + d[(y1 * lw + x1) * 3 + c] * tx) * ty
3506
+ if (c === 0) r += v * layer.weight
3507
+ else if (c === 1) g += v * layer.weight
3508
+ else b += v * layer.weight
3509
+ }
3510
+ }
3511
+ // Screen blend keeps highlights from clipping harshly.
3512
+ pixels[o] = 255 - (255 - pixels[o]) * (255 - Math.min(255, r * amount * 2.4)) / 255
3513
+ pixels[o + 1] = 255 - (255 - pixels[o + 1]) * (255 - Math.min(255, g * amount * 2.4)) / 255
3514
+ pixels[o + 2] = 255 - (255 - pixels[o + 2]) * (255 - Math.min(255, b * amount * 2.4)) / 255
3550
3515
  }
3551
- return this;
3552
3516
  }
3553
- opacity(value) {
3554
- return this.set("opacity", value);
3517
+ }
3518
+
3519
+ function raster(svg, width, height) {
3520
+ const image = new Resvg(svg, { fitTo: { mode: 'width', value: width }, font: { loadSystemFonts: false } }).render()
3521
+ if (image.height === height) return image.pixels
3522
+ // Rounding can differ by a row at unusual sizes. Keep the requested size exactly.
3523
+ const out = new Uint8Array(width * height * 4)
3524
+ for (let y = 0; y < height; y++) {
3525
+ const row = Math.min(image.height - 1, y) * width * 4
3526
+ out.set(image.pixels.subarray(row, row + width * 4), y * width * 4)
3555
3527
  }
3556
- /** Soft light around the shape. The radius is in stage pixels. */
3557
- glow(radius, color) {
3558
- this.set("glow", radius);
3559
- if (color !== void 0) {
3560
- const paint = toPaint(color);
3561
- this.set("glowColor", isGradient(paint) ? null : paint);
3528
+ return out
3529
+ }
3530
+
3531
+ parentPort.on('message', (job) => {
3532
+ try {
3533
+ let out
3534
+ if (job.svgs.length === 1) {
3535
+ out = new Uint8Array(raster(job.svgs[0], job.width, job.height))
3536
+ } else {
3537
+ // Motion blur: average sub-frames across the shutter.
3538
+ const n = job.svgs.length
3539
+ // Sixteen bits hold 257 full-white sub-frames, at half the memory of thirty-two.
3540
+ let sum = null
3541
+ for (const svg of job.svgs) {
3542
+ const px = raster(svg, job.width, job.height)
3543
+ if (!sum) sum = n <= 257 ? new Uint16Array(px.length) : new Uint32Array(px.length)
3544
+ for (let i = 0; i < px.length; i++) sum[i] += px[i]
3545
+ }
3546
+ out = new Uint8Array(sum.length)
3547
+ for (let i = 0; i < sum.length; i++) out[i] = sum[i] / n + 0.5
3562
3548
  }
3563
- return this;
3549
+ if (job.bloom > 0) bloom(out, job.width, job.height, job.bloom, job.background)
3550
+ parentPort.postMessage({ id: job.id, pixels: out }, [out.buffer])
3551
+ } catch (error) {
3552
+ parentPort.postMessage({ id: job.id, error: String(error && error.message || error) })
3564
3553
  }
3565
- dash(pattern, offset = 0) {
3566
- this.set("dash", pattern);
3567
- return this.set("dashOffset", offset);
3554
+ })
3555
+ `;
3556
+ function resolveResvg() {
3557
+ const here = typeof __filename !== "undefined" ? __filename : (0, import_node_url.fileURLToPath)(void 0);
3558
+ return (0, import_node_module.createRequire)(here).resolve("@resvg/resvg-js");
3559
+ }
3560
+ var RasterPool = class {
3561
+ workers = [];
3562
+ idle = [];
3563
+ queue = [];
3564
+ pending = /* @__PURE__ */ new Map();
3565
+ nextId = 1;
3566
+ failure = null;
3567
+ constructor(size = defaultPoolSize()) {
3568
+ const resvgPath = resolveResvg();
3569
+ for (let i = 0; i < size; i++) {
3570
+ const worker = new import_node_worker_threads.Worker(RASTER_WORKER_SOURCE, { eval: true, workerData: { resvgPath } });
3571
+ worker.on("message", (message) => {
3572
+ const entry = this.pending.get(message.id);
3573
+ this.pending.delete(message.id);
3574
+ this.idle.push(worker);
3575
+ this.pump();
3576
+ if (!entry) return;
3577
+ if (message.error || !message.pixels) entry.reject(new Error(`Frame rasterization failed: ${message.error}`));
3578
+ else entry.resolve(message.pixels);
3579
+ });
3580
+ worker.on("error", (error) => this.fail(error instanceof Error ? error : new Error(String(error))));
3581
+ this.workers.push(worker);
3582
+ this.idle.push(worker);
3583
+ }
3568
3584
  }
3569
- zIndex(value) {
3570
- return this.set("z", value);
3585
+ get size() {
3586
+ return this.workers.length;
3571
3587
  }
3572
- /** Pin to the screen so the camera does not move this node. */
3573
- pin() {
3574
- return this.set("fixed", true);
3588
+ fail(error) {
3589
+ this.failure = error;
3590
+ for (const entry of this.pending.values()) entry.reject(error);
3591
+ this.pending.clear();
3575
3592
  }
3576
- hide() {
3577
- return this.set("visible", false);
3593
+ pump() {
3594
+ while (this.idle.length > 0 && this.queue.length > 0) {
3595
+ const worker = this.idle.pop();
3596
+ const { job, id } = this.queue.shift();
3597
+ worker.postMessage({ id, ...job });
3598
+ }
3578
3599
  }
3579
- show() {
3580
- return this.set("visible", true);
3600
+ run(job) {
3601
+ if (this.failure) return Promise.reject(this.failure);
3602
+ const id = this.nextId++;
3603
+ return new Promise((resolve3, reject) => {
3604
+ this.pending.set(id, { resolve: resolve3, reject });
3605
+ this.queue.push({ job, id });
3606
+ this.pump();
3607
+ });
3581
3608
  }
3582
- named(label) {
3583
- this.label = label;
3584
- return this;
3609
+ async close() {
3610
+ this.failure ??= new Error("The raster pool was closed.");
3611
+ for (const entry of this.pending.values()) entry.reject(this.failure);
3612
+ this.pending.clear();
3613
+ this.queue.length = 0;
3614
+ await Promise.all(this.workers.map((worker) => worker.terminate()));
3585
3615
  }
3586
3616
  };
3587
- function boundsOfRect(m, width, height) {
3588
- const corners = [apply(m, 0, 0), apply(m, width, 0), apply(m, width, height), apply(m, 0, height)];
3589
- const xs = corners.map((c) => c[0]), ys = corners.map((c) => c[1]);
3590
- const x = Math.min(...xs), y = Math.min(...ys);
3591
- return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y };
3592
- }
3593
- function direction(side) {
3594
- if (typeof side !== "string") return side;
3595
- if (side === "left") return [-1, 0];
3596
- if (side === "right") return [1, 0];
3597
- if (side === "top" || side === "up") return [0, -1];
3598
- return [0, 1];
3617
+ function defaultPoolSize() {
3618
+ return Math.max(1, Math.min(12, (0, import_node_os.cpus)().length - 2));
3599
3619
  }
3600
- function mountTree(node, time) {
3601
- const wasVisible = node.base.visible;
3602
- for (const entry of node.all()) entry.mounted = true;
3603
- if (time > 0 || !wasVisible) {
3604
- const track = node.track("visible");
3605
- track.initial = false;
3606
- if (wasVisible) track.step(time, true);
3607
- }
3620
+ function framesToJob(frames, width, parseBackground, height) {
3621
+ const first = frames[0];
3622
+ const scale = width / first.width;
3623
+ return {
3624
+ svgs: frames.map((frame) => frameToSvg(frame)),
3625
+ width,
3626
+ height: height ?? Math.round(first.height * scale),
3627
+ bloom: first.dark ? first.bloom : 0,
3628
+ background: parseBackground(first.background)
3629
+ };
3608
3630
  }
3609
3631
 
3610
3632
  // src/stage/stage.ts