BlueGit

timfa questward

Files

questward / server / src / simulation / follow.js

follow.js

follow.js 8.3 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
3import { chunkBoundsAround, findPath } from "../navigation/astar.js";
4import { chebyshev } from "../combat/service.js";
5
6const FOLLOW_BREAK_TILES = CHUNK_SIZE;
7const FOLLOW_ALWAYS_RUN_TILES = 3;
8const FOLLOW_TRAIL_MAX = CHUNK_SIZE * 2;
9
10function canEntityRun (ecs, handle)
11{
12 const stamina = ecs.get(handle, Component.stamina);
13 if (!stamina)
14 { return true; }
15 return Number(stamina.current) > 0;
16}
17
18export function clearFollow (ecs, entityId)
19{
20 const handle = ecs.handleOf(entityId);
21 const follow = handle != null ? ecs.get(handle, Component.follow) : null;
22 if (follow)
23 {
24 follow.targetEntityId = null;
25 follow.trail = [];
26 }
27}
28
29export function setFollow (ecs, followerId, targetId)
30{
31 const handle = ecs.handleOf(followerId);
32 if (handle == null)
33 { return false; }
34 let follow = ecs.get(handle, Component.follow);
35 if (!follow)
36 { follow = ecs.add(handle, Component.follow, { targetEntityId: null, trail: [] }); }
37 follow.targetEntityId = targetId;
38 follow.trail = [];
39 return true;
40}
41
42/** Record a tile the target just vacated so followers can reuse that path. */
43export function recordFollowTrail (ecs, targetEntityId, fromTileX, fromTileY)
44{
45 for (const entity of ecs.query(Component.follow))
46 {
47 const follow = entity.follow;
48 if (follow.targetEntityId !== targetEntityId)
49 { continue; }
50 if (!Array.isArray(follow.trail))
51 { follow.trail = []; }
52 const last = follow.trail[follow.trail.length - 1];
53 if (last && last.x === fromTileX && last.y === fromTileY)
54 { continue; }
55 follow.trail.push({ x: fromTileX, y: fromTileY });
56 if (follow.trail.length > FOLLOW_TRAIL_MAX)
57 { follow.trail.splice(0, follow.trail.length - FOLLOW_TRAIL_MAX); }
58 }
59}
60
61/** Drop trail tiles the follower has already reached. */
62export function consumeFollowTrail (ecs, followerId, tileX, tileY)
63{
64 const handle = ecs.handleOf(followerId);
65 const follow = handle != null ? ecs.get(handle, Component.follow) : null;
66 if (!follow?.trail?.length)
67 { return; }
68 while (follow.trail.length && follow.trail[0].x === tileX && follow.trail[0].y === tileY)
69 { follow.trail.shift(); }
70}
71
72export function stepFollow (world)
73{
74 for (const entity of world.ecs.query(Component.follow, Component.position, Component.movement))
75 {
76 const follow = entity.follow;
77 const targetId = follow.targetEntityId;
78 if (targetId == null)
79 { continue; }
80 if (world.frozen?.has?.(entity.entityId))
81 { continue; }
82
83 const target = resolveFollowTarget(world, targetId);
84 if (!target)
85 {
86 follow.targetEntityId = null;
87 follow.trail = [];
88 continue;
89 }
90
91 const dist = chebyshev(
92 entity.position.tileX,
93 entity.position.tileY,
94 target.pos.tileX,
95 target.pos.tileY
96 );
97 if (dist > FOLLOW_BREAK_TILES)
98 {
99 follow.targetEntityId = null;
100 follow.trail = [];
101 clearPath(world.ecs, entity.handle);
102 continue;
103 }
104
105 const canRun = canEntityRun(world.ecs, entity.handle);
106 if (dist > FOLLOW_ALWAYS_RUN_TILES)
107 { entity.movement.gait = canRun ? GAIT.run : GAIT.walk; }
108 else if (dist > 1)
109 {
110 entity.movement.gait = canRun && target.gait === GAIT.run
111 ? GAIT.run
112 : GAIT.walk;
113 }
114
115 if (!Array.isArray(follow.trail))
116 { follow.trail = []; }
117 trimTrailBehindFollower(follow.trail, entity.position);
118
119 const targetMoving = (target.pathTiles?.length ?? 0) > 0 || follow.trail.length > 0;
120 // Stay put only when already adjacent and the target is idle — otherwise keep
121 // chasing footsteps (including waiting on the target's current tile).
122 if (dist <= 1 && !targetMoving)
123 {
124 clearPath(world.ecs, entity.handle);
125 continue;
126 }
127
128 const reused = buildFollowPath(
129 world,
130 entity.entityId,
131 entity.position,
132 target.pos,
133 follow.trail,
134 target.pathTiles
135 );
136
137 let path = world.ecs.get(entity.handle, Component.path);
138 if (!path)
139 { path = world.ecs.add(entity.handle, Component.path, { tiles: [] }); }
140
141 if (reused.waiting)
142 {
143 // Next trail tile is occupied — wait for vacancy instead of detouring.
144 assignFollowPath(entity.movement, path, reused.tiles);
145 continue;
146 }
147
148 if (reused.tiles.length)
149 {
150 assignFollowPath(entity.movement, path, reused.tiles);
151 continue;
152 }
153
154 // No shared trail/path yet — catch up with a one-shot approach path.
155 queueCatchUp(world, entity.entityId, entity.handle, entity.position, target.pos, path);
156 }
157}
158
159function resolveFollowTarget (world, targetId)
160{
161 const targetHandle = world.ecs.handleOf(targetId);
162 if (targetHandle != null)
163 {
164 const pos = world.ecs.get(targetHandle, Component.position);
165 if (!pos)
166 { return null; }
167 const movement = world.ecs.get(targetHandle, Component.movement);
168 const path = world.ecs.get(targetHandle, Component.path);
169 return {
170 pos,
171 gait: movement?.gait,
172 pathTiles: path?.tiles ?? []
173 };
174 }
175 const ghost = world.ghosts?.get?.(targetId);
176 if (!ghost)
177 { return null; }
178 return {
179 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
180 gait: ghost.gait,
181 pathTiles: []
182 };
183}
184
185function buildFollowPath (world, followerId, followerPos, targetPos, trail, targetPathTiles)
186{
187 const combined = [];
188 for (const tile of trail)
189 { combined.push({ x: tile.x, y: tile.y }); }
190 const lastTrail = combined[combined.length - 1];
191 if (!lastTrail || lastTrail.x !== targetPos.tileX || lastTrail.y !== targetPos.tileY)
192 { combined.push({ x: targetPos.tileX, y: targetPos.tileY }); }
193 for (const tile of targetPathTiles)
194 {
195 const prev = combined[combined.length - 1];
196 if (prev && prev.x === tile.x && prev.y === tile.y)
197 { continue; }
198 combined.push({ x: tile.x, y: tile.y });
199 }
200
201 const result = [];
202 let cursorX = followerPos.tileX;
203 let cursorY = followerPos.tileY;
204 for (const tile of combined)
205 {
206 if (tile.x === cursorX && tile.y === cursorY)
207 { continue; }
208 const stepDist = chebyshev(cursorX, cursorY, tile.x, tile.y);
209 if (stepDist > 1)
210 {
211 // Gap between follower and trail — fall through to catch-up.
212 if (!result.length)
213 { return { tiles: [], waiting: false }; }
214 break;
215 }
216 if (!world.walkableFor(followerId, tile.x, tile.y))
217 {
218 // Occupied (usually by the follow target) — wait on that footstep.
219 if (!result.length)
220 { return { tiles: [{ x: tile.x, y: tile.y }], waiting: true }; }
221 break;
222 }
223 const prev = result[result.length - 1];
224 if (prev && prev.x === tile.x && prev.y === tile.y)
225 { continue; }
226 result.push({ x: tile.x, y: tile.y });
227 cursorX = tile.x;
228 cursorY = tile.y;
229 }
230 return { tiles: result, waiting: false };
231}
232
233function assignFollowPath (movement, path, tiles)
234{
235 const prevNext = path.tiles?.[0];
236 const next = tiles[0];
237 const nextChanged = !next
238 || !prevNext
239 || prevNext.x !== next.x
240 || prevNext.y !== next.y;
241 path.tiles = tiles;
242 // Only reset walk cadence when the immediate step changes; refreshing the
243 // remaining trail every systems tick must not stall walking followers.
244 if (nextChanged)
245 { movement.walkCarry = 0; }
246}
247
248function trimTrailBehindFollower (trail, position)
249{
250 while (trail.length)
251 {
252 const next = trail[0];
253 if (next.x === position.tileX && next.y === position.tileY)
254 {
255 trail.shift();
256 continue;
257 }
258 break;
259 }
260}
261
262function queueCatchUp (world, entityId, handle, position, targetPos, path)
263{
264 const goal = { x: targetPos.tileX, y: targetPos.tileY };
265 if (position.tileX === goal.x && position.tileY === goal.y)
266 {
267 path.tiles = [];
268 return;
269 }
270 if (path.tiles?.length)
271 {
272 const last = path.tiles[path.tiles.length - 1];
273 const first = path.tiles[0];
274 if (last.x === goal.x && last.y === goal.y
275 && chebyshev(position.tileX, position.tileY, first.x, first.y) <= 1)
276 { return; }
277 }
278 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
279 const inCombat = !!world.ecs.get(handle, Component.combat)?.targetEntityId;
280 const nextTiles = findPath(
281 position.tileX,
282 position.tileY,
283 goal.x,
284 goal.y,
285 (x, y) =>
286 {
287 // Plan onto the target tile; movement still waits while they occupy it.
288 return world.walkableFor(entityId, x, y);
289 },
290 bounds.minX,
291 bounds.minY,
292 bounds.maxX,
293 bounds.maxY,
294 world.pathfindOptions({ preferVertical: true, preferPaths: !inCombat, entityId })
295 );
296 const movement = world.ecs.get(handle, Component.movement);
297 if (movement)
298 { assignFollowPath(movement, path, nextTiles); }
299 else
300 { path.tiles = nextTiles; }
301}
302
303function clearPath (ecs, handle)
304{
305 const path = ecs.get(handle, Component.path);
306 if (path)
307 { path.tiles = []; }
308}