BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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