Sample CodeiOS, iPadOS, Mac Catalyst, macOSReviewed 2026-07-21View on Apple Developer

Rendering reflections in real time using ray tracing

At a glance

Item Summary
Purpose Implement realistic real-time lighting by dynamically generating reflection maps by encoding a ray-tracing compute pass.
App architecture Objective-C host code with Metal shaders; AAPLViewController hands work to AAPLRenderer, which owns hybrid raster/ray-tracing renderer before ray-traced reflections plus raster composition.
Main patterns Hybrid rendering pipeline, Scene data model, Host-shader data contract
Scope High-level review of 20 scanned source files and 33 detected declarations; build assets are omitted.

Project structure

Source bundle/
├── Renderer/
│   ├── AAPLRenderer.m
│   ├── AAPLShaders.metal
│   ├── AAPLShaderTypes.h
│   └── AAPLArgumentBufferTypes.h
└── Application/
    ├── iOS/
    │   └── AAPLViewController.m
    ├── main.m
    ├── WindowSceneDelegate.m
    ├── AAPLAppDelegate.h
    └── AAPLAppDelegate.m

Structure observations

  • The entry/composition boundary and renderer or operation boundary are separate in the source; AAPLRenderer is the principal feature coordinator.
  • GPU-specific logic stays in Metal shader files; shared headers bridge host/shader layouts where present.
  • The tree above is intentionally pruned to composition, resource, and shader files.

Overall architecture

Reference code

Renderer/AAPLRenderer.m:1251 — ray-traced reflection pass setup

            [commandBuffer pushDebugGroup:@"Raytrace Compute"];
            [commandBuffer encodeWaitForEvent:_accelerationStructureBuildEvent value:kInstanceAccelerationStructureBuild];
            id<MTLComputeCommandEncoder> compEnc = [commandBuffer computeCommandEncoder];
            compEnc.label = @"RaytracedReflectionsComputeEncoder";
            [compEnc setTexture:_rtReflectionMap atIndex:OutImageIndex];
            [compEnc setTexture:_thinGBuffer.positionTexture atIndex:ThinGBufferPositionIndex];
            [compEnc setTexture:_thinGBuffer.directionTexture atIndex:ThinGBufferDirectionIndex];
            [compEnc setTexture:_skyMap atIndex:AAPLSkyDomeTexture];

Interpretation

This is the dominant control/data path: platform code composes AAPLRenderer; that object controls hybrid raster/ray-tracing renderer; GPU-visible work ends in ray-traced reflections plus raster composition. The arrows summarize responsibility transfer, not a claim that every node directly calls the next.

Ownership and state

Ownership evidence

Application/iOS/AAPLViewController.m:40AAPLViewController creates and stores _renderer

@implementation AAPLViewController
// ...
            strongSelf->_renderer = [[AAPLRenderer alloc] initWithMetalKitView:strongSelf->_view size:size];
// ...
@end
Owner Object or state Relationship Mutation authority
AAPLViewController _renderer / AAPLRenderer Creates and stores; the diagram uses composition because construction is source-visible. The declaring scope performs setup and replacement.
AAPLRenderer Feature-specific framework and Metal resources Operation-local calls or stored state; exclusive lifetime is not assumed beyond cited evidence. Feature setup/encoding code controls mutation and command submission.

Class and protocol design

Type Responsibility Depends on or conforms to Source
AAPLViewController selects/configures the view and composes the feature objects. UIViewController, NSViewController Application/iOS/AAPLViewController.h:12
AAPLRenderer owns pipeline/resource setup and per-frame command encoding. NSObject, MTKViewDelegate Renderer/AAPLRenderer.h:19
Scene holds scene geometry, instances, camera, or lighting data. concrete Metal/framework collaborators Renderer/AAPLArgumentBufferTypes.h:79
AAPLAppDelegate handles application/window lifecycle callbacks. UIResponder, UIApplicationDelegate, NSObject Application/AAPLAppDelegate.h:11
WindowSceneDelegate handles application/window lifecycle callbacks. UIResponder, UIWindowSceneDelegate Application/WindowSceneDelegate.h:15
MeshGenerics defines texture-coordinate and tangent-space vertex attributes stored in the mesh argument buffer. Metal argument-buffer member IDs Renderer/AAPLArgumentBufferTypes.h:38

Framework delegate conformance is a callback seam; the source does not justify calling the whole app protocol-oriented.

Access control

Symbol Access Verified effect Design reason
AAPLAppDelegate header-visible available to translation units that import the header; this is not Swift public. Keep the usable surface no wider than the collaboration requires. (Application/AAPLAppDelegate.h:11)
AAPLRenderer implementation details implementation-only native helpers, stored state, or registration code stays out of the imported header contract. Hide native implementation details from importing translation units. (Renderer/AAPLRenderer.m:1)
AAPLShaders entry points Metal library boundary host code resolves named shader entry points; Swift access modifiers do not apply. Expose only named shader entry points needed by pipeline creation. (Renderer/AAPLShaders.metal:337)

This sample does not use Swift private, fileprivate, or public for its native boundary. Objective-C/Objective-C++ use header versus implementation placement, C++ uses access specifiers/linkage, Python uses module conventions, and Metal entry points cross a compiled-library boundary; these are not Swift access levels.

Logic ownership and placement

Logic Owning type or file Why it lives there
Selects/configures the view and composes the feature objects AAPLViewControllerApplication/iOS/AAPLViewController.h:12 The type’s callbacks and stored state align with this responsibility.
Owns pipeline/resource setup and per-frame command encoding AAPLRendererRenderer/AAPLRenderer.h:19 The type’s callbacks and stored state align with this responsibility.
Holds scene geometry, instances, camera, or lighting data SceneRenderer/AAPLArgumentBufferTypes.h:79 The type’s callbacks and stored state align with this responsibility.
Handles application/window lifecycle callbacks AAPLAppDelegateApplication/AAPLAppDelegate.h:11 The type’s callbacks and stored state align with this responsibility.
Hybrid raster/ray-tracing renderer AAPLRenderer / Renderer/AAPLRenderer.m:1251 Keeps Metal/framework setup and encoding out of entry or lifecycle code.
Ray-traced reflections plus raster composition Renderer/AAPLShaders.metal:337 GPU-parallel code remains in the Metal compilation boundary.

Shader boundary reference

Renderer/AAPLShaders.metal:337 — ray-traced reflection kernel and binding contract

kernel void rtReflection(
             texture2d< float, access::write >      outImage                [[texture(OutImageIndex)]],
             texture2d< float >                     positions               [[texture(ThinGBufferPositionIndex)]],
             texture2d< float >                     directions              [[texture(ThinGBufferDirectionIndex)]],
             texture2d< float >                     skydomeMap              [[texture(AAPLSkyDomeTexture)]],
             constant AAPLInstanceTransform*        instanceTransforms      [[buffer(BufferIndexInstanceTransforms)]],
             constant AAPLCameraData&               cameraData              [[buffer(BufferIndexCameraData)]],
             constant AAPLLightData&                lightData               [[buffer(BufferIndexLightData)]],
             constant Scene*                        pScene                  [[buffer(SceneIndex)]],
             instance_acceleration_structure        accelerationStructure   [[buffer(AccelerationStructureIndex)]],
             uint2 tid [[thread_position_in_grid]])

Design patterns

Pattern Source evidence Purpose or tradeoff
Hybrid rendering pipeline Renderer/AAPLRenderer.m:1251 Makes the sample’s hybrid raster/ray-tracing renderer an explicit, reviewable boundary.
Scene data model Application/iOS/AAPLViewController.m:40 Makes the sample’s hybrid raster/ray-tracing renderer an explicit, reviewable boundary.
Host-shader data contract Renderer/AAPLRenderer.m:19 Shared indices/structs and matching bindings couple host encoding to shader signatures deliberately.

Naming conventions

  • Role suffixes make ownership visible: AAPLViewController, AAPLRenderer, Scene, AAPLAppDelegate, WindowSceneDelegate.
  • Method names describe setup or encoding actions: initWithMetalKitView, resizeRTReflectionMapTo, loadMetalWithView, loadAssets, argumentDescriptorWithIndex, buildSceneArgumentBufferFromReflectionFunction, newResidencySetWithLabel.
  • Shader entry points use stage/operation names: skyboxVertex, skyboxFragment, vertexShader, fragmentShader, reflectionShader, gBufferFragmentShader.
  • AAPL is a sample namespace prefix, not a recommendation for production module naming; retain semantic suffixes such as Renderer, Manager, Scene, or Adapter.

Architecture takeaways

  • Keep AAPLViewController focused on composition; AAPLRenderer is the owner of hybrid raster/ray-tracing renderer.
  • Treat ray-traced reflections plus raster composition as a separate execution/compilation boundary with explicit resource and data-layout contracts.
  • The verified ownership edge is AAPLViewController_renderer; broader exclusive ownership is not inferred.
  • Access-control rationale follows concrete language boundaries rather than translating every header or shader symbol into Swift terms.

Source map

Source file Architectural role
Renderer/AAPLRenderer.m AAPLRenderer, Instance, Mesh, Submesh
Application/iOS/AAPLViewController.m AAPLViewController
Renderer/AAPLShaders.metal LightingParameters, SkyboxVertex, SkyboxV2F, ThinGBufferOut, VertexInOut
Application/main.m entry point or feature implementation
Application/WindowSceneDelegate.m WindowSceneDelegate
Renderer/AAPLShaderTypes.h entry point or feature implementation
Application/AAPLAppDelegate.h AAPLAppDelegate, AAPLAppDelegate
Renderer/AAPLArgumentBufferTypes.h MeshGenerics, Submesh, Mesh, Instance, Scene
Application/AAPLAppDelegate.m AAPLAppDelegate, AAPLAppDelegate