Skip to main content

wgpu/backend/
wgpu_core.rs

1use alloc::{
2    borrow::Cow::{self, Borrowed},
3    boxed::Box,
4    format,
5    string::{String, ToString as _},
6    sync::Arc,
7    vec,
8    vec::Vec,
9};
10use core::{
11    error::Error,
12    fmt,
13    future::ready,
14    ops::{Deref, Range},
15    pin::Pin,
16    ptr::NonNull,
17    slice,
18};
19use hashbrown::HashMap;
20
21use arrayvec::ArrayVec;
22use smallvec::SmallVec;
23use wgc::{
24    error::ContextErrorSource, pipeline::CreateShaderModuleError,
25    resource::BlasPrepareCompactResult,
26};
27use wgt::{
28    error::{ErrorType, WebGpuError},
29    WasmNotSendSync,
30};
31
32use crate::{
33    api,
34    dispatch::{self, BlasCompactCallback, BufferMappedRangeInterface},
35    BindingResource, Blas, BufferBinding, BufferDescriptor, CompilationInfo, CompilationMessage,
36    CompilationMessageType, ErrorSource, Features, Label, LoadOp, MapMode, Operations,
37    ShaderSource, SurfaceTargetUnsafe, TextureDescriptor, Tlas, WriteOnly,
38};
39use crate::{dispatch::DispatchAdapter, util::Mutex};
40
41mod thread_id;
42
43#[derive(Clone)]
44pub struct ContextWgpuCore(Arc<wgc::global::Global>);
45
46impl Drop for ContextWgpuCore {
47    fn drop(&mut self) {
48        //nothing
49    }
50}
51
52impl fmt::Debug for ContextWgpuCore {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        f.debug_struct("ContextWgpuCore")
55            .field("type", &"Native")
56            .finish()
57    }
58}
59
60impl ContextWgpuCore {
61    pub unsafe fn from_hal_instance<A: hal::Api>(hal_instance: A::Instance) -> Self {
62        Self(unsafe {
63            Arc::new(wgc::global::Global::from_hal_instance::<A>(
64                "wgpu",
65                hal_instance,
66            ))
67        })
68    }
69
70    /// # Safety
71    ///
72    /// - The raw instance handle returned must not be manually destroyed.
73    pub unsafe fn instance_as_hal<A: hal::Api>(&self) -> Option<&A::Instance> {
74        unsafe { self.0.instance_as_hal::<A>() }
75    }
76
77    pub unsafe fn from_core_instance(core_instance: wgc::instance::Instance) -> Self {
78        Self(unsafe { Arc::new(wgc::global::Global::from_instance(core_instance)) })
79    }
80
81    #[cfg(wgpu_core)]
82    pub fn enumerate_adapters(&self, backends: wgt::Backends) -> Vec<wgc::id::AdapterId> {
83        self.0
84            .enumerate_adapters(backends, false /* no limit bucketing */)
85    }
86
87    pub unsafe fn create_adapter_from_hal<A: hal::Api>(
88        &self,
89        hal_adapter: hal::ExposedAdapter<A>,
90    ) -> wgc::id::AdapterId {
91        unsafe { self.0.create_adapter_from_hal(hal_adapter.into(), None) }
92    }
93
94    pub unsafe fn adapter_as_hal<A: hal::Api>(
95        &self,
96        adapter: &CoreAdapter,
97    ) -> Option<impl Deref<Target = A::Adapter> + WasmNotSendSync> {
98        unsafe { self.0.adapter_as_hal::<A>(adapter.id) }
99    }
100
101    pub unsafe fn buffer_as_hal<A: hal::Api>(
102        &self,
103        buffer: &CoreBuffer,
104    ) -> Option<impl Deref<Target = A::Buffer>> {
105        unsafe { self.0.buffer_as_hal::<A>(buffer.id) }
106    }
107
108    pub unsafe fn create_device_from_hal<A: hal::Api>(
109        &self,
110        adapter: &CoreAdapter,
111        hal_device: hal::OpenDevice<A>,
112        desc: &crate::DeviceDescriptor<'_>,
113    ) -> Result<(CoreDevice, CoreQueue), crate::RequestDeviceError> {
114        let (device_id, queue_id) = unsafe {
115            self.0.create_device_from_hal(
116                adapter.id,
117                hal_device.into(),
118                &desc.map_label(|l| l.map(Borrowed)),
119                None,
120                None,
121            )
122        }?;
123        let error_sink = Arc::new(Mutex::new(ErrorSinkRaw::new()));
124        let device = CoreDevice {
125            context: self.clone(),
126            id: device_id,
127            error_sink: error_sink.clone(),
128            features: desc.required_features,
129        };
130        let queue = CoreQueue {
131            context: self.clone(),
132            id: queue_id,
133            error_sink,
134        };
135        Ok((device, queue))
136    }
137
138    pub unsafe fn create_texture_from_hal<A: hal::Api>(
139        &self,
140        hal_texture: A::Texture,
141        device: &CoreDevice,
142        desc: &TextureDescriptor<'_>,
143        initial_state: wgt::TextureUses,
144    ) -> CoreTexture {
145        let descriptor = desc.map_label_and_view_formats(|l| l.map(Borrowed), |v| v.to_vec());
146        let (id, error) = unsafe {
147            self.0.create_texture_from_hal(
148                Box::new(hal_texture),
149                device.id,
150                &descriptor,
151                initial_state,
152                None,
153            )
154        };
155        if let Some(cause) = error {
156            self.handle_error(
157                &device.error_sink,
158                cause,
159                desc.label,
160                "Device::create_texture_from_hal",
161            );
162        }
163        CoreTexture {
164            context: self.clone(),
165            id,
166            error_sink: Arc::clone(&device.error_sink),
167        }
168    }
169
170    /// # Safety
171    ///
172    /// - `hal_buffer` must be created from `device`.
173    /// - `hal_buffer` must be created respecting `desc`
174    /// - `hal_buffer` must be initialized
175    /// - `hal_buffer` must not have zero size.
176    pub unsafe fn create_buffer_from_hal<A: hal::Api>(
177        &self,
178        hal_buffer: A::Buffer,
179        device: &CoreDevice,
180        desc: &BufferDescriptor<'_>,
181    ) -> CoreBuffer {
182        let (id, error) = unsafe {
183            self.0.create_buffer_from_hal::<A>(
184                hal_buffer,
185                device.id,
186                &desc.map_label(|l| l.map(Borrowed)),
187                None,
188            )
189        };
190        if let Some(cause) = error {
191            self.handle_error(
192                &device.error_sink,
193                cause,
194                desc.label,
195                "Device::create_buffer_from_hal",
196            );
197        }
198        CoreBuffer {
199            context: self.clone(),
200            id,
201            error_sink: Arc::clone(&device.error_sink),
202        }
203    }
204
205    pub unsafe fn device_as_hal<A: hal::Api>(
206        &self,
207        device: &CoreDevice,
208    ) -> Option<impl Deref<Target = A::Device>> {
209        unsafe { self.0.device_as_hal::<A>(device.id) }
210    }
211
212    pub unsafe fn surface_as_hal<A: hal::Api>(
213        &self,
214        surface: &CoreSurface,
215    ) -> Option<impl Deref<Target = A::Surface>> {
216        unsafe { self.0.surface_as_hal::<A>(surface.id) }
217    }
218
219    pub unsafe fn texture_as_hal<A: hal::Api>(
220        &self,
221        texture: &CoreTexture,
222    ) -> Option<impl Deref<Target = A::Texture>> {
223        unsafe { self.0.texture_as_hal::<A>(texture.id) }
224    }
225
226    pub unsafe fn texture_view_as_hal<A: hal::Api>(
227        &self,
228        texture_view: &CoreTextureView,
229    ) -> Option<impl Deref<Target = A::TextureView>> {
230        unsafe { self.0.texture_view_as_hal::<A>(texture_view.id) }
231    }
232
233    /// This method will start the wgpu_core level command recording.
234    pub unsafe fn command_encoder_as_hal_mut<
235        A: hal::Api,
236        F: FnOnce(Option<&mut A::CommandEncoder>) -> R,
237        R,
238    >(
239        &self,
240        command_encoder: &CoreCommandEncoder,
241        hal_command_encoder_callback: F,
242    ) -> R {
243        unsafe {
244            self.0.command_encoder_as_hal_mut::<A, F, R>(
245                command_encoder.id,
246                hal_command_encoder_callback,
247            )
248        }
249    }
250
251    pub unsafe fn blas_as_hal<A: hal::Api>(
252        &self,
253        blas: &CoreBlas,
254    ) -> Option<impl Deref<Target = A::AccelerationStructure>> {
255        unsafe { self.0.blas_as_hal::<A>(blas.id) }
256    }
257
258    pub unsafe fn tlas_as_hal<A: hal::Api>(
259        &self,
260        tlas: &CoreTlas,
261    ) -> Option<impl Deref<Target = A::AccelerationStructure>> {
262        unsafe { self.0.tlas_as_hal::<A>(tlas.id) }
263    }
264
265    pub fn generate_report(&self) -> wgc::global::GlobalReport {
266        self.0.generate_report()
267    }
268
269    #[cold]
270    #[track_caller]
271    #[inline(never)]
272    fn handle_error_inner(
273        &self,
274        sink_mutex: &Mutex<ErrorSinkRaw>,
275        error_type: ErrorType,
276        source: ContextErrorSource,
277        label: Label<'_>,
278        fn_ident: &'static str,
279    ) {
280        let source: ErrorSource = Box::new(wgc::error::ContextError {
281            fn_ident,
282            source,
283            label: label.unwrap_or_default().to_string(),
284        });
285        let final_error_handling = {
286            let mut sink = sink_mutex.lock();
287            let description = || self.format_error(&*source);
288            let error = match error_type {
289                ErrorType::Internal => {
290                    let description = description();
291                    crate::Error::Internal {
292                        source,
293                        description,
294                    }
295                }
296                ErrorType::OutOfMemory => crate::Error::OutOfMemory { source },
297                ErrorType::Validation => {
298                    let description = description();
299                    crate::Error::Validation {
300                        source,
301                        description,
302                    }
303                }
304                ErrorType::DeviceLost => return, // will be surfaced via callback
305            };
306            sink.handle_error_or_return_handler(error)
307        };
308
309        if let Some(f) = final_error_handling {
310            // If the user has provided their own `uncaptured_handler` callback, invoke it now,
311            // having released our lock on `sink_mutex`. See the comments on
312            // `handle_error_or_return_handler` for details.
313            f();
314        }
315    }
316
317    #[inline]
318    #[track_caller]
319    fn handle_error(
320        &self,
321        sink_mutex: &Mutex<ErrorSinkRaw>,
322        source: impl WebGpuError + WasmNotSendSync + 'static,
323        label: Label<'_>,
324        fn_ident: &'static str,
325    ) {
326        let error_type = source.webgpu_error_type();
327        self.handle_error_inner(sink_mutex, error_type, Box::new(source), label, fn_ident)
328    }
329
330    #[inline]
331    #[track_caller]
332    fn handle_error_nolabel(
333        &self,
334        sink_mutex: &Mutex<ErrorSinkRaw>,
335        source: impl WebGpuError + WasmNotSendSync + 'static,
336        fn_ident: &'static str,
337    ) {
338        let error_type = source.webgpu_error_type();
339        self.handle_error_inner(sink_mutex, error_type, Box::new(source), None, fn_ident)
340    }
341
342    #[track_caller]
343    #[cold]
344    fn handle_error_fatal(
345        &self,
346        cause: impl Error + WasmNotSendSync + 'static,
347        operation: &'static str,
348    ) -> ! {
349        panic!("Error in {operation}: {f}", f = self.format_error(&cause));
350    }
351
352    #[inline(never)]
353    fn format_error(&self, err: &(dyn Error + 'static)) -> String {
354        let mut output = String::new();
355        let mut level = 1;
356
357        fn print_tree(output: &mut String, level: &mut usize, e: &(dyn Error + 'static)) {
358            let mut print = |e: &(dyn Error + 'static)| {
359                use core::fmt::Write;
360                writeln!(output, "{}{}", " ".repeat(*level * 2), e).unwrap();
361
362                if let Some(e) = e.source() {
363                    *level += 1;
364                    print_tree(output, level, e);
365                    *level -= 1;
366                }
367            };
368            if let Some(multi) = e.downcast_ref::<wgc::error::MultiError>() {
369                for e in multi.errors() {
370                    print(e);
371                }
372            } else {
373                print(e);
374            }
375        }
376
377        print_tree(&mut output, &mut level, err);
378
379        format!("Validation Error\n\nCaused by:\n{output}")
380    }
381
382    pub unsafe fn queue_as_hal<A: hal::Api>(
383        &self,
384        queue: &CoreQueue,
385    ) -> Option<impl Deref<Target = A::Queue> + WasmNotSendSync> {
386        unsafe { self.0.queue_as_hal::<A>(queue.id) }
387    }
388}
389
390fn map_buffer_copy_view(
391    view: crate::TexelCopyBufferInfo<'_>,
392) -> wgt::TexelCopyBufferInfo<wgc::id::BufferId> {
393    wgt::TexelCopyBufferInfo {
394        buffer: view.buffer.inner.as_core().id,
395        layout: view.layout,
396    }
397}
398
399fn map_texture_copy_view(
400    view: crate::TexelCopyTextureInfo<'_>,
401) -> wgt::TexelCopyTextureInfo<wgc::id::TextureId> {
402    wgt::TexelCopyTextureInfo {
403        texture: view.texture.inner.as_core().id,
404        mip_level: view.mip_level,
405        origin: view.origin,
406        aspect: view.aspect,
407    }
408}
409
410#[cfg_attr(not(webgl), expect(unused))]
411fn map_texture_tagged_copy_view(
412    view: crate::CopyExternalImageDestInfo<&api::Texture>,
413) -> wgt::CopyExternalImageDestInfo<wgc::id::TextureId> {
414    wgt::CopyExternalImageDestInfo {
415        texture: view.texture.inner.as_core().id,
416        mip_level: view.mip_level,
417        origin: view.origin,
418        aspect: view.aspect,
419        color_space: view.color_space,
420        premultiplied_alpha: view.premultiplied_alpha,
421    }
422}
423
424fn map_load_op<V: Copy>(load: &LoadOp<V>) -> LoadOp<Option<V>> {
425    match *load {
426        LoadOp::Clear(clear_value) => LoadOp::Clear(Some(clear_value)),
427        LoadOp::DontCare(token) => LoadOp::DontCare(token),
428        LoadOp::Load => LoadOp::Load,
429    }
430}
431
432fn map_pass_channel<V: Copy>(ops: Option<&Operations<V>>) -> wgc::command::PassChannel<Option<V>> {
433    match ops {
434        Some(&Operations { load, store }) => wgc::command::PassChannel {
435            load_op: Some(map_load_op(&load)),
436            store_op: Some(store),
437            read_only: false,
438        },
439        None => wgc::command::PassChannel {
440            load_op: None,
441            store_op: None,
442            read_only: true,
443        },
444    }
445}
446
447#[derive(Debug)]
448pub struct CoreSurface {
449    pub(crate) context: ContextWgpuCore,
450    id: wgc::id::SurfaceId,
451    /// Configured device is needed to know which backend
452    /// code to execute when acquiring a new frame.
453    configured_device: Mutex<Option<wgc::id::DeviceId>>,
454    /// The error sink with which to report errors.
455    /// `None` if the surface has not been configured.
456    error_sink: Mutex<Option<ErrorSink>>,
457}
458
459#[derive(Debug)]
460pub struct CoreAdapter {
461    pub(crate) context: ContextWgpuCore,
462    pub(crate) id: wgc::id::AdapterId,
463}
464
465#[derive(Debug)]
466pub struct CoreDevice {
467    pub(crate) context: ContextWgpuCore,
468    id: wgc::id::DeviceId,
469    error_sink: ErrorSink,
470    features: Features,
471}
472
473impl CoreDevice {
474    /// A module of GLSL templates on a WebGL device, which the browser checks.
475    #[cfg(webgl)]
476    pub fn create_shader_module_glsl_templates(
477        &self,
478        label: crate::Label<'_>,
479        templates: &'static [hal::GlslTemplate],
480    ) -> dispatch::DispatchShaderModule {
481        // SAFETY: on WebGL the browser checks the GLSL before it compiles.
482        let (id, error) = unsafe {
483            self.context.0.device_create_shader_module_glsl_templates(
484                self.id,
485                &label.map(Cow::Borrowed),
486                templates,
487                None,
488            )
489        };
490        let compilation_info = match error {
491            Some(cause) => {
492                self.context.handle_error(
493                    &self.error_sink,
494                    cause.clone(),
495                    label,
496                    "Device::create_shader_module_glsl_templates",
497                );
498                CompilationInfo::from(cause)
499            }
500            None => CompilationInfo { messages: vec![] },
501        };
502        CoreShaderModule {
503            context: self.context.clone(),
504            id,
505            compilation_info,
506        }
507        .into()
508    }
509}
510
511#[derive(Debug)]
512pub struct CoreBuffer {
513    pub(crate) context: ContextWgpuCore,
514    id: wgc::id::BufferId,
515    error_sink: ErrorSink,
516}
517
518#[derive(Debug)]
519pub struct CoreShaderModule {
520    pub(crate) context: ContextWgpuCore,
521    id: wgc::id::ShaderModuleId,
522    compilation_info: CompilationInfo,
523}
524
525#[derive(Debug)]
526pub struct CoreBindGroupLayout {
527    pub(crate) context: ContextWgpuCore,
528    id: wgc::id::BindGroupLayoutId,
529}
530
531#[derive(Debug)]
532pub struct CoreBindGroup {
533    pub(crate) context: ContextWgpuCore,
534    id: wgc::id::BindGroupId,
535}
536
537#[derive(Debug)]
538pub struct CoreTexture {
539    pub(crate) context: ContextWgpuCore,
540    id: wgc::id::TextureId,
541    error_sink: ErrorSink,
542}
543
544#[derive(Debug)]
545pub struct CoreTextureView {
546    pub(crate) context: ContextWgpuCore,
547    id: wgc::id::TextureViewId,
548}
549
550#[derive(Debug)]
551pub struct CoreExternalTexture {
552    pub(crate) context: ContextWgpuCore,
553    id: wgc::id::ExternalTextureId,
554}
555
556#[derive(Debug)]
557pub struct CoreSampler {
558    pub(crate) context: ContextWgpuCore,
559    id: wgc::id::SamplerId,
560}
561
562#[derive(Debug)]
563pub struct CoreQuerySet {
564    pub(crate) context: ContextWgpuCore,
565    id: wgc::id::QuerySetId,
566}
567
568#[derive(Debug)]
569pub struct CorePipelineLayout {
570    pub(crate) context: ContextWgpuCore,
571    id: wgc::id::PipelineLayoutId,
572}
573
574#[derive(Debug)]
575pub struct CorePipelineCache {
576    pub(crate) context: ContextWgpuCore,
577    id: wgc::id::PipelineCacheId,
578}
579
580#[derive(Debug)]
581pub struct CoreCommandBuffer {
582    pub(crate) context: ContextWgpuCore,
583    id: wgc::id::CommandBufferId,
584}
585
586#[derive(Debug)]
587pub struct CoreRenderBundleEncoder {
588    pub(crate) context: ContextWgpuCore,
589    encoder: Box<wgc::command::RenderBundleEncoder>,
590    id: crate::cmp::Identifier,
591}
592
593#[derive(Debug)]
594pub struct CoreRenderBundle {
595    context: ContextWgpuCore,
596    id: wgc::id::RenderBundleId,
597}
598
599#[derive(Debug)]
600pub struct CoreQueue {
601    pub(crate) context: ContextWgpuCore,
602    id: wgc::id::QueueId,
603    error_sink: ErrorSink,
604}
605
606#[derive(Debug)]
607pub struct CoreComputePipeline {
608    pub(crate) context: ContextWgpuCore,
609    id: wgc::id::ComputePipelineId,
610    error_sink: ErrorSink,
611}
612
613#[derive(Debug)]
614pub struct CoreRenderPipeline {
615    pub(crate) context: ContextWgpuCore,
616    id: wgc::id::RenderPipelineId,
617    error_sink: ErrorSink,
618}
619
620#[derive(Debug)]
621pub struct CoreComputePass {
622    pub(crate) context: ContextWgpuCore,
623    pass: wgc::command::ComputePass,
624    error_sink: ErrorSink,
625    id: crate::cmp::Identifier,
626}
627
628#[derive(Debug)]
629pub struct CoreRenderPass {
630    pub(crate) context: ContextWgpuCore,
631    pass: wgc::command::RenderPass,
632    error_sink: ErrorSink,
633    id: crate::cmp::Identifier,
634}
635
636#[derive(Debug)]
637pub struct CoreCommandEncoder {
638    pub(crate) context: ContextWgpuCore,
639    id: wgc::id::CommandEncoderId,
640    error_sink: ErrorSink,
641}
642
643#[derive(Debug)]
644pub struct CoreBlas {
645    pub(crate) context: ContextWgpuCore,
646    id: wgc::id::BlasId,
647    error_sink: ErrorSink,
648}
649
650#[derive(Debug)]
651pub struct CoreTlas {
652    pub(crate) context: ContextWgpuCore,
653    id: wgc::id::TlasId,
654    // error_sink: ErrorSink,
655}
656
657#[derive(Debug)]
658pub struct CoreSurfaceOutputDetail {
659    context: ContextWgpuCore,
660    surface_id: wgc::id::SurfaceId,
661    error_sink: ErrorSink,
662    image: Option<crate::SurfaceImage>,
663}
664
665type ErrorSink = Arc<Mutex<ErrorSinkRaw>>;
666
667struct ErrorScope {
668    error: Option<crate::Error>,
669    filter: crate::ErrorFilter,
670}
671
672struct ErrorSinkRaw {
673    scopes: HashMap<thread_id::ThreadId, Vec<ErrorScope>>,
674    uncaptured_handler: Option<Arc<dyn crate::UncapturedErrorHandler>>,
675}
676
677impl ErrorSinkRaw {
678    fn new() -> ErrorSinkRaw {
679        ErrorSinkRaw {
680            scopes: HashMap::new(),
681            uncaptured_handler: None,
682        }
683    }
684
685    /// Deliver the error to
686    ///
687    /// * the innermost error scope, if any, or
688    /// * the uncaptured error handler, if there is one, or
689    /// * [`default_error_handler()`].
690    ///
691    /// If a closure is returned, the caller should call it immediately after dropping the
692    /// [`ErrorSink`] mutex guard. This makes sure that the user callback is not called with
693    /// a wgpu mutex held.
694    #[track_caller]
695    #[must_use]
696    fn handle_error_or_return_handler(&mut self, err: crate::Error) -> Option<impl FnOnce()> {
697        let filter = match err {
698            crate::Error::OutOfMemory { .. } => crate::ErrorFilter::OutOfMemory,
699            crate::Error::Validation { .. } => crate::ErrorFilter::Validation,
700            crate::Error::Internal { .. } => crate::ErrorFilter::Internal,
701        };
702        let thread_id = thread_id::ThreadId::current();
703        let scopes = self.scopes.entry(thread_id).or_default();
704        match scopes.iter_mut().rev().find(|scope| scope.filter == filter) {
705            Some(scope) => {
706                if scope.error.is_none() {
707                    scope.error = Some(err);
708                }
709                None
710            }
711            None => {
712                if let Some(custom_handler) = &self.uncaptured_handler {
713                    let custom_handler = Arc::clone(custom_handler);
714                    Some(move || (custom_handler)(err))
715                } else {
716                    // direct call preserves #[track_caller] where dyn can't
717                    default_error_handler(err)
718                }
719            }
720        }
721    }
722}
723
724impl fmt::Debug for ErrorSinkRaw {
725    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
726        write!(f, "ErrorSink")
727    }
728}
729
730#[track_caller]
731fn default_error_handler(err: crate::Error) -> ! {
732    log::error!("Handling wgpu errors as fatal by default");
733    panic!("wgpu error: {err}\n");
734}
735
736impl From<CreateShaderModuleError> for CompilationInfo {
737    fn from(value: CreateShaderModuleError) -> Self {
738        match value {
739            #[cfg(feature = "wgsl")]
740            CreateShaderModuleError::Parsing(v) => v.into(),
741            #[cfg(feature = "glsl")]
742            CreateShaderModuleError::ParsingGlsl(v) => v.into(),
743            #[cfg(feature = "spirv")]
744            CreateShaderModuleError::ParsingSpirV(v) => v.into(),
745            CreateShaderModuleError::Validation(v) => v.into(),
746            // Device errors are reported through the error sink, and are not compilation errors.
747            // Same goes for native shader module generation errors.
748            CreateShaderModuleError::Device(_) | CreateShaderModuleError::Generation => {
749                CompilationInfo {
750                    messages: Vec::new(),
751                }
752            }
753            // Everything else is an error message without location information.
754            _ => CompilationInfo {
755                messages: vec![CompilationMessage {
756                    message: value.to_string(),
757                    message_type: CompilationMessageType::Error,
758                    location: None,
759                }],
760            },
761        }
762    }
763}
764
765#[derive(Debug)]
766pub struct CoreQueueWriteBuffer {
767    buffer_id: wgc::id::StagingBufferId,
768    mapping: CoreBufferMappedRange,
769}
770
771#[derive(Debug)]
772pub struct CoreBufferMappedRange {
773    ptr: NonNull<u8>,
774    size: usize,
775}
776
777#[cfg(send_sync)]
778unsafe impl Send for CoreBufferMappedRange {}
779#[cfg(send_sync)]
780unsafe impl Sync for CoreBufferMappedRange {}
781
782impl Drop for CoreBufferMappedRange {
783    fn drop(&mut self) {
784        // Intentionally left blank so that `BufferMappedRange` still
785        // implements `Drop`, to match the web backend
786    }
787}
788
789crate::cmp::impl_eq_ord_hash_arc_address!(ContextWgpuCore => .0);
790crate::cmp::impl_eq_ord_hash_proxy!(CoreAdapter => .id);
791crate::cmp::impl_eq_ord_hash_proxy!(CoreDevice => .id);
792crate::cmp::impl_eq_ord_hash_proxy!(CoreQueue => .id);
793crate::cmp::impl_eq_ord_hash_proxy!(CoreShaderModule => .id);
794crate::cmp::impl_eq_ord_hash_proxy!(CoreBindGroupLayout => .id);
795crate::cmp::impl_eq_ord_hash_proxy!(CoreBindGroup => .id);
796crate::cmp::impl_eq_ord_hash_proxy!(CoreTextureView => .id);
797crate::cmp::impl_eq_ord_hash_proxy!(CoreSampler => .id);
798crate::cmp::impl_eq_ord_hash_proxy!(CoreBuffer => .id);
799crate::cmp::impl_eq_ord_hash_proxy!(CoreTexture => .id);
800crate::cmp::impl_eq_ord_hash_proxy!(CoreExternalTexture => .id);
801crate::cmp::impl_eq_ord_hash_proxy!(CoreBlas => .id);
802crate::cmp::impl_eq_ord_hash_proxy!(CoreTlas => .id);
803crate::cmp::impl_eq_ord_hash_proxy!(CoreQuerySet => .id);
804crate::cmp::impl_eq_ord_hash_proxy!(CorePipelineLayout => .id);
805crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderPipeline => .id);
806crate::cmp::impl_eq_ord_hash_proxy!(CoreComputePipeline => .id);
807crate::cmp::impl_eq_ord_hash_proxy!(CorePipelineCache => .id);
808crate::cmp::impl_eq_ord_hash_proxy!(CoreCommandEncoder => .id);
809crate::cmp::impl_eq_ord_hash_proxy!(CoreComputePass => .id);
810crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderPass => .id);
811crate::cmp::impl_eq_ord_hash_proxy!(CoreCommandBuffer => .id);
812crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderBundleEncoder => .id);
813crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderBundle => .id);
814crate::cmp::impl_eq_ord_hash_proxy!(CoreSurface => .id);
815crate::cmp::impl_eq_ord_hash_proxy!(CoreSurfaceOutputDetail => .surface_id);
816crate::cmp::impl_eq_ord_hash_proxy!(CoreQueueWriteBuffer => .mapping.ptr);
817crate::cmp::impl_eq_ord_hash_proxy!(CoreBufferMappedRange => .ptr);
818
819impl dispatch::InstanceInterface for ContextWgpuCore {
820    fn new(desc: wgt::InstanceDescriptor) -> Self
821    where
822        Self: Sized,
823    {
824        Self(Arc::new(wgc::global::Global::new("wgpu", desc, None)))
825    }
826
827    unsafe fn create_surface(
828        &self,
829        target: crate::api::SurfaceTargetUnsafe,
830    ) -> Result<dispatch::DispatchSurface, crate::CreateSurfaceError> {
831        let id = match target {
832            SurfaceTargetUnsafe::RawHandle {
833                raw_display_handle,
834                raw_window_handle,
835            } => unsafe {
836                self.0
837                    .instance_create_surface(raw_display_handle, raw_window_handle, None)
838            },
839
840            #[cfg(all(drm, not(target_os = "netbsd")))]
841            SurfaceTargetUnsafe::Drm {
842                fd,
843                plane,
844                connector_id,
845                width,
846                height,
847                refresh_rate,
848            } => unsafe {
849                self.0.instance_create_surface_from_drm(
850                    fd,
851                    plane,
852                    connector_id,
853                    width,
854                    height,
855                    refresh_rate,
856                    None,
857                )
858            },
859
860            #[cfg(metal)]
861            SurfaceTargetUnsafe::CoreAnimationLayer(layer) => unsafe {
862                self.0.instance_create_surface_metal(layer, None)
863            },
864
865            #[cfg(all(drm, target_os = "netbsd"))]
866            SurfaceTargetUnsafe::Drm { .. } => Err(
867                wgc::instance::CreateSurfaceError::BackendNotEnabled(wgt::Backend::Vulkan),
868            ),
869
870            #[cfg(dx12)]
871            SurfaceTargetUnsafe::CompositionVisual(visual) => unsafe {
872                self.0.instance_create_surface_from_visual(visual, None)
873            },
874
875            #[cfg(dx12)]
876            SurfaceTargetUnsafe::SurfaceHandle(surface_handle) => unsafe {
877                self.0
878                    .instance_create_surface_from_surface_handle(surface_handle, None)
879            },
880
881            #[cfg(dx12)]
882            SurfaceTargetUnsafe::SwapChainPanel(swap_chain_panel) => unsafe {
883                self.0
884                    .instance_create_surface_from_swap_chain_panel(swap_chain_panel, None)
885            },
886        }?;
887
888        Ok(CoreSurface {
889            context: self.clone(),
890            id,
891            configured_device: Mutex::default(),
892            error_sink: Mutex::default(),
893        }
894        .into())
895    }
896
897    fn request_adapter(
898        &self,
899        options: &crate::api::RequestAdapterOptions<'_, '_>,
900    ) -> Pin<Box<dyn dispatch::RequestAdapterFuture>> {
901        let id = self.0.request_adapter(
902            &wgc::instance::RequestAdapterOptions {
903                power_preference: options.power_preference,
904                force_fallback_adapter: options.force_fallback_adapter,
905                compatible_surface: options
906                    .compatible_surface
907                    .map(|surface| surface.inner.as_core().id),
908                apply_limit_buckets: false,
909            },
910            wgt::Backends::all(),
911            None,
912        );
913        let adapter = id.map(|id| {
914            let core = CoreAdapter {
915                context: self.clone(),
916                id,
917            };
918            let generic: dispatch::DispatchAdapter = core.into();
919            generic
920        });
921        Box::pin(ready(adapter))
922    }
923
924    fn poll_all_devices(&self, force_wait: bool) -> bool {
925        match self.0.poll_all_devices(force_wait) {
926            Ok(all_queue_empty) => all_queue_empty,
927            Err(err) => self.handle_error_fatal(err, "Instance::poll_all_devices"),
928        }
929    }
930
931    #[cfg(feature = "wgsl")]
932    fn wgsl_language_features(&self) -> crate::WgslLanguageFeatures {
933        use wgc::naga::front::wgsl::ImplementedLanguageExtension;
934        ImplementedLanguageExtension::all().iter().copied().fold(
935            crate::WgslLanguageFeatures::empty(),
936            |acc, wle| {
937                acc | match wle {
938                    ImplementedLanguageExtension::ReadOnlyAndReadWriteStorageTextures => {
939                        crate::WgslLanguageFeatures::ReadOnlyAndReadWriteStorageTextures
940                    }
941                    ImplementedLanguageExtension::Packed4x8IntegerDotProduct => {
942                        crate::WgslLanguageFeatures::Packed4x8IntegerDotProduct
943                    }
944                    ImplementedLanguageExtension::PointerCompositeAccess => {
945                        crate::WgslLanguageFeatures::PointerCompositeAccess
946                    }
947                }
948            },
949        )
950    }
951
952    fn enumerate_adapters(
953        &self,
954        backends: crate::Backends,
955    ) -> Pin<Box<dyn dispatch::EnumerateAdapterFuture>> {
956        let adapters: Vec<DispatchAdapter> = self
957            .enumerate_adapters(backends)
958            .into_iter()
959            .map(|adapter| {
960                let core = crate::backend::wgpu_core::CoreAdapter {
961                    context: self.clone(),
962                    id: adapter,
963                };
964                core.into()
965            })
966            .collect();
967        Box::pin(ready(adapters))
968    }
969}
970
971impl dispatch::AdapterInterface for CoreAdapter {
972    fn request_device(
973        &self,
974        desc: &crate::DeviceDescriptor<'_>,
975    ) -> Pin<Box<dyn dispatch::RequestDeviceFuture>> {
976        let res = self.context.0.adapter_request_device(
977            self.id,
978            &desc.map_label(|l| l.map(Borrowed)),
979            None,
980            None,
981        );
982        let (device_id, queue_id) = match res {
983            Ok(ids) => ids,
984            Err(err) => {
985                return Box::pin(ready(Err(err.into())));
986            }
987        };
988        let error_sink = Arc::new(Mutex::new(ErrorSinkRaw::new()));
989        let device = CoreDevice {
990            context: self.context.clone(),
991            id: device_id,
992            error_sink: error_sink.clone(),
993            features: desc.required_features,
994        };
995        let queue = CoreQueue {
996            context: self.context.clone(),
997            id: queue_id,
998            error_sink,
999        };
1000        Box::pin(ready(Ok((device.into(), queue.into()))))
1001    }
1002
1003    fn is_surface_supported(&self, surface: &dispatch::DispatchSurface) -> bool {
1004        let surface = surface.as_core();
1005
1006        self.context
1007            .0
1008            .adapter_is_surface_supported(self.id, surface.id)
1009    }
1010
1011    fn features(&self) -> crate::Features {
1012        self.context.0.adapter_features(self.id)
1013    }
1014
1015    fn limits(&self) -> crate::Limits {
1016        self.context.0.adapter_limits(self.id)
1017    }
1018
1019    fn downlevel_capabilities(&self) -> crate::DownlevelCapabilities {
1020        self.context.0.adapter_downlevel_capabilities(self.id)
1021    }
1022
1023    fn get_info(&self) -> crate::AdapterInfo {
1024        self.context.0.adapter_get_info(self.id)
1025    }
1026
1027    fn get_texture_format_features(
1028        &self,
1029        format: crate::TextureFormat,
1030    ) -> crate::TextureFormatFeatures {
1031        self.context
1032            .0
1033            .adapter_get_texture_format_features(self.id, format)
1034    }
1035
1036    fn get_presentation_timestamp(&self) -> crate::PresentationTimestamp {
1037        self.context.0.adapter_get_presentation_timestamp(self.id)
1038    }
1039
1040    fn cooperative_matrix_properties(&self) -> Vec<crate::wgt::CooperativeMatrixProperties> {
1041        self.context
1042            .0
1043            .adapter_cooperative_matrix_properties(self.id)
1044    }
1045}
1046
1047impl Drop for CoreAdapter {
1048    fn drop(&mut self) {
1049        self.context.0.adapter_drop(self.id)
1050    }
1051}
1052
1053impl dispatch::DeviceInterface for CoreDevice {
1054    fn features(&self) -> crate::Features {
1055        self.context.0.device_features(self.id)
1056    }
1057
1058    fn limits(&self) -> crate::Limits {
1059        self.context.0.device_limits(self.id)
1060    }
1061
1062    fn adapter_info(&self) -> crate::AdapterInfo {
1063        self.context.0.device_adapter_info(self.id)
1064    }
1065
1066    // If we have no way to create a shader module, we can't return one, and so most of the function is unreachable.
1067    #[cfg_attr(
1068        not(any(
1069            feature = "spirv",
1070            feature = "glsl",
1071            feature = "wgsl",
1072            feature = "naga-ir"
1073        )),
1074        expect(unused)
1075    )]
1076    fn create_shader_module(
1077        &self,
1078        desc: crate::ShaderModuleDescriptor<'_>,
1079        shader_bound_checks: wgt::ShaderRuntimeChecks,
1080    ) -> dispatch::DispatchShaderModule {
1081        let descriptor = wgc::pipeline::ShaderModuleDescriptor {
1082            label: desc.label.map(Borrowed),
1083            runtime_checks: shader_bound_checks,
1084        };
1085        let source = match desc.source {
1086            #[cfg(feature = "spirv")]
1087            ShaderSource::SpirV(ref spv) => {
1088                // Parse the given shader code and store its representation.
1089                let options = naga::front::spv::Options {
1090                    adjust_coordinate_space: false, // we require NDC_Y_UP feature
1091                    strict_capabilities: true,
1092                    block_ctx_dump_prefix: None,
1093                };
1094                wgc::pipeline::ShaderModuleSource::SpirV(Borrowed(spv), options)
1095            }
1096            #[cfg(feature = "glsl")]
1097            ShaderSource::Glsl {
1098                ref shader,
1099                stage,
1100                defines,
1101            } => {
1102                let options = naga::front::glsl::Options {
1103                    stage,
1104                    defines: defines
1105                        .iter()
1106                        .map(|&(key, value)| (String::from(key), String::from(value)))
1107                        .collect(),
1108                };
1109                wgc::pipeline::ShaderModuleSource::Glsl(Borrowed(shader), options)
1110            }
1111            #[cfg(feature = "wgsl")]
1112            ShaderSource::Wgsl(ref code) => wgc::pipeline::ShaderModuleSource::Wgsl(Borrowed(code)),
1113            #[cfg(feature = "naga-ir")]
1114            ShaderSource::Naga(module) => wgc::pipeline::ShaderModuleSource::Naga(module),
1115            ShaderSource::Dummy(_) => panic!("found `ShaderSource::Dummy`"),
1116        };
1117        let (id, error) =
1118            self.context
1119                .0
1120                .device_create_shader_module(self.id, &descriptor, source, None);
1121        let compilation_info = match error {
1122            Some(cause) => {
1123                self.context.handle_error(
1124                    &self.error_sink,
1125                    cause.clone(),
1126                    desc.label,
1127                    "Device::create_shader_module",
1128                );
1129                CompilationInfo::from(cause)
1130            }
1131            None => CompilationInfo { messages: vec![] },
1132        };
1133
1134        CoreShaderModule {
1135            context: self.context.clone(),
1136            id,
1137            compilation_info,
1138        }
1139        .into()
1140    }
1141
1142    unsafe fn create_shader_module_passthrough(
1143        &self,
1144        desc: &crate::ShaderModuleDescriptorPassthrough<'_>,
1145    ) -> dispatch::DispatchShaderModule {
1146        let desc = desc.map_label(|l| l.map(Cow::from));
1147        let (id, error) = unsafe {
1148            self.context
1149                .0
1150                .device_create_shader_module_passthrough(self.id, &desc, None)
1151        };
1152
1153        let compilation_info = match error {
1154            Some(cause) => {
1155                self.context.handle_error(
1156                    &self.error_sink,
1157                    cause.clone(),
1158                    desc.label.as_deref(),
1159                    "Device::create_shader_module_passthrough",
1160                );
1161                CompilationInfo::from(cause)
1162            }
1163            None => CompilationInfo { messages: vec![] },
1164        };
1165
1166        CoreShaderModule {
1167            context: self.context.clone(),
1168            id,
1169            compilation_info,
1170        }
1171        .into()
1172    }
1173
1174    fn create_bind_group_layout(
1175        &self,
1176        desc: &crate::BindGroupLayoutDescriptor<'_>,
1177    ) -> dispatch::DispatchBindGroupLayout {
1178        let descriptor = wgc::binding_model::BindGroupLayoutDescriptor {
1179            label: desc.label.map(Borrowed),
1180            entries: Borrowed(desc.entries),
1181        };
1182        let (id, error) =
1183            self.context
1184                .0
1185                .device_create_bind_group_layout(self.id, &descriptor, None);
1186        if let Some(cause) = error {
1187            self.context.handle_error(
1188                &self.error_sink,
1189                cause,
1190                desc.label,
1191                "Device::create_bind_group_layout",
1192            );
1193        }
1194        CoreBindGroupLayout {
1195            context: self.context.clone(),
1196            id,
1197        }
1198        .into()
1199    }
1200
1201    fn create_bind_group(
1202        &self,
1203        desc: &crate::BindGroupDescriptor<'_>,
1204    ) -> dispatch::DispatchBindGroup {
1205        use wgc::binding_model as bm;
1206
1207        let mut arrayed_texture_views = Vec::new();
1208        let mut arrayed_samplers = Vec::new();
1209        if self.features.contains(Features::TEXTURE_BINDING_ARRAY) {
1210            // gather all the array view IDs first
1211            for entry in desc.entries.iter() {
1212                if let BindingResource::TextureViewArray(array) = entry.resource {
1213                    arrayed_texture_views.extend(array.iter().map(|view| view.inner.as_core().id));
1214                }
1215                if let BindingResource::SamplerArray(array) = entry.resource {
1216                    arrayed_samplers.extend(array.iter().map(|sampler| sampler.inner.as_core().id));
1217                }
1218            }
1219        }
1220        let mut remaining_arrayed_texture_views = &arrayed_texture_views[..];
1221        let mut remaining_arrayed_samplers = &arrayed_samplers[..];
1222
1223        let mut arrayed_buffer_bindings = Vec::new();
1224        if self.features.contains(Features::BUFFER_BINDING_ARRAY) {
1225            // gather all the buffers first
1226            for entry in desc.entries.iter() {
1227                if let BindingResource::BufferArray(array) = entry.resource {
1228                    arrayed_buffer_bindings.extend(array.iter().map(|binding| bm::BufferBinding {
1229                        buffer: binding.buffer.inner.as_core().id,
1230                        offset: binding.offset,
1231                        size: binding.size.map(wgt::BufferSize::get),
1232                    }));
1233                }
1234            }
1235        }
1236        let mut remaining_arrayed_buffer_bindings = &arrayed_buffer_bindings[..];
1237
1238        let mut arrayed_acceleration_structures = Vec::new();
1239        if self
1240            .features
1241            .contains(Features::ACCELERATION_STRUCTURE_BINDING_ARRAY)
1242        {
1243            // Gather all the TLAS IDs used by TLAS arrays first (same pattern as other arrayed resources).
1244            for entry in desc.entries.iter() {
1245                if let BindingResource::AccelerationStructureArray(array) = entry.resource {
1246                    arrayed_acceleration_structures
1247                        .extend(array.iter().map(|tlas| tlas.inner.as_core().id));
1248                }
1249            }
1250        }
1251        let mut remaining_arrayed_acceleration_structures = &arrayed_acceleration_structures[..];
1252
1253        let entries = desc
1254            .entries
1255            .iter()
1256            .map(|entry| bm::BindGroupEntry {
1257                binding: entry.binding,
1258                resource: match entry.resource {
1259                    BindingResource::Buffer(BufferBinding {
1260                        buffer,
1261                        offset,
1262                        size,
1263                    }) => bm::BindingResource::Buffer(bm::BufferBinding {
1264                        buffer: buffer.inner.as_core().id,
1265                        offset,
1266                        size: size.map(wgt::BufferSize::get),
1267                    }),
1268                    BindingResource::BufferArray(array) => {
1269                        let slice = &remaining_arrayed_buffer_bindings[..array.len()];
1270                        remaining_arrayed_buffer_bindings =
1271                            &remaining_arrayed_buffer_bindings[array.len()..];
1272                        bm::BindingResource::BufferArray(Borrowed(slice))
1273                    }
1274                    BindingResource::Sampler(sampler) => {
1275                        bm::BindingResource::Sampler(sampler.inner.as_core().id)
1276                    }
1277                    BindingResource::SamplerArray(array) => {
1278                        let slice = &remaining_arrayed_samplers[..array.len()];
1279                        remaining_arrayed_samplers = &remaining_arrayed_samplers[array.len()..];
1280                        bm::BindingResource::SamplerArray(Borrowed(slice))
1281                    }
1282                    BindingResource::TextureView(texture_view) => {
1283                        bm::BindingResource::TextureView(texture_view.inner.as_core().id)
1284                    }
1285                    BindingResource::TextureViewArray(array) => {
1286                        let slice = &remaining_arrayed_texture_views[..array.len()];
1287                        remaining_arrayed_texture_views =
1288                            &remaining_arrayed_texture_views[array.len()..];
1289                        bm::BindingResource::TextureViewArray(Borrowed(slice))
1290                    }
1291                    BindingResource::AccelerationStructure(acceleration_structure) => {
1292                        bm::BindingResource::AccelerationStructure(
1293                            acceleration_structure.inner.as_core().id,
1294                        )
1295                    }
1296                    BindingResource::AccelerationStructureArray(array) => {
1297                        let slice = &remaining_arrayed_acceleration_structures[..array.len()];
1298                        remaining_arrayed_acceleration_structures =
1299                            &remaining_arrayed_acceleration_structures[array.len()..];
1300                        bm::BindingResource::AccelerationStructureArray(Borrowed(slice))
1301                    }
1302                    BindingResource::ExternalTexture(external_texture) => {
1303                        bm::BindingResource::ExternalTexture(external_texture.inner.as_core().id)
1304                    }
1305                },
1306            })
1307            .collect::<Vec<_>>();
1308        let descriptor = bm::BindGroupDescriptor {
1309            label: desc.label.as_ref().map(|label| Borrowed(&label[..])),
1310            layout: desc.layout.inner.as_core().id,
1311            entries: Borrowed(&entries),
1312        };
1313
1314        let (id, error) = self
1315            .context
1316            .0
1317            .device_create_bind_group(self.id, &descriptor, None);
1318        if let Some(cause) = error {
1319            self.context.handle_error(
1320                &self.error_sink,
1321                cause,
1322                desc.label,
1323                "Device::create_bind_group",
1324            );
1325        }
1326        CoreBindGroup {
1327            context: self.context.clone(),
1328            id,
1329        }
1330        .into()
1331    }
1332
1333    fn create_pipeline_layout(
1334        &self,
1335        desc: &crate::PipelineLayoutDescriptor<'_>,
1336    ) -> dispatch::DispatchPipelineLayout {
1337        // Limit is always less or equal to hal::MAX_BIND_GROUPS, so this is always right
1338        // Guards following ArrayVec
1339        assert!(
1340            desc.bind_group_layouts.len() <= wgc::MAX_BIND_GROUPS,
1341            "Bind group layout count {} exceeds device bind group limit {}",
1342            desc.bind_group_layouts.len(),
1343            wgc::MAX_BIND_GROUPS
1344        );
1345
1346        let temp_layouts = desc
1347            .bind_group_layouts
1348            .iter()
1349            .map(|bgl| bgl.map(|bgl| bgl.inner.as_core().id))
1350            .collect::<ArrayVec<_, { wgc::MAX_BIND_GROUPS }>>();
1351        let descriptor = wgc::binding_model::PipelineLayoutDescriptor {
1352            label: desc.label.map(Borrowed),
1353            bind_group_layouts: Borrowed(&temp_layouts),
1354            immediate_size: desc.immediate_size,
1355        };
1356
1357        let (id, error) = self
1358            .context
1359            .0
1360            .device_create_pipeline_layout(self.id, &descriptor, None);
1361        if let Some(cause) = error {
1362            self.context.handle_error(
1363                &self.error_sink,
1364                cause,
1365                desc.label,
1366                "Device::create_pipeline_layout",
1367            );
1368        }
1369        CorePipelineLayout {
1370            context: self.context.clone(),
1371            id,
1372        }
1373        .into()
1374    }
1375
1376    fn create_render_pipeline(
1377        &self,
1378        desc: &crate::RenderPipelineDescriptor<'_>,
1379    ) -> dispatch::DispatchRenderPipeline {
1380        use wgc::pipeline as pipe;
1381
1382        let vertex_buffers: ArrayVec<_, { wgc::MAX_VERTEX_BUFFERS }> = desc
1383            .vertex
1384            .buffers
1385            .iter()
1386            .map(|vbuf| {
1387                vbuf.as_ref().map(|vbuf| pipe::VertexBufferLayout {
1388                    array_stride: vbuf.array_stride,
1389                    step_mode: vbuf.step_mode,
1390                    attributes: Borrowed(vbuf.attributes),
1391                })
1392            })
1393            .collect();
1394
1395        let vert_constants = desc
1396            .vertex
1397            .compilation_options
1398            .constants
1399            .iter()
1400            .map(|&(key, value)| (String::from(key), value))
1401            .collect();
1402
1403        let descriptor = pipe::RenderPipelineDescriptor {
1404            label: desc.label.map(Borrowed),
1405            layout: desc.layout.map(|layout| layout.inner.as_core().id),
1406            vertex: pipe::VertexState {
1407                stage: pipe::ProgrammableStageDescriptor {
1408                    module: desc.vertex.module.inner.as_core().id,
1409                    entry_point: desc.vertex.entry_point.map(Borrowed),
1410                    constants: vert_constants,
1411                    zero_initialize_workgroup_memory: desc
1412                        .vertex
1413                        .compilation_options
1414                        .zero_initialize_workgroup_memory,
1415                },
1416                buffers: Borrowed(&vertex_buffers),
1417            },
1418            primitive: desc.primitive,
1419            depth_stencil: desc.depth_stencil.clone(),
1420            multisample: desc.multisample,
1421            fragment: desc.fragment.as_ref().map(|frag| {
1422                let frag_constants = frag
1423                    .compilation_options
1424                    .constants
1425                    .iter()
1426                    .map(|&(key, value)| (String::from(key), value))
1427                    .collect();
1428                pipe::FragmentState {
1429                    stage: pipe::ProgrammableStageDescriptor {
1430                        module: frag.module.inner.as_core().id,
1431                        entry_point: frag.entry_point.map(Borrowed),
1432                        constants: frag_constants,
1433                        zero_initialize_workgroup_memory: frag
1434                            .compilation_options
1435                            .zero_initialize_workgroup_memory,
1436                    },
1437                    targets: Borrowed(frag.targets),
1438                }
1439            }),
1440            multiview_mask: desc.multiview_mask,
1441            cache: desc.cache.map(|cache| cache.inner.as_core().id),
1442        };
1443
1444        let (id, error) = self
1445            .context
1446            .0
1447            .device_create_render_pipeline(self.id, &descriptor, None);
1448        if let Some(cause) = error {
1449            if let wgc::pipeline::CreateRenderPipelineError::Internal { stage, ref error } = cause {
1450                log::error!("Shader translation error for stage {stage:?}: {error}");
1451                log::error!("Please report it to https://github.com/gfx-rs/wgpu");
1452            }
1453            self.context.handle_error(
1454                &self.error_sink,
1455                cause,
1456                desc.label,
1457                "Device::create_render_pipeline",
1458            );
1459        }
1460        CoreRenderPipeline {
1461            context: self.context.clone(),
1462            id,
1463            error_sink: Arc::clone(&self.error_sink),
1464        }
1465        .into()
1466    }
1467
1468    fn create_mesh_pipeline(
1469        &self,
1470        desc: &crate::MeshPipelineDescriptor<'_>,
1471    ) -> dispatch::DispatchRenderPipeline {
1472        use wgc::pipeline as pipe;
1473
1474        let mesh_constants = desc
1475            .mesh
1476            .compilation_options
1477            .constants
1478            .iter()
1479            .map(|&(key, value)| (String::from(key), value))
1480            .collect();
1481        let descriptor = pipe::MeshPipelineDescriptor {
1482            label: desc.label.map(Borrowed),
1483            task: desc.task.as_ref().map(|task| {
1484                let task_constants = task
1485                    .compilation_options
1486                    .constants
1487                    .iter()
1488                    .map(|&(key, value)| (String::from(key), value))
1489                    .collect();
1490                pipe::TaskState {
1491                    stage: pipe::ProgrammableStageDescriptor {
1492                        module: task.module.inner.as_core().id,
1493                        entry_point: task.entry_point.map(Borrowed),
1494                        constants: task_constants,
1495                        zero_initialize_workgroup_memory: desc
1496                            .mesh
1497                            .compilation_options
1498                            .zero_initialize_workgroup_memory,
1499                    },
1500                }
1501            }),
1502            mesh: pipe::MeshState {
1503                stage: pipe::ProgrammableStageDescriptor {
1504                    module: desc.mesh.module.inner.as_core().id,
1505                    entry_point: desc.mesh.entry_point.map(Borrowed),
1506                    constants: mesh_constants,
1507                    zero_initialize_workgroup_memory: desc
1508                        .mesh
1509                        .compilation_options
1510                        .zero_initialize_workgroup_memory,
1511                },
1512            },
1513            layout: desc.layout.map(|layout| layout.inner.as_core().id),
1514            primitive: desc.primitive,
1515            depth_stencil: desc.depth_stencil.clone(),
1516            multisample: desc.multisample,
1517            fragment: desc.fragment.as_ref().map(|frag| {
1518                let frag_constants = frag
1519                    .compilation_options
1520                    .constants
1521                    .iter()
1522                    .map(|&(key, value)| (String::from(key), value))
1523                    .collect();
1524                pipe::FragmentState {
1525                    stage: pipe::ProgrammableStageDescriptor {
1526                        module: frag.module.inner.as_core().id,
1527                        entry_point: frag.entry_point.map(Borrowed),
1528                        constants: frag_constants,
1529                        zero_initialize_workgroup_memory: frag
1530                            .compilation_options
1531                            .zero_initialize_workgroup_memory,
1532                    },
1533                    targets: Borrowed(frag.targets),
1534                }
1535            }),
1536            multiview: desc.multiview,
1537            cache: desc.cache.map(|cache| cache.inner.as_core().id),
1538        };
1539
1540        let (id, error) = self
1541            .context
1542            .0
1543            .device_create_mesh_pipeline(self.id, &descriptor, None);
1544        if let Some(cause) = error {
1545            if let wgc::pipeline::CreateRenderPipelineError::Internal { stage, ref error } = cause {
1546                log::error!("Shader translation error for stage {stage:?}: {error}");
1547                log::error!("Please report it to https://github.com/gfx-rs/wgpu");
1548            }
1549            self.context.handle_error(
1550                &self.error_sink,
1551                cause,
1552                desc.label,
1553                "Device::create_render_pipeline",
1554            );
1555        }
1556        CoreRenderPipeline {
1557            context: self.context.clone(),
1558            id,
1559            error_sink: Arc::clone(&self.error_sink),
1560        }
1561        .into()
1562    }
1563
1564    fn create_compute_pipeline(
1565        &self,
1566        desc: &crate::ComputePipelineDescriptor<'_>,
1567    ) -> dispatch::DispatchComputePipeline {
1568        use wgc::pipeline as pipe;
1569
1570        let constants = desc
1571            .compilation_options
1572            .constants
1573            .iter()
1574            .map(|&(key, value)| (String::from(key), value))
1575            .collect();
1576
1577        let descriptor = pipe::ComputePipelineDescriptor {
1578            label: desc.label.map(Borrowed),
1579            layout: desc.layout.map(|pll| pll.inner.as_core().id),
1580            stage: pipe::ProgrammableStageDescriptor {
1581                module: desc.module.inner.as_core().id,
1582                entry_point: desc.entry_point.map(Borrowed),
1583                constants,
1584                zero_initialize_workgroup_memory: desc
1585                    .compilation_options
1586                    .zero_initialize_workgroup_memory,
1587            },
1588            cache: desc.cache.map(|cache| cache.inner.as_core().id),
1589        };
1590
1591        let (id, error) = self
1592            .context
1593            .0
1594            .device_create_compute_pipeline(self.id, &descriptor, None);
1595        if let Some(cause) = error {
1596            if let wgc::pipeline::CreateComputePipelineError::Internal(ref error) = cause {
1597                log::error!(
1598                    "Shader translation error for stage {:?}: {}",
1599                    wgt::ShaderStages::COMPUTE,
1600                    error
1601                );
1602                log::error!("Please report it to https://github.com/gfx-rs/wgpu");
1603            }
1604            self.context.handle_error(
1605                &self.error_sink,
1606                cause,
1607                desc.label,
1608                "Device::create_compute_pipeline",
1609            );
1610        }
1611        CoreComputePipeline {
1612            context: self.context.clone(),
1613            id,
1614            error_sink: Arc::clone(&self.error_sink),
1615        }
1616        .into()
1617    }
1618
1619    unsafe fn create_pipeline_cache(
1620        &self,
1621        desc: &crate::PipelineCacheDescriptor<'_>,
1622    ) -> dispatch::DispatchPipelineCache {
1623        use wgc::pipeline as pipe;
1624
1625        let descriptor = pipe::PipelineCacheDescriptor {
1626            label: desc.label.map(Borrowed),
1627            data: desc.data.map(Borrowed),
1628            fallback: desc.fallback,
1629        };
1630        let (id, error) = unsafe {
1631            self.context
1632                .0
1633                .device_create_pipeline_cache(self.id, &descriptor, None)
1634        };
1635        if let Some(cause) = error {
1636            self.context.handle_error(
1637                &self.error_sink,
1638                cause,
1639                desc.label,
1640                "Device::device_create_pipeline_cache_init",
1641            );
1642        }
1643        CorePipelineCache {
1644            context: self.context.clone(),
1645            id,
1646        }
1647        .into()
1648    }
1649
1650    fn create_buffer(&self, desc: &crate::BufferDescriptor<'_>) -> dispatch::DispatchBuffer {
1651        let (id, error) = self.context.0.device_create_buffer(
1652            self.id,
1653            &desc.map_label(|l| l.map(Borrowed)),
1654            None,
1655        );
1656        if let Some(cause) = error {
1657            self.context
1658                .handle_error(&self.error_sink, cause, desc.label, "Device::create_buffer");
1659        }
1660
1661        CoreBuffer {
1662            context: self.context.clone(),
1663            id,
1664            error_sink: Arc::clone(&self.error_sink),
1665        }
1666        .into()
1667    }
1668
1669    fn create_texture(&self, desc: &crate::TextureDescriptor<'_>) -> dispatch::DispatchTexture {
1670        let wgt_desc = desc.map_label_and_view_formats(|l| l.map(Borrowed), |v| v.to_vec());
1671        let (id, error) = self
1672            .context
1673            .0
1674            .device_create_texture(self.id, &wgt_desc, None);
1675        if let Some(cause) = error {
1676            self.context.handle_error(
1677                &self.error_sink,
1678                cause,
1679                desc.label,
1680                "Device::create_texture",
1681            );
1682        }
1683
1684        CoreTexture {
1685            context: self.context.clone(),
1686            id,
1687            error_sink: Arc::clone(&self.error_sink),
1688        }
1689        .into()
1690    }
1691
1692    fn create_external_texture(
1693        &self,
1694        desc: &crate::ExternalTextureDescriptor<'_>,
1695        planes: &[&crate::TextureView],
1696    ) -> dispatch::DispatchExternalTexture {
1697        let wgt_desc = desc.map_label(|l| l.map(Borrowed));
1698        let planes = planes
1699            .iter()
1700            .map(|plane| plane.inner.as_core().id)
1701            .collect::<Vec<_>>();
1702        let (id, error) = self
1703            .context
1704            .0
1705            .device_create_external_texture(self.id, &wgt_desc, &planes, None);
1706        if let Some(cause) = error {
1707            self.context.handle_error(
1708                &self.error_sink,
1709                cause,
1710                desc.label,
1711                "Device::create_external_texture",
1712            );
1713        }
1714
1715        CoreExternalTexture {
1716            context: self.context.clone(),
1717            id,
1718        }
1719        .into()
1720    }
1721
1722    fn create_blas(
1723        &self,
1724        desc: &crate::CreateBlasDescriptor<'_>,
1725        sizes: crate::BlasGeometrySizeDescriptors,
1726    ) -> (Option<u64>, dispatch::DispatchBlas) {
1727        let global = &self.context.0;
1728        let (id, handle, error) =
1729            global.device_create_blas(self.id, &desc.map_label(|l| l.map(Borrowed)), sizes, None);
1730        if let Some(cause) = error {
1731            self.context
1732                .handle_error(&self.error_sink, cause, desc.label, "Device::create_blas");
1733        }
1734        (
1735            handle,
1736            CoreBlas {
1737                context: self.context.clone(),
1738                id,
1739                error_sink: Arc::clone(&self.error_sink),
1740            }
1741            .into(),
1742        )
1743    }
1744
1745    fn create_tlas(&self, desc: &crate::CreateTlasDescriptor<'_>) -> dispatch::DispatchTlas {
1746        let global = &self.context.0;
1747        let (id, error) =
1748            global.device_create_tlas(self.id, &desc.map_label(|l| l.map(Borrowed)), None);
1749        if let Some(cause) = error {
1750            self.context
1751                .handle_error(&self.error_sink, cause, desc.label, "Device::create_tlas");
1752        }
1753        CoreTlas {
1754            context: self.context.clone(),
1755            id,
1756            // error_sink: Arc::clone(&self.error_sink),
1757        }
1758        .into()
1759    }
1760
1761    fn create_sampler(&self, desc: &crate::SamplerDescriptor<'_>) -> dispatch::DispatchSampler {
1762        let descriptor = wgc::resource::SamplerDescriptor {
1763            label: desc.label.map(Borrowed),
1764            address_modes: [
1765                desc.address_mode_u,
1766                desc.address_mode_v,
1767                desc.address_mode_w,
1768            ],
1769            mag_filter: desc.mag_filter,
1770            min_filter: desc.min_filter,
1771            mipmap_filter: desc.mipmap_filter,
1772            lod_min_clamp: desc.lod_min_clamp,
1773            lod_max_clamp: desc.lod_max_clamp,
1774            compare: desc.compare,
1775            anisotropy_clamp: desc.anisotropy_clamp,
1776            border_color: desc.border_color,
1777        };
1778
1779        let (id, error) = self
1780            .context
1781            .0
1782            .device_create_sampler(self.id, &descriptor, None);
1783        if let Some(cause) = error {
1784            self.context.handle_error(
1785                &self.error_sink,
1786                cause,
1787                desc.label,
1788                "Device::create_sampler",
1789            );
1790        }
1791        CoreSampler {
1792            context: self.context.clone(),
1793            id,
1794        }
1795        .into()
1796    }
1797
1798    fn create_query_set(&self, desc: &crate::QuerySetDescriptor<'_>) -> dispatch::DispatchQuerySet {
1799        let (id, error) = self.context.0.device_create_query_set(
1800            self.id,
1801            &desc.map_label(|l| l.map(Borrowed)),
1802            None,
1803        );
1804        if let Some(cause) = error {
1805            self.context
1806                .handle_error_nolabel(&self.error_sink, cause, "Device::create_query_set");
1807        }
1808        CoreQuerySet {
1809            context: self.context.clone(),
1810            id,
1811        }
1812        .into()
1813    }
1814
1815    fn create_command_encoder(
1816        &self,
1817        desc: &crate::CommandEncoderDescriptor<'_>,
1818    ) -> dispatch::DispatchCommandEncoder {
1819        let (id, error) = self.context.0.device_create_command_encoder(
1820            self.id,
1821            &desc.map_label(|l| l.map(Borrowed)),
1822            None,
1823        );
1824        if let Some(cause) = error {
1825            self.context.handle_error(
1826                &self.error_sink,
1827                cause,
1828                desc.label,
1829                "Device::create_command_encoder",
1830            );
1831        }
1832
1833        CoreCommandEncoder {
1834            context: self.context.clone(),
1835            id,
1836            error_sink: Arc::clone(&self.error_sink),
1837        }
1838        .into()
1839    }
1840
1841    fn create_render_bundle_encoder(
1842        &self,
1843        desc: &crate::RenderBundleEncoderDescriptor<'_>,
1844    ) -> dispatch::DispatchRenderBundleEncoder {
1845        let descriptor = wgc::command::RenderBundleEncoderDescriptor {
1846            label: desc.label.map(Borrowed),
1847            color_formats: Borrowed(desc.color_formats),
1848            depth_stencil: desc.depth_stencil,
1849            sample_count: desc.sample_count,
1850            multiview: desc.multiview,
1851        };
1852        let (encoder, error) = self
1853            .context
1854            .0
1855            .device_create_render_bundle_encoder(self.id, &descriptor);
1856        if let Some(cause) = error {
1857            self.context.handle_error(
1858                &self.error_sink,
1859                cause,
1860                desc.label,
1861                "Device::create_render_bundle_encoder",
1862            );
1863        }
1864
1865        CoreRenderBundleEncoder {
1866            context: self.context.clone(),
1867            encoder,
1868            id: crate::cmp::Identifier::create(),
1869        }
1870        .into()
1871    }
1872
1873    fn set_device_lost_callback(&self, device_lost_callback: dispatch::BoxDeviceLostCallback) {
1874        self.context
1875            .0
1876            .device_set_device_lost_closure(self.id, device_lost_callback);
1877    }
1878
1879    fn on_uncaptured_error(&self, handler: Arc<dyn crate::UncapturedErrorHandler>) {
1880        let mut error_sink = self.error_sink.lock();
1881        error_sink.uncaptured_handler = Some(handler);
1882    }
1883
1884    fn push_error_scope(&self, filter: crate::ErrorFilter) -> u32 {
1885        let mut error_sink = self.error_sink.lock();
1886        let thread_id = thread_id::ThreadId::current();
1887        let scopes = error_sink.scopes.entry(thread_id).or_default();
1888        let index = scopes
1889            .len()
1890            .try_into()
1891            .expect("Greater than 2^32 nested error scopes");
1892        scopes.push(ErrorScope {
1893            error: None,
1894            filter,
1895        });
1896        index
1897    }
1898
1899    fn pop_error_scope(&self, index: u32) -> Pin<Box<dyn dispatch::PopErrorScopeFuture>> {
1900        let mut error_sink = self.error_sink.lock();
1901
1902        // We go out of our way to avoid panicking while unwinding, because that would abort the process,
1903        // and we are supposed to just drop the error scope on the floor.
1904        let is_panicking = crate::util::is_panicking();
1905        let thread_id = thread_id::ThreadId::current();
1906        let err = "Mismatched pop_error_scope call: no error scope for this thread. Error scopes are thread-local.";
1907        let scopes = match error_sink.scopes.get_mut(&thread_id) {
1908            Some(s) => s,
1909            None => {
1910                if !is_panicking {
1911                    panic!("{err}");
1912                } else {
1913                    return Box::pin(ready(None));
1914                }
1915            }
1916        };
1917        if scopes.is_empty() && !is_panicking {
1918            panic!("{err}");
1919        }
1920        if index as usize != scopes.len() - 1 && !is_panicking {
1921            panic!(
1922                "Mismatched pop_error_scope call: error scopes must be popped in reverse order."
1923            );
1924        }
1925
1926        // It would be more correct in this case to use `remove` here so that when unwinding is occurring
1927        // we would remove the correct error scope, but we don't have such a primitive on the web
1928        // and having consistent behavior here is more important. If you are unwinding and it unwinds
1929        // the guards in the wrong order, it's totally reasonable to have incorrect behavior.
1930        let scope = match scopes.pop() {
1931            Some(s) => s,
1932            None if !is_panicking => unreachable!(),
1933            None => return Box::pin(ready(None)),
1934        };
1935
1936        Box::pin(ready(scope.error))
1937    }
1938
1939    unsafe fn start_graphics_debugger_capture(&self) {
1940        unsafe {
1941            self.context
1942                .0
1943                .device_start_graphics_debugger_capture(self.id)
1944        };
1945    }
1946
1947    unsafe fn stop_graphics_debugger_capture(&self) {
1948        unsafe {
1949            self.context
1950                .0
1951                .device_stop_graphics_debugger_capture(self.id)
1952        };
1953    }
1954
1955    fn poll(&self, poll_type: wgt::PollType<u64>) -> Result<crate::PollStatus, crate::PollError> {
1956        match self.context.0.device_poll(self.id, poll_type) {
1957            Ok(status) => Ok(status),
1958            Err(err) => {
1959                if let Some(poll_error) = err.to_poll_error() {
1960                    return Err(poll_error);
1961                }
1962
1963                self.context.handle_error_fatal(err, "Device::poll")
1964            }
1965        }
1966    }
1967
1968    fn get_internal_counters(&self) -> crate::InternalCounters {
1969        self.context.0.device_get_internal_counters(self.id)
1970    }
1971
1972    fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> {
1973        self.context.0.device_generate_allocator_report(self.id)
1974    }
1975
1976    fn destroy(&self) {
1977        self.context.0.device_destroy(self.id);
1978    }
1979}
1980
1981impl Drop for CoreDevice {
1982    fn drop(&mut self) {
1983        self.context.0.device_drop(self.id)
1984    }
1985}
1986
1987impl dispatch::QueueInterface for CoreQueue {
1988    fn write_buffer(
1989        &self,
1990        buffer: &dispatch::DispatchBuffer,
1991        offset: crate::BufferAddress,
1992        data: &[u8],
1993    ) {
1994        let buffer = buffer.as_core();
1995
1996        match self
1997            .context
1998            .0
1999            .queue_write_buffer(self.id, buffer.id, offset, data)
2000        {
2001            Ok(()) => (),
2002            Err(err) => {
2003                self.context
2004                    .handle_error_nolabel(&self.error_sink, err, "Queue::write_buffer")
2005            }
2006        }
2007    }
2008
2009    fn create_staging_buffer(
2010        &self,
2011        size: crate::BufferSize,
2012    ) -> Option<dispatch::DispatchQueueWriteBuffer> {
2013        match self
2014            .context
2015            .0
2016            .queue_create_staging_buffer(self.id, size, None)
2017        {
2018            Ok((buffer_id, ptr)) => Some(
2019                CoreQueueWriteBuffer {
2020                    buffer_id,
2021                    mapping: CoreBufferMappedRange {
2022                        ptr,
2023                        size: size.get() as usize,
2024                    },
2025                }
2026                .into(),
2027            ),
2028            Err(err) => {
2029                self.context.handle_error_nolabel(
2030                    &self.error_sink,
2031                    err,
2032                    "Queue::write_buffer_with",
2033                );
2034                None
2035            }
2036        }
2037    }
2038
2039    fn validate_write_buffer(
2040        &self,
2041        buffer: &dispatch::DispatchBuffer,
2042        offset: wgt::BufferAddress,
2043        size: wgt::BufferSize,
2044    ) -> Option<()> {
2045        let buffer = buffer.as_core();
2046
2047        match self
2048            .context
2049            .0
2050            .queue_validate_write_buffer(self.id, buffer.id, offset, size)
2051        {
2052            Ok(()) => Some(()),
2053            Err(err) => {
2054                self.context.handle_error_nolabel(
2055                    &self.error_sink,
2056                    err,
2057                    "Queue::write_buffer_with",
2058                );
2059                None
2060            }
2061        }
2062    }
2063
2064    fn write_staging_buffer(
2065        &self,
2066        buffer: &dispatch::DispatchBuffer,
2067        offset: crate::BufferAddress,
2068        staging_buffer: &dispatch::DispatchQueueWriteBuffer,
2069    ) {
2070        let buffer = buffer.as_core();
2071        let staging_buffer = staging_buffer.as_core();
2072
2073        match self.context.0.queue_write_staging_buffer(
2074            self.id,
2075            buffer.id,
2076            offset,
2077            staging_buffer.buffer_id,
2078        ) {
2079            Ok(()) => (),
2080            Err(err) => {
2081                self.context.handle_error_nolabel(
2082                    &self.error_sink,
2083                    err,
2084                    "Queue::write_buffer_with",
2085                );
2086            }
2087        }
2088    }
2089
2090    fn write_texture(
2091        &self,
2092        texture: crate::TexelCopyTextureInfo<'_>,
2093        data: &[u8],
2094        data_layout: crate::TexelCopyBufferLayout,
2095        size: crate::Extent3d,
2096    ) {
2097        match self.context.0.queue_write_texture(
2098            self.id,
2099            &map_texture_copy_view(texture),
2100            data,
2101            &data_layout,
2102            &size,
2103        ) {
2104            Ok(()) => (),
2105            Err(err) => {
2106                self.context
2107                    .handle_error_nolabel(&self.error_sink, err, "Queue::write_texture")
2108            }
2109        }
2110    }
2111
2112    // This method needs to exist if either webgpu or webgl is enabled,
2113    // but we only actually have an implementation if webgl is enabled.
2114    #[cfg(web)]
2115    #[cfg_attr(not(webgl), expect(unused_variables))]
2116    fn copy_external_image_to_texture(
2117        &self,
2118        source: &crate::CopyExternalImageSourceInfo,
2119        dest: crate::CopyExternalImageDestInfo<&crate::api::Texture>,
2120        size: crate::Extent3d,
2121    ) {
2122        #[cfg(webgl)]
2123        match self.context.0.queue_copy_external_image_to_texture(
2124            self.id,
2125            source,
2126            map_texture_tagged_copy_view(dest),
2127            size,
2128        ) {
2129            Ok(()) => (),
2130            Err(err) => self.context.handle_error_nolabel(
2131                &self.error_sink,
2132                err,
2133                "Queue::copy_external_image_to_texture",
2134            ),
2135        }
2136    }
2137
2138    fn submit(
2139        &self,
2140        command_buffers: &mut dyn Iterator<Item = dispatch::DispatchCommandBuffer>,
2141    ) -> u64 {
2142        let temp_command_buffers = command_buffers.collect::<SmallVec<[_; 4]>>();
2143        let command_buffer_ids = temp_command_buffers
2144            .iter()
2145            .map(|cmdbuf| cmdbuf.as_core().id)
2146            .collect::<SmallVec<[_; 4]>>();
2147
2148        let index = match self.context.0.queue_submit(self.id, &command_buffer_ids) {
2149            Ok(index) => index,
2150            Err((index, err)) => {
2151                self.context
2152                    .handle_error_nolabel(&self.error_sink, err, "Queue::submit");
2153                index
2154            }
2155        };
2156
2157        drop(temp_command_buffers);
2158
2159        index
2160    }
2161
2162    fn get_timestamp_period(&self) -> f32 {
2163        self.context.0.queue_get_timestamp_period(self.id)
2164    }
2165
2166    fn on_submitted_work_done(&self, callback: dispatch::BoxSubmittedWorkDoneCallback) {
2167        self.context
2168            .0
2169            .queue_on_submitted_work_done(self.id, callback);
2170    }
2171
2172    fn compact_blas(&self, blas: &dispatch::DispatchBlas) -> (Option<u64>, dispatch::DispatchBlas) {
2173        let (id, handle, error) =
2174            self.context
2175                .0
2176                .queue_compact_blas(self.id, blas.as_core().id, None);
2177
2178        if let Some(cause) = error {
2179            self.context
2180                .handle_error_nolabel(&self.error_sink, cause, "Queue::compact_blas");
2181        }
2182        (
2183            handle,
2184            CoreBlas {
2185                context: self.context.clone(),
2186                id,
2187                error_sink: Arc::clone(&self.error_sink),
2188            }
2189            .into(),
2190        )
2191    }
2192
2193    fn present(&self, detail: &dispatch::DispatchSurfaceOutputDetail) {
2194        let detail = detail.as_core();
2195        match self.context.0.surface_present(detail.surface_id) {
2196            Ok(_status) => (),
2197            Err(err) => {
2198                self.context
2199                    .handle_error_nolabel(&self.error_sink, err, "Queue::present");
2200            }
2201        }
2202    }
2203}
2204
2205impl Drop for CoreQueue {
2206    fn drop(&mut self) {
2207        self.context.0.queue_drop(self.id)
2208    }
2209}
2210
2211impl dispatch::ShaderModuleInterface for CoreShaderModule {
2212    fn get_compilation_info(&self) -> Pin<Box<dyn dispatch::ShaderCompilationInfoFuture>> {
2213        Box::pin(ready(self.compilation_info.clone()))
2214    }
2215}
2216
2217impl Drop for CoreShaderModule {
2218    fn drop(&mut self) {
2219        self.context.0.shader_module_drop(self.id)
2220    }
2221}
2222
2223impl dispatch::BindGroupLayoutInterface for CoreBindGroupLayout {}
2224
2225impl Drop for CoreBindGroupLayout {
2226    fn drop(&mut self) {
2227        self.context.0.bind_group_layout_drop(self.id)
2228    }
2229}
2230
2231impl dispatch::BindGroupInterface for CoreBindGroup {}
2232
2233impl Drop for CoreBindGroup {
2234    fn drop(&mut self) {
2235        self.context.0.bind_group_drop(self.id)
2236    }
2237}
2238
2239impl dispatch::TextureViewInterface for CoreTextureView {}
2240
2241impl Drop for CoreTextureView {
2242    fn drop(&mut self) {
2243        self.context.0.texture_view_drop(self.id);
2244    }
2245}
2246
2247impl dispatch::ExternalTextureInterface for CoreExternalTexture {
2248    fn destroy(&self) {
2249        self.context.0.external_texture_destroy(self.id);
2250    }
2251}
2252
2253impl Drop for CoreExternalTexture {
2254    fn drop(&mut self) {
2255        self.context.0.external_texture_drop(self.id);
2256    }
2257}
2258
2259impl dispatch::SamplerInterface for CoreSampler {}
2260
2261impl Drop for CoreSampler {
2262    fn drop(&mut self) {
2263        self.context.0.sampler_drop(self.id)
2264    }
2265}
2266
2267impl dispatch::BufferInterface for CoreBuffer {
2268    fn map_async(
2269        &self,
2270        mode: crate::MapMode,
2271        range: Range<crate::BufferAddress>,
2272        callback: dispatch::BufferMapCallback,
2273    ) {
2274        let operation = wgc::resource::BufferMapOperation {
2275            host: match mode {
2276                MapMode::Read => wgc::device::HostMap::Read,
2277                MapMode::Write => wgc::device::HostMap::Write,
2278            },
2279            callback: Some(Box::new(|status| {
2280                let res = status.map_err(|_| crate::BufferAsyncError);
2281                callback(res);
2282            })),
2283        };
2284
2285        match self.context.0.buffer_map_async(
2286            self.id,
2287            range.start,
2288            Some(range.end - range.start),
2289            operation,
2290        ) {
2291            Ok(_) => (),
2292            Err(cause) => {
2293                self.context
2294                    .handle_error_nolabel(&self.error_sink, cause, "Buffer::map_async")
2295            }
2296        }
2297    }
2298
2299    fn get_mapped_range(
2300        &self,
2301        sub_range: Range<crate::BufferAddress>,
2302    ) -> Result<dispatch::DispatchBufferMappedRange, crate::MapRangeError> {
2303        let size = sub_range.end - sub_range.start;
2304        self.context
2305            .0
2306            .buffer_get_mapped_range(self.id, sub_range.start, Some(size))
2307            .map(|(ptr, size)| {
2308                CoreBufferMappedRange {
2309                    ptr,
2310                    size: size as usize,
2311                }
2312                .into()
2313            })
2314            .map_err(|err| crate::MapRangeError(self.context.format_error(&err)))
2315    }
2316
2317    fn unmap(&self) {
2318        match self.context.0.buffer_unmap(self.id) {
2319            Ok(()) => (),
2320            Err(cause) => {
2321                self.context
2322                    .handle_error_nolabel(&self.error_sink, cause, "Buffer::buffer_unmap")
2323            }
2324        }
2325    }
2326
2327    fn destroy(&self) {
2328        self.context.0.buffer_destroy(self.id);
2329    }
2330}
2331
2332impl Drop for CoreBuffer {
2333    fn drop(&mut self) {
2334        self.context.0.buffer_drop(self.id)
2335    }
2336}
2337
2338impl dispatch::TextureInterface for CoreTexture {
2339    fn create_view(
2340        &self,
2341        desc: &crate::TextureViewDescriptor<'_>,
2342    ) -> dispatch::DispatchTextureView {
2343        let descriptor = wgc::resource::TextureViewDescriptor {
2344            label: desc.label.map(Borrowed),
2345            format: desc.format,
2346            dimension: desc.dimension,
2347            usage: desc.usage,
2348            range: wgt::ImageSubresourceRange {
2349                aspect: desc.aspect,
2350                base_mip_level: desc.base_mip_level,
2351                mip_level_count: desc.mip_level_count,
2352                base_array_layer: desc.base_array_layer,
2353                array_layer_count: desc.array_layer_count,
2354            },
2355        };
2356        let (id, error) = self
2357            .context
2358            .0
2359            .texture_create_view(self.id, &descriptor, None);
2360        if let Some(cause) = error {
2361            self.context
2362                .handle_error(&self.error_sink, cause, desc.label, "Texture::create_view");
2363        }
2364        CoreTextureView {
2365            context: self.context.clone(),
2366            id,
2367        }
2368        .into()
2369    }
2370
2371    fn destroy(&self) {
2372        self.context.0.texture_destroy(self.id);
2373    }
2374}
2375
2376impl Drop for CoreTexture {
2377    fn drop(&mut self) {
2378        self.context.0.texture_drop(self.id)
2379    }
2380}
2381
2382impl dispatch::BlasInterface for CoreBlas {
2383    fn prepare_compact_async(&self, callback: BlasCompactCallback) {
2384        let callback: Option<wgc::resource::BlasCompactCallback> =
2385            Some(Box::new(|status: BlasPrepareCompactResult| {
2386                let res = status.map_err(|_| crate::BlasAsyncError);
2387                callback(res);
2388            }));
2389
2390        match self.context.0.blas_prepare_compact_async(self.id, callback) {
2391            Ok(_) => (),
2392            Err(cause) => self.context.handle_error_nolabel(
2393                &self.error_sink,
2394                cause,
2395                "Blas::prepare_compact_async",
2396            ),
2397        }
2398    }
2399
2400    fn ready_for_compaction(&self) -> bool {
2401        match self.context.0.ready_for_compaction(self.id) {
2402            Ok(ready) => ready,
2403            Err(cause) => {
2404                self.context.handle_error_nolabel(
2405                    &self.error_sink,
2406                    cause,
2407                    "Blas::ready_for_compaction",
2408                );
2409                // A BLAS is definitely not ready for compaction if it's not valid
2410                false
2411            }
2412        }
2413    }
2414}
2415
2416impl Drop for CoreBlas {
2417    fn drop(&mut self) {
2418        self.context.0.blas_drop(self.id)
2419    }
2420}
2421
2422impl dispatch::TlasInterface for CoreTlas {}
2423
2424impl Drop for CoreTlas {
2425    fn drop(&mut self) {
2426        self.context.0.tlas_drop(self.id)
2427    }
2428}
2429
2430impl dispatch::QuerySetInterface for CoreQuerySet {
2431    fn destroy(&self) {
2432        self.context.0.query_set_destroy(self.id);
2433    }
2434}
2435
2436impl Drop for CoreQuerySet {
2437    fn drop(&mut self) {
2438        self.context.0.query_set_drop(self.id)
2439    }
2440}
2441
2442impl dispatch::PipelineLayoutInterface for CorePipelineLayout {}
2443
2444impl Drop for CorePipelineLayout {
2445    fn drop(&mut self) {
2446        self.context.0.pipeline_layout_drop(self.id)
2447    }
2448}
2449
2450impl dispatch::RenderPipelineInterface for CoreRenderPipeline {
2451    fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout {
2452        let (id, error) = self
2453            .context
2454            .0
2455            .render_pipeline_get_bind_group_layout(self.id, index, None);
2456        if let Some(err) = error {
2457            self.context.handle_error_nolabel(
2458                &self.error_sink,
2459                err,
2460                "RenderPipeline::get_bind_group_layout",
2461            )
2462        }
2463        CoreBindGroupLayout {
2464            context: self.context.clone(),
2465            id,
2466        }
2467        .into()
2468    }
2469}
2470
2471impl Drop for CoreRenderPipeline {
2472    fn drop(&mut self) {
2473        self.context.0.render_pipeline_drop(self.id)
2474    }
2475}
2476
2477impl dispatch::ComputePipelineInterface for CoreComputePipeline {
2478    fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout {
2479        let (id, error) = self
2480            .context
2481            .0
2482            .compute_pipeline_get_bind_group_layout(self.id, index, None);
2483        if let Some(err) = error {
2484            self.context.handle_error_nolabel(
2485                &self.error_sink,
2486                err,
2487                "ComputePipeline::get_bind_group_layout",
2488            )
2489        }
2490        CoreBindGroupLayout {
2491            context: self.context.clone(),
2492            id,
2493        }
2494        .into()
2495    }
2496}
2497
2498impl Drop for CoreComputePipeline {
2499    fn drop(&mut self) {
2500        self.context.0.compute_pipeline_drop(self.id)
2501    }
2502}
2503
2504impl dispatch::PipelineCacheInterface for CorePipelineCache {
2505    fn get_data(&self) -> Option<Vec<u8>> {
2506        self.context.0.pipeline_cache_get_data(self.id)
2507    }
2508}
2509
2510impl Drop for CorePipelineCache {
2511    fn drop(&mut self) {
2512        self.context.0.pipeline_cache_drop(self.id)
2513    }
2514}
2515
2516impl dispatch::CommandEncoderInterface for CoreCommandEncoder {
2517    fn copy_buffer_to_buffer(
2518        &self,
2519        source: &dispatch::DispatchBuffer,
2520        source_offset: crate::BufferAddress,
2521        destination: &dispatch::DispatchBuffer,
2522        destination_offset: crate::BufferAddress,
2523        copy_size: Option<crate::BufferAddress>,
2524    ) {
2525        let source = source.as_core();
2526        let destination = destination.as_core();
2527
2528        if let Err(cause) = self.context.0.command_encoder_copy_buffer_to_buffer(
2529            self.id,
2530            source.id,
2531            source_offset,
2532            destination.id,
2533            destination_offset,
2534            copy_size,
2535        ) {
2536            self.context.handle_error_nolabel(
2537                &self.error_sink,
2538                cause,
2539                "CommandEncoder::copy_buffer_to_buffer",
2540            );
2541        }
2542    }
2543
2544    fn copy_buffer_to_texture(
2545        &self,
2546        source: crate::TexelCopyBufferInfo<'_>,
2547        destination: crate::TexelCopyTextureInfo<'_>,
2548        copy_size: crate::Extent3d,
2549    ) {
2550        if let Err(cause) = self.context.0.command_encoder_copy_buffer_to_texture(
2551            self.id,
2552            &map_buffer_copy_view(source),
2553            &map_texture_copy_view(destination),
2554            &copy_size,
2555        ) {
2556            self.context.handle_error_nolabel(
2557                &self.error_sink,
2558                cause,
2559                "CommandEncoder::copy_buffer_to_texture",
2560            );
2561        }
2562    }
2563
2564    fn copy_texture_to_buffer(
2565        &self,
2566        source: crate::TexelCopyTextureInfo<'_>,
2567        destination: crate::TexelCopyBufferInfo<'_>,
2568        copy_size: crate::Extent3d,
2569    ) {
2570        if let Err(cause) = self.context.0.command_encoder_copy_texture_to_buffer(
2571            self.id,
2572            &map_texture_copy_view(source),
2573            &map_buffer_copy_view(destination),
2574            &copy_size,
2575        ) {
2576            self.context.handle_error_nolabel(
2577                &self.error_sink,
2578                cause,
2579                "CommandEncoder::copy_texture_to_buffer",
2580            );
2581        }
2582    }
2583
2584    fn copy_texture_to_texture(
2585        &self,
2586        source: crate::TexelCopyTextureInfo<'_>,
2587        destination: crate::TexelCopyTextureInfo<'_>,
2588        copy_size: crate::Extent3d,
2589    ) {
2590        if let Err(cause) = self.context.0.command_encoder_copy_texture_to_texture(
2591            self.id,
2592            &map_texture_copy_view(source),
2593            &map_texture_copy_view(destination),
2594            &copy_size,
2595        ) {
2596            self.context.handle_error_nolabel(
2597                &self.error_sink,
2598                cause,
2599                "CommandEncoder::copy_texture_to_texture",
2600            );
2601        }
2602    }
2603
2604    fn begin_compute_pass(
2605        &self,
2606        desc: &crate::ComputePassDescriptor<'_>,
2607    ) -> dispatch::DispatchComputePass {
2608        let timestamp_writes =
2609            desc.timestamp_writes
2610                .as_ref()
2611                .map(|tw| wgc::command::PassTimestampWrites {
2612                    query_set: tw.query_set.inner.as_core().id,
2613                    beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
2614                    end_of_pass_write_index: tw.end_of_pass_write_index,
2615                });
2616
2617        let (pass, err) = self.context.0.command_encoder_begin_compute_pass(
2618            self.id,
2619            &wgc::command::ComputePassDescriptor {
2620                label: desc.label.map(Borrowed),
2621                timestamp_writes,
2622            },
2623        );
2624
2625        if let Some(cause) = err {
2626            self.context.handle_error(
2627                &self.error_sink,
2628                cause,
2629                desc.label,
2630                "CommandEncoder::begin_compute_pass",
2631            );
2632        }
2633
2634        CoreComputePass {
2635            context: self.context.clone(),
2636            pass,
2637            error_sink: self.error_sink.clone(),
2638            id: crate::cmp::Identifier::create(),
2639        }
2640        .into()
2641    }
2642
2643    fn begin_render_pass(
2644        &self,
2645        desc: &crate::RenderPassDescriptor<'_>,
2646    ) -> dispatch::DispatchRenderPass {
2647        let colors = desc
2648            .color_attachments
2649            .iter()
2650            .map(|ca| {
2651                ca.as_ref()
2652                    .map(|at| wgc::command::RenderPassColorAttachment {
2653                        view: at.view.inner.as_core().id,
2654                        depth_slice: at.depth_slice,
2655                        resolve_target: at.resolve_target.map(|view| view.inner.as_core().id),
2656                        load_op: at.ops.load,
2657                        store_op: at.ops.store,
2658                    })
2659            })
2660            .collect::<Vec<_>>();
2661
2662        let depth_stencil = desc.depth_stencil_attachment.as_ref().map(|dsa| {
2663            wgc::command::RenderPassDepthStencilAttachment {
2664                view: dsa.view.inner.as_core().id,
2665                depth: map_pass_channel(dsa.depth_ops.as_ref()),
2666                stencil: map_pass_channel(dsa.stencil_ops.as_ref()),
2667            }
2668        });
2669
2670        let timestamp_writes =
2671            desc.timestamp_writes
2672                .as_ref()
2673                .map(|tw| wgc::command::PassTimestampWrites {
2674                    query_set: tw.query_set.inner.as_core().id,
2675                    beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
2676                    end_of_pass_write_index: tw.end_of_pass_write_index,
2677                });
2678
2679        let (pass, err) = self.context.0.command_encoder_begin_render_pass(
2680            self.id,
2681            &wgc::command::RenderPassDescriptor {
2682                label: desc.label.map(Borrowed),
2683                timestamp_writes,
2684                color_attachments: Borrowed(&colors),
2685                depth_stencil_attachment: depth_stencil,
2686                occlusion_query_set: desc.occlusion_query_set.map(|qs| qs.inner.as_core().id),
2687                multiview_mask: desc.multiview_mask,
2688            },
2689        );
2690
2691        if let Some(cause) = err {
2692            self.context.handle_error(
2693                &self.error_sink,
2694                cause,
2695                desc.label,
2696                "CommandEncoder::begin_render_pass",
2697            );
2698        }
2699
2700        CoreRenderPass {
2701            context: self.context.clone(),
2702            pass,
2703            error_sink: self.error_sink.clone(),
2704            id: crate::cmp::Identifier::create(),
2705        }
2706        .into()
2707    }
2708
2709    fn finish(&mut self) -> dispatch::DispatchCommandBuffer {
2710        let descriptor = wgt::CommandBufferDescriptor::default();
2711        let (id, opt_label_and_error) =
2712            self.context
2713                .0
2714                .command_encoder_finish(self.id, &descriptor, None);
2715        if let Some((label, cause)) = opt_label_and_error {
2716            self.context
2717                .handle_error(&self.error_sink, cause, Some(&label), "a CommandEncoder");
2718        }
2719        CoreCommandBuffer {
2720            context: self.context.clone(),
2721            id,
2722        }
2723        .into()
2724    }
2725
2726    fn clear_texture(
2727        &self,
2728        texture: &dispatch::DispatchTexture,
2729        subresource_range: &crate::ImageSubresourceRange,
2730    ) {
2731        let texture = texture.as_core();
2732
2733        if let Err(cause) =
2734            self.context
2735                .0
2736                .command_encoder_clear_texture(self.id, texture.id, subresource_range)
2737        {
2738            self.context.handle_error_nolabel(
2739                &self.error_sink,
2740                cause,
2741                "CommandEncoder::clear_texture",
2742            );
2743        }
2744    }
2745
2746    fn clear_buffer(
2747        &self,
2748        buffer: &dispatch::DispatchBuffer,
2749        offset: crate::BufferAddress,
2750        size: Option<crate::BufferAddress>,
2751    ) {
2752        let buffer = buffer.as_core();
2753
2754        if let Err(cause) = self
2755            .context
2756            .0
2757            .command_encoder_clear_buffer(self.id, buffer.id, offset, size)
2758        {
2759            self.context.handle_error_nolabel(
2760                &self.error_sink,
2761                cause,
2762                "CommandEncoder::fill_buffer",
2763            );
2764        }
2765    }
2766
2767    fn insert_debug_marker(&self, label: &str) {
2768        if let Err(cause) = self
2769            .context
2770            .0
2771            .command_encoder_insert_debug_marker(self.id, label)
2772        {
2773            self.context.handle_error_nolabel(
2774                &self.error_sink,
2775                cause,
2776                "CommandEncoder::insert_debug_marker",
2777            );
2778        }
2779    }
2780
2781    fn push_debug_group(&self, label: &str) {
2782        if let Err(cause) = self
2783            .context
2784            .0
2785            .command_encoder_push_debug_group(self.id, label)
2786        {
2787            self.context.handle_error_nolabel(
2788                &self.error_sink,
2789                cause,
2790                "CommandEncoder::push_debug_group",
2791            );
2792        }
2793    }
2794
2795    fn pop_debug_group(&self) {
2796        if let Err(cause) = self.context.0.command_encoder_pop_debug_group(self.id) {
2797            self.context.handle_error_nolabel(
2798                &self.error_sink,
2799                cause,
2800                "CommandEncoder::pop_debug_group",
2801            );
2802        }
2803    }
2804
2805    fn write_timestamp(&self, query_set: &dispatch::DispatchQuerySet, query_index: u32) {
2806        let query_set = query_set.as_core();
2807
2808        if let Err(cause) =
2809            self.context
2810                .0
2811                .command_encoder_write_timestamp(self.id, query_set.id, query_index)
2812        {
2813            self.context.handle_error_nolabel(
2814                &self.error_sink,
2815                cause,
2816                "CommandEncoder::write_timestamp",
2817            );
2818        }
2819    }
2820
2821    fn resolve_query_set(
2822        &self,
2823        query_set: &dispatch::DispatchQuerySet,
2824        first_query: u32,
2825        query_count: u32,
2826        destination: &dispatch::DispatchBuffer,
2827        destination_offset: crate::BufferAddress,
2828    ) {
2829        let query_set = query_set.as_core();
2830        let destination = destination.as_core();
2831
2832        if let Err(cause) = self.context.0.command_encoder_resolve_query_set(
2833            self.id,
2834            query_set.id,
2835            first_query,
2836            query_count,
2837            destination.id,
2838            destination_offset,
2839        ) {
2840            self.context.handle_error_nolabel(
2841                &self.error_sink,
2842                cause,
2843                "CommandEncoder::resolve_query_set",
2844            );
2845        }
2846    }
2847
2848    fn mark_acceleration_structures_built<'a>(
2849        &self,
2850        blas: &mut dyn Iterator<Item = &'a Blas>,
2851        tlas: &mut dyn Iterator<Item = &'a Tlas>,
2852    ) {
2853        let blas = blas
2854            .map(|b| b.inner.as_core().id)
2855            .collect::<SmallVec<[_; 4]>>();
2856        let tlas = tlas
2857            .map(|t| t.inner.as_core().id)
2858            .collect::<SmallVec<[_; 4]>>();
2859        if let Err(cause) = self
2860            .context
2861            .0
2862            .command_encoder_mark_acceleration_structures_built(self.id, &blas, &tlas)
2863        {
2864            self.context.handle_error_nolabel(
2865                &self.error_sink,
2866                cause,
2867                "CommandEncoder::build_acceleration_structures_unsafe_tlas",
2868            );
2869        }
2870    }
2871
2872    fn build_acceleration_structures<'a>(
2873        &self,
2874        blas: &mut dyn Iterator<Item = &'a crate::BlasBuildEntry<'a>>,
2875        tlas: &mut dyn Iterator<Item = &'a crate::Tlas>,
2876    ) {
2877        let blas = blas.map(|e: &crate::BlasBuildEntry<'_>| {
2878            let geometries = match e.geometry {
2879                crate::BlasGeometries::TriangleGeometries(ref triangle_geometries) => {
2880                    let iter = triangle_geometries.iter().map(|tg| {
2881                        wgc::ray_tracing::BlasTriangleGeometry {
2882                            vertex_buffer: tg.vertex_buffer.inner.as_core().id,
2883                            index_buffer: tg.index_buffer.map(|buf| buf.inner.as_core().id),
2884                            transform_buffer: tg.transform_buffer.map(|buf| buf.inner.as_core().id),
2885                            size: tg.size,
2886                            transform_buffer_offset: tg.transform_buffer_offset,
2887                            first_vertex: tg.first_vertex,
2888                            vertex_stride: tg.vertex_stride,
2889                            first_index: tg.first_index,
2890                        }
2891                    });
2892                    wgc::ray_tracing::BlasGeometries::TriangleGeometries(Box::new(iter))
2893                }
2894                crate::BlasGeometries::AabbGeometries(ref aabb_geometries) => {
2895                    let iter =
2896                        aabb_geometries
2897                            .iter()
2898                            .map(|ag| wgc::ray_tracing::BlasAabbGeometry {
2899                                aabb_buffer: ag.aabb_buffer.inner.as_core().id,
2900                                stride: ag.stride,
2901                                size: ag.size,
2902                                primitive_offset: ag.primitive_offset,
2903                            });
2904                    wgc::ray_tracing::BlasGeometries::AabbGeometries(Box::new(iter))
2905                }
2906            };
2907            wgc::ray_tracing::BlasBuildEntry {
2908                blas_id: e.blas.inner.as_core().id,
2909                geometries,
2910            }
2911        });
2912
2913        let tlas = tlas.into_iter().map(|e| {
2914            let instances = e
2915                .instances
2916                .iter()
2917                .map(|instance: &Option<crate::TlasInstance>| {
2918                    instance
2919                        .as_ref()
2920                        .map(|instance| wgc::ray_tracing::TlasInstance {
2921                            blas_id: instance.blas.as_core().id,
2922                            transform: &instance.transform,
2923                            custom_data: instance.custom_data,
2924                            mask: instance.mask,
2925                        })
2926                });
2927            wgc::ray_tracing::TlasPackage {
2928                tlas_id: e.inner.as_core().id,
2929                instances: Box::new(instances),
2930                lowest_unmodified: e.lowest_unmodified,
2931            }
2932        });
2933
2934        if let Err(cause) = self
2935            .context
2936            .0
2937            .command_encoder_build_acceleration_structures(self.id, blas, tlas)
2938        {
2939            self.context.handle_error_nolabel(
2940                &self.error_sink,
2941                cause,
2942                "CommandEncoder::build_acceleration_structures_unsafe_tlas",
2943            );
2944        }
2945    }
2946
2947    fn transition_resources<'a>(
2948        &mut self,
2949        buffer_transitions: &mut dyn Iterator<
2950            Item = wgt::BufferTransition<&'a dispatch::DispatchBuffer>,
2951        >,
2952        texture_transitions: &mut dyn Iterator<
2953            Item = wgt::TextureTransition<&'a dispatch::DispatchTexture>,
2954        >,
2955    ) {
2956        let result = self.context.0.command_encoder_transition_resources(
2957            self.id,
2958            buffer_transitions.map(|t| wgt::BufferTransition {
2959                buffer: t.buffer.as_core().id,
2960                state: t.state,
2961            }),
2962            texture_transitions.map(|t| wgt::TextureTransition {
2963                texture: t.texture.as_core().id,
2964                selector: t.selector.clone(),
2965                state: t.state,
2966            }),
2967        );
2968
2969        if let Err(cause) = result {
2970            self.context.handle_error_nolabel(
2971                &self.error_sink,
2972                cause,
2973                "CommandEncoder::transition_resources",
2974            );
2975        }
2976    }
2977}
2978
2979impl Drop for CoreCommandEncoder {
2980    fn drop(&mut self) {
2981        self.context.0.command_encoder_drop(self.id)
2982    }
2983}
2984
2985impl dispatch::CommandBufferInterface for CoreCommandBuffer {}
2986
2987impl Drop for CoreCommandBuffer {
2988    fn drop(&mut self) {
2989        self.context.0.command_buffer_drop(self.id)
2990    }
2991}
2992
2993impl dispatch::ComputePassInterface for CoreComputePass {
2994    fn set_pipeline(&mut self, pipeline: &dispatch::DispatchComputePipeline) {
2995        let pipeline = pipeline.as_core();
2996
2997        if let Err(cause) = self
2998            .context
2999            .0
3000            .compute_pass_set_pipeline(&mut self.pass, pipeline.id)
3001        {
3002            self.context.handle_error(
3003                &self.error_sink,
3004                cause,
3005                self.pass.label(),
3006                "ComputePass::set_pipeline",
3007            );
3008        }
3009    }
3010
3011    fn set_bind_group(
3012        &mut self,
3013        index: u32,
3014        bind_group: Option<&dispatch::DispatchBindGroup>,
3015        offsets: &[crate::DynamicOffset],
3016    ) {
3017        let bg = bind_group.map(|bg| bg.as_core().id);
3018
3019        if let Err(cause) =
3020            self.context
3021                .0
3022                .compute_pass_set_bind_group(&mut self.pass, index, bg, offsets)
3023        {
3024            self.context.handle_error(
3025                &self.error_sink,
3026                cause,
3027                self.pass.label(),
3028                "ComputePass::set_bind_group",
3029            );
3030        }
3031    }
3032
3033    fn set_immediates(&mut self, offset: u32, data: &[u8]) {
3034        if let Err(cause) = self
3035            .context
3036            .0
3037            .compute_pass_set_immediates(&mut self.pass, offset, data)
3038        {
3039            self.context.handle_error(
3040                &self.error_sink,
3041                cause,
3042                self.pass.label(),
3043                "ComputePass::set_immediates",
3044            );
3045        }
3046    }
3047
3048    fn insert_debug_marker(&mut self, label: &str) {
3049        if let Err(cause) =
3050            self.context
3051                .0
3052                .compute_pass_insert_debug_marker(&mut self.pass, label, 0)
3053        {
3054            self.context.handle_error(
3055                &self.error_sink,
3056                cause,
3057                self.pass.label(),
3058                "ComputePass::insert_debug_marker",
3059            );
3060        }
3061    }
3062
3063    fn push_debug_group(&mut self, group_label: &str) {
3064        if let Err(cause) =
3065            self.context
3066                .0
3067                .compute_pass_push_debug_group(&mut self.pass, group_label, 0)
3068        {
3069            self.context.handle_error(
3070                &self.error_sink,
3071                cause,
3072                self.pass.label(),
3073                "ComputePass::push_debug_group",
3074            );
3075        }
3076    }
3077
3078    fn pop_debug_group(&mut self) {
3079        if let Err(cause) = self.context.0.compute_pass_pop_debug_group(&mut self.pass) {
3080            self.context.handle_error(
3081                &self.error_sink,
3082                cause,
3083                self.pass.label(),
3084                "ComputePass::pop_debug_group",
3085            );
3086        }
3087    }
3088
3089    fn write_timestamp(&mut self, query_set: &dispatch::DispatchQuerySet, query_index: u32) {
3090        let query_set = query_set.as_core();
3091
3092        if let Err(cause) =
3093            self.context
3094                .0
3095                .compute_pass_write_timestamp(&mut self.pass, query_set.id, query_index)
3096        {
3097            self.context.handle_error(
3098                &self.error_sink,
3099                cause,
3100                self.pass.label(),
3101                "ComputePass::write_timestamp",
3102            );
3103        }
3104    }
3105
3106    fn begin_pipeline_statistics_query(
3107        &mut self,
3108        query_set: &dispatch::DispatchQuerySet,
3109        query_index: u32,
3110    ) {
3111        let query_set = query_set.as_core();
3112
3113        if let Err(cause) = self.context.0.compute_pass_begin_pipeline_statistics_query(
3114            &mut self.pass,
3115            query_set.id,
3116            query_index,
3117        ) {
3118            self.context.handle_error(
3119                &self.error_sink,
3120                cause,
3121                self.pass.label(),
3122                "ComputePass::begin_pipeline_statistics_query",
3123            );
3124        }
3125    }
3126
3127    fn end_pipeline_statistics_query(&mut self) {
3128        if let Err(cause) = self
3129            .context
3130            .0
3131            .compute_pass_end_pipeline_statistics_query(&mut self.pass)
3132        {
3133            self.context.handle_error(
3134                &self.error_sink,
3135                cause,
3136                self.pass.label(),
3137                "ComputePass::end_pipeline_statistics_query",
3138            );
3139        }
3140    }
3141
3142    fn dispatch_workgroups(&mut self, x: u32, y: u32, z: u32) {
3143        if let Err(cause) = self
3144            .context
3145            .0
3146            .compute_pass_dispatch_workgroups(&mut self.pass, x, y, z)
3147        {
3148            self.context.handle_error(
3149                &self.error_sink,
3150                cause,
3151                self.pass.label(),
3152                "ComputePass::dispatch_workgroups",
3153            );
3154        }
3155    }
3156
3157    fn dispatch_workgroups_indirect(
3158        &mut self,
3159        indirect_buffer: &dispatch::DispatchBuffer,
3160        indirect_offset: crate::BufferAddress,
3161    ) {
3162        let indirect_buffer = indirect_buffer.as_core();
3163
3164        if let Err(cause) = self.context.0.compute_pass_dispatch_workgroups_indirect(
3165            &mut self.pass,
3166            indirect_buffer.id,
3167            indirect_offset,
3168        ) {
3169            self.context.handle_error(
3170                &self.error_sink,
3171                cause,
3172                self.pass.label(),
3173                "ComputePass::dispatch_workgroups_indirect",
3174            );
3175        }
3176    }
3177
3178    fn transition_resources<'a>(
3179        &mut self,
3180        buffer_transitions: &mut dyn Iterator<
3181            Item = wgt::BufferTransition<&'a dispatch::DispatchBuffer>,
3182        >,
3183        texture_transitions: &mut dyn Iterator<
3184            Item = wgt::TextureTransition<&'a dispatch::DispatchTextureView>,
3185        >,
3186    ) {
3187        let result = self.context.0.compute_pass_transition_resources(
3188            &mut self.pass,
3189            buffer_transitions.map(|t| wgt::BufferTransition {
3190                buffer: t.buffer.as_core().id,
3191                state: t.state,
3192            }),
3193            texture_transitions.map(|t| wgt::TextureTransition {
3194                texture: t.texture.as_core().id,
3195                selector: t.selector.clone(),
3196                state: t.state,
3197            }),
3198        );
3199
3200        if let Err(cause) = result {
3201            self.context.handle_error(
3202                &self.error_sink,
3203                cause,
3204                self.pass.label(),
3205                "ComputePass::transition_resources",
3206            );
3207        }
3208    }
3209}
3210
3211impl Drop for CoreComputePass {
3212    fn drop(&mut self) {
3213        if let Err(cause) = self.context.0.compute_pass_end(&mut self.pass) {
3214            self.context.handle_error(
3215                &self.error_sink,
3216                cause,
3217                self.pass.label(),
3218                "ComputePass::end",
3219            );
3220        }
3221    }
3222}
3223
3224impl dispatch::RenderPassInterface for CoreRenderPass {
3225    fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRenderPipeline) {
3226        let pipeline = pipeline.as_core();
3227
3228        if let Err(cause) = self
3229            .context
3230            .0
3231            .render_pass_set_pipeline(&mut self.pass, pipeline.id)
3232        {
3233            self.context.handle_error(
3234                &self.error_sink,
3235                cause,
3236                self.pass.label(),
3237                "RenderPass::set_pipeline",
3238            );
3239        }
3240    }
3241
3242    fn set_bind_group(
3243        &mut self,
3244        index: u32,
3245        bind_group: Option<&dispatch::DispatchBindGroup>,
3246        offsets: &[crate::DynamicOffset],
3247    ) {
3248        let bg = bind_group.map(|bg| bg.as_core().id);
3249
3250        if let Err(cause) =
3251            self.context
3252                .0
3253                .render_pass_set_bind_group(&mut self.pass, index, bg, offsets)
3254        {
3255            self.context.handle_error(
3256                &self.error_sink,
3257                cause,
3258                self.pass.label(),
3259                "RenderPass::set_bind_group",
3260            );
3261        }
3262    }
3263
3264    fn set_index_buffer(
3265        &mut self,
3266        buffer: &dispatch::DispatchBuffer,
3267        index_format: crate::IndexFormat,
3268        offset: crate::BufferAddress,
3269        size: Option<crate::BufferSize>,
3270    ) {
3271        let buffer = buffer.as_core();
3272
3273        if let Err(cause) = self.context.0.render_pass_set_index_buffer(
3274            &mut self.pass,
3275            buffer.id,
3276            index_format,
3277            offset,
3278            size,
3279        ) {
3280            self.context.handle_error(
3281                &self.error_sink,
3282                cause,
3283                self.pass.label(),
3284                "RenderPass::set_index_buffer",
3285            );
3286        }
3287    }
3288
3289    fn set_vertex_buffer(
3290        &mut self,
3291        slot: u32,
3292        buffer: Option<&dispatch::DispatchBuffer>,
3293        offset: crate::BufferAddress,
3294        size: Option<crate::BufferSize>,
3295    ) {
3296        let buffer = buffer.map(|buffer| buffer.as_core().id);
3297
3298        if let Err(cause) =
3299            self.context
3300                .0
3301                .render_pass_set_vertex_buffer(&mut self.pass, slot, buffer, offset, size)
3302        {
3303            self.context.handle_error(
3304                &self.error_sink,
3305                cause,
3306                self.pass.label(),
3307                "RenderPass::set_vertex_buffer",
3308            );
3309        }
3310    }
3311
3312    fn set_immediates(&mut self, offset: u32, data: &[u8]) {
3313        if let Err(cause) = self
3314            .context
3315            .0
3316            .render_pass_set_immediates(&mut self.pass, offset, data)
3317        {
3318            self.context.handle_error(
3319                &self.error_sink,
3320                cause,
3321                self.pass.label(),
3322                "RenderPass::set_immediates",
3323            );
3324        }
3325    }
3326
3327    fn set_blend_constant(&mut self, color: crate::Color) {
3328        if let Err(cause) = self
3329            .context
3330            .0
3331            .render_pass_set_blend_constant(&mut self.pass, color)
3332        {
3333            self.context.handle_error(
3334                &self.error_sink,
3335                cause,
3336                self.pass.label(),
3337                "RenderPass::set_blend_constant",
3338            );
3339        }
3340    }
3341
3342    fn set_scissor_rect(&mut self, x: u32, y: u32, width: u32, height: u32) {
3343        if let Err(cause) =
3344            self.context
3345                .0
3346                .render_pass_set_scissor_rect(&mut self.pass, x, y, width, height)
3347        {
3348            self.context.handle_error(
3349                &self.error_sink,
3350                cause,
3351                self.pass.label(),
3352                "RenderPass::set_scissor_rect",
3353            );
3354        }
3355    }
3356
3357    fn set_viewport(
3358        &mut self,
3359        x: f32,
3360        y: f32,
3361        width: f32,
3362        height: f32,
3363        min_depth: f32,
3364        max_depth: f32,
3365    ) {
3366        if let Err(cause) = self.context.0.render_pass_set_viewport(
3367            &mut self.pass,
3368            x,
3369            y,
3370            width,
3371            height,
3372            min_depth,
3373            max_depth,
3374        ) {
3375            self.context.handle_error(
3376                &self.error_sink,
3377                cause,
3378                self.pass.label(),
3379                "RenderPass::set_viewport",
3380            );
3381        }
3382    }
3383
3384    fn set_stencil_reference(&mut self, reference: u32) {
3385        if let Err(cause) = self
3386            .context
3387            .0
3388            .render_pass_set_stencil_reference(&mut self.pass, reference)
3389        {
3390            self.context.handle_error(
3391                &self.error_sink,
3392                cause,
3393                self.pass.label(),
3394                "RenderPass::set_stencil_reference",
3395            );
3396        }
3397    }
3398
3399    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
3400        if let Err(cause) = self.context.0.render_pass_draw(
3401            &mut self.pass,
3402            vertices.end - vertices.start,
3403            instances.end - instances.start,
3404            vertices.start,
3405            instances.start,
3406        ) {
3407            self.context.handle_error(
3408                &self.error_sink,
3409                cause,
3410                self.pass.label(),
3411                "RenderPass::draw",
3412            );
3413        }
3414    }
3415
3416    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
3417        if let Err(cause) = self.context.0.render_pass_draw_indexed(
3418            &mut self.pass,
3419            indices.end - indices.start,
3420            instances.end - instances.start,
3421            indices.start,
3422            base_vertex,
3423            instances.start,
3424        ) {
3425            self.context.handle_error(
3426                &self.error_sink,
3427                cause,
3428                self.pass.label(),
3429                "RenderPass::draw_indexed",
3430            );
3431        }
3432    }
3433
3434    fn draw_mesh_tasks(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32) {
3435        if let Err(cause) = self.context.0.render_pass_draw_mesh_tasks(
3436            &mut self.pass,
3437            group_count_x,
3438            group_count_y,
3439            group_count_z,
3440        ) {
3441            self.context.handle_error(
3442                &self.error_sink,
3443                cause,
3444                self.pass.label(),
3445                "RenderPass::draw_mesh_tasks",
3446            );
3447        }
3448    }
3449
3450    fn draw_indirect(
3451        &mut self,
3452        indirect_buffer: &dispatch::DispatchBuffer,
3453        indirect_offset: crate::BufferAddress,
3454    ) {
3455        let indirect_buffer = indirect_buffer.as_core();
3456
3457        if let Err(cause) = self.context.0.render_pass_draw_indirect(
3458            &mut self.pass,
3459            indirect_buffer.id,
3460            indirect_offset,
3461        ) {
3462            self.context.handle_error(
3463                &self.error_sink,
3464                cause,
3465                self.pass.label(),
3466                "RenderPass::draw_indirect",
3467            );
3468        }
3469    }
3470
3471    fn draw_indexed_indirect(
3472        &mut self,
3473        indirect_buffer: &dispatch::DispatchBuffer,
3474        indirect_offset: crate::BufferAddress,
3475    ) {
3476        let indirect_buffer = indirect_buffer.as_core();
3477
3478        if let Err(cause) = self.context.0.render_pass_draw_indexed_indirect(
3479            &mut self.pass,
3480            indirect_buffer.id,
3481            indirect_offset,
3482        ) {
3483            self.context.handle_error(
3484                &self.error_sink,
3485                cause,
3486                self.pass.label(),
3487                "RenderPass::draw_indexed_indirect",
3488            );
3489        }
3490    }
3491
3492    fn draw_mesh_tasks_indirect(
3493        &mut self,
3494        indirect_buffer: &dispatch::DispatchBuffer,
3495        indirect_offset: crate::BufferAddress,
3496    ) {
3497        let indirect_buffer = indirect_buffer.as_core();
3498
3499        if let Err(cause) = self.context.0.render_pass_draw_mesh_tasks_indirect(
3500            &mut self.pass,
3501            indirect_buffer.id,
3502            indirect_offset,
3503        ) {
3504            self.context.handle_error(
3505                &self.error_sink,
3506                cause,
3507                self.pass.label(),
3508                "RenderPass::draw_mesh_tasks_indirect",
3509            );
3510        }
3511    }
3512
3513    fn multi_draw_indirect(
3514        &mut self,
3515        indirect_buffer: &dispatch::DispatchBuffer,
3516        indirect_offset: crate::BufferAddress,
3517        count: u32,
3518    ) {
3519        let indirect_buffer = indirect_buffer.as_core();
3520
3521        if let Err(cause) = self.context.0.render_pass_multi_draw_indirect(
3522            &mut self.pass,
3523            indirect_buffer.id,
3524            indirect_offset,
3525            count,
3526        ) {
3527            self.context.handle_error(
3528                &self.error_sink,
3529                cause,
3530                self.pass.label(),
3531                "RenderPass::multi_draw_indirect",
3532            );
3533        }
3534    }
3535
3536    fn multi_draw_indexed_indirect(
3537        &mut self,
3538        indirect_buffer: &dispatch::DispatchBuffer,
3539        indirect_offset: crate::BufferAddress,
3540        count: u32,
3541    ) {
3542        let indirect_buffer = indirect_buffer.as_core();
3543
3544        if let Err(cause) = self.context.0.render_pass_multi_draw_indexed_indirect(
3545            &mut self.pass,
3546            indirect_buffer.id,
3547            indirect_offset,
3548            count,
3549        ) {
3550            self.context.handle_error(
3551                &self.error_sink,
3552                cause,
3553                self.pass.label(),
3554                "RenderPass::multi_draw_indexed_indirect",
3555            );
3556        }
3557    }
3558
3559    fn multi_draw_mesh_tasks_indirect(
3560        &mut self,
3561        indirect_buffer: &dispatch::DispatchBuffer,
3562        indirect_offset: crate::BufferAddress,
3563        count: u32,
3564    ) {
3565        let indirect_buffer = indirect_buffer.as_core();
3566
3567        if let Err(cause) = self.context.0.render_pass_multi_draw_mesh_tasks_indirect(
3568            &mut self.pass,
3569            indirect_buffer.id,
3570            indirect_offset,
3571            count,
3572        ) {
3573            self.context.handle_error(
3574                &self.error_sink,
3575                cause,
3576                self.pass.label(),
3577                "RenderPass::multi_draw_mesh_tasks_indirect",
3578            );
3579        }
3580    }
3581
3582    fn multi_draw_indirect_count(
3583        &mut self,
3584        indirect_buffer: &dispatch::DispatchBuffer,
3585        indirect_offset: crate::BufferAddress,
3586        count_buffer: &dispatch::DispatchBuffer,
3587        count_buffer_offset: crate::BufferAddress,
3588        max_count: u32,
3589    ) {
3590        let indirect_buffer = indirect_buffer.as_core();
3591        let count_buffer = count_buffer.as_core();
3592
3593        if let Err(cause) = self.context.0.render_pass_multi_draw_indirect_count(
3594            &mut self.pass,
3595            indirect_buffer.id,
3596            indirect_offset,
3597            count_buffer.id,
3598            count_buffer_offset,
3599            max_count,
3600        ) {
3601            self.context.handle_error(
3602                &self.error_sink,
3603                cause,
3604                self.pass.label(),
3605                "RenderPass::multi_draw_indirect_count",
3606            );
3607        }
3608    }
3609
3610    fn multi_draw_indexed_indirect_count(
3611        &mut self,
3612        indirect_buffer: &dispatch::DispatchBuffer,
3613        indirect_offset: crate::BufferAddress,
3614        count_buffer: &dispatch::DispatchBuffer,
3615        count_buffer_offset: crate::BufferAddress,
3616        max_count: u32,
3617    ) {
3618        let indirect_buffer = indirect_buffer.as_core();
3619        let count_buffer = count_buffer.as_core();
3620
3621        if let Err(cause) = self
3622            .context
3623            .0
3624            .render_pass_multi_draw_indexed_indirect_count(
3625                &mut self.pass,
3626                indirect_buffer.id,
3627                indirect_offset,
3628                count_buffer.id,
3629                count_buffer_offset,
3630                max_count,
3631            )
3632        {
3633            self.context.handle_error(
3634                &self.error_sink,
3635                cause,
3636                self.pass.label(),
3637                "RenderPass::multi_draw_indexed_indirect_count",
3638            );
3639        }
3640    }
3641
3642    fn multi_draw_mesh_tasks_indirect_count(
3643        &mut self,
3644        indirect_buffer: &dispatch::DispatchBuffer,
3645        indirect_offset: crate::BufferAddress,
3646        count_buffer: &dispatch::DispatchBuffer,
3647        count_buffer_offset: crate::BufferAddress,
3648        max_count: u32,
3649    ) {
3650        let indirect_buffer = indirect_buffer.as_core();
3651        let count_buffer = count_buffer.as_core();
3652
3653        if let Err(cause) = self
3654            .context
3655            .0
3656            .render_pass_multi_draw_mesh_tasks_indirect_count(
3657                &mut self.pass,
3658                indirect_buffer.id,
3659                indirect_offset,
3660                count_buffer.id,
3661                count_buffer_offset,
3662                max_count,
3663            )
3664        {
3665            self.context.handle_error(
3666                &self.error_sink,
3667                cause,
3668                self.pass.label(),
3669                "RenderPass::multi_draw_mesh_tasks_indirect_count",
3670            );
3671        }
3672    }
3673
3674    fn insert_debug_marker(&mut self, label: &str) {
3675        if let Err(cause) = self
3676            .context
3677            .0
3678            .render_pass_insert_debug_marker(&mut self.pass, label, 0)
3679        {
3680            self.context.handle_error(
3681                &self.error_sink,
3682                cause,
3683                self.pass.label(),
3684                "RenderPass::insert_debug_marker",
3685            );
3686        }
3687    }
3688
3689    fn push_debug_group(&mut self, group_label: &str) {
3690        if let Err(cause) =
3691            self.context
3692                .0
3693                .render_pass_push_debug_group(&mut self.pass, group_label, 0)
3694        {
3695            self.context.handle_error(
3696                &self.error_sink,
3697                cause,
3698                self.pass.label(),
3699                "RenderPass::push_debug_group",
3700            );
3701        }
3702    }
3703
3704    fn pop_debug_group(&mut self) {
3705        if let Err(cause) = self.context.0.render_pass_pop_debug_group(&mut self.pass) {
3706            self.context.handle_error(
3707                &self.error_sink,
3708                cause,
3709                self.pass.label(),
3710                "RenderPass::pop_debug_group",
3711            );
3712        }
3713    }
3714
3715    fn write_timestamp(&mut self, query_set: &dispatch::DispatchQuerySet, query_index: u32) {
3716        let query_set = query_set.as_core();
3717
3718        if let Err(cause) =
3719            self.context
3720                .0
3721                .render_pass_write_timestamp(&mut self.pass, query_set.id, query_index)
3722        {
3723            self.context.handle_error(
3724                &self.error_sink,
3725                cause,
3726                self.pass.label(),
3727                "RenderPass::write_timestamp",
3728            );
3729        }
3730    }
3731
3732    fn begin_occlusion_query(&mut self, query_index: u32) {
3733        if let Err(cause) = self
3734            .context
3735            .0
3736            .render_pass_begin_occlusion_query(&mut self.pass, query_index)
3737        {
3738            self.context.handle_error(
3739                &self.error_sink,
3740                cause,
3741                self.pass.label(),
3742                "RenderPass::begin_occlusion_query",
3743            );
3744        }
3745    }
3746
3747    fn end_occlusion_query(&mut self) {
3748        if let Err(cause) = self
3749            .context
3750            .0
3751            .render_pass_end_occlusion_query(&mut self.pass)
3752        {
3753            self.context.handle_error(
3754                &self.error_sink,
3755                cause,
3756                self.pass.label(),
3757                "RenderPass::end_occlusion_query",
3758            );
3759        }
3760    }
3761
3762    fn begin_pipeline_statistics_query(
3763        &mut self,
3764        query_set: &dispatch::DispatchQuerySet,
3765        query_index: u32,
3766    ) {
3767        let query_set = query_set.as_core();
3768
3769        if let Err(cause) = self.context.0.render_pass_begin_pipeline_statistics_query(
3770            &mut self.pass,
3771            query_set.id,
3772            query_index,
3773        ) {
3774            self.context.handle_error(
3775                &self.error_sink,
3776                cause,
3777                self.pass.label(),
3778                "RenderPass::begin_pipeline_statistics_query",
3779            );
3780        }
3781    }
3782
3783    fn end_pipeline_statistics_query(&mut self) {
3784        if let Err(cause) = self
3785            .context
3786            .0
3787            .render_pass_end_pipeline_statistics_query(&mut self.pass)
3788        {
3789            self.context.handle_error(
3790                &self.error_sink,
3791                cause,
3792                self.pass.label(),
3793                "RenderPass::end_pipeline_statistics_query",
3794            );
3795        }
3796    }
3797
3798    fn execute_bundles(
3799        &mut self,
3800        render_bundles: &mut dyn Iterator<Item = &dispatch::DispatchRenderBundle>,
3801    ) {
3802        let temp_render_bundles = render_bundles
3803            .map(|rb| rb.as_core().id)
3804            .collect::<SmallVec<[_; 4]>>();
3805        if let Err(cause) = self
3806            .context
3807            .0
3808            .render_pass_execute_bundles(&mut self.pass, &temp_render_bundles)
3809        {
3810            self.context.handle_error(
3811                &self.error_sink,
3812                cause,
3813                self.pass.label(),
3814                "RenderPass::execute_bundles",
3815            );
3816        }
3817    }
3818}
3819
3820impl Drop for CoreRenderPass {
3821    fn drop(&mut self) {
3822        if let Err(cause) = self.context.0.render_pass_end(&mut self.pass) {
3823            self.context.handle_error(
3824                &self.error_sink,
3825                cause,
3826                self.pass.label(),
3827                "RenderPass::end",
3828            );
3829        }
3830    }
3831}
3832
3833impl dispatch::RenderBundleEncoderInterface for CoreRenderBundleEncoder {
3834    fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRenderPipeline) {
3835        let pipeline = pipeline.as_core();
3836
3837        self.context
3838            .0
3839            .render_bundle_encoder_set_pipeline(&mut self.encoder, pipeline.id)
3840            .expect("RenderBundleEncoder should not have ended")
3841    }
3842
3843    fn set_bind_group(
3844        &mut self,
3845        index: u32,
3846        bind_group: Option<&dispatch::DispatchBindGroup>,
3847        offsets: &[crate::DynamicOffset],
3848    ) {
3849        let bg = bind_group.map(|bg| bg.as_core().id);
3850
3851        self.context
3852            .0
3853            .render_bundle_encoder_set_bind_group(&mut self.encoder, index, bg, offsets)
3854            .expect("RenderBundleEncoder should not have ended");
3855    }
3856
3857    fn set_index_buffer(
3858        &mut self,
3859        buffer: &dispatch::DispatchBuffer,
3860        index_format: crate::IndexFormat,
3861        offset: crate::BufferAddress,
3862        size: Option<crate::BufferSize>,
3863    ) {
3864        let buffer = buffer.as_core();
3865
3866        self.context
3867            .0
3868            .render_bundle_encoder_set_index_buffer(
3869                &mut self.encoder,
3870                buffer.id,
3871                index_format,
3872                offset,
3873                size,
3874            )
3875            .expect("RenderBundleEncoder should not have ended");
3876    }
3877
3878    fn set_vertex_buffer(
3879        &mut self,
3880        slot: u32,
3881        buffer: Option<&dispatch::DispatchBuffer>,
3882        offset: crate::BufferAddress,
3883        size: Option<crate::BufferSize>,
3884    ) {
3885        let buffer = buffer.map(|buffer| buffer.as_core().id);
3886
3887        self.context
3888            .0
3889            .render_bundle_encoder_set_vertex_buffer(&mut self.encoder, slot, buffer, offset, size)
3890            .expect("RenderBundleEncoder should not have ended");
3891    }
3892
3893    fn set_immediates(&mut self, offset: u32, data: &[u8]) {
3894        self.context
3895            .0
3896            .render_bundle_encoder_set_immediates(&mut self.encoder, offset, data)
3897            .expect("RenderBundleEncoder should not have ended");
3898    }
3899
3900    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
3901        self.context
3902            .0
3903            .render_bundle_encoder_draw(
3904                &mut self.encoder,
3905                vertices.end - vertices.start,
3906                instances.end - instances.start,
3907                vertices.start,
3908                instances.start,
3909            )
3910            .expect("RenderBundleEncoder should not have ended");
3911    }
3912
3913    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
3914        self.context
3915            .0
3916            .render_bundle_encoder_draw_indexed(
3917                &mut self.encoder,
3918                indices.end - indices.start,
3919                instances.end - instances.start,
3920                indices.start,
3921                base_vertex,
3922                instances.start,
3923            )
3924            .expect("RenderBundleEncoder should not have ended");
3925    }
3926
3927    fn draw_indirect(
3928        &mut self,
3929        indirect_buffer: &dispatch::DispatchBuffer,
3930        indirect_offset: crate::BufferAddress,
3931    ) {
3932        let indirect_buffer = indirect_buffer.as_core();
3933
3934        self.context
3935            .0
3936            .render_bundle_encoder_draw_indirect(
3937                &mut self.encoder,
3938                indirect_buffer.id,
3939                indirect_offset,
3940            )
3941            .expect("RenderBundleEncoder should not have ended");
3942    }
3943
3944    fn draw_indexed_indirect(
3945        &mut self,
3946        indirect_buffer: &dispatch::DispatchBuffer,
3947        indirect_offset: crate::BufferAddress,
3948    ) {
3949        let indirect_buffer = indirect_buffer.as_core();
3950
3951        self.context
3952            .0
3953            .render_bundle_encoder_draw_indexed_indirect(
3954                &mut self.encoder,
3955                indirect_buffer.id,
3956                indirect_offset,
3957            )
3958            .expect("RenderBundleEncoder should not have ended");
3959    }
3960
3961    fn finish(mut self, desc: &crate::RenderBundleDescriptor<'_>) -> dispatch::DispatchRenderBundle
3962    where
3963        Self: Sized,
3964    {
3965        let (id, error) = self.context.0.render_bundle_encoder_finish(
3966            &mut self.encoder,
3967            &desc.map_label(|l| l.map(Borrowed)),
3968            None,
3969        );
3970        if let Some(err) = error {
3971            self.context
3972                .handle_error_fatal(err, "RenderBundleEncoder::finish");
3973        }
3974        CoreRenderBundle {
3975            context: self.context.clone(),
3976            id,
3977        }
3978        .into()
3979    }
3980
3981    #[cfg(custom)]
3982    fn finish_boxed(
3983        self: Box<Self>,
3984        desc: &crate::RenderBundleDescriptor<'_>,
3985    ) -> dispatch::DispatchRenderBundle {
3986        (*self).finish(desc)
3987    }
3988}
3989
3990impl dispatch::RenderBundleInterface for CoreRenderBundle {}
3991
3992impl Drop for CoreRenderBundle {
3993    fn drop(&mut self) {
3994        self.context.0.render_bundle_drop(self.id)
3995    }
3996}
3997
3998impl dispatch::SurfaceInterface for CoreSurface {
3999    fn get_capabilities(&self, adapter: &dispatch::DispatchAdapter) -> wgt::SurfaceCapabilities {
4000        let adapter = adapter.as_core();
4001
4002        self.context
4003            .0
4004            .surface_get_capabilities(self.id, adapter.id)
4005            .unwrap_or_default()
4006    }
4007
4008    fn display_hdr_info(&self, adapter: &dispatch::DispatchAdapter) -> wgt::DisplayHdrInfo {
4009        let adapter = adapter.as_core();
4010
4011        self.context.0.surface_display_hdr_info(self.id, adapter.id)
4012    }
4013
4014    fn keep_presented_images(&self, keep: bool) {
4015        self.context.0.surface_keep_presented_images(self.id, keep);
4016    }
4017
4018    fn configure(&self, device: &dispatch::DispatchDevice, config: &crate::SurfaceConfiguration) {
4019        let device = device.as_core();
4020
4021        let error = self.context.0.surface_configure(self.id, device.id, config);
4022        if let Some(e) = error {
4023            self.context
4024                .handle_error_nolabel(&device.error_sink, e, "Surface::configure");
4025        } else {
4026            *self.configured_device.lock() = Some(device.id);
4027            *self.error_sink.lock() = Some(device.error_sink.clone());
4028        }
4029    }
4030
4031    fn get_current_texture(
4032        &self,
4033    ) -> (
4034        Option<dispatch::DispatchTexture>,
4035        crate::SurfaceStatus,
4036        dispatch::DispatchSurfaceOutputDetail,
4037    ) {
4038        let error_sink = if let Some(error_sink) = self.error_sink.lock().as_ref() {
4039            error_sink.clone()
4040        } else {
4041            Arc::new(Mutex::new(ErrorSinkRaw::new()))
4042        };
4043
4044        let output_detail = |image: Option<wgc::present::SurfaceImage>| {
4045            CoreSurfaceOutputDetail {
4046                context: self.context.clone(),
4047                surface_id: self.id,
4048                error_sink: error_sink.clone(),
4049                image: image.map(|image| crate::SurfaceImage {
4050                    index: image.index,
4051                    kept: image.kept,
4052                }),
4053            }
4054            .into()
4055        };
4056
4057        match self.context.0.surface_get_current_texture(self.id, None) {
4058            Ok(wgc::present::SurfaceOutput {
4059                status,
4060                texture: texture_id,
4061                image,
4062            }) => {
4063                let output_detail = output_detail(image);
4064                let data = texture_id
4065                    .map(|id| CoreTexture {
4066                        context: self.context.clone(),
4067                        id,
4068                        error_sink,
4069                    })
4070                    .map(Into::into);
4071
4072                (data, status, output_detail)
4073            }
4074            Err(err) => {
4075                let output_detail = output_detail(None);
4076                let error_sink = self.error_sink.lock();
4077                match error_sink.as_ref() {
4078                    Some(error_sink) => {
4079                        self.context.handle_error_nolabel(
4080                            error_sink,
4081                            err,
4082                            "Surface::get_current_texture_view",
4083                        );
4084                        (None, crate::SurfaceStatus::Validation, output_detail)
4085                    }
4086                    None => self
4087                        .context
4088                        .handle_error_fatal(err, "Surface::get_current_texture_view"),
4089                }
4090            }
4091        }
4092    }
4093}
4094
4095impl Drop for CoreSurface {
4096    fn drop(&mut self) {
4097        self.context.0.surface_drop(self.id)
4098    }
4099}
4100
4101impl dispatch::SurfaceOutputDetailInterface for CoreSurfaceOutputDetail {
4102    fn texture_discard(&self) {
4103        match self.context.0.surface_texture_discard(self.surface_id) {
4104            Ok(_status) => (),
4105            Err(err) => {
4106                self.context
4107                    .handle_error_nolabel(&self.error_sink, err, "Surface::discard_texture")
4108            }
4109        }
4110    }
4111
4112    fn texture_release(&self) {
4113        match self.context.0.surface_texture_release(self.surface_id) {
4114            Ok(_status) => (),
4115            Err(err) => {
4116                self.context
4117                    .handle_error_nolabel(&self.error_sink, err, "Surface::release_texture")
4118            }
4119        }
4120    }
4121
4122    fn image(&self) -> Option<crate::SurfaceImage> {
4123        self.image
4124    }
4125}
4126impl Drop for CoreSurfaceOutputDetail {
4127    fn drop(&mut self) {
4128        // Discard gets called by the api struct
4129
4130        // no-op
4131    }
4132}
4133
4134impl dispatch::QueueWriteBufferInterface for CoreQueueWriteBuffer {
4135    #[inline]
4136    fn len(&self) -> usize {
4137        self.mapping.len()
4138    }
4139
4140    #[inline]
4141    unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]> {
4142        unsafe { self.mapping.write_slice() }
4143    }
4144}
4145impl Drop for CoreQueueWriteBuffer {
4146    fn drop(&mut self) {
4147        // The api struct calls queue.write_staging_buffer
4148
4149        // no-op
4150    }
4151}
4152
4153impl dispatch::BufferMappedRangeInterface for CoreBufferMappedRange {
4154    #[inline]
4155    fn len(&self) -> usize {
4156        self.size
4157    }
4158
4159    #[inline]
4160    unsafe fn read_slice(&self) -> &[u8] {
4161        unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.size) }
4162    }
4163
4164    #[inline]
4165    unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]> {
4166        unsafe { WriteOnly::new(NonNull::slice_from_raw_parts(self.ptr, self.size)) }
4167    }
4168
4169    #[cfg(webgpu)]
4170    fn as_uint8array(&self) -> &js_sys::Uint8Array {
4171        panic!("Only available on WebGPU")
4172    }
4173}