Debian Codegraph @

third_party/rust/wgpu-hal/src/gles/command.rs

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