script/dom/webgl/
webglshader.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
6use std::cell::Cell;
7use std::os::raw::c_int;
8use std::sync::Once;
9
10use canvas_traits::webgl::{
11    GLLimits, GlType, WebGLCommand, WebGLError, WebGLResult, WebGLSLVersion, WebGLShaderId,
12    WebGLVersion, webgl_channel,
13};
14use dom_struct::dom_struct;
15use mozangle::shaders::{BuiltInResources, CompileOptions, Output, ShaderValidator};
16
17use crate::dom::bindings::cell::DomRefCell;
18use crate::dom::bindings::inheritance::Castable;
19use crate::dom::bindings::reflector::{DomGlobal, reflect_dom_object};
20use crate::dom::bindings::root::DomRoot;
21use crate::dom::bindings::str::DOMString;
22use crate::dom::webgl::extensions::WebGLExtensions;
23use crate::dom::webgl::extensions::extfragdepth::EXTFragDepth;
24use crate::dom::webgl::extensions::extshadertexturelod::EXTShaderTextureLod;
25use crate::dom::webgl::extensions::oesstandardderivatives::OESStandardDerivatives;
26use crate::dom::webgl::webglobject::WebGLObject;
27use crate::dom::webgl::webglrenderingcontext::{Operation, WebGLRenderingContext};
28use crate::script_runtime::CanGc;
29
30#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
31pub(crate) enum ShaderCompilationStatus {
32    NotCompiled,
33    Succeeded,
34    Failed,
35}
36
37#[dom_struct]
38pub(crate) struct WebGLShader {
39    webgl_object: WebGLObject,
40    #[no_trace]
41    id: WebGLShaderId,
42    gl_type: u32,
43    source: DomRefCell<DOMString>,
44    info_log: DomRefCell<DOMString>,
45    marked_for_deletion: Cell<bool>,
46    attached_counter: Cell<u32>,
47    compilation_status: Cell<ShaderCompilationStatus>,
48}
49
50static GLSLANG_INITIALIZATION: Once = Once::new();
51
52impl WebGLShader {
53    fn new_inherited(context: &WebGLRenderingContext, id: WebGLShaderId, shader_type: u32) -> Self {
54        GLSLANG_INITIALIZATION.call_once(|| ::mozangle::shaders::initialize().unwrap());
55        Self {
56            webgl_object: WebGLObject::new_inherited(context),
57            id,
58            gl_type: shader_type,
59            source: Default::default(),
60            info_log: Default::default(),
61            marked_for_deletion: Cell::new(false),
62            attached_counter: Cell::new(0),
63            compilation_status: Cell::new(ShaderCompilationStatus::NotCompiled),
64        }
65    }
66
67    pub(crate) fn maybe_new(
68        context: &WebGLRenderingContext,
69        shader_type: u32,
70    ) -> Option<DomRoot<Self>> {
71        let (sender, receiver) = webgl_channel().unwrap();
72        context.send_command(WebGLCommand::CreateShader(shader_type, sender));
73        receiver
74            .recv()
75            .unwrap()
76            .map(|id| WebGLShader::new(context, id, shader_type, CanGc::note()))
77    }
78
79    pub(crate) fn new(
80        context: &WebGLRenderingContext,
81        id: WebGLShaderId,
82        shader_type: u32,
83        can_gc: CanGc,
84    ) -> DomRoot<Self> {
85        reflect_dom_object(
86            Box::new(WebGLShader::new_inherited(context, id, shader_type)),
87            &*context.global(),
88            can_gc,
89        )
90    }
91}
92
93impl WebGLShader {
94    pub(crate) fn id(&self) -> WebGLShaderId {
95        self.id
96    }
97
98    pub(crate) fn gl_type(&self) -> u32 {
99        self.gl_type
100    }
101
102    /// glCompileShader
103    pub(crate) fn compile(
104        &self,
105        api_type: GlType,
106        webgl_version: WebGLVersion,
107        glsl_version: WebGLSLVersion,
108        limits: &GLLimits,
109        ext: &WebGLExtensions,
110    ) -> WebGLResult<()> {
111        if self.marked_for_deletion.get() && !self.is_attached() {
112            return Err(WebGLError::InvalidValue);
113        }
114        if self.compilation_status.get() != ShaderCompilationStatus::NotCompiled {
115            debug!("Compiling already compiled shader {}", self.id);
116        }
117
118        let source = self.source.borrow();
119
120        let mut params = BuiltInResources {
121            MaxVertexAttribs: limits.max_vertex_attribs as c_int,
122            MaxVertexUniformVectors: limits.max_vertex_uniform_vectors as c_int,
123            MaxVertexTextureImageUnits: limits.max_vertex_texture_image_units as c_int,
124            MaxCombinedTextureImageUnits: limits.max_combined_texture_image_units as c_int,
125            MaxTextureImageUnits: limits.max_texture_image_units as c_int,
126            MaxFragmentUniformVectors: limits.max_fragment_uniform_vectors as c_int,
127
128            MaxVertexOutputVectors: limits.max_vertex_output_vectors as c_int,
129            MaxFragmentInputVectors: limits.max_fragment_input_vectors as c_int,
130            MaxVaryingVectors: limits.max_varying_vectors as c_int,
131
132            OES_standard_derivatives: ext.is_enabled::<OESStandardDerivatives>() as c_int,
133            EXT_shader_texture_lod: ext.is_enabled::<EXTShaderTextureLod>() as c_int,
134            EXT_frag_depth: ext.is_enabled::<EXTFragDepth>() as c_int,
135
136            FragmentPrecisionHigh: 1,
137            ..Default::default()
138        };
139
140        if webgl_version == WebGLVersion::WebGL2 {
141            params.MinProgramTexelOffset = limits.min_program_texel_offset as c_int;
142            params.MaxProgramTexelOffset = limits.max_program_texel_offset as c_int;
143            params.MaxDrawBuffers = limits.max_draw_buffers as c_int;
144        }
145
146        let validator = match webgl_version {
147            WebGLVersion::WebGL1 => {
148                let output_format = if api_type == GlType::Gles {
149                    Output::Essl
150                } else {
151                    Output::Glsl
152                };
153                ShaderValidator::for_webgl(self.gl_type, output_format, &params).unwrap()
154            },
155            WebGLVersion::WebGL2 => {
156                let output_format = if api_type == GlType::Gles {
157                    Output::Essl
158                } else {
159                    match (glsl_version.major, glsl_version.minor) {
160                        (1, 30) => Output::Glsl130,
161                        (1, 40) => Output::Glsl140,
162                        (1, 50) => Output::Glsl150Core,
163                        (3, 30) => Output::Glsl330Core,
164                        (4, 0) => Output::Glsl400Core,
165                        (4, 10) => Output::Glsl410Core,
166                        (4, 20) => Output::Glsl420Core,
167                        (4, 30) => Output::Glsl430Core,
168                        (4, 40) => Output::Glsl440Core,
169                        (4, _) => Output::Glsl450Core,
170                        _ => Output::Glsl140,
171                    }
172                };
173                ShaderValidator::for_webgl2(self.gl_type, output_format, &params).unwrap()
174            },
175        };
176
177        // Replicating
178        // https://searchfox.org/mozilla-esr115/rev/f1fb0868dc63b89ccf9eea157960d1ec27fb55a2/dom/canvas/WebGLShaderValidator.cpp#29
179        let mut options = CompileOptions::mozangle();
180        options.set_variables(1);
181        options.set_enforcePackingRestrictions(1);
182        options.set_objectCode(1);
183        options.set_initGLPosition(1);
184        options.set_initializeUninitializedLocals(1);
185        options.set_initOutputVariables(1);
186
187        options.set_limitExpressionComplexity(1);
188        options.set_limitCallStackDepth(1);
189
190        if cfg!(target_os = "macos") {
191            options.set_removeInvariantAndCentroidForESSL3(1);
192
193            // Work around https://bugs.webkit.org/show_bug.cgi?id=124684,
194            // https://chromium.googlesource.com/angle/angle/+/5e70cf9d0b1bb
195            options.set_unfoldShortCircuit(1);
196            // Work around that Mac drivers handle struct scopes incorrectly.
197            options.set_regenerateStructNames(1);
198            // TODO: Only apply this workaround to Intel hardware
199            // Work around that Intel drivers on Mac OSX handle for-loop incorrectly.
200            options.set_addAndTrueToLoopCondition(1);
201            options.set_rewriteTexelFetchOffsetToTexelFetch(1);
202        } else {
203            // We want to do this everywhere, but to do this on Mac, we need
204            // to do it only on Mac OSX > 10.6 as this causes the shader
205            // compiler in 10.6 to crash
206            options.set_clampIndirectArrayBounds(1);
207        }
208
209        match validator.compile(&[&source], options) {
210            Ok(()) => {
211                let translated_source = validator.object_code();
212                debug!("Shader translated: {}", translated_source);
213                // NOTE: At this point we should be pretty sure that the compilation in the paint thread
214                // will succeed.
215                // It could be interesting to retrieve the info log from the paint thread though
216                self.upcast::<WebGLObject>()
217                    .context()
218                    .send_command(WebGLCommand::CompileShader(self.id, translated_source));
219                self.compilation_status
220                    .set(ShaderCompilationStatus::Succeeded);
221            },
222            Err(error) => {
223                self.compilation_status.set(ShaderCompilationStatus::Failed);
224                debug!("Shader {} compilation failed: {}", self.id, error);
225            },
226        }
227
228        *self.info_log.borrow_mut() = validator.info_log().into();
229
230        Ok(())
231    }
232
233    /// Mark this shader as deleted (if it wasn't previously)
234    /// and delete it as if calling glDeleteShader.
235    /// Currently does not check if shader is attached
236    pub(crate) fn mark_for_deletion(&self, operation_fallibility: Operation) {
237        if !self.marked_for_deletion.get() {
238            self.marked_for_deletion.set(true);
239            let context = self.upcast::<WebGLObject>().context();
240            let cmd = WebGLCommand::DeleteShader(self.id);
241            match operation_fallibility {
242                Operation::Fallible => context.send_command_ignored(cmd),
243                Operation::Infallible => context.send_command(cmd),
244            }
245        }
246    }
247
248    pub(crate) fn is_marked_for_deletion(&self) -> bool {
249        self.marked_for_deletion.get()
250    }
251
252    pub(crate) fn is_deleted(&self) -> bool {
253        self.marked_for_deletion.get() && !self.is_attached()
254    }
255
256    pub(crate) fn is_attached(&self) -> bool {
257        self.attached_counter.get() > 0
258    }
259
260    pub(crate) fn increment_attached_counter(&self) {
261        self.attached_counter.set(self.attached_counter.get() + 1);
262    }
263
264    pub(crate) fn decrement_attached_counter(&self) {
265        assert!(self.attached_counter.get() > 0);
266        self.attached_counter.set(self.attached_counter.get() - 1);
267    }
268
269    /// glGetShaderInfoLog
270    pub(crate) fn info_log(&self) -> DOMString {
271        self.info_log.borrow().clone()
272    }
273
274    /// Get the shader source
275    pub(crate) fn source(&self) -> DOMString {
276        self.source.borrow().clone()
277    }
278
279    /// glShaderSource
280    pub(crate) fn set_source(&self, source: DOMString) {
281        *self.source.borrow_mut() = source;
282    }
283
284    pub(crate) fn successfully_compiled(&self) -> bool {
285        self.compilation_status.get() == ShaderCompilationStatus::Succeeded
286    }
287}
288
289impl Drop for WebGLShader {
290    fn drop(&mut self) {
291        self.mark_for_deletion(Operation::Fallible);
292    }
293}