1use alloc::borrow::ToOwned;
2use alloc::{
3 borrow::Cow::{self, Borrowed},
4 boxed::Box,
5 string::String,
6 sync::Arc,
7 vec::Vec,
8};
9use core::{
10 error::Error,
11 fmt,
12 future::ready,
13 ops::{Deref, Range},
14 pin::Pin,
15 ptr::NonNull,
16};
17use wgc::resource::{BufferMapping, ParentDevice as _};
18use wgt::error::WebGpuError;
19
20use arrayvec::ArrayVec;
21use smallvec::SmallVec;
22use wgc::resource::BlasPrepareCompactResult;
23use wgt::WasmNotSendSync;
24
25use crate::{
26 api,
27 dispatch::{self, BlasCompactCallback},
28 BindingResource, Blas, BufferBinding, BufferDescriptor, Features, LoadOp, Operations,
29 ShaderSource, SurfaceTargetUnsafe, TextureDescriptor, Tlas, WriteOnly,
30};
31use crate::{dispatch::DispatchAdapter, util::Mutex};
32
33use wgc::error::format_error;
34
35#[derive(Clone)]
36pub struct ContextWgpuCore(Arc<wgc::instance::Instance>);
37
38impl fmt::Debug for ContextWgpuCore {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 f.debug_struct("ContextWgpuCore")
41 .field("type", &"Native")
42 .finish()
43 }
44}
45
46#[track_caller]
47#[cold]
48fn handle_error_fatal(cause: impl Error + WasmNotSendSync + 'static, operation: &'static str) -> ! {
49 panic!("Error in {operation}: {f}", f = format_error(&cause));
50}
51
52impl ContextWgpuCore {
53 pub unsafe fn from_hal_instance<A: hal::Api>(hal_instance: A::Instance) -> Self {
54 Self(wgc::instance::Instance::from_hal_instance::<A>(
55 "wgpu".to_owned(),
56 hal_instance,
57 ))
58 }
59
60 pub unsafe fn instance_as_hal<A: hal::Api>(&self) -> Option<&A::Instance> {
64 unsafe { self.0.as_hal::<A>() }
65 }
66
67 pub fn from_core_instance(core_instance: Arc<wgc::instance::Instance>) -> Self {
68 Self(core_instance)
69 }
70
71 #[cfg(wgpu_core)]
72 pub fn enumerate_adapters(&self, backends: wgt::Backends) -> Vec<Arc<wgc::instance::Adapter>> {
73 self.0
74 .enumerate_adapters(backends, false )
75 }
76
77 pub unsafe fn create_adapter_from_hal<A: hal::Api>(
78 &self,
79 hal_adapter: hal::ExposedAdapter<A>,
80 ) -> Arc<wgc::instance::Adapter> {
81 unsafe { self.0.create_adapter_from_hal(hal_adapter.into()) }
82 }
83
84 pub(crate) fn as_core(&self) -> Arc<wgc::instance::Instance> {
85 self.0.clone()
86 }
87}
88
89fn map_buffer_copy_view(
90 view: crate::TexelCopyBufferInfo<'_>,
91) -> wgt::TexelCopyBufferInfo<Arc<wgc::resource::Buffer>> {
92 wgt::TexelCopyBufferInfo {
93 buffer: view.buffer.inner.as_core().wgpu_buffer.clone(),
94 layout: view.layout,
95 }
96}
97
98fn map_texture_copy_view(
99 view: crate::TexelCopyTextureInfo<'_>,
100) -> wgt::TexelCopyTextureInfo<Arc<wgc::resource::Texture>> {
101 wgt::TexelCopyTextureInfo {
102 texture: view.texture.inner.as_core().wgpu_texture.clone(),
103 mip_level: view.mip_level,
104 origin: view.origin,
105 aspect: view.aspect,
106 }
107}
108
109#[cfg_attr(not(webgl), expect(unused))]
110fn map_texture_tagged_copy_view(
111 view: crate::CopyExternalImageDestInfo<&api::Texture>,
112) -> wgt::CopyExternalImageDestInfo<Arc<wgc::resource::Texture>> {
113 wgt::CopyExternalImageDestInfo {
114 texture: view.texture.inner.as_core().wgpu_texture.clone(),
115 mip_level: view.mip_level,
116 origin: view.origin,
117 aspect: view.aspect,
118 color_space: view.color_space,
119 premultiplied_alpha: view.premultiplied_alpha,
120 }
121}
122
123fn map_load_op<V: Copy>(load: &LoadOp<V>) -> LoadOp<Option<V>> {
124 match *load {
125 LoadOp::Clear(clear_value) => LoadOp::Clear(Some(clear_value)),
126 LoadOp::DontCare(token) => LoadOp::DontCare(token),
127 LoadOp::Load => LoadOp::Load,
128 }
129}
130
131fn map_pass_channel<V: Copy>(ops: Option<&Operations<V>>) -> wgc::command::PassChannel<Option<V>> {
132 match ops {
133 Some(&Operations { load, store }) => wgc::command::PassChannel {
134 load_op: Some(map_load_op(&load)),
135 store_op: Some(store),
136 read_only: false,
137 },
138 None => wgc::command::PassChannel {
139 load_op: None,
140 store_op: None,
141 read_only: true,
142 },
143 }
144}
145
146#[derive(Clone)]
147pub struct CoreSurface {
148 pub(crate) wgpu_surface: Arc<wgc::instance::Surface>,
149 configured_device: Arc<Mutex<Option<Arc<wgc::device::Device>>>>,
152}
153
154impl fmt::Debug for CoreSurface {
155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156 f.debug_struct("CoreSurface")
157 .field("wgpu_surface", &Arc::as_ptr(&self.wgpu_surface))
158 .field("configured_device", &self.configured_device)
159 .finish()
160 }
161}
162
163impl CoreSurface {
164 pub unsafe fn as_hal<A: hal::Api>(&self) -> Option<impl Deref<Target = A::Surface>> {
165 unsafe { self.wgpu_surface.clone().as_hal::<A>() }
166 }
167}
168
169#[derive(Clone)]
170pub struct CoreAdapter {
171 pub(crate) wgpu_adapter: Arc<wgc::instance::Adapter>,
172}
173
174impl fmt::Debug for CoreAdapter {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 f.debug_struct("CoreAdapter")
177 .field("wgpu_adapter", &Arc::as_ptr(&self.wgpu_adapter))
178 .finish()
179 }
180}
181
182impl CoreAdapter {
183 pub unsafe fn as_hal<A: hal::Api>(
184 &self,
185 ) -> Option<impl Deref<Target = A::Adapter> + WasmNotSendSync> {
186 unsafe { self.wgpu_adapter.clone().as_hal::<A>() }
187 }
188
189 pub unsafe fn create_device_from_hal<A: hal::Api>(
190 &self,
191 hal_device: hal::OpenDevice<A>,
192 desc: &crate::DeviceDescriptor<'_>,
193 ) -> Result<(CoreDevice, CoreQueue), crate::RequestDeviceError> {
194 let (device, queue) = unsafe {
195 self.wgpu_adapter.create_device_and_queue_from_hal(
196 hal_device.into(),
197 &desc.map_label(|l| l.map(Borrowed)),
198 )
199 }?;
200 let device = CoreDevice {
201 wgpu_device: device.clone(),
202 };
203 let queue = CoreQueue { wgpu_queue: queue };
204 Ok((device, queue))
205 }
206
207 pub(crate) fn from_core(core_adapter: Arc<wgc::instance::Adapter>) -> Self {
208 Self {
209 wgpu_adapter: core_adapter,
210 }
211 }
212
213 pub(crate) fn as_core(&self) -> Arc<wgc::instance::Adapter> {
214 self.wgpu_adapter.clone()
215 }
216}
217
218#[derive(Debug, Clone)]
219pub struct CoreDevice {
220 pub(crate) wgpu_device: Arc<wgc::device::Device>,
221}
222
223impl CoreDevice {
224 pub unsafe fn as_hal<A: hal::Api>(&self) -> Option<impl Deref<Target = A::Device>> {
225 unsafe { self.wgpu_device.clone().as_hal::<A>() }
226 }
227
228 pub unsafe fn create_texture_from_hal<A: hal::Api>(
229 &self,
230 hal_texture: A::Texture,
231 desc: &TextureDescriptor<'_>,
232 initial_state: wgt::TextureUses,
233 cleared: bool,
234 ) -> CoreTexture {
235 let descriptor = desc.map_label_and_view_formats(|l| l.map(Borrowed), |v| v.to_vec());
236 let (wgpu_texture, error) = unsafe {
237 self.wgpu_device.create_texture_from_hal(
238 Box::new(hal_texture),
239 &descriptor,
240 initial_state,
241 cleared,
242 )
243 };
244 if let Some(cause) = error {
245 self.wgpu_device
246 .handle_error(cause, desc.label, "Device::create_texture_from_hal");
247 }
248 CoreTexture { wgpu_texture }
249 }
250
251 pub unsafe fn create_buffer_from_hal<A: hal::Api>(
258 &self,
259 hal_buffer: A::Buffer,
260 desc: &BufferDescriptor<'_>,
261 ) -> CoreBuffer {
262 let (wgpu_buffer, error) = unsafe {
263 self.wgpu_device
264 .create_buffer_from_hal(Box::new(hal_buffer), &desc.map_label(|l| l.map(Borrowed)))
265 };
266 if let Some(cause) = error {
267 self.wgpu_device
268 .handle_error(cause, desc.label, "Device::create_buffer_from_hal");
269 }
270 CoreBuffer { wgpu_buffer }
271 }
272
273 #[cfg(webgl)]
275 pub fn texture_belongs_to_device(&self, texture: &CoreTexture) -> bool {
276 use wgc::resource::ParentDevice as _;
277 texture.wgpu_texture.same_device(&self.wgpu_device).is_ok()
278 }
279
280 pub(crate) fn from_core(core_device: Arc<wgc::device::Device>) -> Self {
281 Self {
282 wgpu_device: core_device,
283 }
284 }
285
286 pub(crate) fn as_core(&self) -> Arc<wgc::device::Device> {
287 self.wgpu_device.clone()
288 }
289}
290
291#[derive(Debug, Clone)]
292pub struct CoreBuffer {
293 pub(crate) wgpu_buffer: Arc<wgc::resource::Buffer>,
294}
295
296impl CoreBuffer {
297 pub unsafe fn as_hal<A: hal::Api>(&self) -> Option<impl Deref<Target = A::Buffer>> {
298 unsafe { self.wgpu_buffer.clone().as_hal::<A>() }
299 }
300
301 pub(crate) fn from_core(core_buffer: Arc<wgc::resource::Buffer>) -> Self {
302 Self {
303 wgpu_buffer: core_buffer,
304 }
305 }
306
307 pub(crate) fn as_core(&self) -> Arc<wgc::resource::Buffer> {
308 self.wgpu_buffer.clone()
309 }
310}
311
312#[derive(Debug, Clone)]
313pub struct CoreShaderModule {
314 pub(crate) wgpu_shader_module: Arc<wgc::pipeline::ShaderModule>,
315}
316
317impl CoreShaderModule {
318 pub(crate) fn from_core(core_shader_module: Arc<wgc::pipeline::ShaderModule>) -> Self {
319 Self {
320 wgpu_shader_module: core_shader_module,
321 }
322 }
323
324 pub(crate) fn as_core(&self) -> Arc<wgc::pipeline::ShaderModule> {
325 self.wgpu_shader_module.clone()
326 }
327}
328
329#[derive(Debug, Clone)]
330pub struct CoreBindGroupLayout {
331 pub(crate) wgpu_bind_group_layout: Arc<wgc::binding_model::BindGroupLayout>,
332}
333
334impl CoreBindGroupLayout {
335 pub(crate) fn from_core(
336 core_bind_group_layout: Arc<wgc::binding_model::BindGroupLayout>,
337 ) -> Self {
338 Self {
339 wgpu_bind_group_layout: core_bind_group_layout,
340 }
341 }
342
343 pub(crate) fn as_core(&self) -> Arc<wgc::binding_model::BindGroupLayout> {
344 self.wgpu_bind_group_layout.clone()
345 }
346}
347
348#[derive(Debug, Clone)]
349pub struct CoreBindGroup {
350 pub(crate) wgpu_bind_group: Arc<wgc::binding_model::BindGroup>,
351}
352impl CoreBindGroup {
353 pub(crate) fn from_core(core_bind_group: Arc<wgc::binding_model::BindGroup>) -> Self {
354 Self {
355 wgpu_bind_group: core_bind_group,
356 }
357 }
358
359 pub(crate) fn as_core(&self) -> Arc<wgc::binding_model::BindGroup> {
360 self.wgpu_bind_group.clone()
361 }
362}
363
364#[derive(Debug, Clone)]
365pub struct CoreTexture {
366 pub(crate) wgpu_texture: Arc<wgc::resource::Texture>,
367}
368
369impl CoreTexture {
370 pub unsafe fn as_hal<A: hal::Api>(&self) -> Option<impl Deref<Target = A::Texture>> {
371 unsafe { self.wgpu_texture.clone().as_hal::<A>() }
372 }
373
374 pub(crate) fn from_core(core_texture: Arc<wgc::resource::Texture>) -> Self {
375 Self {
376 wgpu_texture: core_texture,
377 }
378 }
379
380 pub(crate) fn as_core(&self) -> Arc<wgc::resource::Texture> {
381 self.wgpu_texture.clone()
382 }
383}
384
385#[derive(Debug, Clone)]
386pub struct CoreTextureView {
387 pub(crate) wgpu_texture_view: Arc<wgc::resource::TextureView>,
388}
389
390impl CoreTextureView {
391 pub unsafe fn as_hal<A: hal::Api>(&self) -> Option<impl Deref<Target = A::TextureView>> {
392 unsafe { self.wgpu_texture_view.clone().as_hal::<A>() }
393 }
394
395 pub(crate) fn from_core(core_texture_view: Arc<wgc::resource::TextureView>) -> Self {
396 Self {
397 wgpu_texture_view: core_texture_view,
398 }
399 }
400
401 pub(crate) fn as_core(&self) -> Arc<wgc::resource::TextureView> {
402 self.wgpu_texture_view.clone()
403 }
404}
405
406#[derive(Debug, Clone)]
407pub struct CoreExternalTexture {
408 pub(crate) wgpu_external_texture: Arc<wgc::resource::ExternalTexture>,
409}
410
411impl CoreExternalTexture {
412 pub(crate) fn from_core(core_external_texture: Arc<wgc::resource::ExternalTexture>) -> Self {
413 Self {
414 wgpu_external_texture: core_external_texture,
415 }
416 }
417
418 pub(crate) fn as_core(&self) -> Arc<wgc::resource::ExternalTexture> {
419 self.wgpu_external_texture.clone()
420 }
421}
422
423#[derive(Debug, Clone)]
424pub struct CoreSampler {
425 pub(crate) wgpu_sampler: Arc<wgc::resource::Sampler>,
426}
427
428impl CoreSampler {
429 pub(crate) fn from_core(core_sampler: Arc<wgc::resource::Sampler>) -> Self {
430 Self {
431 wgpu_sampler: core_sampler,
432 }
433 }
434
435 pub(crate) fn as_core(&self) -> Arc<wgc::resource::Sampler> {
436 self.wgpu_sampler.clone()
437 }
438}
439
440#[derive(Debug, Clone)]
441pub struct CoreQuerySet {
442 pub(crate) wgpu_query_set: Arc<wgc::resource::QuerySet>,
443}
444
445impl CoreQuerySet {
446 pub(crate) fn from_core(core_query_set: Arc<wgc::resource::QuerySet>) -> Self {
447 Self {
448 wgpu_query_set: core_query_set,
449 }
450 }
451
452 pub(crate) fn as_core(&self) -> Arc<wgc::resource::QuerySet> {
453 self.wgpu_query_set.clone()
454 }
455}
456
457#[derive(Debug, Clone)]
458pub struct CorePipelineLayout {
459 pub(crate) wgpu_pipeline_layout: Arc<wgc::binding_model::PipelineLayout>,
460}
461
462impl CorePipelineLayout {
463 pub(crate) fn from_core(core_pipeline_layout: Arc<wgc::binding_model::PipelineLayout>) -> Self {
464 Self {
465 wgpu_pipeline_layout: core_pipeline_layout,
466 }
467 }
468
469 pub(crate) fn as_core(&self) -> Arc<wgc::binding_model::PipelineLayout> {
470 self.wgpu_pipeline_layout.clone()
471 }
472}
473
474#[derive(Debug, Clone)]
475pub struct CorePipelineCache {
476 pub(crate) wgpu_pipeline_cache: Arc<wgc::pipeline::PipelineCache>,
477}
478
479pub struct CoreCommandBuffer {
480 pub(crate) wgpu_command_buffer: Arc<wgc::command::CommandBuffer>,
481}
482impl CoreCommandBuffer {
483 pub(crate) fn from_core(core_buffer: Arc<wgc::command::CommandBuffer>) -> Self {
484 Self {
485 wgpu_command_buffer: core_buffer,
486 }
487 }
488
489 pub(crate) fn as_core(&self) -> Arc<wgc::command::CommandBuffer> {
490 self.wgpu_command_buffer.clone()
491 }
492}
493
494impl fmt::Debug for CoreCommandBuffer {
495 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496 f.debug_struct("CoreCommandBuffer")
497 .field(
498 "wgpu_command_buffer",
499 &Arc::as_ptr(&self.wgpu_command_buffer),
500 )
501 .finish()
502 }
503}
504
505#[derive(Debug)]
506pub struct CoreRenderBundleEncoder {
507 encoder: Box<wgc::command::RenderBundleEncoder>,
508}
509
510#[derive(Debug, Clone)]
511pub struct CoreRenderBundle {
512 pub(crate) wgpu_render_bundle: Arc<wgc::command::RenderBundle>,
513}
514
515#[derive(Clone)]
516pub struct CoreQueue {
517 pub(crate) wgpu_queue: Arc<wgc::device::queue::Queue>,
518}
519
520impl fmt::Debug for CoreQueue {
521 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522 f.debug_struct("CoreQueue")
523 .field("wgpu_queue", &Arc::as_ptr(&self.wgpu_queue))
524 .finish()
525 }
526}
527
528impl CoreQueue {
529 pub unsafe fn as_hal<A: hal::Api>(
530 &self,
531 ) -> Option<impl Deref<Target = A::Queue> + WasmNotSendSync> {
532 unsafe { self.wgpu_queue.clone().as_hal::<A>() }
533 }
534
535 pub(crate) fn from_core(core_queue: Arc<wgc::device::queue::Queue>) -> Self {
536 Self {
537 wgpu_queue: core_queue,
538 }
539 }
540
541 pub(crate) fn as_core(&self) -> Arc<wgc::device::queue::Queue> {
542 self.wgpu_queue.clone()
543 }
544}
545
546#[derive(Debug, Clone)]
547pub struct CoreComputePipeline {
548 pub(crate) wgpu_compute_pipeline: Arc<wgc::pipeline::ComputePipeline>,
549}
550
551impl CoreComputePipeline {
552 pub(crate) fn from_core(core_compute_pipeline: Arc<wgc::pipeline::ComputePipeline>) -> Self {
553 Self {
554 wgpu_compute_pipeline: core_compute_pipeline,
555 }
556 }
557
558 pub(crate) fn as_core(&self) -> Arc<wgc::pipeline::ComputePipeline> {
559 self.wgpu_compute_pipeline.clone()
560 }
561}
562
563#[derive(Debug, Clone)]
564pub struct CoreRenderPipeline {
565 pub(crate) wgpu_render_pipeline: Arc<wgc::pipeline::RenderPipeline>,
566}
567
568impl CoreRenderPipeline {
569 pub(crate) fn from_core(core_render_pipeline: Arc<wgc::pipeline::RenderPipeline>) -> Self {
570 Self {
571 wgpu_render_pipeline: core_render_pipeline,
572 }
573 }
574
575 pub(crate) fn as_core(&self) -> Arc<wgc::pipeline::RenderPipeline> {
576 self.wgpu_render_pipeline.clone()
577 }
578}
579
580#[derive(Debug, Clone)]
581pub struct CoreRayTracingPipeline {
582 pub(crate) wgpu_ray_tracing_pipeline: Arc<wgc::ray_tracing_pipeline::RayTracingPipeline>,
583}
584
585impl CoreRayTracingPipeline {
586 pub(crate) fn from_core(
587 core_ray_tracing_pipeline: Arc<wgc::ray_tracing_pipeline::RayTracingPipeline>,
588 ) -> Self {
589 Self {
590 wgpu_ray_tracing_pipeline: core_ray_tracing_pipeline,
591 }
592 }
593
594 pub(crate) fn as_core(&self) -> Arc<wgc::ray_tracing_pipeline::RayTracingPipeline> {
595 self.wgpu_ray_tracing_pipeline.clone()
596 }
597}
598
599#[derive(Debug)]
600pub struct CoreComputePass {
601 pass: wgc::command::ComputePass,
602
603 id: crate::cmp::Identifier,
604}
605
606#[derive(Debug)]
607pub struct CoreRenderPass {
608 pass: wgc::command::RenderPass,
609
610 id: crate::cmp::Identifier,
611}
612
613#[derive(Debug)]
614pub struct CoreRayTracingPass {
615 pass: wgc::command::RayTracingPass,
616
617 id: crate::cmp::Identifier,
618}
619
620pub struct CoreCommandEncoder {
621 pub(crate) wgpu_command_encoder: Arc<wgc::command::CommandEncoder>,
622}
623
624impl fmt::Debug for CoreCommandEncoder {
625 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
626 f.debug_struct("CoreCommandEncoder")
627 .field(
628 "wgpu_command_encoder",
629 &Arc::as_ptr(&self.wgpu_command_encoder),
630 )
631 .finish()
632 }
633}
634
635impl CoreCommandEncoder {
636 pub unsafe fn as_hal_mut<A: hal::Api, F: FnOnce(Option<&mut A::CommandEncoder>) -> R, R>(
638 &self,
639 hal_command_encoder_callback: F,
640 ) -> R {
641 unsafe {
642 self.wgpu_command_encoder
643 .as_hal_mut::<A, F, R>(hal_command_encoder_callback)
644 }
645 }
646
647 pub(crate) fn from_core(core_encoder: Arc<wgc::command::CommandEncoder>) -> Self {
648 Self {
649 wgpu_command_encoder: core_encoder,
650 }
651 }
652
653 pub(crate) fn as_core(&self) -> Arc<wgc::command::CommandEncoder> {
654 self.wgpu_command_encoder.clone()
655 }
656}
657
658#[derive(Debug, Clone)]
659pub struct CoreBlas {
660 pub(crate) wgpu_blas: Arc<wgc::resource::Blas>,
661}
662
663impl CoreBlas {
664 pub unsafe fn as_hal<A: hal::Api>(
665 &self,
666 ) -> Option<impl Deref<Target = A::AccelerationStructure>> {
667 unsafe { self.wgpu_blas.clone().as_hal::<A>() }
668 }
669}
670
671#[derive(Debug, Clone)]
672pub struct CoreTlas {
673 pub(crate) wgpu_tlas: Arc<wgc::resource::Tlas>,
674}
675
676impl CoreTlas {
677 pub unsafe fn as_hal<A: hal::Api>(
678 &self,
679 ) -> Option<impl Deref<Target = A::AccelerationStructure>> {
680 unsafe { self.wgpu_tlas.clone().as_hal::<A>() }
681 }
682}
683
684#[derive(Clone)]
685pub struct CoreSurfaceOutputDetail {
686 wgpu_surface: Arc<wgc::instance::Surface>,
687 error_sink: ErrorSink,
688}
689
690impl fmt::Debug for CoreSurfaceOutputDetail {
691 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
692 f.debug_struct("CoreSurfaceOutputDetail")
693 .field("wgpu_surface", &Arc::as_ptr(&self.wgpu_surface))
694 .finish()
695 }
696}
697
698#[derive(Debug)]
699pub struct CoreQueueWriteBuffer {
700 wgpu_staging_buffer: wgc::resource::StagingBuffer,
701}
702
703#[derive(Debug)]
704pub struct CoreBufferMappedRange(BufferMapping);
705
706#[cfg(send_sync)]
707unsafe impl Send for CoreBufferMappedRange {}
708#[cfg(send_sync)]
709unsafe impl Sync for CoreBufferMappedRange {}
710
711impl Drop for CoreBufferMappedRange {
712 fn drop(&mut self) {
713 }
716}
717
718crate::cmp::impl_eq_ord_hash_arc_address!(ContextWgpuCore => .0);
719crate::cmp::impl_eq_ord_hash_arc_address!(CoreAdapter => .wgpu_adapter);
720crate::cmp::impl_eq_ord_hash_arc_address!(CoreDevice => .wgpu_device);
721crate::cmp::impl_eq_ord_hash_arc_address!(CoreQueue => .wgpu_queue);
722crate::cmp::impl_eq_ord_hash_arc_address!(CoreShaderModule => .wgpu_shader_module);
723crate::cmp::impl_eq_ord_hash_arc_address!(CoreBindGroupLayout => .wgpu_bind_group_layout);
724crate::cmp::impl_eq_ord_hash_arc_address!(CoreBindGroup => .wgpu_bind_group);
725crate::cmp::impl_eq_ord_hash_arc_address!(CoreTextureView => .wgpu_texture_view);
726crate::cmp::impl_eq_ord_hash_arc_address!(CoreSampler => .wgpu_sampler);
727crate::cmp::impl_eq_ord_hash_arc_address!(CoreBuffer => .wgpu_buffer);
728crate::cmp::impl_eq_ord_hash_arc_address!(CoreTexture => .wgpu_texture);
729crate::cmp::impl_eq_ord_hash_arc_address!(CoreExternalTexture => .wgpu_external_texture);
730crate::cmp::impl_eq_ord_hash_arc_address!(CoreBlas => .wgpu_blas);
731crate::cmp::impl_eq_ord_hash_arc_address!(CoreTlas => .wgpu_tlas);
732crate::cmp::impl_eq_ord_hash_arc_address!(CoreQuerySet => .wgpu_query_set);
733crate::cmp::impl_eq_ord_hash_arc_address!(CorePipelineLayout => .wgpu_pipeline_layout);
734crate::cmp::impl_eq_ord_hash_arc_address!(CoreRenderPipeline => .wgpu_render_pipeline);
735crate::cmp::impl_eq_ord_hash_arc_address!(CoreComputePipeline => .wgpu_compute_pipeline);
736crate::cmp::impl_eq_ord_hash_arc_address!(CoreRayTracingPipeline => .wgpu_ray_tracing_pipeline);
737crate::cmp::impl_eq_ord_hash_arc_address!(CorePipelineCache => .wgpu_pipeline_cache);
738crate::cmp::impl_eq_ord_hash_arc_address!(CoreCommandEncoder => .wgpu_command_encoder);
739crate::cmp::impl_eq_ord_hash_proxy!(CoreComputePass => .id);
740crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderPass => .id);
741crate::cmp::impl_eq_ord_hash_proxy!(CoreRayTracingPass => .id);
742crate::cmp::impl_eq_ord_hash_arc_address!(CoreCommandBuffer => .wgpu_command_buffer);
743crate::cmp::impl_eq_ord_hash_box_address!(CoreRenderBundleEncoder => .encoder);
744crate::cmp::impl_eq_ord_hash_arc_address!(CoreRenderBundle => .wgpu_render_bundle);
745crate::cmp::impl_eq_ord_hash_arc_address!(CoreSurface => .wgpu_surface);
746crate::cmp::impl_eq_ord_hash_arc_address!(CoreSurfaceOutputDetail => .wgpu_surface);
747impl PartialEq for CoreQueueWriteBuffer {
748 fn eq(&self, other: &Self) -> bool {
749 unsafe { self.wgpu_staging_buffer.ptr() == other.wgpu_staging_buffer.ptr() }
750 }
751}
752impl Eq for CoreQueueWriteBuffer {}
753impl PartialOrd for CoreQueueWriteBuffer {
754 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
755 Some(self.cmp(other))
756 }
757}
758impl Ord for CoreQueueWriteBuffer {
759 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
760 unsafe {
761 self.wgpu_staging_buffer
762 .ptr()
763 .cmp(&other.wgpu_staging_buffer.ptr())
764 }
765 }
766}
767impl core::hash::Hash for CoreQueueWriteBuffer {
768 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
769 unsafe { self.wgpu_staging_buffer.ptr().hash(state) }
770 }
771}
772crate::cmp::impl_eq_ord_hash_proxy!(CoreBufferMappedRange => .0.ptr());
773
774impl dispatch::InstanceInterface for ContextWgpuCore {
775 fn new(desc: wgt::InstanceDescriptor) -> Self
776 where
777 Self: Sized,
778 {
779 Self(wgc::instance::Instance::new("wgpu", desc, None))
780 }
781
782 unsafe fn create_surface(
783 &self,
784 target: crate::api::SurfaceTargetUnsafe,
785 ) -> Result<dispatch::DispatchSurface, crate::CreateSurfaceError> {
786 let wgpu_surface = match target {
787 SurfaceTargetUnsafe::RawHandle {
788 raw_display_handle,
789 raw_window_handle,
790 } => unsafe { self.0.create_surface(raw_display_handle, raw_window_handle) },
791
792 #[cfg(all(drm, not(target_os = "netbsd")))]
793 SurfaceTargetUnsafe::Drm {
794 fd,
795 plane,
796 connector_id,
797 width,
798 height,
799 refresh_rate,
800 } => unsafe {
801 self.0
802 .create_surface_from_drm(fd, plane, connector_id, width, height, refresh_rate)
803 },
804
805 #[cfg(metal)]
806 SurfaceTargetUnsafe::CoreAnimationLayer(layer) => unsafe {
807 self.0.create_surface_metal(layer)
808 },
809
810 #[cfg(all(drm, target_os = "netbsd"))]
811 SurfaceTargetUnsafe::Drm { .. } => Err(
812 wgc::instance::CreateSurfaceError::BackendNotEnabled(wgt::Backend::Vulkan),
813 ),
814
815 #[cfg(dx12)]
816 SurfaceTargetUnsafe::CompositionVisual(visual) => unsafe {
817 self.0.create_surface_from_visual(visual)
818 },
819
820 #[cfg(dx12)]
821 SurfaceTargetUnsafe::SurfaceHandle(surface_handle) => unsafe {
822 self.0.create_surface_from_surface_handle(surface_handle)
823 },
824
825 #[cfg(dx12)]
826 SurfaceTargetUnsafe::SwapChainPanel(swap_chain_panel) => unsafe {
827 self.0
828 .create_surface_from_swap_chain_panel(swap_chain_panel)
829 },
830 }?;
831
832 Ok(CoreSurface {
833 wgpu_surface,
834 configured_device: Arc::new(Mutex::default()),
835 }
836 .into())
837 }
838
839 fn request_adapter(
840 &self,
841 options: &crate::api::RequestAdapterOptions<'_, '_>,
842 ) -> Pin<Box<dyn dispatch::RequestAdapterFuture>> {
843 let adapter = self.0.request_adapter(
844 &wgt::RequestAdapterOptions {
845 power_preference: options.power_preference,
846 force_fallback_adapter: options.force_fallback_adapter,
847 compatible_surface: options
848 .compatible_surface
849 .map(|surface| &*surface.inner.as_core().wgpu_surface),
850 apply_limit_buckets: false,
851 },
852 wgt::Backends::all(),
853 );
854 let adapter = adapter.map(|wgpu_adapter| {
855 let core = CoreAdapter { wgpu_adapter };
856 let generic: dispatch::DispatchAdapter = core.into();
857 generic
858 });
859 Box::pin(ready(adapter))
860 }
861
862 fn poll_all_devices(&self, force_wait: bool) -> bool {
863 match self.0.poll_all_devices(force_wait) {
864 Ok(all_queue_empty) => all_queue_empty,
865 Err(err) => handle_error_fatal(err, "Instance::poll_all_devices"),
866 }
867 }
868
869 #[cfg(feature = "wgsl")]
870 fn wgsl_language_features(&self) -> crate::WgslLanguageFeatures {
871 use wgc::naga::front::wgsl::ImplementedLanguageExtension;
872 ImplementedLanguageExtension::all().iter().copied().fold(
873 crate::WgslLanguageFeatures::empty(),
874 |acc, wle| {
875 acc | match wle {
876 ImplementedLanguageExtension::ReadOnlyAndReadWriteStorageTextures => {
877 crate::WgslLanguageFeatures::ReadOnlyAndReadWriteStorageTextures
878 }
879 ImplementedLanguageExtension::Packed4x8IntegerDotProduct => {
880 crate::WgslLanguageFeatures::Packed4x8IntegerDotProduct
881 }
882 ImplementedLanguageExtension::PointerCompositeAccess => {
883 crate::WgslLanguageFeatures::PointerCompositeAccess
884 }
885 ImplementedLanguageExtension::ImmediateAddressSpace => {
886 crate::WgslLanguageFeatures::ImmediateAddressSpace
887 }
888 }
889 },
890 )
891 }
892
893 fn enumerate_adapters(
894 &self,
895 backends: crate::Backends,
896 ) -> Pin<Box<dyn dispatch::EnumerateAdapterFuture>> {
897 let adapters: Vec<DispatchAdapter> = self
898 .enumerate_adapters(backends)
899 .into_iter()
900 .map(|adapter| {
901 let core = crate::backend::wgpu_core::CoreAdapter {
902 wgpu_adapter: adapter,
903 };
904 core.into()
905 })
906 .collect();
907 Box::pin(ready(adapters))
908 }
909}
910
911impl dispatch::AdapterInterface for CoreAdapter {
912 fn request_device(
913 &self,
914 desc: &crate::DeviceDescriptor<'_>,
915 ) -> Pin<Box<dyn dispatch::RequestDeviceFuture>> {
916 let res = self
917 .wgpu_adapter
918 .request_device(&desc.map_label(|l| l.map(Borrowed)));
919 let (device, queue) = match res {
920 Ok(ids) => ids,
921 Err(err) => {
922 return Box::pin(ready(Err(err.into())));
923 }
924 };
925 let device = CoreDevice {
926 wgpu_device: device,
927 };
928 let queue = CoreQueue { wgpu_queue: queue };
929 Box::pin(ready(Ok((device.into(), queue.into()))))
930 }
931
932 fn is_surface_supported(&self, surface: &dispatch::DispatchSurface) -> bool {
933 let surface = surface.as_core();
934
935 self.wgpu_adapter
936 .is_surface_supported(&surface.wgpu_surface)
937 }
938
939 fn features(&self) -> crate::Features {
940 self.wgpu_adapter.features()
941 }
942
943 fn limits(&self) -> crate::Limits {
944 self.wgpu_adapter.limits()
945 }
946
947 fn downlevel_capabilities(&self) -> crate::DownlevelCapabilities {
948 self.wgpu_adapter.downlevel_capabilities()
949 }
950
951 fn get_info(&self) -> crate::AdapterInfo {
952 self.wgpu_adapter.get_info()
953 }
954
955 fn get_texture_format_features(
956 &self,
957 format: crate::TextureFormat,
958 ) -> crate::TextureFormatFeatures {
959 self.wgpu_adapter.get_texture_format_features(format)
960 }
961
962 fn get_presentation_timestamp(&self) -> crate::PresentationTimestamp {
963 self.wgpu_adapter.get_presentation_timestamp()
964 }
965
966 fn cooperative_matrix_properties(&self) -> Vec<crate::wgt::CooperativeMatrixProperties> {
967 self.wgpu_adapter.cooperative_matrix_properties()
968 }
969}
970
971impl Drop for CoreAdapter {
972 fn drop(&mut self) {}
973}
974
975impl dispatch::DeviceInterface for CoreDevice {
976 fn features(&self) -> crate::Features {
977 *self.wgpu_device.features()
978 }
979
980 fn limits(&self) -> crate::Limits {
981 self.wgpu_device.limits().clone()
982 }
983
984 fn is_surface_supported(&self, surface: &dispatch::DispatchSurface) -> bool {
985 self.wgpu_device
986 .adapter()
987 .is_surface_supported(&surface.as_core().wgpu_surface)
988 }
989
990 fn adapter_info(&self) -> crate::AdapterInfo {
991 self.wgpu_device.adapter_info()
992 }
993
994 fn queue(&self) -> dispatch::DispatchQueue {
995 CoreQueue {
996 wgpu_queue: self.wgpu_device.get_queue().expect("Queue should be set"),
997 }
998 .into()
999 }
1000
1001 #[cfg_attr(
1003 not(any(
1004 feature = "spirv",
1005 feature = "glsl",
1006 feature = "wgsl",
1007 feature = "naga-ir"
1008 )),
1009 expect(unused)
1010 )]
1011 fn create_shader_module(
1012 &self,
1013 desc: crate::ShaderModuleDescriptor<'_>,
1014 shader_bound_checks: wgt::ShaderRuntimeChecks,
1015 ) -> dispatch::DispatchShaderModule {
1016 let descriptor = wgc::pipeline::ShaderModuleDescriptor {
1017 label: desc.label.map(Borrowed),
1018 runtime_checks: shader_bound_checks,
1019 };
1020 let source = match desc.source {
1021 #[cfg(feature = "spirv")]
1022 ShaderSource::SpirV(ref spv) => {
1023 let options = naga::front::spv::Options {
1025 adjust_coordinate_space: false, strict_capabilities: true,
1027 block_ctx_dump_prefix: None,
1028 };
1029 wgc::pipeline::ShaderModuleSource::SpirV(Borrowed(spv), options)
1030 }
1031 #[cfg(feature = "glsl")]
1032 ShaderSource::Glsl {
1033 ref shader,
1034 stage,
1035 defines,
1036 } => {
1037 let options = naga::front::glsl::Options {
1038 stage,
1039 defines: defines
1040 .iter()
1041 .map(|&(key, value)| (String::from(key), String::from(value)))
1042 .collect(),
1043 };
1044 wgc::pipeline::ShaderModuleSource::Glsl(Borrowed(shader), options)
1045 }
1046 #[cfg(feature = "wgsl")]
1047 ShaderSource::Wgsl(ref code) => wgc::pipeline::ShaderModuleSource::Wgsl(Borrowed(code)),
1048 #[cfg(feature = "naga-ir")]
1049 ShaderSource::Naga(module) => wgc::pipeline::ShaderModuleSource::Naga(module),
1050 ShaderSource::Dummy(_) => panic!("found `ShaderSource::Dummy`"),
1051 };
1052 let wgpu_shader_module = self.wgpu_device.create_shader_module(&descriptor, source);
1053
1054 CoreShaderModule { wgpu_shader_module }.into()
1055 }
1056
1057 unsafe fn create_shader_module_passthrough(
1058 &self,
1059 desc: &crate::ShaderModuleDescriptorPassthrough<'_>,
1060 ) -> dispatch::DispatchShaderModule {
1061 let desc = desc.map_label(|l| l.map(Cow::from));
1062 let wgpu_shader_module =
1063 unsafe { self.wgpu_device.create_shader_module_passthrough(&desc) };
1064
1065 CoreShaderModule { wgpu_shader_module }.into()
1066 }
1067
1068 fn create_bind_group_layout(
1069 &self,
1070 desc: &crate::BindGroupLayoutDescriptor<'_>,
1071 ) -> dispatch::DispatchBindGroupLayout {
1072 let descriptor = wgc::binding_model::BindGroupLayoutDescriptor {
1073 label: desc.label.map(Borrowed),
1074 entries: Borrowed(desc.entries),
1075 };
1076 let wgpu_bind_group_layout = self.wgpu_device.create_bind_group_layout(&descriptor);
1077 CoreBindGroupLayout {
1078 wgpu_bind_group_layout,
1079 }
1080 .into()
1081 }
1082
1083 fn create_bind_group(
1084 &self,
1085 desc: &crate::BindGroupDescriptor<'_>,
1086 ) -> dispatch::DispatchBindGroup {
1087 use wgc::binding_model as bm;
1088
1089 let mut arrayed_texture_views = Vec::new();
1090 let mut arrayed_samplers = Vec::new();
1091 if self
1092 .wgpu_device
1093 .features()
1094 .contains(Features::TEXTURE_BINDING_ARRAY)
1095 {
1096 for entry in desc.entries.iter() {
1098 if let BindingResource::TextureViewArray(array) = entry.resource {
1099 arrayed_texture_views.extend(
1100 array
1101 .iter()
1102 .map(|view| view.inner.as_core().wgpu_texture_view.clone()),
1103 );
1104 }
1105 if let BindingResource::SamplerArray(array) = entry.resource {
1106 arrayed_samplers.extend(
1107 array
1108 .iter()
1109 .map(|sampler| sampler.inner.as_core().wgpu_sampler.clone()),
1110 );
1111 }
1112 }
1113 }
1114 let mut remaining_arrayed_texture_views = &arrayed_texture_views[..];
1115 let mut remaining_arrayed_samplers = &arrayed_samplers[..];
1116
1117 let mut arrayed_buffer_bindings = Vec::new();
1118 if self
1119 .wgpu_device
1120 .features()
1121 .contains(Features::BUFFER_BINDING_ARRAY)
1122 {
1123 for entry in desc.entries.iter() {
1125 if let BindingResource::BufferArray(array) = entry.resource {
1126 arrayed_buffer_bindings.extend(array.iter().map(|binding| bm::BufferBinding {
1127 buffer: binding.buffer.inner.as_core().wgpu_buffer.clone(),
1128 offset: binding.offset,
1129 size: binding.size.map(wgt::BufferSize::get),
1130 }));
1131 }
1132 }
1133 }
1134 let mut remaining_arrayed_buffer_bindings = &arrayed_buffer_bindings[..];
1135
1136 let mut arrayed_acceleration_structures = Vec::new();
1137 if self
1138 .wgpu_device
1139 .features()
1140 .contains(Features::ACCELERATION_STRUCTURE_BINDING_ARRAY)
1141 {
1142 for entry in desc.entries.iter() {
1144 if let BindingResource::AccelerationStructureArray(array) = entry.resource {
1145 arrayed_acceleration_structures.extend(
1146 array
1147 .iter()
1148 .map(|tlas| tlas.inner.as_core().wgpu_tlas.clone()),
1149 );
1150 }
1151 }
1152 }
1153 let mut remaining_arrayed_acceleration_structures = &arrayed_acceleration_structures[..];
1154
1155 let entries = desc
1156 .entries
1157 .iter()
1158 .map(|entry| bm::BindGroupEntry {
1159 binding: entry.binding,
1160 resource: match entry.resource {
1161 BindingResource::Buffer(BufferBinding {
1162 buffer,
1163 offset,
1164 size,
1165 }) => bm::BindingResource::Buffer(bm::BufferBinding {
1166 buffer: buffer.inner.as_core().wgpu_buffer.clone(),
1167 offset,
1168 size: size.map(wgt::BufferSize::get),
1169 }),
1170 BindingResource::BufferArray(array) => {
1171 let slice = &remaining_arrayed_buffer_bindings[..array.len()];
1172 remaining_arrayed_buffer_bindings =
1173 &remaining_arrayed_buffer_bindings[array.len()..];
1174 bm::BindingResource::BufferArray(Borrowed(slice))
1175 }
1176 BindingResource::Sampler(sampler) => {
1177 bm::BindingResource::Sampler(sampler.inner.as_core().wgpu_sampler.clone())
1178 }
1179 BindingResource::SamplerArray(array) => {
1180 let slice = &remaining_arrayed_samplers[..array.len()];
1181 remaining_arrayed_samplers = &remaining_arrayed_samplers[array.len()..];
1182 bm::BindingResource::SamplerArray(Borrowed(slice))
1183 }
1184 BindingResource::TextureView(texture_view) => bm::BindingResource::TextureView(
1185 texture_view.inner.as_core().wgpu_texture_view.clone(),
1186 ),
1187 BindingResource::TextureViewArray(array) => {
1188 let slice = &remaining_arrayed_texture_views[..array.len()];
1189 remaining_arrayed_texture_views =
1190 &remaining_arrayed_texture_views[array.len()..];
1191 bm::BindingResource::TextureViewArray(Borrowed(slice))
1192 }
1193 BindingResource::AccelerationStructure(acceleration_structure) => {
1194 bm::BindingResource::AccelerationStructure(
1195 acceleration_structure.inner.as_core().wgpu_tlas.clone(),
1196 )
1197 }
1198 BindingResource::AccelerationStructureArray(array) => {
1199 let slice = &remaining_arrayed_acceleration_structures[..array.len()];
1200 remaining_arrayed_acceleration_structures =
1201 &remaining_arrayed_acceleration_structures[array.len()..];
1202 bm::BindingResource::AccelerationStructureArray(Borrowed(slice))
1203 }
1204 BindingResource::ExternalTexture(external_texture) => {
1205 bm::BindingResource::ExternalTexture(
1206 external_texture
1207 .inner
1208 .as_core()
1209 .wgpu_external_texture
1210 .clone(),
1211 )
1212 }
1213 },
1214 })
1215 .collect::<Vec<_>>();
1216 let descriptor = bm::BindGroupDescriptor {
1217 label: desc.label.as_ref().map(|label| Borrowed(&label[..])),
1218 layout: desc.layout.inner.as_core().wgpu_bind_group_layout.clone(),
1219 entries: Borrowed(&entries),
1220 };
1221
1222 let wgpu_bind_group = self.wgpu_device.create_bind_group(&descriptor);
1223 CoreBindGroup { wgpu_bind_group }.into()
1224 }
1225
1226 fn create_pipeline_layout(
1227 &self,
1228 desc: &crate::PipelineLayoutDescriptor<'_>,
1229 ) -> dispatch::DispatchPipelineLayout {
1230 assert!(
1233 desc.bind_group_layouts.len() <= wgc::MAX_BIND_GROUPS,
1234 "Bind group layout count {} exceeds device bind group limit {}",
1235 desc.bind_group_layouts.len(),
1236 wgc::MAX_BIND_GROUPS
1237 );
1238
1239 let temp_layouts = desc
1240 .bind_group_layouts
1241 .iter()
1242 .map(|bgl| bgl.map(|bgl| bgl.inner.as_core().wgpu_bind_group_layout.clone()))
1243 .collect::<ArrayVec<_, { wgc::MAX_BIND_GROUPS }>>();
1244 let descriptor = wgc::binding_model::PipelineLayoutDescriptor {
1245 label: desc.label.map(Borrowed),
1246 bind_group_layouts: Borrowed(&temp_layouts),
1247 immediate_size: desc.immediate_size,
1248 };
1249
1250 let wgpu_pipeline_layout = self.wgpu_device.create_pipeline_layout(&descriptor);
1251
1252 CorePipelineLayout {
1253 wgpu_pipeline_layout,
1254 }
1255 .into()
1256 }
1257
1258 fn create_render_pipeline(
1259 &self,
1260 desc: &crate::RenderPipelineDescriptor<'_>,
1261 ) -> dispatch::DispatchRenderPipeline {
1262 use wgc::pipeline as pipe;
1263
1264 let vertex_buffers: ArrayVec<_, { wgc::MAX_VERTEX_BUFFERS }> = desc
1265 .vertex
1266 .buffers
1267 .iter()
1268 .map(|vbuf| {
1269 vbuf.as_ref().map(|vbuf| pipe::VertexBufferLayout {
1270 array_stride: vbuf.array_stride,
1271 step_mode: vbuf.step_mode,
1272 attributes: Borrowed(vbuf.attributes),
1273 })
1274 })
1275 .collect();
1276
1277 let vert_constants = desc
1278 .vertex
1279 .compilation_options
1280 .constants
1281 .iter()
1282 .map(|&(key, value)| (String::from(key), value))
1283 .collect();
1284
1285 let descriptor = pipe::ResolvedGeneralRenderPipelineDescriptor {
1286 label: desc.label.map(Borrowed),
1287 layout: desc
1288 .layout
1289 .map(|layout| layout.inner.as_core().wgpu_pipeline_layout.clone()),
1290 vertex: wgc::pipeline::RenderPipelineVertexProcessor::Vertex(pipe::VertexState {
1291 stage: pipe::ProgrammableStageDescriptor {
1292 module: desc
1293 .vertex
1294 .module
1295 .inner
1296 .as_core()
1297 .wgpu_shader_module
1298 .clone(),
1299 entry_point: desc.vertex.entry_point.map(Borrowed),
1300 constants: vert_constants,
1301 zero_initialize_workgroup_memory: desc
1302 .vertex
1303 .compilation_options
1304 .zero_initialize_workgroup_memory,
1305 },
1306 buffers: Borrowed(&vertex_buffers),
1307 }),
1308 primitive: desc.primitive,
1309 depth_stencil: desc.depth_stencil.clone(),
1310 multisample: desc.multisample,
1311 fragment: desc.fragment.as_ref().map(|frag| {
1312 let frag_constants = frag
1313 .compilation_options
1314 .constants
1315 .iter()
1316 .map(|&(key, value)| (String::from(key), value))
1317 .collect();
1318 pipe::FragmentState {
1319 stage: pipe::ProgrammableStageDescriptor {
1320 module: frag.module.inner.as_core().wgpu_shader_module.clone(),
1321 entry_point: frag.entry_point.map(Borrowed),
1322 constants: frag_constants,
1323 zero_initialize_workgroup_memory: frag
1324 .compilation_options
1325 .zero_initialize_workgroup_memory,
1326 },
1327 targets: Borrowed(frag.targets),
1328 }
1329 }),
1330 multiview_mask: desc.multiview_mask,
1331 cache: desc
1332 .cache
1333 .map(|cache| cache.inner.as_core().wgpu_pipeline_cache.clone()),
1334 };
1335
1336 let wgpu_render_pipeline = self.wgpu_device.create_render_pipeline(descriptor);
1337 CoreRenderPipeline {
1338 wgpu_render_pipeline,
1339 }
1340 .into()
1341 }
1342
1343 fn create_mesh_pipeline(
1344 &self,
1345 desc: &crate::MeshPipelineDescriptor<'_>,
1346 ) -> dispatch::DispatchRenderPipeline {
1347 use wgc::pipeline as pipe;
1348
1349 let mesh_constants = desc
1350 .mesh
1351 .compilation_options
1352 .constants
1353 .iter()
1354 .map(|&(key, value)| (String::from(key), value))
1355 .collect();
1356 let descriptor = pipe::MeshPipelineDescriptor {
1357 label: desc.label.map(Borrowed),
1358 task: desc.task.as_ref().map(|task| {
1359 let task_constants = task
1360 .compilation_options
1361 .constants
1362 .iter()
1363 .map(|&(key, value)| (String::from(key), value))
1364 .collect();
1365 pipe::TaskState {
1366 stage: pipe::ProgrammableStageDescriptor {
1367 module: task.module.inner.as_core().wgpu_shader_module.clone(),
1368 entry_point: task.entry_point.map(Borrowed),
1369 constants: task_constants,
1370 zero_initialize_workgroup_memory: desc
1371 .mesh
1372 .compilation_options
1373 .zero_initialize_workgroup_memory,
1374 },
1375 }
1376 }),
1377 mesh: pipe::MeshState {
1378 stage: pipe::ProgrammableStageDescriptor {
1379 module: desc.mesh.module.inner.as_core().wgpu_shader_module.clone(),
1380 entry_point: desc.mesh.entry_point.map(Borrowed),
1381 constants: mesh_constants,
1382 zero_initialize_workgroup_memory: desc
1383 .mesh
1384 .compilation_options
1385 .zero_initialize_workgroup_memory,
1386 },
1387 },
1388 layout: desc
1389 .layout
1390 .map(|layout| layout.inner.as_core().wgpu_pipeline_layout.clone()),
1391 primitive: desc.primitive,
1392 depth_stencil: desc.depth_stencil.clone(),
1393 multisample: desc.multisample,
1394 fragment: desc.fragment.as_ref().map(|frag| {
1395 let frag_constants = frag
1396 .compilation_options
1397 .constants
1398 .iter()
1399 .map(|&(key, value)| (String::from(key), value))
1400 .collect();
1401 pipe::FragmentState {
1402 stage: pipe::ProgrammableStageDescriptor {
1403 module: frag.module.inner.as_core().wgpu_shader_module.clone(),
1404 entry_point: frag.entry_point.map(Borrowed),
1405 constants: frag_constants,
1406 zero_initialize_workgroup_memory: frag
1407 .compilation_options
1408 .zero_initialize_workgroup_memory,
1409 },
1410 targets: Borrowed(frag.targets),
1411 }
1412 }),
1413 multiview: desc.multiview,
1414 cache: desc
1415 .cache
1416 .map(|cache| cache.inner.as_core().wgpu_pipeline_cache.clone()),
1417 };
1418
1419 let wgpu_render_pipeline = self.wgpu_device.create_render_pipeline(descriptor.into());
1420 CoreRenderPipeline {
1421 wgpu_render_pipeline,
1422 }
1423 .into()
1424 }
1425
1426 fn create_compute_pipeline(
1427 &self,
1428 desc: &crate::ComputePipelineDescriptor<'_>,
1429 ) -> dispatch::DispatchComputePipeline {
1430 use wgc::pipeline as pipe;
1431
1432 let constants = desc
1433 .compilation_options
1434 .constants
1435 .iter()
1436 .map(|&(key, value)| (String::from(key), value))
1437 .collect();
1438
1439 let descriptor = pipe::ComputePipelineDescriptor {
1440 label: desc.label.map(Borrowed),
1441 layout: desc
1442 .layout
1443 .map(|pll| pll.inner.as_core().wgpu_pipeline_layout.clone()),
1444 stage: pipe::ProgrammableStageDescriptor {
1445 module: desc.module.inner.as_core().wgpu_shader_module.clone(),
1446 entry_point: desc.entry_point.map(Borrowed),
1447 constants,
1448 zero_initialize_workgroup_memory: desc
1449 .compilation_options
1450 .zero_initialize_workgroup_memory,
1451 },
1452 cache: desc
1453 .cache
1454 .map(|cache| cache.inner.as_core().wgpu_pipeline_cache.clone()),
1455 };
1456
1457 let wgpu_compute_pipeline = self.wgpu_device.create_compute_pipeline(descriptor);
1458 CoreComputePipeline {
1459 wgpu_compute_pipeline,
1460 }
1461 .into()
1462 }
1463
1464 fn create_ray_tracing_pipeline(
1465 &self,
1466 desc: &crate::RayTracingPipelineDescriptor<'_>,
1467 ) -> dispatch::DispatchRayTracingPipeline {
1468 use wgc::pipeline as pipe;
1469 use wgc::ray_tracing_pipeline as rt_pipe;
1470
1471 fn downcast_rt_stage<'a>(
1472 stage: &'a crate::RayTracingStage<'a>,
1473 ) -> pipe::ProgrammableStageDescriptor<'a> {
1474 pipe::ProgrammableStageDescriptor {
1475 module: stage.module.inner.as_core().wgpu_shader_module.clone(),
1476 entry_point: stage.entry_point.map(Borrowed),
1477 constants: stage
1478 .compilation_options
1479 .constants
1480 .iter()
1481 .map(|&(key, value)| (String::from(key), value))
1482 .collect(),
1483 zero_initialize_workgroup_memory: stage
1484 .compilation_options
1485 .zero_initialize_workgroup_memory,
1486 }
1487 }
1488
1489 let descriptor = rt_pipe::RayTracingPipelineDescriptor {
1490 label: desc.label.map(Borrowed),
1491 layout: desc
1492 .layout
1493 .map(|pll| pll.inner.as_core().wgpu_pipeline_layout.clone()),
1494 ray_generation: downcast_rt_stage(&desc.ray_generation),
1495 miss: downcast_rt_stage(&desc.miss),
1496 intersections: desc
1497 .intersections
1498 .iter()
1499 .map(|intersection_desc| match intersection_desc {
1500 crate::RayTracingIntersectionDescriptor::Triangle {
1501 closest_hit,
1502 any_hit,
1503 } => rt_pipe::RayTracingIntersectionDescriptor::Triangle {
1504 closest_hit: downcast_rt_stage(closest_hit),
1505 any_hit: any_hit.as_ref().map(|stage| downcast_rt_stage(stage)),
1506 },
1507 })
1508 .collect::<Vec<_>>(),
1509 max_recursion_depth: desc.max_recursion_depth,
1510 cache: desc
1511 .cache
1512 .map(|cache| cache.inner.as_core().wgpu_pipeline_cache.clone()),
1513 };
1514
1515 let (wgpu_ray_tracing_pipeline, error) =
1516 self.wgpu_device.create_ray_tracing_pipeline(descriptor);
1517 if let Some(cause) = error {
1518 if let pipe::CreatePipelineError::Internal { stage, ref message } = cause {
1519 log::error!(
1520 "Shader translation error for stage {:?}: {}",
1521 stage,
1522 message
1523 );
1524 log::error!("Please report it to https://github.com/gfx-rs/wgpu");
1525 }
1526 self.wgpu_device
1527 .handle_error(cause, desc.label, "Device::create_ray_tracing_pipeline");
1528 }
1529 CoreRayTracingPipeline {
1530 wgpu_ray_tracing_pipeline,
1531 }
1532 .into()
1533 }
1534
1535 unsafe fn create_pipeline_cache(
1536 &self,
1537 desc: &crate::PipelineCacheDescriptor<'_>,
1538 ) -> dispatch::DispatchPipelineCache {
1539 use wgc::pipeline as pipe;
1540
1541 let descriptor = pipe::PipelineCacheDescriptor {
1542 label: desc.label.map(Borrowed),
1543 data: desc.data.map(Borrowed),
1544 fallback: desc.fallback,
1545 };
1546 let (wgpu_pipeline_cache, error) =
1547 unsafe { self.wgpu_device.create_pipeline_cache(&descriptor) };
1548 if let Some(cause) = error {
1549 self.wgpu_device.handle_error(
1550 cause,
1551 desc.label,
1552 "Device::device_create_pipeline_cache_init",
1553 );
1554 }
1555 CorePipelineCache {
1556 wgpu_pipeline_cache,
1557 }
1558 .into()
1559 }
1560
1561 fn create_buffer(&self, desc: &crate::BufferDescriptor<'_>) -> dispatch::DispatchBuffer {
1562 let wgpu_buffer = self
1563 .wgpu_device
1564 .create_buffer(&desc.map_label(|l| l.map(Borrowed)));
1565
1566 CoreBuffer { wgpu_buffer }.into()
1567 }
1568
1569 fn create_texture(&self, desc: &crate::TextureDescriptor<'_>) -> dispatch::DispatchTexture {
1570 let wgt_desc = desc.map_label_and_view_formats(|l| l.map(Borrowed), |v| v.to_vec());
1571 let wgpu_texture = self.wgpu_device.create_texture(&wgt_desc);
1572
1573 CoreTexture { wgpu_texture }.into()
1574 }
1575
1576 fn create_external_texture(
1577 &self,
1578 desc: &crate::ExternalTextureDescriptor<'_>,
1579 planes: &[&crate::TextureView],
1580 ) -> dispatch::DispatchExternalTexture {
1581 let wgt_desc = desc.map_label(|l| l.map(Borrowed));
1582 let planes = planes
1583 .iter()
1584 .map(|plane| plane.inner.as_core().wgpu_texture_view.clone())
1585 .collect::<Vec<_>>();
1586 let wgpu_external_texture = self.wgpu_device.create_external_texture(&wgt_desc, &planes);
1587
1588 CoreExternalTexture {
1589 wgpu_external_texture,
1590 }
1591 .into()
1592 }
1593
1594 fn create_blas(
1595 &self,
1596 desc: &crate::CreateBlasDescriptor<'_>,
1597 sizes: crate::BlasGeometrySizeDescriptors,
1598 ) -> (Option<u64>, dispatch::DispatchBlas) {
1599 let (wgpu_blas, error) = self
1600 .wgpu_device
1601 .create_blas(&desc.map_label(|l| l.map(Borrowed)), sizes);
1602 if let Some(cause) = error {
1603 self.wgpu_device
1604 .handle_error(cause, desc.label, "Device::create_blas");
1605 }
1606 (wgpu_blas.handle(), CoreBlas { wgpu_blas }.into())
1607 }
1608
1609 fn create_tlas(&self, desc: &crate::CreateTlasDescriptor<'_>) -> dispatch::DispatchTlas {
1610 let (wgpu_tlas, error) = self
1611 .wgpu_device
1612 .create_tlas(&desc.map_label(|l| l.map(Borrowed)));
1613 if let Some(cause) = error {
1614 self.wgpu_device
1615 .handle_error(cause, desc.label, "Device::create_tlas");
1616 }
1617 CoreTlas { wgpu_tlas }.into()
1618 }
1619
1620 fn create_sampler(&self, desc: &crate::SamplerDescriptor<'_>) -> dispatch::DispatchSampler {
1621 let descriptor = wgc::resource::SamplerDescriptor {
1622 label: desc.label.map(Borrowed),
1623 address_modes: [
1624 desc.address_mode_u,
1625 desc.address_mode_v,
1626 desc.address_mode_w,
1627 ],
1628 mag_filter: desc.mag_filter,
1629 min_filter: desc.min_filter,
1630 mipmap_filter: desc.mipmap_filter,
1631 lod_min_clamp: desc.lod_min_clamp,
1632 lod_max_clamp: desc.lod_max_clamp,
1633 compare: desc.compare,
1634 anisotropy_clamp: desc.anisotropy_clamp,
1635 border_color: desc.border_color,
1636 };
1637
1638 let wgpu_sampler = self.wgpu_device.create_sampler(&descriptor);
1639 CoreSampler { wgpu_sampler }.into()
1640 }
1641
1642 fn create_query_set(&self, desc: &crate::QuerySetDescriptor<'_>) -> dispatch::DispatchQuerySet {
1643 let wgpu_query_set = self
1644 .wgpu_device
1645 .create_query_set(&desc.map_label(|l| l.map(Borrowed)));
1646 CoreQuerySet { wgpu_query_set }.into()
1647 }
1648
1649 fn create_command_encoder(
1650 &self,
1651 desc: &crate::CommandEncoderDescriptor<'_>,
1652 ) -> dispatch::DispatchCommandEncoder {
1653 let wgpu_command_encoder = self
1654 .wgpu_device
1655 .create_command_encoder(&desc.map_label(|l| l.map(Borrowed)));
1656
1657 CoreCommandEncoder {
1658 wgpu_command_encoder,
1659 }
1660 .into()
1661 }
1662
1663 fn create_render_bundle_encoder(
1664 &self,
1665 desc: &crate::RenderBundleEncoderDescriptor<'_>,
1666 ) -> dispatch::DispatchRenderBundleEncoder {
1667 let descriptor = wgc::command::RenderBundleEncoderDescriptor {
1668 label: desc.label.map(Borrowed),
1669 color_formats: Borrowed(desc.color_formats),
1670 depth_stencil: desc.depth_stencil,
1671 sample_count: desc.sample_count,
1672 multiview: desc.multiview,
1673 };
1674 let encoder = self.wgpu_device.create_render_bundle_encoder(&descriptor);
1675
1676 CoreRenderBundleEncoder { encoder }.into()
1677 }
1678
1679 fn set_device_lost_callback(&self, device_lost_callback: dispatch::BoxDeviceLostCallback) {
1680 self.wgpu_device
1681 .set_device_lost_closure(device_lost_callback);
1682 }
1683
1684 fn on_uncaptured_error(&self, handler: Arc<dyn crate::UncapturedErrorHandler>) {
1685 self.wgpu_device.on_uncaptured_error(handler);
1686 }
1687
1688 fn push_error_scope(&self, filter: crate::ErrorFilter) -> u32 {
1689 self.wgpu_device.push_error_scope_with_index(filter)
1690 }
1691
1692 fn pop_error_scope(&self, index: u32) -> Pin<Box<dyn dispatch::PopErrorScopeFuture>> {
1693 Box::pin(ready(self.wgpu_device.pop_error_scope_checked(index)))
1694 }
1695
1696 unsafe fn start_graphics_debugger_capture(&self) {
1697 unsafe { self.wgpu_device.start_graphics_debugger_capture() };
1698 }
1699
1700 unsafe fn stop_graphics_debugger_capture(&self) {
1701 unsafe { self.wgpu_device.stop_graphics_debugger_capture() };
1702 }
1703
1704 fn poll(&self, poll_type: wgt::PollType<u64>) -> Result<crate::PollStatus, crate::PollError> {
1705 match self.wgpu_device.poll(poll_type) {
1706 Ok(status) => Ok(status),
1707 Err(err) => {
1708 if let Some(poll_error) = err.to_poll_error() {
1709 return Err(poll_error);
1710 }
1711
1712 handle_error_fatal(err, "Device::poll")
1713 }
1714 }
1715 }
1716
1717 fn get_internal_counters(&self) -> crate::InternalCounters {
1718 self.wgpu_device.get_internal_counters()
1719 }
1720
1721 fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> {
1722 self.wgpu_device.generate_allocator_report()
1723 }
1724
1725 fn destroy(&self) {
1726 self.wgpu_device.destroy();
1727 }
1728}
1729
1730impl Drop for CoreDevice {
1731 fn drop(&mut self) {}
1732}
1733
1734impl dispatch::QueueInterface for CoreQueue {
1735 fn write_buffer(
1736 &self,
1737 buffer: &dispatch::DispatchBuffer,
1738 offset: crate::BufferAddress,
1739 data: &[u8],
1740 ) {
1741 let buffer = buffer.as_core();
1742
1743 self.wgpu_queue
1744 .write_buffer(buffer.wgpu_buffer.clone(), offset, data)
1745 }
1746
1747 fn create_staging_buffer(
1748 &self,
1749 size: crate::BufferSize,
1750 ) -> Option<dispatch::DispatchQueueWriteBuffer> {
1751 match self.wgpu_queue.create_staging_buffer(size) {
1752 Ok((wgpu_staging_buffer, _)) => Some(
1753 CoreQueueWriteBuffer {
1754 wgpu_staging_buffer,
1755 }
1756 .into(),
1757 ),
1758 Err(err) => {
1759 self.wgpu_queue
1760 .device()
1761 .handle_error_nolabel(err, "Queue::write_buffer_with");
1762 None
1763 }
1764 }
1765 }
1766
1767 fn validate_write_buffer(
1768 &self,
1769 buffer: &dispatch::DispatchBuffer,
1770 offset: wgt::BufferAddress,
1771 size: wgt::BufferSize,
1772 ) -> Option<()> {
1773 let buffer = buffer.as_core();
1774
1775 match self
1776 .wgpu_queue
1777 .validate_write_buffer(buffer.wgpu_buffer.clone(), offset, size)
1778 {
1779 Ok(()) => Some(()),
1780 Err(err) => {
1781 self.wgpu_queue
1782 .device()
1783 .handle_error_nolabel(err, "Queue::write_buffer_with");
1784 None
1785 }
1786 }
1787 }
1788
1789 fn write_staging_buffer(
1790 &self,
1791 buffer: &dispatch::DispatchBuffer,
1792 offset: crate::BufferAddress,
1793 staging_buffer: dispatch::DispatchQueueWriteBuffer,
1794 ) {
1795 let buffer = buffer.as_core();
1796 let staging_buffer = {
1797 #[allow(
1798 clippy::allow_attributes,
1799 unreachable_patterns,
1800 reason = "features may be disabled"
1801 )]
1802 match staging_buffer {
1803 dispatch::DispatchQueueWriteBuffer::Core(value) => value,
1804 _ => panic!(concat!(
1805 stringify!(DispatchQueueWriteBuffer),
1806 " is not core"
1807 )),
1808 }
1809 };
1810
1811 match self.wgpu_queue.write_staging_buffer(
1812 buffer.wgpu_buffer.clone(),
1813 offset,
1814 staging_buffer.wgpu_staging_buffer,
1815 ) {
1816 Ok(()) => (),
1817 Err(err) => {
1818 self.wgpu_queue
1819 .device()
1820 .handle_error_nolabel(err, "Queue::write_buffer_with");
1821 }
1822 }
1823 }
1824
1825 fn write_texture(
1826 &self,
1827 texture: crate::TexelCopyTextureInfo<'_>,
1828 data: &[u8],
1829 data_layout: crate::TexelCopyBufferLayout,
1830 size: crate::Extent3d,
1831 ) {
1832 self.wgpu_queue
1833 .write_texture(map_texture_copy_view(texture), data, &data_layout, &size);
1834 }
1835
1836 #[cfg(web)]
1839 #[cfg_attr(not(webgl), expect(unused_variables))]
1840 fn copy_external_image_to_texture(
1841 &self,
1842 source: &crate::CopyExternalImageSourceInfo,
1843 dest: crate::CopyExternalImageDestInfo<&crate::api::Texture>,
1844 size: crate::Extent3d,
1845 ) {
1846 #[cfg(webgl)]
1847 match self.wgpu_queue.copy_external_image_to_texture(
1848 source,
1849 map_texture_tagged_copy_view(dest),
1850 size,
1851 ) {
1852 Ok(()) => (),
1853 Err(err) => self
1854 .wgpu_queue
1855 .device()
1856 .handle_error_nolabel(err, "Queue::copy_external_image_to_texture"),
1857 }
1858 }
1859
1860 fn submit(
1861 &self,
1862 command_buffers: &mut dyn Iterator<Item = dispatch::DispatchCommandBuffer>,
1863 ) -> Option<u64> {
1864 let temp_command_buffers = command_buffers.collect::<SmallVec<[_; 4]>>();
1865 let command_buffers = temp_command_buffers
1866 .iter()
1867 .map(|cmdbuf| cmdbuf.as_core().wgpu_command_buffer.clone())
1868 .collect::<SmallVec<[_; 4]>>();
1869
1870 let index = self.wgpu_queue.submit(&command_buffers);
1871
1872 drop(temp_command_buffers);
1873
1874 index
1875 }
1876
1877 fn get_timestamp_period(&self) -> f32 {
1878 self.wgpu_queue.get_timestamp_period()
1879 }
1880
1881 fn on_submitted_work_done(&self, callback: dispatch::BoxSubmittedWorkDoneCallback) {
1882 self.wgpu_queue.on_submitted_work_done(callback);
1883 }
1884
1885 fn compact_blas(&self, blas: &dispatch::DispatchBlas) -> (Option<u64>, dispatch::DispatchBlas) {
1886 let (wgpu_blas, error) = self.wgpu_queue.compact_blas(&blas.as_core().wgpu_blas);
1887
1888 if let Some(cause) = error {
1889 self.wgpu_queue
1890 .device()
1891 .handle_error_nolabel(cause, "Queue::compact_blas");
1892 }
1893 (wgpu_blas.handle(), CoreBlas { wgpu_blas }.into())
1894 }
1895
1896 fn present(&self, detail: &dispatch::DispatchSurfaceOutputDetail) {
1897 self.present_with_damage(detail, &[]);
1898 }
1899
1900 fn present_with_damage(
1901 &self,
1902 detail: &dispatch::DispatchSurfaceOutputDetail,
1903 damage_rects: &[wgt::Rect<u32>],
1904 ) {
1905 let detail = detail.as_core();
1906 match detail.wgpu_surface.present_with_damage(damage_rects) {
1907 Ok(_status) => (),
1908 Err(err) => {
1909 self.wgpu_queue
1910 .device()
1911 .handle_error_nolabel(err, "Queue::present");
1912 }
1913 }
1914 }
1915}
1916
1917impl dispatch::ShaderModuleInterface for CoreShaderModule {
1918 fn get_compilation_info(&self) -> Pin<Box<dyn dispatch::ShaderCompilationInfoFuture>> {
1919 Box::pin(ready(self.wgpu_shader_module.compilation_info().clone()))
1920 }
1921}
1922
1923impl dispatch::BindGroupLayoutInterface for CoreBindGroupLayout {}
1924
1925impl dispatch::BindGroupInterface for CoreBindGroup {}
1926
1927impl dispatch::TextureViewInterface for CoreTextureView {}
1928
1929impl dispatch::ExternalTextureInterface for CoreExternalTexture {
1930 fn destroy(&self) {
1931 self.wgpu_external_texture.destroy();
1932 }
1933}
1934
1935impl dispatch::SamplerInterface for CoreSampler {}
1936
1937impl dispatch::BufferInterface for CoreBuffer {
1938 fn map_async(
1939 &self,
1940 mode: crate::MapMode,
1941 range: Range<crate::BufferAddress>,
1942 callback: dispatch::BufferMapCallback,
1943 ) {
1944 self.wgpu_buffer.map_async(
1945 mode,
1946 range.start,
1947 Some(range.end - range.start),
1948 Some(Box::new(|status| {
1949 let res = status.map(|_| ()).map_err(|_| crate::BufferAsyncError);
1950 callback(res);
1951 })),
1952 );
1953 }
1954
1955 fn get_mapped_range(
1956 &self,
1957 sub_range: Range<crate::BufferAddress>,
1958 ) -> Result<dispatch::DispatchBufferMappedRange, crate::MapRangeError> {
1959 let size = sub_range.end - sub_range.start;
1960 self.wgpu_buffer
1961 .get_mapped_range(sub_range.start, Some(size))
1962 .map(|mapping| CoreBufferMappedRange(mapping).into())
1963 .map_err(|err| crate::MapRangeError(format_error(&err)))
1964 }
1965
1966 fn unmap(&self) {
1967 self.wgpu_buffer.unmap();
1968 }
1969
1970 fn destroy(&self) {
1971 self.wgpu_buffer.destroy();
1972 }
1973
1974 fn size(&self) -> crate::BufferAddress {
1975 self.wgpu_buffer.size()
1976 }
1977
1978 fn usage(&self) -> crate::BufferUsages {
1979 self.wgpu_buffer.usage()
1980 }
1981}
1982
1983impl dispatch::TextureInterface for CoreTexture {
1984 fn create_view(
1985 &self,
1986 desc: &crate::TextureViewDescriptor<'_>,
1987 ) -> dispatch::DispatchTextureView {
1988 let descriptor = wgc::resource::TextureViewDescriptor {
1989 label: desc.label.map(Borrowed),
1990 format: desc.format,
1991 dimension: desc.dimension,
1992 usage: desc.usage,
1993 range: wgt::ImageSubresourceRange {
1994 aspect: desc.aspect,
1995 base_mip_level: desc.base_mip_level,
1996 mip_level_count: desc.mip_level_count,
1997 base_array_layer: desc.base_array_layer,
1998 array_layer_count: desc.array_layer_count,
1999 },
2000 swizzle: desc.swizzle,
2001 };
2002 let wgpu_texture_view = self.wgpu_texture.create_view(&descriptor);
2003 CoreTextureView { wgpu_texture_view }.into()
2004 }
2005
2006 fn destroy(&self) {
2007 self.wgpu_texture.destroy();
2008 }
2009
2010 fn size(&self) -> wgt::Extent3d {
2011 self.wgpu_texture.descriptor().size
2012 }
2013
2014 fn mip_level_count(&self) -> u32 {
2015 self.wgpu_texture.descriptor().mip_level_count
2016 }
2017
2018 fn sample_count(&self) -> u32 {
2019 self.wgpu_texture.descriptor().sample_count
2020 }
2021
2022 fn dimension(&self) -> wgt::TextureDimension {
2023 self.wgpu_texture.descriptor().dimension
2024 }
2025
2026 fn format(&self) -> wgt::TextureFormat {
2027 self.wgpu_texture.descriptor().format
2028 }
2029
2030 fn usage(&self) -> wgt::TextureUsages {
2031 self.wgpu_texture.descriptor().usage
2032 }
2033
2034 unsafe fn mark_externally_initialized(&self) {
2035 unsafe { self.wgpu_texture.mark_externally_initialized() }
2036 }
2037
2038 fn texture_binding_view_dimension(&self) -> Option<crate::TextureViewDimension> {
2039 self.wgpu_texture.texture_binding_view_dimension()
2040 }
2041}
2042
2043impl dispatch::BlasInterface for CoreBlas {
2044 fn prepare_compact_async(&self, callback: BlasCompactCallback) {
2045 let callback: Option<wgc::resource::BlasCompactCallback> =
2046 Some(Box::new(|status: BlasPrepareCompactResult| {
2047 let res = status.map_err(|_| crate::BlasAsyncError);
2048 callback(res);
2049 }));
2050
2051 match self.wgpu_blas.prepare_compact_async(callback) {
2052 Ok(_) => (),
2053 Err(cause) => self
2054 .wgpu_blas
2055 .device()
2056 .handle_error_nolabel(cause, "Blas::prepare_compact_async"),
2057 }
2058 }
2059
2060 fn ready_for_compaction(&self) -> bool {
2061 match self.wgpu_blas.ready_for_compaction() {
2062 Ok(ready) => ready,
2063 Err(cause) => {
2064 self.wgpu_blas
2065 .device()
2066 .handle_error_nolabel(cause, "Blas::ready_for_compaction");
2067 false
2069 }
2070 }
2071 }
2072}
2073
2074impl dispatch::TlasInterface for CoreTlas {}
2075
2076impl dispatch::QuerySetInterface for CoreQuerySet {
2077 fn destroy(&self) {
2078 self.wgpu_query_set.destroy();
2079 }
2080
2081 fn ty(&self) -> crate::QueryType {
2082 self.wgpu_query_set.descriptor().ty
2083 }
2084
2085 fn count(&self) -> u32 {
2086 self.wgpu_query_set.descriptor().count
2087 }
2088}
2089
2090impl dispatch::PipelineLayoutInterface for CorePipelineLayout {}
2091
2092impl dispatch::RenderPipelineInterface for CoreRenderPipeline {
2093 fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout {
2094 let wgpu_bind_group_layout = self.wgpu_render_pipeline.get_bind_group_layout(index);
2095 CoreBindGroupLayout {
2096 wgpu_bind_group_layout,
2097 }
2098 .into()
2099 }
2100}
2101
2102impl dispatch::RayTracingPipelineInterface for CoreRayTracingPipeline {
2103 fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout {
2104 let (wgpu_bind_group_layout, error) =
2105 self.wgpu_ray_tracing_pipeline.get_bind_group_layout(index);
2106 if let Some(err) = error {
2107 self.wgpu_ray_tracing_pipeline
2108 .device()
2109 .handle_error_nolabel(err, "RayTracingPipeline::get_bind_group_layout")
2110 }
2111 CoreBindGroupLayout {
2112 wgpu_bind_group_layout,
2113 }
2114 .into()
2115 }
2116}
2117
2118impl dispatch::ComputePipelineInterface for CoreComputePipeline {
2119 fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout {
2120 let wgpu_bind_group_layout = self.wgpu_compute_pipeline.get_bind_group_layout(index);
2121 CoreBindGroupLayout {
2122 wgpu_bind_group_layout,
2123 }
2124 .into()
2125 }
2126}
2127
2128impl dispatch::PipelineCacheInterface for CorePipelineCache {
2129 fn get_data(&self) -> Option<Vec<u8>> {
2130 self.wgpu_pipeline_cache.get_data()
2131 }
2132}
2133
2134impl dispatch::CommandEncoderInterface for CoreCommandEncoder {
2135 fn copy_buffer_to_buffer(
2136 &self,
2137 source: &dispatch::DispatchBuffer,
2138 source_offset: crate::BufferAddress,
2139 destination: &dispatch::DispatchBuffer,
2140 destination_offset: crate::BufferAddress,
2141 copy_size: Option<crate::BufferAddress>,
2142 ) {
2143 let source = source.as_core();
2144 let destination = destination.as_core();
2145
2146 self.wgpu_command_encoder.copy_buffer_to_buffer(
2147 source.wgpu_buffer.clone(),
2148 source_offset,
2149 destination.wgpu_buffer.clone(),
2150 destination_offset,
2151 copy_size,
2152 )
2153 }
2154
2155 fn copy_buffer_to_texture(
2156 &self,
2157 source: crate::TexelCopyBufferInfo<'_>,
2158 destination: crate::TexelCopyTextureInfo<'_>,
2159 copy_size: crate::Extent3d,
2160 ) {
2161 self.wgpu_command_encoder.copy_buffer_to_texture(
2162 &map_buffer_copy_view(source),
2163 &map_texture_copy_view(destination),
2164 ©_size,
2165 )
2166 }
2167
2168 fn copy_texture_to_buffer(
2169 &self,
2170 source: crate::TexelCopyTextureInfo<'_>,
2171 destination: crate::TexelCopyBufferInfo<'_>,
2172 copy_size: crate::Extent3d,
2173 ) {
2174 self.wgpu_command_encoder.copy_texture_to_buffer(
2175 &map_texture_copy_view(source),
2176 &map_buffer_copy_view(destination),
2177 ©_size,
2178 );
2179 }
2180
2181 fn copy_texture_to_texture(
2182 &self,
2183 source: crate::TexelCopyTextureInfo<'_>,
2184 destination: crate::TexelCopyTextureInfo<'_>,
2185 copy_size: crate::Extent3d,
2186 ) {
2187 self.wgpu_command_encoder.copy_texture_to_texture(
2188 &map_texture_copy_view(source),
2189 &map_texture_copy_view(destination),
2190 ©_size,
2191 );
2192 }
2193
2194 fn begin_compute_pass(
2195 &self,
2196 desc: &crate::ComputePassDescriptor<'_>,
2197 ) -> dispatch::DispatchComputePass {
2198 let timestamp_writes =
2199 desc.timestamp_writes
2200 .as_ref()
2201 .map(|tw| wgc::command::PassTimestampWrites {
2202 query_set: tw.query_set.inner.as_core().wgpu_query_set.clone(),
2203 beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
2204 end_of_pass_write_index: tw.end_of_pass_write_index,
2205 });
2206
2207 let pass =
2208 self.wgpu_command_encoder
2209 .begin_compute_pass(&wgc::command::ComputePassDescriptor {
2210 label: desc.label.map(Borrowed),
2211 timestamp_writes,
2212 });
2213
2214 CoreComputePass {
2215 pass,
2216 id: crate::cmp::Identifier::create(),
2217 }
2218 .into()
2219 }
2220
2221 fn begin_render_pass(
2222 &self,
2223 desc: &crate::RenderPassDescriptor<'_>,
2224 ) -> dispatch::DispatchRenderPass {
2225 let colors = desc
2226 .color_attachments
2227 .iter()
2228 .map(|ca| {
2229 ca.as_ref()
2230 .map(|at| wgc::command::RenderPassColorAttachment {
2231 view: at.view.inner.as_core().wgpu_texture_view.clone(),
2232 depth_slice: at.depth_slice,
2233 resolve_target: at
2234 .resolve_target
2235 .map(|view| view.inner.as_core().wgpu_texture_view.clone()),
2236 load_op: at.ops.load,
2237 store_op: at.ops.store,
2238 })
2239 })
2240 .collect::<Vec<_>>();
2241
2242 let depth_stencil = desc.depth_stencil_attachment.as_ref().map(|dsa| {
2243 wgc::command::RenderPassDepthStencilAttachment {
2244 view: dsa.view.inner.as_core().wgpu_texture_view.clone(),
2245 depth: map_pass_channel(dsa.depth_ops.as_ref()),
2246 stencil: map_pass_channel(dsa.stencil_ops.as_ref()),
2247 }
2248 });
2249
2250 let timestamp_writes =
2251 desc.timestamp_writes
2252 .as_ref()
2253 .map(|tw| wgc::command::PassTimestampWrites {
2254 query_set: tw.query_set.inner.as_core().wgpu_query_set.clone(),
2255 beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
2256 end_of_pass_write_index: tw.end_of_pass_write_index,
2257 });
2258
2259 let pass = self.wgpu_command_encoder.begin_render_pass(
2260 wgc::command::ResolvedRenderPassDescriptor {
2261 label: desc.label.map(Borrowed),
2262 timestamp_writes,
2263 color_attachments: Borrowed(&colors),
2264 depth_stencil_attachment: depth_stencil,
2265 occlusion_query_set: desc
2266 .occlusion_query_set
2267 .map(|qs| qs.inner.as_core().wgpu_query_set.clone()),
2268 multiview_mask: desc.multiview_mask,
2269 },
2270 );
2271
2272 CoreRenderPass {
2273 pass,
2274 id: crate::cmp::Identifier::create(),
2275 }
2276 .into()
2277 }
2278
2279 fn begin_ray_tracing_pass(
2280 &self,
2281 desc: &crate::RayTracingPassDescriptor<'_>,
2282 ) -> dispatch::DispatchRayTracingPass {
2283 let pass = self.wgpu_command_encoder.begin_ray_tracing_pass(
2284 &wgc::command::RayTracingPassDescriptor {
2285 label: desc.label.map(Borrowed),
2286 },
2287 );
2288
2289 CoreRayTracingPass {
2290 pass,
2291 id: crate::cmp::Identifier::create(),
2292 }
2293 .into()
2294 }
2295
2296 fn finish(&mut self) -> dispatch::DispatchCommandBuffer {
2297 let descriptor = wgt::CommandBufferDescriptor::default();
2298 let wgpu_command_buffer = self.wgpu_command_encoder.finish(&descriptor);
2299 CoreCommandBuffer {
2300 wgpu_command_buffer,
2301 }
2302 .into()
2303 }
2304
2305 fn clear_texture(
2306 &self,
2307 texture: &dispatch::DispatchTexture,
2308 subresource_range: &crate::ImageSubresourceRange,
2309 ) {
2310 let texture = texture.as_core();
2311
2312 self.wgpu_command_encoder
2313 .clear_texture(texture.wgpu_texture.clone(), subresource_range)
2314 }
2315
2316 fn clear_buffer(
2317 &self,
2318 buffer: &dispatch::DispatchBuffer,
2319 offset: crate::BufferAddress,
2320 size: Option<crate::BufferAddress>,
2321 ) {
2322 let buffer = buffer.as_core();
2323
2324 self.wgpu_command_encoder
2325 .clear_buffer(buffer.wgpu_buffer.clone(), offset, size)
2326 }
2327
2328 fn insert_debug_marker(&self, label: &str) {
2329 self.wgpu_command_encoder.insert_debug_marker(label)
2330 }
2331
2332 fn push_debug_group(&self, label: &str) {
2333 self.wgpu_command_encoder.push_debug_group(label)
2334 }
2335
2336 fn pop_debug_group(&self) {
2337 self.wgpu_command_encoder.pop_debug_group()
2338 }
2339
2340 fn write_timestamp(&self, query_set: &dispatch::DispatchQuerySet, query_index: u32) {
2341 let query_set = query_set.as_core();
2342
2343 self.wgpu_command_encoder
2344 .write_timestamp(query_set.wgpu_query_set.clone(), query_index)
2345 }
2346
2347 fn resolve_query_set(
2348 &self,
2349 query_set: &dispatch::DispatchQuerySet,
2350 first_query: u32,
2351 query_count: u32,
2352 destination: &dispatch::DispatchBuffer,
2353 destination_offset: crate::BufferAddress,
2354 ) {
2355 let query_set = query_set.as_core();
2356 let destination = destination.as_core();
2357
2358 self.wgpu_command_encoder.resolve_query_set(
2359 query_set.wgpu_query_set.clone(),
2360 first_query,
2361 query_count,
2362 destination.wgpu_buffer.clone(),
2363 destination_offset,
2364 );
2365 }
2366
2367 fn mark_acceleration_structures_built<'a>(
2368 &self,
2369 blas: &mut dyn Iterator<Item = &'a Blas>,
2370 tlas: &mut dyn Iterator<Item = &'a Tlas>,
2371 ) {
2372 let blas = blas
2373 .map(|b| b.inner.as_core().wgpu_blas.clone())
2374 .collect::<SmallVec<[_; 4]>>();
2375 let tlas = tlas
2376 .map(|t| t.inner.as_core().wgpu_tlas.clone())
2377 .collect::<SmallVec<[_; 4]>>();
2378 self.wgpu_command_encoder
2379 .mark_acceleration_structures_built(&blas, &tlas)
2380 }
2381
2382 fn build_acceleration_structures<'a>(
2383 &self,
2384 blas: &mut dyn Iterator<Item = &'a crate::BlasBuildEntry<'a>>,
2385 tlas: &mut dyn Iterator<Item = &'a crate::Tlas>,
2386 ) {
2387 let blas = blas.map(|e: &crate::BlasBuildEntry<'_>| {
2388 let geometries = match e.geometry {
2389 crate::BlasGeometries::TriangleGeometries(ref triangle_geometries) => {
2390 let iter = triangle_geometries.iter().map(|tg| {
2391 wgc::ray_tracing::BlasTriangleGeometry {
2392 vertex_buffer: tg.vertex_buffer.inner.as_core().wgpu_buffer.clone(),
2393 index_buffer: tg
2394 .index_buffer
2395 .map(|buf| buf.inner.as_core().wgpu_buffer.clone()),
2396 transform_buffer: tg
2397 .transform_buffer
2398 .map(|buf| buf.inner.as_core().wgpu_buffer.clone()),
2399 size: tg.size,
2400 transform_buffer_offset: tg.transform_buffer_offset,
2401 first_vertex: tg.first_vertex,
2402 vertex_stride: tg.vertex_stride,
2403 first_index: tg.first_index,
2404 }
2405 });
2406 wgc::ray_tracing::BlasGeometries::TriangleGeometries(Box::new(iter))
2407 }
2408 crate::BlasGeometries::AabbGeometries(ref aabb_geometries) => {
2409 let iter =
2410 aabb_geometries
2411 .iter()
2412 .map(|ag| wgc::ray_tracing::BlasAabbGeometry {
2413 aabb_buffer: ag.aabb_buffer.inner.as_core().wgpu_buffer.clone(),
2414 stride: ag.stride,
2415 size: ag.size,
2416 primitive_offset: ag.primitive_offset,
2417 });
2418 wgc::ray_tracing::BlasGeometries::AabbGeometries(Box::new(iter))
2419 }
2420 };
2421 wgc::ray_tracing::BlasBuildEntry {
2422 blas: e.blas.inner.as_core().wgpu_blas.clone(),
2423 geometries,
2424 }
2425 });
2426
2427 let tlas = tlas.into_iter().map(|e| {
2428 let instances = e
2429 .instances
2430 .iter()
2431 .map(|instance: &Option<crate::TlasInstance>| {
2432 instance
2433 .as_ref()
2434 .map(|instance| wgc::ray_tracing::ArcTlasInstance {
2435 blas: instance.blas.as_core().wgpu_blas.clone(),
2436 transform: instance.transform,
2437 custom_data: instance.custom_data,
2438 mask: instance.mask,
2439 intersection_index: instance.intersection_index,
2440 })
2441 })
2442 .collect();
2443 wgc::ray_tracing::ArcTlasPackage {
2444 tlas: e.inner.as_core().wgpu_tlas.clone(),
2445 instances,
2446 lowest_unmodified: e.lowest_unmodified,
2447 }
2448 });
2449
2450 self.wgpu_command_encoder
2451 .build_acceleration_structures(blas, tlas.collect())
2452 }
2453
2454 fn transition_resources<'a>(
2455 &mut self,
2456 buffer_transitions: &mut dyn Iterator<
2457 Item = wgt::BufferTransition<&'a dispatch::DispatchBuffer>,
2458 >,
2459 texture_transitions: &mut dyn Iterator<
2460 Item = wgt::TextureTransition<&'a dispatch::DispatchTexture>,
2461 >,
2462 ) {
2463 self.wgpu_command_encoder.transition_resources(
2464 buffer_transitions.map(|t| wgt::BufferTransition {
2465 buffer: t.buffer.as_core().wgpu_buffer.clone(),
2466 state: t.state,
2467 }),
2468 texture_transitions.map(|t| wgt::TextureTransition {
2469 texture: t.texture.as_core().wgpu_texture.clone(),
2470 selector: t.selector.clone(),
2471 state: t.state,
2472 }),
2473 );
2474 }
2475}
2476
2477impl dispatch::CommandBufferInterface for CoreCommandBuffer {}
2478
2479impl dispatch::ComputePassInterface for CoreComputePass {
2480 fn set_pipeline(&mut self, pipeline: &dispatch::DispatchComputePipeline) {
2481 let pipeline = pipeline.as_core();
2482
2483 self.pass
2484 .set_pipeline(pipeline.wgpu_compute_pipeline.clone());
2485 }
2486
2487 fn set_bind_group(
2488 &mut self,
2489 index: u32,
2490 bind_group: Option<&dispatch::DispatchBindGroup>,
2491 offsets: &[crate::DynamicOffset],
2492 ) {
2493 let bg = bind_group.map(|bg| bg.as_core().wgpu_bind_group.clone());
2494
2495 self.pass.set_bind_group(index, bg, offsets);
2496 }
2497
2498 fn set_immediates(&mut self, offset: u32, data: &[u8]) {
2499 self.pass.set_immediates(offset, data);
2500 }
2501
2502 fn insert_debug_marker(&mut self, label: &str) {
2503 self.pass.insert_debug_marker(label, 0);
2504 }
2505
2506 fn push_debug_group(&mut self, group_label: &str) {
2507 self.pass.push_debug_group(group_label, 0);
2508 }
2509
2510 fn pop_debug_group(&mut self) {
2511 self.pass.pop_debug_group();
2512 }
2513
2514 fn write_timestamp(&mut self, query_set: &dispatch::DispatchQuerySet, query_index: u32) {
2515 let query_set = query_set.as_core();
2516
2517 self.pass
2518 .write_timestamp(query_set.wgpu_query_set.clone(), query_index);
2519 }
2520
2521 fn begin_pipeline_statistics_query(
2522 &mut self,
2523 query_set: &dispatch::DispatchQuerySet,
2524 query_index: u32,
2525 ) {
2526 let query_set = query_set.as_core();
2527
2528 self.pass
2529 .begin_pipeline_statistics_query(query_set.wgpu_query_set.clone(), query_index);
2530 }
2531
2532 fn end_pipeline_statistics_query(&mut self) {
2533 self.pass.end_pipeline_statistics_query();
2534 }
2535
2536 fn dispatch_workgroups(&mut self, x: u32, y: u32, z: u32) {
2537 self.pass.dispatch_workgroups(x, y, z);
2538 }
2539
2540 fn dispatch_workgroups_indirect(
2541 &mut self,
2542 indirect_buffer: &dispatch::DispatchBuffer,
2543 indirect_offset: crate::BufferAddress,
2544 ) {
2545 let indirect_buffer = indirect_buffer.as_core();
2546
2547 self.pass
2548 .dispatch_workgroups_indirect(indirect_buffer.wgpu_buffer.clone(), indirect_offset);
2549 }
2550
2551 fn transition_resources<'a>(
2552 &mut self,
2553 buffer_transitions: &mut dyn Iterator<
2554 Item = wgt::BufferTransition<&'a dispatch::DispatchBuffer>,
2555 >,
2556 texture_transitions: &mut dyn Iterator<
2557 Item = wgt::TextureTransition<&'a dispatch::DispatchTextureView>,
2558 >,
2559 ) {
2560 self.pass.transition_resources(
2561 buffer_transitions.map(|t| wgt::BufferTransition {
2562 buffer: t.buffer.as_core().wgpu_buffer.clone(),
2563 state: t.state,
2564 }),
2565 texture_transitions.map(|t| wgt::TextureTransition {
2566 texture: t.texture.as_core().wgpu_texture_view.clone(),
2567 selector: t.selector.clone(),
2568 state: t.state,
2569 }),
2570 );
2571 }
2572}
2573
2574impl Drop for CoreComputePass {
2575 fn drop(&mut self) {
2576 self.pass.end();
2577 }
2578}
2579
2580impl dispatch::RenderPassInterface for CoreRenderPass {
2581 fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRenderPipeline) {
2582 let pipeline = pipeline.as_core();
2583
2584 self.pass
2585 .set_pipeline(pipeline.wgpu_render_pipeline.clone());
2586 }
2587
2588 fn set_bind_group(
2589 &mut self,
2590 index: u32,
2591 bind_group: Option<&dispatch::DispatchBindGroup>,
2592 offsets: &[crate::DynamicOffset],
2593 ) {
2594 let bg = bind_group.map(|bg| bg.as_core().wgpu_bind_group.clone());
2595
2596 self.pass.set_bind_group(index, bg, offsets);
2597 }
2598
2599 fn set_index_buffer(
2600 &mut self,
2601 buffer: &dispatch::DispatchBuffer,
2602 index_format: crate::IndexFormat,
2603 offset: crate::BufferAddress,
2604 size: Option<crate::BufferAddress>,
2605 ) {
2606 let buffer = buffer.as_core();
2607
2608 self.pass
2609 .set_index_buffer(buffer.wgpu_buffer.clone(), index_format, offset, size)
2610 }
2611
2612 fn set_vertex_buffer(
2613 &mut self,
2614 slot: u32,
2615 buffer: Option<&dispatch::DispatchBuffer>,
2616 offset: crate::BufferAddress,
2617 size: Option<crate::BufferAddress>,
2618 ) {
2619 let buffer = buffer.map(|buffer| buffer.as_core().wgpu_buffer.clone());
2620
2621 self.pass.set_vertex_buffer(slot, buffer, offset, size);
2622 }
2623
2624 fn set_immediates(&mut self, offset: u32, data: &[u8]) {
2625 self.pass.set_immediates(offset, data);
2626 }
2627
2628 fn set_blend_constant(&mut self, color: crate::Color) {
2629 self.pass.set_blend_constant(color);
2630 }
2631
2632 fn set_scissor_rect(&mut self, x: u32, y: u32, width: u32, height: u32) {
2633 self.pass.set_scissor_rect(x, y, width, height);
2634 }
2635
2636 fn set_viewport(
2637 &mut self,
2638 x: f32,
2639 y: f32,
2640 width: f32,
2641 height: f32,
2642 min_depth: f32,
2643 max_depth: f32,
2644 ) {
2645 self.pass
2646 .set_viewport(x, y, width, height, min_depth, max_depth);
2647 }
2648
2649 fn set_stencil_reference(&mut self, reference: u32) {
2650 self.pass.set_stencil_reference(reference);
2651 }
2652
2653 fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
2654 self.pass.draw(
2655 vertices.end - vertices.start,
2656 instances.end - instances.start,
2657 vertices.start,
2658 instances.start,
2659 );
2660 }
2661
2662 fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
2663 self.pass.draw_indexed(
2664 indices.end - indices.start,
2665 instances.end - instances.start,
2666 indices.start,
2667 base_vertex,
2668 instances.start,
2669 );
2670 }
2671
2672 fn draw_mesh_tasks(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32) {
2673 self.pass
2674 .draw_mesh_tasks(group_count_x, group_count_y, group_count_z);
2675 }
2676
2677 fn draw_indirect(
2678 &mut self,
2679 indirect_buffer: &dispatch::DispatchBuffer,
2680 indirect_offset: crate::BufferAddress,
2681 ) {
2682 let indirect_buffer = indirect_buffer.as_core();
2683
2684 self.pass
2685 .draw_indirect(indirect_buffer.wgpu_buffer.clone(), indirect_offset);
2686 }
2687
2688 fn draw_indexed_indirect(
2689 &mut self,
2690 indirect_buffer: &dispatch::DispatchBuffer,
2691 indirect_offset: crate::BufferAddress,
2692 ) {
2693 let indirect_buffer = indirect_buffer.as_core();
2694
2695 self.pass
2696 .draw_indexed_indirect(indirect_buffer.wgpu_buffer.clone(), indirect_offset);
2697 }
2698
2699 fn draw_mesh_tasks_indirect(
2700 &mut self,
2701 indirect_buffer: &dispatch::DispatchBuffer,
2702 indirect_offset: crate::BufferAddress,
2703 ) {
2704 let indirect_buffer = indirect_buffer.as_core();
2705
2706 self.pass
2707 .draw_mesh_tasks_indirect(indirect_buffer.wgpu_buffer.clone(), indirect_offset);
2708 }
2709
2710 fn multi_draw_indirect(
2711 &mut self,
2712 indirect_buffer: &dispatch::DispatchBuffer,
2713 indirect_offset: crate::BufferAddress,
2714 count: u32,
2715 ) {
2716 let indirect_buffer = indirect_buffer.as_core();
2717
2718 self.pass
2719 .multi_draw_indirect(indirect_buffer.wgpu_buffer.clone(), indirect_offset, count);
2720 }
2721
2722 fn multi_draw_indexed_indirect(
2723 &mut self,
2724 indirect_buffer: &dispatch::DispatchBuffer,
2725 indirect_offset: crate::BufferAddress,
2726 count: u32,
2727 ) {
2728 let indirect_buffer = indirect_buffer.as_core();
2729
2730 self.pass.multi_draw_indexed_indirect(
2731 indirect_buffer.wgpu_buffer.clone(),
2732 indirect_offset,
2733 count,
2734 );
2735 }
2736
2737 fn multi_draw_mesh_tasks_indirect(
2738 &mut self,
2739 indirect_buffer: &dispatch::DispatchBuffer,
2740 indirect_offset: crate::BufferAddress,
2741 count: u32,
2742 ) {
2743 let indirect_buffer = indirect_buffer.as_core();
2744
2745 self.pass.multi_draw_mesh_tasks_indirect(
2746 indirect_buffer.wgpu_buffer.clone(),
2747 indirect_offset,
2748 count,
2749 );
2750 }
2751
2752 fn multi_draw_indirect_count(
2753 &mut self,
2754 indirect_buffer: &dispatch::DispatchBuffer,
2755 indirect_offset: crate::BufferAddress,
2756 count_buffer: &dispatch::DispatchBuffer,
2757 count_buffer_offset: crate::BufferAddress,
2758 max_count: u32,
2759 ) {
2760 let indirect_buffer = indirect_buffer.as_core();
2761 let count_buffer = count_buffer.as_core();
2762
2763 self.pass.multi_draw_indirect_count(
2764 indirect_buffer.wgpu_buffer.clone(),
2765 indirect_offset,
2766 count_buffer.wgpu_buffer.clone(),
2767 count_buffer_offset,
2768 max_count,
2769 );
2770 }
2771
2772 fn multi_draw_indexed_indirect_count(
2773 &mut self,
2774 indirect_buffer: &dispatch::DispatchBuffer,
2775 indirect_offset: crate::BufferAddress,
2776 count_buffer: &dispatch::DispatchBuffer,
2777 count_buffer_offset: crate::BufferAddress,
2778 max_count: u32,
2779 ) {
2780 let indirect_buffer = indirect_buffer.as_core();
2781 let count_buffer = count_buffer.as_core();
2782
2783 self.pass.multi_draw_indexed_indirect_count(
2784 indirect_buffer.wgpu_buffer.clone(),
2785 indirect_offset,
2786 count_buffer.wgpu_buffer.clone(),
2787 count_buffer_offset,
2788 max_count,
2789 );
2790 }
2791
2792 fn multi_draw_mesh_tasks_indirect_count(
2793 &mut self,
2794 indirect_buffer: &dispatch::DispatchBuffer,
2795 indirect_offset: crate::BufferAddress,
2796 count_buffer: &dispatch::DispatchBuffer,
2797 count_buffer_offset: crate::BufferAddress,
2798 max_count: u32,
2799 ) {
2800 let indirect_buffer = indirect_buffer.as_core();
2801 let count_buffer = count_buffer.as_core();
2802
2803 self.pass.multi_draw_mesh_tasks_indirect_count(
2804 indirect_buffer.wgpu_buffer.clone(),
2805 indirect_offset,
2806 count_buffer.wgpu_buffer.clone(),
2807 count_buffer_offset,
2808 max_count,
2809 );
2810 }
2811
2812 fn insert_debug_marker(&mut self, label: &str) {
2813 self.pass.insert_debug_marker(label, 0);
2814 }
2815
2816 fn push_debug_group(&mut self, group_label: &str) {
2817 self.pass.push_debug_group(group_label, 0);
2818 }
2819
2820 fn pop_debug_group(&mut self) {
2821 self.pass.pop_debug_group();
2822 }
2823
2824 fn write_timestamp(&mut self, query_set: &dispatch::DispatchQuerySet, query_index: u32) {
2825 let query_set = query_set.as_core();
2826
2827 self.pass
2828 .write_timestamp(query_set.wgpu_query_set.clone(), query_index);
2829 }
2830
2831 fn begin_occlusion_query(&mut self, query_index: u32) {
2832 self.pass.begin_occlusion_query(query_index);
2833 }
2834
2835 fn end_occlusion_query(&mut self) {
2836 self.pass.end_occlusion_query();
2837 }
2838
2839 fn begin_pipeline_statistics_query(
2840 &mut self,
2841 query_set: &dispatch::DispatchQuerySet,
2842 query_index: u32,
2843 ) {
2844 let query_set = query_set.as_core();
2845
2846 self.pass
2847 .begin_pipeline_statistics_query(query_set.wgpu_query_set.clone(), query_index);
2848 }
2849
2850 fn end_pipeline_statistics_query(&mut self) {
2851 self.pass.end_pipeline_statistics_query();
2852 }
2853
2854 fn execute_bundles(
2855 &mut self,
2856 render_bundles: &mut dyn Iterator<Item = &dispatch::DispatchRenderBundle>,
2857 ) {
2858 let temp_render_bundles = render_bundles
2859 .map(|rb| rb.as_core().wgpu_render_bundle.clone())
2860 .collect::<SmallVec<[_; 4]>>();
2861 self.pass.execute_bundles(&temp_render_bundles);
2862 }
2863}
2864
2865impl Drop for CoreRenderPass {
2866 fn drop(&mut self) {
2867 self.pass.end()
2868 }
2869}
2870
2871impl dispatch::RayTracingPassInterface for CoreRayTracingPass {
2872 fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRayTracingPipeline) {
2873 let pipeline = pipeline.as_core();
2874
2875 self.pass
2876 .set_pipeline(pipeline.wgpu_ray_tracing_pipeline.clone())
2877 }
2878
2879 fn set_bind_group(
2880 &mut self,
2881 index: u32,
2882 bind_group: Option<&dispatch::DispatchBindGroup>,
2883 offsets: &[crate::DynamicOffset],
2884 ) {
2885 let bg = bind_group.map(|bg| bg.as_core().wgpu_bind_group.clone());
2886
2887 self.pass.set_bind_group(index, bg, offsets)
2888 }
2889
2890 fn set_immediates(&mut self, offset: u32, data: &[u8]) {
2891 self.pass.set_immediates(offset, data)
2892 }
2893
2894 fn insert_debug_marker(&mut self, label: &str) {
2895 self.pass.insert_debug_marker(label, 0)
2896 }
2897
2898 fn push_debug_group(&mut self, group_label: &str) {
2899 self.pass.push_debug_group(group_label, 0)
2900 }
2901
2902 fn pop_debug_group(&mut self) {
2903 self.pass.pop_debug_group()
2904 }
2905
2906 fn trace_rays(&mut self, x: u32, y: u32, z: u32) {
2907 self.pass.trace_rays(x, y, z)
2908 }
2909}
2910
2911impl Drop for CoreRayTracingPass {
2912 fn drop(&mut self) {
2913 self.pass.end()
2914 }
2915}
2916
2917impl dispatch::RenderBundleEncoderInterface for CoreRenderBundleEncoder {
2918 fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRenderPipeline) {
2919 let pipeline = pipeline.as_core();
2920
2921 self.encoder
2922 .set_pipeline(pipeline.wgpu_render_pipeline.clone())
2923 }
2924
2925 fn set_bind_group(
2926 &mut self,
2927 index: u32,
2928 bind_group: Option<&dispatch::DispatchBindGroup>,
2929 offsets: &[crate::DynamicOffset],
2930 ) {
2931 let bg = bind_group.map(|bg| bg.as_core().wgpu_bind_group.clone());
2932
2933 self.encoder.set_bind_group(index, bg, offsets);
2934 }
2935
2936 fn set_index_buffer(
2937 &mut self,
2938 buffer: &dispatch::DispatchBuffer,
2939 index_format: crate::IndexFormat,
2940 offset: crate::BufferAddress,
2941 size: Option<crate::BufferAddress>,
2942 ) {
2943 let buffer = buffer.as_core();
2944
2945 self.encoder
2946 .set_index_buffer(buffer.wgpu_buffer.clone(), index_format, offset, size);
2947 }
2948
2949 fn set_vertex_buffer(
2950 &mut self,
2951 slot: u32,
2952 buffer: Option<&dispatch::DispatchBuffer>,
2953 offset: crate::BufferAddress,
2954 size: Option<crate::BufferAddress>,
2955 ) {
2956 let buffer = buffer.map(|buffer| buffer.as_core().wgpu_buffer.clone());
2957
2958 self.encoder.set_vertex_buffer(slot, buffer, offset, size);
2959 }
2960
2961 fn set_immediates(&mut self, offset: u32, data: &[u8]) {
2962 if !data
2963 .len()
2964 .is_multiple_of(wgt::IMMEDIATE_DATA_ALIGNMENT as usize)
2965 {
2966 self.encoder.device().handle_error(
2967 wgc::binding_model::ImmediateUploadError::SizeUnaligned(data.len()),
2968 self.encoder.label(),
2969 "RenderBundleEncoder::set_immediates",
2970 );
2971 return;
2972 }
2973
2974 self.encoder.set_immediates(offset, data);
2975 }
2976
2977 fn insert_debug_marker(&mut self, label: &str) {
2978 self.encoder.insert_debug_marker(label);
2979 }
2980
2981 fn push_debug_group(&mut self, group_label: &str) {
2982 self.encoder.push_debug_group(group_label);
2983 }
2984
2985 fn pop_debug_group(&mut self) {
2986 self.encoder.pop_debug_group();
2987 }
2988
2989 fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
2990 self.encoder.draw(
2991 vertices.end - vertices.start,
2992 instances.end - instances.start,
2993 vertices.start,
2994 instances.start,
2995 );
2996 }
2997
2998 fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
2999 self.encoder.draw_indexed(
3000 indices.end - indices.start,
3001 instances.end - instances.start,
3002 indices.start,
3003 base_vertex,
3004 instances.start,
3005 );
3006 }
3007
3008 fn draw_indirect(
3009 &mut self,
3010 indirect_buffer: &dispatch::DispatchBuffer,
3011 indirect_offset: crate::BufferAddress,
3012 ) {
3013 let indirect_buffer = indirect_buffer.as_core();
3014
3015 self.encoder
3016 .draw_indirect(indirect_buffer.wgpu_buffer.clone(), indirect_offset);
3017 }
3018
3019 fn draw_indexed_indirect(
3020 &mut self,
3021 indirect_buffer: &dispatch::DispatchBuffer,
3022 indirect_offset: crate::BufferAddress,
3023 ) {
3024 let indirect_buffer = indirect_buffer.as_core();
3025
3026 self.encoder
3027 .draw_indexed_indirect(indirect_buffer.wgpu_buffer.clone(), indirect_offset);
3028 }
3029
3030 fn finish(mut self, desc: &crate::RenderBundleDescriptor<'_>) -> dispatch::DispatchRenderBundle
3031 where
3032 Self: Sized,
3033 {
3034 let wgpu_render_bundle = self.encoder.finish(&desc.map_label(|l| l.map(Borrowed)));
3035 CoreRenderBundle { wgpu_render_bundle }.into()
3036 }
3037
3038 #[cfg(custom)]
3039 fn finish_boxed(
3040 self: Box<Self>,
3041 desc: &crate::RenderBundleDescriptor<'_>,
3042 ) -> dispatch::DispatchRenderBundle {
3043 (*self).finish(desc)
3044 }
3045}
3046
3047impl dispatch::RenderBundleInterface for CoreRenderBundle {}
3048
3049#[derive(Clone)]
3050enum ErrorSink {
3051 Actual(Arc<wgc::device::Device>),
3052 Dummy(Arc<Mutex<wgc::error::ErrorSink>>),
3053}
3054
3055impl ErrorSink {
3056 fn new() -> Self {
3057 Self::Dummy(Arc::new(Mutex::new(wgc::error::ErrorSink::new())))
3058 }
3059
3060 fn handle_error_nolabel(
3061 &self,
3062 source: impl WebGpuError + WasmNotSendSync + 'static,
3063 fn_ident: &'static str,
3064 ) {
3065 match self {
3066 ErrorSink::Actual(device) => device.handle_error_nolabel(source, fn_ident),
3067 ErrorSink::Dummy(sink) => sink.lock().handle_error_nolabel(source, fn_ident),
3068 }
3069 }
3070}
3071
3072impl dispatch::SurfaceInterface for CoreSurface {
3073 fn get_capabilities(&self, adapter: &dispatch::DispatchAdapter) -> wgt::SurfaceCapabilities {
3074 let adapter = adapter.as_core();
3075
3076 self.wgpu_surface
3077 .get_capabilities(&adapter.wgpu_adapter)
3078 .unwrap_or_default()
3079 }
3080
3081 fn display_hdr_info(&self, adapter: &dispatch::DispatchAdapter) -> wgt::DisplayHdrInfo {
3082 let adapter = adapter.as_core();
3083
3084 self.wgpu_surface.display_hdr_info(&adapter.wgpu_adapter)
3085 }
3086
3087 fn configure(&self, device: &dispatch::DispatchDevice, config: &crate::SurfaceConfiguration) {
3088 let device = device.as_core();
3089
3090 let result = self.wgpu_surface.configure(&device.wgpu_device, config);
3091 if let Some(e) = result.err() {
3092 device
3093 .wgpu_device
3094 .handle_error_nolabel(e, "Surface::configure");
3095 } else {
3096 *self.configured_device.lock() = Some(device.wgpu_device.clone());
3097 }
3098 }
3099
3100 fn get_current_texture(
3101 &self,
3102 _desc: Option<crate::TextureDescriptor<'static>>,
3103 ) -> (
3104 Option<dispatch::DispatchTexture>,
3105 crate::SurfaceStatus,
3106 dispatch::DispatchSurfaceOutputDetail,
3107 ) {
3108 let error_sink = if let Some(error_sink) = self.configured_device.lock().as_ref() {
3109 ErrorSink::Actual(error_sink.clone())
3110 } else {
3111 ErrorSink::new()
3112 };
3113
3114 let output_detail = CoreSurfaceOutputDetail {
3115 wgpu_surface: self.wgpu_surface.clone(),
3116 error_sink,
3117 }
3118 .into();
3119
3120 match self.wgpu_surface.get_current_texture() {
3121 Ok(wgc::present::SurfaceOutput {
3122 status,
3123 texture: texture_id,
3124 }) => {
3125 let data = texture_id
3126 .map(|wgpu_texture| CoreTexture { wgpu_texture })
3127 .map(Into::into);
3128
3129 (data, status, output_detail)
3130 }
3131 Err(err) => {
3132 let error_sink = self.configured_device.lock();
3133 match error_sink.as_ref() {
3134 Some(error_sink) => {
3135 error_sink.handle_error_nolabel(err, "Surface::get_current_texture_view");
3136 (None, crate::SurfaceStatus::Validation, output_detail)
3137 }
3138 None => handle_error_fatal(err, "Surface::get_current_texture_view"),
3139 }
3140 }
3141 }
3142 }
3143}
3144
3145impl dispatch::SurfaceOutputDetailInterface for CoreSurfaceOutputDetail {
3146 fn texture_discard(&self) {
3147 match self.wgpu_surface.discard() {
3148 Ok(_status) => (),
3149 Err(err) => self
3150 .error_sink
3151 .handle_error_nolabel(err, "Surface::discard_texture"),
3152 }
3153 }
3154
3155 fn texture_release(&self) {
3156 match self.wgpu_surface.release() {
3157 Ok(_status) => (),
3158 Err(err) => self
3159 .error_sink
3160 .handle_error_nolabel(err, "Surface::release_texture"),
3161 }
3162 }
3163}
3164
3165impl dispatch::QueueWriteBufferInterface for CoreQueueWriteBuffer {
3166 #[inline]
3167 fn len(&self) -> usize {
3168 self.wgpu_staging_buffer.size().get() as usize
3169 }
3170
3171 #[inline]
3172 unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]> {
3173 unsafe {
3174 WriteOnly::new(NonNull::slice_from_raw_parts(
3175 self.wgpu_staging_buffer.ptr(),
3176 self.len(),
3177 ))
3178 }
3179 }
3180}
3181
3182impl dispatch::BufferMappedRangeInterface for CoreBufferMappedRange {
3183 #[inline]
3184 unsafe fn read_slice(&self) -> &[u8] {
3185 self.0.read_slice()
3186 }
3187
3188 #[inline]
3189 unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]> {
3190 self.0.write_slice()
3191 }
3192
3193 #[cfg(webgpu)]
3194 fn as_uint8array(&self) -> &js_sys::Uint8Array {
3195 panic!("Only available on WebGPU")
3196 }
3197}