WIP new wgpu-hal

This commit is contained in:
Dzmitry Malyshau committed 2021-06-08 00:46:08 -04:00
1 parent a92b8549a8
commit 569cd0cdd6
37 files changed
+1302 -2559

No files matched your search

Generated
+10 -348
View File
@@ -20,12 +20,6 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234"
[[package]]
name = "ahash"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6789e291be47ace86a60303502173d84af8327e3627ecf334356ee0f87a164c"
[[package]]
name = "aho-corasick"
version = "0.7.15"
@@ -66,15 +60,6 @@ dependencies = [
"serde",
]
[[package]]
name = "ash"
version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ea56be8250318e64923c7e65b82a35b5c29dfb6dc1c7d1c0b288c4b1bbb084"
dependencies = [
"libloading 0.7.0",
]
[[package]]
name = "async-executor"
version = "1.4.1"
@@ -198,9 +183,6 @@ name = "cc"
version = "1.0.62"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1770ced377336a88a67c473594ccc14eca6f4559217c34f64aac8f83d641b40"
dependencies = [
"jobserver",
]
[[package]]
name = "cfg-if"
@@ -456,17 +438,6 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "d3d12"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "091ed1b25fe47c7ff129fc440c23650b6114f36aa00bc7212cc8041879294428"
dependencies = [
"bitflags",
"libloading 0.7.0",
"winapi 0.3.9",
]
[[package]]
name = "darling"
version = "0.10.2"
@@ -546,7 +517,7 @@ version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b11f15d1e3268f140f68d390637d5e76d849782d971ae7063e0da69fe9709a76"
dependencies = [
"libloading 0.6.5",
"libloading",
]
[[package]]
@@ -704,150 +675,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "gfx-auxil"
version = "0.9.0"
source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521"
dependencies = [
"fxhash",
"gfx-hal",
"spirv_cross",
]
[[package]]
name = "gfx-backend-dx11"
version = "0.8.0"
source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521"
dependencies = [
"arrayvec",
"bitflags",
"gfx-auxil",
"gfx-hal",
"libloading 0.7.0",
"log",
"parking_lot",
"range-alloc",
"raw-window-handle",
"smallvec",
"spirv_cross",
"thunderdome",
"winapi 0.3.9",
"wio",
]
[[package]]
name = "gfx-backend-dx12"
version = "0.8.0"
source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521"
dependencies = [
"arrayvec",
"bit-set",
"bitflags",
"d3d12",
"gfx-auxil",
"gfx-hal",
"log",
"parking_lot",
"range-alloc",
"raw-window-handle",
"smallvec",
"spirv_cross",
"thunderdome",
"winapi 0.3.9",
]
[[package]]
name = "gfx-backend-empty"
version = "0.8.0"
source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521"
dependencies = [
"gfx-hal",
"log",
"raw-window-handle",
]
[[package]]
name = "gfx-backend-gl"
version = "0.8.1"
source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521"
dependencies = [
"arrayvec",
"bitflags",
"fxhash",
"gfx-auxil",
"gfx-hal",
"glow",
"js-sys",
"khronos-egl",
"libloading 0.7.0",
"log",
"naga",
"parking_lot",
"raw-window-handle",
"spirv_cross",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "gfx-backend-metal"
version = "0.8.1"
source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521"
dependencies = [
"arrayvec",
"bitflags",
"block",
"cocoa-foundation",
"copyless",
"foreign-types",
"fxhash",
"gfx-auxil",
"gfx-hal",
"log",
"metal",
"naga",
"objc",
"parking_lot",
"profiling",
"range-alloc",
"raw-window-handle",
"spirv_cross",
"storage-map",
]
[[package]]
name = "gfx-backend-vulkan"
version = "0.8.0"
source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521"
dependencies = [
"arrayvec",
"ash",
"byteorder",
"core-graphics-types",
"gfx-hal",
"inplace_it",
"libloading 0.7.0",
"log",
"naga",
"objc",
"parking_lot",
"raw-window-handle",
"renderdoc-sys",
"smallvec",
"winapi 0.3.9",
]
[[package]]
name = "gfx-hal"
version = "0.8.0"
source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521"
dependencies = [
"bitflags",
"naga",
"raw-window-handle",
"thiserror",
]
[[package]]
name = "gif"
version = "0.11.2"
@@ -858,65 +685,11 @@ dependencies = [
"weezl",
]
[[package]]
name = "glow"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b80b98efaa8a34fce11d60dd2ce2760d5d83c373cbcc73bb87c2a3a84a54108"
dependencies = [
"js-sys",
"slotmap",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "gpu-alloc"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8159cab119e2c6947476a8b941d478c8de4a1ce050d92c55903f8d0192ccacda"
dependencies = [
"bitflags",
"gpu-alloc-types",
]
[[package]]
name = "gpu-alloc-types"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54804d0d6bc9d7f26db4eaec1ad10def69b599315f487d32c334a80d1efe67a5"
dependencies = [
"bitflags",
]
[[package]]
name = "gpu-descriptor"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8a70f1e87a3840ed6a3e99e02c2b861e4dbdf26f0d07e38f42ea5aff46cfce2"
dependencies = [
"bitflags",
"gpu-descriptor-types",
"hashbrown",
]
[[package]]
name = "gpu-descriptor-types"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "363e3677e55ad168fef68cf9de3a4a310b53124c5e784c53a1d70e92d23f2126"
dependencies = [
"bitflags",
]
[[package]]
name = "hashbrown"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04"
dependencies = [
"ahash",
]
[[package]]
name = "hermit-abi"
@@ -968,12 +741,6 @@ dependencies = [
"hashbrown",
]
[[package]]
name = "inplace_it"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90953f308a79fe6d62a4643e51f848fbfddcd05975a38e69fdf4ab86a7baf7ca"
[[package]]
name = "instant"
version = "0.1.8"
@@ -1001,15 +768,6 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"
[[package]]
name = "jobserver"
version = "0.1.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c71313ebb9439f74b00d9d2dcec36440beaf57a6aa0623068441dd7cd81a7f2"
dependencies = [
"libc",
]
[[package]]
name = "jpeg-decoder"
version = "0.1.22"
@@ -1038,16 +796,6 @@ dependencies = [
"winapi-build",
]
[[package]]
name = "khronos-egl"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c2352bd1d0bceb871cb9d40f24360c8133c11d7486b68b5381c1dd1a32015e3"
dependencies = [
"libc",
"libloading 0.7.0",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
@@ -1076,16 +824,6 @@ dependencies = [
"winapi 0.3.9",
]
[[package]]
name = "libloading"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f84d96438c15fcd6c3f244c8fce01d1e2b9c6b5623e9c711dc9286d8fc92d6a"
dependencies = [
"cfg-if 1.0.0",
"winapi 0.3.9",
]
[[package]]
name = "lock_api"
version = "0.4.1"
@@ -1154,20 +892,6 @@ dependencies = [
"autocfg",
]
[[package]]
name = "metal"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c12e48c737ee9a55e8bb2352bcde588f79ae308d3529ee888f7cc0f469b5777"
dependencies = [
"bitflags",
"block",
"cocoa-foundation",
"foreign-types",
"log",
"objc",
]
[[package]]
name = "miniz_oxide"
version = "0.3.7"
@@ -1431,16 +1155,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"
dependencies = [
"malloc_buf",
"objc_exception",
]
[[package]]
name = "objc_exception"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad970fb455818ad6cba4c122ad012fae53ae8b4795f86378bce65e4f6bab2ca4"
dependencies = [
"cc",
]
[[package]]
@@ -1639,11 +1353,6 @@ dependencies = [
"rand_core",
]
[[package]]
name = "range-alloc"
version = "0.1.2"
source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521"
[[package]]
name = "raw-window-handle"
version = "0.3.3"
@@ -1702,12 +1411,6 @@ version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b181ba2dcf07aaccad5448e8ead58db5b742cf85dfe035e2227f137a539a189"
[[package]]
name = "renderdoc-sys"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1382d1f0a252c4bf97dc20d979a2fdd05b024acd7c2ed0f7595d7817666a157"
[[package]]
name = "ron"
version = "0.6.2"
@@ -1815,12 +1518,6 @@ version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8"
[[package]]
name = "slotmap"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c46a3482db8f247956e464d783693ece164ca056e6e67563ee5505bdb86452cd"
[[package]]
name = "smallvec"
version = "1.4.2"
@@ -1846,17 +1543,6 @@ dependencies = [
"wayland-protocols",
]
[[package]]
name = "spirv_cross"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06db6bd7b6518f761593783e2896eefe55e90455efc5f44511078ce0426ed418"
dependencies = [
"cc",
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "spirv_headers"
version = "1.5.0"
@@ -1867,15 +1553,6 @@ dependencies = [
"num-traits 0.2.14",
]
[[package]]
name = "storage-map"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "418bb14643aa55a7841d5303f72cf512cfb323b8cc221d51580500a1ca75206c"
dependencies = [
"lock_api",
]
[[package]]
name = "strsim"
version = "0.9.3"
@@ -1931,12 +1608,6 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "thunderdome"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87b4947742c93ece24a0032141d9caa3d853752e694a57e35029dd2bd08673e0"
[[package]]
name = "tiff"
version = "0.6.1"
@@ -2200,15 +1871,6 @@ dependencies = [
"cfg_aliases",
"copyless",
"fxhash",
"gfx-backend-dx11",
"gfx-backend-dx12",
"gfx-backend-empty",
"gfx-backend-gl",
"gfx-backend-metal",
"gfx-backend-vulkan",
"gfx-hal",
"gpu-alloc",
"gpu-descriptor",
"log",
"loom",
"naga",
@@ -2219,6 +1881,15 @@ dependencies = [
"serde",
"smallvec",
"thiserror",
"wgpu-hal",
"wgpu-types",
]
[[package]]
name = "wgpu-hal"
version = "0.1.0"
dependencies = [
"bitflags",
"wgpu-types",
]
@@ -2306,15 +1977,6 @@ dependencies = [
"x11-dl",
]
[[package]]
name = "wio"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5"
dependencies = [
"winapi 0.3.9",
]
[[package]]
name = "ws2_32-sys"
version = "0.2.1"
+1
View File
@@ -4,6 +4,7 @@ members = [
"player",
"wgpu",
"wgpu-core",
"wgpu-hal",
"wgpu-types",
]
default-members = ["wgpu"]
-1
View File
@@ -13,7 +13,6 @@ license = "MPL-2.0"
publish = false
[features]
cross = ["wgc/cross"]
[dependencies]
env_logger = "0.8"
+60 -60
View File
@@ -39,12 +39,12 @@ impl<I: Clone + Debug + wgc::id::TypedId> wgc::hub::IdentityHandlerFactory<I>
impl wgc::hub::GlobalIdentityHandlerFactory for IdentityPassThroughFactory {}
pub trait GlobalPlay {
fn encode_commands<B: wgc::hub::GfxBackend>(
fn encode_commands<B: wgc::hub::HalApi>(
&self,
encoder: wgc::id::CommandEncoderId,
commands: Vec<trace::Command>,
) -> wgc::id::CommandBufferId;
fn process<B: wgc::hub::GfxBackend>(
fn process<B: wgc::hub::HalApi>(
&self,
device: wgc::id::DeviceId,
action: trace::Action,
@@ -54,7 +54,7 @@ pub trait GlobalPlay {
}
impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
fn encode_commands<B: wgc::hub::GfxBackend>(
fn encode_commands<B: wgc::hub::HalApi>(
&self,
encoder: wgc::id::CommandEncoderId,
commands: Vec<trace::Command>,
@@ -68,33 +68,33 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
dst_offset,
size,
} => self
.command_encoder_copy_buffer_to_buffer::<B>(
.command_encoder_copy_buffer_to_buffer::<A>(
encoder, src, src_offset, dst, dst_offset, size,
)
.unwrap(),
trace::Command::CopyBufferToTexture { src, dst, size } => self
.command_encoder_copy_buffer_to_texture::<B>(encoder, &src, &dst, &size)
.command_encoder_copy_buffer_to_texture::<A>(encoder, &src, &dst, &size)
.unwrap(),
trace::Command::CopyTextureToBuffer { src, dst, size } => self
.command_encoder_copy_texture_to_buffer::<B>(encoder, &src, &dst, &size)
.command_encoder_copy_texture_to_buffer::<A>(encoder, &src, &dst, &size)
.unwrap(),
trace::Command::CopyTextureToTexture { src, dst, size } => self
.command_encoder_copy_texture_to_texture::<B>(encoder, &src, &dst, &size)
.command_encoder_copy_texture_to_texture::<A>(encoder, &src, &dst, &size)
.unwrap(),
trace::Command::ClearBuffer { dst, offset, size } => self
.command_encoder_clear_buffer::<B>(encoder, dst, offset, size)
.command_encoder_clear_buffer::<A>(encoder, dst, offset, size)
.unwrap(),
trace::Command::ClearImage {
dst,
subresource_range,
} => self
.command_encoder_clear_image::<B>(encoder, dst, &subresource_range)
.command_encoder_clear_image::<A>(encoder, dst, &subresource_range)
.unwrap(),
trace::Command::WriteTimestamp {
query_set_id,
query_index,
} => self
.command_encoder_write_timestamp::<B>(encoder, query_set_id, query_index)
.command_encoder_write_timestamp::<A>(encoder, query_set_id, query_index)
.unwrap(),
trace::Command::ResolveQuerySet {
query_set_id,
@@ -103,7 +103,7 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
destination,
destination_offset,
} => self
.command_encoder_resolve_query_set::<B>(
.command_encoder_resolve_query_set::<A>(
encoder,
query_set_id,
start_query,
@@ -113,7 +113,7 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
)
.unwrap(),
trace::Command::RunComputePass { base } => {
self.command_encoder_run_compute_pass_impl::<B>(encoder, base.as_ref())
self.command_encoder_run_compute_pass_impl::<A>(encoder, base.as_ref())
.unwrap();
}
trace::Command::RunRenderPass {
@@ -121,7 +121,7 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
target_colors,
target_depth_stencil,
} => {
self.command_encoder_run_render_pass_impl::<B>(
self.command_encoder_run_render_pass_impl::<A>(
encoder,
base.as_ref(),
&target_colors,
@@ -132,14 +132,14 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
}
}
let (cmd_buf, error) = self
.command_encoder_finish::<B>(encoder, &wgt::CommandBufferDescriptor { label: None });
.command_encoder_finish::<A>(encoder, &wgt::CommandBufferDescriptor { label: None });
if let Some(e) = error {
panic!("{:?}", e);
}
cmd_buf
}
fn process<B: wgc::hub::GfxBackend>(
fn process<B: wgc::hub::HalApi>(
&self,
device: wgc::id::DeviceId,
action: trace::Action,
@@ -155,90 +155,90 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
panic!("Unexpected SwapChain action: winit feature is not enabled")
}
A::CreateBuffer(id, desc) => {
self.device_maintain_ids::<B>(device).unwrap();
let (_, error) = self.device_create_buffer::<B>(device, &desc, id);
self.device_maintain_ids::<A>(device).unwrap();
let (_, error) = self.device_create_buffer::<A>(device, &desc, id);
if let Some(e) = error {
panic!("{:?}", e);
}
}
A::FreeBuffer(id) => {
self.buffer_destroy::<B>(id).unwrap();
self.buffer_destroy::<A>(id).unwrap();
}
A::DestroyBuffer(id) => {
self.buffer_drop::<B>(id, true);
self.buffer_drop::<A>(id, true);
}
A::CreateTexture(id, desc) => {
self.device_maintain_ids::<B>(device).unwrap();
let (_, error) = self.device_create_texture::<B>(device, &desc, id);
self.device_maintain_ids::<A>(device).unwrap();
let (_, error) = self.device_create_texture::<A>(device, &desc, id);
if let Some(e) = error {
panic!("{:?}", e);
}
}
A::FreeTexture(id) => {
self.texture_destroy::<B>(id).unwrap();
self.texture_destroy::<A>(id).unwrap();
}
A::DestroyTexture(id) => {
self.texture_drop::<B>(id, true);
self.texture_drop::<A>(id, true);
}
A::CreateTextureView {
id,
parent_id,
desc,
} => {
self.device_maintain_ids::<B>(device).unwrap();
let (_, error) = self.texture_create_view::<B>(parent_id, &desc, id);
self.device_maintain_ids::<A>(device).unwrap();
let (_, error) = self.texture_create_view::<A>(parent_id, &desc, id);
if let Some(e) = error {
panic!("{:?}", e);
}
}
A::DestroyTextureView(id) => {
self.texture_view_drop::<B>(id, true).unwrap();
self.texture_view_drop::<A>(id, true).unwrap();
}
A::CreateSampler(id, desc) => {
self.device_maintain_ids::<B>(device).unwrap();
let (_, error) = self.device_create_sampler::<B>(device, &desc, id);
self.device_maintain_ids::<A>(device).unwrap();
let (_, error) = self.device_create_sampler::<A>(device, &desc, id);
if let Some(e) = error {
panic!("{:?}", e);
}
}
A::DestroySampler(id) => {
self.sampler_drop::<B>(id);
self.sampler_drop::<A>(id);
}
A::GetSwapChainTexture { id, parent_id } => {
self.device_maintain_ids::<B>(device).unwrap();
self.swap_chain_get_current_texture_view::<B>(parent_id, id)
self.device_maintain_ids::<A>(device).unwrap();
self.swap_chain_get_current_texture_view::<A>(parent_id, id)
.unwrap()
.view_id
.unwrap();
}
A::CreateBindGroupLayout(id, desc) => {
let (_, error) = self.device_create_bind_group_layout::<B>(device, &desc, id);
let (_, error) = self.device_create_bind_group_layout::<A>(device, &desc, id);
if let Some(e) = error {
panic!("{:?}", e);
}
}
A::DestroyBindGroupLayout(id) => {
self.bind_group_layout_drop::<B>(id);
self.bind_group_layout_drop::<A>(id);
}
A::CreatePipelineLayout(id, desc) => {
self.device_maintain_ids::<B>(device).unwrap();
let (_, error) = self.device_create_pipeline_layout::<B>(device, &desc, id);
self.device_maintain_ids::<A>(device).unwrap();
let (_, error) = self.device_create_pipeline_layout::<A>(device, &desc, id);
if let Some(e) = error {
panic!("{:?}", e);
}
}
A::DestroyPipelineLayout(id) => {
self.pipeline_layout_drop::<B>(id);
self.pipeline_layout_drop::<A>(id);
}
A::CreateBindGroup(id, desc) => {
self.device_maintain_ids::<B>(device).unwrap();
let (_, error) = self.device_create_bind_group::<B>(device, &desc, id);
self.device_maintain_ids::<A>(device).unwrap();
let (_, error) = self.device_create_bind_group::<A>(device, &desc, id);
if let Some(e) = error {
panic!("{:?}", e);
}
}
A::DestroyBindGroup(id) => {
self.bind_group_drop::<B>(id);
self.bind_group_drop::<A>(id);
}
A::CreateShaderModule { id, desc, data } => {
let source = if data.ends_with(".wgsl") {
@@ -253,20 +253,20 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
.collect::<Vec<_>>();
wgc::pipeline::ShaderModuleSource::SpirV(Cow::Owned(spv))
};
let (_, error) = self.device_create_shader_module::<B>(device, &desc, source, id);
let (_, error) = self.device_create_shader_module::<A>(device, &desc, source, id);
if let Some(e) = error {
panic!("{:?}", e);
}
}
A::DestroyShaderModule(id) => {
self.shader_module_drop::<B>(id);
self.shader_module_drop::<A>(id);
}
A::CreateComputePipeline {
id,
desc,
implicit_context,
} => {
self.device_maintain_ids::<B>(device).unwrap();
self.device_maintain_ids::<A>(device).unwrap();
let implicit_ids =
implicit_context
.as_ref()
@@ -275,20 +275,20 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
group_ids: &ic.group_ids,
});
let (_, error) =
self.device_create_compute_pipeline::<B>(device, &desc, id, implicit_ids);
self.device_create_compute_pipeline::<A>(device, &desc, id, implicit_ids);
if let Some(e) = error {
panic!("{:?}", e);
}
}
A::DestroyComputePipeline(id) => {
self.compute_pipeline_drop::<B>(id);
self.compute_pipeline_drop::<A>(id);
}
A::CreateRenderPipeline {
id,
desc,
implicit_context,
} => {
self.device_maintain_ids::<B>(device).unwrap();
self.device_maintain_ids::<A>(device).unwrap();
let implicit_ids =
implicit_context
.as_ref()
@@ -297,18 +297,18 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
group_ids: &ic.group_ids,
});
let (_, error) =
self.device_create_render_pipeline::<B>(device, &desc, id, implicit_ids);
self.device_create_render_pipeline::<A>(device, &desc, id, implicit_ids);
if let Some(e) = error {
panic!("{:?}", e);
}
}
A::DestroyRenderPipeline(id) => {
self.render_pipeline_drop::<B>(id);
self.render_pipeline_drop::<A>(id);
}
A::CreateRenderBundle { id, desc, base } => {
let bundle =
wgc::command::RenderBundleEncoder::new(&desc, device, Some(base)).unwrap();
let (_, error) = self.render_bundle_encoder_finish::<B>(
let (_, error) = self.render_bundle_encoder_finish::<A>(
bundle,
&wgt::RenderBundleDescriptor { label: desc.label },
id,
@@ -318,17 +318,17 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
}
}
A::DestroyRenderBundle(id) => {
self.render_bundle_drop::<B>(id);
self.render_bundle_drop::<A>(id);
}
A::CreateQuerySet { id, desc } => {
self.device_maintain_ids::<B>(device).unwrap();
let (_, error) = self.device_create_query_set::<B>(device, &desc, id);
self.device_maintain_ids::<A>(device).unwrap();
let (_, error) = self.device_create_query_set::<A>(device, &desc, id);
if let Some(e) = error {
panic!("{:?}", e);
}
}
A::DestroyQuerySet(id) => {
self.query_set_drop::<B>(id);
self.query_set_drop::<A>(id);
}
A::WriteBuffer {
id,
@@ -339,11 +339,11 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
let bin = std::fs::read(dir.join(data)).unwrap();
let size = (range.end - range.start) as usize;
if queued {
self.queue_write_buffer::<B>(device, id, range.start, &bin)
self.queue_write_buffer::<A>(device, id, range.start, &bin)
.unwrap();
} else {
self.device_wait_for_buffer::<B>(device, id).unwrap();
self.device_set_buffer_sub_data::<B>(device, id, range.start, &bin[..size])
self.device_wait_for_buffer::<A>(device, id).unwrap();
self.device_set_buffer_sub_data::<A>(device, id, range.start, &bin[..size])
.unwrap();
}
}
@@ -354,14 +354,14 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
size,
} => {
let bin = std::fs::read(dir.join(data)).unwrap();
self.queue_write_texture::<B>(device, &to, &bin, &layout, &size)
self.queue_write_texture::<A>(device, &to, &bin, &layout, &size)
.unwrap();
}
A::Submit(_index, ref commands) if commands.is_empty() => {
self.queue_submit::<B>(device, &[]).unwrap();
self.queue_submit::<A>(device, &[]).unwrap();
}
A::Submit(_index, commands) => {
let (encoder, error) = self.device_create_command_encoder::<B>(
let (encoder, error) = self.device_create_command_encoder::<A>(
device,
&wgt::CommandEncoderDescriptor { label: None },
comb_manager.alloc(device.backend()),
@@ -369,8 +369,8 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
if let Some(e) = error {
panic!("{:?}", e);
}
let cmdbuf = self.encode_commands::<B>(encoder, commands);
self.queue_submit::<B>(device, &[cmdbuf]).unwrap();
let cmdbuf = self.encode_commands::<A>(encoder, commands);
self.queue_submit::<A>(device, &[cmdbuf]).unwrap();
}
}
}
+5 -24
View File
@@ -13,8 +13,6 @@ license = "MPL-2.0"
[features]
default = []
# Enable SPIRV-Cross
cross = ["gfx-backend-metal/cross", "gfx-backend-gl/cross"]
# Enable API tracing
trace = ["ron", "serde", "wgt/trace", "arrayvec/serde"]
# Enable API replaying
@@ -36,28 +34,6 @@ serde = { version = "1.0", features = ["serde_derive"], optional = true }
smallvec = "1"
thiserror = "1"
gpu-alloc = "0.4"
gpu-descriptor = "0.1"
hal = { package = "gfx-hal", git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" }
gfx-backend-empty = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" }
[target.'cfg(all(not(target_arch = "wasm32"), all(unix, not(target_os = "ios"), not(target_os = "macos"))))'.dependencies]
gfx-backend-vulkan = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521", features = ["naga"] }
gfx-backend-gl = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" }
[target.'cfg(all(not(target_arch = "wasm32"), any(target_os = "ios", target_os = "macos")))'.dependencies]
gfx-backend-metal = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" }
#TODO: could also depend on gfx-backend-vulkan for Vulkan Portability
[target.'cfg(all(not(target_arch = "wasm32"), windows))'.dependencies]
gfx-backend-dx12 = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" }
gfx-backend-dx11 = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" }
gfx-backend-vulkan = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521", features = ["naga"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
gfx-backend-gl = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" }
[dependencies.naga]
git = "https://github.com/gfx-rs/naga"
tag = "gfx-25"
@@ -68,6 +44,11 @@ path = "../wgpu-types"
package = "wgpu-types"
version = "0.8"
[dependencies.hal]
path = "../wgpu-hal"
package = "wgpu-hal"
version = "0.1"
[dev-dependencies]
loom = "0.3"
+12 -12
View File
@@ -12,7 +12,7 @@ use crate::{
memory_init_tracker::MemoryInitTrackerAction,
track::{TrackerSet, UsageConflict, DUMMY_SELECTOR},
validation::{MissingBufferUsageError, MissingTextureUsageError},
FastHashMap, Label, LifeGuard, MultiRefCount, Stored, MAX_BIND_GROUPS,
FastHashMap, Label, LifeGuard, MultiRefCount, Stored,
};
use arrayvec::ArrayVec;
@@ -389,7 +389,7 @@ pub struct BindGroupLayoutDescriptor<'a> {
pub(crate) type BindEntryMap = FastHashMap<u32, wgt::BindGroupLayoutEntry>;
#[derive(Debug)]
pub struct BindGroupLayout<B: hal::Backend> {
pub struct BindGroupLayout<A: hal::Api> {
pub(crate) raw: B::DescriptorSetLayout,
pub(crate) device_id: Stored<DeviceId>,
pub(crate) multi_ref_count: MultiRefCount,
@@ -401,7 +401,7 @@ pub struct BindGroupLayout<B: hal::Backend> {
pub(crate) label: String,
}
impl<B: hal::Backend> Resource for BindGroupLayout<B> {
impl<A: hal::Api> Resource for BindGroupLayout<A> {
const TYPE: &'static str = "BindGroupLayout";
fn life_guard(&self) -> &LifeGuard {
@@ -498,15 +498,15 @@ pub struct PipelineLayoutDescriptor<'a> {
}
#[derive(Debug)]
pub struct PipelineLayout<B: hal::Backend> {
pub struct PipelineLayout<A: hal::Api> {
pub(crate) raw: B::PipelineLayout,
pub(crate) device_id: Stored<DeviceId>,
pub(crate) life_guard: LifeGuard,
pub(crate) bind_group_layout_ids: ArrayVec<[Valid<BindGroupLayoutId>; MAX_BIND_GROUPS]>,
pub(crate) bind_group_layout_ids: ArrayVec<[Valid<BindGroupLayoutId>; hal::MAX_BIND_GROUPS]>,
pub(crate) push_constant_ranges: ArrayVec<[wgt::PushConstantRange; SHADER_STAGE_COUNT]>,
}
impl<B: hal::Backend> PipelineLayout<B> {
impl<A: hal::Api> PipelineLayout<A> {
/// Validate push constants match up with expected ranges.
pub(crate) fn validate_push_constant_ranges(
&self,
@@ -586,7 +586,7 @@ impl<B: hal::Backend> PipelineLayout<B> {
}
}
impl<B: hal::Backend> Resource for PipelineLayout<B> {
impl<A: hal::Api> Resource for PipelineLayout<A> {
const TYPE: &'static str = "PipelineLayout";
fn life_guard(&self) -> &LifeGuard {
@@ -636,8 +636,8 @@ pub struct BindGroupDynamicBindingData {
}
#[derive(Debug)]
pub struct BindGroup<B: hal::Backend> {
pub(crate) raw: DescriptorSet<B>,
pub struct BindGroup<A: hal::Api> {
pub(crate) raw: DescriptorSet<A>,
pub(crate) device_id: Stored<DeviceId>,
pub(crate) layout_id: Valid<BindGroupLayoutId>,
pub(crate) life_guard: LifeGuard,
@@ -646,7 +646,7 @@ pub struct BindGroup<B: hal::Backend> {
pub(crate) dynamic_binding_info: Vec<BindGroupDynamicBindingData>,
}
impl<B: hal::Backend> BindGroup<B> {
impl<A: hal::Api> BindGroup<A> {
pub(crate) fn validate_dynamic_bindings(
&self,
offsets: &[wgt::DynamicOffset],
@@ -681,13 +681,13 @@ impl<B: hal::Backend> BindGroup<B> {
}
}
impl<B: hal::Backend> Borrow<()> for BindGroup<B> {
impl<A: hal::Api> Borrow<()> for BindGroup<A> {
fn borrow(&self) -> &() {
&DUMMY_SELECTOR
}
}
impl<B: hal::Backend> Resource for BindGroup<B> {
impl<A: hal::Api> Resource for BindGroup<A> {
const TYPE: &'static str = "BindGroup";
fn life_guard(&self) -> &LifeGuard {
+16 -16
View File
@@ -4,7 +4,7 @@
use super::{CommandBuffer, CommandEncoderStatus};
use crate::{
device::DeviceError, hub::GfxBackend, id::DeviceId, track::TrackerSet, FastHashMap,
device::DeviceError, hub::HalApi, id::DeviceId, track::TrackerSet, FastHashMap,
PrivateFeatures, Stored, SubmissionIndex,
};
@@ -20,14 +20,14 @@ use std::thread;
const GROW_AMOUNT: usize = 20;
#[derive(Debug)]
struct CommandPool<B: hal::Backend> {
struct CommandPool<A: hal::Api> {
raw: B::CommandPool,
total: usize,
available: Vec<B::CommandBuffer>,
pending: Vec<(B::CommandBuffer, SubmissionIndex)>,
}
impl<B: hal::Backend> CommandPool<B> {
impl<A: hal::Api> CommandPool<A> {
fn maintain(&mut self, last_done_index: SubmissionIndex) {
for i in (0..self.pending.len()).rev() {
if self.pending[i].1 <= last_done_index {
@@ -72,31 +72,31 @@ impl<B: hal::Backend> CommandPool<B> {
}
#[derive(Debug)]
struct Inner<B: hal::Backend> {
pools: FastHashMap<thread::ThreadId, CommandPool<B>>,
struct Inner<A: hal::Api> {
pools: FastHashMap<thread::ThreadId, CommandPool<A>>,
}
#[derive(Debug)]
pub struct CommandAllocator<B: hal::Backend> {
pub struct CommandAllocator<A: hal::Api> {
queue_family: hal::queue::QueueFamilyId,
internal_thread_id: thread::ThreadId,
inner: Mutex<Inner<B>>,
inner: Mutex<Inner<A>>,
}
impl<B: GfxBackend> CommandAllocator<B> {
impl<A: HalApi> CommandAllocator<A> {
#[allow(clippy::too_many_arguments)]
pub(crate) fn allocate(
&self,
device_id: Stored<DeviceId>,
device: &B::Device,
limits: wgt::Limits,
downlevel: wgt::DownlevelProperties,
downlevel: wgt::DownlevelCapabilities,
features: wgt::Features,
private_features: PrivateFeatures,
label: &crate::Label,
#[cfg(feature = "trace")] enable_tracing: bool,
) -> Result<CommandBuffer<B>, CommandAllocatorError> {
//debug_assert_eq!(device_id.backend(), B::VARIANT);
) -> Result<CommandBuffer<A>, CommandAllocatorError> {
//debug_assert_eq!(device_id.backend(), A::VARIANT);
let thread_id = thread::current().id();
let mut inner = self.inner.lock();
@@ -130,7 +130,7 @@ impl<B: GfxBackend> CommandAllocator<B> {
status: CommandEncoderStatus::Recording,
recorded_thread_id: thread_id,
device_id,
trackers: TrackerSet::new(B::VARIANT),
trackers: TrackerSet::new(A::VARIANT),
used_swap_chains: Default::default(),
buffer_memory_init_actions: Default::default(),
limits,
@@ -150,7 +150,7 @@ impl<B: GfxBackend> CommandAllocator<B> {
}
}
impl<B: hal::Backend> CommandAllocator<B> {
impl<A: hal::Api> CommandAllocator<A> {
pub fn new(
queue_family: hal::queue::QueueFamilyId,
device: &B::Device,
@@ -190,7 +190,7 @@ impl<B: hal::Backend> CommandAllocator<B> {
self.allocate_for_thread_id(self.internal_thread_id)
}
pub fn extend(&self, cmd_buf: &CommandBuffer<B>) -> B::CommandBuffer {
pub fn extend(&self, cmd_buf: &CommandBuffer<A>) -> B::CommandBuffer {
self.allocate_for_thread_id(cmd_buf.recorded_thread_id)
}
@@ -203,7 +203,7 @@ impl<B: hal::Backend> CommandAllocator<B> {
.recycle(raw);
}
pub fn discard(&self, mut cmd_buf: CommandBuffer<B>) {
pub fn discard(&self, mut cmd_buf: CommandBuffer<A>) {
cmd_buf.trackers.clear();
let mut inner = self.inner.lock();
let pool = inner.pools.get_mut(&cmd_buf.recorded_thread_id).unwrap();
@@ -224,7 +224,7 @@ impl<B: hal::Backend> CommandAllocator<B> {
pub fn after_submit(
&self,
cmd_buf: CommandBuffer<B>,
cmd_buf: CommandBuffer<A>,
device: &B::Device,
submit_index: SubmissionIndex,
) {
+6 -6
View File
@@ -5,7 +5,7 @@
use crate::{
binding_model::{BindGroup, PipelineLayout},
device::SHADER_STAGE_COUNT,
hub::{GfxBackend, Storage},
hub::{HalApi, Storage},
id::{BindGroupId, BindGroupLayoutId, PipelineLayoutId, Valid},
Stored, MAX_BIND_GROUPS,
};
@@ -166,9 +166,9 @@ impl Binder {
}
}
pub(super) fn change_pipeline_layout<'a, B: GfxBackend>(
pub(super) fn change_pipeline_layout<'a, A: HalApi>(
&'a mut self,
guard: &Storage<PipelineLayout<B>, PipelineLayoutId>,
guard: &Storage<PipelineLayout<A>, PipelineLayoutId>,
new_id: Valid<PipelineLayoutId>,
) -> (usize, &'a [EntryPayload]) {
let old_id_opt = self.pipeline_layout_id.replace(new_id);
@@ -187,15 +187,15 @@ impl Binder {
(bind_range.start, &self.payloads[bind_range])
}
pub(super) fn assign_group<'a, B: GfxBackend>(
pub(super) fn assign_group<'a, A: HalApi>(
&'a mut self,
index: usize,
bind_group_id: Valid<BindGroupId>,
bind_group: &BindGroup<B>,
bind_group: &BindGroup<A>,
offsets: &[wgt::DynamicOffset],
) -> &'a [EntryPayload] {
log::trace!("\tBinding [{}] = group {:?}", index, bind_group_id);
debug_assert_eq!(B::VARIANT, bind_group_id.0.backend());
debug_assert_eq!(A::VARIANT, bind_group_id.0.backend());
let payload = &mut self.payloads[index];
payload.group_id = Some(Stored {
+10 -10
View File
@@ -47,7 +47,7 @@ use crate::{
AttachmentData, Device, DeviceError, RenderPassContext, MAX_VERTEX_BUFFERS,
SHADER_STAGE_COUNT,
},
hub::{GfxBackend, GlobalIdentityHandlerFactory, Hub, Resource, Storage, Token},
hub::{GlobalIdentityHandlerFactory, HalApi, Hub, Resource, Storage, Token},
id,
memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction},
resource::BufferUse,
@@ -135,12 +135,12 @@ impl RenderBundleEncoder {
self.parent_id
}
pub(crate) fn finish<B: hal::Backend, G: GlobalIdentityHandlerFactory>(
pub(crate) fn finish<A: hal::Api, G: GlobalIdentityHandlerFactory>(
self,
desc: &RenderBundleDescriptor,
device: &Device<B>,
hub: &Hub<B, G>,
token: &mut Token<Device<B>>,
device: &Device<A>,
hub: &Hub<A, G>,
token: &mut Token<Device<A>>,
) -> Result<RenderBundle, RenderBundleError> {
let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(token);
let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token);
@@ -565,16 +565,16 @@ impl RenderBundle {
/// Note that the function isn't expected to fail, generally.
/// All the validation has already been done by this point.
/// The only failure condition is if some of the used buffers are destroyed.
pub(crate) unsafe fn execute<B: GfxBackend>(
pub(crate) unsafe fn execute<A: HalApi>(
&self,
cmd_buf: &mut B::CommandBuffer,
pipeline_layout_guard: &Storage<
crate::binding_model::PipelineLayout<B>,
crate::binding_model::PipelineLayout<A>,
id::PipelineLayoutId,
>,
bind_group_guard: &Storage<crate::binding_model::BindGroup<B>, id::BindGroupId>,
pipeline_guard: &Storage<crate::pipeline::RenderPipeline<B>, id::RenderPipelineId>,
buffer_guard: &Storage<crate::resource::Buffer<B>, id::BufferId>,
bind_group_guard: &Storage<crate::binding_model::BindGroup<A>, id::BindGroupId>,
pipeline_guard: &Storage<crate::pipeline::RenderPipeline<A>, id::RenderPipelineId>,
buffer_guard: &Storage<crate::resource::Buffer<A>, id::BufferId>,
) -> Result<(), ExecutionError> {
use hal::command::CommandBuffer as _;
+8 -8
View File
@@ -10,7 +10,7 @@ use crate::{
command::CommandBuffer,
conv,
device::all_buffer_stages,
hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Token},
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Token},
id::{BufferId, CommandEncoderId, TextureId},
memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction},
resource::{BufferUse, TextureUse},
@@ -48,7 +48,7 @@ pub enum ClearError {
MissingCopyDstUsageFlag(Option<BufferId>, Option<TextureId>),
#[error("texture lacks the aspects that were specified in the image subresource range. Texture has {texture_aspects:?}, specified was {subresource_range_aspects:?}")]
MissingTextureAspect {
texture_aspects: hal::format::Aspects,
texture_aspects: hal::FormatAspect,
subresource_range_aspects: TextureAspect,
},
#[error("image subresource level range is outside of the texture's level range. texture range is {texture_level_range:?}, \
@@ -68,7 +68,7 @@ whereas subesource range specified start {subresource_base_array_layer} and coun
}
impl<G: GlobalIdentityHandlerFactory> Global<G> {
pub fn command_encoder_clear_buffer<B: GfxBackend>(
pub fn command_encoder_clear_buffer<A: HalApi>(
&self,
command_encoder_id: CommandEncoderId,
dst: BufferId,
@@ -77,7 +77,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
) -> Result<(), ClearError> {
profiling::scope!("CommandEncoder::fill_buffer");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token);
let cmd_buf = CommandBuffer::get_encoder_mut(&mut *cmd_buf_guard, command_encoder_id)
@@ -165,7 +165,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
Ok(())
}
pub fn command_encoder_clear_image<B: GfxBackend>(
pub fn command_encoder_clear_image<A: HalApi>(
&self,
command_encoder_id: CommandEncoderId,
dst: TextureId,
@@ -173,7 +173,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
) -> Result<(), ClearError> {
profiling::scope!("CommandEncoder::clear_image");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token);
let cmd_buf = CommandBuffer::get_encoder_mut(&mut *cmd_buf_guard, command_encoder_id)
@@ -200,8 +200,8 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
// Check if subresource aspects are valid.
let aspects = match subresource_range.aspect {
wgt::TextureAspect::All => dst_texture.aspects,
wgt::TextureAspect::DepthOnly => hal::format::Aspects::DEPTH,
wgt::TextureAspect::StencilOnly => hal::format::Aspects::STENCIL,
wgt::TextureAspect::DepthOnly => hal::FormatAspect::DEPTH,
wgt::TextureAspect::StencilOnly => hal::FormatAspect::STENCIL,
};
if !dst_texture.aspects.contains(aspects) {
return Err(ClearError::MissingTextureAspect {
+10 -10
View File
@@ -9,7 +9,7 @@ use crate::{
CommandEncoderError, CommandEncoderStatus, MapPassErr, PassErrorScope, QueryUseError,
StateChange,
},
hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Storage, Token},
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token},
id,
memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction},
resource::{Buffer, BufferUse, Texture},
@@ -214,13 +214,13 @@ impl State {
Ok(())
}
fn flush_states<B: GfxBackend>(
fn flush_states<A: HalApi>(
&mut self,
raw_cmd_buf: &mut B::CommandBuffer,
base_trackers: &mut TrackerSet,
bind_group_guard: &Storage<BindGroup<B>, id::BindGroupId>,
buffer_guard: &Storage<Buffer<B>, id::BufferId>,
texture_guard: &Storage<Texture<B>, id::TextureId>,
bind_group_guard: &Storage<BindGroup<A>, id::BindGroupId>,
buffer_guard: &Storage<Buffer<A>, id::BufferId>,
texture_guard: &Storage<Texture<A>, id::TextureId>,
) -> Result<(), UsageConflict> {
for id in self.binder.list_active() {
self.trackers.merge_extend(&bind_group_guard[id].used)?;
@@ -246,16 +246,16 @@ impl State {
// Common routines between render/compute
impl<G: GlobalIdentityHandlerFactory> Global<G> {
pub fn command_encoder_run_compute_pass<B: GfxBackend>(
pub fn command_encoder_run_compute_pass<A: HalApi>(
&self,
encoder_id: id::CommandEncoderId,
pass: &ComputePass,
) -> Result<(), ComputePassError> {
self.command_encoder_run_compute_pass_impl::<B>(encoder_id, pass.base.as_ref())
self.command_encoder_run_compute_pass_impl::<A>(encoder_id, pass.base.as_ref())
}
#[doc(hidden)]
pub fn command_encoder_run_compute_pass_impl<B: GfxBackend>(
pub fn command_encoder_run_compute_pass_impl<A: HalApi>(
&self,
encoder_id: id::CommandEncoderId,
base: BasePassRef<ComputeCommand>,
@@ -263,7 +263,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
profiling::scope!("run_compute_pass", "CommandEncoder");
let scope = PassErrorScope::Pass(encoder_id);
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token);
@@ -308,7 +308,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
let mut state = State {
binder: Binder::new(),
pipeline: StateChange::new(),
trackers: StatefulTrackerSubset::new(B::VARIANT),
trackers: StatefulTrackerSubset::new(A::VARIANT),
debug_scope_depth: 0,
};
let mut temp_offsets = Vec::new();
+16 -16
View File
@@ -23,7 +23,7 @@ pub use self::transfer::*;
use crate::{
device::{all_buffer_stages, all_image_stages},
hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Storage, Token},
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token},
id,
memory_init_tracker::MemoryInitTrackerAction,
resource::{Buffer, Texture},
@@ -47,7 +47,7 @@ enum CommandEncoderStatus {
}
#[derive(Debug)]
pub struct CommandBuffer<B: hal::Backend> {
pub struct CommandBuffer<A: hal::Api> {
pub(crate) raw: Vec<B::CommandBuffer>,
status: CommandEncoderStatus,
recorded_thread_id: ThreadId,
@@ -56,7 +56,7 @@ pub struct CommandBuffer<B: hal::Backend> {
pub(crate) used_swap_chains: SmallVec<[Stored<id::SwapChainId>; 1]>,
pub(crate) buffer_memory_init_actions: Vec<MemoryInitTrackerAction<id::BufferId>>,
limits: wgt::Limits,
downlevel: wgt::DownlevelProperties,
downlevel: wgt::DownlevelCapabilities,
private_features: PrivateFeatures,
support_fill_buffer_texture: bool,
has_labels: bool,
@@ -66,7 +66,7 @@ pub struct CommandBuffer<B: hal::Backend> {
pub(crate) label: String,
}
impl<B: GfxBackend> CommandBuffer<B> {
impl<A: HalApi> CommandBuffer<A> {
fn get_encoder_mut(
storage: &mut Storage<Self, id::CommandEncoderId>,
id: id::CommandEncoderId,
@@ -93,13 +93,13 @@ impl<B: GfxBackend> CommandBuffer<B> {
base: &mut TrackerSet,
head_buffers: &ResourceTracker<BufferState>,
head_textures: &ResourceTracker<TextureState>,
buffer_guard: &Storage<Buffer<B>, id::BufferId>,
texture_guard: &Storage<Texture<B>, id::TextureId>,
buffer_guard: &Storage<Buffer<A>, id::BufferId>,
texture_guard: &Storage<Texture<A>, id::TextureId>,
) {
use hal::command::CommandBuffer as _;
profiling::scope!("insert_barriers");
debug_assert_eq!(B::VARIANT, base.backend());
debug_assert_eq!(A::VARIANT, base.backend());
let buffer_barriers = base.buffers.merge_replace(head_buffers).map(|pending| {
let buf = &buffer_guard[pending.id];
@@ -122,7 +122,7 @@ impl<B: GfxBackend> CommandBuffer<B> {
}
}
impl<B: hal::Backend> crate::hub::Resource for CommandBuffer<B> {
impl<A: hal::Api> crate::hub::Resource for CommandBuffer<A> {
const TYPE: &'static str = "CommandBuffer";
fn life_guard(&self) -> &crate::LifeGuard {
@@ -206,14 +206,14 @@ pub enum CommandEncoderError {
}
impl<G: GlobalIdentityHandlerFactory> Global<G> {
pub fn command_encoder_finish<B: GfxBackend>(
pub fn command_encoder_finish<A: HalApi>(
&self,
encoder_id: id::CommandEncoderId,
_desc: &wgt::CommandBufferDescriptor<Label>,
) -> (id::CommandBufferId, Option<CommandEncoderError>) {
profiling::scope!("finish", "CommandEncoder");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (swap_chain_guard, mut token) = hub.swap_chains.read(&mut token);
//TODO: actually close the last recorded command buffer
@@ -239,14 +239,14 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
(encoder_id, error)
}
pub fn command_encoder_push_debug_group<B: GfxBackend>(
pub fn command_encoder_push_debug_group<A: HalApi>(
&self,
encoder_id: id::CommandEncoderId,
label: &str,
) -> Result<(), CommandEncoderError> {
profiling::scope!("push_debug_group", "CommandEncoder");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut cmd_buf_guard, _) = hub.command_buffers.write(&mut token);
@@ -259,14 +259,14 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
Ok(())
}
pub fn command_encoder_insert_debug_marker<B: GfxBackend>(
pub fn command_encoder_insert_debug_marker<A: HalApi>(
&self,
encoder_id: id::CommandEncoderId,
label: &str,
) -> Result<(), CommandEncoderError> {
profiling::scope!("insert_debug_marker", "CommandEncoder");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut cmd_buf_guard, _) = hub.command_buffers.write(&mut token);
@@ -279,13 +279,13 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
Ok(())
}
pub fn command_encoder_pop_debug_group<B: GfxBackend>(
pub fn command_encoder_pop_debug_group<A: HalApi>(
&self,
encoder_id: id::CommandEncoderId,
) -> Result<(), CommandEncoderError> {
profiling::scope!("pop_debug_marker", "CommandEncoder");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut cmd_buf_guard, _) = hub.command_buffers.write(&mut token);
+18 -18
View File
@@ -9,7 +9,7 @@ use crate::device::trace::Command as TraceCommand;
use crate::{
command::{CommandBuffer, CommandEncoderError},
device::all_buffer_stages,
hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Storage, Token},
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token},
id::{self, Id, TypedId},
resource::{BufferUse, QuerySet},
track::UseExtendError,
@@ -20,11 +20,11 @@ use thiserror::Error;
use wgt::BufferAddress;
#[derive(Debug)]
pub(super) struct QueryResetMap<B: hal::Backend> {
pub(super) struct QueryResetMap<A: hal::Api> {
map: FastHashMap<Index, (Vec<bool>, Epoch)>,
_phantom: PhantomData<B>,
_phantom: PhantomData<A>,
}
impl<B: hal::Backend> QueryResetMap<B> {
impl<A: hal::Api> QueryResetMap<A> {
pub fn new() -> Self {
Self {
map: FastHashMap::default(),
@@ -35,7 +35,7 @@ impl<B: hal::Backend> QueryResetMap<B> {
pub fn use_query_set(
&mut self,
id: id::QuerySetId,
query_set: &QuerySet<B>,
query_set: &QuerySet<A>,
query: u32,
) -> bool {
let (index, epoch, _) = id.unzip();
@@ -50,7 +50,7 @@ impl<B: hal::Backend> QueryResetMap<B> {
pub fn reset_queries(
self,
cmd_buf_raw: &mut B::CommandBuffer,
query_set_storage: &Storage<QuerySet<B>, id::QuerySetId>,
query_set_storage: &Storage<QuerySet<A>, id::QuerySetId>,
backend: wgt::Backend,
) -> Result<(), id::QuerySetId> {
for (query_set_id, (state, epoch)) in self.map.into_iter() {
@@ -161,13 +161,13 @@ pub enum ResolveError {
},
}
impl<B: GfxBackend> QuerySet<B> {
impl<A: HalApi> QuerySet<A> {
fn validate_query(
&self,
query_set_id: id::QuerySetId,
query_type: SimplifiedQueryType,
query_index: u32,
reset_state: Option<&mut QueryResetMap<B>>,
reset_state: Option<&mut QueryResetMap<A>>,
) -> Result<hal::query::Query<'_, B>, QueryUseError> {
// We need to defer our resets because we are in a renderpass, add the usage to the reset map.
if let Some(reset) = reset_state {
@@ -192,7 +192,7 @@ impl<B: GfxBackend> QuerySet<B> {
});
}
let hal_query = hal::query::Query::<B> {
let hal_query = hal::query::Query::<A> {
pool: &self.raw,
id: query_index,
};
@@ -205,7 +205,7 @@ impl<B: GfxBackend> QuerySet<B> {
cmd_buf_raw: &mut B::CommandBuffer,
query_set_id: id::QuerySetId,
query_index: u32,
reset_state: Option<&mut QueryResetMap<B>>,
reset_state: Option<&mut QueryResetMap<A>>,
) -> Result<(), QueryUseError> {
let needs_reset = reset_state.is_none();
let hal_query = self.validate_query(
@@ -231,7 +231,7 @@ impl<B: GfxBackend> QuerySet<B> {
cmd_buf_raw: &mut B::CommandBuffer,
query_set_id: id::QuerySetId,
query_index: u32,
reset_state: Option<&mut QueryResetMap<B>>,
reset_state: Option<&mut QueryResetMap<A>>,
active_query: &mut Option<(id::QuerySetId, u32)>,
) -> Result<(), QueryUseError> {
let needs_reset = reset_state.is_none();
@@ -261,16 +261,16 @@ impl<B: GfxBackend> QuerySet<B> {
}
}
pub(super) fn end_pipeline_statistics_query<B: GfxBackend>(
pub(super) fn end_pipeline_statistics_query<A: HalApi>(
cmd_buf_raw: &mut B::CommandBuffer,
storage: &Storage<QuerySet<B>, id::QuerySetId>,
storage: &Storage<QuerySet<A>, id::QuerySetId>,
active_query: &mut Option<(id::QuerySetId, u32)>,
) -> Result<(), QueryUseError> {
if let Some((query_set_id, query_index)) = active_query.take() {
// We can unwrap here as the validity was validated when the active query was set
let query_set = storage.get(query_set_id).unwrap();
let hal_query = hal::query::Query::<B> {
let hal_query = hal::query::Query::<A> {
pool: &query_set.raw,
id: query_index,
};
@@ -284,13 +284,13 @@ pub(super) fn end_pipeline_statistics_query<B: GfxBackend>(
}
impl<G: GlobalIdentityHandlerFactory> Global<G> {
pub fn command_encoder_write_timestamp<B: GfxBackend>(
pub fn command_encoder_write_timestamp<A: HalApi>(
&self,
command_encoder_id: id::CommandEncoderId,
query_set_id: id::QuerySetId,
query_index: u32,
) -> Result<(), QueryError> {
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token);
@@ -321,7 +321,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
Ok(())
}
pub fn command_encoder_resolve_query_set<B: GfxBackend>(
pub fn command_encoder_resolve_query_set<A: HalApi>(
&self,
command_encoder_id: id::CommandEncoderId,
query_set_id: id::QuerySetId,
@@ -330,7 +330,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
destination: id::BufferId,
destination_offset: BufferAddress,
) -> Result<(), QueryError> {
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token);
+27 -25
View File
@@ -15,7 +15,7 @@ use crate::{
AttachmentData, AttachmentDataVec, Device, FramebufferKey, RenderPassCompatibilityError,
RenderPassContext, RenderPassKey, RenderPassLock, MAX_COLOR_TARGETS, MAX_VERTEX_BUFFERS,
},
hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Storage, Token},
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token},
id,
memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction},
pipeline::PipelineFlags,
@@ -122,14 +122,14 @@ pub struct RenderPassDepthStencilAttachment {
}
impl RenderPassDepthStencilAttachment {
fn is_read_only(&self, aspects: hal::format::Aspects) -> Result<bool, RenderPassErrorInner> {
if aspects.contains(hal::format::Aspects::DEPTH) && !self.depth.read_only {
fn is_read_only(&self, aspects: hal::FormatAspect) -> Result<bool, RenderPassErrorInner> {
if aspects.contains(hal::FormatAspect::DEPTH) && !self.depth.read_only {
return Ok(false);
}
if (self.depth.load_op, self.depth.store_op) != (LoadOp::Load, StoreOp::Store) {
return Err(RenderPassErrorInner::InvalidDepthOps);
}
if aspects.contains(hal::format::Aspects::STENCIL) && !self.stencil.read_only {
if aspects.contains(hal::FormatAspect::STENCIL) && !self.stencil.read_only {
return Ok(false);
}
if (self.stencil.load_op, self.stencil.store_op) != (LoadOp::Load, StoreOp::Store) {
@@ -503,24 +503,26 @@ struct RenderAttachment<'a> {
new_use: TextureUse,
}
struct RenderPassInfo<'a, B: hal::Backend> {
type AttachmentDataVec<T> = ArrayVec<[T; MAX_COLOR_TARGETS + MAX_COLOR_TARGETS + 1]>;
struct RenderPassInfo<'a, A: hal::Api> {
context: RenderPassContext,
trackers: StatefulTrackerSubset,
render_attachments: AttachmentDataVec<RenderAttachment<'a>>,
used_swap_chain: Option<Stored<id::SwapChainId>>,
is_ds_read_only: bool,
extent: wgt::Extent3d,
_phantom: PhantomData<B>,
_phantom: PhantomData<A>,
}
impl<'a, B: GfxBackend> RenderPassInfo<'a, B> {
impl<'a, A: HalApi> RenderPassInfo<'a, A> {
fn start(
raw: &mut B::CommandBuffer,
raw: &mut A::CommandBuffer,
color_attachments: &[RenderPassColorAttachment],
depth_stencil_attachment: Option<&RenderPassDepthStencilAttachment>,
cmd_buf: &mut CommandBuffer<B>,
device: &Device<B>,
view_guard: &'a Storage<TextureView<B>, id::TextureViewId>,
cmd_buf: &mut CommandBuffer<A>,
device: &Device<A>,
view_guard: &'a Storage<TextureView<A>, id::TextureViewId>,
) -> Result<Self, RenderPassErrorInner> {
profiling::scope!("start", "RenderPassInfo");
let sample_count_limit = device.hal_limits.framebuffer_color_sample_counts;
@@ -535,10 +537,10 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> {
let mut attachment_type_name = "";
let mut extent = None;
let mut sample_count = 0;
let mut depth_stencil_aspects = hal::format::Aspects::empty();
let mut depth_stencil_aspects = hal::FormatAspect::empty();
let mut used_swap_chain = None::<Stored<id::SwapChainId>>;
let mut add_view = |view: &TextureView<B>, type_name| {
let mut add_view = |view: &TextureView<A>, type_name| {
if let Some(ex) = extent {
if ex != view.extent {
return Err(RenderPassErrorInner::AttachmentsDimensionMismatch {
@@ -572,7 +574,7 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> {
add_view(view, "depth")?;
depth_stencil_aspects = view.aspects;
if view.aspects.contains(hal::format::Aspects::COLOR) {
if view.aspects.contains(hal::FormatAspect::COLOR) {
return Err(RenderPassErrorInner::InvalidDepthStencilAttachmentFormat(
view.format,
));
@@ -635,7 +637,7 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> {
.map_err(|_| RenderPassErrorInner::InvalidAttachment(at.view))?;
add_view(view, "color")?;
if !view.aspects.contains(hal::format::Aspects::COLOR) {
if !view.aspects.contains(hal::FormatAspect::COLOR) {
return Err(RenderPassErrorInner::InvalidColorAttachmentFormat(
view.format,
));
@@ -656,10 +658,10 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> {
});
let new_layout =
conv::map_texture_state(new_use, hal::format::Aspects::COLOR).1;
conv::map_texture_state(new_use, hal::FormatAspect::COLOR).1;
let old_layout = match previous_use {
Some(usage) => {
conv::map_texture_state(usage, hal::format::Aspects::COLOR).1
conv::map_texture_state(usage, hal::FormatAspect::COLOR).1
}
None => new_layout,
};
@@ -725,10 +727,10 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> {
});
let new_layout =
conv::map_texture_state(new_use, hal::format::Aspects::COLOR).1;
conv::map_texture_state(new_use, hal::FormatAspect::COLOR).1;
let old_layout = match previous_use {
Some(usage) => {
conv::map_texture_state(usage, hal::format::Aspects::COLOR).1
conv::map_texture_state(usage, hal::FormatAspect::COLOR).1
}
None => new_layout,
};
@@ -964,7 +966,7 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> {
Ok(Self {
context,
trackers: StatefulTrackerSubset::new(B::VARIANT),
trackers: StatefulTrackerSubset::new(A::VARIANT),
render_attachments,
used_swap_chain,
is_ds_read_only,
@@ -975,7 +977,7 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> {
fn finish(
mut self,
texture_guard: &Storage<Texture<B>, id::TextureId>,
texture_guard: &Storage<Texture<A>, id::TextureId>,
) -> Result<(StatefulTrackerSubset, Option<Stored<id::SwapChainId>>), RenderPassErrorInner>
{
profiling::scope!("finish", "RenderPassInfo");
@@ -1017,12 +1019,12 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> {
// Common routines between render/compute
impl<G: GlobalIdentityHandlerFactory> Global<G> {
pub fn command_encoder_run_render_pass<B: GfxBackend>(
pub fn command_encoder_run_render_pass<A: HalApi>(
&self,
encoder_id: id::CommandEncoderId,
pass: &RenderPass,
) -> Result<(), RenderPassError> {
self.command_encoder_run_render_pass_impl::<B>(
self.command_encoder_run_render_pass_impl::<A>(
encoder_id,
pass.base.as_ref(),
&pass.color_targets,
@@ -1031,7 +1033,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
}
#[doc(hidden)]
pub fn command_encoder_run_render_pass_impl<B: GfxBackend>(
pub fn command_encoder_run_render_pass_impl<A: HalApi>(
&self,
encoder_id: id::CommandEncoderId,
base: BasePassRef<RenderCommand>,
@@ -1041,7 +1043,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
profiling::scope!("run_render_pass", "CommandEncoder");
let scope = PassErrorScope::Pass(encoder_id);
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (device_guard, mut token) = hub.devices.read(&mut token);
+11 -11
View File
@@ -8,7 +8,7 @@ use crate::{
command::{CommandBuffer, CommandEncoderError},
conv,
device::{all_buffer_stages, all_image_stages},
hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Storage, Token},
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token},
id::{BufferId, CommandEncoderId, TextureId},
memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction},
resource::{BufferUse, Texture, TextureErrorDimension, TextureUse},
@@ -105,10 +105,10 @@ pub enum CopyError {
//TODO: we currently access each texture twice for a transfer,
// once only to get the aspect flags, which is unfortunate.
pub(crate) fn texture_copy_view_to_hal<B: hal::Backend>(
pub(crate) fn texture_copy_view_to_hal<A: hal::Api>(
view: &ImageCopyTexture,
size: &Extent3d,
texture_guard: &Storage<Texture<B>, TextureId>,
texture_guard: &Storage<Texture<A>, TextureId>,
) -> Result<
(
hal::image::SubresourceLayers,
@@ -325,7 +325,7 @@ pub(crate) fn validate_texture_copy_range(
}
impl<G: GlobalIdentityHandlerFactory> Global<G> {
pub fn command_encoder_copy_buffer_to_buffer<B: GfxBackend>(
pub fn command_encoder_copy_buffer_to_buffer<A: HalApi>(
&self,
command_encoder_id: CommandEncoderId,
source: BufferId,
@@ -339,7 +339,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
if source == destination {
return Err(TransferError::SameSourceDestinationBuffer.into());
}
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token);
@@ -465,7 +465,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
Ok(())
}
pub fn command_encoder_copy_buffer_to_texture<B: GfxBackend>(
pub fn command_encoder_copy_buffer_to_texture<A: HalApi>(
&self,
command_encoder_id: CommandEncoderId,
source: &ImageCopyBuffer,
@@ -474,7 +474,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
) -> Result<(), CopyError> {
profiling::scope!("copy_buffer_to_texture", "CommandEncoder");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token);
let cmd_buf = CommandBuffer::get_encoder_mut(&mut *cmd_buf_guard, command_encoder_id)?;
@@ -615,7 +615,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
Ok(())
}
pub fn command_encoder_copy_texture_to_buffer<B: GfxBackend>(
pub fn command_encoder_copy_texture_to_buffer<A: HalApi>(
&self,
command_encoder_id: CommandEncoderId,
source: &ImageCopyTexture,
@@ -624,7 +624,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
) -> Result<(), CopyError> {
profiling::scope!("copy_texture_to_buffer", "CommandEncoder");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token);
let cmd_buf = CommandBuffer::get_encoder_mut(&mut *cmd_buf_guard, command_encoder_id)?;
@@ -768,7 +768,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
Ok(())
}
pub fn command_encoder_copy_texture_to_texture<B: GfxBackend>(
pub fn command_encoder_copy_texture_to_texture<A: HalApi>(
&self,
command_encoder_id: CommandEncoderId,
source: &ImageCopyTexture,
@@ -777,7 +777,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
) -> Result<(), CopyError> {
profiling::scope!("copy_texture_to_texture", "CommandEncoder");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token);
+7 -785
View File
@@ -2,547 +2,7 @@
* 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::{
command::{LoadOp, PassChannel, StoreOp},
pipeline::ColorStateError,
resource, PrivateFeatures,
};
use std::convert::TryInto;
pub fn map_adapter_info(
info: hal::adapter::AdapterInfo,
backend: wgt::Backend,
) -> wgt::AdapterInfo {
use hal::adapter::DeviceType as Dt;
wgt::AdapterInfo {
name: info.name,
vendor: info.vendor,
device: info.device,
device_type: match info.device_type {
Dt::Other => wgt::DeviceType::Other,
Dt::IntegratedGpu => wgt::DeviceType::IntegratedGpu,
Dt::DiscreteGpu => wgt::DeviceType::DiscreteGpu,
Dt::VirtualGpu => wgt::DeviceType::VirtualGpu,
Dt::Cpu => wgt::DeviceType::Cpu,
},
backend,
}
}
pub fn map_buffer_usage(usage: wgt::BufferUsage) -> (hal::buffer::Usage, hal::memory::Properties) {
use hal::buffer::Usage as U;
use hal::memory::Properties as P;
use wgt::BufferUsage as W;
let mut hal_memory = P::empty();
if usage.contains(W::MAP_READ) {
hal_memory |= P::CPU_VISIBLE | P::CPU_CACHED;
}
if usage.contains(W::MAP_WRITE) {
hal_memory |= P::CPU_VISIBLE;
}
let mut hal_usage = U::empty();
if usage.contains(W::COPY_SRC) {
hal_usage |= U::TRANSFER_SRC;
}
if usage.contains(W::COPY_DST) {
hal_usage |= U::TRANSFER_DST;
}
if usage.contains(W::INDEX) {
hal_usage |= U::INDEX;
}
if usage.contains(W::VERTEX) {
hal_usage |= U::VERTEX;
}
if usage.contains(W::UNIFORM) {
hal_usage |= U::UNIFORM;
}
if usage.contains(W::STORAGE) {
hal_usage |= U::STORAGE;
}
if usage.contains(W::INDIRECT) {
hal_usage |= U::INDIRECT;
}
(hal_usage, hal_memory)
}
pub fn map_texture_usage(
usage: wgt::TextureUsage,
aspects: hal::format::Aspects,
) -> hal::image::Usage {
use hal::image::Usage as U;
use wgt::TextureUsage as W;
let mut value = U::empty();
if usage.contains(W::COPY_SRC) {
value |= U::TRANSFER_SRC;
}
if usage.contains(W::COPY_DST) {
value |= U::TRANSFER_DST;
}
if usage.contains(W::SAMPLED) {
value |= U::SAMPLED;
}
if usage.contains(W::STORAGE) {
value |= U::STORAGE;
}
if usage.contains(W::RENDER_ATTACHMENT) {
if aspects.intersects(hal::format::Aspects::DEPTH | hal::format::Aspects::STENCIL) {
value |= U::DEPTH_STENCIL_ATTACHMENT;
} else {
value |= U::COLOR_ATTACHMENT;
}
}
// Note: TextureUsage::Present does not need to be handled explicitly
// TODO: HAL Transient Attachment, HAL Input Attachment
value
}
pub fn map_binding_type(binding: &wgt::BindGroupLayoutEntry) -> hal::pso::DescriptorType {
use hal::pso;
use wgt::BindingType as Bt;
match binding.ty {
Bt::Buffer {
ty,
has_dynamic_offset,
min_binding_size: _,
} => pso::DescriptorType::Buffer {
ty: match ty {
wgt::BufferBindingType::Uniform => pso::BufferDescriptorType::Uniform,
wgt::BufferBindingType::Storage { read_only } => {
pso::BufferDescriptorType::Storage { read_only }
}
},
format: pso::BufferDescriptorFormat::Structured {
dynamic_offset: has_dynamic_offset,
},
},
Bt::Sampler { .. } => pso::DescriptorType::Sampler,
Bt::Texture { .. } => pso::DescriptorType::Image {
ty: pso::ImageDescriptorType::Sampled {
with_sampler: false,
},
},
Bt::StorageTexture { access, .. } => pso::DescriptorType::Image {
ty: pso::ImageDescriptorType::Storage {
read_only: match access {
wgt::StorageTextureAccess::ReadOnly => true,
_ => false,
},
},
},
}
}
pub fn map_shader_stage_flags(shader_stage_flags: wgt::ShaderStage) -> hal::pso::ShaderStageFlags {
use hal::pso::ShaderStageFlags as H;
use wgt::ShaderStage as Ss;
let mut value = H::empty();
if shader_stage_flags.contains(Ss::VERTEX) {
value |= H::VERTEX;
}
if shader_stage_flags.contains(Ss::FRAGMENT) {
value |= H::FRAGMENT;
}
if shader_stage_flags.contains(Ss::COMPUTE) {
value |= H::COMPUTE;
}
value
}
pub fn map_hal_flags_to_shader_stage(
shader_stage_flags: hal::pso::ShaderStageFlags,
) -> wgt::ShaderStage {
use hal::pso::ShaderStageFlags as H;
use wgt::ShaderStage as Ss;
let mut value = Ss::empty();
if shader_stage_flags.contains(H::VERTEX) {
value |= Ss::VERTEX;
}
if shader_stage_flags.contains(H::FRAGMENT) {
value |= Ss::FRAGMENT;
}
if shader_stage_flags.contains(H::COMPUTE) {
value |= Ss::COMPUTE;
}
value
}
pub fn map_extent(extent: &wgt::Extent3d, dim: wgt::TextureDimension) -> hal::image::Extent {
hal::image::Extent {
width: extent.width,
height: extent.height,
depth: match dim {
wgt::TextureDimension::D1 | wgt::TextureDimension::D2 => 1,
wgt::TextureDimension::D3 => extent.depth_or_array_layers,
},
}
}
pub fn map_primitive_topology(primitive_topology: wgt::PrimitiveTopology) -> hal::pso::Primitive {
use hal::pso::Primitive as H;
use wgt::PrimitiveTopology as Pt;
match primitive_topology {
Pt::PointList => H::PointList,
Pt::LineList => H::LineList,
Pt::LineStrip => H::LineStrip,
Pt::TriangleList => H::TriangleList,
Pt::TriangleStrip => H::TriangleStrip,
}
}
pub fn map_color_target_state(
desc: &wgt::ColorTargetState,
) -> Result<hal::pso::ColorBlendDesc, ColorStateError> {
let color_mask = desc.write_mask;
let blend = desc
.blend
.as_ref()
.map(|bs| {
Ok(hal::pso::BlendState {
color: map_blend_component(&bs.color)?,
alpha: map_blend_component(&bs.alpha)?,
})
})
.transpose()?;
Ok(hal::pso::ColorBlendDesc {
mask: map_color_write_flags(color_mask),
blend,
})
}
fn map_color_write_flags(flags: wgt::ColorWrite) -> hal::pso::ColorMask {
use hal::pso::ColorMask as H;
use wgt::ColorWrite as Cw;
let mut value = H::empty();
if flags.contains(Cw::RED) {
value |= H::RED;
}
if flags.contains(Cw::GREEN) {
value |= H::GREEN;
}
if flags.contains(Cw::BLUE) {
value |= H::BLUE;
}
if flags.contains(Cw::ALPHA) {
value |= H::ALPHA;
}
value
}
fn map_blend_component(
component: &wgt::BlendComponent,
) -> Result<hal::pso::BlendOp, ColorStateError> {
use hal::pso::BlendOp as H;
use wgt::BlendOperation as Bo;
Ok(match *component {
wgt::BlendComponent {
operation: Bo::Add,
src_factor,
dst_factor,
} => H::Add {
src: map_blend_factor(src_factor),
dst: map_blend_factor(dst_factor),
},
wgt::BlendComponent {
operation: Bo::Subtract,
src_factor,
dst_factor,
} => H::Sub {
src: map_blend_factor(src_factor),
dst: map_blend_factor(dst_factor),
},
wgt::BlendComponent {
operation: Bo::ReverseSubtract,
src_factor,
dst_factor,
} => H::RevSub {
src: map_blend_factor(src_factor),
dst: map_blend_factor(dst_factor),
},
wgt::BlendComponent {
operation: Bo::Min,
src_factor: wgt::BlendFactor::One,
dst_factor: wgt::BlendFactor::One,
} => H::Min,
wgt::BlendComponent {
operation: Bo::Max,
src_factor: wgt::BlendFactor::One,
dst_factor: wgt::BlendFactor::One,
} => H::Max,
_ => return Err(ColorStateError::InvalidMinMaxBlendFactors(*component)),
})
}
fn map_blend_factor(blend_factor: wgt::BlendFactor) -> hal::pso::Factor {
use hal::pso::Factor as H;
use wgt::BlendFactor as Bf;
match blend_factor {
Bf::Zero => H::Zero,
Bf::One => H::One,
Bf::Src => H::SrcColor,
Bf::OneMinusSrc => H::OneMinusSrcColor,
Bf::SrcAlpha => H::SrcAlpha,
Bf::OneMinusSrcAlpha => H::OneMinusSrcAlpha,
Bf::Dst => H::DstColor,
Bf::OneMinusDst => H::OneMinusDstColor,
Bf::DstAlpha => H::DstAlpha,
Bf::OneMinusDstAlpha => H::OneMinusDstAlpha,
Bf::SrcAlphaSaturated => H::SrcAlphaSaturate,
Bf::Constant => H::ConstColor,
Bf::OneMinusConstant => H::OneMinusConstColor,
}
}
pub fn map_depth_stencil_state(desc: &wgt::DepthStencilState) -> hal::pso::DepthStencilDesc {
hal::pso::DepthStencilDesc {
depth: if desc.is_depth_enabled() {
Some(hal::pso::DepthTest {
fun: map_compare_function(desc.depth_compare),
write: desc.depth_write_enabled,
})
} else {
None
},
depth_bounds: false, // TODO
stencil: if desc.stencil.is_enabled() {
let s = &desc.stencil;
Some(hal::pso::StencilTest {
faces: hal::pso::Sided {
front: map_stencil_face(&s.front),
back: map_stencil_face(&s.back),
},
read_masks: hal::pso::State::Static(hal::pso::Sided::new(s.read_mask)),
write_masks: hal::pso::State::Static(hal::pso::Sided::new(s.write_mask)),
reference_values: if s.needs_ref_value() {
hal::pso::State::Dynamic
} else {
hal::pso::State::Static(hal::pso::Sided::new(0))
},
})
} else {
None
},
}
}
fn map_stencil_face(stencil_state_face_desc: &wgt::StencilFaceState) -> hal::pso::StencilFace {
hal::pso::StencilFace {
fun: map_compare_function(stencil_state_face_desc.compare),
op_fail: map_stencil_operation(stencil_state_face_desc.fail_op),
op_depth_fail: map_stencil_operation(stencil_state_face_desc.depth_fail_op),
op_pass: map_stencil_operation(stencil_state_face_desc.pass_op),
}
}
pub fn map_compare_function(compare_function: wgt::CompareFunction) -> hal::pso::Comparison {
use hal::pso::Comparison as H;
use wgt::CompareFunction as Cf;
match compare_function {
Cf::Never => H::Never,
Cf::Less => H::Less,
Cf::Equal => H::Equal,
Cf::LessEqual => H::LessEqual,
Cf::Greater => H::Greater,
Cf::NotEqual => H::NotEqual,
Cf::GreaterEqual => H::GreaterEqual,
Cf::Always => H::Always,
}
}
fn map_stencil_operation(stencil_operation: wgt::StencilOperation) -> hal::pso::StencilOp {
use hal::pso::StencilOp as H;
use wgt::StencilOperation as So;
match stencil_operation {
So::Keep => H::Keep,
So::Zero => H::Zero,
So::Replace => H::Replace,
So::Invert => H::Invert,
So::IncrementClamp => H::IncrementClamp,
So::DecrementClamp => H::DecrementClamp,
So::IncrementWrap => H::IncrementWrap,
So::DecrementWrap => H::DecrementWrap,
}
}
pub(crate) fn map_texture_format(
texture_format: wgt::TextureFormat,
private_features: PrivateFeatures,
) -> hal::format::Format {
use hal::format::Format as H;
use wgt::TextureFormat as Tf;
match texture_format {
// Normal 8 bit formats
Tf::R8Unorm => H::R8Unorm,
Tf::R8Snorm => H::R8Snorm,
Tf::R8Uint => H::R8Uint,
Tf::R8Sint => H::R8Sint,
// Normal 16 bit formats
Tf::R16Uint => H::R16Uint,
Tf::R16Sint => H::R16Sint,
Tf::R16Float => H::R16Sfloat,
Tf::Rg8Unorm => H::Rg8Unorm,
Tf::Rg8Snorm => H::Rg8Snorm,
Tf::Rg8Uint => H::Rg8Uint,
Tf::Rg8Sint => H::Rg8Sint,
// Normal 32 bit formats
Tf::R32Uint => H::R32Uint,
Tf::R32Sint => H::R32Sint,
Tf::R32Float => H::R32Sfloat,
Tf::Rg16Uint => H::Rg16Uint,
Tf::Rg16Sint => H::Rg16Sint,
Tf::Rg16Float => H::Rg16Sfloat,
Tf::Rgba8Unorm => H::Rgba8Unorm,
Tf::Rgba8UnormSrgb => H::Rgba8Srgb,
Tf::Rgba8Snorm => H::Rgba8Snorm,
Tf::Rgba8Uint => H::Rgba8Uint,
Tf::Rgba8Sint => H::Rgba8Sint,
Tf::Bgra8Unorm => H::Bgra8Unorm,
Tf::Bgra8UnormSrgb => H::Bgra8Srgb,
// Packed 32 bit formats
Tf::Rgb10a2Unorm => H::A2r10g10b10Unorm,
Tf::Rg11b10Float => H::B10g11r11Ufloat,
// Normal 64 bit formats
Tf::Rg32Uint => H::Rg32Uint,
Tf::Rg32Sint => H::Rg32Sint,
Tf::Rg32Float => H::Rg32Sfloat,
Tf::Rgba16Uint => H::Rgba16Uint,
Tf::Rgba16Sint => H::Rgba16Sint,
Tf::Rgba16Float => H::Rgba16Sfloat,
// Normal 128 bit formats
Tf::Rgba32Uint => H::Rgba32Uint,
Tf::Rgba32Sint => H::Rgba32Sint,
Tf::Rgba32Float => H::Rgba32Sfloat,
// Depth and stencil formats
Tf::Depth32Float => H::D32Sfloat,
Tf::Depth24Plus => {
if private_features.texture_d24 {
H::X8D24Unorm
} else {
H::D32Sfloat
}
}
Tf::Depth24PlusStencil8 => {
if private_features.texture_d24_s8 {
H::D24UnormS8Uint
} else {
H::D32SfloatS8Uint
}
}
// BCn compressed formats
Tf::Bc1RgbaUnorm => H::Bc1RgbaUnorm,
Tf::Bc1RgbaUnormSrgb => H::Bc1RgbaSrgb,
Tf::Bc2RgbaUnorm => H::Bc2Unorm,
Tf::Bc2RgbaUnormSrgb => H::Bc2Srgb,
Tf::Bc3RgbaUnorm => H::Bc3Unorm,
Tf::Bc3RgbaUnormSrgb => H::Bc3Srgb,
Tf::Bc4RUnorm => H::Bc4Unorm,
Tf::Bc4RSnorm => H::Bc4Snorm,
Tf::Bc5RgUnorm => H::Bc5Unorm,
Tf::Bc5RgSnorm => H::Bc5Snorm,
Tf::Bc6hRgbSfloat => H::Bc6hSfloat,
Tf::Bc6hRgbUfloat => H::Bc6hUfloat,
Tf::Bc7RgbaUnorm => H::Bc7Unorm,
Tf::Bc7RgbaUnormSrgb => H::Bc7Srgb,
// ETC compressed formats
Tf::Etc2RgbUnorm => H::Etc2R8g8b8Unorm,
Tf::Etc2RgbUnormSrgb => H::Etc2R8g8b8Srgb,
Tf::Etc2RgbA1Unorm => H::Etc2R8g8b8a1Unorm,
Tf::Etc2RgbA1UnormSrgb => H::Etc2R8g8b8a1Srgb,
Tf::Etc2RgbA8Unorm => H::Etc2R8g8b8a8Unorm,
Tf::Etc2RgbA8UnormSrgb => H::Etc2R8g8b8a8Unorm,
Tf::EacRUnorm => H::EacR11Unorm,
Tf::EacRSnorm => H::EacR11Snorm,
Tf::EtcRgUnorm => H::EacR11g11Unorm,
Tf::EtcRgSnorm => H::EacR11g11Snorm,
// ASTC compressed formats
Tf::Astc4x4RgbaUnorm => H::Astc4x4Srgb,
Tf::Astc4x4RgbaUnormSrgb => H::Astc4x4Srgb,
Tf::Astc5x4RgbaUnorm => H::Astc5x4Unorm,
Tf::Astc5x4RgbaUnormSrgb => H::Astc5x4Srgb,
Tf::Astc5x5RgbaUnorm => H::Astc5x5Unorm,
Tf::Astc5x5RgbaUnormSrgb => H::Astc5x5Srgb,
Tf::Astc6x5RgbaUnorm => H::Astc6x5Unorm,
Tf::Astc6x5RgbaUnormSrgb => H::Astc6x5Srgb,
Tf::Astc6x6RgbaUnorm => H::Astc6x6Unorm,
Tf::Astc6x6RgbaUnormSrgb => H::Astc6x6Srgb,
Tf::Astc8x5RgbaUnorm => H::Astc8x5Unorm,
Tf::Astc8x5RgbaUnormSrgb => H::Astc8x5Srgb,
Tf::Astc8x6RgbaUnorm => H::Astc8x6Unorm,
Tf::Astc8x6RgbaUnormSrgb => H::Astc8x6Srgb,
Tf::Astc10x5RgbaUnorm => H::Astc10x5Unorm,
Tf::Astc10x5RgbaUnormSrgb => H::Astc10x5Srgb,
Tf::Astc10x6RgbaUnorm => H::Astc10x6Unorm,
Tf::Astc10x6RgbaUnormSrgb => H::Astc10x6Srgb,
Tf::Astc8x8RgbaUnorm => H::Astc8x8Unorm,
Tf::Astc8x8RgbaUnormSrgb => H::Astc8x8Srgb,
Tf::Astc10x8RgbaUnorm => H::Astc10x8Unorm,
Tf::Astc10x8RgbaUnormSrgb => H::Astc10x8Srgb,
Tf::Astc10x10RgbaUnorm => H::Astc10x10Unorm,
Tf::Astc10x10RgbaUnormSrgb => H::Astc10x10Srgb,
Tf::Astc12x10RgbaUnorm => H::Astc12x10Unorm,
Tf::Astc12x10RgbaUnormSrgb => H::Astc12x10Srgb,
Tf::Astc12x12RgbaUnorm => H::Astc12x12Unorm,
Tf::Astc12x12RgbaUnormSrgb => H::Astc12x12Srgb,
}
}
pub fn map_vertex_format(vertex_format: wgt::VertexFormat) -> hal::format::Format {
use hal::format::Format as H;
use wgt::VertexFormat as Vf;
match vertex_format {
Vf::Uint8x2 => H::Rg8Uint,
Vf::Uint8x4 => H::Rgba8Uint,
Vf::Sint8x2 => H::Rg8Sint,
Vf::Sint8x4 => H::Rgba8Sint,
Vf::Unorm8x2 => H::Rg8Unorm,
Vf::Unorm8x4 => H::Rgba8Unorm,
Vf::Snorm8x2 => H::Rg8Snorm,
Vf::Snorm8x4 => H::Rgba8Snorm,
Vf::Uint16x2 => H::Rg16Uint,
Vf::Uint16x4 => H::Rgba16Uint,
Vf::Sint16x2 => H::Rg16Sint,
Vf::Sint16x4 => H::Rgba16Sint,
Vf::Unorm16x2 => H::Rg16Unorm,
Vf::Unorm16x4 => H::Rgba16Unorm,
Vf::Snorm16x2 => H::Rg16Snorm,
Vf::Snorm16x4 => H::Rgba16Snorm,
Vf::Float16x2 => H::Rg16Sfloat,
Vf::Float16x4 => H::Rgba16Sfloat,
Vf::Float32 => H::R32Sfloat,
Vf::Float32x2 => H::Rg32Sfloat,
Vf::Float32x3 => H::Rgb32Sfloat,
Vf::Float32x4 => H::Rgba32Sfloat,
Vf::Uint32 => H::R32Uint,
Vf::Uint32x2 => H::Rg32Uint,
Vf::Uint32x3 => H::Rgb32Uint,
Vf::Uint32x4 => H::Rgba32Uint,
Vf::Sint32 => H::R32Sint,
Vf::Sint32x2 => H::Rg32Sint,
Vf::Sint32x3 => H::Rgb32Sint,
Vf::Sint32x4 => H::Rgba32Sint,
Vf::Float64 => H::R64Sfloat,
Vf::Float64x2 => H::Rg64Sfloat,
Vf::Float64x3 => H::Rgb64Sfloat,
Vf::Float64x4 => H::Rgba64Sfloat,
}
}
use crate::resource;
pub fn is_power_of_two(val: u32) -> bool {
val != 0 && (val & (val - 1)) == 0
@@ -564,7 +24,7 @@ pub fn is_valid_copy_dst_texture_format(format: wgt::TextureFormat) -> bool {
}
}
pub fn map_texture_dimension_size(
pub fn check_texture_dimension_size(
dimension: wgt::TextureDimension,
wgt::Extent3d {
width,
@@ -573,15 +33,14 @@ pub fn map_texture_dimension_size(
}: wgt::Extent3d,
sample_size: u32,
limits: &wgt::Limits,
) -> Result<hal::image::Kind, resource::TextureDimensionError> {
use hal::image::Kind as H;
) -> Result<(), resource::TextureDimensionError> {
use resource::{TextureDimensionError as Tde, TextureErrorDimension as Ted};
use std::convert::TryInto;
use wgt::TextureDimension::*;
let layers = depth_or_array_layers.try_into().unwrap_or(!0);
let (kind, extent_limits, sample_limit) = match dimension {
let (extent_limits, sample_limit) = match dimension {
D1 => (
H::D1(width, layers),
[
limits.max_texture_dimension_1d,
1,
@@ -590,7 +49,6 @@ pub fn map_texture_dimension_size(
1,
),
D2 => (
H::D2(width, height, layers, sample_size as u8),
[
limits.max_texture_dimension_2d,
limits.max_texture_dimension_2d,
@@ -599,7 +57,6 @@ pub fn map_texture_dimension_size(
32,
),
D3 => (
H::D3(width, height, depth_or_array_layers),
[
limits.max_texture_dimension_3d,
limits.max_texture_dimension_3d,
@@ -625,165 +82,10 @@ pub fn map_texture_dimension_size(
return Err(Tde::InvalidSampleCount(sample_size));
}
Ok(kind)
Ok(())
}
pub fn map_texture_view_dimension(dimension: wgt::TextureViewDimension) -> hal::image::ViewKind {
use hal::image::ViewKind as H;
use wgt::TextureViewDimension::*;
match dimension {
D1 => H::D1,
D2 => H::D2,
D2Array => H::D2Array,
Cube => H::Cube,
CubeArray => H::CubeArray,
D3 => H::D3,
}
}
pub(crate) fn map_buffer_state(usage: resource::BufferUse) -> hal::buffer::State {
use crate::resource::BufferUse as W;
use hal::buffer::Access as A;
let mut access = A::empty();
if usage.contains(W::MAP_READ) {
access |= A::HOST_READ;
}
if usage.contains(W::MAP_WRITE) {
access |= A::HOST_WRITE;
}
if usage.contains(W::COPY_SRC) {
access |= A::TRANSFER_READ;
}
if usage.contains(W::COPY_DST) {
access |= A::TRANSFER_WRITE;
}
if usage.contains(W::INDEX) {
access |= A::INDEX_BUFFER_READ;
}
if usage.contains(W::VERTEX) {
access |= A::VERTEX_BUFFER_READ;
}
if usage.contains(W::UNIFORM) {
access |= A::UNIFORM_READ | A::SHADER_READ;
}
if usage.contains(W::STORAGE_LOAD) {
access |= A::SHADER_READ;
}
if usage.contains(W::STORAGE_STORE) {
access |= A::SHADER_READ | A::SHADER_WRITE;
}
if usage.contains(W::INDIRECT) {
access |= A::INDIRECT_COMMAND_READ;
}
access
}
pub(crate) fn map_texture_state(
usage: resource::TextureUse,
aspects: hal::format::Aspects,
) -> hal::image::State {
use crate::resource::TextureUse as W;
use hal::image::{Access as A, Layout as L};
let is_color = aspects.contains(hal::format::Aspects::COLOR);
let layout = match usage {
W::UNINITIALIZED => return (A::empty(), L::Undefined),
W::COPY_SRC => L::TransferSrcOptimal,
W::COPY_DST => L::TransferDstOptimal,
W::SAMPLED if is_color => L::ShaderReadOnlyOptimal,
W::ATTACHMENT_READ | W::ATTACHMENT_WRITE if is_color => L::ColorAttachmentOptimal,
_ if is_color => L::General,
W::ATTACHMENT_WRITE => L::DepthStencilAttachmentOptimal,
_ => L::DepthStencilReadOnlyOptimal,
};
let mut access = A::empty();
if usage.contains(W::COPY_SRC) {
access |= A::TRANSFER_READ;
}
if usage.contains(W::COPY_DST) {
access |= A::TRANSFER_WRITE;
}
if usage.contains(W::SAMPLED) {
access |= A::SHADER_READ;
}
if usage.contains(W::ATTACHMENT_READ) {
access |= if is_color {
A::COLOR_ATTACHMENT_READ
} else {
A::DEPTH_STENCIL_ATTACHMENT_READ
};
}
if usage.contains(W::ATTACHMENT_WRITE) {
access |= if is_color {
A::COLOR_ATTACHMENT_WRITE
} else {
A::DEPTH_STENCIL_ATTACHMENT_WRITE
};
}
if usage.contains(W::STORAGE_LOAD) {
access |= A::SHADER_READ;
}
if usage.contains(W::STORAGE_STORE) {
access |= A::SHADER_WRITE;
}
(access, layout)
}
pub fn map_query_type(ty: &wgt::QueryType) -> (hal::query::Type, u32) {
match *ty {
wgt::QueryType::PipelineStatistics(pipeline_statistics) => {
let mut ps = hal::query::PipelineStatistic::empty();
ps.set(
hal::query::PipelineStatistic::VERTEX_SHADER_INVOCATIONS,
pipeline_statistics
.contains(wgt::PipelineStatisticsTypes::VERTEX_SHADER_INVOCATIONS),
);
ps.set(
hal::query::PipelineStatistic::CLIPPING_INVOCATIONS,
pipeline_statistics.contains(wgt::PipelineStatisticsTypes::CLIPPER_INVOCATIONS),
);
ps.set(
hal::query::PipelineStatistic::CLIPPING_PRIMITIVES,
pipeline_statistics.contains(wgt::PipelineStatisticsTypes::CLIPPER_PRIMITIVES_OUT),
);
ps.set(
hal::query::PipelineStatistic::FRAGMENT_SHADER_INVOCATIONS,
pipeline_statistics
.contains(wgt::PipelineStatisticsTypes::FRAGMENT_SHADER_INVOCATIONS),
);
ps.set(
hal::query::PipelineStatistic::COMPUTE_SHADER_INVOCATIONS,
pipeline_statistics
.contains(wgt::PipelineStatisticsTypes::COMPUTE_SHADER_INVOCATIONS),
);
(
hal::query::Type::PipelineStatistics(ps),
pipeline_statistics.bits().count_ones(),
)
}
wgt::QueryType::Timestamp => (hal::query::Type::Timestamp, 1),
}
}
pub fn map_load_store_ops<V>(channel: &PassChannel<V>) -> hal::pass::AttachmentOps {
hal::pass::AttachmentOps {
load: match channel.load_op {
LoadOp::Clear => hal::pass::AttachmentLoadOp::Clear,
LoadOp::Load => hal::pass::AttachmentLoadOp::Load,
},
store: match channel.store_op {
StoreOp::Clear => hal::pass::AttachmentStoreOp::DontCare, //TODO!
StoreOp::Store => hal::pass::AttachmentStoreOp::Store,
},
}
}
pub fn map_color_f32(color: &wgt::Color) -> hal::pso::ColorValue {
pub fn map_color_f32(color: &wgt::Color) -> [f32; 4] {
[
color.r as f32,
color.g as f32,
@@ -808,86 +110,6 @@ pub fn map_color_u32(color: &wgt::Color) -> [u32; 4] {
]
}
pub fn map_filter(filter: wgt::FilterMode) -> hal::image::Filter {
match filter {
wgt::FilterMode::Nearest => hal::image::Filter::Nearest,
wgt::FilterMode::Linear => hal::image::Filter::Linear,
}
}
pub fn map_wrap(address: wgt::AddressMode) -> hal::image::WrapMode {
use hal::image::WrapMode as W;
use wgt::AddressMode as Am;
match address {
Am::ClampToEdge => W::Clamp,
Am::Repeat => W::Tile,
Am::MirrorRepeat => W::Mirror,
Am::ClampToBorder => W::Border,
}
}
pub fn map_primitive_state_to_input_assembler(
desc: &wgt::PrimitiveState,
) -> hal::pso::InputAssemblerDesc {
hal::pso::InputAssemblerDesc {
primitive: map_primitive_topology(desc.topology),
with_adjacency: false,
restart_index: desc.strip_index_format.map(map_index_format),
}
}
pub fn map_primitive_state_to_rasterizer(
desc: &wgt::PrimitiveState,
depth_stencil: Option<&wgt::DepthStencilState>,
) -> hal::pso::Rasterizer {
use hal::pso;
let depth_bias = match depth_stencil {
Some(dsd) if dsd.bias.is_enabled() => Some(pso::State::Static(pso::DepthBias {
const_factor: dsd.bias.constant as f32,
slope_factor: dsd.bias.slope_scale,
clamp: dsd.bias.clamp,
})),
_ => None,
};
pso::Rasterizer {
depth_clamping: desc.clamp_depth,
polygon_mode: match desc.polygon_mode {
wgt::PolygonMode::Fill => pso::PolygonMode::Fill,
wgt::PolygonMode::Line => pso::PolygonMode::Line,
wgt::PolygonMode::Point => pso::PolygonMode::Point,
},
cull_face: match desc.cull_mode {
None => pso::Face::empty(),
Some(wgt::Face::Front) => pso::Face::FRONT,
Some(wgt::Face::Back) => pso::Face::BACK,
},
front_face: match desc.front_face {
wgt::FrontFace::Ccw => pso::FrontFace::CounterClockwise,
wgt::FrontFace::Cw => pso::FrontFace::Clockwise,
},
depth_bias,
conservative: desc.conservative,
line_width: pso::State::Static(1.0),
}
}
pub fn map_multisample_state(desc: &wgt::MultisampleState) -> hal::pso::Multisampling {
hal::pso::Multisampling {
rasterization_samples: desc.count as _,
sample_shading: None,
sample_mask: desc.mask,
alpha_coverage: desc.alpha_to_coverage_enabled,
alpha_to_one: false,
}
}
pub fn map_index_format(index_format: wgt::IndexFormat) -> hal::IndexType {
match index_format {
wgt::IndexFormat::Uint16 => hal::IndexType::U16,
wgt::IndexFormat::Uint32 => hal::IndexType::U32,
}
}
/// Take `value` and round it up to the nearest alignment `alignment`.
///
/// ```text
+15 -15
View File
@@ -7,12 +7,12 @@ use hal::device::Device as _;
use std::{borrow::Cow, iter, ptr::NonNull};
#[derive(Debug)]
pub struct MemoryAllocator<B: hal::Backend>(gpu_alloc::GpuAllocator<B::Memory>);
pub struct MemoryAllocator<A: hal::Api>(gpu_alloc::GpuAllocator<B::Memory>);
#[derive(Debug)]
pub struct MemoryBlock<B: hal::Backend>(gpu_alloc::MemoryBlock<B::Memory>);
struct MemoryDevice<'a, B: hal::Backend>(&'a B::Device);
pub struct MemoryBlock<A: hal::Api>(gpu_alloc::MemoryBlock<B::Memory>);
struct MemoryDevice<'a, A: hal::Api>(&'a B::Device);
impl<B: hal::Backend> MemoryAllocator<B> {
impl<A: hal::Api> MemoryAllocator<A> {
pub fn new(mem_props: hal::adapter::MemoryProperties, limits: hal::Limits) -> Self {
let mem_config = gpu_alloc::Config {
dedicated_threshold: 32 << 20,
@@ -60,7 +60,7 @@ impl<B: hal::Backend> MemoryAllocator<B> {
device: &B::Device,
requirements: hal::memory::Requirements,
usage: gpu_alloc::UsageFlags,
) -> Result<MemoryBlock<B>, DeviceError> {
) -> Result<MemoryBlock<A>, DeviceError> {
assert!(requirements.alignment.is_power_of_two());
let request = gpu_alloc::Request {
size: requirements.size,
@@ -69,7 +69,7 @@ impl<B: hal::Backend> MemoryAllocator<B> {
usage,
};
unsafe { self.0.alloc(&MemoryDevice::<B>(device), request) }
unsafe { self.0.alloc(&MemoryDevice::<A>(device), request) }
.map(MemoryBlock)
.map_err(|err| match err {
gpu_alloc::AllocationError::OutOfHostMemory
@@ -78,16 +78,16 @@ impl<B: hal::Backend> MemoryAllocator<B> {
})
}
pub fn free(&mut self, device: &B::Device, block: MemoryBlock<B>) {
unsafe { self.0.dealloc(&MemoryDevice::<B>(device), block.0) }
pub fn free(&mut self, device: &B::Device, block: MemoryBlock<A>) {
unsafe { self.0.dealloc(&MemoryDevice::<A>(device), block.0) }
}
pub fn clear(&mut self, device: &B::Device) {
unsafe { self.0.cleanup(&MemoryDevice::<B>(device)) }
unsafe { self.0.cleanup(&MemoryDevice::<A>(device)) }
}
}
impl<B: hal::Backend> MemoryBlock<B> {
impl<A: hal::Api> MemoryBlock<A> {
pub fn bind_buffer(
&self,
device: &B::Device,
@@ -125,13 +125,13 @@ impl<B: hal::Backend> MemoryBlock<B> {
let offset = inner_offset;
unsafe {
self.0
.map(&MemoryDevice::<B>(device), offset, size as usize)
.map(&MemoryDevice::<A>(device), offset, size as usize)
.map_err(DeviceError::from)
}
}
pub fn unmap(&mut self, device: &B::Device) {
unsafe { self.0.unmap(&MemoryDevice::<B>(device)) };
unsafe { self.0.unmap(&MemoryDevice::<A>(device)) };
}
pub fn write_bytes(
@@ -144,7 +144,7 @@ impl<B: hal::Backend> MemoryBlock<B> {
let offset = inner_offset;
unsafe {
self.0
.write_bytes(&MemoryDevice::<B>(device), offset, data)
.write_bytes(&MemoryDevice::<A>(device), offset, data)
.map_err(DeviceError::from)
}
}
@@ -159,7 +159,7 @@ impl<B: hal::Backend> MemoryBlock<B> {
let offset = inner_offset;
unsafe {
self.0
.read_bytes(&MemoryDevice::<B>(device), offset, data)
.read_bytes(&MemoryDevice::<A>(device), offset, data)
.map_err(DeviceError::from)
}
}
@@ -206,7 +206,7 @@ impl<B: hal::Backend> MemoryBlock<B> {
}
}
impl<B: hal::Backend> gpu_alloc::MemoryDevice<B::Memory> for MemoryDevice<'_, B> {
impl<A: hal::Api> gpu_alloc::MemoryDevice<B::Memory> for MemoryDevice<'_, B> {
unsafe fn allocate_memory(
&self,
size: u64,
+10 -10
View File
@@ -7,15 +7,15 @@ use arrayvec::ArrayVec;
pub use gpu_descriptor::DescriptorTotalCount;
pub type DescriptorSet<B> = gpu_descriptor::DescriptorSet<<B as hal::Backend>::DescriptorSet>;
pub type DescriptorSet<A> = gpu_descriptor::DescriptorSet<<B as hal::Backend>::DescriptorSet>;
#[derive(Debug)]
pub struct DescriptorAllocator<B: hal::Backend>(
pub struct DescriptorAllocator<A: hal::Api>(
gpu_descriptor::DescriptorAllocator<B::DescriptorPool, B::DescriptorSet>,
);
struct DescriptorDevice<'a, B: hal::Backend>(&'a B::Device);
struct DescriptorDevice<'a, A: hal::Api>(&'a B::Device);
impl<B: hal::Backend> DescriptorAllocator<B> {
impl<A: hal::Api> DescriptorAllocator<A> {
pub fn new() -> Self {
DescriptorAllocator(gpu_descriptor::DescriptorAllocator::new(0))
}
@@ -26,10 +26,10 @@ impl<B: hal::Backend> DescriptorAllocator<B> {
layout: &B::DescriptorSetLayout,
layout_descriptor_count: &DescriptorTotalCount,
count: u32,
) -> Result<Vec<DescriptorSet<B>>, DeviceError> {
) -> Result<Vec<DescriptorSet<A>>, DeviceError> {
unsafe {
self.0.allocate(
&DescriptorDevice::<B>(device),
&DescriptorDevice::<A>(device),
layout,
gpu_descriptor::DescriptorSetLayoutCreateFlags::empty(),
layout_descriptor_count,
@@ -42,16 +42,16 @@ impl<B: hal::Backend> DescriptorAllocator<B> {
})
}
pub fn free(&mut self, device: &B::Device, sets: impl IntoIterator<Item = DescriptorSet<B>>) {
unsafe { self.0.free(&DescriptorDevice::<B>(device), sets) }
pub fn free(&mut self, device: &B::Device, sets: impl IntoIterator<Item = DescriptorSet<A>>) {
unsafe { self.0.free(&DescriptorDevice::<A>(device), sets) }
}
pub fn cleanup(&mut self, device: &B::Device) {
unsafe { self.0.cleanup(&DescriptorDevice::<B>(device)) }
unsafe { self.0.cleanup(&DescriptorDevice::<A>(device)) }
}
}
impl<B: hal::Backend>
impl<A: hal::Api>
gpu_descriptor::DescriptorDevice<B::DescriptorSetLayout, B::DescriptorPool, B::DescriptorSet>
for DescriptorDevice<'_, B>
{
+26 -26
View File
@@ -11,7 +11,7 @@ use crate::{
queue::TempResource,
DeviceError,
},
hub::{GfxBackend, GlobalIdentityHandlerFactory, Hub, Token},
hub::{GlobalIdentityHandlerFactory, HalApi, Hub, Token},
id, resource,
track::TrackerSet,
RefCount, Stored, SubmissionIndex,
@@ -90,15 +90,15 @@ impl SuspectedResources {
/// A struct that keeps lists of resources that are no longer needed.
#[derive(Debug)]
struct NonReferencedResources<B: hal::Backend> {
buffers: Vec<(B::Buffer, alloc::MemoryBlock<B>)>,
images: Vec<(B::Image, alloc::MemoryBlock<B>)>,
struct NonReferencedResources<A: hal::Api> {
buffers: Vec<(B::Buffer, alloc::MemoryBlock<A>)>,
images: Vec<(B::Image, alloc::MemoryBlock<A>)>,
// Note: we keep the associated ID here in order to be able to check
// at any point what resources are used in a submission.
image_views: Vec<(id::Valid<id::TextureViewId>, B::ImageView)>,
samplers: Vec<B::Sampler>,
framebuffers: Vec<B::Framebuffer>,
desc_sets: Vec<DescriptorSet<B>>,
desc_sets: Vec<DescriptorSet<A>>,
compute_pipes: Vec<B::ComputePipeline>,
graphics_pipes: Vec<B::GraphicsPipeline>,
descriptor_set_layouts: Vec<B::DescriptorSetLayout>,
@@ -106,7 +106,7 @@ struct NonReferencedResources<B: hal::Backend> {
query_sets: Vec<B::QueryPool>,
}
impl<B: hal::Backend> NonReferencedResources<B> {
impl<A: hal::Api> NonReferencedResources<A> {
fn new() -> Self {
Self {
buffers: Vec::new(),
@@ -140,8 +140,8 @@ impl<B: hal::Backend> NonReferencedResources<B> {
unsafe fn clean(
&mut self,
device: &B::Device,
memory_allocator_mutex: &Mutex<alloc::MemoryAllocator<B>>,
descriptor_allocator_mutex: &Mutex<DescriptorAllocator<B>>,
memory_allocator_mutex: &Mutex<alloc::MemoryAllocator<A>>,
descriptor_allocator_mutex: &Mutex<DescriptorAllocator<A>>,
) {
if !self.buffers.is_empty() || !self.images.is_empty() {
let mut allocator = memory_allocator_mutex.lock();
@@ -192,10 +192,10 @@ impl<B: hal::Backend> NonReferencedResources<B> {
}
#[derive(Debug)]
struct ActiveSubmission<B: hal::Backend> {
struct ActiveSubmission<A: hal::Api> {
index: SubmissionIndex,
fence: B::Fence,
last_resources: NonReferencedResources<B>,
last_resources: NonReferencedResources<A>,
mapped: Vec<id::Valid<id::BufferId>>,
}
@@ -216,7 +216,7 @@ pub enum WaitIdleError {
/// 3. When `ActiveSubmission` is retired, the mapped buffers associated with it are moved to `ready_to_map` vector.
/// 4. Finally, `handle_mapping` issues all the callbacks.
#[derive(Debug)]
pub(super) struct LifetimeTracker<B: hal::Backend> {
pub(super) struct LifetimeTracker<A: hal::Api> {
/// Resources that the user has requested be mapped, but are still in use.
mapped: Vec<Stored<id::BufferId>>,
/// Buffers can be used in a submission that is yet to be made, by the
@@ -229,14 +229,14 @@ pub(super) struct LifetimeTracker<B: hal::Backend> {
/// Resources that are not referenced any more but still used by GPU.
/// Grouped by submissions associated with a fence and a submission index.
/// The active submissions have to be stored in FIFO order: oldest come first.
active: Vec<ActiveSubmission<B>>,
active: Vec<ActiveSubmission<A>>,
/// Resources that are neither referenced or used, just life_tracker
/// actual deletion.
free_resources: NonReferencedResources<B>,
free_resources: NonReferencedResources<A>,
ready_to_map: Vec<id::Valid<id::BufferId>>,
}
impl<B: hal::Backend> LifetimeTracker<B> {
impl<A: hal::Api> LifetimeTracker<A> {
pub fn new() -> Self {
Self {
mapped: Vec::new(),
@@ -254,7 +254,7 @@ impl<B: hal::Backend> LifetimeTracker<B> {
index: SubmissionIndex,
fence: B::Fence,
new_suspects: &SuspectedResources,
temp_resources: impl Iterator<Item = (TempResource<B>, alloc::MemoryBlock<B>)>,
temp_resources: impl Iterator<Item = (TempResource<A>, alloc::MemoryBlock<A>)>,
) {
let mut last_resources = NonReferencedResources::new();
for (res, memory) in temp_resources {
@@ -347,8 +347,8 @@ impl<B: hal::Backend> LifetimeTracker<B> {
pub fn cleanup(
&mut self,
device: &B::Device,
memory_allocator_mutex: &Mutex<alloc::MemoryAllocator<B>>,
descriptor_allocator_mutex: &Mutex<DescriptorAllocator<B>>,
memory_allocator_mutex: &Mutex<alloc::MemoryAllocator<A>>,
descriptor_allocator_mutex: &Mutex<DescriptorAllocator<A>>,
) {
profiling::scope!("cleanup");
unsafe {
@@ -360,8 +360,8 @@ impl<B: hal::Backend> LifetimeTracker<B> {
pub fn schedule_resource_destruction(
&mut self,
temp_resource: TempResource<B>,
memory: alloc::MemoryBlock<B>,
temp_resource: TempResource<A>,
memory: alloc::MemoryBlock<A>,
last_submit_index: SubmissionIndex,
) {
let resources = self
@@ -376,13 +376,13 @@ impl<B: hal::Backend> LifetimeTracker<B> {
}
}
impl<B: GfxBackend> LifetimeTracker<B> {
impl<A: HalApi> LifetimeTracker<A> {
pub(super) fn triage_suspected<G: GlobalIdentityHandlerFactory>(
&mut self,
hub: &Hub<B, G>,
hub: &Hub<A, G>,
trackers: &Mutex<TrackerSet>,
#[cfg(feature = "trace")] trace: Option<&Mutex<trace::Trace>>,
token: &mut Token<super::Device<B>>,
token: &mut Token<super::Device<A>>,
) {
profiling::scope!("triage_suspected");
@@ -662,8 +662,8 @@ impl<B: GfxBackend> LifetimeTracker<B> {
pub(super) fn triage_mapped<G: GlobalIdentityHandlerFactory>(
&mut self,
hub: &Hub<B, G>,
token: &mut Token<super::Device<B>>,
hub: &Hub<A, G>,
token: &mut Token<super::Device<A>>,
) {
if self.mapped.is_empty() {
return;
@@ -692,10 +692,10 @@ impl<B: GfxBackend> LifetimeTracker<B> {
pub(super) fn handle_mapping<G: GlobalIdentityHandlerFactory>(
&mut self,
hub: &Hub<B, G>,
hub: &Hub<A, G>,
raw: &B::Device,
trackers: &Mutex<TrackerSet>,
token: &mut Token<super::Device<B>>,
token: &mut Token<super::Device<A>>,
) -> Vec<super::BufferMapPendingCallback> {
if self.ready_to_map.is_empty() {
return Vec::new();
File diff suppressed because it is too large. Load diff
+26 -26
View File
@@ -11,7 +11,7 @@ use crate::{
},
conv,
device::{alloc, DeviceError, WaitIdleError},
hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Storage, Token},
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token},
id,
memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction},
resource::{Buffer, BufferAccessError, BufferMapState, BufferUse, TextureUse},
@@ -23,27 +23,27 @@ use smallvec::SmallVec;
use std::{iter, ops::Range, ptr};
use thiserror::Error;
struct StagingData<B: hal::Backend> {
struct StagingData<A: hal::Api> {
buffer: B::Buffer,
memory: alloc::MemoryBlock<B>,
memory: alloc::MemoryBlock<A>,
cmdbuf: B::CommandBuffer,
}
#[derive(Debug)]
pub enum TempResource<B: hal::Backend> {
pub enum TempResource<A: hal::Api> {
Buffer(B::Buffer),
Image(B::Image),
}
#[derive(Debug)]
pub(crate) struct PendingWrites<B: hal::Backend> {
pub(crate) struct PendingWrites<A: hal::Api> {
pub command_buffer: Option<B::CommandBuffer>,
pub temp_resources: Vec<(TempResource<B>, alloc::MemoryBlock<B>)>,
pub temp_resources: Vec<(TempResource<A>, alloc::MemoryBlock<A>)>,
pub dst_buffers: FastHashSet<id::BufferId>,
pub dst_textures: FastHashSet<id::TextureId>,
}
impl<B: hal::Backend> PendingWrites<B> {
impl<A: hal::Api> PendingWrites<A> {
pub fn new() -> Self {
Self {
command_buffer: None,
@@ -56,8 +56,8 @@ impl<B: hal::Backend> PendingWrites<B> {
pub fn dispose(
self,
device: &B::Device,
cmd_allocator: &CommandAllocator<B>,
mem_allocator: &mut alloc::MemoryAllocator<B>,
cmd_allocator: &CommandAllocator<A>,
mem_allocator: &mut alloc::MemoryAllocator<A>,
) {
if let Some(raw) = self.command_buffer {
cmd_allocator.discard_internal(raw);
@@ -75,11 +75,11 @@ impl<B: hal::Backend> PendingWrites<B> {
}
}
pub fn consume_temp(&mut self, resource: TempResource<B>, memory: alloc::MemoryBlock<B>) {
pub fn consume_temp(&mut self, resource: TempResource<A>, memory: alloc::MemoryBlock<A>) {
self.temp_resources.push((resource, memory));
}
fn consume(&mut self, stage: StagingData<B>) {
fn consume(&mut self, stage: StagingData<A>) {
self.temp_resources
.push((TempResource::Buffer(stage.buffer), stage.memory));
self.command_buffer = Some(stage.cmdbuf);
@@ -95,7 +95,7 @@ impl<B: hal::Backend> PendingWrites<B> {
})
}
fn borrow_cmd_buf(&mut self, cmd_allocator: &CommandAllocator<B>) -> &mut B::CommandBuffer {
fn borrow_cmd_buf(&mut self, cmd_allocator: &CommandAllocator<A>) -> &mut B::CommandBuffer {
if self.command_buffer.is_none() {
let mut cmdbuf = cmd_allocator.allocate_internal();
unsafe {
@@ -113,10 +113,10 @@ struct RequiredBufferInits {
}
impl RequiredBufferInits {
fn add<B: hal::Backend>(
fn add<A: hal::Api>(
&mut self,
buffer_memory_init_actions: &[MemoryInitTrackerAction<id::BufferId>],
buffer_guard: &mut Storage<Buffer<B>, id::BufferId>,
buffer_guard: &mut Storage<Buffer<A>, id::BufferId>,
) -> Result<(), QueueSubmitError> {
for buffer_use in buffer_memory_init_actions.iter() {
let buffer = buffer_guard
@@ -140,12 +140,12 @@ impl RequiredBufferInits {
}
}
impl<B: hal::Backend> super::Device<B> {
impl<A: hal::Api> super::Device<A> {
pub fn borrow_pending_writes(&mut self) -> &mut B::CommandBuffer {
self.pending_writes.borrow_cmd_buf(&self.cmd_allocator)
}
fn prepare_stage(&mut self, size: wgt::BufferAddress) -> Result<StagingData<B>, DeviceError> {
fn prepare_stage(&mut self, size: wgt::BufferAddress) -> Result<StagingData<A>, DeviceError> {
profiling::scope!("prepare_stage");
let mut buffer = unsafe {
self.raw
@@ -192,7 +192,7 @@ impl<B: hal::Backend> super::Device<B> {
fn initialize_buffer_memory(
&mut self,
mut required_buffer_inits: RequiredBufferInits,
buffer_guard: &mut Storage<Buffer<B>, id::BufferId>,
buffer_guard: &mut Storage<Buffer<A>, id::BufferId>,
) -> Result<(), QueueSubmitError> {
self.pending_writes
.dst_buffers
@@ -285,7 +285,7 @@ pub enum QueueSubmitError {
//TODO: move out common parts of write_xxx.
impl<G: GlobalIdentityHandlerFactory> Global<G> {
pub fn queue_write_buffer<B: GfxBackend>(
pub fn queue_write_buffer<A: HalApi>(
&self,
queue_id: id::QueueId,
buffer_id: id::BufferId,
@@ -294,7 +294,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
) -> Result<(), QueueWriteError> {
profiling::scope!("write_buffer", "Queue");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut device_guard, mut token) = hub.devices.write(&mut token);
let device = device_guard
@@ -391,7 +391,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
Ok(())
}
pub fn queue_write_texture<B: GfxBackend>(
pub fn queue_write_texture<A: HalApi>(
&self,
queue_id: id::QueueId,
destination: &ImageCopyTexture,
@@ -401,7 +401,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
) -> Result<(), QueueWriteError> {
profiling::scope!("write_texture", "Queue");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut device_guard, mut token) = hub.devices.write(&mut token);
let device = device_guard
@@ -586,14 +586,14 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
Ok(())
}
pub fn queue_submit<B: GfxBackend>(
pub fn queue_submit<A: HalApi>(
&self,
queue_id: id::QueueId,
command_buffer_ids: &[id::CommandBufferId],
) -> Result<(), QueueSubmitError> {
profiling::scope!("submit", "Queue");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let callbacks = {
@@ -676,7 +676,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
if !buffer.life_guard.use_at(submit_index) {
if let BufferMapState::Active { .. } = buffer.map_state {
log::warn!("Dropped buffer has a pending mapping.");
super::unmap_buffer(&device.raw, buffer)?;
unsafe { device.raw.unmap_buffer(buffer)? };
}
device.temp_suspected.buffers.push(id);
} else {
@@ -828,11 +828,11 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
Ok(())
}
pub fn queue_get_timestamp_period<B: GfxBackend>(
pub fn queue_get_timestamp_period<A: HalApi>(
&self,
queue_id: id::QueueId,
) -> Result<f32, InvalidQueue> {
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (device_guard, _) = hub.devices.read(&mut token);
match device_guard.get(queue_id) {
+116 -112
View File
@@ -3,7 +3,6 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::{
backend,
binding_model::{BindGroup, BindGroupLayout, PipelineLayout},
command::{CommandBuffer, RenderBundle},
device::Device,
@@ -226,7 +225,7 @@ impl<T, I: TypedId> Storage<T, I> {
}
/// Type system for enforcing the lock order on shared HUB structures.
/// If type A implements `Access<B>`, that means we are allowed to proceed
/// If type A implements `Access<A>`, that means we are allowed to proceed
/// with locking resource `B` after we lock `A`.
///
/// The implenentations basically describe the edges in a directed graph
@@ -234,66 +233,66 @@ impl<T, I: TypedId> Storage<T, I> {
/// multiple concurrent paths on this graph (from multiple threads) without
/// deadlocks, i.e. there is always a path whose next resource is not locked
/// by some other path, at any time.
pub trait Access<B> {}
pub trait Access<A> {}
pub enum Root {}
//TODO: establish an order instead of declaring all the pairs.
impl Access<Instance> for Root {}
impl Access<Surface> for Root {}
impl Access<Surface> for Instance {}
impl<B: hal::Backend> Access<Adapter<B>> for Root {}
impl<B: hal::Backend> Access<Adapter<B>> for Surface {}
impl<B: hal::Backend> Access<Device<B>> for Root {}
impl<B: hal::Backend> Access<Device<B>> for Surface {}
impl<B: hal::Backend> Access<Device<B>> for Adapter<B> {}
impl<B: hal::Backend> Access<SwapChain<B>> for Root {}
impl<B: hal::Backend> Access<SwapChain<B>> for Device<B> {}
impl<B: hal::Backend> Access<PipelineLayout<B>> for Root {}
impl<B: hal::Backend> Access<PipelineLayout<B>> for Device<B> {}
impl<B: hal::Backend> Access<PipelineLayout<B>> for RenderBundle {}
impl<B: hal::Backend> Access<BindGroupLayout<B>> for Root {}
impl<B: hal::Backend> Access<BindGroupLayout<B>> for Device<B> {}
impl<B: hal::Backend> Access<BindGroupLayout<B>> for PipelineLayout<B> {}
impl<B: hal::Backend> Access<BindGroup<B>> for Root {}
impl<B: hal::Backend> Access<BindGroup<B>> for Device<B> {}
impl<B: hal::Backend> Access<BindGroup<B>> for BindGroupLayout<B> {}
impl<B: hal::Backend> Access<BindGroup<B>> for PipelineLayout<B> {}
impl<B: hal::Backend> Access<BindGroup<B>> for CommandBuffer<B> {}
impl<B: hal::Backend> Access<CommandBuffer<B>> for Root {}
impl<B: hal::Backend> Access<CommandBuffer<B>> for Device<B> {}
impl<B: hal::Backend> Access<CommandBuffer<B>> for SwapChain<B> {}
impl<B: hal::Backend> Access<RenderBundle> for Device<B> {}
impl<B: hal::Backend> Access<RenderBundle> for CommandBuffer<B> {}
impl<B: hal::Backend> Access<ComputePipeline<B>> for Device<B> {}
impl<B: hal::Backend> Access<ComputePipeline<B>> for BindGroup<B> {}
impl<B: hal::Backend> Access<RenderPipeline<B>> for Device<B> {}
impl<B: hal::Backend> Access<RenderPipeline<B>> for BindGroup<B> {}
impl<B: hal::Backend> Access<RenderPipeline<B>> for ComputePipeline<B> {}
impl<B: hal::Backend> Access<QuerySet<B>> for Root {}
impl<B: hal::Backend> Access<QuerySet<B>> for Device<B> {}
impl<B: hal::Backend> Access<QuerySet<B>> for CommandBuffer<B> {}
impl<B: hal::Backend> Access<QuerySet<B>> for RenderPipeline<B> {}
impl<B: hal::Backend> Access<QuerySet<B>> for ComputePipeline<B> {}
impl<B: hal::Backend> Access<ShaderModule<B>> for Device<B> {}
impl<B: hal::Backend> Access<ShaderModule<B>> for BindGroupLayout<B> {}
impl<B: hal::Backend> Access<Buffer<B>> for Root {}
impl<B: hal::Backend> Access<Buffer<B>> for Device<B> {}
impl<B: hal::Backend> Access<Buffer<B>> for BindGroupLayout<B> {}
impl<B: hal::Backend> Access<Buffer<B>> for BindGroup<B> {}
impl<B: hal::Backend> Access<Buffer<B>> for CommandBuffer<B> {}
impl<B: hal::Backend> Access<Buffer<B>> for ComputePipeline<B> {}
impl<B: hal::Backend> Access<Buffer<B>> for RenderPipeline<B> {}
impl<B: hal::Backend> Access<Buffer<B>> for QuerySet<B> {}
impl<B: hal::Backend> Access<Texture<B>> for Root {}
impl<B: hal::Backend> Access<Texture<B>> for Device<B> {}
impl<B: hal::Backend> Access<Texture<B>> for Buffer<B> {}
impl<B: hal::Backend> Access<TextureView<B>> for Root {}
impl<B: hal::Backend> Access<TextureView<B>> for SwapChain<B> {}
impl<B: hal::Backend> Access<TextureView<B>> for Device<B> {}
impl<B: hal::Backend> Access<TextureView<B>> for Texture<B> {}
impl<B: hal::Backend> Access<Sampler<B>> for Root {}
impl<B: hal::Backend> Access<Sampler<B>> for Device<B> {}
impl<B: hal::Backend> Access<Sampler<B>> for TextureView<B> {}
impl<A: hal::Api> Access<Adapter<A>> for Root {}
impl<A: hal::Api> Access<Adapter<A>> for Surface {}
impl<A: hal::Api> Access<Device<A>> for Root {}
impl<A: hal::Api> Access<Device<A>> for Surface {}
impl<A: hal::Api> Access<Device<A>> for Adapter<A> {}
impl<A: hal::Api> Access<SwapChain<A>> for Root {}
impl<A: hal::Api> Access<SwapChain<A>> for Device<A> {}
impl<A: hal::Api> Access<PipelineLayout<A>> for Root {}
impl<A: hal::Api> Access<PipelineLayout<A>> for Device<A> {}
impl<A: hal::Api> Access<PipelineLayout<A>> for RenderBundle {}
impl<A: hal::Api> Access<BindGroupLayout<A>> for Root {}
impl<A: hal::Api> Access<BindGroupLayout<A>> for Device<A> {}
impl<A: hal::Api> Access<BindGroupLayout<A>> for PipelineLayout<A> {}
impl<A: hal::Api> Access<BindGroup<A>> for Root {}
impl<A: hal::Api> Access<BindGroup<A>> for Device<A> {}
impl<A: hal::Api> Access<BindGroup<A>> for BindGroupLayout<A> {}
impl<A: hal::Api> Access<BindGroup<A>> for PipelineLayout<A> {}
impl<A: hal::Api> Access<BindGroup<A>> for CommandBuffer<A> {}
impl<A: hal::Api> Access<CommandBuffer<A>> for Root {}
impl<A: hal::Api> Access<CommandBuffer<A>> for Device<A> {}
impl<A: hal::Api> Access<CommandBuffer<A>> for SwapChain<A> {}
impl<A: hal::Api> Access<RenderBundle> for Device<A> {}
impl<A: hal::Api> Access<RenderBundle> for CommandBuffer<A> {}
impl<A: hal::Api> Access<ComputePipeline<A>> for Device<A> {}
impl<A: hal::Api> Access<ComputePipeline<A>> for BindGroup<A> {}
impl<A: hal::Api> Access<RenderPipeline<A>> for Device<A> {}
impl<A: hal::Api> Access<RenderPipeline<A>> for BindGroup<A> {}
impl<A: hal::Api> Access<RenderPipeline<A>> for ComputePipeline<A> {}
impl<A: hal::Api> Access<QuerySet<A>> for Root {}
impl<A: hal::Api> Access<QuerySet<A>> for Device<A> {}
impl<A: hal::Api> Access<QuerySet<A>> for CommandBuffer<A> {}
impl<A: hal::Api> Access<QuerySet<A>> for RenderPipeline<A> {}
impl<A: hal::Api> Access<QuerySet<A>> for ComputePipeline<A> {}
impl<A: hal::Api> Access<ShaderModule<A>> for Device<A> {}
impl<A: hal::Api> Access<ShaderModule<A>> for BindGroupLayout<A> {}
impl<A: hal::Api> Access<Buffer<A>> for Root {}
impl<A: hal::Api> Access<Buffer<A>> for Device<A> {}
impl<A: hal::Api> Access<Buffer<A>> for BindGroupLayout<A> {}
impl<A: hal::Api> Access<Buffer<A>> for BindGroup<A> {}
impl<A: hal::Api> Access<Buffer<A>> for CommandBuffer<A> {}
impl<A: hal::Api> Access<Buffer<A>> for ComputePipeline<A> {}
impl<A: hal::Api> Access<Buffer<A>> for RenderPipeline<A> {}
impl<A: hal::Api> Access<Buffer<A>> for QuerySet<A> {}
impl<A: hal::Api> Access<Texture<A>> for Root {}
impl<A: hal::Api> Access<Texture<A>> for Device<A> {}
impl<A: hal::Api> Access<Texture<A>> for Buffer<A> {}
impl<A: hal::Api> Access<TextureView<A>> for Root {}
impl<A: hal::Api> Access<TextureView<A>> for SwapChain<A> {}
impl<A: hal::Api> Access<TextureView<A>> for Device<A> {}
impl<A: hal::Api> Access<TextureView<A>> for Texture<A> {}
impl<A: hal::Api> Access<Sampler<A>> for Root {}
impl<A: hal::Api> Access<Sampler<A>> for Device<A> {}
impl<A: hal::Api> Access<Sampler<A>> for TextureView<A> {}
#[cfg(debug_assertions)]
thread_local! {
@@ -537,55 +536,55 @@ impl<T: Resource, I: TypedId + Copy, F: IdentityHandlerFactory<I>> Registry<T, I
}
#[derive(Debug)]
pub struct Hub<B: hal::Backend, F: GlobalIdentityHandlerFactory> {
pub adapters: Registry<Adapter<B>, AdapterId, F>,
pub devices: Registry<Device<B>, DeviceId, F>,
pub swap_chains: Registry<SwapChain<B>, SwapChainId, F>,
pub pipeline_layouts: Registry<PipelineLayout<B>, PipelineLayoutId, F>,
pub shader_modules: Registry<ShaderModule<B>, ShaderModuleId, F>,
pub bind_group_layouts: Registry<BindGroupLayout<B>, BindGroupLayoutId, F>,
pub bind_groups: Registry<BindGroup<B>, BindGroupId, F>,
pub command_buffers: Registry<CommandBuffer<B>, CommandBufferId, F>,
pub struct Hub<A: hal::Api, F: GlobalIdentityHandlerFactory> {
pub adapters: Registry<Adapter<A>, AdapterId, F>,
pub devices: Registry<Device<A>, DeviceId, F>,
pub swap_chains: Registry<SwapChain<A>, SwapChainId, F>,
pub pipeline_layouts: Registry<PipelineLayout<A>, PipelineLayoutId, F>,
pub shader_modules: Registry<ShaderModule<A>, ShaderModuleId, F>,
pub bind_group_layouts: Registry<BindGroupLayout<A>, BindGroupLayoutId, F>,
pub bind_groups: Registry<BindGroup<A>, BindGroupId, F>,
pub command_buffers: Registry<CommandBuffer<A>, CommandBufferId, F>,
pub render_bundles: Registry<RenderBundle, RenderBundleId, F>,
pub render_pipelines: Registry<RenderPipeline<B>, RenderPipelineId, F>,
pub compute_pipelines: Registry<ComputePipeline<B>, ComputePipelineId, F>,
pub query_sets: Registry<QuerySet<B>, QuerySetId, F>,
pub buffers: Registry<Buffer<B>, BufferId, F>,
pub textures: Registry<Texture<B>, TextureId, F>,
pub texture_views: Registry<TextureView<B>, TextureViewId, F>,
pub samplers: Registry<Sampler<B>, SamplerId, F>,
pub render_pipelines: Registry<RenderPipeline<A>, RenderPipelineId, F>,
pub compute_pipelines: Registry<ComputePipeline<A>, ComputePipelineId, F>,
pub query_sets: Registry<QuerySet<A>, QuerySetId, F>,
pub buffers: Registry<Buffer<A>, BufferId, F>,
pub textures: Registry<Texture<A>, TextureId, F>,
pub texture_views: Registry<TextureView<A>, TextureViewId, F>,
pub samplers: Registry<Sampler<A>, SamplerId, F>,
}
impl<B: GfxBackend, F: GlobalIdentityHandlerFactory> Hub<B, F> {
impl<A: HalApi, F: GlobalIdentityHandlerFactory> Hub<B, F> {
fn new(factory: &F) -> Self {
Self {
adapters: Registry::new(B::VARIANT, factory),
devices: Registry::new(B::VARIANT, factory),
swap_chains: Registry::new(B::VARIANT, factory),
pipeline_layouts: Registry::new(B::VARIANT, factory),
shader_modules: Registry::new(B::VARIANT, factory),
bind_group_layouts: Registry::new(B::VARIANT, factory),
bind_groups: Registry::new(B::VARIANT, factory),
command_buffers: Registry::new(B::VARIANT, factory),
render_bundles: Registry::new(B::VARIANT, factory),
render_pipelines: Registry::new(B::VARIANT, factory),
compute_pipelines: Registry::new(B::VARIANT, factory),
query_sets: Registry::new(B::VARIANT, factory),
buffers: Registry::new(B::VARIANT, factory),
textures: Registry::new(B::VARIANT, factory),
texture_views: Registry::new(B::VARIANT, factory),
samplers: Registry::new(B::VARIANT, factory),
adapters: Registry::new(A::VARIANT, factory),
devices: Registry::new(A::VARIANT, factory),
swap_chains: Registry::new(A::VARIANT, factory),
pipeline_layouts: Registry::new(A::VARIANT, factory),
shader_modules: Registry::new(A::VARIANT, factory),
bind_group_layouts: Registry::new(A::VARIANT, factory),
bind_groups: Registry::new(A::VARIANT, factory),
command_buffers: Registry::new(A::VARIANT, factory),
render_bundles: Registry::new(A::VARIANT, factory),
render_pipelines: Registry::new(A::VARIANT, factory),
compute_pipelines: Registry::new(A::VARIANT, factory),
query_sets: Registry::new(A::VARIANT, factory),
buffers: Registry::new(A::VARIANT, factory),
textures: Registry::new(A::VARIANT, factory),
texture_views: Registry::new(A::VARIANT, factory),
samplers: Registry::new(A::VARIANT, factory),
}
}
}
impl<B: GfxBackend, F: GlobalIdentityHandlerFactory> Hub<B, F> {
impl<A: HalApi, F: GlobalIdentityHandlerFactory> Hub<B, F> {
//TODO: instead of having a hacky `with_adapters` parameter,
// we should have `clear_device(device_id)` that specifically destroys
// everything related to a logical device.
fn clear(&self, surface_guard: &mut Storage<Surface, SurfaceId>, with_adapters: bool) {
use crate::resource::TextureViewInner;
use hal::{device::Device as _, window::PresentationSurface as _};
use hal::Device as _;
let mut devices = self.devices.data.write();
for element in devices.map.iter_mut() {
@@ -693,7 +692,7 @@ impl<B: GfxBackend, F: GlobalIdentityHandlerFactory> Hub<B, F> {
unsafe {
device.raw.destroy_semaphore(swap_chain.semaphore);
}
let suf_id = TypedId::zip(index as Index, epoch, B::VARIANT);
let suf_id = TypedId::zip(index as Index, epoch, A::VARIANT);
//TODO: hold the surface alive by the swapchain
if surface_guard.contains(suf_id) {
let surface = surface_guard.get_mut(suf_id).unwrap();
@@ -727,21 +726,22 @@ impl<B: GfxBackend, F: GlobalIdentityHandlerFactory> Hub<B, F> {
#[derive(Debug)]
pub struct Hubs<F: GlobalIdentityHandlerFactory> {
#[cfg(vulkan)]
vulkan: Hub<backend::Vulkan, F>,
#[cfg(metal)]
metal: Hub<backend::Metal, F>,
#[cfg(dx12)]
dx12: Hub<backend::Dx12, F>,
#[cfg(dx11)]
dx11: Hub<backend::Dx11, F>,
#[cfg(gl)]
gl: Hub<backend::Gl, F>,
}
/*
#[cfg(vulkan)]
vulkan: Hub<backend::Vulkan, F>,
#[cfg(metal)]
metal: Hub<backend::Metal, F>,
#[cfg(dx12)]
dx12: Hub<backend::Dx12, F>,
#[cfg(dx11)]
dx11: Hub<backend::Dx11, F>,
#[cfg(gl)]
gl: Hub<backend::Gl, F>,*/}
impl<F: GlobalIdentityHandlerFactory> Hubs<F> {
fn new(factory: &F) -> Self {
Self {
/*
#[cfg(vulkan)]
vulkan: Hub::new(factory),
#[cfg(metal)]
@@ -752,6 +752,7 @@ impl<F: GlobalIdentityHandlerFactory> Hubs<F> {
dx11: Hub::new(factory),
#[cfg(gl)]
gl: Hub::new(factory),
*/
}
}
}
@@ -773,9 +774,9 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
}
}
pub fn clear_backend<B: GfxBackend>(&self, _dummy: ()) {
pub fn clear_backend<A: HalApi>(&self, _dummy: ()) {
let mut surface_guard = self.surfaces.data.write();
let hub = B::hub(self);
let hub = A::hub(self);
// this is used for tests, which keep the adapter
hub.clear(&mut *surface_guard, false);
}
@@ -788,6 +789,7 @@ impl<G: GlobalIdentityHandlerFactory> Drop for Global<G> {
let mut surface_guard = self.surfaces.data.write();
// destroy hubs before the instance gets dropped
/*
#[cfg(vulkan)]
{
self.hubs.vulkan.clear(&mut *surface_guard, true);
@@ -808,6 +810,7 @@ impl<G: GlobalIdentityHandlerFactory> Drop for Global<G> {
{
self.hubs.gl.clear(&mut *surface_guard, true);
}
*/
// destroy surfaces
for element in surface_guard.map.drain(..) {
@@ -818,14 +821,15 @@ impl<G: GlobalIdentityHandlerFactory> Drop for Global<G> {
}
}
pub trait GfxBackend: hal::Backend {
pub trait HalApi: hal::Api {
const VARIANT: Backend;
fn hub<G: GlobalIdentityHandlerFactory>(global: &Global<G>) -> &Hub<Self, G>;
fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface;
}
/*
#[cfg(vulkan)]
impl GfxBackend for backend::Vulkan {
impl HalApi for backend::Vulkan {
const VARIANT: Backend = Backend::Vulkan;
fn hub<G: GlobalIdentityHandlerFactory>(global: &Global<G>) -> &Hub<Self, G> {
&global.hubs.vulkan
@@ -836,7 +840,7 @@ impl GfxBackend for backend::Vulkan {
}
#[cfg(metal)]
impl GfxBackend for backend::Metal {
impl HalApi for backend::Metal {
const VARIANT: Backend = Backend::Metal;
fn hub<G: GlobalIdentityHandlerFactory>(global: &Global<G>) -> &Hub<Self, G> {
&global.hubs.metal
@@ -847,7 +851,7 @@ impl GfxBackend for backend::Metal {
}
#[cfg(dx12)]
impl GfxBackend for backend::Dx12 {
impl HalApi for backend::Dx12 {
const VARIANT: Backend = Backend::Dx12;
fn hub<G: GlobalIdentityHandlerFactory>(global: &Global<G>) -> &Hub<Self, G> {
&global.hubs.dx12
@@ -858,7 +862,7 @@ impl GfxBackend for backend::Dx12 {
}
#[cfg(dx11)]
impl GfxBackend for backend::Dx11 {
impl HalApi for backend::Dx11 {
const VARIANT: Backend = Backend::Dx11;
fn hub<G: GlobalIdentityHandlerFactory>(global: &Global<G>) -> &Hub<Self, G> {
&global.hubs.dx11
@@ -869,7 +873,7 @@ impl GfxBackend for backend::Dx11 {
}
#[cfg(gl)]
impl GfxBackend for backend::Gl {
impl HalApi for backend::Gl {
const VARIANT: Backend = Backend::Gl;
fn hub<G: GlobalIdentityHandlerFactory>(global: &Global<G>) -> &Hub<Self, G> {
&global.hubs.gl
@@ -877,7 +881,7 @@ impl GfxBackend for backend::Gl {
fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface {
surface.gl.as_mut().unwrap()
}
}
}*/
#[cfg(test)]
fn _test_send_sync(global: &Global<IdentityManagerFactory>) {
+121 -397
View File
@@ -3,41 +3,34 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::{
backend, conv,
conv,
device::{Device, DeviceDescriptor},
hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Input, Token},
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Input, Token},
id::{AdapterId, DeviceId, SurfaceId, Valid},
LabelHelpers, LifeGuard, PrivateFeatures, Stored, DOWNLEVEL_WARNING_MESSAGE, MAX_BIND_GROUPS,
LabelHelpers, LifeGuard, Stored, DOWNLEVEL_WARNING_MESSAGE,
};
use wgt::{Backend, BackendBit, PowerPreference, BIND_BUFFER_ALIGNMENT};
use hal::{
adapter::PhysicalDevice as _, queue::QueueFamily as _, window::Surface as _, Instance as _,
};
use hal::Adapter as _;
use thiserror::Error;
/// Size that is guaranteed to be available in push constants.
///
/// This is needed because non-vulkan backends might not
/// provide a push-constant size limit.
const MIN_PUSH_CONSTANT_SIZE: u32 = 128;
pub type RequestAdapterOptions = wgt::RequestAdapterOptions<SurfaceId>;
#[derive(Debug)]
pub struct Instance {
#[cfg(vulkan)]
pub vulkan: Option<gfx_backend_vulkan::Instance>,
#[cfg(metal)]
pub metal: Option<gfx_backend_metal::Instance>,
#[cfg(dx12)]
pub dx12: Option<gfx_backend_dx12::Instance>,
#[cfg(dx11)]
pub dx11: Option<gfx_backend_dx11::Instance>,
#[cfg(gl)]
pub gl: Option<gfx_backend_gl::Instance>,
}
/*
#[cfg(vulkan)]
pub vulkan: Option<gfx_backend_vulkan::Instance>,
#[cfg(metal)]
pub metal: Option<gfx_backend_metal::Instance>,
#[cfg(dx12)]
pub dx12: Option<gfx_backend_dx12::Instance>,
#[cfg(dx11)]
pub dx11: Option<gfx_backend_dx11::Instance>,
#[cfg(gl)]
pub gl: Option<gfx_backend_gl::Instance>,
*/}
impl Instance {
pub fn new(name: &str, version: u32, backends: BackendBit) -> Self {
@@ -50,6 +43,7 @@ impl Instance {
}
};
Self {
/*
#[cfg(vulkan)]
vulkan: map((Backend::Vulkan, gfx_backend_vulkan::Instance::create)),
#[cfg(metal)]
@@ -60,6 +54,7 @@ impl Instance {
dx11: map((Backend::Dx11, gfx_backend_dx11::Instance::create)),
#[cfg(gl)]
gl: map((Backend::Gl, gfx_backend_gl::Instance::create)),
*/
}
}
}
@@ -74,6 +69,7 @@ impl Instance {
}
};
/*
#[cfg(vulkan)]
map((surface.vulkan, &self.vulkan)),
#[cfg(metal)]
@@ -84,25 +80,27 @@ impl Instance {
map((surface.dx11, &self.dx11)),
#[cfg(gl)]
map((surface.gl, &self.gl)),
*/
}
}
}
type GfxSurface<B> = <B as hal::Backend>::Surface;
type GfxSurface<A> = <B as hal::Api>::Surface;
#[derive(Debug)]
pub struct Surface {
#[cfg(vulkan)]
pub vulkan: Option<GfxSurface<backend::Vulkan>>,
#[cfg(metal)]
pub metal: Option<GfxSurface<backend::Metal>>,
#[cfg(dx12)]
pub dx12: Option<GfxSurface<backend::Dx12>>,
#[cfg(dx11)]
pub dx11: Option<GfxSurface<backend::Dx11>>,
#[cfg(gl)]
pub gl: Option<GfxSurface<backend::Gl>>,
}
/*
#[cfg(vulkan)]
pub vulkan: Option<GfxSurface<backend::Vulkan>>,
#[cfg(metal)]
pub metal: Option<GfxSurface<backend::Metal>>,
#[cfg(dx12)]
pub dx12: Option<GfxSurface<backend::Dx12>>,
#[cfg(dx11)]
pub dx11: Option<GfxSurface<backend::Dx11>>,
#[cfg(gl)]
pub gl: Option<GfxSurface<backend::Gl>>,
*/}
impl crate::hub::Resource for Surface {
const TYPE: &'static str = "Surface";
@@ -116,236 +114,16 @@ impl crate::hub::Resource for Surface {
}
}
const FEATURE_MAP: &[(wgt::Features, hal::Features)] = &[
(wgt::Features::DEPTH_CLAMPING, hal::Features::DEPTH_CLAMP),
(
wgt::Features::TEXTURE_COMPRESSION_BC,
hal::Features::FORMAT_BC,
),
(
wgt::Features::TEXTURE_COMPRESSION_ETC2,
hal::Features::FORMAT_ETC2,
),
(
wgt::Features::TEXTURE_COMPRESSION_ASTC_LDR,
hal::Features::FORMAT_ASTC_LDR,
),
(
wgt::Features::SAMPLED_TEXTURE_BINDING_ARRAY,
hal::Features::TEXTURE_DESCRIPTOR_ARRAY,
),
(
wgt::Features::SAMPLED_TEXTURE_ARRAY_DYNAMIC_INDEXING,
hal::Features::SHADER_SAMPLED_IMAGE_ARRAY_DYNAMIC_INDEXING,
),
(
wgt::Features::SAMPLED_TEXTURE_ARRAY_NON_UNIFORM_INDEXING,
hal::Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING,
),
(
wgt::Features::UNSIZED_BINDING_ARRAY,
hal::Features::UNSIZED_DESCRIPTOR_ARRAY,
),
(
wgt::Features::MULTI_DRAW_INDIRECT,
hal::Features::MULTI_DRAW_INDIRECT,
),
(
wgt::Features::MULTI_DRAW_INDIRECT_COUNT,
hal::Features::DRAW_INDIRECT_COUNT,
),
(
wgt::Features::NON_FILL_POLYGON_MODE,
hal::Features::NON_FILL_POLYGON_MODE,
),
(
wgt::Features::PIPELINE_STATISTICS_QUERY,
hal::Features::PIPELINE_STATISTICS_QUERY,
),
(wgt::Features::SHADER_FLOAT64, hal::Features::SHADER_FLOAT64),
(
wgt::Features::CONSERVATIVE_RASTERIZATION,
hal::Features::CONSERVATIVE_RASTERIZATION,
),
(
wgt::Features::BUFFER_BINDING_ARRAY,
hal::Features::BUFFER_DESCRIPTOR_ARRAY,
),
(
wgt::Features::UNIFORM_BUFFER_ARRAY_DYNAMIC_INDEXING,
hal::Features::SHADER_UNIFORM_BUFFER_ARRAY_DYNAMIC_INDEXING,
),
(
wgt::Features::UNIFORM_BUFFER_ARRAY_NON_UNIFORM_INDEXING,
hal::Features::UNIFORM_BUFFER_DESCRIPTOR_INDEXING,
),
(
wgt::Features::STORAGE_BUFFER_ARRAY_DYNAMIC_INDEXING,
hal::Features::SHADER_STORAGE_BUFFER_ARRAY_DYNAMIC_INDEXING,
),
(
wgt::Features::STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING,
hal::Features::STORAGE_BUFFER_DESCRIPTOR_INDEXING,
),
(
wgt::Features::VERTEX_WRITABLE_STORAGE,
hal::Features::VERTEX_STORES_AND_ATOMICS,
),
(
wgt::Features::ADDRESS_MODE_CLAMP_TO_BORDER,
hal::Features::SAMPLER_BORDER_COLOR,
),
];
#[derive(Debug)]
pub struct Adapter<B: hal::Backend> {
pub(crate) raw: hal::adapter::Adapter<B>,
features: wgt::Features,
pub(crate) private_features: PrivateFeatures,
limits: wgt::Limits,
downlevel: wgt::DownlevelProperties,
pub struct Adapter<A: hal::Api> {
pub(crate) raw: hal::ExposedAdapter<A>,
life_guard: LifeGuard,
}
impl<B: GfxBackend> Adapter<B> {
fn new(raw: hal::adapter::Adapter<B>) -> Self {
profiling::scope!("new", "Adapter");
let adapter_features = raw.physical_device.features();
let properties = raw.physical_device.properties();
let mut features = wgt::Features::default()
| wgt::Features::MAPPABLE_PRIMARY_BUFFERS
| wgt::Features::PUSH_CONSTANTS
| wgt::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES
| wgt::Features::CLEAR_COMMANDS;
for &(hi, lo) in FEATURE_MAP.iter() {
features.set(hi, adapter_features.contains(lo));
}
features.set(
wgt::Features::TIMESTAMP_QUERY,
properties.limits.timestamp_compute_and_graphics,
);
let private_features = PrivateFeatures {
anisotropic_filtering: adapter_features.contains(hal::Features::SAMPLER_ANISOTROPY),
texture_d24: raw
.physical_device
.format_properties(Some(hal::format::Format::X8D24Unorm))
.optimal_tiling
.contains(hal::format::ImageFeature::DEPTH_STENCIL_ATTACHMENT),
texture_d24_s8: raw
.physical_device
.format_properties(Some(hal::format::Format::D24UnormS8Uint))
.optimal_tiling
.contains(hal::format::ImageFeature::DEPTH_STENCIL_ATTACHMENT),
};
let default_limits = wgt::Limits::default();
// All these casts to u32 are safe as the underlying vulkan types are u32s.
// If another backend provides larger limits than u32, we need to clamp them to u32::MAX.
// TODO: fix all gfx-hal backends to produce limits we care about, and remove .max
let desc_limits = &properties.limits.descriptor_limits;
let limits = wgt::Limits {
max_texture_dimension_1d: properties
.limits
.max_image_1d_size
.max(default_limits.max_texture_dimension_1d),
max_texture_dimension_2d: properties
.limits
.max_image_2d_size
.max(default_limits.max_texture_dimension_1d),
max_texture_dimension_3d: properties
.limits
.max_image_3d_size
.max(default_limits.max_texture_dimension_1d),
max_texture_array_layers: (properties.limits.max_image_array_layers as u32)
.max(default_limits.max_texture_array_layers),
max_bind_groups: (properties.limits.max_bound_descriptor_sets as u32)
.min(MAX_BIND_GROUPS as u32)
.max(default_limits.max_bind_groups),
max_dynamic_uniform_buffers_per_pipeline_layout: desc_limits
.max_descriptor_set_uniform_buffers_dynamic
.max(default_limits.max_dynamic_uniform_buffers_per_pipeline_layout),
max_dynamic_storage_buffers_per_pipeline_layout: desc_limits
.max_descriptor_set_storage_buffers_dynamic
.max(default_limits.max_dynamic_storage_buffers_per_pipeline_layout),
max_sampled_textures_per_shader_stage: desc_limits
.max_per_stage_descriptor_sampled_images
.max(default_limits.max_sampled_textures_per_shader_stage),
max_samplers_per_shader_stage: desc_limits
.max_per_stage_descriptor_samplers
.max(default_limits.max_samplers_per_shader_stage),
max_storage_buffers_per_shader_stage: desc_limits
.max_per_stage_descriptor_storage_buffers
.max(default_limits.max_storage_buffers_per_shader_stage),
max_storage_textures_per_shader_stage: desc_limits
.max_per_stage_descriptor_storage_images
.max(default_limits.max_storage_textures_per_shader_stage),
max_uniform_buffers_per_shader_stage: desc_limits
.max_per_stage_descriptor_uniform_buffers
.max(default_limits.max_uniform_buffers_per_shader_stage),
max_uniform_buffer_binding_size: (properties.limits.max_uniform_buffer_range as u32)
.max(default_limits.max_uniform_buffer_binding_size),
max_storage_buffer_binding_size: (properties.limits.max_storage_buffer_range as u32)
.max(default_limits.max_storage_buffer_binding_size),
max_vertex_buffers: (properties.limits.max_vertex_input_bindings as u32)
.max(default_limits.max_vertex_buffers),
max_vertex_attributes: (properties.limits.max_vertex_input_attributes as u32)
.max(default_limits.max_vertex_attributes),
max_vertex_buffer_array_stride: (properties.limits.max_vertex_input_binding_stride
as u32)
.max(default_limits.max_vertex_buffer_array_stride),
max_push_constant_size: (properties.limits.max_push_constants_size as u32)
.max(MIN_PUSH_CONSTANT_SIZE), // As an extension, the default is always 0, so define a separate minimum.
};
let mut downlevel_flags = wgt::DownlevelFlags::empty();
downlevel_flags.set(
wgt::DownlevelFlags::COMPUTE_SHADERS,
properties.downlevel.compute_shaders,
);
downlevel_flags.set(
wgt::DownlevelFlags::STORAGE_IMAGES,
properties.downlevel.storage_images,
);
downlevel_flags.set(
wgt::DownlevelFlags::READ_ONLY_DEPTH_STENCIL,
properties.downlevel.read_only_depth_stencil,
);
downlevel_flags.set(
wgt::DownlevelFlags::DEVICE_LOCAL_IMAGE_COPIES,
properties.downlevel.device_local_image_copies,
);
downlevel_flags.set(
wgt::DownlevelFlags::NON_POWER_OF_TWO_MIPMAPPED_TEXTURES,
properties.downlevel.non_power_of_two_mipmapped_textures,
);
downlevel_flags.set(
wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES,
adapter_features.contains(hal::Features::IMAGE_CUBE_ARRAY),
);
downlevel_flags.set(
wgt::DownlevelFlags::ANISOTROPIC_FILTERING,
private_features.anisotropic_filtering,
);
let downlevel = wgt::DownlevelProperties {
flags: downlevel_flags,
shader_model: match properties.downlevel.shader_model {
hal::DownlevelShaderModel::ShaderModel2 => wgt::ShaderModel::Sm2,
hal::DownlevelShaderModel::ShaderModel4 => wgt::ShaderModel::Sm4,
hal::DownlevelShaderModel::ShaderModel5 => wgt::ShaderModel::Sm5,
},
};
impl<A: HalApi> Adapter<A> {
fn new(raw: hal::ExposedAdapter<A>) -> Self {
Self {
raw,
features,
private_features,
limits,
downlevel,
life_guard: LifeGuard::new("<Adapter>"),
}
}
@@ -354,75 +132,58 @@ impl<B: GfxBackend> Adapter<B> {
&self,
surface: &mut Surface,
) -> Result<wgt::TextureFormat, GetSwapChainPreferredFormatError> {
let formats = {
let surface = B::get_surface_mut(surface);
let queue_family = &self.raw.queue_families[0];
if !surface.supports_queue_family(queue_family) {
return Err(GetSwapChainPreferredFormatError::UnsupportedQueueFamily);
}
surface.supported_formats(&self.raw.physical_device)
};
if let Some(formats) = formats {
// Check the four formats mentioned in the WebGPU spec:
// Bgra8UnormSrgb, Rgba8UnormSrgb, Bgra8Unorm, Rgba8Unorm
// Also, prefer sRGB over linear as it is better in
// representing perceived colors.
if formats.contains(&hal::format::Format::Bgra8Srgb) {
return Ok(wgt::TextureFormat::Bgra8UnormSrgb);
}
if formats.contains(&hal::format::Format::Rgba8Srgb) {
return Ok(wgt::TextureFormat::Rgba8UnormSrgb);
}
if formats.contains(&hal::format::Format::Bgra8Unorm) {
return Ok(wgt::TextureFormat::Bgra8Unorm);
}
if formats.contains(&hal::format::Format::Rgba8Unorm) {
return Ok(wgt::TextureFormat::Rgba8Unorm);
}
return Err(GetSwapChainPreferredFormatError::NotFound);
}
// Check the four formats mentioned in the WebGPU spec.
// Also, prefer sRGB over linear as it is better in
// representing perceived colors.
let preferred_formats = [
wgt::TextureFormat::Bgra8UnormSrgb,
wgt::TextureFormat::Rgba8UnormSrgb,
wgt::TextureFormat::Bgra8Unorm,
wgt::TextureFormat::Rgba8Unorm,
];
// If no formats were returned, use Bgra8UnormSrgb
Ok(wgt::TextureFormat::Bgra8UnormSrgb)
let formats = B::get_surface(surface).supported_formats(&self.raw.adapter);
preferred_formats
.iter()
.cloned()
.find(|preferred| formats.contains(preferred))
.ok_or(GetSwapChainPreferredFormatError::NotFound)
}
pub(crate) fn get_texture_format_features(
&self,
format: wgt::TextureFormat,
) -> wgt::TextureFormatFeatures {
let texture_format_properties = self
.raw
.physical_device
.format_properties(Some(conv::map_texture_format(
format,
self.private_features,
)))
.optimal_tiling;
let caps = self.raw.adapter.texture_format_capabilities(format);
let mut allowed_usages = format.describe().guaranteed_format_features.allowed_usages;
if texture_format_properties.contains(hal::format::ImageFeature::SAMPLED) {
allowed_usages |= wgt::TextureUsage::SAMPLED;
}
if texture_format_properties.contains(hal::format::ImageFeature::STORAGE) {
allowed_usages |= wgt::TextureUsage::STORAGE;
}
if texture_format_properties.contains(hal::format::ImageFeature::COLOR_ATTACHMENT) {
allowed_usages |= wgt::TextureUsage::RENDER_ATTACHMENT;
}
if texture_format_properties.contains(hal::format::ImageFeature::DEPTH_STENCIL_ATTACHMENT) {
allowed_usages |= wgt::TextureUsage::RENDER_ATTACHMENT;
}
allowed_usages.set(
wgt::TextureUsage::SAMPLED,
caps.contains(hal::TextureFormatCapability::SAMPLED),
);
allowed_usages.set(
wgt::TextureUsage::STORAGE,
caps.contains(hal::TextureFormatCapability::STORAGE),
);
allowed_usages.set(
wgt::TextureUsage::RENDER_ATTACHMENT,
caps.intersects(
hal::TextureFormatCapability::COLOR_ATTACHMENT
| hal::TextureFormatCapability::DEPTH_STENCIL_ATTACHMENT,
),
);
let mut flags = wgt::TextureFormatFeatureFlags::empty();
if texture_format_properties.contains(hal::format::ImageFeature::STORAGE_ATOMIC) {
flags |= wgt::TextureFormatFeatureFlags::STORAGE_ATOMICS;
}
if texture_format_properties.contains(hal::format::ImageFeature::STORAGE_READ_WRITE) {
flags |= wgt::TextureFormatFeatureFlags::STORAGE_READ_WRITE;
}
flags.set(
wgt::TextureFormatFeatureFlags::STORAGE_ATOMICS,
caps.contains(hal::TextureFormatCapability::STORAGE_ATOMIC),
);
flags.set(
wgt::TextureFormatFeatureFlags::STORAGE_READ_WRITE,
caps.contains(hal::TextureFormatCapability::STORAGE_READ_WRITE),
);
let filterable =
texture_format_properties.contains(hal::format::ImageFeature::SAMPLED_LINEAR);
let filterable = caps.contains(hal::TextureFormatCapability::SAMPLED_LINEAR);
wgt::TextureFormatFeatures {
allowed_usages,
@@ -436,11 +197,11 @@ impl<B: GfxBackend> Adapter<B> {
self_id: AdapterId,
desc: &DeviceDescriptor,
trace_path: Option<&std::path::Path>,
) -> Result<Device<B>, RequestDeviceError> {
) -> Result<Device<A>, RequestDeviceError> {
// Verify all features were exposed by the adapter
if !self.features.contains(desc.features) {
if !self.raw.features.contains(desc.features) {
return Err(RequestDeviceError::UnsupportedFeature(
desc.features - self.features,
desc.features - self.raw.features,
));
}
@@ -452,85 +213,43 @@ impl<B: GfxBackend> Adapter<B> {
if desc
.features
.contains(wgt::Features::MAPPABLE_PRIMARY_BUFFERS)
&& self.raw.info.device_type == hal::adapter::DeviceType::DiscreteGpu
&& self.raw.info.device_type == wgt::DeviceType::DiscreteGpu
{
log::warn!("Feature MAPPABLE_PRIMARY_BUFFERS enabled on a discrete gpu. This is a massive performance footgun and likely not what you wanted");
}
let phd = &self.raw.physical_device;
let available_features = phd.features();
// Check features that are always needed
let wishful_features = hal::Features::ROBUST_BUFFER_ACCESS
| hal::Features::FRAGMENT_STORES_AND_ATOMICS
| hal::Features::NDC_Y_UP
| hal::Features::INDEPENDENT_BLENDING
| hal::Features::SAMPLER_ANISOTROPY
| hal::Features::IMAGE_CUBE_ARRAY
| hal::Features::SAMPLE_RATE_SHADING;
let mut enabled_features = available_features & wishful_features;
if enabled_features != wishful_features {
log::warn!(
"Missing internal features: {:?}",
wishful_features - enabled_features
);
}
// Enable low-level features
for &(hi, lo) in FEATURE_MAP.iter() {
enabled_features.set(lo, desc.features.contains(hi));
}
let family = self
.raw
.queue_families
.iter()
.find(|family| family.queue_type().supports_graphics())
.ok_or(RequestDeviceError::NoGraphicsQueue)?;
let mut gpu =
unsafe { phd.open(&[(family, &[1.0])], enabled_features) }.map_err(|err| {
use hal::device::CreationError::*;
match err {
DeviceLost => RequestDeviceError::DeviceLost,
InitializationFailed => RequestDeviceError::Internal,
OutOfMemory(_) => RequestDeviceError::OutOfMemory,
_ => panic!("failed to create `gfx-hal` device: {}", err),
}
})?;
let gpu = unsafe { self.raw.adapter.open(desc.features) }.map_err(|err| match err {
hal::Error::DeviceLost => RequestDeviceError::DeviceLost,
hal::Error::OutOfMemory => RequestDeviceError::OutOfMemory,
})?;
if let Some(_) = desc.label {
//TODO
}
let limits = phd.properties().limits;
let caps = &self.raw.capabilities;
assert_eq!(
0,
BIND_BUFFER_ALIGNMENT % limits.min_storage_buffer_offset_alignment,
BIND_BUFFER_ALIGNMENT % caps.alignments.storage_buffer_offset,
"Adapter storage buffer offset alignment not compatible with WGPU"
);
assert_eq!(
0,
BIND_BUFFER_ALIGNMENT % limits.min_uniform_buffer_offset_alignment,
BIND_BUFFER_ALIGNMENT % caps.alignments.uniform_buffer_offset,
"Adapter uniform buffer offset alignment not compatible with WGPU"
);
if self.limits < desc.limits {
if self.raw.limits < desc.limits {
return Err(RequestDeviceError::LimitsExceeded);
}
let mem_props = phd.memory_properties();
Device::new(
gpu.device,
gpu,
Stored {
value: Valid(self_id),
ref_count: self.life_guard.add_ref(),
},
gpu.queue_groups.swap_remove(0),
mem_props,
limits,
self.private_features,
self.downlevel,
caps.alignments.clone(),
caps.downlevel.clone(),
desc,
trace_path,
)
@@ -538,7 +257,7 @@ impl<B: GfxBackend> Adapter<B> {
}
}
impl<B: hal::Backend> crate::hub::Resource for Adapter<B> {
impl<A: hal::Api> crate::hub::Resource for Adapter<A> {
const TYPE: &'static str = "Adapter";
fn life_guard(&self) -> &LifeGuard {
@@ -700,6 +419,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
}
};
/*
#[cfg(vulkan)]
map((&instance.vulkan, Backend::Vulkan, "Vulkan", backend::Vulkan::hub)),
#[cfg(metal)]
@@ -710,6 +430,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
map((&instance.dx11, Backend::Dx11, "Dx11", backend::Dx11::hub)),
#[cfg(gl)]
map((&instance.gl, Backend::Gl, "GL", backend::Gl::hub)),
*/
}
adapters
@@ -754,7 +475,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
.map_or(false, |qf| surface_backend.supports_queue_family(qf))
});
}
device_types.extend(adapters.iter().map(|ad| ad.info.device_type.clone()));
device_types.extend(adapters.iter().map(|ad| ad.info.device_type));
adapters
}
_ => Vec::new(),
@@ -763,6 +484,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
// NB: The internal function definitions are a workaround for Rust
// being weird with lifetimes for closure literals...
/*
#[cfg(vulkan)]
let adapters_vk = map((&instance.vulkan, &id_vulkan, {
fn surface_vulkan(surf: &Surface) -> Option<&GfxSurface<backend::Vulkan>> {
@@ -797,7 +519,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
surf.gl.as_ref()
}
surface_gl
}));
}));*/
}
if device_types.is_empty() {
@@ -809,19 +531,19 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
for (i, ty) in device_types.into_iter().enumerate() {
match ty {
hal::adapter::DeviceType::IntegratedGpu => {
wgt::DeviceType::IntegratedGpu => {
integrated = integrated.or(Some(i));
}
hal::adapter::DeviceType::DiscreteGpu => {
wgt::DeviceType::DiscreteGpu => {
discrete = discrete.or(Some(i));
}
hal::adapter::DeviceType::VirtualGpu => {
wgt::DeviceType::VirtualGpu => {
virt = virt.or(Some(i));
}
hal::adapter::DeviceType::Cpu => {
wgt::DeviceType::Cpu => {
cpu = cpu.or(Some(i));
}
hal::adapter::DeviceType::Other => {
wgt::DeviceType::Other => {
other = other.or(Some(i));
}
}
@@ -847,6 +569,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
selected -= adapters_backend.len();
};
/*
#[cfg(vulkan)]
map(("Vulkan", &mut id_vulkan, adapters_vk, backend::Vulkan::hub)),
#[cfg(metal)]
@@ -857,6 +580,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
map(("Dx11", &mut id_dx11, adapters_dx11, backend::Dx11::hub)),
#[cfg(gl)]
map(("GL", &mut id_gl, adapters_gl, backend::Gl::hub)),
*/
}
let _ = (
@@ -871,11 +595,11 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
Err(RequestAdapterError::NotFound)
}
pub fn adapter_get_info<B: GfxBackend>(
pub fn adapter_get_info<A: HalApi>(
&self,
adapter_id: AdapterId,
) -> Result<wgt::AdapterInfo, InvalidAdapter> {
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (adapter_guard, _) = hub.adapters.read(&mut token);
adapter_guard
@@ -884,12 +608,12 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
.map_err(|_| InvalidAdapter)
}
pub fn adapter_get_texture_format_features<B: GfxBackend>(
pub fn adapter_get_texture_format_features<A: HalApi>(
&self,
adapter_id: AdapterId,
format: wgt::TextureFormat,
) -> Result<wgt::TextureFormatFeatures, InvalidAdapter> {
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (adapter_guard, _) = hub.adapters.read(&mut token);
adapter_guard
@@ -898,11 +622,11 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
.map_err(|_| InvalidAdapter)
}
pub fn adapter_features<B: GfxBackend>(
pub fn adapter_features<A: HalApi>(
&self,
adapter_id: AdapterId,
) -> Result<wgt::Features, InvalidAdapter> {
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (adapter_guard, _) = hub.adapters.read(&mut token);
adapter_guard
@@ -911,11 +635,11 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
.map_err(|_| InvalidAdapter)
}
pub fn adapter_limits<B: GfxBackend>(
pub fn adapter_limits<A: HalApi>(
&self,
adapter_id: AdapterId,
) -> Result<wgt::Limits, InvalidAdapter> {
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (adapter_guard, _) = hub.adapters.read(&mut token);
adapter_guard
@@ -924,23 +648,23 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
.map_err(|_| InvalidAdapter)
}
pub fn adapter_downlevel_properties<B: GfxBackend>(
pub fn adapter_downlevel_properties<A: HalApi>(
&self,
adapter_id: AdapterId,
) -> Result<wgt::DownlevelProperties, InvalidAdapter> {
let hub = B::hub(self);
) -> Result<wgt::DownlevelCapabilities, InvalidAdapter> {
let hub = A::hub(self);
let mut token = Token::root();
let (adapter_guard, _) = hub.adapters.read(&mut token);
adapter_guard
.get(adapter_id)
.map(|adapter| adapter.downlevel)
.map(|adapter| adapter.raw.downlevel)
.map_err(|_| InvalidAdapter)
}
pub fn adapter_drop<B: GfxBackend>(&self, adapter_id: AdapterId) {
pub fn adapter_drop<A: HalApi>(&self, adapter_id: AdapterId) {
profiling::scope!("drop", "Adapter");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut adapter_guard, _) = hub.adapters.write(&mut token);
@@ -956,7 +680,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
}
impl<G: GlobalIdentityHandlerFactory> Global<G> {
pub fn adapter_request_device<B: GfxBackend>(
pub fn adapter_request_device<A: HalApi>(
&self,
adapter_id: AdapterId,
desc: &DeviceDescriptor,
@@ -965,7 +689,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
) -> (DeviceId, Option<RequestDeviceError>) {
profiling::scope!("request_device", "Adapter");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let fid = hub.devices.prepare(id_in);
+6 -17
View File
@@ -27,8 +27,8 @@
mod macros;
pub mod backend {
pub use gfx_backend_empty::Backend as Empty;
pub use hal::empty::Api as Empty;
/*
#[cfg(dx11)]
pub use gfx_backend_dx11::Backend as Dx11;
#[cfg(dx12)]
@@ -39,6 +39,7 @@ pub mod backend {
pub use gfx_backend_metal::Backend as Metal;
#[cfg(vulkan)]
pub use gfx_backend_vulkan::Backend as Vulkan;
*/
}
pub mod binding_model;
@@ -64,8 +65,6 @@ use atomic::{AtomicUsize, Ordering};
use std::{borrow::Cow, os::raw::c_char, ptr};
pub const MAX_BIND_GROUPS: usize = 8;
type SubmissionIndex = usize;
type Index = u32;
type Epoch = u32;
@@ -230,13 +229,6 @@ struct Stored<T> {
ref_count: RefCount,
}
#[derive(Clone, Copy, Debug)]
struct PrivateFeatures {
anisotropic_filtering: bool,
texture_d24: bool,
texture_d24_s8: bool,
}
const DOWNLEVEL_WARNING_MESSAGE: &str = "The underlying API or device in use does not \
support enough features to be a fully compliant implementation of WebGPU. A subset of the features can still be used. \
If you are running this program on native and not in a browser and wish to limit the features you use to the supported subset, \
@@ -254,6 +246,7 @@ macro_rules! gfx_select {
// Note: For some reason the cfg aliases defined in build.rs don't succesfully apply in this
// macro so we must specify their equivalents manually
match $id.backend() {
/*
#[cfg(all(not(target_arch = "wasm32"), not(target_os = "ios"), not(target_os = "macos")))]
wgt::Backend::Vulkan => $global.$method::<$crate::backend::Vulkan>( $($param),* ),
#[cfg(all(not(target_arch = "wasm32"), any(target_os = "ios", target_os = "macos")))]
@@ -264,7 +257,9 @@ macro_rules! gfx_select {
wgt::Backend::Dx11 => $global.$method::<$crate::backend::Dx11>( $($param),* ),
#[cfg(any(target_arch = "wasm32", all(unix, not(any(target_os = "ios", target_os = "macos")))))]
wgt::Backend::Gl => $global.$method::<$crate::backend::Gl>( $($param),+ ),
*/
other => panic!("Unexpected backend {:?}", other),
}
};
}
@@ -274,9 +269,3 @@ type FastHashMap<K, V> =
std::collections::HashMap<K, V, std::hash::BuildHasherDefault<fxhash::FxHasher>>;
/// Fast hash set used internally.
type FastHashSet<K> = std::collections::HashSet<K, std::hash::BuildHasherDefault<fxhash::FxHasher>>;
#[test]
fn test_default_limits() {
let limits = wgt::Limits::default();
assert!(limits.max_bind_groups <= MAX_BIND_GROUPS as u32);
}
+6 -6
View File
@@ -29,7 +29,7 @@ pub struct ShaderModuleDescriptor<'a> {
}
#[derive(Debug)]
pub struct ShaderModule<B: hal::Backend> {
pub struct ShaderModule<A: hal::Api> {
pub(crate) raw: B::ShaderModule,
pub(crate) device_id: Stored<DeviceId>,
pub(crate) interface: Option<validation::Interface>,
@@ -37,7 +37,7 @@ pub struct ShaderModule<B: hal::Backend> {
pub(crate) label: String,
}
impl<B: hal::Backend> Resource for ShaderModule<B> {
impl<A: hal::Api> Resource for ShaderModule<A> {
const TYPE: &'static str = "ShaderModule";
fn life_guard(&self) -> &LifeGuard {
@@ -125,14 +125,14 @@ pub enum CreateComputePipelineError {
}
#[derive(Debug)]
pub struct ComputePipeline<B: hal::Backend> {
pub struct ComputePipeline<A: hal::Api> {
pub(crate) raw: B::ComputePipeline,
pub(crate) layout_id: Stored<PipelineLayoutId>,
pub(crate) device_id: Stored<DeviceId>,
pub(crate) life_guard: LifeGuard,
}
impl<B: hal::Backend> Resource for ComputePipeline<B> {
impl<A: hal::Api> Resource for ComputePipeline<A> {
const TYPE: &'static str = "ComputePipeline";
fn life_guard(&self) -> &LifeGuard {
@@ -289,7 +289,7 @@ bitflags::bitflags! {
}
#[derive(Debug)]
pub struct RenderPipeline<B: hal::Backend> {
pub struct RenderPipeline<A: hal::Api> {
pub(crate) raw: B::GraphicsPipeline,
pub(crate) layout_id: Stored<PipelineLayoutId>,
pub(crate) device_id: Stored<DeviceId>,
@@ -300,7 +300,7 @@ pub struct RenderPipeline<B: hal::Backend> {
pub(crate) life_guard: LifeGuard,
}
impl<B: hal::Backend> Resource for RenderPipeline<B> {
impl<A: hal::Api> Resource for RenderPipeline<A> {
const TYPE: &'static str = "RenderPipeline";
fn life_guard(&self) -> &LifeGuard {
+37 -45
View File
@@ -3,7 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::{
device::{alloc::MemoryBlock, DeviceError, HostMap, MissingFeatures},
device::{DeviceError, HostMap, MissingFeatures},
hub::Resource,
id::{DeviceId, SwapChainId, TextureId},
memory_init_tracker::MemoryInitTracker,
@@ -77,12 +77,11 @@ pub enum BufferMapAsyncStatus {
}
#[derive(Debug)]
pub(crate) enum BufferMapState<B: hal::Backend> {
pub(crate) enum BufferMapState<A: hal::Api> {
/// Mapped at creation.
Init {
ptr: NonNull<u8>,
stage_buffer: B::Buffer,
stage_memory: MemoryBlock<B>,
stage_buffer: A::Buffer,
needs_flush: bool,
},
/// Waiting for GPU to be done before mapping
@@ -90,15 +89,15 @@ pub(crate) enum BufferMapState<B: hal::Backend> {
/// Mapped
Active {
ptr: NonNull<u8>,
sub_range: hal::buffer::SubRange,
range: hal::MemoryRange,
host: HostMap,
},
/// Not mapped
Idle,
}
unsafe impl<B: hal::Backend> Send for BufferMapState<B> {}
unsafe impl<B: hal::Backend> Sync for BufferMapState<B> {}
unsafe impl<A: hal::Api> Send for BufferMapState<A> {}
unsafe impl<A: hal::Api> Sync for BufferMapState<A> {}
pub type BufferMapCallback = unsafe extern "C" fn(status: BufferMapAsyncStatus, userdata: *mut u8);
@@ -170,15 +169,16 @@ pub(crate) struct BufferPendingMapping {
pub type BufferDescriptor<'a> = wgt::BufferDescriptor<Label<'a>>;
#[derive(Debug)]
pub struct Buffer<B: hal::Backend> {
pub(crate) raw: Option<(B::Buffer, MemoryBlock<B>)>,
pub struct Buffer<A: hal::Api> {
pub(crate) raw: Option<A::Buffer>,
pub(crate) device_id: Stored<DeviceId>,
pub(crate) is_coherent: bool,
pub(crate) usage: wgt::BufferUsage,
pub(crate) size: wgt::BufferAddress,
pub(crate) initialization_status: MemoryInitTracker,
pub(crate) sync_mapped_writes: Option<hal::memory::Segment>,
pub(crate) sync_mapped_writes: Option<hal::MemoryRange>,
pub(crate) life_guard: LifeGuard,
pub(crate) map_state: BufferMapState<B>,
pub(crate) map_state: BufferMapState<A>,
}
#[derive(Clone, Debug, Error)]
@@ -195,7 +195,7 @@ pub enum CreateBufferError {
UsageMismatch(wgt::BufferUsage),
}
impl<B: hal::Backend> Resource for Buffer<B> {
impl<A: hal::Api> Resource for Buffer<A> {
const TYPE: &'static str = "Buffer";
fn life_guard(&self) -> &LifeGuard {
@@ -203,7 +203,7 @@ impl<B: hal::Backend> Resource for Buffer<B> {
}
}
impl<B: hal::Backend> Borrow<()> for Buffer<B> {
impl<A: hal::Api> Borrow<()> for Buffer<A> {
fn borrow(&self) -> &() {
&DUMMY_SELECTOR
}
@@ -212,16 +212,11 @@ impl<B: hal::Backend> Borrow<()> for Buffer<B> {
pub type TextureDescriptor<'a> = wgt::TextureDescriptor<Label<'a>>;
#[derive(Debug)]
pub struct Texture<B: hal::Backend> {
pub(crate) raw: Option<(B::Image, MemoryBlock<B>)>,
pub struct Texture<A: hal::Api> {
pub(crate) raw: Option<A::Image>,
pub(crate) device_id: Stored<DeviceId>,
pub(crate) usage: wgt::TextureUsage,
pub(crate) aspects: hal::format::Aspects,
pub(crate) dimension: wgt::TextureDimension,
pub(crate) kind: hal::image::Kind,
pub(crate) format: wgt::TextureFormat,
pub(crate) desc: wgt::TextureDescriptor<()>,
pub(crate) format_features: wgt::TextureFormatFeatures,
pub(crate) framebuffer_attachment: hal::image::FramebufferAttachment,
pub(crate) full_range: TextureSelector,
pub(crate) life_guard: LifeGuard,
}
@@ -265,7 +260,7 @@ pub enum CreateTextureError {
MissingFeatures(wgt::TextureFormat, #[source] MissingFeatures),
}
impl<B: hal::Backend> Resource for Texture<B> {
impl<A: hal::Api> Resource for Texture<A> {
const TYPE: &'static str = "Texture";
fn life_guard(&self) -> &LifeGuard {
@@ -273,7 +268,7 @@ impl<B: hal::Backend> Resource for Texture<B> {
}
}
impl<B: hal::Backend> Borrow<TextureSelector> for Texture<B> {
impl<A: hal::Api> Borrow<TextureSelector> for Texture<A> {
fn borrow(&self) -> &TextureSelector {
&self.full_range
}
@@ -297,28 +292,25 @@ pub struct TextureViewDescriptor<'a> {
}
#[derive(Debug)]
pub(crate) enum TextureViewInner<B: hal::Backend> {
pub(crate) enum TextureViewInner<A: hal::Api> {
Native {
raw: B::ImageView,
raw: A::ImageView,
source_id: Stored<TextureId>,
},
SwapChain {
image: <B::Surface as hal::window::PresentationSurface<B>>::SwapchainImage,
raw: A::SwapChainTexture,
source_id: Stored<SwapChainId>,
},
}
#[derive(Debug)]
pub struct TextureView<B: hal::Backend> {
pub(crate) inner: TextureViewInner<B>,
pub struct TextureView<A: hal::Api> {
pub(crate) inner: TextureViewInner<A>,
//TODO: store device_id for quick access?
pub(crate) aspects: hal::format::Aspects,
pub(crate) format: wgt::TextureFormat,
pub(crate) desc: hal::TextureViewDescriptor<()>,
pub(crate) format_features: wgt::TextureFormatFeatures,
pub(crate) dimension: wgt::TextureViewDimension,
pub(crate) extent: wgt::Extent3d,
pub(crate) samples: hal::image::NumSamples,
pub(crate) framebuffer_attachment: hal::image::FramebufferAttachment,
pub(crate) samples: u32,
/// Internal use of this texture view when used as `BindingType::Texture`.
pub(crate) sampled_internal_use: TextureUse,
pub(crate) selector: TextureSelector,
@@ -353,8 +345,8 @@ pub enum CreateTextureViewError {
},
#[error("Aspect {requested:?} is not in the source texture ({total:?})")]
InvalidAspect {
requested: hal::format::Aspects,
total: hal::format::Aspects,
requested: hal::FormatAspect,
total: hal::FormatAspect,
},
}
@@ -364,7 +356,7 @@ pub enum TextureViewDestroyError {
SwapChainImage,
}
impl<B: hal::Backend> Resource for TextureView<B> {
impl<A: hal::Api> Resource for TextureView<A> {
const TYPE: &'static str = "TextureView";
fn life_guard(&self) -> &LifeGuard {
@@ -372,7 +364,7 @@ impl<B: hal::Backend> Resource for TextureView<B> {
}
}
impl<B: hal::Backend> Borrow<()> for TextureView<B> {
impl<A: hal::Api> Borrow<()> for TextureView<A> {
fn borrow(&self) -> &() {
&DUMMY_SELECTOR
}
@@ -423,8 +415,8 @@ impl Default for SamplerDescriptor<'_> {
}
#[derive(Debug)]
pub struct Sampler<B: hal::Backend> {
pub(crate) raw: B::Sampler,
pub struct Sampler<A: hal::Api> {
pub(crate) raw: A::Sampler,
pub(crate) device_id: Stored<DeviceId>,
pub(crate) life_guard: LifeGuard,
/// `true` if this is a comparison sampler
@@ -446,7 +438,7 @@ pub enum CreateSamplerError {
MissingFeatures(#[from] MissingFeatures),
}
impl<B: hal::Backend> Resource for Sampler<B> {
impl<A: hal::Api> Resource for Sampler<A> {
const TYPE: &'static str = "Sampler";
fn life_guard(&self) -> &LifeGuard {
@@ -454,7 +446,7 @@ impl<B: hal::Backend> Resource for Sampler<B> {
}
}
impl<B: hal::Backend> Borrow<()> for Sampler<B> {
impl<A: hal::Api> Borrow<()> for Sampler<A> {
fn borrow(&self) -> &() {
&DUMMY_SELECTOR
}
@@ -472,8 +464,8 @@ pub enum CreateQuerySetError {
}
#[derive(Debug)]
pub struct QuerySet<B: hal::Backend> {
pub(crate) raw: B::QueryPool,
pub struct QuerySet<A: hal::Api> {
pub(crate) raw: A::QuerySet,
pub(crate) device_id: Stored<DeviceId>,
pub(crate) life_guard: LifeGuard,
/// Amount of queries in the query set.
@@ -482,7 +474,7 @@ pub struct QuerySet<B: hal::Backend> {
pub(crate) elements: u32,
}
impl<B: hal::Backend> Resource for QuerySet<B> {
impl<A: hal::Api> Resource for QuerySet<A> {
const TYPE: &'static str = "QuerySet";
fn life_guard(&self) -> &LifeGuard {
@@ -490,7 +482,7 @@ impl<B: hal::Backend> Resource for QuerySet<B> {
}
}
impl<B: hal::Backend> Borrow<()> for QuerySet<B> {
impl<A: hal::Api> Borrow<()> for QuerySet<A> {
fn borrow(&self) -> &() {
&DUMMY_SELECTOR
}
+11 -11
View File
@@ -37,14 +37,14 @@ use crate::device::trace::Action;
use crate::{
conv,
device::DeviceError,
hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Input, Token},
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Input, Token},
id::{DeviceId, SwapChainId, TextureViewId, Valid},
resource,
track::TextureSelector,
LifeGuard, PrivateFeatures, Stored, SubmissionIndex,
LifeGuard, Stored, SubmissionIndex,
};
use hal::{queue::Queue as _, window::PresentationSurface as _};
use hal::{Queue as _, Surface as _};
use thiserror::Error;
use wgt::{SwapChainDescriptor, SwapChainStatus};
@@ -52,7 +52,7 @@ const FRAME_TIMEOUT_MS: u64 = 1000;
pub const DESIRED_NUM_FRAMES: u32 = 3;
#[derive(Debug)]
pub struct SwapChain<B: hal::Backend> {
pub struct SwapChain<A: hal::Api> {
pub(crate) life_guard: LifeGuard,
pub(crate) device_id: Stored<DeviceId>,
pub(crate) desc: SwapChainDescriptor,
@@ -63,7 +63,7 @@ pub struct SwapChain<B: hal::Backend> {
pub(crate) framebuffer_attachment: hal::image::FramebufferAttachment,
}
impl<B: hal::Backend> crate::hub::Resource for SwapChain<B> {
impl<A: hal::Api> crate::hub::Resource for SwapChain<A> {
const TYPE: &'static str = "SwapChain";
fn life_guard(&self) -> &LifeGuard {
@@ -116,7 +116,7 @@ pub(crate) fn swap_chain_descriptor_to_hal(
num_frames,
);
//TODO: check for supported
config.image_usage = conv::map_texture_usage(desc.usage, hal::format::Aspects::COLOR);
config.image_usage = conv::map_texture_usage(desc.usage, hal::FormatAspect::COLOR);
config.composite_alpha_mode = hal::window::CompositeAlphaMode::OPAQUE;
config.present_mode = match desc.present_mode {
wgt::PresentMode::Immediate => hal::window::PresentMode::IMMEDIATE,
@@ -134,14 +134,14 @@ pub struct SwapChainOutput {
}
impl<G: GlobalIdentityHandlerFactory> Global<G> {
pub fn swap_chain_get_current_texture_view<B: GfxBackend>(
pub fn swap_chain_get_current_texture_view<A: HalApi>(
&self,
swap_chain_id: SwapChainId,
view_id_in: Input<G, TextureViewId>,
) -> Result<SwapChainOutput, SwapChainError> {
profiling::scope!("get_next_texture", "SwapChain");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let fid = hub.texture_views.prepare(view_id_in);
@@ -195,7 +195,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
ref_count: sc.life_guard.add_ref(),
},
},
aspects: hal::format::Aspects::COLOR,
aspects: hal::FormatAspect::COLOR,
format: sc.desc.format,
format_features: wgt::TextureFormatFeatures {
allowed_usages: wgt::TextureUsage::RENDER_ATTACHMENT,
@@ -238,13 +238,13 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
Ok(SwapChainOutput { status, view_id })
}
pub fn swap_chain_present<B: GfxBackend>(
pub fn swap_chain_present<A: HalApi>(
&self,
swap_chain_id: SwapChainId,
) -> Result<SwapChainStatus, SwapChainError> {
profiling::scope!("present", "SwapChain");
let hub = B::hub(self);
let hub = A::hub(self);
let mut token = Token::root();
let (mut surface_guard, mut token) = self.surfaces.write(&mut token);
+4 -4
View File
@@ -126,9 +126,9 @@ pub(crate) struct PendingTransition<S: ResourceState> {
impl PendingTransition<BufferState> {
/// Produce the gfx-hal barrier corresponding to the transition.
pub fn into_hal<'a, B: hal::Backend>(
pub fn into_hal<'a, A: hal::Api>(
self,
buf: &'a resource::Buffer<B>,
buf: &'a resource::Buffer<A>,
) -> hal::memory::Barrier<'a, B> {
log::trace!("\tbuffer -> {:?}", self);
let &(ref target, _) = buf.raw.as_ref().expect("Buffer is destroyed");
@@ -153,9 +153,9 @@ impl From<PendingTransition<BufferState>> for UsageConflict {
impl PendingTransition<TextureState> {
/// Produce the gfx-hal barrier corresponding to the transition.
pub fn into_hal<'a, B: hal::Backend>(
pub fn into_hal<'a, A: hal::Api>(
self,
tex: &'a resource::Texture<B>,
tex: &'a resource::Texture<A>,
) -> hal::memory::Barrier<'a, B> {
log::trace!("\ttexture -> {:?}", self);
let &(ref target, _) = tex.raw.as_ref().expect("Texture is destroyed");
+8 -9
View File
@@ -13,14 +13,13 @@ use arrayvec::ArrayVec;
use std::{iter, ops::Range};
//TODO: store `hal::image::State` here to avoid extra conversions
type PlaneStates = RangedStates<hal::image::Layer, Unit<TextureUse>>;
type PlaneStates = RangedStates<hal::ArrayLayer, Unit<TextureUse>>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextureSelector {
//pub aspects: hal::format::Aspects,
pub levels: Range<hal::image::Level>,
pub layers: Range<hal::image::Layer>,
//pub aspects: hal::FormatAspect,
pub levels: Range<hal::MipLevel>,
pub layers: Range<hal::ArrayLayer>,
}
#[derive(Clone, Debug, Default, PartialEq)]
@@ -44,7 +43,7 @@ impl PendingTransition<TextureState> {
}
impl TextureState {
pub fn new(mip_level_count: hal::image::Level, array_layer_count: hal::image::Layer) -> Self {
pub fn new(mip_level_count: hal::MipLevel, array_layer_count: hal::ArrayLayer) -> Self {
Self {
mips: iter::repeat_with(|| {
PlaneStates::from_range(0..array_layer_count, Unit::new(TextureUse::UNINITIALIZED))
@@ -104,7 +103,7 @@ impl ResourceState for TextureState {
.iter_mut()
.enumerate()
{
let level = selector.levels.start + mip_id as hal::image::Level;
let level = selector.levels.start + mip_id as hal::MipLevel;
let layers = mip.isolate(&selector.layers, Unit::new(usage));
for &mut (ref range, ref mut unit) in layers {
if unit.last == usage && TextureUse::ORDERED.contains(usage) {
@@ -154,7 +153,7 @@ impl ResourceState for TextureState {
.iter_mut()
.enumerate()
{
let level = selector.levels.start + mip_id as hal::image::Level;
let level = selector.levels.start + mip_id as hal::MipLevel;
let layers = mip.isolate(&selector.layers, Unit::new(usage));
for &mut (ref range, ref mut unit) in layers {
match unit.first {
@@ -193,7 +192,7 @@ impl ResourceState for TextureState {
}
for (mip_id, (mip_self, mip_other)) in self.mips.iter_mut().zip(&other.mips).enumerate() {
let level = mip_id as hal::image::Level;
let level = mip_id as hal::MipLevel;
temp.extend(mip_self.merge(mip_other, 0));
mip_self.clear();
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "wgpu-hal"
version = "0.1.0"
authors = ["wgpu developers"]
edition = "2018"
description = "WebGPU hardware abstraction layer"
homepage = "https://github.com/gfx-rs/wgpu"
repository = "https://github.com/gfx-rs/wgpu"
keywords = ["graphics"]
license = "MPL-2.0"
[lib]
[features]
[dependencies]
bitflags = "1.0"
wgt = { package = "wgpu-types", path = "../wgpu-types" }
+130
View File
@@ -0,0 +1,130 @@
pub struct Api;
pub struct Surface;
pub struct Adapter;
pub struct Queue;
pub struct Device;
pub struct CommandBuffer;
pub struct RenderPass;
pub struct ComputePass;
pub struct Resource;
impl crate::Surface<Api> for Surface {}
impl crate::Adapter<Api> for Adapter {
unsafe fn open(
&self,
_features: wgt::Features,
) -> Result<crate::OpenDevice<Api>, crate::Error> {
Err(crate::Error::DeviceLost)
}
unsafe fn close(&self, _device: Device) {}
unsafe fn texture_format_capabilities(
&self,
_format: wgt::TextureFormat,
) -> crate::TextureFormatCapability {
crate::TextureFormatCapability::empty()
}
unsafe fn surface_formats(&self, _surface: &Surface) -> Vec<wgt::TextureFormat> {
Vec::new()
}
}
impl crate::Queue<Api> for Queue {
unsafe fn submit<I: Iterator<Item = CommandBuffer>>(&mut self, _command_buffers: I) {}
}
impl crate::Device<Api> for Device {
unsafe fn create_buffer(
&self,
_desc: &wgt::BufferDescriptor<crate::Label>,
) -> Result<Resource, crate::Error> {
Ok(Resource)
}
unsafe fn destroy_buffer(&self, _buffer: Resource) {}
unsafe fn map_buffer(
&self,
_buffer: &Resource,
_range: crate::MemoryRange,
) -> Result<std::ptr::NonNull<u8>, crate::Error> {
Err(crate::Error::DeviceLost)
}
unsafe fn unmap_buffer(&self, _buffer: &Resource) {}
unsafe fn flush_mapped_ranges<I: Iterator<Item = crate::MemoryRange>>(
&self,
_buffer: &Resource,
_ranges: I,
) {
}
unsafe fn invalidate_mapped_ranges<I: Iterator<Item = crate::MemoryRange>>(
&self,
_buffer: &Resource,
_ranges: I,
) {
}
unsafe fn create_texture(
&self,
_desc: &wgt::TextureDescriptor<crate::Label>,
) -> Result<Resource, crate::Error> {
Ok(Resource)
}
unsafe fn destroy_texture(&self, _texture: Resource) {}
unsafe fn create_texture_view(
&self,
_texture: &Resource,
_desc: &crate::TextureViewDescriptor<crate::Label>,
) -> Result<Resource, crate::Error> {
Ok(Resource)
}
unsafe fn destroy_texture_view(&self, _view: Resource) {}
unsafe fn create_sampler(
&self,
desc: &crate::SamplerDescriptor<crate::Label>,
) -> Result<Resource, crate::Error> {
Ok(Resource)
}
unsafe fn destroy_sampler(&self, _sampler: Resource) {}
unsafe fn create_command_buffer(&self) -> Result<CommandBuffer, crate::Error> {
Ok(CommandBuffer)
}
}
impl crate::CommandBuffer<Api> for CommandBuffer {
unsafe fn begin(&mut self) {}
unsafe fn end(&mut self) {}
unsafe fn begin_render_pass(&mut self) -> RenderPass {
RenderPass
}
unsafe fn end_render_pass(&mut self, _pass: RenderPass) {}
unsafe fn begin_compute_pass(&mut self) -> ComputePass {
ComputePass
}
unsafe fn end_compute_pass(&mut self, _pass: ComputePass) {}
}
impl crate::RenderPass<Api> for RenderPass {}
impl crate::ComputePass<Api> for ComputePass {}
impl crate::Api for Api {
type Surface = Surface;
type Adapter = Adapter;
type Queue = Queue;
type Device = Device;
type CommandBuffer = CommandBuffer;
type RenderPass = RenderPass;
type ComputePass = ComputePass;
type Buffer = Resource;
type QuerySet = Resource;
type Texture = Resource;
type SwapChainTexture = Resource;
type TextureView = Resource;
type Sampler = Resource;
unsafe fn enumerate_adapters(&self) -> Vec<crate::ExposedAdapter<Api>> {
Vec::new()
}
}
+248
View File
@@ -0,0 +1,248 @@
/* 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/. */
/*! This library describes the internal unsafe graphics abstraction API.
*/
pub mod empty;
use std::{fmt, num::NonZeroU8, ops::Range, ptr::NonNull};
use bitflags::bitflags;
pub const MAX_ANISOTROPY: u8 = 16;
pub const MAX_BIND_GROUPS: usize = 8;
pub type Label<'a> = Option<&'a str>;
pub type MemoryRange = Range<wgt::BufferAddress>;
pub type MipLevel = u8;
pub type ArrayLayer = u16;
#[derive(Debug)]
pub enum Error {
OutOfMemory,
DeviceLost,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::OutOfMemory => write!(f, "out of memory"),
Self::DeviceLost => write!(f, "device is lost"),
}
}
}
impl std::error::Error for Error {}
pub trait Api: Sized {
type Surface: Surface<Self>;
type Adapter: Adapter<Self>;
type Device: Device<Self>;
type Queue: Queue<Self>;
type CommandBuffer: CommandBuffer<Self>;
type RenderPass: RenderPass<Self>;
type ComputePass: ComputePass<Self>;
type Buffer;
type QuerySet;
type Texture;
type SwapChainTexture;
type TextureView;
type Sampler;
unsafe fn enumerate_adapters(&self) -> Vec<ExposedAdapter<Self>>;
}
pub trait Surface<A: Api> {}
pub trait Adapter<A: Api> {
unsafe fn open(&self, features: wgt::Features) -> Result<OpenDevice<A>, Error>;
unsafe fn close(&self, device: A::Device);
/// Return the set of supported capabilities for a texture format.
unsafe fn texture_format_capabilities(
&self,
format: wgt::TextureFormat,
) -> TextureFormatCapability;
/// Returns the list of surface formats supported for presentation, if any.
unsafe fn surface_formats(&self, surface: &A::Surface) -> Vec<wgt::TextureFormat>;
}
pub trait Device<A: Api> {
unsafe fn create_buffer(&self, desc: &wgt::BufferDescriptor<Label>)
-> Result<A::Buffer, Error>;
unsafe fn destroy_buffer(&self, buffer: A::Buffer);
unsafe fn map_buffer(
&self,
buffer: &A::Buffer,
range: MemoryRange,
) -> Result<NonNull<u8>, Error>;
unsafe fn unmap_buffer(&self, buffer: &A::Buffer);
unsafe fn flush_mapped_ranges<I: Iterator<Item = MemoryRange>>(
&self,
buffer: &A::Buffer,
ranges: I,
);
unsafe fn invalidate_mapped_ranges<I: Iterator<Item = MemoryRange>>(
&self,
buffer: &A::Buffer,
ranges: I,
);
unsafe fn create_texture(
&self,
desc: &wgt::TextureDescriptor<Label>,
) -> Result<A::Texture, Error>;
unsafe fn destroy_texture(&self, texture: A::Texture);
unsafe fn create_texture_view(
&self,
texture: &A::Texture,
desc: &TextureViewDescriptor<Label>,
) -> Result<A::TextureView, Error>;
unsafe fn destroy_texture_view(&self, view: A::TextureView);
unsafe fn create_sampler(&self, desc: &SamplerDescriptor<Label>) -> Result<A::Sampler, Error>;
unsafe fn destroy_sampler(&self, sampler: A::Sampler);
unsafe fn create_command_buffer(&self) -> Result<A::CommandBuffer, Error>;
}
pub trait Queue<A: Api> {
unsafe fn submit<I: Iterator<Item = A::CommandBuffer>>(&mut self, command_buffers: I);
}
pub trait CommandBuffer<A: Api> {
unsafe fn begin(&mut self);
unsafe fn end(&mut self);
unsafe fn begin_render_pass(&mut self) -> A::RenderPass;
unsafe fn end_render_pass(&mut self, pass: A::RenderPass);
unsafe fn begin_compute_pass(&mut self) -> A::ComputePass;
unsafe fn end_compute_pass(&mut self, pass: A::ComputePass);
}
pub trait RenderPass<A: Api> {}
pub trait ComputePass<A: Api> {}
#[derive(Debug)]
pub struct Alignments {
/// The alignment of the start of the buffer used as a GPU copy source.
pub buffer_copy_offset: wgt::BufferSize,
/// The alignment of the row pitch of the texture data stored in a buffer that is
/// used in a GPU copy operation.
pub buffer_copy_pitch: wgt::BufferSize,
pub storage_buffer_offset: wgt::BufferSize,
pub uniform_buffer_offset: wgt::BufferSize,
}
#[derive(Debug)]
pub struct Capabilities {
pub limits: wgt::Limits,
pub alignments: Alignments,
pub downlevel: wgt::DownlevelCapabilities,
}
#[derive(Debug)]
pub struct ExposedAdapter<A: Api> {
pub adapter: A::Adapter,
pub info: wgt::AdapterInfo,
pub features: wgt::Features,
pub capabilities: Capabilities,
}
#[derive(Debug)]
pub struct OpenDevice<A: Api> {
pub device: A::Device,
pub queue: A::Queue,
}
bitflags!(
/// Texture format capability flags.
pub struct TextureFormatCapability: u32 {
/// Format can be sampled.
const SAMPLED = 0x1;
/// Format can be sampled with a linear sampler.
const SAMPLED_LINEAR = 0x2;
/// Format can be sampled with a min/max reduction sampler.
const SAMPLED_MINMAX = 0x4;
/// Format can be used as storage with exclusive read & write access.
const STORAGE = 0x10;
/// Format can be used as storage with simultaneous read/write access.
const STORAGE_READ_WRITE = 0x20;
/// Format can be used as storage with atomics.
const STORAGE_ATOMIC = 0x40;
/// Format can be used as color and input attachment.
const COLOR_ATTACHMENT = 0x100;
/// Format can be used as color (with blending) and input attachment.
const COLOR_ATTACHMENT_BLEND = 0x200;
/// Format can be used as depth-stencil and input attachment.
const DEPTH_STENCIL_ATTACHMENT = 0x400;
/// Format can be copied from.
const COPY_SRC = 0x1000;
/// Format can be copied to.
const COPY_DST = 0x2000;
}
);
bitflags!(
/// Texture format capability flags.
pub struct FormatAspect: u8 {
const COLOR = 1;
const DEPTH = 2;
const STENCIL = 4;
}
);
impl From<wgt::TextureFormat> for FormatAspect {
fn from(format: wgt::TextureFormat) -> Self {
match format {
wgt::TextureFormat::Depth32Float | wgt::TextureFormat::Depth24Plus => Self::DEPTH,
wgt::TextureFormat::Depth24PlusStencil8 => Self::DEPTH | Self::STENCIL,
_ => Self::COLOR,
}
}
}
#[derive(Clone, Debug)]
pub struct TextureViewDescriptor<L> {
pub label: L,
pub format: wgt::TextureFormat,
pub dimension: wgt::TextureViewDimension,
pub range: wgt::ImageSubresourceRange,
}
impl<L> TextureViewDescriptor<L> {
///
pub fn map_label<K>(&self, fun: impl FnOnce(&L) -> K) -> TextureViewDescriptor<K> {
TextureViewDescriptor {
label: fun(&self.label),
format: self.format,
dimension: self.dimension,
range: self.range.clone(),
}
}
}
/// Describes a [`Sampler`]
#[derive(Clone, Debug)]
pub struct SamplerDescriptor<L> {
pub label: L,
pub address_modes: [wgt::AddressMode; 3],
pub mag_filter: wgt::FilterMode,
pub min_filter: wgt::FilterMode,
pub mipmap_filter: wgt::FilterMode,
pub lod_clamp: Option<Range<f32>>,
pub compare: Option<wgt::CompareFunction>,
pub anisotropy_clamp: Option<NonZeroU8>,
pub border_color: Option<wgt::SamplerBorderColor>,
}
#[test]
fn test_default_limits() {
let limits = wgt::Limits::default();
assert!(limits.max_bind_groups <= MAX_BIND_GROUPS as u32);
}
+3 -5
View File
@@ -650,16 +650,14 @@ impl Default for Limits {
/// Lists various ways the underlying platform does not conform to the WebGPU standard.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DownlevelProperties {
pub struct DownlevelCapabilities {
/// Combined boolean flags.
pub flags: DownlevelFlags,
/// Which collections of features shaders support. Defined in terms of D3D's shader models.
pub shader_model: ShaderModel,
}
impl Default for DownlevelProperties {
// Note, this defaults to all on, as that is the default assumption in wgpu.
// gfx-hal's equivalent structure defaults to all off.
impl Default for DownlevelCapabilities {
fn default() -> Self {
Self {
flags: DownlevelFlags::COMPLIANT,
@@ -668,7 +666,7 @@ impl Default for DownlevelProperties {
}
}
impl DownlevelProperties {
impl DownlevelCapabilities {
/// Returns true if the underlying platform offers complete support of the baseline WebGPU standard.
///
/// If this returns false, some parts of the API will result in validation errors where they would not normally.
-2
View File
@@ -20,8 +20,6 @@ default = []
trace = ["serde", "wgc/trace"]
replay = ["serde", "wgc/replay"]
webgl = ["wgc"]
# Enable SPIRV-Cross
cross = ["wgc/cross"]
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.wgc]
package = "wgpu-core"
+3 -3
View File
@@ -2,7 +2,7 @@ use crate::{
backend::{error::ContextError, native_gpu_future},
AdapterInfo, BindGroupDescriptor, BindGroupLayoutDescriptor, BindingResource, BufferBinding,
CommandEncoderDescriptor, ComputePassDescriptor, ComputePipelineDescriptor,
DownlevelProperties, Features, Label, Limits, LoadOp, MapMode, Operations,
DownlevelCapabilities, Features, Label, Limits, LoadOp, MapMode, Operations,
PipelineLayoutDescriptor, RenderBundleEncoderDescriptor, RenderPipelineDescriptor,
SamplerDescriptor, ShaderModuleDescriptor, ShaderSource, SwapChainStatus, TextureDescriptor,
TextureFormat, TextureViewDescriptor,
@@ -731,7 +731,7 @@ impl crate::Context for Context {
}
}
fn adapter_downlevel_properties(&self, adapter: &Self::AdapterId) -> DownlevelProperties {
fn adapter_downlevel_properties(&self, adapter: &Self::AdapterId) -> DownlevelCapabilities {
let global = &self.0;
match wgc::gfx_select!(*adapter => global.adapter_downlevel_properties(*adapter)) {
Ok(downlevel) => downlevel,
@@ -776,7 +776,7 @@ impl crate::Context for Context {
}
}
fn device_downlevel_properties(&self, device: &Self::DeviceId) -> DownlevelProperties {
fn device_downlevel_properties(&self, device: &Self::DeviceId) -> DownlevelCapabilities {
let global = &self.0;
match wgc::gfx_select!(device.id => global.device_downlevel_properties(device.id)) {
Ok(limits) => limits,
+7 -4
View File
@@ -1080,9 +1080,12 @@ impl crate::Context for Context {
}
}
fn adapter_downlevel_properties(&self, _adapter: &Self::AdapterId) -> wgt::DownlevelProperties {
fn adapter_downlevel_properties(
&self,
_adapter: &Self::AdapterId,
) -> wgt::DownlevelCapabilities {
// WebGPU is assumed to be fully compliant
wgt::DownlevelProperties::default()
wgt::DownlevelCapabilities::default()
}
fn adapter_get_info(&self, _adapter: &Self::AdapterId) -> wgt::AdapterInfo {
@@ -1114,9 +1117,9 @@ impl crate::Context for Context {
wgt::Limits::default()
}
fn device_downlevel_properties(&self, _device: &Self::DeviceId) -> wgt::DownlevelProperties {
fn device_downlevel_properties(&self, _device: &Self::DeviceId) -> wgt::DownlevelCapabilities {
// WebGPU is assumed to be fully compliant
wgt::DownlevelProperties::default()
wgt::DownlevelCapabilities::default()
}
fn device_create_swap_chain(
+4 -4
View File
@@ -28,8 +28,8 @@ pub use wgt::{
AdapterInfo, AddressMode, Backend, BackendBit, BindGroupLayoutEntry, BindingType,
BlendComponent, BlendFactor, BlendOperation, BlendState, BufferAddress, BufferBindingType,
BufferSize, BufferUsage, Color, ColorTargetState, ColorWrite, CommandBufferDescriptor,
CompareFunction, DepthBiasState, DepthStencilState, DeviceType, DownlevelFlags,
DownlevelProperties, DynamicOffset, Extent3d, Face, Features, FilterMode, FrontFace,
CompareFunction, DepthBiasState, DepthStencilState, DeviceType, DownlevelCapabilities,
DownlevelFlags, DynamicOffset, Extent3d, Face, Features, FilterMode, FrontFace,
ImageDataLayout, IndexFormat, InputStepMode, Limits, MultisampleState, Origin3d,
PipelineStatisticsTypes, PolygonMode, PowerPreference, PresentMode, PrimitiveState,
PrimitiveTopology, PushConstantRange, QuerySetDescriptor, QueryType, SamplerBorderColor,
@@ -206,7 +206,7 @@ trait Context: Debug + Send + Sized + Sync {
) -> Option<TextureFormat>;
fn adapter_features(&self, adapter: &Self::AdapterId) -> Features;
fn adapter_limits(&self, adapter: &Self::AdapterId) -> Limits;
fn adapter_downlevel_properties(&self, adapter: &Self::AdapterId) -> DownlevelProperties;
fn adapter_downlevel_properties(&self, adapter: &Self::AdapterId) -> DownlevelCapabilities;
fn adapter_get_info(&self, adapter: &Self::AdapterId) -> AdapterInfo;
fn adapter_get_texture_format_features(
&self,
@@ -216,7 +216,7 @@ trait Context: Debug + Send + Sized + Sync {
fn device_features(&self, device: &Self::DeviceId) -> Features;
fn device_limits(&self, device: &Self::DeviceId) -> Limits;
fn device_downlevel_properties(&self, device: &Self::DeviceId) -> DownlevelProperties;
fn device_downlevel_properties(&self, device: &Self::DeviceId) -> DownlevelCapabilities;
fn device_create_swap_chain(
&self,
device: &Self::DeviceId,