Skip to content

Maps ​

A map is where a game is played: its ground, players and starts, what stands on it, and the places your rules find by name. It's plain data (GameMap), kept as a .vgmap.json file. To make one, see Make a map and load it in code.

Load your maps ​

ts
import { type GameMap, parseMap } from '@v12-engine/engine'
import field from './maps/field.vgmap.json'

export const maps: Readonly<Record<string, GameMap>> = { field: parseMap(field) }

/** A map by name, as a copy: a game changes nothing of what the next one starts from */
export function mapNamed(name = 'field'): GameMap {
	const map = maps[name]
	if (!map) throw new Error(`There is no map "${name}"`)
	return structuredClone(map)
}

Then make a world on one: await createWorldFromMap({ map, rules, seed: 1 }). A map for another game (its game isn't your rules' id) is refused, as is one with more players than Rules.maxPlayers (8).

With many or large maps, load each only when it's opened. mapsFrom with a lazy glob gives LazyMaps, which appScenes accepts:

ts
import { mapsFrom } from '@v12-engine/engine'

export const maps = mapsFrom(import.meta.glob('./maps/*.vgmap.json', { import: 'default' }))
const field = structuredClone(await maps.field())

A game whose server or tests read maps in Node keeps them loaded eagerly, as the starters do.

Make a map in code ​

ts
import { createMap, mapText } from '@v12-engine/engine'

const map = createMap({ name: 'The field', width: 48, depth: 48, game: 'my-game' })
map.players[0].start = { x: 12, z: 24 }
map.players[1].start = { x: 36, z: 24 }
const file = mapText(map) // the text of a .vgmap.json file

Files are written to diff and merge well: one object a line, one row of ground a line. parseMap upgrades older formats.

Find things by name ​

Rules never hold coordinates. They ask the map by name, so the same rules play on every map with those names.

ts
// the tower defense: the invaders walk the road, and come in at the entry
const road = world.map.path('road')
const entry = world.map.point('entry')
road.length // how long it is; road.at(distance), road.nearest(point)

The editor writes <name>.names.ts beside each map, so a typo doesn't compile:

ts
import type { RoadPaths } from './maps/road.names'

world.map.path<RoadPaths>('road')
On the mapIn the rules
A unit or buildingworld.named('gate')
A region (rect, circle, polygon)An area: world.areas, enteredArea, leftArea
A point, facing a wayworld.map.point('entry')
A path, with a widthworld.map.path('road'): length, at(distance), nearest(point)
A player's own fieldsworld.map.player(id).data
The map's own fieldsworld.map.data

A name belongs to one thing per map. Your game checks a map has what it needs with MapEditorDef.check (in Rules.editor); the editor won't play a map with an error.

Put units at the starts ​

ts
export function onStart(world: World, { map }: { map?: GameMap }): void {
	for (const player of map?.players ?? []) {
		if (!player.start) continue
		for (let i = 0; i < 5; i++) world.spawn(UNIT.knight, player.id, { x: player.start.x, z: player.start.z - 4 + i * 2 })
	}
}

Or say it in the rules: Rules.start.spawn(world, player, at) runs for each player the map places nothing for. On a server, each map player with a start is a seat.

Paint layers of your own, and hide in them ​

A cell layer is a value per cell (0–255) your rules read: bushes, blight. Declare it with defineCellLayer in Rules.cellLayers; paint it in the editor's Terrain panel, under the layer's name. Read it with world.terrain.cellAt('bush', x, z); change it while the game runs:

ts
world.setCells('bush', { kind: 'circle', x: 40, z: 22, radius: 3 }, 0) // the bush burnt

Players see a change where their team sees; elsewhere they keep the cells as last seen (TeamMemory.cells), so spreading blight isn't given away.

Concealment hides whoever stands in a layer, like MOBA bushes. A team sees into a patch only from inside it or from close by:

ts
import { type Rules, concealmentPack } from '@v12-engine/engine'

export const rules: Rules = { ...myGame, packs: [concealmentPack({ layer: 'bush', reach: 2 })] }

Options: hides (who hides; ground units by default), reach, seenBy (a ward, an ability), rustle (shake the bushes for teams that can't see). patchAt(world, layer, x, z) says which patch a place is in. Targeting, commands, snapshots and computer players all respect it.

How a layer looks is the view's (GameView.ground.cellLayers). Ready-made parts:

  • foliage(look): bushes or tall grass that sway and shake. See Make bushes of my own.
  • groundPaint(look): paint laid into the ground, tinted, with a soft ragged edge that creeps as it spreads (melee's blight).

Several parts make one look: blight: [groundPaint(...), gases()].

Generate maps ​

Declare a generator (Rules.generator): parameters and passes that each do one thing. The same seed always makes the same map. The editor's File › New map from a generator… and the start screen's Random map (randomMapScene) use it.

ts
import { createRegistry, generateMap, presetGenerator } from '@v12-engine/engine'

const generator = presetGenerator({ trees: ['forest/common_tree_1.glb', 'forest/pine_1.glb'], rocks: ['forest/rock_medium_1.glb'] })
const { map, problems, seed } = generateMap(generator, { seed: 7, width: 128, depth: 128, players: 2, symmetry: 'half' }, createRegistry(rules))

presetGenerator({ trees, rocks, treeScale, start }) runs terrain, paint, starts, trees and rocks. The empty starter uses it.

Add a pass of your own:

ts
const shrine: GeneratorPass = {
	id: 'shrine',
	name: 'The shrine',
	run(ctx) {
		const x = ctx.map.width / 2
		const z = ctx.map.depth / 2
		ctx.addObject('shrine', MAP_NEUTRAL, x, z)
		ctx.addRegion('shrine', { kind: 'circle', x, z, radius: 6 })
		ctx.mark('shrine', x, z, 6) // what comes after keeps off it
	}
}
export const rules: Rules = { /* … */ generator: { ...presetGenerator(), passes: [...presetGenerator().passes, shrine] } }

Scatter more kinds of scenery:

ts
scatterPass({
	kind: 'ruins',
	density: 0.01,
	spacing: 12,
	avoidKinds: { trees: 3 },
	where: (cell) => cell.level > 0 && cell.slope < 0.3,
	what: (ctx, at) => ctx.addDoodad({ model: 'buildings/ruin.glb', x: at.x, z: at.z, yaw: ctx.rng.next() * Math.PI * 2, blocks: 'build', radius: 2 })
})

A parameter with the kind's id ({ id: 'ruins', name: 'Ruins', default: 0.01, min: 0, max: 0.05 }) becomes a slider in the editor and on the Random map screen.

Ship maps with your game ​

ts
export const rules: Rules = {
	id: 'my-game',
	name: 'My game',
	units: [/* … */],
	maps: Object.values(maps)
}

A world on a shipped map saves only the map's name, a hash of its ground, and changed cells: bytes, not megabytes. If the map changed since, the save is refused (SaveError, reason: 'ground'). Adding a map doesn't change the rules' hash.

Reference ​

What a map holds ​

FieldWhat it is
width, depthSize in cells.
groundHeights, cliff levels, ramps, water, and paint (tileset, by tile name).
playersMapPlayer: id, name, team, color, start, controller ('person', 'computer', 'nobody'), resources, data.
objectsUnits and buildings, with owners.
campsCreep camps.
doodadsScenery. The rules see only what it blocks.
regions, points, pathsNamed places.
boundsThe playable part; the rest is scenery. The camera keeps to it.
pathingHand-painted BLOCKS_BUILD or BLOCKS_WALK per cell.
cellsYour cell layers.
dataYour own fields.
environmentWater, light, sky, fog, weather, lights, effects. Its types (MapLight, MapWeather…) come from @v12-engine/client.
generatedHow a generated map was made.

Region shapes ​

AreaShape is a circle (radius), a rectangle (width, depth) or a polygon ({ kind: 'polygon', x, z, points }, corners relative to its middle; concave is fine). Helpers: inShape, shapeBounds, shapeArea, shapeReach, shapeAt, shapeAsBox.

Generator options and passes ​

generateMap(generator, options, registry) takes seed, width, depth, players, a name, params, symmetry (none, across x, across z, both, half turn, quarter turns) and tries (4: re-rolls a map with a blocking problem). It returns map, problems (checkMap) and the seed used.

PassWhat it doesTakes
terrainPassCliff levels, water, rolling ground, ramps joining every partlevels, water, roughness, hills, ramps, rampWidth, shape (basinShape)
tilesPassPaint: sand by water, rock on slopes, snow up high, dirt where drytile names, or by(cell)
startsPassA start per player, far apart, in a flat clearingclearing, spread, from(player, at, ctx)
scatterPassThings in noisy patches, spaced apartkind, what, density, spacing, avoid, avoidKinds, where, patches
resourcesPassA resource by each start, more about the mapmain, extra, spacing, from
roadsPassRoads between starts or given places, by ramps, round watertile, width, between

A pass is { id, name, run(ctx) }. GeneratorContext has map, rng, param(id, fallback), symmetric(x, z), noise(name, cells), placed, mark, free, and addObject, addCamp, addDoodad, addRegion. Helpers: nearestDryGround, clearGround. The example's melee generator (apps/example/src/games/melee/generator.ts) and The Bay (bay.ts) are full examples.

In the editor's code ​

opened.editor.doc is the editor's MapEditor (addPath, addPoint, addRegion…); editor.edit(action) makes one undo step. See The map editor.