wgpu_types/shader.rs
1use alloc::borrow::Cow;
2
3/// Describes how shader bound checks should be performed.
4#[derive(Copy, Clone, Debug)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6pub struct ShaderRuntimeChecks {
7 /// Enforce bounds checks in shaders, even if the underlying driver doesn't
8 /// support doing so natively.
9 ///
10 /// When this is `true`, `wgpu` promises that shaders can only read or
11 /// write the accessible region of a bindgroup's buffer bindings. If
12 /// the underlying graphics platform cannot implement these bounds checks
13 /// itself, `wgpu` will inject bounds checks before presenting the
14 /// shader to the platform.
15 ///
16 /// When this is `false`, `wgpu` only enforces such bounds checks if the
17 /// underlying platform provides a way to do so itself. `wgpu` does not
18 /// itself add any bounds checks to generated shader code.
19 ///
20 /// Note that `wgpu` users may try to initialize only those portions of
21 /// buffers that they anticipate might be read from. Passing `false` here
22 /// may allow shaders to see wider regions of the buffers than expected,
23 /// making such deferred initialization visible to the application.
24 pub bounds_checks: bool,
25 ///
26 /// If false, the caller MUST ensure that all passed shaders do not contain any infinite loops.
27 ///
28 /// If it does, backend compilers MAY treat such a loop as unreachable code and draw
29 /// conclusions about other safety-critical code paths. This option SHOULD NOT be disabled
30 /// when running untrusted code.
31 pub force_loop_bounding: bool,
32 /// If false, the caller **MUST** ensure that in all passed shaders every function operating
33 /// on a ray query must obey these rules (functions using wgsl naming)
34 /// - `rayQueryInitialize` must have called before `rayQueryProceed`
35 /// - `rayQueryProceed` must have been called, returned true and have hit an AABB before
36 /// `rayQueryGenerateIntersection` is called
37 /// - `rayQueryProceed` must have been called, returned true and have hit a triangle before
38 /// `rayQueryConfirmIntersection` is called
39 /// - `rayQueryProceed` must have been called and have returned true before `rayQueryTerminate`,
40 /// `getCandidateHitVertexPositions` or `rayQueryGetCandidateIntersection` is called
41 /// - `rayQueryProceed` must have been called and have returned false before `rayQueryGetCommittedIntersection`
42 /// or `getCommittedHitVertexPositions` are called
43 ///
44 /// It is the aim that these cases will not cause UB if this is set to true, but currently this will still happen on DX12 and Metal.
45 pub ray_query_initialization_tracking: bool,
46
47 /// If false, task shaders will not validate that the mesh shader grid they dispatch is within legal limits.
48 pub task_shader_dispatch_tracking: bool,
49
50 /// If false, mesh shaders won't clamp the output primitives' vertex indices, which can lead to
51 /// undefined behavior and arbitrary memory access.
52 pub mesh_shader_primitive_indices_clamp: bool,
53}
54
55impl ShaderRuntimeChecks {
56 /// Creates a new configuration where the shader is fully checked.
57 #[must_use]
58 pub const fn checked() -> Self {
59 unsafe { Self::all(true) }
60 }
61
62 /// Creates a new configuration where none of the checks are performed.
63 ///
64 /// # Safety
65 ///
66 /// See the documentation for the `set_*` methods for the safety requirements
67 /// of each sub-configuration.
68 #[must_use]
69 pub const fn unchecked() -> Self {
70 unsafe { Self::all(false) }
71 }
72
73 /// Creates a new configuration where all checks are enabled or disabled. To safely
74 /// create a configuration with all checks enabled, use [`ShaderRuntimeChecks::checked`].
75 ///
76 /// # Safety
77 ///
78 /// See the documentation for the `set_*` methods for the safety requirements
79 /// of each sub-configuration.
80 #[must_use]
81 pub const unsafe fn all(all_checks: bool) -> Self {
82 Self {
83 bounds_checks: all_checks,
84 force_loop_bounding: all_checks,
85 ray_query_initialization_tracking: all_checks,
86 task_shader_dispatch_tracking: all_checks,
87 mesh_shader_primitive_indices_clamp: all_checks,
88 }
89 }
90}
91
92impl Default for ShaderRuntimeChecks {
93 fn default() -> Self {
94 Self::checked()
95 }
96}
97
98/// Descriptor for a shader module given by any of several sources.
99/// These shaders are passed through directly to the underlying api.
100/// At least one shader type that may be used by the backend must be `Some` or a panic is raised.
101#[derive(Debug, Clone)]
102#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
103pub struct CreateShaderModuleDescriptorPassthrough<'a, L> {
104 /// Debug label of the shader module. This will show up in graphics debuggers for easy identification.
105 pub label: L,
106 /// Number of workgroups in each dimension x, y and z. Unused for Spir-V.
107 pub num_workgroups: (u32, u32, u32),
108
109 /// Binary SPIR-V data, in 4-byte words.
110 pub spirv: Option<Cow<'a, [u32]>>,
111 /// Shader DXIL source.
112 pub dxil: Option<Cow<'a, [u8]>>,
113 /// Shader HLSL source.
114 pub hlsl: Option<Cow<'a, str>>,
115 /// Shader MetalLib source.
116 pub metallib: Option<Cow<'a, [u8]>>,
117 /// Shader MSL source.
118 pub msl: Option<Cow<'a, str>>,
119 /// Shader GLSL source (currently unused).
120 pub glsl: Option<Cow<'a, str>>,
121 /// Shader WGSL source.
122 pub wgsl: Option<Cow<'a, str>>,
123}
124
125// This is so people don't have to fill in fields they don't use, like num_workgroups,
126// entry_point, or other shader languages they didn't compile for
127impl<'a, L: Default> Default for CreateShaderModuleDescriptorPassthrough<'a, L> {
128 fn default() -> Self {
129 Self {
130 label: Default::default(),
131 num_workgroups: (0, 0, 0),
132 spirv: None,
133 dxil: None,
134 metallib: None,
135 msl: None,
136 hlsl: None,
137 glsl: None,
138 wgsl: None,
139 }
140 }
141}
142
143impl<'a, L> CreateShaderModuleDescriptorPassthrough<'a, L> {
144 /// Takes a closure and maps the label of the shader module descriptor into another.
145 pub fn map_label<K>(
146 &self,
147 fun: impl FnOnce(&L) -> K,
148 ) -> CreateShaderModuleDescriptorPassthrough<'a, K> {
149 CreateShaderModuleDescriptorPassthrough {
150 label: fun(&self.label),
151 num_workgroups: self.num_workgroups,
152 spirv: self.spirv.clone(),
153 metallib: self.metallib.clone(),
154 dxil: self.dxil.clone(),
155 msl: self.msl.clone(),
156 hlsl: self.hlsl.clone(),
157 glsl: self.glsl.clone(),
158 wgsl: self.wgsl.clone(),
159 }
160 }
161
162 #[cfg(feature = "trace")]
163 /// Returns the source data for tracing purpose.
164 pub fn trace_data(&self) -> &[u8] {
165 if let Some(spirv) = &self.spirv {
166 bytemuck::cast_slice(spirv)
167 } else if let Some(metallib) = &self.metallib {
168 metallib
169 } else if let Some(msl) = &self.msl {
170 msl.as_bytes()
171 } else if let Some(dxil) = &self.dxil {
172 dxil
173 } else if let Some(hlsl) = &self.hlsl {
174 hlsl.as_bytes()
175 } else if let Some(glsl) = &self.glsl {
176 glsl.as_bytes()
177 } else if let Some(wgsl) = &self.wgsl {
178 wgsl.as_bytes()
179 } else {
180 panic!("No binary data provided to `ShaderModuleDescriptorGeneric`")
181 }
182 }
183
184 #[cfg(feature = "trace")]
185 /// Returns the binary file extension for tracing purpose.
186 pub fn trace_binary_ext(&self) -> &'static str {
187 if self.spirv.is_some() {
188 "spv"
189 } else if self.metallib.is_some() {
190 "metallib"
191 } else if self.msl.is_some() {
192 "metal"
193 } else if self.dxil.is_some() {
194 "dxil"
195 } else if self.hlsl.is_some() {
196 "hlsl"
197 } else if self.glsl.is_some() {
198 "glsl"
199 } else if self.wgsl.is_some() {
200 "wgsl"
201 } else {
202 panic!("No binary data provided to `ShaderModuleDescriptorGeneric`")
203 }
204 }
205}