@margoengine/cinematic 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,227 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel, Vec3 } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin } from '@margoengine/core/extension';
4
+ /** Where a camera stands and what it sees. Stages edit one in place. All distances are world units. */
5
+ export interface CameraPose {
6
+ /** Camera position. */
7
+ readonly position: Float64Array;
8
+ /** The point looked at. */
9
+ readonly target: Float64Array;
10
+ /** World up: the direction the top of the screen leans to. It need not be unit length. Default [0, 1, 0]. */
11
+ readonly up: Float64Array;
12
+ /** Vertical field of view in degrees, above 0 and below 180. Default 60. */
13
+ fov: number;
14
+ /** Turn about the view direction in radians. Default 0. */
15
+ roll: number;
16
+ /** Distance to the plane of focus; 0 means no stage has set one. Default 0. */
17
+ focusDistance: number;
18
+ /** Full orthographic world height; undefined selects perspective. Default undefined. */
19
+ orthographicHeight?: number;
20
+ }
21
+ /** What a stage knows about the view it works for. */
22
+ export interface StageContext {
23
+ /** Width / height of the view. */
24
+ readonly aspect: number;
25
+ }
26
+ /**
27
+ * One step of a camera's work: a function, or an object with `update` and an optional `reset`. A stage changes `pose`
28
+ * in place and keeps what it needs between frames; `reset` forgets that, as after a teleport.
29
+ */
30
+ export type CameraStage = ((pose: CameraPose, delta: number, context: StageContext) => void) | {
31
+ update(pose: CameraPose, delta: number, context: StageContext): void;
32
+ reset?(): void;
33
+ };
34
+ /** Settings of a {@link VirtualCamera}. */
35
+ export interface VirtualCameraOptions {
36
+ /** Names the camera in blend rules and events. Names in one brain differ. Default none. */
37
+ name?: string;
38
+ /** The highest priority among enabled cameras goes on screen. Any finite number. Default 0. */
39
+ priority?: number;
40
+ /** Where the camera stands before its stages run. Default [0, 2, 5]. */
41
+ position?: Vec3;
42
+ /** What it looks at before its stages run. Default [0, 0, 0]. */
43
+ target?: Vec3;
44
+ /** World up. Default [0, 1, 0]. */
45
+ up?: Vec3;
46
+ /** Vertical field of view in degrees. Default 60. */
47
+ fov?: number;
48
+ /** Full orthographic world height. Use cinematic/ortho output to drive CameraProjection. Default undefined. */
49
+ orthographicHeight?: number;
50
+ /** Radians. Default 0. */
51
+ roll?: number;
52
+ /** Run in order every update. Default none. */
53
+ stages?: readonly CameraStage[];
54
+ }
55
+ /** How one camera takes over from another. */
56
+ export interface CameraBlend {
57
+ /** Seconds, 0 or more; 0 is a cut. */
58
+ duration: number;
59
+ /** Shape of the blend: takes 0..1, gives 0..1, values outside are clamped. Any tween easing fits. Default smoothstep. */
60
+ ease?: (u: number) => number;
61
+ /**
62
+ * `'direct'` (default) moves the camera straight across and turns the view. `'orbit'` swings it around the point
63
+ * looked at, for two cameras on one subject, so the move does not cut through the subject.
64
+ */
65
+ style?: 'direct' | 'orbit';
66
+ }
67
+ /** A {@link CameraBlend} for one pair of cameras. `'*'` matches any camera. */
68
+ export interface CameraBlendRule extends CameraBlend {
69
+ from: string;
70
+ to: string;
71
+ }
72
+ /** Settings of a {@link CameraBrain}. */
73
+ export interface CameraBrainOptions {
74
+ /** Used when no rule matches. Default a 1 second smoothstep, direct. */
75
+ blend?: CameraBlend;
76
+ /** The first rule for the exact pair wins, then `from` to `'*'`, then `'*'` to `to`, then `'*'` to `'*'`. Default none. */
77
+ rules?: readonly CameraBlendRule[];
78
+ /** Plugin name, so several brains can share an engine (one per view). Default 'cinematic-brain'. */
79
+ name?: string;
80
+ /** The camera written. Default `engine.camera`. */
81
+ camera?: {
82
+ position: Vec3;
83
+ target: Vec3;
84
+ up: Vec3;
85
+ fov: number;
86
+ };
87
+ /** Width / height of the view. Default the canvas's when attached, otherwise 16 / 9. */
88
+ aspect?: number;
89
+ }
90
+ /** What `change` and `blended` give to a listener. */
91
+ export interface CameraBrainEvent {
92
+ /** The camera on screen before the change; null for the first camera. */
93
+ from: VirtualCamera | null;
94
+ /** The camera taking over. */
95
+ to: VirtualCamera;
96
+ /** Seconds the blend takes; 0 for a cut. */
97
+ duration: number;
98
+ }
99
+ /** A pose with the defaults of {@link VirtualCameraOptions}, or the values given. */
100
+ export declare function createPose({ position, target, up, fov, roll, orthographicHeight, }?: Pick<VirtualCameraOptions, 'position' | 'target' | 'up' | 'fov' | 'roll' | 'orthographicHeight'>): CameraPose;
101
+ /** Copies every field of `from` into `to`. */
102
+ export declare function copyPose(to: CameraPose, from: CameraPose): CameraPose;
103
+ /**
104
+ * A camera that is not the real one: a base pose, a priority and a list of stages. Use it alone with `update`, or give
105
+ * it to a {@link CameraBrain}.
106
+ */
107
+ export declare class VirtualCamera {
108
+ readonly name?: string;
109
+ /** The highest priority among enabled cameras goes on screen; change it at any time. */
110
+ priority: number;
111
+ /** Where the camera starts each update, before its stages. Edit it in place. */
112
+ readonly base: CameraPose;
113
+ /** The result of the last update. */
114
+ readonly pose: CameraPose;
115
+ /** Run in order every update. */
116
+ readonly stages: CameraStage[];
117
+ private active;
118
+ private stale;
119
+ private readonly context;
120
+ /** @throws RangeError for a value outside what {@link VirtualCameraOptions} allows. */
121
+ constructor(options?: VirtualCameraOptions);
122
+ /** A disabled camera never goes on screen and stops updating; when enabled again its stages start fresh. */
123
+ get enabled(): boolean;
124
+ set enabled(value: boolean);
125
+ /** Tells every stage to forget what it kept, as after a teleport. */
126
+ reset(): void;
127
+ /**
128
+ * Runs the stages from the base pose into `pose`. A brain calls this each frame.
129
+ * @param delta Seconds, 0 or more.
130
+ * @param aspect Width / height of the view. Default 16 / 9.
131
+ * @throws RangeError for a bad delta or aspect, or a stage's own error.
132
+ */
133
+ update(delta: number, aspect?: number): CameraPose;
134
+ }
135
+ /** Turns a `Cinematic` rig into a stage: the rig runs unattached and places the camera. Give it no engine of its own. */
136
+ export declare const rigStage: (rig: {
137
+ update(delta: number): void;
138
+ readonly cameraPosition: ArrayLike<number>;
139
+ readonly cameraTarget: ArrayLike<number>;
140
+ }) => CameraStage;
141
+ type BrainListener = (event: CameraBrainEvent) => void;
142
+ /**
143
+ * Shows one of many {@link VirtualCamera}s: the enabled camera with the highest priority. On a tie the camera on screen
144
+ * stays, otherwise the one added last wins. A change blends by the rules, and every camera in a blend keeps moving. A
145
+ * switch in the middle of a blend starts from what is on screen, so the picture never jumps.
146
+ */
147
+ export declare class CameraBrain implements EnginePlugin {
148
+ readonly options: CameraBrainOptions;
149
+ readonly name: string;
150
+ /** The result of the last update. */
151
+ readonly pose: CameraPose;
152
+ /** Run in order on the blended pose, so they hold whichever cameras are on screen. */
153
+ readonly stages: CameraStage[];
154
+ private readonly cameras;
155
+ private readonly listeners;
156
+ /** Events of the step running now: the clock step queues them, a live update sends them after it. */
157
+ private readonly events;
158
+ private layers;
159
+ private blendFrom;
160
+ private engine?;
161
+ private readonly screenUp;
162
+ private readonly outPosition;
163
+ private readonly outTarget;
164
+ private readonly outUp;
165
+ private readonly context;
166
+ /** @throws RangeError for a bad blend, rule, or aspect. */
167
+ constructor(options?: CameraBrainOptions);
168
+ /** Create a brain and add it to `engine`; it then updates before every frame and owns the camera. */
169
+ static attach(engine: EngineKernel, options?: CameraBrainOptions): CameraBrain;
170
+ /** The camera on screen, or the one blending in. Null before the first update or with no enabled camera yet. */
171
+ get live(): VirtualCamera | null;
172
+ /** True while a blend runs. */
173
+ get blending(): boolean;
174
+ /** Cameras in the order added. */
175
+ get list(): readonly VirtualCamera[];
176
+ /**
177
+ * Adds a camera, or makes one from `options`, and returns it.
178
+ * @throws RangeError when the name is taken or the camera was added before.
179
+ */
180
+ add(camera?: VirtualCamera | VirtualCameraOptions): VirtualCamera;
181
+ /** Takes a camera out. On screen it holds its last pose until the next camera has blended in. */
182
+ remove(camera: VirtualCamera): void;
183
+ /**
184
+ * Listens for `'change'`, when a camera starts taking over, or `'blended'`, when one has finished. Returns a function
185
+ * that stops listening.
186
+ * @throws RangeError for another event name.
187
+ */
188
+ on(kind: 'change' | 'blended', listener: BrainListener): () => void;
189
+ /** Ends any blend now, so the live camera fills the screen on the next update. */
190
+ cut(): void;
191
+ /** The blend from one camera to another: the rules in order, then the `blend` option. */
192
+ blendFor(from: VirtualCamera | null, to: VirtualCamera): CameraBlend;
193
+ private choose;
194
+ private emit;
195
+ private get aspect();
196
+ /** Moves the running blends on by `delta` and drops every layer a finished one above it has covered. */
197
+ private advance;
198
+ /**
199
+ * Picks the camera, steps the blend by `delta` seconds and writes the real camera when attached. Called every frame
200
+ * when attached. With no enabled camera it writes nothing.
201
+ * @throws RangeError for a bad delta, a priority that is not finite, a blend `ease` that gives no number, or a stage's error.
202
+ */
203
+ update(delta: number): CameraPose;
204
+ /**
205
+ * The film clock: the same step as {@link CameraBrain.update} (cameras, their stages, the blend, the brain's stages
206
+ * and the camera write) without calling a `change` or `blended` listener, as `@margoengine/cutscene/seek` steps every
207
+ * clock. A seek of n steps then leaves the brain where n live updates leave it, so a film rendered scene by scene
208
+ * keeps its blends, camera moves and focus pulls across a cut (KB-FILM-BRAIN1). Events of the replayed steps are
209
+ * not sent later.
210
+ * @throws RangeError as {@link CameraBrain.update} does.
211
+ */
212
+ advanceTime(delta: number): void;
213
+ private step;
214
+ /** Writes the pose, with a screen up that is never parallel to the view (core refuses that). */
215
+ private write;
216
+ /**
217
+ * Plugin hook: bind the brain to `engine`.
218
+ * @throws MargoError `'attached'` when already attached.
219
+ */
220
+ setup(engine: Engine): void;
221
+ /** Plugin hook: runs {@link CameraBrain.update} with the frame delta in seconds. */
222
+ onPreUpdate(delta: number): void;
223
+ /** Detach from the engine and forget what is on screen; the brain keeps its cameras and can be attached again. */
224
+ dispose(): void;
225
+ [Symbol.dispose]: () => void;
226
+ }
227
+ export {};
package/dist/brain.js ADDED
@@ -0,0 +1,272 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const t=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { MargoError as e } from "@margoengine/math/errors";
5
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
6
+ //#region src/brain.ts
7
+ var n = (e, t) => {
8
+ if (e.length !== 3 || !(Number.isFinite(e[0]) && Number.isFinite(e[1]) && Number.isFinite(e[2]))) throw RangeError(`Invalid ${t}; pass three finite numbers`);
9
+ }, r = (e) => {
10
+ if (!(e > 0 && e < 180)) throw RangeError("Invalid camera fov; pass degrees above 0 and below 180");
11
+ }, i = (e) => {
12
+ if (!Number.isFinite(e) || e < 0) throw RangeError("Invalid camera delta; pass a finite delta of 0 or more seconds");
13
+ }, a = (e) => {
14
+ if (!(e > 0 && e < Infinity)) throw RangeError("Invalid camera aspect; pass a width / height above 0");
15
+ }, o = (e) => e * e * (3 - 2 * e), s = (e) => {
16
+ if (!Number.isFinite(e.duration) || e.duration < 0 || e.ease !== void 0 && typeof e.ease != "function" || e.style !== void 0 && e.style !== "direct" && e.style !== "orbit") throw RangeError("Invalid camera blend; pass a duration of 0 or more, an ease function and style 'direct' or 'orbit'");
17
+ };
18
+ function c({ position: e = [
19
+ 0,
20
+ 2,
21
+ 5
22
+ ], target: t = [
23
+ 0,
24
+ 0,
25
+ 0
26
+ ], up: i = [
27
+ 0,
28
+ 1,
29
+ 0
30
+ ], fov: a = 60, roll: o = 0, orthographicHeight: s } = {}) {
31
+ if (n(e, "camera position"), n(t, "camera target"), n(i, "camera up"), r(a), s !== void 0 && !(s > 0 && Number.isFinite(s))) throw RangeError("Invalid orthographic height; pass a finite world height above 0");
32
+ if (!Number.isFinite(o)) throw RangeError("Invalid camera roll; pass finite radians");
33
+ return {
34
+ position: new Float64Array(e),
35
+ target: new Float64Array(t),
36
+ up: new Float64Array(i),
37
+ fov: a,
38
+ roll: o,
39
+ focusDistance: 0,
40
+ orthographicHeight: s
41
+ };
42
+ }
43
+ function l(e, t) {
44
+ return e.position.set(t.position), e.target.set(t.target), e.up.set(t.up), e.fov = t.fov, e.roll = t.roll, e.focusDistance = t.focusDistance, e.orthographicHeight = t.orthographicHeight, e;
45
+ }
46
+ var u = (e, t, n, r) => {
47
+ typeof e == "function" ? e(t, n, r) : e.update(t, n, r);
48
+ }, d = class {
49
+ constructor(e = {}) {
50
+ this.active = !0, this.stale = !1, this.context = { aspect: 16 / 9 };
51
+ let { name: t, priority: n = 0, stages: r = [] } = e;
52
+ if (!Number.isFinite(n)) throw RangeError("Invalid camera priority; pass a finite number");
53
+ this.name = t, this.priority = n, this.base = c(e), this.pose = l(c(), this.base), this.stages = [...r];
54
+ }
55
+ get enabled() {
56
+ return this.active;
57
+ }
58
+ set enabled(e) {
59
+ e && !this.active && (this.stale = !0), this.active = e;
60
+ }
61
+ reset() {
62
+ this.stale = !1;
63
+ for (let e of this.stages) typeof e != "function" && e.reset?.();
64
+ }
65
+ update(e, t = 16 / 9) {
66
+ i(e), a(t), this.stale && this.reset(), this.context.aspect = t, l(this.pose, this.base);
67
+ for (let t of this.stages) u(t, this.pose, e, this.context);
68
+ return this.pose;
69
+ }
70
+ }, f = (e) => (t, n) => {
71
+ e.update(n), t.position.set(e.cameraPosition), t.target.set(e.cameraTarget);
72
+ };
73
+ function p(e, t, n, r, i) {
74
+ let a = Math.hypot(t[0], t[1], t[2]), o = Math.hypot(n[0], n[1], n[2]);
75
+ if (!(a > 0 && o > 0)) {
76
+ for (let i = 0; i < 3; i++) e[i] = t[i] + (n[i] - t[i]) * r;
77
+ return;
78
+ }
79
+ let s = t[0] / a, c = t[1] / a, l = t[2] / a, u = n[0] / o, d = n[1] / o, f = n[2] / o, p = s * u + c * d + l * f, m = a + (o - a) * r, h = u - s * p, g = d - c * p, _ = f - l * p, v = Math.hypot(h, g, _);
80
+ if (v < 1e-9) {
81
+ if (p > 0) {
82
+ e[0] = s * m, e[1] = c * m, e[2] = l * m;
83
+ return;
84
+ }
85
+ if (h = c * i[2] - l * i[1], g = l * i[0] - s * i[2], _ = s * i[1] - c * i[0], Math.hypot(h, g, _) < 1e-9) {
86
+ let e = Math.abs(s) < .9;
87
+ h = e ? 0 : -l, g = e ? l : 0, _ = e ? -c : s;
88
+ }
89
+ v = 0;
90
+ }
91
+ let y = Math.hypot(h, g, _), b = Math.atan2(v, p) * r, x = Math.cos(b) * m, S = Math.sin(b) * m / y;
92
+ e[0] = s * x + h * S, e[1] = c * x + g * S, e[2] = l * x + _ * S;
93
+ }
94
+ var m = /* @__PURE__ */ new Float64Array(3), h = /* @__PURE__ */ new Float64Array(3);
95
+ function g(e, t, n, r) {
96
+ if (n <= 0) return;
97
+ if (n >= 1) {
98
+ l(e, t);
99
+ return;
100
+ }
101
+ let i = r === "orbit";
102
+ for (let r = 0; r < 3; r++) m[r] = i ? e.position[r] - e.target[r] : e.target[r] - e.position[r], h[r] = i ? t.position[r] - t.target[r] : t.target[r] - t.position[r], e.up[r] += (t.up[r] - e.up[r]) * n;
103
+ p(m, m, h, n, t.up);
104
+ for (let r = 0; r < 3; r++) i ? (e.target[r] += (t.target[r] - e.target[r]) * n, e.position[r] = e.target[r] + m[r]) : (e.position[r] += (t.position[r] - e.position[r]) * n, e.target[r] = e.position[r] + m[r]);
105
+ e.fov += (t.fov - e.fov) * n, e.orthographicHeight !== void 0 && t.orthographicHeight !== void 0 && (e.orthographicHeight += (t.orthographicHeight - e.orthographicHeight) * n), e.roll += (t.roll - e.roll) * n, e.focusDistance ? t.focusDistance && (e.focusDistance += (t.focusDistance - e.focusDistance) * n) : e.focusDistance = t.focusDistance;
106
+ }
107
+ var _ = class n {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
108
+ constructor(e = {}) {
109
+ this.options = e, this.pose = c(), this.stages = [], this.cameras = [], this.listeners = {
110
+ change: /* @__PURE__ */ new Set(),
111
+ blended: /* @__PURE__ */ new Set()
112
+ }, this.events = [], this.layers = [], this.blendFrom = null, this.screenUp = new Float64Array([
113
+ 0,
114
+ 1,
115
+ 0
116
+ ]), this.outPosition = [
117
+ 0,
118
+ 0,
119
+ 0
120
+ ], this.outTarget = [
121
+ 0,
122
+ 0,
123
+ 0
124
+ ], this.outUp = [
125
+ 0,
126
+ 1,
127
+ 0
128
+ ], this.context = { aspect: 16 / 9 }, this.name = e.name ?? "cinematic-brain", e.blend && s(e.blend);
129
+ for (let t of e.rules ?? []) if (s(t), typeof t.from != "string" || typeof t.to != "string") throw RangeError("Invalid camera blend rule; pass from and to as camera names or '*'");
130
+ e.aspect !== void 0 && a(e.aspect);
131
+ }
132
+ static attach(e, r = {}) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
133
+ let i = new n(r);
134
+ return t(e).use(i), i;
135
+ }
136
+ get live() {
137
+ return this.layers.at(-1)?.camera ?? null;
138
+ }
139
+ get blending() {
140
+ return this.layers.length > 1;
141
+ }
142
+ get list() {
143
+ return this.cameras;
144
+ }
145
+ add(e = {}) {
146
+ let t = e instanceof d ? e : new d(e);
147
+ if (this.cameras.includes(t)) throw RangeError("Camera already added; add a camera once");
148
+ if (t.name !== void 0 && this.cameras.some((e) => e.name === t.name)) throw RangeError(`Camera name '${t.name}' is taken; give each camera of a brain its own name`);
149
+ return this.cameras.push(t), t;
150
+ }
151
+ remove(e) {
152
+ let t = this.cameras.indexOf(e);
153
+ t >= 0 && this.cameras.splice(t, 1);
154
+ }
155
+ on(e, t) {
156
+ let n = this.listeners[e];
157
+ if (!n) throw RangeError("Unknown camera brain event; pass 'change' or 'blended'");
158
+ return n.add(t), () => n.delete(t);
159
+ }
160
+ cut() {
161
+ let e = this.layers.at(-1);
162
+ e && (this.layers = [e]);
163
+ }
164
+ blendFor(e, t) {
165
+ let n = e?.name, r = t.name, i = this.options.rules ?? [];
166
+ return i.find((e) => e.from === n && e.to === r) ?? i.find((e) => e.from === n && e.to === "*") ?? i.find((e) => e.from === "*" && e.to === r) ?? i.find((e) => e.from === "*" && e.to === "*") ?? this.options.blend ?? { duration: 1 };
167
+ }
168
+ choose() {
169
+ let e = this.live, t = null;
170
+ for (let e of this.cameras) {
171
+ if (!Number.isFinite(e.priority)) throw RangeError("Invalid camera priority; pass a finite number");
172
+ e.enabled && (!t || e.priority >= t.priority) && (t = e);
173
+ }
174
+ return t && e?.enabled && this.cameras.includes(e) && e.priority === t.priority ? e : t;
175
+ }
176
+ emit(e, t, n, r) {
177
+ this.events.push([e, {
178
+ from: t,
179
+ to: n,
180
+ duration: r
181
+ }]);
182
+ }
183
+ get aspect() {
184
+ let e = this.engine?.canvas;
185
+ return this.options.aspect ?? (e?.height ? e.width / e.height : 16 / 9);
186
+ }
187
+ advance(e) {
188
+ let t = this.layers;
189
+ if (t.length < 2) return;
190
+ let n = 0;
191
+ for (let r = 1; r < t.length; r++) t[r].elapsed += e, t[r].elapsed >= t[r].duration && (n = r);
192
+ if (n && (this.layers = t.slice(n), this.layers.length === 1)) {
193
+ let e = this.layers[0];
194
+ this.emit("blended", this.blendFrom, e.camera, e.duration);
195
+ }
196
+ }
197
+ update(e) {
198
+ this.step(e);
199
+ let t = this.events.splice(0);
200
+ for (let [e, n] of t) for (let t of [...this.listeners[e]]) t(n);
201
+ return this.pose;
202
+ }
203
+ advanceTime(e) {
204
+ this.step(e), this.events.length = 0;
205
+ }
206
+ step(e) {
207
+ this.events.length = 0, i(e);
208
+ let t = this.aspect;
209
+ for (let n of this.cameras) n.enabled && n.update(e, t);
210
+ this.advance(e);
211
+ let n = this.choose(), r = this.live;
212
+ if (!n) return;
213
+ if (n !== r) {
214
+ let { duration: e, ease: t = o, style: i = "direct" } = r ? this.blendFor(r, n) : { duration: 0 }, a = {
215
+ camera: n,
216
+ elapsed: 0,
217
+ duration: e,
218
+ ease: t,
219
+ style: i
220
+ };
221
+ e > 0 ? this.layers.push(a) : this.layers = [a], this.blendFrom = r, this.emit("change", r, n, e), e || this.emit("blended", r, n, 0);
222
+ }
223
+ let a = this.layers;
224
+ if (a.length > 1) for (let n = 0; n < a.length; n++) {
225
+ let r = a[n].camera;
226
+ !r.enabled && this.cameras.includes(r) && a.findIndex((e) => e.camera === r) === n && r.update(e, t);
227
+ }
228
+ l(this.pose, this.layers[0].camera.pose);
229
+ for (let e = 1; e < this.layers.length; e++) {
230
+ let t = this.layers[e], n = t.ease(t.elapsed / t.duration);
231
+ if (!Number.isFinite(n)) throw RangeError("Invalid camera blend ease; return a number for every value of 0..1");
232
+ g(this.pose, t.camera.pose, n, t.style);
233
+ }
234
+ this.context.aspect = t;
235
+ for (let t of this.stages) u(t, this.pose, e, this.context);
236
+ this.write();
237
+ }
238
+ write() {
239
+ let { position: e, target: t, up: n, roll: r, fov: i } = this.pose, a = this.options.camera ?? this.engine?.camera, o = this.screenUp, s = t[0] - e[0], c = t[1] - e[1], l = t[2] - e[2], u = Math.hypot(s, c, l);
240
+ if (u > 0) {
241
+ s /= u, c /= u, l /= u;
242
+ let e = n[0] * s + n[1] * c + n[2] * l, t = n[0] - e * s, r = n[1] - e * c, i = n[2] - e * l;
243
+ if (Math.hypot(t, r, i) <= 1e-6 * Math.hypot(n[0], n[1], n[2]) && (e = o[0] * s + o[1] * c + o[2] * l, t = o[0] - e * s, r = o[1] - e * c, i = o[2] - e * l, Math.hypot(t, r, i) < 1e-6)) {
244
+ let e = Math.abs(s) < .9;
245
+ t = e ? 1 - s * s : -c * s, r = e ? -s * c : 1 - c * c, i = e ? -s * l : -c * l;
246
+ }
247
+ let a = Math.hypot(t, r, i);
248
+ o[0] = t / a, o[1] = r / a, o[2] = i / a;
249
+ }
250
+ if (!a) return;
251
+ let d = Math.cos(r), f = Math.sin(r), p = this.outUp;
252
+ p[0] = o[0] * d + (c * o[2] - l * o[1]) * f, p[1] = o[1] * d + (l * o[0] - s * o[2]) * f, p[2] = o[2] * d + (s * o[1] - c * o[0]) * f;
253
+ for (let n = 0; n < 3; n++) this.outPosition[n] = e[n], this.outTarget[n] = t[n];
254
+ a.position = this.outPosition, a.target = this.outTarget, a.up = p, a.fov = i;
255
+ }
256
+ setup(t) {
257
+ if (this.engine) throw new e("attached", "Camera brain already attached; dispose() it before attaching it again");
258
+ this.engine = t;
259
+ }
260
+ onPreUpdate(e) {
261
+ this.update(e);
262
+ }
263
+ dispose() {
264
+ let e = this.engine;
265
+ this.engine = void 0, this.layers = [], e?.sceneOf(this)?.removePlugin(this.name);
266
+ }
267
+ [Symbol.dispose ?? Symbol()]() {
268
+ this.dispose();
269
+ }
270
+ };
271
+ //#endregion
272
+ export { _ as CameraBrain, d as VirtualCamera, l as copyPose, c as createPose, f as rigStage };
@@ -0,0 +1,62 @@
1
+ import type { CameraPose, StageContext } from './brain.js';
2
+ import { type CameraTarget } from './target.js';
3
+ export type { CameraTarget } from './target.js';
4
+ /** Settings of a {@link FramingComposer}. Screen sizes are shares of the screen: 1 is its full width or height. */
5
+ export interface FramingComposerOptions {
6
+ /** Where the subject sits, as [x, y] from the top left: [0.5, 0.5] is the centre. Default [0.5, 0.5]. */
7
+ screen?: readonly [number, number];
8
+ /** Full [width, height] of the box around `screen` where the subject moves freely. Default [0.1, 0.1]. */
9
+ deadZone?: readonly [number, number];
10
+ /** Full [width, height] of the box the subject never leaves; between the boxes the camera catches up. At least `deadZone`. Default [0.8, 0.8]. */
11
+ softZone?: readonly [number, number];
12
+ /** How fast the camera catches up, in 1/seconds (higher is stiffer), as one number or [horizontal, vertical]. Above 0. Default 4. */
13
+ damping?: number | readonly [number, number];
14
+ /** Seconds to aim ahead of the subject along its velocity, 0 or more. Default 0. */
15
+ lookahead?: number;
16
+ /** How fast the measured velocity follows the subject, in 1/seconds, above 0. Lower is calmer. Default 6. */
17
+ lookaheadSmoothing?: number;
18
+ /** Aim ahead vertically too. Turn it off for a platformer, so a jump does not nod the camera. Default true. */
19
+ lookaheadVertical?: boolean;
20
+ }
21
+ /**
22
+ * A stage that aims the camera so `target` stays in a dead zone and soft zone on screen, with lookahead. Put it after
23
+ * the stage that places the camera. It turns the camera and never moves it, and it works without roll: `pose.roll` is
24
+ * left as it is and not counted.
25
+ */
26
+ export declare class FramingComposer {
27
+ /** What the camera frames. Change it at any time; call `reset` to snap to the new subject. */
28
+ target: CameraTarget;
29
+ /** Where the subject was on screen after the last update, as [x, y] from the top left. */
30
+ readonly onScreen: Float64Array<ArrayBuffer>;
31
+ /** The point aimed at after lookahead, in world units. */
32
+ readonly aimPoint: Float64Array<ArrayBuffer>;
33
+ private readonly sx;
34
+ private readonly sy;
35
+ private readonly deadX;
36
+ private readonly deadY;
37
+ private readonly softX;
38
+ private readonly softY;
39
+ private readonly rateX;
40
+ private readonly rateY;
41
+ private readonly lookahead;
42
+ private readonly smoothing;
43
+ private readonly vertical;
44
+ private readonly current;
45
+ private readonly previous;
46
+ private readonly velocity;
47
+ private readonly forward;
48
+ private started;
49
+ /** @throws RangeError for a value outside what {@link FramingComposerOptions} allows. */
50
+ constructor(target: CameraTarget, options?: FramingComposerOptions);
51
+ /** Forgets the aim and the velocity: the next update puts the subject on its screen point, as after a teleport. */
52
+ reset(): void;
53
+ private aim;
54
+ /** Stage hook. @throws RangeError for a bad target, or a camera standing on its subject's axis with no up. */
55
+ update(pose: CameraPose, delta: number, context: StageContext): void;
56
+ /**
57
+ * Finds the view with no roll that puts the unit direction `d` at screen point (nx, ny). In the camera's axes d is
58
+ * c = (nx tanX, ny tanY, 1) made unit. Its height along up is cy cos(p) + cz sin(p) for a view pitched by p, a single
59
+ * cosine that gives p; the heading is then the angle left over between d and c around up.
60
+ */
61
+ private solve;
62
+ }
@@ -0,0 +1,65 @@
1
+ import { t as e } from "./target-CZNe0IXh.js";
2
+ //#region src/composer.ts
3
+ var t = (e, t) => {
4
+ let n = typeof e == "number" ? [e, e] : e;
5
+ if (n?.length !== 2 || !(Number.isFinite(n[0]) && Number.isFinite(n[1]))) throw RangeError(`Invalid composer ${t}; pass two finite numbers`);
6
+ return n;
7
+ }, n = .001, r = (e, t, n) => Math.min(n, Math.max(t, e)), i = class {
8
+ constructor(e, n = {}) {
9
+ this.onScreen = new Float64Array([.5, .5]), this.aimPoint = /* @__PURE__ */ new Float64Array(3), this.current = /* @__PURE__ */ new Float64Array(3), this.previous = /* @__PURE__ */ new Float64Array(3), this.velocity = /* @__PURE__ */ new Float64Array(3), this.forward = /* @__PURE__ */ new Float64Array(3), this.started = !1;
10
+ let { screen: r = [.5, .5], deadZone: i = [.1, .1], softZone: a = [.8, .8], damping: o = 4, lookahead: s = 0, lookaheadSmoothing: c = 6, lookaheadVertical: l = !0 } = n, [u, d] = t(r, "screen"), [f, p] = t(i, "deadZone"), [m, h] = t(a, "softZone"), [g, _] = t(o, "damping");
11
+ if (u < 0 || u > 1 || d < 0 || d > 1) throw RangeError("Invalid composer screen; pass x and y from 0 to 1");
12
+ if (f < 0 || p < 0 || m < f || h < p) throw RangeError("Invalid composer zones; pass a deadZone of 0 or more and a softZone at least as large");
13
+ if (!(g > 0 && _ > 0)) throw RangeError("Invalid composer damping; pass a rate above 0");
14
+ if (!(s >= 0 && s < Infinity) || !(c > 0 && c < Infinity)) throw RangeError("Invalid composer lookahead; pass 0 or more seconds and a smoothing above 0");
15
+ this.target = e, this.sx = u * 2 - 1, this.sy = 1 - d * 2, this.deadX = f, this.deadY = p, this.softX = m, this.softY = h, this.rateX = g, this.rateY = _, this.lookahead = s, this.smoothing = c, this.vertical = l;
16
+ }
17
+ reset() {
18
+ this.started = !1, this.velocity.fill(0);
19
+ }
20
+ aim(e, t, n, r) {
21
+ let { current: i, previous: a, velocity: o, aimPoint: s } = this;
22
+ if (this.started && e > 0) {
23
+ let t = Math.exp(-this.smoothing * e);
24
+ for (let n = 0; n < 3; n++) o[n] = (i[n] - a[n]) / e + (o[n] - (i[n] - a[n]) / e) * t;
25
+ }
26
+ a.set(i);
27
+ let c = o[0], l = o[1], u = o[2];
28
+ if (!this.vertical) {
29
+ let e = c * t + l * n + u * r;
30
+ c -= e * t, l -= e * n, u -= e * r;
31
+ }
32
+ s[0] = i[0] + c * this.lookahead, s[1] = i[1] + l * this.lookahead, s[2] = i[2] + u * this.lookahead;
33
+ }
34
+ update(t, n, i) {
35
+ e(this.target, this.current);
36
+ let { position: a, up: o } = t, s = Math.hypot(o[0], o[1], o[2]);
37
+ if (!(s > 0)) throw RangeError("Invalid camera up; pass a direction that is not zero");
38
+ let c = o[0] / s, l = o[1] / s, u = o[2] / s;
39
+ this.aim(n, c, l, u);
40
+ let d = this.aimPoint, f = d[0] - a[0], p = d[1] - a[1], m = d[2] - a[2], h = Math.hypot(f, p, m);
41
+ if (!(h > 1e-9)) {
42
+ if (this.started) for (let e = 0; e < 3; e++) t.target[e] = a[e] + this.forward[e];
43
+ return;
44
+ }
45
+ f /= h, p /= h, m /= h;
46
+ let g = Math.tan(t.fov * Math.PI / 360), _ = g * i.aspect, v = this.forward, y = this.sx, b = this.sy;
47
+ if (this.started) {
48
+ let e = v[1] * u - v[2] * l, t = v[2] * c - v[0] * u, i = v[0] * l - v[1] * c, a = Math.hypot(e, t, i);
49
+ e /= a, t /= a, i /= a;
50
+ let o = t * v[2] - i * v[1], s = i * v[0] - e * v[2], d = e * v[1] - t * v[0], h = f * e + p * t + m * i, x = f * o + p * s + m * d, S = f * v[0] + p * v[1] + m * v[2], C = this.softX, w = this.softY, T = S > 1e-6, E = T ? h / S / _ : Math.sign(h) * 1e6, D = T ? x / S / g : Math.sign(x) * 1e6, O = E - this.sx, k = D - this.sy, A = r(O, -this.deadX, this.deadX), j = r(k, -this.deadY, this.deadY);
51
+ y = this.sx + r(A + (O - A) * Math.exp(-this.rateX * n), -C, C), b = this.sy + r(j + (k - j) * Math.exp(-this.rateY * n), -w, w);
52
+ }
53
+ this.solve(y, b, _, g, f, p, m, c, l, u, a, t.target, h), this.onScreen[0] = (y + 1) / 2, this.onScreen[1] = (1 - b) / 2, this.started = !0;
54
+ }
55
+ solve(e, t, i, a, o, s, c, l, u, d, f, p, m) {
56
+ let h = this.forward, g = e * i, _ = t * a, v = 1, y = Math.hypot(g, _, v);
57
+ g /= y, _ /= y, v /= y;
58
+ let b = o * l + s * u + c * d, x = Math.hypot(_, v), S = Math.PI / 2 - n, C = r(Math.atan2(v, _) - Math.acos(r(b / x, -1, 1)), -S, S), w = Math.cos(C), T = Math.sin(C), E = o - b * l, D = s - b * u, O = c - b * d, k = Math.hypot(E, D, O);
59
+ k < 1e-9 && (E = h[0] - (h[0] * l + h[1] * u + h[2] * d) * l, D = h[1] - (h[0] * l + h[1] * u + h[2] * d) * u, O = h[2] - (h[0] * l + h[1] * u + h[2] * d) * d, k = Math.hypot(E, D, O), k < 1e-9 && (E = Math.abs(l) < .9 ? 1 - l * l : -l * u, D = Math.abs(l) < .9 ? -l * u : 1 - u * u, O = Math.abs(l) < .9 ? -l * d : -u * d, k = Math.hypot(E, D, O))), E /= k, D /= k, O /= k;
60
+ let A = Math.atan2(g, v * w - _ * T), j = Math.cos(A), M = Math.sin(A), N = u * O - d * D, P = d * E - l * O, F = l * D - u * E, I = E * j + N * M, L = D * j + P * M, R = O * j + F * M;
61
+ h[0] = I * w + l * T, h[1] = L * w + u * T, h[2] = R * w + d * T, p[0] = f[0] + h[0] * m, p[1] = f[1] + h[1] * m, p[2] = f[2] + h[2] * m;
62
+ }
63
+ };
64
+ //#endregion
65
+ export { i as FramingComposer };
@@ -0,0 +1,50 @@
1
+ import type { CameraPose } from './brain.js';
2
+ /** A {@link CameraConfiner} shape: a box. */
3
+ export interface ConfineBox {
4
+ /** Lowest corner, in world units. */
5
+ min: readonly [number, number, number];
6
+ /** Highest corner. */
7
+ max: readonly [number, number, number];
8
+ }
9
+ /** A {@link CameraConfiner} shape: an area of the level, as an outline on the ground (world x and z), convex or not. */
10
+ export interface ConfineArea {
11
+ /** At least 3 [x, z] points in order, either way round. The outline must not cross itself. */
12
+ area: readonly (readonly [number, number])[];
13
+ /** Lowest camera height, world y. Default no limit. */
14
+ bottom?: number;
15
+ /** Highest camera height, world y. Default no limit. */
16
+ top?: number;
17
+ }
18
+ /** Settings of a {@link CameraConfiner}. */
19
+ export interface CameraConfinerOptions {
20
+ /** Space kept between the camera and every wall, 0 or more, in world units. Default 0. */
21
+ margin?: number;
22
+ }
23
+ /**
24
+ * A stage that keeps the camera inside a box or an area, however it got out. Put it last on a camera, after noise, or in
25
+ * `brain.stages` to hold blends too. The camera keeps looking at the same point.
26
+ */
27
+ export declare class CameraConfiner {
28
+ /** True when the last update had to move the camera. */
29
+ clamped: boolean;
30
+ /** How far the last update moved the camera, in world units. */
31
+ correction: number;
32
+ private readonly margin;
33
+ private readonly low;
34
+ private readonly high;
35
+ private readonly outline?;
36
+ private readonly orientation;
37
+ private readonly near;
38
+ private edge;
39
+ /** @throws RangeError for a shape that is empty, or smaller than its margins. */
40
+ constructor(shape: ConfineBox | ConfineArea, options?: CameraConfinerOptions);
41
+ /** Writes the nearest point of the outline to `near`, with the inward normal of its edge. Returns the distance. */
42
+ private nearest;
43
+ /** Writes to `near` the corner where the margins of two edges meet. False when the edges are parallel. */
44
+ private meet;
45
+ /** Even-odd rule: a ray along +x crosses the outline an odd number of times from inside. */
46
+ private inside;
47
+ private holdArea;
48
+ /** Stage hook. */
49
+ update(pose: CameraPose): void;
50
+ }