crcbl_hal/command.rs
1//! Command recording: passes, barriers, copies, draws, dispatches, queries.
2//!
3//! # Flat scopes, not nested encoders
4//!
5//! [`CommandEncoder::begin_render_pass`] / [`end_render_pass`](CommandEncoder::end_render_pass)
6//! are flat calls on one encoder rather than a `begin` that returns a borrowed
7//! `RenderPassEncoder` sub-object. The sub-object form is more type-safe and is
8//! what `wgpu` does, but it does not survive `dyn`: returning
9//! `Box<dyn RenderPassEncoder + '_>` costs an allocation per pass, and the
10//! borrow relationship is awkward to express through a trait object.
11//!
12//! The safety this gives up is bought back elsewhere. The *only* caller of this
13//! trait is `crcbl-render`'s render graph, which emits passes from a compiled
14//! list and cannot mis-nest them by construction; the backends' validation
15//! layers catch it if it somehow does; and [`crate::null`] tracks scope
16//! explicitly and records a validation error, so the graph's own unit suite
17//! fails loudly on a mis-nested pass without a GPU in the room.
18//!
19//! # Barriers: resource states, not stage/access masks
20//!
21//! [`ResourceState`] is a small closed set of "what is this resource being used
22//! for right now" values. The backend expands one into a Vulkan `sync2`
23//! stage+access+layout triple, a DX12 enhanced-barrier state, a Metal fence, or
24//! nothing at all on WebGPU.
25//!
26//! Exposing raw stage/access masks was rejected: Metal cannot represent them,
27//! WebGPU has no barriers to give them to, and the render graph does not have
28//! finer information than the state anyway — a pass declares "I sample this",
29//! not "I sample this in the fragment stage with `SHADER_STORAGE_READ`". The
30//! cost is some over-synchronisation on Vulkan where a state maps to a broader
31//! stage mask than strictly needed. That is the *known* place this seam gives up
32//! performance, and refining it is a P1-or-later change confined to
33//! [`ResourceState`] and its backend translation.
34//!
35//! # Indirect is the steady state
36//!
37//! [`CommandEncoder::draw_indexed_indirect_count`] is the normal path (topic 03:
38//! a compute pass writes the arguments and the count, the CPU never learns how
39//! many draws happen). [`CommandEncoder::draw`] exists for full-screen triangles
40//! and bring-up. A device with no count buffer uses
41//! [`CommandEncoder::draw_indexed_indirect`] once per bucket — hence
42//! [`DrawIndirect::draw_count`], so even that is one call per bucket rather than
43//! one per draw.
44
45use core::ops::Range;
46
47use crcbl_core::Handle;
48
49use crate::{
50 BindGroupHandle, BufferHandle, ComputePipelineHandle, Extent3d, GraphicsPipelineHandle,
51 HalError, ImageHandle, ImageSubresourceLayers, ImageSubresourceRange, ImageViewHandle,
52 IndexFormat, Offset3d, PipelineLayoutHandle, QuerySetHandle, Rect2d, ShaderStages, Viewport,
53 device::QueueHandle,
54};
55
56/// Marker type for command-buffer handles. Uninhabited.
57#[derive(Debug)]
58pub enum CommandBuffer {}
59
60/// A finished command buffer, ready to submit.
61pub type CommandBufferHandle = Handle<CommandBuffer>;
62
63/// Reversed-Z depth constants.
64///
65/// The engine's depth convention is **1.0 at the near plane, 0.0 at infinity,
66/// with an infinite far plane** (locked in stage 2; see `docs/notes/backends.md`). A
67/// sector-tiled world with 300 m+ sightlines z-fights immediately on a
68/// conventional `0..1` buffer, and retrofitting the convention after P1
69/// invalidates every blessed golden frame.
70///
71/// These constants exist so no call site writes a bare `1.0` whose meaning
72/// depends on a convention documented elsewhere.
73///
74/// ```
75/// use crcbl_hal::{ClearValue, CompareOp, DepthStencilState, depth};
76///
77/// // Clear to the far plane, test with Greater: nearer fragments win.
78/// assert_eq!(depth::CLEAR, 0.0);
79/// assert_eq!(DepthStencilState::default().depth_compare, CompareOp::Greater);
80/// assert_eq!(ClearValue::default().depth, depth::CLEAR);
81/// ```
82pub mod depth {
83 /// Depth value at the near plane: **1.0**.
84 pub const NEAR: f32 = 1.0;
85
86 /// Depth value at infinity: **0.0**. The far plane is infinite, so this is
87 /// a limit rather than a distance.
88 pub const FAR: f32 = 0.0;
89
90 /// The value a depth attachment is cleared to — [`FAR`], so that any real
91 /// geometry passes a [`CompareOp::Greater`](crate::CompareOp) test.
92 ///
93 /// Clearing to `1.0` (the conventional-Z value) with the engine's default
94 /// compare op renders nothing at all, which is a confusing enough symptom to
95 /// be worth a named constant.
96 pub const CLEAR: f32 = FAR;
97}
98
99/// Stencil constants the seam guarantees rather than inherits.
100///
101/// ```
102/// use crcbl_hal::stencil;
103///
104/// assert_eq!(stencil::INITIAL_REFERENCE, 0);
105/// ```
106pub mod stencil {
107 /// The reference value a render pass starts with, before any
108 /// [`set_stencil_reference`](crate::CommandEncoder::set_stencil_reference).
109 ///
110 /// **Zero, and stated here because it is a promise rather than an
111 /// observation.** WebGPU and Metal both start an encoder at zero on their
112 /// own; D3D12's `OMSetStencilRef` is command-list state that outlives a
113 /// pass, and Vulkan's reference is *undefined* until
114 /// `vkCmdSetStencilReference` is called, since `crcbl-vk` declares
115 /// `VK_DYNAMIC_STATE_STENCIL_REFERENCE` on every pipeline. Those two
116 /// backends set this value as their passes open so that all four agree.
117 pub const INITIAL_REFERENCE: u32 = 0;
118}
119
120/// What to do with an attachment's existing contents at the start of a pass.
121#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
122pub enum LoadOp {
123 /// Preserve them. The most expensive option on tile-based GPUs; use only
124 /// when the pass genuinely reads what was there.
125 Load,
126 /// Replace them with the attachment's clear value.
127 Clear,
128 /// Leave them undefined. Correct whenever the pass writes every pixel — and
129 /// the right default for a swapchain image, whose previous contents are
130 /// never meaningful.
131 #[default]
132 DontCare,
133}
134
135/// What to do with an attachment's contents at the end of a pass.
136#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
137pub enum StoreOp {
138 /// Write them to memory.
139 #[default]
140 Store,
141 /// Discard them. For depth buffers nothing reads afterwards, and for MSAA
142 /// targets that were resolved.
143 Discard,
144}
145
146/// Clear values for a render pass attachment.
147///
148/// One struct rather than a colour/depth union: an attachment is colour *or*
149/// depth-stencil, and its own descriptor already says which, so a union would
150/// only add a mismatch to check.
151///
152/// [`Default`] clears to transparent black and to [`depth::CLEAR`] — the
153/// reversed-Z far plane, **not** `1.0`.
154#[derive(Clone, Copy, Debug, PartialEq)]
155pub struct ClearValue {
156 /// RGBA clear colour, in the attachment's own space (linear for
157 /// [`Rgba16Float`](crate::Format::Rgba16Float), display-referred for an
158 /// sRGB swapchain).
159 pub color: [f32; 4],
160 /// Depth clear value. Defaults to [`depth::CLEAR`].
161 pub depth: f32,
162 /// Stencil clear value.
163 pub stencil: u32,
164}
165
166impl Default for ClearValue {
167 fn default() -> Self {
168 Self {
169 color: [0.0; 4],
170 depth: depth::CLEAR,
171 stencil: 0,
172 }
173 }
174}
175
176impl ClearValue {
177 /// A colour clear, with the reversed-Z depth default left in place.
178 #[must_use]
179 pub const fn color(rgba: [f32; 4]) -> Self {
180 Self {
181 color: rgba,
182 depth: depth::CLEAR,
183 stencil: 0,
184 }
185 }
186}
187
188/// One colour attachment of a render pass.
189#[derive(Clone, Copy, Debug, PartialEq)]
190pub struct ColorAttachment {
191 /// View rendered into. Must already be in
192 /// [`ResourceState::ColorAttachment`]; the HAL does not transition it.
193 pub view: ImageViewHandle,
194 /// MSAA resolve destination, if any.
195 ///
196 /// Like [`view`](Self::view), and for the same reason it says so: this must
197 /// already be in [`ResourceState::ColorAttachment`]. Every backend reads it
198 /// that way — `crcbl-vk` names `COLOR_ATTACHMENT_OPTIMAL` as the resolve
199 /// image's layout and `crcbl-dx12` transitions out of `RENDER_TARGET` and
200 /// back — so the seam should say it rather than leave three backends
201 /// agreeing by coincidence..
202 pub resolve: Option<ImageViewHandle>,
203 /// Start-of-pass behaviour.
204 pub load: LoadOp,
205 /// End-of-pass behaviour.
206 pub store: StoreOp,
207 /// Used when `load` is [`LoadOp::Clear`].
208 pub clear: ClearValue,
209}
210
211/// The depth/stencil attachment of a render pass.
212#[derive(Clone, Copy, Debug, PartialEq)]
213pub struct DepthStencilAttachment {
214 /// View rendered into. Must already be in
215 /// [`ResourceState::DepthStencilWrite`] or
216 /// [`ResourceState::DepthStencilRead`] — see
217 /// [`read_only`](Self::read_only), which is how the backend is told which.
218 pub view: ImageViewHandle,
219 /// Whether the pass only *tests* depth/stencil — the depth-prepass-read
220 /// shape.
221 ///
222 /// **Which of the two states the view is already in**, and the backend has
223 /// no other way to know. Vulkan and DX12 both give a read-only depth
224 /// attachment a different image layout from a written one
225 /// (`DEPTH_STENCIL_READ_ONLY_OPTIMAL` vs `DEPTH_STENCIL_ATTACHMENT_OPTIMAL`),
226 /// and `vkCmdBeginRendering` requires the layout named here to be the one
227 /// the image is actually in. Guessing from the store op is not equivalent:
228 /// a pass may read depth and store nothing, or write depth and discard it.
229 ///
230 /// `true` pairs with [`ResourceState::DepthStencilRead`], `false` with
231 /// [`ResourceState::DepthStencilWrite`].
232 pub read_only: bool,
233 /// Depth start-of-pass behaviour.
234 pub depth_load: LoadOp,
235 /// Depth end-of-pass behaviour.
236 pub depth_store: StoreOp,
237 /// Stencil start-of-pass behaviour.
238 pub stencil_load: LoadOp,
239 /// Stencil end-of-pass behaviour.
240 pub stencil_store: StoreOp,
241 /// Used when either load op is [`LoadOp::Clear`]. Defaults to
242 /// [`depth::CLEAR`] — see [`ClearValue`].
243 pub clear: ClearValue,
244}
245
246/// The two timestamps that bracket a pass — **the seam's only timestamp verb**.
247///
248/// A timestamp is named by the pass it brackets rather than by a point in the
249/// command stream, because a point in the command stream is not something every
250/// API can express. Vulkan's `vkCmdWriteTimestamp2` and D3D12's `EndQuery` on a
251/// timestamp heap take one anywhere; Metal samples only where a device's
252/// `MTLCounterSamplingPoint` values allow, which is stage boundaries; and
253/// WebGPU takes them *only* through `GPURenderPassDescriptor.timestampWrites`
254/// and `GPUComputePassDescriptor.timestampWrites`, whose
255/// `beginningOfPassWriteIndex`/`endOfPassWriteIndex` this struct is. Half the
256/// backends cannot honour an arbitrary point at all, so the pass boundary is the
257/// intersection — and putting it in the descriptor makes it a *shape* rather
258/// than a rule a caller has to remember, because there is no free-standing call
259/// left to record in the wrong place.
260///
261/// Consequently a pass is the smallest thing this seam can time. A copy or a
262/// barrier is not inside one, so what a profiler attributes to a pass is the
263/// pass alone, and the transitions the caller emitted around it are attributed
264/// to nothing.
265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub struct PassTimestampWrites {
267 /// Set the two queries are written into. Must hold
268 /// [`QueryKind::Timestamp`](crate::QueryKind::Timestamp) queries; a backend
269 /// fails the encoder rather than writing a timestamp into a pool of another
270 /// kind.
271 pub set: QuerySetHandle,
272 /// Query written when the pass begins.
273 pub beginning_of_pass: u32,
274 /// Query written when the pass ends.
275 ///
276 /// **Distinct from [`beginning_of_pass`](Self::beginning_of_pass)**: WebGPU
277 /// requires the two indices to differ, and a pass that wrote both ends into
278 /// one query would report the second over the first on every other backend,
279 /// so a backend refuses the pair rather than measuring nothing.
280 pub end_of_pass: u32,
281}
282
283/// A render pass, in dynamic-rendering form: attachments are named inline and
284/// there is no `RenderPass` or `Framebuffer` object to keep compatible.
285#[derive(Clone, Copy, Debug, PartialEq)]
286pub struct RenderPassDesc<'a> {
287 /// Pass name. Shows up in RenderDoc/PIX capture trees, in the render
288 /// graph's text dump, and in the null backend's recorded stream — which is
289 /// what makes "this frame emitted these passes in this order" assertable.
290 pub label: Option<&'a str>,
291 /// Colour attachments, in shader output order.
292 pub color_attachments: &'a [ColorAttachment],
293 /// Depth/stencil attachment, if any.
294 pub depth_stencil_attachment: Option<DepthStencilAttachment>,
295 /// Region rendered. Usually the full attachment size.
296 pub render_area: Rect2d,
297 /// Timestamps bracketing this pass, if it is being timed. See
298 /// [`PassTimestampWrites`].
299 pub timestamp_writes: Option<PassTimestampWrites>,
300}
301
302/// A compute pass.
303///
304/// Compute has no attachments, so this exists purely to give the pass a name
305/// and a timestamp boundary — which is exactly what the per-pass GPU timer
306/// report needs (topic 03 §3.5).
307#[derive(Clone, Copy, Debug, PartialEq, Eq)]
308pub struct ComputePassDesc<'a> {
309 /// Pass name; see [`RenderPassDesc::label`].
310 pub label: Option<&'a str>,
311 /// Timestamps bracketing this pass; see
312 /// [`RenderPassDesc::timestamp_writes`].
313 pub timestamp_writes: Option<PassTimestampWrites>,
314}
315
316// --- barriers --------------------------------------------------------------
317
318/// What a resource is being used for.
319///
320/// The seam's entire synchronisation vocabulary. A backend expands one of these
321/// into whatever its API needs; see the module docs for why raw stage/access
322/// masks are not exposed.
323///
324/// States are *uses*, not permissions: a resource is in exactly one state at a
325/// time from the graph's point of view, and moving between two states is a
326/// barrier.
327#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
328pub enum ResourceState {
329 /// Contents are undefined. The only legal *source* state for a freshly
330 /// created image, and for a swapchain image just acquired. Transitioning
331 /// *from* `Undefined` discards contents, which is free; transitioning *to*
332 /// it is meaningless.
333 #[default]
334 Undefined,
335 /// Read as a sampled texture or a read-only storage buffer/image in any
336 /// shader stage.
337 ShaderRead,
338 /// Written by a shader (storage buffer or storage image).
339 ShaderWrite,
340 /// Both read and written by a shader in the same pass.
341 ShaderReadWrite,
342 /// A colour attachment being rendered into.
343 ColorAttachment,
344 /// A depth/stencil attachment being written.
345 DepthStencilWrite,
346 /// A depth/stencil attachment being tested but not written — the state for
347 /// a pass drawing against an existing depth prepass.
348 DepthStencilRead,
349 /// Source of a copy.
350 TransferSrc,
351 /// Destination of a copy, clear or fill.
352 TransferDst,
353 /// Read as indirect draw/dispatch arguments or an indirect count. The state
354 /// a culling pass's output must reach before the draws that consume it —
355 /// the single most important barrier in a GPU-driven frame, and the one
356 /// whose absence produces "sometimes nothing draws".
357 IndirectArgument,
358 /// Read as an index buffer.
359 IndexBuffer,
360 /// Mapped and read by the CPU.
361 HostRead,
362 /// Ready to be handed to the compositor.
363 Present,
364}
365
366impl ResourceState {
367 /// Whether this state writes the resource.
368 ///
369 /// Read→read transitions need no barrier at all, so a graph asks this to
370 /// skip emitting one.
371 ///
372 /// [`Self::DepthStencilRead`] is a read, and every backend agrees: Vulkan
373 /// ends such a pass with `VK_ATTACHMENT_STORE_OP_NONE`, which stores
374 /// nothing and declares no attachment write; D3D12 has no store op at all
375 /// and runs a depth-test-only pass with a zero depth-write mask; WebGPU
376 /// takes `depthReadOnly` and forbids the store op entirely; and Metal,
377 /// whose `MTLStoreAction` has no no-op action, stores contents the pass did
378 /// not change. Two such passes in a row therefore hazard against nothing
379 /// and the barrier between them is the one to skip.
380 ///
381 /// It answered `true` until the backends were checked one by one, which was
382 /// conservatism rather than description — see `docs/notes/backends.md`.
383 #[must_use]
384 pub const fn is_write(self) -> bool {
385 matches!(
386 self,
387 Self::ShaderWrite
388 | Self::ShaderReadWrite
389 | Self::ColorAttachment
390 | Self::DepthStencilWrite
391 | Self::TransferDst
392 )
393 }
394
395 /// Whether a transition between two states requires a barrier.
396 ///
397 /// `false` only when both states are reads *and* they are the same state —
398 /// two different read states still differ in image layout on Vulkan and
399 /// DX12, so they need a transition even though no memory hazard exists.
400 #[must_use]
401 pub const fn needs_barrier(from: Self, to: Self) -> bool {
402 if from.is_write() || to.is_write() {
403 return true;
404 }
405 // Both reads: only a layout change remains.
406 from as u8 != to as u8
407 }
408}
409
410/// Queue-family ownership transfer attached to a barrier.
411///
412/// MVP uploads share the graphics+compute queue, so this is `None` everywhere
413/// today. It exists from P0 because stage 2's design review required
414/// that "the render graph's barrier model must nonetheless represent
415/// queue-family acquire/release from the start so a dedicated transfer queue is
416/// additive later rather than a barrier-model rewrite".
417///
418/// A transfer is expressed as **two** barriers with identical fields: a release
419/// recorded on `from`'s queue and an acquire recorded on `to`'s. The HAL relays
420/// both; deciding to emit them is the graph's job.
421#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
422pub struct QueueTransfer {
423 /// Queue releasing ownership.
424 pub from: QueueHandle,
425 /// Queue acquiring ownership.
426 pub to: QueueHandle,
427}
428
429/// A buffer state transition.
430#[derive(Clone, Copy, Debug, PartialEq, Eq)]
431pub struct BufferBarrier {
432 /// Buffer affected.
433 pub buffer: BufferHandle,
434 /// State being left.
435 pub from: ResourceState,
436 /// State being entered.
437 pub to: ResourceState,
438 /// Ownership transfer, if any.
439 pub queue_transfer: Option<QueueTransfer>,
440}
441
442impl BufferBarrier {
443 /// A same-queue transition.
444 #[must_use]
445 pub const fn new(buffer: BufferHandle, from: ResourceState, to: ResourceState) -> Self {
446 Self {
447 buffer,
448 from,
449 to,
450 queue_transfer: None,
451 }
452 }
453}
454
455/// An image state (and, on Vulkan/DX12, layout) transition.
456#[derive(Clone, Copy, Debug, PartialEq, Eq)]
457pub struct ImageBarrier {
458 /// Image affected.
459 pub image: ImageHandle,
460 /// Subrange affected.
461 pub range: ImageSubresourceRange,
462 /// State being left. [`ResourceState::Undefined`] discards contents.
463 pub from: ResourceState,
464 /// State being entered.
465 pub to: ResourceState,
466 /// Ownership transfer, if any.
467 pub queue_transfer: Option<QueueTransfer>,
468}
469
470impl ImageBarrier {
471 /// A same-queue transition of a whole image.
472 #[must_use]
473 pub const fn new(
474 image: ImageHandle,
475 range: ImageSubresourceRange,
476 from: ResourceState,
477 to: ResourceState,
478 ) -> Self {
479 Self {
480 image,
481 range,
482 from,
483 to,
484 queue_transfer: None,
485 }
486 }
487}
488
489/// A batch of barriers recorded as one call.
490///
491/// Batched rather than one-at-a-time because every backend pays a fixed cost per
492/// barrier *call*, and a graph that computed six transitions between two passes
493/// should emit one call, not six. An empty `Barriers` is legal and does nothing.
494#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
495pub struct Barriers<'a> {
496 /// Buffer transitions.
497 pub buffers: &'a [BufferBarrier],
498 /// Image transitions.
499 pub images: &'a [ImageBarrier],
500 /// Global execution+memory barrier with no specific resource, for the cases
501 /// where a graph knows a dependency exists but not which resource carries
502 /// it. Prefer the typed lists; this is the sledgehammer.
503 pub global: bool,
504}
505
506// --- copies ----------------------------------------------------------------
507
508/// A buffer-to-buffer copy region.
509#[derive(Clone, Copy, Debug, PartialEq, Eq)]
510pub struct BufferCopy {
511 /// Source buffer.
512 pub src: BufferHandle,
513 /// Byte offset in the source.
514 pub src_offset: u64,
515 /// Destination buffer.
516 pub dst: BufferHandle,
517 /// Byte offset in the destination.
518 pub dst_offset: u64,
519 /// Bytes copied.
520 pub size: u64,
521}
522
523/// A buffer↔image copy region.
524///
525/// One struct for both directions; which is the source is determined by the
526/// method called, not by a field, so the two can never disagree.
527#[derive(Clone, Copy, Debug, PartialEq, Eq)]
528pub struct BufferImageCopy {
529 /// Buffer side.
530 pub buffer: BufferHandle,
531 /// Byte offset in the buffer.
532 pub buffer_offset: u64,
533 /// Texels per row in the buffer; `0` means tightly packed. Must satisfy the
534 /// backend's row-pitch alignment when non-zero.
535 pub buffer_row_length: u32,
536 /// Rows per layer in the buffer; `0` means tightly packed.
537 pub buffer_image_height: u32,
538 /// Image side.
539 pub image: ImageHandle,
540 /// Mip level and layers touched.
541 pub image_subresource: ImageSubresourceLayers,
542 /// Texel offset within the image.
543 pub image_offset: Offset3d,
544 /// Region size in texels.
545 pub image_extent: Extent3d,
546}
547
548/// An image-to-image copy region.
549#[derive(Clone, Copy, Debug, PartialEq, Eq)]
550pub struct ImageCopy {
551 /// Source image.
552 pub src: ImageHandle,
553 /// Source mip level and layers.
554 pub src_subresource: ImageSubresourceLayers,
555 /// Source texel offset.
556 pub src_offset: Offset3d,
557 /// Destination image.
558 pub dst: ImageHandle,
559 /// Destination mip level and layers.
560 pub dst_subresource: ImageSubresourceLayers,
561 /// Destination texel offset.
562 pub dst_offset: Offset3d,
563 /// Region size in texels.
564 pub extent: Extent3d,
565}
566
567// --- indirect --------------------------------------------------------------
568
569/// Arguments for an indirect draw whose *count* is known on the CPU.
570///
571/// The argument buffer's contents are still GPU-written; only how many argument
572/// structures to read is fixed. This is
573/// [`GeometryPath::IndirectPerBatch`](crate::GeometryPath::IndirectPerBatch)'s
574/// draw path: one call per bucket with `draw_count` set to the bucket's
575/// capacity.
576///
577/// `draw_count > 1` requires
578/// [`Features::MULTI_DRAW_INDIRECT`](crate::Features::MULTI_DRAW_INDIRECT).
579///
580/// **Which structure the words are is the call's, not this type's.**
581/// [`draw_indirect`](CommandEncoder::draw_indirect) reads four words,
582/// [`draw_indexed_indirect`](CommandEncoder::draw_indexed_indirect) five and
583/// [`draw_mesh_tasks_indirect`](CommandEncoder::draw_mesh_tasks_indirect)
584/// three; each method's docs name the API structure it is. `stride` is what
585/// keeps them apart in a buffer, so it is spelled at the call site rather than
586/// derived here.
587#[derive(Clone, Copy, Debug, PartialEq, Eq)]
588pub struct DrawIndirect {
589 /// Buffer holding the argument structures. Must be in
590 /// [`ResourceState::IndirectArgument`].
591 pub args: BufferHandle,
592 /// Byte offset of the first argument structure.
593 pub offset: u64,
594 /// Number of argument structures to read.
595 pub draw_count: u32,
596 /// Bytes between consecutive argument structures.
597 pub stride: u32,
598}
599
600/// Arguments for an indirect draw whose count is *also* read from GPU memory.
601///
602/// [`GeometryPath::IndirectCount`](crate::GeometryPath::IndirectCount)'s
603/// steady-state draw call: a compute pass writes both the arguments and the
604/// count, and the CPU never learns how many draws happen. Requires
605/// [`Features::DRAW_INDIRECT_COUNT`](crate::Features::DRAW_INDIRECT_COUNT).
606#[derive(Clone, Copy, Debug, PartialEq, Eq)]
607pub struct DrawIndirectCount {
608 /// Buffer holding the argument structures.
609 pub args: BufferHandle,
610 /// Byte offset of the first argument structure.
611 pub args_offset: u64,
612 /// Buffer holding a `u32` draw count.
613 pub count_buffer: BufferHandle,
614 /// Byte offset of the count.
615 pub count_offset: u64,
616 /// Upper bound on draws, regardless of what the count buffer says. Bounded
617 /// by [`Limits::max_draw_indirect_count`](crate::Limits::max_draw_indirect_count).
618 pub max_draw_count: u32,
619 /// Bytes between consecutive argument structures.
620 pub stride: u32,
621}
622
623// --- the encoder -----------------------------------------------------------
624
625/// Records commands into a command buffer.
626///
627/// Obtained from [`Device::create_command_encoder`](crate::Device::create_command_encoder)
628/// and consumed by [`finish`](CommandEncoder::finish). One encoder produces one
629/// command buffer.
630///
631/// # Scope rules
632///
633/// * Draw commands, [`set_viewport`](CommandEncoder::set_viewport),
634/// [`set_scissor`](CommandEncoder::set_scissor) and
635/// [`bind_graphics_pipeline`](CommandEncoder::bind_graphics_pipeline) are legal
636/// only between `begin_render_pass` and `end_render_pass`.
637/// * [`dispatch`](CommandEncoder::dispatch) and
638/// [`bind_compute_pipeline`](CommandEncoder::bind_compute_pipeline) are legal
639/// only inside a compute pass.
640/// * Copies, barriers and query resets/resolves are legal only **outside** any
641/// pass — Vulkan forbids them inside dynamic rendering, and the render graph
642/// places them between passes anyway. Timestamps are the exception that
643/// proves the rule: they are not a call at all, but
644/// [`PassTimestampWrites`] on the pass descriptor.
645/// * Passes do not nest.
646///
647/// A backend may assume these hold. [`crate::null`] checks them and records a
648/// validation error, which is how the graph's unit suite catches a violation
649/// without a GPU.
650///
651/// # Thread safety
652///
653/// `Send + Sync` on native, through
654/// [`HalThreadSafe`](crate::threading::HalThreadSafe) — an encoder may be moved
655/// to a worker thread and recorded there, which the P8 job system will do.
656///
657/// Vulkan's external-synchronisation rule for command buffers ("two threads may
658/// not record into one") is discharged by `&mut self` on every recording
659/// method, not by dropping `Sync`: two threads cannot hold `&mut` to the same
660/// encoder, and `&self` alone can record nothing. An earlier version of this
661/// doc claimed `Send` but not `Sync`, which contradicted the trait's own bound
662/// — every implementor has always had to be `Sync`.
663///
664/// On `wasm32` the bound is vacuous, because wgpu's web types are `!Send` and
665/// the browser is single-threaded.
666pub trait CommandEncoder: core::fmt::Debug + crate::threading::HalThreadSafe {
667 // --- debug ---
668
669 /// Opens a named region in capture tools and profilers.
670 ///
671 /// Accepted and dropped when
672 /// [`Features::DEBUG_MARKERS`](crate::Features::DEBUG_MARKERS) is absent —
673 /// debug instrumentation degrades, it does not break the build (topic 10's
674 /// stated policy).
675 fn begin_debug_label(&mut self, label: &str);
676
677 /// Closes the most recent [`begin_debug_label`](CommandEncoder::begin_debug_label).
678 fn end_debug_label(&mut self);
679
680 /// Inserts a zero-width marker.
681 fn insert_debug_marker(&mut self, label: &str);
682
683 // --- sync ---
684
685 /// Records a batch of state transitions.
686 ///
687 /// The only way to synchronise inside a command buffer. See the module docs
688 /// for the division of labour: this seam expresses barriers, the render
689 /// graph decides where they go.
690 fn pipeline_barrier(&mut self, barriers: &Barriers<'_>);
691
692 // --- copies ---
693
694 /// Buffer-to-buffer copy.
695 fn copy_buffer_to_buffer(&mut self, copy: &BufferCopy);
696
697 /// Buffer-to-image copy — the texture upload path.
698 fn copy_buffer_to_image(&mut self, copy: &BufferImageCopy);
699
700 /// Image-to-buffer copy — the readback path (`crcbl screenshot`, the
701 /// delayed debug ring).
702 fn copy_image_to_buffer(&mut self, copy: &BufferImageCopy);
703
704 /// Image-to-image copy.
705 fn copy_image_to_image(&mut self, copy: &ImageCopy);
706
707 /// Zeroes a buffer range.
708 ///
709 /// **Zero and nothing else, which is why it is a clear rather than a fill.**
710 /// This took a `value: u32` until 2026-08-19 and promised "a repeating
711 /// 32-bit value", which two of the four backends could never keep: Metal's
712 /// `fillBuffer:range:value:` repeats a *byte*, so only a word with four
713 /// equal bytes has an encoding, and WebGPU offers `clearBuffer` and no
714 /// valued fill at all. A parameter three backends had to refuse most values
715 /// of is not a seam, and `Capability::BufferFillRepeatedByte` and
716 /// `BufferFillWord` existed only to describe how badly each one could keep
717 /// the promise.
718 ///
719 /// The name follows what the backends call it — `clearBuffer` on WebGPU,
720 /// `clear_buffer` on wgpu — rather than what one of them could do.
721 ///
722 /// Zeroing an indirect count at the top of a frame is the use this was
723 /// written for, and it is **not** what the renderer does: a clear is legal
724 /// only outside a pass, and a render-graph frame is passes end to end. See
725 /// `crcbl_shaders::clear_counters`, which zeroes from inside the graph and
726 /// is what let those counters become device-local.
727 fn clear_buffer(&mut self, buffer: BufferHandle, offset: u64, size: u64);
728
729 // --- render scope ---
730
731 /// Opens a render pass. Attachments must already be in the right state.
732 fn begin_render_pass(&mut self, desc: &RenderPassDesc<'_>);
733
734 /// Closes the current render pass.
735 fn end_render_pass(&mut self);
736
737 /// Sets the viewport transform. See [`Viewport`] on the depth range and
738 /// reversed-Z.
739 fn set_viewport(&mut self, viewport: &Viewport);
740
741 /// Sets the scissor rectangle.
742 fn set_scissor(&mut self, rect: &Rect2d);
743
744 /// Sets the stencil reference value for subsequent draws — the value each
745 /// [`StencilFaceState::compare`](crate::StencilFaceState::compare) tests
746 /// against and [`StencilOp::Replace`](crate::StencilOp::Replace) writes.
747 ///
748 /// **The only channel there is.** [`StencilState`](crate::StencilState)
749 /// carries no reference of its own, because two of the APIs behind this
750 /// seam have no pipeline field to put one in. The rule every backend
751 /// implements, and which
752 /// [`Capability::StencilReference`](crate::Capability::StencilReference)
753 /// stands for:
754 ///
755 /// * The reference is **pass state**: a pass opens holding
756 /// [`stencil::INITIAL_REFERENCE`] and
757 /// keeps whatever this call last set until it ends.
758 /// * **Binding a graphics pipeline does not disturb it.** A call made
759 /// before a bind is still in force for the draws after it.
760 fn set_stencil_reference(&mut self, reference: u32);
761
762 /// Binds a graphics pipeline.
763 fn bind_graphics_pipeline(&mut self, pipeline: GraphicsPipelineHandle);
764
765 /// Binds an index buffer.
766 ///
767 /// There is no `bind_vertex_buffer`: geometry is pulled from storage
768 /// buffers. See [`crate::pipeline`].
769 fn bind_index_buffer(&mut self, buffer: BufferHandle, offset: u64, format: IndexFormat);
770
771 // --- bindings, shared by both scopes ---
772
773 /// Binds a bind group at `slot`, with dynamic offsets for any
774 /// dynamic-offset bindings in its layout, in binding order.
775 ///
776 /// `dynamic_offsets` is the substitute for push constants on a device
777 /// without them — see
778 /// [`BindingKind::UniformBuffer`](crate::BindingKind::UniformBuffer).
779 fn bind_group(
780 &mut self,
781 slot: u32,
782 group: BindGroupHandle,
783 dynamic_offsets: &[u32],
784 layout: PipelineLayoutHandle,
785 );
786
787 /// Writes push constants.
788 ///
789 /// Requires [`Features::PUSH_CONSTANTS`](crate::Features::PUSH_CONSTANTS).
790 /// A backend without it must fail loudly at pipeline-layout creation rather
791 /// than silently dropping the write here.
792 fn push_constants(
793 &mut self,
794 stages: ShaderStages,
795 offset: u32,
796 data: &[u8],
797 layout: PipelineLayoutHandle,
798 );
799
800 // --- draws ---
801
802 /// Non-indexed draw. For full-screen triangles and bring-up; the geometry
803 /// path is indirect.
804 fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>);
805
806 /// Indexed draw.
807 fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>);
808
809 /// Indirect non-indexed draw with a CPU-known draw count.
810 fn draw_indirect(&mut self, draw: &DrawIndirect);
811
812 /// Indirect indexed draw with a CPU-known draw count.
813 /// **[`GeometryPath::IndirectPerBatch`](crate::GeometryPath::IndirectPerBatch)'s
814 /// draw path**, one call per bucket.
815 fn draw_indexed_indirect(&mut self, draw: &DrawIndirect);
816
817 /// Indirect non-indexed draw with a GPU-read draw count.
818 fn draw_indirect_count(&mut self, draw: &DrawIndirectCount);
819
820 /// Indirect indexed draw with a GPU-read draw count.
821 /// **[`GeometryPath::IndirectCount`](crate::GeometryPath::IndirectCount)'s
822 /// steady-state draw call** — one per pass, regardless of scene size.
823 fn draw_indexed_indirect_count(&mut self, draw: &DrawIndirectCount);
824
825 /// Launches a mesh-shading workload, in workgroups —
826 /// **[`GeometryPath::MeshShader`](crate::GeometryPath::MeshShader)'s draw
827 /// call**.
828 ///
829 /// `x`, `y` and `z` count workgroups of the *first* stage the bound
830 /// pipeline has: the task stage when
831 /// [`MeshPipelineDesc::task`](crate::MeshPipelineDesc::task) was `Some`,
832 /// and the mesh stage otherwise. That is Vulkan's rule for
833 /// `vkCmdDrawMeshTasksEXT`, D3D12's for `DispatchMesh`, and Metal's for
834 /// `drawMeshThreadgroups:`, so it is the seam's rule too.
835 ///
836 /// This is a *draw*, not a dispatch: it belongs inside a render pass with a
837 /// mesh pipeline bound, and its output is fragments rather than buffer
838 /// writes. The three-dimensional count is why it does not reuse
839 /// [`draw`](CommandEncoder::draw)'s vertex/instance ranges — there are no
840 /// vertices to range over.
841 ///
842 /// Requires [`Features::MESH_SHADER`](crate::Features::MESH_SHADER), which
843 /// [`create_mesh_pipeline`](crate::Device::create_mesh_pipeline) has
844 /// already refused without.
845 fn draw_mesh_tasks(&mut self, x: u32, y: u32, z: u32);
846
847 /// [`draw_mesh_tasks`](CommandEncoder::draw_mesh_tasks) with the workgroup
848 /// counts read from GPU memory — **the shape a culling pass's output needs
849 /// to reduce work rather than only output**.
850 ///
851 /// # The argument layout
852 ///
853 /// One argument structure is **three consecutive 32-bit words**: the x, y
854 /// and z workgroup counts, in that order, of the same stage
855 /// [`draw_mesh_tasks`](CommandEncoder::draw_mesh_tasks) counts groups of.
856 /// The layout is not this seam's to choose — it is
857 /// `VkDrawMeshTasksIndirectCommandEXT`, `D3D12_DISPATCH_MESH_ARGUMENTS` and
858 /// Metal's `MTLDispatchThreadgroupsIndirectArguments`, which are the same
859 /// three words in the same order, because a driver reads these bytes
860 /// directly.
861 ///
862 /// [`DrawIndirect::stride`] is therefore 12 for a tightly packed buffer, and
863 /// [`DrawIndirect::offset`] must be a multiple of 4.
864 /// [`draw_count`](DrawIndirect::draw_count) `> 1` requires
865 /// [`Features::MULTI_DRAW_INDIRECT`](crate::Features::MULTI_DRAW_INDIRECT),
866 /// exactly as it does for the indexed form.
867 ///
868 /// [`DrawIndirect::args`] must be in
869 /// [`ResourceState::IndirectArgument`] — a buffer the same pass also reads
870 /// as a storage buffer is in one state or the other, never both, so a
871 /// caller that needs both wants two buffers.
872 ///
873 /// # Capability
874 ///
875 /// Requires [`Features::MESH_SHADER`](crate::Features::MESH_SHADER) and
876 /// nothing more. There is no separate flag because none of the three APIs
877 /// has one: `VK_EXT_mesh_shader` defines `vkCmdDrawMeshTasksIndirectEXT`
878 /// alongside `vkCmdDrawMeshTasksEXT`, D3D12 mesh shader tier 1 admits
879 /// `D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH` in a command signature, and
880 /// a Metal device with mesh functions has
881 /// `drawMeshThreadgroupsWithIndirectBuffer:`. A device that can launch this
882 /// stage at all can launch it from memory.
883 fn draw_mesh_tasks_indirect(&mut self, draw: &DrawIndirect);
884
885 // --- compute scope ---
886
887 /// Opens a compute pass.
888 fn begin_compute_pass(&mut self, desc: &ComputePassDesc<'_>);
889
890 /// Closes the current compute pass.
891 fn end_compute_pass(&mut self);
892
893 /// Binds a compute pipeline.
894 fn bind_compute_pipeline(&mut self, pipeline: ComputePipelineHandle);
895
896 /// Dispatches a compute workload, in workgroups.
897 fn dispatch(&mut self, x: u32, y: u32, z: u32);
898
899 /// Dispatches with the workgroup counts read from GPU memory — the shape a
900 /// variable-size culling or compaction pass needs.
901 fn dispatch_indirect(&mut self, args: BufferHandle, offset: u64);
902
903 // --- queries ---
904
905 /// Resets a query range so it can be written again.
906 ///
907 /// Required on Vulkan before every write; a no-op on backends that reset
908 /// implicitly. Callers always call it, so the Vulkan path is never the
909 /// special case.
910 ///
911 /// **What is written between a reset and a resolve is
912 /// [`RenderPassDesc::timestamp_writes`]**, not a call of its own: see
913 /// [`PassTimestampWrites`] for why the seam has no free-standing timestamp.
914 fn reset_query_set(&mut self, set: QuerySetHandle, range: Range<u32>);
915
916 /// Copies query results into a buffer, **as the device wrote them**.
917 ///
918 /// The counterpart of [`Device::query_results`](crate::Device::query_results)
919 /// and the one place the two read paths differ: that one reports a
920 /// [`QueryKind::Timestamp`](crate::QueryKind::Timestamp) in nanoseconds, and
921 /// this one cannot. It records a GPU-side copy — `vkCmdCopyQueryPoolResults`,
922 /// `ResolveQueryData`, `GPUCommandEncoder.resolveQuerySet` — so the values
923 /// never pass through the CPU and there is nowhere to apply a scale. A
924 /// caller reading the destination gets the device's own clock units, and
925 /// what those are worth is a question only the backend can answer.
926 ///
927 /// So this is for feeding a delta back to the GPU — a shader that compares
928 /// two readings, which needs no unit — and
929 /// [`Device::query_results`](crate::Device::query_results) is for a number a
930 /// human or a HUD is going to read.
931 fn resolve_query_set(
932 &mut self,
933 set: QuerySetHandle,
934 range: Range<u32>,
935 dst: BufferHandle,
936 dst_offset: u64,
937 );
938
939 // --- finish ---
940
941 /// Ends recording and produces a submittable command buffer.
942 ///
943 /// Takes `Box<Self>` rather than `self` so the method stays object-safe:
944 /// `Box<dyn CommandEncoder>` can call it, a bare `self` receiver could not.
945 ///
946 /// # Errors
947 ///
948 /// Returns [`HalError`] if the backend rejected the recorded stream — an
949 /// unclosed pass, an out-of-range value, or an out-of-memory condition in
950 /// the command pool.
951 fn finish(self: Box<Self>) -> Result<CommandBufferHandle, HalError>;
952}
953
954/// Creation parameters for a command encoder.
955#[derive(Clone, Copy, Debug, PartialEq, Eq)]
956pub struct CommandEncoderDesc<'a> {
957 /// Debug name; see [`BufferDesc::label`](crate::BufferDesc::label).
958 pub label: Option<&'a str>,
959 /// Queue the resulting command buffer will be submitted to.
960 ///
961 /// Named at creation because Vulkan command pools are per-queue-family and
962 /// DX12 command allocators are per-type; discovering it at submit time
963 /// would force a copy.
964 pub queue: QueueHandle,
965}
966
967#[cfg(test)]
968mod tests {
969 use super::*;
970
971 #[test]
972 fn clear_defaults_to_the_reversed_z_far_plane() {
973 let clear = ClearValue::default();
974 assert_eq!(clear.depth, depth::CLEAR);
975 assert_eq!(clear.depth, 0.0);
976 assert_eq!(clear.color, [0.0; 4]);
977 // A colour clear must not quietly reintroduce conventional-Z depth.
978 assert_eq!(ClearValue::color([1.0, 0.0, 0.0, 1.0]).depth, depth::CLEAR);
979 }
980
981 #[test]
982 fn depth_constants_bracket_the_range_in_reversed_order() {
983 assert_eq!(depth::NEAR, 1.0);
984 assert_eq!(depth::FAR, 0.0);
985 // A const block: the relationship is a compile-time invariant of the
986 // depth convention, not a runtime property.
987 const {
988 assert!(
989 depth::NEAR > depth::FAR,
990 "reversed-Z: the near plane holds the larger value"
991 );
992 }
993 }
994
995 #[test]
996 fn attachment_load_defaults_to_dont_care() {
997 // Preserving contents must be asked for: `Load` is the expensive option
998 // on tile-based GPUs and is wrong for a swapchain image.
999 assert_eq!(LoadOp::default(), LoadOp::DontCare);
1000 assert_eq!(StoreOp::default(), StoreOp::Store);
1001 }
1002
1003 #[test]
1004 fn write_states_are_classified() {
1005 assert!(ResourceState::ColorAttachment.is_write());
1006 assert!(ResourceState::TransferDst.is_write());
1007 assert!(ResourceState::ShaderReadWrite.is_write());
1008 // Its name argues for this one and so does the store op: no backend
1009 // writes an attachment left in this state, so two read-only depth
1010 // passes in a row need no barrier between them.
1011 assert!(!ResourceState::DepthStencilRead.is_write());
1012 assert!(!ResourceState::ShaderRead.is_write());
1013 assert!(!ResourceState::IndirectArgument.is_write());
1014 assert!(!ResourceState::Undefined.is_write());
1015 }
1016
1017 #[test]
1018 fn read_to_same_read_needs_no_barrier_but_read_to_other_read_does() {
1019 use ResourceState as S;
1020 assert!(!S::needs_barrier(S::ShaderRead, S::ShaderRead));
1021 // Different reads still differ in image layout on vk/dx12.
1022 assert!(S::needs_barrier(S::ShaderRead, S::IndirectArgument));
1023 assert!(S::needs_barrier(S::ShaderRead, S::TransferSrc));
1024 // Anything involving a write always needs one.
1025 assert!(S::needs_barrier(S::ShaderWrite, S::ShaderWrite));
1026 assert!(S::needs_barrier(S::ShaderWrite, S::IndirectArgument));
1027 assert!(S::needs_barrier(S::Undefined, S::ColorAttachment));
1028 // Back-to-back depth-test-only passes: nothing stores, so nothing
1029 // orders. The prepass that filled the image is still a write and still
1030 // gets one.
1031 assert!(!S::needs_barrier(S::DepthStencilRead, S::DepthStencilRead));
1032 assert!(S::needs_barrier(S::DepthStencilWrite, S::DepthStencilRead));
1033 }
1034
1035 #[test]
1036 fn barriers_default_to_empty_and_non_global() {
1037 let barriers = Barriers::default();
1038 assert!(barriers.buffers.is_empty());
1039 assert!(barriers.images.is_empty());
1040 assert!(!barriers.global);
1041 }
1042
1043 #[test]
1044 fn same_queue_barrier_constructors_leave_ownership_alone() {
1045 let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
1046 let buffer: BufferHandle = pool.insert(0).cast();
1047 let barrier = BufferBarrier::new(
1048 buffer,
1049 ResourceState::ShaderWrite,
1050 ResourceState::IndirectArgument,
1051 );
1052 assert!(barrier.queue_transfer.is_none());
1053 assert_eq!(barrier.to, ResourceState::IndirectArgument);
1054 }
1055
1056 #[test]
1057 fn default_resource_state_is_undefined() {
1058 // A freshly created resource has no meaningful contents, and the graph's
1059 // first transition must therefore be free to discard them.
1060 assert_eq!(ResourceState::default(), ResourceState::Undefined);
1061 }
1062}