Skip to main content

script/dom/webgpu/
gpu.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::rc::Rc;
6
7use dom_struct::dom_struct;
8use js::context::JSContext;
9use js::jsapi::HandleObject;
10use js::realm::CurrentRealm;
11use script_bindings::reflector::{Reflector, reflect_dom_object_with_cx};
12use servo_constellation_traits::ScriptToConstellationMessage;
13use webgpu_traits::WebGPUAdapterResponse;
14use wgpu_types::PowerPreference;
15
16use super::wgsllanguagefeatures::WGSLLanguageFeatures;
17use crate::dom::bindings::codegen::Bindings::WebGPUBinding::{
18    GPUMethods, GPUPowerPreference, GPURequestAdapterOptions, GPUTextureFormat,
19};
20use crate::dom::bindings::error::Error;
21use crate::dom::bindings::reflector::DomGlobal;
22use crate::dom::bindings::root::{DomRoot, MutNullableDom};
23use crate::dom::bindings::str::DOMString;
24use crate::dom::globalscope::GlobalScope;
25use crate::dom::promise::Promise;
26use crate::dom::webgpu::gpuadapter::GPUAdapter;
27use crate::routed_promise::{RoutedPromiseListener, callback_promise};
28
29#[dom_struct]
30#[expect(clippy::upper_case_acronyms)]
31pub(crate) struct GPU {
32    reflector_: Reflector,
33    /// Same object for <https://www.w3.org/TR/webgpu/#dom-gpu-wgsllanguagefeatures>
34    wgsl_language_features: MutNullableDom<WGSLLanguageFeatures>,
35}
36
37impl GPU {
38    pub(crate) fn new_inherited() -> GPU {
39        GPU {
40            reflector_: Reflector::new(),
41            wgsl_language_features: MutNullableDom::default(),
42        }
43    }
44
45    pub(crate) fn new(cx: &mut JSContext, global: &GlobalScope) -> DomRoot<GPU> {
46        reflect_dom_object_with_cx(Box::new(GPU::new_inherited()), global, cx)
47    }
48}
49
50impl GPUMethods<crate::DomTypeHolder> for GPU {
51    /// <https://gpuweb.github.io/gpuweb/#dom-gpu-requestadapter>
52    fn RequestAdapter(
53        &self,
54        cx: &mut CurrentRealm,
55        options: &GPURequestAdapterOptions,
56    ) -> Rc<Promise> {
57        let global = &self.global();
58        // 1. Let promise be a new promise.
59        let promise = Promise::new_in_realm(cx);
60        let task_manager = global.task_manager();
61        let task_source = task_manager.dom_manipulation_task_source();
62        let callback = callback_promise(&promise, self, task_source);
63
64        let power_preference = match options.powerPreference {
65            Some(GPUPowerPreference::Low_power) => PowerPreference::LowPower,
66            Some(GPUPowerPreference::High_performance) => PowerPreference::HighPerformance,
67            None => PowerPreference::default(),
68        };
69        let ids = global.wgpu_id_hub().create_adapter_id();
70
71        // 3. Issue the initialization steps on the Device timeline of this
72
73        /*
74        We do some steps here to avoid IPC round-trips
75        1. options.featureLevel must be a feature level string.
76        If any are unmet
77            Let adapter be null, issue the resolution steps on contentTimeline, and return.
78        If adapter is null:
79            Resolve promise with null.
80        */
81        match &*options.featureLevel.str() {
82            "core" => {},
83            "compatibility" => {
84                // Set options.featureLevel to "compatibility" if the user agent chooses to support it, or "core" if not.
85                // and wgpu does not support "compatibility" yet so we return core for now
86            },
87            _ => {
88                promise.resolve_native(cx, &None::<GPUAdapter>);
89                return promise;
90            },
91        }
92        let script_to_constellation_chan = global.script_to_constellation_chan();
93        if script_to_constellation_chan
94            .send(ScriptToConstellationMessage::RequestAdapter(
95                callback,
96                wgpu_core::instance::RequestAdapterOptions {
97                    power_preference,
98                    compatible_surface: None,
99                    force_fallback_adapter: options.forceFallbackAdapter,
100                    apply_limit_buckets: false,
101                },
102                ids,
103            ))
104            .is_err()
105        {
106            promise.reject_error(cx, Error::Operation(None));
107        }
108        // 4. Return promise
109        promise
110    }
111
112    /// <https://gpuweb.github.io/gpuweb/#dom-gpu-getpreferredcanvasformat>
113    fn GetPreferredCanvasFormat(&self) -> GPUTextureFormat {
114        // From https://github.com/mozilla-firefox/firefox/blob/24d49101ce17b78c3ba1217d00297fe2891be6b3/dom/webgpu/Instance.h#L68
115        if cfg!(target_os = "android") {
116            GPUTextureFormat::Rgba8unorm
117        } else {
118            GPUTextureFormat::Bgra8unorm
119        }
120    }
121
122    /// <https://www.w3.org/TR/webgpu/#dom-gpu-wgsllanguagefeatures>
123    fn WgslLanguageFeatures(
124        &self,
125        cx: &mut js::context::JSContext,
126    ) -> DomRoot<WGSLLanguageFeatures> {
127        self.wgsl_language_features
128            .or_init(|| WGSLLanguageFeatures::new(cx, &self.global(), None))
129    }
130}
131
132impl RoutedPromiseListener<WebGPUAdapterResponse> for GPU {
133    fn handle_response(
134        &self,
135        cx: &mut js::context::JSContext,
136        response: WebGPUAdapterResponse,
137        promise: &Rc<Promise>,
138    ) {
139        match response {
140            Some(Ok(adapter)) => {
141                let adapter = GPUAdapter::new(
142                    cx,
143                    &self.global(),
144                    adapter.channel,
145                    DOMString::from(format!(
146                        "{} ({:?})",
147                        adapter.adapter_info.name, adapter.adapter_id.0
148                    )),
149                    HandleObject::null(),
150                    adapter.features,
151                    adapter.limits,
152                    adapter.adapter_info,
153                    adapter.adapter_id,
154                );
155                promise.resolve_native(cx, &adapter);
156            },
157            Some(Err(e)) => {
158                warn!("Could not get GPUAdapter ({:?})", e);
159                promise.resolve_native(cx, &None::<GPUAdapter>);
160            },
161            None => {
162                warn!("Couldn't get a response, because WebGPU is disabled");
163                promise.resolve_native(cx, &None::<GPUAdapter>);
164            },
165        }
166    }
167}