Skip to main content

wgpu_hal/gles/
command.rs

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