BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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