sgl-3d 0.2.0

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
//! The scene's specular probe collection on the GPU: the installed probes'
//! cube array and metadata (`baked_specular_probe`'s content), and
//! `Scene::set_baked_specular_probes`.
use super::probe_grid::ProbeGrid;
use super::{Scene, buffer};
use crate::baked_specular_probe::{
    BakedSpecularProbe, LEVELS, MAX_PROBES, ProbeError, SpecularProbeBox, SpecularProbeTexels,
};
use glam::{Mat3, Mat4, Vec3};

impl SpecularProbeTexels {
    fn format(&self) -> wgpu::TextureFormat {
        match self {
            Self::Rgba16Float(_) => wgpu::TextureFormat::Rgba16Float,
            Self::Bc6hUfloat(_) => wgpu::TextureFormat::Bc6hRgbUfloat,
        }
    }
}

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct ProbeMetadata {
    world_to_local: [[f32; 4]; 4],
    /// W is 1 when the proxy corrects parallax.
    center: [f32; 4],
    influence_min: [f32; 4],
    influence_max: [f32; 4],
    blend: [f32; 4],
    proxy_min: [f32; 4],
    proxy_max: [f32; 4],
    sphere: [f32; 4],
}

// One immutable storage buffer: fixed arrays keep host and WGSL indexing
// bounded independently of caller data. The world grid's words follow it
// in the same buffer (`ProbeCollection::grid`).
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct CollectionMetadata {
    counts: [u32; 4],
    /// `probe_grid::ProbeGrid`'s origin, scale and size.
    grid_origin: [f32; 3],
    grid_scale: f32,
    grid_size: [u32; 3],
    padding: u32,
    probes: [ProbeMetadata; MAX_PROBES],
}

impl CollectionMetadata {
    fn new(grid: &ProbeGrid) -> Self {
        Self {
            grid_origin: grid.origin.to_array(),
            grid_scale: grid.scale,
            grid_size: grid.size.to_array(),
            ..bytemuck::Zeroable::zeroed()
        }
    }
}

pub(crate) struct UploadedProbes {
    pub view: wgpu::TextureView,
    /// The collection's metadata, then the world grid's cells and their
    /// probe lists (`ProbeGrid::words`).
    pub metadata: wgpu::Buffer,
    /// Each probe's placement, which the metadata and grid are built from.
    placements: Vec<Placement>,
}

/// Where a probe is: what its metadata and the world grid hold of it.
#[derive(Clone, Copy)]
struct Placement {
    center: Vec3,
    world_to_local: Mat4,
    influence: SpecularProbeBox,
    blend: Vec3,
    proxy: Option<SpecularProbeBox>,
}

impl Placement {
    fn new(probe: &BakedSpecularProbe) -> Self {
        Self {
            center: probe.center,
            world_to_local: probe.world_to_local,
            influence: probe.influence,
            blend: probe.blend,
            proxy: probe.proxy,
        }
    }

    /// The placement in a render frame whose origin lies `by` from this
    /// one's: its centre and its frame's origin translated, and its rigid
    /// `world_to_local` rebuilt from that origin rather than translated.
    fn translated(self, by: Vec3) -> Self {
        let rotation = Mat3::from_mat4(self.world_to_local);
        let origin = -(rotation.transpose() * self.world_to_local.w_axis.truncate()) - by;
        let mut world_to_local = self.world_to_local;
        world_to_local.w_axis = (-(rotation * origin)).extend(self.world_to_local.w_axis.w);
        Self {
            center: self.center - by,
            world_to_local,
            ..self
        }
    }

    fn metadata(&self) -> ProbeMetadata {
        let proxy = self.proxy.unwrap_or(self.influence);
        ProbeMetadata {
            world_to_local: self.world_to_local.to_cols_array_2d(),
            center: self
                .center
                .extend(f32::from(self.proxy.is_some()))
                .to_array(),
            influence_min: self.influence.min.extend(0.).to_array(),
            influence_max: self.influence.max.extend(0.).to_array(),
            blend: self.blend.extend(0.).to_array(),
            proxy_min: proxy.min.extend(0.).to_array(),
            proxy_max: proxy.max.extend(0.).to_array(),
            sphere: self
                .world_to_local
                .inverse()
                .transform_point3((self.influence.min + self.influence.max) * 0.5)
                .extend((self.influence.max - self.influence.min).length() * 0.5)
                .to_array(),
        }
    }
}

/// The collection's metadata and world grid over `placements`, in one
/// buffer.
fn collection(device: &wgpu::Device, placements: &[Placement]) -> wgpu::Buffer {
    let influences: Vec<_> = placements
        .iter()
        .map(|placement| (placement.world_to_local, placement.influence))
        .collect();
    let grid = ProbeGrid::new(&influences);
    let mut metadata = CollectionMetadata::new(&grid);
    metadata.counts[0] = placements.len() as u32;
    for (slot, placement) in metadata.probes.iter_mut().zip(placements) {
        *slot = placement.metadata();
    }
    collection_buffer(device, "baked specular probe collection", &metadata, &grid)
}

pub(crate) fn validate_face_size(face_size: u32, limits: &wgpu::Limits) -> Result<(), ProbeError> {
    if !face_size.is_power_of_two()
        || face_size < 1 << (LEVELS - 1)
        || face_size > limits.max_texture_dimension_2d
    {
        return Err(ProbeError::InvalidDimensions);
    }
    Ok(())
}

/// Bytes per row and rows of one face of a level `size` texels wide.
fn level_rows(format: wgpu::TextureFormat, size: u32) -> (u32, u32) {
    let (width, height) = format.block_dimensions();
    let block = format.block_copy_size(None).unwrap_or(0);
    (size.div_ceil(width) * block, size.div_ceil(height))
}

/// Bytes of a prefiltered cube's every level and face.
pub(crate) fn payload_size(format: wgpu::TextureFormat, face_size: u32) -> usize {
    (0..LEVELS)
        .map(|level| {
            let (row, rows) = level_rows(format, face_size >> level);
            row as usize * rows as usize * 6
        })
        .sum()
}

impl BakedSpecularProbe {
    fn validate(&self, limits: &wgpu::Limits) -> Result<(), ProbeError> {
        self.validate_placement()?;
        validate_face_size(self.radiance.face_size, limits)?;
        let texels = &self.radiance.texels;
        let expected = payload_size(texels.format(), self.radiance.face_size);
        if texels.bytes().len() != expected {
            return Err(ProbeError::InvalidPayloadLength {
                expected,
                actual: texels.bytes().len(),
            });
        }
        texels.validate_radiance()
    }
}

fn cube_array(
    device: &wgpu::Device,
    label: &str,
    format: wgpu::TextureFormat,
    face_size: u32,
    cubes: u32,
    levels: u32,
    usage: wgpu::TextureUsages,
) -> wgpu::Texture {
    device.create_texture(&wgpu::TextureDescriptor {
        label: Some(label),
        size: wgpu::Extent3d {
            width: face_size,
            height: face_size,
            depth_or_array_layers: cubes * 6,
        },
        mip_level_count: levels,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format,
        usage,
        view_formats: &[],
    })
}

fn cube_array_view(texture: &wgpu::Texture) -> wgpu::TextureView {
    texture.create_view(&wgpu::TextureViewDescriptor {
        dimension: Some(wgpu::TextureViewDimension::CubeArray),
        ..Default::default()
    })
}

impl UploadedProbes {
    pub(crate) fn new(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        probes: &[BakedSpecularProbe],
    ) -> Result<Self, ProbeError> {
        let limits = device.limits();
        if probes.len() > MAX_PROBES || probes.len() as u32 * 6 > limits.max_texture_array_layers {
            return Err(ProbeError::TooManyProbes);
        }
        let face_size = probes[0].radiance.face_size;
        let format = probes[0].radiance.texels.format();
        if format.required_features() != wgpu::Features::empty()
            && !device.features().contains(format.required_features())
        {
            return Err(ProbeError::CompressionUnsupported);
        }
        for probe in probes {
            probe.validate(&limits)?;
            if probe.radiance.face_size != face_size || probe.radiance.texels.format() != format {
                return Err(ProbeError::MixedRadiance);
            }
        }
        let placements: Vec<_> = probes.iter().map(Placement::new).collect();
        let texture = cube_array(
            device,
            "baked specular probes",
            format,
            face_size,
            probes.len() as u32,
            LEVELS,
            wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        );
        let (block_width, block_height) = format.block_dimensions();
        for (index, probe) in probes.iter().enumerate() {
            let bytes = probe.radiance.texels.bytes();
            let mut offset = 0;
            for level in 0..LEVELS {
                let size = face_size >> level;
                let (row, rows) = level_rows(format, size);
                let count = row as usize * rows as usize * 6;
                crate::counters::write_texture(
                    queue,
                    wgpu::TexelCopyTextureInfo {
                        mip_level: level,
                        origin: wgpu::Origin3d {
                            x: 0,
                            y: 0,
                            z: index as u32 * 6,
                        },
                        ..texture.as_image_copy()
                    },
                    &bytes[offset..offset + count],
                    wgpu::TexelCopyBufferLayout {
                        offset: 0,
                        bytes_per_row: Some(row),
                        rows_per_image: Some(rows),
                    },
                    // A level smaller than a block copies the whole block.
                    wgpu::Extent3d {
                        width: size.div_ceil(block_width) * block_width,
                        height: size.div_ceil(block_height) * block_height,
                        depth_or_array_layers: 6,
                    },
                );
                offset += count;
            }
        }
        Ok(Self {
            view: cube_array_view(&texture),
            metadata: collection(device, &placements),
            placements,
        })
    }

    /// Moves the render origin by `by` (`Scene::move_origin`): each probe's
    /// centre and frame, and the world grid built over them anew. A
    /// capture's radiance is about its centre and is unchanged.
    pub(crate) fn move_origin(&mut self, device: &wgpu::Device, by: Vec3) {
        for placement in &mut self.placements {
            *placement = placement.translated(by);
        }
        self.metadata = collection(device, &self.placements);
    }

    pub(crate) fn empty(device: &wgpu::Device) -> Self {
        let grid = ProbeGrid::empty();
        Self {
            view: cube_array_view(&cube_array(
                device,
                "empty specular probe collection",
                wgpu::TextureFormat::Rgba16Float,
                1,
                1,
                1,
                wgpu::TextureUsages::TEXTURE_BINDING,
            )),
            metadata: collection_buffer(
                device,
                "empty specular probe collection",
                &CollectionMetadata::new(&grid),
                &grid,
            ),
            placements: Vec::new(),
        }
    }
}

/// `metadata`, then `grid`'s words, padded to the struct's 16-byte
/// alignment, which a binding of it must fill.
fn collection_buffer(
    device: &wgpu::Device,
    label: &str,
    metadata: &CollectionMetadata,
    grid: &ProbeGrid,
) -> wgpu::Buffer {
    let mut bytes = bytemuck::bytes_of(metadata).to_vec();
    bytes.extend_from_slice(bytemuck::cast_slice(&grid.words));
    bytes.resize(bytes.len().next_multiple_of(16), 0);
    buffer(device, label, &bytes, wgpu::BufferUsages::STORAGE)
}

impl Scene {
    /// Replace the installed collection; an empty slice clears it. All probes
    /// must share one face size. Invalid input leaves the previous collection
    /// installed. Receivers take environment specular from the probes whose
    /// influence contains them, then the sky.
    pub fn set_baked_specular_probes(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        probes: &[BakedSpecularProbe],
    ) -> Result<(), super::SceneError> {
        self.edited();
        self.baked_specular_probes = if probes.is_empty() {
            None
        } else {
            Some(UploadedProbes::new(device, queue, probes)?)
        };
        // World-space ray hits bind the collection in a renderer's group 0.
        self.resources = super::next_generation();
        Ok(())
    }
}

#[cfg(test)]
pub(crate) fn mirrors() -> [crate::shading::layout_tests::Mirror; 2] {
    use crate::shading::layout_tests::mirror;
    [
        mirror!(
            "geometry",
            "BakedProbe",
            ProbeMetadata,
            [
                world_to_local,
                center,
                influence_min,
                influence_max,
                blend,
                proxy_min,
                proxy_max,
                sphere,
            ]
        ),
        mirror!(
            "geometry",
            "ProbeCollection",
            CollectionMetadata,
            [counts, grid_origin, grid_scale, grid_size, padding, probes]
        ),
    ]
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;
    use crate::baked_specular_probe::{SpecularProbeBox, SpecularProbeRadiance};
    use glam::{Mat4, Vec3};

    fn fixture() -> BakedSpecularProbe {
        BakedSpecularProbe {
            center: Vec3::ZERO,
            world_to_local: Mat4::IDENTITY,
            influence: SpecularProbeBox {
                min: Vec3::splat(-2.),
                max: Vec3::splat(2.),
            },
            blend: Vec3::splat(0.5),
            proxy: Some(SpecularProbeBox {
                min: Vec3::splat(-2.),
                max: Vec3::splat(2.),
            }),
            radiance: SpecularProbeRadiance {
                face_size: 64,
                texels: SpecularProbeTexels::Rgba16Float(vec![
                    0x3c00;
                    payload_size(
                        wgpu::TextureFormat::Rgba16Float,
                        64
                    ) / 2
                ]),
            },
        }
    }

    // Malformed asset input must be rejected before texture creation/upload,
    // which otherwise reports a GPU validation error or admits poisoned radiance.
    #[test]
    fn malformed_radiance_and_truncated_levels_are_rejected() {
        fn values(probe: &mut BakedSpecularProbe) -> &mut Vec<u16> {
            match &mut probe.radiance.texels {
                SpecularProbeTexels::Rgba16Float(values) => values,
                SpecularProbeTexels::Bc6hUfloat(_) => unreachable!(),
            }
        }
        let mut probe = fixture();
        for invalid in [0x7c00, 0xfc00, 0x7e00, 0xbc00, 0x8001] {
            values(&mut probe)[17] = invalid;
            assert!(matches!(
                probe.validate(&wgpu::Limits::default()),
                Err(ProbeError::InvalidRadiance { component: 17 })
            ));
        }
        values(&mut probe)[17] = 0x8000; // IEEE negative zero is finite and nonnegative.
        assert!(probe.validate(&wgpu::Limits::default()).is_ok());
        values(&mut probe).pop();
        assert!(matches!(
            probe.validate(&wgpu::Limits::default()),
            Err(ProbeError::InvalidPayloadLength { .. })
        ));
    }

    #[test]
    fn box_projection_rejects_scale_shear_and_outside_capture_origin() {
        let mut probe = fixture();
        probe.world_to_local = Mat4::from_scale(Vec3::new(1., 2., 1.));
        assert!(matches!(
            probe.validate(&wgpu::Limits::default()),
            Err(ProbeError::InvalidProbe(_))
        ));
        probe.world_to_local = Mat4::IDENTITY;
        probe.world_to_local.y_axis.x = 0.2;
        assert!(matches!(
            probe.validate(&wgpu::Limits::default()),
            Err(ProbeError::InvalidProbe(_))
        ));
        probe.world_to_local =
            Mat4::from_rotation_y(0.7) * Mat4::from_translation(Vec3::new(-10., 0., 0.));
        assert!(matches!(
            probe.validate(&wgpu::Limits::default()),
            Err(ProbeError::InvalidProbe(_))
        ));
        probe.center = Vec3::new(10., 0., 0.);
        assert!(probe.validate(&wgpu::Limits::default()).is_ok());
        probe.blend.x = -0.1;
        assert!(matches!(
            probe.validate(&wgpu::Limits::default()),
            Err(ProbeError::InvalidProbe(_))
        ));
    }

    #[test]
    fn unaddressable_face_sizes_are_rejected_before_payload_access() {
        let mut probe = fixture();
        for face_size in [0, 32, 96, u32::MAX] {
            probe.radiance.face_size = face_size;
            assert!(matches!(
                probe.validate(&wgpu::Limits::default()),
                Err(ProbeError::InvalidDimensions)
            ));
        }
    }
}