BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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