Skip to main content

script_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::marker::PhantomData;
6use std::rc::Rc;
7
8use dom_struct::dom_struct;
9use js::context::JSContext;
10use js::realm::CurrentRealm;
11use jstraceable_derive::JSTraceable;
12use malloc_size_of_derive::MallocSizeOf;
13use script_bindings::DomTypes;
14use script_bindings::codegen::GenericBindings::WebGPUBinding::{
15    GPUMethods, GPUPowerPreference, GPURequestAdapterOptions, GPUTextureFormat, GPUWrap,
16};
17use script_bindings::dom::MutNullableDom;
18use script_bindings::interfaces::{GlobalScopeHelpers, PromiseHelpers};
19use script_bindings::reflector::{DomGlobalGeneric, Reflector, reflect_dom_object_with_wrap};
20use script_bindings::root::DomRoot;
21use servo_constellation_traits::ScriptToConstellationMessage;
22use wgpu_types::PowerPreference;
23
24use super::wgsllanguagefeatures::WGSLLanguageFeatures;
25use crate::dom::bindings::error::Error;
26use crate::gpuadapter::GPUAdapter;
27use crate::traits::{WebGPUGlobalTrait, WebGPUPromiseTrait};
28
29#[dom_struct]
30pub struct GPU<D: DomTypes> {
31    reflector_: Reflector,
32    /// Same object for <https://www.w3.org/TR/webgpu/#dom-gpu-wgsllanguagefeatures>
33    wgsl_language_features: MutNullableDom<WGSLLanguageFeatures<D>>,
34    #[no_trace = "PhantomData does not exist"]
35    phantom: PhantomData<D>,
36}
37
38impl<D> GPU<D>
39where
40    D: DomTypes<GPU = GPU<D>>,
41{
42    pub(crate) fn new_inherited() -> GPU<D> {
43        GPU {
44            reflector_: Reflector::new(),
45            wgsl_language_features: MutNullableDom::default(),
46            phantom: PhantomData,
47        }
48    }
49
50    pub fn new(cx: &mut JSContext, global: &D::GlobalScope) -> DomRoot<GPU<D>> {
51        reflect_dom_object_with_wrap::<D, _, _>(
52            Box::new(GPU::new_inherited()),
53            global,
54            cx,
55            GPUWrap::<D>,
56        )
57    }
58
59    fn global(&self) -> DomRoot<D::GlobalScope> {
60        <D::GPU as DomGlobalGeneric<D>>::global_from_reflector(self)
61    }
62}
63
64impl<D: DomTypes> GPUMethods<D> for GPU<D>
65where
66    D: DomTypes<GPU = GPU<D>, WGSLLanguageFeatures = WGSLLanguageFeatures<D>>,
67    D::Promise: PromiseHelpers<D> + WebGPUPromiseTrait<D>,
68    D::GPU: DomGlobalGeneric<D>,
69    D::GlobalScope: WebGPUGlobalTrait,
70{
71    /// <https://gpuweb.github.io/gpuweb/#dom-gpu-requestadapter>
72    fn RequestAdapter(
73        &self,
74        cx: &mut CurrentRealm,
75        options: &GPURequestAdapterOptions,
76    ) -> Rc<D::Promise> {
77        let global = &self.global();
78        // 1. Let promise be a new promise.
79        let promise = D::Promise::new_in_realm(cx);
80        let callback = D::Promise::callback_promise_gpu(&promise, self);
81
82        let power_preference = match options.powerPreference {
83            Some(GPUPowerPreference::Low_power) => PowerPreference::LowPower,
84            Some(GPUPowerPreference::High_performance) => PowerPreference::HighPerformance,
85            None => PowerPreference::default(),
86        };
87        let ids = global.global_wgpu_id_hub().create_adapter_id();
88
89        // 3. Issue the initialization steps on the Device timeline of this
90
91        /*
92        We do some steps here to avoid IPC round-trips
93        1. options.featureLevel must be a feature level string.
94        If any are unmet
95            Let adapter be null, issue the resolution steps on contentTimeline, and return.
96        If adapter is null:
97            Resolve promise with null.
98        */
99        match &*options.featureLevel.str() {
100            "core" => {},
101            "compatibility" => {
102                // Set options.featureLevel to "compatibility" if the user agent chooses to support it, or "core" if not.
103                // and wgpu does not support "compatibility" yet so we return core for now
104            },
105            _ => {
106                promise.resolve_native(cx, &None::<GPUAdapter<D>>);
107                return promise;
108            },
109        }
110        let script_to_constellation_chan = global.script_to_constellation_chan();
111        if script_to_constellation_chan
112            .send(ScriptToConstellationMessage::RequestAdapter(
113                callback,
114                wgpu_core::instance::RequestAdapterOptions {
115                    power_preference,
116                    compatible_surface: None,
117                    force_fallback_adapter: options.forceFallbackAdapter,
118                    apply_limit_buckets: false,
119                },
120                ids,
121            ))
122            .is_err()
123        {
124            promise.reject_error(
125                cx,
126                Error::Operation(Some("Could not request adapter".into())),
127            );
128        }
129        // 4. Return promise
130        promise
131    }
132
133    /// <https://gpuweb.github.io/gpuweb/#dom-gpu-getpreferredcanvasformat>
134    fn GetPreferredCanvasFormat(&self) -> GPUTextureFormat {
135        // From https://github.com/mozilla-firefox/firefox/blob/24d49101ce17b78c3ba1217d00297fe2891be6b3/dom/webgpu/Instance.h#L68
136        if cfg!(target_os = "android") {
137            GPUTextureFormat::Rgba8unorm
138        } else {
139            GPUTextureFormat::Bgra8unorm
140        }
141    }
142
143    /// <https://www.w3.org/TR/webgpu/#dom-gpu-wgsllanguagefeatures>
144    fn WgslLanguageFeatures(
145        &self,
146        cx: &mut js::context::JSContext,
147    ) -> DomRoot<WGSLLanguageFeatures<D>> {
148        self.wgsl_language_features
149            .or_init(|| WGSLLanguageFeatures::new(cx, &*self.global(), None))
150    }
151}