BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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