Search code examples
swiftscenekitmetalrealitykit

Metal Ray Tracing – SceneKit or RealityKit


The WWDC21 talk below shows how to "Enhance your app with Metal ray tracing".

How can I add Metal ray tracing to a SceneKit or RealityKit app?

Any basic example or reference code would be hugely appreciated!


Solution

  • It took me some time to prepare example apps for you and anyone else interested in this topic. The apps are pure Swift with Metal and are currently designed to run on iOS platforms. (I personally recommend a fast device)

    Here you can find the first "simple" default Apple RayTracer:

    https://github.com/philvanza/SceneKit-RayTracing

    And here the same app with an additional, more complex RayTracer that supports BSDF (Bidirectional Scattering Distribution Function) which allows you to RayTrace i.Ex. transparent glass:

    https://github.com/philvanza/SceneKit-RayTracing-Advanced

    Basically you need the following to achive RayTracing:

    • Extract the geometry data from the SceneKit node you want to RayTrace
    • Build a triangle acceleration structure (Metal specific)
    • Prepare the buffers to execute on the GPU
    • Send the whole stuff to the RayTracer
    • Accumulate the output image over time

    The longer you let the RayTracer run, the better the result becomes.

    It would take too much code to add here, so I prepared this repositories. Feel free to leave me a comment on whatever you think about the RayTracers.

    Have fun!

    Exaple Image from the Simple RayTracer

    Exaple Image from the Advanced RayTracer