world/storage/RegionFile.js
Classes
class RegionFile
class RegionManager
Re-exports
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes RegionFile Manages a single region file containing 32x32 chunks Method Signature Summary Get filename for this region Convert local chunk coordinates to index (2D per Y layer) Get location entry for a chunk Set location entry for a chunk Check if chunk exists in region Get chunk timestamp Allocate sectors for chunk data Free sectors used by a chunk Write chunk to region Read chunk data from region Delete chunk from region Serialize region to binary for storage Deserialize region from binary data Check if region needs compaction based on fragmentation Get region health status Defragment region file (compact sectors) Get list of all chunk coordinates in this region Get region statistics RegionManager High level interface for region based chunk storage Method Signature Summary Get region key from region coordinates Convert world chunk coordinates to region coordinates Get or create region file Save chunk to appropriate region Load chunk from appropriate region Check if chunk exists Delete chunk Get all dirty regions that need saving Mark region as saved Unload region from memory Get statistics Get health status for all loaded regions Compact all fragmented regions Re exports , , , <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


world/storage/StorageBackends.js
Classes
class OPFSBackend
class IndexedDBBackend
class FileSystemBackend
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: StorageBackends.js Storage backend implementations Extracted from WorldStorage.js for modularity Includes: OPFSBackend (Origin Private File System) IndexedDBBackend (fallback) FileSystemBackend (user selected folder) Classes Method Signature Summary Method Signature Summary Method Signature Summary <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


paletteDecompress(palette, bits, packed, count)

decompressChunk(compressed, chunkSize = 32)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Calculate CRC32 checksum Parameters: (Uint8Array) — No description in source JSDoc. Returns: 32 bit CRC Verify data integrity Parameters: (Uint8Array) — No description in source JSDoc. (number) — No description in source JSDoc. Encode 3D coordinates to Morton code (Z order) Parameters: (number) — X coordinate (0 1023) (number) — Y coordinate (0 1023) (number) — Z coordinate (0 1023) Returns: 30 bit Morton code Decode Morton code to 3D coordinates Parameters: (number) — No description in source JSDoc. Returns: } Generate Morton order traversal indices for a cubic chunk Parameters: (number) — Chunk dimension (e.g., 32) Returns: Morton ordered indices Get cached Morton indices for chunk size Parameters: (number) — No description in source JSDoc. Reorder voxel data from linear to Morton order Parameters: (Uint8Array Uint16Array) — Linear voxel data (number) — Chunk dimension Returns: Morton ordered data Reorder voxel data from Morton to linear order Parameters: (Uint8Array Uint16Array) — Morton ordered data (number) — Chunk dimension Returns: Linear data Build palette from voxel data Parameters: (Uint8Array Uint16Array) — No description in source JSDoc. Returns: } Calculate bits needed for palette size Parameters: (number) — No description in source JSDoc. Returns: Bits per index (1, 2, 4, 8, or 16) Compress voxels using palette compression Parameters: (Uint8Array Uint16Array) — Raw voxel data Returns: } Decompress palette compressed data Parameters: (number[]) — No description in source JSDoc. (number) — No description in source JSDoc. (Uint8Array) — No description in


palette compressed data Parameters: (number[]) — No description in source JSDoc. (number) — No description in source JSDoc. (Uint8Array) — No description in source JSDoc. (number) — Number of voxels RLE compress data (auto trigger: only encodes when beneficial) Format: Literal: byte (if byte != ESCAPE) Escape: ESCAPE, 0, ESCAPE (literal escape byte) Run: ESCAPE, count 3, value (run of count bytes) Parameters: (Uint8Array) — No description in source JSDoc. RLE decompress data Parameters: (Uint8Array) — No description in source JSDoc. Full compression pipeline for voxel chunk Pipeline: Morton → Palette → RLE Parameters: (Uint8Array) — Raw voxel data (linear order) (number) — Chunk dimension (e.g., 32) Returns: {{ Decompress voxel chunk Parameters: (Uint8Array) — No description in source JSDoc. (number) — No description in source JSDoc. Returns: Linear ordered voxel data Encode chunk modifications as delta Decode delta modifications Parameters: (Uint8Array) — No description in source JSDoc. Returns: } Create a compression statistics report Parameters: (Uint8Array) — No description in source JSDoc. (Uint8Array) — No description in source JSDoc. Test compression roundtrip Parameters: (Uint8Array) — No description in source JSDoc. (number) — No description in source JSDoc. <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


world/storage/WorldStorage.js
Classes
class WorldStorage
Functions
validateWorldMetadata(metadata)
parseWorldWalHeader(data)
parseWorldWal(data)
Constants
Re-exports
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes WorldStorage Main API for world persistence Method Signature Summary Set the ChunkManager reference for preview generation Generate and save world map preview image Start periodic file log flushing Stop file logging Log a save operation with detailed chunk info Log a load operation with detailed chunk info Flush log buffers to files Append text to a log file in the world folder Uses a write queue to prevent file contention from concurrent writes Clear log files (call when starting fresh debugging session) Request persistent storage to prevent browser from evicting data under storage pressure Check available storage quota and warn if low Check if there's enough storage space for a write Select storage folder (MUST be called from user gesture like button click) Call this to switch from OPFS to real file system storage Check if using real file system (not OPFS/IndexedDB) Get current storage location info Check if storage is fully ready for save/load operations This ensures all handles are valid and buffers are clear Get current initialization phase Wait for storage to be ready Mark storage as ready after all initialization is complete Should be called after handles are verified and buffers are clear Load world metadata Save world metadata Create an empty region file on disk Use this to pre create region files before adding chunks Enable RAM first mode preloads all regions into memory After this, chunk operations are instant (no disk I/O) Check if RAM first mode is enabled Start background save timer periodically flushes dirty regions to disk Force save all dirty regions to


instant (no disk I/O) Check if RAM first mode is enabled Start background save timer periodically flushes dirty regions to disk Force save all dirty regions to disk (call before exit) Create multiple empty region files Start WAL flush timer for periodic writes Stop WAL timers Write a chunk modification to WAL (call BEFORE actual save) Flush WAL buffer to disk (append only) Record a region mutation and its required durable WAL generation. Clear a dirty marker only if no newer mutation replaced its snapshot. Checkpoint: Apply all WAL entries to regions and truncate WAL Called during idle time or when WAL gets too large Recover from WAL after crash Replays any entries that weren't checkpointed Force WAL flush and checkpoint (call before shutdown) Start autosave timer Stop autosave timer Set logging verbosity Set player position for distance based chunk loading priority Chunks nearest to player will be loaded first Batch log helper accumulates logs and flushes periodically Flush accumulated logs Queue chunk for batched save Flush all queued saves at once Queue a chunk modification for idle based saving Call this when player damages/modifies terrain Reset the idle flush timer Flush all queued modifications to disk Called automatically when idle detected Force flush all modifications immediately Call this before closing/unloading Save chunk to storage (immediate use queueSave for batching) Load chunk from storage Check if chunk exists in storage Delete chunk from storage Mark chunk as dirty (needs saving) Load chunk if exists, otherwise generate and save it This is the PRIMARY method for getting chunks ensures no duplicate generation Batch load or generate multiple chunks More efficient than calling loadOrGenerate individually Chunks are sorted by distance from player


duplicate generation Batch load or generate multiple chunks More efficient than calling loadOrGenerate individually Chunks are sorted by distance from player position (nearest first) Check if chunk needs generation (doesn't exist in storage) Use this to avoid generating chunks that already exist Save a single region immediately Set a chunk to trace for debugging load/save issues Ensure region is loaded from disk Uses loadingRegions Map to prevent race conditions where multiple chunks request the same region simultaneously before it's loaded Actually load region from disk (internal helper) Schedule a deferred save (non blocking, runs during idle time) Saves ONE region per idle callback to prevent frame stalls Save dirt


world/storage/index.js
Re-exports
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Re exports , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


world/streaming/AdaptiveChunkBudget.js
Classes
class AdaptiveChunkBudget
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes AdaptiveChunkBudget.js Self optimizing chunk memory management Uses PID style control with EMA smoothing for smooth, responsive adaptation. Based on game engine best practices for adaptive performance. Method Signature Summary Set limits based on GPU page allocator's detected VRAM Call this after GPUPageAllocator.init() completes Set limits based on GPU buffer pool (the actual mesh buffer allocator) This is more accurate than page allocator since it tracks real mesh memory Get VRAM based job limits for ChunkJobCoordinator Scales with detected VRAM: 4GB=base, 8GB=2x, 12GB=3x Check if we should stop loading chunks due to memory pressure Adapt chunk limit based on current VRAM usage Call this every frame internally rate limited Record frame metrics call every frame Uses EMA for smooth, responsive tracking Get current limits call when checking chunk counts Force immediate reduction (emergency) Get debug info <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


world/streaming/ChunkHistory.js
Classes
class HistoryManager
Re-exports
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes HistoryManager Global history management Method Signature Summary Get or create history for chunk Record voxel change Record entity spawn Record entity despawn Undo last operation in chunk Redo operation in chunk Rollback chunk to timestamp Create snapshot for chunk Prune old history Clear history for chunk Get total memory usage Get statistics Re exports , , , , , , , , , , , <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Generate chunk key Parse chunk key Get Morton code for chunk coordinates Update player velocity for predictive loading Get predicted player position for lookahead loading Calculate priority with velocity weighting Chunks in player's path get higher priority Check if chunk should be loaded using hysteresis Prevents thrashing at boundary distances Check if a chunk can be claimed for loading Try to claim a chunk for loading (atomic operation) Batch claim multiple chunks Update job state Mark a job as complete Cancel a job Cancel all jobs from a source Release a completed chunk (allow it to be loaded again, e.g., after unload) Check if chunk is being worked on Check if chunk is completed Get job state Get available slots for a source Get chunks that are not claimed by anyone and need loading Useful for load balancing between systems Prune stale jobs and distant completed chunks Per frame update Set limit for a source Get statistics Clear all state Load configuration from engine.cfg Get eviction candidates sorted by distance (furthest first) Uses max distance eviction instead of LRU for better spatial locality Evict chunks to free memory, prioritizing furthest chunks Combines distance with recency for optimal eviction Check if memory pressure requires eviction Debug: Get all active jobs Get comprehensive debug info for streaming visualization overlay Format debug info as multi line string for HUD display Compute visible chunks using BFS through open chunk faces (portal culling) Uses faceOpenness bits to traverse through connected air spaces Get


for HUD display Compute visible chunks using BFS through open chunk faces (portal culling) Uses faceOpenness bits to traverse through connected air spaces Get visibility based priority boost for a chunk Returns higher priority for chunks reachable through open faces Get chunks in Morton order within a bounding box Uses Z order curve for cache friendly iteration Functions Encode 3D coordinates to Morton code (Z order curve) Preserves spatial locality for cache friendly iteration Parameters: (number) — X coordinate (0 to 1023) (number) — Y coordinate (0 to 1023) (number) — Z coordinate (0 to 1023) Returns: Morton code Decode Morton code back to 3D coordinates Parameters: (number) — Morton code Returns: } BIGMIN optimization: Find next Morton code inside query box Skips irrelevant ranges when iterating Morton ordered data Parameters: (number) — Current Morton code (number) — Min corner Morton code (number) — Max corner Morton code Returns: Next valid Morton code or 1 if none Constants — ChunkJobCoordinator.js Central Job Assignment for Chunk Loading Prevents duplicate chunk loads across multiple systems: PriorityChunkLoader ChunkStreaming ChunkStreamingCompute ChunkManager.updateStreaming Single source of truth for chunk job state. <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


world/streaming/ChunkLoadingZone.js
Classes
class ChunkLoadingZone
Constants
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes ChunkLoadingZone Manages player movement boundaries Method Signature Summary Update player position and check zones Check if player can move to position Get zone state at chunk position Check if all neighbors within radius are loaded Mark chunk as loaded Mark chunk as loading Mark chunk as pending Mark chunk as unloaded Get corrected position that respects barriers Get distance to nearest barrier Get all chunks in each zone around player Normalize direction vector Clear all chunk tracking Get stats Load configuration from engine.cfg section Constants — ChunkLoadingZone.js Virtual Buffer Wall System Prevents players from advancing past unloaded terrain. Creates an invisible barrier at the edge of generated chunks. Benefits: Players never see unloaded terrain Prevents falling through world Smooth loading experience Configurable buffer distance Zones: SAFE: Fully loaded, player can move freely BUFFER: Loading in progress, soft warning BARRIER: Not yet loaded, cannot pass <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


chunkSeamSeededStructureHash3D(x, y, z, seed)

chunkSeamChunkSeed3D(cx, cy, cz, seed = 0)

chunkSeamPositionSeed3D(x, y, z, seed = 0)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Initialize with external systems Register default structure generators Set the generation phase for a chunk Get the generation phase for a chunk Check if chunk has reached at least the given phase Check if all 6 face neighbors have reached the given phase Returns true if neighbor doesn't exist (will remesh when it loads) Check if chunk can be meshed (neighbors ready) NOTE: We now always allow meshing gaps are worse than seam artifacts Chunks will remesh when neighbors load to fix any edge issues Calculate all structure starts for a chunk This is deterministic based on seed + chunk coords Calculate deterministic tree positions for a chunk Get all structure references that may affect a chunk This checks the origin chunk AND all nearby chunks Place all structures that affect a chunk Call this during the STRUCTURES phase Generate tree voxels for a chunk from a structure reference Add a pending block for a chunk that may not exist yet Apply pending blocks to a chunk Generate deterministic seed for a chunk Generate deterministic seed for a world position Clear references for a chunk (when unloading) Get stats for debugging Functions Constants <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


world/streaming/ChunkStreaming.js
Classes
class ChunkStreaming
Re-exports
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Begin frame reset budget Queue a chunk for loading Calculate priority for a chunk Process streaming queue for this frame Cancel pending load Clear all pending loads Get statistics Load configuration from engine.cfg section Re exports , , <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Initialize the GPU streaming system Enable advanced terrain generation using GPUWorldGenerator Provides biomes, climate, caves, structures, erosion aware terrain Set world seed for terrain generation Find chunks to unload based on distance (GPU accelerated) Generate terrain for a chunk on GPU Batch generate terrain for multiple chunks 8 chunks per GPU dispatch Uses GPUWorldGenerator if advanced mode is enabled, otherwise basic terrain. Advanced terrain generation using GPUWorldGenerator Provides biomes, climate, caves, structures, erosion aware terrain Destroy all GPU resources <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


world/streaming/ChunkUpdater.js
Classes
class ChunkUpdater
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes ChunkUpdater.js Block Update Queue Manager Manages block updates with: Rate limited updates per frame Propagation for lighting/physics Lazy update batching Update coalescing Method Signature Summary Queue a block update Coalesce nearby updates Flush coalesced updates for a chunk Process updates for this frame Get statistics Clear all pending updates Load configuration from engine.cfg section <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


world/streaming/ChunkWorkerPool.js
Classes
class ChunkWorkerPool
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes ChunkWorkerPool Manages a pool of Web Workers Method Signature Summary Initialize the worker pool Send message to specific worker Handle worker message Handle worker error Track task completion time Get an available worker index Process task queue Queue a task Generate terrain for a chunk Generate mesh for voxel data Generate terrain and mesh in one call Batch generate multiple chunks Get queue length Get busy worker count Check if pool is idle Update seed for all workers Get stats Load configuration from engine.cfg section Terminate all workers <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


world/streaming/MovementPredictor.js
Classes
class MovementPredictor
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes MovementPredictor Predicts player movement for chunk prefetch Method Signature Summary Update with new player position Track prediction accuracy over time Get predicted chunk coordinates Check if prediction is active (player moving fast enough) Calculate priority boost for a chunk based on prediction Uses cascaded prediction tiers for different time horizons Get chunks that should be prioritized based on prediction Get current velocity Get movement direction (normalized) Get stats Reset state Load configuration from engine.cfg section <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


world/streaming/PriorityChunkLoader.js
Classes
class PriorityChunkLoader
Constants
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: PriorityChunkLoader.js Distance Based Chunk Loading Loads chunks in order from closest to player outward. Uses spiral/ring pattern for optimal loading experience. Benefits: Player sees nearby terrain first Smooth loading experience Efficient resource usage Integrates with ChunkLoadingZone Patterns: SPIRAL: Classic spiral from center RINGS: Concentric rings outward DIRECTIONAL: Prioritize direction player is facing Classes PriorityChunkLoader Manages chunk load ordering Method Signature Summary Rebuild the precomputed load orders Set load radius and rebuild orders Update player position and rebuild queues Prune queues remove chunks that are now too far away Called every position update to cancel unnecessary loads Re sort queues by distance without full rebuild More efficient when player moves within same chunk Rebuild load/mesh/unload queues based on player position Get load order based on current pattern Get directional load order (prioritize facing direction) Calculate priority for a chunk offset Calculate LOD level for a chunk based on distance Update FOV angle (call when camera FOV changes) Update FPS and adjust loading limits adaptively Call this every frame with current delta time or FPS Adjust loading limits based on current FPS Get current adaptive loads per frame Get current adaptive meshes per frame Process queues call once per frame Track load time for averaging Get chunks that should be loaded but aren't Get chunks waiting to be meshed Check if a specific chunk is loaded Check if a specific chunk is meshed Manually mark a chunk state Configure LOD distance thresholds Get current LOD for a chunk Get loading progress (0 1) Get visual representation of load state Get


mark a chunk state Configure LOD distance thresholds Get current LOD for a chunk Get loading progress (0 1) Get visual representation of load state Get stats Clear all state Load configuration from engine.cfg section Constants <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes ProgressiveChunkLoader Manages progressive LOD loading Method Signature Summary Set callback functions Update camera state Register a chunk for progressive loading Unregister a chunk Update all chunk distances and queue refinements Check if a point is visible (basic frustum check) Build priority sorted refinement queue Process top refinements from queue Refine a chunk to the next level Process chunks that can be downgraded (moved away) Force immediate refinement of a chunk to target level Get current level for a chunk Get all sub meshes for a chunk at its current level Get statistics Re exports , , <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


world/streaming/index.js
Re-exports
Notes & Examples
World Streaming & Scenes

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Re exports , , , , , , , , , , , , , , , , , , , , , , <! HUMAN NOTES Notes & Examples World Streaming & Scenes The world system manages scene graphs, asset streaming, and level transitions. Scenes are entity hierarchies with spatial indexing (BVH) for fast culling and raycasts. Worlds stream assets asynchronously with priority based on distance and visibility. Example: Scene graph and streaming See also: Engine Overview


Rendering Pipeline

State-First representation capability floors

GPU-driven multi-pass rendering — frame structure, lighting, shader/debug modes, mesh rendering, half-res particle compositing, shadow atlas, and post-processing. Rendering Pipeline GPU driven rendering with meshes, lights, materials, shader modes, and multi pass compositing. All rendering is built on the Virtual GPU (vGPU) abstraction. Frame structure A typical frame (from ) follows this pass order: Scene debug modes (steps 4, 8) skip all post processing (steps 9–14) so the debug output is clean and unmodified. Lighting system handles all lighting via a single GPU uniform buffer (832 bytes). It supports sun (directional), ambient, and dynamic point lights. Property Default Description FROM light direction (steep overhead) Warm white sun Sun brightness multiplier Cool ambient fill Ambient brightness Final multiplier on all lighting Direction convention: is the FROM light direction. The shader negates it internally ( ). SDF/Cloth/Rope renderers receive the already negated TO light direction from the Viewport. Shader modes Four debug modes controlled by and : Mode lightingMode debugMode Output Standard Full sun + ambient + dynamic lights Unlit Albedo color only, no lighting Normals World space normals ( ) Depth Distance based depth gradient Particle lighting integration Particles interact with lighting three ways: Receive — particles sample sun + ambient from frame uniforms. Emit — hot particles (fire/plasma) become dynamic point lights via . Shadow/tint — smoke dims sunlight ( ); fire tints it warm ( ). Mesh rendering Entity meshes are rendered by , which reads from ECS and components. Each entity gets a per object uniform buffer (its model matrix) and a bind group linking the uniform to the shader. State First representation capability floors State First semantic


Rendering Pipeline

object uniform buffer (its model matrix) and a bind group linking the uniform to the shader. State First representation capability floors State First semantic sources may set on an entity when their renderer does not implement every generic representation. The planner still returns for a hidden or out of frustum entity, but a visible entity cannot fall below its declared floor. This prevents a quality profile from asking an integration to draw a , , or when only a faithful mesh renderer exists. Actuated City Drive declares for its 13 rigged vehicles. State First continues to cull hidden cars, while every visible car uses the same body, glass, lights, wheels, steering, and suspension renderer as Native mode. It does not substitute chassis sized boxes. (Sources: , .) Half resolution particle compositing Particles render at half resolution for performance, then composite onto the main scene: 1. The SDF shader outputs — non premultiplied. 2. The SDF pipeline renders into a half res texture with alpha blend. 3. The half res texture starts cleared to ; after alpha blend, RGB = lit × alpha (premultiplied). 4. The composite pass uses fully additive blend ( ) onto the scene. Implication: with additive composite, particles can only brighten the scene, never darken it. Fire needs very low alpha (0.03–0.08) plus bright emission (2–5×) to avoid saturating the half res buffer into a solid red wall. Grid renderer & shadow atlas draws the ground plane as a solid fill (alpha 0.85) with sun + ambient lighting, receiving lighting from via each frame. provides unified shadow rendering: all casters (entities, ropes, particles) render into a shared 4096² depth texture, then shadows are composited per category with independent PCF, bias, and strength. Caster categories: ( ), ( shadow pass), (


Rendering Pipeline

into a shared 4096² depth texture, then shadows are composited per category with independent PCF, bias, and strength. Caster categories: ( ), ( shadow pass), ( , round billboard shadows). Debug visualization A two tier debug system, accessible via the editor's view mode dropdown. Scene wide modes (post process) read the actual hardware depth buffer (meshes + ropes) and composite with a particle depth color texture, via : Mode Technique Output Depth Buffer Linearize + particle depth composite Grayscale: near=white, far=black Normal Maps Finite difference world normals from composite depth RGB = XYZ world space normals Why two sources? Particles use (transparent billboards), so they never appear in the hardware depth


Shaders & WGSL

The modular WGSL shader system — organization, ShaderComposer, the WGSL preprocessor, shader reflection, compilation via vGPU, and common patterns. Shaders & WGSL A modular WGSL shader system with composition, preprocessing, a shared library of reusable modules, and the for assembling complex shaders from parts. Shader organization ShaderComposer assembles complex shaders from a library of reusable WGSL modules. Modules are registered by name and injected at compile time, avoiding duplicate functions (e.g. lighting) across shaders. The composer resolves the to inject WGSL function definitions before your main code. WGSL preprocessor supports C style directives before compilation: Shader reflection parses WGSL source to extract bind group layouts, struct definitions, and entry points, enabling automatic pipeline layout generation from shader source. Compilation via vGPU All shader compilation goes through (see Virtual GPU): Important: use instead of in compute shaders and non uniform control flow — WebGPU validation rejects outside uniform control flow. Common pattern: billboard circle clipping Particle debug shaders render billboard quads with vertices .. . The fragment shader must discard corners to produce circular particles: Without the hard clip, still passes the 0.01 threshold, making particles appear as squares.


Virtual GPU (vGPU)

vgpu.pipeline — render & compute pipelines

The unified GPU abstraction that powers every engine system — automatic caching, pooling, and resource management over raw WebGPU, via six core managers plus advanced subsystems. Virtual GPU (vGPU) is the unified GPU abstraction layer that powers every system in the engine. It wraps raw WebGPU with automatic caching, pooling, and resource management — turning 20 lines of boilerplate into one. This is the most important concept in the engine's GPU layer. Every renderer, simulation system, and compute shader goes through vGPU. It is the user space GPU service the OS mediates (see GPU Device Sharing). Source: . Quick start No flags, no bind group layout descriptors, no pipeline layout boilerplate — vGPU handles it. Initialization Three ways to get a vGPU instance: The 6 core managers Every vGPU instance exposes six manager objects — the primary API you'll use daily. — buffer management Create, write, and manage GPU buffers with automatic usage flag resolution and optional pooling. Usage strings map to WebGPU flags: String WebGPU flags Combined flags (pipe separated) — layouts & bind groups Define named layouts and create bind groups with caching and deduplication. Binding type strings: , , , , , . Visibility strings are pipe separated stage names: , , , . — shader compilation Compile WGSL with automatic caching, preprocessor defines, and hot reload support. — render & compute pipelines Create and cache pipelines with simplified blend state resolution. Blend strings: (opaque), (srcAlpha, oneMinusSrcAlpha), (one, one), (one, oneMinusSrcAlpha). Automatic caching: pipelines are keyed by their full configuration. Calling twice with identical options returns the cached pipeline instantly — zero GPU work. — textures & samplers — command encoding Advanced subsystems Beyond the six


Virtual GPU (vGPU)

twice with identical options returns the cached pipeline instantly — zero GPU work. — textures & samplers — command encoding Advanced subsystems Beyond the six core managers, vGPU includes 20+ specialized modules as properties on the instance. Enhancement modules: (labels/markers), (streaming uploads), (GPU timing), (work scheduling), (render bundles), (mipmap gen), (occlusion/stats), (async pre compile). Resource management: (non blocking GPU→CPU), (usage tracking/budgets), (material bind groups), (resource transitions), (dynamic resolution), (draw calls, triangles). Advanced rendering (lazy initialized via factory methods): (pass scheduling + resource aliasing), (GPU driven indirect draws), (hierarchical Z occlusion), (texture/mesh streaming), (immediate mode debug shapes). Compute & shader utilities: (reduction/scan/fill/copy), (WGSL macros/includes), (shader introspection), , , (timeline sync). Common patterns Simple compute shader Frame lifecycle & stats Before & after Creating a particle compute pipeline takes 68 lines of raw WebGPU vs 12 with vGPU — about 82% less code , plus automatic caching, pooling, memory tracking, and debug labels for free. Device properties & cleanup


FAQ & Troubleshooting

FAQ & Troubleshooting
General
WebGPU OS
Documentation viewers
Engine / AGI

Common questions and fixes — Node.js, HTTP serving, browser support, and verifying WebGPU availability. FAQ & Troubleshooting Common questions and fixes. If something here is wrong or missing, follow the Contribution Workflow to update it. General Do I need Node.js or npm? No. The entire stack and the documentation tooling are pure browser + Python. There is no build step required to run anything. Why does everything need an HTTP server? Browsers block and ES module from URLs. Serve over HTTP with and use . Which browser do I need? Use a current browser release that exposes WebGPU on your operating system and GPU. Browser version alone is not proof of capability. Verify that exists and that returns an adapter. Update the browser and GPU driver if either check fails. Does the WebGPU OS Companion enable WebGPU or compatibility mode? No. Compatibility mode belongs to the browser's WebGPU implementation. The optional Companion extension supplies approved browser and provider integrations for WebGPU OS; it cannot make an unsupported GPU/browser combination support WebGPU. The engine and Playground run without the Companion when browser WebGPU is available. WebGPU OS The boot loader is stuck or shows "Boot failed". Open the console. The boot sequence logs each phase. Common causes: WebGPU unavailable, shell root elements missing from the DOM, or an app/mod discovery error (these are logged as warnings and do not block boot). How do I see security posture? Boot with or set . This runs the syscall guard audit, capability map drift check, and Security Doctor, logging results. See Security & Trust Model. Where do apps live, and why aren't they bundled? Apps are discovered and fetched at runtime from (and mods from ). They are intentionally not bundled so they can be added/updated


FAQ & Troubleshooting

and why aren't they bundled? Apps are discovered and fetched at runtime from (and mods from ). They are intentionally not bundled so they can be added/updated without rebuilding the OS. Documentation viewers The viewer shows "Could not load navigation". You opened the viewer from . Serve over HTTP. Code blocks are unstyled and Mermaid diagrams don't render. The vendored libraries are missing. Run . The viewer falls back to a built in Markdown renderer so pages still load. A reference page says "(run extract api.py)" in the sidebar. The API reference hasn't been generated yet. Run then . Search returns nothing / only titles. The search index isn't built. Run to create . Without it, the viewer falls back to title only search. Engine / AGI AGI training won't progress. Confirm WebGPU support, verify 60 FPS physics, and review reward weights. See the Training Guide. Performance is poor. Close other tabs, reduce buffer sizes, disable debug visualizations, and check GPU utilization.


Glossary

Glossary
Stack & runtime
GPU
MorphField
OS concepts
ECS
AGI / ML
Navi
Realm Network

Definitions of the core terms used across the docs — stack and runtime, GPU concepts, kernel, shell, and more. Glossary Terms used throughout this documentation. Each term is defined once here and linked from the pages that use it. Stack & runtime Engine — the WebGPU runtime in : GPU device, frame graph, ECS, rendering, simulation, networking, audio. Plauna — the hybrid DOM/GPU UI framework in (panels, widgets, surfaces, theming). AGI — the reinforcement learning rigging system in ("parasite rig"), plus a WebGPU tensor library and AGI Studio. WebGPU OS — the composition layer in : compositor, shell, kernel, package system, app runtime. Kernel — the OS's privileged core ( ): syscalls, scheduling, GPU mediation, trust, permissions. Shell — the desktop UI ( ): , , , windows, notifications. GPU WebGPU — the browser GPU API the whole stack targets. WGSL — WebGPU Shading Language; the portable shader format used across tiers. VGPU (Virtual GPU) — the engine's abstraction over the raw WebGPU device ( ) that adds multi queue, bind group management, streaming, and resource tracking. GPU device broker — the kernel service ( ) that shares the single WebGPU device across all apps. device lost — a WebGPU event raised when the GPU context is lost; the kernel fans this out to apps for recovery. MorphField MorphField — the Engine's additive semantic field renderer and compiler under . Nexel — a public semantic scene element that describes source geometry or media, material, motion, collision, simulation, and quality intent without selecting a GPU backend. Fieldlet — MorphField's private compiled execution record. A Fieldlet belongs to one of four stable execution families and exposes a mask of supported typed queries. Certified query — a query backed by compiler derived conservative


Glossary

to one of four stable execution families and exposes a mask of supported typed queries. Certified query — a query backed by compiler derived conservative bounds or error records. Authored data cannot declare itself certified. OS concepts App — a plug in module discovered at runtime from , described by a manifest. Manifest — the JSON describing an app: id, entry, permissions, capabilities (see App Manifest Spec). Package ( ) — an installable, signed, encrypted container (v2 = encrypted ZIP + public envelope). Mod — a runtime extension discovered from via . Syscall — a kernel mediated operation exposed to apps ( ). Capability — a permission token gating a syscall or resource (see ). Trust ring / ring 0 roots — the trust hierarchy; ring 0 roots live in . Provenance — verifiable origin/lineage of a package ( , ). Surface — a renderable region (DOM, DOM+GPU, or pure GPU) managed by /Plauna. Workspace / Panel — Plauna's dockable window units; every OS window is a Plauna panel. ECS ECS — Entity Component System; the engine's state model. Entity — an id; Component — data attached to an entity; System — logic over components. World — a container of entities/components/systems (the engine and Plauna each have worlds). AGI / ML PPO — Proximal Policy Optimization, the RL algorithm used to train the rig. Tensor library — the custom WebGPU tensor implementation in . Curriculum — the staged training progression ( ). Ragdoll — the physics body the rig learns to control ( ). Observation / Action space — the RL input (12D) and output (17D) vectors. Navi Navi — a persistent OS principal whose identity, authority, memory, and lineage remain independent from any model, provider, session, device, or body. Continuity Kernel — the kernel owned Navi service that protects persistent identity and


Glossary

remain independent from any model, provider, session, device, or body. Continuity Kernel — the kernel owned Navi service that protects persistent identity and operational signing authority. Covenant — the signed operator Navi contract that bounds observation, memory, autonomy, disclosure, approvals, transfer, recovery, and separation. Cognition Fabric — the model neutral router that selects replaceable remote or local cognition engines while preserving task continuity. Faculty — a signed, versioned, inspectable ability module with typed inputs and outputs, declared permissions, tools, models, costs, tests, and failure behavior. Causal Memory Weave — append only evidence bearing Navi memory and its derived


Install & Run

1. Vendor the viewer's front-end libs locally (offline, no CDN)

2. Generate the per-symbol API reference from source

3. Build the search index and validate navigation

Prerequisites (a WebGPU browser and Python — no Node.js) and how to serve the stack and these docs locally without a compile step. Install & Run This page covers prerequisites and how to serve the stack and these docs locally. Everything runs in the browser — there is no compile step. Prerequisites A current WebGPU capable browser — support depends on the browser release, operating system, GPU, and driver. Confirm that exists and that returns an adapter. Localhost is treated as a secure context; deployed sites must use HTTPS. Python 3.x — used only to serve files over HTTP and to run the docs tooling. There is no Node.js dependency . A dedicated GPU is recommended for the engine, AGI training, and GPU heavy apps. Platform downloads and the optional network service Platform downloads: BTSpaniel/particlerealms.engine publishes browser ready distribution artifacts, including the compressed bundles. It is the public download repository, not the source tree used to generate this API reference. Optional master server source: BTSpaniel/particlerealms.engine master server is a separate discovery, admission, encrypted signaling, TURN, and trusted node service. It is never gameplay authority and is not required to run the engine or Playground locally. Serve the project The repository ships a static HTTP server. From the repository root ( ): Then open the relevant entry point in a WebGPU browser: WebGPU OS — Editor — AGI Studio — These docs (zero build viewer) — Why a server? The viewers and the OS load Markdown, JSON, and ES modules with / , which browsers block from URLs. Always serve over HTTP. WebGPU compatibility and the Companion are different WebGPU compatibility mode is a browser/adapter capability intended for systems backed by older native graphics APIs. When available,


Install & Run

Companion are different WebGPU compatibility mode is a browser/adapter capability intended for systems backed by older native graphics APIs. When available, it still appears through the browser's WebGPU interfaces. It does not come from an extension and may expose lower limits or fewer optional features, so rely on adapter, feature, and limit checks instead of a browser name test. The WebGPU OS Companion Chrome extension is an optional bridge for approved browser controls, provider connectivity, and other OS integrations. It cannot add WebGPU to an unsupported browser, GPU, or driver. The engine and Playground use browser WebGPU directly; install the Companion only for the OS features that explicitly request it. Set up the documentation tooling The docs are plain Markdown, but a few Python helpers build derived artifacts. From : After step 1, open to browse. Optional: MkDocs Material site For the polished static site experience: See Contribution Workflow for the full build/lint pipeline. Troubleshooting Blank page / CORS errors — you opened a URL. Serve over HTTP instead. "WebGPU not available" — update your browser or enable WebGPU; verify with in the console. Viewer renders unstyled code / no diagrams — run . The viewer still works via its built in fallback, but without syntax highlighting or Mermaid. More in FAQ & Troubleshooting.


Overview

What the WebGPU OS stack is, the five subsystems (engine, editor, Plauna, AGI, WebGPU OS), who each part is for, and where to go next. Overview This page explains what the stack is, who each part is for, and where to go next. Read it first if you are new to the project. The five subsystems Subsystem What it is Audience Source Engine Browser resident WebGPU runtime: GPU device, frame graph, ECS, rendering, simulation, networking, audio. Engine/graphics/sim developers Editor Scene and asset authoring IDE built on the engine. Content creators, tools developers Plauna Hybrid DOM/GPU UI framework and workbench (panels, widgets, surfaces, theming). UI/app developers AGI Reinforcement learning "parasite rig" that learns to control humanoid ragdolls, plus a WebGPU tensor library and AGI Studio. ML/animation developers WebGPU OS Composition glue: a GPU first compositor, shell, kernel, package system, and app runtime that turns the above into a desktop like OS in a browser tab. App/package developers, end users Design principles (shared across the stack) Pure browser runtime — no Node.js dependency, no build step required to run. GPU first — heavy work runs on WebGPU compute; a single GPU device is shared. ECS driven — state lives in components. Modular — each subsystem is independent and testable, consumed by the next as a library. Composition, not forking — consumes , , , ; fixes go upstream, not into the glue layer. Who should read what End users of the OS: WebGPU OS Overview → App Catalog. App / package developers : WebGPU OS Architecture, the kernel API Reference , and the Security & Trust Model. Engine / UI / ML developers : the relevant subsystem Overview + Architecture + API Reference . Documentation contributors : Docs Style Guide and Contribution Workflow. Next steps 1.


Overview

: the relevant subsystem Overview + Architecture + API Reference . Documentation contributors : Docs Style Guide and Contribution Workflow. Next steps 1. Install & Run — get the stack serving locally. 2. Quickstart — boot the OS and open your first app. 3. Architecture Overview — the big picture. 4. Glossary — terms used throughout these docs.


Quickstart

Quickstart
1. Boot the OS
then browse to:
http://127.0.0.1:9001/webgpu-os/
2. Boot programmatically (embedding)
3. Open an app
4. Run a security self-audit (optional)
Where to go next

Boot the WebGPU OS and open your first app after installing, using the bundled local Python HTTP server. Quickstart This guide boots the WebGPU OS and opens an app. It assumes you have completed Install & Run. 1. Boot the OS Serve the repo and open the OS: The boot loader shows progress ( ). When it finishes, is ready and the desktop appears. 2. Boot programmatically (embedding) exports a side effect free boot function you can call yourself: The thin simply calls this on for plain ES module usage. 3. Open an app Apps are discovered at runtime from (see ). From the desktop, open the Start Menu and launch any app — for example Terminal , Files , or Settings . The full list is in the App Catalog. 4. Run a security self audit (optional) Append to the URL (or set ) to run the syscall guard audit, capability map drift check, and Security Doctor on boot. Results are logged to the console. See the Security & Trust Model. Where to go next Build an app/package: WebGPU OS Architecture. Understand boot internals: Boot Sequence. Understand GPU sharing across apps: GPU Device Sharing.


Capabilities — What You Can Build

Full platform: Engine + Editor + Plauna + AGI Core

A routing/decision map for the whole stack — which subsystem to use for each goal, public API maps (engine, Plauna, AGI), rendering/physics recipes, bundle targets, the editor module map, and AI editing rules. Capabilities — What You Can Build What the stack can actually build: browser native WebGPU games, simulation sandboxes, tools, editors, UI systems, AI training experiments, and deployable single file runtimes. Use this page to pick the right subsystem before writing code. Decision map Goal Use Primary files Docs WebGPU buffer/pipeline/compute work vGPU vGPU Game state, entities, components ECS , ECS v2 Visual frame, render passes, debug views Rendering Rendering Particles, fire, fluid, matter demos Particle System , Particles Menus, HUDs, app panels Plauna Plauna Training, observations, rewards, neural agents AGI Core AGI Scene authoring and inspection Editor , Editor New app / prototype Template , Template starter Primary entry points: engine → · compiled global → · Plauna → · AGI → · editor → · template → . What you can build GPU simulation demos — particles, fluids, boids, wave optics, ray/path tracing, reaction diffusion, sand, thermal systems, terrain, state first rasterization, diagnostic scenes. Living worlds — ECS driven worlds with items, rules, events, saves, AI state, perception, laws, factions, social graphs, and procedural simulation layers. Physics sandboxes — rigid bodies, GPU physics, PBD ragdolls, active rig controllers, cloth, rope, fluids, soft body hooks, constraints, collision debug, PhysX backed editor workflows. Visual tools — browser editor workflows with viewport, inspector, hierarchy, world settings, gizmos, particles, audio patches, materials, project saves, runtime debug modes. Core engine runtime The engine exports a single public API


Capabilities — What You Can Build

world settings, gizmos, particles, audio patches, materials, project saves, runtime debug modes. Core engine runtime The engine exports a single public API through (source mode) or (compiled bundle mode). Public engine API map Category Common exports Use for Version , , , Runtime identity, diagnostics, release banners Math , , , , Transforms, camera math, simulation utilities ECS , , , Entity state and system stepping Gameplay , , , World rules, events, perception, AI state Saves , , Local persistence and schema aware saves Animation , , , Motion matching, animation datasets, rig features GPU , , , WebGPU device, buffers, shaders, pipelines, compute Compiled runtime pattern: Rendering Classic scene rendering plus experimental research paths (see Rendering): Scene rendering — entities, instancing, mesh segments, materials, lighting, shadows, debug visualizations. Post processing — tonemapping, bloom, temporal reconstruction, FSR/TSR style upscaling, depth/normal debug passes. Path tracing — engine native path tracing foundation, ReSTIR GI experiments, guide buffers, temporal accumulation. Spectral rendering — coherent wave optics pass (double slit demo). State first rendering — CPU/GPU visibility, representation selection, temporal visibility, cluster expansion, GPU culling. Proxy geometry — ray portal proxy with TLAS/BLAS, SDF, billboard, impostor, octahedral cache tiers. Need Start with Notes Normal 3D scene + ECS transforms Use existing passes before adding a new renderer Experimental GI/path tracing (via EngineBootstrap) Playground demos consume it through compiled Many simple visible objects State first rasterizer/culler APIs Use representation selection + GPU culling Debug visual output Scene debug visualizer + editor view modes Prefer debug modes over console only


Capabilities — What You Can Build

APIs Use representation selection + GPU culling Debug visual output Scene debug visualizer + editor view modes Prefer debug modes over console only diagnosis Particles, matter, and fluids Built for large GPU workloads and material behavior, not just sprites (see Particles): high count GPU particles (compaction, sorting, billboards, trails, decals, bonds, adaptive quality); matter states (solid/liquid/gas/plasma); thermal behavior (temperature, heat transfer, phase transitions); SPH fluids + volume fields; interaction (SDF collision, flocking/boids, terrain/sandbox demos). Physics and active bodies Engine physics modules + PhysX integration + active ragdoll architecture (see Physics and GPU Phys


Engine Stack Usage Guide

Engine Stack Usage Guide
1. Which build should you use?
Engine-only bundle
Full platform bundle
Ad-hoc bundle
2. Runtime loading pattern
3. Minimal Engine app
4. WebGPU initialization pattern
5. ECS conventions
6. Rendering conventions
7. Particle system usage
8. Plauna UI usage
9. AGI Core usage
10. Editor workflow
11. Template folder usage
12. Project starter template
13. What to build first
14. Release checklist
15. Design rules for this repository

The practical "how do I build with this?" guide — choosing a bundle, runtime loading, minimal apps, ECS/render/particle conventions, Plauna, AGI Core, the editor, and the release checklist. Engine Stack Usage Guide Version targets: Engine , Editor , Plauna , AGI Core . This guide is the practical "how do I build with this?" document for the full stack: Particle Engine : WebGPU, ECS, rendering, particles, physics, audio, saves, gameplay systems. Plauna : retained mode UI runtime for menus, HUDs, tools, dashboards, and editor like panels. AGI Core : training/control utilities for neural, ragdoll, motion, and simulation agents. Editor : visual scene/project tool for authoring, inspecting, testing, and exporting. Template : a copyable starter app at . Use this guide when starting a new game, demo, tool, or prototype. 1. Which build should you use? Engine only bundle Use this for public demos, playground content, engine examples, and small games that do not need AGI/Plauna/editor APIs. Output identity: Full platform bundle Use this when you want Engine + Editor + Plauna + AGI Core in one runtime. This adds: Ad hoc bundle Use this for local experiments where you want Engine plus one optional layer. 2. Runtime loading pattern For source mode development, import from . For generated release, Playground, Editor, and WebGPU OS pages, await the shared compressed runtime contract and use . writes the external tag with the exact gzip URL, decoded byte count, SHA 384 identity, asset base, and subsystem base. The loader expands , rejects size or integrity mismatches, executes the verified bytes from a CSP approved Blob URL, and resolves . Do not replace it with inline source execution or publish the oversized raw file. Rule: playground/release pages should use compiled APIs, not


Engine Stack Usage Guide

and resolves . Do not replace it with inline source execution or publish the oversized raw file. Rule: playground/release pages should use compiled APIs, not direct source imports. 3. Minimal Engine app This is the smallest pattern for a browser app using EngineBootstrap. Recommended app layout: 4. WebGPU initialization pattern Use raw WebGPU only when a high level helper does not exist yet. Use a single long lived . Recreate size dependent textures on resize. Do not create pipelines every frame. 5. ECS conventions Use components as plain serializable data. System pattern: Recommended phases: Keep simulation state deterministic where possible. Keep DOM/UI state outside physics critical loops. 6. Rendering conventions For simple demos, render from compact state snapshots: For large worlds: Use dirty flags for transforms/materials/bounds. Use culling before upload. Prefer packed typed arrays over per entity object uploads. Use state first representation selection for many simple entities. Avoid GPU readback in the frame loop unless it is delayed/asynchronous. 7. Particle system usage Basic emitter data should be content driven. Good particle app structure: Rules: Keep presets in data modules. Keep GPU buffers owned by one system. Separate emitter authoring from simulation stepping. Add debug counters early: alive count, spawn count, upload bytes, frame ms. 8. Plauna UI usage Use Plauna when you need retained UI, themed panels, menus, HUDs, inspectors, or app shells. Source mode import: Bundle mode usage: Minimal Plauna mount: Recommended Plauna file layout: Plauna rules: Use Plauna for UI state, not physics state. Pass simulation snapshots into UI; do not let UI own simulation truth. Keep UI events as intents: , , , . Avoid creating/destroying large UI trees every frame.


Engine Stack Usage Guide

Pass simulation snapshots into UI; do not let UI own simulation truth. Keep UI events as intents: , , , . Avoid creating/destroying large UI trees every frame. 9. AGI Core usage Use AGI Core for training agents, observation builders, rewards, motion teachers, and neural control experiments. Source mode import: Bundle mode usage: Minimal training loop shape: AGI rules: Keep side effect free. Do not use as a bundle entry; it auto boots a DOM app. Keep observations explicit and versioned. Keep rewards readable and decomposed. Log training metrics every episode, not every frame. Avoid blocking GPU readback in training loops. 10. Editor workflow Use the editor for authoring, inspection, debugging, and visual iteration.


WebGPU OS Documentation

WebGPU OS Documentation
What is this stack?
Find your path
How this documentation is built
For AI agents
Accuracy & safety
Status

Unified, versioned home for the WebGPU OS stack — engine, editor, plauna, agi, and the OS itself. Plain Markdown, readable by AI agents and rendered for humans. WebGPU OS Documentation A unified, versioned home for the entire stack — the engine, the editor, the Plauna UI framework, the AGI rigging system, and the WebGPU OS that composes them all. This site is the single source of truth: plain Markdown that AI tools can read directly, rendered for humans through three viewers that all read the same files. New here? Start with Overview, then the Architecture Overview to see how the pieces fit. What is this stack? The project grew in layers. Each layer is independent and reusable, and the next one builds on it: See History & Evolution for the full story (engine → editor → plauna → agi → webgpu os). Find your path I want to use the OS — WebGPU OS Overview and the App Catalog. I'm building an app/package — WebGPU OS Architecture and the kernel/package API reference. I'm working on the renderer or simulation — Engine Overview. I'm building UI — Plauna Overview. I'm training the rig — AGI Overview and the Training Guide. I'm editing scenes/assets — Editor Overview. I'm writing docs — Docs Style Guide. How this documentation is built This folder is the source. Three viewers consume it: 1. Zero build HTML viewer ( ) — opens over , no build step. 2. MkDocs Material site ( ) — for a polished static site. 3. app inside WebGPU OS — reachable from the OS shell itself. Navigation, search, and reference indexes are generated by Python tools in (no Node). See Contribution Workflow. For AI agents If you are an AI assistant working with these docs, read first — it tells you where things live and the hard boundaries. A curated machine index is at (with full text in ), following the


WebGPU OS Documentation

working with these docs, read first — it tells you where things live and the hard boundaries. A curated machine index is at (with full text in ), following the llmstxt.org standard. Incremental consumers can stream bounded documentation chunks or source backed API modules and symbols, one JSON object per line. Conventions for keeping the docs AI and human safe are in AI & Accessibility. Accuracy & safety The per symbol API reference is machine extracted from source and can lag — verify against the cited source file before relying on it. Fix inaccuracies by improving JSDoc upstream, then regenerating. Documentation contains no secrets ; never paste keys or tokens into examples. Every page links to View source so you can check the original. Status This is the restructured documentation set (v0.1.0). Conceptual and structural docs are authored by hand; the per symbol API reference is generated by and enriched with hand written notes. See the Changelog.


Plauna Architecture

Plauna Architecture
Rendering pipeline
Core (plauna/core/)
Surfaces and the GPU bridge
Workspace (the window manager)
Text engine
Integration with the engine and editor
See also

How Plauna renders and manages UI — a UI ECS world reconciled to DOM and/or GPU surfaces through a dirty-tracking pipeline. Plauna Architecture How Plauna renders and manages UI. State lives in a UI ECS world; a visual tree is reconciled to DOM and/or GPU surfaces through a dirty tracking pipeline. Rendering pipeline Core ( ) — , the top level application object ( ). / — the retained UI tree. — UI state container. — binds state to the visual tree. — tracks what changed so only dirty regions re render. — renders the tree to DOM. / — view/surface registry and event system. — module self tests. Surfaces and the GPU bridge manages renderable surfaces (rect/warped, interactive, hit testable). bridges surfaces to the engine's VGPU, so GPU UI shares the single device. See GPU Device Sharing. Workspace (the window manager) provides , , , , , and . Every OS window is a Plauna panel — the OS shell ( ) builds its desktop/taskbar on top of this. (Source: .) Text engine measures and lays out text without the DOM (Pretext style), enabling GPU rendered text and accurate layout in non DOM surfaces. Public API: , , , . Integration with the engine and editor Bootstraps via ( , exposed as ). Uses the existing VGPU instance and ECS patterns — no separate device. Can enhance existing editor panels incrementally ( ). See also Plauna Overview — rendering modes and module map. WebGPU OS Architecture — how the shell consumes Plauna. Plauna API Reference .


Plauna Getting Started

Plauna Getting Started
Initialize
Measure text without the DOM
Create a GPU surface
Enhance existing editor panels
Choosing a rendering mode
See also

Initialize Plauna and create UI, measure text, and manage surfaces, mirroring the examples in the Plauna README. Plauna Getting Started Initialize Plauna and create UI. This mirrors the examples in . Assumes Install & Run is done. Initialize Plauna bootstraps through the engine's editor bootstrap: options: Option Meaning DOM element for the Plauna root. Function returning the VGPU instance to share. The engine instance. An instance (optional). Load Plauna CSS (default ). Text engine to use (default ). Measure text without the DOM Create a GPU surface Enhance existing editor panels Choosing a rendering mode DOM for text heavy, accessible UI. DOM+GPU for panels with GPU visuals. GPU for warped/particle reactive, performance critical UI. See also Plauna Architecture. Plauna API Reference — , , , .


Plauna

Plauna
In this section
Module map
Related

Section index for Plauna — the hybrid DOM/GPU UI framework and workbench (overview, architecture, getting started, API reference). Plauna Hybrid DOM/GPU UI framework and workbench. Source: . In this section Overview — features, rendering modes, module map. Architecture — the state → visual tree → DOM/GPU pipeline. Getting Started — initialize, measure text, create surfaces. API Reference — per file symbols from (browse ). Module map Related WebGPU OS — the shell built on Plauna workspaces. GPU Device Sharing.


Plauna Overview

Plauna Overview
What it provides
Audience
Rendering modes
Module map
UI ECS components
Next steps

The browser-first hybrid DOM/GPU UI framework and workbench — DOM-free text, GPU surfaces, a dockable workspace, and ECS-driven UI state. Plauna Overview Plauna ( ) is a browser first hybrid DOM/GPU UI framework and workbench. It extends the engine with advanced UI: DOM free text measurement, GPU surfaces, a dockable workspace, and ECS driven UI state. It is the compositor/window manager foundation the WebGPU OS shell is built on. What it provides From : Hybrid rendering — DOM, DOM+GPU, and pure GPU modes. Text engine — DOM free text measurement/layout (Pretext style). Surface graph — GPU accelerated surfaces with clipping, warping, composition. Workbench layout — dockable panels, tabs, splitters, floating windows. ECS integration — a dedicated UI world with component driven state. Zero dependencies — pure ES modules, no build step. Audience UI and app developers. OS shell developers depend on Plauna's workspace/surface/widget systems. Rendering modes Mode Use for DOM Standard UI (inspector, forms, menus); full CSS/accessibility/text editing. DOM+GPU Viewports with GPU overlays; DOM structure + GPU visuals. GPU Warped/particle reactive UI; pure WGSL rendering for performance critical visuals. Module map Module Path Purpose Core , , , , , , , , , Layout layout engine Surface GPU surface management Workspace workspaces, panels, splitters, compositor, switcher Widgets UI atoms (Primitive, Form, Navigation, DataViews, Layout, Feedback) Text DOM free text measurement/layout Input input devices/handling Motion animation/motion Themes / Style , , design tokens + CSS Particle VGPU bridge for GPU UI Notifications notification system / toasts Console dev REPL / system console Showcase / Lab , demos / experiments Editor / ECS , editor integration, UI components UI ECS components


Plauna Overview

system / toasts Console dev REPL / system console Showcase / Lab , demos / experiments Editor / ECS , editor integration, UI components UI ECS components Plauna defines UI components that integrate with the engine's ECS: , , , , , , . Next steps Plauna Architecture. Plauna Getting Started. Plauna API Reference — generated from by .


boot.js

boot.js
Classes
class PlaunaDevShell
Notes & Examples
App & widget lifecycle
App & widget lifecycle

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ============================================================================ PLAUNA ENGINE BOOTSTRAP ============================================================================ PlaunaDevShell is the main entry point for the Plauna UI system. It: 1. Initializes the rendering pipeline (WidgetRenderer, DOMRenderer) 2. Loads and applies themes from plauna/themes/{id}/theme.json 3. Sets up the workspace system for virtual desktops (optional GPU panels) 4. Injects base CSS for the widget gallery/showcase 5. Provides a public API for theme switching and widget rendering ARCHITECTURE FLOW: PlaunaDevShell.boot(root, options) → PlaunaDevShell instance init() → loads styles, theme, workspace manager ThemeLoader applies CSS variables to :root WidgetRenderer converts UINode trees to DOM WorkspaceManager (optional) handles GPU accelerated panels USAGE: const shell = await PlaunaDevShell.boot(document.body, { logger: console }); shell.setTheme('dark'); const element = shell.render(myUINode); document.body.appendChild(element); THEME SYSTEM: Themes live in plauna/themes/{id}/theme.json Themes can extend other themes via "extends": "parent" CSS variables are written to <style data plauna theme="1" tags Per session overrides can be applied via applyOverrides() WORKSPACE SYSTEM (OPTIONAL): Requires gpuDevice option for WebGPU support Creates virtual desktop layers for multi panel layouts Supports DOM panels and GPU panels (WebGPU textures) Managed by WorkspaceManager class Classes Method Signature Summary Static factory — boot the engine and return a ready context. Initialize the Plauna engine. Initialization flow: 1. Load base stylesheet (plauna.css) 2. Inject widget base CSS (scoped to story


boot.js

and return a ready context. Initialize the Plauna engine. Initialization flow: 1. Load base stylesheet (plauna.css) 2. Inject widget base CSS (scoped to story preview cells) 3. Inject modern primitive CSS overrides 4. Create workspace container for virtual desktop layers 5. Initialize WorkspaceManager if GPU device provided 6. Determine initial theme (saved or system preference) 7. Apply theme from themes/{id}/theme.json 8. Pre discover available themes in background Inject base widget CSS for story preview cells. CSS injection pattern: Scoped to .plauna story preview class Provides baseline styles for all primitive widgets Uses design tokens for theme consistency Idempotent (checks for existing style element) Includes animations (skeleton shimmer, progress stripes) Widgets styled: Button, Badge, Avatar, Chip, Text, Progress, Skeleton Variant styles (primary, secondary, success, warning, error) Size variants (sm, lg) Inject modern primitive CSS overrides. Modern pattern injection: Scoped to .plauna story preview class Uses !important to override base styles Modern UI patterns inspired by Material Design 3 and Apple HIG Soft gradients, glassy blur, larger radii, subtle elevation Clearer focus rings for accessibility Modern patterns applied: Buttons: Gradient backgrounds, backdrop blur, larger border radius Badges: Softer backgrounds, glassy blur, refined shadows Avatars: Gradient backgrounds, hover elevation, border styling Chips: Alpha transparent backgrounds, hover states Progress: Gradient fills, inset shadows for depth Tooltip: Glassy blur, refined shadows Input: Soft focus rings, hover elevation Load the base Plauna stylesheet. Stylesheet loading pattern: Loads plauna.css from ./styles/ directory Uses import.meta.url for relative path resolution Idempotent (checks


boot.js

Plauna stylesheet. Stylesheet loading pattern: Loads plauna.css from ./styles/ directory Uses import.meta.url for relative path resolution Idempotent (checks for existing link element) Graceful error handling (warns if stylesheet not found) Sets data attribute for identification Apply a theme by ID. Theme application pattern: Delegates to ThemeLoader to load theme from themes/{id}/theme.json Handles theme extension via "extends" property Writes CSS variables to :root Falls back to 'dark' theme on error Notifies observers of theme change Returns metadata list for all registered themes. Apply per session CSS var overrides on top of the active theme. Direct access to the loader for advanced use. Workspace manager f


console/PlaunaConsole.js

console/PlaunaConsole.js
Functions
createPlaunaConsole(options = {})
getPlaunaConsole()
Constants
Notes & Examples
App & widget lifecycle
App & widget lifecycle

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: PlaunaConsole Main console system for Plauna Integrates HtmlConsole with Plauna specific features and debugging capabilities Functions Constants <! HUMAN NOTES Notes & Examples App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. See also: Plauna Architecture · Plauna Overview App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. Example: Widget with full lifecycle See also: Plauna Architecture · Plauna Overview


core/BindingEngine.js

core/BindingEngine.js
Classes
class BindingEngine
Constants
Notes & Examples
App & widget lifecycle
App & widget lifecycle

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Lifecycle safe StateStore UINode bindings and UINode intent dispatch. Two way bindings never promote local UI values into authoritative state. Method Signature Summary Constants <! HUMAN NOTES Notes & Examples App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. See also: Plauna Architecture · Plauna Overview App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. Example: Widget with full lifecycle See also: Plauna Architecture · Plauna Overview


core/DOMRenderer.js

core/DOMRenderer.js
Classes
class DOMRenderer
Notes & Examples
App & widget lifecycle
App & widget lifecycle

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ============================================================================ DOMRenderer Visual Tree to DOM Renderer ============================================================================ DOMRenderer connects Plauna's retained mode UINode system to the browser DOM. It takes a VisualTree (rooted UINode tree) and renders it to actual DOM elements. DIFFERENCES FROM WidgetRenderer: WidgetRenderer: Converts single UINode widgets to DOM (used by widgets themselves) DOMRenderer: Renders entire visual tree from game/engine to DOM (used by PlaunaApp) RENDERING FLOW: 1. render(visualTree) Entry point, renders entire tree to container 2. renderNode(node) Recursively renders node and all children 3. createDOMElement(node) Creates DOM element based on node type 4. Applies styles, attributes, and content 5. Updates mapping tables for bidirectional lookup MAPPING TABLES: nodeToDOM: Map<UINode, HTMLElement UINode → DOM element domToNode: Map<HTMLElement, UINode DOM element → UINode (reverse lookup) renderedNodes: Set<UINode Track which nodes have been rendered ELEMENT TYPE HANDLING: 'text': Renders as <div with text content 'button': <button element 'input': <input element with type, value, placeholder, validation attributes 'image': <img element with src, alt 'svg': SVG namespace elements for graphics Other: <div as fallback DIRTY FLAG PROCESSING: DIRTY.STYLE: Re apply inline styles to DOM DIRTY.LAYOUT: Re compute position/size DIRTY.PAINT: Re render entire node DIRTY.TEXT: Update text content DIRTY.CHILDREN: Re render child subtree UPDATE MECHANISM: updateNode(node): Incrementally updates a single node based on dirty flags updateDOMElement(element, node): Applies node properties to DOM


core/DOMRenderer.js

UPDATE MECHANISM: updateNode(node): Incrementally updates a single node based on dirty flags updateDOMElement(element, node): Applies node properties to DOM element processStyleDirty(nodes): Batch updates for style changes TEXT SERVICE: Optional textService for internationalization If provided, wraps text content through translation layer Classes Method Signature Summary <! HUMAN NOTES Notes & Examples App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. See also: Plauna Architecture · Plauna Overview App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. Example: Widget with full lifecycle See also: Plauna Architecture · Plauna Overview


core/DirtyGraph.js

core/DirtyGraph.js
Classes
class DirtyGraph
Constants
Notes & Examples
App & widget lifecycle
App & widget lifecycle

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: DirtyGraph Optimized dirty flag propagation and update scheduling. Dirty flag management pattern: Efficient dirty flag propagation for large UI trees Categorizes dirty flags by type (STYLE, LAYOUT, PAINT, etc.) Batch processing of dirty nodes Performance tracking for propagation timing Propagation rules: LAYOUT dirtiness propagates to parent PAINT dirtiness propagates to parent if node affects parent's paint CHILDREN dirtiness propagates to descendants STYLE dirtiness propagates to descendants if style affects them Architecture: dirtyNodes: Set of all dirty nodes dirtySets: Map of flag → Set of nodes (categorized by flag type) propagationQueue: Queue for deferred propagations isProcessing: Flag to prevent re entrant propagation Classes Method Signature Summary Constants <! HUMAN NOTES Notes & Examples App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. See also: Plauna Architecture · Plauna Overview App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. Example: Widget with full lifecycle See also: Plauna Architecture · Plauna Overview


core/ModuleTester.js

core/ModuleTester.js
Classes
class PlaunaModuleTester
Notes & Examples
App & widget lifecycle
App & widget lifecycle

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: PlaunaModuleTester Smoke test runner for modules/widgets. Module testing pattern: Verifies module registration and instantiation Exposes widget properties for console diagnostics Summarizes complex values for readable output Tracks widget registry and available widgets Testing features: Module registration verification Widget instantiation testing Property exposure and summarization Value normalization for comparison Helper functions: summarizeValue(): Human readable value summaries normalizeComparableValue(): Normalize values for comparison isPlainObject(): Check if value is plain object Classes Method Signature Summary <! HUMAN NOTES Notes & Examples App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. See also: Plauna Architecture · Plauna Overview App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. Example: Widget with full lifecycle See also: Plauna Architecture · Plauna Overview


core/StateStore.js

createStore(initialState = {}, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: Observable projection store used by Plauna bindings. The store is intentionally authority neutral: networked UI writes arrive as projections, while user actions leave through BindingEngine intent handlers. Classes Method Signature Summary Functions Framework neutral compatibility helper. The third tuple item subscribes to future values; no React global or hidden lifecycle is required. <! HUMAN NOTES Notes & Examples App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. See also: Plauna Architecture · Plauna Overview App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. Example: Widget with full lifecycle See also: Plauna Architecture · Plauna Overview


core/UINode.js

core/UINode.js
Classes
class UINode
Constants
Notes & Examples
App & widget lifecycle
App & widget lifecycle

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ============================================================================ UINode Retained Visual Tree Node ============================================================================ UINode is the base class for all UI nodes in Plauna's retained visual tree. It represents a node in a virtual DOM like tree that can be rendered to actual DOM. KEY CONCEPTS: Retained Mode: The tree persists in memory and is incrementally updated Dirty Flags: Bits that track what parts of the node need re rendering Layout Box: Computed layout metrics (position, size, margins, padding) Event Handlers: Map of event types to handler functions Accessibility: ARIA attributes and role information DIRTY FLAGS (bitmask): STYLE: CSS styles changed → re apply styles to DOM LAYOUT: Position/size changed → re compute layout PAINT: Visual appearance changed → re render to DOM TEXT: Text content changed → update text nodes ACCESSIBILITY: ARIA attributes changed → update DOM attributes CHILDREN: Child nodes added/removed → re render subtree FOCUS: Focus state changed → update focus ring NODE STATE (bitmask): VISIBLE: Node is visible FOCUSED: Node has keyboard focus HOVERED: Mouse is over the node ACTIVE: Node is being pressed/clicked DISABLED: Node is disabled FOCUSABLE: Node can receive focus CHECKED: Checkbox/radio is checked SELECTED: Option is selected LOADING: Node is in loading/processing state ERROR: Node is in error/validation failure state INPUT FLAGS (bitmask): POINTER CAPTURE: Node captures pointer events KEYBOARD CAPTURE: Node captures keyboard events DRAG TARGET: Node is a drag target DROP TARGET: Node is a drop target SCROLLABLE: Node can be scrolled RENDER FLAGS (bitmask): CLIPS CONTENT: Children


core/UINode.js

events DRAG TARGET: Node is a drag target DROP TARGET: Node is a drop target SCROLLABLE: Node can be scrolled RENDER FLAGS (bitmask): CLIPS CONTENT: Children outside bounds are clipped OPAQUE: Node is fully opaque (optimization hint) REQUIRES LAYER: Needs separate compositing layer TRANSFORM CHANGED: Transform property changed OPACITY CHANGED: Opacity property changed TREE STRUCTURE: parent: Reference to parent UINode children: Array of child UINodes firstChild/lastChild: Linked list pointers for fast traversal nextSibling/previousSibling: Linked list pointers for siblings LAYOUT BOX: x, y: Position relative to parent width, height: Computed size minX, minY, maxX, maxY: Computed bounds paddingLeft, paddingTop, paddingRight, paddingBottom: Padding marginLeft, marginTop, marginRight, marginBottom: Margin borderLeft, borderTop, borderRight, borderBottom: Border width Classes Method Signature Summary Constants — UINode Retained visual tree node. UINode pattern: Base class for all UI nodes in Plauna's retained visual tree Virtual DOM like tree that persists in memory Incrementally updated via dirty flags Supports tree structure (parent/children/siblings) Event handling and accessibility support Key concepts: Dirty flags: Track what needs re rendering Layout box: Computed layout metrics Event handlers: Map of event types to functions Accessibility: ARIA attributes and role information <! HUMAN NOTES Notes & Examples App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. See also: Plauna Architecture · Plauna Overview App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount


core/UINode.js

the OS shell, and standalone. See also: Plauna Architecture · Plauna Overview App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. Example: Widget with full lifecycle See also: Plauna Architecture · Plauna Overview


core/VisualTree.js

core/VisualTree.js
Classes
class VisualTree
Notes & Examples
App & widget lifecycle
App & widget lifecycle

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: VisualTree Manages the retained visual tree and dirty propagation. Visual tree management pattern: Manages UINode hierarchy with root node Dirty flag management and propagation Update scheduling with requestAnimationFrame Performance tracking for update timing Callback hooks for layout, paint, accessibility updates Features: setRoot(): Change root node (marks subtree dirty) markDirty(): Mark node as dirty (schedules update) markSubtreeDirty(): Mark entire subtree as dirty update(): Main update loop (processes dirty nodes) Update queues: layoutQueue: Nodes needing layout recalculation paintQueue: Nodes needing paint updates textQueue: Nodes needing text content updates accessibilityQueue: Nodes needing ARIA updates Architecture: root: Root UINode of the tree dirtyNodes: Set of all dirty nodes isUpdating: Flag to prevent re entrant updates updateScheduled: Flag for RAF scheduling Classes Method Signature Summary <! HUMAN NOTES Notes & Examples App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. See also: Plauna Architecture · Plauna Overview App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. Example: Widget with full lifecycle See also: Plauna Architecture · Plauna Overview


core/app.js

core/app.js
Classes
class PlaunaApp
Functions
async createPlaunaApp(options = {})
Notes & Examples
App & widget lifecycle
App & widget lifecycle

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: ============================================================================ PlaunaApp Main Plauna Application Class ============================================================================ PlaunaApp is the main application class that integrates Plauna UI with the Particle Engine. It manages the visual tree, rendering, events, and development tools. CORE COMPONENTS: VisualTree: Retained mode UI tree (UINode hierarchy) DOMRenderer: Renders visual tree to DOM elements PlaunaEventSystem: Event handling and dispatching ThemeManager: Theme management and CSS variable application TransitionEngine: Animation and transition system PlaunaTextService: Text internationalization (pretext) PlaunaSurfaceManager: Surface/layer management PlaunaGPUBridge: GPU integration bridge PlaunaRegistry: Component registry DEVELOPMENT TOOLS: TreeInspector: Visual tree inspector for debugging StyleInspector: Style inspector for debugging HotReload: Hot module replacement for development PlaunaModuleTester: Module testing framework PlaunaSmartContextMenu: Context aware right click menu INTEGRATION WITH PARTICLE ENGINE: Uses ECS World from engine/ecs/world/World.js Integrates with GPU via PlaunaGPUBridge Uses PlaunaSurfaceManager for surface management Text engine integration (pretext or custom) INITIALIZATION FLOW: 1. createPlaunaApp(options) Factory function 2. PlaunaApp constructor Sets up core components 3. initialize() Initializes all subsystems 4. mount() Mounts to root DOM element OPTIONS: root: Required DOM element to mount to getVGPU: Function to get VGPU instance engine: Particle engine instance editor: Editor instance (optional) useCSS: Enable CSS injection (default: true) textEngine: Text


core/app.js

Function to get VGPU instance engine: Particle engine instance editor: Editor instance (optional) useCSS: Enable CSS injection (default: true) textEngine: Text engine to use ('pretext' or custom) enableModuleTester: Enable module tester (default: true) enableSmartContextMenu: Enable smart context menu (default: true) PUBLIC API: mount(): Mount app to root element destroy(): Cleanup and destroy app addComponent(): Add component to registry getComponent(): Get component from registry visualTree: Access visual tree instance renderer: Access DOM renderer instance eventSystem: Access event system instance themeManager: Access theme manager instance LIFECYCLE: Created via createPlaunaApp() factory Must call mount() to display UI Call destroy() to cleanup USAGE: const app = await createPlaunaApp({ root: document.body, getVGPU: () = vgpuInstance, engine: particleEngine }); await app.mount(); // ... use app app.destroy(); Classes PlaunaApp Main Plauna application class. Application architecture: Integrates Plauna UI with Particle Engine Manages visual tree, rendering, events, and development tools Provides public API for component registration and access Core systems: uiWorld: ECS World for UI entities textService: Internationalization service surfaceManager: Surface/layer management gpuBridge: GPU integration bridge registry: Component registry events: Event system Retained mode systems: visualTree: UINode hierarchy domRenderer: DOM renderer themeManager: Theme management transitionEngine: Animation system Development tools: treeInspector: Visual tree inspector styleInspector: Style inspector hotReload: Hot module replacement moduleTester: Module testing framework smartContextMenu: Context aware menu Method Signature Summary Functions PlaunaApp factory function. Application


core/app.js

moduleTester: Module testing framework smartContextMenu: Context aware menu Method Signature Summary Functions PlaunaApp factory function. Application factory pattern: Creates PlaunaApp instance with provided options Initializes core components (visual tree, renderer, events) Sets up development tools if enabled Returns ready to use app instance Parameters: (Object) — Configuration options (HTMLElement) — Required DOM element to mount to (Function) — Function to get VGPU instance (Object) — Particle engine instance (Object) — Editor instance (optional) (boolean) — Enable CSS injection (default: true) (string) — Text engine to use ('pretext' or custom) (boolean) — Enable module tester (default: true) (boolean)


core/events.js

core/events.js
Classes
class PlaunaEventSystem
Notes & Examples
App & widget lifecycle
App & widget lifecycle

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: PlaunaEventSystem Event system for Plauna. Event bus pattern: Simple publish subscribe event system Follows existing engine/ editor patterns Supports multiple listeners per event Returns unsubscribe function for cleanup Error handling for faulty event handlers Features: on(): Subscribe to event with callback off(): Unsubscribe from event emit(): Dispatch event to all listeners once(): Subscribe for single event occurrence removeAllListeners(): Clean up listeners Classes PlaunaEventSystem Event system for Plauna. Event bus pattern: Simple publish subscribe event system Follows existing engine/ editor patterns Supports multiple listeners per event Returns unsubscribe function for cleanup Error handling for faulty event handlers Features: on(): Subscribe to event with callback off(): Unsubscribe from event emit(): Dispatch event to all listeners once(): Subscribe for single event occurrence removeAllListeners(): Clean up listeners Method Signature Summary <! HUMAN NOTES Notes & Examples App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. See also: Plauna Architecture · Plauna Overview App & widget lifecycle Plauna apps and widgets follow a mount → update → unmount lifecycle; services (storage, command bus, theming) are injected rather than imported, so the same widget runs in the editor, the OS shell, and standalone. Example: Widget with full lifecycle See also: Plauna Architecture · Plauna Overview