sgl-3d 0.4.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
use super::*;
use crate::frame_input::CompensationCurve;
use crate::test_support::{hdr_texture, read};

/// The histogram `exposure` accumulated, read without averaging it.
fn histogram_of(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    exposure: &mut Exposure,
    frame: &wgpu::TextureView,
    automatic: &AutoExposure,
) -> Vec<u32> {
    exposure.upload(
        queue,
        Metering {
            automatic,
            stops: 0.,
            delta_time: 0.,
            reset: true,
        },
    );
    let group = exposure.group(device, frame);
    let size = frame.texture().size();
    let readback = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("histogram readback"),
        size: 64 * 4,
        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    });
    let mut encoder = device.create_command_encoder(&Default::default());
    {
        let mut pass = encoder.begin_compute_pass(&Default::default());
        pass.set_bind_group(0, &group, &[]);
        pass.set_pipeline(&exposure.histogram_pipeline);
        pass.dispatch_workgroups(size.width.div_ceil(16), size.height.div_ceil(16), 1);
    }
    encoder.copy_buffer_to_buffer(&exposure.histogram, 0, &readback, 0, 64 * 4);
    queue.submit([encoder.finish()]);
    readback.map_async(wgpu::MapMode::Read, .., |result| result.unwrap());
    device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
    bytemuck::cast_slice(&readback.get_mapped_range(..).unwrap()).to_vec()
}

/// One frame of auto exposure of `frame`; returns the correction in stops.
fn adapt(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    exposure: &mut Exposure,
    frame: &wgpu::TextureView,
    metering: Metering<'_>,
) -> f32 {
    let mut encoder = device.create_command_encoder(&Default::default());
    exposure.meter(device, queue, &mut encoder, frame, metering, None);
    queue.submit([encoder.finish()]);
    let multiplier: f32 = bytemuck::pod_read_unaligned(&read(device, queue, &exposure.exposure, 4));
    multiplier.log2() - metering.stops
}

/// A grey frame of `luminance`.
fn grey(device: &wgpu::Device, queue: &wgpu::Queue, luminance: f32) -> wgpu::TextureView {
    hdr_texture(
        device,
        queue,
        [64, 64],
        &[[luminance, luminance, luminance, 1.]; 64 * 64],
    )
}

// Defect: counting near-black pixels at the histogram minimum pulls the
// average down and overexposes the lit half by about four stops. The oracle
// is the remaining half's physical luminance, 1 (log2 0), within a bin.
#[test]
fn near_black_pixels_do_not_pull_down_the_lit_average() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let mut exposure = Exposure::new(&device);
    let automatic = AutoExposure::default();
    for dark in [0., 1. / 1024.] {
        let texels: Vec<_> = (0..64 * 64)
            .map(|i| {
                let luminance = if i < 64 * 32 { dark } else { 1. };
                [luminance, luminance, luminance, 1.]
            })
            .collect();
        let frame = hdr_texture(&device, &queue, [64, 64], &texels);
        let correction = adapt(
            &device,
            &queue,
            &mut exposure,
            &frame,
            Metering {
                automatic: &automatic,
                stops: 0.,
                delta_time: 0.,
                reset: true,
            },
        );
        assert!(
            correction.abs() <= 16. / 62.,
            "half luminance {dark}, half luminance 1 should meter near 0 stops: {correction}"
        );
    }
}

// Defect: removing black samples before computing the percentile window
// admits bright outliers. Half this frame is black, 40% is luminance 1,
// and the brightest 10% is luminance 16: the 10-90% window keeps only the
// luminance-1 samples after black is excluded from its average.
#[test]
fn black_pixels_still_position_the_percentile_window() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let mut exposure = Exposure::new(&device);
    let automatic = AutoExposure::default();
    let texels: Vec<_> = (0..100)
        .map(|i| {
            let luminance = match i {
                0..50 => 0.,
                50..90 => 1.,
                _ => 16.,
            };
            [luminance, luminance, luminance, 1.]
        })
        .collect();
    let frame = hdr_texture(&device, &queue, [10, 10], &texels);
    let correction = adapt(
        &device,
        &queue,
        &mut exposure,
        &frame,
        Metering {
            automatic: &automatic,
            stops: 0.,
            delta_time: 0.,
            reset: true,
        },
    );
    assert!(
        correction.abs() <= 16. / 62.,
        "black positions the window so the bright 10% is excluded: {correction}"
    );
}

// Defect: excluding bin 0 can leave no samples and divide by zero. The
// documented fallback is log2 luminance -8 (correction +8): all black,
// an empty mask, or a percentile window smaller than one weighted sample.
#[test]
fn empty_averages_use_the_finite_minimum_luminance() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let mut exposure = Exposure::new(&device);
    let defaults = AutoExposure::default();
    let masked_out = AutoExposure {
        metering_mask: MeteringMask {
            weights: [[0; 16]; 16],
        },
        ..defaults
    };
    let single_sample = AutoExposure {
        metering_mask: MeteringMask {
            weights: [[16; 16]; 16],
        },
        ..defaults
    };
    for (frame, automatic) in [
        (grey(&device, &queue, 0.), &defaults),
        (grey(&device, &queue, 1.), &masked_out),
        (
            hdr_texture(&device, &queue, [1, 1], &[[1., 1., 1., 1.]]),
            &single_sample,
        ),
    ] {
        let correction = adapt(
            &device,
            &queue,
            &mut exposure,
            &frame,
            Metering {
                automatic,
                stops: 0.,
                delta_time: 0.,
                reset: true,
            },
        );
        assert!(
            (correction - 8.).abs() < 1e-4,
            "an empty average uses the minimum luminance: {correction}"
        );
    }
}

// Defects: workgroups that add bins they do not own (Bevy adds 256
// invocations' worth into 64 bins), lost atomics or barriers, partial
// workgroups at the frame's edges counted or dropped wrongly, a mask read
// flipped or scaled, or luminance binned on the wrong scale. The oracle is a
// CPU histogram of a frame whose every pixel was built in the middle of a
// known bin of the 64-bin log2 histogram, weighted by its mask cell.
#[test]
fn histogram_counts_each_pixel_in_its_bin_by_its_mask_weight() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let size = [37usize, 29];
    let automatic = AutoExposure {
        metering_mask: MeteringMask {
            weights: std::array::from_fn(|row| {
                std::array::from_fn(|column| ((row * 31 + column * 17) % 256) as u8)
            }),
        },
        ..Default::default()
    };
    let (min, max) = (MIN_LOG_LUMINANCE, MAX_LOG_LUMINANCE);
    let mut expected = vec![0u32; 64];
    let mut texels = Vec::new();
    for y in 0..size[1] {
        for x in 0..size[0] {
            let bin = (x * 7 + y * 13) % 64;
            let log_luminance = match bin {
                0 => min - 2.,
                63 => max + 1.,
                _ => min + (max - min) * (bin as f32 - 0.5) / 62.,
            };
            let luminance = log_luminance.exp2();
            texels.push([luminance, luminance, luminance, 1.]);
            let weight = automatic.metering_mask.weights[y * 16 / size[1]][x * 16 / size[0]];
            expected[bin] += (f32::from(weight) / 255. * 16.) as u32;
        }
    }
    let frame = hdr_texture(&device, &queue, size.map(|v| v as u32), &texels);
    let mut exposure = Exposure::new(&device);
    let actual = histogram_of(&device, &queue, &mut exposure, &frame, &automatic);
    assert_eq!(actual, expected);
}

// Defects: adaptation at the wrong speed or in the wrong direction's speed,
// a correction that ignores its limits or its compensation curve (points
// unpacked out of order or off by one), or a history reset that does not
// take the target. The oracle is the authored behaviour: steps of speed ×
// time while far from the target, convergence to the correction that brings
// the metered average to 1, the compensation curve's stops linearly
// interpolated between its points (within the histogram's quarter-stop
// bins), and the limits.
#[test]
fn correction_adapts_at_the_authored_speeds_within_its_limits() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let mut exposure = Exposure::new(&device);
    let dim = grey(&device, &queue, 1.);
    let bright = grey(&device, &queue, 16.);
    let automatic = AutoExposure {
        speed_brighten: 2.,
        speed_darken: 0.5,
        ..Default::default()
    };
    let frame = |reset| Metering {
        automatic: &automatic,
        stops: 0.,
        delta_time: 0.1,
        reset,
    };
    let bin = 16. / 62.;
    let start = adapt(&device, &queue, &mut exposure, &dim, frame(true));
    assert!(
        start.abs() <= bin,
        "a reset takes the target, 0 stops: {start}"
    );
    // The scene brightens by 4 stops: 0.2 stops a frame until within 1.5.
    let mut correction = start;
    for step in 0..10 {
        let next = adapt(&device, &queue, &mut exposure, &bright, frame(false));
        assert!(
            (next - correction + 0.2).abs() < 1e-4,
            "brightening step {step}: {correction} to {next}"
        );
        correction = next;
    }
    for _ in 0..200 {
        correction = adapt(&device, &queue, &mut exposure, &bright, frame(false));
    }
    assert!(
        (correction + 4.).abs() <= bin,
        "converges to -4 stops: {correction}"
    );
    // Back to the dim scene: 0.05 stops a frame.
    for step in 0..10 {
        let next = adapt(&device, &queue, &mut exposure, &dim, frame(false));
        assert!(
            (next - correction - 0.05).abs() < 1e-4,
            "darkening step {step}: {correction} to {next}"
        );
        correction = next;
    }
    // The authored stops are metered and corrected for: the multiplier is
    // unchanged by them while the correction is unlimited.
    let shifted = Metering {
        stops: 1.,
        ..frame(true)
    };
    let corrected = adapt(&device, &queue, &mut exposure, &bright, shifted);
    assert!(
        (corrected + 1. + 4.).abs() <= bin,
        "1 authored stop is corrected: {corrected}"
    );
    let limited = AutoExposure {
        correction_min: -1.,
        correction_max: 1.,
        ..automatic
    };
    let limited_frame = Metering {
        automatic: &limited,
        ..frame(true)
    };
    // Three points, two to a vector: each metered average takes the stops
    // interpolated on its own segment.
    let points = [[-4., -1.], [0., -3.], [4., -2.]];
    let curved = AutoExposure {
        compensation: CompensationCurve::new(&points).unwrap(),
        ..automatic
    };
    for log_luminance in [-2f32, 2.] {
        let segment = points
            .windows(2)
            .find(|pair| pair[1][0] >= log_luminance)
            .unwrap();
        let t = (log_luminance - segment[0][0]) / (segment[1][0] - segment[0][0]);
        let stops = segment[0][1] + (segment[1][1] - segment[0][1]) * t;
        let scene = grey(&device, &queue, log_luminance.exp2());
        let corrected = adapt(
            &device,
            &queue,
            &mut exposure,
            &scene,
            Metering {
                automatic: &curved,
                ..frame(true)
            },
        );
        assert!(
            (corrected - (stops - log_luminance)).abs() <= bin,
            "average 2^{log_luminance} compensated by {stops} stops: {corrected}"
        );
    }
    let darkest = adapt(&device, &queue, &mut exposure, &bright, limited_frame);
    assert_eq!(darkest, -1., "the correction stops at its lower limit");
    let brightest = adapt(
        &device,
        &queue,
        &mut exposure,
        &grey(&device, &queue, 1. / 64.),
        limited_frame,
    );
    assert_eq!(brightest, 1., "the correction stops at its upper limit");
}

// Defect: a long frame (a 3 s hitch) within the transition distance scales
// the remaining delta by speed × time, so the correction lands stops past
// its target, or oscillates around it at low frame rates. The oracle is the
// target a history reset takes on the same frame: one long frame one stop
// off, in either direction, ends on it, not past it.
#[test]
fn a_long_frame_lands_on_the_target() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let mut exposure = Exposure::new(&device);
    let automatic = AutoExposure::default();
    let frame = |delta_time, reset| Metering {
        automatic: &automatic,
        stops: 0.,
        delta_time,
        reset,
    };
    let dim = grey(&device, &queue, 1.);
    let bright = grey(&device, &queue, 2.);
    let dim_target = adapt(&device, &queue, &mut exposure, &dim, frame(0., true));
    let bright_target = adapt(&device, &queue, &mut exposure, &bright, frame(0., true));
    for (scene, target, direction) in [
        (&dim, dim_target, "darker"),
        (&bright, bright_target, "brighter"),
    ] {
        let landed = adapt(&device, &queue, &mut exposure, scene, frame(3., false));
        assert!(
            (landed - target).abs() < 1e-4,
            "one stop {direction} over 3 s: {landed}, target {target}"
        );
    }
}

// Defect: a NaN speed reaches the shader and makes the stored correction
// NaN until history restarts; a negative one walks it away from its target.
// The oracle is `AutoExposure`'s documented fallback: the default speeds.
#[test]
fn invalid_speeds_take_the_defaults() {
    let defaults = AutoExposure::default();
    let uniform = AutoExposureUniform::new(
        &AutoExposure {
            speed_brighten: f32::NAN,
            speed_darken: -2.,
            ..defaults
        },
        0.,
        1. / 60.,
        false,
    );
    assert_eq!(uniform.speed_up, defaults.speed_brighten);
    assert_eq!(uniform.speed_down, defaults.speed_darken);
}

// Defect: an unbounded frame time reaches the shader, where a speed of 0
// times it is NaN, so the correction moves (or turns NaN) instead of
// holding. The oracle is the documented speed: 0 holds the correction at
// the target it took on the previous scene, however long the frame.
#[test]
fn a_zero_speed_holds_over_an_unbounded_frame() {
    let Some((device, queue)) = crate::test_support::device() else {
        return;
    };
    let mut exposure = Exposure::new(&device);
    let automatic = AutoExposure {
        speed_brighten: 0.,
        speed_darken: 0.,
        ..Default::default()
    };
    let frame = |delta_time, reset| Metering {
        automatic: &automatic,
        stops: 0.,
        delta_time,
        reset,
    };
    let dim = grey(&device, &queue, 1.);
    let held = adapt(&device, &queue, &mut exposure, &dim, frame(0., true));
    for scene in [grey(&device, &queue, 2.), grey(&device, &queue, 0.5)] {
        let after = adapt(
            &device,
            &queue,
            &mut exposure,
            &scene,
            frame(f32::INFINITY, false),
        );
        assert_eq!(after, held, "a speed of 0 over an unbounded frame");
    }
}