pub struct MPSAccelerationStructure { /* private fields */ }MPSAccelerationStructure and MPSCore and MPSKernel only.Expand description
A data structure built over geometry used to accelerate ray tracing
Do not use this base class directly. Use one of the derived classes instead. The general pattern for creating an acceleration structure is as follows. First, create the acceleration structure:
MPSTriangleAccelerationStructure *accelerationStructure = nil;
accelerationStructure = [[MPSTriangleAccelerationStructure alloc] initWithDevice:device];Then, assign values to the acceleration structureโs properties:
accelerationStructure.vertexBuffer = vertexBuffer;
accelerationStructure.triangleCount = triangleCount;Finally, the acceleration structure must be built:
[accelerationStructure rebuild];The acceleration structure can then be used to encode ray intersection tests with an MPSRayIntersector:
[raytracer encodeIntersectionToCommandBuffer:commandBuffer
intersectionType:MPSIntersectionTypeNearest
rayBuffer:rayBuffer
rayBufferOffset:0
intersectionBuffer:intersectionBuffer
intersectionBufferOffset:0
rayCount:rayCount
accelerationStructure:accelerationStructure];Asynchronous Acceleration Structure Builds: Rebuilding an acceleration structure is an expensive operation. Note that there is also a method to rebuild the acceleration structure asynchronously to avoid blocking the main thread.
[accelerationStructure rebuildWithCompletionHandler:^(MPSAccelerationStructure *accel) {
// Kick off ray intersection work
}];Streaming Geometry Updates: It is generally safe to change buffer properties such as the vertex buffer after intersection tests have been encoded into a command buffer, but the contents of those buffers cannot be safely changed by the CPU until the command buffer has finished executing on the GPU. It is also not safe to rebuild the acceleration structure until the command buffer has completed.
If the CPU needs to stream geometry updates to the GPU, ensure the vertex and other buffers are double or triple buffered.
#define MAX_ASYNC_OPERATIONS 3
// Initialization:
// Create a semaphore with the maximum number of asynchronous operations in flight
dispatch_semaphore_t asyncOperationSemaphore = dispatch_semaphore_create(MAX_ASYNC_OPERATIONS);
// Create an acceleration structure for each vertex buffer range
NSMutableArray *accelerationStructures = [NSMutableArray array];
NSUInteger vertexBufferLength = sizeof(float3) * vertexCount * MAX_ASYNC_OPERATIONS;
id <MTLBuffer> vertexBuffer = [device newBufferWithLength:vertexBufferLength
options:MTLResourceStorageModeManaged];
for (NSUInteger i = 0; i < MAX_ASYNC_OPERATIONS; i++) {
MPSTriangleAccelerationStructure *accel = nil;
accel = [[MPSTriangleAccelerationStructure alloc] initWithDevice:device];
// Configure acceleration structure
accel.vertexBuffer = vertexBuffer;
accel.vertexBufferOffset = i * sizeof(float3) * vertexCount;
[accelerationStructures addObject:accel];
}
NSUInteger asyncOperationIndex = 0;
// Encode intersection testing:
// Wait until there is a free acceleration structure
dispatch_semaphore_wait(asyncOperationSemaphore, DISPATCH_TIME_FOREVER);
MPSTriangleAccelerationStructure *accel = accelerationStructures[asyncOperationIndex];
asyncOperationIndex = (asyncOperationIndex + 1) % MAX_ASYNC_OPERATIONS;
float3 *vertices = (float3 *)((uint8_t *)vertexBuffer.contents + accel.vertexBufferOffset);
// Update vertices
MPSDidModifyRange(vertexBuffer, NSMakeRange(accel.vertexBufferOffset, sizeof(float3) * vertexCount));
// Rebuild the acceleration structure
[accel rebuild];
// Encode actual intersection work
[raytracer encodeIntersectionToCommandBuffer:commandBuffer
intersectionType:MPSIntersectionTypeNearest
rayBuffer:rayBuffer
rayBufferOffset:rayBufferOffset
intersectionBuffer:intersectionBuffer
intersectionBufferOffset:intersectionBufferOffset
rayCount:rayCount
accelerationStructure:accel];
// Register a completion handler to run when the GPU finishes executing
[commandBuffer addCompletedHandler:^(id <MTLCommandBuffer> commandBuffer) {
Intersection *intersections = (Intersection *)((uint8_t *)intersectionBuffer.contents +
intersectionBufferOffset);
// Process intersections
// Signal that the acceleration structure is now available for reuse
dispatch_semaphore_signal(asyncOperationSemaphore);
}];
// Commit the command buffer to allow the GPU to start executing
[commandBuffer commit];Refitting acceleration structures: If geometry has only moved slightly and not added or removed from the scene, it can be much faster to refit the existing topology of an acceleration structure to the new geometry than to rebuild the acceleration structure from scratch. Refitting can also be pipelined with other GPU work such as intersection testing. If the geometry is transformed entirely on the GPU, it is not necessary to use double or triple buffering. For example:
id <MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
id <MTLComputeCommandEncoder> encoder = [commandBuffer computeCommandEncoder];
[encoder setBuffer:untransformedVertexBuffer offset:0 atIndex:0];
[encoder setBuffer:accelerationStructure.vertexBuffer
offset:accelerationStructure.vertexBufferOffset
atIndex:1];
[encoder setBuffer:transformationMatrices offset:0 atIndex:2];
[encoder setComputePipelineState:transformVerticesPipeline];
[encoder dispatchThreads:MTLSizeMake(accelerationStructure.triangleCount * 3, 1, 1)
threadsPerThreadgroup:MTLSizeMake(64, 1, 1)];
[encoder endEncoding];
[accelerationStructure encodeRefitToCommandBuffer:commandBuffer];
[commandBuffer commit];Serializing Acceleration Structures: Instead of rebuilding acceleration structures from scratch they can be built offline, serialized, and reloaded at runtime using the NSSecureCoding protocol:
// Build time:
NSError *error = nil;
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:accel
requiringSecureCoding:YES
error:&error];
if (!data)
NSLog(@"Error archiving MPSAccelerationStructure: %@",
error.localizedDescription);
// Runtime:
MPSTriangleAccelerationStructure *accel;
accel = [NSKeyedUnarchiver unarchivedObjectOfClass:[MPSTriangleAccelerationStructure class]
fromData:data
error:&error];
if (!accel)
NSLog(@"Error unarchiving MPSAccelerationStructure: %@",
error.localizedDescription);Copying Acceleration Structures: Acceleration structures can be copied using the NSCopying protocol, even to a different Metal device. This can be used for multi-GPU raytracing. Buffer properties are not copied to the new acceleration structure. These buffers must instead be copied to the new Metal device and assigned to the new acceleration structure. For example:
MPSTriangleAccelerationStructure *copy = [accelerationStructure copyWithZone:nil
device:newDevice];
copy.vertexBuffer = [self copyBuffer:accelerationStructure.vertexBuffer
withDevice:newDevice];Performance Guidelines:
-
Provide accurate acceleration structure hints: if an acceleration structure does not require support for refitting, a higher quality construction algorithm can be used. However, if an acceleration structure must be rebuilt frequently, a lower quality but higher performance construction algorithm can be used.
-
Consider refitting existing acceleration structures rather than rebuilding them from scratch. This is typically much faster and can result in a reasonably high quality tree if the geometry has not been modified dramatically. Refitting can also be pipelined with other GPU work. If objects have been added to or removed from the scene, it is typically necessary to rebuild the acceleration structure rather than refit it.
-
Rebuild acceleration structures asynchronously when possible to avoid blocking the main thread. Consider presenting a UI indicating that work is happening in the background while allowing the user to consider interacting with your application.
-
If you need to mix intersection testing with acceleration structure builds (e.g. if the user is interactively editing the scene while rendering or if objects are moving significantly) consider allocating two independent acceleration structures that refer to two copies of the scene data. Then, asynchronously rebuild one acceleration structure while the other one is used for rendering. Once the rebuild has completed, swap the acceleration structures. The intermediate frames could be filled by refitting the rendering acceleration structure until the rebuilt acceleration structure is ready.
-
When running in Xcode, disable โEnable Backtrace Recordingโ in your scheme settings. Enabling this setting can significantly increase acceleration structure build time.
-
Consider using quadrilaterals instead of triangles to represent your geometry. The cost of intersecting a quadrilateral is typically less than the cost of intersecting two triangles, so quadrilaterals can improve performance. Quadrilaterals also typically require 30-40% less memory than triangles including vertex data and internal buffers allocated by the acceleration structure. Whether quadrilaterals improve or hurt performance can depend on the geometry and ray distribution, so you should choose whichever performs better for your application.
Thread Safety: MPSAccelerationStructures are generally not thread safe. Changing properties and rebuilding acceleration structures from multiple threads result in undefined behavior. However, it is safe to encode intersection tests with a single acceleration structure from multiple threads as long as each thread uses its own MPSRayIntersector.
See also Appleโs documentation
Implementationsยง
Sourceยงimpl MPSAccelerationStructure
impl MPSAccelerationStructure
Sourcepub unsafe fn group(&self) -> Retained<MPSAccelerationStructureGroup>
๐DeprecatedAvailable on crate features MPSRayIntersector and MPSAccelerationStructureGroup only.
pub unsafe fn group(&self) -> Retained<MPSAccelerationStructureGroup>
MPSRayIntersector and MPSAccelerationStructureGroup only.The group this acceleration structure was created with
Sourcepub unsafe fn status(&self) -> MPSAccelerationStructureStatus
๐DeprecatedAvailable on crate feature MPSRayIntersector only.
pub unsafe fn status(&self) -> MPSAccelerationStructureStatus
MPSRayIntersector only.Status indicating whether the acceleration structure has finished building
Sourcepub unsafe fn usage(&self) -> MPSAccelerationStructureUsage
๐DeprecatedAvailable on crate feature MPSRayIntersector only.
pub unsafe fn usage(&self) -> MPSAccelerationStructureUsage
MPSRayIntersector only.Acceleration structure usage options. Changes to this property require rebuilding the acceleration structure. Defaults to MPSAccelerationStructureUsageNone.
Sourcepub unsafe fn setUsage(&self, usage: MPSAccelerationStructureUsage)
๐DeprecatedAvailable on crate feature MPSRayIntersector only.
pub unsafe fn setUsage(&self, usage: MPSAccelerationStructureUsage)
MPSRayIntersector only.Setter for usage.
pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>
MPSRayIntersector only.Sourcepub unsafe fn initWithDevice(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
) -> Retained<Self>
๐DeprecatedAvailable on crate feature MPSRayIntersector only.
pub unsafe fn initWithDevice( this: Allocated<Self>, device: &ProtocolObject<dyn MTLDevice>, ) -> Retained<Self>
MPSRayIntersector only.Initialize the acceleration structure with a Metal device
Sourcepub unsafe fn initWithCoder_device(
this: Allocated<Self>,
a_decoder: &NSCoder,
device: &ProtocolObject<dyn MTLDevice>,
) -> Option<Retained<Self>>
๐DeprecatedAvailable on crate feature MPSRayIntersector only.
pub unsafe fn initWithCoder_device( this: Allocated<Self>, a_decoder: &NSCoder, device: &ProtocolObject<dyn MTLDevice>, ) -> Option<Retained<Self>>
MPSRayIntersector only.Initialize the acceleration structure with an NSCoder and a Metal device. Buffer properties such as the vertex buffer, instance buffer, etc. are set to nil. Encode and decode these buffers along with the acceleration structure instead.
ยงSafety
a_decoder possibly has further requirements.
Sourcepub unsafe fn initWithGroup(
this: Allocated<Self>,
group: &MPSAccelerationStructureGroup,
) -> Retained<Self>
๐DeprecatedAvailable on crate features MPSRayIntersector and MPSAccelerationStructureGroup only.
pub unsafe fn initWithGroup( this: Allocated<Self>, group: &MPSAccelerationStructureGroup, ) -> Retained<Self>
MPSRayIntersector and MPSAccelerationStructureGroup only.Initialize the acceleration structure with an acceleration structure group, if the acceleration structure will be used in an instance hierarchy.
The Metal device is determined from the acceleration structure group. All acceleration structures in the instance hierarchy must share the same group.
Sourcepub unsafe fn initWithCoder_group(
this: Allocated<Self>,
a_decoder: &NSCoder,
group: &MPSAccelerationStructureGroup,
) -> Option<Retained<Self>>
๐DeprecatedAvailable on crate features MPSRayIntersector and MPSAccelerationStructureGroup only.
pub unsafe fn initWithCoder_group( this: Allocated<Self>, a_decoder: &NSCoder, group: &MPSAccelerationStructureGroup, ) -> Option<Retained<Self>>
MPSRayIntersector and MPSAccelerationStructureGroup only.Initialize the acceleration structure with an NSCoder and an acceleration structure group, if the acceleration structure will be used in an instance hierarchy. All acceleration structures in the instance hierarchy must share the same group. Buffer properties such as the vertex buffer, instance buffer, etc. are set to nil. Encode and decode these buffers along with the acceleration structure instead.
ยงSafety
a_decoder possibly has further requirements.
Sourcepub unsafe fn rebuild(&self)
๐DeprecatedAvailable on crate feature MPSRayIntersector only.
pub unsafe fn rebuild(&self)
MPSRayIntersector only.Rebuild the acceleration structure
This method must be called before any intersection tests can be scheduled with this acceleration structure. Before calling this method, fill out the properties of the acceleration structure such as vertex buffer, instance buffer, etc. The acceleration structure should be rebuilt when its contents (e.g. vertices in a triangle acceleration structure) have been modified significantly and must be rebuilt when properties such as triangle count, vertex stride, etc. have changed. When the contents of the acceleration structure have only been modified slightly, it may be cheaper to refit the acceleration structure instead.
This method blocks until the acceleration structure has been rebuilt. Until the rebuild has completed, the acceleration structure cannot be copied, encoded with NSSecureCoding, rebuilt, or refit. Before this method can be called, any pending GPU writes to the vertex buffer, index buffer, etc. must be completed (and, for managed buffers, synchronized). Any prior intersection tests must also be completed before the acceleration structure can be rebuilt.
Sourcepub unsafe fn rebuildWithCompletionHandler(
&self,
completion_handler: MPSAccelerationStructureCompletionHandler,
)
๐DeprecatedAvailable on crate features MPSRayIntersector and block2 only.
pub unsafe fn rebuildWithCompletionHandler( &self, completion_handler: MPSAccelerationStructureCompletionHandler, )
MPSRayIntersector and block2 only.Rebuild the acceleration structure asynchronously
This method must be called before any intersection tests can be scheduled with this acceleration structure. Before calling this method, fill out the properties of the acceleration structure such as vertex buffer, instance buffer, etc. The acceleration structure should be rebuilt when its contents (e.g. vertices in a triangle acceleration structure) have been modified significantly and must be rebuilt when properties such as triangle count, vertex stride, etc. have changed. When the contents of the acceleration structure have only been modified slightly, it may be cheaper to refit the acceleration structure instead.
Until the rebuild has completed, the acceleration structure cannot be copied, encoded with NSSecureCoding, rebuilt, or refit. Before this method can be called, any pending GPU writes to the vertex buffer, index buffer, etc. must be completed (and, for managed buffers, synchronized). Any prior intersection tests must also be completed before the acceleration structure can be rebuilt.
ยงSafety
completion_handler must be a valid pointer.
Sourcepub unsafe fn encodeRefitToCommandBuffer(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
)
๐DeprecatedAvailable on crate feature MPSRayIntersector only.
pub unsafe fn encodeRefitToCommandBuffer( &self, command_buffer: &ProtocolObject<dyn MTLCommandBuffer>, )
MPSRayIntersector only.Refit the existing acceleration structure to new data
This method is used to refit the acceleration structure to new vertex data, index data, instance data, etc. while preserving the existing acceleration structure topology. This is typically much faster than a full rebuild of the acceleration structure. Refitting can also be pipelined with other GPU work such as ray intersection.
Until the command buffer has completed, the acceleration structure cannot be copied, encoded with NSSecureCoding, or rebuilt. Changes to properties such as the triangle count or instance count might not be reflected. These changes require that the acceleration structure be rebuilt instead. The acceleration structure must be rebuilt at least once before this method can be called.
Sourcepub unsafe fn copyWithZone_device(
&self,
zone: *mut NSZone,
device: Option<&ProtocolObject<dyn MTLDevice>>,
) -> Retained<Self>
๐DeprecatedAvailable on crate feature MPSRayIntersector only.
pub unsafe fn copyWithZone_device( &self, zone: *mut NSZone, device: Option<&ProtocolObject<dyn MTLDevice>>, ) -> Retained<Self>
MPSRayIntersector only.Create a a copy of this acceleration structure
The acceleration structure may be copied to a different Metal device. Buffer properties of the acceleration structure such as the vertex buffer, instance, buffer, etc. are set to nil. Copy these buffers to the new Metal device and assign them to the new acceleration structure instead. Do not copy the acceleration structure until any prior refit or rebuild operations have completed.
Parameter zone: This parameter is ignored. Memory zones are no longer used by Objective-C.
Parameter device: New Metal device
ยงSafety
zone must be a valid pointer or null.
Sourcepub unsafe fn copyWithZone_group(
&self,
zone: *mut NSZone,
group: &MPSAccelerationStructureGroup,
) -> Retained<Self>
๐DeprecatedAvailable on crate features MPSRayIntersector and MPSAccelerationStructureGroup only.
pub unsafe fn copyWithZone_group( &self, zone: *mut NSZone, group: &MPSAccelerationStructureGroup, ) -> Retained<Self>
MPSRayIntersector and MPSAccelerationStructureGroup only.Create a a copy of this acceleration structure
The acceleration structure may be copied with a different acceleration structure group. Buffer properties of the acceleration structure such as the vertex buffer, instance buffer, etc. are set to nil. Copy these buffers with the new Metal device and assign them to the new acceleration structure instead. Do not copy the acceleration structure until any prior refit or rebuild operations have completed.
Parameter zone: This parameter is ignored. Memory zones are no longer used by Objective-C.
Parameter group: New acceleration structure group
ยงSafety
zone must be a valid pointer or null.
Sourcepub unsafe fn encodeWithCoder(&self, coder: &NSCoder)
๐DeprecatedAvailable on crate feature MPSRayIntersector only.
pub unsafe fn encodeWithCoder(&self, coder: &NSCoder)
MPSRayIntersector only.Encode the acceleration structure with an NSCoder
Buffer properties such as the vertex buffer, index buffer, etc. are not be encoded. Encode and decode these buffers along with the acceleration structure instead. Do not encode the acceleration structure until any prior refit or rebuild operations have completed.
Parameter coder: An archiver object
ยงSafety
coder possibly has further requirements.
Sourceยงimpl MPSAccelerationStructure
Methods declared on superclass MPSKernel.
impl MPSAccelerationStructure
Methods declared on superclass MPSKernel.
Sourcepub unsafe fn initWithCoder(
this: Allocated<Self>,
a_decoder: &NSCoder,
) -> Option<Retained<Self>>
Available on crate feature MPSRayIntersector only.
pub unsafe fn initWithCoder( this: Allocated<Self>, a_decoder: &NSCoder, ) -> Option<Retained<Self>>
MPSRayIntersector only.Called by NSCoder to decode MPSKernels
This isnโt the right interface to decode a MPSKernel, but it is the one that NSCoder uses. To enable your NSCoder (e.g. NSKeyedUnarchiver) to set which device to use extend the object to adopt the MPSDeviceProvider protocol. Otherwise, the Metal system default device will be used.
ยงSafety
a_decoder possibly has further requirements.
Methods from Deref<Target = MPSKernel>ยง
Sourcepub unsafe fn options(&self) -> MPSKernelOptions
Available on crate feature MPSCoreTypes only.
pub unsafe fn options(&self) -> MPSKernelOptions
MPSCoreTypes only.The set of options used to run the kernel. subsubsection_options
Sourcepub unsafe fn setOptions(&self, options: MPSKernelOptions)
Available on crate feature MPSCoreTypes only.
pub unsafe fn setOptions(&self, options: MPSKernelOptions)
MPSCoreTypes only.Setter for options.
Sourcepub unsafe fn device(&self) -> Retained<ProtocolObject<dyn MTLDevice>>
pub unsafe fn device(&self) -> Retained<ProtocolObject<dyn MTLDevice>>
The device on which the kernel will be used
Sourcepub unsafe fn label(&self) -> Option<Retained<NSString>>
pub unsafe fn label(&self) -> Option<Retained<NSString>>
A string to help identify this object.
Sourcepub unsafe fn copyWithZone_device(
&self,
zone: *mut NSZone,
device: Option<&ProtocolObject<dyn MTLDevice>>,
) -> Retained<Self>
pub unsafe fn copyWithZone_device( &self, zone: *mut NSZone, device: Option<&ProtocolObject<dyn MTLDevice>>, ) -> Retained<Self>
Make a copy of this MPSKernel for a new device
-copyWithZone: will call this API to make a copy of the MPSKernel on the same device. This interface may also be called directly to make a copy of the MPSKernel on a new device. Typically, the same MPSKernels should not be used to encode kernels on multiple command buffers from multiple threads. Many MPSKernels have mutable properties that might be changed by the other thread while this one is trying to encode. If you need to use a MPSKernel from multiple threads make a copy of it for each additional thread using -copyWithZone: or -copyWithZone:device:
Parameter zone: The NSZone in which to allocate the object
Parameter device: The device for the new MPSKernel. If nil, then use
self.device.
Returns: a pointer to a copy of this MPSKernel. This will fail, returning nil if the device is not supported. Devices must be MTLFeatureSet_iOS_GPUFamily2_v1 or later.
ยงSafety
zone must be a valid pointer or null.
Methods from Deref<Target = NSObject>ยง
Sourcepub fn doesNotRecognizeSelector(&self, sel: Sel) -> !
pub fn doesNotRecognizeSelector(&self, sel: Sel) -> !
Handle messages the object doesnโt recognize.
See Appleโs documentation for details.
Methods from Deref<Target = AnyObject>ยง
Sourcepub fn class(&self) -> &'static AnyClass
pub fn class(&self) -> &'static AnyClass
Dynamically find the class of this object.
ยงPanics
May panic if the object is invalid (which may be the case for objects
returned from unavailable init/new methods).
ยงExample
Check that an instance of NSObject has the precise class NSObject.
use objc2::ClassType;
use objc2::runtime::NSObject;
let obj = NSObject::new();
assert_eq!(obj.class(), NSObject::class());Sourcepub unsafe fn get_ivar<T>(&self, name: &str) -> &Twhere
T: Encode,
๐Deprecated: this is difficult to use correctly, use Ivar::load instead.
pub unsafe fn get_ivar<T>(&self, name: &str) -> &Twhere
T: Encode,
Ivar::load instead.Use Ivar::load instead.
ยงSafety
The object must have an instance variable with the given name, and it
must be of type T.
See Ivar::load_ptr for details surrounding this.
Sourcepub fn downcast_ref<T>(&self) -> Option<&T>where
T: DowncastTarget,
pub fn downcast_ref<T>(&self) -> Option<&T>where
T: DowncastTarget,
Attempt to downcast the object to a class of type T.
This is the reference-variant. Use Retained::downcast if you want
to convert a retained object to another type.
ยงMutable classes
Some classes have immutable and mutable variants, such as NSString
and NSMutableString.
When some Objective-C API signature says it gives you an immutable class, it generally expects you to not mutate that, even though it may technically be mutable โunder the hoodโ.
So using this method to convert a NSString to a NSMutableString,
while not unsound, is generally frowned upon unless you created the
string yourself, or the API explicitly documents the string to be
mutable.
See Appleโs documentation on mutability and on
isKindOfClass: for more details.
ยงGeneric classes
Objective-C generics are called โlightweight genericsโ, and thatโs because they arenโt exposed in the runtime. This makes it impossible to safely downcast to generic collections, so this is disallowed by this method.
You can, however, safely downcast to generic collections where all the
type-parameters are AnyObject.
ยงPanics
This works internally by calling isKindOfClass:. That means that the
object must have the instance method of that name, and an exception
will be thrown (if CoreFoundation is linked) or the process will abort
if that is not the case. In the vast majority of cases, you donโt need
to worry about this, since both root objects NSObject and
NSProxy implement this method.
ยงExamples
Cast an NSString back and forth from NSObject.
use objc2::rc::Retained;
use objc2_foundation::{NSObject, NSString};
let obj: Retained<NSObject> = NSString::new().into_super();
let string = obj.downcast_ref::<NSString>().unwrap();
// Or with `downcast`, if we do not need the object afterwards
let string = obj.downcast::<NSString>().unwrap();Try (and fail) to cast an NSObject to an NSString.
use objc2_foundation::{NSObject, NSString};
let obj = NSObject::new();
assert!(obj.downcast_ref::<NSString>().is_none());Try to cast to an array of strings.
use objc2_foundation::{NSArray, NSObject, NSString};
let arr = NSArray::from_retained_slice(&[NSObject::new()]);
// This is invalid and doesn't type check.
let arr = arr.downcast_ref::<NSArray<NSString>>();This fails to compile, since it would require enumerating over the array to ensure that each element is of the desired type, which is a performance pitfall.
Downcast when processing each element instead.
use objc2_foundation::{NSArray, NSObject, NSString};
let arr = NSArray::from_retained_slice(&[NSObject::new()]);
for elem in arr {
if let Some(data) = elem.downcast_ref::<NSString>() {
// handle `data`
}
}Trait Implementationsยง
Sourceยงimpl AsRef<AnyObject> for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl AsRef<AnyObject> for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl AsRef<MPSAccelerationStructure> for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl AsRef<MPSAccelerationStructure> for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl AsRef<MPSAccelerationStructure> for MPSInstanceAccelerationStructure
Available on crate features MPSInstanceAccelerationStructure and MPSRayIntersector only.
impl AsRef<MPSAccelerationStructure> for MPSInstanceAccelerationStructure
MPSInstanceAccelerationStructure and MPSRayIntersector only.Sourceยงfn as_ref(&self) -> &MPSAccelerationStructure
fn as_ref(&self) -> &MPSAccelerationStructure
Sourceยงimpl AsRef<MPSAccelerationStructure> for MPSPolygonAccelerationStructure
Available on crate features MPSPolygonAccelerationStructure and MPSRayIntersector only.
impl AsRef<MPSAccelerationStructure> for MPSPolygonAccelerationStructure
MPSPolygonAccelerationStructure and MPSRayIntersector only.Sourceยงfn as_ref(&self) -> &MPSAccelerationStructure
fn as_ref(&self) -> &MPSAccelerationStructure
Sourceยงimpl AsRef<MPSAccelerationStructure> for MPSQuadrilateralAccelerationStructure
Available on crate features MPSQuadrilateralAccelerationStructure and MPSRayIntersector and MPSPolygonAccelerationStructure only.
impl AsRef<MPSAccelerationStructure> for MPSQuadrilateralAccelerationStructure
MPSQuadrilateralAccelerationStructure and MPSRayIntersector and MPSPolygonAccelerationStructure only.Sourceยงfn as_ref(&self) -> &MPSAccelerationStructure
fn as_ref(&self) -> &MPSAccelerationStructure
Sourceยงimpl AsRef<MPSAccelerationStructure> for MPSTriangleAccelerationStructure
Available on crate features MPSTriangleAccelerationStructure and MPSRayIntersector and MPSPolygonAccelerationStructure only.
impl AsRef<MPSAccelerationStructure> for MPSTriangleAccelerationStructure
MPSTriangleAccelerationStructure and MPSRayIntersector and MPSPolygonAccelerationStructure only.Sourceยงfn as_ref(&self) -> &MPSAccelerationStructure
fn as_ref(&self) -> &MPSAccelerationStructure
Sourceยงimpl AsRef<MPSKernel> for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl AsRef<MPSKernel> for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl AsRef<NSObject> for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl AsRef<NSObject> for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl Borrow<AnyObject> for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl Borrow<AnyObject> for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl Borrow<MPSAccelerationStructure> for MPSInstanceAccelerationStructure
Available on crate features MPSInstanceAccelerationStructure and MPSRayIntersector only.
impl Borrow<MPSAccelerationStructure> for MPSInstanceAccelerationStructure
MPSInstanceAccelerationStructure and MPSRayIntersector only.Sourceยงfn borrow(&self) -> &MPSAccelerationStructure
fn borrow(&self) -> &MPSAccelerationStructure
Sourceยงimpl Borrow<MPSAccelerationStructure> for MPSPolygonAccelerationStructure
Available on crate features MPSPolygonAccelerationStructure and MPSRayIntersector only.
impl Borrow<MPSAccelerationStructure> for MPSPolygonAccelerationStructure
MPSPolygonAccelerationStructure and MPSRayIntersector only.Sourceยงfn borrow(&self) -> &MPSAccelerationStructure
fn borrow(&self) -> &MPSAccelerationStructure
Sourceยงimpl Borrow<MPSAccelerationStructure> for MPSQuadrilateralAccelerationStructure
Available on crate features MPSQuadrilateralAccelerationStructure and MPSRayIntersector and MPSPolygonAccelerationStructure only.
impl Borrow<MPSAccelerationStructure> for MPSQuadrilateralAccelerationStructure
MPSQuadrilateralAccelerationStructure and MPSRayIntersector and MPSPolygonAccelerationStructure only.Sourceยงfn borrow(&self) -> &MPSAccelerationStructure
fn borrow(&self) -> &MPSAccelerationStructure
Sourceยงimpl Borrow<MPSAccelerationStructure> for MPSTriangleAccelerationStructure
Available on crate features MPSTriangleAccelerationStructure and MPSRayIntersector and MPSPolygonAccelerationStructure only.
impl Borrow<MPSAccelerationStructure> for MPSTriangleAccelerationStructure
MPSTriangleAccelerationStructure and MPSRayIntersector and MPSPolygonAccelerationStructure only.Sourceยงfn borrow(&self) -> &MPSAccelerationStructure
fn borrow(&self) -> &MPSAccelerationStructure
Sourceยงimpl Borrow<MPSKernel> for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl Borrow<MPSKernel> for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl Borrow<NSObject> for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl Borrow<NSObject> for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl ClassType for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl ClassType for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงconst NAME: &'static str = "MPSAccelerationStructure"
const NAME: &'static str = "MPSAccelerationStructure"
Sourceยงtype ThreadKind = <<MPSAccelerationStructure as ClassType>::Super as ClassType>::ThreadKind
type ThreadKind = <<MPSAccelerationStructure as ClassType>::Super as ClassType>::ThreadKind
Sourceยงimpl CopyingHelper for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl CopyingHelper for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงtype Result = MPSAccelerationStructure
type Result = MPSAccelerationStructure
Self if the type has no
immutable counterpart. Read moreSourceยงimpl Debug for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl Debug for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl Deref for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl Deref for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl Hash for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl Hash for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl Message for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl Message for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl NSCoding for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl NSCoding for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl NSCopying for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl NSCopying for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl NSObjectProtocol for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl NSObjectProtocol for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงfn isEqual(&self, other: Option<&AnyObject>) -> bool
fn isEqual(&self, other: Option<&AnyObject>) -> bool
Sourceยงfn hash(&self) -> usize
fn hash(&self) -> usize
Sourceยงfn isKindOfClass(&self, cls: &AnyClass) -> bool
fn isKindOfClass(&self, cls: &AnyClass) -> bool
Sourceยงfn is_kind_of<T>(&self) -> bool
fn is_kind_of<T>(&self) -> bool
isKindOfClass directly, or cast your objects with AnyObject::downcast_refSourceยงfn isMemberOfClass(&self, cls: &AnyClass) -> bool
fn isMemberOfClass(&self, cls: &AnyClass) -> bool
Sourceยงfn respondsToSelector(&self, aSelector: Sel) -> bool
fn respondsToSelector(&self, aSelector: Sel) -> bool
Sourceยงfn conformsToProtocol(&self, aProtocol: &AnyProtocol) -> bool
fn conformsToProtocol(&self, aProtocol: &AnyProtocol) -> bool
Sourceยงfn description(&self) -> Retained<NSObject>
fn description(&self) -> Retained<NSObject>
Sourceยงfn debugDescription(&self) -> Retained<NSObject>
fn debugDescription(&self) -> Retained<NSObject>
Sourceยงimpl NSSecureCoding for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl NSSecureCoding for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl PartialEq for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl PartialEq for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงimpl RefEncode for MPSAccelerationStructure
Available on crate feature MPSRayIntersector only.
impl RefEncode for MPSAccelerationStructure
MPSRayIntersector only.Sourceยงconst ENCODING_REF: Encoding = <MPSKernel as ::objc2::RefEncode>::ENCODING_REF
const ENCODING_REF: Encoding = <MPSKernel as ::objc2::RefEncode>::ENCODING_REF
impl DowncastTarget for MPSAccelerationStructure
MPSRayIntersector only.impl Eq for MPSAccelerationStructure
MPSRayIntersector only.