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