libbhoo 0.3.0

Minimal UI foundations for SpectreOS
Documentation
//! Homogeneous transforms for mapping a planar surface through perspective.
//!
//! This is geometry only: rendering a textured surface also requires
//! perspective-correct interpolation in the renderer.

/// A row-major 3×3 homography acting on points `[x, y, 1]`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ProjectiveTransform {
    matrix: [[f64; 3]; 3],
}

impl ProjectiveTransform {
    pub const IDENTITY: Self = Self { matrix: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] };

    /// Create a transform from finite homogeneous coefficients.
    pub fn new(matrix: [[f64; 3]; 3]) -> Option<Self> {
        matrix.iter().flatten().all(|value| value.is_finite()).then_some(Self { matrix })
    }

    pub fn coefficients(self) -> [[f64; 3]; 3] { self.matrix }

    /// Project a view's planar rotation using Skia's camera-axis convention.
    /// Angles are in degrees and `camera_distance` is in the same units as
    /// the view coordinates. The caller supplies the platform camera distance.
    pub fn camera_view(pivot: [f64; 2], translation: [f64; 2], scale: [f64; 2],
        rotation: [f64; 3], camera_distance: f64) -> Option<Self> {
        if !camera_distance.is_finite() || camera_distance <= 0.0
            || !pivot.into_iter().chain(translation).chain(scale).chain(rotation).all(f64::is_finite) {
            return None;
        }
        let [x, y, z] = rotation.map(f64::to_radians);
        let (sx, cx) = x.sin_cos();
        let (sy, cy) = y.sin_cos();
        let (sz, cz) = z.sin_cos();
        // Sk3DView concatenates rotations around X, negative Y and negative Z,
        // then projects its X and negative-Y patch vectors through the camera.
        let u = [cy * cz, -cx * sz - sx * sy * cz, -sx * sz + cx * sy * cz];
        let v = [-cy * sz, -cx * cz + sx * sy * sz, -sx * cz - cx * sy * sz];
        let projection = Self::new([[u[0], v[0], 0.0], [-u[1], -v[1], 0.0],
            [u[2] / camera_distance, v[2] / camera_distance, 1.0]])?;
        let local = Self::new([[scale[0], 0.0, -scale[0] * pivot[0]],
            [0.0, scale[1], -scale[1] * pivot[1]], [0.0, 0.0, 1.0]])?;
        let offset = Self::new([[1.0, 0.0, pivot[0] + translation[0]],
            [0.0, 1.0, pivot[1] + translation[1]], [0.0, 0.0, 1.0]])?;
        offset.then(projection)?.then(local)
    }

    /// Compose transforms so `local` is applied before `self`.
    pub fn then(self, local: Self) -> Option<Self> {
        let matrix = std::array::from_fn(|row| std::array::from_fn(|column|
            (0..3).map(|k| self.matrix[row][k] * local.matrix[k][column]).sum()));
        Self::new(matrix)
    }

    /// Map a point, returning `None` at the horizon or for non-finite results.
    pub fn map(self, point: [f64; 2]) -> Option<[f64; 2]> {
        if !point.iter().all(|value| value.is_finite()) { return None; }
        let [x, y] = point;
        let m = self.matrix;
        let w = m[2][0] * x + m[2][1] * y + m[2][2];
        if w == 0.0 || !w.is_finite() { return None; }
        let result = [(m[0][0] * x + m[0][1] * y + m[0][2]) / w,
                      (m[1][0] * x + m[1][1] * y + m[1][2]) / w];
        result.iter().all(|value| value.is_finite()).then_some(result)
    }

    /// Bounds of a rectangle after projection, provided it does not cross the
    /// projective horizon. Crossing rectangles have no finite bounding box.
    pub fn map_rect(self, rect: [f64; 4]) -> Option<[f64; 4]> {
        let [x, y, width, height] = rect;
        if !rect.iter().all(|v| v.is_finite()) || width < 0.0 || height < 0.0 { return None; }
        let mut low = [f64::INFINITY; 2];
        let mut high = [f64::NEG_INFINITY; 2];
        let mut sign = 0.0;
        for px in [x, x + width] {
            for py in [y, y + height] {
                let w = self.matrix[2][0] * px + self.matrix[2][1] * py + self.matrix[2][2];
                if !w.is_finite() || w == 0.0 || (sign != 0.0 && sign != w.signum()) { return None; }
                sign = w.signum();
                let point = self.map([px, py])?;
                for axis in 0..2 { low[axis] = low[axis].min(point[axis]); high[axis] = high[axis].max(point[axis]); }
            }
        }
        Some([low[0], low[1], high[0] - low[0], high[1] - low[1]])
    }

    /// Invert a non-singular transform for mapping pointer input to the surface.
    pub fn inverse(self) -> Option<Self> {
        let [[a, b, c], [d, e, f], [g, h, i]] = self.matrix;
        let adjugate = [[e*i-f*h, c*h-b*i, b*f-c*e],
                        [f*g-d*i, a*i-c*g, c*d-a*f],
                        [d*h-e*g, b*g-a*h, a*e-b*d]];
        let determinant = a*adjugate[0][0] + b*adjugate[1][0] + c*adjugate[2][0];
        if determinant == 0.0 || !determinant.is_finite() { return None; }
        Self::new(adjugate.map(|row| row.map(|value| value / determinant)))
    }
}

#[cfg(test)]
mod tests {
    use super::ProjectiveTransform;

    #[test]
    fn perspective_points_round_trip_and_compose() {
        let perspective = ProjectiveTransform::new([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.01, 0.0, 1.0]]).unwrap();
        let translate = ProjectiveTransform::new([[1.0, 0.0, 5.0], [0.0, 1.0, -3.0], [0.0, 0.0, 1.0]]).unwrap();
        let combined = translate.then(perspective).unwrap();
        assert_eq!(combined.map([100.0, 20.0]), Some([55.0, 7.0]));
        let original = combined.inverse().unwrap().map([55.0, 7.0]).unwrap();
        assert!((original[0] - 100.0).abs() < 1e-10 && (original[1] - 20.0).abs() < 1e-10);
        assert_eq!(perspective.map([-100.0, 0.0]), None);
    }

    #[test]
    fn rejects_singular_and_non_finite_transforms() {
        assert!(ProjectiveTransform::new([[1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]).unwrap().inverse().is_none());
        assert!(ProjectiveTransform::new([[f64::NAN; 3]; 3]).is_none());
    }

    #[test]
    fn projected_bounds_reject_horizon_crossings() {
        let p = ProjectiveTransform::new([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.01, 0.0, 1.0]]).unwrap();
        assert_eq!(p.map_rect([0.0, 0.0, 100.0, 20.0]), Some([0.0, 0.0, 50.0, 20.0]));
        assert_eq!(p.map_rect([-150.0, 0.0, 100.0, 20.0]), None);
        assert_eq!(p.map_rect([0.0, 0.0, -1.0, 20.0]), None);
    }

    #[test]
    fn camera_axes_preserve_pivot_and_project_in_opposite_depths() {
        let x = ProjectiveTransform::camera_view([50.0, 50.0], [3.0, -2.0], [1.0, 1.0], [60.0, 0.0, 0.0], 576.0).unwrap();
        assert_eq!(x.map([50.0, 50.0]), Some([53.0, 48.0]));
        let upper = x.map([50.0, 0.0]).unwrap();
        let lower = x.map([50.0, 100.0]).unwrap();
        assert!(upper[1] > 23.0 && lower[1] > 73.0);
        let y = ProjectiveTransform::camera_view([0.0, 0.0], [0.0, 0.0], [1.0, 1.0], [0.0, 60.0, 0.0], 576.0).unwrap();
        assert!((y.map([100.0, 0.0]).unwrap()[0] - 43.464).abs() < 0.01);
        assert!(ProjectiveTransform::camera_view([0.0; 2], [0.0; 2], [1.0; 2], [0.0; 3], 0.0).is_none());
    }

    #[test]
    fn combined_camera_rotation_matches_skia_probe() {
        // Sk3DView: rotateX(31), rotateY(23), rotateZ(-19), default camera.
        // Reference probe: tools/bhoo-skia-camera-probe.cpp, Skia scalar floats.
        let actual = ProjectiveTransform::camera_view([0.0; 2], [0.0; 2], [1.0; 2],
            [31.0, 23.0, 19.0], 576.0).unwrap().coefficients();
        let skia = [[0.870354414, -0.299687088, 0.0],
                    [0.469343930, 0.744949818, 0.0],
                    [0.000258671702, -0.00103475351, 1.0]];
        for (row, reference) in actual.iter().zip(skia) {
            for (value, expected) in row.iter().zip(reference) {
                assert!((value - expected).abs() < 1e-6, "{value} != {expected}");
            }
        }
    }

    #[test]
    fn camera_pivot_scale_translation_match_android_composition_probe() {
        // The second matrix emitted by tools/bhoo-skia-camera-probe.cpp follows
        // Android RenderProperties' preScale / camera / pivot composition.
        let actual = ProjectiveTransform::camera_view([37.0, 61.0], [8.0, -5.0], [1.3, 0.7],
            [31.0, 23.0, 19.0], 576.0).unwrap().coefficients();
        let reference = [[1.14659297, -0.242375702, 17.3609695],
                         [0.628978431, 0.480902523, 3.39274406],
                         [0.000336273195, -0.000724327459, 1.03174186]];
        for (row, expected_row) in actual.iter().zip(reference) {
            for (value, expected) in row.iter().zip(expected_row) {
                assert!((value - expected).abs() < 1e-5, "{value} != {expected}");
            }
        }
    }
}