wgpu/
dispatch.rs

1//! Infrastructure for dispatching calls to the appropriate "backend". The "backends" are:
2//!
3//! - `wgpu_core`: An implementation of the the wgpu api on top of various native graphics APIs.
4//! - `webgpu`: An implementation of the wgpu api which calls WebGPU directly.
5//!
6//! The interface traits are all object safe and listed in the `InterfaceTypes` trait.
7//!
8//! The method for dispatching should optimize well if only one backend is
9//! compiled in, as-if there was no dispatching at all. See the comments on
10//! [`dispatch_types`] for details.
11//!
12//! [`dispatch_types`]: macro.dispatch_types.html
13
14#![allow(
15    drop_bounds,
16    reason = "This exists to remind implementors to impl drop."
17)]
18#![allow(clippy::too_many_arguments, reason = "It's fine.")]
19#![allow(
20    missing_docs,
21    clippy::missing_safety_doc,
22    reason = "Interfaces are not documented"
23)]
24#![allow(
25    clippy::len_without_is_empty,
26    reason = "trait is minimal, not ergonomic"
27)]
28
29use crate::{Blas, Tlas, WasmNotSend, WasmNotSendSync, WriteOnly};
30
31use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec};
32use core::{any::Any, fmt::Debug, future::Future, hash::Hash, ops::Range, pin::Pin};
33
34#[cfg(custom)]
35use crate::backend::custom::*;
36#[cfg(webgpu)]
37use crate::backend::webgpu::*;
38#[cfg(wgpu_core)]
39use crate::backend::wgpu_core::*;
40
41/// Create a single trait with the given supertraits and a blanket impl for all types that implement them.
42///
43/// This is useful for creating a trait alias as a shorthand.
44macro_rules! trait_alias {
45    ($name:ident: $($bound:tt)+) => {
46        pub trait $name: $($bound)+ {}
47        impl<T: $($bound)+> $name for T {}
48    };
49}
50
51// Various return futures in the API.
52trait_alias!(RequestAdapterFuture: Future<Output = Result<DispatchAdapter, wgt::RequestAdapterError>> + WasmNotSend + 'static);
53trait_alias!(RequestDeviceFuture: Future<Output = Result<(DispatchDevice, DispatchQueue), crate::RequestDeviceError>> + WasmNotSend + 'static);
54trait_alias!(PopErrorScopeFuture: Future<Output = Option<crate::Error>> + WasmNotSend + 'static);
55trait_alias!(ShaderCompilationInfoFuture: Future<Output = crate::CompilationInfo> + WasmNotSend + 'static);
56trait_alias!(EnumerateAdapterFuture: Future<Output = Vec<DispatchAdapter>> + WasmNotSend + 'static);
57
58// We can't use trait aliases here, as you can't convert from a dyn Trait to dyn Supertrait _yet_.
59#[cfg(send_sync)]
60pub type BoxDeviceLostCallback = Box<dyn FnOnce(crate::DeviceLostReason, String) + Send + 'static>;
61#[cfg(not(send_sync))]
62pub type BoxDeviceLostCallback = Box<dyn FnOnce(crate::DeviceLostReason, String) + 'static>;
63#[cfg(send_sync)]
64pub type BoxSubmittedWorkDoneCallback = Box<dyn FnOnce() + Send + 'static>;
65#[cfg(not(send_sync))]
66pub type BoxSubmittedWorkDoneCallback = Box<dyn FnOnce() + 'static>;
67#[cfg(send_sync)]
68pub type BufferMapCallback = Box<dyn FnOnce(Result<(), crate::BufferAsyncError>) + Send + 'static>;
69#[cfg(not(send_sync))]
70pub type BufferMapCallback = Box<dyn FnOnce(Result<(), crate::BufferAsyncError>) + 'static>;
71
72#[cfg(send_sync)]
73pub type BlasCompactCallback = Box<dyn FnOnce(Result<(), crate::BlasAsyncError>) + Send + 'static>;
74#[cfg(not(send_sync))]
75pub type BlasCompactCallback = Box<dyn FnOnce(Result<(), crate::BlasAsyncError>) + 'static>;
76
77// remove when rust 1.86
78#[cfg_attr(not(custom), expect(dead_code))]
79pub trait AsAny {
80    fn as_any(&self) -> &dyn Any;
81}
82
83impl<T: 'static> AsAny for T {
84    fn as_any(&self) -> &dyn Any {
85        self
86    }
87}
88
89// Common traits on all the interface traits
90trait_alias!(CommonTraits: AsAny + Any + Debug + WasmNotSendSync);
91
92pub trait InstanceInterface: CommonTraits {
93    fn new(desc: crate::InstanceDescriptor) -> Self
94    where
95        Self: Sized;
96
97    unsafe fn create_surface(
98        &self,
99        target: crate::SurfaceTargetUnsafe,
100    ) -> Result<DispatchSurface, crate::CreateSurfaceError>;
101
102    fn request_adapter(
103        &self,
104        options: &crate::RequestAdapterOptions<'_, '_>,
105    ) -> Pin<Box<dyn RequestAdapterFuture>>;
106
107    fn poll_all_devices(&self, force_wait: bool) -> bool;
108
109    #[cfg(feature = "wgsl")]
110    fn wgsl_language_features(&self) -> crate::WgslLanguageFeatures;
111
112    fn enumerate_adapters(&self, backends: crate::Backends)
113        -> Pin<Box<dyn EnumerateAdapterFuture>>;
114}
115
116pub trait AdapterInterface: CommonTraits {
117    fn request_device(
118        &self,
119        desc: &crate::DeviceDescriptor<'_>,
120    ) -> Pin<Box<dyn RequestDeviceFuture>>;
121
122    fn is_surface_supported(&self, surface: &DispatchSurface) -> bool;
123
124    fn features(&self) -> crate::Features;
125
126    fn limits(&self) -> crate::Limits;
127
128    fn downlevel_capabilities(&self) -> crate::DownlevelCapabilities;
129
130    fn get_info(&self) -> crate::AdapterInfo;
131
132    fn get_texture_format_features(
133        &self,
134        format: crate::TextureFormat,
135    ) -> crate::TextureFormatFeatures;
136
137    fn get_presentation_timestamp(&self) -> crate::PresentationTimestamp;
138
139    fn cooperative_matrix_properties(&self) -> Vec<crate::wgt::CooperativeMatrixProperties>;
140}
141
142pub trait DeviceInterface: CommonTraits {
143    fn features(&self) -> crate::Features;
144    fn limits(&self) -> crate::Limits;
145    fn adapter_info(&self) -> crate::AdapterInfo;
146
147    fn create_shader_module(
148        &self,
149        desc: crate::ShaderModuleDescriptor<'_>,
150        shader_bound_checks: crate::ShaderRuntimeChecks,
151    ) -> DispatchShaderModule;
152
153    unsafe fn create_shader_module_passthrough(
154        &self,
155        desc: &crate::ShaderModuleDescriptorPassthrough<'_>,
156    ) -> DispatchShaderModule;
157
158    fn create_bind_group_layout(
159        &self,
160        desc: &crate::BindGroupLayoutDescriptor<'_>,
161    ) -> DispatchBindGroupLayout;
162    fn create_bind_group(&self, desc: &crate::BindGroupDescriptor<'_>) -> DispatchBindGroup;
163    fn create_pipeline_layout(
164        &self,
165        desc: &crate::PipelineLayoutDescriptor<'_>,
166    ) -> DispatchPipelineLayout;
167    fn create_render_pipeline(
168        &self,
169        desc: &crate::RenderPipelineDescriptor<'_>,
170    ) -> DispatchRenderPipeline;
171    fn create_mesh_pipeline(
172        &self,
173        desc: &crate::MeshPipelineDescriptor<'_>,
174    ) -> DispatchRenderPipeline;
175    fn create_compute_pipeline(
176        &self,
177        desc: &crate::ComputePipelineDescriptor<'_>,
178    ) -> DispatchComputePipeline;
179    unsafe fn create_pipeline_cache(
180        &self,
181        desc: &crate::PipelineCacheDescriptor<'_>,
182    ) -> DispatchPipelineCache;
183    fn create_buffer(&self, desc: &crate::BufferDescriptor<'_>) -> DispatchBuffer;
184    fn create_texture(&self, desc: &crate::TextureDescriptor<'_>) -> DispatchTexture;
185    fn create_external_texture(
186        &self,
187        desc: &crate::ExternalTextureDescriptor<'_>,
188        planes: &[&crate::TextureView],
189    ) -> DispatchExternalTexture;
190    fn create_blas(
191        &self,
192        desc: &crate::CreateBlasDescriptor<'_>,
193        sizes: crate::BlasGeometrySizeDescriptors,
194    ) -> (Option<u64>, DispatchBlas);
195    fn create_tlas(&self, desc: &crate::CreateTlasDescriptor<'_>) -> DispatchTlas;
196    fn create_sampler(&self, desc: &crate::SamplerDescriptor<'_>) -> DispatchSampler;
197    fn create_query_set(&self, desc: &crate::QuerySetDescriptor<'_>) -> DispatchQuerySet;
198    fn create_command_encoder(
199        &self,
200        desc: &crate::CommandEncoderDescriptor<'_>,
201    ) -> DispatchCommandEncoder;
202    fn create_render_bundle_encoder(
203        &self,
204        desc: &crate::RenderBundleEncoderDescriptor<'_>,
205    ) -> DispatchRenderBundleEncoder;
206
207    fn set_device_lost_callback(&self, device_lost_callback: BoxDeviceLostCallback);
208
209    fn on_uncaptured_error(&self, handler: Arc<dyn crate::UncapturedErrorHandler>);
210    // Returns index on the stack of the pushed error scope.
211    fn push_error_scope(&self, filter: crate::ErrorFilter) -> u32;
212    fn pop_error_scope(&self, index: u32) -> Pin<Box<dyn PopErrorScopeFuture>>;
213
214    unsafe fn start_graphics_debugger_capture(&self);
215    unsafe fn stop_graphics_debugger_capture(&self);
216
217    fn poll(&self, poll_type: wgt::PollType<u64>) -> Result<crate::PollStatus, crate::PollError>;
218
219    fn get_internal_counters(&self) -> crate::InternalCounters;
220    fn generate_allocator_report(&self) -> Option<crate::AllocatorReport>;
221
222    fn destroy(&self);
223}
224
225pub trait QueueInterface: CommonTraits {
226    fn write_buffer(&self, buffer: &DispatchBuffer, offset: crate::BufferAddress, data: &[u8]);
227
228    fn create_staging_buffer(&self, size: crate::BufferSize) -> Option<DispatchQueueWriteBuffer>;
229    fn validate_write_buffer(
230        &self,
231        buffer: &DispatchBuffer,
232        offset: crate::BufferAddress,
233        size: crate::BufferSize,
234    ) -> Option<()>;
235    fn write_staging_buffer(
236        &self,
237        buffer: &DispatchBuffer,
238        offset: crate::BufferAddress,
239        staging_buffer: DispatchQueueWriteBuffer,
240    );
241
242    fn write_texture(
243        &self,
244        texture: crate::TexelCopyTextureInfo<'_>,
245        data: &[u8],
246        data_layout: crate::TexelCopyBufferLayout,
247        size: crate::Extent3d,
248    );
249    #[cfg(web)]
250    fn copy_external_image_to_texture(
251        &self,
252        source: &crate::CopyExternalImageSourceInfo,
253        dest: crate::CopyExternalImageDestInfo<&crate::api::Texture>,
254        size: crate::Extent3d,
255    );
256
257    /// Submit must always drain the iterator, even in the case of error.
258    fn submit(&self, command_buffers: &mut dyn Iterator<Item = DispatchCommandBuffer>) -> u64;
259
260    fn get_timestamp_period(&self) -> f32;
261    fn on_submitted_work_done(&self, callback: BoxSubmittedWorkDoneCallback);
262
263    fn compact_blas(&self, blas: &DispatchBlas) -> (Option<u64>, DispatchBlas);
264
265    fn present(&self, detail: &DispatchSurfaceOutputDetail);
266}
267
268pub trait ShaderModuleInterface: CommonTraits {
269    fn get_compilation_info(&self) -> Pin<Box<dyn ShaderCompilationInfoFuture>>;
270}
271pub trait BindGroupLayoutInterface: CommonTraits {}
272pub trait BindGroupInterface: CommonTraits {}
273pub trait TextureViewInterface: CommonTraits {}
274pub trait SamplerInterface: CommonTraits {}
275pub trait BufferInterface: CommonTraits {
276    fn map_async(
277        &self,
278        mode: crate::MapMode,
279        range: Range<crate::BufferAddress>,
280        callback: BufferMapCallback,
281    );
282    fn get_mapped_range(
283        &self,
284        sub_range: Range<crate::BufferAddress>,
285    ) -> Result<DispatchBufferMappedRange, crate::MapRangeError>;
286
287    fn unmap(&self);
288
289    fn destroy(&self);
290
291    fn size(&self) -> crate::BufferAddress;
292
293    fn usage(&self) -> crate::BufferUsages;
294}
295pub trait TextureInterface: CommonTraits {
296    fn create_view(&self, desc: &crate::TextureViewDescriptor<'_>) -> DispatchTextureView;
297
298    fn destroy(&self);
299
300    fn size(&self) -> wgt::Extent3d;
301
302    fn mip_level_count(&self) -> u32;
303
304    fn sample_count(&self) -> u32;
305
306    fn dimension(&self) -> wgt::TextureDimension;
307
308    fn format(&self) -> wgt::TextureFormat;
309
310    fn usage(&self) -> wgt::TextureUsages;
311}
312pub trait ExternalTextureInterface: CommonTraits {
313    fn destroy(&self);
314}
315pub trait BlasInterface: CommonTraits {
316    fn prepare_compact_async(&self, callback: BlasCompactCallback);
317    fn ready_for_compaction(&self) -> bool;
318}
319pub trait TlasInterface: CommonTraits {}
320pub trait QuerySetInterface: CommonTraits {
321    fn destroy(&self);
322
323    fn ty(&self) -> crate::QueryType;
324
325    fn count(&self) -> u32;
326}
327pub trait PipelineLayoutInterface: CommonTraits {}
328pub trait RenderPipelineInterface: CommonTraits {
329    fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout;
330}
331pub trait ComputePipelineInterface: CommonTraits {
332    fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout;
333}
334pub trait PipelineCacheInterface: CommonTraits {
335    fn get_data(&self) -> Option<Vec<u8>>;
336}
337pub trait CommandEncoderInterface: CommonTraits {
338    fn copy_buffer_to_buffer(
339        &self,
340        source: &DispatchBuffer,
341        source_offset: crate::BufferAddress,
342        destination: &DispatchBuffer,
343        destination_offset: crate::BufferAddress,
344        copy_size: Option<crate::BufferAddress>,
345    );
346    fn copy_buffer_to_texture(
347        &self,
348        source: crate::TexelCopyBufferInfo<'_>,
349        destination: crate::TexelCopyTextureInfo<'_>,
350        copy_size: crate::Extent3d,
351    );
352    fn copy_texture_to_buffer(
353        &self,
354        source: crate::TexelCopyTextureInfo<'_>,
355        destination: crate::TexelCopyBufferInfo<'_>,
356        copy_size: crate::Extent3d,
357    );
358    fn copy_texture_to_texture(
359        &self,
360        source: crate::TexelCopyTextureInfo<'_>,
361        destination: crate::TexelCopyTextureInfo<'_>,
362        copy_size: crate::Extent3d,
363    );
364
365    fn begin_compute_pass(&self, desc: &crate::ComputePassDescriptor<'_>) -> DispatchComputePass;
366    fn begin_render_pass(&self, desc: &crate::RenderPassDescriptor<'_>) -> DispatchRenderPass;
367    fn finish(&mut self) -> DispatchCommandBuffer;
368
369    fn clear_texture(
370        &self,
371        texture: &DispatchTexture,
372        subresource_range: &crate::ImageSubresourceRange,
373    );
374    fn clear_buffer(
375        &self,
376        buffer: &DispatchBuffer,
377        offset: crate::BufferAddress,
378        size: Option<crate::BufferAddress>,
379    );
380
381    fn insert_debug_marker(&self, label: &str);
382    fn push_debug_group(&self, label: &str);
383    fn pop_debug_group(&self);
384
385    fn write_timestamp(&self, query_set: &DispatchQuerySet, query_index: u32);
386    fn resolve_query_set(
387        &self,
388        query_set: &DispatchQuerySet,
389        first_query: u32,
390        query_count: u32,
391        destination: &DispatchBuffer,
392        destination_offset: crate::BufferAddress,
393    );
394    fn mark_acceleration_structures_built<'a>(
395        &self,
396        blas: &mut dyn Iterator<Item = &'a Blas>,
397        tlas: &mut dyn Iterator<Item = &'a Tlas>,
398    );
399
400    fn build_acceleration_structures<'a>(
401        &self,
402        blas: &mut dyn Iterator<Item = &'a crate::BlasBuildEntry<'a>>,
403        tlas: &mut dyn Iterator<Item = &'a crate::Tlas>,
404    );
405
406    fn transition_resources<'a>(
407        &mut self,
408        buffer_transitions: &mut dyn Iterator<Item = wgt::BufferTransition<&'a DispatchBuffer>>,
409        texture_transitions: &mut dyn Iterator<Item = wgt::TextureTransition<&'a DispatchTexture>>,
410    );
411}
412pub trait ComputePassInterface: CommonTraits + Drop {
413    fn set_pipeline(&mut self, pipeline: &DispatchComputePipeline);
414    fn set_bind_group(
415        &mut self,
416        index: u32,
417        bind_group: Option<&DispatchBindGroup>,
418        offsets: &[crate::DynamicOffset],
419    );
420    fn set_immediates(&mut self, offset: u32, data: &[u8]);
421
422    fn insert_debug_marker(&mut self, label: &str);
423    fn push_debug_group(&mut self, group_label: &str);
424    fn pop_debug_group(&mut self);
425
426    fn write_timestamp(&mut self, query_set: &DispatchQuerySet, query_index: u32);
427    fn begin_pipeline_statistics_query(&mut self, query_set: &DispatchQuerySet, query_index: u32);
428    fn end_pipeline_statistics_query(&mut self);
429
430    fn dispatch_workgroups(&mut self, x: u32, y: u32, z: u32);
431    fn dispatch_workgroups_indirect(
432        &mut self,
433        indirect_buffer: &DispatchBuffer,
434        indirect_offset: crate::BufferAddress,
435    );
436
437    fn transition_resources<'a>(
438        &mut self,
439        buffer_transitions: &mut dyn Iterator<Item = wgt::BufferTransition<&'a DispatchBuffer>>,
440        texture_transitions: &mut dyn Iterator<
441            Item = wgt::TextureTransition<&'a DispatchTextureView>,
442        >,
443    );
444}
445pub trait RenderPassInterface: CommonTraits + Drop {
446    fn set_pipeline(&mut self, pipeline: &DispatchRenderPipeline);
447    fn set_bind_group(
448        &mut self,
449        index: u32,
450        bind_group: Option<&DispatchBindGroup>,
451        offsets: &[crate::DynamicOffset],
452    );
453    fn set_index_buffer(
454        &mut self,
455        buffer: &DispatchBuffer,
456        index_format: crate::IndexFormat,
457        offset: crate::BufferAddress,
458        size: Option<crate::BufferSize>,
459    );
460    fn set_vertex_buffer(
461        &mut self,
462        slot: u32,
463        buffer: Option<&DispatchBuffer>,
464        offset: crate::BufferAddress,
465        size: Option<crate::BufferSize>,
466    );
467    fn set_immediates(&mut self, offset: u32, data: &[u8]);
468    fn set_blend_constant(&mut self, color: crate::Color);
469    fn set_scissor_rect(&mut self, x: u32, y: u32, width: u32, height: u32);
470    fn set_viewport(
471        &mut self,
472        x: f32,
473        y: f32,
474        width: f32,
475        height: f32,
476        min_depth: f32,
477        max_depth: f32,
478    );
479    fn set_stencil_reference(&mut self, reference: u32);
480
481    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>);
482    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>);
483    fn draw_mesh_tasks(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32);
484    fn draw_indirect(
485        &mut self,
486        indirect_buffer: &DispatchBuffer,
487        indirect_offset: crate::BufferAddress,
488    );
489    fn draw_indexed_indirect(
490        &mut self,
491        indirect_buffer: &DispatchBuffer,
492        indirect_offset: crate::BufferAddress,
493    );
494    fn draw_mesh_tasks_indirect(
495        &mut self,
496        indirect_buffer: &DispatchBuffer,
497        indirect_offset: crate::BufferAddress,
498    );
499
500    fn multi_draw_indirect(
501        &mut self,
502        indirect_buffer: &DispatchBuffer,
503        indirect_offset: crate::BufferAddress,
504        count: u32,
505    );
506    fn multi_draw_indexed_indirect(
507        &mut self,
508        indirect_buffer: &DispatchBuffer,
509        indirect_offset: crate::BufferAddress,
510        count: u32,
511    );
512    fn multi_draw_indirect_count(
513        &mut self,
514        indirect_buffer: &DispatchBuffer,
515        indirect_offset: crate::BufferAddress,
516        count_buffer: &DispatchBuffer,
517        count_buffer_offset: crate::BufferAddress,
518        max_count: u32,
519    );
520    fn multi_draw_mesh_tasks_indirect(
521        &mut self,
522        indirect_buffer: &DispatchBuffer,
523        indirect_offset: crate::BufferAddress,
524        count: u32,
525    );
526    fn multi_draw_indexed_indirect_count(
527        &mut self,
528        indirect_buffer: &DispatchBuffer,
529        indirect_offset: crate::BufferAddress,
530        count_buffer: &DispatchBuffer,
531        count_buffer_offset: crate::BufferAddress,
532        max_count: u32,
533    );
534    fn multi_draw_mesh_tasks_indirect_count(
535        &mut self,
536        indirect_buffer: &DispatchBuffer,
537        indirect_offset: crate::BufferAddress,
538        count_buffer: &DispatchBuffer,
539        count_buffer_offset: crate::BufferAddress,
540        max_count: u32,
541    );
542
543    fn insert_debug_marker(&mut self, label: &str);
544    fn push_debug_group(&mut self, group_label: &str);
545    fn pop_debug_group(&mut self);
546
547    fn write_timestamp(&mut self, query_set: &DispatchQuerySet, query_index: u32);
548    fn begin_occlusion_query(&mut self, query_index: u32);
549    fn end_occlusion_query(&mut self);
550    fn begin_pipeline_statistics_query(&mut self, query_set: &DispatchQuerySet, query_index: u32);
551    fn end_pipeline_statistics_query(&mut self);
552
553    fn execute_bundles(&mut self, render_bundles: &mut dyn Iterator<Item = &DispatchRenderBundle>);
554}
555
556pub trait RenderBundleEncoderInterface: CommonTraits {
557    fn set_pipeline(&mut self, pipeline: &DispatchRenderPipeline);
558    fn set_bind_group(
559        &mut self,
560        index: u32,
561        bind_group: Option<&DispatchBindGroup>,
562        offsets: &[crate::DynamicOffset],
563    );
564    fn set_index_buffer(
565        &mut self,
566        buffer: &DispatchBuffer,
567        index_format: crate::IndexFormat,
568        offset: crate::BufferAddress,
569        size: Option<crate::BufferSize>,
570    );
571    fn set_vertex_buffer(
572        &mut self,
573        slot: u32,
574        buffer: Option<&DispatchBuffer>,
575        offset: crate::BufferAddress,
576        size: Option<crate::BufferSize>,
577    );
578    fn set_immediates(&mut self, offset: u32, data: &[u8]);
579
580    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>);
581    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>);
582    fn draw_indirect(
583        &mut self,
584        indirect_buffer: &DispatchBuffer,
585        indirect_offset: crate::BufferAddress,
586    );
587    fn draw_indexed_indirect(
588        &mut self,
589        indirect_buffer: &DispatchBuffer,
590        indirect_offset: crate::BufferAddress,
591    );
592
593    fn finish(self, desc: &crate::RenderBundleDescriptor<'_>) -> DispatchRenderBundle
594    where
595        Self: Sized;
596
597    /// Object-safe version of `finish` for dyn dispatch through `Box<dyn RenderBundleEncoderInterface>`.
598    ///
599    /// A default implementation cannot be provided here: a default that calls `finish` would
600    /// require `Self: Sized` (to move out of the box), which would remove the method from the
601    /// vtable and break object safety. Every concrete backend must implement this as:
602    /// ```ignore
603    /// fn finish_boxed(self: Box<Self>, desc: &RenderBundleDescriptor<'_>) -> DispatchRenderBundle {
604    ///     (*self).finish(desc)
605    /// }
606    /// ```
607    #[cfg(custom)]
608    fn finish_boxed(
609        self: Box<Self>,
610        desc: &crate::RenderBundleDescriptor<'_>,
611    ) -> DispatchRenderBundle;
612}
613
614pub trait CommandBufferInterface: CommonTraits {}
615pub trait RenderBundleInterface: CommonTraits {}
616
617pub trait SurfaceInterface: CommonTraits {
618    fn get_capabilities(&self, adapter: &DispatchAdapter) -> crate::SurfaceCapabilities;
619
620    /// The backing display's current HDR / luminance characteristics.
621    ///
622    /// Defaults to [`crate::DisplayHdrInfo::default`] (all fields `None`) so
623    /// custom backends without a display query need not override it.
624    fn display_hdr_info(&self, adapter: &DispatchAdapter) -> crate::DisplayHdrInfo {
625        let _ = adapter;
626        crate::DisplayHdrInfo::default()
627    }
628
629    fn configure(&self, device: &DispatchDevice, config: &crate::SurfaceConfiguration);
630    fn get_current_texture(
631        &self,
632        desc: Option<crate::TextureDescriptor<'static>>,
633    ) -> (
634        Option<DispatchTexture>,
635        crate::SurfaceStatus,
636        DispatchSurfaceOutputDetail,
637    );
638}
639
640pub trait SurfaceOutputDetailInterface: CommonTraits {
641    fn texture_discard(&self);
642    fn texture_release(&self);
643}
644
645pub trait QueueWriteBufferInterface: CommonTraits {
646    fn len(&self) -> usize;
647
648    /// # Safety
649    ///
650    /// Must only be used on write, not read, mappings.
651    unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]>;
652}
653
654pub trait BufferMappedRangeInterface: CommonTraits {
655    // Used only in wgpu_core's `impl QueueWriteBufferInterface`
656    #[cfg_attr(not(wgpu_core), expect(unused))]
657    fn len(&self) -> usize;
658
659    /// # Safety
660    ///
661    /// Must only be used on read, not write, mappings.
662    unsafe fn read_slice(&self) -> &[u8];
663
664    /// # Safety
665    ///
666    /// Must only be used on write, not read, mappings.
667    unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]>;
668
669    #[cfg(webgpu)]
670    fn as_uint8array(&self) -> &js_sys::Uint8Array;
671}
672
673/// Generates a dispatch type for some `wgpu` API type.
674///
675/// Invocations of this macro take one of the following forms:
676///
677/// ```ignore
678/// dispatch_types! {mut type D: I = Core, Web, Dyn }
679/// dispatch_types! {ref type D: I = Core, Web, Dyn }
680/// ```
681///
682/// This defines `D` as a type that dereferences to a `dyn I` trait object. Most uses of
683/// `D` in the rest of this crate just call the methods from the `dyn I` object, not from
684/// `D` itself.
685///
686/// Internally, `D` is an enum with up to three variants holding values of type `Core`,
687/// `Web`, and `Dyn`, all of which must implement `I`. `Core`, `Web` and `Dyn` are the
688/// types from the `wgpu_core`, `webgpu`, and `custom` submodules of `wgpu::backend` that
689/// correspond to `D`. The macro generates `Deref` and `DerefMut` implementations that
690/// match on this enum and produce a `dyn I` reference for each variant.
691///
692/// The macro's `mut type` form defines `D` as the unique owner of the backend type, with
693/// a `DerefMut` implementation, and `as_*_mut` methods that return `&mut` references.
694/// This `D` does not implement `Clone`.
695///
696/// The macro's `ref type` form defines `D` to hold an `Arc` pointing to the backend type,
697/// permitting `Clone` and `Deref`, but losing exclusive, mutable access.
698///
699/// For example:
700///
701/// ```ignore
702/// dispatch_types! {ref type DispatchBuffer: BufferInterface =
703///                  CoreBuffer, WebBuffer, DynBuffer}
704/// ```
705///
706/// This defines `DispatchBuffer` as a type that dereferences to `&dyn BufferInterface`,
707/// which has methods like `map_async` and `destroy`. The enum would be:
708///
709/// ```ignore
710/// pub enum DispatchBuffer {
711///     #[cfg(wgpu_core)]
712///     Core(Arc<CoreBuffer>),
713///     #[cfg(webgpu)]
714///     WebGPU(WebBuffer),
715///     #[cfg(custom)]
716///     Custom(DynBuffer),
717/// }
718/// ```
719///
720/// This macro also defines `as_*` methods so that the backend implementations can
721/// dereference other arguments.
722///
723/// ## Devirtualization
724///
725/// The dispatch types generated by this macro are carefully designed to allow the
726/// compiler to completely devirtualize calls in most circumstances.
727///
728/// Note that every variant of the enum generated by this macro is under a `#[cfg]`.
729/// Naturally, the `match` expressions in the `Deref` and `DerefMut` implementations have
730/// matching `#[cfg]` attributes on each match arm.
731///
732/// In practice, when `wgpu`'s `"custom"` feature is not enabled, there is usually only
733/// one variant in the `enum`, making it effectively a newtype around the sole variant's
734/// data: it has no discriminant to branch on, and the `match` expressions are removed
735/// entirely by the compiler.
736///
737/// In this case, when we invoke a method from the interface trait `I` on a dispatch type,
738/// the `Deref` and `DerefMut` implementations' `match` statements build a `&dyn I` for
739/// the data, on which we immediately invoke a method. The vtable is a constant, allowing
740/// the Rust compiler to turn the `dyn` method call into an ordinary method call. This
741/// creates opportunities for inlining.
742///
743/// Similarly, the `as_*` methods are free when there is only one backend.
744macro_rules! dispatch_types {
745    (
746        ref type $name:ident: $interface:ident = $core_type:ident,$webgpu_type:ident,$custom_type:ident
747    ) => {
748        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
749        pub enum $name {
750            #[cfg(wgpu_core)]
751            Core(Arc<$core_type>),
752            #[cfg(webgpu)]
753            WebGPU($webgpu_type),
754            #[allow(clippy::allow_attributes, private_interfaces)]
755            #[cfg(custom)]
756            Custom($custom_type),
757        }
758
759        impl $name {
760            #[cfg(wgpu_core)]
761            #[inline]
762            #[allow(clippy::allow_attributes, unused)]
763            pub fn as_core(&self) -> &$core_type {
764                match self {
765                    Self::Core(value) => value,
766                    _ => panic!(concat!(stringify!($name), " is not core")),
767                }
768            }
769
770            #[cfg(wgpu_core)]
771            #[inline]
772            #[allow(clippy::allow_attributes, unused)]
773            pub fn as_core_opt(&self) -> Option<&$core_type> {
774                match self {
775                    Self::Core(value) => Some(value),
776                    _ => None,
777                }
778            }
779
780            #[cfg(custom)]
781            #[inline]
782            #[allow(clippy::allow_attributes, unused)]
783            pub fn as_custom<T: $interface>(&self) -> Option<&T> {
784                match self {
785                    Self::Custom(value) => value.downcast(),
786                    _ => None,
787                }
788            }
789
790            #[cfg(webgpu)]
791            #[inline]
792            #[allow(clippy::allow_attributes, unused)]
793            pub fn as_webgpu(&self) -> &$webgpu_type {
794                match self {
795                    Self::WebGPU(value) => value,
796                    _ => panic!(concat!(stringify!($name), " is not webgpu")),
797                }
798            }
799
800            #[cfg(webgpu)]
801            #[inline]
802            #[allow(clippy::allow_attributes, unused)]
803            pub fn as_webgpu_opt(&self) -> Option<&$webgpu_type> {
804                match self {
805                    Self::WebGPU(value) => Some(value),
806                    _ => None,
807                }
808            }
809
810            #[cfg(custom)]
811            #[inline]
812            pub fn custom<T: $interface>(t: T) -> Self {
813                Self::Custom($custom_type::new(t))
814            }
815        }
816
817        #[cfg(wgpu_core)]
818        impl From<$core_type> for $name {
819            #[inline]
820            fn from(value: $core_type) -> Self {
821                Self::Core(Arc::new(value))
822            }
823        }
824
825        #[cfg(webgpu)]
826        impl From<$webgpu_type> for $name {
827            #[inline]
828            fn from(value: $webgpu_type) -> Self {
829                Self::WebGPU(value)
830            }
831        }
832
833        impl core::ops::Deref for $name {
834            type Target = dyn $interface;
835
836            #[inline]
837            fn deref(&self) -> &Self::Target {
838                match self {
839                    #[cfg(wgpu_core)]
840                    Self::Core(value) => value.as_ref(),
841                    #[cfg(webgpu)]
842                    Self::WebGPU(value) => value,
843                    #[cfg(custom)]
844                    Self::Custom(value) => value.deref(),
845                    #[cfg(not(any(wgpu_core, webgpu)))]
846                    _ => panic!("No context available. You need to enable one of wgpu's backend feature build flags."),
847                }
848            }
849        }
850    };
851    (
852        mut type $name:ident: $interface:ident = $core_type:ident,$webgpu_type:ident,$custom_type:ident
853    ) => {
854        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
855        pub enum $name {
856            #[cfg(wgpu_core)]
857            Core($core_type),
858            #[cfg(webgpu)]
859            WebGPU($webgpu_type),
860            #[allow(clippy::allow_attributes, private_interfaces)]
861            #[cfg(custom)]
862            Custom($custom_type),
863        }
864
865        impl $name {
866            #[cfg(wgpu_core)]
867            #[inline]
868            #[allow(clippy::allow_attributes, unused)]
869            pub fn as_core(&self) -> &$core_type {
870                match self {
871                    Self::Core(value) => value,
872                    _ => panic!(concat!(stringify!($name), " is not core")),
873                }
874            }
875
876            #[cfg(wgpu_core)]
877            #[inline]
878            #[allow(clippy::allow_attributes, unused)]
879            pub fn as_core_mut(&mut self) -> &mut $core_type {
880                match self {
881                    Self::Core(value) => value,
882                    _ => panic!(concat!(stringify!($name), " is not core")),
883                }
884            }
885
886            #[cfg(wgpu_core)]
887            #[inline]
888            #[allow(clippy::allow_attributes, unused)]
889            pub fn as_core_opt(&self) -> Option<&$core_type> {
890                match self {
891                    Self::Core(value) => Some(value),
892                    _ => None,
893                }
894            }
895
896            #[cfg(wgpu_core)]
897            #[inline]
898            #[allow(clippy::allow_attributes, unused)]
899            pub fn as_core_mut_opt(
900                &mut self,
901            ) -> Option<&mut $core_type> {
902                match self {
903                    Self::Core(value) => Some(value),
904                    _ => None,
905                }
906            }
907
908            #[cfg(custom)]
909            #[inline]
910            #[allow(clippy::allow_attributes, unused)]
911            pub fn as_custom<T: $interface>(&self) -> Option<&T> {
912                match self {
913                    Self::Custom(value) => value.downcast(),
914                    _ => None,
915                }
916            }
917
918            #[cfg(webgpu)]
919            #[inline]
920            #[allow(clippy::allow_attributes, unused)]
921            pub fn as_webgpu(&self) -> &$webgpu_type {
922                match self {
923                    Self::WebGPU(value) => value,
924                    _ => panic!(concat!(stringify!($name), " is not webgpu")),
925                }
926            }
927
928            #[cfg(webgpu)]
929            #[inline]
930            #[allow(clippy::allow_attributes, unused)]
931            pub fn as_webgpu_mut(&mut self) -> &mut $webgpu_type {
932                match self {
933                    Self::WebGPU(value) => value,
934                    _ => panic!(concat!(stringify!($name), " is not webgpu")),
935                }
936            }
937
938            #[cfg(webgpu)]
939            #[inline]
940            #[allow(clippy::allow_attributes, unused)]
941            pub fn as_webgpu_opt(&self) -> Option<&$webgpu_type> {
942                match self {
943                    Self::WebGPU(value) => Some(value),
944                    _ => None,
945                }
946            }
947
948            #[cfg(webgpu)]
949            #[inline]
950            #[allow(clippy::allow_attributes, unused)]
951            pub fn as_webgpu_mut_opt(
952                &mut self,
953            ) -> Option<&mut $webgpu_type> {
954                match self {
955                    Self::WebGPU(value) => Some(value),
956                    _ => None,
957                }
958            }
959
960            #[cfg(custom)]
961            #[inline]
962            pub fn custom<T: $interface>(t: T) -> Self {
963                Self::Custom($custom_type::new(t))
964            }
965        }
966
967        #[cfg(wgpu_core)]
968        impl From<$core_type> for $name {
969            #[inline]
970            fn from(value: $core_type) -> Self {
971                Self::Core(value)
972            }
973        }
974
975        #[cfg(webgpu)]
976        impl From<$webgpu_type> for $name {
977            #[inline]
978            fn from(value: $webgpu_type) -> Self {
979                Self::WebGPU(value)
980            }
981        }
982
983        impl core::ops::Deref for $name {
984            type Target = dyn $interface;
985
986            #[inline]
987            fn deref(&self) -> &Self::Target {
988                match self {
989                    #[cfg(wgpu_core)]
990                    Self::Core(value) => value,
991                    #[cfg(webgpu)]
992                    Self::WebGPU(value) => value,
993                    #[cfg(custom)]
994                    Self::Custom(value) => value.deref(),
995                    #[cfg(not(any(wgpu_core, webgpu)))]
996                    _ => panic!("No context available. You need to enable one of wgpu's backend feature build flags."),
997                }
998            }
999        }
1000
1001        impl core::ops::DerefMut for $name {
1002            #[inline]
1003            fn deref_mut(&mut self) -> &mut Self::Target {
1004                match self {
1005                    #[cfg(wgpu_core)]
1006                    Self::Core(value) => value,
1007                    #[cfg(webgpu)]
1008                    Self::WebGPU(value) => value,
1009                    #[cfg(custom)]
1010                    Self::Custom(value) => value.deref_mut(),
1011                    #[cfg(not(any(wgpu_core, webgpu)))]
1012                    _ => panic!("No context available. You need to enable one of wgpu's backend feature build flags."),
1013                }
1014            }
1015        }
1016    };
1017}
1018
1019dispatch_types! {ref type DispatchInstance: InstanceInterface = ContextWgpuCore, ContextWebGpu, DynContext}
1020dispatch_types! {ref type DispatchAdapter: AdapterInterface = CoreAdapter, WebAdapter, DynAdapter}
1021dispatch_types! {ref type DispatchDevice: DeviceInterface = CoreDevice, WebDevice, DynDevice}
1022dispatch_types! {ref type DispatchQueue: QueueInterface = CoreQueue, WebQueue, DynQueue}
1023dispatch_types! {ref type DispatchShaderModule: ShaderModuleInterface = CoreShaderModule, WebShaderModule, DynShaderModule}
1024dispatch_types! {ref type DispatchBindGroupLayout: BindGroupLayoutInterface = CoreBindGroupLayout, WebBindGroupLayout, DynBindGroupLayout}
1025dispatch_types! {ref type DispatchBindGroup: BindGroupInterface = CoreBindGroup, WebBindGroup, DynBindGroup}
1026dispatch_types! {ref type DispatchTextureView: TextureViewInterface = CoreTextureView, WebTextureView, DynTextureView}
1027dispatch_types! {ref type DispatchSampler: SamplerInterface = CoreSampler, WebSampler, DynSampler}
1028dispatch_types! {ref type DispatchBuffer: BufferInterface = CoreBuffer, WebBuffer, DynBuffer}
1029dispatch_types! {ref type DispatchTexture: TextureInterface = CoreTexture, WebTexture, DynTexture}
1030dispatch_types! {ref type DispatchExternalTexture: ExternalTextureInterface = CoreExternalTexture, WebExternalTexture, DynExternalTexture}
1031dispatch_types! {ref type DispatchBlas: BlasInterface = CoreBlas, WebBlas, DynBlas}
1032dispatch_types! {ref type DispatchTlas: TlasInterface = CoreTlas, WebTlas, DynTlas}
1033dispatch_types! {ref type DispatchQuerySet: QuerySetInterface = CoreQuerySet, WebQuerySet, DynQuerySet}
1034dispatch_types! {ref type DispatchPipelineLayout: PipelineLayoutInterface = CorePipelineLayout, WebPipelineLayout, DynPipelineLayout}
1035dispatch_types! {ref type DispatchRenderPipeline: RenderPipelineInterface = CoreRenderPipeline, WebRenderPipeline, DynRenderPipeline}
1036dispatch_types! {ref type DispatchComputePipeline: ComputePipelineInterface = CoreComputePipeline, WebComputePipeline, DynComputePipeline}
1037dispatch_types! {ref type DispatchPipelineCache: PipelineCacheInterface = CorePipelineCache, WebPipelineCache, DynPipelineCache}
1038dispatch_types! {mut type DispatchCommandEncoder: CommandEncoderInterface = CoreCommandEncoder, WebCommandEncoder, DynCommandEncoder}
1039dispatch_types! {mut type DispatchComputePass: ComputePassInterface = CoreComputePass, WebComputePassEncoder, DynComputePass}
1040dispatch_types! {mut type DispatchRenderPass: RenderPassInterface = CoreRenderPass, WebRenderPassEncoder, DynRenderPass}
1041dispatch_types! {mut type DispatchCommandBuffer: CommandBufferInterface = CoreCommandBuffer, WebCommandBuffer, DynCommandBuffer}
1042dispatch_types! {mut type DispatchRenderBundleEncoder: RenderBundleEncoderInterface = CoreRenderBundleEncoder, WebRenderBundleEncoder, DynRenderBundleEncoder}
1043dispatch_types! {ref type DispatchRenderBundle: RenderBundleInterface = CoreRenderBundle, WebRenderBundle, DynRenderBundle}
1044dispatch_types! {ref type DispatchSurface: SurfaceInterface = CoreSurface, WebSurface, DynSurface}
1045dispatch_types! {ref type DispatchSurfaceOutputDetail: SurfaceOutputDetailInterface = CoreSurfaceOutputDetail, WebSurfaceOutputDetail, DynSurfaceOutputDetail}
1046dispatch_types! {mut type DispatchQueueWriteBuffer: QueueWriteBufferInterface = CoreQueueWriteBuffer, WebQueueWriteBuffer, DynQueueWriteBuffer}
1047dispatch_types! {mut type DispatchBufferMappedRange: BufferMappedRangeInterface = CoreBufferMappedRange, WebBufferMappedRange, DynBufferMappedRange}