Skip to content

@relu-interactives/spatial-ecs


@relu-interactives/spatial-ecs / index

index ​

Classes ​

Other ​

ClassDescription
AnimationStateMachine-
AnimationStateManager-
World-
AnimationSystem-
CameraSyncSystem-
EnvironmentSyncSystem-
InputSystem-
InstancedMeshSystemMaintains the runtime geometry for entities with an InstancedMeshComponent.
LightSyncSystem-
MaterialSyncSystem-
MeshGeometrySystem-
ObjectManagementSystem-
ObjectVisibilitySystem-
PhysicsSyncSystem-
PostprocessingSyncSystem-
RenderSystem-
ScriptBehaviourSystem-
TransformSyncSystem-
UIInteractionSystem-
UIPanelSystem-
VRTeleportAreaSystem-
XRAnchorSystem-
XRControllerVisualSystem-
XREnvironmentSystem-
XRHandPoseSystem-
XRHitTestSystem-
XRHoverVisualSystem-
XRInputSystem-
XRInteractionSystem-
XRLocomotionSystem-
XRSessionSystemOwns the immersive-session lifecycle and fans XR events out to Behaviours.
XRTeleportVisualSystem-
HandPoseTrackerTurns a stream of per-frame confidences into clean start/end events.
TeleportAimGateDecides when a teleport may actually commit.
ThrowVelocityTrackerRolling buffer of hand positions used to recover throw velocity.

Scripting ​

ClassDescription
ScriptObjectBase class for script objects — entities whose THREE.js visual is built entirely by user code (procedural geometry, shaders, particle systems, anything the editor can't author natively).

Systems ​

ClassDescription
AudioSystemReconciles AudioComponent state with the underlying THREE.js audio objects each frame.
ScriptObjectSystemBuilds, ticks, and disposes ScriptObject scripts. Unlike ScriptBehaviourSystem, this runs in the editor AND at runtime — there is NO isEditorMode gating anywhere here. A script's build() output is attached under the entity's Object3DRef.object (so it inherits transform, selection and visibility). runtimeState is written on transitions only (never every frame).
VideoSystemReconciles VideoComponent state with the underlying HTML video element and THREE.js mesh/material each frame.

Interfaces ​

InterfaceDescription
StateMachine-
EcsSystem-

Type Aliases ​

Type AliasDescription
AnimationStateCallbacks-
ComponentValueMaps-
EcsWorldComponentSnapshot-
EcsWorldStateSnapshotLike-
HydrateWorldFromSnapshotResult-
HydrateOptionsOptional behavior tweaks for hydrateWorldFromSnapshotDetailed. Defaults preserve the historical full-world-load behavior; prefab/subtree instantiation passes stricter options.
ApplyPrefabToSnapshotResult-
InstantiateSubtreeResult-
NodeKeyMaps-
NestedRegion-
NodeMaps-
SerializeEntitySubtreeResult-
SubtreeSnapshotSnapshot-space entity-id walking/remapping.
ExternalRefWarning-
RemapSnapshotOptions-
SpawnPrefabSource-
SpawnPrefabOptions-
PrefabAssetEnvelope of a .prefab asset file (and, later, .scene assets — same shape with type: "scene"). snapshot is the same columnar world-snapshot format hydrateWorldFromSnapshotDetailed consumes, with entity ids renumbered 1..N and every entity carrying a PrefabNode identity.
MouseButton-
EcsComponentFactoryKind-
ComponentFactory-
SelectionContextOptional context that enables raycast-based onSelect / onDeselect dispatch. When provided, pointer/touch taps on the canvas fire a raycast against the scene. If the hit object (or any ancestor) carries userData.entityId, every Behaviour instance for that entity receives onSelect(); the previously selected entity's instances receive onDeselect().
UiCanvasLikeStructural canvas type so tests can inject a stub with no DOM.
XrHandPoseEventDetail-
XrHitResultWhere a ray met the real world.
KeyboardKey-
ModuleLoaderResolves a script URL to its ES module namespace.
XrHandJointNameThe 25 joints of the WebXR hand skeleton.
XrFinger-
XrHandJointsJoint positions, in world space.
XrFingerCurlHow curled one finger is.
XrPalmPoseAn orthonormal frame attached to the palm.
XrHandShapeEverything a pose is matched against, derived once per hand per frame.
XrFingerTargetTarget curl for one finger, with the slack allowed around it.
XrHandPoseAxisWhich way something on the hand must point for the pose to count.
XrHandPoseDirection-
XrHandPoseOrientation-
XrHandPoseDefinitionA matchable hand pose.
XrHandPoseMatch-
XrHandPoseContextExtra world context needed only by head-relative orientation conditions.
XrHandPoseEvent-
HandPoseTrackerOptions-
HandMaterialOptionsMaterials for tracked-hand meshes.
VelocitySample-
XrHandednessWhich hand an input source belongs to (none for gaze / single-source devices).
XrInputKindHow an input source is physically driven.
XrInputStateOne frame of normalized input for a single source.
XrCapabilitiesWhat the ACTIVE session actually granted us.

Variables ​

VariableDescription
HYDRATABLE_ENTITY_KINDS-
NODE_KEY_SEPARATOR-
ADDED_NODE_MARKER_COMPONENTReserved override "component" marking a node ADDED by the host document inside a nested instance region (`"<nodeKey>
OVERRIDE_DIFF_EXCLUDED_COMPONENTSComponents that never participate in override diffing/merging.
OVERRIDE_ROOT_EXCLUDED_COMPONENTSComponents excluded ONLY on the instance ROOT node — these are per-instance by definition (where the instance sits in the scene and what it's called).
PREFAB_FILE_VERSION-
PREFAB_FILE_VERSION_NESTEDWritten for files containing NESTED instances (parse accepts either).
SCRIPT_OBJECT_ROOT_FLAGTags the Object3D a script's build() returned, so reloads can find/remove it.
XR_HOVER_SHELL_FLAGMarks shell meshes so they are never mistaken for scene content.
KeyboardKeys-
SHARED_MODEL_RESOURCE_FLAGuserData flag set on geometries/materials that back shared (cached) model scenes. Entity disposal must skip these — other live clones and future spawns reference the same GPU resources.
XR_FINGERS-
PINCH_FINGERSFingers that can oppose the thumb. The thumb cannot pinch itself.
FALLBACK_HAND_SCALEFallback palm width when the hand is too poorly tracked to measure.
STRAIGHT_COSStraightness normalization.
CURLED_COS-
MATCH_FALLOFFConfidence falls to zero this far outside a target's tolerance band.
DEFAULT_DIRECTION_TOLERANCEDefault cone for per-finger direction constraints.
DEFAULT_ENTER_CONFIDENCE-
DEFAULT_EXIT_CONFIDENCE-
DEFAULT_MIN_HOLD_SECONDS-
DEFAULT_LOST_GRACE_SECONDS-
HAND_POSE_PRESETSBuilt-in poses, keyed by id.
HAND_POSE_PRESET_IDSPreset ids, in the order the editor lists them.
ARC_GRAVITYDownward acceleration applied to the aim curve, m/s².
ARC_SPEEDLaunch speed of the virtual projectile, m/s. Tuned for ~5-8m reach.
ARC_STEPSSamples along the curve. Enough to look smooth without wasting raycasts.
ARC_MAX_TIMESeconds of flight to simulate before giving up on finding ground.
VELOCITY_SAMPLESSamples retained. ~5 frames ≈ 55ms at 90Hz — long enough to smooth noise.
MAX_SAMPLE_AGE_SECONDSSamples older than this are ignored on release.
MAX_PLAUSIBLE_SPEEDFastest hand motion treated as real, in metres/second.
NO_XR_CAPABILITIESCapabilities for "no session running" — every feature off.

Functions ​

FunctionDescription
createAnimationComponent-
createAudioComponent-
createCameraComponent-
createEntityTypeComponent-
createEnvironmentComponent-
createImageComponent-
createImageTargetAnchorComponent-
createImageTargetComponent-
createInstanceSlotComponent-
createInstancedMeshComponent-
createLightComponent-
createMaterialComponent-
createMeshComponent-
createMeshGeometryComponent-
createModelComponent-
createNameComponent-
createObject3DRefComponent-
createParentIdComponent-
createPhysicsComponent-
createPostprocessingComponent-
createScriptComponent-
createScriptObjectComponent-
createSelectableComponent-
createSelectionTransformStateComponent-
createSpriteComponent-
createTransformComponent-
createUIButtonComponent-
createUIPanelComponent-
createUISliderComponent-
createUITextComponent-
createUIToggleComponent-
createVRTeleportAreaComponent-
createVideoComponent-
createXRAnchorComponent-
createXRHandPoseComponent-
createXRInteractableComponent-
createXRInteractorComponent-
createXRInteractorSideComponent-
createXRRigComponent-
registerDefaultComponentFactories-
registerDefaultFactories-
buildComponentValueMaps-
hydrateWorldFromSnapshotDetailed-
hydrateWorldFromSnapshot-
restorePostCreateComponents-
restoreComponentState-
applyPrefabToSnapshotInstancesPatch every top-level-relative nested instance of nestedUrl inside hostSnapshot with newNestedSnapshot. Deeper nesting (B inside C inside A) is NOT touched here — it cascades through C's own file.
collectEntitySubtreeCollect the given roots plus every descendant, BFS parent-first, using the ParentId component edges. Parent-first ordering matters: serialization renumbers ids in this order and instantiation creates entities in file order, so parents always exist before their children are linked.
collectDirectPrefabDependenciesDirect (top-level-relative) prefab urls a document depends on — the edges of the nesting graph. Deeper nesting is reached transitively through each dependency's own file, never directly.
instantiateSubtreeHydrate a self-contained subtree snapshot (a prefab file's snapshot) into a LIVE world: fresh entity ids, internal references remapped, no camera promotion, transform pass scoped to the created entities.
buildNodeKeyMapsFromSnapshot-
collectSnapshotSubtreeIdsJSON-space subtree ids (root first, BFS) via ParentId edges.
findTopLevelNestedRegionsTOP-LEVEL-RELATIVE nested instance regions of a document: instance roots that are not the scope root and not themselves inside another region. Deeper nesting is reached by cascading through the intermediate prefab's own file, never directly.
findSnapshotRootEntityIdsEntity ids of entities whose ParentId is null or absent.
buildNodeMapsFromSnapshot-
indexSnapshotByEntityInvert the columnar snapshot into entityId → (componentName → value).
canonicalizeComponentValueCanonicalize a serialized component value into nodeId-space: - entity-id fields → {$node} (internal) or raw id (external) - ScriptComponent entries keep only {className, scriptUrl, enabled, data} (entityId/runtimeState/runtimeMessage are per-instance transients) - ScriptObjectComponent keeps only {scriptUrl, className, enabled, data} (runtimeState/runtimeMessage are per-instance transients) - Object3DRef keeps only {visibility} (the rest is a live object ref)
decanonicalizeComponentValueReplace every {$node} marker (at any depth) with the mapped entity id from nodeToId, or null when the node no longer exists. Exact inverse of canonicalization for the id-bearing positions.
encodeOverride-
parseOverride-
groupOverridePathsnodeId → componentName → set of overridden paths.
collectDiffPathsCollect leaf paths where two canonical values differ. Semantics: - {$node} refs compare atomically by nodeId - arrays of differing length are ONE atomic override (the array path); equal lengths recurse per index - object key present on one side only marks that key's path - type mismatches mark the current path An empty-string path means the values differ at the top level.
computeInstanceOverridesDiff a live instance subtree against its prefab base (both as serialized subtree snapshots carrying PrefabNode identity) and return the encoded override list: every path where the instance deviates from the base.
mergeComponentValueMerge a component's NEW canonical file value with an instance's canonical value, preserving the instance side at every overridden path. An empty path ("") means the whole component is overridden → instance wins.
serializeEntitySubtreeSerialize rootId + all descendants into a self-contained snapshot: entity ids renumbered 1..N in BFS parent-first order, all internal id references remapped, external references nulled + reported, root ParentId forced to null. The result is directly consumable by hydrateWorldFromSnapshotDetailed / instantiateSubtree.
remapSnapshotEntityIdsReturn a deep-cloned snapshot with every entity id (entity list, entry keys, and all id-bearing component fields) remapped through idMap. References to ids missing from the map follow externalRefPolicy and are reported in warnings (with ids in the INPUT snapshot's id space).
setPrefabAssetUrlResolverOverride how prefab asset URLs (the file URL itself AND every asset URL stored inside prefab files) are resolved before fetching. Published/preview runtimes register a resolver that maps the editor's localasset://…/assets/x URLs to ./assets/x; the editor leaves it unset (identity — the localasset:// protocol is fetchable there). Same pattern as setDracoDecoderPath. Pass null to restore identity.
loadPrefabFetch + parse (and cache) a .prefab asset. All strings inside the snapshot are passed through the registered URL resolver, so asset references load correctly in published/preview builds. Use this from preloaders to warm the same cache spawnPrefab reads.
clearPrefabCacheDrop one cached prefab (or all when no url is given).
spawnPrefabInstantiate a prefab into a live world at runtime.
despawnPrefabDelete a spawned prefab instance: the root entity plus every descendant (children first). Returns the number of entities removed. dispose releases GPU resources not flagged as shared (safe with the model cache).
prefabFileVersionForFile version to write for a given snapshot: 2 iff it nests instances.
parsePrefabAssetValidate untrusted JSON into a PrefabAsset, or null when malformed.
setDracoDecoderPathOverride where the DRACO decoder files (draco_wasm_wrapper.js, draco_decoder.wasm, draco_decoder.js) are fetched from. Embedding apps whose bundlers relocate this package's chunks — making the default import.meta.url resolution point at a location that is never populated — should call this before any model loads. The path must end with "/". Pass null to restore the default resolution.
resolveDracoDecoderPath-
loadSharedGltfLoad a GLTF once per URL and share the parsed result, so repeated spawns of the same model skip both the fetch and the parse. The cached scene must never be mounted directly (an Object3D has a single parent) — mount a cloneModelScene() of it. Failed loads are evicted so a retry re-fetches.
clearModelCacheForget cached models (one URL, or everything). Subsequent loads fetch and parse anew. Does not dispose GPU resources — live clones may still use them.
computeFingerCurlCurl for one finger, or null when the finger isn't tracked well enough.
computePalmWidthDistance across the knuckles — our unit of hand size.
estimateHandScaleCharacteristic hand size in metres.
computePinchHow close a fingertip is to the thumb tip. 1 = touching, 0 = far apart.
computeSpreadAngular separation between two fingers. 0 = parallel, 1 = splayed wide.
computePalmPosePalm frame, used for orientation conditions ("palm up", "thumb toward face").
computeHandShapeReduce tracked joints to the matchable shape.
matchHandPoseScore a live hand against a pose.
getHandPosePresetA deep copy of a preset.
cloneHandPose-
handPoseFromCurlsBuild a pose from five curl values — the shape the editor's sliders and the AI tools produce.
createHandMaterialBuild the material for a preset.
applyHandMaterialApply a preset material to every mesh under a hand model.
sampleTeleportArcSample a ballistic curve starting at origin heading along direction.
arcGroundCrossingWhere a sampled arc first crosses groundY going downward, or null.
angularVelocityFromAngular velocity from a rotation delta, as an axis-angle vector (rad/s).
readXrCapabilitiesRead granted features off a live session.

References ​

Component ​

Re-exports Component


Behaviour ​

Re-exports Behaviour


UiInteractionEvent ​

Re-exports UiInteractionEvent


CoreComponents ​

Renames and re-exports components


EntityId ​

Re-exports EntityId


EcsEntityKind ​

Re-exports EcsEntityKind


EcsEntityEditorKind ​

Re-exports EcsEntityEditorKind


SelectionListener ​

Re-exports SelectionListener


TextInput ​

Re-exports TextInput


FloatInput ​

Re-exports FloatInput


ColorInput ​

Re-exports ColorInput


Vector2Input ​

Re-exports Vector2Input


Vector3Input ​

Re-exports Vector3Input


SliderInput ​

Re-exports SliderInput


Re-exports DropdownOption


Re-exports DropdownInput


CheckboxInput ​

Re-exports CheckboxInput


ToggleInput ​

Re-exports ToggleInput


AssetInput ​

Re-exports AssetInput


EntityInput ​

Re-exports EntityInput


ComponentKind ​

Re-exports ComponentKind


ComponentInput ​

Re-exports ComponentInput


WorldEntityView ​

Re-exports WorldEntityView


ParentLookup ​

Re-exports ParentLookup


Vec3 ​

Re-exports Vec3


IntersectionResult ​

Re-exports IntersectionResult