naga/back/glsl/
mod.rs

1/*!
2Backend for [GLSL][glsl] (OpenGL Shading Language).
3
4The main structure is [`Writer`], it maintains internal state that is used
5to 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
46pub use features::Features;
47pub use writer::Writer;
48
49use alloc::{
50    borrow::ToOwned,
51    format,
52    string::{String, ToString},
53    vec,
54    vec::Vec,
55};
56use core::{
57    cmp::Ordering,
58    fmt::{self, Error as FmtError, Write},
59    mem,
60};
61
62use hashbrown::hash_map;
63use thiserror::Error;
64
65use crate::{
66    back::{self, Baked},
67    common,
68    proc::{self, NameKey},
69    valid, Handle, ShaderStage, TypeInner,
70};
71use conv::*;
72use features::FeaturesManager;
73
74/// Contains simple 1:1 conversion functions.
75mod conv;
76/// Contains the features related code and the features querying method
77mod features;
78/// Contains a constant with a slice of all the reserved keywords RESERVED_KEYWORDS
79mod keywords;
80/// Contains the [`Writer`] type.
81mod writer;
82
83/// List of supported `core` GLSL versions.
84pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[140, 150, 330, 400, 410, 420, 430, 440, 450, 460];
85/// List of supported `es` GLSL versions.
86pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320];
87
88/// The suffix of the variable that will hold the calculated clamped level
89/// of detail for bounds checking in `ImageLoad`
90const CLAMPED_LOD_SUFFIX: &str = "_clamped_lod";
91
92pub(crate) const MODF_FUNCTION: &str = "naga_modf";
93pub(crate) const FREXP_FUNCTION: &str = "naga_frexp";
94
95// Must match code in glsl_built_in
96pub const FIRST_INSTANCE_BINDING: &str = "naga_vs_first_instance";
97
98#[cfg(feature = "deserialize")]
99#[derive(serde::Deserialize)]
100struct BindingMapSerialization {
101    resource_binding: crate::ResourceBinding,
102    bind_target: u8,
103}
104
105#[cfg(feature = "deserialize")]
106fn deserialize_binding_map<'de, D>(deserializer: D) -> Result<BindingMap, D::Error>
107where
108    D: serde::Deserializer<'de>,
109{
110    use serde::Deserialize;
111
112    let vec = Vec::<BindingMapSerialization>::deserialize(deserializer)?;
113    let mut map = BindingMap::default();
114    for item in vec {
115        map.insert(item.resource_binding, item.bind_target);
116    }
117    Ok(map)
118}
119
120/// Mapping between resources and bindings.
121pub type BindingMap = alloc::collections::BTreeMap<crate::ResourceBinding, u8>;
122
123impl crate::AtomicFunction {
124    const fn to_glsl(self) -> &'static str {
125        match self {
126            Self::Add | Self::Subtract => "Add",
127            Self::And => "And",
128            Self::InclusiveOr => "Or",
129            Self::ExclusiveOr => "Xor",
130            Self::Min => "Min",
131            Self::Max => "Max",
132            Self::Exchange { compare: None } => "Exchange",
133            Self::Exchange { compare: Some(_) } => "", //TODO
134        }
135    }
136}
137
138impl crate::AddressSpace {
139    /// Whether a variable with this address space can be initialized
140    const fn initializable(&self) -> bool {
141        match *self {
142            crate::AddressSpace::Function | crate::AddressSpace::Private => true,
143            crate::AddressSpace::WorkGroup
144            | crate::AddressSpace::Uniform
145            | crate::AddressSpace::Storage { .. }
146            | crate::AddressSpace::Handle
147            | crate::AddressSpace::Immediate
148            | crate::AddressSpace::TaskPayload => false,
149        }
150    }
151}
152
153/// A GLSL version.
154#[derive(Debug, Copy, Clone, PartialEq)]
155#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
156#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
157pub enum Version {
158    /// `core` GLSL.
159    Desktop(u16),
160    /// `es` GLSL.
161    Embedded { version: u16, is_webgl: bool },
162}
163
164impl Version {
165    /// Create a new gles version
166    pub const fn new_gles(version: u16) -> Self {
167        Self::Embedded {
168            version,
169            is_webgl: false,
170        }
171    }
172
173    /// Returns true if self is `Version::Embedded` (i.e. is a es version)
174    const fn is_es(&self) -> bool {
175        match *self {
176            Version::Desktop(_) => false,
177            Version::Embedded { .. } => true,
178        }
179    }
180
181    /// Returns true if targeting WebGL
182    const fn is_webgl(&self) -> bool {
183        match *self {
184            Version::Desktop(_) => false,
185            Version::Embedded { is_webgl, .. } => is_webgl,
186        }
187    }
188
189    /// Checks the list of currently supported versions and returns true if it contains the
190    /// specified version
191    ///
192    /// # Notes
193    /// As an invalid version number will never be added to the supported version list
194    /// so this also checks for version validity
195    fn is_supported(&self) -> bool {
196        match *self {
197            Version::Desktop(v) => SUPPORTED_CORE_VERSIONS.contains(&v),
198            Version::Embedded { version: v, .. } => SUPPORTED_ES_VERSIONS.contains(&v),
199        }
200    }
201
202    fn supports_io_locations(&self) -> bool {
203        *self >= Version::Desktop(330) || *self >= Version::new_gles(300)
204    }
205
206    /// Checks if the version supports all of the explicit layouts:
207    /// - `location=` qualifiers for bindings
208    /// - `binding=` qualifiers for resources
209    ///
210    /// Note: `location=` for vertex inputs and fragment outputs is supported
211    /// unconditionally for GLES 300.
212    fn supports_explicit_locations(&self) -> bool {
213        *self >= Version::Desktop(420) || *self >= Version::new_gles(310)
214    }
215
216    fn supports_early_depth_test(&self) -> bool {
217        *self >= Version::Desktop(130) || *self >= Version::new_gles(310)
218    }
219
220    fn supports_std140_layout(&self) -> bool {
221        *self >= Version::Desktop(140) || *self >= Version::new_gles(300)
222    }
223
224    fn supports_std430_layout(&self) -> bool {
225        *self >= Version::Desktop(430) || *self >= Version::new_gles(310)
226    }
227
228    fn supports_fma_function(&self) -> bool {
229        *self >= Version::Desktop(400) || *self >= Version::new_gles(320)
230    }
231
232    fn supports_integer_functions(&self) -> bool {
233        *self >= Version::Desktop(400) || *self >= Version::new_gles(310)
234    }
235
236    fn supports_frexp_function(&self) -> bool {
237        *self >= Version::Desktop(400) || *self >= Version::new_gles(310)
238    }
239
240    fn supports_derivative_control(&self) -> bool {
241        *self >= Version::Desktop(450)
242    }
243
244    // For supports_pack_unpack_4x8, supports_pack_unpack_snorm_2x16, supports_pack_unpack_unorm_2x16
245    // see:
246    // https://registry.khronos.org/OpenGL-Refpages/gl4/html/unpackUnorm.xhtml
247    // https://registry.khronos.org/OpenGL-Refpages/es3/html/unpackUnorm.xhtml
248    // https://registry.khronos.org/OpenGL-Refpages/gl4/html/packUnorm.xhtml
249    // https://registry.khronos.org/OpenGL-Refpages/es3/html/packUnorm.xhtml
250    fn supports_pack_unpack_4x8(&self) -> bool {
251        *self >= Version::Desktop(400) || *self >= Version::new_gles(310)
252    }
253    fn supports_pack_unpack_snorm_2x16(&self) -> bool {
254        *self >= Version::Desktop(420) || *self >= Version::new_gles(300)
255    }
256    fn supports_pack_unpack_unorm_2x16(&self) -> bool {
257        *self >= Version::Desktop(400) || *self >= Version::new_gles(300)
258    }
259
260    // https://registry.khronos.org/OpenGL-Refpages/gl4/html/unpackHalf2x16.xhtml
261    // https://registry.khronos.org/OpenGL-Refpages/gl4/html/packHalf2x16.xhtml
262    // https://registry.khronos.org/OpenGL-Refpages/es3/html/unpackHalf2x16.xhtml
263    // https://registry.khronos.org/OpenGL-Refpages/es3/html/packHalf2x16.xhtml
264    fn supports_pack_unpack_half_2x16(&self) -> bool {
265        *self >= Version::Desktop(420) || *self >= Version::new_gles(300)
266    }
267}
268
269impl PartialOrd for Version {
270    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
271        match (*self, *other) {
272            (Version::Desktop(x), Version::Desktop(y)) => Some(x.cmp(&y)),
273            (Version::Embedded { version: x, .. }, Version::Embedded { version: y, .. }) => {
274                Some(x.cmp(&y))
275            }
276            _ => None,
277        }
278    }
279}
280
281impl fmt::Display for Version {
282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283        match *self {
284            Version::Desktop(v) => write!(f, "{v} core"),
285            Version::Embedded { version: v, .. } => write!(f, "{v} es"),
286        }
287    }
288}
289
290bitflags::bitflags! {
291    /// Configuration flags for the [`Writer`].
292    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
293    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
294    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
295    pub struct WriterFlags: u32 {
296        /// Flip output Y and extend Z from (0, 1) to (-1, 1).
297        const ADJUST_COORDINATE_SPACE = 0x1;
298        /// Supports GL_EXT_texture_shadow_lod on the host, which provides
299        /// additional functions on shadows and arrays of shadows.
300        const TEXTURE_SHADOW_LOD = 0x2;
301        /// Supports ARB_shader_draw_parameters on the host, which provides
302        /// support for `gl_BaseInstanceARB`, `gl_BaseVertexARB`, `gl_DrawIDARB`, and `gl_DrawID`.
303        const DRAW_PARAMETERS = 0x4;
304        /// Include unused global variables, constants and functions. By default the output will exclude
305        /// global variables that are not used in the specified entrypoint (including indirect use),
306        /// all constant declarations, and functions that use excluded global variables.
307        const INCLUDE_UNUSED_ITEMS = 0x10;
308        /// Emit `PointSize` output builtin to vertex shaders, which is
309        /// required for drawing with `PointList` topology.
310        ///
311        /// https://registry.khronos.org/OpenGL/specs/es/3.2/GLSL_ES_Specification_3.20.html#built-in-language-variables
312        /// The variable gl_PointSize is intended for a shader to write the size of the point to be rasterized. It is measured in pixels.
313        /// If gl_PointSize is not written to, its value is undefined in subsequent pipe stages.
314        const FORCE_POINT_SIZE = 0x20;
315    }
316}
317
318/// Configuration used in the [`Writer`].
319#[derive(Debug, Clone)]
320#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
321#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
322#[cfg_attr(feature = "deserialize", serde(default))]
323pub struct Options {
324    /// The GLSL version to be used.
325    pub version: Version,
326    /// Configuration flags for the [`Writer`].
327    pub writer_flags: WriterFlags,
328    /// Map of resources association to binding locations.
329    #[cfg_attr(
330        feature = "deserialize",
331        serde(deserialize_with = "deserialize_binding_map")
332    )]
333    pub binding_map: BindingMap,
334    /// Should workgroup variables be zero initialized (by polyfilling)?
335    pub zero_initialize_workgroup_memory: bool,
336}
337
338impl Default for Options {
339    fn default() -> Self {
340        Options {
341            version: Version::new_gles(310),
342            writer_flags: WriterFlags::ADJUST_COORDINATE_SPACE,
343            binding_map: BindingMap::default(),
344            zero_initialize_workgroup_memory: true,
345        }
346    }
347}
348
349/// A subset of options meant to be changed per pipeline.
350#[derive(Debug, Clone)]
351#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
352#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
353pub struct PipelineOptions {
354    /// The stage of the entry point.
355    pub shader_stage: ShaderStage,
356    /// The name of the entry point.
357    ///
358    /// If no entry point that matches is found while creating a [`Writer`], an
359    /// error will be thrown.
360    pub entry_point: String,
361    /// How many views to render to, if doing multiview rendering.
362    pub multiview: Option<core::num::NonZeroU32>,
363}
364
365#[derive(Debug)]
366pub struct VaryingLocation {
367    /// The location of the global.
368    /// This corresponds to `layout(location = ..)` in GLSL.
369    pub location: u32,
370    /// The index which can be used for dual source blending.
371    /// This corresponds to `layout(index = ..)` in GLSL.
372    pub index: u32,
373}
374
375/// Reflection info for texture mappings and uniforms.
376#[derive(Debug)]
377pub struct ReflectionInfo {
378    /// Mapping between texture names and variables/samplers.
379    pub texture_mapping: crate::FastHashMap<String, TextureMapping>,
380    /// Mapping between uniform variables and names.
381    pub uniforms: crate::FastHashMap<Handle<crate::GlobalVariable>, String>,
382    /// Mapping between names and attribute locations.
383    pub varying: crate::FastHashMap<String, VaryingLocation>,
384    /// List of immediate data items in the shader.
385    pub immediates_items: Vec<ImmediateItem>,
386    /// Number of user-defined clip planes. Only applicable to vertex shaders.
387    pub clip_distance_count: u32,
388}
389
390/// Mapping between a texture and its sampler, if it exists.
391///
392/// GLSL pre-Vulkan has no concept of separate textures and samplers. Instead, everything is a
393/// `gsamplerN` where `g` is the scalar type and `N` is the dimension. But naga uses separate textures
394/// and samplers in the IR, so the backend produces a [`FastHashMap`](crate::FastHashMap) with the texture name
395/// as a key and a [`TextureMapping`] as a value. This way, the user knows where to bind.
396///
397/// [`Storage`](crate::ImageClass::Storage) images produce `gimageN` and don't have an associated sampler,
398/// so the [`sampler`](Self::sampler) field will be [`None`].
399#[derive(Debug, Clone)]
400pub struct TextureMapping {
401    /// Handle to the image global variable.
402    pub texture: Handle<crate::GlobalVariable>,
403    /// Handle to the associated sampler global variable, if it exists.
404    pub sampler: Option<Handle<crate::GlobalVariable>>,
405}
406
407/// All information to bind a single uniform value to the shader.
408///
409/// Immediates are emulated using traditional uniforms in OpenGL.
410///
411/// These are composed of a set of primitives (scalar, vector, matrix) that
412/// are given names. Because they are not backed by the concept of a buffer,
413/// we must do the work of calculating the offset of each primitive in the
414/// immediate data block.
415#[derive(Debug, Clone)]
416pub struct ImmediateItem {
417    /// GL uniform name for the item. This name is the same as if you were
418    /// to access it directly from a GLSL shader.
419    ///
420    /// The with the following example, the following names will be generated,
421    /// one name per GLSL uniform.
422    ///
423    /// ```glsl
424    /// struct InnerStruct {
425    ///     value: f32,
426    /// }
427    ///
428    /// struct ImmediateData {
429    ///     InnerStruct inner;
430    ///     vec4 array[2];
431    /// }
432    ///
433    /// uniform ImmediateData _immediates_binding_cs;
434    /// ```
435    ///
436    /// ```text
437    /// - _immediates_binding_cs.inner.value
438    /// - _immediates_binding_cs.array[0]
439    /// - _immediates_binding_cs.array[1]
440    /// ```
441    ///
442    pub access_path: String,
443    /// Type of the uniform. This will only ever be a scalar, vector, or matrix.
444    pub ty: Handle<crate::Type>,
445    /// The offset in the immediate data memory block this uniform maps to.
446    ///
447    /// The size of the uniform can be derived from the type.
448    pub offset: u32,
449}
450
451/// Helper structure that generates a number
452#[derive(Default)]
453struct IdGenerator(u32);
454
455impl IdGenerator {
456    /// Generates a number that's guaranteed to be unique for this `IdGenerator`
457    fn generate(&mut self) -> u32 {
458        // It's just an increasing number but it does the job
459        let ret = self.0;
460        self.0 += 1;
461        ret
462    }
463}
464
465/// Assorted options needed for generating varyings.
466#[derive(Clone, Copy)]
467struct VaryingOptions {
468    output: bool,
469    targeting_webgl: bool,
470    draw_parameters: bool,
471}
472
473impl VaryingOptions {
474    const fn from_writer_options(options: &Options, output: bool) -> Self {
475        Self {
476            output,
477            targeting_webgl: options.version.is_webgl(),
478            draw_parameters: options.writer_flags.contains(WriterFlags::DRAW_PARAMETERS),
479        }
480    }
481}
482
483/// Helper wrapper used to get a name for a varying
484///
485/// Varying have different naming schemes depending on their binding:
486/// - Varyings with builtin bindings get their name from [`glsl_built_in`].
487/// - Varyings with location bindings are named `_S_location_X` where `S` is a
488///   prefix identifying which pipeline stage the varying connects, and `X` is
489///   the location.
490struct VaryingName<'a> {
491    binding: &'a crate::Binding,
492    stage: ShaderStage,
493    options: VaryingOptions,
494}
495impl fmt::Display for VaryingName<'_> {
496    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
497        match *self.binding {
498            crate::Binding::Location {
499                blend_src: Some(1), ..
500            } => {
501                write!(f, "_fs2p_location1",)
502            }
503            crate::Binding::Location { location, .. } => {
504                let prefix = match (self.stage, self.options.output) {
505                    (ShaderStage::Compute, _) => unreachable!(),
506                    // pipeline to vertex
507                    (ShaderStage::Vertex, false) => "p2vs",
508                    // vertex to fragment
509                    (ShaderStage::Vertex, true) | (ShaderStage::Fragment, false) => "vs2fs",
510                    // fragment to pipeline
511                    (ShaderStage::Fragment, true) => "fs2p",
512                    (ShaderStage::Task | ShaderStage::Mesh, _) => unreachable!(),
513                };
514                write!(f, "_{prefix}_location{location}",)
515            }
516            crate::Binding::BuiltIn(built_in) => {
517                write!(f, "{}", glsl_built_in(built_in, self.options))
518            }
519        }
520    }
521}
522
523impl ShaderStage {
524    const fn to_str(self) -> &'static str {
525        match self {
526            ShaderStage::Compute => "cs",
527            ShaderStage::Fragment => "fs",
528            ShaderStage::Vertex => "vs",
529            ShaderStage::Task | ShaderStage::Mesh => unreachable!(),
530        }
531    }
532}
533
534/// Shorthand result used internally by the backend
535type BackendResult<T = ()> = Result<T, Error>;
536
537/// A GLSL compilation error.
538#[derive(Debug, Error)]
539pub enum Error {
540    /// A error occurred while writing to the output.
541    #[error("Format error")]
542    FmtError(#[from] FmtError),
543    /// The specified [`Version`] doesn't have all required [`Features`].
544    ///
545    /// Contains the missing [`Features`].
546    #[error("The selected version doesn't support {0:?}")]
547    MissingFeatures(Features),
548    /// [`AddressSpace::Immediate`](crate::AddressSpace::Immediate) was used more than
549    /// once in the entry point, which isn't supported.
550    #[error("Multiple immediates aren't supported")]
551    MultipleImmediateData,
552    /// The specified [`Version`] isn't supported.
553    #[error("The specified version isn't supported")]
554    VersionNotSupported,
555    /// The entry point couldn't be found.
556    #[error("The requested entry point couldn't be found")]
557    EntryPointNotFound,
558    /// A call was made to an unsupported external.
559    #[error("A call was made to an unsupported external: {0}")]
560    UnsupportedExternal(String),
561    /// A scalar with an unsupported width was requested.
562    #[error("A scalar with an unsupported width was requested: {0:?}")]
563    UnsupportedScalar(crate::Scalar),
564    /// A image was used with multiple samplers, which isn't supported.
565    #[error("A image was used with multiple samplers")]
566    ImageMultipleSamplers,
567    #[error("{0}")]
568    Custom(String),
569    #[error("overrides should not be present at this stage")]
570    Override,
571    /// [`crate::Sampling::First`] is unsupported.
572    #[error("`{:?}` sampling is unsupported", crate::Sampling::First)]
573    FirstSamplingNotSupported,
574    #[error(transparent)]
575    ResolveArraySizeError(#[from] proc::ResolveArraySizeError),
576}
577
578/// Binary operation with a different logic on the GLSL side.
579enum BinaryOperation {
580    /// Vector comparison should use the function like `greaterThan()`, etc.
581    VectorCompare,
582    /// Vector component wise operation; used to polyfill unsupported ops like `|` and `&` for `bvecN`'s
583    VectorComponentWise,
584    /// GLSL `%` is SPIR-V `OpUMod/OpSMod` and `mod()` is `OpFMod`, but [`BinaryOperator::Modulo`](crate::BinaryOperator::Modulo) is `OpFRem`.
585    Modulo,
586    /// Any plain operation. No additional logic required.
587    Other,
588}
589
590fn is_value_init_supported(module: &crate::Module, ty: Handle<crate::Type>) -> bool {
591    match module.types[ty].inner {
592        TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Matrix { .. } => true,
593        TypeInner::Array { base, size, .. } => {
594            size != crate::ArraySize::Dynamic && is_value_init_supported(module, base)
595        }
596        TypeInner::Struct { ref members, .. } => members
597            .iter()
598            .all(|member| is_value_init_supported(module, member.ty)),
599        _ => false,
600    }
601}