| 1 |
/*! |
| 2 |
# Metal API internals. |
| 3 |
|
| 4 |
## Pipeline Layout |
| 5 |
|
| 6 |
In Metal, push constants, vertex buffers, and resources in the bind groups |
| 7 |
are all placed together in the native resource bindings, which work similarly to D3D11: |
| 8 |
there are tables of textures, buffers, and samplers. |
| 9 |
|
| 10 |
We put push constants first (if any) in the table, followed by bind group 0 |
| 11 |
resources, followed by other bind groups. The vertex buffers are bound at the very |
| 12 |
end of the VS buffer table. |
| 13 |
|
| 14 |
!*/ |
| 15 |
|
| 16 |
// `MTLFeatureSet` is superseded by `MTLGpuFamily`. |
| 17 |
// However, `MTLGpuFamily` is only supported starting MacOS 10.15, whereas our minimum target is MacOS 10.13, |
| 18 |
// See https://github.com/gpuweb/gpuweb/issues/1069 for minimum spec. |
| 19 |
// TODO: Eventually all deprecated features should be abstracted and use new api when available. |
| 20 |
#[allow(deprecated)] |
| 21 |
mod adapter; |
| 22 |
mod command; |
| 23 |
mod conv; |
| 24 |
mod device; |
| 25 |
mod layer_observer; |
| 26 |
mod surface; |
| 27 |
mod time; |
| 28 |
|
| 29 |
use alloc::{borrow::ToOwned as _, string::String, sync::Arc, vec::Vec}; |
| 30 |
use core::{fmt, iter, ops, ptr::NonNull, sync::atomic}; |
| 31 |
use std::thread; |
| 32 |
|
| 33 |
use arrayvec::ArrayVec; |
| 34 |
use bitflags::bitflags; |
| 35 |
use hashbrown::HashMap; |
| 36 |
use metal::{ |
| 37 |
foreign_types::ForeignTypeRef as _, MTLArgumentBuffersTier, MTLBuffer, MTLCommandBufferStatus, |
| 38 |
MTLCullMode, MTLDepthClipMode, MTLIndexType, MTLLanguageVersion, MTLPrimitiveType, |
| 39 |
MTLReadWriteTextureTier, MTLRenderStages, MTLResource, MTLResourceUsage, MTLSamplerState, |
| 40 |
MTLSize, MTLTexture, MTLTextureType, MTLTriangleFillMode, MTLWinding, |
| 41 |
}; |
| 42 |
use naga::FastHashMap; |
| 43 |
use parking_lot::{Mutex, RwLock}; |
| 44 |
|
| 45 |
#[derive(Clone, Debug)] |
| 46 |
pub struct Api; |
| 47 |
|
| 48 |
type ResourceIndex = u32; |
| 49 |
|
| 50 |
impl crate::Api for Api { |
| 51 |
type Instance = Instance; |
| 52 |
type Surface = Surface; |
| 53 |
type Adapter = Adapter; |
| 54 |
type Device = Device; |
| 55 |
|
| 56 |
type Queue = Queue; |
| 57 |
type CommandEncoder = CommandEncoder; |
| 58 |
type CommandBuffer = CommandBuffer; |
| 59 |
|
| 60 |
type Buffer = Buffer; |
| 61 |
type Texture = Texture; |
| 62 |
type SurfaceTexture = SurfaceTexture; |
| 63 |
type TextureView = TextureView; |
| 64 |
type Sampler = Sampler; |
| 65 |
type QuerySet = QuerySet; |
| 66 |
type Fence = Fence; |
| 67 |
|
| 68 |
type BindGroupLayout = BindGroupLayout; |
| 69 |
type BindGroup = BindGroup; |
| 70 |
type PipelineLayout = PipelineLayout; |
| 71 |
type ShaderModule = ShaderModule; |
| 72 |
type RenderPipeline = RenderPipeline; |
| 73 |
type ComputePipeline = ComputePipeline; |
| 74 |
type PipelineCache = PipelineCache; |
| 75 |
|
| 76 |
type AccelerationStructure = AccelerationStructure; |
| 77 |
} |
| 78 |
|
| 79 |
crate::impl_dyn_resource!( |
| 80 |
Adapter, |
| 81 |
AccelerationStructure, |
| 82 |
BindGroup, |
| 83 |
BindGroupLayout, |
| 84 |
Buffer, |
| 85 |
CommandBuffer, |
| 86 |
CommandEncoder, |
| 87 |
ComputePipeline, |
| 88 |
Device, |
| 89 |
Fence, |
| 90 |
Instance, |
| 91 |
PipelineCache, |
| 92 |
PipelineLayout, |
| 93 |
QuerySet, |
| 94 |
Queue, |
| 95 |
RenderPipeline, |
| 96 |
Sampler, |
| 97 |
ShaderModule, |
| 98 |
Surface, |
| 99 |
SurfaceTexture, |
| 100 |
Texture, |
| 101 |
TextureView |
| 102 |
); |
| 103 |
|
| 104 |
pub struct Instance {} |
| 105 |
|
| 106 |
impl Instance { |
| 107 |
pub fn create_surface_from_layer(&self, layer: &metal::MetalLayerRef) -> Surface { |
| 108 |
unsafe { Surface::from_layer(layer) } |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
impl crate::Instance for Instance { |
| 113 |
type A = Api; |
| 114 |
|
| 115 |
unsafe fn init(_desc: &crate::InstanceDescriptor) -> Result<Self, crate::InstanceError> { |
| 116 |
profiling::scope!("Init Metal Backend"); |
| 117 |
// We do not enable metal validation based on the validation flags as it affects the entire |
| 118 |
// process. Instead, we enable the validation inside the test harness itself in tests/src/native.rs. |
| 119 |
Ok(Instance {}) |
| 120 |
} |
| 121 |
|
| 122 |
unsafe fn create_surface( |
| 123 |
&self, |
| 124 |
_display_handle: raw_window_handle::RawDisplayHandle, |
| 125 |
window_handle: raw_window_handle::RawWindowHandle, |
| 126 |
) -> Result<Surface, crate::InstanceError> { |
| 127 |
match window_handle { |
| 128 |
#[cfg(any(target_os = "ios", target_os = "visionos"))] |
| 129 |
raw_window_handle::RawWindowHandle::UiKit(handle) => { |
| 130 |
Ok(unsafe { Surface::from_view(handle.ui_view.cast()) }) |
| 131 |
} |
| 132 |
#[cfg(target_os = "macos")] |
| 133 |
raw_window_handle::RawWindowHandle::AppKit(handle) => { |
| 134 |
Ok(unsafe { Surface::from_view(handle.ns_view.cast()) }) |
| 135 |
} |
| 136 |
_ => Err(crate::InstanceError::new(format!( |
| 137 |
"window handle {window_handle:?} is not a Metal-compatible handle" |
| 138 |
))), |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
unsafe fn enumerate_adapters( |
| 143 |
&self, |
| 144 |
_surface_hint: Option<&Surface>, |
| 145 |
) -> Vec<crate::ExposedAdapter<Api>> { |
| 146 |
let devices = metal::Device::all(); |
| 147 |
let mut adapters: Vec<crate::ExposedAdapter<Api>> = devices |
| 148 |
.into_iter() |
| 149 |
.map(|dev| { |
| 150 |
let name = dev.name().into(); |
| 151 |
let shared = AdapterShared::new(dev); |
| 152 |
crate::ExposedAdapter { |
| 153 |
info: wgt::AdapterInfo { |
| 154 |
name, |
| 155 |
vendor: 0, |
| 156 |
device: 0, |
| 157 |
device_type: shared.private_caps.device_type(), |
| 158 |
driver: String::new(), |
| 159 |
driver_info: String::new(), |
| 160 |
backend: wgt::Backend::Metal, |
| 161 |
}, |
| 162 |
features: shared.private_caps.features(), |
| 163 |
capabilities: shared.private_caps.capabilities(), |
| 164 |
adapter: Adapter::new(Arc::new(shared)), |
| 165 |
} |
| 166 |
}) |
| 167 |
.collect(); |
| 168 |
adapters.sort_by_key(|ad| { |
| 169 |
( |
| 170 |
ad.adapter.shared.private_caps.low_power, |
| 171 |
ad.adapter.shared.private_caps.headless, |
| 172 |
) |
| 173 |
}); |
| 174 |
adapters |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
bitflags!( |
| 179 |
/// Similar to `MTLCounterSamplingPoint`, but a bit higher abstracted for our purposes. |
| 180 |
#[derive(Debug, Copy, Clone)] |
| 181 |
pub struct TimestampQuerySupport: u32 { |
| 182 |
/// On creating Metal encoders. |
| 183 |
const STAGE_BOUNDARIES = 1 << 1; |
| 184 |
/// Within existing draw encoders. |
| 185 |
const ON_RENDER_ENCODER = Self::STAGE_BOUNDARIES.bits() | (1 << 2); |
| 186 |
/// Within existing dispatch encoders. |
| 187 |
const ON_COMPUTE_ENCODER = Self::STAGE_BOUNDARIES.bits() | (1 << 3); |
| 188 |
/// Within existing blit encoders. |
| 189 |
const ON_BLIT_ENCODER = Self::STAGE_BOUNDARIES.bits() | (1 << 4); |
| 190 |
|
| 191 |
/// Within any wgpu render/compute pass. |
| 192 |
const INSIDE_WGPU_PASSES = Self::ON_RENDER_ENCODER.bits() | Self::ON_COMPUTE_ENCODER.bits(); |
| 193 |
} |
| 194 |
); |
| 195 |
|
| 196 |
#[allow(dead_code)] |
| 197 |
#[derive(Clone, Debug)] |
| 198 |
struct PrivateCapabilities { |
| 199 |
family_check: bool, |
| 200 |
msl_version: MTLLanguageVersion, |
| 201 |
fragment_rw_storage: bool, |
| 202 |
read_write_texture_tier: MTLReadWriteTextureTier, |
| 203 |
msaa_desktop: bool, |
| 204 |
msaa_apple3: bool, |
| 205 |
msaa_apple7: bool, |
| 206 |
resource_heaps: bool, |
| 207 |
argument_buffers: MTLArgumentBuffersTier, |
| 208 |
shared_textures: bool, |
| 209 |
mutable_comparison_samplers: bool, |
| 210 |
sampler_clamp_to_border: bool, |
| 211 |
indirect_draw_dispatch: bool, |
| 212 |
base_vertex_first_instance_drawing: bool, |
| 213 |
dual_source_blending: bool, |
| 214 |
low_power: bool, |
| 215 |
headless: bool, |
| 216 |
layered_rendering: bool, |
| 217 |
function_specialization: bool, |
| 218 |
depth_clip_mode: bool, |
| 219 |
texture_cube_array: bool, |
| 220 |
supports_float_filtering: bool, |
| 221 |
format_depth24_stencil8: bool, |
| 222 |
format_depth32_stencil8_filter: bool, |
| 223 |
format_depth32_stencil8_none: bool, |
| 224 |
format_min_srgb_channels: u8, |
| 225 |
format_b5: bool, |
| 226 |
format_bc: bool, |
| 227 |
format_eac_etc: bool, |
| 228 |
format_astc: bool, |
| 229 |
format_astc_hdr: bool, |
| 230 |
format_astc_3d: bool, |
| 231 |
format_any8_unorm_srgb_all: bool, |
| 232 |
format_any8_unorm_srgb_no_write: bool, |
| 233 |
format_any8_snorm_all: bool, |
| 234 |
format_r16_norm_all: bool, |
| 235 |
format_r32_all: bool, |
| 236 |
format_r32_no_write: bool, |
| 237 |
format_r32float_no_write_no_filter: bool, |
| 238 |
format_r32float_no_filter: bool, |
| 239 |
format_r32float_all: bool, |
| 240 |
format_rgba8_srgb_all: bool, |
| 241 |
format_rgba8_srgb_no_write: bool, |
| 242 |
format_rgb10a2_unorm_all: bool, |
| 243 |
format_rgb10a2_unorm_no_write: bool, |
| 244 |
format_rgb10a2_uint_write: bool, |
| 245 |
format_rg11b10_all: bool, |
| 246 |
format_rg11b10_no_write: bool, |
| 247 |
format_rgb9e5_all: bool, |
| 248 |
format_rgb9e5_no_write: bool, |
| 249 |
format_rgb9e5_filter_only: bool, |
| 250 |
format_rg32_color: bool, |
| 251 |
format_rg32_color_write: bool, |
| 252 |
format_rg32float_all: bool, |
| 253 |
format_rg32float_color_blend: bool, |
| 254 |
format_rg32float_no_filter: bool, |
| 255 |
format_rgba32int_color: bool, |
| 256 |
format_rgba32int_color_write: bool, |
| 257 |
format_rgba32float_color: bool, |
| 258 |
format_rgba32float_color_write: bool, |
| 259 |
format_rgba32float_all: bool, |
| 260 |
format_depth16unorm: bool, |
| 261 |
format_depth32float_filter: bool, |
| 262 |
format_depth32float_none: bool, |
| 263 |
format_bgr10a2_all: bool, |
| 264 |
format_bgr10a2_no_write: bool, |
| 265 |
max_buffers_per_stage: ResourceIndex, |
| 266 |
max_vertex_buffers: ResourceIndex, |
| 267 |
max_textures_per_stage: ResourceIndex, |
| 268 |
max_samplers_per_stage: ResourceIndex, |
| 269 |
max_binding_array_elements: ResourceIndex, |
| 270 |
max_sampler_binding_array_elements: ResourceIndex, |
| 271 |
buffer_alignment: u64, |
| 272 |
max_buffer_size: u64, |
| 273 |
max_texture_size: u64, |
| 274 |
max_texture_3d_size: u64, |
| 275 |
max_texture_layers: u64, |
| 276 |
max_fragment_input_components: u64, |
| 277 |
max_color_render_targets: u8, |
| 278 |
max_color_attachment_bytes_per_sample: u8, |
| 279 |
max_varying_components: u32, |
| 280 |
max_threads_per_group: u32, |
| 281 |
max_total_threadgroup_memory: u32, |
| 282 |
sample_count_mask: crate::TextureFormatCapabilities, |
| 283 |
supports_debug_markers: bool, |
| 284 |
supports_binary_archives: bool, |
| 285 |
supports_capture_manager: bool, |
| 286 |
can_set_maximum_drawables_count: bool, |
| 287 |
can_set_display_sync: bool, |
| 288 |
can_set_next_drawable_timeout: bool, |
| 289 |
supports_arrays_of_textures: bool, |
| 290 |
supports_arrays_of_textures_write: bool, |
| 291 |
supports_mutability: bool, |
| 292 |
supports_depth_clip_control: bool, |
| 293 |
supports_preserve_invariance: bool, |
| 294 |
supports_shader_primitive_index: bool, |
| 295 |
has_unified_memory: Option<bool>, |
| 296 |
timestamp_query_support: TimestampQuerySupport, |
| 297 |
supports_simd_scoped_operations: bool, |
| 298 |
int64: bool, |
| 299 |
int64_atomics: bool, |
| 300 |
float_atomics: bool, |
| 301 |
supports_shared_event: bool, |
| 302 |
} |
| 303 |
|
| 304 |
#[derive(Clone, Debug)] |
| 305 |
struct PrivateDisabilities { |
| 306 |
/// Near depth is not respected properly on some Intel GPUs. |
| 307 |
broken_viewport_near_depth: bool, |
| 308 |
/// Multi-target clears don't appear to work properly on Intel GPUs. |
| 309 |
#[allow(dead_code)] |
| 310 |
broken_layered_clear_image: bool, |
| 311 |
} |
| 312 |
|
| 313 |
#[derive(Debug, Default)] |
| 314 |
struct Settings { |
| 315 |
retain_command_buffer_references: bool, |
| 316 |
} |
| 317 |
|
| 318 |
struct AdapterShared { |
| 319 |
device: Mutex<metal::Device>, |
| 320 |
disabilities: PrivateDisabilities, |
| 321 |
private_caps: PrivateCapabilities, |
| 322 |
settings: Settings, |
| 323 |
presentation_timer: time::PresentationTimer, |
| 324 |
} |
| 325 |
|
| 326 |
unsafe impl Send for AdapterShared {} |
| 327 |
unsafe impl Sync for AdapterShared {} |
| 328 |
|
| 329 |
impl AdapterShared { |
| 330 |
fn new(device: metal::Device) -> Self { |
| 331 |
let private_caps = PrivateCapabilities::new(&device); |
| 332 |
log::debug!("{:#?}", private_caps); |
| 333 |
|
| 334 |
Self { |
| 335 |
disabilities: PrivateDisabilities::new(&device), |
| 336 |
private_caps, |
| 337 |
device: Mutex::new(device), |
| 338 |
settings: Settings::default(), |
| 339 |
presentation_timer: time::PresentationTimer::new(), |
| 340 |
} |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
pub struct Adapter { |
| 345 |
shared: Arc<AdapterShared>, |
| 346 |
} |
| 347 |
|
| 348 |
pub struct Queue { |
| 349 |
raw: Arc<Mutex<metal::CommandQueue>>, |
| 350 |
timestamp_period: f32, |
| 351 |
} |
| 352 |
|
| 353 |
unsafe impl Send for Queue {} |
| 354 |
unsafe impl Sync for Queue {} |
| 355 |
|
| 356 |
impl Queue { |
| 357 |
pub unsafe fn queue_from_raw(raw: metal::CommandQueue, timestamp_period: f32) -> Self { |
| 358 |
Self { |
| 359 |
raw: Arc::new(Mutex::new(raw)), |
| 360 |
timestamp_period, |
| 361 |
} |
| 362 |
} |
| 363 |
|
| 364 |
pub fn as_raw(&self) -> &Arc<Mutex<metal::CommandQueue>> { |
| 365 |
&self.raw |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
pub struct Device { |
| 370 |
shared: Arc<AdapterShared>, |
| 371 |
features: wgt::Features, |
| 372 |
counters: Arc<wgt::HalCounters>, |
| 373 |
} |
| 374 |
|
| 375 |
pub struct Surface { |
| 376 |
render_layer: Mutex<metal::MetalLayer>, |
| 377 |
swapchain_format: RwLock<Option<wgt::TextureFormat>>, |
| 378 |
extent: RwLock<wgt::Extent3d>, |
| 379 |
main_thread_id: thread::ThreadId, |
| 380 |
// Useful for UI-intensive applications that are sensitive to |
| 381 |
// window resizing. |
| 382 |
pub present_with_transaction: bool, |
| 383 |
} |
| 384 |
|
| 385 |
unsafe impl Send for Surface {} |
| 386 |
unsafe impl Sync for Surface {} |
| 387 |
|
| 388 |
#[derive(Debug)] |
| 389 |
pub struct SurfaceTexture { |
| 390 |
texture: Texture, |
| 391 |
drawable: metal::MetalDrawable, |
| 392 |
present_with_transaction: bool, |
| 393 |
} |
| 394 |
|
| 395 |
impl crate::DynSurfaceTexture for SurfaceTexture {} |
| 396 |
|
| 397 |
impl core::borrow::Borrow<Texture> for SurfaceTexture { |
| 398 |
fn borrow(&self) -> &Texture { |
| 399 |
&self.texture |
| 400 |
} |
| 401 |
} |
| 402 |
|
| 403 |
impl core::borrow::Borrow<dyn crate::DynTexture> for SurfaceTexture { |
| 404 |
fn borrow(&self) -> &dyn crate::DynTexture { |
| 405 |
&self.texture |
| 406 |
} |
| 407 |
} |
| 408 |
|
| 409 |
unsafe impl Send for SurfaceTexture {} |
| 410 |
unsafe impl Sync for SurfaceTexture {} |
| 411 |
|
| 412 |
impl crate::Queue for Queue { |
| 413 |
type A = Api; |
| 414 |
|
| 415 |
unsafe fn submit( |
| 416 |
&self, |
| 417 |
command_buffers: &[&CommandBuffer], |
| 418 |
_surface_textures: &[&SurfaceTexture], |
| 419 |
(signal_fence, signal_value): (&mut Fence, crate::FenceValue), |
| 420 |
) -> Result<(), crate::DeviceError> { |
| 421 |
objc::rc::autoreleasepool(|| { |
| 422 |
let extra_command_buffer = { |
| 423 |
let completed_value = Arc::clone(&signal_fence.completed_value); |
| 424 |
let block = block::ConcreteBlock::new(move |_cmd_buf| { |
| 425 |
completed_value.store(signal_value, atomic::Ordering::Release); |
| 426 |
}) |
| 427 |
.copy(); |
| 428 |
|
| 429 |
let raw = match command_buffers.last() { |
| 430 |
Some(&cmd_buf) => cmd_buf.raw.to_owned(), |
| 431 |
None => { |
| 432 |
let queue = self.raw.lock(); |
| 433 |
queue |
| 434 |
.new_command_buffer_with_unretained_references() |
| 435 |
.to_owned() |
| 436 |
} |
| 437 |
}; |
| 438 |
raw.set_label("(wgpu internal) Signal"); |
| 439 |
raw.add_completed_handler(&block); |
| 440 |
|
| 441 |
signal_fence.maintain(); |
| 442 |
signal_fence |
| 443 |
.pending_command_buffers |
| 444 |
.push((signal_value, raw.to_owned())); |
| 445 |
|
| 446 |
if let Some(shared_event) = signal_fence.shared_event.as_ref() { |
| 447 |
raw.encode_signal_event(shared_event, signal_value); |
| 448 |
} |
| 449 |
// only return an extra one if it's extra |
| 450 |
match command_buffers.last() { |
| 451 |
Some(_) => None, |
| 452 |
None => Some(raw), |
| 453 |
} |
| 454 |
}; |
| 455 |
|
| 456 |
for cmd_buffer in command_buffers { |
| 457 |
cmd_buffer.raw.commit(); |
| 458 |
} |
| 459 |
|
| 460 |
if let Some(raw) = extra_command_buffer { |
| 461 |
raw.commit(); |
| 462 |
} |
| 463 |
}); |
| 464 |
Ok(()) |
| 465 |
} |
| 466 |
unsafe fn present( |
| 467 |
&self, |
| 468 |
_surface: &Surface, |
| 469 |
texture: SurfaceTexture, |
| 470 |
) -> Result<(), crate::SurfaceError> { |
| 471 |
let queue = &self.raw.lock(); |
| 472 |
objc::rc::autoreleasepool(|| { |
| 473 |
let command_buffer = queue.new_command_buffer(); |
| 474 |
command_buffer.set_label("(wgpu internal) Present"); |
| 475 |
|
| 476 |
// https://developer.apple.com/documentation/quartzcore/cametallayer/1478157-presentswithtransaction?language=objc |
| 477 |
if !texture.present_with_transaction { |
| 478 |
command_buffer.present_drawable(&texture.drawable); |
| 479 |
} |
| 480 |
|
| 481 |
command_buffer.commit(); |
| 482 |
|
| 483 |
if texture.present_with_transaction { |
| 484 |
command_buffer.wait_until_scheduled(); |
| 485 |
texture.drawable.present(); |
| 486 |
} |
| 487 |
}); |
| 488 |
Ok(()) |
| 489 |
} |
| 490 |
|
| 491 |
unsafe fn get_timestamp_period(&self) -> f32 { |
| 492 |
self.timestamp_period |
| 493 |
} |
| 494 |
} |
| 495 |
|
| 496 |
#[derive(Debug)] |
| 497 |
pub struct Buffer { |
| 498 |
raw: metal::Buffer, |
| 499 |
size: wgt::BufferAddress, |
| 500 |
} |
| 501 |
|
| 502 |
unsafe impl Send for Buffer {} |
| 503 |
unsafe impl Sync for Buffer {} |
| 504 |
|
| 505 |
impl crate::DynBuffer for Buffer {} |
| 506 |
|
| 507 |
impl Buffer { |
| 508 |
fn as_raw(&self) -> BufferPtr { |
| 509 |
unsafe { NonNull::new_unchecked(self.raw.as_ptr()) } |
| 510 |
} |
| 511 |
} |
| 512 |
|
| 513 |
impl crate::BufferBinding<'_, Buffer> { |
| 514 |
fn resolve_size(&self) -> wgt::BufferAddress { |
| 515 |
match self.size { |
| 516 |
Some(size) => size.get(), |
| 517 |
None => self.buffer.size - self.offset, |
| 518 |
} |
| 519 |
} |
| 520 |
} |
| 521 |
|
| 522 |
#[derive(Debug)] |
| 523 |
pub struct Texture { |
| 524 |
raw: metal::Texture, |
| 525 |
format: wgt::TextureFormat, |
| 526 |
raw_type: MTLTextureType, |
| 527 |
array_layers: u32, |
| 528 |
mip_levels: u32, |
| 529 |
copy_size: crate::CopyExtent, |
| 530 |
} |
| 531 |
|
| 532 |
impl Texture { |
| 533 |
/// # Safety |
| 534 |
/// |
| 535 |
/// - The texture handle must not be manually destroyed |
| 536 |
pub unsafe fn raw_handle(&self) -> &metal::Texture { |
| 537 |
&self.raw |
| 538 |
} |
| 539 |
} |
| 540 |
|
| 541 |
impl crate::DynTexture for Texture {} |
| 542 |
|
| 543 |
unsafe impl Send for Texture {} |
| 544 |
unsafe impl Sync for Texture {} |
| 545 |
|
| 546 |
#[derive(Debug)] |
| 547 |
pub struct TextureView { |
| 548 |
raw: metal::Texture, |
| 549 |
aspects: crate::FormatAspects, |
| 550 |
} |
| 551 |
|
| 552 |
impl crate::DynTextureView for TextureView {} |
| 553 |
|
| 554 |
unsafe impl Send for TextureView {} |
| 555 |
unsafe impl Sync for TextureView {} |
| 556 |
|
| 557 |
impl TextureView { |
| 558 |
fn as_raw(&self) -> TexturePtr { |
| 559 |
unsafe { NonNull::new_unchecked(self.raw.as_ptr()) } |
| 560 |
} |
| 561 |
} |
| 562 |
|
| 563 |
#[derive(Debug)] |
| 564 |
pub struct Sampler { |
| 565 |
raw: metal::SamplerState, |
| 566 |
} |
| 567 |
|
| 568 |
impl crate::DynSampler for Sampler {} |
| 569 |
|
| 570 |
unsafe impl Send for Sampler {} |
| 571 |
unsafe impl Sync for Sampler {} |
| 572 |
|
| 573 |
impl Sampler { |
| 574 |
fn as_raw(&self) -> SamplerPtr { |
| 575 |
unsafe { NonNull::new_unchecked(self.raw.as_ptr()) } |
| 576 |
} |
| 577 |
} |
| 578 |
|
| 579 |
#[derive(Debug)] |
| 580 |
pub struct BindGroupLayout { |
| 581 |
/// Sorted list of BGL entries. |
| 582 |
entries: Arc<[wgt::BindGroupLayoutEntry]>, |
| 583 |
} |
| 584 |
|
| 585 |
impl crate::DynBindGroupLayout for BindGroupLayout {} |
| 586 |
|
| 587 |
#[derive(Clone, Debug, Default)] |
| 588 |
struct ResourceData<T> { |
| 589 |
buffers: T, |
| 590 |
textures: T, |
| 591 |
samplers: T, |
| 592 |
} |
| 593 |
|
| 594 |
#[derive(Clone, Debug, Default)] |
| 595 |
struct MultiStageData<T> { |
| 596 |
vs: T, |
| 597 |
fs: T, |
| 598 |
cs: T, |
| 599 |
} |
| 600 |
|
| 601 |
const NAGA_STAGES: MultiStageData<naga::ShaderStage> = MultiStageData { |
| 602 |
vs: naga::ShaderStage::Vertex, |
| 603 |
fs: naga::ShaderStage::Fragment, |
| 604 |
cs: naga::ShaderStage::Compute, |
| 605 |
}; |
| 606 |
|
| 607 |
impl<T> ops::Index<naga::ShaderStage> for MultiStageData<T> { |
| 608 |
type Output = T; |
| 609 |
fn index(&self, stage: naga::ShaderStage) -> &T { |
| 610 |
match stage { |
| 611 |
naga::ShaderStage::Vertex => &self.vs, |
| 612 |
naga::ShaderStage::Fragment => &self.fs, |
| 613 |
naga::ShaderStage::Compute => &self.cs, |
| 614 |
naga::ShaderStage::Task | naga::ShaderStage::Mesh => unreachable!(), |
| 615 |
} |
| 616 |
} |
| 617 |
} |
| 618 |
|
| 619 |
impl<T> MultiStageData<T> { |
| 620 |
fn map_ref<Y>(&self, fun: impl Fn(&T) -> Y) -> MultiStageData<Y> { |
| 621 |
MultiStageData { |
| 622 |
vs: fun(&self.vs), |
| 623 |
fs: fun(&self.fs), |
| 624 |
cs: fun(&self.cs), |
| 625 |
} |
| 626 |
} |
| 627 |
fn map<Y>(self, fun: impl Fn(T) -> Y) -> MultiStageData<Y> { |
| 628 |
MultiStageData { |
| 629 |
vs: fun(self.vs), |
| 630 |
fs: fun(self.fs), |
| 631 |
cs: fun(self.cs), |
| 632 |
} |
| 633 |
} |
| 634 |
fn iter<'a>(&'a self) -> impl Iterator<Item = &'a T> { |
| 635 |
iter::once(&self.vs) |
| 636 |
.chain(iter::once(&self.fs)) |
| 637 |
.chain(iter::once(&self.cs)) |
| 638 |
} |
| 639 |
fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = &'a mut T> { |
| 640 |
iter::once(&mut self.vs) |
| 641 |
.chain(iter::once(&mut self.fs)) |
| 642 |
.chain(iter::once(&mut self.cs)) |
| 643 |
} |
| 644 |
} |
| 645 |
|
| 646 |
type MultiStageResourceCounters = MultiStageData<ResourceData<ResourceIndex>>; |
| 647 |
type MultiStageResources = MultiStageData<naga::back::msl::EntryPointResources>; |
| 648 |
|
| 649 |
#[derive(Debug)] |
| 650 |
struct BindGroupLayoutInfo { |
| 651 |
base_resource_indices: MultiStageResourceCounters, |
| 652 |
} |
| 653 |
|
| 654 |
#[derive(Copy, Clone, Debug, Eq, PartialEq)] |
| 655 |
struct PushConstantsInfo { |
| 656 |
count: u32, |
| 657 |
buffer_index: ResourceIndex, |
| 658 |
} |
| 659 |
|
| 660 |
#[derive(Debug)] |
| 661 |
pub struct PipelineLayout { |
| 662 |
bind_group_infos: ArrayVec<BindGroupLayoutInfo, { crate::MAX_BIND_GROUPS }>, |
| 663 |
push_constants_infos: MultiStageData<Option<PushConstantsInfo>>, |
| 664 |
total_counters: MultiStageResourceCounters, |
| 665 |
total_push_constants: u32, |
| 666 |
per_stage_map: MultiStageResources, |
| 667 |
} |
| 668 |
|
| 669 |
impl crate::DynPipelineLayout for PipelineLayout {} |
| 670 |
|
| 671 |
trait AsNative { |
| 672 |
type Native; |
| 673 |
fn from(native: &Self::Native) -> Self; |
| 674 |
fn as_native(&self) -> &Self::Native; |
| 675 |
} |
| 676 |
|
| 677 |
type ResourcePtr = NonNull<MTLResource>; |
| 678 |
type BufferPtr = NonNull<MTLBuffer>; |
| 679 |
type TexturePtr = NonNull<MTLTexture>; |
| 680 |
type SamplerPtr = NonNull<MTLSamplerState>; |
| 681 |
|
| 682 |
impl AsNative for ResourcePtr { |
| 683 |
type Native = metal::ResourceRef; |
| 684 |
#[inline] |
| 685 |
fn from(native: &Self::Native) -> Self { |
| 686 |
unsafe { NonNull::new_unchecked(native.as_ptr()) } |
| 687 |
} |
| 688 |
#[inline] |
| 689 |
fn as_native(&self) -> &Self::Native { |
| 690 |
unsafe { Self::Native::from_ptr(self.as_ptr()) } |
| 691 |
} |
| 692 |
} |
| 693 |
|
| 694 |
impl AsNative for BufferPtr { |
| 695 |
type Native = metal::BufferRef; |
| 696 |
#[inline] |
| 697 |
fn from(native: &Self::Native) -> Self { |
| 698 |
unsafe { NonNull::new_unchecked(native.as_ptr()) } |
| 699 |
} |
| 700 |
#[inline] |
| 701 |
fn as_native(&self) -> &Self::Native { |
| 702 |
unsafe { Self::Native::from_ptr(self.as_ptr()) } |
| 703 |
} |
| 704 |
} |
| 705 |
|
| 706 |
impl AsNative for TexturePtr { |
| 707 |
type Native = metal::TextureRef; |
| 708 |
#[inline] |
| 709 |
fn from(native: &Self::Native) -> Self { |
| 710 |
unsafe { NonNull::new_unchecked(native.as_ptr()) } |
| 711 |
} |
| 712 |
#[inline] |
| 713 |
fn as_native(&self) -> &Self::Native { |
| 714 |
unsafe { Self::Native::from_ptr(self.as_ptr()) } |
| 715 |
} |
| 716 |
} |
| 717 |
|
| 718 |
impl AsNative for SamplerPtr { |
| 719 |
type Native = metal::SamplerStateRef; |
| 720 |
#[inline] |
| 721 |
fn from(native: &Self::Native) -> Self { |
| 722 |
unsafe { NonNull::new_unchecked(native.as_ptr()) } |
| 723 |
} |
| 724 |
#[inline] |
| 725 |
fn as_native(&self) -> &Self::Native { |
| 726 |
unsafe { Self::Native::from_ptr(self.as_ptr()) } |
| 727 |
} |
| 728 |
} |
| 729 |
|
| 730 |
#[derive(Debug)] |
| 731 |
struct BufferResource { |
| 732 |
ptr: BufferPtr, |
| 733 |
offset: wgt::BufferAddress, |
| 734 |
dynamic_index: Option<u32>, |
| 735 |
|
| 736 |
/// The buffer's size, if it is a [`Storage`] binding. Otherwise `None`. |
| 737 |
/// |
| 738 |
/// Buffers with the [`wgt::BufferBindingType::Storage`] binding type can |
| 739 |
/// hold WGSL runtime-sized arrays. When one does, we must pass its size to |
| 740 |
/// shader entry points to implement bounds checks and WGSL's `arrayLength` |
| 741 |
/// function. See `device::CompiledShader::sized_bindings` for details. |
| 742 |
/// |
| 743 |
/// [`Storage`]: wgt::BufferBindingType::Storage |
| 744 |
binding_size: Option<wgt::BufferSize>, |
| 745 |
|
| 746 |
binding_location: u32, |
| 747 |
} |
| 748 |
|
| 749 |
#[derive(Debug)] |
| 750 |
struct UseResourceInfo { |
| 751 |
uses: MTLResourceUsage, |
| 752 |
stages: MTLRenderStages, |
| 753 |
visible_in_compute: bool, |
| 754 |
} |
| 755 |
|
| 756 |
impl Default for UseResourceInfo { |
| 757 |
fn default() -> Self { |
| 758 |
Self { |
| 759 |
uses: MTLResourceUsage::empty(), |
| 760 |
stages: MTLRenderStages::empty(), |
| 761 |
visible_in_compute: false, |
| 762 |
} |
| 763 |
} |
| 764 |
} |
| 765 |
|
| 766 |
#[derive(Debug, Default)] |
| 767 |
pub struct BindGroup { |
| 768 |
counters: MultiStageResourceCounters, |
| 769 |
buffers: Vec<BufferResource>, |
| 770 |
samplers: Vec<SamplerPtr>, |
| 771 |
textures: Vec<TexturePtr>, |
| 772 |
|
| 773 |
argument_buffers: Vec<metal::Buffer>, |
| 774 |
resources_to_use: HashMap<ResourcePtr, UseResourceInfo>, |
| 775 |
} |
| 776 |
|
| 777 |
impl crate::DynBindGroup for BindGroup {} |
| 778 |
|
| 779 |
unsafe impl Send for BindGroup {} |
| 780 |
unsafe impl Sync for BindGroup {} |
| 781 |
|
| 782 |
#[derive(Debug)] |
| 783 |
pub enum ShaderModuleSource { |
| 784 |
Naga(crate::NagaShader), |
| 785 |
Passthrough(PassthroughShader), |
| 786 |
} |
| 787 |
|
| 788 |
#[derive(Debug)] |
| 789 |
pub struct PassthroughShader { |
| 790 |
pub library: metal::Library, |
| 791 |
pub function: metal::Function, |
| 792 |
pub entry_point: String, |
| 793 |
pub num_workgroups: (u32, u32, u32), |
| 794 |
} |
| 795 |
|
| 796 |
#[derive(Debug)] |
| 797 |
pub struct ShaderModule { |
| 798 |
source: ShaderModuleSource, |
| 799 |
bounds_checks: wgt::ShaderRuntimeChecks, |
| 800 |
} |
| 801 |
|
| 802 |
impl crate::DynShaderModule for ShaderModule {} |
| 803 |
|
| 804 |
#[derive(Debug, Default)] |
| 805 |
struct PipelineStageInfo { |
| 806 |
push_constants: Option<PushConstantsInfo>, |
| 807 |
|
| 808 |
/// The buffer argument table index at which we pass runtime-sized arrays' buffer sizes. |
| 809 |
/// |
| 810 |
/// See `device::CompiledShader::sized_bindings` for more details. |
| 811 |
sizes_slot: Option<naga::back::msl::Slot>, |
| 812 |
|
| 813 |
/// Bindings of all WGSL `storage` globals that contain runtime-sized arrays. |
| 814 |
/// |
| 815 |
/// See `device::CompiledShader::sized_bindings` for more details. |
| 816 |
sized_bindings: Vec<naga::ResourceBinding>, |
| 817 |
|
| 818 |
/// Info on all bound vertex buffers. |
| 819 |
vertex_buffer_mappings: Vec<naga::back::msl::VertexBufferMapping>, |
| 820 |
} |
| 821 |
|
| 822 |
impl PipelineStageInfo { |
| 823 |
fn clear(&mut self) { |
| 824 |
self.push_constants = None; |
| 825 |
self.sizes_slot = None; |
| 826 |
self.sized_bindings.clear(); |
| 827 |
self.vertex_buffer_mappings.clear(); |
| 828 |
} |
| 829 |
|
| 830 |
fn assign_from(&mut self, other: &Self) { |
| 831 |
self.push_constants = other.push_constants; |
| 832 |
self.sizes_slot = other.sizes_slot; |
| 833 |
self.sized_bindings.clear(); |
| 834 |
self.sized_bindings.extend_from_slice(&other.sized_bindings); |
| 835 |
self.vertex_buffer_mappings.clear(); |
| 836 |
self.vertex_buffer_mappings |
| 837 |
.extend_from_slice(&other.vertex_buffer_mappings); |
| 838 |
} |
| 839 |
} |
| 840 |
|
| 841 |
#[derive(Debug)] |
| 842 |
pub struct RenderPipeline { |
| 843 |
raw: metal::RenderPipelineState, |
| 844 |
#[allow(dead_code)] |
| 845 |
vs_lib: metal::Library, |
| 846 |
#[allow(dead_code)] |
| 847 |
fs_lib: Option<metal::Library>, |
| 848 |
vs_info: PipelineStageInfo, |
| 849 |
fs_info: Option<PipelineStageInfo>, |
| 850 |
raw_primitive_type: MTLPrimitiveType, |
| 851 |
raw_triangle_fill_mode: MTLTriangleFillMode, |
| 852 |
raw_front_winding: MTLWinding, |
| 853 |
raw_cull_mode: MTLCullMode, |
| 854 |
raw_depth_clip_mode: Option<MTLDepthClipMode>, |
| 855 |
depth_stencil: Option<(metal::DepthStencilState, wgt::DepthBiasState)>, |
| 856 |
} |
| 857 |
|
| 858 |
unsafe impl Send for RenderPipeline {} |
| 859 |
unsafe impl Sync for RenderPipeline {} |
| 860 |
|
| 861 |
impl crate::DynRenderPipeline for RenderPipeline {} |
| 862 |
|
| 863 |
#[derive(Debug)] |
| 864 |
pub struct ComputePipeline { |
| 865 |
raw: metal::ComputePipelineState, |
| 866 |
#[allow(dead_code)] |
| 867 |
cs_lib: metal::Library, |
| 868 |
cs_info: PipelineStageInfo, |
| 869 |
work_group_size: MTLSize, |
| 870 |
work_group_memory_sizes: Vec<u32>, |
| 871 |
} |
| 872 |
|
| 873 |
unsafe impl Send for ComputePipeline {} |
| 874 |
unsafe impl Sync for ComputePipeline {} |
| 875 |
|
| 876 |
impl crate::DynComputePipeline for ComputePipeline {} |
| 877 |
|
| 878 |
#[derive(Debug, Clone)] |
| 879 |
pub struct QuerySet { |
| 880 |
raw_buffer: metal::Buffer, |
| 881 |
//Metal has a custom buffer for counters. |
| 882 |
counter_sample_buffer: Option<metal::CounterSampleBuffer>, |
| 883 |
ty: wgt::QueryType, |
| 884 |
} |
| 885 |
|
| 886 |
impl crate::DynQuerySet for QuerySet {} |
| 887 |
|
| 888 |
unsafe impl Send for QuerySet {} |
| 889 |
unsafe impl Sync for QuerySet {} |
| 890 |
|
| 891 |
#[derive(Debug)] |
| 892 |
pub struct Fence { |
| 893 |
completed_value: Arc<atomic::AtomicU64>, |
| 894 |
/// The pending fence values have to be ascending. |
| 895 |
pending_command_buffers: Vec<(crate::FenceValue, metal::CommandBuffer)>, |
| 896 |
shared_event: Option<metal::SharedEvent>, |
| 897 |
} |
| 898 |
|
| 899 |
impl crate::DynFence for Fence {} |
| 900 |
|
| 901 |
unsafe impl Send for Fence {} |
| 902 |
unsafe impl Sync for Fence {} |
| 903 |
|
| 904 |
impl Fence { |
| 905 |
fn get_latest(&self) -> crate::FenceValue { |
| 906 |
let mut max_value = self.completed_value.load(atomic::Ordering::Acquire); |
| 907 |
for &(value, ref cmd_buf) in self.pending_command_buffers.iter() { |
| 908 |
if cmd_buf.status() == MTLCommandBufferStatus::Completed { |
| 909 |
max_value = value; |
| 910 |
} |
| 911 |
} |
| 912 |
max_value |
| 913 |
} |
| 914 |
|
| 915 |
fn maintain(&mut self) { |
| 916 |
let latest = self.get_latest(); |
| 917 |
self.pending_command_buffers |
| 918 |
.retain(|&(value, _)| value > latest); |
| 919 |
} |
| 920 |
|
| 921 |
pub fn raw_shared_event(&self) -> Option<&metal::SharedEvent> { |
| 922 |
self.shared_event.as_ref() |
| 923 |
} |
| 924 |
} |
| 925 |
|
| 926 |
struct IndexState { |
| 927 |
buffer_ptr: BufferPtr, |
| 928 |
offset: wgt::BufferAddress, |
| 929 |
stride: wgt::BufferAddress, |
| 930 |
raw_type: MTLIndexType, |
| 931 |
} |
| 932 |
|
| 933 |
#[derive(Default)] |
| 934 |
struct Temp { |
| 935 |
binding_sizes: Vec<u32>, |
| 936 |
} |
| 937 |
|
| 938 |
struct CommandState { |
| 939 |
blit: Option<metal::BlitCommandEncoder>, |
| 940 |
render: Option<metal::RenderCommandEncoder>, |
| 941 |
compute: Option<metal::ComputeCommandEncoder>, |
| 942 |
raw_primitive_type: MTLPrimitiveType, |
| 943 |
index: Option<IndexState>, |
| 944 |
raw_wg_size: MTLSize, |
| 945 |
stage_infos: MultiStageData<PipelineStageInfo>, |
| 946 |
|
| 947 |
/// Sizes of currently bound [`wgt::BufferBindingType::Storage`] buffers. |
| 948 |
/// |
| 949 |
/// Specifically: |
| 950 |
/// |
| 951 |
/// - The keys are [`ResourceBinding`] values (that is, the WGSL `@group` |
| 952 |
/// and `@binding` attributes) for `var<storage>` global variables in the |
| 953 |
/// current module that contain runtime-sized arrays. |
| 954 |
/// |
| 955 |
/// - The values are the actual sizes of the buffers currently bound to |
| 956 |
/// provide those globals' contents, which are needed to implement bounds |
| 957 |
/// checks and the WGSL `arrayLength` function. |
| 958 |
/// |
| 959 |
/// For each stage `S` in `stage_infos`, we consult this to find the sizes |
| 960 |
/// of the buffers listed in [`stage_infos.S.sized_bindings`], which we must |
| 961 |
/// pass to the entry point. |
| 962 |
/// |
| 963 |
/// See `device::CompiledShader::sized_bindings` for more details. |
| 964 |
/// |
| 965 |
/// [`ResourceBinding`]: naga::ResourceBinding |
| 966 |
storage_buffer_length_map: FastHashMap<naga::ResourceBinding, wgt::BufferSize>, |
| 967 |
|
| 968 |
vertex_buffer_size_map: FastHashMap<u64, wgt::BufferSize>, |
| 969 |
|
| 970 |
work_group_memory_sizes: Vec<u32>, |
| 971 |
push_constants: Vec<u32>, |
| 972 |
|
| 973 |
/// Timer query that should be executed when the next pass starts. |
| 974 |
pending_timer_queries: Vec<(QuerySet, u32)>, |
| 975 |
} |
| 976 |
|
| 977 |
pub struct CommandEncoder { |
| 978 |
shared: Arc<AdapterShared>, |
| 979 |
raw_queue: Arc<Mutex<metal::CommandQueue>>, |
| 980 |
raw_cmd_buf: Option<metal::CommandBuffer>, |
| 981 |
state: CommandState, |
| 982 |
temp: Temp, |
| 983 |
counters: Arc<wgt::HalCounters>, |
| 984 |
} |
| 985 |
|
| 986 |
impl fmt::Debug for CommandEncoder { |
| 987 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 988 |
f.debug_struct("CommandEncoder") |
| 989 |
.field("raw_queue", &self.raw_queue) |
| 990 |
.field("raw_cmd_buf", &self.raw_cmd_buf) |
| 991 |
.finish() |
| 992 |
} |
| 993 |
} |
| 994 |
|
| 995 |
unsafe impl Send for CommandEncoder {} |
| 996 |
unsafe impl Sync for CommandEncoder {} |
| 997 |
|
| 998 |
#[derive(Debug)] |
| 999 |
pub struct CommandBuffer { |
| 1000 |
raw: metal::CommandBuffer, |
| 1001 |
} |
| 1002 |
|
| 1003 |
impl crate::DynCommandBuffer for CommandBuffer {} |
| 1004 |
|
| 1005 |
unsafe impl Send for CommandBuffer {} |
| 1006 |
unsafe impl Sync for CommandBuffer {} |
| 1007 |
|
| 1008 |
#[derive(Debug)] |
| 1009 |
pub struct PipelineCache; |
| 1010 |
|
| 1011 |
impl crate::DynPipelineCache for PipelineCache {} |
| 1012 |
|
| 1013 |
#[derive(Debug)] |
| 1014 |
pub struct AccelerationStructure; |
| 1015 |
|
| 1016 |
impl crate::DynAccelerationStructure for AccelerationStructure {} |