Guidance for Claude Code when working in this repository: either developing the engine itself, or helping a developer build a game or application on top of it. Read Step 0 first — the rules differ.
- Engine development: changes inside this repo (
Sources/UntoldEngine,Sources/UntoldEngineXR,Sources/UntoldEngineAR,Sources/UntoldComponentKit,Tools/,Tests/). Follow §6 Coding Conventions and §8 Build and Validation strictly. - Application development: building a game/app that depends on the
UntoldEngineSwift package (own repo, ownPackage.swift). Use only the public, documented APIs described in §4 anddocs/API/. Never reach into engine internals.
Untold Engine is an open-source Swift + Metal engine for Apple platforms (macOS, iOS, visionOS), built for developers who want full control over rendering, physics, and input without a general-purpose editor-first workflow (RealityKit/Unity/Unreal idioms do not apply here — verify every API against this repo before assuming it exists).
- Language: Swift 6 (strict concurrency,
swiftLanguageMode(.v6)everywhere) for engine/app code; Metal for GPU rendering and compute. - Graphics: Metal, custom render-graph renderer (no SceneKit/RealityKit dependency).
- Platforms: macOS 14+, iOS 17+, visionOS 2+ (per
Package.swift). A separate, non-Swift-Package Untold Editor app exists (untoldengine studio, downloaded separately) for visual scene editing — this repo is the engine + CLI, not the editor. - Distinguishing design choice: the public API is largely free functions operating on an
EntityID(e.g.createEntity(),translateTo(entityId:...),setEntityMesh(entityId:...)), not an object-oriented entity class hierarchy. Don't inventEntitymethods — look up the matching free function instead.
| Area | Path | What's there |
|---|---|---|
| Engine core | Sources/UntoldEngine/ |
ECS, rendering, physics, animation, scripting — see table below |
| Shared GPU types | Sources/CShaderTypes/ |
C header (ShaderTypes.h) defining struct layouts shared by Swift and Metal — the Swift/Metal data bridge |
| visionOS | Sources/UntoldEngineXR/ |
UntoldEngineXR.swift — CompositorServices/ARKit-based XR runtime, separate from the MTKView path |
| iOS AR passthrough | Sources/UntoldEngineAR/ |
UntoldEngineAR.swift — ARSession/MTKView wrapper for iPhone/iPad passthrough AR |
| Code components | Sources/UntoldComponentKit/ |
ComponentPlugin/EntityPlugin/EditorMenuPlugin base classes, @UntoldAttribute reflection, used by the Editor and by code-only projects |
| Cook-time mesh tools | Sources/UntoldEngineMeshCook/ |
LOD-chain generation via CMeshOptimizer (vendored meshoptimizer); used by the CLI/Editor, not by runtime apps |
| Demos | Sources/Demos/* |
Working, runnable example apps — the best ground truth for "how do I actually wire this up" (see §4) |
| CLI | Tools/UntoldEngineCLI/ |
Separate SwiftPM package; untoldengine tool: create, update, export, gaussian-link, studio |
| Tests | Tests/UntoldEngineTests, Tests/UntoldEngineRenderTests, Tests/UntoldComponentKitTests |
Unit tests and image-diff render tests |
| Docs | docs/API/, docs/Architecture/, docs/Tutorials/, docs/Onboarding/, docs/Extensions/ |
Authoritative usage docs — see §9 |
Inside Sources/UntoldEngine/:
| Subdir | Contains |
|---|---|
ECS/ |
Entity id packing (Entity.swift), world storage (Scenes.swift), ComponentRegistry.swift/ComponentPool.swift |
Systems/ |
The bulk of the public API: RegistrationSystem.swift (entity/mesh/light/animation/LOD/batching/gaussian registration — the biggest file in the engine), ScenegraphSystem.swift, CameraSystem.swift, LightingSystem.swift, LightPortalSystem.swift, InputSystem.swift (+ platform extensions), RenderingSystem.swift |
Renderer/ |
UntoldEngine.swift (the MTKViewDelegate, per-frame driver), RenderPasses.swift, PostProcessRenderPasses.swift |
Shaders/ |
One .metal file per effect (modelShader.metal, LightShader.metal, Gaussians.metal, HZBCompute.metal, ...) |
UntoldEngineKernels/ |
UntoldEngineKernels.metal — umbrella file that #includes everything in Shaders/; this is what actually gets compiled (see §8) |
Mesh/ |
Mesh.swift — Material struct, mesh/submesh data model |
AssetFormat/ |
UntoldFormat.swift — the .untold binary container schema |
RuntimeAssets/ |
Asset loaders: RuntimeAssetLoader.swift, NativeFormatLoader.swift, GaussianChunkLoader.swift/GaussianPageManager.swift (Gaussian-splat paging), NativeTextureLoader.swift |
Physics/ |
PhysicsCoordinator.swift, PhysicsBackend.swift/PhysicsBackendRegistry.swift (pluggable backend layer), PhysicsComponents.swift |
Animation/ |
Skeletal animation, pose layers, root motion |
Scripting/ |
USC (Untold Scripting) — data-driven, serializable behavior scripts, distinct from UntoldComponentKit |
Profiling/, Utils/, BuildSystem/, Resources/ |
Supporting infrastructure |
- Entities are
EntityIDs, not objects.createEntity() -> EntityID(RegistrationSystem.swift);destroyEntity(entityId:)tears it down. Creating an entity auto-attaches transform + scenegraph components via an internalmakeSpatialcall — you don't attach those yourself. - Components are attached by dedicated
registerXComponent/setEntityXfunctions, not byentity.addComponent(...). Every component type has a matchingremoveEntityXteardown function invoked bydestroyEntity; when adding a new system that introduces a component, you must register a cleanup handler withComponentRegistryor a debug assertion fires. - Transforms:
translateTo/translateBy,rotateTo(angle:axis:)/rotateTo(rotation:),rotateBy,getPosition/getLocalPosition,getOrientation/getLocalOrientation(docs/API/UsingTransformSystem.md, matches source exactly). Scene-root-level batch operations (translateSceneTo/By,rotateSceneToYaw/ByYaw) exist separately — don't apply them per-entity. - Scene graph / parenting:
setParent(childId:parentId:offset:),removeParent(childId:),getEntityChildren(parentId:),getEntityParent(entityId:)(ScenegraphSystem.swift). Use these instead of inventing a transform hierarchy yourself. - Materials:
Materialstruct (Mesh.swift) has fixed PBR slots —baseColor, roughness, metallic, normal, emissive, height. Change them via accessor functions keyed byentityId/meshIndex/submeshIndex(getMaterialBaseColor,updateMaterialColor,updateMaterialRoughness, ...) documented indocs/API/UsingMaterials.md. Setters auto-refresh static batching — don't bypass them by poking texture fields directly. - Lighting: four light types only —
createDirLight,createPointLight,createSpotLight,createAreaLight. Shared getters/setters (updateLightColor,updateLightIntensity,updateLightAttenuation, per-type shadow toggles). Light portals are a separate system (LightPortalSystem,docs/API/UsingLightPortals.md) for interior/exterior light leaking — not a light type. - Camera:
createGameCamera(entityId:),findGameCamera(), movement (moveCameraTo/By,cameraMoveBy(..., space:)), orbit (orbitAround,setOrbitOffset),cameraLookAt(eye:target:up:), follow modes (cameraFollow,cameraFollowDeadZone), and waypoint paths (startCameraPath(waypoints:mode:settings:)). - Assets and the
.untoldformat: the native binary asset container is.untold(schema:docs/Architecture/assetFormat.md,AssetFormat/UntoldFormat.swift). Sync load:setEntityMesh(entityId:filename:withExtension:assetName:)(.untoldonly). Async/other formats:setEntityMeshAsync(...). Direct in-memory meshes:setEntityMeshDirect(entityId:meshes:assetName:). Animations:setEntityAnimations(entityId:filename:withExtension:name:). Gaussian splats (.untoldgs):setEntityGaussian/setEntityGaussianAsync. Assets resolve against a base path set viasetEngine(.assetBasePath(url)). - Rendering is a render graph, driven once per frame.
UntoldEngine(Renderer/UntoldEngine.swift) is anMTKViewDelegate;draw(in view:)callsUpdateRenderingSystem(in:)(Systems/RenderingSystem.swift), which executes a graph of passes (gBufferPass, shadow pass,postProcessingEffects, Gaussian pass) built bybuildGameModeGraph()/buildExecutableGameModeGraph(). Hook your own per-frame logic viasetupCallbacks/onUpdate(_:)— never calldrawyourself or fight the render graph. - visionOS uses a different runtime entirely.
UntoldEngineXRwraps a CompositorServicesLayerRendererdirectly (noMTKView); it owns its own frame loop (runLoop()), foveation, and device-anchor handling. Don't assume macOS/iOS rendering code paths apply on visionOS. - Two parallel behavior systems, not interchangeable: USC (
Scripting/) is data-driven/serializable (.uscfiles, built withUSCBuilder, run byUSCInterpreter) — use for designer-editable logic.UntoldComponentKit(ComponentPlugin/EntityPlugin) is compiled Swift logic with@UntoldAttribute-exposed properties — use for engine-level reusable behavior. USC scripts can call component-plugin actions viascript.callAction("<TypeName>.<ActionName>"); the reverse is not true. - Extensibility:
EngineExtension/EngineExtensionRegistryfor non-rendering per-frame plugins (physics/audio/AI backends);RenderExtension/RenderExtensionRegistry(refinesEngineExtension) for render-graph-contributing plugins (particles, custom surfaces). Register with exactly one of the two, never both. For single-app gameplay code that doesn't need to be distributable, use the lighterregisterCustomSystem(_:)closure hook instead of either protocol. Physics follows this same two-layer pattern: a built-in dependency-free kinetics layer (setEntityKinetics,applyForce,setLinearVelocity) always works; rigid-body/collider physics (RigidBodyComponent,ColliderComponent) only does anything once an external backend (e.g. Jolt) registers viaPhysicsBackendRegistry— Jolt itself is not vendored in this repo.
Two supported project-creation paths, both producing the same kind of Xcode-buildable package (docs/Onboarding/GettingStartedMakingGamesCLI.md, GettingStartedWithEditor.md):
- CLI-first:
untoldengine create MyGame --platform macos|ios|ios-ar|visionos|multi(install the CLI first — see §8). GeneratesPackage.swift,Sources/<Name>/{AppDelegate,GameScene,...}.swift,GameData/{Scenes,Scripts,Models,Textures,Shaders}. - Editor-first:
untoldengine studioinstalls/launches the separate Untold Editor app for visual placement; still backed by the same code underneath. The Editor is optional — everything it does can be done in code.
Reference the demos, not your assumptions. Sources/Demos/StarterDemo is the smallest complete macOS example and the best starting point to read end-to-end:
main.swiftcreatesNSApplication, assigns anAppDelegate.AppDelegate.swift(NSApplicationDelegate,@MainActor) creates anNSWindow, callsUntoldRenderer.create(), wiressetupCallbacks(gameUpdate:handleInput:), and hosts the engine-providedSceneView(renderer:)viaNSHostingView. You do not write your own render loop orMTKViewon macOS/iOS — the engine owns it.GameScene.swiftis where application code lives: calls free functions directly (createEntity(),setEntityName,setEntityMeshAsync,translateTo,updateMaterialColor,rotateBy,setSceneReady(true)).
Other demos for specific features: ShowcaseDemo, LargeSceneStreamingDemo (tile streaming, large outdoor scenes), InteractionGameplayDemo (input/picking), RenderingQualityDemo (post-FX/quality settings), LightingDemo, ExporterPipelineDemo (asset pipeline), Sandbox. Run any of them with swift run <DemoName> (macOS only; all are hidden, non-published package products, runnable only within this repo during development).
Asset pipeline: author in Blender → untoldengine export converts USD/USDZ to .untold (background Blender process, documented in docs/API/UsingTheExporter.md and docs/API/UsingBlenderAddon.md). Do not hand-author .untold files.
| Platform | Lifecycle | Module | Notes |
|---|---|---|---|
| macOS | NSApplication + AppDelegate + UntoldRenderer/SceneView (MTKView-backed) |
UntoldEngine |
Full input (InputSystem+Keyboard.swift, +Mouse.swift), game controller support |
| iOS | Same MTKView-backed pattern as macOS, UIKit host | UntoldEngine (+ UntoldEngineAR for passthrough) |
UntoldEngineAR's UntoldEngineAR class wraps an app-supplied ARSession/MTKView for camera-passthrough AR (YCbCr textures), separate from visionOS |
| visionOS | ImmersiveSpace/CompositorLayer hands a CompositorServices LayerRenderer to UntoldEngineXR, which runs its own frame loop |
UntoldEngineXR |
No MTKView. Uses ARKit for world tracking/anchors. Immersion modes via setImmersionMode(.none/.mixed/.full). XR-specific lighting (setXRLightingMode) and spatial input (enqueueSpatialInputSnapshot) are distinct APIs — see docs/API/UsingXRImmersionMode.md, docs/API/UsingSpatialInput.md, docs/API/VisionProRenderingProfile.md |
Build-system gating mirrors this: VISIONOS_AVAILABLE / AR_AVAILABLE compile flags (Package.swift) gate CompositorServices/ARKit-only code. Never assume ARKit or CompositorServices symbols are available outside their #if guards.
Read ENGINEERING_PRINCIPLES.md (mirrored at docs/Contributor/EngineeringPrinciples.md) for the project's ten governing principles — reliability first, fail gracefully with diagnostics, keep the engine always buildable, favor simple architecture over speculative abstraction, protect public API compatibility, measure before optimizing, etc. The conventions below are the concrete application of those principles to day-to-day code changes.
- Swift 6, strict concurrency (
swiftLanguageMode(.v6)). Respect@MainActor/Sendableboundaries already present — don't silence concurrency errors by adding@unchecked Sendableor removing actor isolation. - Follow the free-function,
EntityID-keyed API style for anything exposed to application code — do not wrap engine state in new classes "for convenience." - Format/lint with
swiftformat(pinned version0.60.1,--swiftversion 5.8):make format/make lint. Run before considering engine-side work done. - New engine systems require unit tests and a how-to markdown doc under
docs/API/(perdocs/Contributor/ContributionGuidelines.md); small fixes are exempt. - Optional native/third-party dependencies (e.g. a physics backend) belong in a separate plugin repo, never added to this package's
Package.swift— see the extension architecture in §3 anddocs/Extensions/PluginArchitecture.md. - One feature/fix per PR; meaningful commit messages (there is a commit-message-prefix hook).
- Editing a
.metalfile and only runningswift build.swift buildnever invokes the Metal compiler; the engine ships prebuilt.metallibresources. You must rerun./buildkernels.shafter any shader change, or the app/tests silently run the stale shader binary (§8). - Reaching into Mesh/Material internals instead of using accessor functions. Setters like
updateMaterialColordo bookkeeping (static-batch refresh) that direct field mutation skips. - Assuming RealityKit/SceneKit/Unity-style APIs exist. They generally don't. Grep the actual source or an existing demo before using an API you haven't verified in this repo.
- Writing a custom render/update loop on macOS/iOS. The engine's
UntoldRenderer/MTKViewDelegatealready ownsdraw(in:); hook per-frame logic throughsetupCallbacks/onUpdate(_:)instead. - Treating visionOS code as a variant of the macOS/iOS path.
UntoldEngineXRis a structurally different runtime (noMTKView, its own frame loop) — don't port MTKView-based patterns there uncritically. - Registering a new component without a cleanup handler.
destroyEntityrelies on every component type having a registered cleanup function; skipping this leaks state or trips a debug assertion. - Mixing
EngineExtensionandRenderExtensionregistration for the same plugin type, or reaching for either when a simpleregisterCustomSystem(_:)closure would do for app-local code. - Touching SwiftUI/UIKit state from
UntoldComponentKitlifecycle callbacks (onUpdate,onFixedUpdate, etc.) — they run on the engine's simulation thread (main thread on macOS/iOS, the compositor render thread on visionOS), not necessarily the UI thread. - Hand-authoring or hand-editing
.untold/.untoldgsfiles. These are generated by the exporter/cook pipeline; author source assets in Blender and export instead.
Run from the repository root (verified against Makefile, buildkernels.sh, Package.swift):
swift build # build the engine package
sh ./buildkernels.sh # rebuild all platform .metallibs — REQUIRED after any .metal edit
swift test # all tests
swift test --filter UntoldEngineTests # unit tests only (make testcore)
swift test --parallel --num-workers 4 --filter UntoldEngineRenderTests # image-diff render tests (make testrenderer; needs opencv-python-headless + scikit-image)
swift run StarterDemo # run a demo (macOS only); also ShowcaseDemo, LargeSceneStreamingDemo, InteractionGameplayDemo, RenderingQualityDemo, LightingDemo, ExporterPipelineDemo, Sandbox
make lint / make format # swiftformat check / apply
make testrenderer # tests engine renderer
make testcore # tests engine coreNotes:
- Two render-test classes (
AsyncMeshLoadingTest,AssetLoadingGateRenderingTests) hang under parallel workers — run them withmake testrenderer-async(serial,--disable-swift-testing), matching CI. - CLI tool: install with
./scripts/install-untoldengine-create.sh(installs to/usr/local/bin/untoldengine). The installed CLI runs its own compiled copy, not this repo's live source — if you editTools/UntoldEngineCLI, reinstall before testing CLI behavior. - pre-commit hooks run
testexporter/testcore/testrendererandswiftformat --linton staged files; don't bypass with--no-verifyunless the user explicitly asks.
docs/API/— one file per subsystem (UsingTransformSystem.md,UsingMaterials.md,UsingLightingSystem.md,UsingPhysicsSystem.md,UsingScriptingSystem.md,UsingCodeComponents.md, etc.) — the primary source for API usage beyond this file.docs/Architecture/— deep-dive design docs (render graph, asset format, streaming, batching, LOD, animation pose pipeline).docs/Tutorials/,docs/Onboarding/— step-by-step walkthroughs for specific demos and first-project setup.docs/Extensions/— plugin/extension authoring guides.Sources/Demos/*— the most reliable "does this actually work" reference; prefer reading a demo over inferring usage from a doc alone..claude/skills/— task-specific Claude Code skills for application developers:untold-entity-scene(scene/entity/material/light/camera work),untold-new-project(scaffolding a new project with the CLI),untold-asset-pipeline(Blender →.untold/.untoldgsexport). These load automatically when relevant; read one directly if you want the condensed, example-grounded version of a section above.Examples/RenderingExtensions/,Examples/CodeComponents/— standalone worked examples of the extension and code-component systems.
- Prefer existing public engine APIs over implementing duplicate functionality.
- Never invent engine classes, methods, components, or configuration options. If unsure an API exists, grep
Sources/UntoldEngineand checkdocs/API/before using it. - Inspect existing source or a working demo before using an unfamiliar API.
- Follow the engine's free-function/
EntityIDarchitecture and the conventions in §6. - Swift for engine/application code, Metal for GPU work — unless a subsystem already requires something else (e.g. Python for exporter tooling).
- Respect the platform-specific lifecycle in §5; don't port macOS/iOS render-loop patterns to visionOS or vice versa.
- Respect concurrency annotations, GPU/render-graph synchronization, and component/resource lifetime rules in §7.
- Avoid unnecessary architectural changes when implementing an application feature — extend, don't restructure.
- Prefer small, verifiable changes over large speculative implementations.
- Clearly distinguish verified engine functionality (found in source/docs) from proposed or unsupported features in any explanation you give the user.
- Validate changes using the commands in §8 whenever possible, including rebuilding shaders after any
.metaledit.