Debian Codegraph @

third_party/rust/metal/src/mps.rs

raw
1 // Copyright 2020 GFX developers
2 //
3 // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4 // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5 // http://opensource.org/licenses/MIT>, at your option. This file may not be
6 // copied, modified, or distributed except according to those terms.
7
8 use super::*;
9
10 use objc::runtime::BOOL;
11
12 #[cfg_attr(
13 feature = "link",
14 link(name = "MetalPerformanceShaders", kind = "framework")
15 )]
16 extern "C" {
17 fn MPSSupportsMTLDevice(device: *const std::ffi::c_void) -> BOOL;
18 }
19
20 pub fn mps_supports_device(device: &DeviceRef) -> bool {
21 let b: BOOL = unsafe {
22 let ptr: *const DeviceRef = device;
23 MPSSupportsMTLDevice(ptr as _)
24 };
25 b == YES
26 }
27
28 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpskernel>
29 pub enum MPSKernel {}
30
31 foreign_obj_type! {
32 type CType = MPSKernel;
33 pub struct Kernel;
34 }
35
36 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsraydatatype>
37 pub enum MPSRayDataType {
38 OriginDirection = 0,
39 OriginMinDistanceDirectionMaxDistance = 1,
40 OriginMaskDirectionMaxDistance = 2,
41 }
42
43 bitflags::bitflags! {
44 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsraymaskoptions>
45 #[allow(non_upper_case_globals)]
46 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
47 pub struct MPSRayMaskOptions: NSUInteger {
48 /// Enable primitive masks
49 const Primitive = 1;
50 /// Enable instance masks
51 const Instance = 2;
52 }
53 }
54
55 /// Options that determine the data contained in an intersection result.
56 ///
57 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsintersectiondatatype>
58 pub enum MPSIntersectionDataType {
59 Distance = 0,
60 DistancePrimitiveIndex = 1,
61 DistancePrimitiveIndexCoordinates = 2,
62 DistancePrimitiveIndexInstanceIndex = 3,
63 DistancePrimitiveIndexInstanceIndexCoordinates = 4,
64 }
65
66 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsintersectiontype>
67 pub enum MPSIntersectionType {
68 /// Find the closest intersection to the ray's origin along the ray direction.
69 /// This is potentially slower than `Any` but is well suited to primary visibility rays.
70 Nearest = 0,
71 /// Find any intersection along the ray direction. This is potentially faster than `Nearest` and
72 /// is well suited to shadow and occlusion rays.
73 Any = 1,
74 }
75
76 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsraymaskoperator>
77 pub enum MPSRayMaskOperator {
78 /// Accept the intersection if `(primitive mask & ray mask) != 0`.
79 And = 0,
80 /// Accept the intersection if `~(primitive mask & ray mask) != 0`.
81 NotAnd = 1,
82 /// Accept the intersection if `(primitive mask | ray mask) != 0`.
83 Or = 2,
84 /// Accept the intersection if `~(primitive mask | ray mask) != 0`.
85 NotOr = 3,
86 /// Accept the intersection if `(primitive mask ^ ray mask) != 0`.
87 /// Note that this is equivalent to the "!=" operator.
88 Xor = 4,
89 /// Accept the intersection if `~(primitive mask ^ ray mask) != 0`.
90 /// Note that this is equivalent to the "==" operator.
91 NotXor = 5,
92 /// Accept the intersection if `(primitive mask < ray mask) != 0`.
93 LessThan = 6,
94 /// Accept the intersection if `(primitive mask <= ray mask) != 0`.
95 LessThanOrEqualTo = 7,
96 /// Accept the intersection if `(primitive mask > ray mask) != 0`.
97 GreaterThan = 8,
98 /// Accept the intersection if `(primitive mask >= ray mask) != 0`.
99 GreaterThanOrEqualTo = 9,
100 }
101
102 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpstriangleintersectiontesttype>
103 pub enum MPSTriangleIntersectionTestType {
104 /// Use the default ray/triangle intersection test
105 Default = 0,
106 /// Use a watertight ray/triangle intersection test which avoids gaps along shared triangle edges.
107 /// Shared vertices may still have gaps.
108 /// This intersection test may be slower than `Default`.
109 Watertight = 1,
110 }
111
112 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsaccelerationstructurestatus>
113 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
114 pub enum MPSAccelerationStructureStatus {
115 Unbuilt = 0,
116 Built = 1,
117 }
118
119 bitflags::bitflags! {
120 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsaccelerationstructureusage>
121 #[allow(non_upper_case_globals)]
122 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
123 pub struct MPSAccelerationStructureUsage: NSUInteger {
124 /// No usage options specified
125 const None = 0;
126 /// Option that enables support for refitting the acceleration structure after it has been built.
127 const Refit = 1;
128 /// Option indicating that the acceleration structure will be rebuilt frequently.
129 const FrequentRebuild = 2;
130 const PreferGPUBuild = 4;
131 const PreferCPUBuild = 8;
132 }
133 }
134
135 /// A common bit for all floating point data types.
136 const MPSDataTypeFloatBit: isize = 0x10000000;
137 const MPSDataTypeSignedBit: isize = 0x20000000;
138 const MPSDataTypeNormalizedBit: isize = 0x40000000;
139
140 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsdatatype>
141 pub enum MPSDataType {
142 Invalid = 0,
143
144 Float32 = MPSDataTypeFloatBit | 32,
145 Float16 = MPSDataTypeFloatBit | 16,
146
147 // Signed integers.
148 Int8 = MPSDataTypeSignedBit | 8,
149 Int16 = MPSDataTypeSignedBit | 16,
150 Int32 = MPSDataTypeSignedBit | 32,
151
152 // Unsigned integers. Range: [0, UTYPE_MAX]
153 UInt8 = 8,
154 UInt16 = 16,
155 UInt32 = 32,
156
157 // Unsigned normalized. Range: [0, 1.0]
158 Unorm1 = MPSDataTypeNormalizedBit | 1,
159 Unorm8 = MPSDataTypeNormalizedBit | 8,
160 }
161
162 /// A kernel that performs intersection tests between rays and geometry.
163 ///
164 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsrayintersector>
165 pub enum MPSRayIntersector {}
166
167 foreign_obj_type! {
168 type CType = MPSRayIntersector;
169 pub struct RayIntersector;
170 type ParentType = Kernel;
171 }
172
173 impl RayIntersector {
174 pub fn from_device(device: &DeviceRef) -> Option<Self> {
175 unsafe {
176 let intersector: RayIntersector = msg_send![class!(MPSRayIntersector), alloc];
177 let ptr: *mut Object = msg_send![intersector.as_ref(), initWithDevice: device];
178 if ptr.is_null() {
179 None
180 } else {
181 Some(intersector)
182 }
183 }
184 }
185 }
186
187 impl RayIntersectorRef {
188 pub fn set_cull_mode(&self, mode: MTLCullMode) {
189 unsafe { msg_send![self, setCullMode: mode] }
190 }
191
192 pub fn set_front_facing_winding(&self, winding: MTLWinding) {
193 unsafe { msg_send![self, setFrontFacingWinding: winding] }
194 }
195
196 pub fn set_intersection_data_type(&self, options: MPSIntersectionDataType) {
197 unsafe { msg_send![self, setIntersectionDataType: options] }
198 }
199
200 pub fn set_intersection_stride(&self, stride: NSUInteger) {
201 unsafe { msg_send![self, setIntersectionStride: stride] }
202 }
203
204 pub fn set_ray_data_type(&self, ty: MPSRayDataType) {
205 unsafe { msg_send![self, setRayDataType: ty] }
206 }
207
208 pub fn set_ray_index_data_type(&self, ty: MPSDataType) {
209 unsafe { msg_send![self, setRayIndexDataType: ty] }
210 }
211
212 pub fn set_ray_mask(&self, ray_mask: u32) {
213 unsafe { msg_send![self, setRayMask: ray_mask] }
214 }
215
216 pub fn set_ray_mask_operator(&self, operator: MPSRayMaskOperator) {
217 unsafe { msg_send![self, setRayMaskOperator: operator] }
218 }
219
220 pub fn set_ray_mask_options(&self, options: MPSRayMaskOptions) {
221 unsafe { msg_send![self, setRayMaskOptions: options] }
222 }
223
224 pub fn set_ray_stride(&self, stride: NSUInteger) {
225 unsafe { msg_send![self, setRayStride: stride] }
226 }
227
228 pub fn set_triangle_intersection_test_type(&self, test_type: MPSTriangleIntersectionTestType) {
229 unsafe { msg_send![self, setTriangleIntersectionTestType: test_type] }
230 }
231
232 pub fn encode_intersection_to_command_buffer(
233 &self,
234 command_buffer: &CommandBufferRef,
235 intersection_type: MPSIntersectionType,
236 ray_buffer: &BufferRef,
237 ray_buffer_offset: NSUInteger,
238 intersection_buffer: &BufferRef,
239 intersection_buffer_offset: NSUInteger,
240 ray_count: NSUInteger,
241 acceleration_structure: &AccelerationStructureRef,
242 ) {
243 unsafe {
244 msg_send![
245 self,
246 encodeIntersectionToCommandBuffer: command_buffer
247 intersectionType: intersection_type
248 rayBuffer: ray_buffer
249 rayBufferOffset: ray_buffer_offset
250 intersectionBuffer: intersection_buffer
251 intersectionBufferOffset: intersection_buffer_offset
252 rayCount: ray_count
253 accelerationStructure: acceleration_structure
254 ]
255 }
256 }
257
258 pub fn recommended_minimum_ray_batch_size_for_ray_count(
259 &self,
260 ray_count: NSUInteger,
261 ) -> NSUInteger {
262 unsafe { msg_send![self, recommendedMinimumRayBatchSizeForRayCount: ray_count] }
263 }
264 }
265
266 /// A group of acceleration structures which may be used together in an instance acceleration structure.
267 ///
268 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsaccelerationstructuregroup>
269 pub enum MPSAccelerationStructureGroup {}
270
271 foreign_obj_type! {
272 type CType = MPSAccelerationStructureGroup;
273 pub struct AccelerationStructureGroup;
274 }
275
276 impl AccelerationStructureGroup {
277 pub fn new_with_device(device: &DeviceRef) -> Option<Self> {
278 unsafe {
279 let group: AccelerationStructureGroup =
280 msg_send![class!(MPSAccelerationStructureGroup), alloc];
281 let ptr: *mut Object = msg_send![group.as_ref(), initWithDevice: device];
282 if ptr.is_null() {
283 None
284 } else {
285 Some(group)
286 }
287 }
288 }
289 }
290
291 impl AccelerationStructureGroupRef {
292 pub fn device(&self) -> &DeviceRef {
293 unsafe { msg_send![self, device] }
294 }
295 }
296
297 /// The base class for data structures that are built over geometry and used to accelerate ray tracing.
298 ///
299 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsaccelerationstructure>
300 pub enum MPSAccelerationStructure {}
301
302 foreign_obj_type! {
303 type CType = MPSAccelerationStructure;
304 pub struct AccelerationStructure;
305 }
306
307 impl AccelerationStructureRef {
308 pub fn status(&self) -> MPSAccelerationStructureStatus {
309 unsafe { msg_send![self, status] }
310 }
311
312 pub fn usage(&self) -> MPSAccelerationStructureUsage {
313 unsafe { msg_send![self, usage] }
314 }
315
316 pub fn set_usage(&self, usage: MPSAccelerationStructureUsage) {
317 unsafe { msg_send![self, setUsage: usage] }
318 }
319
320 pub fn group(&self) -> &AccelerationStructureGroupRef {
321 unsafe { msg_send![self, group] }
322 }
323
324 pub fn encode_refit_to_command_buffer(&self, buffer: &CommandBufferRef) {
325 unsafe { msg_send![self, encodeRefitToCommandBuffer: buffer] }
326 }
327
328 pub fn rebuild(&self) {
329 unsafe { msg_send![self, rebuild] }
330 }
331 }
332
333 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpspolygonaccelerationstructure>
334 pub enum MPSPolygonAccelerationStructure {}
335
336 foreign_obj_type! {
337 type CType = MPSPolygonAccelerationStructure;
338 pub struct PolygonAccelerationStructure;
339 type ParentType = AccelerationStructure;
340 }
341
342 impl PolygonAccelerationStructureRef {
343 pub fn set_index_buffer(&self, buffer: Option<&BufferRef>) {
344 unsafe { msg_send![self, setIndexBuffer: buffer] }
345 }
346
347 pub fn set_index_buffer_offset(&self, offset: NSUInteger) {
348 unsafe { msg_send![self, setIndexBufferOffset: offset] }
349 }
350
351 pub fn set_index_type(&self, data_type: MPSDataType) {
352 unsafe { msg_send![self, setIndexType: data_type] }
353 }
354
355 pub fn set_mask_buffer(&self, buffer: Option<&BufferRef>) {
356 unsafe { msg_send![self, setMaskBuffer: buffer] }
357 }
358
359 pub fn set_mask_buffer_offset(&self, offset: NSUInteger) {
360 unsafe { msg_send![self, setMaskBufferOffset: offset] }
361 }
362
363 pub fn set_vertex_buffer(&self, buffer: Option<&BufferRef>) {
364 unsafe { msg_send![self, setVertexBuffer: buffer] }
365 }
366
367 pub fn set_vertex_buffer_offset(&self, offset: NSUInteger) {
368 unsafe { msg_send![self, setVertexBufferOffset: offset] }
369 }
370
371 pub fn set_vertex_stride(&self, stride: NSUInteger) {
372 unsafe { msg_send![self, setVertexStride: stride] }
373 }
374 }
375
376 /// An acceleration structure built over triangles.
377 ///
378 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpstriangleaccelerationstructure>
379 pub enum MPSTriangleAccelerationStructure {}
380
381 foreign_obj_type! {
382 type CType = MPSTriangleAccelerationStructure;
383 pub struct TriangleAccelerationStructure;
384 type ParentType = PolygonAccelerationStructure;
385 }
386
387 impl TriangleAccelerationStructure {
388 pub fn from_device(device: &DeviceRef) -> Option<Self> {
389 unsafe {
390 let structure: TriangleAccelerationStructure =
391 msg_send![class!(MPSTriangleAccelerationStructure), alloc];
392 let ptr: *mut Object = msg_send![structure.as_ref(), initWithDevice: device];
393 if ptr.is_null() {
394 None
395 } else {
396 Some(structure)
397 }
398 }
399 }
400 }
401
402 impl TriangleAccelerationStructureRef {
403 pub fn triangle_count(&self) -> NSUInteger {
404 unsafe { msg_send![self, triangleCount] }
405 }
406
407 pub fn set_triangle_count(&self, count: NSUInteger) {
408 unsafe { msg_send![self, setTriangleCount: count] }
409 }
410 }
411
412 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpstransformtype>
413 #[repr(u64)]
414 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
415 pub enum MPSTransformType {
416 Float4x4 = 0,
417 Identity = 1,
418 }
419
420 /// An acceleration structure built over instances of other acceleration structures
421 ///
422 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsinstanceaccelerationstructure>
423 pub enum MPSInstanceAccelerationStructure {}
424
425 foreign_obj_type! {
426 type CType = MPSInstanceAccelerationStructure;
427 pub struct InstanceAccelerationStructure;
428 type ParentType = AccelerationStructure;
429 }
430
431 impl InstanceAccelerationStructure {
432 pub fn init_with_group(group: &AccelerationStructureGroupRef) -> Option<Self> {
433 unsafe {
434 let structure: InstanceAccelerationStructure =
435 msg_send![class!(MPSInstanceAccelerationStructure), alloc];
436 let ptr: *mut Object = msg_send![structure.as_ref(), initWithGroup: group];
437 if ptr.is_null() {
438 None
439 } else {
440 Some(structure)
441 }
442 }
443 }
444 }
445
446 impl InstanceAccelerationStructureRef {
447 /// Marshal to Rust Vec
448 pub fn acceleration_structures(&self) -> Vec<PolygonAccelerationStructure> {
449 unsafe {
450 let acs: *mut Object = msg_send![self, accelerationStructures];
451 let count: NSUInteger = msg_send![acs, count];
452 (0..count)
453 .map(|i| {
454 let ac = msg_send![acs, objectAtIndex: i];
455 PolygonAccelerationStructure::from_ptr(ac)
456 })
457 .collect()
458 }
459 }
460
461 /// Marshal from Rust slice
462 pub fn set_acceleration_structures(&self, acs: &[&PolygonAccelerationStructureRef]) {
463 let ns_array = Array::<PolygonAccelerationStructure>::from_slice(acs);
464 unsafe { msg_send![self, setAccelerationStructures: ns_array] }
465 }
466
467 pub fn instance_buffer(&self) -> &BufferRef {
468 unsafe { msg_send![self, instanceBuffer] }
469 }
470
471 pub fn set_instance_buffer(&self, buffer: &BufferRef) {
472 unsafe { msg_send![self, setInstanceBuffer: buffer] }
473 }
474
475 pub fn instance_buffer_offset(&self) -> NSUInteger {
476 unsafe { msg_send![self, instanceBufferOffset] }
477 }
478
479 pub fn set_instance_buffer_offset(&self, offset: NSUInteger) {
480 unsafe { msg_send![self, setInstanceBufferOffset: offset] }
481 }
482
483 pub fn transform_buffer(&self) -> &BufferRef {
484 unsafe { msg_send![self, transformBuffer] }
485 }
486
487 pub fn set_transform_buffer(&self, buffer: &BufferRef) {
488 unsafe { msg_send![self, setTransformBuffer: buffer] }
489 }
490
491 pub fn transform_buffer_offset(&self) -> NSUInteger {
492 unsafe { msg_send![self, transformBufferOffset] }
493 }
494
495 pub fn set_transform_buffer_offset(&self, offset: NSUInteger) {
496 unsafe { msg_send![self, setTransformBufferOffset: offset] }
497 }
498
499 pub fn transform_type(&self) -> MPSTransformType {
500 unsafe { msg_send![self, transformType] }
501 }
502
503 pub fn set_transform_type(&self, transform_type: MPSTransformType) {
504 unsafe { msg_send![self, setTransformType: transform_type] }
505 }
506
507 pub fn mask_buffer(&self) -> &BufferRef {
508 unsafe { msg_send![self, maskBuffer] }
509 }
510
511 pub fn set_mask_buffer(&self, buffer: &BufferRef) {
512 unsafe { msg_send![self, setMaskBuffer: buffer] }
513 }
514
515 pub fn mask_buffer_offset(&self) -> NSUInteger {
516 unsafe { msg_send![self, maskBufferOffset] }
517 }
518
519 pub fn set_mask_buffer_offset(&self, offset: NSUInteger) {
520 unsafe { msg_send![self, setMaskBufferOffset: offset] }
521 }
522
523 pub fn instance_count(&self) -> NSUInteger {
524 unsafe { msg_send![self, instanceCount] }
525 }
526
527 pub fn set_instance_count(&self, count: NSUInteger) {
528 unsafe { msg_send![self, setInstanceCount: count] }
529 }
530 }
531
532 #[repr(C)]
533 pub struct MPSPackedFloat3 {
534 pub elements: [f32; 3],
535 }
536
537 /// Represents a 3D ray with an origin, a direction, and an intersection distance range from the origin.
538 ///
539 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsrayoriginmindistancedirectionmaxdistance>
540 #[repr(C)]
541 pub struct MPSRayOriginMinDistanceDirectionMaxDistance {
542 /// Ray origin. The intersection test will be skipped if the origin contains NaNs or infinities.
543 pub origin: MPSPackedFloat3,
544 /// Minimum intersection distance from the origin along the ray direction.
545 /// The intersection test will be skipped if the minimum distance is equal to positive infinity or NaN.
546 pub min_distance: f32,
547 /// Ray direction. Does not need to be normalized. The intersection test will be skipped if
548 /// the direction has length zero or contains NaNs or infinities.
549 pub direction: MPSPackedFloat3,
550 /// Maximum intersection distance from the origin along the ray direction. May be infinite.
551 /// The intersection test will be skipped if the maximum distance is less than zero, NaN, or
552 /// less than the minimum intersection distance.
553 pub max_distance: f32,
554 }
555
556 /// Intersection result which contains the distance from the ray origin to the intersection point,
557 /// the index of the intersected primitive, and the first two barycentric coordinates of the intersection point.
558 ///
559 /// See <https://developer.apple.com/documentation/metalperformanceshaders/mpsintersectiondistanceprimitiveindexcoordinates>
560 #[repr(C)]
561 pub struct MPSIntersectionDistancePrimitiveIndexCoordinates {
562 /// Distance from the ray origin to the intersection point along the ray direction vector such
563 /// that `intersection = ray.origin + ray.direction * distance`.
564 /// Is negative if there is no intersection. If the intersection type is `MPSIntersectionTypeAny`,
565 /// is a positive value for a hit or a negative value for a miss.
566 pub distance: f32,
567 /// Index of the intersected primitive. Undefined if the ray does not intersect a primitive or
568 /// if the intersection type is `MPSIntersectionTypeAny`.
569 pub primitive_index: u32,
570 /// The first two barycentric coordinates `U` and `V` of the intersection point.
571 /// The third coordinate `W = 1 - U - V`. Undefined if the ray does not intersect a primitive or
572 /// if the intersection type is `MPSIntersectionTypeAny`.
573 pub coordinates: [f32; 2],
574 }