Skip to main content

crcbl_render/
draw_gen.rs

1//! GPU draw generation: the cull dispatch, the draw-argument dispatch, and the
2//! buffers between them.
3//!
4//! ```text
5//!  begin_frame ──▶ cull params (this frame's frustum)
6//!
7//!  add_passes ──┬─ compute "clear-counters" ──▶ cull stats, draw args,
8//!               │                             counts+mesh args
9//!               │                                        │ graph barrier
10//!               ├─ compute "cull"      instances ──▶ survivors | · | · | ·
11//!               │                                 ──▶ cull stats
12//!               │                                        │ graph barrier
13//!               └─ compute "draw-args"
14//!                    bin      survivors ──▶ · | routes | · | ·
15//!                                       ──▶ draw args, counts+mesh args
16//!                    starts   counts    ──▶ · | · | · | run starts
17//!                    scatter  routes    ──▶ · | · | bucket runs | ·
18//!                                       ──▶ draw args
19//!                                                        │ graph barrier
20//!                        the caller's render pass ◀──────┘  IndirectArgument
21//! ```
22//!
23//! `a | b` is one buffer with regions; the passes below say which is which.
24//!
25//! Topic 03 §3.3, both halves: "compute pass:
26//! frustum cull against instance AABBs → compacted visible instance list →
27//! `draw_indexed_indirect` records + count buffer". The first dispatch is
28//! `cull.slang` and the second is `draw_gen.slang`, with `clear_counters.slang`
29//! ahead of both; **there is not one hand-written barrier here** — the three
30//! passes declare what they touch and [`crate::graph`] computes the
31//! transitions, including the one into [`ResourceState::IndirectArgument`] that
32//! the seam calls the single most important barrier in a GPU-driven frame.
33//!
34//! # Buckets, and why the CPU still records a draw at all
35//!
36//! A draw's instances have to be addressable by the vertex stage, and
37//! `mesh.slang`'s header measures the only number the four shader targets agree
38//! about: `SV_InstanceID`, and only while the draw's first instance is zero. So
39//! the arguments cannot be one per visible instance distinguished by a first
40//! instance — that reaches the shader as the instance index on two targets and
41//! as zero on the other two.
42//!
43//! What they are instead is §3.3's 2026-07-27 correction: **a fixed bucket
44//! table**, one argument structure per bucket, with an instance count the GPU
45//! writes and a contiguous run of surviving instance indices the vertex stage
46//! walks. The caller records one indirect call per bucket — a number decided
47//! when the table is built and independent of what the scene holds, which is the
48//! property the whole stage is for.
49//!
50//! Today a bucket is one resident mesh, because the index range in an argument
51//! structure is per draw and instances of two meshes cannot share one. The
52//! `(material template, permutation, pass)` bucket the correction describes is
53//! the same table with a longer key.
54//!
55//! # The counters a dispatch zeroes, and why it is a dispatch
56//!
57//! Both shaders only ever *add*: the cull pass's survivor counter, each bucket's
58//! instance count and the y extent of its mesh dispatch are atomics, and an
59//! argument buffer left holding last frame's totals would draw last frame's
60//! scene twice over. Something has to zero them.
61//!
62//! The run starts and the routes are **not** among them, and need not be: the
63//! draw-argument pass writes every start and every route it later reads in the
64//! same frame, before it reads them. Only a counter reads what it adds to.
65//!
66//! The seam has a fill for exactly this — `CommandEncoder::fill_buffer`, "the
67//! idiomatic way to zero an indirect count buffer" — and it is unusable here
68//! twice over. A fill is legal only *outside* a pass, and a render-graph frame
69//! is passes end to end; and `crcbl-dx12` refuses one outright — a deliberate
70//! non-fix argued at its `fill_buffer`, D3D12's fill being
71//! `ClearUnorderedAccessViewUint` over a descriptor from a shader-visible heap.
72//! The first reason is the one that binds here regardless of what any backend
73//! decides: a frame of passes has nowhere to put a fill.
74//!
75//! So the zero is a dispatch of its own, `clear_counters.slang`, scheduled
76//! ahead of the cull pass by [`DrawGen::add_passes`] like any other producer —
77//! and the barrier between its write and the cull pass's first atomic is the
78//! graph's, computed from what the two declare. Every backend that can run the
79//! two passes this zeroes for can run this one, which a fill is not true of.
80//!
81//! **Every buffer here a shader writes is therefore
82//! [`MemoryLocation::DeviceLocal`]**, which is not a tidiness point: D3D12 has
83//! no unordered-access view of an upload-heap resource at all — the flag is
84//! rejected at creation and the heap pins the resource to `GENERIC_READ` for
85//! its lifetime — so the counters being host-visible and bound writable is what
86//! took its device down. That rule is about the *binding*, not the frequency:
87//! topic 25's hysteresis state is written once a frame by
88//! `draw_gen.slang` and is device-local for the same reason the counters are,
89//! even though nothing zeroes it per frame. What does zero it is a start-up
90//! copy, on [`crate::mesh_pool`]'s and [`crate::texture`]'s terms — see
91//! [`DrawGen::group_state`] for why zeroing it twice would be worse than not
92//! zeroing it at all. Read-only bindings are untouched by any of this, and the
93//! tables beside it stay host-visible.
94//!
95//! The ones the clearing pass owns carry [`BufferUsage::TRANSFER_DST`] as well
96//! as `TRANSFER_SRC`, and for the same reason: a buffer only ever written by a
97//! shader is one nothing can poison, and a test that cannot poison a counter
98//! cannot tell a zero this pass wrote from the zero the allocation came with.
99//! `crcbl-vk`'s `draw_gen` end-to-end fills them with a sentinel before the
100//! frame.
101//!
102//! # The overflow is visible, and it is not silent
103//!
104//! `cull.slang`'s counter is the *true* survivor count and can exceed the
105//! visible list's capacity; `draw_gen.slang` clamps before it indexes anything
106//! and generates draws for the prefix that fit. [`DrawGen::visible_capacity`] is
107//! what a caller sizes against, and the counter is where a scene that outgrew it
108//! says so.
109//!
110//! # The runs share one region, so a run's start is decided per frame
111//!
112//! **A bucket's run is not a region of its own.** Every bucket used to reserve a
113//! whole [`DrawGenDesc::instance_capacity`] of `u32`, which can never overflow
114//! and made the survivors-and-runs buffer `capacity * (1 + buckets)` words — per
115//! frame in flight, per generator, and a renderer holds a generator per camera,
116//! cascade, shadow light slot and secondary view. In a game scene of 17219
117//! instances and 938 buckets that was 61.7 MiB a buffer and about 864 MiB a
118//! renderer, and it ran a 2 GiB device out of memory.
119//!
120//! A survivor lands in exactly one bucket, so the runs between them hold what the
121//! survivor list does, and the buffer is now **one capacity of runs** beside the
122//! list — plus a capacity of routes and a word per bucket, for the reasons below.
123//! [`draw_gen::runs_at`] has the table, and [`draw_gen::runs_words`] is the size;
124//! `tests::the_measured_scene_pays_a_word_per_bucket_rather_than_a_capacity`
125//! works the same scene through both formulas.
126//!
127//! What that costs is that where a run starts depends on how many survivors the
128//! buckets in front of it took, which the GPU learns only once every survivor is
129//! counted. So `draw_gen.slang` is three entry points dispatched in turn inside
130//! the one `draw-args` pass — route and count each survivor, prefix-sum the
131//! counts into starts, scatter each survivor at its bucket's start — and that
132//! shader's header argues each. The **routes** are the capacity the buffer grew
133//! by: a parallel scatter reads each survivor's bucket while writing the runs,
134//! so the two cannot be one region.
135//!
136//! **And the geometry stages read the start rather than being told it.** The
137//! `DrawConstants` block a draw binds is written once at build, and the draw's
138//! first instance is the one number the four shader targets disagree about, so
139//! neither can carry a per-frame start; the vertex stage's storage bindings are
140//! spent. So the starts are a region of the buffer the stages already read, and
141//! the block names **the word** a bucket's start is in —
142//! [`DrawGen::bucket_start_word`], fixed at build. `mesh.slang`'s header is where
143//! that is argued in full.
144//!
145//! # Buffers here are shared, and the accessors are views rather than allocations
146//!
147//! **The draw-argument pass binds eight storage buffers**, which is what a
148//! WebGPU device guarantees per shader stage — see `shaders/draw_gen.slang`'s
149//! header, which is where the merges and their costs are argued. It bound
150//! fourteen until 2026-08 and could therefore not be created on a browser at the
151//! default limits, nor on SwiftShader, which is every CI runner without a GPU.
152//!
153//! The consequence for a caller is that several of the accessors below **hand
154//! back the same buffer**:
155//!
156//! * [`DrawGen::visible`] and [`DrawGen::runs`] are one buffer. The survivor
157//!   list is at offset zero, and bucket `b`'s run starts at the word this frame
158//!   wrote into word [`DrawGen::bucket_start_word`]`(b)` of it — an absolute
159//!   word index, so a reader multiplies that by four too.
160//! * [`DrawGen::counts`] and [`DrawGen::mesh_args`] are one buffer. The counts
161//!   are at offset zero and bucket `b`'s dispatch extents at
162//!   [`DrawGen::mesh_args_offset`]`(b)`.
163//! * Every host-written table — the bucket table, its per-bucket material
164//!   modes, the per-bucket cluster counts, topic 25's three
165//!   selection tables and the `(mesh, mode) → bucket` lookup built from the
166//!   first two — is one buffer, packed by
167//!   [`crcbl_shaders::draw_gen::pack_tables`].
168//!
169//! So a reader that copies a region back must take its offset from the accessor
170//! that names it. Reading at zero because a region used to be its own allocation
171//! reads the region in front of it, and the words it finds there are plausible
172//! `u32`s.
173
174use std::sync::atomic::{AtomicU32, Ordering};
175
176use crcbl_hal::{
177    Barriers, BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc,
178    BindGroupLayoutEntry, BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource,
179    BufferBarrier, BufferCopy, BufferDesc, BufferHandle, BufferUsage, CommandEncoderDesc,
180    ComputePipelineDesc, ComputePipelineHandle, Device, HalError, ImageViewType, MemoryLocation,
181    PipelineLayoutDesc, PipelineLayoutHandle, QueueHandle, ResourceState, SampleType, ShaderEntry,
182    ShaderModuleDesc, ShaderStages, SubmitInfo, check_portable_storage_buffers,
183};
184use crcbl_shaders::draw_gen::DrawMode;
185use crcbl_shaders::{
186    CLEAR_COUNTERS, CULL, DRAW_GEN, Stage, clear_counters, cull as cull_shader, draw_gen,
187};
188use glam::Mat4;
189
190use crate::cull::{FacePlanes, Frustum};
191use crate::graph::{BufferId, ImageId, ImportedBuffer, RenderGraph};
192
193// `startsMain` is one workgroup of this size on every device, so it has to fit
194// the smallest workgroup any backend promises.
195const _: () = assert!(
196    draw_gen::STARTS_WORKGROUP_SIZE
197        <= crcbl_hal::Limits::minimum().max_compute_invocations_per_workgroup
198        && draw_gen::STARTS_WORKGROUP_SIZE
199            <= crcbl_hal::Limits::minimum().max_compute_workgroup_size[0]
200);
201
202/// How large a [`DrawGen`] is, and what it draws.
203#[derive(Clone, Copy, Debug)]
204pub struct DrawGenDesc<'a> {
205    /// Debug name; every buffer is named after it.
206    pub label: Option<&'a str>,
207    /// The instance array, one buffer per frame in flight — the ring
208    /// [`crate::instance_pool::InstancePool::buffers`] hands out. Its length is
209    /// how many frames this keeps state for.
210    pub instances: &'a [BufferHandle],
211    /// The mesh table both dispatches resolve ranges and bounds out of.
212    pub mesh_table: BufferHandle,
213    /// Which mesh each bucket draws, as an index into the mesh table, in bucket
214    /// order. One entry per indirect call the caller will record.
215    pub bucket_meshes: &'a [u32],
216    /// Which material **mode** each bucket draws, in the same order — the other
217    /// half of a bucket's routing key.
218    ///
219    /// [`GpuMaterial::mode`](crcbl_shaders::mesh::GpuMaterial::mode) of the rows
220    /// the scene holds, and the scatter sends an instance to the bucket matching
221    /// its mesh *and* the mode its own record carries. So one mesh drawn by an
222    /// opaque material and by a cutout one is two buckets, and the depth prepass
223    /// and the shadow atlas bind a pipeline per bucket instead of one per frame.
224    ///
225    /// The same length as [`bucket_meshes`](Self::bucket_meshes). All zeroes for
226    /// a scene whose materials are all opaque, which is every demo in this tree:
227    /// one bucket per mesh, and the region costs one word each.
228    pub bucket_modes: &'a [u32],
229    /// How many clusters each bucket's mesh has, in the same order — the x
230    /// extent of that bucket's mesh dispatch, and the only word of the
231    /// mesh-dispatch arguments — see [`DrawGen::mesh_args`] — the GPU does not
232    /// decide.
233    ///
234    /// **Zero on every geometry path with no mesh stage**, where nothing reads
235    /// those arguments. It is still the same length as
236    /// [`bucket_meshes`](Self::bucket_meshes): the pass writes one structure
237    /// per bucket whatever the path, exactly as it writes one draw argument
238    /// per bucket.
239    pub bucket_clusters: &'a [u32],
240    /// Where each bucket's mesh's clusters start in the cluster pool, in the
241    /// same order — [`TableOffsets::bucket_cluster_bases_at`]'s region, which
242    /// this pass packs and never reads.
243    ///
244    /// **Zero on every geometry path with no mesh stage**, like
245    /// [`bucket_clusters`](Self::bucket_clusters), and the same length as
246    /// [`bucket_meshes`](Self::bucket_meshes).
247    ///
248    /// [`TableOffsets::bucket_cluster_bases_at`]: draw_gen::TableOffsets::bucket_cluster_bases_at
249    pub bucket_cluster_bases: &'a [u32],
250    /// Where each mesh's cluster DAG is, **indexed by mesh id** — so this is
251    /// parallel to the mesh table and long enough for every id an instance can
252    /// name, not one entry per bucket.
253    ///
254    /// [`MeshLevels::FLAT`](crcbl_shaders::level_select::MeshLevels::FLAT) with
255    /// its `first_level` filled in is what an entry
256    /// for a mesh with no hierarchy holds, and it is also what a caller whose
257    /// geometry path selects per cluster hands over for every mesh — see
258    /// `crcbl_shaders::level_select`, which is where that arrangement is written
259    /// down.
260    pub mesh_levels: &'a [crcbl_shaders::level_select::MeshLevels],
261    /// Every mesh's DAG groups end to end, in the order `mesh_levels` points
262    /// into. Empty where nothing has a hierarchy.
263    pub level_groups: &'a [crcbl_shaders::level_select::LevelGroup],
264    /// Which mesh draws which level: element `first_level + d` of a mesh's run
265    /// is the mesh id of its level `d`.
266    pub level_meshes: &'a [u32],
267    /// Instances the pool this culls can hold.
268    ///
269    /// Sizes the visible list, its routes, and the one run region every bucket
270    /// shares, which is what makes a bucket unable to overflow: at most this
271    /// many instances survive, and they are spread across the buckets rather
272    /// than duplicated into each — see the module docs.
273    ///
274    /// It also sizes topic 25's hysteresis state, which is one word
275    /// per (instance slot, group) — see [`DrawGen::group_state`].
276    pub instance_capacity: u32,
277    /// The [`GpuInstance::flags`](crcbl_shaders::mesh::GpuInstance::flags) bit
278    /// that removes an instance from this cull, written into every frame's cull
279    /// parameters.
280    ///
281    /// One bit of
282    /// [`GpuInstance::HIDDEN_VIEWS_MASK`](crcbl_shaders::mesh::GpuInstance::HIDDEN_VIEWS_MASK)
283    /// for a generator that culls for a camera, and
284    /// [`GpuInstance::CASTS_NO_SHADOW`](crcbl_shaders::mesh::GpuInstance::CASTS_NO_SHADOW)
285    /// for one that culls for no view — a shadow cascade's or a shadowed
286    /// light's — so an instance a camera hides still casts its shadow and one
287    /// told not to cast does not. Zero rejects nothing on it.
288    pub hidden_view: u32,
289    /// The most a frame of this generator may ask for, which decides what it
290    /// allocates: [`DrawMode::Plain`] is region 0 alone, as every generator was;
291    /// [`DrawMode::Occlusion`] adds the two occlusion regions and the three
292    /// occlusion pipelines; [`DrawMode::Faces`] adds six face regions and six
293    /// capacities of face runs.
294    ///
295    /// A frame may always run [`DrawMode::Plain`] instead — see
296    /// [`DrawGen::begin_frame_with`].
297    pub mode: DrawMode,
298    /// How many (cluster, instance slot) pairs one task workgroup of the mesh
299    /// tail decides — [`draw_gen::Params::task_lanes`].
300    ///
301    /// [`TASK_LANES`](crcbl_shaders::meshlet::TASK_LANES) for a caller drawing
302    /// behind `mesh_cluster.slang`'s amplification stage, which then reads
303    /// each bucket's mesh-dispatch extents as
304    /// [`task_extents`](crcbl_shaders::meshlet::task_extents). **Zero for every
305    /// other caller**, including a mesh path with no task stage: its
306    /// `meshMain` launches one workgroup per pair from the
307    /// `(clusters, instances, 1)` extents zero leaves in place.
308    pub task_lanes: u32,
309}
310
311/// [`DrawGen::frame_modes`]' word for a frame that dispatches the occlusion
312/// entry point for its small-feature test alone and scatters plainly — past
313/// every [`DrawMode`] word.
314const SMALL_FEATURE_ONLY: u32 = 3;
315
316/// The eye and the budgets a frame's level of detail is selected under — the two
317/// numbers [`DrawGen::begin_frame`] takes beside the frustum, as one value for
318/// [`DrawGen::begin_frame_with`].
319#[derive(Clone, Copy, Debug, PartialEq)]
320pub struct Selection {
321    /// The eye, in world space — [`draw_gen::Params::camera_position`].
322    pub camera_position: [f32; 3],
323    /// Pixels per unit and the two budgets — [`draw_gen::Params::lod_params`].
324    pub lod_params: [f32; 3],
325}
326
327/// What one frame's cull does beyond the frustum — handed to
328/// [`DrawGen::begin_frame_with`].
329#[derive(Clone, Copy, Debug)]
330pub enum FrameCull<'a> {
331    /// The frustum and nothing else, into region 0.
332    Plain,
333    /// A point light's cull: the frustum is the light's box, and each survivor
334    /// is tagged with the faces whose side planes it reaches and scattered into
335    /// each of those faces' regions. Needs a [`DrawMode::Faces`] generator.
336    Faces(&'a FacePlanes),
337    /// The camera's two-phase occlusion and small-feature culls. Needs a
338    /// [`DrawMode::Occlusion`] generator.
339    Occlusion(OcclusionFrame),
340}
341
342/// The camera's half of an occlusion frame — see [`FrameCull::Occlusion`].
343#[derive(Clone, Copy, Debug, PartialEq)]
344pub struct OcclusionFrame {
345    /// This frame's world → clip.
346    pub view_projection: Mat4,
347    /// The previous frame's, which the first phase reprojects through.
348    pub previous_view_projection: Mat4,
349    /// The depth prepass's extent, which is level 0 of the pyramid.
350    pub target: (u32, u32),
351    /// Levels of the farthest-depth pyramid, from
352    /// [`occlusion_cull::levels_for`](crate::occlusion_cull::levels_for).
353    pub pyramid_levels: u32,
354    /// Whether the two phases run at all. With this off the frame is
355    /// [`DrawMode::Plain`] and only the small-feature test is added.
356    pub occlusion: bool,
357    /// Whether the pyramid holds the previous frame at this extent, so the first
358    /// phase may test against it. Off, every survivor is drawn early.
359    pub history: bool,
360    /// The small-feature threshold in pixels, or `None` where it is off.
361    pub small_feature_pixels: Option<f32>,
362}
363
364/// The farthest-depth pyramid a frame's occlusion passes read — see
365/// [`DrawGen::add_occlusion_passes`].
366#[derive(Clone, Copy, Debug)]
367pub struct PyramidInputs<'p> {
368    /// Every distinct level image, as the graph knows it, so the two culls can
369    /// declare their reads and the reduction passes their writes.
370    pub levels: &'p [ImageId],
371    /// The group naming those images at the slots `cull.slang` declares in set
372    /// 1, built against [`DrawGen::occlusion_layout`].
373    pub group: BindGroupHandle,
374}
375
376/// What one frame's generated draws live in.
377///
378/// Returned by [`DrawGen::add_passes`] and consumed by the caller's render
379/// pass, which needs both halves: the [`BufferId`]s to declare its reads with,
380/// so the graph transitions them, and the handles to name in the indirect call
381/// itself.
382#[derive(Clone, Copy, Debug)]
383pub struct GeneratedDraws {
384    /// The indirect arguments, [`draw_gen::DRAW_ARGS_SIZE`] bytes per bucket.
385    ///
386    /// **A buffer of its own**, unlike the counts and dispatch extents below,
387    /// and for the one reason that survives the storage-buffer squeeze the module
388    /// docs describe: the mesh path reads these as a shader read in the same pass
389    /// that executes those as indirect arguments, and a resource is in one state
390    /// at a time.
391    pub args: BufferHandle,
392    /// The same buffer as the graph knows it. Declare it in
393    /// [`ResourceState::IndirectArgument`], or as a shader read on the mesh path.
394    pub args_id: BufferId,
395    /// The per-bucket draw counts **and** the per-bucket mesh-dispatch
396    /// arguments, in that order, in one buffer.
397    ///
398    /// At [`DrawGen::count_offset`]`(b)` is bucket `b`'s `u32` draw count: `1`
399    /// for a bucket with something in it and `0` for one without, which is what
400    /// [`GeometryPath::IndirectCount`](crcbl_hal::GeometryPath::IndirectCount)'s
401    /// call reads. At [`DrawGen::mesh_args_offset`]`(b)` are its
402    /// [`draw_gen::MESH_ARGS_SIZE`] bytes of `(clusters, surviving instances,
403    /// 1)` — or, where [`DrawGenDesc::task_lanes`] is non-zero,
404    /// [`task_extents`](crcbl_shaders::meshlet::task_extents) of those two —
405    /// which is what
406    /// [`CommandEncoder::draw_mesh_tasks_indirect`](crcbl_hal::CommandEncoder::draw_mesh_tasks_indirect)
407    /// reads on
408    /// [`GeometryPath::MeshShader`](crcbl_hal::GeometryPath::MeshShader).
409    ///
410    /// One buffer because no pass reads both: the two indirect tails execute the
411    /// counts and the mesh path executes the extents, so it is in
412    /// [`ResourceState::IndirectArgument`] either way and never in two states at
413    /// once.
414    pub counts: BufferHandle,
415    /// The same buffer as the graph knows it. Declare it in
416    /// [`ResourceState::IndirectArgument`] — **once**, whichever region the
417    /// pass reads.
418    pub counts_id: BufferId,
419    /// Byte offset in [`counts`](Self::counts) of region 0's first flat task
420    /// dispatch: behind every region this generator allocates, one
421    /// [`draw_gen::MESH_ARGS_SIZE`] structure per
422    /// [flat segment](draw_gen::flat_segment) a region, which is where a flat
423    /// call's arguments are — see [`DrawGen::flat_args_offset`]. Per generator
424    /// rather than per renderer, because it sits behind however many regions
425    /// the generator was built with.
426    pub flat_args_offset: u64,
427    /// `cull.slang`'s survivor list, each survivor's route, the per-bucket runs
428    /// of surviving instance indices the vertex stage reads, and where each run
429    /// starts this frame, in that order, in one buffer. Declare it as a shader
430    /// read.
431    ///
432    /// A pass that draws reads only the starts and the runs: bucket `b`'s start
433    /// at word [`DrawGen::bucket_start_word`]`(b)` — which is the number
434    /// [`DrawConstants::start_at`](crcbl_shaders::mesh::DrawConstants::start_at)
435    /// carries — and then the run from the word that start names.
436    pub runs_id: BufferId,
437    /// Topic 25's hysteresis state, as the graph knows it.
438    ///
439    /// Here because a caller whose geometry path has an amplification stage
440    /// **reads** it: `mesh_cluster.slang` looks up the two groups a cluster
441    /// names, so the pass that runs it declares [`ResourceState::ShaderRead`] on
442    /// this id and the graph orders that read after the draw-argument pass's
443    /// write. A caller on a path with no amplification stage declares nothing,
444    /// and the state is then written and read by that pass alone.
445    pub group_state_id: BufferId,
446    /// The frame's culling statistics, as the graph knows them — the buffer
447    /// [`DrawGen::visible_count`] hands out.
448    ///
449    /// Here because §3.5's amplification stage **writes** it: it counts
450    /// surviving clusters into
451    /// [`CLUSTER_SURVIVOR_WORD`](crcbl_shaders::cull::CLUSTER_SURVIVOR_WORD),
452    /// so the pass that runs it declares
453    /// [`ResourceState::ShaderReadWrite`] on this id and the graph orders that
454    /// write after the draw-argument pass's read. A caller on a geometry path
455    /// with no amplification stage declares nothing and the counter keeps the
456    /// zero the clearing pass wrote.
457    pub visible_count_id: BufferId,
458}
459
460/// The cull and draw-argument dispatches, and everything they need.
461#[derive(Debug)]
462pub struct DrawGen {
463    /// Every host-written table `draw_gen.slang` reads, in one buffer: the
464    /// bucket table, the per-bucket cluster counts and topic 25's
465    /// three selection tables.
466    ///
467    /// **Written once**, which is what makes the merge sound rather than merely
468    /// convenient: all five are decided when a mesh becomes resident and none is
469    /// rewritten per frame, so they change together or not at all.
470    /// [`crcbl_shaders::draw_gen::pack_tables`] is what lays them out and
471    /// [`table_offsets`](Self::table_offsets) is where each region starts.
472    tables: BufferHandle,
473    /// Where each region of [`tables`](Self::tables) begins, as the four words
474    /// [`draw_gen::Params`] carries into the shader.
475    table_offsets: draw_gen::TableOffsets,
476    /// The two buffer lengths the clearing dispatch zeroes. Shared by every
477    /// frame's group, because both are fixed when the bucket table is built.
478    clear_params: BufferHandle,
479    /// Topic 25's hysteresis state: one word per (instance slot,
480    /// group), holding whether that instance had that group expanded.
481    ///
482    /// **One buffer, deliberately not a ring**, and `draw_gen.slang`'s own
483    /// declaration is where that is argued: a frame reads what the last frame
484    /// wrote, an instance the frustum rejected writes nothing at all, and a
485    /// per-frame slot would hand such an instance a state that is neither its
486    /// own nor monotone — which is a crack rather than a stale level. Frames are
487    /// ordered against each other by the graph instead, out of the
488    /// `ShaderReadWrite` both the writing and the reading pass declare on it.
489    ///
490    /// Zeroed at build and never again, which is where the monotonicity
491    /// induction starts — by the start-up copy [`fill_at_start_up`] submits,
492    /// because a shader writes this and a buffer a shader writes cannot be
493    /// host-visible. A second zero anywhere would erase the history rather than
494    /// establish it, so there is deliberately no per-frame clear of it.
495    group_state: BufferHandle,
496    /// How many groups one instance's run of [`group_state`](Self::group_state)
497    /// holds — every resident mesh's group count summed, and at least one so the
498    /// buffer is never zero-length.
499    group_stride: u32,
500
501    // One per frame in flight, indexed by the caller's frame slot.
502    /// The block naming the bucket count, the two capacities and this frame's
503    /// selection camera.
504    ///
505    /// **Ringed since the uniform cut arrived**, where it used to be one shared
506    /// buffer: the camera and the pixel budget change every frame, and a frame
507    /// still in flight is a frame still reading them.
508    gen_params: Vec<BufferHandle>,
509    cull_params: Vec<BufferHandle>,
510    visible_count: Vec<BufferHandle>,
511    /// `cull.slang`'s survivor list, its routes, the per-bucket runs and their
512    /// starts — see the module docs, and [`DrawGen::bucket_start_word`] for where
513    /// a bucket's start is.
514    runs: Vec<BufferHandle>,
515    args: Vec<BufferHandle>,
516    /// The per-bucket draw counts, then the per-bucket mesh-dispatch extents.
517    counts: Vec<BufferHandle>,
518    clear_groups: Vec<BindGroupHandle>,
519    cull_groups: Vec<BindGroupHandle>,
520    gen_groups: Vec<BindGroupHandle>,
521
522    clear_layout: BindGroupLayoutHandle,
523    clear_pipeline_layout: PipelineLayoutHandle,
524    clear_pipeline: ComputePipelineHandle,
525    cull_layout: BindGroupLayoutHandle,
526    cull_pipeline_layout: PipelineLayoutHandle,
527    cull_pipeline: ComputePipelineHandle,
528    gen_layout: BindGroupLayoutHandle,
529    gen_pipeline_layout: PipelineLayoutHandle,
530    /// `draw_gen.slang`'s three entry points, in the order the `draw-args` pass
531    /// dispatches them: route and count, prefix-sum the counts into starts,
532    /// scatter. One layout serves all three.
533    bin_pipeline: ComputePipelineHandle,
534    starts_pipeline: ComputePipelineHandle,
535    scatter_pipeline: ComputePipelineHandle,
536
537    bucket_count: u32,
538    capacity: u32,
539    /// Words in each frame's [`runs`](Self::runs) buffer —
540    /// [`draw_gen::runs_words`], checked once at build.
541    runs_words: u32,
542    hidden_view: u32,
543    /// [`DrawGenDesc::task_lanes`], written into every frame's block.
544    task_lanes: u32,
545    /// What [`DrawGenDesc::mode`] built this for.
546    mode: DrawMode,
547    /// `[frame]`: the mode [`DrawGen::begin_frame_with`] last wrote, as its
548    /// word, so the passes a frame records cannot disagree with the block its
549    /// dispatches read.
550    frame_modes: Vec<AtomicU32>,
551    /// The occlusion entry points, on a [`DrawMode::Occlusion`] generator.
552    occlusion: Option<OcclusionPipelines>,
553}
554
555/// The two occlusion phases' cull pipelines and the late draw-argument ones.
556#[derive(Debug)]
557struct OcclusionPipelines {
558    /// Set 1 of the cull layout: the farthest-depth pyramid's levels.
559    pyramid_layout: BindGroupLayoutHandle,
560    /// The cull's set 0 and the pyramid's set 1.
561    cull_pipeline_layout: PipelineLayoutHandle,
562    early: ComputePipelineHandle,
563    late: ComputePipelineHandle,
564    late_scatter: ComputePipelineHandle,
565    late_finish: ComputePipelineHandle,
566}
567
568impl DrawGen {
569    /// Builds both pipelines, both bind groups per frame, and every buffer
570    /// between them.
571    ///
572    /// `queue` carries the one start-up submit this makes: the copy that zeroes
573    /// the hysteresis state, described on
574    /// [`group_state`](Self::group_state) and blocked on before this returns.
575    ///
576    /// # Errors
577    ///
578    /// [`HalError`] from any seam call. A failure part-way through releases
579    /// everything already created, so a caller that gives up leaves nothing
580    /// behind.
581    ///
582    /// # Panics
583    ///
584    /// If `instances` is empty or `bucket_meshes` is: a ring with no buffers has
585    /// nothing to bind, and a table with no buckets generates no draws at all.
586    pub fn new(
587        device: &dyn Device,
588        queue: QueueHandle,
589        desc: &DrawGenDesc<'_>,
590    ) -> Result<Self, HalError> {
591        assert!(
592            !desc.instances.is_empty(),
593            "draw generation needs at least one instance buffer to cull"
594        );
595        assert!(
596            !desc.bucket_meshes.is_empty(),
597            "draw generation with no buckets would generate no draws"
598        );
599        assert_eq!(
600            desc.bucket_modes.len(),
601            desc.bucket_meshes.len(),
602            "one material mode per bucket: a shorter table would key a bucket on a mode that \
603             belongs to another bucket, or to nothing, and the instances meant for it would \
604             scatter nowhere and never be drawn"
605        );
606        assert_eq!(
607            desc.bucket_clusters.len(),
608            desc.bucket_meshes.len(),
609            "one cluster count per bucket: a shorter table would leave a bucket's mesh dispatch \
610             reading a cluster count that belongs to another bucket, or to nothing"
611        );
612        assert_eq!(
613            desc.bucket_cluster_bases.len(),
614            desc.bucket_meshes.len(),
615            "one cluster base per bucket: a shorter table would leave a range of buckets drawn \
616             in one call reading a cluster base that belongs to another bucket, or to nothing"
617        );
618        let mut rollback = Rollback::default();
619        match Self::build(device, queue, desc, &mut rollback) {
620            Ok(built) => Ok(built),
621            Err(error) => {
622                rollback.run(device);
623                Err(error)
624            }
625        }
626    }
627
628    fn build(
629        device: &dyn Device,
630        queue: QueueHandle,
631        desc: &DrawGenDesc<'_>,
632        rollback: &mut Rollback,
633    ) -> Result<Self, HalError> {
634        let stem = desc.label.unwrap_or("draw generation");
635        let bucket_count = u32::try_from(desc.bucket_meshes.len())
636            .map_err(|_| HalError::InvalidDescriptor("more buckets than a u32".to_string()))?;
637        let capacity = desc.instance_capacity;
638        // **The survivor list carries tags above the index**, so a capacity
639        // reaching them would be instance indices read back as faces or as an
640        // occlusion verdict.
641        if capacity > cull_shader::ENTRY_INDEX_MASK + 1 {
642            return Err(HalError::InvalidDescriptor(format!(
643                "{capacity} instances do not fit the {} a survivor entry indexes below its tags",
644                cull_shader::ENTRY_INDEX_MASK + 1
645            )));
646        }
647        let draw_regions = desc.mode.regions();
648        // Checked here, once, because the shader indexes the whole buffer with a
649        // `uint` and every accessor below does the same arithmetic unchecked.
650        let runs_words = draw_gen::runs_words(capacity, bucket_count, desc.mode == DrawMode::Faces)
651            .ok_or_else(|| {
652                HalError::InvalidDescriptor(format!(
653                    "{capacity} instances and {bucket_count} buckets lay out more survivor and run \
654                 words than a u32 addresses"
655                ))
656            })?;
657
658        let mut buffer = |label: &str, size: u64, usage, memory| -> Result<_, HalError> {
659            let handle = device.create_buffer(&BufferDesc {
660                label: Some(&format!("{stem} {label}")),
661                size,
662                usage,
663                memory,
664            })?;
665            rollback.buffers.push(handle);
666            Ok(handle)
667        };
668
669        // **Every host-written table in one buffer**, because the draw-argument
670        // pass has eight storage bindings to spend and a WebGPU device
671        // guarantees no more — see the module docs. They are packed together
672        // rather than any other set because they are the ones written at build
673        // and never per frame: the bucket table, its material modes, its cluster
674        // counts, and topic 25's three selection tables all follow
675        // residency and nothing else.
676        //
677        // `pack_tables` is what pads an empty selection region out to one zeroed
678        // record, which is the ordinary case for a renderer whose meshes have no
679        // hierarchy — a mesh's `first_level` names element zero of the level
680        // region whether it has a DAG or not.
681        let packed = draw_gen::pack_tables(
682            desc.bucket_meshes,
683            desc.bucket_modes,
684            desc.bucket_clusters,
685            desc.bucket_cluster_bases,
686            desc.mesh_levels,
687            desc.level_groups,
688            desc.level_meshes,
689        )
690        .ok_or_else(|| {
691            HalError::InvalidDescriptor("more table words than a u32 addresses".to_string())
692        })?;
693        let tables = buffer(
694            "tables",
695            packed.bytes.len() as u64,
696            BufferUsage::STORAGE,
697            MemoryLocation::HostUpload,
698        )?;
699        device.write_buffer(tables, 0, &packed.bytes)?;
700        let table_offsets = packed.offsets;
701
702        // Topic 25's hysteresis state. **Zeroed here and by
703        // nothing else ever again**: `draw_gen.slang` reads an element before it
704        // writes it, so what the buffer holds on the very first frame is a real
705        // input, and freshly allocated device memory holds whatever it holds. A
706        // state that is not monotone up a DAG is a cut with a hole in it, so
707        // this is the one write that keeps every later frame's induction
708        // standing.
709        //
710        // Device-local like every other buffer a shader writes here, for the
711        // reason the module docs give: D3D12 has no unordered-access view of an
712        // upload-heap resource. So the zero arrives by a **start-up staging
713        // copy** rather than a `write_buffer` — and not by the clearing
714        // dispatch, which runs inside every frame. Running it twice would erase
715        // exactly the history this buffer exists to carry, and once is what a
716        // copy submitted before the first frame is.
717        //
718        // At least one word per instance even when nothing resident has a
719        // hierarchy, because a zero-length buffer is not a descriptor any
720        // backend binds and both shaders index it unconditionally.
721        let group_stride = u32::try_from(desc.level_groups.len())
722            .map_err(|_| HalError::InvalidDescriptor("more groups than a u32".to_string()))?
723            .max(1);
724        let group_state_bytes = u64::from(capacity) * u64::from(group_stride) * 4;
725        let group_state = buffer(
726            "lod group state",
727            group_state_bytes,
728            BufferUsage::STORAGE | BufferUsage::TRANSFER_DST,
729            MemoryLocation::DeviceLocal,
730        )?;
731        fill_at_start_up(
732            device,
733            queue,
734            &format!("{stem} lod group state"),
735            group_state,
736            &vec![
737                0u8;
738                usize::try_from(group_state_bytes).map_err(|_| HalError::InvalidDescriptor(
739                    format!(
740                        "the lod group state is {group_state_bytes} bytes, which does not \
741                             fit this host's address space"
742                    )
743                ))?
744            ],
745            ResourceState::ShaderReadWrite,
746        )?;
747
748        let clear_params = buffer(
749            "clear params",
750            clear_counters::PARAMS_SIZE as u64,
751            BufferUsage::UNIFORM,
752            MemoryLocation::HostUpload,
753        )?;
754        // The argument buffer's length in words, from the crate that owns the
755        // argument layout — so the clearing shader never re-declares it. Every
756        // region's structures, end to end.
757        let args_words = draw_regions * bucket_count * draw_gen::DRAW_ARGS_WORDS as u32;
758        // The counts-and-extents buffer's: every region's counts and extents,
759        // then every region's flat task dispatches.
760        let counts_words = draw_gen::flat_args_word(bucket_count, draw_regions, draw_regions, 0, 0);
761        device.write_buffer(
762            clear_params,
763            0,
764            &clear_counters::Params {
765                args_words,
766                counts_words: bucket_count,
767                stats_words: cull_shader::STATS_WORDS,
768                // Everything behind region 0's counts: its extents, then every
769                // further region's counts and extents, which alternate, and
770                // the flat task dispatches behind them all.
771                mesh_args_words: counts_words - bucket_count,
772            }
773            .to_bytes(),
774        )?;
775
776        let frames = desc.instances.len();
777        let mut gen_params = Vec::with_capacity(frames);
778        let mut cull_params = Vec::with_capacity(frames);
779        let mut visible_count = Vec::with_capacity(frames);
780        let mut runs = Vec::with_capacity(frames);
781        let mut args = Vec::with_capacity(frames);
782        let mut counts = Vec::with_capacity(frames);
783        for frame in 0..frames {
784            // The static half is written here and the camera half in
785            // `begin_frame`, so a frame that never called it still names the
786            // right bucket count rather than reading a zeroed block.
787            let params = buffer(
788                &format!("params {frame}"),
789                draw_gen::PARAMS_SIZE as u64,
790                BufferUsage::UNIFORM,
791                MemoryLocation::HostUpload,
792            )?;
793            device.write_buffer(
794                params,
795                0,
796                &draw_gen::Params {
797                    bucket_count,
798                    visible_capacity: capacity,
799                    group_stride,
800                    bucket_modes_at: table_offsets.bucket_modes_at,
801                    bucket_clusters_at: table_offsets.bucket_clusters_at,
802                    mesh_levels_at: table_offsets.mesh_levels_at,
803                    level_groups_at: table_offsets.level_groups_at,
804                    level_meshes_at: table_offsets.level_meshes_at,
805                    bucket_lookup_at: table_offsets.bucket_lookup_at,
806                    task_lanes: desc.task_lanes,
807                    flat_segments_at: table_offsets.flat_segments_at,
808                    ..draw_gen::Params::default()
809                }
810                .to_bytes(),
811            )?;
812            gen_params.push(params);
813            cull_params.push(buffer(
814                &format!("cull params {frame}"),
815                cull_shader::PARAMS_SIZE as u64,
816                BufferUsage::UNIFORM,
817                MemoryLocation::HostUpload,
818            )?);
819            // `TRANSFER_SRC` on all four, and it is not there for tidiness:
820            // everything these passes produce is written by a shader and read by
821            // another, so a copy out is the *only* way anything can check that
822            // what they produced is what a CPU would have recorded. `crcbl-vk`'s
823            // `draw_gen` end-to-end does exactly that, and topic 03 §3.6's
824            // culling-stats ring — the one readback the frame loop is allowed —
825            // is the counter below.
826            //
827            // `TRANSFER_DST` on the three the clearing dispatch owns, so a test
828            // can poison them — see the module docs. They are device-local like
829            // everything else here: nothing writes them from the host any more.
830            //
831            // **Two words, not one**, and they belong to different passes: the
832            // cull dispatch counts surviving instances into the first and
833            // `mesh_cluster.slang`'s amplification stage counts surviving
834            // clusters into the second. One buffer keeps §3.6's ring at one
835            // readback — see [`crcbl_shaders::cull::STATS_WORDS`].
836            visible_count.push(buffer(
837                &format!("cull stats {frame}"),
838                u64::from(cull_shader::STATS_WORDS) * 4,
839                BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC | BufferUsage::TRANSFER_DST,
840                MemoryLocation::DeviceLocal,
841            )?);
842            // The survivor list, its routes, the per-bucket runs and their
843            // starts, in that order, in one buffer — see the module docs.
844            // `cull.slang` writes the first `capacity` words and
845            // `draw_gen.slang` the rest; nothing reads a word of one region
846            // through another, and the shader is bound the whole buffer once
847            // because a read-only view of part of it beside a writable view of
848            // the rest is a usage conflict on WebGPU.
849            //
850            // **One capacity of runs however many buckets there are**: a word
851            // per bucket is all the bucket count still costs here.
852            runs.push(buffer(
853                &format!("visible and bucket runs {frame}"),
854                u64::from(runs_words) * 4,
855                BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
856                MemoryLocation::DeviceLocal,
857            )?);
858            args.push(buffer(
859                &format!("draw args {frame}"),
860                u64::from(draw_regions) * u64::from(bucket_count) * draw_gen::DRAW_ARGS_SIZE as u64,
861                BufferUsage::STORAGE
862                    | BufferUsage::INDIRECT
863                    | BufferUsage::TRANSFER_SRC
864                    | BufferUsage::TRANSFER_DST,
865                MemoryLocation::DeviceLocal,
866            )?);
867            // The per-bucket draw counts, then the mesh path's dispatch extents
868            // — one buffer, on the argument buffer's terms exactly: written by
869            // the same pass, zeroed by the same one, and read by a driver rather
870            // than by a shader, so `INDIRECT`, and `TRANSFER_SRC` so a test can
871            // read back what the GPU decided.
872            //
873            // Merged because no pass reads both, so the buffer is never in two
874            // resource states at once — see [`GeneratedDraws::counts`], and the
875            // module docs on why a binding had to go.
876            counts.push(buffer(
877                &format!("draw counts and mesh dispatch args {frame}"),
878                u64::from(counts_words) * 4,
879                BufferUsage::STORAGE
880                    | BufferUsage::INDIRECT
881                    | BufferUsage::TRANSFER_SRC
882                    | BufferUsage::TRANSFER_DST,
883                MemoryLocation::DeviceLocal,
884            )?);
885        }
886
887        // --- the clearing pass ---
888        let clear_entries = [
889            uniform(0),
890            storage(1, false, UINT_STRIDE),
891            storage(2, false, UINT_STRIDE),
892            // The draw counts and the mesh-dispatch extents, one buffer.
893            storage(3, false, UINT_STRIDE),
894        ];
895        let clear_desc = BindGroupLayoutDesc {
896            label: Some("clear counters"),
897            entries: &clear_entries,
898        };
899        check_portable_storage_buffers(clear_desc.label, &[&clear_desc])?;
900        let clear_layout = device.create_bind_group_layout(&clear_desc)?;
901        rollback.bind_group_layouts.push(clear_layout);
902        let clear_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
903            label: Some("clear counters"),
904            bind_group_layouts: &[clear_layout],
905            push_constants: None,
906        })?;
907        rollback.pipeline_layouts.push(clear_pipeline_layout);
908        let clear_pipeline = compute_pipeline(
909            device,
910            "clear counters",
911            &CLEAR_COUNTERS,
912            clear_pipeline_layout,
913            clear_counters::WORKGROUP_SIZE,
914        )?;
915        rollback.pipelines.push(clear_pipeline);
916
917        // --- the cull pass ---
918        //
919        // Binding order is `cull.slang`'s declaration order, which is a rule
920        // rather than a convention: Slang's Metal target hands each resource the
921        // next index in its own table, so a layout that renumbered them would
922        // bind the frustum where the instance array goes. See
923        // `crcbl_shaders`' declaration-order lint.
924        let cull_entries = [
925            uniform(0),
926            // `StructuredBuffer` in the shader, so read-only here: the cull
927            // pass decides what is visible and never edits an instance or a
928            // mesh entry.
929            storage(1, true, crcbl_shaders::mesh::INSTANCE_STRIDE as u32),
930            storage(2, true, crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32),
931            storage(3, false, UINT_STRIDE),
932            storage(4, false, UINT_STRIDE),
933        ];
934        let cull_desc = BindGroupLayoutDesc {
935            label: Some("cull"),
936            entries: &cull_entries,
937        };
938        check_portable_storage_buffers(cull_desc.label, &[&cull_desc])?;
939        let cull_layout = device.create_bind_group_layout(&cull_desc)?;
940        rollback.bind_group_layouts.push(cull_layout);
941        let cull_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
942            label: Some("cull"),
943            bind_group_layouts: &[cull_layout],
944            push_constants: None,
945        })?;
946        rollback.pipeline_layouts.push(cull_pipeline_layout);
947        // Named rather than resolved: `cull.slang` has an entry point per
948        // occlusion phase beside this one.
949        let cull_pipeline = compute_pipeline_entry(
950            device,
951            "cull",
952            &CULL,
953            "computeMain",
954            cull_pipeline_layout,
955            cull_shader::WORKGROUP_SIZE,
956        )?;
957        rollback.pipelines.push(cull_pipeline);
958
959        // --- the draw-argument pass ---
960        //
961        // **Eight storage bindings, which is every one a WebGPU device
962        // guarantees.** There is no headroom here: a ninth is a pass that cannot
963        // be created in a browser at the default limits or on SwiftShader, which
964        // is what a CI runner without a GPU has. `check_portable_storage_buffers`
965        // below is what turns a ninth into a failure here rather than into a
966        // pipeline-layout refusal on somebody else's device.
967        let gen_entries = [
968            uniform(0),
969            // The instance array and the mesh table, read only.
970            storage(1, true, crcbl_shaders::mesh::INSTANCE_STRIDE as u32),
971            storage(2, true, crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32),
972            // The culling statistics, read only: this pass clamps against the
973            // survivor count and adds to nothing.
974            storage(3, true, UINT_STRIDE),
975            // Every host-written table in one buffer, read only: the bucket
976            // table, the per-bucket cluster counts and topic 25's
977            // three selection tables were all decided when a mesh became
978            // resident.
979            storage(4, true, UINT_STRIDE),
980            // The survivor list, its routes, the per-bucket runs and their
981            // starts. Writable, and read through the same descriptor — binding
982            // one buffer read-only *and* writable in one group is a usage
983            // conflict on WebGPU.
984            storage(5, false, UINT_STRIDE),
985            // The indirect arguments.
986            storage(6, false, UINT_STRIDE),
987            // The draw counts and the mesh-dispatch extents.
988            storage(7, false, UINT_STRIDE),
989            // The hysteresis state, read *and* written: this pass is the
990            // only writer, and it reads the previous frame's answer out of
991            // the same element it then overwrites.
992            storage(8, false, UINT_STRIDE),
993        ];
994        let gen_desc = BindGroupLayoutDesc {
995            label: Some("draw args"),
996            entries: &gen_entries,
997        };
998        check_portable_storage_buffers(gen_desc.label, &[&gen_desc])?;
999        let gen_layout = device.create_bind_group_layout(&gen_desc)?;
1000        rollback.bind_group_layouts.push(gen_layout);
1001        let gen_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
1002            label: Some("draw args"),
1003            bind_group_layouts: &[gen_layout],
1004            push_constants: None,
1005        })?;
1006        rollback.pipeline_layouts.push(gen_pipeline_layout);
1007        // Three entry points of one module over the one layout above, which is
1008        // why these are `compute_pipeline_entry`: the route, the prefix sum and
1009        // the scatter share the bucket table's accessors and shaders here have
1010        // no `#include`. Each is pushed as soon as it exists, so a failure on
1011        // the second releases the first.
1012        let bin_pipeline = compute_pipeline_entry(
1013            device,
1014            "draw args bin",
1015            &DRAW_GEN,
1016            "binMain",
1017            gen_pipeline_layout,
1018            draw_gen::WORKGROUP_SIZE,
1019        )?;
1020        rollback.pipelines.push(bin_pipeline);
1021        let starts_pipeline = compute_pipeline_entry(
1022            device,
1023            "draw args starts",
1024            &DRAW_GEN,
1025            "startsMain",
1026            gen_pipeline_layout,
1027            // One workgroup for the whole prefix sum, dispatched once by
1028            // `record_passes`: its invocations split the table into chunks
1029            // and scan the chunk totals in workgroup memory.
1030            draw_gen::STARTS_WORKGROUP_SIZE,
1031        )?;
1032        rollback.pipelines.push(starts_pipeline);
1033        let scatter_pipeline = compute_pipeline_entry(
1034            device,
1035            "draw args scatter",
1036            &DRAW_GEN,
1037            "scatterMain",
1038            gen_pipeline_layout,
1039            draw_gen::WORKGROUP_SIZE,
1040        )?;
1041        rollback.pipelines.push(scatter_pipeline);
1042
1043        // --- the occlusion phases, on a generator built for them ---
1044        let occlusion = if desc.mode == DrawMode::Occlusion {
1045            Some(Self::build_occlusion(
1046                device,
1047                rollback,
1048                cull_layout,
1049                gen_pipeline_layout,
1050            )?)
1051        } else {
1052            None
1053        };
1054
1055        let mut clear_groups = Vec::with_capacity(frames);
1056        let mut cull_groups = Vec::with_capacity(frames);
1057        let mut gen_groups = Vec::with_capacity(frames);
1058        for frame in 0..frames {
1059            let group = device.create_bind_group(&BindGroupDesc {
1060                label: Some("clear counters"),
1061                layout: clear_layout,
1062                entries: &[
1063                    bound(0, clear_params),
1064                    bound(1, visible_count[frame]),
1065                    bound(2, args[frame]),
1066                    bound(3, counts[frame]),
1067                ],
1068                variable_count: None,
1069            })?;
1070            rollback.bind_groups.push(group);
1071            clear_groups.push(group);
1072
1073            // **This frame's slot of every ring, not a shared buffer.** Binding
1074            // one buffer here for every group would undo the ring and put a
1075            // frame's writes where the previous frame is still reading.
1076            let group = device.create_bind_group(&BindGroupDesc {
1077                label: Some("cull"),
1078                layout: cull_layout,
1079                entries: &[
1080                    bound(0, cull_params[frame]),
1081                    bound(1, desc.instances[frame]),
1082                    bound(2, desc.mesh_table),
1083                    // The survivor list is the front of the buffer whose later
1084                    // regions hold the routes, the runs and their starts; this
1085                    // pass writes only the front and `CullParams::capacity` is
1086                    // what bounds it there.
1087                    bound(3, runs[frame]),
1088                    bound(4, visible_count[frame]),
1089                ],
1090                variable_count: None,
1091            })?;
1092            rollback.bind_groups.push(group);
1093            cull_groups.push(group);
1094
1095            let group = device.create_bind_group(&BindGroupDesc {
1096                label: Some("draw args"),
1097                layout: gen_layout,
1098                entries: &[
1099                    bound(0, gen_params[frame]),
1100                    bound(1, desc.instances[frame]),
1101                    bound(2, desc.mesh_table),
1102                    bound(3, visible_count[frame]),
1103                    bound(4, tables),
1104                    bound(5, runs[frame]),
1105                    bound(6, args[frame]),
1106                    bound(7, counts[frame]),
1107                    bound(8, group_state),
1108                ],
1109                variable_count: None,
1110            })?;
1111            rollback.bind_groups.push(group);
1112            gen_groups.push(group);
1113        }
1114
1115        rollback.disarm();
1116        Ok(Self {
1117            tables,
1118            table_offsets,
1119            clear_params,
1120            group_state,
1121            group_stride,
1122            gen_params,
1123            cull_params,
1124            visible_count,
1125            runs,
1126            args,
1127            counts,
1128            clear_groups,
1129            cull_groups,
1130            gen_groups,
1131            clear_layout,
1132            clear_pipeline_layout,
1133            clear_pipeline,
1134            cull_layout,
1135            cull_pipeline_layout,
1136            cull_pipeline,
1137            gen_layout,
1138            gen_pipeline_layout,
1139            bin_pipeline,
1140            starts_pipeline,
1141            scatter_pipeline,
1142            bucket_count,
1143            capacity,
1144            runs_words,
1145            hidden_view: desc.hidden_view,
1146            task_lanes: desc.task_lanes,
1147            mode: desc.mode,
1148            frame_modes: (0..frames).map(|_| AtomicU32::new(0)).collect(),
1149            occlusion,
1150        })
1151    }
1152
1153    /// The pipelines only an occlusion generator has: `cull.slang`'s two phases
1154    /// over the cull's set 0 and the pyramid's set 1, and `draw_gen.slang`'s late
1155    /// scatter and finish over the draw-argument layout.
1156    fn build_occlusion(
1157        device: &dyn Device,
1158        rollback: &mut Rollback,
1159        cull_layout: BindGroupLayoutHandle,
1160        gen_pipeline_layout: PipelineLayoutHandle,
1161    ) -> Result<OcclusionPipelines, HalError> {
1162        // One depth texture per level, in `cull.slang`'s declaration order —
1163        // which is the order Slang's Metal target hands out texture indices in.
1164        let entries: Vec<BindGroupLayoutEntry> = (0..cull_shader::OCCLUSION_MAX_LEVELS)
1165            .map(|binding| BindGroupLayoutEntry {
1166                binding,
1167                visibility: ShaderStages::COMPUTE,
1168                kind: BindingKind::SampledImage {
1169                    view_type: ImageViewType::D2,
1170                    // `Depth`, on `crate::hiz`'s terms: `DepthTexture2D` in the
1171                    // shader, read with `Load` and never through a sampler.
1172                    sample_type: SampleType::Depth,
1173                },
1174                count: 1,
1175                flags: BindingFlags::empty(),
1176            })
1177            .collect();
1178        let pyramid_desc = BindGroupLayoutDesc {
1179            label: Some("occlusion pyramid"),
1180            entries: &entries,
1181        };
1182        check_portable_storage_buffers(pyramid_desc.label, &[&pyramid_desc])?;
1183        let pyramid_layout = device.create_bind_group_layout(&pyramid_desc)?;
1184        rollback.bind_group_layouts.push(pyramid_layout);
1185        let cull_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
1186            label: Some("occlusion cull"),
1187            bind_group_layouts: &[cull_layout, pyramid_layout],
1188            push_constants: None,
1189        })?;
1190        rollback.pipeline_layouts.push(cull_pipeline_layout);
1191        let early = compute_pipeline_entry(
1192            device,
1193            "occlusion early cull",
1194            &CULL,
1195            "occlusionMain",
1196            cull_pipeline_layout,
1197            cull_shader::WORKGROUP_SIZE,
1198        )?;
1199        rollback.pipelines.push(early);
1200        let late = compute_pipeline_entry(
1201            device,
1202            "occlusion late cull",
1203            &CULL,
1204            "lateMain",
1205            cull_pipeline_layout,
1206            cull_shader::WORKGROUP_SIZE,
1207        )?;
1208        rollback.pipelines.push(late);
1209        let late_scatter = compute_pipeline_entry(
1210            device,
1211            "draw args late scatter",
1212            &DRAW_GEN,
1213            "lateScatterMain",
1214            gen_pipeline_layout,
1215            draw_gen::WORKGROUP_SIZE,
1216        )?;
1217        rollback.pipelines.push(late_scatter);
1218        let late_finish = compute_pipeline_entry(
1219            device,
1220            "draw args late finish",
1221            &DRAW_GEN,
1222            "lateFinishMain",
1223            gen_pipeline_layout,
1224            // One workgroup, on `startsMain`'s terms: its invocations split
1225            // the buckets into chunks and scan the two closed regions' task
1226            // chunks in workgroup memory.
1227            draw_gen::STARTS_WORKGROUP_SIZE,
1228        )?;
1229        rollback.pipelines.push(late_finish);
1230        Ok(OcclusionPipelines {
1231            pyramid_layout,
1232            cull_pipeline_layout,
1233            early,
1234            late,
1235            late_scatter,
1236            late_finish,
1237        })
1238    }
1239
1240    /// Buckets in the table, which is how many indirect calls a caller records.
1241    #[must_use]
1242    pub const fn bucket_count(&self) -> u32 {
1243        self.bucket_count
1244    }
1245
1246    /// Instances the visible list holds, and so how many every bucket's run
1247    /// holds between them — see [`DrawGenDesc::instance_capacity`].
1248    #[must_use]
1249    pub const fn visible_capacity(&self) -> u32 {
1250        self.capacity
1251    }
1252
1253    /// Which word of [`DrawGen::runs`] holds where bucket `bucket`'s run starts
1254    /// this frame, as the number `mesh.slang`'s `DrawConstants::start_at`
1255    /// carries.
1256    ///
1257    /// **The word, not the start.** The start is a per-frame number the
1258    /// draw-argument pass writes into this word — an absolute word index into
1259    /// the same buffer, never below [`runs_at`](Self::runs_at) — and the word is
1260    /// fixed at build, which is what lets a constant block written once name it.
1261    /// Past the survivors, their routes and the runs; see the module docs. A
1262    /// reader copying either back multiplies by four.
1263    ///
1264    /// The same for every generator a renderer builds from one bucket table and
1265    /// one capacity, which is what lets one set of constant blocks serve the
1266    /// camera, every shadow cull and every secondary view.
1267    #[must_use]
1268    pub const fn bucket_start_word(&self, bucket: u32) -> u32 {
1269        draw_gen::run_start_word(self.capacity, self.bucket_count, 0, bucket)
1270    }
1271
1272    /// Which word holds where bucket `bucket`'s run of draw region `region`
1273    /// starts this frame — [`bucket_start_word`](Self::bucket_start_word) for a
1274    /// region past 0, on its terms exactly.
1275    ///
1276    /// [`draw_gen::DRAW_REGIONS`] regions of start words are laid out in every
1277    /// generator whatever it allocates, so this is the same for every generator
1278    /// one renderer builds.
1279    #[must_use]
1280    pub const fn region_start_word(&self, region: u32, bucket: u32) -> u32 {
1281        draw_gen::run_start_word(self.capacity, self.bucket_count, region, bucket)
1282    }
1283
1284    /// Which word of [`DrawGen::runs`] holds where bucket `bucket`'s task
1285    /// chunks start in draw region `region` this frame —
1286    /// [`draw_gen::chunk_start_word`], the number
1287    /// [`ClusterDrawConstants::chunk_starts_at`](crcbl_shaders::meshlet::ClusterDrawConstants::chunk_starts_at)
1288    /// carries. `bucket` may be [`bucket_count`](Self::bucket_count), the
1289    /// region's end.
1290    ///
1291    /// The same for every generator one renderer builds, for
1292    /// [`region_start_word`](Self::region_start_word)'s reason.
1293    #[must_use]
1294    pub const fn chunk_start_word(&self, region: u32, bucket: u32) -> u32 {
1295        draw_gen::chunk_start_word(self.capacity, self.bucket_count, region, bucket)
1296    }
1297
1298    /// Byte offset in [`DrawGen::counts`] of flat segment `segment`'s task
1299    /// dispatch in draw region `region` — what a flat call's
1300    /// [`DrawIndirect::offset`](crcbl_hal::DrawIndirect::offset) carries.
1301    /// Behind every region this generator allocates, so it differs between
1302    /// generators of one renderer; [`GeneratedDraws::flat_args_offset`] is
1303    /// region 0's first, handed to the pass that draws them.
1304    #[must_use]
1305    pub const fn flat_args_offset(&self, region: u32, segment: u32) -> u64 {
1306        draw_gen::flat_args_word(self.bucket_count, self.mode.regions(), region, segment, 0) as u64
1307            * 4
1308    }
1309
1310    /// Which word of [`DrawGen::runs`] holds bucket `bucket`'s mesh, as the
1311    /// number `mesh.slang`'s `DrawConstants::mesh_at` carries — filled every
1312    /// frame by the draw-argument pass from the bucket table.
1313    ///
1314    /// The same for every generator one renderer builds, for
1315    /// [`region_start_word`](Self::region_start_word)'s reason.
1316    #[must_use]
1317    pub const fn bucket_mesh_word(&self, bucket: u32) -> u32 {
1318        draw_gen::bucket_mesh_word(self.capacity, self.bucket_count, bucket)
1319    }
1320
1321    /// How far region `region`'s argument structures sit behind region 0's, in
1322    /// bytes — what a draw of that region adds to
1323    /// [`args_offset`](Self::args_offset).
1324    #[must_use]
1325    pub const fn args_region_offset(&self, region: u32) -> u64 {
1326        region as u64 * self.bucket_count as u64 * draw_gen::DRAW_ARGS_SIZE as u64
1327    }
1328
1329    /// How far region `region`'s draw counts and dispatch extents sit behind
1330    /// region 0's, in bytes — what a draw of that region adds to
1331    /// [`count_offset`](Self::count_offset) and
1332    /// [`mesh_args_offset`](Self::mesh_args_offset). A region is one count and
1333    /// one extent structure per bucket, so its counts and its extents move
1334    /// together.
1335    #[must_use]
1336    pub const fn counts_region_offset(&self, region: u32) -> u64 {
1337        region as u64 * self.bucket_count as u64 * (4 + draw_gen::MESH_ARGS_SIZE as u64)
1338    }
1339
1340    /// What [`DrawGenDesc::mode`] built this generator for.
1341    #[must_use]
1342    pub const fn mode(&self) -> DrawMode {
1343        self.mode
1344    }
1345
1346    /// Set 1 of the occlusion cull's layout — the farthest-depth pyramid's
1347    /// levels — which [`PyramidInputs::group`] is built against. `None` on a
1348    /// generator not built for [`DrawMode::Occlusion`].
1349    #[must_use]
1350    pub fn occlusion_layout(&self) -> Option<BindGroupLayoutHandle> {
1351        self.occlusion
1352            .as_ref()
1353            .map(|pipelines| pipelines.pyramid_layout)
1354    }
1355
1356    /// The mode `frame`'s dispatches were parametrised for by the last
1357    /// [`begin_frame_with`](Self::begin_frame_with) on that slot.
1358    ///
1359    /// # Panics
1360    ///
1361    /// If `frame` is not a slot this was built with.
1362    #[must_use]
1363    pub fn frame_mode(&self, frame: usize) -> DrawMode {
1364        match self.frame_modes[frame].load(Ordering::Relaxed) {
1365            SMALL_FEATURE_ONLY => DrawMode::Plain,
1366            word if word == DrawMode::Occlusion.word() => DrawMode::Occlusion,
1367            word if word == DrawMode::Faces.word() => DrawMode::Faces,
1368            _ => DrawMode::Plain,
1369        }
1370    }
1371
1372    /// Whether `frame` dispatches `cull.slang`'s occlusion entry point — the two
1373    /// phases, or the small-feature test alone — and so must be recorded with
1374    /// [`add_occlusion_passes`](Self::add_occlusion_passes).
1375    ///
1376    /// # Panics
1377    ///
1378    /// If `frame` is not a slot this was built with.
1379    #[must_use]
1380    pub fn uses_occlusion_entry(&self, frame: usize) -> bool {
1381        let word = self.frame_modes[frame].load(Ordering::Relaxed);
1382        word == DrawMode::Occlusion.word() || word == SMALL_FEATURE_ONLY
1383    }
1384
1385    /// The first word of the run region in [`DrawGen::runs`] — where bucket
1386    /// zero's run starts in every frame, and the floor of every other start.
1387    #[must_use]
1388    pub const fn runs_at(&self) -> u32 {
1389        draw_gen::runs_at(self.capacity)
1390    }
1391
1392    /// Bytes of each frame's [`DrawGen::runs`] buffer: the survivors, their
1393    /// routes, one capacity of runs and a start word per bucket.
1394    #[must_use]
1395    pub const fn runs_size(&self) -> u64 {
1396        self.runs_words as u64 * 4
1397    }
1398
1399    /// Byte offset of bucket `bucket`'s argument structure.
1400    #[must_use]
1401    pub const fn args_offset(&self, bucket: u32) -> u64 {
1402        bucket as u64 * draw_gen::DRAW_ARGS_SIZE as u64
1403    }
1404
1405    /// Byte offset of bucket `bucket`'s draw count, which is at the front of the
1406    /// buffer [`DrawGen::counts`] hands back.
1407    #[must_use]
1408    pub const fn count_offset(&self, bucket: u32) -> u64 {
1409        bucket as u64 * 4
1410    }
1411
1412    /// Byte offset of bucket `bucket`'s mesh-dispatch argument structure — what
1413    /// [`DrawIndirect::offset`](crcbl_hal::DrawIndirect::offset) carries in the
1414    /// call that reads it.
1415    ///
1416    /// **Past the one draw count per bucket** that shares the buffer, so this is
1417    /// never zero — see the module docs.
1418    #[must_use]
1419    pub const fn mesh_args_offset(&self, bucket: u32) -> u64 {
1420        self.bucket_count as u64 * 4 + bucket as u64 * draw_gen::MESH_ARGS_SIZE as u64
1421    }
1422
1423    /// The buffer of per-bucket instance runs for `frame`, which the drawing
1424    /// pass's bind group names.
1425    ///
1426    /// The same buffer [`DrawGen::visible`] hands back: bucket `bucket`'s run
1427    /// starts at the word this frame wrote into word
1428    /// [`bucket_start_word`](Self::bucket_start_word)`(bucket)`, past the
1429    /// survivor list and its routes.
1430    ///
1431    /// # Panics
1432    ///
1433    /// If `frame` is not a slot this was built with.
1434    #[must_use]
1435    pub fn runs(&self, frame: usize) -> BufferHandle {
1436        self.runs[frame]
1437    }
1438
1439    /// `frame`'s cull parameters — the frustum [`DrawGen::begin_frame`] wrote.
1440    ///
1441    /// # Panics
1442    ///
1443    /// If `frame` is not a slot this was built with.
1444    #[must_use]
1445    pub fn cull_params(&self, frame: usize) -> BufferHandle {
1446        self.cull_params[frame]
1447    }
1448
1449    /// `frame`'s compacted visible list — `cull.slang`'s survivors, as indices
1450    /// into the instance array, in no particular order, in the **first
1451    /// [`visible_capacity`](Self::visible_capacity) words** of the buffer.
1452    ///
1453    /// The same buffer [`DrawGen::runs`] hands back; the routes, the per-bucket
1454    /// runs and their starts follow the survivors in it. See the module docs.
1455    ///
1456    /// # Panics
1457    ///
1458    /// If `frame` is not a slot this was built with.
1459    #[must_use]
1460    pub fn visible(&self, frame: usize) -> BufferHandle {
1461        self.runs[frame]
1462    }
1463
1464    /// `frame`'s culling statistics: surviving instances in
1465    /// [`INSTANCE_SURVIVOR_WORD`](crcbl_shaders::cull::INSTANCE_SURVIVOR_WORD)
1466    /// and surviving clusters in
1467    /// [`CLUSTER_SURVIVOR_WORD`](crcbl_shaders::cull::CLUSTER_SURVIVOR_WORD).
1468    ///
1469    /// **Topic 03 §3.6's culling-stats readback is this buffer, on a delayed
1470    /// ring — the one readback the frame loop is allowed.** Both counters live
1471    /// here rather than in a buffer each so that stays one copy per frame.
1472    ///
1473    /// The instance count is the **true** one, which can exceed
1474    /// [`DrawGen::visible_capacity`] — so it is also where a scene that outgrew
1475    /// the list says so. The cluster count is what §3.5's amplification stage
1476    /// kept, and is zero on every path that has no amplification stage: the two
1477    /// indirect tails, and a device with `Features::MESH_SHADER` and no
1478    /// `Features::TASK_SHADER`.
1479    ///
1480    /// # Panics
1481    ///
1482    /// If `frame` is not a slot this was built with.
1483    #[must_use]
1484    pub fn visible_count(&self, frame: usize) -> BufferHandle {
1485        self.visible_count[frame]
1486    }
1487
1488    /// `frame`'s indirect arguments, [`draw_gen::DRAW_ARGS_SIZE`] bytes per
1489    /// bucket. The same buffer [`GeneratedDraws::args`] names.
1490    ///
1491    /// # Panics
1492    ///
1493    /// If `frame` is not a slot this was built with.
1494    #[must_use]
1495    pub fn args(&self, frame: usize) -> BufferHandle {
1496        self.args[frame]
1497    }
1498
1499    /// `frame`'s per-bucket draw counts, in the **first
1500    /// [`bucket_count`](Self::bucket_count) words** of the buffer
1501    /// [`GeneratedDraws::counts`] names.
1502    ///
1503    /// # Panics
1504    ///
1505    /// If `frame` is not a slot this was built with.
1506    #[must_use]
1507    pub fn counts(&self, frame: usize) -> BufferHandle {
1508        self.counts[frame]
1509    }
1510
1511    /// Every host-written table the draw-argument pass reads, in one buffer —
1512    /// the bucket table, the per-bucket cluster counts and
1513    /// topic 25's three selection tables.
1514    ///
1515    /// Shared by every frame, because all five are decided when a mesh becomes
1516    /// resident. Exposed for the reason the per-frame buffers are: the cluster
1517    /// counts are the only CPU-side half of an extent that is otherwise the
1518    /// GPU's, so a test with no GPU can still check the pass copied each
1519    /// bucket's own — [`table_offsets`](Self::table_offsets) is where each
1520    /// region starts.
1521    #[must_use]
1522    pub fn tables(&self) -> BufferHandle {
1523        self.tables
1524    }
1525
1526    /// Where each region of [`tables`](Self::tables) begins, in words.
1527    #[must_use]
1528    pub const fn table_offsets(&self) -> draw_gen::TableOffsets {
1529        self.table_offsets
1530    }
1531
1532    /// `frame`'s per-bucket mesh-dispatch arguments, at
1533    /// [`mesh_args_offset`](Self::mesh_args_offset)`(bucket)` in the buffer
1534    /// [`GeneratedDraws::counts`] names — the thing a test reads back to see that
1535    /// the extent the mesh path dispatched is the count culling produced rather
1536    /// than the instance pool's size.
1537    ///
1538    /// The same buffer [`DrawGen::counts`] hands back. **Not at offset zero**:
1539    /// the draw counts are in front of it.
1540    ///
1541    /// # Panics
1542    ///
1543    /// If `frame` is not a slot this was built with.
1544    #[must_use]
1545    pub fn mesh_args(&self, frame: usize) -> BufferHandle {
1546        self.counts[frame]
1547    }
1548
1549    /// Topic 25's hysteresis state, for a caller binding it into a
1550    /// mesh pipeline that reads it.
1551    ///
1552    /// One buffer for every frame in flight, unlike everything else here that a
1553    /// caller binds — see [`DrawGen::group_state`](Self::group_state)'s field
1554    /// docs, which is where that is argued.
1555    #[must_use]
1556    pub fn group_state(&self) -> BufferHandle {
1557        self.group_state
1558    }
1559
1560    /// The stride between two instances in that buffer, which is what
1561    /// [`ClusterDrawConstants::group_stride`] has to carry for the amplification
1562    /// stage to index it the same way this pass does.
1563    ///
1564    /// [`ClusterDrawConstants::group_stride`]: crcbl_shaders::meshlet::ClusterDrawConstants::group_stride
1565    #[must_use]
1566    pub const fn group_stride(&self) -> u32 {
1567        self.group_stride
1568    }
1569
1570    /// Writes `frame`'s cull parameters — this frame's frustum, how much of the
1571    /// instance array to test, and the camera topic 25's uniform
1572    /// cut selects a level from.
1573    ///
1574    /// The three counters both dispatches add to are **not** zeroed here: that
1575    /// is the clearing pass [`DrawGen::add_passes`] schedules, and the module
1576    /// docs say why it has to be a dispatch inside the frame rather than a host
1577    /// write before it.
1578    ///
1579    /// Call once per frame, before [`DrawGen::add_passes`], against the frame
1580    /// slot the instance pool rotated to — the buffer written here is the one
1581    /// that slot's bind groups name.
1582    ///
1583    /// `instance_count` is how many elements of the instance array the cull
1584    /// dispatch tests, which is
1585    /// [`InstancePool::slot_count`](crate::instance_pool::InstancePool::slot_count)
1586    /// and **not** its live count: an array with a hole in it still has live
1587    /// instances above the hole.
1588    ///
1589    /// # Errors
1590    ///
1591    /// [`HalError`] if the write failed.
1592    ///
1593    /// # Panics
1594    ///
1595    /// If `frame` is not a slot this was built with.
1596    /// `camera_position` and `lod_params` are the two the drawing pass writes
1597    /// into [`FrameUniforms`](crcbl_shaders::mesh::FrameUniforms) — passed in
1598    /// rather than re-derived here for the reason the frustum is: a pass that
1599    /// selects detail against one camera while another draws is a difference
1600    /// nothing in a frame can see.
1601    ///
1602    /// **Which is why the one caller allowed to break that is a deliberate
1603    /// setting rather than an accident of what was in scope.**
1604    /// [`ForwardRenderer::set_frozen_selection_eye`] hands this a pinned eye
1605    /// while the frame block keeps the live camera, so the cut a reviewer is
1606    /// looking at is the one chosen for somewhere they are no longer standing —
1607    /// which is the only vantage point a cut can be judged from.
1608    ///
1609    /// [`ForwardRenderer::set_frozen_selection_eye`]: crate::ForwardRenderer::set_frozen_selection_eye
1610    pub fn begin_frame(
1611        &self,
1612        device: &dyn Device,
1613        frame: usize,
1614        frustum: &Frustum,
1615        instance_count: u32,
1616        camera_position: [f32; 3],
1617        lod_params: [f32; 3],
1618    ) -> Result<(), HalError> {
1619        self.begin_frame_with(
1620            device,
1621            frame,
1622            frustum,
1623            instance_count,
1624            Selection {
1625                camera_position,
1626                lod_params,
1627            },
1628            &FrameCull::Plain,
1629        )
1630    }
1631
1632    /// [`begin_frame`](Self::begin_frame), with what the cull does beyond the
1633    /// frustum this frame.
1634    ///
1635    /// The mode written here is what [`add_passes`](Self::add_passes) and
1636    /// [`add_occlusion_passes`](Self::add_occlusion_passes) check against, so a
1637    /// frame whose passes disagree with the block its dispatches read is a panic
1638    /// rather than a frame that scatters into regions nothing draws.
1639    ///
1640    /// # Errors
1641    ///
1642    /// [`HalError`] if a write failed.
1643    ///
1644    /// # Panics
1645    ///
1646    /// If `frame` is not a slot this was built with, or `cull` asks for a mode
1647    /// this generator was not built for.
1648    pub fn begin_frame_with(
1649        &self,
1650        device: &dyn Device,
1651        frame: usize,
1652        frustum: &Frustum,
1653        instance_count: u32,
1654        selection: Selection,
1655        cull: &FrameCull<'_>,
1656    ) -> Result<(), HalError> {
1657        let Selection {
1658            camera_position,
1659            lod_params,
1660        } = selection;
1661        let mut params = cull_shader::Params {
1662            planes: frustum.planes.map(|plane| plane.to_array()),
1663            instance_count,
1664            capacity: self.capacity,
1665            hidden_view: self.hidden_view,
1666            ..cull_shader::Params::default()
1667        };
1668        let mode = match cull {
1669            FrameCull::Plain => DrawMode::Plain,
1670            FrameCull::Faces(faces) => {
1671                assert_eq!(
1672                    self.mode,
1673                    DrawMode::Faces,
1674                    "a point light's face culls need a generator built with its face regions"
1675                );
1676                params.features = cull_shader::Features::FACES;
1677                for (face, planes) in faces.iter().enumerate() {
1678                    for (plane, value) in planes.iter().enumerate() {
1679                        params.face_planes[face * cull_shader::FACE_PLANES + plane] =
1680                            value.to_array();
1681                    }
1682                }
1683                DrawMode::Faces
1684            }
1685            FrameCull::Occlusion(occlusion) => {
1686                assert_eq!(
1687                    self.mode,
1688                    DrawMode::Occlusion,
1689                    "the occlusion culls need a generator built with the occlusion regions"
1690                );
1691                let mut features = cull_shader::Features::NONE;
1692                if occlusion.occlusion && occlusion.history {
1693                    features = features.union(cull_shader::Features::OCCLUSION_HISTORY);
1694                }
1695                if occlusion.small_feature_pixels.is_some() {
1696                    features = features.union(cull_shader::Features::SMALL_FEATURE);
1697                }
1698                params.features = features;
1699                params.view_proj = occlusion.view_projection.to_cols_array();
1700                params.previous_view_proj = occlusion.previous_view_projection.to_cols_array();
1701                params.target_extent = [occlusion.target.0, occlusion.target.1];
1702                params.pyramid_levels = occlusion
1703                    .pyramid_levels
1704                    .min(cull_shader::OCCLUSION_MAX_LEVELS);
1705                params.small_feature_pixels = occlusion.small_feature_pixels.unwrap_or(0.0);
1706                if occlusion.occlusion {
1707                    DrawMode::Occlusion
1708                } else {
1709                    DrawMode::Plain
1710                }
1711            }
1712        };
1713        device.write_buffer(
1714            self.gen_params[frame],
1715            0,
1716            &draw_gen::Params {
1717                bucket_count: self.bucket_count,
1718                visible_capacity: self.capacity,
1719                group_stride: self.group_stride,
1720                bucket_modes_at: self.table_offsets.bucket_modes_at,
1721                bucket_clusters_at: self.table_offsets.bucket_clusters_at,
1722                mesh_levels_at: self.table_offsets.mesh_levels_at,
1723                level_groups_at: self.table_offsets.level_groups_at,
1724                level_meshes_at: self.table_offsets.level_meshes_at,
1725                camera_position,
1726                lod_params,
1727                mode,
1728                draw_regions: self.mode.regions(),
1729                face_runs_at: draw_gen::face_runs_at(self.capacity, self.bucket_count),
1730                bucket_lookup_at: self.table_offsets.bucket_lookup_at,
1731                task_lanes: self.task_lanes,
1732                flat_segments_at: self.table_offsets.flat_segments_at,
1733            }
1734            .to_bytes(),
1735        )?;
1736        device.write_buffer(self.cull_params[frame], 0, &params.to_bytes())?;
1737        // A frame whose occlusion culls are off but whose small-feature test is
1738        // on still dispatches the occlusion entry point — it is where that test
1739        // lives — and scatters plainly.
1740        let cull_word = match cull {
1741            FrameCull::Occlusion(occlusion)
1742                if !occlusion.occlusion && occlusion.small_feature_pixels.is_some() =>
1743            {
1744                SMALL_FEATURE_ONLY
1745            }
1746            _ => mode.word(),
1747        };
1748        self.frame_modes[frame].store(cull_word, Ordering::Relaxed);
1749        Ok(())
1750    }
1751
1752    /// The maximum number of passes [`add_passes`](Self::add_passes) adds to a
1753    /// frame: the clear, the cull, and the route, prefix-sum and scatter passes.
1754    ///
1755    /// A ceiling rather than an exact count: a frame that tests no instance
1756    /// omits the cull and scatter passes and adds only the clear, route and
1757    /// prefix-sum ones. This upper bound is what a caller sizing
1758    /// [`PassTimers`](crate::timing::PassTimers) adds up — see
1759    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES).
1760    pub const MAX_PASSES: u32 = 5;
1761
1762    /// How many dispatches [`add_passes`](Self::add_passes) records for a frame
1763    /// that tests at least one instance: the clear, the cull, and the
1764    /// draw-argument pass's route, prefix sum and scatter.
1765    ///
1766    /// One per pass of [`MAX_PASSES`](Self::MAX_PASSES), which is the same
1767    /// number: a frame that tests no instance records neither the cull's nor
1768    /// the scatter's, since a dispatch of no workgroups is one Metal rejects.
1769    pub const DISPATCHES: u32 = 5;
1770
1771    /// Passes [`add_late_passes`](Self::add_late_passes) adds at most: the
1772    /// second occlusion phase, the late scatter and the finish.
1773    pub const LATE_PASSES: u32 = 3;
1774
1775    /// Adds the cull and draw-argument passes to `graph` and returns what the
1776    /// caller's render pass draws from.
1777    ///
1778    /// The barriers between the three — including the transition into
1779    /// [`ResourceState::IndirectArgument`] — are the graph's, computed from the
1780    /// accesses declared here and the ones the caller declares on the
1781    /// [`GeneratedDraws`] ids.
1782    ///
1783    /// # Panics
1784    ///
1785    /// If `frame` is not a slot this was built with.
1786    pub fn add_passes(
1787        &self,
1788        graph: &mut RenderGraph<'_>,
1789        frame: usize,
1790        instance_count: u32,
1791    ) -> GeneratedDraws {
1792        let word = self.frame_modes[frame].load(Ordering::Relaxed);
1793        assert!(
1794            word != DrawMode::Occlusion.word() && word != SMALL_FEATURE_ONLY,
1795            "frame {frame} was begun with the occlusion culls, whose passes are \
1796             `add_occlusion_passes`"
1797        );
1798        self.record_passes(graph, frame, instance_count, None)
1799    }
1800
1801    /// [`add_passes`](Self::add_passes) for a frame
1802    /// [`begin_frame_with`](Self::begin_frame_with) began with
1803    /// [`FrameCull::Occlusion`]: the cull is the first occlusion phase against
1804    /// `pyramid`, which it reads before this frame's reduction passes write it.
1805    ///
1806    /// The draws it returns are the **early** ones — region
1807    /// [`draw_gen::EARLY_REGION`] — until [`add_late_passes`](Self::add_late_passes)
1808    /// has closed the frame; a frame whose occlusion is off and whose
1809    /// small-feature test is on draws region 0 from here directly.
1810    ///
1811    /// # Panics
1812    ///
1813    /// If `frame` is not a slot this was built with, or was not begun with
1814    /// [`FrameCull::Occlusion`].
1815    pub fn add_occlusion_passes(
1816        &self,
1817        graph: &mut RenderGraph<'_>,
1818        frame: usize,
1819        instance_count: u32,
1820        pyramid: &PyramidInputs<'_>,
1821    ) -> GeneratedDraws {
1822        let word = self.frame_modes[frame].load(Ordering::Relaxed);
1823        assert!(
1824            word == DrawMode::Occlusion.word() || word == SMALL_FEATURE_ONLY,
1825            "frame {frame} was not begun with the occlusion culls"
1826        );
1827        let occlusion = self
1828            .occlusion
1829            .as_ref()
1830            .unwrap_or_else(|| unreachable!("begin_frame_with checked the generator's mode"));
1831        self.record_passes(
1832            graph,
1833            frame,
1834            instance_count,
1835            Some((occlusion.early, occlusion.cull_pipeline_layout, pyramid)),
1836        )
1837    }
1838
1839    /// The second occlusion phase and the late draw arguments, after this
1840    /// frame's farthest-depth pyramid has been reduced from the early prepass.
1841    ///
1842    /// Three passes: `cull.slang`'s `lateMain` tests every survivor the first
1843    /// phase marked against `pyramid`, `draw_gen.slang`'s late scatter appends
1844    /// the ones it rescued behind each bucket's early run, and its finish writes
1845    /// region [`draw_gen::LATE_REGION`]'s counts and region 0's — the early and
1846    /// late draws together, which is what the forward pass draws. A frame that
1847    /// tests no instance records the finish alone, because region 0 still needs
1848    /// its zeroes written.
1849    ///
1850    /// # Panics
1851    ///
1852    /// If `frame` is not a slot this was built with, or was not begun with
1853    /// occlusion on.
1854    pub fn add_late_passes(
1855        &self,
1856        graph: &mut RenderGraph<'_>,
1857        frame: usize,
1858        instance_count: u32,
1859        draws: &GeneratedDraws,
1860        pyramid: &PyramidInputs<'_>,
1861    ) {
1862        assert_eq!(
1863            self.frame_modes[frame].load(Ordering::Relaxed),
1864            DrawMode::Occlusion.word(),
1865            "frame {frame} was not begun with the occlusion culls on"
1866        );
1867        let occlusion = self
1868            .occlusion
1869            .as_ref()
1870            .unwrap_or_else(|| unreachable!("begin_frame_with checked the generator's mode"));
1871        let groups = instance_count.div_ceil(cull_shader::WORKGROUP_SIZE);
1872        if groups != 0 {
1873            let cull_group = self.cull_groups[frame];
1874            let pyramid_group = pyramid.group;
1875            let layout = occlusion.cull_pipeline_layout;
1876            let pipeline = occlusion.late;
1877            let mut pass = graph
1878                .add_compute_pass("occlusion-late")
1879                .use_buffer(draws.runs_id, ResourceState::ShaderReadWrite)
1880                .use_buffer(draws.visible_count_id, ResourceState::ShaderReadWrite);
1881            for &level in pyramid.levels {
1882                pass = pass.read_image(level);
1883            }
1884            pass.execute(move |ctx| {
1885                let encoder = ctx.encoder();
1886                encoder.bind_compute_pipeline(pipeline);
1887                encoder.bind_group(0, cull_group, &[], layout);
1888                encoder.bind_group(1, pyramid_group, &[], layout);
1889                encoder.dispatch(groups, 1, 1);
1890            });
1891        }
1892        let gen_layout = self.gen_pipeline_layout;
1893        let gen_group = self.gen_groups[frame];
1894        for (label, pipeline, groups) in [
1895            (
1896                "draw-late-scatter",
1897                occlusion.late_scatter,
1898                instance_count.div_ceil(draw_gen::WORKGROUP_SIZE),
1899            ),
1900            ("draw-late-finish", occlusion.late_finish, 1),
1901        ] {
1902            if groups == 0 {
1903                continue;
1904            }
1905            graph
1906                .add_compute_pass(label)
1907                .read_buffer(draws.visible_count_id)
1908                .use_buffer(draws.runs_id, ResourceState::ShaderReadWrite)
1909                .use_buffer(draws.args_id, ResourceState::ShaderReadWrite)
1910                .use_buffer(draws.counts_id, ResourceState::ShaderReadWrite)
1911                .use_buffer(draws.group_state_id, ResourceState::ShaderReadWrite)
1912                .execute(move |ctx| {
1913                    let encoder = ctx.encoder();
1914                    encoder.bind_compute_pipeline(pipeline);
1915                    encoder.bind_group(0, gen_group, &[], gen_layout);
1916                    encoder.dispatch(groups, 1, 1);
1917                });
1918        }
1919    }
1920
1921    /// The clear, the cull and the three draw-argument passes, with the cull
1922    /// either `cull.slang`'s frustum entry point or `occlusion`'s first phase
1923    /// over the pyramid it names.
1924    fn record_passes(
1925        &self,
1926        graph: &mut RenderGraph<'_>,
1927        frame: usize,
1928        instance_count: u32,
1929        occlusion: Option<(
1930            ComputePipelineHandle,
1931            PipelineLayoutHandle,
1932            &PyramidInputs<'_>,
1933        )>,
1934    ) -> GeneratedDraws {
1935        // Each buffer arrives in the state the *previous* frame that used this
1936        // slot left it in, which is the state declared as final below. Vacuous
1937        // on the first frame, when nothing has been written and there is nothing
1938        // to order against, and the real prior use on every later one.
1939        let import = |graph: &mut RenderGraph<'_>, label: &str, buffer, state| {
1940            graph.import_buffer(
1941                label,
1942                ImportedBuffer {
1943                    buffer,
1944                    initial: state,
1945                    final_state: state,
1946                },
1947            )
1948        };
1949        let visible_count = import(
1950            graph,
1951            "cull-count",
1952            self.visible_count[frame],
1953            ResourceState::ShaderRead,
1954        );
1955        // The survivor list and the per-bucket runs are one buffer, so they are
1956        // one id: importing it twice would give the graph two independent
1957        // histories of one resource and a barrier computed from half of it.
1958        let runs = import(
1959            graph,
1960            "visible-and-bucket-runs",
1961            self.runs[frame],
1962            ResourceState::ShaderRead,
1963        );
1964        let args = import(
1965            graph,
1966            "draw-args",
1967            self.args[frame],
1968            ResourceState::IndirectArgument,
1969        );
1970        // The draw counts and the mesh-dispatch extents, likewise.
1971        let counts = import(
1972            graph,
1973            "draw-counts-and-mesh-dispatch-args",
1974            self.counts[frame],
1975            ResourceState::IndirectArgument,
1976        );
1977        // **Not indexed by `frame`**, and that is the point: this one buffer is
1978        // what carries a decision from the previous frame into this one. It
1979        // arrives in `ShaderReadWrite` because that is what the last frame left
1980        // it in — and on the very first frame because that is what
1981        // `fill_at_start_up` left it in, which is why that copy ends with a
1982        // barrier rather than in `TransferDst`. `ResourceState::needs_barrier`
1983        // answers `true` for any
1984        // transition touching a write — so the first barrier of this frame
1985        // carries a source scope covering that frame's writes and the mesh
1986        // stage's reads of them, whether or not that frame is still in flight.
1987        let group_state = import(
1988            graph,
1989            "lod-group-state",
1990            self.group_state,
1991            ResourceState::ShaderReadWrite,
1992        );
1993
1994        // The zero every atomic below counts up from, and the first thing in the
1995        // frame that touches any of the three. Its barrier into the cull pass is
1996        // the graph's, out of the `ShaderReadWrite` declared on both sides.
1997        let clear_pipeline = self.clear_pipeline;
1998        let clear_layout = self.clear_pipeline_layout;
1999        let clear_group = self.clear_groups[frame];
2000        // The longest of the three buffers: the arguments, one structure per
2001        // bucket per region, or for a small table the counts and extents with
2002        // the flat task dispatches behind them. `new` refuses a table with no
2003        // buckets, so this is never the empty dispatch Metal rejects.
2004        let regions = self.mode.regions();
2005        let clear_groups = (regions * self.bucket_count * draw_gen::DRAW_ARGS_WORDS as u32)
2006            .max(draw_gen::flat_args_word(
2007                self.bucket_count,
2008                regions,
2009                regions,
2010                0,
2011                0,
2012            ))
2013            .div_ceil(clear_counters::WORKGROUP_SIZE);
2014        graph
2015            .add_compute_pass("clear-counters")
2016            .use_buffer(visible_count, ResourceState::ShaderReadWrite)
2017            .use_buffer(args, ResourceState::ShaderReadWrite)
2018            // Both regions of it: the counts and the mesh-dispatch extents are
2019            // one buffer and therefore one declaration.
2020            .use_buffer(counts, ResourceState::ShaderReadWrite)
2021            .execute(move |ctx| {
2022                let encoder = ctx.encoder();
2023                encoder.bind_compute_pipeline(clear_pipeline);
2024                encoder.bind_group(0, clear_group, &[], clear_layout);
2025                encoder.dispatch(clear_groups, 1, 1);
2026            });
2027
2028        let (cull_pipeline, cull_layout, pyramid_group) = match occlusion {
2029            Some((pipeline, layout, pyramid)) => (pipeline, layout, Some(pyramid.group)),
2030            None => (self.cull_pipeline, self.cull_pipeline_layout, None),
2031        };
2032        let cull_group = self.cull_groups[frame];
2033        let cull_groups = instance_count.div_ceil(cull_shader::WORKGROUP_SIZE);
2034        // Omit an empty pass, not just its dispatch: Metal still creates an
2035        // encoder for a graph pass, and strict validation rejects ending one
2036        // without work. The clear and argument-generation passes remain needed
2037        // to erase the preceding frame's counts and populate zero draws.
2038        if cull_groups != 0 {
2039            let mut pass = graph
2040                .add_compute_pass("cull")
2041                // `ShaderReadWrite` rather than a write-only state for both: a
2042                // storage-buffer descriptor permits reads whatever the shader does
2043                // with it, and the counter is genuinely read-modify-written.
2044                .use_buffer(runs, ResourceState::ShaderReadWrite)
2045                .use_buffer(visible_count, ResourceState::ShaderReadWrite);
2046            // The previous frame's pyramid, read before this frame's reduction
2047            // writes over it: the declaration is what orders the two.
2048            for &level in occlusion.map_or(&[][..], |(_, _, pyramid)| pyramid.levels) {
2049                pass = pass.read_image(level);
2050            }
2051            pass.execute(move |ctx| {
2052                let encoder = ctx.encoder();
2053                encoder.bind_compute_pipeline(cull_pipeline);
2054                encoder.bind_group(0, cull_group, &[], cull_layout);
2055                if let Some(group) = pyramid_group {
2056                    encoder.bind_group(1, group, &[], cull_layout);
2057                }
2058                encoder.dispatch(cull_groups, 1, 1);
2059            });
2060        }
2061
2062        let gen_layout = self.gen_pipeline_layout;
2063        let gen_group = self.gen_groups[frame];
2064        // One `binMain` invocation owns bucket `i` *and* routes visible instance
2065        // `i`, so its dispatch covers the larger of the two — and is never empty,
2066        // because the static half of every bucket's arguments has to be written
2067        // even for a frame that culled everything.
2068        let bin_groups = instance_count
2069            .max(self.bucket_count)
2070            .div_ceil(draw_gen::WORKGROUP_SIZE);
2071        // `scatterMain` only scatters, and the survivors are at most the tested
2072        // instances.
2073        let scatter_groups = instance_count.div_ceil(draw_gen::WORKGROUP_SIZE);
2074        // **Three passes, not three dispatches in one**, and the difference is
2075        // the whole of whether this works on every device. Each stage reads what
2076        // the one before it wrote — `startsMain` the routes and counts
2077        // `binMain` finished, `scatterMain` the starts — and a dependency a pass
2078        // does not declare is one the device is not told about: `crcbl-vk`
2079        // records explicit pipeline barriers, and a driver may run commands with
2080        // no barrier between them in any order it likes. Recorded as one pass,
2081        // an NVIDIA GeForce MX550 (615.71.09) ran the prefix sum and the scatter
2082        // against buffers the routing dispatch had not written yet, so every
2083        // bucket's start collapsed onto the run region's first word — while
2084        // lavapipe, which runs commands in order, passed every check. As three
2085        // passes over the same declarations the graph puts a barrier on each
2086        // buffer between them, as it does between the cull and this.
2087        //
2088        // Every pass declares all four written buffers, because every pass binds
2089        // the one group that names them.
2090        let passes = [
2091            ("draw-args", self.bin_pipeline, bin_groups),
2092            ("draw-starts", self.starts_pipeline, 1),
2093            ("draw-scatter", self.scatter_pipeline, scatter_groups),
2094        ];
2095        for (label, pipeline, groups) in passes {
2096            // No instances tested is no survivors to scatter: omit that pass
2097            // for the same reason as the cull's.
2098            if groups == 0 {
2099                continue;
2100            }
2101            graph
2102                .add_compute_pass(label)
2103                .read_buffer(visible_count)
2104                // Read for the survivor list and written for the routes, the runs
2105                // and their starts, which share it — one declaration, and
2106                // `ShaderReadWrite` is what it really is.
2107                .use_buffer(runs, ResourceState::ShaderReadWrite)
2108                .use_buffer(args, ResourceState::ShaderReadWrite)
2109                .use_buffer(counts, ResourceState::ShaderReadWrite)
2110                .use_buffer(group_state, ResourceState::ShaderReadWrite)
2111                .execute(move |ctx| {
2112                    let encoder = ctx.encoder();
2113                    encoder.bind_compute_pipeline(pipeline);
2114                    encoder.bind_group(0, gen_group, &[], gen_layout);
2115                    encoder.dispatch(groups, 1, 1);
2116                });
2117        }
2118
2119        GeneratedDraws {
2120            args: self.args[frame],
2121            args_id: args,
2122            counts: self.counts[frame],
2123            counts_id: counts,
2124            flat_args_offset: self.flat_args_offset(0, 0),
2125            runs_id: runs,
2126            group_state_id: group_state,
2127            visible_count_id: visible_count,
2128        }
2129    }
2130
2131    /// Releases everything, in dependency order. The device must be idle.
2132    pub fn destroy(self, device: &dyn Device) {
2133        if let Some(occlusion) = self.occlusion {
2134            for pipeline in [
2135                occlusion.early,
2136                occlusion.late,
2137                occlusion.late_scatter,
2138                occlusion.late_finish,
2139            ] {
2140                device.destroy_compute_pipeline(pipeline);
2141            }
2142            device.destroy_pipeline_layout(occlusion.cull_pipeline_layout);
2143            device.destroy_bind_group_layout(occlusion.pyramid_layout);
2144        }
2145        device.destroy_compute_pipeline(self.scatter_pipeline);
2146        device.destroy_compute_pipeline(self.starts_pipeline);
2147        device.destroy_compute_pipeline(self.bin_pipeline);
2148        device.destroy_pipeline_layout(self.gen_pipeline_layout);
2149        device.destroy_compute_pipeline(self.cull_pipeline);
2150        device.destroy_pipeline_layout(self.cull_pipeline_layout);
2151        device.destroy_compute_pipeline(self.clear_pipeline);
2152        device.destroy_pipeline_layout(self.clear_pipeline_layout);
2153        for group in self
2154            .gen_groups
2155            .into_iter()
2156            .chain(self.cull_groups)
2157            .chain(self.clear_groups)
2158        {
2159            device.destroy_bind_group(group);
2160        }
2161        device.destroy_bind_group_layout(self.gen_layout);
2162        device.destroy_bind_group_layout(self.cull_layout);
2163        device.destroy_bind_group_layout(self.clear_layout);
2164        for buffer in [self.tables, self.clear_params, self.group_state]
2165            .into_iter()
2166            .chain(self.gen_params)
2167            .chain(self.cull_params)
2168            .chain(self.visible_count)
2169            .chain(self.runs)
2170            .chain(self.args)
2171            .chain(self.counts)
2172        {
2173            device.destroy_buffer(buffer);
2174        }
2175    }
2176}
2177
2178/// A uniform-buffer layout entry for the compute stage.
2179///
2180/// Shared with [`crate::light_grid`], which builds a compute pass on exactly
2181/// these terms: one uniform block of parameters and a handful of storage
2182/// buffers, in the shader's declaration order.
2183pub(crate) const fn uniform(binding: u32) -> BindGroupLayoutEntry {
2184    BindGroupLayoutEntry {
2185        binding,
2186        visibility: ShaderStages::COMPUTE,
2187        kind: BindingKind::UniformBuffer { dynamic: false },
2188        count: 1,
2189        flags: BindingFlags::empty(),
2190    }
2191}
2192
2193/// A `uint` element's stride — the element of every counter, index and bitmask
2194/// buffer these compute passes declare.
2195pub(crate) const UINT_STRIDE: u32 = size_of::<u32>() as u32;
2196
2197/// A storage-buffer layout entry for the compute stage. `read_only` is the
2198/// shader's own `StructuredBuffer` versus `RWStructuredBuffer`, so it is the
2199/// truth rather than a hint, and `stride` is the byte size of that buffer's
2200/// element type — `crcbl-vk` and `crcbl-dx12` both refuse a pipeline whose
2201/// shader disagrees.
2202pub(crate) const fn storage(binding: u32, read_only: bool, stride: u32) -> BindGroupLayoutEntry {
2203    BindGroupLayoutEntry {
2204        binding,
2205        visibility: ShaderStages::COMPUTE,
2206        kind: BindingKind::StorageBuffer {
2207            read_only,
2208            dynamic: false,
2209            stride,
2210        },
2211        count: 1,
2212        flags: BindingFlags::empty(),
2213    }
2214}
2215
2216/// A whole-buffer bind group entry.
2217pub(crate) const fn bound(binding: u32, buffer: BufferHandle) -> BindGroupEntry {
2218    BindGroupEntry {
2219        binding,
2220        array_index: 0,
2221        resource: BindingResource::whole_buffer(buffer),
2222    }
2223}
2224
2225/// Creates a compute pipeline from `shader`'s single compute entry point,
2226/// destroying the module whether or not the pipeline was created.
2227pub(crate) fn compute_pipeline(
2228    device: &dyn Device,
2229    label: &str,
2230    shader: &crcbl_shaders::Shader,
2231    layout: PipelineLayoutHandle,
2232    workgroup_size: u32,
2233) -> Result<ComputePipelineHandle, HalError> {
2234    // Resolved before the module exists, for `crate::forward`'s reason: a
2235    // manifest that disagreed with the artifact would otherwise fail inside the
2236    // descriptor literal, with the module already created and nothing holding
2237    // it.
2238    let entry_point = shader.entry_point(Stage::Compute).ok_or_else(|| {
2239        HalError::ShaderCompilation(format!(
2240            "{}.slang exposes no unambiguous compute entry point; the committed SPIR-V and its \
2241             manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
2242            shader.name()
2243        ))
2244    })?;
2245    compute_pipeline_entry(device, label, shader, entry_point, layout, workgroup_size)
2246}
2247
2248/// [`compute_pipeline`] for a module with **more than one** compute entry
2249/// point, which is a thing Slang compiles and [`Shader::entry_point`] refuses
2250/// to guess between.
2251///
2252/// `crate::volumetric` is the caller that needs it: its scatter and integrate
2253/// kernels are two entry points of one module because they share the froxel
2254/// arithmetic and there is no `#include` to share it any other way.
2255///
2256/// The name is not checked against the module here — a wrong one fails at
2257/// pipeline creation, which is where every backend reports it.
2258///
2259/// [`Shader::entry_point`]: crcbl_shaders::Shader::entry_point
2260pub(crate) fn compute_pipeline_entry(
2261    device: &dyn Device,
2262    label: &str,
2263    shader: &crcbl_shaders::Shader,
2264    entry_point: &str,
2265    layout: PipelineLayoutHandle,
2266    workgroup_size: u32,
2267) -> Result<ComputePipelineHandle, HalError> {
2268    let module = device.create_shader_module(&ShaderModuleDesc {
2269        label: Some(shader.name()),
2270        spirv: shader.spirv(),
2271        wgsl: shader.wgsl(),
2272        msl: shader.msl(),
2273        // One DXIL container per entry point, all of them, exactly as the
2274        // two-stage graphics modules pass theirs — the backend picks the one
2275        // `entry_point` names below.
2276        dxil: &shader.dxil_containers(),
2277    })?;
2278    let pipeline = device.create_compute_pipeline(&ComputePipelineDesc {
2279        label: Some(label),
2280        layout,
2281        compute: ShaderEntry {
2282            module,
2283            entry_point,
2284        },
2285        // The shader's own number rather than a literal: a dispatch sized
2286        // against a different one tests part of the array and reads as a cull.
2287        workgroup_size: [workgroup_size, 1, 1],
2288    });
2289    device.destroy_shader_module(module);
2290    pipeline
2291}
2292
2293/// Writes `contents` over `buffer` once, before any frame exists, and blocks
2294/// until the copy has run, leaving it in `final_state`.
2295///
2296/// A start-up staging copy on [`crate::mesh_pool`]'s and [`crate::texture`]'s
2297/// terms, and it joins them on the crate docs' list of named exceptions to the
2298/// no-manual-barriers rule. It is *not* a `write_buffer`, because the
2299/// destination is device-local; not [`crcbl_hal::CommandEncoder::clear_buffer`],
2300/// which `crcbl-dx12` refuses outright and the module docs argue about at
2301/// length; and not the clearing dispatch, which runs inside every frame rather
2302/// than once.
2303///
2304/// `final_state` is the state the buffer's first importer declares as its
2305/// initial one, so the graph's first barrier on it names a state the buffer is
2306/// really in: [`ResourceState::ShaderReadWrite`] for the LOD state below, and
2307/// [`ResourceState::ShaderRead`] for [`crate::exposure`]'s ring.
2308///
2309/// # Errors
2310///
2311/// [`HalError`] from any seam call, and from a `contents` too long to be a
2312/// buffer size on this host.
2313pub(crate) fn fill_at_start_up(
2314    device: &dyn Device,
2315    queue: QueueHandle,
2316    label: &str,
2317    buffer: BufferHandle,
2318    contents: &[u8],
2319    final_state: ResourceState,
2320) -> Result<(), HalError> {
2321    let size = u64::try_from(contents.len()).map_err(|_| {
2322        HalError::InvalidDescriptor(format!(
2323            "{label} is {} bytes, which does not fit a buffer size",
2324            contents.len()
2325        ))
2326    })?;
2327    let staging = device.create_buffer(&BufferDesc {
2328        label: Some(&format!("{label} staging")),
2329        size,
2330        usage: BufferUsage::TRANSFER_SRC,
2331        memory: MemoryLocation::HostUpload,
2332    })?;
2333    let filled = record_fill(device, queue, label, buffer, staging, contents, final_state);
2334    device.destroy_buffer(staging);
2335    filled
2336}
2337
2338/// The half of [`fill_at_start_up`] the staging buffer is live across, so the
2339/// caller releases it on every path out.
2340fn record_fill(
2341    device: &dyn Device,
2342    queue: QueueHandle,
2343    label: &str,
2344    buffer: BufferHandle,
2345    staging: BufferHandle,
2346    contents: &[u8],
2347    final_state: ResourceState,
2348) -> Result<(), HalError> {
2349    device.write_buffer(staging, 0, contents)?;
2350
2351    let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
2352        label: Some(&format!("{label} zero")),
2353        queue,
2354    });
2355    // `Undefined` as the source, unlike [`crate::mesh_pool`]'s pools: this
2356    // buffer was created a few statements ago and has never held anything, so
2357    // there is no state to preserve and its contents are discarded rather than
2358    // transitioned.
2359    encoder.pipeline_barrier(&Barriers {
2360        buffers: &[BufferBarrier::new(
2361            buffer,
2362            ResourceState::Undefined,
2363            ResourceState::TransferDst,
2364        )],
2365        ..Barriers::default()
2366    });
2367    encoder.copy_buffer_to_buffer(&BufferCopy {
2368        src: staging,
2369        src_offset: 0,
2370        dst: buffer,
2371        dst_offset: 0,
2372        size: contents.len() as u64,
2373    });
2374    encoder.pipeline_barrier(&Barriers {
2375        buffers: &[BufferBarrier::new(
2376            buffer,
2377            ResourceState::TransferDst,
2378            final_state,
2379        )],
2380        ..Barriers::default()
2381    });
2382    let commands = encoder.finish()?;
2383
2384    // Blocking is what makes this a start-up path: the staging buffer dies with
2385    // the caller's next statement, and a frame that read the state before the
2386    // copy landed would read whatever the allocation came with.
2387    let submitted = device
2388        .submit(queue, &SubmitInfo::new(&[commands]))
2389        .and_then(|()| device.wait_idle());
2390    device.destroy_command_buffer(commands);
2391    submitted
2392}
2393
2394/// What a partly-built [`DrawGen`] has to give back.
2395///
2396/// `build` creates two dozen objects with `?` between them and the seam's
2397/// `destroy_*` is explicit, so a failure half way through would otherwise leak
2398/// everything created before it.
2399#[derive(Debug, Default)]
2400struct Rollback {
2401    buffers: Vec<BufferHandle>,
2402    bind_groups: Vec<BindGroupHandle>,
2403    bind_group_layouts: Vec<BindGroupLayoutHandle>,
2404    pipeline_layouts: Vec<PipelineLayoutHandle>,
2405    pipelines: Vec<ComputePipelineHandle>,
2406}
2407
2408impl Rollback {
2409    /// Forgets everything, once the objects have an owner that will destroy
2410    /// them.
2411    fn disarm(&mut self) {
2412        *self = Self::default();
2413    }
2414
2415    /// Releases everything, in the same dependency order as
2416    /// [`DrawGen::destroy`].
2417    fn run(self, device: &dyn Device) {
2418        for handle in self.pipelines {
2419            device.destroy_compute_pipeline(handle);
2420        }
2421        for handle in self.pipeline_layouts {
2422            device.destroy_pipeline_layout(handle);
2423        }
2424        for handle in self.bind_groups {
2425            device.destroy_bind_group(handle);
2426        }
2427        for handle in self.bind_group_layouts {
2428            device.destroy_bind_group_layout(handle);
2429        }
2430        for handle in self.buffers {
2431            device.destroy_buffer(handle);
2432        }
2433    }
2434}
2435
2436// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
2437#[cfg(all(test, not(target_arch = "wasm32")))]
2438mod tests {
2439    use super::*;
2440    use crcbl_hal::null::{NullInstance, Recorder};
2441    use crcbl_hal::{DeviceDesc, Instance, QueueKind};
2442    use crcbl_shaders::level_select::MeshLevels;
2443
2444    fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
2445        let recorder = Recorder::new();
2446        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
2447        let adapter = instance.adapters().remove(0);
2448        let device = instance
2449            .create_device(&DeviceDesc::for_adapter(adapter.id))
2450            .expect("the null backend always opens");
2451        let queue = device.queue(QueueKind::Graphics).expect("always present");
2452        (recorder, device, queue)
2453    }
2454
2455    /// A generator over `buckets` buckets of `capacity` instances, every bucket
2456    /// drawing its own flat mesh — the smallest table that is still a table of
2457    /// that length.
2458    fn generator(device: &dyn Device, queue: QueueHandle, capacity: u32, buckets: u32) -> DrawGen {
2459        generator_in(device, queue, capacity, buckets, DrawMode::Plain)
2460    }
2461
2462    /// [`generator`], built for `mode`.
2463    fn generator_in(
2464        device: &dyn Device,
2465        queue: QueueHandle,
2466        capacity: u32,
2467        buckets: u32,
2468        mode: DrawMode,
2469    ) -> DrawGen {
2470        let storage = |label: &str, size: u64| {
2471            device
2472                .create_buffer(&BufferDesc {
2473                    label: Some(label),
2474                    size,
2475                    usage: BufferUsage::STORAGE,
2476                    memory: MemoryLocation::HostUpload,
2477                })
2478                .expect("a storage buffer")
2479        };
2480        let instances = [storage("instances", 4)];
2481        let mesh_table = storage("mesh table", 4);
2482        let bucket_meshes: Vec<u32> = (0..buckets).collect();
2483        let zeroes = vec![0u32; bucket_meshes.len()];
2484        let mesh_levels: Vec<MeshLevels> = bucket_meshes
2485            .iter()
2486            .map(|mesh| MeshLevels {
2487                first_level: *mesh,
2488                ..MeshLevels::FLAT
2489            })
2490            .collect();
2491        DrawGen::new(
2492            device,
2493            queue,
2494            &DrawGenDesc {
2495                label: Some("draw gen test"),
2496                instances: &instances,
2497                mesh_table,
2498                bucket_meshes: &bucket_meshes,
2499                bucket_modes: &zeroes,
2500                bucket_clusters: &zeroes,
2501                bucket_cluster_bases: &zeroes,
2502                mesh_levels: &mesh_levels,
2503                level_groups: &[],
2504                level_meshes: &bucket_meshes,
2505                instance_capacity: capacity,
2506                hidden_view: 0,
2507                mode,
2508                task_lanes: 0,
2509            },
2510        )
2511        .expect("the null backend builds a generator")
2512    }
2513
2514    /// **The runs buffer costs two words per bucket per draw region — its run
2515    /// start and its task chunks' start — and one for the bucket's mesh, not a
2516    /// capacity per bucket.**
2517    ///
2518    /// Two generators of one capacity and very different bucket counts, and the
2519    /// size the device was actually asked for — read off the allocation rather
2520    /// than off [`DrawGen::runs_size`], which a build that sized the buffer some
2521    /// other way would still answer correctly. When each bucket reserved its own
2522    /// run this difference was `capacity` words a bucket, so the second
2523    /// generator's buffer was sixty-four times the first's.
2524    #[test]
2525    fn the_runs_buffer_grows_by_a_word_per_bucket() {
2526        const CAPACITY: u32 = 1000;
2527        let (recorder, device, queue) = open();
2528        let device = device.as_ref();
2529        let few = generator(device, queue, CAPACITY, 1);
2530        let many = generator(device, queue, CAPACITY, 64);
2531        let size = |draws: &DrawGen| {
2532            recorder
2533                .buffer_size(draws.runs(0))
2534                .expect("the runs buffer is live")
2535        };
2536
2537        let regions = u64::from(draw_gen::DRAW_REGIONS);
2538        assert_eq!(
2539            size(&many) - size(&few),
2540            u64::from(many.bucket_count() - few.bucket_count()) * (2 * regions + 1) * 4,
2541            "sixty-three more buckets cost sixty-three more words of run start and of chunk \
2542             start a region, and of mesh, and nothing else"
2543        );
2544        assert_eq!(
2545            size(&few),
2546            (3 * u64::from(CAPACITY) + regions + 1 + 2 * regions) * 4,
2547            "one bucket's generator holds the survivors, their routes, one capacity of runs, \
2548             one start per region, its mesh, and its chunk start and the region's end per region"
2549        );
2550        for draws in [&few, &many] {
2551            assert_eq!(
2552                draws.runs_size(),
2553                size(draws),
2554                "and the accessor a reader sizes a copy by is the size that was allocated"
2555            );
2556        }
2557
2558        few.destroy(device);
2559        many.destroy(device);
2560        recorder.assert_valid();
2561    }
2562
2563    /// **Every start word is past the runs and inside the buffer**, and bucket
2564    /// zero's run opens the run region.
2565    ///
2566    /// The words a constant block names are fixed at build and read by the
2567    /// geometry stages every frame, so two buckets sharing one would draw one
2568    /// bucket's run twice, and a word past the end is a read of nothing. The
2569    /// last region's chunk end, behind every start, mesh and chunk start, is
2570    /// the buffer's last.
2571    #[test]
2572    fn every_bucket_start_is_a_word_of_its_own_behind_the_runs() {
2573        const CAPACITY: u32 = 100;
2574        let (recorder, device, queue) = open();
2575        let device = device.as_ref();
2576        let draws = generator(device, queue, CAPACITY, 5);
2577
2578        assert_eq!(
2579            draws.runs_at(),
2580            2 * CAPACITY,
2581            "past the survivors and their routes"
2582        );
2583        let starts: Vec<u32> = (0..draws.bucket_count())
2584            .map(|bucket| draws.bucket_start_word(bucket))
2585            .collect();
2586        assert_eq!(
2587            starts,
2588            (0..5)
2589                .map(|bucket| 3 * CAPACITY + bucket)
2590                .collect::<Vec<_>>(),
2591            "one word per bucket, in bucket order, behind one capacity of runs"
2592        );
2593        assert_eq!(
2594            draws.region_start_word(1, 0),
2595            starts[starts.len() - 1] + 1,
2596            "region 1's starts directly behind region 0's"
2597        );
2598        assert_eq!(
2599            draws.bucket_mesh_word(0),
2600            draws.region_start_word(draw_gen::DRAW_REGIONS - 1, draws.bucket_count() - 1) + 1,
2601            "the buckets' meshes directly behind the last region's starts"
2602        );
2603        assert_eq!(
2604            draws.chunk_start_word(0, 0),
2605            draws.bucket_mesh_word(draws.bucket_count() - 1) + 1,
2606            "the chunk starts directly behind the last bucket's mesh"
2607        );
2608        assert_eq!(
2609            draws.chunk_start_word(1, 0),
2610            draws.chunk_start_word(0, draws.bucket_count()) + 1,
2611            "each region's chunk starts, its end word included, directly behind the one before"
2612        );
2613        assert_eq!(
2614            u64::from(draws.chunk_start_word(draw_gen::DRAW_REGIONS - 1, draws.bucket_count()) + 1)
2615                * 4,
2616            draws.runs_size(),
2617            "and the last region's chunk end is the buffer's last word"
2618        );
2619
2620        draws.destroy(device);
2621        recorder.assert_valid();
2622    }
2623
2624    /// **The scene that ran a 2 GiB device out of memory**, through the layout
2625    /// each bucket used to reserve and through the one it has now.
2626    ///
2627    /// 17219 instances and 938 buckets are the measured `ew` scene
2628    /// `docs/backlog.md`'s performance review records; the numbers here are its
2629    /// byte sizes, asserted rather than written into a comment, so the module
2630    /// docs' claim moves with the formula.
2631    #[test]
2632    fn the_measured_scene_pays_a_word_per_bucket_rather_than_a_capacity() {
2633        const CAPACITY: u32 = 17219;
2634        const BUCKETS: u32 = 938;
2635        let per_bucket_runs = u64::from(CAPACITY) * (1 + u64::from(BUCKETS)) * 4;
2636        let shared_runs = u64::from(
2637            draw_gen::runs_words(CAPACITY, BUCKETS, false).expect("the scene's layout addresses"),
2638        ) * 4;
2639        assert_eq!(
2640            per_bucket_runs, 64_674_564,
2641            "61.7 MiB a buffer, as measured"
2642        );
2643        assert_eq!(
2644            shared_runs, 262_936,
2645            "256.8 KiB a buffer, with a run start and a chunk start per bucket for every draw \
2646             region, a chunk end per region, and a mesh word per bucket"
2647        );
2648    }
2649
2650    /// **What the draw regions cost one frame in flight**, per generator and per
2651    /// renderer, in the measured scene of
2652    /// [`the_measured_scene_pays_a_word_per_bucket_rather_than_a_capacity`] —
2653    /// read off the allocations the device was asked for, so the figures a
2654    /// report quotes are these assertions' and not arithmetic beside them.
2655    ///
2656    /// A renderer holds a camera generator built for [`DrawMode::Occlusion`],
2657    /// [`crate::shadow::CASCADES`] built for [`DrawMode::Plain`] and
2658    /// [`crate::shadow::LIGHT_SLOTS`] built for [`DrawMode::Faces`] — the point
2659    /// light's face culls, whose face runs are most of the cost.
2660    #[test]
2661    fn the_regions_cost_what_their_layout_says_in_the_measured_scene() {
2662        const CAPACITY: u32 = 17219;
2663        const BUCKETS: u32 = 938;
2664        let (recorder, device, queue) = open();
2665        let device = device.as_ref();
2666        let size = |buffer| recorder.buffer_size(buffer).expect("live");
2667        let per_frame = |mode| {
2668            let draws = generator_in(device, queue, CAPACITY, BUCKETS, mode);
2669            let bytes = size(draws.runs(0)) + size(draws.args(0)) + size(draws.counts(0));
2670            draws.destroy(device);
2671            bytes
2672        };
2673        let [plain, occlusion, faces] =
2674            [DrawMode::Plain, DrawMode::Occlusion, DrawMode::Faces].map(per_frame);
2675        assert_eq!(
2676            plain, 296_776,
2677            "runs, one region of arguments and one of counts, and its flat dispatches"
2678        );
2679        assert_eq!(
2680            occlusion, 364_456,
2681            "three regions of arguments, counts and flat dispatches"
2682        );
2683        assert_eq!(
2684            faces, 913_076,
2685            "seven regions and six capacities of face runs"
2686        );
2687        // What a generator cost before there were regions: the runs with one
2688        // start per bucket, one argument structure and one count region.
2689        let before = (3 * u64::from(CAPACITY) + u64::from(BUCKETS)) * 4
2690            + u64::from(BUCKETS) * (draw_gen::DRAW_ARGS_SIZE as u64 + 16);
2691        assert_eq!(before, 244_148);
2692        let cascades = crate::shadow::CASCADES as u64;
2693        let slots = crate::shadow::LIGHT_SLOTS as u64;
2694        let renderer_before = before * (1 + cascades + slots);
2695        let renderer_after = occlusion + plain * cascades + faces * slots;
2696        assert_eq!(renderer_before, 1_709_036);
2697        assert_eq!(
2698            renderer_after, 4_610_312,
2699            "4.40 MiB a frame in flight, against 1.63 MiB before"
2700        );
2701        recorder.assert_valid();
2702    }
2703}