Skip to content

Making a game ​

A game by hand, file by file: the rules, the look, the page. Then what to add, in order. For a ready project, run npm create @v12-engine my-game (Install).

A game ​

A game is one object made with createGame. The page, a server, the map editor and tests all take it. Keep it to the engine alone so they all play the same game:

ts
/**
 * The game: what there is, its maps, and what happens once a game starts. The engine alone: how it looks is
 * `src/view.ts`, fetched as the page first plays it, so the server and the tests read this file without the client
 */
import { coreVictory, createGame, defineIds, type IdOf, mapsFrom } from '@v12-engine/engine'
import field from './maps/field.vgmap.json'

export const UNIT = defineIds('knight')
export type Unit = IdOf<typeof UNIT>

export const game = createGame({
	// the maps of this game say they are its own by this id: change it, and change theirs (`"game"`) with it
	id: 'my-game',
	name: 'My game',
	// a view that names what the rules do not have stops the page, saying what was meant
	checkView: 'throw',
	// the last side with a knight wins. The engine's own rule, left out, counts buildings, and there are none here
	victory: coreVictory((_world, entity) => entity.def.id === UNIT.knight)
})

game.unit({
	id: UNIT.knight,
	name: 'Knight',
	kind: 'unit',
	radius: 0.5,
	stats: { health: 400, attackDamage: 25, attackSpeed: 1, attackRange: 0.6, moveSpeed: 4 },
	sight: 12,
	attacks: [{ damagePoint: 0.4, acquisitionRange: 8 }]
})

// its maps by name, made in its editor (`npm run dev`, then `/?editor`: Save writes them into `src/maps`). The first is
// the one a game is on when nothing says which; a save of a game on one keeps only what changed of its ground
game.maps(mapsFrom({ './maps/field.vgmap.json': field }))

// what the game does once a world is made from a map, before anyone plays: five knights for each player with a start.
// The page, the server and the editor's Play here each run it with the map
game.onStart((world, { map }) => {
	for (const player of map?.players ?? []) {
		if (!player.start) continue
		for (let i = 0; i < 5; i++) world.spawn(UNIT.knight, { at: { x: player.start.x, z: player.start.z - 4 + i * 2 }, owner: player.id })
	}
})

// how it looks, fetched as the page first plays it: nothing of the client is in what a server or a test imports
game.view(() => import('./view'))

The look, fetched only when a page first plays (src/view.ts):

ts
/** How the game looks: fetched as the page first plays it (`game.view(() => import('./view'))`) */
import { type GameView, presetView } from '@v12-engine/client'
import type { Unit } from './game'

/** A knight is a box in its side's colour, until it has a model (a `.glb` in `public/`) */
export const view: GameView<Unit> = presetView({
	units: {
		looks: {
			knight: { height: 1.6, shapes: [{ shape: 'box', size: [0.7, 1.4, 0.7], offset: [0, 0.7, 0], color: 'team' }] }
		}
	}
})

presetView adds the client's ready-made looks under yours: weather, ability styles, rally flag, buff glow and the engine's tiles. presetView(view, { weather: ['rain'], tiles: false }) picks which.

No map file yet? Make one in code: createMap({ name: 'The field', width: 48, depth: 48, game: 'my-game' }), give its players a start, pass it to game.maps({ field: map }).

Launch ​

The page (src/main.ts): appScenes makes the start screen, the game, a random map (when the rules have a generator), settings, the editor and a server seat. startApp shows them.

ts
/** The page: the game's start screen, and what it goes to from there */
import { appScenes, sceneAsked, startApp } from '@v12-engine/client/app'
import '@v12-engine/client/styles.css'
// the theme's typefaces come with the client: the page's own font stays what it was
import '@v12-engine/client/fonts.css'
import '@v12-engine/editor/styles.css'
import { game } from './game'

// a plain array: a scene of the page's own is added to it, one it has no use for taken away. The game's look (and the
// client that draws it) and the editor are fetched as a scene first needs them: the start screen shows at once
const scenes = appScenes({
	game,
	editor: (scene) => import('@v12-engine/editor').then((editor) => editor.editorScene(scene)),
	server: true
})
// the address opens straight into a scene by its id (`/?editor`, `/?server`), the start screen otherwise
const app = startApp({ target: '#game', game, scenes, start: sceneAsked(scenes, 'home') })
Object.assign(window, { app })
html
<div id="game" style="height: 100vh"></div>
<script type="module" src="/src/main.ts"></script>

Done: five knights a side, fog, selection, orders, the HUD, the minimap and the debug panel (Alt+Shift+D, or the 🐞 button, while developing).

For one game with no start screen: launch({ target: '#game', game, debug: true }). launched.ready is the client; restart() and dispose() restart and end it.

Keep the page smooth with workers ​

WorkerFile (two lines)Pass it as
Navigation buildsserveNavigationBuilds() from @v12-engine/enginenavigationWorker: () => new Worker(new URL('./navigation.worker.ts', import.meta.url), { type: 'module' })
Ground texturesserveGroundTextures() from @v12-engine/client/groundgroundWorker
The whole simulationbelowworker

Pass a function and the worker is made only when first needed. Starters already have the first two. Navigation is cached by a hash of the ground, so a restart or a load is instant.

The simulation runs in the page unless a game asks for a worker, and that is the default to keep: at WC3 scale (a mission of about 50 entities) the worker measured worse than the page (p99 frame 27.5 ms against 16.5, with hitches over 33 ms the page did not have), since a small tick gains nothing and the hand-over between the threads costs. Measure first, and run the simulation in a worker only when ticks are long (big fights, large maps):

ts
// game.worker.ts
import { serveWorld } from '@v12-engine/engine'
import { game } from './game'

serveWorld(game.toRules(), { onStart: game.toStart() })
ts
// main.ts: no `onStart` here, it is the worker's
launch({ target: '#game', game, map: await game.loadMap(), worker: new Worker(new URL('./game.worker.ts', import.meta.url), { type: 'module' }) })

Same seed, same game. Pause, saves, checkpoints, the log and the debug panel still work. Not in a worker: replays, drawing the navmesh, start/world/player in code (give them to serveWorld; plain data goes as workerArgs). The screen shows a tick behind.

A campaign's missions run in a worker the same way. Its file plays the missions' code (onStart, carry) there, so keep that code in a module with nothing of the page in it (no screens, no look):

ts
// sim.worker.ts
import { serveCampaign } from '@v12-engine/client/campaign-worker'
import { game } from './game'
import { MISSION_CODE } from './missions' // the same list `defineCampaign` gets as `missions`

serveCampaign(game.toRules(), { missions: MISSION_CODE })
ts
// main.ts
startApp({ target: '#game', game, scenes, worker: () => new Worker(new URL('./sim.worker.ts', import.meta.url), { type: 'module' }) })

The campaign sends the worker the mission's id, the progress and the difficulty. The heroes carried in, the mission's onStart, a cinematic briefing (held) and carry all run in the worker. When the mission is won, the page gets plain data back (the time, the stats, the heroes and what carry gave), keeps the progress and shows the debrief. The debrief's rating runs in the page, from the stats. Only campaign missions use this worker: free play, a random map and the editor's Play here stay in the page. A campaign with watch (it shares a world of the page's) must say worker: false; otherwise its mission fails with an error. As with any game in a worker, a mission there records no replay, and the page can't reach into its world (client.local is undefined).

Large armies ​

baked: true on a type's look draws it as copies of one mesh with baked animations: 1,000 footmen at 60 fps instead of 5. A unit gets its own skeleton back when something needs its parts, and within baked: { near } of the camera while it is in view (off the screen it stays a copy, and takes its skeleton just before it comes into view). baked: { model } bakes a simpler model. Copies snap between animations instead of blending.

Change a look while it plays ​

client.looks.set('knight', { height: 1.8, model: { src: 'units/knight-gold.glb', scale: 1 }, shapes: [] }); client.looks.get(type) reads it, set(type, undefined) resets it.

Packs ​

The engine's core is what every RTS has: units, buildings, orders, combat, production, supply, fog. Everything else is a pack you add to packs, in the order they apply:

ts
packs: [heroesPack(), concealmentPack({ layer: 'bush' }), capturePack(), stancesPack()]

A game without a pack pays nothing for it: no commands, saves, snapshots or editor fields.

PackBrings
heroesPack(HeroSettings)Heroes, creep camps, shops, taverns (Give my game heroes)
respawnPack, lastHitsPack, lanesPack, mobaStatsPackMOBA rules
concealmentPackHiding in a cell layer (Maps)
foliagePackGrass and bushes: hiding by style, trampling, fire, ruin and growing back (Grass and bushes)
burningPackTrees and buildings that burn (Let trees burn)
capturePack, stancesPack, remainsPack, veterancyPack, wallsPackAs named
movesPack, groundObjectsPack, resourcesPack, holdsPack, abilityChangesPack, visionPackAbility extras (Abilities)
tomesPack, manaBurnPack, runesPack, portalsPack, destructiblesPack, friendlyFirePackClassic RTS rules

Your own lists come after a pack's, so a command, hook or system with the same id replaces the pack's. withoutCommands, withoutOrders, withoutSystems and withoutHooks take one out. hasPack(game, HEROES) says whether a game has one. A mod changes packs with game.packs.

A pack is a GamePack: commands, orders, systems, hooks, listeners, effects, components, events, timers, stats, statFields, report additions, victory, a map check, settings(resolved) laid over the game's (which wins), and requires. assembleGame(game) puts them together. Packs take part through three hooks: made (a unit just made), morphed (turned into another type) and fallenHero. The heroes pack (packages/engine/src/packs/heroes/) is written as yours would be: its commands join Command by declaration merging (interface Commands { heroes: … }).

What reloads as you save ​

In the dev server, saving a game file updates running games and editors, or reloads the page. The console says why when it reloads.

SavedWhat happens
Unit types, abilities, buffs, items, upgrades, races; their effects' and orders' codeTaken: units take their types as they are now
settings, score, day, report, tunables, upkeep, game files (data.json)Taken
The view's looks (looks.json)Taken (hotView)
A modTaken (hotMod, recompose)
A model or texture in publicTaken (hotFiles)
systems, withoutSystems, hooks, withoutHooks, components, resourcesPage reloads
The rest of a view (HUD, parts)Next game has it
A game in a worker without reload, or over a wireKeeps the version it began with

Wire it with hotGame in the file that makes the game:

ts
if (import.meta.hot) import.meta.hot.accept((module) => hotGame(import.meta.hot, game, module?.game))

Rebuild your own caches in Rules.onReload(world) or on gameReloaded.

Your own game, in order ​

  1. Data: units, abilities, buffs, resources (Add a unit type).
  2. A page: createGame, a view of units.looks (shapes are enough), startApp.
  3. What makes it yours: hooks, listeners, orders, timers, components (The world). Change how something behaves says which to pick.
  4. Winning and losing: a victory system, or objectives with objectiveVictory (Make a mission).
  5. Words: message keys in the rules, words in the view's messages.
  6. The look: models, sounds, effects, HUD lines and buttons.
  7. Tests of the rules, and a save and load halfway (Test my rules).

Reference ​

One object, and what is under it ​

Game callWhat it does
unit, ability, buff, item, upgrade, race, resource, stat, system, order, component, command, event, area, prefab, timer, sequence, file, brain, tile, effect, targeting, formation, tunable, cellLayerRegister one; returns the definition.
pack(p), settings({ … })Add a pack; lay settings over, group by group.
on(event, fn)A listener.
before(hook, fn), after(hook, fn)A hook handler before (priority -1) or after (1) the engine's. { priority }, { id } to choose.
onStart(fn)Runs once a world is made. May be given more than once.
mission(id, (m) => …)A mission with ids of its own: m.objective, m.sequence, m.timer, m.component, m.area, m.on, m.before, m.after, m.onStart, m.plays(map), m.idOf(id).
await check()Problems before play: checkRules, ids given twice, each map against the rules.
toRules(), toView(), toStart(), toMaps(), loadMap(name)The parts underneath.

createGame(rules) wraps a Rules written whole. Every host takes a game, or the raw parts: testWorld(rules), startServer({ rules, map, onStart }), loadedGame(rules, view). loadGame(game) fetches and checks the view once.

Launch, declared or in code ​

DeclaredIn code
map, seed, player, startworld: ({ rules, seed }) => createWorld(...), player: (world) => id
from: savegame.restart(save)
session: () => connect(socket, { rules: game })a game run elsewhere
viewview: (view) => ({ ...view, theme: 'moonlight' })
saves: true, replays: truesaveGame, listSaves, loadSave, updateSave; replays: { keep }
saves: { store }, settings: { store }a Store (below)
hud: false, leave, loading: { text }loading: { mount }
error: { title, text }error: { component } or { mount }; onError, onCrash: (report) => …
all of itprepareGame, assembleClient, runGame, GameMount

Saves and settings ​

saves: { autosave: { every: 300, atStart: true, keep: 3 } } autosaves every 300 seconds of game time into Autosave 1–3 (autosaveName(n)). F5 quick-saves (QUICK_SAVE), F6 loads it; players can rebind them (game.quickSave, game.quickLoad). Each save keeps a 320-pixel JPEG (SavedGame.picture).

Saves live in IndexedDB and settings in localStorage unless you pass a Store:

ts
interface Store<R extends { id: string }> {
	list(): Promise<R[]>
	read(id: string): Promise<R | undefined>
	write(record: R): Promise<void>
	remove(id: string): Promise<void>
	heads?(): Promise<Partial<R>[]> // optional: the records without their heavy field, for a list
}

indexedStore(database, name, heavy?) is the browser's own. createSaves({ store }), listSaves, loadSave, saveGame, deleteSave take a store last. A desktop app keeps them as files (A desktop game, offline).

Installing by hand ​

npm install @v12-engine/engine @v12-engine/client

Packages are ES modules with types; Vite needs no setup. The client draws with its own WebGPU renderer (@v12-engine/render, installed with it). Write Solid components of your own? npm install solid-js (1.9).

How units find their way ​

LimitDefault
Path search (maxNodes)A quarter of the map's cells (4096–65535)
Obstacles (maxObstacles)Half the map's cells (8192–65535). Past it, placing is refused (tooManyBuildings).
Repaths after a building changesAn eighth of chasing units a tick (REPATH_SPREAD)
Unit sizes (radii)'auto': a navigation per size group (≤0.5, ≤0.75, more). false for one, or a list. See On the move.

Set them in Rules.navigation, or the world's navigation option.

Declared, or in code ​

Every declared field has a way to decide it in code. Declared, or in code has the pairs.

Seeing what it does ​

ToolWhat it is
Debug panelSpeed, fog, cooldowns, spawning. client.debugTools adds toggles, numbers, actions; client.debugTools.setSpawnTool(tool); counters in perf.
Cheatsreveal, cheat('noCooldowns' | 'noManaCosts' | 'invulnerable', on), client.debugTools.setHour(hour), giveResources, client.debugTools.giveExperience(amount), giveItem, setLevel, levelUp, win, lose.
Inspector, entities, event log, consoleLive numbers, everything by player, recent events and hooks, world.log and client.log.
Browser testsnpm run test:browser (Playwright, Chromium, software WebGL). Once: npx playwright install chromium.
Balance runssimulate(simulation, { seeds, workers }) (Test my rules).

A whole game: the campaign ​

The campaign starter (npm create @v12-engine my-game -- --starter campaign) is a whole game on the public API: three missions, a hero carried between them, a base, a siege of waves at night, a warlord. Let's make a basic campaign builds it step by step. Where to look for each idea:

File in src/campaign/Shows
units.tsUnits, buildings, a hero (hero.learns), splash (attack.splash), an effect of its own (Judgement)
maps.ts (files in src/maps/)Maps by file (mapsFrom), names found by the rules
missions/Objectives with objectiveVictory, areas, sequences with talk and a cinematic, a prefab (definePrefab, world.spawnPrefab), a missionBrain, a choice answered as a command (cinematicChoice)
waves.tsA component for wave state, timers, a listener on entityDied, a game file the editor writes (defineGameFile), a command (nextWave), a replicated event, the report, gates (setGate)
kills.tsA replicated component counted by a listener
index.tsEverything listed in the rules, editable fields, players
scenes.tsThe campaign: missions in order, the hero carried, menu, saves (defineCampaign)
view/index.tsLooks, effects, words, HUD lines and buttons, speakers
view/labels.ts, view/rubble.tsRenderers: a pinned label, a GUI label, physics debris
view/fire.tsA spell style (SpellStyleFactory)
view/cinematics.ts, cinematics/*.json, view/waveLane.tsCinematics in files and in code, a lane of its own (defineLane)