compat/healing-pipeline

Summary: healing-pipeline.js — ordered pre-boot healing passes over a guest. Runs after probing and before the realm is built, mutating the parsed model and the profile in place. Ordered per the compat spec: DOM/CSS scoping happen in the realm itself; here we do the model/profile-level passes: GPU flags → lifecycle flags → error policy → asset URL rewrite → WGSL repair. Each pass is isolated (a throwing healer never aborts the others) and appends to a human-readable report returned to the caller.


compat/html-ingestor

Summary: html-ingestor.js — parse a guest HTML document into a structured model. Uses DOMParser (scripts parsed this way are INERT — they will not execute on insertion), so we can safely inspect and relocate the DOM, then hand the extracted scripts to the runtime realm to execute in controlled order. The returned model: { doc,                       // the parsed Document (inert) title, scripts: [{ module, src, code, async, defer }],   // document order styles:  [{ inline, href, code }],                // document order links:   [{ rel, href }], canvases:[{ id, width, height }], assets:  string[],         // referenced asset URLs (img/src, etc.) }


compat/iframe-realm

Summary: iframe-realm.js — a hard-isolation execution root for UNTRUSTED guest apps. Unlike RuntimeRealm (light-DOM, shared OS origin — best-effort isolation), this runs the guest inside a `sandbox="allow-scripts"` iframe WITHOUT `allow-same-origin`, so it gets a unique opaque origin and cannot touch the OS document, cookies, localStorage/IndexedDB, or kernel globals. It is a real security boundary suitable for community/unverified packages and live remote sites. The guest document is assembled self-contained (bundled JS → `data:` modules with imports rewritten; bundled CSS/assets → inline/`data:` URLs) because parent-origin blob URLs are unreachable from the opaque-origin iframe. A tiny injected bridge routes window.open()/anchor navigations up to the host via postMessage (the host opens them in the OS Browser). Trade-offs vs RuntimeRealm: no shared WebGPU device (the iframe requests its own), and no direct syscall access (a postMessage RPC would be needed). Used only when isolation is requested.


compat/index

Summary: engine/compat/index.js — the Engine Compatibility namespace. `createCompat(ctx)` returns the `engine.compat` API used across the OS: await engine.compat.boot({ id, source, mount, mode, permissions }); `ctx` wires the compat layer to the host engine/kernel (all optional): storage   — kernel.storageManager (profile/snapshot persistence) gpu       — { getOrCreateSharedDevice(adapter, desc), format, healDeviceDescriptor } scheduler — engine frame scheduler (RAF interposition, Phase 5/6) validate  — async (profile) => { valid, errors }      (Phase 3) heal      — async ({ model, profile, files, appId })  (Phase 4) interpose — async ({ realm, profile, app, ctx })      (Phase 5) onError   — (info) => void Phases 3-7 register their hooks onto the same ctx, so this factory stays the single, stable entry point as the pipeline grows.


compat/interposers/fetch

Summary: interposers/fetch.js — default-deny network egress for guest apps + serving bundled package files. Resolution order: 1. If the ref resolves to a bundled package file (e.g. `fetch('data.json')` or a `.wasm`), serve it directly from the file map — relative paths in a blob-loaded module would otherwise 404 against the OS origin. 2. Same-origin, relative, `blob:` and `data:` requests pass through. 3. Cross-origin requests are blocked unless the profile granted `network.fetch` — preventing a wrapped third-party app from phoning home.


makeFetchShim

makeFetchShim({ profile, onError, realm = null } = {})


compat/interposers/file-export

Summary: interposers/file-export.js — safe blob/download handling for a guest realm. Guests export files via `URL.createObjectURL(blob)` + an `<a download>` click (or `showSaveFilePicker`). Two problems: created object URLs leak if never revoked, and downloads are invisible to the OS. This shim wraps `URL` so every `createObjectURL` is tracked (and revoked on realm destroy) and each export is counted into the app's metrics — without blocking the legitimate download.


makeUrlShim

makeUrlShim(realm, { metrics, onExport } = {})


compat/interposers/gpu

Summary: interposers/gpu.js — wrap `navigator.gpu` for a guest realm. The guest keeps using the real WebGPU implementation, but through a shim that: • clamps `requiredLimits` to what the adapter actually supports (a very common crash cause when an app hard-codes limits from a beefier GPU), • drops unsupported `requiredFeatures` instead of throwing, • counts `queue.submit` calls into the app's metrics, • reports device-loss (so the recovery layer can react) without spamming on intentional `destroy()`. It deliberately does NOT share the kernel's device — each guest gets its own device so it cannot corrupt OS GPU state. Sharing/surface hand-off is Phase 6.


compat/interposers/index

Summary: interposers/index.js — install per-realm API shims for a guest app. Guests run in the shared window, so we cannot replace globals process-wide without breaking the OS. Instead we: 1. build a per-realm `context` of shims (gpu/raf/storage/fetch), 2. register it at `globalThis.__engineRealms.get(appId)`, 3. return a code `transform` that prepends a tiny prelude to each guest script which LEXICALLY SHADOWS the relevant globals with the shims. Module scripts: the prelude's top-level `const`s shadow the globals within the module's own scope. Classic scripts: wrapped in an IIFE (only when there's a single classic script, to avoid breaking cross-script global sharing). Which globals are shadowed is driven by `profile.uses`, minimising both collision risk and overhead.


installInterposers

installInterposers({ realm, profile, ctx, app } = {})


compat/interposers/navigation

Summary: navigation.js — keep a guest's "open a new window" / external navigation INSIDE the OS instead of spawning a real browser popup or navigating the whole OS page away. Guests run in the shared OS document (light DOM, not an iframe), so an unhandled `<a href>` click or `window.open()` would either pop a real browser window or unload the entire OS. We intercept both and hand the URL to the host via `onOpenWindow(url, info)` — the host decides where it goes (default: the in-OS Browser app). Two mechanisms: 1. DOM click-capture on the realm container — anchors that open a new window (target=_blank/_new) or point off-origin are cancelled and routed. Always installed (cheap, prevents the OS-unload footgun). 2. Lexically-shadowed `window.open` / `open()` / `location` — routes JS-driven popups and redirects. Only bound when the probe detected such usage (`profile.uses.windowOpen`), to minimise shadowing blast radius.


makeOpenShim

makeOpenShim({ onOpenWindow, onError } = {})

Summary: Replacement for window.open / open(): route the URL, return a harmless stub.


makeWindowProxy

makeWindowProxy(openShim, { onOpenWindow, onError } = {})

Summary: Proxy over the real window that only overrides `open` and `location` writes.


makeLocationProxy

makeLocationProxy({ onOpenWindow, onError } = {})

Summary: Proxy over location: reads pass through; href=/assign/replace are routed.


installNavCapture

installNavCapture(realm, { onOpenWindow, onError } = {})

Summary: Capture-phase click handler on the realm container. Cancels + routes anchor navigations that would open a new window or leave the OS origin. Returns a cleanup function (also registered on the realm).


compat/interposers/raf

Summary: interposers/raf.js — managed requestAnimationFrame for a guest realm. Guest render loops are the #1 resource leak when an app's window closes: the raw `requestAnimationFrame` loop keeps running forever. This shim tracks every pending frame and cancels them all on `realm.destroy()`, so closing a guest window actually stops its GPU work. Errors thrown inside a frame callback are reported instead of silently killing the loop's owner.


compat/interposers/storage

Summary: interposers/storage.js — per-app namespaced localStorage / sessionStorage. Guests freely use `localStorage.foo = x` and `localStorage.getItem(...)`. Left unscoped they would collide with each other and with the OS. This shim transparently prefixes every key with `compat:<appId>:` and supports both the Storage method API and direct property access (via a Proxy). Falls back to an in-memory store when Web Storage is unavailable.


compat/interposers/worker

Summary: interposers/worker.js — resolve guest Worker(url) references to bundled blobs. A guest's `new Worker('worker.js')` references a path relative to its original document, which won't resolve once the guest runs from blob URLs in the OS realm. This shim rewrites a relative/bundled worker URL to its pre-linked module blob (imports already rewritten + shims applied), or a blob of the bundled file. Remote/absolute URLs pass through unchanged. Returns a Worker subclass, or null if Worker is unavailable.


makeWorkerShim

makeWorkerShim(realm, RealWorker = (typeof Worker !== 'undefined' ? Worker : null)


compat/module-linker

Summary: module-linker.js — turn an in-memory file map into runnable blob-URL modules. Loading an ES module from a `blob:` URL loses its path context, so relative imports (`import './a.js'`) and `import.meta.url`-relative resolution break (the blob has no directory). Following the es-module-shims technique, we rewrite every relative / bundled import specifier in each JS module to the `blob:` URL of its resolved target (created in dependency order), optionally apply a code transform (the interposer prelude / shader healing), and return a `path → blobURL` map plus a resolver for inline-module imports. Bare specifiers (`import 'three'`) may be resolved by the caller-provided import resolver (import map / CDN fallback). Absolute/remote URLs are left untouched.


buildModuleBlobs

buildModuleBlobs({ files, transform = null, onWarn = null, resolveBare = null, resolveExternal = null, urlKind = 'blob' } = {})

Summary: Build blob-URL modules for every bundled JS file, with relative imports rewritten to reference each other's blob URLs.


buildImportResolver

Summary: Build a resolver for BARE import specifiers (`three`, `@scope/pkg`, subpaths) from a compat profile. Resolution order: 1. exact match in `profile.imports.map` 2. longest trailing-slash prefix match (`three/` → base) in the map 3. CDN fallback `<cdn><spec>` when `profile.healing.cdnImports !== false` (default CDN https://esm.sh/, overridable via `profile.imports.cdn`) Returns null when nothing matches (the import is left unresolved).


isBareSpecifier

Summary: A bare specifier: not relative (./ ../ /), not an absolute/remote URL.


discoverSpecs

Summary: Collect every (string-literal) import specifier from module code.


rewriteSpecs

Summary: Replace import specifiers using `urlFor(spec)`. When it returns a falsy value the original specifier is kept (bare/remote/cyclic).


resolveSpec

Summary: Resolve an import specifier to a bundled file path, or null when it is bare (no leading ./ ../ or /) or absolute/remote. Tries the literal path, then `.js`/`.mjs`, then `/index.js`.


compat/probe-scanner

Summary: probe-scanner.js — statically detect what a guest app uses. Combines the parsed DOM model with a regex scan of all script source to infer the `uses`, `dom`, and `gpu` sections of a compatibility profile. This is a heuristic pass (static, no execution) — the healing + interposition layers refine it at runtime and the profile cache promotes it once it boots.


compat/profile-builder

Summary: Build a full profile from a static scan result.


mergeProfiles

Summary: Merge a saved profile with a freshly scanned one. Saved healing/permissions decisions win (they were promoted as working); newly detected requirements and `uses`/`gpu` flags are unioned in.


profilePermissionList

Summary: Map a profile to a kernel/AppRegistry permission list (best-effort).


Summary: SHA-256 hex of a string (used for source/version hashing).


Summary: profile-builder.js — assemble & merge compatibility profiles. A profile is the durable description of what a guest app needs and how to heal it. The static scanner produces a fresh profile; the cache may hold a saved one from a previous version. `mergeProfiles` reuses known-good healing decisions and layers in newly detected requirements.


compat/profile-cache

Summary: profile-cache.js — persist & version compatibility profiles. Storage layout (via the kernel StorageManager facade): /os/compat/profiles/{id}.json        ← active (stable or testing) profile /os/compat/index.json                ← { [id]: { knownVersions: [...] } } /os/compat/snapshots/{id}/{ts}.json  ← runtime snapshots (Phase 7) If no storage facade is provided (or a write fails), it degrades to an in-memory cache so the bootloader still works in a bare harness/test.


compat/runtime-realm

Summary: runtime-realm.js — a controlled, scoped execution root for a guest app. Trusted same-origin guests (Mode A/B) reference elements via `document.*`, so the realm is a SCOPED LIGHT-DOM container (`<div data-engine-app="id">`) rather than a shadow root — `getElementById('c')` must still resolve. Isolation comes from: • CSS scoping (css-healer) so guest styles can't touch the OS shell, • API interposition (Phase 5) so guest browser calls route through the engine, • DOM healing so required elements exist before scripts run. Scripts parsed by DOMParser are inert; the realm re-executes them in document order: classic inline → fresh <script>; module inline → blob import(); src → resolved against the package file map (blob) or left as a URL for the browser.


compat/schema-registry

Summary: schema-registry.js — validate a compatibility profile before boot. Self-contained: a tiny JSON-Schema-subset checker (type / required / enum / properties / items / additionalProperties) plus `validateProfile()` which also applies cross-field consistency rules (e.g. GPU pipelines imply uses.webgpu). The bootloader calls this via `ctx.validate`; Package Studio can call `engine.compat.validateProfile(profile)` to preview problems before compiling.


validateProfile

Summary: Validate a full compatibility profile: structural schema + consistency rules.


compat/schemas

Summary: schemas.js — declarative schemas for the compatibility profile and its parts. Kept as plain JS descriptors (not .json) so the engine module is self-contained and needs no fetch. Validated by `schema-registry.js`'s tiny checker, which supports: type, required, enum, properties, items, additionalProperties.


compat/source-loader

Summary: source-loader.js — load a guest app's source from any supported origin. Supported `source` shapes: string                         → treated as raw HTML if it looks like HTML, else a URL { html }                       → raw HTML string { url, fetch? }                → remote fetch (CORS-aware; optional custom fetch) { file: File }                 → an imported File (uses .text()) { files: Map|object, entry }   → an in-memory file map (folder/zip), entry = HTML path { vfsPath, storage }           → read from the OS VFS via a StorageManager Returns: { html, files: Map<string,string|ArrayBuffer>, baseUrl, sourceType, sourceHash }


compat/surface/engine-texture-surface

Summary: surface/engine-texture-surface.js — present the guest's render into an engine texture instead of a DOM canvas (so it can be composited in the 3D/GPU UI). STUB: the full implementation redirects the guest's WebGPU context to an offscreen target on the shared kernel device, then imports the result as an engine texture each frame. That requires the canvas-interposer to hand the guest a wrapped context and the kernel compositor to accept an external texture. Until that lands, `supported` is false so `selectSurface` falls back to the webgpu-canvas surface — the profile can already request this mode, so flipping it on later needs no guest changes.


compat/surface/offscreen-surface

Summary: surface/offscreen-surface.js — render the guest on an OffscreenCanvas. STUB: intended for guests that can run their render loop on a worker / detached canvas (transferControlToOffscreen) for isolation and throttling. Behind the same Surface interface; `supported` is false until the offscreen transfer + present path is implemented, so `selectSurface` falls back to webgpu-canvas.


compat/surface/surface-manager

Summary: surface/surface-manager.js — pick the presentation surface for a guest. Selected by `profile.gpu.presentation`. `webgpu-canvas` (and `canvas-2d`) are fully implemented; `engine-texture` / `offscreen` are stubs that report `supported === false`, so we transparently fall back to the canvas surface — the profile can request them today and they'll light up when implemented, with no guest changes.


compat/surface/webgpu-canvas-surface

Summary: surface/webgpu-canvas-surface.js — default presentation: the guest's own <canvas> inside the realm container. For trusted same-origin guests this is mostly pass-through (the app configures its own WebGPU canvas context). The surface's job is to LOCATE the primary canvas and, when `profile.healing.autoCanvasSize` is enabled, keep its backing store sized to the container with a clamped device-pixel-ratio — fixing the common "canvas stuck at 300×150 / wrong DPR" class of bugs without fighting an app that manages its own sizing.


config/EngineConfig


config/EngineDefaultConfig


config/EngineState

Summary: Create GPU state object


createGpuState

Summary: Create GPU state object


createWaterPassState

Summary: Create water pass state object Used for screen-space fluid/water/metaball rendering


createConfigState

Summary: Create scene configuration state (merge with engine.cfg overrides)


createPhysicsState

Summary: Create physics configuration state


createEcsState

Summary: Create ECS state object


createSpawnState

Summary: Create spawn/ghost state object


createParticlesState

Summary: Create particle system state object


createSmokeState

Summary: Create volumetric smoke state object


createRenderState

Summary: Create render settings state


createCameraState

Summary: Create camera state object


createInputState

Summary: Create input state object


createAudioState

Summary: Create audio state object


createAllState

Summary: Create all state objects at once.


applyEngineConfigToState

Summary: Apply engine.cfg values to config state. Call this after loading engine.cfg.


applyEngineConfigToPhysics

Summary: Apply engine.cfg values to physics state.


Summary: Default configuration values (can be overridden by engine.cfg)


Summary: Default physics values


Summary: Default render settings


core/AppBootstrap

Summary: AppBootstrap.js - Application bootstrap helper Consolidates common app initialization: WebGPU check, canvas ready, config loading, ECS world, GPU init, and main loop setup.


bootstrapApp

Summary: Bootstrap a complete application.


createMainLoop

Summary: Create main loop with standard update/render pattern.


runApp

Summary: Full app bootstrap + loop in one call.


core/EngineIntegration

Summary: High-performance particle emitter using SoA


RenderCommandBuilder

Summary: Render command builder using object pools


initResourceManagement

async initResourceManagement(device, options = {})

Summary: Initialize resource management for the game Call this during game initialization after WebGPU device is ready


frameWrapper

Summary: Frame wrapper that handles resource management automatically Usage: ```js function gameLoop() { frameWrapper(() => { // Your game update code here updatePhysics(); updateAI(); render(); }); requestAnimationFrame(gameLoop); } ```


frameWrapperAsync

Summary: Async frame wrapper for async game loops


submitPhysicsJob

Summary: Submit physics job to scheduler


submitAIJob

Summary: Submit AI job to scheduler


submitStreamingJob

submitStreamingJob(callback, data = null)

Summary: Submit streaming/loading job to scheduler


submitCleanupJob

Summary: Submit background cleanup job


Summary: Schema for high-performance particle system using Structure of Arrays


Summary: Schema for entity transforms using Structure of Arrays


core/EntitySystem

Summary: EntitySystem — lightweight entity registry used by LIFE narrative systems. This is intentionally a simple in-memory map. The ECS runtime lives in the engine simulation layer; narrative modules just need a stable handle to the active entity collection they are narrating.


core/ResourceManager

Summary: ResourceManager.js - Unified High-Performance Resource Management Central facade integrating: - Host Memory (RAM): Slab Allocators, Object Pools, SoA Containers - Device Memory (GPU): Ring Buffers, Buddy Allocators, Texture Management - Task Scheduling: Job System, Worker Pools, Frame Budgeting Based on architectural specification for zero-allocation, high-throughput WebGPU applications targeting 60+ FPS.


ResourceManager

Summary: Unified resource management facade


core/compression/AnimationCompression

Summary: AnimationCompression.js - Animation Data Compression Compresses skeletal animation data using: - Quaternion compression: 37.5% reduction (16 bytes → 10 bytes) - DCT temporal compression: 60-80% reduction - Delta encoding: Store only changed bones - Keyframe reduction: Remove redundant frames Typical compression: 60-80% reduction for skeletal animations


compressAnimationTrack

compressAnimationTrack(track, options = {})

Summary: Compress animation track (position, rotation, or scale)


decompressAnimationTrack

Summary: Decompress animation track


compressSkeletalAnimation

Summary: Compress full skeletal animation


decompressSkeletalAnimation

Summary: Decompress skeletal animation


reduceKeyframes

reduceKeyframes(track, tolerance = 0.001)

Summary: Remove redundant keyframes that can be interpolated


compressAnimationBatch

Summary: Compress multiple animations


core/compression/CompressionUtils

Summary: CompressionUtils.js - Unified Compression Utilities Provides compression techniques for various data types: - Variable-Length Integer Encoding (VLInt) - Quantization (Float32 → Int16/Int8) - Run-Length Encoding (RLE) - Delta Compression - Octahedral Normal Encoding - Quaternion Compression Based on research from particle snapshot compression achieving 390x compression


packVLInt

Summary: Pack small integers into fewer bytes using variable-length encoding Most indices are small, so we can use 1-2 bytes instead of 4 Encoding: - 1 byte: 0xxxxxxx (0-127) - 2 bytes: 10xxxxxx xxxxxxxx (128-16,383) - 3 bytes: 11xxxxxx xxxxxxxx xxxxxxxx (16,384-4,194,303)


unpackVLInt

Summary: Unpack variable-length encoded integers


quantizeFloat

Summary: Quantize float to int16 within range [-range, +range] Achieves 50% memory reduction with minimal precision loss


dequantizeFloat

Summary: Dequantize int16 back to float


quantizeFloatArray

Summary: Quantize array of floats to Int16Array


dequantizeFloatArray

Summary: Dequantize Int16Array back to Float32Array


Summary: Quantize to int8 for even more compression (75% reduction) Use for data that doesn't need high precision (normals, colors)


encodeOctahedralNormal

Summary: Encode 3D unit normal to 2D octahedral coordinates Industry-standard technique used in AAA games Reference: "A Survey of Efficient Representations for Independent Unit Vectors"


decodeOctahedralNormal

Summary: Decode octahedral coordinates back to 3D normal


encodeNormalArray

Summary: Encode array of normals (vec3) to Int16Array Input: Float32Array [nx, ny, nz, nx, ny, nz, ...] Output: Int16Array [x, y, x, y, ...] (66% smaller)


decodeNormalArray

Summary: Decode array of normals back to Float32Array


compressQuaternion

Summary: Compress quaternion by dropping smallest component Technique: Store 3 largest components + index of dropped component Used in animation systems for skeletal rigs


decompressQuaternion

Summary: Decompress quaternion by reconstructing dropped component


runLengthEncode

Summary: Run-Length Encode an array of values Perfect for voxel data with large empty regions Returns: [[value, count], [value, count], ...]


runLengthDecode

Summary: Decode run-length encoded data


runLengthEncodeCompact

Summary: RLE with VLInt encoding for maximum compression Returns Uint8Array: [value, count, value, count, ...]


deltaEncode

Summary: Delta encode array (store differences instead of absolute values) Great for temporal data or sorted indices


deltaDecode

Summary: Decode delta-encoded array


createPalette

Summary: Create palette from array of values Returns: { palette: unique values, indices: array of palette indices }


decodePalette

Summary: Decode palette-compressed data


getCompressionStats

Summary: Calculate compression ratio and statistics


formatBytes

Summary: Format bytes for display


core/compression/HybridCompression

Summary: HybridCompression.js - Best of Both Worlds Intelligently combines lossless and lossy compression: - Lossy techniques for high compression (quantization, RLE, etc.) - Lossless encoding on top (LZ77 + Huffman) - Result: Near-lossless quality with near-lossy compression ratios Achieves 80-90% of lossy compression ratio with <0.001% quality loss


compressMeshHybrid

Summary: Compress mesh with hybrid approach


decompressMeshHybrid

Summary: Decompress hybrid mesh


compressVoxelHybrid

compressVoxelHybrid(voxels, options = {})

Summary: Compress voxel chunk with hybrid approach


decompressVoxelHybrid

Summary: Decompress hybrid voxel chunk


compressAnimationHybrid

compressAnimationHybrid(track, options = {})

Summary: Compress animation with hybrid approach


decompressAnimationHybrid

Summary: Decompress hybrid animation


core/compression/LosslessCompression

Summary: LosslessCompression.js - Zero Quality Loss Compression Implements truly lossless compression using: - DEFLATE (zlib): Industry standard, 2-3x compression - LZ77 dictionary compression: Fast, 1.5-2x compression - Huffman coding: Entropy encoding - Combination with existing techniques for maximum compression All compression is 100% lossless - perfect reconstruction guaranteed


Summary: Simple LZ77 compression (basis of DEFLATE) Finds repeated sequences and replaces with back-references 100% lossless


Summary: Decompress LZ77 data


compressHuffman

Summary: Compress data using Huffman coding 100% lossless entropy encoding


decompressHuffman

Summary: Decompress Huffman coded data


compressLossless

Summary: Compress typed array with zero quality loss Combines LZ77 + Huffman for maximum compression


decompressLossless

Summary: Decompress losslessly compressed data Perfect reconstruction guaranteed


Summary: Compress Float32Array losslessly


Summary: Compress Int16Array losslessly


Summary: Compress Uint8Array losslessly


testLosslessCompression

Summary: Test compression on sample data


core/compression/MeshCompression

Summary: MeshCompression.js - Mesh Data Compression Compresses mesh data using: - Position quantization (Float32 → Int16): 50% reduction - Normal octahedral encoding: 66% reduction - UV half-float encoding: 50% reduction - Index VLInt encoding: 30-50% reduction Typical compression: 70-90% reduction in mesh size


compressMesh

Summary: Compress mesh data


decompressMesh

Summary: Decompress mesh data


compressMeshBatch

Summary: Compress multiple meshes and combine into single buffer Useful for static scene geometry


decompressMeshBatch

Summary: Decompress batch of meshes


compressMeshForStreaming

compressMeshForStreaming(mesh, lodLevels = [1.0, 0.5, 0.25])

Summary: Compress mesh for streaming (progressive loading) Returns base LOD + detail layers


core/compression/VoxelCompression

Summary: VoxelCompression.js - Voxel Data Compression Compresses voxel data using: - Run-Length Encoding (RLE): 80-95% reduction for sparse data - Octree structure: Hierarchical compression - Palette compression: Reuse common materials - Delta encoding: Store chunk changes Typical compression: 80-95% reduction for typical voxel worlds


compressVoxelChunk

compressVoxelChunk(voxels, options = {})

Summary: Compress voxel chunk data


decompressVoxelChunk

Summary: Decompress voxel chunk data


compressVoxelDelta

Summary: Compress changes between two chunk states Perfect for multiplayer sync or undo/redo


applyVoxelDelta

Summary: Apply delta to chunk


compressVoxelWorld

Summary: Compress entire voxel world


decompressVoxelWorld

Summary: Decompress voxel world


compressVoxelChunkForStreaming

Summary: Compress chunk for streaming (progressive loading)


core/compression/index

Summary: Compression Module - Unified Compression System Provides compression for all engine data types: - Particles: 390x compression (VLInt + Delta + Quantization + PCA/DCT) - Meshes: 70-90% reduction (Quantization + Octahedral normals + VLInt indices) - Voxels: 80-95% reduction (RLE + Octree + Palette) - Animations: 60-80% reduction (Quaternion + DCT + Keyframe reduction) All compression techniques are lossless or near-lossless with configurable quality.


core/events/EventBus


core/framegraph/FrameGraph


core/framepipeline/FrameContext

Summary: FrameContext — Per-frame shared state passed to every pipeline stage. The engine provides a minimal base context with timing and GPU fields. Consumers (editor, game) extend it with their own fields via the overrides parameter. Usage: const ctx = createFrameContext({ dt: 0.016, currentTime: performance.now(), device: gpuDevice, camera: myCamera, editor: editorApp, scene: editorApp.scene, }); pipeline.execute(ctx);


createFrameContext

Summary: Create a per-frame context object.


core/framepipeline/FramePipeline

Summary: FramePipeline — Generic phased stage executor. Engine-level primitive. Consumers (editor, game, tests) register their own stages via addStage(). The pipeline knows nothing about WebGPU, ECS, or any specific renderer — it just executes stages in order within named phases. Phases (run in this order by execute()): fixedStep  — 0..N per frame (physics, PBD, fixed-rate sim) update     — 1/frame (camera, matrices, lights, animation) render     — 1/frame (GPU render passes) postRender — 1/frame (composites, post-FX, GPU submit) Inspired by: Unity     — FixedUpdate / Update / LateUpdate / OnPostRender Unreal    — TG_PrePhysics → TG_PostPhysics → TG_PostUpdateWork Bevy      — Extract → Prepare → Queue → Render → Cleanup Frostbite — Frame Graph (Setup → Compile → Execute) Complements engine/core/framegraph/FrameGraph.js which handles resource dependency scheduling; this handles execution scheduling.


core/framepipeline/index

Summary: Frame Pipeline — Barrel exports


core/gpu/AdaptiveQualityGovernor

Summary: Canonical engine-wide adaptive quality decision maker. It emits one immutable decision per frame so downstream systems cannot independently compound degradations. Correctness requirements are intentionally absent from tiers.


core/gpu/AsyncComputeScheduler

Summary: AsyncComputeScheduler - Manages async compute work


ComputeWorkGroup

Summary: ComputeWorkGroup - Helper for organizing related compute work


core/gpu/AsyncGPUWorkScheduler

Summary: Async GPU Work Scheduler - Intelligent queue submission batching Eliminates redundant queue submissions and optimizes GPU pipeline utilization Based on WebGPU best practices for minimizing CPU-GPU sync points


GPUFrameCoordinator

Summary: GPU Frame Coordinator - Coordinates GPU work across frame boundaries Implements triple-buffering and proper synchronization


core/gpu/BindingSignals


core/gpu/BitonicSort

Summary: Calculate 30-bit Morton code for 3D position


positionToMorton

Summary: Calculate Morton code from world position


bitonicSortCPU

Summary: CPU bitonic sort for small arrays or fallback


SortKeyType

Summary: Sort key types


Summary: Maximum elements (must be power of 2)


core/gpu/BufferLayouts

Summary: Convert float to fixed-point integer


toFixed

Summary: Convert float to fixed-point integer


fromFixed

Summary: Convert fixed-point integer back to float


alignTo

Summary: Align a size/offset to the specified boundary


paddingFor

Summary: Calculate padding needed to reach alignment


isAligned

Summary: Validate that a size meets alignment requirements


getParticleBufferSizes

Summary: Calculate buffer sizes for particle system


getGridBufferSizes

Summary: Calculate grid buffer size


createAlignedBuffer

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

Summary: Create a WebGPU buffer with proper alignment


createBufferWithData

createBufferWithData(device, data, usage, label = '')

Summary: Create a mapped buffer for initial data upload


createUniformBuffer

createUniformBuffer(device, size, label = '')

Summary: Create uniform buffer with proper padding


generateWGSLStruct

Summary: Generate WGSL struct definition from layout


Summary: Uniform buffer alignment (must be 16 bytes)


Summary: Storage buffer preferred alignment (4 bytes min, 16 for performance)


Summary: Indirect dispatch buffer alignment


Summary: Minimum workgroup size for good occupancy


Summary: Maximum workgroup size (WebGPU limit)


Summary: WebGPU/WGSL has no native atomicAdd for f32. Solution: Scale floats to integers, use atomicAdd on i32, then descale. FIXED_SCALE = 10000 gives us: - 4 decimal places of precision - Range: ±214,748 (i32 max / 10000) - Good for velocities, forces, densities


Summary: High precision scale for positions (6 decimal places) Range: ±2147 units - use only for local coordinates


Summary: MLS-MPM Particle SoA Layout Buffer 0: Position + Mass (vec4f) - 16 bytes [x, y, z, mass] Buffer 1: Velocity + Padding (vec4f) - 16 bytes [vx, vy, vz, pad] Buffer 2: Deformation Gradient (mat3x3f) - 48 bytes Row-major 3x3 matrix for plasticity Buffer 3: Affine Momentum (mat3x3f) - 48 bytes APIC affine velocity field Total per particle: 128 bytes


Summary: MLS-MPM Grid Cell Layout (Fixed-Point for Atomics) Each cell stores accumulated values from P2G scatter. Uses atomic<i32> for thread-safe accumulation. Momentum: vec3 as 3x atomic<i32> - 12 bytes [mom_x, mom_y, mom_z] (fixed-point scaled) Mass: atomic<i32> - 4 bytes (fixed-point scaled) Total per cell: 16 bytes (nicely aligned)


Summary: Grid velocity output (after grid update) Standard f32 for reading in G2P


Summary: FDTD Electromagnetic Field Cell Electric Displacement D: vec3f - 12 bytes (padded to 16) Magnetic Induction B: vec3f - 12 bytes (padded to 16) Permittivity ε: f32 - 4 bytes Permeability μ: f32 - 4 bytes Padding: 8 bytes Total: 48 bytes per cell


Summary: Phasor Ray Layout Position: vec3f - 12 bytes (padded to 16) Direction: vec3f - 12 bytes (padded to 16) Amplitude, Frequency, Phase, Pad: vec4f - 16 bytes Total: 48 bytes per ray


Summary: Indirect dispatch buffer layout


Summary: Indirect draw buffer layout (for instanced rendering)


Summary: Dirty chunk entry for conditional dispatch


Summary: Dirty flags bitmask


core/gpu/BufferPool

Summary: GPU Buffer Pool - Zero-allocation buffer recycling Eliminates per-frame buffer creation overhead


StagingBufferRing

Summary: Ring buffer for staging data - eliminates mapAsync stalls


core/gpu/ComputeBatchSystem

Summary: Compute Batch System - Parallel GPU compute with indirect dispatch Enables dynamic workgroup sizing and batched compute operations


core/gpu/DynamicUniformBuffer

Summary: DynamicUniformBuffer.js - Self-sizing uniform buffer from WGSL struct Pass in your WGSL struct definition (the same string embedded in your shader) and this class handles: - Parsing field names, types, and byte offsets (with correct WGSL alignment) - Creating the GPU buffer at exactly the right size - Typed CPU-side Float32Array + Uint32Array views - Named setters: buf.set('sunDir', [0.2, -1.0, 0.1]) - Bulk setter: buf.setAll({ viewProj: mat, cameraPos: [x,y,z] }) - Single upload() call to push to GPU Usage: const frame = new DynamicUniformBuffer(device, `struct FrameUniforms { viewProj: mat4x4<f32>, cameraPos: vec3<f32>, time: f32, sunDir: vec3<f32>, sunIntensity: f32, }`, 'MyFrame'); frame.set('viewProj', viewProjMatrix); frame.set('cameraPos', [x, y, z]); frame.set('sunDir', lightManager.sunDirection); frame.set('sunIntensity', 1.85); frame.upload(); // Or bulk: frame.setAll({ viewProj: mat, cameraPos: pos, sunDir: dir, sunIntensity: 1.0 }); frame.upload(); // Use in bind group: { binding: 0, resource: { buffer: frame.buffer } }


core/gpu/GPUPageAllocator

Summary: GPUPageAllocator - Virtual heap for GPU memory


Summary: WGSL shader helper for page indirection


core/gpu/GPUProfiler

Summary: GPUProfiler - Timestamp query-based GPU profiling


core/gpu/GPURandom

Summary: RNG state wrapper for sequential random number generation


DeterministicRNG

Summary: Deterministic RNG for multiplayer synchronization. All clients with the same seed produce identical sequences. Usage: - World generation: seed with worldSeed + chunkCoords - AI decisions: seed with entityId + gameTick - Combat rolls: seed with attackerId + defenderId + gameTick - Loot drops: seed with containerId + gameTick


pcgHash

Summary: PCG hash function - high quality, fast


Summary: Hash 2D coordinates


Summary: Hash 3D coordinates


initRngState

initRngState(pixelX, pixelY, frame, sampleIdx = 0)

Summary: Initialize RNG state for deterministic per-pixel random


accumulationWeight

Summary: Calculate accumulation weight for progressive rendering


accumulateColor

Summary: Accumulate color over frames (progressive rendering)


accumulateEMA

Summary: Exponential moving average accumulation (real-time, non-converging)


wavelengthToRGB

Summary: Convert wavelength (nm) to RGB color


spectralHeatMap

Summary: Map normalized value to spectral color (violet to red)


countToSpectral

Summary: Map count to spectral color with cutoff


blueNoiseOffset

Summary: Generate blue noise sample offset for a pixel Uses R2 sequence (generalized golden ratio) for low-discrepancy sampling


Summary: R2 sequence for 3D sampling (quasi-random, low discrepancy)


halton

Summary: Halton sequence for quasi-random sampling


Summary: 2D Halton sequence


Summary: 3D Halton sequence


Summary: WGSL code for PCG hash and random number generation Include this in your compute shaders for high-quality randomness


Summary: WGSL snippet for jittered sampling in TAA


Summary: WGSL snippet for stratified sampling


Summary: WGSL code for multiplayer-deterministic random Seeds with tick + entityId for synchronized random across clients


core/gpu/GPUTimestampProfiler

Summary: GPUTimestampProfiler - Precise GPU timing using timestamp queries. Requires the optional `timestamp-query` feature.


core/gpu/GpuBuffer


createVertexBuffer

createVertexBuffer(device, data, options = {})


createIndexBuffer

createIndexBuffer(device, data, options = {})


createUniformBuffer

createUniformBuffer(device, byteSize, options = {})


createStorageBuffer

createStorageBuffer(device, byteSizeOrData, options = {})


updateBuffer

updateBuffer(device, buffer, data, offsetBytes = 0)


core/gpu/GpuCanvas


createCanvasContext

createCanvasContext(gpuDevice, canvas, options = {})


core/gpu/GpuDebug


core/gpu/GpuDevice

Summary: Detect GPU platform/browser for per-browser workarounds. WebGPU browser support (Feb 2026): Chrome/Edge 113+ — Win (D3D12), Mac (Metal), ChromeOS (Vulkan) Chrome 121+      — Android 12+ Qualcomm/ARM (Vulkan) Chrome 144+      — Linux Intel Gen12+ (Vulkan), expanding to AMD/NVIDIA See: https://developer.chrome.com/blog/new-in-webgpu-144#webgpu_on_linux Firefox 141+     — Windows (wgpu/Rust backend) Firefox 145+     — macOS ARM64 (wgpu/Rust); Linux/Android expected 2026 Safari 26+       — macOS Tahoe, iOS 26, iPadOS 26, visionOS 26 (Metal) Samsung Internet 24+ — Android (Chromium/Dawn) GPU API backends per OS (Chromium/Dawn): Windows  → D3D12     (SharedTextureMemory D3D11 swap chain bug) macOS    → Metal Linux    → Vulkan    (rest of Chromium stays on OpenGL) Android  → Vulkan    (OpenGL ES compat mode via Chrome 135+ flag) ChromeOS → Vulkan See: https://caniuse.com/webgpu https://github.com/gpuweb/gpuweb/wiki/Implementation-Status


core/gpu/GpuFormats


core/gpu/GpuFrameBudgetBroker

Summary: Dependency-safe frame admission for long compute submissions. The broker never reorders command buffers. Callers await admission, then submit immediately to the one WebGPU queue, preserving queue dependencies. Render-critical work bypasses the budget; interactive/background compute is spread across animation frames so a long producer cannot monopolize the GPU.


core/gpu/GpuInit

Summary: Initialize WebGPU and populate GPU state object.


isWebGpuSupported

Summary: Check if WebGPU is supported.


waitForCanvasReady

Summary: Wait for canvas to be properly sized before GPU init.


core/gpu/GpuMetrics


recordBufferCreate

recordBufferCreate(byteSize, usageKind = "other")


core/gpu/GpuPassGraph


core/gpu/GpuRecovery

Summary: GpuRecovery.js — Automatic GPU device loss recovery (cross-browser) Handles the full lifecycle of device loss and recovery: 1. Detects device loss (unexpected crash vs intentional destroy) 2. Attempts automatic recovery with exponential backoff 3. Reconfigures canvas context with the new device 4. Fires callbacks so the app can re-upload resources 5. Shows user notification if recovery fails Based on: https://toji.dev/webgpu-best-practices/device-loss.html Browser support: Chrome 113+ (Win/Mac/ChromeOS), 121+ (Android), 144+ (Linux) Firefox 141+ (Windows), 145+ (macOS ARM64) — wgpu/Rust backend Safari 26+ (macOS Tahoe, iOS 26, iPadOS 26, visionOS 26) — Metal backend Chrome crash limits: - 1st crash: adapter available immediately - 2nd crash within 2 min: adapter blocked for that page - 3rd crash within 2 min: all pages blocked - 3-6 crashes in 5 min: GPU process stops entirely Firefox/Safari: crash limits are different/unknown — recovery still works. device.lost reason values: Chrome: 'destroyed' (intentional) or 'unknown' (crash) Firefox/Safari: may use 'destroyed' or '' — we check for 'destroyed' only


createRecoveryOverlay

Summary: Create a user-facing recovery notification overlay. Shows status during recovery and a "please refresh" message on failure.


core/gpu/GpuSampler


core/gpu/GpuTexture


createColorTexture

createColorTexture(device, width, height, options = {})


createSampledTexture2D(device, width, height, options = {})


createDepthTexture

createDepthTexture(device, width, height, options = {})


resizeAttachmentTexture

resizeAttachmentTexture(device, handle, width, height)


core/gpu/GpuTextureLoader


loadTextureFromUrl

async loadTextureFromUrl(device, url, options = {})


createTextureFromKtx2Data(device, data, options = {})


async createTextureFromKtx2DataWithDecoder(device, data, options = {})


async loadKtx2TextureFromUrl(device, url, options = {})


inspectKtx2TextureData(data, options = {})


async inspectKtx2TextureFromUrl(url, options = {})


createTextureFromImage

async createTextureFromImage(device, image, options = {})


createTextureFromImageBitmap

async createTextureFromImageBitmap(device, bitmap, options = {})


core/gpu/GpuTransfer

Summary: Upload data to a GPU buffer via a transient staging buffer. Useful for large or streaming uploads when you want explicit control over copy operations rather than relying solely on queue.writeBuffer.


uploadBufferWithStaging

async uploadBufferWithStaging(device, dstBuffer, data, dstOffsetBytes = 0, label = "gpu_staging_upload")


async readBufferToUint8Array(device, srcBuffer, byteOffset, byteLength, label = "gpu_readback_buffer")

Summary: Read back the contents of a GPU buffer into a Uint8Array. Intended for debugging and tooling, not per-frame critical paths.


async readTexture2D(device, srcTexture, width, height, { bytesPerPixel, mipLevel = 0, label = "gpu_readback_texture2d", })

Summary: Read a 2D texture into a buffer for debugging. Caller must provide bytesPerPixel for the chosen format. Returns an object with the raw data and layout information.


core/gpu/IndirectDispatchGen

Summary: IndirectDispatchGen.js - GPU-Driven Indirect Dispatch Generation Problem: CPU deciding which chunks to process creates a bottleneck. The GPU knows best which chunks need work (from dirty flags, visibility, etc.) but standard dispatch requires CPU to specify workgroup counts. Solution: GPU-side stream compaction + indirect dispatch. 1. GPU scans all chunks, compacts active ones into a list 2. GPU writes workgroup counts to indirect buffer 3. CPU issues dispatchWorkgroupsIndirect() - no readback needed Key Technique: Hierarchical atomics for efficient compaction - Each workgroup uses local atomic to count active items - Leader thread reserves global block via global atomic - Threads scatter their items to reserved slots Performance: Eliminates CPU-GPU sync for conditional dispatch


MultiPassDispatchGen

Summary: Generates multiple indirect dispatches for different job types (e.g., separate geometry, lighting, physics passes)


Summary: Workgroup size for generator shader


Summary: Maximum jobs that can be generated per dispatch


Summary: Indirect dispatch buffer size (3 × u32 = 12 bytes)


ktx2VkFormatInfo(vkFormat = 0, supportedFeatures = null)


ktx2PayloadPlan(containerOrData, options = {})


getKtx2SectionPayloadView(data, section = 'sgd')


createKtx2PayloadDecodeRequest(data, options = {})


ktx2DirectUploadPlan(containerOrData, options = {})


getKtx2LevelPayloadView(data, level = 0)


core/gpu/MappedBufferWriter

Summary: Mapped Buffer Writer - Eliminates double-copy overhead from writeBuffer() Based on WebGPU optimization best practices from webgpufundamentals.org Saves one CPU→GPU copy per upload (10-20% faster uploads)


UniformBufferWriter

class UniformBufferWriter extends MappedBufferWriter

Summary: Uniform Buffer Writer - Optimized for frequent uniform updates


core/gpu/OptimizationIntegration

Summary: Enhanced GPU Device wrapper with all optimizations


OptimizationHelpers

Summary: Quick optimization helper functions


core/gpu/PipelineCache

Summary: Next-gen pipeline cache with IndexedDB persistence and background compilation Eliminates ALL pipeline creation stalls


core/gpu/ProgressiveWorkBudget

Summary: Plans optional refinement from measured spare GPU time. It never delays the host frame, submits work, or changes correctness-critical work.


core/gpu/ShaderCompilationQueue

Summary: Async Shader Compilation Queue - Priority-based background compilation Eliminates frame stalls from shader compilation


core/gpu/SimulationProfiler

Summary: SimulationProfiler.js - GPU Timestamp Profiling for Simulation Systems Provides detailed GPU timing information for: - Voxel collision passes - Rope physics passes - Rope rendering passes - Particle simulation passes Uses WebGPU timestamp queries for accurate GPU-side timing.


profiledComputePass

profiledComputePass(profiler, encoder, name, fn)

Summary: Profiled compute pass helper Wraps a compute pass with automatic start/end timestamps


createSimulationProfiler

createSimulationProfiler(device, options = {})

Summary: Create a simulation profiler instance


ProfileSections

Summary: Pre-defined section names for consistency


core/gpu/SparsePageRuntime

Summary: Device-independent, revisioned sparse residency contract shared by field, voxel-derived, and texture pages. A commit is atomic: validation, fallback closure, slot allocation, and eviction all finish before publication.


core/gpu/TextureAtlasManager

Summary: Texture Atlas Manager - Dynamic texture packing for GPU memory optimization Reduces texture bindings and improves cache coherency


core/gpu/VGPUBindGroupManager

Summary: Automatic Bind Group Manager - Material system that auto-generates bind groups from shader


core/gpu/VGPUBindless

Summary: Bindless Preparation - Storage buffer texture arrays for bindless-style rendering


core/gpu/VGPUComputeUtils


core/gpu/VGPUDebugDraw

Summary: Debug Draw System with dynamic buffer sizing


DebugDrawScope

Summary: Scoped debug drawing (auto-clears when scope ends)


core/gpu/VGPUHiZCulling

Summary: Hierarchical-Z Occlusion Culling System


VGPUHiZCulling

Summary: Hierarchical-Z Occlusion Culling System


BoundingBoxBuilder

Summary: Helper to build bounding box data for HiZ culling Grows dynamically - no fixed maximum.


core/gpu/VGPUIndirectRenderer

Summary: GPU-driven indirect renderer with dynamic buffer sizing


IndirectInstanceBuilder

Summary: Helper to build instance data for indirect rendering Grows dynamically - no fixed maximum.


core/gpu/VGPUMemoryTracker

Summary: Memory Budget Tracker - Track GPU memory usage, warn on budget exceeded Also provides GPU memory probing to detect available VRAM


core/gpu/VGPUMultiQueue

Summary: Multi-Queue Abstraction - Separate graphics/compute/transfer queues when available


core/gpu/VGPUQualityScaler

Summary: Quality Scaler - Dynamic resolution/quality based on frame time budget


VGPUDynamicViewport

Summary: Viewport manager for dynamic resolution


core/gpu/VGPUReadbackQueue

Summary: GPU Readback Queue - Async buffer/texture reads with callbacks Batches staging buffers for efficient GPU→CPU data transfer


core/gpu/VGPURenderGraph

Summary: Main Render Graph class


VGPURenderGraph

Summary: Main Render Graph class


RenderGraphBuilder

Summary: Builder pattern for ergonomic graph construction


core/gpu/VGPURenderStats

Summary: Render Statistics - Draw call counts, triangle counts, state changes per frame


VGPUStatsOverlay

Summary: Stats overlay for debug display


core/gpu/VGPUResourceBarriers

Summary: Resource Barriers Helper - Explicit sync points for complex resource dependencies


core/gpu/VGPUShaderReflection

Summary: Shader Reflection - Parse WGSL to extract bindings, uniforms, entry points


getStructBufferSize

Summary: Get the required buffer size for a uniform struct in a shader. Automatically calculates correct WGSL alignment.


getUniformBufferSizes

Summary: Get buffer sizes for all uniform bindings in a shader.


createAutoSizedUniformBuffer

createAutoSizedUniformBuffer(device, shaderSource, structName, options = {})

Summary: Create a uniform buffer with automatically calculated size from shader struct.


validateBufferSize

Summary: Validate that a buffer meets the minimum size requirement for a shader struct.


debugShaderStructs

Summary: Get all struct sizes in a shader for debugging.


core/gpu/VGPUStreamingManager

Summary: VGPUStreamingManager - Progressive resource loading and streaming Features: - Priority-based loading queue with distance/importance weighting - Async texture streaming with mip-level progression - Mesh LOD streaming - Memory budget management - Placeholder resources while loading - Automatic eviction of unused resources Usage: const streaming = new VGPUStreamingManager(vgpu); await streaming.init({ memoryBudget: 512 * 1024 * 1024 }); const textureHandle = streaming.requestTexture('path/to/texture.png', { priority: 1.0 }); const texture = streaming.getTexture(textureHandle); // Returns placeholder until loaded


VGPUStreamingManager

Summary: Main Streaming Manager


core/gpu/VGPUTextureAtlas

Summary: Texture Atlas Manager - Dynamic packing for sprites/UI, automatic UV remapping


VGPUSpriteBatch

Summary: Sprite batch renderer using texture atlas


core/gpu/VGPUTimelineSemaphores

Summary: GPU Timeline Semaphores - Advanced sync for multi-engine scenarios


core/gpu/VirtualGPU

Summary: Get or create the global vGPU instance


getVGPU

Summary: Get or create the global vGPU instance


vgpu

Summary: Get existing vGPU instance (throws if not initialized)


initVGPU

Summary: Initialize vGPU from existing GpuDevice or raw GPUDevice


core/gpu/WGSLPreprocessor

Summary: WGSL Preprocessor - #include, #define, #ifdef support for shader modularity


createPreprocessor

Summary: Create a preprocessor with common includes registered


core/gpu/WGSLStructLayout

Summary: WGSLStructLayout.js - Unified WGSL/JS Struct Layout Generator Parses WGSL struct definitions and generates: - Correct buffer sizes with WebGPU alignment - JS field offset maps for TypedArray access - Accessor helper classes for reading/writing struct data This ensures WGSL and JS stay perfectly in sync - define once in WGSL, use the generated layout in JS. Usage: const layout = parseWGSLStruct(` struct Params { dt: f32, particleCount: u32, roomHalfSize: f32, gravityY: f32, } `); // layout.size = 16 (bytes) // layout.fields = { dt: {offset: 0, size: 4}, particleCount: {offset: 4, size: 4}, ... } const accessor = createStructAccessor(layout); const data = new Float32Array(layout.size / 4); accessor.set(data, 'dt', 0.016); accessor.set(data, 'particleCount', 1000); // auto-converts to u32


parseWGSLStruct

Summary: Parse a WGSL struct definition and compute field layout


createStructAccessor

Summary: Create an accessor object for reading/writing struct fields


defineStruct

Summary: Define a struct layout from WGSL and return both layout and accessor


generateJSLayout

Summary: Generate JS object literal layout definition from WGSL struct Useful for documentation or code generation


validateBuffer

validateBuffer(buffer, layout, expectedCount = 1)

Summary: Validate that a buffer matches the expected struct layout


core/gpu/WGSLStructSize

Summary: Calculate the total size of a WGSL struct with proper alignment


createUniformBuffer

createUniformBuffer(device, structCode, label = 'Uniform Buffer')

Summary: Create a uniform buffer with automatically calculated size


createStorageBuffer

createStorageBuffer(device, structCode, count = 1, label = 'Storage Buffer')

Summary: Create a storage buffer with automatically calculated size


Summary: Get the Float32Array size needed to fill a struct buffer


validateBufferSize

validateBufferSize(bufferSize, structCode, label = '')

Summary: Validate a buffer size against a struct definition


core/gpu/WebGpuCanvasBootstrap


core/gpu/index

Summary: engine/core/gpu/index.js - GPU Utilities Barrel Export


core/index


core/math/AnimationTimeMath

Summary: AnimationTimeMath.js - pure animation timing, keyframe, and sampler reports.


animationActiveDuration

animationActiveDuration(iterationDuration, iterationCount = 1)


animationWrapTime

animationWrapTime(time, duration, options = {})


animationPlaybackStateReport

animationPlaybackStateReport(value = {}, options = {})

Summary: Validate and normalize the serializable state of one animation player.


animationTimeScaleReport

animationTimeScaleReport(time, options = {})


animationOpenUsdLayerOffsetReport

animationOpenUsdLayerOffsetReport(timeCode, options = {})


animationOpenUsdTimeSampleBracket

animationOpenUsdTimeSampleBracket(times, timeCode, options = {})


animationOpenUsdSampleValue

animationOpenUsdSampleValue(times, values, timeCode, options = {})


animationKeyframeBracket

animationKeyframeBracket(times, time, options = {})


animationCubicSplineSample

animationCubicSplineSample(v0, outTangent0, v1, inTangent1, t, duration = 1, options = {})


animationSampleChannel

animationSampleChannel(times, values, time, options = {})


animationSampleChannelInto

animationSampleChannelInto(times, values, time, out, outOffset = 0, options = {})


animationClipSampleTimeReport

animationClipSampleTimeReport(time, options = {})


animationKeyframeReductionReport

animationKeyframeReductionReport(times, values, options = {})


core/math/AudioAutomationMath

Summary: AudioAutomationMath.js - pure AudioParam automation, envelope, and biquad helper math.


audioAutomationLinearRampValue

audioAutomationLinearRampValue(startValue, endValue, startTime, endTime, time)


audioAutomationExponentialRampValue

audioAutomationExponentialRampValue(startValue, endValue, startTime, endTime, time)


audioAutomationSetTargetValue

audioAutomationSetTargetValue(initialValue, targetValue, startTime, timeConstant, time)


audioAutomationValueCurveAtTime

audioAutomationValueCurveAtTime(curve, startTime, duration, time, options = {})


audioAdsrEnvelopeValue

audioAdsrEnvelopeValue(time, options = {})


audioBiquadComputedFrequency

audioBiquadComputedFrequency(frequency = 350, detune = 0, sampleRate = 48000)


audioBiquadCoefficients

audioBiquadCoefficients(type = 'lowpass', options = {})


audioBiquadFrequencyResponse

audioBiquadFrequencyResponse(coefficients, frequencyHz, sampleRate = coefficients?.sampleRate ?? 48000)


core/math/AudioMath

Summary: AudioMath.js - pure PCM/audio-domain math helpers.


audioApplyGain

audioApplyGain(signal, gain = 1, options = {})


audioWindowedRmsReport

audioWindowedRmsReport(signal, windowSize, hopSize = windowSize)


audioSilenceReport

audioSilenceReport(signal, options = {})


audioNoiseFloorReport

audioNoiseFloorReport(signal, options = {})


audioTransientReport

audioTransientReport(signal, options = {})


audioSpectralEntropyReport

audioSpectralEntropyReport(spectrum, options = {})


audioAnalyserByteToDb

audioAnalyserByteToDb(byteValue, minDb = DEFAULT_AUDIO_MIN_DB, maxDb = DEFAULT_AUDIO_MAX_DB)


audioDecibelsToAnalyserByte

audioDecibelsToAnalyserByte(db, minDb = DEFAULT_AUDIO_MIN_DB, maxDb = DEFAULT_AUDIO_MAX_DB)


core/math/BVHAccel

Summary: BVH Node - 32 bytes aligned for GPU If triCount == 0: internal node, leftChild_Or_FirstTri = left child index If triCount > 0: leaf node, leftChild_Or_FirstTri = first triangle index


BVHBuilder

Summary: Build BVH from triangle mesh Uses Surface Area Heuristic for optimal splits


rayTriangleIntersect

rayTriangleIntersect(origin, dir, tri, tMax = INF_T)

Summary: Möller-Trumbore ray-triangle intersection


traverseBVH

traverseBVH(origin, dir, nodes, triIndices, triangles)

Summary: Traverse BVH and find closest intersection


serializeBVHForGPU

Summary: Serialize BVH for GPU buffer upload


createRaycastMesh

Summary: Create raycastable mesh from vertices and indices


core/math/BenchmarkMath

Summary: BenchmarkMath.js - reusable benchmark rate, memory, compression, and cost estimates.


durationReport

durationReport(startMs, endMs, options = {})


core/math/BezierCurves

Summary: Cubic Bezier curve defined by 4 control points


straightLine

Summary: Create a straight line as a degenerate Bezier


arc

arc(center, radius, startAngle, endAngle, tubeRadius = 1.0)

Summary: Create an arc approximation using Bezier


core/math/BezierDistance

Summary: GPU-accelerated Bezier distance field computation


sdCapsule

Summary: Signed distance to a capsule (line segment with radius)


capsuleClosestT

Summary: Find closest point parameter on capsule


bezierDistanceCapsule

bezierDistanceCapsule(p, curve, segments = 16)

Summary: Distance to Bezier using capsule chain approximation Fast but may miss fine details for highly curved sections


bezierDistanceBatch

bezierDistanceBatch(points, curve, segments = 16)

Summary: Batch distance query for multiple points


bezierClosestNewton

bezierClosestNewton(p, curve, initialT = 0.5, iterations = 8)

Summary: Find closest point on Bezier using Newton-Raphson iteration Minimizes |B(t) - p|² by finding roots of d/dt|B(t)-p|²


bezierDistanceHybrid

bezierDistanceHybrid(p, curve, capsuleSegments = 8, newtonIterations = 4)

Summary: Hybrid: Capsule for initial guess, Newton for refinement Best balance of speed and accuracy


multiCurveDistance

multiCurveDistance(p, curves, segments = 16)

Summary: Distance to multiple Bezier curves (smooth union)


smin

Summary: Smooth minimum of two distances (for blending)


multiCurveDistanceSmooth

multiCurveDistanceSmooth(p, curves, smoothness = 0.5)

Summary: Distance to curves with smooth blending


curvesToGPUBuffer

Summary: Prepare curve data for GPU upload Format: 4 vec4s per curve = 64 bytes [p0.xyz, 0] [p1.xyz, 0] [p2.xyz, 0] [p3.xyz, radius]


curvesToSegments

curvesToSegments(curves, segmentsPerCurve = 8)

Summary: Pre-sample curves into line segments for GPU More efficient for many queries


core/math/BlendMath


alphaBlend

alphaBlend(backdrop, source, opacity = 1)


premultipliedAlphaBlend

premultipliedAlphaBlend(backdrop, source, opacity = 1)


blendModeChannel

blendModeChannel(backdrop, source, mode = 'normal')


blendRgb

blendRgb(backdrop, source, mode = 'normal')


blendCompositeStraight

blendCompositeStraight(backdrop, source, mode = 'normal', opacity = 1)


coverageAlpha

coverageAlpha(coveredSamples, sampleCount = 1)


ditherAlpha

ditherAlpha(alpha, x = 0, y = 0, frame = 0)


core/math/BufferMath

Summary: BufferMath.js - reusable byte views, endian-safe DataView reads/writes, UTF-8 helpers, and cursors.


bufferRangeReport

bufferRangeReport(data, byteOffset = 0, byteLength = 0, options = {})


bufferRead

bufferRead(data, type, byteOffset, options = {})


bufferWrite

bufferWrite(data, type, byteOffset, value, options = {})


bufferReadUtf8(data, byteOffset, byteLength, options = {})


bufferWriteUtf8(data, byteOffset, text, options = {})


createBufferCursor

createBufferCursor(dataOrByteLength, options = {})


core/math/ChannelMath

Summary: ChannelMath.js - reusable channel geometry, spacing, hopset, and planning reports.


channelCenterFromIndex

channelCenterFromIndex(index, options = {})


channelIndexFromCenterReport

channelIndexFromCenterReport(centerHz, options = {})


wifi24ChannelReport(channelNumber, options = {})


channelBandMembershipReport

channelBandMembershipReport(channel, bands = [], options = {})


channelGuardBandReport

channelGuardBandReport(aChannel, bChannel, options = {})


channelHopsetReport

channelHopsetReport(channels = [], options = {})


channelInterferenceReport

channelInterferenceReport(candidateChannel, interferers = [], options = {})


channelPlanReport

channelPlanReport(candidates = [], interferers = [], options = {})


core/math/ChecksumMath

Summary: ChecksumMath.js - reusable byte checksums, non-crypto hashes, rolling hashes, and digest wrappers.


fnv1a32(data, seed = FNV1A32_OFFSET_BASIS)


fnv1a64(data, seed = FNV1A64_OFFSET_BASIS)


fnv1aStringCodeUnit32(data, options = {})


fnv1aStringCodePointHead32(data, options = {})


fnv1aLowByteString32(data, options = {})


fnv1aTaggedFloat32Sequence32(values, options = {})


fnv1aTaggedUint32Sequence32(values, options = {})


legacyAvalancheMixUint32Hash32(hash, value, multiplier = 0x9e3779b1)


fnv1aUint32Sequence32(values, options = {})


fnv1aInt32Sequence32(values, options = {})


legacyFnv1aByteSequenceHash32(data, options = {})


legacyFnv1aNumberSequenceHash32(values, seed = FNV1A32_OFFSET_BASIS)


legacyFnv1aStringHash32(data, seed = FNV1A32_OFFSET_BASIS)


legacyDjb2XorStringHash32(data, seed = 5381)


legacyUnsignedStringHash31(data, seed = 0)


legacyScaledNumberSequenceHash32(values, options = {})


bufferHash

bufferHash(data, algorithm = CHECKSUM_ALGORITHMS.crc32)


rollingHash32(data, windowSize, options = {})


contentHashBytes

async contentHashBytes(data, algorithm = CHECKSUM_ALGORITHMS.sha256)


contentHashHex

async contentHashHex(data, algorithm = CHECKSUM_ALGORITHMS.sha256)


core/math/CompressionMath

Summary: CompressionMath.js - pure compression primitive reports and planning helpers.


compressionRunLengthReport

compressionRunLengthReport(values, options = {})


compressionDeltaReport

compressionDeltaReport(values, options = {})


compressionPaletteReport

compressionPaletteReport(values, options = {})


compressionVarintReport

compressionVarintReport(values, options = {})


compressionEntropyPlan

compressionEntropyPlan(data, options = {})


compressionHuffmanLengthReport

compressionHuffmanLengthReport(values, options = {})


compressionRangeModelReport

compressionRangeModelReport(values, options = {})


compressionDictionaryMatchReport

compressionDictionaryMatchReport(values, options = {})


compressionPrimitivePlan

compressionPrimitivePlan(values, options = {})


core/math/CongestionMath

Summary: CongestionMath.js - reusable congestion-window, pacing, Reno, QUIC, and CUBIC report helpers.


renoSlowStartIncreaseBytes

renoSlowStartIncreaseBytes(acknowledgedBytes, smssBytes = CONGESTION_DEFAULT_MAX_DATAGRAM_BYTES)


renoCongestionAvoidanceIncreaseBytes

renoCongestionAvoidanceIncreaseBytes(congestionWindowBytes, smssBytes = CONGESTION_DEFAULT_MAX_DATAGRAM_BYTES)


core/math/ConstraintMath

Summary: ConstraintMath.js - pure joint limit, drive, spring, and projection reports.


constraintNormalizeAngle

constraintNormalizeAngle(angle, options = {})


constraintAngularLimitReport

constraintAngularLimitReport(angle, lowerLimit, upperLimit, options = {})


constraintAxisStateReport

constraintAxisStateReport(value, options = {})


constraintConeLimitReport

constraintConeLimitReport(swingY, swingZ, limitY, limitZ, options = {})


constraintSwingTwistLimitReport

constraintSwingTwistLimitReport(rotation, twistAxis = [1, 0, 0], options = {})


constraintMotorTargetErrorReport

constraintMotorTargetErrorReport(current, target, options = {})


constraintJointProjectionErrorReport

constraintJointProjectionErrorReport(frameA = {}, frameB = {}, options = {})


core/math/DOMGeometryMath

Summary: DOMGeometryMath.js - DOMPoint, DOMRect, DOMMatrix, and canvas coordinate helpers.


domRectNormalize

domRectNormalize(rect = {}, options = {})


domMatrixTransformPoint

domMatrixTransformPoint(point, matrixInit = IDENTITY_COLUMN_MAJOR_4)


domRectTransformBounds

domRectTransformBounds(rect, matrixInit = IDENTITY_COLUMN_MAJOR_4, options = {})


domQuadBoundsReport

domQuadBoundsReport(quad = {}, options = {})


domQuadTransformBounds

domQuadTransformBounds(quad = {}, matrixInit = IDENTITY_COLUMN_MAJOR_4, options = {})


canvasBackingStoreReport

canvasBackingStoreReport(cssWidth, cssHeight, devicePixelRatio = 1, options = {})


domScrollCoordinateReport

domScrollCoordinateReport(point = {}, viewport = {}, options = {})


canvasPointerCssPoint

canvasPointerCssPoint(event = {}, rect = {}, options = {})


canvasPointerWorldPoint

canvasPointerWorldPoint(event = {}, rect = {}, matrixInit = IDENTITY_COLUMN_MAJOR_4, options = {})


canvasPointerDevicePoint

canvasPointerDevicePoint(event = {}, rect = {}, canvasOrScale = {}, options = {})


core/math/EngineMath

Summary: EngineMath - basic 3D vector and matrix helpers shared across engine and tests Pure math, no rendering or platform side effects.


mat4PerspectiveRad(fovRad, aspect, near, far)


mat4PerspectiveRadWebGPU(fovRad, aspect, near, far)


mat4PerspectiveDeg(fovDeg, aspect, near, far)


mat4PerspectiveDegWebGPU(fovDeg, aspect, near, far)


mat4Orthographic(left, right, bottom, top, near, far)


mat4OrthographicWebGPU(left, right, bottom, top, near, far)


core/math/FilterMath

Summary: FilterMath.js - reusable filter kernel, signal FIR, and CPU RGBA convolution helpers.


filterKernelReport

filterKernelReport(kernel, options = {})


normalizeFilterKernel

normalizeFilterKernel(kernel, targetSum = 1, options = {})


boxFilterKernel1D(radius = 1, options = {})


gaussianFilterKernel1D(radius = 1, sigma = null)


gaussianFilterKernel2D(radius = 1, sigma = null)


filterSignalFIR

filterSignalFIR(signal, kernel, options = {})


filterSignalMedian

filterSignalMedian(signal, windowSize = 3)


filterSignalTemporalSmooth

filterSignalTemporalSmooth(signal, alpha = 0.5)


filterSignalNoiseReduce

filterSignalNoiseReduce(signal, options = {})


filterImageConvolutionRgba

filterImageConvolutionRgba(image, kernelSpec, options = {})


filterImageMorphologyRgba

filterImageMorphologyRgba(image, operator = 'dilate', radius = 1, options = {})


filterImageDilateRgba

filterImageDilateRgba(image, radius = 1, options = {})


filterImageErodeRgba

filterImageErodeRgba(image, radius = 1, options = {})


core/math/FormatMath

Summary: FormatMath.js - reusable signatures, MIME helpers, SemVer, text ranges, token cursors, and chunk tables.


formatMimeFromExtension

formatMimeFromExtension(pathOrExtension, fallback = DEFAULT_MIME_TYPE)


formatAcceptMatchReport

formatAcceptMatchReport(file, accept, options = {})


formatAcceptHeaderReport

formatAcceptHeaderReport(acceptHeader, offeredMimeTypes, options = {})


semanticVersionRangeReport

semanticVersionRangeReport(version, range = '*')


formatCompatibilityReport

formatCompatibilityReport(candidate, requirements = {}, options = {})


core/math/FrameMath

Summary: FrameMath.js - pure ImageData-like frame and temporal media math helpers.


frameDifferenceReport

frameDifferenceReport(referenceFrame, candidateFrame, options = {})


frameMotionMagnitudeMap

frameMotionMagnitudeMap(referenceFrame, candidateFrame, options = {})


frameResidualImage

frameResidualImage(referenceFrame, candidateFrame, options = {})


frameSceneChangeReport

frameSceneChangeReport(referenceFrame, candidateFrame, options = {})


frameKeyframeScoreReport

frameKeyframeScoreReport(referenceFrame, candidateFrame, options = {})


frameSequenceDifferenceReport

frameSequenceDifferenceReport(frames, options = {})


runtimeFrameDeltaSeconds

runtimeFrameDeltaSeconds(timestampMs, previousTimestampMs, maxDeltaSeconds = 0.1)


runtimeMonotonicClockStep

runtimeMonotonicClockStep(timestampMs, previousTimestampMs = 0)


core/math/ImageMath

Summary: ImageMath.js - deterministic RGBA/ImageData pixel helpers. These helpers intentionally operate on ImageData-like objects or raw RGBA array data. They do not construct browser ImageData, canvas, bitmap, or GPU resources, so they remain safe for workers and deterministic tests.


imagePixelOffset

imagePixelOffset(width, x, y, options = {})


imageReadPixel

imageReadPixel(image, x, y, options = {})


imageWritePixel

imageWritePixel(image, x, y, rgba, options = {})


imageSampleNearest

imageSampleNearest(image, x, y, options = {})


imageSampleBilinear

imageSampleBilinear(image, x, y, options = {})


imageCopyRect

imageCopyRect(image, rect = {}, options = {})


imageSwizzleRgba

imageSwizzleRgba(image, order = [0, 1, 2, 3], options = {})


imagePremultiplyAlpha

imagePremultiplyAlpha(image, options = {})


imageUnpremultiplyAlpha

imageUnpremultiplyAlpha(image, options = {})


imageHistogramReport

imageHistogramReport(image, options = {})


core/math/InputSignalMath

Summary: InputSignalMath.js - pure pointer/stylus sample shaping, smoothing, and prediction helpers.


inputAxisRemapReport

inputAxisRemapReport(axis, options = {})


inputRadialDeadzoneReport

inputRadialDeadzoneReport(axes, options = {})


inputPressureCurve

inputPressureCurve(pressure, options = {})


inputPressureReport

inputPressureReport(samples, options = {})


pointerTiltToAltitudeAzimuth

pointerTiltToAltitudeAzimuth(tiltX = 0, tiltY = 0)


pointerAltitudeAzimuthToTilt

pointerAltitudeAzimuthToTilt(altitudeAngle = HALF_PI, azimuthAngle = 0)


inputSampleVelocityReport

inputSampleVelocityReport(samples, options = {})


smoothInputSamples

smoothInputSamples(samples, options = {})


predictInputSample

predictInputSample(samples, lookaheadMs = 16.6666666667, options = {})


blendInputSamples

blendInputSamples(leftSample, rightSample, amount = 0.5, options = {})


inputStrokeStabilizationReport

inputStrokeStabilizationReport(samples, options = {})


core/math/JitterMath

Summary: JitterMath.js - packet delay variation, RTP/WebRTC jitter, and adaptive buffer reports.


jitterQualityScore

jitterQualityScore(jitterMs, options = {})


packetDelayVariationReport

packetDelayVariationReport(samplesMs = [], options = {})


rtpJitterUpdateReport

rtpJitterUpdateReport(previous = null, packet = {}, options = {})


rtpJitterReport

rtpJitterReport(packets = [], options = {})


adaptiveJitterEstimateUpdate

adaptiveJitterEstimateUpdate(previous = {}, intervalMs, options = {})


peerRttJitterReport

peerRttJitterReport(rttSamplesMs = [], options = {})


webRtcJitterBufferReport

webRtcJitterBufferReport(stats = {}, options = {})


core/math/LineToVoxel

Summary: Node in a line network (branch point or endpoint)


NetworkEdge

Summary: Edge connecting two nodes


LineNetwork

Summary: Network of connected curves for voxelization


LineToVoxelizer

Summary: Convert line network to voxel density field


GPULineVoxelizer

Summary: GPU-accelerated line network voxelizer


generateTree

Summary: Generate a simple tree structure


generateRoots

Summary: Generate root system


generateTunnel

Summary: Generate cave/tunnel network


Summary: Default voxel resolution


Summary: Blend radius for smooth junctions


Materials

Summary: Material IDs


core/math/LossyCompressionMath

Summary: LossyCompressionMath.js - pure transform, quantization, and reconstruction reports.


lossyZigZagIndices

lossyZigZagIndices(width = DEFAULT_BLOCK_WIDTH, height = DEFAULT_BLOCK_HEIGHT)


lossyQuantizeCoefficients

lossyQuantizeCoefficients(coefficients, quantization = 1)


lossyScalarQuantizationReport

lossyScalarQuantizationReport(values, options = {})


lossyResidualReport

lossyResidualReport(reference, candidate, options = {})


lossyBlockDctReport

lossyBlockDctReport(values, options = {})


core/math/MathBits

Summary: MathBits.js - Bit manipulation, Morton codes, Hilbert curves, hash functions Critical for voxel systems, spatial indexing, and procedural generation


legacyStructureSeededHash3D(x, y, z, seed)


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


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


legacyPrimeCoordinateAbsXorBucket3D(x, y, z, tableSize)


legacyPrimeCoordinateU32XorBucket3D(x, y, z, tableSize)


legacyPrimeCoordinateSignedAddAbsBucket3D(x, y, z, tableSize)


legacyPrimeAxisHash32(value, axis = 'x', modulo = 0)


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


legacySeedCharWeightedXorHash32(seed, charCode, seedMultiplier, charMultiplier)


legacyPcgPixelFrameHash2D(x, y, frameIndex, salt = 0)


legacyPcgPixelFrameRandom24Float01(x, y, frameIndex, salt = 0)


legacyDeterministicRngPositionSeed32(worldSeed, x, y, z)


legacyDeterministicRngInteractionSeed32(worldSeed, entityA, entityB, tick)


core/math/MathColor

Summary: MathColor.js - Color spaces and conversions RGB, HSL, HSV, LAB, LCH, OKLAB, OKLCH, hex, blend modes, gradients, palettes


linearRgbLuminance

linearRgbLuminance(color, coefficients = COLOR_LUMA_REC709)


toneMapReinhardExtended

toneMapReinhardExtended(color, whitePoint = 1)


colorContrastAdjust

colorContrastAdjust(color, amount = 1, pivot = 0.5)


colorSaturationAdjust

colorSaturationAdjust(color, amount = 1, coefficients = COLOR_LUMA_REC709)


colorDisplayTransformReport

colorDisplayTransformReport(color, options = {})


colorDisplayCapabilityReport

colorDisplayCapabilityReport(observed = {}, options = {})


canvasColorSettingsReport

canvasColorSettingsReport(settings = {}, observedAttributes = null)


canvasPixelReadbackReport

canvasPixelReadbackReport(settings = {}, observedReadback = {}, options = {})


canvasPixelReadbackCapabilityReport

canvasPixelReadbackCapabilityReport(cases = [], options = {})


canvasPixelReadbackPrecisionReport

canvasPixelReadbackPrecisionReport(cases = [], options = {})


cssRelativeColorReport

cssRelativeColorReport(value, options = {})


cssSystemColorReport

cssSystemColorReport(value, options = {})


cssSystemColorResolutionReport

cssSystemColorResolutionReport(systemColors = {}, options = {})


cssColorParseReport

cssColorParseReport(value, options = {})


colorContrastChoiceReport

colorContrastChoiceReport(background, candidates = [[0, 0, 0], [1, 1, 1]], options = {})


cssLightDarkColorReport

cssLightDarkColorReport(lightColor, darkColor, options = {})


paletteAnalogous

paletteAnalogous(baseHue, count = 5, spread = 30)


paletteSplitComplementary

paletteSplitComplementary(baseHue, spread = 30)


paletteMonochromatic

paletteMonochromatic(baseHue, count = 5)


core/math/MathConstants


core/math/MathDualQuat

Summary: MathDualQuat.js - Dual Quaternion operations for skinning & rigid body interpolation Dual quaternion = [real_x, real_y, real_z, real_w, dual_x, dual_y, dual_z, dual_w] Real part = rotation quaternion, Dual part encodes translation Used for: DQS (Dual Quaternion Skinning), rigid body interpolation, screw motion


dqCreate

dqCreate(rx, ry, rz, rw, dx, dy, dz, dw)


core/math/MathEasing

Summary: MathEasing.js - Easing functions, Bezier curves, splines For animation, UI transitions, and procedural motion


easeSpring

easeSpring(t, mass = 1, stiffness = 100, damping = 10)


easeSpringSimple

easeSpringSimple(t, bounces = 3, decay = 0.4)


cssCubicBezierValue

cssCubicBezierValue(x1, y1, x2, y2, progress)


cssStepEasing

cssStepEasing(progress, steps = 1, position = 'end', options = {})


cssEasingReport

cssEasingReport(easing, progress, options = {})


cssEasingValue

cssEasingValue(easing, progress, options = {})


catmullRomSpline

catmullRomSpline(points, t, closed = false)


computeArcLengthTable

computeArcLengthTable(curveFn, segments = 100)


bezier3DerivativeVec3(p0, p1, p2, p3, t)


core/math/MathEntropy

Summary: MathEntropy.js - histograms, entropy reports, and distribution diagnostics.


byteFrequencyHistogram

byteFrequencyHistogram(data, histogram = new Uint32Array(256)


symbolFrequencyHistogram

symbolFrequencyHistogram(values, symbolCount, histogram = new Uint32Array(symbolCount)


probabilityTableFromHistogram

probabilityTableFromHistogram(histogram, sampleCount = histogramSampleCount(histogram)


shannonEntropyFromHistogram

shannonEntropyFromHistogram(histogram, options = {})


minEntropyFromHistogram

minEntropyFromHistogram(histogram, options = {})


maxEntropyForSymbolCount

maxEntropyForSymbolCount(symbolCount, options = {})


klDivergence

klDivergence(pDistribution, qDistribution, options = {})


crossEntropy

crossEntropy(pDistribution, qDistribution, options = {})


mutualInformationFromJointHistogram

mutualInformationFromJointHistogram(jointHistogram, xSymbolCount, ySymbolCount, options = {})


conditionalEntropyFromJointHistogram

conditionalEntropyFromJointHistogram(jointHistogram, xSymbolCount, ySymbolCount, options = {})


jointEntropyReport

jointEntropyReport(jointHistogram, xSymbolCount, ySymbolCount, options = {})


byteDistributionReport

byteDistributionReport(data, options = {})


adaptiveProportionReport

adaptiveProportionReport(data, options = {})


minEntropyThresholdReport

minEntropyThresholdReport(data, options = {})


randomnessHealthReport

randomnessHealthReport(data, options = {})


streamingEntropyHealthReport

streamingEntropyHealthReport(data, options = {})


entropyCompressionEstimate

entropyCompressionEstimate(sampleCount, entropyBitsPerSymbol, options = {})


histogramEntropyReport

histogramEntropyReport(histogram, options = {})


core/math/MathGeometry

Summary: Convert a local AABB and entity TRS into a conservative world-space sphere. Rotation moves the scaled local center but does not change the sphere radius.


sphereAABB

sphereAABB(center, radius, aabbMin, aabbMax)


raySphere

raySphere(rayOrigin, rayDir, center, radius)


rayAABB

rayAABB(rayOrigin, rayDir, aabbMin, aabbMax)


rayPlane

rayPlane(rayOrigin, rayDir, planeNormal, planeD)


rayTriangle

rayTriangle(rayOrigin, rayDir, v0, v1, v2)


transformedAabbBoundingSphereReport

transformedAabbBoundingSphereReport(localMin, localMax, position, rotation, scale)


core/math/MathGrid

Summary: MathGrid.js - CPU-side 3D grid sampling and discrete differential operators Consolidates: FluidSimWorld.js inline trilinear, SDFCollision trilinear, WindSimulation grid sample Houdini VEX volumesample / Niagara grid sampling parity


bilinearSample

bilinearSample(grid, width, height, u, v)

Summary: Bilinear interpolation on a 2D scalar grid


bilinearSampleVec3(grid, width, height, u, v)

Summary: Bilinear interpolation on a 2D vector grid (3-component, interleaved)


trilinearSample

trilinearSample(grid, width, height, depth, u, v, w)

Summary: Trilinear interpolation on a 3D scalar grid


trilinearSampleVec3(grid, width, height, depth, u, v, w)

Summary: Trilinear interpolation on a 3D vector grid (3-component, interleaved) Matches FluidSimWorld.js sampleVelocityTrilinear GPU implementation


trilinearSampleVec4(grid, width, height, depth, u, v, w)

Summary: Trilinear interpolation on a 3D grid stored as vec4 (4-component, e.g. velocity + spin)


gridGradient

gridGradient(grid, width, height, depth, x, y, z, cellSize = 1)

Summary: Discrete gradient of a scalar field (central differences)


gridDivergence

gridDivergence(grid, width, height, depth, x, y, z, cellSize = 1)

Summary: Discrete divergence of a vector field (central differences)


gridCurl

gridCurl(grid, width, height, depth, x, y, z, cellSize = 1)

Summary: Discrete curl of a vector field (central differences)


gridLaplacian

gridLaplacian(grid, width, height, depth, x, y, z, cellSize = 1)

Summary: Discrete Laplacian of a scalar field (6-point stencil)


gridLaplacianVec3(grid, width, height, depth, x, y, z, cellSize = 1)

Summary: Discrete Laplacian of a vector field (per-component, 6-point stencil)


advectScalar

advectScalar(scalarField, velocityField, out, width, height, depth, dt, cellSize = 1)

Summary: Semi-Lagrangian advection of a scalar field through a velocity field


advectVelocity

advectVelocity(velocityField, out, width, height, depth, dt, cellSize = 1)

Summary: Semi-Lagrangian advection of a vector field through itself (self-advection)


gridCreateScalar

Summary: Create a zero-filled scalar grid


Summary: Create a zero-filled vec3 grid


Summary: Create a zero-filled vec4 grid


worldToGrid

Summary: World position to grid coordinate


gridToWorld

Summary: Grid coordinate to world position


gridSampleScalarWorld

gridSampleScalarWorld(grid, width, height, depth, worldPos, gridOrigin, cellSize)

Summary: Sample scalar field at world position


gridSampleVec3World(grid, width, height, depth, worldPos, gridOrigin, cellSize)

Summary: Sample vector field at world position


core/math/MathLine3

Summary: MathLine3.js - Line segment operations (Three.js Line3 parity) Segment represented as { a: [x,y,z], b: [x,y,z] } Consolidates: MathGeometry.closestPointOnSegment, ViewportRaycasting.raySegmentDistance, PBDRagdoll.capsuleCollision segment-segment math


core/math/MathMat


mat4Frustum(left, right, bottom, top, near, far)


mat4PerspectiveReverseZ(fov, aspect, near, far)


core/math/MathNoise


shaderFbm3DRotated(x, y, z, octaves = 4)


fbm2D(x, y, octaves = 6, lacunarity = 2, gain = 0.5, noiseFn = perlin2D)


fbm3D(x, y, z, octaves = 6, lacunarity = 2, gain = 0.5, noiseFn = perlin3D)


ridged2D(x, y, octaves = 6, lacunarity = 2, gain = 0.5, offset = 1, noiseFn = perlin2D)


ridged3D(x, y, z, octaves = 6, lacunarity = 2, gain = 0.5, offset = 1, noiseFn = perlin3D)


warpedNoise2D(x, y, warpStrength = 0.5, noiseFn = perlin2D)


warpedNoise3D(x, y, z, warpStrength = 0.5, noiseFn = perlin3D)


curlNoise2D(x, y, epsilon = 0.0001, noiseFn = perlin2D)


curlNoise3D(x, y, z, epsilon = 0.0001, noiseFn = perlin3D)


turbulence2D(x, y, octaves = 6, lacunarity = 2, gain = 0.5, noiseFn = perlin2D)


turbulence3D(x, y, z, octaves = 6, lacunarity = 2, gain = 0.5, noiseFn = perlin3D)


billow2D(x, y, octaves = 6, lacunarity = 2, gain = 0.5, noiseFn = perlin2D)


billow3D(x, y, z, octaves = 6, lacunarity = 2, gain = 0.5, noiseFn = perlin3D)


core/math/MathOscillator

Summary: Kuramoto order parameter (complex form). Computes collective synchronization r·e^(iψ) of N coupled phases. r ≈ 0 = chaos/dissonance; r ≈ 1 = perfect lockstep. Real-world: power-grid frequency lock, neural firing synchrony, firefly flashing, cardiac pacemakers, crowd footsteps (Millennium Bridge wobble).


phaseFromTime

phaseFromTime(frequency, time, phase = 0)


sampleWave

sampleWave(shape, phase, dutyCycle = 0.5)


sampleOscillatorArray

sampleOscillatorArray(oscillators, time, out = [])


applyAmplitudeModulation

applyAmplitudeModulation(sampleValue, modulatorValue, amount = 1, bipolar = false)


applyPhaseModulation

applyPhaseModulation(phase, modulatorValue, amount = 1)


sampleAmplitudeModulated

sampleAmplitudeModulated(carrier, modulator, time, amount = 1, bipolar = false)


samplePhaseModulated

samplePhaseModulated(carrier, modulator, time, amount = 1)


stepKuramotoPhases

stepKuramotoPhases(phases, naturalFrequencies, dt, coupling = 0.5, weights = null, out = null)


stepCoupledOscillators

stepCoupledOscillators(oscillators, dt, coupling = 0.5, weights = null)


kuramotoOrderParameter

Summary: Scalar synchronization metric r = |<e^(iθ)>|. Game uses: swarm AI cohesion, rhythm-combat sync signals, magic ritual progress bars, ambient life pulse coherence.


stepKuramotoDriven

stepKuramotoDriven(phases, naturalFrequencies, dt, t, coupling = 0.5, driveFrequency = 1, driveStrength = 0, weights = null, out = null)

Summary: Euler step for driven Kuramoto model. dθᵢ/dt = 2π·ωᵢ + (K/N)Σⱼsin(θⱼ−θᵢ) + λ·sin(2π·f_drive·t − θᵢ) The λ term is an external forcing function (e.g. Schumann resonance 7.83 Hz, a metronome, a planetary frequency, a bassline tempo). Applications: procedural music harmony, NPC swarm coordination, breathing/ idle animation sync, climate zone oscillations, magic aura pulse coupling.


stepKuramotoMeanFieldDriven

stepKuramotoMeanFieldDriven(phases, naturalFrequencies, dt, t, coupling = 0.5, driveFrequency = 1, driveStrength = 0, out = null, order = null,)

Summary: Exact O(N) Euler step for the globally coupled, driven Kuramoto model. For uniform all-to-all coupling, the pair sum is exactly reducible through Z = <exp(iθ)> = re + i·im: (K/N) Σⱼ sin(θⱼ-θᵢ) = K (im·cos θᵢ - re·sin θᵢ) This is mathematically equivalent to `stepKuramotoDriven(..., weights=null)` while avoiding its O(N²) pair loop. `order` may be supplied when the caller already computed the current order parameter for telemetry.


createOscillatorBank

createOscillatorBank(count, factory = null)


core/math/MathPacking

Summary: MathPacking.js - GPU data packing utilities Half-float, SNORM/UNORM, RGB9E5, R11G11B10F Consolidates: World3DPreviewRenderer._floatToHalf, MeshCompression.quantizeUVs


packSignedRangeUNORMBits

packSignedRangeUNORMBits(value, range, bitDepth = 16, fallback = 0)


unpackSignedRangeUNORMBits

unpackSignedRangeUNORMBits(packed, range, bitDepth = 16, fallback = 0)


packSignedRangeUNORM16(value, range, fallback = 0)


unpackSignedRangeUNORM16(packed, range, fallback = 0)


packSignedRangeSNORMBits

packSignedRangeSNORMBits(value, range, bitDepth = 16, fallback = 0)


unpackSignedRangeSNORMBits

unpackSignedRangeSNORMBits(packed, range, bitDepth = 16, fallback = 0)


packSignedRangeSNORM16(value, range, fallback = 0)


unpackSignedRangeSNORM16(packed, range, fallback = 0)


packTransformTRS10(transform = {}, options = {})


unpackTransformTRS10(packed, options = {})


packParticlePositionAge

packParticlePositionAge(x, y, z, age, options = {})


unpackParticlePositionAge

unpackParticlePositionAge(packed, options = {})


packParticleVelocityLifetime

packParticleVelocityLifetime(vx, vy, vz, lifetime, options = {})


unpackParticleVelocityLifetime

unpackParticleVelocityLifetime(packed, options = {})


packORM8(occlusion = 1, roughness = 1, metallic = 0, alpha = 1)


packPBRMaterialParams8(metallic = 0, roughness = 1, normalScale = 1, alphaCutoff = 0)


packVoxelMaterialUniforms

packVoxelMaterialUniforms(params = {}, out = new Float32Array(VOXEL_MATERIAL_UNIFORM_FLOATS)


core/math/MathPhysics


linearMotion

linearMotion(position, velocity, acceleration, dt)


eulerIntegrate

eulerIntegrate(position, velocity, acceleration, dt)


semiImplicitEuler

semiImplicitEuler(position, velocity, acceleration, dt)


projectileMotion

projectileMotion(position, velocity, gravity, dt)


projectilePosition

projectilePosition(start, velocity, gravity, t)


projectileVelocityToTarget

projectileVelocityToTarget(start, target, gravity, preferHighArc = false)


totalPointVelocity

totalPointVelocity(linearVelocity, angularVelocity, centerOfMass, point)


gravitationalForce

gravitationalForce(m1, m2, p1, p2, G = 6.674e-11)


springForce

springForce(position, anchor, restLength, stiffness)


dampedSpringForce

dampedSpringForce(position, velocity, anchor, restLength, stiffness, damping)


dragForce

dragForce(velocity, dragCoefficient, area, fluidDensity = 1.225)


buoyancyForce

buoyancyForce(submergedVolume, fluidDensity, gravity = 9.81)


inelasticCollision

inelasticCollision(m1, v1, m2, v2, restitution = 0.5)


sphereCollisionResponse

sphereCollisionResponse(p1, v1, m1, r1, p2, v2, m2, r2, restitution = 0.8)


planeCollisionResponse

planeCollisionResponse(velocity, normal, restitution = 0.8)


collisionResponseWithFriction

collisionResponseWithFriction(velocity, normal, restitution, friction)


distanceConstraint

distanceConstraint(p1, p2, targetDistance, stiffness = 1)


distanceConstraintMass

distanceConstraintMass(p1, m1, p2, m2, targetDistance, stiffness = 1)


pointConstraint

pointConstraint(position, target, stiffness = 1)


angleConstraint

angleConstraint(p1, p2, p3, targetAngle, stiffness = 1)


verletIntegrate

verletIntegrate(current, previous, acceleration, dt)


verletIntegrateDamped

verletIntegrateDamped(current, previous, acceleration, dt, damping = 0.99)


totalMechanicalEnergy

totalMechanicalEnergy(mass, velocity, height, g = 9.81)


rk2Integrate(position, velocity, accelerationFn, t, dt)


rk4Integrate(position, velocity, accelerationFn, t, dt)


rk4AdaptiveStep(position, velocity, accelerationFn, t, dt)


pointAttractorForce

pointAttractorForce(position, attractorPos, strength, falloffRadius = 1)


pointAttractorForceInvSq

pointAttractorForceInvSq(position, attractorPos, strength, minDist = 0.1)


vortexFieldForce

vortexFieldForce(position, vortexPos, vortexAxis, strength, radius = 1)


orbitForce

orbitForce(position, centerPos, orbitSpeed, upAxis = [0, 1, 0])


windForce

windForce(velocity, windVelocity, sensitivity = 0.1)


sphereSphereTimeOfImpact

sphereSphereTimeOfImpact(p1, v1, r1, p2, r2)


sphereSphereMovingTOI

sphereSphereMovingTOI(p1, v1, r1, p2, v2, r2)


spherePlaneTimeOfImpact

spherePlaneTimeOfImpact(center, velocity, radius, planeNormal, planeD)


sphereAABBTimeOfImpact

sphereAABBTimeOfImpact(center, velocity, radius, aabbMin, aabbMax)


potentialEnergyGravity

potentialEnergyGravity(mass, height, g = 9.81)


core/math/MathPlane

Summary: MathPlane.js - Plane operations (Three.js/Godot/Unity parity) Plane represented as [nx, ny, nz, d] where nx*x + ny*y + nz*z + d = 0 Consolidates: MeshCutter.Plane, MathGeometry.rayPlane, MathGeometry.sdfPlane


planeClassifyPoint

planeClassifyPoint(plane, point, eps = EPSILON)


core/math/MathPolynomial

Summary: MathPolynomial.js - Polynomial root solvers and evaluation Consolidates: AIAiming.js inline quadratic, SpeculativeContacts.js quadratic CCD Standard in game math libraries for intersection tests, predictive aim, CCD


polyEval

Summary: Evaluate polynomial using Horner's method: coeffs[0]*x^n + coeffs[1]*x^(n-1) + ... + coeffs[n]


polyDerivative

Summary: Derivative coefficients: returns new array of degree n-1


polyEvalWithDerivative

Summary: Evaluate polynomial and its derivative simultaneously (Horner's)


solveQuadraticPositive

Summary: Smallest positive root of quadratic, or null


polyNewtonRoot

polyNewtonRoot(coeffs, guess, maxIter = 20, tolerance = EPSILON)


polyRealRoots

polyRealRoots(coeffs, lo = -1000, hi = 1000, tolerance = 1e-10)

Summary: Find all real roots of an arbitrary polynomial using Sturm chain + bisection


core/math/MathPrecision

Summary: MathPrecision.js - numeric tolerance and world-scale split-double helpers. Pure math helpers for tests, serialization policy, and CPU/GPU coordinate packing.


numberWithinTolerance

numberWithinTolerance(actual, expected, absoluteTolerance = DEFAULT_ABSOLUTE_TOLERANCE, relativeTolerance = DEFAULT_RELATIVE_TOLERANCE)


vecWithinTolerance

vecWithinTolerance(actual, expected, absoluteTolerance = DEFAULT_ABSOLUTE_TOLERANCE, relativeTolerance = DEFAULT_RELATIVE_TOLERANCE)


core/math/MathQuality

Summary: MathQuality.js - reusable error, quality, signal, and size metrics.


peakSignalToNoiseRatio

peakSignalToNoiseRatio(reference, candidate, options = {})


structuralSimilarityLite

structuralSimilarityLite(reference, candidate, options = {})


windowedStructuralSimilarity

windowedStructuralSimilarity(reference, candidate, options = {})


channelQualityReport

channelQualityReport(reference, candidate, options = {})


imageQualityReport

imageQualityReport(referenceImage, candidateImage, options = {})


histogramDifference

histogramDifference(referenceHistogram, candidateHistogram, options = {})


frameDifference

frameDifference(reference, candidate, options = {})


perceptualErrorScore

perceptualErrorScore(reference, candidate, options = {})


qualityMetricsReport

qualityMetricsReport(reference, candidate, options = {})


qualitySizeScore

qualitySizeScore({ quality = 1, byteSize = 0, referenceByteSize = 0, byteBudget = Infinity, budgetBytes = byteBudget, qualityWeight = 0.7, sizeWeight = 0.3, budgetWeight, } = {})


core/math/MathQuat

Summary: MathQuat.js - Extended Quaternion operations [x, y, z, w] Supplements the basic quat ops in EngineMath.js with advanced features Depends on: MathConstants.js, MathScalar.js


quatFromEulerDeg

quatFromEulerDeg(x, y, z, order = 'XYZ')


core/math/MathRandom


uniformDistribution

uniformDistribution(min = 0, max = 1, rng = defaultRng)


normalDistribution

normalDistribution(mean = 0, stdDev = 1, rng = defaultRng)


exponentialDistribution

exponentialDistribution(lambda = 1, rng = defaultRng)


poissonDistribution

poissonDistribution(lambda, rng = defaultRng)


binomialDistribution

binomialDistribution(n, p, rng = defaultRng)


triangularDistribution

triangularDistribution(min, max, mode, rng = defaultRng)


gammaDistribution

gammaDistribution(shape, scale = 1, rng = defaultRng)


betaDistribution

betaDistribution(alpha, beta, rng = defaultRng)


logNormalDistribution

logNormalDistribution(mean = 0, stdDev = 1, rng = defaultRng)


cauchyDistribution

cauchyDistribution(x0 = 0, gamma = 1, rng = defaultRng)


paretoDistribution

paretoDistribution(alpha, xMin = 1, rng = defaultRng)


weightedRandom

weightedRandom(weights, rng = defaultRng)


sampleWithReplacement

sampleWithReplacement(array, n, rng = defaultRng)


reservoirSample

reservoirSample(stream, k, rng = defaultRng)


randomOnHemisphereCosine

randomOnHemisphereCosine(normal, rng = defaultRng)


randomInTriangle

randomInTriangle(v0, v1, v2, rng = defaultRng)


randomInCone

randomInCone(direction, halfAngle, rng = defaultRng)


fibonacciSphere

fibonacciSphere(index, total, rotation = 0)


fibonacciSpherePoints

fibonacciSpherePoints(count, rotation = 0)


poissonDiskSampling

poissonDiskSampling(width, height, minDist, maxAttempts = 30, rng = defaultRng)


core/math/MathRay

Summary: MathRay.js - Ray operations (Three.js/Unity parity) Ray represented as { origin: [x,y,z], direction: [x,y,z] } Consolidates: AIAiming.createRay, MathGeometry.ray*, ScreenRayCaster, Viewport.getPickRay


rayIntersectCapsule

rayIntersectCapsule(ray, capA, capB, radius)


rayIntersectOBB

rayIntersectOBB(ray, boxCenter, boxAxes, halfExtents)


core/math/MathRect2

Summary: MathRect2.js - 2D Axis-Aligned Bounding Box / Rectangle (Godot Rect2 / Three.js Box2 parity) Rect represented as { minX, minY, maxX, maxY } Consolidates: MathGeometry.pointInRect/rectRect, workflow-canvas bounding box logic


core/math/MathRegistry

Summary: MathRegistry.js - inspectable metadata for stable MathEngine modules and functions.


mathRegistryById

mathRegistryById(id, registry = MATH_REGISTRY)


mathRegistryFunctionsForModule

mathRegistryFunctionsForModule(moduleId, registry = MATH_REGISTRY)


core/math/MathRootAlgebra

Summary: Compile the reducer into immutable bilinear and square execution plans. Experimental encoders never enter this path: callers may require the exact algebraic laws their optimized kernel depends on before code is generated.


rootAlgebraFormatElement

rootAlgebraFormatElement(element, n = 4)


rootAlgebraEncodedMultiply

rootAlgebraEncodedMultiply(n, leftMask, rightMask, options = {})


rootAlgebraEncodedTrace

rootAlgebraEncodedTrace(n, leftMask, rightMask, options = {})


rootAlgebraGenerateTable

rootAlgebraGenerateTable(n, multiply = rootAlgebraMultiply)


rootAlgebraCompileExecutionPlan

rootAlgebraCompileExecutionPlan(n, options = {})


rootAlgebraEvaluateExecutionPlan

rootAlgebraEvaluateExecutionPlan(plan, left, right = null)


rootAlgebraExecutionPlanWGSL

rootAlgebraExecutionPlanWGSL(plan, options = {})

Summary: Generate a branch-free WGSL product or square directly from a validated plan.


rootAlgebraPropertyReport

rootAlgebraPropertyReport(n, options = {})


rootAlgebraFindSimpleZeroDivisors

rootAlgebraFindSimpleZeroDivisors(n, options = {})


rootAlgebraSearchEncodedMultipliers

rootAlgebraSearchEncodedMultipliers(n, options = {})


core/math/MathScalar

Summary: MathScalar.js - Scalar utility functions Depends on: MathConstants.js


nearlyEqual

nearlyEqual(a, b, absEps = EPSILON, relEps = EPSILON)


safeDiv

safeDiv(numerator, denominator, fallback = 0)


rangeContains

rangeContains(value, min, max, inclusive = true)


rangeOverlap

rangeOverlap(aMin, aMax, bMin, bMax, inclusive = true)


rangeIntersection

rangeIntersection(aMin, aMax, bMin, bMax)


remapClamped

remapClamped(x, inMin, inMax, outMin, outMax)


springDamp

springDamp(current, target, velocity, smoothTime, dt)


core/math/MathSignal

Summary: MathSignal.js - FFT and Signal Processing FFT, window functions, filters, convolution, spectral analysis


signalSummaryReport

signalSummaryReport(signal, options = {})


exponentialMovingAverage

exponentialMovingAverage(signal, alpha = 0.3)


firBandpassCoeffs

firBandpassCoeffs(lowFreq, highFreq, sampleRate, numTaps)


stft

stft(signal, windowSize, hopSize, windowFn = hannWindow)


istft

istft(frames, windowSize, hopSize, outputLength)


spectrogram

spectrogram(signal, windowSize, hopSize, windowFn = hannWindow)


melFilterbank

melFilterbank(numFilters, fftSize, sampleRate, lowFreq = 0, highFreq = null)


mfcc

mfcc(signal, sampleRate, numCoeffs = 13, numFilters = 26, windowSize = 512, hopSize = 256)


generateSine

generateSine(frequency, sampleRate, duration, amplitude = 1)


generateCosine

generateCosine(frequency, sampleRate, duration, amplitude = 1)


generateSquare

generateSquare(frequency, sampleRate, duration, amplitude = 1)


generateSawtooth

generateSawtooth(frequency, sampleRate, duration, amplitude = 1)


generateTriangle

generateTriangle(frequency, sampleRate, duration, amplitude = 1)


generateWhiteNoise

generateWhiteNoise(sampleRate, duration, amplitude = 1)


generateChirp

generateChirp(startFreq, endFreq, sampleRate, duration, amplitude = 1)


core/math/MathSphericalHarmonics

Summary: MathSphericalHarmonics.js - CPU-side Spherical Harmonics (L0-L2, 9 coefficients) Consolidates: RealtimeGI.js inline WGSL evalSH, provides CPU parity for probe baking/debugging Three.js SphericalHarmonics3 parity


shZero

Summary: Create zero SH (9 RGB coefficients = 27 floats)


shClone

Summary: Clone SH coefficients


shFromColor

Summary: Create SH from constant color (ambient only, L0 band)


shEvaluateBasis

Summary: Evaluate 9 SH basis functions for a direction [x,y,z] (must be normalized)


Summary: Evaluate 4 SH basis functions (L0+L1 only, cheaper)


shEvaluate

Summary: Evaluate RGB color from SH coefficients at a direction


shIrradiance

Summary: Evaluate irradiance (diffuse lighting) from SH at a surface normal


shProject

Summary: Project directional samples onto SH coefficients


shAdd

Summary: Add two SH: out = a + b


shScale

Summary: Scale SH by scalar


shLerp

Summary: Lerp between two SH