Skip to main content

crcbl_frame/
graph.rs

1//! The render graph: passes declare what they touch, and the graph works out
2//! the barriers.
3//!
4//! ```text
5//! RenderGraph ──add_render_pass()──▶ declarations
6//!      │                                  │
7//!      │  compile()                       │  reads/writes of virtual resources
8//!      ▼                                  ▼
9//! CompiledGraph ──▶ ordered passes + exact barriers + layout transitions
10//!      │                        │
11//!      │  dump()                │  execute(device, pool, encoder)
12//!      ▼                        ▼
13//!   text a human reads    the only code in the engine that calls
14//!                         `CommandEncoder::pipeline_barrier`
15//! ```
16//!
17//! Stage 2 §2.4 states the contract in one sentence:
18//! "passes declare reads/writes of virtual resources; graph compiles to ordered
19//! passes + exact `sync2` barriers + image layout transitions. **No manual
20//! barriers outside the graph, ever.**" The sandbox used to hand-write two image
21//! barriers around its frame; it no longer contains the word.
22//!
23//! # Deliberately not a scheduler
24//!
25//! The same section's risk list says: "**Graph over-engineering.** MVP graph =
26//! linear pass list with computed barriers. No multi-queue scheduling, no
27//! reordering. Resist." So:
28//!
29//! * **Passes execute in declaration order.** There is no topological sort,
30//!   because there is nothing to sort — the order the caller wrote *is* the
31//!   dependency order, and a graph that reordered would have to prove it had not
32//!   changed the picture.
33//! * **No dead-pass culling.** Declaring a pass runs it. Culling is the feature
34//!   that makes a graph unpredictable ("why did my debug pass not run?") in
35//!   exchange for saving work a caller could have simply not declared.
36//! * **No multi-queue scheduling.** Every pass names a queue and the barrier
37//!   model carries [`QueueTransfer`], so a dedicated transfer queue is additive
38//!   later — which stage 2's corrections require "from
39//!   the start so a dedicated transfer queue is additive later rather than a
40//!   barrier-model rewrite". Nothing *decides* to use a second queue.
41//!
42//! What it does do is the part that is genuinely error-prone by hand: track
43//! every resource's state, emit exactly the transitions that are needed, batch
44//! them into one call per pass, alias transients whose lifetimes do not overlap,
45//! and return every imported resource to the state its owner requires.
46//!
47//! # The physical resource outlives the frame
48//!
49//! A graph is built and thrown away every frame. The *images* are not: a
50//! steady-state frame gets the same [`ImageHandle`] out of the
51//! [`TransientPool`] it got last frame, and a graph is aliasing when two of its
52//! virtual images land on one of them. So state tracking is per **physical**
53//! resource — and a physical resource's history does not start at this frame's
54//! first pass.
55//!
56//! Treating it as though it did is a real bug and not a subtle one. A barrier
57//! whose source state is [`ResourceState::Undefined`] carries *no source scope*
58//! at all — on Vulkan it expands to `srcStageMask = NONE, srcAccessMask = NONE`
59//! — so a frame that opens by transitioning its depth buffer from `Undefined`
60//! orders that transition against nothing, while the previous frame's
61//! depth writes to the very same image may still be in flight. Two submissions,
62//! no dependency, both writing: a write-after-write hazard that
63//! `CRCBL_VK_SYNC_VALIDATION=1` reports as `write_barriers: 0`, and that a
64//! driver is free to resolve either way.
65//!
66//! So the graph asks the pool what it left each physical resource in, and the
67//! first barrier that touches one names *that* as its source:
68//!
69//! ```text
70//! frame n-1 ─ forward pass writes depth ─▶ pool remembers DepthStencilWrite
71//!                                                │
72//! frame n   ─ compile(&pool) ────────────────────┘
73//!             first barrier: DepthStencilWrite ──▶ DepthStencilWrite
74//!             (a real source scope, so the two frames are ordered)
75//! ```
76//!
77//! Aliasing *within* a frame is the same story one scale down, and used to have
78//! the same hole: handing a slot from one virtual image to the next does not
79//! change which `VkImage` it is, so the incoming resource's barrier must name
80//! the state the outgoing one left, not `Undefined`. Discarding contents is only
81//! free when there are contents worth discarding — with one handle and one
82//! description there is nothing to discard, and pretending otherwise costs the
83//! source scope that made the two passes ordered.
84//!
85//! **Imported resources are the owner's problem**, deliberately: the graph
86//! cannot know what happened to a swapchain image before it was handed one, so
87//! [`ImportedImage::initial`] is a declaration and the owner is the one who has
88//! to be right. See its docs for what makes `Undefined` correct there.
89//!
90//! It is a declaration the graph *audits*, though, wherever auditing is
91//! possible. An import that says [`InitialClaim::Tracked`] is one its owner
92//! keeps across frames, so the pool remembers what the last graph left it in —
93//! [`ImportedImage::final_state`], which the trailing barrier reaches — and the
94//! next [`RenderGraph::compile`] rejects an `initial` that disagrees. That is
95//! [`GraphError::ImportStateMismatch`], and it is the compile-time form of two
96//! bugs this engine has actually shipped: a readback path and a 1×1 shadow
97//! placeholder, each declaring a state the image was not in on every frame
98//! after the first, and each found only by a validation layer on CI. An
99//! [`InitialClaim::Acquired`] import is
100//! exempt because a semaphore, not a barrier, is what orders it; the variant's
101//! docs say why that is a real exemption rather than an escape hatch.
102//!
103//! **A buffer import is audited the same way and has no exemption at all.**
104//! [`ImportedBuffer::initial`] is the identical declaration about a resource
105//! with no layout, which is what makes getting it wrong worse rather than
106//! milder: a capture of a mislabelled image at least shows the wrong layout,
107//! and a buffer whose barrier lost its source scope looks like nothing until the
108//! numbers it carries are wrong. So every buffer import is checked against the
109//! ledger — [`GraphError::BufferImportStateMismatch`] — and [`ImportedBuffer`]
110//! carries no claim, because nothing hands this engine a buffer from behind a
111//! semaphore the way a swapchain hands it an image.
112//!
113//! # Compilation is pure, and that is what makes it testable
114//!
115//! [`RenderGraph::compile`] takes no device and touches no GPU. It reads the
116//! pool — a plain table of "what was this last used for" — and produces a
117//! [`CompiledGraph`] whose barriers name *virtual* resources; only
118//! [`CompiledGraph::execute`] resolves those to handles. That split is why
119//! `docs/notes/process.md` can call the graph-compile suite a
120//! non-negotiable anchor and have it mean something: the interesting half runs
121//! on any machine, in microseconds, with no ICD in the room — including the
122//! cross-frame half, which needs two `compile` calls against one
123//! [`TransientPool::new`] and no driver at all.
124//!
125//! # The graph explains itself
126//!
127//! [`CompiledGraph::dump`] prints the pass order, every barrier with its from
128//! and to states, and which transients ended up sharing a physical resource.
129//! Stage 2 §2.4 asks for exactly this ("the graph must
130//! be able to explain itself") and makes "graph dump readable and correct for
131//! the sandbox frame" a P1 exit criterion.
132
133use core::fmt;
134
135use crcbl_hal::{
136    Barriers, BufferBarrier, BufferHandle, BufferUsage, ClearValue, ColorAttachment,
137    CommandEncoder, ComputePassDesc, DepthStencilAttachment, Device, Format, HalError, ImageAspect,
138    ImageBarrier, ImageHandle, ImageSubresourceRange, ImageUsage, ImageViewHandle, LoadOp,
139    QueueHandle, QueueTransfer, Rect2d, RenderPassDesc, ResourceState, StoreOp, Viewport, depth,
140};
141
142use crate::timing::PassTimers;
143use crate::transient::{TransientBufferDesc, TransientImageDesc, TransientPool, TransientUse};
144
145/// A virtual image inside one graph.
146///
147/// Only meaningful to the [`RenderGraph`] that issued it. Deliberately not a
148/// [`Handle`](crcbl_core::Handle): a graph is built and thrown away every frame,
149/// so there is no use-after-free to protect against, and a plain index keeps
150/// compilation allocation-free.
151#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
152pub struct ImageId(u32);
153
154/// A virtual buffer inside one graph. See [`ImageId`].
155#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
156pub struct BufferId(u32);
157
158impl ImageId {
159    fn index(self) -> usize {
160        self.0 as usize
161    }
162}
163
164impl BufferId {
165    fn index(self) -> usize {
166        self.0 as usize
167    }
168}
169
170/// What backs an importer's claim about [`ImportedImage::initial`].
171///
172/// `initial` is the one thing in a graph the graph cannot derive, and getting
173/// it wrong is silent: a barrier out of a state the image is not in still
174/// records, still renders, and still passes every golden — it just carries the
175/// wrong source scope, and `Undefined` carries none at all. So the importer has
176/// to say *how it knows*, and that answer decides whether the graph can check
177/// the claim or has to take it.
178///
179/// **Images only, and that is a fact about the resources rather than about the
180/// check.** [`ImportedBuffer::initial`] is the same declaration and is audited
181/// on the same ledger, but it has no counterpart to this enum: [`Acquired`] is
182/// the only reason an import escapes the audit, an acquire is what a swapchain
183/// does, and a swapchain hands out images. Giving a buffer a claim field with
184/// one legal value would be an escape hatch with no case behind it — and the
185/// [`Acquired`] docs below are about how such a hatch is how the check gets
186/// lost.
187///
188/// [`Acquired`]: InitialClaim::Acquired
189#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190pub enum InitialClaim {
191    /// The importer owns this image across frames, so `initial` is checkable.
192    ///
193    /// [`RenderGraph::compile`] looks the image up in the pool's ledger of what
194    /// the last graph *left* each tracked import in, and rejects a declaration
195    /// that disagrees with it — see [`GraphError::ImportStateMismatch`]. A
196    /// handle the ledger has never heard of is accepted: the graph has left it
197    /// in nothing, so there is nothing for the claim to contradict, and an
198    /// image put into `ShaderRead` by an upload outside the graph is the
199    /// ordinary case of that.
200    ///
201    /// The right answer for anything the importer keeps and re-imports — a
202    /// shadow atlas, a 1×1 placeholder, an offscreen target it renders into
203    /// twice. Both of the bugs this check exists to stop were images of exactly
204    /// that kind: one declared [`ResourceState::Undefined`] on a placeholder the
205    /// frame before had left in [`ResourceState::ShaderRead`], which is a
206    /// write-after-read with no source scope; the other named
207    /// [`ResourceState::ColorAttachment`] on an image the graph had already
208    /// returned to [`ResourceState::Present`], which is an illegal old layout.
209    Tracked,
210    /// An acquire semaphore stands between the last use and this frame, so
211    /// there is nothing left for `initial` to order against.
212    ///
213    /// The freshly acquired swapchain image, and only that shape. Its
214    /// [`ResourceState::Undefined`] is not a lie the graph should catch: the
215    /// semaphore the acquire signalled is waited on by the submission that runs
216    /// this graph, so the frame is *already* ordered after everything the
217    /// presentation engine and the previous frame did with the image, and the
218    /// first barrier has no ordering left to carry — only a layout to reach.
219    ///
220    /// Which is also why the graph cannot check one. The image goes back into
221    /// the presentation ring at [`ResourceState::Present`] and the window system
222    /// does what it likes with it; a ledger entry saying what this frame left
223    /// would be a claim about an image the engine no longer controls. So the
224    /// ledger does not record these at all, and nothing reads them.
225    ///
226    /// **Reaching for this to quiet a rejection is how the check gets lost.** A
227    /// tracked image marked `Acquired` opts out of the whole guard and reads as
228    /// verified; if a declaration is refused and there is no acquire in the
229    /// chain, the declaration is what is wrong.
230    Acquired,
231}
232
233/// An image the graph did not create, and does not own.
234///
235/// The swapchain image is the canonical one: it belongs to the swapchain, it
236/// arrives in an undefined layout, and it must leave in
237/// [`ResourceState::Present`]. Saying that once, here, is what removes the
238/// hand-written barriers from every frame loop in the engine.
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240pub struct ImportedImage {
241    /// The image itself.
242    pub image: ImageHandle,
243    /// A view covering what the passes will render into or sample.
244    pub view: ImageViewHandle,
245    /// Texel format, which fixes the subresource aspects a barrier names.
246    pub format: Format,
247    /// Size in pixels, which fixes the render area of any pass that attaches it.
248    pub extent: (u32, u32),
249    /// The state it is in when the graph starts.
250    ///
251    /// [`ResourceState::Undefined`] for a freshly acquired swapchain image —
252    /// which discards its contents, which is free, and which is the only
253    /// correct source for one.
254    ///
255    /// Unlike a transient, this is a **declaration the owner makes**, not
256    /// something the graph can derive: the graph never created this image and
257    /// has no description of it to look up. `Undefined` is right for an
258    /// acquired swapchain image because the acquire's semaphore — waited on by
259    /// the submission that runs this graph — already orders the frame after
260    /// everything the presentation engine and the previous frame did with it,
261    /// so the barrier has no ordering left to carry and only has to reach the
262    /// layout. An importer with no such semaphore in the chain owes the graph
263    /// the truth here instead, or it is asking for the same write-after-write
264    /// the module docs describe.
265    ///
266    /// [`claim`](Self::claim) says which of those two an importer is, and a
267    /// [`InitialClaim::Tracked`] one is checked rather than taken on trust.
268    pub initial: ResourceState,
269    /// How the importer knows [`initial`](Self::initial), and so whether the
270    /// graph checks it. See [`InitialClaim`].
271    pub claim: InitialClaim,
272    /// The state the graph must leave it in.
273    ///
274    /// [`ResourceState::Present`] for a swapchain image. The graph emits a
275    /// trailing barrier if the last pass left it somewhere else, and emits
276    /// nothing if it did not — so this is what the image is in once the frame
277    /// has run either way, which is exactly why it is what the ledger behind
278    /// [`InitialClaim::Tracked`] records.
279    pub final_state: ResourceState,
280}
281
282/// A buffer the graph did not create, and does not own.
283///
284/// The importer-owned per-frame ring is the canonical one: a cull counter, a
285/// light grid, a readback slot. Each belongs to something that keeps it across
286/// frames and hands the same handle back every time its turn comes round, so
287/// what orders this frame's first access is a barrier out of the state the last
288/// frame on that handle left it in — and [`ImportedBuffer::initial`] is where
289/// that state is named.
290///
291/// Unlike [`ImportedImage`] there is no [`InitialClaim`] here, because there is
292/// nothing for one to say. A buffer never arrives from a presentation engine,
293/// so no buffer import in this engine has an acquire semaphore standing between
294/// the last use and this frame; every one of them is a resource whose whole
295/// history is frames of this graph, and every one is therefore checked. See
296/// [`GraphError::BufferImportStateMismatch`].
297#[derive(Clone, Copy, Debug, PartialEq, Eq)]
298pub struct ImportedBuffer {
299    /// The buffer itself.
300    pub buffer: BufferHandle,
301    /// The state it is in when the graph starts.
302    ///
303    /// A **declaration the owner makes**, exactly as
304    /// [`ImportedImage::initial`] is and for the same reason: the graph did not
305    /// create this buffer and has no description of it to look up. The right
306    /// answer is what the last thing to touch it left it in —
307    /// [`final_state`](Self::final_state) on a buffer this graph has run with
308    /// before, and whatever the upload or copy outside the graph did on one it
309    /// has not.
310    ///
311    /// [`ResourceState::Undefined`] is the answer only when nothing has written
312    /// the buffer *at all*: it names no source scope, so a barrier out of it
313    /// orders this frame against nothing, and using it on a buffer another
314    /// frame's dispatch or copy wrote is precisely the write-after-write the
315    /// module docs describe. The graph rejects that rather than believing it,
316    /// on the ledger the previous frame left — see
317    /// [`GraphError::BufferImportStateMismatch`].
318    pub initial: ResourceState,
319    /// The state the graph must leave it in.
320    ///
321    /// The graph emits a trailing barrier if the last pass left it somewhere
322    /// else and emits nothing if it did not, so this is what the buffer is in
323    /// once the frame has run either way — which is why it is what the ledger
324    /// records, and so what the next frame's `initial` has to say.
325    pub final_state: ResourceState,
326}
327
328#[derive(Clone, Copy, Debug)]
329enum ImageSource {
330    Imported(ImportedImage),
331    Transient(TransientImageDesc),
332}
333
334#[derive(Clone, Copy, Debug)]
335enum BufferSource {
336    Imported(ImportedBuffer),
337    Transient(TransientBufferDesc),
338}
339
340#[derive(Clone, Debug)]
341struct ImageNode {
342    label: String,
343    source: ImageSource,
344}
345
346#[derive(Clone, Debug)]
347struct BufferNode {
348    label: String,
349    source: BufferSource,
350}
351
352impl ImageNode {
353    fn format(&self) -> Format {
354        match self.source {
355            ImageSource::Imported(imported) => imported.format,
356            ImageSource::Transient(desc) => desc.format,
357        }
358    }
359
360    fn extent(&self) -> (u32, u32) {
361        match self.source {
362            ImageSource::Imported(imported) => imported.extent,
363            ImageSource::Transient(desc) => desc.extent,
364        }
365    }
366}
367
368/// How a pass attaches an image, if it attaches it at all.
369#[derive(Clone, Copy, Debug, PartialEq)]
370pub enum Attachment {
371    /// A colour attachment at `index` in shader output order.
372    Color {
373        /// Output slot.
374        index: u32,
375        /// Start-of-pass behaviour.
376        load: LoadOp,
377        /// End-of-pass behaviour.
378        store: StoreOp,
379        /// Used when `load` is [`LoadOp::Clear`].
380        clear: ClearValue,
381    },
382    /// The depth/stencil attachment.
383    Depth {
384        /// Start-of-pass behaviour.
385        load: LoadOp,
386        /// End-of-pass behaviour.
387        store: StoreOp,
388        /// Used when `load` is [`LoadOp::Clear`]. Defaults to the reversed-Z far
389        /// plane; see [`crcbl_hal::depth`].
390        clear: ClearValue,
391        /// Whether the pass writes depth. `false` is a pass drawing against an
392        /// existing prepass, and is the difference between
393        /// [`ResourceState::DepthStencilWrite`] and
394        /// [`ResourceState::DepthStencilRead`].
395        write: bool,
396    },
397}
398
399#[derive(Clone, Copy, Debug)]
400struct ImageAccess {
401    image: ImageId,
402    state: ResourceState,
403    attachment: Option<Attachment>,
404    /// The sub-resource range this access covers. `None` means the whole image
405    /// (every mip, every layer), resolved at execute time from the image's format.
406    /// Passes that only touch one mip or one layer declare `Some`; the graph then
407    /// emits barriers scoped to just that range rather than the full resource.
408    range: Option<ImageSubresourceRange>,
409}
410
411#[derive(Clone, Copy, Debug)]
412struct BufferAccess {
413    buffer: BufferId,
414    state: ResourceState,
415}
416
417/// Which scope a pass opens.
418#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
419pub enum PassKind {
420    /// A render pass, with attachments.
421    Render,
422    /// A compute pass, with none.
423    Compute,
424    /// A copy, which opens **no** scope at all.
425    ///
426    /// The seam's rule is that "copies, barriers and query writes are legal only
427    /// *outside* any pass", so a body that copies cannot run inside either of
428    /// the other two. The graph still computes this pass's barriers and orders
429    /// it against its neighbours exactly as it does for them — the only
430    /// difference is that [`CompiledGraph::execute`] opens nothing around the
431    /// body.
432    Copy,
433}
434
435impl PassKind {
436    /// What this kind is called in the graph dump and in errors.
437    #[must_use]
438    pub const fn name(self) -> &'static str {
439        match self {
440            Self::Render => "render",
441            Self::Compute => "compute",
442            Self::Copy => "copy",
443        }
444    }
445}
446
447type PassBody<'a> = Box<dyn FnOnce(&mut PassContext<'_>) + 'a>;
448
449struct Pass<'a> {
450    label: String,
451    kind: PassKind,
452    queue: QueueHandle,
453    images: Vec<ImageAccess>,
454    buffers: Vec<BufferAccess>,
455    body: PassBody<'a>,
456}
457
458impl fmt::Debug for Pass<'_> {
459    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460        f.debug_struct("Pass")
461            .field("label", &self.label)
462            .field("kind", &self.kind)
463            .field("images", &self.images)
464            .field("buffers", &self.buffers)
465            .finish_non_exhaustive()
466    }
467}
468
469/// A frame's worth of passes, before compilation.
470///
471/// Built fresh every frame. The lifetime is the passes' closures': they borrow
472/// whatever persistent state the renderer holds, and the graph never outlives a
473/// frame, so nothing has to be cloned into them.
474pub struct RenderGraph<'a> {
475    images: Vec<ImageNode>,
476    buffers: Vec<BufferNode>,
477    passes: Vec<Pass<'a>>,
478    default_queue: QueueHandle,
479    /// The first import that disagreed with an earlier import of the same
480    /// handle, held until [`RenderGraph::compile`] can return it.
481    ///
482    /// Recorded where it happens because that is the only place both
483    /// declarations are in hand, and answered from `compile` because that is
484    /// where this file reports a graph it will not execute — the importer's
485    /// signature says `ImageId`, not `Result<ImageId, _>`, and the subsystem
486    /// that imports second is rarely the one that can decide who is right. The
487    /// first conflict only: the rest of validation names one problem and stops.
488    import_conflict: Option<GraphError>,
489}
490
491impl fmt::Debug for RenderGraph<'_> {
492    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493        f.debug_struct("RenderGraph")
494            .field("images", &self.images)
495            .field("buffers", &self.buffers)
496            .field("passes", &self.passes)
497            .field("import_conflict", &self.import_conflict)
498            .finish()
499    }
500}
501
502impl<'a> RenderGraph<'a> {
503    /// An empty graph whose passes default to `queue`.
504    #[must_use]
505    pub fn new(queue: QueueHandle) -> Self {
506        Self {
507            images: Vec::new(),
508            buffers: Vec::new(),
509            passes: Vec::new(),
510            default_queue: queue,
511            import_conflict: None,
512        }
513    }
514
515    /// Declares an image the graph owns for the duration of the frame.
516    ///
517    /// Backed by the [`TransientPool`], and **aliased** with any other transient
518    /// of the same description whose lifetime does not overlap this one.
519    pub fn create_image(&mut self, label: impl Into<String>, desc: TransientImageDesc) -> ImageId {
520        let id = ImageId(u32::try_from(self.images.len()).expect("a frame has few resources"));
521        self.images.push(ImageNode {
522            label: label.into(),
523            source: ImageSource::Transient(desc),
524        });
525        id
526    }
527
528    /// Declares a buffer the graph owns for the duration of the frame.
529    pub fn create_buffer(
530        &mut self,
531        label: impl Into<String>,
532        desc: TransientBufferDesc,
533    ) -> BufferId {
534        let id = BufferId(u32::try_from(self.buffers.len()).expect("a frame has few resources"));
535        self.buffers.push(BufferNode {
536            label: label.into(),
537            source: BufferSource::Transient(desc),
538        });
539        id
540    }
541
542    /// Brings an externally owned image into the graph.
543    ///
544    /// **One handle is one node.** Importing an image this graph already has
545    /// returns the id already issued for it rather than a second one, and that
546    /// is what makes two subsystems importing the same target — the base-colour
547    /// page a monitor feeds and a forward pass binds, an offscreen target two
548    /// renderers both draw into — the ordinary case it looks like. Two ids on
549    /// one image would carry *independent* state trackers, each starting from
550    /// its own declared [`initial`](ImportedImage::initial), so the graph would
551    /// see nothing to order between a write through one and a read through the
552    /// other and emit no barrier at all.
553    ///
554    /// The node keeps the **first** label. A later import naming it differently
555    /// is not an error — subsystems name the same image for their own reasons —
556    /// but every barrier record and [`CompiledGraph::dump`] line already names
557    /// it, and a label that depended on which subsystem imported last would
558    /// make the dump move under a caller reordering two unrelated imports.
559    ///
560    /// A repeat import whose declaration *disagrees* with the first is refused:
561    /// see [`GraphError::ImportDeclarationConflict`], which
562    /// [`compile`](Self::compile) returns.
563    pub fn import_image(&mut self, label: impl Into<String>, imported: ImportedImage) -> ImageId {
564        // A linear scan rather than a map from handle to id: a frame has few
565        // resources — the same assumption the id conversion below makes — and a
566        // second structure to keep in step with `images` buys nothing at this
567        // size.
568        let existing = self
569            .images
570            .iter()
571            .enumerate()
572            .find_map(|(index, node)| match node.source {
573                ImageSource::Imported(existing) if existing.image == imported.image => {
574                    Some((index, existing))
575                }
576                _ => None,
577            });
578        if let Some((index, first)) = existing {
579            if let Some((field, first, second)) = image_import_conflict(&first, &imported) {
580                self.record_import_conflict(GraphError::ImportDeclarationConflict {
581                    resource: self.images[index].label.clone(),
582                    field,
583                    first,
584                    second,
585                });
586            }
587            return ImageId(u32::try_from(index).expect("a frame has few resources"));
588        }
589        let id = ImageId(u32::try_from(self.images.len()).expect("a frame has few resources"));
590        self.images.push(ImageNode {
591            label: label.into(),
592            source: ImageSource::Imported(imported),
593        });
594        id
595    }
596
597    /// Brings an externally owned buffer into the graph.
598    ///
599    /// One handle is one node, exactly as [`import_image`](Self::import_image)
600    /// describes and for the same reason — a second id would be a second state
601    /// tracker, and a buffer written through one id and read through the other
602    /// would be a read-after-write the graph never barriered. The first label
603    /// wins, and a repeat import that disagrees is
604    /// [`GraphError::BufferImportDeclarationConflict`].
605    pub fn import_buffer(
606        &mut self,
607        label: impl Into<String>,
608        imported: ImportedBuffer,
609    ) -> BufferId {
610        let existing =
611            self.buffers
612                .iter()
613                .enumerate()
614                .find_map(|(index, node)| match node.source {
615                    BufferSource::Imported(existing) if existing.buffer == imported.buffer => {
616                        Some((index, existing))
617                    }
618                    _ => None,
619                });
620        if let Some((index, first)) = existing {
621            if let Some((field, first, second)) = buffer_import_conflict(&first, &imported) {
622                self.record_import_conflict(GraphError::BufferImportDeclarationConflict {
623                    resource: self.buffers[index].label.clone(),
624                    field,
625                    first,
626                    second,
627                });
628            }
629            return BufferId(u32::try_from(index).expect("a frame has few resources"));
630        }
631        let id = BufferId(u32::try_from(self.buffers.len()).expect("a frame has few resources"));
632        self.buffers.push(BufferNode {
633            label: label.into(),
634            source: BufferSource::Imported(imported),
635        });
636        id
637    }
638
639    /// Keeps the first conflicting import for [`compile`](Self::compile) to
640    /// return. Later ones are dropped: the graph is already refused, and the
641    /// second declaration has to come back past `compile` once it is fixed.
642    fn record_import_conflict(&mut self, error: GraphError) {
643        if self.import_conflict.is_none() {
644            self.import_conflict = Some(error);
645        }
646    }
647
648    /// Starts declaring a render pass. Add it with
649    /// [`PassBuilder::execute`].
650    pub fn add_render_pass(&mut self, label: impl Into<String>) -> PassBuilder<'_, 'a> {
651        PassBuilder::new(self, PassKind::Render, label.into())
652    }
653
654    /// Starts declaring a compute pass. Add it with
655    /// [`PassBuilder::execute`].
656    pub fn add_compute_pass(&mut self, label: impl Into<String>) -> PassBuilder<'_, 'a> {
657        PassBuilder::new(self, PassKind::Compute, label.into())
658    }
659
660    /// Starts declaring a copy. Add it with [`PassBuilder::execute`].
661    ///
662    /// **The one way a copy happens inside a frame.** The seam only allows a
663    /// copy outside a pass scope, so a body that calls
664    /// [`copy_buffer_to_buffer`](CommandEncoder::copy_buffer_to_buffer) from a
665    /// render or compute pass is a scope violation the null backend records —
666    /// which is why this is a kind of its own rather than a convention about
667    /// what a compute body may do.
668    ///
669    /// It is otherwise an ordinary pass: it declares what it reads in
670    /// [`ResourceState::TransferSrc`] and what it writes in
671    /// [`ResourceState::TransferDst`], and the graph emits the transitions
672    /// around it.
673    ///
674    /// **Declare the destination too**, even when it is a
675    /// [`MemoryLocation::HostReadback`](crcbl_hal::MemoryLocation::HostReadback)
676    /// staging buffer no pass can bind and nothing else in the frame touches.
677    /// A destination the graph does not know about gets no barrier, and the
678    /// access it needs ordering against is not in this frame at all: it is the
679    /// *previous* write to the same buffer, one turn of a ring ago, in another
680    /// submission. That is a write-after-write with `write_barriers: 0`, and it
681    /// is the bug `crcbl_render::cull_stats` shipped and this sentence exists to stop
682    /// repeating — import it with what the last frame left it in, exactly as
683    /// every other cross-frame resource here is imported.
684    pub fn add_copy_pass(&mut self, label: impl Into<String>) -> PassBuilder<'_, 'a> {
685        PassBuilder::new(self, PassKind::Copy, label.into())
686    }
687
688    /// How many passes have been declared.
689    #[must_use]
690    pub fn pass_count(&self) -> usize {
691        self.passes.len()
692    }
693
694    /// What this graph knows about `image` before anything is realised: its
695    /// format, its extent, and — for a transient only — the usage it will be
696    /// created with. `None` for an id this graph never issued.
697    ///
698    /// For a pass that has to refuse a source *when it is declared* rather than
699    /// let the device refuse the copy at execution:
700    /// `crcbl_render::sprite_pass`'s atlas copies check a rendered image against the
701    /// slot it is copied into here. An import carries no usage, so the second
702    /// half of the answer is the importer's to have got right.
703    #[must_use]
704    pub fn image_facts(&self, image: ImageId) -> Option<(Format, (u32, u32), Option<ImageUsage>)> {
705        let node = self.images.get(image.index())?;
706        let usage = match node.source {
707            ImageSource::Imported(_) => None,
708            ImageSource::Transient(desc) => Some(desc.usage),
709        };
710        Some((node.format(), node.extent(), usage))
711    }
712
713    /// Turns declarations into an ordered pass list with exact barriers.
714    ///
715    /// Pure: no device, no allocation of GPU memory, no side effects. See the
716    /// module docs for why that split exists.
717    ///
718    /// `pool` is read, never touched: it is the same [`TransientPool`]
719    /// [`CompiledGraph::execute`] will realise against, and the only thing
720    /// asked of it is what it left each physical transient in last frame. That
721    /// is what lets the first barrier of a frame carry a source scope covering
722    /// the *previous* frame's writes rather than `Undefined`, which covers
723    /// nothing — see the module docs. Passing a pool the graph will not execute
724    /// against is the one way to get this wrong, which is why the parameter is
725    /// the pool itself rather than a detachable snapshot of it.
726    ///
727    /// # Errors
728    ///
729    /// [`GraphError`] for a graph that cannot be executed as written —
730    /// conflicting accesses within one pass, a render pass with no attachments
731    /// or with attachments of different sizes, a transient nothing uses, or two
732    /// imports of one handle that disagree about what they imported.
733    pub fn compile(self, pool: &TransientPool) -> Result<CompiledGraph<'a>, GraphError> {
734        compile(self, pool)
735    }
736}
737
738/// Declares one pass. `#[must_use]` because a builder that is dropped rather
739/// than [`executed`](PassBuilder::execute) adds nothing to the graph, and a
740/// silently missing pass is a long afternoon.
741#[must_use = "a pass reaches the graph only through `execute`"]
742pub struct PassBuilder<'g, 'a> {
743    graph: &'g mut RenderGraph<'a>,
744    kind: PassKind,
745    label: String,
746    queue: QueueHandle,
747    images: Vec<ImageAccess>,
748    buffers: Vec<BufferAccess>,
749    next_color: u32,
750}
751
752impl fmt::Debug for PassBuilder<'_, '_> {
753    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
754        f.debug_struct("PassBuilder")
755            .field("label", &self.label)
756            .field("kind", &self.kind)
757            .finish_non_exhaustive()
758    }
759}
760
761impl<'g, 'a> PassBuilder<'g, 'a> {
762    fn new(graph: &'g mut RenderGraph<'a>, kind: PassKind, label: String) -> Self {
763        let queue = graph.default_queue;
764        Self {
765            graph,
766            kind,
767            label,
768            queue,
769            images: Vec::new(),
770            buffers: Vec::new(),
771            next_color: 0,
772        }
773    }
774
775    /// Runs this pass on a queue other than the graph's default.
776    ///
777    /// Nothing in the MVP does — uploads share the graphics+compute queue, as
778    /// stage 2's corrections state rather than assume.
779    /// It exists because the *barrier model* has to represent queue-family
780    /// acquire/release from the start, and it does: a resource whose last user
781    /// was on another queue gets a release/acquire pair rather than a plain
782    /// transition.
783    pub fn on_queue(mut self, queue: QueueHandle) -> Self {
784        self.queue = queue;
785        self
786    }
787
788    /// Attaches `image` as the next colour attachment.
789    pub fn color(
790        mut self,
791        image: ImageId,
792        load: LoadOp,
793        store: StoreOp,
794        clear: ClearValue,
795    ) -> Self {
796        let index = self.next_color;
797        self.next_color += 1;
798        self.images.push(ImageAccess {
799            image,
800            state: ResourceState::ColorAttachment,
801            attachment: Some(Attachment::Color {
802                index,
803                load,
804                store,
805                clear,
806            }),
807            range: None,
808        });
809        self
810    }
811
812    /// Attaches `image` as the next colour attachment, cleared to `rgba` and
813    /// stored.
814    pub fn clear_color(self, image: ImageId, rgba: [f32; 4]) -> Self {
815        self.color(
816            image,
817            LoadOp::Clear,
818            StoreOp::Store,
819            ClearValue::color(rgba),
820        )
821    }
822
823    /// Attaches `image` as the depth attachment with depth writes on.
824    pub fn depth(
825        mut self,
826        image: ImageId,
827        load: LoadOp,
828        store: StoreOp,
829        clear: ClearValue,
830    ) -> Self {
831        self.images.push(ImageAccess {
832            image,
833            state: ResourceState::DepthStencilWrite,
834            attachment: Some(Attachment::Depth {
835                load,
836                store,
837                clear,
838                write: true,
839            }),
840            range: None,
841        });
842        self
843    }
844
845    /// Attaches `image` as the depth attachment, cleared to the **reversed-Z**
846    /// far plane and discarded at the end of the pass.
847    ///
848    /// [`depth::CLEAR`] rather than a literal, and discarded rather than stored
849    /// because nothing reads a depth buffer after the pass that wrote it until
850    /// there is a prepass to read — at which point [`PassBuilder::depth`] takes
851    /// a [`StoreOp`] and says so.
852    pub fn clear_depth(self, image: ImageId) -> Self {
853        self.depth(
854            image,
855            LoadOp::Clear,
856            StoreOp::Discard,
857            ClearValue {
858                depth: depth::CLEAR,
859                ..ClearValue::default()
860            },
861        )
862    }
863
864    /// Attaches `image` as a **read-only** depth attachment: tested, not
865    /// written.
866    pub fn depth_read(mut self, image: ImageId) -> Self {
867        self.images.push(ImageAccess {
868            image,
869            state: ResourceState::DepthStencilRead,
870            attachment: Some(Attachment::Depth {
871                load: LoadOp::Load,
872                store: StoreOp::Store,
873                clear: ClearValue::default(),
874                write: false,
875            }),
876            range: None,
877        });
878        self
879    }
880
881    /// Declares that this pass samples or otherwise shader-reads `image`.
882    pub fn read_image(self, image: ImageId) -> Self {
883        self.use_image(image, ResourceState::ShaderRead)
884    }
885
886    /// Declares that this pass samples or otherwise shader-reads `image`,
887    /// but only within the given sub-resource `range` (one mip, one layer,
888    /// etc.). The barrier emitted will cover only that range.
889    pub fn read_subresource(self, image: ImageId, range: ImageSubresourceRange) -> Self {
890        self.use_subresource(image, ResourceState::ShaderRead, range)
891    }
892
893    /// Declares an image access in an arbitrary state — a storage-image write, a
894    /// copy destination, anything the named helpers do not cover.
895    pub fn use_image(mut self, image: ImageId, state: ResourceState) -> Self {
896        self.images.push(ImageAccess {
897            image,
898            state,
899            attachment: None,
900            range: None,
901        });
902        self
903    }
904
905    /// Declares an image access confined to a specific sub-resource range.
906    ///
907    /// The graph emits a barrier scoped to `range` rather than the whole image.
908    /// Passes that read one mip and write another on the same image declare
909    /// disjoint ranges; the graph still tracks one whole-image state (emitting
910    /// conservative barriers when ranges differ), which is correct for the
911    /// linear pass model.
912    pub fn use_subresource(
913        mut self,
914        image: ImageId,
915        state: ResourceState,
916        range: ImageSubresourceRange,
917    ) -> Self {
918        self.images.push(ImageAccess {
919            image,
920            state,
921            attachment: None,
922            range: Some(range),
923        });
924        self
925    }
926
927    /// Declares that this pass shader-reads `buffer` — a uniform block, a
928    /// pulled vertex stream, an instance array.
929    pub fn read_buffer(self, buffer: BufferId) -> Self {
930        self.use_buffer(buffer, ResourceState::ShaderRead)
931    }
932
933    /// Declares that this pass reads `buffer` as an index buffer.
934    pub fn index_buffer(self, buffer: BufferId) -> Self {
935        self.use_buffer(buffer, ResourceState::IndexBuffer)
936    }
937
938    /// Declares a buffer access in an arbitrary state.
939    pub fn use_buffer(mut self, buffer: BufferId, state: ResourceState) -> Self {
940        self.buffers.push(BufferAccess { buffer, state });
941        self
942    }
943
944    /// Adds the pass to the graph, with `body` as the recording callback.
945    ///
946    /// `body` runs inside the pass scope: the graph has already emitted the
947    /// barriers, opened the pass and set a full-target viewport and scissor, so
948    /// a body is normally a pipeline bind, a bind group and a draw. A
949    /// [`PassKind::Copy`] body runs outside every scope instead — see
950    /// [`RenderGraph::add_copy_pass`].
951    pub fn execute(self, body: impl FnOnce(&mut PassContext<'_>) + 'a) {
952        self.graph.passes.push(Pass {
953            label: self.label,
954            kind: self.kind,
955            queue: self.queue,
956            images: self.images,
957            buffers: self.buffers,
958            body: Box::new(body),
959        });
960    }
961}
962
963// --- compiled form ---------------------------------------------------------
964
965/// A barrier the graph computed, in terms of a virtual image.
966#[derive(Clone, Copy, Debug, PartialEq, Eq)]
967pub struct GraphImageBarrier {
968    /// Image transitioned.
969    pub image: ImageId,
970    /// State being left.
971    pub from: ResourceState,
972    /// State being entered.
973    pub to: ResourceState,
974    /// Queue ownership transfer, when the previous user was on another queue.
975    pub queue_transfer: Option<QueueTransfer>,
976    /// Sub-resource range this barrier covers. `None` means the whole image,
977    /// resolved at execute time from the image's format.
978    pub range: Option<ImageSubresourceRange>,
979}
980
981/// A barrier the graph computed, in terms of a virtual buffer.
982#[derive(Clone, Copy, Debug, PartialEq, Eq)]
983pub struct GraphBufferBarrier {
984    /// Buffer transitioned.
985    pub buffer: BufferId,
986    /// State being left.
987    pub from: ResourceState,
988    /// State being entered.
989    pub to: ResourceState,
990    /// Queue ownership transfer, when the previous user was on another queue.
991    pub queue_transfer: Option<QueueTransfer>,
992}
993
994/// One batch of barriers, emitted as a single
995/// [`pipeline_barrier`](CommandEncoder::pipeline_barrier) call.
996#[derive(Clone, Debug, Default, PartialEq, Eq)]
997pub struct GraphBarriers {
998    /// Image transitions, in declaration order.
999    pub images: Vec<GraphImageBarrier>,
1000    /// Buffer transitions, in declaration order.
1001    pub buffers: Vec<GraphBufferBarrier>,
1002}
1003
1004impl GraphBarriers {
1005    /// Whether this batch would do nothing, in which case the graph emits no
1006    /// call at all.
1007    #[must_use]
1008    pub fn is_empty(&self) -> bool {
1009        self.images.is_empty() && self.buffers.is_empty()
1010    }
1011
1012    /// How many transitions it carries.
1013    #[must_use]
1014    pub fn len(&self) -> usize {
1015        self.images.len() + self.buffers.len()
1016    }
1017}
1018
1019/// One pass, after compilation.
1020pub struct CompiledPass<'a> {
1021    label: String,
1022    kind: PassKind,
1023    queue: QueueHandle,
1024    /// Barriers emitted **before** this pass opens.
1025    barriers: GraphBarriers,
1026    /// Barriers emitted **after** this pass closes: the release half of a
1027    /// queue-ownership transfer whose acquire a later pass records. Empty in
1028    /// every single-queue frame, which is every frame the MVP runs.
1029    release_barriers: GraphBarriers,
1030    images: Vec<ImageAccess>,
1031    buffers: Vec<BufferAccess>,
1032    render_area: Rect2d,
1033    body: PassBody<'a>,
1034}
1035
1036impl fmt::Debug for CompiledPass<'_> {
1037    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1038        f.debug_struct("CompiledPass")
1039            .field("label", &self.label)
1040            .field("kind", &self.kind)
1041            .field("barriers", &self.barriers)
1042            .finish_non_exhaustive()
1043    }
1044}
1045
1046impl CompiledPass<'_> {
1047    /// The pass's name, as it appears in captures and in the dump.
1048    #[must_use]
1049    pub fn label(&self) -> &str {
1050        &self.label
1051    }
1052
1053    /// Whether it is a render or a compute pass.
1054    #[must_use]
1055    pub const fn kind(&self) -> PassKind {
1056        self.kind
1057    }
1058
1059    /// The barriers emitted immediately before it.
1060    #[must_use]
1061    pub const fn barriers(&self) -> &GraphBarriers {
1062        &self.barriers
1063    }
1064
1065    /// The barriers emitted immediately after it — the release half of any
1066    /// queue-ownership transfer a later pass acquires. See
1067    /// [`crcbl_hal::QueueTransfer`] on why a transfer is two barriers.
1068    #[must_use]
1069    pub const fn release_barriers(&self) -> &GraphBarriers {
1070        &self.release_barriers
1071    }
1072
1073    /// The queue it was declared on.
1074    ///
1075    /// Always the graph's default in the MVP — uploads share the
1076    /// graphics+compute queue — but the field is what makes a second queue
1077    /// additive rather than a barrier-model rewrite, which
1078    /// stage 2's corrections require from the start.
1079    #[must_use]
1080    pub const fn queue(&self) -> QueueHandle {
1081        self.queue
1082    }
1083
1084    /// The region a render pass covers. Zero-sized for a compute pass.
1085    #[must_use]
1086    pub const fn render_area(&self) -> Rect2d {
1087        self.render_area
1088    }
1089
1090    /// Whether it declared a read of `buffer`.
1091    ///
1092    /// Compilation walks passes in declaration order and never reorders them,
1093    /// so a pass that omits the declaration still runs after the barrier the
1094    /// first reader earned — the omission is invisible in the compiled
1095    /// barriers. This is what lets a test assert the declaration itself.
1096    #[must_use]
1097    pub fn reads_buffer(&self, buffer: BufferId) -> bool {
1098        self.buffers
1099            .iter()
1100            .any(|access| access.buffer == buffer && access.state == ResourceState::ShaderRead)
1101    }
1102}
1103
1104/// Which physical resource a virtual one ended up on.
1105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1106enum Slot {
1107    /// Externally owned; no pool involvement.
1108    Imported,
1109    /// Index into the compiled graph's transient slot list.
1110    Transient(usize),
1111}
1112
1113/// A compiled graph: ordered passes, exact barriers, and a transient plan.
1114pub struct CompiledGraph<'a> {
1115    images: Vec<ImageNode>,
1116    buffers: Vec<BufferNode>,
1117    passes: Vec<CompiledPass<'a>>,
1118    /// Barriers returning imported resources to their required final states.
1119    final_barriers: GraphBarriers,
1120    image_slots: Vec<Slot>,
1121    buffer_slots: Vec<Slot>,
1122    transient_images: Vec<TransientImageDesc>,
1123    transient_buffers: Vec<TransientBufferDesc>,
1124    /// What this frame leaves each physical transient image in, parallel to
1125    /// `transient_images`. Handed to the pool by
1126    /// [`CompiledGraph::execute`] so the *next* frame's first barrier has a
1127    /// source scope; computed here because compilation is what knows it.
1128    transient_image_end: Vec<TransientUse>,
1129    /// The same for buffers.
1130    transient_buffer_end: Vec<TransientUse>,
1131    /// What this frame leaves each [`InitialClaim::Tracked`] import in, which
1132    /// is [`ImportedImage::final_state`] because the trailing barrier is what
1133    /// reaches it. Handed to the pool by [`CompiledGraph::execute`], where the
1134    /// next frame's [`RenderGraph::compile`] checks a declaration against it.
1135    imported_image_end: Vec<(ImageHandle, ResourceState)>,
1136    /// The same for every imported buffer, which is all of them: a buffer
1137    /// import has no [`InitialClaim::Acquired`] counterpart to leave out.
1138    imported_buffer_end: Vec<(BufferHandle, ResourceState)>,
1139}
1140
1141impl fmt::Debug for CompiledGraph<'_> {
1142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1143        f.debug_struct("CompiledGraph")
1144            .field("passes", &self.passes)
1145            .field("final_barriers", &self.final_barriers)
1146            .field("transient_images", &self.transient_images)
1147            .field("transient_buffers", &self.transient_buffers)
1148            .finish_non_exhaustive()
1149    }
1150}
1151
1152impl<'a> CompiledGraph<'a> {
1153    /// The compiled passes, in execution order.
1154    #[must_use]
1155    pub fn passes(&self) -> &[CompiledPass<'a>] {
1156        &self.passes
1157    }
1158
1159    /// The barriers emitted after the last pass, returning imported resources to
1160    /// the states their owners require.
1161    #[must_use]
1162    pub const fn final_barriers(&self) -> &GraphBarriers {
1163        &self.final_barriers
1164    }
1165
1166    /// How many physical images the transients were packed onto.
1167    ///
1168    /// Lower than the number of transients declared exactly when aliasing
1169    /// happened, which is what makes the saving assertable.
1170    #[must_use]
1171    pub fn physical_image_count(&self) -> usize {
1172        self.transient_images.len()
1173    }
1174
1175    /// How many physical buffers the transients were packed onto.
1176    #[must_use]
1177    pub fn physical_buffer_count(&self) -> usize {
1178        self.transient_buffers.len()
1179    }
1180
1181    /// Whether two virtual images share one physical image.
1182    #[must_use]
1183    pub fn images_alias(&self, first: ImageId, second: ImageId) -> bool {
1184        matches!(
1185            (
1186                self.image_slots.get(first.index()),
1187                self.image_slots.get(second.index())
1188            ),
1189            (Some(Slot::Transient(a)), Some(Slot::Transient(b))) if a == b
1190        )
1191    }
1192
1193    /// Every barrier the frame will emit, batch by batch, ending with the final
1194    /// batch. The shape a test asserts on.
1195    #[must_use]
1196    pub fn barrier_batches(&self) -> Vec<&GraphBarriers> {
1197        self.passes
1198            .iter()
1199            .flat_map(|pass| [&pass.barriers, &pass.release_barriers])
1200            .chain(core::iter::once(&self.final_barriers))
1201            .filter(|batch| !batch.is_empty())
1202            .collect()
1203    }
1204
1205    /// The graph, as text a human reads.
1206    ///
1207    /// Stage 2 §2.4's debug-tools principle: "the graph
1208    /// must be able to explain itself", and its exit criteria require the dump
1209    /// to be "readable and correct for the sandbox frame". Every line is derived
1210    /// from the compiled form rather than re-walked from the declarations, so a
1211    /// dump that says a barrier happened is evidence that it will.
1212    #[must_use]
1213    pub fn dump(&self) -> String {
1214        let mut out = String::new();
1215        self.write_dump(&mut out).expect("writing to a String");
1216        out
1217    }
1218
1219    fn write_dump(&self, out: &mut impl fmt::Write) -> fmt::Result {
1220        let aliased = self
1221            .image_slots
1222            .iter()
1223            .filter(|slot| matches!(slot, Slot::Transient(_)))
1224            .count()
1225            .saturating_sub(self.transient_images.len());
1226        writeln!(
1227            out,
1228            "render graph: {} pass(es), {} transient image(s) on {} physical, \
1229             {} transient buffer(s) on {} physical, {} barrier(s)",
1230            self.passes.len(),
1231            self.transient_image_users(),
1232            self.transient_images.len(),
1233            self.transient_buffer_users(),
1234            self.transient_buffers.len(),
1235            self.passes
1236                .iter()
1237                .map(|pass| pass.barriers.len() + pass.release_barriers.len())
1238                .sum::<usize>()
1239                + self.final_barriers.len(),
1240        )?;
1241        if aliased > 0 {
1242            writeln!(out, "  aliasing saved {aliased} physical image(s)")?;
1243        }
1244
1245        for (index, pass) in self.passes.iter().enumerate() {
1246            self.write_barriers(out, &pass.barriers, &format!("[{index}] "))?;
1247            writeln!(
1248                out,
1249                "[{index}] {} pass {:?}  {}x{}",
1250                pass.kind.name(),
1251                pass.label,
1252                pass.render_area.width,
1253                pass.render_area.height
1254            )?;
1255            for access in &pass.images {
1256                let node = &self.images[access.image.index()];
1257                let role = match access.attachment {
1258                    Some(Attachment::Color {
1259                        index, load, store, ..
1260                    }) => {
1261                        format!("color[{index}] load={load:?} store={store:?}")
1262                    }
1263                    Some(Attachment::Depth {
1264                        load, store, write, ..
1265                    }) => format!(
1266                        "depth load={load:?} store={store:?} write={}",
1267                        if write { "yes" } else { "no" }
1268                    ),
1269                    None => "sampled/storage".to_string(),
1270                };
1271                writeln!(
1272                    out,
1273                    "        image  {:<20} {:<20} {role} [{}]",
1274                    node.label,
1275                    format!("{:?}", access.state),
1276                    self.slot_note(self.image_slots[access.image.index()]),
1277                )?;
1278            }
1279            for access in &pass.buffers {
1280                let node = &self.buffers[access.buffer.index()];
1281                writeln!(
1282                    out,
1283                    "        buffer {:<20} {:<20} [{}]",
1284                    node.label,
1285                    format!("{:?}", access.state),
1286                    self.slot_note(self.buffer_slots[access.buffer.index()]),
1287                )?;
1288            }
1289            self.write_barriers(out, &pass.release_barriers, &format!("[{index}] release "))?;
1290        }
1291
1292        self.write_barriers(out, &self.final_barriers, "[final] ")?;
1293        Ok(())
1294    }
1295
1296    fn transient_image_users(&self) -> usize {
1297        self.image_slots
1298            .iter()
1299            .filter(|slot| matches!(slot, Slot::Transient(_)))
1300            .count()
1301    }
1302
1303    fn transient_buffer_users(&self) -> usize {
1304        self.buffer_slots
1305            .iter()
1306            .filter(|slot| matches!(slot, Slot::Transient(_)))
1307            .count()
1308    }
1309
1310    fn slot_note(&self, slot: Slot) -> String {
1311        match slot {
1312            Slot::Imported => "imported".to_string(),
1313            Slot::Transient(index) => format!("transient #{index}"),
1314        }
1315    }
1316
1317    fn write_barriers(
1318        &self,
1319        out: &mut impl fmt::Write,
1320        barriers: &GraphBarriers,
1321        prefix: &str,
1322    ) -> fmt::Result {
1323        if barriers.is_empty() {
1324            return Ok(());
1325        }
1326        writeln!(out, "{prefix}barriers ({})", barriers.len())?;
1327        for barrier in &barriers.images {
1328            writeln!(
1329                out,
1330                "        image  {:<20} {:>18} -> {:<18}{}",
1331                self.images[barrier.image.index()].label,
1332                format!("{:?}", barrier.from),
1333                format!("{:?}", barrier.to),
1334                queue_note(barrier.queue_transfer),
1335            )?;
1336        }
1337        for barrier in &barriers.buffers {
1338            writeln!(
1339                out,
1340                "        buffer {:<20} {:>18} -> {:<18}{}",
1341                self.buffers[barrier.buffer.index()].label,
1342                format!("{:?}", barrier.from),
1343                format!("{:?}", barrier.to),
1344                queue_note(barrier.queue_transfer),
1345            )?;
1346        }
1347        Ok(())
1348    }
1349
1350    /// Records the whole frame into `encoder`.
1351    ///
1352    /// Realises the transients out of `pool`, then for each pass in order:
1353    /// emits its barrier batch as one call, opens the pass — naming the two
1354    /// queries `timers` gave it, which the backend samples where the pass opens
1355    /// and closes — sets a full-target viewport and scissor, runs the body and
1356    /// closes the pass. A [`PassKind::Copy`] is the exception twice over: its
1357    /// body runs with no scope open at all, because that is the only place the
1358    /// seam permits a copy, and having no scope it has no boundary to time.
1359    /// Finally emits the barriers that return
1360    /// imported resources to their required states, and tells `pool` what this
1361    /// frame left each physical transient in — which is what the *next* frame's
1362    /// first barrier uses as its source scope.
1363    ///
1364    /// `pool` must be the one [`RenderGraph::compile`] was given, or the
1365    /// barriers name states the resources are not in.
1366    ///
1367    /// The encoder is left outside any pass, with nothing to clean up.
1368    ///
1369    /// # Errors
1370    ///
1371    /// [`GraphError::Hal`] if the pool could not create a transient. Nothing
1372    /// else can fail here — everything checkable was checked at compile time.
1373    pub fn execute(
1374        self,
1375        device: &dyn Device,
1376        pool: &mut TransientPool,
1377        encoder: &mut dyn CommandEncoder,
1378        mut timers: Option<&mut PassTimers>,
1379    ) -> Result<(), GraphError> {
1380        let realised = self.realise(device, pool)?;
1381        let Self {
1382            images,
1383            passes,
1384            final_barriers,
1385            transient_images,
1386            transient_buffers,
1387            transient_image_end,
1388            transient_buffer_end,
1389            imported_image_end,
1390            imported_buffer_end,
1391            ..
1392        } = self;
1393
1394        if let Some(timers) = timers.as_deref_mut() {
1395            timers.begin_frame(device, encoder, &passes);
1396        }
1397
1398        for (index, pass) in passes.into_iter().enumerate() {
1399            emit(encoder, &images, &realised, &pass.barriers);
1400            // The pass's own boundaries, not a call around it: the seam takes a
1401            // timestamp only where a pass opens and closes, so the barriers just
1402            // emitted are outside what this pass will report.
1403            let timestamp_writes = timers
1404                .as_deref()
1405                .and_then(|timers| timers.pass_writes(index));
1406            let statistics_writes = timers
1407                .as_deref()
1408                .and_then(|timers| timers.pass_statistics(index));
1409
1410            match pass.kind {
1411                PassKind::Render => {
1412                    let (colors, depth_stencil) = attachments(&realised, &pass.images);
1413                    encoder.begin_render_pass(&RenderPassDesc {
1414                        label: Some(&pass.label),
1415                        color_attachments: &colors,
1416                        depth_stencil_attachment: depth_stencil,
1417                        render_area: pass.render_area,
1418                        timestamp_writes,
1419                        statistics_writes,
1420                    });
1421                    // Dynamic state, set by the graph rather than by every pass
1422                    // body: a pipeline that baked a viewport in would have to be
1423                    // rebuilt on every resize, and every body would otherwise
1424                    // repeat the same two lines with the same chance of using
1425                    // the wrong extent.
1426                    encoder.set_viewport(&Viewport::from_size(
1427                        pass.render_area.width,
1428                        pass.render_area.height,
1429                    ));
1430                    encoder.set_scissor(&pass.render_area);
1431                }
1432                PassKind::Compute => {
1433                    encoder.begin_compute_pass(&ComputePassDesc {
1434                        label: Some(&pass.label),
1435                        timestamp_writes,
1436                        statistics_writes,
1437                    });
1438                }
1439                // Nothing is opened: a copy is only legal outside every scope.
1440                PassKind::Copy => {}
1441            }
1442
1443            {
1444                let mut context = PassContext {
1445                    device,
1446                    encoder,
1447                    realised: &realised,
1448                    render_area: pass.render_area,
1449                };
1450                (pass.body)(&mut context);
1451            }
1452
1453            match pass.kind {
1454                PassKind::Render => encoder.end_render_pass(),
1455                PassKind::Compute => encoder.end_compute_pass(),
1456                PassKind::Copy => {}
1457            }
1458            // The release half of any queue-ownership transfer a later pass
1459            // acquires. Outside the pass scope, because the seam only allows
1460            // barriers there.
1461            emit(encoder, &images, &realised, &pass.release_barriers);
1462        }
1463
1464        emit(encoder, &images, &realised, &final_barriers);
1465
1466        // The handover to the next frame. It happens after the commands are
1467        // recorded rather than during compilation because a graph that is
1468        // compiled and dropped ran nothing, and a pool that remembered a frame
1469        // that never happened would order the following frame against writes
1470        // the GPU never performed.
1471        for (slot, desc) in transient_images.iter().enumerate() {
1472            pool.set_image_use(
1473                *desc,
1474                ordinal(&transient_images, slot),
1475                transient_image_end[slot],
1476            );
1477        }
1478        for (slot, desc) in transient_buffers.iter().enumerate() {
1479            pool.set_buffer_use(
1480                *desc,
1481                ordinal(&transient_buffers, slot),
1482                transient_buffer_end[slot],
1483            );
1484        }
1485        // The same handover for the imports the owner says it tracks, and for
1486        // the same reason one turn further out: the next graph's `compile` is
1487        // what reads these, and it reads them to *refuse* a declaration that
1488        // disagrees rather than to barrier against them.
1489        for (image, state) in imported_image_end {
1490            pool.set_imported_image_use(image, state);
1491        }
1492        for (buffer, state) in imported_buffer_end {
1493            pool.set_imported_buffer_use(buffer, state);
1494        }
1495        Ok(())
1496    }
1497
1498    fn realise(
1499        &self,
1500        device: &dyn Device,
1501        pool: &mut TransientPool,
1502    ) -> Result<Realised, GraphError> {
1503        pool.begin_frame();
1504        let mut physical_images = Vec::with_capacity(self.transient_images.len());
1505        for desc in &self.transient_images {
1506            physical_images.push(pool.image(device, *desc)?);
1507        }
1508        let mut physical_buffers = Vec::with_capacity(self.transient_buffers.len());
1509        for desc in &self.transient_buffers {
1510            physical_buffers.push(pool.buffer(device, *desc)?);
1511        }
1512
1513        let images = self
1514            .images
1515            .iter()
1516            .zip(&self.image_slots)
1517            .map(|(node, slot)| match (slot, node.source) {
1518                (Slot::Imported, ImageSource::Imported(imported)) => {
1519                    (imported.image, imported.view)
1520                }
1521                (Slot::Transient(index), _) => physical_images[*index],
1522                // Unreachable: `compile` assigns `Imported` only to imported
1523                // nodes. Stated as a panic rather than an `unwrap` so the
1524                // invariant is named where it is relied on.
1525                (Slot::Imported, ImageSource::Transient(_)) => {
1526                    unreachable!("a transient image was assigned the imported slot")
1527                }
1528            })
1529            .collect();
1530        let buffers = self
1531            .buffers
1532            .iter()
1533            .zip(&self.buffer_slots)
1534            .map(|(node, slot)| match (slot, node.source) {
1535                (Slot::Imported, BufferSource::Imported(imported)) => imported.buffer,
1536                (Slot::Transient(index), _) => physical_buffers[*index],
1537                (Slot::Imported, BufferSource::Transient(_)) => {
1538                    unreachable!("a transient buffer was assigned the imported slot")
1539                }
1540            })
1541            .collect();
1542
1543        Ok(Realised { images, buffers })
1544    }
1545}
1546
1547fn queue_note(transfer: Option<QueueTransfer>) -> String {
1548    transfer.map_or_else(String::new, |transfer| {
1549        format!("  queue {:?} -> {:?}", transfer.from, transfer.to)
1550    })
1551}
1552
1553/// Virtual resources resolved to real handles, for the duration of one
1554/// [`CompiledGraph::execute`].
1555#[derive(Debug)]
1556struct Realised {
1557    images: Vec<(ImageHandle, ImageViewHandle)>,
1558    buffers: Vec<BufferHandle>,
1559}
1560
1561/// What a pass body is handed.
1562///
1563/// It has an encoder already inside the pass scope, the device (for the rare
1564/// body that has to build something against a transient's handle), and a way to
1565/// turn a virtual id into the handle it landed on.
1566#[derive(Debug)]
1567pub struct PassContext<'a> {
1568    device: &'a dyn Device,
1569    encoder: &'a mut dyn CommandEncoder,
1570    realised: &'a Realised,
1571    render_area: Rect2d,
1572}
1573
1574impl PassContext<'_> {
1575    /// The encoder, already inside this pass's scope.
1576    pub fn encoder(&mut self) -> &mut dyn CommandEncoder {
1577        self.encoder
1578    }
1579
1580    /// The device, for a body that must create something against a transient's
1581    /// handle — a bind group naming a graph-owned image view, typically.
1582    #[must_use]
1583    pub fn device(&self) -> &dyn Device {
1584        self.device
1585    }
1586
1587    /// The handle a virtual image landed on.
1588    ///
1589    /// # Panics
1590    ///
1591    /// If `id` came from a different graph.
1592    #[must_use]
1593    pub fn image(&self, id: ImageId) -> ImageHandle {
1594        self.realised.images[id.index()].0
1595    }
1596
1597    /// The view of a virtual image.
1598    ///
1599    /// Stable frame to frame while the graph's shape is, which is what lets a
1600    /// caller cache a bind group against it and rebuild only on a resize.
1601    ///
1602    /// # Panics
1603    ///
1604    /// If `id` came from a different graph.
1605    #[must_use]
1606    pub fn image_view(&self, id: ImageId) -> ImageViewHandle {
1607        self.realised.images[id.index()].1
1608    }
1609
1610    /// The handle a virtual buffer landed on.
1611    ///
1612    /// # Panics
1613    ///
1614    /// If `id` came from a different graph.
1615    #[must_use]
1616    pub fn buffer(&self, id: BufferId) -> BufferHandle {
1617        self.realised.buffers[id.index()]
1618    }
1619
1620    /// The region this pass renders, in pixels. The viewport and scissor are
1621    /// already set to it.
1622    #[must_use]
1623    pub const fn render_area(&self) -> Rect2d {
1624        self.render_area
1625    }
1626}
1627
1628fn emit(
1629    encoder: &mut dyn CommandEncoder,
1630    images: &[ImageNode],
1631    realised: &Realised,
1632    barriers: &GraphBarriers,
1633) {
1634    if barriers.is_empty() {
1635        return;
1636    }
1637    let image_barriers: Vec<ImageBarrier> = barriers
1638        .images
1639        .iter()
1640        .map(|barrier| ImageBarrier {
1641            image: realised.images[barrier.image.index()].0,
1642            range: barrier.range.unwrap_or_else(|| {
1643                ImageSubresourceRange::all(images[barrier.image.index()].format())
1644            }),
1645            from: barrier.from,
1646            to: barrier.to,
1647            queue_transfer: barrier.queue_transfer,
1648        })
1649        .collect();
1650    let buffer_barriers: Vec<BufferBarrier> = barriers
1651        .buffers
1652        .iter()
1653        .map(|barrier| BufferBarrier {
1654            buffer: realised.buffers[barrier.buffer.index()],
1655            from: barrier.from,
1656            to: barrier.to,
1657            queue_transfer: barrier.queue_transfer,
1658        })
1659        .collect();
1660    encoder.pipeline_barrier(&Barriers {
1661        buffers: &buffer_barriers,
1662        images: &image_barriers,
1663        global: false,
1664    });
1665}
1666
1667fn attachments(
1668    realised: &Realised,
1669    accesses: &[ImageAccess],
1670) -> (Vec<ColorAttachment>, Option<DepthStencilAttachment>) {
1671    let mut colors: Vec<(u32, ColorAttachment)> = Vec::new();
1672    let mut depth_stencil = None;
1673    for access in accesses {
1674        let view = realised.images[access.image.index()].1;
1675        match access.attachment {
1676            Some(Attachment::Color {
1677                index,
1678                load,
1679                store,
1680                clear,
1681            }) => colors.push((
1682                index,
1683                ColorAttachment {
1684                    view,
1685                    resolve: None,
1686                    load,
1687                    store,
1688                    clear,
1689                },
1690            )),
1691            Some(Attachment::Depth {
1692                load,
1693                store,
1694                clear,
1695                write,
1696            }) => {
1697                depth_stencil = Some(DepthStencilAttachment {
1698                    view,
1699                    // `PassBuilder::depth_read` declares
1700                    // `ResourceState::DepthStencilRead`, which puts the image in
1701                    // a *different* layout from a written depth attachment. The
1702                    // backend cannot infer that from the ops, so the pass's own
1703                    // `write` flag is what tells it.
1704                    read_only: !write,
1705                    depth_load: load,
1706                    depth_store: store,
1707                    // No stencil plane in anything the engine renders yet; a
1708                    // `D32_SFLOAT` attachment has none to load or store.
1709                    stencil_load: LoadOp::DontCare,
1710                    stencil_store: StoreOp::Discard,
1711                    clear,
1712                });
1713            }
1714            None => {}
1715        }
1716    }
1717    // Attachment order in the descriptor is shader-output order, which is the
1718    // `index` a caller gave — not the order it happened to declare them in.
1719    colors.sort_by_key(|(index, _)| *index);
1720    (
1721        colors
1722            .into_iter()
1723            .map(|(_, attachment)| attachment)
1724            .collect(),
1725        depth_stencil,
1726    )
1727}
1728
1729// --- compilation -----------------------------------------------------------
1730
1731/// Why a graph could not be compiled.
1732#[derive(Debug, thiserror::Error)]
1733pub enum GraphError {
1734    /// One pass declared two different states for the same resource.
1735    #[error(
1736        "pass `{pass}` accesses `{resource}` as both {first:?} and {second:?}; a resource is in \
1737         one state per pass, so this needs two passes or one state"
1738    )]
1739    ConflictingAccess {
1740        /// Pass label.
1741        pass: String,
1742        /// Resource label.
1743        resource: String,
1744        /// The first state declared.
1745        first: ResourceState,
1746        /// The second, incompatible state.
1747        second: ResourceState,
1748    },
1749    /// A render pass attached nothing.
1750    #[error(
1751        "render pass `{pass}` has no attachments; a pass that renders nowhere is a declaration \
1752         mistake, not an optimisation"
1753    )]
1754    NoAttachments {
1755        /// Pass label.
1756        pass: String,
1757    },
1758    /// A render pass attached images of different sizes.
1759    #[error(
1760        "render pass `{pass}` attaches `{first}` at {first_extent:?} and `{second}` at \
1761         {second_extent:?}; every attachment must be the same size"
1762    )]
1763    AttachmentExtentMismatch {
1764        /// Pass label.
1765        pass: String,
1766        /// The first attachment's label.
1767        first: String,
1768        /// Its size.
1769        first_extent: (u32, u32),
1770        /// The disagreeing attachment's label.
1771        second: String,
1772        /// Its size.
1773        second_extent: (u32, u32),
1774    },
1775    /// A render pass attached two depth images.
1776    #[error("render pass `{pass}` attaches more than one depth image")]
1777    DuplicateDepthAttachment {
1778        /// Pass label.
1779        pass: String,
1780    },
1781    /// One pass declared the same resource twice over the same subrange.
1782    ///
1783    /// `.color(image, ..).color(image, ..)` used to be accepted and produced
1784    /// two colour attachments over one view — two shader outputs writing the
1785    /// same pixels, in an order nothing defines. A pass that genuinely touches
1786    /// two parts of one image declares two *different* subresource ranges.
1787    #[error(
1788        "pass `{pass}` declares `{resource}` twice over the same subrange; a resource is declared \
1789         once per pass, and two attachments over one view is not a second attachment"
1790    )]
1791    DuplicateDeclaration {
1792        /// Pass label.
1793        pass: String,
1794        /// Resource label.
1795        resource: String,
1796    },
1797    /// A pass named a mip level or array layer the image does not have.
1798    #[error(
1799        "pass `{pass}` uses `{resource}` at mip {base_mip}+{mip_count} / layer \
1800         {base_layer}+{layer_count}, but the image has {mip_levels} mip level(s) and \
1801         {layers} layer(s); a barrier on a subresource that does not exist covers nothing"
1802    )]
1803    SubresourceOutOfRange {
1804        /// Pass label.
1805        pass: String,
1806        /// Resource label.
1807        resource: String,
1808        /// First mip named.
1809        base_mip: u32,
1810        /// Mip levels named.
1811        mip_count: u32,
1812        /// First layer named.
1813        base_layer: u32,
1814        /// Layers named.
1815        layer_count: u32,
1816        /// Mip levels the image has.
1817        mip_levels: u32,
1818        /// Array layers the image has.
1819        layers: u32,
1820    },
1821    /// A pass that opens no render scope attached something.
1822    #[error("{kind} pass `{pass}` attaches `{resource}`; only a render pass has attachments")]
1823    AttachmentOutsideRenderPass {
1824        /// Which kind of pass declared it — [`PassKind::name`].
1825        kind: &'static str,
1826        /// Pass label.
1827        pass: String,
1828        /// Resource label.
1829        resource: String,
1830    },
1831    /// A transient was declared and never used, so it has no lifetime and no
1832    /// reason to exist.
1833    #[error(
1834        "`{resource}` is a transient no pass reads or writes; either a pass forgot to declare it \
1835         or the resource should not have been created"
1836    )]
1837    UnusedTransient {
1838        /// Resource label.
1839        resource: String,
1840    },
1841    /// An [`InitialClaim::Tracked`] import declared a state the last graph did
1842    /// not leave the image in.
1843    ///
1844    /// The whole point of the claim: the owner said it tracks this image across
1845    /// frames, and the pool remembers what the previous graph's trailing
1846    /// barrier actually reached. When those disagree the first barrier of this
1847    /// frame names a source scope the GPU never visits — and if the declaration
1848    /// is [`ResourceState::Undefined`] it names no source scope at all, so the
1849    /// transition orders against nothing while the previous frame is still
1850    /// reading the same image.
1851    #[error(
1852        "`{resource}` is imported as {declared:?}, but the last graph left it in {left:?}; a \
1853         barrier out of a state the image is not in carries the wrong source scope — declare \
1854         what was left, or say `InitialClaim::Acquired` if a semaphore already orders this frame"
1855    )]
1856    ImportStateMismatch {
1857        /// Resource label.
1858        resource: String,
1859        /// What the import declared as [`ImportedImage::initial`].
1860        declared: ResourceState,
1861        /// What the last graph to execute against this pool left it in.
1862        left: ResourceState,
1863    },
1864    /// A buffer import declared a state the last graph did not leave it in.
1865    ///
1866    /// [`GraphError::ImportStateMismatch`] for a resource with no layout, and
1867    /// its own variant rather than the same one because the two answers a reader
1868    /// needs differ. An image has a way out — say [`InitialClaim::Acquired`] and
1869    /// mean it — and telling a buffer's importer to reach for a field
1870    /// [`ImportedBuffer`] does not have would send them looking for an escape
1871    /// that is not there and should not be. What is left when that clause goes
1872    /// is the whole of the advice: declare what the last frame left.
1873    #[error(
1874        "`{resource}` is imported as {declared:?}, but the last graph left it in {left:?}; a \
1875         barrier out of a state the buffer is not in carries the wrong source scope, and \
1876         `Undefined` carries none at all — declare what was left"
1877    )]
1878    BufferImportStateMismatch {
1879        /// Resource label.
1880        resource: String,
1881        /// What the import declared as [`ImportedBuffer::initial`].
1882        declared: ResourceState,
1883        /// What the last graph to execute against this pool left it in.
1884        left: ResourceState,
1885    },
1886    /// One image handle was imported twice with declarations that disagree.
1887    ///
1888    /// [`RenderGraph::import_image`] hands the second importer the id the first
1889    /// one got, because one handle has to be one node with one state tracker
1890    /// for the graph to barrier between two passes that reach it through
1891    /// different ids. That leaves exactly one thing it cannot do quietly: two
1892    /// declarations that are not the same declaration. Keeping the first would
1893    /// be the graph ignoring the second — silently sampling through a view it
1894    /// was not handed, or barriering out of a state the other importer says the
1895    /// image is not in — so the frame is refused instead and the two importers
1896    /// have to agree.
1897    #[error(
1898        "`{resource}` is imported more than once with different declarations: `{field}` is \
1899         {first} in one and {second} in the other; one handle is one node with one state \
1900         tracker, so the graph cannot honour both — import it once and share the id"
1901    )]
1902    ImportDeclarationConflict {
1903        /// Resource label — the **first** import's, which is the one the node
1904        /// kept.
1905        resource: String,
1906        /// Which field of [`ImportedImage`] disagreed.
1907        field: ImportField,
1908        /// What the first import declared it as, [`Debug`](fmt::Debug)-printed.
1909        first: String,
1910        /// What the later import declared it as.
1911        second: String,
1912    },
1913    /// One buffer handle was imported twice with declarations that disagree.
1914    ///
1915    /// [`GraphError::ImportDeclarationConflict`] for a resource with no layout,
1916    /// and a variant of its own for the same reason
1917    /// [`GraphError::BufferImportStateMismatch`] is one: the message names the
1918    /// resource kind, and a caller matching on the error is usually looking at
1919    /// one kind of resource.
1920    #[error(
1921        "`{resource}` is imported more than once with different declarations: `{field}` is \
1922         {first} in one and {second} in the other; one handle is one node with one state \
1923         tracker, so the graph cannot honour both — import it once and share the id"
1924    )]
1925    BufferImportDeclarationConflict {
1926        /// Resource label — the **first** import's, which is the one the node
1927        /// kept.
1928        resource: String,
1929        /// Which field of [`ImportedBuffer`] disagreed.
1930        field: ImportField,
1931        /// What the first import declared it as, [`Debug`](fmt::Debug)-printed.
1932        first: String,
1933        /// What the later import declared it as.
1934        second: String,
1935    },
1936    /// The seam refused something at execution time.
1937    #[error(transparent)]
1938    Hal(#[from] HalError),
1939}
1940
1941/// Which field of a repeated import declaration disagreed with the first one.
1942///
1943/// Carried by [`GraphError::ImportDeclarationConflict`] and
1944/// [`GraphError::BufferImportDeclarationConflict`] so a caller can tell the
1945/// kinds of disagreement apart without parsing a message: two subsystems
1946/// disagreeing about the state an image arrives in is a synchronisation bug in
1947/// one of them, and two disagreeing about which view they bind is usually one
1948/// of them importing the wrong thing entirely.
1949///
1950/// It spells [`ImportedImage`]'s fields, of which an [`ImportedBuffer`] has
1951/// only [`Initial`](Self::Initial) and [`FinalState`](Self::FinalState); the
1952/// handle itself is absent because it is what the two declarations are matched
1953/// on, so it cannot be what they differ in. [`Display`](fmt::Display) prints
1954/// the field's name as it is spelled in the struct, so a message points at
1955/// something a reader can go and look at.
1956#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1957pub enum ImportField {
1958    /// [`ImportedImage::view`].
1959    View,
1960    /// [`ImportedImage::format`].
1961    Format,
1962    /// [`ImportedImage::extent`].
1963    Extent,
1964    /// [`ImportedImage::initial`] or [`ImportedBuffer::initial`].
1965    Initial,
1966    /// [`ImportedImage::claim`].
1967    Claim,
1968    /// [`ImportedImage::final_state`] or [`ImportedBuffer::final_state`].
1969    FinalState,
1970}
1971
1972impl fmt::Display for ImportField {
1973    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1974        f.write_str(match self {
1975            Self::View => "view",
1976            Self::Format => "format",
1977            Self::Extent => "extent",
1978            Self::Initial => "initial",
1979            Self::Claim => "claim",
1980            Self::FinalState => "final_state",
1981        })
1982    }
1983}
1984
1985/// The first field two declarations of one imported image disagree about.
1986///
1987/// First rather than all of them, because that is how the rest of this file
1988/// reports: one problem named, and the fixed declaration comes back past
1989/// `compile` anyway. Compares the values and formats only what it returns —
1990/// deciding "same declaration" off the printed text would make two handles that
1991/// happen to print alike into one.
1992fn image_import_conflict(
1993    first: &ImportedImage,
1994    second: &ImportedImage,
1995) -> Option<(ImportField, String, String)> {
1996    // Binds nothing; it is here so that adding a field to `ImportedImage` stops
1997    // compiling until this function has decided about it. A field the
1998    // comparison forgets is a disagreement reported as agreement, which is the
1999    // one failure this whole check exists to prevent — and the six blocks below
2000    // look alike enough that a missing seventh would read as complete.
2001    let ImportedImage {
2002        image: _,
2003        view: _,
2004        format: _,
2005        extent: _,
2006        initial: _,
2007        claim: _,
2008        final_state: _,
2009    } = first;
2010    if first.view != second.view {
2011        return Some((
2012            ImportField::View,
2013            format!("{:?}", first.view),
2014            format!("{:?}", second.view),
2015        ));
2016    }
2017    if first.format != second.format {
2018        return Some((
2019            ImportField::Format,
2020            format!("{:?}", first.format),
2021            format!("{:?}", second.format),
2022        ));
2023    }
2024    if first.extent != second.extent {
2025        return Some((
2026            ImportField::Extent,
2027            format!("{:?}", first.extent),
2028            format!("{:?}", second.extent),
2029        ));
2030    }
2031    if first.initial != second.initial {
2032        return Some((
2033            ImportField::Initial,
2034            format!("{:?}", first.initial),
2035            format!("{:?}", second.initial),
2036        ));
2037    }
2038    if first.claim != second.claim {
2039        return Some((
2040            ImportField::Claim,
2041            format!("{:?}", first.claim),
2042            format!("{:?}", second.claim),
2043        ));
2044    }
2045    if first.final_state != second.final_state {
2046        return Some((
2047            ImportField::FinalState,
2048            format!("{:?}", first.final_state),
2049            format!("{:?}", second.final_state),
2050        ));
2051    }
2052    None
2053}
2054
2055/// The first field two declarations of one imported buffer disagree about. See
2056/// [`image_import_conflict`]; a buffer declaration is the two state fields and
2057/// the handle they are about.
2058fn buffer_import_conflict(
2059    first: &ImportedBuffer,
2060    second: &ImportedBuffer,
2061) -> Option<(ImportField, String, String)> {
2062    // See [`image_import_conflict`]: binds nothing, and stops compiling when
2063    // `ImportedBuffer` grows a field this comparison has not decided about.
2064    let ImportedBuffer {
2065        buffer: _,
2066        initial: _,
2067        final_state: _,
2068    } = first;
2069    if first.initial != second.initial {
2070        return Some((
2071            ImportField::Initial,
2072            format!("{:?}", first.initial),
2073            format!("{:?}", second.initial),
2074        ));
2075    }
2076    if first.final_state != second.final_state {
2077        return Some((
2078            ImportField::FinalState,
2079            format!("{:?}", first.final_state),
2080            format!("{:?}", second.final_state),
2081        ));
2082    }
2083    None
2084}
2085
2086/// Array layers a [`TransientImageDesc`] image has. The pool creates them
2087/// single-layer, and the description has no field to say otherwise.
2088const TRANSIENT_LAYERS: u32 = 1;
2089
2090/// Per-physical-resource tracking during compilation.
2091///
2092/// Keyed on the *physical* resource, and seeded from what that resource was
2093/// last used for — [`ImportedImage::initial`] for an import, the pool's memory
2094/// of the previous frame for a transient. There is no "and now the slot is
2095/// fresh" case: a slot handed from one virtual resource to another is the same
2096/// object, in the state the previous one left it, and the module docs explain
2097/// why pretending otherwise loses the barrier.
2098#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2099struct Tracked {
2100    state: ResourceState,
2101    queue: Option<QueueHandle>,
2102    /// Index of the pass in *this* graph that last used it, which is where the
2103    /// release half of a queue-ownership transfer has to be recorded.
2104    last_pass: Option<usize>,
2105}
2106
2107impl Tracked {
2108    const fn carried(last: TransientUse) -> Self {
2109        Self {
2110            state: last.state,
2111            queue: last.queue,
2112            last_pass: None,
2113        }
2114    }
2115
2116    const fn declared(state: ResourceState) -> Self {
2117        Self {
2118            state,
2119            queue: None,
2120            last_pass: None,
2121        }
2122    }
2123
2124    const fn end(self) -> TransientUse {
2125        TransientUse {
2126            state: self.state,
2127            queue: self.queue,
2128        }
2129    }
2130}
2131
2132/// A half-open mip × layer rectangle of one image.
2133///
2134/// The unit of image state tracking. Whole-image is just the rectangle covering
2135/// everything — the graph does not need a second representation for it.
2136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2137struct Subrect {
2138    mips: (u32, u32),
2139    layers: (u32, u32),
2140}
2141
2142impl Subrect {
2143    /// The rectangle a resource with unknown extents starts at. Imported
2144    /// images do not say how many levels or layers they have, and every access
2145    /// to one in this engine covers the whole thing.
2146    const UNBOUNDED: Self = Self {
2147        mips: (0, u32::MAX),
2148        layers: (0, u32::MAX),
2149    };
2150
2151    const fn bounded(mip_levels: u32, layers: u32) -> Self {
2152        Self {
2153            mips: (0, mip_levels),
2154            layers: (0, layers),
2155        }
2156    }
2157
2158    const fn is_empty(self) -> bool {
2159        self.mips.0 >= self.mips.1 || self.layers.0 >= self.layers.1
2160    }
2161
2162    fn intersect(self, other: Self) -> Self {
2163        Self {
2164            mips: (self.mips.0.max(other.mips.0), self.mips.1.min(other.mips.1)),
2165            layers: (
2166                self.layers.0.max(other.layers.0),
2167                self.layers.1.min(other.layers.1),
2168            ),
2169        }
2170    }
2171
2172    /// `self` minus `cut`, as up to four disjoint rectangles.
2173    ///
2174    /// `cut` must already be an intersection with `self`, so the pieces tile
2175    /// the difference exactly.
2176    fn subtract(self, cut: Self) -> Vec<Self> {
2177        let mut out = Vec::new();
2178        if cut.mips.0 > self.mips.0 {
2179            out.push(Self {
2180                mips: (self.mips.0, cut.mips.0),
2181                layers: self.layers,
2182            });
2183        }
2184        if self.mips.1 > cut.mips.1 {
2185            out.push(Self {
2186                mips: (cut.mips.1, self.mips.1),
2187                layers: self.layers,
2188            });
2189        }
2190        if cut.layers.0 > self.layers.0 {
2191            out.push(Self {
2192                mips: cut.mips,
2193                layers: (self.layers.0, cut.layers.0),
2194            });
2195        }
2196        if self.layers.1 > cut.layers.1 {
2197            out.push(Self {
2198                mips: cut.mips,
2199                layers: (cut.layers.1, self.layers.1),
2200            });
2201        }
2202        out
2203    }
2204
2205    fn to_range(self, aspect: crcbl_hal::ImageAspect) -> ImageSubresourceRange {
2206        ImageSubresourceRange {
2207            aspect,
2208            base_mip: self.mips.0,
2209            mip_count: if self.mips.1 == u32::MAX {
2210                ImageSubresourceRange::ALL
2211            } else {
2212                self.mips.1 - self.mips.0
2213            },
2214            base_layer: self.layers.0,
2215            layer_count: if self.layers.1 == u32::MAX {
2216                ImageSubresourceRange::ALL
2217            } else {
2218                self.layers.1 - self.layers.0
2219            },
2220        }
2221    }
2222}
2223
2224/// `ALL` means "every remaining", so it resolves against the image's own size.
2225fn subrect_of(range: ImageSubresourceRange, bounds: Subrect) -> Subrect {
2226    let mip_end = if range.mip_count == ImageSubresourceRange::ALL {
2227        bounds.mips.1
2228    } else {
2229        range.base_mip.saturating_add(range.mip_count)
2230    };
2231    let layer_end = if range.layer_count == ImageSubresourceRange::ALL {
2232        bounds.layers.1
2233    } else {
2234        range.base_layer.saturating_add(range.layer_count)
2235    };
2236    Subrect {
2237        mips: (range.base_mip, mip_end),
2238        layers: (range.base_layer, layer_end),
2239    }
2240}
2241
2242/// One transition the tracker decided is needed.
2243#[derive(Clone, Copy, Debug)]
2244struct SubBarrier {
2245    from: ResourceState,
2246    queue_transfer: Option<QueueTransfer>,
2247    /// The part of the image it covers, or `None` when the whole access range
2248    /// is in one state and the access's own range already describes it.
2249    rect: Option<Subrect>,
2250    /// Pass that last used this part, for the release half of a transfer.
2251    last_pass: Option<usize>,
2252}
2253
2254/// Per-**subresource** image state.
2255///
2256/// A whole-image tracker was wrong in a way that only a per-mip pass could
2257/// notice, and did: writing mip 0 and then mip 1 produced a barrier on mip 1
2258/// whose `from` was the state mip 0 had been left in, which mip 1 had never
2259/// been in. A barrier that names a source state its subresource never occupied
2260/// is a barrier the driver is free to interpret as covering nothing.
2261#[derive(Clone, Debug)]
2262struct ImageTracker {
2263    bounds: Subrect,
2264    /// Disjoint rectangles tiling `bounds`, each with the state of that part.
2265    segments: Vec<(Subrect, Tracked)>,
2266}
2267
2268impl ImageTracker {
2269    fn new(bounds: Subrect, tracked: Tracked) -> Self {
2270        Self {
2271            bounds,
2272            segments: vec![(bounds, tracked)],
2273        }
2274    }
2275
2276    /// Applies an access covering `rect`, returning the barriers it needs.
2277    fn transition(
2278        &mut self,
2279        rect: Subrect,
2280        want: ResourceState,
2281        queue: QueueHandle,
2282        pass: usize,
2283    ) -> Vec<SubBarrier> {
2284        let mut outside: Vec<(Subrect, Tracked)> = Vec::new();
2285        let mut inside: Vec<(Subrect, Tracked)> = Vec::new();
2286        for (segment, tracked) in self.segments.drain(..) {
2287            let overlap = segment.intersect(rect);
2288            if overlap.is_empty() {
2289                outside.push((segment, tracked));
2290                continue;
2291            }
2292            outside.extend(
2293                segment
2294                    .subtract(overlap)
2295                    .into_iter()
2296                    .map(|piece| (piece, tracked)),
2297            );
2298            inside.push((overlap, tracked));
2299        }
2300
2301        let mut barriers = Vec::new();
2302        for (piece, tracked) in &inside {
2303            let queue_transfer = match tracked.queue {
2304                Some(previous) if previous != queue => Some(QueueTransfer {
2305                    from: previous,
2306                    to: queue,
2307                }),
2308                _ => None,
2309            };
2310            // A queue-family transfer is a barrier even between two identical
2311            // states: ownership has to move, or the second queue reads memory
2312            // the first has not released.
2313            if ResourceState::needs_barrier(tracked.state, want) || queue_transfer.is_some() {
2314                barriers.push(SubBarrier {
2315                    from: tracked.state,
2316                    queue_transfer,
2317                    rect: Some(*piece),
2318                    last_pass: tracked.last_pass,
2319                });
2320            }
2321        }
2322
2323        // The common case: every part of the access was in one state, so the
2324        // access's own declared range describes the barrier exactly and there
2325        // is no reason to spell out the pieces.
2326        if barriers.len() == inside.len()
2327            && barriers.windows(2).all(|pair| {
2328                pair[0].from == pair[1].from && pair[0].queue_transfer == pair[1].queue_transfer
2329            })
2330        {
2331            barriers.truncate(1.min(barriers.len()));
2332            if let Some(first) = barriers.first_mut() {
2333                first.rect = None;
2334            }
2335        }
2336
2337        let entered = Tracked {
2338            state: want,
2339            queue: Some(queue),
2340            last_pass: Some(pass),
2341        };
2342        self.segments = outside;
2343        for (piece, tracked) in inside {
2344            // A read that needed no barrier stays in the state it was in — two
2345            // reads of the same kind are the same state by definition.
2346            let state = if ResourceState::needs_barrier(tracked.state, want) {
2347                want
2348            } else {
2349                tracked.state
2350            };
2351            self.segments.push((piece, Tracked { state, ..entered }));
2352        }
2353        self.coalesce();
2354        barriers
2355    }
2356
2357    /// Collapses back to one segment once the whole image agrees again, so a
2358    /// frame of whole-image passes never grows the list.
2359    fn coalesce(&mut self) {
2360        let Some((_, first)) = self.segments.first().copied() else {
2361            return;
2362        };
2363        if self.segments.iter().all(|(_, tracked)| *tracked == first) {
2364            self.segments = vec![(self.bounds, first)];
2365        }
2366    }
2367
2368    /// The state of the base subresource.
2369    ///
2370    /// [`TransientUse`] holds one state per resource, so a frame that leaves an
2371    /// image in mixed states can only hand the pool the one the next frame's
2372    /// whole-image barrier will name — which is the base level's.
2373    fn end(&self) -> TransientUse {
2374        self.segments
2375            .iter()
2376            .find(|(rect, _)| {
2377                rect.mips.0 == self.bounds.mips.0 && rect.layers.0 == self.bounds.layers.0
2378            })
2379            .or_else(|| self.segments.first())
2380            .map_or_else(TransientUse::default, |(_, tracked)| tracked.end())
2381    }
2382}
2383
2384/// How many earlier entries of `descs` carry the same description as `descs[at]`.
2385///
2386/// The pool hands out the *n*-th resource of a description for the *n*-th
2387/// request, and [`CompiledGraph::realise`] requests them in slot order — so this
2388/// is the number that turns "physical slot 3" into "the pool entry slot 3 will
2389/// get", both before it has been realised and after.
2390fn ordinal<D: PartialEq>(descs: &[D], at: usize) -> usize {
2391    descs[..at]
2392        .iter()
2393        .filter(|other| **other == descs[at])
2394        .count()
2395}
2396
2397fn compile<'a>(
2398    graph: RenderGraph<'a>,
2399    pool: &TransientPool,
2400) -> Result<CompiledGraph<'a>, GraphError> {
2401    let RenderGraph {
2402        images,
2403        buffers,
2404        passes,
2405        default_queue: _,
2406        import_conflict,
2407    } = graph;
2408
2409    // First, because it is the earliest thing that went wrong: every check
2410    // below runs against a node whose declaration is already known to have been
2411    // contradicted, so any error they found would be about the wrong half.
2412    if let Some(conflict) = import_conflict {
2413        return Err(conflict);
2414    }
2415    validate(&images, &buffers, &passes)?;
2416    validate_imports(&images, &buffers, pool)?;
2417
2418    let image_lifetimes = lifetimes(passes.len(), passes.iter().map(|pass| &pass.images), |a| {
2419        a.image.0
2420    });
2421    let buffer_lifetimes = lifetimes(passes.len(), passes.iter().map(|pass| &pass.buffers), |a| {
2422        a.buffer.0
2423    });
2424
2425    // Aliasing: pack transients onto as few physical resources as their
2426    // lifetimes allow.
2427    let mut transient_images = Vec::new();
2428    let image_slots = assign(
2429        &images,
2430        &image_lifetimes,
2431        |node| match node.source {
2432            ImageSource::Transient(desc) => Some(desc),
2433            ImageSource::Imported(_) => None,
2434        },
2435        |node| node.label.clone(),
2436        &mut transient_images,
2437    )?;
2438    let mut transient_buffers = Vec::new();
2439    let buffer_slots = assign(
2440        &buffers,
2441        &buffer_lifetimes,
2442        |node| match node.source {
2443            BufferSource::Transient(desc) => Some(desc),
2444            BufferSource::Imported(_) => None,
2445        },
2446        |node| node.label.clone(),
2447        &mut transient_buffers,
2448    )?;
2449
2450    // State tracking is per **physical** resource, because that is what a
2451    // barrier actually names. Imported resources get one tracker each (keyed by
2452    // their own id); transients share one per physical slot.
2453    //
2454    // Every tracker starts where its resource actually is. For an import that
2455    // is what the owner declared; for a transient it is what the pool remembers
2456    // of the last frame that used the very same handle, which is the whole of
2457    // the cross-frame fix.
2458    let mut image_state: Vec<ImageTracker> = images
2459        .iter()
2460        .zip(&image_slots)
2461        .map(|(node, slot)| match (slot, node.source) {
2462            (Slot::Imported, ImageSource::Imported(imported)) => {
2463                ImageTracker::new(Subrect::UNBOUNDED, Tracked::declared(imported.initial))
2464            }
2465            _ => ImageTracker::new(
2466                Subrect::UNBOUNDED,
2467                Tracked::declared(ResourceState::Undefined),
2468            ),
2469        })
2470        .collect();
2471    let mut transient_image_state: Vec<ImageTracker> = (0..transient_images.len())
2472        .map(|slot| {
2473            let desc = transient_images[slot];
2474            ImageTracker::new(
2475                // A transient is a single-layer 2D image whose level count the
2476                // description now states, so a range naming a level it does not
2477                // have is a compile error rather than a barrier on nothing.
2478                Subrect::bounded(desc.mip_levels.max(1), 1),
2479                Tracked::carried(pool.image_use(desc, ordinal(&transient_images, slot))),
2480            )
2481        })
2482        .collect();
2483    let mut buffer_state: Vec<Tracked> = buffers
2484        .iter()
2485        .zip(&buffer_slots)
2486        .map(|(node, slot)| Tracked {
2487            state: match (slot, node.source) {
2488                (Slot::Imported, BufferSource::Imported(imported)) => imported.initial,
2489                _ => ResourceState::Undefined,
2490            },
2491            queue: None,
2492            last_pass: None,
2493        })
2494        .collect();
2495    let mut transient_buffer_state: Vec<Tracked> = (0..transient_buffers.len())
2496        .map(|slot| {
2497            Tracked::carried(
2498                pool.buffer_use(transient_buffers[slot], ordinal(&transient_buffers, slot)),
2499            )
2500        })
2501        .collect();
2502
2503    let mut compiled: Vec<CompiledPass<'a>> = Vec::with_capacity(passes.len());
2504    for (index, pass) in passes.into_iter().enumerate() {
2505        let mut barriers = GraphBarriers::default();
2506
2507        for access in &pass.images {
2508            let node = &images[access.image.index()];
2509            let aspect = access
2510                .range
2511                .map_or_else(|| ImageAspect::of(node.format()), |range| range.aspect);
2512            let tracked = tracker(
2513                image_slots[access.image.index()],
2514                access.image.0,
2515                &mut image_state,
2516                &mut transient_image_state,
2517            );
2518            let rect = access
2519                .range
2520                .map_or(tracked.bounds, |range| subrect_of(range, tracked.bounds));
2521            for sub in tracked.transition(rect, access.state, pass.queue, index) {
2522                let range = match sub.rect {
2523                    None => access.range,
2524                    Some(piece) => Some(piece.to_range(aspect)),
2525                };
2526                let barrier = GraphImageBarrier {
2527                    image: access.image,
2528                    from: sub.from,
2529                    to: access.state,
2530                    queue_transfer: sub.queue_transfer,
2531                    range,
2532                };
2533                // A transfer is *two* barriers with identical fields: a release
2534                // on the source queue and an acquire on the destination
2535                // (`crcbl_hal::QueueTransfer`). The release goes after the last
2536                // pass that used the resource, which is the only point at which
2537                // the source queue is finished with it.
2538                if sub.queue_transfer.is_some()
2539                    && let Some(source) = sub.last_pass
2540                {
2541                    compiled[source].release_barriers.images.push(barrier);
2542                }
2543                barriers.images.push(barrier);
2544            }
2545        }
2546        for access in &pass.buffers {
2547            let tracked = tracker(
2548                buffer_slots[access.buffer.index()],
2549                access.buffer.0,
2550                &mut buffer_state,
2551                &mut transient_buffer_state,
2552            );
2553            if let Some(barrier) = transition(tracked, access.state, pass.queue, index) {
2554                let compiled_barrier = GraphBufferBarrier {
2555                    buffer: access.buffer,
2556                    from: barrier.0,
2557                    to: access.state,
2558                    queue_transfer: barrier.1,
2559                };
2560                if barrier.1.is_some()
2561                    && let Some(source) = barrier.2
2562                {
2563                    compiled[source]
2564                        .release_barriers
2565                        .buffers
2566                        .push(compiled_barrier);
2567                }
2568                barriers.buffers.push(compiled_barrier);
2569            }
2570        }
2571
2572        let render_area = render_area(&images, &pass)?;
2573        compiled.push(CompiledPass {
2574            label: pass.label,
2575            kind: pass.kind,
2576            queue: pass.queue,
2577            barriers,
2578            release_barriers: GraphBarriers::default(),
2579            images: pass.images,
2580            buffers: pass.buffers,
2581            render_area,
2582            body: pass.body,
2583        });
2584    }
2585
2586    // Return every imported resource to the state its owner requires. This is
2587    // the barrier that used to be hand-written after the render pass in
2588    // `apps/sandbox`, and the reason it can be computed rather than remembered.
2589    let mut final_barriers = GraphBarriers::default();
2590    for (index, node) in images.iter().enumerate() {
2591        let ImageSource::Imported(imported) = node.source else {
2592            continue;
2593        };
2594        let tracker = &image_state[index];
2595        let aspect = ImageAspect::of(imported.format);
2596        let whole = tracker.segments.len() == 1;
2597        // `!=` rather than `needs_barrier`: this transition guards nothing —
2598        // the graph is finished with the resource — so its only job is to leave
2599        // the layout its owner asked for. A write-after-write between two passes
2600        // is a hazard and gets a barrier; a write followed by *nothing* is not.
2601        for (rect, tracked) in &tracker.segments {
2602            if tracked.state != imported.final_state {
2603                final_barriers.images.push(GraphImageBarrier {
2604                    image: ImageId(u32::try_from(index).expect("a frame has few resources")),
2605                    from: tracked.state,
2606                    to: imported.final_state,
2607                    queue_transfer: None,
2608                    range: if whole {
2609                        None
2610                    } else {
2611                        Some(rect.to_range(aspect))
2612                    },
2613                });
2614            }
2615        }
2616    }
2617    for (index, node) in buffers.iter().enumerate() {
2618        let BufferSource::Imported(imported) = node.source else {
2619            continue;
2620        };
2621        let tracked = buffer_state[index];
2622        if tracked.state != imported.final_state {
2623            final_barriers.buffers.push(GraphBufferBarrier {
2624                buffer: BufferId(u32::try_from(index).expect("a frame has few resources")),
2625                from: tracked.state,
2626                to: imported.final_state,
2627                queue_transfer: None,
2628            });
2629        }
2630    }
2631
2632    // What the pool is told once these commands are actually recorded. Read off
2633    // the trackers rather than re-derived, so the state the next frame barriers
2634    // against is by construction the state this frame's last barrier reached.
2635    let transient_image_end = transient_image_state
2636        .iter()
2637        .map(ImageTracker::end)
2638        .collect();
2639    let transient_buffer_end = transient_buffer_state.iter().map(|t| t.end()).collect();
2640    // Read off the declaration rather than off the tracker, because the loop
2641    // above has just made them the same thing: every segment of an imported
2642    // image that is not already at `final_state` gets a trailing barrier into
2643    // it, so `final_state` is where the image is once this frame has run.
2644    //
2645    // One entry per handle rather than per import call, and one trailing
2646    // barrier for the same reason: `RenderGraph::import_image` gives a repeat
2647    // import the id the first one got, so there is no second node here to
2648    // barrier the image somewhere else and then overwrite the ledger with it.
2649    let imported_image_end = images
2650        .iter()
2651        .filter_map(|node| match node.source {
2652            ImageSource::Imported(imported) if imported.claim == InitialClaim::Tracked => {
2653                Some((imported.image, imported.final_state))
2654            }
2655            _ => None,
2656        })
2657        .collect();
2658    // And every imported buffer, for the same reason off the same loop, with no
2659    // subset to select: there is no buffer whose declaration the graph takes on
2660    // trust, so there is none whose ending state it has no business recording.
2661    let imported_buffer_end = buffers
2662        .iter()
2663        .filter_map(|node| match node.source {
2664            BufferSource::Imported(imported) => Some((imported.buffer, imported.final_state)),
2665            BufferSource::Transient(_) => None,
2666        })
2667        .collect();
2668
2669    Ok(CompiledGraph {
2670        images,
2671        buffers,
2672        passes: compiled,
2673        final_barriers,
2674        image_slots,
2675        buffer_slots,
2676        transient_images,
2677        transient_buffers,
2678        transient_image_end,
2679        transient_buffer_end,
2680        imported_image_end,
2681        imported_buffer_end,
2682    })
2683}
2684
2685fn tracker<'s, T>(
2686    slot: Slot,
2687    id: u32,
2688    per_resource: &'s mut [T],
2689    per_slot: &'s mut [T],
2690) -> &'s mut T {
2691    match slot {
2692        Slot::Imported => &mut per_resource[id as usize],
2693        Slot::Transient(index) => &mut per_slot[index],
2694    }
2695}
2696
2697/// Decides whether a transition is needed, and updates the tracker.
2698///
2699/// Returns `(from, queue_transfer)` when a barrier must be emitted.
2700///
2701/// There is no special case for a physical slot changing hands. It used to
2702/// start such a transition from [`ResourceState::Undefined`], on the argument
2703/// that the outgoing resource's pixels are garbage to the incoming one and
2704/// discarding them is free. The pixels are indeed garbage — but `Undefined` on
2705/// this seam does not only mean "discard", it means "no source scope", and the
2706/// outgoing resource's *writes* are not garbage: they are in flight. Naming the
2707/// real previous state costs nothing here (one handle, one description, so
2708/// there is no layout change and nothing to decompress) and is the difference
2709/// between the two uses being ordered and racing.
2710fn transition(
2711    tracked: &mut Tracked,
2712    want: ResourceState,
2713    queue: QueueHandle,
2714    pass: usize,
2715) -> Option<(ResourceState, Option<QueueTransfer>, Option<usize>)> {
2716    let queue_transfer = match tracked.queue {
2717        Some(previous) if previous != queue => Some(QueueTransfer {
2718            from: previous,
2719            to: queue,
2720        }),
2721        _ => None,
2722    };
2723    let from = tracked.state;
2724    let source_pass = tracked.last_pass;
2725    tracked.queue = Some(queue);
2726    tracked.last_pass = Some(pass);
2727
2728    // A queue-family transfer is a barrier even between two identical states:
2729    // ownership has to move, or the second queue reads memory the first has not
2730    // released.
2731    if !ResourceState::needs_barrier(from, want) && queue_transfer.is_none() {
2732        return None;
2733    }
2734    tracked.state = want;
2735    Some((from, queue_transfer, source_pass))
2736}
2737
2738/// First and last pass index that touches each resource.
2739fn lifetimes<'p, A: 'p, I>(
2740    pass_count: usize,
2741    accesses: impl Iterator<Item = I>,
2742    id_of: impl Fn(&A) -> u32,
2743) -> Vec<Option<(usize, usize)>>
2744where
2745    I: IntoIterator<Item = &'p A>,
2746{
2747    let mut spans: Vec<Option<(usize, usize)>> = Vec::new();
2748    for (pass, list) in accesses.enumerate() {
2749        debug_assert!(pass < pass_count);
2750        for access in list {
2751            let id = id_of(access) as usize;
2752            if spans.len() <= id {
2753                spans.resize(id + 1, None);
2754            }
2755            spans[id] = Some(match spans[id] {
2756                Some((first, last)) => (first.min(pass), last.max(pass)),
2757                None => (pass, pass),
2758            });
2759        }
2760    }
2761    spans
2762}
2763
2764/// Packs transients onto physical slots, reusing one whose lifetime has ended.
2765fn assign<N, D: Copy + PartialEq>(
2766    nodes: &[N],
2767    spans: &[Option<(usize, usize)>],
2768    desc_of: impl Fn(&N) -> Option<D>,
2769    label_of: impl Fn(&N) -> String,
2770    physical: &mut Vec<D>,
2771) -> Result<Vec<Slot>, GraphError> {
2772    // `free_from[slot]` is the first pass at which the slot is available again.
2773    let mut free_from: Vec<usize> = Vec::new();
2774    let mut slots = Vec::with_capacity(nodes.len());
2775
2776    // Ordered by first use so a single left-to-right sweep is optimal for the
2777    // interval-packing problem this is: identical descriptions, no preemption.
2778    let mut order: Vec<usize> = (0..nodes.len()).collect();
2779    order.sort_by_key(|index| {
2780        spans
2781            .get(*index)
2782            .copied()
2783            .flatten()
2784            .map_or(usize::MAX, |s| s.0)
2785    });
2786
2787    slots.resize(nodes.len(), Slot::Imported);
2788    for index in order {
2789        let Some(desc) = desc_of(&nodes[index]) else {
2790            continue;
2791        };
2792        let Some((first, last)) = spans.get(index).copied().flatten() else {
2793            return Err(GraphError::UnusedTransient {
2794                resource: label_of(&nodes[index]),
2795            });
2796        };
2797        let reused =
2798            (0..physical.len()).find(|slot| physical[*slot] == desc && free_from[*slot] <= first);
2799        let slot = match reused {
2800            Some(slot) => slot,
2801            None => {
2802                physical.push(desc);
2803                free_from.push(0);
2804                physical.len() - 1
2805            }
2806        };
2807        free_from[slot] = last + 1;
2808        slots[index] = Slot::Transient(slot);
2809    }
2810    Ok(slots)
2811}
2812
2813/// Checks every checkable import against what the last graph left it in.
2814///
2815/// The half of validation that needs the pool, which is why it is not inside
2816/// [`validate`]: everything there is a property of the declarations alone, and
2817/// this is a property of the declarations *and* the frames before them.
2818///
2819/// Every buffer import is checkable and only a [`InitialClaim::Tracked`] image
2820/// is — see [`ImportedBuffer`] for why the asymmetry belongs to the resources
2821/// rather than to this function.
2822///
2823/// Silence for a resource the ledger has never heard of is deliberate and is
2824/// not a hole. The ledger records what a graph left, so an absent entry means no
2825/// graph has left this one in anything — an image an upload put into
2826/// [`ResourceState::ShaderRead`] before any frame ran is the ordinary case, and
2827/// there is no previous frame for the declaration to be wrong about.
2828fn validate_imports(
2829    images: &[ImageNode],
2830    buffers: &[BufferNode],
2831    pool: &TransientPool,
2832) -> Result<(), GraphError> {
2833    for node in images {
2834        let ImageSource::Imported(imported) = node.source else {
2835            continue;
2836        };
2837        if imported.claim != InitialClaim::Tracked {
2838            continue;
2839        }
2840        let Some(left) = pool.imported_image_use(imported.image) else {
2841            continue;
2842        };
2843        if left != imported.initial {
2844            return Err(GraphError::ImportStateMismatch {
2845                resource: node.label.clone(),
2846                declared: imported.initial,
2847                left,
2848            });
2849        }
2850    }
2851    for node in buffers {
2852        let BufferSource::Imported(imported) = node.source else {
2853            continue;
2854        };
2855        let Some(left) = pool.imported_buffer_use(imported.buffer) else {
2856            continue;
2857        };
2858        if left != imported.initial {
2859            return Err(GraphError::BufferImportStateMismatch {
2860                resource: node.label.clone(),
2861                declared: imported.initial,
2862                left,
2863            });
2864        }
2865    }
2866    Ok(())
2867}
2868
2869fn validate(
2870    images: &[ImageNode],
2871    buffers: &[BufferNode],
2872    passes: &[Pass<'_>],
2873) -> Result<(), GraphError> {
2874    for pass in passes {
2875        let mut seen_depth = false;
2876        for (position, access) in pass.images.iter().enumerate() {
2877            if pass.kind != PassKind::Render && access.attachment.is_some() {
2878                return Err(GraphError::AttachmentOutsideRenderPass {
2879                    kind: pass.kind.name(),
2880                    pass: pass.label.clone(),
2881                    resource: images[access.image.index()].label.clone(),
2882                });
2883            }
2884            if matches!(access.attachment, Some(Attachment::Depth { .. })) {
2885                if seen_depth {
2886                    return Err(GraphError::DuplicateDepthAttachment {
2887                        pass: pass.label.clone(),
2888                    });
2889                }
2890                seen_depth = true;
2891            }
2892            // A transient states how many levels and layers it has, so a range
2893            // naming one it does not is a mistake the graph can name here
2894            // rather than a barrier on nothing three passes later. An import
2895            // does not say, so there is nothing to check.
2896            if let (Some(range), ImageSource::Transient(desc)) =
2897                (access.range, images[access.image.index()].source)
2898            {
2899                let mip_levels = desc.mip_levels.max(1);
2900                let mips_ok = range.mip_count == ImageSubresourceRange::ALL
2901                    || range.base_mip.saturating_add(range.mip_count) <= mip_levels;
2902                let layers_ok = range.layer_count == ImageSubresourceRange::ALL
2903                    || range.base_layer.saturating_add(range.layer_count) <= TRANSIENT_LAYERS;
2904                if !mips_ok || !layers_ok || range.base_mip >= mip_levels {
2905                    return Err(GraphError::SubresourceOutOfRange {
2906                        pass: pass.label.clone(),
2907                        resource: images[access.image.index()].label.clone(),
2908                        base_mip: range.base_mip,
2909                        mip_count: range.mip_count,
2910                        base_layer: range.base_layer,
2911                        layer_count: range.layer_count,
2912                        mip_levels,
2913                        layers: TRANSIENT_LAYERS,
2914                    });
2915                }
2916            }
2917            for other in &pass.images[position + 1..] {
2918                if other.image != access.image {
2919                    continue;
2920                }
2921                if other.state != access.state {
2922                    return Err(GraphError::ConflictingAccess {
2923                        pass: pass.label.clone(),
2924                        resource: images[access.image.index()].label.clone(),
2925                        first: access.state,
2926                        second: other.state,
2927                    });
2928                }
2929                if other.range == access.range {
2930                    return Err(GraphError::DuplicateDeclaration {
2931                        pass: pass.label.clone(),
2932                        resource: images[access.image.index()].label.clone(),
2933                    });
2934                }
2935            }
2936        }
2937        for (position, access) in pass.buffers.iter().enumerate() {
2938            for other in &pass.buffers[position + 1..] {
2939                if other.buffer != access.buffer {
2940                    continue;
2941                }
2942                if other.state != access.state {
2943                    return Err(GraphError::ConflictingAccess {
2944                        pass: pass.label.clone(),
2945                        resource: buffers[access.buffer.index()].label.clone(),
2946                        first: access.state,
2947                        second: other.state,
2948                    });
2949                }
2950                return Err(GraphError::DuplicateDeclaration {
2951                    pass: pass.label.clone(),
2952                    resource: buffers[access.buffer.index()].label.clone(),
2953                });
2954            }
2955        }
2956    }
2957    Ok(())
2958}
2959
2960fn render_area(images: &[ImageNode], pass: &Pass<'_>) -> Result<Rect2d, GraphError> {
2961    if pass.kind != PassKind::Render {
2962        return Ok(Rect2d::from_size(0, 0));
2963    }
2964    let mut area: Option<(&str, (u32, u32))> = None;
2965    for access in &pass.images {
2966        if access.attachment.is_none() {
2967            continue;
2968        }
2969        let node = &images[access.image.index()];
2970        let extent = node.extent();
2971        match area {
2972            None => area = Some((&node.label, extent)),
2973            Some((first, first_extent)) if first_extent != extent => {
2974                return Err(GraphError::AttachmentExtentMismatch {
2975                    pass: pass.label.clone(),
2976                    first: first.to_string(),
2977                    first_extent,
2978                    second: node.label.clone(),
2979                    second_extent: extent,
2980                });
2981            }
2982            Some(_) => {}
2983        }
2984    }
2985    match area {
2986        Some((_, (width, height))) => Ok(Rect2d::from_size(width, height)),
2987        None => Err(GraphError::NoAttachments {
2988            pass: pass.label.clone(),
2989        }),
2990    }
2991}
2992
2993impl TransientBufferDesc {
2994    /// A device-local storage buffer of `size` bytes.
2995    #[must_use]
2996    pub const fn storage(size: u64) -> Self {
2997        Self {
2998            size,
2999            usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_DST),
3000        }
3001    }
3002}