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