Zero-Asset Single-File 3D Game Workflow
Build rich, playable 3D browser games packaged into one standalone index.html file under 1 MB (~150–250 KB gzipped) with zero external runtime assets—inspired by the Saltline procedural WebGL + WebAudio architecture.
Instead of shipping megabytes of .glb meshes, .png textures, .hdr lightmaps, and .mp3 audio, generate every mesh, surface shader, reflection environment, particle, sound effect, and musical phrase mathematically at runtime.
1. Architecture & Hard Constraints
- Develop modularly, ship as one file:
- Author clean ES modules under
src/during development; bundle into a single rootindex.htmlusingesbuild(format: 'iife', inline<style>+<script>).
- Author clean ES modules under
- Strict zero-external-asset rule:
- No
fetch(),TextureLoader,GLTFLoader,AudioLoader, CDN scripts, or remote@import/ Google Fonts. - Use system font stacks so
index.htmlworks offline and directly overfile://without CORS errors.
- No
- Size budget:
- Minified
three+ game code + CSS typically lands around 550–750 KB raw (140–200 KB gzipped). Avoid heavy physics WASM blobs unless strictly required; prefer analytical 2D/3D collision & constraint math.
- Minified
- Recommended directory layout:
project/ ├── package.json # dev/build deps only: three + esbuild ├── index.html # generated single-file deliverable ├── scripts/ │ └── build.mjs # inline HTML bundler (see scripts/build-single-html.mjs) ├── tests/ │ └── verify.mjs # headless deterministic rules/level/solver check └── src/ ├── main.js # bootstrap & lifecycle wiring ├── styles.css # responsive HUD & modal styling ├── rules/ # pure-JS deterministic state, physics/rules, solver/AI ├── render/ │ ├── shaders.js # procedural HDRI + custom GLSL material hooks │ └── geometry.js # procedural BufferGeometry / Lathe / Extrude builders ├── audio/ │ └── soundEngine.js # procedural WebAudio synth, foley & reverb ├── game/ │ └── engine.js # Three.js scene, camera auto-fit, input & FX loop └── ui/ └── hud.js # DOM overlay HUD, toasts, modals, localStorage save
To initialize a fresh project quickly, run or adapt scripts/scaffold.mjs and bundle with scripts/build-single-html.mjs.
2. Step-by-Step Implementation Sequence
Step 1: Pure Deterministic Core & Headless Verification First (src/rules/)
Never couple core game rules or puzzle logic to THREE.Mesh transforms.
- Represent the world in plain JS data structures (
state,stepState(),cloneState(),isWin()). - Write
tests/verify.mjsbefore building the 3D renderer:- For puzzle/strategy games: validate geometry/layout bounds (zero unintended overlaps) and run a BFS / A* solver across every level to prove solvability and record minimum move counts.
- For action/arcade games: simulate entity spawning, hitboxes, progression curves, and state transitions headlessly.
- Read references/puzzle-and-gameplay-verification.md for solver patterns and coordinate-handedness rules.
Step 2: Procedural 3D Environment, Shaders & Geometry (src/render/)
Flat MeshStandardMaterial colors look like untextured programmer art unless lit by an environment map and broken up by micro-surface variation:
- Procedural HDRI Environment (
PMREMGenerator):- Synthesize a
128x64Float32ArrayequirectangularDataTexturewith sky gradient, softbox highlight strips, key sun lobe, and ground bounce; convert viaPMREMGenerator.fromEquirectangular()and assign toscene.environment.
- Synthesize a
- Custom GLSL Surface Shaders (
onBeforeCompile):- Inject 3D Value/Simplex noise + FBM into
MeshPhysicalMaterial(#include <color_fragment>,<roughnessmap_fragment>,<emissivemap_fragment>) for procedural materials (veined stone/jade, brushed metal, wet concrete, glazed ceramic, rippling water, foliage). - Set a shared
mat.customProgramCacheKeywhen multiple objects share the same GLSL structure so Three.js compiles one GPUWebGLProgramwhile keeping per-materialuniformsindependent.
- Inject 3D Value/Simplex noise + FBM into
- Procedural Geometry:
- Compose silhouettes from
LatheGeometry,ExtrudeGeometry,TubeGeometry, custom indexedBufferGeometry, and hierarchicalTHREE.Grouprigs (hinges, turrets, limbs, clasps) animated in code.
- Compose silhouettes from
- Tone Mapping & Shadows:
- Use
THREE.AgXToneMapping(orACESFilmicToneMapping),SRGBColorSpace, and a tight directional shadow frustum fitted to the playfield.
- Use
Read references/procedural-webgl-and-shaders.md for ready-to-use GLSL noise chunks, HDRI generator code, and Three.js API traps.
Step 3: Procedural WebAudio Synthesis (src/audio/)
- Build a self-contained
AudioEnginearoundAudioContext:- Generate a stereo impulse response buffer (
1.2–1.8sexponentially decaying filtered noise) feeding a sharedConvolverNodeso synthesized plucks, impacts, and chimes sit in a natural acoustic space. - Synthesize percussive/mechanical foley (short pitch-swept oscillators + bandpass noise bursts), tonal feedback (pentatonic/modal harmonic ratios), and toggleable ambient music loops.
- Gate
audioCtx.resume()on the firstpointerdown/keydownevent so browser autoplay policies never throw warnings.
- Generate a stereo impulse response buffer (
- Read references/procedural-webaudio.md for synthesis recipes.
Step 4: Responsive Camera Auto-Fit & Tactile Feel (src/game/engine.js)
- Portrait + Landscape Framing: Compute the playfield bounding radius and adjust camera distance using both vertical FOV and horizontal FOV (
2 * atan(tan(vFov/2) * aspect)), leaving explicit top/bottom margin for HUD bars. - Input Projection: Raycast pointer coordinates onto an analytical ground/drag
THREE.Planerather than expensive high-poly mesh raycasts every frame. - Juice & Feedback: Add magnetic snap/dwell assist where precision is frustrating, subtle spring wobble + toast hint when an action is blocked, particle bursts on clear/hit, and
undo/hint/resetcontrols. - Clean Disposal: Track geometries/materials per level load, dispose non-shared GPU resources, and
clearTimeoutpending win/lose timers when resetting or switching levels.
Step 5: Single-File HTML Bundling (scripts/build.mjs)
- Bundle
src/main.jswithesbuild(bundle: true,write: false,format: 'iife',minify: true,target: ['es2020']). - Critical: Escape closing tags inside inlined CSS and JS before interpolating into the HTML template:
css.replace(/<\/style>/gi, '<\\/style>')js.replace(/<\/script>/gi, '<\\/script>')
- Print both raw KB and gzipped KB after every build and confirm total output stays
< 1024 KB.
3. Critical Pitfalls Checklist
- 2D-to-3D Rotation Handedness: Mapping 2D board
(x, y)to Three.js(X = x, Z = y)flips rotation sign—mesh.rotation.y = +thetarotates+Xtoward-Z(atan2(-sin, cos) = -theta). Always setmesh.rotation.y = -angle2D. THREE.ColorvsTHREE.Vector3:THREE.Colordoes not have.addScaledVector(). Mutate.r/.g/.bdirectly or.add(tmpColor.copy(src).multiplyScalar(k)).Object3D.scalevsBufferGeometry.scale:mesh.scaleis aVector3property (mesh.scale.set(x, y, z)), whereasgeometry.scale(x, y, z)is a method. Callingmesh.scale(...)throws a runtimeTypeError.- Single-File Bind/Inline Escaping: Unescaped
</script>inside minified JS strings immediately breaks the HTML parser and leaves a blank page.
4. Mandatory Verification Gate
Never declare a game complete until both stages pass after your final edit:
-
Headless Build & Logic Gate:
node tests/verify.mjs node scripts/build.mjsConfirm
verify.mjsexits0andindex.htmlbuilds cleanly within size budget. -
Real Browser Runtime Gate: Serve or open
index.htmlin a real browser / headless Chromium and verify:- Zero console
Errors, uncaughtTypeErrors, WebGL warnings, or GLSL shader compile/link errors. - Non-blank 3D canvas with expected lighting, materials, and unobstructed HUD framing on both desktop and mobile-portrait aspect ratios.
- End-to-end interactive play: pointer input, state updates, win/lose modal transition, and level reset/switching.
- Zero console