@pocketrts/grid 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Junjie Bai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,76 @@
1
- # Temporary Holding Version
1
+ # @pocketrts/grid
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 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 and line formations. Pure logic over typed arrays, deterministic (only `@pocketrts/determinism` math), no DOM. Extracted from Pocket War, where it moves thousands of units.
4
+
5
+ Try it: [`apps/grid-demo`](../../apps/grid-demo) (`pnpm --filter @pocketrts/grid-demo dev`).
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pnpm add @pocketrts/grid
11
+ ```
12
+
13
+ ES module, TypeScript types included. Depends on `@pocketrts/determinism`.
14
+
15
+ ## Concepts
16
+
17
+ - Cells are numbered row-major: `cell = y * w + x`. Directions are indices into `DIRX` / `DIRY` (clockwise from east, y down; odd = diagonal).
18
+ - The game owns the grid. The package reads what it is given (cost and block arrays, step-rule callbacks) and never stores game objects.
19
+ - Diagonal steps normally follow `cornerFree`: no squeezing between two diagonal obstacles, so a one-cell-wide 8-connected wall (see `ringChain`) really closes.
20
+ - Everything is deterministic for identical inputs, including budgeted flow-field progress (the budget counts nodes, not time), so it is safe in lockstep simulations.
21
+
22
+ ## Interface
23
+
24
+ | Export | Role |
25
+ |--------|------|
26
+ | `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. |
27
+ | `cornerFree(block, w, a, b)` | The usual diagonal rule. |
28
+ | `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. |
29
+ | `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. |
30
+ | `nearestCell(w, h, cell, maxR, ok)` | Closest cell (Euclidean, ring by ring) that `ok` accepts. |
31
+ | `chamferDistance(src, w, h)` | Two-pass distance to the nearest source cell. |
32
+ | `BucketGrid` | Counting-sort bucket grid rebuilt each step: `build(n, x, y, alive)`, `start` / `items` runs per cell, `cellAt`, `forEachNear(x, y, range, visit)`. |
33
+ | `stampDisc(vis, stamped, w, h, cx, cy, r)` | Reveal a disc of cells; repeated stamps from one cell cost nothing. |
34
+ | `inPolygon(points, x, y)`, `polygonDist(points, x, y)` | Even–odd containment and distance to the outline of a flat `[x0, y0, x1, y1, …]` polygon. |
35
+ | `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. |
36
+ | `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 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. |
37
+ | `DIRX`, `DIRY`, `DIR_HERE`, `DIR_NONE` | Direction tables and markers. |
38
+
39
+ ## Usage
40
+
41
+ One layer, units following a shared field:
42
+
43
+ ```ts
44
+ import { cornerFree, DIR_HERE, DIR_NONE, DIRX, DIRY, FlowFields } from '@pocketrts/grid';
45
+
46
+ const cost = new Uint16Array(w * h); // 10 = ordinary ground, 30 = mud, 0 = wall (outer ring 0)
47
+ const block = new Uint8Array(w * h); // 1 = wall
48
+ const fields = new FlowFields(w, h, [{
49
+ cost,
50
+ canStep: () => true,
51
+ canStepDiag: (a, b) => cornerFree(block, w, a, b),
52
+ }]);
53
+
54
+ function step(tick: number) {
55
+ fields.maintain(tick);
56
+ for (const u of units) {
57
+ const f = fields.get(u.goal, 0, tick, () => Int32Array.of(u.goal)); // key = goal cell, one layer
58
+ const d = f.dirs[u.cell];
59
+ if (d === DIR_HERE) arrive(u);
60
+ else if (d === DIR_NONE) moveStraightTowards(u, u.goal); // not reached yet: head straight
61
+ else moveTowardsCell(u, u.cell + DIRX[d] + DIRY[d] * w);
62
+ }
63
+ }
64
+
65
+ // After a wall is built or destroyed:
66
+ setWall(cell);
67
+ fields.invalidate();
68
+ ```
69
+
70
+ 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.
71
+
72
+ ## Notes
73
+
74
+ - Flow-field costs are integers in tenths; distances are summed as integers, so results do not depend on float rounding.
75
+ - `FlowFields.maintain` refreshes one outdated field at a time, every `refreshEvery` steps, while at most one search is queued; until then units keep using the old directions.
76
+ - `LocalPathfinder`, `BucketGrid` and the flow-field search reuse their buffers: create one per world, or share one when calls never interleave.
@@ -0,0 +1,32 @@
1
+ /**
2
+ * A uniform bucket grid for neighbour queries, rebuilt from scratch every step by a counting sort: the indices of the
3
+ * entities in cell `c` are `items[start[c]]` up to (not including) `items[start[c + 1]]`, in increasing index order.
4
+ * Because cells are row-major, one row segment from column x0 to x1 is the single run `start[row + x0]` to
5
+ * `start[row + x1 + 1]`.
6
+ */
7
+ export declare class BucketGrid {
8
+ readonly gw: number;
9
+ readonly gh: number;
10
+ readonly cellSize: number;
11
+ /** Run starts per cell, plus the total at the end (`gw * gh + 1` entries). */
12
+ readonly start: Int32Array;
13
+ /** Scratch space for `build` (per-cell counts); its contents afterwards are unspecified. */
14
+ readonly count: Int32Array;
15
+ /** Entity indices grouped by cell. */
16
+ readonly items: Int32Array;
17
+ /**
18
+ * @param gw, gh Size in cells; positions must fall inside (0 ≤ x < gw·cellSize, same for y).
19
+ * @param capacity Largest entity count `build` is called with.
20
+ */
21
+ constructor(gw: number, gh: number, cellSize: number, capacity: number);
22
+ /** The cell holding world position (x, y). */
23
+ cellAt(x: number, y: number): number;
24
+ /** Re-sort entities 0 … n − 1 at (`x[i]`, `y[i]`), skipping those whose `alive[i]` is 0. */
25
+ build(n: number, x: ArrayLike<number>, y: ArrayLike<number>, alive: ArrayLike<number>): void;
26
+ /**
27
+ * Call `visit(i)` for every entity in the cells overlapping the square of half-size `range` around (x, y), clamped
28
+ * to the grid, row by row; return `true` from `visit` to stop early. Entities are not filtered by distance.
29
+ * Returns whether it was stopped.
30
+ */
31
+ forEachNear(x: number, y: number, range: number, visit: (i: number) => boolean | void): boolean;
32
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * A uniform bucket grid for neighbour queries, rebuilt from scratch every step by a counting sort: the indices of the
3
+ * entities in cell `c` are `items[start[c]]` up to (not including) `items[start[c + 1]]`, in increasing index order.
4
+ * Because cells are row-major, one row segment from column x0 to x1 is the single run `start[row + x0]` to
5
+ * `start[row + x1 + 1]`.
6
+ */
7
+ export class BucketGrid {
8
+ gw;
9
+ gh;
10
+ cellSize;
11
+ /** Run starts per cell, plus the total at the end (`gw * gh + 1` entries). */
12
+ start;
13
+ /** Scratch space for `build` (per-cell counts); its contents afterwards are unspecified. */
14
+ count;
15
+ /** Entity indices grouped by cell. */
16
+ items;
17
+ /**
18
+ * @param gw, gh Size in cells; positions must fall inside (0 ≤ x < gw·cellSize, same for y).
19
+ * @param capacity Largest entity count `build` is called with.
20
+ */
21
+ constructor(gw, gh, cellSize, capacity) {
22
+ this.gw = gw;
23
+ this.gh = gh;
24
+ this.cellSize = cellSize;
25
+ this.start = new Int32Array(gw * gh + 1);
26
+ this.count = new Int32Array(gw * gh);
27
+ this.items = new Int32Array(capacity);
28
+ }
29
+ /** The cell holding world position (x, y). */
30
+ cellAt(x, y) {
31
+ return ((y / this.cellSize) | 0) * this.gw + ((x / this.cellSize) | 0);
32
+ }
33
+ /** Re-sort entities 0 … n − 1 at (`x[i]`, `y[i]`), skipping those whose `alive[i]` is 0. */
34
+ build(n, x, y, alive) {
35
+ const cs = this.start, cur = this.count, gw = this.gw, size = this.cellSize;
36
+ cur.fill(0);
37
+ for (let i = 0; i < n; i++) {
38
+ if (!alive[i])
39
+ continue;
40
+ cur[((y[i] / size) | 0) * gw + ((x[i] / size) | 0)]++;
41
+ }
42
+ let acc = 0;
43
+ const cells = cur.length;
44
+ for (let c = 0; c < cells; c++) {
45
+ cs[c] = acc;
46
+ acc += cur[c];
47
+ cur[c] = 0;
48
+ }
49
+ cs[cells] = acc;
50
+ for (let i = 0; i < n; i++) {
51
+ if (!alive[i])
52
+ continue;
53
+ const c = ((y[i] / size) | 0) * gw + ((x[i] / size) | 0);
54
+ this.items[cs[c] + cur[c]++] = i;
55
+ }
56
+ }
57
+ /**
58
+ * Call `visit(i)` for every entity in the cells overlapping the square of half-size `range` around (x, y), clamped
59
+ * to the grid, row by row; return `true` from `visit` to stop early. Entities are not filtered by distance.
60
+ * Returns whether it was stopped.
61
+ */
62
+ forEachNear(x, y, range, visit) {
63
+ const gw = this.gw, gh = this.gh, size = this.cellSize, cs = this.start, items = this.items;
64
+ let gx0 = ((x - range) / size) | 0, gx1 = ((x + range) / size) | 0;
65
+ let gy0 = ((y - range) / size) | 0, gy1 = ((y + range) / size) | 0;
66
+ if (gx0 < 0)
67
+ gx0 = 0;
68
+ if (gy0 < 0)
69
+ gy0 = 0;
70
+ if (gx1 >= gw)
71
+ gx1 = gw - 1;
72
+ if (gy1 >= gh)
73
+ gy1 = gh - 1;
74
+ for (let gy = gy0; gy <= gy1; gy++) {
75
+ const row = gy * gw;
76
+ for (let k = cs[row + gx0], k1 = cs[row + gx1 + 1]; k < k1; k++)
77
+ if (visit(items[k]))
78
+ return true;
79
+ }
80
+ return false;
81
+ }
82
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * How far along the straight line from (ax, ay) to (bx, by), in world units, a unit gets before it is stopped: the
3
+ * fraction of the whole line that is clear (1 = all of it). The line is sampled every `sample` world units; at each
4
+ * new cell `stuck(fromCell, toCell)` decides whether the move is blocked. When the line crosses a corner diagonally,
5
+ * it is blocked only if both ways around the corner (via either orthogonal neighbour) are. On a block the result is
6
+ * the last clear sample, so the unit stops less than one sample short of the obstacle.
7
+ * @param cellSize World units per cell.
8
+ * @param w Grid width in cells.
9
+ */
10
+ export declare function lineReach(ax: number, ay: number, bx: number, by: number, cellSize: number, w: number, stuck: (from: number, to: number) => boolean, sample?: number): number;
11
+ /**
12
+ * The cell closest to `cell` (by Euclidean distance) that `ok` accepts, searching square rings of radius 1 to `maxR`;
13
+ * `cell` itself when it is accepted, and also when nothing within `maxR` is. Within a ring, ties go to the first cell
14
+ * in row order.
15
+ */
16
+ export declare function nearestCell(w: number, h: number, cell: number, maxR: number, ok: (c: number) => boolean): number;
17
+ /**
18
+ * Approximate distance (in cells) from every cell to the nearest non-zero cell of `src`, by a two-pass chamfer
19
+ * transform (straight steps 1, diagonal √2). Cells with no source at all read 1e9.
20
+ */
21
+ export declare function chamferDistance(src: ArrayLike<number>, w: number, h: number): Float32Array;
package/dist/cells.js ADDED
@@ -0,0 +1,108 @@
1
+ /** Small cell-grid queries: straight-line reach, nearest acceptable cell, distance field. */
2
+ import { dmath } from '@pocketrts/determinism';
3
+ /**
4
+ * How far along the straight line from (ax, ay) to (bx, by), in world units, a unit gets before it is stopped: the
5
+ * fraction of the whole line that is clear (1 = all of it). The line is sampled every `sample` world units; at each
6
+ * new cell `stuck(fromCell, toCell)` decides whether the move is blocked. When the line crosses a corner diagonally,
7
+ * it is blocked only if both ways around the corner (via either orthogonal neighbour) are. On a block the result is
8
+ * the last clear sample, so the unit stops less than one sample short of the obstacle.
9
+ * @param cellSize World units per cell.
10
+ * @param w Grid width in cells.
11
+ */
12
+ export function lineReach(ax, ay, bx, by, cellSize, w, stuck, sample = 16) {
13
+ const dx = bx - ax, dy = by - ay;
14
+ const steps = Math.ceil(dmath.hypot(dx, dy) / sample);
15
+ let prev = ((ay / cellSize) | 0) * w + ((ax / cellSize) | 0);
16
+ for (let k = 1; k <= steps; k++) {
17
+ const t = k / steps;
18
+ const c = (((ay + dy * t) / cellSize) | 0) * w + (((ax + dx * t) / cellSize) | 0);
19
+ if (c === prev)
20
+ continue;
21
+ if (stuck(prev, c))
22
+ return (k - 1) / steps;
23
+ const dxc = (c % w) - (prev % w), dyc = ((c / w) | 0) - ((prev / w) | 0);
24
+ if (dxc && dyc) {
25
+ const c1 = prev + dxc, c2 = prev + dyc * w;
26
+ if ((stuck(prev, c1) || stuck(c1, c)) && (stuck(prev, c2) || stuck(c2, c)))
27
+ return (k - 1) / steps;
28
+ }
29
+ prev = c;
30
+ }
31
+ return 1;
32
+ }
33
+ /**
34
+ * The cell closest to `cell` (by Euclidean distance) that `ok` accepts, searching square rings of radius 1 to `maxR`;
35
+ * `cell` itself when it is accepted, and also when nothing within `maxR` is. Within a ring, ties go to the first cell
36
+ * in row order.
37
+ */
38
+ export function nearestCell(w, h, cell, maxR, ok) {
39
+ if (ok(cell))
40
+ return cell;
41
+ const cx = cell % w, cy = (cell / w) | 0;
42
+ for (let r = 1; r <= maxR; r++) {
43
+ let best = -1, bestD = 1e9;
44
+ for (let dy = -r; dy <= r; dy++) {
45
+ for (let dx = -r; dx <= r; dx++) {
46
+ if (Math.max(Math.abs(dx), Math.abs(dy)) !== r)
47
+ continue;
48
+ const x = cx + dx, y = cy + dy;
49
+ if (x < 0 || y < 0 || x >= w || y >= h)
50
+ continue;
51
+ const c = y * w + x;
52
+ if (!ok(c))
53
+ continue;
54
+ const d = dx * dx + dy * dy;
55
+ if (d < bestD) {
56
+ bestD = d;
57
+ best = c;
58
+ }
59
+ }
60
+ }
61
+ if (best >= 0)
62
+ return best;
63
+ }
64
+ return cell;
65
+ }
66
+ /**
67
+ * Approximate distance (in cells) from every cell to the nearest non-zero cell of `src`, by a two-pass chamfer
68
+ * transform (straight steps 1, diagonal √2). Cells with no source at all read 1e9.
69
+ */
70
+ export function chamferDistance(src, w, h) {
71
+ const d = new Float32Array(w * h);
72
+ for (let i = 0; i < d.length; i++)
73
+ d[i] = src[i] ? 0 : 1e9;
74
+ const D = Math.SQRT2;
75
+ for (let y = 0; y < h; y++) {
76
+ for (let x = 0; x < w; x++) {
77
+ const i = y * w + x;
78
+ let v = d[i];
79
+ if (x > 0)
80
+ v = Math.min(v, d[i - 1] + 1);
81
+ if (y > 0) {
82
+ v = Math.min(v, d[i - w] + 1);
83
+ if (x > 0)
84
+ v = Math.min(v, d[i - w - 1] + D);
85
+ if (x < w - 1)
86
+ v = Math.min(v, d[i - w + 1] + D);
87
+ }
88
+ d[i] = v;
89
+ }
90
+ }
91
+ for (let y = h - 1; y >= 0; y--) {
92
+ for (let x = w - 1; x >= 0; x--) {
93
+ const i = y * w + x;
94
+ let v = d[i];
95
+ if (x < w - 1)
96
+ v = Math.min(v, d[i + 1] + 1);
97
+ if (y < h - 1) {
98
+ v = Math.min(v, d[i + w] + 1);
99
+ if (x < w - 1)
100
+ v = Math.min(v, d[i + w + 1] + D);
101
+ if (x > 0)
102
+ v = Math.min(v, d[i + w - 1] + D);
103
+ }
104
+ d[i] = v;
105
+ }
106
+ }
107
+ return d;
108
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The cells from (ax, ay) to (bx, by), excluding the start and including the end: half of the straight part, then the
3
+ * diagonal part, then the other half of the straight part, every step 8-connected. The straight part runs along the
4
+ * axis with the larger difference.
5
+ */
6
+ export declare function stepCells(ax: number, ay: number, bx: number, by: number): [number, number][];
7
+ /**
8
+ * A closed chain through waypoints (cell coordinates, x and y alternating, the last joining back to the first), as a
9
+ * flat list of cells (x, y alternating, the first cell not repeated at the end). Small loops formed by doubling back
10
+ * are cut out, and a corner cell whose neighbours already touch is dropped, so diagonal runs are clean single lines.
11
+ * Cells are limited to coordinates in [0, 65535].
12
+ * @param keep Cells that must not be dropped at corners (for example gates and the cells next to them).
13
+ */
14
+ export declare function ringChain(marks: readonly number[], keep?: (x: number, y: number) => boolean): number[];
15
+ /**
16
+ * Which of the eight neighbours of chain cell (x, y) it joins up with, as a bit mask (bit d = direction DIRX[d],
17
+ * DIRY[d]). Straight neighbours always join; a diagonal neighbour joins only when neither cell between them is part
18
+ * of a chain (otherwise the chain already turns through that cell, and a diagonal join would draw a second edge).
19
+ * @param linked Whether a cell is part of a chain (wall, gate, tower, …).
20
+ */
21
+ export declare function chainLinks(linked: (x: number, y: number) => boolean, x: number, y: number): number;
22
+ /**
23
+ * For each joined direction in `links`, which side of that segment faces outward: bit d set means the side
24
+ * (−DIRY[d], DIRX[d]) faces along (ox, oy), cleared means the opposite side does.
25
+ * @param ox, oy A vector pointing outward at this cell (for example from the enclosure's centre to the cell).
26
+ */
27
+ export declare function chainOutSides(links: number, ox: number, oy: number): number;
package/dist/chain.js ADDED
@@ -0,0 +1,112 @@
1
+ /**
2
+ * 8-connected cell chains, such as walls and fences: consecutive cells always touch straight or diagonally. With the
3
+ * no-corner-cutting rule (`cornerFree`), a one-cell-wide closed chain separates its inside from its outside.
4
+ */
5
+ import { DIRX, DIRY } from './dirs.js';
6
+ /**
7
+ * The cells from (ax, ay) to (bx, by), excluding the start and including the end: half of the straight part, then the
8
+ * diagonal part, then the other half of the straight part, every step 8-connected. The straight part runs along the
9
+ * axis with the larger difference.
10
+ */
11
+ export function stepCells(ax, ay, bx, by) {
12
+ const out = [];
13
+ const dx = bx - ax, dy = by - ay, adx = Math.abs(dx), ady = Math.abs(dy);
14
+ const sx = Math.sign(dx), sy = Math.sign(dy);
15
+ const diag = Math.min(adx, ady), straight = Math.max(adx, ady) - diag;
16
+ const hx = adx > ady ? sx : 0, hy = adx > ady ? 0 : sy;
17
+ const first = straight >> 1;
18
+ let x = ax, y = ay;
19
+ const go = (mx, my, n) => {
20
+ for (let k = 0; k < n; k++) {
21
+ x += mx;
22
+ y += my;
23
+ out.push([x, y]);
24
+ }
25
+ };
26
+ go(hx, hy, first);
27
+ go(sx, sy, diag);
28
+ go(hx, hy, straight - first);
29
+ return out;
30
+ }
31
+ const key = (x, y) => (y << 16) | (x & 0xffff);
32
+ /**
33
+ * A closed chain through waypoints (cell coordinates, x and y alternating, the last joining back to the first), as a
34
+ * flat list of cells (x, y alternating, the first cell not repeated at the end). Small loops formed by doubling back
35
+ * are cut out, and a corner cell whose neighbours already touch is dropped, so diagonal runs are clean single lines.
36
+ * Cells are limited to coordinates in [0, 65535].
37
+ * @param keep Cells that must not be dropped at corners (for example gates and the cells next to them).
38
+ */
39
+ export function ringChain(marks, keep = () => false) {
40
+ const n = marks.length >> 1;
41
+ let cells = [];
42
+ for (let k = 0; k < n; k++) {
43
+ const ax = marks[k * 2], ay = marks[k * 2 + 1];
44
+ const b = (k + 1) % n;
45
+ if (k === 0)
46
+ cells.push([ax, ay]);
47
+ for (const c of stepCells(ax, ay, marks[b * 2], marks[b * 2 + 1]))
48
+ cells.push(c);
49
+ }
50
+ if (cells.length > 1 && cells[cells.length - 1][0] === cells[0][0] && cells[cells.length - 1][1] === cells[0][1])
51
+ cells.pop();
52
+ // Cut loops: when a cell comes up a second time, drop everything between its two visits
53
+ const seen = new Map();
54
+ const out = [];
55
+ for (const c of cells) {
56
+ const kk = key(c[0], c[1]);
57
+ const at = seen.get(kk);
58
+ if (at !== undefined) {
59
+ for (let j = at + 1; j < out.length; j++)
60
+ seen.delete(key(out[j][0], out[j][1]));
61
+ out.length = at + 1;
62
+ continue;
63
+ }
64
+ seen.set(kk, out.length);
65
+ out.push(c);
66
+ }
67
+ cells = out;
68
+ for (let changed = true; changed && cells.length > 4;) {
69
+ changed = false;
70
+ for (let k = 0; k < cells.length && cells.length > 4; k++) {
71
+ const p = cells[(k + cells.length - 1) % cells.length], c = cells[k], q = cells[(k + 1) % cells.length];
72
+ if (keep(c[0], c[1]))
73
+ continue;
74
+ if (Math.max(Math.abs(p[0] - q[0]), Math.abs(p[1] - q[1])) <= 1) {
75
+ cells.splice(k, 1);
76
+ k--;
77
+ changed = true;
78
+ }
79
+ }
80
+ }
81
+ return cells.flat();
82
+ }
83
+ /**
84
+ * Which of the eight neighbours of chain cell (x, y) it joins up with, as a bit mask (bit d = direction DIRX[d],
85
+ * DIRY[d]). Straight neighbours always join; a diagonal neighbour joins only when neither cell between them is part
86
+ * of a chain (otherwise the chain already turns through that cell, and a diagonal join would draw a second edge).
87
+ * @param linked Whether a cell is part of a chain (wall, gate, tower, …).
88
+ */
89
+ export function chainLinks(linked, x, y) {
90
+ let mask = 0;
91
+ for (let d = 0; d < 8; d++) {
92
+ const nx = x + DIRX[d], ny = y + DIRY[d];
93
+ if (!linked(nx, ny))
94
+ continue;
95
+ if (d & 1 && (linked(nx, y) || linked(x, ny)))
96
+ continue;
97
+ mask |= 1 << d;
98
+ }
99
+ return mask;
100
+ }
101
+ /**
102
+ * For each joined direction in `links`, which side of that segment faces outward: bit d set means the side
103
+ * (−DIRY[d], DIRX[d]) faces along (ox, oy), cleared means the opposite side does.
104
+ * @param ox, oy A vector pointing outward at this cell (for example from the enclosure's centre to the cell).
105
+ */
106
+ export function chainOutSides(links, ox, oy) {
107
+ let out = 0;
108
+ for (let d = 0; d < 8; d++)
109
+ if (links & (1 << d) && -DIRY[d] * ox + DIRX[d] * oy > 0)
110
+ out |= 1 << d;
111
+ return out;
112
+ }
package/dist/dirs.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /** The eight neighbour offsets, clockwise from east in screen coordinates (y down): even = straight, odd = diagonal. */
2
+ export declare const DIRX: readonly number[];
3
+ export declare const DIRY: readonly number[];
4
+ /** Flow direction of a goal cell: already there. */
5
+ export declare const DIR_HERE = 8;
6
+ /** Flow direction of a cell not reached (yet, or at all). */
7
+ export declare const DIR_NONE = 255;
package/dist/dirs.js ADDED
@@ -0,0 +1,7 @@
1
+ /** The eight neighbour offsets, clockwise from east in screen coordinates (y down): even = straight, odd = diagonal. */
2
+ export const DIRX = [1, 1, 0, -1, -1, -1, 0, 1];
3
+ export const DIRY = [0, 1, 1, 1, 0, -1, -1, -1];
4
+ /** Flow direction of a goal cell: already there. */
5
+ export const DIR_HERE = 8;
6
+ /** Flow direction of a cell not reached (yet, or at all). */
7
+ export const DIR_NONE = 255;
@@ -0,0 +1,85 @@
1
+ /** One movement layer of the grid. */
2
+ export interface FlowLayer {
3
+ /**
4
+ * Cost of entering each cell, in tenths (an ordinary cell is 10); 0 = impassable. A diagonal step costs ⌊cost × 1.4142⌋.
5
+ * The outermost ring of cells must be 0: searches do not check the grid bounds.
6
+ */
7
+ readonly cost: Uint16Array;
8
+ /** Whether a unit may step straight from cell `a` to the adjacent cell `b` (both passable). */
9
+ canStep(a: number, b: number): boolean;
10
+ /** Whether a unit may step diagonally from cell `a` to the diagonal cell `b`. See `cornerFree` for the usual rule. */
11
+ canStepDiag(a: number, b: number): boolean;
12
+ }
13
+ export interface FlowField {
14
+ /** The cache key the field was requested under. */
15
+ readonly key: number;
16
+ /** The layer it was computed on. */
17
+ readonly layer: number;
18
+ /** The first goal cell. */
19
+ readonly cell: number;
20
+ readonly seeds: Int32Array;
21
+ /** Per cell: the direction index (`DIRX` / `DIRY`) of the next step, `DIR_HERE` on a goal, `DIR_NONE` if not reached. */
22
+ dirs: Uint8Array;
23
+ /** The grid version the current `dirs` were computed for. */
24
+ version: number;
25
+ /** The last step it was requested on. */
26
+ lastUse: number;
27
+ /** Evicted from the cache: request a new field instead of keeping this one. */
28
+ dead: boolean;
29
+ /** A search is running: the first one (`dirs` partial), or a refresh after `invalidate` (`dirs` still the previous result). */
30
+ pending: boolean;
31
+ }
32
+ export interface FlowFieldOptions {
33
+ /** Heap pops per `maintain` call, across all searches (about 1–2 ms at the default). Default 22000. */
34
+ budget: number;
35
+ /** Every this many steps, one outdated field still in use starts recomputing (when at most one search is queued). Default 20. */
36
+ refreshEvery: number;
37
+ /** A field counts as in use when it was requested within this many steps. Default 60. */
38
+ refreshWithin: number;
39
+ /** Fields are evicted only while the cache holds more than this many. Default 48. */
40
+ evictAbove: number;
41
+ /** Every this many steps, fields unused for `evictAfter` steps are evicted. Default 64. */
42
+ evictEvery: number;
43
+ /** Steps without a request after which a field may be evicted. Default 300. */
44
+ evictAfter: number;
45
+ }
46
+ export declare const DEFAULT_FLOW_FIELD_OPTIONS: Readonly<FlowFieldOptions>;
47
+ /**
48
+ * The usual diagonal rule: a diagonal step from `a` to `b` is allowed only when neither cell nor either of the two
49
+ * corner cells it brushes past is blocked, so units never squeeze through the gap between two diagonal obstacles.
50
+ * Symmetric in `a` and `b`. `w` is the grid width.
51
+ */
52
+ export declare function cornerFree(block: ArrayLike<number>, w: number, a: number, b: number): boolean;
53
+ export declare class FlowFields {
54
+ readonly w: number;
55
+ readonly h: number;
56
+ readonly layers: readonly FlowLayer[];
57
+ /** Number of cells. */
58
+ readonly n: number;
59
+ readonly options: Readonly<FlowFieldOptions>;
60
+ /** Grid version: raised by `invalidate()`. */
61
+ version: number;
62
+ /** Cached fields by key, in creation order. */
63
+ readonly fields: Map<number, FlowField>;
64
+ /** Searches started so far (statistics). */
65
+ computed: number;
66
+ private readonly jobs;
67
+ private readonly pool;
68
+ private readonly off;
69
+ constructor(w: number, h: number, layers: readonly FlowLayer[], options?: Partial<FlowFieldOptions>);
70
+ /** Call after changing any layer's costs or step rules. */
71
+ invalidate(): void;
72
+ /**
73
+ * The field cached under `key`, or a new one computed on `layer` towards `seeds` (called only when it is not cached).
74
+ * Keys are the caller's: they must tell layers and goals apart, and two layers that always move alike may share keys.
75
+ */
76
+ get(key: number, layer: number, tick: number, seeds: () => Int32Array): FlowField;
77
+ /** Finish a field's pending search at once (tests and the few callers that need a synchronous result). */
78
+ finish(f: FlowField): void;
79
+ /** Call once per simulation step: advance queued searches, refresh outdated fields, evict unused ones. */
80
+ maintain(tick: number): void;
81
+ private start;
82
+ private done;
83
+ /** Advance one search by at most `budget` heap pops; returns the budget left. */
84
+ private step;
85
+ }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Flow fields over an 8-connected grid: one field per goal, shared by every unit heading there, so pathfinding cost
3
+ * does not grow with the number of units.
4
+ *
5
+ * A field is a Dijkstra search spreading out from the goal cells, recording for each cell the direction of the next
6
+ * step. Searches are spread over steps with a fixed node budget per `maintain` call, so no single step stalls; a cell
7
+ * not reached yet reads `DIR_NONE`, and units should head straight for the goal until it fills in. The budget is a
8
+ * node count, not a time, so every peer finishes a field on the same step.
9
+ *
10
+ * The game owns the grid itself as layers (typically one per side or per movement class), each a cost array plus its
11
+ * step rules; after changing any layer, call `invalidate()`: fields still in use are recomputed in the background and
12
+ * swapped in whole when done.
13
+ */
14
+ import { DIR_HERE, DIR_NONE, DIRX, DIRY } from './dirs.js';
15
+ export const DEFAULT_FLOW_FIELD_OPTIONS = Object.freeze({
16
+ budget: 22000,
17
+ refreshEvery: 20,
18
+ refreshWithin: 60,
19
+ evictAbove: 48,
20
+ evictEvery: 64,
21
+ evictAfter: 300,
22
+ });
23
+ /**
24
+ * The usual diagonal rule: a diagonal step from `a` to `b` is allowed only when neither cell nor either of the two
25
+ * corner cells it brushes past is blocked, so units never squeeze through the gap between two diagonal obstacles.
26
+ * Symmetric in `a` and `b`. `w` is the grid width.
27
+ */
28
+ export function cornerFree(block, w, a, b) {
29
+ const dx = (b % w) - (a % w);
30
+ return !(block[a] || block[b] || block[a + dx] || block[b - dx]);
31
+ }
32
+ export class FlowFields {
33
+ w;
34
+ h;
35
+ layers;
36
+ /** Number of cells. */
37
+ n;
38
+ options;
39
+ /** Grid version: raised by `invalidate()`. */
40
+ version = 1;
41
+ /** Cached fields by key, in creation order. */
42
+ fields = new Map();
43
+ /** Searches started so far (statistics). */
44
+ computed = 0;
45
+ jobs = [];
46
+ pool = [];
47
+ off;
48
+ constructor(w, h, layers, options = {}) {
49
+ this.w = w;
50
+ this.h = h;
51
+ this.layers = layers;
52
+ this.n = w * h;
53
+ this.options = { ...DEFAULT_FLOW_FIELD_OPTIONS, ...options };
54
+ this.off = Int32Array.from(DIRX.map((dx, i) => dx + DIRY[i] * w));
55
+ }
56
+ /** Call after changing any layer's costs or step rules. */
57
+ invalidate() {
58
+ this.version++;
59
+ }
60
+ /**
61
+ * The field cached under `key`, or a new one computed on `layer` towards `seeds` (called only when it is not cached).
62
+ * Keys are the caller's: they must tell layers and goals apart, and two layers that always move alike may share keys.
63
+ */
64
+ get(key, layer, tick, seeds) {
65
+ let f = this.fields.get(key);
66
+ if (!f) {
67
+ const s = seeds();
68
+ f = {
69
+ key, layer, cell: s[0], seeds: s, dirs: new Uint8Array(this.n).fill(DIR_NONE), version: this.version, lastUse: tick,
70
+ dead: false, pending: true,
71
+ };
72
+ this.fields.set(key, f);
73
+ this.start(f, f.dirs);
74
+ }
75
+ f.lastUse = tick;
76
+ return f;
77
+ }
78
+ /** Finish a field's pending search at once (tests and the few callers that need a synchronous result). */
79
+ finish(f) {
80
+ const i = this.jobs.findIndex(j => j.field === f);
81
+ if (i < 0)
82
+ return;
83
+ const job = this.jobs[i];
84
+ this.step(job, Infinity);
85
+ this.done(job);
86
+ this.jobs.splice(i, 1);
87
+ }
88
+ /** Call once per simulation step: advance queued searches, refresh outdated fields, evict unused ones. */
89
+ maintain(tick) {
90
+ const o = this.options;
91
+ let budget = o.budget;
92
+ while (budget > 0 && this.jobs.length) {
93
+ const job = this.jobs[0];
94
+ budget = this.step(job, budget);
95
+ if (job.hs > 0)
96
+ break;
97
+ this.done(job);
98
+ this.jobs.shift();
99
+ }
100
+ if (tick % o.refreshEvery === 0 && this.jobs.length < 2) {
101
+ for (const f of this.fields.values()) {
102
+ if (f.version !== this.version && !f.pending && f.lastUse >= tick - o.refreshWithin) {
103
+ this.start(f, new Uint8Array(this.n).fill(DIR_NONE));
104
+ break;
105
+ }
106
+ }
107
+ }
108
+ if (this.fields.size > o.evictAbove && tick % o.evictEvery === 0) {
109
+ for (const [k, f] of this.fields) {
110
+ if (f.lastUse < tick - o.evictAfter && !f.pending) {
111
+ f.dead = true;
112
+ this.fields.delete(k);
113
+ }
114
+ }
115
+ }
116
+ }
117
+ start(f, dirs) {
118
+ this.computed++;
119
+ const buf = this.pool.pop() ?? { dist: new Uint32Array(this.n), hd: new Uint32Array(this.n * 2), hc: new Int32Array(this.n * 2) };
120
+ const job = { field: f, dirs, dist: buf.dist, hd: buf.hd, hc: buf.hc, hs: 0, version: this.version };
121
+ job.dist.fill(0xffffffff);
122
+ for (let i = 0; i < f.seeds.length; i++) {
123
+ const s = f.seeds[i];
124
+ job.dist[s] = 0;
125
+ dirs[s] = DIR_HERE;
126
+ job.hd[job.hs] = 0;
127
+ job.hc[job.hs++] = s;
128
+ }
129
+ f.pending = true;
130
+ this.jobs.push(job);
131
+ }
132
+ done(job) {
133
+ const f = job.field;
134
+ f.dirs = job.dirs;
135
+ f.version = job.version;
136
+ f.pending = false;
137
+ this.pool.push({ dist: job.dist, hd: job.hd, hc: job.hc });
138
+ }
139
+ /** Advance one search by at most `budget` heap pops; returns the budget left. */
140
+ step(job, budget) {
141
+ const layer = this.layers[job.field.layer], cost = layer.cost;
142
+ const dist = job.dist, dirs = job.dirs;
143
+ const off = this.off;
144
+ let hd = job.hd, hc = job.hc, hs = job.hs;
145
+ while (hs > 0 && budget-- > 0) {
146
+ const d = hd[0], c = hc[0];
147
+ hs--;
148
+ if (hs > 0) {
149
+ const ld = hd[hs], lc = hc[hs];
150
+ let i = 0;
151
+ for (;;) {
152
+ let l = 2 * i + 1;
153
+ if (l >= hs)
154
+ break;
155
+ if (l + 1 < hs && hd[l + 1] < hd[l])
156
+ l++;
157
+ if (hd[l] >= ld)
158
+ break;
159
+ hd[i] = hd[l];
160
+ hc[i] = hc[l];
161
+ i = l;
162
+ }
163
+ hd[i] = ld;
164
+ hc[i] = lc;
165
+ }
166
+ if (d > dist[c])
167
+ continue;
168
+ // Cost of entering c; a goal cell always costs 10
169
+ const cc = d === 0 ? 10 : cost[c];
170
+ const cd = (cc * 1.4142) | 0;
171
+ for (let dir = 0; dir < 8; dir++) {
172
+ const nc = c + off[dir];
173
+ if (cost[nc] === 0)
174
+ continue;
175
+ let nd;
176
+ // The search spreads out from the goal: this edge is a unit stepping from nc to c
177
+ if (dir & 1) {
178
+ if (!layer.canStepDiag(nc, c))
179
+ continue;
180
+ nd = d + cd;
181
+ }
182
+ else {
183
+ if (!layer.canStep(nc, c))
184
+ continue;
185
+ nd = d + cc;
186
+ }
187
+ if (nd < dist[nc]) {
188
+ dist[nc] = nd;
189
+ dirs[nc] = (dir + 4) & 7;
190
+ if (hs >= hd.length) {
191
+ const nhd = new Uint32Array(hd.length * 2), nhc = new Int32Array(hc.length * 2);
192
+ nhd.set(hd);
193
+ nhc.set(hc);
194
+ hd = job.hd = nhd;
195
+ hc = job.hc = nhc;
196
+ }
197
+ let i = hs++;
198
+ while (i > 0) {
199
+ const p = (i - 1) >> 1;
200
+ if (hd[p] <= nd)
201
+ break;
202
+ hd[i] = hd[p];
203
+ hc[i] = hc[p];
204
+ i = p;
205
+ }
206
+ hd[i] = nd;
207
+ hc[i] = nc;
208
+ }
209
+ }
210
+ }
211
+ job.hs = hs;
212
+ return budget;
213
+ }
214
+ }
@@ -0,0 +1,52 @@
1
+ /** What `lineFormation` needs to know about one member. */
2
+ export interface FormationUnit {
3
+ /** Rank class: lower classes stand further forward; one rank only ever holds one class. */
4
+ row: number;
5
+ radius: number;
6
+ /** Running speed, for each rank's slowest speed. */
7
+ speed: number;
8
+ }
9
+ export interface FormationOptions {
10
+ /** Spacing added to each unit's diameter, side by side and front to back. Default 3. */
11
+ gap: number;
12
+ /** Narrowest frontage. Default 48. */
13
+ minWidth: number;
14
+ /** Frontage = √(total footprint area × aspect), so the block is about `aspect` times wider than deep. Default 2.6. */
15
+ aspect: number;
16
+ }
17
+ export declare const DEFAULT_FORMATION_OPTIONS: Readonly<FormationOptions>;
18
+ /** The result of `lineFormation`, per member (in input order) and per rank (front to back). */
19
+ export interface Formation {
20
+ /** Each member's spot. */
21
+ sx: Float32Array;
22
+ sy: Float32Array;
23
+ /** Each member's offset from the centre along the facing direction and across it. */
24
+ fa: Float32Array;
25
+ fl: Float32Array;
26
+ /** Each member's rank (0 = front) and place in the rank (0 = leftmost, i.e. smallest lateral offset). */
27
+ row: Int16Array;
28
+ col: Int16Array;
29
+ /** Per rank: total width (sum of spacings), depth (largest spacing), members, offset along the facing direction, largest radius, slowest speed. */
30
+ rowW: number[];
31
+ rowD: number[];
32
+ rowN: number[];
33
+ rowFa: number[];
34
+ rowRad: number[];
35
+ rowRun: number[];
36
+ /** Radius of the circle around the whole block. */
37
+ radius: number;
38
+ width: number;
39
+ depth: number;
40
+ }
41
+ /**
42
+ * Ranks centred on (cx, cy) facing (dx, dy) (any length; a zero vector faces −y). Members are sorted by rank class,
43
+ * then front to back by their current position when `positions` is given, then by input order, and poured into ranks
44
+ * no wider than the frontage, a new rank starting at each class change. Within a rank, members keep that order, or
45
+ * with `positions` are placed left to right by current lateral position, which keeps paths from crossing. Facing east
46
+ * (+x), the left-to-right axis is +y.
47
+ * @param positions Each member's current position, in input order.
48
+ */
49
+ export declare function lineFormation(units: readonly FormationUnit[], cx: number, cy: number, dx: number, dy: number, positions?: readonly {
50
+ x: number;
51
+ y: number;
52
+ }[] | null, options?: Partial<FormationOptions>): Formation;
@@ -0,0 +1,105 @@
1
+ /** Line formation: arrange a group of units in ranks facing a direction. */
2
+ import { dmath } from '@pocketrts/determinism';
3
+ export const DEFAULT_FORMATION_OPTIONS = Object.freeze({ gap: 3, minWidth: 48, aspect: 2.6 });
4
+ /**
5
+ * Ranks centred on (cx, cy) facing (dx, dy) (any length; a zero vector faces −y). Members are sorted by rank class,
6
+ * then front to back by their current position when `positions` is given, then by input order, and poured into ranks
7
+ * no wider than the frontage, a new rank starting at each class change. Within a rank, members keep that order, or
8
+ * with `positions` are placed left to right by current lateral position, which keeps paths from crossing. Facing east
9
+ * (+x), the left-to-right axis is +y.
10
+ * @param positions Each member's current position, in input order.
11
+ */
12
+ export function lineFormation(units, cx, cy, dx, dy, positions = null, options = {}) {
13
+ const { gap, minWidth, aspect } = { ...DEFAULT_FORMATION_OPTIONS, ...options };
14
+ const n = units.length;
15
+ const sx = new Float32Array(n), sy = new Float32Array(n), fa = new Float32Array(n), fl = new Float32Array(n);
16
+ const row = new Int16Array(n), col = new Int16Array(n);
17
+ const dl = dmath.hypot(dx, dy);
18
+ if (dl < 1e-4) {
19
+ dx = 0;
20
+ dy = -1;
21
+ }
22
+ else {
23
+ dx /= dl;
24
+ dy /= dl;
25
+ }
26
+ const lx = -dy, ly = dx;
27
+ const along = new Float32Array(n), lat = new Float32Array(n);
28
+ if (positions) {
29
+ for (let m = 0; m < n; m++) {
30
+ const p = positions[m];
31
+ along[m] = p.x * dx + p.y * dy;
32
+ lat[m] = p.x * lx + p.y * ly;
33
+ }
34
+ }
35
+ const idx = Array.from({ length: n }, (_, i) => i);
36
+ idx.sort((a, b) => units[a].row - units[b].row || along[b] - along[a] || a - b);
37
+ let area = 0;
38
+ for (let m = 0; m < n; m++) {
39
+ const sp = units[m].radius * 2 + gap;
40
+ area += sp * sp;
41
+ }
42
+ const width = Math.max(minWidth, Math.sqrt(area * aspect));
43
+ const rows = [];
44
+ let cur = [], curW = 0, curRow = -1;
45
+ for (const m of idx) {
46
+ const u = units[m];
47
+ const sp = u.radius * 2 + gap;
48
+ if (cur.length && (curW + sp > width || u.row !== curRow)) {
49
+ rows.push(cur);
50
+ cur = [];
51
+ curW = 0;
52
+ }
53
+ curRow = u.row;
54
+ cur.push(m);
55
+ curW += sp;
56
+ }
57
+ if (cur.length)
58
+ rows.push(cur);
59
+ let depth = 0;
60
+ const rowDepth = [];
61
+ for (const r of rows) {
62
+ let mx = 0;
63
+ for (const m of r)
64
+ mx = Math.max(mx, units[m].radius * 2 + gap);
65
+ rowDepth.push(mx);
66
+ depth += mx;
67
+ }
68
+ const rowW = [], rowN = [], rowFa = [], rowRad = [], rowRun = [];
69
+ let dAcc = 0;
70
+ for (let ri = 0; ri < rows.length; ri++) {
71
+ const r = rows[ri];
72
+ if (positions)
73
+ r.sort((a, b) => lat[a] - lat[b]);
74
+ let w = 0, rad = 0, run = Infinity;
75
+ for (const m of r) {
76
+ const u = units[m];
77
+ w += u.radius * 2 + gap;
78
+ if (u.radius > rad)
79
+ rad = u.radius;
80
+ if (u.speed < run)
81
+ run = u.speed;
82
+ }
83
+ let xo = -w / 2;
84
+ const fwd = depth / 2 - dAcc - rowDepth[ri] / 2;
85
+ for (let k = 0; k < r.length; k++) {
86
+ const m = r[k];
87
+ const sp = units[m].radius * 2 + gap;
88
+ const l = xo + sp / 2;
89
+ fa[m] = fwd;
90
+ fl[m] = l;
91
+ row[m] = ri;
92
+ col[m] = k;
93
+ sx[m] = cx + lx * l + dx * fwd;
94
+ sy[m] = cy + ly * l + dy * fwd;
95
+ xo += sp;
96
+ }
97
+ rowW.push(w);
98
+ rowN.push(r.length);
99
+ rowFa.push(fwd);
100
+ rowRad.push(rad);
101
+ rowRun.push(run);
102
+ dAcc += rowDepth[ri];
103
+ }
104
+ return { sx, sy, fa, fl, row, col, rowW, rowD: rowDepth, rowN, rowFa, rowRad, rowRun, radius: dmath.hypot(width, depth) / 2, width, depth };
105
+ }
@@ -0,0 +1,9 @@
1
+ export * from './dirs.js';
2
+ export * from './flowfield.js';
3
+ export * from './localpath.js';
4
+ export * from './cells.js';
5
+ export * from './buckets.js';
6
+ export * from './vision.js';
7
+ export * from './polygon.js';
8
+ export * from './chain.js';
9
+ export * from './formation.js';
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export * from './dirs.js';
2
+ export * from './flowfield.js';
3
+ export * from './localpath.js';
4
+ export * from './cells.js';
5
+ export * from './buckets.js';
6
+ export * from './vision.js';
7
+ export * from './polygon.js';
8
+ export * from './chain.js';
9
+ export * from './formation.js';
@@ -0,0 +1,35 @@
1
+ /** Step rules for `LocalPathfinder.find`. */
2
+ export interface LocalStepRules {
3
+ /** Non-zero = the cell cannot be entered. */
4
+ readonly block: ArrayLike<number>;
5
+ /** Whether a unit may step straight from `a` to the adjacent passable cell `b`. */
6
+ canStep(a: number, b: number): boolean;
7
+ /** Whether a unit may step diagonally from `a` to `b`. */
8
+ canStepDiag(a: number, b: number): boolean;
9
+ }
10
+ export declare class LocalPathfinder {
11
+ readonly maxNodes: number;
12
+ /**
13
+ * The last path found, goal first, start last (`length` cells, truncated to `maxNodes + 1` cells when longer).
14
+ * Valid until the next `find`.
15
+ */
16
+ readonly path: Int32Array;
17
+ /** Cells in `path`; 0 after a failed search. */
18
+ length: number;
19
+ private readonly heapF;
20
+ private readonly heapC;
21
+ private cells;
22
+ private gen;
23
+ private stamp;
24
+ private gScore;
25
+ private parent;
26
+ private closed;
27
+ /** @param maxNodes Most cells a search expands before giving up (a safeguard beyond the length limit). Default 1200. */
28
+ constructor(maxNodes?: number);
29
+ /**
30
+ * Find a path from cell `start` to cell `goal` on a `w` × `h` grid whose length (straight steps 1, diagonal √2)
31
+ * stays within `limit` cells, using the octile distance as the estimate. Returns whether one was found; the path is
32
+ * then in `path` / `length`. A blocked goal is never reached.
33
+ */
34
+ find(w: number, h: number, start: number, goal: number, limit: number, rules: LocalStepRules): boolean;
35
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Short-range A* on an 8-connected grid with a path-length limit, for steering around small obstacles where a whole
3
+ * flow field per goal would be wasteful (a chaser whose target cell changes every few steps, say).
4
+ *
5
+ * One instance owns its search buffers and reuses them across calls; it is not re-entrant. Ties are broken by heap
6
+ * order, so the same inputs always give the same path.
7
+ */
8
+ import { DIRX, DIRY } from './dirs.js';
9
+ const SQRT2 = Math.SQRT2;
10
+ export class LocalPathfinder {
11
+ maxNodes;
12
+ /**
13
+ * The last path found, goal first, start last (`length` cells, truncated to `maxNodes + 1` cells when longer).
14
+ * Valid until the next `find`.
15
+ */
16
+ path;
17
+ /** Cells in `path`; 0 after a failed search. */
18
+ length = 0;
19
+ heapF;
20
+ heapC;
21
+ cells = 0;
22
+ gen = 0;
23
+ stamp = new Int32Array(0);
24
+ gScore = new Float64Array(0);
25
+ parent = new Int32Array(0);
26
+ closed = new Int32Array(0);
27
+ /** @param maxNodes Most cells a search expands before giving up (a safeguard beyond the length limit). Default 1200. */
28
+ constructor(maxNodes = 1200) {
29
+ this.maxNodes = maxNodes;
30
+ this.heapF = new Float64Array(maxNodes * 8 + 1);
31
+ this.heapC = new Int32Array(maxNodes * 8 + 1);
32
+ this.path = new Int32Array(maxNodes + 1);
33
+ }
34
+ /**
35
+ * Find a path from cell `start` to cell `goal` on a `w` × `h` grid whose length (straight steps 1, diagonal √2)
36
+ * stays within `limit` cells, using the octile distance as the estimate. Returns whether one was found; the path is
37
+ * then in `path` / `length`. A blocked goal is never reached.
38
+ */
39
+ find(w, h, start, goal, limit, rules) {
40
+ const n = w * h;
41
+ if (n !== this.cells) {
42
+ this.cells = n;
43
+ this.stamp = new Int32Array(n);
44
+ this.closed = new Int32Array(n);
45
+ this.gScore = new Float64Array(n);
46
+ this.parent = new Int32Array(n);
47
+ this.gen = 0;
48
+ }
49
+ if (++this.gen === 0x7fffffff) {
50
+ this.stamp.fill(0);
51
+ this.closed.fill(0);
52
+ this.gen = 1;
53
+ }
54
+ this.length = 0;
55
+ const { heapF, heapC, stamp, closed, gScore, parent, gen } = this;
56
+ const blk = rules.block;
57
+ if (blk[goal])
58
+ return false;
59
+ const gx = goal % w, gy = (goal / w) | 0;
60
+ let hs = 0, expanded = 0, found = false;
61
+ stamp[start] = gen;
62
+ gScore[start] = 0;
63
+ parent[start] = -1;
64
+ heapF[0] = 0;
65
+ heapC[hs++] = start;
66
+ while (hs > 0) {
67
+ const c = heapC[0];
68
+ hs--;
69
+ if (hs > 0) {
70
+ const lf = heapF[hs], lc = heapC[hs];
71
+ let k = 0;
72
+ for (;;) {
73
+ let l = 2 * k + 1;
74
+ if (l >= hs)
75
+ break;
76
+ if (l + 1 < hs && heapF[l + 1] < heapF[l])
77
+ l++;
78
+ if (heapF[l] >= lf)
79
+ break;
80
+ heapF[k] = heapF[l];
81
+ heapC[k] = heapC[l];
82
+ k = l;
83
+ }
84
+ heapF[k] = lf;
85
+ heapC[k] = lc;
86
+ }
87
+ if (closed[c] === gen)
88
+ continue;
89
+ closed[c] = gen;
90
+ if (c === goal) {
91
+ found = true;
92
+ break;
93
+ }
94
+ if (++expanded > this.maxNodes)
95
+ break;
96
+ const cx = c % w, cy = (c / w) | 0, gc = gScore[c];
97
+ for (let dir = 0; dir < 8; dir++) {
98
+ const nx = cx + DIRX[dir], ny = cy + DIRY[dir];
99
+ if (nx < 0 || ny < 0 || nx >= w || ny >= h)
100
+ continue;
101
+ const nc = ny * w + nx;
102
+ if (closed[nc] === gen || blk[nc])
103
+ continue;
104
+ let ng;
105
+ if (dir & 1) {
106
+ if (!rules.canStepDiag(c, nc))
107
+ continue;
108
+ ng = gc + SQRT2;
109
+ }
110
+ else {
111
+ if (!rules.canStep(c, nc))
112
+ continue;
113
+ ng = gc + 1;
114
+ }
115
+ if (stamp[nc] === gen && gScore[nc] <= ng)
116
+ continue;
117
+ const hx = Math.abs(nx - gx), hy = Math.abs(ny - gy);
118
+ const nf = ng + (hx > hy ? hx - hy + hy * SQRT2 : hy - hx + hx * SQRT2);
119
+ if (nf > limit || hs >= heapF.length)
120
+ continue;
121
+ stamp[nc] = gen;
122
+ gScore[nc] = ng;
123
+ parent[nc] = c;
124
+ let k = hs++;
125
+ while (k > 0) {
126
+ const p = (k - 1) >> 1;
127
+ if (heapF[p] <= nf)
128
+ break;
129
+ heapF[k] = heapF[p];
130
+ heapC[k] = heapC[p];
131
+ k = p;
132
+ }
133
+ heapF[k] = nf;
134
+ heapC[k] = nc;
135
+ }
136
+ }
137
+ if (!found)
138
+ return false;
139
+ let len = 0;
140
+ for (let c = goal; c !== -1 && len < this.path.length; c = parent[c])
141
+ this.path[len++] = c;
142
+ this.length = len;
143
+ return true;
144
+ }
145
+ }
@@ -0,0 +1,4 @@
1
+ /** Whether (x, y) is inside the polygon (even–odd ray casting; points exactly on an edge may go either way). */
2
+ export declare function inPolygon(o: ArrayLike<number>, x: number, y: number): boolean;
3
+ /** Distance from (x, y) to the nearest point of the polygon's outline (whether inside or outside). */
4
+ export declare function polygonDist(o: ArrayLike<number>, x: number, y: number): number;
@@ -0,0 +1,25 @@
1
+ /** Closed polygons given as flat vertex lists (x0, y0, x1, y1, …); the last vertex connects back to the first. */
2
+ import { dmath } from '@pocketrts/determinism';
3
+ /** Whether (x, y) is inside the polygon (even–odd ray casting; points exactly on an edge may go either way). */
4
+ export function inPolygon(o, x, y) {
5
+ let inside = false;
6
+ const n = o.length;
7
+ for (let a = 0, b = n - 2; a < n; b = a, a += 2) {
8
+ const ay = o[a + 1], by = o[b + 1];
9
+ if ((ay > y) !== (by > y) && x < o[a] + ((y - ay) * (o[b] - o[a])) / (by - ay))
10
+ inside = !inside;
11
+ }
12
+ return inside;
13
+ }
14
+ /** Distance from (x, y) to the nearest point of the polygon's outline (whether inside or outside). */
15
+ export function polygonDist(o, x, y) {
16
+ let best = Infinity;
17
+ const n = o.length;
18
+ for (let a = 0, b = n - 2; a < n; b = a, a += 2) {
19
+ const ax = o[b], ay = o[b + 1], ex = o[a] - ax, ey = o[a + 1] - ay;
20
+ const len2 = ex * ex + ey * ey;
21
+ const t = len2 > 0 ? Math.max(0, Math.min(1, ((x - ax) * ex + (y - ay) * ey) / len2)) : 0;
22
+ best = Math.min(best, dmath.hypot(x - ax - ex * t, y - ay - ey * t));
23
+ }
24
+ return best;
25
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Field of view on a cell raster: each viewer reveals a disc of cells. A per-cell record of the largest radius already
3
+ * stamped there lets many viewers standing in the same cell cost one stamp.
4
+ */
5
+ /**
6
+ * Mark the disc of radius `r` cells around cell (cx, cy) in `vis` (set to 1), clipped to the `w` × `h` raster.
7
+ * Row dy spans ⌊√(r² + r − dy²)⌋ cells to each side, a slightly fuller disc than r² would give. `stamped` holds, per
8
+ * cell, the largest radius stamped from it since it was last cleared; a disc no larger than that is skipped. Clear
9
+ * `vis` and `stamped` together (fill with 0) before each recomputation.
10
+ */
11
+ export declare function stampDisc(vis: Uint8Array, stamped: Uint8Array | Uint16Array, w: number, h: number, cx: number, cy: number, r: number): void;
package/dist/vision.js ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Field of view on a cell raster: each viewer reveals a disc of cells. A per-cell record of the largest radius already
3
+ * stamped there lets many viewers standing in the same cell cost one stamp.
4
+ */
5
+ /**
6
+ * Mark the disc of radius `r` cells around cell (cx, cy) in `vis` (set to 1), clipped to the `w` × `h` raster.
7
+ * Row dy spans ⌊√(r² + r − dy²)⌋ cells to each side, a slightly fuller disc than r² would give. `stamped` holds, per
8
+ * cell, the largest radius stamped from it since it was last cleared; a disc no larger than that is skipped. Clear
9
+ * `vis` and `stamped` together (fill with 0) before each recomputation.
10
+ */
11
+ export function stampDisc(vis, stamped, w, h, cx, cy, r) {
12
+ const c = cy * w + cx;
13
+ if (stamped[c] >= r)
14
+ return;
15
+ stamped[c] = r;
16
+ for (let dy = -r; dy <= r; dy++) {
17
+ const yy = cy + dy;
18
+ if (yy < 0 || yy >= h)
19
+ continue;
20
+ const span = Math.floor(Math.sqrt(r * r + r - dy * dy));
21
+ let xa = cx - span, xb = cx + span;
22
+ if (xa < 0)
23
+ xa = 0;
24
+ if (xb >= w)
25
+ xb = w - 1;
26
+ const row = yy * w;
27
+ for (let xx = xa; xx <= xb; xx++)
28
+ vis[row + xx] = 1;
29
+ }
30
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@pocketrts/grid",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Grid algorithms for RTS games: budgeted flow fields, bounded local A*, line reach, distance fields, bucket grids, field of view, polygons, cell chains and line formations",
5
+ "license": "MIT",
6
+ "author": "Junjie Bai <bjj19851010@gmail.com>",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/baijunjie/pocketrts.git",
10
+ "directory": "packages/grid"
11
+ },
12
+ "keywords": [
13
+ "pathfinding",
14
+ "flow-field",
15
+ "astar",
16
+ "spatial-hash",
17
+ "formation",
18
+ "rts",
19
+ "game"
20
+ ],
21
+ "type": "module",
22
+ "sideEffects": false,
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "@pocketrts/source": "./src/index.ts",
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js"
30
+ },
31
+ "./package.json": "./package.json"
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "LICENSE"
36
+ ],
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "dependencies": {
41
+ "@pocketrts/determinism": "^0.1.0"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.build.json",
45
+ "typecheck": "tsc -p tsconfig.json --noEmit",
46
+ "test": "vitest run --maxWorkers=2"
47
+ }
6
48
  }