1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
#[allow(
5
    clippy::float_cmp,
6
    clippy::unreadable_literal,
7
    clippy::excessive_precision,
8
    clippy::cast_possible_truncation,
9
    clippy::cast_precision_loss,
10
    clippy::too_many_lines,
11
    clippy::needless_range_loop,
12
    clippy::suboptimal_flops,
13
    unused_qualifications
14
)] // adversarial numeric tests: exact FP comparisons and literal matrices are the point
15
mod autotest_generated {
16
    use azul_css::props::{
17
        basic::{AngleValue, FloatValue, PercentageValue, PixelValue, SizeMetric},
18
        style::{
19
            StyleTransformMatrix2D, StyleTransformMatrix3D, StyleTransformRotate3D,
20
            StyleTransformScale2D, StyleTransformScale3D, StyleTransformSkew2D,
21
            StyleTransformTranslate2D, StyleTransformTranslate3D,
22
        },
23
    };
24
    use proptest::{prelude::*, proptest};
25

            
26
    use super::*;
27

            
28
    // ---------------------------------------------------------------- helpers
29

            
30
    /// A matrix whose 16 entries are all `v` — the worst case for any code that
31
    /// assumes a well-formed (invertible / affine) transform.
32
    fn filled(v: f32) -> ComputedTransform3D {
33
        ComputedTransform3D { m: [[v; 4]; 4] }
34
    }
35

            
36
    fn assert_mat_approx(a: &ComputedTransform3D, b: &ComputedTransform3D, tol: f32) {
37
        for r in 0..4 {
38
            for c in 0..4 {
39
                assert!(
40
                    (a.m[r][c] - b.m[r][c]).abs() <= tol,
41
                    "mismatch at [{r}][{c}]: {} vs {} (tol {tol})",
42
                    a.m[r][c],
43
                    b.m[r][c]
44
                );
45
            }
46
        }
47
    }
48

            
49
    fn all_finite(t: &ComputedTransform3D) -> bool {
50
        t.m.iter().flatten().all(|v| v.is_finite())
51
    }
52

            
53
    /// Independent 3x3 determinant (Sarrus) for the reference 4x4 below.
54
    fn det3(m: [[f32; 3]; 3]) -> f32 {
55
        m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
56
            - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
57
            + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
58
    }
59

            
60
    /// Independent 4x4 determinant via cofactor expansion along row 0. This is a
61
    /// deliberately different algorithm from the 24-term expansion in
62
    /// `ComputedTransform3D::determinant`, so agreement is a real cross-check.
63
    fn det4_naive(t: &ComputedTransform3D) -> f32 {
64
        let mut sum = 0.0f32;
65
        for col in 0..4 {
66
            let mut minor = [[0.0f32; 3]; 3];
67
            for r in 1..4 {
68
                let mut cc = 0;
69
                for c in 0..4 {
70
                    if c == col {
71
                        continue;
72
                    }
73
                    minor[r - 1][cc] = t.m[r][c];
74
                    cc += 1;
75
                }
76
            }
77
            let sign = if col % 2 == 0 { 1.0 } else { -1.0 };
78
            sum += sign * t.m[0][col] * det3(minor);
79
        }
80
        sum
81
    }
82

            
83
    /// `row * B` — the reference for the SSE/AVX linear-combination kernels.
84
    /// (Only reachable from the x86_64 / non-Miri tests below.)
85
    #[allow(dead_code)]
86
    fn naive_row_combine(a: [f32; 4], b: &ComputedTransform3D) -> [f32; 4] {
87
        let mut out = [0.0f32; 4];
88
        for c in 0..4 {
89
            for k in 0..4 {
90
                out[c] += a[k] * b.m[k][c];
91
            }
92
        }
93
        out
94
    }
95

            
96
    fn origin_px(x: isize, y: isize) -> StyleTransformOrigin {
97
        StyleTransformOrigin {
98
            x: PixelValue::const_px(x),
99
            y: PixelValue::const_px(y),
100
        }
101
    }
102

            
103
    /// Convenience: run a single `StyleTransform` through the private builder
104
    /// with a zero origin (so rotations are not wrapped in translations).
105
    fn build(t: &StyleTransform, px: f32, py: f32) -> ComputedTransform3D {
106
        ComputedTransform3D::from_style_transform(
107
            t,
108
            &origin_px(0, 0),
109
            px,
110
            py,
111
            RotationMode::ForHitTesting,
112
        )
113
    }
114

            
115
    // ------------------------------------------------------ constructors: new
116

            
117
    #[test]
118
    fn new_stores_all_16_elements_row_major() {
119
        let t = ComputedTransform3D::new(
120
            1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
121
        );
122
        for r in 0..4 {
123
            for c in 0..4 {
124
                let expected = (r * 4 + c + 1) as f32;
125
                assert_eq!(t.m[r][c], expected, "row-major slot [{r}][{c}]");
126
            }
127
        }
128
    }
129

            
130
    #[test]
131
    fn new_preserves_extreme_values_verbatim() {
132
        let t = ComputedTransform3D::new(
133
            f32::NAN,
134
            f32::INFINITY,
135
            f32::NEG_INFINITY,
136
            f32::MAX,
137
            f32::MIN,
138
            f32::MIN_POSITIVE,
139
            -0.0,
140
            0.0,
141
            f32::EPSILON,
142
            -f32::EPSILON,
143
            1e-45, // subnormal
144
            -1e-45,
145
            f32::MAX,
146
            f32::MIN,
147
            f32::INFINITY,
148
            f32::NEG_INFINITY,
149
        );
150
        // The constructor must not sanitize, clamp or panic on any of these.
151
        assert!(t.m[0][0].is_nan());
152
        assert!(t.m[0][1].is_infinite() && t.m[0][1].is_sign_positive());
153
        assert!(t.m[0][2].is_infinite() && t.m[0][2].is_sign_negative());
154
        assert_eq!(t.m[0][3], f32::MAX);
155
        assert_eq!(t.m[1][0], f32::MIN);
156
        assert_eq!(t.m[1][1], f32::MIN_POSITIVE);
157
        // -0.0 must survive as -0.0 (it compares == 0.0, so check the sign bit).
158
        assert!(t.m[1][2].is_sign_negative());
159
        assert!(t.m[1][3].is_sign_positive());
160
        assert_eq!(t.m[2][0], f32::EPSILON);
161
        assert!(t.m[3][2].is_infinite());
162
    }
163

            
164
    #[test]
165
    fn new_2d_matches_css_matrix_layout() {
166
        // matrix(a, b, c, d, tx, ty) => [[a,b,0,0],[c,d,0,0],[0,0,1,0],[tx,ty,0,1]]
167
        let t = ComputedTransform3D::new_2d(2.0, 3.0, 4.0, 5.0, 6.0, 7.0);
168
        assert_eq!(t.m[0], [2.0, 3.0, 0.0, 0.0]);
169
        assert_eq!(t.m[1], [4.0, 5.0, 0.0, 0.0]);
170
        assert_eq!(t.m[2], [0.0, 0.0, 1.0, 0.0]); // Z untouched
171
        assert_eq!(t.m[3], [6.0, 7.0, 0.0, 1.0]);
172
    }
173

            
174
    #[test]
175
    fn new_2d_with_extremes_keeps_z_row_intact() {
176
        let t = ComputedTransform3D::new_2d(
177
            f32::NAN,
178
            f32::INFINITY,
179
            f32::MAX,
180
            f32::MIN,
181
            f32::NEG_INFINITY,
182
            -0.0,
183
        );
184
        assert!(t.m[0][0].is_nan());
185
        // The constant Z row / W column must not be corrupted by extreme args.
186
        assert_eq!(t.m[2], [0.0, 0.0, 1.0, 0.0]);
187
        assert_eq!(t.m[3][3], 1.0);
188
    }
189

            
190
    // -------------------------------------------- constructors: scale / translate
191

            
192
    #[test]
193
    fn new_scale_places_factors_on_the_diagonal() {
194
        let t = ComputedTransform3D::new_scale(2.0, -3.0, 0.5);
195
        assert_eq!(t.m[0][0], 2.0);
196
        assert_eq!(t.m[1][1], -3.0);
197
        assert_eq!(t.m[2][2], 0.5);
198
        assert_eq!(t.m[3][3], 1.0);
199
        // Everything off the diagonal stays zero.
200
        for r in 0..4 {
201
            for c in 0..4 {
202
                if r != c {
203
                    assert_eq!(t.m[r][c], 0.0, "off-diagonal [{r}][{c}]");
204
                }
205
            }
206
        }
207
    }
208

            
209
    #[test]
210
    fn new_scale_zero_is_singular_and_inverse_falls_back_to_identity() {
211
        let z = ComputedTransform3D::new_scale(0.0, 0.0, 0.0);
212
        assert_eq!(z.determinant(), 0.0);
213
        // Documented: a singular matrix inverts to the identity rather than
214
        // producing inf/NaN or panicking.
215
        assert_eq!(z.inverse(), ComputedTransform3D::IDENTITY);
216
    }
217

            
218
    proptest! {
219
        #[test]
220
        fn new_scale_extremes_do_not_panic(v in proptest::num::f32::ANY) {
221
            let t = ComputedTransform3D::new_scale(v, v, v);
222
            assert_eq!(t.m[3][3], 1.0);
223
            assert_eq!(t.m[0][1], 0.0);
224
        }
225
    }
226
    #[test]
227
    fn new_scale_nan() {
228
        let nan = ComputedTransform3D::new_scale(f32::NAN, 1.0, 1.0);
229
        assert!(nan.m[0][0].is_nan());
230
        assert!(nan.determinant().is_nan());
231
    }
232

            
233
    #[test]
234
    fn new_translation_places_offsets_in_last_row() {
235
        let t = ComputedTransform3D::new_translation(10.0, -20.0, 30.0);
236
        assert_eq!(t.m[3], [10.0, -20.0, 30.0, 1.0]);
237
        // The upper-left 3x3 stays the identity.
238
        assert_eq!(t.m[0], [1.0, 0.0, 0.0, 0.0]);
239
        assert_eq!(t.m[1], [0.0, 1.0, 0.0, 0.0]);
240
        assert_eq!(t.m[2], [0.0, 0.0, 1.0, 0.0]);
241
    }
242

            
243
    #[test]
244
    fn new_translation_is_always_invertible_even_at_f32_max() {
245
        let t = ComputedTransform3D::new_translation(f32::MAX, f32::MIN, f32::MAX);
246
        // determinant of a translation is 1 regardless of how big the offsets are
247
        assert_eq!(t.determinant(), 1.0);
248
        let inv = t.inverse();
249
        assert_eq!(inv.m[3][0], -f32::MAX);
250
        assert_eq!(inv.m[3][1], f32::MAX); // -f32::MIN
251
    }
252

            
253
    #[test]
254
    fn new_translation_nan_does_not_poison_the_linear_part() {
255
        let t = ComputedTransform3D::new_translation(f32::NAN, f32::INFINITY, 0.0);
256
        assert!(t.m[3][0].is_nan());
257
        assert!(t.m[3][1].is_infinite());
258
        assert_eq!(t.m[0][0], 1.0);
259
        // determinant only sees the 1.0s and 0.0s of the linear part... except the
260
        // 24-term expansion also multiplies through the translation row, so a NaN
261
        // offset does reach it. Assert the *actual* (defined) behaviour: NaN in,
262
        // NaN out — no panic.
263
        assert!(t.determinant().is_nan() || t.determinant() == 1.0);
264
    }
265

            
266
    // ------------------------------------------- constructors: perspective / skew
267

            
268
    #[test]
269
    fn a_transform_list_composes_like_css_last_function_first() {
270
        // CSS: `translate(100px) scale(2)` SCALES first, then translates:
271
        // (1, 0) -> (2, 0) -> (102, 0). The reversed fold gave (202, 0).
272
        let list = [
273
            StyleTransform::Translate(StyleTransformTranslate2D {
274
                x: PixelValue::px(100.0),
275
                y: PixelValue::px(0.0),
276
            }),
277
            StyleTransform::Scale(StyleTransformScale2D {
278
                x: FloatValue::new(2.0),
279
                y: FloatValue::new(2.0),
280
            }),
281
        ];
282
        let zero = StyleTransformOrigin {
283
            x: PixelValue::px(0.0),
284
            y: PixelValue::px(0.0),
285
        };
286
        let m = ComputedTransform3D::from_style_transform_vec(
287
            &list,
288
            &zero,
289
            0.0,
290
            0.0,
291
            RotationMode::ForHitTesting,
292
        );
293
        let p = m
294
            .transform_point2d(LogicalPosition::new(1.0, 0.0))
295
            .expect("affine");
296
        assert!(
297
            (p.x - 102.0).abs() < 1e-3 && p.y.abs() < 1e-3,
298
            "CSS order: scale then translate, got {p:?}"
299
        );
300

            
301
        // The origin wraps the WHOLE list once: `scale(2)` about the centre
302
        // of a 100x100 box keeps the centre fixed and doubles distances from
303
        // it - (25, 25) -> (0, 0).
304
        let centre = StyleTransformOrigin {
305
            x: PixelValue::const_percent(50),
306
            y: PixelValue::const_percent(50),
307
        };
308
        let m = ComputedTransform3D::from_style_transform_vec(
309
            &list[1..],
310
            &centre,
311
            100.0,
312
            100.0,
313
            RotationMode::ForHitTesting,
314
        );
315
        let c = m
316
            .transform_point2d(LogicalPosition::new(50.0, 50.0))
317
            .expect("affine");
318
        assert!(
319
            (c.x - 50.0).abs() < 1e-3 && (c.y - 50.0).abs() < 1e-3,
320
            "the origin is fixed: {c:?}"
321
        );
322
        let q = m
323
            .transform_point2d(LogicalPosition::new(25.0, 25.0))
324
            .expect("affine");
325
        assert!(
326
            q.x.abs() < 1e-3 && q.y.abs() < 1e-3,
327
            "scale about the centre: {q:?}"
328
        );
329
    }
330

            
331
    #[test]
332
    fn perspective_is_applied_about_the_transform_origin() {
333
        // The CSS idiom `perspective(500px) rotateX(60deg)` about the centre
334
        // of a 200x100 box (CSS order: rotateX applies first, the projection
335
        // last): the centre is fixed, and the vertical centre line STAYS
336
        // vertical (a perspective about (0,0) bends it sideways).
337
        let origin = StyleTransformOrigin {
338
            x: PixelValue::px(100.0),
339
            y: PixelValue::px(50.0),
340
        };
341
        let m = ComputedTransform3D::from_style_transform_vec(
342
            &[
343
                StyleTransform::Perspective(PixelValue::px(500.0)),
344
                StyleTransform::RotateX(AngleValue::deg(60.0)),
345
            ],
346
            &origin,
347
            200.0,
348
            100.0,
349
            RotationMode::ForWebRender,
350
        );
351
        assert!(
352
            !m.is_plane_affine(),
353
            "a tilt under perspective is not affine"
354
        );
355
        let centre = m
356
            .transform_point2d(LogicalPosition::new(100.0, 50.0))
357
            .expect("in front of the eye");
358
        assert!(
359
            (centre.x - 100.0).abs() < 1e-3 && (centre.y - 50.0).abs() < 1e-3,
360
            "{centre:?}"
361
        );
362
        let below = m
363
            .transform_point2d(LogicalPosition::new(100.0, 90.0))
364
            .expect("in front of the eye");
365
        let above = m
366
            .transform_point2d(LogicalPosition::new(100.0, 10.0))
367
            .expect("in front of the eye");
368
        assert!(
369
            (below.x - 100.0).abs() < 1e-3,
370
            "the centre line stays vertical below: {below:?}"
371
        );
372
        assert!((above.x - 100.0).abs() < 1e-3, "…and above: {above:?}");
373
        // the homography row carries the foreshortening
374
        let h = m.plane_homography();
375
        assert!(
376
            h[5].abs() > 1e-6,
377
            "m13 carries the rotateX/perspective term: {h:?}"
378
        );
379
    }
380

            
381
    #[test]
382
    fn new_perspective_finite_distance() {
383
        let t = ComputedTransform3D::new_perspective(100.0);
384
        assert!((t.m[2][3] - (-0.01)).abs() < 1e-6);
385
        assert_eq!(t.m[0][0], 1.0);
386
        assert_eq!(t.m[3][3], 1.0);
387
    }
388

            
389
    #[test]
390
    fn new_perspective_zero_distance_divides_by_zero() {
391
        // -1.0 / 0.0 is -inf in IEEE-754: no panic, but the matrix is unusable.
392
        // This is the documented (if hazardous) behaviour of `perspective(0)`.
393
        let t = ComputedTransform3D::new_perspective(0.0);
394
        assert!(t.m[2][3].is_infinite() && t.m[2][3].is_sign_negative());
395
        assert!(!all_finite(&t));
396
    }
397

            
398
    #[test]
399
    fn new_perspective_extreme_distances_do_not_panic() {
400
        let nan = ComputedTransform3D::new_perspective(f32::NAN);
401
        assert!(nan.m[2][3].is_nan());
402

            
403
        let inf = ComputedTransform3D::new_perspective(f32::INFINITY);
404
        assert_eq!(inf.m[2][3], -0.0); // -1/inf == -0.0 => equals the identity
405
        assert!(all_finite(&inf));
406

            
407
        // -1 / (smallest subnormal) overflows f32 => -inf, still no panic.
408
        let tiny = ComputedTransform3D::new_perspective(1e-45);
409
        assert!(tiny.m[2][3].is_infinite() && tiny.m[2][3].is_sign_negative());
410
    }
411

            
412
    #[test]
413
    fn new_skew_45_degrees_is_unit_shear() {
414
        // new_skew(alpha, beta): m[1][0] = tan(alpha), m[0][1] = tan(beta)
415
        let t = ComputedTransform3D::new_skew(45.0, 0.0);
416
        assert!(
417
            (t.m[1][0] - 1.0).abs() < 1e-5,
418
            "tan(45deg) ~= 1, got {}",
419
            t.m[1][0]
420
        );
421
        assert_eq!(t.m[0][1], 0.0);
422
        assert_eq!(t.m[0][0], 1.0);
423
        assert_eq!(t.m[1][1], 1.0);
424
        // A unit shear preserves area.
425
        assert!((t.determinant() - 1.0).abs() < 1e-4);
426
    }
427

            
428
    #[test]
429
    fn new_skew_90_degrees_stays_finite() {
430
        // tan(pi/2) is not representable; f32's rounded pi/2 makes tan() a huge
431
        // (but finite) number rather than inf. Assert it does not panic and that
432
        // nothing becomes NaN/inf.
433
        let t = ComputedTransform3D::new_skew(90.0, 90.0);
434
        assert!(
435
            all_finite(&t),
436
            "skew(90deg) produced a non-finite entry: {t:?}"
437
        );
438
        assert!(
439
            t.m[1][0].abs() > 1e6,
440
            "expected a huge shear, got {}",
441
            t.m[1][0]
442
        );
443
    }
444

            
445
    #[test]
446
    fn new_skew_nan_and_infinite_angles_do_not_panic() {
447
        let nan = ComputedTransform3D::new_skew(f32::NAN, 0.0);
448
        assert!(nan.m[1][0].is_nan());
449
        assert_eq!(nan.m[3][3], 1.0);
450

            
451
        // tan(inf) is NaN, not a panic.
452
        let inf = ComputedTransform3D::new_skew(f32::INFINITY, f32::NEG_INFINITY);
453
        assert!(inf.m[1][0].is_nan());
454
        assert!(inf.m[0][1].is_nan());
455
    }
456

            
457
    // --------------------------------------------------- constructors: rotation
458

            
459
    #[test]
460
    fn new_rotation_zero_angle_is_identity() {
461
        let t = ComputedTransform3D::new_rotation(0.0, 0.0, 1.0, 0.0);
462
        assert_mat_approx(&t, &ComputedTransform3D::IDENTITY, 1e-6);
463
    }
464

            
465
    #[test]
466
    fn new_rotation_quarter_turn_about_z() {
467
        let t = ComputedTransform3D::new_rotation(0.0, 0.0, 1.0, core::f32::consts::FRAC_PI_2);
468
        // sq = sin^2(pi/4) = 0.5, sc = sin*cos(pi/4) = 0.5
469
        assert!((t.m[0][0] - 0.0).abs() < 1e-6);
470
        assert!((t.m[0][1] - 1.0).abs() < 1e-6);
471
        assert!((t.m[1][0] - -1.0).abs() < 1e-6);
472
        assert!((t.m[1][1] - 0.0).abs() < 1e-6);
473
        assert_eq!(t.m[2][2], 1.0);
474
    }
475

            
476
    #[test]
477
    fn new_rotation_is_orthonormal_and_det_one() {
478
        // Normalized axis, as the doc requires.
479
        let (x, y, z) = (0.267_261_24, 0.534_522_5, 0.801_783_7); // (1,2,3)/|(1,2,3)|
480
        let t = ComputedTransform3D::new_rotation(x, y, z, 0.7);
481
        assert!(
482
            (t.determinant() - 1.0).abs() < 1e-4,
483
            "det = {}",
484
            t.determinant()
485
        );
486
        for r in 0..3 {
487
            let len_sq = t.m[r][0] * t.m[r][0] + t.m[r][1] * t.m[r][1] + t.m[r][2] * t.m[r][2];
488
            assert!(
489
                (len_sq - 1.0).abs() < 1e-4,
490
                "row {r} is not unit length: {len_sq}"
491
            );
492
        }
493
        // For a pure rotation, inverse == transpose.
494
        assert_mat_approx(&t.inverse(), &t.get_column_major(), 1e-4);
495
    }
496

            
497
    #[test]
498
    fn new_rotation_degenerate_zero_axis_yields_identity() {
499
        // The doc says the axis "must be normalized"; a zero axis is the classic
500
        // caller mistake. It must not panic or produce NaN — it degenerates to
501
        // the identity (every term is multiplied by an axis component).
502
        let t = ComputedTransform3D::new_rotation(0.0, 0.0, 0.0, 1.234);
503
        assert_mat_approx(&t, &ComputedTransform3D::IDENTITY, 1e-6);
504
    }
505

            
506
    #[test]
507
    fn new_rotation_nan_and_infinite_theta_do_not_panic() {
508
        let nan = ComputedTransform3D::new_rotation(0.0, 0.0, 1.0, f32::NAN);
509
        assert!(nan.m[0][0].is_nan());
510
        assert_eq!(nan.m[3][3], 1.0); // the constant W row survives
511

            
512
        // sin(inf) / cos(inf) are NaN in IEEE-754 — again, no panic.
513
        let inf = ComputedTransform3D::new_rotation(0.0, 0.0, 1.0, f32::INFINITY);
514
        assert!(inf.m[0][0].is_nan());
515
    }
516

            
517
    #[test]
518
    fn new_rotation_huge_theta_stays_bounded() {
519
        // A rotation matrix must stay in [-1, 1] no matter how absurd the angle.
520
        let t = ComputedTransform3D::new_rotation(0.0, 0.0, 1.0, 1e9);
521
        assert!(all_finite(&t));
522
        for r in 0..3 {
523
            for c in 0..3 {
524
                assert!(
525
                    t.m[r][c].abs() <= 1.001,
526
                    "entry [{r}][{c}] = {} escaped [-1,1]",
527
                    t.m[r][c]
528
                );
529
            }
530
        }
531
    }
532

            
533
    // ------------------------------------------------------------- determinant
534

            
535
    #[test]
536
    fn determinant_of_identity_is_one() {
537
        assert_eq!(ComputedTransform3D::IDENTITY.determinant(), 1.0);
538
    }
539

            
540
    #[test]
541
    fn determinant_of_diagonal_is_product() {
542
        let t = ComputedTransform3D::new(
543
            2.0, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0, 5.0,
544
        );
545
        assert_eq!(t.determinant(), 120.0);
546
    }
547

            
548
    #[test]
549
    fn determinant_matches_independent_cofactor_expansion() {
550
        let t = ComputedTransform3D::new(
551
            3.0, 1.0, 0.0, 2.0, 0.0, 2.0, 1.0, 1.0, 1.0, 0.0, 4.0, 0.0, 2.0, 1.0, 1.0, 3.0,
552
        );
553
        let got = t.determinant();
554
        let want = det4_naive(&t);
555
        assert!(
556
            (got - want).abs() < 1e-3,
557
            "determinant() = {got}, cofactor ref = {want}"
558
        );
559
    }
560

            
561
    #[test]
562
    fn determinant_of_singular_matrices_is_zero() {
563
        // All-zero matrix.
564
        assert_eq!(filled(0.0).determinant(), 0.0);
565
        // Two identical rows => rank-deficient. Small integers keep the products
566
        // exact, so the cancellation is exact too.
567
        let dup = ComputedTransform3D::new(
568
            1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0, 4.0, 0.0, 1.0, 0.0, 2.0, 4.0, 3.0, 2.0, 1.0,
569
        );
570
        assert!(
571
            dup.determinant().abs() < 1e-4,
572
            "det = {}",
573
            dup.determinant()
574
        );
575
        // A matrix where every entry is the same is also singular.
576
        assert!(filled(7.0).determinant().abs() < 1e-2);
577
    }
578

            
579
    #[test]
580
    fn determinant_overflows_to_infinity_rather_than_wrapping() {
581
        // diag(1e20)^4 = 1e80, far beyond f32::MAX (~3.4e38): saturates to +inf.
582
        let big = ComputedTransform3D::new_scale(1e20, 1e20, 1e20);
583
        let mut big = big;
584
        big.m[3][3] = 1e20;
585
        let det = big.determinant();
586
        assert!(det.is_infinite() && det.is_sign_positive(), "det = {det}");
587
    }
588

            
589
    #[test]
590
    fn determinant_of_nan_matrix_is_nan_not_a_panic() {
591
        assert!(filled(f32::NAN).determinant().is_nan());
592
    }
593

            
594
    // ----------------------------------------------------------------- inverse
595

            
596
    #[test]
597
    fn inverse_of_identity_is_identity() {
598
        assert_mat_approx(
599
            &ComputedTransform3D::IDENTITY.inverse(),
600
            &ComputedTransform3D::IDENTITY,
601
            1e-6,
602
        );
603
    }
604

            
605
    #[test]
606
    fn inverse_round_trips_to_identity() {
607
        let t = ComputedTransform3D::new_translation(10.0, 20.0, 30.0)
608
            .then(&ComputedTransform3D::new_scale(2.0, 4.0, 8.0));
609
        assert_mat_approx(&t.then(&t.inverse()), &ComputedTransform3D::IDENTITY, 1e-4);
610
        assert_mat_approx(&t.inverse().then(&t), &ComputedTransform3D::IDENTITY, 1e-4);
611
    }
612

            
613
    #[test]
614
    fn inverse_of_singular_matrix_returns_identity() {
615
        assert_eq!(filled(0.0).inverse(), ComputedTransform3D::IDENTITY);
616
        assert_eq!(
617
            ComputedTransform3D::new_scale(1.0, 1.0, 0.0).inverse(),
618
            ComputedTransform3D::IDENTITY
619
        );
620
    }
621

            
622
    #[test]
623
    fn inverse_treats_near_singular_as_singular() {
624
        // PRECISION HAZARD, asserted as the documented contract: the guard is
625
        // `det.abs() < f32::EPSILON` (~1.19e-7), so a *perfectly invertible*
626
        // uniform scale of 1e-3 (det = 1e-9) is rejected and the identity is
627
        // returned instead of the true inverse (a 1000x up-scale).
628
        let tiny = ComputedTransform3D::new_scale(1e-3, 1e-3, 1e-3);
629
        let det = tiny.determinant();
630
        assert!(
631
            det > 0.0 && det < f32::EPSILON,
632
            "det = {det} (must be a nonzero sub-EPSILON)"
633
        );
634
        assert_eq!(tiny.inverse(), ComputedTransform3D::IDENTITY);
635
    }
636

            
637
    #[test]
638
    fn inverse_of_nan_matrix_does_not_panic() {
639
        // det is NaN, and `NaN.abs() < EPSILON` is false, so the singular guard
640
        // does NOT catch it: the algorithm runs and yields an all-NaN matrix.
641
        let inv = filled(f32::NAN).inverse();
642
        assert!(inv.m.iter().flatten().all(|v| v.is_nan()));
643
    }
644

            
645
    #[test]
646
    fn inverse_of_overflowing_matrix_yields_nan_not_a_panic() {
647
        // det = +inf => scale factor 1/inf = 0.0 => cofactor(inf) * 0.0 = NaN.
648
        let mut big = ComputedTransform3D::new_scale(1e20, 1e20, 1e20);
649
        big.m[3][3] = 1e20;
650
        let inv = big.inverse();
651
        assert!(
652
            inv.m[0][0].is_nan(),
653
            "expected NaN from inf * 0.0, got {}",
654
            inv.m[0][0]
655
        );
656
    }
657

            
658
    // ------------------------------------------------------- multiply_scalar
659

            
660
    #[test]
661
    fn multiply_scalar_by_zero_zeroes_every_entry() {
662
        let t = ComputedTransform3D::IDENTITY.multiply_scalar(0.0);
663
        assert!(t.m.iter().flatten().all(|v| *v == 0.0));
664
    }
665

            
666
    #[test]
667
    fn multiply_scalar_is_sign_and_magnitude_exact() {
668
        let t = ComputedTransform3D::new_scale(2.0, 3.0, 4.0).multiply_scalar(-1.0);
669
        assert_eq!(t.m[0][0], -2.0);
670
        assert_eq!(t.m[1][1], -3.0);
671
        assert_eq!(t.m[2][2], -4.0);
672
        assert_eq!(t.m[3][3], -1.0);
673

            
674
        let m = ComputedTransform3D::IDENTITY.multiply_scalar(f32::MAX);
675
        assert_eq!(m.m[0][0], f32::MAX);
676
        assert_eq!(m.m[0][1], 0.0);
677
    }
678

            
679
    #[test]
680
    fn multiply_scalar_overflow_saturates_to_infinity() {
681
        let t = filled(1e30).multiply_scalar(1e30);
682
        assert!(t
683
            .m
684
            .iter()
685
            .flatten()
686
            .all(|v| v.is_infinite() && v.is_sign_positive()));
687
    }
688

            
689
    #[test]
690
    fn multiply_scalar_by_infinity_poisons_zero_entries_with_nan() {
691
        // IEEE-754: 0.0 * inf == NaN. Scaling the IDENTITY by inf therefore does
692
        // NOT give an "infinitely scaled identity" — every off-diagonal 0 becomes
693
        // NaN. Asserted so a future refactor cannot silently change it.
694
        let t = ComputedTransform3D::IDENTITY.multiply_scalar(f32::INFINITY);
695
        assert!(t.m[0][0].is_infinite());
696
        assert!(
697
            t.m[0][1].is_nan(),
698
            "0.0 * inf should be NaN, got {}",
699
            t.m[0][1]
700
        );
701
    }
702

            
703
    #[test]
704
    fn multiply_scalar_by_nan_makes_everything_nan() {
705
        let t = ComputedTransform3D::new_scale(2.0, 3.0, 4.0).multiply_scalar(f32::NAN);
706
        assert!(t.m.iter().flatten().all(|v| v.is_nan()));
707
    }
708

            
709
    // ------------------------------------------------------ get_column_major
710

            
711
    #[test]
712
    fn get_column_major_transposes() {
713
        let t = ComputedTransform3D::new(
714
            1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
715
        );
716
        let c = t.get_column_major();
717
        for r in 0..4 {
718
            for col in 0..4 {
719
                assert_eq!(c.m[r][col], t.m[col][r], "transpose slot [{r}][{col}]");
720
            }
721
        }
722
    }
723

            
724
    #[test]
725
    fn get_column_major_is_an_involution() {
726
        let t = ComputedTransform3D::new_translation(3.0, -4.0, 5.0)
727
            .then(&ComputedTransform3D::new_scale(2.0, 2.0, 2.0));
728
        assert_eq!(t.get_column_major().get_column_major(), t);
729
        // The identity is its own transpose.
730
        assert_eq!(
731
            ComputedTransform3D::IDENTITY.get_column_major(),
732
            ComputedTransform3D::IDENTITY
733
        );
734
    }
735

            
736
    #[test]
737
    fn get_column_major_moves_translation_into_the_last_column() {
738
        let t = ComputedTransform3D::new_translation(7.0, 8.0, 9.0).get_column_major();
739
        assert_eq!(t.m[0][3], 7.0);
740
        assert_eq!(t.m[1][3], 8.0);
741
        assert_eq!(t.m[2][3], 9.0);
742
        assert_eq!(t.m[3], [0.0, 0.0, 0.0, 1.0]);
743
    }
744

            
745
    #[test]
746
    fn get_column_major_of_nan_matrix_does_not_panic() {
747
        let t = filled(f32::NAN).get_column_major();
748
        assert!(t.m.iter().flatten().all(|v| v.is_nan()));
749
    }
750

            
751
    // ----------------------------------------------------- transform_point2d
752

            
753
    #[test]
754
    fn transform_point2d_identity_is_the_point_itself() {
755
        let p = LogicalPosition::new(3.0, -4.0);
756
        let out = ComputedTransform3D::IDENTITY.transform_point2d(p).unwrap();
757
        assert_eq!(out.x, 3.0);
758
        assert_eq!(out.y, -4.0);
759

            
760
        let zero = ComputedTransform3D::IDENTITY
761
            .transform_point2d(LogicalPosition::zero())
762
            .unwrap();
763
        assert_eq!((zero.x, zero.y), (0.0, 0.0));
764
    }
765

            
766
    #[test]
767
    fn transform_point2d_applies_translation_and_scale() {
768
        let t = ComputedTransform3D::new_translation(10.0, 20.0, 0.0);
769
        let out = t.transform_point2d(LogicalPosition::new(1.0, 2.0)).unwrap();
770
        assert_eq!((out.x, out.y), (11.0, 22.0));
771

            
772
        let s = ComputedTransform3D::new_scale(2.0, -3.0, 1.0);
773
        let out = s.transform_point2d(LogicalPosition::new(1.5, 2.0)).unwrap();
774
        assert_eq!((out.x, out.y), (3.0, -6.0));
775
    }
776

            
777
    #[test]
778
    fn transform_point2d_negative_w_returns_none() {
779
        let mut t = ComputedTransform3D::IDENTITY;
780
        t.m[3][3] = -1.0; // w = -1
781
        assert!(t
782
            .transform_point2d(LogicalPosition::new(1.0, 1.0))
783
            .is_none());
784

            
785
        // w driven negative by the point itself (perspective-style m[0][3]).
786
        let mut p = ComputedTransform3D::IDENTITY;
787
        p.m[0][3] = -1.0; // w = 1 - p.x
788
        assert!(p
789
            .transform_point2d(LogicalPosition::new(2.0, 0.0))
790
            .is_none());
791
        assert!(p
792
            .transform_point2d(LogicalPosition::new(0.5, 0.0))
793
            .is_some());
794
    }
795

            
796
    #[test]
797
    fn transform_point2d_zero_w_divides_by_zero_instead_of_returning_none() {
798
        // BOUNDARY: the guard is `!w.is_sign_positive()`, and (+0.0) IS
799
        // sign-positive — so a fully degenerate w == +0.0 slips through and the
800
        // function divides by zero, returning Some(inf, inf) rather than None.
801
        // Asserted as-is (no panic, defined IEEE result); flagged in the report.
802
        let mut t = ComputedTransform3D::IDENTITY;
803
        t.m[3][3] = 0.0;
804
        let out = t.transform_point2d(LogicalPosition::new(1.0, 1.0));
805
        let out = out.expect("w == +0.0 is treated as a valid positive w");
806
        assert!(out.x.is_infinite(), "expected 1.0/0.0 = inf, got {}", out.x);
807
        assert!(out.y.is_infinite());
808

            
809
        // ... whereas a w that comes out as -0.0 IS rejected, so the sign of a
810
        // zero w decides between Some(inf) and None. (The whole w column must be
811
        // -0.0: fma(1.0, +0.0, -0.0) would round back to +0.0.)
812
        let mut neg = ComputedTransform3D::IDENTITY;
813
        neg.m[0][3] = -0.0;
814
        neg.m[1][3] = -0.0;
815
        neg.m[3][3] = -0.0;
816
        assert!(neg
817
            .transform_point2d(LogicalPosition::new(1.0, 1.0))
818
            .is_none());
819
    }
820

            
821
    #[test]
822
    fn transform_point2d_nan_matrix_does_not_panic() {
823
        let out = filled(f32::NAN).transform_point2d(LogicalPosition::new(1.0, 1.0));
824
        // w is NaN; whichever branch the sign bit lands on, neither may panic.
825
        if let Some(p) = out {
826
            assert!(p.x.is_nan() && p.y.is_nan());
827
        }
828
    }
829

            
830
    #[test]
831
    fn transform_point2d_nan_point_does_not_panic() {
832
        let out = ComputedTransform3D::IDENTITY
833
            .transform_point2d(LogicalPosition::new(f32::NAN, f32::NAN));
834
        // w = NaN*0 + (NaN*0 + 1) = NaN => no panic either way.
835
        if let Some(p) = out {
836
            assert!(p.x.is_nan());
837
        }
838
    }
839

            
840
    #[test]
841
    fn transform_point2d_extreme_coordinates_saturate() {
842
        let t = ComputedTransform3D::new_translation(10.0, 10.0, 0.0);
843
        let out = t
844
            .transform_point2d(LogicalPosition::new(f32::MAX, f32::MIN))
845
            .unwrap();
846
        assert_eq!(out.x, f32::MAX); // MAX + 10 rounds back to MAX
847
        assert_eq!(out.y, f32::MIN);
848

            
849
        // A scale big enough to overflow saturates to inf, it does not wrap.
850
        let s = ComputedTransform3D::new_scale(1e30, 1e30, 1.0);
851
        let out = s
852
            .transform_point2d(LogicalPosition::new(1e30, 1e30))
853
            .unwrap();
854
        assert!(out.x.is_infinite() && out.x.is_sign_positive());
855
    }
856

            
857
    // --------------------------------------------------------- scale_for_dpi
858

            
859
    #[test]
860
    fn scale_for_dpi_touches_only_the_translation_row() {
861
        let mut t = ComputedTransform3D::new(
862
            1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
863
        );
864
        let before = t;
865
        t.scale_for_dpi(3.0);
866
        assert_eq!(t.m[0], before.m[0]);
867
        assert_eq!(t.m[1], before.m[1]);
868
        assert_eq!(t.m[2], before.m[2]);
869
        assert_eq!(t.m[3][0], 39.0);
870
        assert_eq!(t.m[3][1], 42.0);
871
        assert_eq!(t.m[3][2], 45.0);
872
        assert_eq!(t.m[3][3], 16.0, "m44 must NOT be scaled");
873
    }
874

            
875
    #[test]
876
    fn scale_for_dpi_zero_and_negative() {
877
        let mut t = ComputedTransform3D::new_translation(10.0, 20.0, 30.0);
878
        t.scale_for_dpi(0.0);
879
        assert_eq!(t.m[3], [0.0, 0.0, 0.0, 1.0]);
880

            
881
        let mut n = ComputedTransform3D::new_translation(10.0, -20.0, 30.0);
882
        n.scale_for_dpi(-2.0);
883
        assert_eq!(n.m[3], [-20.0, 40.0, -60.0, 1.0]);
884
    }
885

            
886
    #[test]
887
    fn scale_for_dpi_is_exactly_reversible_for_powers_of_two() {
888
        let original = ComputedTransform3D::new_translation(13.25, -7.5, 0.125);
889
        let mut t = original;
890
        t.scale_for_dpi(2.0);
891
        t.scale_for_dpi(0.5);
892
        assert_eq!(t, original);
893
    }
894

            
895
    #[test]
896
    fn scale_for_dpi_overflow_saturates_to_infinity() {
897
        let mut t = ComputedTransform3D::new_translation(1e38, -1e38, 1e38);
898
        t.scale_for_dpi(1e5);
899
        assert!(t.m[3][0].is_infinite() && t.m[3][0].is_sign_positive());
900
        assert!(t.m[3][1].is_infinite() && t.m[3][1].is_sign_negative());
901
        assert_eq!(t.m[3][3], 1.0);
902
    }
903

            
904
    #[test]
905
    fn scale_for_dpi_by_infinity_poisons_a_zero_translation() {
906
        // IEEE-754: 0.0 * inf == NaN. A DPI factor of inf turns the *identity's*
907
        // zero translation into NaN — assert the defined result, no panic.
908
        let mut t = ComputedTransform3D::IDENTITY;
909
        t.scale_for_dpi(f32::INFINITY);
910
        assert!(t.m[3][0].is_nan());
911
        assert_eq!(t.m[0][0], 1.0, "the linear part must stay untouched");
912

            
913
        let mut n = ComputedTransform3D::new_translation(1.0, 2.0, 3.0);
914
        n.scale_for_dpi(f32::INFINITY);
915
        assert!(n.m[3][0].is_infinite());
916
    }
917

            
918
    #[test]
919
    fn scale_for_dpi_by_nan_does_not_panic() {
920
        let mut t = ComputedTransform3D::new_translation(1.0, 2.0, 3.0);
921
        t.scale_for_dpi(f32::NAN);
922
        assert!(t.m[3][0].is_nan() && t.m[3][1].is_nan() && t.m[3][2].is_nan());
923
        assert_eq!(t.m[3][3], 1.0);
924
        assert_eq!(t.m[0][0], 1.0);
925
    }
926

            
927
    // -------------------------------------------------------------------- then
928

            
929
    #[test]
930
    fn then_has_identity_as_a_two_sided_unit() {
931
        let a = ComputedTransform3D::new(
932
            1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
933
        );
934
        assert_mat_approx(&a.then(&ComputedTransform3D::IDENTITY), &a, 1e-4);
935
        assert_mat_approx(&ComputedTransform3D::IDENTITY.then(&a), &a, 1e-4);
936
    }
937

            
938
    #[test]
939
    fn then_composes_translations_additively_and_scales_multiplicatively() {
940
        let t = ComputedTransform3D::new_translation(1.0, 2.0, 3.0)
941
            .then(&ComputedTransform3D::new_translation(10.0, 20.0, 30.0));
942
        assert_eq!(t.m[3], [11.0, 22.0, 33.0, 1.0]);
943

            
944
        let s = ComputedTransform3D::new_scale(2.0, 3.0, 4.0)
945
            .then(&ComputedTransform3D::new_scale(5.0, 7.0, 11.0));
946
        assert_eq!(s.m[0][0], 10.0);
947
        assert_eq!(s.m[1][1], 21.0);
948
        assert_eq!(s.m[2][2], 44.0);
949
    }
950

            
951
    #[test]
952
    fn then_is_associative() {
953
        let a = ComputedTransform3D::new(
954
            1.0, 0.5, 0.0, 0.0, -0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 2.0, 3.0, 0.0, 1.0,
955
        );
956
        let b = ComputedTransform3D::new_scale(2.0, 0.5, 1.0);
957
        let c = ComputedTransform3D::new_translation(-1.0, 4.0, 0.0);
958
        assert_mat_approx(&a.then(&b).then(&c), &a.then(&b.then(&c)), 1e-2);
959
    }
960

            
961
    #[test]
962
    fn then_with_extreme_matrices_does_not_panic() {
963
        let big = filled(1e30).then(&filled(1e30));
964
        assert!(
965
            big.m[0][0].is_infinite(),
966
            "expected overflow to inf, got {}",
967
            big.m[0][0]
968
        );
969

            
970
        let nan = filled(f32::NAN).then(&ComputedTransform3D::IDENTITY);
971
        assert!(nan.m.iter().flatten().all(|v| v.is_nan()));
972

            
973
        // inf * 0 inside the dot product => NaN, not a panic.
974
        let mixed = filled(f32::INFINITY).then(&ComputedTransform3D::IDENTITY);
975
        assert!(mixed.m[0][0].is_infinite() || mixed.m[0][0].is_nan());
976
    }
977

            
978
    // ------------------------------------------------ SIMD paths (x86_64 only)
979

            
980
    // `not(miri)`: Miri cannot execute SSE/AVX intrinsics.
981
    #[cfg(all(target_arch = "x86_64", not(miri)))]
982
    proptest! {
983
        #[test]
984
        fn linear_combine_sse_matches_naive_row_combine(
985
            a0 in proptest::num::f32::ANY, a1 in proptest::num::f32::ANY,
986
            a2 in proptest::num::f32::ANY, a3 in proptest::num::f32::ANY
987
        ) {
988
            if !std::is_x86_feature_detected!("sse") {
989
                return Ok(());
990
            }
991
            let b = ComputedTransform3D::new(
992
                1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
993
            );
994
            let a = [a0, a1, a2, a3];
995
            // SAFETY: SSE availability was just checked at runtime.
996
            let got = unsafe { ComputedTransform3D::linear_combine_sse(a, &b) };
997
            let want = naive_row_combine(a, &b);
998
            for c in 0..4 {
999
                let tol = 1e-3 * want[c].abs().max(1.0);
                // Proptest might generate infinite values, which we don't want to fail if they perfectly match.
                if !want[c].is_finite() && !got[c].is_finite() { continue; }
                assert!(
                    (got[c] - want[c]).abs() <= tol || (got[c].is_nan() && want[c].is_nan()),
                    "lane {c}: {} vs {}",
                    got[c],
                    want[c]
                );
            }
        }
    }
    #[cfg(all(target_arch = "x86_64", not(miri)))]
    #[test]
    fn linear_combine_sse_propagates_nan_per_lane() {
        if !std::is_x86_feature_detected!("sse") {
            return;
        }
        // SAFETY: SSE availability was just checked at runtime.
        let got = unsafe {
            ComputedTransform3D::linear_combine_sse([f32::NAN; 4], &ComputedTransform3D::IDENTITY)
        };
        assert!(
            got.iter().all(|v| v.is_nan()),
            "NaN must survive the SIMD path: {got:?}"
        );
    }
    #[cfg(all(target_arch = "x86_64", not(miri)))]
    #[test]
    fn then_sse_and_then_avx8_agree_with_scalar_then() {
        let a = ComputedTransform3D::new(
            1.0, 0.5, -2.0, 0.0, 3.0, 1.0, 0.0, 0.25, 0.0, -1.0, 4.0, 0.0, 5.0, 6.0, 7.0, 1.0,
        );
        let b = ComputedTransform3D::new(
            2.0, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, -4.0, 2.0, 0.5, 1.0,
        );
        let scalar = a.then(&b);
        if std::is_x86_feature_detected!("sse") {
            // SAFETY: SSE availability was just checked at runtime.
            let sse = unsafe { a.then_sse(&b) };
            assert_mat_approx(&scalar, &sse, 1e-3);
            // Identity is still a unit through the SIMD path.
            // SAFETY: same runtime check as above.
            let unit = unsafe { ComputedTransform3D::IDENTITY.then_sse(&b) };
            assert_mat_approx(&unit, &b, 1e-4);
        }
        if std::is_x86_feature_detected!("avx") {
            // SAFETY: AVX availability was just checked at runtime.
            let avx = unsafe { a.then_avx8(&b) };
            assert_mat_approx(&scalar, &avx, 1e-3);
            // SAFETY: same runtime check as above.
            let unit = unsafe { ComputedTransform3D::IDENTITY.then_avx8(&b) };
            assert_mat_approx(&unit, &b, 1e-4);
        }
    }
    #[cfg(all(target_arch = "x86_64", not(miri)))]
    #[test]
    fn simd_paths_do_not_panic_on_extreme_matrices() {
        // NaN/inf must flow through the intrinsics exactly like the scalar path:
        // no trap, no panic. (Values are not compared against the scalar path
        // because `then` fuses with mul_add while the SIMD kernels do not, and
        // fusion legitimately changes which NaN/inf a saturating term produces.)
        let extremes = [
            filled(f32::NAN),
            filled(f32::INFINITY),
            filled(1e30),
            filled(f32::MIN),
        ];
        for a in &extremes {
            for b in &extremes {
                if std::is_x86_feature_detected!("sse") {
                    // SAFETY: SSE availability was just checked at runtime.
                    let r = unsafe { a.then_sse(b) };
                    core::hint::black_box(r);
                }
                if std::is_x86_feature_detected!("avx") {
                    // SAFETY: AVX availability was just checked at runtime.
                    let r = unsafe { a.then_avx8(b) };
                    core::hint::black_box(r);
                }
            }
        }
    }
    #[cfg(all(target_arch = "x86_64", not(miri)))]
    #[test]
    fn linear_combine_avx8_computes_two_rows_at_once() {
        use core::arch::x86_64::{_mm256_loadu_ps, _mm256_storeu_ps};
        if !std::is_x86_feature_detected!("avx") {
            return;
        }
        let b = ComputedTransform3D::new(
            1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
        );
        let row0 = [1.0f32, 0.0, -2.0, 3.0];
        let row1 = [0.5f32, 4.0, 0.0, -1.0];
        let packed: [f32; 8] = [
            row0[0], row0[1], row0[2], row0[3], row1[0], row1[1], row1[2], row1[3],
        ];
        let mut out = [0.0f32; 8];
        // SAFETY: AVX availability was just checked at runtime; `packed`/`out` are
        // live 8-f32 locals and both intrinsics used here are *unaligned* accesses.
        unsafe {
            let a01 = _mm256_loadu_ps(packed.as_ptr());
            let res = ComputedTransform3D::linear_combine_avx8(a01, &b);
            _mm256_storeu_ps(out.as_mut_ptr(), res);
        }
        let want0 = naive_row_combine(row0, &b);
        let want1 = naive_row_combine(row1, &b);
        for c in 0..4 {
            assert!(
                (out[c] - want0[c]).abs() < 1e-3,
                "low lane {c}: {} vs {}",
                out[c],
                want0[c]
            );
            assert!(
                (out[4 + c] - want1[c]).abs() < 1e-3,
                "high lane {c}: {} vs {}",
                out[4 + c],
                want1[c]
            );
        }
    }
    // ------------------------------------------------ from_style_transform_vec
    #[test]
    fn from_style_transform_vec_empty_is_identity() {
        let t = ComputedTransform3D::from_style_transform_vec(
            &[],
            &StyleTransformOrigin::default(),
            100.0,
            100.0,
            RotationMode::ForWebRender,
        );
        assert_eq!(t, ComputedTransform3D::IDENTITY);
    }
    #[test]
    fn from_style_transform_vec_accumulates_a_thousand_translations_exactly() {
        // 1000 x translateX(1px): integer translations compose exactly on every
        // code path (scalar, SSE, AVX), so this must land on exactly 1000.0.
        let list = vec![StyleTransform::TranslateX(PixelValue::const_px(1)); 1000];
        let t = ComputedTransform3D::from_style_transform_vec(
            &list,
            &StyleTransformOrigin::default(),
            0.0,
            0.0,
            RotationMode::ForHitTesting,
        );
        assert_eq!(t.m[3][0], 1000.0);
        assert_eq!(t.m[3][1], 0.0);
        assert_eq!(t.m[0][0], 1.0);
    }
    #[test]
    fn from_style_transform_vec_resolves_percentages_against_each_axis() {
        let list = vec![
            StyleTransform::TranslateX(PixelValue::const_percent(50)),
            StyleTransform::TranslateY(PixelValue::const_percent(50)),
        ];
        let t = ComputedTransform3D::from_style_transform_vec(
            &list,
            &StyleTransformOrigin::default(),
            200.0,
            80.0,
            RotationMode::ForHitTesting,
        );
        assert_eq!(t.m[3][0], 100.0); // 50% of the X basis
        assert_eq!(t.m[3][1], 40.0); // 50% of the Y basis
    }
    #[test]
    fn from_style_transform_vec_with_extreme_percent_basis_does_not_panic() {
        let list = vec![StyleTransform::TranslateX(PixelValue::const_percent(50))];
        let run = |basis: f32| {
            ComputedTransform3D::from_style_transform_vec(
                &list,
                &StyleTransformOrigin::default(),
                basis,
                basis,
                RotationMode::ForWebRender,
            )
        };
        // Any *finite* basis, however absurd, leaves the linear part an identity.
        for basis in [f32::MAX, f32::MIN, 0.0, -0.0, -1e30] {
            let t = run(basis);
            assert_eq!(t.m[0][0], 1.0, "linear part corrupted for basis {basis}");
            assert!(
                !t.m[3][0].is_nan(),
                "finite basis {basis} produced a NaN offset"
            );
        }
        // A NaN basis yields a NaN offset — defined, and no panic.
        assert!(run(f32::NAN).m[3][0].is_nan());
        // HAZARD, asserted as-is: an *infinite* basis does not just give an
        // infinite offset — `then` multiplies the identity's zero w-column by it
        // (0.0 * inf == NaN), so the NaN spreads into the linear part as well.
        // Same on the scalar, SSE and AVX paths.
        let inf = run(f32::INFINITY);
        assert!(
            inf.m[0][0].is_nan(),
            "0.0 * inf should poison m11, got {}",
            inf.m[0][0]
        );
    }
    #[test]
    fn from_style_transform_vec_long_mixed_list_does_not_panic() {
        let mut list = vec![];
        for i in 0..512 {
            list.push(match i % 4 {
                0 => StyleTransform::Rotate(AngleValue::const_deg(37)),
                1 => StyleTransform::Scale(StyleTransformScale2D {
                    x: FloatValue::const_new(1),
                    y: FloatValue::const_new(1),
                }),
                2 => StyleTransform::SkewX(AngleValue::const_deg(5)),
                _ => StyleTransform::TranslateY(PixelValue::const_px(1)),
            });
        }
        let t = ComputedTransform3D::from_style_transform_vec(
            &list,
            &StyleTransformOrigin::default(),
            300.0,
            150.0,
            RotationMode::ForWebRender,
        );
        // 512 chained f32 multiplies may drift, but must never produce NaN.
        assert!(!t.m[3][3].is_nan());
    }
    // ---------------------------------------------------- from_style_transform
    #[test]
    fn from_style_transform_matrix_2d_and_3d() {
        let m2d = StyleTransform::Matrix(StyleTransformMatrix2D {
            a: FloatValue::const_new(2),
            b: FloatValue::const_new(3),
            c: FloatValue::const_new(4),
            d: FloatValue::const_new(5),
            tx: FloatValue::const_new(6),
            ty: FloatValue::const_new(7),
        });
        let t = build(&m2d, 0.0, 0.0);
        assert_eq!(t.m[0], [2.0, 3.0, 0.0, 0.0]);
        assert_eq!(t.m[1], [4.0, 5.0, 0.0, 0.0]);
        assert_eq!(t.m[3], [6.0, 7.0, 0.0, 1.0]);
        // The default matrix3d() is the identity.
        let m3d = StyleTransform::Matrix3D(StyleTransformMatrix3D::default());
        assert_eq!(build(&m3d, 0.0, 0.0), ComputedTransform3D::IDENTITY);
    }
    #[test]
    fn from_style_transform_translate_units() {
        // px
        let t = build(
            &StyleTransform::TranslateX(PixelValue::const_px(25)),
            0.0,
            0.0,
        );
        assert_eq!(t.m[3][0], 25.0);
        // em: resolved against DEFAULT_FONT_SIZE (16px)
        let t = build(
            &StyleTransform::TranslateY(PixelValue::const_em(2)),
            0.0,
            0.0,
        );
        assert_eq!(t.m[3][1], 32.0);
        // 2D translate with mixed units
        let t = build(
            &StyleTransform::Translate(StyleTransformTranslate2D {
                x: PixelValue::const_percent(50),
                y: PixelValue::const_px(-10),
            }),
            400.0,
            0.0,
        );
        assert_eq!(t.m[3][0], 200.0);
        assert_eq!(t.m[3][1], -10.0);
    }
    #[test]
    fn from_style_transform_translate_z_percent_falls_back_to_the_x_basis() {
        // Documented: "CSS has no containing block for Z-axis percentages; use X".
        // percent_resolve_y is deliberately different so a Y-basis regression fails.
        let t = build(
            &StyleTransform::TranslateZ(PixelValue::const_percent(50)),
            200.0,
            999.0,
        );
        assert_eq!(
            t.m[3][2], 100.0,
            "translateZ(%) must resolve against the X basis"
        );
        let t3d = build(
            &StyleTransform::Translate3D(StyleTransformTranslate3D {
                x: PixelValue::const_px(0),
                y: PixelValue::const_px(0),
                z: PixelValue::const_percent(50),
            }),
            200.0,
            999.0,
        );
        assert_eq!(t3d.m[3][2], 100.0);
    }
    #[test]
    fn from_style_transform_viewport_units_resolve_to_zero() {
        // to_pixels_internal() has no viewport context and documents a 0.0 result
        // for vw/vh/vmin/vmax — assert that (a silently-dropped translation), so
        // a future viewport-aware fix has to update this test on purpose.
        let vw = PixelValue::from_metric(SizeMetric::Vw, 50.0);
        let t = build(&StyleTransform::TranslateX(vw), 1000.0, 1000.0);
        assert_eq!(t.m[3][0], 0.0);
    }
    #[test]
    fn from_style_transform_saturating_pixel_values_stay_finite() {
        // PixelValue stores an isize (value * 1000), so an infinite CSS length
        // saturates at isize::MAX/1000 instead of becoming inf, and NaN becomes 0.
        let inf = build(
            &StyleTransform::TranslateX(PixelValue::px(f32::INFINITY)),
            0.0,
            0.0,
        );
        assert!(
            inf.m[3][0].is_finite() && inf.m[3][0] > 1e6,
            "an infinite px length must saturate, got {}",
            inf.m[3][0]
        );
        let nan = build(
            &StyleTransform::TranslateX(PixelValue::px(f32::NAN)),
            0.0,
            0.0,
        );
        assert_eq!(nan.m[3][0], 0.0, "NaN px must saturate to 0, not propagate");
    }
    #[test]
    fn from_style_transform_scale_variants() {
        let s2d = build(
            &StyleTransform::Scale(StyleTransformScale2D {
                x: FloatValue::const_new(2),
                y: FloatValue::const_new(3),
            }),
            0.0,
            0.0,
        );
        assert_eq!((s2d.m[0][0], s2d.m[1][1], s2d.m[2][2]), (2.0, 3.0, 1.0));
        let s3d = build(
            &StyleTransform::Scale3D(StyleTransformScale3D {
                x: FloatValue::const_new(2),
                y: FloatValue::const_new(3),
                z: FloatValue::const_new(4),
            }),
            0.0,
            0.0,
        );
        assert_eq!((s3d.m[0][0], s3d.m[1][1], s3d.m[2][2]), (2.0, 3.0, 4.0));
        // scaleX/Y/Z take a PercentageValue: 150% => 1.5, and only one axis moves.
        let sx = build(
            &StyleTransform::ScaleX(PercentageValue::const_new(150)),
            0.0,
            0.0,
        );
        assert_eq!((sx.m[0][0], sx.m[1][1], sx.m[2][2]), (1.5, 1.0, 1.0));
        let sy = build(
            &StyleTransform::ScaleY(PercentageValue::const_new(150)),
            0.0,
            0.0,
        );
        assert_eq!((sy.m[0][0], sy.m[1][1], sy.m[2][2]), (1.0, 1.5, 1.0));
        let sz = build(
            &StyleTransform::ScaleZ(PercentageValue::const_new(150)),
            0.0,
            0.0,
        );
        assert_eq!((sz.m[0][0], sz.m[1][1], sz.m[2][2]), (1.0, 1.0, 1.5));
    }
    #[test]
    fn from_style_transform_scale_zero_is_singular() {
        let s = build(
            &StyleTransform::Scale3D(StyleTransformScale3D {
                x: FloatValue::const_new(0),
                y: FloatValue::const_new(0),
                z: FloatValue::const_new(0),
            }),
            0.0,
            0.0,
        );
        assert_eq!(s.determinant(), 0.0);
        assert_eq!(s.inverse(), ComputedTransform3D::IDENTITY);
        // A collapsed element still maps points (to the origin), it does not panic.
        let p = s.transform_point2d(LogicalPosition::new(5.0, 9.0)).unwrap();
        assert_eq!((p.x, p.y), (0.0, 0.0));
    }
    #[test]
    fn from_style_transform_skew_variants() {
        let sx = build(&StyleTransform::SkewX(AngleValue::const_deg(45)), 0.0, 0.0);
        assert!((sx.m[1][0] - 1.0).abs() < 1e-5, "skewX => tan(a) at m21");
        assert_eq!(sx.m[0][1], 0.0);
        let sy = build(&StyleTransform::SkewY(AngleValue::const_deg(45)), 0.0, 0.0);
        assert!((sy.m[0][1] - 1.0).abs() < 1e-5, "skewY => tan(b) at m12");
        assert_eq!(sy.m[1][0], 0.0);
        let sk = build(
            &StyleTransform::Skew(StyleTransformSkew2D {
                x: AngleValue::const_deg(30),
                y: AngleValue::const_deg(60),
            }),
            0.0,
            0.0,
        );
        assert!((sk.m[1][0] - 0.577_350_3).abs() < 1e-3); // tan(30deg)
        assert!((sk.m[0][1] - 1.732_050_8).abs() < 1e-3); // tan(60deg)
    }
    #[test]
    fn from_style_transform_skew_90_degrees_stays_finite() {
        let sk = build(&StyleTransform::SkewX(AngleValue::const_deg(90)), 0.0, 0.0);
        assert!(
            all_finite(&sk),
            "skewX(90deg) must not produce inf/NaN: {sk:?}"
        );
    }
    #[test]
    fn from_style_transform_perspective_zero_is_infinite() {
        let p = build(
            &StyleTransform::Perspective(PixelValue::const_px(0)),
            0.0,
            0.0,
        );
        // perspective(0) => -1/0 => -inf. No panic, but a poisoned matrix.
        assert!(p.m[2][3].is_infinite() && p.m[2][3].is_sign_negative());
        let ok = build(
            &StyleTransform::Perspective(PixelValue::const_px(100)),
            0.0,
            0.0,
        );
        assert!((ok.m[2][3] - (-0.01)).abs() < 1e-6);
    }
    #[test]
    fn from_style_transform_rotate_degenerate_axis_is_identity() {
        // rotate3d(0, 0, 0, 45deg) has no axis to rotate about; it must degenerate
        // to the identity (modulo the origin round-trip), not to NaN.
        let r = ComputedTransform3D::from_style_transform(
            &StyleTransform::Rotate3D(StyleTransformRotate3D {
                x: FloatValue::const_new(0),
                y: FloatValue::const_new(0),
                z: FloatValue::const_new(0),
                angle: AngleValue::const_deg(45),
            }),
            &StyleTransformOrigin::default(), // 50% / 50% => (50, 50)
            100.0,
            100.0,
            RotationMode::ForHitTesting,
        );
        assert_mat_approx(&r, &ComputedTransform3D::IDENTITY, 1e-4);
    }
    #[test]
    fn from_style_transform_rotate_angle_metrics_agree() {
        // 90deg == 0.25turn == 100grad. (Radians are NOT compared exactly here:
        // FloatValue quantizes to 3 decimals, so PI/2 stores as 1.570 rad
        // = 89.95deg — hence the looser tolerance on the rad case below.)
        let deg = build(&StyleTransform::Rotate(AngleValue::const_deg(90)), 0.0, 0.0);
        let turn = build(&StyleTransform::RotateZ(AngleValue::turn(0.25)), 0.0, 0.0);
        let grad = build(
            &StyleTransform::Rotate(AngleValue::const_grad(100)),
            0.0,
            0.0,
        );
        assert_mat_approx(&deg, &turn, 1e-5);
        assert_mat_approx(&deg, &grad, 1e-5);
        let rad = build(
            &StyleTransform::Rotate(AngleValue::rad(core::f32::consts::FRAC_PI_2)),
            0.0,
            0.0,
        );
        assert_mat_approx(&deg, &rad, 1e-2);
    }
    #[test]
    fn from_style_transform_full_turn_normalizes_to_no_rotation() {
        // AngleValue::to_degrees() wraps into [0, 360), so 720deg == 0deg.
        let full = build(
            &StyleTransform::Rotate(AngleValue::const_deg(720)),
            0.0,
            0.0,
        );
        assert_mat_approx(&full, &ComputedTransform3D::IDENTITY, 1e-3);
        // ... and a negative angle wraps to its positive equivalent (-90 => 270).
        let neg = build(
            &StyleTransform::Rotate(AngleValue::const_deg(-90)),
            0.0,
            0.0,
        );
        let pos = build(
            &StyleTransform::Rotate(AngleValue::const_deg(270)),
            0.0,
            0.0,
        );
        assert_mat_approx(&neg, &pos, 1e-5);
    }
    #[test]
    fn from_style_transform_rotate_x_y_z_pick_distinct_axes() {
        let rx = build(
            &StyleTransform::RotateX(AngleValue::const_deg(90)),
            0.0,
            0.0,
        );
        let ry = build(
            &StyleTransform::RotateY(AngleValue::const_deg(90)),
            0.0,
            0.0,
        );
        let rz = build(
            &StyleTransform::RotateZ(AngleValue::const_deg(90)),
            0.0,
            0.0,
        );
        // Each keeps its own axis fixed: rotateX leaves m11, rotateY leaves m22,
        // rotateZ leaves m33 equal to 1.
        assert!((rx.m[0][0] - 1.0).abs() < 1e-5);
        assert!((ry.m[1][1] - 1.0).abs() < 1e-5);
        assert!((rz.m[2][2] - 1.0).abs() < 1e-5);
        // ... and they are genuinely different matrices.
        assert!(rx != ry && ry != rz && rx != rz);
        // Every rotation preserves volume.
        for r in [rx, ry, rz] {
            assert!(
                (r.determinant() - 1.0).abs() < 1e-3,
                "det = {}",
                r.determinant()
            );
        }
    }
    #[test]
    fn from_style_transform_huge_angle_stays_finite() {
        // AngleValue saturates through FloatValue's isize backing, and to_degrees()
        // wraps modulo 360 — so even a "f32::MAX degrees" rotation is well-defined.
        let huge = build(&StyleTransform::Rotate(AngleValue::deg(f32::MAX)), 0.0, 0.0);
        assert!(all_finite(&huge), "huge angle produced inf/NaN: {huge:?}");
    }
    // ----------------------------------------------------------- make_rotation
    #[test]
    fn make_rotation_zero_degrees_is_identity_about_any_origin() {
        for mode in [RotationMode::ForWebRender, RotationMode::ForHitTesting] {
            let r = ComputedTransform3D::make_rotation((10.0, 20.0), 0.0, 0.0, 0.0, 1.0, mode);
            assert_mat_approx(&r, &ComputedTransform3D::IDENTITY, 1e-3);
        }
    }
    #[test]
    fn make_rotation_modes_are_mutual_inverses() {
        // ForWebRender negates the angle, ForHitTesting does not — so composing
        // the two about the same origin must cancel out to the identity.
        let origin = (100.0, 50.0);
        let wr = ComputedTransform3D::make_rotation(
            origin,
            45.0,
            0.0,
            0.0,
            1.0,
            RotationMode::ForWebRender,
        );
        let ht = ComputedTransform3D::make_rotation(
            origin,
            45.0,
            0.0,
            0.0,
            1.0,
            RotationMode::ForHitTesting,
        );
        assert!(
            wr != ht,
            "the two rotation modes must not produce the same matrix"
        );
        assert_mat_approx(&wr.then(&ht), &ComputedTransform3D::IDENTITY, 1e-3);
    }
    #[test]
    fn make_rotation_keeps_its_origin_fixed() {
        // The defining property of a rotation about a point: that point does not move.
        let r = ComputedTransform3D::make_rotation(
            (30.0, 40.0),
            90.0,
            0.0,
            0.0,
            1.0,
            RotationMode::ForHitTesting,
        );
        let p = r
            .transform_point2d(LogicalPosition::new(30.0, 40.0))
            .unwrap();
        assert!((p.x - 30.0).abs() < 1e-2, "origin moved in x: {}", p.x);
        assert!((p.y - 40.0).abs() < 1e-2, "origin moved in y: {}", p.y);
    }
    #[test]
    fn make_rotation_preserves_volume() {
        let r = ComputedTransform3D::make_rotation(
            (7.0, -3.0),
            123.456,
            0.0,
            0.0,
            1.0,
            RotationMode::ForWebRender,
        );
        assert!(
            (r.determinant() - 1.0).abs() < 1e-3,
            "det = {}",
            r.determinant()
        );
    }
    #[test]
    fn make_rotation_nan_degrees_does_not_panic() {
        let r = ComputedTransform3D::make_rotation(
            (1.0, 2.0),
            f32::NAN,
            0.0,
            0.0,
            1.0,
            RotationMode::ForWebRender,
        );
        assert!(r.m[0][0].is_nan(), "NaN degrees must propagate, not panic");
    }
    proptest! {
        #[test]
        fn make_rotation_infinite_degrees_does_not_panic(deg in proptest::num::f32::ANY) {
            let r = ComputedTransform3D::make_rotation(
                (0.0, 0.0),
                deg,
                0.0,
                0.0,
                1.0,
                RotationMode::ForHitTesting,
            );
            core::hint::black_box(r);
        }
        #[test]
        fn make_rotation_extreme_origin_does_not_panic(
            ox in proptest::num::f32::ANY, oy in proptest::num::f32::ANY
        ) {
            let r = ComputedTransform3D::make_rotation(
                (ox, oy),
                45.0,
                0.0,
                0.0,
                1.0,
                RotationMode::ForWebRender,
            );
            core::hint::black_box(r);
        }
    }
    #[test]
    fn make_rotation_degenerate_axis_is_a_pure_origin_round_trip() {
        // A zero axis cancels every rotation term, leaving T(-o) * I * T(o) = I.
        let r = ComputedTransform3D::make_rotation(
            (12.0, 34.0),
            90.0,
            0.0,
            0.0,
            0.0,
            RotationMode::ForHitTesting,
        );
        assert_mat_approx(&r, &ComputedTransform3D::IDENTITY, 1e-4);
    }
}