Skip to main content

trackball/
frame.rs

1use crate::{Rigid, float};
2use core::f32::consts::PI;
3use glam::{Quat, Vec3, camera::rh::view::look_to_quat};
4
5/// Frame wrt camera eye and target.
6#[derive(Debug, Clone, Copy, PartialEq, Default)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8#[cfg_attr(
9    feature = "rkyv-08",
10    derive(rkyv_08::Archive, rkyv_08::Serialize, rkyv_08::Deserialize),
11    rkyv(crate = rkyv_08)
12)]
13pub struct Frame {
14    /// Target position in world space.
15    pos: Vec3,
16    /// Eye rotation from camera to world space around target.
17    rot: Quat,
18    /// Target distance from eye.
19    zat: f32,
20}
21
22impl Frame {
23    /// Sets eye position inclusive its roll attitude and target position in world space.
24    #[must_use]
25    pub fn look_at(eye: Vec3, target: Vec3, up: Vec3) -> Self {
26        let (dir, zat) = (target - eye).normalize_and_length();
27        Self {
28            pos: target,
29            rot: look_to_quat(dir, up).inverse(),
30            zat,
31        }
32    }
33    /// Eye position in world space.
34    #[must_use]
35    pub fn eye(&self) -> Vec3 {
36        self.pos + self.rot * Vec3::Z * self.zat
37    }
38    /// Sets eye position inclusive its roll attitude in world space preserving target position.
39    pub fn set_eye(&mut self, eye: Vec3, up: Vec3) {
40        *self = Self::look_at(eye, self.pos, up);
41    }
42    /// Target position in world space.
43    #[must_use]
44    pub const fn target(&self) -> Vec3 {
45        self.pos
46    }
47    /// Sets target position in world space preserving eye position inclusive its roll attitude.
48    ///
49    /// Allows to track a moving object.
50    pub fn set_target(&mut self, pos: Vec3) {
51        let eye = self.eye();
52        let (new_dir, zat) = (pos - eye).normalize_and_length();
53        let old_dir = (self.pos - eye).normalize();
54        // Rotate about yaw axis first if nearly opposite to preserve roll attitude and precision.
55        let yaw = if old_dir.dot(new_dir) < float::sqrt(f32::EPSILON) - 1.0 {
56            Quat::from_axis_angle(self.yaw_axis(), PI)
57        } else {
58            Quat::IDENTITY
59        };
60        // Shortest arc without snapping small angles to identity unlike
61        // `Quat::from_rotation_arc()`.
62        let old_dir = yaw * old_dir;
63        let axis = old_dir.cross(new_dir);
64        let arc = Quat::from_xyzw(axis.x, axis.y, axis.z, 1.0 + old_dir.dot(new_dir)).normalize();
65        let rot = (arc * yaw * self.rot).normalize();
66        *self = Self { pos, rot, zat }
67    }
68    /// Distance between eye and target.
69    #[must_use]
70    pub const fn distance(&self) -> f32 {
71        self.zat
72    }
73    /// Sets distance between eye and target preserving target position.
74    pub const fn set_distance(&mut self, zat: f32) {
75        self.zat = zat;
76    }
77    /// Scales distance between eye and target by ratio preserving target position.
78    pub fn scale(&mut self, rat: f32) {
79        self.zat *= rat;
80    }
81    /// Scales distance between eye and point in camera space by ratio preserving target position.
82    pub fn local_scale_around(&mut self, rat: f32, pos: Vec3) {
83        self.local_slide(pos * (1.0 - rat));
84        self.scale(rat);
85    }
86    /// Scales distance between eye and point in world space by ratio preserving target position.
87    pub fn scale_around(&mut self, rat: f32, pos: Vec3) {
88        let pos = pos - self.pos;
89        self.slide(pos * (1.0 - rat));
90        self.scale(rat);
91    }
92    /// Slides camera eye and target by vector in camera space.
93    pub fn local_slide(&mut self, vec: Vec3) {
94        self.pos += self.rot * vec;
95    }
96    /// Slides camera eye and target by vector in world space.
97    pub fn slide(&mut self, vec: Vec3) {
98        self.pos += vec;
99    }
100    /// Orbits eye by rotation in camera space around target.
101    pub fn local_orbit(&mut self, rot: Quat) {
102        self.rot *= rot;
103    }
104    /// Orbits eye by rotation in camera space around point in camera space.
105    pub fn local_orbit_around(&mut self, rot: Quat, pos: Vec3) {
106        self.local_slide(pos - rot * pos);
107        self.local_orbit(rot);
108    }
109    /// Orbits eye by rotation in world space around target.
110    pub fn orbit(&mut self, rot: Quat) {
111        self.rot = rot * self.rot;
112    }
113    /// Orbits eye by rotation in world space around point in world space.
114    pub fn orbit_around(&mut self, rot: Quat, pos: Vec3) {
115        let pos = pos - self.pos;
116        self.slide(pos - rot * pos);
117        self.orbit(rot);
118    }
119    /// Orbits target around eye by pitch and yaw preserving roll attitude aka first person view.
120    ///
121    /// Use fixed [`Self::yaw_axis()`] by capturing it when entering first person view.
122    pub fn look_around(&mut self, pitch: f32, yaw: f32, yaw_axis: Vec3) {
123        let pitch = Quat::from_axis_angle(self.pitch_axis(), pitch);
124        let yaw = Quat::from_axis_angle(yaw_axis, yaw);
125        self.orbit_around(yaw * pitch, self.eye());
126    }
127    /// Positive x-axis in camera space pointing from left to right.
128    #[allow(clippy::unused_self)]
129    #[must_use]
130    pub const fn local_pitch_axis(&self) -> Vec3 {
131        Vec3::X
132    }
133    /// Positive y-axis in camera space pointing from bottom to top.
134    #[allow(clippy::unused_self)]
135    #[must_use]
136    pub const fn local_yaw_axis(&self) -> Vec3 {
137        Vec3::Y
138    }
139    /// Positive z-axis in camera space pointing from back to front.
140    #[allow(clippy::unused_self)]
141    #[must_use]
142    pub const fn local_roll_axis(&self) -> Vec3 {
143        Vec3::Z
144    }
145    /// Positive x-axis in world space pointing from left to right.
146    #[must_use]
147    pub fn pitch_axis(&self) -> Vec3 {
148        self.rot * self.local_pitch_axis()
149    }
150    /// Positive y-axis in world space pointing from bottom to top.
151    #[must_use]
152    pub fn yaw_axis(&self) -> Vec3 {
153        self.rot * self.local_yaw_axis()
154    }
155    /// Positive z-axis in world space pointing from back to front.
156    #[must_use]
157    pub fn roll_axis(&self) -> Vec3 {
158        self.rot * self.local_roll_axis()
159    }
160    /// Interpolates between two frames using linear interpolation for the translation part, and
161    /// spherical linear interpolation along the shortest path for the rotation part.
162    ///
163    /// # Arguments
164    ///
165    ///   * `self`: The initial frame to interpolate from.
166    ///   * `other`: The final frame to interpolate toward.
167    ///   * `t`: The interpolation parameter between 0 and 1.
168    #[must_use]
169    pub fn lerp_slerp(&self, other: Self, t: f32) -> Self {
170        Self {
171            pos: self.pos.lerp(other.pos, t),
172            rot: self.rot.slerp(other.rot, t),
173            zat: float::mul_add(other.zat, t, self.zat * (1.0 - t)),
174        }
175    }
176    /// Renormalizes eye rotation and returns its norm.
177    pub fn renormalize(&mut self) -> f32 {
178        let norm = self.rot.length();
179        self.rot /= norm;
180        norm
181    }
182    /// View transformation from camera to world space.
183    #[must_use]
184    pub fn view(&self) -> Rigid {
185        Rigid::from_rotation_translation(
186            // Eye rotation from camera to world space around target.
187            self.rot,
188            // Eye position in world space with origin in camera space.
189            self.eye(),
190        )
191    }
192    /// Inverse view transformation from world to camera space.
193    ///
194    /// Uses less computations than <code>[Self::view()].inverse()</code>.
195    #[must_use]
196    pub fn inverse_view(&self) -> Rigid {
197        // Eye rotation from world to camera space around target.
198        let rot = self.rot.inverse();
199        // Eye position in camera space with origin in world space.
200        let eye = rot * self.pos + Vec3::Z * self.zat;
201        // Translate in such a way that the eye position with origin in world space vanishes.
202        Rigid::from_rotation_translation(rot, -eye)
203    }
204    /// Whether all components are approximately equal within absolute difference `max_abs_diff`.
205    #[must_use]
206    pub fn abs_diff_eq(&self, other: Self, max_abs_diff: f32) -> bool {
207        self.pos.abs_diff_eq(other.pos, max_abs_diff)
208            && self.rot.abs_diff_eq(other.rot, max_abs_diff)
209            && (self.zat - other.zat).abs() <= max_abs_diff
210    }
211}