BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

workerWorld.js 83.6 KiB Download Raw
1import { GAIT, VISIBLE_CHUNK_RADIUS, STATIC_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 tileIndex
13} from "../world/coordinates.js";
14import { cloneChunkData, createEmptyChunkData, isChunkTilePassable, isChunkTileClearForRangedAttacks } from "../world/chunkData.js";
15import { closedNeighborEdges } from "../world/chunkFlags.js";
16import { EcsWorld } from "../ecs/world.js";
17import { Component } from "../ecs/components.js";
18import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js";
19import { chunkBoundsAround, findPath } from "../navigation/astar.js";
20import { WorkerMessage } from "./protocol.js";
21import { collectSpawnRequests } from "./spawners.js";
22import { mobDefinition } from "../../../shared/definitions/mobs.js";
23import {
24 bagView,
25 applyBagView,
26 addGroundItem,
27 placeOrMergeGroundStack,
28 expireGroundItems,
29 groundItemsInChunk,
30 groundItemsInRegion,
31 handleItemCommand,
32 removeGroundItem,
33 publicGroundItem,
34 setGroundItemsForRegion,
35 stripCarriedCoinsForDeath
36} from "../items/bags.js";
37import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js";
38import { stepSummons } from "../spells/summons.js";
39import { stepJadeiteFairies } from "../spells/jadeiteFairy.js";
40import {
41 handleJewelryTeleportCommand,
42 stepJewelryTeleports,
43 cancelJewelryTeleport
44} from "../equipment/jewelryTeleport.js";
45import { publicSpellsView } from "../../../shared/spells/state.js";
46import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors, isDoorBlock } from "../doors/service.js";
47import {
48 entityDoorRequirementsAllow
49} from "../doors/conditionContext.js";
50import {
51 doorBlockedMessage,
52 doorHasRequirements
53} from "../../../shared/world/doorRequirements.js";
54import {
55 handleGatherCommand,
56 stepGather,
57 cancelGather,
58 clearOreRespawnsForChunk,
59 clearTreeRespawnsForChunk,
60 clearPlantRespawnsForChunk
61} from "../gathering/service.js";
62import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
63import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
64import { handleFishingCommand, stepFishing } from "../fishing/service.js";
65import { handleShearingCommand, stepShearing, originIsBusyPinned } from "../shearing/service.js";
66import { handleAlchemyCommand } from "../alchemy/service.js";
67import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
68import {
69 applyRemoteMeleeSwing,
70 applyRemoteRangedShot,
71 attackProfileOf,
72 clearAttackersTargeting,
73 clearEngage,
74 engageTarget,
75 ensureMobCombat,
76 isUntargetable,
77 queueMeleeApproach,
78 queueStandInRangeApproach,
79 resolveCombatTarget,
80 silenceDeadPlayer,
81 stepAggression,
82 stepCombat,
83 stepPassiveHealthRegen,
84 chebyshev,
85 tryArmStaffSpellAttack
86} from "../combat/service.js";
87import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
88import { SkillId } from "../../../shared/definitions/skills.js";
89import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
90import { passiveStaminaRegenMultiplier, dropAmuletInsteadOfCoins } from "../../../shared/equipment/jewelryEffects.js";
91import { JewelryItemId } from "../../../shared/definitions/jewelryItems.js";
92import { EQUIPMENT_SLOT } from "../../../shared/definitions/items.js";
93import { syncCharacterChunkPresence } from "../navigation/chunkPresence.js";
94import {
95 STAMINA_REGEN_PER_SECOND,
96 STAMINA_XP_PER_POINT_SPENT,
97 staminaCostPerRunStep,
98 publicStaminaView
99} from "../../../shared/stamina/rules.js";
100import {
101 stepCostForGround,
102 PATH_GROUND_STEP_COST,
103 SOFT_OCCUPIED_DWELL_MS
104} from "../../../shared/navigation/pathGround.js";
105import { canTalkOrShopNear } from "../../../shared/navigation/adjacency.js";
106import { objectPronoun } from "../../../shared/speech/pronouns.js";
107import { withCombatBackstepCost } from "../../../shared/navigation/combatPathCost.js";
108import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js";
109import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
110import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
111import { stepStatusEffects } from "../statusEffects/service.js";
112import { hasStatusEffect, StatusEffectType } from "../../../shared/statusEffects/rules.js";
113
114export class WorkerWorld
115{
116 constructor (workerId)
117 {
118 this.workerId = workerId;
119 this.ecs = new EcsWorld();
120 this.chunks = new Map();
121 this.ownedRegions = new Set();
122 this.occupancy = new Map();
123 this.ghosts = new Map();
124 this.ghostOccupancy = new Map();
125 this.characterEntities = new Map();
126 this.frozen = new Set();
127 this.groundItems = new Map();
128 this.groundByTile = new Map();
129 this.oreRespawns = new Map();
130 this.treeRespawns = new Map();
131 this.campfireExpires = new Map();
132 this.fireSessions = new Map();
133 this.fishingSpotRespawns = new Map();
134 this.fishSessions = new Map();
135 this.pendingSpellImpacts = [];
136 this.jadeiteFairyTimers = new Map();
137 this.jewelryTeleportSessions = new Map();
138 this.settings = { ...DEFAULT_WORLD_SETTINGS };
139 this.activeRevisionId = 1;
140 }
141
142 handle (message)
143 {
144 switch (message.type)
145 {
146 case WorkerMessage.configure:
147 return this.#configure(message);
148 case WorkerMessage.assignRegion:
149 return this.#assignRegion(message);
150 case WorkerMessage.dropRegion:
151 return this.#dropRegion(message);
152 case WorkerMessage.replaceRegionChunks:
153 return this.#replaceRegionChunks(message);
154 case WorkerMessage.setReplicas:
155 return this.#setReplicas(message);
156 case WorkerMessage.setSimulatingChunks:
157 return this.#setSimulatingChunks(message);
158 case WorkerMessage.setGhosts:
159 return this.#setGhosts(message);
160 case WorkerMessage.spawn:
161 return this.#spawn(message);
162 case WorkerMessage.despawn:
163 return this.#despawn(message.entityId);
164 case WorkerMessage.despawnCharacter:
165 return this.#despawnCharacter(message.characterId);
166 case WorkerMessage.reattachSession:
167 return this.#reattachSession(message.characterId, message.sessionId);
168 case WorkerMessage.command:
169 return this.#command(message);
170 case WorkerMessage.stepMovement:
171 return this.#stepMovement(message.now);
172 case WorkerMessage.stepSystems:
173 return this.#stepSystems(message.now, message.dt ?? (1 / 20));
174 case WorkerMessage.stepSpawners:
175 return { spawnRequests: collectSpawnRequests(this, Date.now()) };
176 case WorkerMessage.setGroundItems:
177 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
178 return { ok: true };
179 case WorkerMessage.inspectBag:
180 return this.#inspectBag(message.entityId);
181 case WorkerMessage.inspectSkills:
182 return this.#inspectSkills(message.entityId);
183 case WorkerMessage.inspectSpells:
184 return this.#inspectSpells(message.entityId);
185 case WorkerMessage.inspectStamina:
186 return this.#inspectStamina(message.entityId);
187 case WorkerMessage.applyBag:
188 return this.#applyBag(message.entityId, message.bag);
189 case WorkerMessage.applySkills:
190 return this.#applySkills(message.entityId, message.skills);
191 case WorkerMessage.applyAppearance:
192 return this.#applyAppearance(message.entityId, message.appearance);
193 case WorkerMessage.applySkullValue:
194 return this.#applySkullValue(message.entityId, message.skullValue);
195 case WorkerMessage.applyConditionAccess:
196 return this.#applyConditionAccess(message.entityId, message.conditionAccess);
197 case WorkerMessage.engageTarget:
198 return this.#engageTargetMessage(message);
199 case WorkerMessage.setSpellAutoCast:
200 return this.#setSpellAutoCast(message);
201 case WorkerMessage.inspectCombatState:
202 return this.#inspectCombatState(message.entityId);
203 case WorkerMessage.listTownGuardsNear:
204 return this.#listTownGuardsNear(message);
205 case WorkerMessage.updateFlight:
206 return this.#updateFlight(message.entityId, message.flight, message.now);
207 case WorkerMessage.chunkIsSimulating:
208 return this.chunkIsSimulating(message.tileX, message.tileY, message.dimensionId);
209 case WorkerMessage.applyTransfer:
210 return this.#applyTransfer(message);
211 case WorkerMessage.commitTransfer:
212 return this.#commitTransfer(message.entityId);
213 case WorkerMessage.abortTransfer:
214 return this.#abortTransfer(message.entityId);
215 case WorkerMessage.snapshotChunk:
216 return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly, message.dimensionId);
217 case WorkerMessage.listLoaders:
218 return this.#listLoaders();
219 case WorkerMessage.listPublicEntities:
220 return this.#listPublicEntities();
221 case WorkerMessage.entitiesInRegion:
222 return this.#entitiesInRegion(message.regionX, message.regionY, message.dimensionId);
223 case WorkerMessage.inspect:
224 return publicEntityView(this.ecs, message.entityId);
225 case WorkerMessage.remoteCombatEngage:
226 return this.#remoteCombatEngage(message);
227 case WorkerMessage.applyRemoteMelee:
228 return this.#applyRemoteMelee(message);
229 case WorkerMessage.applyRemoteRanged:
230 return this.#applyRemoteRanged(message);
231 case WorkerMessage.applyCombatHitXp:
232 return this.#applyCombatHitXp(message);
233 case WorkerMessage.spawnCorpseDrops:
234 return this.#spawnCorpseDrops(message);
235 case WorkerMessage.applyRespawn:
236 return this.#applyRespawn(message);
237 case WorkerMessage.relocateEntity:
238 return this.#relocateEntity(message);
239 case WorkerMessage.clearCombat:
240 {
241 clearEngage(this.ecs, message.entityId);
242 const handle = this.ecs.handleOf(message.entityId);
243 if (handle != null)
244 {
245 silenceDeadPlayer(this.ecs, handle);
246 cancelGather(this.ecs, handle);
247 clearFollow(this.ecs, message.entityId);
248 }
249 clearAttackersTargeting(this.ecs, message.targetEntityId ?? message.entityId);
250 return { ok: true };
251 }
252 case WorkerMessage.setItemLastSales:
253 {
254 this.itemLastSales = new Map();
255 for (const [key, sale] of Object.entries(message.sales ?? {}))
256 { this.itemLastSales.set(Number(key), sale); }
257 return { ok: true };
258 }
259 case WorkerMessage.stationExchangeClerk:
260 return this.#stationExchangeClerk(message);
261 case WorkerMessage.releaseExchangeClerk:
262 return this.#releaseExchangeClerk(message);
263 case WorkerMessage.pinDialogue:
264 return this.#pinDialogue(message.entityId, message.characterId);
265 case WorkerMessage.unpinDialogue:
266 return this.#unpinDialogue(message.entityId, message.characterId);
267 default:
268 throw new Error(`Unknown worker message ${message.type}`);
269 }
270 }
271
272 ownsRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
273 {
274 return this.ownedRegions.has(regionKey(regionX, regionY, dimensionId));
275 }
276
277 requireOwnedEntity (sessionId, characterId)
278 {
279 return this.#requireOwnedEntity(sessionId, characterId);
280 }
281
282 chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
283 {
284 return this.#chunkData(chunkX, chunkY, dimensionId);
285 }
286
287 blockTypeAt (tileX, tileY, dimensionId = OVERWORLD_ID)
288 {
289 const dim = normalizeDimensionId(dimensionId);
290 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
291 const block = data?.blocks?.[tileIndex(tileToLocal(tileX), tileToLocal(tileY))];
292 return block?.typeId ?? null;
293 }
294
295 #configure (message)
296 {
297 if (message.settings)
298 { this.settings = { ...this.settings, ...message.settings }; }
299 if (message.activeRevisionId != null)
300 { this.activeRevisionId = message.activeRevisionId; }
301 return { ok: true };
302 }
303
304 #assignRegion (message)
305 {
306 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
307 this.ownedRegions.add(regionKey(message.regionX, message.regionY, dim));
308 for (const chunk of message.chunks ?? [])
309 {
310 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
311 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
312 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
313 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
314 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY, chunkDim), {
315 data: cloneChunkData(chunk.data),
316 simulating: false,
317 replica: false,
318 dimensionId: chunkDim
319 });
320 }
321 return { ok: true };
322 }
323
324 #replaceRegionChunks (message)
325 {
326 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
327 for (const chunk of message.chunks ?? [])
328 {
329 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
330 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
331 const existing = this.chunks.get(key);
332 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
333 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
334 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
335 this.chunks.set(key, {
336 data: cloneChunkData(chunk.data),
337 simulating: existing?.simulating ?? false,
338 replica: existing?.replica ?? false,
339 dimensionId: chunkDim
340 });
341 }
342 return { ok: true };
343 }
344
345 #dropRegion (message)
346 {
347 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
348 const dropped = [];
349 for (const record of this.#entitiesInRegion(message.regionX, message.regionY, dim))
350 {
351 const components = record.payload?.components;
352 if (components?.creature && !components?.character && components?.health)
353 { components.health.current = components.health.max; }
354 dropped.push(record);
355 this.#destroyEntity(record.entityId);
356 }
357 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
358 for (const item of groundItems)
359 { removeGroundItem(this, item.groundItemId); }
360 for (const [key, chunk] of [...this.chunks.entries()])
361 {
362 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
363 if (chunk.replica)
364 { continue; }
365 if (dimensionId !== dim)
366 { continue; }
367 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
368 {
369 clearOreRespawnsForChunk(this, chunkX, chunkY, dimensionId);
370 clearTreeRespawnsForChunk(this, chunkX, chunkY, dimensionId);
371 clearPlantRespawnsForChunk(this, chunkX, chunkY, dimensionId);
372 this.chunks.delete(key);
373 }
374 }
375 this.ownedRegions.delete(regionKey(message.regionX, message.regionY, dim));
376 return { dropped, groundItems };
377 }
378
379 #setReplicas (message)
380 {
381 const keep = new Set();
382 for (const chunk of message.chunks ?? [])
383 {
384 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? OVERWORLD_ID);
385 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
386 keep.add(key);
387 const existing = this.chunks.get(key);
388 if (existing && !existing.replica)
389 { continue; }
390 this.chunks.set(key, {
391 data: cloneChunkData(chunk.data),
392 simulating: false,
393 replica: true,
394 dimensionId: chunkDim
395 });
396 }
397 for (const [key, chunk] of [...this.chunks.entries()])
398 {
399 if (chunk.replica && !keep.has(key))
400 { this.chunks.delete(key); }
401 }
402 return { ok: true };
403 }
404
405 #setSimulatingChunks (message)
406 {
407 const simulating = new Set(message.chunkKeys ?? []);
408 for (const [key, chunk] of this.chunks)
409 {
410 if (chunk.replica)
411 {
412 chunk.simulating = false;
413 continue;
414 }
415 chunk.simulating = simulating.has(key);
416 }
417 return { ok: true };
418 }
419
420 #setGhosts (message)
421 {
422 this.ghosts.clear();
423 this.ghostOccupancy.clear();
424 for (const ghost of message.ghosts ?? [])
425 {
426 this.ghosts.set(ghost.entityId, ghost);
427 const dim = normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID);
428 const key = tileKey(ghost.tileX, ghost.tileY, dim);
429 let set = this.ghostOccupancy.get(key);
430 if (!set)
431 {
432 set = new Set();
433 this.ghostOccupancy.set(key, set);
434 }
435 set.add(ghost.entityId);
436 }
437 return { ok: true };
438 }
439
440 #spawn (message)
441 {
442 const entityId = deserializeEntity(this.ecs, message);
443 const handle = this.ecs.handleOf(entityId);
444 const position = this.ecs.get(handle, Component.position);
445 if (!position)
446 {
447 this.ecs.destroy(handle);
448 throw new Error("Spawned entity is missing position.");
449 }
450 const flying = this.#isFlying(handle);
451 if (!flying)
452 {
453 if (this.#hasOtherOccupant(entityId, position.tileX, position.tileY))
454 {
455 this.ecs.destroy(handle);
456 const error = new Error("That tile is occupied.");
457 error.userFacing = true;
458 throw error;
459 }
460 this.#occupy(entityId, position.tileX, position.tileY);
461 }
462 const creature = this.ecs.get(handle, Component.creature);
463 const def = creature ? mobDefinition(creature.mobTypeId) : null;
464 if (def?.freeFlight)
465 { ensureFlightComponent(this.ecs, handle, position, def); }
466 const character = this.ecs.get(handle, Component.character);
467 if (character?.characterId)
468 {
469 this.characterEntities.set(character.characterId, entityId);
470 syncCharacterChunkPresence(this.ecs, handle, Date.now());
471 }
472 return publicEntityView(this.ecs, entityId);
473 }
474
475 #despawn (entityId)
476 {
477 return this.#destroyEntity(entityId);
478 }
479
480 #despawnCharacter (characterId)
481 {
482 releaseShopBrowsersForCharacter(this, characterId);
483 const entityId = this.characterEntities.get(characterId);
484 if (!entityId)
485 { return null; }
486 return this.#destroyEntity(entityId);
487 }
488
489 #reattachSession (characterId, sessionId)
490 {
491 const entityId = this.characterEntities.get(characterId | 0);
492 if (!entityId)
493 { return { ok: false }; }
494 const handle = this.ecs.handleOf(entityId);
495 if (handle == null)
496 { return { ok: false }; }
497 this.ecs.add(handle, Component.networkIdentity, { sessionId });
498 return { ok: true, entityId };
499 }
500
501 #destroyEntity (entityId)
502 {
503 const handle = this.ecs.handleOf(entityId);
504 if (handle == null)
505 { return null; }
506 const view = publicEntityView(this.ecs, entityId);
507 const position = this.ecs.get(handle, Component.position);
508 const character = this.ecs.get(handle, Component.character);
509 if (position && !this.#isFlying(handle))
510 { this.#vacate(entityId, position.tileX, position.tileY); }
511 if (character?.characterId)
512 { this.characterEntities.delete(character.characterId); }
513 this.frozen.delete(entityId);
514 this.ecs.destroy(handle);
515 return view;
516 }
517
518 #command (message)
519 {
520 const { sessionId, command } = message;
521 switch (command.type)
522 {
523 case "move-to":
524 return this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
525 case "set-gait":
526 return this.#setGait(sessionId, command.characterId, command.gait);
527 case "attack":
528 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
529 case "cancel-attack":
530 return this.#cancelAttack(sessionId, command.characterId);
531 case "interact":
532 return this.#interact(sessionId, command.characterId, command.targetEntityId, command.purpose);
533 case "follow":
534 return this.#follow(sessionId, command.characterId, command.targetEntityId);
535 case "cancel-follow":
536 return this.#cancelFollow(sessionId, command.characterId);
537 case "jewelry-teleport":
538 {
539 const jewelry = handleJewelryTeleportCommand(this, sessionId, command, message.now ?? Date.now());
540 if (jewelry)
541 { return jewelry; }
542 return { events: [] };
543 }
544 case "set-spell-favorite":
545 case "reorder-spell-favorites":
546 case "set-spell-autocast":
547 case "arm-spell":
548 case "cancel-arm-spell":
549 case "cast-spell-tile":
550 case "cast-spell-entity":
551 case "read-spellbook":
552 return handleSpellCommand(this, sessionId, command, message.now ?? Date.now()) ?? { events: [] };
553 default:
554 {
555 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
556 if (gather)
557 { return gather; }
558 const fire = handleFirestartingCommand(this, sessionId, command, message.now ?? Date.now());
559 if (fire)
560 { return fire; }
561 const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now());
562 if (fishing)
563 { return fishing; }
564 const shearing = handleShearingCommand(this, sessionId, command, message.now ?? Date.now());
565 if (shearing)
566 { return shearing; }
567 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
568 if (craft)
569 { return craft; }
570 const shop = handleShopCommand(this, sessionId, command, message.now ?? Date.now());
571 if (shop)
572 { return shop; }
573 const alchemy = handleAlchemyCommand(this, sessionId, command);
574 if (alchemy)
575 { return alchemy; }
576 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
577 return result ?? { events: [] };
578 }
579 }
580 }
581
582 #spawnCorpseDrops (message)
583 {
584 const events = [];
585 const drops = [...(message.drops ?? [])];
586 let privateBag = null;
587 if (message.dropCarriedCoins)
588 {
589 const entityId = this.characterEntities.get(message.characterId);
590 const handle = entityId != null ? this.ecs.handleOf(entityId) : null;
591 const equipment = handle != null ? this.ecs.get(handle, Component.equipment) : null;
592 if (dropAmuletInsteadOfCoins(equipment))
593 {
594 const amulet = equipment?.slots?.[EQUIPMENT_SLOT.amulet]
595 ?? equipment?.slots?.amulet
596 ?? null;
597 if (amulet && (amulet.itemId | 0) === JewelryItemId.rubyAmulet)
598 {
599 equipment.slots[EQUIPMENT_SLOT.amulet] = null;
600 if (message.coinGroundItemId != null)
601 {
602 drops.push({
603 groundItemId: message.coinGroundItemId,
604 stack: {
605 itemId: JewelryItemId.rubyAmulet,
606 quantity: 1,
607 origins: amulet.origins ?? []
608 }
609 });
610 }
611 privateBag = bagView(this.ecs, handle);
612 }
613 }
614 else
615 {
616 const stripped = stripCarriedCoinsForDeath(this, message.characterId);
617 privateBag = stripped.private;
618 if (stripped.stack && message.coinGroundItemId != null)
619 {
620 drops.push({
621 groundItemId: message.coinGroundItemId,
622 stack: stripped.stack
623 });
624 }
625 }
626 }
627 for (const drop of drops)
628 {
629 const stack = drop.stack ?? { itemId: drop.itemId, quantity: 1 };
630 const placed = placeOrMergeGroundStack(this, {
631 tileX: message.tileX,
632 tileY: message.tileY,
633 stack,
634 now: message.now,
635 source: "player-death",
636 droppedByCharacterId: message.characterId,
637 groundItemId: drop.groundItemId
638 });
639 events.push(...placed.events);
640 }
641 return { events, private: privateBag };
642 }
643
644 #applyRespawn (message)
645 {
646 const handle = this.ecs.handleOf(message.entityId);
647 if (handle == null || !this.ecs.has(handle, Component.dead))
648 { return { accepted: false }; }
649 const position = this.ecs.get(handle, Component.position);
650 const fromTileX = position.tileX;
651 const fromTileY = position.tileY;
652 const fromDimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
653 const dimensionId = normalizeDimensionId(message.dimensionId ?? fromDimensionId);
654 const health = this.ecs.get(handle, Component.health);
655 const stamina = this.ecs.get(handle, Component.stamina);
656 if (health)
657 {
658 health.max = message.maxHealth;
659 health.current = message.maxHealth;
660 }
661 if (stamina)
662 {
663 stamina.max = message.maxStamina;
664 stamina.current = message.maxStamina;
665 }
666 else
667 { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); }
668 this.ecs.remove(handle, Component.dead);
669 clearEngage(this.ecs, message.entityId);
670 const path = this.ecs.get(handle, Component.path);
671 if (path)
672 { path.tiles = []; }
673 clearFollow(this.ecs, message.entityId);
674
675 const destRegionX = tileToRegion(message.tileX);
676 const destRegionY = tileToRegion(message.tileY);
677 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
678 {
679 this.frozen.add(message.entityId);
680 const payload = serializeEntity(this.ecs, message.entityId);
681 payload.components.position.tileX = message.tileX | 0;
682 payload.components.position.tileY = message.tileY | 0;
683 payload.components.position.dimensionId = dimensionId;
684 return {
685 accepted: true,
686 transferRequest: {
687 entityId: message.entityId,
688 fromTileX,
689 fromTileY,
690 fromDimensionId,
691 destTileX: message.tileX,
692 destTileY: message.tileY,
693 toRegionX: destRegionX,
694 toRegionY: destRegionY,
695 dimensionId,
696 payload
697 }
698 };
699 }
700 if (!this.isEnterable(message.tileX, message.tileY, dimensionId))
701 { return { accepted: false }; }
702 this.#vacate(message.entityId, fromTileX, fromTileY);
703 position.tileX = message.tileX;
704 position.tileY = message.tileY;
705 position.dimensionId = dimensionId;
706 syncCharacterChunkPresence(this.ecs, handle, Date.now());
707 this.#occupy(message.entityId, position.tileX, position.tileY);
708 return {
709 accepted: true,
710 event: {
711 type: "entity-move",
712 entityId: message.entityId,
713 fromTileX,
714 fromTileY,
715 fromDimensionId,
716 tileX: position.tileX,
717 tileY: position.tileY,
718 dimensionId,
719 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
720 }
721 };
722 }
723
724 /** Move an entity to a tile/dimension; clears path and updates occupancy. */
725 #relocateEntity (message)
726 {
727 const handle = this.ecs.handleOf(message.entityId);
728 if (handle == null)
729 { return { accepted: false }; }
730 const position = this.ecs.get(handle, Component.position);
731 if (!position)
732 { return { accepted: false }; }
733 const fromTileX = position.tileX;
734 const fromTileY = position.tileY;
735 const fromDimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
736 const destTileX = message.tileX | 0;
737 const destTileY = message.tileY | 0;
738 const dimensionId = normalizeDimensionId(message.dimensionId ?? fromDimensionId);
739
740 clearEngage(this.ecs, message.entityId);
741 const path = this.ecs.get(handle, Component.path);
742 if (path)
743 { path.tiles = []; }
744 clearFollow(this.ecs, message.entityId);
745
746 const destRegionX = tileToRegion(destTileX);
747 const destRegionY = tileToRegion(destTileY);
748 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
749 {
750 this.frozen.add(message.entityId);
751 const payload = serializeEntity(this.ecs, message.entityId);
752 if (payload.components?.position)
753 {
754 payload.components.position.tileX = destTileX;
755 payload.components.position.tileY = destTileY;
756 payload.components.position.dimensionId = dimensionId;
757 }
758 return {
759 accepted: true,
760 transferRequest: {
761 entityId: message.entityId,
762 fromTileX,
763 fromTileY,
764 fromDimensionId,
765 destTileX,
766 destTileY,
767 toRegionX: destRegionX,
768 toRegionY: destRegionY,
769 dimensionId,
770 payload
771 }
772 };
773 }
774 if (!this.isEnterable(destTileX, destTileY, dimensionId))
775 { return { accepted: false }; }
776 if (!this.#isFlying(handle))
777 { this.#vacate(message.entityId, fromTileX, fromTileY); }
778 position.tileX = destTileX;
779 position.tileY = destTileY;
780 position.dimensionId = dimensionId;
781 syncCharacterChunkPresence(this.ecs, handle, Date.now());
782 if (!this.#isFlying(handle))
783 { this.#occupy(message.entityId, destTileX, destTileY); }
784 return {
785 accepted: true,
786 event: {
787 type: "entity-move",
788 entityId: message.entityId,
789 fromTileX,
790 fromTileY,
791 fromDimensionId,
792 tileX: destTileX,
793 tileY: destTileY,
794 dimensionId,
795 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
796 }
797 };
798 }
799
800 #inspectBag (entityId)
801 {
802 const handle = this.ecs.handleOf(entityId);
803 if (handle == null)
804 { return null; }
805 return bagView(this.ecs, handle);
806 }
807
808 #inspectSkills (entityId)
809 {
810 const handle = this.ecs.handleOf(entityId);
811 if (handle == null)
812 { return null; }
813 const skills = this.ecs.get(handle, Component.skills);
814 if (!skills?.xp)
815 { return null; }
816 return skills;
817 }
818
819 #inspectSpells (entityId)
820 {
821 const handle = this.ecs.handleOf(entityId);
822 if (handle == null)
823 { return null; }
824 const spells = this.ecs.get(handle, Component.spells);
825 const skills = this.ecs.get(handle, Component.skills);
826 const casting = this.ecs.get(handle, Component.spellcasting);
827 if (!spells)
828 { return null; }
829 return {
830 spells: publicSpellsView(spells, skills),
831 favorites: Array.isArray(spells.favorites) ? [...spells.favorites] : [],
832 autoCast: !!spells.autoCast,
833 armedSpellId: casting?.armedSpellId ?? null
834 };
835 }
836
837 #setSpellAutoCast (message)
838 {
839 const entityId = message.entityId != null
840 ? message.entityId
841 : this.characterEntities.get(message.characterId | 0);
842 const handle = entityId != null ? this.ecs.handleOf(entityId) : null;
843 if (handle == null)
844 { return { ok: false }; }
845 const spells = this.ecs.get(handle, Component.spells);
846 if (!spells)
847 { return { ok: false }; }
848 const previous = !!spells.autoCast;
849 spells.autoCast = !!message.autoCast;
850 return { ok: true, previousAutoCast: previous, autoCast: !!spells.autoCast };
851 }
852
853 #inspectCombatState (entityId)
854 {
855 const handle = this.ecs.handleOf(entityId);
856 if (handle == null)
857 { return null; }
858 const combat = this.ecs.get(handle, Component.combat);
859 const casting = this.ecs.get(handle, Component.spellcasting);
860 const character = this.ecs.get(handle, Component.character);
861 const dead = this.ecs.has(handle, Component.dead);
862 const targetId = combat?.targetEntityId ?? null;
863 const repeatTargetId = casting?.repeatTargetEntityId ?? null;
864 const pendingTargetId = casting?.pendingCast?.targetEntityId ?? null;
865 const inCombat = !dead && !!(targetId != null
866 || repeatTargetId != null
867 || (casting?.pendingCast && (pendingTargetId != null
868 || casting.pendingCast.tileX != null)));
869 return {
870 characterId: character?.characterId ?? null,
871 inCombat,
872 dead,
873 targetEntityId: targetId,
874 repeatTargetEntityId: repeatTargetId,
875 pendingTargetEntityId: pendingTargetId
876 };
877 }
878
879 #inspectStamina (entityId)
880 {
881 const handle = this.ecs.handleOf(entityId);
882 if (handle == null)
883 { return null; }
884 const stamina = this.ecs.get(handle, Component.stamina);
885 const movement = this.ecs.get(handle, Component.movement);
886 if (!stamina)
887 { return null; }
888 return {
889 ...publicStaminaView(stamina),
890 gait: movement?.gait ?? GAIT.walk
891 };
892 }
893
894 #applyBag (entityId, bag)
895 {
896 const handle = this.ecs.handleOf(entityId);
897 if (handle == null)
898 { return null; }
899 return applyBagView(this.ecs, handle, bag);
900 }
901
902 #applySkills (entityId, skills)
903 {
904 const handle = this.ecs.handleOf(entityId);
905 if (handle == null)
906 { return null; }
907 if (!skills?.xp || typeof skills.xp !== "object")
908 { return null; }
909 const current = this.ecs.get(handle, Component.skills);
910 if (current)
911 { Object.assign(current, structuredClone(skills)); }
912 else
913 { this.ecs.add(handle, Component.skills, structuredClone(skills)); }
914 return { ok: true };
915 }
916
917 #applyAppearance (entityId, appearancePatch)
918 {
919 const handle = this.ecs.handleOf(entityId);
920 if (handle == null)
921 { return null; }
922 const appearance = this.ecs.get(handle, Component.appearance);
923 if (!appearance)
924 { return null; }
925 Object.assign(appearance, appearancePatch ?? {});
926 return publicEntityView(this.ecs, entityId);
927 }
928
929 #applySkullValue (entityId, skullValue)
930 {
931 const handle = this.ecs.handleOf(entityId);
932 if (handle == null)
933 { return null; }
934 const character = this.ecs.get(handle, Component.character);
935 if (!character)
936 { return null; }
937 character.skullValue = Math.max(0, skullValue | 0);
938 return { ok: true, skullValue: character.skullValue };
939 }
940
941 #applyConditionAccess (entityId, conditionAccess)
942 {
943 const handle = this.ecs.handleOf(entityId);
944 if (handle == null)
945 { return null; }
946 if (!this.ecs.get(handle, Component.character))
947 { return null; }
948 const next = conditionAccess && typeof conditionAccess === "object"
949 ? structuredClone(conditionAccess)
950 : {
951 questStates: {},
952 questProgress: {},
953 dialogueHeard: [],
954 dialogueTriggers: [],
955 visitedDimensions: []
956 };
957 if (this.ecs.has(handle, Component.conditionAccess))
958 { Object.assign(this.ecs.get(handle, Component.conditionAccess), next); }
959 else
960 { this.ecs.add(handle, Component.conditionAccess, next); }
961 return { ok: true };
962 }
963
964 /**
965 * Toast when a player walks into a door they fail requirements for.
966 * Debounced per door tile so movement ticks do not spam.
967 */
968 #doorRequirementBlockedToast (entityId, tileX, tileY, now = Date.now())
969 {
970 const handle = this.ecs.handleOf(entityId);
971 if (handle == null)
972 { return null; }
973 const character = this.ecs.get(handle, Component.character);
974 if (!character?.characterId)
975 { return null; }
976 const dimensionId = this.#entityDimensionId(entityId);
977 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
978 const block = data?.blocks?.[tileIndex(tileToLocal(tileX), tileToLocal(tileY))];
979 if (!isDoorBlock(block) || !doorHasRequirements(block))
980 { return null; }
981 if (entityDoorRequirementsAllow(this, entityId, tileX, tileY))
982 { return null; }
983 if (!this.doorBlockToastAt)
984 { this.doorBlockToastAt = new Map(); }
985 const key = `${character.characterId}|${tileKey(tileX, tileY, dimensionId)}`;
986 const last = this.doorBlockToastAt.get(key);
987 if (last != null && now - last < 2500)
988 { return null; }
989 this.doorBlockToastAt.set(key, now);
990 return {
991 type: "toast",
992 characterId: character.characterId,
993 message: doorBlockedMessage(block)
994 };
995 }
996
997 #updateFlight (entityId, flightPatch, now = Date.now())
998 {
999 const handle = this.ecs.handleOf(entityId);
1000 if (handle == null)
1001 { return null; }
1002 let flight = this.ecs.get(handle, Component.flight);
1003 if (!flight)
1004 { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); }
1005 else
1006 { Object.assign(flight, flightPatch); }
1007 const position = this.ecs.get(handle, Component.position);
1008 const movement = this.ecs.get(handle, Component.movement);
1009 const fromTileX = position.tileX;
1010 const fromTileY = position.tileY;
1011 const tileX = Math.floor(flight.x);
1012 const tileY = Math.floor(flight.y);
1013 position.tileX = tileX;
1014 position.tileY = tileY;
1015 syncCharacterChunkPresence(this.ecs, handle, now);
1016 const destRegionX = tileToRegion(tileX);
1017 const destRegionY = tileToRegion(tileY);
1018 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
1019 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
1020 {
1021 this.frozen.add(entityId);
1022 return {
1023 transferRequest: {
1024 type: "transfer-request",
1025 entityId,
1026 fromTileX,
1027 fromTileY,
1028 destTileX: tileX,
1029 destTileY: tileY,
1030 toRegionX: destRegionX,
1031 toRegionY: destRegionY,
1032 dimensionId
1033 }
1034 };
1035 }
1036 const dt = flight.lastAt && now > flight.lastAt
1037 ? Math.min(0.25, (now - flight.lastAt) / 1000)
1038 : 1 / 20;
1039 return {
1040 event: {
1041 type: "entity-move",
1042 entityId,
1043 fromTileX,
1044 fromTileY,
1045 tileX,
1046 tileY,
1047 worldX: flight.x,
1048 worldY: flight.y,
1049 gait: movement?.gait ?? "walk",
1050 lerpMs: Math.max(50, Math.round(dt * 1000)),
1051 freeFlight: true
1052 }
1053 };
1054 }
1055
1056 #moveTo (sessionId, characterId, tileX, tileY)
1057 {
1058 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
1059 if (this.frozen.has(entityId))
1060 { return { events: [] }; }
1061 clearEngage(this.ecs, entityId);
1062 clearFollow(this.ecs, entityId);
1063 cancelGather(this.ecs, handle);
1064 cancelJewelryTeleport(this, characterId);
1065 clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting));
1066 const position = this.ecs.get(handle, Component.position);
1067 const movement = this.ecs.get(handle, Component.movement);
1068 let path = this.ecs.get(handle, Component.path);
1069 if (!path)
1070 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
1071 // Match the static map ring (long vision): clicks outside the 3×3 entity view still path.
1072 const bounds = chunkBoundsAround(position.tileX, position.tileY, STATIC_CHUNK_RADIUS);
1073 path.tiles = findPath(
1074 position.tileX,
1075 position.tileY,
1076 tileX,
1077 tileY,
1078 (x, y) => this.walkableFor(entityId, x, y),
1079 bounds.minX,
1080 bounds.minY,
1081 bounds.maxX,
1082 bounds.maxY,
1083 this.pathfindOptions({ preferVertical: true, preferPaths: true, entityId })
1084 );
1085 movement.walkCarry = 0;
1086 const events = [];
1087 /** Open immediately when the next step is a door (player already adjacent). */
1088 const first = path.tiles[0];
1089 if (first)
1090 {
1091 const doorDelta = maybeOpenDoorOnApproach(this, entityId, first.x, first.y);
1092 if (doorDelta)
1093 { events.push(doorDelta); }
1094 }
1095 return { events };
1096 }
1097
1098 #attack (sessionId, characterId, targetEntityId, now)
1099 {
1100 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
1101 if (targetEntityId === entityId)
1102 {
1103 const error = new Error("Cannot attack yourself.");
1104 error.userFacing = true;
1105 throw error;
1106 }
1107 const target = resolveCombatTarget(this, targetEntityId);
1108 if (!target)
1109 {
1110 const error = new Error("Target is not here.");
1111 error.userFacing = true;
1112 throw error;
1113 }
1114 if (target.health && target.health.current <= 0)
1115 {
1116 const error = new Error("That cannot be attacked.");
1117 error.userFacing = true;
1118 throw error;
1119 }
1120 if (!this.ecs.get(handle, Component.combat))
1121 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
1122 clearFollow(this.ecs, entityId);
1123 cancelGather(this.ecs, handle);
1124 // Staff + favorite attack spell: hold spell range via auto-cast (same as retaliate).
1125 if (tryArmStaffSpellAttack(this.ecs, entityId, targetEntityId))
1126 { return { events: [] }; }
1127 clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting));
1128 engageTarget(this.ecs, entityId, targetEntityId, now);
1129 const position = this.ecs.get(handle, Component.position);
1130 const profile = attackProfileOf(this.ecs, handle);
1131 if (position && target.pos)
1132 {
1133 if (profile.mode === "ranged")
1134 {
1135 queueStandInRangeApproach(
1136 this,
1137 entityId,
1138 handle,
1139 position,
1140 target.pos.tileX,
1141 target.pos.tileY,
1142 profile.rangeTiles | 0 || COMBAT_RANGE_TILES,
1143 1
1144 );
1145 }
1146 else if (profile.mode === "melee")
1147 {
1148 queueMeleeApproach(this, entityId, handle, position, target.pos);
1149 }
1150 }
1151 return { events: [] };
1152 }
1153
1154 #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })
1155 {
1156 // Kept for cross-worker hooks; retaliation happens on swing resolution, not Attack click.
1157 void attackerEntityId;
1158 void targetEntityId;
1159 void now;
1160 return { events: [] };
1161 }
1162
1163 #engageTargetMessage ({ attackerEntityId, targetEntityId, now = Date.now() })
1164 {
1165 if (this.ecs.handleOf(attackerEntityId) == null)
1166 { return { ok: false }; }
1167 engageTarget(this.ecs, attackerEntityId, targetEntityId, now);
1168 return { ok: true };
1169 }
1170
1171 /**
1172 * Idle town-guard entity ids from spawners whose wander range covers (tileX, tileY).
1173 * Optionally restrict to one spawnerId.
1174 */
1175 #listTownGuardsNear ({ tileX, tileY, spawnerId = null, limit = 8 })
1176 {
1177 const guards = [];
1178 for (const entity of this.ecs.query(Component.spawnOrigin, Component.creature, Component.combat, Component.position))
1179 {
1180 if (!entity.spawnOrigin?.townGuard)
1181 { continue; }
1182 if (spawnerId != null && entity.spawnOrigin.spawnerId !== spawnerId)
1183 { continue; }
1184 const originX = entity.spawnOrigin.originTileX;
1185 const originY = entity.spawnOrigin.originTileY;
1186 const range = entity.spawnOrigin.wanderRangeTiles | 0;
1187 const dx = Math.abs(tileX - originX);
1188 const dy = Math.abs(tileY - originY);
1189 if (Math.max(dx, dy) > range)
1190 { continue; }
1191 const health = this.ecs.get(entity.handle, Component.health);
1192 if (health && health.current <= 0)
1193 { continue; }
1194 if (this.ecs.has(entity.handle, Component.dead))
1195 { continue; }
1196 guards.push({
1197 entityId: entity.entityId,
1198 spawnerId: entity.spawnOrigin.spawnerId,
1199 busy: entity.combat?.targetEntityId != null
1200 });
1201 if (guards.length >= limit)
1202 { break; }
1203 }
1204 return { guards };
1205 }
1206
1207 #applyRemoteMelee (payload)
1208 {
1209 return applyRemoteMeleeSwing(this, payload);
1210 }
1211
1212 #applyRemoteRanged (payload)
1213 {
1214 return applyRemoteRangedShot(this, payload);
1215 }
1216
1217 #applyCombatHitXp ({ entityId, profile, damage })
1218 {
1219 const handle = this.ecs.handleOf(entityId);
1220 if (handle == null)
1221 { return { events: [] }; }
1222 const character = this.ecs.get(handle, Component.character);
1223 if (!character)
1224 { return { events: [] }; }
1225 const xpAward = awardCombatHitXp(this.ecs, handle, profile, damage);
1226 if (!xpAward)
1227 { return { events: [] }; }
1228 return {
1229 events: [{
1230 type: "skills-updated",
1231 entityId,
1232 characterId: character.characterId,
1233 skills: xpAward.skills,
1234 combatLevel: xpAward.combatLevel,
1235 stored: xpAward.stored,
1236 levelUps: xpAward.levelUps ?? []
1237 }]
1238 };
1239 }
1240
1241 #cancelAttack (sessionId, characterId)
1242 {
1243 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
1244 clearEngage(this.ecs, entityId);
1245 clearSpellAutoRepeat(this.ecs.get(handle, Component.spellcasting));
1246 return { events: [] };
1247 }
1248
1249 #interact (sessionId, characterId, targetEntityId, purpose = null)
1250 {
1251 this.#requireOwnedEntity(sessionId, characterId);
1252 const targetHandle = this.ecs.handleOf(targetEntityId);
1253 if (targetHandle == null)
1254 {
1255 const error = new Error("Target is not here.");
1256 error.userFacing = true;
1257 throw error;
1258 }
1259 if (isUntargetable(this.ecs, targetHandle))
1260 {
1261 const error = new Error("Nothing to say.");
1262 error.userFacing = true;
1263 throw error;
1264 }
1265 const playerEntityId = this.characterEntities.get(characterId);
1266 const playerHandle = this.ecs.handleOf(playerEntityId);
1267 const playerPos = playerHandle != null ? this.ecs.get(playerHandle, Component.position) : null;
1268 const npcPos = this.ecs.get(targetHandle, Component.position);
1269 const playerDim = normalizeDimensionId(playerPos?.dimensionId ?? OVERWORLD_ID);
1270 const npcDim = normalizeDimensionId(npcPos?.dimensionId ?? OVERWORLD_ID);
1271 if (!playerPos || !npcPos || playerDim !== npcDim
1272 || !canTalkOrShopNear(
1273 playerPos.tileX,
1274 playerPos.tileY,
1275 npcPos.tileX,
1276 npcPos.tileY,
1277 (x, y) => this.blockTypeAt(x, y, npcDim)
1278 ))
1279 {
1280 const appearance = this.ecs.get(targetHandle, Component.appearance);
1281 const sex = appearance?.sex === "female" ? "female" : "male";
1282 const error = new Error(`You need to stand next to ${objectPronoun(sex)}.`);
1283 error.userFacing = true;
1284 throw error;
1285 }
1286 const creature = this.ecs.get(targetHandle, Component.creature);
1287 const def = creature ? mobDefinition(creature.mobTypeId) : null;
1288 const shop = this.ecs.get(targetHandle, Component.shop);
1289 const hasShop = shopHasInterface(shop);
1290 const origin = this.ecs.get(targetHandle, Component.spawnOrigin);
1291 const dialogueId = origin?.dialogueId ? String(origin.dialogueId) : "";
1292 const intent = purpose === "shop" || purpose === "talk" ? purpose : null;
1293
1294 if (intent === "shop" && hasShop)
1295 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1296 if (intent === "talk" && dialogueId)
1297 {
1298 // Pin in-worker before return so wander cannot start before the sim thread pins.
1299 this.#pinDialogue(targetEntityId, characterId);
1300 return {
1301 events: [{
1302 type: "open-dialogue",
1303 sessionId,
1304 characterId,
1305 entityId: targetEntityId,
1306 dialogueId
1307 }]
1308 };
1309 }
1310 if (intent === "talk" && hasShop)
1311 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1312
1313 // Default click: prefer dialogue when assigned, else shop, else talkable no-op.
1314 if (dialogueId)
1315 {
1316 this.#pinDialogue(targetEntityId, characterId);
1317 return {
1318 events: [{
1319 type: "open-dialogue",
1320 sessionId,
1321 characterId,
1322 entityId: targetEntityId,
1323 dialogueId
1324 }]
1325 };
1326 }
1327 if (hasShop)
1328 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1329 if (!def?.talkable)
1330 {
1331 const error = new Error("They have nothing to say.");
1332 error.userFacing = true;
1333 throw error;
1334 }
1335 return { events: [] };
1336 }
1337
1338 #follow (sessionId, characterId, targetEntityId)
1339 {
1340 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
1341 const targetHandle = this.ecs.handleOf(targetEntityId);
1342 if (targetHandle == null)
1343 {
1344 const error = new Error("Target is not here.");
1345 error.userFacing = true;
1346 throw error;
1347 }
1348 if (targetEntityId === entityId)
1349 {
1350 const error = new Error("Cannot follow yourself.");
1351 error.userFacing = true;
1352 throw error;
1353 }
1354 if (!this.ecs.get(targetHandle, Component.position))
1355 {
1356 const error = new Error("That cannot be followed.");
1357 error.userFacing = true;
1358 throw error;
1359 }
1360 clearEngage(this.ecs, entityId);
1361 setFollow(this.ecs, entityId, targetEntityId);
1362 const path = this.ecs.get(handle, Component.path);
1363 if (path)
1364 { path.tiles = []; }
1365 return { events: [] };
1366 }
1367
1368 #cancelFollow (sessionId, characterId)
1369 {
1370 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
1371 clearFollow(this.ecs, entityId);
1372 return { events: [] };
1373 }
1374
1375 #setGait (sessionId, characterId, gait)
1376 {
1377 if (gait !== GAIT.walk && gait !== GAIT.run)
1378 {
1379 const error = new Error("Gait must be walk or run.");
1380 error.userFacing = true;
1381 throw error;
1382 }
1383 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
1384 const movement = this.ecs.get(handle, Component.movement);
1385 const stamina = this.ecs.get(handle, Component.stamina);
1386 if (gait === GAIT.run && !(Number(stamina?.current) > 0))
1387 {
1388 const error = new Error("You are too exhausted to run.");
1389 error.userFacing = true;
1390 throw error;
1391 }
1392 movement.gait = gait;
1393 const character = this.ecs.get(handle, Component.character);
1394 return {
1395 events: character
1396 ? [this.#staminaEvent(handle, character.characterId, movement.gait)]
1397 : []
1398 };
1399 }
1400
1401 #staminaEvent (handle, characterId, gait = null)
1402 {
1403 const stamina = this.ecs.get(handle, Component.stamina);
1404 const movement = this.ecs.get(handle, Component.movement);
1405 return {
1406 type: "stamina",
1407 characterId,
1408 ...publicStaminaView(stamina),
1409 gait: gait ?? movement?.gait ?? GAIT.walk
1410 };
1411 }
1412
1413 #consumeRunStamina (handle, events)
1414 {
1415 const character = this.ecs.get(handle, Component.character);
1416 if (!character)
1417 { return; }
1418 let stamina = this.ecs.get(handle, Component.stamina);
1419 if (!stamina)
1420 {
1421 stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 });
1422 }
1423 const skills = this.ecs.get(handle, Component.skills);
1424 syncPlayerStamina(this.ecs, handle);
1425 const position = this.ecs.get(handle, Component.position);
1426 const onPath = position
1427 ? this.groundTypeAt(position.tileX, position.tileY, position.dimensionId) === GroundType.path
1428 : false;
1429 const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond, { onPath });
1430 stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost);
1431 stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost;
1432 let skillsChanged = false;
1433 const levelUps = [];
1434 while (stamina.xpDebt >= 1 && skills?.xp)
1435 {
1436 stamina.xpDebt -= 1;
1437 const result = applySkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT);
1438 if (result.changed)
1439 {
1440 skillsChanged = true;
1441 syncPlayerStamina(this.ecs, handle);
1442 }
1443 if (result.levelUp)
1444 { levelUps.push(result.levelUp); }
1445 }
1446 const movement = this.ecs.get(handle, Component.movement);
1447 if (stamina.current <= 0 && movement)
1448 {
1449 stamina.current = 0;
1450 movement.gait = GAIT.walk;
1451 }
1452 events.push(this.#staminaEvent(handle, character.characterId));
1453 if (skillsChanged)
1454 {
1455 events.push({
1456 type: "skills-updated",
1457 entityId: this.ecs.entityIdOf(handle),
1458 characterId: character.characterId,
1459 ...publicSkillsPayload(skills),
1460 stored: storedSkillXp(skills),
1461 levelUps
1462 });
1463 }
1464 }
1465
1466 #regenStamina (dt, events)
1467 {
1468 if (!(dt > 0))
1469 { return; }
1470 for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement))
1471 {
1472 const { handle, character, stamina, movement } = entity;
1473 if (this.ecs.has(handle, Component.dead))
1474 { continue; }
1475 const status = this.ecs.get(handle, Component.statusEffects);
1476 if (hasStatusEffect(status, StatusEffectType.staminaBlock, Date.now()))
1477 { continue; }
1478 // Run gait only blocks regen while actually stepping along a path.
1479 const path = this.ecs.get(handle, Component.path);
1480 if (movement.gait === GAIT.run && path?.tiles?.length)
1481 { continue; }
1482 syncPlayerStamina(this.ecs, handle);
1483 const before = Number(stamina.current) || 0;
1484 if (before >= stamina.max)
1485 { continue; }
1486 stamina.current = Math.min(
1487 stamina.max,
1488 before + dt * STAMINA_REGEN_PER_SECOND * passiveStaminaRegenMultiplier(
1489 this.ecs.get(handle, Component.equipment)
1490 )
1491 );
1492 const after = Number(stamina.current) || 0;
1493 // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
1494 if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
1495 { events.push(this.#staminaEvent(handle, character.characterId)); }
1496 }
1497 }
1498
1499 #requireOwnedEntity (sessionId, characterId)
1500 {
1501 const entityId = this.characterEntities.get(characterId);
1502 if (!entityId)
1503 {
1504 const error = new Error("Character is not in the world.");
1505 error.userFacing = true;
1506 throw error;
1507 }
1508 const handle = this.ecs.handleOf(entityId);
1509 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
1510 if (!identity || identity.sessionId !== sessionId)
1511 {
1512 const error = new Error("Character is not in the world.");
1513 error.userFacing = true;
1514 throw error;
1515 }
1516 if (this.ecs.has(handle, Component.dead))
1517 {
1518 const error = new Error("You are dead.");
1519 error.userFacing = true;
1520 throw error;
1521 }
1522 return { handle, entityId };
1523 }
1524
1525 #stepSystems (now = Date.now(), dt = 1 / 20)
1526 {
1527 const events = [];
1528 const transferRequests = [];
1529 this.#regenStamina(dt, events);
1530 events.push(...stepStatusEffects(this, now, dt));
1531 events.push(...stepPassiveHealthRegen(this, now, dt));
1532 const flight = stepFreeFlight(this, now);
1533 for (const event of flight)
1534 {
1535 if (event.type === "transfer-request")
1536 {
1537 const payload = serializeEntity(this.ecs, event.entityId);
1538 transferRequests.push({
1539 entityId: event.entityId,
1540 fromTileX: event.fromTileX,
1541 fromTileY: event.fromTileY,
1542 destTileX: event.destTileX,
1543 destTileY: event.destTileY,
1544 toRegionX: event.toRegionX,
1545 toRegionY: event.toRegionY,
1546 dimensionId: event.dimensionId ?? OVERWORLD_ID,
1547 payload
1548 });
1549 continue;
1550 }
1551 events.push(event);
1552 }
1553 stepAggression(this, now);
1554 events.push(...stepCombat(this, now));
1555 events.push(...stepPendingSpellCast(this, now));
1556 events.push(...processSpellImpacts(this, now));
1557 events.push(...stepSpellAutoCast(this, now));
1558 events.push(...tickSpellLights(this, now));
1559 const summons = stepSummons(this, now);
1560 events.push(...(summons.events ?? []));
1561 for (const entityId of summons.despawnIds ?? [])
1562 {
1563 const dropped = this.#destroyEntity(entityId);
1564 if (dropped)
1565 { events.push({ type: "entity-despawn", entityId }); }
1566 }
1567 const fairies = stepJadeiteFairies(this, now);
1568 events.push(...(fairies.events ?? []));
1569 for (const entityId of fairies.despawnIds ?? [])
1570 {
1571 const dropped = this.#destroyEntity(entityId);
1572 if (dropped)
1573 { events.push({ type: "entity-despawn", entityId }); }
1574 }
1575 events.push(...stepJewelryTeleports(this, now).events);
1576 stepFollow(this);
1577 const gather = stepGather(this, now);
1578 events.push(...gather.events);
1579 for (const entry of gather.privates ?? [])
1580 {
1581 events.push({
1582 type: "inventory",
1583 characterId: entry.characterId,
1584 ...entry.bag
1585 });
1586 }
1587 const fire = stepFirestarting(this, now);
1588 events.push(...fire.events);
1589 for (const entry of fire.privates ?? [])
1590 {
1591 events.push({
1592 type: "inventory",
1593 characterId: entry.characterId,
1594 ...entry.bag
1595 });
1596 }
1597 const fishing = stepFishing(this, now);
1598 events.push(...fishing.events);
1599 for (const entry of fishing.privates ?? [])
1600 {
1601 events.push({
1602 type: "inventory",
1603 characterId: entry.characterId,
1604 ...entry.bag
1605 });
1606 }
1607 const shearing = stepShearing(this, now);
1608 events.push(...shearing.events);
1609 for (const entry of shearing.privates ?? [])
1610 {
1611 events.push({
1612 type: "inventory",
1613 characterId: entry.characterId,
1614 ...entry.bag
1615 });
1616 }
1617 const craft = stepCrafting(this, now);
1618 events.push(...craft.events);
1619 for (const entry of craft.privates ?? [])
1620 {
1621 events.push({
1622 type: "inventory",
1623 characterId: entry.characterId,
1624 ...entry.bag
1625 });
1626 }
1627 events.push(...stepDoors(this));
1628 return { events, transferRequests };
1629 }
1630
1631 #stepMovement (now = Date.now())
1632 {
1633 const events = expireGroundItems(this, now);
1634 const transferRequests = [];
1635 events.push(...pruneShopBrowsers(this));
1636 events.push(...this.#pruneDialogueBrowsers());
1637 this.#queueAmbientWander();
1638 this.#queueSpawnerWander();
1639 this.#queueExchangeStations();
1640 for (const entity of this.ecs.query(Component.position, Component.movement))
1641 {
1642 const { handle, entityId, position, movement } = entity;
1643 if (this.ecs.has(handle, Component.dead))
1644 { continue; }
1645 if (this.ecs.has(handle, Component.flight))
1646 { continue; }
1647 const path = this.ecs.get(handle, Component.path);
1648 const tiles = path?.tiles;
1649 if (this.frozen.has(entityId) || !tiles?.length)
1650 {
1651 if (path)
1652 { path.stuckSince = null; }
1653 continue;
1654 }
1655 if (!this.chunkIsSimulating(position.tileX, position.tileY, position.dimensionId ?? OVERWORLD_ID))
1656 { continue; }
1657
1658 this.#repathIfNavigationStuck(entityId, position, movement, path, now);
1659
1660 const stamina = this.ecs.get(handle, Component.stamina);
1661 if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))
1662 { movement.gait = GAIT.walk; }
1663 const isWalk = movement.gait !== GAIT.run;
1664 if (isWalk)
1665 {
1666 movement.walkCarry = (movement.walkCarry + 1) % 2;
1667 if (movement.walkCarry !== 0)
1668 { continue; }
1669 }
1670
1671 const next = tiles[0];
1672 if (!next)
1673 { continue; }
1674 const destRegionX = tileToRegion(next.x);
1675 const destRegionY = tileToRegion(next.y);
1676 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
1677 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
1678 {
1679 this.frozen.add(entityId);
1680 transferRequests.push({
1681 entityId,
1682 fromTileX: position.tileX,
1683 fromTileY: position.tileY,
1684 destTileX: next.x,
1685 destTileY: next.y,
1686 toRegionX: destRegionX,
1687 toRegionY: destRegionY,
1688 dimensionId,
1689 payload: serializeEntity(this.ecs, entityId)
1690 });
1691 continue;
1692 }
1693
1694 if (!this.walkableFor(entityId, next.x, next.y))
1695 {
1696 const blockedToast = this.#doorRequirementBlockedToast(entityId, next.x, next.y, now);
1697 if (blockedToast)
1698 {
1699 events.push(blockedToast);
1700 path.tiles = [];
1701 continue;
1702 }
1703 const combat = this.ecs.get(handle, Component.combat);
1704 if (combat?.targetEntityId != null)
1705 {
1706 const targetHandle = this.ecs.handleOf(combat.targetEntityId);
1707 const targetPos = targetHandle != null
1708 ? this.ecs.get(targetHandle, Component.position)
1709 : null;
1710 const blockedByTarget = targetPos
1711 && next.x === targetPos.tileX
1712 && next.y === targetPos.tileY;
1713 if (!blockedByTarget)
1714 { path.tiles = []; }
1715 }
1716 continue;
1717 }
1718
1719 const doorDelta = maybeOpenDoorOnApproach(this, entityId, next.x, next.y);
1720 if (doorDelta)
1721 { events.push(doorDelta); }
1722
1723 const combat = this.ecs.get(handle, Component.combat);
1724 if (combat?.targetEntityId != null && !this.isClearStanding(entityId, next.x, next.y))
1725 { continue; }
1726
1727 const fromTileX = position.tileX;
1728 const fromTileY = position.tileY;
1729 const flying = this.#isFlying(handle);
1730 if (!flying)
1731 { this.#vacate(entityId, fromTileX, fromTileY); }
1732 position.prevTileX = fromTileX;
1733 position.prevTileY = fromTileY;
1734 position.tileX = next.x;
1735 position.tileY = next.y;
1736 tiles.shift();
1737 if (!flying)
1738 { this.#occupy(entityId, position.tileX, position.tileY, now); }
1739 path.stuckSince = now;
1740 path.stuckTileX = position.tileX;
1741 path.stuckTileY = position.tileY;
1742 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
1743 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
1744 syncCharacterChunkPresence(this.ecs, handle, now);
1745 if (!isWalk)
1746 { this.#consumeRunStamina(handle, events); }
1747 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
1748 }
1749 return { events, transferRequests };
1750 }
1751
1752 /**
1753 * If we still have a destination but have not left this tile for NAV_STUCK_MS,
1754 * recompute A* to the same goal (around whoever is blocking the old route).
1755 */
1756 #repathIfNavigationStuck (entityId, position, movement, path, now)
1757 {
1758 if (!path?.tiles?.length)
1759 {
1760 path.stuckSince = null;
1761 return;
1762 }
1763 if (
1764 path.stuckSince == null
1765 || path.stuckTileX !== position.tileX
1766 || path.stuckTileY !== position.tileY
1767 )
1768 {
1769 path.stuckSince = now;
1770 path.stuckTileX = position.tileX;
1771 path.stuckTileY = position.tileY;
1772 return;
1773 }
1774 if (now - path.stuckSince < NAV_STUCK_MS)
1775 { return; }
1776
1777 const goal = path.tiles[path.tiles.length - 1];
1778 if (!goal || (goal.x === position.tileX && goal.y === position.tileY))
1779 {
1780 path.tiles = [];
1781 path.stuckSince = null;
1782 return;
1783 }
1784 const stuckHandle = this.ecs.handleOf(entityId);
1785 const isCharacter = stuckHandle != null && this.ecs.has(stuckHandle, Component.character);
1786 const bounds = chunkBoundsAround(
1787 position.tileX,
1788 position.tileY,
1789 isCharacter ? STATIC_CHUNK_RADIUS : VISIBLE_CHUNK_RADIUS
1790 );
1791 const inCombat = stuckHandle != null
1792 && this.ecs.get(stuckHandle, Component.combat)?.targetEntityId != null;
1793 path.tiles = findPath(
1794 position.tileX,
1795 position.tileY,
1796 goal.x,
1797 goal.y,
1798 (x, y) => this.isClearStanding(entityId, x, y),
1799 bounds.minX,
1800 bounds.minY,
1801 bounds.maxX,
1802 bounds.maxY,
1803 this.pathfindOptions({
1804 preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character),
1805 preferPaths: !inCombat,
1806 entityId,
1807 penalizeCombatBackstep: inCombat
1808 })
1809 );
1810 path.stuckSince = now;
1811 path.stuckTileX = position.tileX;
1812 path.stuckTileY = position.tileY;
1813 if (movement)
1814 { movement.walkCarry = 0; }
1815 }
1816
1817 #queueAmbientWander ()
1818 {
1819 for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
1820 {
1821 const def = mobDefinition(entity.creature.mobTypeId);
1822 if (!def?.ambient || def.freeFlight)
1823 { continue; }
1824 if (this.ecs.get(entity.handle, Component.spawnOrigin))
1825 { continue; }
1826 const path = this.ecs.get(entity.handle, Component.path);
1827 if (!path)
1828 { continue; }
1829 if (path.tiles?.length)
1830 { continue; }
1831 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1832 { continue; }
1833 if (Math.random() > 0.35)
1834 { continue; }
1835 const dirs = [
1836 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
1837 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
1838 ];
1839 const dir = dirs[Math.floor(Math.random() * dirs.length)];
1840 const nextX = entity.position.tileX + dir.x;
1841 const nextY = entity.position.tileY + dir.y;
1842 if (!this.isClearStanding(entity.entityId, nextX, nextY))
1843 { continue; }
1844 path.tiles = [{ x: nextX, y: nextY }];
1845 }
1846 }
1847
1848 /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner.
1849 * Combat chase is limited to 3× wander range (euclidean); beyond that they leash home. */
1850 #queueSpawnerWander ()
1851 {
1852 for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin))
1853 {
1854 const combat = this.ecs.get(entity.handle, Component.combat);
1855 if (combat?.targetEntityId != null)
1856 { continue; }
1857 const follow = this.ecs.get(entity.handle, Component.follow);
1858 if (follow?.targetEntityId != null)
1859 { continue; }
1860 const shop = this.ecs.get(entity.handle, Component.shop);
1861 if (shopHasActiveBrowsers(shop))
1862 { continue; }
1863 const origin = entity.spawnOrigin;
1864 if (originIsBusyPinned(origin))
1865 { continue; }
1866 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1867 { continue; }
1868 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1869 if (def?.freeFlight)
1870 { continue; }
1871 const path = this.ecs.get(entity.handle, Component.path);
1872 if (!path || path.tiles?.length)
1873 { continue; }
1874 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1875 { continue; }
1876
1877 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1878 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1879 const range = Math.max(0, origin.wanderRangeTiles | 0);
1880 const homeDist = Math.max(
1881 Math.abs(entity.position.tileX - originX),
1882 Math.abs(entity.position.tileY - originY)
1883 );
1884 const tooFar = homeDist > range || !!combat?.leashing;
1885
1886 // Outside the leash / returning from combat: always try to step home. Inside: mostly idle.
1887 if (!tooFar && Math.random() > 0.1)
1888 { continue; }
1889
1890 if (tooFar)
1891 {
1892 if (this.#queueReturnTowardSpawn(entity.entityId, entity.handle, entity.position, path, originX, originY))
1893 { continue; }
1894 queueLocalRandomWanderStep(this, entity.entityId, entity.position, path);
1895 continue;
1896 }
1897
1898 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
1899 if (!goal)
1900 { continue; }
1901 if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY)
1902 { continue; }
1903 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1904 const tiles = findPath(
1905 entity.position.tileX,
1906 entity.position.tileY,
1907 goal.tileX,
1908 goal.tileY,
1909 (x, y) => this.walkableFor(entity.entityId, x, y),
1910 bounds.minX,
1911 bounds.minY,
1912 bounds.maxX,
1913 bounds.maxY,
1914 this.pathfindOptions({ preferPaths: true, entityId: entity.entityId })
1915 );
1916 if (!tiles?.length)
1917 { continue; }
1918 path.tiles = tiles;
1919 }
1920 }
1921
1922 /**
1923 * Path toward the spawner within the current pathfinding window (chunk-step home).
1924 * @returns {boolean} true if a return path was queued
1925 */
1926 #queueReturnTowardSpawn (entityId, handle, position, path, originX, originY)
1927 {
1928 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1929 const goal = pickClearGoalToward(
1930 this,
1931 entityId,
1932 position.tileX,
1933 position.tileY,
1934 originX,
1935 originY,
1936 bounds
1937 );
1938 if (!goal)
1939 { return false; }
1940 if (goal.tileX === position.tileX && goal.tileY === position.tileY)
1941 { return false; }
1942 const tiles = findPath(
1943 position.tileX,
1944 position.tileY,
1945 goal.tileX,
1946 goal.tileY,
1947 (x, y) => this.walkableFor(entityId, x, y),
1948 bounds.minX,
1949 bounds.minY,
1950 bounds.maxX,
1951 bounds.maxY,
1952 this.pathfindOptions({ preferPaths: true, entityId })
1953 );
1954 if (!tiles?.length)
1955 { return false; }
1956 path.tiles = tiles;
1957 const movement = this.ecs.get(handle, Component.movement);
1958 if (movement)
1959 { movement.walkCarry = 0; }
1960 return true;
1961 }
1962
1963 /**
1964 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1965 * message: { stationTileX, stationTileY, dimensionId? }
1966 */
1967 #stationExchangeClerk (message)
1968 {
1969 const stationTileX = message.stationTileX | 0;
1970 const stationTileY = message.stationTileY | 0;
1971 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1972 if (!this.isEnterable(stationTileX, stationTileY, dim))
1973 { return { ok: false, reason: "blocked" }; }
1974
1975 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1976 {
1977 if (!entity.spawnOrigin?.centralExchange)
1978 { continue; }
1979 if (
1980 Number.isInteger(entity.spawnOrigin.stationTileX)
1981 && entity.spawnOrigin.stationTileX === stationTileX
1982 && entity.spawnOrigin.stationTileY === stationTileY
1983 )
1984 { return { ok: true, entityId: entity.entityId, already: true }; }
1985 }
1986
1987 let best = null;
1988 let bestDist = Infinity;
1989 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1990 {
1991 if (!entity.spawnOrigin?.centralExchange)
1992 { continue; }
1993 if (Number.isInteger(entity.spawnOrigin.stationTileX))
1994 { continue; }
1995 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
1996 if (entityDim !== dim)
1997 { continue; }
1998 const dist = Math.max(
1999 Math.abs(entity.position.tileX - stationTileX),
2000 Math.abs(entity.position.tileY - stationTileY)
2001 );
2002 if (dist < bestDist)
2003 {
2004 bestDist = dist;
2005 best = entity;
2006 }
2007 }
2008 if (!best)
2009 { return { ok: false, reason: "none-available" }; }
2010
2011 const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS);
2012 const tiles = findPath(
2013 best.position.tileX,
2014 best.position.tileY,
2015 stationTileX,
2016 stationTileY,
2017 (x, y) => this.walkableFor(best.entityId, x, y),
2018 bounds.minX,
2019 bounds.minY,
2020 bounds.maxX,
2021 bounds.maxY,
2022 this.pathfindOptions({ preferPaths: true, entityId: best.entityId })
2023 );
2024 best.spawnOrigin.stationTileX = stationTileX;
2025 best.spawnOrigin.stationTileY = stationTileY;
2026 if (tiles?.length)
2027 { best.path.tiles = tiles; }
2028 else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY)
2029 { best.path.tiles = []; }
2030 else
2031 { return { ok: false, reason: "no-path" }; }
2032 return { ok: true, entityId: best.entityId };
2033 }
2034
2035 /**
2036 * Clear a CE clerk's station assignment so wander can resume.
2037 * message: { stationTileX, stationTileY }
2038 */
2039 #releaseExchangeClerk (message)
2040 {
2041 const stationTileX = message.stationTileX | 0;
2042 const stationTileY = message.stationTileY | 0;
2043 let released = 0;
2044 for (const entity of this.ecs.query(Component.spawnOrigin, Component.path))
2045 {
2046 if (!entity.spawnOrigin?.centralExchange)
2047 { continue; }
2048 if (
2049 entity.spawnOrigin.stationTileX !== stationTileX
2050 || entity.spawnOrigin.stationTileY !== stationTileY
2051 )
2052 { continue; }
2053 entity.spawnOrigin.stationTileX = null;
2054 entity.spawnOrigin.stationTileY = null;
2055 entity.path.tiles = [];
2056 released += 1;
2057 }
2058 return { ok: true, released };
2059 }
2060
2061 #pinDialogue (entityId, characterId)
2062 {
2063 const handle = this.ecs.handleOf(entityId | 0);
2064 if (handle == null)
2065 { return { ok: false }; }
2066 const origin = this.ecs.get(handle, Component.spawnOrigin);
2067 if (!origin)
2068 { return { ok: false }; }
2069 if (!origin.dialogueBrowsers || typeof origin.dialogueBrowsers !== "object")
2070 { origin.dialogueBrowsers = Object.create(null); }
2071 origin.dialogueBrowsers[characterId | 0] = true;
2072 const path = this.ecs.get(handle, Component.path);
2073 if (path)
2074 { path.tiles = []; }
2075 return { ok: true };
2076 }
2077
2078 #unpinDialogue (entityId, characterId)
2079 {
2080 const handle = this.ecs.handleOf(entityId | 0);
2081 if (handle == null)
2082 { return { ok: false }; }
2083 const origin = this.ecs.get(handle, Component.spawnOrigin);
2084 if (!origin?.dialogueBrowsers)
2085 { return { ok: true }; }
2086 delete origin.dialogueBrowsers[characterId | 0];
2087 return { ok: true };
2088 }
2089
2090 #pruneDialogueBrowsers ()
2091 {
2092 const events = [];
2093 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
2094 {
2095 const browsers = entity.spawnOrigin?.dialogueBrowsers;
2096 const shearBrowsers = entity.spawnOrigin?.shearBrowsers;
2097 const dialogueIds = browsers && typeof browsers === "object"
2098 ? Object.keys(browsers).map((id) => Number(id))
2099 : [];
2100 const shearIds = shearBrowsers && typeof shearBrowsers === "object"
2101 ? Object.keys(shearBrowsers).map((id) => Number(id))
2102 : [];
2103 if (!dialogueIds.length && !shearIds.length)
2104 { continue; }
2105 const path = this.ecs.get(entity.handle, Component.path);
2106 if (path)
2107 { path.tiles = []; }
2108 for (const characterId of dialogueIds)
2109 {
2110 const playerEntityId = this.characterEntities.get(characterId);
2111 if (playerEntityId == null)
2112 {
2113 delete browsers[characterId];
2114 continue;
2115 }
2116 const playerHandle = this.ecs.handleOf(playerEntityId);
2117 const playerPos = this.ecs.get(playerHandle, Component.position);
2118 const npcDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
2119 const stillNear = playerPos
2120 && normalizeDimensionId(playerPos.dimensionId ?? OVERWORLD_ID) === npcDim
2121 && canTalkOrShopNear(
2122 playerPos.tileX,
2123 playerPos.tileY,
2124 entity.position.tileX,
2125 entity.position.tileY,
2126 (x, y) => this.blockTypeAt(x, y, npcDim)
2127 );
2128 if (stillNear)
2129 { continue; }
2130 delete browsers[characterId];
2131 const identity = this.ecs.get(playerHandle, Component.networkIdentity);
2132 events.push({
2133 type: "dialogue-walk-away",
2134 sessionId: identity?.sessionId ?? null,
2135 characterId,
2136 npcEntityId: entity.entityId
2137 });
2138 }
2139 for (const characterId of shearIds)
2140 {
2141 const playerEntityId = this.characterEntities.get(characterId);
2142 if (playerEntityId == null)
2143 {
2144 delete shearBrowsers[characterId];
2145 continue;
2146 }
2147 const playerHandle = this.ecs.handleOf(playerEntityId);
2148 const playerPos = this.ecs.get(playerHandle, Component.position);
2149 const stillNear = playerPos
2150 && chebyshev(
2151 playerPos.tileX,
2152 playerPos.tileY,
2153 entity.position.tileX,
2154 entity.position.tileY
2155 ) <= 1;
2156 if (stillNear)
2157 { continue; }
2158 delete shearBrowsers[characterId];
2159 }
2160 }
2161 return events;
2162 }
2163
2164 /** Keep stationed CE clerks at their counter tile. */
2165 #queueExchangeStations ()
2166 {
2167 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
2168 {
2169 if (!entity.spawnOrigin?.centralExchange)
2170 { continue; }
2171 const sx = entity.spawnOrigin.stationTileX;
2172 const sy = entity.spawnOrigin.stationTileY;
2173 if (!Number.isInteger(sx) || !Number.isInteger(sy))
2174 { continue; }
2175 if (entity.position.tileX === sx && entity.position.tileY === sy)
2176 {
2177 entity.path.tiles = [];
2178 continue;
2179 }
2180 if (entity.path.tiles?.length)
2181 { continue; }
2182 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
2183 const tiles = findPath(
2184 entity.position.tileX,
2185 entity.position.tileY,
2186 sx,
2187 sy,
2188 (x, y) => this.walkableFor(entity.entityId, x, y),
2189 bounds.minX,
2190 bounds.minY,
2191 bounds.maxX,
2192 bounds.maxY,
2193 this.pathfindOptions({ preferPaths: true, entityId: entity.entityId })
2194 );
2195 if (tiles?.length)
2196 { entity.path.tiles = tiles; }
2197 }
2198 }
2199
2200 #applyTransfer (message)
2201 {
2202 const payload = message.payload;
2203 const entityId = payload.entityId;
2204 if (this.ecs.hasEntity(entityId))
2205 { return { accepted: false, reason: "already-present" }; }
2206
2207 const position = payload.components?.position;
2208 const destTileX = message.destTileX ?? position?.tileX;
2209 const destTileY = message.destTileY ?? position?.tileY;
2210 const dimensionId = normalizeDimensionId(
2211 message.dimensionId ?? position?.dimensionId ?? OVERWORLD_ID
2212 );
2213 if (destTileX == null || destTileY == null)
2214 { return { accepted: false, reason: "missing-destination" }; }
2215 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY), dimensionId))
2216 { return { accepted: false, reason: "not-owner" }; }
2217
2218 const creature = payload.components?.creature;
2219 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
2220 if (flying)
2221 {
2222 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY), dimensionId);
2223 if (!data?.open)
2224 { return { accepted: false, reason: "blocked" }; }
2225 }
2226 else if (!this.isEnterable(destTileX, destTileY, dimensionId))
2227 { return { accepted: false, reason: "blocked" }; }
2228
2229 deserializeEntity(this.ecs, payload);
2230 const handle = this.ecs.handleOf(entityId);
2231 const livePosition = this.ecs.get(handle, Component.position);
2232 const path = this.ecs.get(handle, Component.path);
2233 livePosition.tileX = destTileX;
2234 livePosition.tileY = destTileY;
2235 livePosition.dimensionId = dimensionId;
2236 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
2237 { path.tiles.shift(); }
2238 if (!flying)
2239 { this.#occupy(entityId, destTileX, destTileY); }
2240 const character = this.ecs.get(handle, Component.character);
2241 if (character?.characterId)
2242 { this.characterEntities.set(character.characterId, entityId); }
2243 this.frozen.delete(entityId);
2244 return {
2245 accepted: true,
2246 entity: publicEntityView(this.ecs, entityId)
2247 };
2248 }
2249
2250 #commitTransfer (entityId)
2251 {
2252 if (!this.ecs.hasEntity(entityId))
2253 { return null; }
2254 return this.#destroyEntity(entityId);
2255 }
2256
2257 #abortTransfer (entityId)
2258 {
2259 this.frozen.delete(entityId);
2260 return publicEntityView(this.ecs, entityId);
2261 }
2262
2263 #listLoaders ()
2264 {
2265 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
2266 entityId: entity.entityId,
2267 tileX: entity.position.tileX,
2268 tileY: entity.position.tileY,
2269 dimensionId: normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID),
2270 chunkLoader: { ...entity.chunkLoader }
2271 }));
2272 }
2273
2274 #listPublicEntities ()
2275 {
2276 const out = [];
2277 for (const entity of this.ecs.query(Component.position))
2278 {
2279 if (this.ecs.has(entity.handle, Component.dead))
2280 { continue; }
2281 const view = publicEntityView(this.ecs, entity.entityId);
2282 if (view)
2283 { out.push(view); }
2284 }
2285 return out;
2286 }
2287
2288 #entitiesInRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
2289 {
2290 const dim = normalizeDimensionId(dimensionId);
2291 const records = [];
2292 for (const entity of this.ecs.query(Component.position))
2293 {
2294 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
2295 if (entityDim !== dim)
2296 { continue; }
2297 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
2298 { continue; }
2299 records.push({
2300 ...publicEntityView(this.ecs, entity.entityId),
2301 persistent: this.ecs.has(entity.handle, Component.persistent),
2302 payload: serializeEntity(this.ecs, entity.entityId)
2303 });
2304 }
2305 return records;
2306 }
2307
2308 #chunkSnapshot (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
2309 {
2310 const dim = normalizeDimensionId(dimensionId);
2311 const data = this.#chunkData(chunkX, chunkY, dim);
2312 if (staticOnly)
2313 {
2314 return {
2315 chunkX,
2316 chunkY,
2317 dimensionId: dim,
2318 open: data.open,
2319 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
2320 grounds: data.grounds,
2321 blocks: data.blocks,
2322 light: data.light,
2323 occlusion: data.occlusion,
2324 entities: [],
2325 groundItems: []
2326 };
2327 }
2328 const entities = [];
2329 for (const entity of this.ecs.query(Component.position, Component.appearance))
2330 {
2331 if (this.ecs.has(entity.handle, Component.dead))
2332 { continue; }
2333 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
2334 if (entityDim !== dim)
2335 { continue; }
2336 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
2337 { continue; }
2338 entities.push(publicEntityView(this.ecs, entity.entityId));
2339 }
2340 return {
2341 chunkX,
2342 chunkY,
2343 dimensionId: dim,
2344 open: data.open,
2345 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
2346 grounds: data.grounds,
2347 blocks: data.blocks,
2348 light: data.light,
2349 occlusion: data.occlusion,
2350 entities,
2351 groundItems: groundItemsInChunk(this, chunkX, chunkY)
2352 };
2353 }
2354
2355 #moveEvent (entityId, fromTileX, fromTileY)
2356 {
2357 const view = publicEntityView(this.ecs, entityId);
2358 return {
2359 type: "entity-move",
2360 entityId,
2361 fromTileX,
2362 fromTileY,
2363 tileX: view.tileX,
2364 tileY: view.tileY,
2365 worldX: view.worldX,
2366 worldY: view.worldY,
2367 gait: view.gait,
2368 freeFlight: !!view.freeFlight
2369 };
2370 }
2371
2372 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
2373 {
2374 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId));
2375 return !!chunk && !chunk.replica && chunk.simulating;
2376 }
2377
2378 walkableFor (entityId, tileX, tileY)
2379 {
2380 const dim = this.#entityDimensionId(entityId);
2381 const handle = this.ecs.handleOf(entityId);
2382 if (this.#isFlying(handle))
2383 {
2384 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
2385 return !!data?.open;
2386 }
2387 // Entities pass through each other; only terrain / closed chunks block movement.
2388 return this.isEnterable(tileX, tileY, dim, {
2389 canOpenDoors: entityCanOpenDoors(this.ecs, entityId),
2390 requirementsAllow: entityDoorRequirementsAllow(this, entityId, tileX, tileY)
2391 });
2392 }
2393
2394 /** Ground type id at a world tile (defaults to world default ground). */
2395 groundTypeAt (tileX, tileY, dimensionId = OVERWORLD_ID)
2396 {
2397 const dim = normalizeDimensionId(dimensionId) ?? OVERWORLD_ID;
2398 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
2399 const entry = normalizeGround(data.grounds[tileIndex(tileToLocal(tileX), tileToLocal(tileY))]);
2400 return entry?.typeId ?? this.settings.defaultGroundTypeId ?? GroundType.grass;
2401 }
2402
2403 /**
2404 * @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null, penalizeCombatBackstep?: boolean }} [options]
2405 */
2406 pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null, penalizeCombatBackstep = false } = {})
2407 {
2408 const options = { preferVertical: !!preferVertical };
2409 const now = Date.now();
2410 const dimensionId = entityId != null ? this.#entityDimensionId(entityId) : OVERWORLD_ID;
2411 let prevTileX = null;
2412 let prevTileY = null;
2413 if (penalizeCombatBackstep && entityId != null)
2414 {
2415 const handle = this.ecs.handleOf(entityId);
2416 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2417 if (position?.prevTileX != null && position?.prevTileY != null)
2418 {
2419 prevTileX = position.prevTileX | 0;
2420 prevTileY = position.prevTileY | 0;
2421 }
2422 }
2423 options.stepCost = (x, y) =>
2424 {
2425 const base = stepCostForGround(
2426 this.groundTypeAt(x, y, dimensionId),
2427 {
2428 preferPaths: !!preferPaths,
2429 softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now)
2430 }
2431 );
2432 return withCombatBackstepCost(base, x, y, prevTileX, prevTileY);
2433 };
2434 options.minStepCost = preferPaths ? PATH_GROUND_STEP_COST : 1;
2435 return options;
2436 }
2437
2438 /**
2439 * True when another living occupant has stood on this tile for SOFT_OCCUPIED_DWELL_MS+.
2440 * Soft cost only — never blocks pathing.
2441 */
2442 #isSoftOccupiedTile (tileX, tileY, dimensionId, selfEntityId, now = Date.now())
2443 {
2444 const key = tileKey(tileX, tileY, dimensionId);
2445 const local = this.occupancy.get(key);
2446 if (!local?.size)
2447 { return false; }
2448 for (const id of local)
2449 {
2450 if (id === selfEntityId)
2451 { continue; }
2452 const handle = this.ecs.handleOf(id);
2453 if (handle == null)
2454 { continue; }
2455 const position = this.ecs.get(handle, Component.position);
2456 const enteredAt = position?.tileEnteredAt;
2457 if (enteredAt == null)
2458 { continue; }
2459 if (now - enteredAt >= SOFT_OCCUPIED_DWELL_MS)
2460 { return true; }
2461 }
2462 return false;
2463 }
2464
2465 /**
2466 * Standing tile with no other mob/player (self allowed). Used for wander goals
2467 * and melee attack stance.
2468 */
2469 isClearStanding (entityId, tileX, tileY)
2470 {
2471 const dim = this.#entityDimensionId(entityId);
2472 if (!this.isEnterable(tileX, tileY, dim, {
2473 canOpenDoors: entityCanOpenDoors(this.ecs, entityId),
2474 requirementsAllow: entityDoorRequirementsAllow(this, entityId, tileX, tileY)
2475 }))
2476 { return false; }
2477 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
2478 }
2479
2480 destroyEntity (entityId)
2481 {
2482 return this.#destroyEntity(entityId);
2483 }
2484
2485 occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
2486 {
2487 return this.#anyOccupant(tileX, tileY, dimensionId);
2488 }
2489
2490 #chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
2491 {
2492 return this.chunkIsSimulating(tileX, tileY, dimensionId);
2493 }
2494
2495 #chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2496 {
2497 const loaded = this.chunks.get(chunkKey(chunkX, chunkY, dimensionId));
2498 if (loaded)
2499 { return loaded.data; }
2500 return createEmptyChunkData(this.settings.defaultGroundTypeId);
2501 }
2502
2503 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID, { canOpenDoors = false, requirementsAllow = true } = {})
2504 {
2505 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2506 if (!data.open)
2507 { return false; }
2508 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY), {
2509 canOpenDoors,
2510 requirementsAllow
2511 });
2512 }
2513
2514 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
2515 {
2516 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2517 if (!data.open)
2518 { return false; }
2519 return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));
2520 }
2521
2522 #walkableFor (entityId, tileX, tileY)
2523 {
2524 return this.walkableFor(entityId, tileX, tileY);
2525 }
2526
2527 #isFlying (handle)
2528 {
2529 if (handle == null)
2530 { return false; }
2531 const creature = this.ecs.get(handle, Component.creature);
2532 return !!mobDefinition(creature?.mobTypeId)?.flying;
2533 }
2534
2535 #entityDimensionId (entityId)
2536 {
2537 const handle = this.ecs.handleOf(entityId);
2538 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2539 return normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
2540 }
2541
2542 #occupy (entityId, tileX, tileY, now = Date.now())
2543 {
2544 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
2545 let set = this.occupancy.get(key);
2546 if (!set)
2547 {
2548 set = new Set();
2549 this.occupancy.set(key, set);
2550 }
2551 set.add(entityId);
2552 const handle = this.ecs.handleOf(entityId);
2553 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2554 if (position)
2555 { position.tileEnteredAt = now; }
2556 }
2557
2558 #vacate (entityId, tileX, tileY)
2559 {
2560 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
2561 const set = this.occupancy.get(key);
2562 if (!set)
2563 { return; }
2564 set.delete(entityId);
2565 if (set.size === 0)
2566 { this.occupancy.delete(key); }
2567 }
2568
2569 #anyOccupant (tileX, tileY, dimensionId = OVERWORLD_ID)
2570 {
2571 const key = tileKey(tileX, tileY, dimensionId);
2572 const local = this.occupancy.get(key);
2573 if (local?.size)
2574 { return local.values().next().value; }
2575 const ghosts = this.ghostOccupancy.get(key);
2576 if (ghosts?.size)
2577 { return ghosts.values().next().value; }
2578 return null;
2579 }
2580
2581 #hasOtherOccupant (entityId, tileX, tileY, dimensionId = null)
2582 {
2583 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : this.#entityDimensionId(entityId);
2584 const key = tileKey(tileX, tileY, dim);
2585 const local = this.occupancy.get(key);
2586 if (local)
2587 {
2588 for (const id of local)
2589 {
2590 if (id !== entityId)
2591 { return true; }
2592 }
2593 }
2594 const ghosts = this.ghostOccupancy.get(key);
2595 if (ghosts)
2596 {
2597 for (const id of ghosts)
2598 {
2599 if (id !== entityId)
2600 { return true; }
2601 }
2602 }
2603 return false;
2604 }
2605
2606 /** @deprecated use #anyOccupant — kept name for call sites expecting a single id */
2607 #occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
2608 {
2609 return this.#anyOccupant(tileX, tileY, dimensionId);
2610 }
2611}
2612
2613function pickWanderGoalInRange (world, entityId, originX, originY, range)
2614{
2615 const radius = Math.max(0, range | 0);
2616 for (let attempt = 0; attempt < 24; attempt++)
2617 {
2618 const tileX = originX + randInt(-radius, radius);
2619 const tileY = originY + randInt(-radius, radius);
2620 if (!world.isClearStanding(entityId, tileX, tileY))
2621 { continue; }
2622 return { tileX, tileY };
2623 }
2624 return null;
2625}
2626
2627/**
2628 * Clearest standable tile in pathfinding bounds, pulled toward (destX, destY).
2629 * When the destination is outside the window this becomes a chunk-step toward home.
2630 */
2631function pickClearGoalToward (world, entityId, fromX, fromY, destX, destY, bounds)
2632{
2633 const idealX = Math.max(bounds.minX, Math.min(bounds.maxX, destX | 0));
2634 const idealY = Math.max(bounds.minY, Math.min(bounds.maxY, destY | 0));
2635 if (world.isClearStanding(entityId, idealX, idealY))
2636 { return { tileX: idealX, tileY: idealY }; }
2637 for (let radius = 1; radius <= 4; radius++)
2638 {
2639 for (let dy = -radius; dy <= radius; dy++)
2640 {
2641 for (let dx = -radius; dx <= radius; dx++)
2642 {
2643 if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
2644 { continue; }
2645 const tileX = idealX + dx;
2646 const tileY = idealY + dy;
2647 if (tileX < bounds.minX || tileX > bounds.maxX || tileY < bounds.minY || tileY > bounds.maxY)
2648 { continue; }
2649 if (tileX === fromX && tileY === fromY)
2650 { continue; }
2651 if (!world.isClearStanding(entityId, tileX, tileY))
2652 { continue; }
2653 return { tileX, tileY };
2654 }
2655 }
2656 }
2657 return null;
2658}
2659
2660/** One random adjacent step so a stranded mob does not freeze in place. */
2661function queueLocalRandomWanderStep (world, entityId, position, path)
2662{
2663 const dirs = [
2664 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
2665 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
2666 ];
2667 for (let i = dirs.length - 1; i > 0; i--)
2668 {
2669 const j = Math.floor(Math.random() * (i + 1));
2670 const tmp = dirs[i];
2671 dirs[i] = dirs[j];
2672 dirs[j] = tmp;
2673 }
2674 for (const dir of dirs)
2675 {
2676 const nextX = position.tileX + dir.x;
2677 const nextY = position.tileY + dir.y;
2678 if (!world.isClearStanding(entityId, nextX, nextY))
2679 { continue; }
2680 path.tiles = [{ x: nextX, y: nextY }];
2681 return true;
2682 }
2683 return false;
2684}
2685
2686function hasDialogueBrowsers (origin)
2687{
2688 return originIsBusyPinned(origin);
2689}
2690
2691function randInt (min, max)
2692{
2693 return min + Math.floor(Math.random() * (max - min + 1));
2694}
2695
2696export function replicaNeededForOwnedChunks (ownedChunkKeys)
2697{
2698 const needed = new Set();
2699 for (const key of ownedChunkKeys)
2700 {
2701 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2702 for (let dy = -1; dy <= 1; dy++)
2703 {
2704 for (let dx = -1; dx <= 1; dx++)
2705 {
2706 if (dx === 0 && dy === 0)
2707 { continue; }
2708 needed.add(chunkKey(chunkX + dx, chunkY + dy, dimensionId));
2709 }
2710 }
2711 }
2712 return needed;
2713}