1use crate::{Camera, LookAngles};
7use viewport_lib_types::camera::{CameraTarget, Pose};
8
9use crate::input::action::Action;
10use crate::input::action_frame::ActionFrame;
11use crate::input::context::ViewportContext;
12use crate::input::event::ViewportEvent;
13use crate::input::mode::NavigationMode;
14use crate::input::preset::{BindingPreset, preset_bindings};
15use crate::input::viewport_binding::ViewportBinding;
16use crate::input::viewport_input::ViewportInput;
17
18use super::movement::wish_from_actions;
19
20pub struct OrbitCameraController {
67 input: ViewportInput,
68 pub navigation_mode: NavigationMode,
72 pub fly_speed: f32,
78 pub fly_boost: f32,
82 pub orbit_sensitivity: f32,
84 pub zoom_sensitivity: f32,
86 pub gesture_sensitivity: f32,
90 viewport_size: [f32; 2],
92 pivot: Option<CameraTarget>,
94 written: Option<(Pose, f32)>,
97}
98
99impl OrbitCameraController {
100 pub const DEFAULT_ORBIT_SENSITIVITY: f32 = 0.005;
102 pub const DEFAULT_ZOOM_SENSITIVITY: f32 = 0.001;
104 pub const DEFAULT_GESTURE_SENSITIVITY: f32 = 1.0;
106 pub const DEFAULT_FLY_SPEED: f32 = 6.0;
108 pub const DEFAULT_FLY_BOOST: f32 = 3.0;
110
111 pub fn new_stateless() -> Self {
118 Self::from_bindings(Vec::new())
119 }
120
121 pub fn new(preset: BindingPreset) -> Self {
130 Self::from_bindings(preset_bindings(preset))
131 }
132
133 fn from_bindings(bindings: Vec<ViewportBinding>) -> Self {
134 Self {
135 input: ViewportInput::new(bindings),
136 navigation_mode: NavigationMode::Arcball,
137 fly_speed: Self::DEFAULT_FLY_SPEED,
138 fly_boost: Self::DEFAULT_FLY_BOOST,
139 orbit_sensitivity: Self::DEFAULT_ORBIT_SENSITIVITY,
140 zoom_sensitivity: Self::DEFAULT_ZOOM_SENSITIVITY,
141 gesture_sensitivity: Self::DEFAULT_GESTURE_SENSITIVITY,
142 viewport_size: [1.0, 1.0],
143 pivot: None,
144 written: None,
145 }
146 }
147
148 pub fn viewer() -> Self {
153 Self::new(BindingPreset::Viewer)
154 }
155
156 #[deprecated(
158 note = "renamed: use OrbitCameraController::viewer, or new_stateless if the host owns the resolver"
159 )]
160 pub fn viewport_primitives() -> Self {
161 Self::new(BindingPreset::Viewer)
162 }
163
164 #[deprecated(
167 note = "renamed: use OrbitCameraController::new_stateless if a session or host owns the resolver, or new(BindingPreset::Default) for the standalone path"
168 )]
169 pub fn viewport_all() -> Self {
170 Self::new(BindingPreset::Default)
171 }
172
173 pub fn begin_frame(&mut self, ctx: ViewportContext) {
182 self.viewport_size = ctx.viewport_size;
183 self.input.begin_frame(ctx);
184 }
185
186 pub fn set_viewport_size(&mut self, viewport_size: [f32; 2]) {
190 self.viewport_size = viewport_size;
191 }
192
193 #[deprecated(
200 note = "own a ViewportInput and use OrbitCameraController::apply(&mut camera, &frame, dt)"
201 )]
202 pub fn push_event(&mut self, event: ViewportEvent) {
203 self.input.push_event(event);
204 }
205
206 pub fn resolve(&self) -> ActionFrame {
213 self.input.resolve()
214 }
215
216 #[deprecated(
231 note = "own a ViewportInput and use OrbitCameraController::apply(&mut camera, &frame, dt)"
232 )]
233 pub fn apply_to_camera(&mut self, camera: &mut Camera) -> ActionFrame {
234 let frame = self.input.resolve();
235 self.apply(camera, &frame, 1.0 / 60.0);
236 frame
237 }
238
239 pub fn orbit_by(&mut self, camera: &mut Camera, delta: glam::Vec2) {
248 if delta == glam::Vec2::ZERO {
249 return;
250 }
251 let mut target = self.pivot(camera);
252 self.orbit_target_by(&mut target, delta);
253 self.write(camera, target);
254 }
255
256 pub fn target(&self) -> Option<CameraTarget> {
259 self.pivot
260 }
261
262 pub fn sync_from_camera(&mut self, camera: &Camera) {
265 self.pivot = Some(camera.orbit_target());
266 self.written = Some((camera.pose, camera.focus_distance()));
267 }
268
269 fn pivot(&mut self, camera: &Camera) -> CameraTarget {
272 let current = (camera.pose, camera.focus_distance());
273 match self.pivot {
274 Some(pivot) if self.written == Some(current) => pivot,
275 _ => {
276 self.sync_from_camera(camera);
277 camera.orbit_target()
278 }
279 }
280 }
281
282 fn write(&mut self, camera: &mut Camera, target: CameraTarget) {
283 camera.set_orbit_target(target);
284 self.pivot = Some(target);
285 self.written = Some((camera.pose, camera.focus_distance()));
286 }
287
288 fn orbit_target_by(&self, target: &mut CameraTarget, delta: glam::Vec2) {
289 if delta == glam::Vec2::ZERO {
290 return;
291 }
292 let yaw = delta.x * self.orbit_sensitivity;
293 let pitch = delta.y * self.orbit_sensitivity;
294 orbit_in_mode(target, self.navigation_mode, yaw, pitch);
295 }
296
297 pub fn apply(&mut self, camera: &mut Camera, frame: &ActionFrame, dt: f32) {
314 let nav = &frame.navigation;
315 let h = self.viewport_size[1];
316 let start = self.pivot(camera);
317 let mut t = start;
318 let gesture = nav.twist * self.gesture_sensitivity;
319 let pan = |t: &mut CameraTarget| {
320 if nav.pan != glam::Vec2::ZERO {
321 let scale = camera.view_height_at(t.distance) / h.max(1.0);
322 t.pan_world(nav.pan.x * scale, nav.pan.y * scale);
323 }
324 };
325 let zoom = |t: &mut CameraTarget| {
326 if nav.zoom != 0.0 {
327 t.zoom_by_factor(1.0 - nav.zoom * self.zoom_sensitivity);
328 }
329 };
330
331 match self.navigation_mode {
332 NavigationMode::Arcball => {
333 self.orbit_target_by(&mut t, nav.orbit);
334 if gesture != 0.0 {
335 t.orbit(gesture, 0.0);
336 }
337 pan(&mut t);
338 zoom(&mut t);
339 }
340
341 NavigationMode::Turntable => {
342 self.orbit_target_by(&mut t, nav.orbit);
343 if gesture != 0.0 {
344 apply_turntable(&mut t, gesture, 0.0);
346 }
347 pan(&mut t);
348 zoom(&mut t);
349 }
350
351 NavigationMode::Planar => {
352 pan(&mut t);
354 zoom(&mut t);
355 }
356
357 NavigationMode::Fly => {
358 self.orbit_target_by(&mut t, nav.orbit);
360 if gesture != 0.0 {
361 apply_fly_look(&mut t, gesture, 0.0);
362 }
363
364 let q = t.orientation;
366 let forward = -(q * glam::Vec3::Z);
367 let wish = wish_from_actions(frame, forward, q * glam::Vec3::X, q * glam::Vec3::Y);
368 let speed = if frame.is_active(Action::FlySpeedBoost) {
369 self.fly_speed * self.fly_boost
370 } else {
371 self.fly_speed
372 };
373 t.centre += (wish * speed * dt).as_dvec3();
375 }
376
377 _ => {}
379 }
380
381 if t != start {
382 self.write(camera, t);
383 }
384 }
385}
386
387const POLE_LIMIT: f32 = 89.0 * std::f32::consts::PI / 180.0;
394
395pub(crate) fn orbit_in_mode(target: &mut CameraTarget, mode: NavigationMode, yaw: f32, pitch: f32) {
402 match mode {
403 NavigationMode::Arcball => target.orbit(yaw, pitch),
404 NavigationMode::Turntable => apply_turntable(target, yaw, pitch),
405 NavigationMode::Fly => apply_fly_look(target, yaw, pitch),
406 _ => {}
408 }
409}
410
411fn apply_turntable(view: &mut CameraTarget, yaw: f32, pitch: f32) {
419 if yaw != 0.0 {
421 view.orientation = (glam::Quat::from_rotation_z(-yaw) * view.orientation).normalize();
422 }
423
424 if pitch != 0.0 {
425 let elevation = |q: glam::Quat| (q * glam::Vec3::Z).z.clamp(-1.0, 1.0).asin();
428 let pitched =
429 |amount: f32| (view.orientation * glam::Quat::from_rotation_x(-amount)).normalize();
430
431 const PROBE: f32 = 1e-3;
436 let current = elevation(view.orientation);
437 let rate = (elevation(pitched(PROBE)) - current) / PROBE;
438 if rate.abs() < 1e-3 {
439 view.orientation = pitched(pitch);
441 return;
442 }
443
444 let target = current + rate * pitch;
445 if target.abs() <= POLE_LIMIT {
446 view.orientation = pitched(pitch);
447 } else if target.abs() > current.abs() && current.abs() >= POLE_LIMIT {
448 } else {
450 view.orientation = pitched((POLE_LIMIT.copysign(target) - current) / rate);
451 }
452 }
453}
454
455fn apply_fly_look(view: &mut CameraTarget, yaw: f32, pitch: f32) {
461 let eye = view.eye();
462 let look = LookAngles::from_orientation(view.orientation)
464 .turned(yaw, -pitch)
465 .with_pitch_clamped(-POLE_LIMIT, POLE_LIMIT);
466 view.orientation = look.orientation();
467 view.centre = eye + (look.direction() * view.distance).as_dvec3();
468}
469
470#[cfg(test)]
471mod tests {
472 use super::*;
473 use crate::input::binding::KeyCode;
474 use glam::DVec3;
475
476 fn camera_facing(orientation: glam::Quat) -> Camera {
477 Camera::orbit(DVec3::ZERO, 5.0, orientation)
478 }
479
480 fn default_target() -> CameraTarget {
481 Camera::default().orbit_target()
482 }
483 use crate::input::event::{ButtonState, ScrollUnits, ViewportEvent};
484
485 fn make_ctx() -> ViewportContext {
486 ViewportContext::new(crate::input::InputOwnership::full_window(), [800.0, 600.0])
487 }
488
489 #[test]
490 fn new_defaults() {
491 let ctrl = OrbitCameraController::viewport_primitives();
492 assert_eq!(ctrl.navigation_mode, NavigationMode::Arcball);
493 assert!((ctrl.fly_speed - OrbitCameraController::DEFAULT_FLY_SPEED).abs() < 1e-6);
494 assert!(
495 (ctrl.orbit_sensitivity - OrbitCameraController::DEFAULT_ORBIT_SENSITIVITY).abs()
496 < 1e-6
497 );
498 }
499
500 #[test]
501 fn resolve_no_events_zero_nav() {
502 let mut ctrl = OrbitCameraController::new(BindingPreset::Default);
503 ctrl.begin_frame(make_ctx());
504 let frame = ctrl.resolve();
505 assert_eq!(frame.navigation.orbit, glam::Vec2::ZERO);
506 assert_eq!(frame.navigation.pan, glam::Vec2::ZERO);
507 assert_eq!(frame.navigation.zoom, 0.0);
508 }
509
510 #[test]
511 fn apply_zoom_changes_distance() {
512 let mut ctrl = OrbitCameraController::viewport_primitives();
513 ctrl.begin_frame(make_ctx());
514 let mut cam = Camera::default();
515 let d0 = cam.focus_distance();
516 ctrl.push_event(ViewportEvent::Wheel {
517 delta: glam::Vec2::new(0.0, 100.0),
518 units: ScrollUnits::Pixels,
519 });
520 ctrl.apply_to_camera(&mut cam);
521 assert!(
522 (cam.focus_distance() - d0).abs() > 1e-4,
523 "zoom should change camera distance"
524 );
525 }
526
527 #[test]
528 fn orbit_by_matches_a_drag_in_every_mode() {
529 let delta = glam::Vec2::new(37.0, -21.0);
530 let mut frame = ActionFrame::default();
531 frame.navigation.orbit = delta;
532 let start =
533 || camera_facing(glam::Quat::from_rotation_z(0.7) * glam::Quat::from_rotation_x(0.9));
534 for mode in [
535 NavigationMode::Arcball,
536 NavigationMode::Turntable,
537 NavigationMode::Fly,
538 NavigationMode::Planar,
539 ] {
540 let mut ctrl = OrbitCameraController::viewer();
541 ctrl.navigation_mode = mode;
542 let mut by_drag = start();
543 ctrl.apply(&mut by_drag, &frame, 1.0 / 60.0);
544 let mut by_call = start();
545 ctrl.orbit_by(&mut by_call, delta);
546 assert!(
547 by_drag.orientation().angle_between(by_call.orientation()) < 1e-5,
548 "{mode:?}: orientation differs"
549 );
550 assert!(
551 (by_drag.target() - by_call.target()).length() < 1e-4,
552 "{mode:?}: centre differs"
553 );
554 match mode {
555 NavigationMode::Planar => assert_eq!(by_call.orientation(), start().orientation()),
556 NavigationMode::Fly => {
559 assert!((by_call.target() - start().target()).length() > 1e-3)
560 }
561 _ => assert!(by_call.orientation().angle_between(start().orientation()) > 1e-3),
562 }
563 }
564 }
565
566 #[test]
567 fn planar_mode_ignores_orbit() {
568 let mut ctrl = OrbitCameraController::viewport_primitives();
569 ctrl.navigation_mode = NavigationMode::Planar;
570 ctrl.begin_frame(make_ctx());
571 let mut cam = Camera::default();
572 let orient_before = cam.orientation();
573 ctrl.push_event(ViewportEvent::PointerMoved {
575 position: glam::Vec2::new(100.0, 100.0),
576 });
577 ctrl.push_event(ViewportEvent::MouseButton {
578 button: crate::input::binding::MouseButton::Left,
579 state: ButtonState::Pressed,
580 });
581 ctrl.push_event(ViewportEvent::PointerMoved {
582 position: glam::Vec2::new(200.0, 200.0),
583 });
584 ctrl.apply_to_camera(&mut cam);
585 let after = cam.orientation();
586 assert!(
587 (after.x - orient_before.x).abs() < 1e-6
588 && (after.y - orient_before.y).abs() < 1e-6
589 && (after.z - orient_before.z).abs() < 1e-6
590 && (after.w - orient_before.w).abs() < 1e-6,
591 "planar mode should not change orientation"
592 );
593 }
594
595 #[test]
596 fn turntable_pitch_clamped() {
597 let mut cam = default_target();
598 for _ in 0..1000 {
600 apply_turntable(&mut cam, 0.0, 0.1);
601 }
602 let eye_z = (cam.orientation * glam::Vec3::Z).z;
604 let max_sin = 89.0_f32.to_radians().sin();
605 assert!(
606 eye_z.abs() <= max_sin + 1e-4,
607 "turntable pitch should be clamped: eye_z={eye_z}"
608 );
609 }
610
611 #[test]
612 fn fly_look_preserves_eye() {
613 let mut cam = default_target();
614 let eye_before = cam.eye();
615 apply_fly_look(&mut cam, 0.3, 0.2);
616 let eye_after = cam.eye();
617 let diff = (eye_after - eye_before).length();
618 assert!(
619 diff < 1e-3,
620 "firstperson look should preserve eye position, diff={diff}"
621 );
622 }
623
624 #[test]
625 fn fly_moves_camera() {
626 let mut ctrl = OrbitCameraController::new(BindingPreset::Default);
627 ctrl.navigation_mode = NavigationMode::Fly;
628 ctrl.fly_speed = 60.0;
630 ctrl.begin_frame(make_ctx());
631 let mut cam = camera_facing(glam::Quat::IDENTITY);
632 let centre_before = cam.target();
633 ctrl.push_event(ViewportEvent::Key {
634 key: KeyCode::W,
635 state: ButtonState::Pressed,
636 repeat: false,
637 logical: None,
638 });
639 ctrl.apply_to_camera(&mut cam);
640 assert!(
641 (cam.target() - centre_before).length() > 0.5,
642 "FlyForward should move camera centre"
643 );
644 }
645
646 #[test]
647 fn apply_consumes_external_frame() {
648 let mut ctrl = OrbitCameraController::viewport_primitives();
652 let mut cam = Camera::default();
653 let before = cam.orientation();
654 let mut frame = ActionFrame::default();
655 frame.navigation.orbit = glam::Vec2::new(20.0, 0.0);
656 ctrl.apply(&mut cam, &frame, 1.0 / 60.0);
657 assert_ne!(
658 cam.orientation(),
659 before,
660 "apply(&frame) should orbit from the frame's nav delta"
661 );
662 }
663
664 #[test]
665 fn pivot_follows_a_camera_moved_elsewhere() {
666 let mut ctrl = OrbitCameraController::new_stateless();
667 let mut cam = Camera::default();
668 let mut frame = ActionFrame::default();
669 frame.navigation.orbit = glam::Vec2::new(10.0, 0.0);
670 ctrl.apply(&mut cam, &frame, 1.0 / 60.0);
671 assert_eq!(ctrl.target().unwrap().centre, DVec3::ZERO);
672
673 let centre = DVec3::new(10.0, -3.0, 2.0);
676 cam = Camera::orbit(centre, 4.0, cam.orientation());
677 ctrl.apply(&mut cam, &frame, 1.0 / 60.0);
678 assert!((cam.target() - centre).length() < 1e-4);
679 assert_eq!(cam.focus_distance(), 4.0);
680 assert_eq!(ctrl.target().unwrap().centre, centre);
681 }
682
683 #[test]
684 fn no_input_leaves_the_camera_alone() {
685 let mut ctrl = OrbitCameraController::new_stateless();
686 let mut cam = Camera::default();
687 cam.set_orthographic(true);
688 let before = cam.clone();
689 ctrl.apply(&mut cam, &ActionFrame::default(), 1.0 / 60.0);
690 assert_eq!(cam, before);
691 }
692
693 #[test]
694 fn zoom_scales_an_orthographic_view() {
695 let mut ctrl = OrbitCameraController::new_stateless();
696 let mut cam = Camera::default();
697 cam.set_orthographic(true);
698 let height = cam.view_height_at(1.0);
699 let mut frame = ActionFrame::default();
700 frame.navigation.zoom = 500.0;
701 ctrl.apply(&mut cam, &frame, 1.0 / 60.0);
702 let ratio = cam.focus_distance() / 5.0;
703 assert!(ratio < 1.0);
704 assert!((cam.view_height_at(1.0) - height * ratio).abs() < 1e-4);
705 }
706
707 fn fly_frame(actions: &[Action]) -> ActionFrame {
708 let mut frame = ActionFrame::default();
709 for &a in actions {
710 frame
711 .actions
712 .insert(a, crate::input::action_frame::ResolvedActionState::Held);
713 }
714 frame
715 }
716
717 fn fly_controller() -> OrbitCameraController {
718 let mut ctrl = OrbitCameraController::new_stateless();
719 ctrl.navigation_mode = NavigationMode::Fly;
720 ctrl.fly_speed = 1.0;
721 ctrl
722 }
723
724 #[test]
725 fn fly_diagonal_moves_as_far_as_straight() {
726 let mut ctrl = fly_controller();
727 let level = LookAngles::FORWARD.orientation();
728 let mut moved = |actions: &[Action]| {
729 let mut cam = camera_facing(level);
730 let before = cam.target();
731 ctrl.apply(&mut cam, &fly_frame(actions), 1.0);
732 (cam.target() - before).length()
733 };
734 let straight = moved(&[Action::FlyForward]);
735 let diagonal = moved(&[Action::FlyForward, Action::FlyRight]);
736 let three = moved(&[Action::FlyForward, Action::FlyRight, Action::FlyUp]);
737 assert!((straight - 1.0).abs() < 1e-5);
738 assert!((diagonal - straight).abs() < 1e-5, "diagonal={diagonal}");
739 assert!((three - straight).abs() < 1e-5, "three axes={three}");
740 }
741
742 #[test]
743 fn fly_look_stops_short_of_vertical() {
744 let mut cam = default_target();
745 cam.orientation = LookAngles::FORWARD.orientation();
746 for _ in 0..200 {
748 apply_fly_look(&mut cam, 0.0, -0.1);
749 }
750 let look = LookAngles::from_orientation(cam.orientation);
751 assert!(
752 (look.pitch - POLE_LIMIT).abs() < 1e-3,
753 "pitch={}",
754 look.pitch
755 );
756 assert!((cam.orientation * glam::Vec3::X).z.abs() < 1e-4);
758 }
759
760 #[test]
761 fn fly_look_matches_the_old_turn_directions() {
762 let mut cam = default_target();
763 cam.orientation = LookAngles::FORWARD.orientation();
764 apply_fly_look(&mut cam, 0.2, 0.1);
765 let look = LookAngles::from_orientation(cam.orientation);
766 assert!(look.yaw > 0.0 && look.pitch < 0.0, "{look:?}");
768 }
769
770 #[test]
771 fn turntable_fast_step_reaches_the_limit() {
772 let mut cam = default_target();
773 cam.orientation = LookAngles::FORWARD.orientation();
774 apply_turntable(&mut cam, 0.0, 2.0);
776 let eye_elevation = (cam.orientation * glam::Vec3::Z).z.asin();
777 assert!(
778 (eye_elevation.abs() - POLE_LIMIT).abs() < 1e-3,
779 "elevation={eye_elevation}"
780 );
781 }
782
783 #[test]
784 fn turntable_can_back_away_from_past_the_limit() {
785 let mut cam = default_target();
786 cam.orientation = LookAngles::new(0.0, -1.565).orientation();
788 let before = (cam.orientation * glam::Vec3::Z).z;
789 apply_turntable(&mut cam, 0.0, 0.01);
791 assert!(((cam.orientation * glam::Vec3::Z).z - before).abs() < 1e-6);
792 apply_turntable(&mut cam, 0.0, -0.01);
794 let after = (cam.orientation * glam::Vec3::Z).z;
795 assert!(after < before, "before={before} after={after}");
796 }
797
798 #[test]
799 fn fly_speed_is_per_second() {
800 let mut ctrl = fly_controller();
801 let mut moved = |dt: f32, frames: usize| {
802 let mut cam = camera_facing(LookAngles::FORWARD.orientation());
803 let before = cam.target();
804 for _ in 0..frames {
805 ctrl.apply(&mut cam, &fly_frame(&[Action::FlyForward]), dt);
806 }
807 (cam.target() - before).length()
808 };
809 for (dt, frames) in [(1.0 / 30.0, 30), (1.0 / 60.0, 60), (1.0 / 144.0, 144)] {
811 assert!((moved(dt, frames) - 1.0).abs() < 1e-3, "dt={dt}");
812 }
813 }
814
815 #[test]
816 fn fly_boost_multiplies_speed() {
817 let mut ctrl = fly_controller();
818 let mut cam = camera_facing(LookAngles::FORWARD.orientation());
819 let before = cam.target();
820 ctrl.apply(
821 &mut cam,
822 &fly_frame(&[Action::FlyForward, Action::FlySpeedBoost]),
823 1.0,
824 );
825 let moved = (cam.target() - before).length();
826 assert!(
827 (moved - f64::from(ctrl.fly_boost)).abs() < 1e-5,
828 "moved={moved}"
829 );
830 }
831
832 #[test]
833 fn shift_resolves_to_fly_speed_boost() {
834 use crate::input::binding::Modifiers;
835 let mut input = ViewportInput::new(crate::input::viewport_default_bindings());
836 input.begin_frame(make_ctx());
837 input.push_event(ViewportEvent::ModifiersChanged(Modifiers::SHIFT));
838 assert!(input.resolve().is_active(Action::FlySpeedBoost));
839 input.push_event(ViewportEvent::ModifiersChanged(Modifiers::NONE));
840 assert!(!input.resolve().is_active(Action::FlySpeedBoost));
841 }
842}