Module projection

Source
Expand description

Prepared, viewport-aware 3D projection and finite picking rays.

Supply the actual world-to-clip matrix and its conventions explicitly. This module does not infer camera position, handedness, depth range, viewport, or finite/infinite far intent from matrix coefficients. It caches the existing Mat4::checked_inverse; point transforms reuse Mat4::try_project_point3. Preparation and queries use fixed stack storage and no heap allocations. There is no clock, input, renderer, or physics ownership here.

§Coordinates and clipping

Screen positions and viewport dimensions share caller-selected units, normally host logical pixels. Apply framebuffer/DPR conversion at the host boundary. X increases right; ScreenYAxis defines screen Y. Viewport origin always means the numerical minimum corner. NDC X/Y run from -1 to +1. Screen edges map to NDC edges, with no implicit half-pixel offset. For an integer pixel index, supply origin + (index + 0.5) to sample its center. Both edges are inclusive; a host sharing adjacent rectangles must resolve edge ownership.

Depth is returned/accepted as NDC Z, never a linear world distance or a remapped window-depth value. NdcDepth names physical near and far endpoint values, including reversed depth. All membership tests are exact inclusive comparisons on the computed values, without epsilon or clamping.

Matrices must use positive homogeneous W in the supported clip volume (as Ferravex perspective and orthographic constructors do). Projection rejects negative W as ProjectionError::BehindCamera and zero W as a matrix error. This is a projective half-space test, not an inferred eye position: an orthographic matrix has constant W, so behind-eye points are identified only by their out-of-range depth. Projection permits outside XY/depth and reports membership flags, useful for HUD anchors. Unprojection/picking reject outside inputs. No operation promises accuracy for ill-conditioned matrices.

§Runnable camera, HUD anchor, and picking recipe

This headless first-party recipe uses the same RH GL depth convention as ferravex-render::Camera3D. Graphics cameras using perspective_rh instead need NdcDepth::ZeroToOne. A graphics ClipDepth adapter belongs in graphics, never as a dependency of this math module.

use ferravex_math::{Mat4, Vec3, vec2, vec3};
use ferravex_math::projection::{
    FarPlane, NdcDepth, PreparedProjector3D, ScreenYAxis, Viewport,
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A host has already reserved the header and selected this logical viewport.
    let viewport = Viewport { origin: vec2(20., 80.), size: vec2(800., 400.) };
    let view = Mat4::try_look_at_rh(vec3(0., 0., 5.), Vec3::ZERO, Vec3::Y)?;
    let lens = Mat4::try_perspective_rh_gl(1., 2., 0.5, 50.)?;
    let mut projector = PreparedProjector3D::try_new(
        lens * view, viewport, ScreenYAxis::Down,
        NdcDepth::NegativeOneToOne, FarPlane::Finite,
    )?;
    let anchor = projector.project(Vec3::ZERO)?;
    assert!(anchor.inside_viewport && anchor.inside_depth);
    assert!(anchor.screen.abs_diff_eq(vec2(420., 280.), 0.001));
    let restored = projector.unproject(anchor.screen, anchor.ndc_depth)?;
    assert!(restored.abs_diff_eq(Vec3::ZERO, 0.0001));

    // A logical pointer uses the same viewport as drawing; no DPR multiplication.
    let ray = projector.pick_ray(anchor.screen)?;
    assert!(ray.origin.abs_diff_eq(vec3(0., 0., 4.5), 0.0001));
    assert!(ray.direction.abs_diff_eq(Vec3::NEG_Z, 0.0001));
    // Intersect the z=0 authoring plane. A physics consumer can instead pass
    // origin/direction to its own query and cap distance at the far endpoint.
    let distance = -ray.origin.z / ray.direction.z;
    let hit = ray.origin + ray.direction * distance;
    assert!(hit.abs_diff_eq(Vec3::ZERO, 0.0001));
    assert!(ray.far_point.z < hit.z);

    // Resize/camera updates are transactional. Suspend rendering/input after
    // a zero-size error; the retained transform remains usable on restoration.
    let before = projector;
    let suspended = Viewport { size: vec2(0., 0.), ..viewport };
    assert!(projector.try_update(lens * view, suspended, ScreenYAxis::Down,
        NdcDepth::NegativeOneToOne, FarPlane::Finite).is_err());
    assert_eq!(projector, before);
    Ok(())
}

Structs§

PickingRay3D
Picking ray with explicit finite clipping endpoints. See the module recipe.
PreparedProjector3D
Validated world-to-clip transform and cached clip-to-world inverse.
ProjectedPoint
A finite positive-W projection, including unclamped clip membership. See the module’s HUD recipe. Membership is not occlusion testing.
Viewport
Numerical minimum and positive extent in the same units as screen queries.

Enums§

FarPlane
Caller declaration of far-plane intent; it cannot be recovered reliably from rounded, composed matrix coefficients. Infinite far is explicitly unsupported.
NdcDepth
Explicit NDC Z endpoints, ordered by physical near-to-far, not numeric value.
ProjectionError
Checked projection/preparation failure, with no fallback camera or point.
ScreenYAxis
Direction in which numerical screen Y increases; NDC +Y is always up.