bevy_director 0.2.0

Unreal-Sequencer-inspired cinematic camera and sequence system for Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! The viewfinder: the director's chair, without a single widget. Toggle
//! it, fly the frame you want, press K, and the key is on the timeline.
//! Scrub with the brackets, preview with P, save with Ctrl+S. Everything
//! is keyboard and mouse; the overlay (gizmos.rs) is the only readout.
//!
//! This is a dev tool: it reads raw ButtonInput and writes RON to the
//! assets directory on native builds. Games gate their own input on the
//! director's run conditions while it is up.

use bevy::{
    input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll},
    prelude::*,
    window::{CursorGrabMode, CursorOptions},
};

use crate::{
    CineCamera,
    eval::{CameraSnapshot, CompiledSequence, EvalCtx, bake},
    gizmos::{DirectorGizmoGroup, draw_playhead, draw_sequence},
    player::{DirectorPhase, DirectorState, snapshot_of},
    sequence::{FovSpec, Key, KeyInterp, Lens, Rig, ScalarKey, ScalarTrack, SequenceAsset, Shot},
};

const DEFAULT_SHOT_SECS: f32 = 5.0;
/// Capturing within this window of an existing key replaces it.
const REPLACE_WINDOW: f32 = 0.05;
/// Delete reaches this far from the camera.
const DELETE_RANGE: f32 = 2.0;
const MOUSE_SENSITIVITY: f32 = 0.0028;

/// Keybinds and the save location. Insert your own to rebind.
#[derive(Resource)]
pub struct ViewfinderConfig {
    pub toggle: KeyCode,
    pub capture: KeyCode,
    pub delete: KeyCode,
    pub play_pause: KeyCode,
    pub scrub_back: KeyCode,
    pub scrub_forward: KeyCode,
    /// Seconds per bracket tap; Shift steps a single frame (1/30).
    pub scrub_step: f32,
    pub fly_speed: f32,
    /// Where Ctrl+S writes `<name>.dir.ron`, relative to the working dir.
    pub save_dir: std::path::PathBuf,
    /// Ease stamped on captured keys.
    pub capture_ease: EaseFunction,
}

impl Default for ViewfinderConfig {
    fn default() -> Self {
        Self {
            toggle: KeyCode::Backquote,
            capture: KeyCode::KeyK,
            delete: KeyCode::Delete,
            play_pause: KeyCode::KeyP,
            scrub_back: KeyCode::BracketLeft,
            scrub_forward: KeyCode::BracketRight,
            scrub_step: 0.5,
            fly_speed: 8.0,
            save_dir: std::path::PathBuf::from("assets/sequences"),
            capture_ease: EaseFunction::SmoothStep,
        }
    }
}

/// The working take. Lives across toggles so half-built sequences are not
/// lost by ejecting; saving writes it to disk.
#[derive(Resource)]
pub struct ViewfinderSession {
    pub sequence: SequenceAsset,
    pub armed_shot: usize,
    pub playhead: f32,
    pub playing: bool,
    yaw: f32,
    pitch: f32,
    pub(crate) fov_deg: f32,
    speed: f32,
    saved_cursor: Option<(bool, CursorGrabMode)>,
    pub(crate) compiled: Option<CompiledSequence>,
}

impl Default for ViewfinderSession {
    fn default() -> Self {
        Self {
            sequence: SequenceAsset::empty("untitled"),
            armed_shot: 0,
            playhead: 0.0,
            playing: false,
            yaw: 0.0,
            pitch: 0.0,
            fov_deg: 45.0,
            speed: 8.0,
            saved_cursor: None,
            compiled: None,
        }
    }
}

impl ViewfinderSession {
    pub(crate) fn rebake(&mut self) {
        self.compiled = bake(&self.sequence).ok();
    }

    /// Capture a camera framing into the armed shot. The keyboard
    /// viewfinder and the Director's Cut editor deliberately share this
    /// path so both author exactly the same asset data.
    pub(crate) fn capture_frame(&mut self, pos: Vec3, rot: Quat, fov_deg: f32, ease: EaseFunction) {
        let playhead = self.playhead;
        if self.sequence.shots.is_empty() {
            self.sequence.shots.push(Shot {
                start: 0.0,
                duration: DEFAULT_SHOT_SECS.max(playhead),
                blend_in: None,
                rig: Rig::Keys {
                    keys: Vec::new(),
                    interp: KeyInterp::Eased,
                },
                look: Default::default(),
                lens: Lens {
                    fov: FovSpec::VerticalFovDeg(ScalarTrack { keys: Vec::new() }),
                    ..Default::default()
                },
                shake: None,
            });
            self.armed_shot = 0;
        }
        let armed = self.armed_shot.min(self.sequence.shots.len() - 1);
        self.armed_shot = armed;
        let shot = &mut self.sequence.shots[armed];
        let local = (playhead - shot.start).max(0.0);
        if local > shot.duration {
            shot.duration = local;
        }

        if let Rig::Keys { keys, .. } = &mut shot.rig {
            let key = Key {
                time: local,
                pos,
                rot: Some(rot),
                ease,
            };
            match keys
                .iter()
                .position(|key| (key.time - local).abs() <= REPLACE_WINDOW)
            {
                Some(index) => keys[index] = key,
                None => {
                    let at = keys.partition_point(|key| key.time < local);
                    keys.insert(at, key);
                }
            }
        }

        if let FovSpec::VerticalFovDeg(track) = &mut shot.lens.fov {
            let key = ScalarKey {
                time: local,
                value: fov_deg,
                ease,
            };
            match track
                .keys
                .iter()
                .position(|key| (key.time - local).abs() <= REPLACE_WINDOW)
            {
                Some(index) => track.keys[index] = key,
                None => {
                    let at = track.keys.partition_point(|key| key.time < local);
                    track.keys.insert(at, key);
                }
            }
        }
        self.rebake();
    }

    pub(crate) fn sync_pilot_from_pose(&mut self, rotation: Quat, fov_y: f32) {
        let (yaw, pitch, _) = rotation.to_euler(EulerRot::YXZ);
        self.yaw = yaw;
        self.pitch = pitch;
        self.fov_deg = fov_y.to_degrees();
    }
}

pub struct ViewfinderPlugin;

impl Plugin for ViewfinderPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<ViewfinderConfig>()
            .init_resource::<ViewfinderSession>()
            .init_gizmo_group::<DirectorGizmoGroup>()
            .add_systems(
                Update,
                (
                    toggle_viewfinder,
                    fly_camera,
                    scrub_and_preview,
                    capture_key,
                    delete_key,
                    save_session,
                    draw_overlay,
                )
                    .chain(),
            );
    }
}

fn viewfinder_up(state: &DirectorState) -> bool {
    state.phase == DirectorPhase::Viewfinder
}

/// Enter from Idle only; eject back to Idle. The cine camera keeps its
/// last pose either way, and the cursor comes back exactly as it was.
#[allow(clippy::too_many_arguments)] // a mode switch touches many doors
fn toggle_viewfinder(
    mut commands: Commands,
    keys: Res<ButtonInput<KeyCode>>,
    config: Res<ViewfinderConfig>,
    mut session: ResMut<ViewfinderSession>,
    mut state: ResMut<DirectorState>,
    // p0 reads cameras to find the live one; p1 flips is_active.
    mut cameras: ParamSet<(
        Query<
            (Entity, &Camera, &Transform, Option<&Projection>),
            (With<Camera3d>, Without<CineCamera>),
        >,
        Query<&mut Camera>,
    )>,
    cine_query: Query<Entity, With<CineCamera>>,
    mut transforms: Query<(&mut Transform, &mut Projection), With<CineCamera>>,
    mut cursor: Single<&mut CursorOptions>,
) {
    if !keys.just_pressed(config.toggle) {
        return;
    }

    if viewfinder_up(&state) {
        // Eject.
        if let Some((visible, grab)) = session.saved_cursor.take() {
            cursor.visible = visible;
            cursor.grab_mode = grab;
        }
        let mut writable = cameras.p1();
        crate::player::restore_live(&mut commands, &mut state, &mut writable);
        return;
    }
    if state.phase != DirectorPhase::Idle {
        warn!("viewfinder only opens while the director is idle");
        return;
    }

    // Take over from wherever the live camera is looking.
    let live = cameras
        .p0()
        .iter()
        .find(|(_, cam, ..)| cam.is_active)
        .map(|(e, _, t, p)| (e, snapshot_of(t, p)));
    let live_snapshot = live.map(|(_, s)| s).unwrap_or(CameraSnapshot {
        position: Vec3::new(0.0, 2.0, 8.0),
        rotation: Quat::IDENTITY,
        fov_y: 45f32.to_radians(),
    });

    // A fresh spawn carries the live pose and active flag in its bundle:
    // commands have not flushed, so a same-frame get_mut cannot reach it.
    let cine = cine_query.iter().next().unwrap_or_else(|| {
        commands
            .spawn((
                Name::new("cine camera"),
                CineCamera,
                Camera3d::default(),
                Camera {
                    is_active: true,
                    ..Default::default()
                },
                Projection::Perspective(PerspectiveProjection {
                    fov: live_snapshot.fov_y,
                    ..Default::default()
                }),
                Transform::from_translation(live_snapshot.position)
                    .with_rotation(live_snapshot.rotation),
            ))
            .id()
    });

    if let Ok((mut transform, mut projection)) = transforms.get_mut(cine) {
        transform.translation = live_snapshot.position;
        transform.rotation = live_snapshot.rotation;
        if let Projection::Perspective(p) = &mut *projection {
            p.fov = live_snapshot.fov_y;
        }
    }
    let (yaw, pitch, _) = live_snapshot.rotation.to_euler(EulerRot::YXZ);
    session.yaw = yaw;
    session.pitch = pitch;
    session.fov_deg = live_snapshot.fov_y.to_degrees();
    session.speed = config.fly_speed;
    session.playing = false;
    session.rebake();

    let mut writable = cameras.p1();
    if let Some((live_entity, _)) = live
        && let Ok(mut cam) = writable.get_mut(live_entity)
    {
        cam.is_active = false;
    }
    if let Ok(mut cam) = writable.get_mut(cine) {
        cam.is_active = true;
    }

    session.saved_cursor = Some((cursor.visible, cursor.grab_mode));
    cursor.visible = false;
    cursor.grab_mode = CursorGrabMode::Locked;

    state.phase = DirectorPhase::Viewfinder;
    state.camera = Some(cine);
    state.live_camera = live.map(|(e, _)| e);
    info!(
        "viewfinder up: fly WASD/QE, K captures, [ ] scrub, P previews, ctrl+S saves '{}'",
        session.sequence.name
    );
}

/// Free flight. Any stick input while previewing hands the camera back to
/// the pilot.
fn fly_camera(
    keys: Res<ButtonInput<KeyCode>>,
    state: Res<DirectorState>,
    mut session: ResMut<ViewfinderSession>,
    motion: Res<AccumulatedMouseMotion>,
    scroll: Res<AccumulatedMouseScroll>,
    time: Res<Time<Real>>,
    mut cine: Query<(&mut Transform, &mut Projection), With<CineCamera>>,
    #[cfg(feature = "editor")] editor: Option<Res<crate::editor::DirectorsCutState>>,
) {
    if !viewfinder_up(&state) || session.playing {
        return;
    }
    #[cfg(feature = "editor")]
    if editor.is_some_and(|editor| editor.open) {
        return;
    }
    let Some(camera) = state.camera else {
        return;
    };
    let Ok((mut transform, mut projection)) = cine.get_mut(camera) else {
        return;
    };

    let ctrl = keys.pressed(KeyCode::ControlLeft) || keys.pressed(KeyCode::ControlRight);
    if ctrl {
        // Ctrl+wheel: the lens, not the legs.
        session.fov_deg = (session.fov_deg - scroll.delta.y * 1.5).clamp(10.0, 120.0);
    } else if scroll.delta.y.abs() > 0.0 {
        session.speed = (session.speed * 1.1f32.powf(scroll.delta.y)).clamp(0.5, 200.0);
    }

    session.yaw -= motion.delta.x * MOUSE_SENSITIVITY;
    session.pitch = (session.pitch - motion.delta.y * MOUSE_SENSITIVITY).clamp(-1.54, 1.54);
    transform.rotation = Quat::from_euler(EulerRot::YXZ, session.yaw, session.pitch, 0.0);

    let mut wish = Vec3::ZERO;
    let flat_forward = transform.forward().as_vec3();
    let right = transform.right().as_vec3();
    if keys.pressed(KeyCode::KeyW) {
        wish += flat_forward;
    }
    if keys.pressed(KeyCode::KeyS) {
        wish -= flat_forward;
    }
    if keys.pressed(KeyCode::KeyD) {
        wish += right;
    }
    if keys.pressed(KeyCode::KeyA) {
        wish -= right;
    }
    if keys.pressed(KeyCode::KeyE) {
        wish += Vec3::Y;
    }
    if keys.pressed(KeyCode::KeyQ) {
        wish -= Vec3::Y;
    }
    let sprint = if keys.pressed(KeyCode::ShiftLeft) {
        3.0
    } else {
        1.0
    };
    transform.translation += wish.normalize_or_zero() * session.speed * sprint * time.delta_secs();

    if let Projection::Perspective(p) = &mut *projection {
        p.fov = session.fov_deg.to_radians();
    }
}

/// Brackets scrub, P plays the working copy in place. While scrubbing or
/// playing, the camera sits on the evaluated pose.
fn scrub_and_preview(
    keys: Res<ButtonInput<KeyCode>>,
    state: Res<DirectorState>,
    config: Res<ViewfinderConfig>,
    mut session: ResMut<ViewfinderSession>,
    motion: Res<AccumulatedMouseMotion>,
    time: Res<Time<Real>>,
    mut cine: Query<(&mut Transform, &mut Projection), With<CineCamera>>,
    #[cfg(feature = "editor")] editor: Option<Res<crate::editor::DirectorsCutState>>,
) {
    if !viewfinder_up(&state) {
        return;
    }
    let step = if keys.pressed(KeyCode::ShiftLeft) {
        1.0 / 30.0
    } else {
        config.scrub_step
    };
    let mut moved = false;
    if keys.just_pressed(config.scrub_back) {
        session.playhead = (session.playhead - step).max(0.0);
        moved = true;
    }
    if keys.just_pressed(config.scrub_forward) {
        session.playhead += step;
        moved = true;
    }
    if keys.just_pressed(config.play_pause) {
        session.playing = !session.playing;
        if session.playing && session.playhead >= session.sequence.duration() {
            session.playhead = 0.0;
        }
        moved = true;
    }
    if session.playing {
        session.playhead += time.delta_secs();
        if session.playhead >= session.sequence.duration() {
            session.playing = false;
        }
        // The pilot takes over the instant they touch the stick.
        #[cfg(feature = "editor")]
        let editor_open = editor.is_some_and(|editor| editor.open);
        #[cfg(not(feature = "editor"))]
        let editor_open = false;
        if motion.delta.length_squared() > 4.0 && !editor_open {
            session.playing = false;
            return;
        }
        moved = true;
    }
    if !moved {
        return;
    }

    let duration = session.sequence.duration();
    session.playhead = session.playhead.clamp(0.0, duration.max(0.0));
    let Some(compiled) = &session.compiled else {
        return;
    };
    let Some(camera) = state.camera else {
        return;
    };
    let Ok((mut transform, mut projection)) = cine.get_mut(camera) else {
        return;
    };
    // Preview blends from the current camera pose where a live camera
    // would be: close enough for authoring.
    let live = CameraSnapshot {
        position: transform.translation,
        rotation: transform.rotation,
        fov_y: session.fov_deg.to_radians(),
    };
    let pose = compiled.pose_at(session.playhead, &EvalCtx::still(&live));
    transform.translation = pose.position;
    transform.rotation = pose.rotation;
    if let Projection::Perspective(p) = &mut *projection {
        p.fov = pose.fov_y;
    }
    session.sync_pilot_from_pose(pose.rotation, pose.fov_y);
}

/// K: this framing, at this playhead, onto the armed shot.
fn capture_key(
    keys: Res<ButtonInput<KeyCode>>,
    state: Res<DirectorState>,
    config: Res<ViewfinderConfig>,
    mut session: ResMut<ViewfinderSession>,
    cine: Query<&Transform, With<CineCamera>>,
) {
    if !viewfinder_up(&state) || !keys.just_pressed(config.capture) {
        return;
    }
    let Some(transform) = state.camera.and_then(|e| cine.get(e).ok()) else {
        return;
    };

    let fov_deg = session.fov_deg;
    session.capture_frame(
        transform.translation,
        transform.rotation,
        fov_deg,
        config.capture_ease,
    );
    let armed = session.armed_shot;
    let local = (session.playhead - session.sequence.shots[armed].start).max(0.0);
    info!(
        "key at {:.2}s in shot {} ({} keys)",
        local,
        armed,
        key_count(&session.sequence, armed)
    );
}

fn key_count(sequence: &SequenceAsset, shot: usize) -> usize {
    match &sequence.shots[shot].rig {
        Rig::Keys { keys, .. } => keys.len(),
        _ => 0,
    }
}

/// Delete: the nearest key within reach of the camera.
fn delete_key(
    keys: Res<ButtonInput<KeyCode>>,
    state: Res<DirectorState>,
    config: Res<ViewfinderConfig>,
    mut session: ResMut<ViewfinderSession>,
    cine: Query<&Transform, With<CineCamera>>,
) {
    if !viewfinder_up(&state) || !keys.just_pressed(config.delete) {
        return;
    }
    let Some(transform) = state.camera.and_then(|e| cine.get(e).ok()) else {
        return;
    };
    let from = transform.translation;

    let mut best: Option<(usize, usize, f32)> = None;
    for (si, shot) in session.sequence.shots.iter().enumerate() {
        let Rig::Keys { keys, .. } = &shot.rig else {
            continue;
        };
        for (ki, key) in keys.iter().enumerate() {
            let d = key.pos.distance(from);
            if d <= DELETE_RANGE && best.is_none_or(|(_, _, bd)| d < bd) {
                best = Some((si, ki, d));
            }
        }
    }
    let Some((si, ki, _)) = best else {
        info!("no key within {DELETE_RANGE} m to delete");
        return;
    };
    let Rig::Keys { keys, .. } = &mut session.sequence.shots[si].rig else {
        return;
    };
    let removed = keys.remove(ki);
    session.rebake();
    info!("removed key at {:.2}s from shot {si}", removed.time);
}

/// Ctrl+S: the working take to disk, where the asset server reads.
fn save_session(
    keys: Res<ButtonInput<KeyCode>>,
    state: Res<DirectorState>,
    config: Res<ViewfinderConfig>,
    session: Res<ViewfinderSession>,
) {
    if !viewfinder_up(&state) || !keys.just_pressed(KeyCode::KeyS) {
        return;
    }
    if !(keys.pressed(KeyCode::ControlLeft) || keys.pressed(KeyCode::ControlRight)) {
        return;
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        let path = config
            .save_dir
            .join(format!("{}.dir.ron", session.sequence.name));
        match crate::loader::save_sequence(&session.sequence, &path) {
            Ok(()) => info!("saved {}", path.display()),
            Err(err) => error!("could not save sequence: {err}"),
        }
    }
    #[cfg(target_arch = "wasm32")]
    warn!("saving sequences is native-only");
}

/// The whole overlay: paths, keys, aim rays, and the playhead ghost.
fn draw_overlay(
    state: Res<DirectorState>,
    session: Res<ViewfinderSession>,
    mut gizmos: Gizmos<DirectorGizmoGroup>,
) {
    if !viewfinder_up(&state) {
        return;
    }
    draw_sequence(&mut gizmos, &session.sequence);
    if let Some(compiled) = &session.compiled {
        let live = CameraSnapshot {
            position: Vec3::ZERO,
            rotation: Quat::IDENTITY,
            fov_y: 45f32.to_radians(),
        };
        let pose = compiled.pose_at(session.playhead, &EvalCtx::still(&live));
        draw_playhead(&mut gizmos, pose.position, pose.rotation);
    }
}