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
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
//! The game's post effects as startup compiled them: the targets each stage
//! passes the frame between, the scene depth they read, and the passes that
//! run the effects a frame submitted.

use core::ops::Range;

use bytemuck::{Pod, Zeroable};

use crate::gpu::Target;
use crate::math::UVec2;
use crate::post_effect::{self, Declaration, EffectStage, PostEffectId};
use crate::renderer::post::{HDR_FORMAT, Post};
use crate::{Camera, Error, Lens};

/// The format the scene's resolved depth is read from: one lane of meters
/// along the view.
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R32Float;

/// The line the scene depth's own binding replaces, which follows the
/// sample count the frame is drawn over.
const DEPTH_SEAM: &str = "// mirage-engine:depth";
const DEPTH_ONCE: &str = "@group(2) @binding(0) var scene: texture_depth_2d;";
const DEPTH_OVER_SAMPLES: &str = "@group(2) @binding(0) var scene: texture_depth_multisampled_2d;";

/// The one triangle each pass covers its target with.
const FULLSCREEN: Range<u32> = 0..3;

/// The smallest a effect's values buffer is bound at, so that a effect
/// reading none still binds one.
const SMALLEST_VALUES: wgpu::BufferAddress = 16;

/// What the resolve writes where a lens foreshortens, which its own shader
/// reads back.
const FORESHORTENED: u32 = 1;

/// The game's own effects as startup compiles them: one pipeline and one
/// buffer of values each, in the order the set lists them, with the targets
/// their stages pass the frame between.
pub(crate) struct PostPasses {
    compiled: Vec<Compiled>,
    /// Whether each effect runs this frame, by seat.
    running: Vec<bool>,
    /// What the passes are drawn through; nothing at all for a game that
    /// declares no effect.
    built: Option<Built>,
    targets: Option<Targets>,
}

/// What startup builds for a game that declares a effect: what every pass
/// binds, the pipeline that takes the scene's depth to one sample per
/// pixel, and the buffer each pass reads the frame itself through.
struct Built {
    bindings: Bindings,
    resolve: wgpu::RenderPipeline,
    frame: wgpu::Buffer,
    display_format: wgpu::TextureFormat,
    /// Every stage the set declares an effect in, which is what decides how
    /// many targets the frame passes between.
    stages: [bool; EffectStage::ALL.len()],
}

impl PostPasses {
    /// Stitches every declared effect into the engine's own full-screen
    /// shader, builds the pipeline each of them draws with, and returns an
    /// error naming every effect whose own WGSL did not compile.
    ///
    /// A game that declares no effect compiles nothing and costs nothing.
    pub(crate) async fn compile(
        device: &wgpu::Device,
        declared: Vec<Declaration>,
        samples: u32,
        display_format: wgpu::TextureFormat,
    ) -> Result<Self, Error> {
        if declared.is_empty() {
            return Ok(Self {
                compiled: Vec::new(),
                running: Vec::new(),
                built: None,
                targets: None,
            });
        }

        let bindings = Bindings::new(device, samples);
        let frame = buffer(
            device,
            "mirage-engine effect frame",
            size_of::<Reach>() as wgpu::BufferAddress,
            wgpu::BufferUsages::UNIFORM,
        );
        let resolve = resolving(device, &bindings, samples);

        let mut compiled = Vec::with_capacity(declared.len());
        let mut broken = Vec::new();
        for declaration in declared {
            let name = declaration.name;
            // A shader error resolves on the GPU's own timeline, so the
            // scope over the creation is read here at startup.
            let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
            let effect = Compiled::new(device, &bindings, declaration, samples, display_format);
            match scope.pop().await {
                Some(error) => broken.push(format!("{name}: {error}")),
                None => compiled.push(effect),
            }
        }

        if !broken.is_empty() {
            return Err(Error::msg(format!(
                "a post effect did not compile: {}",
                broken.join("; ")
            )));
        }

        let stages =
            EffectStage::ALL.map(|stage| compiled.iter().any(|effect| effect.stage == stage));
        Ok(Self {
            running: vec![false; compiled.len()],
            compiled,
            built: Some(Built {
                bindings,
                resolve,
                frame,
                display_format,
                stages,
            }),
            targets: None,
        })
    }

    /// Builds the targets the frame passes between at `size`, keeping what
    /// is already the right size, and writes what every effect reads of the
    /// frame itself.
    pub(crate) fn prepare(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        size: UVec2,
        camera: Camera,
        post: &Post,
    ) {
        let Some(built) = &self.built else {
            return;
        };
        let Some(drawn) = post.drawn() else {
            return;
        };
        let Some(depth) = post.depth() else {
            return;
        };

        match &self.targets {
            Some(targets) if targets.size == size => {}
            _ => {
                self.targets = Some(Targets::new(
                    device,
                    &built.bindings,
                    built.stages,
                    Frame {
                        size,
                        display_format: built.display_format,
                    },
                    Read {
                        drawn,
                        depth,
                        frame: &built.frame,
                        post,
                    },
                ));
            }
        }

        let projection = camera.projection();
        queue.write_buffer(
            &built.frame,
            0,
            bytemuck::bytes_of(&Reach {
                size: [size.x as f32, size.y as f32],
                near: projection.near(),
                far: projection.far(),
                perspective: match projection.lens() {
                    Lens::Perspective { .. } => FORESHORTENED,
                    Lens::Orthographic { .. } => 0,
                },
                _padding: [0; 3],
            }),
        );
    }

    /// Keeps the values each effect `submitted` passed it this frame, and
    /// which of them run at all.
    pub(crate) fn submit<'a>(
        &mut self,
        queue: &wgpu::Queue,
        submitted: impl Fn(PostEffectId) -> Option<&'a [u8]>,
    ) {
        for (at, effect) in self.compiled.iter().enumerate() {
            let values = submitted(PostEffectId(at as u32));
            self.running[at] = values.is_some();
            if let Some(values) = values.filter(|values| !values.is_empty()) {
                queue.write_buffer(&effect.values, 0, values);
            }
        }
    }

    /// Whether any effect runs this frame, which is what the depth resolve
    /// and every target past the tone map are for.
    fn any(&self) -> bool {
        self.running.iter().any(|running| *running)
    }

    /// The effects of `stage` this frame runs, in the order the set lists
    /// them.
    fn running(&self, stage: EffectStage) -> impl Iterator<Item = &Compiled> {
        self.compiled
            .iter()
            .zip(&self.running)
            .filter(move |(effect, running)| **running && effect.stage == stage)
            .map(|(effect, _)| effect)
    }

    /// Takes the scene's depth to one sample per pixel before any effect
    /// reads it; nothing where no effect runs.
    pub(crate) fn resolve(&self, encoder: &mut wgpu::CommandEncoder) {
        let (Some(built), Some(targets)) = (&self.built, &self.targets) else {
            return;
        };
        if !self.any() {
            return;
        }

        let mut pass = pass(
            encoder,
            "mirage-engine scene depth",
            &targets.depth,
            wgpu::LoadOp::Clear(wgpu::Color::BLACK),
        );
        pass.set_pipeline(&built.resolve);
        pass.set_bind_group(0, &targets.nothing, &[]);
        pass.set_bind_group(1, &targets.nothing, &[]);
        pass.set_bind_group(2, &targets.scene, &[]);
        pass.draw(FULLSCREEN, 0..1);
    }

    /// Runs the frame's `Lit` effects over the drawn frame, and returns
    /// what the chain reads after them, or nothing where none ran.
    pub(crate) fn scene<'a>(
        &'a self,
        encoder: &mut wgpu::CommandEncoder,
    ) -> Option<&'a wgpu::BindGroup> {
        let targets = self.targets.as_ref()?;
        let panes = targets.lit.as_ref()?;
        let mut ran = 0;
        for effect in self.running(EffectStage::Lit) {
            let source = match ran {
                0 => &targets.drawn,
                _ => &panes[(ran - 1) % 2].read,
            };
            effect.draw(encoder, source, &targets.scene, &panes[ran % 2].written);
            ran += 1;
        }
        (ran > 0).then(|| &panes[(ran - 1) % 2].composited)
    }

    /// How many passes write past the tone map this frame: the tone map
    /// itself, then every `ToneMapped` and `OverUi` effect the frame
    /// submitted.
    fn writes(&self) -> usize {
        1 + self.running(EffectStage::ToneMapped).count()
            + self.running(EffectStage::OverUi).count()
    }

    /// Where the write at `at` lands: the pair of targets the stage passes
    /// the frame between, and the surface last. `encoding` is for the one
    /// pass that encodes what it holds on its way out.
    fn written<'a>(
        &'a self,
        at: usize,
        encoding: bool,
        target: &'a Target,
    ) -> &'a wgpu::TextureView {
        let surface = match encoding {
            true => target.color(),
            false => target.encoded(),
        };
        if at + 1 == self.writes() {
            return surface;
        }
        match self
            .targets
            .as_ref()
            .and_then(|targets| targets.shown.as_ref())
        {
            Some(panes) => panes[at % 2].written(encoding),
            None => surface,
        }
    }

    /// Where the tone map writes: the first target the passes after it
    /// pass the frame between, or the surface where none run.
    pub(crate) fn tone_mapped<'a>(&'a self, target: &'a Target) -> &'a wgpu::TextureView {
        self.written(0, true, target)
    }

    /// Where the UI draws: what holds the frame once the `ToneMapped`
    /// effects have run, which is what an `OverUi` effect then reads.
    pub(crate) fn overlaid<'a>(&'a self, target: &'a Target) -> &'a wgpu::TextureView {
        self.written(self.running(EffectStage::ToneMapped).count(), false, target)
    }

    /// Runs the frame's `ToneMapped` effects, over the frame the tone map
    /// left and under the UI.
    pub(crate) fn run_tone_mapped(&self, encoder: &mut wgpu::CommandEncoder, target: &Target) {
        self.run(encoder, EffectStage::ToneMapped, 1, target);
    }

    /// Runs the frame's `OverUi` effects, over the frame the UI left, the
    /// last of them into the surface.
    pub(crate) fn run_over_ui(&self, encoder: &mut wgpu::CommandEncoder, target: &Target) {
        let after = 1 + self.running(EffectStage::ToneMapped).count();
        self.run(encoder, EffectStage::OverUi, after, target);
    }

    /// Runs the frame's effects of `stage`, the first of them the write at
    /// `first`, each one pass between the targets the stage passes the
    /// frame between.
    fn run(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        stage: EffectStage,
        first: usize,
        target: &Target,
    ) {
        let Some(targets) = &self.targets else {
            return;
        };
        let Some(panes) = targets.shown.as_ref() else {
            return;
        };
        for (offset, effect) in self.running(stage).enumerate() {
            let at = first + offset;
            effect.draw(
                encoder,
                &panes[(at - 1) % 2].read,
                &targets.scene,
                self.written(at, false, target),
            );
        }
    }
}

/// One effect on the GPU: the pipeline its pass is drawn with, the buffer
/// its values are read from, and where in the chain it runs.
struct Compiled {
    stage: EffectStage,
    pipeline: wgpu::RenderPipeline,
    values: wgpu::Buffer,
    bound: wgpu::BindGroup,
}

impl Compiled {
    fn new(
        device: &wgpu::Device,
        bindings: &Bindings,
        declaration: Declaration,
        samples: u32,
        display_format: wgpu::TextureFormat,
    ) -> Self {
        let label = Some(declaration.name);
        let shaders = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label,
            source: wgpu::ShaderSource::Wgsl(
                declaration
                    .source
                    .replace(DEPTH_SEAM, sampled_depth(samples))
                    .into(),
            ),
        });
        let values = buffer(
            device,
            "mirage-engine effect",
            SMALLEST_VALUES,
            wgpu::BufferUsages::UNIFORM,
        );
        let bound = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label,
            layout: &bindings.values,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: values.as_entire_binding(),
            }],
        });
        let format = match declaration.stage.after_tone_map() {
            true => display_format.remove_srgb_suffix(),
            false => HDR_FORMAT,
        };

        Self {
            stage: declaration.stage,
            pipeline: pipeline(
                device,
                label,
                &shaders,
                &bindings.effect,
                "effect_fragment",
                format,
            ),
            values,
            bound,
        }
    }

    /// Draws this effect over the whole of `into`, reading the frame
    /// through `source` and the scene's own depth through `scene`.
    fn draw(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        source: &wgpu::BindGroup,
        scene: &wgpu::BindGroup,
        into: &wgpu::TextureView,
    ) {
        let mut pass = pass(encoder, "mirage-engine effect", into, wgpu::LoadOp::Load);
        pass.set_pipeline(&self.pipeline);
        pass.set_bind_group(0, &self.bound, &[]);
        pass.set_bind_group(1, source, &[]);
        pass.set_bind_group(2, scene, &[]);
        pass.draw(FULLSCREEN, 0..1);
    }
}

/// What every effect pass is built against: the layout of each group it
/// binds, the pipeline layout over them, and the sampler it reads the frame
/// through.
struct Bindings {
    sampler: wgpu::Sampler,
    values: wgpu::BindGroupLayout,
    source: wgpu::BindGroupLayout,
    scene: wgpu::BindGroupLayout,
    nothing: wgpu::BindGroupLayout,
    effect: wgpu::PipelineLayout,
    depth: wgpu::PipelineLayout,
}

impl Bindings {
    fn new(device: &wgpu::Device, samples: u32) -> Self {
        let values = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("mirage-engine effect values"),
            entries: &[uniform(0)],
        });
        let source = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("mirage-engine effect source"),
            entries: &[sampled(0, true), sampler(1), sampled(2, false)],
        });
        let scene = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("mirage-engine scene depth"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Depth,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: samples > 1,
                    },
                    count: None,
                },
                uniform(1),
            ],
        });
        let nothing = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("mirage-engine effect nothing"),
            entries: &[],
        });

        Self {
            effect: layout(
                device,
                "mirage-engine effect",
                &[Some(&values), Some(&source), Some(&scene)],
            ),
            depth: layout(
                device,
                "mirage-engine scene depth",
                &[Some(&nothing), Some(&nothing), Some(&scene)],
            ),
            sampler: device.create_sampler(&wgpu::SamplerDescriptor {
                label: Some("mirage-engine effect"),
                address_mode_u: wgpu::AddressMode::ClampToEdge,
                address_mode_v: wgpu::AddressMode::ClampToEdge,
                address_mode_w: wgpu::AddressMode::ClampToEdge,
                mag_filter: wgpu::FilterMode::Linear,
                min_filter: wgpu::FilterMode::Linear,
                ..Default::default()
            }),
            values,
            source,
            scene,
            nothing,
        }
    }

    /// The bindings a effect reads `view` and the resolved depth through.
    fn source(
        &self,
        device: &wgpu::Device,
        view: &wgpu::TextureView,
        depth: &wgpu::TextureView,
    ) -> wgpu::BindGroup {
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("mirage-engine effect source"),
            layout: &self.source,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(depth),
                },
            ],
        })
    }
}

/// The frame as the targets are built for it.
struct Frame {
    size: UVec2,
    display_format: wgpu::TextureFormat,
}

/// What the targets are built to be read beside: the drawn frame, the depth
/// it was drawn at, and the values every pass reads of the frame itself.
struct Read<'a> {
    drawn: &'a wgpu::TextureView,
    depth: &'a wgpu::TextureView,
    frame: &'a wgpu::Buffer,
    post: &'a Post,
}

/// Every target the frame passes between and what each is read through,
/// built again when the frame changes size.
struct Targets {
    size: UVec2,
    /// The pair a `Lit` effect passes the frame between, absent where the
    /// set declares none.
    lit: Option<[Pane; 2]>,
    /// The pair a `ToneMapped` or `OverUi` effect passes the frame between.
    shown: Option<[Pane; 2]>,
    /// The scene's depth at one sample per pixel, in meters.
    depth: wgpu::TextureView,
    /// What a `Lit` effect reads the drawn frame through.
    drawn: wgpu::BindGroup,
    /// What the depth resolve reads the scene's own depth through.
    scene: wgpu::BindGroup,
    nothing: wgpu::BindGroup,
}

impl Targets {
    fn new(
        device: &wgpu::Device,
        bindings: &Bindings,
        stages: [bool; EffectStage::ALL.len()],
        frame: Frame,
        read: Read<'_>,
    ) -> Self {
        let depth = texture(
            device,
            "mirage-engine scene depth",
            frame.size,
            DEPTH_FORMAT,
            &[],
        )
        .create_view(&Default::default());
        let pair = |format: wgpu::TextureFormat| {
            [(); 2].map(|()| Pane::new(device, bindings, read.post, format, frame.size, &depth))
        };

        Self {
            size: frame.size,
            lit: stages[0].then(|| pair(HDR_FORMAT)),
            shown: (stages[1] || stages[2]).then(|| pair(frame.display_format)),
            drawn: bindings.source(device, read.drawn, &depth),
            scene: device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("mirage-engine scene depth"),
                layout: &bindings.scene,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::TextureView(read.depth),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: read.frame.as_entire_binding(),
                    },
                ],
            }),
            nothing: device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("mirage-engine effect nothing"),
                layout: &bindings.nothing,
                entries: &[],
            }),
            depth,
        }
    }
}

/// One target a stage passes the frame between: what a pass writes it
/// through, and what the pass after it reads it through.
struct Pane {
    written: wgpu::TextureView,
    /// The view the tone map writes through, which encodes what it holds;
    /// absent for a target the tone map never writes.
    encoding: Option<wgpu::TextureView>,
    /// What a effect reads this target through.
    read: wgpu::BindGroup,
    /// What the bloom and the tone map read this target through.
    composited: wgpu::BindGroup,
}

impl Pane {
    fn new(
        device: &wgpu::Device,
        bindings: &Bindings,
        post: &Post,
        format: wgpu::TextureFormat,
        size: UVec2,
        depth: &wgpu::TextureView,
    ) -> Self {
        let raw = format.remove_srgb_suffix();
        let texture = texture(device, "mirage-engine effect", size, format, &[raw]);
        let written = texture.create_view(&wgpu::TextureViewDescriptor {
            format: Some(raw),
            ..Default::default()
        });

        Self {
            read: bindings.source(device, &written, depth),
            composited: post.source(device, &written),
            encoding: (raw != format).then(|| {
                texture.create_view(&wgpu::TextureViewDescriptor {
                    format: Some(format),
                    ..Default::default()
                })
            }),
            written,
        }
    }

    /// The view a pass writes this target through.
    fn written(&self, encoding: bool) -> &wgpu::TextureView {
        match (encoding, &self.encoding) {
            (true, Some(view)) => view,
            _ => &self.written,
        }
    }
}

/// What every pass over the frame reads of the frame itself.
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
struct Reach {
    size: [f32; 2],
    near: f32,
    far: f32,
    perspective: u32,
    /// Keeps this struct's size at WGSL's alignment; `bytemuck` needs
    /// padding written out.
    _padding: [u32; 3],
}

/// The binding the scene's depth is read through, by the samples the frame
/// was drawn over.
fn sampled_depth(samples: u32) -> &'static str {
    match samples > 1 {
        true => DEPTH_OVER_SAMPLES,
        false => DEPTH_ONCE,
    }
}

/// The pipeline that takes the scene's depth to meters.
fn resolving(device: &wgpu::Device, bindings: &Bindings, samples: u32) -> wgpu::RenderPipeline {
    let shaders = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("mirage-engine scene depth"),
        source: wgpu::ShaderSource::Wgsl(
            post_effect::unpainted()
                .replace(DEPTH_SEAM, sampled_depth(samples))
                .into(),
        ),
    });
    pipeline(
        device,
        Some("mirage-engine scene depth"),
        &shaders,
        &bindings.depth,
        "resolve",
        DEPTH_FORMAT,
    )
}

fn pipeline(
    device: &wgpu::Device,
    label: Option<&str>,
    shaders: &wgpu::ShaderModule,
    layout: &wgpu::PipelineLayout,
    entry: &str,
    format: wgpu::TextureFormat,
) -> wgpu::RenderPipeline {
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label,
        layout: Some(layout),
        vertex: wgpu::VertexState {
            module: shaders,
            entry_point: Some("fullscreen"),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            buffers: &[],
        },
        primitive: wgpu::PrimitiveState::default(),
        depth_stencil: None,
        multisample: wgpu::MultisampleState::default(),
        fragment: Some(wgpu::FragmentState {
            module: shaders,
            entry_point: Some(entry),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            targets: &[Some(wgpu::ColorTargetState {
                format,
                blend: None,
                write_mask: wgpu::ColorWrites::ALL,
            })],
        }),
        multiview_mask: None,
        cache: None,
    })
}

fn pass<'a>(
    encoder: &'a mut wgpu::CommandEncoder,
    label: &str,
    target: &wgpu::TextureView,
    load: wgpu::LoadOp<wgpu::Color>,
) -> wgpu::RenderPass<'a> {
    encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
        label: Some(label),
        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
            view: target,
            depth_slice: None,
            resolve_target: None,
            ops: wgpu::Operations {
                load,
                store: wgpu::StoreOp::Store,
            },
        })],
        depth_stencil_attachment: None,
        timestamp_writes: None,
        occlusion_query_set: None,
        multiview_mask: None,
    })
}

fn layout(
    device: &wgpu::Device,
    label: &str,
    groups: &[Option<&wgpu::BindGroupLayout>],
) -> wgpu::PipelineLayout {
    device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some(label),
        bind_group_layouts: groups,
        immediate_size: 0,
    })
}

fn texture(
    device: &wgpu::Device,
    label: &str,
    size: UVec2,
    format: wgpu::TextureFormat,
    views: &[wgpu::TextureFormat],
) -> wgpu::Texture {
    device.create_texture(&wgpu::TextureDescriptor {
        label: Some(label),
        size: wgpu::Extent3d {
            width: size.x,
            height: size.y,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
        view_formats: views,
    })
}

fn buffer(
    device: &wgpu::Device,
    label: &str,
    size: wgpu::BufferAddress,
    usage: wgpu::BufferUsages,
) -> wgpu::Buffer {
    device.create_buffer(&wgpu::BufferDescriptor {
        label: Some(label),
        size,
        usage: usage | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    })
}

fn sampled(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Texture {
            sample_type: wgpu::TextureSampleType::Float { filterable },
            view_dimension: wgpu::TextureViewDimension::D2,
            multisampled: false,
        },
        count: None,
    }
}

fn sampler(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
        count: None,
    }
}

fn uniform(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Buffer {
            ty: wgpu::BufferBindingType::Uniform,
            has_dynamic_offset: false,
            min_binding_size: None,
        },
        count: None,
    }
}