Sample CodevisionOSReviewed 2026-11-01View on Apple Developer

Chaparral Village: Building an immersive visionOS adventure game

At a glance

Item Summary
Purpose Create an adventure game using SwiftUI, RealityKit, and Reality Composer Pro 3.
App architecture A thin visionOS app target (ChaparralVillageApp, ContentView) on top of one local Swift package, RCPCustomComponents. The package holds the game logic as RealityKit components, systems, and scene-scoped SceneBound manager objects.
Main patterns Entity-component-system composition, Scene-scoped registry, SwiftUI environment injection, Protocol-oriented abstraction, Observer
Project style One app target with 2 Swift files. One local package with 96 Swift files, grouped by gameplay feature (Managers, SaveRestoration, Menus, Cutscene, ZoneManagement, Alchemy, and others).
Execution model Both the app target and the package default to nonisolated code. Isolation comes from explicit @MainActor declarations, including the SceneBound protocol. Unstructured Tasks handle level loading, ARKit startup, and menu actions. No queue or lock appears in the cited flows.
State/event model An @Observable AppState is injected into both scenes through the SwiftUI environment and is also stored as an ECS component. Other mechanisms: RealityKit component events stored as AnyCancellable, scene events, and SwiftData persistence of saves.
Key frameworks/packages RealityKit, RealityComposerPro, RealityKitScripting, SwiftData, ARKit, Spatial, Combine. Two remote packages, reality-composer-pro-plugin and realitykitscripting, are declared only by the local package’s manifest.

Project structure

ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/
├── ChaparralVillage/                  visionOS app target sources
│   ├── ChaparralVillageApp.swift
│   └── ContentView.swift
├── ChaparralVillage.xcodeproj/        one app target, links RCPCustomComponents
├── ChaparralVillage.realitycomposerpro/
├── Scripts/InstallPlugin.sh           copies a macOS plug-in build into Plugins/
├── Data/Plugins/RCPCustomComponents.framework   prebuilt macOS binary only
└── Packages/
    ├── RCPCustomComponents/           local package: game logic + RCP plug-in
    │   ├── Package.swift
    │   └── Sources/RCPCustomComponents/
    │       ├── RCPCustomComponentsPlugin.swift
    │       ├── EcsAbstractions/       SceneBound, queries, DebugDraw
    │       ├── Managers/              AppState, LevelManager, ARManager, InputManager
    │       ├── SaveRestoration/       SaveManager, SavePersistence, GameRestoreRecord
    │       ├── Menus/                 GameButtonSystem, Start/LoadGameButton
    │       ├── Cutscene/              CutsceneManager, Dialog
    │       ├── ZoneManagement/        ZoneTracker
    │       ├── ObjectManipulation/    DraggableObject, Affordances/
    │       ├── Alchemy/               Cauldron, Potion, Breakable
    │       └── DynamicPhysics/        GourdRopeChain, SleepyPhysicsBody
    ├── CocoLatteFoundation/           tool residue only: no manifest, no sources
    ├── RealityComposerPro/            .swiftpm residue only
    └── realitykit-scripting/          .swiftpm residue only

Structure observations

  • The app target contains only the entry point and one view. Every gameplay type, including AppState, lives in RCPCustomComponents.
  • Packages/CocoLatteFoundation holds only a .build/.lock file and per-user Xcode scheme state. It has no Package.swift and no Swift sources, and neither the project file nor any manifest references it. The source therefore establishes no architectural role or dependency edge for it. Packages/RealityComposerPro and Packages/realitykit-scripting are the same kind of .swiftpm-only residue.
  • Data/Plugins/RCPCustomComponents.framework is a compiled macOS (MacOSX) framework with no sources. Scripts/InstallPlugin.sh installs built frameworks into <repo>/Plugins (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Scripts/InstallPlugin.sh:26), not Data/. The source therefore does not show how Data/ is consumed.
  • The Package.resolved under the project workspace pins reality-composer-pro-plugin 1.1.0, realitykitscripting 1.4.0, and swift-syntax. swift-syntax is not declared in any manifest in the tree, so it is a resolved transitive dependency.

Overall architecture

Reference code

ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Package.swift:37: RCPCustomComponents target dependencies

let package = Package(
    name: "RCPCustomComponents",
    platforms: [
        .macOS(.v27),
        .visionOS(.v27)
    ],
    products: [
        // ...
        .library(
            name: "RCPCustomComponents",
            type: .dynamic,
            targets: ["RCPCustomComponents"]
        )
    ],
    dependencies: [
        .package(url: "https://github.com/apple/reality-composer-pro-plugin", from: "1.1.0"),
        .package(url: "https://github.com/apple/realitykitscripting", from: "1.4.0")
    ],
    targets: [
        // ...
        .target(
            name: "RCPCustomComponents",
            dependencies: [
                .product(name: "RealityComposerPro", package: "reality-composer-pro-plugin"),
                .product(name: "RealityKitScripting", package: "realitykitscripting")
            ],
            swiftSettings: [.defaultIsolation(nil)]
        )
    ],
    // ...
)

ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ChaparralVillageApp.swift:30: two scenes share one AppState and one SaveManager

    var body: some SwiftUI.Scene {
        WindowGroup(id: AppState.mainMenu) {
            ContentView(immersive: false, saveManager: saveManager)
                .frame(width: physicalMetrics.convert(1.5, from: .meters), height: physicalMetrics.convert(1.0, from: .meters))
                .frame(depth: physicalMetrics.convert(1.0, from: .meters))
                .environment(appState)
        }
        .windowStyle(.volumetric)
        .windowResizability(.contentSize)
        .volumeWorldAlignment(.gravityAligned)

        ImmersiveSpace(id: AppState.immersiveSpace) {
            ContentView(immersive: true, saveManager: saveManager)
                .environment(appState)
        }
        // ...
        .immersiveEnvironmentBehavior(.coexist)
    }

Interpretation

Observed dependency direction: the app target has one package product dependency, RCPCustomComponents, which it links and embeds (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage.xcodeproj/project.pbxproj:158). The project-level packageReferences list is empty (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage.xcodeproj/project.pbxproj:189). The two remote packages are declared only by RCPCustomComponents. The app sources still import RealityComposerPro and import RealityKitScripting (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ChaparralVillageApp.swift:9, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ChaparralVillageApp.swift:11). Inference: those modules reach the app through the local package’s resolved graph rather than through a target dependency of its own. Dependencies point one way, app → RCPCustomComponents → remote packages. No package source imports app code.

The same package is also a Reality Composer Pro plug-in: RCPCustomComponentsPlugin conforms to RealityComposerProPlugin (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/RCPCustomComponentsPlugin.swift:36). The app calls the same setup(context:) at launch, so the editor and the game register one shared set of components and systems.

Platform boundary

The app target supports only xros xrsimulator (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage.xcodeproj/project.pbxproj:262). The package also declares macOS 27 so that it can build as a macOS plug-in for Reality Composer Pro. visionOS-only code is fenced with #if os(visionOS) or @available(macOS, unavailable).

Ownership and state

Ownership evidence

ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift:48: each RealityView builds a Singletons entity that carries the scene’s managers as components

            let singletons = Entity()
            singletons.name = "Singletons"
            let levelManager = LevelManager(level: levelRoot, user: userRoot, pocketDimensionRoot: pocketDimensionRoot)
            singletons.components.set(input)
            singletons.components.set(PlayerManager())
            singletons.components.set(levelManager)
            singletons.components.set(DebugDraw())
            singletons.components.set(saveManager)
            singletons.components.set(AudioManager())
            singletons.components.set(ObjectGroupingManager())
            singletons.components.set(InputProxyManager())
            singletons.components.set(CutsceneManager())
            singletons.components.set(appState)
            if immersive {
                singletons.components.set(ARManager())
                singletons.components.set(FingerStirrer())
                // ...
            }
            content.add(singletons)
Owner Object or state Relationship Mutation authority
ChaparralVillageApp AppState (@State private var appState) Creates it, keeps it in SwiftUI state, and injects it with .environment(appState) into both scenes Any holder. Every stored property is public var on a @MainActor class (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/AppState.swift:34)
ChaparralVillageApp SaveManager (let saveManager) Creates it, configures persistence in init, and passes it to both ContentView values (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ChaparralVillageApp.swift:26) SaveManager methods such as startNewSave(), continueSave(_:), and persist()
ContentView (each scene) LevelManager Created inside the RealityView make closure, then stored in the Singletons entity and in @State var levelManager (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift:141). The volume also publishes it as appState.volumeLevelManager (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift:130) LevelManager (private var slots)
ContentView (each scene) InputManager, arRoot, collisionEntity Plain let properties of the view value. Inference: the RealityView make closure captures the instances from its first run InputManager
Singletons entity 10 components (12 in the immersive scene) Retained as entity components. SceneBound also mirrors each one into a static sceneToValue dictionary until the component is removed Each manager
SaveManager ModelContainer Created by configurePersistence() (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/SaveRestoration/SavePersistence.swift:29) SaveManager through mainContext

No single object owns the volume’s LevelManager exclusively: the view state, the entity, and AppState all hold it. ContentView is one view that keeps its own @State and reads AppState from the environment.

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
Default isolation SWIFT_DEFAULT_ACTOR_ISOLATION = nonisolated (app) and .defaultIsolation(nil) (package) Neither module makes declarations main-actor isolated by default, so isolation must be stated explicitly. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage.xcodeproj/project.pbxproj:265, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Package.swift:40
Main-actor isolation @MainActor protocol SceneBound The protocol is main-actor isolated. Inference from Swift’s conformance rules: the eleven final class managers that conform in their primary declaration inherit that isolation, together with their static sceneToValue dictionaries. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/EcsAbstractions/SceneBound.swift:15
Main-actor isolation @MainActor @Observable AppState Shared phase, volume root, and save count are main-actor state that both scenes read. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/AppState.swift:26
Main-actor hop MainActor.assumeIsolated or Task { @MainActor in } Plug-in setup registers the SceneBound types synchronously when it is already on the main thread. Otherwise it creates a main-actor task. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/RCPCustomComponentsPlugin.swift:178
Task creation and join Task and nested Task { @MainActor in } The immersive ContentView starts an unstructured task to load the level. Inside it, a child unstructured task unloads the volume’s menu level. The loader joins it with await unloadMenuTask.value. Neither task is stored or cancelled. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift:89, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift:109
Structured concurrency withTaskGroup fadeOutExistingLevel fades the level and restorable entities concurrently and waits for them all. Each entity is disabled through a @MainActor closure. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/LevelManager.swift:124
Long-running task Task with for await over handProvider.anchorUpdates ARManager.register starts three unretained tasks: spatial tracking, ARKit authorization and run, and a hand-update loop. Nothing in the source stores or cancels them; a hasTriedToRun flag prevents a second start. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/ARManager.swift:76, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/ARManager.swift:104
Deferred work Task { @MainActor in } CutsceneManager defers its bind callbacks until all other SceneBound values have registered. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Cutscene/CutsceneManager.swift:40
Persistence context @MainActor plus modelContainer.mainContext Saves are encoded and written through the SwiftData main context, and only from main-actor methods. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/SaveRestoration/SavePersistence.swift:40

Shared-state safety: the mutable static registries (sceneToValue, SceneBoundTracker.types, ZoneTracker.subscribers) have no lock or queue. They rely on main-actor isolation. ZoneTracker.subscribers and SceneBoundTracker.types are annotated explicitly; sceneToValue is covered by the inference above. No Task.detached, DispatchQueue, or RunLoop scheduling appears in these flows.

Reference code

ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/RCPCustomComponentsPlugin.swift:178: main-actor registration of the scene-scoped managers

        if Thread.isMainThread {
            MainActor.assumeIsolated {
                registerMainActor()
            }
        } else {
            Task { @MainActor in
                registerMainActor()
            }
        }

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
State propagation SwiftUI environment ChaparralVillageApp injects appState, and ContentView and the menu button views read it with @Environment(AppState.self). ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ChaparralVillageApp.swift:34, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift:16
State propagation @Observable AppState, InputManager, and DialogModel publish property changes to SwiftUI observers. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/AppState.swift:27, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Cutscene/Dialog.swift:59
State propagation Property observer to scene registry SaveManager.saves.didSet writes saveCount into the AppState looked up through its registered scene. The Load Game button enables or disables itself from that count. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/SaveRestoration/SaveManager.swift:24, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Menus/LoadGameButton.swift:31
State propagation RealityKit component events and AnyCancellable GameButtonSystem attaches or removes SwiftUI button views as the button components are added or removed, and keeps the subscriptions in a stored array. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Menus/GameButtonSystem.swift:22
State propagation Scene events A Scene.send(_:) extension forwards LevelLoadedEvent as a named "LevelLoaded" scene event with the level as its argument. The listeners are not in the Swift sources. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/LevelManager.swift:177
Persistence SwiftData @Model GameRestoreRecord stores each save, with state that SwiftData can’t hold encoded as a JSON payload. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/SaveRestoration/GameRestoreRecord.swift:24
Package declaration Remote reality-composer-pro-plugin, realitykitscripting Declared by the local package and consumed by its only target as products ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Package.swift:28, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Package.swift:29
Package declaration App target → local RCPCustomComponents product This is the app target’s only package product dependency. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage.xcodeproj/project.pbxproj:158
Source import RealityComposerPro, RealityKitScripting App-target files import these modules even though the target declares no direct product dependency on them ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift:11
Source import ComputeGraph The plug-in file imports this module and registers ComputeGraphComponent. The source doesn’t show which package or SDK supplies it. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/RCPCustomComponentsPlugin.swift:10
Source import ARKit ARManager compiles against ARKit sessions and providers. ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/ARManager.swift:8

The doc comment on configurePersistence() describes discarding an incompatible store and retrying. The method body only logs the error and continues (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/SaveRestoration/SavePersistence.swift:31), so this analysis follows the code. Also, configurePersistence() runs in App.init, before any scene has registered SaveManager. When it loads the persisted saves, saves.didSet therefore has no scene through which to update AppState.saveCount.

Class and protocol design

Reference code

ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/EcsAbstractions/SceneBound.swift:16: SceneBound

@MainActor
public protocol SceneBound: Identifiable, Component {
    static var sceneToValue: [Scene.ID: Self] { get set }
    
    static func setup(scene: Scene, state: Scene.EditorState)
    func register(scene: Scene, on entity: Entity)
    func update(context: SceneUpdateContext)
}

extension Scene {
    public subscript<T: SceneBound>(_ type: T.Type = T.self) -> T? {
        T.sceneToValue[self.id]
    }
}
Type Responsibility Depends on or conforms to
ChaparralVillageApp Creates AppState and SaveManager, registers the plug-in, and declares the volume and immersive scenes App
ContentView Builds the entity roots and singletons and runs the menu-to-game transition View, RealityView, AppState (environment)
RCPCustomComponentsPlugin Registers every component, system, SceneBound type, and scripting module RealityComposerProPlugin
SceneBound / SceneBoundTracker Scene-scoped manager contract, plus the system that registers the managers and calls their update every frame Component, System
AppState Cross-scene launch phase, volume handoff references, and save count SceneBound, @Observable
LevelManager Loads, restores, fades, and unloads levels per slot SceneBound, SaveManager, CutsceneManager
SaveManager In-memory saves and the active restore. A same-type extension adds SwiftData persistence SceneBound, Inspectable
GameButtonSystem Attaches the SwiftUI Start Game and Load Game views to entities that carry button components System
ZoneTracker / ZoneTrackerSystem Tracks zone overlaps and dispatches enter, change, and exit events to registered handler types Component, System, ZoneChangeHandler
Affordance conformers Snap or constrain dragged entities (snap, circle, point-toward, orientation, radial bounds) Affordance, Component

The source defines these other local protocols: TapHandler, DragHandler, PhysicsUpdateBehavior, and CustomRestore.

Access control

Symbol Access Verified effect Likely rationale
appState (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ChaparralVillageApp.swift:18) private @State Only ChaparralVillageApp can reassign the stored state. Other code receives the object through the environment. Inference: the app keeps the lifetime and exposes the reference read-only.
PluginHandler (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ChaparralVillageApp.swift:53) private struct The registration adapter is visible only in the entry-point file. Inference: it is a launch implementation detail.
AppState properties (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/AppState.swift:34) public var The app module and every package type can mutate phase, volumeArRoot, volumeLevelManager, and saveCount. Inference: the cross-module handoff favors simple shared state over encapsulated mutation.
slots (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/LevelManager.swift:27) private Only LevelManager can change the loaded-level bookkeeping. Inference: it protects the slot invariant used by load, store, and unload.
session and the providers (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/ARManager.swift:18) private ARKit objects stay inside ARManager. The class exposes head, hands, and planes instead. Inference: it keeps the ARKit details behind the manager.
scene (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/SaveRestoration/SaveManager.swift:17) private weak A non-owning back-reference that only SaveManager uses. Inference: it avoids a retain cycle with the scene.
storeURL (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/SaveRestoration/SavePersistence.swift:13) private static in an extension Swift allows the same-file extension to declare it, and no other file can see it. Inference: the store location is a persistence detail.
StartGameButtonView (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Menus/StartGameButton.swift:18) explicit internal The view is hidden from the app module, while StartGameButtonComponent is public so that it can be authored. Inference: content authors attach the component, and the package supplies the view.

Reference code

ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/RCPCustomComponentsPlugin.swift:191: public factory beside a public initializer

public final class RCPCustomComponentsPlugin: RealityComposerProPlugin {
    // ...
    public init() {}
    // ...
    /// Returns a new instance of the plug-in. Making `init()` public would
    /// change the API contract that Reality Composer Pro defines, so use this factory instead.
    public static func create() -> RCPCustomComponentsPlugin {
        return RCPCustomComponentsPlugin()
    }
}

The comment says init() should not be public, but line 39 declares public init() {}. The app uses the documented create() path. Declarations without a modifier are Swift internal, visible within their own module only, so the app target cannot see the package’s unmarked helpers.

Logic ownership and placement

Logic Owning type or file Placement rationale
Scene declaration and launch registration ChaparralVillageApp It keeps the app shell minimal. Every reusable piece lives in the package.
Entity-root setup and the menu-to-immersive handoff ContentView The logic needs SwiftUI scene actions (dismissWindow) and RealityView content in one place.
Opening the immersive space StartGameButtonView, LoadGameButtonView These views read openImmersiveSpace directly from the environment. AppState holds no presentation closures.
Level loading, restore, and fades LevelManager It is a scene-scoped manager that ECS systems and scripts can reach through scene[LevelManager.self].
Save selection and persistence SaveManager + SavePersistence.swift SwiftData code sits in a separate extension file, and the @Model lives in GameRestoreRecord.swift.
Per-frame gameplay behavior 49 …System structs (for example BreakSystem, ZoneTrackerSystem) It runs as RealityKit systems that operate on authored components.
Scripting bridge rksModule() on the managers and registerMainActor() Managers expose StaticFunc/TypeSchema entries to the RealityKitScripting runtime.

Design patterns

Pattern Source evidence Purpose or tradeoff
Entity-component-system composition ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/RCPCustomComponentsPlugin.swift:44 and context.registerSystem(BreakSystem.self) Gameplay is authored as components in Reality Composer Pro and run by registered systems. The editor and the app share one registration list.
Scene-scoped registry ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/EcsAbstractions/SceneBound.swift:53 and Scene subscript The registry maps one manager instance per RealityKit scene, populated from component add events and looked up with scene[T.self]. Tradeoff: collaborators locate managers at run time instead of receiving them as constructor dependencies.
SwiftUI environment injection ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ChaparralVillageApp.swift:42 and .environment(appState) One AppState instance reaches both scenes and the attached menu views without being passed through initializers.
Protocol-oriented abstraction ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/ObjectManipulation/Affordances/Affordance.swift:14 and SceneBound Protocols with default extension implementations let many concrete components or managers share one collaboration contract.
Observer ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/ZoneManagement/ZoneTracker.swift:134 and ZoneTracker.subscribers Handler types register through registerZoneHandler(), and ZoneTrackerSystem notifies each one of zone enter, change, and exit events.

Main application flow

This section traces one user action: tapping Start Game in the volumetric menu. The flow runs until the immersive level is in place and the menu window is dismissed.

Reference code

ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Menus/StartGameButton.swift:42: startGame()

    func startGame() {
        started = true
        Task {
            // Try to open the immersive space.
            appState.phase = .transitioning
            switch await openImmersiveSpace(id: AppState.immersiveSpace) {
                case .opened:
                    target.scene?[SaveManager.self]?.setNoActiveRestore()
                // ...
            }
        }
    }

ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift:93, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift:106, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift:109, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift:116, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift:119: immersive RealityView setup

                Task {
                    do {
                        // Start fading out the menu level in the volume.
                        let unloadMenuTask = Task { @MainActor in
                            await appState.volumeLevelManager?.unload(.menu, fadeOver: 2.0)
                        }
                        // ...
                        try await levelManager.load(level: level, slot: .game, fadeOver: 2.0) { @MainActor in
                            // Wait for the menu level to unload and the immersive level to load before
                            // positioning the immersive level at the position of the volume.
                            await unloadMenuTask.value
                            // ...
                            dismissWindow(id: AppState.mainMenu)
                            // ...
                            appState.phase = .immersive
                        }
                        // ...
                    } catch {
                        self.error = error.localizedDescription
                    }
                }

ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/LevelManager.swift:90, ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/LevelManager.swift:98: load(level:slot:fadeOver:prefadeSetup:)

    public func load(
        level: Level,
        slot: LevelLoadSlot,
        fadeOver fadeTime: Float? = nil,
        prefadeSetup: (() async throws -> Void)? = nil
    ) async throws {
        // ...
        try await prefadeSetup?()

        if let fadeTime {
            // Fade in entities in the player's space that are in the new level.
            fadeInRestoredEntities(level: level, fadeTime: fadeTime, activeRestore: activeRestore)
            await levelEntity.fade(over: fadeTime, from: 0.0, to: 1.0)
        }
        levelEntity.components.remove(OpacityComponent.self)
        levelRoot.scene?[CutsceneManager.self]?.levelLoadComplete()
    }

Naming conventions

  • Types: …Component for authored ECS data (BreakableComponent, StartGameButtonComponent). …System for RealityKit systems (GameButtonSystem, BreakSystem). …Manager for SceneBound scene singletons (LevelManager, SaveManager, ARManager). …Handler for zone or input callback types (ContainerHandler, ZoneCutsceneHandler). …Affordance for drag constraints. DioramaViewController is a Component struct, not a UIKit controller (ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/LevelMarkup/Diorama.swift:12).
  • Protocols: role or capability nouns (SceneBound, Affordance, ZoneChangeHandler, TapHandler, DragHandler, CustomRestore).
  • Methods: commands (load, unload, store, persist, startNewSave, continueSave), a register… prefix for registration (registerZoneHandler, registerMainActor), and rksModule() for scripting exposure.
  • Files and extensions: one feature per file. Same-type extensions are split by concern: SavePersistence.swift extends SaveManager, and InputManager+SpatialEvents.swift and InputManager+RealityKitScripting.swift extend InputManager.

Architecture takeaways

  • A thin app target over one dynamic local package keeps all gameplay code shareable with the Reality Composer Pro editor plug-in. Dependencies point app → RCPCustomComponents → remote Apple packages, and the app target declares no remote package of its own.
  • SceneBound turns ECS components into per-scene manager singletons. Collaborators look them up with scene[T.self] instead of receiving them as dependencies, which trades explicit wiring for editor- and script-friendly discovery.
  • Cross-scene coordination runs through one environment-injected @Observable AppState (phase, volumeLevelManager, volumeArRoot). Buttons call openImmersiveSpace themselves rather than through closures stored on shared state.
  • Isolation is explicit: both modules default to nonisolated code, and main-actor guarantees come from @MainActor on SceneBound, AppState, and the persistence methods. Long-running ARKit and level-loading tasks are unstructured and never cancelled.
  • CocoLatteFoundation is present only as tool residue. Nothing in the source supports a foundation-layer role for it.

Source map

Source file Relevant symbols
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ChaparralVillageApp.swift ChaparralVillageApp, PluginHandler
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage/ContentView.swift ContentView, immersive and volume setup
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/ChaparralVillage.xcodeproj/project.pbxproj App target package product dependency, platforms, default isolation
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Package.swift RCPCustomComponents product, remote dependencies, defaultIsolation
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Scripts/InstallPlugin.sh Plug-in install location
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/RCPCustomComponentsPlugin.swift RCPCustomComponentsPlugin, create(), registerMainActor()
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/EcsAbstractions/SceneBound.swift SceneBound, SceneBoundTracker, Scene subscript
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/AppState.swift AppState, AppPhase
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/LevelManager.swift LevelManager, load, fadeOutExistingLevel, LevelLoadedEvent
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Managers/ARManager.swift ARManager.register
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Cutscene/CutsceneManager.swift CutsceneManager
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Cutscene/Dialog.swift DialogModel
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/SaveRestoration/SaveManager.swift SaveManager
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/SaveRestoration/SavePersistence.swift configurePersistence, persist, loadPersistedSaves
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/SaveRestoration/GameRestoreRecord.swift GameRestoreRecord
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Menus/GameButtonSystem.swift GameButtonSystem
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Menus/StartGameButton.swift StartGameButtonComponent, StartGameButtonView
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/Menus/LoadGameButton.swift LoadGameButtonComponent, LoadGameButtonView
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/ZoneManagement/ZoneTracker.swift ZoneTracker, ZoneTrackerSystem, ZoneChangeHandler
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/ObjectManipulation/Affordances/Affordance.swift Affordance, ActiveAffordance
ChaparralVillageBuildingAnImmersiveVisionOSAdventureGame/Packages/RCPCustomComponents/Sources/RCPCustomComponents/LevelMarkup/Diorama.swift DioramaViewController component