Everything You Ever Wanted to Know About Level 0 Engine
The Definitive Architectural Codex, System Internals, Survival Field Manual, and Contributor Handbook
In fidelity to the Level 0 Engineering Codex, every system, tool, and entity in this manual is evaluated through three lenses: What It Does (player behavior, visible manifestations, sensory feedback), How It Works (internal algorithms, web worker pipelines, DSP circuits, spatial indices), and Why It Works (psychological horror design, mathematical guarantees, and zero-allocation performance rules).
Book I: Systems Philosophy & Rules of Reality
1. The Soul of the Backrooms
In liminal fiction, the infinite yellow corridors of Level 0 are often mistaken for mere repetitive chaos. Level 0 Engine operates on a fundamentally different paradigm: The facility has memory, bureaucratic decay, and mathematical logic.
You are not wandering an abstract void; you are navigating a decommissioned corporate subterranean complex trapped in self-replicating spatial recursion. Fluorescent ballasts buzz at precise acoustic frequencies. Shift logs, coffee fund rosters, and disciplinary notices cling to desks and lockers. Behind every door lies not randomness, but a seeded deterministic world where truth can be excavated through careful fact-finding.
- No Bundlers, No Build Step for Development: The repository serves directly to the browser via ES6 modules. What you edit is immediately what executes.
- Determinism Over Randomness: Every corridor, prop, document, and entity spawn is derived mathematically from a 32-bit seed. A single seed produces the exact same labyrinth across machines.
- Hot Paths Never Allocate: The player tick, collision detection, and entity perception loops operate with preallocated scratch vectors. Zero garbage collection stuttering during moments of horror.
- The Player is an Investigator, Not an Action Hero: Survival is attained through patience, kinetic battery management, stealth, and corroborating fragmented documentary claims.
- Verified Means Observed: Claims are invalid until proven by automated headless browser smoke tests or in-engine diagnostic instrumentation.
2. The Zero-Bundler Imperative
Modern web development frequently buries simple 3D experiences beneath brittle stacks of Webpack, Vite, Babel, and node_modules dependencies. Level 0 Engine rejects this ceremony.
All engine code runs as pure, un-transpiled ES6 modules loaded natively by modern browser engines. A lightweight Node HTTP server (engine_server.js) serves static files and injects cross-origin isolation headers. THREE is provided as a trusted global via locally vendored r160.js (Decision D-001). There is zero compilation time, zero bundler configuration drift, and zero risk of supply-chain package compromise.
3. Determinism as Law
In Level 0 Engine, pseudo-randomness is divided into two strict categories:
- Structural RNG (Seeded): The level string is folded into a 32-bit integer by a shift-and-subtract string hash (
Environment.generate()). Everything that shapes a run derives from it: the Julia-set wall topology, macro sector placement, structural blueprints, the case file dealt fromdata/*.json, which Points of Interest appear, and how many each breaker hunt demands (RunSeeds.js). Replaying a seed replays the run. - Route Independence: A chunk builds the same whatever route led to it and whichever neighbours loaded first. Breakers and Points of Interest are kept clear of the seed's spawn point, not of the live camera. Neighbouring sector airlocks are derived from their fixed positions (
AirlockLayout.js) rather than read from sectors already built. That is what lets Rebuild Geometry restore the seed's world around you, and lets a shared link put two players in the same facility. - Deliberate Exceptions: In the exit phase the exit appears in the first unvisited sector to load, so it is always somewhere you have not been. Breaker podiums after the first are planted ahead of the direction you are facing.
- Cosmetic Noise (
Math.random()): Reserved exclusively for ephemeral, non-reproducible visual and auditory effects: fluorescent bulb flicker jitter, film grain noise on canvas textures, and entity spawn micro-jitter.
4. The Cold Case & Fact-Finding
Unlike generic survival games with arbitrary keys, Level 0 centers on the Finding of Fact. Each seed generates a cold case surrounding a missing staff member. Documents scattered throughout the facility make specific documentary claims regarding rules, dates, and names.
Uncorroborated documents induce Paranoia, which physically degrades your kinetic flashlight's battery ceiling. To escape, the player must corroborate claims across disparate macro sectors, assemble the 4-digit PIN for the blast elevator, and submit the cold-case truth at the final Inquest Terminal.
Book II: The Engine Room & Architecture
Level 0 Engine is structured into decoupled, single-responsibility ES6 modules connected through a centralized runtime orchestrator (Environment.js).
+-----------------------------------------------------------------------------------+
| BROWSER RUNTIME |
| |
| index.html ==> engine.html ==> r160.js (THREE Global) + purify.min.js |
| | |
| v |
| main.js |
| | |
| v |
| src/core/Environment.js |
| (THE ORCHESTRATOR) |
| | |
| +--------------------------------+--------------------------------+ |
| | | | |
| v v v |
| RenderEngine.js ChunkManager.js PlayerController |
| - WebGLRenderer - ChunkStreamer (Queue) - SomaticInput |
| - PostProcessing (CRT/Aberr) - ChunkBuilder (Mesh) - Flashlight |
| - LumenGrid (Area Lights) - ChunkWorker.js (Worker) - Compass |
| | | | |
| +--------------------------------+--------------------------------+ |
| | |
| +--------------------------------+--------------------------------+ |
| | | | |
| v v v |
| EntityManager.js StoryEngine.js AcousticEngine |
| - Anomaly (Roaming) - data/*.json Dealing - Web Audio DSP |
| - Sector Entities - CaseFiles & Clues - Wall Occlusion |
| - SpatialHashGrid - JSEP Condition Evaluator - Foley / Mixer |
+-----------------------------------------------------------------------------------+
5. Julia Maze & Chunk Streaming Pipeline
Files: src/world/ChunkManager.js, ChunkStreamer.js, ChunkBuilder.js, ChunkWorker.js
Dynamically streams an infinite 3D labyrinth around the player in fixed-size chunks (typically 16×16 cells), building and tearing down geometries in real time without dropping frames.
- Offloaded Math:
ChunkStreamertracks the player's grid coordinates and calculates chunks within streaming radius. Requests are dispatched toChunkWorker.jsrunning on a separate Web Worker thread. - Julia Set Formulation: The worker computes wall topologies by iterating a 2D complex rational map. Cells where \(|z| > \text{threshold}\) collapse into walls, while interior coordinates carve out open hallways.
- Geometry Synthesis:
ChunkBuilderreceives cell matrices from the worker, applies macro sector rules fromSectors.js, selects structural blueprints fromStructuralBlueprints.js, and stitches meshes viaStructureKit.js. - Batch Disposal: As chunks exit the streaming envelope, buffers, collision lines, and dynamic light instances are cleanly disposed of to reclaim GPU VRAM.
Offloading fractal computation to a web worker guarantees that the main JavaScript execution thread never hitches. The render loop maintains locked 60fps even as massive macro sectors materialize on the horizon.
6. LumenGrid & Shadow Hysteresis
Files: src/aesthetics/LumenGrid.js, src/aesthetics/RectAreaLightUniforms.js
Manages the atmospheric illumination of Level 0, powering fluorescent ceiling panels, emergency strobe conduits, breaker blackout cascades, and cast shadows.
- Ceiling Area Lights: Utilizes vendored
RectAreaLightUniformsLibto simulate rectangular diffuse fixtures without the sharp artificial artifacts of point lights. - Fixed Shadow Caster Pool: Real-time shadows on mobile and integrated GPUs are expensive. LumenGrid maintains a strictly capped budget (e.g., 4 active shadow casters) allocated by proximity to the player camera.
- Distance Hysteresis: Lights crossing the shadow-caster threshold utilize a 2-unit hysteresis buffer, preventing visible shadow popping when the player oscillates near a boundary.
Enforces hardware performance predictability. The engine achieves rich, claustrophobic volumetric atmosphere while respecting mobile WebGL texture unit and shadow map limits.
7. Web Audio DSP & Real-Time Occlusion
Files: src/audio/AcousticEngine.js, Mixer.js, Foley.js
The auditory heart of Level 0. Synthesizes procedural room tones, footstep impacts, fluorescent hums, heartbeat adrenaline pumps, and physically muffles sound when blocked by walls.
- Procedural Synthesis: Tone generators create layered sine, sawtooth, and filtered noise sources for the fluorescent hum (60Hz ground hum with micro-phase harmonics).
- Raycast Occlusion Filter: When spatial audio sources (e.g. entity groans or radio static) emit,
AcousticEnginecasts rays through theSpatialHashGridto the player. Each intersecting wall applies an exponential low-pass BiquadFilter, creating realistic wall dampening. - Exhaustion DSP: When the player sprint stamina or oxygen runs dry, a master dynamics compressor and low-pass filter squashes world audio, elevating internal bodily respiration and erratic heartbeats.
Horror relies more heavily on acoustics than visuals. Hearing an entity's muffled gait around two corners prompts genuine dread, informing player tactical decisions before visual contact occurs.
8. Procedural Canvas Textures & Material Library
Files: src/aesthetics/ProceduralTextureFactory.js, MaterialLibrary.js
Generates all wall, floor, ceiling, and metal textures dynamically at runtime via HTML5 Canvas 2D drawing routines, with zero network asset downloads.
- Canvas Synthesis:
ProceduralTextureFactorydraws perlin noise, stained watermarks, worn wallpaper seams, subway tile grout, and acoustic tile perforations onto off-screen canvas elements. - Mipmap Generation: Canvases are converted to
THREE.CanvasTextureinstances with anisotropic filtering enabled, and cached inMaterialLibrary.js. - Static Fallback: If WebGL context creation constraints or dev tuners require it, textures can fall back to pre-baked PNGs in
assets/textures/.
Shrinks initial page load to under 2 megabytes while eliminating HTTP request roundtrips. Every surface carries procedural variation, avoiding obvious tiling repetition.
9. Dual-Key LocalStorage Persistence
Files: src/system/SaveManager.js
Maintains player session progress, active cold-case leads, gathered document inventory, pulled surge breakers, and custom engine settings.
- Dual-Key Safeguard: Before writing new game state to
localStorage['level0_state'],SaveManagercopies the existing state tolevel0_state_backup. - Integrity Check: On engine boot, JSON parsing is wrapped in strict try/catch blocks. If corruption is detected, the backup is automatically restored, and telemetry logs a warning.
- Purge Mechanics: "Purge Memory" resets the session while preserving player settings; "Purge & Start New Game" restores baseline seed state.
Protects player progress against accidental browser closures, battery failures, or localStorage write crashes.
Book III: Procedural Topography & Macro-Sectors
The maze hierarchy operates in three distinct structural tiers:
- Macro Sectors: Large themed geographic zones (Archive, Atrium, Annex, etc.) spanning many contiguous chunks, defined by distinct wall palettes, fog colors, audio hums, and lighting profiles in
Sectors.js. - Chunks: The 16×16 streaming unit built by
ChunkWorker.jsand assembled byChunkBuilder.js. - Structural Blueprints: Architectural micro-features (Ducts, Arches, Crevices, Faraday Cages) placed within open cell spaces, registered with strict probability weights in
StructuralBlueprints.js.
10. Zone Bounds & Blast Thresholds
Files: src/world/ZoneBounds.js, src/world/AirlockApron.js, src/world/AirlockLayout.js, src/world/SectorPlacement.js, src/world/SetPieces.js
Governs the volumetric fog, acoustic transitions, and heavy mechanical blast doors that seal macro sectors from the surrounding Backrooms.
- Boundary Sealing: Every macro sector is sealed by exactly one true blast threshold at its entry boundary.
- Airlock Apron:
AirlockApron.jsbridges the transitional corridor, aligning subway tiles and corner pillar materials between sectors. Every sector chunk has one airlock per side at a fixed cross-cell (AirlockLayout.js), so neighbouring maze chunks derive those positions from the seed instead of waiting for the sector to build. - Volumetric Interpolation: As the player crosses the apron threshold,
AtmosphereManagerlerps fog color, density, and ambient lighting smoothly over 2.5 seconds, eliminating jarring visual pops.
Gives the player a palpable sense of entering a new hazardous subterranean biome, providing clear spatial landmarks in an infinite world.
11. The 14 Macro Sectors Tour
Files: src/world/sectors/*.js, src/world/Sectors.js
The facility comprises 14 distinct themed macro zones, each featuring custom architectural blueprints, ambient color schemes, and narrative props.
| Sector | Visual Identity | Atmosphere & Fog | Key Features |
|---|---|---|---|
| NORMAL | Classic Level 0 mono-yellow wallpaper, damp carpet | Warm amber tint, moderate falloff | Starting hub, foundational transitional corridors |
| ARCHIVE | Endless rows of steel file stacks, sorting tables | Muted sepia dust fog | Dense paper documents, Archivist entity presence |
| ATRIUM | Soaring vertical courtyards, skylights, railings | Pale blue ethereal glow, low drag | Multi-level verticality, echoed acoustic reverb |
| ANNEX | Low drop-ceiling sterile cubicles, fluorescent tubes | Harsh institutional white haze | Broken office amenities, cubicle mazes |
| ACME | High-voltage research wing, warning hazard stripes | Electric cyan tint, ozone hum | Prototype test chambers, breaker relays |
| BOARDROOM | Mahogany wall paneling, conference tables, drapes | Deep burgundy shadow, dead silence | Executive cold-case files, encrypted safes |
| CHASM | Sheer drop-offs, suspended steel catwalks | Pitch black bottomless void | Narrow footing, falling hazards, vast reverb |
| CHECKPOINT | Reinforced security gates, turnstiles, guard booths | Cold slate grey, security strobes | Warden entity patrols, keycard readers |
| CLINIC | Bleached ceramic tiles, gurneys, surgical lamps | Sterile pale green wash | Medical logs, biohazard quarantine lockers |
| EXIT | Reinforced blast bunker, airlock bulkheads | Heavy emergency red floodlights | The Inquest Terminal, final elevator airlock |
| IMPOUND | Chain-link fence cages, tagged evidence lockers | Dirty amber sodium-vapor fog | Seized artifacts, classified staff dossiers |
| INCINERATOR | Charred brick, floor grates over magma vents | Thick red smoke, heat wave distortion | Incinerator entity, burned record scraps |
| MAINTENANCE | Exposed steam pipes, concrete conduits, floor puddles | Humid yellow condensation mist | Crawlspace ducts, sump pumps, tight vents |
| SERVER | Towering server racks, blinking optical LEDs | Deep cobalt blue, sub-zero chill | Backup Daemon entity, mainframe terminals |
Diverse biomes prevent visual fatigue, give players cognitive maps of their exploration progress, and provide thematic contexts for cold-case evidence.
Book IV: Survival Field Manual (How to Play)
12. The Opening: Arrival, Sighting & First Breaker
Files: src/narrative/OpeningDirector.js, src/narrative/OpeningPlan.js, src/world/ElevatorSpawn.js
Every new run starts in an arrival car and plays a short scripted sequence. The car settles and the doors release. You glimpse something at the end of a hall. The objective comes online, and the first breaker is close enough to reach before the facility starts hunting you. A resumed save skips all of this and puts you back where you left off.
- Arrival: The car is lit at a quarter of normal ambient light, as emergency lighting. On a first run the flashlight starts half charged. The car rumbles, dings at 4.2 s, and releases its doors at 5 s. Returning players enter the override code from the maintenance note on the wall until the keypad remembers it.
- The Objective Comes Online: The
RESTORE POWERline and the POI signal stay hidden until you step out of the car. - The Sighting: When you step out, the director looks for open cells within 24 m of the car that have a straight sight line of at least 16 m, outside every sector. The one nearest the car wins. The first time you look down that corridor in the next 45 s, the Anomaly stands at its far end, 12 to 24 m away. After 1.8 s, or sooner if you close to 9 m, the lights stutter and it is gone. It cannot hurt you here: it is still in its grace period.
- The First Breaker: The first hunt points straight at a breaker podium planted 28 to 56 m from the seed's spawn point. Later hunts may send you through 0 to 2 Points of Interest first, then to a podium placed further ahead.
- Grace From The Doorway: The Anomaly's 90 s grace period does not start until you leave the car, so the first real hunt comes about a minute and a half after you step out, however long you spend reading.
- Learning The Crank: The first time your flashlight dies, a one-time hint explains how to recharge it.
The first minute decides whether a player, or a stream's audience, stays. The opening shows you the threat before it can reach you, then gives you a goal you can achieve quickly. The sighting is chosen from the layout around the car, not from your route, so everyone on a shared seed sees the same corridor. Each beat logs an [OPENING] timing mark to the console and to the Debug HUD's OPEN line, so the pacing can be measured on any seed.
13. The Kinetic Flashlight & Crank Physics
Files: src/player/Flashlight.js, src/player/SomaticInput.js
Your primary survival instrument and psychological shield. The heavy flashlight illuminates dark corridors and freezes the Anomaly in its beam, but rapidly drains power.
- Kinetic Charging: The flashlight has no disposable batteries. It is charged mechanically by sprinting (converting movement inertia) or by rapidly shaking the camera (cranking the dyno mechanism). It only charges while switched off, never past its ceiling of 100% minus accumulated paranoia, and not during the 10 s cooldown after it runs flat. A first run starts at 50%.
- Parabolic Beam: Casts a focused central beam with quadratic distance attenuation and a wider subtle ambient cone.
- Flicker Warning: When charge drops below 15%, the bulb begins irregular brownout flickers, reducing beam efficacy and triggering entity agitation.
Forces dynamic physical engagement. Recharging demands noisy, erratic actions (shaking or running) that risk attracting nearby entities, creating high-tension tactical dilemmas.
14. Paranoia & The Corroboration Loop
Files: src/narrative/StoryEngine.js, src/player/PlayerController.js
A direct mechanical bridge connecting narrative discovery with player physical survival. Reading uncorroborated documents increases Paranoia, which places a hard cap on your maximum flashlight battery charge.
- Unverified Claims: When you read a document making an uncorroborated claim (e.g. "Rule 14 was enacted in 1984"), paranoia ticks up, capping battery maximum to 80%, 60%, or lower.
- Cross-Sector Corroboration: To bleed off paranoia and restore full battery capacity, you must explore and locate a second document in a different macro sector that corroborates the identical claim.
- Resolution: Corroborated claims turn green in your PDA Journal (
J), permanently dispelling paranoia and solidifying an objective truth for the Inquest.
Prevents lore from being treated as passive background decoration. Reading and understanding the narrative is a mandatory survival requirement.
15. Somatic Movement, Exhaustion & Compression
Files: src/player/PlayerController.js, src/system/SomaticController.js
Models realistic physical presence: inertia, footstep cadence, wall impacts, and squeezing through tight bottlenecks.
- Wall Collisions & Camera Trauma: Crashing into walls at high speed jolts the camera with physics trauma, triggers a heavy dull thud, and rattles your flashlight.
- Terminal Exhaustion: Sprinting burns oxygen twice as fast. When exhausted, the player stumbles, hearing muffled breathing DSP, while their hearing radius expands—making them easier for the Anomaly to detect.
- Compression Mode (
Q): PressingQlowers your camera and narrows collision extents, allowing you to compress through tight ductwork, collapsed crevices, and floor vents.
Grounds the player in a fragile physical body. You cannot simply sprint blindly through corridors without suffering disorientation and acoustic penalties.
17. The Assembled Lock & Inquest Escape
Files: src/ui/InquestController.js, src/world/sectors/ExitSector.js
The ultimate victory condition of Level 0 Engine. Unlock the blast elevator, submit the Finding of Fact, and ascend to the surface.
- The 4-Digit Assembled Lock: The exit elevator door is sealed by a mechanical PIN assembled from three distinct clues scattered across the complex: the Rule Number, the Enactment Year, and the Pen Color Code.
- The Finding of Fact: At the glowing green terminal inside the Exit Bunker, you are prompted to present the true sequence of events regarding the cold case.
- Chat's Verdict (Streamer Mode): With streamer mode connected to a Twitch channel, viewers vote while the terminal is open with
!1,!2,!3or!vote N, one vote each. The terminal shows the tally, and pressing4files chat's leading finding. A tie files nothing. - The Elevator Ascent: Entering the correct PIN and fact finding activates the elevator winch, locking the doors and triggering the victory sequence.
Transforms escape into an intellectual triumph. Victory requires both physical mastery of the maze and mental mastery of its lore.
Book V: Hazards, Entities & Phenomena
18. The Anomaly (The Roaming Predator)
Files: src/entities/Anomaly.js
The default macro predator of Level 0. A fast, relentless entity that roams the halls hunting the player by acoustic signature and line-of-sight.
- Acoustic Hearing Radius: Calculates player noise generation (sneaking: 2m, walking: 8m, sprinting: 20m, terminal exhaustion stumble: 35m).
- Direct Flashlight Observation Freeze: When illuminated by the active flashlight with clear line of sight, distance under 25 m, and a dot product above 0.85 (the central ~31.8° forward cone), the Anomaly freezes in place, screeching with rage.
- Rage Buildup: Freezing is temporary. Each second the beam holds it, the Anomaly accumulates rage. When your battery flickers out or you look away, it surges forward with increased velocity!
- Grace Period: After every reset (a new run, a respawn, or leaving a sector) the Anomaly waits 90 s before it hunts or hears anything. On a new run that clock starts when you step out of the arrival car. When it resumes prowling it reappears 40 to 55 m from you.
- Proximity Aberration: As it approaches, the screen suffers severe chromatic aberration, audio crushing, and claustrophobic vignettes.
Inverts conventional horror tropes: facing the monster saves you, but locks you in a terrifying staredown while your flashlight battery drains towards zero.
19. Sector-Locked Entities
Files: src/entities/*.js
Specialized entities bound to specific macro sectors, enforcing unique behavioral hazards.
- The Archivist (Archive Sector): Spectral entity that patrols between file stacks, homing in on the sound of footsteps and document pickups.
- Backup Daemon (Server Sector): High-voltage construct that teleports along cable runs, predicts player velocity, and launches electrical shard bursts.
- The Claw (Atrium Sector): Ceiling-mounted motorized gantry that drops a four-pronged hydraulic claw when players linger in central courtyards.
- Incinerator Entity (Incinerator Sector): Thermodynamic molten core predator that chases aggressively while radiating stamina-sapping heat.
- Sentry Cone (Maintenance Sector): Tripwire construction hazard that wakes on breaker trips or pylon collisions, pursuing at 4.2 m/s with multi-tier steering.
- The Warden (Impound Sector): Heavily armored monolithic juggernaut that smashes through chain-link fences during cage patrols.
Forces the player to adapt their survival strategies as they transition between different sector biomes.
20. Surge Breakers & Blackout Cascades
Files: src/world/BreakerPodium.js, src/world/sectors/MaintenanceSector.js, src/player/InteractionController.js
Heavy high-voltage electrical levers found on walls. Pulling them with E disrupts local facility power, opening secured airlocks while plunging sectors into pitch blackness.
- Blackout Cascade: Pulling the lever instantly shatters local fluorescent tubes with particle debris and sound FX.
- Cascade Delay: Neighboring lights sequentially extinguish down the hall in a terrifying domino wave.
- Emergency Reboot: After a timed blackout duration, emergency amber or red warning strobes initiate an irregular flicking reboot sequence.
Delivers visceral, player-initiated environmental shock. You must willingly plunge yourself into total darkness to progress through locked gates.
21. Liminal Breaches, Faraday Cages & Ephemera
Rare anomalous environmental fixtures providing sanctuary, spatial shortcuts, or atmospheric world-building.
- The Faraday Cage: A rare, copper-plated room blueprint completely shielded from entities. Step inside to recharge your flashlight, check your journal, and catch your breath in total safety.
- Liminal Breaches: Procedural stairwells have a 25% chance to spawn as open breaches, allowing you to warp thousands of units across the grid without mutating the underlying seed.
- Ephemera: Coffee funds, lost wedding rings, and shift schedules scattered near the Exit Bunker. They carry no claims or PIN digits—they are haunting human echoes of the missing workforce.
Provides necessary moments of emotional reprieve (Faraday Cages) and deepens the tragic human context behind the corporate facility.
Book VI: Narrative & Story Engine
22. Seeded Narrative Dealing
Files: src/narrative/StoryEngine.js, data/*.json
Generates a coherent, non-repeating cold-case mystery from thousands of narrative fragments stored in JSON data files.
- Card Dealing: On level generation,
StoryEnginecreates a shuffled deck of clues, foreshadowing snippets, and lore logs seeded by the level seed. - Data Repositories: Draws from
clues.json,lore.json,foreshadow.json,finales.json, andephemera.json. - Placement: Distributes documents onto generated desks, file cabinets, and clipboards as chunks materialize around the player.
Ensures that no two runs tell the exact same story, while guaranteeing that essential clues required to assemble the PIN code are always placed in reachable sectors.
23. Prop Attachment & Evidence Types
Files: src/world/NarrativeProps.js, src/narrative/CaseFiles.js
Spawns tangible 3D interactive props that carry written or recorded testimony.
- Sticky Notes & Paper Files: Simple paper notes fixed to walls and clipboards.
- Rugged Laptops: Glowing screens displaying terminal email logs and staff memos.
- Reel-to-Reel Tape Recorders: Interactive audio logs that play voice transcripts via text and muffled audio cues.
Grounds narrative in physical space. Documents are not abstract UI popups, but tangible objects found sitting in the world.
24. JSEP Logic & Safe AST Templating
Files: src/utils/SafeEval.js, lore-editor/js/rendering.js
Safely evaluates complex display conditions (e.g. ctx.sector === 'ANNEX' && c.lead) and templates variables into text without dangerous JavaScript eval() or new Function().
- Vendored JSEP: Expression strings are parsed into an Abstract Syntax Tree (AST) using vendored
jsep.min.js. - AST Walk:
SafeEval.jsevaluates identifiers and operators against a sanitized context object. - XSS Sanitization: Before rendered text touches the DOM, it is passed through vendored
purify.min.js(DOMPurify).
Enforces complete security isolation (Decision D-001). Community lore expansions or user-edited JSON files cannot execute arbitrary JavaScript in the player's browser.
Book VII: Developer Tooling & The Lore Editor
25. The Standalone Lore Editor (Port 3000)
Files: lore-editor/index.html, editor_server.js, coverage.js
A dedicated visual web application for authoring, editing, and validating the game's narrative JSON databases without touching engine code.
- Dedicated Server: Launched via
./start_editor.sh(Node server listening on port 3000). - Data Synchronization: Reads from and writes directly to
data/*.jsonon disk. - Coverage Report: Features a built-in Coverage view aggregating total available entries per sector, warning writers when sector pools are running thin.
- Factory Reset: Backed by
data/factory/as an immutable reset baseline.
Empowers narrative writers and designers to expand the game's lore without needing 3D graphics or Three.js programming experience.
26. AST Pre-Save Validation
Files: lore-editor/js/rendering.js
Intercepts Lore Editor saves and verifies that all conditions, variables, threads, and sector references exist, preventing broken entries from entering the game.
- Pre-Save Hook: When the author clicks "Save",
runPreSaveConditionChecksparses all condition expressions with JSEP. - Cross-File Audit: Verifies that every referenced variable exists in
parameters.json, every thread inthreads.json, and every sector inSectors.js. - Save Abort: If an unknown identifier is detected, saving is aborted with a clear diagnostic dialog.
Guarantees data integrity at the authoring boundary, catching typos before they can manifest as runtime errors during gameplay.
27. In-Engine Atmosphere & Light Tuners
Files: src/ui/AtmosphereTuner.js, LightTuner.js, SectorTunerFactory.js
Live, in-game developer sliders that allow real-time tuning of fog density, light intensity, and colors, with instant disk persistence.
- Interactive UI: Pressing dev keys displays interactive sliders over the 3D viewport.
- Disk Save: Clicking "Save to Disk" dispatches POST requests to
/save-lightor/save-atmosphereonengine_server.js. - Source Rewriting: The server parses and updates the source code of
Sectors.jsdirectly on disk!
Eliminates the tedious loop of tweaking numbers in code, reloading, and checking. Lighting designers can sculpt the horror atmosphere directly inside the running scene.
Book VIII: The Proving Ground
In Level 0 Engine, code that looks correct in a code review is not considered complete until it has been proven by automated observation in a real browser engine.
28. Headless Playwright Smoke Tests
Files: test/p4_01_smoke.test.js
An automated headless Chromium integration suite that launches the game, traverses all 14 macro sectors, and verifies procedural generation is completely error-free.
- Headless Boot: Spawns Chromium via Playwright, loads
http://localhost:8080/engine.html, and monitors console errors. - Targeted Sector Warp: Extracts explicit chunk coordinates from
SectorPlacement.jsfor fixed seed0x12345678. Warps camera to each sector and forcesChunkStreamergeneration. - Assertion Matrix: Verifies that all meshes, materials, and lights compile without WebGL warnings or uncaught exceptions.
Guarantees that generator changes or sector refactors cannot silently introduce broken imports or geometry synthesis crashes.
29. Frame-Time Baseline Budgets
Files: test/perf_baseline.json
Enforces an automated CPU generation budget across all sectors to prevent performance regressions from creeping into the engine.
- Timing Capture: During headless smoke runs, the test measures total milliseconds spent in
environment.genStats.totalMs. - Baseline Comparison: Compares results against stored measurements in
test/perf_baseline.json. - Regression Gate: If CPU generation time regresses by more than 1.5x against the baseline, the test suite fails automatically.
Keeps procedural generation lean and fast, ensuring low-end laptops and mobile browsers maintain silky 60fps performance.
Book IX: Contributor's Protocol
30. Engineering Conventions & Invariants
Strict software engineering rules governing all code contributions to the repository.
- No Per-Frame Allocations: Hot paths (player movement, entity pathfinding, spatial hash queries) must reuse preallocated scratch vectors. Never call
new THREE.Vector3()inside render loops! - Pure ES6 Modules: Never add bundlers, transpilers, or Babel configurations.
- THREE is a Global: Never write
import * as THREE from 'three'. The global is supplied byr160.js. - Sum to 1.0000: Probabilities registered in
StructuralBlueprints.jsmust sum to exactly1.0000.
Preserves maximum performance, eliminates GC stuttering, and keeps the engine universally runnable in any browser without build tooling.
31. Protected Areas & Conventions
Guards critical repository files against accidental modification.
| Path / Area | Rule | Rationale |
|---|---|---|
r160.js, jsep.min.js, purify.min.js |
Never edit by hand | Vendored third-party libraries (Decision D-001) |
data/factory/ |
Never edit without permission | The Lore Editor's immutable factory-reset baseline |
build/ |
Do not commit to git | Output of npm run build |
Maintains clean boundaries between project code, third-party libraries, and generated artifacts.
32. Single-Maintainer Git Workflow
The process for landing changes directly on master.
- Direct-to-master workflow managed by maintainer gordonk.
- Commit format uses the release version number (e.g.
1.5.8.9). Release numbers are internal (D-009): they live indocs/CHANGELOG.md,package.jsonand commit messages, never on public pages, andtools/check_docs.pyenforces it. - Before committing, run
python3 tools/check_docs.pyandnpm test. - Update
docs/CHANGELOG.mdanddocs/HANDOFF.mdwith every functional change.
Keeps git history concise, transparent, and aligned with release tags.
Technical Appendices
Appendix A: Master Controls & Keybindings Matrix
| Key / Input | Action | System / Subsystem |
|---|---|---|
W, A, S, D |
Move forward, strafe left, move backward, strafe right | PlayerController.js |
Mouse Movement |
First-person camera pitch and yaw | PlayerController.js |
Left Click |
Interact (pickup documents, pull breakers, use terminals, open doors) | InteractionController.js |
Shift |
Sprint (burns oxygen, recharges flashlight kinetically) | PlayerController.js, Flashlight.js |
Q |
Compress / Crouch (squeeze through tight ducts, crevices, vents) | PlayerController.js |
F |
Toggle Kinetic Flashlight on/off | Flashlight.js |
E |
Pull Surge Breakers / Activate Machinery | InteractionController.js |
M |
Raise Threshold Compass (points to nearest sector / exit bunker) | Compass.js |
J |
Open PDA Journal (review gathered lore, leads, virtual cursor) | JournalViewer.js |
P |
Equip Paintball Gun (fire luminescent UV maze markers) | PaintballGun.js |
Tab |
Open Engine Settings Panel (aspect ratio, resolution, fog, seed) | Environment.js, UIManager.js |
| Menu → Copy Link | Copy a link that starts this run's seed from the beginning (blackout and floor suffixes removed) | SeedLink.js, main.js |
| Menu → Rebuild Geometry | Rebuild the seed's world around you in place; position and run progress are kept | Environment.js |
| Menu → Streamer Mode | Show the seed and chat panel, read a Twitch channel's chat anonymously, and let chat vote on the Inquest (!1-!3) or trigger !blackout and !lure |
StreamerMode.js, TwitchChat.js |
| Menu → Ghost Runs | Show a translucent ghost of your best run on this seed (or an imported one), export it as a file, or import someone else's | GhostRuns.js, GhostCodec.js |
4 (at the Inquest) |
File chat's leading finding (streamer mode only) | StreamerMode.js |
X |
Capture Clean Screenshot (PNG download) | RenderEngine.js |
` (Backtick) |
Toggle Debug HUD (FPS, draw calls, active chunk coordinates) | DebugHUD.js |
G |
Toggle God Mode (Dev cheat: collision off, fly speed) | PlayerController.js |
Z |
Sector Warp (Dev cheat: cycle between macro sectors) | Environment.js |
Appendix B: URL Debug Flags & Parameters
| Query Flag | Values | Effect |
|---|---|---|
?seed=<str> |
Any string (64 characters at most) | Starts a new run on this seed. Works on terminal.html and engine.html. If a different session is saved, the continue prompt offers to resume it or start the linked seed. |
?seed=daily |
Keyword | Starts the daily seed: a five-card hand dealt from the UTC date, the same for everyone that day |
?ssaodebug |
normal, ao |
Renders raw normal buffer or ambient occlusion buffer for debugging |
?logdepth |
Boolean toggle | Enables logarithmic depth buffer for massive render view distances |
Appendix C: Sectors.js Registry Schema
// src/world/Sectors.js schema structure:
export const SECTORS = {
NORMAL: {
hasMaze: false,
anomalyAllowed: true,
rectLightIntensity: 2.35,
shadowRadius: 3.25,
lightRange: 2.15,
lightColor: 0xffffff,
lightIntensity: 1.05,
fogColor: 0xa6a6a6,
fog: 0.015,
ambient: 0.3,
groundColor: 0xededed,
ambience: {
noise: 0.0, rumble: 60, freq: 250, freqOcc: 120, whine: 0.0005, dynamicWhine: true
},
foley: { oscFreq: 85, filterType: 'lowpass', filterFreq: 1200, gain: 0.09, attack: 0.02, decay: 0.11 },
reverb: { rt60: 0.8, predelay: 0.010, wet: 0.14 }
},
ARCHIVE: { ... },
ATRIUM: { ... },
// 14 macro sectors defined
};
Appendix D: Saved State Schema
// localStorage['level0_state'] JSON structure (SaveManager.js):
{
"px": 12.4, "py": 1.2, "pz": -45.8,
"rx": 0.0, "ry": 1.57,
"stamina": 100, "battery": 85.0,
"flashlightActive": true,
"isCrouching": false, "isCrawling": false,
"hasExitKey": false, "depth": 3, "bestDepth": 5,
"seed": "0x12345678",
"aspect": "1.3333333333", "fog": "5", "fov": "75", "speed": "100", "res": "1.0",
"shadows": "high", "shadowLights": "6", "renderDist": "1",
"vol": "100", "gamma": "70", "aa": "4", "fxaa": true, "post": true,
"headBob": true, "ssao": false,
"macroChunks": ["0,0", "1,0", "0,1"],
"discoveredSectors": [["NORMAL", 1700000000000], ["ARCHIVE", 1700000050000]],
"story": { "cluesFound": [], "corroborated": [], "locks": [] }
}