Only start WebGPU thread if an adapter is requested

This commit is contained in:
Zakor Gyula 2019-11-20 09:03:10 +01:00
parent f8c957dc1b
commit a751b1c3d7
15 changed files with 200 additions and 147 deletions

1
Cargo.lock generated
View file

@ -4639,6 +4639,7 @@ dependencies = [
"serde", "serde",
"servo_atoms", "servo_atoms",
"servo_url", "servo_url",
"smallvec 0.6.10",
"style_traits", "style_traits",
"time", "time",
"url", "url",

View file

@ -173,7 +173,7 @@ use std::sync::Arc;
use std::thread; use std::thread;
use style_traits::viewport::ViewportConstraints; use style_traits::viewport::ViewportConstraints;
use style_traits::CSSPixel; use style_traits::CSSPixel;
use webgpu::WebGPU; use webgpu::{WebGPU, WebGPURequest};
use webvr_traits::{WebVREvent, WebVRMsg}; use webvr_traits::{WebVREvent, WebVRMsg};
type PendingApprovalNavigations = HashMap<PipelineId, (LoadData, HistoryEntryReplacement)>; type PendingApprovalNavigations = HashMap<PipelineId, (LoadData, HistoryEntryReplacement)>;
@ -242,6 +242,9 @@ struct BrowsingContextGroup {
/// share an event loop, since they can use `document.domain` /// share an event loop, since they can use `document.domain`
/// to become same-origin, at which point they can share DOM objects. /// to become same-origin, at which point they can share DOM objects.
event_loops: HashMap<Host, Weak<EventLoop>>, event_loops: HashMap<Host, Weak<EventLoop>>,
/// The set of all WebGPU channels in this BrowsingContextGroup.
webgpus: HashMap<Host, WebGPU>,
} }
/// The `Constellation` itself. In the servo browser, there is one /// The `Constellation` itself. In the servo browser, there is one
@ -450,10 +453,6 @@ pub struct Constellation<Message, LTF, STF> {
/// Entry point to create and get channels to a WebGLThread. /// Entry point to create and get channels to a WebGLThread.
webgl_threads: Option<WebGLThreads>, webgl_threads: Option<WebGLThreads>,
/// An IPC channel for the constellation to send messages to the
/// WebGPU threads.
webgpu: Option<WebGPU>,
/// A channel through which messages can be sent to the webvr thread. /// A channel through which messages can be sent to the webvr thread.
webvr_chan: Option<IpcSender<WebVRMsg>>, webvr_chan: Option<IpcSender<WebVRMsg>>,
@ -537,9 +536,6 @@ pub struct InitialConstellationState {
/// Entry point to create and get channels to a WebGLThread. /// Entry point to create and get channels to a WebGLThread.
pub webgl_threads: Option<WebGLThreads>, pub webgl_threads: Option<WebGLThreads>,
/// A channel to the WebGPU threads.
pub webgpu: Option<WebGPU>,
/// A channel to the webgl thread. /// A channel to the webgl thread.
pub webvr_chan: Option<IpcSender<WebVRMsg>>, pub webvr_chan: Option<IpcSender<WebVRMsg>>,
@ -973,7 +969,6 @@ where
(rng, prob) (rng, prob)
}), }),
webgl_threads: state.webgl_threads, webgl_threads: state.webgl_threads,
webgpu: state.webgpu,
webvr_chan: state.webvr_chan, webvr_chan: state.webvr_chan,
webxr_registry: state.webxr_registry, webxr_registry: state.webxr_registry,
canvas_chan, canvas_chan,
@ -1230,7 +1225,6 @@ where
.webgl_threads .webgl_threads
.as_ref() .as_ref()
.map(|threads| threads.pipeline()), .map(|threads| threads.pipeline()),
webgpu: self.webgpu.clone(),
webvr_chan: self.webvr_chan.clone(), webvr_chan: self.webvr_chan.clone(),
webxr_registry: self.webxr_registry.clone(), webxr_registry: self.webxr_registry.clone(),
player_context: self.player_context.clone(), player_context: self.player_context.clone(),
@ -1945,9 +1939,65 @@ where
EmbedderMsg::MediaSessionEvent(event), EmbedderMsg::MediaSessionEvent(event),
)); ));
}, },
FromScriptMsg::RequestAdapter(sender, options, ids) => self
.handle_request_wgpu_adapter(
source_pipeline_id,
BrowsingContextId::from(source_top_ctx_id),
FromScriptMsg::RequestAdapter(sender, options, ids),
),
} }
} }
fn handle_request_wgpu_adapter(
&mut self,
source_pipeline_id: PipelineId,
browsing_context_id: BrowsingContextId,
request: FromScriptMsg,
) {
let browsing_context_group_id = match self.browsing_contexts.get(&browsing_context_id) {
Some(bc) => &bc.bc_group_id,
None => return warn!("Browsing context not found"),
};
let host = match self
.pipelines
.get(&source_pipeline_id)
.map(|pipeline| &pipeline.url)
{
Some(ref url) => match reg_host(&url) {
Some(host) => host,
None => return warn!("Invalid host url"),
},
None => return warn!("ScriptMsg from closed pipeline {:?}.", source_pipeline_id),
};
match self
.browsing_context_group_set
.get_mut(&browsing_context_group_id)
{
Some(browsing_context_group) => {
let adapter_request =
if let FromScriptMsg::RequestAdapter(sender, options, ids) = request {
WebGPURequest::RequestAdapter(sender, options, ids)
} else {
return warn!("Wrong message type in handle_request_wgpu_adapter");
};
let send = match browsing_context_group.webgpus.entry(host) {
Entry::Vacant(v) => v
.insert(match WebGPU::new() {
Some(webgpu) => webgpu,
None => return warn!("Failed to create new WebGPU thread"),
})
.0
.send(adapter_request),
Entry::Occupied(o) => o.get().0.send(adapter_request),
};
if send.is_err() {
return warn!("Failed to send request adapter message on WebGPU channel");
}
},
None => return warn!("Browsing context group not found"),
};
}
fn handle_request_from_layout(&mut self, message: FromLayoutMsg) { fn handle_request_from_layout(&mut self, message: FromLayoutMsg) {
debug!("Constellation got {:?} message", message); debug!("Constellation got {:?} message", message);
match message { match message {
@ -2496,12 +2546,25 @@ where
} }
} }
if let Some(webgpu) = self.webgpu.as_ref() { debug!("Exiting WebGPU threads.");
debug!("Exiting WebGPU thread."); let receivers = self
.browsing_context_group_set
.values()
.map(|browsing_context_group| {
browsing_context_group.webgpus.values().map(|webgpu| {
let (sender, receiver) = ipc::channel().expect("Failed to create IPC channel!"); let (sender, receiver) = ipc::channel().expect("Failed to create IPC channel!");
if let Err(e) = webgpu.exit(sender) { if let Err(e) = webgpu.exit(sender) {
warn!("Exit WebGPU Thread failed ({})", e); warn!("Exit WebGPU Thread failed ({})", e);
None
} else {
Some(receiver)
} }
})
})
.flatten()
.filter_map(|r| r);
for receiver in receivers {
if let Err(e) = receiver.recv() { if let Err(e) = receiver.recv() {
warn!("Failed to receive exit response from WebGPU ({})", e); warn!("Failed to receive exit response from WebGPU ({})", e);
} }

View file

@ -48,7 +48,6 @@ use std::process;
use std::rc::Rc; use std::rc::Rc;
use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicBool;
use std::sync::Arc; use std::sync::Arc;
use webgpu::WebGPU;
use webvr_traits::WebVRMsg; use webvr_traits::WebVRMsg;
/// A `Pipeline` is the constellation's view of a `Document`. Each pipeline has an /// A `Pipeline` is the constellation's view of a `Document`. Each pipeline has an
@ -194,9 +193,6 @@ pub struct InitialPipelineState {
/// A channel to the WebGL thread. /// A channel to the WebGL thread.
pub webgl_chan: Option<WebGLPipeline>, pub webgl_chan: Option<WebGLPipeline>,
/// A channel to the WebGPU threads.
pub webgpu: Option<WebGPU>,
/// A channel to the webvr thread. /// A channel to the webvr thread.
pub webvr_chan: Option<IpcSender<WebVRMsg>>, pub webvr_chan: Option<IpcSender<WebVRMsg>>,
@ -309,7 +305,6 @@ impl Pipeline {
webrender_document: state.webrender_document, webrender_document: state.webrender_document,
webgl_chan: state.webgl_chan, webgl_chan: state.webgl_chan,
webvr_chan: state.webvr_chan, webvr_chan: state.webvr_chan,
webgpu: state.webgpu,
webxr_registry: state.webxr_registry, webxr_registry: state.webxr_registry,
player_context: state.player_context, player_context: state.player_context,
}; };
@ -516,7 +511,6 @@ pub struct UnprivilegedPipelineContent {
webrender_image_api_sender: net_traits::WebrenderIpcSender, webrender_image_api_sender: net_traits::WebrenderIpcSender,
webrender_document: webrender_api::DocumentId, webrender_document: webrender_api::DocumentId,
webgl_chan: Option<WebGLPipeline>, webgl_chan: Option<WebGLPipeline>,
webgpu: Option<WebGPU>,
webvr_chan: Option<IpcSender<WebVRMsg>>, webvr_chan: Option<IpcSender<WebVRMsg>>,
webxr_registry: webxr_api::Registry, webxr_registry: webxr_api::Registry,
player_context: WindowGLContext, player_context: WindowGLContext,
@ -569,7 +563,6 @@ impl UnprivilegedPipelineContent {
pipeline_namespace_id: self.pipeline_namespace_id, pipeline_namespace_id: self.pipeline_namespace_id,
content_process_shutdown_chan: content_process_shutdown_chan, content_process_shutdown_chan: content_process_shutdown_chan,
webgl_chan: self.webgl_chan, webgl_chan: self.webgl_chan,
webgpu: self.webgpu,
webvr_chan: self.webvr_chan, webvr_chan: self.webvr_chan,
webxr_registry: self.webxr_registry, webxr_registry: self.webxr_registry,
webrender_document: self.webrender_document, webrender_document: self.webrender_document,

View file

@ -521,6 +521,7 @@ unsafe_no_jsmanaged_fields!(WebGLTextureId);
unsafe_no_jsmanaged_fields!(WebGLVertexArrayId); unsafe_no_jsmanaged_fields!(WebGLVertexArrayId);
unsafe_no_jsmanaged_fields!(WebGLVersion); unsafe_no_jsmanaged_fields!(WebGLVersion);
unsafe_no_jsmanaged_fields!(WebGLSLVersion); unsafe_no_jsmanaged_fields!(WebGLSLVersion);
unsafe_no_jsmanaged_fields!(RefCell<Option<WebGPU>>);
unsafe_no_jsmanaged_fields!(RefCell<Identities>); unsafe_no_jsmanaged_fields!(RefCell<Identities>);
unsafe_no_jsmanaged_fields!(WebGPU); unsafe_no_jsmanaged_fields!(WebGPU);
unsafe_no_jsmanaged_fields!(WebGPUAdapter); unsafe_no_jsmanaged_fields!(WebGPUAdapter);

View file

@ -19,9 +19,10 @@ use dom_struct::dom_struct;
use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::router::ROUTER; use ipc_channel::router::ROUTER;
use js::jsapi::Heap; use js::jsapi::Heap;
use script_traits::ScriptMsg;
use std::rc::Rc; use std::rc::Rc;
use webgpu::wgpu; use webgpu::wgpu;
use webgpu::{WebGPU, WebGPURequest, WebGPUResponse, WebGPUResponseResult}; use webgpu::{WebGPUResponse, WebGPUResponseResult};
#[dom_struct] #[dom_struct]
pub struct GPU { pub struct GPU {
@ -38,10 +39,6 @@ impl GPU {
pub fn new(global: &GlobalScope) -> DomRoot<GPU> { pub fn new(global: &GlobalScope) -> DomRoot<GPU> {
reflect_dom_object(Box::new(GPU::new_inherited()), global, GPUBinding::Wrap) reflect_dom_object(Box::new(GPU::new_inherited()), global, GPUBinding::Wrap)
} }
fn wgpu_channel(&self) -> Option<WebGPU> {
self.global().as_window().webgpu_channel()
}
} }
pub trait AsyncWGPUListener { pub trait AsyncWGPUListener {
@ -114,7 +111,8 @@ impl GPUMethods for GPU {
options: &GPURequestAdapterOptions, options: &GPURequestAdapterOptions,
comp: InCompartment, comp: InCompartment,
) -> Rc<Promise> { ) -> Rc<Promise> {
let promise = Promise::new_in_current_compartment(&self.global(), comp); let global = &self.global();
let promise = Promise::new_in_current_compartment(global, comp);
let sender = response_async(&promise, self); let sender = response_async(&promise, self);
let power_preference = match options.powerPreference { let power_preference = match options.powerPreference {
Some(GPUPowerPreference::Low_power) => wgpu::instance::PowerPreference::LowPower, Some(GPUPowerPreference::Low_power) => wgpu::instance::PowerPreference::LowPower,
@ -123,21 +121,21 @@ impl GPUMethods for GPU {
}, },
None => wgpu::instance::PowerPreference::Default, None => wgpu::instance::PowerPreference::Default,
}; };
let ids = self.global().as_window().Navigator().create_adapter_ids(); let ids = global.as_window().Navigator().create_adapter_ids();
match self.wgpu_channel() { let script_to_constellation_chan = global.script_to_constellation_chan();
Some(channel) => { if script_to_constellation_chan
channel .send(ScriptMsg::RequestAdapter(
.0
.send(WebGPURequest::RequestAdapter(
sender, sender,
wgpu::instance::RequestAdapterOptions { power_preference }, wgpu::instance::RequestAdapterOptions { power_preference },
ids, ids,
)) ))
.unwrap(); .is_err()
}, {
None => promise.reject_error(Error::Type("No WebGPU thread...".to_owned())), promise.reject_error(Error::Type(
}; "Failed to send adapter request to constellation...".to_owned(),
));
}
promise promise
} }
} }
@ -145,9 +143,10 @@ impl GPUMethods for GPU {
impl AsyncWGPUListener for GPU { impl AsyncWGPUListener for GPU {
fn handle_response(&self, response: WebGPUResponse, promise: &Rc<Promise>) { fn handle_response(&self, response: WebGPUResponse, promise: &Rc<Promise>) {
match response { match response {
WebGPUResponse::RequestAdapter(name, adapter) => { WebGPUResponse::RequestAdapter(name, adapter, channel) => {
let adapter = GPUAdapter::new( let adapter = GPUAdapter::new(
&self.global(), &self.global(),
channel,
DOMString::from(format!("{} ({:?})", name, adapter.0.backend())), DOMString::from(format!("{} ({:?})", name, adapter.0.backend())),
Heap::default(), Heap::default(),
adapter, adapter,

View file

@ -23,11 +23,13 @@ use dom_struct::dom_struct;
use js::jsapi::{Heap, JSObject}; use js::jsapi::{Heap, JSObject};
use std::ptr::NonNull; use std::ptr::NonNull;
use std::rc::Rc; use std::rc::Rc;
use webgpu::{wgpu, WebGPUAdapter, WebGPURequest, WebGPUResponse}; use webgpu::{wgpu, WebGPU, WebGPUAdapter, WebGPURequest, WebGPUResponse};
#[dom_struct] #[dom_struct]
pub struct GPUAdapter { pub struct GPUAdapter {
reflector_: Reflector, reflector_: Reflector,
#[ignore_malloc_size_of = "channels are hard"]
channel: WebGPU,
name: DOMString, name: DOMString,
#[ignore_malloc_size_of = "mozjs"] #[ignore_malloc_size_of = "mozjs"]
extensions: Heap<*mut JSObject>, extensions: Heap<*mut JSObject>,
@ -36,12 +38,14 @@ pub struct GPUAdapter {
impl GPUAdapter { impl GPUAdapter {
pub fn new_inherited( pub fn new_inherited(
channel: WebGPU,
name: DOMString, name: DOMString,
extensions: Heap<*mut JSObject>, extensions: Heap<*mut JSObject>,
adapter: WebGPUAdapter, adapter: WebGPUAdapter,
) -> GPUAdapter { ) -> GPUAdapter {
GPUAdapter { GPUAdapter {
reflector_: Reflector::new(), reflector_: Reflector::new(),
channel,
name, name,
extensions, extensions,
adapter, adapter,
@ -50,12 +54,15 @@ impl GPUAdapter {
pub fn new( pub fn new(
global: &GlobalScope, global: &GlobalScope,
channel: WebGPU,
name: DOMString, name: DOMString,
extensions: Heap<*mut JSObject>, extensions: Heap<*mut JSObject>,
adapter: WebGPUAdapter, adapter: WebGPUAdapter,
) -> DomRoot<GPUAdapter> { ) -> DomRoot<GPUAdapter> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUAdapter::new_inherited(name, extensions, adapter)), Box::new(GPUAdapter::new_inherited(
channel, name, extensions, adapter,
)),
global, global,
GPUAdapterBinding::Wrap, GPUAdapterBinding::Wrap,
) )
@ -89,12 +96,15 @@ impl GPUAdapterMethods for GPUAdapter {
let id = window let id = window
.Navigator() .Navigator()
.create_device_id(self.adapter.0.backend()); .create_device_id(self.adapter.0.backend());
match window.webgpu_channel() { if self
Some(thread) => thread .channel
.0 .0
.send(WebGPURequest::RequestDevice(sender, self.adapter, desc, id)) .send(WebGPURequest::RequestDevice(sender, self.adapter, desc, id))
.unwrap(), .is_err()
None => promise.reject_error(Error::Type("No WebGPU thread...".to_owned())), {
promise.reject_error(Error::Type(
"Failed to send RequestDevice message...".to_owned(),
));
} }
} else { } else {
promise.reject_error(Error::Type("No WebGPU thread...".to_owned())) promise.reject_error(Error::Type("No WebGPU thread...".to_owned()))
@ -109,6 +119,7 @@ impl AsyncWGPUListener for GPUAdapter {
WebGPUResponse::RequestDevice(device_id, _descriptor) => { WebGPUResponse::RequestDevice(device_id, _descriptor) => {
let device = GPUDevice::new( let device = GPUDevice::new(
&self.global(), &self.global(),
self.channel.clone(),
&self, &self,
Heap::default(), Heap::default(),
Heap::default(), Heap::default(),

View file

@ -11,9 +11,8 @@ use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString; use crate::dom::bindings::str::DOMString;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use ipc_channel::ipc::IpcSender;
use std::cell::Cell; use std::cell::Cell;
use webgpu::{WebGPUBuffer, WebGPUDevice, WebGPURequest}; use webgpu::{WebGPU, WebGPUBuffer, WebGPUDevice, WebGPURequest};
#[derive(MallocSizeOf)] #[derive(MallocSizeOf)]
pub enum GPUBufferState { pub enum GPUBufferState {
@ -26,7 +25,7 @@ pub enum GPUBufferState {
pub struct GPUBuffer { pub struct GPUBuffer {
reflector_: Reflector, reflector_: Reflector,
#[ignore_malloc_size_of = "channels are hard"] #[ignore_malloc_size_of = "channels are hard"]
channel: IpcSender<WebGPURequest>, channel: WebGPU,
label: DomRefCell<Option<DOMString>>, label: DomRefCell<Option<DOMString>>,
size: GPUBufferSize, size: GPUBufferSize,
usage: u32, usage: u32,
@ -38,7 +37,7 @@ pub struct GPUBuffer {
impl GPUBuffer { impl GPUBuffer {
fn new_inherited( fn new_inherited(
channel: IpcSender<WebGPURequest>, channel: WebGPU,
buffer: WebGPUBuffer, buffer: WebGPUBuffer,
device: WebGPUDevice, device: WebGPUDevice,
state: GPUBufferState, state: GPUBufferState,
@ -62,7 +61,7 @@ impl GPUBuffer {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn new( pub fn new(
global: &GlobalScope, global: &GlobalScope,
channel: IpcSender<WebGPURequest>, channel: WebGPU,
buffer: WebGPUBuffer, buffer: WebGPUBuffer,
device: WebGPUDevice, device: WebGPUDevice,
state: GPUBufferState, state: GPUBufferState,
@ -90,6 +89,7 @@ impl GPUBufferMethods for GPUBuffer {
/// https://gpuweb.github.io/gpuweb/#dom-gpubuffer-unmap /// https://gpuweb.github.io/gpuweb/#dom-gpubuffer-unmap
fn Unmap(&self) { fn Unmap(&self) {
self.channel self.channel
.0
.send(WebGPURequest::UnmapBuffer(self.buffer)) .send(WebGPURequest::UnmapBuffer(self.buffer))
.unwrap(); .unwrap();
} }
@ -103,6 +103,7 @@ impl GPUBufferMethods for GPUBuffer {
_ => {}, _ => {},
}; };
self.channel self.channel
.0
.send(WebGPURequest::DestroyBuffer(self.buffer)) .send(WebGPURequest::DestroyBuffer(self.buffer))
.unwrap(); .unwrap();
*self.state.borrow_mut() = GPUBufferState::Destroyed; *self.state.borrow_mut() = GPUBufferState::Destroyed;

View file

@ -25,11 +25,13 @@ use js::jsval::{JSVal, ObjectValue, UndefinedValue};
use js::typedarray::{ArrayBuffer, CreateWith}; use js::typedarray::{ArrayBuffer, CreateWith};
use std::ptr::{self, NonNull}; use std::ptr::{self, NonNull};
use webgpu::wgpu::resource::{BufferDescriptor, BufferUsage}; use webgpu::wgpu::resource::{BufferDescriptor, BufferUsage};
use webgpu::{WebGPUBuffer, WebGPUDevice, WebGPURequest}; use webgpu::{WebGPU, WebGPUBuffer, WebGPUDevice, WebGPURequest};
#[dom_struct] #[dom_struct]
pub struct GPUDevice { pub struct GPUDevice {
eventtarget: EventTarget, eventtarget: EventTarget,
#[ignore_malloc_size_of = "channels are hard"]
channel: WebGPU,
adapter: Dom<GPUAdapter>, adapter: Dom<GPUAdapter>,
#[ignore_malloc_size_of = "mozjs"] #[ignore_malloc_size_of = "mozjs"]
extensions: Heap<*mut JSObject>, extensions: Heap<*mut JSObject>,
@ -41,6 +43,7 @@ pub struct GPUDevice {
impl GPUDevice { impl GPUDevice {
fn new_inherited( fn new_inherited(
channel: WebGPU,
adapter: &GPUAdapter, adapter: &GPUAdapter,
extensions: Heap<*mut JSObject>, extensions: Heap<*mut JSObject>,
limits: Heap<*mut JSObject>, limits: Heap<*mut JSObject>,
@ -48,6 +51,7 @@ impl GPUDevice {
) -> GPUDevice { ) -> GPUDevice {
Self { Self {
eventtarget: EventTarget::new_inherited(), eventtarget: EventTarget::new_inherited(),
channel,
adapter: Dom::from_ref(adapter), adapter: Dom::from_ref(adapter),
extensions, extensions,
limits, limits,
@ -59,6 +63,7 @@ impl GPUDevice {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn new( pub fn new(
global: &GlobalScope, global: &GlobalScope,
channel: WebGPU,
adapter: &GPUAdapter, adapter: &GPUAdapter,
extensions: Heap<*mut JSObject>, extensions: Heap<*mut JSObject>,
limits: Heap<*mut JSObject>, limits: Heap<*mut JSObject>,
@ -66,7 +71,7 @@ impl GPUDevice {
) -> DomRoot<GPUDevice> { ) -> DomRoot<GPUDevice> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUDevice::new_inherited( Box::new(GPUDevice::new_inherited(
adapter, extensions, limits, device, channel, adapter, extensions, limits, device,
)), )),
global, global,
GPUDeviceBinding::Wrap, GPUDeviceBinding::Wrap,
@ -78,7 +83,6 @@ impl GPUDevice {
unsafe fn resolve_create_buffer_mapped( unsafe fn resolve_create_buffer_mapped(
&self, &self,
cx: SafeJSContext, cx: SafeJSContext,
channel: ipc_channel::ipc::IpcSender<WebGPURequest>,
gpu_buffer: WebGPUBuffer, gpu_buffer: WebGPUBuffer,
array_buffer: Vec<u8>, array_buffer: Vec<u8>,
descriptor: BufferDescriptor, descriptor: BufferDescriptor,
@ -95,7 +99,7 @@ impl GPUDevice {
let buff = GPUBuffer::new( let buff = GPUBuffer::new(
&self.global(), &self.global(),
channel, self.channel.clone(),
gpu_buffer, gpu_buffer,
self.device, self.device,
GPUBufferState::Mapped, GPUBufferState::Mapped,
@ -165,14 +169,10 @@ impl GPUDeviceMethods for GPUDevice {
/// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createbuffer /// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createbuffer
fn CreateBuffer(&self, descriptor: &GPUBufferDescriptor) -> DomRoot<GPUBuffer> { fn CreateBuffer(&self, descriptor: &GPUBufferDescriptor) -> DomRoot<GPUBuffer> {
let (valid, wgpu_descriptor) = self.validate_buffer_descriptor(descriptor); let (valid, wgpu_descriptor) = self.validate_buffer_descriptor(descriptor);
let channel;
let (sender, receiver) = ipc::channel().unwrap(); let (sender, receiver) = ipc::channel().unwrap();
if let Some(window) = self.global().downcast::<Window>() { if let Some(window) = self.global().downcast::<Window>() {
let id = window.Navigator().create_buffer_id(self.device.0.backend()); let id = window.Navigator().create_buffer_id(self.device.0.backend());
match window.webgpu_channel() { self.channel
Some(thread) => {
channel = thread.0.clone();
thread
.0 .0
.send(WebGPURequest::CreateBuffer( .send(WebGPURequest::CreateBuffer(
sender, sender,
@ -181,9 +181,6 @@ impl GPUDeviceMethods for GPUDevice {
wgpu_descriptor, wgpu_descriptor,
)) ))
.unwrap(); .unwrap();
},
None => unimplemented!(),
}
} else { } else {
unimplemented!() unimplemented!()
}; };
@ -192,7 +189,7 @@ impl GPUDeviceMethods for GPUDevice {
GPUBuffer::new( GPUBuffer::new(
&self.global(), &self.global(),
channel, self.channel.clone(),
buffer, buffer,
self.device, self.device,
GPUBufferState::Unmapped, GPUBufferState::Unmapped,
@ -209,15 +206,11 @@ impl GPUDeviceMethods for GPUDevice {
descriptor: &GPUBufferDescriptor, descriptor: &GPUBufferDescriptor,
) -> Vec<JSVal> { ) -> Vec<JSVal> {
let (valid, wgpu_descriptor) = self.validate_buffer_descriptor(descriptor); let (valid, wgpu_descriptor) = self.validate_buffer_descriptor(descriptor);
let channel;
let (sender, receiver) = ipc::channel().unwrap(); let (sender, receiver) = ipc::channel().unwrap();
rooted!(in(*cx) let js_val = UndefinedValue()); rooted!(in(*cx) let js_val = UndefinedValue());
if let Some(window) = self.global().downcast::<Window>() { if let Some(window) = self.global().downcast::<Window>() {
let id = window.Navigator().create_buffer_id(self.device.0.backend()); let id = window.Navigator().create_buffer_id(self.device.0.backend());
match window.webgpu_channel() { self.channel
Some(thread) => {
channel = thread.0.clone();
thread
.0 .0
.send(WebGPURequest::CreateBufferMapped( .send(WebGPURequest::CreateBufferMapped(
sender, sender,
@ -226,9 +219,6 @@ impl GPUDeviceMethods for GPUDevice {
wgpu_descriptor.clone(), wgpu_descriptor.clone(),
)) ))
.unwrap() .unwrap()
},
None => return vec![js_val.get()],
}
} else { } else {
return vec![js_val.get()]; return vec![js_val.get()];
}; };
@ -236,14 +226,7 @@ impl GPUDeviceMethods for GPUDevice {
let (buffer, array_buffer) = receiver.recv().unwrap(); let (buffer, array_buffer) = receiver.recv().unwrap();
unsafe { unsafe {
self.resolve_create_buffer_mapped( self.resolve_create_buffer_mapped(cx, buffer, array_buffer, wgpu_descriptor, valid)
cx,
channel,
buffer,
array_buffer,
wgpu_descriptor,
valid,
)
} }
} }
} }

View file

@ -135,7 +135,6 @@ use style::str::HTML_SPACE_CHARACTERS;
use style::stylesheets::CssRuleType; use style::stylesheets::CssRuleType;
use style_traits::{CSSPixel, DevicePixel, ParsingMode}; use style_traits::{CSSPixel, DevicePixel, ParsingMode};
use url::Position; use url::Position;
use webgpu::WebGPU;
use webrender_api::units::{DeviceIntPoint, DeviceIntSize, LayoutPixel}; use webrender_api::units::{DeviceIntPoint, DeviceIntSize, LayoutPixel};
use webrender_api::{DocumentId, ExternalScrollId}; use webrender_api::{DocumentId, ExternalScrollId};
use webvr_traits::WebVRMsg; use webvr_traits::WebVRMsg;
@ -267,10 +266,6 @@ pub struct Window {
#[ignore_malloc_size_of = "channels are hard"] #[ignore_malloc_size_of = "channels are hard"]
webgl_chan: Option<WebGLChan>, webgl_chan: Option<WebGLChan>,
#[ignore_malloc_size_of = "channels are hard"]
/// A handle for communicating messages to the WebGPU threads.
webgpu: Option<WebGPU>,
/// A handle for communicating messages to the webvr thread, if available. /// A handle for communicating messages to the webvr thread, if available.
#[ignore_malloc_size_of = "channels are hard"] #[ignore_malloc_size_of = "channels are hard"]
webvr_chan: Option<IpcSender<WebVRMsg>>, webvr_chan: Option<IpcSender<WebVRMsg>>,
@ -466,10 +461,6 @@ impl Window {
.map(|chan| WebGLCommandSender::new(chan.clone(), self.get_event_loop_waker())) .map(|chan| WebGLCommandSender::new(chan.clone(), self.get_event_loop_waker()))
} }
pub fn webgpu_channel(&self) -> Option<WebGPU> {
self.webgpu.clone()
}
pub fn webvr_thread(&self) -> Option<IpcSender<WebVRMsg>> { pub fn webvr_thread(&self) -> Option<IpcSender<WebVRMsg>> {
self.webvr_chan.clone() self.webvr_chan.clone()
} }
@ -2213,7 +2204,6 @@ impl Window {
navigation_start: u64, navigation_start: u64,
navigation_start_precise: u64, navigation_start_precise: u64,
webgl_chan: Option<WebGLChan>, webgl_chan: Option<WebGLChan>,
webgpu: Option<WebGPU>,
webvr_chan: Option<IpcSender<WebVRMsg>>, webvr_chan: Option<IpcSender<WebVRMsg>>,
webxr_registry: webxr_api::Registry, webxr_registry: webxr_api::Registry,
microtask_queue: Rc<MicrotaskQueue>, microtask_queue: Rc<MicrotaskQueue>,
@ -2292,7 +2282,6 @@ impl Window {
media_query_lists: DOMTracker::new(), media_query_lists: DOMTracker::new(),
test_runner: Default::default(), test_runner: Default::default(),
webgl_chan, webgl_chan,
webgpu,
webvr_chan, webvr_chan,
webxr_registry, webxr_registry,
permission_state_invocation_results: Default::default(), permission_state_invocation_results: Default::default(),

View file

@ -164,7 +164,6 @@ use style::dom::OpaqueNode;
use style::thread_state::{self, ThreadState}; use style::thread_state::{self, ThreadState};
use time::{at_utc, get_time, precise_time_ns, Timespec}; use time::{at_utc, get_time, precise_time_ns, Timespec};
use url::Position; use url::Position;
use webgpu::WebGPU;
use webrender_api::units::LayoutPixel; use webrender_api::units::LayoutPixel;
use webrender_api::DocumentId; use webrender_api::DocumentId;
use webvr_traits::{WebVREvent, WebVRMsg}; use webvr_traits::{WebVREvent, WebVRMsg};
@ -630,9 +629,6 @@ pub struct ScriptThread {
/// A handle to the WebGL thread /// A handle to the WebGL thread
webgl_chan: Option<WebGLPipeline>, webgl_chan: Option<WebGLPipeline>,
/// A handle to the WebGPU threads
webgpu: Option<WebGPU>,
/// A handle to the webvr thread, if available /// A handle to the webvr thread, if available
webvr_chan: Option<IpcSender<WebVRMsg>>, webvr_chan: Option<IpcSender<WebVRMsg>>,
@ -1339,7 +1335,6 @@ impl ScriptThread {
layout_to_constellation_chan: state.layout_to_constellation_chan, layout_to_constellation_chan: state.layout_to_constellation_chan,
webgl_chan: state.webgl_chan, webgl_chan: state.webgl_chan,
webgpu: state.webgpu,
webvr_chan: state.webvr_chan, webvr_chan: state.webvr_chan,
webxr_registry: state.webxr_registry, webxr_registry: state.webxr_registry,
@ -3201,7 +3196,6 @@ impl ScriptThread {
incomplete.navigation_start, incomplete.navigation_start,
incomplete.navigation_start_precise, incomplete.navigation_start_precise,
self.webgl_chan.as_ref().map(|chan| chan.channel()), self.webgl_chan.as_ref().map(|chan| chan.channel()),
self.webgpu.clone(),
self.webvr_chan.clone(), self.webvr_chan.clone(),
self.webxr_registry.clone(), self.webxr_registry.clone(),
self.microtask_queue.clone(), self.microtask_queue.clone(),

View file

@ -36,6 +36,7 @@ profile_traits = {path = "../profile_traits"}
serde = "1.0" serde = "1.0"
servo_atoms = {path = "../atoms"} servo_atoms = {path = "../atoms"}
servo_url = {path = "../url"} servo_url = {path = "../url"}
smallvec = "0.6"
style_traits = {path = "../style_traits", features = ["servo"]} style_traits = {path = "../style_traits", features = ["servo"]}
time = "0.1.12" time = "0.1.12"
url = "2.0" url = "2.0"

View file

@ -65,7 +65,6 @@ use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use style_traits::CSSPixel; use style_traits::CSSPixel;
use style_traits::SpeculativePainter; use style_traits::SpeculativePainter;
use webgpu::WebGPU;
use webrender_api::units::{ use webrender_api::units::{
DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint, LayoutSize, WorldPoint, DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint, LayoutSize, WorldPoint,
}; };
@ -665,8 +664,6 @@ pub struct InitialScriptState {
pub content_process_shutdown_chan: Sender<()>, pub content_process_shutdown_chan: Sender<()>,
/// A channel to the WebGL thread used in this pipeline. /// A channel to the WebGL thread used in this pipeline.
pub webgl_chan: Option<WebGLPipeline>, pub webgl_chan: Option<WebGLPipeline>,
/// A channel to the WebGPU threads.
pub webgpu: Option<WebGPU>,
/// A channel to the webvr thread, if available. /// A channel to the webvr thread, if available.
pub webvr_chan: Option<IpcSender<WebVRMsg>>, pub webvr_chan: Option<IpcSender<WebVRMsg>>,
/// The XR device registry /// The XR device registry

View file

@ -30,10 +30,12 @@ use net_traits::storage_thread::StorageType;
use net_traits::CoreResourceMsg; use net_traits::CoreResourceMsg;
use servo_url::ImmutableOrigin; use servo_url::ImmutableOrigin;
use servo_url::ServoUrl; use servo_url::ServoUrl;
use smallvec::SmallVec;
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
use std::fmt; use std::fmt;
use style_traits::viewport::ViewportConstraints; use style_traits::viewport::ViewportConstraints;
use style_traits::CSSPixel; use style_traits::CSSPixel;
use webgpu::{wgpu, WebGPUResponseResult};
use webrender_api::units::{DeviceIntPoint, DeviceIntSize}; use webrender_api::units::{DeviceIntPoint, DeviceIntSize};
/// A particular iframe's size, associated with a browsing context. /// A particular iframe's size, associated with a browsing context.
@ -257,6 +259,12 @@ pub enum ScriptMsg {
/// Notifies the constellation about media session events /// Notifies the constellation about media session events
/// (i.e. when there is metadata for the active media session, playback state changes...). /// (i.e. when there is metadata for the active media session, playback state changes...).
MediaSessionEvent(PipelineId, MediaSessionEvent), MediaSessionEvent(PipelineId, MediaSessionEvent),
/// Create a WebGPU Adapter instance
RequestAdapter(
IpcSender<WebGPUResponseResult>,
wgpu::instance::RequestAdapterOptions,
SmallVec<[wgpu::id::AdapterId; 4]>,
),
} }
impl fmt::Debug for ScriptMsg { impl fmt::Debug for ScriptMsg {
@ -309,6 +317,7 @@ impl fmt::Debug for ScriptMsg {
GetScreenSize(..) => "GetScreenSize", GetScreenSize(..) => "GetScreenSize",
GetScreenAvailSize(..) => "GetScreenAvailSize", GetScreenAvailSize(..) => "GetScreenAvailSize",
MediaSessionEvent(..) => "MediaSessionEvent", MediaSessionEvent(..) => "MediaSessionEvent",
RequestAdapter(..) => "RequestAdapter",
}; };
write!(formatter, "ScriptMsg::{}", variant) write!(formatter, "ScriptMsg::{}", variant)
} }

View file

@ -874,8 +874,6 @@ fn create_constellation(
let resource_sender = public_resource_threads.sender(); let resource_sender = public_resource_threads.sender();
let webgpu = webgpu::WebGPU::new();
let initial_state = InitialConstellationState { let initial_state = InitialConstellationState {
compositor_proxy, compositor_proxy,
embedder_proxy, embedder_proxy,
@ -890,7 +888,6 @@ fn create_constellation(
webrender_document, webrender_document,
webrender_api_sender, webrender_api_sender,
webgl_threads, webgl_threads,
webgpu,
webvr_chan, webvr_chan,
webxr_registry, webxr_registry,
glplayer_threads, glplayer_threads,

View file

@ -16,7 +16,7 @@ use smallvec::SmallVec;
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
pub enum WebGPUResponse { pub enum WebGPUResponse {
RequestAdapter(String, WebGPUAdapter), RequestAdapter(String, WebGPUAdapter, WebGPU),
RequestDevice(WebGPUDevice, wgpu::instance::DeviceDescriptor), RequestDevice(WebGPUDevice, wgpu::instance::DeviceDescriptor),
} }
@ -70,11 +70,12 @@ impl WebGPU {
return None; return None;
}, },
}; };
let sender_clone = sender.clone();
if let Err(e) = std::thread::Builder::new() if let Err(e) = std::thread::Builder::new()
.name("WGPU".to_owned()) .name("WGPU".to_owned())
.spawn(move || { .spawn(move || {
WGPU::new(receiver).run(); WGPU::new(receiver, sender_clone).run();
}) })
{ {
warn!("Failed to spwan WGPU thread ({})", e); warn!("Failed to spwan WGPU thread ({})", e);
@ -92,6 +93,7 @@ impl WebGPU {
struct WGPU { struct WGPU {
receiver: IpcReceiver<WebGPURequest>, receiver: IpcReceiver<WebGPURequest>,
sender: IpcSender<WebGPURequest>,
global: wgpu::hub::Global<()>, global: wgpu::hub::Global<()>,
adapters: Vec<WebGPUAdapter>, adapters: Vec<WebGPUAdapter>,
devices: Vec<WebGPUDevice>, devices: Vec<WebGPUDevice>,
@ -100,9 +102,10 @@ struct WGPU {
} }
impl WGPU { impl WGPU {
fn new(receiver: IpcReceiver<WebGPURequest>) -> Self { fn new(receiver: IpcReceiver<WebGPURequest>, sender: IpcSender<WebGPURequest>) -> Self {
WGPU { WGPU {
receiver, receiver,
sender,
global: wgpu::hub::Global::new("wgpu-core"), global: wgpu::hub::Global::new("wgpu-core"),
adapters: Vec::new(), adapters: Vec::new(),
devices: Vec::new(), devices: Vec::new(),
@ -118,6 +121,13 @@ impl WGPU {
while let Ok(msg) = self.receiver.recv() { while let Ok(msg) = self.receiver.recv() {
match msg { match msg {
WebGPURequest::RequestAdapter(sender, options, ids) => { WebGPURequest::RequestAdapter(sender, options, ids) => {
let adapter_id = if let Some(pos) = self
.adapters
.iter()
.position(|adapter| ids.contains(&adapter.0))
{
self.adapters[pos].0
} else {
let adapter_id = match self.global.pick_adapter( let adapter_id = match self.global.pick_adapter(
&options, &options,
wgpu::instance::AdapterInputs::IdSet(&ids, |id| id.backend()), wgpu::instance::AdapterInputs::IdSet(&ids, |id| id.backend()),
@ -135,13 +145,17 @@ impl WGPU {
return; return;
}, },
}; };
adapter_id
};
let adapter = WebGPUAdapter(adapter_id); let adapter = WebGPUAdapter(adapter_id);
self.adapters.push(adapter); self.adapters.push(adapter);
let global = &self.global; let global = &self.global;
let info = gfx_select!(adapter_id => global.adapter_get_info(adapter_id)); let info = gfx_select!(adapter_id => global.adapter_get_info(adapter_id));
if let Err(e) = if let Err(e) = sender.send(Ok(WebGPUResponse::RequestAdapter(
sender.send(Ok(WebGPUResponse::RequestAdapter(info.name, adapter))) info.name,
{ adapter,
WebGPU(self.sender.clone()),
))) {
warn!( warn!(
"Failed to send response to WebGPURequest::RequestAdapter ({})", "Failed to send response to WebGPURequest::RequestAdapter ({})",
e e