use glam::{DMat4, DQuat, DVec3};
use crate::geo::projection::Projection;
pub(crate) fn orientation_from_roll_pitch_bearing(roll: f64, pitch: f64, bearing: f64) -> DQuat {
DQuat::from_axis_angle(DVec3::Z, -bearing)
* DQuat::from_axis_angle(DVec3::X, -pitch)
* DQuat::from_axis_angle(DVec3::Z, roll)
}
fn roll_pitch_bearing(forward: DVec3, right: DVec3, up: DVec3) -> (f64, f64, f64) {
let f01 = forward.truncate().length();
let pitch = f01.atan2(-forward.z);
let (bearing, roll) = if f01 > 1.0e-3 {
(-forward.x.atan2(-forward.y), -right.z.atan2(up.z))
} else {
((-right.y).atan2(right.x), 0.0)
};
(roll, pitch, bearing)
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct CameraPose {
pub(crate) position: DVec3,
pub(crate) orientation: DQuat,
}
impl Default for CameraPose {
fn default() -> Self {
CameraPose { position: DVec3::ZERO, orientation: DQuat::IDENTITY }
}
}
impl CameraPose {
pub(crate) fn from_angles(position: DVec3, roll: f64, pitch: f64, bearing: f64) -> Self {
CameraPose { position, orientation: orientation_from_roll_pitch_bearing(roll, pitch, bearing) }
}
pub(crate) fn world_to_camera(&self, scale: f64, pixels_per_meter: f64) -> DMat4 {
let world_size = Projection::world_size(scale);
DMat4::from_scale(DVec3::new(1.0, -1.0, 1.0))
* DMat4::from_quat(self.orientation.conjugate())
* DMat4::from_translation(-self.position * world_size)
* DMat4::from_scale(DVec3::new(1.0, 1.0, pixels_per_meter))
}
pub(crate) fn forward(&self) -> DVec3 {
self.orientation * DVec3::NEG_Z
}
pub(crate) fn right(&self) -> DVec3 {
self.orientation * DVec3::X
}
pub(crate) fn up(&self) -> DVec3 {
self.orientation * DVec3::NEG_Y
}
pub(crate) fn orientation_angles(&self) -> (f64, f64, f64) {
roll_pitch_bearing(self.forward(), self.right(), self.up())
}
pub(crate) fn orientation_from_frame(forward: DVec3, up: DVec3) -> Option<DQuat> {
let right = up.cross(forward);
if right.length() < 1e-15 {
return None;
}
let (roll, pitch, bearing) = roll_pitch_bearing(forward, right, up);
Some(orientation_from_roll_pitch_bearing(roll, pitch, bearing))
}
}
#[cfg(test)]
#[path = "camera_pose_test.rs"]
mod camera_pose_test;