Skip to content

Repository files navigation

three-hex-map

A Civilization-like 3D hexagonal terrain map for the browser, built on three.js and rendered with instancing + custom shaders. One draw call per layer, no per-tile meshes.

See the live demo · Changelog

Screenshot

Features

  • Instanced terrain - the whole map is a handful of InstancedBufferGeometry draw calls (land, water, grass, trees), with grid lines, land-type edge blending and beach slopes computed in the shaders.
  • Animated water - sea/coastal tiles render as a solid-colored, wave-displaced surface (sum-of-sines with analytic normals) with sparkle, fresnel and stylized coastal foam waves rolling towards every shoreline.
  • Rivers - mark a grass tile with the "river" modifier and it renders an animated water channel with noise-curved banks, a light vegetation strip, a carved 3D riverbed and shallow-to-deep shading. Connectivity is auto-detected from neighbors: rivers merge at junctions, spring from source pools and flow into lakes and the sea.
  • Lakes - the "lake" modifier fills a tile with water except a noise-curved grass shore rim; neighboring lake tiles merge into one body and river channels visibly open through the shore.
  • Forests & grass - instanced glTF tree models per wood tile (mixable species via per-tile treeModel) and a wind-animated grass-blade layer on grass tiles. Both automatically keep clear of river/lake water.
  • Cities & buildings - cities with territory and their own stores; buildings in a city or on tiles, built by cities or units over turns or with unit charges, with costs paid upfront or per turn from configurable stores. Everything is game data.
  • Players & turns - owners of units, cities and buildings: each with a color (ring under its units) and its own fog of war. Players play in turn (game.endTurn()); units have movement points per turn and long move orders continue over the next turns.
  • Units & game loop (optional GameEngine) - glTF units with animations, click-to-move A* pathfinding with terrain/unit restrictions, hover route preview.
  • Resources & yield view - the game defines its own resources (food, iron, mana - nothing is built in) with icons, and base yields per terrain type / modifier / tile; game.yieldsVisible = true shows them as icons over every tile, Civ-style.
  • Fog of war - unseen tiles render a fog texture, explored-but-out-of-view tiles render darkened, across every layer (terrain, water, grass, trees, cities, units). Can be hidden/re-shown at runtime without losing state.
  • Map styles - the ground is drawn by a pluggable style: textured (below) or 3D tile models like Kenney's Hexagon Kit; a build carries only the style it imports.
  • Live tuning - nearly every visual knob is a live shader uniform exposed as a property (see the dat.gui panel in the demo); no rebuilds needed.

Getting started

Run the demo locally

git clone https://github.com/gunyakov/three-hex-map.git
cd three-hex-map
npm install
npm run start   # builds the library + demo, then serves ./public

Open http://127.0.0.1:3000. The demo page (public/index.html) is also the best usage reference - it spells out every option and wires a dat.gui panel to the live-tunable properties.

Use as a library

three.js is a peer dependency - your page/bundle supplies its own copy.

import { HexMap, TexturedStyle } from "three-hex-map";

const map = new HexMap({
    element: "canvas",          // CSS selector of your <canvas>
    size: 40,                   // hex circumradius, world units
    style: new TexturedStyle({ texturesBaseUrl: "textures/" })  // or TilesStyle, see "Map styles"
});

await map.load(mapData);        // MapInfo, see "Map data" below

map.on("click", ({ x, y, tile }) => console.log("clicked", x, y, tile));
map.on("hover", ({ x, y, tile }) => console.log("hover", x, y, tile));

Or take the batteries-included game loop (unit selection, click-to-move, fog of war driven by unit view ranges):

import { GameEngine, TexturedStyle } from "three-hex-map";

const game = new GameEngine({ element: "canvas", style: new TexturedStyle(), fogOfWar: true });
// players: [{ id, name, color }], units: UnitPlacement[] ({ id, type, owner, x, y })
await game.init({ map: mapData, players, units, resources });

game.on("unitClick", ({ unit }) => console.log(unit.actions));
game.on("end_move", ({ unit, to }) => console.log(unit.id, "arrived at", to));

// units
const scout = await game.createUnit({ id: "scout", type: "Assets/units/ship", owner: "vikings", x: 17, y: 16 });
scout.on("before_move", e => { if (tooFar(e.path)) e.cancel(); });
const arrived = await scout.move({ x: 5, y: 16 }); // false if refused
game.removeUnit("scout");

Map data

HexMap.load() / GameEngine.init() take a plain MapInfo object - see public/gameInfo/map.json for a full example:

{
  "w": 39, "h": 34,
  "data": {
    "0": {                       // column x
      "0": {                     // row y
        "type": "land",          // sea | coastal | land | sand | tundra | snow
        "modifiers": ["wood"],   // optional flags, see below
        "treeModel": "Assets/models/oak", // optional per-tile tree species
        "yields": { "iron": 2 }   // optional per-tile resource bonus
      }
    }
  }
}

Tile modifiers

Modifier Effect
"hill" raised-looking tile
"wood" scatters instanced tree models on the tile
"river" animated water channel through the hex; connects automatically to neighboring river/lake/sea/coastal tiles (a single-connection tile renders a source pool)
"lake" water fills the hex except a grass shore rim; adjacent lake tiles merge into one body, adjacent rivers flow in through channel openings

Modifiers are free-form strings, so new ones don't require core changes - only shader/atlas support for whatever reads them.

Units

Units are declared as an array of placements ({ id, type, owner, x, y }) where type is a model folder (e.g. Assets/units/ship) containing model.glb + info.json. The info.json carries both the model fine-tuning (offset/rotation/scale) and the gameplay stats: movement points, health, attack/defence, view range, allowed terrain types and animations. Tree and city models follow the same folder convention.

Skinned, animated models work too: "animations": { "idle": "idle", "walk": "walk" } in info.json maps the unit's states to clip names in the glTF - idle plays while it stands, walk while it moves, unit.animate(state) plays any other (e.g. an attack).

Unit behaviors

Code that belongs to a unit type rather than to the engine - procedural animation, effects, anything per frame - is plugged in from its info.json and loaded at runtime; the engine itself contains none of it:

"behaviors": [
  { "script": "../../behaviors/motion.js", "waves": true, "parts": [...] },  // ES module, URL relative to the model folder
  { "code": "export default ctx => ({ update(dt) { ... } })" },              // the same, inline
  { "use": "sparkle" }                                                       // compiled into your game: registerUnitBehavior("sparkle", factory)
]

A behavior module's default export gets a context - unit, root (placed and turned by the engine), body (holds the model; only behaviors move it), model, options (its own info.json entry), size, heightAt(x, z), three (math classes, so the script needs no import "three") - and returns { update(dt), dispose() }, both optional. A module loads once and is shared by every unit using it; one that fails is reported in the console and skipped. Scripts run with the page's full rights - load only your own.

The demo's Assets/behaviors/motion.js rocks the ships on the waves and swings named parts: flags and sail of the ship, the rowboat's paddles only while it moves.

Map styles

The map itself (camera, picking, markers, move area, yield icons, units, cities, the game) does not know how the ground is drawn - a style does. Two come with the library:

  • TexturedStyle - textured terrain blended across tile borders, mountains with ridgelines, a smooth coastline, animated water with foam, meandering rivers and lakes, wind-blown grass, instanced trees.
  • TilesStyle - every tile is a 3D model from a tile set: low poly and flat colors, like Kenney's Hexagon Kit (the demo's set, Assets/tiles/kenney-hexagon). Another look = another tile set (models + a JSON of rules), no code. Much lighter to render.
import { HexMap, TilesStyle } from "three-hex-map";
const map = new HexMap({ element: "canvas", style: new TilesStyle({ tileset: "Assets/tiles/kenney-hexagon/tileset.json" }) });

Only the imported style is built in. The package is marked "sideEffects": false, so a bundler drops the style a game doesn't import together with its shaders (a game with TilesStyle only: ~210 KB of library code, with TexturedStyle only: ~320 KB). For <script> pages there is one prebuilt bundle per style: hex-map.global.js (textured) and hex-map.tiles.global.js (tiles). The demo switches with ?style=tiles.

A style object holds its own live settings: map.style.waterWaveAmplitude = 2 (textured). Writing your own style: implement MapStyle - build the ground for a map, answer heightAt(), draw fog states, clear decorations under cities.

Options

HexMapOptions (src/HexMap.ts) - the same with every style:

Option
element CSS selector of the <canvas> (required)
style the map style (required)
size hex circumradius, world units (default 40)
gridVisible hex grid lines
selectorColor, pointerColor, moveAreaColor, routeColor markers
fogDarkenFactor color multiplier of Explored tiles (default 0.45)
yieldIconSize resource icons
GameEngine only fogOfWar, preventCellClick, tileYield, moveCost, canBoard (rule hooks), cityModel, cityRadius, cityWork, cityIncome

TexturedStyleOptions (src/styles/textured/TexturedStyle.ts):

Group Options
Textures texturesBaseUrl, layerScale, normalStrength
Grid look gridColor, gridWidth, gridOpacity
Water waterColorShallow/Deep, waterWaveAmplitude/Frequency/Speed, waterSparkleIntensity, waterFresnelIntensity, waterDepth, beachWidth
Coastal foam coastalWavesEnabled, coastalWaveColor/Count/Speed/Width/Range/Distortion/Opacity
Blending landBlendWidth, landBlendCurvature, coastCurvature
Mountains mountainHeight
Rivers & lakes riverWidth, riverMaxWidth, riverCurvature (meander), riverBankWidth, riverEdgeNoise, riverColorShallow/Deep, riverBankColor, riverFlowSpeed, riverDepth
Trees treesPerTile, treeModel, treeScale
Grass grassEnabled, grassDensity, grassBladeWidth/Height, grassWindStrength/Speed
Fog of war fogTexture, fogTextureSize

Almost all of these are also live properties of the style (style.riverCurvature = 0.8, style.waterWaveSpeed = 2, ...) backed by shader uniforms - only a few (tree/grass density and sizes) rebuild their layer.

TilesStyleOptions (src/styles/tiles/TilesStyle.ts): tileset (URL of a tile set JSON or the object), gridColor, gridOpacity.

Tile sets

{
  "radius": 0.57735,      // a model's hex corner radius in its own units (scaled to the map's size)
  "rotation": 30,         // degrees onto the map's hexes: 30 for pointy-top models, 0 for flat-top
  "fog": { "color": "#9aa6b2", "height": 0.28 },   // Unseen tiles: a flat hex
  "rules": [              // first match wins
    { "modifiers": ["lake"], "model": "water" },
    { "modifiers": ["river"], "connect": ["river", "lake", "sea", "coastal"],
      "models": { "river-straight": [0, 3], "river-corner": [3, 5], ... } },   // open sides of each model
    { "modifiers": ["wood"], "model": "grass-forest", "cleared": "grass", "surface": 0.2 },
    { "type": "sand", "model": ["sand", "sand", "sand-desert"] },            // variants, one per tile
    { "model": "grass" }
  ]
}

A rule matches by type (one or several) and modifiers (all present). model is a <name>.glb next to the JSON (or in baseUrl). cleared - the model when a city or building stands there; surface - a flat ground height for units instead of the model's top (stand under the trees, not on them). For connecting tiles (rivers, roads) connect lists what the tile joins with (a neighbor's type or modifier) and models the sides each model is open to - 0..5 counter-clockwise seen from above, side e facing 60·e + 30 − rotation degrees in the model's own space; the style picks the model and turn that fit the neighbors best. Ground heights for units and markers are measured from each model's geometry when it loads.

Resources & yields

Nothing about resources is hard-coded - each game passes its own list and rules (see ResourceConfig, demo: public/gameInfo/resources.json):

{
  "resources": [
    { "id": "grain", "name": "Grain", "icon": "Assets/resources/grain.svg", "color": "#6f9a35" },
    { "id": "iron",  "name": "Iron",  "icon": "Assets/resources/iron.svg",  "color": "#3f566e" }
  ],
  "terrain":   { "land": { "grain": 2 }, "mountain": { "iron": 1 } },
  "modifiers": { "wood": { "grain": -1 } }
}

A tile yields terrain[type] + modifiers[each modifier] + its own TileInfo.yields (a deposit: "yields": { "iron": 2 }); totals <= 0 are dropped. Icons are image URLs (a white glyph on a transparent background works best), drawn on a round badge of color with the amount.

await game.init({ map, players, units, resources }); // or game.setResources(resources)
game.tileYield(4, 17);                        // { grain: 2, iron: 2 }
game.yieldsVisible = true;                    // icon overlay on/off
game.refreshYields();                         // after the game changed tile data

Game-specific rules go into the tileYield option: (tile, cell, base) => yields. The map itself only draws (map.setResourceIcons(), map.showYields([{ x, y, yields }]), map.hideYields()) and hides icons on Unseen tiles.

Cities, buildings & stores

Cities are game state, not map data: GameData.cities ({ id, name, owner, x, y, model?, radius? }) or game.foundCity(). A city owns the tiles within its radius, has its own store, a list of buildings and one construction at a time, and sees its territory (fog).

Stores. Every resource says where it may be kept (ResourceDef.storage):

Kind Store
player the player's virtual global stock (player.storage) - nothing to carry (gold, research)
city a city's stock (city.storage)
building a real local store of a building with storage (a mine's output, a warehouse)
unit a real store on a unit with storage in its info.json (a cart, a cargo ship)

Income lands by depositTo (default: most local first - building, city, player), spending takes by spendFrom (default: player, city, building, gathered in that order). "spendFrom": ["city"] makes a resource usable only once it has been brought to the city, however full the mine is. game.transfer(from, to, resource, amount) moves resources between stores (who may carry what where is the game's rule).

Buildings are game data (BuildingType, demo: public/gameInfo/buildings.json):

{ "id": "mine", "icon": "Assets/buildings/mine.svg",
  "placement": "terrain",            // "city" (inside, no model) | "terrain" (on a tile)
  "builtBy": ["city"],               // "city" and/or "unit" (unit info.json "builds": ["mine"])
  "terrain": ["mountain", "tundra"], // + "modifiers" / "noModifiers" / "inTerritory" / "unique"
  "work": 3,                         // work points: cityWork or unit "work" per turn
  "cost": { "wood": 2 }, "costMode": "upfront",   // or "perTurn": paid every turn, pauses when missing
  "produces": { "iron": 1 }, "storage": { "capacity": 30 } }  // + "tileYields", "cityYields", "charges"
game.canBuild(city, "mine", { x: 19, y: 18 });   // null, or why not ("Not enough: iron 2.")
const mine = await game.build(city, "mine", { x: 19, y: 18 });
await game.build(worker, "farm");                  // a unit builds on its own tile, is busy meanwhile
game.cancelBuild(mine);

A unit build with charges is finished at once and spends the unit's charges (a unit with none left is removed). Construction progresses and buildings/cities produce at the start of the owner's turn: events build_start, build_progress, build_paused ({ missing }), build_complete, building_removed, city_founded, cityClick.

Founding, capture, removal. The engine has no rules for who may do these - that belongs to the game (and, in a multiplayer game, to its server). It only refuses what the map can't hold (water, a tile of another city, a building on the tile).

await settler.foundCity({ name: "Uppsala", consume: true });  // owner and tile are the unit's; consume removes it
game.setCityOwner(city, player);     // capture / treaty / revolt: store, buildings and construction go with it
game.setBuildingOwner(mine, player); // a single building outside a city
game.removeCity(city.id);            // razed: territory freed, its terrain buildings stay

Events: city_founded ({ city, unit? }), city_owner_changed / building_owner_changed ({ city|building, from, to }), city_removed.

Production list

A city's production list (Civ style) comes from the game server: what the city builds now, its queue, and what it can build with costs and turns. The engine has no rules for it and no UI. It only hands the list over: the productionList option says where the list comes from, and game.cityProductionList(city | cityId | { x, y }) returns it (ProductionList). Showing the list is the game's own UI. The demo has its own panel in public/js/buildlist.js and a demo list in public/gameInfo/buildlist.json.

{ "city": "Uppsala", "production": 6,
  "queue": [{ "id": "warrior", "progress": 8, "turns": 2 }, { "id": "granary", "turns": 7 }],  // [0] = being built now
  "groups": [{ "title": "Units", "items": [
      { "id": "warrior", "name": "Warrior", "icon": "...", "cost": 20, "turns": 4, "description": "..." },
      { "id": "ship", "name": "Ship", "cost": 50, "resources": { "wood": 5 }, "disabled": "Requires a coastal city" } ] }] }
const game = new GameEngine({ ..., productionList: city => fetch(`/api/city/${city.id}/production`).then(r => r.json()) });
const list = await game.cityProductionList("city_1");   // or a City, or its center tile { x, y }

Writing game rules

Game logic lives in the game's code, not in the engine. It has three ways in, none of which needs a change to the engine:

  1. Events to react to - turn_start, end_move, build_complete, city_owner_changed...
  2. before_* events to veto with - before_move, before_attack, before_defence carry cancel().
  3. Hooks in the options for numbers - tileYield, cityIncome, cityWork.

The game then changes the state through the public API (setCityOwner, removeUnit, transfer...). For example, a battle for a city:

game.on("before_move", e => {
    const city = game.cityAt(e.to);
    if (!city || city.owner === e.unit.owner) return;
    e.cancel();                                        // don't walk in - fight
    const won = myCombat(e.unit, city);                // the game's own rule
    if (won) game.setCityOwner(city, e.unit.owner);
});

Combat

The engine has no combat rules. game.attack(attacker, target) (or unit.strike(target)) takes a unit, a city, a terrain building or a cell, and only fires events. Everything else is the game's code: whether the attack is allowed, its range, the damage, the result. All six events get the same object, { attacker, defender, from, to, data, cancel(), waitFor(promise) }:

Event Fires on
before_attack attacker cancel() - no fight
before_defence defender cancel() - no fight
attack attacker the combat code; waitFor() holds the next events (server answer, animation)
defence defender the same
after_attack attacker apply the result
after_defence defender apply the result

The attacker's events fire on the attacking Unit and the defender's on the defending Unit; the engine re-emits all of them. A city or a building has no events of its own, so its defence events come only from the engine. Whatever one listener puts in data (damage, result...) the next ones see. With a unit selected, a click on another player's visible unit or city center calls attack(). The engine refuses the attack only when there is nothing to attack or the unit can't act (not its owner's turn).

A unit's stats come from its info.json: health, attack, defence and distanceAttack (range, 0 = melee). An attack or defence of 0 is allowed; what it means is up to the game. At runtime, unit.health (0 .. unit.maxHealth), unit.attack and unit.defence can be set by the game. The engine does nothing when health reaches 0; the game calls removeUnit. unit.spendMoves(n) takes movement points, for example when an attack ends the unit's turn. A placement may carry health (a saved game).

game.on("before_attack", e => { if (e.attacker.attack === 0) e.cancel(); });
game.on("attack", e => {
    e.waitFor(server.attack(e.attacker.id, e.defender.id).then(r => { e.data.result = r; }));
});
game.on("after_defence", ({ defender, data }) => {
    defender.health = data.result.health;
    if (defender.health === 0) game.removeUnit(defender.id);
});

The demo's version is in public/index.html, under "Combat".

With a server the same calls apply the server's verdict: the client sends the intent, the server checks and decides, and every client applies the result with setCityOwner / foundCity / unit.move.

Fog of war

HexMap renders whatever fog states it is told: map.setTileFog(x, y, state) with 0 = Unseen (fog texture), 1 = Explored (darkened) or 2 = Visible. GameEngine (with fogOfWar: true, the default) keeps a fog per player, driven by that player's units' view ranges, and shows the active player's one. Other players' units are visible only on tiles the active player currently sees. Other players' cities and terrain buildings are unknown (hidden) until the player first sees their tile; after that they stay shown as last seen - dimmed out of view, like the Explored terrain, and with the owner seen back then: a city captured behind the fog keeps its old owner's color until the player looks again. game.knows(player, cityOrBuilding) tells whether it is known.

map.warFogVisible = false hides the fog for map inspection - states keep being tracked underneath, so setting it back to true repaints the current fog exactly.

Events

All event emitters are typed (an unknown event name or a wrong payload is a compile error).

  • HexMap - the view; only its own events: load, click, hover, frame ({ t, dt } per rendered frame).
  • Unit - before_move ({ unit, from, to, path, cancel() } - call cancel() to refuse the move), move ({ unit, from, to, index, path }, every time the unit enters the next cell), end_move ({ unit, from, to, path }); before_attack / attack / after_attack and before_defence / defence / after_defence (see Combat).
  • GameEngine - re-emits the movement and combat events of every unit it owns (and fires the defence events of cities and buildings), plus unitClick ({ unit, x, y }), click, hover, turn_start / turn_end ({ player, turn }), unit_loaded / unit_unloaded (see Transport).

unit.move(target) gives the unit an order and returns a promise: true on arrival, false if refused or dropped (no route, cell occupied, not its owner's turn, already walking, cancelled, unit.cancelOrder()). The unit walks up to its movement points (movement in info.json, unit.movesLeft) per turn; the rest of the route continues automatically on its owner's next turns, re-planned each time. before_move / move / end_move fire per turn's leg (end_move.arrived tells whether the destination is reached).

Movement costs

Movement rules are game data (GameData.movement, demo: public/gameInfo/movement.json):

{ "enterRule": "anyMoves",                       // or "fullCost"
  "terrain":   { "land": 1, "snow": 2, "mountain": 3 },   // cost to enter, default 1; null = impassable
  "modifiers": { "wood": 1, "hill": 1, "river": 1 } }     // added on top, default 0

A unit's info.json can override single entries for itself - "moveCosts": { "modifiers": { "wood": 0 } } (a ranger), { "terrain": { "mountain": 1 } } (a mountaineer). Anything else - roads, zones of control, embarking - goes into the moveCost option hook: (unit, from, to, base) => cost (Infinity forbids the step).

Routes for a unit take the fewest turns (then leave the most points), counted from its movement points left - not the fewest cells, and not always the cheapest: with 2 points a 2+1 route needs two turns, a 1+3 one only one. A unit walks as far as its points reach; when a step costs more than it has left, "anyMoves" (Civ-like) lets it enter anyway and spend everything, "fullCost" makes it wait for the next turn (unless it has its full movement - a step dearer than a whole turn is never a dead end). game.moveCost(unit, from, to), game.pathCost(unit, path).

A selected unit shows where it can go this turn (Civ-like): the cells are tinted and outlined (game.reachableTiles(unit), map.showMoveArea(cells), color option moveAreaColor). The hovered route is drawn along the ground with a badge on each cell where a turn's movement ends - its turn number, 1 = this turn; the last badge says how many turns the route takes (game.routeTurns(unit, path), map.drawRoutePath(path, turns), option routeColor).

Transport

A unit with "transport": { "capacity": 2 } in its info.json is a ship. A unit of the same owner boards it by moving onto its cell - its route may end on the ship (never cross it) - and leaves by moving off onto any cell it can enter. Aboard, a unit has no model and takes no cell, sees from the ship and sails with it; the ship shows how many it carries. Clicking a selected unit's cell again selects the next unit there (the ship, then the units aboard).

  • game.load(unit, ship) / game.unload(unit, cell) - at once, without moving (a server telling the client, a script).
  • game.unitsAt(cell), game.roomOn(ship), game.canBoard(unit, ship), unit.cargo, unit.carrier, unit.capacity.
  • Events unit_loaded ({ unit, carrier }), unit_unloaded ({ unit, carrier, cell }); removing a ship removes the units aboard.
  • Who may board which ship is the canBoard(unit, carrier) option hook (default: any unit that is not a transport); what boarding costs (Civ: all movement points) is the moveCost hook - by default it is the water tile's terrain cost.

Turns

Players play in the order they were added; game.init() starts turn 1 of the first player. game.endTurn() passes the turn on (turn_end, then turn_start of the next player, whose units get their movement points back and continue their orders). game.turn is the round number, game.activePlayer whose turn it is - the map shows that player's fog and only its units take orders.

Performance

The terrain, water, grass and tree layers are cut into chunks of 10×10 tiles, one mesh each, so only the chunks inside the camera are drawn - a close view of a 106×66 map (Civ 6 "Huge") costs about the same as on a small one.

map.benchmark(frames = 200) measures the real cost of a frame at the current view, independent of the monitor's refresh cap (the fps counter can't go above it): it renders the frames back to back, waits for the GPU after each one and returns { ms, fps }. The demo has a button for it; index.html?map=huge loads a 106×66 test map (the demo map repeated).

Scripts

Script What it does
npm run build:lib builds dist/ (ESM + CJS + global/UMD bundle + type declarations)
npm run build:demo build:lib + copies the bundle/vendor files into public/
npm run server serves public/ on port 3000
npm run start build:demo + server
npm run typecheck tsc --noEmit

Changelog

See CHANGELOG.md for release notes - the current version is 0.4.0 (rivers, lakes, war-fog toggle, wood moved into modifiers, always-animated water).

Credits

License

ISC

Releases

Packages

Contributors

Languages