BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

workerWorld.js 41.5 KiB Download Raw
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js";
2import {
3 chunkKey,
4 chunkToRegion,
5 parseChunkKey,
6 regionKey,
7 tileKey,
8 tileToChunk,
9 tileToLocal,
10 tileToRegion
11} from "../world/coordinates.js";
12import { cloneChunkData, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
13import { closedNeighborEdges } from "../world/chunkFlags.js";
14import { EcsWorld } from "../ecs/world.js";
15import { Component } from "../ecs/components.js";
16import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js";
17import { chunkBoundsAround, findPath } from "../navigation/astar.js";
18import { WorkerMessage } from "./protocol.js";
19import { collectSpawnRequests } from "./spawners.js";
20import { mobDefinition } from "../../../shared/definitions/mobs.js";
21import {
22 bagView,
23 applyBagView,
24 addGroundItem,
25 expireGroundItems,
26 groundItemsInChunk,
27 groundItemsInRegion,
28 handleItemCommand,
29 removeGroundItem,
30 publicGroundItem,
31 setGroundItemsForRegion
32} from "../items/bags.js";
33import { handleAlchemyCommand } from "../alchemy/service.js";
34import {
35 handleGatherCommand,
36 stepGather,
37 cancelGather,
38 clearOreRespawnsForChunk
39} from "../gathering/service.js";
40import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
41import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
42import {
43 applyRemoteMeleeSwing,
44 clearEngage,
45 engageTarget,
46 ensureMobCombat,
47 isUntargetable,
48 resolveCombatTarget,
49 stepAggression,
50 stepCombat
51} from "../combat/service.js";
52import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
53import { SkillId } from "../../../shared/definitions/skills.js";
54import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
55import {
56 STAMINA_REGEN_PER_SECOND,
57 STAMINA_XP_PER_POINT_SPENT,
58 staminaCostPerRunStep,
59 publicStaminaView
60} from "../../../shared/stamina/rules.js";
61import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
62import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
63
64export class WorkerWorld
65{
66 constructor (workerId)
67 {
68 this.workerId = workerId;
69 this.ecs = new EcsWorld();
70 this.chunks = new Map();
71 this.ownedRegions = new Set();
72 this.occupancy = new Map();
73 this.ghosts = new Map();
74 this.ghostOccupancy = new Map();
75 this.characterEntities = new Map();
76 this.frozen = new Set();
77 this.groundItems = new Map();
78 this.groundByTile = new Map();
79 this.oreRespawns = new Map();
80 this.settings = { ...DEFAULT_WORLD_SETTINGS };
81 this.activeRevisionId = 1;
82 }
83
84 handle (message)
85 {
86 switch (message.type)
87 {
88 case WorkerMessage.configure:
89 return this.#configure(message);
90 case WorkerMessage.assignRegion:
91 return this.#assignRegion(message);
92 case WorkerMessage.dropRegion:
93 return this.#dropRegion(message);
94 case WorkerMessage.replaceRegionChunks:
95 return this.#replaceRegionChunks(message);
96 case WorkerMessage.setReplicas:
97 return this.#setReplicas(message);
98 case WorkerMessage.setSimulatingChunks:
99 return this.#setSimulatingChunks(message);
100 case WorkerMessage.setGhosts:
101 return this.#setGhosts(message);
102 case WorkerMessage.spawn:
103 return this.#spawn(message);
104 case WorkerMessage.despawn:
105 return this.#despawn(message.entityId);
106 case WorkerMessage.despawnCharacter:
107 return this.#despawnCharacter(message.characterId);
108 case WorkerMessage.command:
109 return this.#command(message);
110 case WorkerMessage.stepMovement:
111 return this.#stepMovement(message.now);
112 case WorkerMessage.stepSystems:
113 return this.#stepSystems(message.now, message.dt ?? (1 / 20));
114 case WorkerMessage.stepSpawners:
115 return { spawnRequests: collectSpawnRequests(this) };
116 case WorkerMessage.setGroundItems:
117 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
118 return { ok: true };
119 case WorkerMessage.inspectBag:
120 return this.#inspectBag(message.entityId);
121 case WorkerMessage.inspectSkills:
122 return this.#inspectSkills(message.entityId);
123 case WorkerMessage.inspectStamina:
124 return this.#inspectStamina(message.entityId);
125 case WorkerMessage.applyBag:
126 return this.#applyBag(message.entityId, message.bag);
127 case WorkerMessage.updateFlight:
128 return this.#updateFlight(message.entityId, message.flight, message.now);
129 case WorkerMessage.chunkIsSimulating:
130 return this.chunkIsSimulating(message.tileX, message.tileY);
131 case WorkerMessage.applyTransfer:
132 return this.#applyTransfer(message);
133 case WorkerMessage.commitTransfer:
134 return this.#commitTransfer(message.entityId);
135 case WorkerMessage.abortTransfer:
136 return this.#abortTransfer(message.entityId);
137 case WorkerMessage.snapshotChunk:
138 return this.#chunkSnapshot(message.chunkX, message.chunkY);
139 case WorkerMessage.listLoaders:
140 return this.#listLoaders();
141 case WorkerMessage.listPublicEntities:
142 return this.#listPublicEntities();
143 case WorkerMessage.entitiesInRegion:
144 return this.#entitiesInRegion(message.regionX, message.regionY);
145 case WorkerMessage.inspect:
146 return publicEntityView(this.ecs, message.entityId);
147 case WorkerMessage.remoteCombatEngage:
148 return this.#remoteCombatEngage(message);
149 case WorkerMessage.applyRemoteMelee:
150 return this.#applyRemoteMelee(message);
151 case WorkerMessage.applyCombatHitXp:
152 return this.#applyCombatHitXp(message);
153 case WorkerMessage.spawnCorpseDrops:
154 return this.#spawnCorpseDrops(message);
155 case WorkerMessage.applyRespawn:
156 return this.#applyRespawn(message);
157 case WorkerMessage.clearCombat:
158 clearEngage(this.ecs, message.entityId);
159 for (const entity of this.ecs.query(Component.combat))
160 {
161 if (entity.combat.targetEntityId === message.targetEntityId)
162 { entity.combat.targetEntityId = null; }
163 }
164 return { ok: true };
165 default:
166 throw new Error(`Unknown worker message ${message.type}`);
167 }
168 }
169
170 ownsRegion (regionX, regionY)
171 {
172 return this.ownedRegions.has(regionKey(regionX, regionY));
173 }
174
175 requireOwnedEntity (sessionId, characterId)
176 {
177 return this.#requireOwnedEntity(sessionId, characterId);
178 }
179
180 chunkData (chunkX, chunkY)
181 {
182 return this.#chunkData(chunkX, chunkY);
183 }
184
185 occupied (tileX, tileY)
186 {
187 return this.#occupied(tileX, tileY);
188 }
189
190 #configure (message)
191 {
192 if (message.settings)
193 { this.settings = { ...this.settings, ...message.settings }; }
194 if (message.activeRevisionId != null)
195 { this.activeRevisionId = message.activeRevisionId; }
196 return { ok: true };
197 }
198
199 #assignRegion (message)
200 {
201 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
202 for (const chunk of message.chunks ?? [])
203 {
204 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
205 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
206 data: cloneChunkData(chunk.data),
207 simulating: false,
208 replica: false
209 });
210 }
211 return { ok: true };
212 }
213
214 #replaceRegionChunks (message)
215 {
216 for (const chunk of message.chunks ?? [])
217 {
218 const key = chunkKey(chunk.chunkX, chunk.chunkY);
219 const existing = this.chunks.get(key);
220 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
221 this.chunks.set(key, {
222 data: cloneChunkData(chunk.data),
223 simulating: existing?.simulating ?? false,
224 replica: existing?.replica ?? false
225 });
226 }
227 return { ok: true };
228 }
229
230 #dropRegion (message)
231 {
232 const dropped = [];
233 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
234 {
235 const components = record.payload?.components;
236 if (components?.creature && !components?.character && components?.health)
237 { components.health.current = components.health.max; }
238 dropped.push(record);
239 this.#destroyEntity(record.entityId);
240 }
241 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
242 for (const item of groundItems)
243 { removeGroundItem(this, item.groundItemId); }
244 for (const [key, chunk] of [...this.chunks.entries()])
245 {
246 const { chunkX, chunkY } = parseChunkKey(key);
247 if (chunk.replica)
248 { continue; }
249 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
250 {
251 clearOreRespawnsForChunk(this, chunkX, chunkY);
252 this.chunks.delete(key);
253 }
254 }
255 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
256 return { dropped, groundItems };
257 }
258
259 #setReplicas (message)
260 {
261 const keep = new Set();
262 for (const chunk of message.chunks ?? [])
263 {
264 const key = chunkKey(chunk.chunkX, chunk.chunkY);
265 keep.add(key);
266 const existing = this.chunks.get(key);
267 if (existing && !existing.replica)
268 { continue; }
269 this.chunks.set(key, {
270 data: cloneChunkData(chunk.data),
271 simulating: false,
272 replica: true
273 });
274 }
275 for (const [key, chunk] of [...this.chunks.entries()])
276 {
277 if (chunk.replica && !keep.has(key))
278 { this.chunks.delete(key); }
279 }
280 return { ok: true };
281 }
282
283 #setSimulatingChunks (message)
284 {
285 const simulating = new Set(message.chunkKeys ?? []);
286 for (const [key, chunk] of this.chunks)
287 {
288 if (chunk.replica)
289 {
290 chunk.simulating = false;
291 continue;
292 }
293 chunk.simulating = simulating.has(key);
294 }
295 return { ok: true };
296 }
297
298 #setGhosts (message)
299 {
300 this.ghosts.clear();
301 this.ghostOccupancy.clear();
302 for (const ghost of message.ghosts ?? [])
303 {
304 this.ghosts.set(ghost.entityId, ghost);
305 this.ghostOccupancy.set(tileKey(ghost.tileX, ghost.tileY), ghost.entityId);
306 }
307 return { ok: true };
308 }
309
310 #spawn (message)
311 {
312 const entityId = deserializeEntity(this.ecs, message);
313 const handle = this.ecs.handleOf(entityId);
314 const position = this.ecs.get(handle, Component.position);
315 if (!position)
316 {
317 this.ecs.destroy(handle);
318 throw new Error("Spawned entity is missing position.");
319 }
320 const flying = this.#isFlying(handle);
321 if (!flying)
322 {
323 const occupant = this.#occupied(position.tileX, position.tileY);
324 if (occupant && occupant !== entityId)
325 {
326 this.ecs.destroy(handle);
327 const error = new Error("That tile is occupied.");
328 error.userFacing = true;
329 throw error;
330 }
331 this.#occupy(entityId, position.tileX, position.tileY);
332 }
333 const creature = this.ecs.get(handle, Component.creature);
334 const def = creature ? mobDefinition(creature.mobTypeId) : null;
335 if (def?.freeFlight)
336 { ensureFlightComponent(this.ecs, handle, position, def); }
337 const character = this.ecs.get(handle, Component.character);
338 if (character?.characterId)
339 { this.characterEntities.set(character.characterId, entityId); }
340 return publicEntityView(this.ecs, entityId);
341 }
342
343 #despawn (entityId)
344 {
345 return this.#destroyEntity(entityId);
346 }
347
348 #despawnCharacter (characterId)
349 {
350 releaseShopBrowsersForCharacter(this, characterId);
351 const entityId = this.characterEntities.get(characterId);
352 if (!entityId)
353 { return null; }
354 return this.#destroyEntity(entityId);
355 }
356
357 #destroyEntity (entityId)
358 {
359 const handle = this.ecs.handleOf(entityId);
360 if (handle == null)
361 { return null; }
362 const view = publicEntityView(this.ecs, entityId);
363 const position = this.ecs.get(handle, Component.position);
364 const character = this.ecs.get(handle, Component.character);
365 if (position && !this.#isFlying(handle))
366 { this.#vacate(entityId, position.tileX, position.tileY); }
367 if (character?.characterId)
368 { this.characterEntities.delete(character.characterId); }
369 this.frozen.delete(entityId);
370 this.ecs.destroy(handle);
371 return view;
372 }
373
374 #command (message)
375 {
376 const { sessionId, command } = message;
377 switch (command.type)
378 {
379 case "move-to":
380 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
381 return { events: [] };
382 case "set-gait":
383 return this.#setGait(sessionId, command.characterId, command.gait);
384 case "attack":
385 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
386 case "cancel-attack":
387 return this.#cancelAttack(sessionId, command.characterId);
388 case "interact":
389 return this.#interact(sessionId, command.characterId, command.targetEntityId);
390 case "follow":
391 return this.#follow(sessionId, command.characterId, command.targetEntityId);
392 case "cancel-follow":
393 return this.#cancelFollow(sessionId, command.characterId);
394 default:
395 {
396 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
397 if (gather)
398 { return gather; }
399 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
400 if (craft)
401 { return craft; }
402 const shop = handleShopCommand(this, sessionId, command, message.now ?? Date.now());
403 if (shop)
404 { return shop; }
405 const alchemy = handleAlchemyCommand(this, sessionId, command);
406 if (alchemy)
407 { return alchemy; }
408 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
409 return result ?? { events: [] };
410 }
411 }
412 }
413
414 #spawnCorpseDrops (message)
415 {
416 const events = [];
417 for (const drop of message.drops ?? [])
418 {
419 const item = {
420 groundItemId: drop.groundItemId,
421 tileX: message.tileX,
422 tileY: message.tileY,
423 stack: { itemId: drop.itemId, quantity: 1 },
424 droppedAt: message.now,
425 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
426 source: "player-death",
427 droppedByCharacterId: message.characterId
428 };
429 addGroundItem(this, item);
430 events.push({
431 type: "ground-item-appear",
432 ...publicGroundItem(item),
433 stack: item.stack,
434 droppedAt: item.droppedAt,
435 source: item.source,
436 droppedByCharacterId: item.droppedByCharacterId,
437 expiresAt: item.expiresAt
438 });
439 }
440 return { events };
441 }
442
443 #applyRespawn (message)
444 {
445 const handle = this.ecs.handleOf(message.entityId);
446 if (handle == null || !this.ecs.has(handle, Component.dead))
447 { return { accepted: false }; }
448 const position = this.ecs.get(handle, Component.position);
449 const fromTileX = position.tileX;
450 const fromTileY = position.tileY;
451 const health = this.ecs.get(handle, Component.health);
452 const stamina = this.ecs.get(handle, Component.stamina);
453 if (health)
454 {
455 health.max = message.maxHealth;
456 health.current = message.maxHealth;
457 }
458 if (stamina)
459 {
460 stamina.max = message.maxStamina;
461 stamina.current = message.maxStamina;
462 }
463 else
464 { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); }
465 this.ecs.remove(handle, Component.dead);
466 clearEngage(this.ecs, message.entityId);
467 const path = this.ecs.get(handle, Component.path);
468 if (path)
469 { path.tiles = []; }
470 clearFollow(this.ecs, message.entityId);
471
472 const destRegionX = tileToRegion(message.tileX);
473 const destRegionY = tileToRegion(message.tileY);
474 if (!this.ownsRegion(destRegionX, destRegionY))
475 {
476 this.frozen.add(message.entityId);
477 return {
478 accepted: true,
479 transferRequest: {
480 entityId: message.entityId,
481 fromTileX,
482 fromTileY,
483 destTileX: message.tileX,
484 destTileY: message.tileY,
485 toRegionX: destRegionX,
486 toRegionY: destRegionY,
487 payload: serializeEntity(this.ecs, message.entityId)
488 }
489 };
490 }
491 const occupant = this.#occupied(message.tileX, message.tileY);
492 if (!this.isEnterable(message.tileX, message.tileY)
493 || (occupant && occupant !== message.entityId))
494 { return { accepted: false }; }
495 this.#vacate(message.entityId, fromTileX, fromTileY);
496 position.tileX = message.tileX;
497 position.tileY = message.tileY;
498 this.#occupy(message.entityId, position.tileX, position.tileY);
499 return {
500 accepted: true,
501 event: {
502 type: "entity-move",
503 entityId: message.entityId,
504 fromTileX,
505 fromTileY,
506 tileX: position.tileX,
507 tileY: position.tileY,
508 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
509 }
510 };
511 }
512
513 #inspectBag (entityId)
514 {
515 const handle = this.ecs.handleOf(entityId);
516 if (handle == null)
517 { return null; }
518 return bagView(this.ecs, handle);
519 }
520
521 #inspectSkills (entityId)
522 {
523 const handle = this.ecs.handleOf(entityId);
524 if (handle == null)
525 { return null; }
526 const skills = this.ecs.get(handle, Component.skills);
527 if (!skills?.xp)
528 { return null; }
529 return skills;
530 }
531
532 #inspectStamina (entityId)
533 {
534 const handle = this.ecs.handleOf(entityId);
535 if (handle == null)
536 { return null; }
537 const stamina = this.ecs.get(handle, Component.stamina);
538 const movement = this.ecs.get(handle, Component.movement);
539 if (!stamina)
540 { return null; }
541 return {
542 ...publicStaminaView(stamina),
543 gait: movement?.gait ?? GAIT.walk
544 };
545 }
546
547 #applyBag (entityId, bag)
548 {
549 const handle = this.ecs.handleOf(entityId);
550 if (handle == null)
551 { return null; }
552 return applyBagView(this.ecs, handle, bag);
553 }
554
555 #updateFlight (entityId, flightPatch, now = Date.now())
556 {
557 const handle = this.ecs.handleOf(entityId);
558 if (handle == null)
559 { return null; }
560 let flight = this.ecs.get(handle, Component.flight);
561 if (!flight)
562 { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); }
563 else
564 { Object.assign(flight, flightPatch); }
565 const position = this.ecs.get(handle, Component.position);
566 const movement = this.ecs.get(handle, Component.movement);
567 const fromTileX = position.tileX;
568 const fromTileY = position.tileY;
569 const tileX = Math.floor(flight.x);
570 const tileY = Math.floor(flight.y);
571 position.tileX = tileX;
572 position.tileY = tileY;
573 const destRegionX = tileToRegion(tileX);
574 const destRegionY = tileToRegion(tileY);
575 if (!this.ownsRegion(destRegionX, destRegionY))
576 {
577 this.frozen.add(entityId);
578 return {
579 transferRequest: {
580 type: "transfer-request",
581 entityId,
582 fromTileX,
583 fromTileY,
584 destTileX: tileX,
585 destTileY: tileY,
586 toRegionX: destRegionX,
587 toRegionY: destRegionY
588 }
589 };
590 }
591 const dt = flight.lastAt && now > flight.lastAt
592 ? Math.min(0.25, (now - flight.lastAt) / 1000)
593 : 1 / 20;
594 return {
595 event: {
596 type: "entity-move",
597 entityId,
598 fromTileX,
599 fromTileY,
600 tileX,
601 tileY,
602 worldX: flight.x,
603 worldY: flight.y,
604 gait: movement?.gait ?? "walk",
605 lerpMs: Math.max(50, Math.round(dt * 1000)),
606 freeFlight: true
607 }
608 };
609 }
610
611 #moveTo (sessionId, characterId, tileX, tileY)
612 {
613 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
614 if (this.frozen.has(entityId))
615 { return; }
616 clearEngage(this.ecs, entityId);
617 clearFollow(this.ecs, entityId);
618 cancelGather(this.ecs, handle);
619 const position = this.ecs.get(handle, Component.position);
620 const movement = this.ecs.get(handle, Component.movement);
621 let path = this.ecs.get(handle, Component.path);
622 if (!path)
623 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
624 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
625 path.tiles = findPath(
626 position.tileX,
627 position.tileY,
628 tileX,
629 tileY,
630 (x, y) => this.walkableFor(entityId, x, y),
631 bounds.minX,
632 bounds.minY,
633 bounds.maxX,
634 bounds.maxY
635 );
636 movement.walkCarry = 0;
637 }
638
639 #attack (sessionId, characterId, targetEntityId, now)
640 {
641 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
642 if (targetEntityId === entityId)
643 {
644 const error = new Error("Cannot attack yourself.");
645 error.userFacing = true;
646 throw error;
647 }
648 const target = resolveCombatTarget(this, targetEntityId);
649 if (!target)
650 {
651 const error = new Error("Target is not here.");
652 error.userFacing = true;
653 throw error;
654 }
655 if (target.health && target.health.current <= 0)
656 {
657 const error = new Error("That cannot be attacked.");
658 error.userFacing = true;
659 throw error;
660 }
661 if (!this.ecs.get(handle, Component.combat))
662 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
663 clearFollow(this.ecs, entityId);
664 cancelGather(this.ecs, handle);
665 // Engage only the attacker. Targets retaliate on the first resolved swing.
666 engageTarget(this.ecs, entityId, targetEntityId, now);
667 const path = this.ecs.get(handle, Component.path);
668 if (path)
669 { path.tiles = []; }
670 return { events: [] };
671 }
672
673 #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })
674 {
675 // Kept for cross-worker hooks; retaliation happens on swing resolution, not Attack click.
676 void attackerEntityId;
677 void targetEntityId;
678 void now;
679 return { events: [] };
680 }
681
682 #applyRemoteMelee (payload)
683 {
684 return applyRemoteMeleeSwing(this, payload);
685 }
686
687 #applyCombatHitXp ({ entityId, profile })
688 {
689 const handle = this.ecs.handleOf(entityId);
690 if (handle == null)
691 { return { events: [] }; }
692 const character = this.ecs.get(handle, Component.character);
693 if (!character)
694 { return { events: [] }; }
695 const xpAward = awardCombatHitXp(this.ecs, handle, profile);
696 if (!xpAward)
697 { return { events: [] }; }
698 return {
699 events: [{
700 type: "skills-updated",
701 entityId,
702 characterId: character.characterId,
703 skills: xpAward.view,
704 stored: xpAward.stored
705 }]
706 };
707 }
708
709 #cancelAttack (sessionId, characterId)
710 {
711 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
712 clearEngage(this.ecs, entityId);
713 return { events: [] };
714 }
715
716 #interact (sessionId, characterId, targetEntityId)
717 {
718 this.#requireOwnedEntity(sessionId, characterId);
719 const targetHandle = this.ecs.handleOf(targetEntityId);
720 if (targetHandle == null)
721 {
722 const error = new Error("Target is not here.");
723 error.userFacing = true;
724 throw error;
725 }
726 if (isUntargetable(this.ecs, targetHandle))
727 {
728 const error = new Error("Nothing to say.");
729 error.userFacing = true;
730 throw error;
731 }
732 const creature = this.ecs.get(targetHandle, Component.creature);
733 const def = creature ? mobDefinition(creature.mobTypeId) : null;
734 const shop = this.ecs.get(targetHandle, Component.shop);
735 if (shopHasInterface(shop))
736 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
737 if (!def?.talkable)
738 {
739 const error = new Error("They have nothing to say.");
740 error.userFacing = true;
741 throw error;
742 }
743 // Dialogue comes later; talkable NPCs without stock are a no-op for now.
744 return { events: [] };
745 }
746
747 #follow (sessionId, characterId, targetEntityId)
748 {
749 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
750 const targetHandle = this.ecs.handleOf(targetEntityId);
751 if (targetHandle == null)
752 {
753 const error = new Error("Target is not here.");
754 error.userFacing = true;
755 throw error;
756 }
757 if (targetEntityId === entityId)
758 {
759 const error = new Error("Cannot follow yourself.");
760 error.userFacing = true;
761 throw error;
762 }
763 if (!this.ecs.get(targetHandle, Component.position))
764 {
765 const error = new Error("That cannot be followed.");
766 error.userFacing = true;
767 throw error;
768 }
769 clearEngage(this.ecs, entityId);
770 setFollow(this.ecs, entityId, targetEntityId);
771 const path = this.ecs.get(handle, Component.path);
772 if (path)
773 { path.tiles = []; }
774 return { events: [] };
775 }
776
777 #cancelFollow (sessionId, characterId)
778 {
779 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
780 clearFollow(this.ecs, entityId);
781 return { events: [] };
782 }
783
784 #setGait (sessionId, characterId, gait)
785 {
786 if (gait !== GAIT.walk && gait !== GAIT.run)
787 {
788 const error = new Error("Gait must be walk or run.");
789 error.userFacing = true;
790 throw error;
791 }
792 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
793 const movement = this.ecs.get(handle, Component.movement);
794 const stamina = this.ecs.get(handle, Component.stamina);
795 if (gait === GAIT.run && !(Number(stamina?.current) > 0))
796 {
797 const error = new Error("You are too exhausted to run.");
798 error.userFacing = true;
799 throw error;
800 }
801 movement.gait = gait;
802 const character = this.ecs.get(handle, Component.character);
803 return {
804 events: character
805 ? [this.#staminaEvent(handle, character.characterId, movement.gait)]
806 : []
807 };
808 }
809
810 #staminaEvent (handle, characterId, gait = null)
811 {
812 const stamina = this.ecs.get(handle, Component.stamina);
813 const movement = this.ecs.get(handle, Component.movement);
814 return {
815 type: "stamina",
816 characterId,
817 ...publicStaminaView(stamina),
818 gait: gait ?? movement?.gait ?? GAIT.walk
819 };
820 }
821
822 #consumeRunStamina (handle, events)
823 {
824 const character = this.ecs.get(handle, Component.character);
825 if (!character)
826 { return; }
827 let stamina = this.ecs.get(handle, Component.stamina);
828 if (!stamina)
829 {
830 stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 });
831 }
832 const skills = this.ecs.get(handle, Component.skills);
833 syncPlayerStamina(this.ecs, handle);
834 const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond);
835 stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost);
836 stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost;
837 let skillsChanged = false;
838 while (stamina.xpDebt >= 1 && skills?.xp)
839 {
840 stamina.xpDebt -= 1;
841 if (addSkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT))
842 {
843 skillsChanged = true;
844 syncPlayerStamina(this.ecs, handle);
845 }
846 }
847 const movement = this.ecs.get(handle, Component.movement);
848 if (stamina.current <= 0 && movement)
849 {
850 stamina.current = 0;
851 movement.gait = GAIT.walk;
852 }
853 events.push(this.#staminaEvent(handle, character.characterId));
854 if (skillsChanged)
855 {
856 events.push({
857 type: "skills-updated",
858 characterId: character.characterId,
859 skills: publicSkillsView(skills),
860 stored: storedSkillXp(skills)
861 });
862 }
863 }
864
865 #regenStamina (dt, events)
866 {
867 if (!(dt > 0))
868 { return; }
869 for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement))
870 {
871 const { handle, character, stamina, movement } = entity;
872 if (this.ecs.has(handle, Component.dead))
873 { continue; }
874 if (movement.gait === GAIT.run)
875 { continue; }
876 syncPlayerStamina(this.ecs, handle);
877 const before = Number(stamina.current) || 0;
878 if (before >= stamina.max)
879 { continue; }
880 stamina.current = Math.min(stamina.max, before + dt * STAMINA_REGEN_PER_SECOND);
881 const after = Number(stamina.current) || 0;
882 // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
883 if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
884 { events.push(this.#staminaEvent(handle, character.characterId)); }
885 }
886 }
887
888 #requireOwnedEntity (sessionId, characterId)
889 {
890 const entityId = this.characterEntities.get(characterId);
891 if (!entityId)
892 {
893 const error = new Error("Character is not in the world.");
894 error.userFacing = true;
895 throw error;
896 }
897 const handle = this.ecs.handleOf(entityId);
898 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
899 if (!identity || identity.sessionId !== sessionId)
900 {
901 const error = new Error("Character is not in the world.");
902 error.userFacing = true;
903 throw error;
904 }
905 if (this.ecs.has(handle, Component.dead))
906 {
907 const error = new Error("You are dead.");
908 error.userFacing = true;
909 throw error;
910 }
911 return { handle, entityId };
912 }
913
914 #stepSystems (now = Date.now(), dt = 1 / 20)
915 {
916 const events = [];
917 const transferRequests = [];
918 this.#regenStamina(dt, events);
919 const flight = stepFreeFlight(this, now);
920 for (const event of flight)
921 {
922 if (event.type === "transfer-request")
923 {
924 const payload = serializeEntity(this.ecs, event.entityId);
925 transferRequests.push({
926 entityId: event.entityId,
927 fromTileX: event.fromTileX,
928 fromTileY: event.fromTileY,
929 destTileX: event.destTileX,
930 destTileY: event.destTileY,
931 toRegionX: event.toRegionX,
932 toRegionY: event.toRegionY,
933 payload
934 });
935 continue;
936 }
937 events.push(event);
938 }
939 stepAggression(this, now);
940 events.push(...stepCombat(this, now));
941 stepFollow(this);
942 const gather = stepGather(this, now);
943 events.push(...gather.events);
944 for (const entry of gather.privates ?? [])
945 {
946 events.push({
947 type: "inventory",
948 characterId: entry.characterId,
949 ...entry.bag
950 });
951 }
952 const craft = stepCrafting(this, now);
953 events.push(...craft.events);
954 for (const entry of craft.privates ?? [])
955 {
956 events.push({
957 type: "inventory",
958 characterId: entry.characterId,
959 ...entry.bag
960 });
961 }
962 return { events, transferRequests };
963 }
964
965 #stepMovement (now = Date.now())
966 {
967 const events = expireGroundItems(this, now);
968 const transferRequests = [];
969 events.push(...pruneShopBrowsers(this));
970 this.#queueAmbientWander();
971 this.#queueSpawnerWander();
972 for (const entity of this.ecs.query(Component.position, Component.movement))
973 {
974 const { handle, entityId, position, movement } = entity;
975 if (this.ecs.has(handle, Component.dead))
976 { continue; }
977 if (this.ecs.has(handle, Component.flight))
978 { continue; }
979 const path = this.ecs.get(handle, Component.path);
980 const tiles = path?.tiles;
981 if (this.frozen.has(entityId) || !tiles?.length)
982 {
983 if (path)
984 { path.stuckSince = null; }
985 continue;
986 }
987 if (!this.chunkIsSimulating(position.tileX, position.tileY))
988 { continue; }
989
990 this.#repathIfNavigationStuck(entityId, position, movement, path, now);
991
992 const stamina = this.ecs.get(handle, Component.stamina);
993 if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))
994 { movement.gait = GAIT.walk; }
995 const isWalk = movement.gait !== GAIT.run;
996 if (isWalk)
997 {
998 movement.walkCarry = (movement.walkCarry + 1) % 2;
999 if (movement.walkCarry !== 0)
1000 { continue; }
1001 }
1002
1003 const next = tiles[0];
1004 if (!next)
1005 { continue; }
1006 const destRegionX = tileToRegion(next.x);
1007 const destRegionY = tileToRegion(next.y);
1008 if (!this.ownsRegion(destRegionX, destRegionY))
1009 {
1010 this.frozen.add(entityId);
1011 transferRequests.push({
1012 entityId,
1013 fromTileX: position.tileX,
1014 fromTileY: position.tileY,
1015 destTileX: next.x,
1016 destTileY: next.y,
1017 toRegionX: destRegionX,
1018 toRegionY: destRegionY,
1019 payload: serializeEntity(this.ecs, entityId)
1020 });
1021 continue;
1022 }
1023
1024 if (!this.walkableFor(entityId, next.x, next.y))
1025 {
1026 const combat = this.ecs.get(handle, Component.combat);
1027 if (combat?.targetEntityId != null)
1028 {
1029 const targetHandle = this.ecs.handleOf(combat.targetEntityId);
1030 const targetPos = targetHandle != null
1031 ? this.ecs.get(targetHandle, Component.position)
1032 : null;
1033 const blockedByTarget = targetPos
1034 && next.x === targetPos.tileX
1035 && next.y === targetPos.tileY;
1036 if (!blockedByTarget)
1037 { path.tiles = []; }
1038 }
1039 continue;
1040 }
1041
1042 const fromTileX = position.tileX;
1043 const fromTileY = position.tileY;
1044 const flying = this.#isFlying(handle);
1045 if (!flying)
1046 { this.#vacate(entityId, fromTileX, fromTileY); }
1047 position.tileX = next.x;
1048 position.tileY = next.y;
1049 tiles.shift();
1050 if (!flying)
1051 { this.#occupy(entityId, position.tileX, position.tileY); }
1052 path.stuckSince = now;
1053 path.stuckTileX = position.tileX;
1054 path.stuckTileY = position.tileY;
1055 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
1056 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
1057 if (!isWalk)
1058 { this.#consumeRunStamina(handle, events); }
1059 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
1060 }
1061 return { events, transferRequests };
1062 }
1063
1064 /**
1065 * If we still have a destination but have not left this tile for NAV_STUCK_MS,
1066 * recompute A* to the same goal (around whoever is blocking the old route).
1067 */
1068 #repathIfNavigationStuck (entityId, position, movement, path, now)
1069 {
1070 if (!path?.tiles?.length)
1071 {
1072 path.stuckSince = null;
1073 return;
1074 }
1075 if (
1076 path.stuckSince == null
1077 || path.stuckTileX !== position.tileX
1078 || path.stuckTileY !== position.tileY
1079 )
1080 {
1081 path.stuckSince = now;
1082 path.stuckTileX = position.tileX;
1083 path.stuckTileY = position.tileY;
1084 return;
1085 }
1086 if (now - path.stuckSince < NAV_STUCK_MS)
1087 { return; }
1088
1089 const goal = path.tiles[path.tiles.length - 1];
1090 if (!goal || (goal.x === position.tileX && goal.y === position.tileY))
1091 {
1092 path.tiles = [];
1093 path.stuckSince = null;
1094 return;
1095 }
1096 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1097 path.tiles = findPath(
1098 position.tileX,
1099 position.tileY,
1100 goal.x,
1101 goal.y,
1102 (x, y) => this.walkableFor(entityId, x, y),
1103 bounds.minX,
1104 bounds.minY,
1105 bounds.maxX,
1106 bounds.maxY
1107 );
1108 path.stuckSince = now;
1109 path.stuckTileX = position.tileX;
1110 path.stuckTileY = position.tileY;
1111 if (movement)
1112 { movement.walkCarry = 0; }
1113 }
1114
1115 #queueAmbientWander ()
1116 {
1117 for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
1118 {
1119 const def = mobDefinition(entity.creature.mobTypeId);
1120 if (!def?.ambient || def.freeFlight)
1121 { continue; }
1122 if (this.ecs.get(entity.handle, Component.spawnOrigin))
1123 { continue; }
1124 const path = this.ecs.get(entity.handle, Component.path);
1125 if (!path)
1126 { continue; }
1127 if (path.tiles?.length)
1128 { continue; }
1129 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
1130 { continue; }
1131 if (Math.random() > 0.35)
1132 { continue; }
1133 const dirs = [
1134 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
1135 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
1136 ];
1137 const dir = dirs[Math.floor(Math.random() * dirs.length)];
1138 const nextX = entity.position.tileX + dir.x;
1139 const nextY = entity.position.tileY + dir.y;
1140 if (!this.walkableFor(entity.entityId, nextX, nextY))
1141 { continue; }
1142 path.tiles = [{ x: nextX, y: nextY }];
1143 }
1144 }
1145
1146 /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner. Combat chase is unrestricted. */
1147 #queueSpawnerWander ()
1148 {
1149 for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin))
1150 {
1151 const combat = this.ecs.get(entity.handle, Component.combat);
1152 if (combat?.targetEntityId != null)
1153 { continue; }
1154 const follow = this.ecs.get(entity.handle, Component.follow);
1155 if (follow?.targetEntityId != null)
1156 { continue; }
1157 const shop = this.ecs.get(entity.handle, Component.shop);
1158 if (shopHasActiveBrowsers(shop))
1159 { continue; }
1160 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1161 if (def?.freeFlight)
1162 { continue; }
1163 const path = this.ecs.get(entity.handle, Component.path);
1164 if (!path || path.tiles?.length)
1165 { continue; }
1166 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
1167 { continue; }
1168 if (Math.random() > 0.4)
1169 { continue; }
1170
1171 const origin = entity.spawnOrigin;
1172 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1173 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1174 const range = Math.max(0, origin.wanderRangeTiles | 0);
1175 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
1176 if (!goal)
1177 { continue; }
1178 if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY)
1179 { continue; }
1180 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1181 const tiles = findPath(
1182 entity.position.tileX,
1183 entity.position.tileY,
1184 goal.tileX,
1185 goal.tileY,
1186 (x, y) => this.walkableFor(entity.entityId, x, y),
1187 bounds.minX,
1188 bounds.minY,
1189 bounds.maxX,
1190 bounds.maxY
1191 );
1192 if (!tiles?.length)
1193 { continue; }
1194 path.tiles = tiles;
1195 }
1196 }
1197
1198 #applyTransfer (message)
1199 {
1200 const payload = message.payload;
1201 const entityId = payload.entityId;
1202 if (this.ecs.hasEntity(entityId))
1203 { return { accepted: false, reason: "already-present" }; }
1204
1205 const position = payload.components?.position;
1206 const destTileX = message.destTileX ?? position?.tileX;
1207 const destTileY = message.destTileY ?? position?.tileY;
1208 if (destTileX == null || destTileY == null)
1209 { return { accepted: false, reason: "missing-destination" }; }
1210 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
1211 { return { accepted: false, reason: "not-owner" }; }
1212
1213 const creature = payload.components?.creature;
1214 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
1215 if (flying)
1216 {
1217 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY));
1218 if (!data?.open)
1219 { return { accepted: false, reason: "blocked" }; }
1220 }
1221 else if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
1222 { return { accepted: false, reason: "blocked" }; }
1223
1224 deserializeEntity(this.ecs, payload);
1225 const handle = this.ecs.handleOf(entityId);
1226 const livePosition = this.ecs.get(handle, Component.position);
1227 const path = this.ecs.get(handle, Component.path);
1228 livePosition.tileX = destTileX;
1229 livePosition.tileY = destTileY;
1230 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
1231 { path.tiles.shift(); }
1232 if (!flying)
1233 { this.#occupy(entityId, destTileX, destTileY); }
1234 const character = this.ecs.get(handle, Component.character);
1235 if (character?.characterId)
1236 { this.characterEntities.set(character.characterId, entityId); }
1237 this.frozen.delete(entityId);
1238 return {
1239 accepted: true,
1240 entity: publicEntityView(this.ecs, entityId)
1241 };
1242 }
1243
1244 #commitTransfer (entityId)
1245 {
1246 if (!this.ecs.hasEntity(entityId))
1247 { return null; }
1248 return this.#destroyEntity(entityId);
1249 }
1250
1251 #abortTransfer (entityId)
1252 {
1253 this.frozen.delete(entityId);
1254 return publicEntityView(this.ecs, entityId);
1255 }
1256
1257 #listLoaders ()
1258 {
1259 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
1260 entityId: entity.entityId,
1261 tileX: entity.position.tileX,
1262 tileY: entity.position.tileY,
1263 chunkLoader: { ...entity.chunkLoader }
1264 }));
1265 }
1266
1267 #listPublicEntities ()
1268 {
1269 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
1270 }
1271
1272 #entitiesInRegion (regionX, regionY)
1273 {
1274 const records = [];
1275 for (const entity of this.ecs.query(Component.position))
1276 {
1277 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
1278 { continue; }
1279 records.push({
1280 ...publicEntityView(this.ecs, entity.entityId),
1281 persistent: this.ecs.has(entity.handle, Component.persistent),
1282 payload: serializeEntity(this.ecs, entity.entityId)
1283 });
1284 }
1285 return records;
1286 }
1287
1288 #chunkSnapshot (chunkX, chunkY)
1289 {
1290 const data = this.#chunkData(chunkX, chunkY);
1291 const entities = [];
1292 for (const entity of this.ecs.query(Component.position, Component.appearance))
1293 {
1294 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
1295 { continue; }
1296 entities.push(publicEntityView(this.ecs, entity.entityId));
1297 }
1298 return {
1299 chunkX,
1300 chunkY,
1301 open: data.open,
1302 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
1303 grounds: data.grounds,
1304 blocks: data.blocks,
1305 light: data.light,
1306 entities,
1307 groundItems: groundItemsInChunk(this, chunkX, chunkY)
1308 };
1309 }
1310
1311 #moveEvent (entityId, fromTileX, fromTileY)
1312 {
1313 const view = publicEntityView(this.ecs, entityId);
1314 return {
1315 type: "entity-move",
1316 entityId,
1317 fromTileX,
1318 fromTileY,
1319 tileX: view.tileX,
1320 tileY: view.tileY,
1321 worldX: view.worldX,
1322 worldY: view.worldY,
1323 gait: view.gait,
1324 freeFlight: !!view.freeFlight
1325 };
1326 }
1327
1328 chunkIsSimulating (tileX, tileY)
1329 {
1330 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
1331 return !!chunk && !chunk.replica && chunk.simulating;
1332 }
1333
1334 chunkData (chunkX, chunkY)
1335 {
1336 return this.#chunkData(chunkX, chunkY);
1337 }
1338
1339 walkableFor (entityId, tileX, tileY)
1340 {
1341 const handle = this.ecs.handleOf(entityId);
1342 if (this.#isFlying(handle))
1343 {
1344 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1345 return !!data?.open;
1346 }
1347 if (!this.isEnterable(tileX, tileY))
1348 { return false; }
1349 const occupant = this.#occupied(tileX, tileY);
1350 return !occupant || occupant === entityId;
1351 }
1352
1353 destroyEntity (entityId)
1354 {
1355 return this.#destroyEntity(entityId);
1356 }
1357
1358 occupied (tileX, tileY)
1359 {
1360 return this.#occupied(tileX, tileY);
1361 }
1362
1363 #chunkIsSimulating (tileX, tileY)
1364 {
1365 return this.chunkIsSimulating(tileX, tileY);
1366 }
1367
1368 #chunkData (chunkX, chunkY)
1369 {
1370 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
1371 if (loaded)
1372 { return loaded.data; }
1373 return createEmptyChunkData(this.settings.defaultGroundTypeId);
1374 }
1375
1376 isEnterable (tileX, tileY)
1377 {
1378 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1379 if (!data.open)
1380 { return false; }
1381 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1382 }
1383
1384 #walkableFor (entityId, tileX, tileY)
1385 {
1386 return this.walkableFor(entityId, tileX, tileY);
1387 }
1388
1389 #isFlying (handle)
1390 {
1391 if (handle == null)
1392 { return false; }
1393 const creature = this.ecs.get(handle, Component.creature);
1394 return !!mobDefinition(creature?.mobTypeId)?.flying;
1395 }
1396
1397 #occupy (entityId, tileX, tileY)
1398 {
1399 this.occupancy.set(tileKey(tileX, tileY), entityId);
1400 }
1401
1402 #vacate (entityId, tileX, tileY)
1403 {
1404 const key = tileKey(tileX, tileY);
1405 if (this.occupancy.get(key) === entityId)
1406 { this.occupancy.delete(key); }
1407 }
1408
1409 #occupied (tileX, tileY)
1410 {
1411 return this.occupancy.get(tileKey(tileX, tileY))
1412 ?? this.ghostOccupancy.get(tileKey(tileX, tileY))
1413 ?? null;
1414 }
1415}
1416
1417function pickWanderGoalInRange (world, entityId, originX, originY, range)
1418{
1419 const radius = Math.max(0, range | 0);
1420 for (let attempt = 0; attempt < 24; attempt++)
1421 {
1422 const tileX = originX + randInt(-radius, radius);
1423 const tileY = originY + randInt(-radius, radius);
1424 if (!world.walkableFor(entityId, tileX, tileY))
1425 { continue; }
1426 return { tileX, tileY };
1427 }
1428 return null;
1429}
1430
1431function randInt (min, max)
1432{
1433 return min + Math.floor(Math.random() * (max - min + 1));
1434}
1435
1436export function replicaNeededForOwnedChunks (ownedChunkKeys)
1437{
1438 const needed = new Set();
1439 for (const key of ownedChunkKeys)
1440 {
1441 const { chunkX, chunkY } = parseChunkKey(key);
1442 for (let dy = -1; dy <= 1; dy++)
1443 {
1444 for (let dx = -1; dx <= 1; dx++)
1445 {
1446 if (dx === 0 && dy === 0)
1447 { continue; }
1448 needed.add(chunkKey(chunkX + dx, chunkY + dy));
1449 }
1450 }
1451 }
1452 return needed;
1453}