BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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