# Scenery Scripting -- API Reference, runtime types (v0.5.0) Types the JavaScript runtime defines: object descriptors and traits, materials, anchors, animation builders, plus the global functions, static extensions, the `UI` view builders and the objects on `scene` such as `scene.camera` and `scene.gameController`. Sibling bundle (engine types -- entities, scene, meshes, GPU): https://scenery.app/docs/scripting/api/llms-full.txt Sibling bundle (concepts, how-to, worked examples): https://scenery.app/docs/scripting/guide/llms-full.txt Global instances available in every script without declaration: - `experience` -- `Experience` - `scene` -- `Scene` - `environment` -- `Environment` - `http` -- `HTTP client (promisified). Methods: get(url, options?), post(url, body, options?), request(url, options). All return Promise<{status, data}>` - `websocket` -- `WebSocket client. Methods: connect(url, options?) returns WebSocket` - `secrets` -- `Secrets. Methods: mint(name, params?) returns Promise<{value, expiresAt, provider}>. For ordinary REST use `http.request(url, { secret })` instead, which never puts a credential on the device` - `httpClient` -- `HTTPClient (low-level, callback-based -- prefer `http` instead)` - `secretsClient` -- `SecretsClient (low-level, callback-based -- prefer `secrets` instead)` - `webSocketManager` -- `WebSocketManager (low-level -- prefer `websocket` instead)` Any docs page is also available as raw markdown by appending `.md` -- e.g. https://scenery.app/docs/scripting/api/mesh.md, https://scenery.app/docs/scripting/guide/examples.md. Authoritative for runtime v0.5.0. If an API is not listed here or in the sibling bundles, it does not exist in this version -- do not invent signatures. --- ## Runtime Classes ### `Anchor` Anchor types for object placement **Static Methods:** - `Anchor.position(xOrVector: Vector3 | number, y: number, z: number)` → `Object` - Anchor at fixed world position - `xOrVector`: Position vector or X coordinate - `y`: Y coordinate (if first param is number) - `z`: Z coordinate (if first param is number) - `Anchor.geoLocation(latitude: number, longitude: number, altitude: number)` → `any` - Anchor at geographic location - `Anchor.camera(xOrVector: Vector3 | number, y: number, z: number, lerpFactor: number)` → `any` - Anchor relative to camera - `xOrVector`: Offset vector or X coordinate - `y`: Y coordinate (if first param is number) - `z`: Z coordinate (if first param is number) - `lerpFactor`: Smoothing factor - `Anchor.currentPOV(xOrVector: Vector3 | number, y: number, z: number, resetRotation: boolean)` → `Object` - Anchor at user's current point of view (captures current camera position) - `xOrVector`: Offset vector or X coordinate - `y`: Y coordinate (if first param is number) - `z`: Z coordinate (if first param is number) - `resetRotation`: If true, object faces forward instead of matching camera - `Anchor.screenSpace(options: Object, options.alignment: string, options.insets: number | Object, options.respectsSafeArea: boolean)` → `Object` - Anchor a UI panel in screen space -- a flat 2D overlay pinned to a screen edge or corner, rather than a plane placed in the world. Use for HUDs and controls that should stay put wherever the viewer looks. - `options.alignment`: Where the panel sits: `"center"`, `"top"`, `"bottom"`, `"leading"`, `"trailing"`, or a corner (`"topLeading"`, `"topTrailing"`, `"bottomLeading"`, `"bottomTrailing"`). - `options.insets`: Gap from the screen edges, in points. A number applies to all sides; `{ top, leading, bottom, trailing }` sets each. - `options.respectsSafeArea`: Stay clear of notches, home indicators, and system bars. - `Anchor.horizontalPlane(classification: string, minWidth: number, minHeight: number)` → `Object` - Anchor on detected horizontal plane (floor, table, etc.) - `classification`: Surface type: "floor", "table", "seat", "ceiling" - `minWidth`: Minimum plane width in meters - `minHeight`: Minimum plane depth in meters - `Anchor.verticalPlane(classification: string, minWidth: number, minHeight: number)` → `any` - Anchor on vertical plane - `classification`: "wall", "window", "door" - `Anchor.hand(chirality: string, joint: string, trackingScope: string, lerpFactor: number, providesDiscoveryHint: boolean)` → `Object` - Anchor to user's hand (visionOS hand tracking) - `chirality`: "left" or "right" hand - `joint`: Hand joint: "wrist", "thumbTip", "indexFingerTip", "middleFingerTip", etc. - `trackingScope`: "full", "position", or "orientation" - `lerpFactor`: Smoothing factor (0-1, lower = smoother) - `providesDiscoveryHint`: Show visual hint for hand tracking - `Anchor.accessory(options: Object, options.kind: string, options.hand: string, options.location: string, options.offset: Transform | Object, options.smoothing: number, options.trackingMode: string)` → `Object` - Anchor to a spatial accessory: a stylus or a tracked spatial controller (Apple Vision Pro). The object hides while the accessory isn't tracked and moves to another match when it disconnects. Where `environment.features.has('accessoryTracking')` is false it stays hidden. - `options.kind`: `"stylus"` or `"spatialController"`; left out, any accessory matches. - `options.hand`: `"left"` or `"right"`: a controller's own side, the hand holding a stylus. Left out, either hand matches. - `options.location`: `"aim"` (stylus tip, controller aim) or `"grip"` (where the hand holds a controller). A stylus has only an aim; asking for its grip uses the aim. - `options.offset`: Offset from the location, in its space; -z points along the aim. - `options.smoothing`: Fraction of the way to the new pose per frame, 0 to 1; lower is smoother. Left out, the object follows without delay. - `options.trackingMode`: `"predicted"` (lowest latency, can overshoot on jerky moves) or `"continuous"` (more accurate, more latency). - `Anchor.image(imageUrl: string, physicalWidth: number, identifier: string, orientation: string, tracksContinuously: boolean, hideIfTrackingLost: boolean, providesDiscoveryHint: boolean)` → `Object` - Anchor to image marker (image tracking) - `imageUrl`: URL to reference image for tracking - `physicalWidth`: Real-world width of the image in meters - `identifier`: Optional unique identifier - `orientation`: Expected orientation: "horizontal" or "vertical" - `tracksContinuously`: Continue tracking after initial detection - `hideIfTrackingLost`: Hide object when image not visible - `providesDiscoveryHint`: Show visual hint to find image ### `Material` Chainable builder for an inline material. Seven kinds: `unlit`, `pbr`, `occlusion`, `customShader`, `materialX`, `video`, `transmission`. Use the matching factory (`Material.unlit({...})`, etc.) or `new Material(kind)`. Properties map to the underlying material data model with web-standard names: - Colors: `color`, `emissive`, `sheenColor`, `specularColor` -- flat tint. - Maps: `map`, `emissiveMap`, `roughnessMap`, `metalnessMap`, `normalMap`, `aoMap`, `specularMap`, `sheenMap`, `clearcoatMap`, `alphaMap` -- textures accept either a URL/asset-id string or `{ texture, scale }`. - Scalars: `roughness`, `metalness`, `clearcoat`, `opacity`, `emissiveIntensity`. - Rendering: `opaque`, `transparent`, `opacityThreshold`, `blendMode`, `faceCulling`, `wireframe`, `writesDepth`, `readsDepth`. **Static Methods:** - `Material.unlit(opts: Object)` → `Material` - Flat-shaded material. Renders the surface color regardless of scene lighting -- useful for UI, billboards, vertex-colored point clouds, etc. - `opts`: Any chainable setter name as a key: `color`, `map`, `opacity`, `alphaMap`, `disableToneMapping`, `faceCulling`, `blendMode`, `wireframe`, `target`, `name`. - `Material.pbr(opts: Object)` → `Material` - Physically-Based material -- the realistic-rendering default for surfaces that should respond to scene lighting. - `opts`: `color`, `map`, `emissive`, `emissiveMap`, `emissiveIntensity`, `metalness`, `metalnessMap`, `roughness`, `roughnessMap`, `normalMap`, `aoMap`, `sheenColor`, `sheenMap`, `specularColor`, `specularMap`, `clearcoat`, `clearcoatMap`, `opacity`, `alphaMap`, `opacityThreshold`, plus rendering state. - `Material.occlusion(opts: Object)` → `Material` - Occlusion material -- invisible itself but hides geometry behind it. Use for matte holdouts, real-world geometry masks, portals. - `opts`: `receivesDynamicLighting`, `faceCulling`. - `Material.customShader(opts: Object)` → `Material` - Custom shader material -- author-supplied surface shader and/or geometry modifier from a compiled shader library. - `opts`: `shaderLibrary`, `lightingModel`, `surfaceShader`, `geometryModifier`, plus general rendering state. - `Material.materialX(opts: Object)` → `Material` - MaterialX material from a bundled `.usdz`. Reference by file path plus the `/Root/` path inside. - `opts`: Typically use `.materialXAsset(urlOrId, name)` followed by `.setParameter(name, value, typeHint?)` calls. - `Material.video()` → `Material` - Video texture material. Use `.videoSource(urlOrId)` for the playback source and `.videoOptions({ loops, streamContent, volume })` for playback config. - `Material.transmission(opts: Object)` → `Material` - Transmission material -- glass, water or ice that refracts the scene behind it. Refracts on iPhone, iPad and Mac; on Apple Vision Pro it draws tinted and frosted, without refraction. - `opts`: `transmissionOptions`, plus rendering state such as `faceCulling`. **Instance Methods:** - `opacity()` → `any` - Material opacity. Values < 1 also flip `isOpaque` to `false` so the blending state matches. - `transmissionOptions()` → `any` - Transmission settings. Every key is optional and keeps its default when left out: `ior` (1 to 2.333, default 1.5), `thickness` (fraction of the object's largest side, 0.4), `roughness` (0 clear to 1 frosted, 0.25), `dispersion` (0), `distortion` (0), `distortionScale` (0.5), `temporalDistortion` (0), `attenuationColor` and `tint` (colors, white), `attenuationDistance` (fraction of the largest side, 0 = no absorption), `specular` (0), `clearcoat` (0), `lit` (default `true`). - `shaderTexture(name: string, texture: string | Texture | any)` → `Material` - Bind a texture to one of a shader's named texture slots: a slot in an authored shader's header, or a texture input of a MaterialX material. Takes the same inputs as `.map()`, and a dynamic texture keeps updating in the slot, so a video or camera feed drives the shader frame by frame. - `name`: The slot's name. - `texture`: URL, asset id or texture handle. - `materialXAsset()` → `any` - MaterialX: URL or asset id of the .usdz, plus the path to the material inside it (e.g. `"/Root/MyMaterial"`). - `setParameter(name: string, value: any, typeHint: Object)` → `Material` - Set a constant value on a shader parameter. Works on `customShader` and `materialX` kinds -- routes to the right options blob automatically. Warns and no-ops on kinds without shader parameters. For runtime variable bindings, use `entity.representation.bindMaterialParameter(name, variableId, opts?)`. - `name`: Material parameter name (case-sensitive, must match the name the material exposes). - `value`: Number, boolean, string, array (vec2/3/4), color-like object (`'#RRGGBB'`, `{r,g,b,a?}`, `{colorSpace,hex}`), or a `Transform` for a Matrix parameter, which receives its 4×4 matrix. The matrix holds position, rotation and scale only, so it carries no shear. - `typeHint`: Override inferred type: `{ type: "float" | "int" | "vector2" | "vector3" | "vector4" | "matrix4x4" | "color" | "boolean" | "string" }`. - `clone()` → `any` - Deep-copy the material with a fresh `id`. Use for the get → clone → tweak → apply pattern when overriding a library material for a single entity without mutating the library entry. - `toString()` → `any` - Useful per-kind summary for `console.log(mat)` -- includes kind, id, name, and the meaningful state set on the material (channel colors, scalar values, shader params, etc.) so authors can see "what's on this material" at a glance. For the full serialized shape, use `JSON.stringify(mat, null, 2)`. ### `Instances` Instance-data handles for `rep.setInstances(...)` / `entity.setInstances(...)` -- GPU mesh instancing draws one copy of a mesh per transform, far cheaper than real entities. Instances are rendering-only (no physics, collision, or per-instance identity); use `clone()` for objects the user interacts with. Gate with `environment.features.has('instancing')`. **Static Methods:** - `Instances.transforms(list: Array)` → `Object` - Build an instance-data handle from a list of transforms. Each entry is a `Transform` (full pose) or a `Vector3` (a copy placed at that position). A bare array is also accepted -- `setInstances([...])` is sugar for `setInstances(Instances.transforms([...]))`. - `list`: Per-instance transforms. ### `Texture` GPU-only / runtime-managed texture. Authors construct via the static factories below; the returned handle is opaque and passes to material parameters (future) and compute kernel `inputTextures` / `outputTextures` maps (today, for `Texture.compute(...)` only). **Static Methods:** - `Texture.compute(options: Object, options.pixelFormat: string, options.textureType: string, options.width: number, options.height: number, options.depth: number, options.arrayLength: number, options.mipmapLevelCount: number, options.semantic: string, options.usage: Array)` → `Promise` - Allocate a GPU-only texture written by a compute kernel. Supports 2D, 3D, cube, and array textures with optional mipmap chains. Async because the dynamic-texture asset-provider funnel allocates the underlying GPU resource and registers it in the runtime's manager cache (so material binding finds the same instance later). Authors `await` once at allocation; subsequent kernel dispatches are sync. - `options.pixelFormat`: e.g. `'rgba32Float'`, `'rgba16Float'`, `'r32Float'`. - `options.textureType`: `'2d' | '3d' | 'cube' | '2dArray' | 'cubeArray'`. - `options.depth`: Slice count for 3D textures. - `options.arrayLength`: Layer count for arrays. - `options.mipmapLevelCount`: Set > 1 + call `texture.generateMipmaps()` to populate. - `options.semantic`: `'color' | 'normal' | 'scalar' | 'hdrColor' | 'raw'`. Tells material binding how to sample (sRGB vs linear, etc.). - `Texture.fromAsset(idOrName: string)` → `Promise` - A texture from the experience's Library > Textures, by its id or its name. A texture its shader draws can be bound with `.read` and on materials; its `.write` is refused, since the shader owns its contents. Any other Library texture a kernel may also write. The texture belongs to the experience, so `destroy()` only drops this handle. - `idOrName`: The texture's id, or its name when no other Library texture shares it. - `Texture.image(urlOrId: string, options: Object, options.semantic: string, options.scale: number, options.steps: Array)` → `Promise` - Static image-asset texture. Reads an image asset (PNG / JPG / etc.) from the experience's asset library or an absolute URL and binds it as a sampleable texture -- typical use is a hand-painted normal map or albedo map fed to `Material.pbr({ normalMap: tex })`. - `urlOrId`: HTTPS URL or asset id from the project library. - `options.semantic`: `'color' | 'normal' | 'scalar' | 'hdrColor' | 'raw'`. Tells material binding how to sample (sRGB vs linear). - `options.scale`: The picture's size as a fraction of the source's, more than 0 and at most 1, such as `0.5` for half. - `options.steps`: Processing steps, run in order: `{ blur: radius }` in pixels, `{ thresholdToZero: value }` from 0 to 1, `{ radialZoomBlur: amount }` from 0 to 1, or `{ shader: assetId }` for a texture shader. - `Texture.video(urlOrId: string, options: Object, options.semantic: string, options.loops: boolean, options.autoplays: boolean, options.volume: number, options.streamContent: boolean, options.isShared: boolean, options.scale: number, options.steps: Array)` → `Promise` - Video-asset texture. Plays a video file (mp4 / mov) as a sampleable texture and binds it to a material -- typical use is a looping background, an animated diorama, or a UI-overlay video sticker. The video starts playing automatically by default. Pass `{ autoplays: false }` and call `videoTexture.play()` later when the entity becomes visible. - `urlOrId`: HTTPS URL or asset id from the project library. - `options.semantic`: `'color' | 'normal' | 'scalar' | 'hdrColor' | 'raw'`. - `options.loops`: Restart from frame 0 on end. - `options.autoplays`: Start playback as soon as the asset is ready. - `options.volume`: Linear gain (0..1). Unset = system default. - `options.streamContent`: HTTP streaming vs. download-then-play. - `options.isShared`: SharePlay sync -- when true, playback time syncs across session participants. - `options.scale`: The picture's size as a fraction of the source's, as on `Texture.image`. - `options.steps`: Processing steps, as on `Texture.image`. - `Texture.background(options: Object, options.semantic: string, options.scale: number, options.steps: Array)` → `Promise` - The scene background as a sampleable texture: what is behind the scene, as a regular texture handle. Typical uses are first-person portal effects, augmented-reality color grading on detected planes, or piping the background into a compute kernel for a real-time filter. In AR on iPhone and iPad it is the camera image. On Mac it is the scene's background, so a material sampling it at `context.backgroundUV` lines up with what is behind it; resize and filter settings and mipmaps do not apply there. Outside AR on iPhone and iPad it stays black. Not on visionOS. Always gate with `environment.features.has('background')`. - `options.scale`: The picture's size as a fraction of the source's, as on `Texture.image`. - `options.steps`: Processing steps, as on `Texture.image`. - `Texture.cameraFeed(options: Object, options.semantic: string)` → `Promise` - The scene background, under its earlier name. ### `Kernel` Opaque handle to a compiled GPU compute kernel. Authors construct via `Kernel.fromSource(...)` or `Kernel.fromAsset(...)`, then pass to `mesh.runCompute(kernel, options)`. **Static Methods:** - `Kernel.fromSource(options: Object, options.source: string, options.functionName: string)` → `Promise` - Compile a compute kernel from inline MSL source. Handy for prototypes and tests; production scripts should prefer `Kernel.fromAsset(...)` so the source lives in the experience's asset library. - `options.source`: MSL source string. - `options.functionName`: Kernel entry-point name. - `Kernel.fromAsset(options: Object, options.assetId: string, options.functionName: string)` → `Promise` - Compile a compute kernel from a shader-library asset declared in the experience's asset library. A compute shader with a header names its own entry point, and the options of `kernel.run` and `mesh.runCompute` bind by the names in that header. - `options.assetId`: Shader-library asset id. - `options.functionName`: Kernel entry-point name. Required unless the shader has a header. ### `Buffer` Raw GPU buffer for compute kernels. Construct via the static factories below; pass the handle to `mesh.runCompute(...)`'s `inputBuffers` / `outputBuffers` maps to bind it as a kernel argument. **Static Methods:** - `Buffer.float32(length: number, initialValue: number)` → `Buffer | null` - Allocate a Float32-typed GPU buffer. - `length`: Element count (not bytes). - `initialValue`: Optional seed value for all elements. - `Buffer.uint32(length: number, initialValue: number)` → `Buffer | null` - Allocate a Uint32-typed GPU buffer. - `length`: Element count (not bytes). - `initialValue`: Optional seed value for all elements. - `Buffer.uint8(length: number, initialValue: number)` → `Buffer | null` - Allocate a Uint8-typed GPU buffer. - `length`: Element count (not bytes). - `initialValue`: Optional seed value for all elements. - `Buffer.atomic(initialValue: number)` → `Buffer | null` - Allocate a single-element atomic-uint counter -- common pattern for marching-cubes' triangle emitter, particle compaction, etc. - `initialValue`: Counter seed. ### `ObjectTraits` Builder object passed to the compatibility-only `.traits(t => ...)` callback. New code should skip this entirely and use the direct descriptor methods (`.physics(...)`, `.material(...)`, `.shadow(...)`, `.gestures(...)`, `.transform(...)`, `.opacity(...)`, `.fittingBox(...)`, `.pivot(...)`, `.revealAnimation(...)`, `.removalAnimation(...)`, `.hideByDefault(...)`, `.flatten(...)`), which expose the same configuration and chain. **Instance Methods:** - `transform(transform: Transform)` → `ObjectTraits` - Set initial transform - `transform`: Transform object - `fittingBox(size: number)` → `ObjectTraits` - Scale model to fit within a cubic bounding box - `size`: Maximum dimension in meters (model will fit inside this cube) - `pivot(pivot: string)` → `ObjectTraits` - Set pivot adjustment - `pivot`: which face of the model sits at its origin: "automatic", "top", "center", "bottom", "left", "right", "front", or "back". "back" seats a model flat against a wall the way "bottom" stands one on a floor. - `revealAnimation(animation: Object | string | boolean, animation.style: string, animation.duration: number, animation.scaleFactor: number)` → `ObjectTraits` - Choose how the object animates in when it appears. Mirrors the editor's Reveal Animation picker, so a script-created object can look like an authored one. Omit it and the object uses the app default, the same as the picker's "Default". - `animation`: A style name, an options object, or `false` for no animation at all (`true` restores the app default). - `animation.style`: `"default"` (the app's own reveal), `"disabled"` (appear instantly), `"fade"`, or `"fadeAndScale"` (fades in while growing from `scaleFactor`). - `animation.duration`: Seconds, for `"fade"` and `"fadeAndScale"`. - `animation.scaleFactor`: The fraction of full size the object grows from, for `"fadeAndScale"`. - `removalAnimation(animation: Object | string | boolean)` → `ObjectTraits` - Choose how the object animates out when it is removed. Same options as ObjectTraits.revealAnimation, and mirrors the editor's Removal Animation picker. - `hideByDefault(hidden: boolean)` → `ObjectTraits` - Hide the object when it is first added to the scene, so a script can prepare it before anyone sees it. Mirrors the editor's Hide By Default toggle. The object still loads: its representation is built and its physics body precomputed, it is simply not shown and its physics stays paused. Bring it up with `scene.toggle([entity], true)`, which reveals a batch on a single frame. - `hidden`: `true` to start hidden, `false` for the normal behaviour. - `flatten(flatten: boolean)` → `ObjectTraits` - Load a model as one mesh instead of its authored node tree. Mirrors the editor's Flatten toggle. Models only. `setInstances` needs it, since instancing works on a single mesh. The cost is the hierarchy: once flattened, `findChild`, `getChildNames` and per-node material targeting have no nodes to work with. - `flatten`: `true` to collapse the model, `false` to keep its nodes. - `opacity(opacity: number)` → `ObjectTraits` - Set opacity adjustment - `opacity`: Opacity value (0.0 to 1.0) - `shadow(options: Object, options.directional: boolean, options.grounding: boolean | Object)` → `ObjectTraits` - Configure how this object interacts with the scene's two shadow systems. Mirrors `t.physics({...})` / `t.gestures({...})`: pass only the keys you want to change. - `options.directional`: Cast a shadow from the scene's directional light (the main projected shadow). Set `false` where it isn't wanted -- e.g. a dense instanced field, whose many small copies alias the shared shadow map into streaks. - `options.grounding`: The soft AR contact shadow beneath the object. `true` to cast it, or an object to configure: `{ casts?: boolean, receives?: boolean, fadeNearObjects?: boolean }` -- `receives` takes grounding shadows cast by other objects; `fadeNearObjects` fades the shadow as it approaches detected physical surfaces (otherwise constant). - `material(materialOrId: string | Material, target: Object, target.type: string, target.models: Array, target.materialSlots: Array)` → `ObjectTraits` - Apply a material -- either a library reference by ID or an inline Material instance. - `materialOrId`: Library material ID, or a Material instance. - `target`: Optional target override. - `target.type`: "allModels", "firstModel", or "selectedModels" - `target.models`: Array of model names (for selectedModels) - `target.materialSlots`: Material slot indices - `physics(options: Object, options.mode: string, options.shape: string | Object, options.mass: number, options.density: number, options.gravity: boolean, options.linearDamping: number, options.angularDamping: number, options.friction: number, options.restitution: number, options.translationLock: Object, options.rotationLock: Object)` → `ObjectTraits` - Give the object a physics body so it can collide, fall, and be pushed. Mirrors the editor's Physics inspector, so anything set here stays visible and editable there. Sub-groups are written only when you supply at least one of their keys -- `t.physics({ mode: 'static' })` produces a plain static body with no mass, damping, or material overrides. Physics also needs scene-level setup: enable the floor mesh and scene mesh collisions in the scene's settings, or bodies will fall forever. - `options.mode`: `"static"` (never moves, others collide with it), `"dynamic"` (gravity, impulses, collisions), or `"kinematic"` (you move it; it pushes others but isn't pushed). - `options.shape`: Collision shape: `"box"`, `"sphere"`, `"convex"` (hull of the object's geometry), or `{ capsules: [{ from, to, radius }] }`: capsules between two points in the object's own space, in metres. Capsules can follow a shape a convex hull would fill in, such as a ring, and they may overlap. - `options.mass`: Mass in kilograms. Omit for the default. - `options.density`: Kilograms per cubic metre, so the mass follows the shape's volume. Ignored when `mass` is given. - `options.gravity`: Whether the body reacts to gravity. - `options.linearDamping`: How quickly movement slows on its own, like drag. - `options.angularDamping`: How quickly spin slows on its own. - `options.friction`: Resistance to sliding. - `options.restitution`: Bounciness. `0` lands with a thud. - `options.translationLock`: `{ x, y, z }` booleans constraining movement. - `options.rotationLock`: `{ x, y, z }` booleans constraining rotation. - `gestures(options: Object, options.drag: Object | boolean, options.rotate: Object | boolean, options.resize: Object | boolean, options.releaseBehavior: string, options.momentumScale: number, options.angularMomentumScale: number, options.disableAudio: boolean)` → `ObjectTraits` - Let the user move, rotate or resize this object with a gesture, and choose what happens when they let go. Omit a gesture to leave it disabled -- an object with no gestures configured cannot be manipulated at all. - `options`: Gesture configuration. - `options.drag`: Drag/move the object. `true` enables it on all axes, or pass `{ axes: { x, y, z } }` to restrict which axes it may move along. - `options.rotate`: Rotate the object. `true` enables it on all axes, or pass `{ axes: { x, y, z } }`. - `options.resize`: Scale the object. `true` enables it on all axes, or pass `{ axes: { x, y, z }, minScale, maxScale }`. - `options.releaseBehavior`: What the object does when released: - `'stay'` -- stays where it was let go, then falls under gravity if it has a dynamic body. - `'reset'` -- animates back to where the gesture started. - `'momentum'` -- keeps the motion the gesture gave it. A flick throws it; a slow release lets it drift. Requires a dynamic physics body. - `options.momentumScale`: Scales the released linear velocity when `releaseBehavior` is `'momentum'`. `1.0` is the object's true world-space speed, which usually feels too fast on a touchscreen -- a finger flick maps to a large velocity once projected out to the object's distance. Lower it for a gentler toss. - `options.angularMomentumScale`: Scales the released spin. Kept below the linear scale because gesture-derived spin is noisy and tumbles heavily at full strength. - `options.disableAudio`: Suppress the built-in interaction sound. - `set(path: string, value: any)` → `ObjectTraits` - Directly set a property path in traits - `path`: Dot-separated path (e.g., "modelAdjustments.flatten") - `value`: Value to set - `build()` → `Object` - Build and return the traits object ### `ObjectDescriptor` Descriptor for creating scene objects dynamically **Properties:** - `id`: `string` (read-only) - The object's id. Read-only -- set at construction (or preserved by `scene.getObjectDescriptor`, re-minted by `.clone()`). Use it to look the object up later, e.g. `scene.findEntity(descriptor.id)` after `scene.createEntity(descriptor)`. - `kind`: `string | null` (read-only) - The object's representation kind: `'model'` | `'primitive'` | `'visualMedia'` | ... , or `null` if the object has no representation. Read-only. Lets a script branch on what it fetched before editing -- e.g. `if (d.kind === 'model') d.asset(hi)`. **Instance Methods:** - `name(value: string)` → `ObjectDescriptor` - Set the object name - `anchor(anchor: Object)` → `ObjectDescriptor` - Set the anchor - `anchor`: Anchor descriptor created by Anchor static methods - `asset(urlOrId: string)` → `ObjectDescriptor` - Set / replace the object's **source asset**, kind-routed to the right field (`model` → the model asset, image / video / GIF → the media source). Same-kind swap only -- it does **not** change the object's kind: pointing a model at a video URL gives a broken model, not a video (use `.representation(...)` to change kind). Warns for kinds with no source (primitive, container). Accepts an HTTPS URL or an asset id from the project. - `representation(sourceDescriptor: ObjectDescriptor)` → `ObjectDescriptor` - Fully replace this object's visual **representation** with the one from a freshly built descriptor (`createBox`, `createModel`, `createVideo`, ...) -- the clean way to change kind (model → primitive, model → video). Keeps this object's identity and wiring: its id, representation id, anchor (placement), and events. Takes the source's `kind` **and its traits** -- configure the new look via the factory chain, e.g. `d.representation(createBox(0.1,0.1,0.1).gestures({ drag: true }))`. Note: the authored **transform trait** rides inside the old kind and is dropped by the swap ("keeps placement" means the anchor, not the transform) -- re-apply via the source chain if needed. Element-level fields on the source (`.name()`, `.anchor()`, events) are ignored; only its representation is taken. - `clone()` → `ObjectDescriptor` - Deep-copy this descriptor with a **fresh id graph** (element id + every nested representation id + events), so it can be added alongside the original without an id collision. Use it to spawn variants of an authored object: `scene.getObjectDescriptor({ name: 'can' }).clone().transform({ position: p })`, then `scene.createEntity(...)`. The copy inherits the original's events (re-wired to the copy); clear them with `copy.data.events = []` if unwanted. - `traits(configureFn: function)` → `ObjectDescriptor` - Configure traits via a callback. Traits already on the descriptor (e.g. from `createMesh({ materials: [...] })`) are preserved -- calls add on top. - `configureFn`: Function that receives an ObjectTraits builder. - `physics(options: Object)` → `ObjectDescriptor` - Give this object a physics body. See ObjectTraits.physics for the full options. - `options`: `{ mode, shape, mass, friction, restitution, ... }`. - `gestures(options: Object)` → `ObjectDescriptor` - Enable manipulation gestures (drag / rotate / resize). See ObjectTraits.gestures. - `options`: `{ drag, rotate, resize, releaseBehavior, ... }`. - `material(materialOrId: string | Material, target: Object)` → `ObjectDescriptor` - Apply a material -- a library id or an inline `Material`. See ObjectTraits.material. - `target`: Optional model / slot target. - `shadow(options: Object)` → `ObjectDescriptor` - Configure the object's shadows (directional + grounding). See ObjectTraits.shadow. - `options`: `{ directional, grounding }`. - `transform(transform: Object)` → `ObjectDescriptor` - Set the object's transform (position / rotation / scale). See ObjectTraits.transform. - `opacity(opacity: number)` → `ObjectDescriptor` - Set the object's opacity (0-1). See ObjectTraits.opacity. - `fittingBox(size: number)` → `ObjectDescriptor` - Scale a model to fit a box of the given size. See ObjectTraits.fittingBox. - `pivot(pivot: string)` → `ObjectDescriptor` - Adjust the model's pivot. See ObjectTraits.pivot. - `revealAnimation(animation: Object | string | boolean)` → `ObjectDescriptor` - Choose how this object animates in when it appears. See ObjectTraits.revealAnimation. - `animation`: A style name, `{ style, duration, scaleFactor }`, or `false` for no animation. - `removalAnimation(animation: Object | string | boolean)` → `ObjectDescriptor` - Choose how this object animates out when it is removed. See ObjectTraits.removalAnimation. - `hideByDefault(hidden: boolean)` → `ObjectDescriptor` - Start this object hidden, to be brought up with `scene.toggle`. See ObjectTraits.hideByDefault. - `flatten(flatten: boolean)` → `ObjectDescriptor` - Load this model as one mesh rather than its node tree. See ObjectTraits.flatten. ### `EntityAnimation` Entity animation factory - create animation descriptors for use with entity.play() **Static Methods:** - `EntityAnimation.to(toProperties: Object, duration: number, options: Object)` → `EntityAnimation` - Animate to target properties - `toProperties`: Target properties (position, rotation, scale, opacity) - `duration`: Duration in seconds - `options`: Animation options (timingFunction, delay, etc.) - `EntityAnimation.fromTo(fromProperties: Object, toProperties: Object, duration: number, options: Object)` → `EntityAnimation` - Animate from starting to target properties - `fromProperties`: Starting properties - `toProperties`: Target properties - `duration`: Duration in seconds - `options`: Animation options - `EntityAnimation.by(byProperties: Object, duration: number, options: Object)` → `EntityAnimation` - Animate by relative values - `byProperties`: Relative change values - `duration`: Duration in seconds - `options`: Animation options - `EntityAnimation.fromBy(fromProperties: Object, byProperties: Object, duration: number, options: Object)` → `EntityAnimation` - Animate from starting properties by relative values - `fromProperties`: Starting properties - `byProperties`: Relative change values - `duration`: Duration in seconds - `options`: Animation options - `EntityAnimation.spin(revolutions: number, duration: number, options: Object, options.axis: Array)` → `EntityAnimation` - Spin animation - rotate around local axis - `revolutions`: Number of full rotations - `duration`: Duration in seconds - `options`: Animation options - `options.axis`: Local rotation axis [x, y, z] - `EntityAnimation.orbit(config: Object, config.axis: Array | Vector3, config.rotationCount: number, config.clockwise: boolean, config.orientToPath: boolean, config.startTransform: Object, duration: number, options: Object)` → `EntityAnimation` - Orbit animation - rotate around a point - `config`: Orbit configuration - `config.axis`: Rotation axis - `config.rotationCount`: Number of orbits - `config.clockwise`: Spin direction - `config.orientToPath`: Face movement direction - `config.startTransform`: Starting offset transform. `rotation` accepts a `Rotation` or a `Vector3` of euler angles (radians). - `duration`: Duration in seconds - `options`: Animation options - `EntityAnimation.keyframes(frames: Array, duration: number, options: Object, options.tweenMode: string)` → `EntityAnimation` - Keyframe animation - animate through multiple property states - `frames`: Array of property states - `duration`: Total duration in seconds - `options`: Animation options - `options.tweenMode`: "linear" or "hold" - `EntityAnimation.model(name: string, options: Object, options.trimStart: number, options.trimEnd: number, options.duration: number)` → `EntityAnimation` - Play embedded model animation (USDZ animations) - `name`: Animation name (optional, plays default if omitted) - `options`: Options - `options.trimStart`: Trim from start (seconds) - `options.trimEnd`: Trim from end (seconds) - `options.duration`: Override duration - `EntityAnimation.group(animations: Array, options: Object)` → `EntityAnimation` - Group multiple animations to play together - `animations`: Array of EntityAnimation objects - `options`: Animation options (applied to group) - `EntityAnimation.emphasize(style: string, duration: number, options: Object)` → `EntityAnimation` - Emphasize animation - attention-grabbing effect - `style`: "bounce", "pulse", "wiggle", etc. - `duration`: Duration in seconds - `options`: Animation options ### `GeoCoordinate` A geographic coordinate. Construct one for a point of interest, or receive a live fix from `environment.location.current()` (which additionally populates `horizontalAccuracy` and `timestamp`). **Properties:** - `latitude`: `number` - Degrees north (−90 to 90). - `longitude`: `number` - Degrees east (−180 to 180). - `altitude`: `number | null` - Metres above sea level, or `null` when not provided. - `horizontalAccuracy`: `number | null` - Radius of horizontal uncertainty in metres - smaller is more accurate. Populated on a live fix from `environment.location.current()`; `null` on an author-constructed coordinate. - `timestamp`: `number | null` - When the fix was taken, in seconds. Populated on a live fix; `null` on an author-constructed coordinate. **Instance Methods:** - `distanceTo(other: GeoCoordinate)` → `number` - Great-circle distance to another coordinate, in metres (haversine, 6371 km). - `bearingTo(other: GeoCoordinate)` → `number` - Initial great-circle bearing to another coordinate, in degrees (0-360, from north). ## Runtime Functions - `wait(seconds: number)` → `Promise` - Wait for specified seconds - `seconds`: Seconds to wait - `animateValue(options: Object, options.from: number | Vector2 | Vector3 | Vector4 | Color | Rotation, options.to: number | Vector2 | Vector3 | Vector4 | Color | Rotation, options.duration: number, options.curve: string, options.spring: Object, options.spring.duration: number, options.spring.bounce: number, options.spring.velocity: number | Vector2 | Vector3 | Vector4 | Color, options.bezier: Array, options.delay: number, options.repeatCount: number, options.reverseOnRepeat: boolean, options.autoStart: boolean, options.onUpdate: function, options.onComplete: function)` → `ValueAnimation` - Create and start a value animation Automatically interpolates between from/to values based on their type. Supports numbers, Vector2, Vector3, Vector4, Color, and Rotation. Rotations use spherical interpolation (slerp) automatically. Animations clean up automatically when complete. For infinite animations, call destroy() to stop, or they clean up when the scene ends. - `options`: Animation configuration - `options.from`: Start value - `options.to`: End value (must match from type) - `options.duration`: Duration in seconds (for curve timing) - `options.curve`: Easing curve: "linear", "easeIn", "easeOut" or "easeInOut". Any other name warns in the console and plays linear; use `bezier` for other curves. - `options.spring`: Spring timing (overrides duration/curve) - `options.spring.duration`: The spring's perceived duration in seconds; it settles a little later, and onComplete runs then. - `options.spring.bounce`: Bounce amount (0 = no bounce, 1 = full bounce) - `options.spring.velocity`: Speed per second at the start, the same kind of value as `from` and `to`, such as a gesture's speed when the finger lifts. The spring carries on from it instead of starting at rest. Rotations and Transforms take none. - `options.bezier`: Custom bezier curve [p1x, p1y, p2x, p2y], such as [0.33, 1, 0.68, 1] for an ease-out cubic. - `options.delay`: Delay before starting (seconds) - `options.repeatCount`: Number of repeats (0 = play once, -1 = infinite) - `options.reverseOnRepeat`: Reverse direction on each repeat (yoyo) - `options.autoStart`: Start immediately - `options.onUpdate`: Called each frame with the interpolated value - `options.onComplete`: Called when animation finishes (not called for infinite) - `createBox(width: number, height: number, depth: number, cornerRadius: number, options: Object)` → `ObjectDescriptor` - Create a box primitive descriptor - `width`: Width in meters - `height`: Height in meters - `depth`: Depth in meters - `cornerRadius`: Corner radius for rounded edges - `options`: Declarative object config, the same keys as the builder methods: `{ name, anchor, physics, gestures, material, shadow, transform, opacity, fittingBox, pivot, revealAnimation, removalAnimation, hideByDefault, flatten }`. `createBox(w, h, d, r, { physics, material })` equals `createBox(w, h, d, r).physics(...).material(...)`. - `createSphere(radius: number, subdivisions: number, options: Object)` → `ObjectDescriptor` - Create a sphere primitive - `subdivisions`: Cells per side of each of the sphere's six faces, for shaders that move the surface. Leave it out, or pass 1, for the standard sphere. Odd values round up to the next even one. - `options`: Declarative object config (same keys as the builder methods) -- see createBox. May also be passed second when there are no subdivisions: `createSphere(0.5, { name: 'ball' })`. - `createPlane(orientation: string | number, width: number, height: number, cornerRadius: number, subdivisions: number | Array)` → `ObjectDescriptor` - Create a plane primitive - `orientation`: "xz" (horizontal) or "xy" (vertical), or width if orientation omitted - `subdivisions`: Cells along the width and the height, for shaders that move the surface: one number for both, or `[x, y]`. Leave it out, or pass 1, for the standard flat plane. - `createModel(urlOrId: string, options: Object)` → `ObjectDescriptor` - Create a 3D model object descriptor - `urlOrId`: HTTPS URL to .usdz/.reality file or asset ID from project - `options`: Declarative object config (same keys as the builder methods) -- see createBox. - `createSplat(urlOrId: string, options: Object)` → `ObjectDescriptor` - Create a Gaussian splat capture object descriptor - `urlOrId`: HTTPS URL to an .spz file, or asset ID from project - `options`: Declarative object config. Beyond the shared keys (see createBox): `projection` ("perspective" | "tangential"), `sorting` ("depth" | "distance"), `opacityThreshold` (0-1, drops the faintest splats at load), and `coordinateSystem` ("rub" | "rdf", the axes the file stores its splats in; pass "rdf" for a PLY-based export that appears upside down). - `createMedia(kind: string, urlOrId: string, width: number, aspectRatio: number, options: Object, options.cornerRadius: number, options.doubleSided: boolean, options.showLoading: boolean, options.immersive: boolean, options.video: Object, options.video.volume: number, options.video.loops: boolean, options.video.stream: boolean)` → `ObjectDescriptor` - Create a visual media object (image, video, or animated GIF) - `kind`: "image", "video", or "animatedGif" - `urlOrId`: HTTPS URL or asset ID - `width`: Width in meters - `aspectRatio`: Aspect ratio (width/height) - `options`: Additional options - `options.cornerRadius`: Relative corner radius (0-1) - `options.doubleSided`: Render both sides - `options.showLoading`: Show loading placeholder - `options.immersive`: Enable immersive rendering - `options.video`: Video playback options - `options.video.volume`: Volume (0-1) - `options.video.loops`: Loop playback - `options.video.stream`: Stream content - `createImage(urlOrId: string, width: number, aspectRatio: number, options: Object)` → `ObjectDescriptor` - Create an image - `urlOrId`: HTTPS URL or asset ID - `width`: Width in meters - `aspectRatio`: Aspect ratio (width/height) - `options`: Additional options (cornerRadius, doubleSided, showLoading, immersive) - `createVideo(urlOrId: string, width: number, aspectRatio: number, options: Object)` → `ObjectDescriptor` - Create a video - `urlOrId`: HTTPS URL or asset ID - `width`: Width in meters - `aspectRatio`: Aspect ratio (width/height) - `options`: Additional options (cornerRadius, doubleSided, showLoading, immersive, video) - `createAnimatedGif(urlOrId: string, width: number, aspectRatio: number, options: Object)` → `ObjectDescriptor` - Create an animated GIF - `urlOrId`: HTTPS URL or asset ID - `width`: Width in meters - `aspectRatio`: Aspect ratio (width/height) - `options`: Additional options (cornerRadius, doubleSided, showLoading, immersive) - `createContainer(children: Array)` → `ObjectDescriptor` - Create a container/composition - `children`: Child object descriptors - `createPanel(content: Object, options: Object, options.panelSize: any | any | Array | any, options.material: any, options.cornerRadius: number, options.isScrollable: boolean, options.presentation: any | any)` → `ObjectDescriptor` - Build a UI panel descriptor wrapping the given root view. Pass to `scene.createEntity(panel)` to instantiate. - `content`: Root View descriptor (typically a UI.vStack/hStack/zStack). - `options.panelSize`: Panel dimensions. Use `'auto'` (default -- sized to content), `'fill'` (fill parent), or an explicit size in **points** (≈ 1360 pt/m): either `[width, height]` or `{ width, height }`. E.g. `[400, 240]` ≈ 0.29m × 0.18m. - `options.material`: Surface material. `'system'` (default -- platform-appropriate translucent surface), `'transparent'`, a `ColorSource` (hex string / Color) for a solid fill, or `{ prominence: 'standard'|'expressive' }` for system with a prominence override. - `options.presentation`: `'projected'` draws the panel over the scene on iPhone, iPad and Mac: flat, facing the viewer, the same size at any distance and never hidden by objects. Apple Vision Pro always shows it in the world. - `createMesh(opts: Object, opts.vertexCapacity: number, opts.indexCapacity: number, opts.indexType: string, opts.attributes: Object, opts.parts: Array, opts.materials: Array, opts.interleavedGroups: Array>)` → `ObjectDescriptor` - Create a scriptable dynamic mesh with CPU-driven vertex/index updates. Returns an ObjectDescriptor -- pass to `scene.createEntity(...)`. After the entity loads, reach the mesh via `entity.representation.mesh` and write buffer data with `mesh.writeVertices(...)` / `mesh.writeIndices(...)`. Bytes flow straight from `Float32Array` / `Uint32Array` into the GPU-side buffer -- single memcpy per call, no per-element overhead. - `opts.vertexCapacity`: Max vertices the mesh allocates space for. Required. - `opts.indexCapacity`: Max indices the mesh allocates space for. Required (must be > 0). For draw orders that would otherwise be non-indexed, set this to `vertexCapacity` and write sequential indices `[0, 1, 2, ...]` once. - `opts.indexType`: "uint32" or "uint16". - `opts.attributes`: Named attributes. Either a string shorthand or an explicit object. - **Shorthand** (static, semantic auto-derived from name): `position: "float3"`, `color: "uchar4Normalized"`. - **Explicit form**: `{ semantic, format, storage }`. `semantic` ∈ "position" | "normal" | "tangent" | "bitangent" | "color" | "uv0" ... "uv7" | "unspecified" (defaults to the attribute name when omitted). `format` ∈ "float" | "float2" | "float3" | "float4" | "uchar4Normalized". `storage` ∈ "static" (default -- write once at setup) | "dynamic" (CPU-writable via `writeVertices`, per-frame) | "compute" (reserved for a future runtime version; rejected today). - `opts.parts`: Draw ranges. Each part: `{ indexOffset?, indexCount, topology?, materialIndex?, bounds }`. `topology` ∈ "triangle" (default) | "triangleStrip" | "line" | "lineStrip" | "point". `bounds`: `{ min: [x,y,z], max: [x,y,z] }`. Must contain every vertex the part draws. - `opts.materials`: Material reference ids from the experience's material library. Each part's `materialIndex` indexes into this array. If empty, a default material is used. - `opts.interleavedGroups`: Opt-in attribute grouping. Each inner array is a set of attribute names that share one underlying buffer (interleaved layout). Default is one buffer per attribute. Use case: spatial-drawing-style stroke extension where every vertex carries position+normal+color together -- interleaved gives better GPU cache locality. All attributes in a group must share `storage` state (all "static", all "dynamic", etc.). Per-attribute write API (`mesh.writeVertices(name, ...)`) stays the same; the bridge uses a strided memcpy under the hood. - `createSpotLight(options: Object)` → `ObjectDescriptor` - Create a spot light -- a cone of light aimed along the object's forward axis. Rotation aims it; position places it. Intensity is in lumens. - `options`: Light configuration: `color` (`'#RRGGBB'` or `{ r, g, b }`), `intensity` (lumens, default 6740.94), `innerAngle` / `outerAngle` in degrees (full cone aperture, defaults 45 / 60), `attenuationRadius` in metres (default 10), `falloffExponent` (2 is physically correct), `shadow` (see below), `projectedTexture` (asset id, HTTPS URL, or a handle from `Texture.image/video/cameraFeed/compute(...)`), `projectedTextureOffset` / `projectedTextureScale` (`{ x, y }`, a pair, or one number for both axes) and `projectedTextureRotation` in radians, which lay the projected texture out within the cone, `lightsSurroundings` (spill onto real surfaces). Plus every shared descriptor key -- `name`, `anchor`, `transform`, ... `shadow` is `true` for defaults, or `{ edges, lightSize, depthBias }`: `edges` is `'hard'` (default, cheapest), `'soft'` or `'softer'`; `lightSize` is the emitter's size in metres, which widens the blurred edge and does nothing at `'hard'`; `depthBias` offsets the shadow off its own surface. - `createPointLight(options: Object)` → `ObjectDescriptor` - Create a point light -- light radiating equally in every direction. Only its position matters; rotation does nothing. Intensity is in lumens, and a point light cannot cast shadows. - `options`: `color`, `intensity` (lumens, default 26963.76), `attenuationRadius` (metres, default 10), `falloffExponent`, `lightsSurroundings`, plus the shared descriptor keys. - `createDirectionalLight(options: Object)` → `ObjectDescriptor` - Create a directional light -- a sun, shining from infinitely far away. Only its rotation matters; position moves nothing but the editor's marker. Intensity is in lux rather than lumens, so the numbers are not comparable with the other two types. - `options`: `color`, `intensity` (lux, default 2145.71), `shadow`, plus the shared descriptor keys. `shadow` is `true` for defaults or `{ maximumDistance, depthBias, cascades }`: `maximumDistance` is how far from the camera shadows are computed at all, and `cascades` is `'automatic'` or a count of 1...4, where more sharpens distant shadows and costs the same factor in memory. ## Static Extensions ### `Rotation` **Methods:** - `Rotation.quaternion(x: number, y: number, z: number, w: number)` → `Rotation` - Create a rotation from quaternion components - `x`: X component - `y`: Y component - `z`: Z component - `w`: W component (scalar) ### `Color` **Methods:** - `Color.rgb(r: number, g: number, b: number)` → `Color` - Create a color from RGB values (alpha defaults to 1) - `r`: Red (0-1) - `g`: Green (0-1) - `b`: Blue (0-1) - `Color.hex(hex: string)` → `Color | null` - Create a color from hex string - `hex`: Hex color string (with or without #) - `Color.hsl(h: number, s: number, l: number)` → `Color` - Create a color from HSL values - `h`: Hue (0-1) - `s`: Saturation (0-1) - `l`: Lightness (0-1) - `Color.white()` → `Color` - White color (1, 1, 1, 1) - `Color.black()` → `Color` - Black color (0, 0, 0, 1) - `Color.red()` → `Color` - Red color (1, 0, 0, 1) - `Color.green()` → `Color` - Green color (0, 1, 0, 1) - `Color.blue()` → `Color` - Blue color (0, 0, 1, 1) - `Color.clear()` → `Color` - Transparent color (0, 0, 0, 0) ### `Math` **Methods:** - `Math.toRadians(degrees: number)` → `number` - Convert degrees to radians - `degrees`: Angle in degrees - `Math.toDegrees(radians: number)` → `number` - Convert radians to degrees - `radians`: Angle in radians - `Math.lerp(a: number, b: number, t: number)` → `number` - Linear interpolation between two values - `a`: Start value - `b`: End value - `t`: Interpolation factor (0-1) - `Math.clamp(value: number, min: number, max: number)` → `number` - Clamp value between min and max - `value`: Value to clamp - `min`: Minimum value - `max`: Maximum value - `Math.map(value: number, inMin: number, inMax: number, outMin: number, outMax: number)` → `number` - Map value from one range to another - `value`: Input value - `inMin`: Input range minimum - `inMax`: Input range maximum - `outMin`: Output range minimum - `outMax`: Output range maximum - `Math.fract(x: number)` → `number` - Get fractional part of number - `x`: Input value - `Math.smoothstep(edge0: number, edge1: number, x: number)` → `number` - Smooth interpolation with easing - `edge0`: Lower edge - `edge1`: Upper edge - `x`: Input value ## Runtime Objects ### `UI` View tree builders. Each method returns a plain View descriptor, the same shape the editor stores for a panel's views. Compose into a panel via `createPanel(content, options)` and instantiate with `scene.createEntity`. Naming a node (`{ name: 'vol' }`) lets you find it later via `entity.representation.findView({ name: 'vol' })` to bind a variable, attach a listener, or mutate properties. **Common options accepted by every factory:** - `name` -- author-supplied lookup key for `findView({ name })`. - `padding` -- number (uniform), `{ horizontal, vertical }`, or `{ top, leading, bottom, trailing }`. - `background`, `overlay` -- views drawn behind or in front of this one, made with these factories. They never change its size or move its neighbours. - `placement` -- where a view in a background or overlay sits: `{ alignment, anchor }`, each a point named `'topLeading'` ... `'bottomTrailing'` or `'center'`, `[x, y]` from (0, 0) top leading to (1, 1) bottom trailing, or a `Vector2`. `alignment` is the point on the view it belongs to, `anchor` the point on this view placed there; both default to the centre. A badge centred on a corner is `{ alignment: 'topTrailing' }`; inside it, `{ alignment: 'topTrailing', anchor: 'topTrailing' }`. - `style` -- `{ foregroundColor, backgroundColor, font, shape, opacity, ... }`. Colours take `'#RRGGBB[AA]'`, `{ r, g, b, a? }` or `{ light, dark }`; `shape` takes `'rectangle'`, `'capsule'`, `'circle'` or a corner radius in points. On a button, `prominence: 'expressive'` draws Liquid Glass in panels on the screen, tinted with its `backgroundColor`, or blue for `appearance: 'primary'` and red for `'destructive'`. - `safeAreaPadding` -- edges whose padding grows by the safe area, as an array of `'top'`, `'leading'`, `'bottom'` and `'trailing'`. Use it in a panel anchored with `Anchor.screenSpace({ respectsSafeArea: false })`, so a header image can reach the screen edge while text and buttons stay clear of the status bar, the home indicator and rounded corners. Adds nothing while the panel respects the safe area. - `sizing` -- sets width/height per axis. Each axis accepts: `'auto'` (hug content, default), `'fill'` (take available space), a number in points (fixed), or a percentage string like `'50%'`. Pass `sizing: 'fill'` for both axes, `sizing: [w, h]` for fixed both axes, or `sizing: { width: 'fill', height: 'auto', maxWidth: 600 }` for mixed control. Sliders and progress views default to fill on the stack's cross axis (they have no intrinsic width / height to hug); set `sizing: { width: 200 }` if you want a narrower control instead. - `isHidden`, `isEnabled`, `opacity` -- universal interactive flags. **Methods:** - `UI.animate(changes: function, options: Object, options.duration: number, options.timingFunction: string, options.spring: Object, options.spring.duration: number, options.spring.bounce: number)` → `Promise` - Animates every change to panel views made inside `changes`: a stack opens or closes around views shown or hidden, new views fade in, `opacity` and size changes ease, and the panel grows or shrinks with them. Without it the same changes happen at once. - `changes`: Makes the changes, the same way as without an animation. - `options`: Timing, as in `animateTo`; the system's default when left out. - `options.duration`: Seconds. - `options.timingFunction`: 'linear' | 'easeIn' | 'easeOut' | 'easeInOut' - `options.spring`: Spring timing instead of `duration` and `timingFunction`. - `options.spring.duration`: The spring's perceived duration in seconds. - `options.spring.bounce`: 0 settles without overshoot, higher values bounce. - `UI.label(opts: string | Object)` → `Object` - Label (read-only text). Accepts a string shorthand or an options object. Text supports live variable interpolation -- `${var}` reads from the current segment, `${g:var}` from the experience scope. The label re-renders automatically whenever a referenced variable changes; no manual `scene.on('variableChange', ...)` wiring is needed. Optional `|filter` / `|filter(arg)` suffix formats the resolved value: `fixed(N)`, `percent(N)`, `time`, `int`, `signed(N)`. Missing variables render as `UNDEFINED`. See the "Live Labels" guide for the full filter reference. - `opts`: Text shorthand or { text, lineLimit?, textTransform?, name?, ... }. - `UI.button(opts: Object)` → `any` - Tap-able button. - `opts`: { title, icon?, iconPointSize?, iconOffset?, name?, ... }. `iconOffset` is `[x, y]` in points and moves the icon without resizing the button. - `UI.slider(opts: Object)` → `any` - Continuous or stepped slider. - `opts`: { value?, range?|min,max, numberType?, step?, name?, ... }. - `UI.toggle(opts: Object)` → `any` - On/off switch. - `opts`: { isOn?, label?, name?, ... }. - `UI.textField(opts: Object)` → `any` - Single-line text field. - `opts`: { text?, placeholder?, name?, ... }. - `UI.stepper(opts: Object)` → `any` - Stepper (− / + numeric increment). - `opts`: { value?, range?|min,max, step?, label?, name?, ... }. - `UI.segmentedControl(opts: Object)` → `any` - Segmented control. - `opts`: { segments: [...], selectedIndex?, name?, ... }. - `UI.progressView(opts: Object)` → `any` - Determinate (`progress: 0..1`) or indeterminate (omit `progress`) progress bar. - `opts`: { progress?, name?, ... }. - `UI.divider(opts: Object)` → `any` - Thin horizontal separator. - `opts`: { thickness?, ... }. - `UI.shape(opts: Object)` → `any` - Decorative shape fill. - `opts`: { shape?, ... }. `shape` defaults to a rounded rectangle. - `UI.spacer(opts: Object)` → `any` - Flexible empty space. - `opts`: { minLength?, ... }. - `UI.vStack(opts: Object)` → `any` - Vertical stack. - `opts`: { children?, alignment?, distribution?, spacing?, ... }. - `UI.hStack(opts: Object)` → `any` - Horizontal stack. - `opts`: { children?, alignment?, distribution?, spacing?, ... }. - `UI.carousel(opts: Object)` → `any` - Carousel: a row or column of children that scrolls and selects the child in the middle. Listen with `on('valueChanged', ...)` for the selected index, or `on('scroll', ...)` for the position while it moves; `scrollTransition` shrinks, fades or tilts children by their distance from the middle. - `opts`: { children?, axis?, spacing?, itemSize?, selectedIndex?, snapsToItems?, isScrollLocked?, showsPageDots?, neighborScale?, neighborOpacity?, playsSelectionHaptics?, name?, ... }. `axis` is `'horizontal'` (default) or `'vertical'`. `itemSize` is `'fitContent'` (default) or `'matchLargest'`, which gives every child the length of the longest along `axis`. `snapsToItems` (default true) brings a released scroll to rest with a child in the middle. `isScrollLocked` lets only a script or a bound variable move it. `neighborScale` and `neighborOpacity` (default 1) are what a child one step from the middle gets. - `UI.zStack(opts: Object)` → `any` - Z-axis stack (layers children). - `opts`: { children?, alignment?, ... }. - `UI.annotation(opts: Object, opts.card: Object, opts.isExpanded: boolean, opts.direction: any | any | any | any, opts.animation: any | any | any, opts.marker: Object, opts.title: string, opts.image: string, opts.stem: Object, opts.leader: Object, opts.cardStyle: Object)` → `any` - A marker pinned to a point, which expands into a card. The card is the single child, so `card:` is sugar for `children: [view]`. Without one the annotation is just a marker and tapping it does nothing. The marker keeps its authored point size only where the panel is drawn as a screen overlay. In world space it is a physical object and shrinks with distance; the object's Dynamic Scale constraint, set in the editor, keeps it readable at any range. - `opts`: { card?, isExpanded?, direction?, animation?, marker?, title?, image?, stem?, leader?, cardStyle?, shadow?, name?, ... }. - `opts.card`: View shown when expanded, typically a UI.vStack. - `opts.isExpanded`: Starting state, not an entrance. - `opts.direction`: Which way the stem and card grow away from the marker. - `opts.animation`: How the card arrives. - `opts.marker`: { kind?: 'filled'|'ring'|'ringWithCenter', diameter?, ringWidth?, centerScale?, fillColor?, ringColor? }. - `opts.title`: Glyph drawn inside the marker, e.g. a number. - `opts.image`: SF Symbol name drawn inside the marker. - `opts.stem`: { isEnabled?, lineStyle?: 'solid'|'dashed'|'dotted', length?, thickness?, color? }. `isEnabled: false` still holds the card `length` away from the marker. Ignored entirely when `leader` is set, since the card then opens at the marker. - `opts.leader`: A line from the annotated point out to the marker, so the marker floats clear of the subject. Same shape as `stem`. Set, the point takes the annotation's centre, the marker lifts `length` away along `direction`, and the card opens at the marker with no second line between them. - `opts.cardStyle`: { cornerRadius?, backgroundColor?, contentInsets? }. ### `scene.tracking.hands` **Properties:** - `isSupported`: `boolean` (read-only) - whether this device/build can track hands (Apple Vision Pro). - `active`: `boolean` (read-only) - Provider authorized and running -- the "tracking live" signal, distinct from a hand being in view. Flips false if permission is revoked or tracking is lost; poll this to observe loss after a successful enable(). - `enabled`: `boolean` (read-only) - whether this script currently requests hand tracking. - `left`: `AnchorData | null` (read-only) - left hand anchor, or null when not tracked. - `right`: `AnchorData | null` (read-only) - right hand anchor, or null when not tracked. - `anchors`: `Array` (read-only) - all currently tracked hand anchors. **Methods:** - `scene.tracking.hands.enable()` → `Promise` - Opt into hand tracking. Idempotent. Resolves when tracking is live (provider running + authorized); rejects if denied or unsupported. Currently Apple Vision Pro only -- gate with `environment.features.has('handTracking')`. - `scene.tracking.hands.disable()` → `any` - Drop this script's hand-tracking request. Fire-and-forget. ### `scene.tracking.face` **Properties:** - `isSupported`: `boolean` (read-only) - whether the scene can deliver face tracking data. - `active`: `boolean` (read-only) - true when a face is currently tracked (a face context is active). - `current`: `AnchorData | null` (read-only) - current face anchor (blendshapes, eye transforms), or null. ### `scene.gameController` **Properties:** - `controllers`: `Array` (read-only) - Connected controllers, in connection order. **Methods:** - `scene.gameController.on(type: string, listener: any)` → `string | undefined` - Subscribe to controllers connecting or disconnecting. Controllers that are already connected fire `connect` for a new subscriber on the next frame, never inside `on`. Subscriptions end when the scene changes. - `type`: `"connect"` or `"disconnect"`. - `scene.gameController.off(id: string)` → `any` - Remove a subscription made with `on`. - `id`: Id returned from `on`. ### `scene.camera` **Properties:** - `kind`: `string` (read-only) - Who moves the camera: `"orbit"` where the experience drives its own camera (the Mac, the preview outside AR), `"device"` where the device is the camera (AR, Apple Vision Pro). Changes when the preview switches in or out of AR. - `mode`: `string` (read-only) - `"free"`, `"follow"` or `"lookAt"`: what the last call set up. - `gamepad`: `any` (read-only) - Which camera controls a game controller keeps where the experience drives its own camera: `move` is the left stick and the triggers, `orbit` the right stick and its click, which resets the view. Set one to `false` to use those inputs yourself; both return to `true` when the scene changes. While the camera follows or looks at something, `move` has no effect anyway. **Methods:** - `scene.camera.follow(target: ObjectEntity | RepresentationEntity, options: Object, options.distance: number, options.azimuth: number, options.elevation: number, options.offset: Vector3, options.damping: number, options.verticalDamping: number, options.elevationRange: Array, options.orbit: boolean, options.zoom: boolean | any)` → `boolean` - Keep an object in view: the camera's orbit moves along with it, and dragging or the right stick still swings around it. Moving inputs (keys, two-finger pan, the left stick) stop moving the camera until `release()`. The right stick's click returns to the framing the follow started with. Ends when the scene changes or the object leaves the scene, which warns. - `target`: The object to follow. - `options.distance`: Metres from the camera to the target; default: as now. - `options.azimuth`: Degrees around the target; 0 looks toward -z. Default: as now. - `options.elevation`: Degrees above the horizon; default: as now. - `options.offset`: World-space metres from the object's origin to the point the camera aims at, such as above a character's feet. Default `Vector3(0, 0, 0)`. - `options.damping`: Seconds the camera takes to settle after the object moves; `0` is rigid. Default about 1.5. - `options.verticalDamping`: The same for height, so a jump needn't bob the view. Default `damping`, or about 3.8 when `damping` is omitted. - `options.elevationRange`: `[min, max]` degrees the player can orbit between. Default `[0, 60]`. - `options.orbit`: Whether dragging and the right stick orbit. Default `true`. - `options.zoom`: Whether pinch and scroll change the distance, optionally within metres. Default `true`. - `scene.camera.lookAt(target: ObjectEntity | RepresentationEntity, options: Object, options.from: Vector3, options.offset: Vector3, options.damping: number)` → `boolean` - Turn the camera toward an object and keep it turned there while the object moves. The camera stays where it is, or moves to `from`; dragging and zooming do nothing until `release()`. The right stick's click does nothing meanwhile. Ends when the scene changes or the object leaves the scene, which warns. - `target`: The object to look at. - `options.from`: Where the camera stands, in world space. Default: where it is. - `options.offset`: World-space metres from the object's origin to the point the camera aims at. Default `Vector3(0, 0, 0)`. - `options.damping`: Seconds the aim takes to settle after the object moves; `0` is rigid. Default about 1.5. - `scene.camera.release()` → `any` - Hand the camera back to the player, from where it is now. ### `Pose` Where a tracked controller or stylus is, in the same space as `entity.worldPosition`. A new pose arrives every frame; one you keep doesn't change. **Properties:** - `position`: `Vector3` - Assign it to `entity.worldPosition` to put something there. - `rotation`: `Rotation` - As `entity.worldRotation`; the pose points along its -z. - `velocity`: `Vector3` - Metres per second. - `angularVelocity`: `Vector3` - Radians per second around the vector's axis. ### `GameController` A connected game controller, handed to `scene.gameController.on('connect', ...)` and listed in `scene.gameController.controllers`. **Properties:** - `id`: `string` (read-only) - Unique for this connection; a controller that reconnects gets a new id. Use it to tell controllers apart, never to recognise a device. - `kind`: `string` - `"gamepad"` (two hands), `"spatialController"` (one hand, tracked) or `"stylus"` (tracked, held in either hand). - `name`: `string` - The controller's name, for display and logging. Don't branch on it. - `isConnected`: `boolean` - `false` once the controller disconnected; its buttons then read released and its sticks centred. - `buttons`: `Object` - Current button state by name; a button the controller lacks is `undefined`. Gamepads: `buttonA` `buttonB` `buttonX` `buttonY`, `leftShoulder` `rightShoulder`, `leftTrigger` `rightTrigger` (`value` is analog), `leftThumbstickButton` `rightThumbstickButton`, `buttonMenu` `buttonOptions`. Spatial controllers: `trigger`, `gripButton`, `thumbstickButton`, `buttonA` (lower face button of that hand), `buttonB` (upper face button), `buttonMenu`. Styluses: `tip` (pressed against a surface; `value` is the pressure), `primaryButton` (the barrel button nearest the tip), `secondaryButton` (the one above it; `value` is how hard it is pressed). Entries update in place every frame. - `sticks`: `Object` - Current stick state by name, each axis -1 to 1, up is positive: `leftThumbstick` `rightThumbstick` `directionPad` on a gamepad, `thumbstick` on a spatial controller. Entries update in place every frame. - `hand`: `string | null` (read-only) - `"left"` or `"right"`: the side a spatial controller is built for, or the hand holding a stylus right now. A spatial controller is listed and announced only once its side is known, so it's set from `connect` on, unless accessory tracking isn't allowed. `null` for a gamepad, for a stylus nobody holds, and wherever the device doesn't say. Treat `null` as unknown, never as "no hand". - `aim`: `Pose | null` (read-only) - The pointing pose: a stylus tip, a spatial controller's aim. `null` while its position isn't tracked, on a gamepad, and where `environment.features.has('accessoryTracking')` is false. - `grip`: `Pose | null` (read-only) - Where the hand holds a spatial controller. `null` on every stylus and gamepad, and while untracked. **Methods:** - `on(type: string, options: Object | function, listener: function)` → `string | undefined` - Subscribe to this controller's input. Subscriptions end when the scene changes, as `scene.on` ones do; subscribe again in the new scene. - `type`: `"button"` → `{ controller, name, phase, pressed, value, touched, aim, grip }`, where `phase` is `"began"` (pressed), `"ended"` (released) or `"changed"` (value or touch changed while the press state stayed), and `aim` and `grip` are the controller's poses in the frame of the change, as `Pose` or `null`; `"stick"` → `{ controller, name, x, y }`. - `options`: Optional filter: `name` (one button or stick), and for `"button"` `phase`. - `listener`: Called at most once per element per frame, with the latest state. A press and release within one frame is not seen, and neither is the press of a button already held when the controller connected: it reports `"ended"` on release. - `off(id: string)` → `any` - Remove a subscription made with `on`. - `id`: Id returned from `on`. - `pulse(intensity: number, seconds: number)` → `Promise` - Play a haptic pulse on this controller. - `intensity`: Strength, 0 to 1. - `seconds`: Duration in seconds.