@openartifactsai/motion-stage 0.0.0-stage → 0.23.0-rc.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.
Files changed (225) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/package.json +70 -4
  5. package/src/build.d.ts +18 -0
  6. package/src/build.js +73 -0
  7. package/src/host.d.ts +37 -0
  8. package/src/host.js +76 -0
  9. package/src/index.d.ts +11 -0
  10. package/src/index.js +6 -0
  11. package/src/layers.d.ts +30 -0
  12. package/src/layers.js +56 -0
  13. package/src/offline/audio.d.ts +19 -0
  14. package/src/offline/audio.js +20 -0
  15. package/src/offline/data.d.ts +26 -0
  16. package/src/offline/data.js +71 -0
  17. package/src/offline/main.d.ts +9 -0
  18. package/src/offline/main.js +52 -0
  19. package/src/offline/player.d.ts +23 -0
  20. package/src/offline/player.js +157 -0
  21. package/src/protocol/clip-guards.d.ts +5 -0
  22. package/src/protocol/clip-guards.js +22 -0
  23. package/src/protocol/guards.d.ts +6 -0
  24. package/src/protocol/guards.js +257 -0
  25. package/src/protocol/layer-guards.d.ts +7 -0
  26. package/src/protocol/layer-guards.js +100 -0
  27. package/src/protocol/layers.d.ts +135 -0
  28. package/src/protocol/layers.js +1 -0
  29. package/src/protocol/types.d.ts +340 -0
  30. package/src/protocol/types.js +7 -0
  31. package/src/protocol.d.ts +2 -0
  32. package/src/protocol.js +2 -0
  33. package/src/raster.d.ts +4 -0
  34. package/src/raster.js +2 -0
  35. package/src/runtime/assets.d.ts +19 -0
  36. package/src/runtime/assets.js +63 -0
  37. package/src/runtime/caption-box.d.ts +3 -0
  38. package/src/runtime/caption-box.js +16 -0
  39. package/src/runtime/captions.d.ts +31 -0
  40. package/src/runtime/captions.js +115 -0
  41. package/src/runtime/clip-captions.d.ts +9 -0
  42. package/src/runtime/clip-captions.js +27 -0
  43. package/src/runtime/clips.d.ts +83 -0
  44. package/src/runtime/clips.js +259 -0
  45. package/src/runtime/console.d.ts +13 -0
  46. package/src/runtime/console.js +99 -0
  47. package/src/runtime/cut.d.ts +7 -0
  48. package/src/runtime/cut.js +63 -0
  49. package/src/runtime/determinism.d.ts +12 -0
  50. package/src/runtime/determinism.js +47 -0
  51. package/src/runtime/film.d.ts +43 -0
  52. package/src/runtime/film.js +31 -0
  53. package/src/runtime/focus.d.ts +8 -0
  54. package/src/runtime/focus.js +71 -0
  55. package/src/runtime/fonts.d.ts +22 -0
  56. package/src/runtime/fonts.js +109 -0
  57. package/src/runtime/frame.d.ts +9 -0
  58. package/src/runtime/frame.js +140 -0
  59. package/src/runtime/fx/backdrop.d.ts +60 -0
  60. package/src/runtime/fx/backdrop.js +264 -0
  61. package/src/runtime/fx/color.d.ts +19 -0
  62. package/src/runtime/fx/color.js +84 -0
  63. package/src/runtime/fx/css-color.d.ts +6 -0
  64. package/src/runtime/fx/css-color.js +44 -0
  65. package/src/runtime/fx/curve.d.ts +12 -0
  66. package/src/runtime/fx/curve.js +34 -0
  67. package/src/runtime/fx/gl.d.ts +29 -0
  68. package/src/runtime/fx/gl.js +207 -0
  69. package/src/runtime/fx/glsl.d.ts +35 -0
  70. package/src/runtime/fx/glsl.js +113 -0
  71. package/src/runtime/fx/index.d.ts +23 -0
  72. package/src/runtime/fx/index.js +151 -0
  73. package/src/runtime/fx/key.d.ts +11 -0
  74. package/src/runtime/fx/key.js +21 -0
  75. package/src/runtime/fx/numbers.d.ts +14 -0
  76. package/src/runtime/fx/numbers.js +57 -0
  77. package/src/runtime/fx/pace.d.ts +17 -0
  78. package/src/runtime/fx/pace.js +26 -0
  79. package/src/runtime/fx/paint.d.ts +28 -0
  80. package/src/runtime/fx/paint.js +150 -0
  81. package/src/runtime/guard.d.ts +4 -0
  82. package/src/runtime/guard.js +141 -0
  83. package/src/runtime/hand-titles/index.d.ts +9 -0
  84. package/src/runtime/hand-titles/index.js +73 -0
  85. package/src/runtime/hand-titles/layer.d.ts +20 -0
  86. package/src/runtime/hand-titles/layer.js +118 -0
  87. package/src/runtime/hand-titles/place.d.ts +27 -0
  88. package/src/runtime/hand-titles/place.js +45 -0
  89. package/src/runtime/held-store.d.ts +35 -0
  90. package/src/runtime/held-store.js +63 -0
  91. package/src/runtime/held.d.ts +19 -0
  92. package/src/runtime/held.js +225 -0
  93. package/src/runtime/kit/camera.d.ts +59 -0
  94. package/src/runtime/kit/camera.js +81 -0
  95. package/src/runtime/kit/chip.d.ts +25 -0
  96. package/src/runtime/kit/chip.js +75 -0
  97. package/src/runtime/kit/count.d.ts +37 -0
  98. package/src/runtime/kit/count.js +100 -0
  99. package/src/runtime/kit/cursor.d.ts +46 -0
  100. package/src/runtime/kit/cursor.js +108 -0
  101. package/src/runtime/kit/dom.d.ts +14 -0
  102. package/src/runtime/kit/dom.js +46 -0
  103. package/src/runtime/kit/geometry.d.ts +24 -0
  104. package/src/runtime/kit/geometry.js +56 -0
  105. package/src/runtime/kit/index.d.ts +113 -0
  106. package/src/runtime/kit/index.js +157 -0
  107. package/src/runtime/kit/mark-strokes.d.ts +65 -0
  108. package/src/runtime/kit/mark-strokes.js +226 -0
  109. package/src/runtime/kit/marks.d.ts +21 -0
  110. package/src/runtime/kit/marks.js +165 -0
  111. package/src/runtime/kit/math.d.ts +23 -0
  112. package/src/runtime/kit/math.js +35 -0
  113. package/src/runtime/kit/paper.d.ts +7 -0
  114. package/src/runtime/kit/paper.js +27 -0
  115. package/src/runtime/kit/random.d.ts +8 -0
  116. package/src/runtime/kit/random.js +32 -0
  117. package/src/runtime/kit/text-fx.d.ts +18 -0
  118. package/src/runtime/kit/text-fx.js +55 -0
  119. package/src/runtime/kit/typing.d.ts +21 -0
  120. package/src/runtime/kit/typing.js +42 -0
  121. package/src/runtime/laid/layer.d.ts +44 -0
  122. package/src/runtime/laid/layer.js +370 -0
  123. package/src/runtime/layers/describe.d.ts +41 -0
  124. package/src/runtime/layers/describe.js +327 -0
  125. package/src/runtime/layers/item.d.ts +123 -0
  126. package/src/runtime/layers/item.js +150 -0
  127. package/src/runtime/layers/parts.d.ts +53 -0
  128. package/src/runtime/layers/parts.js +158 -0
  129. package/src/runtime/layers/rows.d.ts +4 -0
  130. package/src/runtime/layers/rows.js +233 -0
  131. package/src/runtime/layers/scan.d.ts +24 -0
  132. package/src/runtime/layers/scan.js +204 -0
  133. package/src/runtime/layers/walk.d.ts +16 -0
  134. package/src/runtime/layers/walk.js +337 -0
  135. package/src/runtime/load.d.ts +10 -0
  136. package/src/runtime/load.js +267 -0
  137. package/src/runtime/main.d.ts +1 -0
  138. package/src/runtime/main.js +90 -0
  139. package/src/runtime/modules.d.ts +23 -0
  140. package/src/runtime/modules.js +53 -0
  141. package/src/runtime/port.d.ts +8 -0
  142. package/src/runtime/port.js +46 -0
  143. package/src/runtime/questions.d.ts +24 -0
  144. package/src/runtime/questions.js +162 -0
  145. package/src/runtime/recut.d.ts +81 -0
  146. package/src/runtime/recut.js +325 -0
  147. package/src/runtime/render.d.ts +80 -0
  148. package/src/runtime/render.js +358 -0
  149. package/src/runtime/retouch/ask.d.ts +17 -0
  150. package/src/runtime/retouch/ask.js +171 -0
  151. package/src/runtime/retouch/entry.d.ts +77 -0
  152. package/src/runtime/retouch/entry.js +1 -0
  153. package/src/runtime/retouch/judge.d.ts +25 -0
  154. package/src/runtime/retouch/judge.js +209 -0
  155. package/src/runtime/retouch/look.d.ts +39 -0
  156. package/src/runtime/retouch/look.js +135 -0
  157. package/src/runtime/retouch/own-styles.d.ts +19 -0
  158. package/src/runtime/retouch/own-styles.js +141 -0
  159. package/src/runtime/retouch/parts.d.ts +22 -0
  160. package/src/runtime/retouch/parts.js +166 -0
  161. package/src/runtime/retouch/retouch.d.ts +37 -0
  162. package/src/runtime/retouch/retouch.js +238 -0
  163. package/src/runtime/retouch/seat.d.ts +40 -0
  164. package/src/runtime/retouch/seat.js +228 -0
  165. package/src/runtime/retouch/state.d.ts +37 -0
  166. package/src/runtime/retouch/state.js +153 -0
  167. package/src/runtime/retouch/type-style.d.ts +19 -0
  168. package/src/runtime/retouch/type-style.js +111 -0
  169. package/src/runtime/scan.d.ts +2 -0
  170. package/src/runtime/scan.js +49 -0
  171. package/src/runtime/scenes/card.d.ts +12 -0
  172. package/src/runtime/scenes/card.js +56 -0
  173. package/src/runtime/scenes/install.d.ts +69 -0
  174. package/src/runtime/scenes/install.js +528 -0
  175. package/src/runtime/scenes/read.d.ts +27 -0
  176. package/src/runtime/scenes/read.js +73 -0
  177. package/src/runtime/scenes/scoped.d.ts +13 -0
  178. package/src/runtime/scenes/scoped.js +46 -0
  179. package/src/runtime/score.d.ts +32 -0
  180. package/src/runtime/score.js +262 -0
  181. package/src/runtime/sketch/pen.d.ts +3 -0
  182. package/src/runtime/sketch/pen.js +371 -0
  183. package/src/runtime/sketch/strokes.d.ts +41 -0
  184. package/src/runtime/sketch/strokes.js +187 -0
  185. package/src/runtime/snapshot/draw.d.ts +14 -0
  186. package/src/runtime/snapshot/draw.js +125 -0
  187. package/src/runtime/snapshot/hold-first-draw.d.ts +12 -0
  188. package/src/runtime/snapshot/hold-first-draw.js +128 -0
  189. package/src/runtime/snapshot/lift.d.ts +41 -0
  190. package/src/runtime/snapshot/lift.js +161 -0
  191. package/src/runtime/snapshot/plate.d.ts +20 -0
  192. package/src/runtime/snapshot/plate.js +79 -0
  193. package/src/runtime/snapshot/serialize.d.ts +51 -0
  194. package/src/runtime/snapshot/serialize.js +286 -0
  195. package/src/runtime/snapshot/styles.d.ts +8 -0
  196. package/src/runtime/snapshot/styles.js +109 -0
  197. package/src/runtime/snapshot/xml.d.ts +6 -0
  198. package/src/runtime/snapshot/xml.js +110 -0
  199. package/src/runtime/stage-size.d.ts +7 -0
  200. package/src/runtime/stage-size.js +3 -0
  201. package/src/runtime/stage.d.ts +27 -0
  202. package/src/runtime/stage.js +154 -0
  203. package/src/runtime/stretch.d.ts +13 -0
  204. package/src/runtime/stretch.js +16 -0
  205. package/src/runtime/texts.d.ts +24 -0
  206. package/src/runtime/texts.js +211 -0
  207. package/src/runtime/video-sync.d.ts +51 -0
  208. package/src/runtime/video-sync.js +218 -0
  209. package/src/stills.d.ts +90 -0
  210. package/src/stills.js +329 -0
  211. package/src/tools/film.d.ts +13 -0
  212. package/src/tools/film.js +116 -0
  213. package/src/tools/levels.d.ts +8 -0
  214. package/src/tools/levels.js +28 -0
  215. package/src/tools/main.d.ts +1 -0
  216. package/src/tools/main.js +223 -0
  217. package/src/tools/score.d.ts +4 -0
  218. package/src/tools/score.js +35 -0
  219. package/src/tools/types.d.ts +84 -0
  220. package/src/tools/types.js +2 -0
  221. package/src/tools.d.ts +6 -0
  222. package/src/tools.js +4 -0
  223. package/src/virtual.d.ts +11 -0
  224. package/src/vite.d.ts +8 -0
  225. package/src/vite.js +43 -0
@@ -0,0 +1,35 @@
1
+ export const clamp01 = (x) => (x < 0 ? 0 : x > 1 ? 1 : x);
2
+ export const clamp = (x, low, high) => (x < low ? low : x > high ? high : x);
3
+ /** 0 to 1 across `a` to `b`. */
4
+ export const seg = (t, a, b) => clamp01((t - a) / (b - a));
5
+ export const lerp = (a, b, p) => a + (b - a) * p;
6
+ /** Ease-out cubic. */
7
+ export const eo = (x) => 1 - Math.pow(1 - clamp01(x), 3);
8
+ /** Ease-in cubic. */
9
+ export const ei = (x) => Math.pow(clamp01(x), 3);
10
+ export const eio = (x) => {
11
+ const p = clamp01(x);
12
+ return p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2;
13
+ };
14
+ /** Ease-out quart. */
15
+ export const eoq = (x) => 1 - Math.pow(1 - clamp01(x), 4);
16
+ /** Ease-out expo: a whip. */
17
+ export const eox = (x) => 1 - Math.pow(2, -10 * clamp01(x));
18
+ /** Back-out: overshoots, then settles. */
19
+ export const eob = (x, overshoot = 1.4) => {
20
+ const p = clamp01(x);
21
+ const c3 = overshoot + 1;
22
+ return 1 + c3 * Math.pow(p - 1, 3) + overshoot * Math.pow(p - 1, 2);
23
+ };
24
+ export const spring = (x, damp = 6, freq = 2.2) => {
25
+ const p = clamp01(x);
26
+ return 1 - Math.exp(-damp * p) * Math.cos(freq * Math.PI * 2 * p) * (1 - p);
27
+ };
28
+ export const step = (t, a) => (t >= a ? 1 : 0);
29
+ export const pulse = (t, a, b) => (t >= a && t < b ? 1 : 0);
30
+ export const smoothstep = (a, b, x) => {
31
+ const p = clamp01((x - a) / (b - a));
32
+ return p * p * (3 - 2 * p);
33
+ };
34
+ /** A scale that swells and shrinks gently around 1. */
35
+ export const breathe = (t, amount = 0.012, period = 3.2) => 1 + amount * Math.sin((t / period) * Math.PI * 2);
@@ -0,0 +1,7 @@
1
+ export type Point = [number, number];
2
+ /** A unit polygon (radius about 1) with straight edges at uneven angles, like a shape cut from paper. */
3
+ export declare function cutPaper(seed?: number, sides?: number, irregularity?: number): Point[];
4
+ /** Morphs polygon `from` toward `to`; `to` repeats when it has fewer points. */
5
+ export declare const polyLerp: (from: Point[], to: Point[], p: number) => Point[];
6
+ /** An SVG `points` list: the polygon scaled, turned by `rotation` radians and centred on (cx, cy). */
7
+ export declare function polyStr(points: Point[], cx: number, cy: number, sx: number, sy: number, rotation?: number): string;
@@ -0,0 +1,27 @@
1
+ import { lerp } from "./math.js";
2
+ import { rng } from "./random.js";
3
+ /** A unit polygon (radius about 1) with straight edges at uneven angles, like a shape cut from paper. */
4
+ export function cutPaper(seed = 1, sides = 7, irregularity = 0.28) {
5
+ const next = rng(seed * 977 + 3);
6
+ const points = [];
7
+ let angle = next() * Math.PI * 2;
8
+ for (let i = 0; i < sides; i++) {
9
+ angle += ((Math.PI * 2) / sides) * (0.7 + 0.6 * next());
10
+ const radius = 1 - irregularity * next();
11
+ points.push([Math.cos(angle) * radius, Math.sin(angle) * radius]);
12
+ }
13
+ return points;
14
+ }
15
+ /** Morphs polygon `from` toward `to`; `to` repeats when it has fewer points. */
16
+ export const polyLerp = (from, to, p) => from.map((a, i) => {
17
+ const b = to[i % to.length] ?? a;
18
+ return [lerp(a[0], b[0], p), lerp(a[1], b[1], p)];
19
+ });
20
+ /** An SVG `points` list: the polygon scaled, turned by `rotation` radians and centred on (cx, cy). */
21
+ export function polyStr(points, cx, cy, sx, sy, rotation = 0) {
22
+ const cos = Math.cos(rotation);
23
+ const sin = Math.sin(rotation);
24
+ return points
25
+ .map(([x, y]) => `${(cx + (x * cos - y * sin) * sx).toFixed(1)},${(cy + (x * sin + y * cos) * sy).toFixed(1)}`)
26
+ .join(' ');
27
+ }
@@ -0,0 +1,8 @@
1
+ /** A seeded linear congruential generator: the same seed gives the same numbers in 0..1, in every browser. */
2
+ export declare function rng(seed: number): () => number;
3
+ /** Smooth 1-D value noise in -1..1. */
4
+ export declare function vnoise(seed: number): (position: number) => number;
5
+ /** The seed `Math.random` restarts from at film time `ms` (whole milliseconds), so every frame draws the same numbers. */
6
+ export declare const frameSeed: (ms: number) => number;
7
+ /** FNV-1a of a scene id, mixed with the moment: a scene's own random numbers at that moment. */
8
+ export declare function sceneSeed(id: string, ms: number): number;
@@ -0,0 +1,32 @@
1
+ /** A seeded linear congruential generator: the same seed gives the same numbers in 0..1, in every browser. */
2
+ export function rng(seed) {
3
+ let state = seed >>> 0;
4
+ return () => {
5
+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
6
+ return state / 4294967296;
7
+ };
8
+ }
9
+ /** Smooth 1-D value noise in -1..1. */
10
+ export function vnoise(seed) {
11
+ const next = rng(seed);
12
+ const table = Array.from({ length: 256 }, () => next() * 2 - 1);
13
+ return (position) => {
14
+ const whole = Math.floor(position);
15
+ const fraction = position - whole;
16
+ const a = table[whole & 255] ?? 0;
17
+ const b = table[(whole + 1) & 255] ?? 0;
18
+ const u = fraction * fraction * (3 - 2 * fraction);
19
+ return a + (b - a) * u;
20
+ };
21
+ }
22
+ /** The seed `Math.random` restarts from at film time `ms` (whole milliseconds), so every frame draws the same numbers. */
23
+ export const frameSeed = (ms) => ((Math.round(ms) + 1) * 2654435761) >>> 0;
24
+ /** FNV-1a of a scene id, mixed with the moment: a scene's own random numbers at that moment. */
25
+ export function sceneSeed(id, ms) {
26
+ let hash = 2166136261;
27
+ for (let i = 0; i < id.length; i++) {
28
+ hash ^= id.charCodeAt(i);
29
+ hash = Math.imul(hash, 16777619);
30
+ }
31
+ return (hash ^ Math.imul(Math.round(ms) + 1, 2654435761)) >>> 0;
32
+ }
@@ -0,0 +1,18 @@
1
+ export interface TextFxOptions {
2
+ stagger?: number;
3
+ dur?: number;
4
+ dx?: number;
5
+ }
6
+ /** Splits an element's text into one inline-block span per word, once. */
7
+ declare function split(el: Element): HTMLSpanElement[];
8
+ /** Words drift in from the right one after another; returns when the last one has landed. */
9
+ declare function fadeFromRight(el: Element, t: number, start: number, options?: TextFxOptions): number;
10
+ declare function fadeOutLeft(el: Element, t: number, start: number, options?: TextFxOptions): void;
11
+ declare function inOut(el: Element, t: number, tIn: number, tOut?: number, options?: TextFxOptions): void;
12
+ export declare const TextFx: {
13
+ split: typeof split;
14
+ fadeFromRight: typeof fadeFromRight;
15
+ fadeOutLeft: typeof fadeOutLeft;
16
+ inOut: typeof inOut;
17
+ };
18
+ export {};
@@ -0,0 +1,55 @@
1
+ import { ei, eo, seg } from "./math.js";
2
+ const WORDS = new WeakMap();
3
+ /** Splits an element's text into one inline-block span per word, once. */
4
+ function split(el) {
5
+ const known = WORDS.get(el);
6
+ if (known)
7
+ return known;
8
+ const text = el.textContent ?? '';
9
+ el.textContent = '';
10
+ const spans = [];
11
+ for (const word of text.split(/(\s+)/)) {
12
+ if (/^\s+$/.test(word)) {
13
+ el.appendChild(document.createTextNode(word));
14
+ continue;
15
+ }
16
+ if (!word)
17
+ continue;
18
+ const span = document.createElement('span');
19
+ span.textContent = word;
20
+ span.style.display = 'inline-block';
21
+ span.style.willChange = 'opacity, transform';
22
+ el.appendChild(span);
23
+ spans.push(span);
24
+ }
25
+ WORDS.set(el, spans);
26
+ return spans;
27
+ }
28
+ /** Words drift in from the right one after another; returns when the last one has landed. */
29
+ function fadeFromRight(el, t, start, options = {}) {
30
+ const { stagger = 0.11, dur = 0.5, dx = 26 } = options;
31
+ const words = split(el);
32
+ words.forEach((span, i) => {
33
+ const p = eo(seg(t, start + i * stagger, start + i * stagger + dur));
34
+ span.style.opacity = String(p);
35
+ span.style.transform = `translateX(${((1 - p) * dx).toFixed(1)}px)`;
36
+ });
37
+ return start + (words.length - 1) * stagger + dur;
38
+ }
39
+ function fadeOutLeft(el, t, start, options = {}) {
40
+ const { stagger = 0.07, dur = 0.35, dx = 22 } = options;
41
+ split(el).forEach((span, i) => {
42
+ const p = ei(seg(t, start + i * stagger, start + i * stagger + dur));
43
+ if (t < start)
44
+ return;
45
+ span.style.opacity = String(1 - p);
46
+ span.style.transform = `translateX(${(-p * dx).toFixed(1)}px)`;
47
+ });
48
+ }
49
+ function inOut(el, t, tIn, tOut, options) {
50
+ if (tOut !== undefined && t >= tOut)
51
+ fadeOutLeft(el, t, tOut, options);
52
+ else
53
+ fadeFromRight(el, t, tIn, options);
54
+ }
55
+ export const TextFx = { split, fadeFromRight, fadeOutLeft, inOut };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The first `count` UTF-16 units of `text`, or one fewer where unit `count` would split a surrogate pair
3
+ * (most emoji): half a pair alone draws as U+FFFD.
4
+ */
5
+ export declare const uncut: (text: string, count: number) => string;
6
+ export interface Typist {
7
+ text: string;
8
+ /** Film seconds at which each character lands. */
9
+ times: number[];
10
+ end: number;
11
+ count(now: number): number;
12
+ at(now: number): string;
13
+ }
14
+ /**
15
+ * A natural typing schedule for `text` from `start` at about `cps` characters a second.
16
+ * Every time also goes to `heard`, so a score can put a key click on each.
17
+ */
18
+ export declare function typist(text: string, start: number, cps: number, seed?: number, heard?: number[]): Typist;
19
+ /** The part of `text` shown at `t` when it streams in chunks from `start`, like a model's reply. */
20
+ export declare function streamed(text: string, t: number, start: number, cps?: number, chunk?: number): string;
21
+ export declare const esc: (text: string) => string;
@@ -0,0 +1,42 @@
1
+ import { rng } from "./random.js";
2
+ /**
3
+ * The first `count` UTF-16 units of `text`, or one fewer where unit `count` would split a surrogate pair
4
+ * (most emoji): half a pair alone draws as U+FFFD.
5
+ */
6
+ export const uncut = (text, count) => text.slice(0, count > 0 && count < text.length && (text.charCodeAt(count - 1) & 0xfc00) === 0xd800 ? count - 1 : count);
7
+ /**
8
+ * A natural typing schedule for `text` from `start` at about `cps` characters a second.
9
+ * Every time also goes to `heard`, so a score can put a key click on each.
10
+ */
11
+ export function typist(text, start, cps, seed = 7, heard) {
12
+ const next = rng(seed);
13
+ const times = [];
14
+ let t = start;
15
+ for (let i = 0; i < text.length; i++) {
16
+ let gap = (1 / cps) * (0.55 + 0.9 * next());
17
+ if (text[i] === ' ')
18
+ gap += 0.035;
19
+ if (text[i - 1] === '.' || text[i - 1] === '!')
20
+ gap += 0.16;
21
+ t += gap;
22
+ times.push(t);
23
+ }
24
+ if (heard)
25
+ for (const time of times)
26
+ heard.push(time);
27
+ const count = (now) => {
28
+ let typed = 0;
29
+ while (typed < times.length && (times[typed] ?? Infinity) <= now)
30
+ typed++;
31
+ return typed;
32
+ };
33
+ return { text, times, end: t, count, at: (now) => uncut(text, count(now)) };
34
+ }
35
+ /** The part of `text` shown at `t` when it streams in chunks from `start`, like a model's reply. */
36
+ export function streamed(text, t, start, cps = 95, chunk = 7) {
37
+ if (t < start)
38
+ return '';
39
+ const shown = Math.floor(((t - start) * cps) / chunk) * chunk;
40
+ return uncut(text, Math.min(text.length, Math.max(0, shown)));
41
+ }
42
+ export const esc = (text) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;');
@@ -0,0 +1,44 @@
1
+ import { type LaidPart, type LaidPlan, type LaidPoint, type LaidRecord } from '@openartifactsai/motion-core';
2
+ import type { FilmPart } from '../../protocol.js';
3
+ import { type VideoMode } from '../video-sync.js';
4
+ /**
5
+ * The videos, photos and shapes a person laid over the film (`modules/laid.json`), drawn on the stage after each
6
+ * render: two holders over the picture, the back one and the front one, under the captions. What shows depends only
7
+ * on the played time, so exported frames and stills show the same as live play.
8
+ */
9
+ export declare const PLACED_ATTRIBUTE = "data-film-placed";
10
+ export declare const PLACED_ITEM_ATTRIBUTE = "data-film-placed-item";
11
+ export declare const isPlaced: (node: Node) => boolean;
12
+ /** Played time and the stage's size, for drawing. */
13
+ export interface LaidLayer {
14
+ draw(t: number, stage: HTMLElement): void;
15
+ /** A record tried without a reload; `null` takes back to the one the film loaded with. */
16
+ set(record: LaidRecord | null): void;
17
+ /** Laid videos follow played time at their own speed: play, hold or settle on a frame. */
18
+ sync(t: number, mode: VideoMode, quick: boolean): Promise<unknown> | null;
19
+ readonly plan: LaidPlan;
20
+ }
21
+ export declare const laidParts: (parts: readonly FilmPart[]) => LaidPart[];
22
+ /** What seating the holders reads of the stage's children: an element, or a stand-in for one. */
23
+ export interface SeatChild<N> {
24
+ readonly parentNode: unknown;
25
+ readonly nextElementSibling: N | null;
26
+ readonly previousElementSibling: N | null;
27
+ readonly classList: {
28
+ contains(name: string): boolean;
29
+ };
30
+ }
31
+ export interface SeatStage<N> {
32
+ readonly lastElementChild: N | null;
33
+ insertBefore(node: N, before: N | null): unknown;
34
+ querySelector(selector: string): N | null;
35
+ }
36
+ /**
37
+ * Where the two holders stand among the stage's children: over the film's own picture and under the captions. While a
38
+ * scene comes on they lie over the held picture of the one before, since laid things run across cuts; otherwise the
39
+ * back one goes just under a person's titles and the front one just over them.
40
+ */
41
+ export declare function seatHolders<N extends SeatChild<N>>(stage: SeatStage<N>, back: N, front: N): void;
42
+ /** A point on the edge of a `w` × `h` box, from its compass name. */
43
+ export declare function pointIn(point: LaidPoint, w: number, h: number): [number, number];
44
+ export declare function makeLaidLayer(loaded: LaidRecord | null, parts: readonly FilmPart[], says?: (text: string) => void): LaidLayer;
@@ -0,0 +1,370 @@
1
+ import { LAID_VIDEO_LEAD, isStrokeShape, laidAssetKind, laidSceneKey, planLaid, } from '@openartifactsai/motion-core';
2
+ import { assetStore } from "../assets.js";
3
+ import { nudgedRate, RESEEK_SECONDS, warnOnce, watchVideo } from "../video-sync.js";
4
+ /**
5
+ * The videos, photos and shapes a person laid over the film (`modules/laid.json`), drawn on the stage after each
6
+ * render: two holders over the picture, the back one and the front one, under the captions. What shows depends only
7
+ * on the played time, so exported frames and stills show the same as live play.
8
+ */
9
+ export const PLACED_ATTRIBUTE = 'data-film-placed';
10
+ export const PLACED_ITEM_ATTRIBUTE = 'data-film-placed-item';
11
+ export const isPlaced = (node) => node instanceof Element && node.hasAttribute(PLACED_ATTRIBUTE);
12
+ export const laidParts = (parts) => parts.map((part, index) => ({ key: laidSceneKey(part.key, index), start: part.p0, dur: part.dur, label: part.label }));
13
+ const IMPORTANT = (style, name, value) => style.setProperty(name, value, 'important');
14
+ const HOLDER_STYLE = [
15
+ ['position', 'absolute'],
16
+ ['left', '0'],
17
+ ['top', '0'],
18
+ ['width', '100%'],
19
+ ['height', '100%'],
20
+ ['margin', '0'],
21
+ ['padding', '0'],
22
+ ['overflow', 'hidden'],
23
+ ['pointer-events', 'none'],
24
+ ['z-index', '2147483647'],
25
+ ['transform', 'none'],
26
+ ['filter', 'none'],
27
+ ['opacity', '1'],
28
+ ];
29
+ function holder(layer) {
30
+ const div = document.createElement('div');
31
+ div.setAttribute(PLACED_ATTRIBUTE, layer);
32
+ for (const [name, value] of HOLDER_STYLE)
33
+ IMPORTANT(div.style, name, value);
34
+ return div;
35
+ }
36
+ /**
37
+ * Where the two holders stand among the stage's children: over the film's own picture and under the captions. While a
38
+ * scene comes on they lie over the held picture of the one before, since laid things run across cuts; otherwise the
39
+ * back one goes just under a person's titles and the front one just over them.
40
+ */
41
+ export function seatHolders(stage, back, front) {
42
+ const put = (node, before) => {
43
+ if (node.parentNode !== stage || node.nextElementSibling !== before)
44
+ stage.insertBefore(node, before);
45
+ };
46
+ const held = stage.querySelector(':scope > [data-film-held]');
47
+ const title = stage.querySelector(':scope > [data-film-title]');
48
+ if (held !== null) {
49
+ let after = held.nextElementSibling;
50
+ while (after === back || after === front)
51
+ after = after.nextElementSibling;
52
+ put(front, after);
53
+ put(back, front);
54
+ return;
55
+ }
56
+ if (title !== null) {
57
+ put(back, title);
58
+ put(front, title.nextElementSibling === front ? front.nextElementSibling : title.nextElementSibling);
59
+ return;
60
+ }
61
+ let caption = null;
62
+ for (let c = stage.lastElementChild; c !== null && caption === null; c = c.previousElementSibling)
63
+ if (c.classList.contains('film-caption'))
64
+ caption = c;
65
+ put(front, caption);
66
+ put(back, front);
67
+ }
68
+ /** A point on the edge of a `w` × `h` box, from its compass name. */
69
+ export function pointIn(point, w, h) {
70
+ const x = point.includes('w') ? 0 : point.includes('e') ? w : w / 2;
71
+ const y = point.includes('n') ? 0 : point.includes('s') ? h : h / 2;
72
+ return [x, y];
73
+ }
74
+ const SVG = 'http://www.w3.org/2000/svg';
75
+ /** The colour an ink stands for: a palette role read off the stage, else white; a hex colour as it is. */
76
+ function inkColour(ink, stage) {
77
+ if (ink === undefined)
78
+ return '#ffffff';
79
+ if (ink.startsWith('#'))
80
+ return ink;
81
+ const read = getComputedStyle(stage).getPropertyValue('--' + ink).trim();
82
+ return read !== '' ? read : '#ffffff';
83
+ }
84
+ function drawShape(box, item, stage, width, height) {
85
+ const colour = inkColour(item.ink, stage);
86
+ const short = Math.min(width, height);
87
+ const stroke = Math.max(1, (item.weight ?? 0.008) * short);
88
+ IMPORTANT(box.style, 'opacity', String(item.alpha ?? 1));
89
+ if (!isStrokeShape(item.shape)) {
90
+ IMPORTANT(box.style, 'box-sizing', 'border-box');
91
+ const radius = item.shape === 'oval' ? '50%' : `${(item.round ?? 0) * Math.min(item.box.w * width, item.box.h * height)}px`;
92
+ IMPORTANT(box.style, 'border-radius', radius);
93
+ if (item.outline) {
94
+ IMPORTANT(box.style, 'border', `${stroke}px solid ${colour}`);
95
+ IMPORTANT(box.style, 'background', 'transparent');
96
+ }
97
+ else {
98
+ IMPORTANT(box.style, 'border', '0');
99
+ IMPORTANT(box.style, 'background', colour);
100
+ }
101
+ box.replaceChildren();
102
+ return;
103
+ }
104
+ const w = item.box.w * width;
105
+ const h = item.box.h * height;
106
+ const [a, b] = item.points ?? ['w', 'e'];
107
+ const [x0, y0] = pointIn(a, w, h);
108
+ let [x1, y1] = pointIn(b, w, h);
109
+ const svg = document.createElementNS(SVG, 'svg');
110
+ svg.setAttribute('width', String(w));
111
+ svg.setAttribute('height', String(h));
112
+ svg.setAttribute('viewBox', `0 0 ${w} ${h}`);
113
+ svg.setAttribute('style', 'position:absolute;left:0;top:0;overflow:visible');
114
+ const parts = [];
115
+ if (item.shape === 'arrow') {
116
+ const length = Math.hypot(x1 - x0, y1 - y0) || 1;
117
+ const ux = (x1 - x0) / length;
118
+ const uy = (y1 - y0) / length;
119
+ const head = Math.min(length * 0.6, stroke * 4);
120
+ const tip = [x1, y1];
121
+ // The line stops where the head starts, so its round cap does not show past the tip.
122
+ x1 -= ux * head * 0.9;
123
+ y1 -= uy * head * 0.9;
124
+ const back = [tip[0] - ux * head, tip[1] - uy * head];
125
+ const side = head * 0.6;
126
+ const polygon = document.createElementNS(SVG, 'polygon');
127
+ polygon.setAttribute('points', [tip, [back[0] - uy * side, back[1] + ux * side], [back[0] + uy * side, back[1] - ux * side]].map(([x, y]) => `${x},${y}`).join(' '));
128
+ polygon.setAttribute('fill', colour);
129
+ polygon.setAttribute('stroke', colour);
130
+ polygon.setAttribute('stroke-linejoin', 'round');
131
+ polygon.setAttribute('stroke-width', String(stroke * 0.5));
132
+ parts.push(polygon);
133
+ }
134
+ const line = document.createElementNS(SVG, 'line');
135
+ line.setAttribute('x1', String(x0));
136
+ line.setAttribute('y1', String(y0));
137
+ line.setAttribute('x2', String(x1));
138
+ line.setAttribute('y2', String(y1));
139
+ line.setAttribute('stroke', colour);
140
+ line.setAttribute('stroke-width', String(stroke));
141
+ line.setAttribute('stroke-linecap', 'round');
142
+ svg.append(line, ...parts);
143
+ IMPORTANT(box.style, 'background', 'transparent');
144
+ IMPORTANT(box.style, 'border', '0');
145
+ box.replaceChildren(svg);
146
+ }
147
+ function placeBox(box, item) {
148
+ const { x, y, w, h } = item.box;
149
+ IMPORTANT(box.style, 'position', 'absolute');
150
+ IMPORTANT(box.style, 'left', `${x * 100}%`);
151
+ IMPORTANT(box.style, 'top', `${y * 100}%`);
152
+ IMPORTANT(box.style, 'width', `${w * 100}%`);
153
+ IMPORTANT(box.style, 'height', `${h * 100}%`);
154
+ IMPORTANT(box.style, 'margin', '0');
155
+ IMPORTANT(box.style, 'padding', '0');
156
+ IMPORTANT(box.style, 'overflow', isStrokeShape(item.shape) ? 'visible' : 'hidden');
157
+ }
158
+ function media(item) {
159
+ const fill = (node) => {
160
+ for (const [name, value] of [
161
+ ['position', 'absolute'],
162
+ ['left', '0'],
163
+ ['top', '0'],
164
+ ['width', '100%'],
165
+ ['height', '100%'],
166
+ ['max-width', 'none'],
167
+ ['margin', '0'],
168
+ ['object-fit', item.fit],
169
+ ])
170
+ IMPORTANT(node.style, name, value);
171
+ };
172
+ const url = item.asset === undefined ? '' : assetStore.url(item.asset);
173
+ if (item.kind === 'photo') {
174
+ const image = document.createElement('img');
175
+ image.alt = '';
176
+ image.decoding = 'sync';
177
+ image.src = url;
178
+ fill(image);
179
+ return { node: image, video: null };
180
+ }
181
+ const video = document.createElement('video');
182
+ video.muted = true;
183
+ video.playsInline = true;
184
+ video.preload = 'auto';
185
+ video.src = url;
186
+ fill(video);
187
+ watchVideo(video);
188
+ return { node: video, video };
189
+ }
190
+ const lookOf = (item, width, height) => JSON.stringify([item, width, height]);
191
+ /** Settles once the video shows the frame it was sought to, or after `ms`. */
192
+ function seekDone(video, ms) {
193
+ if (video.error || (!video.seeking && video.readyState >= 2))
194
+ return null;
195
+ return new Promise((resolve) => {
196
+ const events = ['seeked', 'loadeddata', 'error'];
197
+ const done = () => {
198
+ clearTimeout(timer);
199
+ for (const name of events)
200
+ video.removeEventListener(name, check);
201
+ resolve();
202
+ };
203
+ const check = () => {
204
+ if (video.error || (!video.seeking && video.readyState >= 2))
205
+ done();
206
+ };
207
+ const timer = setTimeout(done, ms);
208
+ for (const name of events)
209
+ video.addEventListener(name, check);
210
+ });
211
+ }
212
+ export function makeLaidLayer(loaded, parts, says = (text) => console.info(text)) {
213
+ const laidPartsNow = laidParts(parts);
214
+ const kindOf = (name) => (assetStore.has(name) ? laidAssetKind(assetStore.mime(name)) : null);
215
+ const back = holder('back');
216
+ const front = holder('front');
217
+ const drawn = new Map();
218
+ let plan = { shown: [], sounds: [], leftOut: [] };
219
+ let told = '';
220
+ const tell = (next, record) => {
221
+ const lines = next.leftOut.map(({ id, why }) => {
222
+ const item = record.items.find((each) => each.id === id);
223
+ const name = item?.name ?? item?.asset ?? id;
224
+ return why === 'asset'
225
+ ? `laid.json: ${name} is left out: its asset is missing or not a ${item?.kind === 'photo' ? 'picture' : 'video'}.`
226
+ : why === 'scene'
227
+ ? `laid.json: ${name} is left out: the scene it was laid on is gone or too short.`
228
+ : `laid.json: ${name} is left out: at most 8 laid videos play, 2 at once.`;
229
+ });
230
+ const text = lines.join('\n');
231
+ if (text !== '' && text !== told)
232
+ says(text);
233
+ told = text;
234
+ };
235
+ const take = (record) => {
236
+ try {
237
+ const next = record === null ? { shown: [], sounds: [], leftOut: [] } : planLaid(record, laidPartsNow, kindOf);
238
+ if (record !== null)
239
+ tell(next, record);
240
+ plan = next;
241
+ }
242
+ catch (error) {
243
+ // A record that cannot be laid drops what was laid, never the film.
244
+ plan = { shown: [], sounds: [], leftOut: [] };
245
+ console.warn('laid.json could not be laid over the film: ' + String(error instanceof Error ? error.message : error));
246
+ }
247
+ };
248
+ take(loaded);
249
+ const visible = (entry, t) => t >= entry.start && t < entry.end;
250
+ return {
251
+ get plan() {
252
+ return plan;
253
+ },
254
+ set(record) {
255
+ take(record ?? loaded);
256
+ },
257
+ draw(t, stage) {
258
+ const width = stage.offsetWidth || 1;
259
+ const height = stage.offsetHeight || 1;
260
+ const wanted = new Set(plan.shown.map((entry) => entry.item.id));
261
+ for (const [id, each] of drawn) {
262
+ if (wanted.has(id))
263
+ continue;
264
+ each.video?.pause();
265
+ each.box.remove();
266
+ drawn.delete(id);
267
+ }
268
+ // Topmost first in the plan: each holder is filled bottom up.
269
+ const order = { back: [], front: [] };
270
+ for (const entry of [...plan.shown].reverse()) {
271
+ const { item } = entry;
272
+ let each = drawn.get(item.id);
273
+ if (each !== undefined && (each.entry.item.kind !== item.kind || each.entry.item.asset !== item.asset)) {
274
+ each.video?.pause();
275
+ each.box.remove();
276
+ drawn.delete(item.id);
277
+ each = undefined;
278
+ }
279
+ if (each === undefined) {
280
+ const box = document.createElement('div');
281
+ box.setAttribute(PLACED_ITEM_ATTRIBUTE, item.id);
282
+ let video = null;
283
+ if (item.kind !== 'shape') {
284
+ const made = media(item);
285
+ box.appendChild(made.node);
286
+ video = made.video;
287
+ }
288
+ each = { entry, box, video, look: '' };
289
+ drawn.set(item.id, each);
290
+ }
291
+ each.entry = entry;
292
+ const look = lookOf(item, width, height);
293
+ if (each.look !== look) {
294
+ each.look = look;
295
+ placeBox(each.box, item);
296
+ if (item.kind === 'shape')
297
+ drawShape(each.box, item, stage, width, height);
298
+ else {
299
+ const node = each.box.firstElementChild;
300
+ if (node instanceof HTMLElement)
301
+ IMPORTANT(node.style, 'object-fit', item.fit);
302
+ }
303
+ }
304
+ IMPORTANT(each.box.style, 'visibility', visible(entry, t) ? 'visible' : 'hidden');
305
+ order[item.layer].push(each.box);
306
+ }
307
+ for (const [layer, list] of [
308
+ [back, order.back],
309
+ [front, order.front],
310
+ ]) {
311
+ list.forEach((box, index) => {
312
+ if (layer.children[index] !== box)
313
+ layer.insertBefore(box, layer.children[index] ?? null);
314
+ });
315
+ }
316
+ if (plan.shown.length === 0) {
317
+ back.remove();
318
+ front.remove();
319
+ }
320
+ else
321
+ seatHolders(stage, back, front);
322
+ },
323
+ sync(t, mode, quick) {
324
+ const waits = [];
325
+ for (const each of drawn.values()) {
326
+ const video = each.video;
327
+ if (video === null)
328
+ continue;
329
+ const { entry } = each;
330
+ video.muted = true;
331
+ if (video.error)
332
+ continue;
333
+ const on = t >= entry.start - LAID_VIDEO_LEAD && t < entry.end;
334
+ const length = video.duration;
335
+ let second = entry.item.from + Math.max(0, t - entry.start);
336
+ if (length > 0 && Number.isFinite(length))
337
+ second = Math.min(second, length - 0.001);
338
+ second += 0.0005;
339
+ if (mode === 'play' && on && t >= entry.start) {
340
+ const steady = !video.paused && !video.seeking && video.readyState >= 3;
341
+ const drift = second - video.currentTime;
342
+ const rate = nudgedRate(steady ? drift : 0, 1);
343
+ if (Math.abs(video.playbackRate - rate) > 1e-4)
344
+ video.playbackRate = rate;
345
+ if ((video.paused || steady) && Math.abs(drift) > RESEEK_SECONDS)
346
+ video.currentTime = second;
347
+ if (video.paused)
348
+ video.play().catch((error) => {
349
+ const name = error instanceof Error ? error.name : String(error);
350
+ if (name !== 'AbortError')
351
+ warnOnce(video, 'play', 'laid on the film could not play: ' + name);
352
+ });
353
+ continue;
354
+ }
355
+ if (!video.paused)
356
+ video.pause();
357
+ if (!on)
358
+ continue;
359
+ if (Math.abs(video.currentTime - second) > 0.5 / 60)
360
+ video.currentTime = second;
361
+ if (mode === 'frame') {
362
+ const wait = seekDone(video, quick ? 250 : 4000);
363
+ if (wait)
364
+ waits.push(wait);
365
+ }
366
+ }
367
+ return waits.length > 0 ? Promise.all(waits) : null;
368
+ },
369
+ };
370
+ }