BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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