@margoengine/cinematic 0.1.0 → 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.
package/README.md CHANGED
@@ -1,321 +1,321 @@
1
- # @margoengine/cinematic
2
-
3
- Virtual cameras with priorities and blends, framing, dolly tracks, group framing, camera noise, confiners and focus tracking, on top of damped follow, look-at and shake.
4
-
5
- `Cinematic` and `CameraBrain` detach from the scene where their actual plugin
6
- instance was registered. Direct disposal, removing the owning plugin or scene,
7
- and engine disposal all release the registration. Repeated disposal preserves
8
- same-name replacements. Both plugins can attach to another scene after disposal;
9
- later cleanup follows that new registration.
10
-
11
- Import `margoengine/cinematic` from the `margoengine` package, or `@margoengine/cinematic` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
12
-
13
- `rig.setOrbitOffset(yaw, pitch, distance, height = 0)` writes the retained camera
14
- offset in place from orbit angles (no new vector is created). The sandbox uses this
15
- public method after its shared locomotion step.
16
-
17
- A virtual camera with analytically integrated critically damped follow and look-at springs plus additive screen shake.
18
-
19
- ```ts
20
- import {Cinematic} from 'margoengine/cinematic';
21
- import {Engine} from 'margoengine/core';
22
- import {boxGeometry} from 'margoengine/geometry';
23
- import {PbrMaterial, createMesh} from 'margoengine/materials';
24
- const engine = await Engine.create(document.querySelector('canvas')!);
25
- const player = createMesh(engine, boxGeometry(0.5, 1.8, 0.5), new PbrMaterial()).root;
26
- const rig = Cinematic.attach(engine, {offset: [0,3,6], damping: 6});
27
- rig.follow(player);
28
- rig.shake(0.2, 0.4);
29
- ```
30
-
31
- follow accepts a live mesh from the attached engine or a world-position tuple. Mesh targets use world transforms. Shake amplitude is in world units and duration is seconds; it does not alter the settled spring position. The frame plugin owns camera position/target while attached, so disable competing camera controls. dispose detaches it.
32
-
33
- Film time: `rig.advanceTime(delta)` is one frame of the rig with no draw (springs, shake, `rig.time`), so `seek` from
34
- `@margoengine/cutscene/seek` starts a film scene where a continuous run's follow and shake are. A `CameraNoise` stage
35
- moves its clock with `noise.advanceTime(delta)`; pass it to `seek` as an `extra` clock when no attached `CameraBrain`
36
- runs it as a stage (the brain's own clock steps its stages).
37
-
38
- Scope the rig with `using` (it calls `dispose()` and returns the camera to your controls):
39
-
40
- ```ts
41
- import {Cinematic} from 'margoengine/cinematic';
42
- import {Engine} from 'margoengine/core';
43
- import {Physics} from 'margoengine/physics';
44
- const engine = await Engine.create(document.querySelector('canvas')!);
45
- await Physics.load();
46
- const physics = Physics.attach(engine);
47
- {
48
- using rig = Cinematic.attach(engine, {offset: [0, 3, 6]});
49
- rig.follow([0, 1.6, 0]);
50
- rig.update(1 / 60);
51
- }
52
- ```
53
-
54
- Errors name their fix: a bad argument throws `RangeError` or `TypeError` (for example `Invalid camera delta; pass a finite delta of 0 or more seconds`), and attaching a rig twice throws `MargoError` with code `attached`.
55
-
56
- Set `ground: (x,z) => height` to keep the camera arm above a CPU heightfield.
57
- `clearance` defaults to 0.65 world units. The rig checks both its desired arm and
58
- the resulting damped/shaken camera, without changing your requested `offset`.
59
- For a below-target orbit, it raises the rendered aim point by as much as the ground
60
- lifted the camera, so terrain clearance preserves upward look instead of forcing the
61
- view back down; shake and spring lag never move the aim point.
62
- Six samples along each arm suit broad terrain; narrow ridges and buildings need
63
- collision geometry. Heights must be finite. Ground handling is disabled by default.
64
-
65
- Walls and ceilings: set `collide: (origin, direction, distance) => hitDistance | null`. Each frame
66
- the rig asks for the first obstacle along the arm from the look-at point to the (damped, shaken,
67
- ground-lifted) camera; on a hit the camera moves in at once to `clearance` short of it, and once the
68
- arm is clear it eases back out at the follow damping. The spring state and your `offset` are
69
- unchanged. The arrays passed in are reused each frame. Any scene query fits, for example a sphere
70
- cast against the physics world (so the near plane does not clip into the wall):
71
-
72
- ```ts
73
- const rig = Cinematic.attach(engine, {offset: [0, 3, 6], clearance: 0.3,
74
- collide: (o, d, max) => physics.shapeCast({shape: 'sphere', radius: 0.2}, [o[0], o[1], o[2]], [0, 0, 0, 1], [d[0], d[1], d[2]], {maxDistance: max, excludeDynamic: true})?.distance});
75
- ```
76
-
77
- or `@margoengine/bvh`'s Raycaster (`firstHitOnly`, `far = max`) over the level. Exclude the followed
78
- character from the query, and start it above the floor if the look-at point sits on it (the arm
79
- starts at the target, usually the character's feet).
80
-
81
- ## Camera priorities and blends
82
-
83
- `@margoengine/cinematic/brain` runs many virtual cameras and shows one. Every enabled `VirtualCamera` keeps moving; the `CameraBrain` puts the highest `priority` on screen and blends when that changes. Raise a priority to take the shot:
84
-
85
- ```ts
86
- import {CameraBrain} from 'margoengine/cinematic/brain';
87
- import {Engine} from 'margoengine/core';
88
- const engine = await Engine.create(document.querySelector('canvas')!);
89
- const brain = CameraBrain.attach(engine, {
90
- blend: {duration: 1.5},
91
- rules: [{from: 'wide', to: 'boss', duration: 0}],
92
- });
93
- brain.add({name: 'wide', priority: 10, position: [0, 8, 20], target: [0, 1, 0], fov: 50});
94
- const boss = brain.add({name: 'boss', priority: 0, position: [3, 2, 6], target: [0, 2, 0], fov: 35});
95
- brain.on('change', ({from, to}) => console.log(from?.name, 'to', to.name));
96
- boss.priority = 20; // The next frame cuts to it, by the rule. Set it back and it blends out over 1.5 s.
97
- ```
98
-
99
- | Option | Default | Meaning |
100
- | --- | --- | --- |
101
- | `blend` | `{duration: 1}` | Used when no rule matches. `duration` in seconds, 0 is a cut; `ease` takes and gives 0..1 (any tween easing), default smoothstep; `style` `'direct'` moves straight across, `'orbit'` swings around the subject. |
102
- | `rules` | none | `{from, to, ...blend}` with camera names or `'*'`. The exact pair wins, then `from` to `'*'`, `'*'` to `to`, `'*'` to `'*'`. |
103
- | `camera` | `engine.camera` | The camera written. |
104
- | `aspect` | the canvas's | Width / height, read by stages. |
105
- | `name` | `'cinematic-brain'` | Plugin name, so each view of a split screen can have a brain. |
106
-
107
- On a tie the camera on screen stays; with none on screen the one added last wins. A switch in the middle of a blend starts from what is on screen, and every camera in a blend keeps moving. `brain.cut()` ends a blend now. `camera.enabled = false` takes a camera out of the running and stops its work; its stages start fresh when it comes back.
108
-
109
- A camera starts each frame from its `base` pose and runs its `stages` in order; `brain.stages` run after them on the blended pose. A stage is a function `(pose, delta, context) => void` or an object with `update` and `reset`. `rigStage` makes a `Cinematic` rig a stage, so the spring follow of this package drives a virtual camera. Do not attach that rig to the engine:
110
-
111
- ```ts
112
- import {Cinematic} from 'margoengine/cinematic';
113
- import {CameraBrain, rigStage} from 'margoengine/cinematic/brain';
114
- const brain = new CameraBrain();
115
- const rig = new Cinematic({offset: [0, 3, 6]});
116
- rig.follow([0, 1, 0]);
117
- brain.add({name: 'follow', stages: [rigStage(rig)]});
118
- console.log(brain.update(1 / 60).position);
119
- ```
120
-
121
- Film time: `brain.advanceTime(delta)` is one update with no listener call (the cameras and their stages, the blend, `brain.stages` and the camera write), so `seek` from `@margoengine/cutscene/seek` starts a film scene where a continuous run's blend, camera moves and focus pulls are. A live `update` sends its `change` and `blended` events after its step, so a listener reads that frame's pose; the steps a seek replays send none.
122
-
123
- ```ts
124
- import {CameraBrain} from 'margoengine/cinematic/brain';
125
- const brain = new CameraBrain({camera: {position: [0, 0, 0], target: [0, 0, 0], up: [0, 1, 0], fov: 60}});
126
- brain.add({name: 'wide', position: [0, 4, 12]});
127
- for (let step = 0; step < 600; step++) brain.advanceTime(1 / 60);
128
- console.log(brain.live?.name, brain.pose.position);
129
- ```
130
-
131
- Cutscenes have their own timed cameras in `@margoengine/cutscene/shots`; the brain is for play, where what happens decides the shot.
132
-
133
- ## Framing composer
134
-
135
- `FramingComposer` keeps a subject on a chosen spot of the screen the way a camera operator does: small moves leave the picture still, bigger ones are caught up with, and the subject never leaves the frame. It is a stage, so it goes after whatever places the camera. It only turns the camera:
136
-
137
- ```ts
138
- import {CameraBrain} from 'margoengine/cinematic/brain';
139
- import {FramingComposer} from 'margoengine/cinematic/composer';
140
- import {Engine} from 'margoengine/core';
141
- import {boxGeometry} from 'margoengine/geometry';
142
- import {PbrMaterial, createMesh} from 'margoengine/materials';
143
- const engine = await Engine.create(document.querySelector('canvas')!);
144
- const player = createMesh(engine, boxGeometry(0.5, 1.8, 0.5), new PbrMaterial()).root;
145
- const brain = CameraBrain.attach(engine);
146
- brain.add({
147
- position: [0, 4, 12],
148
- stages: [new FramingComposer(player, {screen: [0.4, 0.6], deadZone: [0.15, 0.1], lookahead: 0.4})],
149
- });
150
- ```
151
-
152
- The target is a mesh, a world point or a function giving one. Sizes are shares of the screen, and `screen` counts from the top left.
153
-
154
- | Option | Default | Meaning |
155
- | --- | --- | --- |
156
- | `screen` | `[0.5, 0.5]` | Where the subject sits. `[1 / 3, 0.5]` is the rule of thirds. |
157
- | `deadZone` | `[0.1, 0.1]` | Full width and height of the box around `screen` where the camera does not move. |
158
- | `softZone` | `[0.8, 0.8]` | The box the subject never leaves. Between the two the camera catches up. |
159
- | `damping` | `4` | Catch-up rate in 1/seconds, or `[horizontal, vertical]`. Higher is stiffer. Any frame rate gives the same motion. |
160
- | `lookahead` | `0` | Seconds to aim ahead of the subject along its velocity. |
161
- | `lookaheadSmoothing` | `6` | How fast the measured velocity follows, in 1/seconds. Lower is calmer. |
162
- | `lookaheadVertical` | `true` | Turn it off for a platformer, so a jump does not nod the camera. |
163
-
164
- `composer.onScreen` says where the subject is, and `composer.reset()` snaps it back to `screen`, as after a teleport. The camera's `reset()` does the same for all its stages.
165
-
166
- ## Dolly tracks
167
-
168
- `DollyTrack` puts the camera on a rail: any `Spline` from `@margoengine/splines`. Give it a target and the cart goes to the point of the track nearest that target, so the camera keeps pace with the subject without keyframes. It is a stage and goes first; aim afterwards with `FramingComposer`, or let `lookAlong` look down the track.
169
-
170
- ```ts
171
- import {CameraBrain} from 'margoengine/cinematic/brain';
172
- import {FramingComposer} from 'margoengine/cinematic/composer';
173
- import {DollyTrack} from 'margoengine/cinematic/dolly';
174
- import {Engine} from 'margoengine/core';
175
- import {boxGeometry} from 'margoengine/geometry';
176
- import {PbrMaterial, createMesh} from 'margoengine/materials';
177
- import {Spline} from 'margoengine/splines';
178
- const engine = await Engine.create(document.querySelector('canvas')!);
179
- const runner = createMesh(engine, boxGeometry(0.5, 1.8, 0.5), new PbrMaterial()).root;
180
- const rail = new Spline([[-20, 3, 8], [0, 4, 10], [20, 3, 8]]);
181
- const brain = CameraBrain.attach(engine);
182
- brain.add({stages: [new DollyTrack(rail, {target: runner, lead: 2}), new FramingComposer(runner)]});
183
- ```
184
-
185
- | Option | Default | Meaning |
186
- | --- | --- | --- |
187
- | `target` | none | A mesh, point or function. Without one the cart stays at `position`; write `dolly.position` to move it. |
188
- | `position` | `0`, or nearest to `target` | Start, in world units along the track. |
189
- | `lead` | `0` | Stay this far ahead of the nearest point; below 0 is behind. |
190
- | `damping` | `4` | Catch-up rate in 1/seconds. |
191
- | `window` | whole track | Search only this far either side of the cart. Set it when the track passes close to itself. |
192
- | `lookAlong` | `false` | Look down the track. |
193
-
194
- A closed track wraps and the cart takes the short way round; an open one stops at its ends. `dolly.reset()` puts the cart back on the subject at once. The tests use generated curves as a stand-in for a track from a real level.
195
-
196
- ## Group framing
197
-
198
- `GroupFraming` keeps several subjects in one shot. It aims at their centre and moves or zooms until all of them fit. The angle of the shot comes from the pose, so set that with the camera's `position` and `target`, or an earlier stage:
199
-
200
- ```ts
201
- import {CameraBrain} from 'margoengine/cinematic/brain';
202
- import {GroupFraming} from 'margoengine/cinematic/group';
203
- import {Engine} from 'margoengine/core';
204
- import {boxGeometry} from 'margoengine/geometry';
205
- import {PbrMaterial, createMesh} from 'margoengine/materials';
206
- const engine = await Engine.create(document.querySelector('canvas')!);
207
- const player = (x: number) => {
208
- const mesh = createMesh(engine, boxGeometry(0.5, 1.8, 0.5), new PbrMaterial()).root;
209
- mesh.setPosition([x, 0, 0]);
210
- return mesh;
211
- };
212
- const brain = CameraBrain.attach(engine);
213
- const group = new GroupFraming(
214
- [{target: player(-4), radius: 1}, {target: player(4), radius: 1, weight: 2}],
215
- {mode: 'both', maxDistance: 40},
216
- );
217
- brain.add({position: [0, 8, 14], target: [0, 1, 0], fov: 45, stages: [group]});
218
- ```
219
-
220
- | Option | Default | Meaning |
221
- | --- | --- | --- |
222
- | `mode` | `'dolly'` | `'dolly'` moves along the view; `'zoom'` stands still and changes the field of view; `'both'` moves, then zooms for what the distance limits left. |
223
- | `padding` | `0.1` | Share of the screen kept clear at each side. |
224
- | `minDistance`, `maxDistance` | `1`, `Infinity` | How near and far the camera goes from the centre. |
225
- | `minFov`, `maxFov` | `10`, `100` | Limits of the zoom, in degrees. |
226
- | `damping` | `4` | How fast the shot follows, in 1/seconds. |
227
-
228
- A member is a mesh, a point, a function or `{target, radius, weight}`. `radius` is a sphere that stays in view; `weight` pulls the centre, and 0 leaves the member out. `group.members` can change at any time. `group.fits` is false when the limits stop the shot, and `group.center` can feed a `FramingComposer`: `new FramingComposer(() => group.center)`.
229
-
230
- ## Noise profiles
231
-
232
- `CameraNoise` makes a camera feel held, carried or driven. A profile is plain data, so it can live in a JSON file: bands of smooth noise on each axis, each with a `frequency` in hertz, the middle of its power, and an `amplitude` that is the most it can add. It is a stage and goes after the stages that aim:
233
-
234
- ```ts
235
- import {CameraBrain} from 'margoengine/cinematic/brain';
236
- import {CameraNoise, handheld, type NoiseProfile} from 'margoengine/cinematic/noise';
237
- const brain = new CameraBrain();
238
- const shaky = new CameraNoise(handheld, {gain: 1.5, seed: 7});
239
- brain.add({name: 'documentary', position: [0, 2, 6], target: [0, 1, 0], stages: [shaky]});
240
-
241
- const boat: NoiseProfile = {
242
- position: {y: [{frequency: 0.2, amplitude: 0.3}]},
243
- rotation: {roll: [{frequency: 0.15, amplitude: 0.05}], pitch: [{frequency: 0.2, amplitude: 0.02}]},
244
- };
245
- brain.add({name: 'deck', position: [0, 3, 6], target: [0, 2, 0], stages: [new CameraNoise(boat)]});
246
- console.log(brain.update(1 / 60).position);
247
- ```
248
-
249
- | Export | What it is |
250
- | --- | --- |
251
- | `handheld` | Slow sway of the arms and a little hand tremor near 8 Hz. |
252
- | `walking` | The step up and down near 2 Hz, the sway of each leg at half that. |
253
- | `vehicle` | Body bounce near 1 to 2 Hz and the buzz of the wheels near 12 Hz. |
254
-
255
- | Option | Default | Meaning |
256
- | --- | --- | --- |
257
- | `gain` | `1` | Scales every amplitude. Change it at any time, or tween it to fade the noise. |
258
- | `speed` | `1` | Scales every frequency. Tie it to a vehicle's speed. |
259
- | `seed` | `0` | The same seed gives the same motion. |
260
-
261
- `position` moves along the camera's own axes in world units; `rotation` is `pitch`, `yaw` and `roll` in radians. The motion is a function of time, so it does not change with the frame rate; set `noise.time` to replay a moment. The amplitudes of the presets were chosen by eye and their frequencies follow published ranges, so treat them as starting points. Keep a band below half the frame rate. For one short hit, use `Cinematic.shake`.
262
-
263
- ## Confiner volumes
264
-
265
- `CameraConfiner` keeps the camera inside a box or an area of the level, however it got out. The camera keeps looking at the same point. Put it last on a camera, after noise, or in `brain.stages`, where it holds blends between cameras too:
266
-
267
- ```ts
268
- import {CameraBrain} from 'margoengine/cinematic/brain';
269
- import {CameraConfiner} from 'margoengine/cinematic/confine';
270
- const brain = new CameraBrain();
271
- brain.stages.push(new CameraConfiner({min: [-50, 0.5, -50], max: [50, 30, 50]}, {margin: 1}));
272
- const room = new CameraConfiner(
273
- {area: [[0, 0], [30, 0], [30, 30], [20, 30], [20, 10], [10, 10], [10, 30], [0, 30]], bottom: 1, top: 6},
274
- {margin: 0.5},
275
- );
276
- const camera = brain.add({position: [15, 3, 25], target: [15, 2, 0], stages: [room]});
277
- console.log(camera.update(1 / 60).position, room.clamped);
278
- ```
279
-
280
- | Shape | Meaning |
281
- | --- | --- |
282
- | `{min, max}` | A box, aligned to the world axes. |
283
- | `{area, bottom, top}` | An outline of `[x, z]` points on the ground, convex or not, either way round, with optional height limits. |
284
-
285
- `margin` (default 0) is the space kept from every wall. `confiner.clamped` says whether the last update moved the camera and `confiner.correction` how far. For walls between the camera and its subject use the `collide` option of `Cinematic`.
286
-
287
- ## Focus tracking
288
-
289
- `FocusTracker` is a focus puller and a zoom operator. It sets the pose's focus from a followed subject, measured along the view as a lens does, and with `size` it also sets the field of view that holds the subject at one size on screen. `focusOutput` goes in `brain.stages` and hands the focus to the lens, so a blend racks focus from one camera to the next:
290
-
291
- ```ts
292
- import {PhysicalCamera} from 'margoengine/cameras/physical';
293
- import {CameraBrain} from 'margoengine/cinematic/brain';
294
- import {FocusTracker, focusOutput} from 'margoengine/cinematic/lens';
295
- const brain = new CameraBrain();
296
- const physical = new PhysicalCamera({focalLength: 85, aperture: 1.8});
297
- brain.stages.push(focusOutput({physical}));
298
- const hero = [0, 1.6, 0] as const;
299
- brain.add({position: [0, 1.6, 6], target: [0, 1.6, 0], stages: [new FocusTracker(hero, {size: 1.8, screenHeight: 0.6})]});
300
- brain.update(1 / 60);
301
- console.log(physical.focusDistance, brain.pose.fov);
302
- ```
303
-
304
- Pass `dof` as well to drive a `DOF` effect from `@margoengine/dof`.
305
-
306
- | Option | Default | Meaning |
307
- | --- | --- | --- |
308
- | `focusDamping` | `6` | How fast focus follows, in 1/seconds. Lower is a slow rack. |
309
- | `focusOffset` | `0` | Added to the distance, to focus on a face rather than the feet. |
310
- | `minFocus` | `0.1` | Nearest focus. Keep it beyond the focal length. |
311
- | `size` | none | Height of the subject in world units. Turns on the field of view. |
312
- | `screenHeight` | `0.5` | Share of the screen height the subject fills. |
313
- | `fovDamping` | `4` | How fast the field of view follows. |
314
- | `minFov`, `maxFov` | `10`, `100` | Limits, in degrees. |
315
-
316
- Keep `minFocus` above the lens's focal length: `DOF` refuses a focus at or inside it. Focus comes from the point you give it. To focus on whatever a pixel shows, use `Autofocus` from `@margoengine/dof/autofocus`.
317
-
318
- Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
319
-
320
- Build and unit tests: npm test --workspace @margoengine/cinematic
321
-
1
+ # @margoengine/cinematic
2
+
3
+ Virtual cameras with priorities and blends, framing, dolly tracks, group framing, camera noise, confiners and focus tracking, on top of damped follow, look-at and shake.
4
+
5
+ `Cinematic` and `CameraBrain` detach from the scene where their actual plugin
6
+ instance was registered. Direct disposal, removing the owning plugin or scene,
7
+ and engine disposal all release the registration. Repeated disposal preserves
8
+ same-name replacements. Both plugins can attach to another scene after disposal;
9
+ later cleanup follows that new registration.
10
+
11
+ Import `margoengine/cinematic` from the `margoengine` package, or `@margoengine/cinematic` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
12
+
13
+ `rig.setOrbitOffset(yaw, pitch, distance, height = 0)` writes the retained camera
14
+ offset in place from orbit angles (no new vector is created). The sandbox uses this
15
+ public method after its shared locomotion step.
16
+
17
+ A virtual camera with analytically integrated critically damped follow and look-at springs plus additive screen shake.
18
+
19
+ ```ts
20
+ import {Cinematic} from 'margoengine/cinematic';
21
+ import {Engine} from 'margoengine/core';
22
+ import {boxGeometry} from 'margoengine/geometry';
23
+ import {PbrMaterial, createMesh} from 'margoengine/materials';
24
+ const engine = await Engine.create(document.querySelector('canvas')!);
25
+ const player = createMesh(engine, boxGeometry(0.5, 1.8, 0.5), new PbrMaterial()).root;
26
+ const rig = Cinematic.attach(engine, {offset: [0,3,6], damping: 6});
27
+ rig.follow(player);
28
+ rig.shake(0.2, 0.4);
29
+ ```
30
+
31
+ follow accepts a live mesh from the attached engine or a world-position tuple. Mesh targets use world transforms. Shake amplitude is in world units and duration is seconds; it does not alter the settled spring position. The frame plugin owns camera position/target while attached, so disable competing camera controls. dispose detaches it.
32
+
33
+ Film time: `rig.advanceTime(delta)` is one frame of the rig with no draw (springs, shake, `rig.time`), so `seek` from
34
+ `@margoengine/cutscene/seek` starts a film scene where a continuous run's follow and shake are. A `CameraNoise` stage
35
+ moves its clock with `noise.advanceTime(delta)`; pass it to `seek` as an `extra` clock when no attached `CameraBrain`
36
+ runs it as a stage (the brain's own clock steps its stages).
37
+
38
+ Scope the rig with `using` (it calls `dispose()` and returns the camera to your controls):
39
+
40
+ ```ts
41
+ import {Cinematic} from 'margoengine/cinematic';
42
+ import {Engine} from 'margoengine/core';
43
+ import {Physics} from 'margoengine/physics';
44
+ const engine = await Engine.create(document.querySelector('canvas')!);
45
+ await Physics.load();
46
+ const physics = Physics.attach(engine);
47
+ {
48
+ using rig = Cinematic.attach(engine, {offset: [0, 3, 6]});
49
+ rig.follow([0, 1.6, 0]);
50
+ rig.update(1 / 60);
51
+ }
52
+ ```
53
+
54
+ Errors name their fix: a bad argument throws `RangeError` or `TypeError` (for example `Invalid camera delta; pass a finite delta of 0 or more seconds`), and attaching a rig twice throws `MargoError` with code `attached`.
55
+
56
+ Set `ground: (x,z) => height` to keep the camera arm above a CPU heightfield.
57
+ `clearance` defaults to 0.65 world units. The rig checks both its desired arm and
58
+ the resulting damped/shaken camera, without changing your requested `offset`.
59
+ For a below-target orbit, it raises the rendered aim point by as much as the ground
60
+ lifted the camera, so terrain clearance preserves upward look instead of forcing the
61
+ view back down; shake and spring lag never move the aim point.
62
+ Six samples along each arm suit broad terrain; narrow ridges and buildings need
63
+ collision geometry. Heights must be finite. Ground handling is disabled by default.
64
+
65
+ Walls and ceilings: set `collide: (origin, direction, distance) => hitDistance | null`. Each frame
66
+ the rig asks for the first obstacle along the arm from the look-at point to the (damped, shaken,
67
+ ground-lifted) camera; on a hit the camera moves in at once to `clearance` short of it, and once the
68
+ arm is clear it eases back out at the follow damping. The spring state and your `offset` are
69
+ unchanged. The arrays passed in are reused each frame. Any scene query fits, for example a sphere
70
+ cast against the physics world (so the near plane does not clip into the wall):
71
+
72
+ ```ts
73
+ const rig = Cinematic.attach(engine, {offset: [0, 3, 6], clearance: 0.3,
74
+ collide: (o, d, max) => physics.shapeCast({shape: 'sphere', radius: 0.2}, [o[0], o[1], o[2]], [0, 0, 0, 1], [d[0], d[1], d[2]], {maxDistance: max, excludeDynamic: true})?.distance});
75
+ ```
76
+
77
+ or `@margoengine/bvh`'s Raycaster (`firstHitOnly`, `far = max`) over the level. Exclude the followed
78
+ character from the query, and start it above the floor if the look-at point sits on it (the arm
79
+ starts at the target, usually the character's feet).
80
+
81
+ ## Camera priorities and blends
82
+
83
+ `@margoengine/cinematic/brain` runs many virtual cameras and shows one. Every enabled `VirtualCamera` keeps moving; the `CameraBrain` puts the highest `priority` on screen and blends when that changes. Raise a priority to take the shot:
84
+
85
+ ```ts
86
+ import {CameraBrain} from 'margoengine/cinematic/brain';
87
+ import {Engine} from 'margoengine/core';
88
+ const engine = await Engine.create(document.querySelector('canvas')!);
89
+ const brain = CameraBrain.attach(engine, {
90
+ blend: {duration: 1.5},
91
+ rules: [{from: 'wide', to: 'boss', duration: 0}],
92
+ });
93
+ brain.add({name: 'wide', priority: 10, position: [0, 8, 20], target: [0, 1, 0], fov: 50});
94
+ const boss = brain.add({name: 'boss', priority: 0, position: [3, 2, 6], target: [0, 2, 0], fov: 35});
95
+ brain.on('change', ({from, to}) => console.log(from?.name, 'to', to.name));
96
+ boss.priority = 20; // The next frame cuts to it, by the rule. Set it back and it blends out over 1.5 s.
97
+ ```
98
+
99
+ | Option | Default | Meaning |
100
+ | --- | --- | --- |
101
+ | `blend` | `{duration: 1}` | Used when no rule matches. `duration` in seconds, 0 is a cut; `ease` takes and gives 0..1 (any tween easing), default smoothstep; `style` `'direct'` moves straight across, `'orbit'` swings around the subject. |
102
+ | `rules` | none | `{from, to, ...blend}` with camera names or `'*'`. The exact pair wins, then `from` to `'*'`, `'*'` to `to`, `'*'` to `'*'`. |
103
+ | `camera` | `engine.camera` | The camera written. |
104
+ | `aspect` | the canvas's | Width / height, read by stages. |
105
+ | `name` | `'cinematic-brain'` | Plugin name, so each view of a split screen can have a brain. |
106
+
107
+ On a tie the camera on screen stays; with none on screen the one added last wins. A switch in the middle of a blend starts from what is on screen, and every camera in a blend keeps moving. `brain.cut()` ends a blend now. `camera.enabled = false` takes a camera out of the running and stops its work; its stages start fresh when it comes back.
108
+
109
+ A camera starts each frame from its `base` pose and runs its `stages` in order; `brain.stages` run after them on the blended pose. A stage is a function `(pose, delta, context) => void` or an object with `update` and `reset`. `rigStage` makes a `Cinematic` rig a stage, so the spring follow of this package drives a virtual camera. Do not attach that rig to the engine:
110
+
111
+ ```ts
112
+ import {Cinematic} from 'margoengine/cinematic';
113
+ import {CameraBrain, rigStage} from 'margoengine/cinematic/brain';
114
+ const brain = new CameraBrain();
115
+ const rig = new Cinematic({offset: [0, 3, 6]});
116
+ rig.follow([0, 1, 0]);
117
+ brain.add({name: 'follow', stages: [rigStage(rig)]});
118
+ console.log(brain.update(1 / 60).position);
119
+ ```
120
+
121
+ Film time: `brain.advanceTime(delta)` is one update with no listener call (the cameras and their stages, the blend, `brain.stages` and the camera write), so `seek` from `@margoengine/cutscene/seek` starts a film scene where a continuous run's blend, camera moves and focus pulls are. A live `update` sends its `change` and `blended` events after its step, so a listener reads that frame's pose; the steps a seek replays send none.
122
+
123
+ ```ts
124
+ import {CameraBrain} from 'margoengine/cinematic/brain';
125
+ const brain = new CameraBrain({camera: {position: [0, 0, 0], target: [0, 0, 0], up: [0, 1, 0], fov: 60}});
126
+ brain.add({name: 'wide', position: [0, 4, 12]});
127
+ for (let step = 0; step < 600; step++) brain.advanceTime(1 / 60);
128
+ console.log(brain.live?.name, brain.pose.position);
129
+ ```
130
+
131
+ Cutscenes have their own timed cameras in `@margoengine/cutscene/shots`; the brain is for play, where what happens decides the shot.
132
+
133
+ ## Framing composer
134
+
135
+ `FramingComposer` keeps a subject on a chosen spot of the screen the way a camera operator does: small moves leave the picture still, bigger ones are caught up with, and the subject never leaves the frame. It is a stage, so it goes after whatever places the camera. It only turns the camera:
136
+
137
+ ```ts
138
+ import {CameraBrain} from 'margoengine/cinematic/brain';
139
+ import {FramingComposer} from 'margoengine/cinematic/composer';
140
+ import {Engine} from 'margoengine/core';
141
+ import {boxGeometry} from 'margoengine/geometry';
142
+ import {PbrMaterial, createMesh} from 'margoengine/materials';
143
+ const engine = await Engine.create(document.querySelector('canvas')!);
144
+ const player = createMesh(engine, boxGeometry(0.5, 1.8, 0.5), new PbrMaterial()).root;
145
+ const brain = CameraBrain.attach(engine);
146
+ brain.add({
147
+ position: [0, 4, 12],
148
+ stages: [new FramingComposer(player, {screen: [0.4, 0.6], deadZone: [0.15, 0.1], lookahead: 0.4})],
149
+ });
150
+ ```
151
+
152
+ The target is a mesh, a world point or a function giving one. Sizes are shares of the screen, and `screen` counts from the top left.
153
+
154
+ | Option | Default | Meaning |
155
+ | --- | --- | --- |
156
+ | `screen` | `[0.5, 0.5]` | Where the subject sits. `[1 / 3, 0.5]` is the rule of thirds. |
157
+ | `deadZone` | `[0.1, 0.1]` | Full width and height of the box around `screen` where the camera does not move. |
158
+ | `softZone` | `[0.8, 0.8]` | The box the subject never leaves. Between the two the camera catches up. |
159
+ | `damping` | `4` | Catch-up rate in 1/seconds, or `[horizontal, vertical]`. Higher is stiffer. Any frame rate gives the same motion. |
160
+ | `lookahead` | `0` | Seconds to aim ahead of the subject along its velocity. |
161
+ | `lookaheadSmoothing` | `6` | How fast the measured velocity follows, in 1/seconds. Lower is calmer. |
162
+ | `lookaheadVertical` | `true` | Turn it off for a platformer, so a jump does not nod the camera. |
163
+
164
+ `composer.onScreen` says where the subject is, and `composer.reset()` snaps it back to `screen`, as after a teleport. The camera's `reset()` does the same for all its stages.
165
+
166
+ ## Dolly tracks
167
+
168
+ `DollyTrack` puts the camera on a rail: any `Spline` from `@margoengine/splines`. Give it a target and the cart goes to the point of the track nearest that target, so the camera keeps pace with the subject without keyframes. It is a stage and goes first; aim afterwards with `FramingComposer`, or let `lookAlong` look down the track.
169
+
170
+ ```ts
171
+ import {CameraBrain} from 'margoengine/cinematic/brain';
172
+ import {FramingComposer} from 'margoengine/cinematic/composer';
173
+ import {DollyTrack} from 'margoengine/cinematic/dolly';
174
+ import {Engine} from 'margoengine/core';
175
+ import {boxGeometry} from 'margoengine/geometry';
176
+ import {PbrMaterial, createMesh} from 'margoengine/materials';
177
+ import {Spline} from 'margoengine/splines';
178
+ const engine = await Engine.create(document.querySelector('canvas')!);
179
+ const runner = createMesh(engine, boxGeometry(0.5, 1.8, 0.5), new PbrMaterial()).root;
180
+ const rail = new Spline([[-20, 3, 8], [0, 4, 10], [20, 3, 8]]);
181
+ const brain = CameraBrain.attach(engine);
182
+ brain.add({stages: [new DollyTrack(rail, {target: runner, lead: 2}), new FramingComposer(runner)]});
183
+ ```
184
+
185
+ | Option | Default | Meaning |
186
+ | --- | --- | --- |
187
+ | `target` | none | A mesh, point or function. Without one the cart stays at `position`; write `dolly.position` to move it. |
188
+ | `position` | `0`, or nearest to `target` | Start, in world units along the track. |
189
+ | `lead` | `0` | Stay this far ahead of the nearest point; below 0 is behind. |
190
+ | `damping` | `4` | Catch-up rate in 1/seconds. |
191
+ | `window` | whole track | Search only this far either side of the cart. Set it when the track passes close to itself. |
192
+ | `lookAlong` | `false` | Look down the track. |
193
+
194
+ A closed track wraps and the cart takes the short way round; an open one stops at its ends. `dolly.reset()` puts the cart back on the subject at once. The tests use generated curves as a stand-in for a track from a real level.
195
+
196
+ ## Group framing
197
+
198
+ `GroupFraming` keeps several subjects in one shot. It aims at their centre and moves or zooms until all of them fit. The angle of the shot comes from the pose, so set that with the camera's `position` and `target`, or an earlier stage:
199
+
200
+ ```ts
201
+ import {CameraBrain} from 'margoengine/cinematic/brain';
202
+ import {GroupFraming} from 'margoengine/cinematic/group';
203
+ import {Engine} from 'margoengine/core';
204
+ import {boxGeometry} from 'margoengine/geometry';
205
+ import {PbrMaterial, createMesh} from 'margoengine/materials';
206
+ const engine = await Engine.create(document.querySelector('canvas')!);
207
+ const player = (x: number) => {
208
+ const mesh = createMesh(engine, boxGeometry(0.5, 1.8, 0.5), new PbrMaterial()).root;
209
+ mesh.setPosition([x, 0, 0]);
210
+ return mesh;
211
+ };
212
+ const brain = CameraBrain.attach(engine);
213
+ const group = new GroupFraming(
214
+ [{target: player(-4), radius: 1}, {target: player(4), radius: 1, weight: 2}],
215
+ {mode: 'both', maxDistance: 40},
216
+ );
217
+ brain.add({position: [0, 8, 14], target: [0, 1, 0], fov: 45, stages: [group]});
218
+ ```
219
+
220
+ | Option | Default | Meaning |
221
+ | --- | --- | --- |
222
+ | `mode` | `'dolly'` | `'dolly'` moves along the view; `'zoom'` stands still and changes the field of view; `'both'` moves, then zooms for what the distance limits left. |
223
+ | `padding` | `0.1` | Share of the screen kept clear at each side. |
224
+ | `minDistance`, `maxDistance` | `1`, `Infinity` | How near and far the camera goes from the centre. |
225
+ | `minFov`, `maxFov` | `10`, `100` | Limits of the zoom, in degrees. |
226
+ | `damping` | `4` | How fast the shot follows, in 1/seconds. |
227
+
228
+ A member is a mesh, a point, a function or `{target, radius, weight}`. `radius` is a sphere that stays in view; `weight` pulls the centre, and 0 leaves the member out. `group.members` can change at any time. `group.fits` is false when the limits stop the shot, and `group.center` can feed a `FramingComposer`: `new FramingComposer(() => group.center)`.
229
+
230
+ ## Noise profiles
231
+
232
+ `CameraNoise` makes a camera feel held, carried or driven. A profile is plain data, so it can live in a JSON file: bands of smooth noise on each axis, each with a `frequency` in hertz, the middle of its power, and an `amplitude` that is the most it can add. It is a stage and goes after the stages that aim:
233
+
234
+ ```ts
235
+ import {CameraBrain} from 'margoengine/cinematic/brain';
236
+ import {CameraNoise, handheld, type NoiseProfile} from 'margoengine/cinematic/noise';
237
+ const brain = new CameraBrain();
238
+ const shaky = new CameraNoise(handheld, {gain: 1.5, seed: 7});
239
+ brain.add({name: 'documentary', position: [0, 2, 6], target: [0, 1, 0], stages: [shaky]});
240
+
241
+ const boat: NoiseProfile = {
242
+ position: {y: [{frequency: 0.2, amplitude: 0.3}]},
243
+ rotation: {roll: [{frequency: 0.15, amplitude: 0.05}], pitch: [{frequency: 0.2, amplitude: 0.02}]},
244
+ };
245
+ brain.add({name: 'deck', position: [0, 3, 6], target: [0, 2, 0], stages: [new CameraNoise(boat)]});
246
+ console.log(brain.update(1 / 60).position);
247
+ ```
248
+
249
+ | Export | What it is |
250
+ | --- | --- |
251
+ | `handheld` | Slow sway of the arms and a little hand tremor near 8 Hz. |
252
+ | `walking` | The step up and down near 2 Hz, the sway of each leg at half that. |
253
+ | `vehicle` | Body bounce near 1 to 2 Hz and the buzz of the wheels near 12 Hz. |
254
+
255
+ | Option | Default | Meaning |
256
+ | --- | --- | --- |
257
+ | `gain` | `1` | Scales every amplitude. Change it at any time, or tween it to fade the noise. |
258
+ | `speed` | `1` | Scales every frequency. Tie it to a vehicle's speed. |
259
+ | `seed` | `0` | The same seed gives the same motion. |
260
+
261
+ `position` moves along the camera's own axes in world units; `rotation` is `pitch`, `yaw` and `roll` in radians. The motion is a function of time, so it does not change with the frame rate; set `noise.time` to replay a moment. The amplitudes of the presets were chosen by eye and their frequencies follow published ranges, so treat them as starting points. Keep a band below half the frame rate. For one short hit, use `Cinematic.shake`.
262
+
263
+ ## Confiner volumes
264
+
265
+ `CameraConfiner` keeps the camera inside a box or an area of the level, however it got out. The camera keeps looking at the same point. Put it last on a camera, after noise, or in `brain.stages`, where it holds blends between cameras too:
266
+
267
+ ```ts
268
+ import {CameraBrain} from 'margoengine/cinematic/brain';
269
+ import {CameraConfiner} from 'margoengine/cinematic/confine';
270
+ const brain = new CameraBrain();
271
+ brain.stages.push(new CameraConfiner({min: [-50, 0.5, -50], max: [50, 30, 50]}, {margin: 1}));
272
+ const room = new CameraConfiner(
273
+ {area: [[0, 0], [30, 0], [30, 30], [20, 30], [20, 10], [10, 10], [10, 30], [0, 30]], bottom: 1, top: 6},
274
+ {margin: 0.5},
275
+ );
276
+ const camera = brain.add({position: [15, 3, 25], target: [15, 2, 0], stages: [room]});
277
+ console.log(camera.update(1 / 60).position, room.clamped);
278
+ ```
279
+
280
+ | Shape | Meaning |
281
+ | --- | --- |
282
+ | `{min, max}` | A box, aligned to the world axes. |
283
+ | `{area, bottom, top}` | An outline of `[x, z]` points on the ground, convex or not, either way round, with optional height limits. |
284
+
285
+ `margin` (default 0) is the space kept from every wall. `confiner.clamped` says whether the last update moved the camera and `confiner.correction` how far. For walls between the camera and its subject use the `collide` option of `Cinematic`.
286
+
287
+ ## Focus tracking
288
+
289
+ `FocusTracker` is a focus puller and a zoom operator. It sets the pose's focus from a followed subject, measured along the view as a lens does, and with `size` it also sets the field of view that holds the subject at one size on screen. `focusOutput` goes in `brain.stages` and hands the focus to the lens, so a blend racks focus from one camera to the next:
290
+
291
+ ```ts
292
+ import {PhysicalCamera} from 'margoengine/cameras/physical';
293
+ import {CameraBrain} from 'margoengine/cinematic/brain';
294
+ import {FocusTracker, focusOutput} from 'margoengine/cinematic/lens';
295
+ const brain = new CameraBrain();
296
+ const physical = new PhysicalCamera({focalLength: 85, aperture: 1.8});
297
+ brain.stages.push(focusOutput({physical}));
298
+ const hero = [0, 1.6, 0] as const;
299
+ brain.add({position: [0, 1.6, 6], target: [0, 1.6, 0], stages: [new FocusTracker(hero, {size: 1.8, screenHeight: 0.6})]});
300
+ brain.update(1 / 60);
301
+ console.log(physical.focusDistance, brain.pose.fov);
302
+ ```
303
+
304
+ Pass `dof` as well to drive a `DOF` effect from `@margoengine/dof`.
305
+
306
+ | Option | Default | Meaning |
307
+ | --- | --- | --- |
308
+ | `focusDamping` | `6` | How fast focus follows, in 1/seconds. Lower is a slow rack. |
309
+ | `focusOffset` | `0` | Added to the distance, to focus on a face rather than the feet. |
310
+ | `minFocus` | `0.1` | Nearest focus. Keep it beyond the focal length. |
311
+ | `size` | none | Height of the subject in world units. Turns on the field of view. |
312
+ | `screenHeight` | `0.5` | Share of the screen height the subject fills. |
313
+ | `fovDamping` | `4` | How fast the field of view follows. |
314
+ | `minFov`, `maxFov` | `10`, `100` | Limits, in degrees. |
315
+
316
+ Keep `minFocus` above the lens's focal length: `DOF` refuses a focus at or inside it. Focus comes from the point you give it. To focus on whatever a pixel shows, use `Autofocus` from `@margoengine/dof/autofocus`.
317
+
318
+ Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
319
+
320
+ Build and unit tests: npm test --workspace @margoengine/cinematic
321
+