| 1 |
/*! |
| 2 |
Backend for [MSL][msl] (Metal Shading Language). |
| 3 |
|
| 4 |
This backend does not support the [`SHADER_INT64_ATOMIC_ALL_OPS`][all-atom] |
| 5 |
capability. |
| 6 |
|
| 7 |
## Binding model |
| 8 |
|
| 9 |
Metal's bindings are flat per resource. Since there isn't an obvious mapping |
| 10 |
from SPIR-V's descriptor sets, we require a separate mapping provided in the options. |
| 11 |
This mapping may have one or more resource end points for each descriptor set + index |
| 12 |
pair. |
| 13 |
|
| 14 |
## Entry points |
| 15 |
|
| 16 |
Even though MSL and our IR appear to be similar in that the entry points in both can |
| 17 |
accept arguments and return values, the restrictions are different. |
| 18 |
MSL allows the varyings to be either in separate arguments, or inside a single |
| 19 |
`[[stage_in]]` struct. We gather input varyings and form this artificial structure. |
| 20 |
We also add all the (non-Private) globals into the arguments. |
| 21 |
|
| 22 |
At the beginning of the entry point, we assign the local constants and re-compose |
| 23 |
the arguments as they are declared on IR side, so that the rest of the logic can |
| 24 |
pretend that MSL doesn't have all the restrictions it has. |
| 25 |
|
| 26 |
For the result type, if it's a structure, we re-compose it with a temporary value |
| 27 |
holding the result. |
| 28 |
|
| 29 |
[msl]: https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf |
| 30 |
[all-atom]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_ALL_OPS |
| 31 |
|
| 32 |
## Pointer-typed bounds-checked expressions and OOB locals |
| 33 |
|
| 34 |
MSL (unlike HLSL and GLSL) has native support for pointer-typed function |
| 35 |
arguments. When the [`BoundsCheckPolicy`] is `ReadZeroSkipWrite` and an |
| 36 |
out-of-bounds index expression is used for such an argument, our strategy is to |
| 37 |
pass a pointer to a dummy variable. These dummy variables are called "OOB |
| 38 |
locals". We emit at most one OOB local per function for each type, since all |
| 39 |
expressions producing a result of that type can share the same OOB local. (Note |
| 40 |
that the OOB local mechanism is not actually implementing "skip write", nor even |
| 41 |
"read zero" in some cases of read-after-write, but doing so would require |
| 42 |
additional effort and the difference is unlikely to matter.) |
| 43 |
|
| 44 |
[`BoundsCheckPolicy`]: crate::proc::BoundsCheckPolicy |
| 45 |
|
| 46 |
*/ |
| 47 |
|
| 48 |
use alloc::{ |
| 49 |
format, |
| 50 |
string::{String, ToString}, |
| 51 |
vec::Vec, |
| 52 |
}; |
| 53 |
use core::fmt::{Error as FmtError, Write}; |
| 54 |
|
| 55 |
use crate::{arena::Handle, ir, proc::index, valid::ModuleInfo}; |
| 56 |
|
| 57 |
mod keywords; |
| 58 |
pub mod sampler; |
| 59 |
mod writer; |
| 60 |
|
| 61 |
pub use writer::Writer; |
| 62 |
|
| 63 |
pub type Slot = u8; |
| 64 |
pub type InlineSamplerIndex = u8; |
| 65 |
|
| 66 |
#[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 67 |
#[cfg_attr(feature = "serialize", derive(serde::Serialize))] |
| 68 |
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] |
| 69 |
pub enum BindSamplerTarget { |
| 70 |
Resource(Slot), |
| 71 |
Inline(InlineSamplerIndex), |
| 72 |
} |
| 73 |
|
| 74 |
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] |
| 75 |
#[cfg_attr(feature = "serialize", derive(serde::Serialize))] |
| 76 |
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] |
| 77 |
#[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(default))] |
| 78 |
pub struct BindTarget { |
| 79 |
pub buffer: Option<Slot>, |
| 80 |
pub texture: Option<Slot>, |
| 81 |
pub sampler: Option<BindSamplerTarget>, |
| 82 |
pub mutable: bool, |
| 83 |
} |
| 84 |
|
| 85 |
#[cfg(any(feature = "serialize", feature = "deserialize"))] |
| 86 |
#[cfg_attr(feature = "serialize", derive(serde::Serialize))] |
| 87 |
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] |
| 88 |
struct BindingMapSerialization { |
| 89 |
resource_binding: crate::ResourceBinding, |
| 90 |
bind_target: BindTarget, |
| 91 |
} |
| 92 |
|
| 93 |
#[cfg(feature = "deserialize")] |
| 94 |
fn deserialize_binding_map<'de, D>(deserializer: D) -> Result<BindingMap, D::Error> |
| 95 |
where |
| 96 |
D: serde::Deserializer<'de>, |
| 97 |
{ |
| 98 |
use serde::Deserialize; |
| 99 |
|
| 100 |
let vec = Vec::<BindingMapSerialization>::deserialize(deserializer)?; |
| 101 |
let mut map = BindingMap::default(); |
| 102 |
for item in vec { |
| 103 |
map.insert(item.resource_binding, item.bind_target); |
| 104 |
} |
| 105 |
Ok(map) |
| 106 |
} |
| 107 |
|
| 108 |
// Using `BTreeMap` instead of `HashMap` so that we can hash itself. |
| 109 |
pub type BindingMap = alloc::collections::BTreeMap<crate::ResourceBinding, BindTarget>; |
| 110 |
|
| 111 |
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq)] |
| 112 |
#[cfg_attr(feature = "serialize", derive(serde::Serialize))] |
| 113 |
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] |
| 114 |
#[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(default))] |
| 115 |
pub struct EntryPointResources { |
| 116 |
#[cfg_attr( |
| 117 |
feature = "deserialize", |
| 118 |
serde(deserialize_with = "deserialize_binding_map") |
| 119 |
)] |
| 120 |
pub resources: BindingMap, |
| 121 |
|
| 122 |
pub push_constant_buffer: Option<Slot>, |
| 123 |
|
| 124 |
/// The slot of a buffer that contains an array of `u32`, |
| 125 |
/// one for the size of each bound buffer that contains a runtime array, |
| 126 |
/// in order of [`crate::GlobalVariable`] declarations. |
| 127 |
pub sizes_buffer: Option<Slot>, |
| 128 |
} |
| 129 |
|
| 130 |
pub type EntryPointResourceMap = alloc::collections::BTreeMap<String, EntryPointResources>; |
| 131 |
|
| 132 |
enum ResolvedBinding { |
| 133 |
BuiltIn(crate::BuiltIn), |
| 134 |
Attribute(u32), |
| 135 |
Color { |
| 136 |
location: u32, |
| 137 |
blend_src: Option<u32>, |
| 138 |
}, |
| 139 |
User { |
| 140 |
prefix: &'static str, |
| 141 |
index: u32, |
| 142 |
interpolation: Option<ResolvedInterpolation>, |
| 143 |
}, |
| 144 |
Resource(BindTarget), |
| 145 |
} |
| 146 |
|
| 147 |
#[derive(Copy, Clone)] |
| 148 |
enum ResolvedInterpolation { |
| 149 |
CenterPerspective, |
| 150 |
CenterNoPerspective, |
| 151 |
CentroidPerspective, |
| 152 |
CentroidNoPerspective, |
| 153 |
SamplePerspective, |
| 154 |
SampleNoPerspective, |
| 155 |
Flat, |
| 156 |
} |
| 157 |
|
| 158 |
// Note: some of these should be removed in favor of proper IR validation. |
| 159 |
|
| 160 |
#[derive(Debug, thiserror::Error)] |
| 161 |
pub enum Error { |
| 162 |
#[error(transparent)] |
| 163 |
Format(#[from] FmtError), |
| 164 |
#[error("bind target {0:?} is empty")] |
| 165 |
UnimplementedBindTarget(BindTarget), |
| 166 |
#[error("composing of {0:?} is not implemented yet")] |
| 167 |
UnsupportedCompose(Handle<crate::Type>), |
| 168 |
#[error("operation {0:?} is not implemented yet")] |
| 169 |
UnsupportedBinaryOp(crate::BinaryOperator), |
| 170 |
#[error("standard function '{0}' is not implemented yet")] |
| 171 |
UnsupportedCall(String), |
| 172 |
#[error("feature '{0}' is not implemented yet")] |
| 173 |
FeatureNotImplemented(String), |
| 174 |
#[error("internal naga error: module should not have validated: {0}")] |
| 175 |
GenericValidation(String), |
| 176 |
#[error("BuiltIn {0:?} is not supported")] |
| 177 |
UnsupportedBuiltIn(crate::BuiltIn), |
| 178 |
#[error("capability {0:?} is not supported")] |
| 179 |
CapabilityNotSupported(crate::valid::Capabilities), |
| 180 |
#[error("attribute '{0}' is not supported for target MSL version")] |
| 181 |
UnsupportedAttribute(String), |
| 182 |
#[error("function '{0}' is not supported for target MSL version")] |
| 183 |
UnsupportedFunction(String), |
| 184 |
#[error("can not use writeable storage buffers in fragment stage prior to MSL 1.2")] |
| 185 |
UnsupportedWriteableStorageBuffer, |
| 186 |
#[error("can not use writeable storage textures in {0:?} stage prior to MSL 1.2")] |
| 187 |
UnsupportedWriteableStorageTexture(ir::ShaderStage), |
| 188 |
#[error("can not use read-write storage textures prior to MSL 1.2")] |
| 189 |
UnsupportedRWStorageTexture, |
| 190 |
#[error("array of '{0}' is not supported for target MSL version")] |
| 191 |
UnsupportedArrayOf(String), |
| 192 |
#[error("array of type '{0:?}' is not supported")] |
| 193 |
UnsupportedArrayOfType(Handle<crate::Type>), |
| 194 |
#[error("ray tracing is not supported prior to MSL 2.3")] |
| 195 |
UnsupportedRayTracing, |
| 196 |
#[error("overrides should not be present at this stage")] |
| 197 |
Override, |
| 198 |
#[error("bitcasting to {0:?} is not supported")] |
| 199 |
UnsupportedBitCast(crate::TypeInner), |
| 200 |
#[error(transparent)] |
| 201 |
ResolveArraySizeError(#[from] crate::proc::ResolveArraySizeError), |
| 202 |
#[error("entry point with stage {0:?} and name '{1}' not found")] |
| 203 |
EntryPointNotFound(ir::ShaderStage, String), |
| 204 |
} |
| 205 |
|
| 206 |
#[derive(Clone, Debug, PartialEq, thiserror::Error)] |
| 207 |
#[cfg_attr(feature = "serialize", derive(serde::Serialize))] |
| 208 |
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] |
| 209 |
pub enum EntryPointError { |
| 210 |
#[error("global '{0}' doesn't have a binding")] |
| 211 |
MissingBinding(String), |
| 212 |
#[error("mapping of {0:?} is missing")] |
| 213 |
MissingBindTarget(crate::ResourceBinding), |
| 214 |
#[error("mapping for push constants is missing")] |
| 215 |
MissingPushConstants, |
| 216 |
#[error("mapping for sizes buffer is missing")] |
| 217 |
MissingSizesBuffer, |
| 218 |
} |
| 219 |
|
| 220 |
/// Points in the MSL code where we might emit a pipeline input or output. |
| 221 |
/// |
| 222 |
/// Note that, even though vertex shaders' outputs are always fragment |
| 223 |
/// shaders' inputs, we still need to distinguish `VertexOutput` and |
| 224 |
/// `FragmentInput`, since there are certain differences in the way |
| 225 |
/// [`ResolvedBinding`s] are represented on either side. |
| 226 |
/// |
| 227 |
/// [`ResolvedBinding`s]: ResolvedBinding |
| 228 |
#[derive(Clone, Copy, Debug)] |
| 229 |
enum LocationMode { |
| 230 |
/// Input to the vertex shader. |
| 231 |
VertexInput, |
| 232 |
|
| 233 |
/// Output from the vertex shader. |
| 234 |
VertexOutput, |
| 235 |
|
| 236 |
/// Input to the fragment shader. |
| 237 |
FragmentInput, |
| 238 |
|
| 239 |
/// Output from the fragment shader. |
| 240 |
FragmentOutput, |
| 241 |
|
| 242 |
/// Compute shader input or output. |
| 243 |
Uniform, |
| 244 |
} |
| 245 |
|
| 246 |
#[derive(Clone, Debug, Hash, PartialEq, Eq)] |
| 247 |
#[cfg_attr(feature = "serialize", derive(serde::Serialize))] |
| 248 |
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] |
| 249 |
#[cfg_attr(feature = "deserialize", serde(default))] |
| 250 |
pub struct Options { |
| 251 |
/// (Major, Minor) target version of the Metal Shading Language. |
| 252 |
pub lang_version: (u8, u8), |
| 253 |
/// Map of entry-point resources, indexed by entry point function name, to slots. |
| 254 |
pub per_entry_point_map: EntryPointResourceMap, |
| 255 |
/// Samplers to be inlined into the code. |
| 256 |
pub inline_samplers: Vec<sampler::InlineSampler>, |
| 257 |
/// Make it possible to link different stages via SPIRV-Cross. |
| 258 |
pub spirv_cross_compatibility: bool, |
| 259 |
/// Don't panic on missing bindings, instead generate invalid MSL. |
| 260 |
pub fake_missing_bindings: bool, |
| 261 |
/// Bounds checking policies. |
| 262 |
pub bounds_check_policies: index::BoundsCheckPolicies, |
| 263 |
/// Should workgroup variables be zero initialized (by polyfilling)? |
| 264 |
pub zero_initialize_workgroup_memory: bool, |
| 265 |
/// If set, loops will have code injected into them, forcing the compiler |
| 266 |
/// to think the number of iterations is bounded. |
| 267 |
pub force_loop_bounding: bool, |
| 268 |
} |
| 269 |
|
| 270 |
impl Default for Options { |
| 271 |
fn default() -> Self { |
| 272 |
Options { |
| 273 |
lang_version: (1, 0), |
| 274 |
per_entry_point_map: EntryPointResourceMap::default(), |
| 275 |
inline_samplers: Vec::new(), |
| 276 |
spirv_cross_compatibility: false, |
| 277 |
fake_missing_bindings: true, |
| 278 |
bounds_check_policies: index::BoundsCheckPolicies::default(), |
| 279 |
zero_initialize_workgroup_memory: true, |
| 280 |
force_loop_bounding: true, |
| 281 |
} |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
/// Corresponds to [WebGPU `GPUVertexFormat`]( |
| 286 |
/// https://gpuweb.github.io/gpuweb/#enumdef-gpuvertexformat). |
| 287 |
#[repr(u32)] |
| 288 |
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] |
| 289 |
#[cfg_attr(feature = "serialize", derive(serde::Serialize))] |
| 290 |
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] |
| 291 |
pub enum VertexFormat { |
| 292 |
/// One unsigned byte (u8). `u32` in shaders. |
| 293 |
Uint8 = 0, |
| 294 |
/// Two unsigned bytes (u8). `vec2<u32>` in shaders. |
| 295 |
Uint8x2 = 1, |
| 296 |
/// Four unsigned bytes (u8). `vec4<u32>` in shaders. |
| 297 |
Uint8x4 = 2, |
| 298 |
/// One signed byte (i8). `i32` in shaders. |
| 299 |
Sint8 = 3, |
| 300 |
/// Two signed bytes (i8). `vec2<i32>` in shaders. |
| 301 |
Sint8x2 = 4, |
| 302 |
/// Four signed bytes (i8). `vec4<i32>` in shaders. |
| 303 |
Sint8x4 = 5, |
| 304 |
/// One unsigned byte (u8). [0, 255] converted to float [0, 1] `f32` in shaders. |
| 305 |
Unorm8 = 6, |
| 306 |
/// Two unsigned bytes (u8). [0, 255] converted to float [0, 1] `vec2<f32>` in shaders. |
| 307 |
Unorm8x2 = 7, |
| 308 |
/// Four unsigned bytes (u8). [0, 255] converted to float [0, 1] `vec4<f32>` in shaders. |
| 309 |
Unorm8x4 = 8, |
| 310 |
/// One signed byte (i8). [-127, 127] converted to float [-1, 1] `f32` in shaders. |
| 311 |
Snorm8 = 9, |
| 312 |
/// Two signed bytes (i8). [-127, 127] converted to float [-1, 1] `vec2<f32>` in shaders. |
| 313 |
Snorm8x2 = 10, |
| 314 |
/// Four signed bytes (i8). [-127, 127] converted to float [-1, 1] `vec4<f32>` in shaders. |
| 315 |
Snorm8x4 = 11, |
| 316 |
/// One unsigned short (u16). `u32` in shaders. |
| 317 |
Uint16 = 12, |
| 318 |
/// Two unsigned shorts (u16). `vec2<u32>` in shaders. |
| 319 |
Uint16x2 = 13, |
| 320 |
/// Four unsigned shorts (u16). `vec4<u32>` in shaders. |
| 321 |
Uint16x4 = 14, |
| 322 |
/// One signed short (u16). `i32` in shaders. |
| 323 |
Sint16 = 15, |
| 324 |
/// Two signed shorts (i16). `vec2<i32>` in shaders. |
| 325 |
Sint16x2 = 16, |
| 326 |
/// Four signed shorts (i16). `vec4<i32>` in shaders. |
| 327 |
Sint16x4 = 17, |
| 328 |
/// One unsigned short (u16). [0, 65535] converted to float [0, 1] `f32` in shaders. |
| 329 |
Unorm16 = 18, |
| 330 |
/// Two unsigned shorts (u16). [0, 65535] converted to float [0, 1] `vec2<f32>` in shaders. |
| 331 |
Unorm16x2 = 19, |
| 332 |
/// Four unsigned shorts (u16). [0, 65535] converted to float [0, 1] `vec4<f32>` in shaders. |
| 333 |
Unorm16x4 = 20, |
| 334 |
/// One signed short (i16). [-32767, 32767] converted to float [-1, 1] `f32` in shaders. |
| 335 |
Snorm16 = 21, |
| 336 |
/// Two signed shorts (i16). [-32767, 32767] converted to float [-1, 1] `vec2<f32>` in shaders. |
| 337 |
Snorm16x2 = 22, |
| 338 |
/// Four signed shorts (i16). [-32767, 32767] converted to float [-1, 1] `vec4<f32>` in shaders. |
| 339 |
Snorm16x4 = 23, |
| 340 |
/// One half-precision float (no Rust equiv). `f32` in shaders. |
| 341 |
Float16 = 24, |
| 342 |
/// Two half-precision floats (no Rust equiv). `vec2<f32>` in shaders. |
| 343 |
Float16x2 = 25, |
| 344 |
/// Four half-precision floats (no Rust equiv). `vec4<f32>` in shaders. |
| 345 |
Float16x4 = 26, |
| 346 |
/// One single-precision float (f32). `f32` in shaders. |
| 347 |
Float32 = 27, |
| 348 |
/// Two single-precision floats (f32). `vec2<f32>` in shaders. |
| 349 |
Float32x2 = 28, |
| 350 |
/// Three single-precision floats (f32). `vec3<f32>` in shaders. |
| 351 |
Float32x3 = 29, |
| 352 |
/// Four single-precision floats (f32). `vec4<f32>` in shaders. |
| 353 |
Float32x4 = 30, |
| 354 |
/// One unsigned int (u32). `u32` in shaders. |
| 355 |
Uint32 = 31, |
| 356 |
/// Two unsigned ints (u32). `vec2<u32>` in shaders. |
| 357 |
Uint32x2 = 32, |
| 358 |
/// Three unsigned ints (u32). `vec3<u32>` in shaders. |
| 359 |
Uint32x3 = 33, |
| 360 |
/// Four unsigned ints (u32). `vec4<u32>` in shaders. |
| 361 |
Uint32x4 = 34, |
| 362 |
/// One signed int (i32). `i32` in shaders. |
| 363 |
Sint32 = 35, |
| 364 |
/// Two signed ints (i32). `vec2<i32>` in shaders. |
| 365 |
Sint32x2 = 36, |
| 366 |
/// Three signed ints (i32). `vec3<i32>` in shaders. |
| 367 |
Sint32x3 = 37, |
| 368 |
/// Four signed ints (i32). `vec4<i32>` in shaders. |
| 369 |
Sint32x4 = 38, |
| 370 |
/// Three unsigned 10-bit integers and one 2-bit integer, packed into a 32-bit integer (u32). [0, 1024] converted to float [0, 1] `vec4<f32>` in shaders. |
| 371 |
#[cfg_attr( |
| 372 |
any(feature = "serialize", feature = "deserialize"), |
| 373 |
serde(rename = "unorm10-10-10-2") |
| 374 |
)] |
| 375 |
Unorm10_10_10_2 = 43, |
| 376 |
/// Four unsigned 8-bit integers, packed into a 32-bit integer (u32). [0, 255] converted to float [0, 1] `vec4<f32>` in shaders. |
| 377 |
#[cfg_attr( |
| 378 |
any(feature = "serialize", feature = "deserialize"), |
| 379 |
serde(rename = "unorm8x4-bgra") |
| 380 |
)] |
| 381 |
Unorm8x4Bgra = 44, |
| 382 |
} |
| 383 |
|
| 384 |
/// A mapping of vertex buffers and their attributes to shader |
| 385 |
/// locations. |
| 386 |
#[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 387 |
#[cfg_attr(feature = "serialize", derive(serde::Serialize))] |
| 388 |
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] |
| 389 |
pub struct AttributeMapping { |
| 390 |
/// Shader location associated with this attribute |
| 391 |
pub shader_location: u32, |
| 392 |
/// Offset in bytes from start of vertex buffer structure |
| 393 |
pub offset: u32, |
| 394 |
/// Format code to help us unpack the attribute into the type |
| 395 |
/// used by the shader. Codes correspond to a 0-based index of |
| 396 |
/// <https://gpuweb.github.io/gpuweb/#enumdef-gpuvertexformat>. |
| 397 |
/// The conversion process is described by |
| 398 |
/// <https://gpuweb.github.io/gpuweb/#vertex-processing>. |
| 399 |
pub format: VertexFormat, |
| 400 |
} |
| 401 |
|
| 402 |
/// A description of a vertex buffer with all the information we |
| 403 |
/// need to address the attributes within it. |
| 404 |
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)] |
| 405 |
#[cfg_attr(feature = "serialize", derive(serde::Serialize))] |
| 406 |
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] |
| 407 |
pub struct VertexBufferMapping { |
| 408 |
/// Shader location associated with this buffer |
| 409 |
pub id: u32, |
| 410 |
/// Size of the structure in bytes |
| 411 |
pub stride: u32, |
| 412 |
/// True if the buffer is indexed by vertex, false if indexed |
| 413 |
/// by instance. |
| 414 |
pub indexed_by_vertex: bool, |
| 415 |
/// Vec of the attributes within the structure |
| 416 |
pub attributes: Vec<AttributeMapping>, |
| 417 |
} |
| 418 |
|
| 419 |
/// A subset of options that are meant to be changed per pipeline. |
| 420 |
#[derive(Debug, Default, Clone)] |
| 421 |
#[cfg_attr(feature = "serialize", derive(serde::Serialize))] |
| 422 |
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] |
| 423 |
#[cfg_attr(feature = "deserialize", serde(default))] |
| 424 |
pub struct PipelineOptions { |
| 425 |
/// The entry point to write. |
| 426 |
/// |
| 427 |
/// Entry points are identified by a shader stage specification, |
| 428 |
/// and a name. |
| 429 |
/// |
| 430 |
/// If `None`, all entry points will be written. If `Some` and the entry |
| 431 |
/// point is not found, an error will be thrown while writing. |
| 432 |
pub entry_point: Option<(ir::ShaderStage, String)>, |
| 433 |
|
| 434 |
/// Allow `BuiltIn::PointSize` and inject it if doesn't exist. |
| 435 |
/// |
| 436 |
/// Metal doesn't like this for non-point primitive topologies and requires it for |
| 437 |
/// point primitive topologies. |
| 438 |
/// |
| 439 |
/// Enable this for vertex shaders with point primitive topologies. |
| 440 |
pub allow_and_force_point_size: bool, |
| 441 |
|
| 442 |
/// If set, when generating the Metal vertex shader, transform it |
| 443 |
/// to receive the vertex buffers, lengths, and vertex id as args, |
| 444 |
/// and bounds-check the vertex id and use the index into the |
| 445 |
/// vertex buffers to access attributes, rather than using Metal's |
| 446 |
/// [[stage-in]] assembled attribute data. This is true by default, |
| 447 |
/// but remains configurable for use by tests via deserialization |
| 448 |
/// of this struct. There is no user-facing way to set this value. |
| 449 |
pub vertex_pulling_transform: bool, |
| 450 |
|
| 451 |
/// vertex_buffer_mappings are used during shader translation to |
| 452 |
/// support vertex pulling. |
| 453 |
pub vertex_buffer_mappings: Vec<VertexBufferMapping>, |
| 454 |
} |
| 455 |
|
| 456 |
impl Options { |
| 457 |
fn resolve_local_binding( |
| 458 |
&self, |
| 459 |
binding: &crate::Binding, |
| 460 |
mode: LocationMode, |
| 461 |
) -> Result<ResolvedBinding, Error> { |
| 462 |
match *binding { |
| 463 |
crate::Binding::BuiltIn(mut built_in) => { |
| 464 |
match built_in { |
| 465 |
crate::BuiltIn::Position { ref mut invariant } => { |
| 466 |
if *invariant && self.lang_version < (2, 1) { |
| 467 |
return Err(Error::UnsupportedAttribute("invariant".to_string())); |
| 468 |
} |
| 469 |
|
| 470 |
// The 'invariant' attribute may only appear on vertex |
| 471 |
// shader outputs, not fragment shader inputs. |
| 472 |
if !matches!(mode, LocationMode::VertexOutput) { |
| 473 |
*invariant = false; |
| 474 |
} |
| 475 |
} |
| 476 |
crate::BuiltIn::BaseInstance if self.lang_version < (1, 2) => { |
| 477 |
return Err(Error::UnsupportedAttribute("base_instance".to_string())); |
| 478 |
} |
| 479 |
crate::BuiltIn::InstanceIndex if self.lang_version < (1, 2) => { |
| 480 |
return Err(Error::UnsupportedAttribute("instance_id".to_string())); |
| 481 |
} |
| 482 |
// macOS: Since Metal 2.2 |
| 483 |
// iOS: Since Metal 2.3 (check depends on https://github.com/gfx-rs/naga/issues/2164) |
| 484 |
crate::BuiltIn::PrimitiveIndex if self.lang_version < (2, 2) => { |
| 485 |
return Err(Error::UnsupportedAttribute("primitive_id".to_string())); |
| 486 |
} |
| 487 |
_ => {} |
| 488 |
} |
| 489 |
|
| 490 |
Ok(ResolvedBinding::BuiltIn(built_in)) |
| 491 |
} |
| 492 |
crate::Binding::Location { |
| 493 |
location, |
| 494 |
interpolation, |
| 495 |
sampling, |
| 496 |
blend_src, |
| 497 |
} => match mode { |
| 498 |
LocationMode::VertexInput => Ok(ResolvedBinding::Attribute(location)), |
| 499 |
LocationMode::FragmentOutput => { |
| 500 |
if blend_src.is_some() && self.lang_version < (1, 2) { |
| 501 |
return Err(Error::UnsupportedAttribute("blend_src".to_string())); |
| 502 |
} |
| 503 |
Ok(ResolvedBinding::Color { |
| 504 |
location, |
| 505 |
blend_src, |
| 506 |
}) |
| 507 |
} |
| 508 |
LocationMode::VertexOutput | LocationMode::FragmentInput => { |
| 509 |
Ok(ResolvedBinding::User { |
| 510 |
prefix: if self.spirv_cross_compatibility { |
| 511 |
"locn" |
| 512 |
} else { |
| 513 |
"loc" |
| 514 |
}, |
| 515 |
index: location, |
| 516 |
interpolation: { |
| 517 |
// unwrap: The verifier ensures that vertex shader outputs and fragment |
| 518 |
// shader inputs always have fully specified interpolation, and that |
| 519 |
// sampling is `None` only for Flat interpolation. |
| 520 |
let interpolation = interpolation.unwrap(); |
| 521 |
let sampling = sampling.unwrap_or(crate::Sampling::Center); |
| 522 |
Some(ResolvedInterpolation::from_binding(interpolation, sampling)) |
| 523 |
}, |
| 524 |
}) |
| 525 |
} |
| 526 |
LocationMode::Uniform => Err(Error::GenericValidation(format!( |
| 527 |
"Unexpected Binding::Location({location}) for the Uniform mode" |
| 528 |
))), |
| 529 |
}, |
| 530 |
} |
| 531 |
} |
| 532 |
|
| 533 |
fn get_entry_point_resources(&self, ep: &crate::EntryPoint) -> Option<&EntryPointResources> { |
| 534 |
self.per_entry_point_map.get(&ep.name) |
| 535 |
} |
| 536 |
|
| 537 |
fn get_resource_binding_target( |
| 538 |
&self, |
| 539 |
ep: &crate::EntryPoint, |
| 540 |
res_binding: &crate::ResourceBinding, |
| 541 |
) -> Option<&BindTarget> { |
| 542 |
self.get_entry_point_resources(ep) |
| 543 |
.and_then(|res| res.resources.get(res_binding)) |
| 544 |
} |
| 545 |
|
| 546 |
fn resolve_resource_binding( |
| 547 |
&self, |
| 548 |
ep: &crate::EntryPoint, |
| 549 |
res_binding: &crate::ResourceBinding, |
| 550 |
) -> Result<ResolvedBinding, EntryPointError> { |
| 551 |
let target = self.get_resource_binding_target(ep, res_binding); |
| 552 |
match target { |
| 553 |
Some(target) => Ok(ResolvedBinding::Resource(target.clone())), |
| 554 |
None if self.fake_missing_bindings => Ok(ResolvedBinding::User { |
| 555 |
prefix: "fake", |
| 556 |
index: 0, |
| 557 |
interpolation: None, |
| 558 |
}), |
| 559 |
None => Err(EntryPointError::MissingBindTarget(*res_binding)), |
| 560 |
} |
| 561 |
} |
| 562 |
|
| 563 |
fn resolve_push_constants( |
| 564 |
&self, |
| 565 |
ep: &crate::EntryPoint, |
| 566 |
) -> Result<ResolvedBinding, EntryPointError> { |
| 567 |
let slot = self |
| 568 |
.get_entry_point_resources(ep) |
| 569 |
.and_then(|res| res.push_constant_buffer); |
| 570 |
match slot { |
| 571 |
Some(slot) => Ok(ResolvedBinding::Resource(BindTarget { |
| 572 |
buffer: Some(slot), |
| 573 |
..Default::default() |
| 574 |
})), |
| 575 |
None if self.fake_missing_bindings => Ok(ResolvedBinding::User { |
| 576 |
prefix: "fake", |
| 577 |
index: 0, |
| 578 |
interpolation: None, |
| 579 |
}), |
| 580 |
None => Err(EntryPointError::MissingPushConstants), |
| 581 |
} |
| 582 |
} |
| 583 |
|
| 584 |
fn resolve_sizes_buffer( |
| 585 |
&self, |
| 586 |
ep: &crate::EntryPoint, |
| 587 |
) -> Result<ResolvedBinding, EntryPointError> { |
| 588 |
let slot = self |
| 589 |
.get_entry_point_resources(ep) |
| 590 |
.and_then(|res| res.sizes_buffer); |
| 591 |
match slot { |
| 592 |
Some(slot) => Ok(ResolvedBinding::Resource(BindTarget { |
| 593 |
buffer: Some(slot), |
| 594 |
..Default::default() |
| 595 |
})), |
| 596 |
None if self.fake_missing_bindings => Ok(ResolvedBinding::User { |
| 597 |
prefix: "fake", |
| 598 |
index: 0, |
| 599 |
interpolation: None, |
| 600 |
}), |
| 601 |
None => Err(EntryPointError::MissingSizesBuffer), |
| 602 |
} |
| 603 |
} |
| 604 |
} |
| 605 |
|
| 606 |
impl ResolvedBinding { |
| 607 |
fn as_inline_sampler<'a>(&self, options: &'a Options) -> Option<&'a sampler::InlineSampler> { |
| 608 |
match *self { |
| 609 |
Self::Resource(BindTarget { |
| 610 |
sampler: Some(BindSamplerTarget::Inline(index)), |
| 611 |
.. |
| 612 |
}) => Some(&options.inline_samplers[index as usize]), |
| 613 |
_ => None, |
| 614 |
} |
| 615 |
} |
| 616 |
|
| 617 |
fn try_fmt<W: Write>(&self, out: &mut W) -> Result<(), Error> { |
| 618 |
write!(out, " [[")?; |
| 619 |
match *self { |
| 620 |
Self::BuiltIn(built_in) => { |
| 621 |
use crate::BuiltIn as Bi; |
| 622 |
let name = match built_in { |
| 623 |
Bi::Position { invariant: false } => "position", |
| 624 |
Bi::Position { invariant: true } => "position, invariant", |
| 625 |
// vertex |
| 626 |
Bi::BaseInstance => "base_instance", |
| 627 |
Bi::BaseVertex => "base_vertex", |
| 628 |
Bi::ClipDistance => "clip_distance", |
| 629 |
Bi::InstanceIndex => "instance_id", |
| 630 |
Bi::PointSize => "point_size", |
| 631 |
Bi::VertexIndex => "vertex_id", |
| 632 |
// fragment |
| 633 |
Bi::FragDepth => "depth(any)", |
| 634 |
Bi::PointCoord => "point_coord", |
| 635 |
Bi::FrontFacing => "front_facing", |
| 636 |
Bi::PrimitiveIndex => "primitive_id", |
| 637 |
Bi::SampleIndex => "sample_id", |
| 638 |
Bi::SampleMask => "sample_mask", |
| 639 |
// compute |
| 640 |
Bi::GlobalInvocationId => "thread_position_in_grid", |
| 641 |
Bi::LocalInvocationId => "thread_position_in_threadgroup", |
| 642 |
Bi::LocalInvocationIndex => "thread_index_in_threadgroup", |
| 643 |
Bi::WorkGroupId => "threadgroup_position_in_grid", |
| 644 |
Bi::WorkGroupSize => "dispatch_threads_per_threadgroup", |
| 645 |
Bi::NumWorkGroups => "threadgroups_per_grid", |
| 646 |
// subgroup |
| 647 |
Bi::NumSubgroups => "simdgroups_per_threadgroup", |
| 648 |
Bi::SubgroupId => "simdgroup_index_in_threadgroup", |
| 649 |
Bi::SubgroupSize => "threads_per_simdgroup", |
| 650 |
Bi::SubgroupInvocationId => "thread_index_in_simdgroup", |
| 651 |
Bi::CullDistance | Bi::ViewIndex | Bi::DrawID => { |
| 652 |
return Err(Error::UnsupportedBuiltIn(built_in)) |
| 653 |
} |
| 654 |
}; |
| 655 |
write!(out, "{name}")?; |
| 656 |
} |
| 657 |
Self::Attribute(index) => write!(out, "attribute({index})")?, |
| 658 |
Self::Color { |
| 659 |
location, |
| 660 |
blend_src, |
| 661 |
} => { |
| 662 |
if let Some(blend_src) = blend_src { |
| 663 |
write!(out, "color({location}) index({blend_src})")? |
| 664 |
} else { |
| 665 |
write!(out, "color({location})")? |
| 666 |
} |
| 667 |
} |
| 668 |
Self::User { |
| 669 |
prefix, |
| 670 |
index, |
| 671 |
interpolation, |
| 672 |
} => { |
| 673 |
write!(out, "user({prefix}{index})")?; |
| 674 |
if let Some(interpolation) = interpolation { |
| 675 |
write!(out, ", ")?; |
| 676 |
interpolation.try_fmt(out)?; |
| 677 |
} |
| 678 |
} |
| 679 |
Self::Resource(ref target) => { |
| 680 |
if let Some(id) = target.buffer { |
| 681 |
write!(out, "buffer({id})")?; |
| 682 |
} else if let Some(id) = target.texture { |
| 683 |
write!(out, "texture({id})")?; |
| 684 |
} else if let Some(BindSamplerTarget::Resource(id)) = target.sampler { |
| 685 |
write!(out, "sampler({id})")?; |
| 686 |
} else { |
| 687 |
return Err(Error::UnimplementedBindTarget(target.clone())); |
| 688 |
} |
| 689 |
} |
| 690 |
} |
| 691 |
write!(out, "]]")?; |
| 692 |
Ok(()) |
| 693 |
} |
| 694 |
} |
| 695 |
|
| 696 |
impl ResolvedInterpolation { |
| 697 |
const fn from_binding(interpolation: crate::Interpolation, sampling: crate::Sampling) -> Self { |
| 698 |
use crate::Interpolation as I; |
| 699 |
use crate::Sampling as S; |
| 700 |
|
| 701 |
match (interpolation, sampling) { |
| 702 |
(I::Perspective, S::Center) => Self::CenterPerspective, |
| 703 |
(I::Perspective, S::Centroid) => Self::CentroidPerspective, |
| 704 |
(I::Perspective, S::Sample) => Self::SamplePerspective, |
| 705 |
(I::Linear, S::Center) => Self::CenterNoPerspective, |
| 706 |
(I::Linear, S::Centroid) => Self::CentroidNoPerspective, |
| 707 |
(I::Linear, S::Sample) => Self::SampleNoPerspective, |
| 708 |
(I::Flat, _) => Self::Flat, |
| 709 |
_ => unreachable!(), |
| 710 |
} |
| 711 |
} |
| 712 |
|
| 713 |
fn try_fmt<W: Write>(self, out: &mut W) -> Result<(), Error> { |
| 714 |
let identifier = match self { |
| 715 |
Self::CenterPerspective => "center_perspective", |
| 716 |
Self::CenterNoPerspective => "center_no_perspective", |
| 717 |
Self::CentroidPerspective => "centroid_perspective", |
| 718 |
Self::CentroidNoPerspective => "centroid_no_perspective", |
| 719 |
Self::SamplePerspective => "sample_perspective", |
| 720 |
Self::SampleNoPerspective => "sample_no_perspective", |
| 721 |
Self::Flat => "flat", |
| 722 |
}; |
| 723 |
out.write_str(identifier)?; |
| 724 |
Ok(()) |
| 725 |
} |
| 726 |
} |
| 727 |
|
| 728 |
/// Information about a translated module that is required |
| 729 |
/// for the use of the result. |
| 730 |
pub struct TranslationInfo { |
| 731 |
/// Mapping of the entry point names. Each item in the array |
| 732 |
/// corresponds to an entry point index. |
| 733 |
/// |
| 734 |
///Note: Some entry points may fail translation because of missing bindings. |
| 735 |
pub entry_point_names: Vec<Result<String, EntryPointError>>, |
| 736 |
} |
| 737 |
|
| 738 |
pub fn write_string( |
| 739 |
module: &crate::Module, |
| 740 |
info: &ModuleInfo, |
| 741 |
options: &Options, |
| 742 |
pipeline_options: &PipelineOptions, |
| 743 |
) -> Result<(String, TranslationInfo), Error> { |
| 744 |
let mut w = Writer::new(String::new()); |
| 745 |
let info = w.write(module, info, options, pipeline_options)?; |
| 746 |
Ok((w.finish(), info)) |
| 747 |
} |
| 748 |
|
| 749 |
#[test] |
| 750 |
fn test_error_size() { |
| 751 |
assert_eq!(size_of::<Error>(), 40); |
| 752 |
} |