Skip to main content

wgpu_hal/gles/
mod.rs

1/*!
2# OpenGL ES3 API (aka GLES3).
3
4Designed to work on Linux and Android, with context provided by EGL.
5
6## Texture views
7
8GLES3 doesn't really have separate texture view objects. We have to remember the
9original texture and the sub-range into it. Problem is, however, that there is
10no way to expose a subset of array layers or mip levels of a sampled texture.
11
12## Binding model
13
14Binding model is very different from WebGPU, especially with regards to samplers.
15GLES3 has sampler objects, but they aren't separately bindable to the shaders.
16Each sampled texture is exposed to the shader as a combined texture-sampler binding.
17
18When building the pipeline layout, we linearize binding entries based on the groups
19(uniform/storage buffers, uniform/storage textures), and record the mapping into
20`BindGroupLayoutInfo`.
21When a pipeline gets created, and we track all the texture-sampler associations
22from the static use in the shader.
23We only support at most one sampler used with each texture so far. The linear index
24of this sampler is stored per texture slot in `SamplerBindMap` array.
25
26The texture-sampler pairs get potentially invalidated in 2 places:
27  - when a new pipeline is set, we update the linear indices of associated samplers
28  - when a new bind group is set, we update both the textures and the samplers
29
30We expect that the changes to sampler states between any 2 pipelines of the same layout
31will be minimal, if any.
32
33## Vertex data
34
35Generally, vertex buffers are marked as dirty and lazily bound on draw.
36
37GLES3 doesn't support `first_instance` semantics. However, it's easy to support,
38since we are forced to do late binding anyway. We just adjust the offsets
39into the vertex data.
40
41### Old path
42
43In GLES-3.0 and WebGL2, vertex buffer layout is provided
44together with the actual buffer binding.
45We invalidate the attributes on the vertex buffer change, and re-bind them.
46
47### New path
48
49In GLES-3.1 and higher, the vertex buffer layout can be declared separately
50from the vertex data itself. This mostly matches WebGPU, however there is a catch:
51`stride` needs to be specified with the data, not as a part of the layout.
52
53To address this, we invalidate the vertex buffers based on:
54  - whether or not `first_instance` is used
55  - stride has changed
56
57## Handling of `base_vertex`, `first_instance`, and `first_vertex`
58
59Between indirect, the lack of `first_instance` semantics, and the availability of `gl_BaseInstance`
60in shaders, getting buffers and builtins to work correctly is a bit tricky.
61
62We never emulate `base_vertex` and gl_VertexID behaves as `@builtin(vertex_index)` does, so we
63never need to do anything about that.
64
65### GL 4.2+ with ARB_shader_draw_parameters
66
67- `@builtin(instance_index)` translates to `gl_InstanceID + gl_BaseInstance`
68- We bind instance buffers without any offset emulation.
69- We advertise support for the `INDIRECT_FIRST_INSTANCE` feature.
70
71While we can theoretically have a card with 4.2+ support but without ARB_shader_draw_parameters,
72we don't bother with that combination.
73
74### GLES & GL 4.1
75
76- `@builtin(instance_index)` translates to `gl_InstanceID + naga_vs_first_instance`
77- We bind instance buffers with offset emulation.
78- We _do not_ advertise support for `INDIRECT_FIRST_INSTANCE` and cpu-side pretend the `first_instance` is 0 on indirect calls.
79
80*/
81
82///cbindgen:ignore
83#[cfg(not(any(windows, webgl)))]
84mod egl;
85#[cfg(Emscripten)]
86mod emscripten;
87#[cfg(webgl)]
88mod web;
89#[cfg(windows)]
90mod wgl;
91
92mod adapter;
93mod command;
94mod conv;
95mod debug_text;
96mod device;
97mod fence;
98mod gl_state;
99mod queue;
100
101pub use fence::Fence;
102
103#[cfg(not(any(windows, webgl)))]
104pub use self::egl::{AdapterContext, AdapterContextLock};
105#[cfg(not(any(windows, webgl)))]
106pub use self::egl::{Instance, Surface};
107
108#[cfg(webgl)]
109pub use self::web::AdapterContext;
110#[cfg(webgl)]
111pub use self::web::{Instance, Surface, ask_only_for_used_extensions};
112
113#[cfg(windows)]
114use self::wgl::AdapterContext;
115#[cfg(windows)]
116pub use self::wgl::{Instance, Surface};
117
118use alloc::{boxed::Box, string::String, string::ToString as _, sync::Arc, vec::Vec};
119use core::{
120    fmt,
121    ops::Range,
122    sync::atomic::{AtomicU32, AtomicU8, AtomicUsize},
123};
124use parking_lot::Mutex;
125
126use arrayvec::ArrayVec;
127use glow::HasContext;
128use naga::FastHashMap;
129
130use crate::{CopyExtent, TextureDescriptor};
131
132#[derive(Clone, Debug)]
133pub struct Api;
134
135//Note: we can support more samplers if not every one of them is used at a time,
136// but it probably doesn't worth it.
137const MAX_TEXTURE_SLOTS: usize = 16;
138const MAX_SAMPLERS: usize = 16;
139const MAX_VERTEX_ATTRIBUTES: usize = 16;
140const ZERO_BUFFER_SIZE: usize = 256 << 10;
141const MAX_IMMEDIATES: usize = 64;
142// We have to account for each immediate data may need to be set for every shader.
143const MAX_IMMEDIATES_COMMANDS: usize = MAX_IMMEDIATES * crate::MAX_CONCURRENT_SHADER_STAGES;
144
145impl crate::Api for Api {
146    const VARIANT: wgt::Backend = wgt::Backend::Gl;
147
148    type Instance = Instance;
149    type Surface = Surface;
150    type Adapter = Adapter;
151    type Device = Device;
152
153    type Queue = Queue;
154    type CommandEncoder = CommandEncoder;
155    type CommandBuffer = CommandBuffer;
156
157    type Buffer = Buffer;
158    type Texture = Texture;
159    type SurfaceTexture = Texture;
160    type TextureView = TextureView;
161    type Sampler = Sampler;
162    type QuerySet = QuerySet;
163    type Fence = Fence;
164    type AccelerationStructure = AccelerationStructure;
165    type PipelineCache = PipelineCache;
166
167    type BindGroupLayout = BindGroupLayout;
168    type BindGroup = BindGroup;
169    type PipelineLayout = PipelineLayout;
170    type ShaderModule = ShaderModule;
171    type RenderPipeline = RenderPipeline;
172    type ComputePipeline = ComputePipeline;
173    type RayTracingPipeline = RayTracingPipeline;
174}
175
176crate::impl_dyn_resource!(
177    Adapter,
178    AccelerationStructure,
179    BindGroup,
180    BindGroupLayout,
181    Buffer,
182    CommandBuffer,
183    CommandEncoder,
184    ComputePipeline,
185    Device,
186    Fence,
187    Instance,
188    PipelineCache,
189    PipelineLayout,
190    QuerySet,
191    Queue,
192    RenderPipeline,
193    RayTracingPipeline,
194    Sampler,
195    ShaderModule,
196    Surface,
197    Texture,
198    TextureView
199);
200
201bitflags::bitflags! {
202    /// Flags that affect internal code paths but do not
203    /// change the exposed feature set.
204    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
205    struct PrivateCapabilities: u32 {
206        /// Indicates support for `glBufferStorage` allocation.
207        const BUFFER_ALLOCATION = 1 << 0;
208        /// Support explicit layouts in shader.
209        const SHADER_BINDING_LAYOUT = 1 << 1;
210        /// Support extended shadow sampling instructions.
211        const SHADER_TEXTURE_SHADOW_LOD = 1 << 2;
212        /// Support memory barriers.
213        const MEMORY_BARRIERS = 1 << 3;
214        /// Vertex buffer layouts separate from the data.
215        const VERTEX_BUFFER_LAYOUT = 1 << 4;
216        /// Indicates that buffers used as `GL_ELEMENT_ARRAY_BUFFER` may be created / initialized / used
217        /// as other targets, if not present they must not be mixed with other targets.
218        const INDEX_BUFFER_ROLE_CHANGE = 1 << 5;
219        /// Supports `glGetBufferSubData`
220        const GET_BUFFER_SUB_DATA = 1 << 7;
221        /// Supports `f16` color buffers
222        const COLOR_BUFFER_HALF_FLOAT = 1 << 8;
223        /// Supports `f11/f10` and `f32` color buffers
224        const COLOR_BUFFER_FLOAT = 1 << 9;
225        /// Supports query buffer objects.
226        const QUERY_BUFFERS = 1 << 11;
227        /// Supports 64 bit queries via `glGetQueryObjectui64v`
228        const QUERY_64BIT = 1 << 12;
229        /// Supports `glTexStorage2D`, etc.
230        const TEXTURE_STORAGE = 1 << 13;
231        /// Supports `push_debug_group`, `pop_debug_group` and `debug_message_insert`.
232        const DEBUG_FNS = 1 << 14;
233        /// Supports framebuffer invalidation.
234        const INVALIDATE_FRAMEBUFFER = 1 << 15;
235        /// Indicates support for `glDrawElementsInstancedBaseVertexBaseInstance` and `ARB_shader_draw_parameters`
236        ///
237        /// When this is true, instance offset emulation via vertex buffer rebinding and a shader uniform will be disabled.
238        const FULLY_FEATURED_INSTANCING = 1 << 16;
239        /// Supports direct multisampled rendering to a texture without needing a resolve texture.
240        const MULTISAMPLED_RENDER_TO_TEXTURE = 1 << 17;
241        /// Supports norm16 sized internal formats as filterable sampled
242        /// textures, with UNORM variants also color-renderable. SNORM
243        /// renderability is gated on `TEXTURE_FORMAT_SNORM16_RENDERABLE`.
244        const TEXTURE_FORMAT_NORM16 = 1 << 18;
245        /// Supports SNORM 16-bit formats as color attachments. Requires
246        /// `GL_EXT_render_snorm` (in addition to `GL_EXT_texture_norm16`
247        /// on GLES) - desktop GL alone only "optionally" renders SNORM 16.
248        const TEXTURE_FORMAT_SNORM16_RENDERABLE = 1 << 19;
249        /// Supports norm16 sized internal formats as image-load/store targets.
250        /// Desktop GL >= 4.2 (core image-format list) or pre-4.2 with
251        /// `GL_ARB_shader_image_load_store`; GLES needs `GL_NV_image_formats`
252        /// (which itself depends on `GL_EXT_texture_norm16`).
253        const TEXTURE_FORMAT_NORM16_STORAGE = 1 << 20;
254    }
255}
256
257bitflags::bitflags! {
258    /// Flags that indicate necessary workarounds for specific devices or driver bugs
259    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
260    struct Workarounds: u32 {
261        // Needs workaround for Intel Mesa bug:
262        // https://gitlab.freedesktop.org/mesa/mesa/-/issues/2565.
263        //
264        // This comment
265        // (https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/4972/diffs?diff_id=75888#22f5d1004713c9bbf857988c7efb81631ab88f99_323_327)
266        // seems to indicate all skylake models are effected.
267        const MESA_I915_SRGB_SHADER_CLEAR = 1 << 0;
268        /// Buffer map must emulated because it is not supported natively
269        const EMULATE_BUFFER_MAP = 1 << 1;
270    }
271}
272
273type BindTarget = u32;
274
275#[derive(Debug, Default, Clone, Copy)]
276enum VertexAttribKind {
277    #[default]
278    Float, // glVertexAttribPointer
279    Integer, // glVertexAttribIPointer
280             //Double,  // glVertexAttribLPointer
281}
282
283#[derive(Clone, Debug)]
284pub struct TextureFormatDesc {
285    pub internal: u32,
286    pub external: u32,
287    pub data_type: u32,
288}
289
290struct AdapterShared {
291    context: AdapterContext,
292    private_caps: PrivateCapabilities,
293    features: wgt::Features,
294    limits: wgt::Limits,
295    workarounds: Workarounds,
296    options: wgt::GlBackendOptions,
297    shading_language_version: naga::back::glsl::Version,
298    next_shader_id: AtomicU32,
299    program_cache: Mutex<ProgramCache>,
300    /// Programs whose link no command read yet: while any, a submission
301    /// reads the links of the programs it uses before its commands.
302    unread_links: AtomicUsize,
303    es: bool,
304
305    /// Result of `gl.get_parameter_i32(glow::MAX_SAMPLES)`.
306    /// Cached here so it doesn't need to be queried every time texture format capabilities are requested.
307    /// (this has been shown to be a significant enough overhead)
308    max_msaa_samples: i32,
309}
310
311impl fmt::Debug for AdapterShared {
312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313        let Self {
314            context: _, // may or may not implement Debug depending on platform
315            private_caps,
316            features,
317            limits,
318            workarounds,
319            options,
320            shading_language_version,
321            next_shader_id,
322            program_cache: _,
323            unread_links,
324            es,
325            max_msaa_samples,
326        } = self;
327        f.debug_struct("AdapterShared")
328            .field("private_caps", private_caps)
329            .field("features", features)
330            .field("limits", limits)
331            .field("workarounds", workarounds)
332            .field("options", options)
333            .field("shading_language_version", shading_language_version)
334            .field("next_shader_id", next_shader_id)
335            .field("unread_links", unread_links)
336            .field("es", es)
337            .field("max_msaa_samples", max_msaa_samples)
338            .finish_non_exhaustive()
339    }
340}
341
342#[derive(Debug)]
343pub struct Adapter {
344    shared: Arc<AdapterShared>,
345}
346
347#[derive(Debug)]
348pub struct Device {
349    shared: Arc<AdapterShared>,
350    main_vao: glow::VertexArray,
351    #[cfg(all(native, feature = "renderdoc"))]
352    render_doc: crate::auxil::renderdoc::RenderDoc,
353    counters: Arc<wgt::HalCounters>,
354}
355
356impl Drop for Device {
357    fn drop(&mut self) {
358        let gl = &self.shared.context.lock();
359        unsafe { gl.delete_vertex_array(self.main_vao) };
360    }
361}
362
363#[derive(Debug)]
364pub struct ShaderClearProgram {
365    pub program: glow::Program,
366    pub color_uniform_location: glow::UniformLocation,
367}
368
369#[derive(Debug)]
370pub struct Queue {
371    shared: Arc<AdapterShared>,
372    features: wgt::Features,
373    draw_fbo: glow::Framebuffer,
374    copy_fbo: glow::Framebuffer,
375    /// Shader program used to clear the screen for [`Workarounds::MESA_I915_SRGB_SHADER_CLEAR`]
376    /// devices.
377    shader_clear_program: Option<ShaderClearProgram>,
378    /// Keep a reasonably large buffer filled with zeroes, so that we can implement `ClearBuffer` of
379    /// zeroes by copying from it.
380    zero_buffer: glow::Buffer,
381    temp_query_results: Mutex<Vec<u64>>,
382    draw_buffer_count: AtomicU8,
383    current_index_buffer: Mutex<Option<glow::Buffer>>,
384    /// The state each submitted command buffer's commands set, kept here so
385    /// its lists keep their storage from one command buffer to the next.
386    gl_state: Mutex<gl_state::GlState>,
387}
388
389impl Drop for Queue {
390    fn drop(&mut self) {
391        let gl = &self.shared.context.lock();
392        unsafe { gl.delete_framebuffer(self.draw_fbo) };
393        unsafe { gl.delete_framebuffer(self.copy_fbo) };
394        unsafe { gl.delete_buffer(self.zero_buffer) };
395    }
396}
397
398#[derive(Clone, Debug)]
399pub struct Buffer {
400    raw: Option<glow::Buffer>,
401    target: BindTarget,
402    size: wgt::BufferAddress,
403    /// Flags to use within calls to [`Device::map_buffer`](crate::Device::map_buffer).
404    map_flags: u32,
405    /// Buffer mapping state.
406    ///
407    /// If locked concurrently with the GL context, the GL context should be locked first.
408    map_state: Arc<MaybeMutex<BufferMapState>>,
409    /// Set when the buffer wraps an externally-owned GL name created via
410    /// [`Device::buffer_from_raw`](crate::gles::Device::buffer_from_raw).
411    ///
412    /// `Buffer` is `Clone`, so the guard is shared via `Arc`
413    /// and only fires its callback once every clone is dropped.
414    drop_guard: Option<Arc<crate::DropGuard>>,
415}
416
417#[derive(Clone, Debug)]
418struct BufferMapState {
419    /// True if the GL buffer is actually mapped, i.e. not "fake-mapped" with
420    /// an empty slice
421    mapped: bool,
422    data: Option<Vec<u8>>,
423    offset_of_current_mapping: wgt::BufferAddress,
424}
425
426#[cfg(send_sync)]
427static_assertions::assert_impl_all!(Buffer: Send, Sync);
428
429impl crate::DynBuffer for Buffer {}
430
431#[derive(Clone, Debug)]
432pub enum TextureInner {
433    Renderbuffer {
434        raw: glow::Renderbuffer,
435    },
436    DefaultRenderbuffer,
437    Texture {
438        raw: glow::Texture,
439        target: BindTarget,
440    },
441    #[cfg(webgl)]
442    /// Render to a `WebGLFramebuffer`
443    ///
444    /// This is a web feature
445    ExternalFramebuffer {
446        inner: web_sys::WebGlFramebuffer,
447    },
448    #[cfg(native)]
449    /// Render to a `glow::NativeFramebuffer`
450    /// Useful when the framebuffer to draw to
451    /// has a non-zero framebuffer ID
452    ///
453    /// This is a native feature
454    ExternalNativeFramebuffer {
455        inner: glow::NativeFramebuffer,
456    },
457}
458
459#[cfg(send_sync)]
460unsafe impl Sync for TextureInner {}
461#[cfg(send_sync)]
462unsafe impl Send for TextureInner {}
463
464impl TextureInner {
465    fn as_native(&self) -> (glow::Texture, BindTarget) {
466        match *self {
467            Self::Renderbuffer { .. } | Self::DefaultRenderbuffer => {
468                panic!("Unexpected renderbuffer");
469            }
470            Self::Texture { raw, target } => (raw, target),
471            #[cfg(webgl)]
472            Self::ExternalFramebuffer { .. } => panic!("Unexpected external framebuffer"),
473            #[cfg(native)]
474            Self::ExternalNativeFramebuffer { .. } => panic!("unexpected external framebuffer"),
475        }
476    }
477}
478
479#[derive(Debug)]
480pub struct Texture {
481    pub inner: TextureInner,
482    pub mip_level_count: u32,
483    pub array_layer_count: u32,
484    pub format: wgt::TextureFormat,
485    pub format_desc: TextureFormatDesc,
486    pub copy_size: CopyExtent,
487
488    // The `drop_guard` field must be the last field of this struct so it is dropped last.
489    // Do not add new fields after it.
490    pub drop_guard: Option<crate::DropGuard>,
491}
492
493impl crate::DynTexture for Texture {}
494impl crate::DynSurfaceTexture for Texture {
495    /// A native GL surface draws every frame into its one texture or
496    /// renderbuffer, made at configure, and copies it to the window at
497    /// present. A web surface draws into its canvas's buffer, which the
498    /// browser hands back cleared.
499    fn image_id(&self) -> Option<u64> {
500        match self.inner {
501            TextureInner::DefaultRenderbuffer => None,
502            _ => Some(0),
503        }
504    }
505}
506
507impl core::borrow::Borrow<dyn crate::DynTexture> for Texture {
508    fn borrow(&self) -> &dyn crate::DynTexture {
509        self
510    }
511}
512
513impl Texture {
514    pub fn default_framebuffer(format: wgt::TextureFormat) -> Self {
515        Self {
516            inner: TextureInner::DefaultRenderbuffer,
517            drop_guard: None,
518            mip_level_count: 1,
519            array_layer_count: 1,
520            format,
521            format_desc: TextureFormatDesc {
522                internal: 0,
523                external: 0,
524                data_type: 0,
525            },
526            copy_size: CopyExtent {
527                width: 0,
528                height: 0,
529                depth: 0,
530            },
531        }
532    }
533
534    /// Returns the `target`, whether the image is 3d and whether the image is a cubemap.
535    fn get_info_from_desc(desc: &TextureDescriptor) -> u32 {
536        match desc.dimension {
537            // WebGL (1 and 2) as well as some GLES versions do not have 1D textures, so we are
538            // doing `TEXTURE_2D` instead
539            wgt::TextureDimension::D1 => glow::TEXTURE_2D,
540            wgt::TextureDimension::D2 => {
541                // HACK: detect a cube map; forces cube compatible textures to be cube textures
542                match (desc.is_cube_compatible(), desc.size.depth_or_array_layers) {
543                    (false, 1) => glow::TEXTURE_2D,
544                    (false, _) => glow::TEXTURE_2D_ARRAY,
545                    (true, 6) => glow::TEXTURE_CUBE_MAP,
546                    (true, _) => glow::TEXTURE_CUBE_MAP_ARRAY,
547                }
548            }
549            wgt::TextureDimension::D3 => glow::TEXTURE_3D,
550        }
551    }
552
553    /// More information can be found in issues #1614 and #1574
554    fn log_failing_target_heuristics(view_dimension: wgt::TextureViewDimension, target: u32) {
555        let expected_target = match view_dimension {
556            wgt::TextureViewDimension::D1 => glow::TEXTURE_2D,
557            wgt::TextureViewDimension::D2 => glow::TEXTURE_2D,
558            wgt::TextureViewDimension::D2Array => glow::TEXTURE_2D_ARRAY,
559            wgt::TextureViewDimension::Cube => glow::TEXTURE_CUBE_MAP,
560            wgt::TextureViewDimension::CubeArray => glow::TEXTURE_CUBE_MAP_ARRAY,
561            wgt::TextureViewDimension::D3 => glow::TEXTURE_3D,
562        };
563
564        if expected_target == target {
565            return;
566        }
567
568        let buffer;
569        let got = match target {
570            glow::TEXTURE_2D => "D2",
571            glow::TEXTURE_2D_ARRAY => "D2Array",
572            glow::TEXTURE_CUBE_MAP => "Cube",
573            glow::TEXTURE_CUBE_MAP_ARRAY => "CubeArray",
574            glow::TEXTURE_3D => "D3",
575            target => {
576                buffer = target.to_string();
577                &buffer
578            }
579        };
580
581        log::error!(
582            concat!(
583                "wgpu-hal heuristics assumed that ",
584                "the view dimension will be equal to `{}` rather than `{:?}`.\n",
585                "`D2` textures with ",
586                "`depth_or_array_layers == 1` ",
587                "are assumed to have view dimension `D2`\n",
588                "`D2` textures with ",
589                "`depth_or_array_layers > 1` ",
590                "are assumed to have view dimension `D2Array`\n",
591                "`D2` textures with ",
592                "`depth_or_array_layers == 6` ",
593                "are assumed to have view dimension `Cube`\n",
594                "`D2` textures with ",
595                "`depth_or_array_layers > 6 && depth_or_array_layers % 6 == 0` ",
596                "are assumed to have view dimension `CubeArray`\n",
597            ),
598            got,
599            view_dimension,
600        );
601    }
602}
603
604#[derive(Clone, Debug)]
605pub struct TextureView {
606    inner: TextureInner,
607    aspects: crate::FormatAspects,
608    mip_levels: Range<u32>,
609    array_layers: Range<u32>,
610    format: wgt::TextureFormat,
611}
612
613impl crate::DynTextureView for TextureView {}
614
615#[derive(Debug)]
616pub struct Sampler {
617    raw: glow::Sampler,
618}
619
620impl crate::DynSampler for Sampler {}
621
622#[derive(Debug)]
623pub struct BindGroupLayout {
624    entries: Arc<[wgt::BindGroupLayoutEntry]>,
625}
626
627impl crate::DynBindGroupLayout for BindGroupLayout {}
628
629#[derive(Debug)]
630struct BindGroupLayoutInfo {
631    entries: Arc<[wgt::BindGroupLayoutEntry]>,
632    /// Mapping of resources, indexed by `binding`, into the whole layout space.
633    /// For texture resources, the value is the texture slot index.
634    /// For sampler resources, the value is the index of the sampler in the whole layout.
635    /// For buffers, the value is the uniform or storage slot index.
636    /// For unused bindings, the value is `!0`
637    binding_to_slot: Box<[u8]>,
638}
639
640#[derive(Debug)]
641pub struct PipelineLayout {
642    group_infos: Box<[Option<BindGroupLayoutInfo>]>,
643    naga_options: naga::back::glsl::Options,
644}
645
646impl crate::DynPipelineLayout for PipelineLayout {}
647
648impl PipelineLayout {
649    /// # Panics
650    /// If the pipeline layout does not contain a bind group layout used by
651    /// the resource binding.
652    fn get_slot(&self, br: &naga::ResourceBinding) -> u8 {
653        let group_info = self.group_infos[br.group as usize].as_ref().unwrap();
654        group_info.binding_to_slot[br.binding as usize]
655    }
656}
657
658#[derive(Debug)]
659enum BindingRegister {
660    UniformBuffers,
661    StorageBuffers,
662    Textures,
663    Images,
664}
665
666#[derive(Debug)]
667enum RawBinding {
668    Buffer {
669        raw: glow::Buffer,
670        offset: i32,
671        size: i32,
672    },
673    Texture {
674        raw: glow::Texture,
675        target: BindTarget,
676        aspects: crate::FormatAspects,
677        mip_levels: Range<u32>,
678        //TODO: array layers
679    },
680    Image(ImageBinding),
681    Sampler(glow::Sampler),
682}
683
684#[derive(Debug)]
685pub struct BindGroup {
686    contents: Box<[RawBinding]>,
687}
688
689impl crate::DynBindGroup for BindGroup {}
690
691type ShaderId = u32;
692
693#[derive(Debug)]
694pub enum ShaderModuleSource {
695    Naga(crate::NagaShader),
696    Passthrough { source: String },
697    Templates(&'static [crate::GlslTemplate]),
698}
699
700#[derive(Debug)]
701pub struct ShaderModule {
702    source: ShaderModuleSource,
703    label: Option<String>,
704    id: ShaderId,
705}
706
707impl crate::DynShaderModule for ShaderModule {}
708
709#[derive(Clone, Debug, Default)]
710struct VertexFormatDesc {
711    element_count: i32,
712    element_format: u32,
713    attrib_kind: VertexAttribKind,
714}
715
716#[derive(Clone, Debug, Default)]
717struct AttributeDesc {
718    location: u32,
719    offset: u32,
720    buffer_index: u32,
721    format_desc: VertexFormatDesc,
722}
723
724#[derive(Clone, Debug)]
725struct BufferBinding {
726    raw: glow::Buffer,
727    offset: wgt::BufferAddress,
728}
729
730#[derive(Clone, Debug)]
731struct ImageBinding {
732    raw: glow::Texture,
733    mip_level: u32,
734    array_layer: Option<u32>,
735    access: u32,
736    format: u32,
737}
738
739#[derive(Clone, Debug, Default, PartialEq)]
740struct VertexBufferDesc {
741    step: wgt::VertexStepMode,
742    stride: u32,
743}
744
745#[derive(Clone, Debug)]
746struct ImmediateDesc {
747    location: glow::UniformLocation,
748    ty: nt::glsl::GlslUniformType,
749    offset: u32,
750}
751
752#[cfg(send_sync)]
753unsafe impl Sync for ImmediateDesc {}
754#[cfg(send_sync)]
755unsafe impl Send for ImmediateDesc {}
756
757/// For each texture in the pipeline layout, store the index of the only
758/// sampler (in this layout) that the texture is used with.
759type SamplerBindMap = [Option<u8>; MAX_TEXTURE_SLOTS];
760
761#[derive(Debug)]
762struct PipelineInner {
763    program: glow::Program,
764    sampler_map: SamplerBindMap,
765    clip_distance_count: u32,
766    /// The program's link, whose state the queue reads when a command
767    /// buffer first uses it (see [`PipelineInner::linked`]).
768    link: Mutex<ProgramLink>,
769}
770
771/// A program's link: pending until its first use, then what it tells.
772#[derive(Debug)]
773struct ProgramLink {
774    pending: Option<Box<device::PendingLink>>,
775    linked: Option<Arc<LinkedProgram>>,
776}
777
778/// What only the linked program tells: the uniforms its draws set.
779#[derive(Debug, Default)]
780struct LinkedProgram {
781    first_instance_location: Option<glow::UniformLocation>,
782    immediates_descs: ArrayVec<ImmediateDesc, MAX_IMMEDIATES_COMMANDS>,
783}
784
785#[cfg(send_sync)]
786unsafe impl Sync for PipelineInner {}
787#[cfg(send_sync)]
788unsafe impl Send for PipelineInner {}
789
790#[derive(Clone, Debug)]
791struct DepthState {
792    function: u32,
793    mask: bool,
794}
795
796#[derive(Clone, Debug, PartialEq)]
797struct BlendComponent {
798    src: u32,
799    dst: u32,
800    equation: u32,
801}
802
803#[derive(Clone, Debug, PartialEq)]
804struct BlendDesc {
805    alpha: BlendComponent,
806    color: BlendComponent,
807}
808
809#[derive(Clone, Debug, Default, PartialEq)]
810struct ColorTargetDesc {
811    mask: wgt::ColorWrites,
812    blend: Option<BlendDesc>,
813}
814
815#[derive(Debug, PartialEq, Eq, Hash)]
816struct ProgramStage {
817    naga_stage: naga::ShaderStage,
818    shader_id: ShaderId,
819    entry_point: String,
820    zero_initialize_workgroup_memory: bool,
821    constant_hash: Vec<u8>,
822}
823
824#[derive(Debug, PartialEq, Eq, Hash)]
825struct ProgramCacheKey {
826    stages: ArrayVec<ProgramStage, 3>,
827    group_to_binding_to_slot: Box<[Option<Box<[u8]>>]>,
828    force_point_size: bool,
829}
830
831type ProgramCache = FastHashMap<ProgramCacheKey, Result<Arc<PipelineInner>, crate::PipelineError>>;
832
833#[derive(Debug)]
834pub struct RenderPipeline {
835    inner: Arc<PipelineInner>,
836    primitive: wgt::PrimitiveState,
837    vertex_buffers: Box<[Option<VertexBufferDesc>]>,
838    vertex_attributes: Box<[AttributeDesc]>,
839    color_targets: Box<[ColorTargetDesc]>,
840    depth: Option<DepthState>,
841    depth_bias: wgt::DepthBiasState,
842    stencil: Option<StencilState>,
843    alpha_to_coverage_enabled: bool,
844}
845
846impl crate::DynRenderPipeline for RenderPipeline {}
847
848#[cfg(send_sync)]
849static_assertions::assert_impl_all!(RenderPipeline: Send, Sync);
850
851#[derive(Debug)]
852pub struct ComputePipeline {
853    inner: Arc<PipelineInner>,
854}
855
856impl crate::DynComputePipeline for ComputePipeline {}
857
858#[derive(Debug)]
859pub struct RayTracingPipeline {}
860
861impl crate::DynRayTracingPipeline for RayTracingPipeline {}
862
863#[cfg(send_sync)]
864static_assertions::assert_impl_all!(ComputePipeline: Send, Sync);
865
866#[derive(Debug)]
867pub struct QuerySet {
868    queries: Box<[glow::Query]>,
869    target: BindTarget,
870}
871
872impl crate::DynQuerySet for QuerySet {}
873
874#[derive(Debug)]
875pub struct AccelerationStructure;
876
877impl crate::DynAccelerationStructure for AccelerationStructure {}
878
879#[derive(Debug)]
880pub struct PipelineCache;
881
882impl crate::DynPipelineCache for PipelineCache {}
883
884#[derive(Clone, Debug, PartialEq)]
885struct StencilOps {
886    pass: u32,
887    fail: u32,
888    depth_fail: u32,
889}
890
891impl Default for StencilOps {
892    fn default() -> Self {
893        Self {
894            pass: glow::KEEP,
895            fail: glow::KEEP,
896            depth_fail: glow::KEEP,
897        }
898    }
899}
900
901#[derive(Clone, Debug, PartialEq)]
902struct StencilSide {
903    function: u32,
904    mask_read: u32,
905    mask_write: u32,
906    reference: u32,
907    ops: StencilOps,
908}
909
910impl Default for StencilSide {
911    fn default() -> Self {
912        Self {
913            function: glow::ALWAYS,
914            mask_read: 0xFF,
915            mask_write: 0xFF,
916            reference: 0,
917            ops: StencilOps::default(),
918        }
919    }
920}
921
922#[derive(Debug, Clone, Default)]
923struct StencilState {
924    front: StencilSide,
925    back: StencilSide,
926}
927
928#[derive(Clone, Debug, Default, PartialEq)]
929struct PrimitiveState {
930    front_face: u32,
931    cull_face: u32,
932    unclipped_depth: bool,
933    polygon_mode: u32,
934}
935
936type InvalidatedAttachments = ArrayVec<u32, { crate::MAX_COLOR_ATTACHMENTS + 2 }>;
937
938#[derive(Debug)]
939struct ClearBufferOp {
940    dst: Buffer,
941    dst_target: BindTarget,
942    range: crate::MemoryRange,
943}
944
945#[derive(Debug)]
946struct BufferToBufferCopy {
947    src: Buffer,
948    src_target: BindTarget,
949    dst: Buffer,
950    dst_target: BindTarget,
951    copy: crate::BufferCopy,
952}
953
954#[cfg(webgl)]
955#[derive(Debug)]
956struct ExternalImageToTextureCopy {
957    src: wgt::CopyExternalImageSourceInfo,
958    dst: glow::Texture,
959    dst_target: BindTarget,
960    dst_format: wgt::TextureFormat,
961    dst_premultiplication: bool,
962    copy: crate::TextureCopy,
963}
964
965#[derive(Debug)]
966struct TextureToTextureCopy {
967    src: glow::Texture,
968    src_target: BindTarget,
969    dst: glow::Texture,
970    dst_target: BindTarget,
971    copy: crate::TextureCopy,
972}
973
974/// A copy between a texture and the default framebuffer: the web canvas a
975/// surface draws into (`web::Surface`).
976#[derive(Debug)]
977struct CanvasCopy {
978    texture: glow::Texture,
979    target: BindTarget,
980    copy: crate::TextureCopy,
981}
982
983#[derive(Debug)]
984struct BufferToTextureCopy {
985    src: Buffer,
986    #[allow(unused)]
987    src_target: BindTarget,
988    dst: glow::Texture,
989    dst_target: BindTarget,
990    dst_format: wgt::TextureFormat,
991    copy: crate::BufferTextureCopy,
992}
993
994#[derive(Debug)]
995struct TextureToBufferCopy {
996    src: glow::Texture,
997    src_target: BindTarget,
998    src_format: wgt::TextureFormat,
999    dst: Buffer,
1000    #[allow(unused)]
1001    dst_target: BindTarget,
1002    copy: crate::BufferTextureCopy,
1003}
1004
1005#[derive(Debug)]
1006struct QueryResultsCopy {
1007    query_range: Range<u32>,
1008    dst: Buffer,
1009    dst_target: BindTarget,
1010    dst_offset: wgt::BufferAddress,
1011}
1012
1013#[derive(Debug)]
1014struct AttachmentBinding {
1015    attachment: u32,
1016    view: TextureView,
1017    depth_slice: Option<u32>,
1018    sample_count: u32,
1019}
1020
1021#[derive(Debug)]
1022struct AttachmentResolve {
1023    attachment: u32,
1024    dst: TextureView,
1025    size: wgt::Extent3d,
1026}
1027
1028#[derive(Debug)]
1029enum Command {
1030    Draw {
1031        topology: u32,
1032        first_vertex: u32,
1033        vertex_count: u32,
1034        first_instance: u32,
1035        instance_count: u32,
1036    },
1037    DrawIndexed {
1038        topology: u32,
1039        index_type: u32,
1040        index_count: u32,
1041        index_offset: wgt::BufferAddress,
1042        base_vertex: i32,
1043        first_instance: u32,
1044        instance_count: u32,
1045    },
1046    DrawIndirect {
1047        topology: u32,
1048        indirect_buf: glow::Buffer,
1049        indirect_offset: wgt::BufferAddress,
1050    },
1051    DrawIndexedIndirect {
1052        topology: u32,
1053        index_type: u32,
1054        indirect_buf: glow::Buffer,
1055        indirect_offset: wgt::BufferAddress,
1056    },
1057    Dispatch([u32; 3]),
1058    DispatchIndirect {
1059        indirect_buf: glow::Buffer,
1060        indirect_offset: wgt::BufferAddress,
1061    },
1062    ClearBuffer(Box<ClearBufferOp>),
1063    CopyBufferToBuffer(Box<BufferToBufferCopy>),
1064    #[cfg(webgl)]
1065    CopyExternalImageToTexture(Box<ExternalImageToTextureCopy>),
1066    CopyTextureToTexture(Box<TextureToTextureCopy>),
1067    CopyCanvasToTexture(Box<CanvasCopy>),
1068    CopyTextureToCanvas(Box<CanvasCopy>),
1069    CopyBufferToTexture(Box<BufferToTextureCopy>),
1070    CopyTextureToBuffer(Box<TextureToBufferCopy>),
1071    SetIndexBuffer(glow::Buffer),
1072    BeginQuery(glow::Query, BindTarget),
1073    EndQuery(BindTarget),
1074    TimestampQuery(glow::Query),
1075    CopyQueryResults(Box<QueryResultsCopy>),
1076    ResetFramebuffer {
1077        is_default: bool,
1078    },
1079    BindAttachment(Box<AttachmentBinding>),
1080    ResolveAttachment(Box<AttachmentResolve>),
1081    InvalidateAttachments(InvalidatedAttachments),
1082    SetDrawColorBuffers(u8),
1083    ClearColorF {
1084        draw_buffer: u32,
1085        color: [f32; 4],
1086        is_srgb: bool,
1087    },
1088    ClearColorU(u32, [u32; 4]),
1089    ClearColorI(u32, [i32; 4]),
1090    ClearDepth(f32),
1091    ClearStencil(u32),
1092    // Clearing both the depth and stencil buffer individually appears to
1093    // result in the stencil buffer failing to clear, atleast in WebGL.
1094    // It is also more efficient to emit a single command instead of two for
1095    // this.
1096    ClearDepthAndStencil(f32, u32),
1097    BufferBarrier(glow::Buffer, wgt::BufferUses),
1098    TextureBarrier(wgt::TextureUses),
1099    SetViewport {
1100        rect: crate::Rect<i32>,
1101        depth: Range<f32>,
1102    },
1103    SetScissor(crate::Rect<i32>),
1104    SetStencilFunc {
1105        face: u32,
1106        function: u32,
1107        reference: u32,
1108        read_mask: u32,
1109    },
1110    SetStencilOps {
1111        face: u32,
1112        write_mask: u32,
1113        ops: StencilOps,
1114    },
1115    SetDepth(DepthState),
1116    SetDepthBias(wgt::DepthBiasState),
1117    ConfigureDepthStencil(crate::FormatAspects),
1118    SetAlphaToCoverage(bool),
1119    SetVertexAttribute {
1120        buffer: Option<glow::Buffer>,
1121        buffer_desc: VertexBufferDesc,
1122        attribute_desc: AttributeDesc,
1123    },
1124    UnsetVertexAttribute(u32),
1125    SetVertexBuffer {
1126        index: u32,
1127        buffer: BufferBinding,
1128        buffer_desc: VertexBufferDesc,
1129    },
1130    SetProgram(Arc<PipelineInner>),
1131    SetPrimitive(PrimitiveState),
1132    SetBlendConstant([f32; 4]),
1133    SetColorTarget {
1134        draw_buffer_index: Option<u32>,
1135        desc: ColorTargetDesc,
1136    },
1137    BindBuffer {
1138        target: BindTarget,
1139        slot: u32,
1140        buffer: glow::Buffer,
1141        offset: i32,
1142        size: i32,
1143    },
1144    BindSampler(u32, Option<glow::Sampler>),
1145    BindTexture {
1146        slot: u32,
1147        texture: glow::Texture,
1148        target: BindTarget,
1149        aspects: crate::FormatAspects,
1150        mip_levels: Range<u32>,
1151    },
1152    BindImage {
1153        slot: u32,
1154        binding: ImageBinding,
1155    },
1156    InsertDebugMarker(Range<u32>),
1157    PushDebugGroup(Range<u32>),
1158    PopDebugGroup,
1159    SetImmediates {
1160        /// The whole immediate data block in `data_bytes`, as the encoder
1161        /// last set it.
1162        data: Range<u32>,
1163    },
1164    SetClipDistances {
1165        old_count: u32,
1166        new_count: u32,
1167    },
1168}
1169
1170#[derive(Default)]
1171pub struct CommandBuffer {
1172    // A NUL follows the label's text: a driver may read it up to the NUL (see debug_text.rs)
1173    label: Option<alloc::ffi::CString>,
1174    commands: Vec<Command>,
1175    data_bytes: Vec<u8>,
1176    queries: Vec<glow::Query>,
1177}
1178
1179impl crate::DynCommandBuffer for CommandBuffer {}
1180
1181impl fmt::Debug for CommandBuffer {
1182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1183        let mut builder = f.debug_struct("CommandBuffer");
1184        if let Some(ref label) = self.label {
1185            builder.field("label", label);
1186        }
1187        builder.finish()
1188    }
1189}
1190
1191#[cfg(send_sync)]
1192unsafe impl Sync for CommandBuffer {}
1193#[cfg(send_sync)]
1194unsafe impl Send for CommandBuffer {}
1195
1196//TODO: we would have something like `Arc<typed_arena::Arena>`
1197// here and in the command buffers. So that everything grows
1198// inside the encoder and stays there until `reset_all`.
1199
1200pub struct CommandEncoder {
1201    cmd_buffer: CommandBuffer,
1202    state: command::State,
1203    private_caps: PrivateCapabilities,
1204    counters: Arc<wgt::HalCounters>,
1205}
1206
1207impl fmt::Debug for CommandEncoder {
1208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1209        f.debug_struct("CommandEncoder")
1210            .field("cmd_buffer", &self.cmd_buffer)
1211            .finish()
1212    }
1213}
1214
1215#[cfg(send_sync)]
1216unsafe impl Sync for CommandEncoder {}
1217#[cfg(send_sync)]
1218unsafe impl Send for CommandEncoder {}
1219
1220#[cfg(not(webgl))]
1221fn gl_debug_message_callback(source: u32, gltype: u32, id: u32, severity: u32, message: &str) {
1222    let source_str = match source {
1223        glow::DEBUG_SOURCE_API => "API",
1224        glow::DEBUG_SOURCE_WINDOW_SYSTEM => "Window System",
1225        glow::DEBUG_SOURCE_SHADER_COMPILER => "ShaderCompiler",
1226        glow::DEBUG_SOURCE_THIRD_PARTY => "Third Party",
1227        glow::DEBUG_SOURCE_APPLICATION => "Application",
1228        glow::DEBUG_SOURCE_OTHER => "Other",
1229        _ => unreachable!(),
1230    };
1231
1232    let log_severity = match severity {
1233        glow::DEBUG_SEVERITY_HIGH => log::Level::Error,
1234        glow::DEBUG_SEVERITY_MEDIUM => log::Level::Warn,
1235        glow::DEBUG_SEVERITY_LOW => log::Level::Debug,
1236        glow::DEBUG_SEVERITY_NOTIFICATION => log::Level::Trace,
1237        _ => unreachable!(),
1238    };
1239
1240    let type_str = match gltype {
1241        glow::DEBUG_TYPE_DEPRECATED_BEHAVIOR => "Deprecated Behavior",
1242        glow::DEBUG_TYPE_ERROR => "Error",
1243        glow::DEBUG_TYPE_MARKER => "Marker",
1244        glow::DEBUG_TYPE_OTHER => "Other",
1245        glow::DEBUG_TYPE_PERFORMANCE => "Performance",
1246        glow::DEBUG_TYPE_POP_GROUP => "Pop Group",
1247        glow::DEBUG_TYPE_PORTABILITY => "Portability",
1248        glow::DEBUG_TYPE_PUSH_GROUP => "Push Group",
1249        glow::DEBUG_TYPE_UNDEFINED_BEHAVIOR => "Undefined Behavior",
1250        _ => unreachable!(),
1251    };
1252
1253    let _ = std::panic::catch_unwind(|| {
1254        log::log!(
1255            log_severity,
1256            "GLES: [{source_str}/{type_str}] ID {id} : {message}"
1257        );
1258    });
1259
1260    #[cfg(feature = "validation_canary")]
1261    if cfg!(debug_assertions) && log_severity == log::Level::Error {
1262        // Set canary and continue
1263        crate::VALIDATION_CANARY.add(message.to_string());
1264    }
1265}
1266
1267// If we are using `std`, then use `Mutex` to provide `Send` and `Sync`
1268cfg_if::cfg_if! {
1269    if #[cfg(gles_with_std)] {
1270        type MaybeMutex<T> = std::sync::Mutex<T>;
1271
1272        fn lock<T>(mutex: &MaybeMutex<T>) -> std::sync::MutexGuard<'_, T> {
1273            mutex.lock().unwrap()
1274        }
1275    } else {
1276        // It should be impossible for any build configuration to trigger this error
1277        // It is intended only as a guard against changes elsewhere causing the use of
1278        // `RefCell` here to become unsound.
1279        #[cfg(all(send_sync, not(feature = "fragile-send-sync-non-atomic-wasm")))]
1280        compile_error!("cannot provide non-fragile Send+Sync without std");
1281
1282        type MaybeMutex<T> = core::cell::RefCell<T>;
1283
1284        fn lock<T>(mutex: &MaybeMutex<T>) -> core::cell::RefMut<'_, T> {
1285            mutex.borrow_mut()
1286        }
1287    }
1288}