Skip to main content

script_webgpu/
gpudevice.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::borrow::Cow;
6use std::cell::Cell;
7use std::rc::Rc;
8
9use dom_struct::dom_struct;
10use js::context::{JSContext, NoGC};
11use js::jsapi::{HandleObject, Heap, JSObject};
12use js::realm::CurrentRealm;
13use jstraceable_derive::JSTraceable;
14use log::warn;
15use malloc_size_of_derive::MallocSizeOf;
16use script_bindings::callback::CallbackContainer;
17use script_bindings::cell::DomRefCell;
18use script_bindings::codegen::GenericBindings::EventBinding::EventInit;
19use script_bindings::codegen::GenericBindings::EventHandlerBinding::EventHandlerNonNull;
20use script_bindings::codegen::GenericBindings::WebGPUBinding::{
21    GPUBindGroupDescriptor, GPUBindGroupLayoutDescriptor, GPUBufferDescriptor,
22    GPUCommandEncoderDescriptor, GPUComputePipelineDescriptor, GPUDeviceLostReason,
23    GPUDeviceMethods, GPUDeviceWrap, GPUErrorFilter, GPUExternalTextureDescriptor,
24    GPUPipelineErrorReason, GPUPipelineLayoutDescriptor, GPUQuerySetDescriptor,
25    GPURenderBundleEncoderDescriptor, GPURenderPipelineDescriptor, GPUSamplerDescriptor,
26    GPUShaderModuleDescriptor, GPUTextureDescriptor, GPUTextureFormat, GPUUncapturedErrorEventInit,
27    GPUVertexStepMode,
28};
29use script_bindings::codegen::GenericUnionTypes::GPUPipelineLayoutOrGPUAutoLayoutMode;
30use script_bindings::conversions::DerivedFrom;
31use script_bindings::error::Error;
32use script_bindings::inheritance::Castable;
33use script_bindings::interfaces::{
34    HeapTracedPromiseHelpers, PromiseHelpers, StackRootPromiseHelpers,
35};
36use script_bindings::reflector::{
37    DomGlobalGeneric, reflect_weak_referenceable_dom_object_with_wrap,
38};
39use script_bindings::routed_promise::RoutedPromiseListener;
40use script_bindings::trace::RootedTraceableBox;
41use script_bindings::traits::{DomEventTrait, DomExceptionTrait};
42use script_bindings::{DomTypes, cformat, task};
43use stylo_atoms::atom;
44use webgpu_traits::{
45    BlendState, ColorTargetState, ColorWrites, DepthBiasState, DepthStencilState, Features,
46    FragmentState, Limits, MultisampleState, PopError, RenderPipelineDescriptor, StencilFaceState,
47    StencilState, TextureFormat, VertexAttribute, VertexBufferLayout, VertexState, VertexStepMode,
48    WebGPU, WebGPUComputePipeline, WebGPUComputePipelineResponse, WebGPUDevice,
49    WebGPUPoppedErrorScopeResponse, WebGPUQueue, WebGPURenderPipeline,
50    WebGPURenderPipelineResponse, WebGPURequest,
51};
52
53use super::gpudevicelostinfo::GPUDeviceLostInfo;
54use crate::PipelineLayout;
55use crate::dom::bindings::error::Fallible;
56use crate::dom::bindings::refcounted::Trusted;
57use crate::dom::bindings::root::{Dom, DomRoot};
58use crate::dom::bindings::str::USVString;
59use crate::gpuadapter::GPUAdapter;
60use crate::gpuadapterinfo::GPUAdapterInfo;
61use crate::gpubindgroup::GPUBindGroup;
62use crate::gpubindgrouplayout::GPUBindGroupLayout;
63use crate::gpubuffer::GPUBuffer;
64use crate::gpucommandencoder::GPUCommandEncoder;
65use crate::gpucomputepipeline::GPUComputePipeline;
66use crate::gpuconvert::WebGPUConvert;
67use crate::gpuerror::{AsWebGpu, GPUError};
68use crate::gpuexternaltexture::GPUExternalTexture;
69use crate::gpupipelineerror::GPUPipelineError;
70use crate::gpupipelinelayout::GPUPipelineLayout;
71use crate::gpuqueryset::GPUQuerySet;
72use crate::gpurenderbundleencoder::GPURenderBundleEncoder;
73use crate::gpurenderpipeline::GPURenderPipeline;
74use crate::gpusampler::GPUSampler;
75use crate::gpushadermodule::GPUShaderModule;
76use crate::gpusupportedfeatures::GPUSupportedFeatures;
77use crate::gpusupportedlimits::GPUSupportedLimits;
78use crate::gputexture::GPUTexture;
79use crate::gpuuncapturederrorevent::GPUUncapturedErrorEvent;
80use crate::traits::{
81    Equivalence, EventTargetTrait, WebGPUGlobalTrait, WebGPUPromise, WebGPUPromiseCallbackTrait,
82};
83
84macro_rules! event_handler(
85    ($event_type: ident, $getter: ident, $setter: ident) => (
86        define_event_handler!(
87            script_bindings::codegen::GenericBindings::EventHandlerBinding::EventHandlerNonNull<D>,
88            $event_type,
89            $getter,
90            $setter,
91            set_event_handler_common
92        );
93    )
94);
95
96/// These are used to generate a event handler which has no special case.
97macro_rules! define_event_handler(
98    ($handler: ty, $event_type: ident, $getter: ident, $setter: ident, $setter_fn: ident) => (
99        fn $getter(&self, cx: &mut js::context::JSContext) -> Option<script_bindings::callback::RootedCallback<$handler>> {
100            use crate::dom::bindings::inheritance::Castable;
101            let eventtarget = self.upcast::<D::EventTarget>();
102            D::EventTarget::get_event_handler_common(eventtarget, cx, stringify!($event_type))
103        }
104
105        fn $setter(&self, cx: &mut js::context::JSContext, listener: Option<script_bindings::callback::RootedCallback<$handler>>) {
106            use crate::dom::bindings::inheritance::Castable;
107            let eventtarget = self.upcast::<D::EventTarget>();
108            eventtarget.$setter_fn(cx, stringify!($event_type), listener)
109        }
110    )
111);
112
113#[derive(JSTraceable, MallocSizeOf)]
114struct DroppableGPUDevice {
115    #[no_trace]
116    channel: WebGPU,
117    #[no_trace]
118    device: WebGPUDevice,
119}
120
121impl Drop for DroppableGPUDevice {
122    fn drop(&mut self) {
123        if let Err(e) = self
124            .channel
125            .0
126            .send(WebGPURequest::DropDevice(self.device.0))
127        {
128            warn!("Failed to send DropDevice ({:?}) ({})", self.device.0, e);
129        }
130    }
131}
132
133#[dom_struct]
134pub struct GPUDevice<D: DomTypes> {
135    eventtarget: D::EventTarget,
136    adapter: Dom<GPUAdapter<D>>,
137    #[ignore_malloc_size_of = "mozjs"]
138    extensions: Heap<*mut JSObject>,
139    features: Dom<GPUSupportedFeatures<D>>,
140    limits: Dom<GPUSupportedLimits<D>>,
141    adapter_info: Dom<GPUAdapterInfo<D>>,
142    label: DomRefCell<USVString>,
143    default_queue: Dom<D::GPUQueue>,
144    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-lost>
145    lost_promise: DomRefCell<<D::Promise as PromiseHelpers<D>>::HeapTraced>,
146    valid: Cell<bool>,
147    droppable: DroppableGPUDevice,
148}
149
150impl<D> GPUDevice<D>
151where
152    D: Equivalence,
153    EventHandlerNonNull<D>: CallbackContainer,
154{
155    #[expect(clippy::too_many_arguments)]
156    fn new_inherited(
157        channel: WebGPU,
158        adapter: &GPUAdapter<D>,
159        features: &GPUSupportedFeatures<D>,
160        limits: &GPUSupportedLimits<D>,
161        adapter_info: &GPUAdapterInfo<D>,
162        device: WebGPUDevice,
163        queue: &D::GPUQueue,
164        label: String,
165        lost_promise: &<D::Promise as PromiseHelpers<D>>::StackRoot,
166    ) -> Self {
167        Self {
168            eventtarget: D::EventTarget::new_inherited(),
169            adapter: Dom::from_ref(adapter),
170            extensions: Heap::default(),
171            features: Dom::from_ref(features),
172            limits: Dom::from_ref(limits),
173            adapter_info: Dom::from_ref(adapter_info),
174            label: DomRefCell::new(USVString::from(label)),
175            default_queue: Dom::from_ref(queue),
176            lost_promise: DomRefCell::new(lost_promise.to_traced()),
177            valid: Cell::new(true),
178            droppable: DroppableGPUDevice { channel, device },
179        }
180    }
181
182    #[allow(clippy::too_many_arguments)]
183    pub fn new(
184        cx: &mut JSContext,
185        global: &D::GlobalScope,
186        channel: WebGPU,
187        adapter: &GPUAdapter<D>,
188        extensions: HandleObject,
189        features: Features,
190        limits: Limits,
191        device: WebGPUDevice,
192        queue: WebGPUQueue,
193        label: String,
194    ) -> DomRoot<Self> {
195        let queue = D::GPUQueue::new(cx, global, channel.clone(), queue);
196        let limits = GPUSupportedLimits::new(cx, global, limits);
197        let features = GPUSupportedFeatures::Constructor(cx, global, None, features).unwrap();
198        let adapter_info = GPUAdapterInfo::clone_from(cx, global, &adapter.info());
199        let lost_promise = D::Promise::new(cx, global);
200        let device = reflect_weak_referenceable_dom_object_with_wrap::<D, _, _>(
201            cx,
202            Rc::new(GPUDevice::new_inherited(
203                channel,
204                adapter,
205                &features,
206                &limits,
207                &adapter_info,
208                device,
209                &queue,
210                label,
211                &lost_promise,
212            )),
213            global,
214            GPUDeviceWrap::<D>,
215        );
216        queue.set_device(&device);
217        device.extensions.set(*extensions);
218        device
219    }
220}
221
222impl<D> GPUDevice<D>
223where
224    D: Equivalence,
225    <D::Promise as PromiseHelpers<D>>::StackRoot: WebGPUPromise<D>,
226    EventHandlerNonNull<D>: CallbackContainer,
227{
228    pub fn id(&self) -> WebGPUDevice {
229        self.droppable.device
230    }
231
232    pub fn queue_id(&self) -> WebGPUQueue {
233        self.default_queue.id()
234    }
235
236    pub(crate) fn dispatch_error(&self, error: webgpu_traits::Error) {
237        if let Err(e) = self.droppable.channel.0.send(WebGPURequest::DispatchError {
238            device_id: self.id().0,
239            error,
240        }) {
241            warn!("Failed to send WebGPURequest::DispatchError due to {e:?}");
242        }
243    }
244
245    /// <https://gpuweb.github.io/gpuweb/#eventdef-gpudevice-uncapturederror>
246    pub fn fire_uncaptured_error(&self, error: webgpu_traits::Error) {
247        let this = Trusted::new(self);
248
249        // Queue a global task, using the webgpu task source, to fire an event named
250        // uncapturederror at a GPUDevice using GPUUncapturedErrorEvent.
251        self.global_from_reflector().queue_webgpu_task_source(task!(
252            fire_uncaptured_error: move |cx| {
253                let this = this.root();
254
255                let global = this.global_from_reflector();
256                let error = GPUError::<D>::from_error(cx, &*global, error);
257
258                let dictionary = RootedTraceableBox::new(GPUUncapturedErrorEventInit::<D> {
259                    parent: EventInit::empty(),
260                    error: error.as_traced(),
261                });
262
263                let event = GPUUncapturedErrorEvent::new(cx, &*global, atom!("uncapturederror"), &dictionary);
264                event.upcast::<D::Event>().fire(cx, this.upcast());
265            }
266        ));
267    }
268
269    /// <https://gpuweb.github.io/gpuweb/#abstract-opdef-validate-texture-format-required-features>
270    ///
271    /// Validates that the device suppports required features,
272    /// and if so returns an ok containing wgpu's `TextureFormat`
273    pub(crate) fn validate_texture_format_required_features(
274        &self,
275        format: &GPUTextureFormat,
276    ) -> Fallible<TextureFormat> {
277        let texture_format: TextureFormat = (*format).convert();
278        if self
279            .features
280            .wgpu_features()
281            .contains(texture_format.required_features())
282        {
283            Ok(texture_format)
284        } else {
285            Err(Error::Type(cformat!(
286                "{texture_format:?} is not supported by this GPUDevice"
287            )))
288        }
289    }
290
291    pub(crate) fn get_pipeline_layout_data(
292        &self,
293        layout: &GPUPipelineLayoutOrGPUAutoLayoutMode<D>,
294    ) -> PipelineLayout {
295        if let GPUPipelineLayoutOrGPUAutoLayoutMode::GPUPipelineLayout(layout) = layout {
296            PipelineLayout::Explicit(layout.id().0)
297        } else {
298            PipelineLayout::Implicit
299        }
300    }
301
302    pub(crate) fn parse_render_pipeline<'a>(
303        &self,
304        descriptor: &GPURenderPipelineDescriptor<D>,
305    ) -> Fallible<RenderPipelineDescriptor<'a>> {
306        let pipeline_layout = self.get_pipeline_layout_data(&descriptor.parent.layout);
307        let desc = RenderPipelineDescriptor {
308            label: (&descriptor.parent.parent).convert(),
309            layout: pipeline_layout.explicit(),
310            cache: None,
311            vertex: VertexState {
312                stage: (&descriptor.vertex.parent).convert(),
313                buffers: Cow::Owned(
314                    descriptor
315                        .vertex
316                        .buffers
317                        .iter()
318                        // FIXME: webidl has `sequence<GPUVertexBufferLayout?> buffers`
319                        // but we get no option here so it must be eaten by codegen
320                        .map(|buffer| {
321                            Some(VertexBufferLayout {
322                                array_stride: buffer.arrayStride,
323                                step_mode: match buffer.stepMode {
324                                    GPUVertexStepMode::Vertex => VertexStepMode::Vertex,
325                                    GPUVertexStepMode::Instance => VertexStepMode::Instance,
326                                },
327                                attributes: Cow::Owned(
328                                    buffer
329                                        .attributes
330                                        .iter()
331                                        .map(|att| VertexAttribute {
332                                            format: att.format.convert(),
333                                            offset: att.offset,
334                                            shader_location: att.shaderLocation,
335                                        })
336                                        .collect::<Vec<_>>(),
337                                ),
338                            })
339                        })
340                        .collect::<Vec<_>>(),
341                ),
342            },
343            fragment: descriptor
344                .fragment
345                .as_ref()
346                .map(|stage| -> Fallible<FragmentState> {
347                    Ok(FragmentState {
348                        stage: (&stage.parent).convert(),
349                        targets: Cow::Owned(
350                            stage
351                                .targets
352                                .iter()
353                                .map(|state| {
354                                    self.validate_texture_format_required_features(&state.format)
355                                        .map(|format| {
356                                            Some(ColorTargetState {
357                                                format,
358                                                write_mask: ColorWrites::from_bits_retain(
359                                                    state.writeMask,
360                                                ),
361                                                blend: state.blend.as_ref().map(|blend| {
362                                                    BlendState {
363                                                        color: (&blend.color).convert(),
364                                                        alpha: (&blend.alpha).convert(),
365                                                    }
366                                                }),
367                                            })
368                                        })
369                                })
370                                .collect::<Result<Vec<_>, _>>()?,
371                        ),
372                    })
373                })
374                .transpose()?,
375            primitive: (&descriptor.primitive).convert(),
376            depth_stencil: descriptor
377                .depthStencil
378                .as_ref()
379                .map(|dss_desc| {
380                    self.validate_texture_format_required_features(&dss_desc.format)
381                        .map(|format| DepthStencilState {
382                            format,
383                            depth_write_enabled: dss_desc.depthWriteEnabled,
384                            depth_compare: dss_desc.depthCompare.map(|dc| dc.convert()),
385                            stencil: StencilState {
386                                front: StencilFaceState {
387                                    compare: dss_desc.stencilFront.compare.convert(),
388
389                                    fail_op: dss_desc.stencilFront.failOp.convert(),
390                                    depth_fail_op: dss_desc.stencilFront.depthFailOp.convert(),
391                                    pass_op: dss_desc.stencilFront.passOp.convert(),
392                                },
393                                back: StencilFaceState {
394                                    compare: dss_desc.stencilBack.compare.convert(),
395                                    fail_op: dss_desc.stencilBack.failOp.convert(),
396                                    depth_fail_op: dss_desc.stencilBack.depthFailOp.convert(),
397                                    pass_op: dss_desc.stencilBack.passOp.convert(),
398                                },
399                                read_mask: dss_desc.stencilReadMask,
400                                write_mask: dss_desc.stencilWriteMask,
401                            },
402                            bias: DepthBiasState {
403                                constant: dss_desc.depthBias,
404                                slope_scale: *dss_desc.depthBiasSlopeScale,
405                                clamp: *dss_desc.depthBiasClamp,
406                            },
407                        })
408                })
409                .transpose()?,
410            multisample: MultisampleState {
411                count: descriptor.multisample.count,
412                mask: descriptor.multisample.mask as u64,
413                alpha_to_coverage_enabled: descriptor.multisample.alphaToCoverageEnabled,
414            },
415            multiview_mask: None,
416        };
417        Ok(desc)
418    }
419}
420
421impl<D> GPUDevice<D>
422where
423    D: Equivalence,
424{
425    pub fn channel(&self) -> WebGPU {
426        self.droppable.channel.clone()
427    }
428
429    /// <https://gpuweb.github.io/gpuweb/#lose-the-device>
430    pub fn lose(&self, reason: GPUDeviceLostReason, msg: String) {
431        let this = Trusted::new(self);
432
433        // Queue a global task, using the webgpu task source, to resolve device.lost
434        // promise with a new GPUDeviceLostInfo with reason and message.
435        let global: DomRoot<D::GlobalScope> = self.global_from_reflector();
436        global.queue_webgpu_task_source(task!(resolve_device_lost: move |cx| {
437            let this = this.root();
438
439            let lost_promise = &(*this.lost_promise.borrow());
440            let lost =
441                GPUDeviceLostInfo::<D>::new(cx, &*this.global_from_reflector(), msg.into(), reason);
442            lost_promise.resolve_native(cx, &*lost);
443        }));
444    }
445
446    pub(crate) fn is_lost(&self) -> bool {
447        self.lost_promise.borrow().is_fulfilled()
448    }
449}
450
451impl<D> GPUDeviceMethods<D> for GPUDevice<D>
452where
453    D: Equivalence,
454    <D::Promise as PromiseHelpers<D>>::StackRoot: WebGPUPromise<D>,
455    <D::Promise as PromiseHelpers<D>>::HeapTraced: HeapTracedPromiseHelpers<D>,
456{
457    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-features>
458    fn Features(&self) -> DomRoot<GPUSupportedFeatures<D>> {
459        DomRoot::from_ref(&self.features)
460    }
461
462    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-limits>
463    fn Limits(&self) -> DomRoot<GPUSupportedLimits<D>> {
464        DomRoot::from_ref(&*self.limits)
465    }
466
467    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-adapterinfo>
468    fn AdapterInfo(&self) -> DomRoot<GPUAdapterInfo<D>> {
469        DomRoot::from_ref(&self.adapter_info)
470    }
471
472    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-queue>
473    fn GetQueue(&self) -> DomRoot<D::GPUQueue> {
474        DomRoot::from_ref(&self.default_queue)
475    }
476
477    /// <https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label>
478    fn Label(&self) -> USVString {
479        self.label.borrow().clone()
480    }
481
482    /// <https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label>
483    fn SetLabel(&self, no_gc: &NoGC, value: USVString) {
484        *self.label.safe_borrow_mut(no_gc) = value;
485    }
486
487    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-lost>
488    fn Lost(&self, cx: &JSContext) -> <<D as script_bindings::DomTypes>::Promise as script_bindings::interfaces::PromiseHelpers<D>>::StackRoot{
489        self.lost_promise.borrow().root(cx)
490    }
491
492    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createbuffer>
493    fn CreateBuffer(
494        &self,
495        cx: &mut JSContext,
496        descriptor: &GPUBufferDescriptor,
497    ) -> Fallible<DomRoot<GPUBuffer<D>>> {
498        GPUBuffer::create(cx, self, descriptor)
499    }
500
501    /// <https://gpuweb.github.io/gpuweb/#GPUDevice-createBindGroupLayout>
502    fn CreateBindGroupLayout(
503        &self,
504        cx: &mut JSContext,
505        descriptor: &GPUBindGroupLayoutDescriptor,
506    ) -> Fallible<DomRoot<GPUBindGroupLayout<D>>> {
507        GPUBindGroupLayout::create(cx, self, descriptor)
508    }
509
510    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createpipelinelayout>
511    fn CreatePipelineLayout(
512        &self,
513        cx: &mut JSContext,
514        descriptor: &GPUPipelineLayoutDescriptor<D>,
515    ) -> DomRoot<GPUPipelineLayout<D>> {
516        GPUPipelineLayout::create(cx, self, descriptor)
517    }
518
519    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createbindgroup>
520    fn CreateBindGroup(
521        &self,
522        cx: &mut JSContext,
523        descriptor: &GPUBindGroupDescriptor<D>,
524    ) -> DomRoot<GPUBindGroup<D>> {
525        GPUBindGroup::create(cx, self, descriptor)
526    }
527
528    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createshadermodule>
529    fn CreateShaderModule(
530        &self,
531        cx: &mut CurrentRealm<'_>,
532        descriptor: &GPUShaderModuleDescriptor,
533    ) -> DomRoot<GPUShaderModule<D>> {
534        GPUShaderModule::create(cx, self, descriptor)
535    }
536
537    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createcomputepipeline>
538    fn CreateComputePipeline(
539        &self,
540        cx: &mut JSContext,
541        descriptor: &GPUComputePipelineDescriptor<D>,
542    ) -> DomRoot<GPUComputePipeline<D>> {
543        let compute_pipeline = GPUComputePipeline::create(self, descriptor, None);
544        GPUComputePipeline::new(
545            cx,
546            &*self.global_from_reflector(),
547            compute_pipeline,
548            descriptor.parent.parent.label.clone(),
549            self,
550        )
551    }
552
553    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createcomputepipelineasync>
554    fn CreateComputePipelineAsync(
555        &self,
556        cx: &mut CurrentRealm<'_>,
557        descriptor: &GPUComputePipelineDescriptor<D>,
558    ) -> <<D as script_bindings::DomTypes>::Promise as script_bindings::interfaces::PromiseHelpers<D>>::StackRoot{
559        let promise = D::Promise::new_in_realm(cx);
560        let callback =
561            <D::Promise as PromiseHelpers<D>>::StackRoot::callback_promise_dom_manipulation_task_source(&promise, self);
562        GPUComputePipeline::create(self, descriptor, Some(callback));
563        promise
564    }
565
566    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createcommandencoder>
567    fn CreateCommandEncoder(
568        &self,
569        cx: &mut JSContext,
570        descriptor: &GPUCommandEncoderDescriptor,
571    ) -> DomRoot<GPUCommandEncoder<D>> {
572        GPUCommandEncoder::create(cx, self, descriptor)
573    }
574
575    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createtexture>
576    fn CreateTexture(
577        &self,
578        cx: &mut JSContext,
579        descriptor: &GPUTextureDescriptor,
580    ) -> Fallible<DomRoot<GPUTexture<D>>> {
581        GPUTexture::create(cx, self, descriptor)
582    }
583
584    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createsampler>
585    fn CreateSampler(
586        &self,
587        cx: &mut JSContext,
588        descriptor: &GPUSamplerDescriptor,
589    ) -> DomRoot<GPUSampler<D>> {
590        GPUSampler::create(cx, self, descriptor)
591    }
592
593    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createrenderpipeline>
594    fn CreateRenderPipeline(
595        &self,
596        cx: &mut JSContext,
597        descriptor: &GPURenderPipelineDescriptor<D>,
598    ) -> Fallible<DomRoot<GPURenderPipeline<D>>> {
599        let desc = self.parse_render_pipeline(descriptor)?;
600        let render_pipeline = GPURenderPipeline::create(self, desc, None)?;
601        Ok(GPURenderPipeline::new(
602            cx,
603            &*self.global_from_reflector(),
604            render_pipeline,
605            descriptor.parent.parent.label.clone(),
606            self,
607        ))
608    }
609
610    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createrenderpipelineasync>
611    fn CreateRenderPipelineAsync(
612        &self,
613        cx: &mut CurrentRealm<'_>,
614        descriptor: &GPURenderPipelineDescriptor<D>,
615    ) -> Fallible<<<D as script_bindings::DomTypes>::Promise as script_bindings::interfaces::PromiseHelpers<D>>::StackRoot>{
616        let desc = self.parse_render_pipeline(descriptor)?;
617        let promise = D::Promise::new_in_realm(cx);
618        let callback = <D::Promise as PromiseHelpers<D>>::StackRoot::callback_promise_dom_manipulation_task_source(
619            &promise, self,
620        );
621        GPURenderPipeline::create(self, desc, Some(callback))?;
622        Ok(promise)
623    }
624
625    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createrenderbundleencoder>
626    fn CreateRenderBundleEncoder(
627        &self,
628        cx: &mut JSContext,
629        descriptor: &GPURenderBundleEncoderDescriptor,
630    ) -> Fallible<DomRoot<GPURenderBundleEncoder<D>>> {
631        GPURenderBundleEncoder::create(cx, self, descriptor)
632    }
633
634    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createqueryset>
635    fn CreateQuerySet(
636        &self,
637        cx: &mut JSContext,
638        descriptor: &GPUQuerySetDescriptor,
639    ) -> Fallible<DomRoot<GPUQuerySet<D>>> {
640        GPUQuerySet::create(cx, self, descriptor)
641    }
642
643    /// <https://www.w3.org/TR/webgpu/#dom-gpudevice-importexternaltexture>
644    fn ImportExternalTexture(
645        &self,
646        cx: &mut JSContext,
647        descriptor: &GPUExternalTextureDescriptor<D>,
648    ) -> Fallible<DomRoot<GPUExternalTexture<D>>> {
649        GPUExternalTexture::create(cx, self, descriptor)
650    }
651
652    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-pusherrorscope>
653    fn PushErrorScope(&self, filter: GPUErrorFilter) {
654        if self
655            .droppable
656            .channel
657            .0
658            .send(WebGPURequest::PushErrorScope {
659                device_id: self.id().0,
660                filter: filter.as_webgpu(),
661            })
662            .is_err()
663        {
664            warn!("Failed sending WebGPURequest::PushErrorScope");
665        }
666    }
667
668    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-poperrorscope>
669    fn PopErrorScope(&self, cx: &mut CurrentRealm<'_>) -> <<D as script_bindings::DomTypes>::Promise as script_bindings::interfaces::PromiseHelpers<D>>::StackRoot{
670        let promise = D::Promise::new_in_realm(cx);
671        let callback = <D::Promise as PromiseHelpers<D>>::StackRoot::callback_promise_dom_manipulation_task_source(
672            &promise, self,
673        );
674        if self
675            .droppable
676            .channel
677            .0
678            .send(WebGPURequest::PopErrorScope {
679                device_id: self.id().0,
680                callback,
681            })
682            .is_err()
683        {
684            warn!("Error when sending WebGPURequest::PopErrorScope");
685        }
686        promise
687    }
688
689    // https://gpuweb.github.io/gpuweb/#dom-gpudevice-onuncapturederror
690    event_handler!(uncapturederror, GetOnuncapturederror, SetOnuncapturederror);
691
692    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-destroy>
693    fn Destroy(&self) {
694        if self.valid.get() {
695            self.valid.set(false);
696
697            if let Err(e) = self
698                .droppable
699                .channel
700                .0
701                .send(WebGPURequest::DestroyDevice(self.id().0))
702            {
703                warn!("Failed to send DestroyDevice ({:?}) ({})", self.id().0, e);
704            }
705        }
706    }
707}
708
709impl<D: Equivalence> RoutedPromiseListener<D, WebGPUPoppedErrorScopeResponse> for GPUDevice<D>
710where
711    Self: DomGlobalGeneric<D>,
712    D::GPUError: Castable,
713    D::GPUValidationError: DerivedFrom<GPUError<D>>,
714    D::GPUOutOfMemoryError: DerivedFrom<GPUError<D>>,
715    D::GPUInternalError: DerivedFrom<GPUError<D>>,
716    D::DOMException: DomExceptionTrait,
717{
718    fn handle_response(
719        &self,
720        cx: &mut js::context::JSContext,
721        response: WebGPUPoppedErrorScopeResponse,
722        promise: &<D::Promise as PromiseHelpers<D>>::StackRoot,
723    ) {
724        match response {
725            Ok(None) | Err(PopError::Lost) => {
726                promise.resolve_native(cx, &None::<Option<GPUError<D>>>)
727            },
728            Err(PopError::Empty) => promise.reject_error(
729                cx,
730                Error::Operation(Some("Error scope stack is empty".into())),
731            ),
732            Ok(Some(error)) => {
733                let error = GPUError::<D>::from_error(cx, &self.global_from_reflector(), error);
734                promise.resolve_native(cx, &error);
735            },
736        }
737    }
738}
739
740impl<D: Equivalence> RoutedPromiseListener<D, WebGPUComputePipelineResponse> for GPUDevice<D>
741where
742    Self: DomGlobalGeneric<D>,
743    D::GPUError: Castable,
744    D::GPUValidationError: DerivedFrom<GPUError<D>>,
745    D::GPUOutOfMemoryError: DerivedFrom<GPUError<D>>,
746    D::GPUInternalError: DerivedFrom<GPUError<D>>,
747    D::DOMException: DomExceptionTrait,
748{
749    fn handle_response(
750        &self,
751        cx: &mut js::context::JSContext,
752        response: WebGPUComputePipelineResponse,
753        promise: &<D::Promise as PromiseHelpers<D>>::StackRoot,
754    ) {
755        match response {
756            Ok(pipeline) => {
757                let gpu_compute_pipeline = GPUComputePipeline::<D>::new(
758                    cx,
759                    &self.global_from_reflector(),
760                    WebGPUComputePipeline(pipeline.id),
761                    pipeline.label.into(),
762                    self,
763                );
764                promise.resolve_native(cx, &gpu_compute_pipeline)
765            },
766            Err(webgpu_traits::Error::Validation(msg)) => {
767                let gpu_pipeline_error = GPUPipelineError::<D>::new(
768                    cx,
769                    &self.global_from_reflector(),
770                    msg.into(),
771                    GPUPipelineErrorReason::Validation,
772                );
773                promise.reject_native(cx, &gpu_pipeline_error)
774            },
775            Err(webgpu_traits::Error::OutOfMemory(msg) | webgpu_traits::Error::Internal(msg)) => {
776                let gpu_pipeline_error = GPUPipelineError::<D>::new(
777                    cx,
778                    &self.global_from_reflector(),
779                    msg.into(),
780                    GPUPipelineErrorReason::Internal,
781                );
782                promise.reject_native(cx, &gpu_pipeline_error)
783            },
784        }
785    }
786}
787
788impl<D: Equivalence> RoutedPromiseListener<D, WebGPURenderPipelineResponse> for GPUDevice<D>
789where
790    Self: DomGlobalGeneric<D>,
791    D::GPUError: Castable,
792    D::GPUValidationError: DerivedFrom<GPUError<D>>,
793    D::GPUOutOfMemoryError: DerivedFrom<GPUError<D>>,
794    D::GPUInternalError: DerivedFrom<GPUError<D>>,
795    D::DOMException: DomExceptionTrait,
796{
797    fn handle_response(
798        &self,
799        cx: &mut js::context::JSContext,
800        response: WebGPURenderPipelineResponse,
801        promise: &<D::Promise as PromiseHelpers<D>>::StackRoot,
802    ) {
803        match response {
804            Ok(pipeline) => {
805                let gpu_pipeline = GPURenderPipeline::<D>::new(
806                    cx,
807                    &self.global_from_reflector(),
808                    WebGPURenderPipeline(pipeline.id),
809                    pipeline.label.into(),
810                    self,
811                );
812                promise.resolve_native(cx, &gpu_pipeline)
813            },
814            Err(webgpu_traits::Error::Validation(msg)) => {
815                let pipeline_error = GPUPipelineError::<D>::new(
816                    cx,
817                    &self.global_from_reflector(),
818                    msg.into(),
819                    GPUPipelineErrorReason::Validation,
820                );
821
822                promise.reject_native(cx, &pipeline_error)
823            },
824            Err(webgpu_traits::Error::OutOfMemory(msg) | webgpu_traits::Error::Internal(msg)) => {
825                let pipeline_error = GPUPipelineError::<D>::new(
826                    cx,
827                    &self.global_from_reflector(),
828                    msg.into(),
829                    GPUPipelineErrorReason::Internal,
830                );
831                promise.reject_native(cx, &pipeline_error)
832            },
833        }
834    }
835}