Skip to main content

crcbl_frame/
transient.rs

1//! The transient resource pool: graph-owned images and buffers, reused across
2//! frames and aliased within one.
3//!
4//! Stage 2 §2.4 asks for a "transient resource pool:
5//! graph-owned images/buffers aliased across non-overlapping passes". Aliasing
6//! *within* a frame is [`crate::graph`]'s half — it decides which virtual
7//! resources can share a physical one, and it can decide that without a device.
8//! This module is the other half: it turns "I need N physical images shaped like
9//! this" into handles, and it keeps them between frames so a steady-state frame
10//! creates nothing.
11//!
12//! # Reuse is keyed on the whole description, not on size
13//!
14//! [`TransientImageDesc`] is the key, and it is `Hash + Eq` for that reason. Two
15//! images of the same size but different formats or usages are different
16//! resources; treating them as interchangeable is how a depth buffer ends up
17//! sampled as colour on one driver and not another.
18//!
19//! # Retirement is generational, not immediate
20//!
21//! A resize changes the key of every scene target, and the old ones stop being
22//! asked for. They are destroyed after
23//! [`RETIRE_AFTER_FRAMES`] consecutive frames without a request rather than at
24//! once, because `crcbl-hal` is explicit that "`destroy_*` means *this handle is
25//! dead now*; it does **not** promise the GPU is finished with the object", and
26//! frames are in flight. Waiting more frames than the loop keeps in flight makes
27//! the destroy safe without a device-wide idle.
28//!
29//! # The pool remembers what each resource was last used for
30//!
31//! "Transient" names the *virtual* resource's lifetime, not the physical one: a
32//! steady-state frame reuses the very same [`ImageHandle`] it used last frame,
33//! and the frame before that. So the state a frame leaves a pooled resource in
34//! is the state the *next* frame's first barrier has to name as its source, or
35//! that barrier orders itself against nothing and the two frames' writes race.
36//! That is what [`TransientUse`] carries and what
37//! [`TransientPool::image_use`] hands to
38//! [`RenderGraph::compile`](crate::graph::RenderGraph::compile); see that
39//! module's "the physical resource outlives the frame" section for the failure
40//! it fixes.
41//!
42//! The state lives **on the pooled entry**, so retirement takes it with the
43//! resource and a resize cannot leave one resource wearing another's history.
44//!
45//! The pool keeps one more thing for the same reason, about resources it does
46//! not own: what the last graph left each *imported* image and buffer in. An
47//! import's starting state is a declaration rather than a lookup, and
48//! [`TransientPool::imported_image_use`] and
49//! [`TransientPool::imported_buffer_use`] are what let the next
50//! [`RenderGraph::compile`](crate::graph::RenderGraph::compile) reject one that
51//! contradicts the frame before it — see
52//! [`InitialClaim`](crate::graph::InitialClaim) for the image half, which is
53//! the only one of the two with an exemption. The pool holds both because it is
54//! the one thing that outlives a graph and is already handed to `compile` and
55//! `execute` alike.
56
57use std::collections::HashMap;
58
59use crcbl_hal::{
60    BufferDesc, BufferHandle, BufferUsage, Device, Format, HalError, ImageDesc, ImageHandle,
61    ImageSubresourceRange, ImageType, ImageUsage, ImageViewDesc, ImageViewHandle, ImageViewType,
62    MemoryLocation, QueueHandle, ResourceState,
63};
64
65/// Frames a pooled resource may go unused before it is destroyed.
66///
67/// Strictly greater than the two frames the engine keeps in flight, so a
68/// resource dropped at the end of frame *n* is destroyed no earlier than frame
69/// *n + 4* — by which time the submission that used it has certainly completed.
70pub const RETIRE_AFTER_FRAMES: u32 = 3;
71
72/// What a graph-owned image should be.
73///
74/// Deliberately smaller than [`ImageDesc`]: a transient is always a
75/// single-layer 2D image and never has a caller-chosen label — the graph names
76/// it. Fewer fields is fewer ways for two "identical" transients to fail to
77/// alias.
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
79pub struct TransientImageDesc {
80    /// Size in pixels.
81    pub extent: (u32, u32),
82    /// Texel format.
83    pub format: Format,
84    /// Permitted uses.
85    pub usage: ImageUsage,
86    /// Samples per pixel; `1` for everything the MVP renders.
87    pub samples: u32,
88    /// Mip levels. `1` for a plain render target; more for anything a pass
89    /// addresses one level of.
90    ///
91    /// The pool used to hard-code `1` while
92    /// [`PassBuilder::use_subresource`](crate::graph::PassBuilder::use_subresource)
93    /// happily barriered level 3, so the graph and the image disagreed about
94    /// how many levels existed. It is a field for that reason: the graph now
95    /// rejects a subresource the image does not have, and it can only do that
96    /// if the description says.
97    pub mip_levels: u32,
98}
99
100impl TransientImageDesc {
101    /// A single-mip, single-sample 2D image.
102    #[must_use]
103    pub const fn new(extent: (u32, u32), format: Format, usage: ImageUsage) -> Self {
104        Self {
105            extent,
106            format,
107            usage,
108            samples: 1,
109            mip_levels: 1,
110        }
111    }
112
113    /// The same description with `mip_levels` levels.
114    #[must_use]
115    pub const fn with_mip_levels(mut self, mip_levels: u32) -> Self {
116        self.mip_levels = mip_levels;
117        self
118    }
119}
120
121/// What a graph-owned buffer should be.
122#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
123pub struct TransientBufferDesc {
124    /// Size in bytes.
125    pub size: u64,
126    /// Permitted uses.
127    pub usage: BufferUsage,
128}
129
130/// What the last frame to use a pooled resource left it in.
131///
132/// The source scope of the next frame's first barrier against that resource.
133/// [`ResourceState::Undefined`] with no queue is the honest answer for a
134/// resource no frame has touched yet — nothing has been written, so there is
135/// nothing to order against, which is exactly what `Undefined` means.
136#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
137pub struct TransientUse {
138    /// The state the last access left it in.
139    pub state: ResourceState,
140    /// The queue that access ran on, so a frame that uses the resource from a
141    /// different queue emits the acquire half of a queue-family transfer rather
142    /// than reading memory the other queue never released.
143    pub queue: Option<QueueHandle>,
144}
145
146#[derive(Debug)]
147struct PooledImage {
148    image: ImageHandle,
149    view: ImageViewHandle,
150    /// Consecutive frames this has not been asked for.
151    idle_frames: u32,
152    /// Whether it has already been handed out this frame.
153    taken: bool,
154    /// What the last frame that used it left it in.
155    last: TransientUse,
156}
157
158#[derive(Debug)]
159struct PooledBuffer {
160    buffer: BufferHandle,
161    idle_frames: u32,
162    taken: bool,
163    last: TransientUse,
164}
165
166/// Physical backing for the graph's transients.
167///
168/// Owned by the renderer, not by a graph: a graph lives for one frame and a pool
169/// has to outlive it, or "pool" would mean "allocate every frame".
170#[derive(Debug, Default)]
171pub struct TransientPool {
172    images: HashMap<TransientImageDesc, Vec<PooledImage>>,
173    buffers: HashMap<TransientBufferDesc, Vec<PooledBuffer>>,
174    /// What the last graph left each **imported** image in — the ledger behind
175    /// [`InitialClaim::Tracked`](crate::graph::InitialClaim::Tracked).
176    ///
177    /// The pool does not own these images and never hands one out, so this is
178    /// not pooling: it is the only place that outlives a graph and is already
179    /// threaded through both halves of one, which is what a cross-frame check
180    /// on an import needs. Keyed on the handle rather than on a description
181    /// because an import has no description here — the graph did not create it.
182    ///
183    /// Only tracked imports land here. An
184    /// [`Acquired`](crate::graph::InitialClaim::Acquired) one is never read
185    /// back, and its handles are precisely the ones a resize throws away, so
186    /// recording them would grow a table nothing consults. What remains is an
187    /// entry per long-lived importer-owned image — an atlas, a placeholder —
188    /// and a handle carries a generation, so an entry left by a destroyed image
189    /// can never be read by whatever takes its slot.
190    imported_images: HashMap<ImageHandle, ResourceState>,
191    /// What the last graph left each **imported** buffer in, and the ledger
192    /// [`ImportedBuffer::initial`](crate::graph::ImportedBuffer::initial) is
193    /// checked against.
194    ///
195    /// The image ledger above, one resource kind over, and held for the same
196    /// reasons — it is not pooling, and a handle is the only key an import
197    /// offers. What differs is that every buffer import lands here rather than
198    /// the tracked subset: no buffer in this engine arrives behind an acquire
199    /// semaphore, so there is no buffer the graph has to take a declaration
200    /// from on trust. See [`ImportedBuffer`](crate::graph::ImportedBuffer) for
201    /// why that asymmetry is the resources' and not the check's.
202    imported_buffers: HashMap<BufferHandle, ResourceState>,
203    /// Frames begun. Reported by [`TransientPool::frame_count`]; retirement
204    /// counts idle frames per entry rather than reading this.
205    frames: u64,
206}
207
208impl TransientPool {
209    /// An empty pool.
210    #[must_use]
211    pub fn new() -> Self {
212        Self::default()
213    }
214
215    /// Marks every pooled resource available again.
216    ///
217    /// Called by [`CompiledGraph::execute`](crate::graph::CompiledGraph::execute)
218    /// before it realises anything, so a caller never has to remember to.
219    pub fn begin_frame(&mut self) {
220        self.frames = self.frames.wrapping_add(1);
221        for pooled in self.images.values_mut().flatten() {
222            pooled.taken = false;
223        }
224        for pooled in self.buffers.values_mut().flatten() {
225            pooled.taken = false;
226        }
227    }
228
229    /// An image matching `desc`, creating one only if every match is already in
230    /// use this frame.
231    ///
232    /// # Errors
233    ///
234    /// [`HalError`] from image or view creation.
235    pub fn image(
236        &mut self,
237        device: &dyn Device,
238        desc: TransientImageDesc,
239    ) -> Result<(ImageHandle, ImageViewHandle), HalError> {
240        let entries = self.images.entry(desc).or_default();
241        if let Some(pooled) = entries.iter_mut().find(|pooled| !pooled.taken) {
242            pooled.taken = true;
243            pooled.idle_frames = 0;
244            return Ok((pooled.image, pooled.view));
245        }
246
247        let image = device.create_image(&ImageDesc {
248            label: Some("graph transient"),
249            image_type: ImageType::D2,
250            extent: crcbl_hal::Extent3d::d2(desc.extent.0, desc.extent.1),
251            format: desc.format,
252            mip_levels: desc.mip_levels,
253            samples: desc.samples,
254            usage: desc.usage,
255        })?;
256        let view = match device.create_image_view(&ImageViewDesc {
257            label: Some("graph transient"),
258            image,
259            view_type: ImageViewType::D2,
260            format: desc.format,
261            range: ImageSubresourceRange::all(desc.format),
262        }) {
263            Ok(view) => view,
264            Err(error) => {
265                // Never leak the image on the failure path: it is already the
266                // pool's, and nothing else has a handle to it.
267                device.destroy_image(image);
268                return Err(error);
269            }
270        };
271        crcbl_core::log::debug!(
272            "graph: created a transient {}x{} {:?} image",
273            desc.extent.0,
274            desc.extent.1,
275            desc.format
276        );
277        entries.push(PooledImage {
278            image,
279            view,
280            idle_frames: 0,
281            taken: true,
282            last: TransientUse::default(),
283        });
284        Ok((image, view))
285    }
286
287    /// A buffer matching `desc`, creating one only if every match is already in
288    /// use this frame.
289    ///
290    /// # Errors
291    ///
292    /// [`HalError`] from buffer creation.
293    pub fn buffer(
294        &mut self,
295        device: &dyn Device,
296        desc: TransientBufferDesc,
297    ) -> Result<BufferHandle, HalError> {
298        let entries = self.buffers.entry(desc).or_default();
299        if let Some(pooled) = entries.iter_mut().find(|pooled| !pooled.taken) {
300            pooled.taken = true;
301            pooled.idle_frames = 0;
302            return Ok(pooled.buffer);
303        }
304        let buffer = device.create_buffer(&BufferDesc {
305            label: Some("graph transient"),
306            size: desc.size,
307            usage: desc.usage,
308            memory: MemoryLocation::DeviceLocal,
309        })?;
310        crcbl_core::log::debug!("graph: created a transient {}-byte buffer", desc.size);
311        entries.push(PooledBuffer {
312            buffer,
313            idle_frames: 0,
314            taken: true,
315            last: TransientUse::default(),
316        });
317        Ok(buffer)
318    }
319
320    /// What the last frame left the `ordinal`-th pooled image matching `desc`
321    /// in.
322    ///
323    /// `ordinal` counts within one description, in the order
324    /// [`TransientPool::image`] hands them out — so the *n*-th request for a
325    /// description in a frame is the *n*-th entry here, and a graph that has
326    /// packed its transients onto physical slots can ask about a slot it has not
327    /// realised yet. [`TransientUse::default`] for a description the pool has
328    /// never been asked for, which is the correct answer: there is no resource,
329    /// so nothing has written one.
330    #[must_use]
331    pub fn image_use(&self, desc: TransientImageDesc, ordinal: usize) -> TransientUse {
332        self.images
333            .get(&desc)
334            .and_then(|entries| entries.get(ordinal))
335            .map_or_else(TransientUse::default, |pooled| pooled.last)
336    }
337
338    /// What the last frame left the `ordinal`-th pooled buffer matching `desc`
339    /// in. See [`TransientPool::image_use`].
340    #[must_use]
341    pub fn buffer_use(&self, desc: TransientBufferDesc, ordinal: usize) -> TransientUse {
342        self.buffers
343            .get(&desc)
344            .and_then(|entries| entries.get(ordinal))
345            .map_or_else(TransientUse::default, |pooled| pooled.last)
346    }
347
348    /// What the last graph left the imported image `image` in, if one has.
349    ///
350    /// [`None`] means no graph has executed against this pool with `image`
351    /// declared as
352    /// [`InitialClaim::Tracked`](crate::graph::InitialClaim::Tracked) — so
353    /// there is no claim to contradict, and an importer whose image was put
354    /// into its state by an upload outside the graph is the ordinary way to
355    /// arrive here. [`RenderGraph::compile`](crate::graph::RenderGraph::compile)
356    /// reads it; a test asserts on it to show the ledger is not silently empty,
357    /// which is the difference between this guard checking something and
358    /// checking nothing.
359    #[must_use]
360    pub fn imported_image_use(&self, image: ImageHandle) -> Option<ResourceState> {
361        self.imported_images.get(&image).copied()
362    }
363
364    /// Records what this frame left the imported image `image` in.
365    ///
366    /// Deliberately not public, for the reason
367    /// [`TransientPool::set_image_use`] is not: the only caller that can know
368    /// this is [`CompiledGraph::execute`](crate::graph::CompiledGraph::execute),
369    /// which has just recorded the trailing barrier that reaches the state. A
370    /// caller writing a different one here would not move a barrier — it would
371    /// teach the *check* the wrong answer, and every following frame's honest
372    /// declaration would be rejected.
373    pub(crate) fn set_imported_image_use(&mut self, image: ImageHandle, state: ResourceState) {
374        self.imported_images.insert(image, state);
375    }
376
377    /// What the last graph left the imported buffer `buffer` in, if one has.
378    ///
379    /// [`TransientPool::imported_image_use`]'s answer for a buffer, and [`None`]
380    /// means the same thing: no graph has executed against this pool with
381    /// `buffer` imported, so there is no claim to contradict. A buffer a
382    /// `write_buffer` filled before any frame ran is the ordinary way to arrive
383    /// here.
384    #[must_use]
385    pub fn imported_buffer_use(&self, buffer: BufferHandle) -> Option<ResourceState> {
386        self.imported_buffers.get(&buffer).copied()
387    }
388
389    /// Records what this frame left the imported buffer `buffer` in.
390    ///
391    /// Not public, for [`TransientPool::set_imported_image_use`]'s reason: the
392    /// caller that knows this is the one that has just recorded the trailing
393    /// barrier reaching the state, and any other would be teaching the check a
394    /// wrong answer rather than moving a barrier.
395    pub(crate) fn set_imported_buffer_use(&mut self, buffer: BufferHandle, state: ResourceState) {
396        self.imported_buffers.insert(buffer, state);
397    }
398
399    /// Records what this frame left the `ordinal`-th pooled image in.
400    ///
401    /// Deliberately not public: the only caller that can know this is
402    /// [`CompiledGraph::execute`](crate::graph::CompiledGraph::execute), which
403    /// computed the state at compile time and has just recorded the commands
404    /// that reach it. A caller who wrote a different number here would move
405    /// every following frame's first barrier onto a source scope the GPU never
406    /// visits.
407    pub(crate) fn set_image_use(
408        &mut self,
409        desc: TransientImageDesc,
410        ordinal: usize,
411        last: TransientUse,
412    ) {
413        if let Some(pooled) = self
414            .images
415            .get_mut(&desc)
416            .and_then(|entries| entries.get_mut(ordinal))
417        {
418            pooled.last = last;
419        }
420    }
421
422    /// Records what this frame left the `ordinal`-th pooled buffer in. See
423    /// [`TransientPool::set_image_use`].
424    pub(crate) fn set_buffer_use(
425        &mut self,
426        desc: TransientBufferDesc,
427        ordinal: usize,
428        last: TransientUse,
429    ) {
430        if let Some(pooled) = self
431            .buffers
432            .get_mut(&desc)
433            .and_then(|entries| entries.get_mut(ordinal))
434        {
435            pooled.last = last;
436        }
437    }
438
439    /// Destroys anything that has gone unused for [`RETIRE_AFTER_FRAMES`]
440    /// consecutive frames, and reports how many resources went.
441    ///
442    /// Call once per frame **after** submitting. A resize is the case that makes
443    /// this necessary: it changes the key of every scene target, so without it a
444    /// window dragged across the screen accumulates one image per size it passed
445    /// through.
446    pub fn retire_unused(&mut self, device: &dyn Device) -> usize {
447        let mut retired = 0;
448        self.images.retain(|_, entries| {
449            entries.retain(|pooled| {
450                let keep = pooled.taken || pooled.idle_frames < RETIRE_AFTER_FRAMES;
451                if !keep {
452                    device.destroy_image_view(pooled.view);
453                    device.destroy_image(pooled.image);
454                    retired += 1;
455                }
456                keep
457            });
458            !entries.is_empty()
459        });
460        self.buffers.retain(|_, entries| {
461            entries.retain(|pooled| {
462                let keep = pooled.taken || pooled.idle_frames < RETIRE_AFTER_FRAMES;
463                if !keep {
464                    device.destroy_buffer(pooled.buffer);
465                    retired += 1;
466                }
467                keep
468            });
469            !entries.is_empty()
470        });
471        // Aged *after* the sweep, so a resource is only destroyed on the frame
472        // after it reached the threshold — never on the frame it was last used.
473        for pooled in self.images.values_mut().flatten() {
474            if !pooled.taken {
475                pooled.idle_frames += 1;
476            }
477        }
478        for pooled in self.buffers.values_mut().flatten() {
479            if !pooled.taken {
480                pooled.idle_frames += 1;
481            }
482        }
483        if retired > 0 {
484            crcbl_core::log::debug!("graph: retired {retired} transient(s)");
485        }
486        retired
487    }
488
489    /// How many frames have begun against this pool.
490    #[must_use]
491    pub const fn frame_count(&self) -> u64 {
492        self.frames
493    }
494
495    /// How many physical images the pool is holding.
496    #[must_use]
497    pub fn image_count(&self) -> usize {
498        self.images.values().map(Vec::len).sum()
499    }
500
501    /// How many physical buffers the pool is holding.
502    #[must_use]
503    pub fn buffer_count(&self) -> usize {
504        self.buffers.values().map(Vec::len).sum()
505    }
506
507    /// Destroys everything. Call after the device is idle, at shutdown.
508    pub fn destroy(&mut self, device: &dyn Device) {
509        for pooled in self.images.values().flatten() {
510            device.destroy_image_view(pooled.view);
511            device.destroy_image(pooled.image);
512        }
513        for pooled in self.buffers.values().flatten() {
514            device.destroy_buffer(pooled.buffer);
515        }
516        self.images.clear();
517        self.buffers.clear();
518        // Not resources to destroy — imports belong to their owners — but the
519        // pool is finished, and a ledger outliving it would answer questions
520        // about frames it can no longer be the pool for.
521        self.imported_images.clear();
522        self.imported_buffers.clear();
523    }
524}
525
526// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
527#[cfg(all(test, not(target_arch = "wasm32")))]
528mod tests {
529    use super::*;
530    use crcbl_hal::null::NullInstance;
531    use crcbl_hal::{DeviceDesc, Instance};
532
533    fn device() -> Box<dyn Device> {
534        let instance = NullInstance::gpu_driven();
535        let adapter = instance.adapters().remove(0);
536        instance
537            .create_device(&DeviceDesc::for_adapter(adapter.id))
538            .expect("the null backend always opens")
539    }
540
541    fn scene(extent: (u32, u32)) -> TransientImageDesc {
542        TransientImageDesc {
543            extent,
544            format: Format::Rgba16Float,
545            usage: ImageUsage::COLOR_ATTACHMENT | ImageUsage::SAMPLED,
546            samples: 1,
547            mip_levels: 1,
548        }
549    }
550
551    #[test]
552    fn a_steady_state_frame_creates_nothing_after_the_first() {
553        let device = device();
554        let mut pool = TransientPool::new();
555
556        pool.begin_frame();
557        let first = pool
558            .image(device.as_ref(), scene((64, 48)))
559            .expect("created");
560        assert_eq!(pool.image_count(), 1);
561
562        for _ in 0..8 {
563            pool.begin_frame();
564            let again = pool
565                .image(device.as_ref(), scene((64, 48)))
566                .expect("reused");
567            assert_eq!(again, first, "a steady frame must reuse, not allocate");
568            assert_eq!(pool.image_count(), 1);
569            pool.retire_unused(device.as_ref());
570        }
571        pool.destroy(device.as_ref());
572    }
573
574    /// Two live requests in one frame must not hand back the same image — that
575    /// is the difference between a pool and a cache, and getting it wrong is a
576    /// pass rendering over another pass's output.
577    #[test]
578    fn two_requests_in_one_frame_get_two_images() {
579        let device = device();
580        let mut pool = TransientPool::new();
581        pool.begin_frame();
582        let first = pool
583            .image(device.as_ref(), scene((64, 48)))
584            .expect("created");
585        let second = pool
586            .image(device.as_ref(), scene((64, 48)))
587            .expect("created");
588        assert_ne!(first, second);
589        assert_eq!(pool.image_count(), 2);
590
591        // And the next frame reuses both rather than growing to four.
592        pool.begin_frame();
593        let (a, b) = (
594            pool.image(device.as_ref(), scene((64, 48)))
595                .expect("reused"),
596            pool.image(device.as_ref(), scene((64, 48)))
597                .expect("reused"),
598        );
599        assert_eq!((a, b), (first, second));
600        assert_eq!(pool.image_count(), 2);
601        pool.destroy(device.as_ref());
602    }
603
604    /// Different descriptions are different resources, whatever their size.
605    #[test]
606    fn the_key_is_the_whole_description() {
607        let device = device();
608        let mut pool = TransientPool::new();
609        pool.begin_frame();
610        let color = pool
611            .image(device.as_ref(), scene((64, 48)))
612            .expect("created");
613        let depth = pool
614            .image(
615                device.as_ref(),
616                TransientImageDesc {
617                    extent: (64, 48),
618                    format: Format::D32Float,
619                    usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT,
620                    samples: 1,
621                    mip_levels: 1,
622                },
623            )
624            .expect("created");
625        assert_ne!(color, depth);
626        assert_eq!(pool.image_count(), 2);
627        pool.destroy(device.as_ref());
628    }
629
630    /// A resize must not leak: the old size stops being asked for and is
631    /// eventually destroyed — but not before the frames it might still be in
632    /// have drained.
633    #[test]
634    fn a_resize_retires_the_old_size_after_the_frames_in_flight_have_drained() {
635        let device = device();
636        let mut pool = TransientPool::new();
637
638        pool.begin_frame();
639        pool.image(device.as_ref(), scene((64, 48)))
640            .expect("created");
641        pool.retire_unused(device.as_ref());
642        assert_eq!(pool.image_count(), 1);
643
644        // The resize.
645        for frame in 0..RETIRE_AFTER_FRAMES {
646            pool.begin_frame();
647            pool.image(device.as_ref(), scene((128, 96)))
648                .expect("created");
649            pool.retire_unused(device.as_ref());
650            assert_eq!(
651                pool.image_count(),
652                2,
653                "frame {frame}: the old size must survive until the in-flight \
654                 frames that could still reference it have drained"
655            );
656        }
657
658        pool.begin_frame();
659        pool.image(device.as_ref(), scene((128, 96)))
660            .expect("reused");
661        assert_eq!(pool.retire_unused(device.as_ref()), 1);
662        assert_eq!(pool.image_count(), 1, "the old size is gone");
663        pool.destroy(device.as_ref());
664    }
665
666    /// A resize storm must converge rather than accumulate one image per size
667    /// the window passed through.
668    #[test]
669    fn a_resize_storm_converges() {
670        let device = device();
671        let mut pool = TransientPool::new();
672        for width in 100..160u32 {
673            pool.begin_frame();
674            pool.image(device.as_ref(), scene((width, 96)))
675                .expect("created");
676            pool.retire_unused(device.as_ref());
677            assert!(
678                pool.image_count() <= usize::try_from(RETIRE_AFTER_FRAMES).expect("small") + 1,
679                "at width {width} the pool held {} images",
680                pool.image_count()
681            );
682        }
683        pool.destroy(device.as_ref());
684    }
685
686    #[test]
687    fn buffers_pool_on_the_same_rules() {
688        let device = device();
689        let mut pool = TransientPool::new();
690        let desc = TransientBufferDesc {
691            size: 4096,
692            usage: BufferUsage::STORAGE,
693        };
694        pool.begin_frame();
695        let first = pool.buffer(device.as_ref(), desc).expect("created");
696        assert_eq!(pool.buffer_count(), 1);
697        pool.begin_frame();
698        assert_eq!(pool.buffer(device.as_ref(), desc).expect("reused"), first);
699        assert_eq!(pool.buffer_count(), 1);
700        pool.destroy(device.as_ref());
701        assert_eq!(pool.buffer_count(), 0);
702    }
703
704    #[test]
705    fn destroying_a_transient_pool_releases_every_image_and_buffer_and_can_be_repeated() {
706        let device = device();
707        let mut pool = TransientPool::new();
708        pool.begin_frame();
709        pool.image(device.as_ref(), scene((64, 48)))
710            .expect("created");
711        pool.buffer(
712            device.as_ref(),
713            TransientBufferDesc {
714                size: 256,
715                usage: BufferUsage::STORAGE,
716            },
717        )
718        .expect("created");
719        pool.destroy(device.as_ref());
720        assert_eq!(pool.image_count(), 0);
721        assert_eq!(pool.buffer_count(), 0);
722        // And destroying twice is harmless.
723        pool.destroy(device.as_ref());
724    }
725}