BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

workerWorld.js 83.8 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 is limited to 3× wander range (euclidean); beyond that they leash home. */
1864 #queueSpawnerWander ()
1865 {
1866 for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin))
1867 {
1868 const combat = this.ecs.get(entity.handle, Component.combat);
1869 if (combat?.targetEntityId != null)
1870 { continue; }
1871 const follow = this.ecs.get(entity.handle, Component.follow);
1872 if (follow?.targetEntityId != null)
1873 { continue; }
1874 const shop = this.ecs.get(entity.handle, Component.shop);
1875 if (shopHasActiveBrowsers(shop))
1876 { continue; }
1877 const origin = entity.spawnOrigin;
1878 if (originIsBusyPinned(origin))
1879 { continue; }
1880 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1881 { continue; }
1882 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1883 if (def?.freeFlight)
1884 { continue; }
1885 const path = this.ecs.get(entity.handle, Component.path);
1886 if (!path || path.tiles?.length)
1887 { continue; }
1888 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1889 { continue; }
1890
1891 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1892 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1893 const range = Math.max(0, origin.wanderRangeTiles | 0);
1894 const homeDist = Math.max(
1895 Math.abs(entity.position.tileX - originX),
1896 Math.abs(entity.position.tileY - originY)
1897 );
1898 const tooFar = homeDist > range || !!combat?.leashing;
1899
1900 // Outside the leash / returning from combat: always try to step home. Inside: mostly idle.
1901 if (!tooFar && Math.random() > 0.1)
1902 { continue; }
1903
1904 if (tooFar)
1905 {
1906 if (this.#queueReturnTowardSpawn(entity.entityId, entity.handle, entity.position, path, originX, originY))
1907 { continue; }
1908 queueLocalRandomWanderStep(this, entity.entityId, entity.position, path);
1909 continue;
1910 }
1911
1912 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
1913 if (!goal)
1914 { continue; }
1915 if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY)
1916 { continue; }
1917 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1918 const tiles = findPath(
1919 entity.position.tileX,
1920 entity.position.tileY,
1921 goal.tileX,
1922 goal.tileY,
1923 (x, y) => this.walkableFor(entity.entityId, x, y),
1924 bounds.minX,
1925 bounds.minY,
1926 bounds.maxX,
1927 bounds.maxY,
1928 this.pathfindOptions({ preferPaths: true, entityId: entity.entityId })
1929 );
1930 if (!tiles?.length)
1931 { continue; }
1932 path.tiles = tiles;
1933 }
1934 }
1935
1936 /**
1937 * Path toward the spawner within the current pathfinding window (chunk-step home).
1938 * @returns {boolean} true if a return path was queued
1939 */
1940 #queueReturnTowardSpawn (entityId, handle, position, path, originX, originY)
1941 {
1942 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1943 const goal = pickClearGoalToward(
1944 this,
1945 entityId,
1946 position.tileX,
1947 position.tileY,
1948 originX,
1949 originY,
1950 bounds
1951 );
1952 if (!goal)
1953 { return false; }
1954 if (goal.tileX === position.tileX && goal.tileY === position.tileY)
1955 { return false; }
1956 const tiles = findPath(
1957 position.tileX,
1958 position.tileY,
1959 goal.tileX,
1960 goal.tileY,
1961 (x, y) => this.walkableFor(entityId, x, y),
1962 bounds.minX,
1963 bounds.minY,
1964 bounds.maxX,
1965 bounds.maxY,
1966 this.pathfindOptions({ preferPaths: true, entityId })
1967 );
1968 if (!tiles?.length)
1969 { return false; }
1970 path.tiles = tiles;
1971 const movement = this.ecs.get(handle, Component.movement);
1972 if (movement)
1973 { movement.walkCarry = 0; }
1974 return true;
1975 }
1976
1977 /**
1978 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1979 * message: { stationTileX, stationTileY, dimensionId? }
1980 */
1981 #stationExchangeClerk (message)
1982 {
1983 const stationTileX = message.stationTileX | 0;
1984 const stationTileY = message.stationTileY | 0;
1985 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1986 if (!this.isEnterable(stationTileX, stationTileY, dim))
1987 { return { ok: false, reason: "blocked" }; }
1988
1989 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1990 {
1991 if (!entity.spawnOrigin?.centralExchange)
1992 { continue; }
1993 if (
1994 Number.isInteger(entity.spawnOrigin.stationTileX)
1995 && entity.spawnOrigin.stationTileX === stationTileX
1996 && entity.spawnOrigin.stationTileY === stationTileY
1997 )
1998 { return { ok: true, entityId: entity.entityId, already: true }; }
1999 }
2000
2001 let best = null;
2002 let bestDist = Infinity;
2003 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
2004 {
2005 if (!entity.spawnOrigin?.centralExchange)
2006 { continue; }
2007 if (Number.isInteger(entity.spawnOrigin.stationTileX))
2008 { continue; }
2009 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
2010 if (entityDim !== dim)
2011 { continue; }
2012 const dist = Math.max(
2013 Math.abs(entity.position.tileX - stationTileX),
2014 Math.abs(entity.position.tileY - stationTileY)
2015 );
2016 if (dist < bestDist)
2017 {
2018 bestDist = dist;
2019 best = entity;
2020 }
2021 }
2022 if (!best)
2023 { return { ok: false, reason: "none-available" }; }
2024
2025 const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS);
2026 const tiles = findPath(
2027 best.position.tileX,
2028 best.position.tileY,
2029 stationTileX,
2030 stationTileY,
2031 (x, y) => this.walkableFor(best.entityId, x, y),
2032 bounds.minX,
2033 bounds.minY,
2034 bounds.maxX,
2035 bounds.maxY,
2036 this.pathfindOptions({ preferPaths: true, entityId: best.entityId })
2037 );
2038 best.spawnOrigin.stationTileX = stationTileX;
2039 best.spawnOrigin.stationTileY = stationTileY;
2040 if (tiles?.length)
2041 { best.path.tiles = tiles; }
2042 else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY)
2043 { best.path.tiles = []; }
2044 else
2045 { return { ok: false, reason: "no-path" }; }
2046 return { ok: true, entityId: best.entityId };
2047 }
2048
2049 /**
2050 * Clear a CE clerk's station assignment so wander can resume.
2051 * message: { stationTileX, stationTileY }
2052 */
2053 #releaseExchangeClerk (message)
2054 {
2055 const stationTileX = message.stationTileX | 0;
2056 const stationTileY = message.stationTileY | 0;
2057 let released = 0;
2058 for (const entity of this.ecs.query(Component.spawnOrigin, Component.path))
2059 {
2060 if (!entity.spawnOrigin?.centralExchange)
2061 { continue; }
2062 if (
2063 entity.spawnOrigin.stationTileX !== stationTileX
2064 || entity.spawnOrigin.stationTileY !== stationTileY
2065 )
2066 { continue; }
2067 entity.spawnOrigin.stationTileX = null;
2068 entity.spawnOrigin.stationTileY = null;
2069 entity.path.tiles = [];
2070 released += 1;
2071 }
2072 return { ok: true, released };
2073 }
2074
2075 #pinDialogue (entityId, characterId)
2076 {
2077 const handle = this.ecs.handleOf(entityId | 0);
2078 if (handle == null)
2079 { return { ok: false }; }
2080 const origin = this.ecs.get(handle, Component.spawnOrigin);
2081 if (!origin)
2082 { return { ok: false }; }
2083 if (!origin.dialogueBrowsers || typeof origin.dialogueBrowsers !== "object")
2084 { origin.dialogueBrowsers = Object.create(null); }
2085 origin.dialogueBrowsers[characterId | 0] = true;
2086 const path = this.ecs.get(handle, Component.path);
2087 if (path)
2088 { path.tiles = []; }
2089 return { ok: true };
2090 }
2091
2092 #unpinDialogue (entityId, characterId)
2093 {
2094 const handle = this.ecs.handleOf(entityId | 0);
2095 if (handle == null)
2096 { return { ok: false }; }
2097 const origin = this.ecs.get(handle, Component.spawnOrigin);
2098 if (!origin?.dialogueBrowsers)
2099 { return { ok: true }; }
2100 delete origin.dialogueBrowsers[characterId | 0];
2101 return { ok: true };
2102 }
2103
2104 #pruneDialogueBrowsers ()
2105 {
2106 const events = [];
2107 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
2108 {
2109 const browsers = entity.spawnOrigin?.dialogueBrowsers;
2110 const shearBrowsers = entity.spawnOrigin?.shearBrowsers;
2111 const dialogueIds = browsers && typeof browsers === "object"
2112 ? Object.keys(browsers).map((id) => Number(id))
2113 : [];
2114 const shearIds = shearBrowsers && typeof shearBrowsers === "object"
2115 ? Object.keys(shearBrowsers).map((id) => Number(id))
2116 : [];
2117 if (!dialogueIds.length && !shearIds.length)
2118 { continue; }
2119 const path = this.ecs.get(entity.handle, Component.path);
2120 if (path)
2121 { path.tiles = []; }
2122 for (const characterId of dialogueIds)
2123 {
2124 const playerEntityId = this.characterEntities.get(characterId);
2125 if (playerEntityId == null)
2126 {
2127 delete browsers[characterId];
2128 continue;
2129 }
2130 const playerHandle = this.ecs.handleOf(playerEntityId);
2131 const playerPos = this.ecs.get(playerHandle, Component.position);
2132 const npcDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
2133 const stillNear = playerPos
2134 && normalizeDimensionId(playerPos.dimensionId ?? OVERWORLD_ID) === npcDim
2135 && canTalkOrShopNear(
2136 playerPos.tileX,
2137 playerPos.tileY,
2138 entity.position.tileX,
2139 entity.position.tileY,
2140 (x, y) => this.blockTypeAt(x, y, npcDim)
2141 );
2142 if (stillNear)
2143 { continue; }
2144 delete browsers[characterId];
2145 const identity = this.ecs.get(playerHandle, Component.networkIdentity);
2146 events.push({
2147 type: "dialogue-walk-away",
2148 sessionId: identity?.sessionId ?? null,
2149 characterId,
2150 npcEntityId: entity.entityId
2151 });
2152 }
2153 for (const characterId of shearIds)
2154 {
2155 const playerEntityId = this.characterEntities.get(characterId);
2156 if (playerEntityId == null)
2157 {
2158 delete shearBrowsers[characterId];
2159 continue;
2160 }
2161 const playerHandle = this.ecs.handleOf(playerEntityId);
2162 const playerPos = this.ecs.get(playerHandle, Component.position);
2163 const stillNear = playerPos
2164 && chebyshev(
2165 playerPos.tileX,
2166 playerPos.tileY,
2167 entity.position.tileX,
2168 entity.position.tileY
2169 ) <= 1;
2170 if (stillNear)
2171 { continue; }
2172 delete shearBrowsers[characterId];
2173 }
2174 }
2175 return events;
2176 }
2177
2178 /** Keep stationed CE clerks at their counter tile. */
2179 #queueExchangeStations ()
2180 {
2181 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
2182 {
2183 if (!entity.spawnOrigin?.centralExchange)
2184 { continue; }
2185 const sx = entity.spawnOrigin.stationTileX;
2186 const sy = entity.spawnOrigin.stationTileY;
2187 if (!Number.isInteger(sx) || !Number.isInteger(sy))
2188 { continue; }
2189 if (entity.position.tileX === sx && entity.position.tileY === sy)
2190 {
2191 entity.path.tiles = [];
2192 continue;
2193 }
2194 if (entity.path.tiles?.length)
2195 { continue; }
2196 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
2197 const tiles = findPath(
2198 entity.position.tileX,
2199 entity.position.tileY,
2200 sx,
2201 sy,
2202 (x, y) => this.walkableFor(entity.entityId, x, y),
2203 bounds.minX,
2204 bounds.minY,
2205 bounds.maxX,
2206 bounds.maxY,
2207 this.pathfindOptions({ preferPaths: true, entityId: entity.entityId })
2208 );
2209 if (tiles?.length)
2210 { entity.path.tiles = tiles; }
2211 }
2212 }
2213
2214 #applyTransfer (message)
2215 {
2216 const payload = message.payload;
2217 const entityId = payload.entityId;
2218 if (this.ecs.hasEntity(entityId))
2219 { return { accepted: false, reason: "already-present" }; }
2220
2221 const position = payload.components?.position;
2222 const destTileX = message.destTileX ?? position?.tileX;
2223 const destTileY = message.destTileY ?? position?.tileY;
2224 const dimensionId = normalizeDimensionId(
2225 message.dimensionId ?? position?.dimensionId ?? OVERWORLD_ID
2226 );
2227 if (destTileX == null || destTileY == null)
2228 { return { accepted: false, reason: "missing-destination" }; }
2229 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY), dimensionId))
2230 { return { accepted: false, reason: "not-owner" }; }
2231
2232 const creature = payload.components?.creature;
2233 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
2234 if (flying)
2235 {
2236 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY), dimensionId);
2237 if (!data?.open)
2238 { return { accepted: false, reason: "blocked" }; }
2239 }
2240 else if (!this.isEnterable(destTileX, destTileY, dimensionId))
2241 { return { accepted: false, reason: "blocked" }; }
2242
2243 deserializeEntity(this.ecs, payload);
2244 const handle = this.ecs.handleOf(entityId);
2245 const livePosition = this.ecs.get(handle, Component.position);
2246 const path = this.ecs.get(handle, Component.path);
2247 livePosition.tileX = destTileX;
2248 livePosition.tileY = destTileY;
2249 livePosition.dimensionId = dimensionId;
2250 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
2251 { path.tiles.shift(); }
2252 if (!flying)
2253 { this.#occupy(entityId, destTileX, destTileY); }
2254 const character = this.ecs.get(handle, Component.character);
2255 if (character?.characterId)
2256 { this.characterEntities.set(character.characterId, entityId); }
2257 this.frozen.delete(entityId);
2258 return {
2259 accepted: true,
2260 entity: publicEntityView(this.ecs, entityId)
2261 };
2262 }
2263
2264 #commitTransfer (entityId)
2265 {
2266 if (!this.ecs.hasEntity(entityId))
2267 { return null; }
2268 return this.#destroyEntity(entityId);
2269 }
2270
2271 #abortTransfer (entityId)
2272 {
2273 this.frozen.delete(entityId);
2274 return publicEntityView(this.ecs, entityId);
2275 }
2276
2277 #listLoaders ()
2278 {
2279 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
2280 entityId: entity.entityId,
2281 tileX: entity.position.tileX,
2282 tileY: entity.position.tileY,
2283 dimensionId: normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID),
2284 chunkLoader: { ...entity.chunkLoader }
2285 }));
2286 }
2287
2288 #listPublicEntities ()
2289 {
2290 const out = [];
2291 for (const entity of this.ecs.query(Component.position))
2292 {
2293 if (this.ecs.has(entity.handle, Component.dead))
2294 { continue; }
2295 const view = publicEntityView(this.ecs, entity.entityId);
2296 if (view)
2297 { out.push(view); }
2298 }
2299 return out;
2300 }
2301
2302 #entitiesInRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
2303 {
2304 const dim = normalizeDimensionId(dimensionId);
2305 const records = [];
2306 for (const entity of this.ecs.query(Component.position))
2307 {
2308 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
2309 if (entityDim !== dim)
2310 { continue; }
2311 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
2312 { continue; }
2313 records.push({
2314 ...publicEntityView(this.ecs, entity.entityId),
2315 persistent: this.ecs.has(entity.handle, Component.persistent),
2316 payload: serializeEntity(this.ecs, entity.entityId)
2317 });
2318 }
2319 return records;
2320 }
2321
2322 #chunkSnapshot (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
2323 {
2324 const dim = normalizeDimensionId(dimensionId);
2325 const data = this.#chunkData(chunkX, chunkY, dim);
2326 if (staticOnly)
2327 {
2328 return {
2329 chunkX,
2330 chunkY,
2331 dimensionId: dim,
2332 open: data.open,
2333 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
2334 grounds: data.grounds,
2335 blocks: data.blocks,
2336 light: data.light,
2337 occlusion: data.occlusion,
2338 entities: [],
2339 groundItems: []
2340 };
2341 }
2342 const entities = [];
2343 for (const entity of this.ecs.query(Component.position, Component.appearance))
2344 {
2345 if (this.ecs.has(entity.handle, Component.dead))
2346 { continue; }
2347 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
2348 if (entityDim !== dim)
2349 { continue; }
2350 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
2351 { continue; }
2352 entities.push(publicEntityView(this.ecs, entity.entityId));
2353 }
2354 return {
2355 chunkX,
2356 chunkY,
2357 dimensionId: dim,
2358 open: data.open,
2359 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
2360 grounds: data.grounds,
2361 blocks: data.blocks,
2362 light: data.light,
2363 occlusion: data.occlusion,
2364 entities,
2365 groundItems: groundItemsInChunk(this, chunkX, chunkY, dim)
2366 };
2367 }
2368
2369 #moveEvent (entityId, fromTileX, fromTileY)
2370 {
2371 const view = publicEntityView(this.ecs, entityId);
2372 return {
2373 type: "entity-move",
2374 entityId,
2375 fromTileX,
2376 fromTileY,
2377 tileX: view.tileX,
2378 tileY: view.tileY,
2379 worldX: view.worldX,
2380 worldY: view.worldY,
2381 gait: view.gait,
2382 freeFlight: !!view.freeFlight
2383 };
2384 }
2385
2386 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
2387 {
2388 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId));
2389 return !!chunk && !chunk.replica && chunk.simulating;
2390 }
2391
2392 walkableFor (entityId, tileX, tileY)
2393 {
2394 const dim = this.#entityDimensionId(entityId);
2395 const handle = this.ecs.handleOf(entityId);
2396 if (this.#isFlying(handle))
2397 {
2398 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
2399 return !!data?.open;
2400 }
2401 // Entities pass through each other; only terrain / closed chunks block movement.
2402 return this.isEnterable(tileX, tileY, dim, {
2403 canOpenDoors: entityCanOpenDoors(this.ecs, entityId),
2404 requirementsAllow: entityDoorRequirementsAllow(this, entityId, tileX, tileY)
2405 });
2406 }
2407
2408 /** Ground type id at a world tile (defaults to world default ground). */
2409 groundTypeAt (tileX, tileY, dimensionId = OVERWORLD_ID)
2410 {
2411 const dim = normalizeDimensionId(dimensionId) ?? OVERWORLD_ID;
2412 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
2413 const entry = normalizeGround(data.grounds[tileIndex(tileToLocal(tileX), tileToLocal(tileY))]);
2414 return entry?.typeId ?? this.settings.defaultGroundTypeId ?? GroundType.grass;
2415 }
2416
2417 /**
2418 * @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null, penalizeCombatBackstep?: boolean }} [options]
2419 */
2420 pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null, penalizeCombatBackstep = false } = {})
2421 {
2422 const options = { preferVertical: !!preferVertical };
2423 const now = Date.now();
2424 const dimensionId = entityId != null ? this.#entityDimensionId(entityId) : OVERWORLD_ID;
2425 let prevTileX = null;
2426 let prevTileY = null;
2427 if (penalizeCombatBackstep && entityId != null)
2428 {
2429 const handle = this.ecs.handleOf(entityId);
2430 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2431 if (position?.prevTileX != null && position?.prevTileY != null)
2432 {
2433 prevTileX = position.prevTileX | 0;
2434 prevTileY = position.prevTileY | 0;
2435 }
2436 }
2437 options.stepCost = (x, y) =>
2438 {
2439 const base = stepCostForGround(
2440 this.groundTypeAt(x, y, dimensionId),
2441 {
2442 preferPaths: !!preferPaths,
2443 softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now)
2444 }
2445 );
2446 return withCombatBackstepCost(base, x, y, prevTileX, prevTileY);
2447 };
2448 options.minStepCost = preferPaths ? PATH_GROUND_STEP_COST : 1;
2449 return options;
2450 }
2451
2452 /**
2453 * True when another living occupant has stood on this tile for SOFT_OCCUPIED_DWELL_MS+.
2454 * Soft cost only — never blocks pathing.
2455 */
2456 #isSoftOccupiedTile (tileX, tileY, dimensionId, selfEntityId, now = Date.now())
2457 {
2458 const key = tileKey(tileX, tileY, dimensionId);
2459 const local = this.occupancy.get(key);
2460 if (!local?.size)
2461 { return false; }
2462 for (const id of local)
2463 {
2464 if (id === selfEntityId)
2465 { continue; }
2466 const handle = this.ecs.handleOf(id);
2467 if (handle == null)
2468 { continue; }
2469 const position = this.ecs.get(handle, Component.position);
2470 const enteredAt = position?.tileEnteredAt;
2471 if (enteredAt == null)
2472 { continue; }
2473 if (now - enteredAt >= SOFT_OCCUPIED_DWELL_MS)
2474 { return true; }
2475 }
2476 return false;
2477 }
2478
2479 /**
2480 * Standing tile with no other mob/player (self allowed). Used for wander goals
2481 * and melee attack stance.
2482 */
2483 isClearStanding (entityId, tileX, tileY)
2484 {
2485 const dim = this.#entityDimensionId(entityId);
2486 if (!this.isEnterable(tileX, tileY, dim, {
2487 canOpenDoors: entityCanOpenDoors(this.ecs, entityId),
2488 requirementsAllow: entityDoorRequirementsAllow(this, entityId, tileX, tileY)
2489 }))
2490 { return false; }
2491 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
2492 }
2493
2494 destroyEntity (entityId)
2495 {
2496 return this.#destroyEntity(entityId);
2497 }
2498
2499 occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
2500 {
2501 return this.#anyOccupant(tileX, tileY, dimensionId);
2502 }
2503
2504 #chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
2505 {
2506 return this.chunkIsSimulating(tileX, tileY, dimensionId);
2507 }
2508
2509 #chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
2510 {
2511 const loaded = this.chunks.get(chunkKey(chunkX, chunkY, dimensionId));
2512 if (loaded)
2513 { return loaded.data; }
2514 return createEmptyChunkData(this.settings.defaultGroundTypeId);
2515 }
2516
2517 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID, { canOpenDoors = false, requirementsAllow = true } = {})
2518 {
2519 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2520 if (!data.open)
2521 { return false; }
2522 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY), {
2523 canOpenDoors,
2524 requirementsAllow
2525 });
2526 }
2527
2528 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
2529 {
2530 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2531 if (!data.open)
2532 { return false; }
2533 return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));
2534 }
2535
2536 #walkableFor (entityId, tileX, tileY)
2537 {
2538 return this.walkableFor(entityId, tileX, tileY);
2539 }
2540
2541 #isFlying (handle)
2542 {
2543 if (handle == null)
2544 { return false; }
2545 const creature = this.ecs.get(handle, Component.creature);
2546 return !!mobDefinition(creature?.mobTypeId)?.flying;
2547 }
2548
2549 #entityDimensionId (entityId)
2550 {
2551 const handle = this.ecs.handleOf(entityId);
2552 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2553 return normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
2554 }
2555
2556 #occupy (entityId, tileX, tileY, now = Date.now())
2557 {
2558 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
2559 let set = this.occupancy.get(key);
2560 if (!set)
2561 {
2562 set = new Set();
2563 this.occupancy.set(key, set);
2564 }
2565 set.add(entityId);
2566 const handle = this.ecs.handleOf(entityId);
2567 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2568 if (position)
2569 { position.tileEnteredAt = now; }
2570 }
2571
2572 #vacate (entityId, tileX, tileY)
2573 {
2574 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
2575 const set = this.occupancy.get(key);
2576 if (!set)
2577 { return; }
2578 set.delete(entityId);
2579 if (set.size === 0)
2580 { this.occupancy.delete(key); }
2581 }
2582
2583 #anyOccupant (tileX, tileY, dimensionId = OVERWORLD_ID)
2584 {
2585 const key = tileKey(tileX, tileY, dimensionId);
2586 const local = this.occupancy.get(key);
2587 if (local?.size)
2588 { return local.values().next().value; }
2589 const ghosts = this.ghostOccupancy.get(key);
2590 if (ghosts?.size)
2591 { return ghosts.values().next().value; }
2592 return null;
2593 }
2594
2595 #hasOtherOccupant (entityId, tileX, tileY, dimensionId = null)
2596 {
2597 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : this.#entityDimensionId(entityId);
2598 const key = tileKey(tileX, tileY, dim);
2599 const local = this.occupancy.get(key);
2600 if (local)
2601 {
2602 for (const id of local)
2603 {
2604 if (id !== entityId)
2605 { return true; }
2606 }
2607 }
2608 const ghosts = this.ghostOccupancy.get(key);
2609 if (ghosts)
2610 {
2611 for (const id of ghosts)
2612 {
2613 if (id !== entityId)
2614 { return true; }
2615 }
2616 }
2617 return false;
2618 }
2619
2620 /** @deprecated use #anyOccupant — kept name for call sites expecting a single id */
2621 #occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
2622 {
2623 return this.#anyOccupant(tileX, tileY, dimensionId);
2624 }
2625}
2626
2627function pickWanderGoalInRange (world, entityId, originX, originY, range)
2628{
2629 const radius = Math.max(0, range | 0);
2630 for (let attempt = 0; attempt < 24; attempt++)
2631 {
2632 const tileX = originX + randInt(-radius, radius);
2633 const tileY = originY + randInt(-radius, radius);
2634 if (!world.isClearStanding(entityId, tileX, tileY))
2635 { continue; }
2636 return { tileX, tileY };
2637 }
2638 return null;
2639}
2640
2641/**
2642 * Clearest standable tile in pathfinding bounds, pulled toward (destX, destY).
2643 * When the destination is outside the window this becomes a chunk-step toward home.
2644 */
2645function pickClearGoalToward (world, entityId, fromX, fromY, destX, destY, bounds)
2646{
2647 const idealX = Math.max(bounds.minX, Math.min(bounds.maxX, destX | 0));
2648 const idealY = Math.max(bounds.minY, Math.min(bounds.maxY, destY | 0));
2649 if (world.isClearStanding(entityId, idealX, idealY))
2650 { return { tileX: idealX, tileY: idealY }; }
2651 for (let radius = 1; radius <= 4; radius++)
2652 {
2653 for (let dy = -radius; dy <= radius; dy++)
2654 {
2655 for (let dx = -radius; dx <= radius; dx++)
2656 {
2657 if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
2658 { continue; }
2659 const tileX = idealX + dx;
2660 const tileY = idealY + dy;
2661 if (tileX < bounds.minX || tileX > bounds.maxX || tileY < bounds.minY || tileY > bounds.maxY)
2662 { continue; }
2663 if (tileX === fromX && tileY === fromY)
2664 { continue; }
2665 if (!world.isClearStanding(entityId, tileX, tileY))
2666 { continue; }
2667 return { tileX, tileY };
2668 }
2669 }
2670 }
2671 return null;
2672}
2673
2674/** One random adjacent step so a stranded mob does not freeze in place. */
2675function queueLocalRandomWanderStep (world, entityId, position, path)
2676{
2677 const dirs = [
2678 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
2679 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
2680 ];
2681 for (let i = dirs.length - 1; i > 0; i--)
2682 {
2683 const j = Math.floor(Math.random() * (i + 1));
2684 const tmp = dirs[i];
2685 dirs[i] = dirs[j];
2686 dirs[j] = tmp;
2687 }
2688 for (const dir of dirs)
2689 {
2690 const nextX = position.tileX + dir.x;
2691 const nextY = position.tileY + dir.y;
2692 if (!world.isClearStanding(entityId, nextX, nextY))
2693 { continue; }
2694 path.tiles = [{ x: nextX, y: nextY }];
2695 return true;
2696 }
2697 return false;
2698}
2699
2700function hasDialogueBrowsers (origin)
2701{
2702 return originIsBusyPinned(origin);
2703}
2704
2705function randInt (min, max)
2706{
2707 return min + Math.floor(Math.random() * (max - min + 1));
2708}
2709
2710export function replicaNeededForOwnedChunks (ownedChunkKeys)
2711{
2712 const needed = new Set();
2713 for (const key of ownedChunkKeys)
2714 {
2715 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
2716 for (let dy = -1; dy <= 1; dy++)
2717 {
2718 for (let dx = -1; dx <= 1; dx++)
2719 {
2720 if (dx === 0 && dy === 0)
2721 { continue; }
2722 needed.add(chunkKey(chunkX + dx, chunkY + dy, dimensionId));
2723 }
2724 }
2725 }
2726 return needed;
2727}