RealityKit#
3D in the browser build, for games and scenes about as involved as a three.js
one. An app writes RealityKit as it would for iOS 18 (RealityView,
entities, components, systems) and the same source runs on a page, where
three.js draws it. Experimental.
import RealityKit
import SwiftUI
struct Spin: Component { var speed: Float }
struct SpinSystem: System {
static let query = EntityQuery(where: .has(Spin.self))
init(scene: RealityKit.Scene) {}
func update(context: SceneUpdateContext) {
for entity in context.entities(matching: Self.query, updatingSystemWhen: .rendering) {
let speed = entity.components[Spin.self]!.speed
entity.orientation = simd_quatf(angle: speed * Float(context.deltaTime), axis: [0, 1, 0]) * entity.orientation
}
}
}
struct ContentView: View {
var body: some View {
RealityView { content in
SpinSystem.registerSystem()
let box = ModelEntity(mesh: .generateBox(size: 0.2, cornerRadius: 0.02),
materials: [SimpleMaterial(color: .systemBlue, roughness: 0.4, isMetallic: false)])
box.components.set(Spin(speed: 1))
content.add(box)
}
.realityViewCameraControls(.orbit)
}
}
Examples/Shapes is a whole app: a floor, a sun with
shadows, shapes a system spins at the speed a SwiftUI slider sets (a long
press on one fades it out or back in, animating its OpacityComponent), and
buttons that add and clear them. Examples/Blocks
is physics: a pyramid of blocks on a platform; a tap on a block throws a
ball at it, collision events count the hits, and blocks knocked off the
platform score; the ball whooshes as it flies and a hit block thuds. Examples/Pop is a
game: shapes rise out of a board with move(to:), a tap on one
(SpatialTapGesture().targetedToAnyEntity()) scores it in a burst of
sparks (ParticleEmitterComponent), and the score and
lives are SwiftUI views of an @Observable model the scene's update events
drive. Examples/Meadow loads a model: windmills from
a USDZ file in its bundle, cloned, each turning its sails by the file's
animation (tap one to stop it), on hills made vertex by vertex in a bundle
texture, under the sun and a warm lamp, each with its shadows.
How it works#
Swift (Sources/RealityKit) page (@swiftbrowser/reality)
RealityView ── registered element ──────────► ViewRegistry builds a <div>,
{ name: "RealityKit.RealityView", loads three.js (scene.ts) the
props: { source: n, cameraControls } } first time a page shows one
(the app's page module)
│ every animation frame
_FrameHost source n ◄──── sb_frame(n, now, flags) ────┘
scene.step(deltaTime): SceneEvents.Update,
then every registered System
FrameEncoder: what changed, as bytes ───────► applyFrame (frame.ts) →
◄──── sb_frame_ptr ───────────── three.js groups, meshes,
lights, cameras; render
- The scene lives in Swift.
Entity, its components and its children are plain Swift objects; systems andSceneEvents.Updatehandlers run on them in Swift, every frame. The page holds a copy for drawing and never sends anything back about it. - Frames bypass the element tree. The reconciler and the ops are for
views that change when the app's state does; a scene changes every frame,
and a render pass a frame would cost a layout pass a frame
(driven values measured what commits cost). So
RealityViewemits oneregisteredelement and stays still; the page's view calls the module'ssb_frameexport once per animation frame (docs/ops-protocol.md, "Frames"), and the answer is bytes the page reads straight out of linear memory. - Only what changed crosses. The encoder remembers what it last sent per
entity: a still scene costs one byte a frame, a spinning cube one
transform (45 bytes). A page view that was just built asks with the
fullflag and gets everything. - Meshes are descriptions.
MeshResource.generateBox(size:)is a shape and its size on the wire, not vertices; the page builds and shares the geometry. - App state still renders as usual. After each frame the page runs the
executor, so a system that changes an
@Observablescore has it drawn by SwiftUI like any other change. - Nobody else pays. The
RealityKitandsimdmodules link only into apps that import them (packages/cli/src/frameworks.ts). The page's half is a package of its own, @swiftbrowser/reality, which depends on three.js; neither @swiftbrowser/web nor the CLI depends on it. The CLI fetches it, and the three.js it pins, into its cache the first time it builds an app that imports RealityKit (packages/cli/src/ pagePackages.ts), and names it as the app's page module (@swiftbrowser/ web'sAppSpec.pageModules, plugins/page-modules.ts): the page imports it before the app starts and hands it the view registry. three.js is then a chunk the page fetches only when it shows aRealityView(about 565 KB minified, 140 KB compressed).
Wire format#
Little-endian, floats 32-bit. A version byte (1), then commands to the end (Sources/RealityKit/FrameEncoder.swift writes them, packages/reality/src/ frame.ts reads them, packages/reality/src/encode.ts writes them for tests):
| Command | Fields |
|---|---|
| 1 entity | u32 id, u32 parent (0: a root). Made if new, moved under the parent |
| 2 remove | u32 id. Its descendants go with it |
| 3 transform | u32 id, translation xyz, rotation xyzw, scale xyz |
| 4 enabled | u32 id, u8 |
| 5 model | u32 id, u8 present, then a shape code, four parameters, a material count and the materials |
| 6 light | u32 id, u8 kind (0 none, 1 directional, 2 point, 3 spot), color, intensity, attenuation radius, inner and outer angle, shadow, shadow distance |
| 7 camera | u32 id, u8 present, near, far, field of view |
| 8 mesh | u32 mesh id, vertex count, flags (normals, texture coordinates), the positions, normals and coordinates, the triangles' indices, and runs of them by material. A custom mesh, sent before the first model that draws it |
| 9 asset | u32 id, the model's source (bundle:<path> or a URL). The entity is a model's root: the page places a copy of the file's model under it |
| 10 node | u32 id, u32 root, u32 index. The entity is that object of the model's copy (before its entity command) |
| 11 animate | u32 id, the clip (empty: stop), and whether it repeats or is paused, its speed, the blend from what played before, a serial |
| 12 opacity | u32 id, f32 the entity's own OpacityComponent value, 0 … 1 (1: none). The page multiplies it down through the descendants |
| 13 audio resource | u32 resource id, the sound's source (bundle:<path> or a URL), u8 flags (1 loops, 2 streams, 4 starts anywhere), u8 input mode (0 spatial, 1 non-spatial, 2 ambient). Before the first playback naming it |
| 14 audio playback | u32 playback id, u8 state (0 gone, 1 prepared, 2 playing, 3 paused), then, unless gone, u32 entity, u32 resource, u32 serial (changes each time it starts over), gain (dB), fade (seconds to reach that gain), speed |
| 15 audio source | u32 id, u8 kind (0 none, 1 spatial, 2 ambient, 3 channel), then, unless none, gain (dB), rolloff factor, directivity focus. The entity's audio component |
| 16 particles | u32 id, u8 present, then the emitter: its shape and size, where and in which direction particles are born, speed, timing, flags (emitting, particles inherit the transform, fields in local space), simulation state, burst count, a restart serial, and the main emitter's attributes (birth rate, life span, size, colors, opacity curve, acceleration, damping, spread, spin, noise, vortex, attraction, blend, billboard, lighting, image) |
| 17 burst | u32 id. The emitter emits its burst count now (one per burst() since the last frame) |
| 18 image-based light | u32 id, the environment image's source (empty: none), then a second source (empty: none), the blend between them, the intensity exponent and whether it turns with the entity |
| 19 light receiver | u32 id, u32 the entity whose image-based light lights it and those under it (0: the scene's own) |
A material's other textures follow its base color texture: a count, each with its slot (normal, roughness, metallic, emissive, ambient occlusion, opacity, clearcoat, clearcoat roughness, sheen, specular, anisotropy level and angle) and source; then whether its texture coordinates are transformed (offset, scale, rotation), its opacity threshold (negative for none), and whether a physically based material's extras follow: clearcoat, clearcoat roughness, specular, anisotropy level and angle (a fraction of a turn), and a sheen color if it has one.
A material is its kind (lit, unlit, occlusion, the model's own, or video:
an AVPlayer's pictures, its texture avplayer:<the player's number>), color,
roughness, metalness, glow, opacity and its base color's texture (a
bundle:<path> or a URL; empty for none). Parents always come before their
children in a frame.
Frame input#
The page sends something with each frame too (sb_frame_input, a buffer it
fills before sb_frame; docs/ops-protocol.md, "Frames"): the camera it drew
the last frame with, and the view's size. A u8 version (1), then floats:
position xyz, orientation xyzw, vertical field of view (degrees), near, far,
and the view's width and height in points; then a u32 count and, for each
node of a model the page's animations moved since the last frame, its entity
id and transform (10 floats); then a u32 count and, for each sound that
played to its end since the last frame, its playback id and serial (two
u32s; "Audio"). That camera may be one Swift
never set (the one that frames the content, or one the camera controls
moved), so Swift learns it this way rather than working it out. With it a
point in the view becomes a ray (_ViewCamera.ray(through:)), which is how
gestures find their entities.
The native view (SwiftBrowserReality) writes the same input for a
JavaScript scene (SwiftBrowserRealityCore's FrameInput) when it has
something to say: the scene's camera entity and the models' nodes RealityKit's
animations moved. It sends none while there is neither: it does not know
the pose of RealityKit's own camera, nor yet the view's size.
Gestures#
An entity-targeted gesture is an ordinary SwiftUI gesture on the
RealityView:
RealityView { content in … }
.gesture(SpatialTapGesture().targetedToAnyEntity().onEnded { value in
value.entity.removeFromParent()
})
.gesture(DragGesture().targetedToEntity(where: .has(Draggable.self)).onChanged { value in
value.entity.position.x += Float(value.translation.width) / 1000
})
.gesture(MagnifyGesture().targetedToAnyEntity().onChanged { value in
value.entity.scale = .init(repeating: Float(value.magnification))
})
.gesture(LongPressGesture().targetedToAnyEntity().onEnded { value in
value.entity.components.set(OpacityComponent(opacity: 0.3))
})
SpatialTapGesture, DragGesture, MagnifyGesture, RotateGesture and
LongPressGesture can be targeted. The page reports where the gesture
happened in the view: a tap's location, a drag's start, a pinch's start (the
fingers' midpoint, or the pointer for a trackpad pinch), and where a long
press was held (the longpress event's location, which the renderer sends
for this; LongPressGesture's own value is only true). Swift casts the ray
through that point against the scene's collision shapes (Collision.swift).
As in RealityKit, an entity is a target when it has a CollisionComponent
and it or an ancestor has an enabled InputTargetComponent;
targetedToEntity(_:) takes the entity or anything under it,
targetedToEntity(where:) the nearest one at or above what was hit that
matches. A drag, magnification or rotation targets what was under its start
and keeps that entity while it lasts, however far it moves; a magnification
and a rotation of the same two fingers (simultaneously(with:)) share it.
EntityTargetValue forwards the gesture value's properties (translation,
magnification, rotation, startLocation, …). The gesture should be on
the RealityView itself, so its points are the view's. Two fingers on a
view with camera controls also move the camera, as the page's controls do
not know whether the pinch found an entity.
Opacity#
OpacityComponent(opacity:) fades an entity and everything under it: an
entity draws at its own opacity times its ancestors' (the opacity command
carries each entity's own; the page multiplies them). On the page, a mesh
below 1 draws with transparent copies of its materials at their own opacity
times that, so a material's own transparency is kept and materials shared
with other meshes (a model's copies share the file's) are left alone; at 0
it is not drawn, shadows included. It still takes gestures and collides, as
in RealityKit. A FromToByAnimation<Float> (or SampledAnimation<Float>)
bound to .opacity fades it frame by frame
(Animation).
Physics#
A body is an entity with a PhysicsBodyComponent and collision shapes (its
CollisionComponent, or the body's own shapes). The simulation is a
rigid-body engine written in Swift (Sources/RealityKit/Physics), stepped with
the scene at a fixed sixtieth of a second after the animations and before the
systems, so a system sees where the bodies are this frame and a force it adds
acts on the next step. A frame shorter than a step (a 120 Hz display, or
uneven frames) runs none, and changes nothing: what touched still touches
and forces and impulses wait for the next step:
Bodies.
.dynamicbodies fall, are pushed and bounce;.staticones never move;.kinematicones move as the app moves them (their velocity is worked out from how far they went, or theirPhysicsMotionComponent's) and push dynamic bodies without being pushed back. Mass and inertia come from the shapes (PhysicsMassProperties);PhysicsMaterialResourcegives friction and restitution; damping, gravity per body (isAffectedByGravity) and per subtree (PhysicsSimulationComponent), and locked translation and rotation axes are honoured.Pushing.
addForce,addTorque,applyLinearImpulse,applyAngularImpulseandapplyImpulse(_:at:relativeTo:); velocities read and written throughPhysicsMotionComponent.Contacts. Spheres, boxes, capsules and convex shapes in any pair: boxes against boxes by the separating axis test, clipping the faces for up to four points, so boxes rest flat and stack. Sequential impulses (ten iterations) with friction, restitution, a little positional correction and warm starting from the last step's impulses.
Convex shapes.
ShapeResource.generateConvex(from:)takes points or a mesh (its vertices; a box's corners, a sphere's, cylinder's or cone's curves at a few dozen points), and the async, throwing forms take the same. The shape is the points' hull, built once (Physics/ ConvexHull.swift) with its coplanar triangles merged into faces, so a hull of a box's corners has six square faces; points that span no volume make one a millimeter thick. A hull meets boxes and other hulls by the same separating axis test as two boxes, over both sets of faces and the crossings of their edges, clipping the face most against the other's for up to four points (for boxes it finds the same contacts as the box test), so hulls rest flat and stack; spheres and capsules meet it at its nearest point. Its volume, center and inertia come from the hull, and raycasts, gestures and convex casts hit it like any shape.Continuous collision detection. A dynamic body with
isContinuousCollisionDetectionEnabledthat moves further in a step than half its smallest shape's inner radius (a sphere's radius, a box's smallest half size) is swept from where it was to where it went, turning as it went (Physics/Sweep.swift), and stopped just touching the first static or kinematic body in its way, so the next step's contacts stop or bounce it instead of letting it pass through. The sweep tries the shape along its path at steps of half that radius, only where its bounds can meet the other's, and halves its way to the touch, so it works for every pair of shapes and finds walls however thin. It costs nothing for bodies without the flag, or slow ones; it does not look at other dynamic bodies, and the rest of a stopped body's step is lost.Sleep. A body slow for half a second sleeps, and the solver treats it as immovable, which is what lets a pile settle; a push, a teleport (the app setting its transform) or a moving body touching it wakes it.
Events.
CollisionEvents.Began,Updated(each frame while touching, except while both sleep) andEnded, with the contact's position, impulse and depth;subscribe(to:on:)filters by either entity. ACollisionComponentin.triggermode, or one without a body, reports what passes through it and pushes nothing.Casts.
Scene.raycastandScene.convexCastlook at every enabled entity with aCollisionComponentwhose group is in the mask, body or not, and answerCollisionCastHits nearest first (.nearest,.allor.any), in the space of the entity given asrelativeTo. A convex cast sweeps any shape from one position and orientation to another by the same sweep as continuous collision detection; each hit is where the shape first touches the entity, with the entity's surface normal there and how far the shape had gone (distance), andshapeIndexsays which of the entity's shapes it was. What the shape overlaps where it starts is hit at distance 0, at the origin, with the normal against the sweep, as RealityKit has it.Joints. Pins name a position and orientation on an entity (
entity.pins.set(named:position:orientation:), orrelativeTo:a reference, kept in aGeometricPinsComponent). A joint ties two pins together:PhysicsRevoluteJoint(a hinge about the pins' x axis, with an optionalangularLimit),PhysicsSphericalJoint(a ball and socket, with an optional elliptical coneangularLimitInYZ),PhysicsPrismaticJoint(a slider along x, with an optionallinearLimit),PhysicsFixedJoint,PhysicsDistanceJoint(distanceLimit,tolerance) andPhysicsCustomJoint(each of the six axes.fixed,.rangeor.unlimited).addToSimulation()puts a joint in the nearestPhysicsJointsComponentabovepin0's entity, stopping at thePhysicsSimulationComponent, or on that entity; removing it fromjoints, or removing the component, frees the bodies, and a joint whose entity is disabled or gone is skipped. Each joint is a few constraint rows solved together in the same loop as the contacts, with limits that only push, warm starting, and split impulses for its errors, which move the bodies without adding speed. Jointed bodies sleep and wake together, and do not collide with each other unlesschecksForInternalCollisionsis set. A pin may sit on a static or kinematic body, on an entity without a body, or on no entity, which fixes it in the scene. Skeletal-joint pins do not resolve. Chains of up to about fifty light links hold at the default passes; longer ones stretch, and a hundred come apart (moresolverIterationshelps only so far).
Why in Swift and not Rapier, as first planned: Rapier on the page would
answer a frame late, through a round trip, and not run in swift test or
the headless snapshots; linked into the app's module, it would need a Rust
build for WASI shipped in the kit and the in-browser compiler. An engine in
Swift steps with the systems, the same everywhere, and needs nothing new to
ship. It is a game's engine, not a robotics one: no concave (static) mesh
shapes yet, and continuous collision detection only against what holds
still.
Meshes and textures#
MeshResource.generate(from: [MeshDescriptor]) makes a mesh of the app's own
vertices: positions, normals (the page works them out when there are none)
and texture coordinates, faces as triangles, polygons or triangles and
quads, and a material for all faces or for each. Its vertices cross to the
page once (the mesh command), the first time a model draws it, and every
model drawing it shares them.
MeshResource.generateText(_:extrusionDepth:font:containerFrame:alignment:lineBreakMode:)
makes a mesh of a string's glyphs. Swift keeps the string, the font (as a
CSS family and weight: the system font in its design, or a named font with
the system's after it) and the layout, and sends them once (the text
command), before the first model that draws it; the model names it as a
custom mesh. The page draws each line into a canvas in that font, traces the
drawn pixels' edges into outlines, simplifies them, matches holes to their
glyphs and extrudes them (packages/reality/src/text.ts). So no font file
comes with the package, the system font is the page's, and a font the app
ships is the one its bundle registered. A point of the font is a meter, as in
RealityKit. Without a container frame the text starts at x = 0 with its last
line's descender at y = 0; with one, the lines wrap at its width (by word or
by character), line up across it by alignment, and lines past its height
are dropped, a truncating mode ending the last with an ellipsis. Swift
estimates the text's box (for visualBounds and collision shapes) from the
system font's average advance; the page has the real outlines. In a native
app (SwiftBrowserReality) the same description goes to RealityKit's own
generateText.
TextureResource.load(named:) and TextureResource(named:) find an image
in the app's bundle; load(contentsOf:) takes a bundle file's URL or a web
URL. A texture is where the image is, never its pixels: the page loads it
from where it serves the bundle (page modules get a resolver for that), and
Swift reads its size from the file's header. A base color texture
(SimpleMaterial.color, UnlitMaterial.color,
PhysicallyBasedMaterial.baseColor, or iOS 13's baseColor = .texture(…))
is drawn under the tint, repeated past the edges. PhysicallyBasedMaterial
also takes a normal map (normal), roughness and metallic textures (times
their scales), an emissive texture (times emissiveColor and its
intensity), ambient occlusion, an opacity texture (with
.transparent(opacity:)), opacityThreshold for cut-outs, and
textureCoordinateTransform (offset, scale and rotation, for every texture
of the material); SimpleMaterial takes roughness and metallic textures
(MaterialScalarParameter.texture). Color textures are read as sRGB and the
others as data.
PhysicallyBasedMaterial's clearcoat, clearcoatRoughness, sheen
(SheenColor), specular, anisotropyLevel and anisotropyAngle are drawn
by three.js's MeshPhysicalMaterial, which a material gets only when it has
one of them (the others draw with the plainer MeshStandardMaterial). The
clearcoat's and its roughness's textures and the sheen's are drawn; the
specular and anisotropy textures cross to the page and are not (three.js
reads them from other channels than RealityKit's grayscale images).
RealityKit's specular adds to what roughness gives: 1 doubles the
reflectance seen head on. three.js has no sheen roughness of RealityKit's:
it is drawn at its softest.
Lights and shadows#
DirectionalLightComponent.Shadow draws one shadow map out to
maximumDistance around the light's entity. SpotLightComponent.Shadow
draws one from the light out to its attenuation radius (zFar fixed nearer
is sent; three.js keeps the radius as the map's far plane); depthBias and
zNear are accepted. RealityKit has no point light shadows, and neither
does the page (three.js would draw six maps for one). A spot light sits at
its entity, its cone along the entity's −z.
Image-based light#
Every scene is lit by an environment, as every RealityKit scene is (three.js's
room, prefiltered). An entity with an ImageBasedLightComponent supplies
another: an EnvironmentResource from the bundle (EnvironmentResource(named:)
or load(named:), an equirectangular PNG, JPEG or Radiance HDR at the
bundle's root or in a .skybox folder of the same name), brightened by
2^intensityExponent, turning with the entity when inheritsRotation. A
.blend of two draws the nearer of the two. The entities whose
ImageBasedLightReceiverComponent names that entity, and the entities under
them, are lit by it (three.js: each lit material's envMap, which the
renderer prefilters); the others keep the scene's own. The environment is
light only: it is not drawn as a background.
Video#
VideoMaterial(avPlayer:) shows what the player plays, unlit, as
RealityKit's does. The player reaches the page as it does for a
VideoPlayer: the RealityView draws, unseen (zero size, transparent), a
video element for each player its scene's video materials show, which
plays, pauses, seeks, loops and reports to the player as a view's would (the
player's video element, docs/ops-protocol.md "Video and audio", with
texture), and the page draws that element's pictures on the materials (a
three.js VideoTexture), finding the <video> by the player's number. Play
and pause follow the player; the browser's rule holds that sound needs a tap
first (a muted player starts at once). A remote video must be served with
CORS for WebGL to draw it. If a view also shows the player, the newer of the
two plays it, as for any two views of one player.
VideoMaterial is in a module of its own, _RealityKit_AVFoundation, which
the CLI links, and re-exports in the app's generated file, only into apps
that import both RealityKit and AVFoundation (as Swift's cross-import
overlays are): a scene without video does not carry AVFoundation (about 1.9
MB of an unoptimized module, 0.6 MB compressed). RealityKit itself only
offers the hook (_RealityVideoSupport) the first video material installs.
Models#
try await Entity(named: "Windmill"), Entity(contentsOf:) and
ModelEntity's load a USDZ, USDC or USDA file of the bundle or the web. The
page parses it with three.js's USD loader (meshes, UsdPreviewSurface
materials and their textures, skinned meshes, skeletal and transform
animation) and keeps it, one load per file, for every view; Swift asks it
for the file's outline (a realitykit.asset request, which the page module
answers through the page's request registry). That makes an entity for
every object of the file, with its name and transform, a ModelEntity for a
mesh, whose bounds the page measured: findEntity(named:), transforms,
visualBounds, generateCollisionShapes, gestures and physics work on them
as on any entity. The vertices stay on the page: the model's root tells the
page to place a copy of the model under it (asset), and each entity is
bound to its object in that copy (node), which its transform, visibility
and materials then move, hide and replace. A model's own materials stay as
the file has them until the app gives a mesh others. clone(recursive:)
makes a copy that places a copy of its own.
availableAnimations lists the file's animations (its skeletal animations,
and its time-sampled transforms as one clip); playAnimation(_:) plays one
(.repeat() to loop, with a blend from what played before), and its
controller pauses, resumes, changes speed and stops it. The page moves the
model, and tells the app what it moved: with each frame's input come the
transforms its animations gave the model's nodes since the last frame, which
become the entities' transforms before the systems run (and are not sent
back), so a system reads where a sail or a bone is now. What the app then
sets on such an entity is drawn, until the animation moves it again.
The older synchronous loads (Entity.load(named:),
ModelEntity.loadModel(named:)) return the entity at once and fill it in
when the page has loaded the file: there is no waiting for the page without
await. Reality Composer Pro's .reality files do not load.
Animation#
Animations built in code play in Swift. FromToByAnimation (from, to or by
a value, with a timing function, additive or not), SampledAnimation
(frames a fixed interval apart, interpolated or held), OrbitAnimation
(around the parent's origin, turning with the path or not) and
AnimationGroup become resources with AnimationResource.generate(with:),
and sequence(with:) and group(with:) combine resources. playAnimation(_:)
runs them in the scene's animation pass each frame, before physics and the
systems, so the transforms they write are the ones systems, physics,
gestures and the page see. Delay, speed, offset, trims, the repeat modes
(.repeat, .autoReverse, .cumulative, repeated(count:),
repeatingForever(), the resource's repeat), backwards fill and a blend in
over transitionDuration are honoured, and the controller pauses, resumes,
changes speed and stops them; a finished animation leaves its last value,
and a new animation of the same property (or a move(to:)) takes over from
the one before. A Transform animates the entity's transform and a Float
its OpacityComponent (.opacity), on the playing entity or a descendant
named with .entity(_:); values bound elsewhere (.parameter,
.jointTransforms, a vector bound to .transform) keep time and complete
without changing anything. Blend layers are accepted and ignored (the newer
animation of a property stops the older), rotations given by take the
short way round, and a model's animations cannot be part of a sequence or
group.
Particles#
ParticleEmitterComponent describes an emitter; the page simulates it.
Swift sends the description when it changes (particles) and each
burst() as a command of its own (burst), so a burst reaches the page
when nothing else changed; nothing about the particles comes back. The page
(packages/reality/src/particles.ts) steps them on the CPU each animation
frame, at most 2000 to an emitter, and draws them as camera-facing quads
(particleView.ts): quads rather than points, which the WebGPU renderer
draws a pixel wide.
var sparks = ParticleEmitterComponent.Presets.sparks
sparks.isEmitting = false
sparks.burstCount = 80
entity.components.set(sparks)
…
entity.components[ParticleEmitterComponent.self]?.burst()
- Births. The shapes
.point,.box,.sphere,.plane,.cone,.cylinderand.torus, sized byemitterShapeSize(the whole extent; a torus's tube istorusInnerRadiusof its ring's radius) and swept byradialAmount; on the.surface, in the.volume, or at grid.vertices(of a box or a plane; the others fall back to the surface). Particles leave along the surface.normal(a point's is any direction), oremissionDirectionin the entity's space (.local) or the scene's (.world), spread overspreadingAngle, atspeed±speedVariation. - Timing.
.once(warmUp:emit:)and.repeating(warmUp:emit:idle:)with their variations, atbirthRatea second whileisEmitting;burst()emitsburstCount±burstCountVariationwhether emitting or not.simulationStatepauses (.pause) or clears (.stop), andrestart()starts the timing over. - Motion and looks.
acceleration,dampingFactor, noise (noiseStrength,noiseScale,noiseAnimationSpeed), a vortex and an attraction center;lifeSpan,sizeandsizeMultiplierAtEndOfLifespan(with its power),color(.constantor.evolving, each.singleor.random(a:b:), withcolorEvolutionPower),opacityCurve,angleandangularSpeed,blendMode(.alpha, sorted back to front;.additive;.opaque),billboardModeandimage(a soft white dot without one). - Spaces. As in RealityKit by default, particles stay where they were
born in the scene when the entity moves; with
particlesInheritTransformthey move with it.fieldSimulationSpacesays whetheraccelerationand the other fields are the scene's (.global) or the entity's. - Presets.
ParticleEmitterComponent.Presets.sparks,.magic,.rain,.snow,.impactand.fireworksare values chosen to look like their names, not Apple's own numbers. - For tests, the view element says how many particles are alive and
how many were ever born (
data-particles,data-particles-born).
Not there: spawnedEmitter and its spawn settings (accepted, nothing is
spawned), stretchFactor, isLightingEnabled (particles are unlit), sprite
sheets, sortOrder (accepted), particle mass, and emitters in a
@swiftbrowser/react scene or the native view.
Audio#
let thud = try await AudioFileResource(named: "Thud.wav")
let controller = block.playAudio(thud)
controller.gain = -6
controller.completionHandler = { print("done") }
AudioFileResource(named:in:configuration:), AudioFileResource.load(named:in:inputMode:loadingStrategy:shouldLoop:)
and their contentsOf: forms find a sound in the app's bundle (a WAV, MP3,
AAC or anything else the browser decodes; with or without its extension)
or take a web URL. As with a texture, a resource is where the sound is:
the page fetches the file from where it serves the bundle and decodes it
with Web Audio, once per file.
playAudio(_:) and prepareAudio(_:) give an AudioPlaybackController
whose state crosses with each frame (audio playback, after an audio resource the first time a resource is played): playing, paused, prepared,
its gain in decibels (fade(to:duration:) ramps to it), its speed, and a
serial that changes when it starts over. The page plays a buffer source
for it from the entity: a spatial sound through a PannerNode (inverse
distance, the component's rolloff factor) moved to the entity's world
position each frame, with the AudioListener at the camera the view draws
through; an ambient or channel sound straight out. The entity's
SpatialAudioComponent, AmbientAudioComponent or ChannelAudioComponent
decides which (audio source; spatial first when it has several), its gain
added to the controller's; without one, the resource's input mode does
(.spatial unless load was told otherwise). stop(), stopAllAudio()
and the entity leaving the scene end a sound.
How Swift learns a sound ended: the page reports each one that played to its
end with the next frame's input, by playback id and serial ("Frame input");
Swift completes the controller (isPlaying turns false, then its
completionHandler and AudioEvents.PlaybackCompleted) only when the
serial is the one it is playing, so a report about a sound already
restarted is ignored. A looping sound never ends by itself. A sound whose
file does not load is reported as ended at once.
Browsers start an AudioContext only after the person has interacted with the page: the page's one context is resumed on the first pointer, touch or key event. A sound that does not loop and would start before any interaction is skipped and reported ended, rather than held to play late when the context starts; a looping one waits for it.
Not there: streaming (.stream decodes the whole file first, too),
directivity, reverb (reverbLevel, reverbSendLevel), normalization
and calibration, mix groups, AudioFileGroupResource, generated audio
(AudioGeneratorController) and seeking. The native view of a
JavaScript scene plays its sounds with RealityKit ("From JavaScript").
The renderer#
A view draws with three.js's WebGPU renderer where the browser has a WebGPU
adapter, and its WebGL renderer elsewhere (packages/reality/src/renderer.ts);
?renderer=webgl or ?renderer=webgpu on the page's URL chooses. Both
builds of three.js share one core (three.core.js), so the scene's objects,
the USD loader's and the add-ons' are the same classes whichever draws them,
and the WebGPU build (about 630 KB) is a chunk only a browser with WebGPU
fetches. Before it draws, the WebGPU renderer draws one frame to its canvas
and is dropped for the WebGL one if the device is lost: a browser can offer
an adapter and still not present to a canvas (a headless Chromium does),
which would leave the view blank without an error.
Many entities of one model draw as one: each frame, the meshes whose models
are the same (the same shape and materials) are grouped, and a group of 16
or more is drawn by one three.js InstancedMesh, each entity's world matrix
an instance (packages/reality/src/batches.ts). A hundred ModelEntitys of
one box are a hundred entities in Swift and one draw call on the page. The
entities' own meshes are hidden for the render and shown after it, so
nothing else sees the batching; meshes that would draw differently
instanced keep their own (transparent materials, which are sorted one mesh
at a time, materials with their own image-based light, video, and
occlusion). The view element's data-instanced says how many meshes the
last frame drew instanced. Swift still compares every entity with the last
frame to find what changed, so a scene of thousands of entities costs that
much each frame there.
What has been checked, and how: in a headless Chromium with a software
adapter, the WebGPU setup (tone mapping, shadows, the environment's
prefiltering) draws a lit scene to a render target as expected, and a view
falls back to WebGL and draws (e2e/reality-webgpu.spec.ts). That browser
cannot present WebGPU to a canvas, so the views have not been seen drawn by
WebGPU on a real GPU yet; ?renderer=webgl is the way back if one draws
wrong.
What there is#
| Supported | Not yet | |
|---|---|---|
| Views | RealityView(make:update:) and with a placeholder, RealityViewCameraContent (add, remove, entities, subscribe(to:), camera, hitTest(point:in:), ray(through:in:), project(point:to:)), .realityViewCameraControls (.orbit, .pan, .tilt, .dolly) |
the AR cameras (.worldTracking and .spatialTracking show the virtual camera), ARView; attachments (RealityView(make:update:attachments:), ViewAttachmentComponent) are visionOS's alone, so an iOS app cannot use them: a label that follows an entity is a SwiftUI view placed at content.project(point:to:) |
| Gestures | SpatialTapGesture, DragGesture, MagnifyGesture, RotateGesture and LongPressGesture with .targetedToAnyEntity(), .targetedToEntity(_:), .targetedToEntity(where:) and EntityTargetValue (entity, gestureValue, the gesture value's properties) |
location3D, the older MagnificationGesture and RotationGesture targeted, a targeted long press in the native renderer (it sends no location) |
| Entities | Entity (hierarchy, name, isEnabled, transform, position, orientation, scale, the relativeTo: forms, look(at:from:upVector:relativeTo:), findEntity(named:), clone(recursive:), visualBounds, generateCollisionShapes), ModelEntity, AnchorEntity(world:), DirectionalLight, PointLight, SpotLight, PerspectiveCamera |
|
| Models | Entity(named:in:), Entity(contentsOf:withName:), Entity.load(named:), ModelEntity.loadModel(named:) and (contentsOf:), for USDZ, USDC and USDA |
.reality files, Reality Composer Pro packages, loadAsync |
| Animation | move(to:relativeTo:duration:timingFunction:) (a Transform or a matrix), AnimationPlaybackController (stop, pause, resume, isPlaying, isComplete, speed), AnimationTimingFunction (.linear, .easeIn, .easeOut, .easeInOut, .default, .cubicBezier), AnimationEvents.PlaybackCompleted and PlaybackTerminated, stopAllAnimations; a model's availableAnimations and playAnimation(_:transitionDuration:startsPaused:), AnimationResource.repeat(), the entities following what it moves; animations built in code: FromToByAnimation, SampledAnimation, OrbitAnimation, AnimationGroup, AnimationResource.generate(with:), sequence(with:), group(with:), repeat and fill modes, trims, BindTarget (.transform, .opacity, .entity(_:) paths) |
joint and blend-shape animations built in code, .parameter bind targets, blend layers, AnimationView, BlendTreeAnimation, action animations |
| Audio | AudioFileResource (init(named:in:configuration:), init(contentsOf:withName:configuration:), load(named:in:inputMode:loadingStrategy:shouldLoop:), load(contentsOf:…), Configuration, shouldLoop), Entity.playAudio(_:), prepareAudio(_:), stopAllAudio(), AudioPlaybackController (play, pause, stop, isPlaying, gain, speed, fade(to:duration:), completionHandler, entity), SpatialAudioComponent (gain, distanceAttenuation), AmbientAudioComponent, ChannelAudioComponent, AudioEvents.PlaybackCompleted |
streaming, directivity, reverb, normalization and calibration, AudioFileGroupResource, AudioGeneratorController, seeking |
| Components | Component (your own), ModelComponent, the three lights' components, directional and spot light shadows (SpotLightComponent.Shadow with zFar; depthBias, zNear accepted), ImageBasedLightComponent (.single, .blend, intensityExponent, inheritsRotation) and ImageBasedLightReceiverComponent, PerspectiveCameraComponent, Transform, CollisionComponent (box, sphere, capsule and convex shapes, offsetBy, .trigger; hit by gestures and raycasts), InputTargetComponent, OpacityComponent (multiplied down through the descendants) |
|
| Particles | ParticleEmitterComponent (emitterShape, emitterShapeSize, birthLocation, birthDirection, emissionDirection, speed, radialAmount, timing, isEmitting, simulationState, burst(), burstCount, restart(), fieldSimulationSpace, particlesInheritTransform, mainEmitter), ParticleEmitter (birth rate, life span, size, color, opacityCurve, acceleration, damping, spread, angle and spin, noise, vortex, attraction, blendMode, billboardMode, image), Presets (.sparks, .magic, .rain, .snow, .impact, .fireworks) |
spawnedEmitter (accepted), stretchFactor, lit particles, sprite sheets (imageSequence) |
| Physics | PhysicsBodyComponent (.dynamic, .static, .kinematic, mass properties, material, damping, gravity, locked axes, isContinuousCollisionDetectionEnabled against static and kinematic bodies), convex shapes (ShapeResource.generateConvex(from:) with points or a mesh, and its async throwing forms, ShapeResourceError), PhysicsMotionComponent, PhysicsMaterialResource, PhysicsSimulationComponent (gravity, solverIterations), forces, torques and impulses, CollisionEvents.Began, Updated and Ended, triggers; joints: GeometricPin, entity.pins, PhysicsRevoluteJoint, PhysicsSphericalJoint, PhysicsPrismaticJoint, PhysicsFixedJoint, PhysicsDistanceJoint, PhysicsCustomJoint with their limits, PhysicsJointsComponent, addToSimulation() |
continuous collision detection between dynamic bodies, skeletal-joint pins, AttachedTransformComponent |
| Raycasts | Scene.raycast(origin:direction:length:query:mask:relativeTo:) and raycast(from:to:…), Scene.convexCast(convexShape:fromPosition:fromOrientation:toPosition:toOrientation:query:mask:relativeTo:), CollisionCastHit (with shapeIndex), CollisionGroup, CollisionFilter |
CollisionCastHit.triangleHit, pixelCast |
| Systems | System (registerSystem, init(scene:), update(context:)), EntityQuery with .has, &&, ` |
|
| Meshes | generateBox (with corner radius), generateSphere, generatePlane (both orientations), generateCylinder, generateCone, generate(from: [MeshDescriptor]) and MeshResource(from:) (positions, normals, texture coordinates; triangles, polygons, quads; materials per face), generateText(_:extrusionDepth:font:containerFrame:alignment:lineBreakMode:) |
LowLevelMesh, a plane's corner radius, generateText(_:textOptions:extrusionOptions:) (attributed strings) |
| Materials | SimpleMaterial, UnlitMaterial, PhysicallyBasedMaterial (base color, roughness, metallic, emissive, transparency, opacityThreshold, clearcoat, clearcoatRoughness, sheen, specular, anisotropyLevel, anisotropyAngle), OcclusionMaterial, VideoMaterial(avPlayer:); textures (TextureResource from the bundle or a URL) for base color, normal, roughness, metallic, emissive, ambient occlusion, opacity, clearcoat, clearcoat roughness and sheen, textureCoordinateTransform; EnvironmentResource(named:) and load(named:) |
specular and anisotropy textures (sent, not drawn), VideoMaterial's controller and init(videoRenderer:), environments from a cube or CGImage, a skybox background (RealityViewCameraContent.environment), faceCulling (accepted); custom shader materials (ShaderGraphMaterial, CustomMaterial) are not planned: their shaders are Metal or Reality Composer Pro graphs |
| simd | simd_quatf, simd_float3x3, simd_float4x4, and the vector functions RealityKit code uses (simd_normalize, simd_cross, simd_slerp, simd_act, …) |
double-precision quaternions and matrices |
Without a PerspectiveCamera in the scene, the view frames its content the
first time it has some, from the front and a little above. Lights keep
RealityKit's units: the page scales lux and lumens so RealityKit's default
lights look about as bright as on a device, over an image-based light like
the one every RealityKit scene has (or the one an entity's
ImageBasedLightReceiverComponent names).
From JavaScript#
A @swiftbrowser/react app shows a 3D scene the same way, with the scene in
its JavaScript instead of Swift (@swiftbrowser/reality/react):
import { Entity, MeshResource, RealityView, simpleMaterial } from '@swiftbrowser/reality/react';
const box = new Entity();
box.model = { mesh: MeshResource.generateBox(0.2), materials: [simpleMaterial({ color: '#ff9500' })] };
<RealityView make={(content) => content.add(box)} onUpdate={({ deltaTime }) => box.rotate([0, 1, 0], deltaTime)} />
- The scene (packages/reality/src/content.ts) is RealityKit's in
TypeScript, as far as a game needs it so far:
Entity(a hierarchy,position,orientation,scale,isEnabled,opacity,rotate,lookAt,worldTransform), a model (a shape fromMeshResource.generate…, text fromgenerateText, and its materials:simpleMaterial,unlitMaterialwith an optional texture URL,physicallyBasedMaterial,occlusionMaterial), a light (directionalLightandspotLightwith shadows,pointLight) and a camera (perspectiveCamera).RealityViewContentholds the top-level entities and runsonUpdatehandlers before each frame, after stepping the entities'move(to:)animations (eased as RealityKit's timing functions, with a controller to stop or hear the end of).ray(through:)andhitTestgo through the scene's camera entity against the models' boxes (a sphere's ball), or what a registered hit tester says (registerHitTester: physics makes an entity with aCollisionComponentbe hit by its collision shapes), andRealityView'sonTapreports the nearest entity under a tap; its entity gestures are below. - Each frame the view asks the content for what changed since the last, and the content writes it in the wire format a Swift app's frames use: it keeps what it last sent of each entity and compares (a model by identity first, then by value), so a frame of a game where one slab slides is that slab's transform and the camera's.
- On a page the frames go to the scene a Swift app's go to (scene.ts,
three.js). The page reads them from the app's own content, in the same
page, through a map of sources (sources.ts). The app's web entry installs
that half with
installRealityPage(ViewRegistry)from@swiftbrowser/reality/page, and three.js loads the first time a view appears. - In a native app the frames go to RealityKit itself:
SwiftBrowserReality (Native/Packages/SwiftBrowserReality) registers the
view as a RealityKit
RealityViewwhoseSceneEvents.Updateasks the app's JavaScript for a frame (NativeFunctions.send("reality.frame")). The frame comes back, synchronously and inside that call, to the native function of the same name, in base64. A decoder with no Apple framework reads it (tested on Linux against the commands the page's reader reads from the same bytes: packages/reality/test/fixtures/frames.json), and the view makes the entities, meshes, materials, lights and camera with RealityKit's own types. The app's native entry installs the JavaScript half withinstallRealityNative({ callNative, callNativeSync, onNativeEvent })from@swiftbrowser/reality/native. three.js is never in the native bundle. - Separate imports. Physics (
@swiftbrowser/reality/physics), particles (/particles), sounds (/audio), image-based light (/lighting), models from files (/models) and animations built in code (/animation) are entry points of their own, not part of/react: an app that shows a spinning box ships none of them. Importing one is what turns it on for every content (it registers its component codecs, content systems and frame-input handlers when it loads), and the package lists them as side effects so a bundler keeps a bareimport. - Files in a native app: in the native view a
texture, sound or environment image is loaded by RealityKit from the
app's bundle (a relative path) or a URL (downloaded to a temporary file
first), and what names it is set again once it has loaded. RealityKit's
RealityViewneeds iOS 18 or macOS 15; before that the native view says so.
Physically based materials#
physicallyBasedMaterial (in the core, from /react) is RealityKit's
PhysicallyBasedMaterial: base color, roughness and metalness, each a value
times a texture's when it has one, the other textures (normal, ambient
occlusion, emissive, opacity), clearcoat, sheen, specular and anisotropy,
and a texture-coordinate transform. It writes the material record as
Materials.swift does for a Swift app (texture slots 1 … 12 and the trailing
physical block), drawn by three.js's MeshPhysicalMaterial on a page and
by RealityKit's own material natively. A spot light's shadow (true, or
{ zFar }) reaches as far as the light does, as SpotLightComponent.Shadow.
import { physicallyBasedMaterial, spotLight } from '@swiftbrowser/reality/react';
box.model = {
mesh: MeshResource.generateBox(0.2),
materials: [physicallyBasedMaterial({
baseColor: { tint: '#ffffff', texture: 'wood.png' }, roughness: { scale: 0.8, texture: 'wood-rough.png' },
normal: 'wood-normal.png', clearcoat: 1, clearcoatRoughness: 0.1, emissiveColor: '#000000',
})],
};
lamp.light = spotLight({ intensity: 6000, shadow: true });
Particles#
ParticleEmitterComponent (src/particleEmitter.ts) is RealityKit's, with
its defaults and presets (Presets.sparks, magic, rain, snow,
impact, fireworks): the emitter's shape, birth location and direction,
speed, timing, and its mainEmitter's birth rate, life span, size, colors
(constant or evolving, one or a random one between two), opacity curve,
forces, blend and billboard modes and image. It lives on the entity's
components; its codec sends the description when it changes and each
burst() as a command of its own. The page simulates the particles
(particles.ts); the native view makes RealityKit's own emitter (a vertex
grid birth location becomes the shape's volume there).
import { ParticleEmitterComponent } from '@swiftbrowser/reality/particles';
const sparks = ParticleEmitterComponent.Presets.sparks;
sparks.mainEmitter.birthRate = 0;
anvil.components.set(sparks);
// on a hit
anvil.components.get(ParticleEmitterComponent)?.burst();
Sounds#
AudioFileResource.load(url, { shouldLoop, inputMode, … }) names a sound
file; entity.playAudio(resource) (and prepareAudio, stopAllAudio) gives
an AudioPlaybackController to play, pause, stop, fade(to, duration),
change gain (decibels) and speed of, and hear the end of
(completionHandler, onCompletion). SpatialAudioComponent,
AmbientAudioComponent and ChannelAudioComponent say how the entity's
sounds are heard. The view reports the playbacks that played to their end
with the next frame's input (finishedPlaybacks), which completes their
controllers (a report of an earlier serial, from before the sound was played
again, is not). On a page Web Audio plays them (audio.ts: a one-shot sound
started before the person has interacted with the page is skipped and
reported finished); natively RealityKit does.
import { AudioFileResource, SpatialAudioComponent } from '@swiftbrowser/reality/audio';
const thud = AudioFileResource.load('sounds/thud.wav');
box.components.set(new SpatialAudioComponent({ gain: -6 }));
box.playAudio(thud).onCompletion(() => setLanded(true));
Image-based light#
ImageBasedLightComponent supplies an environment (an equirectangular PNG,
JPEG or Radiance HDR, EnvironmentResource.load(url), or two blended), at
2 to the intensityExponent times its brightness, to the entities whose
ImageBasedLightReceiverComponent names it. The page prefilters it with
three.js; the native view makes RealityKit's EnvironmentResource from the
image.
import { EnvironmentResource, ImageBasedLightComponent, ImageBasedLightReceiverComponent } from '@swiftbrowser/reality/lighting';
const sky = new Entity();
sky.components.set(new ImageBasedLightComponent({ source: EnvironmentResource.load('sky.hdr'), intensityExponent: 1 }));
statue.components.set(new ImageBasedLightReceiverComponent({ imageBasedLight: sky }));
Custom meshes#
MeshResource.generate([...descriptors]) is RealityKit's
generate(from:), in the core (@swiftbrowser/reality/react): each
MeshDescriptor (a class, or a plain object with its fields) is a part with
positions, maybe normals (kept only when every part has one per vertex;
the page works them out otherwise) and textureCoordinates, its faces as
{ triangles }, { polygons: { counts, indices } } (fans) or
{ trianglesAndQuads: { triangles, quads } }, and materials as
{ allFaces: i } or { perFace: [...] } (a quad or polygon is one face, as
in Swift). The parts become one list of vertices and triangles ordered by
material, exactly as Swift orders them (packages/reality/src/meshes.ts), so
the mesh command carries the same bytes a Swift app's would; it goes once,
before the first model that draws the mesh, and again in a full frame. A
bad index or a part without positions throws a MeshGenerationError. Hit
tests meet the mesh's box. In a native app the view makes RealityKit's own
MeshResource.generate(from:) of the same vertices, a material per run.
import { Entity, MeshDescriptor, MeshResource, unlitMaterial } from '@swiftbrowser/reality/react';
const quad = new Entity('quad');
quad.model = {
mesh: MeshResource.generate([{
positions: [[-0.5, -0.5, 0], [0.5, -0.5, 0], [0.5, 0.5, 0], [-0.5, 0.5, 0]],
textureCoordinates: [[0, 0], [1, 0], [1, 1], [0, 1]],
primitives: { trianglesAndQuads: { triangles: [], quads: [0, 1, 2, 3] } },
}]),
materials: [unlitMaterial({ color: '#ff3b30' })],
};
Models from files#
A separate import, so a scene without models ships no loader:
@swiftbrowser/reality/models adds Entity.load, availableAnimations,
playAnimation and findEntity to the core's Entity when it is imported.
It does what Models describes for a Swift app, with the same
commands: await Entity.load(url) asks the view's host for the file's
outline (packages/reality/src/models.ts; a JavaScript scene never parses the
file, as Swift does not), and builds an entity for each node, depth first
under the returned root, a model of the file's own mesh (shape 8) and
materials for each mesh. The root sends asset, each node node before its
first entity, and playAnimation sends animate: the host plays the
clip, its controller pauses, resumes, changes speed (setSpeed) and stops
it, and onComplete hears its end (the time is kept in the scene). The
transforms the host's animation gives the nodes come back with each frame's
input and become the entities' own, not sent back, so an onUpdate handler
reads where a rotor is now. A material the app gives a node replaces the
file's, and hit tests meet a node's measured box.
import { Entity, RealityView } from '@swiftbrowser/reality/react';
import '@swiftbrowser/reality/models';
const windmill = await Entity.load('models/Windmill.usdz');
windmill.playAnimation(windmill.availableAnimations[0]!.repeat());
const rotor = windmill.findEntity('Rotor');
<RealityView make={(content) => content.add(windmill)} onUpdate={() => console.log(rotor?.orientation)} />
Which host loads the file, and what it reads:
- On a page
installRealityPageinstalls the loader: three.js's USD loader (assets.ts), so USDZ, USDC and USDA, a URL relative to the page. The outline and the views' copies share one load. glTF does not load (Swift's models are USD, and the page has one loader). - In a native app pass
callNativetoo:installRealityNative({ callNative, callNativeSync, onNativeEvent }).reality.asset, an async native function of SwiftBrowserReality, has RealityKit load the file (Entity(contentsOf:); a relative path is in the app's bundle, a remote URL is downloaded to a temporary file first) and answers the outline of RealityKit's own entity tree; the view places clones of that load, binds nodes by the same depth-first index, plays the root'savailableAnimationsby name, and reports the nodes they moved in the frame input. RealityKit reads USDZ, USDC, USDA and Reality files, not glTF. WithoutcallNative,Entity.loadrejects. The native half type-checks against the repository's RealityKit stand-in and has not yet run on a device or simulator.
The older synchronous loads and clone(recursive:) of a model are Swift's
alone so far; repeat(count) keeps Swift's behaviour for a model's clip (the
controller lasts count times as long; the host plays the clip once).
Entity gestures#
RealityView takes Swift's entity-targeted gestures as props
(packages/reality/src/gestures.ts, part of @swiftbrowser/reality/react):
import { InputTargetComponent, RealityView, quaternion, type Vector3 } from '@swiftbrowser/reality/react';
box.components.set(new InputTargetComponent());
let start: Vector3 = [0, 0, 0];
<RealityView
make={(content) => { content.add(camera); content.add(box); }}
onEntityTap={({ entity }) => entity.removeFromParent()}
onEntityDrag={({ entity, phase, translation3D }) => {
if (phase === 'began') start = [...entity.position];
if (translation3D) entity.position = [start[0] + translation3D[0], start[1] + translation3D[1], start[2] + translation3D[2]];
}}
onEntityMagnify={({ entity, magnification }) => (entity.scale = [magnification, magnification, magnification])}
onEntityRotate={({ entity, rotation }) => (entity.orientation = quaternion([0, 0, -1], rotation))}
onEntityLongPress={({ entity }) => (entity.opacity = 0.3)}
/>
They are SpatialTapGesture, DragGesture, MagnifyGesture,
RotateGesture and LongPressGesture with .targetedToAnyEntity(), made of
@swiftbrowser/react's own gesture modifiers on the view (onTapGesture,
dragGesture, magnifyGesture and rotateGesture as one pinch,
onLongPressGesture), so SwiftUI recognizes them in a native app and the
renderer on a page; the view is measured by a GeometryReader for the
camera's ray, as onTap's always was. The point the gesture reports becomes a
ray through the camera the view last drew with, and content.hitTest (the
models' boxes, or whatever a feature makes it test) finds the nearest entity
that takes input: it, or an ancestor, has an enabled InputTargetComponent.
targetedToEntity narrows them, to an entity (or anything under it) or the
nearest entity at or above the hit a predicate takes. A drag or a pinch keeps
the entity under its start until it ends, and a magnification and a rotation
of the same fingers share it. Each event has the entity, the points
(location, startLocation, translation), a phase (began, changed,
ended) for the lasting ones, and the gesture's own value (gestureValue).
rotation is in radians, clockwise on the screen as SwiftUI's. Where Swift on
visionOS has location3D, a drag here has startLocation3D, location3D and
translation3D on the plane through the entity that faces the camera (so
moving the entity by translation3D keeps it under the pointer), and its
ray for a plane of the app's own (rayPlaneIntersection);
convertPosition(point, from, to) takes a point between entities' spaces.
onTap still reports any entity with a model under a tap. A long press finds
its entity on a page only: the native renderer's long press sends no
location. With cameraControls, a drag on an entity turns the camera too.
Animations built in code#
import { AnimationResource, FromToByAnimation, OrbitAnimation } from '@swiftbrowser/reality/animation';
const orbit = AnimationResource.generate(new OrbitAnimation({ duration: 4, startTransform: { position: [1, 0, 0] } }));
const fade = AnimationResource.generate(new FromToByAnimation<number>({ from: 1, to: 0, bindTarget: 'opacity' }));
const controller = moon.playAnimation(AnimationResource.group([orbit.repeat({ count: 2 }), fade]), { transitionDuration: 0.3 });
controller.onComplete(() => moon.removeFromParent());
The animations of the Animation section, from JavaScript, as a
separate import (packages/reality/src/animation.ts): importing it adds
entity.playAnimation and entity.stopAllAnimations and registers the
content system that plays them, so an app that only moves entities does not
ship it. FromToByAnimation (from, to or by a transform, a number or a
vector, with a timing function, additive or not), SampledAnimation,
OrbitAnimation and AnimationGroup take their Swift initializers' labels as
options, with trimmed, repeated and repeatingForever;
AnimationResource.generate, sequence and group make resources, with
repeat({ count }) or repeat({ duration }). A transform animates the
entity's transform and a number its opacity, on the playing entity or a
descendant named through BindTarget.entity('Wheel').transform; other targets
keep time and change nothing, as in Swift. The content plays them each frame
after the entities' moves and before the update handlers, and only what they
change goes to the view as the transforms and opacities a frame always
carries. Delay, speed, offset, trims, the repeat modes, backwards fill and the
blend in over transitionDuration are honoured. The controller is a move's
(AnimationController, which now also pauses, resumes and takes a speed),
with entity and onTerminate; subscribeToAnimationEvents(content, AnimationEvents.PlaybackCompleted, handler, entity?) hears them across a
content. A new animation of a property stops the one before, a move(to:)
among them; a move stops a generated animation of the transform on the next
frame (Swift's does at once).
Physics#
import { Entity, MeshResource, RealityView, simpleMaterial } from '@swiftbrowser/reality/react';
import { CollisionComponent, CollisionEvents, PhysicsBodyComponent, ShapeResource } from '@swiftbrowser/reality/physics';
const ground = new Entity('ground');
ground.components.set(new CollisionComponent({ shapes: [ShapeResource.generateBox([4, 0.1, 4])] }));
ground.components.set(new PhysicsBodyComponent({ mode: 'static' }));
const crate = new Entity('crate');
crate.position = [0, 2, 0];
crate.model = { mesh: MeshResource.generateBox(0.3), materials: [simpleMaterial({ color: '#ff9500' })] };
crate.generateCollisionShapes(false);
crate.components.set(new PhysicsBodyComponent({ mass: 1, material: { friction: 0.8, restitution: 0.3 } }));
<RealityView
make={(content) => {
content.add(ground);
content.add(crate);
content.subscribe(CollisionEvents.Began, (event) => console.log('landed', event.impulse), crate);
}}
onTap={({ entity }) => entity?.applyLinearImpulse([0, 3, 0])}
/>
The engine is the Swift one ported to TypeScript (packages/reality/src/physics/), case for case, with the Swift tests ported too (packages/reality/test/physics*.test.ts), so a scene behaves the same whichever language builds it. It runs in the app's JavaScript and only moves entities' transforms, which the frames already carry: there is no wire command of its own, and it works on a page and in a native app alike.
- Components on
entity.components, as RealityKit's:CollisionComponent({ shapes, mode: 'default' | 'trigger', filter: { group, mask } }),PhysicsBodyComponent({ mode: 'dynamic' | 'static' | 'kinematic', shapes, mass | density | massProperties, material, isAffectedByGravity, linearDamping, angularDamping, isTranslationLocked, isRotationLocked, isContinuousCollisionDetectionEnabled }),PhysicsMotionComponent({ linearVelocity, angularVelocity })(in the parent's space; the simulation writes it back each step) andPhysicsSimulationComponent({ gravity, solverIterations })for a subtree;content.physics.gravityis the rest's. Shapes come fromShapeResource.generateBox,generateSphere,generateCapsuleandgenerateConvex(points | mesh)(offsetBymoves one), andentity.generateCollisionShapes(recursive)makes one from a model.PhysicsMaterialResource.generateandPhysicsMassProperties.fromShapeare there too; plain objects do for both. - Stepping is a content system (
registerContentSystem): each frame, after the moves and before theonUpdatehandlers, at a fixed sixtieth of a second. A body is simulated in the scene's space; one under a parent is given back the transform relative to it. A frame shorter than a step (a 120 Hz display) steps nothing and announces nothing, so touches do not flicker and impulses are not lost. - Pushing:
entity.addForce(force, relativeTo?),addForce(force, at, relativeTo?),addTorque,applyLinearImpulse,applyAngularImpulse,applyImpulse(impulse, at, relativeTo?),clearForcesAndTorquesandresetPhysicsTransform;isSleeping(entity)says whether a body rests. - Events:
content.subscribe(CollisionEvents.Began | Updated | Ended, handler, on?)returns the function that stops it, asonUpdatedoes. - Queries:
content.physics.raycast({ origin, direction, length }, options),raycast(from, to, options)andconvexCast(shape, { fromPosition, fromOrientation, toPosition, toOrientation }, options), with{ query: 'nearest' | 'all' | 'any', mask, relativeTo }, answer{ entity, position, normal, distance, shapeIndex }nearest first.content.hitTest(and soonTap) hits collision shapes. - Joints:
entity.pins.set(name, { position, orientation, relativeTo }), thennew PhysicsRevoluteJoint({ pin0, pin1, angularLimit }),PhysicsSphericalJoint,PhysicsPrismaticJoint,PhysicsFixedJoint,PhysicsDistanceJointorPhysicsCustomJoint, andaddToSimulation().
The Showcase's Tower (Native/Examples/Showcase/src/tower) is a whole example: a stacking game whose rules are plain TypeScript, drawn by three.js on its web page and by RealityKit in its iOS and Mac app. The native half builds with Xcode for the iOS simulator and the Mac (native.yml builds the package and the Showcase app), and has not yet run on a device or a simulator.
Next phases#
- Input. A
GameControllerstand-in over the Gamepad API and the keyboard (GCController,GCKeyboard), sent with each frame as the camera is. - Looking at WebGPU on real GPUs, in the browsers that have it (Chrome, Edge, Safari 26), against the WebGL renderer, before trusting it as the default.