bevy_lagrange 0.0.3

Bevy camera controller with pan, orbit, zoom-to-fit, queued animations, and trackpad support
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! Observers that wire events to camera behavior.

use std::collections::VecDeque;
use std::time::Duration;

use bevy::math::curve::easing::EaseFunction;
use bevy::prelude::*;
use bevy_kana::Displacement;
use bevy_kana::Position;

use super::ForceUpdate;
use super::OrbitCam;
use super::animation;
use super::animation::CameraMove;
use super::animation::CameraMoveList;
use super::components::AnimationConflictPolicy;
use super::components::AnimationSourceMarker;
use super::components::CameraInputInterruptBehavior;
use super::components::CurrentFitTarget;
use super::components::OrbitCamStash;
use super::components::ZoomAnimationMarker;
use super::events::AnimateToFit;
use super::events::AnimationBegin;
use super::events::AnimationCancelled;
use super::events::AnimationEnd;
use super::events::AnimationRejected;
use super::events::AnimationSource;
use super::events::LookAt;
use super::events::LookAtAndZoomToFit;
use super::events::PlayAnimation;
use super::events::SetFitTarget;
use super::events::ZoomBegin;
use super::events::ZoomCancelled;
use super::events::ZoomContext;
use super::events::ZoomEnd;
use super::events::ZoomToFit;
use super::fit;
use super::support;

/// Parameters for an instant orbital snap.
struct SnapOrbit {
    focus:  Position,
    yaw:    Option<f32>,
    pitch:  Option<f32>,
    radius: f32,
}

/// Snaps the camera to an orbital position instantly (no animation) and fires
/// caller-provided lifecycle events via `emit_events`.
fn snap_to_orbit(
    commands: &mut Commands,
    orbit_cam: &mut OrbitCam,
    snap: SnapOrbit,
    emit_events: impl FnOnce(&mut Commands),
) {
    orbit_cam.focus = *snap.focus;
    orbit_cam.radius = Some(snap.radius);
    orbit_cam.target_focus = *snap.focus;
    orbit_cam.target_radius = snap.radius;
    if let Some(yaw) = snap.yaw {
        orbit_cam.yaw = Some(yaw);
        orbit_cam.target_yaw = yaw;
    }
    if let Some(pitch) = snap.pitch {
        orbit_cam.pitch = Some(pitch);
        orbit_cam.target_pitch = pitch;
    }
    orbit_cam.force_update = ForceUpdate::Pending;

    emit_events(commands);
}

/// Ensures camera runtime state is stashed once and animation overrides are applied.
fn stash_camera_state(
    commands: &mut Commands,
    entity: Entity,
    camera: &mut OrbitCam,
    has_existing_stash: bool,
    interrupt_behavior: CameraInputInterruptBehavior,
) {
    if !has_existing_stash {
        let stash = OrbitCamStash {
            zoom:    camera.zoom_smoothness,
            pan:     camera.pan_smoothness,
            orbit:   camera.orbit_smoothness,
            control: camera.input_control,
        };
        commands.entity(entity).insert(stash);
    }

    camera.zoom_smoothness = 0.0;
    camera.pan_smoothness = 0.0;
    camera.orbit_smoothness = 0.0;

    if interrupt_behavior == CameraInputInterruptBehavior::Ignore {
        camera.input_control = None;
    }
}

/// Parameters for a fit calculation request.
struct FitRequest<'a> {
    context:    &'a str,
    target:     Entity,
    yaw:        f32,
    pitch:      f32,
    margin:     f32,
    projection: &'a Projection,
    camera:     &'a Camera,
}

/// Shared fit preparation used by both `ZoomToFit` and `AnimateToFit` observers.
/// Extracts target mesh vertices and computes the fit solution for the requested
/// camera orientation.
fn prepare_fit_for_target(
    req: &FitRequest,
    mesh_query: &Query<&Mesh3d>,
    children_query: &Query<&Children>,
    global_transform_query: &Query<&GlobalTransform>,
    meshes: &Assets<Mesh>,
) -> Option<fit::FitSolution> {
    let context = req.context;
    let target = req.target;
    let Some((vertices, geometric_center)) = support::extract_mesh_vertices(
        target,
        children_query,
        mesh_query,
        global_transform_query,
        meshes,
    ) else {
        warn!("{context}: Failed to extract mesh vertices for entity {target:?}");
        return None;
    };

    let Ok(fit) = fit::calculate_fit(
        &vertices,
        geometric_center,
        req.yaw,
        req.pitch,
        req.margin,
        req.projection,
        req.camera,
    )
    .inspect_err(|error| {
        warn!("{context}: Failed to calculate fit for entity {target:?}: {error}");
    }) else {
        return None;
    };

    Some(fit)
}

/// Observer for `ZoomToFit` event - frames a target entity in the camera view.
/// When duration is `Duration::ZERO`, snaps instantly.
/// When duration is greater than zero, animates smoothly via [`PlayAnimation`]
/// with a [`ZoomContext`] so that `on_play_animation` handles all conflict
/// resolution and zoom lifecycle events in one place.
/// Requires target entity to have a `Mesh3d` (direct or on descendants).
pub(crate) fn on_zoom_to_fit(
    zoom: On<ZoomToFit>,
    mut commands: Commands,
    mut camera_query: Query<(&mut OrbitCam, &Projection, &Camera)>,
    mesh_query: Query<&Mesh3d>,
    children_query: Query<&Children>,
    global_transform_query: Query<&GlobalTransform>,
    meshes: Res<Assets<Mesh>>,
) {
    let camera = zoom.camera;
    let target = zoom.target;
    let margin = zoom.margin;
    let duration = zoom.duration;
    let easing = zoom.easing;

    let Ok((mut orbit_cam, projection, camera_component)) = camera_query.get_mut(camera) else {
        return;
    };

    debug!(
        "ZoomToFit: yaw={:.3} pitch={:.3} current_focus={:.1?} current_radius={:.1} duration_ms={:.0}",
        orbit_cam.target_yaw,
        orbit_cam.target_pitch,
        orbit_cam.target_focus,
        orbit_cam.target_radius,
        duration.as_secs_f32() * 1000.0,
    );

    let Some(fit) = prepare_fit_for_target(
        &FitRequest {
            context: "ZoomToFit",
            target,
            yaw: orbit_cam.target_yaw,
            pitch: orbit_cam.target_pitch,
            margin,
            projection,
            camera: camera_component,
        },
        &mesh_query,
        &children_query,
        &global_transform_query,
        &meshes,
    ) else {
        return;
    };

    if duration > Duration::ZERO {
        // Animated path: use `ToOrbit` to pass orbital params directly, avoiding
        // gimbal lock from atan2 decomposition at extreme pitch angles.
        let camera_moves = VecDeque::from([CameraMove::ToOrbit {
            focus: *fit.focus,
            yaw: orbit_cam.target_yaw,
            pitch: orbit_cam.target_pitch,
            radius: fit.radius,
            duration,
            easing,
        }]);

        let ctx = ZoomContext {
            target,
            margin,
            duration,
            easing,
        };

        // `on_play_animation` handles conflict resolution, `ZoomBegin`, and
        // `ZoomAnimationMarker` insertion — all in one place after acceptance.
        commands.trigger(PlayAnimation::new(camera, camera_moves).zoom_context(ctx));
    } else {
        // Instant path: snap directly to target — no `PlayAnimation` involved.
        snap_to_orbit(
            &mut commands,
            &mut orbit_cam,
            SnapOrbit {
                focus:  fit.focus,
                yaw:    None,
                pitch:  None,
                radius: fit.radius,
            },
            |commands| {
                commands.trigger(ZoomBegin {
                    camera,
                    target,
                    margin,
                    duration,
                    easing,
                });
                commands.trigger(ZoomEnd {
                    camera,
                    target,
                    margin,
                    duration: Duration::ZERO,
                    easing,
                });
            },
        );
    }

    // Route fit target updates through a single lifecycle owner.
    commands.trigger(SetFitTarget::new(camera, target));
}

/// Fires `ZoomBegin` and inserts `ZoomAnimationMarker` when the accepted
/// animation carries zoom context.
fn begin_zoom_if_needed(
    commands: &mut Commands,
    entity: Entity,
    zoom_context: Option<&ZoomContext>,
) {
    if let Some(ctx) = zoom_context {
        commands.trigger(ZoomBegin {
            camera:   entity,
            target:   ctx.target,
            margin:   ctx.margin,
            duration: ctx.duration,
            easing:   ctx.easing,
        });
        commands
            .entity(entity)
            .insert(ZoomAnimationMarker(ctx.clone()));
    }
}

/// Observer for `PlayAnimation` event - initiates camera animation sequence.
/// This is the single decision point for all trigger-time logic: conflict
/// resolution, zoom lifecycle (`ZoomBegin` / `ZoomAnimationMarker`), and
/// animation begin.
pub(crate) fn on_play_animation(
    start: On<PlayAnimation>,
    mut commands: Commands,
    mut camera_query: Query<(
        &mut OrbitCam,
        Option<&OrbitCamStash>,
        Option<&CameraInputInterruptBehavior>,
        Option<&AnimationConflictPolicy>,
    )>,
    move_list_query: Query<&CameraMoveList>,
    marker_query: Query<&ZoomAnimationMarker>,
    source_marker_query: Query<&AnimationSourceMarker>,
) {
    let entity = start.camera;
    let zoom_context = start.zoom_context.clone();
    let source = if zoom_context.is_some() {
        AnimationSource::ZoomToFit
    } else {
        start.source
    };

    let Ok((mut camera, existing_stash, interrupt_behavior, conflict_policy)) =
        camera_query.get_mut(entity)
    else {
        return;
    };

    let interrupt_behavior = interrupt_behavior.copied().unwrap_or_default();
    let policy = conflict_policy.copied().unwrap_or_default();
    let has_in_flight = move_list_query.get(entity).is_ok();

    if has_in_flight {
        match policy {
            AnimationConflictPolicy::FirstWins => {
                commands.trigger(AnimationRejected {
                    camera: entity,
                    source,
                });
                return;
            },
            AnimationConflictPolicy::LastWins => {
                // Cancel in-flight animation — read source from existing marker
                let in_flight_source = source_marker_query
                    .get(entity)
                    .map_or(AnimationSource::PlayAnimation, |m| m.0);
                if let Ok(queue) = move_list_query.get(entity) {
                    let camera_move =
                        queue
                            .camera_moves
                            .front()
                            .cloned()
                            .unwrap_or(CameraMove::ToOrbit {
                                focus:    Vec3::ZERO,
                                yaw:      0.0,
                                pitch:    0.0,
                                radius:   1.0,
                                duration: Duration::ZERO,
                                easing:   EaseFunction::Linear,
                            });
                    commands.trigger(AnimationCancelled {
                        camera: entity,
                        source: in_flight_source,
                        camera_move,
                    });
                }
                // Cancel in-flight zoom if present
                if let Ok(marker) = marker_query.get(entity) {
                    commands.entity(entity).remove::<ZoomAnimationMarker>();
                    commands.trigger(ZoomCancelled {
                        camera:   entity,
                        target:   marker.0.target,
                        margin:   marker.0.margin,
                        duration: marker.0.duration,
                        easing:   marker.0.easing,
                    });
                }
            },
        }
    }

    // Zoom lifecycle fires here — after conflict resolution has passed.
    // No command-ordering hazard since everything happens in the same observer.
    begin_zoom_if_needed(&mut commands, entity, zoom_context.as_ref());

    commands.trigger(AnimationBegin {
        camera: entity,
        source,
    });

    stash_camera_state(
        &mut commands,
        entity,
        &mut camera,
        existing_stash.is_some(),
        interrupt_behavior,
    );

    commands
        .entity(entity)
        .insert(CameraMoveList::new(start.camera_moves.clone()));
    commands
        .entity(entity)
        .insert(AnimationSourceMarker(source));
}

/// Observer for direct `CameraMoveList` insertion (bypassing `PlayAnimation`).
/// Reuses the same camera-state stashing behavior as the event-driven path.
pub(crate) fn on_camera_move_list_added(
    add: On<Add, CameraMoveList>,
    mut commands: Commands,
    mut camera_query: Query<(
        &mut OrbitCam,
        Option<&OrbitCamStash>,
        Option<&CameraInputInterruptBehavior>,
    )>,
) {
    let entity = add.entity;
    let Ok((mut camera, existing_stash, interrupt_behavior)) = camera_query.get_mut(entity) else {
        return;
    };
    let interrupt_behavior = interrupt_behavior.copied().unwrap_or_default();

    stash_camera_state(
        &mut commands,
        entity,
        &mut camera,
        existing_stash.is_some(),
        interrupt_behavior,
    );
}

/// Observer for `SetFitTarget` event - sets the target entity for fit debug overlay.
pub(crate) fn on_set_fit_target(set_target: On<SetFitTarget>, mut commands: Commands) {
    commands
        .entity(set_target.camera)
        .insert(CurrentFitTarget(set_target.target));
}

/// Observer for `AnimateToFit` event - animates the camera to a specific orientation
/// while fitting a target entity in view.
pub(crate) fn on_animate_to_fit(
    event: On<AnimateToFit>,
    mut commands: Commands,
    mut camera_query: Query<(&mut OrbitCam, &Projection, &Camera)>,
    mesh_query: Query<&Mesh3d>,
    children_query: Query<&Children>,
    global_transform_query: Query<&GlobalTransform>,
    meshes: Res<Assets<Mesh>>,
) {
    let camera = event.camera;
    let target = event.target;
    let yaw = event.yaw;
    let pitch = event.pitch;
    let margin = event.margin;
    let duration = event.duration;
    let easing = event.easing;

    let Ok((mut orbit_cam, projection, camera_component)) = camera_query.get_mut(camera) else {
        return;
    };

    let Some(fit) = prepare_fit_for_target(
        &FitRequest {
            context: "AnimateToFit",
            target,
            yaw,
            pitch,
            margin,
            projection,
            camera: camera_component,
        },
        &mesh_query,
        &children_query,
        &global_transform_query,
        &meshes,
    ) else {
        return;
    };

    if duration > Duration::ZERO {
        let camera_moves = VecDeque::from([CameraMove::ToOrbit {
            focus: *fit.focus,
            yaw,
            pitch,
            radius: fit.radius,
            duration,
            easing,
        }]);
        commands.trigger(
            PlayAnimation::new(camera, camera_moves).source(AnimationSource::AnimateToFit),
        );
    } else {
        snap_to_orbit(
            &mut commands,
            &mut orbit_cam,
            SnapOrbit {
                focus:  fit.focus,
                yaw:    Some(yaw),
                pitch:  Some(pitch),
                radius: fit.radius,
            },
            |commands| {
                let source = AnimationSource::AnimateToFit;
                commands.trigger(AnimationBegin { camera, source });
                commands.trigger(AnimationEnd { camera, source });
            },
        );
    }
    // Route fit target updates through a single lifecycle owner.
    commands.trigger(SetFitTarget::new(camera, target));
}

/// Observer for `LookAt` event — rotates the camera in place to look at a target entity.
/// The camera stays at its current world position; only the orbit pivot re-anchors.
pub(crate) fn on_look_at(
    event: On<LookAt>,
    mut commands: Commands,
    mut camera_query: Query<(&mut OrbitCam, &GlobalTransform)>,
    global_transform_query: Query<&GlobalTransform>,
) {
    let camera = event.camera;
    let target = event.target;
    let duration = event.duration;
    let easing = event.easing;

    let Ok((mut orbit_cam, camera_transform)) = camera_query.get_mut(camera) else {
        return;
    };

    let Ok(target_transform) = global_transform_query.get(target) else {
        warn!("LookAt: target {target:?} has no GlobalTransform");
        return;
    };

    let camera_pos = camera_transform.translation();
    let target_pos = target_transform.translation();

    if duration > Duration::ZERO {
        commands.trigger(
            PlayAnimation::new(
                camera,
                [CameraMove::ToPosition {
                    translation: camera_pos,
                    focus: target_pos,
                    duration,
                    easing,
                }],
            )
            .source(AnimationSource::LookAt),
        );
    } else {
        // Instant path: back-solve orbital params and snap
        let (yaw, pitch, radius) =
            animation::orbital_params_from_offset(Displacement(camera_pos - target_pos));
        snap_to_orbit(
            &mut commands,
            &mut orbit_cam,
            SnapOrbit {
                focus: Position(target_pos),
                yaw: Some(yaw),
                pitch: Some(pitch),
                radius,
            },
            |commands| {
                let source = AnimationSource::LookAt;
                commands.trigger(AnimationBegin { camera, source });
                commands.trigger(AnimationEnd { camera, source });
            },
        );
    }
}

/// Observer for `LookAtAndZoomToFit` event — rotates the camera in place to look at
/// a target entity and adjusts the radius to frame it, all in one fluid motion.
/// The yaw and pitch are back-solved from the camera's current world position.
pub(crate) fn on_look_at_and_zoom_to_fit(
    event: On<LookAtAndZoomToFit>,
    mut commands: Commands,
    mut camera_query: Query<(&mut OrbitCam, &Projection, &Camera, &GlobalTransform)>,
    mesh_query: Query<&Mesh3d>,
    children_query: Query<&Children>,
    global_transform_query: Query<&GlobalTransform>,
    meshes: Res<Assets<Mesh>>,
) {
    let camera = event.camera;
    let target = event.target;
    let margin = event.margin;
    let duration = event.duration;
    let easing = event.easing;

    let Ok((mut orbit_cam, projection, camera_component, camera_transform)) =
        camera_query.get_mut(camera)
    else {
        return;
    };

    let camera_pos = camera_transform.translation();

    // Back-solve yaw/pitch from camera's current position relative to the target.
    // We need the target's bounds center for this, so we run the fit calculation
    // with a preliminary yaw/pitch, then refine.
    let Ok(target_gt) = global_transform_query.get(target) else {
        warn!("LookAtAndZoomToFit: target {target:?} has no GlobalTransform");
        return;
    };
    let target_pos = target_gt.translation();
    let (preliminary_yaw, preliminary_pitch, _) =
        animation::orbital_params_from_offset(Displacement(camera_pos - target_pos));

    let Some(fit) = prepare_fit_for_target(
        &FitRequest {
            context: "LookAtAndZoomToFit",
            target,
            yaw: preliminary_yaw,
            pitch: preliminary_pitch,
            margin,
            projection,
            camera: camera_component,
        },
        &mesh_query,
        &children_query,
        &global_transform_query,
        &meshes,
    ) else {
        return;
    };

    // Recompute yaw/pitch relative to the fit's focus (bounds center), which may
    // differ slightly from the raw `GlobalTransform` translation.
    let (yaw, pitch, _) =
        animation::orbital_params_from_offset(Displacement(camera_pos - *fit.focus));

    if duration > Duration::ZERO {
        commands.trigger(
            PlayAnimation::new(
                camera,
                [CameraMove::ToOrbit {
                    focus: *fit.focus,
                    yaw,
                    pitch,
                    radius: fit.radius,
                    duration,
                    easing,
                }],
            )
            .source(AnimationSource::LookAtAndZoomToFit),
        );
    } else {
        snap_to_orbit(
            &mut commands,
            &mut orbit_cam,
            SnapOrbit {
                focus:  fit.focus,
                yaw:    Some(yaw),
                pitch:  Some(pitch),
                radius: fit.radius,
            },
            |commands| {
                let source = AnimationSource::LookAtAndZoomToFit;
                commands.trigger(AnimationBegin { camera, source });
                commands.trigger(AnimationEnd { camera, source });
            },
        );
    }

    commands.trigger(SetFitTarget::new(camera, target));
}

/// Observer that restores camera runtime state when `CameraMoveList` is removed.
pub(crate) fn restore_camera_state(
    remove: On<Remove, CameraMoveList>,
    mut commands: Commands,
    mut query: Query<(&OrbitCamStash, &mut OrbitCam)>,
) {
    let entity = remove.entity;

    let Ok((stash, mut camera)) = query.get_mut(entity) else {
        return;
    };

    camera.zoom_smoothness = stash.zoom;
    camera.pan_smoothness = stash.pan;
    camera.orbit_smoothness = stash.orbit;
    camera.input_control = stash.control;

    commands.entity(entity).remove::<OrbitCamStash>();
}