sgl-3d 0.9.2

Caller-driven 3D rendering for SGL games, native and in the browser (WebGPU)
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
//! Group 0 of one view: the lit, unlit and shadow layouts, the frame's
//! `FrameUniform` buffer, neutral stand-ins, and the groups built from
//! them, which the view owns and stages borrow. The layouts are made once
//! (`Layouts`, which the renderer holds) and shared by every view's groups and
//! the geometry pipelines. The scene layout (group 1) matches the scene's
//! own groups; group 2's is the geometry pipelines' (`view::pipelines`), of
//! the device's binding tier.
use super::FrameViews;
use crate::FrameEnvironment;
use crate::scene::environments::Environments;
use crate::scene::probes::UploadedProbes;
use crate::shading;
use crate::shading::bind::{LitLayout, group0};
use crate::{Scene, shading::uniforms::FrameUniform};
use bytemuck::Zeroable;

/// The shadow maps, local-light shadow records and comparison sampler lit
/// group 0 binds, which the shadow stage draws.
pub(crate) struct ShadowMaps {
    /// The directional shadow cascades, one per layer.
    pub directional: wgpu::TextureView,
    /// The frame's local-light shadow atlas.
    pub local_atlas: wgpu::TextureView,
    /// Its static layers, which probe captures and ray hits sample.
    pub local_layers: wgpu::TextureView,
    /// Where each light's shadow is in it.
    pub local_records: wgpu::Buffer,
    pub sampler: wgpu::Sampler,
}

/// The fog volume every group 0 binds, which the fog stage writes, and the
/// sampler that filters it.
#[derive(Clone, Copy)]
pub(crate) struct FogVolume<'a> {
    pub view: &'a wgpu::TextureView,
    pub sampler: &'a wgpu::Sampler,
}

/// The local-light shadows a lit group 0 binds: an atlas and the records
/// that place each light's shadow in it.
#[derive(Clone, Copy)]
pub(crate) struct LocalShadows<'a> {
    pub atlas: &'a wgpu::TextureView,
    pub records: &'a wgpu::Buffer,
}

/// What group 0 binds for the frame's environment: the backdrop (unlit
/// group 0's `backdrop_map`) and the PMREM atlas (`environment_map`).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct EnvironmentViews {
    pub backdrop: wgpu::TextureView,
    pub pmrem: wgpu::TextureView,
}

impl EnvironmentViews {
    /// The one resolver of what group 0 binds for `environment`: a live
    /// map's panorama and atlas; for a procedural sky, the view's sky stage's
    /// `sky` views, its sky-view table as the backdrop and its environment
    /// atlas, in the format a map's is; the black stand-in for none or an
    /// ended map (or a sky whose stage holds no tables).
    pub fn resolve(
        environments: &Environments,
        environment: &FrameEnvironment,
        sky: Option<[&wgpu::TextureView; 2]>,
    ) -> Self {
        let neutral = environments.frame(None);
        let (backdrop, pmrem) = match environment {
            FrameEnvironment::None => (&neutral.backdrop, &neutral.pmrem),
            FrameEnvironment::Map(id) => {
                let map = environments.frame(Some(*id));
                (&map.backdrop, &map.pmrem)
            }
            FrameEnvironment::Sky(_) => match sky {
                Some([sky_view, atlas]) => (sky_view, atlas),
                None => (&neutral.backdrop, &neutral.pmrem),
            },
        };
        Self {
            backdrop: backdrop.clone(),
            pmrem: pmrem.clone(),
        }
    }
}

/// The groups that bind one scene's resources, the frame's environment and
/// the views' clusters.
struct SceneGroups {
    /// `Scene::resources` they were built from.
    resources: u64,
    /// The environment's textures they bind.
    environment: EnvironmentViews,
    /// The camera's clusters, the ray hits' lists and the volume's probe
    /// hits' lists they bind.
    clusters: [wgpu::Buffer; 3],
    /// The local-light shadow records they bind.
    local_records: wgpu::Buffer,
    /// The shadow maps they bind: the directional cascades, the local-light
    /// atlas and its static layers.
    shadow_maps: [wgpu::TextureView; 3],
    /// The fog volume they bind.
    fog: wgpu::TextureView,
    /// The dynamic GI volume's probes they bind, on the Extended binding
    /// tier.
    dynamic_gi: Option<wgpu::TextureView>,
    /// The camera's lit group, with the installed probes, which its
    /// blended surfaces sample: source completion adds opaque surfaces'
    /// probe specular from the G-buffer, but blended surfaces write none.
    camera_lit: wgpu::BindGroup,
    /// The lit group of world-space ray hits: their light and decal lists,
    /// the static shadow layers and the installed probes, since they run no
    /// source completion and add probe specular themselves, as captures do.
    ray_hit_lit: wgpu::BindGroup,
    /// The lit group of the dynamic GI probe rays' hits: as world-space ray
    /// hits', with the volume's light and decal list.
    volume_lit: wgpu::BindGroup,
    /// The camera's sky and transient group.
    camera_unlit: wgpu::BindGroup,
}

/// The bind group layouts the geometry pipelines are made with and every
/// view's groups are made from, made once for the device.
pub(crate) struct Layouts {
    /// Lit group 0's layout, of the device's binding tier.
    pub lit: LitLayout,
    pub unlit: wgpu::BindGroupLayout,
    pub shadow: wgpu::BindGroupLayout,
    /// Group 1's layout (`shading::bind::scene`).
    pub scene: wgpu::BindGroupLayout,
    /// The blended pipelines' group 3 (`shading::bind::blended`).
    pub blended: wgpu::BindGroupLayout,
    /// The lighting pass's group 3 while ray-traced shadows run
    /// (`shading::bind::shadow_mask`).
    pub shadow_mask: wgpu::BindGroupLayout,
    /// The fused and lighting passes' group 3 while screen-space indirect
    /// light has a kept result (`shading::bind::screen_indirect`), and the
    /// lighting pass's with the shadow mask too
    /// (`shading::bind::shadow_mask_screen_indirect`).
    pub screen_indirect: wgpu::BindGroupLayout,
    pub shadow_mask_screen_indirect: wgpu::BindGroupLayout,
    /// The lighting pass's group 3 while contact shadows run
    /// (`shading::bind::contact_shadow`), and with screen-space indirect
    /// light too (`shading::bind::contact_shadow_screen_indirect`).
    pub contact_shadow: wgpu::BindGroupLayout,
    pub contact_shadow_screen_indirect: wgpu::BindGroupLayout,
    /// The GPU-built cascades' casters' group 3
    /// (`shading::bind::caster_positions`).
    pub caster_positions: wgpu::BindGroupLayout,
}

impl Layouts {
    /// The layouts of `device`'s binding tier.
    pub fn new(device: &wgpu::Device) -> Self {
        let lit = shading::bind::lit(device, shading::bind::BindingTier::of(&device.limits()));
        Self {
            unlit: shading::bind::unlit(device),
            shadow: shading::bind::shadow(device),
            scene: shading::bind::scene(device),
            blended: shading::bind::blended(device, lit.tier),
            shadow_mask: shading::bind::shadow_mask(device),
            screen_indirect: shading::bind::screen_indirect(device),
            shadow_mask_screen_indirect: shading::bind::shadow_mask_screen_indirect(device),
            contact_shadow: shading::bind::contact_shadow(device),
            contact_shadow_screen_indirect: shading::bind::contact_shadow_screen_indirect(device),
            caster_positions: shading::bind::caster_positions(device),
            lit,
        }
    }
}

pub(crate) struct FrameBindings {
    /// Lit group 0's layout, of the device's binding tier.
    pub lit: LitLayout,
    pub unlit: wgpu::BindGroupLayout,
    pub shadow: wgpu::BindGroupLayout,
    /// Group 1's layout (`shading::bind::scene`).
    pub scene: wgpu::BindGroupLayout,
    /// The blended pipelines' group 3 (`shading::bind::blended`), which the
    /// transparent stage binds.
    pub blended: wgpu::BindGroupLayout,
    /// The lighting pass's group 3 while ray-traced shadows run
    /// (`shading::bind::shadow_mask`), which the opaque stage binds.
    pub shadow_mask: wgpu::BindGroupLayout,
    /// The fused and lighting passes' group 3 while screen-space indirect
    /// light has a kept result, without and with the shadow mask, which the
    /// opaque stage binds.
    pub screen_indirect: wgpu::BindGroupLayout,
    pub shadow_mask_screen_indirect: wgpu::BindGroupLayout,
    /// The lighting pass's group 3 while contact shadows run, without and
    /// with screen-space indirect light, which the opaque stage binds.
    pub contact_shadow: wgpu::BindGroupLayout,
    pub contact_shadow_screen_indirect: wgpu::BindGroupLayout,
    /// The frame's `FrameUniform`, shared by every view of the frame.
    pub frame: wgpu::Buffer,
    /// No specular probes: lit groups bind this while the scene has none
    /// installed.
    pub empty_probes: UploadedProbes,
    pub shadow_maps: ShadowMaps,
    /// The fog volume every group 0 binds and its sampler, which the fog
    /// stage writes.
    fog: (wgpu::TextureView, wgpu::Sampler),
    /// The dynamic GI volume's probes every lit group 0 binds on the
    /// Extended binding tier, which the dynamic GI stage writes; none on
    /// Basic, which has no such stage.
    dynamic_gi: Option<wgpu::TextureView>,
    camera_view: wgpu::Buffer,
    cascades: [wgpu::BindGroup; super::cascades::MAX_SHADOW_CASCADES],
    groups: Option<SceneGroups>,
}

impl FrameBindings {
    /// Group 0 for `views` over `layouts`, binding `shadow_maps`, `fog`
    /// and the `dynamic_gi` probes until a frame refreshes them, with the
    /// layouts of groups 1 and 3.
    pub fn new(
        device: &wgpu::Device,
        layouts: &Layouts,
        views: &FrameViews,
        shadow_maps: ShadowMaps,
        fog: FogVolume<'_>,
        dynamic_gi: Option<&wgpu::TextureView>,
    ) -> Self {
        let shadow = layouts.shadow.clone();
        let frame = crate::scene::buffer(
            device,
            "camera frame",
            bytemuck::bytes_of(&FrameUniform::zeroed()),
            wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
        );
        let shadow_group = |label, view: &wgpu::Buffer| {
            device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some(label),
                layout: &shadow,
                entries: &shading::bind::uniforms(view, &frame),
            })
        };
        let cascades = std::array::from_fn(|index| {
            shadow_group("directional shadow cascade", &views.cascades[index].buffer)
        });
        Self {
            lit: layouts.lit.clone(),
            unlit: layouts.unlit.clone(),
            shadow,
            scene: layouts.scene.clone(),
            blended: layouts.blended.clone(),
            shadow_mask: layouts.shadow_mask.clone(),
            screen_indirect: layouts.screen_indirect.clone(),
            shadow_mask_screen_indirect: layouts.shadow_mask_screen_indirect.clone(),
            contact_shadow: layouts.contact_shadow.clone(),
            contact_shadow_screen_indirect: layouts.contact_shadow_screen_indirect.clone(),
            frame,
            empty_probes: UploadedProbes::empty(device),
            shadow_maps,
            fog: (fog.view.clone(), fog.sampler.clone()),
            dynamic_gi: dynamic_gi.cloned(),
            camera_view: views.camera.buffer.clone(),
            cascades,
            groups: None,
        }
    }

    /// Rebuilds the camera's groups when `scene` is another scene, has
    /// replaced a resource they bind, `environment` (the frame's, resolved
    /// by `EnvironmentViews::resolve`) binds other textures, `views`
    /// replaced a cluster buffer, `shadows` replaced a map or its
    /// local-light shadow records, `fog` its volume, or the dynamic GI stage
    /// its probes (`dynamic_gi`).
    #[allow(clippy::too_many_arguments)]
    pub fn refresh(
        &mut self,
        device: &wgpu::Device,
        scene: &Scene,
        environment: EnvironmentViews,
        views: &FrameViews,
        shadows: ShadowMaps,
        fog: FogVolume<'_>,
        dynamic_gi: Option<&wgpu::TextureView>,
    ) {
        self.shadow_maps = shadows;
        self.fog = (fog.view.clone(), fog.sampler.clone());
        self.dynamic_gi = dynamic_gi.cloned();
        let clusters = [
            views.clusters.buffer().clone(),
            views.ray_lists.buffer().clone(),
            views.volume_lists.buffer().clone(),
        ];
        let local_records = self.shadow_maps.local_records.clone();
        let maps = &self.shadow_maps;
        let shadow_maps = [
            maps.directional.clone(),
            maps.local_atlas.clone(),
            maps.local_layers.clone(),
        ];
        if self.groups.as_ref().is_some_and(|groups| {
            groups.resources == scene.resources
                && groups.environment == environment
                && groups.clusters == clusters
                && groups.local_records == local_records
                && groups.shadow_maps == shadow_maps
                && groups.fog == self.fog.0
                && groups.dynamic_gi == self.dynamic_gi
        }) {
            return;
        }
        let probes = scene.specular_probes().unwrap_or(&self.empty_probes);
        let camera_lit = self.lit_group(
            device,
            scene,
            &environment,
            [&self.camera_view, &self.frame],
            probes,
            &clusters[0],
            self.local_shadows(),
            self.dynamic_gi.as_ref(),
        );
        let ray_hit_lit = self.lit_group(
            device,
            scene,
            &environment,
            [&self.camera_view, &self.frame],
            probes,
            &clusters[1],
            self.static_local_shadows(&self.shadow_maps.local_records),
            self.dynamic_gi.as_ref(),
        );
        let volume_lit = self.lit_group(
            device,
            scene,
            &environment,
            [&self.camera_view, &self.frame],
            probes,
            &clusters[2],
            self.static_local_shadows(&self.shadow_maps.local_records),
            self.dynamic_gi.as_ref(),
        );
        let camera_unlit =
            self.unlit_group(device, scene, &environment, &self.camera_view, &self.frame);
        self.groups = Some(SceneGroups {
            resources: scene.resources,
            environment,
            clusters,
            local_records,
            shadow_maps,
            fog: self.fog.0.clone(),
            dynamic_gi: self.dynamic_gi.clone(),
            camera_lit,
            ray_hit_lit,
            volume_lit,
            camera_unlit,
        });
    }

    fn groups(&self) -> &SceneGroups {
        self.groups
            .as_ref()
            .expect("FrameBindings::refresh before drawing")
    }

    pub fn camera_lit(&self) -> &wgpu::BindGroup {
        &self.groups().camera_lit
    }

    pub fn ray_hit_lit(&self) -> &wgpu::BindGroup {
        &self.groups().ray_hit_lit
    }

    /// The lit group of the dynamic GI probe rays' hits.
    pub fn volume_lit(&self) -> &wgpu::BindGroup {
        &self.groups().volume_lit
    }

    pub fn camera_unlit(&self) -> &wgpu::BindGroup {
        &self.groups().camera_unlit
    }

    /// The frame environment's textures the groups bind.
    pub fn environment(&self) -> &EnvironmentViews {
        &self.groups().environment
    }

    /// The fog volume every group 0 binds.
    pub fn fog(&self) -> FogVolume<'_> {
        FogVolume {
            view: &self.fog.0,
            sampler: &self.fog.1,
        }
    }

    /// Directional shadow cascade `index`'s shadow group.
    pub fn cascade(&self, index: usize) -> &wgpu::BindGroup {
        &self.cascades[index]
    }

    /// The frame's local-light shadows.
    pub fn local_shadows(&self) -> LocalShadows<'_> {
        LocalShadows {
            atlas: &self.shadow_maps.local_atlas,
            records: &self.shadow_maps.local_records,
        }
    }

    /// The local-light shadows' static layers, placed by `records`: what
    /// probe captures and ray hits sample.
    pub fn static_local_shadows<'a>(&'a self, records: &'a wgpu::Buffer) -> LocalShadows<'a> {
        LocalShadows {
            atlas: &self.shadow_maps.local_layers,
            records,
        }
    }

    /// A lit group 0 of the lit layout's binding tier: `view` and `frame`,
    /// the scene's lighting, decals, irradiance volume and `environment`'s
    /// atlas, `probes`, the view's `clusters`, the `local` shadows its lights take,
    /// the fog volume and the `dynamic_gi` volume's probes, of which it
    /// binds those its tier binds (`group0::tier`).
    #[allow(clippy::too_many_arguments)]
    pub fn lit_group(
        &self,
        device: &wgpu::Device,
        scene: &Scene,
        environment: &EnvironmentViews,
        [view, frame]: [&wgpu::Buffer; 2],
        probes: &UploadedProbes,
        clusters: &wgpu::Buffer,
        local: LocalShadows<'_>,
        dynamic_gi: Option<&wgpu::TextureView>,
    ) -> wgpu::BindGroup {
        let environments = &scene.environments;
        let baked = &scene.static_lighting;
        let texture = |binding, view| wgpu::BindGroupEntry {
            binding,
            resource: wgpu::BindingResource::TextureView(view),
        };
        let [view_entry, frame_entry] = shading::bind::uniforms(view, frame);
        let entries = [
            view_entry,
            frame_entry,
            texture(group0::STATIC_IRRADIANCE_ATLAS, &baked.atlas.irradiance),
            texture(group0::STATIC_DIRECTION_ATLAS, &baked.atlas.direction),
            texture(group0::STATIC_LIGHTMAP, &baked.lightmap.irradiance),
            texture(group0::STATIC_LIGHTMAP_DIRECTION, &baked.lightmap.direction),
            wgpu::BindGroupEntry {
                binding: group0::BAKED_SAMPLER,
                resource: wgpu::BindingResource::Sampler(&baked.sampler),
            },
            texture(
                group0::DIRECTIONAL_SHADOW_MAP,
                &self.shadow_maps.directional,
            ),
            texture(group0::LOCAL_SHADOW_ATLAS, local.atlas),
            wgpu::BindGroupEntry {
                binding: group0::LOCAL_SHADOWS,
                resource: local.records.as_entire_binding(),
            },
            wgpu::BindGroupEntry {
                binding: group0::SHADOW_SAMPLER,
                resource: wgpu::BindingResource::Sampler(&self.shadow_maps.sampler),
            },
            texture(group0::ENVIRONMENT_MAP, &environment.pmrem),
            wgpu::BindGroupEntry {
                binding: group0::ENVIRONMENT_SAMPLER,
                resource: wgpu::BindingResource::Sampler(&environments.sampler),
            },
            texture(group0::LOOKUP_TABLES, &scene.lookup_tables),
            wgpu::BindGroupEntry {
                binding: group0::LIGHTS,
                resource: scene.lights.buffer().as_entire_binding(),
            },
            wgpu::BindGroupEntry {
                binding: group0::CLUSTERS,
                resource: clusters.as_entire_binding(),
            },
            wgpu::BindGroupEntry {
                binding: group0::DECALS,
                resource: scene.decals.buffer().as_entire_binding(),
            },
            texture(group0::DECAL_ATLAS, &scene.decals.atlas.view),
            wgpu::BindGroupEntry {
                binding: group0::DECAL_SAMPLER,
                resource: wgpu::BindingResource::Sampler(&scene.decals.sampler),
            },
            texture(group0::BAKED, &probes.view),
            wgpu::BindGroupEntry {
                binding: group0::COLLECTION,
                resource: probes.metadata.as_entire_binding(),
            },
            texture(group0::FOG_VOLUME, &self.fog.0),
            wgpu::BindGroupEntry {
                binding: group0::FOG_SAMPLER,
                resource: wgpu::BindingResource::Sampler(&self.fog.1),
            },
            texture(group0::IRRADIANCE_VOLUME, scene.irradiance_cells.view()),
        ];
        let entries: Vec<_> = entries
            .into_iter()
            .chain(dynamic_gi.map(|view| texture(group0::DYNAMIC_GI_PROBES, view)))
            .filter(|entry| group0::tier(entry.binding) <= self.lit.tier)
            .collect();
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("scene lighting and local environment"),
            layout: &self.lit.layout,
            entries: &entries,
        })
    }

    /// An unlit group 0: `view` and `frame` with the backdrop and PMREM
    /// atlas of `environment` and the fog volume.
    pub fn unlit_group(
        &self,
        device: &wgpu::Device,
        scene: &Scene,
        environment: &EnvironmentViews,
        view: &wgpu::Buffer,
        frame: &wgpu::Buffer,
    ) -> wgpu::BindGroup {
        let environments = &scene.environments;
        let texture = |binding, view| wgpu::BindGroupEntry {
            binding,
            resource: wgpu::BindingResource::TextureView(view),
        };
        let [view_entry, frame_entry] = shading::bind::uniforms(view, frame);
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("sky and transient frame"),
            layout: &self.unlit,
            entries: &[
                view_entry,
                frame_entry,
                texture(group0::BACKDROP_MAP, &environment.backdrop),
                texture(group0::ENVIRONMENT_MAP, &environment.pmrem),
                wgpu::BindGroupEntry {
                    binding: group0::ENVIRONMENT_SAMPLER,
                    resource: wgpu::BindingResource::Sampler(&environments.sampler),
                },
                texture(group0::FOG_VOLUME, &self.fog.0),
                wgpu::BindGroupEntry {
                    binding: group0::FOG_SAMPLER,
                    resource: wgpu::BindingResource::Sampler(&self.fog.1),
                },
            ],
        })
    }

    /// A shadow group 0: `view` and `frame`.
    pub fn shadow_group(
        &self,
        device: &wgpu::Device,
        view: &wgpu::Buffer,
        frame: &wgpu::Buffer,
    ) -> wgpu::BindGroup {
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("shadow view"),
            layout: &self.shadow,
            entries: &shading::bind::uniforms(view, frame),
        })
    }
}