Skip to main content

wgpu/api/
render_pipeline.rs

1use core::num::NonZeroU32;
2
3use crate::*;
4
5/// Handle to a rendering (graphics) pipeline.
6///
7/// A `RenderPipeline` object represents a graphics pipeline and its stages, bindings, vertex
8/// buffers and targets. It can be created with [`Device::create_render_pipeline`].
9///
10/// Corresponds to [WebGPU `GPURenderPipeline`](https://gpuweb.github.io/gpuweb/#render-pipeline).
11#[derive(Debug, Clone)]
12pub struct RenderPipeline {
13    pub(crate) inner: dispatch::DispatchRenderPipeline,
14}
15#[cfg(send_sync)]
16static_assertions::assert_impl_all!(RenderPipeline: Send, Sync);
17
18crate::cmp::impl_eq_ord_hash_proxy!(RenderPipeline => .inner);
19
20impl RenderPipeline {
21    /// Get an object representing the bind group layout at a given index.
22    ///
23    /// If this pipeline was created with a [default layout][RenderPipelineDescriptor::layout], then
24    /// bind groups created with the returned `BindGroupLayout` can only be used with this pipeline.
25    ///
26    /// This method will raise a validation error if there is no bind group layout at `index`.
27    pub fn get_bind_group_layout(&self, index: u32) -> BindGroupLayout {
28        let layout = self.inner.get_bind_group_layout(index);
29        BindGroupLayout { inner: layout }
30    }
31
32    #[cfg(custom)]
33    /// Returns custom implementation of RenderPipeline (if custom backend and is internally T)
34    pub fn as_custom<T: custom::RenderPipelineInterface>(&self) -> Option<&T> {
35        self.inner.as_custom()
36    }
37}
38
39#[cfg(wgpu_core)]
40impl RenderPipeline {
41    /// Create a new render pipeline of wgpu from a wgpu-core render pipeline.
42    ///
43    /// # Arguments
44    ///
45    /// - `core_render_pipeline` - wgpu-core render pipeline.
46    pub fn from_core(
47        core_render_pipeline: alloc::sync::Arc<wgc::pipeline::RenderPipeline>,
48    ) -> Self {
49        Self {
50            inner: crate::backend::wgpu_core::CoreRenderPipeline::from_core(core_render_pipeline)
51                .into(),
52        }
53    }
54
55    /// Returns the underlying wgpu-core render pipeline if this `RenderPipeline` is on the wgpu-core backend, otherwise `None`.
56    pub fn as_core(&self) -> Option<alloc::sync::Arc<wgc::pipeline::RenderPipeline>> {
57        self.inner.as_core_opt().map(|rp| rp.as_core())
58    }
59}
60
61/// Specifies an interpretation of the bytes of a vertex buffer as vertex attributes.
62///
63/// Use this in a [`RenderPipelineDescriptor`] to describe the format of the vertex buffers that
64/// are passed to [`RenderPass::set_vertex_buffer()`].
65///
66/// Corresponds to [WebGPU `GPUVertexBufferLayout`](
67/// https://gpuweb.github.io/gpuweb/#dictdef-gpuvertexbufferlayout).
68///
69/// # Example
70///
71/// The following example defines a `struct` with three fields,
72/// and a [`VertexBufferLayout`] that contains [`VertexAttribute`]s for each field,
73/// using the [`vertex_attr_array!`] macro to compute attribute offsets:
74///
75/// ```
76/// #[repr(C, packed)]
77/// struct Vertex {
78///     foo: [f32; 2],
79///     bar: f32,
80///     baz: [u16; 4],
81/// }
82///
83/// impl Vertex {
84///     /// Layout to use with a buffer whose contents are a `[Vertex]`.
85///     pub const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
86///         array_stride: size_of::<Self>() as wgpu::BufferAddress,
87///         step_mode: wgpu::VertexStepMode::Vertex,
88///         attributes: &wgpu::vertex_attr_array![
89///             0 => Float32x2,
90///             1 => Float32,
91///             2 => Uint16x4,
92///         ],
93///     };
94/// }
95///
96/// # assert_eq!(Vertex::LAYOUT.attributes[2].offset, Vertex::LAYOUT.array_stride - 2 * 4);
97#[derive(Clone, Debug, Hash, Eq, PartialEq)]
98pub struct VertexBufferLayout<'a> {
99    /// The stride, in bytes, between elements of this buffer (between vertices).
100    ///
101    /// This must be a multiple of [`VERTEX_ALIGNMENT`].
102    pub array_stride: BufferAddress,
103    /// How often this vertex buffer is "stepped" forward.
104    pub step_mode: VertexStepMode,
105    /// The list of attributes which comprise a single vertex.
106    pub attributes: &'a [VertexAttribute],
107}
108static_assertions::assert_impl_all!(VertexBufferLayout<'_>: Send, Sync);
109
110/// Describes the vertex processing in a render pipeline.
111///
112/// For use in [`RenderPipelineDescriptor`].
113///
114/// Corresponds to [WebGPU `GPUVertexState`](
115/// https://gpuweb.github.io/gpuweb/#dictdef-gpuvertexstate).
116#[derive(Clone, Debug)]
117pub struct VertexState<'a> {
118    /// The compiled shader module for this stage.
119    pub module: &'a ShaderModule,
120    /// The name of the entry point in the compiled shader to use.
121    ///
122    /// If [`Some`], there must be a vertex-stage shader entry point with this name in `module`.
123    /// Otherwise, expect exactly one vertex-stage entry point in `module`, which will be
124    /// selected.
125    // NOTE: keep phrasing in sync. with `ComputePipelineDescriptor::entry_point`
126    // NOTE: keep phrasing in sync. with `FragmentState::entry_point`
127    // NOTE: keep phrasing in sync. with `RayTracingStage::entry_point`
128    pub entry_point: Option<&'a str>,
129    /// Advanced options for when this pipeline is compiled
130    ///
131    /// This implements `Default`, and for most users can be set to `Default::default()`
132    pub compilation_options: PipelineCompilationOptions<'a>,
133    /// The format of any vertex buffers used with this pipeline via
134    /// [`RenderPass::set_vertex_buffer()`].
135    ///
136    /// The attribute locations and types specified in this layout must match the
137    /// locations and types of the inputs to the `entry_point` function.
138    pub buffers: &'a [Option<VertexBufferLayout<'a>>],
139}
140#[cfg(send_sync)]
141static_assertions::assert_impl_all!(VertexState<'_>: Send, Sync);
142
143/// Describes the fragment processing in a render pipeline.
144///
145/// For use in [`RenderPipelineDescriptor`].
146///
147/// Corresponds to [WebGPU `GPUFragmentState`](
148/// https://gpuweb.github.io/gpuweb/#dictdef-gpufragmentstate).
149#[derive(Clone, Debug)]
150pub struct FragmentState<'a> {
151    /// The compiled shader module for this stage.
152    pub module: &'a ShaderModule,
153    /// The name of the entry point in the compiled shader to use.
154    ///
155    /// If [`Some`], there must be a `@fragment` shader entry point with this name in `module`.
156    /// Otherwise, expect exactly one fragment-stage entry point in `module`, which will be
157    /// selected.
158    // NOTE: keep phrasing in sync. with `ComputePipelineDescriptor::entry_point`
159    // NOTE: keep phrasing in sync. with `VertexState::entry_point`
160    pub entry_point: Option<&'a str>,
161    /// Advanced options for when this pipeline is compiled
162    ///
163    /// This implements `Default`, and for most users can be set to `Default::default()`
164    pub compilation_options: PipelineCompilationOptions<'a>,
165    /// The color state of the render targets.
166    pub targets: &'a [Option<ColorTargetState>],
167}
168#[cfg(send_sync)]
169static_assertions::assert_impl_all!(FragmentState<'_>: Send, Sync);
170
171/// Describes the task shader stage in a mesh shader pipeline.
172///
173/// For use in [`MeshPipelineDescriptor`]
174#[derive(Clone, Debug)]
175pub struct TaskState<'a> {
176    /// The compiled shader module for this stage.
177    pub module: &'a ShaderModule,
178
179    /// The name of the task shader entry point in the shader module to use.
180    ///
181    /// If [`Some`], there must be a task shader entry point with the given name
182    /// in `module`. Otherwise, there must be exactly one task shader entry
183    /// point in `module`, which will be selected.
184    pub entry_point: Option<&'a str>,
185
186    /// Advanced options for when this pipeline is compiled.
187    ///
188    /// This implements `Default`, and for most users can be set to `Default::default()`
189    pub compilation_options: PipelineCompilationOptions<'a>,
190}
191#[cfg(send_sync)]
192static_assertions::assert_impl_all!(TaskState<'_>: Send, Sync);
193
194/// Describes the mesh shader stage in a mesh shader pipeline.
195///
196/// For use in [`MeshPipelineDescriptor`]
197#[derive(Clone, Debug)]
198pub struct MeshState<'a> {
199    /// The compiled shader module for this stage.
200    pub module: &'a ShaderModule,
201    /// The name of the entry point in the compiled shader to use.
202    ///
203    /// If [`Some`], there must be a vertex-stage shader entry point with this name in `module`.
204    /// Otherwise, expect exactly one vertex-stage entry point in `module`, which will be
205    /// selected.
206    pub entry_point: Option<&'a str>,
207    /// Advanced options for when this pipeline is compiled
208    ///
209    /// This implements `Default`, and for most users can be set to `Default::default()`
210    pub compilation_options: PipelineCompilationOptions<'a>,
211}
212#[cfg(send_sync)]
213static_assertions::assert_impl_all!(MeshState<'_>: Send, Sync);
214
215/// Describes a render (graphics) pipeline.
216///
217/// For use with [`Device::create_render_pipeline`].
218///
219/// Corresponds to [WebGPU `GPURenderPipelineDescriptor`](
220/// https://gpuweb.github.io/gpuweb/#dictdef-gpurenderpipelinedescriptor).
221#[derive(Clone, Debug)]
222pub struct RenderPipelineDescriptor<'a> {
223    /// Debug label of the pipeline. This will show up in graphics debuggers for easy identification.
224    pub label: Label<'a>,
225    /// The layout of bind groups for this pipeline.
226    ///
227    /// If this is set, then [`Device::create_render_pipeline`] will raise a validation error if
228    /// the layout doesn't match what the shader module(s) expect.
229    ///
230    /// Using the same [`PipelineLayout`] for many [`RenderPipeline`] or [`ComputePipeline`]
231    /// pipelines guarantees that you don't have to rebind any resources when switching between
232    /// those pipelines.
233    ///
234    /// ## Default pipeline layout
235    ///
236    /// If `layout` is `None`, then the pipeline has a [default layout] created and used instead.
237    /// The default layout is deduced from the shader modules.
238    ///
239    /// You can use [`RenderPipeline::get_bind_group_layout`] to create bind groups for use with the
240    /// default layout. However, these bind groups cannot be used with any other pipelines. This is
241    /// convenient for simple pipelines, but using an explicit layout is recommended in most cases.
242    ///
243    /// [default layout]: https://www.w3.org/TR/webgpu/#default-pipeline-layout
244    pub layout: Option<&'a PipelineLayout>,
245    /// The compiled vertex stage, its entry point, and the input buffers layout.
246    pub vertex: VertexState<'a>,
247    /// The properties of the pipeline at the primitive assembly and rasterization level.
248    pub primitive: PrimitiveState,
249    /// The effect of draw calls on the depth and stencil aspects of the output target, if any.
250    pub depth_stencil: Option<DepthStencilState>,
251    /// The multi-sampling properties of the pipeline.
252    pub multisample: MultisampleState,
253    /// The compiled fragment stage, its entry point, and the color targets.
254    pub fragment: Option<FragmentState<'a>>,
255    /// If the pipeline will be used with a multiview render pass, this indicates what multiview
256    /// mask the render pass will be used with. The masks must match exactly.
257    ///
258    /// For example, if you wish to render to the first 2 layers, you would use 3=0b11. If you
259    /// wanted to render to only the 2nd layer, you would use 2=0b10. If you aren't using
260    /// multiview this should be `None`.
261    pub multiview_mask: Option<NonZeroU32>,
262    /// The pipeline cache to use when creating this pipeline.
263    pub cache: Option<&'a PipelineCache>,
264}
265#[cfg(send_sync)]
266static_assertions::assert_impl_all!(RenderPipelineDescriptor<'_>: Send, Sync);
267
268/// Describes a mesh shader (graphics) pipeline.
269///
270/// For use with [`Device::create_mesh_pipeline`]. A mesh pipeline is very much
271/// like a render pipeline, except that instead of [`RenderPass::draw`] it is
272/// invoked with [`RenderPass::draw_mesh_tasks`], and instead of a vertex shader
273/// and a fragment shader:
274///
275/// - [`task`] specifies an optional task shader entry point, which determines how
276///   many groups of mesh shaders to dispatch.
277///
278/// - [`mesh`] specifies a mesh shader entry point, which generates groups of
279///   primitives to draw
280///
281/// - [`fragment`] specifies as fragment shader for drawing those primitives,
282///   just like in an ordinary render pipeline.
283///
284/// The key difference is that, whereas a vertex shader is invoked on the
285/// elements of vertex buffers, the task shader gets to decide how many mesh
286/// shader workgroups to make, and then each mesh shader workgroup gets to
287/// decide which primitives it wants to generate, and what their vertex
288/// attributes are. Task and mesh shaders can use whatever they please as
289/// inputs, like a compute shader. However, they cannot use specialized vertex
290/// or index buffers.
291///
292/// A mesh pipeline is invoked by [`RenderPass::draw_mesh_tasks`], which looks
293/// like a compute shader dispatch with [`ComputePass::dispatch_workgroups`]:
294/// you pass `x`, `y`, and `z` values indicating the number of task shaders to
295/// invoke in parallel. The output value of the first thread in a task shader
296/// workgroup determines how many mesh workgroups should be dispatched from there.
297/// Those mesh workgroups also get a special payload passed from the task shader.
298///
299/// If the task shader is omitted, then the (`x`, `y`, `z`) parameters to
300/// `draw_mesh_tasks` are used to decide how many invocations of the mesh shader
301/// to invoke directly, without a task payload.
302///
303/// [vertex formats]: wgpu_types::VertexFormat
304/// [`task`]: Self::task
305/// [`mesh`]: Self::mesh
306/// [`fragment`]: Self::fragment
307#[derive(Clone, Debug)]
308pub struct MeshPipelineDescriptor<'a> {
309    /// Debug label of the pipeline. This will show up in graphics debuggers for easy identification.
310    pub label: Label<'a>,
311    /// The layout of bind groups for this pipeline.
312    ///
313    /// If this is set, then [`Device::create_render_pipeline`] will raise a validation error if
314    /// the layout doesn't match what the shader module(s) expect.
315    ///
316    /// Using the same [`PipelineLayout`] for many [`RenderPipeline`] or [`ComputePipeline`]
317    /// pipelines guarantees that you don't have to rebind any resources when switching between
318    /// those pipelines.
319    ///
320    /// ## Default pipeline layout
321    ///
322    /// If `layout` is `None`, then the pipeline has a [default layout] created and used instead.
323    /// The default layout is deduced from the shader modules.
324    ///
325    /// You can use [`RenderPipeline::get_bind_group_layout`] to create bind groups for use with the
326    /// default layout. However, these bind groups cannot be used with any other pipelines. This is
327    /// convenient for simple pipelines, but using an explicit layout is recommended in most cases.
328    ///
329    /// [default layout]: https://www.w3.org/TR/webgpu/#default-pipeline-layout
330    pub layout: Option<&'a PipelineLayout>,
331
332    /// The mesh pipeline's task shader.
333    ///
334    /// If this is `None`, the mesh pipeline has no task shader. Executing a
335    /// mesh drawing command simply dispatches a grid of mesh shaders directly.
336    ///
337    /// [`draw_mesh_tasks`]: RenderPass::draw_mesh_tasks
338    pub task: Option<TaskState<'a>>,
339
340    /// The compiled mesh stage and its entry point
341    pub mesh: MeshState<'a>,
342    /// The properties of the pipeline at the primitive assembly and rasterization level.
343    pub primitive: PrimitiveState,
344    /// The effect of draw calls on the depth and stencil aspects of the output target, if any.
345    pub depth_stencil: Option<DepthStencilState>,
346    /// The multi-sampling properties of the pipeline.
347    pub multisample: MultisampleState,
348    /// The compiled fragment stage, its entry point, and the color targets.
349    pub fragment: Option<FragmentState<'a>>,
350    /// If the pipeline will be used with a multiview render pass, this indicates how many array
351    /// layers the attachments will have.
352    pub multiview: Option<NonZeroU32>,
353    /// The pipeline cache to use when creating this pipeline.
354    pub cache: Option<&'a PipelineCache>,
355}
356#[cfg(send_sync)]
357static_assertions::assert_impl_all!(MeshPipelineDescriptor<'_>: Send, Sync);