mirage-engine 0.1.1

Mirage, an immediate-mode 3D engine for simple games on desktop and the browser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
use core::ops::Range;

use crate::Ray;
use crate::math::camera::rh::proj::directx::{orthographic, perspective};
use crate::math::camera::rh::view::look_at_mat4;
use crate::math::{Mat3, Mat4, Quat, UVec2, Vec2, Vec3, Vec4};
use crate::mesh::BoundingSphere;

/// A [`View`] and a [`Projection`]: where a frame is viewed from, and how
/// that view is projected.
///
/// A frame is drawn from the last call to
/// [`FrameContext::set_camera`](crate::FrameContext::set_camera); each
/// frame needs its own.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Camera {
    view: View,
    projection: Projection,
}

impl Camera {
    /// A camera from `view` and `projection`.
    pub const fn new(view: View, projection: Projection) -> Self {
        Self { view, projection }
    }

    /// The world's viewpoint.
    pub const fn view(&self) -> View {
        self.view
    }

    /// The view's projection onto the screen.
    pub const fn projection(&self) -> Projection {
        self.projection
    }

    /// The ray through `pixel` on a surface `size` across, in world space.
    ///
    /// Both are physical pixels, as
    /// [`FrameContext::window_size`](crate::FrameContext::window_size)
    /// reports them. The ray starts at the [`View::eye`] where the lens
    /// foreshortens, and in the view plane where it does not.
    pub fn ray_through(&self, pixel: Vec2, size: UVec2) -> Ray {
        let size = size.as_vec2();
        let clip = clip_space(pixel, size);
        let world = self.view_projection(size.x / size.y).inverse();
        let near = world.project_point3(clip.extend(0.0));
        let far = world.project_point3(clip.extend(1.0));

        match self.projection.lens {
            Lens::Perspective { .. } => Ray::new(self.view.eye, far - near),
            Lens::Orthographic { .. } => Ray::new(near, far - near),
        }
    }

    /// The pixel `point` draws at, on a surface `size` across, in physical
    /// pixels.
    ///
    /// The inverse of [`Camera::ray_through`] at the same `size`, counted
    /// from the drawing area's top left. A point off screen returns a pixel
    /// outside the surface, for the caller to clamp. `None` where `point`
    /// lies at or behind the [`View::eye`], where either side of `size` is
    /// zero, or where the view or the lens has no shape to draw through.
    pub fn pixel_of(&self, point: Vec3, size: UVec2) -> Option<Vec2> {
        self.depth_in_front(point)?;
        let size = surface(size)?;
        let clip = self.view_projection(size.x / size.y).project_point3(point);
        let pixel = Vec2::new(clip.x + 1.0, 1.0 - clip.y) / 2.0 * size;

        pixel.is_finite().then_some(pixel)
    }

    /// The pixels a meter across the view covers at the depth of `point` in
    /// front of the [`View::eye`], on a surface `size` across: the scale.
    ///
    /// The scale falls with depth under [`Lens::Perspective`] and stays the
    /// same at every depth under [`Lens::Orthographic`]. `None` where
    /// `point` lies at or behind the [`View::eye`], where either side of
    /// `size` is zero, or where the view or the lens has no shape to draw
    /// through.
    pub fn pixels_per_meter(&self, point: Vec3, size: UVec2) -> Option<f32> {
        let depth = self.depth_in_front(point)?;
        let size = surface(size)?;
        let visible_height = match self.projection.lens {
            Lens::Perspective { fov_degrees } => {
                2.0 * depth * (fov_degrees.to_radians() / 2.0).tan()
            }
            Lens::Orthographic { world_height } => world_height,
        };
        let scale = size.y / visible_height;

        scale.is_normal().then_some(scale)
    }

    /// The same camera moved so that `point` draws at `lands_at`, on a
    /// surface `size` across.
    ///
    /// Required if you want a drag to pan the view. `lands_at` is a pixel
    /// as [`pixel_of`](Camera::pixel_of) returns one: physical pixels from
    /// the drawing area's top left. The camera is moved and never turned,
    /// and it moves in the view plane, so `point` keeps its depth and the
    /// [`View::eye`] and [`View::target`] move by the same vector. `None`
    /// where `point` lies at or behind the [`View::eye`], where either side
    /// of `size` is zero, where the view or the lens has no shape to draw
    /// through, where `lands_at` is not finite, or where the camera it
    /// would return does not draw `point`: the [`View::eye`] and
    /// [`View::target`] landed together.
    pub fn shifted_so(&self, point: Vec3, lands_at: Vec2, size: UVec2) -> Option<Camera> {
        let drawn = self.pixel_of(point, size)?;
        let scale = self.pixels_per_meter(point, size)?;
        let axes = self.view.basis()?;
        if !lands_at.is_finite() {
            return None;
        }
        let moved = lands_at - drawn;
        let shift = (axes.upward * moved.y - axes.across * moved.x) / scale;
        let shifted = Self::new(self.view.moved(shift), self.projection);

        shifted.pixel_of(point, size).is_some().then_some(shifted)
    }

    /// The same camera zoomed about `point`, on a surface `size` across, so
    /// that `point` keeps the pixel it draws at.
    ///
    /// Required if you want a wheel to zoom towards what the pointer is
    /// over. The distance from the [`View::eye`] to `point` becomes the
    /// fraction `1.0 / factor` of what it was, so `2.0` halves it, and the
    /// direction the view looks and its field of view are left alone. Under
    /// [`Lens::Orthographic`] the [`View::eye`] keeps its own depth: the
    /// lens takes that same fraction of its world height and the
    /// [`View::eye`] moves in the view plane instead. `None` where `point`
    /// lies at or behind the [`View::eye`], where either side of `size` is
    /// zero, where the view or the lens has no shape to draw through, where
    /// `factor` is not finite or not above zero, or where the camera it
    /// would return does not draw `point`: the [`View::eye`] and
    /// [`View::target`] landed together, or the lens was left with no
    /// finite height.
    pub fn zoomed_about(&self, point: Vec3, factor: f32, size: UVec2) -> Option<Camera> {
        self.pixel_of(point, size)?;
        let closer = (factor.is_finite() && factor > 0.0).then(|| 1.0 - 1.0 / factor)?;
        let to_point = point - self.view.eye;

        let line = match self.projection.lens {
            Lens::Orthographic { .. } => {
                let axes = self.view.basis()?;
                to_point - axes.forward * to_point.dot(axes.forward)
            }
            Lens::Perspective { .. } => to_point,
        };
        let zoomed = Self::new(
            self.view.moved(line * closer),
            self.projection.zoomed(factor)?,
        );

        zoomed.pixel_of(point, size).is_some().then_some(zoomed)
    }

    /// The same camera turned about `point`, so that `point` keeps the pixel
    /// it draws at.
    ///
    /// Required if you want a drag to orbit the view about what the pointer
    /// is over. The [`View::eye`] turns about `point` by `pitch` radians
    /// about the direction across the view to the right, then by `yaw`
    /// radians about the [`View::up`] direction, and the direction the view
    /// looks turns with it, so the distance from the [`View::eye`] to
    /// `point` and the [`Projection`] are left alone. `None` where `point`
    /// lies at or behind the [`View::eye`], where the view has no shape to
    /// draw through, where `yaw` or `pitch` is not finite, or where the turn
    /// takes the direction the view looks past the [`View::up`] direction —
    /// the pole.
    pub fn turned_about(&self, point: Vec3, yaw: f32, pitch: f32) -> Option<Camera> {
        self.depth_in_front(point)?;
        let axes = self.view.basis()?;
        let turn = Quat::from_axis_angle(axes.up, yaw) * Quat::from_axis_angle(axes.across, pitch);
        let turned = Self::new(self.view.turned(point, turn), self.projection);

        // `point` keeps its pixel where the view's own axes turned with the
        // viewpoint; past the pole the right axis points the other way. No
        // type states which side of the pole a turn left the view on.
        (turned.view.basis()?.across.dot(turn * axes.across) > 0.0).then_some(turned)
    }

    /// The matrix that takes world space to clip space, with `aspect`.
    pub(crate) fn view_projection(&self, aspect: f32) -> Mat4 {
        self.projection.matrix(aspect) * self.view.matrix()
    }

    /// The inverse of this camera with its [`View::eye`] left at the
    /// origin, with `aspect`: it takes a clip position to a point on the ray
    /// the camera reads that position along.
    ///
    /// Under [`Lens::Orthographic`] every such ray is the direction the view
    /// looks, which this matrix does not hold; see
    /// [`Camera::foreshortened`].
    pub(crate) fn rays_from_clip(&self, aspect: f32) -> Mat4 {
        let turned = Mat4::from_mat3(Mat3::from_mat4(self.view.matrix()));

        (self.projection.matrix(aspect) * turned).inverse()
    }

    /// Whether rays leave the [`View::eye`], rather than running level
    /// through it.
    pub(crate) fn foreshortened(&self) -> bool {
        matches!(self.projection.lens(), Lens::Perspective { .. })
    }

    /// How far `point` lies in front of the [`View::eye`], in meters along
    /// the view direction; `None` where it lies at or behind the
    /// [`View::eye`], or the view has no direction.
    fn depth_in_front(&self, point: Vec3) -> Option<f32> {
        let depth = -self.view.matrix().transform_point3(point).z;
        (depth > 0.0 && depth.is_finite()).then_some(depth)
    }
}

impl Default for Camera {
    /// Looks at the origin from 5 meters back and 2 meters up, at 60°.
    fn default() -> Self {
        Self::new(
            View::look_at(Vec3::new(0.0, 2.0, 5.0), Vec3::ZERO),
            Projection::perspective(60.0),
        )
    }
}

/// The world's viewpoint.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct View {
    eye: Vec3,
    target: Vec3,
    up: Vec3,
}

impl View {
    /// Looks from `eye` at `target`, `+Y` up.
    pub const fn look_at(eye: Vec3, target: Vec3) -> Self {
        Self {
            eye,
            target,
            up: Vec3::Y,
        }
    }

    /// Sets the view's up direction; `+Y` by default.
    #[must_use]
    pub const fn with_up(mut self, up: Vec3) -> Self {
        self.up = up;
        self
    }

    /// Camera position.
    pub const fn eye(&self) -> Vec3 {
        self.eye
    }

    /// The camera's target.
    pub const fn target(&self) -> Vec3 {
        self.target
    }

    /// Up direction on the screen.
    pub const fn up(&self) -> Vec3 {
        self.up
    }

    /// The direction from the [`View::eye`] to the [`View::target`], one
    /// meter long; zero where the two are one point.
    pub fn direction(&self) -> Vec3 {
        (self.target - self.eye).normalize_or_zero()
    }

    fn matrix(&self) -> Mat4 {
        look_at_mat4(self.eye, self.target, self.up)
    }

    /// Where this view looks, the directions across and up the screen, and
    /// the up direction it holds, each one meter long; `None` where the view
    /// has no shape.
    fn basis(&self) -> Option<Basis> {
        let forward = self.direction();
        if forward == Vec3::ZERO {
            return None;
        }
        let across = forward.cross(self.up).try_normalize()?;
        let up = self.up.try_normalize()?;

        Some(Basis {
            forward,
            across,
            upward: across.cross(forward),
            up,
        })
    }

    /// The same view moved by `offset`, looking the same way.
    fn moved(self, offset: Vec3) -> Self {
        Self {
            eye: self.eye + offset,
            target: self.target + offset,
            up: self.up,
        }
    }

    /// The same view with its [`View::eye`] and its [`View::target`] turned
    /// by `turn` about `about`, under the up direction it had.
    fn turned(self, about: Vec3, turn: Quat) -> Self {
        Self {
            eye: about + turn * (self.eye - about),
            target: about + turn * (self.target - about),
            up: self.up,
        }
    }
}

/// A view's own directions, each one meter long.
struct Basis {
    /// Where the view looks.
    forward: Vec3,
    /// Across the screen, to the right.
    across: Vec3,
    /// Up the screen, at a right angle to [`Basis::forward`] and
    /// [`Basis::across`].
    upward: Vec3,
    /// The up direction the view holds, which it is drawn the right way up
    /// by and turned about.
    up: Vec3,
}

/// Screen extent of the world, and its foreshortening by depth.
///
/// The view is always the drawing area's shape; games never need an aspect
/// ratio.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Projection {
    lens: Lens,
    near: f32,
    far: f32,
}

impl Projection {
    const DEFAULT_NEAR: f32 = 0.1;
    const DEFAULT_FAR: f32 = 1000.0;

    /// Foreshortened by depth, over a vertical field of view, in degrees.
    pub const fn perspective(fov_degrees: f32) -> Self {
        Self {
            lens: Lens::Perspective { fov_degrees },
            near: Self::DEFAULT_NEAR,
            far: Self::DEFAULT_FAR,
        }
    }

    /// No foreshortening; `world_height` meters of world are visible over the
    /// drawing area's height.
    pub const fn orthographic(world_height: f32) -> Self {
        Self {
            lens: Lens::Orthographic { world_height },
            near: Self::DEFAULT_NEAR,
            far: Self::DEFAULT_FAR,
        }
    }

    /// Sets the distances, in meters, between which the world is visible;
    /// `0.1..1000.0` by default.
    #[must_use]
    pub const fn clip(mut self, clip: Range<f32>) -> Self {
        self.near = clip.start;
        self.far = clip.end;
        self
    }

    /// This projection's lens, and the number shaping it.
    pub const fn lens(&self) -> Lens {
        self.lens
    }

    /// This projection's `near` clip distance, in meters.
    pub const fn near(&self) -> f32 {
        self.near
    }

    /// This projection's `far` clip distance, in meters.
    pub const fn far(&self) -> f32 {
        self.far
    }

    /// The same projection over the fraction `1.0 / factor` of the world
    /// this one covers. Under [`Lens::Perspective`] that is this projection
    /// unchanged: there the distance from the [`View::eye`] is what changes
    /// how much world the view covers, not the lens.
    ///
    /// Takes a `factor` the caller has already read as finite and above
    /// zero; [`Lens::Perspective`] returns itself whatever it is given.
    /// `None` where the world height it leaves is not finite or not above
    /// zero. A lens whose height was already zero or under it leaves such
    /// a height whatever `factor` is.
    pub(crate) fn zoomed(&self, factor: f32) -> Option<Self> {
        let Lens::Orthographic { world_height } = self.lens else {
            return Some(*self);
        };
        let world_height = world_height / factor;

        (world_height.is_finite() && world_height > 0.0).then_some(Self {
            lens: Lens::Orthographic { world_height },
            ..*self
        })
    }

    fn matrix(&self, aspect: f32) -> Mat4 {
        match self.lens {
            Lens::Perspective { fov_degrees } => {
                perspective(fov_degrees.to_radians(), aspect, self.near, self.far)
            }
            Lens::Orthographic { world_height } => {
                let half_height = world_height / 2.0;
                let half_width = half_height * aspect;
                orthographic(
                    -half_width,
                    half_width,
                    -half_height,
                    half_height,
                    self.near,
                    self.far,
                )
            }
        }
    }
}

/// The shape a projection applies to depth, and the number shaping it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Lens {
    /// Foreshortens with distance.
    Perspective {
        /// The vertical field of view, in degrees.
        fov_degrees: f32,
    },
    /// Keeps size the same at any distance.
    Orthographic {
        /// The meters of world visible over the drawing area's height.
        world_height: f32,
    },
}

/// The six planes a camera draws within, in world space, each facing what it
/// keeps.
pub(crate) struct Frustum([Vec4; 6]);

impl Frustum {
    /// The planes `view_projection` clips against, read off its rows: the
    /// sides from the last row plus and minus the first two, the nearest
    /// from the depth row alone (depth runs from zero), the furthest from
    /// the last row minus it.
    pub(crate) fn new(view_projection: Mat4) -> Self {
        let [across, up, depth, clip] = [0, 1, 2, 3].map(|row| view_projection.row(row));

        Self(
            [
                clip + across,
                clip - across,
                clip + up,
                clip - up,
                depth,
                clip - depth,
            ]
            .map(facing_inward),
        )
    }

    /// True where the camera covers any of `sphere`: one that crosses a
    /// plane is kept, one left past a plane is not.
    pub(crate) fn holds(&self, sphere: BoundingSphere) -> bool {
        let center = sphere.center().extend(1.0);

        !self
            .0
            .iter()
            .any(|plane| plane.dot(center) < -sphere.radius())
    }
}

/// `plane` scaled to a unit normal, so what it measures is in meters. A
/// plane that a squashed matrix left with no direction is returned as
/// `Vec4::ZERO`, which keeps nothing out.
fn facing_inward(plane: Vec4) -> Vec4 {
    let reach = plane.truncate().length();
    if reach.is_normal() {
        plane / reach
    } else {
        Vec4::ZERO
    }
}

/// `size` as the surface a pixel is measured over; `None` where either
/// side is zero.
fn surface(size: UVec2) -> Option<Vec2> {
    (size.x > 0 && size.y > 0).then(|| size.as_vec2())
}

/// Position of `pixel` in clip space: `-1..1` across the surface and up
/// it, which pixels measure down.
fn clip_space(pixel: Vec2, size: Vec2) -> Vec2 {
    let across = pixel / size * 2.0 - Vec2::ONE;
    Vec2::new(across.x, -across.y)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ray;

    /// The surface every ray is taken across, in physical pixels.
    const SIZE: UVec2 = UVec2::new(1280, 720);

    /// Every lens a ray is taken through.
    const LENSES: [Projection; 2] = [
        Projection::perspective(60.0),
        Projection::orthographic(20.0),
    ];

    /// The corners of that surface, and its middle.
    const PIXELS: [Vec2; 5] = [
        Vec2::ZERO,
        Vec2::new(1280.0, 0.0),
        Vec2::new(0.0, 720.0),
        Vec2::new(1280.0, 720.0),
        Vec2::new(640.0, 360.0),
    ];

    /// Looking down at the origin from up and back, through `projection`.
    fn overhead(projection: Projection) -> Camera {
        Camera::new(
            View::look_at(Vec3::new(0.0, 10.0, 10.0), Vec3::ZERO),
            projection,
        )
    }

    fn looking(camera: &Camera) -> Vec3 {
        (camera.view().target() - camera.view().eye()).normalize()
    }

    #[test]
    fn the_middle_pixel_looks_where_the_camera_does() {
        for projection in LENSES {
            let camera = overhead(projection);
            let ray = camera.ray_through(SIZE.as_vec2() / 2.0, SIZE);

            assert!(
                ray.direction().abs_diff_eq(looking(&camera), 1e-5),
                "{:?} against {:?}",
                ray.direction(),
                looking(&camera)
            );
        }
    }

    #[test]
    fn a_foreshortened_view_takes_every_ray_from_the_eye() {
        let camera = overhead(Projection::perspective(60.0));

        for pixel in PIXELS {
            let ray = camera.ray_through(pixel, SIZE);
            assert!(ray.origin().abs_diff_eq(camera.view().eye(), 1e-4));
        }
    }

    #[test]
    fn a_flat_view_takes_every_ray_from_the_near_plane_it_lies_in() {
        let camera = overhead(Projection::orthographic(20.0));
        let middle = camera.ray_through(SIZE.as_vec2() / 2.0, SIZE);
        let near = camera.view().eye() + looking(&camera) * camera.projection().near();

        assert!(middle.origin().abs_diff_eq(near, 1e-4));
        for pixel in PIXELS {
            let ray = camera.ray_through(pixel, SIZE);
            assert!(
                ray.direction().abs_diff_eq(middle.direction(), 1e-5),
                "every ray is parallel, {pixel} was not"
            );
            assert!(
                (ray.origin() - near).dot(middle.direction()).abs() < 1e-3,
                "and starts in the same plane, {pixel} did not"
            );
        }
    }

    #[test]
    fn a_surface_with_no_area_names_a_ray_that_reaches_nothing() {
        for projection in LENSES {
            let ray = overhead(projection).ray_through(Vec2::ZERO, UVec2::ZERO);

            assert_eq!(ray.direction(), Vec3::ZERO);
            assert_eq!(
                ray.hit_plane(ray::Plane {
                    point: Vec3::ZERO,
                    normal: Vec3::Y
                }),
                None
            );
        }
    }

    /// The reach of a camera at the origin looking down `-Z`, over a square
    /// target.
    fn ahead() -> Frustum {
        Frustum::new(
            Camera::new(
                View::look_at(Vec3::ZERO, Vec3::NEG_Z),
                Projection::perspective(60.0),
            )
            .view_projection(1.0),
        )
    }

    /// A one-meter sphere `at`.
    fn ball(at: Vec3) -> BoundingSphere {
        BoundingSphere::new(at, 1.0)
    }

    #[test]
    fn a_camera_reaches_what_is_ahead_of_it_and_nothing_past_its_own_planes() {
        let seen = ahead();

        assert!(seen.holds(ball(Vec3::new(0.0, 0.0, -5.0))));
        assert!(!seen.holds(ball(Vec3::new(0.0, 0.0, 5.0))), "behind it");
        assert!(!seen.holds(ball(Vec3::new(0.0, 0.0, -2000.0))), "past far");
        assert!(!seen.holds(ball(Vec3::new(20.0, 0.0, -5.0))), "beside it");
        assert!(!seen.holds(ball(Vec3::new(0.0, 20.0, -5.0))), "above it");
    }

    #[test]
    fn a_sphere_lying_across_a_plane_is_reached_by_the_camera_it_crosses() {
        let seen = ahead();

        assert!(
            seen.holds(ball(Vec3::new(0.0, 0.0, 0.5))),
            "one behind the eye still reaching in front of it is kept"
        );
        assert!(
            seen.holds(ball(Vec3::new(3.0, 0.0, -5.0))),
            "and so is one reaching in over the side"
        );
        assert!(
            seen.holds(BoundingSphere::new(Vec3::new(0.0, 0.0, 400.0), 1e4)),
            "as is one the whole view sits inside"
        );
    }

    #[test]
    fn a_camera_with_no_shape_to_it_keeps_every_sphere() {
        let squashed = Frustum::new(Mat4::ZERO);
        let nowhere = Frustum::new(
            Camera::new(
                View::look_at(Vec3::ZERO, Vec3::ZERO),
                Projection::perspective(60.0),
            )
            .view_projection(0.0),
        );

        assert!(squashed.holds(ball(Vec3::new(0.0, 0.0, 5.0))));
        assert!(nowhere.holds(ball(Vec3::new(0.0, 0.0, 5.0))));
        assert!(
            ahead().holds(ball(Vec3::NAN)),
            "and a sphere placed nowhere is kept by any camera"
        );
    }

    #[test]
    fn a_ray_lands_where_the_pixel_it_came_from_draws() {
        for projection in LENSES {
            let camera = overhead(projection);

            for pixel in PIXELS {
                let ray = camera.ray_through(pixel, SIZE);
                let Some(distance) = ray.hit_plane(ray::Plane {
                    point: Vec3::ZERO,
                    normal: Vec3::Y,
                }) else {
                    panic!("{pixel} of an overhead view reaches the ground");
                };
                let ground = ray.at(distance);

                assert!(ground.y.abs() < 1e-3, "{ground} left the ground");
                let drawn = camera.pixel_of(ground, SIZE);
                assert!(
                    drawn.is_some_and(|drawn| drawn.abs_diff_eq(pixel, 0.05)),
                    "{pixel} landed at {ground}, which draws at {drawn:?}"
                );
            }
        }
    }

    #[test]
    fn every_point_a_ray_reaches_draws_back_at_the_pixel_it_came_from() {
        for projection in LENSES {
            let camera = overhead(projection);

            for pixel in PIXELS {
                let ray = camera.ray_through(pixel, SIZE);

                for distance in [0.5, 3.0, 40.0] {
                    let point = ray.at(distance);
                    let drawn = camera.pixel_of(point, SIZE);

                    assert!(
                        drawn.is_some_and(|drawn| drawn.abs_diff_eq(pixel, 0.05)),
                        "{pixel} reaches {point} at {distance} meters, which draws at {drawn:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn a_point_behind_the_camera_draws_nowhere_and_has_no_scale() {
        for projection in LENSES {
            let camera = overhead(projection);
            let behind = camera.view().eye() - looking(&camera) * 5.0;

            assert_eq!(camera.pixel_of(behind, SIZE), None);
            assert_eq!(camera.pixels_per_meter(behind, SIZE), None);
        }
    }

    #[test]
    fn two_points_a_meter_apart_across_the_view_draw_the_scale_apart() {
        for projection in LENSES {
            let camera = overhead(projection);
            let across = looking(&camera).cross(camera.view().up()).normalize();
            let point = camera.view().eye() + looking(&camera) * 8.0;

            let (Some(scale), Some(here), Some(there)) = (
                camera.pixels_per_meter(point, SIZE),
                camera.pixel_of(point, SIZE),
                camera.pixel_of(point + across, SIZE),
            ) else {
                panic!("{point} is in front of a {projection:?} camera");
            };

            assert!(
                ((there - here).length() - scale).abs() < 0.05,
                "a meter draws {} pixels across, against a scale of {scale}",
                (there - here).length()
            );
        }
    }

    #[test]
    fn depth_shrinks_the_scale_of_a_foreshortened_view_and_leaves_a_flat_one_alone() {
        for projection in LENSES {
            let camera = overhead(projection);
            let [near, far] = [5.0, 20.0].map(|depth| {
                camera.pixels_per_meter(camera.view().eye() + looking(&camera) * depth, SIZE)
            });

            let (Some(near), Some(far)) = (near, far) else {
                panic!("both depths lie in front of a {projection:?} camera");
            };

            match projection.lens() {
                Lens::Perspective { .. } => {
                    assert!(far < near, "{far} at 20 meters is not under {near} at 5")
                }
                Lens::Orthographic { .. } => assert_eq!(near, far),
            }
        }
    }

    #[test]
    fn a_shifted_camera_draws_the_point_at_the_pixel_it_was_given_and_looks_the_same_way() {
        for projection in LENSES {
            let camera = overhead(projection);
            let point = Vec3::new(2.0, 0.0, -1.0);

            for lands_at in PIXELS {
                let Some(shifted) = camera.shifted_so(point, lands_at, SIZE) else {
                    panic!("{point} draws under a {projection:?} camera");
                };

                let drawn = shifted.pixel_of(point, SIZE);
                assert!(
                    drawn.is_some_and(|drawn| drawn.abs_diff_eq(lands_at, 0.01)),
                    "given {lands_at}, drew at {drawn:?}"
                );
                assert!(
                    looking(&shifted).abs_diff_eq(looking(&camera), 1e-6),
                    "and the camera turned to {:?}",
                    looking(&shifted)
                );
                assert_eq!(shifted.projection(), camera.projection());
            }
        }
    }

    #[test]
    fn a_camera_zoomed_about_a_point_keeps_its_pixel_and_halves_what_the_view_covers() {
        for projection in LENSES {
            let camera = overhead(projection);
            let point = Vec3::new(2.0, 0.0, -1.0);

            let (Some(before), Some(zoomed)) = (
                camera.pixel_of(point, SIZE),
                camera.zoomed_about(point, 2.0, SIZE),
            ) else {
                panic!("{point} draws under a {projection:?} camera");
            };

            let drawn = zoomed.pixel_of(point, SIZE);
            assert!(
                drawn.is_some_and(|drawn| drawn.abs_diff_eq(before, 0.01)),
                "{point} drew at {before} and now draws at {drawn:?}"
            );
            assert!(
                looking(&zoomed).abs_diff_eq(looking(&camera), 1e-6),
                "and the camera turned to {:?}",
                looking(&zoomed)
            );

            match (camera.projection().lens(), zoomed.projection().lens()) {
                (Lens::Perspective { fov_degrees }, Lens::Perspective { fov_degrees: same }) => {
                    let (was, now) = (
                        camera.view().eye().distance(point),
                        zoomed.view().eye().distance(point),
                    );
                    assert!(
                        (now - was / 2.0).abs() < 1e-4,
                        "{was} meters away became {now}"
                    );
                    assert_eq!(fov_degrees, same, "over the same field of view");
                }
                (
                    Lens::Orthographic { world_height },
                    Lens::Orthographic {
                        world_height: halved,
                    },
                ) => {
                    assert!(
                        (halved - world_height / 2.0).abs() < 1e-4,
                        "{world_height} meters of world became {halved}"
                    );
                    let along = looking(&camera);
                    assert!(
                        (zoomed.view().eye() - camera.view().eye()).dot(along).abs() < 1e-4,
                        "and the eye kept its depth"
                    );
                }
                (lens, zoomed) => panic!("{lens:?} zoomed to a {zoomed:?}"),
            }
        }
    }

    /// The number the lens takes its shape from, which every camera a zoom
    /// returns must still hold.
    fn covered(camera: &Camera) -> f32 {
        match camera.projection().lens() {
            Lens::Perspective { fov_degrees } => fov_degrees,
            Lens::Orthographic { world_height } => world_height,
        }
    }

    #[test]
    fn every_camera_a_zoom_returns_still_draws_the_point_it_was_zoomed_about() {
        let point = Vec3::new(2.0, 0.0, -1.0);
        let factors = [
            f32::MIN_POSITIVE,
            1e-38,
            1e-30,
            1e-20,
            1e-12,
            1e-8,
            1e-6,
            0.5,
            1.0,
            2.0,
            1e6,
        ];

        for projection in LENSES {
            let camera = overhead(projection);

            for factor in factors {
                let Some(zoomed) = camera.zoomed_about(point, factor, SIZE) else {
                    continue;
                };

                assert!(
                    zoomed.pixel_of(point, SIZE).is_some(),
                    "a {projection:?} camera zoomed by {factor} draws nothing"
                );
                assert!(
                    zoomed.view().eye().is_finite() && zoomed.view().target().is_finite(),
                    "and sits at {:?} looking at {:?}",
                    zoomed.view().eye(),
                    zoomed.view().target()
                );
                let shape = covered(&zoomed);
                assert!(
                    shape.is_finite() && shape > 0.0,
                    "and its lens is shaped by {shape}"
                );
            }
            assert!(camera.zoomed_about(point, 2.0, SIZE).is_some());
        }
    }

    #[test]
    fn a_zoom_out_doubles_what_the_view_covers_and_a_zoom_of_one_changes_nothing() {
        for projection in LENSES {
            let camera = overhead(projection);
            let point = Vec3::new(2.0, 0.0, -1.0);

            let (Some(before), Some(out)) = (
                camera.pixel_of(point, SIZE),
                camera.zoomed_about(point, 0.5, SIZE),
            ) else {
                panic!("{point} draws under a {projection:?} camera");
            };

            let drawn = out.pixel_of(point, SIZE);
            assert!(
                drawn.is_some_and(|drawn| drawn.abs_diff_eq(before, 0.01)),
                "{point} drew at {before} and now draws at {drawn:?}"
            );
            match projection.lens() {
                Lens::Perspective { .. } => {
                    let (was, now) = (
                        camera.view().eye().distance(point),
                        out.view().eye().distance(point),
                    );
                    assert!((now - was * 2.0).abs() < 1e-3, "{was} meters became {now}");
                }
                Lens::Orthographic { world_height } => assert!(
                    (covered(&out) - world_height * 2.0).abs() < 1e-3,
                    "{world_height} meters of world became {}",
                    covered(&out)
                ),
            }

            assert_eq!(
                camera.zoomed_about(point, 1.0, SIZE),
                Some(camera),
                "and a zoom of one leaves the camera where it was"
            );
        }
    }

    #[test]
    fn a_camera_turned_about_a_point_draws_it_at_the_pixel_it_drew_at() {
        for projection in LENSES {
            let camera = overhead(projection);
            let point = Vec3::new(2.0, 0.0, -1.0);
            let Some(before) = camera.pixel_of(point, SIZE) else {
                panic!("{point} draws under a {projection:?} camera");
            };

            for (yaw, pitch) in [(0.5, 0.0), (0.0, 0.3), (-1.2, 0.4), (3.0, -0.6)] {
                let Some(turned) = camera.turned_about(point, yaw, pitch) else {
                    panic!("a turn of {yaw} and {pitch} keeps {point} in front of the camera");
                };

                let drawn = turned.pixel_of(point, SIZE);
                assert!(
                    drawn.is_some_and(|drawn| drawn.abs_diff_eq(before, 0.05)),
                    "{point} drew at {before} and, turned by {yaw} and {pitch}, draws at {drawn:?}"
                );
                assert!(
                    (turned.view().eye().distance(point) - camera.view().eye().distance(point))
                        .abs()
                        < 1e-3,
                    "and it turned to {} meters from {} away",
                    turned.view().eye().distance(point),
                    camera.view().eye().distance(point)
                );
                assert_eq!(turned.projection(), camera.projection());
            }
        }
    }

    #[test]
    fn a_turn_keeps_the_point_at_its_pixel_under_a_view_with_an_up_of_its_own() {
        let tilted = Camera::new(
            View::look_at(Vec3::new(0.0, 10.0, 10.0), Vec3::ZERO)
                .with_up(Vec3::new(0.3, 1.0, 0.0).normalize()),
            Projection::perspective(60.0),
        );
        let point = Vec3::new(2.0, 0.0, -1.0);
        let Some(before) = tilted.pixel_of(point, SIZE) else {
            panic!("{point} draws under a camera holding its own up");
        };

        for (yaw, pitch) in [(0.7, 0.0), (0.0, 0.4), (-1.1, 0.25)] {
            let Some(turned) = tilted.turned_about(point, yaw, pitch) else {
                panic!("a turn of {yaw} and {pitch} keeps {point} in front of the camera");
            };

            let drawn = turned.pixel_of(point, SIZE);
            assert!(
                drawn.is_some_and(|drawn| drawn.abs_diff_eq(before, 0.05)),
                "{point} drew at {before} and, turned by {yaw} and {pitch}, draws at {drawn:?}"
            );
        }
    }

    #[test]
    fn a_turn_of_a_whole_circle_returns_the_camera_it_started_from() {
        for projection in LENSES {
            let camera = overhead(projection);
            let point = Vec3::new(2.0, 0.0, -1.0);

            let Some(turned) = camera.turned_about(point, core::f32::consts::TAU, 0.0) else {
                panic!("a whole circle about {point} is a turn a {projection:?} camera takes");
            };

            assert!(
                turned.view().eye().abs_diff_eq(camera.view().eye(), 1e-4),
                "the eye came back to {:?} from {:?}",
                turned.view().eye(),
                camera.view().eye()
            );
            assert!(
                turned
                    .view()
                    .target()
                    .abs_diff_eq(camera.view().target(), 1e-4),
                "and looks at {:?}",
                turned.view().target()
            );
            assert_eq!(turned.projection(), camera.projection());
        }
    }

    #[test]
    fn a_quarter_turn_moves_the_eye_a_quarter_of_the_way_about_the_point() {
        let camera = overhead(Projection::perspective(60.0));
        let point = Vec3::new(2.0, 0.0, -1.0);

        let Some(turned) = camera.turned_about(point, core::f32::consts::FRAC_PI_2, 0.0) else {
            panic!("a quarter turn about {point} is a turn this camera takes");
        };

        let (was, now) = (camera.view().eye() - point, turned.view().eye() - point);
        let flat = |offset: Vec3| Vec2::new(offset.x, offset.z);

        assert!(
            (now.length() - was.length()).abs() < 1e-4,
            "{} meters out became {}",
            was.length(),
            now.length()
        );
        assert!((now.y - was.y).abs() < 1e-4, "and left the height alone");
        assert!(
            (flat(now).angle_to(flat(was)).abs() - core::f32::consts::FRAC_PI_2).abs() < 1e-4,
            "a quarter of the way about {point}, not {} radians",
            flat(now).angle_to(flat(was))
        );
    }

    #[test]
    fn a_turn_that_takes_the_view_past_the_up_direction_returns_no_camera() {
        let level = Camera::new(
            View::look_at(Vec3::new(0.0, 0.0, 10.0), Vec3::ZERO),
            Projection::perspective(60.0),
        );
        let short_of = core::f32::consts::FRAC_PI_2 - 0.1;

        for pitch in [short_of, -short_of] {
            assert!(
                level.turned_about(Vec3::ZERO, 0.0, pitch).is_some(),
                "{pitch} radians leaves the view under the pole"
            );
        }
        for pitch in [
            short_of + 0.2,
            -short_of - 0.2,
            core::f32::consts::PI,
            -core::f32::consts::PI,
        ] {
            assert_eq!(
                level.turned_about(Vec3::ZERO, 0.0, pitch),
                None,
                "{pitch} radians takes it past the pole"
            );
        }
    }

    #[test]
    fn a_turn_about_a_point_the_camera_does_not_draw_returns_no_camera() {
        for projection in LENSES {
            let camera = overhead(projection);
            let behind = camera.view().eye() - looking(&camera) * 5.0;
            let nowhere = Camera::new(View::look_at(Vec3::ZERO, Vec3::ZERO), projection);

            assert_eq!(camera.turned_about(behind, 0.5, 0.0), None);
            assert_eq!(camera.turned_about(camera.view().eye(), 0.5, 0.0), None);
            assert_eq!(nowhere.turned_about(Vec3::NEG_Z, 0.5, 0.0), None);

            for angle in [f32::NAN, f32::INFINITY] {
                assert_eq!(camera.turned_about(Vec3::ZERO, angle, 0.0), None, "{angle}");
                assert_eq!(camera.turned_about(Vec3::ZERO, 0.0, angle), None, "{angle}");
            }
        }
    }

    #[test]
    fn a_shift_that_would_leave_the_point_undrawn_returns_no_camera() {
        for projection in LENSES {
            let camera = overhead(projection);

            for far in [1e20, 1e25, 1e30, 1e38] {
                assert_eq!(
                    camera.shifted_so(Vec3::ZERO, Vec2::splat(far), SIZE),
                    None,
                    "{far} pixels out of a {projection:?} camera"
                );
            }
        }

        let wide = Camera::new(
            View::look_at(Vec3::new(0.0, 10.0, 10.0), Vec3::ZERO),
            Projection::orthographic(f32::MAX),
        );

        assert!(
            wide.pixel_of(Vec3::ZERO, SIZE).is_some()
                && wide.pixels_per_meter(Vec3::ZERO, SIZE).is_some(),
            "a camera that draws on its own"
        );
        assert_eq!(wide.shifted_so(Vec3::ZERO, Vec2::splat(1e30), SIZE), None);
    }

    #[test]
    fn neither_move_returns_a_camera_where_no_pixel_is_drawn_or_a_number_is_not_finite() {
        for projection in LENSES {
            let camera = overhead(projection);
            let behind = camera.view().eye() - looking(&camera) * 5.0;
            let nowhere = Camera::new(View::look_at(Vec3::ZERO, Vec3::ZERO), projection);
            let middle = SIZE.as_vec2() / 2.0;

            assert_eq!(camera.shifted_so(behind, middle, SIZE), None);
            assert_eq!(camera.zoomed_about(behind, 2.0, SIZE), None);
            assert_eq!(nowhere.shifted_so(Vec3::NEG_Z, middle, SIZE), None);
            assert_eq!(nowhere.zoomed_about(Vec3::NEG_Z, 2.0, SIZE), None);

            for size in [UVec2::ZERO, UVec2::new(1280, 0), UVec2::new(0, 720)] {
                assert_eq!(camera.shifted_so(Vec3::ZERO, middle, size), None, "{size}");
                assert_eq!(camera.zoomed_about(Vec3::ZERO, 2.0, size), None, "{size}");
            }

            for lands_at in [Vec2::NAN, Vec2::INFINITY, Vec2::new(0.0, f32::NAN)] {
                assert_eq!(camera.shifted_so(Vec3::ZERO, lands_at, SIZE), None);
            }
            for factor in [0.0, -1.0, f32::NAN, f32::INFINITY] {
                assert_eq!(camera.zoomed_about(Vec3::ZERO, factor, SIZE), None);
            }
        }
    }

    #[test]
    fn a_surface_with_no_area_and_a_view_with_no_direction_draw_no_pixel() {
        for projection in LENSES {
            let camera = overhead(projection);
            let nowhere = Camera::new(View::look_at(Vec3::ZERO, Vec3::ZERO), projection);

            for size in [UVec2::ZERO, UVec2::new(1280, 0), UVec2::new(0, 720)] {
                assert_eq!(camera.pixel_of(Vec3::ZERO, size), None, "{size}");
                assert_eq!(camera.pixels_per_meter(Vec3::ZERO, size), None, "{size}");
            }
            assert_eq!(nowhere.pixel_of(Vec3::NEG_Z, SIZE), None);
            assert_eq!(nowhere.pixels_per_meter(Vec3::NEG_Z, SIZE), None);
        }
    }
}