Debian Codegraph @

third_party/rust/wgpu-hal/src/metal/device.rs

raw
1 use alloc::{borrow::ToOwned as _, sync::Arc, vec::Vec};
2 use core::{ptr::NonNull, sync::atomic};
3 use std::{thread, time};
4
5 use parking_lot::Mutex;
6
7 use super::{conv, PassthroughShader};
8 use crate::auxil::map_naga_stage;
9 use crate::metal::ShaderModuleSource;
10 use crate::TlasInstance;
11
12 use metal::{
13 foreign_types::ForeignType, MTLCommandBufferStatus, MTLDepthClipMode, MTLLanguageVersion,
14 MTLMutability, MTLPixelFormat, MTLPrimitiveTopologyClass, MTLResourceID, MTLResourceOptions,
15 MTLSamplerAddressMode, MTLSamplerMipFilter, MTLSize, MTLStorageMode, MTLTextureType,
16 MTLTriangleFillMode, MTLVertexStepFunction, NSRange,
17 };
18
19 type DeviceResult<T> = Result<T, crate::DeviceError>;
20
21 struct CompiledShader {
22 library: metal::Library,
23 function: metal::Function,
24 wg_size: MTLSize,
25 wg_memory_sizes: Vec<u32>,
26
27 /// Bindings of WGSL `storage` globals that contain variable-sized arrays.
28 ///
29 /// In order to implement bounds checks and the `arrayLength` function for
30 /// WGSL runtime-sized arrays, we pass the entry point a struct with a
31 /// member for each global variable that contains such an array. That member
32 /// is a `u32` holding the variable's total size in bytes---which is simply
33 /// the size of the `Buffer` supplying that variable's contents for the
34 /// draw call.
35 sized_bindings: Vec<naga::ResourceBinding>,
36
37 immutable_buffer_mask: usize,
38 }
39
40 fn create_stencil_desc(
41 face: &wgt::StencilFaceState,
42 read_mask: u32,
43 write_mask: u32,
44 ) -> metal::StencilDescriptor {
45 let desc = metal::StencilDescriptor::new();
46 desc.set_stencil_compare_function(conv::map_compare_function(face.compare));
47 desc.set_read_mask(read_mask);
48 desc.set_write_mask(write_mask);
49 desc.set_stencil_failure_operation(conv::map_stencil_op(face.fail_op));
50 desc.set_depth_failure_operation(conv::map_stencil_op(face.depth_fail_op));
51 desc.set_depth_stencil_pass_operation(conv::map_stencil_op(face.pass_op));
52 desc
53 }
54
55 fn create_depth_stencil_desc(state: &wgt::DepthStencilState) -> metal::DepthStencilDescriptor {
56 let desc = metal::DepthStencilDescriptor::new();
57 desc.set_depth_compare_function(conv::map_compare_function(state.depth_compare));
58 desc.set_depth_write_enabled(state.depth_write_enabled);
59 let s = &state.stencil;
60 if s.is_enabled() {
61 let front_desc = create_stencil_desc(&s.front, s.read_mask, s.write_mask);
62 desc.set_front_face_stencil(Some(&front_desc));
63 let back_desc = create_stencil_desc(&s.back, s.read_mask, s.write_mask);
64 desc.set_back_face_stencil(Some(&back_desc));
65 }
66 desc
67 }
68
69 const fn convert_vertex_format_to_naga(format: wgt::VertexFormat) -> naga::back::msl::VertexFormat {
70 match format {
71 wgt::VertexFormat::Uint8 => naga::back::msl::VertexFormat::Uint8,
72 wgt::VertexFormat::Uint8x2 => naga::back::msl::VertexFormat::Uint8x2,
73 wgt::VertexFormat::Uint8x4 => naga::back::msl::VertexFormat::Uint8x4,
74 wgt::VertexFormat::Sint8 => naga::back::msl::VertexFormat::Sint8,
75 wgt::VertexFormat::Sint8x2 => naga::back::msl::VertexFormat::Sint8x2,
76 wgt::VertexFormat::Sint8x4 => naga::back::msl::VertexFormat::Sint8x4,
77 wgt::VertexFormat::Unorm8 => naga::back::msl::VertexFormat::Unorm8,
78 wgt::VertexFormat::Unorm8x2 => naga::back::msl::VertexFormat::Unorm8x2,
79 wgt::VertexFormat::Unorm8x4 => naga::back::msl::VertexFormat::Unorm8x4,
80 wgt::VertexFormat::Snorm8 => naga::back::msl::VertexFormat::Snorm8,
81 wgt::VertexFormat::Snorm8x2 => naga::back::msl::VertexFormat::Snorm8x2,
82 wgt::VertexFormat::Snorm8x4 => naga::back::msl::VertexFormat::Snorm8x4,
83 wgt::VertexFormat::Uint16 => naga::back::msl::VertexFormat::Uint16,
84 wgt::VertexFormat::Uint16x2 => naga::back::msl::VertexFormat::Uint16x2,
85 wgt::VertexFormat::Uint16x4 => naga::back::msl::VertexFormat::Uint16x4,
86 wgt::VertexFormat::Sint16 => naga::back::msl::VertexFormat::Sint16,
87 wgt::VertexFormat::Sint16x2 => naga::back::msl::VertexFormat::Sint16x2,
88 wgt::VertexFormat::Sint16x4 => naga::back::msl::VertexFormat::Sint16x4,
89 wgt::VertexFormat::Unorm16 => naga::back::msl::VertexFormat::Unorm16,
90 wgt::VertexFormat::Unorm16x2 => naga::back::msl::VertexFormat::Unorm16x2,
91 wgt::VertexFormat::Unorm16x4 => naga::back::msl::VertexFormat::Unorm16x4,
92 wgt::VertexFormat::Snorm16 => naga::back::msl::VertexFormat::Snorm16,
93 wgt::VertexFormat::Snorm16x2 => naga::back::msl::VertexFormat::Snorm16x2,
94 wgt::VertexFormat::Snorm16x4 => naga::back::msl::VertexFormat::Snorm16x4,
95 wgt::VertexFormat::Float16 => naga::back::msl::VertexFormat::Float16,
96 wgt::VertexFormat::Float16x2 => naga::back::msl::VertexFormat::Float16x2,
97 wgt::VertexFormat::Float16x4 => naga::back::msl::VertexFormat::Float16x4,
98 wgt::VertexFormat::Float32 => naga::back::msl::VertexFormat::Float32,
99 wgt::VertexFormat::Float32x2 => naga::back::msl::VertexFormat::Float32x2,
100 wgt::VertexFormat::Float32x3 => naga::back::msl::VertexFormat::Float32x3,
101 wgt::VertexFormat::Float32x4 => naga::back::msl::VertexFormat::Float32x4,
102 wgt::VertexFormat::Uint32 => naga::back::msl::VertexFormat::Uint32,
103 wgt::VertexFormat::Uint32x2 => naga::back::msl::VertexFormat::Uint32x2,
104 wgt::VertexFormat::Uint32x3 => naga::back::msl::VertexFormat::Uint32x3,
105 wgt::VertexFormat::Uint32x4 => naga::back::msl::VertexFormat::Uint32x4,
106 wgt::VertexFormat::Sint32 => naga::back::msl::VertexFormat::Sint32,
107 wgt::VertexFormat::Sint32x2 => naga::back::msl::VertexFormat::Sint32x2,
108 wgt::VertexFormat::Sint32x3 => naga::back::msl::VertexFormat::Sint32x3,
109 wgt::VertexFormat::Sint32x4 => naga::back::msl::VertexFormat::Sint32x4,
110 wgt::VertexFormat::Unorm10_10_10_2 => naga::back::msl::VertexFormat::Unorm10_10_10_2,
111 wgt::VertexFormat::Unorm8x4Bgra => naga::back::msl::VertexFormat::Unorm8x4Bgra,
112
113 wgt::VertexFormat::Float64
114 | wgt::VertexFormat::Float64x2
115 | wgt::VertexFormat::Float64x3
116 | wgt::VertexFormat::Float64x4 => {
117 unimplemented!()
118 }
119 }
120 }
121
122 impl super::Device {
123 fn load_shader(
124 &self,
125 stage: &crate::ProgrammableStage<super::ShaderModule>,
126 vertex_buffer_mappings: &[naga::back::msl::VertexBufferMapping],
127 layout: &super::PipelineLayout,
128 primitive_class: MTLPrimitiveTopologyClass,
129 naga_stage: naga::ShaderStage,
130 ) -> Result<CompiledShader, crate::PipelineError> {
131 let naga_shader = if let ShaderModuleSource::Naga(naga) = &stage.module.source {
132 naga
133 } else {
134 panic!("load_shader required a naga shader");
135 };
136 let stage_bit = map_naga_stage(naga_stage);
137 let (module, module_info) = naga::back::pipeline_constants::process_overrides(
138 &naga_shader.module,
139 &naga_shader.info,
140 stage.constants,
141 )
142 .map_err(|e| crate::PipelineError::PipelineConstants(stage_bit, format!("MSL: {:?}", e)))?;
143
144 let ep_resources = &layout.per_stage_map[naga_stage];
145
146 let bounds_check_policy = if stage.module.bounds_checks.bounds_checks {
147 naga::proc::BoundsCheckPolicy::Restrict
148 } else {
149 naga::proc::BoundsCheckPolicy::Unchecked
150 };
151
152 let options = naga::back::msl::Options {
153 lang_version: match self.shared.private_caps.msl_version {
154 MTLLanguageVersion::V1_0 => (1, 0),
155 MTLLanguageVersion::V1_1 => (1, 1),
156 MTLLanguageVersion::V1_2 => (1, 2),
157 MTLLanguageVersion::V2_0 => (2, 0),
158 MTLLanguageVersion::V2_1 => (2, 1),
159 MTLLanguageVersion::V2_2 => (2, 2),
160 MTLLanguageVersion::V2_3 => (2, 3),
161 MTLLanguageVersion::V2_4 => (2, 4),
162 MTLLanguageVersion::V3_0 => (3, 0),
163 MTLLanguageVersion::V3_1 => (3, 1),
164 },
165 inline_samplers: Default::default(),
166 spirv_cross_compatibility: false,
167 fake_missing_bindings: false,
168 per_entry_point_map: naga::back::msl::EntryPointResourceMap::from([(
169 stage.entry_point.to_owned(),
170 ep_resources.clone(),
171 )]),
172 bounds_check_policies: naga::proc::BoundsCheckPolicies {
173 index: bounds_check_policy,
174 buffer: bounds_check_policy,
175 image_load: bounds_check_policy,
176 // TODO: support bounds checks on binding arrays
177 binding_array: naga::proc::BoundsCheckPolicy::Unchecked,
178 },
179 zero_initialize_workgroup_memory: stage.zero_initialize_workgroup_memory,
180 force_loop_bounding: stage.module.bounds_checks.force_loop_bounding,
181 };
182
183 let pipeline_options = naga::back::msl::PipelineOptions {
184 entry_point: Some((naga_stage, stage.entry_point.to_owned())),
185 allow_and_force_point_size: match primitive_class {
186 MTLPrimitiveTopologyClass::Point => true,
187 _ => false,
188 },
189 vertex_pulling_transform: true,
190 vertex_buffer_mappings: vertex_buffer_mappings.to_vec(),
191 };
192
193 let (source, info) =
194 naga::back::msl::write_string(&module, &module_info, &options, &pipeline_options)
195 .map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("MSL: {:?}", e)))?;
196
197 log::debug!(
198 "Naga generated shader for entry point '{}' and stage {:?}\n{}",
199 stage.entry_point,
200 naga_stage,
201 &source
202 );
203
204 let options = metal::CompileOptions::new();
205 options.set_language_version(self.shared.private_caps.msl_version);
206
207 if self.shared.private_caps.supports_preserve_invariance {
208 options.set_preserve_invariance(true);
209 }
210
211 let library = self
212 .shared
213 .device
214 .lock()
215 .new_library_with_source(source.as_ref(), &options)
216 .map_err(|err| {
217 log::warn!("Naga generated shader:\n{}", source);
218 crate::PipelineError::Linkage(stage_bit, format!("Metal: {}", err))
219 })?;
220
221 let ep_index = module
222 .entry_points
223 .iter()
224 .position(|ep| ep.stage == naga_stage && ep.name == stage.entry_point)
225 .ok_or(crate::PipelineError::EntryPoint(naga_stage))?;
226 let ep = &module.entry_points[ep_index];
227 let translated_ep_name = info.entry_point_names[0]
228 .as_ref()
229 .map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("{}", e)))?;
230
231 let wg_size = MTLSize {
232 width: ep.workgroup_size[0] as _,
233 height: ep.workgroup_size[1] as _,
234 depth: ep.workgroup_size[2] as _,
235 };
236
237 let function = library
238 .get_function(translated_ep_name, None)
239 .map_err(|e| {
240 log::error!("get_function: {:?}", e);
241 crate::PipelineError::EntryPoint(naga_stage)
242 })?;
243
244 // collect sizes indices, immutable buffers, and work group memory sizes
245 let ep_info = &module_info.get_entry_point(ep_index);
246 let mut wg_memory_sizes = Vec::new();
247 let mut sized_bindings = Vec::new();
248 let mut immutable_buffer_mask = 0;
249 for (var_handle, var) in module.global_variables.iter() {
250 match var.space {
251 naga::AddressSpace::WorkGroup => {
252 if !ep_info[var_handle].is_empty() {
253 let size = module.types[var.ty].inner.size(module.to_ctx());
254 wg_memory_sizes.push(size);
255 }
256 }
257 naga::AddressSpace::Uniform | naga::AddressSpace::Storage { .. } => {
258 let br = match var.binding {
259 Some(br) => br,
260 None => continue,
261 };
262 let storage_access_store = match var.space {
263 naga::AddressSpace::Storage { access } => {
264 access.contains(naga::StorageAccess::STORE)
265 }
266 _ => false,
267 };
268
269 // check for an immutable buffer
270 if !ep_info[var_handle].is_empty() && !storage_access_store {
271 let slot = ep_resources.resources[&br].buffer.unwrap();
272 immutable_buffer_mask |= 1 << slot;
273 }
274
275 let mut dynamic_array_container_ty = var.ty;
276 if let naga::TypeInner::Struct { ref members, .. } = module.types[var.ty].inner
277 {
278 dynamic_array_container_ty = members.last().unwrap().ty;
279 }
280 if let naga::TypeInner::Array {
281 size: naga::ArraySize::Dynamic,
282 ..
283 } = module.types[dynamic_array_container_ty].inner
284 {
285 sized_bindings.push(br);
286 }
287 }
288 _ => {}
289 }
290 }
291
292 Ok(CompiledShader {
293 library,
294 function,
295 wg_size,
296 wg_memory_sizes,
297 sized_bindings,
298 immutable_buffer_mask,
299 })
300 }
301
302 fn set_buffers_mutability(
303 buffers: &metal::PipelineBufferDescriptorArrayRef,
304 mut immutable_mask: usize,
305 ) {
306 while immutable_mask != 0 {
307 let slot = immutable_mask.trailing_zeros();
308 immutable_mask ^= 1 << slot;
309 buffers
310 .object_at(slot as u64)
311 .unwrap()
312 .set_mutability(MTLMutability::Immutable);
313 }
314 }
315
316 pub unsafe fn texture_from_raw(
317 raw: metal::Texture,
318 format: wgt::TextureFormat,
319 raw_type: MTLTextureType,
320 array_layers: u32,
321 mip_levels: u32,
322 copy_size: crate::CopyExtent,
323 ) -> super::Texture {
324 super::Texture {
325 raw,
326 format,
327 raw_type,
328 array_layers,
329 mip_levels,
330 copy_size,
331 }
332 }
333
334 pub unsafe fn device_from_raw(raw: metal::Device, features: wgt::Features) -> super::Device {
335 super::Device {
336 shared: Arc::new(super::AdapterShared::new(raw)),
337 features,
338 counters: Default::default(),
339 }
340 }
341
342 pub unsafe fn buffer_from_raw(raw: metal::Buffer, size: wgt::BufferAddress) -> super::Buffer {
343 super::Buffer { raw, size }
344 }
345
346 pub fn raw_device(&self) -> &Mutex<metal::Device> {
347 &self.shared.device
348 }
349 }
350
351 impl crate::Device for super::Device {
352 type A = super::Api;
353
354 unsafe fn create_buffer(&self, desc: &crate::BufferDescriptor) -> DeviceResult<super::Buffer> {
355 let map_read = desc.usage.contains(wgt::BufferUses::MAP_READ);
356 let map_write = desc.usage.contains(wgt::BufferUses::MAP_WRITE);
357
358 let mut options = MTLResourceOptions::empty();
359 options |= if map_read || map_write {
360 // `crate::MemoryFlags::PREFER_COHERENT` is ignored here
361 MTLResourceOptions::StorageModeShared
362 } else {
363 MTLResourceOptions::StorageModePrivate
364 };
365 options.set(MTLResourceOptions::CPUCacheModeWriteCombined, map_write);
366
367 //TODO: HazardTrackingModeUntracked
368
369 objc::rc::autoreleasepool(|| {
370 let raw = self.shared.device.lock().new_buffer(desc.size, options);
371 if let Some(label) = desc.label {
372 raw.set_label(label);
373 }
374 self.counters.buffers.add(1);
375 Ok(super::Buffer {
376 raw,
377 size: desc.size,
378 })
379 })
380 }
381 unsafe fn destroy_buffer(&self, _buffer: super::Buffer) {
382 self.counters.buffers.sub(1);
383 }
384
385 unsafe fn add_raw_buffer(&self, _buffer: &super::Buffer) {
386 self.counters.buffers.add(1);
387 }
388
389 unsafe fn map_buffer(
390 &self,
391 buffer: &super::Buffer,
392 range: crate::MemoryRange,
393 ) -> DeviceResult<crate::BufferMapping> {
394 let ptr = buffer.raw.contents().cast::<u8>();
395 assert!(!ptr.is_null());
396 Ok(crate::BufferMapping {
397 ptr: NonNull::new(unsafe { ptr.offset(range.start as isize) }).unwrap(),
398 is_coherent: true,
399 })
400 }
401
402 unsafe fn unmap_buffer(&self, _buffer: &super::Buffer) {}
403 unsafe fn flush_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) {}
404 unsafe fn invalidate_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) {}
405
406 unsafe fn create_texture(
407 &self,
408 desc: &crate::TextureDescriptor,
409 ) -> DeviceResult<super::Texture> {
410 use metal::foreign_types::ForeignType as _;
411
412 let mtl_format = self.shared.private_caps.map_format(desc.format);
413
414 objc::rc::autoreleasepool(|| {
415 let descriptor = metal::TextureDescriptor::new();
416
417 let mtl_type = match desc.dimension {
418 wgt::TextureDimension::D1 => MTLTextureType::D1,
419 wgt::TextureDimension::D2 => {
420 if desc.sample_count > 1 {
421 descriptor.set_sample_count(desc.sample_count as u64);
422 MTLTextureType::D2Multisample
423 } else if desc.size.depth_or_array_layers > 1 {
424 descriptor.set_array_length(desc.size.depth_or_array_layers as u64);
425 MTLTextureType::D2Array
426 } else {
427 MTLTextureType::D2
428 }
429 }
430 wgt::TextureDimension::D3 => {
431 descriptor.set_depth(desc.size.depth_or_array_layers as u64);
432 MTLTextureType::D3
433 }
434 };
435
436 descriptor.set_texture_type(mtl_type);
437 descriptor.set_width(desc.size.width as u64);
438 descriptor.set_height(desc.size.height as u64);
439 descriptor.set_mipmap_level_count(desc.mip_level_count as u64);
440 descriptor.set_pixel_format(mtl_format);
441 descriptor.set_usage(conv::map_texture_usage(desc.format, desc.usage));
442 descriptor.set_storage_mode(MTLStorageMode::Private);
443
444 let raw = self.shared.device.lock().new_texture(&descriptor);
445 if raw.as_ptr().is_null() {
446 return Err(crate::DeviceError::OutOfMemory);
447 }
448 if let Some(label) = desc.label {
449 raw.set_label(label);
450 }
451
452 self.counters.textures.add(1);
453
454 Ok(super::Texture {
455 raw,
456 format: desc.format,
457 raw_type: mtl_type,
458 mip_levels: desc.mip_level_count,
459 array_layers: desc.array_layer_count(),
460 copy_size: desc.copy_extent(),
461 })
462 })
463 }
464
465 unsafe fn destroy_texture(&self, _texture: super::Texture) {
466 self.counters.textures.sub(1);
467 }
468
469 unsafe fn add_raw_texture(&self, _texture: &super::Texture) {
470 self.counters.textures.add(1);
471 }
472
473 unsafe fn create_texture_view(
474 &self,
475 texture: &super::Texture,
476 desc: &crate::TextureViewDescriptor,
477 ) -> DeviceResult<super::TextureView> {
478 let raw_type = if texture.raw_type == MTLTextureType::D2Multisample {
479 texture.raw_type
480 } else {
481 conv::map_texture_view_dimension(desc.dimension)
482 };
483
484 let aspects = crate::FormatAspects::new(texture.format, desc.range.aspect);
485
486 let raw_format = self
487 .shared
488 .private_caps
489 .map_view_format(desc.format, aspects);
490
491 let format_equal = raw_format == self.shared.private_caps.map_format(texture.format);
492 let type_equal = raw_type == texture.raw_type;
493 let range_full_resource =
494 desc.range
495 .is_full_resource(desc.format, texture.mip_levels, texture.array_layers);
496
497 let raw = if format_equal && type_equal && range_full_resource {
498 // Some images are marked as framebuffer-only, and we can't create aliases of them.
499 // Also helps working around Metal bugs with aliased array textures.
500 texture.raw.to_owned()
501 } else {
502 let mip_level_count = desc
503 .range
504 .mip_level_count
505 .unwrap_or(texture.mip_levels - desc.range.base_mip_level);
506 let array_layer_count = desc
507 .range
508 .array_layer_count
509 .unwrap_or(texture.array_layers - desc.range.base_array_layer);
510
511 objc::rc::autoreleasepool(|| {
512 let raw = texture.raw.new_texture_view_from_slice(
513 raw_format,
514 raw_type,
515 NSRange {
516 location: desc.range.base_mip_level as _,
517 length: mip_level_count as _,
518 },
519 NSRange {
520 location: desc.range.base_array_layer as _,
521 length: array_layer_count as _,
522 },
523 );
524 if let Some(label) = desc.label {
525 raw.set_label(label);
526 }
527 raw
528 })
529 };
530
531 self.counters.texture_views.add(1);
532
533 Ok(super::TextureView { raw, aspects })
534 }
535
536 unsafe fn destroy_texture_view(&self, _view: super::TextureView) {
537 self.counters.texture_views.sub(1);
538 }
539
540 unsafe fn create_sampler(
541 &self,
542 desc: &crate::SamplerDescriptor,
543 ) -> DeviceResult<super::Sampler> {
544 objc::rc::autoreleasepool(|| {
545 let descriptor = metal::SamplerDescriptor::new();
546
547 descriptor.set_min_filter(conv::map_filter_mode(desc.min_filter));
548 descriptor.set_mag_filter(conv::map_filter_mode(desc.mag_filter));
549 descriptor.set_mip_filter(match desc.mipmap_filter {
550 wgt::FilterMode::Nearest if desc.lod_clamp == (0.0..0.0) => {
551 MTLSamplerMipFilter::NotMipmapped
552 }
553 wgt::FilterMode::Nearest => MTLSamplerMipFilter::Nearest,
554 wgt::FilterMode::Linear => MTLSamplerMipFilter::Linear,
555 });
556
557 let [s, t, r] = desc.address_modes;
558 descriptor.set_address_mode_s(conv::map_address_mode(s));
559 descriptor.set_address_mode_t(conv::map_address_mode(t));
560 descriptor.set_address_mode_r(conv::map_address_mode(r));
561
562 // Anisotropy is always supported on mac up to 16x
563 descriptor.set_max_anisotropy(desc.anisotropy_clamp as _);
564
565 descriptor.set_lod_min_clamp(desc.lod_clamp.start);
566 descriptor.set_lod_max_clamp(desc.lod_clamp.end);
567
568 if let Some(fun) = desc.compare {
569 descriptor.set_compare_function(conv::map_compare_function(fun));
570 }
571
572 if let Some(border_color) = desc.border_color {
573 if let wgt::SamplerBorderColor::Zero = border_color {
574 if s == wgt::AddressMode::ClampToBorder {
575 descriptor.set_address_mode_s(MTLSamplerAddressMode::ClampToZero);
576 }
577
578 if t == wgt::AddressMode::ClampToBorder {
579 descriptor.set_address_mode_t(MTLSamplerAddressMode::ClampToZero);
580 }
581
582 if r == wgt::AddressMode::ClampToBorder {
583 descriptor.set_address_mode_r(MTLSamplerAddressMode::ClampToZero);
584 }
585 } else {
586 descriptor.set_border_color(conv::map_border_color(border_color));
587 }
588 }
589
590 if let Some(label) = desc.label {
591 descriptor.set_label(label);
592 }
593 if self.features.contains(wgt::Features::TEXTURE_BINDING_ARRAY) {
594 descriptor.set_support_argument_buffers(true);
595 }
596 let raw = self.shared.device.lock().new_sampler(&descriptor);
597
598 self.counters.samplers.add(1);
599
600 Ok(super::Sampler { raw })
601 })
602 }
603 unsafe fn destroy_sampler(&self, _sampler: super::Sampler) {
604 self.counters.samplers.sub(1);
605 }
606
607 unsafe fn create_command_encoder(
608 &self,
609 desc: &crate::CommandEncoderDescriptor<super::Queue>,
610 ) -> Result<super::CommandEncoder, crate::DeviceError> {
611 self.counters.command_encoders.add(1);
612 Ok(super::CommandEncoder {
613 shared: Arc::clone(&self.shared),
614 raw_queue: Arc::clone(&desc.queue.raw),
615 raw_cmd_buf: None,
616 state: super::CommandState::default(),
617 temp: super::Temp::default(),
618 counters: Arc::clone(&self.counters),
619 })
620 }
621
622 unsafe fn create_bind_group_layout(
623 &self,
624 desc: &crate::BindGroupLayoutDescriptor,
625 ) -> DeviceResult<super::BindGroupLayout> {
626 self.counters.bind_group_layouts.add(1);
627
628 Ok(super::BindGroupLayout {
629 entries: Arc::from(desc.entries),
630 })
631 }
632
633 unsafe fn destroy_bind_group_layout(&self, _bg_layout: super::BindGroupLayout) {
634 self.counters.bind_group_layouts.sub(1);
635 }
636
637 unsafe fn create_pipeline_layout(
638 &self,
639 desc: &crate::PipelineLayoutDescriptor<super::BindGroupLayout>,
640 ) -> DeviceResult<super::PipelineLayout> {
641 #[derive(Debug)]
642 struct StageInfo {
643 stage: naga::ShaderStage,
644 counters: super::ResourceData<super::ResourceIndex>,
645 pc_buffer: Option<super::ResourceIndex>,
646 pc_limit: u32,
647 sizes_buffer: Option<super::ResourceIndex>,
648 need_sizes_buffer: bool,
649 resources: naga::back::msl::BindingMap,
650 }
651
652 let mut stage_data = super::NAGA_STAGES.map(|stage| StageInfo {
653 stage,
654 counters: super::ResourceData::default(),
655 pc_buffer: None,
656 pc_limit: 0,
657 sizes_buffer: None,
658 need_sizes_buffer: false,
659 resources: Default::default(),
660 });
661 let mut bind_group_infos = arrayvec::ArrayVec::new();
662
663 // First, place the push constants
664 let mut total_push_constants = 0;
665 for info in stage_data.iter_mut() {
666 for pcr in desc.push_constant_ranges {
667 if pcr.stages.contains(map_naga_stage(info.stage)) {
668 debug_assert_eq!(pcr.range.end % 4, 0);
669 info.pc_limit = (pcr.range.end / 4).max(info.pc_limit);
670 }
671 }
672
673 // round up the limits alignment to 4, so that it matches MTL compiler logic
674 const LIMIT_MASK: u32 = 3;
675 //TODO: figure out what and how exactly does the alignment. Clearly, it's not
676 // straightforward, given that value of 2 stays non-aligned.
677 if info.pc_limit > LIMIT_MASK {
678 info.pc_limit = (info.pc_limit + LIMIT_MASK) & !LIMIT_MASK;
679 }
680
681 // handle the push constant buffer assignment and shader overrides
682 if info.pc_limit != 0 {
683 info.pc_buffer = Some(info.counters.buffers);
684 info.counters.buffers += 1;
685 }
686
687 total_push_constants = total_push_constants.max(info.pc_limit);
688 }
689
690 // Second, place the described resources
691 for (group_index, &bgl) in desc.bind_group_layouts.iter().enumerate() {
692 // remember where the resources for this set start at each shader stage
693 let base_resource_indices = stage_data.map_ref(|info| info.counters.clone());
694
695 for entry in bgl.entries.iter() {
696 if let wgt::BindingType::Buffer {
697 ty: wgt::BufferBindingType::Storage { .. },
698 ..
699 } = entry.ty
700 {
701 for info in stage_data.iter_mut() {
702 if entry.visibility.contains(map_naga_stage(info.stage)) {
703 info.need_sizes_buffer = true;
704 }
705 }
706 }
707
708 for info in stage_data.iter_mut() {
709 if !entry.visibility.contains(map_naga_stage(info.stage)) {
710 continue;
711 }
712
713 let mut target = naga::back::msl::BindTarget::default();
714 // Bindless path
715 if let Some(_) = entry.count {
716 target.buffer = Some(info.counters.buffers as _);
717 info.counters.buffers += 1;
718 } else {
719 match entry.ty {
720 wgt::BindingType::Buffer { ty, .. } => {
721 target.buffer = Some(info.counters.buffers as _);
722 info.counters.buffers += 1;
723 if let wgt::BufferBindingType::Storage { read_only } = ty {
724 target.mutable = !read_only;
725 }
726 }
727 wgt::BindingType::Sampler { .. } => {
728 target.sampler =
729 Some(naga::back::msl::BindSamplerTarget::Resource(
730 info.counters.samplers as _,
731 ));
732 info.counters.samplers += 1;
733 }
734 wgt::BindingType::Texture { .. } => {
735 target.texture = Some(info.counters.textures as _);
736 info.counters.textures += 1;
737 }
738 wgt::BindingType::StorageTexture { access, .. } => {
739 target.texture = Some(info.counters.textures as _);
740 info.counters.textures += 1;
741 target.mutable = match access {
742 wgt::StorageTextureAccess::ReadOnly => false,
743 wgt::StorageTextureAccess::WriteOnly => true,
744 wgt::StorageTextureAccess::ReadWrite => true,
745 wgt::StorageTextureAccess::Atomic => true,
746 };
747 }
748 wgt::BindingType::AccelerationStructure { .. } => unimplemented!(),
749 }
750 }
751
752 let br = naga::ResourceBinding {
753 group: group_index as u32,
754 binding: entry.binding,
755 };
756 info.resources.insert(br, target);
757 }
758 }
759
760 bind_group_infos.push(super::BindGroupLayoutInfo {
761 base_resource_indices,
762 });
763 }
764
765 // Finally, make sure we fit the limits
766 for info in stage_data.iter_mut() {
767 if info.need_sizes_buffer || info.stage == naga::ShaderStage::Vertex {
768 // Set aside space for the sizes_buffer, which is required
769 // for variable-length buffers, or to support vertex pulling.
770 info.sizes_buffer = Some(info.counters.buffers);
771 info.counters.buffers += 1;
772 }
773
774 if info.counters.buffers > self.shared.private_caps.max_buffers_per_stage
775 || info.counters.textures > self.shared.private_caps.max_textures_per_stage
776 || info.counters.samplers > self.shared.private_caps.max_samplers_per_stage
777 {
778 log::error!("Resource limit exceeded: {:?}", info);
779 return Err(crate::DeviceError::OutOfMemory);
780 }
781 }
782
783 let push_constants_infos = stage_data.map_ref(|info| {
784 info.pc_buffer.map(|buffer_index| super::PushConstantsInfo {
785 count: info.pc_limit,
786 buffer_index,
787 })
788 });
789
790 let total_counters = stage_data.map_ref(|info| info.counters.clone());
791
792 let per_stage_map = stage_data.map(|info| naga::back::msl::EntryPointResources {
793 push_constant_buffer: info
794 .pc_buffer
795 .map(|buffer_index| buffer_index as naga::back::msl::Slot),
796 sizes_buffer: info
797 .sizes_buffer
798 .map(|buffer_index| buffer_index as naga::back::msl::Slot),
799 resources: info.resources,
800 });
801
802 self.counters.pipeline_layouts.add(1);
803
804 Ok(super::PipelineLayout {
805 bind_group_infos,
806 push_constants_infos,
807 total_counters,
808 total_push_constants,
809 per_stage_map,
810 })
811 }
812
813 unsafe fn destroy_pipeline_layout(&self, _pipeline_layout: super::PipelineLayout) {
814 self.counters.pipeline_layouts.sub(1);
815 }
816
817 unsafe fn create_bind_group(
818 &self,
819 desc: &crate::BindGroupDescriptor<
820 super::BindGroupLayout,
821 super::Buffer,
822 super::Sampler,
823 super::TextureView,
824 super::AccelerationStructure,
825 >,
826 ) -> DeviceResult<super::BindGroup> {
827 objc::rc::autoreleasepool(|| {
828 let mut bg = super::BindGroup::default();
829 for (&stage, counter) in super::NAGA_STAGES.iter().zip(bg.counters.iter_mut()) {
830 let stage_bit = map_naga_stage(stage);
831 let mut dynamic_offsets_count = 0u32;
832 let layout_and_entry_iter = desc.entries.iter().map(|entry| {
833 let layout = desc
834 .layout
835 .entries
836 .iter()
837 .find(|layout_entry| layout_entry.binding == entry.binding)
838 .expect("internal error: no layout entry found with binding slot");
839 (entry, layout)
840 });
841 for (entry, layout) in layout_and_entry_iter {
842 // Bindless path
843 if layout.count.is_some() {
844 if !layout.visibility.contains(stage_bit) {
845 continue;
846 }
847
848 let count = entry.count;
849
850 let stages = conv::map_render_stages(layout.visibility);
851 let uses = conv::map_resource_usage(&layout.ty);
852
853 // Create argument buffer for this array
854 let buffer = self.shared.device.lock().new_buffer(
855 8 * count as u64,
856 MTLResourceOptions::HazardTrackingModeUntracked
857 | MTLResourceOptions::StorageModeShared,
858 );
859
860 let contents: &mut [MTLResourceID] = unsafe {
861 core::slice::from_raw_parts_mut(
862 buffer.contents().cast(),
863 count as usize,
864 )
865 };
866
867 match layout.ty {
868 wgt::BindingType::Texture { .. }
869 | wgt::BindingType::StorageTexture { .. } => {
870 let start = entry.resource_index as usize;
871 let end = start + count as usize;
872 let textures = &desc.textures[start..end];
873
874 for (idx, tex) in textures.iter().enumerate() {
875 contents[idx] = tex.view.raw.gpu_resource_id();
876
877 let use_info = bg
878 .resources_to_use
879 .entry(tex.view.as_raw().cast())
880 .or_default();
881 use_info.stages |= stages;
882 use_info.uses |= uses;
883 use_info.visible_in_compute |=
884 layout.visibility.contains(wgt::ShaderStages::COMPUTE);
885 }
886 }
887 wgt::BindingType::Sampler { .. } => {
888 let start = entry.resource_index as usize;
889 let end = start + count as usize;
890 let samplers = &desc.samplers[start..end];
891
892 for (idx, &sampler) in samplers.iter().enumerate() {
893 contents[idx] = sampler.raw.gpu_resource_id();
894 // Samplers aren't resources like buffers and textures, so don't
895 // need to be passed to useResource
896 }
897 }
898 _ => {
899 unimplemented!();
900 }
901 }
902
903 bg.buffers.push(super::BufferResource {
904 ptr: unsafe { NonNull::new_unchecked(buffer.as_ptr()) },
905 offset: 0,
906 dynamic_index: None,
907 binding_size: None,
908 binding_location: layout.binding,
909 });
910 counter.buffers += 1;
911
912 bg.argument_buffers.push(buffer)
913 }
914 // Bindfull path
915 else {
916 if let wgt::BindingType::Buffer {
917 has_dynamic_offset: true,
918 ..
919 } = layout.ty
920 {
921 dynamic_offsets_count += 1;
922 }
923 if !layout.visibility.contains(stage_bit) {
924 continue;
925 }
926 match layout.ty {
927 wgt::BindingType::Buffer {
928 ty,
929 has_dynamic_offset,
930 ..
931 } => {
932 let start = entry.resource_index as usize;
933 let end = start + 1;
934 bg.buffers
935 .extend(desc.buffers[start..end].iter().map(|source| {
936 // Given the restrictions on `BufferBinding::offset`,
937 // this should never be `None`.
938 let remaining_size = wgt::BufferSize::new(
939 source.buffer.size - source.offset,
940 );
941 let binding_size = match ty {
942 wgt::BufferBindingType::Storage { .. } => {
943 source.size.or(remaining_size)
944 }
945 _ => None,
946 };
947 super::BufferResource {
948 ptr: source.buffer.as_raw(),
949 offset: source.offset,
950 dynamic_index: if has_dynamic_offset {
951 Some(dynamic_offsets_count - 1)
952 } else {
953 None
954 },
955 binding_size,
956 binding_location: layout.binding,
957 }
958 }));
959 counter.buffers += 1;
960 }
961 wgt::BindingType::Sampler { .. } => {
962 let start = entry.resource_index as usize;
963 let end = start + 1;
964 bg.samplers.extend(
965 desc.samplers[start..end].iter().map(|samp| samp.as_raw()),
966 );
967 counter.samplers += 1;
968 }
969 wgt::BindingType::Texture { .. }
970 | wgt::BindingType::StorageTexture { .. } => {
971 let start = entry.resource_index as usize;
972 let end = start + 1;
973 bg.textures.extend(
974 desc.textures[start..end]
975 .iter()
976 .map(|tex| tex.view.as_raw()),
977 );
978 counter.textures += 1;
979 }
980 wgt::BindingType::AccelerationStructure { .. } => unimplemented!(),
981 }
982 }
983 }
984 }
985
986 self.counters.bind_groups.add(1);
987
988 Ok(bg)
989 })
990 }
991
992 unsafe fn destroy_bind_group(&self, _group: super::BindGroup) {
993 self.counters.bind_groups.sub(1);
994 }
995
996 unsafe fn create_shader_module(
997 &self,
998 desc: &crate::ShaderModuleDescriptor,
999 shader: crate::ShaderInput,
1000 ) -> Result<super::ShaderModule, crate::ShaderError> {
1001 self.counters.shader_modules.add(1);
1002
1003 match shader {
1004 crate::ShaderInput::Naga(naga) => Ok(super::ShaderModule {
1005 source: ShaderModuleSource::Naga(naga),
1006 bounds_checks: desc.runtime_checks,
1007 }),
1008 crate::ShaderInput::Msl {
1009 shader: source,
1010 entry_point,
1011 num_workgroups,
1012 } => {
1013 let options = metal::CompileOptions::new();
1014 // Obtain the locked device from shared
1015 let device = self.shared.device.lock();
1016 let library = device
1017 .new_library_with_source(&source, &options)
1018 .map_err(|e| crate::ShaderError::Compilation(format!("MSL: {:?}", e)))?;
1019 let function = library.get_function(&entry_point, None).map_err(|_| {
1020 crate::ShaderError::Compilation(format!(
1021 "Entry point '{}' not found",
1022 entry_point
1023 ))
1024 })?;
1025
1026 Ok(super::ShaderModule {
1027 source: ShaderModuleSource::Passthrough(PassthroughShader {
1028 library,
1029 function,
1030 entry_point,
1031 num_workgroups,
1032 }),
1033 bounds_checks: desc.runtime_checks,
1034 })
1035 }
1036 crate::ShaderInput::SpirV(_) => {
1037 panic!("SPIRV_SHADER_PASSTHROUGH is not enabled for this backend")
1038 }
1039 }
1040 }
1041
1042 unsafe fn destroy_shader_module(&self, _module: super::ShaderModule) {
1043 self.counters.shader_modules.sub(1);
1044 }
1045
1046 unsafe fn create_render_pipeline(
1047 &self,
1048 desc: &crate::RenderPipelineDescriptor<
1049 super::PipelineLayout,
1050 super::ShaderModule,
1051 super::PipelineCache,
1052 >,
1053 ) -> Result<super::RenderPipeline, crate::PipelineError> {
1054 objc::rc::autoreleasepool(|| {
1055 let descriptor = metal::RenderPipelineDescriptor::new();
1056
1057 let raw_triangle_fill_mode = match desc.primitive.polygon_mode {
1058 wgt::PolygonMode::Fill => MTLTriangleFillMode::Fill,
1059 wgt::PolygonMode::Line => MTLTriangleFillMode::Lines,
1060 wgt::PolygonMode::Point => panic!(
1061 "{:?} is not enabled for this backend",
1062 wgt::Features::POLYGON_MODE_POINT
1063 ),
1064 };
1065
1066 let (primitive_class, raw_primitive_type) =
1067 conv::map_primitive_topology(desc.primitive.topology);
1068
1069 // Vertex shader
1070 let (vs_lib, vs_info) = {
1071 let mut vertex_buffer_mappings = Vec::<naga::back::msl::VertexBufferMapping>::new();
1072 for (i, vbl) in desc.vertex_buffers.iter().enumerate() {
1073 let mut attributes = Vec::<naga::back::msl::AttributeMapping>::new();
1074 for attribute in vbl.attributes.iter() {
1075 attributes.push(naga::back::msl::AttributeMapping {
1076 shader_location: attribute.shader_location,
1077 offset: attribute.offset as u32,
1078 format: convert_vertex_format_to_naga(attribute.format),
1079 });
1080 }
1081
1082 vertex_buffer_mappings.push(naga::back::msl::VertexBufferMapping {
1083 id: self.shared.private_caps.max_vertex_buffers - 1 - i as u32,
1084 stride: if vbl.array_stride > 0 {
1085 vbl.array_stride.try_into().unwrap()
1086 } else {
1087 vbl.attributes
1088 .iter()
1089 .map(|attribute| attribute.offset + attribute.format.size())
1090 .max()
1091 .unwrap_or(0)
1092 .try_into()
1093 .unwrap()
1094 },
1095 indexed_by_vertex: (vbl.step_mode == wgt::VertexStepMode::Vertex {}),
1096 attributes,
1097 });
1098 }
1099
1100 let vs = self.load_shader(
1101 &desc.vertex_stage,
1102 &vertex_buffer_mappings,
1103 desc.layout,
1104 primitive_class,
1105 naga::ShaderStage::Vertex,
1106 )?;
1107
1108 descriptor.set_vertex_function(Some(&vs.function));
1109 if self.shared.private_caps.supports_mutability {
1110 Self::set_buffers_mutability(
1111 descriptor.vertex_buffers().unwrap(),
1112 vs.immutable_buffer_mask,
1113 );
1114 }
1115
1116 let info = super::PipelineStageInfo {
1117 push_constants: desc.layout.push_constants_infos.vs,
1118 sizes_slot: desc.layout.per_stage_map.vs.sizes_buffer,
1119 sized_bindings: vs.sized_bindings,
1120 vertex_buffer_mappings,
1121 };
1122
1123 (vs.library, info)
1124 };
1125
1126 // Fragment shader
1127 let (fs_lib, fs_info) = match desc.fragment_stage {
1128 Some(ref stage) => {
1129 let fs = self.load_shader(
1130 stage,
1131 &[],
1132 desc.layout,
1133 primitive_class,
1134 naga::ShaderStage::Fragment,
1135 )?;
1136
1137 descriptor.set_fragment_function(Some(&fs.function));
1138 if self.shared.private_caps.supports_mutability {
1139 Self::set_buffers_mutability(
1140 descriptor.fragment_buffers().unwrap(),
1141 fs.immutable_buffer_mask,
1142 );
1143 }
1144
1145 let info = super::PipelineStageInfo {
1146 push_constants: desc.layout.push_constants_infos.fs,
1147 sizes_slot: desc.layout.per_stage_map.fs.sizes_buffer,
1148 sized_bindings: fs.sized_bindings,
1149 vertex_buffer_mappings: vec![],
1150 };
1151
1152 (Some(fs.library), Some(info))
1153 }
1154 None => {
1155 // TODO: This is a workaround for what appears to be a Metal validation bug
1156 // A pixel format is required even though no attachments are provided
1157 if desc.color_targets.is_empty() && desc.depth_stencil.is_none() {
1158 descriptor.set_depth_attachment_pixel_format(MTLPixelFormat::Depth32Float);
1159 }
1160 (None, None)
1161 }
1162 };
1163
1164 for (i, ct) in desc.color_targets.iter().enumerate() {
1165 let at_descriptor = descriptor.color_attachments().object_at(i as u64).unwrap();
1166 let ct = if let Some(color_target) = ct.as_ref() {
1167 color_target
1168 } else {
1169 at_descriptor.set_pixel_format(MTLPixelFormat::Invalid);
1170 continue;
1171 };
1172
1173 let raw_format = self.shared.private_caps.map_format(ct.format);
1174 at_descriptor.set_pixel_format(raw_format);
1175 at_descriptor.set_write_mask(conv::map_color_write(ct.write_mask));
1176
1177 if let Some(ref blend) = ct.blend {
1178 at_descriptor.set_blending_enabled(true);
1179 let (color_op, color_src, color_dst) = conv::map_blend_component(&blend.color);
1180 let (alpha_op, alpha_src, alpha_dst) = conv::map_blend_component(&blend.alpha);
1181
1182 at_descriptor.set_rgb_blend_operation(color_op);
1183 at_descriptor.set_source_rgb_blend_factor(color_src);
1184 at_descriptor.set_destination_rgb_blend_factor(color_dst);
1185
1186 at_descriptor.set_alpha_blend_operation(alpha_op);
1187 at_descriptor.set_source_alpha_blend_factor(alpha_src);
1188 at_descriptor.set_destination_alpha_blend_factor(alpha_dst);
1189 }
1190 }
1191
1192 let depth_stencil = match desc.depth_stencil {
1193 Some(ref ds) => {
1194 let raw_format = self.shared.private_caps.map_format(ds.format);
1195 let aspects = crate::FormatAspects::from(ds.format);
1196 if aspects.contains(crate::FormatAspects::DEPTH) {
1197 descriptor.set_depth_attachment_pixel_format(raw_format);
1198 }
1199 if aspects.contains(crate::FormatAspects::STENCIL) {
1200 descriptor.set_stencil_attachment_pixel_format(raw_format);
1201 }
1202
1203 let ds_descriptor = create_depth_stencil_desc(ds);
1204 let raw = self
1205 .shared
1206 .device
1207 .lock()
1208 .new_depth_stencil_state(&ds_descriptor);
1209 Some((raw, ds.bias))
1210 }
1211 None => None,
1212 };
1213
1214 if desc.layout.total_counters.vs.buffers + (desc.vertex_buffers.len() as u32)
1215 > self.shared.private_caps.max_vertex_buffers
1216 {
1217 let msg = format!(
1218 "pipeline needs too many buffers in the vertex stage: {} vertex and {} layout",
1219 desc.vertex_buffers.len(),
1220 desc.layout.total_counters.vs.buffers
1221 );
1222 return Err(crate::PipelineError::Linkage(
1223 wgt::ShaderStages::VERTEX,
1224 msg,
1225 ));
1226 }
1227
1228 if !desc.vertex_buffers.is_empty() {
1229 let vertex_descriptor = metal::VertexDescriptor::new();
1230 for (i, vb) in desc.vertex_buffers.iter().enumerate() {
1231 let buffer_index =
1232 self.shared.private_caps.max_vertex_buffers as u64 - 1 - i as u64;
1233 let buffer_desc = vertex_descriptor.layouts().object_at(buffer_index).unwrap();
1234
1235 // Metal expects the stride to be the actual size of the attributes.
1236 // The semantics of array_stride == 0 can be achieved by setting
1237 // the step function to constant and rate to 0.
1238 if vb.array_stride == 0 {
1239 let stride = vb
1240 .attributes
1241 .iter()
1242 .map(|attribute| attribute.offset + attribute.format.size())
1243 .max()
1244 .unwrap_or(0);
1245 buffer_desc.set_stride(wgt::math::align_to(stride, 4));
1246 buffer_desc.set_step_function(MTLVertexStepFunction::Constant);
1247 buffer_desc.set_step_rate(0);
1248 } else {
1249 buffer_desc.set_stride(vb.array_stride);
1250 buffer_desc.set_step_function(conv::map_step_mode(vb.step_mode));
1251 }
1252
1253 for at in vb.attributes {
1254 let attribute_desc = vertex_descriptor
1255 .attributes()
1256 .object_at(at.shader_location as u64)
1257 .unwrap();
1258 attribute_desc.set_format(conv::map_vertex_format(at.format));
1259 attribute_desc.set_buffer_index(buffer_index);
1260 attribute_desc.set_offset(at.offset);
1261 }
1262 }
1263 descriptor.set_vertex_descriptor(Some(vertex_descriptor));
1264 }
1265
1266 if desc.multisample.count != 1 {
1267 //TODO: handle sample mask
1268 descriptor.set_sample_count(desc.multisample.count as u64);
1269 descriptor
1270 .set_alpha_to_coverage_enabled(desc.multisample.alpha_to_coverage_enabled);
1271 //descriptor.set_alpha_to_one_enabled(desc.multisample.alpha_to_one_enabled);
1272 }
1273
1274 if let Some(name) = desc.label {
1275 descriptor.set_label(name);
1276 }
1277
1278 let raw = self
1279 .shared
1280 .device
1281 .lock()
1282 .new_render_pipeline_state(&descriptor)
1283 .map_err(|e| {
1284 crate::PipelineError::Linkage(
1285 wgt::ShaderStages::VERTEX | wgt::ShaderStages::FRAGMENT,
1286 format!("new_render_pipeline_state: {:?}", e),
1287 )
1288 })?;
1289
1290 self.counters.render_pipelines.add(1);
1291
1292 Ok(super::RenderPipeline {
1293 raw,
1294 vs_lib,
1295 fs_lib,
1296 vs_info,
1297 fs_info,
1298 raw_primitive_type,
1299 raw_triangle_fill_mode,
1300 raw_front_winding: conv::map_winding(desc.primitive.front_face),
1301 raw_cull_mode: conv::map_cull_mode(desc.primitive.cull_mode),
1302 raw_depth_clip_mode: if self.features.contains(wgt::Features::DEPTH_CLIP_CONTROL) {
1303 Some(if desc.primitive.unclipped_depth {
1304 MTLDepthClipMode::Clamp
1305 } else {
1306 MTLDepthClipMode::Clip
1307 })
1308 } else {
1309 None
1310 },
1311 depth_stencil,
1312 })
1313 })
1314 }
1315
1316 unsafe fn create_mesh_pipeline(
1317 &self,
1318 _desc: &crate::MeshPipelineDescriptor<
1319 <Self::A as crate::Api>::PipelineLayout,
1320 <Self::A as crate::Api>::ShaderModule,
1321 <Self::A as crate::Api>::PipelineCache,
1322 >,
1323 ) -> Result<<Self::A as crate::Api>::RenderPipeline, crate::PipelineError> {
1324 unreachable!()
1325 }
1326
1327 unsafe fn destroy_render_pipeline(&self, _pipeline: super::RenderPipeline) {
1328 self.counters.render_pipelines.sub(1);
1329 }
1330
1331 unsafe fn create_compute_pipeline(
1332 &self,
1333 desc: &crate::ComputePipelineDescriptor<
1334 super::PipelineLayout,
1335 super::ShaderModule,
1336 super::PipelineCache,
1337 >,
1338 ) -> Result<super::ComputePipeline, crate::PipelineError> {
1339 objc::rc::autoreleasepool(|| {
1340 let descriptor = metal::ComputePipelineDescriptor::new();
1341
1342 let module = desc.stage.module;
1343 let cs = if let ShaderModuleSource::Passthrough(desc) = &module.source {
1344 CompiledShader {
1345 library: desc.library.clone(),
1346 function: desc.function.clone(),
1347 wg_size: MTLSize::new(
1348 desc.num_workgroups.0 as u64,
1349 desc.num_workgroups.1 as u64,
1350 desc.num_workgroups.2 as u64,
1351 ),
1352 wg_memory_sizes: vec![],
1353 sized_bindings: vec![],
1354 immutable_buffer_mask: 0,
1355 }
1356 } else {
1357 self.load_shader(
1358 &desc.stage,
1359 &[],
1360 desc.layout,
1361 MTLPrimitiveTopologyClass::Unspecified,
1362 naga::ShaderStage::Compute,
1363 )?
1364 };
1365
1366 descriptor.set_compute_function(Some(&cs.function));
1367
1368 if self.shared.private_caps.supports_mutability {
1369 Self::set_buffers_mutability(
1370 descriptor.buffers().unwrap(),
1371 cs.immutable_buffer_mask,
1372 );
1373 }
1374
1375 let cs_info = super::PipelineStageInfo {
1376 push_constants: desc.layout.push_constants_infos.cs,
1377 sizes_slot: desc.layout.per_stage_map.cs.sizes_buffer,
1378 sized_bindings: cs.sized_bindings,
1379 vertex_buffer_mappings: vec![],
1380 };
1381
1382 if let Some(name) = desc.label {
1383 descriptor.set_label(name);
1384 }
1385
1386 let raw = self
1387 .shared
1388 .device
1389 .lock()
1390 .new_compute_pipeline_state(&descriptor)
1391 .map_err(|e| {
1392 crate::PipelineError::Linkage(
1393 wgt::ShaderStages::COMPUTE,
1394 format!("new_compute_pipeline_state: {:?}", e),
1395 )
1396 })?;
1397
1398 self.counters.compute_pipelines.add(1);
1399
1400 Ok(super::ComputePipeline {
1401 raw,
1402 cs_info,
1403 cs_lib: cs.library,
1404 work_group_size: cs.wg_size,
1405 work_group_memory_sizes: cs.wg_memory_sizes,
1406 })
1407 })
1408 }
1409
1410 unsafe fn destroy_compute_pipeline(&self, _pipeline: super::ComputePipeline) {
1411 self.counters.compute_pipelines.sub(1);
1412 }
1413
1414 unsafe fn create_pipeline_cache(
1415 &self,
1416 _desc: &crate::PipelineCacheDescriptor<'_>,
1417 ) -> Result<super::PipelineCache, crate::PipelineCacheError> {
1418 Ok(super::PipelineCache)
1419 }
1420 unsafe fn destroy_pipeline_cache(&self, _: super::PipelineCache) {}
1421
1422 unsafe fn create_query_set(
1423 &self,
1424 desc: &wgt::QuerySetDescriptor<crate::Label>,
1425 ) -> DeviceResult<super::QuerySet> {
1426 objc::rc::autoreleasepool(|| {
1427 match desc.ty {
1428 wgt::QueryType::Occlusion => {
1429 let size = desc.count as u64 * crate::QUERY_SIZE;
1430 let options = MTLResourceOptions::empty();
1431 //TODO: HazardTrackingModeUntracked
1432 let raw_buffer = self.shared.device.lock().new_buffer(size, options);
1433 if let Some(label) = desc.label {
1434 raw_buffer.set_label(label);
1435 }
1436 Ok(super::QuerySet {
1437 raw_buffer,
1438 counter_sample_buffer: None,
1439 ty: desc.ty,
1440 })
1441 }
1442 wgt::QueryType::Timestamp => {
1443 let size = desc.count as u64 * crate::QUERY_SIZE;
1444 let device = self.shared.device.lock();
1445 let destination_buffer = device.new_buffer(size, MTLResourceOptions::empty());
1446
1447 let csb_desc = metal::CounterSampleBufferDescriptor::new();
1448 csb_desc.set_storage_mode(MTLStorageMode::Shared);
1449 csb_desc.set_sample_count(desc.count as _);
1450 if let Some(label) = desc.label {
1451 csb_desc.set_label(label);
1452 }
1453
1454 let counter_sets = device.counter_sets();
1455 let timestamp_counter =
1456 match counter_sets.iter().find(|cs| cs.name() == "timestamp") {
1457 Some(counter) => counter,
1458 None => {
1459 log::error!("Failed to obtain timestamp counter set.");
1460 return Err(crate::DeviceError::ResourceCreationFailed);
1461 }
1462 };
1463 csb_desc.set_counter_set(timestamp_counter);
1464
1465 let counter_sample_buffer =
1466 match device.new_counter_sample_buffer_with_descriptor(&csb_desc) {
1467 Ok(buffer) => buffer,
1468 Err(err) => {
1469 log::error!("Failed to create counter sample buffer: {:?}", err);
1470 return Err(crate::DeviceError::ResourceCreationFailed);
1471 }
1472 };
1473
1474 self.counters.query_sets.add(1);
1475
1476 Ok(super::QuerySet {
1477 raw_buffer: destination_buffer,
1478 counter_sample_buffer: Some(counter_sample_buffer),
1479 ty: desc.ty,
1480 })
1481 }
1482 _ => {
1483 todo!()
1484 }
1485 }
1486 })
1487 }
1488
1489 unsafe fn destroy_query_set(&self, _set: super::QuerySet) {
1490 self.counters.query_sets.add(1);
1491 }
1492
1493 unsafe fn create_fence(&self) -> DeviceResult<super::Fence> {
1494 self.counters.fences.add(1);
1495 let shared_event = if self.shared.private_caps.supports_shared_event {
1496 Some(self.shared.device.lock().new_shared_event())
1497 } else {
1498 None
1499 };
1500 Ok(super::Fence {
1501 completed_value: Arc::new(atomic::AtomicU64::new(0)),
1502 pending_command_buffers: Vec::new(),
1503 shared_event,
1504 })
1505 }
1506
1507 unsafe fn destroy_fence(&self, _fence: super::Fence) {
1508 self.counters.fences.sub(1);
1509 }
1510
1511 unsafe fn get_fence_value(&self, fence: &super::Fence) -> DeviceResult<crate::FenceValue> {
1512 let mut max_value = fence.completed_value.load(atomic::Ordering::Acquire);
1513 for &(value, ref cmd_buf) in fence.pending_command_buffers.iter() {
1514 if cmd_buf.status() == MTLCommandBufferStatus::Completed {
1515 max_value = value;
1516 }
1517 }
1518 Ok(max_value)
1519 }
1520 unsafe fn wait(
1521 &self,
1522 fence: &super::Fence,
1523 wait_value: crate::FenceValue,
1524 timeout_ms: u32,
1525 ) -> DeviceResult<bool> {
1526 if wait_value <= fence.completed_value.load(atomic::Ordering::Acquire) {
1527 return Ok(true);
1528 }
1529
1530 let cmd_buf = match fence
1531 .pending_command_buffers
1532 .iter()
1533 .find(|&&(value, _)| value >= wait_value)
1534 {
1535 Some((_, cmd_buf)) => cmd_buf,
1536 None => {
1537 log::error!("No active command buffers for fence value {}", wait_value);
1538 return Err(crate::DeviceError::Lost);
1539 }
1540 };
1541
1542 let start = time::Instant::now();
1543 loop {
1544 if let MTLCommandBufferStatus::Completed = cmd_buf.status() {
1545 return Ok(true);
1546 }
1547 if start.elapsed().as_millis() >= timeout_ms as u128 {
1548 return Ok(false);
1549 }
1550 thread::sleep(core::time::Duration::from_millis(1));
1551 }
1552 }
1553
1554 unsafe fn start_graphics_debugger_capture(&self) -> bool {
1555 if !self.shared.private_caps.supports_capture_manager {
1556 return false;
1557 }
1558 let device = self.shared.device.lock();
1559 let shared_capture_manager = metal::CaptureManager::shared();
1560 let default_capture_scope = shared_capture_manager.new_capture_scope_with_device(&device);
1561 shared_capture_manager.set_default_capture_scope(&default_capture_scope);
1562 shared_capture_manager.start_capture_with_scope(&default_capture_scope);
1563 default_capture_scope.begin_scope();
1564 true
1565 }
1566
1567 unsafe fn stop_graphics_debugger_capture(&self) {
1568 let shared_capture_manager = metal::CaptureManager::shared();
1569 if let Some(default_capture_scope) = shared_capture_manager.default_capture_scope() {
1570 default_capture_scope.end_scope();
1571 }
1572 shared_capture_manager.stop_capture();
1573 }
1574
1575 unsafe fn get_acceleration_structure_build_sizes(
1576 &self,
1577 _desc: &crate::GetAccelerationStructureBuildSizesDescriptor<super::Buffer>,
1578 ) -> crate::AccelerationStructureBuildSizes {
1579 unimplemented!()
1580 }
1581
1582 unsafe fn get_acceleration_structure_device_address(
1583 &self,
1584 _acceleration_structure: &super::AccelerationStructure,
1585 ) -> wgt::BufferAddress {
1586 unimplemented!()
1587 }
1588
1589 unsafe fn create_acceleration_structure(
1590 &self,
1591 _desc: &crate::AccelerationStructureDescriptor,
1592 ) -> Result<super::AccelerationStructure, crate::DeviceError> {
1593 unimplemented!()
1594 }
1595
1596 unsafe fn destroy_acceleration_structure(
1597 &self,
1598 _acceleration_structure: super::AccelerationStructure,
1599 ) {
1600 unimplemented!()
1601 }
1602
1603 fn tlas_instance_to_bytes(&self, _instance: TlasInstance) -> Vec<u8> {
1604 unimplemented!()
1605 }
1606
1607 fn get_internal_counters(&self) -> wgt::HalCounters {
1608 self.counters.as_ref().clone()
1609 }
1610
1611 fn check_if_oom(&self) -> Result<(), crate::DeviceError> {
1612 // TODO: see https://github.com/gfx-rs/wgpu/issues/7460
1613
1614 Ok(())
1615 }
1616 }