Skip to main content

wgpu_core/command/
render.rs

1use alloc::{borrow::Cow, boxed::Box, sync::Arc, vec::Vec};
2use core::{convert::Infallible, fmt, num::NonZeroU32, ops::Range, str};
3use smallvec::SmallVec;
4
5use arrayvec::ArrayVec;
6use thiserror::Error;
7use wgt::{
8    error::{ErrorType, WebGpuError},
9    BufferAddress, BufferUsages, Color, DynamicOffset, IndexFormat, InstanceFlags, TextureSelector,
10    TextureUsages, TextureViewDimension, VertexStepMode,
11};
12
13use crate::{
14    api_log,
15    binding_model::{BindError, BindGroup, ImmediateUploadError},
16    command::{
17        bind::Binder,
18        draw::validate_mesh_draw_multiview,
19        memory_init::{fixup_discarded_surfaces, SurfacesInDiscardState, TextureSurfaceDiscard},
20        pass::{self, flush_bindings_helper, ImmediateState},
21        pass_base, pass_try,
22        query::{
23            end_occlusion_query, end_pipeline_statistics_query, record_pass_timestamp_writes,
24            validate_and_begin_occlusion_query, validate_and_begin_pipeline_statistics_query,
25            QueryResetMap, QuerySetWrites,
26        },
27        render_command::ArcRenderCommand,
28        ArcCommand, BasePass, BindGroupStateChange, CommandBufferTextureMemoryActions,
29        CommandEncoder, CommandEncoderError, DebugGroupError, DrawCommandFamily, DrawError,
30        DrawKind, EncoderStateError, EncodingState, ExecutionError, InnerCommandEncoder,
31        MapPassErr, PassErrorScope, PassStateError, PassTimestampWrites, QueryUseError, Rect,
32        RenderBundle, RenderCommandError, StateChange, TimestampWritesError,
33    },
34    device::{
35        AttachmentData, Device, DeviceError, MissingDownlevelFlags, MissingFeatures,
36        RenderPassCompatibilityError, RenderPassContext,
37    },
38    hal_label, id, impl_resource_type,
39    init_tracker::{MemoryInitKind, TextureInitRange, TextureInitTrackerAction},
40    pipeline::{PipelineFlags, RenderPipeline, VertexStep},
41    resource::{
42        Buffer, DestroyedResourceError, InvalidOrDestroyedResourceError, InvalidResourceError,
43        Labeled, MissingBufferUsageError, MissingTextureUsageError, ParentDevice, QuerySet,
44        RawResourceAccess, ResourceErrorIdent, Texture, TextureView,
45        TextureViewNotRenderableReason,
46    },
47    snatch::SnatchGuard,
48    track::{ResourceUsageCompatibilityError, Tracker, UsageScope},
49    validation::{self, WorkgroupSizeCheck},
50    Label,
51};
52
53#[cfg(feature = "serde")]
54use serde::Deserialize;
55#[cfg(feature = "serde")]
56use serde::Serialize;
57
58pub use wgt::{LoadOp, StoreOp};
59
60fn load_hal_ops<V>(load: LoadOp<V>) -> hal::AttachmentOps {
61    match load {
62        LoadOp::Load => hal::AttachmentOps::LOAD,
63        LoadOp::Clear(_) => hal::AttachmentOps::LOAD_CLEAR,
64        LoadOp::DontCare(_) => hal::AttachmentOps::LOAD_DONT_CARE,
65    }
66}
67
68fn store_hal_ops(store: StoreOp) -> hal::AttachmentOps {
69    match store {
70        StoreOp::Store => hal::AttachmentOps::STORE,
71        StoreOp::Discard => hal::AttachmentOps::STORE_DISCARD,
72    }
73}
74
75// Stencil clear and reference value should take the LSBs.
76fn convert_stencil_value(value: u32, format: Option<wgt::TextureFormat>) -> u32 {
77    let Some(format) = format else {
78        return value;
79    };
80    let Some(stencil_format) = format.aspect_specific_format(wgt::TextureAspect::StencilOnly)
81    else {
82        return value;
83    };
84    // Currently only 8-bit stencil formats are supported
85    assert_eq!(stencil_format, wgt::TextureFormat::Stencil8);
86    value & 255
87}
88
89/// Describes an individual channel within a render pass, such as color, depth, or stencil.
90///
91/// A channel must either be read-only, or it must specify both load and store
92/// operations. See [`ResolvedPassChannel`] for a validated version.
93#[repr(C)]
94#[derive(Clone, Debug, Eq, PartialEq)]
95#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
96pub struct PassChannel<V> {
97    /// Operation to perform to the output attachment at the start of a
98    /// renderpass.
99    ///
100    /// This must be clear if it is the first renderpass rendering to a swap
101    /// chain image.
102    pub load_op: Option<LoadOp<V>>,
103    /// Operation to perform to the output attachment at the end of a renderpass.
104    pub store_op: Option<StoreOp>,
105    /// If true, the relevant channel is not changed by a renderpass, and the
106    /// corresponding attachment can be used inside the pass by other read-only
107    /// usages.
108    pub read_only: bool,
109}
110
111impl<V: Copy + Default> PassChannel<Option<V>> {
112    fn resolve(
113        &self,
114        instance_flags: InstanceFlags,
115        handle_clear: impl Fn(Option<V>) -> Result<V, AttachmentError>,
116    ) -> Result<ResolvedPassChannel<V>, AttachmentError> {
117        if self.read_only {
118            if self.load_op.is_some() {
119                return Err(AttachmentError::ReadOnlyWithLoad);
120            }
121            if self.store_op.is_some() {
122                return Err(AttachmentError::ReadOnlyWithStore);
123            }
124            Ok(ResolvedPassChannel::ReadOnly)
125        } else {
126            Ok(ResolvedPassChannel::Operational(wgt::Operations {
127                load: match self.load_op.ok_or(AttachmentError::NoLoad)? {
128                    LoadOp::Clear(clear_value) => LoadOp::Clear(handle_clear(clear_value)?),
129                    LoadOp::DontCare(token) => {
130                        if instance_flags.contains(InstanceFlags::STRICT_WEBGPU_COMPLIANCE) {
131                            return Err(AttachmentError::LoadOpDontCareUnderStrictWebgpuCompliance);
132                        }
133                        LoadOp::DontCare(token)
134                    }
135                    LoadOp::Load => LoadOp::Load,
136                },
137                store: self.store_op.ok_or(AttachmentError::NoStore)?,
138            }))
139        }
140    }
141}
142
143/// Describes an individual channel within a render pass, such as color, depth, or stencil.
144///
145/// Unlike [`PassChannel`], this version uses the Rust type system to guarantee
146/// a valid specification.
147#[derive(Clone, Debug)]
148#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
149pub enum ResolvedPassChannel<V> {
150    ReadOnly,
151    Operational(wgt::Operations<V>),
152}
153
154impl<V: Copy + Default> ResolvedPassChannel<V> {
155    fn load_op(&self) -> LoadOp<V> {
156        match self {
157            ResolvedPassChannel::ReadOnly => LoadOp::Load,
158            ResolvedPassChannel::Operational(wgt::Operations { load, .. }) => *load,
159        }
160    }
161
162    fn store_op(&self) -> StoreOp {
163        match self {
164            ResolvedPassChannel::ReadOnly => StoreOp::Store,
165            ResolvedPassChannel::Operational(wgt::Operations { store, .. }) => *store,
166        }
167    }
168
169    fn clear_value(&self) -> V {
170        match self {
171            Self::Operational(wgt::Operations {
172                load: LoadOp::Clear(clear_value),
173                ..
174            }) => *clear_value,
175            _ => Default::default(),
176        }
177    }
178
179    fn is_readonly(&self) -> bool {
180        matches!(self, Self::ReadOnly)
181    }
182
183    fn hal_ops(&self) -> hal::AttachmentOps {
184        load_hal_ops(self.load_op()) | store_hal_ops(self.store_op())
185    }
186}
187
188/// Describes a color attachment to a render pass.
189#[repr(C)]
190#[derive(Clone, Debug, PartialEq)]
191#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
192pub struct RenderPassColorAttachment<TV = Arc<TextureView>> {
193    /// The view to use as an attachment.
194    pub view: TV,
195    /// The depth slice index of a 3D view. It must not be provided if the view is not 3D.
196    pub depth_slice: Option<u32>,
197    /// The view that will receive the resolved output if multisampling is used.
198    pub resolve_target: Option<TV>,
199    /// Operation to perform to the output attachment at the start of a
200    /// renderpass.
201    ///
202    /// This must be clear if it is the first renderpass rendering to a swap
203    /// chain image.
204    pub load_op: LoadOp<Color>,
205    /// Operation to perform to the output attachment at the end of a renderpass.
206    pub store_op: StoreOp,
207}
208
209// Avoid allocation in the common case that there is only one color attachment,
210// but don't bloat `ArcCommand::RunRenderPass` excessively.
211pub type ColorAttachments<TV = Arc<TextureView>> =
212    SmallVec<[Option<RenderPassColorAttachment<TV>>; 1]>;
213
214impl RenderPassColorAttachment {
215    fn hal_ops(&self) -> hal::AttachmentOps {
216        load_hal_ops(self.load_op) | store_hal_ops(self.store_op)
217    }
218
219    fn clear_value(&self) -> Color {
220        match self.load_op {
221            LoadOp::Clear(clear_value) => clear_value,
222            LoadOp::DontCare(_) | LoadOp::Load => Color::default(),
223        }
224    }
225}
226
227/// Describes a depth/stencil attachment to a render pass.
228///
229/// This version uses the unvalidated [`PassChannel`].
230#[repr(C)]
231#[derive(Clone, Debug, PartialEq)]
232#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
233pub struct RenderPassDepthStencilAttachment<TV> {
234    /// The view to use as an attachment.
235    pub view: TV,
236    /// What operations will be performed on the depth part of the attachment.
237    pub depth: PassChannel<Option<f32>>,
238    /// What operations will be performed on the stencil part of the attachment.
239    pub stencil: PassChannel<Option<u32>>,
240}
241
242/// Describes a depth/stencil attachment to a render pass.
243///
244/// This version uses the validated [`ResolvedPassChannel`].
245#[derive(Clone, Debug)]
246#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
247pub struct ResolvedRenderPassDepthStencilAttachment<TV> {
248    /// The view to use as an attachment.
249    pub view: TV,
250    /// What operations will be performed on the depth part of the attachment.
251    pub depth: ResolvedPassChannel<f32>,
252    /// What operations will be performed on the stencil part of the attachment.
253    pub stencil: ResolvedPassChannel<u32>,
254}
255
256/// Describes the attachments of a render pass.
257#[derive(Clone, Default)]
258pub struct ResolvedRenderPassDescriptor<'a> {
259    pub label: Label<'a>,
260    /// The color attachments of the render pass.
261    pub color_attachments: Cow<'a, [Option<RenderPassColorAttachment<Arc<TextureView>>>]>,
262    /// The depth and stencil attachment of the render pass, if any.
263    pub depth_stencil_attachment: Option<RenderPassDepthStencilAttachment<Arc<TextureView>>>,
264    /// Defines where and when timestamp values will be written for this pass.
265    pub timestamp_writes: Option<PassTimestampWrites<Arc<QuerySet>>>,
266    /// Defines where the occlusion query results will be stored for this pass.
267    pub occlusion_query_set: Option<Arc<QuerySet>>,
268    /// The multiview array layers that will be used
269    pub multiview_mask: Option<NonZeroU32>,
270}
271
272/// Describes the attachments of a render pass.
273struct ArcRenderPassDescriptor<'a> {
274    pub label: &'a Label<'a>,
275    /// The color attachments of the render pass.
276    pub color_attachments:
277        ArrayVec<Option<RenderPassColorAttachment>, { hal::MAX_COLOR_ATTACHMENTS }>,
278    /// The depth and stencil attachment of the render pass, if any.
279    pub depth_stencil_attachment:
280        Option<ResolvedRenderPassDepthStencilAttachment<Arc<TextureView>>>,
281    /// Defines where and when timestamp values will be written for this pass.
282    pub timestamp_writes: Option<PassTimestampWrites>,
283    /// Defines where the occlusion query results will be stored for this pass.
284    pub occlusion_query_set: Option<Arc<QuerySet>>,
285    /// The multiview array layers that will be used
286    pub multiview_mask: Option<NonZeroU32>,
287}
288
289pub type RenderBasePass = BasePass<ArcRenderCommand, RenderPassError>;
290
291/// A pass's [encoder state](https://www.w3.org/TR/webgpu/#encoder-state) and
292/// its validity are two distinct conditions, i.e., the full matrix of
293/// (open, ended) x (valid, invalid) is possible.
294///
295/// The presence or absence of the `parent` `Option` indicates the pass's state.
296/// The presence or absence of an error in `base.error` indicates the pass's
297/// validity.
298pub struct RenderPass {
299    /// All pass data & records is stored here.
300    base: BasePass<ArcRenderCommand, RenderPassError>,
301
302    /// Parent command encoder that this pass records commands into.
303    ///
304    /// If this is `Some`, then the pass is in WebGPU's "open" state. If it is
305    /// `None`, then the pass is in the "ended" state.
306    /// See <https://www.w3.org/TR/webgpu/#encoder-state>
307    parent: Option<Arc<CommandEncoder>>,
308
309    device: Arc<Device>,
310
311    color_attachments: ArrayVec<Option<RenderPassColorAttachment>, { hal::MAX_COLOR_ATTACHMENTS }>,
312    depth_stencil_attachment: Option<ResolvedRenderPassDepthStencilAttachment<Arc<TextureView>>>,
313    timestamp_writes: Option<PassTimestampWrites>,
314    occlusion_query_set: Option<Arc<QuerySet>>,
315    multiview_mask: Option<NonZeroU32>,
316
317    // Resource binding dedupe state.
318    current_bind_groups: BindGroupStateChange,
319    current_pipeline: StateChange<Arc<RenderPipeline>>,
320}
321
322impl_resource_type!(RenderPass);
323
324impl crate::storage::StorageItem for RenderPass {
325    type Marker = id::markers::RenderPassEncoder;
326}
327
328impl RenderPass {
329    /// If the parent command encoder is invalid, the returned pass will be invalid.
330    fn new(parent: Arc<CommandEncoder>, desc: ArcRenderPassDescriptor) -> Self {
331        let ArcRenderPassDescriptor {
332            label,
333            timestamp_writes,
334            color_attachments,
335            depth_stencil_attachment,
336            occlusion_query_set,
337            multiview_mask,
338        } = desc;
339
340        Self {
341            base: BasePass::new(label),
342            device: parent.device().clone(),
343            parent: Some(parent),
344            color_attachments,
345            depth_stencil_attachment,
346            timestamp_writes,
347            occlusion_query_set,
348            multiview_mask,
349
350            current_bind_groups: BindGroupStateChange::new(),
351            current_pipeline: StateChange::new(),
352        }
353    }
354
355    fn new_invalid(parent: Arc<CommandEncoder>, label: &Label, err: RenderPassError) -> Self {
356        Self {
357            base: BasePass::new_invalid(label, err),
358            device: parent.device().clone(),
359            parent: Some(parent),
360            color_attachments: ArrayVec::new(),
361            depth_stencil_attachment: None,
362            timestamp_writes: None,
363            occlusion_query_set: None,
364            multiview_mask: None,
365            current_bind_groups: BindGroupStateChange::new(),
366            current_pipeline: StateChange::new(),
367        }
368    }
369
370    #[inline]
371    pub fn label(&self) -> Option<&str> {
372        self.base.label.as_deref()
373    }
374
375    pub fn device(&self) -> &Arc<Device> {
376        &self.device
377    }
378}
379
380impl fmt::Debug for RenderPass {
381    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382        f.debug_struct("RenderPass")
383            .field("label", &self.label())
384            .field("color_attachments", &self.color_attachments)
385            .field("depth_stencil_target", &self.depth_stencil_attachment)
386            .field("command count", &self.base.commands.len())
387            .field("dynamic offset count", &self.base.dynamic_offsets.len())
388            .field("multiview mask", &self.multiview_mask)
389            .finish()
390    }
391}
392
393#[derive(Debug, PartialEq)]
394enum OptionalState {
395    Unused,
396    Required,
397    Set,
398}
399
400impl OptionalState {
401    fn require(&mut self, require: bool) {
402        if require && *self == Self::Unused {
403            *self = Self::Required;
404        }
405    }
406}
407
408#[derive(Debug, Default)]
409struct IndexState {
410    buffer_format: Option<IndexFormat>,
411    limit: u64,
412}
413
414impl IndexState {
415    fn update_buffer(&mut self, range: Range<BufferAddress>, format: IndexFormat) {
416        self.buffer_format = Some(format);
417        let shift = match format {
418            IndexFormat::Uint16 => 1,
419            IndexFormat::Uint32 => 2,
420        };
421        self.limit = (range.end - range.start) >> shift;
422    }
423
424    fn reset(&mut self) {
425        self.buffer_format = None;
426        self.limit = 0;
427    }
428}
429
430#[derive(Debug, Default)]
431pub(crate) struct VertexLimits {
432    /// Length of the shortest vertex rate vertex buffer
433    pub(crate) vertex_limit: u64,
434    /// Buffer slot which the shortest vertex rate vertex buffer is bound to
435    vertex_limit_slot: u32,
436    /// Length of the shortest instance rate vertex buffer
437    pub(crate) instance_limit: u64,
438    /// Buffer slot which the shortest instance rate vertex buffer is bound to
439    instance_limit_slot: u32,
440}
441
442impl VertexLimits {
443    pub(crate) fn new(
444        buffer_sizes: impl ExactSizeIterator<Item = Option<BufferAddress>>,
445        pipeline_steps: &[Option<VertexStep>],
446    ) -> Self {
447        // Implements the validation from https://gpuweb.github.io/gpuweb/#dom-gpurendercommandsmixin-draw
448        // Except that the formula is shuffled to extract the number of vertices in order
449        // to carry the bulk of the computation when changing states instead of when producing
450        // draws. Draw calls tend to happen at a higher frequency. Here we determine vertex
451        // limits that can be cheaply checked for each draw call.
452
453        let mut vertex_limit = u64::MAX;
454        let mut vertex_limit_slot = 0;
455        let mut instance_limit = u64::MAX;
456        let mut instance_limit_slot = 0;
457
458        for (idx, (buffer_size, step)) in buffer_sizes.zip(pipeline_steps).enumerate() {
459            let Some(step) = step else {
460                continue;
461            };
462
463            let Some(buffer_size) = buffer_size else {
464                // Missing required vertex buffer
465                return Self::default();
466            };
467
468            let limit = if buffer_size < step.last_stride {
469                // The buffer cannot fit the last vertex.
470                0
471            } else {
472                if step.stride == 0 {
473                    // We already checked that the last stride fits, the same
474                    // vertex will be repeated so this slot can accommodate any number of
475                    // vertices.
476                    continue;
477                }
478
479                // The general case.
480                (buffer_size - step.last_stride) / step.stride + 1
481            };
482
483            match step.mode {
484                VertexStepMode::Vertex => {
485                    if limit < vertex_limit {
486                        vertex_limit = limit;
487                        vertex_limit_slot = idx as _;
488                    }
489                }
490                VertexStepMode::Instance => {
491                    if limit < instance_limit {
492                        instance_limit = limit;
493                        instance_limit_slot = idx as _;
494                    }
495                }
496            }
497        }
498
499        Self {
500            vertex_limit,
501            vertex_limit_slot,
502            instance_limit,
503            instance_limit_slot,
504        }
505    }
506
507    pub(crate) fn validate_vertex_limit(
508        &self,
509        first_vertex: u32,
510        vertex_count: u32,
511    ) -> Result<(), DrawError> {
512        let last_vertex = first_vertex as u64 + vertex_count as u64;
513        let vertex_limit = self.vertex_limit;
514        if last_vertex > vertex_limit {
515            return Err(DrawError::VertexBeyondLimit {
516                last_vertex,
517                vertex_limit,
518                slot: self.vertex_limit_slot,
519            });
520        }
521
522        Ok(())
523    }
524
525    pub(crate) fn validate_instance_limit(
526        &self,
527        first_instance: u32,
528        instance_count: u32,
529    ) -> Result<(), DrawError> {
530        let last_instance = first_instance as u64 + instance_count as u64;
531        let instance_limit = self.instance_limit;
532        if last_instance > instance_limit {
533            return Err(DrawError::InstanceBeyondLimit {
534                last_instance,
535                instance_limit,
536                slot: self.instance_limit_slot,
537            });
538        }
539
540        Ok(())
541    }
542}
543
544/// State of a single vertex buffer slot.
545#[derive(Debug)]
546pub(crate) struct VertexSlot {
547    pub(crate) buffer: Arc<Buffer>,
548    pub(crate) range: Range<BufferAddress>,
549    pub(crate) is_dirty: bool,
550}
551
552/// Vertex buffer tracking state, shared between render passes and render bundles.
553///
554/// Tracks which vertex buffer slots are set, and caches the vertex and instance limits
555/// derived from those buffers and the current pipeline, avoiding recomputation on each draw.
556#[derive(Debug, Default)]
557pub(crate) struct VertexState {
558    slots: [Option<VertexSlot>; hal::MAX_VERTEX_BUFFERS],
559    pub(crate) limits: VertexLimits,
560}
561
562impl VertexState {
563    /// Set a vertex buffer slot, marking it dirty.
564    pub(crate) fn set_buffer(
565        &mut self,
566        slot: usize,
567        buffer: Arc<Buffer>,
568        range: Range<BufferAddress>,
569    ) {
570        self.slots[slot] = Some(VertexSlot {
571            buffer,
572            range,
573            is_dirty: true,
574        });
575    }
576
577    /// Clear a vertex buffer slot.
578    pub(crate) fn clear_buffer(&mut self, slot: usize) {
579        self.slots[slot] = None;
580    }
581
582    /// Recompute the cached vertex and instance limits based on the current slots and pipeline.
583    pub(crate) fn update_limits(&mut self, pipeline_steps: &[Option<VertexStep>]) {
584        self.limits = VertexLimits::new(
585            self.slots
586                .iter()
587                .map(|s| s.as_ref().map(|s| s.range.end - s.range.start)),
588            pipeline_steps,
589        );
590    }
591
592    fn last_assigned_index(&self) -> Option<usize> {
593        self.slots
594            .iter()
595            .enumerate()
596            .filter_map(|(i, s)| s.as_ref().map(|_| i))
597            .next_back()
598    }
599
600    pub(super) fn validate(
601        &self,
602        pipeline: &RenderPipeline,
603        binder: &Binder,
604    ) -> Result<(), DrawError> {
605        // Check all needed vertex buffers have been bound
606        for index in pipeline
607            .vertex_steps
608            .iter()
609            .enumerate()
610            .filter_map(|(index, step)| step.map(|_| index))
611        {
612            if self.slots[index].is_none() {
613                return Err(DrawError::MissingVertexBuffer {
614                    pipeline: pipeline.error_ident(),
615                    index,
616                });
617            }
618        }
619
620        let bind_group_space_used = binder.last_assigned_index().map_or(0, |i| i + 1);
621        let vertex_buffer_space_used = self.last_assigned_index().map_or(0, |i| i + 1);
622
623        let bind_groups_plus_vertex_buffers =
624            u32::try_from(bind_group_space_used + vertex_buffer_space_used).unwrap();
625        if bind_groups_plus_vertex_buffers
626            > pipeline.device.limits.max_bind_groups_plus_vertex_buffers
627        {
628            return Err(DrawError::TooManyBindGroupsPlusVertexBuffers {
629                given: bind_groups_plus_vertex_buffers,
630                limit: pipeline.device.limits.max_bind_groups_plus_vertex_buffers,
631            });
632        }
633
634        Ok(())
635    }
636
637    /// Call `f` for each dirty slot with `(slot_index, buffer, offset, size)` and mark them clean.
638    pub(crate) fn flush<F>(&mut self, mut f: F)
639    where
640        F: FnMut(u32, &Arc<Buffer>, BufferAddress, BufferAddress),
641    {
642        for (i, slot) in self.slots.iter_mut().enumerate() {
643            let Some(slot) = slot.as_mut() else { continue };
644            if !slot.is_dirty {
645                continue;
646            }
647            slot.is_dirty = false;
648            let size = slot.range.end - slot.range.start;
649            f(i as u32, &slot.buffer, slot.range.start, size);
650        }
651    }
652}
653
654struct State<'scope, 'snatch_guard, 'cmd_enc> {
655    pipeline_flags: PipelineFlags,
656    blend_constant: OptionalState,
657    stencil_reference: u32,
658    pipeline: Option<Arc<RenderPipeline>>,
659    index: IndexState,
660    vertex: VertexState,
661
662    info: RenderPassInfo,
663
664    pass: pass::PassState<'scope, 'snatch_guard, 'cmd_enc>,
665
666    active_occlusion_query: Option<(Arc<QuerySet>, u32)>,
667    active_pipeline_statistics_query: Option<(Arc<QuerySet>, u32)>,
668}
669
670impl<'scope, 'snatch_guard, 'cmd_enc> State<'scope, 'snatch_guard, 'cmd_enc> {
671    fn is_ready(&self, family: DrawCommandFamily) -> Result<(), DrawError> {
672        if let Some(pipeline) = self.pipeline.as_ref() {
673            self.pass
674                .binder
675                .check_compatibility(pipeline.as_ref(), &pipeline.late_sized_buffer_groups)?;
676
677            if self.blend_constant == OptionalState::Required {
678                return Err(DrawError::MissingBlendConstant);
679            }
680
681            self.vertex.validate(pipeline.as_ref(), &self.pass.binder)?;
682
683            if family == DrawCommandFamily::DrawIndexed {
684                // Pipeline expects an index buffer
685                // We have a buffer bound
686                let buffer_index_format = self
687                    .index
688                    .buffer_format
689                    .ok_or(DrawError::MissingIndexBuffer)?;
690
691                if pipeline.topology.is_strip()
692                    && pipeline.strip_index_format != Some(buffer_index_format)
693                {
694                    return Err(DrawError::UnmatchedStripIndexFormat {
695                        pipeline: pipeline.error_ident(),
696                        strip_index_format: pipeline.strip_index_format,
697                        buffer_format: buffer_index_format,
698                    });
699                }
700            }
701            if (family == DrawCommandFamily::DrawMeshTasks) != pipeline.is_mesh {
702                return Err(DrawError::WrongPipelineType {
703                    wanted_mesh_pipeline: !pipeline.is_mesh,
704                });
705            }
706            if !self
707                .pass
708                .immediate_state
709                .immediate_slots_set
710                .contains(pipeline.immediate_slots_required)
711            {
712                return Err(DrawError::MissingImmediateData {
713                    missing: pipeline
714                        .immediate_slots_required
715                        .difference(self.pass.immediate_state.immediate_slots_set),
716                });
717            }
718            Ok(())
719        } else {
720            Err(DrawError::MissingPipeline(pass::MissingPipeline))
721        }
722    }
723
724    fn flush_immediates(&mut self) {
725        let pipeline = self.pipeline.as_ref().unwrap();
726        let layout = pipeline.layout().unwrap();
727        self.pass
728            .immediate_state
729            .flush_immediates(layout, self.pass.base.raw_encoder);
730    }
731
732    /// Flush binding state in preparation for a draw call.
733    ///
734    /// See the compute pass version for an explanation of some ways that
735    /// `flush_bindings` differs between the two types of passes.
736    fn flush_bindings(&mut self) -> Result<(), RenderPassErrorInner> {
737        flush_bindings_helper(&mut self.pass)?;
738        Ok(())
739    }
740
741    /// Reset the `RenderBundle`-related states.
742    fn reset_bundle(&mut self) {
743        self.pass.binder.reset();
744        self.pipeline = None;
745        self.index.reset();
746        self.vertex = Default::default();
747        self.pass.immediate_state.immediate_slots_set = Default::default();
748    }
749
750    /// Flush dirty vertex buffer slots to the HAL encoder in preparation for a draw call.
751    fn flush_vertex_buffers(&mut self) -> Result<(), RenderPassErrorInner> {
752        let vertex = &mut self.vertex;
753        let raw_encoder: &mut dyn hal::DynCommandEncoder = self.pass.base.raw_encoder;
754        let snatch_guard = self.pass.base.snatch_guard;
755        let mut result = Ok(());
756        vertex.flush(|slot, buffer, offset, size| {
757            if result.is_err() {
758                return;
759            }
760            match buffer.try_raw(snatch_guard) {
761                Ok(raw) => unsafe {
762                    // SAFETY: The offset and size were validated in set_vertex_buffer.
763                    raw_encoder.set_vertex_buffer(
764                        slot,
765                        hal::BufferBinding::new_unchecked(raw, offset, size),
766                    );
767                },
768                Err(e) => result = Err(e.into()),
769            }
770        });
771        result
772    }
773}
774
775/// Describes an attachment location in words.
776///
777/// Can be used as "the {loc} has..." or "{loc} has..."
778#[derive(Debug, Copy, Clone)]
779pub enum AttachmentErrorLocation {
780    Color { index: usize, resolve: bool },
781    Depth,
782}
783
784impl fmt::Display for AttachmentErrorLocation {
785    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
786        match *self {
787            AttachmentErrorLocation::Color {
788                index,
789                resolve: false,
790            } => write!(f, "color attachment at index {index}'s texture view"),
791            AttachmentErrorLocation::Color {
792                index,
793                resolve: true,
794            } => write!(
795                f,
796                "color attachment at index {index}'s resolve texture view"
797            ),
798            AttachmentErrorLocation::Depth => write!(f, "depth attachment's texture view"),
799        }
800    }
801}
802
803#[derive(Clone, Debug, Error)]
804#[non_exhaustive]
805pub enum ColorAttachmentError {
806    #[error("Attachment format {0:?} is not a color format")]
807    InvalidFormat(wgt::TextureFormat),
808    #[error("The number of color attachments {given} exceeds the limit {limit}")]
809    TooMany { given: usize, limit: usize },
810    #[error("The total number of bytes per sample in color attachments {total} exceeds the limit {limit}")]
811    TooManyBytesPerSample { total: u32, limit: u32 },
812    #[error("Depth slice must be less than {limit} but is {given}")]
813    DepthSliceLimit { given: u32, limit: u32 },
814    #[error("Color attachment's view is 3D and requires depth slice to be provided")]
815    MissingDepthSlice,
816    #[error("Depth slice was provided but the color attachment's view is not 3D")]
817    UnneededDepthSlice,
818    #[error("{view}'s subresource at mip {mip_level} and depth/array layer {depth_or_array_layer} is already attached to this render pass")]
819    SubresourceOverlap {
820        view: ResourceErrorIdent,
821        mip_level: u32,
822        depth_or_array_layer: u32,
823    },
824    #[error(
825        "Color attachment with `TRANSIENT_ATTACHMENT` usage can only be used with \
826        `LoadOp::Clear` or `LoadOp::DontCare` (if it is available) and  `StoreOp::Discard`. Operations `{0:?}` were provided"
827    )]
828    InvalidTransientAttachmentOp((LoadOp<Color>, StoreOp)),
829    #[error("Color attachment's load op is `LoadOp::DontCare` but `InstanceFlags::STRICT_WEBGPU_COMPLIANCE` is set")]
830    LoadOpDontCareUnderStrictWebgpuCompliance,
831}
832
833impl WebGpuError for ColorAttachmentError {
834    fn webgpu_error_type(&self) -> ErrorType {
835        ErrorType::Validation
836    }
837}
838
839#[derive(Clone, Debug, Error)]
840#[non_exhaustive]
841pub enum AttachmentError {
842    #[error("The format of the depth-stencil attachment ({0:?}) is not a depth-or-stencil format")]
843    InvalidDepthStencilAttachmentFormat(wgt::TextureFormat),
844    #[error(
845        "Depth attachment with `TRANSIENT_ATTACHMENT` usage can only be used with \
846        `LoadOp::Clear` or `LoadOp::DontCare` (if it is available) and  `StoreOp::Discard`. Operations `{0:?}` were provided"
847    )]
848    InvalidTransientDepthAttachmentOps((LoadOp<Option<f32>>, StoreOp)),
849    #[error("Depth attachment with `TRANSIENT_ATTACHMENT` usage cannot be read-only")]
850    ReadOnlyTransientDepthAttachment,
851    #[error(
852        "Stencil attachment with `TRANSIENT_ATTACHMENT` usage can only be used with \
853        `LoadOp::Clear` or `LoadOp::DontCare` (if it is available) and  `StoreOp::Discard`. Operations `{0:?}` were provided"
854    )]
855    InvalidTransientStencilAttachmentOps((LoadOp<Option<u32>>, StoreOp)),
856    #[error("Stencil attachment with `TRANSIENT_ATTACHMENT` usage cannot be read-only")]
857    ReadOnlyTransientStencilAttachment,
858    #[error("LoadOp must be None for read-only attachments")]
859    ReadOnlyWithLoad,
860    #[error("StoreOp must be None for read-only attachments")]
861    ReadOnlyWithStore,
862    #[error("Depth `LoadOp` and `StoreOp` (`{ops:?}`) must be `None` for attachments (`{format:?}`) without depth aspect")]
863    DepthOpsWithoutAspect {
864        format: wgt::TextureFormat,
865        ops: (Option<LoadOp<Option<f32>>>, Option<StoreOp>),
866    },
867    #[error("Stencil `LoadOp` and `StoreOp` (`{ops:?}`) must be `None` for attachments (`{format:?}`) without stencil aspect")]
868    StencilOpsWithoutAspect {
869        format: wgt::TextureFormat,
870        ops: (Option<LoadOp<Option<u32>>>, Option<StoreOp>),
871    },
872    #[error("Attachment without load")]
873    NoLoad,
874    #[error("Attachment without store")]
875    NoStore,
876    #[error("LoadOp is `Clear` but no clear value was provided")]
877    NoClearValue,
878    #[error("Clear value ({0}) must be between 0.0 and 1.0, inclusive")]
879    ClearValueOutOfRange(f32),
880    #[error("Load op is `DontCare` but `InstanceFlags::STRICT_WEBGPU_COMPLIANCE` is set")]
881    LoadOpDontCareUnderStrictWebgpuCompliance,
882}
883
884impl WebGpuError for AttachmentError {
885    fn webgpu_error_type(&self) -> ErrorType {
886        ErrorType::Validation
887    }
888}
889
890/// Error encountered when performing a render pass.
891#[derive(Clone, Debug, Error)]
892pub enum RenderPassErrorInner {
893    #[error(transparent)]
894    Device(#[from] DeviceError),
895    #[error(transparent)]
896    ColorAttachment(#[from] ColorAttachmentError),
897    #[error(transparent)]
898    InvalidAttachment(#[from] AttachmentError),
899    #[error(transparent)]
900    EncoderState(#[from] EncoderStateError),
901    #[error("Parent encoder is invalid")]
902    InvalidParentEncoder,
903    #[error(transparent)]
904    DebugGroupError(#[from] DebugGroupError),
905    #[error("The format of the {location} ({format:?}) is not resolvable")]
906    UnsupportedResolveTargetFormat {
907        location: AttachmentErrorLocation,
908        format: wgt::TextureFormat,
909    },
910    #[error("The {location} is not valid, because the texture has `TRANSIENT_ATTACHMENT` usage")]
911    InvalidTransientResolveTarget { location: AttachmentErrorLocation },
912    #[error("No color attachments or depth attachments were provided, at least one attachment of any kind must be provided")]
913    MissingAttachments,
914    #[error("The {location} is not renderable:")]
915    TextureViewIsNotRenderable {
916        location: AttachmentErrorLocation,
917        #[source]
918        reason: TextureViewNotRenderableReason,
919    },
920    #[error("Attachments have differing sizes: the {expected_location} has extent {expected_extent:?} but is followed by the {actual_location} which has {actual_extent:?}")]
921    AttachmentsDimensionMismatch {
922        expected_location: AttachmentErrorLocation,
923        expected_extent: wgt::Extent3d,
924        actual_location: AttachmentErrorLocation,
925        actual_extent: wgt::Extent3d,
926    },
927    #[error("Attachments have differing sample counts: the {expected_location} has count {expected_samples:?} but is followed by the {actual_location} which has count {actual_samples:?}")]
928    AttachmentSampleCountMismatch {
929        expected_location: AttachmentErrorLocation,
930        expected_samples: u32,
931        actual_location: AttachmentErrorLocation,
932        actual_samples: u32,
933    },
934    #[error("The resolve source, {location}, must be multi-sampled (has {src} samples) while the resolve destination must not be multisampled (has {dst} samples)")]
935    InvalidResolveSampleCounts {
936        location: AttachmentErrorLocation,
937        src: u32,
938        dst: u32,
939    },
940    #[error(
941        "Resource source, {location}, format ({src:?}) must match the resolve destination format ({dst:?})"
942    )]
943    MismatchedResolveTextureFormat {
944        location: AttachmentErrorLocation,
945        src: wgt::TextureFormat,
946        dst: wgt::TextureFormat,
947    },
948    #[error("Unable to clear non-present/read-only depth")]
949    InvalidDepthOps,
950    #[error("Unable to clear non-present/read-only stencil")]
951    InvalidStencilOps,
952    #[error(transparent)]
953    MissingFeatures(#[from] MissingFeatures),
954    #[error(transparent)]
955    MissingDownlevelFlags(#[from] MissingDownlevelFlags),
956    #[error("Indirect draw count of {count_bytes} bytes starting at {begin_count_offset} would overrun buffer of size {count_buffer_size}")]
957    IndirectCountBufferOverrun {
958        count_bytes: u64,
959        begin_count_offset: u64,
960        count_buffer_size: u64,
961    },
962    #[error(transparent)]
963    ResourceUsageCompatibility(#[from] ResourceUsageCompatibilityError),
964    #[error("Render bundle has incompatible targets, {0}")]
965    IncompatibleBundleTargets(#[from] RenderPassCompatibilityError),
966    #[error(
967        "Render bundle has incompatible read-only flags: \
968             bundle has flags depth = {bundle_depth} and stencil = {bundle_stencil}, \
969             while the pass has flags depth = {pass_depth} and stencil = {pass_stencil}. \
970             Read-only renderpasses are only compatible with read-only bundles for that aspect."
971    )]
972    IncompatibleBundleReadOnlyDepthStencil {
973        pass_depth: bool,
974        pass_stencil: bool,
975        bundle_depth: bool,
976        bundle_stencil: bool,
977    },
978    #[error(transparent)]
979    RenderCommand(#[from] RenderCommandError),
980    #[error(transparent)]
981    Draw(#[from] DrawError),
982    #[error(transparent)]
983    Bind(#[from] BindError),
984    #[error(transparent)]
985    QueryUse(#[from] QueryUseError),
986    #[error("Multiview layer count must match")]
987    MultiViewMismatch,
988    #[error(
989        "Multiview pass texture views with more than one array layer must have D2Array dimension"
990    )]
991    MultiViewDimensionMismatch,
992    #[error("Multiview view count limit violated")]
993    TooManyMultiviewViews,
994    #[error("missing occlusion query set")]
995    MissingOcclusionQuerySet,
996    #[error(transparent)]
997    DestroyedResource(#[from] DestroyedResourceError),
998    #[error("The compute pass has already been ended and no further commands can be recorded")]
999    PassEnded,
1000    #[error(transparent)]
1001    InvalidResource(#[from] InvalidResourceError),
1002    #[error(transparent)]
1003    TimestampWrites(#[from] TimestampWritesError),
1004}
1005
1006impl From<InvalidOrDestroyedResourceError> for RenderPassErrorInner {
1007    fn from(error: InvalidOrDestroyedResourceError) -> Self {
1008        match error {
1009            InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e),
1010            InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e),
1011        }
1012    }
1013}
1014
1015impl From<MissingBufferUsageError> for RenderPassErrorInner {
1016    fn from(error: MissingBufferUsageError) -> Self {
1017        Self::RenderCommand(error.into())
1018    }
1019}
1020
1021impl From<MissingTextureUsageError> for RenderPassErrorInner {
1022    fn from(error: MissingTextureUsageError) -> Self {
1023        Self::RenderCommand(error.into())
1024    }
1025}
1026
1027impl From<pass::BindGroupIndexOutOfRange> for RenderPassErrorInner {
1028    fn from(error: pass::BindGroupIndexOutOfRange) -> Self {
1029        Self::RenderCommand(RenderCommandError::BindGroupIndexOutOfRange(error))
1030    }
1031}
1032
1033impl From<pass::MissingPipeline> for RenderPassErrorInner {
1034    fn from(error: pass::MissingPipeline) -> Self {
1035        Self::Draw(DrawError::MissingPipeline(error))
1036    }
1037}
1038
1039impl From<ImmediateUploadError> for RenderPassErrorInner {
1040    fn from(error: ImmediateUploadError) -> Self {
1041        Self::RenderCommand(error.into())
1042    }
1043}
1044
1045/// Error encountered when performing a render pass.
1046#[derive(Clone, Debug, Error)]
1047#[error("{scope}")]
1048pub struct RenderPassError {
1049    pub scope: PassErrorScope,
1050    #[source]
1051    pub(super) inner: Box<RenderPassErrorInner>,
1052}
1053
1054impl<E: Into<RenderPassErrorInner>> MapPassErr<RenderPassError> for E {
1055    fn map_pass_err(self, scope: PassErrorScope) -> RenderPassError {
1056        RenderPassError {
1057            scope,
1058            inner: Box::new(self.into()),
1059        }
1060    }
1061}
1062
1063impl WebGpuError for RenderPassError {
1064    fn webgpu_error_type(&self) -> ErrorType {
1065        match self.inner.as_ref() {
1066            RenderPassErrorInner::Device(e) => e.webgpu_error_type(),
1067            RenderPassErrorInner::ColorAttachment(e) => e.webgpu_error_type(),
1068            RenderPassErrorInner::EncoderState(e) => e.webgpu_error_type(),
1069            RenderPassErrorInner::DebugGroupError(e) => e.webgpu_error_type(),
1070            RenderPassErrorInner::MissingFeatures(e) => e.webgpu_error_type(),
1071            RenderPassErrorInner::MissingDownlevelFlags(e) => e.webgpu_error_type(),
1072            RenderPassErrorInner::RenderCommand(e) => e.webgpu_error_type(),
1073            RenderPassErrorInner::Draw(e) => e.webgpu_error_type(),
1074            RenderPassErrorInner::Bind(e) => e.webgpu_error_type(),
1075            RenderPassErrorInner::QueryUse(e) => e.webgpu_error_type(),
1076            RenderPassErrorInner::DestroyedResource(e) => e.webgpu_error_type(),
1077            RenderPassErrorInner::InvalidResource(e) => e.webgpu_error_type(),
1078            RenderPassErrorInner::IncompatibleBundleTargets(e) => e.webgpu_error_type(),
1079            RenderPassErrorInner::InvalidAttachment(e) => e.webgpu_error_type(),
1080            RenderPassErrorInner::TimestampWrites(e) => e.webgpu_error_type(),
1081
1082            RenderPassErrorInner::InvalidParentEncoder
1083            | RenderPassErrorInner::UnsupportedResolveTargetFormat { .. }
1084            | RenderPassErrorInner::InvalidTransientResolveTarget { .. }
1085            | RenderPassErrorInner::MissingAttachments
1086            | RenderPassErrorInner::TextureViewIsNotRenderable { .. }
1087            | RenderPassErrorInner::AttachmentsDimensionMismatch { .. }
1088            | RenderPassErrorInner::AttachmentSampleCountMismatch { .. }
1089            | RenderPassErrorInner::InvalidResolveSampleCounts { .. }
1090            | RenderPassErrorInner::MismatchedResolveTextureFormat { .. }
1091            | RenderPassErrorInner::InvalidDepthOps
1092            | RenderPassErrorInner::InvalidStencilOps
1093            | RenderPassErrorInner::IndirectCountBufferOverrun { .. }
1094            | RenderPassErrorInner::ResourceUsageCompatibility(..)
1095            | RenderPassErrorInner::IncompatibleBundleReadOnlyDepthStencil { .. }
1096            | RenderPassErrorInner::MultiViewMismatch
1097            | RenderPassErrorInner::MultiViewDimensionMismatch
1098            | RenderPassErrorInner::TooManyMultiviewViews
1099            | RenderPassErrorInner::MissingOcclusionQuerySet
1100            | RenderPassErrorInner::PassEnded => ErrorType::Validation,
1101        }
1102    }
1103}
1104
1105struct RenderAttachment {
1106    texture: Arc<Texture>,
1107    selector: TextureSelector,
1108    usage: wgt::TextureUses,
1109}
1110
1111impl TextureView {
1112    fn to_render_attachment(&self, usage: wgt::TextureUses) -> RenderAttachment {
1113        RenderAttachment {
1114            texture: self.parent.clone(),
1115            selector: self.selector.clone(),
1116            usage,
1117        }
1118    }
1119}
1120
1121const MAX_TOTAL_ATTACHMENTS: usize = hal::MAX_COLOR_ATTACHMENTS + hal::MAX_COLOR_ATTACHMENTS + 1;
1122type AttachmentDataVec<T> = ArrayVec<T, MAX_TOTAL_ATTACHMENTS>;
1123
1124struct RenderPassInfo {
1125    context: RenderPassContext,
1126    /// All render attachments, including depth/stencil
1127    render_attachments: AttachmentDataVec<RenderAttachment>,
1128    is_depth_read_only: bool,
1129    is_stencil_read_only: bool,
1130    extent: wgt::Extent3d,
1131
1132    divergent_discarded_depth_stencil_aspect: Option<(wgt::TextureAspect, Arc<TextureView>)>,
1133    multiview_mask: Option<NonZeroU32>,
1134}
1135
1136impl RenderPassInfo {
1137    fn add_pass_texture_init_actions<V>(
1138        load_op: LoadOp<V>,
1139        store_op: StoreOp,
1140        texture_memory_actions: &mut CommandBufferTextureMemoryActions,
1141        view: &TextureView,
1142        depth_slice: Option<u32>,
1143        pending_discard_init_fixups: &mut SurfacesInDiscardState,
1144    ) {
1145        match (
1146            depth_slice,
1147            view.parent.desc.dimension == wgt::TextureDimension::D3,
1148        ) {
1149            (Some(_), true) | (None, false) => {}
1150            _ => unreachable!("3D textures, but not any other kind, must specify a depth slice"),
1151        }
1152        // 3D textures with more than one depth slice are a special case,
1153        // because we don't track initialization status per slice.
1154        let partial_z = view.parent.desc.dimension == wgt::TextureDimension::D3
1155            && view
1156                .parent
1157                .desc
1158                .mip_level_size(view.selector.mips.start)
1159                .is_some_and(|dim| dim.depth_or_array_layers > 1);
1160
1161        if matches!(load_op, LoadOp::Load) {
1162            // Record the initialization action for the texture. Simultaneously, collect a
1163            // list of any ranges of the texture that were discarded within the current
1164            // command buffer, for initialization by `fixup_discarded_surfaces`.
1165            // (The analogous case for texture copies is in `handle_texture_init`.)
1166            //
1167            // Even when the target is a depth slice of a 3D texture, this is an action
1168            // for the entire mip. In most cases that is what we want (if there is any
1169            // live data in the mip at the end of a command buffer, we must have the
1170            // entire thing initialized). The exception is Load+Discard of one slice in an
1171            // uninitialized mip. In that case, we could initialize only one slice, and then
1172            // leave the entire mip uninitialized at the end of the command buffer. But we
1173            // don't optimize that, because it is a lot of complexity for a case that
1174            // doesn't seem very useful (if the render targets are only used transiently,
1175            // why is it important that they are volume slices?).
1176            pending_discard_init_fixups.extend(texture_memory_actions.register_init_action(
1177                &TextureInitTrackerAction {
1178                    texture: view.parent.clone(),
1179                    range: TextureInitRange::from(view),
1180                    // Note that this is needed for `Load` even if the target has `StoreOp::Discard`.
1181                    kind: MemoryInitKind::NeedsInitializedMemory,
1182                },
1183                depth_slice.map(|slice| slice..slice + 1),
1184            ));
1185        } else if store_op == StoreOp::Store {
1186            if partial_z {
1187                // We must initialize the entire mip due to init tracking granularity.
1188                pending_discard_init_fixups.extend(texture_memory_actions.register_init_action(
1189                    &TextureInitTrackerAction {
1190                        texture: view.parent.clone(),
1191                        range: TextureInitRange::from(view),
1192                        kind: MemoryInitKind::NeedsInitializedMemory,
1193                    },
1194                    depth_slice.map(|slice| slice..slice + 1),
1195                ));
1196            } else {
1197                // Clear + Store
1198                texture_memory_actions
1199                    .register_implicit_init(&view.parent, TextureInitRange::from(view));
1200            }
1201        }
1202        if store_op == StoreOp::Discard {
1203            // The discard happens at the *end* of a pass, but recording the
1204            // discard right away is fine, since attachments can't be used
1205            // for any other purpose during the pass.
1206            //
1207            // Discards are usually deferred as long as possible (i.e. until the
1208            // next use of the subresource). But discarded depth slices of 3D
1209            // textures will be reinitialized at the end of the command buffer
1210            // (by [`BakedCommands::initialize_discarded_depth_slices`]),
1211            // because the primary init tracker does not track individual slices.
1212            texture_memory_actions.discard(TextureSurfaceDiscard {
1213                texture: view.parent.clone(),
1214                mip_level: view.selector.mips.start,
1215                layer_or_depth_slice: depth_slice.unwrap_or(view.selector.layers.start),
1216            });
1217        }
1218    }
1219
1220    fn start(
1221        device: &Arc<Device>,
1222        hal_label: Option<&str>,
1223        color_attachments: &[Option<RenderPassColorAttachment>],
1224        mut depth_stencil_attachment: Option<
1225            ResolvedRenderPassDepthStencilAttachment<Arc<TextureView>>,
1226        >,
1227        mut timestamp_writes: Option<PassTimestampWrites>,
1228        mut occlusion_query_set: Option<Arc<QuerySet>>,
1229        encoder: &mut dyn hal::DynCommandEncoder,
1230        trackers: &mut Tracker,
1231        texture_memory_actions: &mut CommandBufferTextureMemoryActions,
1232        pending_query_resets: &mut QueryResetMap,
1233        pending_discard_init_fixups: &mut SurfacesInDiscardState,
1234        snatch_guard: &SnatchGuard<'_>,
1235        query_set_writes: &mut QuerySetWrites,
1236        multiview_mask: Option<NonZeroU32>,
1237    ) -> Result<Self, RenderPassErrorInner> {
1238        profiling::scope!("RenderPassInfo::start");
1239
1240        // We default to false intentionally, even if depth-stencil isn't used at all.
1241        // This allows us to use the primary raw pipeline in `RenderPipeline`,
1242        // instead of the special read-only one, which would be `None`.
1243        let mut is_depth_read_only = false;
1244        let mut is_stencil_read_only = false;
1245
1246        let mut render_attachments = AttachmentDataVec::<RenderAttachment>::new();
1247        let mut divergent_discarded_depth_stencil_aspect = None;
1248
1249        let mut attachment_location = AttachmentErrorLocation::Color {
1250            index: usize::MAX,
1251            resolve: false,
1252        };
1253        let mut extent = None;
1254        let mut sample_count = 0;
1255
1256        let mut detected_multiview: Option<Option<NonZeroU32>> = None;
1257
1258        let mut check_multiview = |view: &TextureView| {
1259            // Get the multiview configuration for this texture view
1260            let layers = view.selector.layers.end - view.selector.layers.start;
1261            let this_multiview = if layers >= 2 {
1262                // Trivially proven by the if above
1263                Some(unsafe { NonZeroU32::new_unchecked(layers) })
1264            } else {
1265                None
1266            };
1267
1268            // Make sure that if this view is a multiview, it is set to be an array
1269            if this_multiview.is_some() && view.desc.dimension != TextureViewDimension::D2Array {
1270                return Err(RenderPassErrorInner::MultiViewDimensionMismatch);
1271            }
1272
1273            // Validate matching first, or store the first one
1274            if let Some(multiview) = detected_multiview {
1275                if multiview != this_multiview {
1276                    return Err(RenderPassErrorInner::MultiViewMismatch);
1277                }
1278            } else {
1279                // Multiview is only supported if the feature is enabled
1280                if let Some(this_multiview) = this_multiview {
1281                    device.require_features(wgt::Features::MULTIVIEW)?;
1282                    if this_multiview.get() > device.limits.max_multiview_view_count {
1283                        return Err(RenderPassErrorInner::TooManyMultiviewViews);
1284                    }
1285                }
1286
1287                detected_multiview = Some(this_multiview);
1288            }
1289
1290            Ok(())
1291        };
1292        let mut add_view = |view: &TextureView, location| {
1293            let render_extent = view.state()?.render_extent.map_err(|reason| {
1294                RenderPassErrorInner::TextureViewIsNotRenderable { location, reason }
1295            })?;
1296            if let Some(ex) = extent {
1297                if ex != render_extent {
1298                    return Err(RenderPassErrorInner::AttachmentsDimensionMismatch {
1299                        expected_location: attachment_location,
1300                        expected_extent: ex,
1301                        actual_location: location,
1302                        actual_extent: render_extent,
1303                    });
1304                }
1305            } else {
1306                extent = Some(render_extent);
1307            }
1308            if sample_count == 0 {
1309                sample_count = view.samples;
1310            } else if sample_count != view.samples {
1311                return Err(RenderPassErrorInner::AttachmentSampleCountMismatch {
1312                    expected_location: attachment_location,
1313                    expected_samples: sample_count,
1314                    actual_location: location,
1315                    actual_samples: view.samples,
1316                });
1317            }
1318            attachment_location = location;
1319            Ok(())
1320        };
1321
1322        let mut depth_stencil = None;
1323
1324        if let Some(at) = depth_stencil_attachment.as_ref() {
1325            let view = &at.view;
1326            check_multiview(view)?;
1327            add_view(view, AttachmentErrorLocation::Depth)?;
1328
1329            let ds_aspects = view.desc.aspects();
1330
1331            if !ds_aspects.contains(hal::FormatAspects::STENCIL)
1332                || (at.stencil.load_op().eq_variant(at.depth.load_op())
1333                    && at.stencil.store_op() == at.depth.store_op())
1334            {
1335                Self::add_pass_texture_init_actions(
1336                    at.depth.load_op(),
1337                    at.depth.store_op(),
1338                    texture_memory_actions,
1339                    view,
1340                    None,
1341                    pending_discard_init_fixups,
1342                );
1343            } else if !ds_aspects.contains(hal::FormatAspects::DEPTH) {
1344                Self::add_pass_texture_init_actions(
1345                    at.stencil.load_op(),
1346                    at.stencil.store_op(),
1347                    texture_memory_actions,
1348                    view,
1349                    None,
1350                    pending_discard_init_fixups,
1351                );
1352            } else {
1353                // This is the only place (anywhere in wgpu) where Stencil &
1354                // Depth init state can diverge.
1355                //
1356                // To save us the overhead of tracking init state of texture
1357                // aspects everywhere, we're going to cheat a little bit in
1358                // order to keep the init state of both Stencil and Depth
1359                // aspects in sync. The expectation is that we hit this path
1360                // extremely rarely!
1361                //
1362                // Diverging LoadOp, i.e. Load + Clear:
1363                //
1364                // Record MemoryInitKind::NeedsInitializedMemory for the entire
1365                // surface, a bit wasteful due to redundancy with Clear, but no
1366                // negative effect!
1367                //
1368                // Rationale: If the loaded channel is uninitialized it needs
1369                // clearing, the cleared channel doesn't care. (If everything is
1370                // already initialized nothing special happens)
1371                //
1372                // (possible minor optimization: Clear caused by
1373                // NeedsInitializedMemory should know that it doesn't need to
1374                // clear the aspect that was set to C)
1375                let need_init_beforehand =
1376                    at.depth.load_op() == LoadOp::Load || at.stencil.load_op() == LoadOp::Load;
1377                if need_init_beforehand {
1378                    pending_discard_init_fixups.extend(
1379                        texture_memory_actions.register_init_action(
1380                            &TextureInitTrackerAction {
1381                                texture: view.parent.clone(),
1382                                range: TextureInitRange::from(view.as_ref()),
1383                                kind: MemoryInitKind::NeedsInitializedMemory,
1384                            },
1385                            None, // depth/stencil textures are never 3D
1386                        ),
1387                    );
1388                }
1389
1390                // Diverging Store, i.e. Discard + Store:
1391                //
1392                // Immediately zero out channel that is set to discard after
1393                // we're done with the render pass. This allows us to set the
1394                // entire surface to MemoryInitKind::ImplicitlyInitialized (if
1395                // it isn't already set to NeedsInitializedMemory).
1396                //
1397                // (possible optimization: Delay and potentially drop this zeroing)
1398                if at.depth.store_op() != at.stencil.store_op() {
1399                    if !need_init_beforehand {
1400                        texture_memory_actions.register_implicit_init(
1401                            &view.parent,
1402                            TextureInitRange::from(view.as_ref()),
1403                        );
1404                    }
1405                    divergent_discarded_depth_stencil_aspect = Some((
1406                        if at.depth.store_op() == StoreOp::Discard {
1407                            wgt::TextureAspect::DepthOnly
1408                        } else {
1409                            wgt::TextureAspect::StencilOnly
1410                        },
1411                        view.clone(),
1412                    ));
1413                } else if at.depth.store_op() == StoreOp::Discard {
1414                    // Both are discarded using the regular path.
1415                    texture_memory_actions.discard(TextureSurfaceDiscard {
1416                        texture: view.parent.clone(),
1417                        mip_level: view.selector.mips.start,
1418                        layer_or_depth_slice: view.selector.layers.start,
1419                    });
1420                }
1421            }
1422
1423            is_depth_read_only = at.depth.is_readonly();
1424            is_stencil_read_only = at.stencil.is_readonly();
1425
1426            let usage = 'b: {
1427                if device
1428                    .downlevel
1429                    .flags
1430                    .contains(wgt::DownlevelFlags::READ_ONLY_DEPTH_STENCIL)
1431                {
1432                    let depth_stencil_uses = match (is_depth_read_only, is_stencil_read_only) {
1433                        (true, true) => {
1434                            wgt::TextureUses::DEPTH_READ | wgt::TextureUses::STENCIL_READ
1435                        }
1436                        (true, false) => {
1437                            wgt::TextureUses::DEPTH_READ | wgt::TextureUses::STENCIL_WRITE
1438                        }
1439                        (false, true) => {
1440                            wgt::TextureUses::DEPTH_WRITE | wgt::TextureUses::STENCIL_READ
1441                        }
1442                        (false, false) => {
1443                            break 'b wgt::TextureUses::DEPTH_WRITE
1444                                | wgt::TextureUses::STENCIL_WRITE;
1445                        }
1446                    };
1447                    // If the texture supports TEXTURE_BINDING, it can be used as a shader
1448                    // resource and a read-only depth attachment simultaneously. But if it
1449                    // doesn't support TEXTURE_BINDING, don't attempt to transition it to a
1450                    // shader resource state, because DX12 will raise an error.
1451                    if view.desc.usage.contains(TextureUsages::TEXTURE_BINDING) {
1452                        depth_stencil_uses | wgt::TextureUses::RESOURCE
1453                    } else {
1454                        depth_stencil_uses
1455                    }
1456                } else {
1457                    wgt::TextureUses::DEPTH_WRITE | wgt::TextureUses::STENCIL_WRITE
1458                }
1459            };
1460            render_attachments.push(view.to_render_attachment(usage));
1461
1462            depth_stencil = Some(hal::DepthStencilAttachment {
1463                target: hal::Attachment {
1464                    view: view.try_raw(snatch_guard)?,
1465                    usage,
1466                },
1467                depth_ops: at.depth.hal_ops(),
1468                stencil_ops: at.stencil.hal_ops(),
1469                clear_value: (at.depth.clear_value(), at.stencil.clear_value()),
1470                depth_read_only: is_depth_read_only,
1471                stencil_read_only: is_stencil_read_only,
1472            });
1473        }
1474
1475        let mut attachment_set = crate::FastHashSet::default();
1476
1477        let mut color_attachments_hal =
1478            ArrayVec::<Option<hal::ColorAttachment<_>>, { hal::MAX_COLOR_ATTACHMENTS }>::new();
1479        for (index, attachment) in color_attachments.iter().enumerate() {
1480            let at = if let Some(attachment) = attachment.as_ref() {
1481                attachment
1482            } else {
1483                color_attachments_hal.push(None);
1484                continue;
1485            };
1486            let color_view: &TextureView = &at.view;
1487            color_view.same_device(device)?;
1488            check_multiview(color_view)?;
1489            add_view(
1490                color_view,
1491                AttachmentErrorLocation::Color {
1492                    index,
1493                    resolve: false,
1494                },
1495            )?;
1496
1497            if !color_view.desc.aspects().intersects(
1498                hal::FormatAspects::COLOR
1499                    | hal::FormatAspects::PLANE_0
1500                    | hal::FormatAspects::PLANE_1
1501                    | hal::FormatAspects::PLANE_2,
1502            ) {
1503                return Err(RenderPassErrorInner::ColorAttachment(
1504                    ColorAttachmentError::InvalidFormat(color_view.desc.format),
1505                ));
1506            }
1507
1508            if color_view.desc.dimension == TextureViewDimension::D3 {
1509                if let Some(depth_slice) = at.depth_slice {
1510                    let mip = color_view.desc.range.base_mip_level;
1511                    let mip_size = color_view
1512                        .parent
1513                        .desc
1514                        .size
1515                        .mip_level_size(mip, color_view.parent.desc.dimension);
1516                    let limit = mip_size.depth_or_array_layers;
1517                    if depth_slice >= limit {
1518                        return Err(RenderPassErrorInner::ColorAttachment(
1519                            ColorAttachmentError::DepthSliceLimit {
1520                                given: depth_slice,
1521                                limit,
1522                            },
1523                        ));
1524                    }
1525                } else {
1526                    return Err(RenderPassErrorInner::ColorAttachment(
1527                        ColorAttachmentError::MissingDepthSlice,
1528                    ));
1529                }
1530            } else if at.depth_slice.is_some() {
1531                return Err(RenderPassErrorInner::ColorAttachment(
1532                    ColorAttachmentError::UnneededDepthSlice,
1533                ));
1534            }
1535
1536            validation::validate_color_attachment_bytes_per_sample(
1537                color_attachments
1538                    .iter()
1539                    .flatten()
1540                    .map(|at| at.view.desc.format),
1541                device.limits.max_color_attachment_bytes_per_sample,
1542            )
1543            .map_err(RenderPassErrorInner::ColorAttachment)?;
1544
1545            fn check_attachment_overlap(
1546                attachment_set: &mut crate::FastHashSet<(crate::track::TrackerIndex, u32, u32)>,
1547                view: &TextureView,
1548                depth_slice: Option<u32>,
1549            ) -> Result<(), ColorAttachmentError> {
1550                let mut insert = |slice| {
1551                    let mip_level = view.desc.range.base_mip_level;
1552                    if attachment_set.insert((
1553                        view.parent.tracking_data.tracker_index(),
1554                        mip_level,
1555                        slice,
1556                    )) {
1557                        Ok(())
1558                    } else {
1559                        Err(ColorAttachmentError::SubresourceOverlap {
1560                            view: view.error_ident(),
1561                            mip_level,
1562                            depth_or_array_layer: slice,
1563                        })
1564                    }
1565                };
1566                match view.desc.dimension {
1567                    TextureViewDimension::D2 => {
1568                        insert(view.desc.range.base_array_layer)?;
1569                    }
1570                    TextureViewDimension::D2Array => {
1571                        for layer in view.selector.layers.clone() {
1572                            insert(layer)?;
1573                        }
1574                    }
1575                    TextureViewDimension::D3 => {
1576                        insert(depth_slice.unwrap())?;
1577                    }
1578                    _ => unreachable!(),
1579                };
1580                Ok(())
1581            }
1582
1583            check_attachment_overlap(&mut attachment_set, color_view, at.depth_slice)?;
1584
1585            Self::add_pass_texture_init_actions(
1586                at.load_op,
1587                at.store_op,
1588                texture_memory_actions,
1589                color_view,
1590                at.depth_slice,
1591                pending_discard_init_fixups,
1592            );
1593            render_attachments
1594                .push(color_view.to_render_attachment(wgt::TextureUses::COLOR_TARGET));
1595
1596            let mut hal_resolve_target = None;
1597            if let Some(resolve_view) = &at.resolve_target {
1598                resolve_view.same_device(device)?;
1599                check_multiview(resolve_view)?;
1600
1601                check_attachment_overlap(&mut attachment_set, resolve_view, None)?;
1602
1603                let resolve_location = AttachmentErrorLocation::Color {
1604                    index,
1605                    resolve: true,
1606                };
1607
1608                let render_extent = resolve_view.state()?.render_extent.map_err(|reason| {
1609                    RenderPassErrorInner::TextureViewIsNotRenderable {
1610                        location: resolve_location,
1611                        reason,
1612                    }
1613                })?;
1614                if color_view.state()?.render_extent.unwrap() != render_extent {
1615                    return Err(RenderPassErrorInner::AttachmentsDimensionMismatch {
1616                        expected_location: attachment_location,
1617                        expected_extent: extent.unwrap_or_default(),
1618                        actual_location: resolve_location,
1619                        actual_extent: render_extent,
1620                    });
1621                }
1622                if color_view.samples == 1 || resolve_view.samples != 1 {
1623                    return Err(RenderPassErrorInner::InvalidResolveSampleCounts {
1624                        location: resolve_location,
1625                        src: color_view.samples,
1626                        dst: resolve_view.samples,
1627                    });
1628                }
1629                if color_view.desc.format != resolve_view.desc.format {
1630                    return Err(RenderPassErrorInner::MismatchedResolveTextureFormat {
1631                        location: resolve_location,
1632                        src: color_view.desc.format,
1633                        dst: resolve_view.desc.format,
1634                    });
1635                }
1636                if !resolve_view
1637                    .format_features
1638                    .flags
1639                    .contains(wgt::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE)
1640                {
1641                    return Err(RenderPassErrorInner::UnsupportedResolveTargetFormat {
1642                        location: resolve_location,
1643                        format: resolve_view.desc.format,
1644                    });
1645                }
1646                if resolve_view
1647                    .desc
1648                    .usage
1649                    .contains(TextureUsages::TRANSIENT_ATTACHMENT)
1650                {
1651                    return Err(RenderPassErrorInner::InvalidTransientResolveTarget {
1652                        location: resolve_location,
1653                    });
1654                }
1655
1656                texture_memory_actions.register_implicit_init(
1657                    &resolve_view.parent,
1658                    TextureInitRange::from(resolve_view.as_ref()),
1659                );
1660                render_attachments
1661                    .push(resolve_view.to_render_attachment(wgt::TextureUses::COLOR_TARGET));
1662
1663                hal_resolve_target = Some(hal::Attachment {
1664                    view: resolve_view.try_raw(snatch_guard)?,
1665                    usage: wgt::TextureUses::COLOR_TARGET,
1666                });
1667            }
1668
1669            color_attachments_hal.push(Some(hal::ColorAttachment {
1670                target: hal::Attachment {
1671                    view: color_view.try_raw(snatch_guard)?,
1672                    usage: wgt::TextureUses::COLOR_TARGET,
1673                },
1674                depth_slice: at.depth_slice,
1675                resolve_target: hal_resolve_target,
1676                ops: at.hal_ops(),
1677                clear_value: at.clear_value(),
1678            }));
1679        }
1680
1681        let extent = extent.ok_or(RenderPassErrorInner::MissingAttachments)?;
1682
1683        let detected_multiview =
1684            detected_multiview.expect("Multiview was not detected, no attachments");
1685        if let Some(mask) = multiview_mask {
1686            // 0x01 will have msb 0
1687            let mask_msb = 31 - mask.leading_zeros();
1688            let detected_mv = detected_multiview.map(NonZeroU32::get).unwrap_or(1);
1689            if mask_msb >= detected_mv {
1690                return Err(RenderPassErrorInner::MultiViewMismatch);
1691            }
1692            if mask.get() != (1 << detected_mv) - 1 {
1693                device.require_features(wgt::Features::SELECTIVE_MULTIVIEW)?;
1694            }
1695        }
1696
1697        let attachment_formats = AttachmentData {
1698            colors: color_attachments
1699                .iter()
1700                .map(|at| at.as_ref().map(|at| at.view.desc.format))
1701                .collect(),
1702            resolves: color_attachments
1703                .iter()
1704                .filter_map(|at| {
1705                    at.as_ref().and_then(|at| {
1706                        at.resolve_target
1707                            .as_ref()
1708                            .map(|resolve| resolve.desc.format)
1709                    })
1710                })
1711                .collect(),
1712            depth_stencil: depth_stencil_attachment
1713                .as_ref()
1714                .map(|at| at.view.desc.format),
1715        };
1716
1717        let context = RenderPassContext {
1718            attachments: attachment_formats,
1719            sample_count,
1720            multiview_mask,
1721        };
1722
1723        let timestamp_writes_hal = if let Some(tw) = timestamp_writes.as_ref() {
1724            let query_set = &tw.query_set;
1725            query_set.same_device(device)?;
1726
1727            if let Some(index) = tw.beginning_of_pass_write_index {
1728                pending_query_resets.use_query_set(query_set, index);
1729            }
1730            if let Some(index) = tw.end_of_pass_write_index {
1731                pending_query_resets.use_query_set(query_set, index);
1732            }
1733
1734            record_pass_timestamp_writes(tw, query_set_writes);
1735
1736            Some(hal::PassTimestampWrites {
1737                query_set: query_set.try_raw(snatch_guard)?,
1738                beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
1739                end_of_pass_write_index: tw.end_of_pass_write_index,
1740            })
1741        } else {
1742            None
1743        };
1744
1745        let occlusion_query_set_hal = if let Some(query_set) = occlusion_query_set.as_ref() {
1746            query_set.same_device(device)?;
1747            Some(query_set.try_raw(snatch_guard)?)
1748        } else {
1749            None
1750        };
1751
1752        let hal_desc = hal::RenderPassDescriptor {
1753            label: hal_label,
1754            extent,
1755            sample_count,
1756            color_attachments: &color_attachments_hal,
1757            depth_stencil_attachment: depth_stencil,
1758            multiview_mask,
1759            timestamp_writes: timestamp_writes_hal,
1760            occlusion_query_set: occlusion_query_set_hal,
1761        };
1762        unsafe {
1763            encoder
1764                .begin_render_pass(&hal_desc)
1765                .map_err(|e| device.handle_hal_error(e))?;
1766        };
1767        drop(color_attachments_hal); // Drop, so we can consume `color_attachments` for the tracker.
1768
1769        // Can't borrow the tracker more than once, so have to add to the tracker after the `begin_render_pass` hal call.
1770        if let Some(tw) = timestamp_writes.take() {
1771            trackers.query_sets.insert_single(tw.query_set);
1772        };
1773        if let Some(occlusion_query_set) = occlusion_query_set.take() {
1774            trackers.query_sets.insert_single(occlusion_query_set);
1775        };
1776        if let Some(at) = depth_stencil_attachment.take() {
1777            trackers.views.insert_single(at.view.clone());
1778        }
1779        for at in color_attachments.iter().flatten() {
1780            trackers.views.insert_single(at.view.clone());
1781            if let Some(resolve_target) = at.resolve_target.clone() {
1782                trackers.views.insert_single(resolve_target);
1783            }
1784        }
1785
1786        Ok(Self {
1787            context,
1788            render_attachments,
1789            is_depth_read_only,
1790            is_stencil_read_only,
1791            extent,
1792            divergent_discarded_depth_stencil_aspect,
1793            multiview_mask,
1794        })
1795    }
1796
1797    fn finish(
1798        self,
1799        device: &Device,
1800        raw: &mut dyn hal::DynCommandEncoder,
1801        snatch_guard: &SnatchGuard,
1802        scope: &mut UsageScope<'_>,
1803        instance_flags: InstanceFlags,
1804    ) -> Result<(), RenderPassErrorInner> {
1805        profiling::scope!("RenderPassInfo::finish");
1806        unsafe {
1807            raw.end_render_pass();
1808        }
1809
1810        for ra in self.render_attachments {
1811            let texture = &ra.texture;
1812            texture.check_usage(TextureUsages::RENDER_ATTACHMENT)?;
1813
1814            // the tracker set of the pass is always in "extend" mode
1815            unsafe {
1816                scope
1817                    .textures
1818                    .merge_single(texture, Some(ra.selector.clone()), ra.usage)?
1819            };
1820        }
1821
1822        // If one aspect of a combined depth/stencil format was discarded, we
1823        // clear that aspect immediately to keep the init status of the aspects
1824        // in sync. We do this so we don't need to track init state for depth/
1825        // stencil aspects individually. We can't initialize the entire texture,
1826        // because the user may genuinely want to preserve the data in the
1827        // aspect that was not discarded.
1828        if let Some((aspect, view)) = self.divergent_discarded_depth_stencil_aspect {
1829            let (depth_ops, stencil_ops) = if aspect == wgt::TextureAspect::DepthOnly {
1830                (
1831                    hal::AttachmentOps::LOAD_CLEAR | hal::AttachmentOps::STORE, // clear depth
1832                    hal::AttachmentOps::LOAD | hal::AttachmentOps::STORE,       // unchanged stencil
1833                )
1834            } else {
1835                (
1836                    hal::AttachmentOps::LOAD | hal::AttachmentOps::STORE, // unchanged stencil
1837                    hal::AttachmentOps::LOAD_CLEAR | hal::AttachmentOps::STORE, // clear depth
1838                )
1839            };
1840            let desc = hal::RenderPassDescriptor::<'_, _, dyn hal::DynTextureView> {
1841                label: hal_label(
1842                    Some("(wgpu internal) Zero init discarded depth/stencil aspect"),
1843                    instance_flags,
1844                ),
1845                extent: view.state()?.render_extent.unwrap(),
1846                sample_count: view.samples,
1847                color_attachments: &[],
1848                depth_stencil_attachment: Some(hal::DepthStencilAttachment {
1849                    target: hal::Attachment {
1850                        view: view.try_raw(snatch_guard)?,
1851                        usage: wgt::TextureUses::DEPTH_WRITE | wgt::TextureUses::STENCIL_WRITE,
1852                    },
1853                    depth_ops,
1854                    stencil_ops,
1855                    clear_value: (0.0, 0),
1856                    depth_read_only: false,
1857                    stencil_read_only: false,
1858                }),
1859                multiview_mask: self.multiview_mask,
1860                timestamp_writes: None,
1861                occlusion_query_set: None,
1862            };
1863            unsafe {
1864                raw.begin_render_pass(&desc)
1865                    .map_err(|e| device.handle_hal_error(e))?;
1866                raw.end_render_pass();
1867            }
1868        }
1869
1870        Ok(())
1871    }
1872}
1873
1874fn check_transient_attachment_ops<V>(load_op: LoadOp<V>, store_op: StoreOp) -> bool {
1875    matches!(
1876        (load_op, store_op),
1877        (LoadOp::Clear(_) | LoadOp::DontCare(_), StoreOp::Discard)
1878    )
1879}
1880
1881impl CommandEncoder {
1882    fn begin_render_pass_inner(
1883        self: &Arc<Self>,
1884        desc: ResolvedRenderPassDescriptor<'_>,
1885    ) -> (RenderPass, Option<CommandEncoderError>) {
1886        use EncoderStateError as SErr;
1887
1888        fn fill_arc_desc(
1889            desc: ResolvedRenderPassDescriptor<'_>,
1890            arc_desc: &mut ArcRenderPassDescriptor,
1891            device: &Device,
1892        ) -> Result<(), RenderPassErrorInner> {
1893            device.check_is_valid()?;
1894
1895            let max_color_attachments = device.limits.max_color_attachments as usize;
1896            if desc.color_attachments.len() > max_color_attachments {
1897                return Err(RenderPassErrorInner::ColorAttachment(
1898                    ColorAttachmentError::TooMany {
1899                        given: desc.color_attachments.len(),
1900                        limit: max_color_attachments,
1901                    },
1902                ));
1903            }
1904
1905            for color_attachment in desc.color_attachments.iter() {
1906                if let Some(RenderPassColorAttachment {
1907                    view,
1908                    depth_slice,
1909                    resolve_target,
1910                    load_op,
1911                    store_op,
1912                }) = color_attachment
1913                {
1914                    view.check_valid()?;
1915                    view.same_device(device)?;
1916                    if matches!(*load_op, LoadOp::DontCare(..))
1917                        && device
1918                            .instance_flags
1919                            .contains(InstanceFlags::STRICT_WEBGPU_COMPLIANCE)
1920                    {
1921                        return Err(RenderPassErrorInner::ColorAttachment(
1922                            ColorAttachmentError::LoadOpDontCareUnderStrictWebgpuCompliance,
1923                        ));
1924                    }
1925
1926                    if view
1927                        .desc
1928                        .usage
1929                        .contains(TextureUsages::TRANSIENT_ATTACHMENT)
1930                        && !check_transient_attachment_ops(*load_op, *store_op)
1931                    {
1932                        return Err(RenderPassErrorInner::ColorAttachment(
1933                            ColorAttachmentError::InvalidTransientAttachmentOp((
1934                                *load_op, *store_op,
1935                            )),
1936                        ));
1937                    }
1938
1939                    let resolve_target = if let Some(resolve_target) = resolve_target {
1940                        resolve_target.check_valid()?;
1941                        resolve_target.same_device(device)?;
1942
1943                        Some(resolve_target)
1944                    } else {
1945                        None
1946                    };
1947
1948                    arc_desc
1949                        .color_attachments
1950                        .push(Some(RenderPassColorAttachment {
1951                            view: Arc::clone(view),
1952                            depth_slice: *depth_slice,
1953                            resolve_target: resolve_target.map(Arc::clone),
1954                            load_op: *load_op,
1955                            store_op: *store_op,
1956                        }));
1957                } else {
1958                    arc_desc.color_attachments.push(None);
1959                }
1960            }
1961
1962            // https://gpuweb.github.io/gpuweb/#abstract-opdef-gpurenderpassdepthstencilattachment-gpurenderpassdepthstencilattachment-valid-usage
1963            arc_desc.depth_stencil_attachment = if let Some(depth_stencil_attachment) =
1964                desc.depth_stencil_attachment
1965            {
1966                let view = depth_stencil_attachment.view;
1967                view.check_valid()?;
1968                view.same_device(device)?;
1969
1970                let format = view.desc.format;
1971                if !format.is_depth_stencil_format() {
1972                    return Err(RenderPassErrorInner::InvalidAttachment(
1973                        AttachmentError::InvalidDepthStencilAttachmentFormat(view.desc.format),
1974                    ));
1975                }
1976
1977                #[allow(
1978                    clippy::collapsible_match,
1979                    reason = "Match guards change which attachment error is returned."
1980                )]
1981                if view
1982                    .desc
1983                    .usage
1984                    .contains(TextureUsages::TRANSIENT_ATTACHMENT)
1985                {
1986                    // We raise errors here for transient depth/stencil attachments if they
1987                    // are read only, or use unsupported ops. `resolve` (called below)
1988                    // validates that operations are specified iff the attachment is not
1989                    // read-only.
1990                    if format.has_depth_aspect() {
1991                        match depth_stencil_attachment.depth {
1992                            PassChannel {
1993                                load_op: Some(load_op),
1994                                store_op: Some(store_op),
1995                                read_only: _,
1996                            } => {
1997                                if !check_transient_attachment_ops(load_op, store_op) {
1998                                    return Err(RenderPassErrorInner::InvalidAttachment(
1999                                        AttachmentError::InvalidTransientDepthAttachmentOps((
2000                                            load_op, store_op,
2001                                        )),
2002                                    ));
2003                                }
2004                            }
2005                            PassChannel {
2006                                read_only: true, ..
2007                            } => {
2008                                return Err(RenderPassErrorInner::InvalidAttachment(
2009                                    AttachmentError::ReadOnlyTransientDepthAttachment,
2010                                ))
2011                            }
2012                            _ => {}
2013                        }
2014                    }
2015
2016                    if format.has_stencil_aspect() {
2017                        match depth_stencil_attachment.stencil {
2018                            PassChannel {
2019                                load_op: Some(load_op),
2020                                store_op: Some(store_op),
2021                                read_only: _,
2022                            } => {
2023                                if !check_transient_attachment_ops(load_op, store_op) {
2024                                    return Err(RenderPassErrorInner::InvalidAttachment(
2025                                        AttachmentError::InvalidTransientStencilAttachmentOps((
2026                                            load_op, store_op,
2027                                        )),
2028                                    ));
2029                                }
2030                            }
2031                            PassChannel {
2032                                read_only: true, ..
2033                            } => {
2034                                return Err(RenderPassErrorInner::InvalidAttachment(
2035                                    AttachmentError::ReadOnlyTransientStencilAttachment,
2036                                ))
2037                            }
2038                            _ => {}
2039                        }
2040                    }
2041                }
2042
2043                Some(ResolvedRenderPassDepthStencilAttachment {
2044                    view,
2045                    depth: if format.has_depth_aspect() {
2046                        depth_stencil_attachment
2047                            .depth
2048                            .resolve(device.instance_flags, |clear| {
2049                                if let Some(clear) = clear {
2050                                    // If this.depthLoadOp is "clear", this.depthClearValue must be provided and must be between 0.0 and 1.0, inclusive.
2051                                    if !(0.0..=1.0).contains(&clear) {
2052                                        Err(AttachmentError::ClearValueOutOfRange(clear))
2053                                    } else {
2054                                        Ok(clear)
2055                                    }
2056                                } else {
2057                                    Err(AttachmentError::NoClearValue)
2058                                }
2059                            })?
2060                    } else {
2061                        if depth_stencil_attachment.depth.load_op.is_some()
2062                            || depth_stencil_attachment.depth.store_op.is_some()
2063                        {
2064                            return Err(RenderPassErrorInner::InvalidAttachment(
2065                                AttachmentError::DepthOpsWithoutAspect {
2066                                    format,
2067                                    ops: (
2068                                        depth_stencil_attachment.depth.load_op,
2069                                        depth_stencil_attachment.depth.store_op,
2070                                    ),
2071                                },
2072                            ));
2073                        }
2074                        ResolvedPassChannel::ReadOnly
2075                    },
2076                    stencil: if format.has_stencil_aspect() {
2077                        depth_stencil_attachment.stencil.resolve(
2078                            device.instance_flags,
2079                            |clear| {
2080                                Ok(convert_stencil_value(
2081                                    clear.unwrap_or_default(),
2082                                    Some(format),
2083                                ))
2084                            },
2085                        )?
2086                    } else {
2087                        if depth_stencil_attachment.stencil.load_op.is_some()
2088                            || depth_stencil_attachment.stencil.store_op.is_some()
2089                        {
2090                            return Err(RenderPassErrorInner::InvalidAttachment(
2091                                AttachmentError::StencilOpsWithoutAspect {
2092                                    format,
2093                                    ops: (
2094                                        depth_stencil_attachment.stencil.load_op,
2095                                        depth_stencil_attachment.stencil.store_op,
2096                                    ),
2097                                },
2098                            ));
2099                        }
2100                        ResolvedPassChannel::ReadOnly
2101                    },
2102                })
2103            } else {
2104                None
2105            };
2106
2107            arc_desc.timestamp_writes = desc
2108                .timestamp_writes
2109                .map(|tw| {
2110                    CommandEncoder::validate_pass_timestamp_writes::<RenderPassErrorInner>(
2111                        device, &tw,
2112                    )
2113                })
2114                .transpose()?;
2115
2116            arc_desc.occlusion_query_set =
2117                if let Some(occlusion_query_set) = desc.occlusion_query_set {
2118                    occlusion_query_set.check_is_valid()?;
2119                    occlusion_query_set.same_device(device)?;
2120
2121                    if !matches!(occlusion_query_set.desc.ty, wgt::QueryType::Occlusion) {
2122                        return Err(QueryUseError::IncompatibleType {
2123                            set_type: occlusion_query_set.desc.ty.into(),
2124                            query_type: super::SimplifiedQueryType::Occlusion,
2125                        }
2126                        .into());
2127                    }
2128
2129                    Some(occlusion_query_set)
2130                } else {
2131                    None
2132                };
2133
2134            arc_desc.multiview_mask = desc.multiview_mask;
2135
2136            Ok(())
2137        }
2138
2139        let scope = PassErrorScope::Pass;
2140        let mut cmd_buf_data = self.data.lock();
2141
2142        match cmd_buf_data.lock_encoder() {
2143            Ok(()) => {
2144                drop(cmd_buf_data);
2145                let label = desc.label.clone();
2146                let mut arc_desc = ArcRenderPassDescriptor {
2147                    label: &label,
2148                    timestamp_writes: None,
2149                    color_attachments: ArrayVec::new(),
2150                    depth_stencil_attachment: None,
2151                    occlusion_query_set: None,
2152                    multiview_mask: None,
2153                };
2154                match fill_arc_desc(desc, &mut arc_desc, &self.device) {
2155                    Ok(()) => (RenderPass::new(self.clone(), arc_desc), None),
2156                    Err(err) => (
2157                        RenderPass::new_invalid(self.clone(), &label, err.map_pass_err(scope)),
2158                        None,
2159                    ),
2160                }
2161            }
2162            Err(err @ SErr::Locked) => {
2163                // Attempting to open a new pass while the encoder is locked
2164                // invalidates the encoder, but does not generate a validation
2165                // error.
2166                cmd_buf_data.invalidate(err.clone());
2167                drop(cmd_buf_data);
2168                (
2169                    RenderPass::new_invalid(self.clone(), &desc.label, err.map_pass_err(scope)),
2170                    None,
2171                )
2172            }
2173            Err(err @ (SErr::Ended | SErr::Submitted)) => {
2174                // Attempting to open a new pass after the encode has ended
2175                // generates an immediate validation error.
2176                drop(cmd_buf_data);
2177                (
2178                    RenderPass::new_invalid(
2179                        self.clone(),
2180                        &desc.label,
2181                        err.clone().map_pass_err(scope),
2182                    ),
2183                    Some(err.into()),
2184                )
2185            }
2186            Err(err @ SErr::Invalid) => {
2187                // Passes can be opened even on an invalid encoder. Such passes
2188                // are even valid, but since there's no visible side-effect of
2189                // the pass being valid and there's no point in storing recorded
2190                // commands that will ultimately be discarded, we open an
2191                // invalid pass to save that work.
2192                drop(cmd_buf_data);
2193                (
2194                    RenderPass::new_invalid(self.clone(), &desc.label, err.map_pass_err(scope)),
2195                    None,
2196                )
2197            }
2198            Err(SErr::Unlocked) => {
2199                unreachable!("lock_encoder cannot fail due to the encoder being unlocked")
2200            }
2201        }
2202    }
2203
2204    pub fn begin_render_pass(
2205        self: &Arc<Self>,
2206        desc: ResolvedRenderPassDescriptor<'_>,
2207    ) -> RenderPass {
2208        let (pass, err) = self.begin_render_pass_inner(desc);
2209        if let Some(err) = err {
2210            self.device
2211                .handle_error(err, pass.label(), "CommandEncoder::begin_render_pass");
2212        }
2213        pass
2214    }
2215}
2216
2217impl RenderPass {
2218    fn end_inner(&mut self) -> Result<(), EncoderStateError> {
2219        profiling::scope!(
2220            "CommandEncoder::run_render_pass {}",
2221            self.base.label.as_deref().unwrap_or("")
2222        );
2223
2224        let cmd_enc = self.parent.take().ok_or(EncoderStateError::Ended)?;
2225        let mut cmd_buf_data = cmd_enc.data.lock();
2226
2227        cmd_buf_data.unlock_encoder()?;
2228
2229        let base = self.base.take();
2230
2231        if let Err(RenderPassError { inner, scope: _ }) = &base {
2232            if let RenderPassErrorInner::EncoderState(
2233                err @ (EncoderStateError::Locked | EncoderStateError::Ended),
2234            ) = inner.as_ref()
2235            {
2236                // Most encoding errors are detected and raised within `finish()`.
2237                //
2238                // However, we raise a validation error here if the pass was opened
2239                // within another pass, or on a finished encoder. The latter is
2240                // particularly important, because in that case reporting errors via
2241                // `CommandEncoder::finish` is not possible.
2242                return Err(err.clone());
2243            }
2244        }
2245
2246        cmd_buf_data.push_with(|| -> Result<_, RenderPassError> {
2247            Ok(ArcCommand::RunRenderPass {
2248                pass: base?,
2249                color_attachments: SmallVec::from(self.color_attachments.as_slice()),
2250                depth_stencil_attachment: self.depth_stencil_attachment.take(),
2251                timestamp_writes: self.timestamp_writes.take(),
2252                occlusion_query_set: self.occlusion_query_set.take(),
2253                multiview_mask: self.multiview_mask,
2254            })
2255        })
2256    }
2257
2258    pub fn end(&mut self) {
2259        if let Err(err) = self.end_inner() {
2260            self.device
2261                .handle_error(err, self.label(), "RenderPass::end");
2262        }
2263    }
2264}
2265
2266pub(super) fn encode_render_pass(
2267    parent_state: &mut EncodingState<InnerCommandEncoder>,
2268    mut base: BasePass<ArcRenderCommand, Infallible>,
2269    color_attachments: ColorAttachments<Arc<TextureView>>,
2270    mut depth_stencil_attachment: Option<
2271        ResolvedRenderPassDepthStencilAttachment<Arc<TextureView>>,
2272    >,
2273    mut timestamp_writes: Option<PassTimestampWrites>,
2274    occlusion_query_set: Option<Arc<QuerySet>>,
2275    multiview_mask: Option<NonZeroU32>,
2276) -> Result<(), RenderPassError> {
2277    let pass_scope = PassErrorScope::Pass;
2278
2279    let device = parent_state.device;
2280
2281    let mut indirect_draw_validation_batcher = crate::indirect_validation::DrawBatcher::new();
2282
2283    // We automatically keep extending command buffers over time, and because
2284    // we want to insert a command buffer _before_ what we're about to record,
2285    // we need to make sure to close the previous one.
2286    parent_state
2287        .raw_encoder
2288        .close_if_open()
2289        .map_pass_err(pass_scope)?;
2290    let raw_encoder = parent_state
2291        .raw_encoder
2292        .open_pass(base.label.as_deref())
2293        .map_pass_err(pass_scope)?;
2294
2295    let (scope, pending_discard_init_fixups, mut pending_query_resets) = {
2296        let mut pending_query_resets = QueryResetMap::new();
2297        let mut pending_discard_init_fixups = SurfacesInDiscardState::new();
2298
2299        let info = RenderPassInfo::start(
2300            device,
2301            hal_label(base.label.as_deref(), device.instance_flags),
2302            &color_attachments,
2303            depth_stencil_attachment.take(),
2304            timestamp_writes.take(),
2305            // Still needed down the line.
2306            // TODO(wumpf): by restructuring the code, we could get rid of some of this Arc clone.
2307            occlusion_query_set.clone(),
2308            raw_encoder,
2309            parent_state.tracker,
2310            parent_state.texture_memory_actions,
2311            &mut pending_query_resets,
2312            &mut pending_discard_init_fixups,
2313            parent_state.snatch_guard,
2314            parent_state.query_set_writes,
2315            multiview_mask,
2316        )
2317        .map_pass_err(pass_scope)?;
2318
2319        let indices = &device.tracker_indices;
2320        parent_state
2321            .tracker
2322            .buffers
2323            .set_size(indices.buffers.size());
2324        parent_state
2325            .tracker
2326            .textures
2327            .set_size(indices.textures.size());
2328
2329        let mut debug_scope_depth = 0;
2330
2331        let mut state = State {
2332            pipeline_flags: PipelineFlags::empty(),
2333            blend_constant: OptionalState::Unused,
2334            stencil_reference: 0,
2335            pipeline: None,
2336            index: IndexState::default(),
2337            vertex: VertexState::default(),
2338
2339            info,
2340
2341            pass: pass::PassState {
2342                base: EncodingState {
2343                    device,
2344                    raw_encoder,
2345                    tracker: parent_state.tracker,
2346                    buffer_memory_init_actions: parent_state.buffer_memory_init_actions,
2347                    texture_memory_actions: parent_state.texture_memory_actions,
2348                    as_actions: parent_state.as_actions,
2349                    temp_resources: parent_state.temp_resources,
2350                    indirect_draw_validation_resources: parent_state
2351                        .indirect_draw_validation_resources,
2352                    snatch_guard: parent_state.snatch_guard,
2353                    debug_scope_depth: &mut debug_scope_depth,
2354                    query_set_writes: parent_state.query_set_writes,
2355                    deferred_query_set_resolves: parent_state.deferred_query_set_resolves,
2356                },
2357                pending_discard_init_fixups,
2358                scope: device.new_usage_scope(),
2359                binder: Binder::new(),
2360
2361                temp_offsets: Vec::new(),
2362                dynamic_offset_count: 0,
2363
2364                string_offset: 0,
2365
2366                immediate_state: ImmediateState::default(),
2367            },
2368
2369            active_occlusion_query: None,
2370            active_pipeline_statistics_query: None,
2371        };
2372
2373        for command in base.commands.drain(..) {
2374            match command {
2375                ArcRenderCommand::SetBindGroup {
2376                    index,
2377                    num_dynamic_offsets,
2378                    bind_group,
2379                } => {
2380                    let scope = PassErrorScope::SetBindGroup;
2381                    pass::set_bind_group::<RenderPassErrorInner>(
2382                        &mut state.pass,
2383                        device,
2384                        &base.dynamic_offsets,
2385                        index,
2386                        num_dynamic_offsets,
2387                        bind_group,
2388                        true,
2389                    )
2390                    .map_pass_err(scope)?;
2391                }
2392                ArcRenderCommand::SetPipeline(pipeline) => {
2393                    let scope = PassErrorScope::SetPipelineRender;
2394                    set_pipeline(&mut state, device, pipeline).map_pass_err(scope)?;
2395                }
2396                ArcRenderCommand::SetIndexBuffer {
2397                    buffer,
2398                    index_format,
2399                    offset,
2400                    size,
2401                } => {
2402                    let scope = PassErrorScope::SetIndexBuffer;
2403                    set_index_buffer(&mut state, device, buffer, index_format, offset, size)
2404                        .map_pass_err(scope)?;
2405                }
2406                ArcRenderCommand::SetVertexBuffer {
2407                    slot,
2408                    buffer,
2409                    offset,
2410                    size,
2411                } => {
2412                    let scope = PassErrorScope::SetVertexBuffer;
2413                    set_vertex_buffer(&mut state, device, slot, buffer, offset, size)
2414                        .map_pass_err(scope)?;
2415                }
2416                ArcRenderCommand::SetBlendConstant(ref color) => {
2417                    set_blend_constant(&mut state, color);
2418                }
2419                ArcRenderCommand::SetStencilReference(value) => {
2420                    set_stencil_reference(&mut state, value);
2421                }
2422                ArcRenderCommand::SetViewport {
2423                    rect,
2424                    depth_min,
2425                    depth_max,
2426                } => {
2427                    let scope = PassErrorScope::SetViewport;
2428                    set_viewport(&mut state, rect, depth_min, depth_max).map_pass_err(scope)?;
2429                }
2430                ArcRenderCommand::SetImmediate { offset, data } => {
2431                    let scope = PassErrorScope::SetImmediate;
2432                    state
2433                        .pass
2434                        .immediate_state
2435                        .set_immediates::<RenderPassErrorInner>(
2436                            &state.pass.base.device.limits,
2437                            offset,
2438                            &data,
2439                        )
2440                        .map_pass_err(scope)?;
2441                }
2442                ArcRenderCommand::SetScissor(rect) => {
2443                    let scope = PassErrorScope::SetScissorRect;
2444                    set_scissor(&mut state, rect).map_pass_err(scope)?;
2445                }
2446                ArcRenderCommand::Draw {
2447                    vertex_count,
2448                    instance_count,
2449                    first_vertex,
2450                    first_instance,
2451                } => {
2452                    let scope = PassErrorScope::Draw {
2453                        kind: DrawKind::Draw,
2454                        family: DrawCommandFamily::Draw,
2455                    };
2456                    draw(
2457                        &mut state,
2458                        vertex_count,
2459                        instance_count,
2460                        first_vertex,
2461                        first_instance,
2462                    )
2463                    .map_pass_err(scope)?;
2464                }
2465                ArcRenderCommand::DrawIndexed {
2466                    index_count,
2467                    instance_count,
2468                    first_index,
2469                    base_vertex,
2470                    first_instance,
2471                } => {
2472                    let scope = PassErrorScope::Draw {
2473                        kind: DrawKind::Draw,
2474                        family: DrawCommandFamily::DrawIndexed,
2475                    };
2476                    draw_indexed(
2477                        &mut state,
2478                        index_count,
2479                        instance_count,
2480                        first_index,
2481                        base_vertex,
2482                        first_instance,
2483                    )
2484                    .map_pass_err(scope)?;
2485                }
2486                ArcRenderCommand::DrawMeshTasks {
2487                    group_count_x,
2488                    group_count_y,
2489                    group_count_z,
2490                } => {
2491                    let scope = PassErrorScope::Draw {
2492                        kind: DrawKind::Draw,
2493                        family: DrawCommandFamily::DrawMeshTasks,
2494                    };
2495                    draw_mesh_tasks(&mut state, group_count_x, group_count_y, group_count_z)
2496                        .map_pass_err(scope)?;
2497                }
2498                ArcRenderCommand::DrawIndirect {
2499                    buffer,
2500                    offset,
2501                    count,
2502                    family,
2503
2504                    vertex_or_index_limit: _,
2505                    instance_limit: _,
2506                } => {
2507                    let scope = PassErrorScope::Draw {
2508                        kind: if count != 1 {
2509                            DrawKind::MultiDrawIndirect
2510                        } else {
2511                            DrawKind::DrawIndirect
2512                        },
2513                        family,
2514                    };
2515                    multi_draw_indirect(
2516                        &mut state,
2517                        &mut indirect_draw_validation_batcher,
2518                        device,
2519                        buffer,
2520                        offset,
2521                        count,
2522                        family,
2523                    )
2524                    .map_pass_err(scope)?;
2525                }
2526                ArcRenderCommand::MultiDrawIndirectCount {
2527                    buffer,
2528                    offset,
2529                    count_buffer,
2530                    count_buffer_offset,
2531                    max_count,
2532                    family,
2533                } => {
2534                    let scope = PassErrorScope::Draw {
2535                        kind: DrawKind::MultiDrawIndirectCount,
2536                        family,
2537                    };
2538                    multi_draw_indirect_count(
2539                        &mut state,
2540                        device,
2541                        buffer,
2542                        offset,
2543                        count_buffer,
2544                        count_buffer_offset,
2545                        max_count,
2546                        family,
2547                    )
2548                    .map_pass_err(scope)?;
2549                }
2550                ArcRenderCommand::PushDebugGroup { color: _, len } => {
2551                    pass::push_debug_group(&mut state.pass, &base.string_data, len);
2552                }
2553                ArcRenderCommand::PopDebugGroup => {
2554                    let scope = PassErrorScope::PopDebugGroup;
2555                    pass::pop_debug_group::<RenderPassErrorInner>(&mut state.pass)
2556                        .map_pass_err(scope)?;
2557                }
2558                ArcRenderCommand::InsertDebugMarker { color: _, len } => {
2559                    pass::insert_debug_marker(&mut state.pass, &base.string_data, len);
2560                }
2561                ArcRenderCommand::WriteTimestamp {
2562                    query_set,
2563                    query_index,
2564                } => {
2565                    let scope = PassErrorScope::WriteTimestamp;
2566                    pass::write_timestamp::<RenderPassErrorInner>(
2567                        &mut state.pass,
2568                        device,
2569                        Some(&mut pending_query_resets),
2570                        query_set,
2571                        query_index,
2572                    )
2573                    .map_pass_err(scope)?;
2574                }
2575                ArcRenderCommand::BeginOcclusionQuery { query_index } => {
2576                    api_log!("RenderPass::begin_occlusion_query {query_index}");
2577                    let scope = PassErrorScope::BeginOcclusionQuery;
2578
2579                    let query_set = occlusion_query_set
2580                        .clone()
2581                        .ok_or(RenderPassErrorInner::MissingOcclusionQuerySet)
2582                        .map_pass_err(scope)?;
2583
2584                    validate_and_begin_occlusion_query(
2585                        query_set,
2586                        state.pass.base.raw_encoder,
2587                        &mut state.pass.base.tracker.query_sets,
2588                        query_index,
2589                        Some(&mut pending_query_resets),
2590                        &mut state.active_occlusion_query,
2591                        state.pass.base.snatch_guard,
2592                    )
2593                    .map_pass_err(scope)?;
2594                }
2595                ArcRenderCommand::EndOcclusionQuery => {
2596                    api_log!("RenderPass::end_occlusion_query");
2597                    let scope = PassErrorScope::EndOcclusionQuery;
2598
2599                    end_occlusion_query(
2600                        state.pass.base.raw_encoder,
2601                        &mut state.active_occlusion_query,
2602                        state.pass.base.snatch_guard,
2603                        state.pass.base.query_set_writes,
2604                    )
2605                    .map_pass_err(scope)?;
2606                }
2607                ArcRenderCommand::BeginPipelineStatisticsQuery {
2608                    query_set,
2609                    query_index,
2610                } => {
2611                    api_log!(
2612                        "RenderPass::begin_pipeline_statistics_query {query_index} {}",
2613                        query_set.error_ident()
2614                    );
2615                    let scope = PassErrorScope::BeginPipelineStatisticsQuery;
2616
2617                    validate_and_begin_pipeline_statistics_query(
2618                        query_set,
2619                        state.pass.base.raw_encoder,
2620                        &mut state.pass.base.tracker.query_sets,
2621                        device,
2622                        query_index,
2623                        Some(&mut pending_query_resets),
2624                        &mut state.active_pipeline_statistics_query,
2625                        state.pass.base.snatch_guard,
2626                    )
2627                    .map_pass_err(scope)?;
2628                }
2629                ArcRenderCommand::EndPipelineStatisticsQuery => {
2630                    api_log!("RenderPass::end_pipeline_statistics_query");
2631                    let scope = PassErrorScope::EndPipelineStatisticsQuery;
2632
2633                    end_pipeline_statistics_query(
2634                        state.pass.base.raw_encoder,
2635                        &mut state.active_pipeline_statistics_query,
2636                        state.pass.base.snatch_guard,
2637                        state.pass.base.query_set_writes,
2638                    )
2639                    .map_pass_err(scope)?;
2640                }
2641                ArcRenderCommand::ExecuteBundle(bundle) => {
2642                    let scope = PassErrorScope::ExecuteBundle;
2643                    execute_bundle(
2644                        &mut state,
2645                        &mut indirect_draw_validation_batcher,
2646                        device,
2647                        bundle,
2648                    )
2649                    .map_pass_err(scope)?;
2650                }
2651            }
2652        }
2653
2654        if *state.pass.base.debug_scope_depth > 0 {
2655            Err(
2656                RenderPassErrorInner::DebugGroupError(DebugGroupError::MissingPop)
2657                    .map_pass_err(pass_scope),
2658            )?;
2659        }
2660        if state.active_occlusion_query.is_some() {
2661            Err(RenderPassErrorInner::QueryUse(QueryUseError::MissingEnd {
2662                query_type: super::SimplifiedQueryType::Occlusion,
2663            })
2664            .map_pass_err(pass_scope))?;
2665        }
2666        if state.active_pipeline_statistics_query.is_some() {
2667            Err(RenderPassErrorInner::QueryUse(QueryUseError::MissingEnd {
2668                query_type: super::SimplifiedQueryType::PipelineStatistics,
2669            })
2670            .map_pass_err(pass_scope))?;
2671        }
2672
2673        state
2674            .info
2675            .finish(
2676                device,
2677                state.pass.base.raw_encoder,
2678                state.pass.base.snatch_guard,
2679                &mut state.pass.scope,
2680                device.instance_flags,
2681            )
2682            .map_pass_err(pass_scope)?;
2683
2684        let trackers = state.pass.scope;
2685
2686        let pending_discard_init_fixups = state.pass.pending_discard_init_fixups;
2687
2688        parent_state.raw_encoder.close().map_pass_err(pass_scope)?;
2689        (trackers, pending_discard_init_fixups, pending_query_resets)
2690    };
2691
2692    let encoder = &mut parent_state.raw_encoder;
2693    let tracker = &mut parent_state.tracker;
2694
2695    {
2696        let transit = encoder
2697            .open_pass(hal_label(
2698                Some("(wgpu internal) Pre Pass"),
2699                device.instance_flags,
2700            ))
2701            .map_pass_err(pass_scope)?;
2702
2703        // If this pass reads any surfaces that were discarded by a previous
2704        // pass in the same command buffer, initialize them.
2705        fixup_discarded_surfaces(
2706            pending_discard_init_fixups.into_iter(),
2707            transit,
2708            &mut tracker.textures,
2709            device,
2710            parent_state.snatch_guard,
2711        );
2712
2713        pending_query_resets
2714            .reset_queries(transit, parent_state.snatch_guard)
2715            .map_pass_err(pass_scope)?;
2716
2717        CommandEncoder::insert_barriers_from_scope(
2718            transit,
2719            tracker,
2720            &scope,
2721            parent_state.snatch_guard,
2722        );
2723
2724        if let Some(ref indirect_validation) = device.indirect_validation {
2725            indirect_validation
2726                .draw
2727                .inject_validation_pass(
2728                    device,
2729                    parent_state.snatch_guard,
2730                    parent_state.indirect_draw_validation_resources,
2731                    parent_state.temp_resources,
2732                    transit,
2733                    indirect_draw_validation_batcher,
2734                )
2735                .map_pass_err(pass_scope)?;
2736        }
2737
2738        // Backends may have deferred setup work for the pass's indirect
2739        // multi-draws (e.g. Metal indirect-command-buffer generation); encode
2740        // it after indirect validation so it reads validated draw arguments.
2741        unsafe { transit.encode_deferred_multi_draws() };
2742    }
2743
2744    encoder.close_and_swap().map_pass_err(pass_scope)?;
2745
2746    Ok(())
2747}
2748
2749fn set_pipeline(
2750    state: &mut State,
2751    device: &Arc<Device>,
2752    pipeline: Arc<RenderPipeline>,
2753) -> Result<(), RenderPassErrorInner> {
2754    api_log!("RenderPass::set_pipeline {}", pipeline.error_ident());
2755
2756    state.pipeline = Some(pipeline.clone());
2757
2758    let pipeline = state
2759        .pass
2760        .base
2761        .tracker
2762        .render_pipelines
2763        .insert_single(pipeline)
2764        .clone();
2765
2766    pipeline.same_device(device)?;
2767
2768    state
2769        .info
2770        .context
2771        .check_compatible(&pipeline.pass_context, pipeline.as_ref())
2772        .map_err(RenderCommandError::IncompatiblePipelineTargets)?;
2773
2774    state.pipeline_flags = pipeline.flags;
2775
2776    if pipeline.flags.contains(PipelineFlags::WRITES_DEPTH) && state.info.is_depth_read_only {
2777        return Err(RenderCommandError::IncompatibleDepthAccess(pipeline.error_ident()).into());
2778    }
2779    if pipeline.flags.contains(PipelineFlags::WRITES_STENCIL) && state.info.is_stencil_read_only {
2780        return Err(RenderCommandError::IncompatibleStencilAccess(pipeline.error_ident()).into());
2781    }
2782
2783    state
2784        .blend_constant
2785        .require(pipeline.flags.contains(PipelineFlags::BLEND_CONSTANT));
2786
2787    unsafe {
2788        state
2789            .pass
2790            .base
2791            .raw_encoder
2792            .set_render_pipeline(pipeline.raw()?);
2793    }
2794
2795    if pipeline.flags.contains(PipelineFlags::STENCIL_REFERENCE) {
2796        unsafe {
2797            state
2798                .pass
2799                .base
2800                .raw_encoder
2801                .set_stencil_reference(state.stencil_reference);
2802        }
2803    }
2804
2805    // Rebind resource
2806    pass::change_pipeline_layout::<RenderPassErrorInner>(&mut state.pass, pipeline.layout()?)?;
2807
2808    // Update vertex buffer limits.
2809    state.vertex.update_limits(&pipeline.vertex_steps);
2810    Ok(())
2811}
2812
2813// This function is duplicative of `bundle::set_index_buffer`.
2814fn set_index_buffer(
2815    state: &mut State,
2816    device: &Arc<Device>,
2817    buffer: Arc<Buffer>,
2818    index_format: IndexFormat,
2819    offset: u64,
2820    size: Option<BufferAddress>,
2821) -> Result<(), RenderPassErrorInner> {
2822    api_log!("RenderPass::set_index_buffer {}", buffer.error_ident());
2823
2824    state
2825        .pass
2826        .scope
2827        .buffers
2828        .merge_single(&buffer, wgt::BufferUses::INDEX)?;
2829
2830    buffer.same_device(device)?;
2831
2832    buffer.check_usage(BufferUsages::INDEX)?;
2833
2834    if !offset.is_multiple_of(u64::from(index_format.byte_size())) {
2835        return Err(RenderCommandError::UnalignedIndexBuffer {
2836            offset,
2837            alignment: index_format.byte_size() as usize,
2838        }
2839        .into());
2840    }
2841
2842    let range = buffer
2843        .resolve_vertex_or_index_binding_range(offset, size)
2844        .map_err(RenderCommandError::from)?;
2845
2846    let raw = buffer.try_raw(state.pass.base.snatch_guard)?;
2847
2848    state.index.update_buffer(range.clone(), index_format);
2849
2850    state.pass.base.buffer_memory_init_actions.extend(
2851        buffer.initialization_status.read().create_action(
2852            &buffer,
2853            range.clone(),
2854            MemoryInitKind::NeedsInitializedMemory,
2855        ),
2856    );
2857
2858    unsafe {
2859        // SAFETY: The binding range was validated by `resolve_vertex_or_index_binding_range`.
2860        hal::DynCommandEncoder::set_index_buffer(
2861            state.pass.base.raw_encoder,
2862            hal::BufferBinding::new_unchecked(raw, range.start, range.end - range.start),
2863            index_format,
2864        );
2865    }
2866    Ok(())
2867}
2868
2869// This function is duplicative of `render::set_vertex_buffer`.
2870fn set_vertex_buffer(
2871    state: &mut State,
2872    device: &Arc<Device>,
2873    slot: u32,
2874    buffer: Option<Arc<Buffer>>,
2875    offset: u64,
2876    size: Option<BufferAddress>,
2877) -> Result<(), RenderPassErrorInner> {
2878    if let Some(ref buffer) = buffer {
2879        api_log!(
2880            "RenderPass::set_vertex_buffer {slot} {}",
2881            buffer.error_ident()
2882        );
2883    } else {
2884        api_log!("RenderPass::set_vertex_buffer {slot} None");
2885    }
2886
2887    let max_vertex_buffers = state.pass.base.device.limits.max_vertex_buffers;
2888    if slot >= max_vertex_buffers {
2889        return Err(RenderCommandError::VertexBufferIndexOutOfRange {
2890            index: slot,
2891            max: max_vertex_buffers,
2892        }
2893        .into());
2894    }
2895
2896    if let Some(buffer) = buffer {
2897        buffer.same_device(device)?;
2898        buffer.check_usage(BufferUsages::VERTEX)?;
2899
2900        if !offset.is_multiple_of(wgt::VERTEX_ALIGNMENT) {
2901            return Err(RenderCommandError::UnalignedVertexBuffer { slot, offset }.into());
2902        }
2903        let range = buffer
2904            .resolve_vertex_or_index_binding_range(offset, size)
2905            .map_err(RenderCommandError::from)?;
2906
2907        state
2908            .pass
2909            .scope
2910            .buffers
2911            .merge_single(&buffer, wgt::BufferUses::VERTEX)?;
2912
2913        state.pass.base.buffer_memory_init_actions.extend(
2914            buffer.initialization_status.read().create_action(
2915                &buffer,
2916                range.clone(),
2917                MemoryInitKind::NeedsInitializedMemory,
2918            ),
2919        );
2920
2921        state
2922            .vertex
2923            .set_buffer(slot as usize, buffer, range.clone());
2924        if let Some(pipeline) = state.pipeline.as_ref() {
2925            state.vertex.update_limits(&pipeline.vertex_steps);
2926        }
2927    } else {
2928        if offset != 0 {
2929            return Err(RenderCommandError::from(
2930                crate::binding_model::BindingError::UnbindingVertexBufferOffsetNotZero {
2931                    slot,
2932                    offset,
2933                },
2934            )
2935            .into());
2936        }
2937        match size {
2938            Some(size) if size != 0 => {
2939                return Err(RenderCommandError::from(
2940                    crate::binding_model::BindingError::UnbindingVertexBufferSizeNotZero {
2941                        slot,
2942                        size,
2943                    },
2944                )
2945                .into());
2946            }
2947            _ => {}
2948        }
2949
2950        state.vertex.clear_buffer(slot as usize);
2951        if let Some(pipeline) = state.pipeline.as_ref() {
2952            state.vertex.update_limits(&pipeline.vertex_steps);
2953        }
2954    }
2955
2956    Ok(())
2957}
2958
2959fn set_blend_constant(state: &mut State, color: &Color) {
2960    api_log!("RenderPass::set_blend_constant");
2961
2962    state.blend_constant = OptionalState::Set;
2963    let array = [
2964        color.r as f32,
2965        color.g as f32,
2966        color.b as f32,
2967        color.a as f32,
2968    ];
2969    unsafe {
2970        state.pass.base.raw_encoder.set_blend_constants(&array);
2971    }
2972}
2973
2974fn set_stencil_reference(state: &mut State, value: u32) {
2975    api_log!("RenderPass::set_stencil_reference {value}");
2976
2977    state.stencil_reference = value;
2978    if state
2979        .pipeline_flags
2980        .contains(PipelineFlags::STENCIL_REFERENCE)
2981    {
2982        unsafe {
2983            state.pass.base.raw_encoder.set_stencil_reference(value);
2984        }
2985    }
2986}
2987
2988fn set_viewport(
2989    state: &mut State,
2990    rect: Rect<f32>,
2991    depth_min: f32,
2992    depth_max: f32,
2993) -> Result<(), RenderPassErrorInner> {
2994    api_log!("RenderPass::set_viewport {rect:?}");
2995
2996    if rect.w < 0.0
2997        || rect.h < 0.0
2998        || rect.w > state.pass.base.device.limits.max_texture_dimension_2d as f32
2999        || rect.h > state.pass.base.device.limits.max_texture_dimension_2d as f32
3000    {
3001        return Err(RenderCommandError::InvalidViewportRectSize {
3002            w: rect.w,
3003            h: rect.h,
3004            max: state.pass.base.device.limits.max_texture_dimension_2d,
3005        }
3006        .into());
3007    }
3008
3009    let max_viewport_range = state.pass.base.device.limits.max_texture_dimension_2d as f32 * 2.0;
3010
3011    if rect.x < -max_viewport_range
3012        || rect.y < -max_viewport_range
3013        || rect.x + rect.w > max_viewport_range - 1.0
3014        || rect.y + rect.h > max_viewport_range - 1.0
3015    {
3016        return Err(RenderCommandError::InvalidViewportRectPosition {
3017            rect,
3018            min: -max_viewport_range,
3019            max: max_viewport_range - 1.0,
3020        }
3021        .into());
3022    }
3023    if !(0.0..=1.0).contains(&depth_min)
3024        || !(0.0..=1.0).contains(&depth_max)
3025        || depth_min > depth_max
3026    {
3027        return Err(RenderCommandError::InvalidViewportDepth(depth_min, depth_max).into());
3028    }
3029    let r = hal::Rect {
3030        x: rect.x,
3031        y: rect.y,
3032        w: rect.w,
3033        h: rect.h,
3034    };
3035    unsafe {
3036        state
3037            .pass
3038            .base
3039            .raw_encoder
3040            .set_viewport(&r, depth_min..depth_max);
3041    }
3042    Ok(())
3043}
3044
3045fn set_scissor(state: &mut State, rect: Rect<u32>) -> Result<(), RenderPassErrorInner> {
3046    api_log!("RenderPass::set_scissor_rect {rect:?}");
3047
3048    if rect.x.saturating_add(rect.w) > state.info.extent.width
3049        || rect.y.saturating_add(rect.h) > state.info.extent.height
3050    {
3051        return Err(RenderCommandError::InvalidScissorRect(rect, state.info.extent).into());
3052    }
3053    let r = hal::Rect {
3054        x: rect.x,
3055        y: rect.y,
3056        w: rect.w,
3057        h: rect.h,
3058    };
3059    unsafe {
3060        state.pass.base.raw_encoder.set_scissor_rect(&r);
3061    }
3062    Ok(())
3063}
3064
3065fn draw(
3066    state: &mut State,
3067    vertex_count: u32,
3068    instance_count: u32,
3069    first_vertex: u32,
3070    first_instance: u32,
3071) -> Result<(), RenderPassErrorInner> {
3072    api_log!("RenderPass::draw {vertex_count} {instance_count} {first_vertex} {first_instance}");
3073
3074    state.is_ready(DrawCommandFamily::Draw)?;
3075    state.flush_vertex_buffers()?;
3076    state.flush_bindings()?;
3077    state.flush_immediates();
3078
3079    state
3080        .vertex
3081        .limits
3082        .validate_vertex_limit(first_vertex, vertex_count)?;
3083    state
3084        .vertex
3085        .limits
3086        .validate_instance_limit(first_instance, instance_count)?;
3087
3088    unsafe {
3089        if instance_count > 0 && vertex_count > 0 {
3090            state.pass.base.raw_encoder.draw(
3091                first_vertex,
3092                vertex_count,
3093                first_instance,
3094                instance_count,
3095            );
3096        }
3097    }
3098    Ok(())
3099}
3100
3101fn draw_indexed(
3102    state: &mut State,
3103    index_count: u32,
3104    instance_count: u32,
3105    first_index: u32,
3106    base_vertex: i32,
3107    first_instance: u32,
3108) -> Result<(), RenderPassErrorInner> {
3109    api_log!("RenderPass::draw_indexed {index_count} {instance_count} {first_index} {base_vertex} {first_instance}");
3110
3111    state.is_ready(DrawCommandFamily::DrawIndexed)?;
3112    state.flush_vertex_buffers()?;
3113    state.flush_bindings()?;
3114    state.flush_immediates();
3115
3116    let last_index = first_index as u64 + index_count as u64;
3117    let index_limit = state.index.limit;
3118    if last_index > index_limit {
3119        return Err(DrawError::IndexBeyondLimit {
3120            last_index,
3121            index_limit,
3122        }
3123        .into());
3124    }
3125    state
3126        .vertex
3127        .limits
3128        .validate_instance_limit(first_instance, instance_count)?;
3129
3130    unsafe {
3131        if instance_count > 0 && index_count > 0 {
3132            state.pass.base.raw_encoder.draw_indexed(
3133                first_index,
3134                index_count,
3135                base_vertex,
3136                first_instance,
3137                instance_count,
3138            );
3139        }
3140    }
3141    Ok(())
3142}
3143
3144fn draw_mesh_tasks(
3145    state: &mut State,
3146    group_count_x: u32,
3147    group_count_y: u32,
3148    group_count_z: u32,
3149) -> Result<(), RenderPassErrorInner> {
3150    api_log!("RenderPass::draw_mesh_tasks {group_count_x} {group_count_y} {group_count_z}");
3151
3152    state.is_ready(DrawCommandFamily::DrawMeshTasks)?;
3153
3154    state.flush_bindings()?;
3155    state.flush_immediates();
3156    validate_mesh_draw_multiview(state.pass.base.device, state.info.multiview_mask)?;
3157
3158    let limits = &state.pass.base.device.limits;
3159    let (groups_size_limit, max_groups) = if state.pipeline.as_ref().unwrap().has_task_shader {
3160        (
3161            limits.max_task_workgroups_per_dimension,
3162            limits.max_task_workgroup_total_count,
3163        )
3164    } else {
3165        (
3166            limits.max_mesh_workgroups_per_dimension,
3167            limits.max_mesh_workgroup_total_count,
3168        )
3169    };
3170
3171    let total_count = WorkgroupSizeCheck {
3172        dimensions: &[group_count_x, group_count_y, group_count_z],
3173        per_dimension_limits: &[groups_size_limit, groups_size_limit, groups_size_limit],
3174        per_dimension_limits_desc: "max_task_mesh_workgroups_per_dimension",
3175
3176        total_limit: max_groups,
3177        total_limit_desc: "max_task_mesh_workgroup_total_count",
3178    }
3179    .check_and_compute_total_invocations()
3180    .map_err(|err| RenderPassErrorInner::Draw(err.into()))?;
3181
3182    unsafe {
3183        if total_count > 0 {
3184            state.pass.base.raw_encoder.draw_mesh_tasks(
3185                group_count_x,
3186                group_count_y,
3187                group_count_z,
3188            );
3189        }
3190    }
3191    Ok(())
3192}
3193
3194fn multi_draw_indirect(
3195    state: &mut State,
3196    indirect_draw_validation_batcher: &mut crate::indirect_validation::DrawBatcher,
3197    device: &Arc<Device>,
3198    indirect_buffer: Arc<Buffer>,
3199    offset: u64,
3200    count: u32,
3201    family: DrawCommandFamily,
3202) -> Result<(), RenderPassErrorInner> {
3203    api_log!(
3204        "RenderPass::draw_indirect (family:{family:?}) {} {offset} {count:?}",
3205        indirect_buffer.error_ident()
3206    );
3207
3208    state.is_ready(family)?;
3209    state.flush_vertex_buffers()?;
3210    state.flush_bindings()?;
3211    state.flush_immediates();
3212
3213    if family == DrawCommandFamily::DrawMeshTasks {
3214        validate_mesh_draw_multiview(state.pass.base.device, state.info.multiview_mask)?;
3215    }
3216
3217    state
3218        .pass
3219        .base
3220        .device
3221        .require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
3222
3223    indirect_buffer.same_device(device)?;
3224    indirect_buffer.check_usage(BufferUsages::INDIRECT)?;
3225    indirect_buffer.check_destroyed(state.pass.base.snatch_guard)?;
3226
3227    if !offset.is_multiple_of(4) {
3228        return Err(RenderCommandError::UnalignedIndirectBufferOffset(offset).into());
3229    }
3230
3231    let stride = get_src_stride_of_indirect_args(family);
3232    let args_size = match stride.checked_mul(u64::from(count)) {
3233        Some(sz) if sz <= indirect_buffer.size && indirect_buffer.size - sz >= offset => sz,
3234        args_size => {
3235            return Err(RenderCommandError::IndirectBufferOverrun {
3236                count,
3237                offset,
3238                args_size: args_size.unwrap_or(u64::MAX),
3239                buffer_size: indirect_buffer.size,
3240            }
3241            .into());
3242        }
3243    };
3244
3245    let validate_indirect = state.pass.base.device.indirect_validation.is_some()
3246        && family != DrawCommandFamily::DrawMeshTasks;
3247    state.pass.scope.buffers.merge_single(
3248        &indirect_buffer,
3249        if validate_indirect {
3250            wgt::BufferUses::STORAGE_READ_ONLY
3251        } else {
3252            wgt::BufferUses::INDIRECT
3253        },
3254    )?;
3255
3256    if count == 0 {
3257        return Ok(());
3258    }
3259
3260    state.pass.base.buffer_memory_init_actions.extend(
3261        indirect_buffer.initialization_status.read().create_action(
3262            &indirect_buffer,
3263            offset..offset + args_size,
3264            MemoryInitKind::NeedsInitializedMemory,
3265        ),
3266    );
3267
3268    fn draw(
3269        raw_encoder: &mut dyn hal::DynCommandEncoder,
3270        family: DrawCommandFamily,
3271        indirect_buffer: &dyn hal::DynBuffer,
3272        offset: u64,
3273        count: u32,
3274    ) {
3275        match family {
3276            DrawCommandFamily::Draw => unsafe {
3277                raw_encoder.draw_indirect(indirect_buffer, offset, count);
3278            },
3279            DrawCommandFamily::DrawIndexed => unsafe {
3280                raw_encoder.draw_indexed_indirect(indirect_buffer, offset, count);
3281            },
3282            DrawCommandFamily::DrawMeshTasks => unsafe {
3283                raw_encoder.draw_mesh_tasks_indirect(indirect_buffer, offset, count);
3284            },
3285        }
3286    }
3287
3288    if validate_indirect {
3289        struct DrawData {
3290            buffer_index: usize,
3291            offset: u64,
3292            count: u32,
3293        }
3294
3295        struct DrawContext<'a> {
3296            raw_encoder: &'a mut dyn hal::DynCommandEncoder,
3297            device: &'a Device,
3298
3299            indirect_draw_validation_resources: &'a mut crate::indirect_validation::DrawResources,
3300            indirect_draw_validation_batcher: &'a mut crate::indirect_validation::DrawBatcher,
3301
3302            indirect_buffer: Arc<Buffer>,
3303            family: DrawCommandFamily,
3304            vertex_or_index_limit: u64,
3305            instance_limit: u64,
3306        }
3307
3308        impl<'a> DrawContext<'a> {
3309            fn add(&mut self, offset: u64) -> Result<DrawData, DeviceError> {
3310                let (dst_resource_index, dst_offset) = self.indirect_draw_validation_batcher.add(
3311                    self.indirect_draw_validation_resources,
3312                    self.device,
3313                    &self.indirect_buffer,
3314                    offset,
3315                    self.family,
3316                    self.vertex_or_index_limit,
3317                    self.instance_limit,
3318                )?;
3319                Ok(DrawData {
3320                    buffer_index: dst_resource_index,
3321                    offset: dst_offset,
3322                    count: 1,
3323                })
3324            }
3325            fn draw(&mut self, draw_data: DrawData) {
3326                let dst_buffer = self
3327                    .indirect_draw_validation_resources
3328                    .get_dst_buffer(draw_data.buffer_index);
3329                draw(
3330                    self.raw_encoder,
3331                    self.family,
3332                    dst_buffer,
3333                    draw_data.offset,
3334                    draw_data.count,
3335                );
3336            }
3337        }
3338
3339        let mut draw_ctx = DrawContext {
3340            raw_encoder: state.pass.base.raw_encoder,
3341            device: state.pass.base.device,
3342            indirect_draw_validation_resources: state.pass.base.indirect_draw_validation_resources,
3343            indirect_draw_validation_batcher,
3344            indirect_buffer,
3345            family,
3346            vertex_or_index_limit: if family == DrawCommandFamily::DrawIndexed {
3347                state.index.limit
3348            } else {
3349                state.vertex.limits.vertex_limit
3350            },
3351            instance_limit: state.vertex.limits.instance_limit,
3352        };
3353
3354        let mut current_draw_data = draw_ctx.add(offset)?;
3355
3356        for i in 1..count {
3357            let draw_data = draw_ctx.add(offset + stride * i as u64)?;
3358
3359            if draw_data.buffer_index == current_draw_data.buffer_index {
3360                #[cfg(debug_assertions)]
3361                {
3362                    let dst_stride =
3363                        get_dst_stride_of_indirect_args(state.pass.base.device.backend(), family);
3364                    debug_assert_eq!(
3365                        draw_data.offset,
3366                        current_draw_data.offset + dst_stride * current_draw_data.count as u64
3367                    );
3368                }
3369                current_draw_data.count += 1;
3370            } else {
3371                draw_ctx.draw(current_draw_data);
3372                current_draw_data = draw_data;
3373            }
3374        }
3375
3376        draw_ctx.draw(current_draw_data);
3377    } else {
3378        draw(
3379            state.pass.base.raw_encoder,
3380            family,
3381            indirect_buffer.try_raw(state.pass.base.snatch_guard)?,
3382            offset,
3383            count,
3384        );
3385    };
3386
3387    Ok(())
3388}
3389
3390fn multi_draw_indirect_count(
3391    state: &mut State,
3392    device: &Arc<Device>,
3393    indirect_buffer: Arc<Buffer>,
3394    offset: u64,
3395    count_buffer: Arc<Buffer>,
3396    count_buffer_offset: u64,
3397    max_count: u32,
3398    family: DrawCommandFamily,
3399) -> Result<(), RenderPassErrorInner> {
3400    api_log!(
3401        "RenderPass::multi_draw_indirect_count (family:{family:?}) {} {offset} {} {count_buffer_offset:?} {max_count:?}",
3402        indirect_buffer.error_ident(),
3403        count_buffer.error_ident()
3404    );
3405
3406    state.is_ready(family)?;
3407    state.flush_vertex_buffers()?;
3408    state.flush_bindings()?;
3409    state.flush_immediates();
3410
3411    if family == DrawCommandFamily::DrawMeshTasks {
3412        validate_mesh_draw_multiview(state.pass.base.device, state.info.multiview_mask)?;
3413    }
3414
3415    let stride = get_src_stride_of_indirect_args(family);
3416
3417    state
3418        .pass
3419        .base
3420        .device
3421        .require_features(wgt::Features::MULTI_DRAW_INDIRECT_COUNT)?;
3422    state
3423        .pass
3424        .base
3425        .device
3426        .require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
3427
3428    indirect_buffer.same_device(device)?;
3429    count_buffer.same_device(device)?;
3430
3431    state
3432        .pass
3433        .scope
3434        .buffers
3435        .merge_single(&indirect_buffer, wgt::BufferUses::INDIRECT)?;
3436
3437    indirect_buffer.check_usage(BufferUsages::INDIRECT)?;
3438    let indirect_raw = indirect_buffer.try_raw(state.pass.base.snatch_guard)?;
3439
3440    state
3441        .pass
3442        .scope
3443        .buffers
3444        .merge_single(&count_buffer, wgt::BufferUses::INDIRECT)?;
3445
3446    count_buffer.check_usage(BufferUsages::INDIRECT)?;
3447    let count_raw = count_buffer.try_raw(state.pass.base.snatch_guard)?;
3448
3449    if !offset.is_multiple_of(4) {
3450        return Err(RenderCommandError::UnalignedIndirectBufferOffset(offset).into());
3451    }
3452
3453    let args_size = match stride.checked_mul(u64::from(max_count)) {
3454        Some(sz) if sz <= indirect_buffer.size && indirect_buffer.size - sz >= offset => sz,
3455        args_size => {
3456            return Err(RenderCommandError::IndirectBufferOverrun {
3457                count: 1,
3458                offset,
3459                args_size: args_size.unwrap_or(u64::MAX),
3460                buffer_size: indirect_buffer.size,
3461            }
3462            .into());
3463        }
3464    };
3465
3466    state.pass.base.buffer_memory_init_actions.extend(
3467        indirect_buffer.initialization_status.read().create_action(
3468            &indirect_buffer,
3469            offset..offset + args_size,
3470            MemoryInitKind::NeedsInitializedMemory,
3471        ),
3472    );
3473
3474    let begin_count_offset = count_buffer_offset;
3475    let count_bytes = 4;
3476    if count_buffer.size < count_bytes || count_buffer.size - count_bytes < count_buffer_offset {
3477        return Err(RenderPassErrorInner::IndirectCountBufferOverrun {
3478            begin_count_offset,
3479            count_bytes: 4,
3480            count_buffer_size: count_buffer.size,
3481        });
3482    }
3483    state.pass.base.buffer_memory_init_actions.extend(
3484        count_buffer.initialization_status.read().create_action(
3485            &count_buffer,
3486            count_buffer_offset..count_buffer_offset + count_bytes,
3487            MemoryInitKind::NeedsInitializedMemory,
3488        ),
3489    );
3490
3491    match family {
3492        DrawCommandFamily::Draw => unsafe {
3493            state.pass.base.raw_encoder.draw_indirect_count(
3494                indirect_raw,
3495                offset,
3496                count_raw,
3497                count_buffer_offset,
3498                max_count,
3499            );
3500        },
3501        DrawCommandFamily::DrawIndexed => unsafe {
3502            state.pass.base.raw_encoder.draw_indexed_indirect_count(
3503                indirect_raw,
3504                offset,
3505                count_raw,
3506                count_buffer_offset,
3507                max_count,
3508            );
3509        },
3510        DrawCommandFamily::DrawMeshTasks => unsafe {
3511            state.pass.base.raw_encoder.draw_mesh_tasks_indirect_count(
3512                indirect_raw,
3513                offset,
3514                count_raw,
3515                count_buffer_offset,
3516                max_count,
3517            );
3518        },
3519    }
3520    Ok(())
3521}
3522
3523fn execute_bundle(
3524    state: &mut State,
3525    indirect_draw_validation_batcher: &mut crate::indirect_validation::DrawBatcher,
3526    device: &Arc<Device>,
3527    bundle: Arc<RenderBundle>,
3528) -> Result<(), RenderPassErrorInner> {
3529    api_log!("RenderPass::execute_bundle {}", bundle.error_ident());
3530
3531    let bundle = state.pass.base.tracker.bundles.insert_single(bundle);
3532
3533    let bundle_state = bundle.state()?;
3534    bundle.same_device(device)?;
3535
3536    state
3537        .info
3538        .context
3539        .check_compatible(&bundle_state.context, bundle.as_ref())
3540        .map_err(RenderPassErrorInner::IncompatibleBundleTargets)?;
3541
3542    if (state.info.is_depth_read_only && !bundle.is_depth_read_only)
3543        || (state.info.is_stencil_read_only && !bundle.is_stencil_read_only)
3544    {
3545        return Err(
3546            RenderPassErrorInner::IncompatibleBundleReadOnlyDepthStencil {
3547                pass_depth: state.info.is_depth_read_only,
3548                pass_stencil: state.info.is_stencil_read_only,
3549                bundle_depth: bundle.is_depth_read_only,
3550                bundle_stencil: bundle.is_stencil_read_only,
3551            },
3552        );
3553    }
3554
3555    state.pass.base.buffer_memory_init_actions.extend(
3556        bundle
3557            .buffer_memory_init_actions
3558            .iter()
3559            .filter_map(|action| {
3560                action
3561                    .buffer
3562                    .initialization_status
3563                    .read()
3564                    .check_action(action)
3565            }),
3566    );
3567    for action in bundle.texture_memory_init_actions.iter() {
3568        state.pass.pending_discard_init_fixups.extend(
3569            state
3570                .pass
3571                .base
3572                .texture_memory_actions
3573                .register_init_action(action, None),
3574        );
3575    }
3576
3577    unsafe {
3578        bundle.execute(
3579            state.pass.base.raw_encoder,
3580            state.pass.base.indirect_draw_validation_resources,
3581            indirect_draw_validation_batcher,
3582            state.pass.base.snatch_guard,
3583        )
3584    }
3585    .map_err(|e| match e {
3586        ExecutionError::Device(e) => RenderPassErrorInner::Device(e),
3587        ExecutionError::DestroyedResource(e) => {
3588            RenderPassErrorInner::RenderCommand(RenderCommandError::DestroyedResource(e))
3589        }
3590        ExecutionError::InvalidResource(e) => {
3591            RenderPassErrorInner::RenderCommand(RenderCommandError::InvalidResource(e))
3592        }
3593    })?;
3594
3595    unsafe {
3596        state.pass.scope.merge_render_bundle(&bundle_state.used)?;
3597    };
3598    state.reset_bundle();
3599    Ok(())
3600}
3601
3602// Recording a render pass.
3603//
3604// The only error that should be returned from these methods is
3605// `EncoderStateError::Ended`, when the pass has already ended and an immediate
3606// validation error is raised.
3607//
3608// All other errors should be stored in the pass for later reporting when
3609// `CommandEncoder.finish()` is called.
3610//
3611// The `pass_try!` macro should be used to handle errors appropriately. Note
3612// that the `pass_try!` and `pass_base!` macros may return early from the
3613// function that invokes them, like the `?` operator.
3614impl RenderPass {
3615    fn set_bind_group_inner(
3616        &mut self,
3617        index: u32,
3618        bind_group: Option<Arc<BindGroup>>,
3619        offsets: &[DynamicOffset],
3620    ) -> Result<(), PassStateError> {
3621        let scope = PassErrorScope::SetBindGroup;
3622
3623        // This statement will return an error if the pass is ended. It's
3624        // important the error check comes before the early-out for
3625        // `set_and_check_redundant`.
3626        let base = pass_base!(self, scope);
3627
3628        if self.current_bind_groups.set_and_check_redundant(
3629            &bind_group,
3630            index,
3631            &mut base.dynamic_offsets,
3632            offsets,
3633        ) {
3634            return Ok(());
3635        }
3636
3637        let bind_group = if let Some(bind_group) = bind_group {
3638            pass_try!(base, scope, bind_group.check_is_valid());
3639            Some(bind_group)
3640        } else {
3641            None
3642        };
3643
3644        base.commands.push(ArcRenderCommand::SetBindGroup {
3645            index,
3646            num_dynamic_offsets: offsets.len(),
3647            bind_group,
3648        });
3649
3650        Ok(())
3651    }
3652
3653    pub fn set_bind_group(
3654        &mut self,
3655        index: u32,
3656        bind_group: Option<Arc<BindGroup>>,
3657        offsets: &[DynamicOffset],
3658    ) {
3659        if let Err(err) = self.set_bind_group_inner(index, bind_group, offsets) {
3660            self.device
3661                .handle_error(err, self.label(), "RenderPass::set_bind_group");
3662        }
3663    }
3664
3665    fn set_pipeline_inner(&mut self, pipeline: Arc<RenderPipeline>) -> Result<(), PassStateError> {
3666        let scope = PassErrorScope::SetPipelineRender;
3667
3668        let redundant = self.current_pipeline.set_and_check_redundant(&pipeline);
3669
3670        // This statement will return an error if the pass is ended.
3671        // Its important the error check comes before the early-out for `redundant`.
3672        let base = pass_base!(self, scope);
3673
3674        if redundant {
3675            return Ok(());
3676        }
3677
3678        pass_try!(base, scope, pipeline.check_valid());
3679
3680        base.commands.push(ArcRenderCommand::SetPipeline(pipeline));
3681
3682        Ok(())
3683    }
3684
3685    pub fn set_pipeline(&mut self, pipeline: Arc<RenderPipeline>) {
3686        if let Err(err) = self.set_pipeline_inner(pipeline) {
3687            self.device
3688                .handle_error(err, self.label(), "RenderPass::set_pipeline");
3689        }
3690    }
3691
3692    fn set_index_buffer_inner(
3693        &mut self,
3694        buffer: Arc<Buffer>,
3695        index_format: IndexFormat,
3696        offset: BufferAddress,
3697        size: Option<BufferAddress>,
3698    ) -> Result<(), PassStateError> {
3699        let scope = PassErrorScope::SetIndexBuffer;
3700        let base = pass_base!(self, scope);
3701
3702        pass_try!(base, scope, buffer.check_is_valid());
3703
3704        base.commands.push(ArcRenderCommand::SetIndexBuffer {
3705            buffer,
3706            index_format,
3707            offset,
3708            size,
3709        });
3710
3711        Ok(())
3712    }
3713
3714    pub fn set_index_buffer(
3715        &mut self,
3716        buffer: Arc<Buffer>,
3717        index_format: IndexFormat,
3718        offset: BufferAddress,
3719        size: Option<BufferAddress>,
3720    ) {
3721        if let Err(err) = self.set_index_buffer_inner(buffer, index_format, offset, size) {
3722            self.device
3723                .handle_error(err, self.label(), "RenderPass::set_index_buffer");
3724        }
3725    }
3726
3727    fn set_vertex_buffer_inner(
3728        &mut self,
3729        slot: u32,
3730        buffer: Option<Arc<Buffer>>,
3731        offset: BufferAddress,
3732        size: Option<BufferAddress>,
3733    ) -> Result<(), PassStateError> {
3734        let scope = PassErrorScope::SetVertexBuffer;
3735        let base = pass_base!(self, scope);
3736
3737        let buffer = if let Some(buffer) = buffer {
3738            pass_try!(base, scope, buffer.check_is_valid());
3739            Some(buffer)
3740        } else {
3741            None
3742        };
3743
3744        base.commands.push(ArcRenderCommand::SetVertexBuffer {
3745            slot,
3746            buffer,
3747            offset,
3748            size,
3749        });
3750
3751        Ok(())
3752    }
3753
3754    pub fn set_vertex_buffer(
3755        &mut self,
3756        slot: u32,
3757        buffer: Option<Arc<Buffer>>,
3758        offset: BufferAddress,
3759        size: Option<BufferAddress>,
3760    ) {
3761        if let Err(err) = self.set_vertex_buffer_inner(slot, buffer, offset, size) {
3762            self.device
3763                .handle_error(err, self.label(), "RenderPass::set_vertex_buffer");
3764        }
3765    }
3766
3767    fn set_blend_constant_inner(&mut self, color: Color) -> Result<(), PassStateError> {
3768        let scope = PassErrorScope::SetBlendConstant;
3769        let base = pass_base!(self, scope);
3770
3771        base.commands
3772            .push(ArcRenderCommand::SetBlendConstant(color));
3773
3774        Ok(())
3775    }
3776
3777    pub fn set_blend_constant(&mut self, color: Color) {
3778        if let Err(err) = self.set_blend_constant_inner(color) {
3779            self.device
3780                .handle_error(err, self.label(), "RenderPass::set_blend_constant");
3781        }
3782    }
3783
3784    fn set_stencil_reference_inner(&mut self, value: u32) -> Result<(), PassStateError> {
3785        let scope = PassErrorScope::SetStencilReference;
3786        let base = pass_base!(self, scope);
3787        let value = convert_stencil_value(
3788            value,
3789            self.depth_stencil_attachment
3790                .as_ref()
3791                .map(|at| at.view.desc.format),
3792        );
3793        base.commands
3794            .push(ArcRenderCommand::SetStencilReference(value));
3795
3796        Ok(())
3797    }
3798
3799    pub fn set_stencil_reference(&mut self, value: u32) {
3800        if let Err(err) = self.set_stencil_reference_inner(value) {
3801            self.device
3802                .handle_error(err, self.label(), "RenderPass::set_stencil_reference");
3803        }
3804    }
3805
3806    fn set_viewport_inner(
3807        &mut self,
3808        x: f32,
3809        y: f32,
3810        w: f32,
3811        h: f32,
3812        depth_min: f32,
3813        depth_max: f32,
3814    ) -> Result<(), PassStateError> {
3815        let scope = PassErrorScope::SetViewport;
3816        let base = pass_base!(self, scope);
3817
3818        base.commands.push(ArcRenderCommand::SetViewport {
3819            rect: Rect { x, y, w, h },
3820            depth_min,
3821            depth_max,
3822        });
3823
3824        Ok(())
3825    }
3826
3827    pub fn set_viewport(&mut self, x: f32, y: f32, w: f32, h: f32, depth_min: f32, depth_max: f32) {
3828        if let Err(err) = self.set_viewport_inner(x, y, w, h, depth_min, depth_max) {
3829            self.device
3830                .handle_error(err, self.label(), "RenderPass::set_viewport");
3831        }
3832    }
3833
3834    fn set_scissor_rect_inner(
3835        &mut self,
3836        x: u32,
3837        y: u32,
3838        w: u32,
3839        h: u32,
3840    ) -> Result<(), PassStateError> {
3841        let scope = PassErrorScope::SetScissorRect;
3842        let base = pass_base!(self, scope);
3843
3844        base.commands
3845            .push(ArcRenderCommand::SetScissor(Rect { x, y, w, h }));
3846
3847        Ok(())
3848    }
3849
3850    pub fn set_scissor_rect(&mut self, x: u32, y: u32, w: u32, h: u32) {
3851        if let Err(err) = self.set_scissor_rect_inner(x, y, w, h) {
3852            self.device
3853                .handle_error(err, self.label(), "RenderPass::set_scissor_rect");
3854        }
3855    }
3856
3857    fn set_immediates_inner(&mut self, offset: u32, data: &[u8]) -> Result<(), PassStateError> {
3858        let scope = PassErrorScope::SetImmediate;
3859        let base = pass_base!(self, scope);
3860
3861        pass_try!(
3862            base,
3863            scope,
3864            pass::validate_immediates_alignment(offset, data.len())
3865        );
3866
3867        base.commands.push(ArcRenderCommand::SetImmediate {
3868            offset,
3869            data: data
3870                .chunks_exact(size_of::<u32>())
3871                .map(|ck| u32::from_le_bytes(ck.try_into().unwrap()))
3872                .collect(),
3873        });
3874
3875        Ok(())
3876    }
3877
3878    pub fn set_immediates(&mut self, offset: u32, data: &[u8]) {
3879        if let Err(err) = self.set_immediates_inner(offset, data) {
3880            self.device
3881                .handle_error(err, self.label(), "RenderPass::set_immediates");
3882        }
3883    }
3884
3885    fn draw_inner(
3886        &mut self,
3887        vertex_count: u32,
3888        instance_count: u32,
3889        first_vertex: u32,
3890        first_instance: u32,
3891    ) -> Result<(), PassStateError> {
3892        let scope = PassErrorScope::Draw {
3893            kind: DrawKind::Draw,
3894            family: DrawCommandFamily::Draw,
3895        };
3896        let base = pass_base!(self, scope);
3897
3898        base.commands.push(ArcRenderCommand::Draw {
3899            vertex_count,
3900            instance_count,
3901            first_vertex,
3902            first_instance,
3903        });
3904
3905        Ok(())
3906    }
3907
3908    pub fn draw(
3909        &mut self,
3910        vertex_count: u32,
3911        instance_count: u32,
3912        first_vertex: u32,
3913        first_instance: u32,
3914    ) {
3915        if let Err(err) =
3916            self.draw_inner(vertex_count, instance_count, first_vertex, first_instance)
3917        {
3918            self.device
3919                .handle_error(err, self.label(), "RenderPass::draw");
3920        }
3921    }
3922
3923    fn draw_indexed_inner(
3924        &mut self,
3925        index_count: u32,
3926        instance_count: u32,
3927        first_index: u32,
3928        base_vertex: i32,
3929        first_instance: u32,
3930    ) -> Result<(), PassStateError> {
3931        let scope = PassErrorScope::Draw {
3932            kind: DrawKind::Draw,
3933            family: DrawCommandFamily::DrawIndexed,
3934        };
3935        let base = pass_base!(self, scope);
3936
3937        base.commands.push(ArcRenderCommand::DrawIndexed {
3938            index_count,
3939            instance_count,
3940            first_index,
3941            base_vertex,
3942            first_instance,
3943        });
3944
3945        Ok(())
3946    }
3947
3948    pub fn draw_indexed(
3949        &mut self,
3950        index_count: u32,
3951        instance_count: u32,
3952        first_index: u32,
3953        base_vertex: i32,
3954        first_instance: u32,
3955    ) {
3956        if let Err(err) = self.draw_indexed_inner(
3957            index_count,
3958            instance_count,
3959            first_index,
3960            base_vertex,
3961            first_instance,
3962        ) {
3963            self.device
3964                .handle_error(err, self.label(), "RenderPass::draw_indexed");
3965        }
3966    }
3967
3968    fn draw_mesh_tasks_inner(
3969        &mut self,
3970        group_count_x: u32,
3971        group_count_y: u32,
3972        group_count_z: u32,
3973    ) -> Result<(), RenderPassError> {
3974        let scope = PassErrorScope::Draw {
3975            kind: DrawKind::Draw,
3976            family: DrawCommandFamily::DrawMeshTasks,
3977        };
3978        let base = pass_base!(self, scope);
3979
3980        base.commands.push(ArcRenderCommand::DrawMeshTasks {
3981            group_count_x,
3982            group_count_y,
3983            group_count_z,
3984        });
3985        Ok(())
3986    }
3987
3988    pub fn draw_mesh_tasks(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32) {
3989        if let Err(err) = self.draw_mesh_tasks_inner(group_count_x, group_count_y, group_count_z) {
3990            self.device
3991                .handle_error(err, self.label(), "RenderPass::draw_mesh_tasks");
3992        }
3993    }
3994
3995    fn draw_indirect_inner(
3996        &mut self,
3997        buffer: Arc<Buffer>,
3998        offset: BufferAddress,
3999    ) -> Result<(), PassStateError> {
4000        let scope = PassErrorScope::Draw {
4001            kind: DrawKind::DrawIndirect,
4002            family: DrawCommandFamily::Draw,
4003        };
4004        let base = pass_base!(self, scope);
4005
4006        pass_try!(base, scope, buffer.check_is_valid());
4007
4008        base.commands.push(ArcRenderCommand::DrawIndirect {
4009            buffer,
4010            offset,
4011            count: 1,
4012            family: DrawCommandFamily::Draw,
4013
4014            vertex_or_index_limit: None,
4015            instance_limit: None,
4016        });
4017
4018        Ok(())
4019    }
4020
4021    pub fn draw_indirect(&mut self, buffer: Arc<Buffer>, offset: BufferAddress) {
4022        if let Err(err) = self.draw_indirect_inner(buffer, offset) {
4023            self.device
4024                .handle_error(err, self.label(), "RenderPass::draw_indirect");
4025        }
4026    }
4027
4028    fn draw_indexed_indirect_inner(
4029        &mut self,
4030        buffer: Arc<Buffer>,
4031        offset: BufferAddress,
4032    ) -> Result<(), PassStateError> {
4033        let scope = PassErrorScope::Draw {
4034            kind: DrawKind::DrawIndirect,
4035            family: DrawCommandFamily::DrawIndexed,
4036        };
4037        let base = pass_base!(self, scope);
4038
4039        pass_try!(base, scope, buffer.check_is_valid());
4040
4041        base.commands.push(ArcRenderCommand::DrawIndirect {
4042            buffer,
4043            offset,
4044            count: 1,
4045            family: DrawCommandFamily::DrawIndexed,
4046
4047            vertex_or_index_limit: None,
4048            instance_limit: None,
4049        });
4050
4051        Ok(())
4052    }
4053
4054    pub fn draw_indexed_indirect(&mut self, buffer: Arc<Buffer>, offset: BufferAddress) {
4055        if let Err(err) = self.draw_indexed_indirect_inner(buffer, offset) {
4056            self.device
4057                .handle_error(err, self.label(), "RenderPass::draw_indexed_indirect");
4058        }
4059    }
4060
4061    fn draw_mesh_tasks_indirect_inner(
4062        &mut self,
4063        buffer: Arc<Buffer>,
4064        offset: BufferAddress,
4065    ) -> Result<(), RenderPassError> {
4066        let scope = PassErrorScope::Draw {
4067            kind: DrawKind::DrawIndirect,
4068            family: DrawCommandFamily::DrawMeshTasks,
4069        };
4070        let base = pass_base!(self, scope);
4071
4072        pass_try!(base, scope, buffer.check_is_valid());
4073
4074        base.commands.push(ArcRenderCommand::DrawIndirect {
4075            buffer,
4076            offset,
4077            count: 1,
4078            family: DrawCommandFamily::DrawMeshTasks,
4079
4080            vertex_or_index_limit: None,
4081            instance_limit: None,
4082        });
4083
4084        Ok(())
4085    }
4086
4087    pub fn draw_mesh_tasks_indirect(&mut self, buffer: Arc<Buffer>, offset: BufferAddress) {
4088        if let Err(err) = self.draw_mesh_tasks_indirect_inner(buffer, offset) {
4089            self.device
4090                .handle_error(err, self.label(), "RenderPass::draw_mesh_tasks_indirect");
4091        }
4092    }
4093
4094    fn multi_draw_indirect_inner(
4095        &mut self,
4096        buffer: Arc<Buffer>,
4097        offset: BufferAddress,
4098        count: u32,
4099    ) -> Result<(), PassStateError> {
4100        let scope = PassErrorScope::Draw {
4101            kind: DrawKind::MultiDrawIndirect,
4102            family: DrawCommandFamily::Draw,
4103        };
4104        let base = pass_base!(self, scope);
4105
4106        pass_try!(base, scope, buffer.check_is_valid());
4107
4108        base.commands.push(ArcRenderCommand::DrawIndirect {
4109            buffer,
4110            offset,
4111            count,
4112            family: DrawCommandFamily::Draw,
4113
4114            vertex_or_index_limit: None,
4115            instance_limit: None,
4116        });
4117
4118        Ok(())
4119    }
4120
4121    pub fn multi_draw_indirect(&mut self, buffer: Arc<Buffer>, offset: BufferAddress, count: u32) {
4122        if let Err(err) = self.multi_draw_indirect_inner(buffer, offset, count) {
4123            self.device
4124                .handle_error(err, self.label(), "RenderPass::multi_draw_indirect");
4125        }
4126    }
4127
4128    fn multi_draw_indexed_indirect_inner(
4129        &mut self,
4130        buffer: Arc<Buffer>,
4131        offset: BufferAddress,
4132        count: u32,
4133    ) -> Result<(), PassStateError> {
4134        let scope = PassErrorScope::Draw {
4135            kind: DrawKind::MultiDrawIndirect,
4136            family: DrawCommandFamily::DrawIndexed,
4137        };
4138        let base = pass_base!(self, scope);
4139
4140        pass_try!(base, scope, buffer.check_is_valid());
4141
4142        base.commands.push(ArcRenderCommand::DrawIndirect {
4143            buffer,
4144            offset,
4145            count,
4146            family: DrawCommandFamily::DrawIndexed,
4147
4148            vertex_or_index_limit: None,
4149            instance_limit: None,
4150        });
4151
4152        Ok(())
4153    }
4154
4155    pub fn multi_draw_indexed_indirect(
4156        &mut self,
4157        buffer: Arc<Buffer>,
4158        offset: BufferAddress,
4159        count: u32,
4160    ) {
4161        if let Err(err) = self.multi_draw_indexed_indirect_inner(buffer, offset, count) {
4162            self.device
4163                .handle_error(err, self.label(), "RenderPass::multi_draw_indexed_indirect");
4164        }
4165    }
4166
4167    fn multi_draw_mesh_tasks_indirect_inner(
4168        &mut self,
4169        buffer: Arc<Buffer>,
4170        offset: BufferAddress,
4171        count: u32,
4172    ) -> Result<(), RenderPassError> {
4173        let scope = PassErrorScope::Draw {
4174            kind: DrawKind::MultiDrawIndirect,
4175            family: DrawCommandFamily::DrawMeshTasks,
4176        };
4177        let base = pass_base!(self, scope);
4178
4179        pass_try!(base, scope, buffer.check_is_valid());
4180
4181        base.commands.push(ArcRenderCommand::DrawIndirect {
4182            buffer,
4183            offset,
4184            count,
4185            family: DrawCommandFamily::DrawMeshTasks,
4186
4187            vertex_or_index_limit: None,
4188            instance_limit: None,
4189        });
4190
4191        Ok(())
4192    }
4193
4194    pub fn multi_draw_mesh_tasks_indirect(
4195        &mut self,
4196        buffer: Arc<Buffer>,
4197        offset: BufferAddress,
4198        count: u32,
4199    ) {
4200        if let Err(err) = self.multi_draw_mesh_tasks_indirect_inner(buffer, offset, count) {
4201            self.device.handle_error(
4202                err,
4203                self.label(),
4204                "RenderPass::multi_draw_mesh_tasks_indirect",
4205            );
4206        }
4207    }
4208
4209    fn multi_draw_indirect_count_inner(
4210        &mut self,
4211        buffer: Arc<Buffer>,
4212        offset: BufferAddress,
4213        count_buffer: Arc<Buffer>,
4214        count_buffer_offset: BufferAddress,
4215        max_count: u32,
4216    ) -> Result<(), PassStateError> {
4217        let scope = PassErrorScope::Draw {
4218            kind: DrawKind::MultiDrawIndirectCount,
4219            family: DrawCommandFamily::Draw,
4220        };
4221        let base = pass_base!(self, scope);
4222        pass_try!(base, scope, buffer.check_is_valid());
4223        pass_try!(base, scope, count_buffer.check_is_valid());
4224
4225        base.commands
4226            .push(ArcRenderCommand::MultiDrawIndirectCount {
4227                buffer,
4228                offset,
4229                count_buffer,
4230                count_buffer_offset,
4231                max_count,
4232                family: DrawCommandFamily::Draw,
4233            });
4234
4235        Ok(())
4236    }
4237
4238    pub fn multi_draw_indirect_count(
4239        &mut self,
4240        buffer: Arc<Buffer>,
4241        offset: BufferAddress,
4242        count_buffer: Arc<Buffer>,
4243        count_buffer_offset: BufferAddress,
4244        max_count: u32,
4245    ) {
4246        if let Err(err) = self.multi_draw_indirect_count_inner(
4247            buffer,
4248            offset,
4249            count_buffer,
4250            count_buffer_offset,
4251            max_count,
4252        ) {
4253            self.device
4254                .handle_error(err, self.label(), "RenderPass::multi_draw_indirect_count");
4255        }
4256    }
4257
4258    fn multi_draw_indexed_indirect_count_inner(
4259        &mut self,
4260        buffer: Arc<Buffer>,
4261        offset: BufferAddress,
4262        count_buffer: Arc<Buffer>,
4263        count_buffer_offset: BufferAddress,
4264        max_count: u32,
4265    ) -> Result<(), PassStateError> {
4266        let scope = PassErrorScope::Draw {
4267            kind: DrawKind::MultiDrawIndirectCount,
4268            family: DrawCommandFamily::DrawIndexed,
4269        };
4270        let base = pass_base!(self, scope);
4271
4272        pass_try!(base, scope, buffer.check_is_valid());
4273        pass_try!(base, scope, count_buffer.check_is_valid());
4274
4275        base.commands
4276            .push(ArcRenderCommand::MultiDrawIndirectCount {
4277                buffer,
4278                offset,
4279                count_buffer,
4280                count_buffer_offset,
4281                max_count,
4282                family: DrawCommandFamily::DrawIndexed,
4283            });
4284
4285        Ok(())
4286    }
4287
4288    pub fn multi_draw_indexed_indirect_count(
4289        &mut self,
4290        buffer: Arc<Buffer>,
4291        offset: BufferAddress,
4292        count_buffer: Arc<Buffer>,
4293        count_buffer_offset: BufferAddress,
4294        max_count: u32,
4295    ) {
4296        if let Err(err) = self.multi_draw_indexed_indirect_count_inner(
4297            buffer,
4298            offset,
4299            count_buffer,
4300            count_buffer_offset,
4301            max_count,
4302        ) {
4303            self.device.handle_error(
4304                err,
4305                self.label(),
4306                "RenderPass::multi_draw_indexed_indirect_count",
4307            );
4308        }
4309    }
4310
4311    fn multi_draw_mesh_tasks_indirect_count_inner(
4312        &mut self,
4313        buffer: Arc<Buffer>,
4314        offset: BufferAddress,
4315        count_buffer: Arc<Buffer>,
4316        count_buffer_offset: BufferAddress,
4317        max_count: u32,
4318    ) -> Result<(), RenderPassError> {
4319        let scope = PassErrorScope::Draw {
4320            kind: DrawKind::MultiDrawIndirectCount,
4321            family: DrawCommandFamily::DrawMeshTasks,
4322        };
4323        let base = pass_base!(self, scope);
4324
4325        pass_try!(base, scope, buffer.check_is_valid());
4326        pass_try!(base, scope, count_buffer.check_is_valid());
4327
4328        base.commands
4329            .push(ArcRenderCommand::MultiDrawIndirectCount {
4330                buffer,
4331                offset,
4332                count_buffer,
4333                count_buffer_offset,
4334                max_count,
4335                family: DrawCommandFamily::DrawMeshTasks,
4336            });
4337
4338        Ok(())
4339    }
4340
4341    pub fn multi_draw_mesh_tasks_indirect_count(
4342        &mut self,
4343        buffer: Arc<Buffer>,
4344        offset: BufferAddress,
4345        count_buffer: Arc<Buffer>,
4346        count_buffer_offset: BufferAddress,
4347        max_count: u32,
4348    ) {
4349        if let Err(err) = self.multi_draw_mesh_tasks_indirect_count_inner(
4350            buffer,
4351            offset,
4352            count_buffer,
4353            count_buffer_offset,
4354            max_count,
4355        ) {
4356            self.device.handle_error(
4357                err,
4358                self.label(),
4359                "RenderPass::multi_draw_mesh_tasks_indirect_count",
4360            );
4361        }
4362    }
4363
4364    fn push_debug_group_inner(&mut self, label: &str, color: u32) -> Result<(), PassStateError> {
4365        let base = pass_base!(self, PassErrorScope::PushDebugGroup);
4366
4367        let bytes = label.as_bytes();
4368        base.string_data.extend_from_slice(bytes);
4369
4370        base.commands.push(ArcRenderCommand::PushDebugGroup {
4371            color,
4372            len: bytes.len(),
4373        });
4374
4375        Ok(())
4376    }
4377
4378    pub fn push_debug_group(&mut self, label: &str, color: u32) {
4379        if let Err(err) = self.push_debug_group_inner(label, color) {
4380            self.device
4381                .handle_error(err, self.label(), "RenderPass::push_debug_group");
4382        }
4383    }
4384
4385    fn pop_debug_group_inner(&mut self) -> Result<(), PassStateError> {
4386        let base = pass_base!(self, PassErrorScope::PopDebugGroup);
4387
4388        base.commands.push(ArcRenderCommand::PopDebugGroup);
4389
4390        Ok(())
4391    }
4392
4393    pub fn pop_debug_group(&mut self) {
4394        if let Err(err) = self.pop_debug_group_inner() {
4395            self.device
4396                .handle_error(err, self.label(), "RenderPass::pop_debug_group");
4397        }
4398    }
4399
4400    fn insert_debug_marker_inner(&mut self, label: &str, color: u32) -> Result<(), PassStateError> {
4401        let base = pass_base!(self, PassErrorScope::InsertDebugMarker);
4402
4403        let bytes = label.as_bytes();
4404        base.string_data.extend_from_slice(bytes);
4405
4406        base.commands.push(ArcRenderCommand::InsertDebugMarker {
4407            color,
4408            len: bytes.len(),
4409        });
4410
4411        Ok(())
4412    }
4413
4414    pub fn insert_debug_marker(&mut self, label: &str, color: u32) {
4415        if let Err(err) = self.insert_debug_marker_inner(label, color) {
4416            self.device
4417                .handle_error(err, self.label(), "RenderPass::insert_debug_marker");
4418        }
4419    }
4420
4421    fn write_timestamp_inner(
4422        &mut self,
4423        query_set: Arc<QuerySet>,
4424        query_index: u32,
4425    ) -> Result<(), PassStateError> {
4426        let scope = PassErrorScope::WriteTimestamp;
4427        let base = pass_base!(self, scope);
4428
4429        pass_try!(base, scope, query_set.check_is_valid());
4430        base.commands.push(ArcRenderCommand::WriteTimestamp {
4431            query_set,
4432            query_index,
4433        });
4434
4435        Ok(())
4436    }
4437
4438    pub fn write_timestamp(&mut self, query_set: Arc<QuerySet>, query_index: u32) {
4439        if let Err(err) = self.write_timestamp_inner(query_set, query_index) {
4440            self.device
4441                .handle_error(err, self.label(), "RenderPass::write_timestamp");
4442        }
4443    }
4444
4445    fn begin_occlusion_query_inner(&mut self, query_index: u32) -> Result<(), PassStateError> {
4446        let scope = PassErrorScope::BeginOcclusionQuery;
4447        let base = pass_base!(self, scope);
4448
4449        base.commands
4450            .push(ArcRenderCommand::BeginOcclusionQuery { query_index });
4451
4452        Ok(())
4453    }
4454
4455    pub fn begin_occlusion_query(&mut self, query_index: u32) {
4456        if let Err(err) = self.begin_occlusion_query_inner(query_index) {
4457            self.device
4458                .handle_error(err, self.label(), "RenderPass::begin_occlusion_query");
4459        }
4460    }
4461
4462    fn end_occlusion_query_inner(&mut self) -> Result<(), PassStateError> {
4463        let scope = PassErrorScope::EndOcclusionQuery;
4464        let base = pass_base!(self, scope);
4465
4466        base.commands.push(ArcRenderCommand::EndOcclusionQuery);
4467
4468        Ok(())
4469    }
4470
4471    pub fn end_occlusion_query(&mut self) {
4472        if let Err(err) = self.end_occlusion_query_inner() {
4473            self.device
4474                .handle_error(err, self.label(), "RenderPass::end_occlusion_query");
4475        }
4476    }
4477
4478    fn begin_pipeline_statistics_query_inner(
4479        &mut self,
4480        query_set: Arc<QuerySet>,
4481        query_index: u32,
4482    ) -> Result<(), PassStateError> {
4483        let scope = PassErrorScope::BeginPipelineStatisticsQuery;
4484        let base = pass_base!(self, scope);
4485
4486        pass_try!(base, scope, query_set.check_is_valid());
4487        base.commands
4488            .push(ArcRenderCommand::BeginPipelineStatisticsQuery {
4489                query_set,
4490                query_index,
4491            });
4492
4493        Ok(())
4494    }
4495
4496    pub fn begin_pipeline_statistics_query(&mut self, query_set: Arc<QuerySet>, query_index: u32) {
4497        if let Err(err) = self.begin_pipeline_statistics_query_inner(query_set, query_index) {
4498            self.device.handle_error(
4499                err,
4500                self.label(),
4501                "RenderPass::begin_pipeline_statistics_query",
4502            );
4503        }
4504    }
4505
4506    fn end_pipeline_statistics_query_inner(&mut self) -> Result<(), PassStateError> {
4507        let scope = PassErrorScope::EndPipelineStatisticsQuery;
4508        let base = pass_base!(self, scope);
4509
4510        base.commands
4511            .push(ArcRenderCommand::EndPipelineStatisticsQuery);
4512
4513        Ok(())
4514    }
4515
4516    pub fn end_pipeline_statistics_query(&mut self) {
4517        if let Err(err) = self.end_pipeline_statistics_query_inner() {
4518            self.device.handle_error(
4519                err,
4520                self.label(),
4521                "RenderPass::end_pipeline_statistics_query",
4522            );
4523        }
4524    }
4525
4526    fn execute_bundles_inner(
4527        &mut self,
4528        render_bundles: &[Arc<RenderBundle>],
4529    ) -> Result<(), PassStateError> {
4530        let scope = PassErrorScope::ExecuteBundle;
4531        let base = pass_base!(self, scope);
4532
4533        for bundle in render_bundles {
4534            pass_try!(base, scope, bundle.check_is_valid());
4535
4536            base.commands
4537                .push(ArcRenderCommand::ExecuteBundle(bundle.clone()));
4538        }
4539        self.current_pipeline.reset();
4540        self.current_bind_groups.reset();
4541
4542        Ok(())
4543    }
4544
4545    pub fn execute_bundles(&mut self, render_bundles: &[Arc<RenderBundle>]) {
4546        if let Err(err) = self.execute_bundles_inner(render_bundles) {
4547            self.device
4548                .handle_error(err, self.label(), "RenderPass::execute_bundles");
4549        }
4550    }
4551}
4552
4553pub(crate) const fn get_src_stride_of_indirect_args(family: DrawCommandFamily) -> u64 {
4554    match family {
4555        DrawCommandFamily::Draw => size_of::<wgt::DrawIndirectArgs>() as u64,
4556        DrawCommandFamily::DrawIndexed => size_of::<wgt::DrawIndexedIndirectArgs>() as u64,
4557        DrawCommandFamily::DrawMeshTasks => size_of::<wgt::DispatchIndirectArgs>() as u64,
4558    }
4559}
4560
4561pub(crate) const fn get_dst_stride_of_indirect_args(
4562    backend: wgt::Backend,
4563    family: DrawCommandFamily,
4564) -> u64 {
4565    // space for D3D12 special constants
4566    let extra = if matches!(backend, wgt::Backend::Dx12) {
4567        3 * size_of::<u32>() as u64
4568    } else {
4569        0
4570    };
4571    extra + get_src_stride_of_indirect_args(family)
4572}