Auto merge of #27389 - kunalmohan:update-wgpu, r=kvark

Implement GPURenderBundles

<!-- Please describe your changes on the following line: -->
1. Implement `GPURenderBundleEncoder` and `GPURenderBundle`.
2. Update wgpu to use serializable descriptors.
3. Set user-defined labels on object creation.

r?@kvark

---
<!-- Thank you for contributing to Servo! Please replace each `[ ]` by `[X]` when the step is complete, and replace `___` with appropriate data: -->
- [X] `./mach build -d` does not report any errors
- [X] `./mach test-tidy` does not report any errors

<!-- Also, please make sure that "Allow edits from maintainers" checkbox is checked, so that we can help you if you get stuck somewhere along the way.-->

<!-- Pull requests that do not address these steps are welcome, but they will require additional verification as part of the review process. -->
This commit is contained in:
bors-servo 2020-07-24 14:55:09 -04:00 committed by GitHub
commit ebec798263
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
31 changed files with 899 additions and 443 deletions

8
Cargo.lock generated
View file

@ -3641,13 +3641,14 @@ checksum = "0419348c027fa7be448d2ae7ea0e4e04c2334c31dc4e74ab29f00a2a7ca69204"
[[package]] [[package]]
name = "naga" name = "naga"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/gfx-rs/naga?rev=a9228d2aed38c71388489a95817238ff98198fa3#a9228d2aed38c71388489a95817238ff98198fa3" source = "git+https://github.com/gfx-rs/naga?rev=94802078c3bc5d138f497419ea3e7a869f10916d#94802078c3bc5d138f497419ea3e7a869f10916d"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"fxhash", "fxhash",
"log", "log",
"num-traits", "num-traits",
"spirv_headers", "spirv_headers",
"thiserror",
] ]
[[package]] [[package]]
@ -6860,7 +6861,7 @@ dependencies = [
[[package]] [[package]]
name = "wgpu-core" name = "wgpu-core"
version = "0.5.0" version = "0.5.0"
source = "git+https://github.com/gfx-rs/wgpu#73b230871ea4428ed3fb1e6e8bff81a7364fcdb2" source = "git+https://github.com/gfx-rs/wgpu#8a2ee26fffcdf02fc5e7f0a29771f4720522f7d8"
dependencies = [ dependencies = [
"arrayvec 0.5.1", "arrayvec 0.5.1",
"bitflags", "bitflags",
@ -6880,7 +6881,6 @@ dependencies = [
"ron", "ron",
"serde", "serde",
"smallvec 1.4.1", "smallvec 1.4.1",
"spirv_headers",
"thiserror", "thiserror",
"tracing", "tracing",
"wgpu-types", "wgpu-types",
@ -6889,7 +6889,7 @@ dependencies = [
[[package]] [[package]]
name = "wgpu-types" name = "wgpu-types"
version = "0.5.0" version = "0.5.0"
source = "git+https://github.com/gfx-rs/wgpu#73b230871ea4428ed3fb1e6e8bff81a7364fcdb2" source = "git+https://github.com/gfx-rs/wgpu#8a2ee26fffcdf02fc5e7f0a29771f4720522f7d8"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"serde", "serde",

View file

@ -168,12 +168,12 @@ use tendril::{StrTendril, TendrilSink};
use time::{Duration, Timespec, Tm}; use time::{Duration, Timespec, Tm};
use uuid::Uuid; use uuid::Uuid;
use webgpu::{ use webgpu::{
wgpu::command::{ComputePass, RenderPass}, wgpu::command::{ComputePass, RenderBundleEncoder, RenderPass},
wgt::BindGroupLayoutEntry, wgt::BindGroupLayoutEntry,
WebGPU, WebGPUAdapter, WebGPUBindGroup, WebGPUBindGroupLayout, WebGPUBuffer, WebGPU, WebGPUAdapter, WebGPUBindGroup, WebGPUBindGroupLayout, WebGPUBuffer,
WebGPUCommandBuffer, WebGPUCommandEncoder, WebGPUComputePipeline, WebGPUDevice, WebGPUCommandBuffer, WebGPUCommandEncoder, WebGPUComputePipeline, WebGPUDevice,
WebGPUPipelineLayout, WebGPUQueue, WebGPURenderPipeline, WebGPUSampler, WebGPUShaderModule, WebGPUPipelineLayout, WebGPUQueue, WebGPURenderBundle, WebGPURenderPipeline, WebGPUSampler,
WebGPUTexture, WebGPUTextureView, WebGPUShaderModule, WebGPUTexture, WebGPUTextureView,
}; };
use webrender_api::{DocumentId, ExternalImageId, ImageKey}; use webrender_api::{DocumentId, ExternalImageId, ImageKey};
use webxr_api::{Finger, Hand, Ray, View}; use webxr_api::{Finger, Hand, Ray, View};
@ -618,6 +618,7 @@ unsafe_no_jsmanaged_fields!(WebGPUBindGroup);
unsafe_no_jsmanaged_fields!(WebGPUBindGroupLayout); unsafe_no_jsmanaged_fields!(WebGPUBindGroupLayout);
unsafe_no_jsmanaged_fields!(WebGPUComputePipeline); unsafe_no_jsmanaged_fields!(WebGPUComputePipeline);
unsafe_no_jsmanaged_fields!(WebGPURenderPipeline); unsafe_no_jsmanaged_fields!(WebGPURenderPipeline);
unsafe_no_jsmanaged_fields!(WebGPURenderBundle);
unsafe_no_jsmanaged_fields!(WebGPUPipelineLayout); unsafe_no_jsmanaged_fields!(WebGPUPipelineLayout);
unsafe_no_jsmanaged_fields!(WebGPUQueue); unsafe_no_jsmanaged_fields!(WebGPUQueue);
unsafe_no_jsmanaged_fields!(WebGPUShaderModule); unsafe_no_jsmanaged_fields!(WebGPUShaderModule);
@ -630,6 +631,7 @@ unsafe_no_jsmanaged_fields!(WebGPUCommandEncoder);
unsafe_no_jsmanaged_fields!(WebGPUDevice); unsafe_no_jsmanaged_fields!(WebGPUDevice);
unsafe_no_jsmanaged_fields!(BindGroupLayoutEntry); unsafe_no_jsmanaged_fields!(BindGroupLayoutEntry);
unsafe_no_jsmanaged_fields!(Option<RenderPass>); unsafe_no_jsmanaged_fields!(Option<RenderPass>);
unsafe_no_jsmanaged_fields!(Option<RenderBundleEncoder>);
unsafe_no_jsmanaged_fields!(Option<ComputePass>); unsafe_no_jsmanaged_fields!(Option<ComputePass>);
unsafe_no_jsmanaged_fields!(GPUBufferState); unsafe_no_jsmanaged_fields!(GPUBufferState);
unsafe_no_jsmanaged_fields!(GPUCommandEncoderState); unsafe_no_jsmanaged_fields!(GPUCommandEncoderState);

View file

@ -103,6 +103,7 @@ impl GPUAdapterMethods for GPUAdapter {
descriptor: desc, descriptor: desc,
device_id: id, device_id: id,
pipeline_id, pipeline_id,
label: descriptor.parent.label.as_ref().map(|s| s.to_string()),
}) })
.is_err() .is_err()
{ {
@ -119,6 +120,7 @@ impl AsyncWGPUListener for GPUAdapter {
device_id, device_id,
queue_id, queue_id,
_descriptor, _descriptor,
label,
} => { } => {
let device = GPUDevice::new( let device = GPUDevice::new(
&self.global(), &self.global(),
@ -128,6 +130,7 @@ impl AsyncWGPUListener for GPUAdapter {
Heap::default(), Heap::default(),
device_id, device_id,
queue_id, queue_id,
label,
); );
self.global().add_gpu_device(&device); self.global().add_gpu_device(&device);
promise.resolve_native(&device); promise.resolve_native(&device);

View file

@ -26,10 +26,11 @@ impl GPUBindGroup {
bind_group: WebGPUBindGroup, bind_group: WebGPUBindGroup,
device: WebGPUDevice, device: WebGPUDevice,
layout: &GPUBindGroupLayout, layout: &GPUBindGroupLayout,
label: Option<USVString>,
) -> Self { ) -> Self {
Self { Self {
reflector_: Reflector::new(), reflector_: Reflector::new(),
label: DomRefCell::new(None), label: DomRefCell::new(label),
bind_group, bind_group,
device, device,
layout: Dom::from_ref(layout), layout: Dom::from_ref(layout),
@ -41,9 +42,12 @@ impl GPUBindGroup {
bind_group: WebGPUBindGroup, bind_group: WebGPUBindGroup,
device: WebGPUDevice, device: WebGPUDevice,
layout: &GPUBindGroupLayout, layout: &GPUBindGroupLayout,
label: Option<USVString>,
) -> DomRoot<Self> { ) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUBindGroup::new_inherited(bind_group, device, layout)), Box::new(GPUBindGroup::new_inherited(
bind_group, device, layout, label,
)),
global, global,
) )
} }

View file

@ -19,17 +19,21 @@ pub struct GPUBindGroupLayout {
} }
impl GPUBindGroupLayout { impl GPUBindGroupLayout {
fn new_inherited(bind_group_layout: WebGPUBindGroupLayout) -> Self { fn new_inherited(bind_group_layout: WebGPUBindGroupLayout, label: Option<USVString>) -> Self {
Self { Self {
reflector_: Reflector::new(), reflector_: Reflector::new(),
label: DomRefCell::new(None), label: DomRefCell::new(label),
bind_group_layout, bind_group_layout,
} }
} }
pub fn new(global: &GlobalScope, bind_group_layout: WebGPUBindGroupLayout) -> DomRoot<Self> { pub fn new(
global: &GlobalScope,
bind_group_layout: WebGPUBindGroupLayout,
label: Option<USVString>,
) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUBindGroupLayout::new_inherited(bind_group_layout)), Box::new(GPUBindGroupLayout::new_inherited(bind_group_layout, label)),
global, global,
) )
} }

View file

@ -76,11 +76,12 @@ impl GPUBuffer {
state: GPUBufferState, state: GPUBufferState,
size: GPUSize64, size: GPUSize64,
map_info: DomRefCell<Option<GPUBufferMapInfo>>, map_info: DomRefCell<Option<GPUBufferMapInfo>>,
label: Option<USVString>,
) -> Self { ) -> Self {
Self { Self {
reflector_: Reflector::new(), reflector_: Reflector::new(),
channel, channel,
label: DomRefCell::new(None), label: DomRefCell::new(label),
state: Cell::new(state), state: Cell::new(state),
device, device,
buffer, buffer,
@ -99,10 +100,11 @@ impl GPUBuffer {
state: GPUBufferState, state: GPUBufferState,
size: GPUSize64, size: GPUSize64,
map_info: DomRefCell<Option<GPUBufferMapInfo>>, map_info: DomRefCell<Option<GPUBufferMapInfo>>,
label: Option<USVString>,
) -> DomRoot<Self> { ) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUBuffer::new_inherited( Box::new(GPUBuffer::new_inherited(
channel, buffer, device, state, size, map_info, channel, buffer, device, state, size, map_info, label,
)), )),
global, global,
) )

View file

@ -201,7 +201,13 @@ impl GPUCanvasContextMethods for GPUCanvasContext {
self.webrender_image.set(Some(receiver.recv().unwrap())); self.webrender_image.set(Some(receiver.recv().unwrap()));
let swap_chain = GPUSwapChain::new(&self.global(), self.channel.clone(), &self, &*texture); let swap_chain = GPUSwapChain::new(
&self.global(),
self.channel.clone(),
&self,
&*texture,
descriptor.parent.label.as_ref().cloned(),
);
*self.swap_chain.borrow_mut() = Some(Dom::from_ref(&*swap_chain)); *self.swap_chain.borrow_mut() = Some(Dom::from_ref(&*swap_chain));
swap_chain swap_chain
} }

View file

@ -37,11 +37,12 @@ impl GPUCommandBuffer {
channel: WebGPU, channel: WebGPU,
command_buffer: WebGPUCommandBuffer, command_buffer: WebGPUCommandBuffer,
buffers: HashSet<DomRoot<GPUBuffer>>, buffers: HashSet<DomRoot<GPUBuffer>>,
label: Option<USVString>,
) -> Self { ) -> Self {
Self { Self {
channel, channel,
reflector_: Reflector::new(), reflector_: Reflector::new(),
label: DomRefCell::new(None), label: DomRefCell::new(label),
command_buffer, command_buffer,
buffers: DomRefCell::new(buffers.into_iter().map(|b| Dom::from_ref(&*b)).collect()), buffers: DomRefCell::new(buffers.into_iter().map(|b| Dom::from_ref(&*b)).collect()),
} }
@ -52,12 +53,14 @@ impl GPUCommandBuffer {
channel: WebGPU, channel: WebGPU,
command_buffer: WebGPUCommandBuffer, command_buffer: WebGPUCommandBuffer,
buffers: HashSet<DomRoot<GPUBuffer>>, buffers: HashSet<DomRoot<GPUBuffer>>,
label: Option<USVString>,
) -> DomRoot<Self> { ) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUCommandBuffer::new_inherited( Box::new(GPUCommandBuffer::new_inherited(
channel, channel,
command_buffer, command_buffer,
buffers, buffers,
label,
)), )),
global, global,
) )

View file

@ -25,6 +25,7 @@ use crate::dom::gpucomputepassencoder::GPUComputePassEncoder;
use crate::dom::gpudevice::{convert_texture_size_to_dict, convert_texture_size_to_wgt}; use crate::dom::gpudevice::{convert_texture_size_to_dict, convert_texture_size_to_wgt};
use crate::dom::gpurenderpassencoder::GPURenderPassEncoder; use crate::dom::gpurenderpassencoder::GPURenderPassEncoder;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use std::borrow::Cow;
use std::cell::Cell; use std::cell::Cell;
use std::collections::HashSet; use std::collections::HashSet;
use webgpu::wgpu::command as wgpu_com; use webgpu::wgpu::command as wgpu_com;
@ -58,11 +59,12 @@ impl GPUCommandEncoder {
device: WebGPUDevice, device: WebGPUDevice,
encoder: webgpu::WebGPUCommandEncoder, encoder: webgpu::WebGPUCommandEncoder,
valid: bool, valid: bool,
label: Option<USVString>,
) -> Self { ) -> Self {
Self { Self {
channel, channel,
reflector_: Reflector::new(), reflector_: Reflector::new(),
label: DomRefCell::new(None), label: DomRefCell::new(label),
device, device,
encoder, encoder,
buffers: DomRefCell::new(HashSet::new()), buffers: DomRefCell::new(HashSet::new()),
@ -77,10 +79,11 @@ impl GPUCommandEncoder {
device: WebGPUDevice, device: WebGPUDevice,
encoder: webgpu::WebGPUCommandEncoder, encoder: webgpu::WebGPUCommandEncoder,
valid: bool, valid: bool,
label: Option<USVString>,
) -> DomRoot<Self> { ) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUCommandEncoder::new_inherited( Box::new(GPUCommandEncoder::new_inherited(
channel, device, encoder, valid, channel, device, encoder, valid, label,
)), )),
global, global,
) )
@ -116,13 +119,18 @@ impl GPUCommandEncoderMethods for GPUCommandEncoder {
/// https://gpuweb.github.io/gpuweb/#dom-gpucommandencoder-begincomputepass /// https://gpuweb.github.io/gpuweb/#dom-gpucommandencoder-begincomputepass
fn BeginComputePass( fn BeginComputePass(
&self, &self,
_descriptor: &GPUComputePassDescriptor, descriptor: &GPUComputePassDescriptor,
) -> DomRoot<GPUComputePassEncoder> { ) -> DomRoot<GPUComputePassEncoder> {
self.set_state( self.set_state(
GPUCommandEncoderState::EncodingComputePass, GPUCommandEncoderState::EncodingComputePass,
GPUCommandEncoderState::Open, GPUCommandEncoderState::Open,
); );
GPUComputePassEncoder::new(&self.global(), self.channel.clone(), &self) GPUComputePassEncoder::new(
&self.global(),
self.channel.clone(),
&self,
descriptor.parent.label.as_ref().cloned(),
)
} }
/// https://gpuweb.github.io/gpuweb/#dom-gpucommandencoder-beginrenderpass /// https://gpuweb.github.io/gpuweb/#dom-gpucommandencoder-beginrenderpass
@ -135,12 +143,50 @@ impl GPUCommandEncoderMethods for GPUCommandEncoder {
GPUCommandEncoderState::Open, GPUCommandEncoderState::Open,
); );
let colors = descriptor let depth_stencil = descriptor.depthStencilAttachment.as_ref().map(|depth| {
let (depth_load_op, clear_depth) = match depth.depthLoadValue {
GPULoadOpOrFloat::GPULoadOp(_) => (wgpu_com::LoadOp::Load, 0.0f32),
GPULoadOpOrFloat::Float(f) => (wgpu_com::LoadOp::Clear, *f),
};
let (stencil_load_op, clear_stencil) = match depth.stencilLoadValue {
GPUStencilLoadValue::GPULoadOp(_) => (wgpu_com::LoadOp::Load, 0u32),
GPUStencilLoadValue::RangeEnforcedUnsignedLong(l) => (wgpu_com::LoadOp::Clear, l),
};
let depth_channel = wgpu_com::PassChannel {
load_op: depth_load_op,
store_op: match depth.depthStoreOp {
GPUStoreOp::Store => wgpu_com::StoreOp::Store,
GPUStoreOp::Clear => wgpu_com::StoreOp::Clear,
},
clear_value: clear_depth,
read_only: depth.depthReadOnly,
};
let stencil_channel = wgpu_com::PassChannel {
load_op: stencil_load_op,
store_op: match depth.stencilStoreOp {
GPUStoreOp::Store => wgpu_com::StoreOp::Store,
GPUStoreOp::Clear => wgpu_com::StoreOp::Clear,
},
clear_value: clear_stencil,
read_only: depth.stencilReadOnly,
};
wgpu_com::DepthStencilAttachmentDescriptor {
attachment: depth.attachment.id().0,
depth: depth_channel,
stencil: stencil_channel,
}
});
let desc = wgpu_com::RenderPassDescriptor {
color_attachments: Cow::Owned(
descriptor
.colorAttachments .colorAttachments
.iter() .iter()
.map(|color| { .map(|color| {
let (load_op, clear_value) = match color.loadValue { let (load_op, clear_value) = match color.loadValue {
GPUColorLoad::GPULoadOp(_) => (wgpu_com::LoadOp::Load, wgt::Color::TRANSPARENT), GPUColorLoad::GPULoadOp(_) => {
(wgpu_com::LoadOp::Load, wgt::Color::TRANSPARENT)
},
GPUColorLoad::DoubleSequence(ref s) => { GPUColorLoad::DoubleSequence(ref s) => {
let mut w = s.clone(); let mut w = s.clone();
if w.len() < 3 { if w.len() < 3 {
@ -182,50 +228,20 @@ impl GPUCommandEncoderMethods for GPUCommandEncoder {
channel, channel,
} }
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>(),
),
let depth_stencil = descriptor.depthStencilAttachment.as_ref().map(|depth| {
let (depth_load_op, clear_depth) = match depth.depthLoadValue {
GPULoadOpOrFloat::GPULoadOp(_) => (wgpu_com::LoadOp::Load, 0.0f32),
GPULoadOpOrFloat::Float(f) => (wgpu_com::LoadOp::Clear, *f),
};
let (stencil_load_op, clear_stencil) = match depth.stencilLoadValue {
GPUStencilLoadValue::GPULoadOp(_) => (wgpu_com::LoadOp::Load, 0u32),
GPUStencilLoadValue::RangeEnforcedUnsignedLong(l) => (wgpu_com::LoadOp::Clear, l),
};
let depth_channel = wgpu_com::PassChannel {
load_op: depth_load_op,
store_op: match depth.depthStoreOp {
GPUStoreOp::Store => wgpu_com::StoreOp::Store,
GPUStoreOp::Clear => wgpu_com::StoreOp::Clear,
},
clear_value: clear_depth,
read_only: depth.depthReadOnly,
};
let stencil_channel = wgpu_com::PassChannel {
load_op: stencil_load_op,
store_op: match depth.stencilStoreOp {
GPUStoreOp::Store => wgpu_com::StoreOp::Store,
GPUStoreOp::Clear => wgpu_com::StoreOp::Clear,
},
clear_value: clear_stencil,
read_only: depth.stencilReadOnly,
};
wgpu_com::DepthStencilAttachmentDescriptor {
attachment: depth.attachment.id().0,
depth: depth_channel,
stencil: stencil_channel,
}
});
let desc = wgpu_com::RenderPassDescriptor {
color_attachments: colors.as_slice(),
depth_stencil_attachment: depth_stencil.as_ref(), depth_stencil_attachment: depth_stencil.as_ref(),
}; };
let render_pass = wgpu_com::RenderPass::new(self.encoder.0, desc); let render_pass = wgpu_com::RenderPass::new(self.encoder.0, desc);
GPURenderPassEncoder::new(&self.global(), self.channel.clone(), render_pass, &self) GPURenderPassEncoder::new(
&self.global(),
self.channel.clone(),
render_pass,
&self,
descriptor.parent.label.as_ref().cloned(),
)
} }
/// https://gpuweb.github.io/gpuweb/#dom-gpucommandencoder-copybuffertobuffer /// https://gpuweb.github.io/gpuweb/#dom-gpucommandencoder-copybuffertobuffer
@ -349,7 +365,7 @@ impl GPUCommandEncoderMethods for GPUCommandEncoder {
} }
/// https://gpuweb.github.io/gpuweb/#dom-gpucommandencoder-finish /// https://gpuweb.github.io/gpuweb/#dom-gpucommandencoder-finish
fn Finish(&self, _descriptor: &GPUCommandBufferDescriptor) -> DomRoot<GPUCommandBuffer> { fn Finish(&self, descriptor: &GPUCommandBufferDescriptor) -> DomRoot<GPUCommandBuffer> {
self.channel self.channel
.0 .0
.send(WebGPURequest::CommandEncoderFinish { .send(WebGPURequest::CommandEncoderFinish {
@ -366,6 +382,7 @@ impl GPUCommandEncoderMethods for GPUCommandEncoder {
self.channel.clone(), self.channel.clone(),
buffer, buffer,
self.buffers.borrow_mut().drain().collect(), self.buffers.borrow_mut().drain().collect(),
descriptor.parent.label.as_ref().cloned(),
) )
} }
} }

View file

@ -30,19 +30,28 @@ pub struct GPUComputePassEncoder {
} }
impl GPUComputePassEncoder { impl GPUComputePassEncoder {
fn new_inherited(channel: WebGPU, parent: &GPUCommandEncoder) -> Self { fn new_inherited(
channel: WebGPU,
parent: &GPUCommandEncoder,
label: Option<USVString>,
) -> Self {
Self { Self {
channel, channel,
reflector_: Reflector::new(), reflector_: Reflector::new(),
label: DomRefCell::new(None), label: DomRefCell::new(label),
compute_pass: DomRefCell::new(Some(ComputePass::new(parent.id().0))), compute_pass: DomRefCell::new(Some(ComputePass::new(parent.id().0))),
command_encoder: Dom::from_ref(parent), command_encoder: Dom::from_ref(parent),
} }
} }
pub fn new(global: &GlobalScope, channel: WebGPU, parent: &GPUCommandEncoder) -> DomRoot<Self> { pub fn new(
global: &GlobalScope,
channel: WebGPU,
parent: &GPUCommandEncoder,
label: Option<USVString>,
) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUComputePassEncoder::new_inherited(channel, parent)), Box::new(GPUComputePassEncoder::new_inherited(channel, parent, label)),
global, global,
) )
} }
@ -86,7 +95,7 @@ impl GPUComputePassEncoderMethods for GPUComputePassEncoder {
command_encoder_id: self.command_encoder.id().0, command_encoder_id: self.command_encoder.id().0,
compute_pass, compute_pass,
}) })
.unwrap(); .expect("Failed to send RunComputePass");
self.command_encoder.set_state( self.command_encoder.set_state(
GPUCommandEncoderState::Open, GPUCommandEncoderState::Open,

View file

@ -20,17 +20,21 @@ pub struct GPUComputePipeline {
} }
impl GPUComputePipeline { impl GPUComputePipeline {
fn new_inherited(compute_pipeline: WebGPUComputePipeline) -> Self { fn new_inherited(compute_pipeline: WebGPUComputePipeline, label: Option<USVString>) -> Self {
Self { Self {
reflector_: Reflector::new(), reflector_: Reflector::new(),
label: DomRefCell::new(None), label: DomRefCell::new(label),
compute_pipeline, compute_pipeline,
} }
} }
pub fn new(global: &GlobalScope, compute_pipeline: WebGPUComputePipeline) -> DomRoot<Self> { pub fn new(
global: &GlobalScope,
compute_pipeline: WebGPUComputePipeline,
label: Option<USVString>,
) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUComputePipeline::new_inherited(compute_pipeline)), Box::new(GPUComputePipeline::new_inherited(compute_pipeline, label)),
global, global,
) )
} }

View file

@ -17,6 +17,7 @@ use crate::dom::bindings::codegen::Bindings::GPUDeviceBinding::{
GPUCommandEncoderDescriptor, GPUDeviceMethods, GPUCommandEncoderDescriptor, GPUDeviceMethods,
}; };
use crate::dom::bindings::codegen::Bindings::GPUPipelineLayoutBinding::GPUPipelineLayoutDescriptor; use crate::dom::bindings::codegen::Bindings::GPUPipelineLayoutBinding::GPUPipelineLayoutDescriptor;
use crate::dom::bindings::codegen::Bindings::GPURenderBundleEncoderBinding::GPURenderBundleEncoderDescriptor;
use crate::dom::bindings::codegen::Bindings::GPURenderPipelineBinding::{ use crate::dom::bindings::codegen::Bindings::GPURenderPipelineBinding::{
GPUBlendDescriptor, GPUBlendFactor, GPUBlendOperation, GPUCullMode, GPUFrontFace, GPUBlendDescriptor, GPUBlendFactor, GPUBlendOperation, GPUCullMode, GPUFrontFace,
GPUIndexFormat, GPUInputStepMode, GPUPrimitiveTopology, GPURenderPipelineDescriptor, GPUIndexFormat, GPUInputStepMode, GPUPrimitiveTopology, GPURenderPipelineDescriptor,
@ -50,6 +51,7 @@ use crate::dom::gpucommandencoder::GPUCommandEncoder;
use crate::dom::gpucomputepipeline::GPUComputePipeline; use crate::dom::gpucomputepipeline::GPUComputePipeline;
use crate::dom::gpupipelinelayout::GPUPipelineLayout; use crate::dom::gpupipelinelayout::GPUPipelineLayout;
use crate::dom::gpuqueue::GPUQueue; use crate::dom::gpuqueue::GPUQueue;
use crate::dom::gpurenderbundleencoder::GPURenderBundleEncoder;
use crate::dom::gpurenderpipeline::GPURenderPipeline; use crate::dom::gpurenderpipeline::GPURenderPipeline;
use crate::dom::gpusampler::GPUSampler; use crate::dom::gpusampler::GPUSampler;
use crate::dom::gpushadermodule::GPUShaderModule; use crate::dom::gpushadermodule::GPUShaderModule;
@ -57,16 +59,17 @@ use crate::dom::gputexture::GPUTexture;
use crate::dom::promise::Promise; use crate::dom::promise::Promise;
use crate::realms::InRealm; use crate::realms::InRealm;
use crate::script_runtime::JSContext as SafeJSContext; use crate::script_runtime::JSContext as SafeJSContext;
use arrayvec::ArrayVec;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSObject}; use js::jsapi::{Heap, JSObject};
use std::borrow::Cow;
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
use std::ptr::NonNull; use std::ptr::NonNull;
use std::rc::Rc; use std::rc::Rc;
use std::string::String; use webgpu::wgpu::{
use webgpu::wgpu::binding_model::BufferBinding; binding_model as wgpu_bind, command::RenderBundleEncoder, pipeline as wgpu_pipe,
use webgpu::{self, wgt, WebGPU, WebGPUBindings, WebGPURequest}; };
use webgpu::{self, wgt, WebGPU, WebGPURequest};
type ErrorScopeId = u64; type ErrorScopeId = u64;
@ -116,6 +119,7 @@ impl GPUDevice {
limits: Heap<*mut JSObject>, limits: Heap<*mut JSObject>,
device: webgpu::WebGPUDevice, device: webgpu::WebGPUDevice,
queue: &GPUQueue, queue: &GPUQueue,
label: Option<String>,
) -> Self { ) -> Self {
Self { Self {
eventtarget: EventTarget::new_inherited(), eventtarget: EventTarget::new_inherited(),
@ -123,7 +127,7 @@ impl GPUDevice {
adapter: Dom::from_ref(adapter), adapter: Dom::from_ref(adapter),
extensions, extensions,
limits, limits,
label: DomRefCell::new(None), label: DomRefCell::new(label.map(|l| USVString::from(l))),
device, device,
default_queue: Dom::from_ref(queue), default_queue: Dom::from_ref(queue),
scope_context: DomRefCell::new(ScopeContext { scope_context: DomRefCell::new(ScopeContext {
@ -144,11 +148,12 @@ impl GPUDevice {
limits: Heap<*mut JSObject>, limits: Heap<*mut JSObject>,
device: webgpu::WebGPUDevice, device: webgpu::WebGPUDevice,
queue: webgpu::WebGPUQueue, queue: webgpu::WebGPUQueue,
label: Option<String>,
) -> DomRoot<Self> { ) -> DomRoot<Self> {
let queue = GPUQueue::new(global, channel.clone(), queue); let queue = GPUQueue::new(global, channel.clone(), queue);
reflect_dom_object( reflect_dom_object(
Box::new(GPUDevice::new_inherited( Box::new(GPUDevice::new_inherited(
channel, adapter, extensions, limits, device, &queue, channel, adapter, extensions, limits, device, &queue, label,
)), )),
global, global,
) )
@ -247,11 +252,7 @@ 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 wgpu_descriptor = wgt::BufferDescriptor { let wgpu_descriptor = wgt::BufferDescriptor {
label: descriptor label: descriptor.parent.label.as_ref().map(|s| s.to_string()),
.parent
.label
.as_ref()
.map(|s| String::from(s.as_ref())),
size: descriptor.size, size: descriptor.size,
usage: match wgt::BufferUsage::from_bits(descriptor.usage) { usage: match wgt::BufferUsage::from_bits(descriptor.usage) {
Some(u) => u, Some(u) => u,
@ -299,6 +300,7 @@ impl GPUDeviceMethods for GPUDevice {
state, state,
descriptor.size, descriptor.size,
map_info, map_info,
descriptor.parent.label.as_ref().cloned(),
) )
} }
@ -401,6 +403,15 @@ impl GPUDeviceMethods for GPUDevice {
} }
} }
let desc = wgt::BindGroupLayoutDescriptor {
label: descriptor
.parent
.label
.as_ref()
.map(|s| Cow::Owned(s.to_string())),
entries: Cow::Owned(entries.clone()),
};
let bind_group_layout_id = self let bind_group_layout_id = self
.global() .global()
.wgpu_id_hub() .wgpu_id_hub()
@ -411,19 +422,18 @@ impl GPUDeviceMethods for GPUDevice {
.send(WebGPURequest::CreateBindGroupLayout { .send(WebGPURequest::CreateBindGroupLayout {
device_id: self.device.0, device_id: self.device.0,
bind_group_layout_id, bind_group_layout_id,
entries: entries.clone(),
scope_id, scope_id,
label: descriptor descriptor: desc,
.parent
.label
.as_ref()
.map(|s| String::from(s.as_ref())),
}) })
.expect("Failed to create WebGPU BindGroupLayout"); .expect("Failed to create WebGPU BindGroupLayout");
let bgl = webgpu::WebGPUBindGroupLayout(bind_group_layout_id); let bgl = webgpu::WebGPUBindGroupLayout(bind_group_layout_id);
let layout = GPUBindGroupLayout::new(&self.global(), bgl); let layout = GPUBindGroupLayout::new(
&self.global(),
bgl,
descriptor.parent.label.as_ref().cloned(),
);
self.bind_group_layouts self.bind_group_layouts
.borrow_mut() .borrow_mut()
@ -437,11 +447,16 @@ impl GPUDeviceMethods for GPUDevice {
&self, &self,
descriptor: &GPUPipelineLayoutDescriptor, descriptor: &GPUPipelineLayoutDescriptor,
) -> DomRoot<GPUPipelineLayout> { ) -> DomRoot<GPUPipelineLayout> {
let mut bgl_ids = Vec::new(); let desc = wgt::PipelineLayoutDescriptor {
bind_group_layouts: Cow::Owned(
descriptor descriptor
.bindGroupLayouts .bindGroupLayouts
.iter() .iter()
.for_each(|each| bgl_ids.push(each.id().0)); .map(|each| each.id().0)
.collect::<Vec<_>>(),
),
push_constant_ranges: Cow::Owned(vec![]),
};
let scope_id = self.use_current_scope(); let scope_id = self.use_current_scope();
@ -455,13 +470,17 @@ impl GPUDeviceMethods for GPUDevice {
.send(WebGPURequest::CreatePipelineLayout { .send(WebGPURequest::CreatePipelineLayout {
device_id: self.device.0, device_id: self.device.0,
pipeline_layout_id, pipeline_layout_id,
bind_group_layouts: bgl_ids, descriptor: desc,
scope_id, scope_id,
}) })
.expect("Failed to create WebGPU PipelineLayout"); .expect("Failed to create WebGPU PipelineLayout");
let pipeline_layout = webgpu::WebGPUPipelineLayout(pipeline_layout_id); let pipeline_layout = webgpu::WebGPUPipelineLayout(pipeline_layout_id);
GPUPipelineLayout::new(&self.global(), pipeline_layout) GPUPipelineLayout::new(
&self.global(),
pipeline_layout,
descriptor.parent.label.as_ref().cloned(),
)
} }
/// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createbindgroup /// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createbindgroup
@ -469,26 +488,36 @@ impl GPUDeviceMethods for GPUDevice {
let entries = descriptor let entries = descriptor
.entries .entries
.iter() .iter()
.map(|bind| { .map(|bind| wgpu_bind::BindGroupEntry {
( binding: bind.binding,
bind.binding, resource: match bind.resource {
match bind.resource { GPUBindingResource::GPUSampler(ref s) => {
GPUBindingResource::GPUSampler(ref s) => WebGPUBindings::Sampler(s.id().0), wgpu_bind::BindingResource::Sampler(s.id().0)
},
GPUBindingResource::GPUTextureView(ref t) => { GPUBindingResource::GPUTextureView(ref t) => {
WebGPUBindings::TextureView(t.id().0) wgpu_bind::BindingResource::TextureView(t.id().0)
}, },
GPUBindingResource::GPUBufferBindings(ref b) => { GPUBindingResource::GPUBufferBindings(ref b) => {
WebGPUBindings::Buffer(BufferBinding { wgpu_bind::BindingResource::Buffer(wgpu_bind::BufferBinding {
buffer_id: b.buffer.id().0, buffer_id: b.buffer.id().0,
offset: b.offset, offset: b.offset,
size: b.size.and_then(wgt::BufferSize::new), size: b.size.and_then(wgt::BufferSize::new),
}) })
}, },
}, },
)
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let desc = wgpu_bind::BindGroupDescriptor {
label: descriptor
.parent
.label
.as_ref()
.map(|l| Cow::Owned(l.to_string())),
layout: descriptor.layout.id().0,
entries: Cow::Owned(entries),
};
let scope_id = self.use_current_scope(); let scope_id = self.use_current_scope();
let bind_group_id = self let bind_group_id = self
@ -501,20 +530,20 @@ impl GPUDeviceMethods for GPUDevice {
.send(WebGPURequest::CreateBindGroup { .send(WebGPURequest::CreateBindGroup {
device_id: self.device.0, device_id: self.device.0,
bind_group_id, bind_group_id,
bind_group_layout_id: descriptor.layout.id().0, descriptor: desc,
entries,
scope_id, scope_id,
label: descriptor
.parent
.label
.as_ref()
.map(|s| String::from(s.as_ref())),
}) })
.expect("Failed to create WebGPU BindGroup"); .expect("Failed to create WebGPU BindGroup");
let bind_group = webgpu::WebGPUBindGroup(bind_group_id); let bind_group = webgpu::WebGPUBindGroup(bind_group_id);
GPUBindGroup::new(&self.global(), bind_group, self.device, &*descriptor.layout) GPUBindGroup::new(
&self.global(),
bind_group,
self.device,
&*descriptor.layout,
descriptor.parent.label.as_ref().cloned(),
)
} }
/// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createshadermodule /// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createshadermodule
@ -543,7 +572,11 @@ impl GPUDeviceMethods for GPUDevice {
.expect("Failed to create WebGPU ShaderModule"); .expect("Failed to create WebGPU ShaderModule");
let shader_module = webgpu::WebGPUShaderModule(program_id); let shader_module = webgpu::WebGPUShaderModule(program_id);
GPUShaderModule::new(&self.global(), shader_module) GPUShaderModule::new(
&self.global(),
shader_module,
descriptor.parent.label.as_ref().cloned(),
)
} }
/// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createcomputepipeline /// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createcomputepipeline
@ -551,9 +584,6 @@ impl GPUDeviceMethods for GPUDevice {
&self, &self,
descriptor: &GPUComputePipelineDescriptor, descriptor: &GPUComputePipelineDescriptor,
) -> DomRoot<GPUComputePipeline> { ) -> DomRoot<GPUComputePipeline> {
let pipeline = descriptor.parent.layout.id();
let program = descriptor.computeStage.module.id();
let entry_point = descriptor.computeStage.entryPoint.to_string();
let compute_pipeline_id = self let compute_pipeline_id = self
.global() .global()
.wgpu_id_hub() .wgpu_id_hub()
@ -562,20 +592,30 @@ impl GPUDeviceMethods for GPUDevice {
let scope_id = self.use_current_scope(); let scope_id = self.use_current_scope();
let desc = wgpu_pipe::ComputePipelineDescriptor {
layout: descriptor.parent.layout.id().0,
compute_stage: wgpu_pipe::ProgrammableStageDescriptor {
module: descriptor.computeStage.module.id().0,
entry_point: Cow::Owned(descriptor.computeStage.entryPoint.to_string()),
},
};
self.channel self.channel
.0 .0
.send(WebGPURequest::CreateComputePipeline { .send(WebGPURequest::CreateComputePipeline {
device_id: self.device.0, device_id: self.device.0,
scope_id, scope_id,
compute_pipeline_id, compute_pipeline_id,
pipeline_layout_id: pipeline.0, descriptor: desc,
program_id: program.0,
entry_point,
}) })
.expect("Failed to create WebGPU ComputePipeline"); .expect("Failed to create WebGPU ComputePipeline");
let compute_pipeline = webgpu::WebGPUComputePipeline(compute_pipeline_id); let compute_pipeline = webgpu::WebGPUComputePipeline(compute_pipeline_id);
GPUComputePipeline::new(&self.global(), compute_pipeline) GPUComputePipeline::new(
&self.global(),
compute_pipeline,
descriptor.parent.parent.label.as_ref().cloned(),
)
} }
/// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createcommandencoder /// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createcommandencoder
@ -593,11 +633,7 @@ impl GPUDeviceMethods for GPUDevice {
.send(WebGPURequest::CreateCommandEncoder { .send(WebGPURequest::CreateCommandEncoder {
device_id: self.device.0, device_id: self.device.0,
command_encoder_id, command_encoder_id,
label: descriptor label: descriptor.parent.label.as_ref().map(|s| s.to_string()),
.parent
.label
.as_ref()
.map(|s| String::from(s.as_ref())),
}) })
.expect("Failed to create WebGPU command encoder"); .expect("Failed to create WebGPU command encoder");
@ -609,6 +645,7 @@ impl GPUDeviceMethods for GPUDevice {
self.device, self.device,
encoder, encoder,
true, true,
descriptor.parent.label.as_ref().cloned(),
) )
} }
@ -616,11 +653,7 @@ impl GPUDeviceMethods for GPUDevice {
fn CreateTexture(&self, descriptor: &GPUTextureDescriptor) -> DomRoot<GPUTexture> { fn CreateTexture(&self, descriptor: &GPUTextureDescriptor) -> DomRoot<GPUTexture> {
let size = convert_texture_size_to_dict(&descriptor.size); let size = convert_texture_size_to_dict(&descriptor.size);
let desc = wgt::TextureDescriptor { let desc = wgt::TextureDescriptor {
label: descriptor label: descriptor.parent.label.as_ref().map(|s| s.to_string()),
.parent
.label
.as_ref()
.map(|s| String::from(s.as_ref())),
size: convert_texture_size_to_wgt(&size), size: convert_texture_size_to_wgt(&size),
mip_level_count: descriptor.mipLevelCount, mip_level_count: descriptor.mipLevelCount,
sample_count: descriptor.sampleCount, sample_count: descriptor.sampleCount,
@ -664,6 +697,7 @@ impl GPUDeviceMethods for GPUDevice {
descriptor.dimension, descriptor.dimension,
descriptor.format, descriptor.format,
descriptor.usage, descriptor.usage,
descriptor.parent.label.as_ref().cloned(),
) )
} }
@ -676,11 +710,7 @@ impl GPUDeviceMethods for GPUDevice {
.create_sampler_id(self.device.0.backend()); .create_sampler_id(self.device.0.backend());
let compare_enable = descriptor.compare.is_some(); let compare_enable = descriptor.compare.is_some();
let desc = wgt::SamplerDescriptor { let desc = wgt::SamplerDescriptor {
label: descriptor label: descriptor.parent.label.as_ref().map(|s| s.to_string()),
.parent
.label
.as_ref()
.map(|s| String::from(s.as_ref())),
address_mode_u: convert_address_mode(descriptor.addressModeU), address_mode_u: convert_address_mode(descriptor.addressModeU),
address_mode_v: convert_address_mode(descriptor.addressModeV), address_mode_v: convert_address_mode(descriptor.addressModeV),
address_mode_w: convert_address_mode(descriptor.addressModeW), address_mode_w: convert_address_mode(descriptor.addressModeW),
@ -704,7 +734,13 @@ impl GPUDeviceMethods for GPUDevice {
let sampler = webgpu::WebGPUSampler(sampler_id); let sampler = webgpu::WebGPUSampler(sampler_id);
GPUSampler::new(&self.global(), self.device, compare_enable, sampler) GPUSampler::new(
&self.global(),
self.device,
compare_enable,
sampler,
descriptor.parent.label.as_ref().cloned(),
)
} }
/// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createrenderpipeline /// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createrenderpipeline
@ -712,23 +748,22 @@ impl GPUDeviceMethods for GPUDevice {
&self, &self,
descriptor: &GPURenderPipelineDescriptor, descriptor: &GPURenderPipelineDescriptor,
) -> DomRoot<GPURenderPipeline> { ) -> DomRoot<GPURenderPipeline> {
let vertex_module = descriptor.vertexStage.module.id().0;
let vertex_entry_point = descriptor.vertexStage.entryPoint.to_string();
let (fragment_module, fragment_entry_point) = match descriptor.fragmentStage {
Some(ref frag) => (Some(frag.module.id().0), Some(frag.entryPoint.to_string())),
None => (None, None),
};
let primitive_topology = match descriptor.primitiveTopology {
GPUPrimitiveTopology::Point_list => wgt::PrimitiveTopology::PointList,
GPUPrimitiveTopology::Line_list => wgt::PrimitiveTopology::LineList,
GPUPrimitiveTopology::Line_strip => wgt::PrimitiveTopology::LineStrip,
GPUPrimitiveTopology::Triangle_list => wgt::PrimitiveTopology::TriangleList,
GPUPrimitiveTopology::Triangle_strip => wgt::PrimitiveTopology::TriangleStrip,
};
let ref rs_desc = descriptor.rasterizationState; let ref rs_desc = descriptor.rasterizationState;
let rasterization_state = wgt::RasterizationStateDescriptor { let ref vs_desc = descriptor.vertexState;
let desc = wgpu_pipe::RenderPipelineDescriptor {
layout: descriptor.parent.layout.id().0,
vertex_stage: wgpu_pipe::ProgrammableStageDescriptor {
module: descriptor.vertexStage.module.id().0,
entry_point: Cow::Owned(descriptor.vertexStage.entryPoint.to_string()),
},
fragment_stage: descriptor.fragmentStage.as_ref().map(|stage| {
wgpu_pipe::ProgrammableStageDescriptor {
module: stage.module.id().0,
entry_point: Cow::Owned(stage.entryPoint.to_string()),
}
}),
rasterization_state: Some(wgt::RasterizationStateDescriptor {
front_face: match rs_desc.frontFace { front_face: match rs_desc.frontFace {
GPUFrontFace::Ccw => wgt::FrontFace::Ccw, GPUFrontFace::Ccw => wgt::FrontFace::Ccw,
GPUFrontFace::Cw => wgt::FrontFace::Cw, GPUFrontFace::Cw => wgt::FrontFace::Cw,
@ -738,12 +773,20 @@ impl GPUDeviceMethods for GPUDevice {
GPUCullMode::Front => wgt::CullMode::Front, GPUCullMode::Front => wgt::CullMode::Front,
GPUCullMode::Back => wgt::CullMode::Back, GPUCullMode::Back => wgt::CullMode::Back,
}, },
clamp_depth: rs_desc.clampDepth,
depth_bias: rs_desc.depthBias, depth_bias: rs_desc.depthBias,
depth_bias_slope_scale: *rs_desc.depthBiasSlopeScale, depth_bias_slope_scale: *rs_desc.depthBiasSlopeScale,
depth_bias_clamp: *rs_desc.depthBiasClamp, depth_bias_clamp: *rs_desc.depthBiasClamp,
}; }),
primitive_topology: match descriptor.primitiveTopology {
let color_states = descriptor GPUPrimitiveTopology::Point_list => wgt::PrimitiveTopology::PointList,
GPUPrimitiveTopology::Line_list => wgt::PrimitiveTopology::LineList,
GPUPrimitiveTopology::Line_strip => wgt::PrimitiveTopology::LineStrip,
GPUPrimitiveTopology::Triangle_list => wgt::PrimitiveTopology::TriangleList,
GPUPrimitiveTopology::Triangle_strip => wgt::PrimitiveTopology::TriangleStrip,
},
color_states: Cow::Owned(
descriptor
.colorStates .colorStates
.iter() .iter()
.map(|state| wgt::ColorStateDescriptor { .map(|state| wgt::ColorStateDescriptor {
@ -755,10 +798,10 @@ impl GPUDeviceMethods for GPUDevice {
None => wgt::ColorWrite::empty(), None => wgt::ColorWrite::empty(),
}, },
}) })
.collect::<ArrayVec<_>>(); .collect::<Vec<_>>(),
),
let depth_stencil_state = if let Some(ref dss_desc) = descriptor.depthStencilState { depth_stencil_state: descriptor.depthStencilState.as_ref().map(|dss_desc| {
Some(wgt::DepthStencilStateDescriptor { wgt::DepthStencilStateDescriptor {
format: convert_texture_format(dss_desc.format), format: convert_texture_format(dss_desc.format),
depth_write_enabled: dss_desc.depthWriteEnabled, depth_write_enabled: dss_desc.depthWriteEnabled,
depth_compare: convert_compare_function(dss_desc.depthCompare), depth_compare: convert_compare_function(dss_desc.depthCompare),
@ -776,27 +819,24 @@ impl GPUDeviceMethods for GPUDevice {
}, },
stencil_read_mask: dss_desc.stencilReadMask, stencil_read_mask: dss_desc.stencilReadMask,
stencil_write_mask: dss_desc.stencilWriteMask, stencil_write_mask: dss_desc.stencilWriteMask,
}) }
} else { }),
None vertex_state: wgt::VertexStateDescriptor {
}; index_format: match vs_desc.indexFormat {
let ref vs_desc = descriptor.vertexState;
let vertex_state = (
match vs_desc.indexFormat {
GPUIndexFormat::Uint16 => wgt::IndexFormat::Uint16, GPUIndexFormat::Uint16 => wgt::IndexFormat::Uint16,
GPUIndexFormat::Uint32 => wgt::IndexFormat::Uint32, GPUIndexFormat::Uint32 => wgt::IndexFormat::Uint32,
}, },
vertex_buffers: Cow::Owned(
vs_desc vs_desc
.vertexBuffers .vertexBuffers
.iter() .iter()
.map(|buffer| { .map(|buffer| wgt::VertexBufferDescriptor {
( stride: buffer.arrayStride,
buffer.arrayStride, step_mode: match buffer.stepMode {
match buffer.stepMode {
GPUInputStepMode::Vertex => wgt::InputStepMode::Vertex, GPUInputStepMode::Vertex => wgt::InputStepMode::Vertex,
GPUInputStepMode::Instance => wgt::InputStepMode::Instance, GPUInputStepMode::Instance => wgt::InputStepMode::Instance,
}, },
attributes: Cow::Owned(
buffer buffer
.attributes .attributes
.iter() .iter()
@ -806,10 +846,15 @@ impl GPUDeviceMethods for GPUDevice {
shader_location: att.shaderLocation, shader_location: att.shaderLocation,
}) })
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
) ),
}) })
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
); ),
},
sample_count: descriptor.sampleCount,
sample_mask: descriptor.sampleMask,
alpha_to_coverage_enabled: descriptor.alphaToCoverageEnabled,
};
let render_pipeline_id = self let render_pipeline_id = self
.global() .global()
@ -825,25 +870,54 @@ impl GPUDeviceMethods for GPUDevice {
device_id: self.device.0, device_id: self.device.0,
render_pipeline_id, render_pipeline_id,
scope_id, scope_id,
pipeline_layout_id: descriptor.parent.layout.id().0, descriptor: desc,
vertex_module,
vertex_entry_point,
fragment_module,
fragment_entry_point,
primitive_topology,
rasterization_state,
color_states,
depth_stencil_state,
vertex_state,
sample_count: descriptor.sampleCount,
sample_mask: descriptor.sampleMask,
alpha_to_coverage_enabled: descriptor.alphaToCoverageEnabled,
}) })
.expect("Failed to create WebGPU render pipeline"); .expect("Failed to create WebGPU render pipeline");
let render_pipeline = webgpu::WebGPURenderPipeline(render_pipeline_id); let render_pipeline = webgpu::WebGPURenderPipeline(render_pipeline_id);
GPURenderPipeline::new(&self.global(), render_pipeline, self.device) GPURenderPipeline::new(
&self.global(),
render_pipeline,
self.device,
descriptor.parent.parent.label.as_ref().cloned(),
)
}
/// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createrenderbundleencoder
fn CreateRenderBundleEncoder(
&self,
descriptor: &GPURenderBundleEncoderDescriptor,
) -> DomRoot<GPURenderBundleEncoder> {
let desc = wgt::RenderBundleEncoderDescriptor {
label: descriptor
.parent
.label
.as_ref()
.map(|s| Cow::Owned(s.to_string())),
color_formats: Cow::Owned(
descriptor
.colorFormats
.iter()
.map(|f| convert_texture_format(*f))
.collect::<Vec<_>>(),
),
depth_stencil_format: descriptor
.depthStencilFormat
.map(|f| convert_texture_format(f)),
sample_count: descriptor.sampleCount,
};
// Handle error gracefully
let render_bundle_encoder = RenderBundleEncoder::new(&desc, self.device.0, None).unwrap();
GPURenderBundleEncoder::new(
&self.global(),
render_bundle_encoder,
self.device,
self.channel.clone(),
descriptor.parent.label.as_ref().cloned(),
)
} }
/// https://gpuweb.github.io/gpuweb/#dom-gpudevice-pusherrorscope /// https://gpuweb.github.io/gpuweb/#dom-gpudevice-pusherrorscope

View file

@ -19,17 +19,21 @@ pub struct GPUPipelineLayout {
} }
impl GPUPipelineLayout { impl GPUPipelineLayout {
fn new_inherited(pipeline_layout: WebGPUPipelineLayout) -> Self { fn new_inherited(pipeline_layout: WebGPUPipelineLayout, label: Option<USVString>) -> Self {
Self { Self {
reflector_: Reflector::new(), reflector_: Reflector::new(),
label: DomRefCell::new(None), label: DomRefCell::new(label),
pipeline_layout, pipeline_layout,
} }
} }
pub fn new(global: &GlobalScope, pipeline_layout: WebGPUPipelineLayout) -> DomRoot<Self> { pub fn new(
global: &GlobalScope,
pipeline_layout: WebGPUPipelineLayout,
label: Option<USVString>,
) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUPipelineLayout::new_inherited(pipeline_layout)), Box::new(GPUPipelineLayout::new_inherited(pipeline_layout, label)),
global, global,
) )
} }

View file

@ -0,0 +1,75 @@
/* 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 crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::GPURenderBundleBinding::GPURenderBundleMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::USVString;
use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use webgpu::{WebGPU, WebGPUDevice, WebGPURenderBundle};
#[dom_struct]
pub struct GPURenderBundle {
reflector_: Reflector,
#[ignore_malloc_size_of = "channels are hard"]
channel: WebGPU,
device: WebGPUDevice,
render_bundle: WebGPURenderBundle,
label: DomRefCell<Option<USVString>>,
}
impl GPURenderBundle {
fn new_inherited(
render_bundle: WebGPURenderBundle,
device: WebGPUDevice,
channel: WebGPU,
label: Option<USVString>,
) -> Self {
Self {
reflector_: Reflector::new(),
render_bundle,
device,
channel,
label: DomRefCell::new(label),
}
}
pub fn new(
global: &GlobalScope,
render_bundle: WebGPURenderBundle,
device: WebGPUDevice,
channel: WebGPU,
label: Option<USVString>,
) -> DomRoot<Self> {
reflect_dom_object(
Box::new(GPURenderBundle::new_inherited(
render_bundle,
device,
channel,
label,
)),
global,
)
}
}
impl GPURenderBundle {
pub fn id(&self) -> WebGPURenderBundle {
self.render_bundle
}
}
impl GPURenderBundleMethods for GPURenderBundle {
/// https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label
fn GetLabel(&self) -> Option<USVString> {
self.label.borrow().clone()
}
/// https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label
fn SetLabel(&self, value: Option<USVString>) {
*self.label.borrow_mut() = value;
}
}

View file

@ -0,0 +1,213 @@
/* 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 crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::GPURenderBundleBinding::GPURenderBundleDescriptor;
use crate::dom::bindings::codegen::Bindings::GPURenderBundleEncoderBinding::GPURenderBundleEncoderMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::USVString;
use crate::dom::globalscope::GlobalScope;
use crate::dom::gpubindgroup::GPUBindGroup;
use crate::dom::gpubuffer::GPUBuffer;
use crate::dom::gpurenderbundle::GPURenderBundle;
use crate::dom::gpurenderpipeline::GPURenderPipeline;
use dom_struct::dom_struct;
use webgpu::{
wgpu::command::{bundle_ffi as wgpu_bundle, RenderBundleEncoder},
wgt, WebGPU, WebGPUDevice, WebGPURenderBundle, WebGPURequest,
};
#[dom_struct]
pub struct GPURenderBundleEncoder {
reflector_: Reflector,
#[ignore_malloc_size_of = "channels are hard"]
channel: WebGPU,
device: WebGPUDevice,
#[ignore_malloc_size_of = "defined in wgpu-core"]
render_bundle_encoder: DomRefCell<Option<RenderBundleEncoder>>,
label: DomRefCell<Option<USVString>>,
}
impl GPURenderBundleEncoder {
fn new_inherited(
render_bundle_encoder: RenderBundleEncoder,
device: WebGPUDevice,
channel: WebGPU,
label: Option<USVString>,
) -> Self {
Self {
reflector_: Reflector::new(),
render_bundle_encoder: DomRefCell::new(Some(render_bundle_encoder)),
device,
channel,
label: DomRefCell::new(label),
}
}
pub fn new(
global: &GlobalScope,
render_bundle_encoder: RenderBundleEncoder,
device: WebGPUDevice,
channel: WebGPU,
label: Option<USVString>,
) -> DomRoot<Self> {
reflect_dom_object(
Box::new(GPURenderBundleEncoder::new_inherited(
render_bundle_encoder,
device,
channel,
label,
)),
global,
)
}
}
impl GPURenderBundleEncoderMethods for GPURenderBundleEncoder {
/// https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label
fn GetLabel(&self) -> Option<USVString> {
self.label.borrow().clone()
}
/// https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label
fn SetLabel(&self, value: Option<USVString>) {
*self.label.borrow_mut() = value;
}
/// https://gpuweb.github.io/gpuweb/#dom-gpuprogrammablepassencoder-setbindgroup
#[allow(unsafe_code)]
fn SetBindGroup(&self, index: u32, bind_group: &GPUBindGroup, dynamic_offsets: Vec<u32>) {
if let Some(encoder) = self.render_bundle_encoder.borrow_mut().as_mut() {
unsafe {
wgpu_bundle::wgpu_render_bundle_set_bind_group(
encoder,
index,
bind_group.id().0,
dynamic_offsets.as_ptr(),
dynamic_offsets.len(),
)
};
}
}
/// https://gpuweb.github.io/gpuweb/#dom-gpurenderencoderbase-setpipeline
fn SetPipeline(&self, pipeline: &GPURenderPipeline) {
if let Some(encoder) = self.render_bundle_encoder.borrow_mut().as_mut() {
wgpu_bundle::wgpu_render_bundle_set_pipeline(encoder, pipeline.id().0);
}
}
/// https://gpuweb.github.io/gpuweb/#dom-gpurenderencoderbase-setindexbuffer
fn SetIndexBuffer(&self, buffer: &GPUBuffer, offset: u64, size: u64) {
if let Some(encoder) = self.render_bundle_encoder.borrow_mut().as_mut() {
wgpu_bundle::wgpu_render_bundle_set_index_buffer(
encoder,
buffer.id().0,
offset,
wgt::BufferSize::new(size),
);
}
}
/// https://gpuweb.github.io/gpuweb/#dom-gpurenderencoderbase-setvertexbuffer
fn SetVertexBuffer(&self, slot: u32, buffer: &GPUBuffer, offset: u64, size: u64) {
if let Some(encoder) = self.render_bundle_encoder.borrow_mut().as_mut() {
wgpu_bundle::wgpu_render_bundle_set_vertex_buffer(
encoder,
slot,
buffer.id().0,
offset,
wgt::BufferSize::new(size),
);
}
}
/// https://gpuweb.github.io/gpuweb/#dom-gpurenderencoderbase-draw
fn Draw(&self, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32) {
if let Some(encoder) = self.render_bundle_encoder.borrow_mut().as_mut() {
wgpu_bundle::wgpu_render_bundle_draw(
encoder,
vertex_count,
instance_count,
first_vertex,
first_instance,
);
}
}
/// https://gpuweb.github.io/gpuweb/#dom-gpurenderencoderbase-drawindexed
fn DrawIndexed(
&self,
index_count: u32,
instance_count: u32,
first_index: u32,
base_vertex: i32,
first_instance: u32,
) {
if let Some(encoder) = self.render_bundle_encoder.borrow_mut().as_mut() {
wgpu_bundle::wgpu_render_bundle_draw_indexed(
encoder,
index_count,
instance_count,
first_index,
base_vertex,
first_instance,
);
}
}
/// https://gpuweb.github.io/gpuweb/#dom-gpurenderencoderbase-drawindirect
fn DrawIndirect(&self, indirect_buffer: &GPUBuffer, indirect_offset: u64) {
if let Some(encoder) = self.render_bundle_encoder.borrow_mut().as_mut() {
wgpu_bundle::wgpu_render_bundle_draw_indirect(
encoder,
indirect_buffer.id().0,
indirect_offset,
);
}
}
/// https://gpuweb.github.io/gpuweb/#dom-gpurenderencoderbase-drawindexedindirect
fn DrawIndexedIndirect(&self, indirect_buffer: &GPUBuffer, indirect_offset: u64) {
if let Some(encoder) = self.render_bundle_encoder.borrow_mut().as_mut() {
wgpu_bundle::wgpu_render_pass_bundle_indexed_indirect(
encoder,
indirect_buffer.id().0,
indirect_offset,
);
}
}
/// https://gpuweb.github.io/gpuweb/#dom-gpurenderbundleencoder-finish
fn Finish(&self, descriptor: &GPURenderBundleDescriptor) -> DomRoot<GPURenderBundle> {
let desc = wgt::RenderBundleDescriptor {
label: descriptor.parent.label.as_ref().map(|s| s.to_string()),
};
let encoder = self.render_bundle_encoder.borrow_mut().take().unwrap();
let render_bundle_id = self
.global()
.wgpu_id_hub()
.lock()
.create_render_bundle_id(self.device.0.backend());
self.channel
.0
.send(WebGPURequest::RenderBundleEncoderFinish {
render_bundle_encoder: encoder,
descriptor: desc,
render_bundle_id,
})
.expect("Failed to send RenderBundleEncoderFinish");
let render_bundle = WebGPURenderBundle(render_bundle_id);
GPURenderBundle::new(
&self.global(),
render_bundle,
self.device,
self.channel.clone(),
descriptor.parent.label.as_ref().cloned(),
)
}
}

View file

@ -13,6 +13,7 @@ use crate::dom::globalscope::GlobalScope;
use crate::dom::gpubindgroup::GPUBindGroup; use crate::dom::gpubindgroup::GPUBindGroup;
use crate::dom::gpubuffer::GPUBuffer; use crate::dom::gpubuffer::GPUBuffer;
use crate::dom::gpucommandencoder::{GPUCommandEncoder, GPUCommandEncoderState}; use crate::dom::gpucommandencoder::{GPUCommandEncoder, GPUCommandEncoderState};
use crate::dom::gpurenderbundle::GPURenderBundle;
use crate::dom::gpurenderpipeline::GPURenderPipeline; use crate::dom::gpurenderpipeline::GPURenderPipeline;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use webgpu::{ use webgpu::{
@ -32,11 +33,16 @@ pub struct GPURenderPassEncoder {
} }
impl GPURenderPassEncoder { impl GPURenderPassEncoder {
fn new_inherited(channel: WebGPU, render_pass: RenderPass, parent: &GPUCommandEncoder) -> Self { fn new_inherited(
channel: WebGPU,
render_pass: RenderPass,
parent: &GPUCommandEncoder,
label: Option<USVString>,
) -> Self {
Self { Self {
channel, channel,
reflector_: Reflector::new(), reflector_: Reflector::new(),
label: DomRefCell::new(None), label: DomRefCell::new(label),
render_pass: DomRefCell::new(Some(render_pass)), render_pass: DomRefCell::new(Some(render_pass)),
command_encoder: Dom::from_ref(parent), command_encoder: Dom::from_ref(parent),
} }
@ -47,12 +53,14 @@ impl GPURenderPassEncoder {
channel: WebGPU, channel: WebGPU,
render_pass: RenderPass, render_pass: RenderPass,
parent: &GPUCommandEncoder, parent: &GPUCommandEncoder,
label: Option<USVString>,
) -> DomRoot<Self> { ) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPURenderPassEncoder::new_inherited( Box::new(GPURenderPassEncoder::new_inherited(
channel, channel,
render_pass, render_pass,
parent, parent,
label,
)), )),
global, global,
) )
@ -125,11 +133,17 @@ impl GPURenderPassEncoderMethods for GPURenderPassEncoder {
b: *d.b, b: *d.b,
a: *d.a, a: *d.a,
}, },
GPUColor::DoubleSequence(s) => wgt::Color { GPUColor::DoubleSequence(mut s) => {
if s.len() < 3 {
s.resize(3, Finite::wrap(0.0f64));
}
s.resize(4, Finite::wrap(1.0f64));
wgt::Color {
r: *s[0], r: *s[0],
g: *s[1], g: *s[1],
b: *s[2], b: *s[2],
a: *s[3], a: *s[3],
}
}, },
}; };
if let Some(render_pass) = self.render_pass.borrow_mut().as_mut() { if let Some(render_pass) = self.render_pass.borrow_mut().as_mut() {
@ -153,7 +167,7 @@ impl GPURenderPassEncoderMethods for GPURenderPassEncoder {
command_encoder_id: self.command_encoder.id().0, command_encoder_id: self.command_encoder.id().0,
render_pass, render_pass,
}) })
.unwrap(); .expect("Failed to send RunRenderPass");
self.command_encoder.set_state( self.command_encoder.set_state(
GPUCommandEncoderState::Open, GPUCommandEncoderState::Open,
@ -249,4 +263,19 @@ impl GPURenderPassEncoderMethods for GPURenderPassEncoder {
); );
} }
} }
/// https://gpuweb.github.io/gpuweb/#dom-gpurenderpassencoder-executebundles
#[allow(unsafe_code)]
fn ExecuteBundles(&self, bundles: Vec<DomRoot<GPURenderBundle>>) {
let bundle_ids = bundles.iter().map(|b| b.id().0).collect::<Vec<_>>();
if let Some(render_pass) = self.render_pass.borrow_mut().as_mut() {
unsafe {
wgpu_render::wgpu_render_pass_execute_bundles(
render_pass,
bundle_ids.as_ptr(),
bundle_ids.len(),
)
};
}
}
} }

View file

@ -21,10 +21,14 @@ pub struct GPURenderPipeline {
} }
impl GPURenderPipeline { impl GPURenderPipeline {
fn new_inherited(render_pipeline: WebGPURenderPipeline, device: WebGPUDevice) -> Self { fn new_inherited(
render_pipeline: WebGPURenderPipeline,
device: WebGPUDevice,
label: Option<USVString>,
) -> Self {
Self { Self {
reflector_: Reflector::new(), reflector_: Reflector::new(),
label: DomRefCell::new(None), label: DomRefCell::new(label),
render_pipeline, render_pipeline,
device, device,
} }
@ -34,9 +38,14 @@ impl GPURenderPipeline {
global: &GlobalScope, global: &GlobalScope,
render_pipeline: WebGPURenderPipeline, render_pipeline: WebGPURenderPipeline,
device: WebGPUDevice, device: WebGPUDevice,
label: Option<USVString>,
) -> DomRoot<Self> { ) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPURenderPipeline::new_inherited(render_pipeline, device)), Box::new(GPURenderPipeline::new_inherited(
render_pipeline,
device,
label,
)),
global, global,
) )
} }

View file

@ -21,10 +21,15 @@ pub struct GPUSampler {
} }
impl GPUSampler { impl GPUSampler {
fn new_inherited(device: WebGPUDevice, compare_enable: bool, sampler: WebGPUSampler) -> Self { fn new_inherited(
device: WebGPUDevice,
compare_enable: bool,
sampler: WebGPUSampler,
label: Option<USVString>,
) -> Self {
Self { Self {
reflector_: Reflector::new(), reflector_: Reflector::new(),
label: DomRefCell::new(None), label: DomRefCell::new(label),
device, device,
sampler, sampler,
compare_enable, compare_enable,
@ -36,9 +41,15 @@ impl GPUSampler {
device: WebGPUDevice, device: WebGPUDevice,
compare_enable: bool, compare_enable: bool,
sampler: WebGPUSampler, sampler: WebGPUSampler,
label: Option<USVString>,
) -> DomRoot<Self> { ) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUSampler::new_inherited(device, compare_enable, sampler)), Box::new(GPUSampler::new_inherited(
device,
compare_enable,
sampler,
label,
)),
global, global,
) )
} }

View file

@ -19,17 +19,21 @@ pub struct GPUShaderModule {
} }
impl GPUShaderModule { impl GPUShaderModule {
fn new_inherited(shader_module: WebGPUShaderModule) -> Self { fn new_inherited(shader_module: WebGPUShaderModule, label: Option<USVString>) -> Self {
Self { Self {
reflector_: Reflector::new(), reflector_: Reflector::new(),
label: DomRefCell::new(None), label: DomRefCell::new(label),
shader_module, shader_module,
} }
} }
pub fn new(global: &GlobalScope, shader_module: WebGPUShaderModule) -> DomRoot<Self> { pub fn new(
global: &GlobalScope,
shader_module: WebGPUShaderModule,
label: Option<USVString>,
) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUShaderModule::new_inherited(shader_module)), Box::new(GPUShaderModule::new_inherited(shader_module, label)),
global, global,
) )
} }

View file

@ -24,13 +24,18 @@ pub struct GPUSwapChain {
} }
impl GPUSwapChain { impl GPUSwapChain {
fn new_inherited(channel: WebGPU, context: &GPUCanvasContext, texture: &GPUTexture) -> Self { fn new_inherited(
channel: WebGPU,
context: &GPUCanvasContext,
texture: &GPUTexture,
label: Option<USVString>,
) -> Self {
Self { Self {
reflector_: Reflector::new(), reflector_: Reflector::new(),
channel, channel,
context: Dom::from_ref(context), context: Dom::from_ref(context),
texture: Dom::from_ref(texture), texture: Dom::from_ref(texture),
label: DomRefCell::new(None), label: DomRefCell::new(label),
} }
} }
@ -39,9 +44,12 @@ impl GPUSwapChain {
channel: WebGPU, channel: WebGPU,
context: &GPUCanvasContext, context: &GPUCanvasContext,
texture: &GPUTexture, texture: &GPUTexture,
label: Option<USVString>,
) -> DomRoot<Self> { ) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUSwapChain::new_inherited(channel, context, texture)), Box::new(GPUSwapChain::new_inherited(
channel, context, texture, label,
)),
global, global,
) )
} }

View file

@ -47,11 +47,12 @@ impl GPUTexture {
dimension: GPUTextureDimension, dimension: GPUTextureDimension,
format: GPUTextureFormat, format: GPUTextureFormat,
texture_usage: u32, texture_usage: u32,
label: Option<USVString>,
) -> Self { ) -> Self {
Self { Self {
reflector_: Reflector::new(), reflector_: Reflector::new(),
texture, texture,
label: DomRefCell::new(None), label: DomRefCell::new(label),
device, device,
channel, channel,
texture_size, texture_size,
@ -74,6 +75,7 @@ impl GPUTexture {
dimension: GPUTextureDimension, dimension: GPUTextureDimension,
format: GPUTextureFormat, format: GPUTextureFormat,
texture_usage: u32, texture_usage: u32,
label: Option<USVString>,
) -> DomRoot<Self> { ) -> DomRoot<Self> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUTexture::new_inherited( Box::new(GPUTexture::new_inherited(
@ -86,6 +88,7 @@ impl GPUTexture {
dimension, dimension,
format, format,
texture_usage, texture_usage,
label,
)), )),
global, global,
) )
@ -179,7 +182,12 @@ impl GPUTextureMethods for GPUTexture {
let texture_view = WebGPUTextureView(texture_view_id); let texture_view = WebGPUTextureView(texture_view_id);
GPUTextureView::new(&self.global(), texture_view, &self) GPUTextureView::new(
&self.global(),
texture_view,
&self,
descriptor.parent.label.as_ref().cloned(),
)
} }
/// https://gpuweb.github.io/gpuweb/#dom-gputexture-destroy /// https://gpuweb.github.io/gpuweb/#dom-gputexture-destroy

View file

@ -21,11 +21,15 @@ pub struct GPUTextureView {
} }
impl GPUTextureView { impl GPUTextureView {
fn new_inherited(texture_view: WebGPUTextureView, texture: &GPUTexture) -> GPUTextureView { fn new_inherited(
texture_view: WebGPUTextureView,
texture: &GPUTexture,
label: Option<USVString>,
) -> GPUTextureView {
Self { Self {
reflector_: Reflector::new(), reflector_: Reflector::new(),
texture: Dom::from_ref(texture), texture: Dom::from_ref(texture),
label: DomRefCell::new(None), label: DomRefCell::new(label),
texture_view, texture_view,
} }
} }
@ -34,9 +38,10 @@ impl GPUTextureView {
global: &GlobalScope, global: &GlobalScope,
texture_view: WebGPUTextureView, texture_view: WebGPUTextureView,
texture: &GPUTexture, texture: &GPUTexture,
label: Option<USVString>,
) -> DomRoot<GPUTextureView> { ) -> DomRoot<GPUTextureView> {
reflect_dom_object( reflect_dom_object(
Box::new(GPUTextureView::new_inherited(texture_view, texture)), Box::new(GPUTextureView::new_inherited(texture_view, texture, label)),
global, global,
) )
} }

View file

@ -7,8 +7,8 @@ use webgpu::wgpu::{
hub::IdentityManager, hub::IdentityManager,
id::{ id::{
AdapterId, BindGroupId, BindGroupLayoutId, BufferId, CommandEncoderId, ComputePipelineId, AdapterId, BindGroupId, BindGroupLayoutId, BufferId, CommandEncoderId, ComputePipelineId,
DeviceId, PipelineLayoutId, RenderPipelineId, SamplerId, ShaderModuleId, TextureId, DeviceId, PipelineLayoutId, RenderBundleId, RenderPipelineId, SamplerId, ShaderModuleId,
TextureViewId, TextureId, TextureViewId,
}, },
}; };
use webgpu::wgt::Backend; use webgpu::wgt::Backend;
@ -28,6 +28,7 @@ pub struct IdentityHub {
texture_views: IdentityManager, texture_views: IdentityManager,
samplers: IdentityManager, samplers: IdentityManager,
render_pipelines: IdentityManager, render_pipelines: IdentityManager,
render_bundles: IdentityManager,
} }
impl IdentityHub { impl IdentityHub {
@ -46,6 +47,7 @@ impl IdentityHub {
texture_views: IdentityManager::default(), texture_views: IdentityManager::default(),
samplers: IdentityManager::default(), samplers: IdentityManager::default(),
render_pipelines: IdentityManager::default(), render_pipelines: IdentityManager::default(),
render_bundles: IdentityManager::default(),
} }
} }
} }
@ -215,4 +217,12 @@ impl Identities {
pub fn kill_texture_view_id(&mut self, id: TextureViewId) { pub fn kill_texture_view_id(&mut self, id: TextureViewId) {
self.select(id.backend()).texture_views.free(id); self.select(id.backend()).texture_views.free(id);
} }
pub fn create_render_bundle_id(&mut self, backend: Backend) -> RenderBundleId {
self.select(backend).render_bundles.alloc(backend)
}
pub fn kill_render_bundle_id(&mut self, id: RenderBundleId) {
self.select(id.backend()).render_bundles.free(id);
}
} }

View file

@ -338,6 +338,8 @@ pub mod gpumapmode;
pub mod gpuoutofmemoryerror; pub mod gpuoutofmemoryerror;
pub mod gpupipelinelayout; pub mod gpupipelinelayout;
pub mod gpuqueue; pub mod gpuqueue;
pub mod gpurenderbundle;
pub mod gpurenderbundleencoder;
pub mod gpurenderpassencoder; pub mod gpurenderpassencoder;
pub mod gpurenderpipeline; pub mod gpurenderpipeline;
pub mod gpusampler; pub mod gpusampler;

View file

@ -3,7 +3,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
// https://gpuweb.github.io/gpuweb/#gpudevice // https://gpuweb.github.io/gpuweb/#gpudevice
[Exposed=(Window, DedicatedWorker)/*, Serializable */, Pref="dom.webgpu.enabled"] [Exposed=(Window, DedicatedWorker), /*Serializable,*/ Pref="dom.webgpu.enabled"]
interface GPUDevice : EventTarget { interface GPUDevice : EventTarget {
[SameObject] readonly attribute GPUAdapter adapter; [SameObject] readonly attribute GPUAdapter adapter;
readonly attribute object extensions; readonly attribute object extensions;
@ -24,7 +24,7 @@ interface GPUDevice : EventTarget {
GPURenderPipeline createRenderPipeline(GPURenderPipelineDescriptor descriptor); GPURenderPipeline createRenderPipeline(GPURenderPipelineDescriptor descriptor);
GPUCommandEncoder createCommandEncoder(optional GPUCommandEncoderDescriptor descriptor = {}); GPUCommandEncoder createCommandEncoder(optional GPUCommandEncoderDescriptor descriptor = {});
// GPURenderBundleEncoder createRenderBundleEncoder(GPURenderBundleEncoderDescriptor descriptor); GPURenderBundleEncoder createRenderBundleEncoder(GPURenderBundleEncoderDescriptor descriptor);
}; };
GPUDevice includes GPUObjectBase; GPUDevice includes GPUObjectBase;

View file

@ -0,0 +1,12 @@
/* 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/. */
// https://gpuweb.github.io/gpuweb/#gpurenderbundle
[Exposed=(Window, DedicatedWorker), Pref="dom.webgpu.enabled"]
interface GPURenderBundle {
};
GPURenderBundle includes GPUObjectBase;
dictionary GPURenderBundleDescriptor : GPUObjectDescriptorBase {
};

View file

@ -0,0 +1,18 @@
/* 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/. */
// https://gpuweb.github.io/gpuweb/#gpurenderbundleencoder
[Exposed=(Window, DedicatedWorker), Pref="dom.webgpu.enabled"]
interface GPURenderBundleEncoder {
GPURenderBundle finish(optional GPURenderBundleDescriptor descriptor = {});
};
GPURenderBundleEncoder includes GPUObjectBase;
GPURenderBundleEncoder includes GPUProgrammablePassEncoder;
GPURenderBundleEncoder includes GPURenderEncoderBase;
dictionary GPURenderBundleEncoderDescriptor : GPUObjectDescriptorBase {
required sequence<GPUTextureFormat> colorFormats;
GPUTextureFormat depthStencilFormat;
GPUSize32 sampleCount = 1;
};

View file

@ -16,9 +16,14 @@ interface GPURenderPassEncoder {
void setStencilReference(GPUStencilValue reference); void setStencilReference(GPUStencilValue reference);
//void beginOcclusionQuery(GPUSize32 queryIndex); //void beginOcclusionQuery(GPUSize32 queryIndex);
//void endOcclusionQuery(GPUSize32 queryIndex); //void endOcclusionQuery();
//void executeBundles(sequence<GPURenderBundle> bundles); //void beginPipelineStatisticsQuery(GPUQuerySet querySet, GPUSize32 queryIndex);
//void endPipelineStatisticsQuery();
//void writeTimestamp(GPUQuerySet querySet, GPUSize32 queryIndex);
void executeBundles(sequence<GPURenderBundle> bundles);
void endPass(); void endPass();
}; };
GPURenderPassEncoder includes GPUObjectBase; GPURenderPassEncoder includes GPUObjectBase;

View file

@ -38,6 +38,8 @@ typedef [EnforceRange] long GPUDepthBias;
dictionary GPURasterizationStateDescriptor { dictionary GPURasterizationStateDescriptor {
GPUFrontFace frontFace = "ccw"; GPUFrontFace frontFace = "ccw";
GPUCullMode cullMode = "none"; GPUCullMode cullMode = "none";
// Enable depth clamping (requires "depth-clamping" extension)
boolean clampDepth = false;
GPUDepthBias depthBias = 0; GPUDepthBias depthBias = 0;
float depthBiasSlopeScale = 0; float depthBiasSlopeScale = 0;

View file

@ -2057,6 +2057,7 @@ impl ScriptThread {
WebGPUMsg::FreeCommandBuffer(id) => self.gpu_id_hub.lock().kill_command_buffer_id(id), WebGPUMsg::FreeCommandBuffer(id) => self.gpu_id_hub.lock().kill_command_buffer_id(id),
WebGPUMsg::FreeSampler(id) => self.gpu_id_hub.lock().kill_sampler_id(id), WebGPUMsg::FreeSampler(id) => self.gpu_id_hub.lock().kill_sampler_id(id),
WebGPUMsg::FreeShaderModule(id) => self.gpu_id_hub.lock().kill_shader_module_id(id), WebGPUMsg::FreeShaderModule(id) => self.gpu_id_hub.lock().kill_shader_module_id(id),
WebGPUMsg::FreeRenderBundle(id) => self.gpu_id_hub.lock().kill_render_bundle_id(id),
WebGPUMsg::FreeRenderPipeline(id) => self.gpu_id_hub.lock().kill_render_pipeline_id(id), WebGPUMsg::FreeRenderPipeline(id) => self.gpu_id_hub.lock().kill_render_pipeline_id(id),
WebGPUMsg::FreeTexture(id) => self.gpu_id_hub.lock().kill_texture_id(id), WebGPUMsg::FreeTexture(id) => self.gpu_id_hub.lock().kill_texture_id(id),
WebGPUMsg::FreeTextureView(id) => self.gpu_id_hub.lock().kill_texture_view_id(id), WebGPUMsg::FreeTextureView(id) => self.gpu_id_hub.lock().kill_texture_view_id(id),

View file

@ -19,6 +19,7 @@ use msg::constellation_msg::PipelineId;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use servo_config::pref; use servo_config::pref;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::borrow::Cow;
use std::collections::HashMap; use std::collections::HashMap;
use std::ffi::CString; use std::ffi::CString;
use std::ptr; use std::ptr;
@ -31,11 +32,12 @@ use webrender_traits::{
WebrenderImageSource, WebrenderImageSource,
}; };
use wgpu::{ use wgpu::{
binding_model::{BindGroupDescriptor, BindGroupEntry, BindingResource, BufferBinding}, binding_model::BindGroupDescriptor,
command::{BufferCopyView, ComputePass, RenderPass, TextureCopyView}, command::{BufferCopyView, ComputePass, RenderBundleEncoder, RenderPass, TextureCopyView},
device::HostMap, device::HostMap,
id, id,
instance::RequestAdapterOptions, instance::RequestAdapterOptions,
pipeline::{ComputePipelineDescriptor, RenderPipelineDescriptor},
resource::{BufferMapAsyncStatus, BufferMapOperation}, resource::{BufferMapAsyncStatus, BufferMapOperation},
}; };
@ -53,6 +55,7 @@ pub enum WebGPUResponse {
device_id: WebGPUDevice, device_id: WebGPUDevice,
queue_id: WebGPUQueue, queue_id: WebGPUQueue,
_descriptor: wgt::DeviceDescriptor, _descriptor: wgt::DeviceDescriptor,
label: Option<String>,
}, },
BufferMapAsync(IpcSharedMemory), BufferMapAsync(IpcSharedMemory),
} }
@ -104,16 +107,13 @@ pub enum WebGPURequest {
// TODO: Consider using NonZeroU64 to reduce enum size // TODO: Consider using NonZeroU64 to reduce enum size
scope_id: Option<u64>, scope_id: Option<u64>,
bind_group_id: id::BindGroupId, bind_group_id: id::BindGroupId,
bind_group_layout_id: id::BindGroupLayoutId, descriptor: BindGroupDescriptor<'static>,
entries: Vec<(u32, WebGPUBindings)>,
label: Option<String>,
}, },
CreateBindGroupLayout { CreateBindGroupLayout {
device_id: id::DeviceId, device_id: id::DeviceId,
scope_id: Option<u64>, scope_id: Option<u64>,
bind_group_layout_id: id::BindGroupLayoutId, bind_group_layout_id: id::BindGroupLayoutId,
entries: Vec<wgt::BindGroupLayoutEntry>, descriptor: wgt::BindGroupLayoutDescriptor<'static>,
label: Option<String>,
}, },
CreateBuffer { CreateBuffer {
device_id: id::DeviceId, device_id: id::DeviceId,
@ -131,37 +131,20 @@ pub enum WebGPURequest {
device_id: id::DeviceId, device_id: id::DeviceId,
scope_id: Option<u64>, scope_id: Option<u64>,
compute_pipeline_id: id::ComputePipelineId, compute_pipeline_id: id::ComputePipelineId,
pipeline_layout_id: id::PipelineLayoutId, descriptor: ComputePipelineDescriptor<'static>,
program_id: id::ShaderModuleId,
entry_point: String,
}, },
CreateContext(IpcSender<webrender_api::ExternalImageId>), CreateContext(IpcSender<webrender_api::ExternalImageId>),
CreatePipelineLayout { CreatePipelineLayout {
device_id: id::DeviceId, device_id: id::DeviceId,
scope_id: Option<u64>, scope_id: Option<u64>,
pipeline_layout_id: id::PipelineLayoutId, pipeline_layout_id: id::PipelineLayoutId,
bind_group_layouts: Vec<id::BindGroupLayoutId>, descriptor: wgt::PipelineLayoutDescriptor<'static, id::BindGroupLayoutId>,
}, },
CreateRenderPipeline { CreateRenderPipeline {
device_id: id::DeviceId, device_id: id::DeviceId,
scope_id: Option<u64>, scope_id: Option<u64>,
render_pipeline_id: id::RenderPipelineId, render_pipeline_id: id::RenderPipelineId,
pipeline_layout_id: id::PipelineLayoutId, descriptor: RenderPipelineDescriptor<'static>,
vertex_module: id::ShaderModuleId,
vertex_entry_point: String,
fragment_module: Option<id::ShaderModuleId>,
fragment_entry_point: Option<String>,
primitive_topology: wgt::PrimitiveTopology,
rasterization_state: wgt::RasterizationStateDescriptor,
color_states: ArrayVec<[wgt::ColorStateDescriptor; wgpu::device::MAX_COLOR_TARGETS]>,
depth_stencil_state: Option<wgt::DepthStencilStateDescriptor>,
vertex_state: (
wgt::IndexFormat,
Vec<(u64, wgt::InputStepMode, Vec<wgt::VertexAttributeDescriptor>)>,
),
sample_count: u32,
sample_mask: u32,
alpha_to_coverage_enabled: bool,
}, },
CreateSampler { CreateSampler {
device_id: id::DeviceId, device_id: id::DeviceId,
@ -199,6 +182,11 @@ pub enum WebGPURequest {
DestroyTexture(id::TextureId), DestroyTexture(id::TextureId),
Exit(IpcSender<()>), Exit(IpcSender<()>),
FreeDevice(id::DeviceId), FreeDevice(id::DeviceId),
RenderBundleEncoderFinish {
render_bundle_encoder: RenderBundleEncoder,
descriptor: wgt::RenderBundleDescriptor<Option<String>>,
render_bundle_id: id::RenderBundleId,
},
RequestAdapter { RequestAdapter {
sender: IpcSender<WebGPUResponseResult>, sender: IpcSender<WebGPUResponseResult>,
options: RequestAdapterOptions, options: RequestAdapterOptions,
@ -210,6 +198,7 @@ pub enum WebGPURequest {
descriptor: wgt::DeviceDescriptor, descriptor: wgt::DeviceDescriptor,
device_id: id::DeviceId, device_id: id::DeviceId,
pipeline_id: PipelineId, pipeline_id: PipelineId,
label: Option<String>,
}, },
RunComputePass { RunComputePass {
command_encoder_id: id::CommandEncoderId, command_encoder_id: id::CommandEncoderId,
@ -255,13 +244,6 @@ pub enum WebGPURequest {
}, },
} }
#[derive(Debug, Deserialize, Serialize)]
pub enum WebGPUBindings {
Buffer(BufferBinding),
Sampler(id::SamplerId),
TextureView(id::TextureViewId),
}
struct BufferMapInfo<'a, T> { struct BufferMapInfo<'a, T> {
buffer_id: id::BufferId, buffer_id: id::BufferId,
sender: IpcSender<T>, sender: IpcSender<T>,
@ -420,7 +402,8 @@ impl<'a> WGPU<'a> {
BufferMapAsyncStatus::Success => { BufferMapAsyncStatus::Success => {
let global = &info.global; let global = &info.global;
let data_pt = gfx_select!(info.buffer_id => let data_pt = gfx_select!(info.buffer_id =>
global.buffer_get_mapped_range(info.buffer_id, 0, None)); global.buffer_get_mapped_range(info.buffer_id, 0, None))
.unwrap();
let data = slice::from_raw_parts(data_pt, info.size); let data = slice::from_raw_parts(data_pt, info.size);
if let Err(e) = if let Err(e) =
info.sender.send(Ok(WebGPUResponse::BufferMapAsync( info.sender.send(Ok(WebGPUResponse::BufferMapAsync(
@ -442,7 +425,7 @@ impl<'a> WGPU<'a> {
), ),
}; };
let global = &self.global; let global = &self.global;
gfx_select!(buffer_id => global.buffer_map_async(buffer_id, map_range, operation)); let _ = gfx_select!(buffer_id => global.buffer_map_async(buffer_id, map_range, operation));
}, },
WebGPURequest::BufferMapComplete(buffer_id) => { WebGPURequest::BufferMapComplete(buffer_id) => {
self.buffer_maps.remove(&buffer_id); self.buffer_maps.remove(&buffer_id);
@ -518,32 +501,9 @@ impl<'a> WGPU<'a> {
device_id, device_id,
scope_id, scope_id,
bind_group_id, bind_group_id,
bind_group_layout_id, descriptor,
mut entries,
label,
} => { } => {
let global = &self.global; let global = &self.global;
let bindings = entries
.drain(..)
.map(|(bind, res)| {
let resource = match res {
WebGPUBindings::Sampler(s) => BindingResource::Sampler(s),
WebGPUBindings::TextureView(t) => {
BindingResource::TextureView(t)
},
WebGPUBindings::Buffer(b) => BindingResource::Buffer(b),
};
BindGroupEntry {
binding: bind,
resource,
}
})
.collect::<Vec<_>>();
let descriptor = BindGroupDescriptor {
label: label.as_deref(),
layout: bind_group_layout_id,
entries: bindings.as_slice(),
};
let result = gfx_select!(bind_group_id => let result = gfx_select!(bind_group_id =>
global.device_create_bind_group(device_id, &descriptor, bind_group_id)); global.device_create_bind_group(device_id, &descriptor, bind_group_id));
if let Some(s_id) = scope_id { if let Some(s_id) = scope_id {
@ -554,14 +514,9 @@ impl<'a> WGPU<'a> {
device_id, device_id,
scope_id, scope_id,
bind_group_layout_id, bind_group_layout_id,
entries, descriptor,
label,
} => { } => {
let global = &self.global; let global = &self.global;
let descriptor = wgt::BindGroupLayoutDescriptor {
entries: entries.as_slice(),
label: label.as_deref(),
};
let result = gfx_select!(bind_group_layout_id => let result = gfx_select!(bind_group_layout_id =>
global.device_create_bind_group_layout(device_id, &descriptor, bind_group_layout_id)); global.device_create_bind_group_layout(device_id, &descriptor, bind_group_layout_id));
if let Some(s_id) = scope_id { if let Some(s_id) = scope_id {
@ -607,18 +562,9 @@ impl<'a> WGPU<'a> {
device_id, device_id,
scope_id, scope_id,
compute_pipeline_id, compute_pipeline_id,
pipeline_layout_id, descriptor,
program_id,
entry_point,
} => { } => {
let global = &self.global; let global = &self.global;
let descriptor = wgpu_core::pipeline::ComputePipelineDescriptor {
layout: pipeline_layout_id,
compute_stage: wgpu_core::pipeline::ProgrammableStageDescriptor {
module: program_id,
entry_point: entry_point.as_str(),
},
};
let result = gfx_select!(compute_pipeline_id => let result = gfx_select!(compute_pipeline_id =>
global.device_create_compute_pipeline(device_id, &descriptor, compute_pipeline_id)); global.device_create_compute_pipeline(device_id, &descriptor, compute_pipeline_id));
if let Some(s_id) = scope_id { if let Some(s_id) = scope_id {
@ -639,13 +585,9 @@ impl<'a> WGPU<'a> {
device_id, device_id,
scope_id, scope_id,
pipeline_layout_id, pipeline_layout_id,
bind_group_layouts, descriptor,
} => { } => {
let global = &self.global; let global = &self.global;
let descriptor = wgt::PipelineLayoutDescriptor {
bind_group_layouts: bind_group_layouts.as_slice(),
push_constant_ranges: &[],
};
let result = gfx_select!(pipeline_layout_id => let result = gfx_select!(pipeline_layout_id =>
global.device_create_pipeline_layout(device_id, &descriptor, pipeline_layout_id)); global.device_create_pipeline_layout(device_id, &descriptor, pipeline_layout_id));
if let Some(s_id) = scope_id { if let Some(s_id) = scope_id {
@ -657,65 +599,9 @@ impl<'a> WGPU<'a> {
device_id, device_id,
scope_id, scope_id,
render_pipeline_id, render_pipeline_id,
pipeline_layout_id, descriptor,
vertex_module,
vertex_entry_point,
fragment_module,
fragment_entry_point,
primitive_topology,
rasterization_state,
color_states,
depth_stencil_state,
vertex_state,
sample_count,
sample_mask,
alpha_to_coverage_enabled,
} => { } => {
let global = &self.global; let global = &self.global;
let frag_ep;
let fragment_stage = match fragment_module {
Some(frag) => {
frag_ep = fragment_entry_point.unwrap().clone();
let frag_module =
wgpu_core::pipeline::ProgrammableStageDescriptor {
module: frag,
entry_point: frag_ep.as_str(),
};
Some(frag_module)
},
None => None,
};
let vert_buffers = vertex_state
.1
.iter()
.map(|&(stride, step_mode, ref attributes)| {
wgt::VertexBufferDescriptor {
stride,
step_mode,
attributes: attributes.as_slice(),
}
})
.collect::<Vec<_>>();
let descriptor = wgpu_core::pipeline::RenderPipelineDescriptor {
layout: pipeline_layout_id,
vertex_stage: wgpu_core::pipeline::ProgrammableStageDescriptor {
module: vertex_module,
entry_point: vertex_entry_point.as_str(),
},
fragment_stage,
primitive_topology,
rasterization_state: Some(rasterization_state),
color_states: color_states.as_slice(),
depth_stencil_state,
vertex_state: wgt::VertexStateDescriptor {
index_format: vertex_state.0,
vertex_buffers: vert_buffers.as_slice(),
},
sample_count,
sample_mask,
alpha_to_coverage_enabled,
};
let result = gfx_select!(render_pipeline_id => let result = gfx_select!(render_pipeline_id =>
global.device_create_render_pipeline(device_id, &descriptor, render_pipeline_id)); global.device_create_render_pipeline(device_id, &descriptor, render_pipeline_id));
if let Some(s_id) = scope_id { if let Some(s_id) = scope_id {
@ -748,7 +634,8 @@ impl<'a> WGPU<'a> {
program, program,
} => { } => {
let global = &self.global; let global = &self.global;
let source = wgpu_core::pipeline::ShaderModuleSource::SpirV(&program); let source =
wgpu_core::pipeline::ShaderModuleSource::SpirV(Cow::Owned(program));
let _ = gfx_select!(program_id => let _ = gfx_select!(program_id =>
global.device_create_shader_module(device_id, source, program_id)); global.device_create_shader_module(device_id, source, program_id));
}, },
@ -888,6 +775,26 @@ impl<'a> WGPU<'a> {
warn!("Unable to send CleanDevice({:?}) ({:?})", device_id, e); warn!("Unable to send CleanDevice({:?}) ({:?})", device_id, e);
} }
}, },
WebGPURequest::RenderBundleEncoderFinish {
render_bundle_encoder,
descriptor,
render_bundle_id,
} => {
let global = &self.global;
let st;
let label = match descriptor.label {
Some(ref s) => {
st = CString::new(s.as_bytes()).unwrap();
st.as_ptr()
},
None => ptr::null(),
};
let _ = gfx_select!(render_bundle_id => global.render_bundle_encoder_finish(
render_bundle_encoder,
&descriptor.map_label(|_| label),
render_bundle_id
));
},
WebGPURequest::RequestAdapter { WebGPURequest::RequestAdapter {
sender, sender,
options, options,
@ -931,6 +838,7 @@ impl<'a> WGPU<'a> {
descriptor, descriptor,
device_id, device_id,
pipeline_id, pipeline_id,
label,
} => { } => {
let global = &self.global; let global = &self.global;
let result = gfx_select!(device_id => global.adapter_request_device( let result = gfx_select!(device_id => global.adapter_request_device(
@ -950,6 +858,7 @@ impl<'a> WGPU<'a> {
device_id: device, device_id: device,
queue_id: queue, queue_id: queue,
_descriptor: descriptor, _descriptor: descriptor,
label,
})) { })) {
warn!( warn!(
"Failed to send response to WebGPURequest::RequestDevice ({})", "Failed to send response to WebGPURequest::RequestDevice ({})",
@ -1117,7 +1026,7 @@ impl<'a> WGPU<'a> {
self.present_buffer_maps.get(&buffer_id).unwrap().clone(), self.present_buffer_maps.get(&buffer_id).unwrap().clone(),
), ),
}; };
gfx_select!(buffer_id => global.buffer_map_async(buffer_id, 0..buffer_size, map_op)); let _ = gfx_select!(buffer_id => global.buffer_map_async(buffer_id, 0..buffer_size, map_op));
}, },
WebGPURequest::UnmapBuffer { WebGPURequest::UnmapBuffer {
buffer_id, buffer_id,
@ -1132,11 +1041,12 @@ impl<'a> WGPU<'a> {
buffer_id, buffer_id,
offset, offset,
wgt::BufferSize::new(size) wgt::BufferSize::new(size)
)); ))
.unwrap();
unsafe { slice::from_raw_parts_mut(map_ptr, size as usize) } unsafe { slice::from_raw_parts_mut(map_ptr, size as usize) }
.copy_from_slice(&array_buffer); .copy_from_slice(&array_buffer);
} }
gfx_select!(buffer_id => global.buffer_unmap(buffer_id)); let _ = gfx_select!(buffer_id => global.buffer_unmap(buffer_id));
}, },
WebGPURequest::UpdateWebRenderData { WebGPURequest::UpdateWebRenderData {
buffer_id, buffer_id,
@ -1145,7 +1055,8 @@ impl<'a> WGPU<'a> {
} => { } => {
let global = &self.global; let global = &self.global;
let data_pt = gfx_select!(buffer_id => let data_pt = gfx_select!(buffer_id =>
global.buffer_get_mapped_range(buffer_id, 0, None)); global.buffer_get_mapped_range(buffer_id, 0, None))
.unwrap();
let data = unsafe { slice::from_raw_parts(data_pt, buffer_size) }.to_vec(); let data = unsafe { slice::from_raw_parts(data_pt, buffer_size) }.to_vec();
if let Some(present_data) = if let Some(present_data) =
self.wgpu_image_map.lock().unwrap().get_mut(&external_id) self.wgpu_image_map.lock().unwrap().get_mut(&external_id)
@ -1167,7 +1078,7 @@ impl<'a> WGPU<'a> {
} else { } else {
warn!("Data not found for ExternalImageId({:?})", external_id); warn!("Data not found for ExternalImageId({:?})", external_id);
} }
gfx_select!(buffer_id => global.buffer_unmap(buffer_id)); let _ = gfx_select!(buffer_id => global.buffer_unmap(buffer_id));
self.present_buffer_maps.remove(&buffer_id); self.present_buffer_maps.remove(&buffer_id);
}, },
WebGPURequest::WriteBuffer { WebGPURequest::WriteBuffer {
@ -1256,6 +1167,7 @@ webgpu_resource!(WebGPUComputePipeline, id::ComputePipelineId);
webgpu_resource!(WebGPUDevice, id::DeviceId); webgpu_resource!(WebGPUDevice, id::DeviceId);
webgpu_resource!(WebGPUPipelineLayout, id::PipelineLayoutId); webgpu_resource!(WebGPUPipelineLayout, id::PipelineLayoutId);
webgpu_resource!(WebGPUQueue, id::QueueId); webgpu_resource!(WebGPUQueue, id::QueueId);
webgpu_resource!(WebGPURenderBundle, id::RenderBundleId);
webgpu_resource!(WebGPURenderPipeline, id::RenderPipelineId); webgpu_resource!(WebGPURenderPipeline, id::RenderPipelineId);
webgpu_resource!(WebGPUSampler, id::SamplerId); webgpu_resource!(WebGPUSampler, id::SamplerId);
webgpu_resource!(WebGPUShaderModule, id::ShaderModuleId); webgpu_resource!(WebGPUShaderModule, id::ShaderModuleId);