@pocketrts/grid 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +146 -2
- package/dist/buckets.d.ts +32 -0
- package/dist/buckets.js +82 -0
- package/dist/cells.d.ts +21 -0
- package/dist/cells.js +108 -0
- package/dist/chain.d.ts +27 -0
- package/dist/chain.js +112 -0
- package/dist/dirs.d.ts +7 -0
- package/dist/dirs.js +7 -0
- package/dist/flowfield.d.ts +85 -0
- package/dist/flowfield.js +214 -0
- package/dist/formation.d.ts +74 -0
- package/dist/formation.js +143 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +16 -0
- package/dist/localpath.d.ts +35 -0
- package/dist/localpath.js +145 -0
- package/dist/march.d.ts +77 -0
- package/dist/march.js +665 -0
- package/dist/marchChoke.d.ts +27 -0
- package/dist/marchChoke.js +140 -0
- package/dist/marchGround.d.ts +45 -0
- package/dist/marchGround.js +73 -0
- package/dist/marchSlots.d.ts +66 -0
- package/dist/marchSlots.js +215 -0
- package/dist/marchTrail.d.ts +48 -0
- package/dist/marchTrail.js +282 -0
- package/dist/marchTypes.d.ts +289 -0
- package/dist/marchTypes.js +31 -0
- package/dist/polygon.d.ts +4 -0
- package/dist/polygon.js +25 -0
- package/dist/vision.d.ts +11 -0
- package/dist/vision.js +30 -0
- package/package.json +45 -3
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,147 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pocketrts/grid
|
|
2
2
|
|
|
3
|
-
|
|
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, 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.
|
|
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 `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. |
|
|
37
|
+
| `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. |
|
|
38
|
+
| `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. |
|
|
39
|
+
| `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. |
|
|
40
|
+
| `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. |
|
|
41
|
+
| `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. |
|
|
42
|
+
| `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). |
|
|
43
|
+
| `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. |
|
|
44
|
+
| `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. |
|
|
45
|
+
| `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. |
|
|
46
|
+
| `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. |
|
|
47
|
+
| `DIRX`, `DIRY`, `DIR_HERE`, `DIR_NONE` | Direction tables and markers. |
|
|
48
|
+
|
|
49
|
+
## Usage
|
|
50
|
+
|
|
51
|
+
One layer, units following a shared field:
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { cornerFree, DIR_HERE, DIR_NONE, DIRX, DIRY, FlowFields } from '@pocketrts/grid';
|
|
55
|
+
|
|
56
|
+
const cost = new Uint16Array(w * h); // 10 = ordinary ground, 30 = mud, 0 = wall (outer ring 0)
|
|
57
|
+
const block = new Uint8Array(w * h); // 1 = wall
|
|
58
|
+
const fields = new FlowFields(w, h, [{
|
|
59
|
+
cost,
|
|
60
|
+
canStep: () => true,
|
|
61
|
+
canStepDiag: (a, b) => cornerFree(block, w, a, b),
|
|
62
|
+
}]);
|
|
63
|
+
|
|
64
|
+
function step(tick: number) {
|
|
65
|
+
fields.maintain(tick);
|
|
66
|
+
for (const u of units) {
|
|
67
|
+
const f = fields.get(u.goal, 0, tick, () => Int32Array.of(u.goal)); // key = goal cell, one layer
|
|
68
|
+
const d = f.dirs[u.cell];
|
|
69
|
+
if (d === DIR_HERE) arrive(u);
|
|
70
|
+
else if (d === DIR_NONE) moveStraightTowards(u, u.goal); // not reached yet: head straight
|
|
71
|
+
else moveTowardsCell(u, u.cell + DIRX[d] + DIRY[d] * w);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// After a wall is built or destroyed:
|
|
76
|
+
setWall(cell);
|
|
77
|
+
fields.invalidate();
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
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:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import {
|
|
84
|
+
cornerFree, createMarch, FlowFields, GridGround, lineFormation, marchRules, STEER, STEER_APART, STEER_KEEP, STEER_LEAVE,
|
|
85
|
+
STEER_PUSH, steerMember, updateMarches, type March, type MarchMembers,
|
|
86
|
+
} from '@pocketrts/grid';
|
|
87
|
+
|
|
88
|
+
// The map: one ground per movement layer (the outer ring of `block` must be blocked)
|
|
89
|
+
const fields = new FlowFields(w, h, [{ cost, canStep: () => true, canStepDiag: (a, b) => cornerFree(block, w, a, b) }]);
|
|
90
|
+
const ground = new GridGround({ w, h, cellSize, block, fields });
|
|
91
|
+
const rules = marchRules(cellSize / 32); // the defaults suit cells of 32 units
|
|
92
|
+
|
|
93
|
+
// The units: per-unit arrays the march reads (march: Int16Array filled with -1; apart: Uint8Array)
|
|
94
|
+
const marches: March[] = [];
|
|
95
|
+
const members: MarchMembers = {
|
|
96
|
+
n, alive: () => true, march: i => marchOf[i], leave: i => { marchOf[i] = -1; },
|
|
97
|
+
x: i => px[i], y: i => py[i], row: i => rank[i], col: i => place[i], lateral: i => offset[i],
|
|
98
|
+
apart: i => apart[i] !== 0, state: () => 0, // MEMBER_… flags when units fight
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
// An order: lay the ranks out facing (fx, fy) round the goal (gx, gy), then set the group marching
|
|
102
|
+
function order(gx: number, gy: number, fx: number, fy: number) {
|
|
103
|
+
const f = lineFormation(units, gx, gy, fx, fy, positions); // positions: current { x, y } per unit
|
|
104
|
+
const g = createMarch(marches, ground, rules, {
|
|
105
|
+
layer: 0, x: centreX, y: centreY, destX: gx, destY: gy, destCell: ground.cellAt(gx, gy),
|
|
106
|
+
speed: slowest * 0.9, run: slowest, hold: false, fx, fy, formation: f,
|
|
107
|
+
});
|
|
108
|
+
for (let i = 0; i < n; i++) {
|
|
109
|
+
marchOf[i] = g.id; rank[i] = f.row[i]; place[i] = f.col[i]; offset[i] = f.fl[i];
|
|
110
|
+
spotX[i] = f.sx[i]; spotY[i] = f.sy[i]; // the unit's own spot at the goal
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Each step: the march first, then every member as it answers
|
|
115
|
+
function step(tick: number) {
|
|
116
|
+
ground.tick = tick;
|
|
117
|
+
fields.maintain(tick);
|
|
118
|
+
updateMarches(marches, () => ground, members, rules, dt, tick);
|
|
119
|
+
for (let i = 0; i < n; i++) {
|
|
120
|
+
if (marchOf[i] < 0) continue;
|
|
121
|
+
const what = steerMember(ground, marches[marchOf[i]], rules, rank[i], place[i], offset[i], px[i], py[i],
|
|
122
|
+
spotX[i], spotY[i], speed[i], speed[i], false);
|
|
123
|
+
apart[i] = STEER.apart ? 1 : 0; // read before the next call overwrites STEER
|
|
124
|
+
if (what === STEER_KEEP) moveBy(i, STEER.vx * dt, STEER.vy * dt);
|
|
125
|
+
else if (what === STEER_APART || what === STEER_PUSH) walkOwnRoute(i, STEER.speed * dt);
|
|
126
|
+
else if (what === STEER_LEAVE) { marchOf[i] = -1; walkToSpot(i); }
|
|
127
|
+
// STEER_IDLE: move as if there were no march
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
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.
|
|
133
|
+
|
|
134
|
+
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.
|
|
135
|
+
|
|
136
|
+
## Notes
|
|
137
|
+
|
|
138
|
+
- Flow-field costs are integers in tenths; distances are summed as integers, so results do not depend on float rounding.
|
|
139
|
+
- `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.
|
|
140
|
+
- `LocalPathfinder`, `BucketGrid` and the flow-field search reuse their buffers: create one per world, or share one when calls never interleave.
|
|
141
|
+
- 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.
|
|
142
|
+
- Speeds are world units per second, including the `speed` of the units given to `lineFormation`. The defaults suit cells of about 32 units: for other cells use `marchRules(cellSize / 32)` and scale `lineFormation`'s `gap` and `minWidth` alike.
|
|
143
|
+
- `MarchRules.flank` (default off) also keeps ranks clear of an obstacle on one side and of thin obstacles, counts a thin wall that runs on across the column's width as a narrow place, and lets the column turn as tightly as half the usable width where the way is narrower than the column: turn it on where routes run along walls.
|
|
144
|
+
- `MarchRules.faceRoute`, `wheel` and `lookClear` (all off by default) are for rigid formations on routes that hug walls: `faceRoute` forms the column up along the route's first stretch instead of the straight line to the goal, `wheel` makes only the ranks on a bend close up along the trail, and `lookClear` straightens the route toward points that keep clear of walls to each side. With all of them off, the march is exactly the one Pocket War ships (its state checksums are byte-identical on the package).
|
|
145
|
+
- `createMarch` creates the `March` object with its properties in a fixed order, because games hash their state in property order; a game that hashes a march keeps that order.
|
|
146
|
+
- The result objects `STEER`, `MARCH_SLOT`, `MARCH_FOLLOW` and `MARCH_POINT` are shared and overwritten by each call: copy what is needed before the next one.
|
|
147
|
+
- As for flow fields, the outermost ring of the grid must be blocked.
|
|
@@ -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
|
+
}
|
package/dist/buckets.js
ADDED
|
@@ -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
|
+
}
|
package/dist/cells.d.ts
ADDED
|
@@ -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
|
+
}
|
package/dist/chain.d.ts
ADDED
|
@@ -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;
|