Debian Codegraph @

third_party/rust/naga/src/back/glsl/mod.rs

raw
1 /*!
2 Backend for [GLSL][glsl] (OpenGL Shading Language).
3
4 The main structure is [`Writer`], it maintains internal state that is used
5 to output a [`Module`](crate::Module) into glsl
6
7 # Supported versions
8 ### Core
9 - 330
10 - 400
11 - 410
12 - 420
13 - 430
14 - 450
15
16 ### ES
17 - 300
18 - 310
19
20 [glsl]: https://www.khronos.org/registry/OpenGL/index_gl.php
21 */
22
23 // GLSL is mostly a superset of C but it also removes some parts of it this is a list of relevant
24 // aspects for this backend.
25 //
26 // The most notable change is the introduction of the version preprocessor directive that must
27 // always be the first line of a glsl file and is written as
28 // `#version number profile`
29 // `number` is the version itself (i.e. 300) and `profile` is the
30 // shader profile we only support "core" and "es", the former is used in desktop applications and
31 // the later is used in embedded contexts, mobile devices and browsers. Each one as it's own
32 // versions (at the time of writing this the latest version for "core" is 460 and for "es" is 320)
33 //
34 // Other important preprocessor addition is the extension directive which is written as
35 // `#extension name: behaviour`
36 // Extensions provide increased features in a plugin fashion but they aren't required to be
37 // supported hence why they are called extensions, that's why `behaviour` is used it specifies
38 // whether the extension is strictly required or if it should only be enabled if needed. In our case
39 // when we use extensions we set behaviour to `require` always.
40 //
41 // The only thing that glsl removes that makes a difference are pointers.
42 //
43 // Additions that are relevant for the backend are the discard keyword, the introduction of
44 // vector, matrices, samplers, image types and functions that provide common shader operations
45
46 pub use features::Features;
47
48 use alloc::{
49 borrow::ToOwned,
50 format,
51 string::{String, ToString},
52 vec,
53 vec::Vec,
54 };
55 use core::{
56 cmp::Ordering,
57 fmt::{self, Error as FmtError, Write},
58 mem,
59 };
60
61 use hashbrown::hash_map;
62 use thiserror::Error;
63
64 use crate::{
65 back::{self, Baked},
66 common,
67 proc::{self, NameKey},
68 valid, Handle, ShaderStage, TypeInner,
69 };
70 use features::FeaturesManager;
71
72 /// Contains the features related code and the features querying method
73 mod features;
74 /// Contains a constant with a slice of all the reserved keywords RESERVED_KEYWORDS
75 mod keywords;
76
77 /// List of supported `core` GLSL versions.
78 pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[140, 150, 330, 400, 410, 420, 430, 440, 450, 460];
79 /// List of supported `es` GLSL versions.
80 pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320];
81
82 /// The suffix of the variable that will hold the calculated clamped level
83 /// of detail for bounds checking in `ImageLoad`
84 const CLAMPED_LOD_SUFFIX: &str = "_clamped_lod";
85
86 pub(crate) const MODF_FUNCTION: &str = "naga_modf";
87 pub(crate) const FREXP_FUNCTION: &str = "naga_frexp";
88
89 // Must match code in glsl_built_in
90 pub const FIRST_INSTANCE_BINDING: &str = "naga_vs_first_instance";
91
92 #[cfg(any(feature = "serialize", feature = "deserialize"))]
93 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
94 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
95 struct BindingMapSerialization {
96 resource_binding: crate::ResourceBinding,
97 bind_target: u8,
98 }
99
100 #[cfg(feature = "deserialize")]
101 fn deserialize_binding_map<'de, D>(deserializer: D) -> Result<BindingMap, D::Error>
102 where
103 D: serde::Deserializer<'de>,
104 {
105 use serde::Deserialize;
106
107 let vec = Vec::<BindingMapSerialization>::deserialize(deserializer)?;
108 let mut map = BindingMap::default();
109 for item in vec {
110 map.insert(item.resource_binding, item.bind_target);
111 }
112 Ok(map)
113 }
114
115 /// Mapping between resources and bindings.
116 pub type BindingMap = alloc::collections::BTreeMap<crate::ResourceBinding, u8>;
117
118 impl crate::AtomicFunction {
119 const fn to_glsl(self) -> &'static str {
120 match self {
121 Self::Add | Self::Subtract => "Add",
122 Self::And => "And",
123 Self::InclusiveOr => "Or",
124 Self::ExclusiveOr => "Xor",
125 Self::Min => "Min",
126 Self::Max => "Max",
127 Self::Exchange { compare: None } => "Exchange",
128 Self::Exchange { compare: Some(_) } => "", //TODO
129 }
130 }
131 }
132
133 impl crate::AddressSpace {
134 /// Whether a variable with this address space can be initialized
135 const fn initializable(&self) -> bool {
136 match *self {
137 crate::AddressSpace::Function | crate::AddressSpace::Private => true,
138 crate::AddressSpace::WorkGroup
139 | crate::AddressSpace::Uniform
140 | crate::AddressSpace::Storage { .. }
141 | crate::AddressSpace::Handle
142 | crate::AddressSpace::PushConstant => false,
143 }
144 }
145 }
146
147 /// A GLSL version.
148 #[derive(Debug, Copy, Clone, PartialEq)]
149 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
150 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
151 pub enum Version {
152 /// `core` GLSL.
153 Desktop(u16),
154 /// `es` GLSL.
155 Embedded { version: u16, is_webgl: bool },
156 }
157
158 impl Version {
159 /// Create a new gles version
160 pub const fn new_gles(version: u16) -> Self {
161 Self::Embedded {
162 version,
163 is_webgl: false,
164 }
165 }
166
167 /// Returns true if self is `Version::Embedded` (i.e. is a es version)
168 const fn is_es(&self) -> bool {
169 match *self {
170 Version::Desktop(_) => false,
171 Version::Embedded { .. } => true,
172 }
173 }
174
175 /// Returns true if targeting WebGL
176 const fn is_webgl(&self) -> bool {
177 match *self {
178 Version::Desktop(_) => false,
179 Version::Embedded { is_webgl, .. } => is_webgl,
180 }
181 }
182
183 /// Checks the list of currently supported versions and returns true if it contains the
184 /// specified version
185 ///
186 /// # Notes
187 /// As an invalid version number will never be added to the supported version list
188 /// so this also checks for version validity
189 fn is_supported(&self) -> bool {
190 match *self {
191 Version::Desktop(v) => SUPPORTED_CORE_VERSIONS.contains(&v),
192 Version::Embedded { version: v, .. } => SUPPORTED_ES_VERSIONS.contains(&v),
193 }
194 }
195
196 fn supports_io_locations(&self) -> bool {
197 *self >= Version::Desktop(330) || *self >= Version::new_gles(300)
198 }
199
200 /// Checks if the version supports all of the explicit layouts:
201 /// - `location=` qualifiers for bindings
202 /// - `binding=` qualifiers for resources
203 ///
204 /// Note: `location=` for vertex inputs and fragment outputs is supported
205 /// unconditionally for GLES 300.
206 fn supports_explicit_locations(&self) -> bool {
207 *self >= Version::Desktop(420) || *self >= Version::new_gles(310)
208 }
209
210 fn supports_early_depth_test(&self) -> bool {
211 *self >= Version::Desktop(130) || *self >= Version::new_gles(310)
212 }
213
214 fn supports_std140_layout(&self) -> bool {
215 *self >= Version::Desktop(140) || *self >= Version::new_gles(300)
216 }
217
218 fn supports_std430_layout(&self) -> bool {
219 *self >= Version::Desktop(430) || *self >= Version::new_gles(310)
220 }
221
222 fn supports_fma_function(&self) -> bool {
223 *self >= Version::Desktop(400) || *self >= Version::new_gles(320)
224 }
225
226 fn supports_integer_functions(&self) -> bool {
227 *self >= Version::Desktop(400) || *self >= Version::new_gles(310)
228 }
229
230 fn supports_frexp_function(&self) -> bool {
231 *self >= Version::Desktop(400) || *self >= Version::new_gles(310)
232 }
233
234 fn supports_derivative_control(&self) -> bool {
235 *self >= Version::Desktop(450)
236 }
237
238 // For supports_pack_unpack_4x8, supports_pack_unpack_snorm_2x16, supports_pack_unpack_unorm_2x16
239 // see:
240 // https://registry.khronos.org/OpenGL-Refpages/gl4/html/unpackUnorm.xhtml
241 // https://registry.khronos.org/OpenGL-Refpages/es3/html/unpackUnorm.xhtml
242 // https://registry.khronos.org/OpenGL-Refpages/gl4/html/packUnorm.xhtml
243 // https://registry.khronos.org/OpenGL-Refpages/es3/html/packUnorm.xhtml
244 fn supports_pack_unpack_4x8(&self) -> bool {
245 *self >= Version::Desktop(400) || *self >= Version::new_gles(310)
246 }
247 fn supports_pack_unpack_snorm_2x16(&self) -> bool {
248 *self >= Version::Desktop(420) || *self >= Version::new_gles(300)
249 }
250 fn supports_pack_unpack_unorm_2x16(&self) -> bool {
251 *self >= Version::Desktop(400) || *self >= Version::new_gles(300)
252 }
253
254 // https://registry.khronos.org/OpenGL-Refpages/gl4/html/unpackHalf2x16.xhtml
255 // https://registry.khronos.org/OpenGL-Refpages/gl4/html/packHalf2x16.xhtml
256 // https://registry.khronos.org/OpenGL-Refpages/es3/html/unpackHalf2x16.xhtml
257 // https://registry.khronos.org/OpenGL-Refpages/es3/html/packHalf2x16.xhtml
258 fn supports_pack_unpack_half_2x16(&self) -> bool {
259 *self >= Version::Desktop(420) || *self >= Version::new_gles(300)
260 }
261 }
262
263 impl PartialOrd for Version {
264 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
265 match (*self, *other) {
266 (Version::Desktop(x), Version::Desktop(y)) => Some(x.cmp(&y)),
267 (Version::Embedded { version: x, .. }, Version::Embedded { version: y, .. }) => {
268 Some(x.cmp(&y))
269 }
270 _ => None,
271 }
272 }
273 }
274
275 impl fmt::Display for Version {
276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277 match *self {
278 Version::Desktop(v) => write!(f, "{v} core"),
279 Version::Embedded { version: v, .. } => write!(f, "{v} es"),
280 }
281 }
282 }
283
284 bitflags::bitflags! {
285 /// Configuration flags for the [`Writer`].
286 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
287 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
288 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
289 pub struct WriterFlags: u32 {
290 /// Flip output Y and extend Z from (0, 1) to (-1, 1).
291 const ADJUST_COORDINATE_SPACE = 0x1;
292 /// Supports GL_EXT_texture_shadow_lod on the host, which provides
293 /// additional functions on shadows and arrays of shadows.
294 const TEXTURE_SHADOW_LOD = 0x2;
295 /// Supports ARB_shader_draw_parameters on the host, which provides
296 /// support for `gl_BaseInstanceARB`, `gl_BaseVertexARB`, `gl_DrawIDARB`, and `gl_DrawID`.
297 const DRAW_PARAMETERS = 0x4;
298 /// Include unused global variables, constants and functions. By default the output will exclude
299 /// global variables that are not used in the specified entrypoint (including indirect use),
300 /// all constant declarations, and functions that use excluded global variables.
301 const INCLUDE_UNUSED_ITEMS = 0x10;
302 /// Emit `PointSize` output builtin to vertex shaders, which is
303 /// required for drawing with `PointList` topology.
304 ///
305 /// https://registry.khronos.org/OpenGL/specs/es/3.2/GLSL_ES_Specification_3.20.html#built-in-language-variables
306 /// The variable gl_PointSize is intended for a shader to write the size of the point to be rasterized. It is measured in pixels.
307 /// If gl_PointSize is not written to, its value is undefined in subsequent pipe stages.
308 const FORCE_POINT_SIZE = 0x20;
309 }
310 }
311
312 /// Configuration used in the [`Writer`].
313 #[derive(Debug, Clone)]
314 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
315 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
316 #[cfg_attr(feature = "deserialize", serde(default))]
317 pub struct Options {
318 /// The GLSL version to be used.
319 pub version: Version,
320 /// Configuration flags for the [`Writer`].
321 pub writer_flags: WriterFlags,
322 /// Map of resources association to binding locations.
323 #[cfg_attr(
324 feature = "deserialize",
325 serde(deserialize_with = "deserialize_binding_map")
326 )]
327 pub binding_map: BindingMap,
328 /// Should workgroup variables be zero initialized (by polyfilling)?
329 pub zero_initialize_workgroup_memory: bool,
330 }
331
332 impl Default for Options {
333 fn default() -> Self {
334 Options {
335 version: Version::new_gles(310),
336 writer_flags: WriterFlags::ADJUST_COORDINATE_SPACE,
337 binding_map: BindingMap::default(),
338 zero_initialize_workgroup_memory: true,
339 }
340 }
341 }
342
343 /// A subset of options meant to be changed per pipeline.
344 #[derive(Debug, Clone)]
345 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
346 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
347 pub struct PipelineOptions {
348 /// The stage of the entry point.
349 pub shader_stage: ShaderStage,
350 /// The name of the entry point.
351 ///
352 /// If no entry point that matches is found while creating a [`Writer`], an
353 /// error will be thrown.
354 pub entry_point: String,
355 /// How many views to render to, if doing multiview rendering.
356 pub multiview: Option<core::num::NonZeroU32>,
357 }
358
359 #[derive(Debug)]
360 pub struct VaryingLocation {
361 /// The location of the global.
362 /// This corresponds to `layout(location = ..)` in GLSL.
363 pub location: u32,
364 /// The index which can be used for dual source blending.
365 /// This corresponds to `layout(index = ..)` in GLSL.
366 pub index: u32,
367 }
368
369 /// Reflection info for texture mappings and uniforms.
370 #[derive(Debug)]
371 pub struct ReflectionInfo {
372 /// Mapping between texture names and variables/samplers.
373 pub texture_mapping: crate::FastHashMap<String, TextureMapping>,
374 /// Mapping between uniform variables and names.
375 pub uniforms: crate::FastHashMap<Handle<crate::GlobalVariable>, String>,
376 /// Mapping between names and attribute locations.
377 pub varying: crate::FastHashMap<String, VaryingLocation>,
378 /// List of push constant items in the shader.
379 pub push_constant_items: Vec<PushConstantItem>,
380 }
381
382 /// Mapping between a texture and its sampler, if it exists.
383 ///
384 /// GLSL pre-Vulkan has no concept of separate textures and samplers. Instead, everything is a
385 /// `gsamplerN` where `g` is the scalar type and `N` is the dimension. But naga uses separate textures
386 /// and samplers in the IR, so the backend produces a [`FastHashMap`](crate::FastHashMap) with the texture name
387 /// as a key and a [`TextureMapping`] as a value. This way, the user knows where to bind.
388 ///
389 /// [`Storage`](crate::ImageClass::Storage) images produce `gimageN` and don't have an associated sampler,
390 /// so the [`sampler`](Self::sampler) field will be [`None`].
391 #[derive(Debug, Clone)]
392 pub struct TextureMapping {
393 /// Handle to the image global variable.
394 pub texture: Handle<crate::GlobalVariable>,
395 /// Handle to the associated sampler global variable, if it exists.
396 pub sampler: Option<Handle<crate::GlobalVariable>>,
397 }
398
399 /// All information to bind a single uniform value to the shader.
400 ///
401 /// Push constants are emulated using traditional uniforms in OpenGL.
402 ///
403 /// These are composed of a set of primitives (scalar, vector, matrix) that
404 /// are given names. Because they are not backed by the concept of a buffer,
405 /// we must do the work of calculating the offset of each primitive in the
406 /// push constant block.
407 #[derive(Debug, Clone)]
408 pub struct PushConstantItem {
409 /// GL uniform name for the item. This name is the same as if you were
410 /// to access it directly from a GLSL shader.
411 ///
412 /// The with the following example, the following names will be generated,
413 /// one name per GLSL uniform.
414 ///
415 /// ```glsl
416 /// struct InnerStruct {
417 /// value: f32,
418 /// }
419 ///
420 /// struct PushConstant {
421 /// InnerStruct inner;
422 /// vec4 array[2];
423 /// }
424 ///
425 /// uniform PushConstants _push_constant_binding_cs;
426 /// ```
427 ///
428 /// ```text
429 /// - _push_constant_binding_cs.inner.value
430 /// - _push_constant_binding_cs.array[0]
431 /// - _push_constant_binding_cs.array[1]
432 /// ```
433 ///
434 pub access_path: String,
435 /// Type of the uniform. This will only ever be a scalar, vector, or matrix.
436 pub ty: Handle<crate::Type>,
437 /// The offset in the push constant memory block this uniform maps to.
438 ///
439 /// The size of the uniform can be derived from the type.
440 pub offset: u32,
441 }
442
443 /// Helper structure that generates a number
444 #[derive(Default)]
445 struct IdGenerator(u32);
446
447 impl IdGenerator {
448 /// Generates a number that's guaranteed to be unique for this `IdGenerator`
449 fn generate(&mut self) -> u32 {
450 // It's just an increasing number but it does the job
451 let ret = self.0;
452 self.0 += 1;
453 ret
454 }
455 }
456
457 /// Assorted options needed for generating varyings.
458 #[derive(Clone, Copy)]
459 struct VaryingOptions {
460 output: bool,
461 targeting_webgl: bool,
462 draw_parameters: bool,
463 }
464
465 impl VaryingOptions {
466 const fn from_writer_options(options: &Options, output: bool) -> Self {
467 Self {
468 output,
469 targeting_webgl: options.version.is_webgl(),
470 draw_parameters: options.writer_flags.contains(WriterFlags::DRAW_PARAMETERS),
471 }
472 }
473 }
474
475 /// Helper wrapper used to get a name for a varying
476 ///
477 /// Varying have different naming schemes depending on their binding:
478 /// - Varyings with builtin bindings get the from [`glsl_built_in`].
479 /// - Varyings with location bindings are named `_S_location_X` where `S` is a
480 /// prefix identifying which pipeline stage the varying connects, and `X` is
481 /// the location.
482 struct VaryingName<'a> {
483 binding: &'a crate::Binding,
484 stage: ShaderStage,
485 options: VaryingOptions,
486 }
487 impl fmt::Display for VaryingName<'_> {
488 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
489 match *self.binding {
490 crate::Binding::Location {
491 blend_src: Some(1), ..
492 } => {
493 write!(f, "_fs2p_location1",)
494 }
495 crate::Binding::Location { location, .. } => {
496 let prefix = match (self.stage, self.options.output) {
497 (ShaderStage::Compute, _) => unreachable!(),
498 // pipeline to vertex
499 (ShaderStage::Vertex, false) => "p2vs",
500 // vertex to fragment
501 (ShaderStage::Vertex, true) | (ShaderStage::Fragment, false) => "vs2fs",
502 // fragment to pipeline
503 (ShaderStage::Fragment, true) => "fs2p",
504 (ShaderStage::Task | ShaderStage::Mesh, _) => unreachable!(),
505 };
506 write!(f, "_{prefix}_location{location}",)
507 }
508 crate::Binding::BuiltIn(built_in) => {
509 write!(f, "{}", glsl_built_in(built_in, self.options))
510 }
511 }
512 }
513 }
514
515 impl ShaderStage {
516 const fn to_str(self) -> &'static str {
517 match self {
518 ShaderStage::Compute => "cs",
519 ShaderStage::Fragment => "fs",
520 ShaderStage::Vertex => "vs",
521 ShaderStage::Task | ShaderStage::Mesh => unreachable!(),
522 }
523 }
524 }
525
526 /// Shorthand result used internally by the backend
527 type BackendResult<T = ()> = Result<T, Error>;
528
529 /// A GLSL compilation error.
530 #[derive(Debug, Error)]
531 pub enum Error {
532 /// A error occurred while writing to the output.
533 #[error("Format error")]
534 FmtError(#[from] FmtError),
535 /// The specified [`Version`] doesn't have all required [`Features`].
536 ///
537 /// Contains the missing [`Features`].
538 #[error("The selected version doesn't support {0:?}")]
539 MissingFeatures(Features),
540 /// [`AddressSpace::PushConstant`](crate::AddressSpace::PushConstant) was used more than
541 /// once in the entry point, which isn't supported.
542 #[error("Multiple push constants aren't supported")]
543 MultiplePushConstants,
544 /// The specified [`Version`] isn't supported.
545 #[error("The specified version isn't supported")]
546 VersionNotSupported,
547 /// The entry point couldn't be found.
548 #[error("The requested entry point couldn't be found")]
549 EntryPointNotFound,
550 /// A call was made to an unsupported external.
551 #[error("A call was made to an unsupported external: {0}")]
552 UnsupportedExternal(String),
553 /// A scalar with an unsupported width was requested.
554 #[error("A scalar with an unsupported width was requested: {0:?}")]
555 UnsupportedScalar(crate::Scalar),
556 /// A image was used with multiple samplers, which isn't supported.
557 #[error("A image was used with multiple samplers")]
558 ImageMultipleSamplers,
559 #[error("{0}")]
560 Custom(String),
561 #[error("overrides should not be present at this stage")]
562 Override,
563 /// [`crate::Sampling::First`] is unsupported.
564 #[error("`{:?}` sampling is unsupported", crate::Sampling::First)]
565 FirstSamplingNotSupported,
566 #[error(transparent)]
567 ResolveArraySizeError(#[from] proc::ResolveArraySizeError),
568 }
569
570 /// Binary operation with a different logic on the GLSL side.
571 enum BinaryOperation {
572 /// Vector comparison should use the function like `greaterThan()`, etc.
573 VectorCompare,
574 /// Vector component wise operation; used to polyfill unsupported ops like `|` and `&` for `bvecN`'s
575 VectorComponentWise,
576 /// GLSL `%` is SPIR-V `OpUMod/OpSMod` and `mod()` is `OpFMod`, but [`BinaryOperator::Modulo`](crate::BinaryOperator::Modulo) is `OpFRem`.
577 Modulo,
578 /// Any plain operation. No additional logic required.
579 Other,
580 }
581
582 /// Writer responsible for all code generation.
583 pub struct Writer<'a, W> {
584 // Inputs
585 /// The module being written.
586 module: &'a crate::Module,
587 /// The module analysis.
588 info: &'a valid::ModuleInfo,
589 /// The output writer.
590 out: W,
591 /// User defined configuration to be used.
592 options: &'a Options,
593 /// The bound checking policies to be used
594 policies: proc::BoundsCheckPolicies,
595
596 // Internal State
597 /// Features manager used to store all the needed features and write them.
598 features: FeaturesManager,
599 namer: proc::Namer,
600 /// A map with all the names needed for writing the module
601 /// (generated by a [`Namer`](crate::proc::Namer)).
602 names: crate::FastHashMap<NameKey, String>,
603 /// A map with the names of global variables needed for reflections.
604 reflection_names_globals: crate::FastHashMap<Handle<crate::GlobalVariable>, String>,
605 /// The selected entry point.
606 entry_point: &'a crate::EntryPoint,
607 /// The index of the selected entry point.
608 entry_point_idx: proc::EntryPointIndex,
609 /// A generator for unique block numbers.
610 block_id: IdGenerator,
611 /// Set of expressions that have associated temporary variables.
612 named_expressions: crate::NamedExpressions,
613 /// Set of expressions that need to be baked to avoid unnecessary repetition in output
614 need_bake_expressions: back::NeedBakeExpressions,
615 /// Information about nesting of loops and switches.
616 ///
617 /// Used for forwarding continue statements in switches that have been
618 /// transformed to `do {} while(false);` loops.
619 continue_ctx: back::continue_forward::ContinueCtx,
620 /// How many views to render to, if doing multiview rendering.
621 multiview: Option<core::num::NonZeroU32>,
622 /// Mapping of varying variables to their location. Needed for reflections.
623 varying: crate::FastHashMap<String, VaryingLocation>,
624 }
625
626 impl<'a, W: Write> Writer<'a, W> {
627 /// Creates a new [`Writer`] instance.
628 ///
629 /// # Errors
630 /// - If the version specified is invalid or supported.
631 /// - If the entry point couldn't be found in the module.
632 /// - If the version specified doesn't support some used features.
633 pub fn new(
634 out: W,
635 module: &'a crate::Module,
636 info: &'a valid::ModuleInfo,
637 options: &'a Options,
638 pipeline_options: &'a PipelineOptions,
639 policies: proc::BoundsCheckPolicies,
640 ) -> Result<Self, Error> {
641 // Check if the requested version is supported
642 if !options.version.is_supported() {
643 log::error!("Version {}", options.version);
644 return Err(Error::VersionNotSupported);
645 }
646
647 // Try to find the entry point and corresponding index
648 let ep_idx = module
649 .entry_points
650 .iter()
651 .position(|ep| {
652 pipeline_options.shader_stage == ep.stage && pipeline_options.entry_point == ep.name
653 })
654 .ok_or(Error::EntryPointNotFound)?;
655
656 // Generate a map with names required to write the module
657 let mut names = crate::FastHashMap::default();
658 let mut namer = proc::Namer::default();
659 namer.reset(
660 module,
661 &keywords::RESERVED_KEYWORD_SET,
662 &[],
663 &[
664 "gl_", // all GL built-in variables
665 "_group", // all normal bindings
666 "_push_constant_binding_", // all push constant bindings
667 ],
668 &mut names,
669 );
670
671 // Build the instance
672 let mut this = Self {
673 module,
674 info,
675 out,
676 options,
677 policies,
678
679 namer,
680 features: FeaturesManager::new(),
681 names,
682 reflection_names_globals: crate::FastHashMap::default(),
683 entry_point: &module.entry_points[ep_idx],
684 entry_point_idx: ep_idx as u16,
685 multiview: pipeline_options.multiview,
686 block_id: IdGenerator::default(),
687 named_expressions: Default::default(),
688 need_bake_expressions: Default::default(),
689 continue_ctx: back::continue_forward::ContinueCtx::default(),
690 varying: Default::default(),
691 };
692
693 // Find all features required to print this module
694 this.collect_required_features()?;
695
696 Ok(this)
697 }
698
699 /// Writes the [`Module`](crate::Module) as glsl to the output
700 ///
701 /// # Notes
702 /// If an error occurs while writing, the output might have been written partially
703 ///
704 /// # Panics
705 /// Might panic if the module is invalid
706 pub fn write(&mut self) -> Result<ReflectionInfo, Error> {
707 // We use `writeln!(self.out)` throughout the write to add newlines
708 // to make the output more readable
709
710 let es = self.options.version.is_es();
711
712 // Write the version (It must be the first thing or it isn't a valid glsl output)
713 writeln!(self.out, "#version {}", self.options.version)?;
714 // Write all the needed extensions
715 //
716 // This used to be the last thing being written as it allowed to search for features while
717 // writing the module saving some loops but some older versions (420 or less) required the
718 // extensions to appear before being used, even though extensions are part of the
719 // preprocessor not the processor ¯\_(ツ)_/¯
720 self.features.write(self.options, &mut self.out)?;
721
722 // glsl es requires a precision to be specified for floats and ints
723 // TODO: Should this be user configurable?
724 if es {
725 writeln!(self.out)?;
726 writeln!(self.out, "precision highp float;")?;
727 writeln!(self.out, "precision highp int;")?;
728 writeln!(self.out)?;
729 }
730
731 if self.entry_point.stage == ShaderStage::Compute {
732 let workgroup_size = self.entry_point.workgroup_size;
733 writeln!(
734 self.out,
735 "layout(local_size_x = {}, local_size_y = {}, local_size_z = {}) in;",
736 workgroup_size[0], workgroup_size[1], workgroup_size[2]
737 )?;
738 writeln!(self.out)?;
739 }
740
741 if self.entry_point.stage == ShaderStage::Vertex
742 && !self
743 .options
744 .writer_flags
745 .contains(WriterFlags::DRAW_PARAMETERS)
746 && self.features.contains(Features::INSTANCE_INDEX)
747 {
748 writeln!(self.out, "uniform uint {FIRST_INSTANCE_BINDING};")?;
749 writeln!(self.out)?;
750 }
751
752 // Enable early depth tests if needed
753 if let Some(depth_test) = self.entry_point.early_depth_test {
754 // If early depth test is supported for this version of GLSL
755 if self.options.version.supports_early_depth_test() {
756 writeln!(self.out, "layout(early_fragment_tests) in;")?;
757
758 if let Some(conservative) = depth_test.conservative {
759 use crate::ConservativeDepth as Cd;
760
761 let depth = match conservative {
762 Cd::GreaterEqual => "greater",
763 Cd::LessEqual => "less",
764 Cd::Unchanged => "unchanged",
765 };
766 writeln!(self.out, "layout (depth_{depth}) out float gl_FragDepth;")?;
767 }
768 writeln!(self.out)?;
769 } else {
770 log::warn!(
771 "Early depth testing is not supported for this version of GLSL: {}",
772 self.options.version
773 );
774 }
775 }
776
777 if self.entry_point.stage == ShaderStage::Vertex && self.options.version.is_webgl() {
778 if let Some(multiview) = self.multiview.as_ref() {
779 writeln!(self.out, "layout(num_views = {multiview}) in;")?;
780 writeln!(self.out)?;
781 }
782 }
783
784 // Write struct types.
785 //
786 // This are always ordered because the IR is structured in a way that
787 // you can't make a struct without adding all of its members first.
788 for (handle, ty) in self.module.types.iter() {
789 if let TypeInner::Struct { ref members, .. } = ty.inner {
790 // Structures ending with runtime-sized arrays can only be
791 // rendered as shader storage blocks in GLSL, not stand-alone
792 // struct types.
793 if !self.module.types[members.last().unwrap().ty]
794 .inner
795 .is_dynamically_sized(&self.module.types)
796 {
797 let name = &self.names[&NameKey::Type(handle)];
798 write!(self.out, "struct {name} ")?;
799 self.write_struct_body(handle, members)?;
800 writeln!(self.out, ";")?;
801 }
802 }
803 }
804
805 // Write functions to create special types.
806 for (type_key, struct_ty) in self.module.special_types.predeclared_types.iter() {
807 match type_key {
808 &crate::PredeclaredType::ModfResult { size, scalar }
809 | &crate::PredeclaredType::FrexpResult { size, scalar } => {
810 let arg_type_name_owner;
811 let arg_type_name = if let Some(size) = size {
812 arg_type_name_owner = format!(
813 "{}vec{}",
814 if scalar.width == 8 { "d" } else { "" },
815 size as u8
816 );
817 &arg_type_name_owner
818 } else if scalar.width == 8 {
819 "double"
820 } else {
821 "float"
822 };
823
824 let other_type_name_owner;
825 let (defined_func_name, called_func_name, other_type_name) =
826 if matches!(type_key, &crate::PredeclaredType::ModfResult { .. }) {
827 (MODF_FUNCTION, "modf", arg_type_name)
828 } else {
829 let other_type_name = if let Some(size) = size {
830 other_type_name_owner = format!("ivec{}", size as u8);
831 &other_type_name_owner
832 } else {
833 "int"
834 };
835 (FREXP_FUNCTION, "frexp", other_type_name)
836 };
837
838 let struct_name = &self.names[&NameKey::Type(*struct_ty)];
839
840 writeln!(self.out)?;
841 if !self.options.version.supports_frexp_function()
842 && matches!(type_key, &crate::PredeclaredType::FrexpResult { .. })
843 {
844 writeln!(
845 self.out,
846 "{struct_name} {defined_func_name}({arg_type_name} arg) {{
847 {other_type_name} other = arg == {arg_type_name}(0) ? {other_type_name}(0) : {other_type_name}({arg_type_name}(1) + log2(arg));
848 {arg_type_name} fract = arg * exp2({arg_type_name}(-other));
849 return {struct_name}(fract, other);
850 }}",
851 )?;
852 } else {
853 writeln!(
854 self.out,
855 "{struct_name} {defined_func_name}({arg_type_name} arg) {{
856 {other_type_name} other;
857 {arg_type_name} fract = {called_func_name}(arg, other);
858 return {struct_name}(fract, other);
859 }}",
860 )?;
861 }
862 }
863 &crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {}
864 }
865 }
866
867 // Write all named constants
868 let mut constants = self
869 .module
870 .constants
871 .iter()
872 .filter(|&(_, c)| c.name.is_some())
873 .peekable();
874 while let Some((handle, _)) = constants.next() {
875 self.write_global_constant(handle)?;
876 // Add extra newline for readability on last iteration
877 if constants.peek().is_none() {
878 writeln!(self.out)?;
879 }
880 }
881
882 let ep_info = self.info.get_entry_point(self.entry_point_idx as usize);
883
884 // Write the globals
885 //
886 // Unless explicitly disabled with WriterFlags::INCLUDE_UNUSED_ITEMS,
887 // we filter all globals that aren't used by the selected entry point as they might be
888 // interfere with each other (i.e. two globals with the same location but different with
889 // different classes)
890 let include_unused = self
891 .options
892 .writer_flags
893 .contains(WriterFlags::INCLUDE_UNUSED_ITEMS);
894 for (handle, global) in self.module.global_variables.iter() {
895 let is_unused = ep_info[handle].is_empty();
896 if !include_unused && is_unused {
897 continue;
898 }
899
900 match self.module.types[global.ty].inner {
901 // We treat images separately because they might require
902 // writing the storage format
903 TypeInner::Image {
904 mut dim,
905 arrayed,
906 class,
907 } => {
908 // Gather the storage format if needed
909 let storage_format_access = match self.module.types[global.ty].inner {
910 TypeInner::Image {
911 class: crate::ImageClass::Storage { format, access },
912 ..
913 } => Some((format, access)),
914 _ => None,
915 };
916
917 if dim == crate::ImageDimension::D1 && es {
918 dim = crate::ImageDimension::D2
919 }
920
921 // Gether the location if needed
922 let layout_binding = if self.options.version.supports_explicit_locations() {
923 let br = global.binding.as_ref().unwrap();
924 self.options.binding_map.get(br).cloned()
925 } else {
926 None
927 };
928
929 // Write all the layout qualifiers
930 if layout_binding.is_some() || storage_format_access.is_some() {
931 write!(self.out, "layout(")?;
932 if let Some(binding) = layout_binding {
933 write!(self.out, "binding = {binding}")?;
934 }
935 if let Some((format, _)) = storage_format_access {
936 let format_str = glsl_storage_format(format)?;
937 let separator = match layout_binding {
938 Some(_) => ",",
939 None => "",
940 };
941 write!(self.out, "{separator}{format_str}")?;
942 }
943 write!(self.out, ") ")?;
944 }
945
946 if let Some((_, access)) = storage_format_access {
947 self.write_storage_access(access)?;
948 }
949
950 // All images in glsl are `uniform`
951 // The trailing space is important
952 write!(self.out, "uniform ")?;
953
954 // write the type
955 //
956 // This is way we need the leading space because `write_image_type` doesn't add
957 // any spaces at the beginning or end
958 self.write_image_type(dim, arrayed, class)?;
959
960 // Finally write the name and end the global with a `;`
961 // The leading space is important
962 let global_name = self.get_global_name(handle, global);
963 writeln!(self.out, " {global_name};")?;
964 writeln!(self.out)?;
965
966 self.reflection_names_globals.insert(handle, global_name);
967 }
968 // glsl has no concept of samplers so we just ignore it
969 TypeInner::Sampler { .. } => continue,
970 // All other globals are written by `write_global`
971 _ => {
972 self.write_global(handle, global)?;
973 // Add a newline (only for readability)
974 writeln!(self.out)?;
975 }
976 }
977 }
978
979 for arg in self.entry_point.function.arguments.iter() {
980 self.write_varying(arg.binding.as_ref(), arg.ty, false)?;
981 }
982 if let Some(ref result) = self.entry_point.function.result {
983 self.write_varying(result.binding.as_ref(), result.ty, true)?;
984 }
985 writeln!(self.out)?;
986
987 // Write all regular functions
988 for (handle, function) in self.module.functions.iter() {
989 // Check that the function doesn't use globals that aren't supported
990 // by the current entry point
991 if !include_unused && !ep_info.dominates_global_use(&self.info[handle]) {
992 continue;
993 }
994
995 let fun_info = &self.info[handle];
996
997 // Skip functions that that are not compatible with this entry point's stage.
998 //
999 // When validation is enabled, it rejects modules whose entry points try to call
1000 // incompatible functions, so if we got this far, then any functions incompatible
1001 // with our selected entry point must not be used.
1002 //
1003 // When validation is disabled, `fun_info.available_stages` is always just
1004 // `ShaderStages::all()`, so this will write all functions in the module, and
1005 // the downstream GLSL compiler will catch any problems.
1006 if !fun_info.available_stages.contains(ep_info.available_stages) {
1007 continue;
1008 }
1009
1010 // Write the function
1011 self.write_function(back::FunctionType::Function(handle), function, fun_info)?;
1012
1013 writeln!(self.out)?;
1014 }
1015
1016 self.write_function(
1017 back::FunctionType::EntryPoint(self.entry_point_idx),
1018 &self.entry_point.function,
1019 ep_info,
1020 )?;
1021
1022 // Add newline at the end of file
1023 writeln!(self.out)?;
1024
1025 // Collect all reflection info and return it to the user
1026 self.collect_reflection_info()
1027 }
1028
1029 fn write_array_size(
1030 &mut self,
1031 base: Handle<crate::Type>,
1032 size: crate::ArraySize,
1033 ) -> BackendResult {
1034 write!(self.out, "[")?;
1035
1036 // Write the array size
1037 // Writes nothing if `IndexableLength::Dynamic`
1038 match size.resolve(self.module.to_ctx())? {
1039 proc::IndexableLength::Known(size) => {
1040 write!(self.out, "{size}")?;
1041 }
1042 proc::IndexableLength::Dynamic => (),
1043 }
1044
1045 write!(self.out, "]")?;
1046
1047 if let TypeInner::Array {
1048 base: next_base,
1049 size: next_size,
1050 ..
1051 } = self.module.types[base].inner
1052 {
1053 self.write_array_size(next_base, next_size)?;
1054 }
1055
1056 Ok(())
1057 }
1058
1059 /// Helper method used to write value types
1060 ///
1061 /// # Notes
1062 /// Adds no trailing or leading whitespace
1063 fn write_value_type(&mut self, inner: &TypeInner) -> BackendResult {
1064 match *inner {
1065 // Scalars are simple we just get the full name from `glsl_scalar`
1066 TypeInner::Scalar(scalar)
1067 | TypeInner::Atomic(scalar)
1068 | TypeInner::ValuePointer {
1069 size: None,
1070 scalar,
1071 space: _,
1072 } => write!(self.out, "{}", glsl_scalar(scalar)?.full)?,
1073 // Vectors are just `gvecN` where `g` is the scalar prefix and `N` is the vector size
1074 TypeInner::Vector { size, scalar }
1075 | TypeInner::ValuePointer {
1076 size: Some(size),
1077 scalar,
1078 space: _,
1079 } => write!(self.out, "{}vec{}", glsl_scalar(scalar)?.prefix, size as u8)?,
1080 // Matrices are written with `gmatMxN` where `g` is the scalar prefix (only floats and
1081 // doubles are allowed), `M` is the columns count and `N` is the rows count
1082 //
1083 // glsl supports a matrix shorthand `gmatN` where `N` = `M` but it doesn't justify the
1084 // extra branch to write matrices this way
1085 TypeInner::Matrix {
1086 columns,
1087 rows,
1088 scalar,
1089 } => write!(
1090 self.out,
1091 "{}mat{}x{}",
1092 glsl_scalar(scalar)?.prefix,
1093 columns as u8,
1094 rows as u8
1095 )?,
1096 // GLSL arrays are written as `type name[size]`
1097 // Here we only write the size of the array i.e. `[size]`
1098 // Base `type` and `name` should be written outside
1099 TypeInner::Array { base, size, .. } => self.write_array_size(base, size)?,
1100 // Write all variants instead of `_` so that if new variants are added a
1101 // no exhaustiveness error is thrown
1102 TypeInner::Pointer { .. }
1103 | TypeInner::Struct { .. }
1104 | TypeInner::Image { .. }
1105 | TypeInner::Sampler { .. }
1106 | TypeInner::AccelerationStructure { .. }
1107 | TypeInner::RayQuery { .. }
1108 | TypeInner::BindingArray { .. } => {
1109 return Err(Error::Custom(format!("Unable to write type {inner:?}")))
1110 }
1111 }
1112
1113 Ok(())
1114 }
1115
1116 /// Helper method used to write non image/sampler types
1117 ///
1118 /// # Notes
1119 /// Adds no trailing or leading whitespace
1120 fn write_type(&mut self, ty: Handle<crate::Type>) -> BackendResult {
1121 match self.module.types[ty].inner {
1122 // glsl has no pointer types so just write types as normal and loads are skipped
1123 TypeInner::Pointer { base, .. } => self.write_type(base),
1124 // glsl structs are written as just the struct name
1125 TypeInner::Struct { .. } => {
1126 // Get the struct name
1127 let name = &self.names[&NameKey::Type(ty)];
1128 write!(self.out, "{name}")?;
1129 Ok(())
1130 }
1131 // glsl array has the size separated from the base type
1132 TypeInner::Array { base, .. } => self.write_type(base),
1133 ref other => self.write_value_type(other),
1134 }
1135 }
1136
1137 /// Helper method to write a image type
1138 ///
1139 /// # Notes
1140 /// Adds no leading or trailing whitespace
1141 fn write_image_type(
1142 &mut self,
1143 dim: crate::ImageDimension,
1144 arrayed: bool,
1145 class: crate::ImageClass,
1146 ) -> BackendResult {
1147 // glsl images consist of four parts the scalar prefix, the image "type", the dimensions
1148 // and modifiers
1149 //
1150 // There exists two image types
1151 // - sampler - for sampled images
1152 // - image - for storage images
1153 //
1154 // There are three possible modifiers that can be used together and must be written in
1155 // this order to be valid
1156 // - MS - used if it's a multisampled image
1157 // - Array - used if it's an image array
1158 // - Shadow - used if it's a depth image
1159 use crate::ImageClass as Ic;
1160 use crate::Scalar as S;
1161 let float = S {
1162 kind: crate::ScalarKind::Float,
1163 width: 4,
1164 };
1165 let (base, scalar, ms, comparison) = match class {
1166 Ic::Sampled { kind, multi: true } => ("sampler", S { kind, width: 4 }, "MS", ""),
1167 Ic::Sampled { kind, multi: false } => ("sampler", S { kind, width: 4 }, "", ""),
1168 Ic::Depth { multi: true } => ("sampler", float, "MS", ""),
1169 Ic::Depth { multi: false } => ("sampler", float, "", "Shadow"),
1170 Ic::Storage { format, .. } => ("image", format.into(), "", ""),
1171 };
1172
1173 let precision = if self.options.version.is_es() {
1174 "highp "
1175 } else {
1176 ""
1177 };
1178
1179 write!(
1180 self.out,
1181 "{}{}{}{}{}{}{}",
1182 precision,
1183 glsl_scalar(scalar)?.prefix,
1184 base,
1185 glsl_dimension(dim),
1186 ms,
1187 if arrayed { "Array" } else { "" },
1188 comparison
1189 )?;
1190
1191 Ok(())
1192 }
1193
1194 /// Helper method used by [Self::write_global] to write just the layout part of
1195 /// a non image/sampler global variable, if applicable.
1196 ///
1197 /// # Notes
1198 ///
1199 /// Adds trailing whitespace if any layout qualifier is written
1200 fn write_global_layout(&mut self, global: &crate::GlobalVariable) -> BackendResult {
1201 // Determine which (if any) explicit memory layout to use, and whether we support it
1202 let layout = match global.space {
1203 crate::AddressSpace::Uniform => {
1204 if !self.options.version.supports_std140_layout() {
1205 return Err(Error::Custom(
1206 "Uniform address space requires std140 layout support".to_string(),
1207 ));
1208 }
1209
1210 Some("std140")
1211 }
1212 crate::AddressSpace::Storage { .. } => {
1213 if !self.options.version.supports_std430_layout() {
1214 return Err(Error::Custom(
1215 "Storage address space requires std430 layout support".to_string(),
1216 ));
1217 }
1218
1219 Some("std430")
1220 }
1221 _ => None,
1222 };
1223
1224 // If our version supports explicit layouts, we can also output the explicit binding
1225 // if we have it
1226 if self.options.version.supports_explicit_locations() {
1227 if let Some(ref br) = global.binding {
1228 match self.options.binding_map.get(br) {
1229 Some(binding) => {
1230 write!(self.out, "layout(")?;
1231
1232 if let Some(layout) = layout {
1233 write!(self.out, "{}, ", layout)?;
1234 }
1235
1236 write!(self.out, "binding = {binding}) ")?;
1237
1238 return Ok(());
1239 }
1240 None => {
1241 log::debug!("unassigned binding for {:?}", global.name);
1242 }
1243 }
1244 }
1245 }
1246
1247 // Either no explicit bindings are supported or we didn't have any.
1248 // Write just the memory layout.
1249 if let Some(layout) = layout {
1250 write!(self.out, "layout({}) ", layout)?;
1251 }
1252
1253 Ok(())
1254 }
1255
1256 /// Helper method used to write non images/sampler globals
1257 ///
1258 /// # Notes
1259 /// Adds a newline
1260 ///
1261 /// # Panics
1262 /// If the global has type sampler
1263 fn write_global(
1264 &mut self,
1265 handle: Handle<crate::GlobalVariable>,
1266 global: &crate::GlobalVariable,
1267 ) -> BackendResult {
1268 self.write_global_layout(global)?;
1269
1270 if let crate::AddressSpace::Storage { access } = global.space {
1271 self.write_storage_access(access)?;
1272 }
1273
1274 if let Some(storage_qualifier) = glsl_storage_qualifier(global.space) {
1275 write!(self.out, "{storage_qualifier} ")?;
1276 }
1277
1278 match global.space {
1279 crate::AddressSpace::Private => {
1280 self.write_simple_global(handle, global)?;
1281 }
1282 crate::AddressSpace::WorkGroup => {
1283 self.write_simple_global(handle, global)?;
1284 }
1285 crate::AddressSpace::PushConstant => {
1286 self.write_simple_global(handle, global)?;
1287 }
1288 crate::AddressSpace::Uniform => {
1289 self.write_interface_block(handle, global)?;
1290 }
1291 crate::AddressSpace::Storage { .. } => {
1292 self.write_interface_block(handle, global)?;
1293 }
1294 // A global variable in the `Function` address space is a
1295 // contradiction in terms.
1296 crate::AddressSpace::Function => unreachable!(),
1297 // Textures and samplers are handled directly in `Writer::write`.
1298 crate::AddressSpace::Handle => unreachable!(),
1299 }
1300
1301 Ok(())
1302 }
1303
1304 fn write_simple_global(
1305 &mut self,
1306 handle: Handle<crate::GlobalVariable>,
1307 global: &crate::GlobalVariable,
1308 ) -> BackendResult {
1309 self.write_type(global.ty)?;
1310 write!(self.out, " ")?;
1311 self.write_global_name(handle, global)?;
1312
1313 if let TypeInner::Array { base, size, .. } = self.module.types[global.ty].inner {
1314 self.write_array_size(base, size)?;
1315 }
1316
1317 if global.space.initializable() && is_value_init_supported(self.module, global.ty) {
1318 write!(self.out, " = ")?;
1319 if let Some(init) = global.init {
1320 self.write_const_expr(init, &self.module.global_expressions)?;
1321 } else {
1322 self.write_zero_init_value(global.ty)?;
1323 }
1324 }
1325
1326 writeln!(self.out, ";")?;
1327
1328 if let crate::AddressSpace::PushConstant = global.space {
1329 let global_name = self.get_global_name(handle, global);
1330 self.reflection_names_globals.insert(handle, global_name);
1331 }
1332
1333 Ok(())
1334 }
1335
1336 /// Write an interface block for a single Naga global.
1337 ///
1338 /// Write `block_name { members }`. Since `block_name` must be unique
1339 /// between blocks and structs, we add `_block_ID` where `ID` is a
1340 /// `IdGenerator` generated number. Write `members` in the same way we write
1341 /// a struct's members.
1342 fn write_interface_block(
1343 &mut self,
1344 handle: Handle<crate::GlobalVariable>,
1345 global: &crate::GlobalVariable,
1346 ) -> BackendResult {
1347 // Write the block name, it's just the struct name appended with `_block_ID`
1348 let ty_name = &self.names[&NameKey::Type(global.ty)];
1349 let block_name = format!(
1350 "{}_block_{}{:?}",
1351 // avoid double underscores as they are reserved in GLSL
1352 ty_name.trim_end_matches('_'),
1353 self.block_id.generate(),
1354 self.entry_point.stage,
1355 );
1356 write!(self.out, "{block_name} ")?;
1357 self.reflection_names_globals.insert(handle, block_name);
1358
1359 match self.module.types[global.ty].inner {
1360 TypeInner::Struct { ref members, .. }
1361 if self.module.types[members.last().unwrap().ty]
1362 .inner
1363 .is_dynamically_sized(&self.module.types) =>
1364 {
1365 // Structs with dynamically sized arrays must have their
1366 // members lifted up as members of the interface block. GLSL
1367 // can't write such struct types anyway.
1368 self.write_struct_body(global.ty, members)?;
1369 write!(self.out, " ")?;
1370 self.write_global_name(handle, global)?;
1371 }
1372 _ => {
1373 // A global of any other type is written as the sole member
1374 // of the interface block. Since the interface block is
1375 // anonymous, this becomes visible in the global scope.
1376 write!(self.out, "{{ ")?;
1377 self.write_type(global.ty)?;
1378 write!(self.out, " ")?;
1379 self.write_global_name(handle, global)?;
1380 if let TypeInner::Array { base, size, .. } = self.module.types[global.ty].inner {
1381 self.write_array_size(base, size)?;
1382 }
1383 write!(self.out, "; }}")?;
1384 }
1385 }
1386
1387 writeln!(self.out, ";")?;
1388
1389 Ok(())
1390 }
1391
1392 /// Helper method used to find which expressions of a given function require baking
1393 ///
1394 /// # Notes
1395 /// Clears `need_bake_expressions` set before adding to it
1396 fn update_expressions_to_bake(&mut self, func: &crate::Function, info: &valid::FunctionInfo) {
1397 use crate::Expression;
1398 self.need_bake_expressions.clear();
1399 for (fun_handle, expr) in func.expressions.iter() {
1400 let expr_info = &info[fun_handle];
1401 let min_ref_count = func.expressions[fun_handle].bake_ref_count();
1402 if min_ref_count <= expr_info.ref_count {
1403 self.need_bake_expressions.insert(fun_handle);
1404 }
1405
1406 let inner = expr_info.ty.inner_with(&self.module.types);
1407
1408 if let Expression::Math {
1409 fun,
1410 arg,
1411 arg1,
1412 arg2,
1413 ..
1414 } = *expr
1415 {
1416 match fun {
1417 crate::MathFunction::Dot => {
1418 // if the expression is a Dot product with integer arguments,
1419 // then the args needs baking as well
1420 if let TypeInner::Scalar(crate::Scalar {
1421 kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
1422 ..
1423 }) = *inner
1424 {
1425 self.need_bake_expressions.insert(arg);
1426 self.need_bake_expressions.insert(arg1.unwrap());
1427 }
1428 }
1429 crate::MathFunction::Dot4U8Packed | crate::MathFunction::Dot4I8Packed => {
1430 self.need_bake_expressions.insert(arg);
1431 self.need_bake_expressions.insert(arg1.unwrap());
1432 }
1433 crate::MathFunction::Pack4xI8
1434 | crate::MathFunction::Pack4xU8
1435 | crate::MathFunction::Pack4xI8Clamp
1436 | crate::MathFunction::Pack4xU8Clamp
1437 | crate::MathFunction::Unpack4xI8
1438 | crate::MathFunction::Unpack4xU8
1439 | crate::MathFunction::QuantizeToF16 => {
1440 self.need_bake_expressions.insert(arg);
1441 }
1442 /* crate::MathFunction::Pack4x8unorm | */
1443 crate::MathFunction::Unpack4x8snorm
1444 if !self.options.version.supports_pack_unpack_4x8() =>
1445 {
1446 // We have a fallback if the platform doesn't natively support these
1447 self.need_bake_expressions.insert(arg);
1448 }
1449 /* crate::MathFunction::Pack4x8unorm | */
1450 crate::MathFunction::Unpack4x8unorm
1451 if !self.options.version.supports_pack_unpack_4x8() =>
1452 {
1453 self.need_bake_expressions.insert(arg);
1454 }
1455 /* crate::MathFunction::Pack2x16snorm | */
1456 crate::MathFunction::Unpack2x16snorm
1457 if !self.options.version.supports_pack_unpack_snorm_2x16() =>
1458 {
1459 self.need_bake_expressions.insert(arg);
1460 }
1461 /* crate::MathFunction::Pack2x16unorm | */
1462 crate::MathFunction::Unpack2x16unorm
1463 if !self.options.version.supports_pack_unpack_unorm_2x16() =>
1464 {
1465 self.need_bake_expressions.insert(arg);
1466 }
1467 crate::MathFunction::ExtractBits => {
1468 // Only argument 1 is re-used.
1469 self.need_bake_expressions.insert(arg1.unwrap());
1470 }
1471 crate::MathFunction::InsertBits => {
1472 // Only argument 2 is re-used.
1473 self.need_bake_expressions.insert(arg2.unwrap());
1474 }
1475 crate::MathFunction::CountLeadingZeros => {
1476 if let Some(crate::ScalarKind::Sint) = inner.scalar_kind() {
1477 self.need_bake_expressions.insert(arg);
1478 }
1479 }
1480 _ => {}
1481 }
1482 }
1483 }
1484 }
1485
1486 /// Helper method used to get a name for a global
1487 ///
1488 /// Globals have different naming schemes depending on their binding:
1489 /// - Globals without bindings use the name from the [`Namer`](crate::proc::Namer)
1490 /// - Globals with resource binding are named `_group_X_binding_Y` where `X`
1491 /// is the group and `Y` is the binding
1492 fn get_global_name(
1493 &self,
1494 handle: Handle<crate::GlobalVariable>,
1495 global: &crate::GlobalVariable,
1496 ) -> String {
1497 match (&global.binding, global.space) {
1498 (&Some(ref br), _) => {
1499 format!(
1500 "_group_{}_binding_{}_{}",
1501 br.group,
1502 br.binding,
1503 self.entry_point.stage.to_str()
1504 )
1505 }
1506 (&None, crate::AddressSpace::PushConstant) => {
1507 format!("_push_constant_binding_{}", self.entry_point.stage.to_str())
1508 }
1509 (&None, _) => self.names[&NameKey::GlobalVariable(handle)].clone(),
1510 }
1511 }
1512
1513 /// Helper method used to write a name for a global without additional heap allocation
1514 fn write_global_name(
1515 &mut self,
1516 handle: Handle<crate::GlobalVariable>,
1517 global: &crate::GlobalVariable,
1518 ) -> BackendResult {
1519 match (&global.binding, global.space) {
1520 (&Some(ref br), _) => write!(
1521 self.out,
1522 "_group_{}_binding_{}_{}",
1523 br.group,
1524 br.binding,
1525 self.entry_point.stage.to_str()
1526 )?,
1527 (&None, crate::AddressSpace::PushConstant) => write!(
1528 self.out,
1529 "_push_constant_binding_{}",
1530 self.entry_point.stage.to_str()
1531 )?,
1532 (&None, _) => write!(
1533 self.out,
1534 "{}",
1535 &self.names[&NameKey::GlobalVariable(handle)]
1536 )?,
1537 }
1538
1539 Ok(())
1540 }
1541
1542 /// Write a GLSL global that will carry a Naga entry point's argument or return value.
1543 ///
1544 /// A Naga entry point's arguments and return value are rendered in GLSL as
1545 /// variables at global scope with the `in` and `out` storage qualifiers.
1546 /// The code we generate for `main` loads from all the `in` globals into
1547 /// appropriately named locals. Before it returns, `main` assigns the
1548 /// components of its return value into all the `out` globals.
1549 ///
1550 /// This function writes a declaration for one such GLSL global,
1551 /// representing a value passed into or returned from [`self.entry_point`]
1552 /// that has a [`Location`] binding. The global's name is generated based on
1553 /// the location index and the shader stages being connected; see
1554 /// [`VaryingName`]. This means we don't need to know the names of
1555 /// arguments, just their types and bindings.
1556 ///
1557 /// Emit nothing for entry point arguments or return values with [`BuiltIn`]
1558 /// bindings; `main` will read from or assign to the appropriate GLSL
1559 /// special variable; these are pre-declared. As an exception, we do declare
1560 /// `gl_Position` or `gl_FragCoord` with the `invariant` qualifier if
1561 /// needed.
1562 ///
1563 /// Use `output` together with [`self.entry_point.stage`] to determine which
1564 /// shader stages are being connected, and choose the `in` or `out` storage
1565 /// qualifier.
1566 ///
1567 /// [`self.entry_point`]: Writer::entry_point
1568 /// [`self.entry_point.stage`]: crate::EntryPoint::stage
1569 /// [`Location`]: crate::Binding::Location
1570 /// [`BuiltIn`]: crate::Binding::BuiltIn
1571 fn write_varying(
1572 &mut self,
1573 binding: Option<&crate::Binding>,
1574 ty: Handle<crate::Type>,
1575 output: bool,
1576 ) -> Result<(), Error> {
1577 // For a struct, emit a separate global for each member with a binding.
1578 if let TypeInner::Struct { ref members, .. } = self.module.types[ty].inner {
1579 for member in members {
1580 self.write_varying(member.binding.as_ref(), member.ty, output)?;
1581 }
1582 return Ok(());
1583 }
1584
1585 let binding = match binding {
1586 None => return Ok(()),
1587 Some(binding) => binding,
1588 };
1589
1590 let (location, interpolation, sampling, blend_src) = match *binding {
1591 crate::Binding::Location {
1592 location,
1593 interpolation,
1594 sampling,
1595 blend_src,
1596 } => (location, interpolation, sampling, blend_src),
1597 crate::Binding::BuiltIn(built_in) => {
1598 if let crate::BuiltIn::Position { invariant: true } = built_in {
1599 match (self.options.version, self.entry_point.stage) {
1600 (
1601 Version::Embedded {
1602 version: 300,
1603 is_webgl: true,
1604 },
1605 ShaderStage::Fragment,
1606 ) => {
1607 // `invariant gl_FragCoord` is not allowed in WebGL2 and possibly
1608 // OpenGL ES in general (waiting on confirmation).
1609 //
1610 // See https://github.com/KhronosGroup/WebGL/issues/3518
1611 }
1612 _ => {
1613 writeln!(
1614 self.out,
1615 "invariant {};",
1616 glsl_built_in(
1617 built_in,
1618 VaryingOptions::from_writer_options(self.options, output)
1619 )
1620 )?;
1621 }
1622 }
1623 }
1624 return Ok(());
1625 }
1626 };
1627
1628 // Write the interpolation modifier if needed
1629 //
1630 // We ignore all interpolation and auxiliary modifiers that aren't used in fragment
1631 // shaders' input globals or vertex shaders' output globals.
1632 let emit_interpolation_and_auxiliary = match self.entry_point.stage {
1633 ShaderStage::Vertex => output,
1634 ShaderStage::Fragment => !output,
1635 ShaderStage::Compute => false,
1636 ShaderStage::Task | ShaderStage::Mesh => unreachable!(),
1637 };
1638
1639 // Write the I/O locations, if allowed
1640 let io_location = if self.options.version.supports_explicit_locations()
1641 || !emit_interpolation_and_auxiliary
1642 {
1643 if self.options.version.supports_io_locations() {
1644 if let Some(blend_src) = blend_src {
1645 write!(
1646 self.out,
1647 "layout(location = {location}, index = {blend_src}) "
1648 )?;
1649 } else {
1650 write!(self.out, "layout(location = {location}) ")?;
1651 }
1652 None
1653 } else {
1654 Some(VaryingLocation {
1655 location,
1656 index: blend_src.unwrap_or(0),
1657 })
1658 }
1659 } else {
1660 None
1661 };
1662
1663 // Write the interpolation qualifier.
1664 if let Some(interp) = interpolation {
1665 if emit_interpolation_and_auxiliary {
1666 write!(self.out, "{} ", glsl_interpolation(interp))?;
1667 }
1668 }
1669
1670 // Write the sampling auxiliary qualifier.
1671 //
1672 // Before GLSL 4.2, the `centroid` and `sample` qualifiers were required to appear
1673 // immediately before the `in` / `out` qualifier, so we'll just follow that rule
1674 // here, regardless of the version.
1675 if let Some(sampling) = sampling {
1676 if emit_interpolation_and_auxiliary {
1677 if let Some(qualifier) = glsl_sampling(sampling)? {
1678 write!(self.out, "{qualifier} ")?;
1679 }
1680 }
1681 }
1682
1683 // Write the input/output qualifier.
1684 write!(self.out, "{} ", if output { "out" } else { "in" })?;
1685
1686 // Write the type
1687 // `write_type` adds no leading or trailing spaces
1688 self.write_type(ty)?;
1689
1690 // Finally write the global name and end the global with a `;` and a newline
1691 // Leading space is important
1692 let vname = VaryingName {
1693 binding: &crate::Binding::Location {
1694 location,
1695 interpolation: None,
1696 sampling: None,
1697 blend_src,
1698 },
1699 stage: self.entry_point.stage,
1700 options: VaryingOptions::from_writer_options(self.options, output),
1701 };
1702 writeln!(self.out, " {vname};")?;
1703
1704 if let Some(location) = io_location {
1705 self.varying.insert(vname.to_string(), location);
1706 }
1707
1708 Ok(())
1709 }
1710
1711 /// Helper method used to write functions (both entry points and regular functions)
1712 ///
1713 /// # Notes
1714 /// Adds a newline
1715 fn write_function(
1716 &mut self,
1717 ty: back::FunctionType,
1718 func: &crate::Function,
1719 info: &valid::FunctionInfo,
1720 ) -> BackendResult {
1721 // Create a function context for the function being written
1722 let ctx = back::FunctionCtx {
1723 ty,
1724 info,
1725 expressions: &func.expressions,
1726 named_expressions: &func.named_expressions,
1727 };
1728
1729 self.named_expressions.clear();
1730 self.update_expressions_to_bake(func, info);
1731
1732 // Write the function header
1733 //
1734 // glsl headers are the same as in c:
1735 // `ret_type name(args)`
1736 // `ret_type` is the return type
1737 // `name` is the function name
1738 // `args` is a comma separated list of `type name`
1739 // | - `type` is the argument type
1740 // | - `name` is the argument name
1741
1742 // Start by writing the return type if any otherwise write void
1743 // This is the only place where `void` is a valid type
1744 // (though it's more a keyword than a type)
1745 if let back::FunctionType::EntryPoint(_) = ctx.ty {
1746 write!(self.out, "void")?;
1747 } else if let Some(ref result) = func.result {
1748 self.write_type(result.ty)?;
1749 if let TypeInner::Array { base, size, .. } = self.module.types[result.ty].inner {
1750 self.write_array_size(base, size)?
1751 }
1752 } else {
1753 write!(self.out, "void")?;
1754 }
1755
1756 // Write the function name and open parentheses for the argument list
1757 let function_name = match ctx.ty {
1758 back::FunctionType::Function(handle) => &self.names[&NameKey::Function(handle)],
1759 back::FunctionType::EntryPoint(_) => "main",
1760 };
1761 write!(self.out, " {function_name}(")?;
1762
1763 // Write the comma separated argument list
1764 //
1765 // We need access to `Self` here so we use the reference passed to the closure as an
1766 // argument instead of capturing as that would cause a borrow checker error
1767 let arguments = match ctx.ty {
1768 back::FunctionType::EntryPoint(_) => &[][..],
1769 back::FunctionType::Function(_) => &func.arguments,
1770 };
1771 let arguments: Vec<_> = arguments
1772 .iter()
1773 .enumerate()
1774 .filter(|&(_, arg)| match self.module.types[arg.ty].inner {
1775 TypeInner::Sampler { .. } => false,
1776 _ => true,
1777 })
1778 .collect();
1779 self.write_slice(&arguments, |this, _, &(i, arg)| {
1780 // Write the argument type
1781 match this.module.types[arg.ty].inner {
1782 // We treat images separately because they might require
1783 // writing the storage format
1784 TypeInner::Image {
1785 dim,
1786 arrayed,
1787 class,
1788 } => {
1789 // Write the storage format if needed
1790 if let TypeInner::Image {
1791 class: crate::ImageClass::Storage { format, .. },
1792 ..
1793 } = this.module.types[arg.ty].inner
1794 {
1795 write!(this.out, "layout({}) ", glsl_storage_format(format)?)?;
1796 }
1797
1798 // write the type
1799 //
1800 // This is way we need the leading space because `write_image_type` doesn't add
1801 // any spaces at the beginning or end
1802 this.write_image_type(dim, arrayed, class)?;
1803 }
1804 TypeInner::Pointer { base, .. } => {
1805 // write parameter qualifiers
1806 write!(this.out, "inout ")?;
1807 this.write_type(base)?;
1808 }
1809 // All other types are written by `write_type`
1810 _ => {
1811 this.write_type(arg.ty)?;
1812 }
1813 }
1814
1815 // Write the argument name
1816 // The leading space is important
1817 write!(this.out, " {}", &this.names[&ctx.argument_key(i as u32)])?;
1818
1819 // Write array size
1820 match this.module.types[arg.ty].inner {
1821 TypeInner::Array { base, size, .. } => {
1822 this.write_array_size(base, size)?;
1823 }
1824 TypeInner::Pointer { base, .. } => {
1825 if let TypeInner::Array { base, size, .. } = this.module.types[base].inner {
1826 this.write_array_size(base, size)?;
1827 }
1828 }
1829 _ => {}
1830 }
1831
1832 Ok(())
1833 })?;
1834
1835 // Close the parentheses and open braces to start the function body
1836 writeln!(self.out, ") {{")?;
1837
1838 if self.options.zero_initialize_workgroup_memory
1839 && ctx.ty.is_compute_entry_point(self.module)
1840 {
1841 self.write_workgroup_variables_initialization(&ctx)?;
1842 }
1843
1844 // Compose the function arguments from globals, in case of an entry point.
1845 if let back::FunctionType::EntryPoint(ep_index) = ctx.ty {
1846 let stage = self.module.entry_points[ep_index as usize].stage;
1847 for (index, arg) in func.arguments.iter().enumerate() {
1848 write!(self.out, "{}", back::INDENT)?;
1849 self.write_type(arg.ty)?;
1850 let name = &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)];
1851 write!(self.out, " {name}")?;
1852 write!(self.out, " = ")?;
1853 match self.module.types[arg.ty].inner {
1854 TypeInner::Struct { ref members, .. } => {
1855 self.write_type(arg.ty)?;
1856 write!(self.out, "(")?;
1857 for (index, member) in members.iter().enumerate() {
1858 let varying_name = VaryingName {
1859 binding: member.binding.as_ref().unwrap(),
1860 stage,
1861 options: VaryingOptions::from_writer_options(self.options, false),
1862 };
1863 if index != 0 {
1864 write!(self.out, ", ")?;
1865 }
1866 write!(self.out, "{varying_name}")?;
1867 }
1868 writeln!(self.out, ");")?;
1869 }
1870 _ => {
1871 let varying_name = VaryingName {
1872 binding: arg.binding.as_ref().unwrap(),
1873 stage,
1874 options: VaryingOptions::from_writer_options(self.options, false),
1875 };
1876 writeln!(self.out, "{varying_name};")?;
1877 }
1878 }
1879 }
1880 }
1881
1882 // Write all function locals
1883 // Locals are `type name (= init)?;` where the init part (including the =) are optional
1884 //
1885 // Always adds a newline
1886 for (handle, local) in func.local_variables.iter() {
1887 // Write indentation (only for readability) and the type
1888 // `write_type` adds no trailing space
1889 write!(self.out, "{}", back::INDENT)?;
1890 self.write_type(local.ty)?;
1891
1892 // Write the local name
1893 // The leading space is important
1894 write!(self.out, " {}", self.names[&ctx.name_key(handle)])?;
1895 // Write size for array type
1896 if let TypeInner::Array { base, size, .. } = self.module.types[local.ty].inner {
1897 self.write_array_size(base, size)?;
1898 }
1899 // Write the local initializer if needed
1900 if let Some(init) = local.init {
1901 // Put the equal signal only if there's a initializer
1902 // The leading and trailing spaces aren't needed but help with readability
1903 write!(self.out, " = ")?;
1904
1905 // Write the constant
1906 // `write_constant` adds no trailing or leading space/newline
1907 self.write_expr(init, &ctx)?;
1908 } else if is_value_init_supported(self.module, local.ty) {
1909 write!(self.out, " = ")?;
1910 self.write_zero_init_value(local.ty)?;
1911 }
1912
1913 // Finish the local with `;` and add a newline (only for readability)
1914 writeln!(self.out, ";")?
1915 }
1916
1917 // Write the function body (statement list)
1918 for sta in func.body.iter() {
1919 // Write a statement, the indentation should always be 1 when writing the function body
1920 // `write_stmt` adds a newline
1921 self.write_stmt(sta, &ctx, back::Level(1))?;
1922 }
1923
1924 // Close braces and add a newline
1925 writeln!(self.out, "}}")?;
1926
1927 Ok(())
1928 }
1929
1930 fn write_workgroup_variables_initialization(
1931 &mut self,
1932 ctx: &back::FunctionCtx,
1933 ) -> BackendResult {
1934 let mut vars = self
1935 .module
1936 .global_variables
1937 .iter()
1938 .filter(|&(handle, var)| {
1939 !ctx.info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup
1940 })
1941 .peekable();
1942
1943 if vars.peek().is_some() {
1944 let level = back::Level(1);
1945
1946 writeln!(self.out, "{level}if (gl_LocalInvocationID == uvec3(0u)) {{")?;
1947
1948 for (handle, var) in vars {
1949 let name = &self.names[&NameKey::GlobalVariable(handle)];
1950 write!(self.out, "{}{} = ", level.next(), name)?;
1951 self.write_zero_init_value(var.ty)?;
1952 writeln!(self.out, ";")?;
1953 }
1954
1955 writeln!(self.out, "{level}}}")?;
1956 self.write_barrier(crate::Barrier::WORK_GROUP, level)?;
1957 }
1958
1959 Ok(())
1960 }
1961
1962 /// Write a list of comma separated `T` values using a writer function `F`.
1963 ///
1964 /// The writer function `F` receives a mutable reference to `self` that if needed won't cause
1965 /// borrow checker issues (using for example a closure with `self` will cause issues), the
1966 /// second argument is the 0 based index of the element on the list, and the last element is
1967 /// a reference to the element `T` being written
1968 ///
1969 /// # Notes
1970 /// - Adds no newlines or leading/trailing whitespace
1971 /// - The last element won't have a trailing `,`
1972 fn write_slice<T, F: FnMut(&mut Self, u32, &T) -> BackendResult>(
1973 &mut self,
1974 data: &[T],
1975 mut f: F,
1976 ) -> BackendResult {
1977 // Loop through `data` invoking `f` for each element
1978 for (index, item) in data.iter().enumerate() {
1979 if index != 0 {
1980 write!(self.out, ", ")?;
1981 }
1982 f(self, index as u32, item)?;
1983 }
1984
1985 Ok(())
1986 }
1987
1988 /// Helper method used to write global constants
1989 fn write_global_constant(&mut self, handle: Handle<crate::Constant>) -> BackendResult {
1990 write!(self.out, "const ")?;
1991 let constant = &self.module.constants[handle];
1992 self.write_type(constant.ty)?;
1993 let name = &self.names[&NameKey::Constant(handle)];
1994 write!(self.out, " {name}")?;
1995 if let TypeInner::Array { base, size, .. } = self.module.types[constant.ty].inner {
1996 self.write_array_size(base, size)?;
1997 }
1998 write!(self.out, " = ")?;
1999 self.write_const_expr(constant.init, &self.module.global_expressions)?;
2000 writeln!(self.out, ";")?;
2001 Ok(())
2002 }
2003
2004 /// Helper method used to output a dot product as an arithmetic expression
2005 ///
2006 fn write_dot_product(
2007 &mut self,
2008 arg: Handle<crate::Expression>,
2009 arg1: Handle<crate::Expression>,
2010 size: usize,
2011 ctx: &back::FunctionCtx,
2012 ) -> BackendResult {
2013 // Write parentheses around the dot product expression to prevent operators
2014 // with different precedences from applying earlier.
2015 write!(self.out, "(")?;
2016
2017 // Cycle through all the components of the vector
2018 for index in 0..size {
2019 let component = back::COMPONENTS[index];
2020 // Write the addition to the previous product
2021 // This will print an extra '+' at the beginning but that is fine in glsl
2022 write!(self.out, " + ")?;
2023 // Write the first vector expression, this expression is marked to be
2024 // cached so unless it can't be cached (for example, it's a Constant)
2025 // it shouldn't produce large expressions.
2026 self.write_expr(arg, ctx)?;
2027 // Access the current component on the first vector
2028 write!(self.out, ".{component} * ")?;
2029 // Write the second vector expression, this expression is marked to be
2030 // cached so unless it can't be cached (for example, it's a Constant)
2031 // it shouldn't produce large expressions.
2032 self.write_expr(arg1, ctx)?;
2033 // Access the current component on the second vector
2034 write!(self.out, ".{component}")?;
2035 }
2036
2037 write!(self.out, ")")?;
2038 Ok(())
2039 }
2040
2041 /// Helper method used to write structs
2042 ///
2043 /// # Notes
2044 /// Ends in a newline
2045 fn write_struct_body(
2046 &mut self,
2047 handle: Handle<crate::Type>,
2048 members: &[crate::StructMember],
2049 ) -> BackendResult {
2050 // glsl structs are written as in C
2051 // `struct name() { members };`
2052 // | `struct` is a keyword
2053 // | `name` is the struct name
2054 // | `members` is a semicolon separated list of `type name`
2055 // | `type` is the member type
2056 // | `name` is the member name
2057 writeln!(self.out, "{{")?;
2058
2059 for (idx, member) in members.iter().enumerate() {
2060 // The indentation is only for readability
2061 write!(self.out, "{}", back::INDENT)?;
2062
2063 match self.module.types[member.ty].inner {
2064 TypeInner::Array {
2065 base,
2066 size,
2067 stride: _,
2068 } => {
2069 self.write_type(base)?;
2070 write!(
2071 self.out,
2072 " {}",
2073 &self.names[&NameKey::StructMember(handle, idx as u32)]
2074 )?;
2075 // Write [size]
2076 self.write_array_size(base, size)?;
2077 // Newline is important
2078 writeln!(self.out, ";")?;
2079 }
2080 _ => {
2081 // Write the member type
2082 // Adds no trailing space
2083 self.write_type(member.ty)?;
2084
2085 // Write the member name and put a semicolon
2086 // The leading space is important
2087 // All members must have a semicolon even the last one
2088 writeln!(
2089 self.out,
2090 " {};",
2091 &self.names[&NameKey::StructMember(handle, idx as u32)]
2092 )?;
2093 }
2094 }
2095 }
2096
2097 write!(self.out, "}}")?;
2098 Ok(())
2099 }
2100
2101 /// Helper method used to write statements
2102 ///
2103 /// # Notes
2104 /// Always adds a newline
2105 fn write_stmt(
2106 &mut self,
2107 sta: &crate::Statement,
2108 ctx: &back::FunctionCtx,
2109 level: back::Level,
2110 ) -> BackendResult {
2111 use crate::Statement;
2112
2113 match *sta {
2114 // This is where we can generate intermediate constants for some expression types.
2115 Statement::Emit(ref range) => {
2116 for handle in range.clone() {
2117 let ptr_class = ctx.resolve_type(handle, &self.module.types).pointer_space();
2118 let expr_name = if ptr_class.is_some() {
2119 // GLSL can't save a pointer-valued expression in a variable,
2120 // but we shouldn't ever need to: they should never be named expressions,
2121 // and none of the expression types flagged by bake_ref_count can be pointer-valued.
2122 None
2123 } else if let Some(name) = ctx.named_expressions.get(&handle) {
2124 // Front end provides names for all variables at the start of writing.
2125 // But we write them to step by step. We need to recache them
2126 // Otherwise, we could accidentally write variable name instead of full expression.
2127 // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords.
2128 Some(self.namer.call(name))
2129 } else if self.need_bake_expressions.contains(&handle) {
2130 Some(Baked(handle).to_string())
2131 } else {
2132 None
2133 };
2134
2135 // If we are going to write an `ImageLoad` next and the target image
2136 // is sampled and we are using the `Restrict` policy for bounds
2137 // checking images we need to write a local holding the clamped lod.
2138 if let crate::Expression::ImageLoad {
2139 image,
2140 level: Some(level_expr),
2141 ..
2142 } = ctx.expressions[handle]
2143 {
2144 if let TypeInner::Image {
2145 class: crate::ImageClass::Sampled { .. },
2146 ..
2147 } = *ctx.resolve_type(image, &self.module.types)
2148 {
2149 if let proc::BoundsCheckPolicy::Restrict = self.policies.image_load {
2150 write!(self.out, "{level}")?;
2151 self.write_clamped_lod(ctx, handle, image, level_expr)?
2152 }
2153 }
2154 }
2155
2156 if let Some(name) = expr_name {
2157 write!(self.out, "{level}")?;
2158 self.write_named_expr(handle, name, handle, ctx)?;
2159 }
2160 }
2161 }
2162 // Blocks are simple we just need to write the block statements between braces
2163 // We could also just print the statements but this is more readable and maps more
2164 // closely to the IR
2165 Statement::Block(ref block) => {
2166 write!(self.out, "{level}")?;
2167 writeln!(self.out, "{{")?;
2168 for sta in block.iter() {
2169 // Increase the indentation to help with readability
2170 self.write_stmt(sta, ctx, level.next())?
2171 }
2172 writeln!(self.out, "{level}}}")?
2173 }
2174 // Ifs are written as in C:
2175 // ```
2176 // if(condition) {
2177 // accept
2178 // } else {
2179 // reject
2180 // }
2181 // ```
2182 Statement::If {
2183 condition,
2184 ref accept,
2185 ref reject,
2186 } => {
2187 write!(self.out, "{level}")?;
2188 write!(self.out, "if (")?;
2189 self.write_expr(condition, ctx)?;
2190 writeln!(self.out, ") {{")?;
2191
2192 for sta in accept {
2193 // Increase indentation to help with readability
2194 self.write_stmt(sta, ctx, level.next())?;
2195 }
2196
2197 // If there are no statements in the reject block we skip writing it
2198 // This is only for readability
2199 if !reject.is_empty() {
2200 writeln!(self.out, "{level}}} else {{")?;
2201
2202 for sta in reject {
2203 // Increase indentation to help with readability
2204 self.write_stmt(sta, ctx, level.next())?;
2205 }
2206 }
2207
2208 writeln!(self.out, "{level}}}")?
2209 }
2210 // Switch are written as in C:
2211 // ```
2212 // switch (selector) {
2213 // // Fallthrough
2214 // case label:
2215 // block
2216 // // Non fallthrough
2217 // case label:
2218 // block
2219 // break;
2220 // default:
2221 // block
2222 // }
2223 // ```
2224 // Where the `default` case happens isn't important but we put it last
2225 // so that we don't need to print a `break` for it
2226 Statement::Switch {
2227 selector,
2228 ref cases,
2229 } => {
2230 let l2 = level.next();
2231 // Some GLSL consumers may not handle switches with a single
2232 // body correctly: See wgpu#4514. Write such switch statements
2233 // as a `do {} while(false);` loop instead.
2234 //
2235 // Since doing so may inadvertently capture `continue`
2236 // statements in the switch body, we must apply continue
2237 // forwarding. See the `naga::back::continue_forward` module
2238 // docs for details.
2239 let one_body = cases
2240 .iter()
2241 .rev()
2242 .skip(1)
2243 .all(|case| case.fall_through && case.body.is_empty());
2244 if one_body {
2245 // Unlike HLSL, in GLSL `continue_ctx` only needs to know
2246 // about [`Switch`] statements that are being rendered as
2247 // `do-while` loops.
2248 if let Some(variable) = self.continue_ctx.enter_switch(&mut self.namer) {
2249 writeln!(self.out, "{level}bool {variable} = false;",)?;
2250 };
2251 writeln!(self.out, "{level}do {{")?;
2252 // Note: Expressions have no side-effects so we don't need to emit selector expression.
2253
2254 // Body
2255 if let Some(case) = cases.last() {
2256 for sta in case.body.iter() {
2257 self.write_stmt(sta, ctx, l2)?;
2258 }
2259 }
2260 // End do-while
2261 writeln!(self.out, "{level}}} while(false);")?;
2262
2263 // Handle any forwarded continue statements.
2264 use back::continue_forward::ExitControlFlow;
2265 let op = match self.continue_ctx.exit_switch() {
2266 ExitControlFlow::None => None,
2267 ExitControlFlow::Continue { variable } => Some(("continue", variable)),
2268 ExitControlFlow::Break { variable } => Some(("break", variable)),
2269 };
2270 if let Some((control_flow, variable)) = op {
2271 writeln!(self.out, "{level}if ({variable}) {{")?;
2272 writeln!(self.out, "{l2}{control_flow};")?;
2273 writeln!(self.out, "{level}}}")?;
2274 }
2275 } else {
2276 // Start the switch
2277 write!(self.out, "{level}")?;
2278 write!(self.out, "switch(")?;
2279 self.write_expr(selector, ctx)?;
2280 writeln!(self.out, ") {{")?;
2281
2282 // Write all cases
2283 for case in cases {
2284 match case.value {
2285 crate::SwitchValue::I32(value) => {
2286 write!(self.out, "{l2}case {value}:")?
2287 }
2288 crate::SwitchValue::U32(value) => {
2289 write!(self.out, "{l2}case {value}u:")?
2290 }
2291 crate::SwitchValue::Default => write!(self.out, "{l2}default:")?,
2292 }
2293
2294 let write_block_braces = !(case.fall_through && case.body.is_empty());
2295 if write_block_braces {
2296 writeln!(self.out, " {{")?;
2297 } else {
2298 writeln!(self.out)?;
2299 }
2300
2301 for sta in case.body.iter() {
2302 self.write_stmt(sta, ctx, l2.next())?;
2303 }
2304
2305 if !case.fall_through && case.body.last().is_none_or(|s| !s.is_terminator())
2306 {
2307 writeln!(self.out, "{}break;", l2.next())?;
2308 }
2309
2310 if write_block_braces {
2311 writeln!(self.out, "{l2}}}")?;
2312 }
2313 }
2314
2315 writeln!(self.out, "{level}}}")?
2316 }
2317 }
2318 // Loops in naga IR are based on wgsl loops, glsl can emulate the behaviour by using a
2319 // while true loop and appending the continuing block to the body resulting on:
2320 // ```
2321 // bool loop_init = true;
2322 // while(true) {
2323 // if (!loop_init) { <continuing> }
2324 // loop_init = false;
2325 // <body>
2326 // }
2327 // ```
2328 Statement::Loop {
2329 ref body,
2330 ref continuing,
2331 break_if,
2332 } => {
2333 self.continue_ctx.enter_loop();
2334 if !continuing.is_empty() || break_if.is_some() {
2335 let gate_name = self.namer.call("loop_init");
2336 writeln!(self.out, "{level}bool {gate_name} = true;")?;
2337 writeln!(self.out, "{level}while(true) {{")?;
2338 let l2 = level.next();
2339 let l3 = l2.next();
2340 writeln!(self.out, "{l2}if (!{gate_name}) {{")?;
2341 for sta in continuing {
2342 self.write_stmt(sta, ctx, l3)?;
2343 }
2344 if let Some(condition) = break_if {
2345 write!(self.out, "{l3}if (")?;
2346 self.write_expr(condition, ctx)?;
2347 writeln!(self.out, ") {{")?;
2348 writeln!(self.out, "{}break;", l3.next())?;
2349 writeln!(self.out, "{l3}}}")?;
2350 }
2351 writeln!(self.out, "{l2}}}")?;
2352 writeln!(self.out, "{}{} = false;", level.next(), gate_name)?;
2353 } else {
2354 writeln!(self.out, "{level}while(true) {{")?;
2355 }
2356 for sta in body {
2357 self.write_stmt(sta, ctx, level.next())?;
2358 }
2359 writeln!(self.out, "{level}}}")?;
2360 self.continue_ctx.exit_loop();
2361 }
2362 // Break, continue and return as written as in C
2363 // `break;`
2364 Statement::Break => {
2365 write!(self.out, "{level}")?;
2366 writeln!(self.out, "break;")?
2367 }
2368 // `continue;`
2369 Statement::Continue => {
2370 // Sometimes we must render a `Continue` statement as a `break`.
2371 // See the docs for the `back::continue_forward` module.
2372 if let Some(variable) = self.continue_ctx.continue_encountered() {
2373 writeln!(self.out, "{level}{variable} = true;",)?;
2374 writeln!(self.out, "{level}break;")?
2375 } else {
2376 writeln!(self.out, "{level}continue;")?
2377 }
2378 }
2379 // `return expr;`, `expr` is optional
2380 Statement::Return { value } => {
2381 write!(self.out, "{level}")?;
2382 match ctx.ty {
2383 back::FunctionType::Function(_) => {
2384 write!(self.out, "return")?;
2385 // Write the expression to be returned if needed
2386 if let Some(expr) = value {
2387 write!(self.out, " ")?;
2388 self.write_expr(expr, ctx)?;
2389 }
2390 writeln!(self.out, ";")?;
2391 }
2392 back::FunctionType::EntryPoint(ep_index) => {
2393 let mut has_point_size = false;
2394 let ep = &self.module.entry_points[ep_index as usize];
2395 if let Some(ref result) = ep.function.result {
2396 let value = value.unwrap();
2397 match self.module.types[result.ty].inner {
2398 TypeInner::Struct { ref members, .. } => {
2399 let temp_struct_name = match ctx.expressions[value] {
2400 crate::Expression::Compose { .. } => {
2401 let return_struct = "_tmp_return";
2402 write!(
2403 self.out,
2404 "{} {} = ",
2405 &self.names[&NameKey::Type(result.ty)],
2406 return_struct
2407 )?;
2408 self.write_expr(value, ctx)?;
2409 writeln!(self.out, ";")?;
2410 write!(self.out, "{level}")?;
2411 Some(return_struct)
2412 }
2413 _ => None,
2414 };
2415
2416 for (index, member) in members.iter().enumerate() {
2417 if let Some(crate::Binding::BuiltIn(
2418 crate::BuiltIn::PointSize,
2419 )) = member.binding
2420 {
2421 has_point_size = true;
2422 }
2423
2424 let varying_name = VaryingName {
2425 binding: member.binding.as_ref().unwrap(),
2426 stage: ep.stage,
2427 options: VaryingOptions::from_writer_options(
2428 self.options,
2429 true,
2430 ),
2431 };
2432 write!(self.out, "{varying_name} = ")?;
2433
2434 if let Some(struct_name) = temp_struct_name {
2435 write!(self.out, "{struct_name}")?;
2436 } else {
2437 self.write_expr(value, ctx)?;
2438 }
2439
2440 // Write field name
2441 writeln!(
2442 self.out,
2443 ".{};",
2444 &self.names
2445 [&NameKey::StructMember(result.ty, index as u32)]
2446 )?;
2447 write!(self.out, "{level}")?;
2448 }
2449 }
2450 _ => {
2451 let name = VaryingName {
2452 binding: result.binding.as_ref().unwrap(),
2453 stage: ep.stage,
2454 options: VaryingOptions::from_writer_options(
2455 self.options,
2456 true,
2457 ),
2458 };
2459 write!(self.out, "{name} = ")?;
2460 self.write_expr(value, ctx)?;
2461 writeln!(self.out, ";")?;
2462 write!(self.out, "{level}")?;
2463 }
2464 }
2465 }
2466
2467 let is_vertex_stage = self.module.entry_points[ep_index as usize].stage
2468 == ShaderStage::Vertex;
2469 if is_vertex_stage
2470 && self
2471 .options
2472 .writer_flags
2473 .contains(WriterFlags::ADJUST_COORDINATE_SPACE)
2474 {
2475 writeln!(
2476 self.out,
2477 "gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);",
2478 )?;
2479 write!(self.out, "{level}")?;
2480 }
2481
2482 if is_vertex_stage
2483 && self
2484 .options
2485 .writer_flags
2486 .contains(WriterFlags::FORCE_POINT_SIZE)
2487 && !has_point_size
2488 {
2489 writeln!(self.out, "gl_PointSize = 1.0;")?;
2490 write!(self.out, "{level}")?;
2491 }
2492 writeln!(self.out, "return;")?;
2493 }
2494 }
2495 }
2496 // This is one of the places were glsl adds to the syntax of C in this case the discard
2497 // keyword which ceases all further processing in a fragment shader, it's called OpKill
2498 // in spir-v that's why it's called `Statement::Kill`
2499 Statement::Kill => writeln!(self.out, "{level}discard;")?,
2500 Statement::Barrier(flags) => {
2501 self.write_barrier(flags, level)?;
2502 }
2503 // Stores in glsl are just variable assignments written as `pointer = value;`
2504 Statement::Store { pointer, value } => {
2505 write!(self.out, "{level}")?;
2506 self.write_expr(pointer, ctx)?;
2507 write!(self.out, " = ")?;
2508 self.write_expr(value, ctx)?;
2509 writeln!(self.out, ";")?
2510 }
2511 Statement::WorkGroupUniformLoad { pointer, result } => {
2512 // GLSL doesn't have pointers, which means that this backend needs to ensure that
2513 // the actual "loading" is happening between the two barriers.
2514 // This is done in `Emit` by never emitting a variable name for pointer variables
2515 self.write_barrier(crate::Barrier::WORK_GROUP, level)?;
2516
2517 let result_name = Baked(result).to_string();
2518 write!(self.out, "{level}")?;
2519 // Expressions cannot have side effects, so just writing the expression here is fine.
2520 self.write_named_expr(pointer, result_name, result, ctx)?;
2521
2522 self.write_barrier(crate::Barrier::WORK_GROUP, level)?;
2523 }
2524 // Stores a value into an image.
2525 Statement::ImageStore {
2526 image,
2527 coordinate,
2528 array_index,
2529 value,
2530 } => {
2531 write!(self.out, "{level}")?;
2532 self.write_image_store(ctx, image, coordinate, array_index, value)?
2533 }
2534 // A `Call` is written `name(arguments)` where `arguments` is a comma separated expressions list
2535 Statement::Call {
2536 function,
2537 ref arguments,
2538 result,
2539 } => {
2540 write!(self.out, "{level}")?;
2541 if let Some(expr) = result {
2542 let name = Baked(expr).to_string();
2543 let result = self.module.functions[function].result.as_ref().unwrap();
2544 self.write_type(result.ty)?;
2545 write!(self.out, " {name}")?;
2546 if let TypeInner::Array { base, size, .. } = self.module.types[result.ty].inner
2547 {
2548 self.write_array_size(base, size)?
2549 }
2550 write!(self.out, " = ")?;
2551 self.named_expressions.insert(expr, name);
2552 }
2553 write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?;
2554 let arguments: Vec<_> = arguments
2555 .iter()
2556 .enumerate()
2557 .filter_map(|(i, arg)| {
2558 let arg_ty = self.module.functions[function].arguments[i].ty;
2559 match self.module.types[arg_ty].inner {
2560 TypeInner::Sampler { .. } => None,
2561 _ => Some(*arg),
2562 }
2563 })
2564 .collect();
2565 self.write_slice(&arguments, |this, _, arg| this.write_expr(*arg, ctx))?;
2566 writeln!(self.out, ");")?
2567 }
2568 Statement::Atomic {
2569 pointer,
2570 ref fun,
2571 value,
2572 result,
2573 } => {
2574 write!(self.out, "{level}")?;
2575 if let Some(result) = result {
2576 let res_name = Baked(result).to_string();
2577 let res_ty = ctx.resolve_type(result, &self.module.types);
2578 self.write_value_type(res_ty)?;
2579 write!(self.out, " {res_name} = ")?;
2580 self.named_expressions.insert(result, res_name);
2581 }
2582
2583 let fun_str = fun.to_glsl();
2584 write!(self.out, "atomic{fun_str}(")?;
2585 self.write_expr(pointer, ctx)?;
2586 write!(self.out, ", ")?;
2587 // handle the special cases
2588 match *fun {
2589 crate::AtomicFunction::Subtract => {
2590 // we just wrote `InterlockedAdd`, so negate the argument
2591 write!(self.out, "-")?;
2592 }
2593 crate::AtomicFunction::Exchange { compare: Some(_) } => {
2594 return Err(Error::Custom(
2595 "atomic CompareExchange is not implemented".to_string(),
2596 ));
2597 }
2598 _ => {}
2599 }
2600 self.write_expr(value, ctx)?;
2601 writeln!(self.out, ");")?;
2602 }
2603 // Stores a value into an image.
2604 Statement::ImageAtomic {
2605 image,
2606 coordinate,
2607 array_index,
2608 fun,
2609 value,
2610 } => {
2611 write!(self.out, "{level}")?;
2612 self.write_image_atomic(ctx, image, coordinate, array_index, fun, value)?
2613 }
2614 Statement::RayQuery { .. } => unreachable!(),
2615 Statement::SubgroupBallot { result, predicate } => {
2616 write!(self.out, "{level}")?;
2617 let res_name = Baked(result).to_string();
2618 let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2619 self.write_value_type(res_ty)?;
2620 write!(self.out, " {res_name} = ")?;
2621 self.named_expressions.insert(result, res_name);
2622
2623 write!(self.out, "subgroupBallot(")?;
2624 match predicate {
2625 Some(predicate) => self.write_expr(predicate, ctx)?,
2626 None => write!(self.out, "true")?,
2627 }
2628 writeln!(self.out, ");")?;
2629 }
2630 Statement::SubgroupCollectiveOperation {
2631 op,
2632 collective_op,
2633 argument,
2634 result,
2635 } => {
2636 write!(self.out, "{level}")?;
2637 let res_name = Baked(result).to_string();
2638 let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2639 self.write_value_type(res_ty)?;
2640 write!(self.out, " {res_name} = ")?;
2641 self.named_expressions.insert(result, res_name);
2642
2643 match (collective_op, op) {
2644 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::All) => {
2645 write!(self.out, "subgroupAll(")?
2646 }
2647 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Any) => {
2648 write!(self.out, "subgroupAny(")?
2649 }
2650 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Add) => {
2651 write!(self.out, "subgroupAdd(")?
2652 }
2653 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Mul) => {
2654 write!(self.out, "subgroupMul(")?
2655 }
2656 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Max) => {
2657 write!(self.out, "subgroupMax(")?
2658 }
2659 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Min) => {
2660 write!(self.out, "subgroupMin(")?
2661 }
2662 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::And) => {
2663 write!(self.out, "subgroupAnd(")?
2664 }
2665 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Or) => {
2666 write!(self.out, "subgroupOr(")?
2667 }
2668 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Xor) => {
2669 write!(self.out, "subgroupXor(")?
2670 }
2671 (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Add) => {
2672 write!(self.out, "subgroupExclusiveAdd(")?
2673 }
2674 (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Mul) => {
2675 write!(self.out, "subgroupExclusiveMul(")?
2676 }
2677 (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Add) => {
2678 write!(self.out, "subgroupInclusiveAdd(")?
2679 }
2680 (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Mul) => {
2681 write!(self.out, "subgroupInclusiveMul(")?
2682 }
2683 _ => unimplemented!(),
2684 }
2685 self.write_expr(argument, ctx)?;
2686 writeln!(self.out, ");")?;
2687 }
2688 Statement::SubgroupGather {
2689 mode,
2690 argument,
2691 result,
2692 } => {
2693 write!(self.out, "{level}")?;
2694 let res_name = Baked(result).to_string();
2695 let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2696 self.write_value_type(res_ty)?;
2697 write!(self.out, " {res_name} = ")?;
2698 self.named_expressions.insert(result, res_name);
2699
2700 match mode {
2701 crate::GatherMode::BroadcastFirst => {
2702 write!(self.out, "subgroupBroadcastFirst(")?;
2703 }
2704 crate::GatherMode::Broadcast(_) => {
2705 write!(self.out, "subgroupBroadcast(")?;
2706 }
2707 crate::GatherMode::Shuffle(_) => {
2708 write!(self.out, "subgroupShuffle(")?;
2709 }
2710 crate::GatherMode::ShuffleDown(_) => {
2711 write!(self.out, "subgroupShuffleDown(")?;
2712 }
2713 crate::GatherMode::ShuffleUp(_) => {
2714 write!(self.out, "subgroupShuffleUp(")?;
2715 }
2716 crate::GatherMode::ShuffleXor(_) => {
2717 write!(self.out, "subgroupShuffleXor(")?;
2718 }
2719 }
2720 self.write_expr(argument, ctx)?;
2721 match mode {
2722 crate::GatherMode::BroadcastFirst => {}
2723 crate::GatherMode::Broadcast(index)
2724 | crate::GatherMode::Shuffle(index)
2725 | crate::GatherMode::ShuffleDown(index)
2726 | crate::GatherMode::ShuffleUp(index)
2727 | crate::GatherMode::ShuffleXor(index) => {
2728 write!(self.out, ", ")?;
2729 self.write_expr(index, ctx)?;
2730 }
2731 }
2732 writeln!(self.out, ");")?;
2733 }
2734 }
2735
2736 Ok(())
2737 }
2738
2739 /// Write a const expression.
2740 ///
2741 /// Write `expr`, a handle to an [`Expression`] in the current [`Module`]'s
2742 /// constant expression arena, as GLSL expression.
2743 ///
2744 /// # Notes
2745 /// Adds no newlines or leading/trailing whitespace
2746 ///
2747 /// [`Expression`]: crate::Expression
2748 /// [`Module`]: crate::Module
2749 fn write_const_expr(
2750 &mut self,
2751 expr: Handle<crate::Expression>,
2752 arena: &crate::Arena<crate::Expression>,
2753 ) -> BackendResult {
2754 self.write_possibly_const_expr(
2755 expr,
2756 arena,
2757 |expr| &self.info[expr],
2758 |writer, expr| writer.write_const_expr(expr, arena),
2759 )
2760 }
2761
2762 /// Write [`Expression`] variants that can occur in both runtime and const expressions.
2763 ///
2764 /// Write `expr`, a handle to an [`Expression`] in the arena `expressions`,
2765 /// as as GLSL expression. This must be one of the [`Expression`] variants
2766 /// that is allowed to occur in constant expressions.
2767 ///
2768 /// Use `write_expression` to write subexpressions.
2769 ///
2770 /// This is the common code for `write_expr`, which handles arbitrary
2771 /// runtime expressions, and `write_const_expr`, which only handles
2772 /// const-expressions. Each of those callers passes itself (essentially) as
2773 /// the `write_expression` callback, so that subexpressions are restricted
2774 /// to the appropriate variants.
2775 ///
2776 /// # Notes
2777 /// Adds no newlines or leading/trailing whitespace
2778 ///
2779 /// [`Expression`]: crate::Expression
2780 fn write_possibly_const_expr<'w, I, E>(
2781 &'w mut self,
2782 expr: Handle<crate::Expression>,
2783 expressions: &crate::Arena<crate::Expression>,
2784 info: I,
2785 write_expression: E,
2786 ) -> BackendResult
2787 where
2788 I: Fn(Handle<crate::Expression>) -> &'w proc::TypeResolution,
2789 E: Fn(&mut Self, Handle<crate::Expression>) -> BackendResult,
2790 {
2791 use crate::Expression;
2792
2793 match expressions[expr] {
2794 Expression::Literal(literal) => {
2795 match literal {
2796 // Floats are written using `Debug` instead of `Display` because it always appends the
2797 // decimal part even it's zero which is needed for a valid glsl float constant
2798 crate::Literal::F64(value) => write!(self.out, "{value:?}LF")?,
2799 crate::Literal::F32(value) => write!(self.out, "{value:?}")?,
2800 crate::Literal::F16(_) => {
2801 return Err(Error::Custom("GLSL has no 16-bit float type".into()));
2802 }
2803 // Unsigned integers need a `u` at the end
2804 //
2805 // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we
2806 // always write it as the extra branch wouldn't have any benefit in readability
2807 crate::Literal::U32(value) => write!(self.out, "{value}u")?,
2808 crate::Literal::I32(value) => write!(self.out, "{value}")?,
2809 crate::Literal::Bool(value) => write!(self.out, "{value}")?,
2810 crate::Literal::I64(_) => {
2811 return Err(Error::Custom("GLSL has no 64-bit integer type".into()));
2812 }
2813 crate::Literal::U64(_) => {
2814 return Err(Error::Custom("GLSL has no 64-bit integer type".into()));
2815 }
2816 crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
2817 return Err(Error::Custom(
2818 "Abstract types should not appear in IR presented to backends".into(),
2819 ));
2820 }
2821 }
2822 }
2823 Expression::Constant(handle) => {
2824 let constant = &self.module.constants[handle];
2825 if constant.name.is_some() {
2826 write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?;
2827 } else {
2828 self.write_const_expr(constant.init, &self.module.global_expressions)?;
2829 }
2830 }
2831 Expression::ZeroValue(ty) => {
2832 self.write_zero_init_value(ty)?;
2833 }
2834 Expression::Compose { ty, ref components } => {
2835 self.write_type(ty)?;
2836
2837 if let TypeInner::Array { base, size, .. } = self.module.types[ty].inner {
2838 self.write_array_size(base, size)?;
2839 }
2840
2841 write!(self.out, "(")?;
2842 for (index, component) in components.iter().enumerate() {
2843 if index != 0 {
2844 write!(self.out, ", ")?;
2845 }
2846 write_expression(self, *component)?;
2847 }
2848 write!(self.out, ")")?
2849 }
2850 // `Splat` needs to actually write down a vector, it's not always inferred in GLSL.
2851 Expression::Splat { size: _, value } => {
2852 let resolved = info(expr).inner_with(&self.module.types);
2853 self.write_value_type(resolved)?;
2854 write!(self.out, "(")?;
2855 write_expression(self, value)?;
2856 write!(self.out, ")")?
2857 }
2858 _ => {
2859 return Err(Error::Override);
2860 }
2861 }
2862
2863 Ok(())
2864 }
2865
2866 /// Helper method to write expressions
2867 ///
2868 /// # Notes
2869 /// Doesn't add any newlines or leading/trailing spaces
2870 fn write_expr(
2871 &mut self,
2872 expr: Handle<crate::Expression>,
2873 ctx: &back::FunctionCtx,
2874 ) -> BackendResult {
2875 use crate::Expression;
2876
2877 if let Some(name) = self.named_expressions.get(&expr) {
2878 write!(self.out, "{name}")?;
2879 return Ok(());
2880 }
2881
2882 match ctx.expressions[expr] {
2883 Expression::Literal(_)
2884 | Expression::Constant(_)
2885 | Expression::ZeroValue(_)
2886 | Expression::Compose { .. }
2887 | Expression::Splat { .. } => {
2888 self.write_possibly_const_expr(
2889 expr,
2890 ctx.expressions,
2891 |expr| &ctx.info[expr].ty,
2892 |writer, expr| writer.write_expr(expr, ctx),
2893 )?;
2894 }
2895 Expression::Override(_) => return Err(Error::Override),
2896 // `Access` is applied to arrays, vectors and matrices and is written as indexing
2897 Expression::Access { base, index } => {
2898 self.write_expr(base, ctx)?;
2899 write!(self.out, "[")?;
2900 self.write_expr(index, ctx)?;
2901 write!(self.out, "]")?
2902 }
2903 // `AccessIndex` is the same as `Access` except that the index is a constant and it can
2904 // be applied to structs, in this case we need to find the name of the field at that
2905 // index and write `base.field_name`
2906 Expression::AccessIndex { base, index } => {
2907 self.write_expr(base, ctx)?;
2908
2909 let base_ty_res = &ctx.info[base].ty;
2910 let mut resolved = base_ty_res.inner_with(&self.module.types);
2911 let base_ty_handle = match *resolved {
2912 TypeInner::Pointer { base, space: _ } => {
2913 resolved = &self.module.types[base].inner;
2914 Some(base)
2915 }
2916 _ => base_ty_res.handle(),
2917 };
2918
2919 match *resolved {
2920 TypeInner::Vector { .. } => {
2921 // Write vector access as a swizzle
2922 write!(self.out, ".{}", back::COMPONENTS[index as usize])?
2923 }
2924 TypeInner::Matrix { .. }
2925 | TypeInner::Array { .. }
2926 | TypeInner::ValuePointer { .. } => write!(self.out, "[{index}]")?,
2927 TypeInner::Struct { .. } => {
2928 // This will never panic in case the type is a `Struct`, this is not true
2929 // for other types so we can only check while inside this match arm
2930 let ty = base_ty_handle.unwrap();
2931
2932 write!(
2933 self.out,
2934 ".{}",
2935 &self.names[&NameKey::StructMember(ty, index)]
2936 )?
2937 }
2938 ref other => return Err(Error::Custom(format!("Cannot index {other:?}"))),
2939 }
2940 }
2941 // `Swizzle` adds a few letters behind the dot.
2942 Expression::Swizzle {
2943 size,
2944 vector,
2945 pattern,
2946 } => {
2947 self.write_expr(vector, ctx)?;
2948 write!(self.out, ".")?;
2949 for &sc in pattern[..size as usize].iter() {
2950 self.out.write_char(back::COMPONENTS[sc as usize])?;
2951 }
2952 }
2953 // Function arguments are written as the argument name
2954 Expression::FunctionArgument(pos) => {
2955 write!(self.out, "{}", &self.names[&ctx.argument_key(pos)])?
2956 }
2957 // Global variables need some special work for their name but
2958 // `get_global_name` does the work for us
2959 Expression::GlobalVariable(handle) => {
2960 let global = &self.module.global_variables[handle];
2961 self.write_global_name(handle, global)?
2962 }
2963 // A local is written as it's name
2964 Expression::LocalVariable(handle) => {
2965 write!(self.out, "{}", self.names[&ctx.name_key(handle)])?
2966 }
2967 // glsl has no pointers so there's no load operation, just write the pointer expression
2968 Expression::Load { pointer } => self.write_expr(pointer, ctx)?,
2969 // `ImageSample` is a bit complicated compared to the rest of the IR.
2970 //
2971 // First there are three variations depending whether the sample level is explicitly set,
2972 // if it's automatic or it it's bias:
2973 // `texture(image, coordinate)` - Automatic sample level
2974 // `texture(image, coordinate, bias)` - Bias sample level
2975 // `textureLod(image, coordinate, level)` - Zero or Exact sample level
2976 //
2977 // Furthermore if `depth_ref` is some we need to append it to the coordinate vector
2978 Expression::ImageSample {
2979 image,
2980 sampler: _, //TODO?
2981 gather,
2982 coordinate,
2983 array_index,
2984 offset,
2985 level,
2986 depth_ref,
2987 } => {
2988 let (dim, class, arrayed) = match *ctx.resolve_type(image, &self.module.types) {
2989 TypeInner::Image {
2990 dim,
2991 class,
2992 arrayed,
2993 ..
2994 } => (dim, class, arrayed),
2995 _ => unreachable!(),
2996 };
2997 let mut err = None;
2998 if dim == crate::ImageDimension::Cube {
2999 if offset.is_some() {
3000 err = Some("gsamplerCube[Array][Shadow] doesn't support texture sampling with offsets");
3001 }
3002 if arrayed
3003 && matches!(class, crate::ImageClass::Depth { .. })
3004 && matches!(level, crate::SampleLevel::Gradient { .. })
3005 {
3006 err = Some("samplerCubeArrayShadow don't support textureGrad");
3007 }
3008 }
3009 if gather.is_some() && level != crate::SampleLevel::Zero {
3010 err = Some("textureGather doesn't support LOD parameters");
3011 }
3012 if let Some(err) = err {
3013 return Err(Error::Custom(String::from(err)));
3014 }
3015
3016 // `textureLod[Offset]` on `sampler2DArrayShadow` and `samplerCubeShadow` does not exist in GLSL,
3017 // unless `GL_EXT_texture_shadow_lod` is present.
3018 // But if the target LOD is zero, we can emulate that by using `textureGrad[Offset]` with a constant gradient of 0.
3019 let workaround_lod_with_grad = ((dim == crate::ImageDimension::Cube && !arrayed)
3020 || (dim == crate::ImageDimension::D2 && arrayed))
3021 && level == crate::SampleLevel::Zero
3022 && matches!(class, crate::ImageClass::Depth { .. })
3023 && !self.features.contains(Features::TEXTURE_SHADOW_LOD);
3024
3025 // Write the function to be used depending on the sample level
3026 let fun_name = match level {
3027 crate::SampleLevel::Zero if gather.is_some() => "textureGather",
3028 crate::SampleLevel::Zero if workaround_lod_with_grad => "textureGrad",
3029 crate::SampleLevel::Auto | crate::SampleLevel::Bias(_) => "texture",
3030 crate::SampleLevel::Zero | crate::SampleLevel::Exact(_) => "textureLod",
3031 crate::SampleLevel::Gradient { .. } => "textureGrad",
3032 };
3033 let offset_name = match offset {
3034 Some(_) => "Offset",
3035 None => "",
3036 };
3037
3038 write!(self.out, "{fun_name}{offset_name}(")?;
3039
3040 // Write the image that will be used
3041 self.write_expr(image, ctx)?;
3042 // The space here isn't required but it helps with readability
3043 write!(self.out, ", ")?;
3044
3045 // We need to get the coordinates vector size to later build a vector that's `size + 1`
3046 // if `depth_ref` is some, if it isn't a vector we panic as that's not a valid expression
3047 let mut coord_dim = match *ctx.resolve_type(coordinate, &self.module.types) {
3048 TypeInner::Vector { size, .. } => size as u8,
3049 TypeInner::Scalar { .. } => 1,
3050 _ => unreachable!(),
3051 };
3052
3053 if array_index.is_some() {
3054 coord_dim += 1;
3055 }
3056 let merge_depth_ref = depth_ref.is_some() && gather.is_none() && coord_dim < 4;
3057 if merge_depth_ref {
3058 coord_dim += 1;
3059 }
3060
3061 let tex_1d_hack = dim == crate::ImageDimension::D1 && self.options.version.is_es();
3062 let is_vec = tex_1d_hack || coord_dim != 1;
3063 // Compose a new texture coordinates vector
3064 if is_vec {
3065 write!(self.out, "vec{}(", coord_dim + tex_1d_hack as u8)?;
3066 }
3067 self.write_expr(coordinate, ctx)?;
3068 if tex_1d_hack {
3069 write!(self.out, ", 0.0")?;
3070 }
3071 if let Some(expr) = array_index {
3072 write!(self.out, ", ")?;
3073 self.write_expr(expr, ctx)?;
3074 }
3075 if merge_depth_ref {
3076 write!(self.out, ", ")?;
3077 self.write_expr(depth_ref.unwrap(), ctx)?;
3078 }
3079 if is_vec {
3080 write!(self.out, ")")?;
3081 }
3082
3083 if let (Some(expr), false) = (depth_ref, merge_depth_ref) {
3084 write!(self.out, ", ")?;
3085 self.write_expr(expr, ctx)?;
3086 }
3087
3088 match level {
3089 // Auto needs no more arguments
3090 crate::SampleLevel::Auto => (),
3091 // Zero needs level set to 0
3092 crate::SampleLevel::Zero => {
3093 if workaround_lod_with_grad {
3094 let vec_dim = match dim {
3095 crate::ImageDimension::Cube => 3,
3096 _ => 2,
3097 };
3098 write!(self.out, ", vec{vec_dim}(0.0), vec{vec_dim}(0.0)")?;
3099 } else if gather.is_none() {
3100 write!(self.out, ", 0.0")?;
3101 }
3102 }
3103 // Exact and bias require another argument
3104 crate::SampleLevel::Exact(expr) => {
3105 write!(self.out, ", ")?;
3106 self.write_expr(expr, ctx)?;
3107 }
3108 crate::SampleLevel::Bias(_) => {
3109 // This needs to be done after the offset writing
3110 }
3111 crate::SampleLevel::Gradient { x, y } => {
3112 // If we are using sampler2D to replace sampler1D, we also
3113 // need to make sure to use vec2 gradients
3114 if tex_1d_hack {
3115 write!(self.out, ", vec2(")?;
3116 self.write_expr(x, ctx)?;
3117 write!(self.out, ", 0.0)")?;
3118 write!(self.out, ", vec2(")?;
3119 self.write_expr(y, ctx)?;
3120 write!(self.out, ", 0.0)")?;
3121 } else {
3122 write!(self.out, ", ")?;
3123 self.write_expr(x, ctx)?;
3124 write!(self.out, ", ")?;
3125 self.write_expr(y, ctx)?;
3126 }
3127 }
3128 }
3129
3130 if let Some(constant) = offset {
3131 write!(self.out, ", ")?;
3132 if tex_1d_hack {
3133 write!(self.out, "ivec2(")?;
3134 }
3135 self.write_const_expr(constant, ctx.expressions)?;
3136 if tex_1d_hack {
3137 write!(self.out, ", 0)")?;
3138 }
3139 }
3140
3141 // Bias is always the last argument
3142 if let crate::SampleLevel::Bias(expr) = level {
3143 write!(self.out, ", ")?;
3144 self.write_expr(expr, ctx)?;
3145 }
3146
3147 if let (Some(component), None) = (gather, depth_ref) {
3148 write!(self.out, ", {}", component as usize)?;
3149 }
3150
3151 // End the function
3152 write!(self.out, ")")?
3153 }
3154 Expression::ImageLoad {
3155 image,
3156 coordinate,
3157 array_index,
3158 sample,
3159 level,
3160 } => self.write_image_load(expr, ctx, image, coordinate, array_index, sample, level)?,
3161 // Query translates into one of the:
3162 // - textureSize/imageSize
3163 // - textureQueryLevels
3164 // - textureSamples/imageSamples
3165 Expression::ImageQuery { image, query } => {
3166 use crate::ImageClass;
3167
3168 // This will only panic if the module is invalid
3169 let (dim, class) = match *ctx.resolve_type(image, &self.module.types) {
3170 TypeInner::Image {
3171 dim,
3172 arrayed: _,
3173 class,
3174 } => (dim, class),
3175 _ => unreachable!(),
3176 };
3177 let components = match dim {
3178 crate::ImageDimension::D1 => 1,
3179 crate::ImageDimension::D2 => 2,
3180 crate::ImageDimension::D3 => 3,
3181 crate::ImageDimension::Cube => 2,
3182 };
3183
3184 if let crate::ImageQuery::Size { .. } = query {
3185 match components {
3186 1 => write!(self.out, "uint(")?,
3187 _ => write!(self.out, "uvec{components}(")?,
3188 }
3189 } else {
3190 write!(self.out, "uint(")?;
3191 }
3192
3193 match query {
3194 crate::ImageQuery::Size { level } => {
3195 match class {
3196 ImageClass::Sampled { multi, .. } | ImageClass::Depth { multi } => {
3197 write!(self.out, "textureSize(")?;
3198 self.write_expr(image, ctx)?;
3199 if let Some(expr) = level {
3200 let cast_to_int = matches!(
3201 *ctx.resolve_type(expr, &self.module.types),
3202 TypeInner::Scalar(crate::Scalar {
3203 kind: crate::ScalarKind::Uint,
3204 ..
3205 })
3206 );
3207
3208 write!(self.out, ", ")?;
3209
3210 if cast_to_int {
3211 write!(self.out, "int(")?;
3212 }
3213
3214 self.write_expr(expr, ctx)?;
3215
3216 if cast_to_int {
3217 write!(self.out, ")")?;
3218 }
3219 } else if !multi {
3220 // All textureSize calls requires an lod argument
3221 // except for multisampled samplers
3222 write!(self.out, ", 0")?;
3223 }
3224 }
3225 ImageClass::Storage { .. } => {
3226 write!(self.out, "imageSize(")?;
3227 self.write_expr(image, ctx)?;
3228 }
3229 }
3230 write!(self.out, ")")?;
3231 if components != 1 || self.options.version.is_es() {
3232 write!(self.out, ".{}", &"xyz"[..components])?;
3233 }
3234 }
3235 crate::ImageQuery::NumLevels => {
3236 write!(self.out, "textureQueryLevels(",)?;
3237 self.write_expr(image, ctx)?;
3238 write!(self.out, ")",)?;
3239 }
3240 crate::ImageQuery::NumLayers => {
3241 let fun_name = match class {
3242 ImageClass::Sampled { .. } | ImageClass::Depth { .. } => "textureSize",
3243 ImageClass::Storage { .. } => "imageSize",
3244 };
3245 write!(self.out, "{fun_name}(")?;
3246 self.write_expr(image, ctx)?;
3247 // All textureSize calls requires an lod argument
3248 // except for multisampled samplers
3249 if !class.is_multisampled() {
3250 write!(self.out, ", 0")?;
3251 }
3252 write!(self.out, ")")?;
3253 if components != 1 || self.options.version.is_es() {
3254 write!(self.out, ".{}", back::COMPONENTS[components])?;
3255 }
3256 }
3257 crate::ImageQuery::NumSamples => {
3258 let fun_name = match class {
3259 ImageClass::Sampled { .. } | ImageClass::Depth { .. } => {
3260 "textureSamples"
3261 }
3262 ImageClass::Storage { .. } => "imageSamples",
3263 };
3264 write!(self.out, "{fun_name}(")?;
3265 self.write_expr(image, ctx)?;
3266 write!(self.out, ")",)?;
3267 }
3268 }
3269
3270 write!(self.out, ")")?;
3271 }
3272 Expression::Unary { op, expr } => {
3273 let operator_or_fn = match op {
3274 crate::UnaryOperator::Negate => "-",
3275 crate::UnaryOperator::LogicalNot => {
3276 match *ctx.resolve_type(expr, &self.module.types) {
3277 TypeInner::Vector { .. } => "not",
3278 _ => "!",
3279 }
3280 }
3281 crate::UnaryOperator::BitwiseNot => "~",
3282 };
3283 write!(self.out, "{operator_or_fn}(")?;
3284
3285 self.write_expr(expr, ctx)?;
3286
3287 write!(self.out, ")")?
3288 }
3289 // `Binary` we just write `left op right`, except when dealing with
3290 // comparison operations on vectors as they are implemented with
3291 // builtin functions.
3292 // Once again we wrap everything in parentheses to avoid precedence issues
3293 Expression::Binary {
3294 mut op,
3295 left,
3296 right,
3297 } => {
3298 // Holds `Some(function_name)` if the binary operation is
3299 // implemented as a function call
3300 use crate::{BinaryOperator as Bo, ScalarKind as Sk, TypeInner as Ti};
3301
3302 let left_inner = ctx.resolve_type(left, &self.module.types);
3303 let right_inner = ctx.resolve_type(right, &self.module.types);
3304
3305 let function = match (left_inner, right_inner) {
3306 (&Ti::Vector { scalar, .. }, &Ti::Vector { .. }) => match op {
3307 Bo::Less
3308 | Bo::LessEqual
3309 | Bo::Greater
3310 | Bo::GreaterEqual
3311 | Bo::Equal
3312 | Bo::NotEqual => BinaryOperation::VectorCompare,
3313 Bo::Modulo if scalar.kind == Sk::Float => BinaryOperation::Modulo,
3314 Bo::And if scalar.kind == Sk::Bool => {
3315 op = crate::BinaryOperator::LogicalAnd;
3316 BinaryOperation::VectorComponentWise
3317 }
3318 Bo::InclusiveOr if scalar.kind == Sk::Bool => {
3319 op = crate::BinaryOperator::LogicalOr;
3320 BinaryOperation::VectorComponentWise
3321 }
3322 _ => BinaryOperation::Other,
3323 },
3324 _ => match (left_inner.scalar_kind(), right_inner.scalar_kind()) {
3325 (Some(Sk::Float), _) | (_, Some(Sk::Float)) => match op {
3326 Bo::Modulo => BinaryOperation::Modulo,
3327 _ => BinaryOperation::Other,
3328 },
3329 (Some(Sk::Bool), Some(Sk::Bool)) => match op {
3330 Bo::InclusiveOr => {
3331 op = crate::BinaryOperator::LogicalOr;
3332 BinaryOperation::Other
3333 }
3334 Bo::And => {
3335 op = crate::BinaryOperator::LogicalAnd;
3336 BinaryOperation::Other
3337 }
3338 _ => BinaryOperation::Other,
3339 },
3340 _ => BinaryOperation::Other,
3341 },
3342 };
3343
3344 match function {
3345 BinaryOperation::VectorCompare => {
3346 let op_str = match op {
3347 Bo::Less => "lessThan(",
3348 Bo::LessEqual => "lessThanEqual(",
3349 Bo::Greater => "greaterThan(",
3350 Bo::GreaterEqual => "greaterThanEqual(",
3351 Bo::Equal => "equal(",
3352 Bo::NotEqual => "notEqual(",
3353 _ => unreachable!(),
3354 };
3355 write!(self.out, "{op_str}")?;
3356 self.write_expr(left, ctx)?;
3357 write!(self.out, ", ")?;
3358 self.write_expr(right, ctx)?;
3359 write!(self.out, ")")?;
3360 }
3361 BinaryOperation::VectorComponentWise => {
3362 self.write_value_type(left_inner)?;
3363 write!(self.out, "(")?;
3364
3365 let size = match *left_inner {
3366 Ti::Vector { size, .. } => size,
3367 _ => unreachable!(),
3368 };
3369
3370 for i in 0..size as usize {
3371 if i != 0 {
3372 write!(self.out, ", ")?;
3373 }
3374
3375 self.write_expr(left, ctx)?;
3376 write!(self.out, ".{}", back::COMPONENTS[i])?;
3377
3378 write!(self.out, " {} ", back::binary_operation_str(op))?;
3379
3380 self.write_expr(right, ctx)?;
3381 write!(self.out, ".{}", back::COMPONENTS[i])?;
3382 }
3383
3384 write!(self.out, ")")?;
3385 }
3386 // TODO: handle undefined behavior of BinaryOperator::Modulo
3387 //
3388 // sint:
3389 // if right == 0 return 0
3390 // if left == min(type_of(left)) && right == -1 return 0
3391 // if sign(left) == -1 || sign(right) == -1 return result as defined by WGSL
3392 //
3393 // uint:
3394 // if right == 0 return 0
3395 //
3396 // float:
3397 // if right == 0 return ? see https://github.com/gpuweb/gpuweb/issues/2798
3398 BinaryOperation::Modulo => {
3399 write!(self.out, "(")?;
3400
3401 // write `e1 - e2 * trunc(e1 / e2)`
3402 self.write_expr(left, ctx)?;
3403 write!(self.out, " - ")?;
3404 self.write_expr(right, ctx)?;
3405 write!(self.out, " * ")?;
3406 write!(self.out, "trunc(")?;
3407 self.write_expr(left, ctx)?;
3408 write!(self.out, " / ")?;
3409 self.write_expr(right, ctx)?;
3410 write!(self.out, ")")?;
3411
3412 write!(self.out, ")")?;
3413 }
3414 BinaryOperation::Other => {
3415 write!(self.out, "(")?;
3416
3417 self.write_expr(left, ctx)?;
3418 write!(self.out, " {} ", back::binary_operation_str(op))?;
3419 self.write_expr(right, ctx)?;
3420
3421 write!(self.out, ")")?;
3422 }
3423 }
3424 }
3425 // `Select` is written as `condition ? accept : reject`
3426 // We wrap everything in parentheses to avoid precedence issues
3427 Expression::Select {
3428 condition,
3429 accept,
3430 reject,
3431 } => {
3432 let cond_ty = ctx.resolve_type(condition, &self.module.types);
3433 let vec_select = if let TypeInner::Vector { .. } = *cond_ty {
3434 true
3435 } else {
3436 false
3437 };
3438
3439 // TODO: Boolean mix on desktop required GL_EXT_shader_integer_mix
3440 if vec_select {
3441 // Glsl defines that for mix when the condition is a boolean the first element
3442 // is picked if condition is false and the second if condition is true
3443 write!(self.out, "mix(")?;
3444 self.write_expr(reject, ctx)?;
3445 write!(self.out, ", ")?;
3446 self.write_expr(accept, ctx)?;
3447 write!(self.out, ", ")?;
3448 self.write_expr(condition, ctx)?;
3449 } else {
3450 write!(self.out, "(")?;
3451 self.write_expr(condition, ctx)?;
3452 write!(self.out, " ? ")?;
3453 self.write_expr(accept, ctx)?;
3454 write!(self.out, " : ")?;
3455 self.write_expr(reject, ctx)?;
3456 }
3457
3458 write!(self.out, ")")?
3459 }
3460 // `Derivative` is a function call to a glsl provided function
3461 Expression::Derivative { axis, ctrl, expr } => {
3462 use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl};
3463 let fun_name = if self.options.version.supports_derivative_control() {
3464 match (axis, ctrl) {
3465 (Axis::X, Ctrl::Coarse) => "dFdxCoarse",
3466 (Axis::X, Ctrl::Fine) => "dFdxFine",
3467 (Axis::X, Ctrl::None) => "dFdx",
3468 (Axis::Y, Ctrl::Coarse) => "dFdyCoarse",
3469 (Axis::Y, Ctrl::Fine) => "dFdyFine",
3470 (Axis::Y, Ctrl::None) => "dFdy",
3471 (Axis::Width, Ctrl::Coarse) => "fwidthCoarse",
3472 (Axis::Width, Ctrl::Fine) => "fwidthFine",
3473 (Axis::Width, Ctrl::None) => "fwidth",
3474 }
3475 } else {
3476 match axis {
3477 Axis::X => "dFdx",
3478 Axis::Y => "dFdy",
3479 Axis::Width => "fwidth",
3480 }
3481 };
3482 write!(self.out, "{fun_name}(")?;
3483 self.write_expr(expr, ctx)?;
3484 write!(self.out, ")")?
3485 }
3486 // `Relational` is a normal function call to some glsl provided functions
3487 Expression::Relational { fun, argument } => {
3488 use crate::RelationalFunction as Rf;
3489
3490 let fun_name = match fun {
3491 Rf::IsInf => "isinf",
3492 Rf::IsNan => "isnan",
3493 Rf::All => "all",
3494 Rf::Any => "any",
3495 };
3496 write!(self.out, "{fun_name}(")?;
3497
3498 self.write_expr(argument, ctx)?;
3499
3500 write!(self.out, ")")?
3501 }
3502 Expression::Math {
3503 fun,
3504 arg,
3505 arg1,
3506 arg2,
3507 arg3,
3508 } => {
3509 use crate::MathFunction as Mf;
3510
3511 let fun_name = match fun {
3512 // comparison
3513 Mf::Abs => "abs",
3514 Mf::Min => "min",
3515 Mf::Max => "max",
3516 Mf::Clamp => {
3517 let scalar_kind = ctx
3518 .resolve_type(arg, &self.module.types)
3519 .scalar_kind()
3520 .unwrap();
3521 match scalar_kind {
3522 crate::ScalarKind::Float => "clamp",
3523 // Clamp is undefined if min > max. In practice this means it can use a median-of-three
3524 // instruction to determine the value. This is fine according to the WGSL spec for float
3525 // clamp, but integer clamp _must_ use min-max. As such we write out min/max.
3526 _ => {
3527 write!(self.out, "min(max(")?;
3528 self.write_expr(arg, ctx)?;
3529 write!(self.out, ", ")?;
3530 self.write_expr(arg1.unwrap(), ctx)?;
3531 write!(self.out, "), ")?;
3532 self.write_expr(arg2.unwrap(), ctx)?;
3533 write!(self.out, ")")?;
3534
3535 return Ok(());
3536 }
3537 }
3538 }
3539 Mf::Saturate => {
3540 write!(self.out, "clamp(")?;
3541
3542 self.write_expr(arg, ctx)?;
3543
3544 match *ctx.resolve_type(arg, &self.module.types) {
3545 TypeInner::Vector { size, .. } => write!(
3546 self.out,
3547 ", vec{}(0.0), vec{0}(1.0)",
3548 common::vector_size_str(size)
3549 )?,
3550 _ => write!(self.out, ", 0.0, 1.0")?,
3551 }
3552
3553 write!(self.out, ")")?;
3554
3555 return Ok(());
3556 }
3557 // trigonometry
3558 Mf::Cos => "cos",
3559 Mf::Cosh => "cosh",
3560 Mf::Sin => "sin",
3561 Mf::Sinh => "sinh",
3562 Mf::Tan => "tan",
3563 Mf::Tanh => "tanh",
3564 Mf::Acos => "acos",
3565 Mf::Asin => "asin",
3566 Mf::Atan => "atan",
3567 Mf::Asinh => "asinh",
3568 Mf::Acosh => "acosh",
3569 Mf::Atanh => "atanh",
3570 Mf::Radians => "radians",
3571 Mf::Degrees => "degrees",
3572 // glsl doesn't have atan2 function
3573 // use two-argument variation of the atan function
3574 Mf::Atan2 => "atan",
3575 // decomposition
3576 Mf::Ceil => "ceil",
3577 Mf::Floor => "floor",
3578 Mf::Round => "roundEven",
3579 Mf::Fract => "fract",
3580 Mf::Trunc => "trunc",
3581 Mf::Modf => MODF_FUNCTION,
3582 Mf::Frexp => FREXP_FUNCTION,
3583 Mf::Ldexp => "ldexp",
3584 // exponent
3585 Mf::Exp => "exp",
3586 Mf::Exp2 => "exp2",
3587 Mf::Log => "log",
3588 Mf::Log2 => "log2",
3589 Mf::Pow => "pow",
3590 // geometry
3591 Mf::Dot => match *ctx.resolve_type(arg, &self.module.types) {
3592 TypeInner::Vector {
3593 scalar:
3594 crate::Scalar {
3595 kind: crate::ScalarKind::Float,
3596 ..
3597 },
3598 ..
3599 } => "dot",
3600 TypeInner::Vector { size, .. } => {
3601 return self.write_dot_product(arg, arg1.unwrap(), size as usize, ctx)
3602 }
3603 _ => unreachable!(
3604 "Correct TypeInner for dot product should be already validated"
3605 ),
3606 },
3607 fun @ (Mf::Dot4I8Packed | Mf::Dot4U8Packed) => {
3608 let conversion = match fun {
3609 Mf::Dot4I8Packed => "int",
3610 Mf::Dot4U8Packed => "",
3611 _ => unreachable!(),
3612 };
3613
3614 let arg1 = arg1.unwrap();
3615
3616 // Write parentheses around the dot product expression to prevent operators
3617 // with different precedences from applying earlier.
3618 write!(self.out, "(")?;
3619 for i in 0..4 {
3620 // Since `bitfieldExtract` only sign extends if the value is signed, we
3621 // need to convert the inputs to `int` in case of `Dot4I8Packed`. For
3622 // `Dot4U8Packed`, the code below only introduces parenthesis around
3623 // each factor, which aren't strictly needed because both operands are
3624 // baked, but which don't hurt either.
3625 write!(self.out, "bitfieldExtract({}(", conversion)?;
3626 self.write_expr(arg, ctx)?;
3627 write!(self.out, "), {}, 8)", i * 8)?;
3628
3629 write!(self.out, " * bitfieldExtract({}(", conversion)?;
3630 self.write_expr(arg1, ctx)?;
3631 write!(self.out, "), {}, 8)", i * 8)?;
3632
3633 if i != 3 {
3634 write!(self.out, " + ")?;
3635 }
3636 }
3637 write!(self.out, ")")?;
3638
3639 return Ok(());
3640 }
3641 Mf::Outer => "outerProduct",
3642 Mf::Cross => "cross",
3643 Mf::Distance => "distance",
3644 Mf::Length => "length",
3645 Mf::Normalize => "normalize",
3646 Mf::FaceForward => "faceforward",
3647 Mf::Reflect => "reflect",
3648 Mf::Refract => "refract",
3649 // computational
3650 Mf::Sign => "sign",
3651 Mf::Fma => {
3652 if self.options.version.supports_fma_function() {
3653 // Use the fma function when available
3654 "fma"
3655 } else {
3656 // No fma support. Transform the function call into an arithmetic expression
3657 write!(self.out, "(")?;
3658
3659 self.write_expr(arg, ctx)?;
3660 write!(self.out, " * ")?;
3661
3662 let arg1 =
3663 arg1.ok_or_else(|| Error::Custom("Missing fma arg1".to_owned()))?;
3664 self.write_expr(arg1, ctx)?;
3665 write!(self.out, " + ")?;
3666
3667 let arg2 =
3668 arg2.ok_or_else(|| Error::Custom("Missing fma arg2".to_owned()))?;
3669 self.write_expr(arg2, ctx)?;
3670 write!(self.out, ")")?;
3671
3672 return Ok(());
3673 }
3674 }
3675 Mf::Mix => "mix",
3676 Mf::Step => "step",
3677 Mf::SmoothStep => "smoothstep",
3678 Mf::Sqrt => "sqrt",
3679 Mf::InverseSqrt => "inversesqrt",
3680 Mf::Inverse => "inverse",
3681 Mf::Transpose => "transpose",
3682 Mf::Determinant => "determinant",
3683 Mf::QuantizeToF16 => match *ctx.resolve_type(arg, &self.module.types) {
3684 TypeInner::Scalar { .. } => {
3685 write!(self.out, "unpackHalf2x16(packHalf2x16(vec2(")?;
3686 self.write_expr(arg, ctx)?;
3687 write!(self.out, "))).x")?;
3688 return Ok(());
3689 }
3690 TypeInner::Vector {
3691 size: crate::VectorSize::Bi,
3692 ..
3693 } => {
3694 write!(self.out, "unpackHalf2x16(packHalf2x16(")?;
3695 self.write_expr(arg, ctx)?;
3696 write!(self.out, "))")?;
3697 return Ok(());
3698 }
3699 TypeInner::Vector {
3700 size: crate::VectorSize::Tri,
3701 ..
3702 } => {
3703 write!(self.out, "vec3(unpackHalf2x16(packHalf2x16(")?;
3704 self.write_expr(arg, ctx)?;
3705 write!(self.out, ".xy)), unpackHalf2x16(packHalf2x16(")?;
3706 self.write_expr(arg, ctx)?;
3707 write!(self.out, ".zz)).x)")?;
3708 return Ok(());
3709 }
3710 TypeInner::Vector {
3711 size: crate::VectorSize::Quad,
3712 ..
3713 } => {
3714 write!(self.out, "vec4(unpackHalf2x16(packHalf2x16(")?;
3715 self.write_expr(arg, ctx)?;
3716 write!(self.out, ".xy)), unpackHalf2x16(packHalf2x16(")?;
3717 self.write_expr(arg, ctx)?;
3718 write!(self.out, ".zw)))")?;
3719 return Ok(());
3720 }
3721 _ => unreachable!(
3722 "Correct TypeInner for QuantizeToF16 should be already validated"
3723 ),
3724 },
3725 // bits
3726 Mf::CountTrailingZeros => {
3727 match *ctx.resolve_type(arg, &self.module.types) {
3728 TypeInner::Vector { size, scalar, .. } => {
3729 let s = common::vector_size_str(size);
3730 if let crate::ScalarKind::Uint = scalar.kind {
3731 write!(self.out, "min(uvec{s}(findLSB(")?;
3732 self.write_expr(arg, ctx)?;
3733 write!(self.out, ")), uvec{s}(32u))")?;
3734 } else {
3735 write!(self.out, "ivec{s}(min(uvec{s}(findLSB(")?;
3736 self.write_expr(arg, ctx)?;
3737 write!(self.out, ")), uvec{s}(32u)))")?;
3738 }
3739 }
3740 TypeInner::Scalar(scalar) => {
3741 if let crate::ScalarKind::Uint = scalar.kind {
3742 write!(self.out, "min(uint(findLSB(")?;
3743 self.write_expr(arg, ctx)?;
3744 write!(self.out, ")), 32u)")?;
3745 } else {
3746 write!(self.out, "int(min(uint(findLSB(")?;
3747 self.write_expr(arg, ctx)?;
3748 write!(self.out, ")), 32u))")?;
3749 }
3750 }
3751 _ => unreachable!(),
3752 };
3753 return Ok(());
3754 }
3755 Mf::CountLeadingZeros => {
3756 if self.options.version.supports_integer_functions() {
3757 match *ctx.resolve_type(arg, &self.module.types) {
3758 TypeInner::Vector { size, scalar } => {
3759 let s = common::vector_size_str(size);
3760
3761 if let crate::ScalarKind::Uint = scalar.kind {
3762 write!(self.out, "uvec{s}(ivec{s}(31) - findMSB(")?;
3763 self.write_expr(arg, ctx)?;
3764 write!(self.out, "))")?;
3765 } else {
3766 write!(self.out, "mix(ivec{s}(31) - findMSB(")?;
3767 self.write_expr(arg, ctx)?;
3768 write!(self.out, "), ivec{s}(0), lessThan(")?;
3769 self.write_expr(arg, ctx)?;
3770 write!(self.out, ", ivec{s}(0)))")?;
3771 }
3772 }
3773 TypeInner::Scalar(scalar) => {
3774 if let crate::ScalarKind::Uint = scalar.kind {
3775 write!(self.out, "uint(31 - findMSB(")?;
3776 } else {
3777 write!(self.out, "(")?;
3778 self.write_expr(arg, ctx)?;
3779 write!(self.out, " < 0 ? 0 : 31 - findMSB(")?;
3780 }
3781
3782 self.write_expr(arg, ctx)?;
3783 write!(self.out, "))")?;
3784 }
3785 _ => unreachable!(),
3786 };
3787 } else {
3788 match *ctx.resolve_type(arg, &self.module.types) {
3789 TypeInner::Vector { size, scalar } => {
3790 let s = common::vector_size_str(size);
3791
3792 if let crate::ScalarKind::Uint = scalar.kind {
3793 write!(self.out, "uvec{s}(")?;
3794 write!(self.out, "vec{s}(31.0) - floor(log2(vec{s}(")?;
3795 self.write_expr(arg, ctx)?;
3796 write!(self.out, ") + 0.5)))")?;
3797 } else {
3798 write!(self.out, "ivec{s}(")?;
3799 write!(self.out, "mix(vec{s}(31.0) - floor(log2(vec{s}(")?;
3800 self.write_expr(arg, ctx)?;
3801 write!(self.out, ") + 0.5)), ")?;
3802 write!(self.out, "vec{s}(0.0), lessThan(")?;
3803 self.write_expr(arg, ctx)?;
3804 write!(self.out, ", ivec{s}(0u))))")?;
3805 }
3806 }
3807 TypeInner::Scalar(scalar) => {
3808 if let crate::ScalarKind::Uint = scalar.kind {
3809 write!(self.out, "uint(31.0 - floor(log2(float(")?;
3810 self.write_expr(arg, ctx)?;
3811 write!(self.out, ") + 0.5)))")?;
3812 } else {
3813 write!(self.out, "(")?;
3814 self.write_expr(arg, ctx)?;
3815 write!(self.out, " < 0 ? 0 : int(")?;
3816 write!(self.out, "31.0 - floor(log2(float(")?;
3817 self.write_expr(arg, ctx)?;
3818 write!(self.out, ") + 0.5))))")?;
3819 }
3820 }
3821 _ => unreachable!(),
3822 };
3823 }
3824
3825 return Ok(());
3826 }
3827 Mf::CountOneBits => "bitCount",
3828 Mf::ReverseBits => "bitfieldReverse",
3829 Mf::ExtractBits => {
3830 // The behavior of ExtractBits is undefined when offset + count > bit_width. We need
3831 // to first sanitize the offset and count first. If we don't do this, AMD and Intel chips
3832 // will return out-of-spec values if the extracted range is not within the bit width.
3833 //
3834 // This encodes the exact formula specified by the wgsl spec, without temporary values:
3835 // https://gpuweb.github.io/gpuweb/wgsl/#extractBits-unsigned-builtin
3836 //
3837 // w = sizeof(x) * 8
3838 // o = min(offset, w)
3839 // c = min(count, w - o)
3840 //
3841 // bitfieldExtract(x, o, c)
3842 //
3843 // extract_bits(e, min(offset, w), min(count, w - min(offset, w))))
3844 let scalar_bits = ctx
3845 .resolve_type(arg, &self.module.types)
3846 .scalar_width()
3847 .unwrap()
3848 * 8;
3849
3850 write!(self.out, "bitfieldExtract(")?;
3851 self.write_expr(arg, ctx)?;
3852 write!(self.out, ", int(min(")?;
3853 self.write_expr(arg1.unwrap(), ctx)?;
3854 write!(self.out, ", {scalar_bits}u)), int(min(",)?;
3855 self.write_expr(arg2.unwrap(), ctx)?;
3856 write!(self.out, ", {scalar_bits}u - min(")?;
3857 self.write_expr(arg1.unwrap(), ctx)?;
3858 write!(self.out, ", {scalar_bits}u))))")?;
3859
3860 return Ok(());
3861 }
3862 Mf::InsertBits => {
3863 // InsertBits has the same considerations as ExtractBits above
3864 let scalar_bits = ctx
3865 .resolve_type(arg, &self.module.types)
3866 .scalar_width()
3867 .unwrap()
3868 * 8;
3869
3870 write!(self.out, "bitfieldInsert(")?;
3871 self.write_expr(arg, ctx)?;
3872 write!(self.out, ", ")?;
3873 self.write_expr(arg1.unwrap(), ctx)?;
3874 write!(self.out, ", int(min(")?;
3875 self.write_expr(arg2.unwrap(), ctx)?;
3876 write!(self.out, ", {scalar_bits}u)), int(min(",)?;
3877 self.write_expr(arg3.unwrap(), ctx)?;
3878 write!(self.out, ", {scalar_bits}u - min(")?;
3879 self.write_expr(arg2.unwrap(), ctx)?;
3880 write!(self.out, ", {scalar_bits}u))))")?;
3881
3882 return Ok(());
3883 }
3884 Mf::FirstTrailingBit => "findLSB",
3885 Mf::FirstLeadingBit => "findMSB",
3886 // data packing
3887 Mf::Pack4x8snorm => {
3888 if self.options.version.supports_pack_unpack_4x8() {
3889 "packSnorm4x8"
3890 } else {
3891 // polyfill should go here. Needs a corresponding entry in `need_bake_expression`
3892 return Err(Error::UnsupportedExternal("packSnorm4x8".into()));
3893 }
3894 }
3895 Mf::Pack4x8unorm => {
3896 if self.options.version.supports_pack_unpack_4x8() {
3897 "packUnorm4x8"
3898 } else {
3899 return Err(Error::UnsupportedExternal("packUnorm4x8".to_owned()));
3900 }
3901 }
3902 Mf::Pack2x16snorm => {
3903 if self.options.version.supports_pack_unpack_snorm_2x16() {
3904 "packSnorm2x16"
3905 } else {
3906 return Err(Error::UnsupportedExternal("packSnorm2x16".to_owned()));
3907 }
3908 }
3909 Mf::Pack2x16unorm => {
3910 if self.options.version.supports_pack_unpack_unorm_2x16() {
3911 "packUnorm2x16"
3912 } else {
3913 return Err(Error::UnsupportedExternal("packUnorm2x16".to_owned()));
3914 }
3915 }
3916 Mf::Pack2x16float => {
3917 if self.options.version.supports_pack_unpack_half_2x16() {
3918 "packHalf2x16"
3919 } else {
3920 return Err(Error::UnsupportedExternal("packHalf2x16".to_owned()));
3921 }
3922 }
3923
3924 fun @ (Mf::Pack4xI8 | Mf::Pack4xU8 | Mf::Pack4xI8Clamp | Mf::Pack4xU8Clamp) => {
3925 let was_signed = matches!(fun, Mf::Pack4xI8 | Mf::Pack4xI8Clamp);
3926 let clamp_bounds = match fun {
3927 Mf::Pack4xI8Clamp => Some(("-128", "127")),
3928 Mf::Pack4xU8Clamp => Some(("0", "255")),
3929 _ => None,
3930 };
3931 let const_suffix = if was_signed { "" } else { "u" };
3932 if was_signed {
3933 write!(self.out, "uint(")?;
3934 }
3935 let write_arg = |this: &mut Self| -> BackendResult {
3936 if let Some((min, max)) = clamp_bounds {
3937 write!(this.out, "clamp(")?;
3938 this.write_expr(arg, ctx)?;
3939 write!(this.out, ", {min}{const_suffix}, {max}{const_suffix})")?;
3940 } else {
3941 this.write_expr(arg, ctx)?;
3942 }
3943 Ok(())
3944 };
3945 write!(self.out, "(")?;
3946 write_arg(self)?;
3947 write!(self.out, "[0] & 0xFF{const_suffix}) | ((")?;
3948 write_arg(self)?;
3949 write!(self.out, "[1] & 0xFF{const_suffix}) << 8) | ((")?;
3950 write_arg(self)?;
3951 write!(self.out, "[2] & 0xFF{const_suffix}) << 16) | ((")?;
3952 write_arg(self)?;
3953 write!(self.out, "[3] & 0xFF{const_suffix}) << 24)")?;
3954 if was_signed {
3955 write!(self.out, ")")?;
3956 }
3957
3958 return Ok(());
3959 }
3960 // data unpacking
3961 Mf::Unpack2x16float => {
3962 if self.options.version.supports_pack_unpack_half_2x16() {
3963 "unpackHalf2x16"
3964 } else {
3965 return Err(Error::UnsupportedExternal("unpackHalf2x16".into()));
3966 }
3967 }
3968 Mf::Unpack2x16snorm => {
3969 if self.options.version.supports_pack_unpack_snorm_2x16() {
3970 "unpackSnorm2x16"
3971 } else {
3972 let scale = 32767;
3973
3974 write!(self.out, "(vec2(ivec2(")?;
3975 self.write_expr(arg, ctx)?;
3976 write!(self.out, " << 16, ")?;
3977 self.write_expr(arg, ctx)?;
3978 write!(self.out, ") >> 16) / {scale}.0)")?;
3979 return Ok(());
3980 }
3981 }
3982 Mf::Unpack2x16unorm => {
3983 if self.options.version.supports_pack_unpack_unorm_2x16() {
3984 "unpackUnorm2x16"
3985 } else {
3986 let scale = 65535;
3987
3988 write!(self.out, "(vec2(")?;
3989 self.write_expr(arg, ctx)?;
3990 write!(self.out, " & 0xFFFFu, ")?;
3991 self.write_expr(arg, ctx)?;
3992 write!(self.out, " >> 16) / {scale}.0)")?;
3993 return Ok(());
3994 }
3995 }
3996 Mf::Unpack4x8snorm => {
3997 if self.options.version.supports_pack_unpack_4x8() {
3998 "unpackSnorm4x8"
3999 } else {
4000 let scale = 127;
4001
4002 write!(self.out, "(vec4(ivec4(")?;
4003 self.write_expr(arg, ctx)?;
4004 write!(self.out, " << 24, ")?;
4005 self.write_expr(arg, ctx)?;
4006 write!(self.out, " << 16, ")?;
4007 self.write_expr(arg, ctx)?;
4008 write!(self.out, " << 8, ")?;
4009 self.write_expr(arg, ctx)?;
4010 write!(self.out, ") >> 24) / {scale}.0)")?;
4011 return Ok(());
4012 }
4013 }
4014 Mf::Unpack4x8unorm => {
4015 if self.options.version.supports_pack_unpack_4x8() {
4016 "unpackUnorm4x8"
4017 } else {
4018 let scale = 255;
4019
4020 write!(self.out, "(vec4(")?;
4021 self.write_expr(arg, ctx)?;
4022 write!(self.out, " & 0xFFu, ")?;
4023 self.write_expr(arg, ctx)?;
4024 write!(self.out, " >> 8 & 0xFFu, ")?;
4025 self.write_expr(arg, ctx)?;
4026 write!(self.out, " >> 16 & 0xFFu, ")?;
4027 self.write_expr(arg, ctx)?;
4028 write!(self.out, " >> 24) / {scale}.0)")?;
4029 return Ok(());
4030 }
4031 }
4032 fun @ (Mf::Unpack4xI8 | Mf::Unpack4xU8) => {
4033 let sign_prefix = match fun {
4034 Mf::Unpack4xI8 => 'i',
4035 Mf::Unpack4xU8 => 'u',
4036 _ => unreachable!(),
4037 };
4038 write!(self.out, "{sign_prefix}vec4(")?;
4039 for i in 0..4 {
4040 write!(self.out, "bitfieldExtract(")?;
4041 // Since bitfieldExtract only sign extends if the value is signed, this
4042 // cast is needed
4043 match fun {
4044 Mf::Unpack4xI8 => {
4045 write!(self.out, "int(")?;
4046 self.write_expr(arg, ctx)?;
4047 write!(self.out, ")")?;
4048 }
4049 Mf::Unpack4xU8 => self.write_expr(arg, ctx)?,
4050 _ => unreachable!(),
4051 };
4052 write!(self.out, ", {}, 8)", i * 8)?;
4053 if i != 3 {
4054 write!(self.out, ", ")?;
4055 }
4056 }
4057 write!(self.out, ")")?;
4058
4059 return Ok(());
4060 }
4061 };
4062
4063 let extract_bits = fun == Mf::ExtractBits;
4064 let insert_bits = fun == Mf::InsertBits;
4065
4066 // Some GLSL functions always return signed integers (like findMSB),
4067 // so they need to be cast to uint if the argument is also an uint.
4068 let ret_might_need_int_to_uint = matches!(
4069 fun,
4070 Mf::FirstTrailingBit | Mf::FirstLeadingBit | Mf::CountOneBits | Mf::Abs
4071 );
4072
4073 // Some GLSL functions only accept signed integers (like abs),
4074 // so they need their argument cast from uint to int.
4075 let arg_might_need_uint_to_int = matches!(fun, Mf::Abs);
4076
4077 // Check if the argument is an unsigned integer and return the vector size
4078 // in case it's a vector
4079 let maybe_uint_size = match *ctx.resolve_type(arg, &self.module.types) {
4080 TypeInner::Scalar(crate::Scalar {
4081 kind: crate::ScalarKind::Uint,
4082 ..
4083 }) => Some(None),
4084 TypeInner::Vector {
4085 scalar:
4086 crate::Scalar {
4087 kind: crate::ScalarKind::Uint,
4088 ..
4089 },
4090 size,
4091 } => Some(Some(size)),
4092 _ => None,
4093 };
4094
4095 // Cast to uint if the function needs it
4096 if ret_might_need_int_to_uint {
4097 if let Some(maybe_size) = maybe_uint_size {
4098 match maybe_size {
4099 Some(size) => write!(self.out, "uvec{}(", size as u8)?,
4100 None => write!(self.out, "uint(")?,
4101 }
4102 }
4103 }
4104
4105 write!(self.out, "{fun_name}(")?;
4106
4107 // Cast to int if the function needs it
4108 if arg_might_need_uint_to_int {
4109 if let Some(maybe_size) = maybe_uint_size {
4110 match maybe_size {
4111 Some(size) => write!(self.out, "ivec{}(", size as u8)?,
4112 None => write!(self.out, "int(")?,
4113 }
4114 }
4115 }
4116
4117 self.write_expr(arg, ctx)?;
4118
4119 // Close the cast from uint to int
4120 if arg_might_need_uint_to_int && maybe_uint_size.is_some() {
4121 write!(self.out, ")")?
4122 }
4123
4124 if let Some(arg) = arg1 {
4125 write!(self.out, ", ")?;
4126 if extract_bits {
4127 write!(self.out, "int(")?;
4128 self.write_expr(arg, ctx)?;
4129 write!(self.out, ")")?;
4130 } else {
4131 self.write_expr(arg, ctx)?;
4132 }
4133 }
4134 if let Some(arg) = arg2 {
4135 write!(self.out, ", ")?;
4136 if extract_bits || insert_bits {
4137 write!(self.out, "int(")?;
4138 self.write_expr(arg, ctx)?;
4139 write!(self.out, ")")?;
4140 } else {
4141 self.write_expr(arg, ctx)?;
4142 }
4143 }
4144 if let Some(arg) = arg3 {
4145 write!(self.out, ", ")?;
4146 if insert_bits {
4147 write!(self.out, "int(")?;
4148 self.write_expr(arg, ctx)?;
4149 write!(self.out, ")")?;
4150 } else {
4151 self.write_expr(arg, ctx)?;
4152 }
4153 }
4154 write!(self.out, ")")?;
4155
4156 // Close the cast from int to uint
4157 if ret_might_need_int_to_uint && maybe_uint_size.is_some() {
4158 write!(self.out, ")")?
4159 }
4160 }
4161 // `As` is always a call.
4162 // If `convert` is true the function name is the type
4163 // Else the function name is one of the glsl provided bitcast functions
4164 Expression::As {
4165 expr,
4166 kind: target_kind,
4167 convert,
4168 } => {
4169 let inner = ctx.resolve_type(expr, &self.module.types);
4170 match convert {
4171 Some(width) => {
4172 // this is similar to `write_type`, but with the target kind
4173 let scalar = glsl_scalar(crate::Scalar {
4174 kind: target_kind,
4175 width,
4176 })?;
4177 match *inner {
4178 TypeInner::Matrix { columns, rows, .. } => write!(
4179 self.out,
4180 "{}mat{}x{}",
4181 scalar.prefix, columns as u8, rows as u8
4182 )?,
4183 TypeInner::Vector { size, .. } => {
4184 write!(self.out, "{}vec{}", scalar.prefix, size as u8)?
4185 }
4186 _ => write!(self.out, "{}", scalar.full)?,
4187 }
4188
4189 write!(self.out, "(")?;
4190 self.write_expr(expr, ctx)?;
4191 write!(self.out, ")")?
4192 }
4193 None => {
4194 use crate::ScalarKind as Sk;
4195
4196 let target_vector_type = match *inner {
4197 TypeInner::Vector { size, scalar } => Some(TypeInner::Vector {
4198 size,
4199 scalar: crate::Scalar {
4200 kind: target_kind,
4201 width: scalar.width,
4202 },
4203 }),
4204 _ => None,
4205 };
4206
4207 let source_kind = inner.scalar_kind().unwrap();
4208
4209 match (source_kind, target_kind, target_vector_type) {
4210 // No conversion needed
4211 (Sk::Sint, Sk::Sint, _)
4212 | (Sk::Uint, Sk::Uint, _)
4213 | (Sk::Float, Sk::Float, _)
4214 | (Sk::Bool, Sk::Bool, _) => {
4215 self.write_expr(expr, ctx)?;
4216 return Ok(());
4217 }
4218
4219 // Cast to/from floats
4220 (Sk::Float, Sk::Sint, _) => write!(self.out, "floatBitsToInt")?,
4221 (Sk::Float, Sk::Uint, _) => write!(self.out, "floatBitsToUint")?,
4222 (Sk::Sint, Sk::Float, _) => write!(self.out, "intBitsToFloat")?,
4223 (Sk::Uint, Sk::Float, _) => write!(self.out, "uintBitsToFloat")?,
4224
4225 // Cast between vector types
4226 (_, _, Some(vector)) => {
4227 self.write_value_type(&vector)?;
4228 }
4229
4230 // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion
4231 (Sk::Uint | Sk::Bool, Sk::Sint, None) => write!(self.out, "int")?,
4232 (Sk::Sint | Sk::Bool, Sk::Uint, None) => write!(self.out, "uint")?,
4233 (Sk::Bool, Sk::Float, None) => write!(self.out, "float")?,
4234 (Sk::Sint | Sk::Uint | Sk::Float, Sk::Bool, None) => {
4235 write!(self.out, "bool")?
4236 }
4237
4238 (Sk::AbstractInt | Sk::AbstractFloat, _, _)
4239 | (_, Sk::AbstractInt | Sk::AbstractFloat, _) => unreachable!(),
4240 };
4241
4242 write!(self.out, "(")?;
4243 self.write_expr(expr, ctx)?;
4244 write!(self.out, ")")?;
4245 }
4246 }
4247 }
4248 // These expressions never show up in `Emit`.
4249 Expression::CallResult(_)
4250 | Expression::AtomicResult { .. }
4251 | Expression::RayQueryProceedResult
4252 | Expression::WorkGroupUniformLoadResult { .. }
4253 | Expression::SubgroupOperationResult { .. }
4254 | Expression::SubgroupBallotResult => unreachable!(),
4255 // `ArrayLength` is written as `expr.length()` and we convert it to a uint
4256 Expression::ArrayLength(expr) => {
4257 write!(self.out, "uint(")?;
4258 self.write_expr(expr, ctx)?;
4259 write!(self.out, ".length())")?
4260 }
4261 // not supported yet
4262 Expression::RayQueryGetIntersection { .. }
4263 | Expression::RayQueryVertexPositions { .. } => unreachable!(),
4264 }
4265
4266 Ok(())
4267 }
4268
4269 /// Helper function to write the local holding the clamped lod
4270 fn write_clamped_lod(
4271 &mut self,
4272 ctx: &back::FunctionCtx,
4273 expr: Handle<crate::Expression>,
4274 image: Handle<crate::Expression>,
4275 level_expr: Handle<crate::Expression>,
4276 ) -> Result<(), Error> {
4277 // Define our local and start a call to `clamp`
4278 write!(
4279 self.out,
4280 "int {}{} = clamp(",
4281 Baked(expr),
4282 CLAMPED_LOD_SUFFIX
4283 )?;
4284 // Write the lod that will be clamped
4285 self.write_expr(level_expr, ctx)?;
4286 // Set the min value to 0 and start a call to `textureQueryLevels` to get
4287 // the maximum value
4288 write!(self.out, ", 0, textureQueryLevels(")?;
4289 // Write the target image as an argument to `textureQueryLevels`
4290 self.write_expr(image, ctx)?;
4291 // Close the call to `textureQueryLevels` subtract 1 from it since
4292 // the lod argument is 0 based, close the `clamp` call and end the
4293 // local declaration statement.
4294 writeln!(self.out, ") - 1);")?;
4295
4296 Ok(())
4297 }
4298
4299 // Helper method used to retrieve how many elements a coordinate vector
4300 // for the images operations need.
4301 fn get_coordinate_vector_size(&self, dim: crate::ImageDimension, arrayed: bool) -> u8 {
4302 // openGL es doesn't have 1D images so we need workaround it
4303 let tex_1d_hack = dim == crate::ImageDimension::D1 && self.options.version.is_es();
4304 // Get how many components the coordinate vector needs for the dimensions only
4305 let tex_coord_size = match dim {
4306 crate::ImageDimension::D1 => 1,
4307 crate::ImageDimension::D2 => 2,
4308 crate::ImageDimension::D3 => 3,
4309 crate::ImageDimension::Cube => 2,
4310 };
4311 // Calculate the true size of the coordinate vector by adding 1 for arrayed images
4312 // and another 1 if we need to workaround 1D images by making them 2D
4313 tex_coord_size + tex_1d_hack as u8 + arrayed as u8
4314 }
4315
4316 /// Helper method to write the coordinate vector for image operations
4317 fn write_texture_coord(
4318 &mut self,
4319 ctx: &back::FunctionCtx,
4320 vector_size: u8,
4321 coordinate: Handle<crate::Expression>,
4322 array_index: Option<Handle<crate::Expression>>,
4323 // Emulate 1D images as 2D for profiles that don't support it (glsl es)
4324 tex_1d_hack: bool,
4325 ) -> Result<(), Error> {
4326 match array_index {
4327 // If the image needs an array indice we need to add it to the end of our
4328 // coordinate vector, to do so we will use the `ivec(ivec, scalar)`
4329 // constructor notation (NOTE: the inner `ivec` can also be a scalar, this
4330 // is important for 1D arrayed images).
4331 Some(layer_expr) => {
4332 write!(self.out, "ivec{vector_size}(")?;
4333 self.write_expr(coordinate, ctx)?;
4334 write!(self.out, ", ")?;
4335 // If we are replacing sampler1D with sampler2D we also need
4336 // to add another zero to the coordinates vector for the y component
4337 if tex_1d_hack {
4338 write!(self.out, "0, ")?;
4339 }
4340 self.write_expr(layer_expr, ctx)?;
4341 write!(self.out, ")")?;
4342 }
4343 // Otherwise write just the expression (and the 1D hack if needed)
4344 None => {
4345 let uvec_size = match *ctx.resolve_type(coordinate, &self.module.types) {
4346 TypeInner::Scalar(crate::Scalar {
4347 kind: crate::ScalarKind::Uint,
4348 ..
4349 }) => Some(None),
4350 TypeInner::Vector {
4351 size,
4352 scalar:
4353 crate::Scalar {
4354 kind: crate::ScalarKind::Uint,
4355 ..
4356 },
4357 } => Some(Some(size as u32)),
4358 _ => None,
4359 };
4360 if tex_1d_hack {
4361 write!(self.out, "ivec2(")?;
4362 } else if uvec_size.is_some() {
4363 match uvec_size {
4364 Some(None) => write!(self.out, "int(")?,
4365 Some(Some(size)) => write!(self.out, "ivec{size}(")?,
4366 _ => {}
4367 }
4368 }
4369 self.write_expr(coordinate, ctx)?;
4370 if tex_1d_hack {
4371 write!(self.out, ", 0)")?;
4372 } else if uvec_size.is_some() {
4373 write!(self.out, ")")?;
4374 }
4375 }
4376 }
4377
4378 Ok(())
4379 }
4380
4381 /// Helper method to write the `ImageStore` statement
4382 fn write_image_store(
4383 &mut self,
4384 ctx: &back::FunctionCtx,
4385 image: Handle<crate::Expression>,
4386 coordinate: Handle<crate::Expression>,
4387 array_index: Option<Handle<crate::Expression>>,
4388 value: Handle<crate::Expression>,
4389 ) -> Result<(), Error> {
4390 use crate::ImageDimension as IDim;
4391
4392 // NOTE: openGL requires that `imageStore`s have no effects when the texel is invalid
4393 // so we don't need to generate bounds checks (OpenGL 4.2 Core §3.9.20)
4394
4395 // This will only panic if the module is invalid
4396 let dim = match *ctx.resolve_type(image, &self.module.types) {
4397 TypeInner::Image { dim, .. } => dim,
4398 _ => unreachable!(),
4399 };
4400
4401 // Begin our call to `imageStore`
4402 write!(self.out, "imageStore(")?;
4403 self.write_expr(image, ctx)?;
4404 // Separate the image argument from the coordinates
4405 write!(self.out, ", ")?;
4406
4407 // openGL es doesn't have 1D images so we need workaround it
4408 let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es();
4409 // Write the coordinate vector
4410 self.write_texture_coord(
4411 ctx,
4412 // Get the size of the coordinate vector
4413 self.get_coordinate_vector_size(dim, array_index.is_some()),
4414 coordinate,
4415 array_index,
4416 tex_1d_hack,
4417 )?;
4418
4419 // Separate the coordinate from the value to write and write the expression
4420 // of the value to write.
4421 write!(self.out, ", ")?;
4422 self.write_expr(value, ctx)?;
4423 // End the call to `imageStore` and the statement.
4424 writeln!(self.out, ");")?;
4425
4426 Ok(())
4427 }
4428
4429 /// Helper method to write the `ImageAtomic` statement
4430 fn write_image_atomic(
4431 &mut self,
4432 ctx: &back::FunctionCtx,
4433 image: Handle<crate::Expression>,
4434 coordinate: Handle<crate::Expression>,
4435 array_index: Option<Handle<crate::Expression>>,
4436 fun: crate::AtomicFunction,
4437 value: Handle<crate::Expression>,
4438 ) -> Result<(), Error> {
4439 use crate::ImageDimension as IDim;
4440
4441 // NOTE: openGL requires that `imageAtomic`s have no effects when the texel is invalid
4442 // so we don't need to generate bounds checks (OpenGL 4.2 Core §3.9.20)
4443
4444 // This will only panic if the module is invalid
4445 let dim = match *ctx.resolve_type(image, &self.module.types) {
4446 TypeInner::Image { dim, .. } => dim,
4447 _ => unreachable!(),
4448 };
4449
4450 // Begin our call to `imageAtomic`
4451 let fun_str = fun.to_glsl();
4452 write!(self.out, "imageAtomic{fun_str}(")?;
4453 self.write_expr(image, ctx)?;
4454 // Separate the image argument from the coordinates
4455 write!(self.out, ", ")?;
4456
4457 // openGL es doesn't have 1D images so we need workaround it
4458 let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es();
4459 // Write the coordinate vector
4460 self.write_texture_coord(
4461 ctx,
4462 // Get the size of the coordinate vector
4463 self.get_coordinate_vector_size(dim, false),
4464 coordinate,
4465 array_index,
4466 tex_1d_hack,
4467 )?;
4468
4469 // Separate the coordinate from the value to write and write the expression
4470 // of the value to write.
4471 write!(self.out, ", ")?;
4472 self.write_expr(value, ctx)?;
4473 // End the call to `imageAtomic` and the statement.
4474 writeln!(self.out, ");")?;
4475
4476 Ok(())
4477 }
4478
4479 /// Helper method for writing an `ImageLoad` expression.
4480 #[allow(clippy::too_many_arguments)]
4481 fn write_image_load(
4482 &mut self,
4483 handle: Handle<crate::Expression>,
4484 ctx: &back::FunctionCtx,
4485 image: Handle<crate::Expression>,
4486 coordinate: Handle<crate::Expression>,
4487 array_index: Option<Handle<crate::Expression>>,
4488 sample: Option<Handle<crate::Expression>>,
4489 level: Option<Handle<crate::Expression>>,
4490 ) -> Result<(), Error> {
4491 use crate::ImageDimension as IDim;
4492
4493 // `ImageLoad` is a bit complicated.
4494 // There are two functions one for sampled
4495 // images another for storage images, the former uses `texelFetch` and the
4496 // latter uses `imageLoad`.
4497 //
4498 // Furthermore we have `level` which is always `Some` for sampled images
4499 // and `None` for storage images, so we end up with two functions:
4500 // - `texelFetch(image, coordinate, level)` for sampled images
4501 // - `imageLoad(image, coordinate)` for storage images
4502 //
4503 // Finally we also have to consider bounds checking, for storage images
4504 // this is easy since openGL requires that invalid texels always return
4505 // 0, for sampled images we need to either verify that all arguments are
4506 // in bounds (`ReadZeroSkipWrite`) or make them a valid texel (`Restrict`).
4507
4508 // This will only panic if the module is invalid
4509 let (dim, class) = match *ctx.resolve_type(image, &self.module.types) {
4510 TypeInner::Image {
4511 dim,
4512 arrayed: _,
4513 class,
4514 } => (dim, class),
4515 _ => unreachable!(),
4516 };
4517
4518 // Get the name of the function to be used for the load operation
4519 // and the policy to be used with it.
4520 let (fun_name, policy) = match class {
4521 // Sampled images inherit the policy from the user passed policies
4522 crate::ImageClass::Sampled { .. } => ("texelFetch", self.policies.image_load),
4523 crate::ImageClass::Storage { .. } => {
4524 // OpenGL ES 3.1 mentions in Chapter "8.22 Texture Image Loads and Stores" that:
4525 // "Invalid image loads will return a vector where the value of R, G, and B components
4526 // is 0 and the value of the A component is undefined."
4527 //
4528 // OpenGL 4.2 Core mentions in Chapter "3.9.20 Texture Image Loads and Stores" that:
4529 // "Invalid image loads will return zero."
4530 //
4531 // So, we only inject bounds checks for ES
4532 let policy = if self.options.version.is_es() {
4533 self.policies.image_load
4534 } else {
4535 proc::BoundsCheckPolicy::Unchecked
4536 };
4537 ("imageLoad", policy)
4538 }
4539 // TODO: Is there even a function for this?
4540 crate::ImageClass::Depth { multi: _ } => {
4541 return Err(Error::Custom(
4542 "WGSL `textureLoad` from depth textures is not supported in GLSL".to_string(),
4543 ))
4544 }
4545 };
4546
4547 // openGL es doesn't have 1D images so we need workaround it
4548 let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es();
4549 // Get the size of the coordinate vector
4550 let vector_size = self.get_coordinate_vector_size(dim, array_index.is_some());
4551
4552 if let proc::BoundsCheckPolicy::ReadZeroSkipWrite = policy {
4553 // To write the bounds checks for `ReadZeroSkipWrite` we will use a
4554 // ternary operator since we are in the middle of an expression and
4555 // need to return a value.
4556 //
4557 // NOTE: glsl does short circuit when evaluating logical
4558 // expressions so we can be sure that after we test a
4559 // condition it will be true for the next ones
4560
4561 // Write parentheses around the ternary operator to prevent problems with
4562 // expressions emitted before or after it having more precedence
4563 write!(self.out, "(",)?;
4564
4565 // The lod check needs to precede the size check since we need
4566 // to use the lod to get the size of the image at that level.
4567 if let Some(level_expr) = level {
4568 self.write_expr(level_expr, ctx)?;
4569 write!(self.out, " < textureQueryLevels(",)?;
4570 self.write_expr(image, ctx)?;
4571 // Chain the next check
4572 write!(self.out, ") && ")?;
4573 }
4574
4575 // Check that the sample arguments doesn't exceed the number of samples
4576 if let Some(sample_expr) = sample {
4577 self.write_expr(sample_expr, ctx)?;
4578 write!(self.out, " < textureSamples(",)?;
4579 self.write_expr(image, ctx)?;
4580 // Chain the next check
4581 write!(self.out, ") && ")?;
4582 }
4583
4584 // We now need to write the size checks for the coordinates and array index
4585 // first we write the comparison function in case the image is 1D non arrayed
4586 // (and no 1D to 2D hack was needed) we are comparing scalars so the less than
4587 // operator will suffice, but otherwise we'll be comparing two vectors so we'll
4588 // need to use the `lessThan` function but it returns a vector of booleans (one
4589 // for each comparison) so we need to fold it all in one scalar boolean, since
4590 // we want all comparisons to pass we use the `all` function which will only
4591 // return `true` if all the elements of the boolean vector are also `true`.
4592 //
4593 // So we'll end with one of the following forms
4594 // - `coord < textureSize(image, lod)` for 1D images
4595 // - `all(lessThan(coord, textureSize(image, lod)))` for normal images
4596 // - `all(lessThan(ivec(coord, array_index), textureSize(image, lod)))`
4597 // for arrayed images
4598 // - `all(lessThan(coord, textureSize(image)))` for multi sampled images
4599
4600 if vector_size != 1 {
4601 write!(self.out, "all(lessThan(")?;
4602 }
4603
4604 // Write the coordinate vector
4605 self.write_texture_coord(ctx, vector_size, coordinate, array_index, tex_1d_hack)?;
4606
4607 if vector_size != 1 {
4608 // If we used the `lessThan` function we need to separate the
4609 // coordinates from the image size.
4610 write!(self.out, ", ")?;
4611 } else {
4612 // If we didn't use it (ie. 1D images) we perform the comparison
4613 // using the less than operator.
4614 write!(self.out, " < ")?;
4615 }
4616
4617 // Call `textureSize` to get our image size
4618 write!(self.out, "textureSize(")?;
4619 self.write_expr(image, ctx)?;
4620 // `textureSize` uses the lod as a second argument for mipmapped images
4621 if let Some(level_expr) = level {
4622 // Separate the image from the lod
4623 write!(self.out, ", ")?;
4624 self.write_expr(level_expr, ctx)?;
4625 }
4626 // Close the `textureSize` call
4627 write!(self.out, ")")?;
4628
4629 if vector_size != 1 {
4630 // Close the `all` and `lessThan` calls
4631 write!(self.out, "))")?;
4632 }
4633
4634 // Finally end the condition part of the ternary operator
4635 write!(self.out, " ? ")?;
4636 }
4637
4638 // Begin the call to the function used to load the texel
4639 write!(self.out, "{fun_name}(")?;
4640 self.write_expr(image, ctx)?;
4641 write!(self.out, ", ")?;
4642
4643 // If we are using `Restrict` bounds checking we need to pass valid texel
4644 // coordinates, to do so we use the `clamp` function to get a value between
4645 // 0 and the image size - 1 (indexing begins at 0)
4646 if let proc::BoundsCheckPolicy::Restrict = policy {
4647 write!(self.out, "clamp(")?;
4648 }
4649
4650 // Write the coordinate vector
4651 self.write_texture_coord(ctx, vector_size, coordinate, array_index, tex_1d_hack)?;
4652
4653 // If we are using `Restrict` bounds checking we need to write the rest of the
4654 // clamp we initiated before writing the coordinates.
4655 if let proc::BoundsCheckPolicy::Restrict = policy {
4656 // Write the min value 0
4657 if vector_size == 1 {
4658 write!(self.out, ", 0")?;
4659 } else {
4660 write!(self.out, ", ivec{vector_size}(0)")?;
4661 }
4662 // Start the `textureSize` call to use as the max value.
4663 write!(self.out, ", textureSize(")?;
4664 self.write_expr(image, ctx)?;
4665 // If the image is mipmapped we need to add the lod argument to the
4666 // `textureSize` call, but this needs to be the clamped lod, this should
4667 // have been generated earlier and put in a local.
4668 if class.is_mipmapped() {
4669 write!(self.out, ", {}{}", Baked(handle), CLAMPED_LOD_SUFFIX)?;
4670 }
4671 // Close the `textureSize` call
4672 write!(self.out, ")")?;
4673
4674 // Subtract 1 from the `textureSize` call since the coordinates are zero based.
4675 if vector_size == 1 {
4676 write!(self.out, " - 1")?;
4677 } else {
4678 write!(self.out, " - ivec{vector_size}(1)")?;
4679 }
4680
4681 // Close the `clamp` call
4682 write!(self.out, ")")?;
4683
4684 // Add the clamped lod (if present) as the second argument to the
4685 // image load function.
4686 if level.is_some() {
4687 write!(self.out, ", {}{}", Baked(handle), CLAMPED_LOD_SUFFIX)?;
4688 }
4689
4690 // If a sample argument is needed we need to clamp it between 0 and
4691 // the number of samples the image has.
4692 if let Some(sample_expr) = sample {
4693 write!(self.out, ", clamp(")?;
4694 self.write_expr(sample_expr, ctx)?;
4695 // Set the min value to 0 and start the call to `textureSamples`
4696 write!(self.out, ", 0, textureSamples(")?;
4697 self.write_expr(image, ctx)?;
4698 // Close the `textureSamples` call, subtract 1 from it since the sample
4699 // argument is zero based, and close the `clamp` call
4700 writeln!(self.out, ") - 1)")?;
4701 }
4702 } else if let Some(sample_or_level) = sample.or(level) {
4703 // GLSL only support SInt on this field while WGSL support also UInt
4704 let cast_to_int = matches!(
4705 *ctx.resolve_type(sample_or_level, &self.module.types),
4706 TypeInner::Scalar(crate::Scalar {
4707 kind: crate::ScalarKind::Uint,
4708 ..
4709 })
4710 );
4711
4712 // If no bounds checking is need just add the sample or level argument
4713 // after the coordinates
4714 write!(self.out, ", ")?;
4715
4716 if cast_to_int {
4717 write!(self.out, "int(")?;
4718 }
4719
4720 self.write_expr(sample_or_level, ctx)?;
4721
4722 if cast_to_int {
4723 write!(self.out, ")")?;
4724 }
4725 }
4726
4727 // Close the image load function.
4728 write!(self.out, ")")?;
4729
4730 // If we were using the `ReadZeroSkipWrite` policy we need to end the first branch
4731 // (which is taken if the condition is `true`) with a colon (`:`) and write the
4732 // second branch which is just a 0 value.
4733 if let proc::BoundsCheckPolicy::ReadZeroSkipWrite = policy {
4734 // Get the kind of the output value.
4735 let kind = match class {
4736 // Only sampled images can reach here since storage images
4737 // don't need bounds checks and depth images aren't implemented
4738 crate::ImageClass::Sampled { kind, .. } => kind,
4739 _ => unreachable!(),
4740 };
4741
4742 // End the first branch
4743 write!(self.out, " : ")?;
4744 // Write the 0 value
4745 write!(
4746 self.out,
4747 "{}vec4(",
4748 glsl_scalar(crate::Scalar { kind, width: 4 })?.prefix,
4749 )?;
4750 self.write_zero_init_scalar(kind)?;
4751 // Close the zero value constructor
4752 write!(self.out, ")")?;
4753 // Close the parentheses surrounding our ternary
4754 write!(self.out, ")")?;
4755 }
4756
4757 Ok(())
4758 }
4759
4760 fn write_named_expr(
4761 &mut self,
4762 handle: Handle<crate::Expression>,
4763 name: String,
4764 // The expression which is being named.
4765 // Generally, this is the same as handle, except in WorkGroupUniformLoad
4766 named: Handle<crate::Expression>,
4767 ctx: &back::FunctionCtx,
4768 ) -> BackendResult {
4769 match ctx.info[named].ty {
4770 proc::TypeResolution::Handle(ty_handle) => match self.module.types[ty_handle].inner {
4771 TypeInner::Struct { .. } => {
4772 let ty_name = &self.names[&NameKey::Type(ty_handle)];
4773 write!(self.out, "{ty_name}")?;
4774 }
4775 _ => {
4776 self.write_type(ty_handle)?;
4777 }
4778 },
4779 proc::TypeResolution::Value(ref inner) => {
4780 self.write_value_type(inner)?;
4781 }
4782 }
4783
4784 let resolved = ctx.resolve_type(named, &self.module.types);
4785
4786 write!(self.out, " {name}")?;
4787 if let TypeInner::Array { base, size, .. } = *resolved {
4788 self.write_array_size(base, size)?;
4789 }
4790 write!(self.out, " = ")?;
4791 self.write_expr(handle, ctx)?;
4792 writeln!(self.out, ";")?;
4793 self.named_expressions.insert(named, name);
4794
4795 Ok(())
4796 }
4797
4798 /// Helper function that write string with default zero initialization for supported types
4799 fn write_zero_init_value(&mut self, ty: Handle<crate::Type>) -> BackendResult {
4800 let inner = &self.module.types[ty].inner;
4801 match *inner {
4802 TypeInner::Scalar(scalar) | TypeInner::Atomic(scalar) => {
4803 self.write_zero_init_scalar(scalar.kind)?;
4804 }
4805 TypeInner::Vector { scalar, .. } => {
4806 self.write_value_type(inner)?;
4807 write!(self.out, "(")?;
4808 self.write_zero_init_scalar(scalar.kind)?;
4809 write!(self.out, ")")?;
4810 }
4811 TypeInner::Matrix { .. } => {
4812 self.write_value_type(inner)?;
4813 write!(self.out, "(")?;
4814 self.write_zero_init_scalar(crate::ScalarKind::Float)?;
4815 write!(self.out, ")")?;
4816 }
4817 TypeInner::Array { base, size, .. } => {
4818 let count = match size.resolve(self.module.to_ctx())? {
4819 proc::IndexableLength::Known(count) => count,
4820 proc::IndexableLength::Dynamic => return Ok(()),
4821 };
4822 self.write_type(base)?;
4823 self.write_array_size(base, size)?;
4824 write!(self.out, "(")?;
4825 for _ in 1..count {
4826 self.write_zero_init_value(base)?;
4827 write!(self.out, ", ")?;
4828 }
4829 // write last parameter without comma and space
4830 self.write_zero_init_value(base)?;
4831 write!(self.out, ")")?;
4832 }
4833 TypeInner::Struct { ref members, .. } => {
4834 let name = &self.names[&NameKey::Type(ty)];
4835 write!(self.out, "{name}(")?;
4836 for (index, member) in members.iter().enumerate() {
4837 if index != 0 {
4838 write!(self.out, ", ")?;
4839 }
4840 self.write_zero_init_value(member.ty)?;
4841 }
4842 write!(self.out, ")")?;
4843 }
4844 _ => unreachable!(),
4845 }
4846
4847 Ok(())
4848 }
4849
4850 /// Helper function that write string with zero initialization for scalar
4851 fn write_zero_init_scalar(&mut self, kind: crate::ScalarKind) -> BackendResult {
4852 match kind {
4853 crate::ScalarKind::Bool => write!(self.out, "false")?,
4854 crate::ScalarKind::Uint => write!(self.out, "0u")?,
4855 crate::ScalarKind::Float => write!(self.out, "0.0")?,
4856 crate::ScalarKind::Sint => write!(self.out, "0")?,
4857 crate::ScalarKind::AbstractInt | crate::ScalarKind::AbstractFloat => {
4858 return Err(Error::Custom(
4859 "Abstract types should not appear in IR presented to backends".to_string(),
4860 ))
4861 }
4862 }
4863
4864 Ok(())
4865 }
4866
4867 /// Issue a memory barrier. Please note that to ensure visibility,
4868 /// OpenGL always requires a call to the `barrier()` function after a `memoryBarrier*()`
4869 fn write_barrier(&mut self, flags: crate::Barrier, level: back::Level) -> BackendResult {
4870 if flags.contains(crate::Barrier::STORAGE) {
4871 writeln!(self.out, "{level}memoryBarrierBuffer();")?;
4872 }
4873 if flags.contains(crate::Barrier::WORK_GROUP) {
4874 writeln!(self.out, "{level}memoryBarrierShared();")?;
4875 }
4876 if flags.contains(crate::Barrier::SUB_GROUP) {
4877 writeln!(self.out, "{level}subgroupMemoryBarrier();")?;
4878 }
4879 if flags.contains(crate::Barrier::TEXTURE) {
4880 writeln!(self.out, "{level}memoryBarrierImage();")?;
4881 }
4882 writeln!(self.out, "{level}barrier();")?;
4883 Ok(())
4884 }
4885
4886 /// Helper function that return the glsl storage access string of [`StorageAccess`](crate::StorageAccess)
4887 ///
4888 /// glsl allows adding both `readonly` and `writeonly` but this means that
4889 /// they can only be used to query information about the resource which isn't what
4890 /// we want here so when storage access is both `LOAD` and `STORE` add no modifiers
4891 fn write_storage_access(&mut self, storage_access: crate::StorageAccess) -> BackendResult {
4892 if storage_access.contains(crate::StorageAccess::ATOMIC) {
4893 return Ok(());
4894 }
4895 if !storage_access.contains(crate::StorageAccess::STORE) {
4896 write!(self.out, "readonly ")?;
4897 }
4898 if !storage_access.contains(crate::StorageAccess::LOAD) {
4899 write!(self.out, "writeonly ")?;
4900 }
4901 Ok(())
4902 }
4903
4904 /// Helper method used to produce the reflection info that's returned to the user
4905 fn collect_reflection_info(&mut self) -> Result<ReflectionInfo, Error> {
4906 let info = self.info.get_entry_point(self.entry_point_idx as usize);
4907 let mut texture_mapping = crate::FastHashMap::default();
4908 let mut uniforms = crate::FastHashMap::default();
4909
4910 for sampling in info.sampling_set.iter() {
4911 let tex_name = self.reflection_names_globals[&sampling.image].clone();
4912
4913 match texture_mapping.entry(tex_name) {
4914 hash_map::Entry::Vacant(v) => {
4915 v.insert(TextureMapping {
4916 texture: sampling.image,
4917 sampler: Some(sampling.sampler),
4918 });
4919 }
4920 hash_map::Entry::Occupied(e) => {
4921 if e.get().sampler != Some(sampling.sampler) {
4922 log::error!("Conflicting samplers for {}", e.key());
4923 return Err(Error::ImageMultipleSamplers);
4924 }
4925 }
4926 }
4927 }
4928
4929 let mut push_constant_info = None;
4930 for (handle, var) in self.module.global_variables.iter() {
4931 if info[handle].is_empty() {
4932 continue;
4933 }
4934 match self.module.types[var.ty].inner {
4935 TypeInner::Image { .. } => {
4936 let tex_name = self.reflection_names_globals[&handle].clone();
4937 match texture_mapping.entry(tex_name) {
4938 hash_map::Entry::Vacant(v) => {
4939 v.insert(TextureMapping {
4940 texture: handle,
4941 sampler: None,
4942 });
4943 }
4944 hash_map::Entry::Occupied(_) => {
4945 // already used with a sampler, do nothing
4946 }
4947 }
4948 }
4949 _ => match var.space {
4950 crate::AddressSpace::Uniform | crate::AddressSpace::Storage { .. } => {
4951 let name = self.reflection_names_globals[&handle].clone();
4952 uniforms.insert(handle, name);
4953 }
4954 crate::AddressSpace::PushConstant => {
4955 let name = self.reflection_names_globals[&handle].clone();
4956 push_constant_info = Some((name, var.ty));
4957 }
4958 _ => (),
4959 },
4960 }
4961 }
4962
4963 let mut push_constant_segments = Vec::new();
4964 let mut push_constant_items = vec![];
4965
4966 if let Some((name, ty)) = push_constant_info {
4967 // We don't have a layouter available to us, so we need to create one.
4968 //
4969 // This is potentially a bit wasteful, but the set of types in the program
4970 // shouldn't be too large.
4971 let mut layouter = proc::Layouter::default();
4972 layouter.update(self.module.to_ctx()).unwrap();
4973
4974 // We start with the name of the binding itself.
4975 push_constant_segments.push(name);
4976
4977 // We then recursively collect all the uniform fields of the push constant.
4978 self.collect_push_constant_items(
4979 ty,
4980 &mut push_constant_segments,
4981 &layouter,
4982 &mut 0,
4983 &mut push_constant_items,
4984 );
4985 }
4986
4987 Ok(ReflectionInfo {
4988 texture_mapping,
4989 uniforms,
4990 varying: mem::take(&mut self.varying),
4991 push_constant_items,
4992 })
4993 }
4994
4995 fn collect_push_constant_items(
4996 &mut self,
4997 ty: Handle<crate::Type>,
4998 segments: &mut Vec<String>,
4999 layouter: &proc::Layouter,
5000 offset: &mut u32,
5001 items: &mut Vec<PushConstantItem>,
5002 ) {
5003 // At this point in the recursion, `segments` contains the path
5004 // needed to access `ty` from the root.
5005
5006 let layout = &layouter[ty];
5007 *offset = layout.alignment.round_up(*offset);
5008 match self.module.types[ty].inner {
5009 // All these types map directly to GL uniforms.
5010 TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Matrix { .. } => {
5011 // Build the full name, by combining all current segments.
5012 let name: String = segments.iter().map(String::as_str).collect();
5013 items.push(PushConstantItem {
5014 access_path: name,
5015 offset: *offset,
5016 ty,
5017 });
5018 *offset += layout.size;
5019 }
5020 // Arrays are recursed into.
5021 TypeInner::Array { base, size, .. } => {
5022 let crate::ArraySize::Constant(count) = size else {
5023 unreachable!("Cannot have dynamic arrays in push constants");
5024 };
5025
5026 for i in 0..count.get() {
5027 // Add the array accessor and recurse.
5028 segments.push(format!("[{i}]"));
5029 self.collect_push_constant_items(base, segments, layouter, offset, items);
5030 segments.pop();
5031 }
5032
5033 // Ensure the stride is kept by rounding up to the alignment.
5034 *offset = layout.alignment.round_up(*offset)
5035 }
5036 TypeInner::Struct { ref members, .. } => {
5037 for (index, member) in members.iter().enumerate() {
5038 // Add struct accessor and recurse.
5039 segments.push(format!(
5040 ".{}",
5041 self.names[&NameKey::StructMember(ty, index as u32)]
5042 ));
5043 self.collect_push_constant_items(member.ty, segments, layouter, offset, items);
5044 segments.pop();
5045 }
5046
5047 // Ensure ending padding is kept by rounding up to the alignment.
5048 *offset = layout.alignment.round_up(*offset)
5049 }
5050 _ => unreachable!(),
5051 }
5052 }
5053 }
5054
5055 /// Structure returned by [`glsl_scalar`]
5056 ///
5057 /// It contains both a prefix used in other types and the full type name
5058 struct ScalarString<'a> {
5059 /// The prefix used to compose other types
5060 prefix: &'a str,
5061 /// The name of the scalar type
5062 full: &'a str,
5063 }
5064
5065 /// Helper function that returns scalar related strings
5066 ///
5067 /// Check [`ScalarString`] for the information provided
5068 ///
5069 /// # Errors
5070 /// If a [`Float`](crate::ScalarKind::Float) with an width that isn't 4 or 8
5071 const fn glsl_scalar(scalar: crate::Scalar) -> Result<ScalarString<'static>, Error> {
5072 use crate::ScalarKind as Sk;
5073
5074 Ok(match scalar.kind {
5075 Sk::Sint => ScalarString {
5076 prefix: "i",
5077 full: "int",
5078 },
5079 Sk::Uint => ScalarString {
5080 prefix: "u",
5081 full: "uint",
5082 },
5083 Sk::Float => match scalar.width {
5084 4 => ScalarString {
5085 prefix: "",
5086 full: "float",
5087 },
5088 8 => ScalarString {
5089 prefix: "d",
5090 full: "double",
5091 },
5092 _ => return Err(Error::UnsupportedScalar(scalar)),
5093 },
5094 Sk::Bool => ScalarString {
5095 prefix: "b",
5096 full: "bool",
5097 },
5098 Sk::AbstractInt | Sk::AbstractFloat => {
5099 return Err(Error::UnsupportedScalar(scalar));
5100 }
5101 })
5102 }
5103
5104 /// Helper function that returns the glsl variable name for a builtin
5105 const fn glsl_built_in(built_in: crate::BuiltIn, options: VaryingOptions) -> &'static str {
5106 use crate::BuiltIn as Bi;
5107
5108 match built_in {
5109 Bi::Position { .. } => {
5110 if options.output {
5111 "gl_Position"
5112 } else {
5113 "gl_FragCoord"
5114 }
5115 }
5116 Bi::ViewIndex if options.targeting_webgl => "int(gl_ViewID_OVR)",
5117 Bi::ViewIndex => "gl_ViewIndex",
5118 // vertex
5119 Bi::BaseInstance => "uint(gl_BaseInstance)",
5120 Bi::BaseVertex => "uint(gl_BaseVertex)",
5121 Bi::ClipDistance => "gl_ClipDistance",
5122 Bi::CullDistance => "gl_CullDistance",
5123 Bi::InstanceIndex => {
5124 if options.draw_parameters {
5125 "(uint(gl_InstanceID) + uint(gl_BaseInstanceARB))"
5126 } else {
5127 // Must match FIRST_INSTANCE_BINDING
5128 "(uint(gl_InstanceID) + naga_vs_first_instance)"
5129 }
5130 }
5131 Bi::PointSize => "gl_PointSize",
5132 Bi::VertexIndex => "uint(gl_VertexID)",
5133 Bi::DrawID => "gl_DrawID",
5134 // fragment
5135 Bi::FragDepth => "gl_FragDepth",
5136 Bi::PointCoord => "gl_PointCoord",
5137 Bi::FrontFacing => "gl_FrontFacing",
5138 Bi::PrimitiveIndex => "uint(gl_PrimitiveID)",
5139 Bi::SampleIndex => "gl_SampleID",
5140 Bi::SampleMask => {
5141 if options.output {
5142 "gl_SampleMask"
5143 } else {
5144 "gl_SampleMaskIn"
5145 }
5146 }
5147 // compute
5148 Bi::GlobalInvocationId => "gl_GlobalInvocationID",
5149 Bi::LocalInvocationId => "gl_LocalInvocationID",
5150 Bi::LocalInvocationIndex => "gl_LocalInvocationIndex",
5151 Bi::WorkGroupId => "gl_WorkGroupID",
5152 Bi::WorkGroupSize => "gl_WorkGroupSize",
5153 Bi::NumWorkGroups => "gl_NumWorkGroups",
5154 // subgroup
5155 Bi::NumSubgroups => "gl_NumSubgroups",
5156 Bi::SubgroupId => "gl_SubgroupID",
5157 Bi::SubgroupSize => "gl_SubgroupSize",
5158 Bi::SubgroupInvocationId => "gl_SubgroupInvocationID",
5159 }
5160 }
5161
5162 /// Helper function that returns the string corresponding to the address space
5163 const fn glsl_storage_qualifier(space: crate::AddressSpace) -> Option<&'static str> {
5164 use crate::AddressSpace as As;
5165
5166 match space {
5167 As::Function => None,
5168 As::Private => None,
5169 As::Storage { .. } => Some("buffer"),
5170 As::Uniform => Some("uniform"),
5171 As::Handle => Some("uniform"),
5172 As::WorkGroup => Some("shared"),
5173 As::PushConstant => Some("uniform"),
5174 }
5175 }
5176
5177 /// Helper function that returns the string corresponding to the glsl interpolation qualifier
5178 const fn glsl_interpolation(interpolation: crate::Interpolation) -> &'static str {
5179 use crate::Interpolation as I;
5180
5181 match interpolation {
5182 I::Perspective => "smooth",
5183 I::Linear => "noperspective",
5184 I::Flat => "flat",
5185 }
5186 }
5187
5188 /// Return the GLSL auxiliary qualifier for the given sampling value.
5189 const fn glsl_sampling(sampling: crate::Sampling) -> BackendResult<Option<&'static str>> {
5190 use crate::Sampling as S;
5191
5192 Ok(match sampling {
5193 S::First => return Err(Error::FirstSamplingNotSupported),
5194 S::Center | S::Either => None,
5195 S::Centroid => Some("centroid"),
5196 S::Sample => Some("sample"),
5197 })
5198 }
5199
5200 /// Helper function that returns the glsl dimension string of [`ImageDimension`](crate::ImageDimension)
5201 const fn glsl_dimension(dim: crate::ImageDimension) -> &'static str {
5202 use crate::ImageDimension as IDim;
5203
5204 match dim {
5205 IDim::D1 => "1D",
5206 IDim::D2 => "2D",
5207 IDim::D3 => "3D",
5208 IDim::Cube => "Cube",
5209 }
5210 }
5211
5212 /// Helper function that returns the glsl storage format string of [`StorageFormat`](crate::StorageFormat)
5213 fn glsl_storage_format(format: crate::StorageFormat) -> Result<&'static str, Error> {
5214 use crate::StorageFormat as Sf;
5215
5216 Ok(match format {
5217 Sf::R8Unorm => "r8",
5218 Sf::R8Snorm => "r8_snorm",
5219 Sf::R8Uint => "r8ui",
5220 Sf::R8Sint => "r8i",
5221 Sf::R16Uint => "r16ui",
5222 Sf::R16Sint => "r16i",
5223 Sf::R16Float => "r16f",
5224 Sf::Rg8Unorm => "rg8",
5225 Sf::Rg8Snorm => "rg8_snorm",
5226 Sf::Rg8Uint => "rg8ui",
5227 Sf::Rg8Sint => "rg8i",
5228 Sf::R32Uint => "r32ui",
5229 Sf::R32Sint => "r32i",
5230 Sf::R32Float => "r32f",
5231 Sf::Rg16Uint => "rg16ui",
5232 Sf::Rg16Sint => "rg16i",
5233 Sf::Rg16Float => "rg16f",
5234 Sf::Rgba8Unorm => "rgba8",
5235 Sf::Rgba8Snorm => "rgba8_snorm",
5236 Sf::Rgba8Uint => "rgba8ui",
5237 Sf::Rgba8Sint => "rgba8i",
5238 Sf::Rgb10a2Uint => "rgb10_a2ui",
5239 Sf::Rgb10a2Unorm => "rgb10_a2",
5240 Sf::Rg11b10Ufloat => "r11f_g11f_b10f",
5241 Sf::R64Uint => "r64ui",
5242 Sf::Rg32Uint => "rg32ui",
5243 Sf::Rg32Sint => "rg32i",
5244 Sf::Rg32Float => "rg32f",
5245 Sf::Rgba16Uint => "rgba16ui",
5246 Sf::Rgba16Sint => "rgba16i",
5247 Sf::Rgba16Float => "rgba16f",
5248 Sf::Rgba32Uint => "rgba32ui",
5249 Sf::Rgba32Sint => "rgba32i",
5250 Sf::Rgba32Float => "rgba32f",
5251 Sf::R16Unorm => "r16",
5252 Sf::R16Snorm => "r16_snorm",
5253 Sf::Rg16Unorm => "rg16",
5254 Sf::Rg16Snorm => "rg16_snorm",
5255 Sf::Rgba16Unorm => "rgba16",
5256 Sf::Rgba16Snorm => "rgba16_snorm",
5257
5258 Sf::Bgra8Unorm => {
5259 return Err(Error::Custom(
5260 "Support format BGRA8 is not implemented".into(),
5261 ))
5262 }
5263 })
5264 }
5265
5266 fn is_value_init_supported(module: &crate::Module, ty: Handle<crate::Type>) -> bool {
5267 match module.types[ty].inner {
5268 TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Matrix { .. } => true,
5269 TypeInner::Array { base, size, .. } => {
5270 size != crate::ArraySize::Dynamic && is_value_init_supported(module, base)
5271 }
5272 TypeInner::Struct { ref members, .. } => members
5273 .iter()
5274 .all(|member| is_value_init_supported(module, member.ty)),
5275 _ => false,
5276 }
5277 }