Skip to main content

wgpu_core/
pipeline.rs

1use alloc::string::ToString as _;
2use alloc::{
3    borrow::{Cow, ToOwned},
4    boxed::Box,
5    string::String,
6    sync::Arc,
7    vec::Vec,
8};
9use core::{marker::PhantomData, mem::ManuallyDrop, num::NonZeroU32};
10
11use arrayvec::ArrayVec;
12use naga::error::ShaderError;
13use thiserror::Error;
14use wgt::error::{ErrorType, WebGpuError};
15
16pub use crate::pipeline_cache::PipelineCacheValidationError;
17use crate::ray_tracing_pipeline::RayTracingPipelineError;
18use crate::{
19    api_log,
20    binding_model::{
21        BindGroupLayout, CreateBindGroupLayoutError, CreatePipelineLayoutError,
22        GetBindGroupLayoutError, PipelineLayout,
23    },
24    command::ColorAttachmentError,
25    device::{
26        AttachmentData, Device, DeviceError, MissingDownlevelFlags, MissingFeatures,
27        RenderPassContext,
28    },
29    pipeline_cache,
30    resource::{InvalidResourceError, Labeled, ResourceState, TrackingData},
31    resource_log, validation, FastHashSet, Label, LabelHelpers as _,
32};
33
34/// Information about buffer bindings, which
35/// is validated against the shader (and pipeline)
36/// at draw time as opposed to initialization time.
37#[derive(Debug, Default)]
38pub(crate) struct LateSizedBufferGroup {
39    /// Shader-required sizes of `BindGroupLayout::late_sized_bindings`, in the same order.
40    pub(crate) shader_sizes: Vec<wgt::BufferAddress>,
41}
42
43#[allow(clippy::large_enum_variant)]
44pub enum ShaderModuleSource<'a> {
45    #[cfg(feature = "wgsl")]
46    Wgsl(Cow<'a, str>),
47    #[cfg(feature = "glsl")]
48    Glsl(Cow<'a, str>, naga::front::glsl::Options),
49    #[cfg(feature = "spirv")]
50    SpirV(Cow<'a, [u32]>, naga::front::spv::Options),
51    Naga(Cow<'static, naga::Module>),
52    /// Dummy variant because `Naga` doesn't have a lifetime and without enough active features it
53    /// could be the last one active.
54    #[doc(hidden)]
55    Dummy(PhantomData<&'a ()>),
56}
57
58#[derive(Clone, Debug)]
59#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
60pub struct ShaderModuleDescriptor<'a> {
61    pub label: Label<'a>,
62    #[cfg_attr(feature = "serde", serde(default))]
63    pub runtime_checks: wgt::ShaderRuntimeChecks,
64}
65
66pub type ShaderModuleDescriptorPassthrough<'a> =
67    wgt::CreateShaderModuleDescriptorPassthrough<'a, Label<'a>>;
68
69#[derive(Debug)]
70pub struct PassthroughInterface {
71    pub entry_point_names: FastHashSet<String>,
72}
73
74// Most shaders will use a standard interface which is very large.
75// Passthrough shaders have a much smaller interface. No reason to
76// box the standard interface though.
77#[expect(clippy::large_enum_variant)]
78#[derive(Debug)]
79pub enum ShaderModuleState {
80    /// A Naga module, from which we generate a `wgpu_hal` shader module
81    /// for each pipeline stage that uses it.
82    NagaModule {
83        shader: hal::NagaShader,
84        runtime_checks: wgt::ShaderRuntimeChecks,
85    },
86    Passthrough {
87        raw: Box<dyn hal::DynShaderModule>,
88        interface: PassthroughInterface,
89    },
90}
91
92#[derive(Debug)]
93pub struct ShaderModule {
94    pub(crate) state: ResourceState<ShaderModuleState>,
95    pub(crate) device: Arc<Device>,
96    /// The `label` from the descriptor used to create the resource.
97    pub(crate) label: String,
98    pub(crate) compilation_info: wgt::CompilationInfo,
99}
100
101impl Drop for ShaderModule {
102    #[allow(trivial_casts)]
103    fn drop(&mut self) {
104        profiling::scope!("ShaderModule::drop");
105        api_log!("ShaderModule::drop {:?}", self as *const _);
106        resource_log!("Destroy raw {}", self.error_ident());
107        #[cfg(feature = "trace")]
108        if let Some(t) = self.device.trace.lock().as_mut() {
109            use crate::device::trace::{to_trace, Action};
110
111            t.add(Action::DropShaderModule(unsafe { to_trace(self) }));
112        }
113        let ResourceState::Valid(state) =
114            core::mem::replace(&mut self.state, ResourceState::Invalid)
115        else {
116            return;
117        };
118        match state {
119            ShaderModuleState::NagaModule { .. } => {}
120            ShaderModuleState::Passthrough { raw, .. } => unsafe {
121                self.device.raw().destroy_shader_module(raw);
122            },
123        }
124    }
125}
126
127crate::impl_resource_type!(ShaderModule);
128crate::impl_labeled!(ShaderModule);
129crate::impl_parent_device!(ShaderModule);
130crate::impl_storage_item!(ShaderModule);
131
132impl ShaderModule {
133    pub(crate) fn state(&self) -> Result<&ShaderModuleState, InvalidResourceError> {
134        let ResourceState::Valid(state) = &self.state else {
135            return Err(InvalidResourceError(self.error_ident()));
136        };
137        Ok(state)
138    }
139
140    pub(crate) fn invalid(
141        device: Arc<Device>,
142        label: String,
143        compilation_info: wgt::CompilationInfo,
144    ) -> Arc<Self> {
145        Arc::new(Self {
146            state: ResourceState::Invalid,
147            device,
148            label,
149            compilation_info,
150        })
151    }
152
153    pub fn compilation_info(&self) -> &wgt::CompilationInfo {
154        &self.compilation_info
155    }
156
157    /// Select an entry point name, given an optional name and a shader stage.
158    ///
159    /// This function resolves an `Option<&str>`
160    /// [`ProgrammableStageDescriptor::entry_point`][ep] value to the name of an
161    /// entry point in `self`.
162    ///
163    /// If `entry_point` is given, verify that `self` has an entry point by that
164    /// name for `stage`, and then return the name as an owned `String`.
165    ///
166    /// If `entry_point` is `None`, verify that `self` has exactly one entry
167    /// point for `stage`, and return its name.
168    ///
169    /// Passthrough modules do not record entry points' stages, so for those,
170    /// `stage` is ignored.
171    ///
172    /// [ep]: crate::pipeline::ProgrammableStageDescriptor::entry_point
173    pub(crate) fn finalize_entry_point_name(
174        &self,
175        stage: naga::ShaderStage,
176        entry_point: Option<&str>,
177    ) -> Result<String, validation::StageError> {
178        let state = self.state()?;
179        match state {
180            ShaderModuleState::NagaModule { ref shader, .. } => {
181                finalize_naga_entry_point_name(&shader.module, stage, entry_point)
182            }
183            ShaderModuleState::Passthrough { ref interface, .. } => {
184                finalize_passthrough_entry_point_name(interface, entry_point)
185            }
186        }
187    }
188}
189
190fn finalize_naga_entry_point_name(
191    module: &naga::Module,
192    stage: naga::ShaderStage,
193    entry_point: Option<&str>,
194) -> Result<String, validation::StageError> {
195    let mut candidates = module.entry_points.iter().filter(|ep| ep.stage == stage);
196    if let Some(name) = entry_point {
197        return match candidates.find(|ep| ep.name == name) {
198            Some(ep) => Ok(ep.name.clone()),
199            None => Err(validation::StageError::NoEntryPointWithNameForStage {
200                stage,
201                name: name.to_owned(),
202            }),
203        };
204    }
205
206    let Some(first) = candidates.next() else {
207        return Err(validation::StageError::NoEntryPointForStage(stage));
208    };
209    if candidates.next().is_some() {
210        return Err(validation::StageError::AmbiguousEntryPointForStage(stage));
211    }
212    Ok(first.name.clone())
213}
214
215fn finalize_passthrough_entry_point_name(
216    interface: &PassthroughInterface,
217    entry_point: Option<&str>,
218) -> Result<String, validation::StageError> {
219    if let Some(ep) = entry_point {
220        return if interface.entry_point_names.contains(ep) {
221            Ok(ep.to_owned())
222        } else {
223            Err(validation::StageError::NoEntryPointWithName(ep.to_owned()))
224        };
225    }
226
227    match interface.entry_point_names.len() {
228        0 => Err(validation::StageError::NoEntryPoints),
229        1 => Ok(interface
230            .entry_point_names
231            .iter()
232            .next()
233            .unwrap()
234            .to_owned()),
235        _ => Err(validation::StageError::AmbiguousEntryPoint),
236    }
237}
238
239//Note: `Clone` would require `WithSpan: Clone`.
240#[derive(Clone, Debug, Error)]
241#[non_exhaustive]
242pub enum CreateShaderModuleError {
243    // These variants deliberately don't forward to `ShaderError`'s `Display`,
244    // which would include the shader source text and detailed compiler messages:
245    // per the WebGPU specification <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createshadermodule>,
246    // the message of the validation error raised by `createShaderModule` should not include those details,
247    // since they are accessible via `getCompilationInfo()`.
248    #[cfg(feature = "wgsl")]
249    #[error("Shader '{label}' parsing error. Concrete error is available via `get_compilation_info`", label = _0.label.as_deref().unwrap_or_default())]
250    Parsing(ShaderError<naga::front::wgsl::ParseError>),
251
252    #[cfg(feature = "glsl")]
253    #[error("Shader '{label}' parsing error. Concrete error is available via `get_compilation_info`", label = _0.label.as_deref().unwrap_or_default())]
254    ParsingGlsl(ShaderError<naga::front::glsl::ParseErrors>),
255
256    #[cfg(feature = "spirv")]
257    #[error("Shader '{label}' parsing error. Concrete error is available via `get_compilation_info`", label = _0.label.as_deref().unwrap_or_default())]
258    ParsingSpirV(ShaderError<naga::front::spv::Error>),
259
260    #[error("Failed to generate the backend-specific code")]
261    Generation,
262
263    #[error(transparent)]
264    Device(#[from] DeviceError),
265
266    #[error("Shader '{label}' validation error. Concrete error is available via `get_compilation_info`", label = _0.label.as_deref().unwrap_or_default())]
267    Validation(ShaderError<naga::WithSpan<naga::valid::ValidationError>>),
268
269    #[error(transparent)]
270    MissingFeatures(#[from] MissingFeatures),
271
272    #[error(
273        "Shader global {bind:?} uses a group index {group} that exceeds the max_bind_groups limit of {limit}."
274    )]
275    InvalidGroupIndex {
276        bind: naga::ResourceBinding,
277        group: u32,
278        limit: u32,
279    },
280
281    #[error("Generic shader passthrough does not contain any code compatible with this backend.")]
282    NotCompiledForBackend,
283
284    #[error(
285        "Generic passthrough shaders which use GLSL or DXIL must contain exactly one entry point."
286    )]
287    IncorrectPassthroughEntryPointCount,
288}
289
290impl WebGpuError for CreateShaderModuleError {
291    fn webgpu_error_type(&self) -> ErrorType {
292        match self {
293            Self::Device(e) => e.webgpu_error_type(),
294            Self::MissingFeatures(e) => e.webgpu_error_type(),
295
296            Self::Generation => ErrorType::Internal,
297
298            Self::Validation(..)
299            | Self::InvalidGroupIndex { .. }
300            | Self::IncorrectPassthroughEntryPointCount
301            | Self::NotCompiledForBackend => ErrorType::Validation,
302            #[cfg(feature = "wgsl")]
303            Self::Parsing(..) => ErrorType::Validation,
304            #[cfg(feature = "glsl")]
305            Self::ParsingGlsl(..) => ErrorType::Validation,
306            #[cfg(feature = "spirv")]
307            Self::ParsingSpirV(..) => ErrorType::Validation,
308        }
309    }
310}
311
312#[cfg(feature = "wgsl")]
313pub(crate) fn wgsl_to_compilation_info(
314    value: &ShaderError<naga::front::wgsl::ParseError>,
315) -> wgt::CompilationInfo {
316    use alloc::{string::ToString, vec};
317    wgt::CompilationInfo {
318        messages: vec![wgt::CompilationMessage {
319            message: value.to_string(),
320            message_type: wgt::CompilationMessageType::Error,
321            location: value
322                .inner
323                .location(&value.source)
324                .as_ref()
325                .map(naga_to_source_location),
326        }],
327    }
328}
329#[cfg(feature = "glsl")]
330pub(crate) fn glsl_to_compilation_info(
331    value: &ShaderError<naga::front::glsl::ParseErrors>,
332) -> wgt::CompilationInfo {
333    use alloc::string::ToString;
334    let messages = value
335        .inner
336        .errors
337        .iter()
338        .map(|err| wgt::CompilationMessage {
339            message: err.to_string(),
340            message_type: wgt::CompilationMessageType::Error,
341            location: err
342                .location(&value.source)
343                .as_ref()
344                .map(naga_to_source_location),
345        })
346        .collect();
347    wgt::CompilationInfo { messages }
348}
349
350#[cfg(feature = "spirv")]
351pub(crate) fn spirv_to_compilation_info(
352    value: &ShaderError<naga::front::spv::Error>,
353) -> wgt::CompilationInfo {
354    use alloc::{string::ToString, vec};
355    wgt::CompilationInfo {
356        messages: vec![wgt::CompilationMessage {
357            message: value.to_string(),
358            message_type: wgt::CompilationMessageType::Error,
359            location: None,
360        }],
361    }
362}
363
364pub(crate) fn naga_to_compilation_info(
365    value: &ShaderError<naga::WithSpan<naga::valid::ValidationError>>,
366) -> wgt::CompilationInfo {
367    use alloc::{string::ToString, vec};
368    wgt::CompilationInfo {
369        messages: vec![wgt::CompilationMessage {
370            message: value.to_string(),
371            message_type: wgt::CompilationMessageType::Error,
372            location: value
373                .inner
374                .location(&value.source)
375                .as_ref()
376                .map(naga_to_source_location),
377        }],
378    }
379}
380
381fn naga_to_source_location(value: &naga::SourceLocation) -> wgt::SourceLocation {
382    wgt::SourceLocation {
383        length: value.length,
384        offset: value.offset,
385        line_number: value.line_number,
386        line_position: value.line_position,
387    }
388}
389
390pub(crate) fn shader_module_error_into_compilation_info(
391    value: &CreateShaderModuleError,
392) -> wgt::CompilationInfo {
393    match value {
394        #[cfg(feature = "wgsl")]
395        CreateShaderModuleError::Parsing(v) => wgsl_to_compilation_info(v),
396        #[cfg(feature = "glsl")]
397        CreateShaderModuleError::ParsingGlsl(v) => glsl_to_compilation_info(v),
398        #[cfg(feature = "spirv")]
399        CreateShaderModuleError::ParsingSpirV(v) => spirv_to_compilation_info(v),
400        CreateShaderModuleError::Validation(v) => naga_to_compilation_info(v),
401        // Device errors are reported through the error sink, and are not compilation errors.
402        // Same goes for native shader module generation errors.
403        CreateShaderModuleError::Device(_) | CreateShaderModuleError::Generation => {
404            wgt::CompilationInfo {
405                messages: Vec::new(),
406            }
407        }
408        // Everything else is an error message without location information.
409        _ => wgt::CompilationInfo {
410            messages: alloc::vec![wgt::CompilationMessage {
411                message: value.to_string(),
412                message_type: wgt::CompilationMessageType::Error,
413                location: None,
414            }],
415        },
416    }
417}
418
419/// Describes a programmable pipeline stage.
420#[derive(Clone, Debug)]
421#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
422/// cbindgen:ignore
423pub struct ProgrammableStageDescriptor<'a, SM = Arc<ShaderModule>> {
424    /// The compiled shader module for this stage.
425    pub module: SM,
426
427    /// The name of the entry point in `module` that this stage should use.
428    ///
429    /// - If this is `Some(name)`, `module` must contain an entry point with the
430    ///   given name.
431    ///
432    /// - If this is `None`, `module` must have only one entry point for this
433    ///   stage; we use that one.
434    pub entry_point: Option<Cow<'a, str>>,
435
436    /// Values for pipeline-overridable constants in `module` that this stage
437    /// should use.
438    ///
439    /// If an `@id` attribute was specified on the declaration,
440    /// the key must be the pipeline constant ID as a decimal ASCII number; if not,
441    /// the key must be the constant's identifier name.
442    ///
443    /// The value may represent any of WGSL's concrete scalar types.
444    pub constants: naga::back::PipelineConstants,
445
446    /// Whether variables in the workgroup address space will be initialized
447    /// with zero values for this stage.
448    ///
449    /// The WebGPU spec requires variables in the workgroup address space to be
450    /// zeroed. However, initialization does impose some overhead, and
451    /// non-browser applications may not need it.
452    pub zero_initialize_workgroup_memory: bool,
453}
454
455#[derive(Clone, Debug, Error)]
456#[non_exhaustive]
457pub enum CreatePipelineError {
458    #[error(transparent)]
459    Device(#[from] DeviceError),
460    #[error("Unable to derive an implicit layout")]
461    Implicit(#[from] ImplicitLayoutError),
462    #[error("Error matching {stage:?} shader requirements against the pipeline")]
463    Stage {
464        stage: wgt::ShaderStages,
465        #[source]
466        error: validation::StageError,
467    },
468    #[error("Internal error in {stage:?} shader: {message}")]
469    Internal {
470        stage: wgt::ShaderStages,
471        message: String,
472    },
473    #[error("Pipeline constant error in {stage:?} shader: {message}")]
474    PipelineConstants {
475        stage: wgt::ShaderStages,
476        message: String,
477    },
478    #[error(transparent)]
479    MissingFeatures(#[from] MissingFeatures),
480    #[error(transparent)]
481    MissingDownlevelFlags(#[from] MissingDownlevelFlags),
482    #[error(transparent)]
483    InvalidResource(#[from] InvalidResourceError),
484    #[error(transparent)]
485    Render(#[from] RenderError),
486    #[error(transparent)]
487    RayTracing(#[from] RayTracingPipelineError),
488}
489
490impl From<ColorAttachmentError> for CreatePipelineError {
491    fn from(error: ColorAttachmentError) -> Self {
492        Self::Render(error.into())
493    }
494}
495
496impl From<DepthStencilStateError> for CreatePipelineError {
497    fn from(error: DepthStencilStateError) -> Self {
498        Self::Render(error.into())
499    }
500}
501
502impl CreatePipelineError {
503    /// Convert a [`hal::PipelineError`] to a [`CreatePipelineError`], without noting device loss.
504    ///
505    /// If you have a [`Device`] handy, prefer to call
506    /// [`Device::handle_hal_pipeline_error`] instead, since that checks for
507    /// device loss errors and sets the device's lost flag accordingly.
508    ///
509    /// This is deliberately not a `From` impl, so that `?` cannot silently skip
510    /// device-loss handling.
511    pub(crate) fn from_hal_without_device_loss(error: hal::PipelineError) -> Self {
512        match error {
513            hal::PipelineError::Device(error) => {
514                CreatePipelineError::Device(DeviceError::from_hal(error))
515            }
516            hal::PipelineError::Linkage(stage, message) => {
517                CreatePipelineError::Internal { stage, message }
518            }
519            hal::PipelineError::EntryPoint(stage) => CreatePipelineError::Internal {
520                stage: hal::auxil::map_naga_stage(stage),
521                message: crate::device::ENTRYPOINT_FAILURE_ERROR.to_string(),
522            },
523            hal::PipelineError::PipelineConstants(stage, message) => {
524                CreatePipelineError::PipelineConstants { stage, message }
525            }
526        }
527    }
528}
529
530/// Number of implicit bind groups derived at pipeline creation.
531pub type ImplicitBindGroupCount = u8;
532
533#[derive(Clone, Debug, Error)]
534#[non_exhaustive]
535pub enum ImplicitLayoutError {
536    #[error(transparent)]
537    BindGroup(#[from] CreateBindGroupLayoutError),
538    #[error(transparent)]
539    Pipeline(#[from] CreatePipelineLayoutError),
540    #[error("Unable to create implicit pipeline layout from passthrough shader stage: {0:?}")]
541    Passthrough(wgt::ShaderStages),
542}
543
544impl WebGpuError for ImplicitLayoutError {
545    fn webgpu_error_type(&self) -> ErrorType {
546        match self {
547            Self::BindGroup(e) => e.webgpu_error_type(),
548            Self::Pipeline(e) => e.webgpu_error_type(),
549            Self::Passthrough(_) => ErrorType::Validation,
550        }
551    }
552}
553
554/// Describes a compute pipeline.
555#[derive(Clone, Debug)]
556#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
557/// cbindgen:ignore
558pub struct ComputePipelineDescriptor<
559    'a,
560    PLL = Arc<PipelineLayout>,
561    SM = Arc<ShaderModule>,
562    PLC = Arc<PipelineCache>,
563> {
564    pub label: Label<'a>,
565    /// The layout of bind groups for this pipeline.
566    pub layout: Option<PLL>,
567    /// The compiled compute stage and its entry point.
568    pub stage: ProgrammableStageDescriptor<'a, SM>,
569    /// The pipeline cache to use when creating this pipeline.
570    pub cache: Option<PLC>,
571}
572
573impl WebGpuError for CreatePipelineError {
574    fn webgpu_error_type(&self) -> ErrorType {
575        match self {
576            Self::Device(e) => e.webgpu_error_type(),
577            Self::InvalidResource(e) => e.webgpu_error_type(),
578            Self::MissingFeatures(e) => e.webgpu_error_type(),
579            Self::MissingDownlevelFlags(e) => e.webgpu_error_type(),
580            Self::Implicit(e) => e.webgpu_error_type(),
581            Self::Stage { error: e, .. } => e.webgpu_error_type(),
582            Self::Internal { .. } => ErrorType::Internal,
583            Self::PipelineConstants { .. } => ErrorType::Validation,
584            Self::Render(e) => e.webgpu_error_type(),
585            Self::RayTracing(e) => e.webgpu_error_type(),
586        }
587    }
588}
589
590#[derive(Debug)]
591pub struct ComputePipelineState {
592    pub(crate) raw: ManuallyDrop<Box<dyn hal::DynComputePipeline>>,
593    pub(crate) layout: Arc<PipelineLayout>,
594    pub(crate) _shader_module: Arc<ShaderModule>,
595}
596
597#[derive(Debug)]
598pub struct ComputePipeline {
599    pub(crate) state: ResourceState<ComputePipelineState>,
600    pub(crate) device: Arc<Device>,
601    pub(crate) late_sized_buffer_groups: ArrayVec<LateSizedBufferGroup, { hal::MAX_BIND_GROUPS }>,
602    pub(crate) immediate_slots_required: naga::valid::ImmediateSlots,
603    /// The `label` from the descriptor used to create the resource.
604    pub(crate) label: String,
605    pub(crate) tracking_data: TrackingData,
606}
607
608impl Drop for ComputePipeline {
609    #[allow(trivial_casts)]
610    fn drop(&mut self) {
611        profiling::scope!("ComputePipeline::drop");
612        api_log!("ComputePipeline::drop {:?}", self as *const _);
613        resource_log!("Destroy raw {}", self.error_ident());
614        #[cfg(feature = "trace")]
615        {
616            use crate::device::trace;
617            if let Some(t) = self.device.trace.lock().as_mut() {
618                t.add(trace::Action::DropComputePipeline(unsafe {
619                    trace::to_trace(self)
620                }));
621            }
622        }
623        let ResourceState::Valid(state) = &mut self.state else {
624            return;
625        };
626        // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
627        let raw = unsafe { ManuallyDrop::take(&mut state.raw) };
628        unsafe {
629            self.device.raw().destroy_compute_pipeline(raw);
630        }
631    }
632}
633
634crate::impl_resource_type!(ComputePipeline);
635crate::impl_labeled!(ComputePipeline);
636crate::impl_parent_device!(ComputePipeline);
637crate::impl_storage_item!(ComputePipeline);
638crate::impl_trackable!(ComputePipeline);
639
640impl ComputePipeline {
641    pub(crate) fn raw(&self) -> Result<&dyn hal::DynComputePipeline, InvalidResourceError> {
642        let ResourceState::Valid(state) = &self.state else {
643            return Err(InvalidResourceError(self.error_ident()));
644        };
645        Ok(state.raw.as_ref())
646    }
647
648    pub(crate) fn layout(&self) -> Result<&Arc<PipelineLayout>, InvalidResourceError> {
649        let ResourceState::Valid(state) = &self.state else {
650            return Err(InvalidResourceError(self.error_ident()));
651        };
652        Ok(&state.layout)
653    }
654
655    pub(crate) fn check_valid(&self) -> Result<(), InvalidResourceError> {
656        let ResourceState::Valid(_) = &self.state else {
657            return Err(InvalidResourceError(self.error_ident()));
658        };
659        Ok(())
660    }
661
662    pub(crate) fn invalid(device: Arc<Device>, label: String) -> Arc<Self> {
663        Arc::new(Self {
664            tracking_data: TrackingData::new(device.tracker_indices.compute_pipelines.clone()),
665            state: ResourceState::Invalid,
666            device,
667            late_sized_buffer_groups: ArrayVec::new(),
668            immediate_slots_required: naga::valid::ImmediateSlots::default(),
669            label,
670        })
671    }
672
673    pub fn get_bind_group_layout_inner(
674        self: &Arc<Self>,
675        index: u32,
676    ) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
677        self.layout()?.get_bind_group_layout(index, self.into())
678    }
679
680    pub fn get_bind_group_layout(self: &Arc<Self>, index: u32) -> Arc<BindGroupLayout> {
681        let bgl = self
682            .get_bind_group_layout_inner(index)
683            .unwrap_or_else(|err| {
684                self.device
685                    .handle_error_nolabel(err, "ComputePipeline::get_bind_group_layout");
686                BindGroupLayout::invalid(&self.device, String::new())
687            });
688        #[cfg(feature = "trace")]
689        if let Some(ref mut trace) = *self.device.trace.lock() {
690            use crate::device::trace;
691            use trace::IntoTrace;
692            trace.add(trace::Action::GetComputePipelineBindGroupLayout {
693                id: bgl.to_trace(),
694                pipeline: self.to_trace(),
695                index,
696            });
697        };
698        bgl
699    }
700
701    pub fn get_subgroup_size(self: &Arc<Self>) -> Option<u32> {
702        if !self
703            .device
704            .features
705            .contains(wgt::Features::COMPUTE_PIPELINE_SUBGROUP_SIZE)
706        {
707            return None;
708        }
709        self.raw()
710            .ok()
711            .and_then(hal::DynComputePipeline::get_subgroup_size)
712    }
713}
714
715#[derive(Clone, Debug, Error)]
716#[non_exhaustive]
717pub enum CreatePipelineCacheError {
718    #[error(transparent)]
719    Device(#[from] DeviceError),
720    #[error("Pipeline cache validation failed")]
721    Validation(#[from] PipelineCacheValidationError),
722    #[error(transparent)]
723    MissingFeatures(#[from] MissingFeatures),
724}
725
726impl WebGpuError for CreatePipelineCacheError {
727    fn webgpu_error_type(&self) -> ErrorType {
728        match self {
729            Self::Device(e) => e.webgpu_error_type(),
730            Self::Validation(e) => e.webgpu_error_type(),
731            Self::MissingFeatures(e) => e.webgpu_error_type(),
732        }
733    }
734}
735
736#[derive(Debug)]
737pub struct PipelineCache {
738    pub(crate) raw: ResourceState<Box<dyn hal::DynPipelineCache>>,
739    pub(crate) device: Arc<Device>,
740    /// The `label` from the descriptor used to create the resource.
741    pub(crate) label: String,
742}
743
744impl Drop for PipelineCache {
745    #[allow(trivial_casts)]
746    fn drop(&mut self) {
747        profiling::scope!("PipelineCache::drop");
748        api_log!("PipelineCache::drop {:?}", self as *const _);
749        #[cfg(feature = "trace")]
750        if let Some(t) = self.device.trace.lock().as_mut() {
751            use crate::device::trace::{to_trace, Action};
752            t.add(Action::DropPipelineCache(unsafe { to_trace(self) }));
753        }
754        resource_log!("Destroy raw {}", self.error_ident());
755        if let ResourceState::Valid(raw) = core::mem::replace(&mut self.raw, ResourceState::Invalid)
756        {
757            unsafe {
758                self.device.raw().destroy_pipeline_cache(raw);
759            }
760        }
761    }
762}
763
764crate::impl_resource_type!(PipelineCache);
765crate::impl_labeled!(PipelineCache);
766crate::impl_parent_device!(PipelineCache);
767crate::impl_storage_item!(PipelineCache);
768
769impl PipelineCache {
770    pub(crate) fn raw(&self) -> Result<&dyn hal::DynPipelineCache, InvalidResourceError> {
771        self.raw
772            .as_ref()
773            .valid()
774            .map(|raw| raw.as_ref())
775            .ok_or_else(|| InvalidResourceError(self.error_ident()))
776    }
777
778    pub(crate) fn check_is_valid(&self) -> Result<(), InvalidResourceError> {
779        self.raw().map(|_| ())
780    }
781
782    pub(crate) fn invalid(device: Arc<Device>, desc: &PipelineCacheDescriptor) -> Arc<Self> {
783        Arc::new(Self {
784            raw: ResourceState::Invalid,
785            device,
786            label: desc.label.to_string(),
787        })
788    }
789
790    pub fn get_data(self: &Arc<Self>) -> Option<Vec<u8>> {
791        api_log!("PipelineCache::get_data");
792
793        let ResourceState::Valid(raw) = &self.raw else {
794            return None;
795        };
796
797        if !self.device.is_valid() {
798            return None;
799        }
800        let mut vec = unsafe { self.device.raw().pipeline_cache_get_data(raw.as_ref()) }?;
801        let validation_key = self.device.raw().pipeline_cache_validation_key()?;
802
803        let mut header_contents = [0; pipeline_cache::HEADER_LENGTH];
804        pipeline_cache::add_cache_header(
805            &mut header_contents,
806            &vec,
807            &self.device.adapter.raw.info,
808            validation_key,
809        );
810
811        let deleted = vec.splice(..0, header_contents).collect::<Vec<_>>();
812        debug_assert!(deleted.is_empty());
813
814        Some(vec)
815    }
816}
817
818/// Describes how the vertex buffer is interpreted.
819#[derive(Clone, Debug)]
820#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
821#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
822pub struct VertexBufferLayout<'a> {
823    /// The stride, in bytes, between elements of this buffer.
824    pub array_stride: wgt::BufferAddress,
825    /// How often this vertex buffer is "stepped" forward.
826    pub step_mode: wgt::VertexStepMode,
827    /// The list of attributes which comprise a single vertex.
828    pub attributes: Cow<'a, [wgt::VertexAttribute]>,
829}
830
831/// A null vertex buffer layout that may be placed in unused slots.
832impl Default for VertexBufferLayout<'_> {
833    fn default() -> Self {
834        Self {
835            array_stride: Default::default(),
836            step_mode: Default::default(),
837            attributes: Cow::Borrowed(&[]),
838        }
839    }
840}
841
842/// Describes the vertex process in a render pipeline.
843#[derive(Clone, Debug)]
844#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
845/// cbindgen:ignore
846pub struct VertexState<'a, SM = Arc<ShaderModule>> {
847    /// The compiled vertex stage and its entry point.
848    pub stage: ProgrammableStageDescriptor<'a, SM>,
849    /// The format of any vertex buffers used with this pipeline.
850    pub buffers: Cow<'a, [Option<VertexBufferLayout<'a>>]>,
851}
852
853/// Describes fragment processing in a render pipeline.
854#[derive(Clone, Debug)]
855#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
856/// cbindgen:ignore
857pub struct FragmentState<'a, SM = Arc<ShaderModule>> {
858    /// The compiled fragment stage and its entry point.
859    pub stage: ProgrammableStageDescriptor<'a, SM>,
860    /// The effect of draw calls on the color aspect of the output target.
861    pub targets: Cow<'a, [Option<wgt::ColorTargetState>]>,
862}
863
864/// Describes the task shader in a mesh shader pipeline.
865#[derive(Clone, Debug)]
866#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
867pub struct TaskState<'a, SM = Arc<ShaderModule>> {
868    /// The compiled task stage and its entry point.
869    pub stage: ProgrammableStageDescriptor<'a, SM>,
870}
871
872/// Describes the mesh shader in a mesh shader pipeline.
873#[derive(Clone, Debug)]
874#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
875pub struct MeshState<'a, SM = Arc<ShaderModule>> {
876    /// The compiled mesh stage and its entry point.
877    pub stage: ProgrammableStageDescriptor<'a, SM>,
878}
879
880/// Describes a vertex processor for either a conventional or mesh shading
881/// pipeline architecture.
882///
883/// This is not a public API. It is for use by `player` only. The public APIs
884/// are [`VertexState`], [`TaskState`], and [`MeshState`].
885///
886/// cbindgen:ignore
887#[doc(hidden)]
888#[derive(Clone, Debug)]
889#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
890pub enum RenderPipelineVertexProcessor<'a, SM = Arc<ShaderModule>> {
891    Vertex(VertexState<'a, SM>),
892    Mesh(Option<TaskState<'a, SM>>, MeshState<'a, SM>),
893}
894
895/// Describes a render (graphics) pipeline.
896#[derive(Clone, Debug)]
897#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
898pub struct RenderPipelineDescriptor<
899    'a,
900    PLL = Arc<PipelineLayout>,
901    SM = Arc<ShaderModule>,
902    PLC = Arc<PipelineCache>,
903> {
904    pub label: Label<'a>,
905    /// The layout of bind groups for this pipeline.
906    pub layout: Option<PLL>,
907    /// The vertex processing state for this pipeline.
908    pub vertex: VertexState<'a, SM>,
909    /// The properties of the pipeline at the primitive assembly and rasterization level.
910    #[cfg_attr(feature = "serde", serde(default))]
911    pub primitive: wgt::PrimitiveState,
912    /// The effect of draw calls on the depth and stencil aspects of the output target, if any.
913    #[cfg_attr(feature = "serde", serde(default))]
914    pub depth_stencil: Option<wgt::DepthStencilState>,
915    /// The multi-sampling properties of the pipeline.
916    #[cfg_attr(feature = "serde", serde(default))]
917    pub multisample: wgt::MultisampleState,
918    /// The fragment processing state for this pipeline.
919    pub fragment: Option<FragmentState<'a, SM>>,
920    /// If the pipeline will be used with a multiview render pass, this indicates how many array
921    /// layers the attachments will have.
922    pub multiview_mask: Option<NonZeroU32>,
923    /// The pipeline cache to use when creating this pipeline.
924    pub cache: Option<PLC>,
925}
926/// Describes a mesh shader pipeline.
927#[derive(Clone, Debug)]
928#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
929pub struct MeshPipelineDescriptor<
930    'a,
931    PLL = Arc<PipelineLayout>,
932    SM = Arc<ShaderModule>,
933    PLC = Arc<PipelineCache>,
934> {
935    pub label: Label<'a>,
936    /// The layout of bind groups for this pipeline.
937    pub layout: Option<PLL>,
938    /// The task processing state for this pipeline.
939    pub task: Option<TaskState<'a, SM>>,
940    /// The mesh processing state for this pipeline
941    pub mesh: MeshState<'a, SM>,
942    /// The properties of the pipeline at the primitive assembly and rasterization level.
943    #[cfg_attr(feature = "serde", serde(default))]
944    pub primitive: wgt::PrimitiveState,
945    /// The effect of draw calls on the depth and stencil aspects of the output target, if any.
946    #[cfg_attr(feature = "serde", serde(default))]
947    pub depth_stencil: Option<wgt::DepthStencilState>,
948    /// The multi-sampling properties of the pipeline.
949    #[cfg_attr(feature = "serde", serde(default))]
950    pub multisample: wgt::MultisampleState,
951    /// The fragment processing state for this pipeline.
952    pub fragment: Option<FragmentState<'a, SM>>,
953    /// If the pipeline will be used with a multiview render pass, this indicates how many array
954    /// layers the attachments will have.
955    pub multiview: Option<NonZeroU32>,
956    /// The pipeline cache to use when creating this pipeline.
957    pub cache: Option<PLC>,
958}
959
960/// Describes a render (graphics) pipeline, with either conventional or mesh
961/// shading architecture.
962///
963/// This is not a public API. It is for use by `player` only. The public APIs
964/// are [`RenderPipelineDescriptor`] and [`MeshPipelineDescriptor`].
965///
966/// cbindgen:ignore
967#[doc(hidden)]
968#[derive(Clone, Debug)]
969#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
970pub struct GeneralRenderPipelineDescriptor<
971    'a,
972    PLL = Arc<PipelineLayout>,
973    SM = Arc<ShaderModule>,
974    PLC = Arc<PipelineCache>,
975> {
976    pub label: Label<'a>,
977    /// The layout of bind groups for this pipeline.
978    pub layout: Option<PLL>,
979    /// The vertex processing state for this pipeline.
980    pub vertex: RenderPipelineVertexProcessor<'a, SM>,
981    /// The properties of the pipeline at the primitive assembly and rasterization level.
982    #[cfg_attr(feature = "serde", serde(default))]
983    pub primitive: wgt::PrimitiveState,
984    /// The effect of draw calls on the depth and stencil aspects of the output target, if any.
985    #[cfg_attr(feature = "serde", serde(default))]
986    pub depth_stencil: Option<wgt::DepthStencilState>,
987    /// The multi-sampling properties of the pipeline.
988    #[cfg_attr(feature = "serde", serde(default))]
989    pub multisample: wgt::MultisampleState,
990    /// The fragment processing state for this pipeline.
991    pub fragment: Option<FragmentState<'a, SM>>,
992    /// If the pipeline will be used with a multiview render pass, this indicates how many array
993    /// layers the attachments will have.
994    pub multiview_mask: Option<NonZeroU32>,
995    /// The pipeline cache to use when creating this pipeline.
996    pub cache: Option<PLC>,
997}
998impl<'a, PLL, SM, PLC> From<RenderPipelineDescriptor<'a, PLL, SM, PLC>>
999    for GeneralRenderPipelineDescriptor<'a, PLL, SM, PLC>
1000{
1001    fn from(value: RenderPipelineDescriptor<'a, PLL, SM, PLC>) -> Self {
1002        Self {
1003            label: value.label,
1004            layout: value.layout,
1005            vertex: RenderPipelineVertexProcessor::Vertex(value.vertex),
1006            primitive: value.primitive,
1007            depth_stencil: value.depth_stencil,
1008            multisample: value.multisample,
1009            fragment: value.fragment,
1010            multiview_mask: value.multiview_mask,
1011            cache: value.cache,
1012        }
1013    }
1014}
1015impl<'a, PLL, SM, PLC> From<MeshPipelineDescriptor<'a, PLL, SM, PLC>>
1016    for GeneralRenderPipelineDescriptor<'a, PLL, SM, PLC>
1017{
1018    fn from(value: MeshPipelineDescriptor<'a, PLL, SM, PLC>) -> Self {
1019        Self {
1020            label: value.label,
1021            layout: value.layout,
1022            vertex: RenderPipelineVertexProcessor::Mesh(value.task, value.mesh),
1023            primitive: value.primitive,
1024            depth_stencil: value.depth_stencil,
1025            multisample: value.multisample,
1026            fragment: value.fragment,
1027            multiview_mask: value.multiview,
1028            cache: value.cache,
1029        }
1030    }
1031}
1032
1033/// Not a public API. For use by `player` only.
1034///
1035/// cbindgen:ignore
1036pub type ResolvedGeneralRenderPipelineDescriptor<'a> =
1037    GeneralRenderPipelineDescriptor<'a, Arc<PipelineLayout>, Arc<ShaderModule>, Arc<PipelineCache>>;
1038
1039#[derive(Clone, Debug)]
1040#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1041pub struct PipelineCacheDescriptor<'a> {
1042    pub label: Label<'a>,
1043    pub data: Option<Cow<'a, [u8]>>,
1044    pub fallback: bool,
1045}
1046
1047#[derive(Clone, Debug, Error)]
1048#[non_exhaustive]
1049pub enum ColorStateError {
1050    #[error("Format {0:?} is not renderable")]
1051    FormatNotRenderable(wgt::TextureFormat),
1052    #[error("Format {0:?} is not blendable")]
1053    FormatNotBlendable(wgt::TextureFormat),
1054    #[error("Format {0:?} does not have a color aspect")]
1055    FormatNotColor(wgt::TextureFormat),
1056    #[error("Sample count {0} is not supported by format {1:?} on this device. The WebGPU spec guarantees {2:?} samples are supported by this format. With the TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES feature your device supports {3:?}.")]
1057    InvalidSampleCount(u32, wgt::TextureFormat, Vec<u32>, Vec<u32>),
1058    #[error("Output format {pipeline} is incompatible with the shader {shader}")]
1059    IncompatibleFormat {
1060        pipeline: validation::NumericType,
1061        shader: validation::NumericType,
1062    },
1063    #[error("Invalid write mask {0:?}")]
1064    InvalidWriteMask(wgt::ColorWrites),
1065    #[error("Using the blend factor {factor:?} for render target {target} is not possible. Only the first render target may be used when dual-source blending.")]
1066    BlendFactorOnUnsupportedTarget {
1067        factor: wgt::BlendFactor,
1068        target: u32,
1069    },
1070    #[error("The {which} blend factor {factor:?} is not valid because the shader output does not have an alpha channel.")]
1071    InvalidAlphaBlend {
1072        which: &'static str,
1073        factor: wgt::BlendFactor,
1074    },
1075    #[error(
1076        "Blend factor {factor:?} for render target {target} is not valid. Blend factor must be `one` when using min/max blend operations."
1077    )]
1078    InvalidMinMaxBlendFactor {
1079        factor: wgt::BlendFactor,
1080        target: u32,
1081    },
1082    #[error("Shader does not produce an output at this index")]
1083    OutputNotPresent,
1084}
1085
1086#[derive(Clone, Debug, Error)]
1087#[non_exhaustive]
1088pub enum DepthStencilStateError {
1089    #[error("Format {0:?} is not renderable")]
1090    FormatNotRenderable(wgt::TextureFormat),
1091    #[error("Format {0:?} is not a depth/stencil format")]
1092    FormatNotDepthOrStencil(wgt::TextureFormat),
1093    #[error("Format {0:?} does not have a depth aspect, but depth test/write is enabled")]
1094    FormatNotDepth(wgt::TextureFormat),
1095    #[error("Format {0:?} does not have a stencil aspect, but stencil test/write is enabled")]
1096    FormatNotStencil(wgt::TextureFormat),
1097    #[error("Sample count {0} is not supported by format {1:?} on this device. The WebGPU spec guarantees {2:?} samples are supported by this format. With the TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES feature your device supports {3:?}.")]
1098    InvalidSampleCount(u32, wgt::TextureFormat, Vec<u32>, Vec<u32>),
1099    #[error("Depth bias is not compatible with non-triangle topology {0:?}")]
1100    DepthBiasWithIncompatibleTopology(wgt::PrimitiveTopology),
1101    #[error("Depth compare function must be specified for depth format {0:?}")]
1102    MissingDepthCompare(wgt::TextureFormat),
1103    #[error("Depth write enabled must be specified for depth format {0:?}")]
1104    MissingDepthWriteEnabled(wgt::TextureFormat),
1105}
1106
1107/// Errors specific to render pipeline creation.
1108///
1109/// These are usually returned as [`CreatePipelineError::Render`].
1110#[derive(Clone, Debug, Error)]
1111#[non_exhaustive]
1112pub enum RenderError {
1113    #[error(transparent)]
1114    ColorAttachment(#[from] ColorAttachmentError),
1115    #[error("Color state [{0}] is invalid")]
1116    ColorState(u8, #[source] ColorStateError),
1117    #[error("Depth/stencil state is invalid")]
1118    DepthStencilState(#[from] DepthStencilStateError),
1119    #[error("Invalid sample count {0}")]
1120    InvalidSampleCount(u32),
1121    #[error("The number of vertex buffers {given} exceeds the limit {limit}")]
1122    TooManyVertexBuffers { given: u32, limit: u32 },
1123    #[error("The number of bind groups + vertex buffers {given} exceeds the limit {limit}")]
1124    TooManyBindGroupsPlusVertexBuffers { given: u32, limit: u32 },
1125    #[error("The number of vertex-stage buffers and acceleration structures {given} exceeds the limit {limit}")]
1126    TooManyBuffersAndAccelerationStructuresInVertexStage { given: u32, limit: u32 },
1127    #[error("The total number of vertex attributes {given} exceeds the limit {limit}")]
1128    TooManyVertexAttributes { given: u32, limit: u32 },
1129    #[error("Vertex attribute location {given} must be less than limit {limit}")]
1130    VertexAttributeLocationTooLarge { given: u32, limit: u32 },
1131    #[error("Vertex buffer {index} stride {given} exceeds the limit {limit}")]
1132    VertexStrideTooLarge { index: u32, given: u32, limit: u32 },
1133    #[error("Vertex attribute at location {location} stride {given} exceeds the limit {limit}")]
1134    VertexAttributeStrideTooLarge {
1135        location: wgt::ShaderLocation,
1136        given: u32,
1137        limit: u32,
1138    },
1139    #[error("Vertex buffer {index} stride {stride} does not respect `VERTEX_ALIGNMENT`")]
1140    UnalignedVertexStride {
1141        index: u32,
1142        stride: wgt::BufferAddress,
1143    },
1144    #[error("Vertex attribute at location {location} has invalid offset {offset}")]
1145    InvalidVertexAttributeOffset {
1146        location: wgt::ShaderLocation,
1147        offset: wgt::BufferAddress,
1148    },
1149    #[error("Two or more vertex attributes were assigned to the same location in the shader: {0}")]
1150    ShaderLocationClash(u32),
1151    #[error("Strip index format was not set to None but to {strip_index_format:?} while using the non-strip topology {topology:?}")]
1152    StripIndexFormatForNonStripTopology {
1153        strip_index_format: Option<wgt::IndexFormat>,
1154        topology: wgt::PrimitiveTopology,
1155    },
1156    #[error("Conservative Rasterization is only supported for wgt::PolygonMode::Fill")]
1157    ConservativeRasterizationNonFillPolygonMode,
1158    #[error("In the provided shader, the type given for group {group} binding {binding} has a size of {size}. As the device does not support `DownlevelFlags::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED`, the type must have a size that is a multiple of 16 bytes.")]
1159    UnalignedShader { group: u32, binding: u32, size: u64 },
1160    #[error("Dual-source blending requires exactly one color target, but {count} color targets are present")]
1161    DualSourceBlendingWithMultipleColorTargets { count: usize },
1162    #[error("{}", concat!(
1163        "At least one color attachment or depth-stencil attachment was expected, ",
1164        "but no render target for the pipeline was specified."
1165    ))]
1166    NoTargetSpecified,
1167}
1168
1169impl WebGpuError for RenderError {
1170    fn webgpu_error_type(&self) -> ErrorType {
1171        match self {
1172            Self::ColorAttachment(_)
1173            | Self::ColorState(_, _)
1174            | Self::DepthStencilState(_)
1175            | Self::InvalidSampleCount(_)
1176            | Self::TooManyVertexBuffers { .. }
1177            | Self::TooManyBindGroupsPlusVertexBuffers { .. }
1178            | Self::TooManyBuffersAndAccelerationStructuresInVertexStage { .. }
1179            | Self::TooManyVertexAttributes { .. }
1180            | Self::VertexAttributeLocationTooLarge { .. }
1181            | Self::VertexStrideTooLarge { .. }
1182            | Self::UnalignedVertexStride { .. }
1183            | Self::InvalidVertexAttributeOffset { .. }
1184            | Self::ShaderLocationClash(_)
1185            | Self::StripIndexFormatForNonStripTopology { .. }
1186            | Self::ConservativeRasterizationNonFillPolygonMode
1187            | Self::UnalignedShader { .. }
1188            | Self::DualSourceBlendingWithMultipleColorTargets { .. }
1189            | Self::NoTargetSpecified
1190            | Self::VertexAttributeStrideTooLarge { .. } => ErrorType::Validation,
1191        }
1192    }
1193}
1194
1195bitflags::bitflags! {
1196    #[repr(transparent)]
1197    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1198    pub struct PipelineFlags: u32 {
1199        const BLEND_CONSTANT = 1 << 0;
1200        const STENCIL_REFERENCE = 1 << 1;
1201        const WRITES_DEPTH = 1 << 2;
1202        const WRITES_STENCIL = 1 << 3;
1203    }
1204}
1205
1206/// How a render pipeline will retrieve attributes from a particular vertex buffer.
1207#[derive(Clone, Copy, Debug)]
1208pub struct VertexStep {
1209    /// The byte stride in the buffer between one attribute value and the next.
1210    pub stride: wgt::BufferAddress,
1211
1212    /// The byte size required to fit the last vertex in the stream.
1213    pub last_stride: wgt::BufferAddress,
1214
1215    /// Whether the buffer is indexed by vertex number or instance number.
1216    pub mode: wgt::VertexStepMode,
1217}
1218
1219impl Default for VertexStep {
1220    fn default() -> Self {
1221        Self {
1222            stride: 0,
1223            last_stride: 0,
1224            mode: wgt::VertexStepMode::Vertex,
1225        }
1226    }
1227}
1228
1229#[derive(Debug)]
1230pub(crate) struct RenderPipelineState {
1231    pub(crate) raw: ManuallyDrop<Box<dyn hal::DynRenderPipeline>>,
1232    pub(crate) layout: Arc<PipelineLayout>,
1233}
1234
1235#[derive(Debug)]
1236pub struct RenderPipeline {
1237    pub(crate) state: ResourceState<RenderPipelineState>,
1238    pub(crate) device: Arc<Device>,
1239    pub(crate) _shader_modules: ArrayVec<Arc<ShaderModule>, { hal::MAX_CONCURRENT_SHADER_STAGES }>,
1240    pub(crate) pass_context: RenderPassContext,
1241    pub(crate) flags: PipelineFlags,
1242    pub(crate) topology: wgt::PrimitiveTopology,
1243    pub(crate) strip_index_format: Option<wgt::IndexFormat>,
1244    pub(crate) vertex_steps: Vec<Option<VertexStep>>,
1245    pub(crate) late_sized_buffer_groups: ArrayVec<LateSizedBufferGroup, { hal::MAX_BIND_GROUPS }>,
1246    pub(crate) immediate_slots_required: naga::valid::ImmediateSlots,
1247    /// The `label` from the descriptor used to create the resource.
1248    pub(crate) label: String,
1249    pub(crate) tracking_data: TrackingData,
1250    /// Whether this is a mesh shader pipeline
1251    pub(crate) is_mesh: bool,
1252    pub(crate) has_task_shader: bool,
1253}
1254
1255impl Drop for RenderPipeline {
1256    #[allow(trivial_casts)]
1257    fn drop(&mut self) {
1258        profiling::scope!("RenderPipeline::drop");
1259        api_log!("RenderPipeline::drop {:?}", self as *const _);
1260        resource_log!("Destroy raw {}", self.error_ident());
1261        #[cfg(feature = "trace")]
1262        {
1263            use crate::device::trace;
1264            if let Some(t) = self.device.trace.lock().as_mut() {
1265                t.add(trace::Action::DropRenderPipeline(unsafe {
1266                    trace::to_trace(self)
1267                }));
1268            }
1269        }
1270        let ResourceState::Valid(state) = &mut self.state else {
1271            return;
1272        };
1273        // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
1274        let raw = unsafe { ManuallyDrop::take(&mut state.raw) };
1275        unsafe {
1276            self.device.raw().destroy_render_pipeline(raw);
1277        }
1278    }
1279}
1280
1281crate::impl_resource_type!(RenderPipeline);
1282crate::impl_labeled!(RenderPipeline);
1283crate::impl_parent_device!(RenderPipeline);
1284crate::impl_storage_item!(RenderPipeline);
1285crate::impl_trackable!(RenderPipeline);
1286
1287impl RenderPipeline {
1288    pub(crate) fn raw(&self) -> Result<&dyn hal::DynRenderPipeline, InvalidResourceError> {
1289        let ResourceState::Valid(state) = &self.state else {
1290            return Err(InvalidResourceError(self.error_ident()));
1291        };
1292        Ok(state.raw.as_ref())
1293    }
1294
1295    pub(crate) fn layout(&self) -> Result<&Arc<PipelineLayout>, InvalidResourceError> {
1296        let ResourceState::Valid(state) = &self.state else {
1297            return Err(InvalidResourceError(self.error_ident()));
1298        };
1299        Ok(&state.layout)
1300    }
1301
1302    pub(crate) fn check_valid(&self) -> Result<(), InvalidResourceError> {
1303        let ResourceState::Valid(_) = &self.state else {
1304            return Err(InvalidResourceError(self.error_ident()));
1305        };
1306        Ok(())
1307    }
1308
1309    pub(crate) fn invalid(device: Arc<Device>, label: String) -> Arc<Self> {
1310        Arc::new(Self {
1311            tracking_data: TrackingData::new(device.tracker_indices.render_pipelines.clone()),
1312            state: ResourceState::Invalid,
1313            device,
1314            _shader_modules: ArrayVec::new(),
1315            pass_context: RenderPassContext {
1316                attachments: AttachmentData {
1317                    colors: ArrayVec::new(),
1318                    resolves: ArrayVec::new(),
1319                    depth_stencil: None,
1320                },
1321                sample_count: 0,
1322                multiview_mask: None,
1323            },
1324            flags: PipelineFlags::empty(),
1325            topology: wgt::PrimitiveTopology::TriangleList,
1326            strip_index_format: None,
1327            vertex_steps: Vec::new(),
1328            late_sized_buffer_groups: ArrayVec::new(),
1329            immediate_slots_required: naga::valid::ImmediateSlots::default(),
1330            label,
1331            is_mesh: false,
1332            has_task_shader: false,
1333        })
1334    }
1335
1336    pub fn get_bind_group_layout_inner(
1337        self: &Arc<Self>,
1338        index: u32,
1339    ) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
1340        self.layout()?.get_bind_group_layout(index, self.into())
1341    }
1342
1343    pub fn get_bind_group_layout(self: &Arc<Self>, index: u32) -> Arc<BindGroupLayout> {
1344        let bgl = self
1345            .get_bind_group_layout_inner(index)
1346            .unwrap_or_else(|err| {
1347                self.device
1348                    .handle_error_nolabel(err, "RenderPipeline::get_bind_group_layout");
1349                BindGroupLayout::invalid(&self.device, String::new())
1350            });
1351        #[cfg(feature = "trace")]
1352        if let Some(ref mut trace) = *self.device.trace.lock() {
1353            use crate::device::trace;
1354            use trace::IntoTrace;
1355            trace.add(trace::Action::GetRenderPipelineBindGroupLayout {
1356                id: bgl.to_trace(),
1357                pipeline: self.to_trace(),
1358                index,
1359            });
1360        };
1361        bgl
1362    }
1363}
1364
1365#[cfg(test)]
1366mod tests {
1367    use super::*;
1368
1369    fn passthrough_interface(entry_point_names: &[&str]) -> PassthroughInterface {
1370        PassthroughInterface {
1371            entry_point_names: entry_point_names
1372                .iter()
1373                .map(|name| (*name).to_owned())
1374                .collect(),
1375        }
1376    }
1377
1378    #[test]
1379    fn select_implicit_passthrough_entry_point() {
1380        let empty = passthrough_interface(&[]);
1381        assert!(matches!(
1382            finalize_passthrough_entry_point_name(&empty, None),
1383            Err(validation::StageError::NoEntryPoints)
1384        ));
1385
1386        let single = passthrough_interface(&["main"]);
1387        assert_eq!(
1388            finalize_passthrough_entry_point_name(&single, None).unwrap(),
1389            "main"
1390        );
1391
1392        let multiple = passthrough_interface(&["vertex", "fragment"]);
1393        assert!(matches!(
1394            finalize_passthrough_entry_point_name(&multiple, None),
1395            Err(validation::StageError::AmbiguousEntryPoint)
1396        ));
1397    }
1398
1399    #[test]
1400    fn select_explicit_passthrough_entry_point() {
1401        let interface = passthrough_interface(&["main"]);
1402        assert_eq!(
1403            finalize_passthrough_entry_point_name(&interface, Some("main")).unwrap(),
1404            "main"
1405        );
1406        assert!(matches!(
1407            finalize_passthrough_entry_point_name(&interface, Some("missing")),
1408            Err(validation::StageError::NoEntryPointWithName(name)) if name == "missing"
1409        ));
1410    }
1411}