Skip to main content

wgpu_hal/gles/
queue.rs

1use alloc::sync::Arc;
2use alloc::vec;
3use core::sync::atomic::Ordering;
4
5use arrayvec::ArrayVec;
6use glow::HasContext;
7
8use super::{conv::is_layered_target, debug_text, lock, Command as C, PrivateCapabilities};
9
10fn get_2d_target(target: u32, array_layer: u32) -> u32 {
11    const CUBEMAP_FACES: [u32; 6] = [
12        glow::TEXTURE_CUBE_MAP_POSITIVE_X,
13        glow::TEXTURE_CUBE_MAP_NEGATIVE_X,
14        glow::TEXTURE_CUBE_MAP_POSITIVE_Y,
15        glow::TEXTURE_CUBE_MAP_NEGATIVE_Y,
16        glow::TEXTURE_CUBE_MAP_POSITIVE_Z,
17        glow::TEXTURE_CUBE_MAP_NEGATIVE_Z,
18    ];
19
20    match target {
21        glow::TEXTURE_2D => target,
22        glow::TEXTURE_CUBE_MAP => CUBEMAP_FACES[array_layer as usize],
23        _ => unreachable!(),
24    }
25}
26
27fn get_z_offset(target: u32, base: &crate::TextureCopyBase) -> u32 {
28    match target {
29        glow::TEXTURE_2D_ARRAY | glow::TEXTURE_CUBE_MAP_ARRAY => base.array_layer,
30        glow::TEXTURE_3D => base.origin.z,
31        _ => unreachable!(),
32    }
33}
34
35impl super::Queue {
36    /// Performs a manual shader clear, used as a workaround for a clearing bug on mesa
37    unsafe fn perform_shader_clear(&self, gl: &glow::Context, draw_buffer: u32, color: [f32; 4]) {
38        let shader_clear = self
39            .shader_clear_program
40            .as_ref()
41            .expect("shader_clear_program should always be set if the workaround is enabled");
42        unsafe { gl.use_program(Some(shader_clear.program)) };
43        unsafe {
44            gl.uniform_4_f32(
45                Some(&shader_clear.color_uniform_location),
46                color[0],
47                color[1],
48                color[2],
49                color[3],
50            )
51        };
52        unsafe { gl.disable(glow::DEPTH_TEST) };
53        unsafe { gl.disable(glow::STENCIL_TEST) };
54        unsafe { gl.disable(glow::SCISSOR_TEST) };
55        unsafe { gl.disable(glow::BLEND) };
56        unsafe { gl.disable(glow::CULL_FACE) };
57        unsafe { gl.draw_buffers(&[glow::COLOR_ATTACHMENT0 + draw_buffer]) };
58        unsafe { gl.draw_arrays(glow::TRIANGLES, 0, 3) };
59
60        let draw_buffer_count = self.draw_buffer_count.load(Ordering::Relaxed);
61        if draw_buffer_count != 0 {
62            // Reset the draw buffers to what they were before the clear
63            let indices = (0..draw_buffer_count as u32)
64                .map(|i| glow::COLOR_ATTACHMENT0 + i)
65                .collect::<ArrayVec<_, { crate::MAX_COLOR_ATTACHMENTS }>>();
66            unsafe { gl.draw_buffers(&indices) };
67        }
68    }
69
70    unsafe fn reset_state(&self, gl: &glow::Context) {
71        unsafe { gl.use_program(None) };
72        unsafe { gl.bind_framebuffer(glow::FRAMEBUFFER, None) };
73        unsafe { gl.disable(glow::DEPTH_TEST) };
74        unsafe { gl.disable(glow::STENCIL_TEST) };
75        unsafe { gl.disable(glow::SCISSOR_TEST) };
76        unsafe { gl.disable(glow::BLEND) };
77        unsafe { gl.disable(glow::CULL_FACE) };
78        unsafe { gl.disable(glow::POLYGON_OFFSET_FILL) };
79        unsafe { gl.disable(glow::SAMPLE_ALPHA_TO_COVERAGE) };
80        if self.features.contains(wgt::Features::DEPTH_CLIP_CONTROL) {
81            unsafe { gl.disable(glow::DEPTH_CLAMP) };
82        }
83
84        unsafe { gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, None) };
85        let mut current_index_buffer = self.current_index_buffer.lock();
86        *current_index_buffer = None;
87    }
88
89    unsafe fn set_attachment(
90        &self,
91        gl: &glow::Context,
92        fbo_target: u32,
93        attachment: u32,
94        view: &super::TextureView,
95        depth_slice: Option<u32>,
96        sample_count: u32,
97    ) {
98        match view.inner {
99            super::TextureInner::Renderbuffer { raw } => {
100                unsafe {
101                    gl.framebuffer_renderbuffer(
102                        fbo_target,
103                        attachment,
104                        glow::RENDERBUFFER,
105                        Some(raw),
106                    )
107                };
108            }
109            super::TextureInner::DefaultRenderbuffer => panic!("Unexpected default RBO"),
110            super::TextureInner::Texture { raw, target } => {
111                let num_layers = view.array_layers.end - view.array_layers.start;
112                if num_layers > 1 {
113                    #[cfg(webgl)]
114                    unsafe {
115                        gl.framebuffer_texture_multiview_ovr(
116                            fbo_target,
117                            attachment,
118                            Some(raw),
119                            view.mip_levels.start as i32,
120                            view.array_layers.start as i32,
121                            num_layers as i32,
122                        )
123                    };
124                } else if is_layered_target(target) {
125                    let layer = if target == glow::TEXTURE_3D {
126                        depth_slice.unwrap() as i32
127                    } else {
128                        view.array_layers.start as i32
129                    };
130                    unsafe {
131                        gl.framebuffer_texture_layer(
132                            fbo_target,
133                            attachment,
134                            Some(raw),
135                            view.mip_levels.start as i32,
136                            layer,
137                        )
138                    };
139                } else {
140                    unsafe {
141                        assert_eq!(view.mip_levels.len(), 1);
142                        if sample_count != 1 {
143                            gl.framebuffer_texture_2d_multisample(
144                                fbo_target,
145                                attachment,
146                                get_2d_target(target, view.array_layers.start),
147                                Some(raw),
148                                view.mip_levels.start as i32,
149                                sample_count as i32,
150                            )
151                        } else {
152                            gl.framebuffer_texture_2d(
153                                fbo_target,
154                                attachment,
155                                get_2d_target(target, view.array_layers.start),
156                                Some(raw),
157                                view.mip_levels.start as i32,
158                            )
159                        }
160                    };
161                }
162            }
163            #[cfg(webgl)]
164            super::TextureInner::ExternalFramebuffer { ref inner } => unsafe {
165                gl.bind_external_framebuffer(glow::FRAMEBUFFER, inner);
166            },
167            #[cfg(native)]
168            super::TextureInner::ExternalNativeFramebuffer { ref inner } => unsafe {
169                gl.bind_framebuffer(glow::FRAMEBUFFER, Some(*inner));
170            },
171        }
172    }
173
174    /// Runs `command`; `program` is what the program in use tells.
175    unsafe fn process(
176        &self,
177        gl: &glow::Context,
178        command: &C,
179        #[cfg_attr(target_arch = "wasm32", allow(unused))] data_bytes: &[u8],
180        queries: &[glow::Query],
181        program: Option<&super::LinkedProgram>,
182    ) {
183        let first_instance_location =
184            program.and_then(|program| program.first_instance_location.as_ref());
185        match *command {
186            C::Draw {
187                topology,
188                first_vertex,
189                vertex_count,
190                instance_count,
191                first_instance,
192            } => {
193                let supports_full_instancing = self
194                    .shared
195                    .private_caps
196                    .contains(PrivateCapabilities::FULLY_FEATURED_INSTANCING);
197
198                if supports_full_instancing {
199                    unsafe {
200                        gl.draw_arrays_instanced_base_instance(
201                            topology,
202                            first_vertex as i32,
203                            vertex_count as i32,
204                            instance_count as i32,
205                            first_instance,
206                        )
207                    }
208                } else {
209                    // `GlState::apply` set the program's first instance.
210
211                    // Don't use `gl.draw_arrays` for `instance_count == 1`.
212                    // Angle has a bug where it doesn't consider the instance divisor when `DYNAMIC_DRAW` is used in `draw_arrays`.
213                    // See https://github.com/gfx-rs/wgpu/issues/3578
214                    unsafe {
215                        gl.draw_arrays_instanced(
216                            topology,
217                            first_vertex as i32,
218                            vertex_count as i32,
219                            instance_count as i32,
220                        )
221                    }
222                };
223            }
224            C::DrawIndexed {
225                topology,
226                index_type,
227                index_count,
228                index_offset,
229                base_vertex,
230                first_instance,
231                instance_count,
232            } => {
233                let supports_full_instancing = self
234                    .shared
235                    .private_caps
236                    .contains(PrivateCapabilities::FULLY_FEATURED_INSTANCING);
237
238                if supports_full_instancing {
239                    unsafe {
240                        gl.draw_elements_instanced_base_vertex_base_instance(
241                            topology,
242                            index_count as i32,
243                            index_type,
244                            index_offset as i32,
245                            instance_count as i32,
246                            base_vertex,
247                            first_instance,
248                        )
249                    }
250                } else {
251                    // `GlState::apply` set the program's first instance.
252
253                    if base_vertex == 0 {
254                        unsafe {
255                            // Don't use `gl.draw_elements`/`gl.draw_elements_base_vertex` for `instance_count == 1`.
256                            // Angle has a bug where it doesn't consider the instance divisor when `DYNAMIC_DRAW` is used in `gl.draw_elements`/`gl.draw_elements_base_vertex`.
257                            // See https://github.com/gfx-rs/wgpu/issues/3578
258                            gl.draw_elements_instanced(
259                                topology,
260                                index_count as i32,
261                                index_type,
262                                index_offset as i32,
263                                instance_count as i32,
264                            )
265                        }
266                    } else {
267                        // If we've gotten here, wgpu-core has already validated that this function exists via the DownlevelFlags::BASE_VERTEX feature.
268                        unsafe {
269                            gl.draw_elements_instanced_base_vertex(
270                                topology,
271                                index_count as _,
272                                index_type,
273                                index_offset as i32,
274                                instance_count as i32,
275                                base_vertex,
276                            )
277                        }
278                    }
279                }
280            }
281            C::DrawIndirect {
282                topology,
283                indirect_buf,
284                indirect_offset,
285            } => {
286                unsafe { gl.uniform_1_u32(first_instance_location, 0) };
287
288                unsafe { gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(indirect_buf)) };
289                unsafe { gl.draw_arrays_indirect_offset(topology, indirect_offset as i32) };
290            }
291            C::DrawIndexedIndirect {
292                topology,
293                index_type,
294                indirect_buf,
295                indirect_offset,
296            } => {
297                unsafe { gl.uniform_1_u32(first_instance_location, 0) };
298
299                unsafe { gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(indirect_buf)) };
300                unsafe {
301                    gl.draw_elements_indirect_offset(topology, index_type, indirect_offset as i32)
302                };
303            }
304            C::Dispatch(group_counts) => {
305                unsafe { gl.dispatch_compute(group_counts[0], group_counts[1], group_counts[2]) };
306            }
307            C::DispatchIndirect {
308                indirect_buf,
309                indirect_offset,
310            } => {
311                unsafe { gl.bind_buffer(glow::DISPATCH_INDIRECT_BUFFER, Some(indirect_buf)) };
312                unsafe { gl.dispatch_compute_indirect(indirect_offset as i32) };
313            }
314            C::ClearBuffer(ref op) => {
315                let super::ClearBufferOp {
316                    ref dst,
317                    dst_target,
318                    ref range,
319                } = **op;
320                match dst.raw {
321                    Some(buffer) => {
322                        // When `INDEX_BUFFER_ROLE_CHANGE` isn't available, we can't copy into the
323                        // index buffer from the zero buffer. This would fail in Chrome with the
324                        // following message:
325                        //
326                        // > Cannot copy into an element buffer destination from a non-element buffer
327                        // > source
328                        //
329                        // Instead, we'll upload zeroes into the buffer.
330                        let can_use_zero_buffer = self
331                            .shared
332                            .private_caps
333                            .contains(PrivateCapabilities::INDEX_BUFFER_ROLE_CHANGE)
334                            || dst_target != glow::ELEMENT_ARRAY_BUFFER;
335
336                        if can_use_zero_buffer {
337                            unsafe {
338                                gl.bind_buffer(glow::COPY_READ_BUFFER, Some(self.zero_buffer))
339                            };
340                            unsafe { gl.bind_buffer(dst_target, Some(buffer)) };
341                            let mut dst_offset = range.start;
342                            while dst_offset < range.end {
343                                let size =
344                                    (range.end - dst_offset).min(super::ZERO_BUFFER_SIZE as u64);
345                                unsafe {
346                                    gl.copy_buffer_sub_data(
347                                        glow::COPY_READ_BUFFER,
348                                        dst_target,
349                                        0,
350                                        dst_offset as i32,
351                                        size as i32,
352                                    )
353                                };
354                                dst_offset += size;
355                            }
356                        } else {
357                            unsafe { gl.bind_buffer(dst_target, Some(buffer)) };
358                            let zeroes = vec![0u8; (range.end - range.start) as usize];
359                            unsafe {
360                                gl.buffer_sub_data_u8_slice(dst_target, range.start as i32, &zeroes)
361                            };
362                        }
363                    }
364                    None => {
365                        let mut map_state = lock(&dst.map_state);
366                        map_state.data.as_mut().unwrap().as_mut_slice()
367                            [range.start as usize..range.end as usize]
368                            .fill(0);
369                    }
370                }
371            }
372            C::CopyBufferToBuffer(ref op) => {
373                let super::BufferToBufferCopy {
374                    ref src,
375                    src_target,
376                    ref dst,
377                    dst_target,
378                    copy,
379                } = **op;
380                let copy_src_target = glow::COPY_READ_BUFFER;
381                let is_index_buffer_only_element_dst = !self
382                    .shared
383                    .private_caps
384                    .contains(PrivateCapabilities::INDEX_BUFFER_ROLE_CHANGE)
385                    && dst_target == glow::ELEMENT_ARRAY_BUFFER
386                    || src_target == glow::ELEMENT_ARRAY_BUFFER;
387
388                // WebGL not allowed to copy data from other targets to element buffer and can't copy element data to other buffers
389                let copy_dst_target = if is_index_buffer_only_element_dst {
390                    glow::ELEMENT_ARRAY_BUFFER
391                } else {
392                    glow::COPY_WRITE_BUFFER
393                };
394                let size = copy.size.get() as usize;
395                match (src.raw, dst.raw) {
396                    (Some(ref src), Some(ref dst)) => {
397                        unsafe { gl.bind_buffer(copy_src_target, Some(*src)) };
398                        unsafe { gl.bind_buffer(copy_dst_target, Some(*dst)) };
399                        unsafe {
400                            gl.copy_buffer_sub_data(
401                                copy_src_target,
402                                copy_dst_target,
403                                copy.src_offset as _,
404                                copy.dst_offset as _,
405                                copy.size.get() as _,
406                            )
407                        };
408                    }
409                    (Some(src), None) => {
410                        let mut map_state = lock(&dst.map_state);
411                        let dst_data = &mut map_state.data.as_mut().unwrap().as_mut_slice()
412                            [copy.dst_offset as usize..copy.dst_offset as usize + size];
413
414                        unsafe { gl.bind_buffer(copy_src_target, Some(src)) };
415                        unsafe {
416                            self.shared.get_buffer_sub_data(
417                                gl,
418                                copy_src_target,
419                                copy.src_offset as i32,
420                                dst_data,
421                            )
422                        };
423                    }
424                    (None, Some(dst)) => {
425                        let map_state = lock(&src.map_state);
426                        let src_data = &map_state.data.as_ref().unwrap().as_slice()
427                            [copy.src_offset as usize..copy.src_offset as usize + size];
428                        unsafe { gl.bind_buffer(copy_dst_target, Some(dst)) };
429                        unsafe {
430                            gl.buffer_sub_data_u8_slice(
431                                copy_dst_target,
432                                copy.dst_offset as i32,
433                                src_data,
434                            )
435                        };
436                    }
437                    (None, None) => {
438                        todo!()
439                    }
440                }
441                unsafe { gl.bind_buffer(copy_src_target, None) };
442                if is_index_buffer_only_element_dst {
443                    unsafe {
444                        gl.bind_buffer(
445                            glow::ELEMENT_ARRAY_BUFFER,
446                            *self.current_index_buffer.lock(),
447                        )
448                    };
449                } else {
450                    unsafe { gl.bind_buffer(copy_dst_target, None) };
451                }
452            }
453            #[cfg(webgl)]
454            C::CopyExternalImageToTexture(ref op) => {
455                let super::ExternalImageToTextureCopy {
456                    ref src,
457                    dst,
458                    dst_target,
459                    dst_format,
460                    dst_premultiplication,
461                    ref copy,
462                } = **op;
463                const UNPACK_FLIP_Y_WEBGL: u32 =
464                    web_sys::WebGl2RenderingContext::UNPACK_FLIP_Y_WEBGL;
465                const UNPACK_PREMULTIPLY_ALPHA_WEBGL: u32 =
466                    web_sys::WebGl2RenderingContext::UNPACK_PREMULTIPLY_ALPHA_WEBGL;
467
468                unsafe {
469                    if src.flip_y {
470                        gl.pixel_store_bool(UNPACK_FLIP_Y_WEBGL, true);
471                    }
472                    if dst_premultiplication {
473                        gl.pixel_store_bool(UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
474                    }
475                }
476
477                unsafe { gl.bind_texture(dst_target, Some(dst)) };
478                let format_desc = self.shared.describe_texture_format(dst_format);
479                if is_layered_target(dst_target) {
480                    let z_offset = get_z_offset(dst_target, &copy.dst_base);
481
482                    match src.source {
483                        wgt::ExternalImageSource::ImageBitmap(ref b) => unsafe {
484                            gl.tex_sub_image_3d_with_image_bitmap(
485                                dst_target,
486                                copy.dst_base.mip_level as i32,
487                                copy.dst_base.origin.x as i32,
488                                copy.dst_base.origin.y as i32,
489                                z_offset as i32,
490                                copy.size.width as i32,
491                                copy.size.height as i32,
492                                copy.size.depth as i32,
493                                format_desc.external,
494                                format_desc.data_type,
495                                b,
496                            );
497                        },
498                        wgt::ExternalImageSource::HTMLImageElement(ref i) => unsafe {
499                            gl.tex_sub_image_3d_with_html_image_element(
500                                dst_target,
501                                copy.dst_base.mip_level as i32,
502                                copy.dst_base.origin.x as i32,
503                                copy.dst_base.origin.y as i32,
504                                z_offset as i32,
505                                copy.size.width as i32,
506                                copy.size.height as i32,
507                                copy.size.depth as i32,
508                                format_desc.external,
509                                format_desc.data_type,
510                                i,
511                            );
512                        },
513                        wgt::ExternalImageSource::HTMLVideoElement(ref v) => unsafe {
514                            gl.tex_sub_image_3d_with_html_video_element(
515                                dst_target,
516                                copy.dst_base.mip_level as i32,
517                                copy.dst_base.origin.x as i32,
518                                copy.dst_base.origin.y as i32,
519                                z_offset as i32,
520                                copy.size.width as i32,
521                                copy.size.height as i32,
522                                copy.size.depth as i32,
523                                format_desc.external,
524                                format_desc.data_type,
525                                v,
526                            );
527                        },
528                        wgt::ExternalImageSource::VideoFrame(ref v) => unsafe {
529                            gl.tex_sub_image_3d_with_video_frame(
530                                dst_target,
531                                copy.dst_base.mip_level as i32,
532                                copy.dst_base.origin.x as i32,
533                                copy.dst_base.origin.y as i32,
534                                z_offset as i32,
535                                copy.size.width as i32,
536                                copy.size.height as i32,
537                                copy.size.depth as i32,
538                                format_desc.external,
539                                format_desc.data_type,
540                                v,
541                            )
542                        },
543                        wgt::ExternalImageSource::ImageData(ref i) => unsafe {
544                            gl.tex_sub_image_3d_with_image_data(
545                                dst_target,
546                                copy.dst_base.mip_level as i32,
547                                copy.dst_base.origin.x as i32,
548                                copy.dst_base.origin.y as i32,
549                                z_offset as i32,
550                                copy.size.width as i32,
551                                copy.size.height as i32,
552                                copy.size.depth as i32,
553                                format_desc.external,
554                                format_desc.data_type,
555                                i,
556                            );
557                        },
558                        wgt::ExternalImageSource::HTMLCanvasElement(ref c) => unsafe {
559                            gl.tex_sub_image_3d_with_html_canvas_element(
560                                dst_target,
561                                copy.dst_base.mip_level as i32,
562                                copy.dst_base.origin.x as i32,
563                                copy.dst_base.origin.y as i32,
564                                z_offset as i32,
565                                copy.size.width as i32,
566                                copy.size.height as i32,
567                                copy.size.depth as i32,
568                                format_desc.external,
569                                format_desc.data_type,
570                                c,
571                            );
572                        },
573                        wgt::ExternalImageSource::OffscreenCanvas(_) => unreachable!(),
574                    }
575                } else {
576                    let dst_target = get_2d_target(dst_target, copy.dst_base.array_layer);
577
578                    match src.source {
579                        wgt::ExternalImageSource::ImageBitmap(ref b) => unsafe {
580                            gl.tex_sub_image_2d_with_image_bitmap_and_width_and_height(
581                                dst_target,
582                                copy.dst_base.mip_level as i32,
583                                copy.dst_base.origin.x as i32,
584                                copy.dst_base.origin.y as i32,
585                                copy.size.width as i32,
586                                copy.size.height as i32,
587                                format_desc.external,
588                                format_desc.data_type,
589                                b,
590                            );
591                        },
592                        wgt::ExternalImageSource::HTMLImageElement(ref i) => unsafe {
593                            gl.tex_sub_image_2d_with_html_image_and_width_and_height(
594                                dst_target,
595                                copy.dst_base.mip_level as i32,
596                                copy.dst_base.origin.x as i32,
597                                copy.dst_base.origin.y as i32,
598                                copy.size.width as i32,
599                                copy.size.height as i32,
600                                format_desc.external,
601                                format_desc.data_type,
602                                i,
603                            )
604                        },
605                        wgt::ExternalImageSource::HTMLVideoElement(ref v) => unsafe {
606                            gl.tex_sub_image_2d_with_html_video_and_width_and_height(
607                                dst_target,
608                                copy.dst_base.mip_level as i32,
609                                copy.dst_base.origin.x as i32,
610                                copy.dst_base.origin.y as i32,
611                                copy.size.width as i32,
612                                copy.size.height as i32,
613                                format_desc.external,
614                                format_desc.data_type,
615                                v,
616                            )
617                        },
618                        wgt::ExternalImageSource::VideoFrame(ref v) => unsafe {
619                            gl.tex_sub_image_2d_with_video_frame_and_width_and_height(
620                                dst_target,
621                                copy.dst_base.mip_level as i32,
622                                copy.dst_base.origin.x as i32,
623                                copy.dst_base.origin.y as i32,
624                                copy.size.width as i32,
625                                copy.size.height as i32,
626                                format_desc.external,
627                                format_desc.data_type,
628                                v,
629                            )
630                        },
631                        wgt::ExternalImageSource::ImageData(ref i) => unsafe {
632                            gl.tex_sub_image_2d_with_image_data_and_width_and_height(
633                                dst_target,
634                                copy.dst_base.mip_level as i32,
635                                copy.dst_base.origin.x as i32,
636                                copy.dst_base.origin.y as i32,
637                                copy.size.width as i32,
638                                copy.size.height as i32,
639                                format_desc.external,
640                                format_desc.data_type,
641                                i,
642                            );
643                        },
644                        wgt::ExternalImageSource::HTMLCanvasElement(ref c) => unsafe {
645                            gl.tex_sub_image_2d_with_html_canvas_and_width_and_height(
646                                dst_target,
647                                copy.dst_base.mip_level as i32,
648                                copy.dst_base.origin.x as i32,
649                                copy.dst_base.origin.y as i32,
650                                copy.size.width as i32,
651                                copy.size.height as i32,
652                                format_desc.external,
653                                format_desc.data_type,
654                                c,
655                            )
656                        },
657                        wgt::ExternalImageSource::OffscreenCanvas(_) => unreachable!(),
658                    }
659                }
660
661                unsafe {
662                    if src.flip_y {
663                        gl.pixel_store_bool(UNPACK_FLIP_Y_WEBGL, false);
664                    }
665                    if dst_premultiplication {
666                        gl.pixel_store_bool(UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
667                    }
668                }
669            }
670            C::CopyTextureToTexture(ref op) => {
671                let super::TextureToTextureCopy {
672                    src,
673                    src_target,
674                    dst,
675                    dst_target,
676                    ref copy,
677                } = **op;
678                //TODO: handle 3D copies
679                unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(self.copy_fbo)) };
680                if is_layered_target(src_target) {
681                    //TODO: handle GLES without framebuffer_texture_3d
682                    unsafe {
683                        gl.framebuffer_texture_layer(
684                            glow::READ_FRAMEBUFFER,
685                            glow::COLOR_ATTACHMENT0,
686                            Some(src),
687                            copy.src_base.mip_level as i32,
688                            copy.src_base.array_layer as i32,
689                        )
690                    };
691                } else {
692                    unsafe {
693                        gl.framebuffer_texture_2d(
694                            glow::READ_FRAMEBUFFER,
695                            glow::COLOR_ATTACHMENT0,
696                            src_target,
697                            Some(src),
698                            copy.src_base.mip_level as i32,
699                        )
700                    };
701                }
702
703                unsafe { gl.bind_texture(dst_target, Some(dst)) };
704                if is_layered_target(dst_target) {
705                    unsafe {
706                        gl.copy_tex_sub_image_3d(
707                            dst_target,
708                            copy.dst_base.mip_level as i32,
709                            copy.dst_base.origin.x as i32,
710                            copy.dst_base.origin.y as i32,
711                            get_z_offset(dst_target, &copy.dst_base) as i32,
712                            copy.src_base.origin.x as i32,
713                            copy.src_base.origin.y as i32,
714                            copy.size.width as i32,
715                            copy.size.height as i32,
716                        )
717                    };
718                } else {
719                    unsafe {
720                        gl.copy_tex_sub_image_2d(
721                            get_2d_target(dst_target, copy.dst_base.array_layer),
722                            copy.dst_base.mip_level as i32,
723                            copy.dst_base.origin.x as i32,
724                            copy.dst_base.origin.y as i32,
725                            copy.src_base.origin.x as i32,
726                            copy.src_base.origin.y as i32,
727                            copy.size.width as i32,
728                            copy.size.height as i32,
729                        )
730                    };
731                }
732            }
733            C::CopyCanvasToTexture(ref op) => {
734                let super::CanvasCopy {
735                    texture,
736                    target,
737                    ref copy,
738                } = **op;
739                // The default framebuffer is the canvas, read from its back
740                // buffer, which holds the frame drawn so far.
741                unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) };
742                unsafe { gl.bind_texture(target, Some(texture)) };
743                if is_layered_target(target) {
744                    unsafe {
745                        gl.copy_tex_sub_image_3d(
746                            target,
747                            copy.dst_base.mip_level as i32,
748                            copy.dst_base.origin.x as i32,
749                            copy.dst_base.origin.y as i32,
750                            get_z_offset(target, &copy.dst_base) as i32,
751                            copy.src_base.origin.x as i32,
752                            copy.src_base.origin.y as i32,
753                            copy.size.width as i32,
754                            copy.size.height as i32,
755                        )
756                    };
757                } else {
758                    unsafe {
759                        gl.copy_tex_sub_image_2d(
760                            get_2d_target(target, copy.dst_base.array_layer),
761                            copy.dst_base.mip_level as i32,
762                            copy.dst_base.origin.x as i32,
763                            copy.dst_base.origin.y as i32,
764                            copy.src_base.origin.x as i32,
765                            copy.src_base.origin.y as i32,
766                            copy.size.width as i32,
767                            copy.size.height as i32,
768                        )
769                    };
770                }
771            }
772            C::CopyTextureToCanvas(ref op) => {
773                let super::CanvasCopy {
774                    texture,
775                    target,
776                    ref copy,
777                } = **op;
778                unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(self.copy_fbo)) };
779                if is_layered_target(target) {
780                    unsafe {
781                        gl.framebuffer_texture_layer(
782                            glow::READ_FRAMEBUFFER,
783                            glow::COLOR_ATTACHMENT0,
784                            Some(texture),
785                            copy.src_base.mip_level as i32,
786                            copy.src_base.array_layer as i32,
787                        )
788                    };
789                } else {
790                    unsafe {
791                        gl.framebuffer_texture_2d(
792                            glow::READ_FRAMEBUFFER,
793                            glow::COLOR_ATTACHMENT0,
794                            target,
795                            Some(texture),
796                            copy.src_base.mip_level as i32,
797                        )
798                    };
799                }
800                unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) };
801                // A blit is clipped by the scissor test; a copy is not.
802                unsafe { gl.disable(glow::SCISSOR_TEST) };
803                let [src_x, src_y] = [copy.src_base.origin.x, copy.src_base.origin.y].map(|v| v as i32);
804                let [dst_x, dst_y] = [copy.dst_base.origin.x, copy.dst_base.origin.y].map(|v| v as i32);
805                let [width, height] = [copy.size.width, copy.size.height].map(|v| v as i32);
806                // Both hold the frame the same way up: no flip.
807                unsafe {
808                    gl.blit_framebuffer(
809                        src_x,
810                        src_y,
811                        src_x + width,
812                        src_y + height,
813                        dst_x,
814                        dst_y,
815                        dst_x + width,
816                        dst_y + height,
817                        glow::COLOR_BUFFER_BIT,
818                        glow::NEAREST,
819                    )
820                };
821            }
822            C::CopyBufferToTexture(ref op) => {
823                let super::BufferToTextureCopy {
824                    ref src,
825                    src_target: _,
826                    dst,
827                    dst_target,
828                    dst_format,
829                    ref copy,
830                } = **op;
831                let (block_width, block_height) = dst_format.block_dimensions();
832                let block_size = dst_format.block_copy_size(None).unwrap();
833                let format_desc = self.shared.describe_texture_format(dst_format);
834                let row_texels = copy
835                    .buffer_layout
836                    .bytes_per_row
837                    .map_or(0, |bpr| block_width * bpr / block_size);
838                let column_texels = copy
839                    .buffer_layout
840                    .rows_per_image
841                    .map_or(0, |rpi| block_height * rpi);
842
843                unsafe { gl.bind_texture(dst_target, Some(dst)) };
844                unsafe { gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, row_texels as i32) };
845                unsafe { gl.pixel_store_i32(glow::UNPACK_IMAGE_HEIGHT, column_texels as i32) };
846                let mut unbind_unpack_buffer = false;
847                if !dst_format.is_compressed() {
848                    let map_state;
849                    let unpack_data = match src.raw {
850                        Some(buffer) => {
851                            unsafe { gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, Some(buffer)) };
852                            unbind_unpack_buffer = true;
853                            glow::PixelUnpackData::BufferOffset(copy.buffer_layout.offset as u32)
854                        }
855                        None => {
856                            map_state = lock(&src.map_state);
857                            let src_data = &map_state.data.as_ref().unwrap().as_slice()
858                                [copy.buffer_layout.offset as usize..];
859                            glow::PixelUnpackData::Slice(Some(src_data))
860                        }
861                    };
862                    if is_layered_target(dst_target) {
863                        unsafe {
864                            gl.tex_sub_image_3d(
865                                dst_target,
866                                copy.texture_base.mip_level as i32,
867                                copy.texture_base.origin.x as i32,
868                                copy.texture_base.origin.y as i32,
869                                get_z_offset(dst_target, &copy.texture_base) as i32,
870                                copy.size.width as i32,
871                                copy.size.height as i32,
872                                copy.size.depth as i32,
873                                format_desc.external,
874                                format_desc.data_type,
875                                unpack_data,
876                            )
877                        };
878                    } else {
879                        unsafe {
880                            gl.tex_sub_image_2d(
881                                get_2d_target(dst_target, copy.texture_base.array_layer),
882                                copy.texture_base.mip_level as i32,
883                                copy.texture_base.origin.x as i32,
884                                copy.texture_base.origin.y as i32,
885                                copy.size.width as i32,
886                                copy.size.height as i32,
887                                format_desc.external,
888                                format_desc.data_type,
889                                unpack_data,
890                            )
891                        };
892                    }
893                } else {
894                    let bytes_per_row = copy
895                        .buffer_layout
896                        .bytes_per_row
897                        .unwrap_or(copy.size.width * block_size);
898                    let minimum_rows_per_image = copy.size.height.div_ceil(block_height);
899                    let rows_per_image = copy
900                        .buffer_layout
901                        .rows_per_image
902                        .unwrap_or(minimum_rows_per_image);
903
904                    let bytes_per_image = bytes_per_row * rows_per_image;
905                    let minimum_bytes_per_image = bytes_per_row * minimum_rows_per_image;
906                    let bytes_in_upload =
907                        (bytes_per_image * (copy.size.depth - 1)) + minimum_bytes_per_image;
908                    let offset = copy.buffer_layout.offset as u32;
909
910                    let map_state;
911                    let unpack_data = match src.raw {
912                        Some(buffer) => {
913                            unsafe { gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, Some(buffer)) };
914                            unbind_unpack_buffer = true;
915                            glow::CompressedPixelUnpackData::BufferRange(
916                                offset..offset + bytes_in_upload,
917                            )
918                        }
919                        None => {
920                            map_state = lock(&src.map_state);
921                            let src_data = &map_state.data.as_ref().unwrap().as_slice()
922                                [(offset as usize)..(offset + bytes_in_upload) as usize];
923                            glow::CompressedPixelUnpackData::Slice(src_data)
924                        }
925                    };
926
927                    if is_layered_target(dst_target) {
928                        unsafe {
929                            gl.compressed_tex_sub_image_3d(
930                                dst_target,
931                                copy.texture_base.mip_level as i32,
932                                copy.texture_base.origin.x as i32,
933                                copy.texture_base.origin.y as i32,
934                                get_z_offset(dst_target, &copy.texture_base) as i32,
935                                copy.size.width as i32,
936                                copy.size.height as i32,
937                                copy.size.depth as i32,
938                                format_desc.internal,
939                                unpack_data,
940                            )
941                        };
942                    } else {
943                        unsafe {
944                            gl.compressed_tex_sub_image_2d(
945                                get_2d_target(dst_target, copy.texture_base.array_layer),
946                                copy.texture_base.mip_level as i32,
947                                copy.texture_base.origin.x as i32,
948                                copy.texture_base.origin.y as i32,
949                                copy.size.width as i32,
950                                copy.size.height as i32,
951                                format_desc.internal,
952                                unpack_data,
953                            )
954                        };
955                    }
956                }
957                if unbind_unpack_buffer {
958                    unsafe { gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, None) };
959                }
960            }
961            C::CopyTextureToBuffer(ref op) => {
962                let super::TextureToBufferCopy {
963                    src,
964                    src_target,
965                    src_format,
966                    ref dst,
967                    dst_target: _,
968                    ref copy,
969                } = **op;
970                let block_size = src_format.block_copy_size(None).unwrap();
971                if src_format.is_compressed() {
972                    log::error!("Not implemented yet: compressed texture copy to buffer");
973                    return;
974                }
975                if src_target == glow::TEXTURE_CUBE_MAP
976                    || src_target == glow::TEXTURE_CUBE_MAP_ARRAY
977                {
978                    log::error!("Not implemented yet: cubemap texture copy to buffer");
979                    return;
980                }
981                let format_desc = self.shared.describe_texture_format(src_format);
982                let row_texels = copy
983                    .buffer_layout
984                    .bytes_per_row
985                    .map_or(copy.size.width, |bpr| bpr / block_size);
986                let column_texels = copy
987                    .buffer_layout
988                    .rows_per_image
989                    .unwrap_or(copy.size.height);
990
991                unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(self.copy_fbo)) };
992
993                let read_pixels = |offset| {
994                    let mut map_state;
995                    let unpack_data = match dst.raw {
996                        Some(buffer) => {
997                            unsafe { gl.pixel_store_i32(glow::PACK_ROW_LENGTH, row_texels as i32) };
998                            unsafe { gl.bind_buffer(glow::PIXEL_PACK_BUFFER, Some(buffer)) };
999                            glow::PixelPackData::BufferOffset(offset as u32)
1000                        }
1001                        None => {
1002                            map_state = lock(&dst.map_state);
1003                            let dst_data = &mut map_state.data.as_mut().unwrap().as_mut_slice()
1004                                [offset as usize..];
1005                            glow::PixelPackData::Slice(Some(dst_data))
1006                        }
1007                    };
1008                    unsafe {
1009                        gl.read_pixels(
1010                            copy.texture_base.origin.x as i32,
1011                            copy.texture_base.origin.y as i32,
1012                            copy.size.width as i32,
1013                            copy.size.height as i32,
1014                            format_desc.external,
1015                            format_desc.data_type,
1016                            unpack_data,
1017                        )
1018                    };
1019                };
1020
1021                match src_target {
1022                    glow::TEXTURE_2D => {
1023                        unsafe {
1024                            gl.framebuffer_texture_2d(
1025                                glow::READ_FRAMEBUFFER,
1026                                glow::COLOR_ATTACHMENT0,
1027                                src_target,
1028                                Some(src),
1029                                copy.texture_base.mip_level as i32,
1030                            )
1031                        };
1032                        read_pixels(copy.buffer_layout.offset);
1033                    }
1034                    glow::TEXTURE_2D_ARRAY => {
1035                        unsafe {
1036                            gl.framebuffer_texture_layer(
1037                                glow::READ_FRAMEBUFFER,
1038                                glow::COLOR_ATTACHMENT0,
1039                                Some(src),
1040                                copy.texture_base.mip_level as i32,
1041                                copy.texture_base.array_layer as i32,
1042                            )
1043                        };
1044                        read_pixels(copy.buffer_layout.offset);
1045                    }
1046                    glow::TEXTURE_3D => {
1047                        for z in copy.texture_base.origin.z..copy.size.depth {
1048                            unsafe {
1049                                gl.framebuffer_texture_layer(
1050                                    glow::READ_FRAMEBUFFER,
1051                                    glow::COLOR_ATTACHMENT0,
1052                                    Some(src),
1053                                    copy.texture_base.mip_level as i32,
1054                                    z as i32,
1055                                )
1056                            };
1057                            let offset = copy.buffer_layout.offset
1058                                + (z * block_size * row_texels * column_texels) as u64;
1059                            read_pixels(offset);
1060                        }
1061                    }
1062                    glow::TEXTURE_CUBE_MAP | glow::TEXTURE_CUBE_MAP_ARRAY => unimplemented!(),
1063                    _ => unreachable!(),
1064                }
1065            }
1066            C::SetIndexBuffer(buffer) => {
1067                unsafe { gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(buffer)) };
1068                let mut current_index_buffer = self.current_index_buffer.lock();
1069                *current_index_buffer = Some(buffer);
1070            }
1071            C::BeginQuery(query, target) => {
1072                unsafe { gl.begin_query(target, query) };
1073            }
1074            C::EndQuery(target) => {
1075                unsafe { gl.end_query(target) };
1076            }
1077            C::TimestampQuery(query) => {
1078                unsafe { gl.query_counter(query, glow::TIMESTAMP) };
1079            }
1080            C::CopyQueryResults(ref op) => {
1081                let super::QueryResultsCopy {
1082                    ref query_range,
1083                    ref dst,
1084                    dst_target,
1085                    dst_offset,
1086                } = **op;
1087                if self
1088                    .shared
1089                    .private_caps
1090                    .contains(PrivateCapabilities::QUERY_BUFFERS)
1091                    && dst.raw.is_some()
1092                {
1093                    unsafe {
1094                        // We're assuming that the only relevant queries are 8 byte timestamps or
1095                        // occlusion tests.
1096                        let query_size = 8;
1097
1098                        let query_range_size = query_size * query_range.len();
1099
1100                        let buffer = gl.create_buffer().ok();
1101                        gl.bind_buffer(glow::QUERY_BUFFER, buffer);
1102                        gl.buffer_data_size(
1103                            glow::QUERY_BUFFER,
1104                            query_range_size as _,
1105                            glow::STREAM_COPY,
1106                        );
1107
1108                        for (i, &query) in queries
1109                            [query_range.start as usize..query_range.end as usize]
1110                            .iter()
1111                            .enumerate()
1112                        {
1113                            gl.get_query_parameter_u64_with_offset(
1114                                query,
1115                                glow::QUERY_RESULT,
1116                                query_size * i,
1117                            )
1118                        }
1119                        gl.bind_buffer(dst_target, dst.raw);
1120                        gl.copy_buffer_sub_data(
1121                            glow::QUERY_BUFFER,
1122                            dst_target,
1123                            0,
1124                            dst_offset as _,
1125                            query_range_size as _,
1126                        );
1127                        if let Some(buffer) = buffer {
1128                            gl.delete_buffer(buffer)
1129                        }
1130                    }
1131                } else {
1132                    let mut temp_query_results = self.temp_query_results.lock();
1133                    temp_query_results.clear();
1134                    for &query in
1135                        queries[query_range.start as usize..query_range.end as usize].iter()
1136                    {
1137                        let mut result: u64 = 0;
1138                        unsafe {
1139                            if self
1140                                .shared
1141                                .private_caps
1142                                .contains(PrivateCapabilities::QUERY_64BIT)
1143                            {
1144                                let result: *mut u64 = &mut result;
1145                                gl.get_query_parameter_u64_with_offset(
1146                                    query,
1147                                    glow::QUERY_RESULT,
1148                                    result as usize,
1149                                )
1150                            } else {
1151                                result =
1152                                    gl.get_query_parameter_u32(query, glow::QUERY_RESULT) as u64;
1153                            }
1154                        };
1155                        temp_query_results.push(result);
1156                    }
1157                    let query_data = bytemuck::cast_slice(&temp_query_results);
1158                    match dst.raw {
1159                        Some(buffer) => {
1160                            unsafe { gl.bind_buffer(dst_target, Some(buffer)) };
1161                            unsafe {
1162                                gl.buffer_sub_data_u8_slice(
1163                                    dst_target,
1164                                    dst_offset as i32,
1165                                    query_data,
1166                                )
1167                            };
1168                        }
1169                        None => {
1170                            let mut map_state = lock(&dst.map_state);
1171                            let data = map_state.data.as_mut().unwrap();
1172                            let len = query_data.len().min(data.len());
1173                            data[..len].copy_from_slice(&query_data[..len]);
1174                        }
1175                    }
1176                }
1177            }
1178            C::ResetFramebuffer { is_default } => {
1179                if is_default {
1180                    unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) };
1181                } else {
1182                    unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, Some(self.draw_fbo)) };
1183                    unsafe {
1184                        gl.framebuffer_texture_2d(
1185                            glow::DRAW_FRAMEBUFFER,
1186                            glow::DEPTH_STENCIL_ATTACHMENT,
1187                            glow::TEXTURE_2D,
1188                            None,
1189                            0,
1190                        )
1191                    };
1192                    for i in 0..self.shared.limits.max_color_attachments {
1193                        let target = glow::COLOR_ATTACHMENT0 + i;
1194                        unsafe {
1195                            gl.framebuffer_texture_2d(
1196                                glow::DRAW_FRAMEBUFFER,
1197                                target,
1198                                glow::TEXTURE_2D,
1199                                None,
1200                                0,
1201                            )
1202                        };
1203                    }
1204                }
1205                unsafe { gl.color_mask(true, true, true, true) };
1206                unsafe { gl.depth_mask(true) };
1207                unsafe { gl.stencil_mask(!0) };
1208                unsafe { gl.disable(glow::DEPTH_TEST) };
1209                unsafe { gl.disable(glow::STENCIL_TEST) };
1210                unsafe { gl.disable(glow::SCISSOR_TEST) };
1211            }
1212            C::BindAttachment(ref op) => {
1213                let super::AttachmentBinding {
1214                    attachment,
1215                    ref view,
1216                    depth_slice,
1217                    sample_count,
1218                } = **op;
1219                unsafe {
1220                    self.set_attachment(
1221                        gl,
1222                        glow::DRAW_FRAMEBUFFER,
1223                        attachment,
1224                        view,
1225                        depth_slice,
1226                        sample_count,
1227                    )
1228                };
1229            }
1230            C::ResolveAttachment(ref op) => {
1231                let super::AttachmentResolve {
1232                    attachment,
1233                    ref dst,
1234                    ref size,
1235                } = **op;
1236                unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(self.draw_fbo)) };
1237                unsafe { gl.read_buffer(attachment) };
1238                unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, Some(self.copy_fbo)) };
1239                unsafe {
1240                    self.set_attachment(
1241                        gl,
1242                        glow::DRAW_FRAMEBUFFER,
1243                        glow::COLOR_ATTACHMENT0,
1244                        dst,
1245                        None,
1246                        1,
1247                    )
1248                };
1249                unsafe {
1250                    gl.blit_framebuffer(
1251                        0,
1252                        0,
1253                        size.width as i32,
1254                        size.height as i32,
1255                        0,
1256                        0,
1257                        size.width as i32,
1258                        size.height as i32,
1259                        glow::COLOR_BUFFER_BIT,
1260                        glow::NEAREST,
1261                    )
1262                };
1263                unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) };
1264                unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, Some(self.draw_fbo)) };
1265            }
1266            C::InvalidateAttachments(ref list) => {
1267                if self
1268                    .shared
1269                    .private_caps
1270                    .contains(PrivateCapabilities::INVALIDATE_FRAMEBUFFER)
1271                {
1272                    unsafe { gl.invalidate_framebuffer(glow::DRAW_FRAMEBUFFER, list) };
1273                }
1274            }
1275            C::SetDrawColorBuffers(count) => {
1276                self.draw_buffer_count.store(count, Ordering::Relaxed);
1277                let indices = (0..count as u32)
1278                    .map(|i| glow::COLOR_ATTACHMENT0 + i)
1279                    .collect::<ArrayVec<_, { crate::MAX_COLOR_ATTACHMENTS }>>();
1280                unsafe { gl.draw_buffers(&indices) };
1281            }
1282            C::ClearColorF {
1283                draw_buffer,
1284                ref color,
1285                is_srgb,
1286            } => {
1287                if self
1288                    .shared
1289                    .workarounds
1290                    .contains(super::Workarounds::MESA_I915_SRGB_SHADER_CLEAR)
1291                    && is_srgb
1292                {
1293                    unsafe { self.perform_shader_clear(gl, draw_buffer, *color) };
1294                } else {
1295                    unsafe { gl.clear_buffer_f32_slice(glow::COLOR, draw_buffer, color) };
1296                }
1297            }
1298            C::ClearColorU(draw_buffer, ref color) => {
1299                unsafe { gl.clear_buffer_u32_slice(glow::COLOR, draw_buffer, color) };
1300            }
1301            C::ClearColorI(draw_buffer, ref color) => {
1302                unsafe { gl.clear_buffer_i32_slice(glow::COLOR, draw_buffer, color) };
1303            }
1304            C::ClearDepth(depth) => {
1305                // Prefer `clear` as `clear_buffer` functions have issues on Sandy Bridge
1306                // on Windows.
1307                unsafe {
1308                    gl.clear_depth_f32(depth);
1309                    gl.clear(glow::DEPTH_BUFFER_BIT);
1310                }
1311            }
1312            C::ClearStencil(value) => {
1313                // Prefer `clear` as `clear_buffer` functions have issues on Sandy Bridge
1314                // on Windows.
1315                unsafe {
1316                    gl.clear_stencil(value as i32);
1317                    gl.clear(glow::STENCIL_BUFFER_BIT);
1318                }
1319            }
1320            C::ClearDepthAndStencil(depth, stencil_value) => {
1321                // Prefer `clear` as `clear_buffer` functions have issues on Sandy Bridge
1322                // on Windows.
1323                unsafe {
1324                    gl.clear_depth_f32(depth);
1325                    gl.clear_stencil(stencil_value as i32);
1326                    gl.clear(glow::DEPTH_BUFFER_BIT | glow::STENCIL_BUFFER_BIT);
1327                }
1328            }
1329            C::BufferBarrier(raw, usage) => {
1330                let mut flags = 0;
1331                if usage.contains(wgt::BufferUses::VERTEX) {
1332                    flags |= glow::VERTEX_ATTRIB_ARRAY_BARRIER_BIT;
1333                    unsafe { gl.bind_buffer(glow::ARRAY_BUFFER, Some(raw)) };
1334                    unsafe { gl.vertex_attrib_pointer_f32(0, 1, glow::BYTE, true, 0, 0) };
1335                }
1336                if usage.contains(wgt::BufferUses::INDEX) {
1337                    flags |= glow::ELEMENT_ARRAY_BARRIER_BIT;
1338                    unsafe { gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(raw)) };
1339                }
1340                if usage.contains(wgt::BufferUses::UNIFORM) {
1341                    flags |= glow::UNIFORM_BARRIER_BIT;
1342                }
1343                if usage.contains(wgt::BufferUses::INDIRECT) {
1344                    flags |= glow::COMMAND_BARRIER_BIT;
1345                    unsafe { gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(raw)) };
1346                }
1347                if usage.contains(wgt::BufferUses::COPY_SRC) {
1348                    flags |= glow::PIXEL_BUFFER_BARRIER_BIT;
1349                    unsafe { gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, Some(raw)) };
1350                }
1351                if usage.contains(wgt::BufferUses::COPY_DST) {
1352                    flags |= glow::PIXEL_BUFFER_BARRIER_BIT;
1353                    unsafe { gl.bind_buffer(glow::PIXEL_PACK_BUFFER, Some(raw)) };
1354                }
1355                if usage.intersects(wgt::BufferUses::MAP_READ | wgt::BufferUses::MAP_WRITE) {
1356                    flags |= glow::BUFFER_UPDATE_BARRIER_BIT;
1357                }
1358                if usage.intersects(
1359                    wgt::BufferUses::STORAGE_READ_ONLY | wgt::BufferUses::STORAGE_READ_WRITE,
1360                ) {
1361                    flags |= glow::SHADER_STORAGE_BARRIER_BIT;
1362                }
1363                unsafe { gl.memory_barrier(flags) };
1364            }
1365            // because `STORAGE_WRITE_ONLY` and `STORAGE_READ_WRITE` are only states
1366            // we can transit from due OpenGL memory barriers are used to make _subsequent_
1367            // operations see changes from the _shader_ side. We filter out usage changes that are
1368            // does not comes from the shader side in `transition_textures`
1369            C::TextureBarrier(usage) => {
1370                let mut flags = 0;
1371                if usage.contains(wgt::TextureUses::RESOURCE) {
1372                    flags |= glow::TEXTURE_FETCH_BARRIER_BIT;
1373                }
1374                if usage.intersects(
1375                    wgt::TextureUses::STORAGE_READ_ONLY
1376                        | wgt::TextureUses::STORAGE_WRITE_ONLY
1377                        | wgt::TextureUses::STORAGE_READ_WRITE,
1378                ) {
1379                    flags |= glow::SHADER_IMAGE_ACCESS_BARRIER_BIT;
1380                }
1381                if usage.intersects(wgt::TextureUses::COPY_SRC) {
1382                    flags |= glow::PIXEL_BUFFER_BARRIER_BIT;
1383                }
1384                if usage.contains(wgt::TextureUses::COPY_DST) {
1385                    flags |= glow::TEXTURE_UPDATE_BARRIER_BIT;
1386                }
1387                if usage.intersects(
1388                    wgt::TextureUses::COLOR_TARGET
1389                        | wgt::TextureUses::DEPTH_STENCIL_READ
1390                        | wgt::TextureUses::DEPTH_STENCIL_WRITE,
1391                ) {
1392                    flags |= glow::FRAMEBUFFER_BARRIER_BIT;
1393                }
1394                unsafe { gl.memory_barrier(flags) };
1395            }
1396            C::SetViewport {
1397                ref rect,
1398                ref depth,
1399            } => {
1400                unsafe { gl.viewport(rect.x, rect.y, rect.w, rect.h) };
1401                unsafe { gl.depth_range_f32(depth.start, depth.end) };
1402            }
1403            // `GlState::apply` runs these, issuing only the calls that change
1404            // the context's state.
1405            C::SetScissor(_)
1406            | C::SetStencilFunc { .. }
1407            | C::SetStencilOps { .. }
1408            | C::SetVertexAttribute {
1409                buffer: Some(_), ..
1410            }
1411            | C::UnsetVertexAttribute(_)
1412            | C::SetDepth(_)
1413            | C::ConfigureDepthStencil(_)
1414            | C::SetProgram(_)
1415            | C::BindSampler(..)
1416            | C::BindTexture { .. }
1417            | C::SetColorTarget {
1418                draw_buffer_index: None,
1419                ..
1420            } => {}
1421            C::SetVertexAttribute {
1422                buffer: None,
1423                buffer_desc: _,
1424                attribute_desc: ref vat,
1425            } => {
1426                unsafe { gl.bind_buffer(glow::ARRAY_BUFFER, None) };
1427                unsafe { gl.enable_vertex_attrib_array(vat.location) };
1428                match vat.format_desc.attrib_kind {
1429                    super::VertexAttribKind::Float => unsafe {
1430                        gl.vertex_attrib_format_f32(
1431                            vat.location,
1432                            vat.format_desc.element_count,
1433                            vat.format_desc.element_format,
1434                            true, // always normalized
1435                            vat.offset,
1436                        )
1437                    },
1438                    super::VertexAttribKind::Integer => unsafe {
1439                        gl.vertex_attrib_format_i32(
1440                            vat.location,
1441                            vat.format_desc.element_count,
1442                            vat.format_desc.element_format,
1443                            vat.offset,
1444                        )
1445                    },
1446                }
1447
1448                //Note: there is apparently a bug on AMD 3500U:
1449                // this call is ignored if the current array is disabled.
1450                unsafe { gl.vertex_attrib_binding(vat.location, vat.buffer_index) };
1451            }
1452            C::SetVertexBuffer {
1453                index,
1454                ref buffer,
1455                ref buffer_desc,
1456            } => {
1457                unsafe { gl.vertex_binding_divisor(index, buffer_desc.step as u32) };
1458                unsafe {
1459                    gl.bind_vertex_buffer(
1460                        index,
1461                        Some(buffer.raw),
1462                        buffer.offset as i32,
1463                        buffer_desc.stride as i32,
1464                    )
1465                };
1466            }
1467            C::SetDepthBias(bias) => {
1468                if bias.is_enabled() {
1469                    unsafe { gl.enable(glow::POLYGON_OFFSET_FILL) };
1470                    unsafe { gl.polygon_offset(bias.slope_scale, bias.constant as f32) };
1471                } else {
1472                    unsafe { gl.disable(glow::POLYGON_OFFSET_FILL) };
1473                }
1474            }
1475            C::SetAlphaToCoverage(enabled) => {
1476                if enabled {
1477                    unsafe { gl.enable(glow::SAMPLE_ALPHA_TO_COVERAGE) };
1478                } else {
1479                    unsafe { gl.disable(glow::SAMPLE_ALPHA_TO_COVERAGE) };
1480                }
1481            }
1482            C::SetPrimitive(ref state) => {
1483                unsafe { gl.front_face(state.front_face) };
1484                if state.cull_face != 0 {
1485                    unsafe { gl.enable(glow::CULL_FACE) };
1486                    unsafe { gl.cull_face(state.cull_face) };
1487                } else {
1488                    unsafe { gl.disable(glow::CULL_FACE) };
1489                }
1490                if self.features.contains(wgt::Features::DEPTH_CLIP_CONTROL) {
1491                    //Note: this is a bit tricky, since we are controlling the clip, not the clamp.
1492                    if state.unclipped_depth {
1493                        unsafe { gl.enable(glow::DEPTH_CLAMP) };
1494                    } else {
1495                        unsafe { gl.disable(glow::DEPTH_CLAMP) };
1496                    }
1497                }
1498                // POLYGON_MODE_LINE also implies POLYGON_MODE_POINT
1499                if self.features.contains(wgt::Features::POLYGON_MODE_LINE) {
1500                    unsafe { gl.polygon_mode(glow::FRONT_AND_BACK, state.polygon_mode) };
1501                }
1502            }
1503            C::SetBlendConstant(c) => {
1504                unsafe { gl.blend_color(c[0], c[1], c[2], c[3]) };
1505            }
1506            C::SetColorTarget {
1507                draw_buffer_index: Some(index),
1508                desc: super::ColorTargetDesc { mask, ref blend },
1509            } => {
1510                use wgt::ColorWrites as Cw;
1511                unsafe {
1512                    gl.color_mask_draw_buffer(
1513                        index,
1514                        mask.contains(Cw::RED),
1515                        mask.contains(Cw::GREEN),
1516                        mask.contains(Cw::BLUE),
1517                        mask.contains(Cw::ALPHA),
1518                    )
1519                };
1520                if let Some(ref blend) = *blend {
1521                    unsafe { gl.enable_draw_buffer(glow::BLEND, index) };
1522                    if blend.color != blend.alpha {
1523                        unsafe {
1524                            gl.blend_equation_separate_draw_buffer(
1525                                index,
1526                                blend.color.equation,
1527                                blend.alpha.equation,
1528                            )
1529                        };
1530                        unsafe {
1531                            gl.blend_func_separate_draw_buffer(
1532                                index,
1533                                blend.color.src,
1534                                blend.color.dst,
1535                                blend.alpha.src,
1536                                blend.alpha.dst,
1537                            )
1538                        };
1539                    } else {
1540                        unsafe { gl.blend_equation_draw_buffer(index, blend.color.equation) };
1541                        unsafe {
1542                            gl.blend_func_draw_buffer(index, blend.color.src, blend.color.dst)
1543                        };
1544                    }
1545                } else {
1546                    unsafe { gl.disable_draw_buffer(glow::BLEND, index) };
1547                }
1548            }
1549            C::BindBuffer {
1550                target,
1551                slot,
1552                buffer,
1553                offset,
1554                size,
1555            } => {
1556                unsafe { gl.bind_buffer_range(target, slot, Some(buffer), offset, size) };
1557            }
1558            C::BindImage { slot, ref binding } => {
1559                unsafe {
1560                    gl.bind_image_texture(
1561                        slot,
1562                        Some(binding.raw),
1563                        binding.mip_level as i32,
1564                        binding.array_layer.is_none(),
1565                        binding.array_layer.unwrap_or_default() as i32,
1566                        binding.access,
1567                        binding.format,
1568                    )
1569                };
1570            }
1571            C::InsertDebugMarker(ref range) => {
1572                if self
1573                    .shared
1574                    .private_caps
1575                    .contains(PrivateCapabilities::DEBUG_FNS)
1576                {
1577                    let marker = debug_text::marker(data_bytes, range);
1578                    unsafe { debug_text::insert_debug_marker(gl, marker) };
1579                }
1580            }
1581            C::PushDebugGroup(ref range) => {
1582                if self
1583                    .shared
1584                    .private_caps
1585                    .contains(PrivateCapabilities::DEBUG_FNS)
1586                {
1587                    let marker = debug_text::marker(data_bytes, range);
1588                    unsafe { debug_text::push_debug_group(gl, marker) };
1589                }
1590            }
1591            C::PopDebugGroup => {
1592                unsafe {
1593                    if self
1594                        .shared
1595                        .private_caps
1596                        .contains(PrivateCapabilities::DEBUG_FNS)
1597                    {
1598                        gl.pop_debug_group()
1599                    }
1600                };
1601            }
1602            C::SetImmediates { ref data } => {
1603                // Each uniform of the program from the block: one per stage
1604                // may read the same words, and those the program does not
1605                // use have no location.
1606                for uniform in program.into_iter().flat_map(|program| &program.immediates_descs) {
1607                    unsafe { set_immediate(gl, uniform, data_bytes, data.start + uniform.offset) };
1608                }
1609            }
1610            C::SetClipDistances {
1611                old_count,
1612                new_count,
1613            } => {
1614                // Disable clip planes that are no longer active
1615                for i in new_count..old_count {
1616                    unsafe { gl.disable(glow::CLIP_DISTANCE0 + i) };
1617                }
1618
1619                // Enable clip planes that are now active
1620                for i in old_count..new_count {
1621                    unsafe { gl.enable(glow::CLIP_DISTANCE0 + i) };
1622                }
1623            }
1624        }
1625    }
1626}
1627
1628impl crate::Queue for super::Queue {
1629    type A = super::Api;
1630
1631    unsafe fn submit(
1632        &self,
1633        command_buffers: &[&super::CommandBuffer],
1634        _surface_textures: &[&super::Texture],
1635        (signal_fence, signal_value): (&super::Fence, crate::FenceValue),
1636    ) -> Result<(), crate::DeviceError> {
1637        let shared = Arc::clone(&self.shared);
1638        let gl = &shared.context.lock();
1639        // Each link read waits for the GPU process to reach it. Read before
1640        // this submission's commands, it waits for the links alone; read
1641        // at the program's first draw, it also waits for every command sent
1642        // before that draw. In Chrome on a Mate 20 X the gauntlet's first
1643        // frame waited 16 ms in these reads instead of 34 on a second visit.
1644        let unread = shared.unread_links.load(Ordering::Relaxed);
1645        if unread > 0 {
1646            for command in command_buffers.iter().flat_map(|cmd_buf| cmd_buf.commands.iter()) {
1647                if let C::SetProgram(ref inner) = *command {
1648                    drop(unsafe { inner.read_link(gl, &shared.unread_links) });
1649                }
1650            }
1651            // The first read waited for the GPU process to run everything
1652            // sent before it, every link sent so far among them, so the
1653            // links no command here uses cost only their replies now. Read
1654            // at a later frame's first use, each would wait for the frames
1655            // sent before it: 12-43 ms in an early frame of the gauntlet in
1656            // Chrome on a Mate 20 X, for the one program its first frame
1657            // did not draw with.
1658            if shared.unread_links.load(Ordering::Relaxed) < unread {
1659                for program in shared.program_cache.lock().values().flatten() {
1660                    drop(unsafe { program.read_link(gl, &shared.unread_links) });
1661                }
1662            }
1663        }
1664        // A draw sets its program's emulated first instance unless the
1665        // context draws from a first instance of its own.
1666        let emulates_first_instance = !shared
1667            .private_caps
1668            .contains(PrivateCapabilities::FULLY_FEATURED_INSTANCING);
1669        let mut state = self.gl_state.lock();
1670        for cmd_buf in command_buffers.iter() {
1671            // The command encoder assumes a default state when encoding the command buffer.
1672            // Always reset the state between command_buffers to reflect this assumption. Do
1673            // this at the beginning of the loop in case something outside of wgpu modified
1674            // this state prior to commit.
1675            unsafe { self.reset_state(gl) };
1676            if let Some(ref label) = cmd_buf.label {
1677                if self
1678                    .shared
1679                    .private_caps
1680                    .contains(PrivateCapabilities::DEBUG_FNS)
1681                {
1682                    unsafe { debug_text::push_debug_group(gl, label) };
1683                }
1684            }
1685
1686            state.reset();
1687            // The program in use: its link is read at its first use, so
1688            // the GPU process links while the encoders record.
1689            let mut program = None;
1690            for command in cmd_buf.commands.iter() {
1691                if let C::SetProgram(ref inner) = *command {
1692                    program = Some(unsafe { inner.linked(gl, &shared.unread_links) });
1693                }
1694                let first_instance = program
1695                    .as_deref()
1696                    .and_then(|program| program.first_instance_location.as_ref())
1697                    .filter(|_| emulates_first_instance);
1698                if !unsafe { state.apply(gl, command, first_instance) } {
1699                    unsafe {
1700                        self.process(
1701                            gl,
1702                            command,
1703                            &cmd_buf.data_bytes,
1704                            &cmd_buf.queries,
1705                            program.as_deref(),
1706                        )
1707                    };
1708                }
1709            }
1710            unsafe { state.finish(gl) };
1711
1712            if cmd_buf.label.is_some()
1713                && self
1714                    .shared
1715                    .private_caps
1716                    .contains(PrivateCapabilities::DEBUG_FNS)
1717            {
1718                unsafe { gl.pop_debug_group() };
1719            }
1720        }
1721
1722        signal_fence.maintain(gl);
1723        signal_fence.signal(gl, signal_value)?;
1724
1725        // This is extremely important. If we don't flush, the above fences may never
1726        // be signaled, particularly in headless contexts. Headed contexts will
1727        // often flush every so often, but headless contexts may not.
1728        unsafe { gl.flush() };
1729
1730        Ok(())
1731    }
1732
1733    unsafe fn present(
1734        &self,
1735        surface: &super::Surface,
1736        texture: super::Texture,
1737    ) -> Result<(), crate::SurfaceError> {
1738        unsafe { surface.present(texture, &self.shared.context) }
1739    }
1740
1741    unsafe fn get_timestamp_period(&self) -> f32 {
1742        1.0
1743    }
1744
1745    unsafe fn wait_for_idle(&self) -> Result<(), crate::DeviceError> {
1746        let gl = &self.shared.context.lock();
1747        unsafe { gl.finish() };
1748        Ok(())
1749    }
1750}
1751
1752#[cfg(send_sync)]
1753unsafe impl Sync for super::Queue {}
1754#[cfg(send_sync)]
1755unsafe impl Send for super::Queue {}
1756
1757/// Sets `uniform` from its words at `offset` in `data`.
1758unsafe fn set_immediate(
1759    gl: &glow::Context,
1760    uniform: &super::ImmediateDesc,
1761    data_bytes: &[u8],
1762    offset: u32,
1763) {
1764    fn get_data<T, const COUNT: usize>(data: &[u8], offset: u32) -> [T; COUNT]
1765    where
1766        [T; COUNT]: bytemuck::AnyBitPattern,
1767    {
1768        let data_required = size_of::<T>() * COUNT;
1769        let raw = &data[(offset as usize)..][..data_required];
1770        bytemuck::pod_read_unaligned(raw)
1771    }
1772
1773    let location = Some(&uniform.location);
1774    use nt::glsl::{GlslScalar, GlslUniformType, GlslVectorSize};
1775    match uniform.ty {
1776        //
1777        // --- Float 1-4 Component ---
1778        //
1779        GlslUniformType::Scalar(GlslScalar::F32) => {
1780            let data = get_data::<f32, 1>(data_bytes, offset)[0];
1781            unsafe { gl.uniform_1_f32(location, data) };
1782        }
1783        GlslUniformType::Vector {
1784            size: GlslVectorSize::Bi,
1785            scalar: GlslScalar::F32,
1786        } => {
1787            let data = &get_data::<f32, 2>(data_bytes, offset);
1788            unsafe { gl.uniform_2_f32_slice(location, data) };
1789        }
1790        GlslUniformType::Vector {
1791            size: GlslVectorSize::Tri,
1792            scalar: GlslScalar::F32,
1793        } => {
1794            let data = &get_data::<f32, 3>(data_bytes, offset);
1795            unsafe { gl.uniform_3_f32_slice(location, data) };
1796        }
1797        GlslUniformType::Vector {
1798            size: GlslVectorSize::Quad,
1799            scalar: GlslScalar::F32,
1800        } => {
1801            let data = &get_data::<f32, 4>(data_bytes, offset);
1802            unsafe { gl.uniform_4_f32_slice(location, data) };
1803        }
1804
1805        //
1806        // --- Int 1-4 Component ---
1807        //
1808        GlslUniformType::Scalar(GlslScalar::I32) => {
1809            let data = get_data::<i32, 1>(data_bytes, offset)[0];
1810            unsafe { gl.uniform_1_i32(location, data) };
1811        }
1812        GlslUniformType::Vector {
1813            size: GlslVectorSize::Bi,
1814            scalar: GlslScalar::I32,
1815        } => {
1816            let data = &get_data::<i32, 2>(data_bytes, offset);
1817            unsafe { gl.uniform_2_i32_slice(location, data) };
1818        }
1819        GlslUniformType::Vector {
1820            size: GlslVectorSize::Tri,
1821            scalar: GlslScalar::I32,
1822        } => {
1823            let data = &get_data::<i32, 3>(data_bytes, offset);
1824            unsafe { gl.uniform_3_i32_slice(location, data) };
1825        }
1826        GlslUniformType::Vector {
1827            size: GlslVectorSize::Quad,
1828            scalar: GlslScalar::I32,
1829        } => {
1830            let data = &get_data::<i32, 4>(data_bytes, offset);
1831            unsafe { gl.uniform_4_i32_slice(location, data) };
1832        }
1833
1834        //
1835        // --- Uint 1-4 Component ---
1836        //
1837        GlslUniformType::Scalar(GlslScalar::U32) => {
1838            let data = get_data::<u32, 1>(data_bytes, offset)[0];
1839            unsafe { gl.uniform_1_u32(location, data) };
1840        }
1841        GlslUniformType::Vector {
1842            size: GlslVectorSize::Bi,
1843            scalar: GlslScalar::U32,
1844        } => {
1845            let data = &get_data::<u32, 2>(data_bytes, offset);
1846            unsafe { gl.uniform_2_u32_slice(location, data) };
1847        }
1848        GlslUniformType::Vector {
1849            size: GlslVectorSize::Tri,
1850            scalar: GlslScalar::U32,
1851        } => {
1852            let data = &get_data::<u32, 3>(data_bytes, offset);
1853            unsafe { gl.uniform_3_u32_slice(location, data) };
1854        }
1855        GlslUniformType::Vector {
1856            size: GlslVectorSize::Quad,
1857            scalar: GlslScalar::U32,
1858        } => {
1859            let data = &get_data::<u32, 4>(data_bytes, offset);
1860            unsafe { gl.uniform_4_u32_slice(location, data) };
1861        }
1862
1863        //
1864        // --- Matrix 2xR ---
1865        //
1866        GlslUniformType::Matrix {
1867            columns: GlslVectorSize::Bi,
1868            rows: GlslVectorSize::Bi,
1869            scalar: GlslScalar::F32,
1870        } => {
1871            let data = &get_data::<f32, 4>(data_bytes, offset);
1872            unsafe { gl.uniform_matrix_2_f32_slice(location, false, data) };
1873        }
1874        GlslUniformType::Matrix {
1875            columns: GlslVectorSize::Bi,
1876            rows: GlslVectorSize::Tri,
1877            scalar: GlslScalar::F32,
1878        } => {
1879            // repack 2 vec3s into 6 values.
1880            let unpacked_data = &get_data::<f32, 8>(data_bytes, offset);
1881            #[rustfmt::skip]
1882            let packed_data = [
1883                unpacked_data[0], unpacked_data[1], unpacked_data[2],
1884                unpacked_data[4], unpacked_data[5], unpacked_data[6],
1885            ];
1886            unsafe { gl.uniform_matrix_2x3_f32_slice(location, false, &packed_data) };
1887        }
1888        GlslUniformType::Matrix {
1889            columns: GlslVectorSize::Bi,
1890            rows: GlslVectorSize::Quad,
1891            scalar: GlslScalar::F32,
1892        } => {
1893            let data = &get_data::<f32, 8>(data_bytes, offset);
1894            unsafe { gl.uniform_matrix_2x4_f32_slice(location, false, data) };
1895        }
1896
1897        //
1898        // --- Matrix 3xR ---
1899        //
1900        GlslUniformType::Matrix {
1901            columns: GlslVectorSize::Tri,
1902            rows: GlslVectorSize::Bi,
1903            scalar: GlslScalar::F32,
1904        } => {
1905            let data = &get_data::<f32, 6>(data_bytes, offset);
1906            unsafe { gl.uniform_matrix_3x2_f32_slice(location, false, data) };
1907        }
1908        GlslUniformType::Matrix {
1909            columns: GlslVectorSize::Tri,
1910            rows: GlslVectorSize::Tri,
1911            scalar: GlslScalar::F32,
1912        } => {
1913            // repack 3 vec3s into 9 values.
1914            let unpacked_data = &get_data::<f32, 12>(data_bytes, offset);
1915            #[rustfmt::skip]
1916            let packed_data = [
1917                unpacked_data[0], unpacked_data[1], unpacked_data[2],
1918                unpacked_data[4], unpacked_data[5], unpacked_data[6],
1919                unpacked_data[8], unpacked_data[9], unpacked_data[10],
1920            ];
1921            unsafe { gl.uniform_matrix_3_f32_slice(location, false, &packed_data) };
1922        }
1923        GlslUniformType::Matrix {
1924            columns: GlslVectorSize::Tri,
1925            rows: GlslVectorSize::Quad,
1926            scalar: GlslScalar::F32,
1927        } => {
1928            let data = &get_data::<f32, 12>(data_bytes, offset);
1929            unsafe { gl.uniform_matrix_3x4_f32_slice(location, false, data) };
1930        }
1931
1932        //
1933        // --- Matrix 4xR ---
1934        //
1935        GlslUniformType::Matrix {
1936            columns: GlslVectorSize::Quad,
1937            rows: GlslVectorSize::Bi,
1938            scalar: GlslScalar::F32,
1939        } => {
1940            let data = &get_data::<f32, 8>(data_bytes, offset);
1941            unsafe { gl.uniform_matrix_4x2_f32_slice(location, false, data) };
1942        }
1943        GlslUniformType::Matrix {
1944            columns: GlslVectorSize::Quad,
1945            rows: GlslVectorSize::Tri,
1946            scalar: GlslScalar::F32,
1947        } => {
1948            // repack 4 vec3s into 12 values.
1949            let unpacked_data = &get_data::<f32, 16>(data_bytes, offset);
1950            #[rustfmt::skip]
1951            let packed_data = [
1952                unpacked_data[0], unpacked_data[1], unpacked_data[2],
1953                unpacked_data[4], unpacked_data[5], unpacked_data[6],
1954                unpacked_data[8], unpacked_data[9], unpacked_data[10],
1955                unpacked_data[12], unpacked_data[13], unpacked_data[14],
1956            ];
1957            unsafe { gl.uniform_matrix_4x3_f32_slice(location, false, &packed_data) };
1958        }
1959        GlslUniformType::Matrix {
1960            columns: GlslVectorSize::Quad,
1961            rows: GlslVectorSize::Quad,
1962            scalar: GlslScalar::F32,
1963        } => {
1964            let data = &get_data::<f32, 16>(data_bytes, offset);
1965            unsafe { gl.uniform_matrix_4_f32_slice(location, false, data) };
1966        }
1967        _ => panic!("Unsupported uniform datatype: {:?}!", uniform.ty),
1968    }
1969}