mod orthographic;
mod perspective;
pub use orthographic::OrthographicCamera;
pub use perspective::{PerspectiveCamera, ProjectionKind, SensorFit};
use crate::core::Layers;
use crate::math::{Matrix4, Vector2, Vector3};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Lens {
pub aperture: f32,
pub focus_distance: f32,
pub blades: u32,
pub anamorphic: f32,
}
impl Default for Lens {
fn default() -> Self {
Self {
aperture: 0.0,
focus_distance: 0.0,
blades: 0,
anamorphic: 1.0,
}
}
}
impl Lens {
pub fn is_thin_lens(&self) -> bool {
self.aperture > 0.0
}
pub fn sample(&self, u1: f32, u2: f32) -> (f32, f32) {
let (mut x, mut y) = if self.blades >= 3 {
polygon_sample(self.blades, u1, u2)
} else {
concentric_disk(u1, u2)
};
if self.anamorphic > 0.0 && self.anamorphic != 1.0 {
x /= self.anamorphic;
}
let r = (x * x + y * y).sqrt();
if r > 1.0 {
x /= r;
y /= r;
}
(x, y)
}
}
pub fn concentric_disk(u1: f32, u2: f32) -> (f32, f32) {
let a = 2.0 * u1 - 1.0;
let b = 2.0 * u2 - 1.0;
if a == 0.0 && b == 0.0 {
return (0.0, 0.0);
}
let (r, theta) = if a * a > b * b {
(a, std::f32::consts::FRAC_PI_4 * (b / a))
} else {
(
b,
std::f32::consts::FRAC_PI_2 - std::f32::consts::FRAC_PI_4 * (a / b),
)
};
(r * theta.cos(), r * theta.sin())
}
pub fn polygon_sample(blades: u32, u1: f32, u2: f32) -> (f32, f32) {
let n = blades.max(3) as f32;
let wedge = std::f32::consts::TAU / n;
let scaled = (u1 * n).min(n - f32::EPSILON);
let index = scaled.floor();
let mut a = scaled - index;
let mut b = u2;
if a + b > 1.0 {
a = 1.0 - a;
b = 1.0 - b;
}
let (t0, t1) = (index * wedge, (index + 1.0) * wedge);
let (c0, s0) = (t0.cos(), t0.sin());
let (c1, s1) = (t1.cos(), t1.sin());
(a * c0 + b * c1, a * s0 + b * s1)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ViewOverride {
pub view: Matrix4,
pub position: Vector3,
pub target: Vector3,
pub up: Vector3,
}
impl ViewOverride {
pub fn for_pose(&self, position: Vector3, target: Vector3, up: Vector3) -> Option<Matrix4> {
(self.position == position && self.target == target && self.up == up).then_some(self.view)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ViewOffset {
pub full_width: f32,
pub full_height: f32,
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
}
impl ViewOffset {
pub fn apply(&self, projection: Matrix4) -> Matrix4 {
projection.sub_view(
(self.full_width, self.full_height),
(self.x, self.y, self.width, self.height),
)
}
}
pub trait Camera {
fn view_matrix(&self) -> Matrix4;
fn projection_matrix(&self) -> Matrix4;
fn position(&self) -> Vector3;
fn set_aspect(&mut self, aspect: f32);
fn lens(&self) -> Lens {
Lens::default()
}
fn look_at(&mut self, target: Vector3);
fn near_far(&self) -> (f32, f32) {
(0.1, 1000.0)
}
fn layers(&self) -> Layers {
Layers::default()
}
fn world_to_ndc(&self, point: Vector3) -> Option<Vector3> {
self.projector(1, 1).ndc(point)
}
fn world_to_screen(&self, point: Vector3, width: u32, height: u32) -> Option<Vector2> {
self.projector(width, height).screen(point)
}
fn projector(&self, width: u32, height: u32) -> ScreenProjector {
let view = self.view_matrix();
ScreenProjector {
eye_z: [
view.elements[2],
view.elements[6],
view.elements[10],
view.elements[14],
],
view_projection: self.projection_matrix().multiply(&view),
width: width as f32,
height: height as f32,
}
}
}
#[derive(Debug, Clone)]
pub struct ScreenProjector {
eye_z: [f32; 4],
view_projection: Matrix4,
width: f32,
height: f32,
}
impl ScreenProjector {
pub fn ndc(&self, point: Vector3) -> Option<Vector3> {
let z = self.eye_z[0] * point.x
+ self.eye_z[1] * point.y
+ self.eye_z[2] * point.z
+ self.eye_z[3];
if z >= 0.0 {
return None;
}
Some(point.apply_matrix4(&self.view_projection))
}
pub fn screen(&self, point: Vector3) -> Option<Vector2> {
let ndc = self.ndc(point)?;
Some(Vector2::new(
(ndc.x * 0.5 + 0.5) * self.width,
(1.0 - (ndc.y * 0.5 + 0.5)) * self.height,
))
}
pub fn view_projection(&self) -> &Matrix4 {
&self.view_projection
}
}
#[cfg(test)]
mod tests {
use super::*;
fn camera() -> PerspectiveCamera {
let mut c = PerspectiveCamera::new(60.0, 2.0, 0.1, 100.0);
c.position = Vector3::new(0.0, 0.0, 5.0);
c.look_at(Vector3::ZERO);
c
}
#[test]
fn the_point_a_camera_looks_at_lands_in_the_middle() {
let c = camera();
let p = c
.world_to_screen(Vector3::ZERO, 800, 400)
.expect("in front");
assert!(
(p.x - 400.0).abs() < 0.01 && (p.y - 200.0).abs() < 0.01,
"expected the centre of an 800x400 view, got {p:?}"
);
}
#[test]
fn up_in_the_world_is_up_on_the_screen() {
let c = camera();
let up = c
.world_to_screen(Vector3::new(0.0, 1.0, 0.0), 800, 400)
.unwrap();
let down = c
.world_to_screen(Vector3::new(0.0, -1.0, 0.0), 800, 400)
.unwrap();
assert!(
up.y < 200.0,
"a point above the target should be high: {up:?}"
);
assert!(down.y > 200.0, "and one below should be low: {down:?}");
assert!(
((up.y + down.y) * 0.5 - 200.0).abs() < 0.01,
"symmetric about the middle: {up:?} {down:?}"
);
let right = c
.world_to_screen(Vector3::new(1.0, 0.0, 0.0), 800, 400)
.unwrap();
assert!(right.x > 400.0, "+x should be to the right: {right:?}");
}
#[test]
fn a_point_behind_the_eye_has_no_projection() {
let c = camera();
assert!(c
.world_to_screen(Vector3::new(0.0, 0.0, 6.0), 800, 400)
.is_none());
assert!(
c.world_to_ndc(Vector3::new(0.0, 0.0, 5.0)).is_none(),
"at the eye"
);
assert!(c
.world_to_screen(Vector3::new(0.0, 0.0, 4.0), 800, 400)
.is_some());
}
#[test]
fn the_projector_matches_applying_the_matrices_in_turn() {
let c = camera();
let (view, projection) = (c.view_matrix(), c.projection_matrix());
let project = c.projector(800, 400);
let mut rng = crate::math::Rng::new(0xCA1);
for _ in 0..200 {
let p = Vector3::new(
rng.range(-8.0, 8.0),
rng.range(-8.0, 8.0),
rng.range(-8.0, 4.9),
);
let eye = p.apply_matrix4(&view);
let step_by_step = (eye.z < 0.0).then(|| {
let ndc = eye.apply_matrix4(&projection);
Vector2::new(
(ndc.x * 0.5 + 0.5) * 800.0,
(1.0 - (ndc.y * 0.5 + 0.5)) * 400.0,
)
});
match (project.screen(p), step_by_step) {
(None, None) => {}
(Some(a), Some(b)) => assert!(
(a.x - b.x).abs() < 1e-2 && (a.y - b.y).abs() < 1e-2,
"{p:?}: combined {a:?} vs stepwise {b:?}"
),
(a, b) => panic!("{p:?}: disagreed on whether it projects at all: {a:?} {b:?}"),
}
}
}
#[test]
fn the_per_point_method_and_the_projector_agree() {
let c = camera();
let project = c.projector(640, 480);
for p in [
Vector3::ZERO,
Vector3::new(2.0, -1.0, 1.0),
Vector3::new(0.0, 0.0, 9.0),
] {
assert_eq!(
c.world_to_screen(p, 640, 480).map(|v| (v.x, v.y)),
project.screen(p).map(|v| (v.x, v.y)),
"{p:?}"
);
}
}
#[test]
fn it_round_trips_through_unproject() {
let c = camera();
let (view, projection) = (c.view_matrix(), c.projection_matrix());
for p in [
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(1.5, -0.5, 2.0),
Vector3::new(-2.0, 1.0, -3.0),
] {
let ndc = c.world_to_ndc(p).expect("in front");
let back = ndc.unproject(&view, &projection);
assert!(
(back.x - p.x).abs() < 1e-3
&& (back.y - p.y).abs() < 1e-3
&& (back.z - p.z).abs() < 1e-3,
"{p:?} projected to {ndc:?} and came back as {back:?}"
);
}
}
#[test]
fn it_works_for_an_orthographic_camera_too() {
let mut c = OrthographicCamera::new(-2.0, 2.0, 1.0, -1.0, 0.1, 100.0);
c.position = Vector3::new(0.0, 0.0, 5.0);
c.target = Vector3::ZERO;
let mid = c.world_to_screen(Vector3::ZERO, 400, 200).expect("in view");
assert!(
(mid.x - 200.0).abs() < 0.01 && (mid.y - 100.0).abs() < 0.01,
"got {mid:?}"
);
let off = c
.world_to_screen(Vector3::new(1.0, 0.0, 0.0), 400, 200)
.unwrap();
assert!((off.x - 300.0).abs() < 0.01, "got {off:?}");
assert!(
c.world_to_screen(Vector3::new(0.0, 0.0, 6.0), 400, 200)
.is_none(),
"a point behind an orthographic camera is not placeable"
);
}
#[test]
fn every_camera_can_be_aimed_through_the_trait() {
let mut perspective = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
perspective.position = Vector3::new(0.0, 0.0, 5.0);
let mut orthographic = OrthographicCamera::new(-1.0, 1.0, 1.0, -1.0, 0.1, 100.0);
orthographic.position = Vector3::new(0.0, 0.0, 5.0);
let aim = Vector3::new(2.0, 1.0, 0.0);
let cameras: [&mut dyn Camera; 2] = [&mut perspective, &mut orthographic];
let before: Vec<_> = cameras.iter().map(|c| c.view_matrix().elements).collect();
for (camera, was) in cameras.into_iter().zip(before) {
camera.look_at(aim);
assert_ne!(
camera.view_matrix().elements,
was,
"the view matrix did not follow look_at"
);
let forward = (aim - camera.position()).normalize();
let view = camera.view_matrix().elements;
let cam_forward = Vector3::new(-view[2], -view[6], -view[10]).normalize();
let dot =
forward.x * cam_forward.x + forward.y * cam_forward.y + forward.z * cam_forward.z;
assert!(
dot > 0.999,
"camera is aimed {dot} of the way at the target"
);
}
let aimed = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0)
.look_at(Vector3::ONE)
.position;
assert_eq!(aimed, Vector3::new(0.0, 0.0, 5.0));
let mut ortho = OrthographicCamera::new(-1.0, 1.0, 1.0, -1.0, 0.1, 100.0);
assert_eq!(ortho.look_at(Vector3::ONE).target, Vector3::ONE);
}
}
#[cfg(test)]
mod lens_tests {
use super::*;
#[test]
fn an_f_stop_becomes_an_aperture_in_world_units() {
let mut c = PerspectiveCamera::new(0.0, 1.0, 0.1, 100.0);
c.fov = 2.0 * (17.5f32 / 50.0).atan();
assert!(
(c.focal_length_mm() - 50.0).abs() < 0.01,
"focal length {} mm",
c.focal_length_mm()
);
c.f_stop = 2.8;
let lens = c.lens();
let expected = 0.050 / (2.0 * 2.8);
assert!(
(lens.aperture - expected).abs() < 1e-6,
"f/2.8 gave {} , wanted {expected}",
lens.aperture
);
c.f_stop = 1.4;
assert!((c.lens().aperture - expected * 2.0).abs() < 1e-6);
c.aperture = 0.25;
assert_eq!(c.lens().aperture, 0.25);
let plain = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
assert_eq!(plain.lens().aperture, 0.0);
assert!(!plain.lens().is_thin_lens());
}
#[test]
fn blades_make_the_aperture_a_polygon() {
let hex = Lens {
aperture: 1.0,
blades: 6,
..Lens::default()
};
let round = Lens {
aperture: 1.0,
..Lens::default()
};
let samples = |lens: &Lens| -> Vec<(f32, f32)> {
let n = 160;
(0..n * n)
.map(|i| {
let (a, b) = ((i % n) as f32, (i / n) as f32);
lens.sample((a + 0.5) / n as f32, (b + 0.5) / n as f32)
})
.collect()
};
let h = samples(&hex);
let r = samples(&round);
for (x, y) in h.iter().chain(r.iter()) {
assert!(x * x + y * y <= 1.0 + 1e-4, "({x}, {y}) is outside");
}
let max_at = |pts: &[(f32, f32)], angle: f32| -> f32 {
pts.iter()
.filter(|(x, y)| {
let a = y.atan2(*x);
let d = (a - angle).abs();
d.min(std::f32::consts::TAU - d) < 0.05
})
.map(|(x, y)| (x * x + y * y).sqrt())
.fold(0.0f32, f32::max)
};
let vertex = max_at(&h, 0.0);
let edge = max_at(&h, std::f32::consts::PI / 6.0);
assert!(vertex > 0.97, "hexagon vertex reach {vertex}");
assert!(
(edge - 0.866).abs() < 0.03,
"hexagon edge-midpoint reach {edge}, wanted 0.866"
);
assert!(
(max_at(&r, 0.0) - max_at(&r, std::f32::consts::PI / 6.0)).abs() < 0.03,
"the round aperture is not round"
);
let inner = h
.iter()
.filter(|(x, y)| (x * x + y * y).sqrt() < 0.866 / std::f32::consts::SQRT_2)
.count() as f32
/ h.len() as f32;
assert!(
(0.35..0.55).contains(&inner),
"{inner:.2} of the samples are in the inner half-area — the \
aperture has a bright core"
);
}
#[test]
fn an_anamorphic_lens_has_oval_bokeh() {
let lens = Lens {
aperture: 1.0,
anamorphic: 2.0,
..Lens::default()
};
let mut wide: f32 = 0.0;
let mut tall: f32 = 0.0;
let n = 128;
for i in 0..n * n {
let (a, b) = ((i % n) as f32, (i / n) as f32);
let (x, y) = lens.sample((a + 0.5) / n as f32, (b + 0.5) / n as f32);
wide = wide.max(x.abs());
tall = tall.max(y.abs());
}
assert!(
(tall / wide - 2.0).abs() < 0.1,
"a 2x squeeze gave {:.2}:1 bokeh",
tall / wide
);
let round = Lens {
aperture: 1.0,
..Lens::default()
};
let (x, y) = round.sample(0.9, 0.1);
let (x2, y2) = Lens {
anamorphic: 1.0,
..round
}
.sample(0.9, 0.1);
assert_eq!((x, y), (x2, y2));
}
#[test]
fn the_two_lens_samplers_agree() {
let wgsl = |u1: f32, u2: f32, blades: f32, anamorphic: f32| -> (f32, f32) {
let (mut x, mut y) = if blades >= 3.0 {
let n = blades.max(3.0);
let wedge = std::f32::consts::TAU / n;
let scaled = (u1 * n).min(n - 1e-6);
let index = scaled.floor();
let mut a = scaled - index;
let mut b = u2;
if a + b > 1.0 {
a = 1.0 - a;
b = 1.0 - b;
}
let (t0, t1) = (index * wedge, (index + 1.0) * wedge);
(a * t0.cos() + b * t1.cos(), a * t0.sin() + b * t1.sin())
} else {
concentric_disk(u1, u2)
};
if anamorphic > 0.0 && anamorphic != 1.0 {
x /= anamorphic;
}
let r = (x * x + y * y).sqrt();
if r > 1.0 {
x /= r;
y /= r;
}
(x, y)
};
for &(blades, anamorphic) in &[(0u32, 1.0f32), (5, 1.0), (6, 2.0), (8, 0.5)] {
let lens = Lens {
aperture: 1.0,
blades,
anamorphic,
..Lens::default()
};
for i in 0..64 {
for j in 0..64 {
let (u1, u2) = ((i as f32 + 0.5) / 64.0, (j as f32 + 0.5) / 64.0);
let a = lens.sample(u1, u2);
let b = wgsl(u1, u2, blades as f32, anamorphic);
assert!(
(a.0 - b.0).abs() < 1e-5 && (a.1 - b.1).abs() < 1e-5,
"blades {blades}, squeeze {anamorphic}, u ({u1}, {u2}): \
Rust {a:?} vs WGSL {b:?}"
);
}
}
}
}
}