Module affine

Source
Expand description

Checked, reusable affine point, vector and normal transformation.

PreparedAffine3D accepts an existing Mat4; it does not author another TRS/scene hierarchy. Preparation checks finite coefficients, the exact affine row (0, 0, 0, 1) and a representable inverse of the linear part. Translation is excluded from inversion, so an unrepresentable inverse translation does not prevent forward transformation. No projective division is performed.

Normals use the inverse transpose, including for nonuniform scale and shear. Reflections are accepted. Normals retain their covector orientation: there is no extra determinant-sign flip. For a mirrored model, a transformed triangle’s edge cross product points opposite its transformed authored normal. Use PreparedAffine3D::is_reflected to choose a winding/culling policy, or explicitly negate the returned normal when matching that cross product is intended. The cached normal matrix follows the same policy.

Scalar operations reject nonfinite inputs. Points/vectors use f64 dot products and reject outputs that round to nonfinite f32. Normals rescale wide dot products before using Vec3::try_normalize, allowing a unit result even when an unnormalized component would overflow/underflow f32. A zero input or a transformed normal that collapses to zero is an error. Ordinary f32 rounding and the conditioning limits of Mat4::checked_inverse remain; success is not an accuracy certificate.

Slice operations require enough caller storage, process the entire input (never truncate), and leave all output elements unchanged on any error. On success only the input-length prefix is written. They use two passes, O(n) work, O(1) stack storage and no heap allocations. Callers impose their own input/work bound. Separate calls are separate transactions.

§Runnable mesh preparation recipe

Prepare once when an authored model changes, then reuse for mesh positions, directions and lighting normals. This recipe uses a mirrored, sheared model and caller-owned output arrays; it does not replace a renderer.

use ferravex_math::{Mat4, Vec3, Vec4, vec3, vec4};
use ferravex_math::affine::PreparedAffine3D;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let model = Mat4::from_cols(
        vec4(-2.0, 0.0, 0.0, 0.0),
        vec4(1.0, 3.0, 0.0, 0.0),
        vec4(0.0, 0.0, 0.5, 0.0),
        vec3(10.0, 2.0, -1.0).extend(1.0),
    );
    let mut prepared = PreparedAffine3D::try_new(model)?;
    assert_eq!(prepared.model(), model);
    assert!(prepared.is_reflected()); // renderer chooses winding explicitly
    let local_positions = [Vec3::ZERO, Vec3::X, Vec3::Y];
    let mut world_positions = [Vec3::ZERO; 3];
    let mut world_normals = [Vec3::ZERO; 3];
    prepared.transform_points_into(&local_positions, &mut world_positions)?;
    prepared.transform_normals_into(&[Vec3::Z; 3], &mut world_normals)?;
    let edge = prepared.transform_vector(Vec3::X)?;
    assert!(edge.dot(world_normals[0]).abs() < 1.0e-6);
    let winding_normal = (world_positions[1] - world_positions[0])
        .cross(world_positions[2] - world_positions[0]).normalize();
    assert!(winding_normal.dot(world_normals[0]) < -0.999);
    assert_eq!(prepared.normal_matrix().transform_vector3(Vec3::Z), Vec3::Z * 2.0);
    assert_eq!(prepared.transform_point(Vec3::ZERO)?, model.w_axis.truncate());
    let mut directions = [Vec3::ZERO];
    prepared.transform_vectors_into(&[Vec3::X], &mut directions)?;
    assert_eq!(directions[0], edge);
    let retained = prepared;
    assert!(prepared.try_update(Mat4::from_scale(Vec3::ZERO)).is_err());
    assert_eq!(prepared, retained); // failed edits retain the last good cache
    prepared.try_update(Mat4::IDENTITY)?;
    assert!(!prepared.is_reflected());
    assert_eq!(prepared.normal_matrix(), Mat4::IDENTITY);
    assert_eq!(prepared.transform_normal(Vec3::Z)?, Vec3::Z);
    assert_eq!(prepared.model().w_axis, Vec4::W);
    Ok(())
}

Structs§

PreparedAffine3D
Validated immutable cache of an affine model, linear inverse transpose and orientation. All accessors return copies, preserving cache invariants.

Enums§

AffineError
Failure from preparation or one scalar affine operation. No identity, zero normal or other fallback is substituted.
AffineSliceError
An atomic slice operation failed before writing any output. Capacity is checked first; otherwise the first failing input index wins.