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
75fn 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 assert_eq!(stencil_format, wgt::TextureFormat::Stencil8);
86 value & 255
87}
88
89#[repr(C)]
94#[derive(Clone, Debug, Eq, PartialEq)]
95#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
96pub struct PassChannel<V> {
97 pub load_op: Option<LoadOp<V>>,
103 pub store_op: Option<StoreOp>,
105 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#[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#[repr(C)]
190#[derive(Clone, Debug, PartialEq)]
191#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
192pub struct RenderPassColorAttachment<TV = Arc<TextureView>> {
193 pub view: TV,
195 pub depth_slice: Option<u32>,
197 pub resolve_target: Option<TV>,
199 pub load_op: LoadOp<Color>,
205 pub store_op: StoreOp,
207}
208
209pub 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#[repr(C)]
231#[derive(Clone, Debug, PartialEq)]
232#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
233pub struct RenderPassDepthStencilAttachment<TV> {
234 pub view: TV,
236 pub depth: PassChannel<Option<f32>>,
238 pub stencil: PassChannel<Option<u32>>,
240}
241
242#[derive(Clone, Debug)]
246#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
247pub struct ResolvedRenderPassDepthStencilAttachment<TV> {
248 pub view: TV,
250 pub depth: ResolvedPassChannel<f32>,
252 pub stencil: ResolvedPassChannel<u32>,
254}
255
256#[derive(Clone, Default)]
258pub struct ResolvedRenderPassDescriptor<'a> {
259 pub label: Label<'a>,
260 pub color_attachments: Cow<'a, [Option<RenderPassColorAttachment<Arc<TextureView>>>]>,
262 pub depth_stencil_attachment: Option<RenderPassDepthStencilAttachment<Arc<TextureView>>>,
264 pub timestamp_writes: Option<PassTimestampWrites<Arc<QuerySet>>>,
266 pub occlusion_query_set: Option<Arc<QuerySet>>,
268 pub multiview_mask: Option<NonZeroU32>,
270}
271
272struct ArcRenderPassDescriptor<'a> {
274 pub label: &'a Label<'a>,
275 pub color_attachments:
277 ArrayVec<Option<RenderPassColorAttachment>, { hal::MAX_COLOR_ATTACHMENTS }>,
278 pub depth_stencil_attachment:
280 Option<ResolvedRenderPassDepthStencilAttachment<Arc<TextureView>>>,
281 pub timestamp_writes: Option<PassTimestampWrites>,
283 pub occlusion_query_set: Option<Arc<QuerySet>>,
285 pub multiview_mask: Option<NonZeroU32>,
287}
288
289pub type RenderBasePass = BasePass<ArcRenderCommand, RenderPassError>;
290
291pub struct RenderPass {
299 base: BasePass<ArcRenderCommand, RenderPassError>,
301
302 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 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 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 pub(crate) vertex_limit: u64,
434 vertex_limit_slot: u32,
436 pub(crate) instance_limit: u64,
438 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 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 return Self::default();
466 };
467
468 let limit = if buffer_size < step.last_stride {
469 0
471 } else {
472 if step.stride == 0 {
473 continue;
477 }
478
479 (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#[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#[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 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 pub(crate) fn clear_buffer(&mut self, slot: usize) {
579 self.slots[slot] = None;
580 }
581
582 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 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 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.binder.check_compatibility(pipeline.as_ref())?;
674 self.pass.binder.check_late_buffer_bindings()?;
675
676 if self.blend_constant == OptionalState::Required {
677 return Err(DrawError::MissingBlendConstant);
678 }
679
680 self.vertex.validate(pipeline.as_ref(), &self.pass.binder)?;
681
682 if family == DrawCommandFamily::DrawIndexed {
683 let buffer_index_format = self
686 .index
687 .buffer_format
688 .ok_or(DrawError::MissingIndexBuffer)?;
689
690 if pipeline.topology.is_strip()
691 && pipeline.strip_index_format != Some(buffer_index_format)
692 {
693 return Err(DrawError::UnmatchedStripIndexFormat {
694 pipeline: pipeline.error_ident(),
695 strip_index_format: pipeline.strip_index_format,
696 buffer_format: buffer_index_format,
697 });
698 }
699 }
700 if (family == DrawCommandFamily::DrawMeshTasks) != pipeline.is_mesh {
701 return Err(DrawError::WrongPipelineType {
702 wanted_mesh_pipeline: !pipeline.is_mesh,
703 });
704 }
705 if !self
706 .pass
707 .immediate_state
708 .immediate_slots_set
709 .contains(pipeline.immediate_slots_required)
710 {
711 return Err(DrawError::MissingImmediateData {
712 missing: pipeline
713 .immediate_slots_required
714 .difference(self.pass.immediate_state.immediate_slots_set),
715 });
716 }
717 Ok(())
718 } else {
719 Err(DrawError::MissingPipeline(pass::MissingPipeline))
720 }
721 }
722
723 fn flush_immediates(&mut self) {
724 let pipeline = self.pipeline.as_ref().unwrap();
725 let layout = pipeline.layout().unwrap();
726 self.pass
727 .immediate_state
728 .flush_immediates(layout, self.pass.base.raw_encoder);
729 }
730
731 fn flush_bindings(&mut self) -> Result<(), RenderPassErrorInner> {
736 flush_bindings_helper(&mut self.pass)?;
737 Ok(())
738 }
739
740 fn reset_bundle(&mut self) {
742 self.pass.binder.reset();
743 self.pipeline = None;
744 self.index.reset();
745 self.vertex = Default::default();
746 self.pass.immediate_state.immediate_slots_set = Default::default();
747 }
748
749 fn flush_vertex_buffers(&mut self) -> Result<(), RenderPassErrorInner> {
751 let vertex = &mut self.vertex;
752 let raw_encoder: &mut dyn hal::DynCommandEncoder = self.pass.base.raw_encoder;
753 let snatch_guard = self.pass.base.snatch_guard;
754 let mut result = Ok(());
755 vertex.flush(|slot, buffer, offset, size| {
756 if result.is_err() {
757 return;
758 }
759 match buffer.try_raw(snatch_guard) {
760 Ok(raw) => unsafe {
761 raw_encoder.set_vertex_buffer(
763 slot,
764 hal::BufferBinding::new_unchecked(raw, offset, size),
765 );
766 },
767 Err(e) => result = Err(e.into()),
768 }
769 });
770 result
771 }
772}
773
774#[derive(Debug, Copy, Clone)]
778pub enum AttachmentErrorLocation {
779 Color { index: usize, resolve: bool },
780 Depth,
781}
782
783impl fmt::Display for AttachmentErrorLocation {
784 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785 match *self {
786 AttachmentErrorLocation::Color {
787 index,
788 resolve: false,
789 } => write!(f, "color attachment at index {index}'s texture view"),
790 AttachmentErrorLocation::Color {
791 index,
792 resolve: true,
793 } => write!(
794 f,
795 "color attachment at index {index}'s resolve texture view"
796 ),
797 AttachmentErrorLocation::Depth => write!(f, "depth attachment's texture view"),
798 }
799 }
800}
801
802#[derive(Clone, Debug, Error)]
803#[non_exhaustive]
804pub enum ColorAttachmentError {
805 #[error("Attachment format {0:?} is not a color format")]
806 InvalidFormat(wgt::TextureFormat),
807 #[error("The number of color attachments {given} exceeds the limit {limit}")]
808 TooMany { given: usize, limit: usize },
809 #[error("The total number of bytes per sample in color attachments {total} exceeds the limit {limit}")]
810 TooManyBytesPerSample { total: u32, limit: u32 },
811 #[error("Depth slice must be less than {limit} but is {given}")]
812 DepthSliceLimit { given: u32, limit: u32 },
813 #[error("Color attachment's view is 3D and requires depth slice to be provided")]
814 MissingDepthSlice,
815 #[error("Depth slice was provided but the color attachment's view is not 3D")]
816 UnneededDepthSlice,
817 #[error("{view}'s subresource at mip {mip_level} and depth/array layer {depth_or_array_layer} is already attached to this render pass")]
818 SubresourceOverlap {
819 view: ResourceErrorIdent,
820 mip_level: u32,
821 depth_or_array_layer: u32,
822 },
823 #[error(
824 "Color attachment with `TRANSIENT_ATTACHMENT` usage can only be used with \
825 `LoadOp::Clear` or `LoadOp::DontCare` (if it is available) and `StoreOp::Discard`. Operations `{0:?}` were provided"
826 )]
827 InvalidTransientAttachmentOp((LoadOp<Color>, StoreOp)),
828 #[error("Color attachment's load op is `LoadOp::DontCare` but `InstanceFlags::STRICT_WEBGPU_COMPLIANCE` is set")]
829 LoadOpDontCareUnderStrictWebgpuCompliance,
830}
831
832impl WebGpuError for ColorAttachmentError {
833 fn webgpu_error_type(&self) -> ErrorType {
834 ErrorType::Validation
835 }
836}
837
838#[derive(Clone, Debug, Error)]
839#[non_exhaustive]
840pub enum AttachmentError {
841 #[error("The format of the depth-stencil attachment ({0:?}) is not a depth-or-stencil format")]
842 InvalidDepthStencilAttachmentFormat(wgt::TextureFormat),
843 #[error(
844 "Depth attachment with `TRANSIENT_ATTACHMENT` usage can only be used with \
845 `LoadOp::Clear` or `LoadOp::DontCare` (if it is available) and `StoreOp::Discard`. Operations `{0:?}` were provided"
846 )]
847 InvalidTransientDepthAttachmentOps((LoadOp<Option<f32>>, StoreOp)),
848 #[error("Depth attachment with `TRANSIENT_ATTACHMENT` usage cannot be read-only")]
849 ReadOnlyTransientDepthAttachment,
850 #[error(
851 "Stencil attachment with `TRANSIENT_ATTACHMENT` usage can only be used with \
852 `LoadOp::Clear` or `LoadOp::DontCare` (if it is available) and `StoreOp::Discard`. Operations `{0:?}` were provided"
853 )]
854 InvalidTransientStencilAttachmentOps((LoadOp<Option<u32>>, StoreOp)),
855 #[error("Stencil attachment with `TRANSIENT_ATTACHMENT` usage cannot be read-only")]
856 ReadOnlyTransientStencilAttachment,
857 #[error("LoadOp must be None for read-only attachments")]
858 ReadOnlyWithLoad,
859 #[error("StoreOp must be None for read-only attachments")]
860 ReadOnlyWithStore,
861 #[error("Depth `LoadOp` and `StoreOp` (`{ops:?}`) must be `None` for attachments (`{format:?}`) without depth aspect")]
862 DepthOpsWithoutAspect {
863 format: wgt::TextureFormat,
864 ops: (Option<LoadOp<Option<f32>>>, Option<StoreOp>),
865 },
866 #[error("Stencil `LoadOp` and `StoreOp` (`{ops:?}`) must be `None` for attachments (`{format:?}`) without stencil aspect")]
867 StencilOpsWithoutAspect {
868 format: wgt::TextureFormat,
869 ops: (Option<LoadOp<Option<u32>>>, Option<StoreOp>),
870 },
871 #[error("Attachment without load")]
872 NoLoad,
873 #[error("Attachment without store")]
874 NoStore,
875 #[error("LoadOp is `Clear` but no clear value was provided")]
876 NoClearValue,
877 #[error("Clear value ({0}) must be between 0.0 and 1.0, inclusive")]
878 ClearValueOutOfRange(f32),
879 #[error("Load op is `DontCare` but `InstanceFlags::STRICT_WEBGPU_COMPLIANCE` is set")]
880 LoadOpDontCareUnderStrictWebgpuCompliance,
881}
882
883impl WebGpuError for AttachmentError {
884 fn webgpu_error_type(&self) -> ErrorType {
885 ErrorType::Validation
886 }
887}
888
889#[derive(Clone, Debug, Error)]
891pub enum RenderPassErrorInner {
892 #[error(transparent)]
893 Device(#[from] DeviceError),
894 #[error(transparent)]
895 ColorAttachment(#[from] ColorAttachmentError),
896 #[error(transparent)]
897 InvalidAttachment(#[from] AttachmentError),
898 #[error(transparent)]
899 EncoderState(#[from] EncoderStateError),
900 #[error("Parent encoder is invalid")]
901 InvalidParentEncoder,
902 #[error(transparent)]
903 DebugGroupError(#[from] DebugGroupError),
904 #[error("The format of the {location} ({format:?}) is not resolvable")]
905 UnsupportedResolveTargetFormat {
906 location: AttachmentErrorLocation,
907 format: wgt::TextureFormat,
908 },
909 #[error("The {location} is not valid, because the texture has `TRANSIENT_ATTACHMENT` usage")]
910 InvalidTransientResolveTarget { location: AttachmentErrorLocation },
911 #[error("No color attachments or depth attachments were provided, at least one attachment of any kind must be provided")]
912 MissingAttachments,
913 #[error("The {location} is not renderable:")]
914 TextureViewIsNotRenderable {
915 location: AttachmentErrorLocation,
916 #[source]
917 reason: TextureViewNotRenderableReason,
918 },
919 #[error("Attachments have differing sizes: the {expected_location} has extent {expected_extent:?} but is followed by the {actual_location} which has {actual_extent:?}")]
920 AttachmentsDimensionMismatch {
921 expected_location: AttachmentErrorLocation,
922 expected_extent: wgt::Extent3d,
923 actual_location: AttachmentErrorLocation,
924 actual_extent: wgt::Extent3d,
925 },
926 #[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:?}")]
927 AttachmentSampleCountMismatch {
928 expected_location: AttachmentErrorLocation,
929 expected_samples: u32,
930 actual_location: AttachmentErrorLocation,
931 actual_samples: u32,
932 },
933 #[error("The resolve source, {location}, must be multi-sampled (has {src} samples) while the resolve destination must not be multisampled (has {dst} samples)")]
934 InvalidResolveSampleCounts {
935 location: AttachmentErrorLocation,
936 src: u32,
937 dst: u32,
938 },
939 #[error(
940 "Resource source, {location}, format ({src:?}) must match the resolve destination format ({dst:?})"
941 )]
942 MismatchedResolveTextureFormat {
943 location: AttachmentErrorLocation,
944 src: wgt::TextureFormat,
945 dst: wgt::TextureFormat,
946 },
947 #[error("Unable to clear non-present/read-only depth")]
948 InvalidDepthOps,
949 #[error("Unable to clear non-present/read-only stencil")]
950 InvalidStencilOps,
951 #[error(transparent)]
952 MissingFeatures(#[from] MissingFeatures),
953 #[error(transparent)]
954 MissingDownlevelFlags(#[from] MissingDownlevelFlags),
955 #[error("Indirect draw count of {count_bytes} bytes starting at {begin_count_offset} would overrun buffer of size {count_buffer_size}")]
956 IndirectCountBufferOverrun {
957 count_bytes: u64,
958 begin_count_offset: u64,
959 count_buffer_size: u64,
960 },
961 #[error(transparent)]
962 ResourceUsageCompatibility(#[from] ResourceUsageCompatibilityError),
963 #[error("Render bundle has incompatible targets, {0}")]
964 IncompatibleBundleTargets(#[from] RenderPassCompatibilityError),
965 #[error(
966 "Render bundle has incompatible read-only flags: \
967 bundle has flags depth = {bundle_depth} and stencil = {bundle_stencil}, \
968 while the pass has flags depth = {pass_depth} and stencil = {pass_stencil}. \
969 Read-only renderpasses are only compatible with read-only bundles for that aspect."
970 )]
971 IncompatibleBundleReadOnlyDepthStencil {
972 pass_depth: bool,
973 pass_stencil: bool,
974 bundle_depth: bool,
975 bundle_stencil: bool,
976 },
977 #[error(transparent)]
978 RenderCommand(#[from] RenderCommandError),
979 #[error(transparent)]
980 Draw(#[from] DrawError),
981 #[error(transparent)]
982 Bind(#[from] BindError),
983 #[error(transparent)]
984 QueryUse(#[from] QueryUseError),
985 #[error("Multiview layer count must match")]
986 MultiViewMismatch,
987 #[error(
988 "Multiview pass texture views with more than one array layer must have D2Array dimension"
989 )]
990 MultiViewDimensionMismatch,
991 #[error("Multiview view count limit violated")]
992 TooManyMultiviewViews,
993 #[error("missing occlusion query set")]
994 MissingOcclusionQuerySet,
995 #[error(transparent)]
996 DestroyedResource(#[from] DestroyedResourceError),
997 #[error("The compute pass has already been ended and no further commands can be recorded")]
998 PassEnded,
999 #[error(transparent)]
1000 InvalidResource(#[from] InvalidResourceError),
1001 #[error(transparent)]
1002 TimestampWrites(#[from] TimestampWritesError),
1003}
1004
1005impl From<InvalidOrDestroyedResourceError> for RenderPassErrorInner {
1006 fn from(error: InvalidOrDestroyedResourceError) -> Self {
1007 match error {
1008 InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e),
1009 InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e),
1010 }
1011 }
1012}
1013
1014impl From<MissingBufferUsageError> for RenderPassErrorInner {
1015 fn from(error: MissingBufferUsageError) -> Self {
1016 Self::RenderCommand(error.into())
1017 }
1018}
1019
1020impl From<MissingTextureUsageError> for RenderPassErrorInner {
1021 fn from(error: MissingTextureUsageError) -> Self {
1022 Self::RenderCommand(error.into())
1023 }
1024}
1025
1026impl From<pass::BindGroupIndexOutOfRange> for RenderPassErrorInner {
1027 fn from(error: pass::BindGroupIndexOutOfRange) -> Self {
1028 Self::RenderCommand(RenderCommandError::BindGroupIndexOutOfRange(error))
1029 }
1030}
1031
1032impl From<pass::MissingPipeline> for RenderPassErrorInner {
1033 fn from(error: pass::MissingPipeline) -> Self {
1034 Self::Draw(DrawError::MissingPipeline(error))
1035 }
1036}
1037
1038impl From<ImmediateUploadError> for RenderPassErrorInner {
1039 fn from(error: ImmediateUploadError) -> Self {
1040 Self::RenderCommand(error.into())
1041 }
1042}
1043
1044#[derive(Clone, Debug, Error)]
1046#[error("{scope}")]
1047pub struct RenderPassError {
1048 pub scope: PassErrorScope,
1049 #[source]
1050 pub(super) inner: Box<RenderPassErrorInner>,
1051}
1052
1053impl<E: Into<RenderPassErrorInner>> MapPassErr<RenderPassError> for E {
1054 fn map_pass_err(self, scope: PassErrorScope) -> RenderPassError {
1055 RenderPassError {
1056 scope,
1057 inner: Box::new(self.into()),
1058 }
1059 }
1060}
1061
1062impl WebGpuError for RenderPassError {
1063 fn webgpu_error_type(&self) -> ErrorType {
1064 match self.inner.as_ref() {
1065 RenderPassErrorInner::Device(e) => e.webgpu_error_type(),
1066 RenderPassErrorInner::ColorAttachment(e) => e.webgpu_error_type(),
1067 RenderPassErrorInner::EncoderState(e) => e.webgpu_error_type(),
1068 RenderPassErrorInner::DebugGroupError(e) => e.webgpu_error_type(),
1069 RenderPassErrorInner::MissingFeatures(e) => e.webgpu_error_type(),
1070 RenderPassErrorInner::MissingDownlevelFlags(e) => e.webgpu_error_type(),
1071 RenderPassErrorInner::RenderCommand(e) => e.webgpu_error_type(),
1072 RenderPassErrorInner::Draw(e) => e.webgpu_error_type(),
1073 RenderPassErrorInner::Bind(e) => e.webgpu_error_type(),
1074 RenderPassErrorInner::QueryUse(e) => e.webgpu_error_type(),
1075 RenderPassErrorInner::DestroyedResource(e) => e.webgpu_error_type(),
1076 RenderPassErrorInner::InvalidResource(e) => e.webgpu_error_type(),
1077 RenderPassErrorInner::IncompatibleBundleTargets(e) => e.webgpu_error_type(),
1078 RenderPassErrorInner::InvalidAttachment(e) => e.webgpu_error_type(),
1079 RenderPassErrorInner::TimestampWrites(e) => e.webgpu_error_type(),
1080
1081 RenderPassErrorInner::InvalidParentEncoder
1082 | RenderPassErrorInner::UnsupportedResolveTargetFormat { .. }
1083 | RenderPassErrorInner::InvalidTransientResolveTarget { .. }
1084 | RenderPassErrorInner::MissingAttachments
1085 | RenderPassErrorInner::TextureViewIsNotRenderable { .. }
1086 | RenderPassErrorInner::AttachmentsDimensionMismatch { .. }
1087 | RenderPassErrorInner::AttachmentSampleCountMismatch { .. }
1088 | RenderPassErrorInner::InvalidResolveSampleCounts { .. }
1089 | RenderPassErrorInner::MismatchedResolveTextureFormat { .. }
1090 | RenderPassErrorInner::InvalidDepthOps
1091 | RenderPassErrorInner::InvalidStencilOps
1092 | RenderPassErrorInner::IndirectCountBufferOverrun { .. }
1093 | RenderPassErrorInner::ResourceUsageCompatibility(..)
1094 | RenderPassErrorInner::IncompatibleBundleReadOnlyDepthStencil { .. }
1095 | RenderPassErrorInner::MultiViewMismatch
1096 | RenderPassErrorInner::MultiViewDimensionMismatch
1097 | RenderPassErrorInner::TooManyMultiviewViews
1098 | RenderPassErrorInner::MissingOcclusionQuerySet
1099 | RenderPassErrorInner::PassEnded => ErrorType::Validation,
1100 }
1101 }
1102}
1103
1104struct RenderAttachment {
1105 texture: Arc<Texture>,
1106 selector: TextureSelector,
1107 usage: wgt::TextureUses,
1108}
1109
1110impl TextureView {
1111 fn to_render_attachment(&self, usage: wgt::TextureUses) -> RenderAttachment {
1112 RenderAttachment {
1113 texture: self.parent.clone(),
1114 selector: self.selector.clone(),
1115 usage,
1116 }
1117 }
1118}
1119
1120const MAX_TOTAL_ATTACHMENTS: usize = hal::MAX_COLOR_ATTACHMENTS + hal::MAX_COLOR_ATTACHMENTS + 1;
1121type AttachmentDataVec<T> = ArrayVec<T, MAX_TOTAL_ATTACHMENTS>;
1122
1123struct RenderPassInfo {
1124 context: RenderPassContext,
1125 render_attachments: AttachmentDataVec<RenderAttachment>,
1127 is_depth_read_only: bool,
1128 is_stencil_read_only: bool,
1129 extent: wgt::Extent3d,
1130
1131 divergent_discarded_depth_stencil_aspect: Option<(wgt::TextureAspect, Arc<TextureView>)>,
1132 multiview_mask: Option<NonZeroU32>,
1133}
1134
1135impl RenderPassInfo {
1136 fn add_pass_texture_init_actions<V>(
1137 load_op: LoadOp<V>,
1138 store_op: StoreOp,
1139 texture_memory_actions: &mut CommandBufferTextureMemoryActions,
1140 view: &TextureView,
1141 depth_slice: Option<u32>,
1142 pending_discard_init_fixups: &mut SurfacesInDiscardState,
1143 ) {
1144 match (
1145 depth_slice,
1146 view.parent.desc.dimension == wgt::TextureDimension::D3,
1147 ) {
1148 (Some(_), true) | (None, false) => {}
1149 _ => unreachable!("3D textures, but not any other kind, must specify a depth slice"),
1150 }
1151 let partial_z = view.parent.desc.dimension == wgt::TextureDimension::D3
1154 && view
1155 .parent
1156 .desc
1157 .mip_level_size(view.selector.mips.start)
1158 .is_some_and(|dim| dim.depth_or_array_layers > 1);
1159
1160 if matches!(load_op, LoadOp::Load) {
1161 pending_discard_init_fixups.extend(texture_memory_actions.register_init_action(
1176 &TextureInitTrackerAction {
1177 texture: view.parent.clone(),
1178 range: TextureInitRange::from(view),
1179 kind: MemoryInitKind::NeedsInitializedMemory,
1181 },
1182 depth_slice.map(|slice| slice..slice + 1),
1183 ));
1184 } else if store_op == StoreOp::Store {
1185 if partial_z {
1186 pending_discard_init_fixups.extend(texture_memory_actions.register_init_action(
1188 &TextureInitTrackerAction {
1189 texture: view.parent.clone(),
1190 range: TextureInitRange::from(view),
1191 kind: MemoryInitKind::NeedsInitializedMemory,
1192 },
1193 depth_slice.map(|slice| slice..slice + 1),
1194 ));
1195 } else {
1196 texture_memory_actions
1198 .register_implicit_init(&view.parent, TextureInitRange::from(view));
1199 }
1200 }
1201 if store_op == StoreOp::Discard {
1202 texture_memory_actions.discard(TextureSurfaceDiscard {
1212 texture: view.parent.clone(),
1213 mip_level: view.selector.mips.start,
1214 layer_or_depth_slice: depth_slice.unwrap_or(view.selector.layers.start),
1215 });
1216 }
1217 }
1218
1219 fn start(
1220 device: &Arc<Device>,
1221 hal_label: Option<&str>,
1222 color_attachments: &[Option<RenderPassColorAttachment>],
1223 mut depth_stencil_attachment: Option<
1224 ResolvedRenderPassDepthStencilAttachment<Arc<TextureView>>,
1225 >,
1226 mut timestamp_writes: Option<PassTimestampWrites>,
1227 mut occlusion_query_set: Option<Arc<QuerySet>>,
1228 encoder: &mut dyn hal::DynCommandEncoder,
1229 trackers: &mut Tracker,
1230 texture_memory_actions: &mut CommandBufferTextureMemoryActions,
1231 pending_query_resets: &mut QueryResetMap,
1232 pending_discard_init_fixups: &mut SurfacesInDiscardState,
1233 snatch_guard: &SnatchGuard<'_>,
1234 query_set_writes: &mut QuerySetWrites,
1235 multiview_mask: Option<NonZeroU32>,
1236 ) -> Result<Self, RenderPassErrorInner> {
1237 profiling::scope!("RenderPassInfo::start");
1238
1239 let mut is_depth_read_only = false;
1243 let mut is_stencil_read_only = false;
1244
1245 let mut render_attachments = AttachmentDataVec::<RenderAttachment>::new();
1246 let mut divergent_discarded_depth_stencil_aspect = None;
1247
1248 let mut attachment_location = AttachmentErrorLocation::Color {
1249 index: usize::MAX,
1250 resolve: false,
1251 };
1252 let mut extent = None;
1253 let mut sample_count = 0;
1254
1255 let mut detected_multiview: Option<Option<NonZeroU32>> = None;
1256
1257 let mut check_multiview = |view: &TextureView| {
1258 let layers = view.selector.layers.end - view.selector.layers.start;
1260 let this_multiview = if layers >= 2 {
1261 Some(unsafe { NonZeroU32::new_unchecked(layers) })
1263 } else {
1264 None
1265 };
1266
1267 if this_multiview.is_some() && view.desc.dimension != TextureViewDimension::D2Array {
1269 return Err(RenderPassErrorInner::MultiViewDimensionMismatch);
1270 }
1271
1272 if let Some(multiview) = detected_multiview {
1274 if multiview != this_multiview {
1275 return Err(RenderPassErrorInner::MultiViewMismatch);
1276 }
1277 } else {
1278 if let Some(this_multiview) = this_multiview {
1280 device.require_features(wgt::Features::MULTIVIEW)?;
1281 if this_multiview.get() > device.limits.max_multiview_view_count {
1282 return Err(RenderPassErrorInner::TooManyMultiviewViews);
1283 }
1284 }
1285
1286 detected_multiview = Some(this_multiview);
1287 }
1288
1289 Ok(())
1290 };
1291 let mut add_view = |view: &TextureView, location| {
1292 let render_extent = view.state()?.render_extent.map_err(|reason| {
1293 RenderPassErrorInner::TextureViewIsNotRenderable { location, reason }
1294 })?;
1295 if let Some(ex) = extent {
1296 if ex != render_extent {
1297 return Err(RenderPassErrorInner::AttachmentsDimensionMismatch {
1298 expected_location: attachment_location,
1299 expected_extent: ex,
1300 actual_location: location,
1301 actual_extent: render_extent,
1302 });
1303 }
1304 } else {
1305 extent = Some(render_extent);
1306 }
1307 if sample_count == 0 {
1308 sample_count = view.samples;
1309 } else if sample_count != view.samples {
1310 return Err(RenderPassErrorInner::AttachmentSampleCountMismatch {
1311 expected_location: attachment_location,
1312 expected_samples: sample_count,
1313 actual_location: location,
1314 actual_samples: view.samples,
1315 });
1316 }
1317 attachment_location = location;
1318 Ok(())
1319 };
1320
1321 let mut depth_stencil = None;
1322
1323 if let Some(at) = depth_stencil_attachment.as_ref() {
1324 let view = &at.view;
1325 check_multiview(view)?;
1326 add_view(view, AttachmentErrorLocation::Depth)?;
1327
1328 let ds_aspects = view.desc.aspects();
1329
1330 if !ds_aspects.contains(hal::FormatAspects::STENCIL)
1331 || (at.stencil.load_op().eq_variant(at.depth.load_op())
1332 && at.stencil.store_op() == at.depth.store_op())
1333 {
1334 Self::add_pass_texture_init_actions(
1335 at.depth.load_op(),
1336 at.depth.store_op(),
1337 texture_memory_actions,
1338 view,
1339 None,
1340 pending_discard_init_fixups,
1341 );
1342 } else if !ds_aspects.contains(hal::FormatAspects::DEPTH) {
1343 Self::add_pass_texture_init_actions(
1344 at.stencil.load_op(),
1345 at.stencil.store_op(),
1346 texture_memory_actions,
1347 view,
1348 None,
1349 pending_discard_init_fixups,
1350 );
1351 } else {
1352 let need_init_beforehand =
1375 at.depth.load_op() == LoadOp::Load || at.stencil.load_op() == LoadOp::Load;
1376 if need_init_beforehand {
1377 pending_discard_init_fixups.extend(
1378 texture_memory_actions.register_init_action(
1379 &TextureInitTrackerAction {
1380 texture: view.parent.clone(),
1381 range: TextureInitRange::from(view.as_ref()),
1382 kind: MemoryInitKind::NeedsInitializedMemory,
1383 },
1384 None, ),
1386 );
1387 }
1388
1389 if at.depth.store_op() != at.stencil.store_op() {
1398 if !need_init_beforehand {
1399 texture_memory_actions.register_implicit_init(
1400 &view.parent,
1401 TextureInitRange::from(view.as_ref()),
1402 );
1403 }
1404 divergent_discarded_depth_stencil_aspect = Some((
1405 if at.depth.store_op() == StoreOp::Discard {
1406 wgt::TextureAspect::DepthOnly
1407 } else {
1408 wgt::TextureAspect::StencilOnly
1409 },
1410 view.clone(),
1411 ));
1412 } else if at.depth.store_op() == StoreOp::Discard {
1413 texture_memory_actions.discard(TextureSurfaceDiscard {
1415 texture: view.parent.clone(),
1416 mip_level: view.selector.mips.start,
1417 layer_or_depth_slice: view.selector.layers.start,
1418 });
1419 }
1420 }
1421
1422 is_depth_read_only = at.depth.is_readonly();
1423 is_stencil_read_only = at.stencil.is_readonly();
1424
1425 let usage = 'b: {
1426 if device
1427 .downlevel
1428 .flags
1429 .contains(wgt::DownlevelFlags::READ_ONLY_DEPTH_STENCIL)
1430 {
1431 let depth_stencil_uses = match (is_depth_read_only, is_stencil_read_only) {
1432 (true, true) => {
1433 wgt::TextureUses::DEPTH_READ | wgt::TextureUses::STENCIL_READ
1434 }
1435 (true, false) => {
1436 wgt::TextureUses::DEPTH_READ | wgt::TextureUses::STENCIL_WRITE
1437 }
1438 (false, true) => {
1439 wgt::TextureUses::DEPTH_WRITE | wgt::TextureUses::STENCIL_READ
1440 }
1441 (false, false) => {
1442 break 'b wgt::TextureUses::DEPTH_WRITE
1443 | wgt::TextureUses::STENCIL_WRITE;
1444 }
1445 };
1446 if view.desc.usage.contains(TextureUsages::TEXTURE_BINDING) {
1451 depth_stencil_uses | wgt::TextureUses::RESOURCE
1452 } else {
1453 depth_stencil_uses
1454 }
1455 } else {
1456 wgt::TextureUses::DEPTH_WRITE | wgt::TextureUses::STENCIL_WRITE
1457 }
1458 };
1459 render_attachments.push(view.to_render_attachment(usage));
1460
1461 depth_stencil = Some(hal::DepthStencilAttachment {
1462 target: hal::Attachment {
1463 view: view.try_raw(snatch_guard)?,
1464 usage,
1465 },
1466 depth_ops: at.depth.hal_ops(),
1467 stencil_ops: at.stencil.hal_ops(),
1468 clear_value: (at.depth.clear_value(), at.stencil.clear_value()),
1469 depth_read_only: is_depth_read_only,
1470 stencil_read_only: is_stencil_read_only,
1471 });
1472 }
1473
1474 let mut attachment_set = crate::FastHashSet::default();
1475
1476 let mut color_attachments_hal =
1477 ArrayVec::<Option<hal::ColorAttachment<_>>, { hal::MAX_COLOR_ATTACHMENTS }>::new();
1478 for (index, attachment) in color_attachments.iter().enumerate() {
1479 let at = if let Some(attachment) = attachment.as_ref() {
1480 attachment
1481 } else {
1482 color_attachments_hal.push(None);
1483 continue;
1484 };
1485 let color_view: &TextureView = &at.view;
1486 color_view.same_device(device)?;
1487 check_multiview(color_view)?;
1488 add_view(
1489 color_view,
1490 AttachmentErrorLocation::Color {
1491 index,
1492 resolve: false,
1493 },
1494 )?;
1495
1496 if !color_view.desc.aspects().intersects(
1497 hal::FormatAspects::COLOR
1498 | hal::FormatAspects::PLANE_0
1499 | hal::FormatAspects::PLANE_1
1500 | hal::FormatAspects::PLANE_2,
1501 ) {
1502 return Err(RenderPassErrorInner::ColorAttachment(
1503 ColorAttachmentError::InvalidFormat(color_view.desc.format),
1504 ));
1505 }
1506
1507 if color_view.desc.dimension == TextureViewDimension::D3 {
1508 if let Some(depth_slice) = at.depth_slice {
1509 let mip = color_view.desc.range.base_mip_level;
1510 let mip_size = color_view
1511 .parent
1512 .desc
1513 .size
1514 .mip_level_size(mip, color_view.parent.desc.dimension);
1515 let limit = mip_size.depth_or_array_layers;
1516 if depth_slice >= limit {
1517 return Err(RenderPassErrorInner::ColorAttachment(
1518 ColorAttachmentError::DepthSliceLimit {
1519 given: depth_slice,
1520 limit,
1521 },
1522 ));
1523 }
1524 } else {
1525 return Err(RenderPassErrorInner::ColorAttachment(
1526 ColorAttachmentError::MissingDepthSlice,
1527 ));
1528 }
1529 } else if at.depth_slice.is_some() {
1530 return Err(RenderPassErrorInner::ColorAttachment(
1531 ColorAttachmentError::UnneededDepthSlice,
1532 ));
1533 }
1534
1535 validation::validate_color_attachment_bytes_per_sample(
1536 color_attachments
1537 .iter()
1538 .flatten()
1539 .map(|at| at.view.desc.format),
1540 device.limits.max_color_attachment_bytes_per_sample,
1541 )
1542 .map_err(RenderPassErrorInner::ColorAttachment)?;
1543
1544 fn check_attachment_overlap(
1545 attachment_set: &mut crate::FastHashSet<(crate::track::TrackerIndex, u32, u32)>,
1546 view: &TextureView,
1547 depth_slice: Option<u32>,
1548 ) -> Result<(), ColorAttachmentError> {
1549 let mut insert = |slice| {
1550 let mip_level = view.desc.range.base_mip_level;
1551 if attachment_set.insert((
1552 view.parent.tracking_data.tracker_index(),
1553 mip_level,
1554 slice,
1555 )) {
1556 Ok(())
1557 } else {
1558 Err(ColorAttachmentError::SubresourceOverlap {
1559 view: view.error_ident(),
1560 mip_level,
1561 depth_or_array_layer: slice,
1562 })
1563 }
1564 };
1565 match view.desc.dimension {
1566 TextureViewDimension::D2 => {
1567 insert(view.desc.range.base_array_layer)?;
1568 }
1569 TextureViewDimension::D2Array => {
1570 for layer in view.selector.layers.clone() {
1571 insert(layer)?;
1572 }
1573 }
1574 TextureViewDimension::D3 => {
1575 insert(depth_slice.unwrap())?;
1576 }
1577 _ => unreachable!(),
1578 };
1579 Ok(())
1580 }
1581
1582 check_attachment_overlap(&mut attachment_set, color_view, at.depth_slice)?;
1583
1584 Self::add_pass_texture_init_actions(
1585 at.load_op,
1586 at.store_op,
1587 texture_memory_actions,
1588 color_view,
1589 at.depth_slice,
1590 pending_discard_init_fixups,
1591 );
1592 render_attachments
1593 .push(color_view.to_render_attachment(wgt::TextureUses::COLOR_TARGET));
1594
1595 let mut hal_resolve_target = None;
1596 if let Some(resolve_view) = &at.resolve_target {
1597 resolve_view.same_device(device)?;
1598 check_multiview(resolve_view)?;
1599
1600 check_attachment_overlap(&mut attachment_set, resolve_view, None)?;
1601
1602 let resolve_location = AttachmentErrorLocation::Color {
1603 index,
1604 resolve: true,
1605 };
1606
1607 let render_extent = resolve_view.state()?.render_extent.map_err(|reason| {
1608 RenderPassErrorInner::TextureViewIsNotRenderable {
1609 location: resolve_location,
1610 reason,
1611 }
1612 })?;
1613 if color_view.state()?.render_extent.unwrap() != render_extent {
1614 return Err(RenderPassErrorInner::AttachmentsDimensionMismatch {
1615 expected_location: attachment_location,
1616 expected_extent: extent.unwrap_or_default(),
1617 actual_location: resolve_location,
1618 actual_extent: render_extent,
1619 });
1620 }
1621 if color_view.samples == 1 || resolve_view.samples != 1 {
1622 return Err(RenderPassErrorInner::InvalidResolveSampleCounts {
1623 location: resolve_location,
1624 src: color_view.samples,
1625 dst: resolve_view.samples,
1626 });
1627 }
1628 if color_view.desc.format != resolve_view.desc.format {
1629 return Err(RenderPassErrorInner::MismatchedResolveTextureFormat {
1630 location: resolve_location,
1631 src: color_view.desc.format,
1632 dst: resolve_view.desc.format,
1633 });
1634 }
1635 if !resolve_view
1636 .format_features
1637 .flags
1638 .contains(wgt::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE)
1639 {
1640 return Err(RenderPassErrorInner::UnsupportedResolveTargetFormat {
1641 location: resolve_location,
1642 format: resolve_view.desc.format,
1643 });
1644 }
1645 if resolve_view
1646 .desc
1647 .usage
1648 .contains(TextureUsages::TRANSIENT_ATTACHMENT)
1649 {
1650 return Err(RenderPassErrorInner::InvalidTransientResolveTarget {
1651 location: resolve_location,
1652 });
1653 }
1654
1655 texture_memory_actions.register_implicit_init(
1656 &resolve_view.parent,
1657 TextureInitRange::from(resolve_view.as_ref()),
1658 );
1659 render_attachments
1660 .push(resolve_view.to_render_attachment(wgt::TextureUses::COLOR_TARGET));
1661
1662 hal_resolve_target = Some(hal::Attachment {
1663 view: resolve_view.try_raw(snatch_guard)?,
1664 usage: wgt::TextureUses::COLOR_TARGET,
1665 });
1666 }
1667
1668 color_attachments_hal.push(Some(hal::ColorAttachment {
1669 target: hal::Attachment {
1670 view: color_view.try_raw(snatch_guard)?,
1671 usage: wgt::TextureUses::COLOR_TARGET,
1672 },
1673 depth_slice: at.depth_slice,
1674 resolve_target: hal_resolve_target,
1675 ops: at.hal_ops(),
1676 clear_value: at.clear_value(),
1677 }));
1678 }
1679
1680 let extent = extent.ok_or(RenderPassErrorInner::MissingAttachments)?;
1681
1682 let detected_multiview =
1683 detected_multiview.expect("Multiview was not detected, no attachments");
1684 if let Some(mask) = multiview_mask {
1685 let mask_msb = 31 - mask.leading_zeros();
1687 let detected_mv = detected_multiview.map(NonZeroU32::get).unwrap_or(1);
1688 if mask_msb >= detected_mv {
1689 return Err(RenderPassErrorInner::MultiViewMismatch);
1690 }
1691 if mask.get() != (1 << detected_mv) - 1 {
1692 device.require_features(wgt::Features::SELECTIVE_MULTIVIEW)?;
1693 }
1694 }
1695
1696 let attachment_formats = AttachmentData {
1697 colors: color_attachments
1698 .iter()
1699 .map(|at| at.as_ref().map(|at| at.view.desc.format))
1700 .collect(),
1701 resolves: color_attachments
1702 .iter()
1703 .filter_map(|at| {
1704 at.as_ref().and_then(|at| {
1705 at.resolve_target
1706 .as_ref()
1707 .map(|resolve| resolve.desc.format)
1708 })
1709 })
1710 .collect(),
1711 depth_stencil: depth_stencil_attachment
1712 .as_ref()
1713 .map(|at| at.view.desc.format),
1714 };
1715
1716 let context = RenderPassContext {
1717 attachments: attachment_formats,
1718 sample_count,
1719 multiview_mask,
1720 };
1721
1722 let timestamp_writes_hal = if let Some(tw) = timestamp_writes.as_ref() {
1723 let query_set = &tw.query_set;
1724 query_set.same_device(device)?;
1725
1726 if let Some(index) = tw.beginning_of_pass_write_index {
1727 pending_query_resets.use_query_set(query_set, index);
1728 }
1729 if let Some(index) = tw.end_of_pass_write_index {
1730 pending_query_resets.use_query_set(query_set, index);
1731 }
1732
1733 record_pass_timestamp_writes(tw, query_set_writes);
1734
1735 Some(hal::PassTimestampWrites {
1736 query_set: query_set.try_raw(snatch_guard)?,
1737 beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
1738 end_of_pass_write_index: tw.end_of_pass_write_index,
1739 })
1740 } else {
1741 None
1742 };
1743
1744 let occlusion_query_set_hal = if let Some(query_set) = occlusion_query_set.as_ref() {
1745 query_set.same_device(device)?;
1746 Some(query_set.try_raw(snatch_guard)?)
1747 } else {
1748 None
1749 };
1750
1751 let hal_desc = hal::RenderPassDescriptor {
1752 label: hal_label,
1753 extent,
1754 sample_count,
1755 color_attachments: &color_attachments_hal,
1756 depth_stencil_attachment: depth_stencil,
1757 multiview_mask,
1758 timestamp_writes: timestamp_writes_hal,
1759 occlusion_query_set: occlusion_query_set_hal,
1760 };
1761 unsafe {
1762 encoder
1763 .begin_render_pass(&hal_desc)
1764 .map_err(|e| device.handle_hal_error(e))?;
1765 };
1766 drop(color_attachments_hal); if let Some(tw) = timestamp_writes.take() {
1770 trackers.query_sets.insert_single(tw.query_set);
1771 };
1772 if let Some(occlusion_query_set) = occlusion_query_set.take() {
1773 trackers.query_sets.insert_single(occlusion_query_set);
1774 };
1775 if let Some(at) = depth_stencil_attachment.take() {
1776 trackers.views.insert_single(at.view.clone());
1777 }
1778 for at in color_attachments.iter().flatten() {
1779 trackers.views.insert_single(at.view.clone());
1780 if let Some(resolve_target) = at.resolve_target.clone() {
1781 trackers.views.insert_single(resolve_target);
1782 }
1783 }
1784
1785 Ok(Self {
1786 context,
1787 render_attachments,
1788 is_depth_read_only,
1789 is_stencil_read_only,
1790 extent,
1791 divergent_discarded_depth_stencil_aspect,
1792 multiview_mask,
1793 })
1794 }
1795
1796 fn finish(
1797 self,
1798 device: &Device,
1799 raw: &mut dyn hal::DynCommandEncoder,
1800 snatch_guard: &SnatchGuard,
1801 scope: &mut UsageScope<'_>,
1802 instance_flags: InstanceFlags,
1803 ) -> Result<(), RenderPassErrorInner> {
1804 profiling::scope!("RenderPassInfo::finish");
1805 unsafe {
1806 raw.end_render_pass();
1807 }
1808
1809 for ra in self.render_attachments {
1810 let texture = &ra.texture;
1811 texture.check_usage(TextureUsages::RENDER_ATTACHMENT)?;
1812
1813 unsafe {
1815 scope
1816 .textures
1817 .merge_single(texture, Some(ra.selector.clone()), ra.usage)?
1818 };
1819 }
1820
1821 if let Some((aspect, view)) = self.divergent_discarded_depth_stencil_aspect {
1828 let (depth_ops, stencil_ops) = if aspect == wgt::TextureAspect::DepthOnly {
1829 (
1830 hal::AttachmentOps::LOAD_CLEAR | hal::AttachmentOps::STORE, hal::AttachmentOps::LOAD | hal::AttachmentOps::STORE, )
1833 } else {
1834 (
1835 hal::AttachmentOps::LOAD | hal::AttachmentOps::STORE, hal::AttachmentOps::LOAD_CLEAR | hal::AttachmentOps::STORE, )
1838 };
1839 let desc = hal::RenderPassDescriptor::<'_, _, dyn hal::DynTextureView> {
1840 label: hal_label(
1841 Some("(wgpu internal) Zero init discarded depth/stencil aspect"),
1842 instance_flags,
1843 ),
1844 extent: view.state()?.render_extent.unwrap(),
1845 sample_count: view.samples,
1846 color_attachments: &[],
1847 depth_stencil_attachment: Some(hal::DepthStencilAttachment {
1848 target: hal::Attachment {
1849 view: view.try_raw(snatch_guard)?,
1850 usage: wgt::TextureUses::DEPTH_WRITE | wgt::TextureUses::STENCIL_WRITE,
1851 },
1852 depth_ops,
1853 stencil_ops,
1854 clear_value: (0.0, 0),
1855 depth_read_only: false,
1856 stencil_read_only: false,
1857 }),
1858 multiview_mask: self.multiview_mask,
1859 timestamp_writes: None,
1860 occlusion_query_set: None,
1861 };
1862 unsafe {
1863 raw.begin_render_pass(&desc)
1864 .map_err(|e| device.handle_hal_error(e))?;
1865 raw.end_render_pass();
1866 }
1867 }
1868
1869 Ok(())
1870 }
1871}
1872
1873fn check_transient_attachment_ops<V>(load_op: LoadOp<V>, store_op: StoreOp) -> bool {
1874 matches!(
1875 (load_op, store_op),
1876 (LoadOp::Clear(_) | LoadOp::DontCare(_), StoreOp::Discard)
1877 )
1878}
1879
1880impl CommandEncoder {
1881 fn begin_render_pass_inner(
1882 self: &Arc<Self>,
1883 desc: ResolvedRenderPassDescriptor<'_>,
1884 ) -> (RenderPass, Option<CommandEncoderError>) {
1885 use EncoderStateError as SErr;
1886
1887 fn fill_arc_desc(
1888 desc: ResolvedRenderPassDescriptor<'_>,
1889 arc_desc: &mut ArcRenderPassDescriptor,
1890 device: &Device,
1891 ) -> Result<(), RenderPassErrorInner> {
1892 device.check_is_valid()?;
1893
1894 let max_color_attachments = device.limits.max_color_attachments as usize;
1895 if desc.color_attachments.len() > max_color_attachments {
1896 return Err(RenderPassErrorInner::ColorAttachment(
1897 ColorAttachmentError::TooMany {
1898 given: desc.color_attachments.len(),
1899 limit: max_color_attachments,
1900 },
1901 ));
1902 }
1903
1904 for color_attachment in desc.color_attachments.iter() {
1905 if let Some(RenderPassColorAttachment {
1906 view,
1907 depth_slice,
1908 resolve_target,
1909 load_op,
1910 store_op,
1911 }) = color_attachment
1912 {
1913 view.check_valid()?;
1914 view.same_device(device)?;
1915 if matches!(*load_op, LoadOp::DontCare(..))
1916 && device
1917 .instance_flags
1918 .contains(InstanceFlags::STRICT_WEBGPU_COMPLIANCE)
1919 {
1920 return Err(RenderPassErrorInner::ColorAttachment(
1921 ColorAttachmentError::LoadOpDontCareUnderStrictWebgpuCompliance,
1922 ));
1923 }
1924
1925 if view
1926 .desc
1927 .usage
1928 .contains(TextureUsages::TRANSIENT_ATTACHMENT)
1929 && !check_transient_attachment_ops(*load_op, *store_op)
1930 {
1931 return Err(RenderPassErrorInner::ColorAttachment(
1932 ColorAttachmentError::InvalidTransientAttachmentOp((
1933 *load_op, *store_op,
1934 )),
1935 ));
1936 }
1937
1938 let resolve_target = if let Some(resolve_target) = resolve_target {
1939 resolve_target.check_valid()?;
1940 resolve_target.same_device(device)?;
1941
1942 Some(resolve_target)
1943 } else {
1944 None
1945 };
1946
1947 arc_desc
1948 .color_attachments
1949 .push(Some(RenderPassColorAttachment {
1950 view: Arc::clone(view),
1951 depth_slice: *depth_slice,
1952 resolve_target: resolve_target.map(Arc::clone),
1953 load_op: *load_op,
1954 store_op: *store_op,
1955 }));
1956 } else {
1957 arc_desc.color_attachments.push(None);
1958 }
1959 }
1960
1961 arc_desc.depth_stencil_attachment = if let Some(depth_stencil_attachment) =
1963 desc.depth_stencil_attachment
1964 {
1965 let view = depth_stencil_attachment.view;
1966 view.check_valid()?;
1967 view.same_device(device)?;
1968
1969 let format = view.desc.format;
1970 if !format.is_depth_stencil_format() {
1971 return Err(RenderPassErrorInner::InvalidAttachment(
1972 AttachmentError::InvalidDepthStencilAttachmentFormat(view.desc.format),
1973 ));
1974 }
1975
1976 #[allow(
1977 clippy::collapsible_match,
1978 reason = "Match guards change which attachment error is returned."
1979 )]
1980 if view
1981 .desc
1982 .usage
1983 .contains(TextureUsages::TRANSIENT_ATTACHMENT)
1984 {
1985 if format.has_depth_aspect() {
1990 match depth_stencil_attachment.depth {
1991 PassChannel {
1992 load_op: Some(load_op),
1993 store_op: Some(store_op),
1994 read_only: _,
1995 } => {
1996 if !check_transient_attachment_ops(load_op, store_op) {
1997 return Err(RenderPassErrorInner::InvalidAttachment(
1998 AttachmentError::InvalidTransientDepthAttachmentOps((
1999 load_op, store_op,
2000 )),
2001 ));
2002 }
2003 }
2004 PassChannel {
2005 read_only: true, ..
2006 } => {
2007 return Err(RenderPassErrorInner::InvalidAttachment(
2008 AttachmentError::ReadOnlyTransientDepthAttachment,
2009 ))
2010 }
2011 _ => {}
2012 }
2013 }
2014
2015 if format.has_stencil_aspect() {
2016 match depth_stencil_attachment.stencil {
2017 PassChannel {
2018 load_op: Some(load_op),
2019 store_op: Some(store_op),
2020 read_only: _,
2021 } => {
2022 if !check_transient_attachment_ops(load_op, store_op) {
2023 return Err(RenderPassErrorInner::InvalidAttachment(
2024 AttachmentError::InvalidTransientStencilAttachmentOps((
2025 load_op, store_op,
2026 )),
2027 ));
2028 }
2029 }
2030 PassChannel {
2031 read_only: true, ..
2032 } => {
2033 return Err(RenderPassErrorInner::InvalidAttachment(
2034 AttachmentError::ReadOnlyTransientStencilAttachment,
2035 ))
2036 }
2037 _ => {}
2038 }
2039 }
2040 }
2041
2042 Some(ResolvedRenderPassDepthStencilAttachment {
2043 view,
2044 depth: if format.has_depth_aspect() {
2045 depth_stencil_attachment
2046 .depth
2047 .resolve(device.instance_flags, |clear| {
2048 if let Some(clear) = clear {
2049 if !(0.0..=1.0).contains(&clear) {
2051 Err(AttachmentError::ClearValueOutOfRange(clear))
2052 } else {
2053 Ok(clear)
2054 }
2055 } else {
2056 Err(AttachmentError::NoClearValue)
2057 }
2058 })?
2059 } else {
2060 if depth_stencil_attachment.depth.load_op.is_some()
2061 || depth_stencil_attachment.depth.store_op.is_some()
2062 {
2063 return Err(RenderPassErrorInner::InvalidAttachment(
2064 AttachmentError::DepthOpsWithoutAspect {
2065 format,
2066 ops: (
2067 depth_stencil_attachment.depth.load_op,
2068 depth_stencil_attachment.depth.store_op,
2069 ),
2070 },
2071 ));
2072 }
2073 ResolvedPassChannel::ReadOnly
2074 },
2075 stencil: if format.has_stencil_aspect() {
2076 depth_stencil_attachment.stencil.resolve(
2077 device.instance_flags,
2078 |clear| {
2079 Ok(convert_stencil_value(
2080 clear.unwrap_or_default(),
2081 Some(format),
2082 ))
2083 },
2084 )?
2085 } else {
2086 if depth_stencil_attachment.stencil.load_op.is_some()
2087 || depth_stencil_attachment.stencil.store_op.is_some()
2088 {
2089 return Err(RenderPassErrorInner::InvalidAttachment(
2090 AttachmentError::StencilOpsWithoutAspect {
2091 format,
2092 ops: (
2093 depth_stencil_attachment.stencil.load_op,
2094 depth_stencil_attachment.stencil.store_op,
2095 ),
2096 },
2097 ));
2098 }
2099 ResolvedPassChannel::ReadOnly
2100 },
2101 })
2102 } else {
2103 None
2104 };
2105
2106 arc_desc.timestamp_writes = desc
2107 .timestamp_writes
2108 .map(|tw| {
2109 CommandEncoder::validate_pass_timestamp_writes::<RenderPassErrorInner>(
2110 device, &tw,
2111 )
2112 })
2113 .transpose()?;
2114
2115 arc_desc.occlusion_query_set =
2116 if let Some(occlusion_query_set) = desc.occlusion_query_set {
2117 occlusion_query_set.check_is_valid()?;
2118 occlusion_query_set.same_device(device)?;
2119
2120 if !matches!(occlusion_query_set.desc.ty, wgt::QueryType::Occlusion) {
2121 return Err(QueryUseError::IncompatibleType {
2122 set_type: occlusion_query_set.desc.ty.into(),
2123 query_type: super::SimplifiedQueryType::Occlusion,
2124 }
2125 .into());
2126 }
2127
2128 Some(occlusion_query_set)
2129 } else {
2130 None
2131 };
2132
2133 arc_desc.multiview_mask = desc.multiview_mask;
2134
2135 Ok(())
2136 }
2137
2138 let scope = PassErrorScope::Pass;
2139 let mut cmd_buf_data = self.data.lock();
2140
2141 match cmd_buf_data.lock_encoder() {
2142 Ok(()) => {
2143 drop(cmd_buf_data);
2144 let label = desc.label.clone();
2145 let mut arc_desc = ArcRenderPassDescriptor {
2146 label: &label,
2147 timestamp_writes: None,
2148 color_attachments: ArrayVec::new(),
2149 depth_stencil_attachment: None,
2150 occlusion_query_set: None,
2151 multiview_mask: None,
2152 };
2153 match fill_arc_desc(desc, &mut arc_desc, &self.device) {
2154 Ok(()) => (RenderPass::new(self.clone(), arc_desc), None),
2155 Err(err) => (
2156 RenderPass::new_invalid(self.clone(), &label, err.map_pass_err(scope)),
2157 None,
2158 ),
2159 }
2160 }
2161 Err(err @ SErr::Locked) => {
2162 cmd_buf_data.invalidate(err.clone());
2166 drop(cmd_buf_data);
2167 (
2168 RenderPass::new_invalid(self.clone(), &desc.label, err.map_pass_err(scope)),
2169 None,
2170 )
2171 }
2172 Err(err @ (SErr::Ended | SErr::Submitted)) => {
2173 drop(cmd_buf_data);
2176 (
2177 RenderPass::new_invalid(
2178 self.clone(),
2179 &desc.label,
2180 err.clone().map_pass_err(scope),
2181 ),
2182 Some(err.into()),
2183 )
2184 }
2185 Err(err @ SErr::Invalid) => {
2186 drop(cmd_buf_data);
2192 (
2193 RenderPass::new_invalid(self.clone(), &desc.label, err.map_pass_err(scope)),
2194 None,
2195 )
2196 }
2197 Err(SErr::Unlocked) => {
2198 unreachable!("lock_encoder cannot fail due to the encoder being unlocked")
2199 }
2200 }
2201 }
2202
2203 pub fn begin_render_pass(
2204 self: &Arc<Self>,
2205 desc: ResolvedRenderPassDescriptor<'_>,
2206 ) -> RenderPass {
2207 let (pass, err) = self.begin_render_pass_inner(desc);
2208 if let Some(err) = err {
2209 self.device
2210 .handle_error(err, pass.label(), "CommandEncoder::begin_render_pass");
2211 }
2212 pass
2213 }
2214}
2215
2216impl RenderPass {
2217 fn end_inner(&mut self) -> Result<(), EncoderStateError> {
2218 profiling::scope!(
2219 "CommandEncoder::run_render_pass {}",
2220 self.base.label.as_deref().unwrap_or("")
2221 );
2222
2223 let cmd_enc = self.parent.take().ok_or(EncoderStateError::Ended)?;
2224 let mut cmd_buf_data = cmd_enc.data.lock();
2225
2226 cmd_buf_data.unlock_encoder()?;
2227
2228 let base = self.base.take();
2229
2230 if let Err(RenderPassError { inner, scope: _ }) = &base {
2231 if let RenderPassErrorInner::EncoderState(
2232 err @ (EncoderStateError::Locked | EncoderStateError::Ended),
2233 ) = inner.as_ref()
2234 {
2235 return Err(err.clone());
2242 }
2243 }
2244
2245 cmd_buf_data.push_with(|| -> Result<_, RenderPassError> {
2246 Ok(ArcCommand::RunRenderPass {
2247 pass: base?,
2248 color_attachments: SmallVec::from(self.color_attachments.as_slice()),
2249 depth_stencil_attachment: self.depth_stencil_attachment.take(),
2250 timestamp_writes: self.timestamp_writes.take(),
2251 occlusion_query_set: self.occlusion_query_set.take(),
2252 multiview_mask: self.multiview_mask,
2253 })
2254 })
2255 }
2256
2257 pub fn end(&mut self) {
2258 if let Err(err) = self.end_inner() {
2259 self.device
2260 .handle_error(err, self.label(), "RenderPass::end");
2261 }
2262 }
2263}
2264
2265pub(super) fn encode_render_pass(
2266 parent_state: &mut EncodingState<InnerCommandEncoder>,
2267 mut base: BasePass<ArcRenderCommand, Infallible>,
2268 color_attachments: ColorAttachments<Arc<TextureView>>,
2269 mut depth_stencil_attachment: Option<
2270 ResolvedRenderPassDepthStencilAttachment<Arc<TextureView>>,
2271 >,
2272 mut timestamp_writes: Option<PassTimestampWrites>,
2273 occlusion_query_set: Option<Arc<QuerySet>>,
2274 multiview_mask: Option<NonZeroU32>,
2275) -> Result<(), RenderPassError> {
2276 let pass_scope = PassErrorScope::Pass;
2277
2278 let device = parent_state.device;
2279
2280 let mut indirect_draw_validation_batcher = crate::indirect_validation::DrawBatcher::new();
2281
2282 parent_state
2286 .raw_encoder
2287 .close_if_open()
2288 .map_pass_err(pass_scope)?;
2289 let raw_encoder = parent_state
2290 .raw_encoder
2291 .open_pass(base.label.as_deref())
2292 .map_pass_err(pass_scope)?;
2293
2294 let (scope, pending_discard_init_fixups, mut pending_query_resets) = {
2295 let mut pending_query_resets = QueryResetMap::new();
2296 let mut pending_discard_init_fixups = SurfacesInDiscardState::new();
2297
2298 let info = RenderPassInfo::start(
2299 device,
2300 hal_label(base.label.as_deref(), device.instance_flags),
2301 &color_attachments,
2302 depth_stencil_attachment.take(),
2303 timestamp_writes.take(),
2304 occlusion_query_set.clone(),
2307 raw_encoder,
2308 parent_state.tracker,
2309 parent_state.texture_memory_actions,
2310 &mut pending_query_resets,
2311 &mut pending_discard_init_fixups,
2312 parent_state.snatch_guard,
2313 parent_state.query_set_writes,
2314 multiview_mask,
2315 )
2316 .map_pass_err(pass_scope)?;
2317
2318 let indices = &device.tracker_indices;
2319 parent_state
2320 .tracker
2321 .buffers
2322 .set_size(indices.buffers.size());
2323 parent_state
2324 .tracker
2325 .textures
2326 .set_size(indices.textures.size());
2327
2328 let mut debug_scope_depth = 0;
2329
2330 let mut state = State {
2331 pipeline_flags: PipelineFlags::empty(),
2332 blend_constant: OptionalState::Unused,
2333 stencil_reference: 0,
2334 pipeline: None,
2335 index: IndexState::default(),
2336 vertex: VertexState::default(),
2337
2338 info,
2339
2340 pass: pass::PassState {
2341 base: EncodingState {
2342 device,
2343 raw_encoder,
2344 tracker: parent_state.tracker,
2345 buffer_memory_init_actions: parent_state.buffer_memory_init_actions,
2346 texture_memory_actions: parent_state.texture_memory_actions,
2347 as_actions: parent_state.as_actions,
2348 temp_resources: parent_state.temp_resources,
2349 indirect_draw_validation_resources: parent_state
2350 .indirect_draw_validation_resources,
2351 snatch_guard: parent_state.snatch_guard,
2352 debug_scope_depth: &mut debug_scope_depth,
2353 query_set_writes: parent_state.query_set_writes,
2354 deferred_query_set_resolves: parent_state.deferred_query_set_resolves,
2355 },
2356 pending_discard_init_fixups,
2357 scope: device.new_usage_scope(),
2358 binder: Binder::new(),
2359
2360 temp_offsets: Vec::new(),
2361 dynamic_offset_count: 0,
2362
2363 string_offset: 0,
2364
2365 immediate_state: ImmediateState::default(),
2366 },
2367
2368 active_occlusion_query: None,
2369 active_pipeline_statistics_query: None,
2370 };
2371
2372 for command in base.commands.drain(..) {
2373 match command {
2374 ArcRenderCommand::SetBindGroup {
2375 index,
2376 num_dynamic_offsets,
2377 bind_group,
2378 } => {
2379 let scope = PassErrorScope::SetBindGroup;
2380 pass::set_bind_group::<RenderPassErrorInner>(
2381 &mut state.pass,
2382 device,
2383 &base.dynamic_offsets,
2384 index,
2385 num_dynamic_offsets,
2386 bind_group,
2387 true,
2388 )
2389 .map_pass_err(scope)?;
2390 }
2391 ArcRenderCommand::SetPipeline(pipeline) => {
2392 let scope = PassErrorScope::SetPipelineRender;
2393 set_pipeline(&mut state, device, pipeline).map_pass_err(scope)?;
2394 }
2395 ArcRenderCommand::SetIndexBuffer {
2396 buffer,
2397 index_format,
2398 offset,
2399 size,
2400 } => {
2401 let scope = PassErrorScope::SetIndexBuffer;
2402 set_index_buffer(&mut state, device, buffer, index_format, offset, size)
2403 .map_pass_err(scope)?;
2404 }
2405 ArcRenderCommand::SetVertexBuffer {
2406 slot,
2407 buffer,
2408 offset,
2409 size,
2410 } => {
2411 let scope = PassErrorScope::SetVertexBuffer;
2412 set_vertex_buffer(&mut state, device, slot, buffer, offset, size)
2413 .map_pass_err(scope)?;
2414 }
2415 ArcRenderCommand::SetBlendConstant(ref color) => {
2416 set_blend_constant(&mut state, color);
2417 }
2418 ArcRenderCommand::SetStencilReference(value) => {
2419 set_stencil_reference(&mut state, value);
2420 }
2421 ArcRenderCommand::SetViewport {
2422 rect,
2423 depth_min,
2424 depth_max,
2425 } => {
2426 let scope = PassErrorScope::SetViewport;
2427 set_viewport(&mut state, rect, depth_min, depth_max).map_pass_err(scope)?;
2428 }
2429 ArcRenderCommand::SetImmediate { offset, data } => {
2430 let scope = PassErrorScope::SetImmediate;
2431 state
2432 .pass
2433 .immediate_state
2434 .set_immediates::<RenderPassErrorInner>(
2435 &state.pass.base.device.limits,
2436 offset,
2437 &data,
2438 )
2439 .map_pass_err(scope)?;
2440 }
2441 ArcRenderCommand::SetScissor(rect) => {
2442 let scope = PassErrorScope::SetScissorRect;
2443 set_scissor(&mut state, rect).map_pass_err(scope)?;
2444 }
2445 ArcRenderCommand::Draw {
2446 vertex_count,
2447 instance_count,
2448 first_vertex,
2449 first_instance,
2450 } => {
2451 let scope = PassErrorScope::Draw {
2452 kind: DrawKind::Draw,
2453 family: DrawCommandFamily::Draw,
2454 };
2455 draw(
2456 &mut state,
2457 vertex_count,
2458 instance_count,
2459 first_vertex,
2460 first_instance,
2461 )
2462 .map_pass_err(scope)?;
2463 }
2464 ArcRenderCommand::DrawIndexed {
2465 index_count,
2466 instance_count,
2467 first_index,
2468 base_vertex,
2469 first_instance,
2470 } => {
2471 let scope = PassErrorScope::Draw {
2472 kind: DrawKind::Draw,
2473 family: DrawCommandFamily::DrawIndexed,
2474 };
2475 draw_indexed(
2476 &mut state,
2477 index_count,
2478 instance_count,
2479 first_index,
2480 base_vertex,
2481 first_instance,
2482 )
2483 .map_pass_err(scope)?;
2484 }
2485 ArcRenderCommand::DrawMeshTasks {
2486 group_count_x,
2487 group_count_y,
2488 group_count_z,
2489 } => {
2490 let scope = PassErrorScope::Draw {
2491 kind: DrawKind::Draw,
2492 family: DrawCommandFamily::DrawMeshTasks,
2493 };
2494 draw_mesh_tasks(&mut state, group_count_x, group_count_y, group_count_z)
2495 .map_pass_err(scope)?;
2496 }
2497 ArcRenderCommand::DrawIndirect {
2498 buffer,
2499 offset,
2500 count,
2501 family,
2502
2503 vertex_or_index_limit: _,
2504 instance_limit: _,
2505 } => {
2506 let scope = PassErrorScope::Draw {
2507 kind: if count != 1 {
2508 DrawKind::MultiDrawIndirect
2509 } else {
2510 DrawKind::DrawIndirect
2511 },
2512 family,
2513 };
2514 multi_draw_indirect(
2515 &mut state,
2516 &mut indirect_draw_validation_batcher,
2517 device,
2518 buffer,
2519 offset,
2520 count,
2521 family,
2522 )
2523 .map_pass_err(scope)?;
2524 }
2525 ArcRenderCommand::MultiDrawIndirectCount {
2526 buffer,
2527 offset,
2528 count_buffer,
2529 count_buffer_offset,
2530 max_count,
2531 family,
2532 } => {
2533 let scope = PassErrorScope::Draw {
2534 kind: DrawKind::MultiDrawIndirectCount,
2535 family,
2536 };
2537 multi_draw_indirect_count(
2538 &mut state,
2539 device,
2540 buffer,
2541 offset,
2542 count_buffer,
2543 count_buffer_offset,
2544 max_count,
2545 family,
2546 )
2547 .map_pass_err(scope)?;
2548 }
2549 ArcRenderCommand::PushDebugGroup { color: _, len } => {
2550 pass::push_debug_group(&mut state.pass, &base.string_data, len);
2551 }
2552 ArcRenderCommand::PopDebugGroup => {
2553 let scope = PassErrorScope::PopDebugGroup;
2554 pass::pop_debug_group::<RenderPassErrorInner>(&mut state.pass)
2555 .map_pass_err(scope)?;
2556 }
2557 ArcRenderCommand::InsertDebugMarker { color: _, len } => {
2558 pass::insert_debug_marker(&mut state.pass, &base.string_data, len);
2559 }
2560 ArcRenderCommand::WriteTimestamp {
2561 query_set,
2562 query_index,
2563 } => {
2564 let scope = PassErrorScope::WriteTimestamp;
2565 pass::write_timestamp::<RenderPassErrorInner>(
2566 &mut state.pass,
2567 device,
2568 Some(&mut pending_query_resets),
2569 query_set,
2570 query_index,
2571 )
2572 .map_pass_err(scope)?;
2573 }
2574 ArcRenderCommand::BeginOcclusionQuery { query_index } => {
2575 api_log!("RenderPass::begin_occlusion_query {query_index}");
2576 let scope = PassErrorScope::BeginOcclusionQuery;
2577
2578 let query_set = occlusion_query_set
2579 .clone()
2580 .ok_or(RenderPassErrorInner::MissingOcclusionQuerySet)
2581 .map_pass_err(scope)?;
2582
2583 validate_and_begin_occlusion_query(
2584 query_set,
2585 state.pass.base.raw_encoder,
2586 &mut state.pass.base.tracker.query_sets,
2587 query_index,
2588 Some(&mut pending_query_resets),
2589 &mut state.active_occlusion_query,
2590 state.pass.base.snatch_guard,
2591 )
2592 .map_pass_err(scope)?;
2593 }
2594 ArcRenderCommand::EndOcclusionQuery => {
2595 api_log!("RenderPass::end_occlusion_query");
2596 let scope = PassErrorScope::EndOcclusionQuery;
2597
2598 end_occlusion_query(
2599 state.pass.base.raw_encoder,
2600 &mut state.active_occlusion_query,
2601 state.pass.base.snatch_guard,
2602 state.pass.base.query_set_writes,
2603 )
2604 .map_pass_err(scope)?;
2605 }
2606 ArcRenderCommand::BeginPipelineStatisticsQuery {
2607 query_set,
2608 query_index,
2609 } => {
2610 api_log!(
2611 "RenderPass::begin_pipeline_statistics_query {query_index} {}",
2612 query_set.error_ident()
2613 );
2614 let scope = PassErrorScope::BeginPipelineStatisticsQuery;
2615
2616 validate_and_begin_pipeline_statistics_query(
2617 query_set,
2618 state.pass.base.raw_encoder,
2619 &mut state.pass.base.tracker.query_sets,
2620 device,
2621 query_index,
2622 Some(&mut pending_query_resets),
2623 &mut state.active_pipeline_statistics_query,
2624 state.pass.base.snatch_guard,
2625 )
2626 .map_pass_err(scope)?;
2627 }
2628 ArcRenderCommand::EndPipelineStatisticsQuery => {
2629 api_log!("RenderPass::end_pipeline_statistics_query");
2630 let scope = PassErrorScope::EndPipelineStatisticsQuery;
2631
2632 end_pipeline_statistics_query(
2633 state.pass.base.raw_encoder,
2634 &mut state.active_pipeline_statistics_query,
2635 state.pass.base.snatch_guard,
2636 state.pass.base.query_set_writes,
2637 )
2638 .map_pass_err(scope)?;
2639 }
2640 ArcRenderCommand::ExecuteBundle(bundle) => {
2641 let scope = PassErrorScope::ExecuteBundle;
2642 execute_bundle(
2643 &mut state,
2644 &mut indirect_draw_validation_batcher,
2645 device,
2646 bundle,
2647 )
2648 .map_pass_err(scope)?;
2649 }
2650 }
2651 }
2652
2653 if *state.pass.base.debug_scope_depth > 0 {
2654 Err(
2655 RenderPassErrorInner::DebugGroupError(DebugGroupError::MissingPop)
2656 .map_pass_err(pass_scope),
2657 )?;
2658 }
2659 if state.active_occlusion_query.is_some() {
2660 Err(RenderPassErrorInner::QueryUse(QueryUseError::MissingEnd {
2661 query_type: super::SimplifiedQueryType::Occlusion,
2662 })
2663 .map_pass_err(pass_scope))?;
2664 }
2665 if state.active_pipeline_statistics_query.is_some() {
2666 Err(RenderPassErrorInner::QueryUse(QueryUseError::MissingEnd {
2667 query_type: super::SimplifiedQueryType::PipelineStatistics,
2668 })
2669 .map_pass_err(pass_scope))?;
2670 }
2671
2672 state
2673 .info
2674 .finish(
2675 device,
2676 state.pass.base.raw_encoder,
2677 state.pass.base.snatch_guard,
2678 &mut state.pass.scope,
2679 device.instance_flags,
2680 )
2681 .map_pass_err(pass_scope)?;
2682
2683 let trackers = state.pass.scope;
2684
2685 let pending_discard_init_fixups = state.pass.pending_discard_init_fixups;
2686
2687 parent_state.raw_encoder.close().map_pass_err(pass_scope)?;
2688 (trackers, pending_discard_init_fixups, pending_query_resets)
2689 };
2690
2691 let encoder = &mut parent_state.raw_encoder;
2692 let tracker = &mut parent_state.tracker;
2693
2694 {
2695 let transit = encoder
2696 .open_pass(hal_label(
2697 Some("(wgpu internal) Pre Pass"),
2698 device.instance_flags,
2699 ))
2700 .map_pass_err(pass_scope)?;
2701
2702 fixup_discarded_surfaces(
2705 pending_discard_init_fixups.into_iter(),
2706 transit,
2707 &mut tracker.textures,
2708 device,
2709 parent_state.snatch_guard,
2710 );
2711
2712 pending_query_resets
2713 .reset_queries(transit, parent_state.snatch_guard)
2714 .map_pass_err(pass_scope)?;
2715
2716 CommandEncoder::insert_barriers_from_scope(
2717 transit,
2718 tracker,
2719 &scope,
2720 parent_state.snatch_guard,
2721 );
2722
2723 if let Some(ref indirect_validation) = device.indirect_validation {
2724 indirect_validation
2725 .draw
2726 .inject_validation_pass(
2727 device,
2728 parent_state.snatch_guard,
2729 parent_state.indirect_draw_validation_resources,
2730 parent_state.temp_resources,
2731 transit,
2732 indirect_draw_validation_batcher,
2733 )
2734 .map_pass_err(pass_scope)?;
2735 }
2736 }
2737
2738 encoder.close_and_swap().map_pass_err(pass_scope)?;
2739
2740 Ok(())
2741}
2742
2743fn set_pipeline(
2744 state: &mut State,
2745 device: &Arc<Device>,
2746 pipeline: Arc<RenderPipeline>,
2747) -> Result<(), RenderPassErrorInner> {
2748 api_log!("RenderPass::set_pipeline {}", pipeline.error_ident());
2749
2750 state.pipeline = Some(pipeline.clone());
2751
2752 let pipeline = state
2753 .pass
2754 .base
2755 .tracker
2756 .render_pipelines
2757 .insert_single(pipeline)
2758 .clone();
2759
2760 pipeline.same_device(device)?;
2761
2762 state
2763 .info
2764 .context
2765 .check_compatible(&pipeline.pass_context, pipeline.as_ref())
2766 .map_err(RenderCommandError::IncompatiblePipelineTargets)?;
2767
2768 state.pipeline_flags = pipeline.flags;
2769
2770 if pipeline.flags.contains(PipelineFlags::WRITES_DEPTH) && state.info.is_depth_read_only {
2771 return Err(RenderCommandError::IncompatibleDepthAccess(pipeline.error_ident()).into());
2772 }
2773 if pipeline.flags.contains(PipelineFlags::WRITES_STENCIL) && state.info.is_stencil_read_only {
2774 return Err(RenderCommandError::IncompatibleStencilAccess(pipeline.error_ident()).into());
2775 }
2776
2777 state
2778 .blend_constant
2779 .require(pipeline.flags.contains(PipelineFlags::BLEND_CONSTANT));
2780
2781 unsafe {
2782 state
2783 .pass
2784 .base
2785 .raw_encoder
2786 .set_render_pipeline(pipeline.raw()?);
2787 }
2788
2789 if pipeline.flags.contains(PipelineFlags::STENCIL_REFERENCE) {
2790 unsafe {
2791 state
2792 .pass
2793 .base
2794 .raw_encoder
2795 .set_stencil_reference(state.stencil_reference);
2796 }
2797 }
2798
2799 pass::change_pipeline_layout::<RenderPassErrorInner>(
2801 &mut state.pass,
2802 pipeline.layout()?,
2803 &pipeline.late_sized_buffer_groups,
2804 )?;
2805
2806 state.vertex.update_limits(&pipeline.vertex_steps);
2808 Ok(())
2809}
2810
2811fn set_index_buffer(
2813 state: &mut State,
2814 device: &Arc<Device>,
2815 buffer: Arc<Buffer>,
2816 index_format: IndexFormat,
2817 offset: u64,
2818 size: Option<BufferAddress>,
2819) -> Result<(), RenderPassErrorInner> {
2820 api_log!("RenderPass::set_index_buffer {}", buffer.error_ident());
2821
2822 state
2823 .pass
2824 .scope
2825 .buffers
2826 .merge_single(&buffer, wgt::BufferUses::INDEX)?;
2827
2828 buffer.same_device(device)?;
2829
2830 buffer.check_usage(BufferUsages::INDEX)?;
2831
2832 if !offset.is_multiple_of(u64::from(index_format.byte_size())) {
2833 return Err(RenderCommandError::UnalignedIndexBuffer {
2834 offset,
2835 alignment: index_format.byte_size() as usize,
2836 }
2837 .into());
2838 }
2839
2840 let range = buffer
2841 .resolve_vertex_or_index_binding_range(offset, size)
2842 .map_err(RenderCommandError::from)?;
2843
2844 let raw = buffer.try_raw(state.pass.base.snatch_guard)?;
2845
2846 state.index.update_buffer(range.clone(), index_format);
2847
2848 state.pass.base.buffer_memory_init_actions.extend(
2849 buffer.initialization_status.read().create_action(
2850 &buffer,
2851 range.clone(),
2852 MemoryInitKind::NeedsInitializedMemory,
2853 ),
2854 );
2855
2856 unsafe {
2857 hal::DynCommandEncoder::set_index_buffer(
2859 state.pass.base.raw_encoder,
2860 hal::BufferBinding::new_unchecked(raw, range.start, range.end - range.start),
2861 index_format,
2862 );
2863 }
2864 Ok(())
2865}
2866
2867fn set_vertex_buffer(
2869 state: &mut State,
2870 device: &Arc<Device>,
2871 slot: u32,
2872 buffer: Option<Arc<Buffer>>,
2873 offset: u64,
2874 size: Option<BufferAddress>,
2875) -> Result<(), RenderPassErrorInner> {
2876 if let Some(ref buffer) = buffer {
2877 api_log!(
2878 "RenderPass::set_vertex_buffer {slot} {}",
2879 buffer.error_ident()
2880 );
2881 } else {
2882 api_log!("RenderPass::set_vertex_buffer {slot} None");
2883 }
2884
2885 let max_vertex_buffers = state.pass.base.device.limits.max_vertex_buffers;
2886 if slot >= max_vertex_buffers {
2887 return Err(RenderCommandError::VertexBufferIndexOutOfRange {
2888 index: slot,
2889 max: max_vertex_buffers,
2890 }
2891 .into());
2892 }
2893
2894 if let Some(buffer) = buffer {
2895 buffer.same_device(device)?;
2896 buffer.check_usage(BufferUsages::VERTEX)?;
2897
2898 if !offset.is_multiple_of(wgt::VERTEX_ALIGNMENT) {
2899 return Err(RenderCommandError::UnalignedVertexBuffer { slot, offset }.into());
2900 }
2901 let range = buffer
2902 .resolve_vertex_or_index_binding_range(offset, size)
2903 .map_err(RenderCommandError::from)?;
2904
2905 state
2906 .pass
2907 .scope
2908 .buffers
2909 .merge_single(&buffer, wgt::BufferUses::VERTEX)?;
2910
2911 state.pass.base.buffer_memory_init_actions.extend(
2912 buffer.initialization_status.read().create_action(
2913 &buffer,
2914 range.clone(),
2915 MemoryInitKind::NeedsInitializedMemory,
2916 ),
2917 );
2918
2919 state
2920 .vertex
2921 .set_buffer(slot as usize, buffer, range.clone());
2922 if let Some(pipeline) = state.pipeline.as_ref() {
2923 state.vertex.update_limits(&pipeline.vertex_steps);
2924 }
2925 } else {
2926 if offset != 0 {
2927 return Err(RenderCommandError::from(
2928 crate::binding_model::BindingError::UnbindingVertexBufferOffsetNotZero {
2929 slot,
2930 offset,
2931 },
2932 )
2933 .into());
2934 }
2935 match size {
2936 Some(size) if size != 0 => {
2937 return Err(RenderCommandError::from(
2938 crate::binding_model::BindingError::UnbindingVertexBufferSizeNotZero {
2939 slot,
2940 size,
2941 },
2942 )
2943 .into());
2944 }
2945 _ => {}
2946 }
2947
2948 state.vertex.clear_buffer(slot as usize);
2949 if let Some(pipeline) = state.pipeline.as_ref() {
2950 state.vertex.update_limits(&pipeline.vertex_steps);
2951 }
2952 }
2953
2954 Ok(())
2955}
2956
2957fn set_blend_constant(state: &mut State, color: &Color) {
2958 api_log!("RenderPass::set_blend_constant");
2959
2960 state.blend_constant = OptionalState::Set;
2961 let array = [
2962 color.r as f32,
2963 color.g as f32,
2964 color.b as f32,
2965 color.a as f32,
2966 ];
2967 unsafe {
2968 state.pass.base.raw_encoder.set_blend_constants(&array);
2969 }
2970}
2971
2972fn set_stencil_reference(state: &mut State, value: u32) {
2973 api_log!("RenderPass::set_stencil_reference {value}");
2974
2975 state.stencil_reference = value;
2976 if state
2977 .pipeline_flags
2978 .contains(PipelineFlags::STENCIL_REFERENCE)
2979 {
2980 unsafe {
2981 state.pass.base.raw_encoder.set_stencil_reference(value);
2982 }
2983 }
2984}
2985
2986fn set_viewport(
2987 state: &mut State,
2988 rect: Rect<f32>,
2989 depth_min: f32,
2990 depth_max: f32,
2991) -> Result<(), RenderPassErrorInner> {
2992 api_log!("RenderPass::set_viewport {rect:?}");
2993
2994 if rect.w < 0.0
2995 || rect.h < 0.0
2996 || rect.w > state.pass.base.device.limits.max_texture_dimension_2d as f32
2997 || rect.h > state.pass.base.device.limits.max_texture_dimension_2d as f32
2998 {
2999 return Err(RenderCommandError::InvalidViewportRectSize {
3000 w: rect.w,
3001 h: rect.h,
3002 max: state.pass.base.device.limits.max_texture_dimension_2d,
3003 }
3004 .into());
3005 }
3006
3007 let max_viewport_range = state.pass.base.device.limits.max_texture_dimension_2d as f32 * 2.0;
3008
3009 if rect.x < -max_viewport_range
3010 || rect.y < -max_viewport_range
3011 || rect.x + rect.w > max_viewport_range - 1.0
3012 || rect.y + rect.h > max_viewport_range - 1.0
3013 {
3014 return Err(RenderCommandError::InvalidViewportRectPosition {
3015 rect,
3016 min: -max_viewport_range,
3017 max: max_viewport_range - 1.0,
3018 }
3019 .into());
3020 }
3021 if !(0.0..=1.0).contains(&depth_min)
3022 || !(0.0..=1.0).contains(&depth_max)
3023 || depth_min > depth_max
3024 {
3025 return Err(RenderCommandError::InvalidViewportDepth(depth_min, depth_max).into());
3026 }
3027 let r = hal::Rect {
3028 x: rect.x,
3029 y: rect.y,
3030 w: rect.w,
3031 h: rect.h,
3032 };
3033 unsafe {
3034 state
3035 .pass
3036 .base
3037 .raw_encoder
3038 .set_viewport(&r, depth_min..depth_max);
3039 }
3040 Ok(())
3041}
3042
3043fn set_scissor(state: &mut State, rect: Rect<u32>) -> Result<(), RenderPassErrorInner> {
3044 api_log!("RenderPass::set_scissor_rect {rect:?}");
3045
3046 if rect.x.saturating_add(rect.w) > state.info.extent.width
3047 || rect.y.saturating_add(rect.h) > state.info.extent.height
3048 {
3049 return Err(RenderCommandError::InvalidScissorRect(rect, state.info.extent).into());
3050 }
3051 let r = hal::Rect {
3052 x: rect.x,
3053 y: rect.y,
3054 w: rect.w,
3055 h: rect.h,
3056 };
3057 unsafe {
3058 state.pass.base.raw_encoder.set_scissor_rect(&r);
3059 }
3060 Ok(())
3061}
3062
3063fn draw(
3064 state: &mut State,
3065 vertex_count: u32,
3066 instance_count: u32,
3067 first_vertex: u32,
3068 first_instance: u32,
3069) -> Result<(), RenderPassErrorInner> {
3070 api_log!("RenderPass::draw {vertex_count} {instance_count} {first_vertex} {first_instance}");
3071
3072 state.is_ready(DrawCommandFamily::Draw)?;
3073 state.flush_vertex_buffers()?;
3074 state.flush_bindings()?;
3075 state.flush_immediates();
3076
3077 state
3078 .vertex
3079 .limits
3080 .validate_vertex_limit(first_vertex, vertex_count)?;
3081 state
3082 .vertex
3083 .limits
3084 .validate_instance_limit(first_instance, instance_count)?;
3085
3086 unsafe {
3087 if instance_count > 0 && vertex_count > 0 {
3088 state.pass.base.raw_encoder.draw(
3089 first_vertex,
3090 vertex_count,
3091 first_instance,
3092 instance_count,
3093 );
3094 }
3095 }
3096 Ok(())
3097}
3098
3099fn draw_indexed(
3100 state: &mut State,
3101 index_count: u32,
3102 instance_count: u32,
3103 first_index: u32,
3104 base_vertex: i32,
3105 first_instance: u32,
3106) -> Result<(), RenderPassErrorInner> {
3107 api_log!("RenderPass::draw_indexed {index_count} {instance_count} {first_index} {base_vertex} {first_instance}");
3108
3109 state.is_ready(DrawCommandFamily::DrawIndexed)?;
3110 state.flush_vertex_buffers()?;
3111 state.flush_bindings()?;
3112 state.flush_immediates();
3113
3114 let last_index = first_index as u64 + index_count as u64;
3115 let index_limit = state.index.limit;
3116 if last_index > index_limit {
3117 return Err(DrawError::IndexBeyondLimit {
3118 last_index,
3119 index_limit,
3120 }
3121 .into());
3122 }
3123 state
3124 .vertex
3125 .limits
3126 .validate_instance_limit(first_instance, instance_count)?;
3127
3128 unsafe {
3129 if instance_count > 0 && index_count > 0 {
3130 state.pass.base.raw_encoder.draw_indexed(
3131 first_index,
3132 index_count,
3133 base_vertex,
3134 first_instance,
3135 instance_count,
3136 );
3137 }
3138 }
3139 Ok(())
3140}
3141
3142fn draw_mesh_tasks(
3143 state: &mut State,
3144 group_count_x: u32,
3145 group_count_y: u32,
3146 group_count_z: u32,
3147) -> Result<(), RenderPassErrorInner> {
3148 api_log!("RenderPass::draw_mesh_tasks {group_count_x} {group_count_y} {group_count_z}");
3149
3150 state.is_ready(DrawCommandFamily::DrawMeshTasks)?;
3151
3152 state.flush_bindings()?;
3153 state.flush_immediates();
3154 validate_mesh_draw_multiview(state.pass.base.device, state.info.multiview_mask)?;
3155
3156 let limits = &state.pass.base.device.limits;
3157 let (groups_size_limit, max_groups) = if state.pipeline.as_ref().unwrap().has_task_shader {
3158 (
3159 limits.max_task_workgroups_per_dimension,
3160 limits.max_task_workgroup_total_count,
3161 )
3162 } else {
3163 (
3164 limits.max_mesh_workgroups_per_dimension,
3165 limits.max_mesh_workgroup_total_count,
3166 )
3167 };
3168
3169 let total_count = WorkgroupSizeCheck {
3170 dimensions: &[group_count_x, group_count_y, group_count_z],
3171 per_dimension_limits: &[groups_size_limit, groups_size_limit, groups_size_limit],
3172 per_dimension_limits_desc: "max_task_mesh_workgroups_per_dimension",
3173
3174 total_limit: max_groups,
3175 total_limit_desc: "max_task_mesh_workgroup_total_count",
3176 }
3177 .check_and_compute_total_invocations()
3178 .map_err(|err| RenderPassErrorInner::Draw(err.into()))?;
3179
3180 unsafe {
3181 if total_count > 0 {
3182 state.pass.base.raw_encoder.draw_mesh_tasks(
3183 group_count_x,
3184 group_count_y,
3185 group_count_z,
3186 );
3187 }
3188 }
3189 Ok(())
3190}
3191
3192fn multi_draw_indirect(
3193 state: &mut State,
3194 indirect_draw_validation_batcher: &mut crate::indirect_validation::DrawBatcher,
3195 device: &Arc<Device>,
3196 indirect_buffer: Arc<Buffer>,
3197 offset: u64,
3198 count: u32,
3199 family: DrawCommandFamily,
3200) -> Result<(), RenderPassErrorInner> {
3201 api_log!(
3202 "RenderPass::draw_indirect (family:{family:?}) {} {offset} {count:?}",
3203 indirect_buffer.error_ident()
3204 );
3205
3206 state.is_ready(family)?;
3207 state.flush_vertex_buffers()?;
3208 state.flush_bindings()?;
3209 state.flush_immediates();
3210
3211 if family == DrawCommandFamily::DrawMeshTasks {
3212 validate_mesh_draw_multiview(state.pass.base.device, state.info.multiview_mask)?;
3213 }
3214
3215 state
3216 .pass
3217 .base
3218 .device
3219 .require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
3220
3221 indirect_buffer.same_device(device)?;
3222 indirect_buffer.check_usage(BufferUsages::INDIRECT)?;
3223 indirect_buffer.check_destroyed(state.pass.base.snatch_guard)?;
3224
3225 if !offset.is_multiple_of(4) {
3226 return Err(RenderCommandError::UnalignedIndirectBufferOffset(offset).into());
3227 }
3228
3229 let stride = get_src_stride_of_indirect_args(family);
3230 let args_size = match stride.checked_mul(u64::from(count)) {
3231 Some(sz) if sz <= indirect_buffer.size && indirect_buffer.size - sz >= offset => sz,
3232 args_size => {
3233 return Err(RenderCommandError::IndirectBufferOverrun {
3234 count,
3235 offset,
3236 args_size: args_size.unwrap_or(u64::MAX),
3237 buffer_size: indirect_buffer.size,
3238 }
3239 .into());
3240 }
3241 };
3242
3243 state.pass.base.buffer_memory_init_actions.extend(
3244 indirect_buffer.initialization_status.read().create_action(
3245 &indirect_buffer,
3246 offset..offset + args_size,
3247 MemoryInitKind::NeedsInitializedMemory,
3248 ),
3249 );
3250
3251 fn draw(
3252 raw_encoder: &mut dyn hal::DynCommandEncoder,
3253 family: DrawCommandFamily,
3254 indirect_buffer: &dyn hal::DynBuffer,
3255 offset: u64,
3256 count: u32,
3257 ) {
3258 match family {
3259 DrawCommandFamily::Draw => unsafe {
3260 raw_encoder.draw_indirect(indirect_buffer, offset, count);
3261 },
3262 DrawCommandFamily::DrawIndexed => unsafe {
3263 raw_encoder.draw_indexed_indirect(indirect_buffer, offset, count);
3264 },
3265 DrawCommandFamily::DrawMeshTasks => unsafe {
3266 raw_encoder.draw_mesh_tasks_indirect(indirect_buffer, offset, count);
3267 },
3268 }
3269 }
3270
3271 if state.pass.base.device.indirect_validation.is_some()
3272 && family != DrawCommandFamily::DrawMeshTasks
3273 {
3274 state
3275 .pass
3276 .scope
3277 .buffers
3278 .merge_single(&indirect_buffer, wgt::BufferUses::STORAGE_READ_ONLY)?;
3279
3280 struct DrawData {
3281 buffer_index: usize,
3282 offset: u64,
3283 count: u32,
3284 }
3285
3286 struct DrawContext<'a> {
3287 raw_encoder: &'a mut dyn hal::DynCommandEncoder,
3288 device: &'a Device,
3289
3290 indirect_draw_validation_resources: &'a mut crate::indirect_validation::DrawResources,
3291 indirect_draw_validation_batcher: &'a mut crate::indirect_validation::DrawBatcher,
3292
3293 indirect_buffer: Arc<Buffer>,
3294 family: DrawCommandFamily,
3295 vertex_or_index_limit: u64,
3296 instance_limit: u64,
3297 }
3298
3299 impl<'a> DrawContext<'a> {
3300 fn add(&mut self, offset: u64) -> Result<DrawData, DeviceError> {
3301 let (dst_resource_index, dst_offset) = self.indirect_draw_validation_batcher.add(
3302 self.indirect_draw_validation_resources,
3303 self.device,
3304 &self.indirect_buffer,
3305 offset,
3306 self.family,
3307 self.vertex_or_index_limit,
3308 self.instance_limit,
3309 )?;
3310 Ok(DrawData {
3311 buffer_index: dst_resource_index,
3312 offset: dst_offset,
3313 count: 1,
3314 })
3315 }
3316 fn draw(&mut self, draw_data: DrawData) {
3317 let dst_buffer = self
3318 .indirect_draw_validation_resources
3319 .get_dst_buffer(draw_data.buffer_index);
3320 draw(
3321 self.raw_encoder,
3322 self.family,
3323 dst_buffer,
3324 draw_data.offset,
3325 draw_data.count,
3326 );
3327 }
3328 }
3329
3330 let mut draw_ctx = DrawContext {
3331 raw_encoder: state.pass.base.raw_encoder,
3332 device: state.pass.base.device,
3333 indirect_draw_validation_resources: state.pass.base.indirect_draw_validation_resources,
3334 indirect_draw_validation_batcher,
3335 indirect_buffer,
3336 family,
3337 vertex_or_index_limit: if family == DrawCommandFamily::DrawIndexed {
3338 state.index.limit
3339 } else {
3340 state.vertex.limits.vertex_limit
3341 },
3342 instance_limit: state.vertex.limits.instance_limit,
3343 };
3344
3345 let mut current_draw_data = draw_ctx.add(offset)?;
3346
3347 for i in 1..count {
3348 let draw_data = draw_ctx.add(offset + stride * i as u64)?;
3349
3350 if draw_data.buffer_index == current_draw_data.buffer_index {
3351 #[cfg(debug_assertions)]
3352 {
3353 let dst_stride =
3354 get_dst_stride_of_indirect_args(state.pass.base.device.backend(), family);
3355 debug_assert_eq!(
3356 draw_data.offset,
3357 current_draw_data.offset + dst_stride * current_draw_data.count as u64
3358 );
3359 }
3360 current_draw_data.count += 1;
3361 } else {
3362 draw_ctx.draw(current_draw_data);
3363 current_draw_data = draw_data;
3364 }
3365 }
3366
3367 draw_ctx.draw(current_draw_data);
3368 } else {
3369 state
3370 .pass
3371 .scope
3372 .buffers
3373 .merge_single(&indirect_buffer, wgt::BufferUses::INDIRECT)?;
3374
3375 draw(
3376 state.pass.base.raw_encoder,
3377 family,
3378 indirect_buffer.try_raw(state.pass.base.snatch_guard)?,
3379 offset,
3380 count,
3381 );
3382 };
3383
3384 Ok(())
3385}
3386
3387fn multi_draw_indirect_count(
3388 state: &mut State,
3389 device: &Arc<Device>,
3390 indirect_buffer: Arc<Buffer>,
3391 offset: u64,
3392 count_buffer: Arc<Buffer>,
3393 count_buffer_offset: u64,
3394 max_count: u32,
3395 family: DrawCommandFamily,
3396) -> Result<(), RenderPassErrorInner> {
3397 api_log!(
3398 "RenderPass::multi_draw_indirect_count (family:{family:?}) {} {offset} {} {count_buffer_offset:?} {max_count:?}",
3399 indirect_buffer.error_ident(),
3400 count_buffer.error_ident()
3401 );
3402
3403 state.is_ready(family)?;
3404 state.flush_vertex_buffers()?;
3405 state.flush_bindings()?;
3406 state.flush_immediates();
3407
3408 if family == DrawCommandFamily::DrawMeshTasks {
3409 validate_mesh_draw_multiview(state.pass.base.device, state.info.multiview_mask)?;
3410 }
3411
3412 let stride = get_src_stride_of_indirect_args(family);
3413
3414 state
3415 .pass
3416 .base
3417 .device
3418 .require_features(wgt::Features::MULTI_DRAW_INDIRECT_COUNT)?;
3419 state
3420 .pass
3421 .base
3422 .device
3423 .require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
3424
3425 indirect_buffer.same_device(device)?;
3426 count_buffer.same_device(device)?;
3427
3428 state
3429 .pass
3430 .scope
3431 .buffers
3432 .merge_single(&indirect_buffer, wgt::BufferUses::INDIRECT)?;
3433
3434 indirect_buffer.check_usage(BufferUsages::INDIRECT)?;
3435 let indirect_raw = indirect_buffer.try_raw(state.pass.base.snatch_guard)?;
3436
3437 state
3438 .pass
3439 .scope
3440 .buffers
3441 .merge_single(&count_buffer, wgt::BufferUses::INDIRECT)?;
3442
3443 count_buffer.check_usage(BufferUsages::INDIRECT)?;
3444 let count_raw = count_buffer.try_raw(state.pass.base.snatch_guard)?;
3445
3446 if !offset.is_multiple_of(4) {
3447 return Err(RenderCommandError::UnalignedIndirectBufferOffset(offset).into());
3448 }
3449
3450 let args_size = match stride.checked_mul(u64::from(max_count)) {
3451 Some(sz) if sz <= indirect_buffer.size && indirect_buffer.size - sz >= offset => sz,
3452 args_size => {
3453 return Err(RenderCommandError::IndirectBufferOverrun {
3454 count: 1,
3455 offset,
3456 args_size: args_size.unwrap_or(u64::MAX),
3457 buffer_size: indirect_buffer.size,
3458 }
3459 .into());
3460 }
3461 };
3462
3463 state.pass.base.buffer_memory_init_actions.extend(
3464 indirect_buffer.initialization_status.read().create_action(
3465 &indirect_buffer,
3466 offset..offset + args_size,
3467 MemoryInitKind::NeedsInitializedMemory,
3468 ),
3469 );
3470
3471 let begin_count_offset = count_buffer_offset;
3472 let count_bytes = 4;
3473 if count_buffer.size < count_bytes || count_buffer.size - count_bytes < count_buffer_offset {
3474 return Err(RenderPassErrorInner::IndirectCountBufferOverrun {
3475 begin_count_offset,
3476 count_bytes: 4,
3477 count_buffer_size: count_buffer.size,
3478 });
3479 }
3480 state.pass.base.buffer_memory_init_actions.extend(
3481 count_buffer.initialization_status.read().create_action(
3482 &count_buffer,
3483 count_buffer_offset..count_buffer_offset + count_bytes,
3484 MemoryInitKind::NeedsInitializedMemory,
3485 ),
3486 );
3487
3488 match family {
3489 DrawCommandFamily::Draw => unsafe {
3490 state.pass.base.raw_encoder.draw_indirect_count(
3491 indirect_raw,
3492 offset,
3493 count_raw,
3494 count_buffer_offset,
3495 max_count,
3496 );
3497 },
3498 DrawCommandFamily::DrawIndexed => unsafe {
3499 state.pass.base.raw_encoder.draw_indexed_indirect_count(
3500 indirect_raw,
3501 offset,
3502 count_raw,
3503 count_buffer_offset,
3504 max_count,
3505 );
3506 },
3507 DrawCommandFamily::DrawMeshTasks => unsafe {
3508 state.pass.base.raw_encoder.draw_mesh_tasks_indirect_count(
3509 indirect_raw,
3510 offset,
3511 count_raw,
3512 count_buffer_offset,
3513 max_count,
3514 );
3515 },
3516 }
3517 Ok(())
3518}
3519
3520fn execute_bundle(
3521 state: &mut State,
3522 indirect_draw_validation_batcher: &mut crate::indirect_validation::DrawBatcher,
3523 device: &Arc<Device>,
3524 bundle: Arc<RenderBundle>,
3525) -> Result<(), RenderPassErrorInner> {
3526 api_log!("RenderPass::execute_bundle {}", bundle.error_ident());
3527
3528 let bundle = state.pass.base.tracker.bundles.insert_single(bundle);
3529
3530 let bundle_state = bundle.state()?;
3531 bundle.same_device(device)?;
3532
3533 state
3534 .info
3535 .context
3536 .check_compatible(&bundle_state.context, bundle.as_ref())
3537 .map_err(RenderPassErrorInner::IncompatibleBundleTargets)?;
3538
3539 if (state.info.is_depth_read_only && !bundle.is_depth_read_only)
3540 || (state.info.is_stencil_read_only && !bundle.is_stencil_read_only)
3541 {
3542 return Err(
3543 RenderPassErrorInner::IncompatibleBundleReadOnlyDepthStencil {
3544 pass_depth: state.info.is_depth_read_only,
3545 pass_stencil: state.info.is_stencil_read_only,
3546 bundle_depth: bundle.is_depth_read_only,
3547 bundle_stencil: bundle.is_stencil_read_only,
3548 },
3549 );
3550 }
3551
3552 state.pass.base.buffer_memory_init_actions.extend(
3553 bundle
3554 .buffer_memory_init_actions
3555 .iter()
3556 .filter_map(|action| {
3557 action
3558 .buffer
3559 .initialization_status
3560 .read()
3561 .check_action(action)
3562 }),
3563 );
3564 for action in bundle.texture_memory_init_actions.iter() {
3565 state.pass.pending_discard_init_fixups.extend(
3566 state
3567 .pass
3568 .base
3569 .texture_memory_actions
3570 .register_init_action(action, None),
3571 );
3572 }
3573
3574 unsafe {
3575 bundle.execute(
3576 state.pass.base.raw_encoder,
3577 state.pass.base.indirect_draw_validation_resources,
3578 indirect_draw_validation_batcher,
3579 state.pass.base.snatch_guard,
3580 )
3581 }
3582 .map_err(|e| match e {
3583 ExecutionError::Device(e) => RenderPassErrorInner::Device(e),
3584 ExecutionError::DestroyedResource(e) => {
3585 RenderPassErrorInner::RenderCommand(RenderCommandError::DestroyedResource(e))
3586 }
3587 ExecutionError::InvalidResource(e) => {
3588 RenderPassErrorInner::RenderCommand(RenderCommandError::InvalidResource(e))
3589 }
3590 })?;
3591
3592 unsafe {
3593 state.pass.scope.merge_render_bundle(&bundle_state.used)?;
3594 };
3595 state.reset_bundle();
3596 Ok(())
3597}
3598
3599impl RenderPass {
3612 fn set_bind_group_inner(
3613 &mut self,
3614 index: u32,
3615 bind_group: Option<Arc<BindGroup>>,
3616 offsets: &[DynamicOffset],
3617 ) -> Result<(), PassStateError> {
3618 let scope = PassErrorScope::SetBindGroup;
3619
3620 let base = pass_base!(self, scope);
3624
3625 if self.current_bind_groups.set_and_check_redundant(
3626 &bind_group,
3627 index,
3628 &mut base.dynamic_offsets,
3629 offsets,
3630 ) {
3631 return Ok(());
3632 }
3633
3634 let bind_group = if let Some(bind_group) = bind_group {
3635 pass_try!(base, scope, bind_group.check_is_valid());
3636 Some(bind_group)
3637 } else {
3638 None
3639 };
3640
3641 base.commands.push(ArcRenderCommand::SetBindGroup {
3642 index,
3643 num_dynamic_offsets: offsets.len(),
3644 bind_group,
3645 });
3646
3647 Ok(())
3648 }
3649
3650 pub fn set_bind_group(
3651 &mut self,
3652 index: u32,
3653 bind_group: Option<Arc<BindGroup>>,
3654 offsets: &[DynamicOffset],
3655 ) {
3656 if let Err(err) = self.set_bind_group_inner(index, bind_group, offsets) {
3657 self.device
3658 .handle_error(err, self.label(), "RenderPass::set_bind_group");
3659 }
3660 }
3661
3662 fn set_pipeline_inner(&mut self, pipeline: Arc<RenderPipeline>) -> Result<(), PassStateError> {
3663 let scope = PassErrorScope::SetPipelineRender;
3664
3665 let redundant = self.current_pipeline.set_and_check_redundant(&pipeline);
3666
3667 let base = pass_base!(self, scope);
3670
3671 if redundant {
3672 return Ok(());
3673 }
3674
3675 pass_try!(base, scope, pipeline.check_valid());
3676
3677 base.commands.push(ArcRenderCommand::SetPipeline(pipeline));
3678
3679 Ok(())
3680 }
3681
3682 pub fn set_pipeline(&mut self, pipeline: Arc<RenderPipeline>) {
3683 if let Err(err) = self.set_pipeline_inner(pipeline) {
3684 self.device
3685 .handle_error(err, self.label(), "RenderPass::set_pipeline");
3686 }
3687 }
3688
3689 fn set_index_buffer_inner(
3690 &mut self,
3691 buffer: Arc<Buffer>,
3692 index_format: IndexFormat,
3693 offset: BufferAddress,
3694 size: Option<BufferAddress>,
3695 ) -> Result<(), PassStateError> {
3696 let scope = PassErrorScope::SetIndexBuffer;
3697 let base = pass_base!(self, scope);
3698
3699 pass_try!(base, scope, buffer.check_is_valid());
3700
3701 base.commands.push(ArcRenderCommand::SetIndexBuffer {
3702 buffer,
3703 index_format,
3704 offset,
3705 size,
3706 });
3707
3708 Ok(())
3709 }
3710
3711 pub fn set_index_buffer(
3712 &mut self,
3713 buffer: Arc<Buffer>,
3714 index_format: IndexFormat,
3715 offset: BufferAddress,
3716 size: Option<BufferAddress>,
3717 ) {
3718 if let Err(err) = self.set_index_buffer_inner(buffer, index_format, offset, size) {
3719 self.device
3720 .handle_error(err, self.label(), "RenderPass::set_index_buffer");
3721 }
3722 }
3723
3724 fn set_vertex_buffer_inner(
3725 &mut self,
3726 slot: u32,
3727 buffer: Option<Arc<Buffer>>,
3728 offset: BufferAddress,
3729 size: Option<BufferAddress>,
3730 ) -> Result<(), PassStateError> {
3731 let scope = PassErrorScope::SetVertexBuffer;
3732 let base = pass_base!(self, scope);
3733
3734 let buffer = if let Some(buffer) = buffer {
3735 pass_try!(base, scope, buffer.check_is_valid());
3736 Some(buffer)
3737 } else {
3738 None
3739 };
3740
3741 base.commands.push(ArcRenderCommand::SetVertexBuffer {
3742 slot,
3743 buffer,
3744 offset,
3745 size,
3746 });
3747
3748 Ok(())
3749 }
3750
3751 pub fn set_vertex_buffer(
3752 &mut self,
3753 slot: u32,
3754 buffer: Option<Arc<Buffer>>,
3755 offset: BufferAddress,
3756 size: Option<BufferAddress>,
3757 ) {
3758 if let Err(err) = self.set_vertex_buffer_inner(slot, buffer, offset, size) {
3759 self.device
3760 .handle_error(err, self.label(), "RenderPass::set_vertex_buffer");
3761 }
3762 }
3763
3764 fn set_blend_constant_inner(&mut self, color: Color) -> Result<(), PassStateError> {
3765 let scope = PassErrorScope::SetBlendConstant;
3766 let base = pass_base!(self, scope);
3767
3768 base.commands
3769 .push(ArcRenderCommand::SetBlendConstant(color));
3770
3771 Ok(())
3772 }
3773
3774 pub fn set_blend_constant(&mut self, color: Color) {
3775 if let Err(err) = self.set_blend_constant_inner(color) {
3776 self.device
3777 .handle_error(err, self.label(), "RenderPass::set_blend_constant");
3778 }
3779 }
3780
3781 fn set_stencil_reference_inner(&mut self, value: u32) -> Result<(), PassStateError> {
3782 let scope = PassErrorScope::SetStencilReference;
3783 let base = pass_base!(self, scope);
3784 let value = convert_stencil_value(
3785 value,
3786 self.depth_stencil_attachment
3787 .as_ref()
3788 .map(|at| at.view.desc.format),
3789 );
3790 base.commands
3791 .push(ArcRenderCommand::SetStencilReference(value));
3792
3793 Ok(())
3794 }
3795
3796 pub fn set_stencil_reference(&mut self, value: u32) {
3797 if let Err(err) = self.set_stencil_reference_inner(value) {
3798 self.device
3799 .handle_error(err, self.label(), "RenderPass::set_stencil_reference");
3800 }
3801 }
3802
3803 fn set_viewport_inner(
3804 &mut self,
3805 x: f32,
3806 y: f32,
3807 w: f32,
3808 h: f32,
3809 depth_min: f32,
3810 depth_max: f32,
3811 ) -> Result<(), PassStateError> {
3812 let scope = PassErrorScope::SetViewport;
3813 let base = pass_base!(self, scope);
3814
3815 base.commands.push(ArcRenderCommand::SetViewport {
3816 rect: Rect { x, y, w, h },
3817 depth_min,
3818 depth_max,
3819 });
3820
3821 Ok(())
3822 }
3823
3824 pub fn set_viewport(&mut self, x: f32, y: f32, w: f32, h: f32, depth_min: f32, depth_max: f32) {
3825 if let Err(err) = self.set_viewport_inner(x, y, w, h, depth_min, depth_max) {
3826 self.device
3827 .handle_error(err, self.label(), "RenderPass::set_viewport");
3828 }
3829 }
3830
3831 fn set_scissor_rect_inner(
3832 &mut self,
3833 x: u32,
3834 y: u32,
3835 w: u32,
3836 h: u32,
3837 ) -> Result<(), PassStateError> {
3838 let scope = PassErrorScope::SetScissorRect;
3839 let base = pass_base!(self, scope);
3840
3841 base.commands
3842 .push(ArcRenderCommand::SetScissor(Rect { x, y, w, h }));
3843
3844 Ok(())
3845 }
3846
3847 pub fn set_scissor_rect(&mut self, x: u32, y: u32, w: u32, h: u32) {
3848 if let Err(err) = self.set_scissor_rect_inner(x, y, w, h) {
3849 self.device
3850 .handle_error(err, self.label(), "RenderPass::set_scissor_rect");
3851 }
3852 }
3853
3854 fn set_immediates_inner(&mut self, offset: u32, data: &[u8]) -> Result<(), PassStateError> {
3855 let scope = PassErrorScope::SetImmediate;
3856 let base = pass_base!(self, scope);
3857
3858 pass_try!(
3859 base,
3860 scope,
3861 pass::validate_immediates_alignment(offset, data.len())
3862 );
3863
3864 base.commands.push(ArcRenderCommand::SetImmediate {
3865 offset,
3866 data: data
3867 .chunks_exact(size_of::<u32>())
3868 .map(|ck| u32::from_le_bytes(ck.try_into().unwrap()))
3869 .collect(),
3870 });
3871
3872 Ok(())
3873 }
3874
3875 pub fn set_immediates(&mut self, offset: u32, data: &[u8]) {
3876 if let Err(err) = self.set_immediates_inner(offset, data) {
3877 self.device
3878 .handle_error(err, self.label(), "RenderPass::set_immediates");
3879 }
3880 }
3881
3882 fn draw_inner(
3883 &mut self,
3884 vertex_count: u32,
3885 instance_count: u32,
3886 first_vertex: u32,
3887 first_instance: u32,
3888 ) -> Result<(), PassStateError> {
3889 let scope = PassErrorScope::Draw {
3890 kind: DrawKind::Draw,
3891 family: DrawCommandFamily::Draw,
3892 };
3893 let base = pass_base!(self, scope);
3894
3895 base.commands.push(ArcRenderCommand::Draw {
3896 vertex_count,
3897 instance_count,
3898 first_vertex,
3899 first_instance,
3900 });
3901
3902 Ok(())
3903 }
3904
3905 pub fn draw(
3906 &mut self,
3907 vertex_count: u32,
3908 instance_count: u32,
3909 first_vertex: u32,
3910 first_instance: u32,
3911 ) {
3912 if let Err(err) =
3913 self.draw_inner(vertex_count, instance_count, first_vertex, first_instance)
3914 {
3915 self.device
3916 .handle_error(err, self.label(), "RenderPass::draw");
3917 }
3918 }
3919
3920 fn draw_indexed_inner(
3921 &mut self,
3922 index_count: u32,
3923 instance_count: u32,
3924 first_index: u32,
3925 base_vertex: i32,
3926 first_instance: u32,
3927 ) -> Result<(), PassStateError> {
3928 let scope = PassErrorScope::Draw {
3929 kind: DrawKind::Draw,
3930 family: DrawCommandFamily::DrawIndexed,
3931 };
3932 let base = pass_base!(self, scope);
3933
3934 base.commands.push(ArcRenderCommand::DrawIndexed {
3935 index_count,
3936 instance_count,
3937 first_index,
3938 base_vertex,
3939 first_instance,
3940 });
3941
3942 Ok(())
3943 }
3944
3945 pub fn draw_indexed(
3946 &mut self,
3947 index_count: u32,
3948 instance_count: u32,
3949 first_index: u32,
3950 base_vertex: i32,
3951 first_instance: u32,
3952 ) {
3953 if let Err(err) = self.draw_indexed_inner(
3954 index_count,
3955 instance_count,
3956 first_index,
3957 base_vertex,
3958 first_instance,
3959 ) {
3960 self.device
3961 .handle_error(err, self.label(), "RenderPass::draw_indexed");
3962 }
3963 }
3964
3965 fn draw_mesh_tasks_inner(
3966 &mut self,
3967 group_count_x: u32,
3968 group_count_y: u32,
3969 group_count_z: u32,
3970 ) -> Result<(), RenderPassError> {
3971 let scope = PassErrorScope::Draw {
3972 kind: DrawKind::Draw,
3973 family: DrawCommandFamily::DrawMeshTasks,
3974 };
3975 let base = pass_base!(self, scope);
3976
3977 base.commands.push(ArcRenderCommand::DrawMeshTasks {
3978 group_count_x,
3979 group_count_y,
3980 group_count_z,
3981 });
3982 Ok(())
3983 }
3984
3985 pub fn draw_mesh_tasks(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32) {
3986 if let Err(err) = self.draw_mesh_tasks_inner(group_count_x, group_count_y, group_count_z) {
3987 self.device
3988 .handle_error(err, self.label(), "RenderPass::draw_mesh_tasks");
3989 }
3990 }
3991
3992 fn draw_indirect_inner(
3993 &mut self,
3994 buffer: Arc<Buffer>,
3995 offset: BufferAddress,
3996 ) -> Result<(), PassStateError> {
3997 let scope = PassErrorScope::Draw {
3998 kind: DrawKind::DrawIndirect,
3999 family: DrawCommandFamily::Draw,
4000 };
4001 let base = pass_base!(self, scope);
4002
4003 pass_try!(base, scope, buffer.check_is_valid());
4004
4005 base.commands.push(ArcRenderCommand::DrawIndirect {
4006 buffer,
4007 offset,
4008 count: 1,
4009 family: DrawCommandFamily::Draw,
4010
4011 vertex_or_index_limit: None,
4012 instance_limit: None,
4013 });
4014
4015 Ok(())
4016 }
4017
4018 pub fn draw_indirect(&mut self, buffer: Arc<Buffer>, offset: BufferAddress) {
4019 if let Err(err) = self.draw_indirect_inner(buffer, offset) {
4020 self.device
4021 .handle_error(err, self.label(), "RenderPass::draw_indirect");
4022 }
4023 }
4024
4025 fn draw_indexed_indirect_inner(
4026 &mut self,
4027 buffer: Arc<Buffer>,
4028 offset: BufferAddress,
4029 ) -> Result<(), PassStateError> {
4030 let scope = PassErrorScope::Draw {
4031 kind: DrawKind::DrawIndirect,
4032 family: DrawCommandFamily::DrawIndexed,
4033 };
4034 let base = pass_base!(self, scope);
4035
4036 pass_try!(base, scope, buffer.check_is_valid());
4037
4038 base.commands.push(ArcRenderCommand::DrawIndirect {
4039 buffer,
4040 offset,
4041 count: 1,
4042 family: DrawCommandFamily::DrawIndexed,
4043
4044 vertex_or_index_limit: None,
4045 instance_limit: None,
4046 });
4047
4048 Ok(())
4049 }
4050
4051 pub fn draw_indexed_indirect(&mut self, buffer: Arc<Buffer>, offset: BufferAddress) {
4052 if let Err(err) = self.draw_indexed_indirect_inner(buffer, offset) {
4053 self.device
4054 .handle_error(err, self.label(), "RenderPass::draw_indexed_indirect");
4055 }
4056 }
4057
4058 fn draw_mesh_tasks_indirect_inner(
4059 &mut self,
4060 buffer: Arc<Buffer>,
4061 offset: BufferAddress,
4062 ) -> Result<(), RenderPassError> {
4063 let scope = PassErrorScope::Draw {
4064 kind: DrawKind::DrawIndirect,
4065 family: DrawCommandFamily::DrawMeshTasks,
4066 };
4067 let base = pass_base!(self, scope);
4068
4069 pass_try!(base, scope, buffer.check_is_valid());
4070
4071 base.commands.push(ArcRenderCommand::DrawIndirect {
4072 buffer,
4073 offset,
4074 count: 1,
4075 family: DrawCommandFamily::DrawMeshTasks,
4076
4077 vertex_or_index_limit: None,
4078 instance_limit: None,
4079 });
4080
4081 Ok(())
4082 }
4083
4084 pub fn draw_mesh_tasks_indirect(&mut self, buffer: Arc<Buffer>, offset: BufferAddress) {
4085 if let Err(err) = self.draw_mesh_tasks_indirect_inner(buffer, offset) {
4086 self.device
4087 .handle_error(err, self.label(), "RenderPass::draw_mesh_tasks_indirect");
4088 }
4089 }
4090
4091 fn multi_draw_indirect_inner(
4092 &mut self,
4093 buffer: Arc<Buffer>,
4094 offset: BufferAddress,
4095 count: u32,
4096 ) -> Result<(), PassStateError> {
4097 let scope = PassErrorScope::Draw {
4098 kind: DrawKind::MultiDrawIndirect,
4099 family: DrawCommandFamily::Draw,
4100 };
4101 let base = pass_base!(self, scope);
4102
4103 pass_try!(base, scope, buffer.check_is_valid());
4104
4105 base.commands.push(ArcRenderCommand::DrawIndirect {
4106 buffer,
4107 offset,
4108 count,
4109 family: DrawCommandFamily::Draw,
4110
4111 vertex_or_index_limit: None,
4112 instance_limit: None,
4113 });
4114
4115 Ok(())
4116 }
4117
4118 pub fn multi_draw_indirect(&mut self, buffer: Arc<Buffer>, offset: BufferAddress, count: u32) {
4119 if let Err(err) = self.multi_draw_indirect_inner(buffer, offset, count) {
4120 self.device
4121 .handle_error(err, self.label(), "RenderPass::multi_draw_indirect");
4122 }
4123 }
4124
4125 fn multi_draw_indexed_indirect_inner(
4126 &mut self,
4127 buffer: Arc<Buffer>,
4128 offset: BufferAddress,
4129 count: u32,
4130 ) -> Result<(), PassStateError> {
4131 let scope = PassErrorScope::Draw {
4132 kind: DrawKind::MultiDrawIndirect,
4133 family: DrawCommandFamily::DrawIndexed,
4134 };
4135 let base = pass_base!(self, scope);
4136
4137 pass_try!(base, scope, buffer.check_is_valid());
4138
4139 base.commands.push(ArcRenderCommand::DrawIndirect {
4140 buffer,
4141 offset,
4142 count,
4143 family: DrawCommandFamily::DrawIndexed,
4144
4145 vertex_or_index_limit: None,
4146 instance_limit: None,
4147 });
4148
4149 Ok(())
4150 }
4151
4152 pub fn multi_draw_indexed_indirect(
4153 &mut self,
4154 buffer: Arc<Buffer>,
4155 offset: BufferAddress,
4156 count: u32,
4157 ) {
4158 if let Err(err) = self.multi_draw_indexed_indirect_inner(buffer, offset, count) {
4159 self.device
4160 .handle_error(err, self.label(), "RenderPass::multi_draw_indexed_indirect");
4161 }
4162 }
4163
4164 fn multi_draw_mesh_tasks_indirect_inner(
4165 &mut self,
4166 buffer: Arc<Buffer>,
4167 offset: BufferAddress,
4168 count: u32,
4169 ) -> Result<(), RenderPassError> {
4170 let scope = PassErrorScope::Draw {
4171 kind: DrawKind::MultiDrawIndirect,
4172 family: DrawCommandFamily::DrawMeshTasks,
4173 };
4174 let base = pass_base!(self, scope);
4175
4176 pass_try!(base, scope, buffer.check_is_valid());
4177
4178 base.commands.push(ArcRenderCommand::DrawIndirect {
4179 buffer,
4180 offset,
4181 count,
4182 family: DrawCommandFamily::DrawMeshTasks,
4183
4184 vertex_or_index_limit: None,
4185 instance_limit: None,
4186 });
4187
4188 Ok(())
4189 }
4190
4191 pub fn multi_draw_mesh_tasks_indirect(
4192 &mut self,
4193 buffer: Arc<Buffer>,
4194 offset: BufferAddress,
4195 count: u32,
4196 ) {
4197 if let Err(err) = self.multi_draw_mesh_tasks_indirect_inner(buffer, offset, count) {
4198 self.device.handle_error(
4199 err,
4200 self.label(),
4201 "RenderPass::multi_draw_mesh_tasks_indirect",
4202 );
4203 }
4204 }
4205
4206 fn multi_draw_indirect_count_inner(
4207 &mut self,
4208 buffer: Arc<Buffer>,
4209 offset: BufferAddress,
4210 count_buffer: Arc<Buffer>,
4211 count_buffer_offset: BufferAddress,
4212 max_count: u32,
4213 ) -> Result<(), PassStateError> {
4214 let scope = PassErrorScope::Draw {
4215 kind: DrawKind::MultiDrawIndirectCount,
4216 family: DrawCommandFamily::Draw,
4217 };
4218 let base = pass_base!(self, scope);
4219 pass_try!(base, scope, buffer.check_is_valid());
4220 pass_try!(base, scope, count_buffer.check_is_valid());
4221
4222 base.commands
4223 .push(ArcRenderCommand::MultiDrawIndirectCount {
4224 buffer,
4225 offset,
4226 count_buffer,
4227 count_buffer_offset,
4228 max_count,
4229 family: DrawCommandFamily::Draw,
4230 });
4231
4232 Ok(())
4233 }
4234
4235 pub fn multi_draw_indirect_count(
4236 &mut self,
4237 buffer: Arc<Buffer>,
4238 offset: BufferAddress,
4239 count_buffer: Arc<Buffer>,
4240 count_buffer_offset: BufferAddress,
4241 max_count: u32,
4242 ) {
4243 if let Err(err) = self.multi_draw_indirect_count_inner(
4244 buffer,
4245 offset,
4246 count_buffer,
4247 count_buffer_offset,
4248 max_count,
4249 ) {
4250 self.device
4251 .handle_error(err, self.label(), "RenderPass::multi_draw_indirect_count");
4252 }
4253 }
4254
4255 fn multi_draw_indexed_indirect_count_inner(
4256 &mut self,
4257 buffer: Arc<Buffer>,
4258 offset: BufferAddress,
4259 count_buffer: Arc<Buffer>,
4260 count_buffer_offset: BufferAddress,
4261 max_count: u32,
4262 ) -> Result<(), PassStateError> {
4263 let scope = PassErrorScope::Draw {
4264 kind: DrawKind::MultiDrawIndirectCount,
4265 family: DrawCommandFamily::DrawIndexed,
4266 };
4267 let base = pass_base!(self, scope);
4268
4269 pass_try!(base, scope, buffer.check_is_valid());
4270 pass_try!(base, scope, count_buffer.check_is_valid());
4271
4272 base.commands
4273 .push(ArcRenderCommand::MultiDrawIndirectCount {
4274 buffer,
4275 offset,
4276 count_buffer,
4277 count_buffer_offset,
4278 max_count,
4279 family: DrawCommandFamily::DrawIndexed,
4280 });
4281
4282 Ok(())
4283 }
4284
4285 pub fn multi_draw_indexed_indirect_count(
4286 &mut self,
4287 buffer: Arc<Buffer>,
4288 offset: BufferAddress,
4289 count_buffer: Arc<Buffer>,
4290 count_buffer_offset: BufferAddress,
4291 max_count: u32,
4292 ) {
4293 if let Err(err) = self.multi_draw_indexed_indirect_count_inner(
4294 buffer,
4295 offset,
4296 count_buffer,
4297 count_buffer_offset,
4298 max_count,
4299 ) {
4300 self.device.handle_error(
4301 err,
4302 self.label(),
4303 "RenderPass::multi_draw_indexed_indirect_count",
4304 );
4305 }
4306 }
4307
4308 fn multi_draw_mesh_tasks_indirect_count_inner(
4309 &mut self,
4310 buffer: Arc<Buffer>,
4311 offset: BufferAddress,
4312 count_buffer: Arc<Buffer>,
4313 count_buffer_offset: BufferAddress,
4314 max_count: u32,
4315 ) -> Result<(), RenderPassError> {
4316 let scope = PassErrorScope::Draw {
4317 kind: DrawKind::MultiDrawIndirectCount,
4318 family: DrawCommandFamily::DrawMeshTasks,
4319 };
4320 let base = pass_base!(self, scope);
4321
4322 pass_try!(base, scope, buffer.check_is_valid());
4323 pass_try!(base, scope, count_buffer.check_is_valid());
4324
4325 base.commands
4326 .push(ArcRenderCommand::MultiDrawIndirectCount {
4327 buffer,
4328 offset,
4329 count_buffer,
4330 count_buffer_offset,
4331 max_count,
4332 family: DrawCommandFamily::DrawMeshTasks,
4333 });
4334
4335 Ok(())
4336 }
4337
4338 pub fn multi_draw_mesh_tasks_indirect_count(
4339 &mut self,
4340 buffer: Arc<Buffer>,
4341 offset: BufferAddress,
4342 count_buffer: Arc<Buffer>,
4343 count_buffer_offset: BufferAddress,
4344 max_count: u32,
4345 ) {
4346 if let Err(err) = self.multi_draw_mesh_tasks_indirect_count_inner(
4347 buffer,
4348 offset,
4349 count_buffer,
4350 count_buffer_offset,
4351 max_count,
4352 ) {
4353 self.device.handle_error(
4354 err,
4355 self.label(),
4356 "RenderPass::multi_draw_mesh_tasks_indirect_count",
4357 );
4358 }
4359 }
4360
4361 fn push_debug_group_inner(&mut self, label: &str, color: u32) -> Result<(), PassStateError> {
4362 let base = pass_base!(self, PassErrorScope::PushDebugGroup);
4363
4364 let bytes = label.as_bytes();
4365 base.string_data.extend_from_slice(bytes);
4366
4367 base.commands.push(ArcRenderCommand::PushDebugGroup {
4368 color,
4369 len: bytes.len(),
4370 });
4371
4372 Ok(())
4373 }
4374
4375 pub fn push_debug_group(&mut self, label: &str, color: u32) {
4376 if let Err(err) = self.push_debug_group_inner(label, color) {
4377 self.device
4378 .handle_error(err, self.label(), "RenderPass::push_debug_group");
4379 }
4380 }
4381
4382 fn pop_debug_group_inner(&mut self) -> Result<(), PassStateError> {
4383 let base = pass_base!(self, PassErrorScope::PopDebugGroup);
4384
4385 base.commands.push(ArcRenderCommand::PopDebugGroup);
4386
4387 Ok(())
4388 }
4389
4390 pub fn pop_debug_group(&mut self) {
4391 if let Err(err) = self.pop_debug_group_inner() {
4392 self.device
4393 .handle_error(err, self.label(), "RenderPass::pop_debug_group");
4394 }
4395 }
4396
4397 fn insert_debug_marker_inner(&mut self, label: &str, color: u32) -> Result<(), PassStateError> {
4398 let base = pass_base!(self, PassErrorScope::InsertDebugMarker);
4399
4400 let bytes = label.as_bytes();
4401 base.string_data.extend_from_slice(bytes);
4402
4403 base.commands.push(ArcRenderCommand::InsertDebugMarker {
4404 color,
4405 len: bytes.len(),
4406 });
4407
4408 Ok(())
4409 }
4410
4411 pub fn insert_debug_marker(&mut self, label: &str, color: u32) {
4412 if let Err(err) = self.insert_debug_marker_inner(label, color) {
4413 self.device
4414 .handle_error(err, self.label(), "RenderPass::insert_debug_marker");
4415 }
4416 }
4417
4418 fn write_timestamp_inner(
4419 &mut self,
4420 query_set: Arc<QuerySet>,
4421 query_index: u32,
4422 ) -> Result<(), PassStateError> {
4423 let scope = PassErrorScope::WriteTimestamp;
4424 let base = pass_base!(self, scope);
4425
4426 pass_try!(base, scope, query_set.check_is_valid());
4427 base.commands.push(ArcRenderCommand::WriteTimestamp {
4428 query_set,
4429 query_index,
4430 });
4431
4432 Ok(())
4433 }
4434
4435 pub fn write_timestamp(&mut self, query_set: Arc<QuerySet>, query_index: u32) {
4436 if let Err(err) = self.write_timestamp_inner(query_set, query_index) {
4437 self.device
4438 .handle_error(err, self.label(), "RenderPass::write_timestamp");
4439 }
4440 }
4441
4442 fn begin_occlusion_query_inner(&mut self, query_index: u32) -> Result<(), PassStateError> {
4443 let scope = PassErrorScope::BeginOcclusionQuery;
4444 let base = pass_base!(self, scope);
4445
4446 base.commands
4447 .push(ArcRenderCommand::BeginOcclusionQuery { query_index });
4448
4449 Ok(())
4450 }
4451
4452 pub fn begin_occlusion_query(&mut self, query_index: u32) {
4453 if let Err(err) = self.begin_occlusion_query_inner(query_index) {
4454 self.device
4455 .handle_error(err, self.label(), "RenderPass::begin_occlusion_query");
4456 }
4457 }
4458
4459 fn end_occlusion_query_inner(&mut self) -> Result<(), PassStateError> {
4460 let scope = PassErrorScope::EndOcclusionQuery;
4461 let base = pass_base!(self, scope);
4462
4463 base.commands.push(ArcRenderCommand::EndOcclusionQuery);
4464
4465 Ok(())
4466 }
4467
4468 pub fn end_occlusion_query(&mut self) {
4469 if let Err(err) = self.end_occlusion_query_inner() {
4470 self.device
4471 .handle_error(err, self.label(), "RenderPass::end_occlusion_query");
4472 }
4473 }
4474
4475 fn begin_pipeline_statistics_query_inner(
4476 &mut self,
4477 query_set: Arc<QuerySet>,
4478 query_index: u32,
4479 ) -> Result<(), PassStateError> {
4480 let scope = PassErrorScope::BeginPipelineStatisticsQuery;
4481 let base = pass_base!(self, scope);
4482
4483 pass_try!(base, scope, query_set.check_is_valid());
4484 base.commands
4485 .push(ArcRenderCommand::BeginPipelineStatisticsQuery {
4486 query_set,
4487 query_index,
4488 });
4489
4490 Ok(())
4491 }
4492
4493 pub fn begin_pipeline_statistics_query(&mut self, query_set: Arc<QuerySet>, query_index: u32) {
4494 if let Err(err) = self.begin_pipeline_statistics_query_inner(query_set, query_index) {
4495 self.device.handle_error(
4496 err,
4497 self.label(),
4498 "RenderPass::begin_pipeline_statistics_query",
4499 );
4500 }
4501 }
4502
4503 fn end_pipeline_statistics_query_inner(&mut self) -> Result<(), PassStateError> {
4504 let scope = PassErrorScope::EndPipelineStatisticsQuery;
4505 let base = pass_base!(self, scope);
4506
4507 base.commands
4508 .push(ArcRenderCommand::EndPipelineStatisticsQuery);
4509
4510 Ok(())
4511 }
4512
4513 pub fn end_pipeline_statistics_query(&mut self) {
4514 if let Err(err) = self.end_pipeline_statistics_query_inner() {
4515 self.device.handle_error(
4516 err,
4517 self.label(),
4518 "RenderPass::end_pipeline_statistics_query",
4519 );
4520 }
4521 }
4522
4523 fn execute_bundles_inner(
4524 &mut self,
4525 render_bundles: &[Arc<RenderBundle>],
4526 ) -> Result<(), PassStateError> {
4527 let scope = PassErrorScope::ExecuteBundle;
4528 let base = pass_base!(self, scope);
4529
4530 for bundle in render_bundles {
4531 pass_try!(base, scope, bundle.check_is_valid());
4532
4533 base.commands
4534 .push(ArcRenderCommand::ExecuteBundle(bundle.clone()));
4535 }
4536 self.current_pipeline.reset();
4537 self.current_bind_groups.reset();
4538
4539 Ok(())
4540 }
4541
4542 pub fn execute_bundles(&mut self, render_bundles: &[Arc<RenderBundle>]) {
4543 if let Err(err) = self.execute_bundles_inner(render_bundles) {
4544 self.device
4545 .handle_error(err, self.label(), "RenderPass::execute_bundles");
4546 }
4547 }
4548}
4549
4550pub(crate) const fn get_src_stride_of_indirect_args(family: DrawCommandFamily) -> u64 {
4551 match family {
4552 DrawCommandFamily::Draw => size_of::<wgt::DrawIndirectArgs>() as u64,
4553 DrawCommandFamily::DrawIndexed => size_of::<wgt::DrawIndexedIndirectArgs>() as u64,
4554 DrawCommandFamily::DrawMeshTasks => size_of::<wgt::DispatchIndirectArgs>() as u64,
4555 }
4556}
4557
4558pub(crate) const fn get_dst_stride_of_indirect_args(
4559 backend: wgt::Backend,
4560 family: DrawCommandFamily,
4561) -> u64 {
4562 let extra = if matches!(backend, wgt::Backend::Dx12) {
4564 3 * size_of::<u32>() as u64
4565 } else {
4566 0
4567 };
4568 extra + get_src_stride_of_indirect_args(family)
4569}