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    push_constant_descs: ArrayVec<super::PushConstantDesc, { super::MAX_PUSH_CONSTANT_COMMANDS }>,
37    // The current state of the push constant data block.
38    current_push_constant_data: [u32; super::MAX_PUSH_CONSTANTS],
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            push_constant_descs: Default::default(),
67            current_push_constant_data: [0; super::MAX_PUSH_CONSTANTS],
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_push_constant_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            .push_constant_descs
239            .clone_from(&inner.push_constant_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 !bar
315                .usage
316                .from
317                .contains(wgt::TextureUses::STORAGE_READ_WRITE)
318            {
319                continue;
320            }
321            // unlike buffers, there is no need for a concrete texture
322            // object to be bound anywhere for a barrier
323            combined_usage |= bar.usage.to;
324        }
325
326        if !combined_usage.is_empty() {
327            self.cmd_buffer
328                .commands
329                .push(C::TextureBarrier(combined_usage));
330        }
331    }
332
333    unsafe fn clear_buffer(&mut self, buffer: &super::Buffer, range: crate::MemoryRange) {
334        self.cmd_buffer.commands.push(C::ClearBuffer {
335            dst: buffer.clone(),
336            dst_target: buffer.target,
337            range,
338        });
339    }
340
341    unsafe fn copy_buffer_to_buffer<T>(
342        &mut self,
343        src: &super::Buffer,
344        dst: &super::Buffer,
345        regions: T,
346    ) where
347        T: Iterator<Item = crate::BufferCopy>,
348    {
349        let (src_target, dst_target) = if src.target == dst.target {
350            (glow::COPY_READ_BUFFER, glow::COPY_WRITE_BUFFER)
351        } else {
352            (src.target, dst.target)
353        };
354        for copy in regions {
355            self.cmd_buffer.commands.push(C::CopyBufferToBuffer {
356                src: src.clone(),
357                src_target,
358                dst: dst.clone(),
359                dst_target,
360                copy,
361            })
362        }
363    }
364
365    #[cfg(webgl)]
366    unsafe fn copy_external_image_to_texture<T>(
367        &mut self,
368        src: &wgt::CopyExternalImageSourceInfo,
369        dst: &super::Texture,
370        dst_premultiplication: bool,
371        regions: T,
372    ) where
373        T: Iterator<Item = crate::TextureCopy>,
374    {
375        let (dst_raw, dst_target) = dst.inner.as_native();
376        for copy in regions {
377            self.cmd_buffer
378                .commands
379                .push(C::CopyExternalImageToTexture {
380                    src: src.clone(),
381                    dst: dst_raw,
382                    dst_target,
383                    dst_format: dst.format,
384                    dst_premultiplication,
385                    copy,
386                })
387        }
388    }
389
390    unsafe fn copy_texture_to_texture<T>(
391        &mut self,
392        src: &super::Texture,
393        _src_usage: wgt::TextureUses,
394        dst: &super::Texture,
395        regions: T,
396    ) where
397        T: Iterator<Item = crate::TextureCopy>,
398    {
399        let (src_raw, src_target) = src.inner.as_native();
400        let (dst_raw, dst_target) = dst.inner.as_native();
401        for mut copy in regions {
402            copy.clamp_size_to_virtual(&src.copy_size, &dst.copy_size);
403            self.cmd_buffer.commands.push(C::CopyTextureToTexture {
404                src: src_raw,
405                src_target,
406                dst: dst_raw,
407                dst_target,
408                copy,
409            })
410        }
411    }
412
413    unsafe fn copy_buffer_to_texture<T>(
414        &mut self,
415        src: &super::Buffer,
416        dst: &super::Texture,
417        regions: T,
418    ) where
419        T: Iterator<Item = crate::BufferTextureCopy>,
420    {
421        let (dst_raw, dst_target) = dst.inner.as_native();
422
423        for mut copy in regions {
424            copy.clamp_size_to_virtual(&dst.copy_size);
425            self.cmd_buffer.commands.push(C::CopyBufferToTexture {
426                src: src.clone(),
427                src_target: src.target,
428                dst: dst_raw,
429                dst_target,
430                dst_format: dst.format,
431                copy,
432            })
433        }
434    }
435
436    unsafe fn copy_texture_to_buffer<T>(
437        &mut self,
438        src: &super::Texture,
439        _src_usage: wgt::TextureUses,
440        dst: &super::Buffer,
441        regions: T,
442    ) where
443        T: Iterator<Item = crate::BufferTextureCopy>,
444    {
445        let (src_raw, src_target) = src.inner.as_native();
446        for mut copy in regions {
447            copy.clamp_size_to_virtual(&src.copy_size);
448            self.cmd_buffer.commands.push(C::CopyTextureToBuffer {
449                src: src_raw,
450                src_target,
451                src_format: src.format,
452                dst: dst.clone(),
453                dst_target: dst.target,
454                copy,
455            })
456        }
457    }
458
459    unsafe fn begin_query(&mut self, set: &super::QuerySet, index: u32) {
460        let query = set.queries[index as usize];
461        self.cmd_buffer
462            .commands
463            .push(C::BeginQuery(query, set.target));
464    }
465    unsafe fn end_query(&mut self, set: &super::QuerySet, _index: u32) {
466        self.cmd_buffer.commands.push(C::EndQuery(set.target));
467    }
468    unsafe fn write_timestamp(&mut self, set: &super::QuerySet, index: u32) {
469        let query = set.queries[index as usize];
470        self.cmd_buffer.commands.push(C::TimestampQuery(query));
471    }
472    unsafe fn reset_queries(&mut self, _set: &super::QuerySet, _range: Range<u32>) {
473        //TODO: what do we do here?
474    }
475    unsafe fn copy_query_results(
476        &mut self,
477        set: &super::QuerySet,
478        range: Range<u32>,
479        buffer: &super::Buffer,
480        offset: wgt::BufferAddress,
481        _stride: wgt::BufferSize,
482    ) {
483        let start = self.cmd_buffer.queries.len();
484        self.cmd_buffer
485            .queries
486            .extend_from_slice(&set.queries[range.start as usize..range.end as usize]);
487        let query_range = start as u32..self.cmd_buffer.queries.len() as u32;
488        self.cmd_buffer.commands.push(C::CopyQueryResults {
489            query_range,
490            dst: buffer.clone(),
491            dst_target: buffer.target,
492            dst_offset: offset,
493        });
494    }
495
496    // render
497
498    unsafe fn begin_render_pass(
499        &mut self,
500        desc: &crate::RenderPassDescriptor<super::QuerySet, super::TextureView>,
501    ) -> Result<(), crate::DeviceError> {
502        debug_assert!(self.state.end_of_pass_timestamp.is_none());
503        if let Some(ref t) = desc.timestamp_writes {
504            if let Some(index) = t.beginning_of_pass_write_index {
505                unsafe { self.write_timestamp(t.query_set, index) }
506            }
507            self.state.end_of_pass_timestamp = t
508                .end_of_pass_write_index
509                .map(|index| t.query_set.queries[index as usize]);
510        }
511
512        self.state.render_size = desc.extent;
513        self.state.resolve_attachments.clear();
514        self.state.invalidate_attachments.clear();
515        if let Some(label) = desc.label {
516            let range = self.cmd_buffer.add_marker(label);
517            self.cmd_buffer.commands.push(C::PushDebugGroup(range));
518            self.state.has_pass_label = true;
519        }
520
521        let rendering_to_external_framebuffer = desc
522            .color_attachments
523            .iter()
524            .filter_map(|at| at.as_ref())
525            .any(|at| match at.target.view.inner {
526                #[cfg(webgl)]
527                super::TextureInner::ExternalFramebuffer { .. } => true,
528                #[cfg(native)]
529                super::TextureInner::ExternalNativeFramebuffer { .. } => true,
530                _ => false,
531            });
532
533        if rendering_to_external_framebuffer && desc.color_attachments.len() != 1 {
534            panic!("Multiple render attachments with external framebuffers are not supported.");
535        }
536
537        // `COLOR_ATTACHMENT0` to `COLOR_ATTACHMENT31` gives 32 possible color attachments.
538        assert!(desc.color_attachments.len() <= 32);
539
540        match desc
541            .color_attachments
542            .first()
543            .filter(|at| at.is_some())
544            .and_then(|at| at.as_ref().map(|at| &at.target.view.inner))
545        {
546            // default framebuffer (provided externally)
547            Some(&super::TextureInner::DefaultRenderbuffer) => {
548                self.cmd_buffer
549                    .commands
550                    .push(C::ResetFramebuffer { is_default: true });
551            }
552            _ => {
553                // set the framebuffer
554                self.cmd_buffer
555                    .commands
556                    .push(C::ResetFramebuffer { is_default: false });
557
558                for (i, cat) in desc.color_attachments.iter().enumerate() {
559                    if let Some(cat) = cat.as_ref() {
560                        let attachment = glow::COLOR_ATTACHMENT0 + i as u32;
561                        self.cmd_buffer.commands.push(C::BindAttachment {
562                            attachment,
563                            view: cat.target.view.clone(),
564                            depth_slice: cat.depth_slice,
565                        });
566                        if let Some(ref rat) = cat.resolve_target {
567                            self.state
568                                .resolve_attachments
569                                .push((attachment, rat.view.clone()));
570                        }
571                        if !cat.ops.contains(crate::AttachmentOps::STORE) {
572                            self.state.invalidate_attachments.push(attachment);
573                        }
574                    }
575                }
576                if let Some(ref dsat) = desc.depth_stencil_attachment {
577                    let aspects = dsat.target.view.aspects;
578                    let attachment = match aspects {
579                        crate::FormatAspects::DEPTH => glow::DEPTH_ATTACHMENT,
580                        crate::FormatAspects::STENCIL => glow::STENCIL_ATTACHMENT,
581                        _ => glow::DEPTH_STENCIL_ATTACHMENT,
582                    };
583                    self.cmd_buffer.commands.push(C::BindAttachment {
584                        attachment,
585                        view: dsat.target.view.clone(),
586                        depth_slice: None,
587                    });
588                    if aspects.contains(crate::FormatAspects::DEPTH)
589                        && !dsat.depth_ops.contains(crate::AttachmentOps::STORE)
590                    {
591                        self.state
592                            .invalidate_attachments
593                            .push(glow::DEPTH_ATTACHMENT);
594                    }
595                    if aspects.contains(crate::FormatAspects::STENCIL)
596                        && !dsat.stencil_ops.contains(crate::AttachmentOps::STORE)
597                    {
598                        self.state
599                            .invalidate_attachments
600                            .push(glow::STENCIL_ATTACHMENT);
601                    }
602                }
603            }
604        }
605
606        let rect = crate::Rect {
607            x: 0,
608            y: 0,
609            w: desc.extent.width as i32,
610            h: desc.extent.height as i32,
611        };
612        self.cmd_buffer.commands.push(C::SetScissor(rect.clone()));
613        self.cmd_buffer.commands.push(C::SetViewport {
614            rect,
615            depth: 0.0..1.0,
616        });
617
618        if !rendering_to_external_framebuffer {
619            // set the draw buffers and states
620            self.cmd_buffer
621                .commands
622                .push(C::SetDrawColorBuffers(desc.color_attachments.len() as u8));
623        }
624
625        // issue the clears
626        for (i, cat) in desc
627            .color_attachments
628            .iter()
629            .filter_map(|at| at.as_ref())
630            .enumerate()
631        {
632            if !cat.ops.contains(crate::AttachmentOps::LOAD) {
633                let c = &cat.clear_value;
634                self.cmd_buffer.commands.push(
635                    match cat.target.view.format.sample_type(None, None).unwrap() {
636                        wgt::TextureSampleType::Float { .. } => C::ClearColorF {
637                            draw_buffer: i as u32,
638                            color: [c.r as f32, c.g as f32, c.b as f32, c.a as f32],
639                            is_srgb: cat.target.view.format.is_srgb(),
640                        },
641                        wgt::TextureSampleType::Uint => C::ClearColorU(
642                            i as u32,
643                            [c.r as u32, c.g as u32, c.b as u32, c.a as u32],
644                        ),
645                        wgt::TextureSampleType::Sint => C::ClearColorI(
646                            i as u32,
647                            [c.r as i32, c.g as i32, c.b as i32, c.a as i32],
648                        ),
649                        wgt::TextureSampleType::Depth => unreachable!(),
650                    },
651                );
652            }
653        }
654
655        if let Some(ref dsat) = desc.depth_stencil_attachment {
656            let clear_depth = !dsat.depth_ops.contains(crate::AttachmentOps::LOAD);
657            let clear_stencil = !dsat.stencil_ops.contains(crate::AttachmentOps::LOAD);
658
659            if clear_depth && clear_stencil {
660                self.cmd_buffer.commands.push(C::ClearDepthAndStencil(
661                    dsat.clear_value.0,
662                    dsat.clear_value.1,
663                ));
664            } else if clear_depth {
665                self.cmd_buffer
666                    .commands
667                    .push(C::ClearDepth(dsat.clear_value.0));
668            } else if clear_stencil {
669                self.cmd_buffer
670                    .commands
671                    .push(C::ClearStencil(dsat.clear_value.1));
672            }
673        }
674        Ok(())
675    }
676    unsafe fn end_render_pass(&mut self) {
677        for (attachment, dst) in self.state.resolve_attachments.drain(..) {
678            self.cmd_buffer.commands.push(C::ResolveAttachment {
679                attachment,
680                dst,
681                size: self.state.render_size,
682            });
683        }
684        if !self.state.invalidate_attachments.is_empty() {
685            self.cmd_buffer.commands.push(C::InvalidateAttachments(
686                self.state.invalidate_attachments.clone(),
687            ));
688            self.state.invalidate_attachments.clear();
689        }
690        if self.state.has_pass_label {
691            self.cmd_buffer.commands.push(C::PopDebugGroup);
692            self.state.has_pass_label = false;
693        }
694        self.state.instance_vbuf_mask = 0;
695        self.state.dirty_vbuf_mask = 0;
696        self.state.active_first_instance = 0;
697        self.state.color_targets.clear();
698        for vat in &self.state.vertex_attributes {
699            self.cmd_buffer
700                .commands
701                .push(C::UnsetVertexAttribute(vat.location));
702        }
703        self.state.vertex_attributes.clear();
704        self.state.primitive = super::PrimitiveState::default();
705
706        if let Some(query) = self.state.end_of_pass_timestamp.take() {
707            self.cmd_buffer.commands.push(C::TimestampQuery(query));
708        }
709    }
710
711    unsafe fn set_bind_group(
712        &mut self,
713        layout: &super::PipelineLayout,
714        index: u32,
715        group: &super::BindGroup,
716        dynamic_offsets: &[wgt::DynamicOffset],
717    ) {
718        let mut do_index = 0;
719        let mut dirty_textures = 0u32;
720        let mut dirty_samplers = 0u32;
721        let group_info = &layout.group_infos[index as usize];
722
723        for (binding_layout, raw_binding) in group_info.entries.iter().zip(group.contents.iter()) {
724            let slot = group_info.binding_to_slot[binding_layout.binding as usize] as u32;
725            match *raw_binding {
726                super::RawBinding::Buffer {
727                    raw,
728                    offset: base_offset,
729                    size,
730                } => {
731                    let mut offset = base_offset;
732                    let target = match binding_layout.ty {
733                        wgt::BindingType::Buffer {
734                            ty,
735                            has_dynamic_offset,
736                            min_binding_size: _,
737                        } => {
738                            if has_dynamic_offset {
739                                offset += dynamic_offsets[do_index] as i32;
740                                do_index += 1;
741                            }
742                            match ty {
743                                wgt::BufferBindingType::Uniform => glow::UNIFORM_BUFFER,
744                                wgt::BufferBindingType::Storage { .. } => {
745                                    glow::SHADER_STORAGE_BUFFER
746                                }
747                            }
748                        }
749                        _ => unreachable!(),
750                    };
751                    self.cmd_buffer.commands.push(C::BindBuffer {
752                        target,
753                        slot,
754                        buffer: raw,
755                        offset,
756                        size,
757                    });
758                }
759                super::RawBinding::Sampler(sampler) => {
760                    dirty_samplers |= 1 << slot;
761                    self.state.samplers[slot as usize] = Some(sampler);
762                }
763                super::RawBinding::Texture {
764                    raw,
765                    target,
766                    aspects,
767                    ref mip_levels,
768                } => {
769                    dirty_textures |= 1 << slot;
770                    self.state.texture_slots[slot as usize].tex_target = target;
771                    self.cmd_buffer.commands.push(C::BindTexture {
772                        slot,
773                        texture: raw,
774                        target,
775                        aspects,
776                        mip_levels: mip_levels.clone(),
777                    });
778                }
779                super::RawBinding::Image(ref binding) => {
780                    self.cmd_buffer.commands.push(C::BindImage {
781                        slot,
782                        binding: binding.clone(),
783                    });
784                }
785            }
786        }
787
788        self.rebind_sampler_states(dirty_textures, dirty_samplers);
789    }
790
791    unsafe fn set_push_constants(
792        &mut self,
793        _layout: &super::PipelineLayout,
794        _stages: wgt::ShaderStages,
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_push_constant 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 push constant 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_push_constant_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 push constant 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.push_constant_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_push_constant_data
826                    [uniform_start_words as usize..uniform_end_words as usize];
827
828                let range = self.cmd_buffer.add_push_constant_data(uniform_data);
829
830                self.cmd_buffer.commands.push(C::SetPushConstants {
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}