@margoengine/cutscene 0.0.0-stage → 1.0.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.
@@ -0,0 +1,69 @@
1
+ import type { CutsceneState, CutsceneTrackType } from './cutscene.js';
2
+ import { type ItemRef, TimelineEditor } from './editor.js';
3
+ /** A boolean or string held until the next key. */
4
+ export interface DiscreteKey {
5
+ time: number;
6
+ value: boolean | string;
7
+ }
8
+ /** Step-sampled visibility flags, labels and other nonnumeric properties. */
9
+ export interface DiscreteTrack {
10
+ type: 'discrete';
11
+ id: string;
12
+ target: string;
13
+ property: string;
14
+ keys: DiscreteKey[];
15
+ muted?: boolean;
16
+ }
17
+ declare module './document.js' {
18
+ interface CustomTrackTypes {
19
+ discrete: DiscreteTrack;
20
+ }
21
+ }
22
+ /** Registers validation, step sampling and default editor key fields for discrete tracks. Pass in the tracks option. */
23
+ export declare function discreteTrack(): CutsceneTrackType;
24
+ /** Discrete property values by target then property name. State and nested timing remain pure and seek independent. */
25
+ export declare function discreteOf(state: CutsceneState): Record<string, Record<string, boolean | string>>;
26
+ /** Optional placement of the nested authoring controls. */
27
+ export interface NestedTimelineEditorOptions {
28
+ /** Default the outer editor's element: nested panels open inline there. */
29
+ parent?: HTMLElement;
30
+ /** Maximum milliseconds between two stationary clip presses. Default 400; capture suppresses native dblclick. */
31
+ doubleClickMs?: number;
32
+ }
33
+ /** Inline editing of nested timeline clips, with local playheads, shared root undo and boolean/string key controls. */
34
+ export declare class NestedTimelineEditor {
35
+ readonly editor: TimelineEditor;
36
+ readonly element: HTMLDivElement;
37
+ private readonly panes;
38
+ private active;
39
+ private pressed?;
40
+ private clicked?;
41
+ private readonly doubleClickMs;
42
+ private readonly select;
43
+ private readonly value;
44
+ private readonly flag;
45
+ private readonly button;
46
+ private readonly abort;
47
+ private readonly off;
48
+ constructor(editor: TimelineEditor, { parent, doubleClickMs }?: NestedTimelineEditorOptions);
49
+ /** Editors opened inside nested clips, from outermost to innermost. */
50
+ get editors(): readonly TimelineEditor[];
51
+ private tracks;
52
+ private activate;
53
+ private fields;
54
+ /** Inserts/replaces a discrete key in the active panel at its playhead and selects it. */
55
+ keyDiscrete(track: string, value: boolean | string): ItemRef;
56
+ /** Opens a timeline clip inline. Its definition is edited in place, shared by every placement of that definition. */
57
+ open(ref: ItemRef, parent?: TimelineEditor): TimelineEditor;
58
+ private clip;
59
+ private mapping;
60
+ private syncTimes;
61
+ private validatePanes;
62
+ private readonly rememberPress;
63
+ private readonly finishPress;
64
+ /** Closes the panel at depth and all deeper panels. Default closes every nested panel. Edits remain in the document. */
65
+ close(depth?: number): void;
66
+ /** Removes nested UI and listeners, retaining the borrowed outer editor and document. */
67
+ dispose(): void;
68
+ [Symbol.dispose](): void;
69
+ }
@@ -0,0 +1,217 @@
1
+ import { TimelineEditor as e } from "./editor.js";
2
+ //#region src/nested-editor.ts
3
+ var t = (e, t) => {
4
+ let n = 0, r = e.keys.length;
5
+ for (; n < r;) {
6
+ let i = n + r >>> 1;
7
+ e.keys[i].time <= t ? n = i + 1 : r = i;
8
+ }
9
+ return e.keys[Math.max(0, n - 1)].value;
10
+ };
11
+ function n() {
12
+ return {
13
+ type: "discrete",
14
+ validate(e, t) {
15
+ t.target(), (typeof e.property != "string" || !e.property) && t.add(`${t.path}.property`, "must name a property; pass a nonempty string");
16
+ let n = t.list(e.keys, `${t.path}.keys`);
17
+ n && !n.length && t.add(`${t.path}.keys`, "must contain a key; add an initial value");
18
+ let r;
19
+ n?.forEach((e, n) => {
20
+ let i = `${t.path}.keys[${n}]`;
21
+ t.time(e.time, `${i}.time`), typeof e.value != "boolean" && typeof e.value != "string" ? t.add(`${i}.value`, "must be a boolean or string; use a discrete value") : r !== void 0 && typeof e.value !== r ? t.add(`${i}.value`, "must have the same type as the first key; split different properties") : r = typeof e.value, e.ease !== void 0 && e.ease !== "step" && t.add(`${i}.ease`, "discrete tracks use step sampling; omit easing or use step");
22
+ }), n && t.ordered(n, `${t.path}.keys`, "time");
23
+ },
24
+ evaluate(e, n, r) {
25
+ let i = e, a = (r.extras ??= {}).discrete ??= Object.create(null);
26
+ (a[i.target] ??= Object.create(null))[i.property] = t(i, n);
27
+ },
28
+ sampleKey(e, n) {
29
+ return { value: t(e, n) };
30
+ }
31
+ };
32
+ }
33
+ function r(e) {
34
+ return e.extras?.discrete ?? {};
35
+ }
36
+ var i = class {
37
+ constructor(e, { parent: t = e.element, doubleClickMs: n = 400 } = {}) {
38
+ if (this.editor = e, this.panes = [], this.abort = new AbortController(), this.off = [], this.rememberPress = (e) => {
39
+ let t = e.target.closest(".mtl-item[data-kind=\"clip\"]"), n = t?.closest(".mtl"), r = n === this.editor.element ? this.editor : this.panes.find((e) => e.editor.element === n)?.editor;
40
+ this.pressed = t && r && e.button === 0 ? {
41
+ parent: r,
42
+ ref: {
43
+ track: t.dataset.track,
44
+ index: Number(t.dataset.index)
45
+ },
46
+ x: e.clientX,
47
+ y: e.clientY,
48
+ pointer: e.pointerId
49
+ } : void 0, this.pressed || (this.clicked = void 0);
50
+ }, this.finishPress = (e) => {
51
+ let t = this.pressed;
52
+ if (this.pressed = void 0, !t || t.pointer !== e.pointerId || Math.hypot(e.clientX - t.x, e.clientY - t.y) > 4) {
53
+ this.clicked = void 0;
54
+ return;
55
+ }
56
+ let n = this.clicked;
57
+ this.clicked = {
58
+ ...t,
59
+ at: e.timeStamp
60
+ }, !(!n || n.parent !== t.parent || n.ref.track !== t.ref.track || n.ref.index !== t.ref.index || e.timeStamp - n.at > this.doubleClickMs || Math.hypot(n.x - t.x, n.y - t.y) > 4) && (this.clicked = void 0, t.parent.element.addEventListener("pointerup", () => {
61
+ if (this.abort.signal.aborted) return;
62
+ let e = t.parent.model.document.tracks.find((e) => e.id === t.ref.track);
63
+ e?.type === "timeline" && e.clips[t.ref.index] && this.open(t.ref, t.parent);
64
+ }, {
65
+ once: !0,
66
+ signal: this.abort.signal
67
+ }));
68
+ }, !(n > 0) || !Number.isFinite(n)) throw RangeError("Double-click interval must be finite and positive; pass milliseconds");
69
+ this.doubleClickMs = n, this.active = e;
70
+ let r = e.element.ownerDocument;
71
+ this.element = r.createElement("div"), this.element.className = "margo-nested-editor";
72
+ let i = r.createElement("div");
73
+ i.style.cssText = "padding:8px;display:flex;gap:8px;align-items:center;flex-wrap:wrap", this.select = r.createElement("select"), this.select.setAttribute("aria-label", "Discrete track"), this.value = r.createElement("input"), this.value.type = "text", this.value.setAttribute("aria-label", "String key value"), this.flag = r.createElement("input"), this.flag.type = "checkbox", this.flag.setAttribute("aria-label", "Boolean key value"), this.button = r.createElement("button"), this.button.type = "button", this.button.textContent = "Key value at playhead", i.append(this.select, this.value, this.flag, this.button), this.element.append(i), t.append(this.element), this.select.addEventListener("change", () => {
74
+ this.active.selection = [], this.fields();
75
+ }, { signal: this.abort.signal }), this.button.addEventListener("click", () => {
76
+ let e = this.tracks()[this.select.selectedIndex];
77
+ e && this.keyDiscrete(e.id, typeof e.keys[0].value == "boolean" ? this.flag.checked : this.value.value);
78
+ }, { signal: this.abort.signal }), i.addEventListener("keydown", (e) => e.stopPropagation(), { signal: this.abort.signal }), e.element.addEventListener("pointerdown", this.rememberPress, {
79
+ signal: this.abort.signal,
80
+ capture: !0
81
+ }), e.element.addEventListener("pointerup", this.finishPress, {
82
+ signal: this.abort.signal,
83
+ capture: !0
84
+ }), e.element.contains(this.element) || this.element.addEventListener("pointerdown", this.rememberPress, {
85
+ signal: this.abort.signal,
86
+ capture: !0
87
+ }), e.element.contains(this.element) || this.element.addEventListener("pointerup", this.finishPress, {
88
+ signal: this.abort.signal,
89
+ capture: !0
90
+ }), this.off.push(e.on("select", () => this.activate(e)), e.on("seek", () => this.syncTimes()), e.model.on("change", () => {
91
+ this.validatePanes(), this.fields();
92
+ })), this.fields();
93
+ }
94
+ get editors() {
95
+ return this.panes.map((e) => e.editor);
96
+ }
97
+ tracks() {
98
+ return this.active.model.document.tracks.filter((e) => e.type === "discrete");
99
+ }
100
+ activate(e) {
101
+ this.active = e, this.fields();
102
+ }
103
+ fields() {
104
+ let e = this.select.value, n = this.tracks();
105
+ this.select.replaceChildren(...n.map((e) => {
106
+ let t = this.select.ownerDocument.createElement("option");
107
+ return t.value = e.id, t.textContent = `${e.target}.${e.property}`, t;
108
+ })), n.some((t) => t.id === e) && (this.select.value = e);
109
+ let r = this.active.selection[0], i = n.find((e) => e.id === r?.track) ?? n[this.select.selectedIndex];
110
+ i && (this.select.value = i.id);
111
+ let a = i ? r?.track === i.id ? i.keys[r.index]?.value : t(i, this.active.time) : void 0;
112
+ this.flag.hidden = typeof a != "boolean", this.value.hidden = typeof a != "string", this.button.disabled = !i, typeof a == "boolean" && (this.flag.checked = a), typeof a == "string" && (this.value.value = a);
113
+ }
114
+ keyDiscrete(e, t) {
115
+ let n = this.active.model.document.tracks.find((t) => t.id === e);
116
+ if (!n || n.type !== "discrete") throw RangeError("Choose a discrete track in the active timeline; open its panel first");
117
+ let r = n.keys.findIndex((e) => e.time === this.active.time), i = {
118
+ time: this.active.time,
119
+ value: t
120
+ }, a = r < 0 ? this.active.model.addItem(e, i) : this.active.model.updateItem({
121
+ track: e,
122
+ index: r
123
+ }, i);
124
+ if (!a) throw RangeError("Discrete key was refused; keep its value type consistent with the track");
125
+ return this.active.selection = [a], a;
126
+ }
127
+ open(t, n = this.active) {
128
+ let r = n.model.document.tracks.find((e) => e.id === t.track);
129
+ if (!r || r.type !== "timeline" || !r.clips[t.index]) throw RangeError("Nested editing needs a timeline clip; choose an existing clip item");
130
+ let i = n === this.editor ? -1 : this.panes.findIndex((e) => e.editor === n);
131
+ if (n !== this.editor && i < 0) throw RangeError("Parent editor is not open here; choose this tool's editor");
132
+ this.close(i + 1);
133
+ let a = r.clips[t.index], o = n.model.nested(a.timeline), s = this.element.ownerDocument, c = s.createElement("section");
134
+ c.className = "margo-nested-pane";
135
+ let l = s.createElement("div");
136
+ l.style.cssText = "padding:8px", l.textContent = `Nested timeline: ${a.timeline} `;
137
+ let u = s.createElement("button");
138
+ u.type = "button", u.textContent = "Close nested timeline", l.append(u), c.append(l), this.element.append(c);
139
+ let d = new e(o, {
140
+ parent: c,
141
+ zoom: n.zoom
142
+ }), f = {
143
+ editor: d,
144
+ parent: n,
145
+ ref: { ...t },
146
+ name: a.timeline,
147
+ element: c,
148
+ off: [],
149
+ abort: new AbortController()
150
+ };
151
+ this.panes.push(f), u.addEventListener("click", () => this.close(this.panes.indexOf(f)), { signal: f.abort.signal });
152
+ for (let e of [
153
+ "pointerdown",
154
+ "pointermove",
155
+ "pointerup",
156
+ "pointercancel",
157
+ "keydown",
158
+ "wheel"
159
+ ]) d.element.addEventListener(e, (e) => e.stopPropagation(), { signal: f.abort.signal });
160
+ return d.element.addEventListener("pointerdown", () => this.activate(d), { signal: f.abort.signal }), f.off.push(d.on("select", () => this.activate(d)), d.on("seek", (e) => {
161
+ let t = this.mapping(f), n = t.origin + e / t.rate;
162
+ this.editor.seek(Math.max(t.start, Math.min(t.end, n)));
163
+ })), this.active = d, this.syncTimes(), this.fields(), d;
164
+ }
165
+ clip(e) {
166
+ let t = e.parent.model.document.tracks.find((t) => t.id === e.ref.track);
167
+ return t?.type === "timeline" ? t.clips[e.ref.index] : void 0;
168
+ }
169
+ mapping(e) {
170
+ let t = this.clip(e), n = this.panes.find((t) => t.editor === e.parent), r = n ? this.mapping(n) : {
171
+ origin: 0,
172
+ rate: 1,
173
+ start: 0,
174
+ end: this.editor.model.duration
175
+ }, i = r.origin + t.start / r.rate, a = r.rate * (t.speed ?? 1);
176
+ return {
177
+ origin: i - (t.offset ?? 0) / a,
178
+ rate: a,
179
+ start: Math.max(r.start, i),
180
+ end: Math.min(r.end, i + t.duration / r.rate)
181
+ };
182
+ }
183
+ syncTimes() {
184
+ for (let e of this.panes) {
185
+ let t = this.mapping(e);
186
+ e.editor.time = (this.editor.time - t.origin) * t.rate;
187
+ }
188
+ }
189
+ validatePanes() {
190
+ for (let e = 0; e < this.panes.length; e++) {
191
+ let t = this.panes[e], n = this.clip(t);
192
+ if (!n || n.timeline !== t.name || !this.editor.model.document.timelines?.[t.name]) {
193
+ this.close(e);
194
+ return;
195
+ }
196
+ }
197
+ this.syncTimes();
198
+ }
199
+ close(e = 0) {
200
+ for (let t of this.panes.splice(Math.max(0, e)).reverse()) {
201
+ t.abort.abort();
202
+ for (let e of t.off) e();
203
+ t.editor.dispose(), t.element.remove();
204
+ }
205
+ this.active = this.panes.at(-1)?.editor ?? this.editor, this.fields();
206
+ }
207
+ dispose() {
208
+ this.close(), this.abort.abort();
209
+ for (let e of this.off) e();
210
+ this.off.length = 0, this.element.remove();
211
+ }
212
+ [Symbol.dispose]() {
213
+ this.dispose();
214
+ }
215
+ };
216
+ //#endregion
217
+ export { i as NestedTimelineEditor, r as discreteOf, n as discreteTrack };
@@ -0,0 +1,143 @@
1
+ import { t as e } from "./cutscene-WWP9-stS.js";
2
+ import { MargoError as t } from "@margoengine/math/errors";
3
+ //#region src/player.ts
4
+ var n = 100, r = class {
5
+ constructor(t, n = {}) {
6
+ if (this.running = !1, this.disposed = !1, this.dispatching = !1, this.epoch = 0, this.listeners = /* @__PURE__ */ new Map(), this.waiters = [], this.streams = /* @__PURE__ */ new Set(), this.cutscene = t instanceof e ? t : new e(t, { tracks: n.tracks }), this.speed = n.speed ?? 1, !Number.isFinite(this.speed)) throw RangeError("Cutscene speed must be a finite number; use a negative one to reverse");
7
+ this.loop = n.loop === !0, this.current = this.clamp(n.time ?? 0);
8
+ }
9
+ get time() {
10
+ return this.current;
11
+ }
12
+ get playing() {
13
+ return this.running;
14
+ }
15
+ get duration() {
16
+ return this.cutscene.duration;
17
+ }
18
+ get state() {
19
+ return this.cutscene.evaluate(this.current);
20
+ }
21
+ play(e = {}) {
22
+ this.check();
23
+ let t = e.signal;
24
+ return t?.throwIfAborted(), this.loop || (this.speed > 0 && this.current >= this.duration ? this.current = 0 : this.speed < 0 && this.current <= 0 && (this.current = this.duration)), this.running = !0, new Promise((e, n) => {
25
+ let r = () => {
26
+ this.waiters = this.waiters.filter((e) => e.reject !== n), this.pause(), n(t.reason);
27
+ };
28
+ t?.addEventListener("abort", r, { once: !0 }), this.waiters.push({
29
+ resolve: e,
30
+ reject: n,
31
+ cleanup: () => t?.removeEventListener("abort", r)
32
+ });
33
+ });
34
+ }
35
+ pause() {
36
+ this.running && (this.running = !1, this.settle(!1));
37
+ }
38
+ stop() {
39
+ this.pause(), this.seek(this.speed < 0 ? this.duration : 0);
40
+ }
41
+ reverse() {
42
+ return this.speed = -this.speed, this;
43
+ }
44
+ seek(e) {
45
+ return this.check(), this.current = this.clamp(e), this.epoch++, this;
46
+ }
47
+ skip(e = this.speed < 0 ? 0 : this.duration) {
48
+ this.check();
49
+ let t = this.clamp(e), n = this.current;
50
+ this.current = t;
51
+ let r = ++this.epoch;
52
+ return this.fire(this.cutscene.eventsBetween(n, t), r), r === this.epoch && this.running && !this.loop && (t === this.duration ? this.speed > 0 : t === 0 && this.speed < 0) && this.finish(), this;
53
+ }
54
+ fastForward(e) {
55
+ if (!Number.isFinite(e) || e < 0) throw RangeError("fastForward needs a finite number of seconds, 0 or more");
56
+ return this.skip(this.current + Math.sign(this.speed || 1) * e);
57
+ }
58
+ update(e) {
59
+ if (this.check(), !(e >= 0) || !Number.isFinite(e)) throw RangeError("Cutscene update delta must be a finite number of seconds, 0 or more");
60
+ if (this.dispatching) throw new t("state", "CutscenePlayer.update called from a listener; update once per frame from your game loop");
61
+ if (!this.running || e === 0 || this.speed === 0) return this;
62
+ let r = this.duration, i = ++this.epoch, a = e * this.speed, o = 0;
63
+ for (; a !== 0 && i === this.epoch;) {
64
+ let e = this.current, t = e + a;
65
+ if (t > r || t < 0) {
66
+ let s = t > r ? r : 0;
67
+ if (this.current = s, this.fire(this.cutscene.eventsBetween(e, s), i), i !== this.epoch) return this;
68
+ if (!this.loop) return this.finish(), this;
69
+ if (++o > n) throw RangeError("Cutscene update crossed more than 100 loops; pass a smaller delta");
70
+ a = t - s, this.current = s === r ? 0 : r;
71
+ } else this.current = t, this.fire(this.cutscene.eventsBetween(e, t), i), a = 0;
72
+ }
73
+ return i === this.epoch && !this.loop && (this.current === r ? this.speed > 0 : this.current === 0 && this.speed < 0) && this.finish(), this;
74
+ }
75
+ on(e, t) {
76
+ if (typeof t != "function") throw TypeError("Cutscene listener must be a function");
77
+ let n = this.listeners.get(e);
78
+ n || this.listeners.set(e, n = /* @__PURE__ */ new Set());
79
+ let r = t;
80
+ return n.add(r), () => void n.delete(r);
81
+ }
82
+ async *events(e = {}) {
83
+ this.check();
84
+ let t = [], n = null, r = (e) => {
85
+ t.push(e), n?.();
86
+ }, i = e.signal, a = () => r(null);
87
+ i?.addEventListener("abort", a, { once: !0 }), this.streams.add(r);
88
+ try {
89
+ for (; !i?.aborted;) {
90
+ t.length || await new Promise((e) => n = e), n = null;
91
+ let e = t.shift();
92
+ if (e !== void 0) {
93
+ if (e === null) return;
94
+ yield e;
95
+ }
96
+ }
97
+ } finally {
98
+ this.streams.delete(r), i?.removeEventListener("abort", a);
99
+ }
100
+ }
101
+ dispose() {
102
+ if (!this.disposed) {
103
+ this.pause(), this.disposed = !0;
104
+ for (let e of this.streams) e(null);
105
+ this.listeners.clear();
106
+ }
107
+ }
108
+ [Symbol.dispose]() {
109
+ this.dispose();
110
+ }
111
+ clamp(e) {
112
+ if (typeof e != "number" || !Number.isFinite(e)) throw RangeError("Cutscene time must be a finite number of seconds");
113
+ return Math.min(this.duration, Math.max(0, e));
114
+ }
115
+ check() {
116
+ if (this.disposed) throw new t("disposed", "CutscenePlayer is disposed; create a new CutscenePlayer");
117
+ }
118
+ fire(e, t) {
119
+ let n = this.dispatching;
120
+ this.dispatching = !0;
121
+ try {
122
+ for (let n of e) {
123
+ for (let e of this.streams) e(n);
124
+ for (let e of [n.kind, "*"]) for (let r of [...this.listeners.get(e) ?? []]) if (r(n), t !== this.epoch || this.disposed) return;
125
+ }
126
+ } finally {
127
+ this.dispatching = n;
128
+ }
129
+ }
130
+ finish() {
131
+ this.running = !1;
132
+ for (let e of [...this.listeners.get("finish") ?? []]) e(null);
133
+ for (let e of this.streams) e(null);
134
+ this.settle(!0);
135
+ }
136
+ settle(e) {
137
+ let t = this.waiters;
138
+ this.waiters = [];
139
+ for (let n of t) n.cleanup(), n.resolve(e);
140
+ }
141
+ };
142
+ //#endregion
143
+ export { r as t };
@@ -0,0 +1,94 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import { Cutscene, type CutsceneEvent, type CutsceneState, type CutsceneTrackType } from './cutscene.js';
3
+ import type { CutsceneDocument } from './document.js';
4
+ /** Options of {@link CutscenePlayer}. Every field has a default. */
5
+ export interface CutscenePlayerOptions {
6
+ /** Playback rate; negative plays backwards (default 1). */
7
+ speed?: number;
8
+ /** Wrap at the ends instead of finishing (default false). */
9
+ loop?: boolean;
10
+ /** Start time, seconds (default 0). */
11
+ time?: number;
12
+ /** Custom track types the document may use (default none). Ignored when you pass a built {@link Cutscene}. */
13
+ tracks?: readonly CutsceneTrackType[];
14
+ }
15
+ /** What {@link CutscenePlayer.on} listens to: an instant kind, `'finish'`, or `'*'` for every instant. */
16
+ export type CutscenePlayerEvent = CutsceneEvent['kind'] | 'finish' | '*';
17
+ /**
18
+ * Plays a {@link Cutscene}: `play()`, `pause()`, `reverse()`, `speed`, `seek(t)` (scrubbing, fires nothing),
19
+ * `skip(to)` and `fastForward(seconds)` (fire every instant on the way, in order), and `update(delta)` once per
20
+ * frame. Listen with `on(kind, listener)` or iterate `events()`. `using` works.
21
+ */
22
+ export declare class CutscenePlayer {
23
+ /** The compiled cutscene. */
24
+ readonly cutscene: Cutscene;
25
+ /** Playback rate; negative plays backwards. */
26
+ speed: number;
27
+ /** Wrap at the ends instead of finishing. */
28
+ loop: boolean;
29
+ private current;
30
+ private running;
31
+ private disposed;
32
+ private dispatching;
33
+ private epoch;
34
+ private readonly listeners;
35
+ private waiters;
36
+ private streams;
37
+ /** @throws TypeError for an invalid document; RangeError for a bad speed or time. */
38
+ constructor(cutscene: Cutscene | CutsceneDocument | string | unknown, options?: CutscenePlayerOptions);
39
+ /** Current time, seconds, in [0, duration]. */
40
+ get time(): number;
41
+ /** True between `play()` and a pause, a stop or the end. */
42
+ get playing(): boolean;
43
+ /** Length of the cutscene, seconds. */
44
+ get duration(): number;
45
+ /** The state at the current time: `cutscene.evaluate(player.time)`. */
46
+ get state(): CutsceneState;
47
+ /**
48
+ * Start or resume playing. At the end (or the start, when reversed) it starts over. Resolves `true` when it
49
+ * finishes, `false` when paused or stopped first; rejects with the signal's reason (and pauses) on abort.
50
+ */
51
+ play(options?: {
52
+ signal?: AbortSignal;
53
+ }): Promise<boolean>;
54
+ /** Stop advancing; `play()` resumes from here. */
55
+ pause(): void;
56
+ /** Pause and go back to the start (the end when reversed), firing nothing. */
57
+ stop(): void;
58
+ /** Flip the direction of play. */
59
+ reverse(): this;
60
+ /** Jump to `time` (clamped) without firing anything: scrubbing. The state is exactly that of playing to it. */
61
+ seek(time: number): this;
62
+ /**
63
+ * Jump to `time` (default the end, or the start when reversed), firing every instant on the way in order, as if it
64
+ * had played there in one step. Use it for "skip cutscene" so the game still sees every event.
65
+ */
66
+ skip(time?: number): this;
67
+ /** Skip `seconds` ahead in the direction of play, firing what it passes. */
68
+ fastForward(seconds: number): this;
69
+ /**
70
+ * Advance by `delta` seconds of real time times `speed`, firing the instants passed in order; call once per frame.
71
+ * Does nothing while paused.
72
+ * @throws RangeError for a negative or non-finite delta or one that crosses more than 100 loops; MargoError
73
+ * `'state'` when called from a listener, `'disposed'` after dispose.
74
+ */
75
+ update(delta: number): this;
76
+ /** Call `listener` for each instant of `kind` (`'*'`: every kind) as it fires; returns a function that removes it. */
77
+ on(kind: CutscenePlayerEvent, listener: (event: CutsceneEvent) => void): () => void;
78
+ /**
79
+ * The instants as they fire, as an async iterator: `for await (const event of player.events({signal}))`. Ends when
80
+ * the player finishes or is disposed, or when the signal aborts.
81
+ */
82
+ events(options?: {
83
+ signal?: AbortSignal;
84
+ }): AsyncGenerator<CutsceneEvent, void, undefined>;
85
+ /** Stop playing, settle pending `play()` promises with false and end `events()` iterators; further calls throw. */
86
+ dispose(): void;
87
+ /** Same as {@link CutscenePlayer.dispose}, for `using`. */
88
+ [Symbol.dispose](): void;
89
+ private clamp;
90
+ private check;
91
+ private fire;
92
+ private finish;
93
+ private settle;
94
+ }
@@ -0,0 +1,143 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import { type InputClip, type RecordSource } from '@margoengine/input/replay';
3
+ import type { CutsceneDocument, Marker, Track } from './document.js';
4
+ /** A vector as a `Mesh` holds it (`x`, `y`, `z`) or as an array. */
5
+ type VectorLike = ArrayLike<number> | {
6
+ readonly x: number;
7
+ readonly y: number;
8
+ readonly z: number;
9
+ };
10
+ /** What a transform source gives. A 3-value `rotation` is Euler radians, as a `Mesh`'s; 4 values are a quaternion. */
11
+ export interface TransformSample {
12
+ position?: VectorLike;
13
+ rotation?: VectorLike;
14
+ scale?: VectorLike;
15
+ }
16
+ /** What a camera source gives; `core`'s `Camera` fits. */
17
+ export interface CameraSample {
18
+ position: VectorLike;
19
+ target: VectorLike;
20
+ /** Degrees (default 60). */
21
+ fov?: number;
22
+ /** Radians (default 0). */
23
+ roll?: number;
24
+ }
25
+ /** How far the tracks may stray from the samples. A value of 0 keeps every change. */
26
+ export interface TakeTolerance {
27
+ /** World units, for positions and camera positions and targets. Default 0.001. */
28
+ position?: number;
29
+ /** Radians. Default 0.001. */
30
+ rotation?: number;
31
+ /** Default 0.001. */
32
+ scale?: number;
33
+ /** For properties and fields of view, on each component. Default 0.001. */
34
+ value?: number;
35
+ }
36
+ /** Options of {@link TakeRecorder}. */
37
+ export interface TakeRecorderOptions {
38
+ /** How far the tracks may stray from the samples. */
39
+ tolerance?: TakeTolerance;
40
+ /** Clock in milliseconds, for `capture()` with no time. Default `performance.now`. */
41
+ now?: () => number;
42
+ }
43
+ /** A finished take: tracks, and what else was marked while recording. */
44
+ export interface Take {
45
+ /** Seconds from the first capture to the last. */
46
+ duration: number;
47
+ tracks: Track[];
48
+ markers: Marker[];
49
+ /** Samples each track was thinned from, and the keys left, by track id. */
50
+ kept: Record<string, {
51
+ samples: number;
52
+ keys: number;
53
+ }>;
54
+ }
55
+ /** Options of {@link inputTracks}. */
56
+ export interface InputTrackOptions {
57
+ /** Seconds to add to every time. Default 0. */
58
+ at?: number;
59
+ /** The `target` of the property tracks, and the start of the track ids. Default `'input'`. */
60
+ target?: string;
61
+ }
62
+ /** Options of {@link appendTake}. */
63
+ export interface AppendTakeOptions {
64
+ /** Where the take starts in the document, seconds. Default the document's end. */
65
+ at?: number;
66
+ /** Put in front of the track ids, so a second take of one object can sit beside the first. Default none. */
67
+ prefix?: string;
68
+ }
69
+ /**
70
+ * Records live gameplay into cutscene tracks. Say what to record, call `capture()` once per tick, and `stop()` gives a
71
+ * {@link Take}: put it in a document with {@link takeDocument} or {@link appendTake}.
72
+ *
73
+ * ```ts
74
+ * const recorder = new TakeRecorder();
75
+ * recorder.transform('hero', hero); // a Mesh, or a function giving { position, rotation, scale }
76
+ * recorder.capture(); // once per tick
77
+ * const take = recorder.stop();
78
+ * ```
79
+ */
80
+ export declare class TakeRecorder {
81
+ private readonly tolerance;
82
+ private readonly now;
83
+ private readonly transforms;
84
+ private readonly properties;
85
+ private cameraRead;
86
+ private readonly cameraData;
87
+ private readonly cameraFov;
88
+ private readonly cameraRoll;
89
+ private readonly events;
90
+ private readonly marks;
91
+ private inputs;
92
+ private start;
93
+ private clock;
94
+ private ticks;
95
+ private stopped;
96
+ constructor(_arg0?: TakeRecorderOptions);
97
+ /** Seconds since the first capture. */
98
+ get time(): number;
99
+ /** Ticks captured so far. */
100
+ get frames(): number;
101
+ /** Record an object as `name`: a `Mesh`, anything with `position`, `rotation` or `scale`, or a function giving them. */
102
+ transform(name: string, source: TransformSample | (() => TransformSample)): this;
103
+ /** Record the camera: a `Camera`, or a function giving `position`, `target`, `fov` and `roll`. One per take. */
104
+ camera(source: CameraSample | (() => CameraSample)): this;
105
+ /** Record a number or a numeric array of `target`, as a property track. */
106
+ property(target: string, property: string, read: () => number | readonly number[]): this;
107
+ /** Record every binding of an `Input` from the next capture on; call `capture()` after `input.update()`. */
108
+ input(input: RecordSource, _arg1?: {
109
+ target?: string;
110
+ }): this;
111
+ /** Note an event at the current time, for an event track. */
112
+ event(name: string, data?: unknown): this;
113
+ /** Note a marker at the current time. */
114
+ marker(name: string): this;
115
+ /**
116
+ * Sample everything: once per tick. `time` is seconds on your own clock, for a fixed-step game; by default the
117
+ * `now` clock runs. The first capture is time 0 of the take.
118
+ * @throws RangeError for a time before the last capture.
119
+ */
120
+ capture(time?: number): this;
121
+ /**
122
+ * End the take and give its tracks. The recorder is spent.
123
+ * @throws MargoError `'state'` when nothing was captured or when it has already stopped.
124
+ */
125
+ stop(): Take;
126
+ private open;
127
+ private transformTrack;
128
+ private cameraTrack;
129
+ }
130
+ /**
131
+ * An input recording as tracks: one stepped property track per binding (target `input`, property the action, and
132
+ * `#1` and so on for its later bindings), so `state.properties.input.move` is what the binding gave at any time, and
133
+ * one event track with `<action>` when a binding leaves 0 and `<action>:up` when it comes back.
134
+ */
135
+ export declare function inputTracks(clip: InputClip, _arg2?: InputTrackOptions): Track[];
136
+ /** A take as a whole cutscene document. */
137
+ export declare function takeDocument(take: Take): CutsceneDocument;
138
+ /**
139
+ * A new document with the take added at a time, longer if it needs to be. The document you pass is left alone.
140
+ * @throws RangeError when a track id is taken: pass `prefix`.
141
+ */
142
+ export declare function appendTake(document: CutsceneDocument, take: Take, _arg3?: AppendTakeOptions): CutsceneDocument;
143
+ export {};