Skip to main content

wgpu_hal/gles/
mod.rs

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