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