wgpu_hal/gles/
command.rs

1use alloc::string::String;
2use core::{mem, ops::Range};
3
4use arrayvec::ArrayVec;
5
6use super::{conv, Command as C};
7
8#[derive(Clone, Copy, Debug, Default)]
9struct TextureSlotDesc {
10    tex_target: super::BindTarget,
11    sampler_index: Option<u8>,
12}
13
14pub(super) struct State {
15    topology: u32,
16    primitive: super::PrimitiveState,
17    index_format: wgt::IndexFormat,
18    index_offset: wgt::BufferAddress,
19    vertex_buffers:
20        [(super::VertexBufferDesc, Option<super::BufferBinding>); crate::MAX_VERTEX_BUFFERS],
21    vertex_attributes: ArrayVec<super::AttributeDesc, { super::MAX_VERTEX_ATTRIBUTES }>,
22    color_targets: ArrayVec<super::ColorTargetDesc, { crate::MAX_COLOR_ATTACHMENTS }>,
23    stencil: super::StencilState,
24    depth_bias: wgt::DepthBiasState,
25    alpha_to_coverage_enabled: bool,
26    samplers: [Option<glow::Sampler>; super::MAX_SAMPLERS],
27    texture_slots: [TextureSlotDesc; super::MAX_TEXTURE_SLOTS],
28    render_size: wgt::Extent3d,
29    resolve_attachments: ArrayVec<(u32, super::TextureView), { crate::MAX_COLOR_ATTACHMENTS }>,
30    invalidate_attachments: ArrayVec<u32, { crate::MAX_COLOR_ATTACHMENTS + 2 }>,
31    has_pass_label: bool,
32    instance_vbuf_mask: usize,
33    dirty_vbuf_mask: usize,
34    active_first_instance: u32,
35    first_instance_location: Option<glow::UniformLocation>,
36    immediates_descs: ArrayVec<super::ImmediateDesc, { super::MAX_IMMEDIATES_COMMANDS }>,
37    // The current state of the immediate data block.
38    current_immediates_data: [u32; super::MAX_IMMEDIATES],
39    end_of_pass_timestamp: Option<glow::Query>,
40    clip_distance_count: u32,
41}
42
43impl Default for State {
44    fn default() -> Self {
45        Self {
46            topology: Default::default(),
47            primitive: Default::default(),
48            index_format: Default::default(),
49            index_offset: Default::default(),
50            vertex_buffers: Default::default(),
51            vertex_attributes: Default::default(),
52            color_targets: Default::default(),
53            stencil: Default::default(),
54            depth_bias: Default::default(),
55            alpha_to_coverage_enabled: Default::default(),
56            samplers: Default::default(),
57            texture_slots: Default::default(),
58            render_size: Default::default(),
59            resolve_attachments: Default::default(),
60            invalidate_attachments: Default::default(),
61            has_pass_label: Default::default(),
62            instance_vbuf_mask: Default::default(),
63            dirty_vbuf_mask: Default::default(),
64            active_first_instance: Default::default(),
65            first_instance_location: Default::default(),
66            immediates_descs: Default::default(),
67            current_immediates_data: [0; super::MAX_IMMEDIATES],
68            end_of_pass_timestamp: Default::default(),
69            clip_distance_count: Default::default(),
70        }
71    }
72}
73
74impl super::CommandBuffer {
75    fn clear(&mut self) {
76        self.label = None;
77        self.commands.clear();
78        self.data_bytes.clear();
79        self.queries.clear();
80    }
81
82    fn add_marker(&mut self, marker: &str) -> Range<u32> {
83        let start = self.data_bytes.len() as u32;
84        self.data_bytes.extend(marker.as_bytes());
85        start..self.data_bytes.len() as u32
86    }
87
88    fn add_immediates_data(&mut self, data: &[u32]) -> Range<u32> {
89        let data_raw = bytemuck::cast_slice(data);
90        let start = self.data_bytes.len();
91        assert!(start < u32::MAX as usize);
92        self.data_bytes.extend_from_slice(data_raw);
93        let end = self.data_bytes.len();
94        assert!(end < u32::MAX as usize);
95        (start as u32)..(end as u32)
96    }
97}
98
99impl Drop for super::CommandEncoder {
100    fn drop(&mut self) {
101        use crate::CommandEncoder;
102        unsafe { self.discard_encoding() }
103        self.counters.command_encoders.sub(1);
104    }
105}
106
107impl super::CommandEncoder {
108    fn rebind_stencil_func(&mut self) {
109        fn make(s: &super::StencilSide, face: u32) -> C {
110            C::SetStencilFunc {
111                face,
112                function: s.function,
113                reference: s.reference,
114                read_mask: s.mask_read,
115            }
116        }
117
118        let s = &self.state.stencil;
119        if s.front.function == s.back.function
120            && s.front.mask_read == s.back.mask_read
121            && s.front.reference == s.back.reference
122        {
123            self.cmd_buffer
124                .commands
125                .push(make(&s.front, glow::FRONT_AND_BACK));
126        } else {
127            self.cmd_buffer.commands.push(make(&s.front, glow::FRONT));
128            self.cmd_buffer.commands.push(make(&s.back, glow::BACK));
129        }
130    }
131
132    fn rebind_vertex_data(&mut self, first_instance: u32) {
133        if self
134            .private_caps
135            .contains(super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT)
136        {
137            for (index, pair) in self.state.vertex_buffers.iter().enumerate() {
138                if self.state.dirty_vbuf_mask & (1 << index) == 0 {
139                    continue;
140                }
141                let (buffer_desc, vb) = match *pair {
142                    // Not all dirty bindings are necessarily filled. Some may be unused.
143                    (_, None) => continue,
144                    (ref vb_desc, Some(ref vb)) => (vb_desc.clone(), vb),
145                };
146                let instance_offset = match buffer_desc.step {
147                    wgt::VertexStepMode::Vertex => 0,
148                    wgt::VertexStepMode::Instance => first_instance * buffer_desc.stride,
149                };
150
151                self.cmd_buffer.commands.push(C::SetVertexBuffer {
152                    index: index as u32,
153                    buffer: super::BufferBinding {
154                        raw: vb.raw,
155                        offset: vb.offset + instance_offset as wgt::BufferAddress,
156                    },
157                    buffer_desc,
158                });
159                self.state.dirty_vbuf_mask ^= 1 << index;
160            }
161        } else {
162            let mut vbuf_mask = 0;
163            for attribute in self.state.vertex_attributes.iter() {
164                if self.state.dirty_vbuf_mask & (1 << attribute.buffer_index) == 0 {
165                    continue;
166                }
167                let (buffer_desc, vb) =
168                    match self.state.vertex_buffers[attribute.buffer_index as usize] {
169                        // Not all dirty bindings are necessarily filled. Some may be unused.
170                        (_, None) => continue,
171                        (ref vb_desc, Some(ref vb)) => (vb_desc.clone(), vb),
172                    };
173
174                let mut attribute_desc = attribute.clone();
175                attribute_desc.offset += vb.offset as u32;
176                if buffer_desc.step == wgt::VertexStepMode::Instance {
177                    attribute_desc.offset += buffer_desc.stride * first_instance;
178                }
179
180                self.cmd_buffer.commands.push(C::SetVertexAttribute {
181                    buffer: Some(vb.raw),
182                    buffer_desc,
183                    attribute_desc,
184                });
185                vbuf_mask |= 1 << attribute.buffer_index;
186            }
187            self.state.dirty_vbuf_mask ^= vbuf_mask;
188        }
189    }
190
191    fn rebind_sampler_states(&mut self, dirty_textures: u32, dirty_samplers: u32) {
192        for (texture_index, slot) in self.state.texture_slots.iter().enumerate() {
193            if dirty_textures & (1 << texture_index) != 0
194                || slot
195                    .sampler_index
196                    .is_some_and(|si| dirty_samplers & (1 << si) != 0)
197            {
198                let sampler = slot
199                    .sampler_index
200                    .and_then(|si| self.state.samplers[si as usize]);
201                self.cmd_buffer
202                    .commands
203                    .push(C::BindSampler(texture_index as u32, sampler));
204            }
205        }
206    }
207
208    fn prepare_draw(&mut self, first_instance: u32) {
209        // If we support fully featured instancing, we want to bind everything as normal
210        // and let the draw call sort it out.
211        let emulated_first_instance_value = if self
212            .private_caps
213            .contains(super::PrivateCapabilities::FULLY_FEATURED_INSTANCING)
214        {
215            0
216        } else {
217            first_instance
218        };
219
220        if emulated_first_instance_value != self.state.active_first_instance {
221            // rebind all per-instance buffers on first-instance change
222            self.state.dirty_vbuf_mask |= self.state.instance_vbuf_mask;
223            self.state.active_first_instance = emulated_first_instance_value;
224        }
225        if self.state.dirty_vbuf_mask != 0 {
226            self.rebind_vertex_data(emulated_first_instance_value);
227        }
228    }
229
230    #[allow(clippy::clone_on_copy)] // False positive when cloning glow::UniformLocation
231    fn set_pipeline_inner(&mut self, inner: &super::PipelineInner) {
232        self.cmd_buffer.commands.push(C::SetProgram(inner.program));
233
234        self.state
235            .first_instance_location
236            .clone_from(&inner.first_instance_location);
237        self.state
238            .immediates_descs
239            .clone_from(&inner.immediates_descs);
240
241        // rebind textures, if needed
242        let mut dirty_textures = 0u32;
243        for (texture_index, (slot, &sampler_index)) in self
244            .state
245            .texture_slots
246            .iter_mut()
247            .zip(inner.sampler_map.iter())
248            .enumerate()
249        {
250            if slot.sampler_index != sampler_index {
251                slot.sampler_index = sampler_index;
252                dirty_textures |= 1 << texture_index;
253            }
254        }
255        if dirty_textures != 0 {
256            self.rebind_sampler_states(dirty_textures, 0);
257        }
258    }
259}
260
261impl crate::CommandEncoder for super::CommandEncoder {
262    type A = super::Api;
263
264    unsafe fn begin_encoding(&mut self, label: crate::Label) -> Result<(), crate::DeviceError> {
265        self.state = State::default();
266        self.cmd_buffer.label = label.map(String::from);
267        Ok(())
268    }
269    unsafe fn discard_encoding(&mut self) {
270        self.cmd_buffer.clear();
271    }
272    unsafe fn end_encoding(&mut self) -> Result<super::CommandBuffer, crate::DeviceError> {
273        Ok(mem::take(&mut self.cmd_buffer))
274    }
275    unsafe fn reset_all<I>(&mut self, _command_buffers: I) {
276        //TODO: could re-use the allocations in all these command buffers
277    }
278
279    unsafe fn transition_buffers<'a, T>(&mut self, barriers: T)
280    where
281        T: Iterator<Item = crate::BufferBarrier<'a, super::Buffer>>,
282    {
283        if !self
284            .private_caps
285            .contains(super::PrivateCapabilities::MEMORY_BARRIERS)
286        {
287            return;
288        }
289        for bar in barriers {
290            // GLES only synchronizes storage -> anything explicitly
291            if !bar.usage.from.contains(wgt::BufferUses::STORAGE_READ_WRITE) {
292                continue;
293            }
294            self.cmd_buffer
295                .commands
296                .push(C::BufferBarrier(bar.buffer.raw.unwrap(), bar.usage.to));
297        }
298    }
299
300    unsafe fn transition_textures<'a, T>(&mut self, barriers: T)
301    where
302        T: Iterator<Item = crate::TextureBarrier<'a, super::Texture>>,
303    {
304        if !self
305            .private_caps
306            .contains(super::PrivateCapabilities::MEMORY_BARRIERS)
307        {
308            return;
309        }
310
311        let mut combined_usage = wgt::TextureUses::empty();
312        for bar in barriers {
313            // GLES only synchronizes storage -> anything explicitly
314            // if shader writes to a texture then barriers should be placed
315            if !bar.usage.from.intersects(
316                wgt::TextureUses::STORAGE_READ_WRITE | wgt::TextureUses::STORAGE_WRITE_ONLY,
317            ) {
318                continue;
319            }
320            // unlike buffers, there is no need for a concrete texture
321            // object to be bound anywhere for a barrier
322            combined_usage |= bar.usage.to;
323        }
324
325        if !combined_usage.is_empty() {
326            self.cmd_buffer
327                .commands
328                .push(C::TextureBarrier(combined_usage));
329        }
330    }
331
332    unsafe fn clear_buffer(&mut self, buffer: &super::Buffer, range: crate::MemoryRange) {
333        self.cmd_buffer.commands.push(C::ClearBuffer {
334            dst: buffer.clone(),
335            dst_target: buffer.target,
336            range,
337        });
338    }
339
340    unsafe fn copy_buffer_to_buffer<T>(
341        &mut self,
342        src: &super::Buffer,
343        dst: &super::Buffer,
344        regions: T,
345    ) where
346        T: Iterator<Item = crate::BufferCopy>,
347    {
348        let (src_target, dst_target) = if src.target == dst.target {
349            (glow::COPY_READ_BUFFER, glow::COPY_WRITE_BUFFER)
350        } else {
351            (src.target, dst.target)
352        };
353        for copy in regions {
354            self.cmd_buffer.commands.push(C::CopyBufferToBuffer {
355                src: src.clone(),
356                src_target,
357                dst: dst.clone(),
358                dst_target,
359                copy,
360            })
361        }
362    }
363
364    #[cfg(webgl)]
365    unsafe fn copy_external_image_to_texture<T>(
366        &mut self,
367        src: &wgt::CopyExternalImageSourceInfo,
368        dst: &super::Texture,
369        dst_premultiplication: bool,
370        regions: T,
371    ) where
372        T: Iterator<Item = crate::TextureCopy>,
373    {
374        let (dst_raw, dst_target) = dst.inner.as_native();
375        for copy in regions {
376            self.cmd_buffer
377                .commands
378                .push(C::CopyExternalImageToTexture {
379                    src: src.clone(),
380                    dst: dst_raw,
381                    dst_target,
382                    dst_format: dst.format,
383                    dst_premultiplication,
384                    copy,
385                })
386        }
387    }
388
389    unsafe fn copy_texture_to_texture<T>(
390        &mut self,
391        src: &super::Texture,
392        _src_usage: wgt::TextureUses,
393        dst: &super::Texture,
394        regions: T,
395    ) where
396        T: Iterator<Item = crate::TextureCopy>,
397    {
398        let (src_raw, src_target) = src.inner.as_native();
399        let (dst_raw, dst_target) = dst.inner.as_native();
400        for mut copy in regions {
401            copy.clamp_size_to_virtual(&src.copy_size, &dst.copy_size);
402            self.cmd_buffer.commands.push(C::CopyTextureToTexture {
403                src: src_raw,
404                src_target,
405                dst: dst_raw,
406                dst_target,
407                copy,
408            })
409        }
410    }
411
412    unsafe fn copy_buffer_to_texture<T>(
413        &mut self,
414        src: &super::Buffer,
415        dst: &super::Texture,
416        regions: T,
417    ) where
418        T: Iterator<Item = crate::BufferTextureCopy>,
419    {
420        let (dst_raw, dst_target) = dst.inner.as_native();
421
422        for mut copy in regions {
423            copy.clamp_size_to_virtual(&dst.copy_size);
424            self.cmd_buffer.commands.push(C::CopyBufferToTexture {
425                src: src.clone(),
426                src_target: src.target,
427                dst: dst_raw,
428                dst_target,
429                dst_format: dst.format,
430                copy,
431            })
432        }
433    }
434
435    unsafe fn copy_texture_to_buffer<T>(
436        &mut self,
437        src: &super::Texture,
438        _src_usage: wgt::TextureUses,
439        dst: &super::Buffer,
440        regions: T,
441    ) where
442        T: Iterator<Item = crate::BufferTextureCopy>,
443    {
444        let (src_raw, src_target) = src.inner.as_native();
445        for mut copy in regions {
446            copy.clamp_size_to_virtual(&src.copy_size);
447            self.cmd_buffer.commands.push(C::CopyTextureToBuffer {
448                src: src_raw,
449                src_target,
450                src_format: src.format,
451                dst: dst.clone(),
452                dst_target: dst.target,
453                copy,
454            })
455        }
456    }
457
458    unsafe fn begin_query(&mut self, set: &super::QuerySet, index: u32) {
459        let query = set.queries[index as usize];
460        self.cmd_buffer
461            .commands
462            .push(C::BeginQuery(query, set.target));
463    }
464    unsafe fn end_query(&mut self, set: &super::QuerySet, _index: u32) {
465        self.cmd_buffer.commands.push(C::EndQuery(set.target));
466    }
467    unsafe fn write_timestamp(&mut self, set: &super::QuerySet, index: u32) {
468        let query = set.queries[index as usize];
469        self.cmd_buffer.commands.push(C::TimestampQuery(query));
470    }
471    unsafe fn reset_queries(&mut self, _set: &super::QuerySet, _range: Range<u32>) {
472        //TODO: what do we do here?
473    }
474    unsafe fn copy_query_results(
475        &mut self,
476        set: &super::QuerySet,
477        range: Range<u32>,
478        buffer: &super::Buffer,
479        offset: wgt::BufferAddress,
480        _stride: wgt::BufferSize,
481    ) {
482        let start = self.cmd_buffer.queries.len();
483        self.cmd_buffer
484            .queries
485            .extend_from_slice(&set.queries[range.start as usize..range.end as usize]);
486        let query_range = start as u32..self.cmd_buffer.queries.len() as u32;
487        self.cmd_buffer.commands.push(C::CopyQueryResults {
488            query_range,
489            dst: buffer.clone(),
490            dst_target: buffer.target,
491            dst_offset: offset,
492        });
493    }
494
495    // render
496
497    unsafe fn begin_render_pass(
498        &mut self,
499        desc: &crate::RenderPassDescriptor<super::QuerySet, super::TextureView>,
500    ) -> Result<(), crate::DeviceError> {
501        debug_assert!(self.state.end_of_pass_timestamp.is_none());
502        if let Some(ref t) = desc.timestamp_writes {
503            if let Some(index) = t.beginning_of_pass_write_index {
504                unsafe { self.write_timestamp(t.query_set, index) }
505            }
506            self.state.end_of_pass_timestamp = t
507                .end_of_pass_write_index
508                .map(|index| t.query_set.queries[index as usize]);
509        }
510
511        self.state.render_size = desc.extent;
512        self.state.resolve_attachments.clear();
513        self.state.invalidate_attachments.clear();
514        if let Some(label) = desc.label {
515            let range = self.cmd_buffer.add_marker(label);
516            self.cmd_buffer.commands.push(C::PushDebugGroup(range));
517            self.state.has_pass_label = true;
518        }
519
520        let rendering_to_external_framebuffer = desc
521            .color_attachments
522            .iter()
523            .filter_map(|at| at.as_ref())
524            .any(|at| match at.target.view.inner {
525                #[cfg(webgl)]
526                super::TextureInner::ExternalFramebuffer { .. } => true,
527                #[cfg(native)]
528                super::TextureInner::ExternalNativeFramebuffer { .. } => true,
529                _ => false,
530            });
531
532        if rendering_to_external_framebuffer && desc.color_attachments.len() != 1 {
533            panic!("Multiple render attachments with external framebuffers are not supported.");
534        }
535
536        // `COLOR_ATTACHMENT0` to `COLOR_ATTACHMENT31` gives 32 possible color attachments.
537        assert!(desc.color_attachments.len() <= 32);
538
539        match desc
540            .color_attachments
541            .first()
542            .filter(|at| at.is_some())
543            .and_then(|at| at.as_ref().map(|at| &at.target.view.inner))
544        {
545            // default framebuffer (provided externally)
546            Some(&super::TextureInner::DefaultRenderbuffer) => {
547                self.cmd_buffer
548                    .commands
549                    .push(C::ResetFramebuffer { is_default: true });
550            }
551            _ => {
552                // set the framebuffer
553                self.cmd_buffer
554                    .commands
555                    .push(C::ResetFramebuffer { is_default: false });
556
557                for (i, cat) in desc.color_attachments.iter().enumerate() {
558                    if let Some(cat) = cat.as_ref() {
559                        let attachment = glow::COLOR_ATTACHMENT0 + i as u32;
560                        self.cmd_buffer.commands.push(C::BindAttachment {
561                            attachment,
562                            view: cat.target.view.clone(),
563                            depth_slice: cat.depth_slice,
564                        });
565                        if let Some(ref rat) = cat.resolve_target {
566                            self.state
567                                .resolve_attachments
568                                .push((attachment, rat.view.clone()));
569                        }
570                        if cat.ops.contains(crate::AttachmentOps::STORE_DISCARD) {
571                            self.state.invalidate_attachments.push(attachment);
572                        }
573                    }
574                }
575                if let Some(ref dsat) = desc.depth_stencil_attachment {
576                    let aspects = dsat.target.view.aspects;
577                    let attachment = match aspects {
578                        crate::FormatAspects::DEPTH => glow::DEPTH_ATTACHMENT,
579                        crate::FormatAspects::STENCIL => glow::STENCIL_ATTACHMENT,
580                        _ => glow::DEPTH_STENCIL_ATTACHMENT,
581                    };
582                    self.cmd_buffer.commands.push(C::BindAttachment {
583                        attachment,
584                        view: dsat.target.view.clone(),
585                        depth_slice: None,
586                    });
587                    if aspects.contains(crate::FormatAspects::DEPTH)
588                        && dsat.depth_ops.contains(crate::AttachmentOps::STORE_DISCARD)
589                    {
590                        self.state
591                            .invalidate_attachments
592                            .push(glow::DEPTH_ATTACHMENT);
593                    }
594                    if aspects.contains(crate::FormatAspects::STENCIL)
595                        && dsat
596                            .stencil_ops
597                            .contains(crate::AttachmentOps::STORE_DISCARD)
598                    {
599                        self.state
600                            .invalidate_attachments
601                            .push(glow::STENCIL_ATTACHMENT);
602                    }
603                }
604            }
605        }
606
607        let rect = crate::Rect {
608            x: 0,
609            y: 0,
610            w: desc.extent.width as i32,
611            h: desc.extent.height as i32,
612        };
613        self.cmd_buffer.commands.push(C::SetScissor(rect.clone()));
614        self.cmd_buffer.commands.push(C::SetViewport {
615            rect,
616            depth: 0.0..1.0,
617        });
618
619        if !rendering_to_external_framebuffer {
620            // set the draw buffers and states
621            self.cmd_buffer
622                .commands
623                .push(C::SetDrawColorBuffers(desc.color_attachments.len() as u8));
624        }
625
626        // issue the clears
627        for (i, cat) in desc
628            .color_attachments
629            .iter()
630            .filter_map(|at| at.as_ref())
631            .enumerate()
632        {
633            if cat.ops.contains(crate::AttachmentOps::LOAD_CLEAR) {
634                let c = &cat.clear_value;
635                self.cmd_buffer.commands.push(
636                    match cat.target.view.format.sample_type(None, None).unwrap() {
637                        wgt::TextureSampleType::Float { .. } => C::ClearColorF {
638                            draw_buffer: i as u32,
639                            color: [c.r as f32, c.g as f32, c.b as f32, c.a as f32],
640                            is_srgb: cat.target.view.format.is_srgb(),
641                        },
642                        wgt::TextureSampleType::Uint => C::ClearColorU(
643                            i as u32,
644                            [c.r as u32, c.g as u32, c.b as u32, c.a as u32],
645                        ),
646                        wgt::TextureSampleType::Sint => C::ClearColorI(
647                            i as u32,
648                            [c.r as i32, c.g as i32, c.b as i32, c.a as i32],
649                        ),
650                        wgt::TextureSampleType::Depth => unreachable!(),
651                    },
652                );
653            }
654        }
655
656        if let Some(ref dsat) = desc.depth_stencil_attachment {
657            let clear_depth = dsat.depth_ops.contains(crate::AttachmentOps::LOAD_CLEAR);
658            let clear_stencil = dsat.stencil_ops.contains(crate::AttachmentOps::LOAD_CLEAR);
659
660            if clear_depth && clear_stencil {
661                self.cmd_buffer.commands.push(C::ClearDepthAndStencil(
662                    dsat.clear_value.0,
663                    dsat.clear_value.1,
664                ));
665            } else if clear_depth {
666                self.cmd_buffer
667                    .commands
668                    .push(C::ClearDepth(dsat.clear_value.0));
669            } else if clear_stencil {
670                self.cmd_buffer
671                    .commands
672                    .push(C::ClearStencil(dsat.clear_value.1));
673            }
674        }
675        Ok(())
676    }
677    unsafe fn end_render_pass(&mut self) {
678        for (attachment, dst) in self.state.resolve_attachments.drain(..) {
679            self.cmd_buffer.commands.push(C::ResolveAttachment {
680                attachment,
681                dst,
682                size: self.state.render_size,
683            });
684        }
685        if !self.state.invalidate_attachments.is_empty() {
686            self.cmd_buffer.commands.push(C::InvalidateAttachments(
687                self.state.invalidate_attachments.clone(),
688            ));
689            self.state.invalidate_attachments.clear();
690        }
691        if self.state.has_pass_label {
692            self.cmd_buffer.commands.push(C::PopDebugGroup);
693            self.state.has_pass_label = false;
694        }
695        self.state.instance_vbuf_mask = 0;
696        self.state.dirty_vbuf_mask = 0;
697        self.state.active_first_instance = 0;
698        self.state.color_targets.clear();
699        for vat in &self.state.vertex_attributes {
700            self.cmd_buffer
701                .commands
702                .push(C::UnsetVertexAttribute(vat.location));
703        }
704        self.state.vertex_attributes.clear();
705        self.state.primitive = super::PrimitiveState::default();
706
707        if let Some(query) = self.state.end_of_pass_timestamp.take() {
708            self.cmd_buffer.commands.push(C::TimestampQuery(query));
709        }
710    }
711
712    unsafe fn set_bind_group(
713        &mut self,
714        layout: &super::PipelineLayout,
715        index: u32,
716        group: &super::BindGroup,
717        dynamic_offsets: &[wgt::DynamicOffset],
718    ) {
719        let mut do_index = 0;
720        let mut dirty_textures = 0u32;
721        let mut dirty_samplers = 0u32;
722        let group_info = &layout.group_infos[index as usize];
723
724        for (binding_layout, raw_binding) in group_info.entries.iter().zip(group.contents.iter()) {
725            let slot = group_info.binding_to_slot[binding_layout.binding as usize] as u32;
726            match *raw_binding {
727                super::RawBinding::Buffer {
728                    raw,
729                    offset: base_offset,
730                    size,
731                } => {
732                    let mut offset = base_offset;
733                    let target = match binding_layout.ty {
734                        wgt::BindingType::Buffer {
735                            ty,
736                            has_dynamic_offset,
737                            min_binding_size: _,
738                        } => {
739                            if has_dynamic_offset {
740                                offset += dynamic_offsets[do_index] as i32;
741                                do_index += 1;
742                            }
743                            match ty {
744                                wgt::BufferBindingType::Uniform => glow::UNIFORM_BUFFER,
745                                wgt::BufferBindingType::Storage { .. } => {
746                                    glow::SHADER_STORAGE_BUFFER
747                                }
748                            }
749                        }
750                        _ => unreachable!(),
751                    };
752                    self.cmd_buffer.commands.push(C::BindBuffer {
753                        target,
754                        slot,
755                        buffer: raw,
756                        offset,
757                        size,
758                    });
759                }
760                super::RawBinding::Sampler(sampler) => {
761                    dirty_samplers |= 1 << slot;
762                    self.state.samplers[slot as usize] = Some(sampler);
763                }
764                super::RawBinding::Texture {
765                    raw,
766                    target,
767                    aspects,
768                    ref mip_levels,
769                } => {
770                    dirty_textures |= 1 << slot;
771                    self.state.texture_slots[slot as usize].tex_target = target;
772                    self.cmd_buffer.commands.push(C::BindTexture {
773                        slot,
774                        texture: raw,
775                        target,
776                        aspects,
777                        mip_levels: mip_levels.clone(),
778                    });
779                }
780                super::RawBinding::Image(ref binding) => {
781                    self.cmd_buffer.commands.push(C::BindImage {
782                        slot,
783                        binding: binding.clone(),
784                    });
785                }
786            }
787        }
788
789        self.rebind_sampler_states(dirty_textures, dirty_samplers);
790    }
791
792    unsafe fn set_immediates(
793        &mut self,
794        _layout: &super::PipelineLayout,
795        offset_bytes: u32,
796        data: &[u32],
797    ) {
798        // There is nothing preventing the user from trying to update a single value within
799        // a vector or matrix in the set_immediates call, as to the user, all of this is
800        // just memory. However OpenGL does not allow partial uniform updates.
801        //
802        // As such, we locally keep a copy of the current state of the immediate data memory
803        // block. If the user tries to update a single value, we have the data to update the entirety
804        // of the uniform.
805        let start_words = offset_bytes / 4;
806        let end_words = start_words + data.len() as u32;
807        self.state.current_immediates_data[start_words as usize..end_words as usize]
808            .copy_from_slice(data);
809
810        // We iterate over the uniform list as there may be multiple uniforms that need
811        // updating from the same immediate data memory (one for each shader stage).
812        //
813        // Additionally, any statically unused uniform descs will have been removed from this list
814        // by OpenGL, so the uniform list is not contiguous.
815        for uniform in self.state.immediates_descs.iter().cloned() {
816            let uniform_size_words = uniform.size_bytes / 4;
817            let uniform_start_words = uniform.offset / 4;
818            let uniform_end_words = uniform_start_words + uniform_size_words;
819
820            // Is true if any word within the uniform binding was updated
821            let needs_updating =
822                start_words < uniform_end_words || uniform_start_words <= end_words;
823
824            if needs_updating {
825                let uniform_data = &self.state.current_immediates_data
826                    [uniform_start_words as usize..uniform_end_words as usize];
827
828                let range = self.cmd_buffer.add_immediates_data(uniform_data);
829
830                self.cmd_buffer.commands.push(C::SetImmediates {
831                    uniform,
832                    offset: range.start,
833                });
834            }
835        }
836    }
837
838    unsafe fn insert_debug_marker(&mut self, label: &str) {
839        let range = self.cmd_buffer.add_marker(label);
840        self.cmd_buffer.commands.push(C::InsertDebugMarker(range));
841    }
842    unsafe fn begin_debug_marker(&mut self, group_label: &str) {
843        let range = self.cmd_buffer.add_marker(group_label);
844        self.cmd_buffer.commands.push(C::PushDebugGroup(range));
845    }
846    unsafe fn end_debug_marker(&mut self) {
847        self.cmd_buffer.commands.push(C::PopDebugGroup);
848    }
849
850    unsafe fn set_render_pipeline(&mut self, pipeline: &super::RenderPipeline) {
851        self.state.topology = conv::map_primitive_topology(pipeline.primitive.topology);
852
853        if self
854            .private_caps
855            .contains(super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT)
856        {
857            for vat in pipeline.vertex_attributes.iter() {
858                let vb = &pipeline.vertex_buffers[vat.buffer_index as usize];
859                // set the layout
860                self.cmd_buffer.commands.push(C::SetVertexAttribute {
861                    buffer: None,
862                    buffer_desc: vb.clone(),
863                    attribute_desc: vat.clone(),
864                });
865            }
866        } else {
867            for vat in &self.state.vertex_attributes {
868                self.cmd_buffer
869                    .commands
870                    .push(C::UnsetVertexAttribute(vat.location));
871            }
872            self.state.vertex_attributes.clear();
873
874            self.state.dirty_vbuf_mask = 0;
875            // copy vertex attributes
876            for vat in pipeline.vertex_attributes.iter() {
877                //Note: we can invalidate more carefully here.
878                self.state.dirty_vbuf_mask |= 1 << vat.buffer_index;
879                self.state.vertex_attributes.push(vat.clone());
880            }
881        }
882
883        self.state.instance_vbuf_mask = 0;
884        // copy vertex state
885        for (index, (&mut (ref mut state_desc, _), pipe_desc)) in self
886            .state
887            .vertex_buffers
888            .iter_mut()
889            .zip(pipeline.vertex_buffers.iter())
890            .enumerate()
891        {
892            if pipe_desc.step == wgt::VertexStepMode::Instance {
893                self.state.instance_vbuf_mask |= 1 << index;
894            }
895            if state_desc != pipe_desc {
896                self.state.dirty_vbuf_mask |= 1 << index;
897                *state_desc = pipe_desc.clone();
898            }
899        }
900
901        self.set_pipeline_inner(&pipeline.inner);
902
903        // set primitive state
904        let prim_state = conv::map_primitive_state(&pipeline.primitive);
905        if prim_state != self.state.primitive {
906            self.cmd_buffer
907                .commands
908                .push(C::SetPrimitive(prim_state.clone()));
909            self.state.primitive = prim_state;
910        }
911
912        // set depth/stencil states
913        let mut aspects = crate::FormatAspects::empty();
914        if pipeline.depth_bias != self.state.depth_bias {
915            self.state.depth_bias = pipeline.depth_bias;
916            self.cmd_buffer
917                .commands
918                .push(C::SetDepthBias(pipeline.depth_bias));
919        }
920        if let Some(ref depth) = pipeline.depth {
921            aspects |= crate::FormatAspects::DEPTH;
922            self.cmd_buffer.commands.push(C::SetDepth(depth.clone()));
923        }
924        if let Some(ref stencil) = pipeline.stencil {
925            aspects |= crate::FormatAspects::STENCIL;
926            self.state.stencil = stencil.clone();
927            self.rebind_stencil_func();
928            if stencil.front.ops == stencil.back.ops
929                && stencil.front.mask_write == stencil.back.mask_write
930            {
931                self.cmd_buffer.commands.push(C::SetStencilOps {
932                    face: glow::FRONT_AND_BACK,
933                    write_mask: stencil.front.mask_write,
934                    ops: stencil.front.ops.clone(),
935                });
936            } else {
937                self.cmd_buffer.commands.push(C::SetStencilOps {
938                    face: glow::FRONT,
939                    write_mask: stencil.front.mask_write,
940                    ops: stencil.front.ops.clone(),
941                });
942                self.cmd_buffer.commands.push(C::SetStencilOps {
943                    face: glow::BACK,
944                    write_mask: stencil.back.mask_write,
945                    ops: stencil.back.ops.clone(),
946                });
947            }
948        }
949        self.cmd_buffer
950            .commands
951            .push(C::ConfigureDepthStencil(aspects));
952
953        // set multisampling state
954        if pipeline.alpha_to_coverage_enabled != self.state.alpha_to_coverage_enabled {
955            self.state.alpha_to_coverage_enabled = pipeline.alpha_to_coverage_enabled;
956            self.cmd_buffer
957                .commands
958                .push(C::SetAlphaToCoverage(pipeline.alpha_to_coverage_enabled));
959        }
960
961        // set blend states
962        if self.state.color_targets[..] != pipeline.color_targets[..] {
963            if pipeline
964                .color_targets
965                .iter()
966                .skip(1)
967                .any(|ct| *ct != pipeline.color_targets[0])
968            {
969                for (index, ct) in pipeline.color_targets.iter().enumerate() {
970                    self.cmd_buffer.commands.push(C::SetColorTarget {
971                        draw_buffer_index: Some(index as u32),
972                        desc: ct.clone(),
973                    });
974                }
975            } else {
976                self.cmd_buffer.commands.push(C::SetColorTarget {
977                    draw_buffer_index: None,
978                    desc: pipeline.color_targets.first().cloned().unwrap_or_default(),
979                });
980            }
981        }
982        self.state.color_targets.clear();
983        for ct in pipeline.color_targets.iter() {
984            self.state.color_targets.push(ct.clone());
985        }
986
987        // set clip plane count
988        if pipeline.inner.clip_distance_count != self.state.clip_distance_count {
989            self.cmd_buffer.commands.push(C::SetClipDistances {
990                old_count: self.state.clip_distance_count,
991                new_count: pipeline.inner.clip_distance_count,
992            });
993            self.state.clip_distance_count = pipeline.inner.clip_distance_count;
994        }
995    }
996
997    unsafe fn set_index_buffer<'a>(
998        &mut self,
999        binding: crate::BufferBinding<'a, super::Buffer>,
1000        format: wgt::IndexFormat,
1001    ) {
1002        self.state.index_offset = binding.offset;
1003        self.state.index_format = format;
1004        self.cmd_buffer
1005            .commands
1006            .push(C::SetIndexBuffer(binding.buffer.raw.unwrap()));
1007    }
1008    unsafe fn set_vertex_buffer<'a>(
1009        &mut self,
1010        index: u32,
1011        binding: crate::BufferBinding<'a, super::Buffer>,
1012    ) {
1013        self.state.dirty_vbuf_mask |= 1 << index;
1014        let (_, ref mut vb) = self.state.vertex_buffers[index as usize];
1015        *vb = Some(super::BufferBinding {
1016            raw: binding.buffer.raw.unwrap(),
1017            offset: binding.offset,
1018        });
1019    }
1020    unsafe fn set_viewport(&mut self, rect: &crate::Rect<f32>, depth: Range<f32>) {
1021        self.cmd_buffer.commands.push(C::SetViewport {
1022            rect: crate::Rect {
1023                x: rect.x as i32,
1024                y: rect.y as i32,
1025                w: rect.w as i32,
1026                h: rect.h as i32,
1027            },
1028            depth,
1029        });
1030    }
1031    unsafe fn set_scissor_rect(&mut self, rect: &crate::Rect<u32>) {
1032        self.cmd_buffer.commands.push(C::SetScissor(crate::Rect {
1033            x: rect.x as i32,
1034            y: rect.y as i32,
1035            w: rect.w as i32,
1036            h: rect.h as i32,
1037        }));
1038    }
1039    unsafe fn set_stencil_reference(&mut self, value: u32) {
1040        self.state.stencil.front.reference = value;
1041        self.state.stencil.back.reference = value;
1042        self.rebind_stencil_func();
1043    }
1044    unsafe fn set_blend_constants(&mut self, color: &[f32; 4]) {
1045        self.cmd_buffer.commands.push(C::SetBlendConstant(*color));
1046    }
1047
1048    unsafe fn draw(
1049        &mut self,
1050        first_vertex: u32,
1051        vertex_count: u32,
1052        first_instance: u32,
1053        instance_count: u32,
1054    ) {
1055        self.prepare_draw(first_instance);
1056        #[allow(clippy::clone_on_copy)] // False positive when cloning glow::UniformLocation
1057        self.cmd_buffer.commands.push(C::Draw {
1058            topology: self.state.topology,
1059            first_vertex,
1060            vertex_count,
1061            first_instance,
1062            instance_count,
1063            first_instance_location: self.state.first_instance_location.clone(),
1064        });
1065    }
1066    unsafe fn draw_indexed(
1067        &mut self,
1068        first_index: u32,
1069        index_count: u32,
1070        base_vertex: i32,
1071        first_instance: u32,
1072        instance_count: u32,
1073    ) {
1074        self.prepare_draw(first_instance);
1075        let (index_size, index_type) = match self.state.index_format {
1076            wgt::IndexFormat::Uint16 => (2, glow::UNSIGNED_SHORT),
1077            wgt::IndexFormat::Uint32 => (4, glow::UNSIGNED_INT),
1078        };
1079        let index_offset = self.state.index_offset + index_size * first_index as wgt::BufferAddress;
1080        #[allow(clippy::clone_on_copy)] // False positive when cloning glow::UniformLocation
1081        self.cmd_buffer.commands.push(C::DrawIndexed {
1082            topology: self.state.topology,
1083            index_type,
1084            index_offset,
1085            index_count,
1086            base_vertex,
1087            first_instance,
1088            instance_count,
1089            first_instance_location: self.state.first_instance_location.clone(),
1090        });
1091    }
1092    unsafe fn draw_mesh_tasks(
1093        &mut self,
1094        _group_count_x: u32,
1095        _group_count_y: u32,
1096        _group_count_z: u32,
1097    ) {
1098        unreachable!()
1099    }
1100    unsafe fn draw_indirect(
1101        &mut self,
1102        buffer: &super::Buffer,
1103        offset: wgt::BufferAddress,
1104        draw_count: u32,
1105    ) {
1106        self.prepare_draw(0);
1107        for draw in 0..draw_count as wgt::BufferAddress {
1108            let indirect_offset =
1109                offset + draw * size_of::<wgt::DrawIndirectArgs>() as wgt::BufferAddress;
1110            #[allow(clippy::clone_on_copy)] // False positive when cloning glow::UniformLocation
1111            self.cmd_buffer.commands.push(C::DrawIndirect {
1112                topology: self.state.topology,
1113                indirect_buf: buffer.raw.unwrap(),
1114                indirect_offset,
1115                first_instance_location: self.state.first_instance_location.clone(),
1116            });
1117        }
1118    }
1119    unsafe fn draw_indexed_indirect(
1120        &mut self,
1121        buffer: &super::Buffer,
1122        offset: wgt::BufferAddress,
1123        draw_count: u32,
1124    ) {
1125        self.prepare_draw(0);
1126        let index_type = match self.state.index_format {
1127            wgt::IndexFormat::Uint16 => glow::UNSIGNED_SHORT,
1128            wgt::IndexFormat::Uint32 => glow::UNSIGNED_INT,
1129        };
1130        for draw in 0..draw_count as wgt::BufferAddress {
1131            let indirect_offset =
1132                offset + draw * size_of::<wgt::DrawIndexedIndirectArgs>() as wgt::BufferAddress;
1133            #[allow(clippy::clone_on_copy)] // False positive when cloning glow::UniformLocation
1134            self.cmd_buffer.commands.push(C::DrawIndexedIndirect {
1135                topology: self.state.topology,
1136                index_type,
1137                indirect_buf: buffer.raw.unwrap(),
1138                indirect_offset,
1139                first_instance_location: self.state.first_instance_location.clone(),
1140            });
1141        }
1142    }
1143    unsafe fn draw_mesh_tasks_indirect(
1144        &mut self,
1145        _buffer: &<Self::A as crate::Api>::Buffer,
1146        _offset: wgt::BufferAddress,
1147        _draw_count: u32,
1148    ) {
1149        unreachable!()
1150    }
1151    unsafe fn draw_indirect_count(
1152        &mut self,
1153        _buffer: &super::Buffer,
1154        _offset: wgt::BufferAddress,
1155        _count_buffer: &super::Buffer,
1156        _count_offset: wgt::BufferAddress,
1157        _max_count: u32,
1158    ) {
1159        unreachable!()
1160    }
1161    unsafe fn draw_indexed_indirect_count(
1162        &mut self,
1163        _buffer: &super::Buffer,
1164        _offset: wgt::BufferAddress,
1165        _count_buffer: &super::Buffer,
1166        _count_offset: wgt::BufferAddress,
1167        _max_count: u32,
1168    ) {
1169        unreachable!()
1170    }
1171    unsafe fn draw_mesh_tasks_indirect_count(
1172        &mut self,
1173        _buffer: &<Self::A as crate::Api>::Buffer,
1174        _offset: wgt::BufferAddress,
1175        _count_buffer: &<Self::A as crate::Api>::Buffer,
1176        _count_offset: wgt::BufferAddress,
1177        _max_count: u32,
1178    ) {
1179        unreachable!()
1180    }
1181
1182    // compute
1183
1184    unsafe fn begin_compute_pass(&mut self, desc: &crate::ComputePassDescriptor<super::QuerySet>) {
1185        debug_assert!(self.state.end_of_pass_timestamp.is_none());
1186        if let Some(ref t) = desc.timestamp_writes {
1187            if let Some(index) = t.beginning_of_pass_write_index {
1188                unsafe { self.write_timestamp(t.query_set, index) }
1189            }
1190            self.state.end_of_pass_timestamp = t
1191                .end_of_pass_write_index
1192                .map(|index| t.query_set.queries[index as usize]);
1193        }
1194
1195        if let Some(label) = desc.label {
1196            let range = self.cmd_buffer.add_marker(label);
1197            self.cmd_buffer.commands.push(C::PushDebugGroup(range));
1198            self.state.has_pass_label = true;
1199        }
1200    }
1201    unsafe fn end_compute_pass(&mut self) {
1202        if self.state.has_pass_label {
1203            self.cmd_buffer.commands.push(C::PopDebugGroup);
1204            self.state.has_pass_label = false;
1205        }
1206
1207        if let Some(query) = self.state.end_of_pass_timestamp.take() {
1208            self.cmd_buffer.commands.push(C::TimestampQuery(query));
1209        }
1210    }
1211
1212    unsafe fn set_compute_pipeline(&mut self, pipeline: &super::ComputePipeline) {
1213        self.set_pipeline_inner(&pipeline.inner);
1214    }
1215
1216    unsafe fn dispatch(&mut self, count: [u32; 3]) {
1217        // Empty dispatches are invalid in OpenGL, but valid in WebGPU.
1218        if count.contains(&0) {
1219            return;
1220        }
1221        self.cmd_buffer.commands.push(C::Dispatch(count));
1222    }
1223    unsafe fn dispatch_indirect(&mut self, buffer: &super::Buffer, offset: wgt::BufferAddress) {
1224        self.cmd_buffer.commands.push(C::DispatchIndirect {
1225            indirect_buf: buffer.raw.unwrap(),
1226            indirect_offset: offset,
1227        });
1228    }
1229
1230    unsafe fn build_acceleration_structures<'a, T>(
1231        &mut self,
1232        _descriptor_count: u32,
1233        _descriptors: T,
1234    ) where
1235        super::Api: 'a,
1236        T: IntoIterator<
1237            Item = crate::BuildAccelerationStructureDescriptor<
1238                'a,
1239                super::Buffer,
1240                super::AccelerationStructure,
1241            >,
1242        >,
1243    {
1244        unimplemented!()
1245    }
1246
1247    unsafe fn place_acceleration_structure_barrier(
1248        &mut self,
1249        _barriers: crate::AccelerationStructureBarrier,
1250    ) {
1251        unimplemented!()
1252    }
1253
1254    unsafe fn copy_acceleration_structure_to_acceleration_structure(
1255        &mut self,
1256        _src: &super::AccelerationStructure,
1257        _dst: &super::AccelerationStructure,
1258        _copy: wgt::AccelerationStructureCopy,
1259    ) {
1260        unimplemented!()
1261    }
1262
1263    unsafe fn read_acceleration_structure_compact_size(
1264        &mut self,
1265        _acceleration_structure: &super::AccelerationStructure,
1266        _buf: &super::Buffer,
1267    ) {
1268        unimplemented!()
1269    }
1270}