mirage-engine 0.1.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
//! What a post effect leaves of the frame it reads.

use super::styles::refused;
use super::*;

/// How deep [`Corners`] darkens the corners of the frame.
const VIGNETTE: f32 = 0.5;

/// What [`Lift`] adds, which a reading of the target reads back out; small
/// enough that neither order of the two reaches the white the target holds
/// at.
const LIFTED: f32 = 0.1;

/// How far the view a depth is read over reaches, in meters.
const REACH: f32 = 100.0;

/// The light an emissive square holds, well past what the screen shows.
const GLOW: Color = Color::rgb(4.0, 0.0, 0.0);

/// An effect that writes back the pixel it was passed.
#[derive(ShaderValues)]
struct Unchanged;

impl PostEffect for Unchanged {
    const STAGE: EffectStage = EffectStage::ToneMapped;
    const SHADER: &'static str = "fn draw(pixel: Pixel) -> vec4<f32> { return pixel.color; }";
}

/// An effect that darkens the corners of the frame by the fraction it is
/// passed, leaving the middle of it alone.
#[derive(ShaderValues)]
struct Corners {
    depth: f32,
}

impl PostEffect for Corners {
    const STAGE: EffectStage = EffectStage::ToneMapped;
    const SHADER: &'static str = "fn draw(pixel: Pixel) -> vec4<f32> {
         let middle = vec2<f32>(0.5);
         let out = distance(pixel.uv, middle) / length(middle);
         return vec4<f32>(pixel.color.rgb * (1.0 - effect.depth * out), pixel.color.a);
     }";
}

/// An effect that adds what it is passed to every pixel.
#[derive(ShaderValues)]
struct Lift {
    by: f32,
}

impl PostEffect for Lift {
    const STAGE: EffectStage = EffectStage::ToneMapped;
    const SHADER: &'static str = "fn draw(pixel: Pixel) -> vec4<f32> {
         return vec4<f32>(pixel.color.rgb + vec3<f32>(effect.by), pixel.color.a);
     }";
}

/// An effect that halves every pixel, which draws another frame in the
/// other order.
#[derive(ShaderValues)]
struct Halve;

impl PostEffect for Halve {
    const STAGE: EffectStage = EffectStage::ToneMapped;
    const SHADER: &'static str = "fn draw(pixel: Pixel) -> vec4<f32> {
         return vec4<f32>(pixel.color.rgb * 0.5, pixel.color.a);
     }";
}

/// An effect that keeps only the light the scene holds past what the
/// screen shows, which only a stage before the tone map reads.
#[derive(ShaderValues)]
struct Past;

impl PostEffect for Past {
    const STAGE: EffectStage = EffectStage::Lit;
    const SHADER: &'static str = "fn draw(pixel: Pixel) -> vec4<f32> {
         return vec4<f32>(max(pixel.color.rgb - vec3<f32>(1.0), vec3<f32>(0.0)), 1.0);
     }";
}

/// An effect that paints the scene's own depth as a fraction of how far the
/// view reaches.
#[derive(ShaderValues)]
struct Reach {
    over: f32,
}

impl PostEffect for Reach {
    const STAGE: EffectStage = EffectStage::Lit;
    const SHADER: &'static str = "fn draw(pixel: Pixel) -> vec4<f32> {
         return vec4<f32>(vec3<f32>(depth_at(pixel.uv) / effect.over), 1.0);
     }";
}

/// An effect over the UI that halves what it covers; [`Halve`] is the one
/// under it.
#[derive(ShaderValues)]
struct Glass;

impl PostEffect for Glass {
    const STAGE: EffectStage = EffectStage::OverUi;
    const SHADER: &'static str = "fn draw(pixel: Pixel) -> vec4<f32> {
         return vec4<f32>(pixel.color.rgb * 0.5, pixel.color.a);
     }";
}

/// An effect whose WGSL names something no shader has.
#[derive(ShaderValues)]
struct Shattered;

impl PostEffect for Shattered {
    const STAGE: EffectStage = EffectStage::ToneMapped;
    const SHADER: &'static str = "fn draw(pixel: Pixel) -> vec4<f32> { return nowhere; }";
}

post_effects! { enum Plain { Unchanged } }
post_effects! { enum Vignetting { Corners } }
post_effects! { enum Ordered { Lift, Halve } }
post_effects! { enum Emitting { Past } }
post_effects! { enum Reaching { Reach } }
post_effects! { enum Glassing { Glass } }
post_effects! { enum Halving { Halve } }
post_effects! { enum Shattering { Shattered } }

/// One square of even color filling the view, so that two readings of it
/// differ only by the effects a frame ran.
fn court<G: Game>(ctx: &mut FrameContext<'_, G>)
where
    G::Meshes: Holds<Quad> + From<Quad>,
{
    ctx.set_camera(FLAT);
    ctx.draw(
        Quad.at(Vec3::ZERO)
            .material(Material::color(Color::rgb(0.6, 0.3, 0.15))),
    );
}

/// The court alone, which every game below draws the same way.
struct Bare;

impl Game for Bare {
    type Meshes = QuadSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

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

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        court(ctx);
    }
}

/// The court under a game that declares an effect and runs it only where
/// the test sets it running.
struct PostEffected {
    running: bool,
}

impl Game for PostEffected {
    type Meshes = QuadSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = Plain;

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

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        court(ctx);
        if self.running {
            ctx.set_post_effect(Unchanged);
        }
    }
}

/// The court under a vignette.
struct Vignetted;

impl Game for Vignetted {
    type Meshes = QuadSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = Vignetting;

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

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        court(ctx);
        ctx.set_post_effect(Corners { depth: VIGNETTE });
    }
}

/// The court under two effects of one stage whose order the frame shows.
struct Sequenced;

impl Game for Sequenced {
    type Meshes = QuadSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = Ordered;

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

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        court(ctx);
        ctx.set_post_effect(Halve);
        ctx.set_post_effect(Lift { by: LIFTED });
    }
}

/// An emissive square over the middle of a dark view, under an effect
/// that keeps only what the screen cannot show, and whatever bloom the test
/// set.
struct Emissive {
    bloom: f32,
    screened: bool,
}

impl Game for Emissive {
    type Meshes = QuadSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = Emitting;

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

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        ctx.set_camera(FLAT);
        ctx.set_bloom(self.bloom);
        ctx.draw(
            Quad.at(Transform::from_scale(Vec3::splat(0.25)))
                .material(Material::color(Color::BLACK).emissive(GLOW)),
        );
        if self.screened {
            ctx.set_post_effect(Past);
        }
    }
}

/// One cube in the middle of a view that reaches [`REACH`] meters, under a
/// effect that paints the depth it was drawn at.
struct Depths;

impl Game for Depths {
    type Meshes = CubeSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = Reaching;

    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::Z * 4.0, Vec3::ZERO),
            Projection::perspective(45.0).clip(0.1..REACH),
        ));
        ctx.draw(Cube.at(Vec3::ZERO).material(Material::color(Color::WHITE)));
        ctx.set_post_effect(Reach { over: REACH });
    }
}

/// A game whose one post effect does not compile.
struct Cracking;

impl Game for Cracking {
    type Meshes = QuadSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = Shattering;

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

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

#[test]
fn an_effect_no_frame_runs_leaves_the_frame_as_a_game_with_none_draws_it() {
    let drawn = |game| rendered(raw("headless effects"), game);
    let Some(none) = drawn(Bare) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(quiet) = rendered(raw("headless effects"), PostEffected { running: false }) else {
        return;
    };
    let Some(same) = rendered(raw("headless effects"), PostEffected { running: true }) else {
        return;
    };

    assert_eq!(
        quiet, none,
        "a set no frame draws from costs the frame nothing"
    );
    assert_eq!(
        same, none,
        "and an effect that writes back what it was passed changes nothing"
    );
}

#[test]
fn a_vignette_darkens_a_corner_by_the_fraction_it_was_passed() {
    let Some(plain) = rendered(raw("headless effects"), Bare) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(vignetted) = rendered(raw("headless effects"), Vignetted) else {
        return;
    };

    let kept = |at: (u32, u32)| {
        let read = |pixels: &[u8]| f32::from(pixel(pixels, at.0, at.1)[0]);
        read(&vignetted) / read(&plain)
    };
    // The middle pixel's own center is half a pixel off the middle of the
    // frame, so the fraction it keeps is just under the whole of it.
    let middle = kept((SIDE / 2, SIDE / 2));
    assert!(
        (middle - 1.0).abs() < 0.02,
        "the middle is as deep as it was, got {middle}"
    );
    let corner = kept((0, 0));
    assert!(
        (corner - (1.0 - VIGNETTE)).abs() < 0.02,
        "and the corner keeps the fraction the effect was passed, got {corner}"
    );
}

#[test]
fn two_effects_of_one_stage_run_in_the_order_their_set_names_them() {
    let Some(pixels) = rendered(raw("headless effects"), Sequenced) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(plain) = rendered(raw("headless effects"), Bare) else {
        return;
    };

    let read = |pixels: &[u8]| pixel(pixels, SIDE / 2, SIDE / 2)[0] as f32 / 255.0;
    let lifted_then_halved = (read(&plain) + LIFTED) * 0.5;
    let halved_then_lifted = read(&plain) * 0.5 + LIFTED;

    assert!(
        (read(&pixels) - lifted_then_halved).abs() < 0.01,
        "the set names the lift first, got {} against {lifted_then_halved} and \
         {halved_then_lifted}",
        read(&pixels)
    );
}

#[test]
fn a_lit_stage_effect_reads_the_light_the_screen_cannot_hold_and_its_own_output_blooms() {
    let lit = |bloom, screened| rendered(raw("headless effects"), Emissive { bloom, screened });
    let Some(kept) = lit(0.0, true) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(spread) = lit(0.5, true) else {
        return;
    };

    let outside = (SIDE / 2 + SIDE / 6, SIDE / 2);
    assert!(
        pixel(&kept, SIDE / 2, SIDE / 2)[0] > 200,
        "the effect kept the light past what the screen shows"
    );
    assert_eq!(
        pixel(&kept, outside.0, outside.1),
        [0, 0, 0, u8::MAX],
        "and nothing of it where the draw does not reach"
    );
    assert!(
        pixel(&spread, outside.0, outside.1)[0] > 8,
        "which the chain then spreads past the draw's own edge"
    );
}

#[test]
fn the_scene_depth_an_effect_reads_is_nearer_under_a_draw_than_where_nothing_was_drawn() {
    for antialiasing in [true, false] {
        let config = raw("headless effects").with_antialiasing(antialiasing);
        let Some(pixels) = rendered(config, Depths) else {
            eprintln!("skipped: this machine has no usable graphics adapter");
            return;
        };

        let under = pixel(&pixels, SIDE / 2, SIDE / 2)[0];
        let beside = pixel(&pixels, 1, 1)[0];
        assert_eq!(
            beside,
            u8::MAX,
            "nothing was drawn in the corner, so the view reaches its own far clip there \
             ({antialiasing})"
        );
        assert!(
            under > 0 && under < beside / 2,
            "and the cube stands well in front of it, got {under} ({antialiasing})"
        );
    }
}

#[test]
fn an_effect_that_does_not_compile_stops_startup_naming_it() {
    let Some(error) = refused(Cracking) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    assert!(error.contains("Shattered"), "{error}");
    assert!(error.contains("nowhere"), "and names what the shader read");
}

#[cfg(feature = "ui")]
mod ui {
    use super::*;

    /// The side of the target the readings below are taken off.
    const PANE: u32 = 64;

    /// The badge's own square, and a pixel well inside it.
    const BADGE: f32 = 32.0;
    const INSIDE: (u32, u32) = (16, 16);

    /// Nothing in `3D`, and one opaque square in the top left of the UI
    /// layer.
    struct Badge;

    impl Game for Badge {
        type Meshes = CubeSet;
        type Sounds = NoSounds;
        type InputActions = NoInputActions;
        type Skyboxes = NoSkyboxes;
        type SurfaceStyles = ();
        type PostEffects = ();

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

        fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
            ctx.ui(|ui| {
                ui.painter().rect_filled(
                    egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(32.0, 32.0)),
                    0.0,
                    egui::Color32::RED,
                );
            });
        }
    }

    /// A red badge over the scene, under whichever of the two effects the
    /// test declared.
    struct Glassed<C: PostEffects> {
        over: PhantomData<C>,
    }

    impl Game for Glassed<Glassing> {
        type Meshes = CubeSet;
        type Sounds = NoSounds;
        type InputActions = NoInputActions;
        type Skyboxes = NoSkyboxes;
        type SurfaceStyles = ();
        type PostEffects = Glassing;

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

        fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
            badge(ctx);
            ctx.set_post_effect(Glass);
        }
    }

    impl Game for Glassed<Halving> {
        type Meshes = CubeSet;
        type Sounds = NoSounds;
        type InputActions = NoInputActions;
        type Skyboxes = NoSkyboxes;
        type SurfaceStyles = ();
        type PostEffects = Halving;

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

        fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
            badge(ctx);
            ctx.set_post_effect(Halve);
        }
    }

    /// One opaque red square in the top left of the UI layer, and nothing
    /// in `3D`.
    fn badge<G: Game>(ctx: &mut FrameContext<'_, G>) {
        ctx.ui(|ui| {
            ui.painter().rect_filled(
                egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(BADGE, BADGE)),
                0.0,
                egui::Color32::RED,
            );
        });
    }

    /// One step of `game` read back off a `PANE`-sized target.
    fn glassed<G: Game>(game: G) -> Option<Vec<u8>> {
        sized(Config::new("headless glass"), UVec2::splat(PANE), game)
    }

    #[test]
    fn an_effect_over_the_ui_darkens_what_one_under_it_leaves() {
        let Some(over) = glassed(Glassed::<Glassing> { over: PhantomData }) else {
            eprintln!("skipped: this machine has no usable graphics adapter");
            return;
        };
        let Some(under) = glassed(Glassed::<Halving> { over: PhantomData }) else {
            return;
        };

        let at = |pixels: &[u8], (x, y): (u32, u32)| {
            let offset = ((y * PANE + x) * 4) as usize;
            pixels[offset]
        };

        assert!(
            at(&under, INSIDE) > 248,
            "the badge is drawn after the effect under it, so it stands whole"
        );
        let kept = f32::from(at(&over, INSIDE)) / f32::from(at(&under, INSIDE));
        assert!(
            (kept - 0.5).abs() < 0.02,
            "and the effect over it halves the badge's own pixels, got {kept}"
        );
    }

    #[test]
    fn the_ui_layer_is_drawn_over_the_scene() {
        let Ok(mut session) = Session::new(Config::new("headless ui"), UVec2::splat(64), |_ctx| {
            Ok(Badge)
        }) else {
            eprintln!("skipped: this machine has no usable graphics adapter");
            return;
        };

        session.step();
        let pixels = session.pixels().expect("the target reads back");
        let pixel = |x: usize, y: usize| {
            let at = (y * 64 + x) * 4;
            [pixels[at], pixels[at + 1], pixels[at + 2], pixels[at + 3]]
        };

        let [red, green, blue, _] = pixel(16, 16);
        assert!(
            red > 248 && green < 16 && blue < 16,
            "the badge covers the top left, and no curve is between it and \
             the target, got {red} {green} {blue}"
        );
        // The far corner, well outside the badge's 32x32 square.
        let background = pixel(63, 0);
        assert_eq!(pixel(48, 48), background, "the rest is the clear color");
    }

    /// Nothing in `3D`, and two UI squares: an opaque grey over the whole
    /// layer, and white at half alpha over its left half.
    struct Wash;

    impl Game for Wash {
        type Meshes = CubeSet;
        type Sounds = NoSounds;
        type InputActions = NoInputActions;
        type Skyboxes = NoSkyboxes;
        type SurfaceStyles = ();
        type PostEffects = ();

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

        fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
            ctx.ui(|ui| {
                let painter = ui.painter();
                painter.rect_filled(
                    egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(64.0, 64.0)),
                    0.0,
                    egui::Color32::from_gray(128),
                );
                painter.rect_filled(
                    egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(32.0, 64.0)),
                    0.0,
                    egui::Color32::from_rgba_unmultiplied(255, 255, 255, 128),
                );
            });
        }
    }

    #[test]
    fn the_ui_layer_blends_in_the_space_its_colors_are_authored_in() {
        let Ok(mut session) = Session::new(Config::new("headless ui blend"), UVec2::splat(64), {
            |_ctx| Ok(Wash)
        }) else {
            eprintln!("skipped: this machine has no usable graphics adapter");
            return;
        };

        session.step();
        let pixels = session.pixels().expect("the target reads back");
        let grey = |x: usize, y: usize| pixels[(y * 64 + x) * 4];

        assert_eq!(
            grey(48, 32),
            128,
            "an opaque UI color reaches the target as it was authored"
        );
        // Half of 255 over half of 128 in encoded values, to a round;
        // blending the same colors as light would leave 154.
        let washed = grey(16, 32);
        assert!(
            (191..=192).contains(&washed),
            "white at half alpha over grey leaves 192, got {washed}"
        );
    }
}