render/shaders/modules/compute/gpu_tile

Summary: GpuTile - WebGPU workgroup shared-memory tile (WebGPU equivalent of NVIDIA cuda-tile) Inspired by: https://github.com/NVIDIA/cuda-tile CONCEPT: Every thread in a workgroup cooperatively loads one element of a global buffer into fast workgroup-shared memory ("the tile"), then ALL threads process the cached tile before advancing to the next tile.  This amortises global-memory latency across the whole group — the same idea that makes tiled matrix-multiply orders of magnitude faster than naive O(N²) reads. CUDA term         WebGPU/WGSL equivalent ─────────────     ───────────────────── __shared__        var<workgroup> template<T,N>     JS class with type / tileSize parameters (build-time) __syncthreads()   workgroupBarrier() threadIdx.x       @builtin(local_invocation_id) USAGE (JavaScript side, shader build-time): import { GpuTile } from ".../modules/compute/gpu_tile.js"; const bodyTile = new GpuTile({ name: 'bodyTile', type: 'vec4f', tileSize: 64 }); const shader = ` // --- module scope --- ${bodyTile.declareWGSL()} @compute @workgroup_size(64) fn cs(@builtin(global_invocation_id) gid: vec3u, @builtin(local_invocation_id)  lid: vec3u) { let i   = gid.x; let myPos = bodies[i].pos.xyz; var acc = vec3f(0.); ${bodyTile.tiledLoopWGSL({ bufExpr:   'bodies',        // storage buffer binding name elemExpr:  'b.pos',         // expression to extract from element countExpr: 'u.count', lidExpr:   'lid.x', bodyWGSL: ` for (var k = 0u; k < _bodyTile_len; k++) { let b = ${bodyTile.getWGSL('k')}; let d = b.xyz - myPos; acc += d / (dot(d,d) + 0.01); }` })} } `; ADVANCED — multiple simultaneous tiles: Give each a unique `name` so their var<workgroup> identifiers don't collide. const posTile = new GpuTile({ name: 'posTile', type: 'vec4f', tileSize: 64 }); const velTile = new GpuTile({ name: 'velTile', type: 'vec4f', tileSize: 64 }); // In shader: ${posTile.declareWGSL()} ${velTile.declareWGSL()}


gpuTile

Summary: Convenience factory — same as `new GpuTile(opts)`.


Summary: Ready-to-paste WGSL string demonstrating the 64-thread tiled N-body pattern. This is the same code used in the playground N-Body demo, expressed via GpuTile.


Summary: vec4f tile, 64 threads — matches the N-Body pattern exactly


Summary: vec4f tile, 128 threads — good for higher-throughput passes


Summary: f32 tile, 64 threads — useful for scalar reduction passes


Summary: vec2f tile, 64 threads — 2-D positions / UVs


render/shaders/modules/compute/grid_splat

Summary: Grid Splat Compute Shader Splats particles/vertices to a 3D density grid for volumetric rendering Input: Particle positions, colors, velocities Output: Density grid + Color grid (for raymarching)


render/shaders/modules/core/particles_billboard


render/shaders/modules/core/particles_billboard_fragment

Summary: ============================================================================ PARTICLE FRAGMENT SHADER - PER-PARTICLE SHAPE RENDERING ============================================================================ This shader renders each particle according to its emitter's shape setting. The shape type is passed from the vertex shader (extracted from meta buffer). SHAPE TYPES: 0 = SPHERE - 3D shaded ball with fake diffuse lighting - Hard circle cutoff (no square corners) - Calculates fake Z depth for sphere surface - Applies directional light from upper-right - Best for: fire, water drops, magic orbs 1 = POINT - Tiny bright dot with small radius - Extra bright center for visibility - Discards most of the quad for small appearance - Best for: sparks, stars, snow, dust 2 = SOFT - Organic smoke/cloud shape with noise-distorted edges - Uses FBM noise to break circular silhouette - Wispy tendrils and irregular boundaries - Best for: smoke, fog, clouds, magic auras 3 = SPARK - Star/cross shape with 4 points - Creates X pattern with bright center - Good for emphasis and magical effects - Best for: magic sparks, highlights, flares INPUTS (from vertex shader): - localPos.xy: Normalized position within quad (-1 to 1) - color: RGBA from emitter - age: Particle age for lifetime fading - shape: Shape type (0-3) OUTPUT: - Final RGBA color with alpha for blending


render/shaders/modules/core/particles_billboard_vertex

Summary: ============================================================================ PARTICLE BILLBOARD VERTEX SHADER ============================================================================ This shader renders particles as SCREEN-ALIGNED quads (always face camera). HOW IT WORKS: 1. Each particle is rendered as 6 vertices (2 triangles = 1 quad) 2. The particle center is transformed to CLIP SPACE first 3. Screen-space offsets are added to create a quad that always faces the camera 4. Per-particle data (color, size, shape) is read from the meta buffer INPUTS (from GPU buffers): - uPositions[ii]: vec4 containing [x, y, z, age] - uMeta[ii]: vec4 containing [r, g, b, packed_size_shape] - uVelocities[ii]: vec4 containing [vx, vy, vz, lifetime] - uParams: Default fallback values OUTPUTS (to fragment shader): - position: Clip-space position for rasterization - color: RGBA color from emitter - localPos: Normalized quad coordinates (-1 to 1) for shape rendering - age: Particle age for lifetime effects - shape: Shape type (0=sphere, 1=point, 2=soft, 3=spark) - lifetime: Per-particle lifetime from emitter SIZE/SHAPE/BEHAVIOR ENCODING: The meta.w value packs size, renderMode, shape, and behavior: meta.w = size * 1000 + renderMode * 100 + shape * 10 + behavior - size: 0-65 (floor(meta.w / 1000)) - renderMode: 0-9 (floor(meta.w / 100) % 10) - shape: 0-9 (floor(meta.w / 10) % 10) - behavior: 0-9 (meta.w % 10) Example: 4302 = size 4, renderMode 3, shape 0, behavior 2


render/shaders/modules/core/particles_blackbody

Summary: particles_blackbody.js - Blackbody Radiation Color Shader (GAP 39) Converts particle temperature → physically-based color + emission. Uses CIE 1931 approximation of Planck's law for blackbody radiation. Stefan-Boltzmann T⁴ scaling for emissive intensity. Generates a 1D LUT texture (256 texels, 300K-30000K → sRGB). Fragment shader samples LUT based on thermalData.x temperature.


generateBlackbodyLUT

generateBlackbodyLUT(minTemp = 300, maxTemp = 30000)

Summary: Generate blackbody LUT as Float32Array (256 × RGBA). Maps temperature range [minT, maxT] linearly across 256 texels. Alpha channel = relative emissive intensity (Stefan-Boltzmann T⁴ scaling).


render/shaders/modules/core/particles_bond_line

Summary: particles_bond_line.js - Bond Line / Stick Shader (GAP 41) Renders molecular bonds as lines/cylinders between bonded particles. Reads constraint buffer to find bonded pairs. Supports single/double/triple bond visualization. Color by bond type: ionic=dashed, covalent=solid, metallic=thick.


render/shaders/modules/core/particles_field_lines

Summary: particles_field_lines.js - Electromagnetic Field Visualization Shader (GAP 42) Renders electric/magnetic field lines and force arrows around charged particles. Supports: field lines, arrow glyphs, heat map, equipotential surfaces. Color: blue=attraction, red=repulsion, intensity=magnitude.


render/shaders/modules/core/particles_orbital

Summary: particles_orbital.js - Electron Cloud / Orbital Shader (GAP 40) Raymarched spherical harmonics for visualizing electron probability clouds. Renders hydrogen-like orbital shapes (1s, 2p, 3d, etc.) around atom-particles. Color by element using CPK convention. LOD: at distance → simple sphere; close → full orbital volume.


render/shaders/modules/core/particles_phase_vfx

Summary: particles_phase_vfx.js - Phase Transition Visual Effects Shader (GAP 43) Visual feedback when particles change phase: - Melt: wet/glossy sheen, drip distortion - Freeze: frost crystallization pattern, ice crackle - Boil: bubble emission pattern, steam distortion - Ionize: plasma glow + electricity arcs Per-particle phase from thermalData.y → drives material blend in fragment. Transition animation uses latentEnergy (thermalData.w) as 0→1 progress.


render/shaders/modules/core/particles_point


render/shaders/modules/core/particles_point_fragment


render/shaders/modules/core/particles_point_vertex


render/shaders/modules/core/particles_sdf_billboard


render/shaders/modules/core/particles_sdf_fragment


render/shaders/modules/core/particles_shared

Summary: ============================================================================ PARTICLE SHADER SHARED DEFINITIONS ============================================================================ This file contains WGSL struct definitions and buffer bindings shared between the vertex and fragment shaders for particle rendering. Uses ShaderSchema.js for consistent buffer layouts. See BINDING_GROUPS.particles and PARTICLE_PARAMS_SCHEMA for schema definitions. GPU BUFFER LAYOUT (from ShaderSchema.js): Group 0: FrameUniforms (camera, time) Group 1: Particle buffers (positions, meta, params, velocities, uvs, texture) PACK FORMAT (from ParticleSchema.js): meta.w = mass * 1e8 + drag * 1e6 + size * 1e4 + renderMode * 1e3 + shape * 10 + behavior


render/shaders/modules/lib/color/blend

Summary: Color Blending Functions Various blend modes for compositing colors. Photoshop-style blend modes and custom game-specific blending.


render/shaders/modules/lib/color/index


render/shaders/modules/lib/density/falloff

Summary: Density Falloff Functions Various falloff curves for volumetric density, particle opacity, etc. Controls how density/opacity decreases with distance.


render/shaders/modules/lib/density/index


render/shaders/modules/lib/depth/index


render/shaders/modules/lib/depth/linearize

Summary: Depth Buffer Utilities - Linearization Functions for linearizing depth values from perspective projection. WebGPU uses [0,1] depth range with perspective non-linearity.


render/shaders/modules/lib/depth/reconstruct


render/shaders/modules/lib/distortion/domain_warp


render/shaders/modules/lib/distortion/index


render/shaders/modules/lib/index


render/shaders/modules/lib/lighting/index


render/shaders/modules/lib/lighting/scatter

Summary: Light Scattering Functions Physical and approximated scattering models for volumetric lighting. Includes phase functions and multiple scattering approximations.


render/shaders/modules/lib/math/index


render/shaders/modules/lib/math/interpolation

Summary: Interpolation Functions Various interpolation curves and easing functions.


render/shaders/modules/lib/noise/curl


render/shaders/modules/lib/noise/fbm


render/shaders/modules/lib/noise/hash

Summary: Hash Functions for Pseudo-Random Noise Generation Provides various hash functions for generating pseudo-random values from coordinate inputs. Used as basis for procedural noise.


render/shaders/modules/lib/noise/index


Summary: 3D Noise Functions for Volumetric Effects Used for smoke turbulence, wispy distortion, and organic blending


render/shaders/modules/lib/noise/value


render/shaders/modules/lib/sdf/shapes

Summary: SDF Shape Library Signed Distance Field functions for volumetric particle rendering. Based on Inigo Quilez's distance functions: https://iquilezles.org/articles/distfunctions/


render/shaders/modules/passes/depth_visualizer


render/shaders/modules/passes/particle_age


render/shaders/modules/passes/particle_albedo


render/shaders/modules/passes/particle_depth


render/shaders/modules/passes/particle_emissive


render/shaders/modules/passes/particle_lighting


render/shaders/modules/passes/particle_normals


render/shaders/modules/passes/particle_size


render/shaders/modules/passes/particle_thermal

Summary: Particle Thermal/Blackbody Debug Pass Visualizes particle temperature as blackbody radiation color. Cold (blue) → Room temp (invisible) → Hot (red/orange/white). Requires uThermalData buffer (binding 4) for per-particle temperature.


render/shaders/modules/passes/particle_velocity


render/shaders/modules/passes/scene_debug_visualizer

Summary: Scene Debug Visualizer Shader Fullscreen post-process that reads the ACTUAL scene depth buffer (texture_depth_2d) containing both entity meshes and particles, and visualizes: Mode 0: Depth — linearized grayscale (near=white, far=black, industry standard) Mode 1: Normals — world-space normals reconstructed from depth (RGB = XYZ) Mode 2: Albedo — passthrough of scene color (placeholder) Mode 3: Lighting — scene luminance only Reads from texture_depth_2d (depth24plus) — NOT texture_2d<f32>.


render/shaders/modules/postfx/bloom


render/shaders/modules/postfx/fluid_water_blur


render/shaders/modules/postfx/fluid_water_composite


render/shaders/modules/postfx/fluid_water_depth


render/shaders/modules/postfx/fluid_water_thickness


render/shaders/modules/postfx/volume_isosurface


render/shaders/modules/postfx/volume_smoke


render/shaders/modules/proxy/ray_portal

Summary: Ray Portal WGSL Shader Module Provides WGSL functions for all proxy geometry quality tiers: ULTRA  — TLAS/BLAS two-level BVH traversal with ray redirect HIGH   — SDF cone marching proxy MED    — True impostor (billboarded SDF/height-field) LOW    — Octahedral impostor atlas sampling All functions are pure WGSL and intended to be embedded via template literals into compute shader source strings.


render/shaders/modules/proxy/tlas_refit


render/spectral/CoherentWaveOpticsPass


render/spectral/SpectralPhotonMapper


render/spectral/SpectralPhotonMappingPass


render/spectral/SpectralPhotonStore


render/spectral/SpectralScattering


sellmeierIor

sellmeierIor(lambdaNm, coefficients = null)


prismMinimumDeviation

prismMinimumDeviation(lambdaNm, apexRadians = Math.PI / 3, coefficients = null)


render/spectral/SpectralSensor


spectralSamplesToDisplayRgb

spectralSamplesToDisplayRgb(samples, exposure = 1)


render/spectral/SpectralTypes


createWavelengthPacket

createWavelengthPacket(lambda, pdf, activeMask = 1, hero = 0)


createPhotonPacket

createPhotonPacket(position, direction, lambdaNm, flux, flags = 0, normal = null)


createVisiblePoint

createVisiblePoint(position, normal, materialId = 0, radius = SPECTRAL_DEFAULTS.photonRadius)


render/spectral/SpectrumAsset


createConstantSpectrum

createConstantSpectrum(value = 1, scale = 1)


createTabulatedSpectrum

createTabulatedSpectrum(samples, scale = 1)


createBlackbodySpectrum

createBlackbodySpectrum(temperatureK = 6500, scale = 1)


render/spectral/WavelengthSampling


wavelengthToBand

wavelengthToBand(lambdaNm, bandCount = 18, minNm = SPECTRAL_RANGE.minNm, maxNm = SPECTRAL_RANGE.maxNm)


bandCenterWavelength

bandCenterWavelength(band, bandCount = 18, minNm = SPECTRAL_RANGE.minNm, maxNm = SPECTRAL_RANGE.maxNm)


sampleVisibleWavelength

sampleVisibleWavelength(u = uniformDistribution(0, 1, Math.random)


sampleStratifiedVisiblePacket

sampleStratifiedVisiblePacket(seed = 1, count = 4)


samplePhotonWavelength

samplePhotonWavelength(lightSpectrum, seed = 1, bandCount = 18)


render/spectral/index


render/state/StateFirstEcsSourceAdapter

Summary: Typed, read-only adapter from the authoritative ECS Transform + Renderable archetypes to the State-First presentation source protocol. ECS continues to own identity and transform/renderable state. Presentation owns mesh bounds, importance, dirty state, and the currently materialized representation through explicit resolver callbacks. The adapter retains no entity records and applies policy only through `applyPresentation`.


render/state/StateFirstExecutionBackend

Summary: Backend-neutral execution policy for State-First simulations. This object owns selection, frame-boundary switching, and measured reports. It deliberately does not own a CPU step function or GPU shader so the same contract can be shared by every State-First simulation.


render/state/StateFirstGpuCuller


render/state/StateFirstRasterizer


chooseStateFirstRepresentation

chooseStateFirstRepresentation(pixelRadius, importance = 0, current = STATE_FIRST_REPRESENTATION.POINT, holdFrames = 0, thresholds = DEFAULT_THRESHOLDS, policy = null, lodRank = 0.5)


render/state/StateFirstRetainedStorage

Summary: Retained state backing for state-first renderers. Entity state lives at a stable entity-id-derived offset while each visual representation owns a dense u32 indirection bucket.  Representation changes therefore never move authoritative state, and an entity may participate in two buckets while an LOD cross-fade is in progress.


render/state/StateFirstSourceBridge

Summary: Explicit runtime bridge between authoritative simulation state and the State-First presentation policy. The bridge deliberately does not guess GPU layouts or invent renderable entities from arbitrary objects. A source must publish the V1 protocol, provide semantic presentation entities, and consume the resulting plan. GPU sources additionally prove that their active byte range fits in the authoritative GPUBuffer on every update, which makes ping-pong buffers and capacity growth safe to expose without readback.


render/state/index


render/streaming/VirtualTexturingSystem

Summary: Virtual Texturing System - On-demand texture streaming Megatexture/Sparse Virtual Texture implementation Used for massive open worlds with unlimited texture detail Now powered by vGPU driver


render/volumes/HybridVolumeSystem


render/volumes/IsoSurfaceVolumeRenderer


render/volumes/ParticleVolumeConnector

Summary: Quick factory to create a connector and initialize it


createParticleVolumeConnector

async createParticleVolumeConnector(device, options = {})


render/volumes/SmokeVolumeRenderer


render/volumes/UnifiedVolumeRenderer


render/volumes/VolumeIntegration


createVolumeIntegration

createVolumeIntegration(device, options = {})


render/volumes/index

Summary: Quick factory to create a complete volumetric setup


createVolumetricSystem

async createVolumetricSystem(device, options = {})


scenes/PhysicsSandboxScene


configurePhysicsSandboxScene

configurePhysicsSandboxScene(world, options = {})


sim/SimulationUpdate

Summary: Step the particle simulation (emission, colliders, physics).


stepFluid

stepFluid(smoke, particles, gpuDevice, delta, options = {})

Summary: Step the fluid simulation (density splatting, advection).


stepAllSimulations

stepAllSimulations(state, delta, entities, options = {})

Summary: Step all simulations in one call.


sim/ai/AIAiming

Summary: Create a ray with pre-computed inverse direction for fast intersection tests


rayAABBIntersect

Summary: Ray-AABB intersection using the slab method Used by NVIDIA OptiX and other professional engines


raySphereIntersect

raySphereIntersect(rayOrigin, rayDir, sphereCenter, radius)

Summary: Ray-sphere intersection using quadratic formula Good for character hitboxes and bounding spheres


hasLineOfSight

hasLineOfSight(from, to, obstacles, options = {})

Summary: Check line of sight between two points against obstacle list


hasLineOfSightSpheres

hasLineOfSightSpheres(from, to, spheres, ignoreIds = [])

Summary: Check line of sight with sphere obstacles (characters)


predictiveAim

predictiveAim(shooterPos, projectileSpeed, targetPos, targetVel)

Summary: Calculate aim point to intercept a moving target Solves: |P + V×t|² = (S×t)² (quadratic intercept equation)


predictiveAimWithAcceleration

predictiveAimWithAcceleration(shooterPos, projectileSpeed, targetPos, targetVel, targetAccel, iterations = 4)

Summary: Iterative predictive aim for accelerating targets


gaussianRandom

gaussianRandom(mean = 0, stdDev = 1, rng = null)

Summary: Generate Gaussian-distributed random number using Box-Muller transform


Summary: Apply accuracy spread to aim direction (2D version)


Summary: Apply accuracy spread to aim direction (3D version) Generates a cone of spread around the aim direction


calculateThreatScore

calculateThreatScore(npc, target, options = {})

Summary: Calculate threat score for a potential target


selectTarget

selectTarget(npc, candidates, options = {})

Summary: Select best target from candidates with hysteresis


createTargetMemory

Summary: Create a target memory tracker for an NPC Remembers lost targets for a duration


updateTargetMemory

Summary: Update target memory with current perception


getAimPointFromMemory

Summary: Get aim point considering target memory


calculateAccuracyModifier

Summary: Calculate accuracy modifier based on combat conditions


degToRad

Summary: Convert degrees to radians


radToDeg

Summary: Convert radians to degrees


distanceSquared

Summary: Squared distance between two points (faster than actual distance)


distance

Summary: Actual distance between two points


isWithinRange

Summary: Check if distance is within range (uses squared comparison)


Summary: Skill level presets for accuracy parameters


Summary: Default threat weight factors


Summary: Hysteresis threshold - only switch targets if new threat exceeds by this factor


Summary: Time to remember lost targets (ms)


sim/ai/AIAimingSystem

Summary: Create an NPC combat controller


createNPCCombatController

Summary: Create an NPC combat controller


initNPCWeapons

Summary: Initialize weapons for an NPC


initNPCMelee

Summary: Initialize melee for an NPC


createAIAimingSystem

Summary: Create the main AI aiming system


registerNPC

Summary: Register an NPC with the aiming system


unregisterNPC

Summary: Unregister an NPC from the aiming system


updatePlayerPosition

Summary: Update player position for LOD calculations


updateAIAimingSystem

updateAIAimingSystem(system, deltaTimeMs, potentialTargets, obstacles)

Summary: Main update function for the AI aiming system


npcFireWeapon

npcFireWeapon(system, npc, targets, obstacles)

Summary: Command NPC to fire current weapon


npcMeleeAttack

Summary: Command NPC to perform melee attack


applyDamageToNPC

Summary: Apply damage to NPC


decayDamageMemory

decayDamageMemory(npc, deltaTimeMs, decayRate = 10)

Summary: Decay recent damage memory over time


getBatchRays

Summary: Get all rays for GPU batch processing


applyBatchRayResults

Summary: Apply batch ray results from GPU


Summary: NPC combat states


Summary: LOD update frequencies (frame intervals)


sim/ai/AIBehaviorTree

Summary: Create a Selector node (OR logic) Runs children left-to-right, succeeds if ANY child succeeds


createSequence

Summary: Create a Sequence node (AND logic) Runs children left-to-right, fails if ANY child fails


createParallel

createParallel(name, children = [], successThreshold = -1, failureThreshold = 1)

Summary: Create a Parallel node Runs all children simultaneously


createRandomSelector

createRandomSelector(name, children = [])

Summary: Create a Random Selector (picks random child)


createInverter

Summary: Create an Inverter decorator Inverts child result: SUCCESS ↔ FAILURE


createRepeater

Summary: Create a Repeater decorator Repeats child N times or until failure


createUntilFail

Summary: Create an UntilFail decorator Repeats child until it fails


createUntilSuccess

Summary: Create an UntilSuccess decorator Repeats child until it succeeds


createSucceeder

Summary: Create a Succeeder decorator Always returns SUCCESS


createFailer

Summary: Create a Failer decorator Always returns FAILURE


createCooldown

Summary: Create a Cooldown decorator Prevents child from running until cooldown expires


createConditionGuard

Summary: Create a Condition Guard decorator Only runs child if condition is met


createAction

Summary: Create an Action leaf node


createCondition

Summary: Create a Condition leaf node


createWait

Summary: Create a Wait leaf node


createLog

Summary: Create a Log leaf node (for debugging)


tickNode

Summary: Tick a behavior tree node


resetNode

Summary: Reset a behavior tree node and all children


createTreeRunner

Summary: Create a behavior tree runner


tickTree

Summary: Tick the behavior tree


createCombatTree

Summary: Create a common combat behavior tree


sim/ai/AICover

Summary: Create a cover point definition


createCoverPoint

createCoverPoint(position, normal, options = {})

Summary: Create a cover point definition


computePeekPositions

Summary: Pre-compute peek positions for a cover point


detectCoverPoints

detectCoverPoints(obstacles, sampleSpacing = 2)

Summary: Find cover points from obstacle geometry


scoreCoverPoint

scoreCoverPoint(cover, npcPos, threatPos, obstacles, options = {})

Summary: Score a cover point for a given tactical situation


findBestCover

findBestCover(coverPoints, npcPos, threatPos, obstacles, options = {})

Summary: Find best cover point from available options


createCoverState

Summary: Create NPC cover state tracker


enterCover

Summary: Enter cover at a cover point


exitCover

Summary: Exit current cover


startPeek

Summary: Start peek action from cover


updateCoverState

Summary: Update cover state


getCoverShootPosition

Summary: Get current shoot position based on cover action


canShootFromCover

Summary: Check if NPC can shoot from current cover state


applySuppression

Summary: Apply suppression to an NPC


isSuppressed

Summary: Check if NPC is suppressed


damageCover

Summary: Apply damage to cover point


findFlankingPositions

findFlankingPositions(targetPos, targetFacing, flankDistance, coverPoints, obstacles)

Summary: Find flanking positions around a target


findRetreatCover

findRetreatCover(npcPos, threatPos, coverPoints, obstacles, minRetreatDist = 10)

Summary: Find retreat positions away from threat


Summary: Cover quality thresholds


Summary: Cover action types


sim/ai/AICrowd

Summary: Calculate social force (Helbing model)


calculateSocialForce

calculateSocialForce(agent, neighbors, walls, goal)

Summary: Calculate social force (Helbing model)


createCrowdAgent

Summary: Create crowd agent


createCrowdSystem

Summary: Create crowd system


addCrowdAgent

Summary: Add agent to crowd


removeCrowdAgent

Summary: Remove agent from crowd


addCrowdWall

Summary: Add wall to crowd system


addAttractor

addAttractor(crowd, position, strength, radius)

Summary: Add attractor (draws crowd)


triggerPanic

triggerPanic(crowd, source, radius, intensity = 1)

Summary: Trigger panic


triggerEvacuation

Summary: Set evacuation mode


updateCrowd

Summary: Update crowd simulation


getCrowdStats

Summary: Get crowd statistics


Summary: Crowd behavior modes


Summary: Individual agent states


sim/ai/AIDialogue

Summary: Create a dialogue tree


createDialogueTree

Summary: Create a dialogue tree


createDialogueNode

Summary: Create a dialogue node


addDialogueNode

Summary: Add node to dialogue tree


createDialogueState

Summary: Create dialogue state for an NPC


addDialogueTree

Summary: Add dialogue tree to NPC


setDialogueFlag

Summary: Set dialogue flag


getDialogueFlag

getDialogueFlag(state, flag, defaultValue = null)

Summary: Get dialogue flag


startConversation

Summary: Start conversation with NPC


processCurrentNode

Summary: Process current dialogue node


selectChoice

selectChoice(state, choiceIndex, context = {})

Summary: Select player choice


continueDialogue

Summary: Continue to next dialogue (for NPC lines)


dialogueBuilder

Summary: Fluent dialogue tree builder


Summary: Node types


sim/ai/AIDirector

Summary: Create player state tracker


createPlayerState

Summary: Create player state tracker


updatePlayerState

Summary: Update player state metrics


createPacingController

Summary: Create pacing controller


updatePacing

Summary: Update pacing state


createSpawnDirector

Summary: Create spawn director


registerSpawnType

Summary: Register spawn type


addSpawnPoint

Summary: Add spawn point


updateSpawnDirector

updateSpawnDirector(director, pacing, playerPosition, deltaTime)

Summary: Update spawn director


reportSpawnKilled

Summary: Report spawn killed


createDifficultyScaler

Summary: Create difficulty scaler


updateDifficulty

Summary: Update difficulty based on player performance


createAIDirector

Summary: Create complete AI Director


updateAIDirector

Summary: Update AI Director


Summary: Pacing states


Summary: Intensity levels


sim/ai/AIEcology

Summary: Create species definition


createSpecies

Summary: Create species definition


createCreature

Summary: Create creature instance


createEcosystem

Summary: Create ecosystem manager


registerSpecies

Summary: Register species in ecosystem


spawnCreature

Summary: Spawn creature in ecosystem


removeCreature

removeCreature(eco, creatureId, cause = "natural")

Summary: Remove creature from ecosystem


createFoodSource

createFoodSource(eco, position, type, nutrition)

Summary: Create food source


consumeFood

Summary: Consume food source


createPack

Summary: Create pack/herd


addToPack

Summary: Add creature to pack


updateCreature

Summary: Update creature behavior


updateEcosystem

Summary: Update entire ecosystem


getEcosystemStats

Summary: Get ecosystem statistics


Summary: Species roles in ecosystem


Summary: Activity states


sim/ai/AIEconomy

Summary: Create resource definition


createResource

Summary: Create resource definition


createMarket

Summary: Create a market (trading location)


initMarketResource

initMarketResource(market, resource, initialSupply = 100, baseDemand = 10)

Summary: Initialize resource in market


calculatePrice

Summary: Calculate current price based on supply/demand


updateMarketPrices

Summary: Update market prices


buyFromMarket

buyFromMarket(market, resourceId, quantity, buyer)

Summary: Execute a buy transaction


sellToMarket

sellToMarket(market, resourceId, quantity, seller)

Summary: Execute a sell transaction


createInventory

Summary: Create inventory


addToInventory

addToInventory(inventory, resourceId, quantity, resourceDef)

Summary: Add items to inventory


removeFromInventory

removeFromInventory(inventory, resourceId, quantity, resourceDef)

Summary: Remove items from inventory


createRecipe

Summary: Create crafting recipe


canCraft

canCraft(recipe, inventory, skills = {})

Summary: Check if can craft recipe


craft

craft(recipe, inventory, resourceDefs, skills = {})

Summary: Execute crafting


createProductionBuilding

Summary: Create production building


updateProductionBuilding

updateProductionBuilding(building, recipes, resourceDefs, deltaHours)

Summary: Update production building


createEconomyManager

Summary: Create economy manager


registerResource

Summary: Register resource


registerRecipe

Summary: Register recipe


updateEconomy

Summary: Update entire economy


Summary: Resource categories


Summary: Market trend directions


sim/ai/AIEvasion

Summary: Create evasion state for an NPC


createEvasionState

Summary: Create evasion state for an NPC


startDodge

startDodge(state, dodgeType, npcPos, npcFacing, now)

Summary: Attempt to dodge in a direction


updateEvasion

Summary: Update evasion state


isEvading

Summary: Check if NPC is currently evading


canDodge

Summary: Check if NPC can dodge


updateStrafe

Summary: Update strafe behavior


setStrafeDirection

Summary: Set explicit strafe direction


reactToThreat

reactToThreat(state, npcPos, npcFacing, threatDir, now, options = {})

Summary: React to incoming threat (projectile, attack)


checkProjectileThreats

checkProjectileThreats(state, npcPos, npcFacing, projectiles, now)

Summary: Check for incoming projectiles and react


checkGrenadeThreats

checkGrenadeThreats(state, npcPos, npcFacing, grenades, now)

Summary: Check for grenades and react


generateCombatMovement

generateCombatMovement(state, npcPos, targetPos, deltaTimeMs)

Summary: Generate unpredictable movement pattern


circleStrafe

circleStrafe(npcPos, targetPos, direction, speed)

Summary: Calculate circle-strafe velocity around target


getEvasionParamsForSkill

Summary: Get evasion parameters for skill level


Summary: Evasion action types


Summary: Default evasion parameters


sim/ai/AIFaction

Summary: Create a faction


createFaction

Summary: Create a faction


createFactionManager

Summary: Create faction manager


registerFaction

Summary: Register a faction


getEntityFaction

Summary: Get entity's faction


addToFaction

Summary: Add entity to faction


setDiplomaticStance

setDiplomaticStance(manager, factionA, factionB, stance)

Summary: Set diplomatic stance between factions


getDiplomaticStance

Summary: Get diplomatic stance between factions


areFactionsHostile

Summary: Check if factions are hostile


areFactionsAllied

Summary: Check if factions are allied


areEntitiesHostile

Summary: Check if two entities are hostile to each other


modifyPlayerReputation

Summary: Modify player reputation with faction


getPlayerReputationLevel

Summary: Get player reputation level with faction


canAccessFactionService

Summary: Check if player can access faction services


createTreaty

Summary: Create a treaty


proposeTreaty

Summary: Propose treaty


declareWar

Summary: Declare war


claimTerritory

Summary: Claim territory for faction


getTerritoryOwner

Summary: Get territory owner


calculateFactionPower

Summary: Calculate faction power


Summary: Diplomatic stance


Summary: Reputation thresholds - from AISchema


Summary: Treaty types


sim/ai/AIFormation

Summary: Create formation definition


createFormation

Summary: Create formation definition


generateFormationSlots

Summary: Generate formation slot positions


createFormationManager

Summary: Create formation manager for a group


assignToFormation

assignToFormation(manager, unitId, isLeader = false)

Summary: Assign unit to formation slot


removeFromFormation

Summary: Remove unit from formation


getFormationPosition

Summary: Get unit's target position in formation


moveFormation

moveFormation(manager, targetCenter, targetFacing = null)

Summary: Move formation to target


updateFormationMovement

Summary: Update formation movement


changeFormation

changeFormation(manager, newType, options = {})

Summary: Change formation type


getAllFormationPositions

Summary: Get all unit target positions


isFormationComplete

isFormationComplete(manager, currentPositions, threshold = 1)

Summary: Check if formation is formed up


Summary: Formation patterns


Summary: Create preset formations for common scenarios


sim/ai/AIHitDetection

Summary: Spatial hash for efficient broad-phase collision detection


sweptSphereSphere

sweptSphereSphere(sphereStart, sphereEnd, sphereRadius, targetCenter, targetRadius)

Summary: Swept sphere vs static sphere intersection Finds time t in [0,1] when moving sphere first touches static sphere


sweptSphereSphereMoving

Summary: Swept sphere vs moving sphere intersection Handles both objects moving (relative velocity approach)


capsuleSphereIntersect

capsuleSphereIntersect(capsuleStart, capsuleEnd, capsuleRadius, targetCenter, targetRadius)

Summary: Swept capsule collision (projectile path as line segment) Creates a capsule from start to end position with given radius


calculateDamageFalloff

calculateDamageFalloff(baseDamage, distance, radius, falloffType = FALLOFF_TYPE.LINEAR, options = {})

Summary: Calculate damage with distance falloff


getAoETargets

getAoETargets(center, radius, targets, options = {})

Summary: Find all targets within an Area of Effect


getConeTargets

getConeTargets(origin, direction, halfAngle, range, targets, options = {})

Summary: Cone-shaped AoE (dragon breath, flamethrower)


checkProjectileHit

checkProjectileHit(projectile, targets, options = {})

Summary: Check projectile hit with swept collision and spatial optimization


checkBeamHit

checkBeamHit(origin, direction, maxRange, targets, options = {})

Summary: Check beam/ray hit against multiple targets


Summary: Damage falloff types


Summary: Hitbox types


sim/ai/AIInfluenceMap

Summary: Create an influence map layer


createInfluenceLayer

createInfluenceLayer(width, height, cellSize, origin = [0, 0])

Summary: Create an influence map layer


createInfluenceMap

createInfluenceMap(width, height, cellSize, origin = [0, 0])

Summary: Create a multi-layer influence map


worldToInfluenceCell

Summary: World position to grid cell


influenceCellToWorld

Summary: Grid cell to world position (center of cell)


getInfluenceAt

Summary: Get influence value at world position


setInfluenceAt

setInfluenceAt(layer, worldX, worldZ, value)

Summary: Set influence value at world position


addInfluenceAt

addInfluenceAt(layer, worldX, worldZ, value)

Summary: Add influence at world position


stampInfluence

stampInfluence(layer, worldX, worldZ, radius, value, falloff = "linear")

Summary: Stamp circular influence at position


propagateInfluence

propagateInfluence(layer, decayFactor = 0.9)

Summary: Propagate influence to neighboring cells (blur/spread)


decayInfluence

Summary: Decay all influence values


clearInfluence

Summary: Clear all influence


findLowestInfluence

findLowestInfluence(layer, worldX, worldZ, searchRadius)

Summary: Find position with lowest influence in radius


findHighestInfluence

findHighestInfluence(layer, worldX, worldZ, searchRadius)

Summary: Find position with highest influence in radius


sampleCombinedInfluence

sampleCombinedInfluence(map, worldX, worldZ, weights)

Summary: Sample combined influence from multiple layers


findChokePoints

Summary: Analyze terrain for choke points


updateThreatInfluence

Summary: Update threat layer from enemy positions


updateAllyInfluence

Summary: Update ally layer from friendly positions


reservePath

reservePath(map, path, reserveValue = 1.0)

Summary: Reserve a path on the influence map


clearPathReservations

Summary: Clear path reservation


sim/ai/AIKnowledge

Summary: Create knowledge item


createKnowledge

Summary: Create knowledge item


distortKnowledge

distortKnowledge(knowledge, distortion = 0.1)

Summary: Create a distorted copy (for rumor spreading)


createKnowledgeBase

Summary: Create NPC knowledge base


addKnowledge

Summary: Add knowledge to NPC's knowledge base


queryKnowledge

Summary: Query knowledge base


hasKnowledgeOf

Summary: Check if NPC knows about something


shareKnowledge

shareKnowledge(giver, receiver, knowledge, giverNpcId)

Summary: Share knowledge between NPCs


spreadKnowledge

spreadKnowledge(network, knowledge, originNpcId, maxHops = 3)

Summary: Spread knowledge through social network


createWorldKnowledgeManager

Summary: Create world knowledge manager


registerNPCKnowledge

registerNPCKnowledge(manager, npcId, config = {})

Summary: Register NPC with knowledge system


connectNPCs

Summary: Connect two NPCs in social network


announcePublicKnowledge

Summary: Announce public knowledge


updateKnowledgePropagation

Summary: Update knowledge propagation


Summary: Information types


RELIABILITY

Summary: Information reliability


sim/ai/AILoot

Summary: Create item definition


createItemDef

Summary: Create item definition


createItemInstance

createItemInstance(itemDef, options = {})

Summary: Create item instance from definition


createAffix

Summary: Create affix definition


applyAffix

Summary: Apply affix to item


generateItemName

Summary: Generate item name from affixes


createLootEntry

Summary: Create loot table entry


createLootTable

Summary: Create loot table


rollLootTable

rollLootTable(table, itemDefs, context = {})

Summary: Roll loot from table


rollRarity

Summary: Roll rarity based on luck


createLootManager

Summary: Create loot manager


registerItemDef

Summary: Register item definition


registerAffix

Summary: Register affix


registerLootTable

Summary: Register loot table


dropLoot

dropLoot(manager, tableId, position, context = {})

Summary: Drop loot at position


cleanupDrops

Summary: Clean up expired drops


RARITY

Summary: Rarity tiers


Summary: Rarity color codes


Summary: Item categories


sim/ai/AIMelee

Summary: Create a melee attack arc (pie-slice shaped hitbox)


createMeleeArc

createMeleeArc(origin, direction, range, arcAngleDeg)


isInMeleeArc

isInMeleeArc(arc, targetPos, targetRadius = 0)

Summary: Check if a point is within the melee arc (2D horizontal check) Uses cosine comparison for efficiency (avoids atan2)


isInMeleeArc3D(arc, targetPos, targetRadius = 0, verticalToleranceRad = Math.PI / 4)

Summary: Check if target is in 3D melee arc (includes vertical angle)


createMeleeAttackState

Summary: Create a melee attack state tracker


startMeleeAttack

Summary: Start a melee attack


updateMeleeAttack

Summary: Update melee attack state and check phase transitions


interruptMeleeAttack

Summary: Try to interrupt a melee attack (e.g., from stagger)


checkMeleeHits

checkMeleeHits(state, attackerPos, attackerDir, targets)

Summary: Check for hits during active phase


chainComboAttack

Summary: Chain to next combo attack


getComboMultiplier

Summary: Get combo multiplier for current step


sweepMeleeArc

sweepMeleeArc(origin, startDir, endDir, range, targets, sweepSamples = 5)

Summary: Perform a sweeping melee attack across multiple positions Useful for wide slash attacks


getPhaseTimeRemaining

Summary: Get remaining time in current phase


getPhaseProgress

Summary: Get phase progress (0-1)


Summary: Attack phase types


Summary: Default phase durations in milliseconds


sim/ai/AIMemory

Summary: Create working memory (limited capacity short-term)


workingMemoryPush

Summary: Add item to working memory (displaces oldest if full)


setFocus

Summary: Set focus of attention


getWorkingMemoryByType

Summary: Get items from working memory by type


clearWorkingMemory

Summary: Clear working memory


createEpisodicMemory

Summary: Create episodic memory (personal experiences)


createEpisode

Summary: Create an episode (memory of an event)


storeEpisode

Summary: Store an episode


recallEpisodesWithEntity

recallEpisodesWithEntity(memory, entityId, limit = 10)

Summary: Recall episodes involving an entity


recallEpisodesWithEmotion

recallEpisodesWithEmotion(memory, emotion, limit = 10)

Summary: Recall episodes by emotion


recallRecentEpisodes

Summary: Recall recent episodes


searchEpisodes

Summary: Search episodes by criteria


createSemanticMemory

Summary: Create semantic memory (facts and knowledge)


storeFact

storeFact(memory, key, value, meta = {})

Summary: Store a fact


getFact

Summary: Retrieve a fact


storeRelationship

storeRelationship(memory, subject, predicate, object, confidence = 1.0)

Summary: Store a relationship between entities


queryRelationships

Summary: Query relationships


storeBelief

storeBelief(memory, topic, belief, confidence = 0.5)

Summary: Store a belief


challengeBelief

challengeBelief(memory, topic, evidenceStrength = 0.1)

Summary: Challenge a belief (potentially weakens it)


createProceduralMemory

Summary: Create procedural memory (skills and habits)


practiceSkill

practiceSkill(memory, skill, success = true)

Summary: Record skill practice


getSkillProficiency

Summary: Get skill proficiency


formHabit

formHabit(memory, trigger, action, initialStrength = 0.3)

Summary: Form a habit


getHabitualResponse

Summary: Get habitual response to trigger


createMemorySystem

Summary: Create complete NPC memory system


consolidateMemories

Summary: Consolidate memories (transfer from working to long-term)


getEntityImpression

Summary: Get overall impression of an entity


Summary: Memory types


IMPORTANCE

Summary: Event importance levels


sim/ai/AIMorale

Summary: Create morale state for an NPC


createMoraleState

Summary: Create morale state for an NPC


changeMorale

Summary: Apply morale change


applySuppression

Summary: Apply suppression


processDamageMorale

processDamageMorale(state, damage, fromBehind = false)

Summary: Process taking damage


processAllyDeath

processAllyDeath(state, wasLeader = false)

Summary: Process ally death


processEnemyDeath

processEnemyDeath(state, wasLeader = false)

Summary: Process enemy death


rally

Summary: Rally (leader ability)


updateMorale

updateMorale(state, deltaTimeSec, inCombat, inCover)

Summary: Update morale over time (recovery, suppression decay)


updateMoraleContext

updateMoraleContext(state, alliesNearby, enemiesVisible, leaderNearby)

Summary: Update context (allies, enemies, leader)


getMoraleAccuracyMod

Summary: Get accuracy modifier based on morale


getMoraleSpeedMod

Summary: Get movement speed modifier based on morale


getMoraleReactionMod

Summary: Get reaction time modifier based on morale


shouldFlee

Summary: Check if NPC should flee


shouldSurrender

shouldSurrender(state, canEscape = true)

Summary: Check if NPC should surrender


shouldSeekCover

Summary: Check if NPC should take cover


shouldBeAggressive

Summary: Check if NPC should be aggressive (charge, flank)


moraleCheck

Summary: Roll morale check for risky action


getGroupMorale

Summary: Calculate group morale average


isGroupRouting

Summary: Check if group is routing (majority broken)


groupRally

Summary: Apply group rally (leader ability affecting all nearby)


Summary: Morale states


Summary: Default morale parameters


sim/ai/AIPerception

Summary: Create perception state for an NPC


createPerceptionState

Summary: Create perception state for an NPC


checkVision

checkVision(perception, npcPos, npcFacing, targetPos, obstacles)

Summary: Check if target is in vision cone


calculateDetectionRate

calculateDetectionRate(visionResult, perception, options = {})

Summary: Calculate detection rate based on visibility conditions


createNoiseEvent

createNoiseEvent(position, loudness, type, sourceId = null)

Summary: Create a noise event


checkHearing

Summary: Check if NPC can hear a noise event


processVisualDetection

processVisualDetection(perception, npcPos, npcFacing, target, obstacles, deltaTimeSec, options = {})

Summary: Process visual detection of a target


processNoiseEvent

Summary: Process a noise event


processDamage

processDamage(perception, damageDirection = null, attackerId = null)

Summary: Process taking damage


shareTeamInfo

Summary: Share threat info from teammate


getLastKnownPosition

Summary: Get last known position of an entity


getMostThreateningEntity

Summary: Get the most threatening known entity


decayAwareness

Summary: Decay awareness over time


checkInvestigationComplete

checkInvestigationComplete(perception, npcPos, arrivalRadius = 2)

Summary: Check if investigation is complete


updatePerception

updatePerception(perception, npcPos, npcFacing, targets, noiseEvents, obstacles, deltaTimeSec)

Summary: Full perception update tick


Summary: Awareness states


Summary: Sense types


Summary: Default perception parameters - from AISchema


sim/ai/AIPersonality

Summary: Create personality profile


createPersonality

Summary: Create personality profile


createPersonalityFromArchetype

Summary: Create personality from archetype


getPersonalityBehaviorMod

Summary: Get personality-based behavior modifier


createEmotionalState

Summary: Create emotional state


applyEmotionalStimulus

applyEmotionalStimulus(state, emotion, intensity, personality = null)

Summary: Apply emotional stimulus


decayEmotions

decayEmotions(state, deltaTimeSec, decayRate = 0.1)

Summary: Decay emotions over time


hasComplexEmotion

hasComplexEmotion(state, complexEmotion, threshold = 0.3)

Summary: Check for complex emotion


createRelationshipTracker

Summary: Create relationship tracker


getRelationship

Summary: Create or get relationship with entity


recordInteraction

recordInteraction(tracker, entityId, interactionType, valence, intensity = 0.5)

Summary: Record interaction with entity


getDisposition

Summary: Get disposition toward entity


willHelp

willHelp(tracker, entityId, personality = null)

Summary: Will entity help another


createCharacterState

Summary: Create complete character psychological state


updateCharacterState

Summary: Update character state


TRAIT

Summary: Personality trait ranges: -1 to 1


EMOTION

Summary: Primary emotions


Summary: Emotion combinations


Summary: Relationship types


sim/ai/AIQuest

Summary: Create quest objective


createObjective

Summary: Create quest objective


updateObjectiveProgress

updateObjectiveProgress(objective, amount = 1)

Summary: Update objective progress


createQuest

Summary: Create quest


canAcceptQuest

Summary: Check if quest can be accepted


acceptQuest

Summary: Accept quest


checkQuestComplete

Summary: Check quest completion


turnInQuest

Summary: Turn in quest and get rewards


failQuest

Summary: Fail quest


createQuestManager

Summary: Create quest manager


registerQuest

Summary: Register quest


updateAvailableQuests

Summary: Update available quests based on player state


reportQuestEvent

Summary: Report event for quest objectives


generateQuest

generateQuest(templateId, params, context = {})

Summary: Generate procedural quest


generateDailyQuests

Summary: Generate daily quests


Summary: Quest types


Summary: Quest status


Summary: Quest priority


sim/ai/AIRandom

Summary: Set the global AI RNG context. Call this at the start of each game tick.


getEntityRngState

Summary: Get RNG state for a specific entity (deterministic per entity+tick)


getPositionRngState

Summary: Get RNG state for a position (terrain, spawns, etc.)


getInteractionRngState

Summary: Get RNG state for interaction between two entities


createEntityRng

Summary: Create RNG stream for a specific entity Use when you need multiple random values for one entity in the same tick


createPositionRng

Summary: Create RNG stream for a world position


sim/ai/AIRaycastGPU

Summary: Create a GPU raycast system


createGPURaycastSystem

async createGPURaycastSystem(device, options = {})

Summary: Create a GPU raycast system


uploadRays

Summary: Upload ray data to GPU


uploadAABBTargets

Summary: Upload AABB targets to GPU


uploadSphereTargets

Summary: Upload sphere targets to GPU


dispatchAABBRaycast

Summary: Dispatch GPU raycast against AABBs


dispatchSphereRaycast

Summary: Dispatch GPU raycast against spheres


copyResultsToReadback

Summary: Copy results to readback buffer


readbackResults

Summary: Read back results from GPU (async)


batchRaycast

async batchRaycast(system, rays, targets, targetType = "sphere")

Summary: Full batch raycast operation


destroyGPURaycastSystem

Summary: Destroy GPU raycast system and free resources


shouldUseGPURaycast

shouldUseGPURaycast(rayCount, threshold = 500)

Summary: Determine if GPU raycast should be used based on ray count


benchmarkRaycast

async benchmarkRaycast(system, rayCount = 1000, targetCount = 100)

Summary: Benchmark CPU vs GPU raycast for calibration


sim/ai/AIScheduler

Summary: Create needs state


createNeedsState

Summary: Create needs state


updateNeeds

Summary: Update needs over time


satisfyNeed

Summary: Satisfy a need


getMostUrgentNeed

Summary: Get most urgent need


getCriticalNeeds

Summary: Get all critical needs


calculateWellbeing

Summary: Calculate overall wellbeing


createActivity

Summary: Create an activity definition


scoreActivity

scoreActivity(activity, needs, gameHour = 12)

Summary: Score an activity based on needs


selectActivity

selectActivity(activities, needs, gameHour = 12)

Summary: Select best activity from options


createSchedule

Summary: Create a daily schedule


addScheduleEntry

addScheduleEntry(schedule, hour, activityId, priority = 1, days = null)

Summary: Add scheduled entry


getScheduledActivity

getScheduledActivity(schedule, gameHour, dayOfWeek = 0)

Summary: Get scheduled activity for time


createJob

Summary: Create job definition


isWorkTime

Summary: Check if currently work hours


createNPCScheduler

Summary: Create NPC scheduler


updateScheduler

updateScheduler(scheduler, gameHour, dayOfWeek, deltaGameHours)

Summary: Update NPC scheduler


NEED

Summary: Basic need types


URGENCY

Summary: Need urgency thresholds


Summary: Job types


sim/ai/AISchema

Summary: Get node type ID from name


getNodeTypeId

Summary: Get node type ID from name


getAwarenessStateId

Summary: Get awareness state ID from name


getAwarenessStateName

Summary: Get awareness state name from ID


getReputationLevel

Summary: Get reputation level from value


validatePerception

Summary: Validate perception parameters


validateSteeringAgent

Summary: Validate steering agent config


validatePersonality

Summary: Validate personality


createDefaultPerception

Summary: Create default perception config


createDefaultSteeringAgent

Summary: Create default steering agent


createDefaultPersonality

Summary: Create default personality


createDefaultFaction

Summary: Create default faction


Summary: Behavior tree node status


Summary: Behavior tree node types


Summary: NPC awareness states


Summary: Sense types for perception


Summary: Perception parameters schema


Summary: Steering behavior types


Summary: Steering agent schema


Summary: Diplomatic stances


Summary: Reputation levels


Summary: Faction schema


Summary: Personality traits (Big Five + custom)


Summary: Personality schema


Summary: Complete NPC AI schema


Summary: Create preset personality


sim/ai/AISenses

Summary: Create scent particle


createScentParticle

Summary: Create scent particle


createScentTrail

Summary: Create scent trail (series of particles)


addTrailParticle

addTrailParticle(trail, position, intensity = 1.0)

Summary: Add particle to trail


createScentSystem

Summary: Create scent system


updateScentSystem

Summary: Update scent system


smellAt

smellAt(system, position, range, sensitivity = 1.0)

Summary: Smell at position


followScentTrail

followScentTrail(system, position, targetSourceId, range)

Summary: Follow scent trail


createVibration

Summary: Create vibration event


createTremorSense

Summary: Create tremor sense system


emitVibration

Summary: Emit vibration


senseVibrations

senseVibrations(system, position, sensitivity = 1.0)

Summary: Sense vibrations at position


createDangerSense

Summary: Create danger sense system


registerThreat

registerThreat(system, threatId, position, dangerLevel, type = "unknown")

Summary: Register threat


removeThreat

Summary: Remove threat


senseDanger

senseDanger(system, position, range, sensitivity = 1.0)

Summary: Sense danger level at position


createEnvironmentSensor

Summary: Create environmental sensor


updateEnvironmentReadings

Summary: Update environment readings


getEnvironmentalComfort

Summary: Get environmental comfort level


detectEnvironmentTrend

Summary: Detect environmental trend


Summary: Scent types


sim/ai/AISmartObjects

Summary: Create a smart object


createSmartObject

Summary: Create a smart object


getSlotWorldPosition

getSlotWorldPosition(smartObject, slotIndex = 0)

Summary: Get world position of an interaction slot


findAvailableSlot

Summary: Find available slot for interaction


reserveSlot

Summary: Reserve a slot for an NPC


releaseSlot

Summary: Release a slot


checkPrerequisites

Summary: Check if NPC meets prerequisites for interaction


createInteraction

Summary: Create an interaction session


updateInteraction

updateInteraction(interaction, npcPos, npcFacing, now)

Summary: Update interaction state


completeInteraction

Summary: Complete interaction and apply effects


createSmartObjectRegistry

Summary: Create a smart object registry


registerSmartObject

Summary: Register a smart object


findByCategory

Summary: Find smart objects by category


findByTag

Summary: Find smart objects by tag


findNearestUsable

findNearestUsable(registry, position, npcState, filters = {})

Summary: Find nearest usable smart object


createHealthStation

createHealthStation(id, position, healAmount = 50)

Summary: Create a health station smart object


createAmmoCrate

createAmmoCrate(id, position, ammoAmount = 30)

Summary: Create an ammo crate smart object


createDoor

Summary: Create a door smart object


Summary: Smart object categories


Summary: Interaction states


sim/ai/AISound

Summary: Create a sound event


createSoundEvent

Summary: Create a sound event


createSoundSystem

Summary: Create sound propagation system


registerListener

registerListener(system, entityId, config = {})

Summary: Register listener (AI agent that can hear)


updateListenerPosition

Summary: Update listener position


addSoundOccluder

Summary: Add wall/occluder


emitSound

Summary: Emit sound


calculateSoundIntensity

Summary: Calculate sound intensity at position


updateSoundSystem

Summary: Update sound propagation and detection


getRecentDetections

getRecentDetections(system, entityId, maxAge = 5000)

Summary: Get recent detections for entity


getHighestPriorityDetection

Summary: Get highest priority unhandled detection


emitFootstep

emitFootstep(system, position, surface = SURFACE_TYPE.CONCRETE, running = false)

Summary: Emit footstep sound


emitGunshot

emitGunshot(system, position, weaponType = "pistol")

Summary: Emit gunshot sound


emitExplosion

emitExplosion(system, position, size = 1.0)

Summary: Emit explosion sound


Summary: Sound categories


Summary: Surface types for acoustic properties


Summary: Sound priority for AI attention


sim/ai/AISquad

Summary: Create a squad manager


createSquadManager

Summary: Create a squad manager


createSquad

Summary: Create a new squad


addToSquad

addToSquad(manager, squad, npc, role = SQUAD_ROLE.NONE)

Summary: Add NPC to squad


removeFromSquad

Summary: Remove NPC from their squad


disbandSquad

Summary: Disband a squad


updateSquadFormations

Summary: Update squad formations based on proximity NPCs within range form impromptu squads


assignSquadRoles

Summary: Assign tactical roles to squad members


calculateAttackPositions

Summary: Calculate attack positions for coordinated assault


planSuppressionManeuver

Summary: Check if squad should coordinate suppression fire


queueBark

queueBark(squad, npcId, barkType, data = {})

Summary: Queue a bark for the squad


processBarkQueue

Summary: Process pending barks


getBarkText

Summary: Get bark text for a bark type


updateSquadTactics

updateSquadTactics(manager, squad, threatPos, options = {})

Summary: Update squad tactical state


getSquadForNPC

Summary: Get squad for an NPC


getTeammates

Summary: Get teammates for an NPC (excluding self)


Summary: Squad roles


Summary: Communication bark types


sim/ai/AISteering

Summary: Create a steering agent Uses AISchema defaults for consistent configuration


applyForce

Summary: Apply steering force to agent


updateSteering

Summary: Update agent physics


seek

Summary: Seek: steer toward target


flee

Summary: Flee: steer away from target


arrive

arrive(agent, target, slowingRadius = 5)

Summary: Arrive: seek with slowing near target


pursue

Summary: Pursue: seek predicted future position of moving target


evade

Summary: Evade: flee from predicted future position


wander

Summary: Wander: random steering


avoidObstacles

Summary: Avoid obstacles using ray casting


avoidWalls

Summary: Avoid walls using feeler rays


separation

separation(agent, neighbors, separationRadius = 3)

Summary: Separation: steer away from nearby agents


alignment

alignment(agent, neighbors, alignmentRadius = 5)

Summary: Alignment: steer toward average heading of neighbors


cohesion

cohesion(agent, neighbors, cohesionRadius = 8)

Summary: Cohesion: steer toward center of neighbors


flock

Summary: Combined flocking behavior


followPath

Summary: Follow a path


createFlowField

Summary: Create a flow field


setFlowDirection

setFlowDirection(field, x, y, dirX, dirZ)

Summary: Set flow field cell direction


getFlowDirection

Summary: Get flow direction at world position


followFlowField

Summary: Follow flow field


generateFlowFieldToTarget

Summary: Generate flow field toward target


sim/ai/AITerrain

Summary: Create terrain grid


createTerrainGrid

Summary: Create terrain grid


setTerrainType

Summary: Set terrain type at cell


getTerrainType

Summary: Get terrain type at cell


setTerrainHeight

Summary: Set height at cell


getTerrainHeight

Summary: Get height at cell


worldToTerrainCell

Summary: World to grid coordinates


terrainCellToWorld

Summary: Grid to world coordinates (cell center)


getTerrainPropertiesAt

Summary: Get terrain properties at world position


calculateMovementCost

calculateMovementCost(grid, fromX, fromZ, toX, toZ)

Summary: Calculate movement cost between two points


getStealthModifier

Summary: Get stealth modifier at position


getNoiseModifier

Summary: Get noise modifier at position


calculateHeightAdvantage

calculateHeightAdvantage(grid, attackerX, attackerZ, defenderX, defenderZ)

Summary: Calculate height advantage


findHighGround

findHighGround(grid, centerX, centerZ, radius, count = 5)

Summary: Find high ground positions in area


findConcealment

findConcealment(grid, centerX, centerZ, radius, count = 5)

Summary: Find concealment positions


detectChokepoints

detectChokepoints(grid, minX, minZ, maxX, maxZ)

Summary: Detect chokepoints in area


evaluateTacticalPosition

evaluateTacticalPosition(grid, worldX, worldZ, threatDirection = null)

Summary: Evaluate tactical position value


Summary: Terrain types


sim/ai/AIUtility

Summary: Linear curve: y = mx + b


linearCurve

Summary: Linear curve: y = mx + b


inverseLinearCurve

Summary: Inverse linear curve: y = 1 - x


quadraticCurve

Summary: Quadratic curve: y = (x - offset)^2 * scale


exponentialCurve

Summary: Exponential curve: y = e^(kx) normalized


logisticCurve

Summary: Logistic (S-curve): y = 1 / (1 + e^(-k(x - midpoint)))


smoothstepCurve

Summary: Smoothstep curve: 3x^2 - 2x^3


stepCurve

Summary: Step curve: returns 0 below threshold, 1 above


bellCurve

Summary: Bell curve (Gaussian-like): peaks at center


customCurve

Summary: Custom curve from control points (piecewise linear)


createConsideration

createConsideration(name, inputFn, curve, weight = 1)

Summary: Create a consideration (single scoring factor)


evaluateConsideration

Summary: Evaluate a consideration


createUtilityAction

createUtilityAction(name, considerations, execute, options = {})

Summary: Create a utility action


scoreAction

Summary: Score an action


selectBestAction

Summary: Select best action from candidates


selectActionWeighted

selectActionWeighted(actions, context, randomFactor = 0.2)

Summary: Select action with weighted randomization Higher scores = higher chance, but not guaranteed


selectActionBucketed

selectActionBucketed(actions, context, bucketSize = 3)

Summary: Select from top N actions (bucketing)


createUtilityBrain

createUtilityBrain(actions, options = {})

Summary: Create a utility AI brain


updateUtilityBrain

updateUtilityBrain(brain, context, now = performance.now()

Summary: Update utility brain and select action


executeCurrentAction

Summary: Execute the current action


createHealthConsideration

Summary: Create health consideration


createDistanceConsideration

Summary: Create distance consideration


createAmmoConsideration

Summary: Create ammo consideration


createThreatConsideration

Summary: Create threat consideration


createCoverConsideration

Summary: Create cover consideration


createLOSConsideration

Summary: Create line of sight consideration


createCombatActions

Summary: Create basic combat action set


sim/ai/AIValues

Summary: Create NPC values system


createValueSystem

Summary: Create NPC values system


createLifeGoal

Summary: Create a life goal


getValue

Summary: Get value strength


setValue

Summary: Set value strength


modifyValue

Summary: Modify value (shift toward a direction)


valuesPositively

Summary: Check if NPC values something


getTopValues

Summary: Get top values (what they care about most)


satisfyPsychNeed

Summary: Update psychological need


decayPsychNeeds

Summary: Decay psychological needs over time


getMostDeprivedNeed

Summary: Get most deprived psychological need


calculateWellbeing

Summary: Calculate overall psychological wellbeing


addLifeGoal

Summary: Add life goal


updateGoalProgress

Summary: Update goal progress


pursueGoal

Summary: Start pursuing a goal


getActiveGoals

Summary: Get active goals being pursued


getUnfulfilledDreams

Summary: Get unfulfilled dreams


scoreActionByValues

Summary: Score an action based on values


wouldDoAction

wouldDoAction(system, action, threshold = 0)

Summary: Would NPC do this action based on values?


createFromPreset

Summary: Create value system from preset


VALUE

Summary: Value types - things an NPC can care about


Summary: Value strength levels


Summary: Types of life goals


Summary: Goal status


Summary: Higher-order psychological needs


Summary: Preference categories


Summary: Value presets for quick character creation


sim/ai/AIVehicle

Summary: AIVehicle.js ⚠ MULTIPLAYER: Uses deterministic RNG from AIRandom.js


createVehicleType

Summary: Create vehicle definition


createVehicle

createVehicle(vehicleType, position, heading = 0)

Summary: Create vehicle instance


updateVehiclePhysics

Summary: Update vehicle physics


updateVehicleAI

Summary: Update vehicle AI


setVehiclePath

Summary: Set vehicle path


createTrafficSystem

Summary: Create traffic system


updateTrafficSystem

Summary: Update traffic system


Summary: Vehicle behavior modes


Summary: Traffic light states


sim/ai/AIWeapons

Summary: Fire a hitscan weapon (instant ray hit)


fireHitscan

fireHitscan(origin, direction, weapon, targets, obstacles = [])

Summary: Fire a hitscan weapon (instant ray hit)


fireShotgun

fireShotgun(origin, direction, weapon, targets, obstacles = [])

Summary: Fire a shotgun (multiple pellets in ring pattern)


calculateDamageFalloff

calculateDamageFalloff(baseDamage, distance, rangeModifier = 0.98)

Summary: Calculate damage falloff (CS:GO style exponential)


createProjectile

createProjectile(position, velocity, config = {})

Summary: Create a projectile entity


updateProjectile

Summary: Update projectile position (kinematic motion)


getProjectilePositionAtTime

Summary: Get projectile position at future time (prediction) P(t) = P₀ + V₀×t + ½×g×t²


checkProjectileCollision

checkProjectileCollision(projectile, targets, projectileRadius = 0.5)

Summary: Check projectile collision with targets


isInCircularAoE

Summary: Check if target is in circular AoE


calculateAoEDamage

Summary: Calculate AoE damage with quadratic falloff


resolveCircularAoE

resolveCircularAoE(center, radius, baseDamage, targets)

Summary: Get all targets in circular AoE with damage


isInConeAoE

isInConeAoE(targetPos, origin, direction, halfAngleRad, range)

Summary: Check if target is in cone AoE


resolveConeAoE

resolveConeAoE(origin, direction, coneAngleDeg, range, baseDamage, targets)

Summary: Get all targets in cone AoE


createBeamWeapon

Summary: Create a beam weapon state


updateBeamTracking

updateBeamTracking(beam, origin, targetPos, deltaTimeSec)

Summary: Update beam weapon direction toward target


fireBeam

fireBeam(beam, origin, targets, obstacles, deltaTimeSec)

Summary: Fire beam weapon (continuous damage)


createGrenade

createGrenade(position, velocity, config = {})

Summary: Create a grenade projectile


updateGrenade

updateGrenade(grenade, deltaTimeSec, surfaces = [])

Summary: Update grenade physics


calculateGrenadeLaunchVelocity

calculateGrenadeLaunchVelocity(start, target, gravity, launchAngleDeg)

Summary: Calculate grenade launch velocity to hit target


createWeaponController

Summary: Create an NPC weapon controller for multi-weapon management


addWeapon

Summary: Add weapon to controller


selectBestWeapon

Summary: Select best weapon for situation


canFireWeapon

Summary: Check if weapon can fire (fire rate cooldown)


recordWeaponFire

Summary: Record weapon fire


Summary: Weapon type constants


Summary: Default weapon configurations


sim/ai/AIWorld

Summary: Create world time system


createWorldTime

Summary: Create world time system


advanceTime

Summary: Advance world time


getSeason

Summary: Get current season


getDayPhase

Summary: Get day/night phase


formatTime

Summary: Get formatted time string


formatDate

Summary: Get formatted date string


createWeatherSystem

Summary: Create weather system


updateWeather

Summary: Update weather


getWeatherEffects

Summary: Get weather effects on gameplay


createWorldEvent

Summary: Create world event


createEventManager

Summary: Create world event manager


scheduleEvent

Summary: Schedule world event


updateEvents

Summary: Update world events


createWorldState

Summary: Create complete world state


updateWorldState

Summary: Update world state


SEASON

Summary: Seasons


Summary: Days of week


MONTH

Summary: Months


Summary: Weather types


Summary: Event types


sim/ai/Blackboard


sim/ai/NavGrid

Summary: Convert axial (q, r) to cube (q, r, s) coordinates


bakeNavGridFromWorldSim

bakeNavGridFromWorldSim(grid, worldSim, options = {})


cubeToAxial

Summary: Convert cube to axial coordinates


hexToWorld

Summary: Convert cube coordinates to world position (pointy-top hexes)


worldToHex

Summary: Convert world position to cube hex coordinates


cubeRound

Summary: Round fractional cube coordinates to nearest hex


hexNeighbors

Summary: Get 6 hex neighbors in cube coordinates


hexDistance

Summary: Calculate hex distance in cube coordinates


hexRange

Summary: Get all hexes within range of center


hexRing

Summary: Get hex ring at exact distance from center


hexLine

Summary: Linear interpolation between two hexes (for line drawing)


createHexGrid

Summary: Create hex grid for strategy layer


sim/ai/NavWorld


sim/ai/Pathfinder


findPathOnGrid

findPathOnGrid(grid, start, goal, options = {})


findPathInNavWorld

findPathInNavWorld(navWorld, layerName, start, goal, options = {})


sim/ai/SpatialHash

Summary: Create a 3D spatial hash grid


createSpatialHash

Summary: Create a 3D spatial hash grid


spatialHashInsert

Summary: Insert an entity into the spatial hash


spatialHashRemove

Summary: Remove an entity from the spatial hash


spatialHashUpdate

Summary: Update an entity's position in the spatial hash


spatialHashQueryRadius

spatialHashQueryRadius(hash, x, y, z, radius)

Summary: Query all entities within radius of a point


spatialHashQueryRadius2D(hash, x, z, radius)

Summary: Query all entities within radius (2D, ignores Y)


spatialHashQueryAABB

Summary: Query entities in an AABB


spatialHashKNearest

spatialHashKNearest(hash, x, y, z, k, maxRadius = 100)

Summary: Get K nearest neighbors to a point


spatialHashClear

Summary: Clear all entities from the spatial hash


spatialHashCount

Summary: Get total entity count


spatialHashRebuild

Summary: Rebuild the spatial hash from an entity array


createObjectPool

createObjectPool(factory, reset = null, initialSize = 100)

Summary: Create an object pool for reducing GC pressure


poolAcquire

Summary: Acquire an object from the pool


poolRelease

Summary: Release an object back to the pool


poolReleaseAll

Summary: Release all active objects back to pool


poolStats

Summary: Get pool statistics


sim/ai/index


sim/cloth/ClothSimWorld


stepClothSimWorld

stepClothSimWorld(world, deltaSeconds, options = {})


sim/fluids/FDTDSolver

Summary: Yee cell field components Staggered grid: E at integers, H at half-integers


TimeVaryingMaterial

Summary: Time-varying material properties


PHYSICS

Summary: Physical constants


MaterialType

Summary: Material types


BoundaryCondition

Summary: Boundary conditions


SourceType

Summary: Source types


sim/fluids/FluidBoundary

Summary: Generate WGSL shader for applying solid boundaries to velocity This should run after the pressure projection step


createPressureSolveWithBoundaryShader

Summary: Generate WGSL shader for pressure solve with solid boundaries Modifies the Jacobi iteration to handle solid cells


createBoundaryPipeline

createBoundaryPipeline(device, options = {})

Summary: Create boundary enforcement pipeline


applyBoundaries

Summary: Apply solid boundaries to velocity field


sim/fluids/FluidConfig


sim/fluids/FluidCpuWorld


applyFluidSourcesCpu

applyFluidSourcesCpu(world, options = {})


sim/fluids/FluidMPM

Summary: Create MPM-specific buffers for the fluid simulation


destroyMPMBuffers

Summary: Destroy MPM buffers


Summary: Generate the P2G (Particle to Grid) compute shader Uses linear kernel (tent function) for simplicity


createGridUpdateShader

Summary: Generate the Grid Update compute shader Converts accumulated momentum to velocity, applies forces and boundaries


Summary: Generate the G2P (Grid to Particle) compute shader


createMPMPipelines

createMPMPipelines(device, options = {})

Summary: Create MPM compute pipelines


createMPMWorld

Summary: Create a complete MPM simulation world


destroyMPMWorld

Summary: Destroy MPM world


stepMPMWorld

stepMPMWorld(world, particles, dt, options = {})

Summary: Step the MPM simulation


setMPMWorldBounds

Summary: Update MPM world bounds


sim/fluids/FluidPhaseChange

Summary: Create phase change data structures


createPhaseChangeBuffers

Summary: Create phase change data structures


createSpellForce

createSpellForce(position, direction, power, element)

Summary: Spell force injection point


createSpellForceShader

Summary: Generate shader for applying spell forces to fluid


createFreezeShader

Summary: Generate shader for freeze effect (temperature-based phase transition)


createCrystallizationShader

Summary: Generate shader for particle-based crystallization chain reaction Physics-based with latent heat buffer, hysteresis, and asymmetric rates Key concepts from real physics: - Latent heat: Energy absorbed/released during phase change while temp stays constant - Hysteresis: Different thresholds for freezing vs melting (prevents flickering) - Supercooling: Fluid can stay liquid below freezing until nucleation occurs


createSolidCollisionShader

Summary: Generate shader for solid particle collision Frozen particles get rigid collision with world, entities, AND other particles Also handles temperature transfer on contact


createCrystalBondShader

Summary: Generate shader for crystal bond formation Finds nearby frozen particles and creates rigid bonds between them


createBondConstraintShader

Summary: Generate shader for bond constraint solving (Position-Based Dynamics) Maintains rigid crystal structure by keeping bonded particles at fixed distances


createSolidCollisionPipeline

createSolidCollisionPipeline(device, workgroupSize = 256)

Summary: Create compute pipeline for solid particle collision


createCrystalBondPipeline

createCrystalBondPipeline(device, workgroupSize = 256)

Summary: Create compute pipeline for crystal bond formation


createBondConstraintPipeline

createBondConstraintPipeline(device, workgroupSize = 256)

Summary: Create compute pipeline for bond constraint solving


stepSolidCollision

stepSolidCollision(device, collisionPipeline, phaseBuffers, particleWorld, colliderData, roomBounds, dt, options = {})

Summary: Step the solid collision system


stepCrystalBonds

stepCrystalBonds(device, bondPipeline, phaseBuffers, particleWorld, options = {})

Summary: Step the crystal bond formation system


stepBondConstraints

stepBondConstraints(device, constraintPipeline, phaseBuffers, particleWorld, bondCount, options = {})

Summary: Step the bond constraint solver (PBD) Run multiple iterations for stability


readBondCount

Summary: Read bond count from GPU (async)


clearBonds

Summary: Clear all bonds (for reset or when spawning rigid body)


stepCrystalSystem

stepCrystalSystem(device, systems, phaseBuffers, particleWorld, colliderData, roomBounds, dt, options = {})

Summary: Full crystal system - combines all steps Call this each frame to handle solidification, collision, bonding, and constraints


createCrystalSystemPipelines

createCrystalSystemPipelines(device, workgroupSize = 256)

Summary: Create all crystal system pipelines at once


extractCrystalClusters

async extractCrystalClusters(device, phaseBuffers, particleWorld, minClusterSize = 5)

Summary: Extract connected crystal clusters from bonds for rigid body spawning Uses Union-Find algorithm to identify connected components


createSeedInjectionParams

createSeedInjectionParams(position, radius, seedStrength, temperature, magicSaturation)

Summary: Inject seed particles at a position (ice spell impact, magic anchor, etc.)


createCrystallizationPipeline

createCrystallizationPipeline(device, workgroupSize = 256)

Summary: Create compute pipeline for crystallization chain reaction


stepCrystallization

stepCrystallization(device, crystallization, phaseBuffers, particleWorld, dt, options = {})

Summary: Step the crystallization system - run compute pass to propagate freezing


injectFreezeSeeds

injectFreezeSeeds(device, phaseBuffers, particleWorld, seedParams)

Summary: Inject freeze seeds at a world position (for ice spell impact) Affects particles within radius - sets their temp/magic/seed values


injectHeatSeeds

injectHeatSeeds(device, phaseBuffers, particleWorld, seedParams)


applyPhaseVisuals

applyPhaseVisuals(device, phaseBuffers, particleWorld, options = {})

Summary: Apply visual effects based on phase state (color frozen particles blue/white) Call this after stepCrystallization to update particle rendering


extractFrozenShape

async extractFrozenShape(device, phaseChangeBuffers, gridSize, worldMin, cellSize)

Summary: Extract frozen region as convex hull for rigid body creation This runs on CPU after GPU freeze pass


clearFreezeRegion

Summary: Clear freeze region after rigid body is spawned


injectMeltedFluid

injectMeltedFluid(device, fluidWorld, position, velocity, mass, radius)

Summary: Inject mass/momentum when melting a rigid body


destroyPhaseChangeBuffers

Summary: Destroy phase change buffers


destroyCrystalSystemPipelines

Summary: Destroy crystal system pipelines


extractFrozenParticles

async extractFrozenParticles(device, phaseBuffer, positionBuffer, particleCount, minClusterSize = 5)

Summary: Extract frozen particle cluster for rigid body spawning Returns particles that are FROZEN phase and form a connected cluster


FluidPhase

Summary: Phase states for fluid cells/particles


Summary: Particle solidification attributes (per-particle) - temperature: Current temp (ambient ~20, freezing < 0) - magicSaturation: 0-1, how much "freeze magic" has accumulated - solidPhase: 0=fluid, 1=freezing, 2=frozen - seedStrength: If > 0, this particle spreads solidification


Summary: Crystal bond attributes (per-bond) Stores connections between frozen particles forming crystal lattice - particleA: index of first particle - particleB: index of second particle - restDistance: original distance when bond formed (constraint target) - stiffness: bond strength (0-1, higher = more rigid)


Summary: Default crystallization parameters - tuned for fast freeze, slow melt


Summary: Default solid collision parameters


sim/fluids/FluidSimWorld

Summary: Clear/reset the density and velocity buffers to zero. Use this when bounds change significantly to prevent stale data from appearing at wrong world-space locations.


createFluidSimWorld

async createFluidSimWorld(gpuDevice, options = {})


stepFluidSimWorld

stepFluidSimWorld(world, deltaSeconds, options = {})


clearFluidDensity

Summary: Clear the density and color buffers to zero. Used in particle-as-smoke mode to reset before splatting particle positions/colors.


initFluidSimWorldLazy

Summary: Initialize fluid sim world lazily with bind group creation for smoke rendering. This is a convenience function that handles the full setup sequence.


sim/fluids/FluidSimulation

Summary: Per-voxel simulation metadata Stored separately from material ID to avoid expanding chunks


Summary: Physical properties for each material type Properties: - type: 'solid' | 'powder' | 'liquid' | 'gas' | 'fire' - density: Higher density sinks below lower density (0-100) - viscosity: How slowly liquid spreads (0=instant, 1=very slow) - flammable: Can catch fire - burnTime: Ticks until destroyed by fire - spreadRate: How many cells to check for spreading (liquids/gases)


sim/fluids/FluidSourceSplat

Summary: PARTICLES AS SMOKE - splat density at each particle position. Each particle IS the smoke - not a separate effect. Inherits from particle: - Position → where density is splatted - Size (from meta.a) → splat radius - Color (from meta.rgb) → smoke color (sampled by smoke shader) - Age/Lifetime → fade behavior When raymarched, overlapping particles merge into smooth fluid blobs.


splatFluidSources

async splatFluidSources(fluidWorld, gpuDevice, options = {})


splatParticleDensity

splatParticleDensity(fluidWorld, particleWorld, options = {})


sim/fluids/FluidWorldDomain

Summary: Build fluid domain from ECS world colliders


buildFluidDomainFromColliders

buildFluidDomainFromColliders(ecsWorld, options = {})


createSolidMaskTexture

Summary: Create a 3D solid mask texture from colliders Each cell is 0 (fluid) or 1 (solid)


createWorldFluidDomain

createWorldFluidDomain(device, ecsWorld, options = {})

Summary: Create a world fluid domain with solid mask


updateWorldFluidDomainParams

Summary: Update world fluid domain params buffer


destroyWorldFluidDomain

Summary: Destroy world fluid domain


rebuildSolidMask

Summary: Rebuild solid mask when scene changes


sim/fluids/PhasorRays

Summary: Ray with wave properties (phasor representation)


frequencyToColor

Summary: Convert frequency to visible color (RGB)


wavelengthToColor

Summary: Convert wavelength to color


dopplerColor

Summary: Apply Doppler shift color


generateRayVisualization

Summary: Generate visualization data for rays


Summary: Base visible light frequencies


RayInteraction

Summary: Ray interaction types


RayState

Summary: Ray state


sim/fluids/PhotonicCrystal

Summary: Computes dispersion relation for time-varying medium For photonic time crystal: ω(k) has gaps in k-space (momentum gaps)


TimeReflectionEvent

Summary: Represents a sudden change in ε that creates time reflection


TemporalCloak

Summary: Temporal cloaking using time lens approach Opens and closes a gap in the time domain


CrystalType

Summary: Photonic crystal types


ModulationWaveform

Summary: Modulation waveforms


TemporalEffect

Summary: Time crystal effects


sim/fluids/VolumeFieldSmooth


sim/fluids/VolumeFieldWorld


createVolumeFieldWorld

async createVolumeFieldWorld(gpuDevice, options = {})


sim/fluids/index


sim/particles/AsyncSnapshotManager

Summary: AsyncSnapshotManager.js - Async wrapper for worker-based snapshot capture Coordinates between main thread (GPU readback) and worker (compression). Uses TRIPLE buffering for completely non-blocking capture: Buffer A: Being filled from GPU readback Buffer B: Being processed by worker Buffer C: Completed and ready for use This ensures the render loop NEVER waits for GPU or worker.


initAsyncSnapshotSystem

Summary: Initialize the async snapshot system


captureFrameAsync

async captureFrameAsync(snapshot, particleState, emitters, currentTimeMs)

Summary: Capture a frame asynchronously GPU readback happens on main thread, compression in worker


captureFrameTripleBuffered

captureFrameTripleBuffered(snapshot, particleState, emitters, currentTimeMs)

Summary: Triple-buffered capture - completely non-blocking Returns immediately, GPU readback and worker processing happen in background


destroyAsyncSnapshot

Summary: Clean up


setSnapshotCaptureInterval

Summary: Set capture interval (for quality/performance tradeoff)


sim/particles/AttachedParticlesCompute


updateAttachedParticlesIntoWorld

async updateAttachedParticlesIntoWorld(gpuDevice, meshBuffers, particleWorld, attachmentBuffer, options = {})


async updateAttachedParticlesIntoParticlesState(particles, meshBuffers, options = {})


sim/particles/BoneAttachedParticlesCompute


assignParticlesToBonesIntoWorld

async assignParticlesToBonesIntoWorld(gpuDevice, boneBuffer, particleWorld, attachmentBuffer, options = {})


updateBoneAttachedParticlesIntoWorld

async updateBoneAttachedParticlesIntoWorld(gpuDevice, boneBuffer, particleWorld, attachmentBuffer, options = {})


async assignParticlesToBonesIntoParticlesState(particles, boneBuffer, options = {})


async updateBoneAttachedParticlesIntoParticlesState(particles, boneBuffer, options = {})


sim/particles/CustomSDFCollisionBridge

Summary: CustomSDFCollisionBridge.js - Bridge Custom Particle Effects to Physics Collision Ensures visual SDF and collision SDF are IDENTICAL by: 1. Generating collision shaders from the same SDF code as visual effects 2. Providing a unified API for registering custom effects with physics 3. Syncing effect parameters between render and simulation This ensures "what you see is what collides" - particles collide exactly with the shape that's being rendered.


generateCustomEffectCollisionShader

Summary: Generate collision shader that uses the SAME SDF code as visual rendering This is the key to ensuring physics matches visuals exactly


createCustomEffectCollisionSystem

createCustomEffectCollisionSystem(device, registeredEffects = [])

Summary: Create custom effect collision system Uses the same SDF code as visual rendering for exact physics/visual match


addCustomEffectCollider

addCustomEffectCollider(system, device, effectId, center, radius, effectParams = [0, 0, 0, 0])

Summary: Add a custom effect collider Uses the same effect ID as visual rendering for exact match


updateCustomEffectCollider

updateCustomEffectCollider(system, device, index, center, radius, effectParams)

Summary: Update collider transform (for moving effects)


initCustomEffectCollisionBindGroup

initCustomEffectCollisionBindGroup(system, device, positionsBuffer, velocitiesBuffer, metaBuffer = null)

Summary: Initialize bind group with particle buffers


executeCustomEffectCollision

executeCustomEffectCollision(system, device, queue, particleCount, time, dt, bounciness = 0.3, friction = 0.1, fallbackRadius = 0.1)

Summary: Execute custom effect collision pass


rebuildCustomEffectCollisionSystem

Summary: Rebuild collision system when effects change Call this after registering new custom effects


clearCustomEffectColliders

Summary: Clear all colliders


destroyCustomEffectCollisionSystem

Summary: Destroy system and release GPU resources


sim/particles/GPUParticleSorter


sim/particles/MeshToParticlesCompute


generateMeshParticlesIntoWorld

async generateMeshParticlesIntoWorld(gpuDevice, meshBuffers, particleWorld, options = {})


generateMeshParticlesIntoParticlesState

async generateMeshParticlesIntoParticlesState(particles, meshBuffers, options = {})


sim/particles/MeshToParticlesPipelineCache


sim/particles/ParticleAdaptiveSubstep

Summary: ParticleAdaptiveSubstep.js - Adaptive Substeps with CFL Condition (GAP 20) Automatically determines the number of simulation substeps per frame based on the maximum particle velocity (CFL condition), preventing tunneling for fast particles without wasting substeps on slow ones. CFL: dt_sub = cellSize * cflFactor / maxSpeed Substeps = ceil(dt_frame / dt_sub), clamped to [minSubsteps, maxSubsteps] Uses GPU readback of max velocity (from indirect dispatch counters or a separate reduction pass) when available, falls back to CPU-side estimate. Ref: Houdini POP Solver CFL, PhysX particle substeps


createAdaptiveSubstepController

Summary: Create an adaptive substep controller.


computeAdaptiveSubsteps

Summary: Compute the number of substeps needed for this frame.


estimateMaxSpeedCPU

estimateMaxSpeedCPU(velocityData, particleCount, sampleCount = 256)

Summary: Estimate max particle speed from CPU-side velocity data. Use this as fallback when GPU readback is not available.


resetAdaptiveSubsteps

Summary: Reset the controller state.


sim/particles/ParticleAdvanced

Summary: ParticleAdvanced.js - GPU Sorting, Chunked Buffers, Wire Constraints, SDF Collision Advanced particle system features: - Bitonic GPU sorting for transparency - Chunked buffer management for 100M+ particles - Wire/spring constraints between particles - SDF mesh collision - GPU particle seeding - Volumetric lighting integration


createGPUSortSystem

Summary: Create GPU sorting system for transparent particle rendering


initSortBindGroup

Summary: Initialize sort bind group with position buffer


executeGPUSort

executeGPUSort(sortSystem, device, particleCount, cameraPos)

Summary: Execute GPU sort pass


createChunkedBufferSystem

createChunkedBufferSystem(device, maxParticles, bytesPerParticle = 16)

Summary: Create chunked particle buffer system for 100M+ particles


getChunkForParticle

Summary: Get chunk index for a particle index


getLocalIndex

Summary: Get local index within a chunk


destroyChunkedBufferSystem

Summary: Destroy chunked buffer system


createWireConstraintSystem

createWireConstraintSystem(device, maxWires = 10000)

Summary: Create wire constraint system


addWireConstraint

addWireConstraint(wireSystem, device, particleA, particleB, restLength, stiffness = 0.5)

Summary: Add a wire constraint between two particles


initWireBindGroup

initWireBindGroup(wireSystem, device, positionsBuffer, velocitiesBuffer)

Summary: Initialize wire constraint bind group


solveWireConstraints

solveWireConstraints(wireSystem, device, iterations = 4)

Summary: Solve wire constraints


createSDFCollisionSystem

createSDFCollisionSystem(device, initialCapacity = 64)

Summary: Create SDF collision system


addSDFCollider

addSDFCollider(sdfSystem, device, type, center, radius, halfExtents = [1, 1, 1])

Summary: Add an SDF collider


clearSDFColliders

Summary: Clear all SDF colliders (for per-frame rebuild from entity shapes)


rebuildSDFColliders

Summary: Batch-write SDF colliders from an array of collider descriptors. Much more efficient than calling addSDFCollider() in a loop.


initSDFBindGroup

initSDFBindGroup(sdfSystem, device, positionsBuffer, velocitiesBuffer, metaBuffer = null)

Summary: Initialize SDF collision bind group


executeSDFCollision

executeSDFCollision(sdfSystem, device, particleCount, bounciness = 0.3, friction = 0.1, options = {})

Summary: Execute SDF collision pass


createSeedingSystem

Summary: Create GPU particle seeding system


initSeedingBindGroup

initSeedingBindGroup(seedSystem, device, positionsBuffer, velocitiesBuffer)

Summary: Initialize seeding bind group


seedParticlesGPU

seedParticlesGPU(seedSystem, device, particleCount, options = {})

Summary: Seed particles on GPU


createVolumetricLightingSystem

Summary: Create volumetric lighting system for particles


initVolumetricBindGroup

initVolumetricBindGroup(volSystem, device, positionsBuffer, thermalBuffer, velocitiesBuffer)

Summary: Initialize volumetric lighting bind group


computeVolumetricLighting

computeVolumetricLighting(volSystem, device, particleCount, lightPos, lightColor, options = {})

Summary: Compute volumetric lighting for particles


createDepthCollisionSystem

Summary: Create depth buffer collision system. Bind group is created separately via initDepthCollisionBindGroup (recreate on depth texture resize).


initDepthCollisionBindGroup

initDepthCollisionBindGroup(system, device, positionsBuffer, velocitiesBuffer, depthTextureView)

Summary: Initialize or recreate the depth collision bind group. Must be called whenever the depth texture changes (e.g., on window resize).


executeDepthCollision

executeDepthCollision(system, device, particleCount, viewProj, invViewProj, options = {})

Summary: Execute depth buffer collision compute pass.


sim/particles/ParticleAttributeReader

Summary: ParticleAttributeReader.js - Cross-Emitter Attribute Reader (GAP 21) Allows one emitter to read particle data from another emitter's buffers. Enables leader-follower, flocking, synchronized multi-layer effects. Matches Niagara's Particle Attribute Reader data interface. Two modes: 1. Direct index: read specific particle by index (leader-follower) 2. Nearest query: find closest particle to a given position (via spatial grid) Usage: const reader = createAttributeReader(sourceWorld); // In consumer emitter logic: const pos = readParticlePosition(reader, particleIndex); const vel = readParticleVelocity(reader, particleIndex); const nearest = findNearestParticle(reader, queryPos);


createAttributeReader

createAttributeReader(sourceWorld, options = {})

Summary: Create an attribute reader bound to a source particle world.


refreshAttributeCache

Summary: Refresh CPU-side cache from GPU buffers (async). Call once per frame before reading attributes.


readParticlePosition

Summary: Read a particle's position and age.


readParticleVelocity

Summary: Read a particle's velocity and lifetime.


readParticleMeta

Summary: Read a particle's color and packed meta.


findNearestParticle

Summary: Find the nearest alive particle to a query position (brute force). For large counts, use the spatial grid instead.


findParticlesInRadius

findParticlesInRadius(reader, queryPos, radius, maxResults = 32)

Summary: Find all particles within a radius of a query position.


destroyAttributeReader

Summary: Destroy the reader.


sim/particles/ParticleAudioBridge

Summary: ParticleAudioBridge.js - Real-Time Procedural Spatial Audio for Particle Systems Zero-latency audio driven by GPU particle events via onParticleEvent callbacks. Every collision triggers sound immediately — no polling, no timers. Architecture informed by FMOD, PopcornFX, and Web Audio API perf research: - HRTF panning — binaural left/right ear simulation with elevation + front/back cues - Spatial clustering — nearby same-material impacts merge into single louder sound - Priority classes — critical/high/normal/low tiers (FMOD-style, not just volume) - Fade-out on voice steal — 5ms gain ramp prevents audible clicks - Separate ambient bus — continuous loops bypass transient compressor (no pumping) - Listener orientation — correct panning from camera forward/up vectors - Shared AudioContext — accepts external context to avoid browser resource limits - Per-material spatial cooldown — dedupes only within a radius, not globally - Dynamic compressor on impact bus — tames peak transients without affecting ambients Usage: const bridge = createAudioBridge({ maxVoices: 32, maxDistance: 100 }); wireEventCallbacks(bridge, world.eventSystem, getMaterialForEvent); // Per-frame (for ambient loops + listener tracking): updateListenerFromCamera(bridge, camera); updateEmitterAmbients(bridge, emitters); // Cleanup: destroyAudioBridge(bridge);


createAudioBridge

Summary: Create an audio bridge with full voice management.


destroyAudioBridge

Summary: Destroy the bridge and release all audio resources.


updateListenerFromCamera

Summary: Update listener from a camera object. Sets both position AND orientation for correct spatial panning (research: without orientation, all panning is wrong).


triggerImpact

triggerImpact(bridge, material, position, speed = 2, temperature = 300, priorityClass = PRIORITY_NORMAL, velocity = null)

Summary: Trigger an impact sound immediately. Used for reaction events and manual triggers. For collision/death events, use the batched system (flushImpactBatches) instead.


wireEventCallbacks

Summary: Wire the bridge into the ParticleEventSystem via onParticleEvent callbacks. Fires immediately when readbackEvents completes — zero polling, zero timers. Registers for collision events (type 2, 3) and death events (type 1).


unwireEventCallbacks

Summary: Unwire event callbacks (for cleanup). Actually removes the callback functions from the event system's callback arrays.


updateAmbientLoop

updateAmbientLoop(bridge, emitterId, material, position, params = {})


stopAllSounds

Summary: Immediately silence ALL particle audio — impacts + ambients. Called when the editor exits play mode (Stop button).


setReverbParams

Summary: Update reverb parameters at runtime (e.g., when entering a cave or outdoor area).


setImpactVolume

Summary: Set impact bus volume independently (0-1). Smoothed to avoid zipper noise.


setAmbientVolume

Summary: Set ambient bus volume independently (0-1). Smoothed to avoid zipper noise.


resumeAudioContext

Summary: Resume AudioContext after browser autoplay policy suspension. Research (Chrome/Safari): Context starts 'suspended' until user gesture. Call this from your first click/keydown handler.


autoUnlockAudioContext

Summary: Auto-unlock AudioContext on first user interaction (Safari/iOS workaround). Research (Matt Montag): Safari requires resume() from touch/click handler. Registers one-shot listeners that self-remove after first successful resume.


pauseAllAudio

Summary: Pause all audio (suspend context). Use when tab hidden or game paused. Research (web.dev Fieldrunners): every game should pause audio on tab hide to prevent wasted CPU and audio buildup.


resumeAllAudio

Summary: Resume all audio after pause.


hookVisibilityAutoPause

Summary: Hook into Page Visibility API to auto-pause/resume audio. Call once after createAudioBridge.


setOcclusionCallback

Summary: Set an occlusion callback. The function receives (sourcePos, listenerPos) and returns 0-1 (0=fully occluded, 1=clear). Used to modulate LPF cutoff for obstruction. Game code provides the raycast logic; audio system just applies the result.


soloMaterial

Summary: Debug: solo a specific material (only that material plays). Pass null to clear.


muteMaterial

Summary: Debug: mute a specific material. Pass null to unmute all.


resetAudioBridgeStats

Summary: Reset per-frame stats counters for delta profiling. Call after getAudioBridgeStats each frame.


sim/particles/ParticleBonds

Summary: ParticleBonds.js - Dynamic Bond Formation & Breaking System Manages runtime creation and destruction of particle bonds (WELD, STICKY constraints) driven by proximity, temperature, and particle flags. Features: - Bond formation: WELDABLE particles within threshold + temperature conditions → WELD constraint - Bond breaking: Constraints with FLAG_BROKEN get cleaned up + optional break effects - Temperature-driven dynamics: Freezing forms bonds, melting breaks them - Rate limiting: Max bonds per frame to prevent GPU stalls


createBondSystem

Summary: Create a bond management system.


stepBondFormation

stepBondFormation(world, bondSystem, options = {})

Summary: Attempt to form bonds between nearby particles. Called each frame from the simulation loop.


stepBondBreaking

stepBondBreaking(world, bondSystem, options = {})

Summary: Process broken bonds and clean them up. Call after constraint solver has run.


stepBondSystem

stepBondSystem(world, bondSystem, options = {})

Summary: Step the full bond system (formation + breaking).


getBondStats

Summary: Get bond system stats.


destroyBondSystem

Summary: Destroy bond system and clear all bonds.