Skip to main content

crcbl_render/
exposure.rs

1//! Topic 43 §6's auto-exposure: the luminance
2//! histogram of the finished frame, the reduce that turns it into one number,
3//! and the buffer the tonemap reads that number out of.
4//!
5//! ```text
6//!  begin_frame ──▶ extent ──▶ params[frame]
7//!
8//!  add_passes ── compute "exposure-clear"     ──▶ histogram[frame]
9//!             ── compute "exposure-histogram" scene-color ──▶ histogram[frame]
10//!             ── compute "exposure-reduce"    histogram   ──▶ measured[frame]
11//!                                                  tonemap reads measured[frame]
12//! ```
13//!
14//! A module of its own on [`crate::volumetric`]'s terms exactly: three
15//! pipelines, two buffer rings and the pass group, none of it reachable from
16//! the passes that draw except through [`Exposure::add_passes`].
17//!
18//! # Nothing here is read back, and nothing here is a frame behind
19//!
20//! All three passes run inside the frame they measure — the histogram bins the
21//! scene colour the passes before it produced, and the tonemap that follows
22//! reads the exposure the reduce wrote. So the exposure a frame is drawn with
23//! is measured from that frame, with no readback to stall on.
24//!
25//! The one value that survives between frames is the adaptation's starting
26//! point: with an [`ExposureAdaptation`] set, the reduce steps from the
27//! previous frame's exposure — the `measured` ring's slot behind the one it
28//! writes — toward this frame's measurement, so a cut between two
29//! differently-lit shots rolls rather than landing in a single frame.
30//!
31//! # The switch is a lane of the tonemap's block
32//!
33//! `tonemap.slang` binds [`Exposure::measured`]'s buffer on every frame and
34//! reads it only when its block says to, so a frame that adds no passes here
35//! writes a zero into that lane and draws exactly the picture this engine drew
36//! before the pass existed. [`crate::forward`] is what writes both.
37
38use crcbl_hal::{
39    BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
40    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
41    BufferUsage, ComputePipelineHandle, Device, HalError, ImageViewHandle, ImageViewType,
42    MemoryLocation, PipelineLayoutDesc, PipelineLayoutHandle, QueueHandle, ResourceState,
43    SampleType, ShaderStages, check_portable_storage_buffers,
44};
45use crcbl_shaders::EXPOSURE;
46use crcbl_shaders::exposure::{
47    BIN_COUNT, BIN_STRIDE, ExposureParams, HISTOGRAM_TILE_SIDE, MEASURED_SIZE, PARAMS_SIZE,
48    WORKGROUP_SIZE,
49};
50
51use std::cell::Cell;
52use std::rc::Rc;
53
54use crate::draw_gen::{
55    UINT_STRIDE, bound, compute_pipeline_entry, compute_pipeline_entry_with_workgroup,
56    fill_at_start_up, storage, uniform,
57};
58use crate::graph::{ImageId, ImportedBuffer, RenderGraph};
59use crate::ssao::cached_group;
60
61/// How far one frame's exposure may travel toward the one its histogram asks
62/// for.
63///
64/// **Why a step and not the measurement itself.** A real eye takes seconds to
65/// adapt; an exposure that lands on its target in a single frame turns a camera
66/// cut, a muzzle flash or a door opening into a flicker. So a view hands this
67/// in every frame with its own delta, and
68/// [`ForwardRenderer::set_exposure_adaptation`](crate::ForwardRenderer::set_exposure_adaptation)
69/// is where it goes.
70///
71/// **The two rates differ because the eye's do.** Adapting *down* to a scene
72/// that just got bright is fast and adapting back up is slow, and a viewer
73/// notices immediately when they are swapped. They are named for what the
74/// exposure does, not for what the scene did: `brighten` is the exposure
75/// climbing, which is the picture getting brighter as the eye opens up in the
76/// dark.
77///
78/// Each is a fraction of the remaining distance per second, so `2.0` covers
79/// half the distance in a quarter of a second and anything at or above
80/// `1.0 / delta` arrives in one frame. It is the linear approximation of the
81/// exponential approach every engine writes as `1 - exp(-rate * delta)`, and it
82/// is linear on purpose: this workspace lets no transcendental reach a colour,
83/// and an exposure multiplies every texel of the frame.
84#[derive(Clone, Copy, Debug, PartialEq)]
85pub struct ExposureAdaptation {
86    /// Fraction of the remaining distance per second while the exposure climbs.
87    pub brighten: f32,
88    /// The same while it falls.
89    pub darken: f32,
90    /// How long this frame was, in seconds — the view's own delta.
91    pub delta: f32,
92}
93
94impl ExposureAdaptation {
95    /// The two blends the block carries: `rate * delta`, clamped into `[0, 1]`.
96    ///
97    /// Clamped here rather than only in the shader because a rate and a delta
98    /// are both a caller's numbers, and the product of two of those is where a
99    /// pause, a breakpoint or a first frame puts a blend of several hundred.
100    fn blends(self) -> (f32, f32) {
101        let blend = |rate: f32| (rate * self.delta).clamp(0.0, 1.0);
102        (blend(self.brighten), blend(self.darken))
103    }
104}
105
106/// The buffers one frame's measurement lives in.
107///
108/// **A window for a test, and this pass's only public surface**, on
109/// [`FroxelBuffers`](crate::FroxelBuffers)' terms: the histogram is checked
110/// against `crcbl_shaders::exposure` bin by bin, which is the one thing that
111/// can tell a wrong bin from a wrong dispatch extent — a frame-level check sees
112/// only the exposure the two of them compose to.
113#[derive(Clone, Copy, Debug)]
114pub struct ExposureBuffers {
115    /// `[bin]`: how many texels of the frame landed in each bin, as
116    /// `histogramMain` left it.
117    pub histogram: BufferHandle,
118    /// `[0]`: the exposure `reduceMain` measured, and the one the tonemap
119    /// applied.
120    pub measured: BufferHandle,
121}
122
123/// Everything the pass owns.
124///
125/// Built once by [`Exposure::new`] and released by [`Exposure::destroy`], which
126/// is the shape every other resource group in this crate has.
127#[derive(Debug)]
128pub(crate) struct Exposure {
129    layout: BindGroupLayoutHandle,
130    pipeline_layout: PipelineLayoutHandle,
131    /// Zeroes the bins. A pass of its own because the histogram accumulates
132    /// with an atomic add — `exposure.slang` says why that is the only clear a
133    /// storage buffer has here.
134    clear: ComputePipelineHandle,
135    histogram_pipeline: ComputePipelineHandle,
136    reduce: ComputePipelineHandle,
137    /// `[frame]`: the extent being binned, one block per frame in flight for
138    /// the frame uniforms' reason — the previous frame may still be reading
139    /// last frame's while this one is written.
140    params: Vec<BufferHandle>,
141    /// `[frame]`: the bins.
142    histograms: Vec<BufferHandle>,
143    /// `[frame]`: the one float the tonemap reads.
144    measured: Vec<BufferHandle>,
145    /// `[frame]`: the group all three dispatches bind, cached against the scene
146    /// view — which is a graph transient, so it cannot be built until the graph
147    /// has realised one.
148    groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
149}
150
151impl Exposure {
152    /// Passes [`Exposure::add_passes`] adds to a frame.
153    ///
154    /// Exact rather than a ceiling: the three run or none of them do.
155    pub(crate) const PASSES: u32 = 3;
156
157    /// Builds the three pipelines and the buffer rings.
158    ///
159    /// # Errors
160    ///
161    /// [`HalError`] from any seam call. **Nothing is released on the failing
162    /// path**, for the reason every other builder in this crate gives: the
163    /// caller holds a rollback, and this is stored in it whole.
164    pub(crate) fn new(
165        device: &dyn Device,
166        queue: QueueHandle,
167        frames: usize,
168    ) -> Result<Self, HalError> {
169        // **Two, not one.** A frame reads the slot behind it for the exposure
170        // to adapt away from, and with a single slot that is the one this
171        // frame's reduce also writes — which the graph refuses outright, since
172        // a pass cannot claim one resource as both written and read. Enforced
173        // here rather than branched around: [`crate::forward::FRAMES_IN_FLIGHT`]
174        // is two, so the one-slot path would be a branch nothing ever takes.
175        if frames < 2 {
176            return Err(HalError::InvalidDescriptor(format!(
177                "auto-exposure needs at least two frames in flight, so a frame can read \
178                 the exposure the frame before it measured; got {frames}"
179            )));
180        }
181        // `exposure.slang`'s declaration order, which is the only order Metal
182        // and D3D12 agree about — see `crcbl_shaders::declaration_order`.
183        let entries = [
184            uniform(0),
185            BindGroupLayoutEntry {
186                binding: 1,
187                visibility: ShaderStages::COMPUTE,
188                kind: BindingKind::SampledImage {
189                    view_type: ImageViewType::D2,
190                    // The `Rgba16Float` scene target: an ordinary colour image,
191                    // and the WGSL artifact declares `texture_2d<f32>` for it.
192                    sample_type: SampleType::Float,
193                },
194                count: 1,
195                flags: BindingFlags::empty(),
196            },
197            storage(2, false, UINT_STRIDE),
198            storage(3, false, size_of::<f32>() as u32),
199            // Read-only: the reduce reads the frame before's exposure and never
200            // writes through this binding, which is what lets it be a different
201            // slot of the same ring the entry above writes.
202            storage(4, true, size_of::<f32>() as u32),
203        ];
204        let desc = BindGroupLayoutDesc {
205            label: Some("exposure"),
206            entries: &entries,
207        };
208        check_portable_storage_buffers(Some("exposure"), &[&desc])?;
209        let layout = device.create_bind_group_layout(&desc)?;
210        let set_layouts = [layout];
211        let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
212            label: Some("exposure"),
213            bind_group_layouts: &set_layouts,
214            push_constants: None,
215        })?;
216        // Three entry points of one module, which is why this is
217        // `compute_pipeline_entry` rather than `compute_pipeline`: the three
218        // share the binning arithmetic and shaders here have no `#include`.
219        let clear = compute_pipeline_entry(
220            device,
221            "exposure clear",
222            &EXPOSURE,
223            "clearMain",
224            pipeline_layout,
225            WORKGROUP_SIZE,
226        )?;
227        let histogram_pipeline = compute_pipeline_entry_with_workgroup(
228            device,
229            "exposure histogram",
230            &EXPOSURE,
231            "histogramMain",
232            pipeline_layout,
233            [HISTOGRAM_TILE_SIDE, HISTOGRAM_TILE_SIDE, 1],
234        )?;
235        let reduce = compute_pipeline_entry(
236            device,
237            "exposure reduce",
238            &EXPOSURE,
239            "reduceMain",
240            pipeline_layout,
241            // One invocation for the whole reduce, on the shader's own terms:
242            // float addition is not associative, so a tree would sum the bins in
243            // an order a device schedules and the exposure would differ in its
244            // last place between backends.
245            1,
246        )?;
247
248        let mut params = Vec::with_capacity(frames);
249        let mut histograms = Vec::with_capacity(frames);
250        let mut measured = Vec::with_capacity(frames);
251        for frame in 0..frames {
252            params.push(device.create_buffer(&BufferDesc {
253                label: Some(&format!("exposure params {frame}")),
254                size: PARAMS_SIZE as u64,
255                usage: BufferUsage::UNIFORM,
256                memory: MemoryLocation::HostUpload,
257            })?);
258            histograms.push(device.create_buffer(&BufferDesc {
259                label: Some(&format!("exposure histogram {frame}")),
260                size: u64::from(BIN_COUNT) * BIN_STRIDE as u64,
261                // `TRANSFER_SRC` because a test reads the bins back and compares
262                // them against the host's own binning of the same frame — the
263                // pass has no other observable, since the exposure it produces
264                // is a single number two different mistakes can agree on.
265                usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
266                memory: MemoryLocation::DeviceLocal,
267            })?);
268            let slot = device.create_buffer(&BufferDesc {
269                label: Some(&format!("exposure measured {frame}")),
270                size: MEASURED_SIZE as u64,
271                // `STORAGE` in three stages: written by the reduce, read by the
272                // tonemap, and read again by the *next* frame's reduce as the
273                // exposure to adapt away from. `TRANSFER_DST` for the start-up
274                // fill below.
275                usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC | BufferUsage::TRANSFER_DST,
276                memory: MemoryLocation::DeviceLocal,
277            })?;
278            // **Every slot starts at the default exposure**, because the first
279            // frame's reduce reads one of them as the value to adapt from and a
280            // device-local allocation carries whatever was last in that memory.
281            // A garbage prior inside the legal range would be indistinguishable
282            // from a measurement, and would differ between runs.
283            fill_at_start_up(
284                device,
285                queue,
286                &format!("exposure measured {frame}"),
287                slot,
288                &crcbl_shaders::tonemap::DEFAULT_EXPOSURE.to_le_bytes(),
289                // What `add_passes` imports it in, and what the tonemap left it
290                // in on every frame after the first.
291                ResourceState::ShaderRead,
292            )?;
293            measured.push(slot);
294        }
295
296        Ok(Self {
297            layout,
298            pipeline_layout,
299            clear,
300            histogram_pipeline,
301            reduce,
302            params,
303            histograms,
304            measured,
305            groups: vec![None; frames],
306        })
307    }
308
309    /// Writes `frame`'s parameter block: the extent of the image to bin.
310    ///
311    /// # Errors
312    ///
313    /// [`HalError`] from the mapped write.
314    ///
315    /// # Panics
316    ///
317    /// If `frame` is not a slot this was built with.
318    pub(crate) fn begin_frame(
319        &self,
320        device: &dyn Device,
321        frame: usize,
322        extent: (u32, u32),
323        adaptation: Option<ExposureAdaptation>,
324    ) -> Result<(), HalError> {
325        // `None` is both blends at one, which is the whole distance in one
326        // frame — the picture this pass drew before adaptation existed, and the
327        // one `ExposureParams::default` carries for the same reason.
328        let (brighten_blend, darken_blend) =
329            adaptation.map_or((1.0, 1.0), ExposureAdaptation::blends);
330        device.write_buffer(
331            self.params[frame],
332            0,
333            &ExposureParams {
334                viewport_x: extent.0.max(1),
335                viewport_y: extent.1.max(1),
336                brighten_blend,
337                darken_blend,
338            }
339            .to_bytes(),
340        )
341    }
342
343    /// The slot holding what the frame before `frame` was exposed by.
344    ///
345    /// One step back around the same ring, which is the previous frame because
346    /// the frame index advances by one — and never `frame`'s own slot, which is
347    /// what [`Exposure::new`]'s two-slot floor is for.
348    ///
349    /// # Panics
350    ///
351    /// If `frame` is not a slot this was built with.
352    fn previous(&self, frame: usize) -> BufferHandle {
353        assert!(frame < self.measured.len(), "no such frame slot");
354        self.measured[(frame + self.measured.len() - 1) % self.measured.len()]
355    }
356
357    /// The buffer the tonemap binds: `frame`'s measured exposure.
358    ///
359    /// # Panics
360    ///
361    /// If `frame` is not a slot this was built with.
362    pub(crate) fn measured(&self, frame: usize) -> BufferHandle {
363        self.measured[frame]
364    }
365
366    /// `frame`'s bins and the exposure they were reduced to.
367    ///
368    /// # Panics
369    ///
370    /// If `frame` is not a slot this was built with.
371    pub(crate) fn buffers(&self, frame: usize) -> ExposureBuffers {
372        ExposureBuffers {
373            histogram: self.histograms[frame],
374            measured: self.measured[frame],
375        }
376    }
377
378    /// Adds the clear, the histogram and the reduce, in that order.
379    ///
380    /// `scene` is the image the tonemap is about to read, and binning anything
381    /// else would expose the frame for a picture nobody sees.
382    ///
383    /// # Panics
384    ///
385    /// If `frame` is not a slot this was built with.
386    pub(crate) fn add_passes<'a>(
387        &'a mut self,
388        graph: &mut RenderGraph<'a>,
389        frame: usize,
390        extent: (u32, u32),
391        scene: ImageId,
392    ) {
393        // Both arrive in the state the previous frame that used this slot left
394        // them in, which is the state declared as final: the tonemap read the
395        // measurement and nothing read the bins. Vacuous on the first frame, and
396        // the real prior use on every later one.
397        let bins = graph.import_buffer(
398            "exposure-histogram",
399            ImportedBuffer {
400                buffer: self.histograms[frame],
401                initial: ResourceState::ShaderRead,
402                final_state: ResourceState::ShaderRead,
403            },
404        );
405        let measured = graph.import_buffer(
406            "exposure-measured",
407            ImportedBuffer {
408                buffer: self.measured[frame],
409                initial: ResourceState::ShaderRead,
410                final_state: ResourceState::ShaderRead,
411            },
412        );
413        // The frame before's slot, always a different buffer from the one this
414        // frame writes — `Exposure::new` refuses a ring too short for that.
415        let previous_buffer = self.previous(frame);
416        let previous = graph.import_buffer(
417            "exposure-previous",
418            ImportedBuffer {
419                buffer: previous_buffer,
420                // What the frame that wrote it left it in, and what this frame
421                // leaves it in: nothing here writes through it.
422                initial: ResourceState::ShaderRead,
423                final_state: ResourceState::ShaderRead,
424            },
425        );
426        let params = self.params[frame];
427        let histogram_buffer = self.histograms[frame];
428        let measured_buffer = self.measured[frame];
429        let layout = self.layout;
430        let pipeline_layout = self.pipeline_layout;
431        let clear = self.clear;
432        let histogram = self.histogram_pipeline;
433        let reduce = self.reduce;
434        let cached = &mut self.groups[frame];
435
436        // One group for all three dispatches, built inside the first of them:
437        // it names the scene colour, which is a graph transient, so there is no
438        // view to name until the graph has realised one. Cached against that
439        // view, and therefore rebuilt only on a resize.
440        //
441        // A shared `Cell` carries it to the two passes after this one: the pass
442        // bodies run synchronously and in order on this thread, so the pass that
443        // builds the group has always run before the two that bind it. `Rc`
444        // rather than a borrow because each body is an owned closure the graph
445        // keeps, and a body that finds no group records no dispatch rather than
446        // binding a stale one.
447        let group: Rc<Cell<Option<BindGroupHandle>>> = Rc::new(Cell::new(None));
448        let build = Rc::clone(&group);
449        graph
450            .add_compute_pass("exposure-clear")
451            // `ShaderReadWrite` rather than a write-only state, on the light
452            // grid's terms: a storage-buffer descriptor permits reads whatever
453            // the shader does with it.
454            .use_buffer(bins, ResourceState::ShaderReadWrite)
455            .use_buffer(measured, ResourceState::ShaderReadWrite)
456            // The image the pass after this one bins. Declared here as well
457            // because the group naming it is built in this pass, and a view is
458            // only realised for a pass that declared the image.
459            .read_image(scene)
460            .execute(move |ctx| {
461                let view = ctx.image_view(scene);
462                let device = ctx.device();
463                let entries = [
464                    bound(0, params),
465                    // Overwritten by `cached_group` with the realised view;
466                    // written here so the list is a complete description of the
467                    // layout rather than one with a hole in it.
468                    BindGroupEntry {
469                        binding: 1,
470                        array_index: 0,
471                        resource: BindingResource::ImageView(view),
472                    },
473                    bound(2, histogram_buffer),
474                    bound(3, measured_buffer),
475                    bound(4, previous_buffer),
476                ];
477                let Some(built) =
478                    cached_group(cached, device, &[(1, view)], "exposure", layout, &entries)
479                else {
480                    return;
481                };
482                build.set(Some(built));
483                let encoder = ctx.encoder();
484                encoder.bind_compute_pipeline(clear);
485                encoder.bind_group(0, built, &[], pipeline_layout);
486                encoder.dispatch(BIN_COUNT.div_ceil(WORKGROUP_SIZE), 1, 1);
487            });
488
489        // One invocation per texel of the scene target, grouped into square
490        // tiles that merge their local bins before touching the frame-wide
491        // histogram. Never zero: Metal rejects an empty dispatch outright
492        // rather than treating it as a no-op.
493        let columns = extent.0.max(1).div_ceil(HISTOGRAM_TILE_SIDE);
494        let rows = extent.1.max(1).div_ceil(HISTOGRAM_TILE_SIDE);
495        let bind = Rc::clone(&group);
496        graph
497            .add_compute_pass("exposure-histogram")
498            .use_buffer(bins, ResourceState::ShaderReadWrite)
499            .read_image(scene)
500            .execute(move |ctx| {
501                let Some(group) = bind.get() else {
502                    return;
503                };
504                let encoder = ctx.encoder();
505                encoder.bind_compute_pipeline(histogram);
506                encoder.bind_group(0, group, &[], pipeline_layout);
507                encoder.dispatch(columns, rows, 1);
508            });
509
510        let bind = group;
511        graph
512            .add_compute_pass("exposure-reduce")
513            // The histogram's own output, read here — the graph's barrier
514            // between the two comes from both declaring this one id.
515            .use_buffer(bins, ResourceState::ShaderReadWrite)
516            .use_buffer(measured, ResourceState::ShaderReadWrite)
517            // The frame before's exposure, read to adapt away from.
518            .use_buffer(previous, ResourceState::ShaderRead)
519            .execute(move |ctx| {
520                let Some(group) = bind.get() else {
521                    return;
522                };
523                let encoder = ctx.encoder();
524                encoder.bind_compute_pipeline(reduce);
525                encoder.bind_group(0, group, &[], pipeline_layout);
526                encoder.dispatch(1, 1, 1);
527            });
528    }
529
530    /// Releases every object this owns.
531    pub(crate) fn destroy(self, device: &dyn Device) {
532        for cached in self.groups.into_iter().flatten() {
533            device.destroy_bind_group(cached.1);
534        }
535        device.destroy_compute_pipeline(self.reduce);
536        device.destroy_compute_pipeline(self.histogram_pipeline);
537        device.destroy_compute_pipeline(self.clear);
538        device.destroy_pipeline_layout(self.pipeline_layout);
539        device.destroy_bind_group_layout(self.layout);
540        for buffer in self
541            .params
542            .into_iter()
543            .chain(self.histograms)
544            .chain(self.measured)
545        {
546            device.destroy_buffer(buffer);
547        }
548    }
549}
550
551// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
552#[cfg(all(test, not(target_arch = "wasm32")))]
553mod tests {
554    use super::*;
555    use crate::TransientPool;
556    use crcbl_hal::{
557        ClearValue, CommandEncoderDesc, DeviceDesc, Features, Instance, Limits, LoadOp, QueueKind,
558        StoreOp,
559        null::{Command, NullInstance},
560    };
561
562    #[test]
563    fn histogram_dispatch_stays_within_the_portable_budget() {
564        let backend = NullInstance::portable();
565        let recorder = backend.recorder();
566        let adapter = backend.adapters().remove(0);
567        let device = backend
568            .create_device(&DeviceDesc {
569                required_features: Features::COMPUTE,
570                ..DeviceDesc::for_adapter(adapter.id)
571            })
572            .expect("device");
573        let queue = device.queue(QueueKind::Graphics).expect("queue");
574        let limits = Limits::minimum();
575        for extent in [
576            (3840, 2160),
577            (0, 0),
578            (1, 1),
579            (63, 193),
580            (64, 193),
581            (65, 193),
582            (limits.max_image_2d, limits.max_image_2d),
583        ] {
584            let normalized = (extent.0.max(1), extent.1.max(1));
585            let mut exposure = Exposure::new(device.as_ref(), queue, 2).expect("exposure");
586            exposure
587                .begin_frame(device.as_ref(), 0, extent, None)
588                .expect("parameters");
589            let mut pool = TransientPool::new();
590            let mut graph = RenderGraph::new(queue);
591            let scene = graph.create_image("scene", crate::targets::scene_color(normalized));
592            graph
593                .add_render_pass("scene-clear")
594                .color(scene, LoadOp::Clear, StoreOp::Store, ClearValue::default())
595                .execute(|_| {});
596            exposure.add_passes(&mut graph, 0, extent, scene);
597            let compiled = graph.compile(&pool).expect("compiled");
598            recorder.clear();
599            let mut encoder =
600                device.create_command_encoder(&CommandEncoderDesc { label: None, queue });
601            compiled
602                .execute(device.as_ref(), &mut pool, encoder.as_mut(), None)
603                .expect("recorded");
604            let command_buffer = encoder.finish().expect("finished");
605            let dispatches: Vec<_> = recorder
606                .commands()
607                .into_iter()
608                .filter_map(|command| match command {
609                    Command::Dispatch { x, y, z } => Some([x, y, z]),
610                    _ => None,
611                })
612                .collect();
613            assert_eq!(dispatches.len(), Exposure::PASSES as usize, "{extent:?}");
614            for dispatch in &dispatches {
615                assert!(
616                    dispatch.iter().all(
617                        |&axis| axis > 0 && axis <= limits.max_compute_workgroups_per_dimension
618                    ),
619                    "{extent:?}: {dispatch:?} exceeds the portable dispatch budget"
620                );
621            }
622            assert_eq!(
623                dispatches[1],
624                [
625                    normalized.0.div_ceil(HISTOGRAM_TILE_SIDE),
626                    normalized.1.div_ceil(HISTOGRAM_TILE_SIDE),
627                    1,
628                ],
629                "{extent:?}"
630            );
631            device.destroy_command_buffer(command_buffer);
632            exposure.destroy(device.as_ref());
633            pool.destroy(device.as_ref());
634            recorder.assert_valid();
635        }
636    }
637}