summaryrefslogtreecommitdiffstats
path: root/gfx/wgpu_bindings/src
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-07 19:33:14 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-07 19:33:14 +0000
commit36d22d82aa202bb199967e9512281e9a53db42c9 (patch)
tree105e8c98ddea1c1e4784a60a5a6410fa416be2de /gfx/wgpu_bindings/src
parentInitial commit. (diff)
downloadfirefox-esr-36d22d82aa202bb199967e9512281e9a53db42c9.tar.xz
firefox-esr-36d22d82aa202bb199967e9512281e9a53db42c9.zip
Adding upstream version 115.7.0esr.upstream/115.7.0esr
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'gfx/wgpu_bindings/src')
-rw-r--r--gfx/wgpu_bindings/src/client.rs1150
-rw-r--r--gfx/wgpu_bindings/src/identity.rs225
-rw-r--r--gfx/wgpu_bindings/src/lib.rs218
-rw-r--r--gfx/wgpu_bindings/src/server.rs993
4 files changed, 2586 insertions, 0 deletions
diff --git a/gfx/wgpu_bindings/src/client.rs b/gfx/wgpu_bindings/src/client.rs
new file mode 100644
index 0000000000..78f91ec365
--- /dev/null
+++ b/gfx/wgpu_bindings/src/client.rs
@@ -0,0 +1,1150 @@
+/* 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 http://mozilla.org/MPL/2.0/. */
+
+use crate::{
+ cow_label, wgpu_string, AdapterInformation, ByteBuf, CommandEncoderAction, DeviceAction,
+ DropAction, ImageDataLayout, ImplicitLayout, QueueWriteAction, RawString, TextureAction,
+};
+
+use wgc::{hub::IdentityManager, id};
+use wgt::{Backend, TextureFormat};
+
+pub use wgc::command::{compute_ffi::*, render_ffi::*};
+
+use parking_lot::Mutex;
+
+use nsstring::{nsACString, nsString};
+
+use std::{borrow::Cow, ptr};
+
+// we can't call `from_raw_parts` unconditionally because the caller
+// may not even have a valid pointer (e.g. NULL) if the `length` is zero.
+fn make_slice<'a, T>(pointer: *const T, length: usize) -> &'a [T] {
+ if length == 0 {
+ &[]
+ } else {
+ unsafe { std::slice::from_raw_parts(pointer, length) }
+ }
+}
+
+fn make_byte_buf<T: serde::Serialize>(data: &T) -> ByteBuf {
+ let vec = bincode::serialize(data).unwrap();
+ ByteBuf::from_vec(vec)
+}
+
+#[repr(C)]
+pub struct ProgrammableStageDescriptor {
+ module: id::ShaderModuleId,
+ entry_point: RawString,
+}
+
+impl ProgrammableStageDescriptor {
+ fn to_wgpu(&self) -> wgc::pipeline::ProgrammableStageDescriptor {
+ wgc::pipeline::ProgrammableStageDescriptor {
+ module: self.module,
+ entry_point: cow_label(&self.entry_point).unwrap(),
+ }
+ }
+}
+
+#[repr(C)]
+pub struct ComputePipelineDescriptor {
+ label: RawString,
+ layout: Option<id::PipelineLayoutId>,
+ stage: ProgrammableStageDescriptor,
+}
+
+#[repr(C)]
+pub struct VertexBufferLayout {
+ array_stride: wgt::BufferAddress,
+ step_mode: wgt::VertexStepMode,
+ attributes: *const wgt::VertexAttribute,
+ attributes_length: usize,
+}
+
+#[repr(C)]
+pub struct VertexState {
+ stage: ProgrammableStageDescriptor,
+ buffers: *const VertexBufferLayout,
+ buffers_length: usize,
+}
+
+impl VertexState {
+ fn to_wgpu(&self) -> wgc::pipeline::VertexState {
+ let buffer_layouts = make_slice(self.buffers, self.buffers_length)
+ .iter()
+ .map(|vb| wgc::pipeline::VertexBufferLayout {
+ array_stride: vb.array_stride,
+ step_mode: vb.step_mode,
+ attributes: Cow::Borrowed(make_slice(vb.attributes, vb.attributes_length)),
+ })
+ .collect();
+ wgc::pipeline::VertexState {
+ stage: self.stage.to_wgpu(),
+ buffers: Cow::Owned(buffer_layouts),
+ }
+ }
+}
+
+#[repr(C)]
+pub struct ColorTargetState<'a> {
+ format: wgt::TextureFormat,
+ blend: Option<&'a wgt::BlendState>,
+ write_mask: wgt::ColorWrites,
+}
+
+#[repr(C)]
+pub struct FragmentState<'a> {
+ stage: ProgrammableStageDescriptor,
+ targets: *const ColorTargetState<'a>,
+ targets_length: usize,
+}
+
+impl FragmentState<'_> {
+ fn to_wgpu(&self) -> wgc::pipeline::FragmentState {
+ let color_targets = make_slice(self.targets, self.targets_length)
+ .iter()
+ .map(|ct| {
+ Some(wgt::ColorTargetState {
+ format: ct.format,
+ blend: ct.blend.cloned(),
+ write_mask: ct.write_mask,
+ })
+ })
+ .collect();
+ wgc::pipeline::FragmentState {
+ stage: self.stage.to_wgpu(),
+ targets: Cow::Owned(color_targets),
+ }
+ }
+}
+
+#[repr(C)]
+pub struct PrimitiveState<'a> {
+ topology: wgt::PrimitiveTopology,
+ strip_index_format: Option<&'a wgt::IndexFormat>,
+ front_face: wgt::FrontFace,
+ cull_mode: Option<&'a wgt::Face>,
+ polygon_mode: wgt::PolygonMode,
+ unclipped_depth: bool,
+}
+
+impl PrimitiveState<'_> {
+ fn to_wgpu(&self) -> wgt::PrimitiveState {
+ wgt::PrimitiveState {
+ topology: self.topology,
+ strip_index_format: self.strip_index_format.cloned(),
+ front_face: self.front_face.clone(),
+ cull_mode: self.cull_mode.cloned(),
+ polygon_mode: self.polygon_mode,
+ unclipped_depth: self.unclipped_depth,
+ conservative: false,
+ }
+ }
+}
+
+#[repr(C)]
+pub struct RenderPipelineDescriptor<'a> {
+ label: Option<&'a nsACString>,
+ layout: Option<id::PipelineLayoutId>,
+ vertex: &'a VertexState,
+ primitive: PrimitiveState<'a>,
+ fragment: Option<&'a FragmentState<'a>>,
+ depth_stencil: Option<&'a wgt::DepthStencilState>,
+ multisample: wgt::MultisampleState,
+}
+
+#[repr(C)]
+pub enum RawTextureSampleType {
+ Float,
+ UnfilterableFloat,
+ Uint,
+ Sint,
+ Depth,
+}
+
+#[repr(C)]
+pub enum RawBindingType {
+ UniformBuffer,
+ StorageBuffer,
+ ReadonlyStorageBuffer,
+ Sampler,
+ SampledTexture,
+ ReadonlyStorageTexture,
+ WriteonlyStorageTexture,
+}
+
+#[repr(C)]
+pub struct BindGroupLayoutEntry<'a> {
+ binding: u32,
+ visibility: wgt::ShaderStages,
+ ty: RawBindingType,
+ has_dynamic_offset: bool,
+ min_binding_size: Option<wgt::BufferSize>,
+ view_dimension: Option<&'a wgt::TextureViewDimension>,
+ texture_sample_type: Option<&'a RawTextureSampleType>,
+ multisampled: bool,
+ storage_texture_format: Option<&'a wgt::TextureFormat>,
+ sampler_filter: bool,
+ sampler_compare: bool,
+}
+
+#[repr(C)]
+pub struct BindGroupLayoutDescriptor<'a> {
+ label: Option<&'a nsACString>,
+ entries: *const BindGroupLayoutEntry<'a>,
+ entries_length: usize,
+}
+
+#[repr(C)]
+#[derive(Debug)]
+pub struct BindGroupEntry {
+ binding: u32,
+ buffer: Option<id::BufferId>,
+ offset: wgt::BufferAddress,
+ size: Option<wgt::BufferSize>,
+ sampler: Option<id::SamplerId>,
+ texture_view: Option<id::TextureViewId>,
+}
+
+#[repr(C)]
+pub struct BindGroupDescriptor<'a> {
+ label: Option<&'a nsACString>,
+ layout: id::BindGroupLayoutId,
+ entries: *const BindGroupEntry,
+ entries_length: usize,
+}
+
+#[repr(C)]
+pub struct PipelineLayoutDescriptor<'a> {
+ label: Option<&'a nsACString>,
+ bind_group_layouts: *const id::BindGroupLayoutId,
+ bind_group_layouts_length: usize,
+}
+
+#[repr(C)]
+pub struct SamplerDescriptor<'a> {
+ label: Option<&'a nsACString>,
+ address_modes: [wgt::AddressMode; 3],
+ mag_filter: wgt::FilterMode,
+ min_filter: wgt::FilterMode,
+ mipmap_filter: wgt::FilterMode,
+ lod_min_clamp: f32,
+ lod_max_clamp: f32,
+ compare: Option<&'a wgt::CompareFunction>,
+ anisotropy_clamp: Option<&'a u16>,
+}
+
+#[repr(C)]
+pub struct TextureViewDescriptor<'a> {
+ label: Option<&'a nsACString>,
+ format: Option<&'a wgt::TextureFormat>,
+ dimension: Option<&'a wgt::TextureViewDimension>,
+ aspect: wgt::TextureAspect,
+ base_mip_level: u32,
+ mip_level_count: Option<&'a u32>,
+ base_array_layer: u32,
+ array_layer_count: Option<&'a u32>,
+}
+
+#[repr(C)]
+pub struct RenderBundleEncoderDescriptor<'a> {
+ label: Option<&'a nsACString>,
+ color_formats: *const wgt::TextureFormat,
+ color_formats_length: usize,
+ depth_stencil_format: Option<&'a wgt::TextureFormat>,
+ depth_read_only: bool,
+ stencil_read_only: bool,
+ sample_count: u32,
+}
+
+#[derive(Debug, Default)]
+struct IdentityHub {
+ adapters: IdentityManager,
+ devices: IdentityManager,
+ buffers: IdentityManager,
+ command_buffers: IdentityManager,
+ render_bundles: IdentityManager,
+ bind_group_layouts: IdentityManager,
+ pipeline_layouts: IdentityManager,
+ bind_groups: IdentityManager,
+ shader_modules: IdentityManager,
+ compute_pipelines: IdentityManager,
+ render_pipelines: IdentityManager,
+ textures: IdentityManager,
+ texture_views: IdentityManager,
+ samplers: IdentityManager,
+}
+
+impl ImplicitLayout<'_> {
+ fn new(identities: &mut IdentityHub, backend: Backend) -> Self {
+ ImplicitLayout {
+ pipeline: identities.pipeline_layouts.alloc(backend),
+ bind_groups: Cow::Owned(
+ (0..8) // hal::MAX_BIND_GROUPS
+ .map(|_| identities.bind_group_layouts.alloc(backend))
+ .collect(),
+ ),
+ }
+ }
+}
+
+#[derive(Debug, Default)]
+struct Identities {
+ vulkan: IdentityHub,
+ #[cfg(any(target_os = "ios", target_os = "macos"))]
+ metal: IdentityHub,
+ #[cfg(windows)]
+ dx12: IdentityHub,
+}
+
+impl Identities {
+ fn select(&mut self, backend: Backend) -> &mut IdentityHub {
+ match backend {
+ Backend::Vulkan => &mut self.vulkan,
+ #[cfg(any(target_os = "ios", target_os = "macos"))]
+ Backend::Metal => &mut self.metal,
+ #[cfg(windows)]
+ Backend::Dx12 => &mut self.dx12,
+ _ => panic!("Unexpected backend: {:?}", backend),
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct Client {
+ identities: Mutex<Identities>,
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_client_drop_action(client: &mut Client, byte_buf: &ByteBuf) {
+ let mut cursor = std::io::Cursor::new(byte_buf.as_slice());
+ let mut identities = client.identities.lock();
+ while let Ok(action) = bincode::deserialize_from(&mut cursor) {
+ match action {
+ DropAction::Adapter(id) => identities.select(id.backend()).adapters.free(id),
+ DropAction::Device(id) => identities.select(id.backend()).devices.free(id),
+ DropAction::ShaderModule(id) => identities.select(id.backend()).shader_modules.free(id),
+ DropAction::PipelineLayout(id) => {
+ identities.select(id.backend()).pipeline_layouts.free(id)
+ }
+ DropAction::BindGroupLayout(id) => {
+ identities.select(id.backend()).bind_group_layouts.free(id)
+ }
+ DropAction::BindGroup(id) => identities.select(id.backend()).bind_groups.free(id),
+ DropAction::CommandBuffer(id) => {
+ identities.select(id.backend()).command_buffers.free(id)
+ }
+ DropAction::RenderBundle(id) => identities.select(id.backend()).render_bundles.free(id),
+ DropAction::RenderPipeline(id) => {
+ identities.select(id.backend()).render_pipelines.free(id)
+ }
+ DropAction::ComputePipeline(id) => {
+ identities.select(id.backend()).compute_pipelines.free(id)
+ }
+ DropAction::Buffer(id) => identities.select(id.backend()).buffers.free(id),
+ DropAction::Texture(id) => identities.select(id.backend()).textures.free(id),
+ DropAction::TextureView(id) => identities.select(id.backend()).texture_views.free(id),
+ DropAction::Sampler(id) => identities.select(id.backend()).samplers.free(id),
+ }
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_kill_device_id(client: &Client, id: id::DeviceId) {
+ client
+ .identities
+ .lock()
+ .select(id.backend())
+ .devices
+ .free(id)
+}
+
+#[repr(C)]
+#[derive(Debug)]
+pub struct Infrastructure {
+ pub client: *mut Client,
+ pub error: *const u8,
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_new() -> Infrastructure {
+ log::info!("Initializing WGPU client");
+ let client = Box::new(Client {
+ identities: Mutex::new(Identities::default()),
+ });
+ Infrastructure {
+ client: Box::into_raw(client),
+ error: ptr::null(),
+ }
+}
+
+/// # Safety
+///
+/// This function is unsafe because improper use may lead to memory
+/// problems. For example, a double-free may occur if the function is called
+/// twice on the same raw pointer.
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_client_delete(client: *mut Client) {
+ log::info!("Terminating WGPU client");
+ let _client = Box::from_raw(client);
+}
+
+/// # Safety
+///
+/// This function is unsafe as there is no guarantee that the given pointer is
+/// valid for `id_length` elements.
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_client_make_adapter_ids(
+ client: &Client,
+ ids: *mut id::AdapterId,
+ id_length: usize,
+) -> usize {
+ let mut identities = client.identities.lock();
+ assert_ne!(id_length, 0);
+ let mut ids = std::slice::from_raw_parts_mut(ids, id_length).iter_mut();
+
+ *ids.next().unwrap() = identities.vulkan.adapters.alloc(Backend::Vulkan);
+
+ #[cfg(any(target_os = "ios", target_os = "macos"))]
+ {
+ *ids.next().unwrap() = identities.metal.adapters.alloc(Backend::Metal);
+ }
+ #[cfg(windows)]
+ {
+ *ids.next().unwrap() = identities.dx12.adapters.alloc(Backend::Dx12);
+ }
+
+ id_length - ids.len()
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_fill_default_limits(limits: &mut wgt::Limits) {
+ *limits = wgt::Limits::default();
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_adapter_extract_info(
+ byte_buf: &ByteBuf,
+ info: &mut AdapterInformation<nsString>,
+) {
+ let AdapterInformation {
+ backend,
+ device_type,
+ device,
+ driver_info,
+ driver,
+ features,
+ id,
+ limits,
+ name,
+ vendor,
+ } = bincode::deserialize::<AdapterInformation<String>>(unsafe { byte_buf.as_slice() }).unwrap();
+
+ let nss = |s: &str| {
+ let mut ns_string = nsString::new();
+ ns_string.assign_str(s);
+ ns_string
+ };
+ *info = AdapterInformation {
+ backend,
+ device_type,
+ device,
+ driver_info: nss(&driver_info),
+ driver: nss(&driver),
+ features,
+ id,
+ limits,
+ name: nss(&name),
+ vendor,
+ };
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_serialize_device_descriptor(
+ desc: &wgt::DeviceDescriptor<Option<&nsACString>>,
+ bb: &mut ByteBuf,
+) {
+ let label = wgpu_string(desc.label);
+ *bb = make_byte_buf(&desc.map_label(|_| label));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_make_device_id(
+ client: &Client,
+ adapter_id: id::AdapterId,
+) -> id::DeviceId {
+ let backend = adapter_id.backend();
+ client
+ .identities
+ .lock()
+ .select(backend)
+ .devices
+ .alloc(backend)
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_make_buffer_id(
+ client: &Client,
+ device_id: id::DeviceId,
+) -> id::BufferId {
+ let backend = device_id.backend();
+ client
+ .identities
+ .lock()
+ .select(backend)
+ .buffers
+ .alloc(backend)
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_create_texture(
+ client: &Client,
+ device_id: id::DeviceId,
+ desc: &wgt::TextureDescriptor<Option<&nsACString>, crate::FfiSlice<TextureFormat>>,
+ bb: &mut ByteBuf,
+) -> id::TextureId {
+ let label = wgpu_string(desc.label);
+
+ let backend = device_id.backend();
+ let id = client
+ .identities
+ .lock()
+ .select(backend)
+ .textures
+ .alloc(backend);
+
+ let view_formats = unsafe { desc.view_formats.as_slice() }.to_vec();
+
+ let action = DeviceAction::CreateTexture(
+ id,
+ desc.map_label_and_view_formats(|_| label, |_| view_formats),
+ );
+ *bb = make_byte_buf(&action);
+
+ id
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_create_texture_view(
+ client: &Client,
+ device_id: id::DeviceId,
+ desc: &TextureViewDescriptor,
+ bb: &mut ByteBuf,
+) -> id::TextureViewId {
+ let label = wgpu_string(desc.label);
+
+ let backend = device_id.backend();
+ let id = client
+ .identities
+ .lock()
+ .select(backend)
+ .texture_views
+ .alloc(backend);
+
+ let wgpu_desc = wgc::resource::TextureViewDescriptor {
+ label: label,
+ format: desc.format.cloned(),
+ dimension: desc.dimension.cloned(),
+ range: wgt::ImageSubresourceRange {
+ aspect: desc.aspect,
+ base_mip_level: desc.base_mip_level,
+ mip_level_count: desc.mip_level_count.map(|ptr| *ptr),
+ base_array_layer: desc.base_array_layer,
+ array_layer_count: desc.array_layer_count.map(|ptr| *ptr),
+ },
+ };
+
+ let action = TextureAction::CreateView(id, wgpu_desc);
+ *bb = make_byte_buf(&action);
+ id
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_create_sampler(
+ client: &Client,
+ device_id: id::DeviceId,
+ desc: &SamplerDescriptor,
+ bb: &mut ByteBuf,
+) -> id::SamplerId {
+ let label = wgpu_string(desc.label);
+
+ let backend = device_id.backend();
+ let id = client
+ .identities
+ .lock()
+ .select(backend)
+ .samplers
+ .alloc(backend);
+
+ let wgpu_desc = wgc::resource::SamplerDescriptor {
+ label: label,
+ address_modes: desc.address_modes,
+ mag_filter: desc.mag_filter,
+ min_filter: desc.min_filter,
+ mipmap_filter: desc.mipmap_filter,
+ lod_min_clamp: desc.lod_min_clamp,
+ lod_max_clamp: desc.lod_max_clamp,
+ compare: desc.compare.cloned(),
+ anisotropy_clamp: *desc.anisotropy_clamp.unwrap_or(&1),
+ border_color: None,
+ };
+ let action = DeviceAction::CreateSampler(id, wgpu_desc);
+ *bb = make_byte_buf(&action);
+ id
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_make_encoder_id(
+ client: &Client,
+ device_id: id::DeviceId,
+) -> id::CommandEncoderId {
+ let backend = device_id.backend();
+ client
+ .identities
+ .lock()
+ .select(backend)
+ .command_buffers
+ .alloc(backend)
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_create_command_encoder(
+ client: &Client,
+ device_id: id::DeviceId,
+ desc: &wgt::CommandEncoderDescriptor<Option<&nsACString>>,
+ bb: &mut ByteBuf,
+) -> id::CommandEncoderId {
+ let label = wgpu_string(desc.label);
+
+ let backend = device_id.backend();
+ let id = client
+ .identities
+ .lock()
+ .select(backend)
+ .command_buffers
+ .alloc(backend);
+
+ let action = DeviceAction::CreateCommandEncoder(id, desc.map_label(|_| label));
+ *bb = make_byte_buf(&action);
+ id
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_device_create_render_bundle_encoder(
+ device_id: id::DeviceId,
+ desc: &RenderBundleEncoderDescriptor,
+ bb: &mut ByteBuf,
+) -> *mut wgc::command::RenderBundleEncoder {
+ let label = wgpu_string(desc.label);
+
+ let color_formats: Vec<_> = make_slice(desc.color_formats, desc.color_formats_length)
+ .iter()
+ .map(|format| Some(format.clone()))
+ .collect();
+ let descriptor = wgc::command::RenderBundleEncoderDescriptor {
+ label: label,
+ color_formats: Cow::Owned(color_formats),
+ depth_stencil: desc
+ .depth_stencil_format
+ .map(|&format| wgt::RenderBundleDepthStencil {
+ format,
+ depth_read_only: desc.depth_read_only,
+ stencil_read_only: desc.stencil_read_only,
+ }),
+ sample_count: desc.sample_count,
+ multiview: None,
+ };
+ match wgc::command::RenderBundleEncoder::new(&descriptor, device_id, None) {
+ Ok(encoder) => Box::into_raw(Box::new(encoder)),
+ Err(e) => {
+ let message = format!("Error in Device::create_render_bundle_encoder: {}", e);
+ let action = DeviceAction::Error(message);
+ *bb = make_byte_buf(&action);
+ ptr::null_mut()
+ }
+ }
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_render_bundle_encoder_destroy(
+ pass: *mut wgc::command::RenderBundleEncoder,
+) {
+ // The RB encoder is just a boxed Rust struct, it doesn't have any API primitives
+ // associated with it right now, but in the future it will.
+ let _ = Box::from_raw(pass);
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_client_create_render_bundle(
+ client: &Client,
+ encoder: *mut wgc::command::RenderBundleEncoder,
+ device_id: id::DeviceId,
+ desc: &wgt::RenderBundleDescriptor<Option<&nsACString>>,
+ bb: &mut ByteBuf,
+) -> id::RenderBundleId {
+ let label = wgpu_string(desc.label);
+
+ let backend = device_id.backend();
+ let id = client
+ .identities
+ .lock()
+ .select(backend)
+ .render_bundles
+ .alloc(backend);
+
+ let action =
+ DeviceAction::CreateRenderBundle(id, *Box::from_raw(encoder), desc.map_label(|_| label));
+ *bb = make_byte_buf(&action);
+ id
+}
+
+#[repr(C)]
+pub struct ComputePassDescriptor<'a> {
+ pub label: Option<&'a nsACString>,
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_command_encoder_begin_compute_pass(
+ encoder_id: id::CommandEncoderId,
+ desc: &ComputePassDescriptor,
+) -> *mut wgc::command::ComputePass {
+ let label = wgpu_string(desc.label);
+
+ let pass = wgc::command::ComputePass::new(
+ encoder_id,
+ &wgc::command::ComputePassDescriptor { label: label },
+ );
+ Box::into_raw(Box::new(pass))
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_compute_pass_finish(
+ pass: *mut wgc::command::ComputePass,
+ output: &mut ByteBuf,
+) {
+ let command = Box::from_raw(pass).into_command();
+ *output = make_byte_buf(&command);
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_compute_pass_destroy(pass: *mut wgc::command::ComputePass) {
+ let _ = Box::from_raw(pass);
+}
+
+#[repr(C)]
+pub struct RenderPassDescriptor<'a> {
+ pub label: Option<&'a nsACString>,
+ pub color_attachments: *const wgc::command::RenderPassColorAttachment,
+ pub color_attachments_length: usize,
+ pub depth_stencil_attachment: *const wgc::command::RenderPassDepthStencilAttachment,
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_command_encoder_begin_render_pass(
+ encoder_id: id::CommandEncoderId,
+ desc: &RenderPassDescriptor,
+) -> *mut wgc::command::RenderPass {
+ let label = wgpu_string(desc.label);
+
+ let color_attachments: Vec<_> =
+ make_slice(desc.color_attachments, desc.color_attachments_length)
+ .iter()
+ .map(|format| Some(format.clone()))
+ .collect();
+ let pass = wgc::command::RenderPass::new(
+ encoder_id,
+ &wgc::command::RenderPassDescriptor {
+ label: label,
+ color_attachments: Cow::Owned(color_attachments),
+ depth_stencil_attachment: desc.depth_stencil_attachment.as_ref(),
+ },
+ );
+ Box::into_raw(Box::new(pass))
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_render_pass_finish(
+ pass: *mut wgc::command::RenderPass,
+ output: &mut ByteBuf,
+) {
+ let command = Box::from_raw(pass).into_command();
+ *output = make_byte_buf(&command);
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_render_pass_destroy(pass: *mut wgc::command::RenderPass) {
+ let _ = Box::from_raw(pass);
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_client_create_bind_group_layout(
+ client: &Client,
+ device_id: id::DeviceId,
+ desc: &BindGroupLayoutDescriptor,
+ bb: &mut ByteBuf,
+) -> id::BindGroupLayoutId {
+ let label = wgpu_string(desc.label);
+
+ let backend = device_id.backend();
+ let id = client
+ .identities
+ .lock()
+ .select(backend)
+ .bind_group_layouts
+ .alloc(backend);
+
+ let mut entries = Vec::with_capacity(desc.entries_length);
+ for entry in make_slice(desc.entries, desc.entries_length) {
+ entries.push(wgt::BindGroupLayoutEntry {
+ binding: entry.binding,
+ visibility: entry.visibility,
+ count: None,
+ ty: match entry.ty {
+ RawBindingType::UniformBuffer => wgt::BindingType::Buffer {
+ ty: wgt::BufferBindingType::Uniform,
+ has_dynamic_offset: entry.has_dynamic_offset,
+ min_binding_size: entry.min_binding_size,
+ },
+ RawBindingType::StorageBuffer => wgt::BindingType::Buffer {
+ ty: wgt::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: entry.has_dynamic_offset,
+ min_binding_size: entry.min_binding_size,
+ },
+ RawBindingType::ReadonlyStorageBuffer => wgt::BindingType::Buffer {
+ ty: wgt::BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: entry.has_dynamic_offset,
+ min_binding_size: entry.min_binding_size,
+ },
+ RawBindingType::Sampler => wgt::BindingType::Sampler(if entry.sampler_compare {
+ wgt::SamplerBindingType::Comparison
+ } else if entry.sampler_filter {
+ wgt::SamplerBindingType::Filtering
+ } else {
+ wgt::SamplerBindingType::NonFiltering
+ }),
+ RawBindingType::SampledTexture => wgt::BindingType::Texture {
+ //TODO: the spec has a bug here
+ view_dimension: *entry
+ .view_dimension
+ .unwrap_or(&wgt::TextureViewDimension::D2),
+ sample_type: match entry.texture_sample_type {
+ None | Some(RawTextureSampleType::Float) => {
+ wgt::TextureSampleType::Float { filterable: true }
+ }
+ Some(RawTextureSampleType::UnfilterableFloat) => {
+ wgt::TextureSampleType::Float { filterable: false }
+ }
+ Some(RawTextureSampleType::Uint) => wgt::TextureSampleType::Uint,
+ Some(RawTextureSampleType::Sint) => wgt::TextureSampleType::Sint,
+ Some(RawTextureSampleType::Depth) => wgt::TextureSampleType::Depth,
+ },
+ multisampled: entry.multisampled,
+ },
+ RawBindingType::ReadonlyStorageTexture => wgt::BindingType::StorageTexture {
+ access: wgt::StorageTextureAccess::ReadOnly,
+ view_dimension: *entry.view_dimension.unwrap(),
+ format: *entry.storage_texture_format.unwrap(),
+ },
+ RawBindingType::WriteonlyStorageTexture => wgt::BindingType::StorageTexture {
+ access: wgt::StorageTextureAccess::WriteOnly,
+ view_dimension: *entry.view_dimension.unwrap(),
+ format: *entry.storage_texture_format.unwrap(),
+ },
+ },
+ });
+ }
+ let wgpu_desc = wgc::binding_model::BindGroupLayoutDescriptor {
+ label: label,
+ entries: Cow::Owned(entries),
+ };
+
+ let action = DeviceAction::CreateBindGroupLayout(id, wgpu_desc);
+ *bb = make_byte_buf(&action);
+ id
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_client_create_pipeline_layout(
+ client: &Client,
+ device_id: id::DeviceId,
+ desc: &PipelineLayoutDescriptor,
+ bb: &mut ByteBuf,
+) -> id::PipelineLayoutId {
+ let label = wgpu_string(desc.label);
+
+ let backend = device_id.backend();
+ let id = client
+ .identities
+ .lock()
+ .select(backend)
+ .pipeline_layouts
+ .alloc(backend);
+
+ let wgpu_desc = wgc::binding_model::PipelineLayoutDescriptor {
+ label: label,
+ bind_group_layouts: Cow::Borrowed(make_slice(
+ desc.bind_group_layouts,
+ desc.bind_group_layouts_length,
+ )),
+ push_constant_ranges: Cow::Borrowed(&[]),
+ };
+
+ let action = DeviceAction::CreatePipelineLayout(id, wgpu_desc);
+ *bb = make_byte_buf(&action);
+ id
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_client_create_bind_group(
+ client: &Client,
+ device_id: id::DeviceId,
+ desc: &BindGroupDescriptor,
+ bb: &mut ByteBuf,
+) -> id::BindGroupId {
+ let label = wgpu_string(desc.label);
+
+ let backend = device_id.backend();
+ let id = client
+ .identities
+ .lock()
+ .select(backend)
+ .bind_groups
+ .alloc(backend);
+
+ let mut entries = Vec::with_capacity(desc.entries_length);
+ for entry in make_slice(desc.entries, desc.entries_length) {
+ entries.push(wgc::binding_model::BindGroupEntry {
+ binding: entry.binding,
+ resource: if let Some(id) = entry.buffer {
+ wgc::binding_model::BindingResource::Buffer(wgc::binding_model::BufferBinding {
+ buffer_id: id,
+ offset: entry.offset,
+ size: entry.size,
+ })
+ } else if let Some(id) = entry.sampler {
+ wgc::binding_model::BindingResource::Sampler(id)
+ } else if let Some(id) = entry.texture_view {
+ wgc::binding_model::BindingResource::TextureView(id)
+ } else {
+ panic!("Unexpected binding entry {:?}", entry);
+ },
+ });
+ }
+ let wgpu_desc = wgc::binding_model::BindGroupDescriptor {
+ label: label,
+ layout: desc.layout,
+ entries: Cow::Owned(entries),
+ };
+
+ let action = DeviceAction::CreateBindGroup(id, wgpu_desc);
+ *bb = make_byte_buf(&action);
+ id
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_client_make_shader_module_id(
+ client: &Client,
+ device_id: id::DeviceId,
+) -> id::ShaderModuleId {
+ let backend = device_id.backend();
+ client
+ .identities
+ .lock()
+ .select(backend)
+ .shader_modules
+ .alloc(backend)
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_client_create_compute_pipeline(
+ client: &Client,
+ device_id: id::DeviceId,
+ desc: &ComputePipelineDescriptor,
+ bb: &mut ByteBuf,
+ implicit_pipeline_layout_id: *mut Option<id::PipelineLayoutId>,
+ implicit_bind_group_layout_ids: *mut Option<id::BindGroupLayoutId>,
+) -> id::ComputePipelineId {
+ let backend = device_id.backend();
+ let mut identities = client.identities.lock();
+ let id = identities.select(backend).compute_pipelines.alloc(backend);
+
+ let wgpu_desc = wgc::pipeline::ComputePipelineDescriptor {
+ label: cow_label(&desc.label),
+ layout: desc.layout,
+ stage: desc.stage.to_wgpu(),
+ };
+
+ let implicit = match desc.layout {
+ Some(_) => None,
+ None => {
+ let implicit = ImplicitLayout::new(identities.select(backend), backend);
+ ptr::write(implicit_pipeline_layout_id, Some(implicit.pipeline));
+ for (i, bgl_id) in implicit.bind_groups.iter().enumerate() {
+ *implicit_bind_group_layout_ids.add(i) = Some(*bgl_id);
+ }
+ Some(implicit)
+ }
+ };
+
+ let action = DeviceAction::CreateComputePipeline(id, wgpu_desc, implicit);
+ *bb = make_byte_buf(&action);
+ id
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_client_create_render_pipeline(
+ client: &Client,
+ device_id: id::DeviceId,
+ desc: &RenderPipelineDescriptor,
+ bb: &mut ByteBuf,
+ implicit_pipeline_layout_id: *mut Option<id::PipelineLayoutId>,
+ implicit_bind_group_layout_ids: *mut Option<id::BindGroupLayoutId>,
+) -> id::RenderPipelineId {
+ let label = wgpu_string(desc.label);
+
+ let backend = device_id.backend();
+ let mut identities = client.identities.lock();
+ let id = identities.select(backend).render_pipelines.alloc(backend);
+
+ let wgpu_desc = wgc::pipeline::RenderPipelineDescriptor {
+ label: label,
+ layout: desc.layout,
+ vertex: desc.vertex.to_wgpu(),
+ fragment: desc.fragment.map(FragmentState::to_wgpu),
+ primitive: desc.primitive.to_wgpu(),
+ depth_stencil: desc.depth_stencil.cloned(),
+ multisample: desc.multisample.clone(),
+ multiview: None,
+ };
+
+ let implicit = match desc.layout {
+ Some(_) => None,
+ None => {
+ let implicit = ImplicitLayout::new(identities.select(backend), backend);
+ ptr::write(implicit_pipeline_layout_id, Some(implicit.pipeline));
+ for (i, bgl_id) in implicit.bind_groups.iter().enumerate() {
+ *implicit_bind_group_layout_ids.add(i) = Some(*bgl_id);
+ }
+ Some(implicit)
+ }
+ };
+
+ let action = DeviceAction::CreateRenderPipeline(id, wgpu_desc, implicit);
+ *bb = make_byte_buf(&action);
+ id
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_command_encoder_copy_buffer_to_buffer(
+ src: id::BufferId,
+ src_offset: wgt::BufferAddress,
+ dst: id::BufferId,
+ dst_offset: wgt::BufferAddress,
+ size: wgt::BufferAddress,
+ bb: &mut ByteBuf,
+) {
+ let action = CommandEncoderAction::CopyBufferToBuffer {
+ src,
+ src_offset,
+ dst,
+ dst_offset,
+ size,
+ };
+ *bb = make_byte_buf(&action);
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_command_encoder_copy_texture_to_buffer(
+ src: wgc::command::ImageCopyTexture,
+ dst_buffer: wgc::id::BufferId,
+ dst_layout: &ImageDataLayout,
+ size: wgt::Extent3d,
+ bb: &mut ByteBuf,
+) {
+ let action = CommandEncoderAction::CopyTextureToBuffer {
+ src,
+ dst: wgc::command::ImageCopyBuffer {
+ buffer: dst_buffer,
+ layout: dst_layout.into_wgt(),
+ },
+ size,
+ };
+ *bb = make_byte_buf(&action);
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_command_encoder_copy_buffer_to_texture(
+ src_buffer: wgc::id::BufferId,
+ src_layout: &ImageDataLayout,
+ dst: wgc::command::ImageCopyTexture,
+ size: wgt::Extent3d,
+ bb: &mut ByteBuf,
+) {
+ let action = CommandEncoderAction::CopyBufferToTexture {
+ src: wgc::command::ImageCopyBuffer {
+ buffer: src_buffer,
+ layout: src_layout.into_wgt(),
+ },
+ dst,
+ size,
+ };
+ *bb = make_byte_buf(&action);
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_command_encoder_copy_texture_to_texture(
+ src: wgc::command::ImageCopyTexture,
+ dst: wgc::command::ImageCopyTexture,
+ size: wgt::Extent3d,
+ bb: &mut ByteBuf,
+) {
+ let action = CommandEncoderAction::CopyTextureToTexture { src, dst, size };
+ *bb = make_byte_buf(&action);
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_command_encoder_push_debug_group(marker: &nsACString, bb: &mut ByteBuf) {
+ let string = marker.to_string();
+ let action = CommandEncoderAction::PushDebugGroup(string);
+ *bb = make_byte_buf(&action);
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_command_encoder_pop_debug_group(bb: &mut ByteBuf) {
+ let action = CommandEncoderAction::PopDebugGroup;
+ *bb = make_byte_buf(&action);
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_command_encoder_insert_debug_marker(
+ marker: &nsACString,
+ bb: &mut ByteBuf,
+) {
+ let string = marker.to_string();
+ let action = CommandEncoderAction::InsertDebugMarker(string);
+ *bb = make_byte_buf(&action);
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_queue_write_buffer(
+ dst: id::BufferId,
+ offset: wgt::BufferAddress,
+ bb: &mut ByteBuf,
+) {
+ let action = QueueWriteAction::Buffer { dst, offset };
+ *bb = make_byte_buf(&action);
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_queue_write_texture(
+ dst: wgt::ImageCopyTexture<id::TextureId>,
+ layout: ImageDataLayout,
+ size: wgt::Extent3d,
+ bb: &mut ByteBuf,
+) {
+ let layout = layout.into_wgt();
+ let action = QueueWriteAction::Texture { dst, layout, size };
+ *bb = make_byte_buf(&action);
+}
diff --git a/gfx/wgpu_bindings/src/identity.rs b/gfx/wgpu_bindings/src/identity.rs
new file mode 100644
index 0000000000..7d608b275b
--- /dev/null
+++ b/gfx/wgpu_bindings/src/identity.rs
@@ -0,0 +1,225 @@
+/* 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 http://mozilla.org/MPL/2.0/. */
+
+use wgc::id;
+
+pub type FactoryParam = *mut std::ffi::c_void;
+
+#[derive(Debug)]
+pub struct IdentityRecycler<I> {
+ fun: extern "C" fn(I, FactoryParam),
+ param: FactoryParam,
+ kind: &'static str,
+}
+
+impl<I: id::TypedId + Clone + std::fmt::Debug> wgc::hub::IdentityHandler<I>
+ for IdentityRecycler<I>
+{
+ type Input = I;
+ fn process(&self, id: I, _backend: wgt::Backend) -> I {
+ log::debug!("process {} {:?}", self.kind, id);
+ //debug_assert_eq!(id.unzip().2, backend);
+ id
+ }
+ fn free(&self, id: I) {
+ log::debug!("free {} {:?}", self.kind, id);
+ (self.fun)(id, self.param);
+ }
+}
+
+//TODO: remove this in favor of `DropAction` that could be sent over IPC.
+#[repr(C)]
+pub struct IdentityRecyclerFactory {
+ param: FactoryParam,
+ free_adapter: extern "C" fn(id::AdapterId, FactoryParam),
+ free_device: extern "C" fn(id::DeviceId, FactoryParam),
+ free_pipeline_layout: extern "C" fn(id::PipelineLayoutId, FactoryParam),
+ free_shader_module: extern "C" fn(id::ShaderModuleId, FactoryParam),
+ free_bind_group_layout: extern "C" fn(id::BindGroupLayoutId, FactoryParam),
+ free_bind_group: extern "C" fn(id::BindGroupId, FactoryParam),
+ free_command_buffer: extern "C" fn(id::CommandBufferId, FactoryParam),
+ free_render_bundle: extern "C" fn(id::RenderBundleId, FactoryParam),
+ free_render_pipeline: extern "C" fn(id::RenderPipelineId, FactoryParam),
+ free_compute_pipeline: extern "C" fn(id::ComputePipelineId, FactoryParam),
+ free_query_set: extern "C" fn(id::QuerySetId, FactoryParam),
+ free_buffer: extern "C" fn(id::BufferId, FactoryParam),
+ free_staging_buffer: extern "C" fn(id::StagingBufferId, FactoryParam),
+ free_texture: extern "C" fn(id::TextureId, FactoryParam),
+ free_texture_view: extern "C" fn(id::TextureViewId, FactoryParam),
+ free_sampler: extern "C" fn(id::SamplerId, FactoryParam),
+ free_surface: extern "C" fn(id::SurfaceId, FactoryParam),
+}
+
+impl wgc::hub::IdentityHandlerFactory<id::AdapterId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::AdapterId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_adapter,
+ param: self.param,
+ kind: "adapter",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::DeviceId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::DeviceId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_device,
+ param: self.param,
+ kind: "device",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::PipelineLayoutId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::PipelineLayoutId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_pipeline_layout,
+ param: self.param,
+ kind: "pipeline_layout",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::ShaderModuleId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::ShaderModuleId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_shader_module,
+ param: self.param,
+ kind: "shader_module",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::BindGroupLayoutId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::BindGroupLayoutId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_bind_group_layout,
+ param: self.param,
+ kind: "bind_group_layout",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::BindGroupId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::BindGroupId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_bind_group,
+ param: self.param,
+ kind: "bind_group",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::CommandBufferId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::CommandBufferId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_command_buffer,
+ param: self.param,
+ kind: "command_buffer",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::RenderBundleId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::RenderBundleId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_render_bundle,
+ param: self.param,
+ kind: "render_bundle",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::RenderPipelineId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::RenderPipelineId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_render_pipeline,
+ param: self.param,
+ kind: "render_pipeline",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::ComputePipelineId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::ComputePipelineId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_compute_pipeline,
+ param: self.param,
+ kind: "compute_pipeline",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::QuerySetId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::QuerySetId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_query_set,
+ param: self.param,
+ kind: "query_set",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::BufferId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::BufferId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_buffer,
+ param: self.param,
+ kind: "buffer",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::StagingBufferId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::StagingBufferId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_staging_buffer,
+ param: self.param,
+ kind: "staging buffer",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::TextureId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::TextureId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_texture,
+ param: self.param,
+ kind: "texture",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::TextureViewId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::TextureViewId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_texture_view,
+ param: self.param,
+ kind: "texture_view",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::SamplerId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::SamplerId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_sampler,
+ param: self.param,
+ kind: "sampler",
+ }
+ }
+}
+impl wgc::hub::IdentityHandlerFactory<id::SurfaceId> for IdentityRecyclerFactory {
+ type Filter = IdentityRecycler<id::SurfaceId>;
+ fn spawn(&self) -> Self::Filter {
+ IdentityRecycler {
+ fun: self.free_surface,
+ param: self.param,
+ kind: "surface",
+ }
+ }
+}
+
+impl wgc::hub::GlobalIdentityHandlerFactory for IdentityRecyclerFactory {}
diff --git a/gfx/wgpu_bindings/src/lib.rs b/gfx/wgpu_bindings/src/lib.rs
new file mode 100644
index 0000000000..de34649c95
--- /dev/null
+++ b/gfx/wgpu_bindings/src/lib.rs
@@ -0,0 +1,218 @@
+/* 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 http://mozilla.org/MPL/2.0/. */
+
+use wgc::id;
+
+pub use wgc::command::{compute_ffi::*, render_ffi::*};
+
+pub mod client;
+pub mod identity;
+pub mod server;
+
+pub use wgc::device::trace::Command as CommandEncoderAction;
+
+use std::marker::PhantomData;
+use std::{borrow::Cow, mem, slice};
+
+use nsstring::nsACString;
+
+type RawString = *const std::os::raw::c_char;
+
+//TODO: figure out why 'a and 'b have to be different here
+//TODO: remove this
+fn cow_label<'a, 'b>(raw: &'a RawString) -> Option<Cow<'b, str>> {
+ if raw.is_null() {
+ None
+ } else {
+ let cstr = unsafe { std::ffi::CStr::from_ptr(*raw) };
+ cstr.to_str().ok().map(Cow::Borrowed)
+ }
+}
+
+// Hides the repeated boilerplate of turning a `Option<&nsACString>` into a `Option<Cow<str>`.
+pub fn wgpu_string(gecko_string: Option<&nsACString>) -> Option<Cow<str>> {
+ gecko_string.map(|s| s.to_utf8())
+}
+
+/// An equivalent of `&[T]` for ffi structures and function parameters.
+#[repr(C)]
+pub struct FfiSlice<'a, T> {
+ // `data` may be null.
+ pub data: *const T,
+ pub length: usize,
+ pub _marker: PhantomData<&'a T>,
+}
+
+impl<'a, T> FfiSlice<'a, T> {
+ pub unsafe fn as_slice(&self) -> &'a [T] {
+ if self.data.is_null() {
+ // It is invalid to construct a rust slice with a null pointer.
+ return &[];
+ }
+
+ std::slice::from_raw_parts(self.data, self.length)
+ }
+}
+
+impl<'a, T> Copy for FfiSlice<'a, T> {}
+impl<'a, T> Clone for FfiSlice<'a, T> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+#[repr(C)]
+pub struct ByteBuf {
+ data: *const u8,
+ len: usize,
+ capacity: usize,
+}
+
+impl ByteBuf {
+ fn from_vec(vec: Vec<u8>) -> Self {
+ if vec.is_empty() {
+ ByteBuf {
+ data: std::ptr::null(),
+ len: 0,
+ capacity: 0,
+ }
+ } else {
+ let bb = ByteBuf {
+ data: vec.as_ptr(),
+ len: vec.len(),
+ capacity: vec.capacity(),
+ };
+ mem::forget(vec);
+ bb
+ }
+ }
+
+ unsafe fn as_slice(&self) -> &[u8] {
+ slice::from_raw_parts(self.data, self.len)
+ }
+}
+
+#[repr(C)]
+#[derive(serde::Serialize, serde::Deserialize)]
+pub struct AdapterInformation<S> {
+ id: id::AdapterId,
+ limits: wgt::Limits,
+ features: wgt::Features,
+ name: S,
+ vendor: u32,
+ device: u32,
+ device_type: wgt::DeviceType,
+ driver: S,
+ driver_info: S,
+ backend: wgt::Backend,
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+struct ImplicitLayout<'a> {
+ pipeline: id::PipelineLayoutId,
+ bind_groups: Cow<'a, [id::BindGroupLayoutId]>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+enum DeviceAction<'a> {
+ CreateTexture(id::TextureId, wgc::resource::TextureDescriptor<'a>),
+ CreateSampler(id::SamplerId, wgc::resource::SamplerDescriptor<'a>),
+ CreateBindGroupLayout(
+ id::BindGroupLayoutId,
+ wgc::binding_model::BindGroupLayoutDescriptor<'a>,
+ ),
+ CreatePipelineLayout(
+ id::PipelineLayoutId,
+ wgc::binding_model::PipelineLayoutDescriptor<'a>,
+ ),
+ CreateBindGroup(id::BindGroupId, wgc::binding_model::BindGroupDescriptor<'a>),
+ CreateShaderModule(
+ id::ShaderModuleId,
+ wgc::pipeline::ShaderModuleDescriptor<'a>,
+ Cow<'a, str>,
+ ),
+ CreateComputePipeline(
+ id::ComputePipelineId,
+ wgc::pipeline::ComputePipelineDescriptor<'a>,
+ Option<ImplicitLayout<'a>>,
+ ),
+ CreateRenderPipeline(
+ id::RenderPipelineId,
+ wgc::pipeline::RenderPipelineDescriptor<'a>,
+ Option<ImplicitLayout<'a>>,
+ ),
+ CreateRenderBundle(
+ id::RenderBundleId,
+ wgc::command::RenderBundleEncoder,
+ wgc::command::RenderBundleDescriptor<'a>,
+ ),
+ CreateCommandEncoder(
+ id::CommandEncoderId,
+ wgt::CommandEncoderDescriptor<wgc::Label<'a>>,
+ ),
+ Error(String),
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+enum QueueWriteAction {
+ Buffer {
+ dst: id::BufferId,
+ offset: wgt::BufferAddress,
+ },
+ Texture {
+ dst: wgt::ImageCopyTexture<id::TextureId>,
+ layout: wgt::ImageDataLayout,
+ size: wgt::Extent3d,
+ },
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+enum TextureAction<'a> {
+ CreateView(id::TextureViewId, wgc::resource::TextureViewDescriptor<'a>),
+}
+
+#[repr(C)]
+#[derive(serde::Serialize, serde::Deserialize)]
+enum DropAction {
+ Adapter(id::AdapterId),
+ Device(id::DeviceId),
+ ShaderModule(id::ShaderModuleId),
+ PipelineLayout(id::PipelineLayoutId),
+ BindGroupLayout(id::BindGroupLayoutId),
+ BindGroup(id::BindGroupId),
+ CommandBuffer(id::CommandBufferId),
+ RenderBundle(id::RenderBundleId),
+ RenderPipeline(id::RenderPipelineId),
+ ComputePipeline(id::ComputePipelineId),
+ Buffer(id::BufferId),
+ Texture(id::TextureId),
+ TextureView(id::TextureViewId),
+ Sampler(id::SamplerId),
+}
+
+impl DropAction {
+ // helper function to construct byte bufs
+ fn to_byte_buf(&self) -> ByteBuf {
+ let mut data = Vec::new();
+ bincode::serialize_into(&mut data, self).unwrap();
+ ByteBuf::from_vec(data)
+ }
+}
+
+#[repr(C)]
+pub struct ImageDataLayout<'a> {
+ pub offset: wgt::BufferAddress,
+ pub bytes_per_row: Option<&'a u32>,
+ pub rows_per_image: Option<&'a u32>,
+}
+
+impl<'a> ImageDataLayout<'a> {
+ fn into_wgt(&self) -> wgt::ImageDataLayout {
+ wgt::ImageDataLayout {
+ offset: self.offset,
+ bytes_per_row: self.bytes_per_row.map(|bpr| *bpr),
+ rows_per_image: self.rows_per_image.map(|rpi| *rpi),
+ }
+ }
+}
diff --git a/gfx/wgpu_bindings/src/server.rs b/gfx/wgpu_bindings/src/server.rs
new file mode 100644
index 0000000000..6fb170761b
--- /dev/null
+++ b/gfx/wgpu_bindings/src/server.rs
@@ -0,0 +1,993 @@
+/* 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 http://mozilla.org/MPL/2.0/. */
+
+use crate::{
+ identity::IdentityRecyclerFactory, wgpu_string, AdapterInformation, ByteBuf,
+ CommandEncoderAction, DeviceAction, DropAction, QueueWriteAction, TextureAction,
+};
+
+use nsstring::{nsACString, nsCString, nsString};
+
+use wgc::pipeline::CreateShaderModuleError;
+use wgc::{gfx_select, id};
+
+use std::borrow::Cow;
+use std::sync::atomic::{AtomicU32, Ordering};
+use std::{error::Error, os::raw::c_char, ptr, slice};
+
+/// We limit the size of buffer allocations for stability reason.
+/// We can reconsider this limit in the future. Note that some drivers (mesa for example),
+/// have issues when the size of a buffer, mapping or copy command does not fit into a
+/// signed 32 bits integer, so beyond a certain size, large allocations will need some form
+/// of driver allow/blocklist.
+const MAX_BUFFER_SIZE: wgt::BufferAddress = 1 << 30;
+// Mesa has issues with height/depth that don't fit in a 16 bits signed integers.
+const MAX_TEXTURE_EXTENT: u32 = std::i16::MAX as u32;
+
+/// A fixed-capacity, null-terminated error buffer owned by C++.
+///
+/// This type points to space owned by a C++ `mozilla::webgpu::ErrorBuffer`
+/// object, owned by our callers in `WebGPUParent.cpp`. If we catch a
+/// `Result::Err` here, we convert the error to a string, copy as much of that
+/// string as fits into this buffer, and null-terminate it. The caller
+/// determines whether a error occurred by simply checking if there's any text
+/// before the first null byte.
+///
+/// C++ callers of Rust functions that expect one of these structs can create a
+/// `mozilla::webgpu::ErrorBuffer` object, and call its `ToFFI` method to
+/// construct a value of this type, available to C++ as
+/// `mozilla::webgpu::ffi::WGPUErrorBuffer`.
+#[repr(C)]
+pub struct ErrorBuffer {
+ string: *mut c_char,
+ capacity: usize,
+}
+
+impl ErrorBuffer {
+ /// Fill this buffer with the textual representation of `error`.
+ ///
+ /// If the error message is too long, truncate it as needed. In either case,
+ /// the error message is always terminated by a zero byte.
+ ///
+ /// Note that there is no explicit indication of the message's length, only
+ /// the terminating zero byte. If the textual form of `error` itself
+ /// includes a zero byte (as Rust strings can), then the C++ code receiving
+ /// this error message has no way to distinguish that from the terminating
+ /// zero byte, and will see the message as shorter than it is.
+ fn init(&mut self, error: impl Error) {
+ use std::fmt::Write;
+
+ let mut string = format!("{}", error);
+ let mut e = error.source();
+ while let Some(source) = e {
+ write!(string, ", caused by: {}", source).unwrap();
+ e = source.source();
+ }
+
+ self.init_str(&string);
+ }
+
+ fn init_str(&mut self, message: &str) {
+ assert_ne!(self.capacity, 0);
+ let length = if message.len() >= self.capacity {
+ log::warn!(
+ "Error length {} reached capacity {}",
+ message.len(),
+ self.capacity
+ );
+ self.capacity - 1
+ } else {
+ message.len()
+ };
+ unsafe {
+ ptr::copy_nonoverlapping(message.as_ptr(), self.string as *mut u8, length);
+ *self.string.add(length) = 0;
+ }
+ }
+}
+
+// hide wgc's global in private
+pub struct Global(wgc::hub::Global<IdentityRecyclerFactory>);
+
+impl std::ops::Deref for Global {
+ type Target = wgc::hub::Global<IdentityRecyclerFactory>;
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_new(factory: IdentityRecyclerFactory) -> *mut Global {
+ log::info!("Initializing WGPU server");
+ let backends_pref = static_prefs::pref!("dom.webgpu.wgpu-backend").to_string();
+ let backends = if backends_pref.is_empty() {
+ wgt::Backends::PRIMARY
+ } else {
+ log::info!(
+ "Selecting backends based on dom.webgpu.wgpu-backend pref: {:?}",
+ backends_pref
+ );
+ wgc::instance::parse_backends_from_comma_list(&backends_pref)
+ };
+ let global = Global(wgc::hub::Global::new(
+ "wgpu",
+ factory,
+ wgt::InstanceDescriptor {
+ backends,
+ dx12_shader_compiler: wgt::Dx12Compiler::Fxc,
+ },
+ ));
+ Box::into_raw(Box::new(global))
+}
+
+/// # Safety
+///
+/// This function is unsafe because improper use may lead to memory
+/// problems. For example, a double-free may occur if the function is called
+/// twice on the same raw pointer.
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_server_delete(global: *mut Global) {
+ log::info!("Terminating WGPU server");
+ let _ = Box::from_raw(global);
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_poll_all_devices(global: &Global, force_wait: bool) {
+ global.poll_all_devices(force_wait).unwrap();
+}
+
+/// Request an adapter according to the specified options.
+/// Provide the list of IDs to pick from.
+///
+/// Returns the index in this list, or -1 if unable to pick.
+///
+/// # Safety
+///
+/// This function is unsafe as there is no guarantee that the given pointer is
+/// valid for `id_length` elements.
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_server_instance_request_adapter(
+ global: &Global,
+ desc: &wgc::instance::RequestAdapterOptions,
+ ids: *const id::AdapterId,
+ id_length: usize,
+ mut error_buf: ErrorBuffer,
+) -> i8 {
+ let ids = slice::from_raw_parts(ids, id_length);
+ match global.request_adapter(
+ desc,
+ wgc::instance::AdapterInputs::IdSet(ids, |i| i.backend()),
+ ) {
+ Ok(id) => ids.iter().position(|&i| i == id).unwrap() as i8,
+ Err(e) => {
+ error_buf.init(e);
+ -1
+ }
+ }
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_server_adapter_pack_info(
+ global: &Global,
+ self_id: Option<id::AdapterId>,
+ byte_buf: &mut ByteBuf,
+) {
+ let mut data = Vec::new();
+ match self_id {
+ Some(id) => {
+ let wgt::AdapterInfo {
+ name,
+ vendor,
+ device,
+ device_type,
+ driver,
+ driver_info,
+ backend,
+ } = gfx_select!(id => global.adapter_get_info(id)).unwrap();
+
+ let info = AdapterInformation {
+ id,
+ limits: gfx_select!(id => global.adapter_limits(id)).unwrap(),
+ features: gfx_select!(id => global.adapter_features(id)).unwrap(),
+ name,
+ vendor,
+ device,
+ device_type,
+ driver,
+ driver_info,
+ backend,
+ };
+ bincode::serialize_into(&mut data, &info).unwrap();
+ }
+ None => {
+ bincode::serialize_into(&mut data, &0u64).unwrap();
+ }
+ }
+ *byte_buf = ByteBuf::from_vec(data);
+}
+
+static TRACE_IDX: AtomicU32 = AtomicU32::new(0);
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_server_adapter_request_device(
+ global: &Global,
+ self_id: id::AdapterId,
+ byte_buf: &ByteBuf,
+ new_id: id::DeviceId,
+ mut error_buf: ErrorBuffer,
+) {
+ let desc: wgc::device::DeviceDescriptor = bincode::deserialize(byte_buf.as_slice()).unwrap();
+ let trace_string = std::env::var("WGPU_TRACE").ok().map(|s| {
+ let idx = TRACE_IDX.fetch_add(1, Ordering::Relaxed);
+ let path = format!("{}/{}/", s, idx);
+
+ if std::fs::create_dir_all(&path).is_err() {
+ log::warn!("Failed to create directory {:?} for wgpu recording.", path);
+ }
+
+ path
+ });
+ let trace_path = trace_string
+ .as_ref()
+ .map(|string| std::path::Path::new(string.as_str()));
+ let (_, error) =
+ gfx_select!(self_id => global.adapter_request_device(self_id, &desc, trace_path, new_id));
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_adapter_drop(global: &Global, adapter_id: id::AdapterId) {
+ gfx_select!(adapter_id => global.adapter_drop(adapter_id))
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_device_drop(global: &Global, self_id: id::DeviceId) {
+ gfx_select!(self_id => global.device_drop(self_id))
+}
+
+impl ShaderModuleCompilationMessage {
+ fn set_error(&mut self, error: &CreateShaderModuleError, source: &str) {
+ // The WebGPU spec says that if the message doesn't point to a particular position in
+ // the source, the line number, position, offset and lengths should be zero.
+ self.line_number = 0;
+ self.line_pos = 0;
+ self.utf16_offset = 0;
+ self.utf16_length = 0;
+
+ if let Some(location) = error.location(source) {
+ self.line_number = location.line_number as u64;
+ self.line_pos = location.line_position as u64;
+
+ let start = location.offset as usize;
+ let end = start + location.length as usize;
+ self.utf16_offset = source[0..start].chars().map(|c| c.len_utf16() as u64).sum();
+ self.utf16_length = source[start..end]
+ .chars()
+ .map(|c| c.len_utf16() as u64)
+ .sum();
+ }
+
+ let error_string = error.to_string();
+
+ if !error_string.is_empty() {
+ self.message = nsString::from(&error_string[..]);
+ }
+ }
+}
+
+/// A compilation message representation for the ffi boundary.
+/// the message is immediately copied into an equivalent C++
+/// structure that owns its strings.
+#[repr(C)]
+#[derive(Clone)]
+pub struct ShaderModuleCompilationMessage {
+ pub line_number: u64,
+ pub line_pos: u64,
+ pub utf16_offset: u64,
+ pub utf16_length: u64,
+ pub message: nsString,
+}
+
+/// Creates a shader module and returns an object describing the errors if any.
+///
+/// If there was no error, the returned pointer is nil.
+#[no_mangle]
+pub extern "C" fn wgpu_server_device_create_shader_module(
+ global: &Global,
+ self_id: id::DeviceId,
+ module_id: id::ShaderModuleId,
+ label: Option<&nsACString>,
+ code: &nsCString,
+ out_message: &mut ShaderModuleCompilationMessage,
+) -> bool {
+ let utf8_label = label.map(|utf16| utf16.to_string());
+ let label = utf8_label.as_ref().map(|s| Cow::from(&s[..]));
+
+ let source_str = code.to_utf8();
+
+ let source = wgc::pipeline::ShaderModuleSource::Wgsl(Cow::from(&source_str[..]));
+
+ let desc = wgc::pipeline::ShaderModuleDescriptor {
+ label,
+ shader_bound_checks: wgt::ShaderBoundChecks::new(),
+ };
+
+ let (_, error) = gfx_select!(
+ self_id => global.device_create_shader_module(
+ self_id, &desc, source, module_id
+ )
+ );
+
+ if let Some(err) = error {
+ out_message.set_error(&err, &source_str[..]);
+ return false;
+ }
+
+ // Avoid allocating the structure that holds errors in the common case (no errors).
+ return true;
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_device_create_buffer(
+ global: &Global,
+ self_id: id::DeviceId,
+ buffer_id: id::BufferId,
+ label: Option<&nsACString>,
+ size: wgt::BufferAddress,
+ usage: u32,
+ mapped_at_creation: bool,
+ mut error_buf: ErrorBuffer,
+) {
+ let utf8_label = label.map(|utf16| utf16.to_string());
+ let label = utf8_label.as_ref().map(|s| Cow::from(&s[..]));
+ let usage = wgt::BufferUsages::from_bits_retain(usage);
+
+ // Don't trust the graphics driver with buffer sizes larger than our conservative max texture size.
+ if size > MAX_BUFFER_SIZE {
+ error_buf.init_str("Out of memory");
+ gfx_select!(self_id => global.create_buffer_error(buffer_id, label));
+ return;
+ }
+
+ let desc = wgc::resource::BufferDescriptor {
+ label,
+ size,
+ usage,
+ mapped_at_creation,
+ };
+ let (_, error) = gfx_select!(self_id => global.device_create_buffer(self_id, &desc, buffer_id));
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+}
+
+/// # Safety
+///
+/// Callers are responsible for ensuring `callback` is well-formed.
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_server_buffer_map(
+ global: &Global,
+ buffer_id: id::BufferId,
+ start: wgt::BufferAddress,
+ size: wgt::BufferAddress,
+ map_mode: wgc::device::HostMap,
+ callback: wgc::resource::BufferMapCallbackC,
+) {
+ let callback = wgc::resource::BufferMapCallback::from_c(callback);
+ let operation = wgc::resource::BufferMapOperation {
+ host: map_mode,
+ callback,
+ };
+ // All errors are also exposed to the mapping callback, so we handle them there and ignore
+ // the the returned value of buffer_map_async.
+ let _ = gfx_select!(buffer_id => global.buffer_map_async(
+ buffer_id,
+ start .. start + size,
+ operation
+ ));
+}
+
+#[repr(C)]
+pub struct MappedBufferSlice {
+ pub ptr: *mut u8,
+ pub length: u64,
+}
+
+/// # Safety
+///
+/// This function is unsafe as there is no guarantee that the given pointer is
+/// valid for `size` elements.
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_server_buffer_get_mapped_range(
+ global: &Global,
+ buffer_id: id::BufferId,
+ start: wgt::BufferAddress,
+ size: wgt::BufferAddress,
+) -> MappedBufferSlice {
+ let result = gfx_select!(buffer_id => global.buffer_get_mapped_range(
+ buffer_id,
+ start,
+ Some(size)
+ ));
+
+ // TODO: error reporting.
+
+ result
+ .map(|(ptr, length)| MappedBufferSlice { ptr, length })
+ .unwrap_or(MappedBufferSlice {
+ ptr: std::ptr::null_mut(),
+ length: 0,
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_buffer_unmap(
+ global: &Global,
+ buffer_id: id::BufferId,
+ mut error_buf: ErrorBuffer,
+) {
+ if let Err(e) = gfx_select!(buffer_id => global.buffer_unmap(buffer_id)) {
+ error_buf.init(e);
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_buffer_destroy(global: &Global, self_id: id::BufferId) {
+ // Per spec, there is no need for the buffer or even device to be in a valid state,
+ // even calling calling destroy multiple times is fine, so no error to push into
+ // an error scope.
+ let _ = gfx_select!(self_id => global.buffer_destroy(self_id));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_buffer_drop(global: &Global, self_id: id::BufferId) {
+ gfx_select!(self_id => global.buffer_drop(self_id, false));
+}
+
+impl Global {
+ fn device_action<A: wgc::hub::HalApi>(
+ &self,
+ self_id: id::DeviceId,
+ action: DeviceAction,
+ mut error_buf: ErrorBuffer,
+ ) {
+ match action {
+ DeviceAction::CreateTexture(id, desc) => {
+ let max = MAX_TEXTURE_EXTENT;
+ if desc.size.width > max
+ || desc.size.height > max
+ || desc.size.depth_or_array_layers > max
+ {
+ gfx_select!(self_id => self.create_texture_error(id, desc.label));
+ error_buf.init_str("Out of memory");
+ return;
+ }
+ let (_, error) = self.device_create_texture::<A>(self_id, &desc, id);
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+ }
+ DeviceAction::CreateSampler(id, desc) => {
+ let (_, error) = self.device_create_sampler::<A>(self_id, &desc, id);
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+ }
+ DeviceAction::CreateBindGroupLayout(id, desc) => {
+ let (_, error) = self.device_create_bind_group_layout::<A>(self_id, &desc, id);
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+ }
+ DeviceAction::CreatePipelineLayout(id, desc) => {
+ let (_, error) = self.device_create_pipeline_layout::<A>(self_id, &desc, id);
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+ }
+ DeviceAction::CreateBindGroup(id, desc) => {
+ let (_, error) = self.device_create_bind_group::<A>(self_id, &desc, id);
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+ }
+ DeviceAction::CreateShaderModule(id, desc, code) => {
+ let source = wgc::pipeline::ShaderModuleSource::Wgsl(code);
+ let (_, error) = self.device_create_shader_module::<A>(self_id, &desc, source, id);
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+ }
+ DeviceAction::CreateComputePipeline(id, desc, implicit) => {
+ let implicit_ids = implicit
+ .as_ref()
+ .map(|imp| wgc::device::ImplicitPipelineIds {
+ root_id: imp.pipeline,
+ group_ids: &imp.bind_groups,
+ });
+ let (_, error) =
+ self.device_create_compute_pipeline::<A>(self_id, &desc, id, implicit_ids);
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+ }
+ DeviceAction::CreateRenderPipeline(id, desc, implicit) => {
+ let implicit_ids = implicit
+ .as_ref()
+ .map(|imp| wgc::device::ImplicitPipelineIds {
+ root_id: imp.pipeline,
+ group_ids: &imp.bind_groups,
+ });
+ let (_, error) =
+ self.device_create_render_pipeline::<A>(self_id, &desc, id, implicit_ids);
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+ }
+ DeviceAction::CreateRenderBundle(id, encoder, desc) => {
+ let (_, error) = self.render_bundle_encoder_finish::<A>(encoder, &desc, id);
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+ }
+ DeviceAction::CreateCommandEncoder(id, desc) => {
+ let (_, error) = self.device_create_command_encoder::<A>(self_id, &desc, id);
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+ }
+ DeviceAction::Error(message) => {
+ error_buf.init_str(&message);
+ }
+ }
+ }
+
+ fn texture_action<A: wgc::hub::HalApi>(
+ &self,
+ self_id: id::TextureId,
+ action: TextureAction,
+ mut error_buf: ErrorBuffer,
+ ) {
+ match action {
+ TextureAction::CreateView(id, desc) => {
+ let (_, error) = self.texture_create_view::<A>(self_id, &desc, id);
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+ }
+ }
+ }
+
+ fn command_encoder_action<A: wgc::hub::HalApi>(
+ &self,
+ self_id: id::CommandEncoderId,
+ action: CommandEncoderAction,
+ mut error_buf: ErrorBuffer,
+ ) {
+ match action {
+ CommandEncoderAction::CopyBufferToBuffer {
+ src,
+ src_offset,
+ dst,
+ dst_offset,
+ size,
+ } => {
+ if let Err(err) = self.command_encoder_copy_buffer_to_buffer::<A>(
+ self_id, src, src_offset, dst, dst_offset, size,
+ ) {
+ error_buf.init(err);
+ }
+ }
+ CommandEncoderAction::CopyBufferToTexture { src, dst, size } => {
+ if let Err(err) =
+ self.command_encoder_copy_buffer_to_texture::<A>(self_id, &src, &dst, &size)
+ {
+ error_buf.init(err);
+ }
+ }
+ CommandEncoderAction::CopyTextureToBuffer { src, dst, size } => {
+ if let Err(err) =
+ self.command_encoder_copy_texture_to_buffer::<A>(self_id, &src, &dst, &size)
+ {
+ error_buf.init(err);
+ }
+ }
+ CommandEncoderAction::CopyTextureToTexture { src, dst, size } => {
+ if let Err(err) =
+ self.command_encoder_copy_texture_to_texture::<A>(self_id, &src, &dst, &size)
+ {
+ error_buf.init(err);
+ }
+ }
+ CommandEncoderAction::RunComputePass { base } => {
+ if let Err(err) =
+ self.command_encoder_run_compute_pass_impl::<A>(self_id, base.as_ref())
+ {
+ error_buf.init(err);
+ }
+ }
+ CommandEncoderAction::WriteTimestamp {
+ query_set_id,
+ query_index,
+ } => {
+ if let Err(err) =
+ self.command_encoder_write_timestamp::<A>(self_id, query_set_id, query_index)
+ {
+ error_buf.init(err);
+ }
+ }
+ CommandEncoderAction::ResolveQuerySet {
+ query_set_id,
+ start_query,
+ query_count,
+ destination,
+ destination_offset,
+ } => {
+ if let Err(err) = self.command_encoder_resolve_query_set::<A>(
+ self_id,
+ query_set_id,
+ start_query,
+ query_count,
+ destination,
+ destination_offset,
+ ) {
+ error_buf.init(err);
+ }
+ }
+ CommandEncoderAction::RunRenderPass {
+ base,
+ target_colors,
+ target_depth_stencil,
+ } => {
+ if let Err(err) = self.command_encoder_run_render_pass_impl::<A>(
+ self_id,
+ base.as_ref(),
+ &target_colors,
+ target_depth_stencil.as_ref(),
+ ) {
+ error_buf.init(err);
+ }
+ }
+ CommandEncoderAction::ClearBuffer { dst, offset, size } => {
+ if let Err(err) = self.command_encoder_clear_buffer::<A>(self_id, dst, offset, size)
+ {
+ error_buf.init(err);
+ }
+ }
+ CommandEncoderAction::ClearTexture {
+ dst,
+ ref subresource_range,
+ } => {
+ if let Err(err) =
+ self.command_encoder_clear_texture::<A>(self_id, dst, subresource_range)
+ {
+ error_buf.init(err);
+ }
+ }
+ CommandEncoderAction::PushDebugGroup(marker) => {
+ if let Err(err) = self.command_encoder_push_debug_group::<A>(self_id, &marker) {
+ error_buf.init(err);
+ }
+ }
+ CommandEncoderAction::PopDebugGroup => {
+ if let Err(err) = self.command_encoder_pop_debug_group::<A>(self_id) {
+ error_buf.init(err);
+ }
+ }
+ CommandEncoderAction::InsertDebugMarker(marker) => {
+ if let Err(err) = self.command_encoder_insert_debug_marker::<A>(self_id, &marker) {
+ error_buf.init(err);
+ }
+ }
+ }
+ }
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_server_device_action(
+ global: &Global,
+ self_id: id::DeviceId,
+ byte_buf: &ByteBuf,
+ error_buf: ErrorBuffer,
+) {
+ let action = bincode::deserialize(byte_buf.as_slice()).unwrap();
+ gfx_select!(self_id => global.device_action(self_id, action, error_buf));
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_server_texture_action(
+ global: &Global,
+ self_id: id::TextureId,
+ byte_buf: &ByteBuf,
+ error_buf: ErrorBuffer,
+) {
+ let action = bincode::deserialize(byte_buf.as_slice()).unwrap();
+ gfx_select!(self_id => global.texture_action(self_id, action, error_buf));
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_server_command_encoder_action(
+ global: &Global,
+ self_id: id::CommandEncoderId,
+ byte_buf: &ByteBuf,
+ error_buf: ErrorBuffer,
+) {
+ let action = bincode::deserialize(byte_buf.as_slice()).unwrap();
+ gfx_select!(self_id => global.command_encoder_action(self_id, action, error_buf));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_device_create_encoder(
+ global: &Global,
+ self_id: id::DeviceId,
+ desc: &wgt::CommandEncoderDescriptor<Option<&nsACString>>,
+ new_id: id::CommandEncoderId,
+ mut error_buf: ErrorBuffer,
+) {
+ let utf8_label = desc.label.map(|utf16| utf16.to_string());
+ let label = utf8_label.as_ref().map(|s| Cow::from(&s[..]));
+
+ let desc = desc.map_label(|_| label);
+ let (_, error) =
+ gfx_select!(self_id => global.device_create_command_encoder(self_id, &desc, new_id));
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_encoder_finish(
+ global: &Global,
+ self_id: id::CommandEncoderId,
+ desc: &wgt::CommandBufferDescriptor<Option<&nsACString>>,
+ mut error_buf: ErrorBuffer,
+) {
+ let label = wgpu_string(desc.label);
+ let desc = desc.map_label(|_| label);
+ let (_, error) = gfx_select!(self_id => global.command_encoder_finish(self_id, &desc));
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_encoder_drop(global: &Global, self_id: id::CommandEncoderId) {
+ gfx_select!(self_id => global.command_encoder_drop(self_id));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_command_buffer_drop(global: &Global, self_id: id::CommandBufferId) {
+ gfx_select!(self_id => global.command_buffer_drop(self_id));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_render_bundle_drop(global: &Global, self_id: id::RenderBundleId) {
+ gfx_select!(self_id => global.render_bundle_drop(self_id));
+}
+
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_server_encoder_copy_texture_to_buffer(
+ global: &Global,
+ self_id: id::CommandEncoderId,
+ source: &wgc::command::ImageCopyTexture,
+ dst_buffer: wgc::id::BufferId,
+ dst_layout: &crate::ImageDataLayout,
+ size: &wgt::Extent3d,
+) {
+ let destination = wgc::command::ImageCopyBuffer {
+ buffer: dst_buffer,
+ layout: dst_layout.into_wgt(),
+ };
+ gfx_select!(self_id => global.command_encoder_copy_texture_to_buffer(self_id, source, &destination, size)).unwrap();
+}
+
+/// # Safety
+///
+/// This function is unsafe as there is no guarantee that the given pointer is
+/// valid for `command_buffer_id_length` elements.
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_server_queue_submit(
+ global: &Global,
+ self_id: id::QueueId,
+ command_buffer_ids: *const id::CommandBufferId,
+ command_buffer_id_length: usize,
+ mut error_buf: ErrorBuffer,
+) {
+ let command_buffers = slice::from_raw_parts(command_buffer_ids, command_buffer_id_length);
+ let result = gfx_select!(self_id => global.queue_submit(self_id, command_buffers));
+ if let Err(err) = result {
+ error_buf.init(err);
+ }
+}
+
+/// # Safety
+///
+/// This function is unsafe as there is no guarantee that the given pointer is
+/// valid for `data_length` elements.
+#[no_mangle]
+pub unsafe extern "C" fn wgpu_server_queue_write_action(
+ global: &Global,
+ self_id: id::QueueId,
+ byte_buf: &ByteBuf,
+ data: *const u8,
+ data_length: usize,
+ mut error_buf: ErrorBuffer,
+) {
+ let action: QueueWriteAction = bincode::deserialize(byte_buf.as_slice()).unwrap();
+ let data = slice::from_raw_parts(data, data_length);
+ let result = match action {
+ QueueWriteAction::Buffer { dst, offset } => {
+ gfx_select!(self_id => global.queue_write_buffer(self_id, dst, offset, data))
+ }
+ QueueWriteAction::Texture { dst, layout, size } => {
+ gfx_select!(self_id => global.queue_write_texture(self_id, &dst, data, &layout, &size))
+ }
+ };
+ if let Err(err) = result {
+ error_buf.init(err);
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_bind_group_layout_drop(
+ global: &Global,
+ self_id: id::BindGroupLayoutId,
+) {
+ gfx_select!(self_id => global.bind_group_layout_drop(self_id));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_pipeline_layout_drop(global: &Global, self_id: id::PipelineLayoutId) {
+ gfx_select!(self_id => global.pipeline_layout_drop(self_id));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_bind_group_drop(global: &Global, self_id: id::BindGroupId) {
+ gfx_select!(self_id => global.bind_group_drop(self_id));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_shader_module_drop(global: &Global, self_id: id::ShaderModuleId) {
+ gfx_select!(self_id => global.shader_module_drop(self_id));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_compute_pipeline_drop(
+ global: &Global,
+ self_id: id::ComputePipelineId,
+) {
+ gfx_select!(self_id => global.compute_pipeline_drop(self_id));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_render_pipeline_drop(global: &Global, self_id: id::RenderPipelineId) {
+ gfx_select!(self_id => global.render_pipeline_drop(self_id));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_texture_drop(global: &Global, self_id: id::TextureId) {
+ gfx_select!(self_id => global.texture_drop(self_id, false));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_texture_view_drop(global: &Global, self_id: id::TextureViewId) {
+ gfx_select!(self_id => global.texture_view_drop(self_id, false)).unwrap();
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_sampler_drop(global: &Global, self_id: id::SamplerId) {
+ gfx_select!(self_id => global.sampler_drop(self_id));
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_compute_pipeline_get_bind_group_layout(
+ global: &Global,
+ self_id: id::ComputePipelineId,
+ index: u32,
+ assign_id: id::BindGroupLayoutId,
+ mut error_buf: ErrorBuffer,
+) {
+ let (_, error) = gfx_select!(self_id => global.compute_pipeline_get_bind_group_layout(self_id, index, assign_id));
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn wgpu_server_render_pipeline_get_bind_group_layout(
+ global: &Global,
+ self_id: id::RenderPipelineId,
+ index: u32,
+ assign_id: id::BindGroupLayoutId,
+ mut error_buf: ErrorBuffer,
+) {
+ let (_, error) = gfx_select!(self_id => global.render_pipeline_get_bind_group_layout(self_id, index, assign_id));
+ if let Some(err) = error {
+ error_buf.init(err);
+ }
+}
+
+/// Encode the freeing of the selected ID into a byte buf.
+#[no_mangle]
+pub extern "C" fn wgpu_server_adapter_free(id: id::AdapterId, drop_byte_buf: &mut ByteBuf) {
+ *drop_byte_buf = DropAction::Adapter(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_device_free(id: id::DeviceId, drop_byte_buf: &mut ByteBuf) {
+ *drop_byte_buf = DropAction::Device(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_shader_module_free(
+ id: id::ShaderModuleId,
+ drop_byte_buf: &mut ByteBuf,
+) {
+ *drop_byte_buf = DropAction::ShaderModule(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_pipeline_layout_free(
+ id: id::PipelineLayoutId,
+ drop_byte_buf: &mut ByteBuf,
+) {
+ *drop_byte_buf = DropAction::PipelineLayout(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_bind_group_layout_free(
+ id: id::BindGroupLayoutId,
+ drop_byte_buf: &mut ByteBuf,
+) {
+ *drop_byte_buf = DropAction::BindGroupLayout(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_bind_group_free(id: id::BindGroupId, drop_byte_buf: &mut ByteBuf) {
+ *drop_byte_buf = DropAction::BindGroup(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_command_buffer_free(
+ id: id::CommandBufferId,
+ drop_byte_buf: &mut ByteBuf,
+) {
+ *drop_byte_buf = DropAction::CommandBuffer(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_render_bundle_free(
+ id: id::RenderBundleId,
+ drop_byte_buf: &mut ByteBuf,
+) {
+ *drop_byte_buf = DropAction::RenderBundle(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_render_pipeline_free(
+ id: id::RenderPipelineId,
+ drop_byte_buf: &mut ByteBuf,
+) {
+ *drop_byte_buf = DropAction::RenderPipeline(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_compute_pipeline_free(
+ id: id::ComputePipelineId,
+ drop_byte_buf: &mut ByteBuf,
+) {
+ *drop_byte_buf = DropAction::ComputePipeline(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_buffer_free(id: id::BufferId, drop_byte_buf: &mut ByteBuf) {
+ *drop_byte_buf = DropAction::Buffer(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_texture_free(id: id::TextureId, drop_byte_buf: &mut ByteBuf) {
+ *drop_byte_buf = DropAction::Texture(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_texture_view_free(
+ id: id::TextureViewId,
+ drop_byte_buf: &mut ByteBuf,
+) {
+ *drop_byte_buf = DropAction::TextureView(id).to_byte_buf();
+}
+#[no_mangle]
+pub extern "C" fn wgpu_server_sampler_free(id: id::SamplerId, drop_byte_buf: &mut ByteBuf) {
+ *drop_byte_buf = DropAction::Sampler(id).to_byte_buf();
+}