BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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