Sample CodevisionOSReviewed 2026-11-01View on Apple Developer

Manipulating models with RealityKit

At a glance

Item Summary
Purpose Load a USDZ model into a mixed immersive space, move it with ManipulationComponent, expand its parts apart, browse its hierarchy, and clip it with six draggable planes.
App architecture ModelManipulatorApp owns one @Observable AppModel and injects it into a ContentWindow and an ImmersiveScene. ImmersiveView loads the model in a RealityView and hands the entity to AppModel, which owns clipping controllers and observation tasks. Custom components plus one System keep the clipping control aligned with the model.
Main patterns One observable app-state owner injected through the SwiftUI environment; RealityKit components and a per-frame system for entity-level state; Entity extensions for assembly, clipping, and expansion behavior.
Project style Role folders: Models/, Scenes/, Views/, Entities/, Components/, Systems/, Extensions/. One primary type per file.
Execution model The target sets SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor, so undecorated declarations are main-actor isolated. AppModel stores and cancels two observation tasks per entity. A task group generates collision shapes concurrently at load.
State/event model @Observable AppModel read through @Environment(AppModel.self); Observations { ... } async sequences over observable RealityKit components; RealityKit gesture closures; per-frame System.update.
Key frameworks/packages SwiftUI, RealityKit, Observation, UniformTypeIdentifiers, simd, os.log. The target declares no Swift package product.

Project structure

ModelManipulator.xcodeproj/        one visionOS application target
ModelManipulator/
├── ModelManipulatorApp.swift      @main; owns AppModel; window <-> immersive transitions
├── Models/
│   ├── AppModel.swift             @Observable app state, clipping controllers, observation tasks
│   ├── ClippingController.swift   holds one ClippingControlEntity
│   └── ClippingPlane.swift        enum of six planes: direction, rotation, offset, scale
├── Scenes/
│   ├── ContentWindow.swift        WindowGroup -> ContentView
│   └── ImmersiveScene.swift       ImmersiveSpace (.mixed) -> ImmersiveView
├── Views/                         ContentView, ImmersiveView, ImmersiveControlsView,
│                                  EntityHierarchyView, one file per toolbar button,
│                                  LoadingIndicatorSpatialOverlay
├── Entities/
│   ├── ClippingControlEntity.swift      six-plane container, drag math
│   └── ClippingPlaneControlEntity.swift one plane + DragGesture
├── Components/
│   ├── ClippingBoundsCacheComponent.swift  clipping state + stored bounds
│   └── ClippingTransformSyncComponent.swift weak link to the control entity
├── Systems/ClippingTransformSyncSystem.swift
└── Extensions/                    Entity+ModelManipulator, Axis, BoundingBox, Logger

Structure observations

  • Scenes are separate Scene types with a static sceneID, and the app composes them in makeDefaultScenes() (ModelManipulator/Scenes/ContentWindow.swift:12, ModelManipulator/Scenes/ImmersiveScene.swift:12, ModelManipulator/ModelManipulatorApp.swift:67).
  • Each toolbar control is its own small view that reads AppModel from the environment and calls one model method (ModelManipulator/Views/LockModelButton.swift:15, ModelManipulator/Views/ExpandModelButton.swift:16, ModelManipulator/Views/ExitButton.swift:15).
  • Most RealityKit behavior lives in Entity extensions grouped by // MARK: (component accessors, assembly, hierarchy, clipping, expansion) rather than in view or model types (ModelManipulator/Extensions/Entity+ModelManipulator.swift:14, ModelManipulator/Extensions/Entity+ModelManipulator.swift:64, ModelManipulator/Extensions/Entity+ModelManipulator.swift:170, ModelManipulator/Extensions/Entity+ModelManipulator.swift:231).
  • The project’s only target uses a file-system-synchronized group and an empty packageProductDependencies list (ModelManipulator.xcodeproj/project.pbxproj:102), and supports only xros xrsimulator (ModelManipulator.xcodeproj/project.pbxproj:186).

Overall architecture

Reference code

ModelManipulator/ModelManipulatorApp.swift:11 — ModelManipulatorApp

struct ModelManipulatorApp: App {
    @State private var appModel = AppModel()
    // ...
    var body: some Scene {
        makeDefaultScenes()
            .environment(appModel)
            .onChange(of: appModel.viewState) { fromState, toState in
                Task { @MainActor in
                    switch (fromState, toState) {
                    case (.portal, .immersive):
                        await enterImmersivePresentation()
                    case (.immersive, .portal):
                        await exitImmersivePresentation()
                    default:
                        break
                    }
                }
            }
            .onChange(of: scenePhase) { _, newPhase in
                if newPhase == .background {
                    appModel.reset()
                }
            }
    }
    // ...
}

Interpretation

Observed: views never open or dismiss scenes themselves. They change AppModel.viewState (through selectModel(url:) or reset()), and the app’s onChange handler translates that transition into openImmersiveSpace / dismissWindow or dismissImmersiveSpace / openWindow (ModelManipulator/ModelManipulatorApp.swift:44, ModelManipulator/ModelManipulatorApp.swift:58). immersiveSpaceState tracks the transition so a second request is ignored while one is in flight.

Inference: keeping scene transitions in the App type, where the scene-opening environment actions live, lets AppModel stay free of SwiftUI environment actions while still driving navigation through plain state.

Ownership and state

Ownership evidence

ModelManipulator/Models/AppModel.swift:15 — AppModel stored state

final class AppModel {
    /// The app-wide clipping state, mirrored from the active entity to drive `isClipping` and `isEditingClip`.
    private var clippingState = ClippingBoundsCacheComponent.ClippingState.off
    // ...
    /// A Boolean value that indicates whether the model parts are expanded apart.
    private(set) var isModelExpanded = false
    // ...
    /// A Boolean value that indicates whether the model is locked from direct manipulation.
    private(set) var isModelLocked = true
    /// The root entity of the currently loaded 3D model.
    var modelEntity: Entity?

    /// The URL of the currently selected model.
    private(set) var selectedModelURL: URL?
    /// The current view state determining the active presentation mode.
    private(set) var viewState = ViewState.default

    /// The active clipping controllers, keyed by the entity each one clips.
    private var clippingControllers: [Entity.ID: ClippingController] = [:]
    /// The transform each assembly child had before expansion, keyed by child entity.
    private var initialChildTransforms: [Entity.ID: Transform] = [:]
    /// The async tasks observing each entity's clipping state and bounds, keyed by entity.
    private var observationTasks: [Entity.ID: [Task<Void, Never>]] = [:]
    // ...
}
Owner Object or state Relationship Mutation authority
ModelManipulatorApp AppModel Creates it in @State private var and injects it with .environment(appModel) (ModelManipulator/ModelManipulatorApp.swift:12, ModelManipulator/ModelManipulatorApp.swift:22) AppModel methods; a few plain vars are also set by views
AppModel viewState, selectedModelURL, isModelExpanded, isModelLocked private(set) (ModelManipulator/Models/AppModel.swift:29, ModelManipulator/Models/AppModel.swift:42) Only AppModel
ImmersiveView modelEntity, isModelLoaded Writes them after loading (ModelManipulator/Views/ImmersiveView.swift:47, ModelManipulator/Views/ImmersiveView.swift:49); the entity itself is added to RealityViewContent ImmersiveView sets; AppModel.reset() clears
AppModel ClippingController per entity Created lazily in ensureClippingController(for:) (ModelManipulator/Models/AppModel.swift:218) and removed when clipping turns off AppModel
ClippingController ClippingControlEntity var container, built by the async factory makeEntity() (ModelManipulator/Models/ClippingController.swift:16) AppModel parents and unparents it
ClippingControlEntity Six ClippingPlaneControlEntity children, clippedEntity private var planes, private weak var clippedEntity (ModelManipulator/Entities/ClippingControlEntity.swift:13, ModelManipulator/Entities/ClippingControlEntity.swift:17) The control entity itself
Model entity ClippingBoundsCacheComponent, ClippingComponent, ClippingTransformSyncComponent Components set by ImmersiveView, the clippingState setter, and clipEntity(_:) (ModelManipulator/Views/ImmersiveView.swift:99, ModelManipulator/Extensions/Entity+ModelManipulator.swift:178, ModelManipulator/Entities/ClippingControlEntity.swift:52) Entity extension methods and the sync system

Observed: both cross-references between the model entity and its clipping control are weak (ClippingTransformSyncComponent.clippingControl and ClippingControlEntity.clippedEntity) (ModelManipulator/Components/ClippingTransformSyncComponent.swift:12). The strong path to the control runs from AppModel.clippingControllers and, while editing, from the scene graph.

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 main-actor isolation SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor, SWIFT_APPROACHABLE_CONCURRENCY = YES, Swift 6 Undecorated types such as AppModel, the entity subclasses, and ClippingTransformSyncSystem are main-actor isolated by build setting, not by annotation ModelManipulator.xcodeproj/project.pbxproj:187, ModelManipulator.xcodeproj/project.pbxproj:188, ModelManipulator.xcodeproj/project.pbxproj:191
Explicit main-actor task Task { @MainActor in ... } in the viewState onChange Awaits openImmersiveSpace or dismissImmersiveSpace; the task is not stored ModelManipulator/ModelManipulatorApp.swift:24
Retained observation tasks Task { @MainActor [weak self, weak entity] in for await ... in Observations { ... } } Two loops per entity, one for clipping state and one for clipping bounds, stored in observationTasks[entity.id] ModelManipulator/Models/AppModel.swift:137, ModelManipulator/Models/AppModel.swift:146, ModelManipulator/Models/AppModel.swift:154
Cancellation task.cancel() in teardownClippingObservation(for:), called from reset() reset() runs on Exit and when the scene phase becomes .background ModelManipulator/Models/AppModel.swift:199, ModelManipulator/Models/AppModel.swift:102, ModelManipulator/ModelManipulatorApp.swift:37
Unretained tasks Task { await ensureClippingController(for:) }; button Task { await appModel.handleClippingStateChange(...) } Short tasks that inherit main-actor isolation from their context; not stored or cancelled ModelManipulator/Models/AppModel.swift:132, ModelManipulator/Views/EditClipButton.swift:20, ModelManipulator/Views/ClippingStateButton.swift:23
Structured concurrency withTaskGroup with one addTask per mesh calling ShapeResource.generateConvex(from:) Child results return (index, shape, error); the parent loop assigns collisionComponent to each entity. The source comment says generation “runs concurrently”; the executor of child tasks is not established in source. ModelManipulator/Extensions/Entity+ModelManipulator.swift:97, ModelManipulator/Extensions/Entity+ModelManipulator.swift:110
Async load RealityView { content in await loadModel(...) } Loads Entity(contentsOf:), attaches collision shapes, then writes model state ModelManipulator/Views/ImmersiveView.swift:24, ModelManipulator/Views/ImmersiveView.swift:82
Per-frame scheduling System.update(context:) with updatingSystemWhen: .rendering Copies the model entity’s transform to its clipping control every rendered frame when it changed ModelManipulator/Systems/ClippingTransformSyncSystem.swift:21
Shared-state safety Main-actor isolation only No lock or queue; AppModel’s dictionaries are touched only from main-actor code ModelManipulator/Models/AppModel.swift:45

Reference code

ModelManipulator/Models/AppModel.swift:131 — retained observation tasks

    func setupClippingObservation(for entity: Entity) {
        Task {
            await ensureClippingController(for: entity)
        }

        // Use weak captures because the entity or model may be deallocated while observation is active.
        let stateTask = Task { @MainActor [weak self, weak entity] in
            // Access the observable version of the component to enable async observation of property changes.
            let stateObservations = Observations { entity?.observable.components[ClippingBoundsCacheComponent.self]?.clippingState ?? .off }
            for await state in stateObservations {
                guard let self, let entity else { break }
                await self.handleClippingStateChange(for: entity, newState: state)
            }
        }

        let boundsTask = Task { @MainActor [weak self, weak entity] in
            let boundsObservations = Observations { entity?.observable.components[ClippingComponent.self]?.bounds }
            for await _ in boundsObservations {
                guard let self, let entity else { break }
                await self.handleClippingBoundsChange(for: entity)
            }
        }

        observationTasks[entity.id] = [stateTask, boundsTask]
    }

ModelManipulator/Models/AppModel.swift:196 — cancellation

    func teardownClippingObservation(for entity: Entity) {
        if let tasks = observationTasks[entity.id] {
            for task in tasks {
                task.cancel()
            }
        }
        observationTasks[entity.id] = nil
        // ...
    }

Interpretation: lifetime is explicit for the long-running loops. Each loop also exits on its own when the weakly captured model or entity disappears. The first Task in setupClippingObservation is fire-and-forget, and ensureClippingController guards against creating a second controller for the same entity.

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 @Observable AppModel + .environment(appModel) / @Environment(AppModel.self) Every view reads the same model instance from the environment ModelManipulator/Models/AppModel.swift:14, ModelManipulator/Views/ImmersiveView.swift:13
State propagation Explicit .environment(appModel) on attachment roots ViewAttachmentComponent root views (controls, error view) receive the model explicitly ModelManipulator/Views/ImmersiveView.swift:63, ModelManipulator/Views/ImmersiveView.swift:72
State propagation @Bindable var appModel = appModel inside body Creates a binding for fileImporter(isPresented:) ModelManipulator/Views/ContentView.swift:14, ModelManipulator/Views/ContentView.swift:26
Entity-to-model state Observations { entity?.observable.components[...] } Changes to the entity’s clipping state and clipping bounds drive AppModel handlers ModelManipulator/Models/AppModel.swift:139, ModelManipulator/Models/AppModel.swift:147
Gesture input GestureComponent(DragGesture ... .onChanged/.onEnded) on each plane The plane forwards drag values to its parent ClippingControlEntity ModelManipulator/Entities/ClippingPlaneControlEntity.swift:47
Framework import RealityKit, SwiftUI, Observation, UniformTypeIdentifiers, os.log Imported by AppModel ModelManipulator/Models/AppModel.swift:8, ModelManipulator/Models/AppModel.swift:12
Framework import simd Plane geometry and expansion math ModelManipulator/Models/ClippingPlane.swift:9
Package declaration None Empty packageProductDependencies ModelManipulator.xcodeproj/project.pbxproj:102

No Combine import appears in the source.

Class and protocol design

Reference code

ModelManipulator/Systems/ClippingTransformSyncSystem.swift:12 — ClippingTransformSyncSystem

final class ClippingTransformSyncSystem: System {
    /// A query that matches all entities with a clipping transform sync component.
    static let query = EntityQuery(where: .has(ClippingTransformSyncComponent.self))

    required init(scene: Scene) {}
    // ...
    func update(context: SceneUpdateContext) {
        for entity in context.entities(matching: Self.query, updatingSystemWhen: .rendering) {
            guard var component = entity.clippingTransformSyncComponent else {
                continue
            }

            guard let control = component.clippingControl else {
                entity.clippingTransformSyncComponent = nil
                continue
            }

            let currentTransform = entity.transform
            // Only write when the transform actually changed to avoid sending unnecessary change notifications.
            if component.lastSyncedTransform != currentTransform {
                control.transform = currentTransform
                component.lastSyncedTransform = currentTransform
            }

            // Entity Component System (ECS) components are value types; write mutations back to the entity.
            entity.clippingTransformSyncComponent = component
        }
    }
}
Type Responsibility Depends on
AppModel App-wide UI state, model selection, lock/expand, clipping lifecycle and observation Entity, ClippingController, components
ClippingController Async construction wrapper holding one ClippingControlEntity ClippingControlEntity
ClippingControlEntity Fits six planes to bounds, turns drags into trimmed clipping bounds ClippingPlaneControlEntity, ClippingPlane, Entity clipping extensions
ClippingPlaneControlEntity One translucent plane with collision, hover effect, and a drag gesture ClippingPlane
ClippingPlane Value enum with per-face direction, rotation, offset, and scale simd, BoundingBox
ClippingBoundsCacheComponent Per-entity clipping state and stored bounds RealityKit.Component
ClippingTransformSyncComponent / ClippingTransformSyncSystem Weak link from model to control; per-frame transform copy RealityKit ECS

Observed: the sample declares no protocol of its own. It conforms to RealityKit’s Component and System and subclasses Entity. AppModel.init() registers the system before any scene runs (ModelManipulator/Models/AppModel.swift:53). The system’s header comment explains why a System is used instead of an onChange handler: it “runs every frame, keeping transforms in sync without a frame of lag” (ModelManipulator/Systems/ClippingTransformSyncSystem.swift:10).

Access control

Symbol Access Verified effect Likely rationale
AppModel.viewState, selectedModelURL, isModelExpanded, isModelLocked (ModelManipulator/Models/AppModel.swift:29) private(set) Views read them but must call selectModel, reset, toggleModelExpansion, or toggleModelLock to change them Inference: these changes have side effects (scene transitions, assembly open/close) that must run together.
AppModel.clippingControllers, initialChildTransforms, observationTasks, clippingState (ModelManipulator/Models/AppModel.swift:17, ModelManipulator/Models/AppModel.swift:45) private Only AppModel manages controllers and task lifetimes Inference: keeps creation and cancellation in one place.
AppModel.modelEntity, isModelLoaded, isFileImporterPresented, isHierarchyVisible implicit internal var Views write these directly (ModelManipulator/Views/ImmersiveView.swift:47, ModelManipulator/Views/HierarchyButton.swift:16) Inference: simple flags with no side effects.
ClippingControlEntity.clippedEntity, planes, drag-start fields (ModelManipulator/Entities/ClippingControlEntity.swift:13) private (clippedEntity also weak) Drag state cannot be altered from outside the control Inference: the drag math relies on these values being consistent within one gesture.
ClippingPlaneControlEntity.clippingPlane (ModelManipulator/Entities/ClippingPlaneControlEntity.swift:13) private(set) The parent reads which face a plane controls; nobody reassigns it Inference: a plane’s face is fixed at creation.
LoadingIndicatorSpatialOverlay, LoadingIndicatorOverlayModifier (ModelManipulator/Views/LoadingIndicatorSpatialOverlay.swift:13, ModelManipulator/Views/LoadingIndicatorSpatialOverlay.swift:44) private struct Only the file’s View.loadingIndicatorOverlay(appModel:) extension is visible Inference: exposes a modifier API and hides its implementation.
Entity.locallyUpdateIsClipped(_:) and expansion helpers (ModelManipulator/Extensions/Entity+ModelManipulator.swift:204, ModelManipulator/Extensions/Entity+ModelManipulator.swift:245) private Callers go through clippingState or expandAlongPrimaryAxis(offset:) Inference: keeps component bookkeeping behind one setter.

Reference code

ModelManipulator/Entities/ClippingControlEntity.swift:12 — private drag state

final class ClippingControlEntity: Entity {
    private weak var clippedEntity: Entity?
    private var firstEventLocationInWorld: SIMD3<Float>?
    private var mostRecentBounds: BoundingBox?
    private var planeLocationStartOfDragInWorld: SIMD3<Float>?
    private var planes: [ClippingPlane: ClippingPlaneControlEntity] = [:]
    // ...
}

No declaration is public or open; undecorated declarations are Swift’s implicit internal within the single app module.

Logic ownership and placement

Logic Owning type or file Placement rationale
Window/immersive-space transitions ModelManipulatorApp.enterImmersivePresentation() / exitImmersivePresentation() Uses the scene environment actions that only views and the app can read.
Model loading and initial components ImmersiveView.makeModelEntity(from:) Sets ManipulationComponent (releaseBehavior = .stay), bounds cache, input target, hover effect, and fit-to-size scale (ModelManipulator/Views/ImmersiveView.swift:92).
Per-leaf collision Entity.attachLeafCollisionShapes() Builds convex hulls once at load so assembly open/close does not rebuild collision (ModelManipulator/Extensions/Entity+ModelManipulator.swift:86).
Lock/unlock and expand AppModel.toggleModelLock() / toggleModelExpansion() with Entity.openAssembly() / closeAssembly() / expandAlongPrimaryAxis(offset:) AppModel holds the flags and saved transforms; entity extensions move manipulation components between the root and its parts.
Clipping state machine AppModel.handleClippingStateChange(for:newState:) Adds, hides, or removes the control entity per state, then writes entity.clippingState (ModelManipulator/Models/AppModel.swift:60).
Clip component bookkeeping Entity.clippingState setter → locallyUpdateIsClipped(_:) Creates or removes ClippingComponent and preserves bounds in the cache (ModelManipulator/Extensions/Entity+ModelManipulator.swift:172).
Drag-to-trim math ClippingControlEntity.handleDragChanged(_:) / handleDragEnded(_:) Projects the drag onto the plane’s axis, constrains it to model bounds, and commits bounds at drag end.
Transform following ClippingTransformSyncSystem Per-frame copy, writing only when the transform changed.

Design patterns

Pattern Source evidence Purpose or tradeoff
Observable state owner @Observable final class AppModel with private(set) state and command methods (ModelManipulator/Models/AppModel.swift:14, ModelManipulator/Models/AppModel.swift:42) One owner for UI state and clipping lifecycle; some plain flags remain writable by views.
SwiftUI environment injection .environment(appModel) on the scenes and on attachment root views; @Environment(AppModel.self) in every view (ModelManipulator/ModelManipulatorApp.swift:22, ModelManipulator/Views/ImmersiveView.swift:72, ModelManipulator/Views/ContentView.swift:11) Shares one instance across a window, an immersive space, and RealityKit view attachments.
Entity-component-system composition ClippingBoundsCacheComponent, ClippingTransformSyncComponent, ClippingTransformSyncSystem with EntityQuery (ModelManipulator/Components/ClippingBoundsCacheComponent.swift:10, ModelManipulator/Systems/ClippingTransformSyncSystem.swift:14) Entity-level state lives on the entity; the system applies per-frame behavior to every entity that has the component.

Removed: “View-controller organization”. ClippingController is a two-property wrapper whose only job is to build and hold a ClippingControlEntity asynchronously (ModelManipulator/Models/ClippingController.swift:11); the source does not give it a controller role.

Main application flow

Reference code

ModelManipulator/Views/EditClipButton.swift:22 — button starts the transition

        Button {
            if appModel.isEditingClip {
                Task { await appModel.handleClippingStateChange(for: entity, newState: .active) }
            } else {
                Task { await appModel.handleClippingStateChange(for: entity, newState: .editing) }
            }
        } label: {
            // ...
        }

ModelManipulator/Models/AppModel.swift:60 — editing branch of the state handler

    func handleClippingStateChange(
        for entity: Entity,
        newState: ClippingBoundsCacheComponent.ClippingState
    ) async {
        switch newState {
        // ...
        case .editing:
            // Transitioning to editing: show the clipping planes so the person can adjust them.
            guard let parent = entity.parent else { return }
            await ensureClippingController(for: entity)
            guard let controller = clippingControllers[entity.id] else { return }
            do {
                try controller.container.clipEntity(entity)
                parent.addChild(controller.container)
            } catch {
                Logger.logger.error("Failed to clip entity: \(error)")
            }
        }

        entity.clippingState = newState
        clippingState = newState
    }

ModelManipulator/Entities/ClippingControlEntity.swift:52 — the control attaches the sync component

    func clipEntity(_ model: Entity) throws {
        guard model.parent != nil else {
            throw ClippingControlError.clippedEntityMustHaveParent
        }

        let bounds = model.clippingBoundsCacheComponent?.storedClippingBounds
            ?? model.visualBounds(recursive: true, relativeTo: model)

        transform = model.transform
        makeFit(to: bounds)
        clippedEntity = model

        // Sync ensures the clipping planes follow the model if it moves, such as when using a drag gesture.
        model.clippingTransformSyncComponent = ClippingTransformSyncComponent(clippingControl: self)
    }

Observed: the handler writes the new state onto the entity’s component, which the stored Observations task in setupClippingObservation watches, so the same handler is re-entered with the state it just wrote. The Entity.clippingState setter returns early when the value is unchanged, so the repeated write is a no-op. Inference: this round trip keeps AppModel consistent even if another path changes the component.

Naming conventions

  • Types: feature prefix plus RealityKit role suffix: ClippingBoundsCacheComponent, ClippingTransformSyncComponent, ClippingTransformSyncSystem, ClippingControlEntity, ClippingPlaneControlEntity. Scenes are named for their kind (ContentWindow, ImmersiveScene), and each toolbar control is <Action>Button.
  • Protocols: none declared locally.
  • Methods: toggle… for flag flips (toggleModelLock, toggleModelExpansion), setup…/teardown… pairs for observation lifetime, handle… for reactions (handleClippingStateChange, handleDragChanged), make… for factories (makeEntity, makeModelEntity, makeDefaultScenes), and ensure… for idempotent creation (ensureClippingController).
  • Files and extensions: Type+ModelManipulator.swift for extensions of framework types (Entity, Axis3D, BoundingBox, Logger); // MARK: - Private behavior separates public and private members throughout.

Architecture takeaways

  • Navigation is state-driven: views change AppModel.viewState, and only the App type turns that into immersive-space and window actions.
  • Long-running observation tasks are stored per entity and cancelled in one teardown method, and each loop also captures its owners weakly so it can end on its own.
  • RealityKit state that belongs to an entity (clip state, stored bounds, link to its control) lives in components, and per-frame alignment is a System rather than a view callback.
  • Weak references on both sides of the model-to-control link, and [weak self] in gesture closures, avoid retain cycles between entities, components, and closures.
  • Collision shapes are generated once per leaf with a task group at load, moving expensive work out of interactive paths.

Source map

Source file Relevant symbols
ModelManipulator/ModelManipulatorApp.swift ModelManipulatorApp, enterImmersivePresentation(), exitImmersivePresentation(), makeDefaultScenes()
ModelManipulator/Models/AppModel.swift AppModel, handleClippingStateChange(for:newState:), setupClippingObservation(for:), teardownClippingObservation(for:), toggleModelExpansion(), toggleModelLock(), reset(), ViewState, ImmersiveSpaceState
ModelManipulator/Models/ClippingController.swift ClippingController
ModelManipulator/Models/ClippingPlane.swift ClippingPlane
ModelManipulator/Scenes/ContentWindow.swift ContentWindow
ModelManipulator/Scenes/ImmersiveScene.swift ImmersiveScene
ModelManipulator/Views/ImmersiveView.swift ImmersiveView, loadModel(from:into:), makeModelEntity(from:), makeControlsEntity()
ModelManipulator/Views/ContentView.swift ContentView
ModelManipulator/Views/EditClipButton.swift EditClipButton
ModelManipulator/Views/ClippingStateButton.swift ClippingStateButton
ModelManipulator/Views/HierarchyButton.swift HierarchyButton
ModelManipulator/Views/LockModelButton.swift LockModelButton
ModelManipulator/Views/ExpandModelButton.swift ExpandModelButton
ModelManipulator/Views/ExitButton.swift ExitButton
ModelManipulator/Views/LoadingIndicatorSpatialOverlay.swift LoadingIndicatorSpatialOverlay, LoadingIndicatorOverlayModifier, loadingIndicatorOverlay(appModel:)
ModelManipulator/Entities/ClippingControlEntity.swift ClippingControlEntity, makeEntity(), clipEntity(_:), handleDragChanged(_:), handleDragEnded(_:)
ModelManipulator/Entities/ClippingPlaneControlEntity.swift ClippingPlaneControlEntity, GestureComponent
ModelManipulator/Components/ClippingBoundsCacheComponent.swift ClippingBoundsCacheComponent, ClippingState
ModelManipulator/Components/ClippingTransformSyncComponent.swift ClippingTransformSyncComponent
ModelManipulator/Systems/ClippingTransformSyncSystem.swift ClippingTransformSyncSystem
ModelManipulator/Extensions/Entity+ModelManipulator.swift attachLeafCollisionShapes(), openAssembly(), closeAssembly(), clippingState, expandAlongPrimaryAxis(offset:)
ModelManipulator.xcodeproj/project.pbxproj SWIFT_DEFAULT_ACTOR_ISOLATION, SUPPORTED_PLATFORMS, packageProductDependencies