Skip to main content

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