mirage-engine 0.2.0

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
//! What a blocker casts over the ground a light reaches.

use super::*;

/// The position a blocker is drawn at for a sun and a cone, and its
/// material.
const STANDING: Vec3 = Vec3::new(-2.0, 2.0, 0.0);
const SOLID: Material = Material::lit(Color::WHITE);

/// The side of the target a cascade scene is read off.
const FIELD: u32 = 128;

/// The two views a standing sprite is seen from: straight down on it,
/// which leaves it in no upright plane at all, and down at it from
/// behind, which is the view a game stands a sprite in.
const OVERHEAD: Camera = Camera::new(
    View::look_at(Vec3::new(0.0, 10.0, 0.0), Vec3::ZERO).with_up(Vec3::NEG_Z),
    Projection::orthographic(ACROSS),
);
const OVER_THE_SHOULDER: Camera = Camera::new(
    View::look_at(Vec3::new(0.0, 4.0, 5.0), Vec3::new(0.0, 1.0, 0.0)),
    Projection::perspective(45.0),
);

/// Ground extent a cascade scene lays down, in meters.
const LONG: f32 = 100.0;

/// Ground extent a cascade scene lays down for a reading out to the end of a
/// sun's reach, in meters.
const LONGEST: f32 = 600.0;

/// The two cameras a cascade scene is seen from, both looking at the
/// origin: one close over it, within the nearest cascade, and one far
/// back and above it, past where that cascade is split.
const CLOSE: Camera = Camera::new(
    View::look_at(Vec3::new(0.0, 1.2, 2.5), Vec3::ZERO),
    Projection::perspective(60.0),
);
const BACK: Camera = Camera::new(
    View::look_at(Vec3::new(0.0, 12.0, 30.0), Vec3::ZERO),
    Projection::perspective(60.0),
);

/// A camera 100 meters over the ground, looking straight down: every pixel
/// of it reads ground 100 meters along its view.
const HIGH: Camera = Camera::new(
    View::look_at(Vec3::new(0.0, 100.0, 0.0), Vec3::ZERO).with_up(Vec3::NEG_Z),
    Projection::perspective(60.0),
);

/// A camera back and above the ground looking down it at 45 degrees, so
/// that one column of its target reads ground from a few meters out to
/// past the end of a sun's reach.
const ALONG: Camera = Camera::new(
    View::look_at(Vec3::new(0.0, 100.0, 100.0), Vec3::ZERO),
    Projection::perspective(60.0),
);

/// A camera 5 meters over the ground looking level along it, so that one
/// column of its target reads ground from under 9 meters out to past the
/// 12.5 the nearest cascade ends at.
const LEVEL: Camera = Camera::new(
    View::look_at(Vec3::new(0.0, 5.0, 30.0), Vec3::new(0.0, 5.0, 0.0)),
    Projection::perspective(60.0),
);

/// The side of the target those columns are read off, large enough that the
/// span a cascade hands over across covers many of its rows.
const TALL: u32 = 512;

/// A camera straight down over the ground a lamp and a cone light below,
/// whose target holds ground and no sky.
const DOWN: Camera = Camera::new(
    View::look_at(Vec3::new(0.0, 10.0, 0.0), Vec3::ZERO).with_up(Vec3::NEG_Z),
    Projection::orthographic(ACROSS),
);

/// Where those two stand, and how far they reach, in meters: the ground they
/// light lies three quarters of the way out to their range, where a
/// perspective map holds the least depth to the meter, and at a slope from
/// them, where a plane's own depth runs across the map.
const LAMP: Vec3 = Vec3::new(0.0, 24.0, 18.0);
const LAMP_RANGE: f32 = 40.0;

/// How wide the cone of those readings opens, in radians: wide enough that
/// the whole target lies inside it at that range.
const CONE: f32 = 0.6;

/// The view a shadow's edge is read from twice: 2 meters over the ground
/// looking level along it, so that one row of the target reads ground
/// `EDGE_DEPTH` meters out.
const ALONGSIDE: View = View::look_at(Vec3::new(0.0, 2.0, 12.0), Vec3::new(0.0, 2.0, 0.0));

/// The sun those two readings are lit by: low over the ground, where a lift
/// off it moves a shadow's edge furthest.
const LOW: Vec3 = Vec3::new(-2.0, -1.0, 0.0);

/// The depth along that view the edge is read at, in meters.
const EDGE_DEPTH: f32 = 15.0;

/// The near planes the two readings clip at, in meters. A sun's nearest
/// slice covers the 12.5 meters past the near plane, so ground `EDGE_DEPTH`
/// out lies in the slice past the nearest one for the first and inside the
/// nearest one for the second, both clear of where a slice hands over. The
/// two draw the same pixels: where a lens clips moves nothing it draws.
const CLIPPED_AT: [f32; 2] = [0.1, 6.0];

/// The far plane both of them clip at, in meters: past the reach a sun's
/// slices cover, so neither reading leaves them shorter.
const REACHING: f32 = 400.0;

/// The view depths the end of the reach is read between, in meters: ground
/// either side of the 200 meters a sun's cascades reach.
const NEARER: f32 = 150.0;
const FURTHER: f32 = 220.0;

/// The view depths where the nearest cascade hands over is read between, in
/// meters: ground either side of the 12.5 that cascade ends at.
const NEARER_HAND: f32 = 9.0;
const FURTHER_HAND: f32 = 20.0;

/// How far either side of the shadow's own edge those columns are read, in
/// pixels: past where either map's filter reaches at that depth, so the
/// columns hold the whole edge, the shadow inside it and the light outside
/// it.
const BESIDE: u32 = 20;

/// The most one pixel of that column may differ from its neighbor by, out
/// of 255, for the end of the reach to read as a fade and not an edge. The
/// fade covers many rows, and an edge steps by more than half the range.
const STEP: u8 = 32;

meshes! { enum RelievedSet { Relieved } }

/// A ground plane with a blocker drawn over it, turned to the camera
/// or not and faded or not, lit by one light.
struct Cast {
    light: Light,
    blocker: Option<(Vec3, Material)>,
    faced: bool,
    fade: f32,
}

/// Seen from straight above, so that the ground fills the target and the
/// blocker is well left of what is read back.
impl Game for Cast {
    type Meshes = GroundSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = NoSurfaceStyles;
    type PostEffects = NoPostEffects;

    fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        ctx.set_camera(Camera::new(
            View::look_at(Vec3::Y * 10.0, Vec3::ZERO).with_up(Vec3::NEG_Z),
            Projection::orthographic(ACROSS),
        ));
        ctx.light(self.light);
        ctx.draw(
            Ground::Floor
                .at(Transform::from_scale(Vec3::splat(ACROSS)))
                .material(Material::lit(Color::WHITE)),
        );
        if let Some((standing, material)) = self.blocker {
            let blocker = Ground::Blocker
                .at(standing)
                .material(material)
                .faded(self.fade);
            ctx.draw(if self.faced {
                blocker.billboard()
            } else {
                blocker
            });
        }
    }
}

/// The colors one cast scene leaves at the origin, which every blocker
/// here is in front of, and three meters along `X`, which none is.
fn cast(light: Light, blocker: Option<(Vec3, Material)>) -> Option<([u8; 4], [u8; 4])> {
    shone(Cast {
        light,
        blocker,
        faced: false,
        fade: 1.0,
    })
}

/// The same, over a scene the test laid out itself.
fn shone(scene: Cast) -> Option<([u8; 4], [u8; 4])> {
    let config = raw("headless shadows").with_shadow_resolution(512);
    let pixels = sized(config, UVec2::splat(YARD), scene)?;
    let ground = |across: u32| pixel(&pixels, across, YARD / 2, YARD);

    Some((ground(YARD / 2), ground(YARD / 2 + 24)))
}

#[test]
fn a_translucent_blocker_takes_the_fraction_of_the_light_its_alpha_covers() {
    let sun = Light::directional(Vec3::new(1.0, -1.0, 0.0), Color::WHITE).shadow();
    let glass = |alpha| Material::lit(Color::rgba(1.0, 1.0, 1.0, alpha));

    let Some((behind_glass, _)) = cast(sun, Some((STANDING, glass(0.5)))) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some((behind_a_pane_of_air, _)) = cast(sun, Some((STANDING, glass(0.0)))) else {
        return;
    };
    let Some((clear, _)) = cast(sun, None) else {
        return;
    };

    assert!(
        behind_glass[0] > 0 && behind_glass[0] < clear[0],
        "half of the light passes: {behind_glass:?} against {clear:?}"
    );
    assert_eq!(
        behind_a_pane_of_air, clear,
        "and a draw covering nothing blocks nothing"
    );
}

#[test]
fn an_additive_blocker_casts_nothing() {
    let sun = Light::directional(Vec3::new(1.0, -1.0, 0.0), Color::WHITE).shadow();

    let Some((behind, _)) = cast(sun, Some((STANDING, SOLID.additive()))) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some((clear, _)) = cast(sun, None) else {
        return;
    };

    assert_eq!(behind, clear, "a draw that is light blocks none of it");
}

/// A ground plane with one faced sprite standing on it, lit by a sun
/// crossing the ground along `+Z`, seen from the camera the test names.
struct Standing {
    sprite: Relieved,
    seen: Camera,
    casts: bool,
}

impl Game for Standing {
    type Meshes = RelievedSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = NoSurfaceStyles;
    type PostEffects = NoPostEffects;

    fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        ctx.set_camera(self.seen);
        let sun = Light::directional(Vec3::new(0.0, -1.0, 1.0), Color::WHITE);
        ctx.light(if self.casts { sun.shadow() } else { sun });
        ctx.draw(
            Relieved::Ground
                .at(Transform::from_scale(Vec3::splat(ACROSS)))
                .material(Material::lit(Color::WHITE)),
        );
        ctx.draw(
            self.sprite
                .at(Transform::from_scale_rotation_translation(
                    Vec3::new(2.0, 2.0, 1.0),
                    Quat::IDENTITY,
                    Vec3::Y,
                ))
                .material(Material::lit(Color::WHITE).cutout())
                .billboard(),
        );
    }
}

/// The meshes a `Standing` scene draws: the ground, a flat sprite, and
/// two drawn in a relief a whole sprite width deep.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
enum Relieved {
    Ground,
    Flat,
    Mapped,
    Domed,
}

impl Catalog for Relieved {
    fn catalog() -> Vec<Self> {
        vec![Self::Ground, Self::Flat, Self::Mapped, Self::Domed]
    }
}

impl Mesh for Relieved {
    fn build(&self, assets: &Assets) -> MeshData {
        let white = TextureData::rgba8(UVec2::ONE, vec![u8::MAX; 4]);
        match self {
            Self::Ground => Plane.build(assets),
            Self::Flat => Quad.build(assets).with_texture(white),
            // A normal straight out of the sprite, at its full depth.
            Self::Mapped => Quad
                .build(assets)
                .with_texture(white)
                .with_relief(ReliefData::rgba8(
                    UVec2::ONE,
                    vec![128, 128, u8::MAX, u8::MAX],
                )),
            // The same at its full depth, turned up the map.
            Self::Domed => Quad
                .build(assets)
                .with_texture(white)
                .with_relief(ReliefData::rgba8(UVec2::ONE, vec![128, 218, 218, u8::MAX])),
        }
    }
}

/// The color a `Standing` scene's own sprite draws at its middle, which
/// both cameras below look at.
fn stood(sprite: Relieved, seen: Camera, casts: bool) -> Option<[u8; 4]> {
    let config = raw("headless relief").with_shadow_resolution(512);
    let scene = Standing {
        sprite,
        seen,
        casts,
    };

    Some(middle(&sized(config, UVec2::splat(SIDE), scene)?, SIDE))
}

#[test]
fn a_faced_draw_never_stands_in_its_own_shadow() {
    for seen in [OVERHEAD, OVER_THE_SHOULDER] {
        let sprite = |sprite, casts| stood(sprite, seen, casts);

        let Some(domed) = sprite(Relieved::Domed, true) else {
            eprintln!("skipped: this machine has no usable graphics adapter");
            return;
        };
        let (Some(domed_clear), Some(mapped), Some(mapped_clear), Some(flat), Some(flat_clear)) = (
            sprite(Relieved::Domed, false),
            sprite(Relieved::Mapped, true),
            sprite(Relieved::Mapped, false),
            sprite(Relieved::Flat, true),
            sprite(Relieved::Flat, false),
        ) else {
            return;
        };

        assert_eq!(
            domed, domed_clear,
            "a relief turned off the sprite clears its own record"
        );
        assert_eq!(
            mapped, mapped_clear,
            "one straight out of it clears its own"
        );
        assert_eq!(flat, flat_clear, "and a flat sprite clears its own");
        assert_ne!(mapped, flat, "where the three are lit by different normals");
        assert_ne!(domed, mapped, "the turned one taking its own share");
    }
}

/// A ground plane with one blocker over it, lit by a sun that drops the
/// blocker's shadow over the origin.
struct Cascades {
    camera: Camera,
    light: Light,
    /// The side of the ground it lays down, in meters.
    ground: f32,
    blocker: Option<Transform>,
}

impl Game for Cascades {
    type Meshes = GroundSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = NoSurfaceStyles;
    type PostEffects = NoPostEffects;

    fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        ctx.set_camera(self.camera);
        ctx.light(self.light);
        ctx.draw(
            Ground::Floor
                .at(Transform::from_scale(Vec3::splat(self.ground)))
                .material(SOLID),
        );
        if let Some(standing) = self.blocker {
            ctx.draw(Ground::Blocker.at(standing).material(SOLID));
        }
    }
}

/// A blocker `side` meters across, placed where the sun of a cascade
/// scene drops its shadow over the origin.
fn standing(side: f32) -> Transform {
    let lift = side * 0.75;

    Transform::from_scale_rotation_translation(
        Vec3::splat(side),
        Quat::IDENTITY,
        Vec3::new(0.0, lift, -lift),
    )
}

/// A blocker 30 meters over the ground, placed so that a sun crossing it
/// along `+X` drops its shadow over the origin, and far enough off the
/// origin that the blocker itself is not read there.
fn lofted() -> Transform {
    Transform::from_scale_rotation_translation(
        Vec3::splat(8.0),
        Quat::IDENTITY,
        Vec3::new(-30.0, 30.0, 0.0),
    )
}

/// A slab over every meter of the ground that camera reads, looking along
/// it, 50 meters above the camera: it casts into the sun's maps and stays
/// out of the view.
fn slab() -> Transform {
    Transform::from_scale_rotation_translation(
        Vec3::new(300.0, 1.0, 305.0),
        Quat::IDENTITY,
        Vec3::new(0.0, 150.0, -132.5),
    )
}

/// A wall standing along the view 10 meters to one side, whose shadow's own
/// edge a sun crossing it at 45 degrees drops over the ground straight
/// ahead: the edge runs away from the camera down the target's own middle.
fn wall() -> Transform {
    Transform::from_scale_rotation_translation(
        Vec3::new(1.0, 10.0, 120.0),
        Quat::IDENTITY,
        Vec3::new(10.5, 5.0, -20.0),
    )
}

/// A slab floating four meters over the ground and running along the view,
/// beside what the camera reading the edge below looks at: a sun crossing it
/// drops a band of shadow over the ground, whose edges run away from the
/// camera, and the slab itself stays over the horizon.
fn floating() -> Transform {
    Transform::from_scale_rotation_translation(
        Vec3::new(4.0, 0.5, 120.0),
        Quat::IDENTITY,
        Vec3::new(4.0, 4.0, -20.0),
    )
}

/// The depth along `camera`'s view of the ground the pixel `across` and
/// `row` down a `TALL`-sized target reads; absent where that pixel reads no
/// ground at all.
fn ground_depth(camera: Camera, across: u32, row: u32) -> Option<f32> {
    let at = Vec2::new(across as f32 + 0.5, row as f32 + 0.5);
    let ray = camera.ray_through(at, UVec2::splat(TALL));
    let reached = ray.hit_plane(crate::ray::Plane {
        point: Vec3::ZERO,
        normal: Vec3::Y,
    })?;
    let view = camera.view();

    Some(view.direction().dot(ray.at(reached) - view.eye()))
}

/// The rows of a `TALL`-sized target whose middle column reads ground
/// between `nearer` and `further` meters along `camera`'s view, from the
/// nearer ground up the target to the further.
fn rows_between(camera: Camera, nearer: f32, further: f32) -> Vec<u32> {
    (0..TALL)
        .rev()
        .filter(|&row| {
            ground_depth(camera, TALL / 2, row)
                .is_some_and(|depth| (nearer..further).contains(&depth))
        })
        .collect()
}

/// Where a band of shadow lies across `row`, over a `TALL`-sized target: the
/// column halfway between its two edges, each taken as the pixel where the
/// row crosses halfway between what it reads inside the shadow and what it
/// reads outside it. Absent where the row holds no shadow to have edges.
///
/// The two edges take that crossing to either side of themselves, so what a
/// wider filter spreads them by leaves the column between them where it is.
fn shadow_across(pixels: &[u8], row: u32) -> Option<f32> {
    let line: Vec<u32> = (0..TALL)
        .map(|across| u32::from(pixel(pixels, across, row, TALL)[0]))
        .collect();
    let darkest = *line.iter().min()?;
    let lightest = *line.iter().max()?;
    if darkest * 2 >= lightest {
        return None;
    }
    let shadowed = |reading: &u32| reading * 2 < darkest + lightest;
    let first = line.iter().position(shadowed)?;
    let last = line.iter().rposition(shadowed)?;

    Some((first + last) as f32 / 2.0)
}

/// The pixels one cascade scene leaves, over a target `side` pixels square.
fn field(side: u32, scene: Cascades) -> Option<Vec<u8>> {
    let config = raw("headless cascades").with_shadow_resolution(512);

    sized(config, UVec2::splat(side), scene)
}

/// The least of the ground a cascade scene lit by `light` alone leaves over
/// the bottom quarter of its target, which holds ground and no sky from
/// either camera below.
fn darkest_ground(camera: Camera, light: Light) -> Option<u8> {
    let scene = Cascades {
        camera,
        light,
        ground: LONG,
        blocker: None,
    };
    let pixels = field(FIELD, scene)?;

    (3 * FIELD / 4..FIELD)
        .flat_map(|row| (0..FIELD).map(move |across| (across, row)))
        .map(|(across, row)| pixel(&pixels, across, row, FIELD)[0])
        .min()
}

/// The color one cascade scene leaves at the origin, which is the
/// middle of either camera's view.
fn over(camera: Camera, light: Light, blocker: Option<f32>) -> Option<[u8; 4]> {
    let scene = Cascades {
        camera,
        light,
        ground: LONG,
        blocker: blocker.map(standing),
    };

    Some(middle(&field(FIELD, scene)?, FIELD))
}

#[test]
fn a_suns_cascades_darken_the_ground_near_the_camera_and_far_from_it() {
    let sun = Light::directional(Vec3::new(0.0, -1.0, 1.0), Color::WHITE).shadow();
    let Some([near, ..]) = over(CLOSE, sun, Some(1.0)) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let (Some([near_clear, ..]), Some([far, ..]), Some([far_clear, ..])) = (
        over(CLOSE, sun, None),
        over(BACK, sun, Some(3.0)),
        over(BACK, sun, None),
    ) else {
        return;
    };

    assert!(
        near < near_clear,
        "the nearest cascade darkens the ground behind a blocker, \
         which reads {near} against {near_clear}"
    );
    assert!(
        far < far_clear,
        "and the widest carries what is past its split, \
         which reads {far} against {far_clear}"
    );
}

#[test]
fn a_suns_shadow_lands_a_hundred_meters_from_the_camera() {
    let sun = Light::directional(Vec3::new(1.0, -1.0, 0.0), Color::WHITE).shadow();
    let ground = |blocker| {
        let scene = Cascades {
            camera: HIGH,
            light: sun,
            ground: LONGEST,
            blocker,
        };

        Some(middle(&field(FIELD, scene)?, FIELD)[0])
    };

    let Some(shadowed) = ground(Some(lofted())) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(clear) = ground(None) else {
        return;
    };

    assert!(
        shadowed < clear / 2,
        "a sun darkens ground a hundred meters out, which reads \
         {shadowed} against {clear}"
    );
}

#[test]
fn a_shadow_crossing_the_end_of_a_suns_reach_fades_out_rather_than_ending_on_a_line() {
    let scene = Cascades {
        camera: ALONG,
        light: Light::directional(Vec3::NEG_Y, Color::WHITE).shadow(),
        ground: LONGEST,
        blocker: Some(slab()),
    };
    let Some(pixels) = field(TALL, scene) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    let line: Vec<u8> = rows_between(ALONG, NEARER, FURTHER)
        .into_iter()
        .map(|row| pixel(&pixels, TALL / 2, row, TALL)[0])
        .collect();

    let (Some(&shadowed), Some(&lit)) = (line.first(), line.last()) else {
        panic!("the camera reads ground between {NEARER} and {FURTHER} meters out");
    };
    assert!(
        line.len() > 64,
        "the end of the reach is read over {} pixels of ground",
        line.len()
    );
    assert!(
        u32::from(shadowed) * 2 < u32::from(lit),
        "which run out of the shadow into the light, from {shadowed} to {lit}"
    );
    for (at, (behind, ahead)) in line.iter().zip(&line[1..]).enumerate() {
        assert!(
            ahead.abs_diff(*behind) <= STEP,
            "and read {behind} against {ahead} between pixels {at} and {}, \
             where the whole line reads {line:?}",
            at + 1
        );
    }
}

#[test]
fn the_edge_of_a_shadow_crossing_the_first_hand_over_reads_without_a_step() {
    let scene = Cascades {
        camera: LEVEL,
        light: Light::directional(Vec3::new(-1.0, -1.0, 0.0), Color::WHITE).shadow(),
        ground: LONGEST,
        blocker: Some(wall()),
    };
    let Some(pixels) = field(TALL, scene) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    let rows = rows_between(LEVEL, NEARER_HAND, FURTHER_HAND);
    let beside = |across: u32| -> Vec<u8> {
        rows.iter()
            .map(|&row| pixel(&pixels, across, row, TALL)[0])
            .collect()
    };
    let columns: Vec<Vec<u8>> = (1..=BESIDE)
        .flat_map(|off| [beside(TALL / 2 - off), beside(TALL / 2 + off)])
        .collect();
    let readings = || columns.iter().flatten().copied();

    let (Some(darkest), Some(lightest)) = (readings().min(), readings().max()) else {
        panic!("the camera reads ground between {NEARER_HAND} and {FURTHER_HAND} meters out");
    };
    assert!(
        rows.len() > 64,
        "the first hand-over is read over {} rows of ground",
        rows.len()
    );
    assert!(
        u32::from(darkest) * 2 < u32::from(lightest),
        "which hold the shadow's own edge, reading {darkest} against {lightest}"
    );
    for (at, line) in columns.iter().enumerate() {
        for (row, (behind, ahead)) in line.iter().zip(&line[1..]).enumerate() {
            assert!(
                ahead.abs_diff(*behind) <= STEP,
                "and column {at} reads {behind} against {ahead} between its rows \
                 {row} and {}, where the whole column reads {line:?}",
                row + 1
            );
        }
    }
}

#[test]
fn a_shadow_lands_in_one_place_whichever_cascade_reads_the_ground_under_it() {
    let seen = |near: f32| {
        Camera::new(
            ALONGSIDE,
            Projection::perspective(60.0).clip(near..REACHING),
        )
    };
    let shadow = |near: f32, row: u32| {
        let scene = Cascades {
            camera: seen(near),
            light: Light::directional(LOW, Color::WHITE).shadow(),
            ground: LONGEST,
            blocker: Some(floating()),
        };

        Some(shadow_across(&field(TALL, scene)?, row))
    };

    let rows = rows_between(seen(CLIPPED_AT[0]), EDGE_DEPTH - 0.5, EDGE_DEPTH + 0.5);
    let Some(&row) = rows.first() else {
        panic!("the camera reads ground {EDGE_DEPTH} meters along its view");
    };
    let Some(inside) = shadow(CLIPPED_AT[0], row) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(past) = shadow(CLIPPED_AT[1], row) else {
        return;
    };

    let (Some(inside), Some(past)) = (inside, past) else {
        panic!("the row the two are read along holds a band of shadow: {inside:?}, {past:?}");
    };
    assert!(
        (inside - past).abs() <= 1.0,
        "one caster's shadow lands where it lands, reading the column between \
         its edges at {inside} from the slice holding the ground and at {past} \
         from the slice past it"
    );
}

#[test]
fn a_lit_plane_at_a_slant_to_the_sun_stands_in_no_shadow_of_its_own() {
    let sun = Light::directional(Vec3::new(0.0, -1.0, 1.0), Color::WHITE);

    let Some(near) = darkest_ground(CLOSE, sun.shadow()) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let (Some(near_clear), Some(far), Some(far_clear)) = (
        darkest_ground(CLOSE, sun),
        darkest_ground(BACK, sun.shadow()),
        darkest_ground(BACK, sun),
    ) else {
        return;
    };

    assert_eq!(
        near, near_clear,
        "ground the nearest cascade reads is as lit under a sun that casts"
    );
    assert_eq!(
        far, far_clear,
        "and so is ground the widest reads, whose texels are wider"
    );
}

#[test]
fn a_lit_plane_at_a_slant_to_a_lamp_stands_in_no_shadow_of_its_own() {
    let lamp = Light::point(LAMP, Color::WHITE, LAMP_RANGE);

    let Some(casting) = darkest_ground(DOWN, lamp.shadow()) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(clear) = darkest_ground(DOWN, lamp) else {
        return;
    };

    assert_eq!(
        casting, clear,
        "ground near the end of a lamp's range is as lit under one that casts"
    );
}

#[test]
fn a_lit_plane_at_a_slant_to_a_cone_stands_in_no_shadow_of_its_own() {
    let cone = Light::spot(Spot {
        position: LAMP,
        direction: -LAMP,
        color: Color::WHITE,
        range: LAMP_RANGE,
        angle: CONE,
    });

    let Some(casting) = darkest_ground(DOWN, cone.shadow()) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(clear) = darkest_ground(DOWN, cone) else {
        return;
    };

    assert_eq!(casting, clear, "and so is ground near the end of a cone's");
}