Skip to main content

webgpu/
wgpu_thread.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
5//! Data and main loop of WebGPU thread.
6
7use std::borrow::Cow;
8use std::ptr::NonNull;
9use std::slice;
10use std::sync::{Arc, Mutex};
11
12use log::{info, warn};
13use paint_api::{CrossProcessPaintApi, WebRenderExternalImageIdManager, WebRenderImageHandlerType};
14use rustc_hash::FxHashMap;
15use servo_base::generic_channel::{GenericReceiver, GenericSender, GenericSharedMemory};
16use servo_base::id::PipelineId;
17use servo_config::pref;
18use webgpu_traits::id::DeviceId;
19use webgpu_traits::{
20    Adapter, BufferAddress, BufferUpdate, ComputePassDescriptor, DeviceDescriptor,
21    DeviceLostReason, Error, ErrorScope, ExperimentalFeatures, Extent3d, HostMap, Mapping,
22    MemoryHints, Origin3d, Pipeline, PopError, RenderPassDescriptor, ShaderCompilationInfo,
23    ShaderModuleDescriptor, TexelCopyBufferLayout, TexelCopyTextureInfo, TextureAspect,
24    TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, TextureViewDescriptor,
25    WebGPU, WebGPUAdapter, WebGPUContextId, WebGPUDevice, WebGPUMsg, WebGPUQueue, WebGPURequest,
26    id,
27};
28use webrender_api::ExternalImageId;
29use wgpu_core::resource::{BufferAccessResult, BufferMapOperation};
30use wgpu_types::error::WebGpuError;
31use wgpu_types::{
32    ExternalTextureDescriptor, ExternalTextureFormat, ExternalTextureTransferFunction,
33    InstanceDescriptor,
34};
35
36use crate::canvas_context::WebGpuExternalImageMap;
37use crate::encoders::{
38    handle_command_encoder_command, handle_compute_pass_command, handle_render_bundle_command,
39    handle_render_pass_command,
40};
41use crate::poll_thread::Poller;
42
43#[derive(Eq, Hash, PartialEq)]
44pub(crate) struct DeviceScope {
45    pub device_id: DeviceId,
46    pub pipeline_id: PipelineId,
47    /// <https://www.w3.org/TR/webgpu/#dom-gpudevice-errorscopestack-slot>
48    ///
49    /// Is `None` if device is lost
50    pub error_scope_stack: Option<Vec<ErrorScope>>,
51    // TODO:
52    // Queue for this device (to remove transmutes)
53    // queue_id: QueueId,
54    // Poller for this device
55    // poller: Poller,
56}
57
58impl DeviceScope {
59    pub fn new(device_id: DeviceId, pipeline_id: PipelineId) -> Self {
60        Self {
61            device_id,
62            pipeline_id,
63            error_scope_stack: Some(Vec::new()),
64        }
65    }
66}
67
68#[expect(clippy::upper_case_acronyms)] // Name of the library
69pub(crate) struct WGPU {
70    receiver: GenericReceiver<WebGPURequest>,
71    sender: GenericSender<WebGPURequest>,
72    pub(crate) script_sender: GenericSender<WebGPUMsg>,
73    pub(crate) global: Arc<wgpu_core::global::Global>,
74    devices: Arc<Mutex<FxHashMap<DeviceId, DeviceScope>>>,
75    buffers: Arc<Mutex<FxHashMap<id::BufferId, GenericSharedMemory>>>,
76    pub(crate) paint_api: CrossProcessPaintApi,
77    pub(crate) webrender_external_image_id_manager: WebRenderExternalImageIdManager,
78    pub(crate) wgpu_image_map: WebGpuExternalImageMap,
79    /// Provides access to poller thread
80    pub(crate) poller: Poller,
81}
82
83impl WGPU {
84    pub(crate) fn new(
85        receiver: GenericReceiver<WebGPURequest>,
86        sender: GenericSender<WebGPURequest>,
87        script_sender: GenericSender<WebGPUMsg>,
88        paint_api: CrossProcessPaintApi,
89        webrender_external_image_id_manager: WebRenderExternalImageIdManager,
90        wgpu_image_map: WebGpuExternalImageMap,
91    ) -> Self {
92        let backend_pref = pref!(dom_webgpu_wgpu_backend);
93        let backends = if backend_pref.is_empty() {
94            wgpu_types::Backends::PRIMARY
95        } else {
96            info!(
97                "Selecting backends based on dom.webgpu.wgpu_backend pref: {:?}",
98                backend_pref
99            );
100            wgpu_types::Backends::from_comma_list(&backend_pref)
101        };
102        let global = Arc::new(wgpu_core::global::Global::new(
103            "wgpu-core",
104            InstanceDescriptor {
105                backends,
106                backend_options: wgpu_types::BackendOptions {
107                    gl: wgpu_types::GlBackendOptions {
108                        gles_minor_version: wgpu_types::Gles3MinorVersion::Automatic,
109                        fence_behavior: wgpu_types::GlFenceBehavior::Normal,
110                        debug_fns: wgpu_types::GlDebugFns::Auto,
111                    },
112                    dx12: wgpu_types::Dx12BackendOptions {
113                        ..Default::default()
114                    },
115                    noop: wgpu_types::NoopBackendOptions::default(),
116                },
117
118                flags: wgpu_types::InstanceFlags::from_build_config() |
119                    wgpu_types::InstanceFlags::AUTOMATIC_TIMESTAMP_NORMALIZATION |
120                    wgpu_types::InstanceFlags::STRICT_WEBGPU_COMPLIANCE,
121                // TODO(sagudev): firefox actually sets this, but it can cause OOM for us
122                // meaning that we are likely leaking something
123                memory_budget_thresholds: wgpu_types::MemoryBudgetThresholds {
124                    for_resource_creation: Some(95),
125                    for_device_loss: Some(99),
126                },
127                display: None,
128            },
129            None,
130        ));
131        WGPU {
132            poller: Poller::new(Arc::clone(&global)),
133            receiver,
134            sender,
135            script_sender,
136            global,
137            devices: Arc::new(Mutex::new(FxHashMap::default())),
138            buffers: Arc::new(Mutex::new(FxHashMap::default())),
139            paint_api,
140            webrender_external_image_id_manager,
141            wgpu_image_map,
142        }
143    }
144
145    pub(crate) fn run(&mut self) {
146        loop {
147            if let Ok(msg) = self.receiver.recv() {
148                log::trace!("recv: {msg:?}");
149                match msg {
150                    WebGPURequest::SetImageKey {
151                        context_id,
152                        image_key,
153                    } => self.set_image_key(context_id, image_key),
154                    WebGPURequest::BufferMapAsync {
155                        callback: sender,
156                        buffer_id,
157                        device_id,
158                        host_map,
159                        offset,
160                        size,
161                        buffer_size,
162                    } => {
163                        let glob = Arc::clone(&self.global);
164                        let buffers = Arc::clone(&self.buffers);
165                        let resp_sender = sender.clone();
166                        let token = self.poller.token();
167                        let callback = Box::from(move |result: BufferAccessResult| {
168                            drop(token);
169                            let response = result.and_then(|_| {
170                                let global = &glob;
171                                let mut data =
172                                    buffers.lock().unwrap().remove(&buffer_id).unwrap_or_else(
173                                        || GenericSharedMemory::from_byte(0, buffer_size as usize),
174                                    );
175                                if host_map == HostMap::Read {
176                                    let (slice_pointer, range_size) =
177                                        global.buffer_get_mapped_range(buffer_id, offset, size)?;
178                                    // SAFETY: guarantee to be safe from wgpu
179                                    let slice = unsafe {
180                                        slice::from_raw_parts(
181                                            slice_pointer.as_ptr(),
182                                            range_size as usize,
183                                        )
184                                    };
185                                    let data = unsafe { data.deref_mut() };
186                                    data[offset as usize..(offset + range_size) as usize]
187                                        .copy_from_slice(slice);
188                                }
189
190                                Ok(Mapping {
191                                    data,
192                                    range: offset..size.map(|s| offset + s).unwrap_or(buffer_size),
193                                    mode: host_map,
194                                })
195                            });
196                            if let Err(e) = resp_sender.send(response) {
197                                warn!("Could not send BufferMapAsync Response ({})", e);
198                            }
199                        });
200
201                        let operation = BufferMapOperation {
202                            host: host_map,
203                            callback: Some(callback),
204                        };
205                        let global = &self.global;
206                        let result = global.buffer_map_async(buffer_id, offset, size, operation);
207                        self.poller.wake();
208                        // Per spec we also need to raise validation error here
209                        self.maybe_dispatch_wgpu_error(device_id, result.err());
210                    },
211                    WebGPURequest::CommandEncoderFinish {
212                        command_encoder_id,
213                        device_id,
214                        desc,
215                        command_buffer_id,
216                    } => {
217                        let global = &self.global;
218                        let (_, error) = global.command_encoder_finish(
219                            command_encoder_id,
220                            &desc,
221                            Some(command_buffer_id),
222                        );
223                        self.maybe_dispatch_wgpu_error(device_id, error.map(|(_, e)| e));
224                    },
225                    WebGPURequest::CommandEncoderCommand {
226                        command_encoder_id,
227                        command,
228                        device_id,
229                    } => {
230                        let global = &self.global;
231                        let result =
232                            handle_command_encoder_command(global, command_encoder_id, command);
233                        self.maybe_dispatch_wgpu_error(device_id, result.err());
234                    },
235                    WebGPURequest::CreateBindGroup {
236                        device_id,
237                        bind_group_id,
238                        descriptor,
239                    } => {
240                        let global = &self.global;
241                        let (_, error) = global.device_create_bind_group(
242                            device_id,
243                            &descriptor,
244                            Some(bind_group_id),
245                        );
246                        self.maybe_dispatch_wgpu_error(device_id, error);
247                    },
248                    WebGPURequest::CreateBindGroupLayout {
249                        device_id,
250                        bind_group_layout_id,
251                        descriptor,
252                    } => {
253                        let global = &self.global;
254                        if let Some(desc) = descriptor {
255                            let (_, error) = global.device_create_bind_group_layout(
256                                device_id,
257                                &desc,
258                                Some(bind_group_layout_id),
259                            );
260
261                            self.maybe_dispatch_wgpu_error(device_id, error);
262                        } else {
263                            // Script already reported the error; register an invalid id so that
264                            // later uses of it are validation errors instead of panics.
265                            global.create_bind_group_layout_error(
266                                device_id,
267                                Some(bind_group_layout_id),
268                                None,
269                            );
270                        }
271                    },
272                    WebGPURequest::CreateBuffer {
273                        device_id,
274                        buffer_id,
275                        descriptor,
276                    } => {
277                        let global = &self.global;
278                        let (_, error) =
279                            global.device_create_buffer(device_id, &descriptor, Some(buffer_id));
280
281                        self.maybe_dispatch_wgpu_error(device_id, error);
282                    },
283                    WebGPURequest::CreateCommandEncoder {
284                        device_id,
285                        command_encoder_id,
286                        desc,
287                    } => {
288                        let global = &self.global;
289                        let (_, error) = global.device_create_command_encoder(
290                            device_id,
291                            &desc,
292                            Some(command_encoder_id),
293                        );
294
295                        self.maybe_dispatch_wgpu_error(device_id, error);
296                    },
297                    WebGPURequest::CreateComputePipeline {
298                        device_id,
299                        compute_pipeline_id,
300                        descriptor,
301                        async_sender: sender,
302                    } => {
303                        let global = &self.global;
304                        let (_, error) = global.device_create_compute_pipeline(
305                            device_id,
306                            &descriptor,
307                            Some(compute_pipeline_id),
308                        );
309                        if let Some(sender) = sender {
310                            let res = match error.and_then(Error::from_wgpu_error) {
311                                // if device is lost we must return pipeline and not raise any error
312                                None => Ok(Pipeline {
313                                    id: compute_pipeline_id,
314                                    label: descriptor.label.unwrap_or_default().to_string(),
315                                }),
316                                Some(e) => Err(e),
317                            };
318                            if let Err(e) = sender.send(res) {
319                                warn!("Failed sending WebGPUComputePipelineResponse {e:?}");
320                            }
321                        } else {
322                            self.maybe_dispatch_wgpu_error(device_id, error);
323                        }
324                    },
325                    WebGPURequest::CreatePipelineLayout {
326                        device_id,
327                        pipeline_layout_id,
328                        descriptor,
329                    } => {
330                        let global = &self.global;
331                        let (_, error) = global.device_create_pipeline_layout(
332                            device_id,
333                            &descriptor,
334                            Some(pipeline_layout_id),
335                        );
336                        self.maybe_dispatch_wgpu_error(device_id, error);
337                    },
338                    WebGPURequest::CreateRenderPipeline {
339                        device_id,
340                        render_pipeline_id,
341                        descriptor,
342                        async_sender: sender,
343                    } => {
344                        let global = &self.global;
345                        let (_, error) = global.device_create_render_pipeline(
346                            device_id,
347                            &descriptor,
348                            Some(render_pipeline_id),
349                        );
350
351                        if let Some(sender) = sender {
352                            let res = match error.and_then(Error::from_wgpu_error) {
353                                // if device is lost we must return pipeline and not raise any error
354                                None => Ok(Pipeline {
355                                    id: render_pipeline_id,
356                                    label: descriptor.label.unwrap_or_default().to_string(),
357                                }),
358                                Some(e) => Err(e),
359                            };
360                            if let Err(e) = sender.send(res) {
361                                warn!("Failed sending WebGPURenderPipelineResponse {e:?}");
362                            }
363                        } else {
364                            self.maybe_dispatch_wgpu_error(device_id, error);
365                        }
366                    },
367                    WebGPURequest::CreateSampler {
368                        device_id,
369                        sampler_id,
370                        descriptor,
371                    } => {
372                        let global = &self.global;
373                        let (_, error) =
374                            global.device_create_sampler(device_id, &descriptor, Some(sampler_id));
375                        self.maybe_dispatch_wgpu_error(device_id, error);
376                    },
377                    WebGPURequest::CreateShaderModule {
378                        device_id,
379                        program_id,
380                        program,
381                        label,
382                        callback: sender,
383                    } => {
384                        let global = &self.global;
385                        let source =
386                            wgpu_core::pipeline::ShaderModuleSource::Wgsl(Cow::Borrowed(&program));
387                        let desc = ShaderModuleDescriptor {
388                            label: label.map(|s| s.into()),
389                            runtime_checks: wgpu_types::ShaderRuntimeChecks::checked(),
390                        };
391                        let (_, error) = global.device_create_shader_module(
392                            device_id,
393                            &desc,
394                            source,
395                            Some(program_id),
396                        );
397                        if let Err(e) = sender.send(
398                            error
399                                .as_ref()
400                                .map(|e| ShaderCompilationInfo::from(e, &program)),
401                        ) {
402                            warn!("Failed to send CompilationInfo {e:?}");
403                        }
404                        self.maybe_dispatch_wgpu_error(device_id, error);
405                    },
406                    WebGPURequest::CreateContext {
407                        buffer_ids,
408                        size,
409                        sender,
410                    } => {
411                        let id = self
412                            .webrender_external_image_id_manager
413                            .next_id(WebRenderImageHandlerType::WebGpu);
414                        let context_id = WebGPUContextId(id.0);
415
416                        if let Err(error) = sender.send(context_id) {
417                            warn!("Failed to send ContextId to new context ({error})");
418                        };
419
420                        self.create_context(context_id, size, buffer_ids);
421                    },
422                    WebGPURequest::Present {
423                        context_id,
424                        pending_texture,
425                        size,
426                        canvas_epoch,
427                    } => {
428                        self.present(context_id, pending_texture, size, canvas_epoch);
429                    },
430                    WebGPURequest::GetImage {
431                        context_id,
432                        pending_texture,
433                        sender,
434                    } => self.get_image(context_id, pending_texture, sender),
435                    WebGPURequest::ValidateTextureDescriptor {
436                        device_id,
437                        texture_id,
438                        descriptor,
439                    } => {
440                        // https://gpuweb.github.io/gpuweb/#dom-gpucanvascontext-configure
441                        // validating TextureDescriptor by creating dummy texture
442                        let global = &self.global;
443                        let (_, error) =
444                            global.device_create_texture(device_id, &descriptor, Some(texture_id));
445                        global.texture_drop(texture_id);
446                        self.poller.wake();
447                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeTexture(texture_id))
448                        {
449                            warn!("Unable to send FreeTexture({:?}) ({:?})", texture_id, e);
450                        };
451                        self.maybe_dispatch_wgpu_error(device_id, error);
452                    },
453                    WebGPURequest::DestroyContext { context_id } => {
454                        self.destroy_context(context_id);
455                        self.webrender_external_image_id_manager
456                            .remove(&ExternalImageId(context_id.0));
457                    },
458                    WebGPURequest::CreateTexture {
459                        device_id,
460                        texture_id,
461                        descriptor,
462                    } => {
463                        let global = &self.global;
464                        let (_, error) =
465                            global.device_create_texture(device_id, &descriptor, Some(texture_id));
466                        self.maybe_dispatch_wgpu_error(device_id, error);
467                    },
468                    WebGPURequest::CreateTextureView {
469                        texture_id,
470                        texture_view_id,
471                        device_id,
472                        descriptor,
473                    } => {
474                        let (_, error) = self.global.texture_create_view(
475                            texture_id,
476                            &descriptor,
477                            Some(texture_view_id),
478                        );
479                        self.maybe_dispatch_wgpu_error(device_id, error);
480                    },
481                    WebGPURequest::DestroyBuffer(buffer) => {
482                        let global = &self.global;
483                        global.buffer_destroy(buffer);
484                    },
485                    WebGPURequest::DestroyDevice(device) => {
486                        let global = &self.global;
487                        global.device_destroy(device);
488                        // Wake poller thread to trigger DeviceLostClosure
489                        self.poller.wake();
490                    },
491                    WebGPURequest::DestroyTexture(texture_id) => {
492                        let global = &self.global;
493                        global.texture_destroy(texture_id);
494                    },
495                    WebGPURequest::Exit(sender) => {
496                        if let Err(e) = sender.send(()) {
497                            warn!("Failed to send response to WebGPURequest::Exit ({})", e)
498                        }
499                        break;
500                    },
501                    WebGPURequest::DropCommandEncoder(id) => {
502                        let global = &self.global;
503                        global.command_encoder_drop(id);
504                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeCommandEncoder(id)) {
505                            warn!("Unable to send FreeCommandEncoder({:?}) ({:?})", id, e);
506                        };
507                    },
508                    WebGPURequest::DropCommandBuffer(id) => {
509                        let global = &self.global;
510                        global.command_buffer_drop(id);
511                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeCommandBuffer(id)) {
512                            warn!("Unable to send FreeCommandBuffer({:?}) ({:?})", id, e);
513                        };
514                    },
515                    WebGPURequest::DropDevice(device_id) => {
516                        let global = &self.global;
517                        global.device_drop(device_id);
518                        let device_scope = self
519                            .devices
520                            .lock()
521                            .unwrap()
522                            .remove(&device_id)
523                            .expect("Device should not be dropped by this point");
524                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeDevice {
525                            device_id,
526                            pipeline_id: device_scope.pipeline_id,
527                        }) {
528                            warn!("Unable to send FreeDevice({:?}) ({:?})", device_id, e);
529                        };
530                    },
531                    WebGPURequest::RequestAdapter {
532                        sender,
533                        options,
534                        adapter_id,
535                    } => {
536                        let global = &self.global;
537                        let response = self
538                            .global
539                            .request_adapter(
540                                &options,
541                                wgpu_types::Backends::all(),
542                                Some(adapter_id),
543                            )
544                            .map(|adapter_id| {
545                                // TODO: can we do this lazily
546                                let adapter_info = global.adapter_get_info(adapter_id);
547                                let limits = global.adapter_limits(adapter_id);
548                                let features = global.adapter_features(adapter_id);
549                                Adapter {
550                                    adapter_info,
551                                    adapter_id: WebGPUAdapter(adapter_id),
552                                    features,
553                                    limits,
554                                    channel: WebGPU(self.sender.clone()),
555                                }
556                            })
557                            .map_err(|err| err.to_string());
558
559                        if let Err(e) = sender.send(Some(response)) {
560                            warn!(
561                                "Failed to send response to WebGPURequest::RequestAdapter ({})",
562                                e
563                            )
564                        }
565                    },
566                    WebGPURequest::RequestDevice {
567                        sender,
568                        adapter_id,
569                        descriptor,
570                        device_id,
571                        queue_id,
572                        pipeline_id,
573                    } => {
574                        let mut desc = DeviceDescriptor {
575                            label: descriptor.label.as_ref().map(crate::Cow::from),
576                            required_features: descriptor.required_features,
577                            required_limits: descriptor.required_limits.clone(),
578                            memory_hints: MemoryHints::MemoryUsage,
579                            trace: wgpu_types::Trace::Off,
580                            experimental_features: ExperimentalFeatures::disabled(),
581                        };
582                        let global = &self.global;
583                        // enable external texture support if available
584                        let features = global.adapter_features(adapter_id.0);
585                        if features.contains(wgpu_types::Features::EXTERNAL_TEXTURE) {
586                            desc.required_features |= wgpu_types::Features::EXTERNAL_TEXTURE;
587                        }
588                        let device = WebGPUDevice(device_id);
589                        let queue = WebGPUQueue(queue_id);
590                        let result = global
591                            .adapter_request_device(
592                                adapter_id.0,
593                                &desc,
594                                Some(device_id),
595                                Some(queue_id),
596                            )
597                            .map(|_| {
598                                {
599                                    self.devices.lock().unwrap().insert(
600                                        device_id,
601                                        DeviceScope::new(device_id, pipeline_id),
602                                    );
603                                }
604                                let script_sender = self.script_sender.clone();
605                                let devices = Arc::clone(&self.devices);
606                                let callback = Box::from(move |reason, msg| {
607                                    let reason = match reason {
608                                        wgpu_types::DeviceLostReason::Unknown => {
609                                            DeviceLostReason::Unknown
610                                        },
611                                        wgpu_types::DeviceLostReason::Destroyed => {
612                                            DeviceLostReason::Destroyed
613                                        },
614                                    };
615                                    // make device lost by removing error scopes stack
616                                    let _ = devices
617                                        .lock()
618                                        .unwrap()
619                                        .get_mut(&device_id)
620                                        .expect("Device should not be dropped by this point")
621                                        .error_scope_stack
622                                        .take();
623                                    if let Err(e) = script_sender.send(WebGPUMsg::DeviceLost {
624                                        device,
625                                        pipeline_id,
626                                        reason,
627                                        msg,
628                                    }) {
629                                        warn!("Failed to send WebGPUMsg::DeviceLost: {e}");
630                                    }
631                                });
632                                global.device_set_device_lost_closure(device_id, callback);
633                                let mut descriptor = descriptor;
634                                descriptor.required_limits = global.device_limits(device_id);
635                                descriptor.required_features = global.device_features(device_id);
636                                descriptor
637                            })
638                            .map_err(Into::into);
639
640                        if let Err(e) = sender.send((device, queue, result)) {
641                            warn!(
642                                "Failed to send response to WebGPURequest::RequestDevice ({})",
643                                e
644                            )
645                        }
646                    },
647                    WebGPURequest::BeginComputePass {
648                        command_encoder_id,
649                        compute_pass_id,
650                        label,
651                        timestamp_writes,
652                        device_id,
653                    } => {
654                        let global = &self.global;
655                        let (_, error) = global.command_encoder_begin_compute_pass_with_id(
656                            command_encoder_id,
657                            &ComputePassDescriptor {
658                                label,
659                                timestamp_writes,
660                            },
661                            Some(compute_pass_id),
662                        );
663                        self.maybe_dispatch_wgpu_error(device_id, error);
664                    },
665                    WebGPURequest::ComputePassCommand {
666                        compute_pass_id,
667                        compute_command,
668                        device_id,
669                    } => {
670                        let result = handle_compute_pass_command(
671                            &self.global,
672                            compute_pass_id,
673                            compute_command,
674                        );
675                        self.maybe_dispatch_wgpu_error(device_id, result.err());
676                    },
677                    WebGPURequest::EndComputePass {
678                        compute_pass_id,
679                        device_id,
680                    } => {
681                        // https://www.w3.org/TR/2024/WD-webgpu-20240703/#dom-gpucomputepassencoder-end
682                        let result = self.global.compute_pass_end_with_id(compute_pass_id);
683                        self.maybe_dispatch_wgpu_error(device_id, result.err());
684                    },
685                    WebGPURequest::BeginRenderPass {
686                        command_encoder_id,
687                        render_pass_id,
688                        label,
689                        color_attachments,
690                        depth_stencil_attachment,
691                        timestamp_writes,
692                        device_id,
693                    } => {
694                        let global = &self.global;
695                        let desc = &RenderPassDescriptor {
696                            label,
697                            color_attachments: color_attachments.into(),
698                            depth_stencil_attachment,
699                            timestamp_writes,
700                            occlusion_query_set: None,
701                            multiview_mask: None,
702                        };
703                        let (_, error) = global.command_encoder_begin_render_pass_with_id(
704                            command_encoder_id,
705                            desc,
706                            Some(render_pass_id),
707                        );
708                        self.maybe_dispatch_wgpu_error(device_id, error);
709                    },
710                    WebGPURequest::RenderPassCommand {
711                        render_pass_id,
712                        render_command,
713                        device_id,
714                    } => {
715                        let result = handle_render_pass_command(
716                            &self.global,
717                            render_pass_id,
718                            render_command,
719                        );
720                        self.maybe_dispatch_wgpu_error(device_id, result.err());
721                    },
722                    WebGPURequest::EndRenderPass {
723                        render_pass_id,
724                        device_id,
725                    } => {
726                        // https://www.w3.org/TR/2024/WD-webgpu-20240703/#dom-gpurenderpassencoder-end
727                        let result = self.global.render_pass_end_with_id(render_pass_id);
728                        self.maybe_dispatch_wgpu_error(device_id, result.err());
729                    },
730                    WebGPURequest::Submit {
731                        device_id,
732                        queue_id,
733                        command_buffers,
734                    } => {
735                        let global = &self.global;
736                        let result = {
737                            let _guard = self.poller.lock();
738                            global.queue_submit(queue_id, &command_buffers)
739                        };
740                        self.maybe_dispatch_wgpu_error(device_id, result.err().map(|(_, x)| x));
741                    },
742                    WebGPURequest::UnmapBuffer {
743                        buffer_id,
744                        buffer_update,
745                    } => {
746                        let global = &self.global;
747                        if let BufferUpdate::Write(data, range) = &buffer_update &&
748                            let Ok((slice_pointer, range_size)) = global.buffer_get_mapped_range(
749                                buffer_id,
750                                range.start,
751                                Some(range.end - range.start),
752                            )
753                        {
754                            let mut write_slice = unsafe {
755                                wgpu_types::WriteOnly::new(NonNull::slice_from_raw_parts(
756                                    slice_pointer,
757                                    range_size as usize,
758                                ))
759                            };
760                            write_slice.copy_from_slice(
761                                &data.as_ref()[range.start as usize..range.end as usize],
762                            );
763                        }
764                        let data = match buffer_update {
765                            BufferUpdate::Read(generic_shared_memory) => generic_shared_memory,
766                            BufferUpdate::Write(generic_shared_memory, _) => generic_shared_memory,
767                        };
768                        self.buffers.lock().unwrap().insert(buffer_id, data);
769
770                        // Ignore result because this operation always succeed from user perspective
771                        let _result = global.buffer_unmap(buffer_id);
772                    },
773                    WebGPURequest::WriteBuffer {
774                        device_id,
775                        queue_id,
776                        buffer_id,
777                        buffer_offset,
778                        data,
779                    } => {
780                        let global = &self.global;
781                        let result = global.queue_write_buffer(
782                            queue_id,
783                            buffer_id,
784                            buffer_offset as BufferAddress,
785                            &data,
786                        );
787                        self.maybe_dispatch_wgpu_error(device_id, result.err());
788                    },
789                    WebGPURequest::WriteTexture {
790                        device_id,
791                        queue_id,
792                        texture_cv,
793                        data_layout,
794                        size,
795                        data,
796                    } => {
797                        let global = &self.global;
798                        let _guard = self.poller.lock();
799                        // TODO: Report result to content process
800                        let result = global.queue_write_texture(
801                            queue_id,
802                            &texture_cv,
803                            &data,
804                            &data_layout,
805                            &size,
806                        );
807                        drop(_guard);
808                        self.maybe_dispatch_wgpu_error(device_id, result.err());
809                    },
810                    WebGPURequest::CopyExternalImageToTexture {
811                        device_id,
812                        queue_id,
813                        usable_source,
814                        destination,
815                        dest_tex_descriptor,
816                        copy_size,
817                    } => {
818                        // device and queue timeline of https://www.w3.org/TR/webgpu/#dom-gpuqueue-copyexternalimagetotexture
819                        let global = &self.global;
820                        // If any of the following requirements are unmet, generate a validation error and return.
821                        // usability must be good.
822                        let Some(source) = usable_source else {
823                            self.maybe_dispatch_error(
824                                device_id,
825                                Some(Error::Validation("Source is not usable".to_string())),
826                            );
827                            continue;
828                        };
829                        // texture.usage must include both RENDER_ATTACHMENT
830                        if !dest_tex_descriptor
831                            .usage
832                            .contains(TextureUsages::RENDER_ATTACHMENT)
833                        {
834                            self.maybe_dispatch_error(
835                                device_id,
836                                Some(Error::Validation(
837                                    "Texture usage must include RENDER_ATTACHMENT".to_string(),
838                                )),
839                            );
840                            continue;
841                        }
842                        // texture.dimension must be "2d".
843                        if dest_tex_descriptor.dimension != TextureDimension::D2 {
844                            self.maybe_dispatch_error(
845                                device_id,
846                                Some(Error::Validation(
847                                    "Texture dimension must be 2d".to_string(),
848                                )),
849                            );
850                            continue;
851                        }
852                        // texture.format must be a plain color format supporting RENDER_ATTACHMENT and be a unorm/unorm-srgb or float/ufloat format (not snorm, uint, or sint).
853                        // currently to to hard to check
854                        // the rest will be checked as part of write texture
855                        let _guard = self.poller.lock();
856                        let result = global.queue_write_texture(
857                            queue_id,
858                            &destination,
859                            source.data(),
860                            &TexelCopyBufferLayout {
861                                offset: 0,
862                                bytes_per_row: Some(source.size().width * 4),
863                                rows_per_image: None,
864                            },
865                            &copy_size,
866                        );
867                        drop(_guard);
868                        self.maybe_dispatch_wgpu_error(device_id, result.err());
869                    },
870                    WebGPURequest::QueueOnSubmittedWorkDone { sender, queue_id } => {
871                        let global = &self.global;
872                        let token = self.poller.token();
873                        let callback = Box::from(move || {
874                            drop(token);
875                            if let Err(e) = sender.send(()) {
876                                warn!("Could not send SubmittedWorkDone Response ({})", e);
877                            }
878                        });
879                        global.queue_on_submitted_work_done(queue_id, callback);
880                        self.poller.wake();
881                    },
882                    WebGPURequest::DropTexture(id) => {
883                        let global = &self.global;
884                        global.texture_drop(id);
885                        self.poller.wake();
886                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeTexture(id)) {
887                            warn!("Unable to send FreeTexture({:?}) ({:?})", id, e);
888                        };
889                    },
890                    WebGPURequest::DropAdapter(id) => {
891                        let global = &self.global;
892                        global.adapter_drop(id);
893                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeAdapter(id)) {
894                            warn!("Unable to send FreeAdapter({:?}) ({:?})", id, e);
895                        };
896                    },
897                    WebGPURequest::DropBuffer(id) => {
898                        let global = &self.global;
899                        global.buffer_drop(id);
900                        self.buffers.lock().unwrap().remove(&id);
901                        self.poller.wake();
902                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeBuffer(id)) {
903                            warn!("Unable to send FreeBuffer({:?}) ({:?})", id, e);
904                        };
905                    },
906                    WebGPURequest::DropPipelineLayout(id) => {
907                        let global = &self.global;
908                        global.pipeline_layout_drop(id);
909                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreePipelineLayout(id)) {
910                            warn!("Unable to send FreePipelineLayout({:?}) ({:?})", id, e);
911                        };
912                    },
913                    WebGPURequest::DropComputePipeline(id) => {
914                        let global = &self.global;
915                        global.compute_pipeline_drop(id);
916                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeComputePipeline(id))
917                        {
918                            warn!("Unable to send FreeComputePipeline({:?}) ({:?})", id, e);
919                        };
920                    },
921                    WebGPURequest::DropComputePass(id) => {
922                        self.global.compute_pass_drop(id);
923                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeComputePass(id)) {
924                            warn!("Unable to send FreeComputePass({:?}) ({:?})", id, e);
925                        };
926                    },
927                    WebGPURequest::DropRenderPass(id) => {
928                        self.global.render_pass_drop(id);
929                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeRenderPass(id)) {
930                            warn!("Unable to send FreeRenderPass({:?}) ({:?})", id, e);
931                        };
932                    },
933                    WebGPURequest::DropRenderPipeline(id) => {
934                        let global = &self.global;
935                        global.render_pipeline_drop(id);
936                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeRenderPipeline(id)) {
937                            warn!("Unable to send FreeRenderPipeline({:?}) ({:?})", id, e);
938                        };
939                    },
940                    WebGPURequest::DropBindGroup(id) => {
941                        let global = &self.global;
942                        global.bind_group_drop(id);
943                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeBindGroup(id)) {
944                            warn!("Unable to send FreeBindGroup({:?}) ({:?})", id, e);
945                        };
946                    },
947                    WebGPURequest::DropBindGroupLayout(id) => {
948                        let global = &self.global;
949                        global.bind_group_layout_drop(id);
950                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeBindGroupLayout(id))
951                        {
952                            warn!("Unable to send FreeBindGroupLayout({:?}) ({:?})", id, e);
953                        };
954                    },
955                    WebGPURequest::DropTextureView(id) => {
956                        let global = &self.global;
957                        global.texture_view_drop(id);
958                        self.poller.wake();
959                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeTextureView(id)) {
960                            warn!("Unable to send FreeTextureView({:?}) ({:?})", id, e);
961                        };
962                    },
963                    WebGPURequest::DropSampler(id) => {
964                        let global = &self.global;
965                        global.sampler_drop(id);
966                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeSampler(id)) {
967                            warn!("Unable to send FreeSampler({:?}) ({:?})", id, e);
968                        };
969                    },
970                    WebGPURequest::DropShaderModule(id) => {
971                        let global = &self.global;
972                        global.shader_module_drop(id);
973                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeShaderModule(id)) {
974                            warn!("Unable to send FreeShaderModule({:?}) ({:?})", id, e);
975                        };
976                    },
977                    WebGPURequest::DropRenderBundleEncoder(id) => {
978                        let global = &self.global;
979                        global.render_bundle_encoder_drop(id);
980                        if let Err(e) = self
981                            .script_sender
982                            .send(WebGPUMsg::FreeRenderBundleEncoder(id))
983                        {
984                            warn!("Unable to send FreeRenderBundleEncoder({:?}) ({:?})", id, e);
985                        };
986                    },
987                    WebGPURequest::DropRenderBundle(id) => {
988                        let global = &self.global;
989                        global.render_bundle_drop(id);
990                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeRenderBundle(id)) {
991                            warn!("Unable to send FreeRenderBundle({:?}) ({:?})", id, e);
992                        };
993                    },
994                    WebGPURequest::DropQuerySet(id) => {
995                        let global = &self.global;
996                        global.query_set_drop(id);
997                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeQuerySet(id)) {
998                            warn!("Unable to send FreeQuerySet({:?}) ({:?})", id, e);
999                        };
1000                    },
1001                    WebGPURequest::PushErrorScope { device_id, filter } => {
1002                        // <https://www.w3.org/TR/webgpu/#dom-gpudevice-pusherrorscope>
1003                        let mut devices = self.devices.lock().unwrap();
1004                        let device_scope = devices
1005                            .get_mut(&device_id)
1006                            .expect("Device should not be dropped by this point");
1007                        if let Some(error_scope_stack) = &mut device_scope.error_scope_stack {
1008                            error_scope_stack.push(ErrorScope::new(filter));
1009                        } // else device is lost
1010                    },
1011                    WebGPURequest::DispatchError { device_id, error } => {
1012                        self.dispatch_error(device_id, error);
1013                    },
1014                    WebGPURequest::PopErrorScope {
1015                        device_id,
1016                        callback: sender,
1017                    } => {
1018                        // <https://www.w3.org/TR/webgpu/#dom-gpudevice-poperrorscope>
1019                        let mut devices = self.devices.lock().unwrap();
1020                        let device_scope = devices
1021                            .get_mut(&device_id)
1022                            .expect("Device should not be dropped by this point");
1023                        let result =
1024                            if let Some(error_scope_stack) = &mut device_scope.error_scope_stack {
1025                                if let Some(error_scope) = error_scope_stack.pop() {
1026                                    Ok(
1027                                        // TODO: Do actual selection instead of selecting first error
1028                                        error_scope.errors.first().cloned(),
1029                                    )
1030                                } else {
1031                                    Err(PopError::Empty)
1032                                }
1033                            } else {
1034                                // This means the device has been lost.
1035                                Err(PopError::Lost)
1036                            };
1037                        if let Err(error) = sender.send(result) {
1038                            warn!("Error while sending PopErrorScope result: {error}");
1039                        }
1040                    },
1041                    WebGPURequest::ComputeGetBindGroupLayout {
1042                        device_id,
1043                        pipeline_id,
1044                        index,
1045                        id,
1046                    } => {
1047                        let global = &self.global;
1048                        let (_, error) = global.compute_pipeline_get_bind_group_layout(
1049                            pipeline_id,
1050                            index,
1051                            Some(id),
1052                        );
1053                        self.maybe_dispatch_wgpu_error(device_id, error);
1054                    },
1055                    WebGPURequest::RenderGetBindGroupLayout {
1056                        device_id,
1057                        pipeline_id,
1058                        index,
1059                        id,
1060                    } => {
1061                        let global = &self.global;
1062                        let (_, error) = global.render_pipeline_get_bind_group_layout(
1063                            pipeline_id,
1064                            index,
1065                            Some(id),
1066                        );
1067                        self.maybe_dispatch_wgpu_error(device_id, error);
1068                    },
1069                    WebGPURequest::CreateQuerySet {
1070                        device_id,
1071                        query_set_id,
1072                        descriptor,
1073                    } => {
1074                        let global = &self.global;
1075                        let (_, error) = global.device_create_query_set(
1076                            device_id,
1077                            &descriptor,
1078                            Some(query_set_id),
1079                        );
1080                        self.maybe_dispatch_wgpu_error(device_id, error);
1081                    },
1082                    WebGPURequest::CreatePlanarTexture {
1083                        device_id,
1084                        size,
1085                        format,
1086                        texture_id,
1087                        texture_view_id,
1088                    } => {
1089                        let (_, maybe_error) = self.global.device_create_texture(
1090                            device_id,
1091                            &TextureDescriptor {
1092                                label: None,
1093                                size: Extent3d {
1094                                    width: size.width,
1095                                    height: size.height,
1096                                    depth_or_array_layers: 1,
1097                                },
1098                                mip_level_count: 1,
1099                                sample_count: 1,
1100                                dimension: TextureDimension::D2,
1101                                format: match format {
1102                                    pixels::SnapshotPixelFormat::RGBA => TextureFormat::Rgba8Unorm,
1103                                    pixels::SnapshotPixelFormat::BGRA => TextureFormat::Bgra8Unorm,
1104                                },
1105                                usage: TextureUsages::COPY_DST | TextureUsages::TEXTURE_BINDING,
1106                                view_formats: Vec::new(),
1107                            },
1108                            Some(texture_id),
1109                        );
1110                        self.maybe_dispatch_error(
1111                            device_id,
1112                            maybe_error.map(|error| {
1113                                Error::Internal(format!(
1114                                    "Failed to create planar texture: {error:?}"
1115                                ))
1116                            }),
1117                        );
1118                        let (_, maybe_error) = self.global.texture_create_view(
1119                            texture_id,
1120                            &TextureViewDescriptor {
1121                                ..Default::default()
1122                            },
1123                            Some(texture_view_id),
1124                        );
1125                        self.maybe_dispatch_error(
1126                            device_id,
1127                            maybe_error.map(|error| {
1128                                Error::Internal(format!(
1129                                    "Failed to create planar texture view: {error:?}"
1130                                ))
1131                            }),
1132                        );
1133                    },
1134                    WebGPURequest::UpdatePlanarTexture {
1135                        device_id,
1136                        queue_id,
1137                        texture_id,
1138                        snapshot,
1139                    } => {
1140                        let result = self.global.queue_write_texture(
1141                            queue_id,
1142                            &TexelCopyTextureInfo {
1143                                texture: texture_id,
1144                                mip_level: 0,
1145                                origin: Origin3d::ZERO,
1146                                aspect: TextureAspect::All,
1147                            },
1148                            snapshot.data(),
1149                            &TexelCopyBufferLayout {
1150                                offset: 0,
1151                                bytes_per_row: Some(snapshot.size().width * 4),
1152                                rows_per_image: None,
1153                            },
1154                            &Extent3d {
1155                                width: snapshot.size().width,
1156                                height: snapshot.size().height,
1157                                depth_or_array_layers: 1,
1158                            },
1159                        );
1160                        self.maybe_dispatch_error(
1161                            device_id,
1162                            result.err().map(|error| {
1163                                Error::Internal(format!(
1164                                    "Failed to write planar texture: {error:?}"
1165                                ))
1166                            }),
1167                        );
1168                    },
1169                    WebGPURequest::DropPlanarTexture(id, view_id) => {
1170                        self.global.texture_view_drop(view_id);
1171                        self.global.texture_drop(id);
1172                        self.poller.wake();
1173                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeTextureView(view_id))
1174                        {
1175                            warn!("Unable to send FreeTextureView({:?}) ({:?})", view_id, e);
1176                        };
1177                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeTexture(id)) {
1178                            warn!("Unable to send FreeTexture({:?}) ({:?})", id, e);
1179                        };
1180                    },
1181                    WebGPURequest::ImportExternalTexture {
1182                        device_id,
1183                        external_texture_id,
1184                        size,
1185                        label,
1186                        plane0,
1187                    } => {
1188                        let desc = ExternalTextureDescriptor {
1189                            label: Some(label.into()),
1190                            width: size.width,
1191                            height: size.height,
1192                            format: ExternalTextureFormat::Rgba,
1193                            yuv_conversion_matrix: [0.; 16],
1194                            gamut_conversion_matrix: [
1195                                1., 0., 0., //
1196                                0., 1., 0., //
1197                                0., 0., 1., //
1198                            ],
1199                            src_transfer_function: ExternalTextureTransferFunction::default(),
1200                            dst_transfer_function: ExternalTextureTransferFunction::default(),
1201                            sample_transform: [
1202                                1., 0., //
1203                                0., 1., //
1204                                0., 0., //
1205                            ],
1206                            load_transform: [
1207                                1., 0., //
1208                                0., 1., //
1209                                0., 0., //
1210                            ],
1211                        };
1212                        if let Some(plane0) = plane0 {
1213                            let (_, maybe_error) = self.global.device_create_external_texture(
1214                                device_id,
1215                                &desc,
1216                                &[plane0],
1217                                Some(external_texture_id),
1218                            );
1219                            self.maybe_dispatch_error(
1220                                device_id,
1221                                maybe_error.map(|error| {
1222                                    Error::Internal(format!(
1223                                        "Failed to import external texture: {error:?}"
1224                                    ))
1225                                }),
1226                            );
1227                        } else {
1228                            self.global
1229                                .create_external_texture_error(Some(external_texture_id), &desc);
1230                            self.maybe_dispatch_error(
1231                                device_id,
1232                                Some(Error::Validation("Usability is not good".to_string())),
1233                            );
1234                        }
1235                    },
1236                    WebGPURequest::DestroyExternalTexture(id) => {
1237                        self.global.external_texture_destroy(id);
1238                    },
1239                    WebGPURequest::DropExternalTexture(id) => {
1240                        self.global.external_texture_drop(id);
1241                        if let Err(e) = self.script_sender.send(WebGPUMsg::FreeExternalTexture(id))
1242                        {
1243                            warn!("Unable to send FreeExternalTexture({:?}) ({:?})", id, e);
1244                        };
1245                    },
1246                    WebGPURequest::DestroyQuerySet(query_set_id) => {
1247                        self.global.query_set_destroy(query_set_id);
1248                    },
1249                    WebGPURequest::RenderBundleEncoderFinish {
1250                        render_bundle_encoder_id,
1251                        descriptor,
1252                        render_bundle_id,
1253                        device_id,
1254                    } => {
1255                        let global = &self.global;
1256                        let (_, error) = global.render_bundle_encoder_finish_with_id(
1257                            render_bundle_encoder_id,
1258                            &descriptor,
1259                            Some(render_bundle_id),
1260                        );
1261
1262                        self.maybe_dispatch_wgpu_error(device_id, error);
1263                    },
1264                    WebGPURequest::CreateRenderBundleEncoder {
1265                        device_id,
1266                        render_bundle_encoder_id,
1267                        desc,
1268                    } => {
1269                        let (_, error) = self.global.device_create_render_bundle_encoder_with_id(
1270                            device_id,
1271                            &desc,
1272                            Some(render_bundle_encoder_id),
1273                        );
1274                        self.maybe_dispatch_wgpu_error(device_id, error);
1275                    },
1276                    WebGPURequest::RenderBundleEncoderCommand {
1277                        render_bundle_encoder_id,
1278                        render_command,
1279                        device_id,
1280                    } => {
1281                        let result = handle_render_bundle_command(
1282                            &self.global,
1283                            render_bundle_encoder_id,
1284                            render_command,
1285                        );
1286                        self.maybe_dispatch_wgpu_error(device_id, result.err());
1287                    },
1288                }
1289            }
1290        }
1291        if let Err(e) = self.script_sender.send(WebGPUMsg::Exit) {
1292            warn!("Failed to send WebGPUMsg::Exit to script ({})", e);
1293        }
1294    }
1295
1296    #[inline]
1297    fn maybe_dispatch_wgpu_error<E: WebGpuError>(
1298        &mut self,
1299        device_id: id::DeviceId,
1300        error: Option<E>,
1301    ) {
1302        self.maybe_dispatch_error(device_id, error.and_then(Error::from_wgpu_error))
1303    }
1304
1305    /// Dispatches error (if there is any)
1306    fn maybe_dispatch_error(&mut self, device_id: id::DeviceId, error: Option<Error>) {
1307        if let Some(error) = error {
1308            self.dispatch_error(device_id, error);
1309        }
1310    }
1311
1312    /// <https://www.w3.org/TR/webgpu/#abstract-opdef-dispatch-error>
1313    fn dispatch_error(&mut self, device_id: id::DeviceId, error: Error) {
1314        log::trace!("Dispatching error for device {:?}: {:?}", device_id, error);
1315        let mut devices = self.devices.lock().unwrap();
1316        let device_scope = devices
1317            .get_mut(&device_id)
1318            .expect("Device should not be dropped by this point");
1319        if let Some(error_scope_stack) = &mut device_scope.error_scope_stack {
1320            if let Some(error_scope) = error_scope_stack
1321                .iter_mut()
1322                .rev()
1323                .find(|error_scope| error_scope.filter == error.filter())
1324            {
1325                error_scope.errors.push(error);
1326            } else if self
1327                .script_sender
1328                .send(WebGPUMsg::UncapturedError {
1329                    device: WebGPUDevice(device_id),
1330                    pipeline_id: device_scope.pipeline_id,
1331                    error: error.clone(),
1332                })
1333                .is_err()
1334            {
1335                warn!("Failed to send WebGPUMsg::UncapturedError: {error:?}");
1336            }
1337        } // else device is lost
1338    }
1339}