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::ComputePipeline for ComputePipeline {
784    fn get_subgroup_size(&self) -> Option<u32> {
785        None
786    }
787}
788
789#[derive(Debug)]
790pub struct RayTracingPipeline {}
791
792impl crate::DynRayTracingPipeline for RayTracingPipeline {}
793
794#[cfg(send_sync)]
795static_assertions::assert_impl_all!(ComputePipeline: Send, Sync);
796
797#[derive(Debug)]
798pub struct QuerySet {
799    queries: Box<[glow::Query]>,
800    target: BindTarget,
801}
802
803impl crate::DynQuerySet for QuerySet {}
804
805#[derive(Debug)]
806pub struct AccelerationStructure;
807
808impl crate::DynAccelerationStructure for AccelerationStructure {}
809
810#[derive(Debug)]
811pub struct PipelineCache;
812
813impl crate::DynPipelineCache for PipelineCache {}
814
815#[derive(Clone, Debug, PartialEq)]
816struct StencilOps {
817    pass: u32,
818    fail: u32,
819    depth_fail: u32,
820}
821
822impl Default for StencilOps {
823    fn default() -> Self {
824        Self {
825            pass: glow::KEEP,
826            fail: glow::KEEP,
827            depth_fail: glow::KEEP,
828        }
829    }
830}
831
832#[derive(Clone, Debug, PartialEq)]
833struct StencilSide {
834    function: u32,
835    mask_read: u32,
836    mask_write: u32,
837    reference: u32,
838    ops: StencilOps,
839}
840
841impl Default for StencilSide {
842    fn default() -> Self {
843        Self {
844            function: glow::ALWAYS,
845            mask_read: 0xFF,
846            mask_write: 0xFF,
847            reference: 0,
848            ops: StencilOps::default(),
849        }
850    }
851}
852
853#[derive(Debug, Clone, Default)]
854struct StencilState {
855    front: StencilSide,
856    back: StencilSide,
857}
858
859#[derive(Clone, Debug, Default, PartialEq)]
860struct PrimitiveState {
861    front_face: u32,
862    cull_face: u32,
863    unclipped_depth: bool,
864    polygon_mode: u32,
865}
866
867type InvalidatedAttachments = ArrayVec<u32, { crate::MAX_COLOR_ATTACHMENTS + 2 }>;
868
869#[derive(Debug)]
870enum Command {
871    Draw {
872        topology: u32,
873        first_vertex: u32,
874        vertex_count: u32,
875        first_instance: u32,
876        instance_count: u32,
877        first_instance_location: Option<glow::UniformLocation>,
878    },
879    DrawIndexed {
880        topology: u32,
881        index_type: u32,
882        index_count: u32,
883        index_offset: wgt::BufferAddress,
884        base_vertex: i32,
885        first_instance: u32,
886        instance_count: u32,
887        first_instance_location: Option<glow::UniformLocation>,
888    },
889    DrawIndirect {
890        topology: u32,
891        indirect_buf: glow::Buffer,
892        indirect_offset: wgt::BufferAddress,
893        first_instance_location: Option<glow::UniformLocation>,
894    },
895    DrawIndexedIndirect {
896        topology: u32,
897        index_type: u32,
898        indirect_buf: glow::Buffer,
899        indirect_offset: wgt::BufferAddress,
900        first_instance_location: Option<glow::UniformLocation>,
901    },
902    Dispatch([u32; 3]),
903    DispatchIndirect {
904        indirect_buf: glow::Buffer,
905        indirect_offset: wgt::BufferAddress,
906    },
907    ClearBuffer {
908        dst: Buffer,
909        dst_target: BindTarget,
910        range: crate::MemoryRange,
911    },
912    CopyBufferToBuffer {
913        src: Buffer,
914        src_target: BindTarget,
915        dst: Buffer,
916        dst_target: BindTarget,
917        copy: crate::BufferCopy,
918    },
919    #[cfg(webgl)]
920    CopyExternalImageToTexture {
921        src: wgt::CopyExternalImageSourceInfo,
922        dst: glow::Texture,
923        dst_target: BindTarget,
924        dst_format: wgt::TextureFormat,
925        dst_premultiplication: bool,
926        copy: crate::TextureCopy,
927    },
928    CopyTextureToTexture {
929        src: glow::Texture,
930        src_target: BindTarget,
931        dst: glow::Texture,
932        dst_target: BindTarget,
933        copy: crate::TextureCopy,
934    },
935    CopyBufferToTexture {
936        src: Buffer,
937        #[allow(unused)]
938        src_target: BindTarget,
939        dst: glow::Texture,
940        dst_target: BindTarget,
941        dst_format: wgt::TextureFormat,
942        copy: crate::BufferTextureCopy,
943    },
944    CopyTextureToBuffer {
945        src: glow::Texture,
946        src_target: BindTarget,
947        src_format: wgt::TextureFormat,
948        dst: Buffer,
949        #[allow(unused)]
950        dst_target: BindTarget,
951        copy: crate::BufferTextureCopy,
952    },
953    SetIndexBuffer(glow::Buffer),
954    BeginQuery(glow::Query, BindTarget),
955    EndQuery(BindTarget),
956    TimestampQuery(glow::Query),
957    CopyQueryResults {
958        query_range: Range<u32>,
959        dst: Buffer,
960        dst_target: BindTarget,
961        dst_offset: wgt::BufferAddress,
962    },
963    ResetFramebuffer {
964        is_default: bool,
965    },
966    BindAttachment {
967        attachment: u32,
968        view: TextureView,
969        depth_slice: Option<u32>,
970        sample_count: u32,
971    },
972    ResolveAttachment {
973        attachment: u32,
974        dst: TextureView,
975        size: wgt::Extent3d,
976    },
977    InvalidateAttachments(InvalidatedAttachments),
978    SetDrawColorBuffers(u8),
979    ClearColorF {
980        draw_buffer: u32,
981        color: [f32; 4],
982        is_srgb: bool,
983    },
984    ClearColorU(u32, [u32; 4]),
985    ClearColorI(u32, [i32; 4]),
986    ClearDepth(f32),
987    ClearStencil(u32),
988    // Clearing both the depth and stencil buffer individually appears to
989    // result in the stencil buffer failing to clear, at least in WebGL.
990    // It is also more efficient to emit a single command instead of two for
991    // this.
992    ClearDepthAndStencil(f32, u32),
993    BufferBarrier(glow::Buffer, wgt::BufferUses),
994    TextureBarrier(wgt::TextureUses),
995    SetViewport {
996        rect: crate::Rect<i32>,
997        depth: Range<f32>,
998    },
999    SetScissor(crate::Rect<i32>),
1000    SetStencilFunc {
1001        face: u32,
1002        function: u32,
1003        reference: u32,
1004        read_mask: u32,
1005    },
1006    SetStencilOps {
1007        face: u32,
1008        write_mask: u32,
1009        ops: StencilOps,
1010    },
1011    SetDepth(DepthState),
1012    SetDepthBias(wgt::DepthBiasState),
1013    ConfigureDepthStencil(crate::FormatAspects),
1014    SetAlphaToCoverage(bool),
1015    SetVertexAttribute {
1016        buffer: Option<glow::Buffer>,
1017        buffer_desc: VertexBufferDesc,
1018        attribute_desc: AttributeDesc,
1019    },
1020    UnsetVertexAttribute(u32),
1021    SetVertexBuffer {
1022        index: u32,
1023        buffer: BufferBinding,
1024        buffer_desc: VertexBufferDesc,
1025    },
1026    SetProgram(glow::Program),
1027    SetPrimitive(PrimitiveState),
1028    SetBlendConstant([f32; 4]),
1029    SetColorTarget {
1030        draw_buffer_index: Option<u32>,
1031        desc: ColorTargetDesc,
1032    },
1033    BindBuffer {
1034        target: BindTarget,
1035        slot: u32,
1036        buffer: glow::Buffer,
1037        offset: i32,
1038        size: i32,
1039    },
1040    BindSampler(u32, Option<glow::Sampler>),
1041    BindTexture {
1042        slot: u32,
1043        texture: glow::Texture,
1044        target: BindTarget,
1045        aspects: crate::FormatAspects,
1046        mip_levels: Range<u32>,
1047    },
1048    BindImage {
1049        slot: u32,
1050        binding: ImageBinding,
1051    },
1052    InsertDebugMarker(Range<u32>),
1053    PushDebugGroup(Range<u32>),
1054    PopDebugGroup,
1055    SetImmediates {
1056        uniform: ImmediateDesc,
1057        /// Offset from the start of the `data_bytes`
1058        offset: u32,
1059    },
1060    SetClipDistances {
1061        old_count: u32,
1062        new_count: u32,
1063    },
1064}
1065
1066#[derive(Default)]
1067pub struct CommandBuffer {
1068    label: Option<String>,
1069    commands: Vec<Command>,
1070    data_bytes: Vec<u8>,
1071    queries: Vec<glow::Query>,
1072}
1073
1074impl crate::DynCommandBuffer for CommandBuffer {}
1075
1076impl fmt::Debug for CommandBuffer {
1077    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1078        let mut builder = f.debug_struct("CommandBuffer");
1079        if let Some(ref label) = self.label {
1080            builder.field("label", label);
1081        }
1082        builder.finish()
1083    }
1084}
1085
1086#[cfg(send_sync)]
1087unsafe impl Sync for CommandBuffer {}
1088#[cfg(send_sync)]
1089unsafe impl Send for CommandBuffer {}
1090
1091//TODO: we would have something like `Arc<typed_arena::Arena>`
1092// here and in the command buffers. So that everything grows
1093// inside the encoder and stays there until `reset_all`.
1094
1095pub struct CommandEncoder {
1096    cmd_buffer: CommandBuffer,
1097    state: command::State,
1098    private_caps: PrivateCapabilities,
1099    counters: Arc<wgt::HalCounters>,
1100}
1101
1102impl fmt::Debug for CommandEncoder {
1103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1104        f.debug_struct("CommandEncoder")
1105            .field("cmd_buffer", &self.cmd_buffer)
1106            .finish()
1107    }
1108}
1109
1110#[cfg(send_sync)]
1111unsafe impl Sync for CommandEncoder {}
1112#[cfg(send_sync)]
1113unsafe impl Send for CommandEncoder {}
1114
1115#[cfg(not(webgl))]
1116fn gl_debug_message_callback(source: u32, gltype: u32, id: u32, severity: u32, message: &str) {
1117    let source_str = match source {
1118        glow::DEBUG_SOURCE_API => "API",
1119        glow::DEBUG_SOURCE_WINDOW_SYSTEM => "Window System",
1120        glow::DEBUG_SOURCE_SHADER_COMPILER => "ShaderCompiler",
1121        glow::DEBUG_SOURCE_THIRD_PARTY => "Third Party",
1122        glow::DEBUG_SOURCE_APPLICATION => "Application",
1123        glow::DEBUG_SOURCE_OTHER => "Other",
1124        _ => unreachable!(),
1125    };
1126
1127    let log_severity = match severity {
1128        glow::DEBUG_SEVERITY_HIGH => log::Level::Error,
1129        glow::DEBUG_SEVERITY_MEDIUM => log::Level::Warn,
1130        glow::DEBUG_SEVERITY_LOW => log::Level::Debug,
1131        glow::DEBUG_SEVERITY_NOTIFICATION => log::Level::Trace,
1132        _ => unreachable!(),
1133    };
1134
1135    let type_str = match gltype {
1136        glow::DEBUG_TYPE_DEPRECATED_BEHAVIOR => "Deprecated Behavior",
1137        glow::DEBUG_TYPE_ERROR => "Error",
1138        glow::DEBUG_TYPE_MARKER => "Marker",
1139        glow::DEBUG_TYPE_OTHER => "Other",
1140        glow::DEBUG_TYPE_PERFORMANCE => "Performance",
1141        glow::DEBUG_TYPE_POP_GROUP => "Pop Group",
1142        glow::DEBUG_TYPE_PORTABILITY => "Portability",
1143        glow::DEBUG_TYPE_PUSH_GROUP => "Push Group",
1144        glow::DEBUG_TYPE_UNDEFINED_BEHAVIOR => "Undefined Behavior",
1145        _ => unreachable!(),
1146    };
1147
1148    let _ = std::panic::catch_unwind(|| {
1149        log::log!(
1150            log_severity,
1151            "GLES: [{source_str}/{type_str}] ID {id} : {message}"
1152        );
1153    });
1154
1155    #[cfg(feature = "validation_canary")]
1156    if cfg!(debug_assertions) && log_severity == log::Level::Error {
1157        use alloc::string::ToString as _;
1158
1159        // Set canary and continue
1160        crate::VALIDATION_CANARY.add(message.to_string());
1161    }
1162}