@pocketrts/grid
v0.4.0
Published
Grid algorithms for RTS games: budgeted flow fields, bounded local A*, line reach, distance fields, bucket grids, field of view, polygons, cell chains, line formations and column march
Maintainers
Readme
@pocketrts/grid
Grid algorithms for real-time strategy games on an 8-connected cell grid: flow fields shared by whole armies and computed under a fixed per-step budget, bounded local A*, straight-line reach, nearest free cell, distance fields, bucket grids for neighbour queries, field of view, polygons, 8-connected wall chains, line formations and a complete elastic-column march system. Pure logic over typed arrays, deterministic (only @pocketrts/determinism math), no DOM. Extracted from Pocket War, where it moves thousands of units.
Try it: apps/grid-demo (pnpm --filter @pocketrts/grid-demo dev).
Install
pnpm add @pocketrts/gridES module, TypeScript types included. Depends on @pocketrts/determinism.
Concepts
- Cells are numbered row-major:
cell = y * w + x. Directions are indices intoDIRX/DIRY(clockwise from east, y down; odd = diagonal). - The game owns the grid. The package reads what it is given (cost and block arrays, step-rule callbacks) and never stores game objects.
- Diagonal steps normally follow
cornerFree: no squeezing between two diagonal obstacles, so a one-cell-wide 8-connected wall (seeringChain) really closes. - Everything is deterministic for identical inputs, including budgeted flow-field progress (the budget counts nodes, not time), so it is safe in lockstep simulations.
Interface
| Export | Role |
|--------|------|
| FlowFields, FlowField, FlowLayer, FlowFieldOptions, DEFAULT_FLOW_FIELD_OPTIONS | Flow-field cache over one or more layers (cost in tenths, 0 = impassable, outer ring must be 0; canStep, canStepDiag). get(key, layer, tick, seeds) returns the cached field or starts one; maintain(tick) once per step advances searches within budget heap pops, recomputes fields still in use after invalidate() and swaps them in whole, and evicts unused ones; finish(field) completes one at once. A field's dirs[cell] is a direction, DIR_HERE on a goal, DIR_NONE where not reached yet. |
| cornerFree(block, w, a, b) | The usual diagonal rule. |
| LocalPathfinder, LocalStepRules | Reusable bounded A* (find(w, h, start, goal, limit, rules), path in path / length, goal first); gives up beyond limit cells of path or maxNodes expansions. For short detours where a flow field per target would be waste. |
| lineReach(ax, ay, bx, by, cellSize, w, stuck, sample?) | Fraction of a straight move that is clear, sampled along the line, with the corner rule. |
| nearestCell(w, h, cell, maxR, ok) | Closest cell (Euclidean, ring by ring) that ok accepts. |
| chamferDistance(src, w, h) | Two-pass distance to the nearest source cell. |
| BucketGrid | Counting-sort bucket grid rebuilt each step: build(n, x, y, alive), start / items runs per cell, cellAt, forEachNear(x, y, range, visit). |
| stampDisc(vis, stamped, w, h, cx, cy, r) | Reveal a disc of cells; repeated stamps from one cell cost nothing. |
| inPolygon(points, x, y), polygonDist(points, x, y) | Even–odd containment and distance to the outline of a flat [x0, y0, x1, y1, …] polygon. |
| stepCells, ringChain, chainLinks, chainOutSides | 8-connected chains (walls, fences): cells between two points, a closed chain through waypoints with loops and extra corner cells removed, which neighbours a chain cell joins, which side of each joined segment faces out. |
| lineFormation(units, cx, cy, dx, dy, positions?, options?), FormationUnit, Formation, FormationOptions, DEFAULT_FORMATION_OPTIONS | Ranks facing a direction: one rank class per rank (lower in front), frontage from the group's footprint (with taper, the ranks in front narrower: a wedge); with current positions, members keep their lateral order so paths do not cross. Returns spots, offsets, rank and place per member, and per-rank width, depth, count, radius and slowest speed. |
| formationShape(shape, scale?), FormationShape, FORMATION_SHAPES | The lineFormation options of a named shape (line, column, wedge, loose), scaled for another world. A shape is only ranks, so createMarch carries it unchanged: a march keeps its formation on the way and at the goal. |
| MarchRules, DEFAULT_MARCH_RULES, marchRules(scale, overrides?) | The march system's tunable values (distances, speeds' limits, turning, folding, engagement) and the defaults, made for a world of cells of about 32 units; marchRules scales the distances for another world. |
| MarchGround, GridGround, GridGroundOptions | What the game gives the march about its map, per movement layer (cells, passability, lines of sight, routes, ground speed), and a ready-made implementation for a plain grid of open and blocked cells. |
| MarchGround.crossSection, MarchCrossSection | Supply a passage’s transverse unit axis and distances to its physical edges for route alignment and rank placement. The march applies its own padding and member radii. |
| MarchGround.probeBlocked | Check probe movement and trail obstructions in world coordinates. Both ground queries are optional and can return undefined locally to use the grid rules. |
| MarchMembers, MEMBER_OUT, MEMBER_ENGAGED, MEMBER_OPPOSED, MEMBER_FREE | What the game gives the march about its units (position, march, rank, place, lateral offset, condition flags) and the condition flags. |
| March | The state of one marching group: the front rank and the probe ahead of it, the trail, the ranks' current widths and lengths, arrival and hold flags. The game reads it; only the march functions write it. |
| createMarch(marches, ground, rules, order), MarchOrder, rerouteMarch(...) | Set a group marching from the ranks of a lineFormation (reusing a dead entry of marches), or turn a group already marching onto a new goal without forming up again (false: the new route turns back, start a new march). |
| updateMarches(marches, grounds, members, rules, dt, tick) | Advance every march one step: tally the members, move the probe and the front rank, settle holding, arriving, breaking up and winding up. Once per step, before the members move. |
| steerMember(...), STEER, STEER_IDLE, STEER_LEAVE, STEER_PUSH, STEER_APART, STEER_KEEP | What one member does this step: keep its place (a velocity), find its own way or push on along its own route (a speed), leave the march, or act as if it had no march. |
| marchSlot, marchFollow, marchRelease, MARCH_SLOT, MARCH_FOLLOW, FOLLOW_SLOT, FOLLOW_SQUEEZE, FOLLOW_APART | The pieces of steerMember for games that steer members their own way: a member's place in the column, the point it heads for, and whether it should leave while the column winds up. |
| marchTrailAt(march, rules, b), MARCH_POINT | A point of the trail at distance b behind the probe, with its heading and usable width on each side; for drawing the column's route. |
| DIRX, DIRY, DIR_HERE, DIR_NONE | Direction tables and markers. |
Usage
One layer, units following a shared field:
import { cornerFree, DIR_HERE, DIR_NONE, DIRX, DIRY, FlowFields } from '@pocketrts/grid';
const cost = new Uint16Array(w * h); // 10 = ordinary ground, 30 = mud, 0 = wall (outer ring 0)
const block = new Uint8Array(w * h); // 1 = wall
const fields = new FlowFields(w, h, [{
cost,
canStep: () => true,
canStepDiag: (a, b) => cornerFree(block, w, a, b),
}]);
function step(tick: number) {
fields.maintain(tick);
for (const u of units) {
const f = fields.get(u.goal, 0, tick, () => Int32Array.of(u.goal)); // key = goal cell, one layer
const d = f.dirs[u.cell];
if (d === DIR_HERE) arrive(u);
else if (d === DIR_NONE) moveStraightTowards(u, u.goal); // not reached yet: head straight
else moveTowardsCell(u, u.cell + DIRX[d] + DIRY[d] * w);
}
}
// After a wall is built or destroyed:
setWall(cell);
fields.invalidate();A group of units marching as an elastic column (the ranks bend round corners, close up and fold at gates, spread out again). The game owns the units, their spots at the goal and their collisions; units are plain arrays here, units holds { row, radius, speed } per unit with speeds in world units per second:
import {
cornerFree, createMarch, FlowFields, GridGround, lineFormation, marchRules, STEER, STEER_APART, STEER_KEEP, STEER_LEAVE,
STEER_PUSH, steerMember, updateMarches, type March, type MarchMembers,
} from '@pocketrts/grid';
// The map: one ground per movement layer (the outer ring of `block` must be blocked)
const fields = new FlowFields(w, h, [{ cost, canStep: () => true, canStepDiag: (a, b) => cornerFree(block, w, a, b) }]);
const ground = new GridGround({ w, h, cellSize, block, fields });
const rules = marchRules(cellSize / 32); // the defaults suit cells of 32 units
// The units: per-unit arrays the march reads (march: Int16Array filled with -1; apart: Uint8Array)
const marches: March[] = [];
const members: MarchMembers = {
n, alive: () => true, march: i => marchOf[i], leave: i => { marchOf[i] = -1; },
x: i => px[i], y: i => py[i], row: i => rank[i], col: i => place[i], lateral: i => offset[i],
apart: i => apart[i] !== 0, state: () => 0, // MEMBER_… flags when units fight
};
// An order: lay the ranks out facing (fx, fy) round the goal (gx, gy), then set the group marching
function order(gx: number, gy: number, fx: number, fy: number) {
const f = lineFormation(units, gx, gy, fx, fy, positions); // positions: current { x, y } per unit
const g = createMarch(marches, ground, rules, {
layer: 0, x: centreX, y: centreY, destX: gx, destY: gy, destCell: ground.cellAt(gx, gy),
speed: slowest * 0.9, run: slowest, hold: false, fx, fy, formation: f,
});
for (let i = 0; i < n; i++) {
marchOf[i] = g.id; rank[i] = f.row[i]; place[i] = f.col[i]; offset[i] = f.fl[i];
spotX[i] = f.sx[i]; spotY[i] = f.sy[i]; // the unit's own spot at the goal
}
}
// Each step: the march first, then every member as it answers
function step(tick: number) {
ground.tick = tick;
fields.maintain(tick);
updateMarches(marches, () => ground, members, rules, dt, tick);
for (let i = 0; i < n; i++) {
if (marchOf[i] < 0) continue;
const what = steerMember(ground, marches[marchOf[i]], rules, rank[i], place[i], offset[i], px[i], py[i],
spotX[i], spotY[i], speed[i], speed[i], false);
apart[i] = STEER.apart ? 1 : 0; // read before the next call overwrites STEER
if (what === STEER_KEEP) moveBy(i, STEER.vx * dt, STEER.vy * dt);
else if (what === STEER_APART || what === STEER_PUSH) walkOwnRoute(i, STEER.speed * dt);
else if (what === STEER_LEAVE) { marchOf[i] = -1; walkToSpot(i); }
// STEER_IDLE: move as if there were no march
}
}A group already marching that gets a new order goes to rerouteMarch first; apps/grid-demo/src/sim.ts (order, step, marchStep) is a complete working example.
Several sides with different passability (gates that open only for their owner, say) get one layer each; key the cache so different layers never share a key, for example layer * 1048576 + goalCell. Sides that always move alike may share keys and fields.
Notes
- Flow-field costs are integers in tenths; distances are summed as integers, so results do not depend on float rounding.
FlowFields.maintainrefreshes one outdated field at a time, everyrefreshEverysteps, while at most one search is queued; until then units keep using the old directions.LocalPathfinder,BucketGridand the flow-field search reuse their buffers: create one per world, or share one when calls never interleave.- The march system knows nothing of sides, buildings, combat or weather. Whether a group is compact enough to march together, the members' own spots at the goal, unit collisions and what members do when they find their own way are the game's.
- Speeds are world units per second, including the
speedof the units given tolineFormation. The defaults suit cells of about 32 units: for other cells usemarchRules(cellSize / 32)and scalelineFormation'sgapandminWidthalike. createMarchcreates theMarchobject with its properties in a fixed order, because games hash their state in property order; a game that hashes a march keeps that order.- The result objects
STEER,MARCH_SLOT,MARCH_FOLLOWandMARCH_POINTare shared and overwritten by each call: copy what is needed before the next one. - As for flow fields, the outermost ring of the grid must be blocked.
Upgrading the march from 0.3 to 0.4
Start with marchRules(cellSize / 32). The column forms up along the route, keeps clearance beside walls and closes its ranks around bends. Members walk back toward reachable places after a reversal. A member cut off from both its place and its rank follows its own route at the supplied run speed.
- Remove
flank,faceRoute,wheel,lookClear,waitAheadandapartTrailfrom rule objects. Drop copied values forlookMin,axisFromandaxisFullto inherit the defaults of ten cells, 0.5 and 0.3. Keep explicit overrides where the map or game uses different tuning. - For games that let members advance along their own routes during combat, set
pushAheadto the distance in world units a member must be ahead of its place to receiveSTEER_PUSHwhile the group is opposed. The default isInfinity. - For subcell passages such as diagonal bridges, keep the map's world-space movement queries and optional
crossSectionmeasurements. They supply the physical boundaries of the passage. - March trajectories and checksums change with this version. Pin the same grid version on every peer in a lockstep match and replay recordings with the version that produced them.
