1use alloc::string::String;
2use core::{mem, ops::Range};
3
4use arrayvec::ArrayVec;
5
6use super::{conv, Command as C};
7
8#[derive(Clone, Copy, Debug, Default)]
9struct TextureSlotDesc {
10 tex_target: super::BindTarget,
11 sampler_index: Option<u8>,
12}
13
14pub(super) struct State {
15 topology: u32,
16 primitive: super::PrimitiveState,
17 index_format: wgt::IndexFormat,
18 index_offset: wgt::BufferAddress,
19 vertex_buffers:
20 [(super::VertexBufferDesc, Option<super::BufferBinding>); crate::MAX_VERTEX_BUFFERS],
21 vertex_attributes: ArrayVec<super::AttributeDesc, { super::MAX_VERTEX_ATTRIBUTES }>,
22 color_targets: ArrayVec<super::ColorTargetDesc, { crate::MAX_COLOR_ATTACHMENTS }>,
23 stencil: super::StencilState,
24 depth_bias: wgt::DepthBiasState,
25 alpha_to_coverage_enabled: bool,
26 samplers: [Option<glow::Sampler>; super::MAX_SAMPLERS],
27 texture_slots: [TextureSlotDesc; super::MAX_TEXTURE_SLOTS],
28 render_size: wgt::Extent3d,
29 resolve_attachments: ArrayVec<(u32, super::TextureView), { crate::MAX_COLOR_ATTACHMENTS }>,
30 invalidate_attachments: ArrayVec<u32, { crate::MAX_COLOR_ATTACHMENTS + 2 }>,
31 has_pass_label: bool,
32 instance_vbuf_mask: usize,
33 dirty_vbuf_mask: usize,
34 active_first_instance: u32,
35 first_instance_location: Option<glow::UniformLocation>,
36 immediates_descs: ArrayVec<super::ImmediateDesc, { super::MAX_IMMEDIATES_COMMANDS }>,
37 current_immediates_data: [u32; super::MAX_IMMEDIATES],
39 end_of_pass_timestamp: Option<glow::Query>,
40 clip_distance_count: u32,
41}
42
43impl Default for State {
44 fn default() -> Self {
45 Self {
46 topology: Default::default(),
47 primitive: Default::default(),
48 index_format: Default::default(),
49 index_offset: Default::default(),
50 vertex_buffers: Default::default(),
51 vertex_attributes: Default::default(),
52 color_targets: Default::default(),
53 stencil: Default::default(),
54 depth_bias: Default::default(),
55 alpha_to_coverage_enabled: Default::default(),
56 samplers: Default::default(),
57 texture_slots: Default::default(),
58 render_size: Default::default(),
59 resolve_attachments: Default::default(),
60 invalidate_attachments: Default::default(),
61 has_pass_label: Default::default(),
62 instance_vbuf_mask: Default::default(),
63 dirty_vbuf_mask: Default::default(),
64 active_first_instance: Default::default(),
65 first_instance_location: Default::default(),
66 immediates_descs: Default::default(),
67 current_immediates_data: [0; super::MAX_IMMEDIATES],
68 end_of_pass_timestamp: Default::default(),
69 clip_distance_count: Default::default(),
70 }
71 }
72}
73
74impl super::CommandBuffer {
75 fn clear(&mut self) {
76 self.label = None;
77 self.commands.clear();
78 self.data_bytes.clear();
79 self.queries.clear();
80 }
81
82 fn add_marker(&mut self, marker: &str) -> Range<u32> {
83 let start = self.data_bytes.len() as u32;
84 self.data_bytes.extend(marker.as_bytes());
85 start..self.data_bytes.len() as u32
86 }
87
88 fn add_immediates_data(&mut self, data: &[u32]) -> Range<u32> {
89 let data_raw = bytemuck::cast_slice(data);
90 let start = self.data_bytes.len();
91 assert!(start < u32::MAX as usize);
92 self.data_bytes.extend_from_slice(data_raw);
93 let end = self.data_bytes.len();
94 assert!(end < u32::MAX as usize);
95 (start as u32)..(end as u32)
96 }
97}
98
99impl Drop for super::CommandEncoder {
100 fn drop(&mut self) {
101 use crate::CommandEncoder;
102 unsafe { self.discard_encoding() }
103 self.counters.command_encoders.sub(1);
104 }
105}
106
107impl super::CommandEncoder {
108 fn rebind_stencil_func(&mut self) {
109 fn make(s: &super::StencilSide, face: u32) -> C {
110 C::SetStencilFunc {
111 face,
112 function: s.function,
113 reference: s.reference,
114 read_mask: s.mask_read,
115 }
116 }
117
118 let s = &self.state.stencil;
119 if s.front.function == s.back.function
120 && s.front.mask_read == s.back.mask_read
121 && s.front.reference == s.back.reference
122 {
123 self.cmd_buffer
124 .commands
125 .push(make(&s.front, glow::FRONT_AND_BACK));
126 } else {
127 self.cmd_buffer.commands.push(make(&s.front, glow::FRONT));
128 self.cmd_buffer.commands.push(make(&s.back, glow::BACK));
129 }
130 }
131
132 fn rebind_vertex_data(&mut self, first_instance: u32) {
133 if self
134 .private_caps
135 .contains(super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT)
136 {
137 for (index, pair) in self.state.vertex_buffers.iter().enumerate() {
138 if self.state.dirty_vbuf_mask & (1 << index) == 0 {
139 continue;
140 }
141 let (buffer_desc, vb) = match *pair {
142 (_, 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 (_, 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 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 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 fn set_pipeline_inner(&mut self, inner: &super::PipelineInner) {
231 self.cmd_buffer.commands.push(C::SetProgram(inner.program));
232
233 self.state
234 .first_instance_location
235 .clone_from(&inner.first_instance_location);
236 self.state
237 .immediates_descs
238 .clone_from(&inner.immediates_descs);
239
240 let mut dirty_textures = 0u32;
242 for (texture_index, (slot, &sampler_index)) in self
243 .state
244 .texture_slots
245 .iter_mut()
246 .zip(inner.sampler_map.iter())
247 .enumerate()
248 {
249 if slot.sampler_index != sampler_index {
250 slot.sampler_index = sampler_index;
251 dirty_textures |= 1 << texture_index;
252 }
253 }
254 if dirty_textures != 0 {
255 self.rebind_sampler_states(dirty_textures, 0);
256 }
257 }
258}
259
260impl crate::CommandEncoder for super::CommandEncoder {
261 type A = super::Api;
262
263 unsafe fn begin_encoding(&mut self, label: crate::Label) -> Result<(), crate::DeviceError> {
264 self.state = State::default();
265 self.cmd_buffer.label = label.map(String::from);
266 Ok(())
267 }
268 unsafe fn discard_encoding(&mut self) {
269 self.cmd_buffer.clear();
270 }
271 unsafe fn end_encoding(&mut self) -> Result<super::CommandBuffer, crate::DeviceError> {
272 Ok(mem::take(&mut self.cmd_buffer))
273 }
274 unsafe fn reset_all<I>(&mut self, _command_buffers: I) {
275 }
277
278 unsafe fn transition_buffers<'a, T>(&mut self, barriers: T)
279 where
280 T: Iterator<Item = crate::BufferBarrier<'a, super::Buffer>>,
281 {
282 if !self
283 .private_caps
284 .contains(super::PrivateCapabilities::MEMORY_BARRIERS)
285 {
286 return;
287 }
288 for bar in barriers {
289 if !bar.usage.from.contains(wgt::BufferUses::STORAGE_READ_WRITE) {
291 continue;
292 }
293 self.cmd_buffer
294 .commands
295 .push(C::BufferBarrier(bar.buffer.raw.unwrap(), bar.usage.to));
296 }
297 }
298
299 unsafe fn transition_textures<'a, T>(&mut self, barriers: T)
300 where
301 T: Iterator<Item = crate::TextureBarrier<'a, super::Texture>>,
302 {
303 if !self
304 .private_caps
305 .contains(super::PrivateCapabilities::MEMORY_BARRIERS)
306 {
307 return;
308 }
309
310 let mut combined_usage = wgt::TextureUses::empty();
311 for bar in barriers {
312 if !bar.usage.from.intersects(
315 wgt::TextureUses::STORAGE_READ_WRITE | wgt::TextureUses::STORAGE_WRITE_ONLY,
316 ) {
317 continue;
318 }
319 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 }
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 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 #[cfg(native)]
527 super::TextureInner::ExternalNativeFramebuffer { .. } => true,
528 _ => false,
529 });
530
531 if rendering_to_external_framebuffer && desc.color_attachments.len() != 1 {
532 panic!("Multiple render attachments with external framebuffers are not supported.");
533 }
534
535 assert!(desc.color_attachments.len() <= 32);
537
538 match desc
539 .color_attachments
540 .first()
541 .filter(|at| at.is_some())
542 .and_then(|at| at.as_ref().map(|at| &at.target.view.inner))
543 {
544 Some(&super::TextureInner::DefaultRenderbuffer) => {
546 self.cmd_buffer
547 .commands
548 .push(C::ResetFramebuffer { is_default: true });
549 }
550 _ => {
551 self.cmd_buffer
553 .commands
554 .push(C::ResetFramebuffer { is_default: false });
555
556 for (i, cat) in desc.color_attachments.iter().enumerate() {
557 if let Some(cat) = cat.as_ref() {
558 let attachment = glow::COLOR_ATTACHMENT0 + i as u32;
559 self.cmd_buffer.commands.push(C::BindAttachment {
560 attachment,
561 view: cat.target.view.clone(),
562 depth_slice: cat.depth_slice,
563 });
564 if let Some(ref rat) = cat.resolve_target {
565 self.state
566 .resolve_attachments
567 .push((attachment, rat.view.clone()));
568 }
569 if cat.ops.contains(crate::AttachmentOps::STORE_DISCARD) {
570 self.state.invalidate_attachments.push(attachment);
571 }
572 }
573 }
574 if let Some(ref dsat) = desc.depth_stencil_attachment {
575 let aspects = dsat.target.view.aspects;
576 let attachment = match aspects {
577 crate::FormatAspects::DEPTH => glow::DEPTH_ATTACHMENT,
578 crate::FormatAspects::STENCIL => glow::STENCIL_ATTACHMENT,
579 _ => glow::DEPTH_STENCIL_ATTACHMENT,
580 };
581 self.cmd_buffer.commands.push(C::BindAttachment {
582 attachment,
583 view: dsat.target.view.clone(),
584 depth_slice: None,
585 });
586 if aspects.contains(crate::FormatAspects::DEPTH)
587 && dsat.depth_ops.contains(crate::AttachmentOps::STORE_DISCARD)
588 {
589 self.state
590 .invalidate_attachments
591 .push(glow::DEPTH_ATTACHMENT);
592 }
593 if aspects.contains(crate::FormatAspects::STENCIL)
594 && dsat
595 .stencil_ops
596 .contains(crate::AttachmentOps::STORE_DISCARD)
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 self.cmd_buffer
621 .commands
622 .push(C::SetDrawColorBuffers(desc.color_attachments.len() as u8));
623 }
624
625 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_CLEAR) {
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_CLEAR);
657 let clear_stencil = dsat.stencil_ops.contains(crate::AttachmentOps::LOAD_CLEAR);
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_immediates(
792 &mut self,
793 _layout: &super::PipelineLayout,
794 offset_bytes: u32,
795 data: &[u32],
796 ) {
797 let start_words = offset_bytes / 4;
805 let end_words = start_words + data.len() as u32;
806 self.state.current_immediates_data[start_words as usize..end_words as usize]
807 .copy_from_slice(data);
808
809 for uniform in self.state.immediates_descs.iter().cloned() {
815 let uniform_size_words = uniform.size_bytes / 4;
816 let uniform_start_words = uniform.offset / 4;
817 let uniform_end_words = uniform_start_words + uniform_size_words;
818
819 let needs_updating =
821 start_words < uniform_end_words || uniform_start_words <= end_words;
822
823 if needs_updating {
824 let uniform_data = &self.state.current_immediates_data
825 [uniform_start_words as usize..uniform_end_words as usize];
826
827 let range = self.cmd_buffer.add_immediates_data(uniform_data);
828
829 self.cmd_buffer.commands.push(C::SetImmediates {
830 uniform,
831 offset: range.start,
832 });
833 }
834 }
835 }
836
837 unsafe fn insert_debug_marker(&mut self, label: &str) {
838 let range = self.cmd_buffer.add_marker(label);
839 self.cmd_buffer.commands.push(C::InsertDebugMarker(range));
840 }
841 unsafe fn begin_debug_marker(&mut self, group_label: &str) {
842 let range = self.cmd_buffer.add_marker(group_label);
843 self.cmd_buffer.commands.push(C::PushDebugGroup(range));
844 }
845 unsafe fn end_debug_marker(&mut self) {
846 self.cmd_buffer.commands.push(C::PopDebugGroup);
847 }
848
849 unsafe fn set_render_pipeline(&mut self, pipeline: &super::RenderPipeline) {
850 self.state.topology = conv::map_primitive_topology(pipeline.primitive.topology);
851
852 if self
853 .private_caps
854 .contains(super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT)
855 {
856 for vat in pipeline.vertex_attributes.iter() {
857 let vb = &pipeline.vertex_buffers[vat.buffer_index as usize];
858 self.cmd_buffer.commands.push(C::SetVertexAttribute {
860 buffer: None,
861 buffer_desc: vb.clone(),
862 attribute_desc: vat.clone(),
863 });
864 }
865 } else {
866 for vat in &self.state.vertex_attributes {
867 self.cmd_buffer
868 .commands
869 .push(C::UnsetVertexAttribute(vat.location));
870 }
871 self.state.vertex_attributes.clear();
872
873 self.state.dirty_vbuf_mask = 0;
874 for vat in pipeline.vertex_attributes.iter() {
876 self.state.dirty_vbuf_mask |= 1 << vat.buffer_index;
878 self.state.vertex_attributes.push(vat.clone());
879 }
880 }
881
882 self.state.instance_vbuf_mask = 0;
883 for (index, (&mut (ref mut state_desc, _), pipe_desc)) in self
885 .state
886 .vertex_buffers
887 .iter_mut()
888 .zip(pipeline.vertex_buffers.iter())
889 .enumerate()
890 {
891 if pipe_desc.step == wgt::VertexStepMode::Instance {
892 self.state.instance_vbuf_mask |= 1 << index;
893 }
894 if state_desc != pipe_desc {
895 self.state.dirty_vbuf_mask |= 1 << index;
896 *state_desc = pipe_desc.clone();
897 }
898 }
899
900 self.set_pipeline_inner(&pipeline.inner);
901
902 let prim_state = conv::map_primitive_state(&pipeline.primitive);
904 if prim_state != self.state.primitive {
905 self.cmd_buffer
906 .commands
907 .push(C::SetPrimitive(prim_state.clone()));
908 self.state.primitive = prim_state;
909 }
910
911 let mut aspects = crate::FormatAspects::empty();
913 if pipeline.depth_bias != self.state.depth_bias {
914 self.state.depth_bias = pipeline.depth_bias;
915 self.cmd_buffer
916 .commands
917 .push(C::SetDepthBias(pipeline.depth_bias));
918 }
919 if let Some(ref depth) = pipeline.depth {
920 aspects |= crate::FormatAspects::DEPTH;
921 self.cmd_buffer.commands.push(C::SetDepth(depth.clone()));
922 }
923 if let Some(ref stencil) = pipeline.stencil {
924 aspects |= crate::FormatAspects::STENCIL;
925 self.state.stencil = stencil.clone();
926 self.rebind_stencil_func();
927 if stencil.front.ops == stencil.back.ops
928 && stencil.front.mask_write == stencil.back.mask_write
929 {
930 self.cmd_buffer.commands.push(C::SetStencilOps {
931 face: glow::FRONT_AND_BACK,
932 write_mask: stencil.front.mask_write,
933 ops: stencil.front.ops.clone(),
934 });
935 } else {
936 self.cmd_buffer.commands.push(C::SetStencilOps {
937 face: glow::FRONT,
938 write_mask: stencil.front.mask_write,
939 ops: stencil.front.ops.clone(),
940 });
941 self.cmd_buffer.commands.push(C::SetStencilOps {
942 face: glow::BACK,
943 write_mask: stencil.back.mask_write,
944 ops: stencil.back.ops.clone(),
945 });
946 }
947 }
948 self.cmd_buffer
949 .commands
950 .push(C::ConfigureDepthStencil(aspects));
951
952 if pipeline.alpha_to_coverage_enabled != self.state.alpha_to_coverage_enabled {
954 self.state.alpha_to_coverage_enabled = pipeline.alpha_to_coverage_enabled;
955 self.cmd_buffer
956 .commands
957 .push(C::SetAlphaToCoverage(pipeline.alpha_to_coverage_enabled));
958 }
959
960 if self.state.color_targets[..] != pipeline.color_targets[..] {
962 if pipeline
963 .color_targets
964 .iter()
965 .skip(1)
966 .any(|ct| *ct != pipeline.color_targets[0])
967 {
968 for (index, ct) in pipeline.color_targets.iter().enumerate() {
969 self.cmd_buffer.commands.push(C::SetColorTarget {
970 draw_buffer_index: Some(index as u32),
971 desc: ct.clone(),
972 });
973 }
974 } else {
975 self.cmd_buffer.commands.push(C::SetColorTarget {
976 draw_buffer_index: None,
977 desc: pipeline.color_targets.first().cloned().unwrap_or_default(),
978 });
979 }
980 }
981 self.state.color_targets.clear();
982 for ct in pipeline.color_targets.iter() {
983 self.state.color_targets.push(ct.clone());
984 }
985
986 if pipeline.inner.clip_distance_count != self.state.clip_distance_count {
988 self.cmd_buffer.commands.push(C::SetClipDistances {
989 old_count: self.state.clip_distance_count,
990 new_count: pipeline.inner.clip_distance_count,
991 });
992 self.state.clip_distance_count = pipeline.inner.clip_distance_count;
993 }
994 }
995
996 unsafe fn set_index_buffer<'a>(
997 &mut self,
998 binding: crate::BufferBinding<'a, super::Buffer>,
999 format: wgt::IndexFormat,
1000 ) {
1001 self.state.index_offset = binding.offset;
1002 self.state.index_format = format;
1003 self.cmd_buffer
1004 .commands
1005 .push(C::SetIndexBuffer(binding.buffer.raw.unwrap()));
1006 }
1007 unsafe fn set_vertex_buffer<'a>(
1008 &mut self,
1009 index: u32,
1010 binding: crate::BufferBinding<'a, super::Buffer>,
1011 ) {
1012 self.state.dirty_vbuf_mask |= 1 << index;
1013 let (_, ref mut vb) = self.state.vertex_buffers[index as usize];
1014 *vb = Some(super::BufferBinding {
1015 raw: binding.buffer.raw.unwrap(),
1016 offset: binding.offset,
1017 });
1018 }
1019 unsafe fn set_viewport(&mut self, rect: &crate::Rect<f32>, depth: Range<f32>) {
1020 self.cmd_buffer.commands.push(C::SetViewport {
1021 rect: crate::Rect {
1022 x: rect.x as i32,
1023 y: rect.y as i32,
1024 w: rect.w as i32,
1025 h: rect.h as i32,
1026 },
1027 depth,
1028 });
1029 }
1030 unsafe fn set_scissor_rect(&mut self, rect: &crate::Rect<u32>) {
1031 self.cmd_buffer.commands.push(C::SetScissor(crate::Rect {
1032 x: rect.x as i32,
1033 y: rect.y as i32,
1034 w: rect.w as i32,
1035 h: rect.h as i32,
1036 }));
1037 }
1038 unsafe fn set_stencil_reference(&mut self, value: u32) {
1039 self.state.stencil.front.reference = value;
1040 self.state.stencil.back.reference = value;
1041 self.rebind_stencil_func();
1042 }
1043 unsafe fn set_blend_constants(&mut self, color: &[f32; 4]) {
1044 self.cmd_buffer.commands.push(C::SetBlendConstant(*color));
1045 }
1046
1047 unsafe fn draw(
1048 &mut self,
1049 first_vertex: u32,
1050 vertex_count: u32,
1051 first_instance: u32,
1052 instance_count: u32,
1053 ) {
1054 self.prepare_draw(first_instance);
1055 #[allow(clippy::clone_on_copy)] self.cmd_buffer.commands.push(C::Draw {
1057 topology: self.state.topology,
1058 first_vertex,
1059 vertex_count,
1060 first_instance,
1061 instance_count,
1062 first_instance_location: self.state.first_instance_location.clone(),
1063 });
1064 }
1065 unsafe fn draw_indexed(
1066 &mut self,
1067 first_index: u32,
1068 index_count: u32,
1069 base_vertex: i32,
1070 first_instance: u32,
1071 instance_count: u32,
1072 ) {
1073 self.prepare_draw(first_instance);
1074 let (index_size, index_type) = match self.state.index_format {
1075 wgt::IndexFormat::Uint16 => (2, glow::UNSIGNED_SHORT),
1076 wgt::IndexFormat::Uint32 => (4, glow::UNSIGNED_INT),
1077 };
1078 let index_offset = self.state.index_offset + index_size * first_index as wgt::BufferAddress;
1079 #[allow(clippy::clone_on_copy)] self.cmd_buffer.commands.push(C::DrawIndexed {
1081 topology: self.state.topology,
1082 index_type,
1083 index_offset,
1084 index_count,
1085 base_vertex,
1086 first_instance,
1087 instance_count,
1088 first_instance_location: self.state.first_instance_location.clone(),
1089 });
1090 }
1091 unsafe fn draw_mesh_tasks(
1092 &mut self,
1093 _group_count_x: u32,
1094 _group_count_y: u32,
1095 _group_count_z: u32,
1096 ) {
1097 unreachable!()
1098 }
1099 unsafe fn draw_indirect(
1100 &mut self,
1101 buffer: &super::Buffer,
1102 offset: wgt::BufferAddress,
1103 draw_count: u32,
1104 ) {
1105 self.prepare_draw(0);
1106 for draw in 0..draw_count as wgt::BufferAddress {
1107 let indirect_offset =
1108 offset + draw * size_of::<wgt::DrawIndirectArgs>() as wgt::BufferAddress;
1109 #[allow(clippy::clone_on_copy)] self.cmd_buffer.commands.push(C::DrawIndirect {
1111 topology: self.state.topology,
1112 indirect_buf: buffer.raw.unwrap(),
1113 indirect_offset,
1114 first_instance_location: self.state.first_instance_location.clone(),
1115 });
1116 }
1117 }
1118 unsafe fn draw_indexed_indirect(
1119 &mut self,
1120 buffer: &super::Buffer,
1121 offset: wgt::BufferAddress,
1122 draw_count: u32,
1123 ) {
1124 self.prepare_draw(0);
1125 let index_type = match self.state.index_format {
1126 wgt::IndexFormat::Uint16 => glow::UNSIGNED_SHORT,
1127 wgt::IndexFormat::Uint32 => glow::UNSIGNED_INT,
1128 };
1129 for draw in 0..draw_count as wgt::BufferAddress {
1130 let indirect_offset =
1131 offset + draw * size_of::<wgt::DrawIndexedIndirectArgs>() as wgt::BufferAddress;
1132 #[allow(clippy::clone_on_copy)] self.cmd_buffer.commands.push(C::DrawIndexedIndirect {
1134 topology: self.state.topology,
1135 index_type,
1136 indirect_buf: buffer.raw.unwrap(),
1137 indirect_offset,
1138 first_instance_location: self.state.first_instance_location.clone(),
1139 });
1140 }
1141 }
1142 unsafe fn draw_mesh_tasks_indirect(
1143 &mut self,
1144 _buffer: &<Self::A as crate::Api>::Buffer,
1145 _offset: wgt::BufferAddress,
1146 _draw_count: u32,
1147 ) {
1148 unreachable!()
1149 }
1150 unsafe fn draw_indirect_count(
1151 &mut self,
1152 _buffer: &super::Buffer,
1153 _offset: wgt::BufferAddress,
1154 _count_buffer: &super::Buffer,
1155 _count_offset: wgt::BufferAddress,
1156 _max_count: u32,
1157 ) {
1158 unreachable!()
1159 }
1160 unsafe fn draw_indexed_indirect_count(
1161 &mut self,
1162 _buffer: &super::Buffer,
1163 _offset: wgt::BufferAddress,
1164 _count_buffer: &super::Buffer,
1165 _count_offset: wgt::BufferAddress,
1166 _max_count: u32,
1167 ) {
1168 unreachable!()
1169 }
1170 unsafe fn draw_mesh_tasks_indirect_count(
1171 &mut self,
1172 _buffer: &<Self::A as crate::Api>::Buffer,
1173 _offset: wgt::BufferAddress,
1174 _count_buffer: &<Self::A as crate::Api>::Buffer,
1175 _count_offset: wgt::BufferAddress,
1176 _max_count: u32,
1177 ) {
1178 unreachable!()
1179 }
1180
1181 unsafe fn begin_compute_pass(&mut self, desc: &crate::ComputePassDescriptor<super::QuerySet>) {
1184 debug_assert!(self.state.end_of_pass_timestamp.is_none());
1185 if let Some(ref t) = desc.timestamp_writes {
1186 if let Some(index) = t.beginning_of_pass_write_index {
1187 unsafe { self.write_timestamp(t.query_set, index) }
1188 }
1189 self.state.end_of_pass_timestamp = t
1190 .end_of_pass_write_index
1191 .map(|index| t.query_set.queries[index as usize]);
1192 }
1193
1194 if let Some(label) = desc.label {
1195 let range = self.cmd_buffer.add_marker(label);
1196 self.cmd_buffer.commands.push(C::PushDebugGroup(range));
1197 self.state.has_pass_label = true;
1198 }
1199 }
1200 unsafe fn end_compute_pass(&mut self) {
1201 if self.state.has_pass_label {
1202 self.cmd_buffer.commands.push(C::PopDebugGroup);
1203 self.state.has_pass_label = false;
1204 }
1205
1206 if let Some(query) = self.state.end_of_pass_timestamp.take() {
1207 self.cmd_buffer.commands.push(C::TimestampQuery(query));
1208 }
1209 }
1210
1211 unsafe fn set_compute_pipeline(&mut self, pipeline: &super::ComputePipeline) {
1212 self.set_pipeline_inner(&pipeline.inner);
1213 }
1214
1215 unsafe fn dispatch(&mut self, count: [u32; 3]) {
1216 if count.contains(&0) {
1218 return;
1219 }
1220 self.cmd_buffer.commands.push(C::Dispatch(count));
1221 }
1222 unsafe fn dispatch_indirect(&mut self, buffer: &super::Buffer, offset: wgt::BufferAddress) {
1223 self.cmd_buffer.commands.push(C::DispatchIndirect {
1224 indirect_buf: buffer.raw.unwrap(),
1225 indirect_offset: offset,
1226 });
1227 }
1228
1229 unsafe fn build_acceleration_structures<'a, T>(
1230 &mut self,
1231 _descriptor_count: u32,
1232 _descriptors: T,
1233 ) where
1234 super::Api: 'a,
1235 T: IntoIterator<
1236 Item = crate::BuildAccelerationStructureDescriptor<
1237 'a,
1238 super::Buffer,
1239 super::AccelerationStructure,
1240 >,
1241 >,
1242 {
1243 unimplemented!()
1244 }
1245
1246 unsafe fn place_acceleration_structure_barrier(
1247 &mut self,
1248 _barriers: crate::AccelerationStructureBarrier,
1249 ) {
1250 unimplemented!()
1251 }
1252
1253 unsafe fn copy_acceleration_structure_to_acceleration_structure(
1254 &mut self,
1255 _src: &super::AccelerationStructure,
1256 _dst: &super::AccelerationStructure,
1257 _copy: wgt::AccelerationStructureCopy,
1258 ) {
1259 unimplemented!()
1260 }
1261
1262 unsafe fn read_acceleration_structure_compact_size(
1263 &mut self,
1264 _acceleration_structure: &super::AccelerationStructure,
1265 _buf: &super::Buffer,
1266 ) {
1267 unimplemented!()
1268 }
1269}