# Build a game with VANILLAJS

New to the engine? Start with the [Creator Hub](demos/creator-hub/index.html) and
[step-by-step creator guide](docs/CREATOR_GUIDE.md): choose a genre, build a
playable scene, make a soundtrack, package it and troubleshoot common failures.
The recipes below are for adding your own game rules in JavaScript.

To package a visual-editor project with its runtime files:

```sh
node scripts/export-game.js /path/to/game.vproject.json --out /path/to/new-game-folder
```

The destination must be new. Serve the complete output over HTTP(S); retain
your editable project separately. [Export details and limits](docs/CREATOR_GUIDE.md#package-an-authored-preview).

For new integer simulations, start with [the integer-engine composition example](docs/INTEGER_ENGINE.md#compose-a-game).
It covers fixed-point units, atomic ticks, collision and replay. The examples
below remain the compatible floating-point controller recipes.

For the separately registered ARCH-OMI-001 research surface, see
[OMI Lab](docs/ARCH_OMI.md). Its sixteen-bit encoding and exhaustive evidence can
inform a puzzle experiment, but it is not a core game module or a replacement
for navigation/physics. Pin the repository commit when trying its API.

Start from an exact release or commit, inspect `MODULES.json` and select only the
modules needed by the game. Keep all required dependencies and relative paths.
The APIs remain experimental; record the revision instead of silently tracking
`main`. Preserve LICENSE and NOTICE when distributing copied modules.

For example, a flight game vendors `math`, `collision`, `flight`, `time` and
`input`; it can use `render-webgl` or supply its own renderer. A physics-only test
does not need any browser adapter. No module imports from the demos.

## Minimal simulation

```js
import {createBody, flightConfig, snapshot, stepFlight} from './vendor/vanillajs/modules/flight/index.js';
import {FixedClock} from './vendor/vanillajs/modules/time/index.js';
import {Actions, attachKeyboard} from './vendor/vanillajs/modules/input/index.js';

const body = createBody({position: [0, 0, 10]});
const config = flightConfig({assisted: true});
const clock = new FixedClock();
const actions = new Actions();
const keyboard = attachKeyboard(window, actions, {enabled: () => !clock.paused});
const solids = []; // aabb(min,max) objects from your validated world
let previous = snapshot(body);
let last = null;

function frame(now) {
  const seconds = last === null ? 0 : (now-last)/1000;
  last = now;
  const command = actions.flight();
  const {alpha} = clock.advance(seconds, dt => {
    previous = snapshot(body);
    stepFlight(body, command, dt, config, solids);
  });
  // Render previous/current poses using alpha; the demo shows a WebGL example.
  requestAnimationFrame(frame);
}
function setPaused(paused) {
  clock.setPaused(paused);
  last = null; // never accumulate the hidden interval on resume
  keyboard.clear();
}
window.addEventListener('blur', () => setPaused(true));
document.addEventListener('visibilitychange', () => {
  if (document.hidden) setPaused(true);
});
// Connect your explicit Resume button to setPaused(false).
requestAnimationFrame(frame);
```

Production games should also implement reset, teardown, controller disconnect,
touch cancellation and unsupported-renderer behaviour. The Flight Lab app is a
complete reference for those boundaries; its DOM layout is not a module contract.

## Stream a dense bullet field without per-box garbage

The new experimental [RENDER-PACKING-001](docs/RENDER_PACKING_001.md) module owns a bounded, reusable typed buffer for coloured boxes. It emits the same Float32 geometry as `boxVertices`, then passes one live subview per frame to the existing `Renderer.update` method. For 512 bullets, one 442,368-byte storage allocation replaces repeated JS-number assembly and per-frame conversion. **This is a rendering optimization, not collision or a new combat projectile limit.**

```js
import {BoxVertexStream} from './vendor/vanillajs/modules/render-packing/index.js';

const bullets=new BoxVertexStream(512);
const bulletMesh=renderer.mesh([]);
function renderBulletHeads(acceptedShots) {
  bullets.reset();
  for (const p of acceptedShots)
    bullets.appendXYZRGB(p.x,p.y,p.z,.12,.12,.12,1,.5,.2);
  renderer.update(bulletMesh,bullets.view());
  renderer.draw(bulletMesh);
}
```

Keep source projectile caps, actual damaging collision, stable ordering and tested replay independent of this presentation helper. Over-capacity requests throw and must be handled by explicit game policy.

## Measure allocations before optimizing visuals

[GC-PROFILE-001](docs/GC_PROFILE_001.md) is a development-only Chromium Allocation Observatory. It profiles a real packaged FPS skirmish and pairs 64–512-box WebGL visual workloads under statistical allocation sampling, conservative GC tracing and raw frame observations. No browser collector tuning, native GPU speedup or game runtime dependency is implied.

## Copper-inspired scanline presentation (COPPER-001)

The optional [COPPER-001](docs/COPPER_001.md) compiler accepts ordered per-scanline palette and horizontal-scroll commands over a read-only indexed frame, such as `BitplaneSurface.indices()`. `CopperDisplay` owns the RGBA presentation buffer; it never affects game physics or the original bitplanes. Try the [Raster Conductor](demos/copper-lab/index.html). This models the *concept* of Amiga Copper display changes, not cycle-exact beam-timed hardware.

## Classic arcade-inspired Bitplane Forge (BLIT-001)

`modules/blit/index.js` offers a bounded 16-bit planar bitmap and masked raster operations inspired by early arcade, Amiga and Atari STE blitters. The [interactive Bitplane Forge](demos/blit-lab/index.html) renders original indexed pixels into a local Canvas2D framebuffer. It does not change physics, replace the WebGL engine or claim hardware-equivalent performance. See [BLIT-001](docs/BLIT_001.md).

## Original Super FX-inspired graphics staging (FX-PIPE-001)

The experimental [FX-PIPE-001](docs/FX_PIPE_001.md) module prepares bounded RGB quads and triangles using integer Q16.16 affine transforms and one retained `Float32Array`. It is an independent **graphics preparation stage**: submit its live `view()` to `Renderer.update()` for the existing WebGL1 renderer to draw. It adds no new physics, sprite textures, compositor or performance guarantee. The caller owns the camera, 3D world authority and lifecycle.

## Record the dependency selection

Keep a small file in the consuming game, for example:

```json
{
  "repository": "https://github.com/QSOLKCB/VANILLAJS",
  "commit": "REPLACE_WITH_THE_EXACT_40_CHARACTER_COMMIT",
  "modules": ["math", "collision", "flight", "time", "input"],
  "localChanges": []
}
```

Copy complete module directories under `vendor/vanillajs/modules/`. Copy LICENSE
and NOTICE into `vendor/vanillajs/`. Pin a real commit when adopting; the example
is a template and is not a populated provenance record. A later bug fix belongs
upstream, with an explicit consuming-game update and its own tests.

## Recipe choices

- **Assisted tunnel:** set `assisted:true`; provide corridor collision boxes and
  ordered signals. The conduit uses 32 m/s² acceleration and a 27 m/s target speed.
- **Inertial arena:** set `assisted:false`; leave damping off except explicit
  braking. Open orbit uses 16 m/s² thrust and static obstacle boxes.
- **Different renderer:** consume pose snapshots only. Preserve the coordinate
  conventions or convert at the renderer boundary.
- **Bullet time:** pass a scale to `clock.advance`; keep UI timers independent.
- **Different ship mass:** fixed acceleration uses `stepFlight`; fixed force uses
  `integrateBody` and your own control law.

Before release, run module tests and game-level scenarios at different render
rates. Include input cancellation, pause, transitions, collisions and the actual
deployment subpath. Do not equate a headless simulation pass with graphics,
physical controller or device-performance validation.

## Add projectiles and conditional effects

Vendor `projectiles`, `collision`, `math` and `interactions`. Add `time` for a
fixed-step loop and whichever browser/flight adapters your game needs. The
Interaction Lab recipes are small complete consumers; their game data stays in
`demos/interaction-lab/recipes.js`. See [API contracts](docs/API.md) for validation,
event ordering and [recipe limits](docs/INTERACTION_LAB.md) for the examples.

```js
import {aabb} from './vendor/vanillajs/modules/collision/index.js';
import {ProjectileSystem} from './vendor/vanillajs/modules/projectiles/index.js';
import {createInteractionResolver} from './vendor/vanillajs/modules/interactions/index.js';

const shots = new ProjectileSystem({capacity:64});
const target = {kind:'drone',health:100};
const colliders = [{id:'drone',box:aabb([-2,-2,-22],[2,2,-20])}];
const rules = createInteractionResolver([{
  id:'pulse-hull',match:{source:'pulse',target:'drone'},
  requires:[{scope:'context',key:'shield',equals:false,
    code:'shield-active',message:'Open the shield first.'}],
  effects:[{type:'damage',amount:25}],
  reason:{code:'hit',message:'Pulse hit the hull.'}
}]);
shots.spawn({position:[0,0,0],velocity:[0,0,-100],data:{kind:'pulse'}});
const context = {shield:false};
function update(dt) {
  for (const event of shots.step(dt,colliders)) {
    if (event.type !== 'hit' || event.hit.id !== 'drone') continue;
    const result = rules.evaluate({source:event.data,target,context});
    for (const effect of result.effects) {
      if (effect.type === 'damage') target.health = Math.max(0,target.health-effect.amount);
    }
    // Display result.reasons, including blocked or resisted outcomes.
  }
}
// Invoke update from FixedClock.advance. Pausing the clock also pauses shots.
```

Include walls in the same collider query as targets so the nearest obstruction
wins. Explicitly ignore the shooter if its collider is included. Consume each
event once, retain the documented ordering, and choose when conditions are
sampled. If a dead target must reject further effects, add an `alive` requirement
as the complete Target practice recipe does. Keep cooldowns in simulation time.
On pause, clear the keyboard adapter, pointer states and queued fire commands;
do not recreate held firing from keyboard repeat events on resume.


## Build a grounded FPS

Vendor `character`, `collision`, `math`, `input` and `time`; add `weapons` and
optionally `projectiles`/`interactions`. The character's position is feet-centred,
not its eye or collision centre. Start on a valid floor and supply static boxes.

```js
import {createCharacter, characterConfig, lookCharacter, characterView,
  stepCharacter} from './vendor/vanillajs/modules/character/index.js';
import {WeaponTimer} from './vendor/vanillajs/modules/weapons/index.js';
import {Actions, attachKeyboard, attachMouseLook, fpsBindings}
  from './vendor/vanillajs/modules/input/index.js';

const character = createCharacter({position:[0,0,7]});
const config = characterConfig();
const weapon = new WeaponTimer({magazineSize:8, reserve:32});
const actions = new Actions();
const keys = attachKeyboard(window, actions, {bindings:fpsBindings,
  enabled:() => running});
const mouse = attachMouseLook(canvas, {enabled:() => running,
  onUnlock:() => setPaused(true)});
// Use the FixedClock/RAF lifecycle from the first example, replacing its update:
function update(dt) {
  const look = mouse.consume();
  lookCharacter(character, look); // deltas already in radians; no dt multiplier
  const previous = characterView(character);
  const fireEdge = actions.consume('fire'); // drain even when a button is held
  const events = weapon.step(dt, {
    fire:fireEdge || actions.value('fire') || look.pressed || look.primary,
    reload:actions.consume('reload'),
  });
  for (const event of events) if (event.type === 'shot') {
    // Cast a ray or spawn a bolt from previous.position / previous.orientation.
    // Query walls and targets together, then apply returned effects once.
  }
  stepCharacter(character, {
    move:[actions.axis('left','right'), actions.axis('forward','backward')],
    jump:actions.consume('jump'), sprint:!!actions.value('sprint'),
    crouch:!!actions.value('crouch'),
  }, dt, config, solids);
  // Interpolate previous and characterView(character) for presentation.
}
// setPaused must clear keys and mouse.release(), pause the clock and reset
// the RAF timestamp. Do not step the weapon while paused. Dispose adapters
// and renderer when your game tears down.
```

The snippet assumes the surrounding game's `canvas`, `running`, `solids` and
`setPaused` lifecycle. For a complete implementation, start with
`demos/fps-lab/app.js` and its six world recipes. For single-shot behaviour, omit
the held `actions.value('fire')` / `look.primary` terms and retain only edges.
Keep ammo/weapon timers separate from shot geometry and damage rules. Consult
[the contracts and limits](docs/FPS_LAB.md) before adapting steps or body sizes.


## Shoot at moving targets

Use `castMovingSegment` for a single swept query or `shots.stepMoving` for the
owned projectile system. Each collider supplies its **start box** and the full
tick's **displacement**, not its velocity or end box. Static walls omit motion.
Do not update target boxes first; shots and targets must share the same interval.

```js
const dt = 1/120;
const targetVelocity = [3,0,0];
const displacement = targetVelocity.map(v => v*dt);
const colliders = [
  {id:'wall', box:wallBox},
  {id:'plate', box:targetBox, displacement},
];
const events = shots.stepMoving(dt, colliders);
// Consume each returned hit once, then advance the target to its end pose.
targetBox = {
  min:targetBox.min.map((v,i) => v+displacement[i]),
  max:targetBox.max.map((v,i) => v+displacement[i]),
};
```

This snippet assumes your existing `shots`, `wallBox` and mutable `targetBox`.
The system clips target movement when a projectile's lifetime ends before the
tick ends. Instant hitscan still uses `raycast` against the current boxes; it
has no travel time to lead. Never use target displacement as ray travel time.
Translation is linear for each query: split at turns, teleports or discontinuities;
rotating/resizing colliders need another model. Tracking range's smooth paths
use straight segments between 120 Hz endpoints. Keep character movement on static
world geometry; these shot queries do not carry or push a character.


## Plan RTS routes

The navigation module is a standalone native ES module. Construct an immutable
X/Z occupancy grid for the map and the unit footprint, then request a bounded
route. Keep graphics, orders, time and movement separate from the planner.

```js
import {NavigationGrid,findPath,formationSlots}
  from './vendor/vanillajs/modules/navigation/index.js';

let grid=new NavigationGrid({width:32,height:24,cellSize:1,
  origin:[-16,-12],blocked:[[10,5],[10,6]]});
const destination=grid.worldToCell([6,3]);
if(destination){
  const result=findPath(grid,[2,3],destination,{maxExpanded:2048});
  if(result.status==='found'){
    const worldWaypoints=result.path.map(cell=>grid.cellCenter(cell));
    // Hand worldWaypoints to your movement system, after accepting the order.
    // Validate each move against current occupancy/body collision.
  }
  // 'budget' is incomplete work; 'unreachable' is a proved disconnected route.
}
grid=grid.withBlocked([[10,7]],true); // explicitly replan old orders on edits
const slots=formationSlots(grid,[22,15],6,{exclude:[[22,16]]});
if(slots.status==='found'){
  // Assign these unique cells to units, plan every route, then commit together.
  // Slot reachability from the anchor is not reachability from every unit.
}
```

Grid paths use four cardinal neighbours and uniform costs. Inflate occupied cells
for your intended body footprint; the planner does not know body radius or height.
Accepted routes need movement validation, and group destinations need a traffic
policy. See `demos/rts-lab/worlds.js` for one bounded cell-reservation example,
including stopped units, head-on swaps, retry limits and atomic rejected orders.
Its six-unit policy can deadlock; it is not a complete crowd solver. Preserve
pause cancellation for unfinished gestures while keeping accepted orders frozen.
See [RTS Lab](docs/RTS_LAB.md) for controls, scope and adoption limits.

## Share routes across many units

Use a flow field when many units need a nearest destination on the same immutable
grid. Build it in bounded slices, then let units sample it without running A* for
each order. A full field can cost more work than one short individual route.

```js
import {FlowFieldSearch} from './vendor/vanillajs/modules/navigation/index.js';
let pending=null,active=null,generation=0;
function requestField(currentGrid,goals){
  const job=new FlowFieldSearch(currentGrid,goals); // validate before replacing
  if(job.status==='blocked')return false;
  pending?.job.cancel();generation++;active=null;
  pending={job,generation};return true;
}
function fixedUpdate(dt){
  // The application's paused FixedClock does not call this update.
  if(pending?.job.status==='building')pending.job.step(32);
  if(pending?.job.status==='ready'&&pending.generation===generation)
    active={field:pending.job.result,generation};
  if(!active||active.generation!==generation||active.field.grid!==currentGrid)return;
  for(const unit of units){
    const route=active.field.sample(unit.cell);
    if(route.status==='reachable'){
      // Propose route.next to your traffic/body movement system.
      // A distance gradient does not reserve the cell or sweep the body.
    }
  }
}
```

The snippet assumes game-owned `currentGrid`, `units` and movement integration.
Call `requestField` again after terrain or destination changes. Cancel old jobs
on reset/world replacement. Preserve already accepted in-flight moves only if
the terrain edit remains safe for their full segment; otherwise stage/rollback
the world transaction. For more than one destination, integration selects nearest
distance with stable goal ties, not least congestion. The Flow convoy and Two-exit
evacuation recipes demonstrate current-generation publication and cell reservations.
They remove delivered units at exits; a persistent formation needs another arrival
policy. See [work measurements and limits](docs/FLOW_FIELDS.md).

## Ride translating platforms

Use `stepCharacterPlatforms` instead of `stepCharacter` in a platform world.
Keep a stable id for every collider and include stationary walls and ceilings in
the same list. Supply start boxes and intended translation, then commit their
end boxes only if the rider update succeeds. This mode has no automatic stairs.

```js
import {stepCharacterPlatforms}
  from './vendor/vanillajs/modules/character/index.js';

function updatePlatformWorld(dt, input) {
  // Game-owned routes produce proposed translation; stationary walls use zero.
  const proposed = world.map(surface => ({
    id:surface.id, box:surface.box,
    displacement:plannedDisplacement(surface, dt),
  }));
  const result = stepCharacterPlatforms(character, input, dt, config, proposed);
  if (result.blocked) {
    // Body was not mutated. Stop the platforms and let the player move free.
    stepCharacterPlatforms(character, input, dt, config,
      proposed.map(c => ({...c, displacement:[0,0,0]})));
  } else {
    for (let i=0; i<world.length; i++) {
      const c=proposed[i];
      world[i].box = {
        min:c.box.min.map((v,j) => v+c.displacement[j]),
        max:c.box.max.map((v,j) => v+c.displacement[j]),
      };
    }
    // Advance route clocks only here, by accepted simulated time.
  }
}
```

The snippet assumes a game-owned `world`, `plannedDisplacement`, `character` and
`config`. Also handle a blocked stopped-world update, for example by pausing and
resetting to a validated spawn. Preserve start/end poses for interpolation and
moving-shot queries before committing geometry. The complete FPS recipe stages
platform/rider movement, resolves shots over the accepted world interval, then
commits platform end poses. Pause skips all simulation, including route clocks.

`character.velocity` is world m/s; support metadata is diagnostic and also carries
state for the next tick. Jump once from an input edge, and do not manually add
platform speed a second time. Multi-actor games must stage copies of all affected
riders and world state before committing any of them. Rotating/resizing platforms,
slopes, teleporting routes and reciprocal body dynamics need separate models.

## Borrow the Clockwork Vault composition

`demos/clockwork-vault/world.js` composes character/platform movement, collision,
interactions and fixed ticks into a complete chamber. `puzzles.js` owns the
finite-word rules and bounded hint search; `app.js` owns rendering, input and
focus lifecycle. The game uses the existing Brass Engine model for staged OMI
turns. Copy the recipe deliberately; these game rules and replay schemas are
not new core APIs. See [the game contract](docs/CLOCKWORK_VAULT.md).


## Experimental MOD-SDK-001 data-only registry

The opt-in [MOD-SDK-001 contract](docs/MOD_SDK_001.md) provides a bounded, versioned, local registry for **inert data**, with dependency checks and transactional activation. It does not validate game courses or execute plugins. For exact, reusable ALIEN MATH game-authoring and a reference moddable lab, see the planned **MOD-SDK-002** phase in [ROADMAP.md](ROADMAP.md).


## Experimental MOD-SDK-002 cardinal circuits

A [typed data-only course adapter](docs/MOD_SDK_002.md) now composes MOD-SDK-001 with existing exact-course v1 and independently implemented cardinal v2 circuit math. Try the [ALIEN Circuit Foundry](demos/circuit-mod-lab/index.html) to validate a manifest, inspect raw Q16.16 coordinates and download it as inert JSON. The adapter does not supply collision physics, Float64-to-Q16 conversion, arbitrary 3D hoops, audio playback or executable plugins. Pin a reviewed VANILLAJS commit when redistributing the modules.

## Racing Lab — five complete demo-owned starting points

Open [Racing Lab](demos/racing-lab/index.html) for an original retro pseudo-3D highway, 3D circuit, demolition derby, car-football arena or elevated stunt course. Vehicle game rules live in `demos/racing-lab/world.js`; the optional 3D renderer uses existing `modules/render-webgl`, and the browser shell uses `modules/time` with fixed 1/60 s steps. These are **experimental demos**, not an exact Q16.16 driving API. For exact checkpoint authoring see [Circuit Mod Lab](demos/circuit-mod-lab/index.html). The controls, failure modes and replay limitations are described in [RACING_LAB.md](docs/RACING_LAB.md).

## Manage a football club

Open [Touchline](demos/football-manager/index.html), choose one of SOCCERWEB's
eight clubs, and manage the squad, tactics, training and finances. Press Play to
watch a real AI match, then continue through the home-and-away league. The
[football SDK guide](docs/FOOTBALL_SDK.md) includes a runnable headless example,
validated JSON mod format and replay contract. Start from
[demos/football-manager/starter.json](demos/football-manager/starter.json), then
use the in-game Mod workshop to validate, export and start a custom career.
