1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::rc::Rc;
use dom_struct::dom_struct;
use js::jsapi::{HandleObject, Heap, JSObject};
use js::realm::CurrentRealm;
use script_bindings::cformat;
use script_bindings::like::Setlike;
use script_bindings::reflector::{Reflector, reflect_dom_object_with_cx};
use webgpu_traits::{
RequestDeviceError, WebGPU, WebGPUAdapter, WebGPUDeviceResponse, WebGPURequest,
};
use wgpu_types::{self, AdapterInfo, ExperimentalFeatures, MemoryHints};
use super::gpusupportedfeatures::GPUSupportedFeatures;
use super::gpusupportedlimits::set_limit;
use crate::dom::bindings::codegen::Bindings::WebGPUBinding::{
GPUAdapterMethods, GPUDeviceDescriptor, GPUDeviceLostReason,
};
use crate::dom::bindings::error::Error;
use crate::dom::bindings::reflector::DomGlobal;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::globalscope::GlobalScope;
use crate::dom::promise::Promise;
use crate::dom::types::{GPUAdapterInfo, GPUSupportedLimits};
use crate::dom::webgpu::gpudevice::GPUDevice;
use crate::dom::webgpu::gpusupportedfeatures::gpu_to_wgt_feature;
use crate::routed_promise::{RoutedPromiseListener, callback_promise};
#[derive(JSTraceable, MallocSizeOf)]
struct DroppableGPUAdapter {
#[no_trace]
channel: WebGPU,
#[no_trace]
adapter: WebGPUAdapter,
}
impl Drop for DroppableGPUAdapter {
fn drop(&mut self) {
if let Err(e) = self
.channel
.0
.send(WebGPURequest::DropAdapter(self.adapter.0))
{
warn!(
"Failed to send WebGPURequest::DropAdapter({:?}) ({})",
self.adapter.0, e
);
};
}
}
#[dom_struct]
pub(crate) struct GPUAdapter {
reflector_: Reflector,
name: DOMString,
#[ignore_malloc_size_of = "mozjs"]
extensions: Heap<*mut JSObject>,
features: Dom<GPUSupportedFeatures>,
limits: Dom<GPUSupportedLimits>,
info: Dom<GPUAdapterInfo>,
droppable: DroppableGPUAdapter,
}
impl GPUAdapter {
fn new_inherited(
channel: WebGPU,
name: DOMString,
features: &GPUSupportedFeatures,
limits: &GPUSupportedLimits,
info: &GPUAdapterInfo,
adapter: WebGPUAdapter,
) -> Self {
Self {
reflector_: Reflector::new(),
name,
extensions: Heap::default(),
features: Dom::from_ref(features),
limits: Dom::from_ref(limits),
info: Dom::from_ref(info),
droppable: DroppableGPUAdapter { channel, adapter },
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
cx: &mut js::context::JSContext,
global: &GlobalScope,
channel: WebGPU,
name: DOMString,
extensions: HandleObject,
features: wgpu_types::Features,
limits: wgpu_types::Limits,
info: wgpu_types::AdapterInfo,
adapter: WebGPUAdapter,
) -> DomRoot<Self> {
let features = GPUSupportedFeatures::Constructor(cx, global, None, features).unwrap();
let limits = GPUSupportedLimits::new(cx, global, limits);
let info = GPUAdapter::create_adapter_info(cx, global, info, &features);
let dom_root = reflect_dom_object_with_cx(
Box::new(GPUAdapter::new_inherited(
channel, name, &features, &limits, &info, adapter,
)),
global,
cx,
);
dom_root.extensions.set(*extensions);
dom_root
}
/// <https://gpuweb.github.io/gpuweb/#abstract-opdef-new-adapter-info>
fn create_adapter_info(
cx: &mut js::context::JSContext,
global: &GlobalScope,
info: AdapterInfo,
features: &GPUSupportedFeatures,
) -> DomRoot<GPUAdapterInfo> {
// Step 2. If the vendor is known, set adapterInfo.vendor to the name of adapter’s vendor as
// a normalized identifier string. To preserve privacy, the user agent may instead set
// adapterInfo.vendor to the empty string or a reasonable approximation of the vendor as a
// normalized identifier string.
let vendor = if info.vendor != 0 {
info.vendor.to_string().into()
} else {
DOMString::new()
};
// Step 3. If the architecture is known, set adapterInfo.architecture to a normalized
// identifier string representing the family or class of adapters to which adapter belongs.
// To preserve privacy, the user agent may instead set adapterInfo.architecture to the empty
// string or a reasonable approximation of the architecture as a normalized identifier
// string.
// TODO: AdapterInfo::architecture missing
// https://github.com/gfx-rs/wgpu/issues/2170
let architecture = DOMString::new();
// Step 4. If the device is known, set adapterInfo.device to a normalized identifier string
// representing a vendor-specific identifier for adapter. To preserve privacy, the user
// agent may instead set adapterInfo.device to to the empty string or a reasonable
// approximation of a vendor-specific identifier as a normalized identifier string.
let device = if info.device != 0 {
info.device.to_string().into()
} else {
DOMString::new()
};
// Step 5. If a description is known, set adapterInfo.description to a description of the
// adapter as reported by the driver. To preserve privacy, the user agent may instead set
// adapterInfo.description to the empty string or a reasonable approximation of a
// description.
let description = info.name.clone().into();
// Step 6. If "subgroups" is supported, set subgroupMinSize to the smallest supported
// subgroup size. Otherwise, set this value to 4.
// Step 7. If "subgroups" is supported, set subgroupMaxSize to the largest supported
// subgroup size. Otherwise, set this value to 128.
let (subgroup_min_size, subgroup_max_size) = if features.has("subgroups".into()) {
(info.subgroup_min_size, info.subgroup_max_size)
} else {
(4, 128)
};
// Step 8. Set adapterInfo.isFallbackAdapter to adapter.[[fallback]].
let is_fallback_adapter = info.device_type == wgpu_types::DeviceType::Cpu;
// Step 1. Let adapterInfo be a new GPUAdapterInfo.
GPUAdapterInfo::new(
cx,
global,
vendor,
architecture,
device,
description,
subgroup_min_size,
subgroup_max_size,
is_fallback_adapter,
)
}
}
impl GPUAdapterMethods<crate::DomTypeHolder> for GPUAdapter {
/// <https://gpuweb.github.io/gpuweb/#dom-gpuadapter-requestdevice>
fn RequestDevice(
&self,
cx: &mut CurrentRealm<'_>,
descriptor: &GPUDeviceDescriptor,
) -> Rc<Promise> {
// Step 2
let promise = Promise::new_in_realm(cx);
let callback = callback_promise(
&promise,
self,
self.global().task_manager().dom_manipulation_task_source(),
);
let mut required_features = wgpu_types::Features::empty();
for &ext in descriptor.requiredFeatures.iter() {
if let Some(feature) = gpu_to_wgt_feature(ext) {
required_features.insert(feature);
} else {
promise.reject_error(
cx,
Error::Type(cformat!("{} is not supported feature", ext.as_str())),
);
return promise;
}
}
let mut required_limits = wgpu_types::Limits::default();
if let Some(limits) = &descriptor.requiredLimits {
for (limit, value) in (*limits).iter() {
if !set_limit(&mut required_limits, &limit.str(), *value) {
warn!("Unknown GPUDevice limit: {limit}");
promise.reject_error(cx, Error::Operation(None));
return promise;
}
}
}
let desc = wgpu_types::DeviceDescriptor {
required_features,
required_limits,
label: Some(descriptor.parent.label.to_string()),
memory_hints: MemoryHints::MemoryUsage,
trace: wgpu_types::Trace::Off,
experimental_features: ExperimentalFeatures::disabled(),
};
let device_id = self.global().wgpu_id_hub().create_device_id();
let queue_id = self.global().wgpu_id_hub().create_queue_id();
let pipeline_id = self.global().pipeline_id();
if self
.droppable
.channel
.0
.send(WebGPURequest::RequestDevice {
sender: callback,
adapter_id: self.droppable.adapter,
descriptor: desc,
device_id,
queue_id,
pipeline_id,
})
.is_err()
{
promise.reject_error(cx, Error::Operation(None));
}
// Step 5
promise
}
/// <https://gpuweb.github.io/gpuweb/#dom-gpuadapter-features>
fn Features(&self) -> DomRoot<GPUSupportedFeatures> {
DomRoot::from_ref(&self.features)
}
/// <https://gpuweb.github.io/gpuweb/#dom-gpuadapter-limits>
fn Limits(&self) -> DomRoot<GPUSupportedLimits> {
DomRoot::from_ref(&self.limits)
}
/// <https://gpuweb.github.io/gpuweb/#dom-gpuadapter-info>
fn Info(&self) -> DomRoot<GPUAdapterInfo> {
DomRoot::from_ref(&self.info)
}
}
impl RoutedPromiseListener<WebGPUDeviceResponse> for GPUAdapter {
/// <https://www.w3.org/TR/webgpu/#dom-gpuadapter-requestdevice>
fn handle_response(
&self,
cx: &mut js::context::JSContext,
response: WebGPUDeviceResponse,
promise: &Rc<Promise>,
) {
match response {
// 3.1 Let device be a new device with the capabilities described by descriptor.
(device_id, queue_id, Ok(descriptor)) => {
let device = GPUDevice::new(
cx,
&self.global(),
self.droppable.channel.clone(),
self,
HandleObject::null(),
descriptor.required_features,
descriptor.required_limits,
device_id,
queue_id,
descriptor.label.unwrap_or_default(),
);
self.global().add_gpu_device(&device);
promise.resolve_native(cx, &device);
},
// 1. If features are not supported reject promise with a TypeError.
(_, _, Err(RequestDeviceError::UnsupportedFeature(f))) => promise.reject_error(
cx,
Error::Type(cformat!(
"{}",
wgpu_core::instance::RequestDeviceError::UnsupportedFeature(f)
)),
),
// 2. If limits are not supported reject promise with an OperationError.
(_, _, Err(RequestDeviceError::LimitsExceeded(l))) => {
warn!(
"{}",
wgpu_core::instance::RequestDeviceError::LimitsExceeded(l)
);
promise.reject_error(cx, Error::Operation(None))
},
// 3. user agent otherwise cannot fulfill the request
(device_id, queue_id, Err(RequestDeviceError::Other(e))) => {
// TODO(sagudev): firefox always says operation error,
// meanwhile we create "invalid" device that is not invalid in wgpu
// causing crashes when one tries to use it
// 1. Let device be a new device.
let device = GPUDevice::new(
cx,
&self.global(),
self.droppable.channel.clone(),
self,
HandleObject::null(),
wgpu_types::Features::default(),
wgpu_types::Limits::default(),
device_id,
queue_id,
String::new(),
);
// 2. Lose the device(device, "unknown").
device.lose(GPUDeviceLostReason::Unknown, e);
promise.resolve_native(cx, &device);
},
}
}
}