Effecting People Occlusion in Custom Renderers
At a glance
| Item | Summary |
|---|---|
| Purpose | Hide virtual content behind people in the camera feed in a custom Metal renderer, using ARMatteGenerator to produce a person matte and dilated depth each frame. |
| App architecture | A storyboard UIKit app. ViewController creates the ARSession and a Renderer, then forwards MTKView callbacks to it. Renderer draws the camera image and anchor cubes offscreen, then composites them with the matte in a final pass. |
| Main patterns | Delegate callbacks (MTKViewDelegate, ARSessionDelegate) and a small render-destination protocol that MTKView adopts retroactively. |
| Project style | One target with three Swift files, one Metal shader file, and a shared C header bridged into Swift. |
| Execution model | Rendering runs in MTKView’s draw(in:) callback. A DispatchSemaphore limits CPU-encoded frames to three in flight, and command-buffer completion handlers signal it. |
| State/event model | The renderer pulls session.currentFrame each frame. No observation or publisher mechanism is used. |
| Key frameworks/packages | ARKit, Metal, MetalKit, UIKit, simd (in ShaderTypes.h). The project declares no Swift package. |
Project structure
ARMatteExampleSwift.xcodeproj/
ARMatteExampleSwift/
├── AppDelegate.swift @UIApplicationMain; scene configuration
├── SceneDelegate.swift window scene lifecycle (empty hooks)
├── ViewController.swift ARSession + Renderer composition; MTKView and ARSession delegate
├── Renderer.swift RenderDestinationProvider; Renderer (Metal state, per-frame update)
├── Shaders.metal captured-image, anchor, and composite shaders
├── ShaderTypes.h uniforms and buffer/texture indices shared with Swift
├── ARMatteExampleSwift-Bridging-Header.h
├── Base.lproj/Main.storyboard
└── Info.plist scene manifest, orientations
Structure observations
- All rendering logic is in one class,
Renderer(ARMatteExampleSwift/Renderer.swift:39).ViewControlleronly composes and forwards. ShaderTypes.his shared by Swift (through the bridging header) and Metal, so buffer and texture indices such askBufferIndexSharedUniformshave one definition.- The app uses the scene-based lifecycle.
Info.plistdeclares aUIApplicationSceneManifestwithSceneDelegate(ARMatteExampleSwift/Info.plist:25), andAppDelegatereturns the default scene configuration (ARMatteExampleSwift/AppDelegate.swift:22).
Overall architecture
flowchart LR
VC["ViewController"] --> Session["ARSession (.personSegmentationWithDepth)"]
VC --> Renderer["Renderer"]
View["MTKView"] -- "draw(in:)" --> VC
Renderer --> Matte["ARMatteGenerator"]
Renderer --> Offscreen["Offscreen pass: camera + anchors"]
Matte --> Composite["Composite pass"]
Offscreen --> Composite
Composite --> Drawable["MTKView drawable"]
Reference code
ARMatteExampleSwift/Renderer.swift:154 — per-frame order inside update()
class Renderer {
// ...
func update() {
// ...
if let commandBuffer = commandQueue.makeCommandBuffer() {
// ...
updateBufferStates()
updateGameState()
updateMatteTextures(commandBuffer: commandBuffer)
if let renderPassDescriptor = renderDestination.currentRenderPassDescriptor, let currentDrawable = renderDestination.currentDrawable {
// ...
if let sceneRenderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: sceneRenderDescriptor) {
// ...
drawCapturedImage(renderEncoder: sceneRenderEncoder)
// ...
drawAnchorGeometry(renderEncoder: sceneRenderEncoder)
// ...
}
// ...
if let compositeRenderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) {
// ...
compositeImagesWithEncoder(renderEncoder: compositeRenderEncoder)
// ...
}
// ...
commandBuffer.present(currentDrawable)
}
// ...
commandBuffer.commit()
}
}
// ...
}Interpretation
Observed: each frame encodes three kinds of GPU work into one command buffer. ARMatteGenerator writes the matte and dilated-depth textures, an offscreen pass draws the camera image and anchor geometry into sceneColorTexture/sceneDepthTexture, and a composite pass draws to the view’s drawable. The composite fragment shader mixes the scene color with the camera color by the matte alpha. When depth is enabled, it shows the person only where the dilated person depth is closer than the scene depth (ARMatteExampleSwift/Shaders.metal:233, ARMatteExampleSwift/Shaders.metal:237).
Inference: rendering the virtual scene offscreen first is what makes per-pixel occlusion possible, because the composite pass needs the scene’s color and depth as textures.
Ownership and state
classDiagram
ViewController *-- ARSession : session
ViewController *-- Renderer : renderer
Renderer o-- ARSession : let session
Renderer *-- ARMatteGenerator : let
Renderer o-- RenderDestinationProvider : renderDestination (MTKView)
Renderer *-- MTLCommandQueue : commandQueue
Renderer *-- SceneTextures : sceneColorTexture, sceneDepthTexture
ViewController --> MTKView : delegate
Ownership evidence
ARMatteExampleSwift/ViewController.swift:25 — the controller composes session, view, and renderer
session = ARSession()
session.delegate = self
// Set the view to use the default device
if let view = self.view as? MTKView {
view.device = MTLCreateSystemDefaultDevice()
view.backgroundColor = UIColor.clear
view.delegate = self
guard view.device != nil else {
print("Metal is not supported on this device")
return
}
// Configure the renderer to draw to the view
renderer = Renderer(session: session, metalDevice: view.device!, renderDestination: view)
if #available(iOS 27.0, *) {
session.viewLayer = view.layer
}
renderer.drawRectResized(size: view.drawableSize)
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
ViewController |
ARSession |
Creates it in viewDidLoad, stores it in var session: ARSession!, runs and pauses it (ARMatteExampleSwift/ViewController.swift:18, ARMatteExampleSwift/ViewController.swift:71, ARMatteExampleSwift/ViewController.swift:78) |
ViewController |
ViewController |
Renderer |
Creates and stores it (ARMatteExampleSwift/ViewController.swift:19, ARMatteExampleSwift/ViewController.swift:40) |
ViewController calls drawRectResized and update |
Renderer |
ARSession |
Receives and stores it as let session; reads currentFrame, configuration, and viewRotationAngle (ARMatteExampleSwift/Renderer.swift:40) |
Read-only use |
Renderer |
ARMatteGenerator |
Creates it with .half matte resolution (ARMatteExampleSwift/Renderer.swift:106) |
Renderer |
Renderer |
RenderDestinationProvider (the MTKView) |
Receives it in init; sets its pixel formats in loadMetal() (ARMatteExampleSwift/Renderer.swift:105, ARMatteExampleSwift/Renderer.swift:216) |
Renderer configures formats |
Renderer |
Offscreen sceneColorTexture, sceneDepthTexture |
Recreated at the drawable size in drawRectResized(size:) (ARMatteExampleSwift/Renderer.swift:111) |
Renderer |
Renderer |
Matte textures | alphaTexture and dilatedDepthTexture are replaced every frame (ARMatteExampleSwift/Renderer.swift:523, ARMatteExampleSwift/Renderer.swift:525) |
Renderer |
ViewController |
Anchors | A tap adds an ARAnchor one meter in front of the camera (ARMatteExampleSwift/ViewController.swift:93) |
ARSession stores them; Renderer reads them each frame |
Observed: ViewController is the composition root. The renderer depends on the session it is given and never creates or runs one.
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Frame callback | MTKViewDelegate.draw(in:) calls renderer.update() |
All CPU-side encoding runs in the view’s draw callback | ARMatteExampleSwift/ViewController.swift:105 |
| Resize callback | mtkView(_:drawableSizeWillChange:) calls drawRectResized(size:) |
Offscreen targets are rebuilt when the drawable size changes, including on rotation | ARMatteExampleSwift/ViewController.swift:100, ARMatteExampleSwift/Renderer.swift:114 |
| Frames in flight | DispatchSemaphore(value: kMaxBuffersInFlight) with wait before encoding |
At most three frames are encoded ahead of the GPU | ARMatteExampleSwift/Renderer.swift:43, ARMatteExampleSwift/Renderer.swift:132 |
| GPU completion | commandBuffer.addCompletedHandler { [weak self] ... signal() } |
Releases a semaphore slot and the retained CVMetalTextures when the GPU finishes |
ARMatteExampleSwift/Renderer.swift:147 |
| Ring buffers | uniformBufferIndex modulo kMaxBuffersInFlight selects the uniform slot |
CPU writes one slot while the GPU reads another | ARMatteExampleSwift/Renderer.swift:419, ARMatteExampleSwift/Renderer.swift:226 |
| Session callbacks | ARSessionDelegate methods |
Failure and interruption hooks are present but empty | ARMatteExampleSwift/ViewController.swift:111 |
Reference code
ARMatteExampleSwift/Renderer.swift:129 — semaphore wait and completion signal
func update() {
// Wait to ensure only kMaxBuffersInFlight are getting proccessed by any stage in the Metal
// pipeline (App, Metal, Drivers, GPU, etc)
_ = inFlightSemaphore.wait(timeout: DispatchTime.distantFuture)
// Create a new command buffer for each renderpass to the current drawable
if let commandBuffer = commandQueue.makeCommandBuffer() {
// ...
var textures = [capturedImageTextureY, capturedImageTextureCbCr]
commandBuffer.addCompletedHandler { [weak self] commandBuffer in
if let strongSelf = self {
strongSelf.inFlightSemaphore.signal()
}
textures.removeAll()
}
// ...
}
}Observed: the semaphore provides backpressure between CPU encoding and GPU execution. It does not protect general renderer state. The source does not name the thread that calls draw(in:), and no queue, actor, or lock guards the renderer’s properties. Inference: correctness relies on MTKView calling draw(in:) and the resize callback from the same context.
State propagation, frameworks, and dependencies
Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.
| Category | Mechanism or module | Verified role | Evidence |
|---|---|---|---|
| Frame data | Pull: session.currentFrame each frame |
Camera image, anchors, light estimate, and camera matrices | ARMatteExampleSwift/Renderer.swift:431 |
| Occlusion mode | configuration.frameSemantics = .personSegmentationWithDepth |
Enables person segmentation with depth for the matte generator | ARMatteExampleSwift/ViewController.swift:68 |
| Depth toggle | uniforms.useDepth set from the session configuration |
The composite shader uses dilated depth only when the configuration includes depth | ARMatteExampleSwift/Renderer.swift:480, ARMatteExampleSwift/Shaders.metal:227 |
| Rotation | session.viewLayer and session.viewRotationAngle (iOS 27) |
View and projection matrices and the display transform follow the view’s rotation; earlier systems use .landscapeRight |
ARMatteExampleSwift/ViewController.swift:43, ARMatteExampleSwift/Renderer.swift:448, ARMatteExampleSwift/Renderer.swift:546 |
| CPU/GPU shared types | ShaderTypes.h through the bridging header |
Uniform structs and index enums | ARMatteExampleSwift/ARMatteExampleSwift-Bridging-Header.h:8 |
| Framework import | ARKit, Metal, MetalKit |
Session, matte generator, and rendering | ARMatteExampleSwift/Renderer.swift:9, ARMatteExampleSwift/Renderer.swift:10, ARMatteExampleSwift/Renderer.swift:11 |
| Framework import | UIKit |
App, scene, and view controller | ARMatteExampleSwift/ViewController.swift:8 |
Combine and Observation are not used.
Platform boundary
The project’s deployment target is iOS 15.0 (ARMatteExampleSwift.xcodeproj/project.pbxproj:258). The rotation-aware path is gated with #available(iOS 27.0, *). On earlier systems, the view controller allows only landscape-right orientation (ARMatteExampleSwift/ViewController.swift:53).
Class and protocol design
classDiagram
class RenderDestinationProvider {
<<protocol>>
currentRenderPassDescriptor
currentDrawable
colorPixelFormat
depthStencilPixelFormat
sampleCount
}
MTKView ..|> RenderDestinationProvider : extension
Renderer --> RenderDestinationProvider
ViewController ..|> MTKViewDelegate
ViewController ..|> ARSessionDelegate
ViewController --> Renderer
Reference code
ARMatteExampleSwift/Renderer.swift:13 — the renderer’s view-facing contract
protocol RenderDestinationProvider {
var currentRenderPassDescriptor: MTLRenderPassDescriptor? { get }
var currentDrawable: CAMetalDrawable? { get }
var colorPixelFormat: MTLPixelFormat { get set }
var depthStencilPixelFormat: MTLPixelFormat { get set }
var sampleCount: Int { get set }
}| Type | Responsibility | Depends on |
|---|---|---|
RenderDestinationProvider |
The subset of MTKView the renderer needs |
Metal types |
Renderer |
Metal setup, per-frame uniforms and textures, offscreen and composite passes | ARSession, ARMatteGenerator, RenderDestinationProvider |
ViewController |
Creates the session and renderer, runs the session, adds anchors on tap, forwards view callbacks | Renderer, ARSession, MTKView |
AppDelegate / SceneDelegate |
App and scene lifecycle; no app logic | UIKit |
Observed: MTKView adopts the protocol through an empty extension (ARMatteExampleSwift/ViewController.swift:13), because it already has those properties. Renderer stores the destination as the protocol type (ARMatteExampleSwift/Renderer.swift:44), so it does not import the view’s concrete type into its API.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
Renderer and all its members (ARMatteExampleSwift/Renderer.swift:39) |
implicit internal |
Any type in the app module can read or replace Metal state; the // MARK: - Private section is a comment, not an access modifier (ARMatteExampleSwift/Renderer.swift:211) |
Inference: a compact sample that does not enforce boundaries in a single-target app. |
ViewController.session, renderer (ARMatteExampleSwift/ViewController.swift:18) |
implicit internal, implicitly unwrapped |
Set in viewDidLoad, used afterward |
Inference: storyboard instantiation prevents initializer injection. |
RenderDestinationProvider (ARMatteExampleSwift/Renderer.swift:13) |
implicit internal |
Module-wide contract | Inference: no exported surface is needed. |
Reference code
ARMatteExampleSwift/Renderer.swift:39 — stored properties without explicit modifiers
class Renderer {
let session: ARSession
let matteGenerator: ARMatteGenerator
let device: MTLDevice
let inFlightSemaphore = DispatchSemaphore(value: kMaxBuffersInFlight)
var renderDestination: RenderDestinationProvider
// ...
}The sample uses no explicit private, fileprivate, or private(set) modifiers. Every Swift declaration shown is implicitly internal.
Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Session configuration and lifecycle | ViewController.viewWillAppear / viewWillDisappear |
Tied to view visibility (ARMatteExampleSwift/ViewController.swift:60). |
| Matte generation | Renderer.updateMatteTextures(commandBuffer:) |
Encoded into the frame’s command buffer (ARMatteExampleSwift/Renderer.swift:518). |
| Camera-image texture creation | Renderer.updateCapturedImageTextures(frame:) |
Y and CbCr planes through a CVMetalTextureCache (ARMatteExampleSwift/Renderer.swift:506). |
| Display transform and rotation | Renderer.updateImagePlane(frame:), updateSharedUniforms(frame:) |
Recomputed every frame (ARMatteExampleSwift/Renderer.swift:440). |
| Per-pixel occlusion | compositeImageFragmentShader |
Mixes camera, scene, and matte on the GPU (ARMatteExampleSwift/Shaders.metal:201). |
| Anchor placement | ViewController.handleTap(gestureRecognize:) |
Input handling stays in the controller (ARMatteExampleSwift/ViewController.swift:82). |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Delegate or data-source callbacks | ViewController: UIViewController, MTKViewDelegate, ARSessionDelegate (ARMatteExampleSwift/ViewController.swift:16); view.delegate = self (ARMatteExampleSwift/ViewController.swift:32) |
The view drives frame timing and resizes through callbacks, and the controller forwards them to the renderer |
| Protocol-oriented abstraction | RenderDestinationProvider (ARMatteExampleSwift/Renderer.swift:13) adopted by MTKView in an extension (ARMatteExampleSwift/ViewController.swift:13) |
The renderer depends on a narrow drawable contract rather than on MTKView |
Removed: “View-controller organization”, which came from the type-name suffix. The controller’s verified role is composition and callback forwarding, which the ownership section already describes.
Naming conventions
- Types: role nouns (
Renderer,ViewController). The protocol uses a…Providersuffix for something that supplies render targets. - Methods: per-frame steps are
update…(updateBufferStates,updateGameState,updateSharedUniforms,updateAnchors,updateCapturedImageTextures,updateMatteTextures,updateImagePlane). Encoding steps aredraw…andcomposite…. Setup isload…(loadMetal,loadAssets). - Constants: global
k-prefixed constants (kMaxBuffersInFlight,kAlignedSharedUniformsSize), matching the shared C header’s naming (kBufferIndexSharedUniforms). - Files: one primary type per Swift file. The protocol lives with the renderer, and the
MTKViewconformance lives with the controller that uses the view.
Architecture takeaways
- To occlude virtual content with people, render the virtual scene to offscreen color and depth textures, then combine them with the matte and dilated depth in a separate composite pass.
- Keep the renderer independent of the view type through a small destination protocol, and let the framework view adopt it retroactively.
- A semaphore plus command-buffer completion handlers is a simple way to bound frames in flight and to keep
CVMetalTexturesources alive until the GPU is done. - Size offscreen targets in the drawable-size callback, not in the per-frame path, so rotation rebuilds them only when the size changes.
- Gate new rotation APIs with
#availableand keep a fixed-orientation fallback, assupportedInterfaceOrientationsdoes here.
Source map
| Source file | Relevant symbols |
|---|---|
ARMatteExampleSwift/ViewController.swift |
ViewController, viewDidLoad, supportedInterfaceOrientations, handleTap(gestureRecognize:), MTKView: RenderDestinationProvider |
ARMatteExampleSwift/Renderer.swift |
RenderDestinationProvider, Renderer, drawRectResized(size:), update(), updateMatteTextures(commandBuffer:), updateImagePlane(frame:), compositeImagesWithEncoder(renderEncoder:) |
ARMatteExampleSwift/Shaders.metal |
compositeImageFragmentShader |
ARMatteExampleSwift/ShaderTypes.h |
Shared uniform structs and index enums |
ARMatteExampleSwift/AppDelegate.swift |
AppDelegate |
ARMatteExampleSwift/SceneDelegate.swift |
SceneDelegate |
ARMatteExampleSwift/Info.plist |
Scene manifest, supported orientations |
ARMatteExampleSwift/ARMatteExampleSwift-Bridging-Header.h |
#import "ShaderTypes.h" |
ARMatteExampleSwift.xcodeproj/project.pbxproj |
IPHONEOS_DEPLOYMENT_TARGET |