Skip to main content

gpu/
vk_cmd.rs

1// vk_cmd -- command recording: CommandEncoder -> CommandBuffer
2//
3//   device.encoder() -> Result<CommandEncoder>      a command buffer slot, begun
4//   copies (outside render passes): copy_buffer, fill_buffer, copy_buffer_to_texture (the
5//        region in Layout::CopyDst), copy_texture_to_buffer (Layout::CopySrc)
6//   barrier(before: Access, after: Access)          a global memory barrier
7//   texture_barrier(tex, before, after) / texture_barrier_range(.., mips, layers, ..)
8//   set_compute_pipeline, set_bind_group(g, &group), push_constants(off, &[T]),
9//        dispatch(x, y, z), dispatch_indirect(&buf, off)
10//   begin_render(&RenderPassDesc) .. end_render()   dynamic rendering; the attachments go from
11//        `before` to ColorTarget / DepthTarget at the start and to `after` at the end; viewport
12//        and scissor = the whole target
13//   set_render_pipeline, set_viewport, set_scissor, set_vertex_buffer, set_index_buffer,
14//        draw, draw_indexed, draw_indirect, draw_indexed_indirect (Basis), and on Voll
15//        draw_indexed_indirect_multi and draw_indexed_indirect_count
16//   reset_timestamps(&ts, first, n) (outside passes), timestamp(&ts, i)
17//   finish() -> Result<CommandBuffer>               the first misuse recorded, if any
18//
19// Bind groups and push constants go to the pipeline set last: the compute pipeline outside
20// render passes, the render pipeline inside (set the pipeline first).  Every command checks
21// what the backend can know cheaply (the pipeline and pass state, bind group / pipeline layout
22// compatibility, target formats, buffer usages, ranges and alignments, the Voll features); a
23// failed check skips the command and finish() returns it as GpuError::Invalid.
24//
25// Stages and accesses per Layout (texture_barrier, attachments, write_texture), as (source;
26// destination): Undefined (colour output + copy + compute, no access -- the stages the
27// swapchain acquisition waits at; not a destination), General (all commands, memory read /
28// write), CopySrc / CopyDst (transfer), Sampled (vertex + fragment + compute shaders), ColorTarget
29// (colour output), DepthTarget (early + late fragment tests), DepthRead (fragment tests and
30// shaders), Present (as Undefined; bottom of pipe).
31// Viewport: y flipped (origin top left, NDC y up: lib.rs conventions).
32// (G5d) An encoder of the compute queue (ComputeQueue::encoder) records no render pass, and its barriers keep the
33// stages and accesses a compute family has (compute, copies, indirect arguments, the host): the graphics stages of a
34// layout or of Access flags fall away there.
35
36use alloc::vec::Vec;
37use core::marker::PhantomData;
38
39use crate::vk_dev::{Device, Shared, Slot};
40use crate::vk_ffi as vk;
41use crate::vk_res::{PipeInner, copy_region, subresources};
42use crate::*;
43
44/// what an image handed to the window is in: Linux has no VK_KHR_swapchain, vk_dmabuf.rs hands
45/// dma-bufs over in GENERAL
46const LAYOUT_PRESENT: u32 = if cfg!(jfgui_glibc) { vk::IMAGE_LAYOUT_GENERAL } else { vk::IMAGE_LAYOUT_PRESENT_SRC_KHR };
47
48/// (vk layout, stages, access) of a layout as the source of a barrier
49fn src_of(l: Layout) -> (u32, u32, u32) {
50    let shaders = vk::PIPELINE_STAGE_VERTEX_SHADER_BIT | vk::PIPELINE_STAGE_FRAGMENT_SHADER_BIT | vk::PIPELINE_STAGE_COMPUTE_SHADER_BIT;
51    let tests = vk::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | vk::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
52    let acquire = vk::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | vk::PIPELINE_STAGE_TRANSFER_BIT | vk::PIPELINE_STAGE_COMPUTE_SHADER_BIT;
53    match l {
54        Layout::Undefined => (vk::IMAGE_LAYOUT_UNDEFINED, acquire, 0),
55        Layout::General => (vk::IMAGE_LAYOUT_GENERAL, vk::PIPELINE_STAGE_ALL_COMMANDS_BIT, vk::ACCESS_MEMORY_WRITE_BIT),
56        Layout::CopySrc => (vk::IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, vk::PIPELINE_STAGE_TRANSFER_BIT, 0),
57        Layout::CopyDst => (vk::IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, vk::PIPELINE_STAGE_TRANSFER_BIT, vk::ACCESS_TRANSFER_WRITE_BIT),
58        Layout::Sampled => (vk::IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, shaders, 0),
59        Layout::ColorTarget => (vk::IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, vk::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
60                                vk::ACCESS_COLOR_ATTACHMENT_WRITE_BIT),
61        Layout::DepthTarget => (vk::IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, tests, vk::ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT),
62        Layout::DepthRead => (vk::IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, tests | shaders, 0),
63        Layout::Present => (LAYOUT_PRESENT, acquire, 0),
64    }
65}
66
67/// (vk layout, stages, access) of a layout as the destination of a barrier
68fn dst_of(l: Layout) -> (u32, u32, u32) {
69    let shaders = vk::PIPELINE_STAGE_VERTEX_SHADER_BIT | vk::PIPELINE_STAGE_FRAGMENT_SHADER_BIT | vk::PIPELINE_STAGE_COMPUTE_SHADER_BIT;
70    let tests = vk::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | vk::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
71    match l {
72        Layout::Undefined => (vk::IMAGE_LAYOUT_UNDEFINED, vk::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0),
73        Layout::General => (vk::IMAGE_LAYOUT_GENERAL, vk::PIPELINE_STAGE_ALL_COMMANDS_BIT,
74                            vk::ACCESS_MEMORY_READ_BIT | vk::ACCESS_MEMORY_WRITE_BIT),
75        Layout::CopySrc => (vk::IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, vk::PIPELINE_STAGE_TRANSFER_BIT, vk::ACCESS_TRANSFER_READ_BIT),
76        Layout::CopyDst => (vk::IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, vk::PIPELINE_STAGE_TRANSFER_BIT, vk::ACCESS_TRANSFER_WRITE_BIT),
77        Layout::Sampled => (vk::IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, shaders, vk::ACCESS_SHADER_READ_BIT),
78        Layout::ColorTarget => (vk::IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, vk::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
79                                vk::ACCESS_COLOR_ATTACHMENT_READ_BIT | vk::ACCESS_COLOR_ATTACHMENT_WRITE_BIT),
80        Layout::DepthTarget => (vk::IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, tests,
81                                vk::ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | vk::ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT),
82        Layout::DepthRead => (vk::IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, tests | shaders,
83                              vk::ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | vk::ACCESS_SHADER_READ_BIT),
84        Layout::Present => (LAYOUT_PRESENT, vk::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0),
85    }
86}
87
88fn image_barrier_info(image: vk::Handle, range: vk::ImageSubresourceRange, before: Layout, after: Layout)
89                      -> (vk::ImageMemoryBarrier, u32, u32) {
90    let (ol, ss, sa) = src_of(before);
91    let (nl, ds, da) = dst_of(after);
92    let b = vk::ImageMemoryBarrier {
93        s_type: vk::STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
94        src_access_mask: sa,
95        dst_access_mask: da,
96        old_layout: ol,
97        new_layout: nl,
98        src_queue_family_index: vk::QUEUE_FAMILY_IGNORED,
99        dst_queue_family_index: vk::QUEUE_FAMILY_IGNORED,
100        image,
101        subresource_range: range,
102        ..vk::Zero::zero()
103    };
104    (b, ss, ds)
105}
106
107/// record one image layout transition
108///
109/// # Safety
110/// cb is recording outside a render pass; image belongs to f's device.
111pub(crate) unsafe fn image_barrier(f: &vk::DeviceFns, cb: vk::CommandBuffer, image: vk::Handle, range: vk::ImageSubresourceRange,
112                                   before: Layout, after: Layout) {
113    let (b, ss, ds) = image_barrier_info(image, range, before, after);
114    // SAFETY: the caller's contract.
115    unsafe { (f.cmd_pipeline_barrier)(cb, ss, ds, 0, 0, core::ptr::null(), 0, core::ptr::null(), 1, &b) };
116}
117
118/// (G5d) the stages and accesses a queue family without graphics has
119const COMPUTE_STAGES: u32 = vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT | vk::PIPELINE_STAGE_DRAW_INDIRECT_BIT | vk::PIPELINE_STAGE_COMPUTE_SHADER_BIT
120    | vk::PIPELINE_STAGE_TRANSFER_BIT | vk::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT | vk::PIPELINE_STAGE_HOST_BIT | vk::PIPELINE_STAGE_ALL_COMMANDS_BIT;
121const COMPUTE_ACCESS: u32 = vk::ACCESS_INDIRECT_COMMAND_READ_BIT | vk::ACCESS_UNIFORM_READ_BIT | vk::ACCESS_SHADER_READ_BIT | vk::ACCESS_SHADER_WRITE_BIT
122    | vk::ACCESS_TRANSFER_READ_BIT | vk::ACCESS_TRANSFER_WRITE_BIT | vk::ACCESS_HOST_READ_BIT | vk::ACCESS_HOST_WRITE_BIT | vk::ACCESS_MEMORY_READ_BIT
123    | vk::ACCESS_MEMORY_WRITE_BIT;
124
125/// (stages, source access, destination access) of Access flags
126fn access_of(a: Access) -> (u32, u32, u32) {
127    let table: [(Access, u32, u32, u32); 12] = [
128        (Access::COPY_READ, vk::PIPELINE_STAGE_TRANSFER_BIT, 0, vk::ACCESS_TRANSFER_READ_BIT),
129        (Access::COPY_WRITE, vk::PIPELINE_STAGE_TRANSFER_BIT, vk::ACCESS_TRANSFER_WRITE_BIT, vk::ACCESS_TRANSFER_WRITE_BIT),
130        (Access::COMPUTE_READ, vk::PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, vk::ACCESS_SHADER_READ_BIT | vk::ACCESS_UNIFORM_READ_BIT),
131        (Access::COMPUTE_WRITE, vk::PIPELINE_STAGE_COMPUTE_SHADER_BIT, vk::ACCESS_SHADER_WRITE_BIT,
132         vk::ACCESS_SHADER_READ_BIT | vk::ACCESS_SHADER_WRITE_BIT),
133        (Access::GRAPHICS_READ, vk::PIPELINE_STAGE_VERTEX_SHADER_BIT | vk::PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0,
134         vk::ACCESS_SHADER_READ_BIT | vk::ACCESS_UNIFORM_READ_BIT),
135        (Access::GRAPHICS_WRITE, vk::PIPELINE_STAGE_VERTEX_SHADER_BIT | vk::PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
136         vk::ACCESS_SHADER_WRITE_BIT, vk::ACCESS_SHADER_READ_BIT | vk::ACCESS_SHADER_WRITE_BIT),
137        (Access::INDIRECT, vk::PIPELINE_STAGE_DRAW_INDIRECT_BIT, 0, vk::ACCESS_INDIRECT_COMMAND_READ_BIT),
138        (Access::INDEX_VERTEX, vk::PIPELINE_STAGE_VERTEX_INPUT_BIT, 0,
139         vk::ACCESS_INDEX_READ_BIT | vk::ACCESS_VERTEX_ATTRIBUTE_READ_BIT),
140        (Access::COLOR_TARGET, vk::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, vk::ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
141         vk::ACCESS_COLOR_ATTACHMENT_READ_BIT | vk::ACCESS_COLOR_ATTACHMENT_WRITE_BIT),
142        (Access::DEPTH_TARGET, vk::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | vk::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
143         vk::ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
144         vk::ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | vk::ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT),
145        (Access::HOST_READ, vk::PIPELINE_STAGE_HOST_BIT, 0, vk::ACCESS_HOST_READ_BIT),
146        (Access::HOST_WRITE, vk::PIPELINE_STAGE_HOST_BIT, vk::ACCESS_HOST_WRITE_BIT, vk::ACCESS_HOST_WRITE_BIT),
147    ];
148    let mut out = (0, 0, 0);
149    for (flag, st, sa, da) in table {
150        if a.intersects(flag) {
151            out.0 |= st;
152            out.1 |= sa;
153            out.2 |= da;
154        }
155    }
156    out
157}
158
159/// an attachment's transition at the end of a pass
160struct EndBarrier {
161    image: vk::Handle,
162    range: vk::ImageSubresourceRange,
163    from: Layout,
164    to: Layout,
165}
166
167struct Pass {
168    colors: [u32; COLOR_TARGETS_MAX],
169    n: usize,
170    depth: u32,
171    end: Vec<EndBarrier>,
172    /// a draw was recorded in it
173    drew: bool,
174    /// the attachments it clears (Load::Clear), cleared again at its end if it drew nothing (end_render)
175    clears: Vec<vk::ClearAttachment>,
176    size: (u32, u32),
177}
178
179/// records commands; finish() makes a CommandBuffer for Queue::submit
180pub struct CommandEncoder<'a> {
181    sh: &'a Shared,
182    slot: Option<Slot>,
183    /// (G5d) of the compute queue's family
184    compute: bool,
185    cb: vk::CommandBuffer,
186    err: Option<GpuError>,
187    pass: Option<Pass>,
188    compute_pipe: Option<&'a PipeInner>,
189    graphics: Option<&'a PipeInner>,
190    index: bool,
191    _borrow: PhantomData<&'a ()>,
192}
193
194/// recorded commands, ready to submit (dropped unsubmitted: discarded)
195pub struct CommandBuffer<'a> {
196    sh: &'a Shared,
197    slot: Option<Slot>,
198}
199
200impl CommandBuffer<'_> {
201    pub(crate) fn into_slot(mut self) -> Slot {
202        self.slot.take().unwrap_or_else(|| unreachable!())
203    }
204}
205
206impl Drop for CommandBuffer<'_> {
207    fn drop(&mut self) {
208        if let Some(s) = self.slot.take() {
209            self.sh.give_slot(s);
210        }
211    }
212}
213
214impl Drop for CommandEncoder<'_> {
215    fn drop(&mut self) {
216        if let Some(s) = self.slot.take() {
217            // the buffer is recording (maybe inside a pass) and never submitted: resetting its
218            // pool returns it to the initial state
219            self.sh.give_slot(s);
220        }
221    }
222}
223
224impl Device {
225    /// a command encoder (a recording command buffer) of the device's queue
226    pub fn encoder(&self) -> Result<CommandEncoder<'_>> {
227        CommandEncoder::of(&self.sh, false)
228    }
229}
230
231impl<'a> CommandEncoder<'a> {
232    /// (G5d) an encoder of the device queue's family or of the compute queue's
233    pub(crate) fn of(sh: &'a Shared, compute: bool) -> Result<CommandEncoder<'a>> {
234        let slot = sh.take_slot_for(compute)?;
235        Ok(CommandEncoder {
236            sh,
237            cb: slot.cb,
238            slot: Some(slot),
239            compute,
240            err: None,
241            pass: None,
242            compute_pipe: None,
243            graphics: None,
244            index: false,
245            _borrow: PhantomData,
246        })
247    }
248
249    /// (G5d) stages and accesses this encoder's queue has
250    fn fit(&self, stages: u32, access: u32) -> (u32, u32) {
251        if self.compute { (stages & COMPUTE_STAGES, access & COMPUTE_ACCESS) } else { (stages, access) }
252    }
253}
254
255impl<'a> CommandEncoder<'a> {
256    /// record the first misuse; Some(()) when the command may be recorded
257    #[inline]
258    fn ok(&mut self, cond: bool, what: &'static str) -> Option<()> {
259        if self.err.is_some() {
260            return None;
261        }
262        if !cond {
263            self.err = Some(GpuError::Invalid(what));
264            return None;
265        }
266        Some(())
267    }
268
269    #[inline]
270    fn outside(&mut self, what: &'static str) -> Option<()> {
271        let c = self.pass.is_none();
272        self.ok(c, what)
273    }
274
275    fn buf_range(&mut self, b: &Buffer, off: u64, n: u64, what: &'static str) -> Option<()> {
276        let c = off.checked_add(n).is_some_and(|e| e <= b.size());
277        self.ok(c, what)
278    }
279
280    // ------------------------------------------------------------ copies
281
282    pub fn copy_buffer(&mut self, src: &'a Buffer, src_off: u64, dst: &'a Buffer, dst_off: u64, size: u64) {
283        if self.outside("copy_buffer inside a render pass").is_none()
284            || self.buf_range(src, src_off, size, "copy_buffer: source range").is_none()
285            || self.buf_range(dst, dst_off, size, "copy_buffer: destination range").is_none()
286            || size == 0
287        {
288            return;
289        }
290        let r = vk::BufferCopy { src_offset: src_off, dst_offset: dst_off, size };
291        // SAFETY: recording; ranges checked.
292        unsafe { (self.sh.f.cmd_copy_buffer)(self.cb, src.handle(), dst.handle(), 1, &r) };
293    }
294
295    /// fill size bytes at offset with a 32-bit value (both multiples of 4)
296    pub fn fill_buffer(&mut self, buf: &'a Buffer, offset: u64, size: u64, value: u32) {
297        if self.outside("fill_buffer inside a render pass").is_none()
298            || self.ok(offset % 4 == 0 && size % 4 == 0 && size > 0, "fill_buffer: offset and size multiples of 4").is_none()
299            || self.buf_range(buf, offset, size, "fill_buffer: range").is_none()
300        {
301            return;
302        }
303        // SAFETY: recording; range checked.
304        unsafe { (self.sh.f.cmd_fill_buffer)(self.cb, buf.handle(), offset, size, value) };
305    }
306
307    /// buffer data -> a texture region (the region in Layout::CopyDst)
308    pub fn copy_buffer_to_texture(&mut self, src: &'a Buffer, layout: DataLayout, dst: TextureRegion<'a>) {
309        if self.outside("copy inside a render pass").is_none() {
310            return;
311        }
312        let c = copy_region(&dst, &layout, src.size());
313        let ok = c.is_ok() && dst.texture.usage().contains(TextureUsage::COPY_DST);
314        if self.ok(ok, "copy_buffer_to_texture: region, data layout or COPY_DST usage").is_none() {
315            return;
316        }
317        let Ok((r, _)) = c else { return };
318        // SAFETY: recording; region checked against texture and buffer.
319        unsafe {
320            (self.sh.f.cmd_copy_buffer_to_image)(self.cb, src.handle(), dst.texture.image(),
321                vk::IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &r)
322        };
323    }
324
325    /// a texture region -> buffer data (the region in Layout::CopySrc)
326    pub fn copy_texture_to_buffer(&mut self, src: TextureRegion<'a>, dst: &'a Buffer, layout: DataLayout) {
327        if self.outside("copy inside a render pass").is_none() {
328            return;
329        }
330        let c = copy_region(&src, &layout, dst.size());
331        let ok = c.is_ok() && src.texture.usage().contains(TextureUsage::COPY_SRC);
332        if self.ok(ok, "copy_texture_to_buffer: region, data layout or COPY_SRC usage").is_none() {
333            return;
334        }
335        let Ok((r, _)) = c else { return };
336        // SAFETY: as above.
337        unsafe {
338            (self.sh.f.cmd_copy_image_to_buffer)(self.cb, src.texture.image(), vk::IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
339                dst.handle(), 1, &r)
340        };
341    }
342
343    // ------------------------------------------------------------ barriers
344
345    /// the accesses `before` finish (and their writes become visible) before the `after` ones
346    pub fn barrier(&mut self, before: Access, after: Access) {
347        if self.outside("barrier inside a render pass").is_none() {
348            return;
349        }
350        let (ss, sa, _) = access_of(before);
351        let (ds, _, da) = access_of(after);
352        let ((ss, sa), (ds, da)) = (self.fit(ss, sa), self.fit(ds, da));
353        let mb = vk::MemoryBarrier { s_type: vk::STRUCTURE_TYPE_MEMORY_BARRIER, src_access_mask: sa, dst_access_mask: da,
354                                     ..vk::Zero::zero() };
355        let ss = if ss == 0 { vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT } else { ss };
356        let ds = if ds == 0 { vk::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT } else { ds };
357        // SAFETY: recording outside a pass.
358        unsafe { (self.sh.f.cmd_pipeline_barrier)(self.cb, ss, ds, 0, 1, &mb, 0, core::ptr::null(), 0, core::ptr::null()) };
359    }
360
361    /// every mip and layer of tex from `before` to `after`
362    pub fn texture_barrier(&mut self, tex: &'a Texture, before: Layout, after: Layout) {
363        self.texture_barrier_range(tex, 0, tex.mips(), 0, tex.layers(), before, after);
364    }
365
366    /// mips base_mip .. +mips and layers base_layer .. +layers of tex from `before` to `after`
367    #[allow(clippy::too_many_arguments)]
368    pub fn texture_barrier_range(&mut self, tex: &'a Texture, base_mip: u32, mips: u32, base_layer: u32, layers: u32,
369                                 before: Layout, after: Layout) {
370        if self.outside("texture_barrier inside a render pass").is_none()
371            || self.ok(mips > 0 && layers > 0 && base_mip.checked_add(mips).is_some_and(|e| e <= tex.mips())
372                           && base_layer.checked_add(layers).is_some_and(|e| e <= tex.layers()),
373                       "texture_barrier: range outside the texture").is_none()
374            || self.ok(after != Layout::Undefined, "texture_barrier: Undefined is no destination").is_none()
375        {
376            return;
377        }
378        let range = subresources(tex, base_mip, mips, base_layer, layers);
379        let (mut b, ss, ds) = image_barrier_info(tex.image(), range, before, after);
380        let ((ss, sa), (ds, da)) = (self.fit(ss, b.src_access_mask), self.fit(ds, b.dst_access_mask));
381        b.src_access_mask = sa;
382        b.dst_access_mask = da;
383        let ss = if ss == 0 { vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT } else { ss };
384        let ds = if ds == 0 { vk::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT } else { ds };
385        // SAFETY: recording outside a pass.
386        unsafe { (self.sh.f.cmd_pipeline_barrier)(self.cb, ss, ds, 0, 0, core::ptr::null(), 0, core::ptr::null(), 1, &b) };
387    }
388
389    // ------------------------------------------------------------ compute
390
391    pub fn set_compute_pipeline(&mut self, p: &'a ComputePipeline) {
392        if self.outside("set_compute_pipeline inside a render pass").is_none() {
393            return;
394        }
395        self.compute_pipe = Some(&p.0);
396        // SAFETY: recording; the pipeline belongs to this device.
397        unsafe { (self.sh.f.cmd_bind_pipeline)(self.cb, vk::PIPELINE_BIND_POINT_COMPUTE, p.0.h) };
398    }
399
400    /// the pipeline bind groups and push constants go to: the render pipeline inside a pass,
401    /// else the compute pipeline
402    fn current(&mut self) -> Option<(&'a PipeInner, u32)> {
403        let (p, bp) = if self.pass.is_some() {
404            (self.graphics, vk::PIPELINE_BIND_POINT_GRAPHICS)
405        } else {
406            (self.compute_pipe, vk::PIPELINE_BIND_POINT_COMPUTE)
407        };
408        self.ok(p.is_some(), "bind group / push constants before a pipeline")?;
409        p.map(|p| (p, bp))
410    }
411
412    /// bind group g (= @group(g)) of the current pipeline's layout
413    pub fn set_bind_group(&mut self, index: u32, group: &'a BindGroup) {
414        let Some((p, bp)) = self.current() else { return };
415        let sets = &p.layout.0.sets;
416        let fits = sets.get(index as usize).is_some_and(|&l| l == group.0.layout);
417        if self.ok(fits, "set_bind_group: the group's layout differs from the pipeline layout's").is_none() {
418            return;
419        }
420        // SAFETY: recording; set and layout are compatible (checked).
421        unsafe {
422            (self.sh.f.cmd_bind_descriptor_sets)(self.cb, bp, p.layout.0.h, index, 1, &group.0.set, 0, core::ptr::null())
423        };
424    }
425
426    /// push constants at offset (bytes) for the current pipeline
427    pub fn push_constants<T: Pod>(&mut self, offset: u32, data: &[T]) {
428        let Some((p, _)) = self.current() else { return };
429        let bytes = bytes_of(data);
430        let n = bytes.len() as u32;
431        let fits = offset % 4 == 0 && n % 4 == 0 && n > 0 && offset.checked_add(n).is_some_and(|e| e <= p.layout.0.push);
432        if self.ok(fits, "push_constants: range outside the layout's (multiples of 4)").is_none() {
433            return;
434        }
435        // SAFETY: recording; the range lies within the layout's push-constant range.
436        unsafe {
437            (self.sh.f.cmd_push_constants)(self.cb, p.layout.0.h, vk::SHADER_STAGE_ALL, offset, n,
438                bytes.as_ptr() as *const core::ffi::c_void)
439        };
440    }
441
442    pub fn dispatch(&mut self, x: u32, y: u32, z: u32) {
443        let m = self.sh.limits.max_compute_workgroups;
444        let ok = self.pass.is_none() && self.compute_pipe.is_some() && x <= m[0] && y <= m[1] && z <= m[2];
445        if self.ok(ok, "dispatch: no compute pipeline, inside a pass or too many workgroups").is_none() {
446            return;
447        }
448        // SAFETY: recording with a compute pipeline bound.
449        unsafe { (self.sh.f.cmd_dispatch)(self.cb, x, y, z) };
450    }
451
452    /// workgroup counts (3 x u32) from buf at offset
453    pub fn dispatch_indirect(&mut self, buf: &'a Buffer, offset: u64) {
454        let ok = self.pass.is_none() && self.compute_pipe.is_some() && buf.usage().contains(BufferUsage::INDIRECT) && offset % 4 == 0
455            && offset.checked_add(12).is_some_and(|e| e <= buf.size());
456        if self.ok(ok, "dispatch_indirect: pipeline, INDIRECT usage, offset or range").is_none() {
457            return;
458        }
459        // SAFETY: as above; range checked.
460        unsafe { (self.sh.f.cmd_dispatch_indirect)(self.cb, buf.handle(), offset) };
461    }
462
463    // ------------------------------------------------------------ render passes
464
465    pub fn begin_render(&mut self, desc: &RenderPassDesc<'_, 'a>) {
466        if self.outside("begin_render inside a render pass").is_none()
467            || self.ok(!self.compute, "begin_render: a render pass on the compute queue").is_none()
468        {
469            return;
470        }
471        let n = desc.color.len();
472        if self.ok(n <= self.sh.limits.max_color_targets as usize && (n > 0 || desc.depth.is_some()),
473                   "begin_render: no attachments or too many").is_none()
474        {
475            return;
476        }
477        let first = desc.color.first().map(|c| c.view).or(desc.depth.map(|d| d.view));
478        let Some(first) = first else { return };
479        let (w, h) = first.size();
480        let single = |v: &TextureView| v.0.mips == 1 && v.0.layers == 1 && v.size() == (w, h);
481        let colors_ok = desc.color.iter().all(|c| {
482            single(c.view) && c.view.usage().contains(TextureUsage::COLOR_TARGET) && c.after != Layout::Undefined
483        });
484        let depth_ok = desc.depth.is_none_or(|d| {
485            single(d.view) && d.view.usage().contains(TextureUsage::DEPTH_TARGET) && d.after != Layout::Undefined
486        });
487        if self.ok(colors_ok && depth_ok, "begin_render: attachments (one mip and layer, equal sizes, usage)").is_none() {
488            return;
489        }
490        let mut barriers: Vec<vk::ImageMemoryBarrier> = Vec::with_capacity(n + 1);
491        let (mut ss, mut ds) = (0, 0);
492        let mut end = Vec::new();
493        let mut atts: Vec<vk::RenderingAttachmentInfo> = Vec::with_capacity(n);
494        let mut colors = [0u32; COLOR_TARGETS_MAX];
495        let load = |l: Load| match l {
496            Load::Keep => vk::ATTACHMENT_LOAD_OP_LOAD,
497            Load::Clear => vk::ATTACHMENT_LOAD_OP_CLEAR,
498            Load::Discard => vk::ATTACHMENT_LOAD_OP_DONT_CARE,
499        };
500        let store = |s: bool| if s { vk::ATTACHMENT_STORE_OP_STORE } else { vk::ATTACHMENT_STORE_OP_DONT_CARE };
501        for (i, c) in desc.color.iter().enumerate() {
502            let v = &c.view.0;
503            let range = vk::ImageSubresourceRange { aspect_mask: v.tex.aspect_all, base_mip_level: v.base_mip, level_count: 1,
504                                                    base_array_layer: v.base_layer, layer_count: 1 };
505            let (b, s, d) = image_barrier_info(v.tex.image, range, c.before, Layout::ColorTarget);
506            barriers.push(b);
507            ss |= s;
508            ds |= d;
509            if c.after != Layout::ColorTarget {
510                end.push(EndBarrier { image: v.tex.image, range, from: Layout::ColorTarget, to: c.after });
511            }
512            colors[i] = crate::vk_res::vk_format(c.view.format());
513            atts.push(vk::RenderingAttachmentInfo {
514                s_type: vk::STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
515                image_view: v.h,
516                image_layout: vk::IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
517                load_op: load(c.load),
518                store_op: store(c.store),
519                clear_value: c.clear.map(f32::to_bits),
520                ..vk::Zero::zero()
521            });
522        }
523        let mut datt: vk::RenderingAttachmentInfo = vk::Zero::zero();
524        let mut depth = vk::FORMAT_UNDEFINED;
525        if let Some(d) = desc.depth {
526            let v = &d.view.0;
527            let range = vk::ImageSubresourceRange { aspect_mask: v.tex.aspect_all, base_mip_level: v.base_mip, level_count: 1,
528                                                    base_array_layer: v.base_layer, layer_count: 1 };
529            let (b, s, dd) = image_barrier_info(v.tex.image, range, d.before, Layout::DepthTarget);
530            barriers.push(b);
531            ss |= s;
532            ds |= dd;
533            if d.after != Layout::DepthTarget {
534                end.push(EndBarrier { image: v.tex.image, range, from: Layout::DepthTarget, to: d.after });
535            }
536            depth = crate::vk_res::vk_format(d.view.format());
537            datt = vk::RenderingAttachmentInfo {
538                s_type: vk::STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
539                image_view: v.h,
540                image_layout: vk::IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
541                load_op: load(d.load),
542                store_op: store(d.store),
543                clear_value: [d.clear.to_bits(), 0, 0, 0],
544                ..vk::Zero::zero()
545            };
546        }
547        let has_stencil = desc.depth.is_some_and(|d| d.view.format().has_stencil());
548        let ri = vk::RenderingInfo {
549            s_type: vk::STRUCTURE_TYPE_RENDERING_INFO,
550            render_area: vk::Rect2D { offset: vk::Offset2D { x: 0, y: 0 }, extent: vk::Extent2D { width: w, height: h } },
551            layer_count: 1,
552            color_attachment_count: n as u32,
553            p_color_attachments: atts.as_ptr(),
554            p_depth_attachment: if desc.depth.is_some() { &datt } else { core::ptr::null() },
555            p_stencil_attachment: if has_stencil { &datt } else { core::ptr::null() },
556            ..vk::Zero::zero()
557        };
558        let vp = vk::Viewport { x: 0.0, y: h as f32, width: w as f32, height: -(h as f32), min_depth: 0.0, max_depth: 1.0 };
559        let sc = vk::Rect2D { offset: vk::Offset2D { x: 0, y: 0 }, extent: vk::Extent2D { width: w, height: h } };
560        // SAFETY: recording outside a pass; the attachments were checked; the structures live
561        // until the calls return.
562        unsafe {
563            (self.sh.f.cmd_pipeline_barrier)(self.cb, ss, ds, 0, 0, core::ptr::null(), 0, core::ptr::null(),
564                barriers.len() as u32, barriers.as_ptr());
565            (self.sh.f.cmd_begin_rendering)(self.cb, &ri);
566            (self.sh.f.cmd_set_viewport)(self.cb, 0, 1, &vp);
567            (self.sh.f.cmd_set_scissor)(self.cb, 0, 1, &sc);
568        }
569        let mut clears: Vec<vk::ClearAttachment> = desc.color.iter().enumerate().filter(|(_, c)| c.load == Load::Clear)
570            .map(|(i, c)| vk::ClearAttachment { aspect_mask: vk::IMAGE_ASPECT_COLOR_BIT, color_attachment: i as u32, clear_value: c.clear.map(f32::to_bits) })
571            .collect();
572        if let Some(d) = desc.depth.filter(|d| d.load == Load::Clear) {
573            let aspect = vk::IMAGE_ASPECT_DEPTH_BIT | if has_stencil { vk::IMAGE_ASPECT_STENCIL_BIT } else { 0 };
574            clears.push(vk::ClearAttachment { aspect_mask: aspect, color_attachment: 0, clear_value: [d.clear.to_bits(), 0, 0, 0] });
575        }
576        self.pass = Some(Pass { colors, n, depth, end, drew: false, clears, size: (w, h) });
577        self.graphics = None;
578        self.index = false;
579    }
580
581    pub fn end_render(&mut self) {
582        let Some(pass) = self.pass.take() else {
583            self.ok(false, "end_render without begin_render");
584            return;
585        };
586        // A pass that drew nothing clears its clearing attachments once more, as a command in the pass: on Intel's Windows
587        // driver (UHD 615, 31.0.101.2135) a pass that only cleared, after a global barrier earlier in the command buffer,
588        // was not written before a copy after the barrier at its end (the copy read the image before; render3d's empty
589        // scene, docs/GPU.md).  The barriers are Vulkan's; with a draw in the pass, or without the earlier barrier, it was.
590        if !pass.drew && !pass.clears.is_empty() {
591            let rect = vk::ClearRect { rect: vk::Rect2D { offset: vk::Offset2D { x: 0, y: 0 }, extent: vk::Extent2D { width: pass.size.0, height: pass.size.1 } },
592                                       base_array_layer: 0, layer_count: 1 };
593            // SAFETY: recording inside the pass; the attachments and their aspects are the pass's own, the rectangle its area.
594            unsafe { (self.sh.f.cmd_clear_attachments)(self.cb, pass.clears.len() as u32, pass.clears.as_ptr(), 1, &rect) };
595        }
596        // SAFETY: recording inside the pass begun by begin_render.
597        unsafe { (self.sh.f.cmd_end_rendering)(self.cb) };
598        if pass.end.is_empty() {
599            return;
600        }
601        let (mut ss, mut ds) = (0, 0);
602        let barriers: Vec<vk::ImageMemoryBarrier> = pass
603            .end
604            .iter()
605            .map(|e| {
606                let (b, s, d) = image_barrier_info(e.image, e.range, e.from, e.to);
607                ss |= s;
608                ds |= d;
609                b
610            })
611            .collect();
612        // SAFETY: recording outside a pass.
613        unsafe {
614            (self.sh.f.cmd_pipeline_barrier)(self.cb, ss, ds, 0, 0, core::ptr::null(), 0, core::ptr::null(),
615                barriers.len() as u32, barriers.as_ptr())
616        };
617    }
618
619    pub fn set_render_pipeline(&mut self, p: &'a RenderPipeline) {
620        let fits = self.pass.as_ref().is_some_and(|pass| {
621            pass.n == p.0.ncolor && pass.colors[..pass.n] == p.0.colors[..pass.n] && pass.depth == p.0.depth
622        });
623        if self.ok(fits, "set_render_pipeline: outside a pass or target formats differ").is_none() {
624            return;
625        }
626        self.graphics = Some(&p.0);
627        // SAFETY: recording inside a pass.
628        unsafe { (self.sh.f.cmd_bind_pipeline)(self.cb, vk::PIPELINE_BIND_POINT_GRAPHICS, p.0.h) };
629    }
630
631    /// the viewport in pixels from the top left (depth range min ..= max)
632    pub fn set_viewport(&mut self, x: f32, y: f32, w: f32, h: f32, min_depth: f32, max_depth: f32) {
633        if self.ok(self.pass.is_some() && w > 0.0 && h > 0.0, "set_viewport: outside a pass or empty").is_none() {
634            return;
635        }
636        let vp = vk::Viewport { x, y: y + h, width: w, height: -h, min_depth, max_depth };
637        // SAFETY: recording inside a pass.
638        unsafe { (self.sh.f.cmd_set_viewport)(self.cb, 0, 1, &vp) };
639    }
640
641    pub fn set_scissor(&mut self, x: u32, y: u32, w: u32, h: u32) {
642        if self.ok(self.pass.is_some(), "set_scissor outside a pass").is_none() {
643            return;
644        }
645        let r = vk::Rect2D { offset: vk::Offset2D { x: x as i32, y: y as i32 }, extent: vk::Extent2D { width: w, height: h } };
646        // SAFETY: recording inside a pass.
647        unsafe { (self.sh.f.cmd_set_scissor)(self.cb, 0, 1, &r) };
648    }
649
650    pub fn set_vertex_buffer(&mut self, slot: u32, buf: &'a Buffer, offset: u64) {
651        let ok = self.pass.is_some() && buf.usage().contains(BufferUsage::VERTEX) && offset < buf.size()
652            && slot < self.sh.limits.max_vertex_buffers;
653        if self.ok(ok, "set_vertex_buffer: outside a pass, VERTEX usage or offset").is_none() {
654            return;
655        }
656        // SAFETY: recording inside a pass.
657        unsafe { (self.sh.f.cmd_bind_vertex_buffers)(self.cb, slot, 1, &buf.handle(), &offset) };
658    }
659
660    pub fn set_index_buffer(&mut self, buf: &'a Buffer, offset: u64, format: IndexFormat) {
661        let size = if format == IndexFormat::U16 { 2 } else { 4 };
662        let ok = self.pass.is_some() && buf.usage().contains(BufferUsage::INDEX) && offset % size == 0 && offset < buf.size();
663        if self.ok(ok, "set_index_buffer: outside a pass, INDEX usage or offset").is_none() {
664            return;
665        }
666        let t = if format == IndexFormat::U16 { vk::INDEX_TYPE_UINT16 } else { vk::INDEX_TYPE_UINT32 };
667        // SAFETY: recording inside a pass.
668        unsafe { (self.sh.f.cmd_bind_index_buffer)(self.cb, buf.handle(), offset, t) };
669        self.index = true;
670    }
671
672    #[inline]
673    fn can_draw(&mut self, indexed: bool) -> Option<()> {
674        let ok = self.pass.is_some() && self.graphics.is_some() && (!indexed || self.index);
675        if let (true, Some(p)) = (ok, self.pass.as_mut()) {
676            p.drew = true;
677        }
678        self.ok(ok, "draw: outside a pass, without a render pipeline or index buffer")
679    }
680
681    pub fn draw(&mut self, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) {
682        if self.can_draw(false).is_some() {
683            // SAFETY: recording with a render pipeline inside a pass.
684            unsafe { (self.sh.f.cmd_draw)(self.cb, vertices, instances, first_vertex, first_instance) };
685        }
686    }
687
688    pub fn draw_indexed(&mut self, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) {
689        if self.can_draw(true).is_some() {
690            // SAFETY: as above, with an index buffer.
691            unsafe { (self.sh.f.cmd_draw_indexed)(self.cb, indices, instances, first_index, base_vertex, first_instance) };
692        }
693    }
694
695    fn indirect_ok(&mut self, buf: &Buffer, offset: u64, bytes: u64) -> Option<()> {
696        let ok = buf.usage().contains(BufferUsage::INDIRECT) && offset % 4 == 0 && offset.checked_add(bytes).is_some_and(|e| e <= buf.size());
697        self.ok(ok, "indirect: INDIRECT usage, offset (multiple of 4) or range")
698    }
699
700    /// one draw: vertex count, instance count, first vertex, first instance (4 x u32)
701    pub fn draw_indirect(&mut self, buf: &'a Buffer, offset: u64) {
702        if self.can_draw(false).is_some() && self.indirect_ok(buf, offset, 16).is_some() {
703            // SAFETY: recording; range checked.
704            unsafe { (self.sh.f.cmd_draw_indirect)(self.cb, buf.handle(), offset, 1, 16) };
705        }
706    }
707
708    /// one indexed draw: index count, instance count, first index, base vertex (i32), first
709    /// instance (5 x 32 bits)
710    pub fn draw_indexed_indirect(&mut self, buf: &'a Buffer, offset: u64) {
711        if self.can_draw(true).is_some() && self.indirect_ok(buf, offset, 20).is_some() {
712            // SAFETY: recording; range checked.
713            unsafe { (self.sh.f.cmd_draw_indexed_indirect)(self.cb, buf.handle(), offset, 1, 20) };
714        }
715    }
716
717    /// count indexed draws, stride bytes apart (Features::multi_draw_indirect)
718    pub fn draw_indexed_indirect_multi(&mut self, buf: &'a Buffer, offset: u64, count: u32, stride: u32) {
719        let ok = self.sh.features.multi_draw_indirect && stride >= 20 && stride % 4 == 0 && count > 0
720            && count <= self.sh.limits.max_draw_indirect_count;
721        if self.ok(ok, "draw_indexed_indirect_multi: needs multi_draw_indirect, stride >= 20").is_none()
722            || self.can_draw(true).is_none()
723            || self.indirect_ok(buf, offset, (count as u64 - 1) * stride as u64 + 20).is_none()
724        {
725            return;
726        }
727        // SAFETY: recording; range checked.
728        unsafe { (self.sh.f.cmd_draw_indexed_indirect)(self.cb, buf.handle(), offset, count, stride) };
729    }
730
731    /// up to max_count indexed draws, their number (u32) read from count_buf at count_offset
732    /// (level Voll: Features::draw_indirect_count)
733    pub fn draw_indexed_indirect_count(&mut self, buf: &'a Buffer, offset: u64, count_buf: &'a Buffer, count_offset: u64,
734                                       max_count: u32, stride: u32) {
735        let f = self.sh.f.cmd_draw_indexed_indirect_count;
736        let ok = self.sh.features.draw_indirect_count && f.is_some() && stride >= 20 && stride % 4 == 0 && max_count > 0;
737        if self.ok(ok, "draw_indexed_indirect_count: needs level Voll, stride >= 20").is_none()
738            || self.can_draw(true).is_none()
739            || self.indirect_ok(buf, offset, (max_count as u64 - 1) * stride as u64 + 20).is_none()
740            || self.indirect_ok(count_buf, count_offset, 4).is_none()
741        {
742            return;
743        }
744        let Some(f) = f else { return };
745        // SAFETY: recording; ranges checked; the feature is enabled.
746        unsafe { f(self.cb, buf.handle(), offset, count_buf.handle(), count_offset, max_count, stride) };
747    }
748
749    // ------------------------------------------------------------ timestamps
750
751    /// timestamps first .. first + n may be written again (outside render passes)
752    pub fn reset_timestamps(&mut self, ts: &'a Timestamps, first: u32, n: u32) {
753        let ok = self.pass.is_none() && n > 0 && first.checked_add(n).is_some_and(|e| e <= ts.0.count) && self.timestamps_here();
754        if self.ok(ok, "reset_timestamps: inside a pass or range").is_none() {
755            return;
756        }
757        // SAFETY: recording outside a pass; range checked.
758        unsafe { (self.sh.f.cmd_reset_query_pool)(self.cb, ts.0.pool, first, n) };
759    }
760
761    /// write timestamp i once every earlier command has finished (reset it first)
762    pub fn timestamp(&mut self, ts: &'a Timestamps, i: u32) {
763        if self.ok(i < ts.0.count && self.timestamps_here(), "timestamp: index outside the set, or no timestamps on this queue").is_none() {
764            return;
765        }
766        // SAFETY: recording; index checked.
767        unsafe { (self.sh.f.cmd_write_timestamp)(self.cb, vk::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, ts.0.pool, i) };
768    }
769
770    /// (G5d) this encoder's queue writes timestamps (the compute queue's family may have none)
771    fn timestamps_here(&self) -> bool {
772        !self.compute || self.sh.lane.as_ref().is_some_and(|l| l.ts_bits > 0)
773    }
774
775    // ------------------------------------------------------------ end
776
777    /// the recorded commands, or the first misuse
778    pub fn finish(mut self) -> Result<CommandBuffer<'a>> {
779        if self.pass.is_some() {
780            self.ok(false, "finish inside a render pass");
781        }
782        if let Some(e) = self.err {
783            return Err(e); // Drop gives the slot back
784        }
785        let slot = self.slot.take().unwrap_or_else(|| unreachable!());
786        // SAFETY: the buffer is recording.
787        let r = unsafe { (self.sh.f.end_command_buffer)(slot.cb) };
788        if let Err(e) = self.sh.vk(r) {
789            self.sh.give_slot(slot);
790            return Err(e);
791        }
792        Ok(CommandBuffer { sh: self.sh, slot: Some(slot) })
793    }
794}