destroyAudioNodePalette

Summary: Destroy the palette.


components/AudioPatchEditor

Summary: AudioPatchEditor.js - Live Material Patch Editor for Sound Studio Reads real substance audio definitions from the SubstanceRegistry and lets you tweak them on the spot. Changes feed into the ProceduralPatches runtime override system. Edits persist with scene. Layout: Material list (compact cards) + Dedicated param panel below.


createAudioPatchEditor

createAudioPatchEditor(container, callbacks = {})


components/AudioPresetBrowser

Summary: AudioPresetBrowser.js - Load/Save/Browse Patch Presets Browse built-in presets per substance, load/save patches as JSON.


getPresetPatch

Summary: Get a preset patch by name.


createAudioPresetBrowser

createAudioPresetBrowser(container, callbacks = {})

Summary: Create the preset browser panel.


destroyAudioPresetBrowser

Summary: Destroy the preset browser.


components/AudioPreviewControls

Summary: AudioPreviewControls.js - Professional Transport Bar Play/Pause/Stop with icons, elapsed time display, wave shape selector, volume control with arc knob, and waveform quick-switch.


createAudioPreviewControls

createAudioPreviewControls(container, callbacks = {})

Summary: Create the transport controls bar.


setPreviewPlaying

Summary: Set playing state externally.


destroyAudioPreviewControls

Summary: Destroy preview controls.


components/AudioSignalAnalyzer

Summary: AudioSignalAnalyzer.js - Professional Signal Analysis Panel Full-width bottom panel with switchable visualization modes: - Oscilloscope (time-domain waveform) - Spectrum Analyzer (FFT frequency bars, log scale) - Spectrogram (scrolling waterfall) Plus stereo VU/peak meter and freeze capability.


createSignalAnalyzer

Summary: Create the signal analyzer panel.


connectSignalAnalyzer

Summary: Connect an AnalyserNode for visualization.


disconnectSignalAnalyzer

Summary: Disconnect and stop rendering.


destroySignalAnalyzer

Summary: Destroy the analyzer.


components/CollabPanel

Summary: CollabPanel.js Collaboration sidebar panel for the editor.


components/GraphPersistenceContracts

Summary: Normalize legacy audio patches and validate the full candidate before use.


UnsupportedGraphVersionError

class UnsupportedGraphVersionError extends Error


prepareMaterialGraphDocument

prepareMaterialGraphDocument(input, { allowedNodeTypes = null } = {})

Summary: Normalize legacy material graphs and reject dangling connections/future schemas.


components/MaterialNodeGraph

Summary: MaterialNodeGraph.js - Canvas-based node graph editor for materials Features: pan/zoom, node drag, port connections, context menu to add nodes, node deletion, bezier connection rendering, port type coloring.


createNodeGraph

createNodeGraph(container, options = {})


evaluateGraphData

Summary: Standalone evaluator for raw graph data (no canvas UI needed). Used by headless preview animation.


components/MaterialNodePresets

Summary: MaterialNodePresets.js - Pre-built node graph recipes for all built-in materials Each preset is a valid node graph using only standard MaterialNodeTypes nodes. These serve as demos showing users how to wire nodes to create materials. Graph structure: { nodes: [...], connections: [...], view: { panX, panY, zoom } } Node: { id, type, x, y, params } Connection: { fromNode, fromPort, toNode, toPort }


getPresetGraph

Summary: Get the preset node graph for a built-in material.


hasPresetGraph

Summary: Check if a material has a preset graph.


listPresetIds

Summary: List all material IDs that have preset graphs.


listSubstancePresetIds

Summary: Get all substance-linked preset IDs.


listAnimatedPresetIds

Summary: Get all animated effect preset IDs (lava, water, hologram, etc.).


components/MaterialNodeTypes

Summary: MaterialNodeTypes.js - Node type definitions for the material graph editor Modeled after Substance Designer / Material Maker / Unreal Material Editor. Each node type defines inputs, outputs, defaults, and an evaluate function. Port types: 'float', 'vec2', 'vec3', 'vec4', 'color', 'texture'


components/MaterialPanel

Summary: MaterialPanel.js - Material Studio Panel Composes Library + PBR Inspector + 3D Preview into an overlay panel. Follows the Sound Studio (AudioEditorPanel.js) architecture.


createMaterialPanel

createMaterialPanel(container, options = {})

Summary: Create the material panel contents inside the overlay body.


destroyMaterialPanel

Summary: Destroy the material panel.


components/MaterialPatchGraphs

Summary: MaterialPatchGraphs.js - High-level node graph representations for ProceduralPatches.js These graphs provide design-facing topology for each material family. They intentionally summarize synthesis layers so editor UX stays readable even when runtime patches contain deeper stochastic/detail layers.


getMaterialGraph

Summary: Get the node graph for a substance. Returns a deep copy so edits don't mutate the template.


Summary: Maps substance IDs to editor-facing graph representations. Graphs are intentionally compact abstractions of runtime synthesis.


components/MaterialStrip

Summary: MaterialStrip.js - Compact material browser for bottom panel Horizontal scrollable strip of material thumbnails with preview sidebar. Designed to sit in the bottom panel alongside Console.


createMaterialStrip

createMaterialStrip(container, options = {})


components/ParticleEffectControls

Summary: ParticleEffectControls.js - Editor UI Controls for Custom Particle Effects Adds controls to the particle emitter inspector panel: - Checkbox to enable custom effects - Effect selector dropdown - Edit button to open shader editor - Parameter sliders for effect params


createParticleEffectControls

Summary: Create particle effect controls


components/ShaderCodeEditor

Summary: ShaderCodeEditor.js - In-Editor WGSL Code Editor Popup A notepad-style popup for editing custom particle effect shaders. Features: - Syntax highlighting for WGSL - Real-time validation - Live preview - Template snippets - Error display with line numbers


openShaderCodeEditor

openShaderCodeEditor(effect, options = {})

Summary: Create and open a shader code editor


loader-guard

Summary: Keep the loading veil's context-menu suppression CSP-safe and scoped to the short interval in which the veil can actually receive pointer input.


main

Summary: Main entry point for Game Editor


modules/ColliderGenerators

Summary: ColliderGenerators.js - Procedural collider generation utilities Extracted from EditorPhysics.js for modularity Includes: - SDF-based collider generation with anti-aliasing - Line/curve to voxel colliders - Network-based colliders (trees, tunnels, pipes) - Noise-based procedural colliders - Spatial hash for collider queries


generateCollidersFromSDF

generateCollidersFromSDF(sdfFunc, bounds, resolution = 10, options = {})

Summary: Generate colliders from ANY SDF function with anti-aliasing


generateConvexMeshFromSDF

generateConvexMeshFromSDF(sdfFunc, bounds, resolution = 16)

Summary: Generate a CONVEX MESH collider from SDF


generateHollowTorusColliders

generateHollowTorusColliders(majorRadius, minorRadius, wallThickness, resolution = 12)

Summary: Generate hollow torus colliders


generateHollowConeColliders

generateHollowConeColliders(angle, height, wallThickness, resolution = 12)

Summary: Generate hollow cone/funnel colliders


generateLineColliders

generateLineColliders(start, end, radius, resolution = 10)

Summary: Generate voxel colliders along a line segment


generateCurveColliders

generateCurveColliders(points, radius, resolution = 10, segments = 20)

Summary: Generate voxel colliders along a curve


generateCollidersFromNetwork

generateCollidersFromNetwork(network, resolution = 8)

Summary: Generate colliders from a LineNetwork


generateTreeColliders

Summary: Generate tree-shaped colliders


generateRootColliders

Summary: Generate root system colliders


generateTunnelColliders

Summary: Generate tunnel/cave colliders


generatePipeNetworkColliders

generatePipeNetworkColliders(nodes, connections, resolution = 8)

Summary: Generate custom pipe/beam network colliders


generateBezierColliders

generateBezierColliders(p0, p1, p2, p3, radius, resolution = 10)

Summary: Generate colliders along a cubic Bezier curve


generateSplineColliders

generateSplineColliders(controlPoints, radius, resolution = 10)

Summary: Generate colliders along a Bezier spline


testSphereAABB

testSphereAABB(center, radius, aabbMin, aabbMax)


generateNoisyColliders

generateNoisyColliders(baseSdf, bounds, options = {})

Summary: Generate rocky/organic colliders using noise-displaced SDF


generateRockySphereColliders

generateRockySphereColliders(center, radius, roughness = 0.15, resolution = 12)

Summary: Generate rocky sphere collider


generateTerrainColliders

generateTerrainColliders(sizeX, sizeZ, height, resolution = 8, seed = 0)

Summary: Generate terrain chunk collider


generateCaveColliders

generateCaveColliders(bounds, tunnelRadius = 1.5, resolution = 6, seed = 0)

Summary: Generate cave/hollow rock colliders


addToSpatialHash

addToSpatialHash(id, colliders, worldPosition = [0, 0, 0])


computeBounce

computeBounce(velocity, normal, restitution = 0.5)


applyFriction

applyFriction(velocity, normal, friction, dt)


predictLanding

predictLanding(start, velocity, gravity = 9.81)


modules/CollisionDebugOverlay

Summary: CollisionDebugOverlay.js - Visual debug overlay for collision layers and modes Displays collision layer, mask, and mode information for selected entities and optionally renders debug visualizations for collision relationships.


createCollisionDebugPanel

Summary: Create collision debug overlay panel


toggleCollisionDebugOverlay

Summary: Toggle collision debug overlay


dumpCollisionInfo

Summary: Get collision debug info for all entities (for console debugging)


checkCollisionConflicts

Summary: Check for collision layer conflicts (entities that should collide but don't)


modules/EditorAI

Summary: EditorAI.js - AI, Navigation, Steering, and Behavior Trees for Editor Extracted from EditorPhysics.js for modularity


getOrCreateNavGrid

Summary: Initialize or get the editor's navigation grid


findPath

Summary: Find a path between two world positions


updateNavGridFromColliders

updateNavGridFromColliders(colliders, walkable = false)

Summary: Mark cells as blocked/walkable based on colliders


smoothPath

Summary: Smooth a path using string-pulling


getPathSteering

getPathSteering(currentPos, waypoints, lookahead = 1.0)

Summary: Get steering direction to follow a path


getNavGridVisualization

Summary: Debug: visualize nav grid walkability


createAIAgent

Summary: Create an AI agent with steering behaviors


updateAIAgent

Summary: Update AI agent with combined steering behaviors


createFlock

Summary: Create a flock of AI agents


updateFlock

Summary: Update entire flock with flocking behavior


createPatrolBehavior

Summary: Create a simple patrol behavior tree


createChaseFleeBehavior

createChaseFleeBehavior(chaseRadius = 10, fleeHealth = 20)

Summary: Create a chase/flee behavior tree


tickBehaviorTree

Summary: Run a behavior tree tick


createAIPerception

Summary: Create an AI perception component


canSee

canSee(perception, position, forward, targetPos)

Summary: Check if an entity can see a target


canHear

canHear(perception, position, soundPos, soundVolume = 1)

Summary: Check if an entity can hear a sound


updateAIPerception

updateAIPerception(perception, position, forward, entities, dt)

Summary: Update perception - detect nearby entities


getLastKnownPosition

Summary: Get last known position of an entity


modules/EditorAudio

Summary: EditorAudio.js - Simulation Audio Bridge for the Editor Manages the runtime AudioEngine lifecycle during play mode: - Initializes AudioEngine on first play - Ticks audio each frame while playing - Stops all sim audio on stop/pause - Bridges substance emitters → procedural audio


startSimAudio

Summary: Called when user enters play mode. Initializes engine if needed and starts audio.


stopSimAudio

Summary: Called when user exits play mode (Stop). Stops all active sources with a short fade.


pauseSimAudio

Summary: Called when user pauses. Suspends the AudioContext (freezes all audio in place).


resumeSimAudio

Summary: Called when user resumes from pause.


tickSimAudio

Summary: Tick the audio engine. Call once per frame while playing.


destroySimAudio

Summary: Full cleanup. Call on editor close.


getSimAudioEngine

Summary: Get the current engine instance (for external integration).


modules/EditorAudioFX

Summary: EditorAudioFX.js - Procedural Editor Sound Effects All sounds are synthesized with Web Audio API oscillators & noise — no sample files. Provides: loading ambient pad, play/stop/pause chimes, UI clicks, error beeps. Usage: import { editorAudioFX } from './EditorAudioFX.js'; editorAudioFX.init();               // call once after first user gesture editorAudioFX.playChime();           // play-mode enter editorAudioFX.stopChime();           // play-mode exit editorAudioFX.pauseClick();          // pause toggle editorAudioFX.uiClick();             // generic button click editorAudioFX.uiHover();             // hover over interactive element editorAudioFX.errorBeep();           // error / invalid action editorAudioFX.startLoadingAmbient(); // loading screen ambient pad editorAudioFX.stopLoadingAmbient();  // fade out loading pad


modules/EditorCollab

Summary: EditorCollab.js Editor-side integration for the collab system. Mounts onto EditorApp and wires all hooks. Hooks wired: - EditorHistory.pushAction  → broadcast op to peers - ProjectStorage.saveProject → broadcast snapshot - PrefabLibrary.save/delete  → broadcast prefab ops - Viewport render loop       → presence tick at 10 Hz - EditorApp.enterPlayMode    → broadcast play_sync - EditorApp.togglePause      → broadcast pause_sync - EditorApp.exitPlayMode     → broadcast stop_sync


initEditorCollab

Summary: Initialize the collab system and attach it to the editor. Called from EditorApp.initialize() at the end.


destroyEditorCollab

Summary: Destroy the collab system and remove all hooks.


getCollabState

Summary: Get the current collab state from the editor.


getCollabInterpCamera

Summary: Get Hermite-interpolated camera for a remote peer (smooth, per-frame). Returns { pos: [x,y,z], target: [x,y,z] } or null.


getCollabStats

Summary: Get collab camera interpolation + connection stats for UI display.


getCollabRouterStats

Summary: Get message router stats for bandwidth monitoring. Returns { sent, dropped, coalesced, bytesSent, backpressureFrames, rateMultiplier }


getCollabInterpDelay

Summary: Get the current adaptive interpolation delay (ms). On LAN: ~20ms. On jittery connections: up to 150ms. Auto-adjusts each frame.


collabPresenceTick

Summary: Called from Viewport render loop to send presence at 10 Hz.


exportCollabTimeline

Summary: Export local timeline as JSON download.


collabTrackGrab

Summary: Notify collab that local user started grabbing an entity (play mode). Claims per-entity ownership at GRABBED priority so our transforms are authoritative.


collabUntrackGrab

Summary: Notify collab that local user released a grabbed entity. Releases per-entity ownership so default authority resumes.


collabClaimSelected

Summary: Claim ownership of an entity at SELECTED priority (inspector editing).


collabReleaseEntity

Summary: Release ownership of an entity (selected or grabbed).


getCollabEntityOwner

Summary: Get the current owner of an entity. Returns { ownerId, priority } or null.


isCollabEntityLocallyOwned

Summary: Check if the local peer owns an entity.


getCollabGrabGlows

Summary: Get map of entityId → color hex for entities being grabbed by remote peers. Used by Viewport to render grab glow.


isCollabPlayAuthority

Summary: Returns true if this peer is the physics authority during play mode. Non-authority peers should skip local physics stepping and instead receive transforms from the authority.


collabInterpolateFrame

Summary: Interpolate buffered remote transforms. Call every render frame on non-authority peers. Smoothly tweens entity positions between received keyframes with a 100ms render delay.


hostRoom

hostRoom(editor, roomId, wordKey, numberKey)

Summary: Host a room. Auto-generates word key and number key if not provided. Starts signaling so peers can discover this host.


setCollabRoom

setCollabRoom(editor, roomId, wordKey, numberKey, hostId, hostFingerprint)

Summary: Join a room with dual-key authentication (all 3 must match the host). Legacy alias: setCollabRoomId calls this.


setAnonMode

Summary: Toggle anonymous mode. Must be called BEFORE hostRoom/joinRoom. When enabled: - Peers get random anonymous IDs (different each session) - Real peer IDs are stripped from all ops - TURN-only relay hides IP addresses - Garlic encryption prevents relay from reading message content


leaveRoom

Summary: Leave the current room. Stops signaling and clears peer state. Does NOT destroy the collab system — user can Host/Join again.


generateWordKey

Summary: Generate a random word key (two words joined by a dash). 120 words × 120 words = 14,400 combinations per word pair.


generateNumberKey

Summary: Generate a random 6-digit number key. 900,000 combinations (100000-999999). Total key space with words: 120×120×900000 ≈ 12.96 billion combinations.


encodeInviteCode

encodeInviteCode(roomId, wordKey, numberKey, hostId, hostFingerprint)

Summary: Encode room credentials into a single invite code string. Format: PE-<base64url(roomId § wordKey § numberKey § hostId § hostFingerprint)> The hostFingerprint (16 hex chars) allows joiners to verify host identity.


decodeInviteCode

Summary: Decode an invite code back to { roomId, wordKey, numberKey, hostId, hostFingerprint }. Returns null if the code is invalid.


setAutoMod

Summary: Toggle auto-moderation (auto-kick, mute, throttle from integrity violations). Only the host can enable/disable. Off by default.


kickPeer

Summary: Kick a peer from the room. Only the host (first connected) should call this. Broadcasts a __kick__ op, then the kicked peer clears its stored credentials.


getSavedRoomCredentials

Summary: Get saved room credentials from localStorage.


clearRoomCredentials

Summary: Clear saved room credentials (called on kick or manual disconnect).


editorCollabCompositeSuffix

Summary: Build a composite project ID from room + wordKey + numberKey. The composite is used as the BitTorrent info_hash seed, so only peers with all 3 matching values will discover each other on the swarm. IMPORTANT: NEVER returns a bare roomId. Even without keys, a random salt is included so two users with the same folder name can't collide. The hostId (selfId of host) is mixed in when hosting to guarantee that different hosts with identical room+word+number still get unique swarms. Uses FNV-1a 64-bit (emulated as two 32-bit hashes) for collision resistance.


buildEditorCollabCompositeId

buildEditorCollabCompositeId(roomId, wordKey, numberKey, hostId)


modules/EditorGuide

Summary: EditorGuide.js — Fullscreen interactive guide overlay Future-proof feature list: - ARIA accessibility (role=dialog, aria-modal, focus trap) - Keyboard nav (Arrow keys sidebar, Tab sections, ? global shortcut) - Search / filter across all section text - localStorage progress tracking with completion badges - First-launch auto-show - Guide versioning — "what's new" badge on updates - Deep linking via URL hash (#guide-camera) - Scroll progress bar - Reading time estimates per section - Interactive demo placeholder canvases (ready for engine runtime) - Print-friendly CSS (@media print)


modules/EditorHistory

Summary: EditorHistory - Undo/Redo System with Clipboard Support Action types: - transform: Entity position/rotation/scale change - create: Entity creation - delete: Entity deletion - delete_multi: Multiple entity deletion - property: Component property change - model_animation: Imported model clip/playback state change - model_morph_weights: Imported model morph ownership/weight change - rename: Entity rename - reparent: Entity moved to different folder - paste: Paste operation (multiple entities) - folder_create: Folder creation - folder_delete: Folder deletion - folder_rename: Folder rename - component_add: Component added to entity - component_remove: Component removed from entity - selection: Selection change (for group operations) Memory optimizations: - Transform actions use quantized floats (0.001 precision for position) - Batches rapid transform changes into single action Component capture: - All ECS components listed in TRACKED_COMPONENTS are captured - Add new component types to TRACKED_COMPONENTS as they're added to engine


initHistory

Summary: Initialize history system with editor reference


selectAll

Summary: Select all entities


pushAction

Summary: Push an action to the undo stack


recordTransform

recordTransform(entityId, beforePos, beforeRot, beforeScale, afterPos, afterRot, afterScale)

Summary: Record a transform change (with batching and compression)


flushPendingTransform

Summary: Force commit any pending transform (call before other operations)


recordCreate

Summary: Record entity creation


recordDelete

Summary: Record entity deletion


recordProperty

recordProperty(entityId, componentName, propertyName, beforeValue, afterValue)

Summary: Record property change


recordRename

Summary: Record rename


recordReparent

Summary: Record entity reparent (move to different folder)


recordFolderCreate

Summary: Record folder creation


recordFolderDelete

Summary: Record folder deletion


recordFolderRename

Summary: Record folder rename


recordComponentAdd

Summary: Record component added to entity


recordComponentRemove

Summary: Record component removed from entity


recordSelectionChange

Summary: Record selection change (for group operations)


undo

Summary: Undo last action


redo

Summary: Redo last undone action


copy

Summary: Copy selected entities to clipboard


cut

Summary: Cut selected entities (copy + delete)


paste

Summary: Paste from clipboard


duplicate

Summary: Duplicate selected entities


deleteSelected

Summary: Delete selected entities


clearHistory

Summary: Clear all history


getHistoryState

Summary: Get history state for debugging


modules/EditorMeshConversions

Summary: ============================================================================ EditorMeshConversions.js — Mesh conversion operations for editor entities  Bridges Kaolin conversion modules to the editor: - Mesh → Voxel grid (MeshToVoxel) - Mesh → Point cloud (MeshToPoints) - Mesh → Soft Body (AutoTetMesh → PBD sim) - Points → Mesh (PointsToMesh) - SDF → Mesh (SDFToMesh) - Export mesh as OBJ/PLY/STL (MeshIO) ============================================================================


meshToVoxel

async meshToVoxel(editor, entityId, opts = {})

Summary: Voxelize an entity's mesh and spawn a new entity with the voxel data.


meshToPoints

async meshToPoints(editor, entityId, opts = {})

Summary: Sample points from an entity's mesh and spawn a point cloud entity.


meshToSoftBody

async meshToSoftBody(editor, entityId, opts = {})

Summary: Convert an entity's mesh to a soft body using AutoTetMesh.


pointsToMesh

async pointsToMesh(editor, entityId, opts = {})

Summary: Reconstruct a mesh from a point cloud entity.


sdfToMesh

Summary: Generate a mesh from an SDF function.


exportMesh

async exportMesh(editor, entityId, format = 'obj')

Summary: Export an entity's mesh as a downloadable file.


modules/EditorMeshOps

Summary: ============================================================================ EditorMeshOps.js — Mesh operations for editor entities  Exposes Kaolin mesh ops (subdivide, smooth, normals, validate, flip) on selected entities. Each op clones the mesh, runs the Kaolin function, re-registers with CustomMeshRegistry + EntityMeshRenderer, and pushes an undo snapshot (hybrid: auto for <50k tris, confirm dialog for larger). ============================================================================


getMeshDataForEntity

Summary: Get mesh geometry data for an entity. Checks CustomMeshRegistry first, then EntityMeshRenderer cache.


applyMeshOp

async applyMeshOp(editor, entityId, opName, params = {})

Summary: Apply a mesh operation to an entity. Pipeline: get mesh → optional undo snapshot → run op → re-register → update entity.


modules/EditorMetrics

Summary: ============================================================================ EditorMetrics.js — 3D mesh comparison metrics for the editor console  Exposes Kaolin metrics (Chamfer Distance, Hausdorff, Volumetric IoU) as editor commands for comparing mesh entities.  Usage (from editor console or script): editor.compareMeshes(entityA, entityB) editor.meshMetrics(entityA, entityB, 'chamfer') ============================================================================


setupMetricsCommands

Summary: Setup mesh metrics commands on the editor instance. Call once during editor initialization.


modules/EditorParticleSkinning

Summary: ============================================================================ EditorParticleSkinning.js — Editor bridge for learned deformation skinning  Connects Kaolin's ParticleSkinning pipeline to the editor: 1. Capture deformation snapshots from a running soft body sim 2. Extract PCA deformation modes 3. Compute skinning weights 4. Bake to animation keyframes for replay without physics 5. Runtime preview via skinning evaluator  Usage (from editor console or context menu): editor.skinning.startCapture(entityId) editor.skinning.stopCapture(entityId) editor.skinning.train(entityId, { numModes: 8 }) editor.skinning.bake(entityId, { fps: 60 }) editor.skinning.playBaked(entityId) ============================================================================


setupSkinningCommands

Summary: Set up particle skinning commands on the editor instance.


modules/EditorParticles

Summary: Initialize the particle system for the editor


initParticleSystem

async initParticleSystem(editor, device, format)


stopParticleAudio

Summary: Immediately stop all particle audio (impacts + ambients). Called when exiting play mode (Stop button).


destroyParticleSystem

Summary: Destroy the particle system


syncWorldSystemsToEmitters

Summary: Scan all active emitters' physics profiles and ensure required world systems are initialized. Call this after registering emitters or when emitter substances change.


registerEmitter

Summary: Register an emitter entity


unregisterEmitter

Summary: Unregister an emitter entity


createComposedSpellEffect

createComposedSpellEffect(editor, sourceEntityId, elements, baseConfig)

Summary: === AUTO-BLENDING SPELL EFFECT COMPOSER === Applies composed spell effect properties directly to the source emitter. Does NOT create child entities — modifies the source emitter's visual properties based on the element mix to produce a richer, more layered look. The composer analyzes the element combination and applies: - Optimized color derived from element combo - Adjusted emit rate, size, lifetime for a "spell-like" feel - Temperature and material properties from element chemistry Called by "Create Spell From This" button in EmitterInspectorCard.js.


updateEmitter

Summary: Update emitter configuration


enableEmitter

Summary: Enable an emitter


disableEmitter

Summary: Disable an emitter


toggleEmitter

Summary: Toggle emitter on/off


isEmitterEnabled

Summary: Check if emitter is enabled


getEmitter

Summary: Get emitter by entity ID (for inspector UI binding)


hasEmitter

Summary: Check if an entity has an emitter


saveEmitterToECS

Summary: Save emitter config to entity metadata for serialization


seedParticleRng

Summary: Seed the particle RNG with a shared collab seed. Call at play start so all peers produce identical particle sequences.


updateParticleQuality

updateParticleQuality(editor, frameDt, cameraPosition = null)

Summary: Feed the quality stack once per displayed frame using measured wall-clock time. Fixed simulation ticks must not drive this API because a constant 16.67 ms input hides real render pressure and prevents adaptive quality from reacting.


getParticleQualityStackStatus

Summary: Return a serializable, truthful snapshot of every active particle quality layer.


prepareDebugRenderer

Summary: Prepare a debug renderer for use (call before switching to debug mode)


isDebugRendererReady

Summary: Check if a debug renderer is ready


renderParticlesDepth

Summary: Render particles to depth texture


renderParticlesNormals

Summary: Render particles normals to texture


renderParticlesAlbedo

Summary: Render particles albedo to texture


renderParticlesLighting

Summary: Render particles lighting to texture


renderParticlesVelocity

Summary: Render particles velocity to texture


renderParticlesAge

Summary: Render particles age to texture


renderParticlesEmissive

Summary: Render particles emissive to texture


renderParticlesSize

Summary: Render particles size to texture


renderParticlesThermal

Summary: Render particles thermal/blackbody to texture


setThermalEnabled

Summary: Enable/disable blackbody thermal coloring in the main SDF render. When disabled (default), particles render with base colors only. Use the Thermal debug pass to visualize temperature separately.


renderParticles

renderParticles(pass, camera, depthTextureView, depthScale)

Summary: Render particles to the current render pass


getParticleCount

Summary: Get current particle count


clearParticles

Summary: Clear all particles - kills all living particles immediately


getParticleDecals

Summary: Get active decals for rendering (from collision events)


getDecalSpawner

Summary: Get the decal spawner (for Viewport to create its renderer)


getExtractedParticleLights

Summary: Get extracted particle lights for scene lighting


getParticleLightSystem

Summary: Get the particle light system handle


getDistortionRenderer

Summary: Get or lazy-create the distortion renderer for heat haze effects


initDistortion

Summary: Initialize distortion bind groups (call when scene color view is available)


executeDistortionPass

Summary: Execute distortion render pass (accumulate UV offsets from hot particles)


executeDistortionComposite

Summary: Composite distortion onto scene


resizeDistortion

Summary: Resize distortion texture on viewport resize


getTrailHistorySystem

Summary: Get the trail history system handle


renderTrailHistoryPass

renderTrailHistoryPass(pass, viewProj, cameraPos, time)

Summary: Render trail histories as additive fading billboards


getBeamRenderer

Summary: Get or lazy-create the beam renderer


renderBeamPass

renderBeamPass(pass, viewProj, viewRight, viewUp, time, segmentCount)

Summary: Render beam particles


getBeamSegmentCount

Summary: Get the number of beam segments to render. Returns 0 unless beam-type emitters are explicitly active in the scene. Prevents the beam renderer from treating all alive particles as a single chain.


updateBeamParams

Summary: Update beam parameters


getExistingMeshRenderer

Summary: Get the existing mesh renderer without triggering creation. Returns null if not yet created. Used by shadow caster integration.


getMeshRenderer

Summary: Get or lazy-create the mesh particle renderer


setParticleMeshGeometry

Summary: Set the mesh geometry for particle mesh rendering


renderMeshPass

renderMeshPass(pass, viewProj, cameraPos, time, instanceCount)

Summary: Render mesh particles


hasLiquidEmitters

Summary: GAP 6: Query whether any active emitter has liquid-phase particles. Viewport uses this to auto-enable/disable SSFR rendering.


getSPHSurfaceRendererHandle

Summary: Get or lazy-create the SPH surface renderer


setSPHSurfaceTintColor

Summary: GAP 13: Set SSFR tint color from substance [r, g, b].


initSPHComposite

Summary: Initialize SPH composite bind group (needs scene color view)


renderSPHSurfacePass

Summary: Render SPH fluid surface depth pass


compositeSPHSurfacePass

Summary: Composite SPH surface onto scene


getBondRenderer

Summary: Get or lazy-create the bond renderer


renderBondPass

renderBondPass(pass, viewProj, cameraPos, viewRight, viewUp)

Summary: Render bonds


setBondVisualsEnabled

Summary: Set bond visualization enabled/disabled


setBondRadius

Summary: Set bond radius for proximity detection


getFieldRenderer

Summary: Get or lazy-create the field renderer


updateFieldVisualization

Summary: Update field probes from charged particles


renderFieldPass

renderFieldPass(pass, viewProj, cameraPos, viewRight, viewUp)

Summary: Render field arrows


getOrbitalRenderer

Summary: Get or lazy-create the orbital renderer


renderOrbitalPass

renderOrbitalPass(pass, viewProj, cameraPos, viewRight, viewUp, instanceCount)

Summary: Render orbital electron clouds


isReady

Summary: Check if particle system is ready


getActiveEmitters

Summary: Get active emitters


clearAllEmitters

Summary: Clear all emitters and particles (used before scene reload)


spawnBurst

spawnBurst(position, preset = 'explosion', count = 50)

Summary: Spawn a burst of particles at a position


spawnDustPuff

spawnDustPuff(position, color, intensity = 0.5, normal)

Summary: Spawn a dust puff at a world position when fragments take damage or break. Uses small, soft point particles colored to match the breaking material. Best-practice references (real-time VFX): - Unreal Niagara: one-shot burst, soft sprite, high drag, gravity settle - Unity VFX Graph: short lifetime, size-over-life bell curve, alpha fade - GDC "The Art of Destruction": dust = desaturated material color, 0.2-0.6s


getParticleSettings

Summary: Get advanced particle system settings


setParticleSettings

Summary: Update advanced particle system settings


getParticlePerformanceStats

Summary: Get particle system performance stats


startParticleRewind

Summary: Start particle time rewind mode


stopParticleRewind

Summary: Stop particle rewind and resume simulation


seekParticleTime

Summary: Seek to a specific time in particle history Restores FULL particle state including spawn/death events


setParticleRewindSpeed

Summary: Set particle rewind playback speed


getParticleRewindInfo

Summary: Get particle rewind/snapshot info


isParticleRewinding

Summary: Check if particles are currently rewinding


clearParticleSnapshots

Summary: Clear all particle snapshots


setParticleEasing

Summary: Set particle easing type for timeline interpolation


setAdvancedInterpolation

Summary: Enable/disable advanced interpolation (Catmull-Rom/Hermite splines)


getInterpolationMode

Summary: Get current interpolation mode


getParticleEasingTypes

Summary: Get available easing types for particle rewind


initAdvancedFeatures

Summary: Initialize advanced particle features (spatial grid, line generation) Call after initParticleSystem for enhanced features


resetQualityScale

Summary: Reset quality scale to 1.0 - call when entering play mode to ensure consistent emission


updateVolumeSystem

Summary: Update the hybrid volumetric system (call before render)


renderVolumeSystem

Summary: Render the hybrid volumetric system


setVolumeMode

Summary: Set volume render mode


setVolumeEnabled

Summary: Enable/disable volume rendering


toggleVolumeRendering

Summary: Toggle volume rendering


isVolumeReady

Summary: Check if volume system is ready


getVolumeStats

Summary: Get volume system stats


setVolumeBounds

Summary: Set volume bounds


modules/EditorPhysicalMaterial

Summary: ============================================================================ EditorPhysicalMaterial.js — Runtime bridge for physical material simulation  Connects PhysicalMaterial ECS component to existing physics systems: - Collision → damage accumulation - Damage exceeds threshold → deform (voxel crater) or fracture (Voronoi) - Fracture spawns real ECS entities with Renderable + PhysicsBody + Collider - Material-specific debris FX (dust, sparks, splinters) - Fragment count scales with impact energy - Brittleness determines shatter vs bend behavior  Lazy-loads heavy modules (VoronoiFracture, AutoTetMesh) only when triggered. ============================================================================


clearPlayState

Summary: Clear all play-session state. Must be called when exiting play mode so that damage/fracture/deformation caches don't persist into the next session.


handleCollision

handleCollision(editor, entityIdA, entityIdB, impactForce, contactPoint, contactNormal, massA, massB)

Summary: Handle a collision between two entities. Called from EditorPhysics.js contact callback.


applyDamage

Summary: Apply direct damage to an entity (e.g., from explosions, scripts).


resetDamage

Summary: Reset damage on an entity.


convertToSoftBody

Summary: Convert a rigid entity to a soft body on-the-fly. Uses AutoTetMesh to generate tet volume, then PBD solver.


deformAtImpact

async deformAtImpact(editor, entityId, contactPoint, contactNormal, normalizedForce)

Summary: Deform mesh at impact point by carving a crater via voxel subtraction. If the carve disconnects pieces, broken-off pieces become fragment entities.


fractureEntity

async fractureEntity(editor, entityId, contactPoint, contactNormal, impactForce, normalizedForce)

Summary: Fracture an entity into visible fragment ECS entities using VoronoiFracture. Each fragment gets its own Renderable, PhysicsBody, and Collider. Fragment count scales with impact energy (Phase D).


updateDebris

Summary: Update debris lifecycle — call from physics step. Removes expired debris entities.


syncColliderFromMaterial

Summary: Sync collider friction/restitution from material properties. Call after material changes.


modules/EditorPhysics

Summary: Public API to manually verify collision state (useful for debugging)


createHingeJoint

createHingeJoint(world, bodyA, bodyB, options = {})

Summary: Create a hinge joint between two bodies


createBallJoint

createBallJoint(world, bodyA, bodyB, options = {})

Summary: Create a ball-socket joint (spherical)


createSpringJoint

createSpringJoint(world, bodyA, bodyB, options = {})

Summary: Create a spring/distance joint


createParticleChain

Summary: Create a particle chain using PBD (Position-Based Dynamics)


createChain

Summary: Create a chain of rigid body links


createSoftBody

Summary: Create a soft body simulation


generateSoftBodyParticles

generateSoftBodyParticles(sdfFunc, bounds, density = 100)

Summary: Generate particles for a soft body in a shape


initFractureSystem

Summary: Initialize fracture system


preFractureMesh

Summary: Pre-fracture a mesh into fragments


generateFragmentColliders

generateFragmentColliders(fragments, resolution = 6)

Summary: Generate colliders for each fragment


createBreakableCollider

Summary: Create breakable compound collider that fractures on impact


raycast

raycast(world, origin, direction, maxDistance = 1000)

Summary: Cast a ray into the physics world


raycastCone

raycastCone(world, origin, direction, coneAngle, rayCount = 8, maxDistance = 100)

Summary: Cast multiple rays in a cone pattern (for shotgun spread, vision cone, etc.)


createTriggerZone

createTriggerZone(shape, size, position = [0, 0, 0])

Summary: Create a trigger zone collider config


pointInTrigger

Summary: Check if a point is inside a trigger zone


overlapSphere

Summary: Find all entities within a sphere (using spatial hash if available)


overlapBox

Summary: Find all entities within a box


createMeshColliderDecomposed

createMeshColliderDecomposed(vertices, indices, options = {})

Summary: Create a mesh collider with automatic convex decomposition for complex shapes. Use this when you have a mesh that's too complex for a single convex hull.


createSDFCollider

createSDFCollider(sdfFunc, bounds, options = {})

Summary: Create a collider from an SDF function with automatic voxelization. Use this for procedural or mathematical shapes.


createVoxelCollider

createVoxelCollider(voxels, sizeX, sizeY, sizeZ, voxelSize = 0.1)

Summary: Create a collider grid from a 3D voxel array. Use this when you already have voxel data.


createSDFGridFromFunction

createSDFGridFromFunction(sdfFunc, bounds, resolution = 32)

Summary: Create an SDF grid for collision detection with complex shapes. Useful for soft-body or particle interactions.


checkSDFCollision

checkSDFCollision(grid, point, radius = 0)

Summary: Check if a point or sphere collides with an SDF grid.


createPhysicsChain

async createPhysicsChain(editor, startPos, endPos, options = {})

Summary: Create articulated chain between two points. Use for physics-based chains, ropes, cables.


enableSpeculativeCCDForAll

Summary: Enable speculative CCD on all dynamic bodies in the physics world. Helps prevent fast-moving objects from tunneling through thin walls.


createBroadPhaseGrid

Summary: Create a spatial hash grid for fast broad-phase collision queries. Useful for custom collision detection with many objects.


updateBroadPhaseGrid

Summary: Update all bodies in a spatial hash grid from editor entities.


getBroadPhasePairs

Summary: Get potential collision pairs from broad phase.


modules/EditorPhysicsSim

Summary: EditorPhysicsSim.js - Physics Simulation Management for Editor Manages rope, wire, hair, cloth, and soft body simulations in the editor. Uses PBD solver with OGC contact model for penetration-free simulation.


initRopeSimulation

initRopeSimulation(editor, entityId, position, opts)

Summary: Initialize rope simulation for an entity


initRopeSimulationBetweenPoints

initRopeSimulationBetweenPoints(editor, entityId, startPos, endPos, opts)

Summary: Initialize rope simulation between two points (for tool-created ropes)


initPhysXRopeSimulation

initPhysXRopeSimulation(editor, entityId, startPos, endPos, opts)

Summary: Initialize PhysX articulation-based rope simulation Uses NVIDIA PhysX for more stable, unified physics simulation


initGPURopeSimulation

initGPURopeSimulation(editor, entityId, startPos, endPos, opts)

Summary: Initialize GPU-based rope simulation using unified particle system Uses GPU constraint solver for native rope physics (Phase 2)


initWireSimulation

initWireSimulation(editor, entityId, position, opts)


initHairSimulation

initHairSimulation(editor, entityId, position, opts)


initChainSimulation

initChainSimulation(editor, entityId, position, opts)


initClothSimulation

async initClothSimulation(editor, entityId, position, opts)


initSoftBodySimulation

initSoftBodySimulation(editor, entityId, position, opts)


initSoftBodyFromMesh

async initSoftBodyFromMesh(editor, entityId, meshPositions, meshIndices, opts = {})

Summary: Initialize a soft body from an arbitrary surface mesh using AutoTetMesh. Converts the surface mesh to a tetrahedral volume mesh, then creates PBD particles and constraints from the tet nodes.


initBalloonSimulation

initBalloonSimulation(editor, entityId, position, opts)

Summary: Initialize balloon simulation (pressure-based soft body)


initFluidSimulation

initFluidSimulation(editor, entityId, position, opts)

Summary: Initialize fluid simulation (SPH density-based)


stepPhysicsSimulations

Summary: Step all physics simulations


syncSimulationsToComponents

Summary: Sync all active simulation particle data to ECS components. Call this before saving the scene to ensure particles are persisted.


initTwistedRopeSimulation

initTwistedRopeSimulation(editor, entityId, startPos, endPos, opts = {})

Summary: Initialize a twisted rope simulation with multiple threads Creates helical thread arrangement that twists together like real rope fibers


destroyPhysicsSimulation

destroyPhysicsSimulation(editor, entityId, options = {})

Summary: Destroy a physics simulation.


updateRopesForEntityMove

Summary: Check all ropes that are attached to a given entity and update them. Call this when an entity's transform changes in edit mode.


modules/EditorPointCloud

Summary: ============================================================================ EditorPointCloud.js — Point cloud entity management  Handles spawning point cloud entities from asset files (PLY/PCD/XYZ), managing the PointCloud component, and bridging to the EntityMeshRenderer point-sprite render pass. ============================================================================


spawnPointCloudAsset

Summary: Load a point cloud asset, parse it, and create an entity in the scene.


spawnPointCloudEntity

spawnPointCloudEntity(editor, pcData, opts = {})

Summary: Create a point cloud entity from raw point data.


unregisterPointCloud

Summary: Unregister a point cloud entity from the renderer.


getPointCloudData

Summary: Get point cloud data for an entity (reads PointCloud component).


modules/EditorScene

Summary: Get all entities in a welded group (parent + all children) If the entity is a child, finds its parent and returns the whole group If the entity is a parent, returns itself + all children If not welded, returns just the entity


createEntity

createEntity(editor, name = 'Entity', options = {})


createFolder

createFolder(editor, name = 'New Folder', parentId = null)


cleanupInvalidEntities

cleanupInvalidEntities(editor, intervalMs = 1000)


modules/EditorSettings

Summary: EditorSettings.js - Global Editor Settings with Persistence Features: - Centralized settings management - localStorage persistence - Settings UI with categories/tabs - Live preview of changes


modules/EditorSpawnMenu


createEmitter

createEmitter(editor, markerEntityId, type = 'gas')


modules/EditorTools

Summary: EditorTools.js - GMod-style Tool System Manages interactive tools like chain tool, weld tool, constraint tool. Tools are activated from spawn menu and handle click events in viewport.


modules/EditorTransitions

Summary: EditorTransitions.js - Transition Effects System Features: - Multiple transition effects (fade, dissolve, pixelate, wipe, zoom, etc.) - Canvas-based effects for complex transitions - Random effect selection - Configurable duration and easing - Can be used for dialogs, scenes, or any UI element


modules/EditorUI

Summary: ============================================================================ EditorUI.js - UI Setup and Menu Handling ============================================================================


showPrompt

showPrompt(title, message, defaultValue = '')

Summary: Show a custom prompt dialog


showConfirm

showConfirm(title, message, options = {})

Summary: Show a custom confirm dialog


showAlert

Summary: Show a custom alert dialog


setupSceneSelector

Summary: Setup scene selector dropdown in viewport header


refreshSceneSelector

Summary: Refresh scene selector with available scenes


updateTimelineUI

updateTimelineUI(editor, skipMarkers = false)


modules/EditorUIComponents

Summary: Show a toast notification


showToast

Summary: Show a toast notification


setTheme

Summary: Apply a theme by name - delegates to themeManager


getCurrentTheme

Summary: Get current theme name


getThemes

Summary: Get all available themes


initTheme

Summary: Initialize theme from localStorage


showThemePicker

Summary: Show theme picker dialog with categories


showContextMenu

Summary: Show a custom context menu


initTooltips

Summary: Initialize tooltip system


showShortcutsHelp

Summary: Show keyboard shortcuts overlay


modules/EditorWelding

Summary: EditorWelding.js - Auto-weld system for physics bodies Extracted from EditorPhysics.js for modularity Features: - Auto-weld colliding bodies into rigid compounds - D6 joint-based welding with PhysX optimizations - ECS component persistence for scene save/load - Emitter weld pre-scanning


createFixedJoint

createFixedJoint(editor, bodyA, bodyB, entityB)

Summary: Create a fixed joint between two bodies Uses D6 joint locked in all axes with PhysX optimizations


restoreWeldsFromComponents

Summary: Restore welds from WeldConstraint components (for scene load)


performInitialWelding

Summary: Perform initial welding of nearby bodies before simulation starts. Graph-based approach: 1. Filter eligible entities (skip ragdolls, skinned meshes, spheres/capsules) 2. Find all directly-touching pairs via AABB overlap 3. Create joints for each touching pair 4. detectWeldGroups (called after) finds connected components from joints Spheres and capsules are excluded because they are projectiles/characters, not structural elements. Only box/convexMesh entities form weldable structures.


setAutoWeld

Summary: Enable/disable auto-welding of colliding bodies


processWeldContacts

Summary: Process potential welds by checking body proximity (runtime)


clearAllWelds

Summary: Break all welds and reset


preScanEmitterWelds

Summary: Pre-scan to detect which emitters should be welded based on AABB surface proximity. Uses entity scale and physics body extents to compute surface-to-surface distance, so emitters touching any face of a large/tall object get welded correctly.


detectWeldGroups

Summary: Detect connected components of welded entities (weld groups). Runs AFTER performInitialWelding — uses editor.weldParentChildren + weldJoints. Outputs stored on editor: weldGroups: Map<rootEntityId, Set<memberEntityIds>>  (root included in set) weldChildToRoot: Map<childEntityId, rootEntityId>    (O(1) render skip) weldGroupLocalTransforms: Map<entityId, {localPos, localRot, localScale}>


buildWeldGroupMeshes

Summary: Build merged meshes for each weld group and register them with EntityMeshRenderer. Follows Unity CombineMeshes pattern: transform child vertices into root's local space. Also stores per-member mesh segment info for per-frame vertex updates.


syncWeldedEntities

Summary: Sync welded child entity transforms to their parent bodies Called from stepPhysics loop


modules/EntitySchema

Summary: Generate a full JSON schema for an entity


generateSceneSchema

Summary: Generate schemas for all entities in the scene


exportSceneToJSON

exportSceneToJSON(editor, pretty = true)

Summary: Export scene schema to JSON string


debugEntitySchema

Summary: Print entity schema to console (for debugging)


debugSceneSchema

Summary: Print full scene schema to console (for debugging)


getRelationshipSummary

Summary: Get a summary of entity relationships


modules/GeometryBuilders

Summary: GeometryBuilders.js - Procedural geometry generation for physics colliders Extracted from EditorPhysics.js for modularity


createWedgeGeometry

Summary: Create wedge/ramp geometry - flat bottom, sloped top


createPrismGeometry

Summary: Create hexagonal prism geometry


createStairsGeometry

Summary: Create stairs geometry (4 steps)


createArchGeometry

Summary: Create arch geometry with legs and curved top


createHelixGeometry

Summary: Create helix/spring geometry


createGearGeometry

Summary: Create gear geometry with teeth


createStarGeometry

Summary: Create 5-point star geometry


modules/HotkeyManager

Summary: HotkeyManager.js - Centralized Hotkey System with YAML-style Configuration Features: - Centralized hotkey definitions - Easy configuration via config object (YAML-style) - Runtime hotkey rebinding - Hotkey editor UI - localStorage persistence for custom bindings - Conflict detection


modules/LoadingManager

Summary: LoadingManager.js - Advanced loading system with progress tracking Manages dynamic loading of editor components with real progress, stage tracking, and a polished loading screen UI.


LoadingManager

Summary: LoadingManager - Tracks and displays loading progress


modules/ModelImporter

Summary: ============================================================================ ModelImporter.js - OBJ / glTF / GLB parsers + entity spawning ============================================================================


parseModelFile

Summary: Parse a model File into geometry data.


parsePointCloudFile

Summary: Parse a point cloud file into point data.


parseOBJ

Summary: Parse Wavefront OBJ text into indexed geometry. Handles v, vn, vt, f directives. Triangulates quads.


parseGLB

Summary: Parse a GLB (binary glTF 2.0) ArrayBuffer. Extracts all mesh primitives as flat position/normal/uv/index arrays.


parseGLTFJson

Summary: Parse glTF JSON + optional binary buffer into mesh geometries.


collectGLTFNodeInstances

collectGLTFNodeInstances(gltf, suppliedGraph = null)


createModelPartDescriptors

createModelPartDescriptors(result, assetId, instanceId, existingParts = null)


registerModelRuntimeMaterials

async registerModelRuntimeMaterials(editor, result, parts)


registerModelRuntimeMeshes

async registerModelRuntimeMeshes(editor, result, parts, modelInstanceId = null, modelAnimation = null, modelMorphWeights = null,)


spawnModelAsset

Summary: Load a model asset, register its mesh, and create an entity in the scene.


modules/PrefabLibrary

Summary: PrefabManager.js - Folder-based Prefab System (File-based) Based on J:\game2 implementation - proper file persistence Every entity folder is a prefab that can be: - Exported to Assets/Prefabs/*.prefab.json - Imported/instantiated into any scene - Updated (re-export overwrites) - Listed and browsed


exportFolderAsPrefab

Summary: Export a folder as a prefab data structure


savePrefabToFile

Summary: Save prefab to Assets/Prefabs/ directory


exportFolder

Summary: Export folder and save to file (combined operation)


listPrefabs

Summary: List all available prefabs in Assets/Prefabs/


loadPrefabFile

Summary: Load prefab from file


loadPrefabByUUID

Summary: Load prefab by UUID


instantiatePrefab

instantiatePrefab(editor, prefab, targetFolderId = null, offset = [0, 0, 0])

Summary: Instantiate a prefab in the scene


importPrefab

async importPrefab(editor, fileName, targetFolderId = null, offset = [0, 0, 0])

Summary: Import prefab from file and instantiate


deletePrefab

Summary: Delete prefab file


modules/ProjectStorage

Summary: ProjectManager - Save/load/export projects (pure browser, no Node.js) Uses IndexedDB + File System Access API


saveProject

Summary: Save project to IndexedDB


loadProject

Summary: Load project from IndexedDB


listProjects

Summary: List all projects


deleteProject

Summary: Delete project


getLastProjectUuid

Summary: Get last opened project UUID


createProject

Summary: Create new project


exportProject

async exportProject(project, options = {})

Summary: Export project to ZIP for distribution Strips editor-only data and packs for runtime


downloadProjectBackup

Summary: Download project as JSON file (backup)


importProjectFromFile

Summary: Import project from JSON file


enableAutoSave

enableAutoSave(project, intervalMs = 60000)


modules/SubScene

Summary: ============================================================================ SubScene.js — Parallel scene layer for debris, fragments & world environment  Lives alongside the editor scene but is NOT part of it. Objects here: - Are NOT in editor.scene.entities - Are NOT selectable, saveable, or undoable - Have their own PhysX bodies for physics simulation - Are rendered via EntityMeshRenderer in a dedicated pass - Have automatic lifecycle (fade, expire, cleanup)  Categories: 'debris'   — tiny short-lived particles (dust, sparks, splinters) 'fragment' — larger breakoff chunks from fractured meshes 'env'      — persistent world environment objects (no auto-expire)  Usage: const sub = editor.subScene; sub.spawn({ category: 'debris', meshType: 'cube', position, velocity, ... }); sub.spawnFragment(parentEntityId, { meshType, position, ... }); sub.tick(dt);          // called from stepPhysics sub.render(rp, vp, emr); // called from Viewport sub.clear();           // on play→edit transition ============================================================================


panels/AssetPanel

Summary: ============================================================================ AssetPanel.js - Bottom-panel asset browser (Unity/Unreal-inspired) ============================================================================


sampleAssetAnimationTransforms

sampleAssetAnimationTransforms(gltf, animIdx, time, binStart, buf)


panels/Hierarchy

Summary: HierarchyPanel - Entity tree view


HierarchyPanel

Summary: HierarchyPanel - Entity tree view


panels/Inspector

Summary: InspectorPanel - Component property editor


panels/SpellGeneratorPanel

Summary: SpellGeneratorPanel.js - Spell Generator Editor UI A panel for procedurally generating spells in the editor. Features: - Element selection (with combination preview) - Spell type selection - Modifier toggles - Power level slider - Live preview - Save to spell library


panels/Viewport


project/AssetRegistry

Summary: AssetRegistry.js - UUID-based asset management Adapted from J:\game2 - handles: - Asset registration and UUID assignment - Path ↔ UUID lookup - Lazy loading of asset data - Asset index persistence (Assets/index.json) - Import and update operations


UnsupportedAssetIndexVersionError

class UnsupportedAssetIndexVersionError extends Error


getAssetTypeFromExtension

Summary: Get asset type from file extension


project/AutoSave

Summary: Wrap editor methods to track dirty state


setupSaveShortcut

Summary: Setup Ctrl+S shortcut


setupNewSceneShortcut

Summary: Setup Ctrl+N for new scene


project/ProjectCompatibility

Summary: Normalize a persisted/imported project without mutating the source object.


prepareProjectRecord

prepareProjectRecord(input, { deserializeMaps = true } = {})


project/ProjectExporter

Summary: Pack data into binary format Format: [magic:4][version:4][indexOffset:4][...blobs...][index]


unpackData

Summary: Unpack binary data (for runtime)


exportScene

Summary: Export a single scene to packed binary


exportProject

async exportProject(editor, sceneDataList, options = {})

Summary: Export full project with multiple scenes


downloadZip

downloadZip(zipBuffer, filename = 'game-export.zip')


exportAndDownload

async exportAndDownload(editor, sceneDataList, options = {})

Summary: Export and download project


project/ProjectLauncher

Summary: ProjectLauncher.js - Startup screen with recent projects Adapted from J:\game2 - Unity Hub / Godot style launcher: - Recent projects list with thumbnails - New project / Open project buttons - Project templates (future)


hideLauncher

Summary: Hide launcher (for when editor is already initialized)


project/SceneManager

Summary: SceneManager.js - Scene loading, saving, and management Handles: - Scene file I/O (Scenes/*.scene.json) - Scene serialization/deserialization - Multi-scene support - Scene switching


prepareSceneForImport

Summary: Validate and fully normalize a serialized scene before touching live editor state. Missing schemaVersion is the legacy v1 format; future versions fail closed.


createSceneData

Summary: Create empty scene data with full Unity/Godot-style structure


serializeScene

serializeScene(editor, sceneName = null)

Summary: Serialize current editor scene to JSON-compatible object


deserializeScene

Summary: Validate and stage a complete scene before replacing live editor state. If an unexpected runtime failure occurs while applying it, restore the previously serialized scene so callers never inherit a half-loaded scene.


clearScene

Summary: Clear all entities and folders from scene


saveSceneToFile

async saveSceneToFile(editor, sceneName = null)

Summary: Save scene to file system


loadSceneFromFile

Summary: Load scene from file system


listScenes

Summary: List all scenes in project


deleteSceneFile

Summary: Delete scene file


newScene

Summary: Create new scene (clears current and sets name)


findEntitiesByLayer

Summary: Find all entities on a specific layer


findEntitiesByLayerMask

Summary: Find all entities matching a layer mask


findEntitiesByTag

Summary: Find all entities with a specific tag


findEntityByTag

Summary: Find first entity with a specific tag


findEnabledEntities

Summary: Find all enabled entities (active in scene)


findEntitiesByRenderFlags

findEntitiesByRenderFlags(editor, flags, matchAll = true)

Summary: Find all entities with specific render flags


findPrefabInstances

findPrefabInstances(editor, prefabUuid = null)

Summary: Find all prefab instances


getEntityConnections

Summary: Get all connections for an entity (both incoming and outgoing)


addConnection

addConnection(editor, fromEntity, signal, toEntity, method, flags = 0, binds = [])

Summary: Add a signal connection between entities


removeConnection

removeConnection(editor, fromEntity, signal, toEntity, method)

Summary: Remove a signal connection


setEntityLayer

Summary: Set entity layer


setEntityTag

Summary: Set entity tag


addEntityTag

Summary: Add tag to entity's tags array


removeEntityTag

Summary: Remove tag from entity's tags array


setEntityRenderFlags

Summary: Set entity render flags


setEntityEnabled

Summary: Set entity enabled state


project/index


spawnables/SpawnableItem

Summary: SpawnableItem - Base class for all spawnable objects in the editor. Physics collider options: - Override getCollider() to define custom colliders - Use helper imports from EditorPhysics for advanced physics: - generateCollidersFromSDF(sdfFunc, bounds, resolution) - createMeshColliderDecomposed(vertices, indices, options) - createSDFCollider(sdfFunc, bounds, options) - createVoxelCollider(voxels, sizeX, sizeY, sizeZ, voxelSize) ```js import { generateCollidersFromSDF } from '../../modules/EditorPhysics.js'; static getCollider() { return { shape: 'box', halfExtents: [0.01, 0.01, 0.01], compoundColliders: generateCollidersFromSDF( (x, y, z) => mySDF(x, y, z), { min: [-1, -1, -1], max: [1, 1, 1] }, 12 ), }; } ```


spawnables/cameras/Camera


spawnables/complex/Arch


spawnables/complex/CSGShape

Summary: ============================================================================ CSGShape.js — CSG Boolean operations on mesh entities  Select 2 mesh entities → right-click → CSG Union / Subtract / Intersect V1: Voxelize both → VoxelOps boolean → SDFToMesh marching cubes reconstruct V2: Voxelize both → VoxelOps boolean → DualContouring for sharp features ============================================================================


performCSG

async performCSG(editor, entityIdA, entityIdB, operation = 'union', opts = {})

Summary: Perform a CSG boolean operation on two mesh entities.


spawnables/complex/Gear


spawnables/complex/Helix


spawnables/complex/Prism


spawnables/complex/Pyramid


spawnables/complex/SDFShape


spawnables/complex/Stairs


spawnables/complex/Star


spawnables/complex/Wedge


spawnables/emitters/ParticleEmitter


ParticleEmitter

class ParticleEmitter extends SpawnableItem


spawnables/emitters/PhaseEmitters


spawnables/index


spawnables/lights/DirectionalLight


DirectionalLight

class DirectionalLight extends SpawnableItem


spawnables/lights/PointLight


spawnables/lights/SpotLight


spawnables/physics/Balloon


spawnables/physics/Chain


spawnables/physics/Cloth


spawnables/physics/Fluid


spawnables/physics/Hair


spawnables/physics/Ragdoll


spawnables/physics/Rope


spawnables/physics/RopeSchema

Summary: ============================================================================= ROPE SCHEMA - Shared schema for RopeTool and PhysicsRopeComponentEditor =============================================================================


getFiberMaterial

Summary: Get fiber material properties by name


applyFiberMaterial

Summary: Apply fiber material preset to rope data


Summary: Fiber material properties - affects both physics and rendering


Summary: Default values for rope properties


Summary: Material presets for quick setup


Summary: Fiber material options for dropdown


Summary: Unified inspector schema for rope properties Used by both RopeTool and PhysicsRopeComponentEditor Organized into logical groups with the most commonly used options first


spawnables/physics/SoftBody


spawnables/physics/Wire


spawnables/primitives/Capsule


spawnables/primitives/Cone


spawnables/primitives/Cube


spawnables/primitives/Cylinder


spawnables/primitives/Plane


spawnables/primitives/Sphere


spawnables/primitives/Torus


spawnables/tools/ConstraintTool


ConstraintTool

class ConstraintTool extends SpawnableItem


spawnables/tools/RemoverTool


spawnables/tools/RopeTool


spawnables/tools/SpringTool


spawnables/tools/WeldTool


storage/EditorPreferenceContracts

Summary: Canonical localStorage contracts for structured editor preferences. The original keys remain v1 rollback mirrors. Current clients publish the legacy payload first and the v2 envelope last. The envelope remembers the exact legacy JSON it accompanied, allowing a later write from an older tab to be detected and read instead of being shadowed by stale v2 data.


EditorPreferenceContractError

class EditorPreferenceContractError extends Error


storage/GameEditorDatabase

Summary: The single schema owner for editor IndexedDB persistence. Version 1 was opened independently by main.js and ProjectStorage.js, which meant only the first caller's object store was created. Version 2 expands the database to contain both stores without removing any version-1 data.


themes/cyberpunk

Summary: Cyberpunk Theme - Neon pink and cyan


themeCyberpunk

Summary: Cyberpunk Theme - Neon pink and cyan


themes/dark

Summary: Dark Theme - Default editor theme


themeDark

Summary: Dark Theme - Default editor theme


themes/index

Summary: Theme System Index Central theme management with modular theme files


themes/light

Summary: Light Theme - Clean bright interface


themeLight

Summary: Light Theme - Clean bright interface


themes/matrix

Summary: Matrix Theme - Hacker green aesthetic


themeMatrix

Summary: Matrix Theme - Hacker green aesthetic


themes/midnight

Summary: Midnight Blue Theme - Deep blue professional theme


themes/monokai

Summary: Monokai Theme - Classic code editor colors


themes/nord

Summary: Nord Theme - Arctic, north-bluish color palette


themes/ocean

Summary: Ocean Theme - Deep sea blues and teals


themeOcean

Summary: Ocean Theme - Deep sea blues and teals


themes/purple

Summary: Purple Haze Theme - Vibrant purple aesthetic


themes/solarized

Summary: Solarized Dark Theme - Ethan Schoonover's iconic palette


utils/CompressionManager

Summary: CompressionManager - Manages background compression via WebWorker Provides async compression/decompression for timeline and undo history


initCompressionWorker

Summary: Initialize the compression worker


estimateCompressedSize

Summary: Get memory estimate for compressed data


utils/DialogAnimations

Summary: DialogAnimations.js - Smooth open/close animations for all dialogs Provides consistent animation utilities for modals and dialogs


smoothCloseDialog

smoothCloseDialog(dialog, duration = 300)

Summary: Smoothly close a dialog with fade-out animation


smoothCloseModal

Summary: Smoothly close a modal with fade-out animation


closeOnBackdropClick

closeOnBackdropClick(dialog, contentSelector = '.editor-dialog-box, .modal-content, .settings-dialog')

Summary: Close dialog on backdrop click (outside content area)


closeOnEscape

Summary: Close dialog on Escape key


setupDialogCloseHandlers

setupDialogCloseHandlers(dialog, options = {})

Summary: Setup all standard dialog close handlers


utils/FrameSpikeDetector

Summary: FrameSpikeDetector.js - Detect and log frame time spikes Monitors frame times and logs detailed information when spikes occur, helping identify performance bottlenecks and optimization opportunities.


utils/FrustumCulling

Summary: Extract and normalize frustum planes from a 4×4 view-projection matrix. Uses Gribb-Hartmann method (column-major matrix). Must be called once per frame before any culling tests.


isSphereInFrustum

Summary: Test if a bounding sphere is inside or intersects the frustum.


isAABBInFrustum

isAABBInFrustum(minX, minY, minZ, maxX, maxY, maxZ, planes)

Summary: Test if a world-space AABB intersects the frustum. Uses the P-vertex method: for each plane pick the AABB corner most in the direction of the plane normal (the "positive" vertex). If that corner is behind the plane, the entire box is outside.


isAABBCenterExtentsInFrustum

isAABBCenterExtentsInFrustum(cx, cy, cz, ex, ey, ez, planes)

Summary: Convenience: test AABB from center + half-extents (world space). Converts to min/max and delegates.


isEntityAABBVisible

isEntityAABBVisible(entityPos, entityScale, localCenter, localExtents, planes)

Summary: High-level entity visibility test using AABB. Takes the mesh's local-space AABB center+extents, the entity's world position and scale, and produces the world-space AABB for frustum testing.


isEntitySphereVisible

Summary: Legacy: entity visibility using bounding sphere (kept for broad-phase / fallback).


getFrustumPlanes

Summary: Get current frustum planes (for debugging / external use)


getFrustumCorners

Summary: Calculate frustum corners in world space (for debug visualization)


utils/GPUBufferPool

Summary: Get a buffer from pool or create new one


getBuffer

getBuffer(device, size, usage, label = '')


releaseBuffer

Summary: Return a buffer to the pool


getPoolStats

Summary: Get pool statistics


clearPools

Summary: Clear all pools and destroy buffers


trimPools

Summary: Trim pools to reduce memory


utils/InterpolationCurves

Summary: Animation track - keyframe-based animation


Tween

Summary: Tween - simple value animation


smoothstep

Summary: Smoothstep interpolation (Hermite)


smootherstep

Summary: Smootherstep (Ken Perlin's improved version)


springInterpolation

springInterpolation(t, stiffness = 100, damping = 10)

Summary: Spring interpolation with damping


bounceInterpolation

Summary: Bounce interpolation


lerp

Summary: Interpolate between two values with easing


lerpVec3(from, to, t, easing = 'linear')

Summary: Interpolate between two vec3s with easing


slerp

Summary: Spherical linear interpolation for quaternions (SLERP)


catmullRom

Summary: Catmull-Rom spline interpolation (passes through all control points)


bSpline

Summary: B-Spline interpolation (smooth curve, doesn't pass through control points)


hermite

Summary: Hermite spline interpolation


utils/MemoryIntegration

Summary: MemoryIntegration.js - Wires up off-heap memory to editor/engine systems Integrates OffHeapMemoryManager with: - Particle snapshot system (large frame buffers → WASM/Worker) - Editor history (old undo entries → IDB) - Asset cache (loaded assets → Worker memory) - Profiler timeline (frame history → off-heap)


initMemoryIntegration

async initMemoryIntegration(gpuDevice = null)

Summary: Initialize memory integration


getMemoryPressure

Summary: Get current memory pressure (0-1)


shouldOffload

Summary: Check if we should offload to off-heap storage


storeParticleFrame

Summary: Store particle frame in off-heap memory Large frames (>100KB) go to worker memory


retrieveParticleFrame

Summary: Retrieve particle frame from off-heap storage


archiveHistoryEntry

Summary: Store old history entry to IDB when memory pressure is high


retrieveHistoryEntry

Summary: Retrieve archived history entry from IDB


cacheAsset

Summary: Store large asset in worker memory


retrieveCachedAsset

async retrieveCachedAsset(uuid, asText = false)

Summary: Retrieve cached asset from worker memory


storeProfilerFrames

Summary: Store profiler frame batch in WASM memory


getMemoryStats

Summary: Get comprehensive memory stats


formatMemoryForProfiler

Summary: Format memory stats for profiler display


utils/ObjectPool

Summary: Get a Float32Array of specified size from pool


Summary: Return a Float32Array to the pool


getArray

Summary: Get a generic array from pool


releaseArray

Summary: Return a generic array to the pool


Summary: Get a vec3 [x, y, z] from pool


Summary: Return a vec3 to pool


Summary: Get a vec4 [x, y, z, w] from pool


Summary: Return a vec4 to pool


Summary: Get a mat4 (16 floats) from pool


Summary: Return a mat4 to pool


getPoolStats

Summary: Get pool statistics


clearPools

Summary: Clear all pools (for memory pressure situations)


trimPools

Summary: Trim pools to reduce memory (keep some for reuse)


utils/OffHeapMemory

Summary: OffHeapMemory.js - MAXIMUM Memory Expansion System Pushes browser memory limits to the absolute maximum using every available strategy: 1. Multi-WASM Pool - Multiple 4GB WASM modules (up to 16GB+ total) 2. Worker Memory Pool - Each worker has its own ~4GB heap 3. SharedArrayBuffer - Zero-copy cross-worker/thread communication 4. GPU Buffer Storage - VRAM is separate from system RAM limits 5. IndexedDB Sharding - Multiple databases for unlimited persistent storage 6. ArrayBuffer Pooling - Aggressive reuse to minimize GC pressure 7. Memory Pressure Management - Auto-offloading and tiered storage THEORETICAL MAXIMUM: - 4 WASM modules × 4GB = 16GB - 8 Workers × 4GB heap = 32GB (but shared address space limits this) - GPU buffers = Limited by VRAM (8-24GB on modern GPUs) - IndexedDB = Unlimited (disk-backed) PRACTICAL MAXIMUM: ~8-16GB usable off-heap memory


MultiWasmMemoryPool

Summary: Multi-WASM Memory Pool Creates multiple WASM memory instances, each up to 4GB Total capacity: up to 16GB off-heap


ArrayBufferPool

Summary: ArrayBuffer pool for reducing GC pressure Reuses buffers instead of creating new ones


GPUBufferStorage

Summary: GPU buffer storage for large data Keeps data in VRAM instead of JS heap


IndexedDBStorage

Summary: IndexedDB storage for large persistent data


WorkerMemoryPool

Summary: Worker-based memory expansion Each Web Worker has its own JS heap (~4GB potential) Spawn multiple workers to multiply available memory


SharedRingBuffer

Summary: SharedArrayBuffer Ring Buffer Zero-copy data sharing between main thread and workers Requires Cross-Origin-Isolation headers


MaxGPUBufferStorage

class MaxGPUBufferStorage extends GPUBufferStorage

Summary: Maximum GPU Buffer Storage Aggressively uses VRAM for data storage


OffHeapMemoryManager

Summary: MAXIMUM Memory Expansion Manager Combines ALL strategies for absolute maximum memory capacity


invalidateLegacyOffHeapCaches

async invalidateLegacyOffHeapCaches(indexedDBApi = globalThis.indexedDB)


initOffHeapManager

async initOffHeapManager(device = null, options = {})


utils/PhysicsBodyPool

Summary: Get a body handle from pool or signal that new one is needed


releaseBody

releaseBody(physicsWorld, bodyHandle, simMode, colliderShape)

Summary: Return a body to the pool for reuse


resetPooledBody

resetPooledBody(physicsWorld, bodyHandle, position, rotation, scale)

Summary: Reset a pooled body for reuse with new transform


getPoolStats

Summary: Get pool statistics


clearPools

Summary: Clear all pools (destroys pooled bodies)


trimPools

Summary: Trim pools to reduce memory


utils/RenderBundleCache

Summary: Create or get cached render bundle


getOrCreateBundle

getOrCreateBundle(device, key, version, descriptor, recordFn)

Summary: Create or get cached render bundle


invalidateBundle

Summary: Invalidate a specific bundle (force re-record next frame)


invalidateBundlesWithPrefix

Summary: Invalidate all bundles matching a prefix


clearBundleCache

Summary: Clear all cached bundles


pruneOldBundles

Summary: Remove bundles not used recently


getCacheStats

Summary: Get cache statistics


createStandardDescriptor

createStandardDescriptor(colorFormat = 'bgra8unorm', depthFormat = 'depth24plus')

Summary: Helper to create standard descriptor for color + depth rendering


executeBundles

Summary: Execute render bundles in a render pass


utils/SIMDMath

Summary: Create a batch of vec3s in SoA format


Summary: Create a batch of vec3s in SoA format


Summary: Create batch from array of [x,y,z] vectors


Summary: Convert batch back to array of [x,y,z]


batchAdd

batchAdd(a, b, out = createVec3Batch(a.count)

Summary: Batch add: out = a + b


batchSub

batchSub(a, b, out = createVec3Batch(a.count)

Summary: Batch subtract: out = a - b


batchScale

batchScale(a, scalar, out = createVec3Batch(a.count)

Summary: Batch scale: out = a * scalar


batchMul

batchMul(a, b, out = createVec3Batch(a.count)

Summary: Batch multiply component-wise: out = a * b


batchDot

batchDot(a, b, out = new Float32Array(a.count)

Summary: Batch dot product: out[i] = dot(a[i], b[i])


batchCross

batchCross(a, b, out = createVec3Batch(a.count)

Summary: Batch cross product: out = a × b


batchLengthSq

batchLengthSq(a, out = new Float32Array(a.count)

Summary: Batch length squared: out[i] = |a[i]|²


batchLength

batchLength(a, out = new Float32Array(a.count)

Summary: Batch length: out[i] = |a[i]|


batchNormalize

batchNormalize(a, out = createVec3Batch(a.count)

Summary: Batch normalize: out[i] = normalize(a[i])


batchLerp

batchLerp(a, b, t, out = createVec3Batch(a.count)

Summary: Batch lerp: out = lerp(a, b, t)


batchTransform

batchTransform(batch, m, out = createVec3Batch(batch.count)

Summary: Batch transform by 4x4 matrix


batchDistanceToPoint

batchDistanceToPoint(batch, point, out = new Float32Array(batch.count)

Summary: Batch distance to point


batchDistanceSqToPoint

batchDistanceSqToPoint(batch, point, out = new Float32Array(batch.count)

Summary: Batch distance squared to point (faster, for comparisons)


batchFindWithinRadius

Summary: Find indices within radius of point


batchFindKNearest

Summary: Find K nearest neighbors


batchComputeAABB

Summary: Batch AABB computation


utils/SpatialIndex

Summary: Simple Octree for dynamic entity queries Better for frequently changing scenes than BVH


EntitySpatialIndex

Summary: EntitySpatialIndex - Manages spatial indexing for editor entities


utils/TextureCompression

Summary: TextureCompression - WebGPU compressed texture format support. Supports: - BC formats (Desktop: DXT/S3TC) - ASTC formats (Mobile/Apple) - ETC2 formats (Android/WebGL fallback)


detectCompressedFormats

Summary: Detect supported compressed texture formats.


getOptimalFormat

getOptimalFormat(adapter, needsAlpha = true)

Summary: Get optimal texture format for device.


getCompressedSize

Summary: Calculate compressed texture size.


getMemorySavings

Summary: Calculate memory savings percentage.


getQualitySizeScore

getQualitySizeScore(width, height, format, options = {})

Summary: Calculate a quality-size report for picker and audit UI.


createCompressedTexture

Summary: Create compressed texture with fallback.


getFormatInfo

Summary: Get format info for display.


utils/WeakCache

Summary: WeakValueMap - Map with weak references to values Values are auto-removed when garbage collected


LRUCache

Summary: LRUCache - Least Recently Used cache with max size


TTLCache

Summary: TTLCache - Cache with time-to-live expiration


viewport/AuraRenderer

Summary: AuraRenderer — System 1: Outer Energy Shell / Aura Layer ========================================================= Renders the actual model mesh at slightly expanded scale with electric blue-cyan color — same approach as SkinRenderer but bigger and more transparent. No hull approximation needed; the real mesh IS the aura shell. LAYER ROLE: Outermost visible layer — glowing energy field that exactly traces the body shape at AURA_SCALE (8% larger than entity scale). VISUAL: - Full-res model mesh, electric blue-cyan [0.2, 0.7, 1.0, 0.15] - Scale multiplied by AURA_SCALE so it sits slightly outside the skin - High roughness for a soft diffuse glow look DATA SOURCE: EntityMeshRenderer already has 'custom_<uuid>' registered. No extra work. INDEPENDENCE: - No imports needed beyond EntityMeshRenderer (draw) - No reference to SkinRenderer, SkeletonRenderer, SDFColliderRenderer


viewport/CameraController


viewport/CollabOverlayRenderer

Summary: CollabOverlayRenderer.js Renders peer cameras as small 3D camcorder-style pyramids in the viewport, with colored tint matching the peer's chosen color and a floating name label. Uses the existing EntityMeshRenderer to draw pyramids (no new GPU pipelines needed). Name labels are HTML overlays positioned via 3D→2D projection.


viewport/GhostPreviewRenderer


viewport/SDFColliderRenderer


viewport/ShapeWireframes

Summary: ShapeWireframes.js — Shared shape-specific wireframe generators ================================================================ Used by SkeletonRenderer, SkinRenderer, and AuraRenderer to render shape-accurate wireframe overlays that match the SDF collider shapes. Each generator returns { joints: [[x,y,z],...], edges: [[i,j],...] } in LOCAL space. The caller transforms to world space.


generateShapeWireframe

generateShapeWireframe(meshType, es, ep, er, doRot)

Summary: Generate a shape-specific wireframe for an entity.


quatFromDir

Summary: Compute quaternion that aligns Y-axis [0,1,0] with direction [dx,dy,dz]. Exported for use in renderers that draw capsule sticks between joints.


viewport/SkeletonRenderer

Summary: SkeletonRenderer — System 3: X-Ray Skeleton / Bone Layer ========================================================= Renders the internal skeleton as solid physical geometry — gold ball joints at each bone pivot, ivory metallic bone sticks connecting them. Think medical X-ray imaging or the internal rig view in a 3D animation tool. LAYER ROLE: Innermost visible layer — inside the skin capsules. Fully opaque metallic geometry. Shows the exact bone hierarchy as a physical rig. VISUAL: Ball joints: gold [1.0, 0.85, 0.3, 1.0], metallic=0.9, roughness=0.15 Bone sticks: ivory [0.95, 0.9, 0.8, 1.0], metallic=0.85, roughness=0.2 Sizes scaled by body height — proportionally correct DATA SOURCE: getAnimatedBoneShapes() → .joints[] (all joint world positions + child links) INDEPENDENCE: - Imports ONLY from SkeletalAnimation.js (data) and EntityMeshRenderer (draw) - No reference to AuraRenderer, SkinRenderer, SDFColliderRenderer - Can be deleted without affecting any other system EDIT MODE vs PLAY MODE: Edit: animated bone joints from getAnimatedBoneShapes() Play (ragdoll): bone positions from live physics bodies


viewport/SkinRenderer

Summary: SkinRenderer — System 2: High-Detail Body Skin ================================================ Renders the ACTUAL mesh geometry of the entity, semi-transparent, with a warm skin tone. Full triangle count of the imported model — this is NOT a hull approximation. The mesh IS the skin layer. LAYER ROLE: Inner visible layer — shows the real body geometry as a translucent skin shell. Since it uses the same mesh as the actual entity render, it is perfectly shape-accurate at full detail. VISUAL: - Full-res model mesh, warm skin tone [0.9, 0.6, 0.4, 0.28] - Rendered via the existing 'custom_<uuid>' mesh key already in EntityMeshRenderer - No separate mesh registration needed — the mesh is already uploaded DATA SOURCE: EntityMeshRenderer already has the 'custom_<uuid>' mesh registered when the entity loads. No separate computation needed — just pass entity transform directly. INDEPENDENCE: - No external imports needed beyond EntityMeshRenderer (draw) - No reference to AuraRenderer, SkeletonRenderer, SDFColliderRenderer


viewport/SurfaceGridRenderer

Summary: SurfaceGridRenderer.js GMod-style surface grid overlay for precise tool placement Shows a transparent green grid aligned to the surface normal


viewport/ViewportMeshUtils

Summary: ViewportMeshUtils - Mesh type inference and color mapping utilities Extracted from Viewport.js for modularity


getSpawnIdLower

Summary: Get lowercase spawnId for an entityMeta (no caching — small string allocs are cheaper than WeakMap GC overhead)


isEmitterEntity

Summary: Check if entityMeta represents an emitter


getEntityMeshTypes

getEntityMeshTypes(entityMeta, fallbackMeshType = null)


getEntityMeshParts

getEntityMeshParts(entityMeta, fallbackMeshType = null)


getModelPartLocalMatrix

getModelPartLocalMatrix(part, animatedMatrix = null)


composeEntityPartMatrix

composeEntityPartMatrix(position, rotation, scale, part, animatedMatrix = null)


getAggregateMeshBounds

getAggregateMeshBounds(entityMeta, meshRenderer, fallbackMeshType = null, resolveAnimatedMatrix = null)


inferMeshMaterial

Summary: Get PBR material properties for a mesh type


inferEntityMeshTypeAndColor

Summary: Infer mesh type and color from entity metadata Results are cached for performance


clearMeshTypeCache

Summary: Clear mesh type cache (call when entities are added/removed/renamed)


snapToGrid

Summary: Snap a value to grid


viewport/ViewportProfiler

Summary: ViewportProfiler - Performance profiler UI for the viewport Extracted from Viewport.js for modularity


viewport/ViewportRaycasting

Summary: ViewportRaycasting.js - Pure raycasting math utilities Extracted from Viewport.js for modularity


rayGroundPlaneIntersect

rayGroundPlaneIntersect(rayOrigin, rayDir, planeY = 0)

Summary: Ray-ground plane intersection


raySegmentDistance

raySegmentDistance(rayOrigin, rayDir, segA, segB)

Summary: Calculate distance from ray to line segment (for rope picking)


raySphereIntersect

raySphereIntersect(rayOrigin, rayDir, sphereCenter, radius)

Summary: Ray-sphere intersection test


rotatePointByQuaternion

Summary: Rotate a point by quaternion


multiplyQuaternions

Summary: Multiply two quaternions: result = a * b


rayOBBIntersect

rayOBBIntersect(rayOrigin, rayDir, boxCenter, boxRotation, halfExtents)

Summary: Ray-OBB (Oriented Bounding Box) intersection


closestPointOnAxis

closestPointOnAxis(rayOrigin, rayDir, axisOrigin, axisDir)

Summary: Closest point on axis from ray


viewport/stages/FixedStepStages

Summary: FixedStepStages — Physics, elastic drag, sim audio, particle step. These run 0..N times per frame on a fixed timestep accumulator. Only active in play mode (condition-gated).


registerFixedStepStages

Summary: Register all fixedStep-phase stages into the pipeline.


viewport/stages/PostRenderStages

Summary: PostRenderStages — Composite passes, post-FX, GPU submit, profiler, spike detection, collab presence. During the transitional period, post-render work still lives inside Viewport.renderFrame(). These stages will be populated one-by-one as code is extracted.


registerPostRenderStages

Summary: Register all postRender-phase stages into the pipeline.


viewport/stages/RenderStages

Summary: RenderStages — GPU render pass stages: debug targets, volume compute, clear pass, grid, entities, physics lines, cloth, surface grid, particles, diagnostics, SDF colliders, bone directions, gizmos. During the transitional period, the main renderFrame() body still runs inline. These stages will be populated one-by-one as code is extracted from Viewport.renderFrame(). Stage order values reserve gaps (10, 20, 30…) so new stages can be inserted between existing ones without renumbering.


registerRenderStages

Summary: Register all render-phase stages into the pipeline.


viewport/stages/UpdateStages

Summary: UpdateStages — Per-frame update logic: timing, vGPU, camera, matrices, lights, animation, frustum, collab, stats UI, cleanup. Runs once per frame before GPU render passes.


registerUpdateStages

Summary: Register all update-phase stages into the pipeline.


workers/CollabSignalWorker

Summary: CollabSignalWorker.js — SharedWorker In-memory SDP relay for all editor tabs on the same machine. Runs once per origin, shared across all tabs. Message types (client → worker): HELLO    { peerId, username } OFFER    { from, to, offerId, payload } ANSWER   { from, to, offerId, payload } CANDIDATE { from, to, offerId, payload } LEAVE    { peerId } LIST     (request peer list) Message types (worker → client): HELLO_ACK   { peerId, peers: [{peerId, username}] } PEER_JOINED { peerId, username } PEER_LEFT   { peerId } OFFER       { from, to, offerId, payload } ANSWER      { from, to, offerId, payload } CANDIDATE   { from, to, offerId, payload } LIST        { peers: [{peerId, username}] }


workers/CompressionWorker

Summary: CompressionWorker - Offloads timeline/history compression to background thread Uses delta+entropy residual encoding for lossless reconstruction


workers/ProfilerCanvasWorker

Summary: ProfilerCanvasWorker.js - OffscreenCanvas worker for profiler rendering Moves ALL canvas rendering off the main thread: - Timeline graph - Thread lanes - Flame graph bars Main thread only sends frame data, worker handles all drawing.


EcsImports


EngineBootstrap

Summary: EngineBootstrap.js - Unified engine import for games and tests Single import point for all engine functionality: - Math utilities - ECS (Entity Component System) - Rendering (meshes, shaders, pipelines) - Tools (inspector, camera, physics sandbox) - GPU utilities (buffers, WebGPU init) - Simulation (particles, fluids) - Configuration


EngineEditorBootstrap

Summary: EngineEditorBootstrap.js - Combined Engine + Editor entry point Use this as the entry point when you want the FULL library bundled: - All engine modules (math, ECS, rendering, simulation, audio, tools) - All editor modules (viewport, physics sim, particles, collab, UI) Usage: python bundle_engine.py --entry engine/EngineEditorBootstrap.js --eager The bundled runtime exposes everything on window.PE / window.ParticleEngine: PE.vec3(), PE.createWorld(), PE.EditorApp, etc.


EngineImports

Summary: Global barrel for engine modules, grouped by domain. This is intended for games/tests/tools that want a single import and then access Math/Gpu/Ecs/Render/Tools/etc as namespaces.


MathImports

Summary: MathImports: convenience barrel for engine math utilities. Provides both a grouped Math namespace and flat re-exports for common ops.


RenderImports


ToolsImports


animation/index


animation/learning/FbxMotionExtractor


extractMotionClipFromFbxAscii

extractMotionClipFromFbxAscii(text, options = {})


extractMotionDatasetFromFbxAsciiEntries

extractMotionDatasetFromFbxAsciiEntries(entries, options = {})


extractMotionDatasetFromFbxFiles

async extractMotionDatasetFromFbxFiles(files, options = {})


async extractMotionDatasetFromFbxDirectoryHandle(dirHandle, options = {})


animation/learning/GltfMotionExtractor


extractMotionDatasetFromGltf

extractMotionDatasetFromGltf(gltf, options = {})


extractMotionClipFromGltf

extractMotionClipFromGltf(gltf, animationIndex = 0, options = {})


animation/learning/MotionClip


animation/learning/MotionDataset


animation/learning/MotionFeatures


buildJointPositionDataset

buildJointPositionDataset(clip, options = {})


buildMotionFeatureIndex

buildMotionFeatureIndex(dataset, options = {})


fillRagdollFeature

fillRagdollFeature(ragdoll, boneIndices, out, options = {})


animation/learning/MotionMatcher


animation/learning/SkeletonHierarchy


animation/learning/index


assets/AssetCache

Summary: engine/assets/AssetCache.js — local engine cache (spec §3, cache://).  Converted artifacts (engine binaries, preview meshes, thumbnails, colliders, SDFs, material packs) are cached under cache:// keyed by content hash so a re-import of the same source is instant. The primary backend is the Origin Private File System (OPFS) — origin-private and optimized for file access; an in-memory Map backs environments without OPFS (Node tests, locked-down contexts) so the rest of the runtime is backend-agnostic.


assets/AssetDeduper

Summary: engine/assets/AssetDeduper.js — content-hash dedup (spec §3).  Assets are deduplicated by source content hash. We separate source / mesh / material hashes so that the dedup rules can distinguish exact duplicates from variants and conflicts: same source hash               = same source asset (exact duplicate) same name + different hash      = version/conflict same mesh hash + diff material  = variant same texture hash               = shared texture Hashing prefers Web Crypto SHA-256; in a non-secure context it falls back to a deterministic FNV-1a stamp (clearly tagged so callers know it isn't crypto).


hashContent

Summary: Content hash of arbitrary data. Returns 'sha256:<hex>' (secure) or 'fnv1a:<hex>' (fallback). Async because Web Crypto digest is async.


classify

Summary: Classify a candidate against the existing records.


assets/AssetRecord

Summary: engine/assets/AssetRecord.js — the registry's record for one source asset.  The asset registry (not the filesystem) is the source of truth. Each record tracks the source content hash, a primary virtual path, redundant backup paths, the set of converted engine artifacts, and license metadata. Records are deduplicated by source hash; variants/conflicts are linked, never merged blindly (see AssetDeduper / AssetRegistry).


createAssetRecord

Summary: Create an asset record.


createLicenseBlock

Summary: License metadata is mandatory before import (unknown is allowed but flagged). Marketplace assets are licensed, not sold — track it and warn on restricted.


licenseNeedsReview

Summary: True if the license is unknown or explicitly disallows engine conversion.


assets/AssetRegistry

Summary: engine/assets/AssetRegistry.js — the source of truth (spec §3, rule 3).  The registry (not the filesystem) owns asset identity. Sources are deduplicated by content hash; the registry links exact duplicates, variants, and conflicts rather than merging them blindly. Registering an already-known source returns the canonical record (idempotent), so re-importing the same file never produces a second asset.


assets/AssetResolver

Summary: engine/assets/AssetResolver.js — virtual-path resolution + backup repair (spec §3, rule 5). Files move, browser permissions expire, cloud mirrors lag. The resolver maps a scheme:// path to a concrete backend and, when reading a registered asset, tries the primary then each backup, verifying by content hash. If a backup matches the expected hash it repairs the primary; if a candidate's hash differs it is flagged a conflict (never silently accepted).


AssetResolver

Summary: A backend is { async read(path) -> Uint8Array|null, async write?(path, bytes) }. Schemes without a registered backend simply fail to resolve (caller falls back).


backendFromCache

Summary: Adapt an AssetCache instance to a resolver backend (cache:// scheme).


makeFetchBackend

Summary: A read-only backend that fetches relative to a base URL (asset://, cloud://).


makeMemoryBackend

Summary: A simple in-memory backend (temp:// drag-drop, user:// session mounts).


assets/CanonicalSpace

Summary: engine/assets/CanonicalSpace.js — the engine's canonical coordinate frame.  Y = up, Z = forward, X = side (right), unit = meter, origin = logical root.  Source files come from Blender/Maya/Max/CAD/Unity/Unreal/etc. with inconsistent axes, scale, and origin. We never trust source orientation and never rewrite it destructively — instead we compute a non-destructive axis correction (a quaternion + uniform scale) that maps the declared source frame into this canonical frame, and store it on the model's ImportTransform.


axisVector

Summary: Resolve an axis token ('+Y', '-Z', …) to a unit vector.


axisCorrectionQuat

axisCorrectionQuat(upAxis = '+Y', forwardAxis = '+Z')

Summary: Quaternion (xyzw) that rotates a vector from a source frame (declared by its up + forward axes) into the canonical Y-up / Z-forward frame.


Summary: Convert a row-major 3x3 rotation matrix to a quaternion (xyzw).


rotateVecByQuat

Summary: Rotate a 3-vector by a quaternion (xyzw).


Summary: Common unit guesses for formats that don't carry units (e.g. STL). Returns a scale factor to convert the source unit to meters. These are *guesses* — the editor exposes an override per import.


assets/EngineModel

Summary: engine/assets/EngineModel.js — the unified runtime object.  Core rule of the ingestion runtime: a model file is raw evidence, not the runtime object. The importer parses a source file into an EngineModel, which keeps every layer explicitly separate (source ≠ visual mesh ≠ material ≠ collider ≠ SDF ≠ skeleton ≠ animation ≠ runtime rig ≠ render surface). Layers that have not been built yet are explicitly null/empty — never faked — so the editor can show exactly what was detected vs generated.  Corrections (axis/scale/origin, material fixes, rig edits) live in metadata as an ImportTransform / import profile and are NEVER baked destructively into the source: the original imported look must always be recoverable.


createEngineModel

Summary: Create an empty EngineModel with every layer present but unbuilt.


createImportTransform

Summary: A non-destructive correction applied at runtime (never baked into source). Confidence drives the auto-apply / review / preview / neutral policy.


createEngineNode

Summary: A node in the preserved source hierarchy (transforms kept as-authored).


createEngineMesh

Summary: A mesh = a set of primitives (submeshes), each with its own material.


createEnginePrimitive

Summary: A primitive/submesh: geometry + a single material binding.


layerStatus

Summary: Report which layers are built (non-empty) vs explicitly unbuilt.


Summary: Canonical layer list — used by the editor to show built vs unbuilt layers.


assets/LicenseTracker

Summary: engine/assets/LicenseTracker.js — license metadata + import gate (spec §21).  License metadata is mandatory before import. Marketplace assets are licensed, not sold, and portability varies. The hard rules: only import assets the user owns or is licensed to use; never rip copyrighted game assets; never bypass DRM; store license metadata; warn on unknown/restricted licenses. This gate is advisory by default (warn) and can be set strict (block) per project.


assets/geometry/PrincipalAxes

Summary: engine/assets/geometry/PrincipalAxes.js — Principal Component Analysis of an EngineModel node's geometry. Small, dependency-free, GPU-free, and reusable: any engine system can ask for the natural axes of a mesh (oriented bounds, alignment, the axle of a wheel disc, the long axis of a barrel, etc.).  PCA finds the orthogonal axes of greatest → least variance of the vertex cloud. A disc/cylinder is thin along its axle, so its axle is the axis of LEAST variance — orientation- and mirror-proof, unlike axis-aligned guesses.


Summary: Jacobi eigen-decomposition of a symmetric 3×3 (row-major length-9 array).


principalAxes

Summary: PCA of a node's mesh-local vertex cloud.


leastVarianceAxis

leastVarianceAxis(model, nodeId, opts = {})

Summary: Convenience: the axis of LEAST variance (e.g. a wheel/disc axle), or null.


assets/humanoid/BoneMapper

Summary: engine/assets/humanoid/BoneMapper.js — map a source skeleton's bones onto the canonical humanoid slots (HumanoidRig) by NAME first (Mixamo / VRM / generic rig conventions), then hierarchy for the spine chain. Every mapping is a hint; ambiguous/extra bones are reported as `unmapped` and missing required slots as `missing` so the editor can correct (rule 62). Pure + GPU-free (gate-testable).


mapBones

Summary: Map a model's skeleton to canonical humanoid bones.