BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

workerWorld.js 62.0 KiB Download Raw
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js";
2import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
3import {
4 chunkKey,
5 chunkToRegion,
6 parseChunkKey,
7 regionKey,
8 tileKey,
9 tileToChunk,
10 tileToLocal,
11 tileToRegion
12} from "../world/coordinates.js";
13import { cloneChunkData, createEmptyChunkData, isChunkTilePassable, isChunkTileClearForRangedAttacks } from "../world/chunkData.js";
14import { closedNeighborEdges } from "../world/chunkFlags.js";
15import { EcsWorld } from "../ecs/world.js";
16import { Component } from "../ecs/components.js";
17import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js";
18import { chunkBoundsAround, findPath } from "../navigation/astar.js";
19import { WorkerMessage } from "./protocol.js";
20import { collectSpawnRequests } from "./spawners.js";
21import { mobDefinition } from "../../../shared/definitions/mobs.js";
22import {
23 bagView,
24 applyBagView,
25 addGroundItem,
26 expireGroundItems,
27 groundItemsInChunk,
28 groundItemsInRegion,
29 handleItemCommand,
30 removeGroundItem,
31 publicGroundItem,
32 setGroundItemsForRegion
33} from "../items/bags.js";
34import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights } from "../spells/service.js";
35import { publicSpellsView } from "../../../shared/spells/state.js";
36import {
37 handleGatherCommand,
38 stepGather,
39 cancelGather,
40 clearOreRespawnsForChunk,
41 clearTreeRespawnsForChunk,
42 clearPlantRespawnsForChunk
43} from "../gathering/service.js";
44import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
45import { handleAlchemyCommand } from "../alchemy/service.js";
46import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
47import {
48 applyRemoteMeleeSwing,
49 applyRemoteRangedShot,
50 attackProfileOf,
51 clearEngage,
52 engageTarget,
53 ensureMobCombat,
54 isUntargetable,
55 queueMeleeApproach,
56 queueStandInRangeApproach,
57 resolveCombatTarget,
58 stepAggression,
59 stepCombat,
60 chebyshev
61} from "../combat/service.js";
62import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
63import { SkillId } from "../../../shared/definitions/skills.js";
64import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
65import {
66 STAMINA_REGEN_PER_SECOND,
67 STAMINA_XP_PER_POINT_SPENT,
68 staminaCostPerRunStep,
69 publicStaminaView
70} from "../../../shared/stamina/rules.js";
71import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
72import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
73import { stepStatusEffects } from "../statusEffects/service.js";
74
75export class WorkerWorld
76{
77 constructor (workerId)
78 {
79 this.workerId = workerId;
80 this.ecs = new EcsWorld();
81 this.chunks = new Map();
82 this.ownedRegions = new Set();
83 this.occupancy = new Map();
84 this.ghosts = new Map();
85 this.ghostOccupancy = new Map();
86 this.characterEntities = new Map();
87 this.frozen = new Set();
88 this.groundItems = new Map();
89 this.groundByTile = new Map();
90 this.oreRespawns = new Map();
91 this.treeRespawns = new Map();
92 this.pendingSpellImpacts = [];
93 this.settings = { ...DEFAULT_WORLD_SETTINGS };
94 this.activeRevisionId = 1;
95 }
96
97 handle (message)
98 {
99 switch (message.type)
100 {
101 case WorkerMessage.configure:
102 return this.#configure(message);
103 case WorkerMessage.assignRegion:
104 return this.#assignRegion(message);
105 case WorkerMessage.dropRegion:
106 return this.#dropRegion(message);
107 case WorkerMessage.replaceRegionChunks:
108 return this.#replaceRegionChunks(message);
109 case WorkerMessage.setReplicas:
110 return this.#setReplicas(message);
111 case WorkerMessage.setSimulatingChunks:
112 return this.#setSimulatingChunks(message);
113 case WorkerMessage.setGhosts:
114 return this.#setGhosts(message);
115 case WorkerMessage.spawn:
116 return this.#spawn(message);
117 case WorkerMessage.despawn:
118 return this.#despawn(message.entityId);
119 case WorkerMessage.despawnCharacter:
120 return this.#despawnCharacter(message.characterId);
121 case WorkerMessage.reattachSession:
122 return this.#reattachSession(message.characterId, message.sessionId);
123 case WorkerMessage.command:
124 return this.#command(message);
125 case WorkerMessage.stepMovement:
126 return this.#stepMovement(message.now);
127 case WorkerMessage.stepSystems:
128 return this.#stepSystems(message.now, message.dt ?? (1 / 20));
129 case WorkerMessage.stepSpawners:
130 return { spawnRequests: collectSpawnRequests(this) };
131 case WorkerMessage.setGroundItems:
132 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
133 return { ok: true };
134 case WorkerMessage.inspectBag:
135 return this.#inspectBag(message.entityId);
136 case WorkerMessage.inspectSkills:
137 return this.#inspectSkills(message.entityId);
138 case WorkerMessage.inspectSpells:
139 return this.#inspectSpells(message.entityId);
140 case WorkerMessage.inspectStamina:
141 return this.#inspectStamina(message.entityId);
142 case WorkerMessage.applyBag:
143 return this.#applyBag(message.entityId, message.bag);
144 case WorkerMessage.applyAppearance:
145 return this.#applyAppearance(message.entityId, message.appearance);
146 case WorkerMessage.engageTarget:
147 return this.#engageTargetMessage(message);
148 case WorkerMessage.listTownGuardsNear:
149 return this.#listTownGuardsNear(message);
150 case WorkerMessage.updateFlight:
151 return this.#updateFlight(message.entityId, message.flight, message.now);
152 case WorkerMessage.chunkIsSimulating:
153 return this.chunkIsSimulating(message.tileX, message.tileY, message.dimensionId);
154 case WorkerMessage.applyTransfer:
155 return this.#applyTransfer(message);
156 case WorkerMessage.commitTransfer:
157 return this.#commitTransfer(message.entityId);
158 case WorkerMessage.abortTransfer:
159 return this.#abortTransfer(message.entityId);
160 case WorkerMessage.snapshotChunk:
161 return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly, message.dimensionId);
162 case WorkerMessage.listLoaders:
163 return this.#listLoaders();
164 case WorkerMessage.listPublicEntities:
165 return this.#listPublicEntities();
166 case WorkerMessage.entitiesInRegion:
167 return this.#entitiesInRegion(message.regionX, message.regionY, message.dimensionId);
168 case WorkerMessage.inspect:
169 return publicEntityView(this.ecs, message.entityId);
170 case WorkerMessage.remoteCombatEngage:
171 return this.#remoteCombatEngage(message);
172 case WorkerMessage.applyRemoteMelee:
173 return this.#applyRemoteMelee(message);
174 case WorkerMessage.applyRemoteRanged:
175 return this.#applyRemoteRanged(message);
176 case WorkerMessage.applyCombatHitXp:
177 return this.#applyCombatHitXp(message);
178 case WorkerMessage.spawnCorpseDrops:
179 return this.#spawnCorpseDrops(message);
180 case WorkerMessage.applyRespawn:
181 return this.#applyRespawn(message);
182 case WorkerMessage.relocateEntity:
183 return this.#relocateEntity(message);
184 case WorkerMessage.clearCombat:
185 clearEngage(this.ecs, message.entityId);
186 for (const entity of this.ecs.query(Component.combat))
187 {
188 if (entity.combat.targetEntityId === message.targetEntityId)
189 { entity.combat.targetEntityId = null; }
190 }
191 return { ok: true };
192 case WorkerMessage.setItemLastSales:
193 {
194 this.itemLastSales = new Map();
195 for (const [key, sale] of Object.entries(message.sales ?? {}))
196 { this.itemLastSales.set(Number(key), sale); }
197 return { ok: true };
198 }
199 case WorkerMessage.stationExchangeClerk:
200 return this.#stationExchangeClerk(message);
201 case WorkerMessage.releaseExchangeClerk:
202 return this.#releaseExchangeClerk(message);
203 case WorkerMessage.pinDialogue:
204 return this.#pinDialogue(message.entityId, message.characterId);
205 case WorkerMessage.unpinDialogue:
206 return this.#unpinDialogue(message.entityId, message.characterId);
207 default:
208 throw new Error(`Unknown worker message ${message.type}`);
209 }
210 }
211
212 ownsRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
213 {
214 return this.ownedRegions.has(regionKey(regionX, regionY, dimensionId));
215 }
216
217 requireOwnedEntity (sessionId, characterId)
218 {
219 return this.#requireOwnedEntity(sessionId, characterId);
220 }
221
222 chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
223 {
224 return this.#chunkData(chunkX, chunkY, dimensionId);
225 }
226
227 #configure (message)
228 {
229 if (message.settings)
230 { this.settings = { ...this.settings, ...message.settings }; }
231 if (message.activeRevisionId != null)
232 { this.activeRevisionId = message.activeRevisionId; }
233 return { ok: true };
234 }
235
236 #assignRegion (message)
237 {
238 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
239 this.ownedRegions.add(regionKey(message.regionX, message.regionY, dim));
240 for (const chunk of message.chunks ?? [])
241 {
242 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
243 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
244 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
245 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
246 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY, chunkDim), {
247 data: cloneChunkData(chunk.data),
248 simulating: false,
249 replica: false,
250 dimensionId: chunkDim
251 });
252 }
253 return { ok: true };
254 }
255
256 #replaceRegionChunks (message)
257 {
258 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
259 for (const chunk of message.chunks ?? [])
260 {
261 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
262 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
263 const existing = this.chunks.get(key);
264 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
265 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
266 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
267 this.chunks.set(key, {
268 data: cloneChunkData(chunk.data),
269 simulating: existing?.simulating ?? false,
270 replica: existing?.replica ?? false,
271 dimensionId: chunkDim
272 });
273 }
274 return { ok: true };
275 }
276
277 #dropRegion (message)
278 {
279 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
280 const dropped = [];
281 for (const record of this.#entitiesInRegion(message.regionX, message.regionY, dim))
282 {
283 const components = record.payload?.components;
284 if (components?.creature && !components?.character && components?.health)
285 { components.health.current = components.health.max; }
286 dropped.push(record);
287 this.#destroyEntity(record.entityId);
288 }
289 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
290 for (const item of groundItems)
291 { removeGroundItem(this, item.groundItemId); }
292 for (const [key, chunk] of [...this.chunks.entries()])
293 {
294 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
295 if (chunk.replica)
296 { continue; }
297 if (dimensionId !== dim)
298 { continue; }
299 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
300 {
301 clearOreRespawnsForChunk(this, chunkX, chunkY);
302 clearTreeRespawnsForChunk(this, chunkX, chunkY);
303 clearPlantRespawnsForChunk(this, chunkX, chunkY);
304 this.chunks.delete(key);
305 }
306 }
307 this.ownedRegions.delete(regionKey(message.regionX, message.regionY, dim));
308 return { dropped, groundItems };
309 }
310
311 #setReplicas (message)
312 {
313 const keep = new Set();
314 for (const chunk of message.chunks ?? [])
315 {
316 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? OVERWORLD_ID);
317 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
318 keep.add(key);
319 const existing = this.chunks.get(key);
320 if (existing && !existing.replica)
321 { continue; }
322 this.chunks.set(key, {
323 data: cloneChunkData(chunk.data),
324 simulating: false,
325 replica: true,
326 dimensionId: chunkDim
327 });
328 }
329 for (const [key, chunk] of [...this.chunks.entries()])
330 {
331 if (chunk.replica && !keep.has(key))
332 { this.chunks.delete(key); }
333 }
334 return { ok: true };
335 }
336
337 #setSimulatingChunks (message)
338 {
339 const simulating = new Set(message.chunkKeys ?? []);
340 for (const [key, chunk] of this.chunks)
341 {
342 if (chunk.replica)
343 {
344 chunk.simulating = false;
345 continue;
346 }
347 chunk.simulating = simulating.has(key);
348 }
349 return { ok: true };
350 }
351
352 #setGhosts (message)
353 {
354 this.ghosts.clear();
355 this.ghostOccupancy.clear();
356 for (const ghost of message.ghosts ?? [])
357 {
358 this.ghosts.set(ghost.entityId, ghost);
359 const dim = normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID);
360 const key = tileKey(ghost.tileX, ghost.tileY, dim);
361 let set = this.ghostOccupancy.get(key);
362 if (!set)
363 {
364 set = new Set();
365 this.ghostOccupancy.set(key, set);
366 }
367 set.add(ghost.entityId);
368 }
369 return { ok: true };
370 }
371
372 #spawn (message)
373 {
374 const entityId = deserializeEntity(this.ecs, message);
375 const handle = this.ecs.handleOf(entityId);
376 const position = this.ecs.get(handle, Component.position);
377 if (!position)
378 {
379 this.ecs.destroy(handle);
380 throw new Error("Spawned entity is missing position.");
381 }
382 const flying = this.#isFlying(handle);
383 if (!flying)
384 {
385 if (this.#hasOtherOccupant(entityId, position.tileX, position.tileY))
386 {
387 this.ecs.destroy(handle);
388 const error = new Error("That tile is occupied.");
389 error.userFacing = true;
390 throw error;
391 }
392 this.#occupy(entityId, position.tileX, position.tileY);
393 }
394 const creature = this.ecs.get(handle, Component.creature);
395 const def = creature ? mobDefinition(creature.mobTypeId) : null;
396 if (def?.freeFlight)
397 { ensureFlightComponent(this.ecs, handle, position, def); }
398 const character = this.ecs.get(handle, Component.character);
399 if (character?.characterId)
400 { this.characterEntities.set(character.characterId, entityId); }
401 return publicEntityView(this.ecs, entityId);
402 }
403
404 #despawn (entityId)
405 {
406 return this.#destroyEntity(entityId);
407 }
408
409 #despawnCharacter (characterId)
410 {
411 releaseShopBrowsersForCharacter(this, characterId);
412 const entityId = this.characterEntities.get(characterId);
413 if (!entityId)
414 { return null; }
415 return this.#destroyEntity(entityId);
416 }
417
418 #reattachSession (characterId, sessionId)
419 {
420 const entityId = this.characterEntities.get(characterId | 0);
421 if (!entityId)
422 { return { ok: false }; }
423 const handle = this.ecs.handleOf(entityId);
424 if (handle == null)
425 { return { ok: false }; }
426 this.ecs.add(handle, Component.networkIdentity, { sessionId });
427 return { ok: true, entityId };
428 }
429
430 #destroyEntity (entityId)
431 {
432 const handle = this.ecs.handleOf(entityId);
433 if (handle == null)
434 { return null; }
435 const view = publicEntityView(this.ecs, entityId);
436 const position = this.ecs.get(handle, Component.position);
437 const character = this.ecs.get(handle, Component.character);
438 if (position && !this.#isFlying(handle))
439 { this.#vacate(entityId, position.tileX, position.tileY); }
440 if (character?.characterId)
441 { this.characterEntities.delete(character.characterId); }
442 this.frozen.delete(entityId);
443 this.ecs.destroy(handle);
444 return view;
445 }
446
447 #command (message)
448 {
449 const { sessionId, command } = message;
450 switch (command.type)
451 {
452 case "move-to":
453 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
454 return { events: [] };
455 case "set-gait":
456 return this.#setGait(sessionId, command.characterId, command.gait);
457 case "attack":
458 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
459 case "cancel-attack":
460 return this.#cancelAttack(sessionId, command.characterId);
461 case "interact":
462 return this.#interact(sessionId, command.characterId, command.targetEntityId, command.purpose);
463 case "follow":
464 return this.#follow(sessionId, command.characterId, command.targetEntityId);
465 case "cancel-follow":
466 return this.#cancelFollow(sessionId, command.characterId);
467 case "set-spell-favorite":
468 case "set-spell-autocast":
469 case "arm-spell":
470 case "cancel-arm-spell":
471 case "cast-spell-tile":
472 case "cast-spell-entity":
473 case "read-spellbook":
474 return handleSpellCommand(this, sessionId, command, message.now ?? Date.now()) ?? { events: [] };
475 default:
476 {
477 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
478 if (gather)
479 { return gather; }
480 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
481 if (craft)
482 { return craft; }
483 const shop = handleShopCommand(this, sessionId, command, message.now ?? Date.now());
484 if (shop)
485 { return shop; }
486 const alchemy = handleAlchemyCommand(this, sessionId, command);
487 if (alchemy)
488 { return alchemy; }
489 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
490 return result ?? { events: [] };
491 }
492 }
493 }
494
495 #spawnCorpseDrops (message)
496 {
497 const events = [];
498 for (const drop of message.drops ?? [])
499 {
500 const stack = drop.stack ?? { itemId: drop.itemId, quantity: 1 };
501 const item = {
502 groundItemId: drop.groundItemId,
503 tileX: message.tileX,
504 tileY: message.tileY,
505 stack,
506 droppedAt: message.now,
507 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
508 source: "player-death",
509 droppedByCharacterId: message.characterId
510 };
511 addGroundItem(this, item);
512 events.push({
513 type: "ground-item-appear",
514 ...publicGroundItem(item),
515 stack: item.stack,
516 droppedAt: item.droppedAt,
517 source: item.source,
518 droppedByCharacterId: item.droppedByCharacterId,
519 expiresAt: item.expiresAt
520 });
521 }
522 return { events };
523 }
524
525 #applyRespawn (message)
526 {
527 const handle = this.ecs.handleOf(message.entityId);
528 if (handle == null || !this.ecs.has(handle, Component.dead))
529 { return { accepted: false }; }
530 const position = this.ecs.get(handle, Component.position);
531 const fromTileX = position.tileX;
532 const fromTileY = position.tileY;
533 const health = this.ecs.get(handle, Component.health);
534 const stamina = this.ecs.get(handle, Component.stamina);
535 if (health)
536 {
537 health.max = message.maxHealth;
538 health.current = message.maxHealth;
539 }
540 if (stamina)
541 {
542 stamina.max = message.maxStamina;
543 stamina.current = message.maxStamina;
544 }
545 else
546 { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); }
547 this.ecs.remove(handle, Component.dead);
548 clearEngage(this.ecs, message.entityId);
549 const path = this.ecs.get(handle, Component.path);
550 if (path)
551 { path.tiles = []; }
552 clearFollow(this.ecs, message.entityId);
553
554 const destRegionX = tileToRegion(message.tileX);
555 const destRegionY = tileToRegion(message.tileY);
556 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
557 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
558 {
559 this.frozen.add(message.entityId);
560 return {
561 accepted: true,
562 transferRequest: {
563 entityId: message.entityId,
564 fromTileX,
565 fromTileY,
566 destTileX: message.tileX,
567 destTileY: message.tileY,
568 toRegionX: destRegionX,
569 toRegionY: destRegionY,
570 dimensionId,
571 payload: serializeEntity(this.ecs, message.entityId)
572 }
573 };
574 }
575 if (!this.isEnterable(message.tileX, message.tileY, dimensionId))
576 { return { accepted: false }; }
577 this.#vacate(message.entityId, fromTileX, fromTileY);
578 position.tileX = message.tileX;
579 position.tileY = message.tileY;
580 this.#occupy(message.entityId, position.tileX, position.tileY);
581 return {
582 accepted: true,
583 event: {
584 type: "entity-move",
585 entityId: message.entityId,
586 fromTileX,
587 fromTileY,
588 tileX: position.tileX,
589 tileY: position.tileY,
590 dimensionId,
591 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
592 }
593 };
594 }
595
596 /** Move an entity to a tile/dimension; clears path and updates occupancy. */
597 #relocateEntity (message)
598 {
599 const handle = this.ecs.handleOf(message.entityId);
600 if (handle == null)
601 { return { accepted: false }; }
602 const position = this.ecs.get(handle, Component.position);
603 if (!position)
604 { return { accepted: false }; }
605 const fromTileX = position.tileX;
606 const fromTileY = position.tileY;
607 const fromDimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
608 const destTileX = message.tileX | 0;
609 const destTileY = message.tileY | 0;
610 const dimensionId = normalizeDimensionId(message.dimensionId ?? fromDimensionId);
611
612 clearEngage(this.ecs, message.entityId);
613 const path = this.ecs.get(handle, Component.path);
614 if (path)
615 { path.tiles = []; }
616 clearFollow(this.ecs, message.entityId);
617
618 const destRegionX = tileToRegion(destTileX);
619 const destRegionY = tileToRegion(destTileY);
620 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
621 {
622 this.frozen.add(message.entityId);
623 const payload = serializeEntity(this.ecs, message.entityId);
624 if (payload.components?.position)
625 {
626 payload.components.position.tileX = destTileX;
627 payload.components.position.tileY = destTileY;
628 payload.components.position.dimensionId = dimensionId;
629 }
630 return {
631 accepted: true,
632 transferRequest: {
633 entityId: message.entityId,
634 fromTileX,
635 fromTileY,
636 fromDimensionId,
637 destTileX,
638 destTileY,
639 toRegionX: destRegionX,
640 toRegionY: destRegionY,
641 dimensionId,
642 payload
643 }
644 };
645 }
646 if (!this.isEnterable(destTileX, destTileY, dimensionId))
647 { return { accepted: false }; }
648 if (!this.#isFlying(handle))
649 { this.#vacate(message.entityId, fromTileX, fromTileY); }
650 position.tileX = destTileX;
651 position.tileY = destTileY;
652 position.dimensionId = dimensionId;
653 if (!this.#isFlying(handle))
654 { this.#occupy(message.entityId, destTileX, destTileY); }
655 return {
656 accepted: true,
657 event: {
658 type: "entity-move",
659 entityId: message.entityId,
660 fromTileX,
661 fromTileY,
662 fromDimensionId,
663 tileX: destTileX,
664 tileY: destTileY,
665 dimensionId,
666 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
667 }
668 };
669 }
670
671 #inspectBag (entityId)
672 {
673 const handle = this.ecs.handleOf(entityId);
674 if (handle == null)
675 { return null; }
676 return bagView(this.ecs, handle);
677 }
678
679 #inspectSkills (entityId)
680 {
681 const handle = this.ecs.handleOf(entityId);
682 if (handle == null)
683 { return null; }
684 const skills = this.ecs.get(handle, Component.skills);
685 if (!skills?.xp)
686 { return null; }
687 return skills;
688 }
689
690 #inspectSpells (entityId)
691 {
692 const handle = this.ecs.handleOf(entityId);
693 if (handle == null)
694 { return null; }
695 const spells = this.ecs.get(handle, Component.spells);
696 const skills = this.ecs.get(handle, Component.skills);
697 const casting = this.ecs.get(handle, Component.spellcasting);
698 if (!spells)
699 { return null; }
700 return {
701 spells: publicSpellsView(spells, skills),
702 autoCast: !!spells.autoCast,
703 armedSpellId: casting?.armedSpellId ?? null
704 };
705 }
706
707 #inspectStamina (entityId)
708 {
709 const handle = this.ecs.handleOf(entityId);
710 if (handle == null)
711 { return null; }
712 const stamina = this.ecs.get(handle, Component.stamina);
713 const movement = this.ecs.get(handle, Component.movement);
714 if (!stamina)
715 { return null; }
716 return {
717 ...publicStaminaView(stamina),
718 gait: movement?.gait ?? GAIT.walk
719 };
720 }
721
722 #applyBag (entityId, bag)
723 {
724 const handle = this.ecs.handleOf(entityId);
725 if (handle == null)
726 { return null; }
727 return applyBagView(this.ecs, handle, bag);
728 }
729
730 #applyAppearance (entityId, appearancePatch)
731 {
732 const handle = this.ecs.handleOf(entityId);
733 if (handle == null)
734 { return null; }
735 const appearance = this.ecs.get(handle, Component.appearance);
736 if (!appearance)
737 { return null; }
738 Object.assign(appearance, appearancePatch ?? {});
739 return publicEntityView(this.ecs, entityId);
740 }
741
742 #updateFlight (entityId, flightPatch, now = Date.now())
743 {
744 const handle = this.ecs.handleOf(entityId);
745 if (handle == null)
746 { return null; }
747 let flight = this.ecs.get(handle, Component.flight);
748 if (!flight)
749 { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); }
750 else
751 { Object.assign(flight, flightPatch); }
752 const position = this.ecs.get(handle, Component.position);
753 const movement = this.ecs.get(handle, Component.movement);
754 const fromTileX = position.tileX;
755 const fromTileY = position.tileY;
756 const tileX = Math.floor(flight.x);
757 const tileY = Math.floor(flight.y);
758 position.tileX = tileX;
759 position.tileY = tileY;
760 const destRegionX = tileToRegion(tileX);
761 const destRegionY = tileToRegion(tileY);
762 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
763 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
764 {
765 this.frozen.add(entityId);
766 return {
767 transferRequest: {
768 type: "transfer-request",
769 entityId,
770 fromTileX,
771 fromTileY,
772 destTileX: tileX,
773 destTileY: tileY,
774 toRegionX: destRegionX,
775 toRegionY: destRegionY,
776 dimensionId
777 }
778 };
779 }
780 const dt = flight.lastAt && now > flight.lastAt
781 ? Math.min(0.25, (now - flight.lastAt) / 1000)
782 : 1 / 20;
783 return {
784 event: {
785 type: "entity-move",
786 entityId,
787 fromTileX,
788 fromTileY,
789 tileX,
790 tileY,
791 worldX: flight.x,
792 worldY: flight.y,
793 gait: movement?.gait ?? "walk",
794 lerpMs: Math.max(50, Math.round(dt * 1000)),
795 freeFlight: true
796 }
797 };
798 }
799
800 #moveTo (sessionId, characterId, tileX, tileY)
801 {
802 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
803 if (this.frozen.has(entityId))
804 { return; }
805 clearEngage(this.ecs, entityId);
806 clearFollow(this.ecs, entityId);
807 cancelGather(this.ecs, handle);
808 const casting = this.ecs.get(handle, Component.spellcasting);
809 if (casting)
810 { casting.pendingCast = null; }
811 const position = this.ecs.get(handle, Component.position);
812 const movement = this.ecs.get(handle, Component.movement);
813 let path = this.ecs.get(handle, Component.path);
814 if (!path)
815 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
816 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
817 path.tiles = findPath(
818 position.tileX,
819 position.tileY,
820 tileX,
821 tileY,
822 (x, y) => this.walkableFor(entityId, x, y),
823 bounds.minX,
824 bounds.minY,
825 bounds.maxX,
826 bounds.maxY,
827 { preferVertical: true }
828 );
829 movement.walkCarry = 0;
830 }
831
832 #attack (sessionId, characterId, targetEntityId, now)
833 {
834 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
835 if (targetEntityId === entityId)
836 {
837 const error = new Error("Cannot attack yourself.");
838 error.userFacing = true;
839 throw error;
840 }
841 const target = resolveCombatTarget(this, targetEntityId);
842 if (!target)
843 {
844 const error = new Error("Target is not here.");
845 error.userFacing = true;
846 throw error;
847 }
848 if (target.health && target.health.current <= 0)
849 {
850 const error = new Error("That cannot be attacked.");
851 error.userFacing = true;
852 throw error;
853 }
854 if (!this.ecs.get(handle, Component.combat))
855 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
856 clearFollow(this.ecs, entityId);
857 cancelGather(this.ecs, handle);
858 engageTarget(this.ecs, entityId, targetEntityId, now);
859 const position = this.ecs.get(handle, Component.position);
860 const profile = attackProfileOf(this.ecs, handle);
861 if (position && target.pos)
862 {
863 if (profile.mode === "ranged")
864 {
865 queueStandInRangeApproach(
866 this,
867 entityId,
868 handle,
869 position,
870 target.pos.tileX,
871 target.pos.tileY,
872 profile.rangeTiles | 0 || COMBAT_RANGE_TILES,
873 1
874 );
875 }
876 else if (profile.mode === "melee")
877 {
878 queueMeleeApproach(this, entityId, handle, position, target.pos);
879 }
880 }
881 return { events: [] };
882 }
883
884 #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })
885 {
886 // Kept for cross-worker hooks; retaliation happens on swing resolution, not Attack click.
887 void attackerEntityId;
888 void targetEntityId;
889 void now;
890 return { events: [] };
891 }
892
893 #engageTargetMessage ({ attackerEntityId, targetEntityId, now = Date.now() })
894 {
895 if (this.ecs.handleOf(attackerEntityId) == null)
896 { return { ok: false }; }
897 engageTarget(this.ecs, attackerEntityId, targetEntityId, now);
898 return { ok: true };
899 }
900
901 /**
902 * Idle town-guard entity ids from spawners whose wander range covers (tileX, tileY).
903 * Optionally restrict to one spawnerId.
904 */
905 #listTownGuardsNear ({ tileX, tileY, spawnerId = null, limit = 8 })
906 {
907 const guards = [];
908 for (const entity of this.ecs.query(Component.spawnOrigin, Component.creature, Component.combat, Component.position))
909 {
910 if (!entity.spawnOrigin?.townGuard)
911 { continue; }
912 if (spawnerId != null && entity.spawnOrigin.spawnerId !== spawnerId)
913 { continue; }
914 const originX = entity.spawnOrigin.originTileX;
915 const originY = entity.spawnOrigin.originTileY;
916 const range = entity.spawnOrigin.wanderRangeTiles | 0;
917 const dx = Math.abs(tileX - originX);
918 const dy = Math.abs(tileY - originY);
919 if (Math.max(dx, dy) > range)
920 { continue; }
921 const health = this.ecs.get(entity.handle, Component.health);
922 if (health && health.current <= 0)
923 { continue; }
924 if (this.ecs.has(entity.handle, Component.dead))
925 { continue; }
926 guards.push({
927 entityId: entity.entityId,
928 spawnerId: entity.spawnOrigin.spawnerId,
929 busy: entity.combat?.targetEntityId != null
930 });
931 if (guards.length >= limit)
932 { break; }
933 }
934 return { guards };
935 }
936
937 #applyRemoteMelee (payload)
938 {
939 return applyRemoteMeleeSwing(this, payload);
940 }
941
942 #applyRemoteRanged (payload)
943 {
944 return applyRemoteRangedShot(this, payload);
945 }
946
947 #applyCombatHitXp ({ entityId, profile, damage })
948 {
949 const handle = this.ecs.handleOf(entityId);
950 if (handle == null)
951 { return { events: [] }; }
952 const character = this.ecs.get(handle, Component.character);
953 if (!character)
954 { return { events: [] }; }
955 const xpAward = awardCombatHitXp(this.ecs, handle, profile, damage);
956 if (!xpAward)
957 { return { events: [] }; }
958 return {
959 events: [{
960 type: "skills-updated",
961 entityId,
962 characterId: character.characterId,
963 skills: xpAward.view,
964 stored: xpAward.stored,
965 levelUps: xpAward.levelUps ?? []
966 }]
967 };
968 }
969
970 #cancelAttack (sessionId, characterId)
971 {
972 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
973 clearEngage(this.ecs, entityId);
974 return { events: [] };
975 }
976
977 #interact (sessionId, characterId, targetEntityId, purpose = null)
978 {
979 this.#requireOwnedEntity(sessionId, characterId);
980 const targetHandle = this.ecs.handleOf(targetEntityId);
981 if (targetHandle == null)
982 {
983 const error = new Error("Target is not here.");
984 error.userFacing = true;
985 throw error;
986 }
987 if (isUntargetable(this.ecs, targetHandle))
988 {
989 const error = new Error("Nothing to say.");
990 error.userFacing = true;
991 throw error;
992 }
993 const creature = this.ecs.get(targetHandle, Component.creature);
994 const def = creature ? mobDefinition(creature.mobTypeId) : null;
995 const shop = this.ecs.get(targetHandle, Component.shop);
996 const hasShop = shopHasInterface(shop);
997 const origin = this.ecs.get(targetHandle, Component.spawnOrigin);
998 const dialogueId = origin?.dialogueId ? String(origin.dialogueId) : "";
999 const intent = purpose === "shop" || purpose === "talk" ? purpose : null;
1000
1001 if (intent === "shop" && hasShop)
1002 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1003 if (intent === "talk" && dialogueId)
1004 {
1005 // Pin in-worker before return so wander cannot start before the sim thread pins.
1006 this.#pinDialogue(targetEntityId, characterId);
1007 return {
1008 events: [{
1009 type: "open-dialogue",
1010 sessionId,
1011 characterId,
1012 entityId: targetEntityId,
1013 dialogueId
1014 }]
1015 };
1016 }
1017 if (intent === "talk" && hasShop)
1018 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1019
1020 // Default click: prefer dialogue when assigned, else shop, else talkable no-op.
1021 if (dialogueId)
1022 {
1023 this.#pinDialogue(targetEntityId, characterId);
1024 return {
1025 events: [{
1026 type: "open-dialogue",
1027 sessionId,
1028 characterId,
1029 entityId: targetEntityId,
1030 dialogueId
1031 }]
1032 };
1033 }
1034 if (hasShop)
1035 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1036 if (!def?.talkable)
1037 {
1038 const error = new Error("They have nothing to say.");
1039 error.userFacing = true;
1040 throw error;
1041 }
1042 return { events: [] };
1043 }
1044
1045 #follow (sessionId, characterId, targetEntityId)
1046 {
1047 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
1048 const targetHandle = this.ecs.handleOf(targetEntityId);
1049 if (targetHandle == null)
1050 {
1051 const error = new Error("Target is not here.");
1052 error.userFacing = true;
1053 throw error;
1054 }
1055 if (targetEntityId === entityId)
1056 {
1057 const error = new Error("Cannot follow yourself.");
1058 error.userFacing = true;
1059 throw error;
1060 }
1061 if (!this.ecs.get(targetHandle, Component.position))
1062 {
1063 const error = new Error("That cannot be followed.");
1064 error.userFacing = true;
1065 throw error;
1066 }
1067 clearEngage(this.ecs, entityId);
1068 setFollow(this.ecs, entityId, targetEntityId);
1069 const path = this.ecs.get(handle, Component.path);
1070 if (path)
1071 { path.tiles = []; }
1072 return { events: [] };
1073 }
1074
1075 #cancelFollow (sessionId, characterId)
1076 {
1077 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
1078 clearFollow(this.ecs, entityId);
1079 return { events: [] };
1080 }
1081
1082 #setGait (sessionId, characterId, gait)
1083 {
1084 if (gait !== GAIT.walk && gait !== GAIT.run)
1085 {
1086 const error = new Error("Gait must be walk or run.");
1087 error.userFacing = true;
1088 throw error;
1089 }
1090 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
1091 const movement = this.ecs.get(handle, Component.movement);
1092 const stamina = this.ecs.get(handle, Component.stamina);
1093 if (gait === GAIT.run && !(Number(stamina?.current) > 0))
1094 {
1095 const error = new Error("You are too exhausted to run.");
1096 error.userFacing = true;
1097 throw error;
1098 }
1099 movement.gait = gait;
1100 const character = this.ecs.get(handle, Component.character);
1101 return {
1102 events: character
1103 ? [this.#staminaEvent(handle, character.characterId, movement.gait)]
1104 : []
1105 };
1106 }
1107
1108 #staminaEvent (handle, characterId, gait = null)
1109 {
1110 const stamina = this.ecs.get(handle, Component.stamina);
1111 const movement = this.ecs.get(handle, Component.movement);
1112 return {
1113 type: "stamina",
1114 characterId,
1115 ...publicStaminaView(stamina),
1116 gait: gait ?? movement?.gait ?? GAIT.walk
1117 };
1118 }
1119
1120 #consumeRunStamina (handle, events)
1121 {
1122 const character = this.ecs.get(handle, Component.character);
1123 if (!character)
1124 { return; }
1125 let stamina = this.ecs.get(handle, Component.stamina);
1126 if (!stamina)
1127 {
1128 stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 });
1129 }
1130 const skills = this.ecs.get(handle, Component.skills);
1131 syncPlayerStamina(this.ecs, handle);
1132 const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond);
1133 stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost);
1134 stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost;
1135 let skillsChanged = false;
1136 const levelUps = [];
1137 while (stamina.xpDebt >= 1 && skills?.xp)
1138 {
1139 stamina.xpDebt -= 1;
1140 const result = applySkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT);
1141 if (result.changed)
1142 {
1143 skillsChanged = true;
1144 syncPlayerStamina(this.ecs, handle);
1145 }
1146 if (result.levelUp)
1147 { levelUps.push(result.levelUp); }
1148 }
1149 const movement = this.ecs.get(handle, Component.movement);
1150 if (stamina.current <= 0 && movement)
1151 {
1152 stamina.current = 0;
1153 movement.gait = GAIT.walk;
1154 }
1155 events.push(this.#staminaEvent(handle, character.characterId));
1156 if (skillsChanged)
1157 {
1158 events.push({
1159 type: "skills-updated",
1160 entityId: this.ecs.entityIdOf(handle),
1161 characterId: character.characterId,
1162 skills: publicSkillsView(skills),
1163 stored: storedSkillXp(skills),
1164 levelUps
1165 });
1166 }
1167 }
1168
1169 #regenStamina (dt, events)
1170 {
1171 if (!(dt > 0))
1172 { return; }
1173 for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement))
1174 {
1175 const { handle, character, stamina, movement } = entity;
1176 if (this.ecs.has(handle, Component.dead))
1177 { continue; }
1178 // Run gait only blocks regen while actually stepping along a path.
1179 const path = this.ecs.get(handle, Component.path);
1180 if (movement.gait === GAIT.run && path?.tiles?.length)
1181 { continue; }
1182 syncPlayerStamina(this.ecs, handle);
1183 const before = Number(stamina.current) || 0;
1184 if (before >= stamina.max)
1185 { continue; }
1186 stamina.current = Math.min(stamina.max, before + dt * STAMINA_REGEN_PER_SECOND);
1187 const after = Number(stamina.current) || 0;
1188 // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
1189 if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
1190 { events.push(this.#staminaEvent(handle, character.characterId)); }
1191 }
1192 }
1193
1194 #requireOwnedEntity (sessionId, characterId)
1195 {
1196 const entityId = this.characterEntities.get(characterId);
1197 if (!entityId)
1198 {
1199 const error = new Error("Character is not in the world.");
1200 error.userFacing = true;
1201 throw error;
1202 }
1203 const handle = this.ecs.handleOf(entityId);
1204 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
1205 if (!identity || identity.sessionId !== sessionId)
1206 {
1207 const error = new Error("Character is not in the world.");
1208 error.userFacing = true;
1209 throw error;
1210 }
1211 if (this.ecs.has(handle, Component.dead))
1212 {
1213 const error = new Error("You are dead.");
1214 error.userFacing = true;
1215 throw error;
1216 }
1217 return { handle, entityId };
1218 }
1219
1220 #stepSystems (now = Date.now(), dt = 1 / 20)
1221 {
1222 const events = [];
1223 const transferRequests = [];
1224 this.#regenStamina(dt, events);
1225 events.push(...stepStatusEffects(this, now, dt));
1226 const flight = stepFreeFlight(this, now);
1227 for (const event of flight)
1228 {
1229 if (event.type === "transfer-request")
1230 {
1231 const payload = serializeEntity(this.ecs, event.entityId);
1232 transferRequests.push({
1233 entityId: event.entityId,
1234 fromTileX: event.fromTileX,
1235 fromTileY: event.fromTileY,
1236 destTileX: event.destTileX,
1237 destTileY: event.destTileY,
1238 toRegionX: event.toRegionX,
1239 toRegionY: event.toRegionY,
1240 dimensionId: event.dimensionId ?? OVERWORLD_ID,
1241 payload
1242 });
1243 continue;
1244 }
1245 events.push(event);
1246 }
1247 stepAggression(this, now);
1248 events.push(...stepCombat(this, now));
1249 events.push(...stepPendingSpellCast(this, now));
1250 events.push(...processSpellImpacts(this, now));
1251 events.push(...stepSpellAutoCast(this, now));
1252 events.push(...tickSpellLights(this, now));
1253 stepFollow(this);
1254 const gather = stepGather(this, now);
1255 events.push(...gather.events);
1256 for (const entry of gather.privates ?? [])
1257 {
1258 events.push({
1259 type: "inventory",
1260 characterId: entry.characterId,
1261 ...entry.bag
1262 });
1263 }
1264 const craft = stepCrafting(this, now);
1265 events.push(...craft.events);
1266 for (const entry of craft.privates ?? [])
1267 {
1268 events.push({
1269 type: "inventory",
1270 characterId: entry.characterId,
1271 ...entry.bag
1272 });
1273 }
1274 return { events, transferRequests };
1275 }
1276
1277 #stepMovement (now = Date.now())
1278 {
1279 const events = expireGroundItems(this, now);
1280 const transferRequests = [];
1281 events.push(...pruneShopBrowsers(this));
1282 events.push(...this.#pruneDialogueBrowsers());
1283 this.#queueAmbientWander();
1284 this.#queueSpawnerWander();
1285 this.#queueExchangeStations();
1286 for (const entity of this.ecs.query(Component.position, Component.movement))
1287 {
1288 const { handle, entityId, position, movement } = entity;
1289 if (this.ecs.has(handle, Component.dead))
1290 { continue; }
1291 if (this.ecs.has(handle, Component.flight))
1292 { continue; }
1293 const path = this.ecs.get(handle, Component.path);
1294 const tiles = path?.tiles;
1295 if (this.frozen.has(entityId) || !tiles?.length)
1296 {
1297 if (path)
1298 { path.stuckSince = null; }
1299 continue;
1300 }
1301 if (!this.chunkIsSimulating(position.tileX, position.tileY, position.dimensionId ?? OVERWORLD_ID))
1302 { continue; }
1303
1304 this.#repathIfNavigationStuck(entityId, position, movement, path, now);
1305
1306 const stamina = this.ecs.get(handle, Component.stamina);
1307 if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))
1308 { movement.gait = GAIT.walk; }
1309 const isWalk = movement.gait !== GAIT.run;
1310 if (isWalk)
1311 {
1312 movement.walkCarry = (movement.walkCarry + 1) % 2;
1313 if (movement.walkCarry !== 0)
1314 { continue; }
1315 }
1316
1317 const next = tiles[0];
1318 if (!next)
1319 { continue; }
1320 const destRegionX = tileToRegion(next.x);
1321 const destRegionY = tileToRegion(next.y);
1322 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
1323 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
1324 {
1325 this.frozen.add(entityId);
1326 transferRequests.push({
1327 entityId,
1328 fromTileX: position.tileX,
1329 fromTileY: position.tileY,
1330 destTileX: next.x,
1331 destTileY: next.y,
1332 toRegionX: destRegionX,
1333 toRegionY: destRegionY,
1334 dimensionId,
1335 payload: serializeEntity(this.ecs, entityId)
1336 });
1337 continue;
1338 }
1339
1340 if (!this.walkableFor(entityId, next.x, next.y))
1341 {
1342 const combat = this.ecs.get(handle, Component.combat);
1343 if (combat?.targetEntityId != null)
1344 {
1345 const targetHandle = this.ecs.handleOf(combat.targetEntityId);
1346 const targetPos = targetHandle != null
1347 ? this.ecs.get(targetHandle, Component.position)
1348 : null;
1349 const blockedByTarget = targetPos
1350 && next.x === targetPos.tileX
1351 && next.y === targetPos.tileY;
1352 if (!blockedByTarget)
1353 { path.tiles = []; }
1354 }
1355 continue;
1356 }
1357
1358 const fromTileX = position.tileX;
1359 const fromTileY = position.tileY;
1360 const flying = this.#isFlying(handle);
1361 if (!flying)
1362 { this.#vacate(entityId, fromTileX, fromTileY); }
1363 position.tileX = next.x;
1364 position.tileY = next.y;
1365 tiles.shift();
1366 if (!flying)
1367 { this.#occupy(entityId, position.tileX, position.tileY); }
1368 path.stuckSince = now;
1369 path.stuckTileX = position.tileX;
1370 path.stuckTileY = position.tileY;
1371 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
1372 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
1373 if (!isWalk)
1374 { this.#consumeRunStamina(handle, events); }
1375 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
1376 }
1377 return { events, transferRequests };
1378 }
1379
1380 /**
1381 * If we still have a destination but have not left this tile for NAV_STUCK_MS,
1382 * recompute A* to the same goal (around whoever is blocking the old route).
1383 */
1384 #repathIfNavigationStuck (entityId, position, movement, path, now)
1385 {
1386 if (!path?.tiles?.length)
1387 {
1388 path.stuckSince = null;
1389 return;
1390 }
1391 if (
1392 path.stuckSince == null
1393 || path.stuckTileX !== position.tileX
1394 || path.stuckTileY !== position.tileY
1395 )
1396 {
1397 path.stuckSince = now;
1398 path.stuckTileX = position.tileX;
1399 path.stuckTileY = position.tileY;
1400 return;
1401 }
1402 if (now - path.stuckSince < NAV_STUCK_MS)
1403 { return; }
1404
1405 const goal = path.tiles[path.tiles.length - 1];
1406 if (!goal || (goal.x === position.tileX && goal.y === position.tileY))
1407 {
1408 path.tiles = [];
1409 path.stuckSince = null;
1410 return;
1411 }
1412 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1413 const stuckHandle = this.ecs.handleOf(entityId);
1414 path.tiles = findPath(
1415 position.tileX,
1416 position.tileY,
1417 goal.x,
1418 goal.y,
1419 (x, y) => this.isClearStanding(entityId, x, y),
1420 bounds.minX,
1421 bounds.minY,
1422 bounds.maxX,
1423 bounds.maxY,
1424 { preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character) }
1425 );
1426 path.stuckSince = now;
1427 path.stuckTileX = position.tileX;
1428 path.stuckTileY = position.tileY;
1429 if (movement)
1430 { movement.walkCarry = 0; }
1431 }
1432
1433 #queueAmbientWander ()
1434 {
1435 for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
1436 {
1437 const def = mobDefinition(entity.creature.mobTypeId);
1438 if (!def?.ambient || def.freeFlight)
1439 { continue; }
1440 if (this.ecs.get(entity.handle, Component.spawnOrigin))
1441 { continue; }
1442 const path = this.ecs.get(entity.handle, Component.path);
1443 if (!path)
1444 { continue; }
1445 if (path.tiles?.length)
1446 { continue; }
1447 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1448 { continue; }
1449 if (Math.random() > 0.35)
1450 { continue; }
1451 const dirs = [
1452 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
1453 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
1454 ];
1455 const dir = dirs[Math.floor(Math.random() * dirs.length)];
1456 const nextX = entity.position.tileX + dir.x;
1457 const nextY = entity.position.tileY + dir.y;
1458 if (!this.isClearStanding(entity.entityId, nextX, nextY))
1459 { continue; }
1460 path.tiles = [{ x: nextX, y: nextY }];
1461 }
1462 }
1463
1464 /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner. Combat chase is unrestricted. */
1465 #queueSpawnerWander ()
1466 {
1467 for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin))
1468 {
1469 const combat = this.ecs.get(entity.handle, Component.combat);
1470 if (combat?.targetEntityId != null)
1471 { continue; }
1472 const follow = this.ecs.get(entity.handle, Component.follow);
1473 if (follow?.targetEntityId != null)
1474 { continue; }
1475 const shop = this.ecs.get(entity.handle, Component.shop);
1476 if (shopHasActiveBrowsers(shop))
1477 { continue; }
1478 const origin = entity.spawnOrigin;
1479 if (hasDialogueBrowsers(origin))
1480 { continue; }
1481 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1482 { continue; }
1483 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1484 if (def?.freeFlight)
1485 { continue; }
1486 const path = this.ecs.get(entity.handle, Component.path);
1487 if (!path || path.tiles?.length)
1488 { continue; }
1489 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1490 { continue; }
1491 // ~4× longer idle stands than the old 0.4 chance (mobs mostly idle, rarely walk).
1492 if (Math.random() > 0.1)
1493 { continue; }
1494
1495 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1496 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1497 const range = Math.max(0, origin.wanderRangeTiles | 0);
1498 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
1499 if (!goal)
1500 { continue; }
1501 if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY)
1502 { continue; }
1503 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1504 const tiles = findPath(
1505 entity.position.tileX,
1506 entity.position.tileY,
1507 goal.tileX,
1508 goal.tileY,
1509 (x, y) => this.walkableFor(entity.entityId, x, y),
1510 bounds.minX,
1511 bounds.minY,
1512 bounds.maxX,
1513 bounds.maxY
1514 );
1515 if (!tiles?.length)
1516 { continue; }
1517 path.tiles = tiles;
1518 }
1519 }
1520
1521 /**
1522 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1523 * message: { stationTileX, stationTileY }
1524 */
1525 #stationExchangeClerk (message)
1526 {
1527 const stationTileX = message.stationTileX | 0;
1528 const stationTileY = message.stationTileY | 0;
1529 if (!this.isEnterable(stationTileX, stationTileY))
1530 { return { ok: false, reason: "blocked" }; }
1531
1532 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1533 {
1534 if (!entity.spawnOrigin?.centralExchange)
1535 { continue; }
1536 if (
1537 Number.isInteger(entity.spawnOrigin.stationTileX)
1538 && entity.spawnOrigin.stationTileX === stationTileX
1539 && entity.spawnOrigin.stationTileY === stationTileY
1540 )
1541 { return { ok: true, entityId: entity.entityId, already: true }; }
1542 }
1543
1544 let best = null;
1545 let bestDist = Infinity;
1546 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1547 {
1548 if (!entity.spawnOrigin?.centralExchange)
1549 { continue; }
1550 if (Number.isInteger(entity.spawnOrigin.stationTileX))
1551 { continue; }
1552 const dist = Math.max(
1553 Math.abs(entity.position.tileX - stationTileX),
1554 Math.abs(entity.position.tileY - stationTileY)
1555 );
1556 if (dist < bestDist)
1557 {
1558 bestDist = dist;
1559 best = entity;
1560 }
1561 }
1562 if (!best)
1563 { return { ok: false, reason: "none-available" }; }
1564
1565 const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS);
1566 const tiles = findPath(
1567 best.position.tileX,
1568 best.position.tileY,
1569 stationTileX,
1570 stationTileY,
1571 (x, y) => this.walkableFor(best.entityId, x, y),
1572 bounds.minX,
1573 bounds.minY,
1574 bounds.maxX,
1575 bounds.maxY
1576 );
1577 best.spawnOrigin.stationTileX = stationTileX;
1578 best.spawnOrigin.stationTileY = stationTileY;
1579 if (tiles?.length)
1580 { best.path.tiles = tiles; }
1581 else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY)
1582 { best.path.tiles = []; }
1583 else
1584 { return { ok: false, reason: "no-path" }; }
1585 return { ok: true, entityId: best.entityId };
1586 }
1587
1588 /**
1589 * Clear a CE clerk's station assignment so wander can resume.
1590 * message: { stationTileX, stationTileY }
1591 */
1592 #releaseExchangeClerk (message)
1593 {
1594 const stationTileX = message.stationTileX | 0;
1595 const stationTileY = message.stationTileY | 0;
1596 let released = 0;
1597 for (const entity of this.ecs.query(Component.spawnOrigin, Component.path))
1598 {
1599 if (!entity.spawnOrigin?.centralExchange)
1600 { continue; }
1601 if (
1602 entity.spawnOrigin.stationTileX !== stationTileX
1603 || entity.spawnOrigin.stationTileY !== stationTileY
1604 )
1605 { continue; }
1606 entity.spawnOrigin.stationTileX = null;
1607 entity.spawnOrigin.stationTileY = null;
1608 entity.path.tiles = [];
1609 released += 1;
1610 }
1611 return { ok: true, released };
1612 }
1613
1614 #pinDialogue (entityId, characterId)
1615 {
1616 const handle = this.ecs.handleOf(entityId | 0);
1617 if (handle == null)
1618 { return { ok: false }; }
1619 const origin = this.ecs.get(handle, Component.spawnOrigin);
1620 if (!origin)
1621 { return { ok: false }; }
1622 if (!origin.dialogueBrowsers || typeof origin.dialogueBrowsers !== "object")
1623 { origin.dialogueBrowsers = Object.create(null); }
1624 origin.dialogueBrowsers[characterId | 0] = true;
1625 const path = this.ecs.get(handle, Component.path);
1626 if (path)
1627 { path.tiles = []; }
1628 return { ok: true };
1629 }
1630
1631 #unpinDialogue (entityId, characterId)
1632 {
1633 const handle = this.ecs.handleOf(entityId | 0);
1634 if (handle == null)
1635 { return { ok: false }; }
1636 const origin = this.ecs.get(handle, Component.spawnOrigin);
1637 if (!origin?.dialogueBrowsers)
1638 { return { ok: true }; }
1639 delete origin.dialogueBrowsers[characterId | 0];
1640 return { ok: true };
1641 }
1642
1643 #pruneDialogueBrowsers ()
1644 {
1645 const events = [];
1646 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1647 {
1648 const browsers = entity.spawnOrigin?.dialogueBrowsers;
1649 if (!browsers || typeof browsers !== "object")
1650 { continue; }
1651 const ids = Object.keys(browsers).map((id) => Number(id));
1652 if (!ids.length)
1653 { continue; }
1654 const path = this.ecs.get(entity.handle, Component.path);
1655 if (path)
1656 { path.tiles = []; }
1657 for (const characterId of ids)
1658 {
1659 const playerEntityId = this.characterEntities.get(characterId);
1660 if (playerEntityId == null)
1661 {
1662 delete browsers[characterId];
1663 continue;
1664 }
1665 const playerHandle = this.ecs.handleOf(playerEntityId);
1666 const playerPos = this.ecs.get(playerHandle, Component.position);
1667 const stillNear = playerPos
1668 && chebyshev(
1669 playerPos.tileX,
1670 playerPos.tileY,
1671 entity.position.tileX,
1672 entity.position.tileY
1673 ) <= 1;
1674 if (stillNear)
1675 { continue; }
1676 delete browsers[characterId];
1677 const identity = this.ecs.get(playerHandle, Component.networkIdentity);
1678 events.push({
1679 type: "dialogue-walk-away",
1680 sessionId: identity?.sessionId ?? null,
1681 characterId,
1682 npcEntityId: entity.entityId
1683 });
1684 }
1685 }
1686 return events;
1687 }
1688
1689 /** Keep stationed CE clerks at their counter tile. */
1690 #queueExchangeStations ()
1691 {
1692 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1693 {
1694 if (!entity.spawnOrigin?.centralExchange)
1695 { continue; }
1696 const sx = entity.spawnOrigin.stationTileX;
1697 const sy = entity.spawnOrigin.stationTileY;
1698 if (!Number.isInteger(sx) || !Number.isInteger(sy))
1699 { continue; }
1700 if (entity.position.tileX === sx && entity.position.tileY === sy)
1701 {
1702 entity.path.tiles = [];
1703 continue;
1704 }
1705 if (entity.path.tiles?.length)
1706 { continue; }
1707 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1708 const tiles = findPath(
1709 entity.position.tileX,
1710 entity.position.tileY,
1711 sx,
1712 sy,
1713 (x, y) => this.walkableFor(entity.entityId, x, y),
1714 bounds.minX,
1715 bounds.minY,
1716 bounds.maxX,
1717 bounds.maxY
1718 );
1719 if (tiles?.length)
1720 { entity.path.tiles = tiles; }
1721 }
1722 }
1723
1724 #applyTransfer (message)
1725 {
1726 const payload = message.payload;
1727 const entityId = payload.entityId;
1728 if (this.ecs.hasEntity(entityId))
1729 { return { accepted: false, reason: "already-present" }; }
1730
1731 const position = payload.components?.position;
1732 const destTileX = message.destTileX ?? position?.tileX;
1733 const destTileY = message.destTileY ?? position?.tileY;
1734 const dimensionId = normalizeDimensionId(
1735 message.dimensionId ?? position?.dimensionId ?? OVERWORLD_ID
1736 );
1737 if (destTileX == null || destTileY == null)
1738 { return { accepted: false, reason: "missing-destination" }; }
1739 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY), dimensionId))
1740 { return { accepted: false, reason: "not-owner" }; }
1741
1742 const creature = payload.components?.creature;
1743 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
1744 if (flying)
1745 {
1746 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY), dimensionId);
1747 if (!data?.open)
1748 { return { accepted: false, reason: "blocked" }; }
1749 }
1750 else if (!this.isEnterable(destTileX, destTileY, dimensionId))
1751 { return { accepted: false, reason: "blocked" }; }
1752
1753 deserializeEntity(this.ecs, payload);
1754 const handle = this.ecs.handleOf(entityId);
1755 const livePosition = this.ecs.get(handle, Component.position);
1756 const path = this.ecs.get(handle, Component.path);
1757 livePosition.tileX = destTileX;
1758 livePosition.tileY = destTileY;
1759 livePosition.dimensionId = dimensionId;
1760 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
1761 { path.tiles.shift(); }
1762 if (!flying)
1763 { this.#occupy(entityId, destTileX, destTileY); }
1764 const character = this.ecs.get(handle, Component.character);
1765 if (character?.characterId)
1766 { this.characterEntities.set(character.characterId, entityId); }
1767 this.frozen.delete(entityId);
1768 return {
1769 accepted: true,
1770 entity: publicEntityView(this.ecs, entityId)
1771 };
1772 }
1773
1774 #commitTransfer (entityId)
1775 {
1776 if (!this.ecs.hasEntity(entityId))
1777 { return null; }
1778 return this.#destroyEntity(entityId);
1779 }
1780
1781 #abortTransfer (entityId)
1782 {
1783 this.frozen.delete(entityId);
1784 return publicEntityView(this.ecs, entityId);
1785 }
1786
1787 #listLoaders ()
1788 {
1789 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
1790 entityId: entity.entityId,
1791 tileX: entity.position.tileX,
1792 tileY: entity.position.tileY,
1793 dimensionId: normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID),
1794 chunkLoader: { ...entity.chunkLoader }
1795 }));
1796 }
1797
1798 #listPublicEntities ()
1799 {
1800 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
1801 }
1802
1803 #entitiesInRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
1804 {
1805 const dim = normalizeDimensionId(dimensionId);
1806 const records = [];
1807 for (const entity of this.ecs.query(Component.position))
1808 {
1809 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
1810 if (entityDim !== dim)
1811 { continue; }
1812 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
1813 { continue; }
1814 records.push({
1815 ...publicEntityView(this.ecs, entity.entityId),
1816 persistent: this.ecs.has(entity.handle, Component.persistent),
1817 payload: serializeEntity(this.ecs, entity.entityId)
1818 });
1819 }
1820 return records;
1821 }
1822
1823 #chunkSnapshot (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
1824 {
1825 const dim = normalizeDimensionId(dimensionId);
1826 const data = this.#chunkData(chunkX, chunkY, dim);
1827 if (staticOnly)
1828 {
1829 return {
1830 chunkX,
1831 chunkY,
1832 dimensionId: dim,
1833 open: data.open,
1834 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
1835 grounds: data.grounds,
1836 blocks: data.blocks,
1837 light: data.light,
1838 occlusion: data.occlusion,
1839 entities: [],
1840 groundItems: []
1841 };
1842 }
1843 const entities = [];
1844 for (const entity of this.ecs.query(Component.position, Component.appearance))
1845 {
1846 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
1847 if (entityDim !== dim)
1848 { continue; }
1849 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
1850 { continue; }
1851 entities.push(publicEntityView(this.ecs, entity.entityId));
1852 }
1853 return {
1854 chunkX,
1855 chunkY,
1856 dimensionId: dim,
1857 open: data.open,
1858 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
1859 grounds: data.grounds,
1860 blocks: data.blocks,
1861 light: data.light,
1862 occlusion: data.occlusion,
1863 entities,
1864 groundItems: groundItemsInChunk(this, chunkX, chunkY)
1865 };
1866 }
1867
1868 #moveEvent (entityId, fromTileX, fromTileY)
1869 {
1870 const view = publicEntityView(this.ecs, entityId);
1871 return {
1872 type: "entity-move",
1873 entityId,
1874 fromTileX,
1875 fromTileY,
1876 tileX: view.tileX,
1877 tileY: view.tileY,
1878 worldX: view.worldX,
1879 worldY: view.worldY,
1880 gait: view.gait,
1881 freeFlight: !!view.freeFlight
1882 };
1883 }
1884
1885 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
1886 {
1887 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId));
1888 return !!chunk && !chunk.replica && chunk.simulating;
1889 }
1890
1891 walkableFor (entityId, tileX, tileY)
1892 {
1893 const dim = this.#entityDimensionId(entityId);
1894 const handle = this.ecs.handleOf(entityId);
1895 if (this.#isFlying(handle))
1896 {
1897 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
1898 return !!data?.open;
1899 }
1900 // Entities pass through each other; only terrain / closed chunks block movement.
1901 return this.isEnterable(tileX, tileY, dim);
1902 }
1903
1904 /**
1905 * Standing tile with no other mob/player (self allowed). Used for wander goals
1906 * and melee attack stance.
1907 */
1908 isClearStanding (entityId, tileX, tileY)
1909 {
1910 const dim = this.#entityDimensionId(entityId);
1911 if (!this.isEnterable(tileX, tileY, dim))
1912 { return false; }
1913 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
1914 }
1915
1916 destroyEntity (entityId)
1917 {
1918 return this.#destroyEntity(entityId);
1919 }
1920
1921 occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
1922 {
1923 return this.#anyOccupant(tileX, tileY, dimensionId);
1924 }
1925
1926 #chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
1927 {
1928 return this.chunkIsSimulating(tileX, tileY, dimensionId);
1929 }
1930
1931 #chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
1932 {
1933 const loaded = this.chunks.get(chunkKey(chunkX, chunkY, dimensionId));
1934 if (loaded)
1935 { return loaded.data; }
1936 return createEmptyChunkData(this.settings.defaultGroundTypeId);
1937 }
1938
1939 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID)
1940 {
1941 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
1942 if (!data.open)
1943 { return false; }
1944 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1945 }
1946
1947 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
1948 {
1949 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
1950 if (!data.open)
1951 { return false; }
1952 return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));
1953 }
1954
1955 #walkableFor (entityId, tileX, tileY)
1956 {
1957 return this.walkableFor(entityId, tileX, tileY);
1958 }
1959
1960 #isFlying (handle)
1961 {
1962 if (handle == null)
1963 { return false; }
1964 const creature = this.ecs.get(handle, Component.creature);
1965 return !!mobDefinition(creature?.mobTypeId)?.flying;
1966 }
1967
1968 #entityDimensionId (entityId)
1969 {
1970 const handle = this.ecs.handleOf(entityId);
1971 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
1972 return normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
1973 }
1974
1975 #occupy (entityId, tileX, tileY)
1976 {
1977 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
1978 let set = this.occupancy.get(key);
1979 if (!set)
1980 {
1981 set = new Set();
1982 this.occupancy.set(key, set);
1983 }
1984 set.add(entityId);
1985 }
1986
1987 #vacate (entityId, tileX, tileY)
1988 {
1989 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
1990 const set = this.occupancy.get(key);
1991 if (!set)
1992 { return; }
1993 set.delete(entityId);
1994 if (set.size === 0)
1995 { this.occupancy.delete(key); }
1996 }
1997
1998 #anyOccupant (tileX, tileY, dimensionId = OVERWORLD_ID)
1999 {
2000 const key = tileKey(tileX, tileY, dimensionId);
2001 const local = this.occupancy.get(key);
2002 if (local?.size)
2003 { return local.values().next().value; }
2004 const ghosts = this.ghostOccupancy.get(key);
2005 if (ghosts?.size)
2006 { return ghosts.values().next().value; }
2007 return null;
2008 }
2009
2010 #hasOtherOccupant (entityId, tileX, tileY, dimensionId = null)
2011 {
2012 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : this.#entityDimensionId(entityId);
2013 const key = tileKey(tileX, tileY, dim);
2014 const local = this.occupancy.get(key);
2015 if (local)
2016 {
2017 for (const id of local)
2018 {
2019 if (id !== entityId)
2020 { return true; }
2021 }
2022 }
2023 const ghosts = this.ghostOccupancy.get(key);
2024 if (ghosts)
2025 {
2026 for (const id of ghosts)
2027 {
2028 if (id !== entityId)
2029 { return true; }
2030 }
2031 }
2032 return false;
2033 }
2034
2035 /** @deprecated use #anyOccupant — kept name for call sites expecting a single id */
2036 #occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
2037 {
2038 return this.#anyOccupant(tileX, tileY, dimensionId);
2039 }
2040}
2041
2042function pickWanderGoalInRange (world, entityId, originX, originY, range)
2043{
2044 const radius = Math.max(0, range | 0);
2045 for (let attempt = 0; attempt < 24; attempt++)
2046 {
2047 const tileX = originX + randInt(-radius, radius);
2048 const tileY = originY + randInt(-radius, radius);
2049 if (!world.isClearStanding(entityId, tileX, tileY))
2050 { continue; }
2051 return { tileX, tileY };
2052 }
2053 return null;
2054}
2055
2056function hasDialogueBrowsers (origin)
2057{
2058 const browsers = origin?.dialogueBrowsers;
2059 if (!browsers || typeof browsers !== "object")
2060 { return false; }
2061 return Object.keys(browsers).length > 0;
2062}
2063
2064function randInt (min, max)
2065{
2066 return min + Math.floor(Math.random() * (max - min + 1));
2067}
2068
2069export function replicaNeededForOwnedChunks (ownedChunkKeys)
2070{
2071 const needed = new Set();
2072 for (const key of ownedChunkKeys)
2073 {
2074 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2075 for (let dy = -1; dy <= 1; dy++)
2076 {
2077 for (let dx = -1; dx <= 1; dx++)
2078 {
2079 if (dx === 0 && dy === 0)
2080 { continue; }
2081 needed.add(chunkKey(chunkX + dx, chunkY + dy, dimensionId));
2082 }
2083 }
2084 }
2085 return needed;
2086}