threers 0.0.4

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, an OpenSCAD front end with a watertight exact-CSG kernel, headless render, and native media codecs
Documentation
//! Camera rays, including a thin lens.
//!
//! Rays are generated by unprojecting through the camera's own matrices rather
//! than by rebuilding a frustum from a field of view. That costs two matrix
//! inversions once per frame and buys exactness: an
//! [`OrthographicCamera`](crate::cameras::OrthographicCamera), a
//! [`PerspectiveCamera`](crate::cameras::PerspectiveCamera), and a camera
//! carrying an oblique-clip `projection_override` all work with no special
//! cases, and the traced image lines up with the rasterised one pixel for
//! pixel.

use crate::cameras::Camera;
use crate::math::{Matrix4, Vector2, Vector3};

use super::sampler::concentric_disk;
use super::settings::RaytraceSettings;

/// A camera resolved into the form the tracer needs: world-space ray origins
/// and directions, plus a lens.
#[derive(Debug, Clone, Copy)]
pub struct RtCamera {
    inv_view: Matrix4,
    inv_proj: Matrix4,
    position: Vector3,
    /// Camera basis in world space, for the lens offset.
    right: Vector3,
    up: Vector3,
    forward: Vector3,
    /// False for an orthographic projection, where every ray is parallel and
    /// the origin varies instead of the direction.
    perspective: bool,
    aperture: f32,
    focus_distance: f32,
}

impl RtCamera {
    /// Resolve `camera` for tracing. `focus_distance` of 0 in the settings is
    /// left as 0 here; [`Self::with_focus_distance`] fills it in once the scene
    /// is known.
    pub fn new(camera: &dyn Camera, settings: &RaytraceSettings) -> Self {
        let view = camera.view_matrix();
        let proj = camera.projection_matrix();
        let inv_view = view.invert();
        // The inverse view matrix is the camera's world transform: its columns
        // are the basis vectors, and view space looks down its own -Z.
        let e = &inv_view.elements;
        let right = Vector3::new(e[0], e[1], e[2]).normalize();
        let up = Vector3::new(e[4], e[5], e[6]).normalize();
        let forward = Vector3::new(-e[8], -e[9], -e[10]).normalize();
        // A perspective matrix puts -1 in the w row; an orthographic one has 0
        // there. That single element is the whole distinction.
        let perspective = proj.elements[11].abs() > 1e-6;
        Self {
            inv_view,
            inv_proj: proj.invert(),
            position: camera.position(),
            right,
            up,
            forward,
            perspective,
            aperture: settings.aperture.max(0.0),
            focus_distance: settings.focus_distance.max(0.0),
        }
    }

    /// Set the focal distance — used to apply autofocus once the scene has been
    /// probed.
    pub fn with_focus_distance(mut self, d: f32) -> Self {
        self.focus_distance = d.max(1e-4);
        self
    }

    pub fn focus_distance(&self) -> f32 {
        self.focus_distance
    }

    pub fn is_perspective(&self) -> bool {
        self.perspective
    }

    pub fn forward(&self) -> Vector3 {
        self.forward
    }

    pub fn position(&self) -> Vector3 {
        self.position
    }

    /// Camera basis in world space — the lens offset is built from these, and
    /// the GPU kernel needs them for the same reason.
    pub fn right(&self) -> Vector3 {
        self.right
    }

    pub fn up(&self) -> Vector3 {
        self.up
    }

    /// The inverted matrices ray generation unprojects through. Exposed so a
    /// device backend can do the same arithmetic rather than re-deriving a
    /// frustum from a field of view and drifting out of alignment.
    pub fn inv_view_matrix(&self) -> Matrix4 {
        self.inv_view
    }

    pub fn inv_proj_matrix(&self) -> Matrix4 {
        self.inv_proj
    }

    /// A ray through normalised device coordinates `ndc` ∈ [-1, 1]².
    ///
    /// `lens` is a pair of uniform randoms used to pick a point on the aperture;
    /// it is ignored for a pinhole.
    pub fn ray(&self, ndc: Vector2, lens: (f32, f32)) -> (Vector3, Vector3) {
        // WebGPU's clip space runs z from 0 at the near plane to 1 at the far
        // one, unlike OpenGL's -1..1 — unprojecting at -1 would put the near
        // point behind the camera.
        let near = Vector3::new(ndc.x, ndc.y, 0.0)
            .apply_matrix4(&self.inv_proj)
            .apply_matrix4(&self.inv_view);
        let far = Vector3::new(ndc.x, ndc.y, 1.0)
            .apply_matrix4(&self.inv_proj)
            .apply_matrix4(&self.inv_view);

        let (mut origin, mut dir) = if self.perspective {
            let o = self.position;
            let d = far - o;
            if d.length_sq() <= 1e-20 {
                (o, self.forward)
            } else {
                (o, d.normalize())
            }
        } else {
            let d = far - near;
            if d.length_sq() <= 1e-20 {
                (near, self.forward)
            } else {
                (near, d.normalize())
            }
        };

        if self.aperture > 0.0 && self.focus_distance > 0.0 {
            // Thin lens: every ray through the lens that would meet at the
            // focal plane still meets there, so that plane stays sharp and
            // everything else spreads into a circle of confusion.
            let cos = dir.dot(self.forward);
            if cos.abs() > 1e-6 {
                let t = self.focus_distance / cos;
                let focal_point = origin + dir * t;
                let (lx, ly) = concentric_disk(lens.0, lens.1);
                origin =
                    origin + self.right * (lx * self.aperture) + self.up * (ly * self.aperture);
                let d = focal_point - origin;
                if d.length_sq() > 1e-20 {
                    dir = d.normalize();
                }
            }
        }
        (origin, dir)
    }

    /// A ray through pixel `(x, y)` with sub-pixel offset `jitter` ∈ [0, 1)².
    /// Row 0 is the top of the image, matching every other raster path in the
    /// crate.
    pub fn pixel_ray(
        &self,
        x: u32,
        y: u32,
        width: u32,
        height: u32,
        jitter: (f32, f32),
        lens: (f32, f32),
    ) -> (Vector3, Vector3) {
        let u = (x as f32 + jitter.0) / width as f32;
        let v = (y as f32 + jitter.1) / height as f32;
        self.ray(Vector2::new(u * 2.0 - 1.0, 1.0 - v * 2.0), lens)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cameras::{OrthographicCamera, PerspectiveCamera};

    fn perspective() -> PerspectiveCamera {
        let mut c = PerspectiveCamera::new(60.0, 1.0, 0.1, 100.0);
        c.position = Vector3::new(0.0, 0.0, 5.0);
        c.target = Vector3::ZERO;
        c
    }

    #[test]
    fn the_centre_ray_looks_down_the_view_axis() {
        let cam = perspective();
        let rt = RtCamera::new(&cam, &RaytraceSettings::default());
        assert!(rt.is_perspective());
        let (o, d) = rt.ray(Vector2::new(0.0, 0.0), (0.5, 0.5));
        assert!((o - Vector3::new(0.0, 0.0, 5.0)).length() < 1e-5, "{o:?}");
        assert!((d - Vector3::new(0.0, 0.0, -1.0)).length() < 1e-4, "{d:?}");
    }

    #[test]
    fn ndc_corners_spread_the_expected_way() {
        let cam = perspective();
        let rt = RtCamera::new(&cam, &RaytraceSettings::default());
        let (_, right) = rt.ray(Vector2::new(1.0, 0.0), (0.5, 0.5));
        let (_, up) = rt.ray(Vector2::new(0.0, 1.0), (0.5, 0.5));
        assert!(
            right.x > 0.0,
            "+X in NDC must go +X in world here: {right:?}"
        );
        assert!(up.y > 0.0, "+Y in NDC must go up: {up:?}");
        // A 60 degree vertical FOV: the top edge is 30 degrees off axis.
        let angle = up.dot(Vector3::new(0.0, 0.0, -1.0)).acos();
        assert!(
            (angle - 30f32.to_radians()).abs() < 1e-3,
            "{} deg",
            angle.to_degrees()
        );
    }

    #[test]
    fn pixel_row_zero_is_the_top_of_the_image() {
        let cam = perspective();
        let rt = RtCamera::new(&cam, &RaytraceSettings::default());
        let (_, top) = rt.pixel_ray(50, 0, 100, 100, (0.5, 0.5), (0.5, 0.5));
        let (_, bottom) = rt.pixel_ray(50, 99, 100, 100, (0.5, 0.5), (0.5, 0.5));
        assert!(
            top.y > bottom.y,
            "row 0 should look higher: {top:?} vs {bottom:?}"
        );
    }

    #[test]
    fn orthographic_rays_are_parallel() {
        let mut cam = OrthographicCamera::new(-2.0, 2.0, 2.0, -2.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 5.0);
        let rt = RtCamera::new(&cam, &RaytraceSettings::default());
        assert!(!rt.is_perspective());
        let (o1, d1) = rt.ray(Vector2::new(-0.5, -0.5), (0.5, 0.5));
        let (o2, d2) = rt.ray(Vector2::new(0.5, 0.5), (0.5, 0.5));
        assert!((d1 - d2).length() < 1e-5, "{d1:?} vs {d2:?}");
        assert!(
            (o1 - o2).length() > 0.5,
            "origins should differ: {o1:?} {o2:?}"
        );
        assert!((d1 - Vector3::new(0.0, 0.0, -1.0)).length() < 1e-4);
    }

    #[test]
    fn a_pinhole_ignores_the_lens_sample() {
        let cam = perspective();
        let rt = RtCamera::new(&cam, &RaytraceSettings::default());
        let (o1, d1) = rt.ray(Vector2::new(0.2, -0.3), (0.1, 0.9));
        let (o2, d2) = rt.ray(Vector2::new(0.2, -0.3), (0.8, 0.2));
        assert!((o1 - o2).length() < 1e-6);
        assert!((d1 - d2).length() < 1e-6);
    }

    /// Every ray through the lens must still cross the focal plane at the same
    /// point — that is the entire definition of "in focus".
    #[test]
    fn depth_of_field_keeps_the_focal_plane_sharp() {
        let cam = perspective();
        let settings = RaytraceSettings::default().with_depth_of_field(0.3, 5.0);
        let rt = RtCamera::new(&cam, &settings);
        let ndc = Vector2::new(0.4, -0.2);
        let mut reference = None;
        for lens in [(0.1, 0.1), (0.9, 0.5), (0.5, 0.95), (0.25, 0.75)] {
            let (o, d) = rt.ray(ndc, lens);
            let t = 5.0 / d.dot(rt.forward());
            let p = o + d * t;
            match reference {
                None => reference = Some(p),
                Some(r) => assert!((p - r).length() < 1e-3, "{p:?} vs {r:?}"),
            }
        }
        // And the origins really did move.
        let (o1, _) = rt.ray(ndc, (0.05, 0.5));
        let (o2, _) = rt.ray(ndc, (0.95, 0.5));
        assert!((o1 - o2).length() > 0.1, "the aperture had no effect");
    }
}