Swift 3D Engine
A Swift 3D engine for Linux first, and Apple platforms: a SceneKit-style scene graph and a RealityKit-style ECS over one data-oriented core, with asset codecs (3DMF, OBJ, glTF, Collada, SCN, USD), Box3D physics and an SDL3 host.
scene-viewer scene-convert SceneSCN (SceneKit) SceneReality (RealityKit)
| | | |
+-------+------+-------+--------+----------+-----------+----------+
| | | |
SceneSDL SceneFormats SceneUSD ScenePhysics, SceneRealityPhysics
(SDL3, GL) (3DMF, …) (USD/USDZ) (Box3D)
| | | |
| +-------+--------+ |
| SceneGraph |
| | |
+----------------------+-------------------------------+
SceneCore
SceneCore is the shared foundation: math, the EntityStore both APIs keep their state in, mesh and material
descriptors every renderer and codec reads, and the render backend protocols. SceneGraph (nodes, as SceneKit) and
SceneReality (entities and systems, as RealityKit) are two surfaces over it, so they share assets and can render
side by side; SceneReality reads files and makes its primitives through SceneGraph. Codecs read files into scenes, physics moves EntityStore transforms, and backends draw
SceneCore frames.
| Module | Contents |
|---|---|
SceneCore |
Matrix4x4, Quaternion, Transform, bounds, rays and frusta; polygon Triangulation with holes; the sparse-set EntityStore; MeshBuffer, MaterialDescriptor, light and camera descriptors; the RenderBackend and FrameCommandBuffer protocols |
SceneGraph |
Scene, Node, Geometry and the built-in primitives, QuadricSurface (QuickDraw 3D's ellipsoids, cones, cylinders, disks and tori), NURBSPatch and NURBSCurve, Material, Light, Camera, Action, Transaction, SceneRenderer, @NodeBuilder |
SceneReality |
RealityKit's API over the EntityStore: Entity and its components, ModelEntity, AnchorEntity, lights and cameras, Systems and EntityQuery, scene events, MeshResource (generated or from MeshDescriptors), SimpleMaterial, UnlitMaterial, PhysicallyBasedMaterial and CustomMaterial (GLSL), TextureResource, animations and their playback controllers, ParticleEmitterComponent, loading entities and their animations from USD and the formats above, and ARView drawing through any backend, with GLSL post-processing; checked against Apple's framework |
SceneRealityPhysics |
RealityKit's physics over Box3D, in its own module so SceneReality needs no Box3D: CollisionComponent and ShapeResource, PhysicsBodyComponent, PhysicsMotionComponent, PhysicsMaterialResource, collision groups and filters, CollisionEvents, Scene.raycast and convexCast, ARView.hitTest, and the character controller; checked against Apple's framework |
SceneRealityText |
RealityKit's MeshResource.generateText, in its own module so SceneReality needs no font libraries: glyph outlines from FreeType (over PureSwift/swift-freetype), fonts found by PureSwift/FontConfig or CoreText, set in lines and frames and extruded; checked against Apple's framework |
RealityKit |
SceneReality, SceneRealityPhysics and SceneRealityText, re-exported, on platforms without Apple's RealityKit. Not built on a Mac, where import RealityKit is Apple's framework and the RealityKit product is those three |
SceneFormats |
ThreeDMFDecoder: QuickDraw 3D metafiles, binary (either byte order, parsed with apple/swift-binary-parsing) and text, ported from Quesa — geometry, attributes, textures, lights, cameras, view hints and styles; WavefrontOBJDecoder and MTLDecoder: Wavefront OBJ and material libraries; PNGDecoder (over PureSwift/swift-png) and TextureImageLoader for PNG/JPEG textures via PureSwift/swift-jpeg; GLTFDecoder for glTF/GLB with animation and CPU skinning, ColladaDecoder, SCNArchiveDecoder, and SceneAssetFile for local resources and dependency tracking |
SceneUSD |
Pure-Swift USDA and USDC (Crate) reading and writing, USDZ I/O, and composition of sublayers, inherits, variants, references, payloads and specializes, with instancing, layer offsets and value clips; scene import with time-sampled animation, UsdSkel skinning, every UsdLux light type and display colors; static triangle export |
SceneModel |
(in progress) A Swift-first Model I/O: assets, meshes, materials, textures and animation with Model I/O's conventions, the engine under Perry's Model I/O provider. So far: the data model, mesh generators and operations, OBJ, PLY, STL and USD import and export, textures, skeletons and animation, baking, voxels, light probes and photometric lights, each checked against recorded Model I/O output. Like everything it links, it imports FoundationEssentials at most; see the plan |
SceneModelGraph |
(in progress) Conversions between SceneModel assets and SceneGraph scenes |
SceneUSDKit |
Apple's USDKit API (USDLayer, USDStage, USDPrim, USDToken, USDValue) on SceneUSD, checked against Apple's framework; values and layers work (layers read USDA, Crate and USDZ, and write USDA and Crate), stages read, compose, author (with change notices), save, flatten and package as USDZ |
USDKit |
SceneUSDKit, re-exported, on platforms without Apple's USDKit; empty on Apple platforms, where import USDKit is Apple's framework |
ScenePhysics |
PhysicsWorld, PhysicsBody, PhysicsShape (spheres, capsules, boxes, convex hulls, triangle meshes) and joints (hinge, slider, ball and socket, distance, weld) over Box3D; PhysicsBodyComponent keeps EntityStore transforms in step, and Scene.physicsWorld and Node.makePhysicsBody give SceneGraph SceneKit's physics; on Linux and macOS |
SceneSCN |
SceneKit's API on SceneGraph: SCNScene (including reading every format above), SCNNode, SCNGeometry with sources, elements and the built-in shapes, SCNMaterial, SCNLight, SCNCamera, SCNAnimationPlayer, SceneKit's vector and matrix types and functions, and simd's names where there is no simd module |
SceneSCNPhysics |
SceneKit's physics (SCNPhysicsBody, SCNPhysicsShape, SCNPhysicsWorld, contacts, ray tests and joints) on ScenePhysics; empty where ScenePhysics is |
SceneKit |
SceneSCN, re-exported, on platforms without Apple's SceneKit. Not built on a Mac, where import SceneKit is Apple's framework and the SceneKit product is SceneSCN |
SceneQuickDraw3D |
A Swift-first QuickDraw 3D: Apple's object model (shared objects with reference counts and edit indices, shapes, every geometry type, attribute sets, transforms, styles, shaders, textures and groups), its row-vector math checked against QuickDraw 3D 1.6's own output, and views with Quesa's cameras, lights, state stack and submit loop, drawn by an interactive or wireframe renderer through any RenderBackend, and picked by window points, rectangles and world rays, down to a mesh's faces, edges and vertices; Q3Metafile reads and writes its objects as binary or text 3DMF, and Q3File reads them object by object from memory or path storage and writes a view's writing loop, view hints included. Its Error Manager keeps the errors, warnings and notices posted and tells registered handlers, and its class tree takes custom classes, elements and attributes, which 3DMF carries by name and attribute sets and views pass down. libQuickDraw3D exports QuickDraw 3D 1.6's C API over it; see the plan |
SceneSDL |
SDLRenderBackend: an SDL3 window with an OpenGL 3.3 Core / ES 3.0 context, and OpenGLRenderer, which draws SceneCore frames in any current GL context |
Swift 6 on Linux (developed on Debian 13) or macOS 15 and later. System libraries:
-
SDL3 for
SceneSDLandscene-viewer:apt install libsdl3-dev, orbrew install sdl3. -
zlib for swift-png's default system-zlib trait:
apt install zlib1g-dev. -
FreeType and FontConfig for
SceneRealityText:apt install libfreetype-dev libfontconfig-dev, orbrew install freetype fontconfig. -
Box3D for
ScenePhysics, built with CMake and found by pkg-config. Without root, install it in your home:git clone https://github.com/erincatto/box3d.git cmake -S box3d -B box3d/build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=$HOME/.local \ -DBOX3D_SAMPLES=OFF -DBOX3D_UNIT_TESTS=OFF -DCMAKE_POSITION_INDEPENDENT_CODE=ON cmake --build box3d/build -j && cmake --install box3d/build export PKG_CONFIG_PATH=$HOME/.local/lib/pkgconfig
On macOS the same CMake build works (
brew install cmake pkg-config); on other Apple platformsScenePhysicsdoesn't link Box3D yet, and builds empty.
swift build
swift testConventions: right-handed, y up, cameras and lights look down -z, angles in radians (camera field of view and spot
angles in degrees, as SceneKit's). Matrices are column-major acting on column vectors; Matrix4x4(quickDraw3D:)
reads QuickDraw 3D's row-vector matrices.
import SceneGraph
let scene = Scene {
Node(name: "camera").camera(Camera()).positioned(at: [0, 1.5, 4]).looking(at: .zero)
Node(name: "box", geometry: .box())
.running(.repeatForever(.rotate(by: 2 * .pi, around: [0, 1, 0], duration: .seconds(4))))
}
let renderer = SceneRenderer(backend: HeadlessRenderBackend(), scene: scene)
renderer.update(by: .milliseconds(16))
try renderer.render(target: RenderTargetDescriptor(width: 1280, height: 720))scene-viewer [file] opens .3dmf, .obj, .gltf, .glb, .dae, .scn, or standalone static
USDA (.usda/.usd, including inside .usdz), or a rotating textured demo without a file.
USD materials are Preview Surface constants and textures, with what SceneGraph can't represent left out;
--geometry-only discards shading.
Source assets, external buffers, material libraries, and texture files are checked for changes every half second.
A successful reload preserves the viewing camera and pause state. A failed reload retains the last valid scene and
reports the error in the console (and inspector status); saving a corrected file retries it.
| Control | Action |
|---|---|
| Drag / scroll | Orbit / zoom; drag looks around in fly mode |
| Tab | Toggle orbit and fly modes |
| W A S D / Q E | Move forward, left, back, right / down and up in fly mode |
| F2 / N | Toggle wireframe / vertex normals |
| H | Show or hide the hierarchy inspector |
| Up / Down | Select a node in the hierarchy |
| V / F | Toggle selected node visibility / frame its hierarchy bounds |
| Space / R / Escape | Pause animation / reset camera / quit |
The inspector shows node hierarchy, geometry/light/camera type, visibility, vertex count, child count and position. Normals follow animated and skinned geometry. Wireframe uses polygon mode on desktop GL and indexed lines on GLES; the inspector remains filled and readable in either mode.
--snapshot <path.bmp> writes one frame, --frames <n> quits after n frames, --view <yaw>,<pitch> sets angles in
degrees, and --es requests OpenGL ES 3.0. --inspector, --normals, and --wireframe enable overlays at launch,
including in snapshots. SDL3 is required: brew install sdl3 on macOS or apt install libsdl3-dev on Debian/Ubuntu.
swift run scene-viewer model.glb --inspector
swift run scene-viewer model.dae --normals --snapshot model.bmp
swift run scene-viewer --geometry-only model.usdz --inspectorMaterials take GLSL snippets at SceneKit's four entry points, with the same pragmas and variable names. Metal's
type names (float4, float3x3, half, …) and saturate are defined, and scn_frame (time, sinTime,
cosTime, the view and projection transforms) and scn_node (modelTransform, normalTransform,
modelViewProjectionTransform, …) are set as SceneKit's, so most SCNShadable snippets run unchanged:
material.shaderModifiers[.surface] = """
#pragma arguments
vec4 tint;
#pragma body
_surface.diffuse *= tint;
"""
material.shaderUniforms["tint"] = .vector4(SIMD4(1, 0.5, 0.5, 1))| Entry point | Reads and writes |
|---|---|
.geometry |
_geometry.position, normal, tangent, color, texcoords[0...1], in model space |
.surface |
_surface.diffuse, ambient, specular, emission (linear vec4), normal, position, view, shininess, metalness, roughness, ambientOcclusion, diffuseTexcoord |
.lightingModel |
_light.direction (toward the light) and intensity, adding to _lightingContribution.diffuse and specular; runs once per non-ambient light in place of the built-in model |
.fragment |
_output.color, linear, before sRGB encoding |
#pragma arguments lines become uniforms set from shaderUniforms (int, float, vectors, 4×4 matrix); code before
#pragma body is global declarations, and a snippet without pragmas is all body. #pragma transparent makes a
legacy material blend; #pragma opaque ignores alpha. Unlike SceneKit, positions and normals are in world space,
and sampler arguments are not supported. Each distinct set of snippets compiles once into its own program;
OpenGLRenderer.prepareShaderModifiers(_:) compiles ahead of time and throws the compiler log, while a snippet that
fails at draw time skips that draw and is kept in shaderModifierErrors. Values persist per program, so every
material sharing snippets should set all of their arguments. GLB, USD and 3DMF exporters reject shader modifiers.
import SceneKit builds SceneKit code on Linux, Windows and Android: the SceneKit module re-exports SceneSCN,
whose classes are SceneKit's faces of SceneGraph's. Each holds its SceneGraph object (sceneGraphScene,
sceneGraphNode, sceneGraphGeometry, sceneGraphMaterial, sceneGraphLight, sceneGraphCamera) and keeps it in
step, so SceneRenderer draws what SceneKit code builds:
import SceneKit
import SceneGraph
let scene = try SCNScene(url: modelURL)
let box = SCNNode(geometry: SCNBox(width: 1, height: 1, length: 1, chamferRadius: 0))
box.geometry?.firstMaterial?.diffuse.contents = SIMD4<Float>(1, 0.5, 0, 1)
scene.rootNode.addChildNode(box)
let renderer = SceneRenderer(backend: backend, scene: scene.sceneGraphScene)contents takes numbers, SIMD4<Float> sRGB colours, ImageBuffers, file names and URLs; conform a platform's
colour and image types to SCNColorContents and SCNImageContents to pass them as SceneKit takes UIColor and
CGImage. Shader modifiers may use Metal's type names (float4) and SceneKit's scn_frame and scn_node buffers.
SCNScene(url:) gives a file's top-level nodes its units and up axis, and plays a USD stage's animation through an
SCNAnimationPlayer on the first of them.
SCNParticleSystem emits from the nodes it's added to through SceneGraph's ParticleSystem, which the scene's
updates simulate and SceneRenderer draws as camera-facing quads, one streamed draw per emitter. Property
controllers follow a CAKeyframeAnimation's or CABasicAnimation's values over each particle's life, for opacity,
size, colour and angle; where there is no QuartzCore, SceneSCN has those classes. Particles are drawn unlit, colour
variation strays per channel rather than in hue, and physics, image sequences, events and modifiers aren't supported.
SCNRenderer and SCNView draw offscreen with OpenGL through SceneSDL's SDLOffscreenRenderBackend. That backend
draws into a framebuffer the size of the frame, multisampled as antialiasingMode asks, and reads it back. Without
UIKit or AppKit, SCNView isn't a view class: it holds the view's frame, scale and SceneKit's settings, and the UI
toolkit hosting it calls renderFrame(atTime:) once per display refresh while needsFrame is true. That call runs
SceneKit's frame loop and returns the frame's pixels: the SCNSceneRendererDelegate updates, the scene moves on
(its actions, animation players, constraints, particles and physics, as in SceneKit, and its scene time while
isPlaying), then it draws. The host also handles gestures. SCNRenderer(backend:) draws with any other
backend.
hitTest(_:options:), projectPoint and unprojectPoint work on a view's bounds, or on the last frame an
SCNRenderer drew, in points from the top left on every platform, with depths from 0 at the near plane to 1 at the
far one. Hit tests meet triangles in the node's own space, by SceneKit's options: search mode, back faces (except on
double-sided materials), bounding boxes only, hidden nodes, categories, a root node, and the camera's depth range.
Results give the node, element, triangle, local and world points and normals, and texture coordinates.
SCNNode.hitTestWithSegment(from:to:options:) searches a node and those below it, and isNode(_:insideFrustumOf:) and
nodesInsideFrustum(of:) test bounds against the camera's frustum. Skinned meshes are hit in their rest pose.
SCNActions run on nodes through SceneGraph's actions, and constraints (SCNLookAtConstraint,
SCNBillboardConstraint, SCNDistanceConstraint, SCNAccelerationConstraint, SCNTransformConstraint) through its
constraints, so the scene's updates run a node's actions, then its constraints. Blocks get the SCNNode. Inside an
SCNTransaction with a duration, setting a node's position, orientation, rotation, Euler angles, scale or opacity
animates it there linearly; the node reads back the value set, and the transaction's completion runs once its
animations end. An action's timingFunction and a transaction's animationTimingFunction are kept but not used, and
transforms set as a matrix, materials, lights and cameras change at once.
SceneKit's physics is in a module of its own, SceneSCNPhysics, so SceneKit's API doesn't need Box3D: with
import SceneSCNPhysics, SCNNode.physicsBody, SCNPhysicsShape (from geometry, a node's tree, or shapes placed by
transforms; boxes, spheres, capsules, floors, convex hulls and, for static bodies, concave meshes), SCNPhysicsWorld
(gravity, speed, time step, contact delegate, ray tests by segment) and its hinge, slider and ball-socket joints run on
ScenePhysics. A scene with a body gets its world at its first update. The world steps after actions and
constraints: a kinematic body follows its node, pushing what it meets; a static or dynamic body whose node was moved
jumps there; dynamic bodies move their nodes. Box3D filters collisions both ways, so two bodies collide only if each
one's collisionBitMask takes the other's category, and contacts are reported only between bodies that collide.
didUpdate, fields, rolling friction, charge, set moments of inertia, velocity factors and vehicles aren't there yet.
What draws differently from SceneKit, for now: lightingEnvironment lights as an ambient light of its mean colour;
multiply tints the diffuse colour before lighting; animations start and stop without blending; box chamfers, fog,
shadows and reflections are kept but not drawn; scene time doesn't loop or go back. The replicator, slider, IK
and avoid-occluder constraints are not there yet.
import RealityKit builds RealityKit code on Linux, Windows and Android: the RealityKit module re-exports
SceneReality, which keeps each entity's state in SceneCore's EntityStore. A detached entity has a store of its
own, and adding it to a parent moves its subtree into the parent's. Entity, Scene, systems and ARView are
@MainActor, as in Apple's current SDK:
import RealityKit
struct SpinComponent: Component { var speed: Float }
struct SpinSystem: System {
static let query = EntityQuery(where: .has(SpinComponent.self))
init(scene: Scene) {}
func update(context: SceneUpdateContext) {
for entity in context.entities(matching: Self.query, updatingSystemWhen: .rendering) {
let speed = entity.components[SpinComponent.self]!.speed
entity.orientation *= simd_quatf(angle: speed * Float(context.deltaTime), axis: [0, 1, 0])
}
}
}
SpinComponent.registerComponent()
SpinSystem.registerSystem()
let view = ARView(frame: CGRect(x: 0, y: 0, width: 640, height: 480))
let box = ModelEntity(mesh: .generateBox(size: 0.2), materials: [SimpleMaterial(color: .blue, isMetallic: false)])
box.components.set(SpinComponent(speed: 1))
let anchor = AnchorEntity(world: .zero)
anchor.addChild(box)
view.scene.addAnchor(anchor)
let pixels = view.renderFrame(atTime: 0)Where there is no simd module, simd_quatf and float4x4 are SceneCore's Quaternion and Matrix4x4. Where there
is no AppKit or UIKit, Material.Color is a small RGBA type with the system's named colours.
Systems run in their dependencies' order, then the scene posts SceneEvents.Update. Entities post DidAddEntity
and WillRemoveEntity as they join and leave a scene, and subscribe(to:on:) can scope any event to one entity.
Entity(contentsOf:) and Entity(named:) read USD and every format SceneAssetFile reads into named entities:
meshes become ModelEntitys with physically based or unlit materials, and lights and cameras become their
components.
Animations play on entities in a scene, which moves them on before its systems run: move(to:relativeTo:duration:),
and playAnimation with FromToByAnimation, SampledAnimation, OrbitAnimation, AnimationGroup and
AnimationView definitions, or AnimationResource.sequence, group and repeat. They time as RealityKit's do, with
delays, speeds, trims, repeats (plain, autoreversing and cumulative) and Core Animation's timing curves. They animate
transforms and opacity, on the entity or on one a BindTarget path names. AnimationPlaybackController pauses,
resumes, seeks and stops them, and the scene posts AnimationEvents as they start, loop, complete and are stopped. A
USD stage's time samples and skinning, and each glTF animation, become availableAnimations of the file's entity,
played by posing the file's nodes as SceneUSD and SceneFormats play them and copying the poses onto the entities.
ARView isn't a view class, as with SCNView: the UI toolkit hosting it calls renderFrame(atTime:) once per display
refresh, which runs the scene's systems and draws. It draws offscreen with OpenGL through SceneSDL's
SDLOffscreenRenderBackend, or ARView(frame:backend:) draws with any other backend. Without a camera entity it
looks down -z from 2 m back along +z, as RealityKit's does. Translucent models draw after opaque ones, back to front.
Physics comes with SceneRealityPhysics, which import RealityKit brings in: each active entity with a
CollisionComponent or PhysicsBodyComponent gets a Box3D body when the scene next updates or is queried. Scenes
step their physics after animations and before systems, at most 1/60 s a step. Dynamic bodies move their entities,
and their PhysicsMotionComponents if they have one; kinematic bodies, and entities with collision shapes and no
body, follow their entities, pushing dynamic bodies aside; static ones stay put. Forces, torques and impulses wait
for the next step. The scene posts CollisionEvents.Began, Updated and Ended for entities that touch, triggers
included, with where they touch and how hard, and a subscription on either entity hears them. Touching materials mix
their friction and restitution by their average:
let floor = ModelEntity(mesh: .generatePlane(width: 10, depth: 10))
floor.components.set(CollisionComponent(shapes: [.generateBox(width: 10, height: 0.01, depth: 10)], isStatic: true))
let ball = ModelEntity(mesh: .generateSphere(radius: 0.1), collisionShape: .generateSphere(radius: 0.1), mass: 1)
ball.position.y = 2
let ground = AnchorEntity(world: .zero)
ground.addChild(floor)
ground.addChild(ball)
view.scene.addAnchor(ground)
let subscription = view.scene.subscribe(to: CollisionEvents.Began.self, on: ball) { event in
print("landed at", event.position)
}
let hits = view.scene.raycast(origin: [0, 5, 0], direction: [0, -1, 0])
let tapped = view.entity(at: CGPoint(x: 320, y: 240))Scene.raycast and convexCast find collision shapes along a ray or a swept shape, all, the nearest or any one, in
groups a mask picks. ARView.hitTest, entity(at:) and entities(at:) cast through a point in the view, measured
from its top left. moveCharacter(by:deltaTime:relativeTo:collisionHandler:) slides a character controller's
capsule along what it meets, telling which of its sides touched, and CharacterControllerStateComponent keeps its
velocity and whether it's on the ground.
CustomMaterial runs GLSL functions where RealityKit's runs Metal ones, through the OpenGL backends' shader
modifiers. A ShaderLibrary holds the GLSL, as an MTLLibrary holds Metal (ShaderLibrary.makeDefaultLibrary()
joins a bundle's .glsl files), and SurfaceShader(named:in:) and GeometryModifier(named:in:) name functions in
it, which take with them what they use from the library. A function sees RealityKit's parameters by RealityKit's
names, as fields where Metal has methods:
let library = ShaderLibrary(source: """
void sway(inout realitykit_geometry_parameters params) {
float height = params.geometry.model_position.y;
params.geometry.model_position_offset.x = sin(params.uniforms.time * 2.0 + height * 3.0) * 0.1 * height;
}
void tint(inout realitykit_surface_parameters params) {
params.surface.base_color *= params.uniforms.custom_parameter.rgb;
}
""")
var seaweed = try CustomMaterial(surfaceShader: .init(named: "tint", in: library),
geometryModifier: .init(named: "sway", in: library), lightingModel: .lit)
seaweed.custom.value = [0.2, 0.8, 0.3, 1]| Parameters | Fields |
|---|---|
params.uniforms |
time, custom_parameter, model_to_world, world_to_model, model_to_view, view_to_projection, projection_to_view |
params.geometry |
model_position, model_position_offset (what a geometry modifier moves a vertex by), world_position, view_direction, normal, tangent, uv0, uv1, color |
params.surface |
base_color, emissive_color, roughness, metallic, ambient_occlusion, specular, opacity, normal (in tangent space), clearcoat, clearcoat_roughness, each starting at the material's own |
params.material_constants |
base_color_tint, opacity_scale, roughness_scale, metallic_scale, emissive_color, specular_scale |
textures |
samplers: base_color, metallic, normal, ambient_occlusion, emissive_color, custom |
ARView.renderCallbacks.postProcess is a GLSL pass over each finished frame, where RealityKit's is a closure that
encodes Metal work. It defines vec4 postProcess(vec2 uv) and reads the frame from u_sourceColor and
u_sourceDepth, with u_projection, u_inverseProjection, u_time, u_resolution, and uniforms of its own under
#pragma arguments:
view.renderCallbacks.postProcess = ARView.PostProcessEffect(source: """
#pragma arguments
vec3 fogColor;
#pragma body
vec4 postProcess(vec2 uv) {
float depth = texture(u_sourceDepth, uv).r;
vec4 point = u_inverseProjection * vec4(uv * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);
float fog = 1.0 - exp(-0.25 * (depth < 1.0 ? -point.z / point.w : 100.0));
return vec4(mix(texture(u_sourceColor, uv).rgb, fogColor, fog), 1.0);
}
""", uniforms: ["fogColor": .vector3([0.1, 0.25, 0.45])])ParticleEmitterComponent has RealityKit's defaults and presets, burst() and restart(). Its particles are born
from the emitter's shape at its rate and timing, then speed, slow, spin, grow or shrink, change colour and fade over
their lives, simulated by SceneGraph's ParticleSystem after the scene's systems run. They're drawn unlit, facing
the camera, among the translucent parts.
MeshResource.generateText comes with SceneRealityText, which import RealityKit brings in. It reads the font's
glyph outlines with FreeType, sets them in lines (at newlines, and by lineBreakMode within a container frame, with
the font's kerning and the alignment) and extrudes them extrusionDepth deep about z = 0, as a front, a back and
walls. Without a frame the text's bottom left is at the origin; with one, its first line is at the frame's top. A
font's size is in points taken as metres; MeshResource.Font is NSFont or UIFont where there's AppKit or UIKit,
and elsewhere a FontConfig pattern and a size, with systemFont(ofSize:) as sans-serif.
Tools/realitykit-oracle runs the scenarios in Tests/SceneRealityTests/Scenarios against Apple's RealityKit on a
Mac and records what they observe; the tests compare SceneReality with that on every platform. Covered: transforms
and conversions between entities, look(at:), generated mesh bounds, visualBounds, component and material
defaults, how animation definitions and resources time, collision shapes' bounds and mass properties, physics
defaults, raycasts, rays through a view and its hit tests, particle emitter defaults and presets, and how generated
text is laid out.
What differs from RealityKit, for now:
- There's no AR. Only
.worldanchors place their entities; other targets are kept, and their entities stay at the origin. - Image-based lighting lights as an ambient and a directional light, scaled by its intensity exponent. Skyboxes are kept but not drawn.
- Several things are kept but not drawn: box corner radii, clearcoat, and
OcclusionMaterial. - An infinite far plane, the default, is drawn at 10 km.
- Animations don't blend: a new one replaces the others at once, and transition and blend-out durations, blend layers and separate animated values are kept but not used. They write straight into components, so a value stays where an animation left it. They animate transforms and opacity; joint transforms, parameters, material values and blend shape weights are not animated, nor are skeletal poses outside loaded files.
- Box3D reports no touches between two bodies that don't move by the simulation (static, kinematic, or collision
shapes without a body), so
PhysicsSimulationComponent's collision options are kept but not used, as are its solver iterations. - Bodies can't lock translation, nor rotation about single axes: rotation is held only when all three are locked. Static and dynamic friction are one, the dynamic. Static mesh shapes collide only on static bodies.
convexCastsweeps its shape without turning it.- Characters don't climb steps, and aren't bodies: bodies don't collide with them. Collision shapes scale with their entities only as near as a box, sphere or capsule can.
- On a Mac, Apple's
ARViewmeasures points from its bottom left, asNSViewdoes; SceneReality's measure from the top left everywhere, as on iOS. - Custom materials and post-processing are GLSL rather than Metal, and only the OpenGL backends run them.
prepareWithDeviceis never called. A custom material's texture coordinate transforms and clearcoat are kept, not used. - Particles' spawned emitters, mass, noise, attraction, vortex, image sequences, lighting and timing variations are kept but not simulated. A random colour varies each channel between its two, and the presets show a soft dot where Apple's show its images. Particles don't write depth, so a post-process reading depth sees what's behind them.
- Text is kerned by the font's
kerntable, without shaping, and each curve is cut into 6 lines.
All readers provide synchronous decodeScene(_:) and the async SceneAssetDecoder.decode(_:) API, with typed
SceneFormatError failures. Local files and their relative resources can be loaded together:
import Foundation
import SceneFormats
let asset = SceneAssetFile(url: URL(fileURLWithPath: "model.gltf"))
let scene = try asset.load()
// asset.dependencies includes buffers and images loaded by the decoder.For custom storage, pass a SceneResourceLoader closure to GLTFDecoder, ColladaDecoder, or SCNArchiveDecoder.
The file loader resolves local file URLs only; decoder closures can implement other storage policies.
| Reader | Implemented |
|---|---|
| OBJ / MTL | Streaming line parsing, indexed faces and triangulation, normals, UVs, materials and texture paths |
| glTF 2.0 / GLB | JSON and binary containers, external/data-URI buffers, interleaved and sparse accessors, normalized integers, matrix padding, all core primitive modes, hierarchy/TRS, perspective/orthographic cameras, metallic-roughness materials, PNG/JPEG images, samplers, UV0/UV1, normal/occlusion/emissive maps, opaque/mask/blend alpha |
| glTF animation | STEP, LINEAR and CUBICSPLINE channels; translation, rotation, scale and morph weights; inverse bind matrices and CPU skinning with four joint influences per vertex |
| Collada | XML DOM, namespaces, unit/up-axis conversion, ordered matrix/TRS/look-at transforms, node instances, indexed mesh inputs, triangles/strips/fans/polygons/polylist/lines, profile_COMMON materials and textures, lights and cameras |
| SCN | Binary plist and NSKeyedArchiver/SCNKeyedArchiver UID resolution without instantiating archived classes; nodes, mesh sources/elements, common procedural shapes, color/scalar/path-texture materials, lights and cameras |
The first glTF animation plays automatically. Retrieve GLTFSceneRuntime from scene.systems to select a clip via
animationIndex, seek with time, change speed, or disable looping. Setting animationIndex = nil retains the
pose while skinning continues; scene.isPaused pauses updates. CPU skinning prioritizes portability over large-rig
throughput. The GL renderer uses approximate metallic-roughness lighting; environment IBL belongs to Phase 5.
The readers are bounded implementations, not complete replacements for every vendor extension: required glTF
extensions other than KHR_materials_unlit, KHR_materials_emissive_strength, KHR_texture_transform and KHR_lights_punctual (including compressed geometry), additional joint sets and texture channels beyond UV1 are rejected.
Collada controllers, polygon holes and skew transforms are rejected; Collada animation is not imported. SCN
skinners/morphers, custom geometry classes, embedded platform image objects, constraints, actions and effects are
not reconstructed. SCN procedural tessellation uses SceneGraph defaults. The retained transform representation
uses translation/rotation/scale, so arbitrary shear is not preserved. Unsupported essential geometry features
produce errors instead of executing archived code. Vulkan remains follow-on work.
PNG and JPEG decoding are pure Swift. The JPEG dependency uses PureSwift/swift-jpeg, pinned before its Span API
introduced a macOS 26 deployment requirement, retaining this package's macOS 15 minimum.
Tests cover accessor layouts and malformed references, GLB truncation, skinning and cubic morph animation, Collada coordinate conversion, SceneKit-generated archive fixtures, JPEG decoding, GPU alpha/texture sampling, inspector commands, orbit framing, and dependency edits/deletion/recovery. OpenGL tests require a display; physics tests run on Linux. The desktop viewer and snapshot path have been checked on macOS; GLES/Linux require validation there.
scene-convert loads local 3DMF, OBJ/MTL, glTF/GLB, Collada, SCN and static USDA/USDZ assets through
SceneAssetFile, including their supported external resources:
swift run scene-convert model.obj model.glb
swift run scene-convert scene.scn scene.glb
swift run scene-convert --aspect-ratio 1.777778 scene.scn widescreen.glb
swift run scene-convert --geometry-only scene.scn meshes.glb
swift run scene-convert model.obj model.3dmf
swift run scene-convert --geometry-only model.usdz model.glb
swift run scene-convert --geometry-only model.3dmf model.usdz
swift run scene-convert --geometry-only model.dae model.usda
swift run scene-convert colored.obj colored.usdzGLB export captures the current visible pose, hierarchy (including pivots), names, mesh streams,
submeshes, opacity and materials. PNG/JPEG textures are embedded as lossless PNG images using
PureSwift/swift-png. Supported inputs include UV0/UV1, normal/occlusion/emissive maps, packed shared
metallic-roughness maps, samplers, alpha modes, PBR factors and KHR_materials_unlit.
Independent scale/rotation/offset on UV0 or UV1 uses KHR_texture_transform for diffuse, emission, normal,
occlusion and packed metallic/roughness maps, including negative and zero scales.
GLB output declares the extension required, since no fallback UV set is authored. Import honors
the extension's coordinate override and rotation in radians, applied after scale and before offset.
GLB export preserves rotations and reflections, including zero scales; shear and projective transforms are rejected.
HDR emission uses KHR_materials_emissive_strength: export normalizes the core emissive RGB
factor and stores its peak as strength; import restores HDR constants or texture multipliers.
This preserves HDR emission during USDZ-to-GLB conversion. Strength defaults to 1 and must be
finite and nonnegative; the extension cannot be combined with KHR_materials_unlit.
Legacy Phong/Blinn/Lambert materials are approximated as fully rough, nonmetallic PBR surfaces; their ambient and specular terms are not retained. Sampler anisotropy is not serialized.
Perspective and orthographic cameras and directional/point/spot lights are exported by default.
Cameras retain their names, transforms, clipping planes and projection, including infinite perspective
far planes. Horizontal-FOV and orthographic cameras need a fixed aspect ratio or an explicit
--aspect-ratio width/height number; vertical-FOV perspective cameras can follow the destination viewport.
Lights use KHR_lights_punctual.
The reader preserves color, strength, range and spot half angles, and the OpenGL backend applies
inverse-square distance falloff, a range cutoff and squared spot-cone falloff for imported lights.
Internal intensity is 1000 times glTF candela (point/spot) or lux (directional); legacy light export
maps its normalized strength (intensity / 1000) to those units. This is an approximation of legacy
lighting: its distance and spot falloff change to glTF's model on export. Existing SCN rendering
continues using the legacy falloff by default. The renderer still uses approximate PBR shading.
Ambient lights, nondefault temperature, shadow settings and custom attenuation have no supported
mapping and produce errors. --geometry-only explicitly omits all cameras and lights, and remains
necessary for 3DMF export of scenes containing them.
Animation tracks, physics and GLB backgrounds are not exported. Unsupported vertex streams, separate transparency maps, independent metallic/roughness textures, unsupported texture transforms/intensities, front-face culling, custom blend/depth state and unresolved textures produce errors. Hidden branches are omitted. Skin/morph meshes are exported at their current evaluated pose. Binary 3DMF output uses the stricter color-material subset described below.
USD export writes .usda, text .usd, or .usdz containing scene.usda. It preserves static
visible hierarchy, affine transforms (including pivots), triangle geometry, normals and UV0.
Constant materials are exported as Preview Surface shaders; USDZ embeds their textures, and .usda/.usd
write them beside the layer in <name>_textures/. Directional, point, spot and ambient lights become UsdLux
distant, sphere (shaped for a spot) and dome lights, with color temperature and shadows.
Like Xcode's xcrun scntool --convert … --format usda, scene-convert approximates what USD can't hold exactly:
cameras without an aspect ratio get a square aperture, point and spot lights lose a legacy falloff and attenuation
distances, textures of meshes without UV0 are dropped, and SCN textures that can't be read are skipped. --strict
refuses all of these instead. On the repository's SCN fixtures its geometry matches scntool's triangle for triangle;
unlike scntool it follows SCN reference nodes and exports lights as UsdLux lights. Materials differ by convention:
colors are linear, as UsdPreviewSurface defines them (scntool writes SceneKit's sRGB values), and SceneKit's
constant lighting becomes emission. Animation isn't exported (scntool's --append-animation). --geometry-only
still discards materials, cameras, lights, opacity and unsupported vertex streams; double-sided surfaces are retained.
Existing outputs are protected unless --force is supplied; the input cannot be overwritten.
Encoding completes before writing. New output publication requires a filesystem with hard-link
support; replacement uses an atomic write.
Library callers can use GLBEncoder().encodeScene(scene) or
SceneAssetConverter.convert(from: inputURL, to: outputURL).
Both APIs accept an optional cameraAspectRatio for viewport-dependent cameras.
GLB tests cover round trips, submeshes, texture pixels and sampling, unlit materials, invalid mesh
data, camera/light round trips, malformed light definitions, SCN conversion, and output preservation
after errors. GPU tests cover inverse-square light falloff, range and spot cutoffs alongside the
existing Apple SCN reference comparisons.
Metafile3D.encoded() serializes a parsed or edited object tree in its original text or binary
encoding (including little-endian binary files):
let metafile = try Metafile3D(inputBytes)
let outputBytes = try metafile.encoded()The writer preserves object payloads and hierarchy, including custom binary classes. Resolved references
are expanded inline; output uses normal mode without a table of contents, original labels, or offsets.
Binary payloads must retain their byte order. Text/binary payload conversion is not implemented;
incompatible payloads throw SceneFormatError.unsupported.
ThreeDMFEncoder exports a static Scene as text or binary 3DMF:
let outputBytes = try ThreeDMFEncoder().encodeScene(scene)
let binaryBytes = try ThreeDMFEncoder(encoding: .binary(.bigEndian)).encodeScene(scene)
// Use .binary(.littleEndian) for little-endian output.
// Also conforms to SceneAssetEncoder:
let asyncOutputBytes = try await ThreeDMFEncoder().encode(scene)Scene export supports triangle lists and strips, indexed or non-indexed, normals, UV channel zero, node names, transforms, visibility, and color-based Phong/Blinn, Lambert and unlit materials. Blinn maps to Phong. Submeshes become separate TriMeshes inside display groups, so reloading preserves world placement and material assignment rather than the exact original node count. Material transparency, specular color, shininess, emission and face culling are exported. Textures, PBR, lights, cameras, node opacity and unsupported vertex streams throw an error. Animation and physics are not serialized; the current node transforms are exported as a static snapshot. Binary export supports the same scene subset as text, with byte-order-aware floats and integers, padded UTF-8 names, and 8-, 16- or 32-bit TriMesh indices selected from the vertex count. General conversion of arbitrary metafile payloads remains unsupported.
Round-trip tests cover text and both binary byte orders, geometry, materials, textures, custom classes, and resolved references. With a Quesa checkout beside the package, tests also rewrite its sample models and decode the results.
SceneQuickDraw3D keeps QuickDraw 3D's API shape in Swift: objects are created, submitted to a view between
startRendering and endRendering, and released by dispose, whose reference counts follow Apple's rules.
import SceneQuickDraw3D
import SceneSDL
let backend = try SDLRenderBackend(title: "QuickDraw 3D", width: 640, height: 480) // After SDL's video starts
let context = Q3BackendDrawContext(backend: backend, width: 640, height: 480)
let view = Q3View(defaultsFor: context) // A view angle camera, ambient and directional lights
context.dispose()
let objects = try Q3Metafile.read(fileBytes) // Or make geometry: Q3Box(Q3BoxData()), Q3TriMesh(…)
let phong = Q3IlluminationShader(.phong) // Unlit until an illumination shader is submitted
try view.startRendering()
repeat {
try view.submit(phong)
for object in objects where object.isDrawable { try view.submit(object) }
} while try view.endRendering() == .retraverse
let written = try Q3Metafile.write(objects, encoding: .text)
// What's under a click, nearest first.
let pick = Q3WindowPointPick(point: Q3Point2D(x, y), data: Q3PickData(sort: .nearToFar, mask: [.object, .xyz, .distance]))
try view.startPicking(pick)
repeat {
for object in objects where object.isDrawable { try view.submit(object) }
} while try view.endPicking() == .retraverse
let nearest = pick.hits.first?.object
// A mesh's vertices, edges or faces instead, by the pick parts style.
let parts = Q3WindowPointPick(point: Q3Point2D(x, y), data: Q3PickData(mask: [.shapePart, .pickPart]))
try view.startPicking(parts)
repeat {
try view.submit(Q3Style(.pickParts(Q3PickParts([.face, .edge, .vertex]).rawValue)))
try view.submit(mesh)
} while try view.endPicking() == .retraverse
let vertex = (parts.hits.first?.shapePart as? Q3MeshVertexPart)?.vertexThe interactive renderer draws as Quesa's OpenGL renderer does: lights attenuate and spot lights fall off by its
terms, markers draw their bitmaps and pixmaps on top of the scene pixel for pixel, NURB patches are cut by their
trim loops, and fog fades surfaces by distance through a fragment shader modifier. Q3WireFrameRenderer draws the
same through the same backend, but unlit and with lines only, surfaces as the edges of their triangles.
Matrices act on row vectors, as QuickDraw 3D's do; Q3Matrix4x4.engineMatrix gives SceneCore's column-vector
matrix. Tests check the math against QuickDraw 3D 1.6's output from Quesa's math test, cameras against Quesa's
matrices, the submit and picking loops through the headless backend, 3DMF round trips in every encoding and, with
a Quesa checkout or the July 2009 ADC Reference Library beside the package, Quesa's sample models and Apple's sample
code models; with a display, they draw through SDL and OpenGL.
libQuickDraw3D is QuickDraw 3D 1.6's C API over SceneQuickDraw3D, for programs written against Apple's
headers. It exports every function they declare. So far the system, Error Manager, math, object, group,
storage and file functions are implemented, enough to read a 3DMF model's objects, and the attribute set,
geometry, transform, style, shader and texture functions, enough to build and change the shapes a game draws,
and the camera, light, draw context, renderer, view and pick functions, enough to set up a view, render, measure
and pick; the rest post kQ3ErrorUnimplemented. A view draws into a pixmap draw context's pixmap through SDL's
OpenGL, offscreen, for the program to put on screen as it likes, and into a Mac draw context's window through
QD3DHost.h's Q3Host_SetPortMethods, with which the program's own Toolbox gives its windows' pixels and is told
when each frame is drawn. CMake builds and installs it with its headers,
which a program includes as it included Apple's:
#include <QD3D.h>
#include <QD3DMath.h>
Q3Initialize();
TQ3Matrix4x4 rotation;
Q3Matrix4x4_SetRotate_XYZ(&rotation, kQ3Pi / 6, kQ3Pi / 5, kQ3Pi / 4);
Q3Exit();cmake -S . -B build -G Ninja && cmake --build build --target QuickDraw3D
cc game.c -I/usr/local/include/QuickDraw3D -lQuickDraw3DWith a Quesa checkout, Tools/quickdraw3d-abi/conformance/math-test.sh runs Quesa's math test against the library
and compares what it prints with QuickDraw 3D 1.6's own output.
The 3DMF reader, and SceneQuickDraw3D's math, cameras and view state, are ported from
Quesa, © 1999–2021 Quesa Developers, under the BSD 3-Clause License in
LICENSE-Quesa; libQuickDraw3D's headers are made from Quesa's.
SceneUSD.USDZArchive reads and writes the uncompressed ZIP container defined by the
OpenUSD USDZ specification. It is pure Swift,
uses no OpenUSD binaries or C++ interoperability, and is tested on macOS and Linux CI.
import SceneUSD
let archive = try USDZArchive(entries: [
.init(path: "root.usda", data: Array("#usda 1.0\ndef Xform \"World\" {}\n".utf8))
])
let bytes = try archive.encoded()
let loaded = try USDZArchive(bytes)
let root = loaded.defaultLayer
let layerBytes = loaded["root.usda"]?.dataEntry data uses ArraySlice<UInt8> views into the input archive; use each slice's startIndex
or iterate it instead of assuming zero-based indices. Lookup is by exact canonical relative path.
Physical entry order determines the optional default layer. Asset-only and empty packages are
supported. Encoding preserves member order and bytes, with fixed timestamps and 64-byte alignment;
ZIP comments and extra metadata are not preserved.
The reader validates local/central headers, member ranges, alignment, UTF-8/ASCII names and CRC-32. It rejects duplicate or unsafe paths, unsupported member extensions, compression, encryption, ZIP64, multi-disk archives, data descriptors, preambles, and directory/symlink entries. It never extracts files to disk. The checked-in fixture is independently generated with Python's ZIP writer.
USDStage parses standalone static USDA definitions from UTF-8 bytes or a package's default layer:
let stage = try USDStage(usda: Array("#usda 1.0\ndef Xform \"World\" {}\n".utf8))
let packagedStage = try USDStage(archive: loaded)
let world = stage.prim(at: "/World")
let definitions = stage.traverse()
let points = world?[property: "points"]?.valueThe stage retains prim and property order, declared type names, custom/variability qualifiers,
metadata, typed dictionaries, arrays, tuples, relationship targets, asset paths and value blocks.
USDValue.number preserves numeric spelling rather than converting integers through floating point.
apiSchemas lists (explicit, prepend or append) are normalized to their authored token order, and lists
from several layers or arcs are united, strongest first.
This is a syntax model: it does not validate schema-specific attribute types, apply schema defaults,
resolve assets or evaluate transforms. Traversal includes inactive authored definitions.
The current subset requires ASCII prim/property identifiers, supports UTF-8 strings and asset paths,
and limits combined hierarchy/value nesting to 32 levels. Inherits, specializes, general list
operations other than prepend/append/add on apiSchemas, references and payload, non-shading connections, time samples, triple-delimited asset paths and uncommon
string escapes throw errors. A mesh fixture serialized by OpenUSD 26.11, malformed input tests,
truncation tests and byte-mutation tests exercise the parser without a native USD dependency.
USDSceneDecoder converts that static subset into SceneGraph and can feed existing encoders:
let scene = try USDSceneDecoder(geometryOnly: true).decodeScene(stage)
let glb = try GLBEncoder().encodeScene(scene)
// decodeScene(bytes) also detects USDA or a USDZ package containing USDA.Import supports Xform/Scope hierarchies, static cameras and polygon meshes, including concave faces, hole
indices, handedness, double-sided surfaces, normals and primvars:st; implicit surfaces (Cube, Sphere,
Cylinder, Cone, Capsule, Plane and the _1 variants with equal capsule radii) become meshes along their axis,
and each instance of a PointInstancer a copy of its prototype, placed as OpenUSD places it (scale, orientation,
position; hidden ids left out). Polygons ear clipping can't take apart (non-planar ones) are fans. Vertex streams are expanded across
triangle corners to preserve normal/UV seams. Constant, uniform, vertex, varying and face-varying
interpolation are supported, along with indexed UVs; a primvar with the wrong number of values for its
interpolation is left out, as renderers leave it, and a role-less type (float3[] for color3f[]) reads as the
role's. Missing normals are generated per face. UVs are
converted to the engine's top-origin convention. primvars:displayColor and displayOpacity become a vertex
color stream, from the mesh or, when constant, from its nearest ancestor that authors them; other primvars
nothing reads are left out. Subdivision surfaces (catmullClark, loop) import as their control cage with
smooth normals (each point's area-weighted face normals, authored normals ignored as USD specifies) and are not
refined; bilinear meshes have flat normals.
Animation. When a stage animates, decodeScene poses the scene at startTimeCode and adds a
USDSceneRuntime to Scene.systems, which plays the rest: transform operations' time samples (resets
included), points' time samples, and UsdSkel. Time samples take precedence over defaults, interpolate linearly
(orientations spherically) and hold beyond their ends; the runtime loops over the stage's time range. Skinned
meshes bind to their own skel:skeleton or an ancestor's; joints take the SkelAnimation's translations,
rotations and scales (in its own joint order) or their rest transforms, and points move by the weighted sum of
joint transforms times inverse bind transforms after geomBindTransform, with any number of influences per
point and weights as authored; a mesh's skel:joints renumbers its joints. Blend shapes (with in-betweens, and
weights past 1) move the rest points before skinning, weighted by the animation's blendShapeWeights. The skinned points are in the skeleton's space, so the mesh's own transform
doesn't move them. USDAnimationTests compares world transforms and points at seven time codes with
OpenUSD 26.11's, including UsdSkel's skinning.
Lights. Every UsdLux boundable light, and DomeLight without a texture, maps to the nearest SceneGraph light
(USDDistantLight.decode documents the rules): distant lights are directional; sphere and cylinder lights are
omnidirectional, or spots when shaped by shaping:cone:angle; rectangle and disk lights are 180° spots facing
-Z; dome lights are ambient. Strength is intensity × 2^exposure × 1000, scaled by the light's area (or a distant
light's solid angle) when it isn't normalized; color temperature and shadows map directly. Dome textures, IES
profiles, shaping focus, light filters and diffuse or specular multipliers are left out, or throw when strict.
Transforms support ordered translate/scale, axis and six Euler rotations (degrees), orient quaternions,
affine matrices, inverse operations and reset stacks. Shear/reflection matrices use SceneGraph pivots
when TRS decomposition would lose them; unrepresentable singular matrices throw. Stage units default
to centimetres and convert to metres; Y-up and Z-up convert to the engine's Y-up convention.
Inactive subtrees are omitted and visibility is inherited through nodes. Prims are imported for the default
and proxy purposes, as usdview shows them (purposes chooses others), inheriting their nearest ancestor's;
skeletons are read whatever theirs. An invalid upAxis reads as Y, as in OpenUSD.
Material import finds each gprim's material as UsdShade computes it for the preview purpose: preview bindings,
then all-purpose ones; collection bindings (with includes, excludes and expansion rules) before direct ones at each
prim; the nearest binding unless an ancestor's is strongerThanDescendants. GeomSubsets in the materialBind
family give their faces their own materials, as submeshes. Connections are followed through node graph outputs and
material interface inputs to a UsdPreviewSurface shader. Diffuse/emissive colors, metallic/roughness, alpha
and positive opacity masks map to material descriptors. The exporter's emission-only unlit approximation
is recognized. Unbound shading definitions are ignored.
What SceneGraph can't represent exactly is left out unless strict: true, which makes it an error: clearcoat,
IOR, the specular workflow, displacement, texture graphs other than UV0 lookups (the texture is dropped), and
materials without a universal Preview Surface output (MaterialX ones, which bind the default material; MaterialX
layers themselves read as empty); cameras' depth of field, lens shift, motion blur and stereo; the light features
above; and prim types this reader doesn't know, which are groups. scene-convert decodes strictly.
geometryOnly: true discards shading in favor of default materials. Both tools register the USD decoder and retain
their import options across reloads.
USDSampleAssetTests loads the USD Working Group's sample assets (fetched by
Tools/fetch-usd-wg-assets.sh; set USD_WG_ASSETS to run it, as CI does) and checks, for each of the 241 files
OpenUSD 26.11 opens, that the scene draws the gprims OpenUSD draws, with the same bounds, transforms and preview
materials. Only one is expected to fail: a projective matrix. USDHardeningTests checks the same against a fixture
of its own, hardening/. Viewer cameras and lights remain outside the USD unit/axis transform.
Standalone USD image dependencies are watched for changes; USDZ watches its package. Layers composed from files are tracked as dependencies too.
USDCFile provides pure-Swift structural inspection of Crate versions 0.4–0.9 (0.9 adds time codes):
bootstrap/version checks, bounded section-directory reads, LZ4 token decoding and
string-table resolution. Token decompression defaults to a 64 MiB limit. The reader
uses Apple’s swift-binary-parsing (ParserSpan and checked little-endian integer
initializers), without native struct casts or OpenUSD dependencies.
The Cyber Warrior fixture exercises its 0.8.0 section directory and 79-token table.
The binary layout is referenced against OpenUSD v26.11.
USDCFieldTables decodes compressed 32-bit integer streams, field token indices,
64-bit encoded value references and terminated field-set index streams. The Cyber
Warrior fixture contains 58 field records and 119 field-set indices. Limits bound
decompression and table sizes; malformed indices and unterminated sets are rejected.
USDCSpecTables reconstructs ordinary prim and namespaced property paths, validates
path jumps and duplicate records, and resolves spec kinds and field-set references.
Cyber Warrior’s 37 paths and 37 specs are covered by the fixture test. Variant,
target and mapper paths remain unsupported.
USDCValueReader decodes scalar booleans, integers, half/float/double values,
strings, tokens, asset paths, 2–4 component vectors, enum metadata and value blocks.
Inline and out-of-line values are tested against an independent OpenUSD fixture,
including exact 64-bit integer values. Nonfinite numbers, invalid offsets and
unsupported flags produce errors. Matrix2d/3d/4d values preserve USD row order,
including compact inline diagonals. Quatd/quatf/quath values are reordered from
Crate storage into USD’s real-first tuple convention. Uncompressed numeric, vector,
matrix, quaternion, string, token and asset arrays are supported, as are compressed
32/64-bit integer arrays and compressed half/float/double arrays (integer and lookup-table modes). Array decoding defaults to a four-million-element limit and
checks payload bounds before constructing values. Cyber Warrior’s 841,998 triangle
face counts exercise the compressed path.
Token/path vectors and token/path list operations are decoded as if applied to an empty
weaker list, and metadata dictionaries (customData, assetInfo) keep their entries' declared
types. Variant-selection and relationship-target path syntax is read. USDStage(crate:) assembles prims, properties, relationships, shading
connections and metadata from a single Crate layer, and USDSceneDecoder imports it,
including USDZ packages whose default layer is Crate. Inherit, specialize, instancing, clip and
layer-offset fields are read; relocates are rejected, as are fields whose value type is not decoded.
SceneUSDKit is Apple's USDKit API built on SceneUSD, under its own module name so it builds on every platform,
beside Apple's framework too. On platforms without Apple's framework, the USDKit module re-exports it, so
import USDKit works unchanged; on Apple platforms USDKit is empty and import USDKit is Apple's framework.
Docs/USDKitPlan.md has the plan; the API follows the macOS 27.2 SDK's USDKit.swiftinterface.
- Values (done):
USDValue(with OpenUSD's C++ type names, as Apple's reports them),USDArray, the vector, quaternion and matrix types,USDLayer.AssetPath,TimeCode,TimeOffsetandPathExpression, andUSDPrim.Attribute.ValueTypewith its arrays and roles. Values are kept in SIMD storage; matrix rows and columns areInlineArrays, as in USDKit, so those subscripts need an OS withInlineArray. Matrices convert to and fromsimdandSpatialtypes where those exist. - Layers (done): anonymous and registered layers, specs and their fields as
SdfDatakeeps them, every spec handle, time samples, traversal, list operations andUSDLayer.Path. Layers open, reload and import from USDA, Crate and USDZ (the package's first file), read into the same specs and fields OpenUSD reads (Fixtures/generate-sdf-reference.pyrecords OpenUSD's), and save and export as USDA or Crate (.usdc, and.usdunless the layer was read from USDA), which OpenUSD reads back the same. As in OpenUSD, a layer can't be created, saved or exported as.usdz. - Stages (reading done): stages open from files, text, data or layers and compose as OpenUSD does
(sublayers, references, payloads, inherits, specializes, variants, layer offsets and value clips): prims with
their flags and traversal, authored properties with values at time codes, targets, connections and metadata,
checked against OpenUSD 26.11 (
Fixtures/generate-stage-reference.py). - Instancing (done): instances whose own arcs bring in the same sites and select the same variants share a
prototype,
/__Prototype_Nat the stage's root, numbered as OpenUSD numbers them withUSD_ASSIGN_PROTOTYPES_DETERMINISTICALLYset and kept through edits that leave its instances. The prims below an instance are instance proxies, its prototype's prims at its paths, and nothing is authored on them or in a prototype. Checked against Apple's USDKit (Scenarios/InstanceScenarios.swift, prototypes named by their first instance, since by default OpenUSD's numbers follow a hash table's order) and OpenUSD 26.11. - Stage objects and metadata (done):
USDStage.Objectfor prims and properties, and the metadata every stage object reads and writes as OpenUSD'sUsdObjectdoes: typed reads and writes, key paths into dictionaries, composed and authored metadata (with a schema property's definition),customData,assetInfo,documentation,displayNameandhidden; only fields OpenUSD registers for the object's spec type are written. Checked against Apple's USDKit (Scenarios/MetadataScenarios.swift) and OpenUSD 26.11. - Schemas (done): OpenUSD 26.11's schema registry, generated into
UsdSchemaDefinitions.swift(Tools/generate-usd-schemas.py): prims list the properties their type and applied API schemas define, with their types, variability and fallback values, and the API schemas those build in;isSchemafollows schema inheritance, andapplyAPISchemarefuses what isn't an applicable API schema. Checked against OpenUSD (Fixtures/generate-schema-reference.py) for every concrete typed and applied API schema, and against Apple's USDKit for inheritance and which schemas apply (on macOS 27.0.1 it loads no schema definitions). - Authoring stages (done): prims, attributes and values, relationships, connections, metadata,
composition arcs, variant sets, API schemas, transform operations, layer muting, up axis and units, in the edit
target (the root layer, or a variant), checked against OpenUSD 26.11 (
Fixtures/authoring/scenarios.json). Each authoring call, and each edit made directly throughUSDLayer, posts oneObjectsDidChangeto every observing stage that uses the edited layer, with the paths it resynced and those whose information changed, as OpenUSD's notices report them. - Saving and exporting stages (done):
saveandsaveSessionLayerswrite the edited layers the stage uses, andreloadreads them again.exportFlattenedwrites the composed stage as one USDA or Crate layer, as OpenUSD'sUsdStage::Exportdoes: prims in composed order with their resolved values (samples in stage time), arcs, variants and clips resolved away, inactive prims left out, and instances referencingFlattened_Prototype_Nprims.exportPackagewrites a USDZ with the root layer first and every layer and file it depends on, laid out as OpenUSD'sUsdUtils.CreateNewUsdzPackagelays them out, each layer as the stage holds it, unsaved edits included. Both are checked against OpenUSD 26.11 (Fixtures/generate-export-reference.py). Mesh and texture compression options aren't applied: Apple's USDKit compresses meshes into a private codec only its runtime reads. - Handles (done): prims and properties compare, hash and describe themselves as Apple's USDKit and OpenUSD's
UsdDescribedo; properties convert between kinds; predicates, time codes, references and payloads print as Apple's; and a stage's default prim and timing, and prim specs' children, properties, default values, substitutions and relocates, are settable. Relocates on prims, which Apple's USDKit keeps and OpenUSD 26.11 no longer has, are read and written in USDA and Crate and, as in Apple's, don't move composed prims.USDLayer.ChangeListis declared as Apple declares it, though neither API hands one out. Checked against Apple's USDKit (Scenarios/ObjectScenarios.swift).
Handles and queries that can't throw return invalid handles and empty collections, as USDKit does for a missing object.
Its tests run scenarios (Tests/SceneUSDKitTests/Scenarios) that compile against both SceneUSDKit and Apple's
USDKit: Tools/usdkit-oracle/run.sh runs them on Apple's (macOS 27) and records what they observe, and the tests
compare SceneUSDKit's observations with those records on every platform. On macOS 27.0.1, Apple's static value types
(.float3 and the rest) fail to register and are invalid, so the scenarios use ValueType.type(named:).
USDStage composes a root layer with its sublayers, inherits, variants, references, payloads and specializes
(LIVRPS) into a stage. Layers are USDA or Crate and are found through the package (USDZ) or the resource
loader (files), by asset paths relative to the layer that authors them; absolute paths, URLs and paths that
leave the package are rejected, as are cycles and fan-out beyond 2,000,000 prims or 256 layers.
Stronger opinions win per field: the layer stack (root layer, then its sublayers in order), then
variants, then references, then payloads, applied at each prim and recursively inside what it brings in. Children merge by name, properties by name with their metadata merged key by key,
customData and other dictionaries entry by entry. over specs apply but do not create prims, and
class prims are left out. References take a prim path or the layer's defaultPrim, or point into the same
layer; relationship and connection targets are mapped into the referencing prim's namespace, and a target
outside the referenced prim is rejected. Asset paths are rewritten relative to the root layer.
Variant sets (USDA variantSet blocks and Crate variant specs) apply the variant their variants
selection names; the strongest selection among the prim's sites wins, wherever its set is defined, so a
referencing prim, or an over of a child prim, can choose a variant of a referenced layer's set. A selection
that names no variant selects nothing. Variants may nest, and may carry their own references. Paths in a
variant's content may be written with or without the variant selection.
Classes come right after a site's own opinions; a class a referenced prim inherits is also looked for at the same
path in the root layer stack (an implied inherit), as strong as the root's own inherits. Specialized prims are
weakest of all. An instanceable prim's descendants take only the opinions its arcs bring, so overrides authored
over an instance's children are ignored, as for OpenUSD's instance proxies; each instance gets its own copy.
Sublayer and reference layer offsets retime time samples. Value clips (clips with one clip set, on a prim or an
ancestor) become time samples of the attributes the stage declares: each active clip's samples mapped to stage
time through times, a sample at each times entry and at each clip's start, interpolated across switches as
OpenUSD does. USDComposedArcsTests compares every composed prim and attribute value, at the default time and at
ten time codes, with OpenUSD 26.11's for the same layers written as USDA and as Crate. Where several specs author
references, payloads or apiSchemas, the lists are united, strongest first; an explicit list does not
hide weaker ones. A connection or relationship list that prepends or appends cannot be combined with a
weaker opinion and is rejected; an explicit one replaces it.
Authored primvars:tangents (float4) are imported as tangent streams. UsdUVTexture
min/mag filter tokens map to the sampler: nearest/linear magnification, and all six
minification tokens as a minification filter plus a mip filter (linearMipmapLinear is linear with
linear mipmapping, as glTF's LINEAR_MIPMAP_LINEAR); unauthored filters are linear without
mipmapping. Export writes linearMipmapLinear for linear mipmapping and leaves the default otherwise. An unauthored or auto source color space resolves as OpenUSD does: sRGB for 8-bit
images with three or four channels, raw otherwise (8-bit grayscale PNG data maps are raw; JPEG is
treated as color). Color slots require sRGB and data slots raw. General
shading network evaluation remains unimplemented. Cyber Warrior imports natively;
renderer parity with Apple's USD renderer is not verified.
Apple SwiftUsd is not a dependency.
USDSceneEncoder exports the current visible pose to deterministic USDA or a USDZ with a
scene.usda default layer and optional PNG textures. It authors a Scene default prim,
Y-up coordinates and metre units. Stable
prims take their nodes' names (as RealityKit names entities after prims) where those are identifiers no sibling
has, else stable Node_N names; original names are also stored in displayName and restored by the decoder. Each
geometry becomes one Mesh child, its identical vertices welded, with a materialBind subset per material (submeshes
sharing a material share one); materials that disagree on double-sidedness get separate meshes. Indexed and nonindexed triangle lists/strips are
supported; degenerate triangles are omitted. Normals and UV0 use vertex interpolation, with
UV V converted back to USD's bottom-origin convention. Hierarchies are limited to 25 node levels.
let bytes = try USDSceneEncoder(encoding: .usdz, geometryOnly: true).encodeScene(scene)The encoder emits MaterialBindingAPI bindings, on the mesh or its subsets, and a UsdPreviewSurface shader for
every material, the default one too (SceneKit draws it white). It preserves linear diffuse/emissive colors, metallic/roughness
constants and factors, and material alpha (opaque, blend/legacy, or positive mask thresholds).
Legacy Phong/Blinn/Lambert surfaces become fully rough nonmetallic PBR; their ambient/specular
terms and shininess are not retained. Unlit surfaces are approximated using emission, zero diffuse
and IOR 1. Material names use displayName. Default materials need no authored shader.
USDZ diffuse and emissive textures accept in-memory images or local PNG/JPEG paths (JPEG uses PureSwift/swift-jpeg).
Images are encoded as PNG and deduplicated within the package. A UsdUVTexture and
UsdPrimvarReader_float2 connect UV0 to diffuse/emissive RGB and, unless opaque, diffuse texture alpha.
Independent linear color/alpha factors are applied through texture scale; emissive RGB factors may exceed 1 for HDR emission; source pixels are marked sRGB.
PNG rows retain their original orientation while mesh UV V is flipped for USD. Clamp, repeat,
mirror and transparent-black border wrapping are supported. Linear min/mag filters and unit
anisotropy are required; mip filtering is left to the consuming renderer. Standalone USDA
texture output and secondary UVs remain unsupported.
USDZ import accepts these diffuse RGB/alpha and emissive RGB graphs, including PNG/JPEG package members, explicit
sRGB color space, texture scale, zero bias, wrap modes and a direct st primvar reader. Image
paths resolve relative to the default layer inside the package; USDZ never opens external files.
Shared diffuse/opacity sampling is supported; emissive image alpha never controls surface opacity.
Images shared between diffuse and emissive slots are deduplicated, while samplers and factors remain independent. Constant opacity ignores image alpha, and missing
UVs, missing/corrupt images, unsupported color spaces or other graph structures produce errors.
Standalone USDA image loading is available through an explicit resource loader or the file registrations described below.
Independent UV0 texture scale and offset round-trip through UsdTransform2d for diffuse, emission,
normal, occlusion and packed metallic/roughness maps. Negative and zero
scales are supported; the exporter conjugates the transform by the UV V flip so sampling stays
consistent. Import restores MaterialProperty.contentsTransform. Rotation, shear, projective
transforms remain unsupported. GLB preserves these transforms with KHR_texture_transform, including its UV-origin convention.
The OpenGL renderer applies independent texture transforms to diffuse, emission, normal, occlusion,
and packed metallic/roughness maps on UV0 or UV1. Normal-map placement preserves the mesh tangent frame.
Unlit diffuse textures round-trip through USDZ using the emission-only Preview Surface
approximation (zero diffuse, IOR 1). RGB connects to emission; blended and masked materials
connect the same texture alpha to opacity. Color factors, diffuse intensity and inherited
node opacity are preserved without modifying source pixels. Opaque import clears unused
image alpha. Additional emission, normal/occlusion maps and other unlit texture combinations
remain unsupported. Import recognizes this restricted graph and restores an unlit material,
including KHR_materials_unlit when subsequently exported to GLB.
Packed metallic/roughness maps also round-trip through USDZ: roughness uses green, metallic
uses blue, and both connections share one UsdUVTexture in raw color space. Their independent
factors are stored in the corresponding scale channels. Export requires a physically based
material with identical metalness/roughness texture properties, including sampler and UV settings.
Import also accepts separate metallic and roughness maps, each connected through outputs:r:
it packs them into one image (roughness in green, metallic in blue), which requires equal sizes and
identical sampling and UVs; export writes the packed form. Single connected channels, other channel
packing and sRGB data maps are rejected.
The packed image may share storage with color textures while each shader retains its own color space.
Tangent-space normal maps also round-trip through USDZ using raw RGB, signed scale/bias and
uniform nonnegative XY strength. UsdPreviewSurface, glTF and the engine share one convention,
tangent-space +Y toward the image's top, so images pass between them unchanged: export writes
standard positive-Y decoding, and import converts the green channel only for negative-Y decoding
(which earlier versions of this exporter wrote). The OpenGL backend uses the same convention whether
tangents are authored or derived from UVs; a SceneKit-referenced render test checks both and GLB.
Alpha's scale and bias are ignored, since only RGB is read. Normal maps require UV0; custom tangent
streams, anisotropic XY strength, object-space normals and unlit normal maps remain unsupported.
GLB conversion preserves normal strength through normalTexture.scale.
Occlusion maps round-trip through USDZ using raw red-channel sampling. Strength in 0...1
is encoded as scale and complementary bias, preserving the renderer's interpolation from
unoccluded to sampled occlusion. Packed ORM images are shared without changing their pixels.
GLB conversion retains this value through occlusionTexture.strength. Unlit occlusion maps
and nonstandard occlusion shader graphs remain unsupported.
Diffuse property intensity is baked into RGB constants or texture scale, leaving alpha unchanged.
Constant emission intensity is likewise baked into emission RGB, including HDR values. Import
normalizes these multipliers into colors/factors with unit property intensity. Intensities must
be finite and nonnegative; the final diffuse RGB must remain in 0...1. Emissive textures continue
to use emissionFactor; non-unit emissive texture intensity is rejected.
Transparency maps, other unsupported property intensities, custom culling/blending/depth
state and unsupported light types remain unsupported. Explicit geometryOnly: true drops
material shading and those node properties. Exported constant materials can be imported without
geometryOnly; arbitrary shader graphs remain unsupported. Transparent Preview Surface materials
use the renderer's alpha blending approximation rather than full optical transmission.
Static perspective and orthographic cameras round-trip through USDA/USDZ, preserving their
projection and transforms. Export requires a fixed CameraDescriptor.aspectRatio or
USDSceneEncoder(cameraAspectRatio:); the conversion CLI forwards --aspect-ratio.
Both vertical and horizontal field-of-view inputs are supported; import normalizes to vertical.
Apertures and focal lengths follow USD camera units.
Stage unit and axis conversion stays in the imported root transform, so local lens distances
are not converted twice. Camera names use displayName. A node carrying both geometry and
a camera exports a separate Camera child.
Only symmetric lenses with finite clipping planes are supported. Aperture offsets, depth of field, motion blur, stereo roles and custom clipping planes are rejected. Infinite far planes require an explicit finite distance before export. Geometry-only mode discards camera lenses while retaining their child geometry and transforms.
Directional lights round-trip as zero-angle DistantLight prims, preserving color, direction,
names and normalized strength (LightDescriptor.intensity / 1000). Export enables light
normalization and explicitly disables shadows through ShadowAPI. Import folds exposure
into intensity using 2^exposure. This follows the zero-angle distant-light subset of
USD LightAPI.
Legacy directional strength uses the same numerical mapping as GLB export.
Import requires zero angle and explicitly disabled shadows. Nonzero angular extent, temperature controls, custom diffuse/specular contributions, filters, light linking and connected inputs are rejected. Ambient, spot and area lights remain unsupported. Geometry-only mode discards directional lights while retaining their transforms and child geometry.
Inverse-square point lights without a range cutoff round-trip as normalized SphereLight
prims with treatAsPoint = true, zero radius and disabled shadows. Intensity maps numerically
as LightDescriptor.intensity / 1000, following
OpenUSD Storm's point-source approximation.
This is a documented brightness approximation, not a guarantee of photometric equivalence
across USD renderers. Import folds exposure into intensity and preserves position and color.
Legacy distance falloff, range cutoffs, nonzero radii, shaping, shadows and unnormalized sphere
lights are rejected. Geometry-only mode omits these lights.
Inherited node opacity is baked into each exported material's constant opacity or diffuse texture alpha scale. Shared source materials remain unchanged. Legacy/blended surfaces multiply node opacity by material alpha and transparency; masked surfaces apply their cutoff after that multiplication, while explicit opaque surfaces ignore alpha, matching the renderer. Fully transparent node subtrees are omitted. Reimport preserves the visible opacity through materials, rather than reconstructing the original node opacity values. Geometry-only export ignores opacity.
Animation tracks, skin bindings, physics and backgrounds are not serialized; deformed mesh data and transforms capture the current pose. Round-trip tests cover transforms, escaped names, submeshes, malformed geometry, deterministic bytes and safe file replacement.
Standalone USDA may reference relative PNG/JPEG image paths when a resource resolver is supplied.
Use USDSceneDecoder(resourceLoader:) for library-owned resources, or
resourceFileDecoders with SceneAssetFile/SceneAssetConverter for local file resolution and
dependency tracking. The CLI and viewer use these registrations. Paths are resolved relative
to the layer file, including parent-directory references; literal spaces, percent signs and
hash characters are encoded for the resource loader. Absolute paths, URL schemes and nested
package references are unsupported. Missing or corrupt images fail conversion before output
is written. Byte-only decoding without a resolver still performs no external I/O.
Library clients opt into USD file loading with per-instance registrations, without global mutable state:
let decoders = USDSceneDecoder(geometryOnly: true).resourceFileDecoders
let asset = SceneAssetFile(url: inputURL, resourceDecoders: decoders)
let loadedScene = try asset.load()
let encoders = USDSceneEncoder(geometryOnly: true).fileEncoders
try SceneAssetConverter.convert(from: inputURL, to: outputURL,
encoders: encoders, resourceDecoders: decoders)