BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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