BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

workerWorld.js 46.1 KiB Download Raw
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js";
2import {
3 chunkKey,
4 chunkToRegion,
5 parseChunkKey,
6 regionKey,
7 tileKey,
8 tileToChunk,
9 tileToLocal,
10 tileToRegion
11} from "../world/coordinates.js";
12import { cloneChunkData, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
13import { closedNeighborEdges } from "../world/chunkFlags.js";
14import { EcsWorld } from "../ecs/world.js";
15import { Component } from "../ecs/components.js";
16import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js";
17import { chunkBoundsAround, findPath } from "../navigation/astar.js";
18import { WorkerMessage } from "./protocol.js";
19import { collectSpawnRequests } from "./spawners.js";
20import { mobDefinition } from "../../../shared/definitions/mobs.js";
21import {
22 bagView,
23 applyBagView,
24 addGroundItem,
25 expireGroundItems,
26 groundItemsInChunk,
27 groundItemsInRegion,
28 handleItemCommand,
29 removeGroundItem,
30 publicGroundItem,
31 setGroundItemsForRegion
32} from "../items/bags.js";
33import { handleAlchemyCommand } from "../alchemy/service.js";
34import {
35 handleGatherCommand,
36 stepGather,
37 cancelGather,
38 clearOreRespawnsForChunk,
39 clearTreeRespawnsForChunk
40} from "../gathering/service.js";
41import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
42import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
43import {
44 applyRemoteMeleeSwing,
45 clearEngage,
46 engageTarget,
47 ensureMobCombat,
48 isUntargetable,
49 resolveCombatTarget,
50 stepAggression,
51 stepCombat
52} from "../combat/service.js";
53import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
54import { SkillId } from "../../../shared/definitions/skills.js";
55import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
56import {
57 STAMINA_REGEN_PER_SECOND,
58 STAMINA_XP_PER_POINT_SPENT,
59 staminaCostPerRunStep,
60 publicStaminaView
61} from "../../../shared/stamina/rules.js";
62import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
63import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
64
65export class WorkerWorld
66{
67 constructor (workerId)
68 {
69 this.workerId = workerId;
70 this.ecs = new EcsWorld();
71 this.chunks = new Map();
72 this.ownedRegions = new Set();
73 this.occupancy = new Map();
74 this.ghosts = new Map();
75 this.ghostOccupancy = new Map();
76 this.characterEntities = new Map();
77 this.frozen = new Set();
78 this.groundItems = new Map();
79 this.groundByTile = new Map();
80 this.oreRespawns = new Map();
81 this.treeRespawns = new Map();
82 this.settings = { ...DEFAULT_WORLD_SETTINGS };
83 this.activeRevisionId = 1;
84 }
85
86 handle (message)
87 {
88 switch (message.type)
89 {
90 case WorkerMessage.configure:
91 return this.#configure(message);
92 case WorkerMessage.assignRegion:
93 return this.#assignRegion(message);
94 case WorkerMessage.dropRegion:
95 return this.#dropRegion(message);
96 case WorkerMessage.replaceRegionChunks:
97 return this.#replaceRegionChunks(message);
98 case WorkerMessage.setReplicas:
99 return this.#setReplicas(message);
100 case WorkerMessage.setSimulatingChunks:
101 return this.#setSimulatingChunks(message);
102 case WorkerMessage.setGhosts:
103 return this.#setGhosts(message);
104 case WorkerMessage.spawn:
105 return this.#spawn(message);
106 case WorkerMessage.despawn:
107 return this.#despawn(message.entityId);
108 case WorkerMessage.despawnCharacter:
109 return this.#despawnCharacter(message.characterId);
110 case WorkerMessage.command:
111 return this.#command(message);
112 case WorkerMessage.stepMovement:
113 return this.#stepMovement(message.now);
114 case WorkerMessage.stepSystems:
115 return this.#stepSystems(message.now, message.dt ?? (1 / 20));
116 case WorkerMessage.stepSpawners:
117 return { spawnRequests: collectSpawnRequests(this) };
118 case WorkerMessage.setGroundItems:
119 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
120 return { ok: true };
121 case WorkerMessage.inspectBag:
122 return this.#inspectBag(message.entityId);
123 case WorkerMessage.inspectSkills:
124 return this.#inspectSkills(message.entityId);
125 case WorkerMessage.inspectStamina:
126 return this.#inspectStamina(message.entityId);
127 case WorkerMessage.applyBag:
128 return this.#applyBag(message.entityId, message.bag);
129 case WorkerMessage.updateFlight:
130 return this.#updateFlight(message.entityId, message.flight, message.now);
131 case WorkerMessage.chunkIsSimulating:
132 return this.chunkIsSimulating(message.tileX, message.tileY);
133 case WorkerMessage.applyTransfer:
134 return this.#applyTransfer(message);
135 case WorkerMessage.commitTransfer:
136 return this.#commitTransfer(message.entityId);
137 case WorkerMessage.abortTransfer:
138 return this.#abortTransfer(message.entityId);
139 case WorkerMessage.snapshotChunk:
140 return this.#chunkSnapshot(message.chunkX, message.chunkY);
141 case WorkerMessage.listLoaders:
142 return this.#listLoaders();
143 case WorkerMessage.listPublicEntities:
144 return this.#listPublicEntities();
145 case WorkerMessage.entitiesInRegion:
146 return this.#entitiesInRegion(message.regionX, message.regionY);
147 case WorkerMessage.inspect:
148 return publicEntityView(this.ecs, message.entityId);
149 case WorkerMessage.remoteCombatEngage:
150 return this.#remoteCombatEngage(message);
151 case WorkerMessage.applyRemoteMelee:
152 return this.#applyRemoteMelee(message);
153 case WorkerMessage.applyCombatHitXp:
154 return this.#applyCombatHitXp(message);
155 case WorkerMessage.spawnCorpseDrops:
156 return this.#spawnCorpseDrops(message);
157 case WorkerMessage.applyRespawn:
158 return this.#applyRespawn(message);
159 case WorkerMessage.clearCombat:
160 clearEngage(this.ecs, message.entityId);
161 for (const entity of this.ecs.query(Component.combat))
162 {
163 if (entity.combat.targetEntityId === message.targetEntityId)
164 { entity.combat.targetEntityId = null; }
165 }
166 return { ok: true };
167 case WorkerMessage.setItemLastSales:
168 {
169 this.itemLastSales = new Map();
170 for (const [key, sale] of Object.entries(message.sales ?? {}))
171 { this.itemLastSales.set(Number(key), sale); }
172 return { ok: true };
173 }
174 case WorkerMessage.stationExchangeClerk:
175 return this.#stationExchangeClerk(message);
176 case WorkerMessage.releaseExchangeClerk:
177 return this.#releaseExchangeClerk(message);
178 default:
179 throw new Error(`Unknown worker message ${message.type}`);
180 }
181 }
182
183 ownsRegion (regionX, regionY)
184 {
185 return this.ownedRegions.has(regionKey(regionX, regionY));
186 }
187
188 requireOwnedEntity (sessionId, characterId)
189 {
190 return this.#requireOwnedEntity(sessionId, characterId);
191 }
192
193 chunkData (chunkX, chunkY)
194 {
195 return this.#chunkData(chunkX, chunkY);
196 }
197
198 occupied (tileX, tileY)
199 {
200 return this.#occupied(tileX, tileY);
201 }
202
203 #configure (message)
204 {
205 if (message.settings)
206 { this.settings = { ...this.settings, ...message.settings }; }
207 if (message.activeRevisionId != null)
208 { this.activeRevisionId = message.activeRevisionId; }
209 return { ok: true };
210 }
211
212 #assignRegion (message)
213 {
214 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
215 for (const chunk of message.chunks ?? [])
216 {
217 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
218 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
219 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
220 data: cloneChunkData(chunk.data),
221 simulating: false,
222 replica: false
223 });
224 }
225 return { ok: true };
226 }
227
228 #replaceRegionChunks (message)
229 {
230 for (const chunk of message.chunks ?? [])
231 {
232 const key = chunkKey(chunk.chunkX, chunk.chunkY);
233 const existing = this.chunks.get(key);
234 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
235 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
236 this.chunks.set(key, {
237 data: cloneChunkData(chunk.data),
238 simulating: existing?.simulating ?? false,
239 replica: existing?.replica ?? false
240 });
241 }
242 return { ok: true };
243 }
244
245 #dropRegion (message)
246 {
247 const dropped = [];
248 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
249 {
250 const components = record.payload?.components;
251 if (components?.creature && !components?.character && components?.health)
252 { components.health.current = components.health.max; }
253 dropped.push(record);
254 this.#destroyEntity(record.entityId);
255 }
256 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
257 for (const item of groundItems)
258 { removeGroundItem(this, item.groundItemId); }
259 for (const [key, chunk] of [...this.chunks.entries()])
260 {
261 const { chunkX, chunkY } = parseChunkKey(key);
262 if (chunk.replica)
263 { continue; }
264 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
265 {
266 clearOreRespawnsForChunk(this, chunkX, chunkY);
267 clearTreeRespawnsForChunk(this, chunkX, chunkY);
268 this.chunks.delete(key);
269 }
270 }
271 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
272 return { dropped, groundItems };
273 }
274
275 #setReplicas (message)
276 {
277 const keep = new Set();
278 for (const chunk of message.chunks ?? [])
279 {
280 const key = chunkKey(chunk.chunkX, chunk.chunkY);
281 keep.add(key);
282 const existing = this.chunks.get(key);
283 if (existing && !existing.replica)
284 { continue; }
285 this.chunks.set(key, {
286 data: cloneChunkData(chunk.data),
287 simulating: false,
288 replica: true
289 });
290 }
291 for (const [key, chunk] of [...this.chunks.entries()])
292 {
293 if (chunk.replica && !keep.has(key))
294 { this.chunks.delete(key); }
295 }
296 return { ok: true };
297 }
298
299 #setSimulatingChunks (message)
300 {
301 const simulating = new Set(message.chunkKeys ?? []);
302 for (const [key, chunk] of this.chunks)
303 {
304 if (chunk.replica)
305 {
306 chunk.simulating = false;
307 continue;
308 }
309 chunk.simulating = simulating.has(key);
310 }
311 return { ok: true };
312 }
313
314 #setGhosts (message)
315 {
316 this.ghosts.clear();
317 this.ghostOccupancy.clear();
318 for (const ghost of message.ghosts ?? [])
319 {
320 this.ghosts.set(ghost.entityId, ghost);
321 this.ghostOccupancy.set(tileKey(ghost.tileX, ghost.tileY), ghost.entityId);
322 }
323 return { ok: true };
324 }
325
326 #spawn (message)
327 {
328 const entityId = deserializeEntity(this.ecs, message);
329 const handle = this.ecs.handleOf(entityId);
330 const position = this.ecs.get(handle, Component.position);
331 if (!position)
332 {
333 this.ecs.destroy(handle);
334 throw new Error("Spawned entity is missing position.");
335 }
336 const flying = this.#isFlying(handle);
337 if (!flying)
338 {
339 const occupant = this.#occupied(position.tileX, position.tileY);
340 if (occupant && occupant !== entityId)
341 {
342 this.ecs.destroy(handle);
343 const error = new Error("That tile is occupied.");
344 error.userFacing = true;
345 throw error;
346 }
347 this.#occupy(entityId, position.tileX, position.tileY);
348 }
349 const creature = this.ecs.get(handle, Component.creature);
350 const def = creature ? mobDefinition(creature.mobTypeId) : null;
351 if (def?.freeFlight)
352 { ensureFlightComponent(this.ecs, handle, position, def); }
353 const character = this.ecs.get(handle, Component.character);
354 if (character?.characterId)
355 { this.characterEntities.set(character.characterId, entityId); }
356 return publicEntityView(this.ecs, entityId);
357 }
358
359 #despawn (entityId)
360 {
361 return this.#destroyEntity(entityId);
362 }
363
364 #despawnCharacter (characterId)
365 {
366 releaseShopBrowsersForCharacter(this, characterId);
367 const entityId = this.characterEntities.get(characterId);
368 if (!entityId)
369 { return null; }
370 return this.#destroyEntity(entityId);
371 }
372
373 #destroyEntity (entityId)
374 {
375 const handle = this.ecs.handleOf(entityId);
376 if (handle == null)
377 { return null; }
378 const view = publicEntityView(this.ecs, entityId);
379 const position = this.ecs.get(handle, Component.position);
380 const character = this.ecs.get(handle, Component.character);
381 if (position && !this.#isFlying(handle))
382 { this.#vacate(entityId, position.tileX, position.tileY); }
383 if (character?.characterId)
384 { this.characterEntities.delete(character.characterId); }
385 this.frozen.delete(entityId);
386 this.ecs.destroy(handle);
387 return view;
388 }
389
390 #command (message)
391 {
392 const { sessionId, command } = message;
393 switch (command.type)
394 {
395 case "move-to":
396 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
397 return { events: [] };
398 case "set-gait":
399 return this.#setGait(sessionId, command.characterId, command.gait);
400 case "attack":
401 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
402 case "cancel-attack":
403 return this.#cancelAttack(sessionId, command.characterId);
404 case "interact":
405 return this.#interact(sessionId, command.characterId, command.targetEntityId);
406 case "follow":
407 return this.#follow(sessionId, command.characterId, command.targetEntityId);
408 case "cancel-follow":
409 return this.#cancelFollow(sessionId, command.characterId);
410 default:
411 {
412 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
413 if (gather)
414 { return gather; }
415 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
416 if (craft)
417 { return craft; }
418 const shop = handleShopCommand(this, sessionId, command, message.now ?? Date.now());
419 if (shop)
420 { return shop; }
421 const alchemy = handleAlchemyCommand(this, sessionId, command);
422 if (alchemy)
423 { return alchemy; }
424 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
425 return result ?? { events: [] };
426 }
427 }
428 }
429
430 #spawnCorpseDrops (message)
431 {
432 const events = [];
433 for (const drop of message.drops ?? [])
434 {
435 const item = {
436 groundItemId: drop.groundItemId,
437 tileX: message.tileX,
438 tileY: message.tileY,
439 stack: { itemId: drop.itemId, quantity: 1 },
440 droppedAt: message.now,
441 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
442 source: "player-death",
443 droppedByCharacterId: message.characterId
444 };
445 addGroundItem(this, item);
446 events.push({
447 type: "ground-item-appear",
448 ...publicGroundItem(item),
449 stack: item.stack,
450 droppedAt: item.droppedAt,
451 source: item.source,
452 droppedByCharacterId: item.droppedByCharacterId,
453 expiresAt: item.expiresAt
454 });
455 }
456 return { events };
457 }
458
459 #applyRespawn (message)
460 {
461 const handle = this.ecs.handleOf(message.entityId);
462 if (handle == null || !this.ecs.has(handle, Component.dead))
463 { return { accepted: false }; }
464 const position = this.ecs.get(handle, Component.position);
465 const fromTileX = position.tileX;
466 const fromTileY = position.tileY;
467 const health = this.ecs.get(handle, Component.health);
468 const stamina = this.ecs.get(handle, Component.stamina);
469 if (health)
470 {
471 health.max = message.maxHealth;
472 health.current = message.maxHealth;
473 }
474 if (stamina)
475 {
476 stamina.max = message.maxStamina;
477 stamina.current = message.maxStamina;
478 }
479 else
480 { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); }
481 this.ecs.remove(handle, Component.dead);
482 clearEngage(this.ecs, message.entityId);
483 const path = this.ecs.get(handle, Component.path);
484 if (path)
485 { path.tiles = []; }
486 clearFollow(this.ecs, message.entityId);
487
488 const destRegionX = tileToRegion(message.tileX);
489 const destRegionY = tileToRegion(message.tileY);
490 if (!this.ownsRegion(destRegionX, destRegionY))
491 {
492 this.frozen.add(message.entityId);
493 return {
494 accepted: true,
495 transferRequest: {
496 entityId: message.entityId,
497 fromTileX,
498 fromTileY,
499 destTileX: message.tileX,
500 destTileY: message.tileY,
501 toRegionX: destRegionX,
502 toRegionY: destRegionY,
503 payload: serializeEntity(this.ecs, message.entityId)
504 }
505 };
506 }
507 const occupant = this.#occupied(message.tileX, message.tileY);
508 if (!this.isEnterable(message.tileX, message.tileY)
509 || (occupant && occupant !== message.entityId))
510 { return { accepted: false }; }
511 this.#vacate(message.entityId, fromTileX, fromTileY);
512 position.tileX = message.tileX;
513 position.tileY = message.tileY;
514 this.#occupy(message.entityId, position.tileX, position.tileY);
515 return {
516 accepted: true,
517 event: {
518 type: "entity-move",
519 entityId: message.entityId,
520 fromTileX,
521 fromTileY,
522 tileX: position.tileX,
523 tileY: position.tileY,
524 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
525 }
526 };
527 }
528
529 #inspectBag (entityId)
530 {
531 const handle = this.ecs.handleOf(entityId);
532 if (handle == null)
533 { return null; }
534 return bagView(this.ecs, handle);
535 }
536
537 #inspectSkills (entityId)
538 {
539 const handle = this.ecs.handleOf(entityId);
540 if (handle == null)
541 { return null; }
542 const skills = this.ecs.get(handle, Component.skills);
543 if (!skills?.xp)
544 { return null; }
545 return skills;
546 }
547
548 #inspectStamina (entityId)
549 {
550 const handle = this.ecs.handleOf(entityId);
551 if (handle == null)
552 { return null; }
553 const stamina = this.ecs.get(handle, Component.stamina);
554 const movement = this.ecs.get(handle, Component.movement);
555 if (!stamina)
556 { return null; }
557 return {
558 ...publicStaminaView(stamina),
559 gait: movement?.gait ?? GAIT.walk
560 };
561 }
562
563 #applyBag (entityId, bag)
564 {
565 const handle = this.ecs.handleOf(entityId);
566 if (handle == null)
567 { return null; }
568 return applyBagView(this.ecs, handle, bag);
569 }
570
571 #updateFlight (entityId, flightPatch, now = Date.now())
572 {
573 const handle = this.ecs.handleOf(entityId);
574 if (handle == null)
575 { return null; }
576 let flight = this.ecs.get(handle, Component.flight);
577 if (!flight)
578 { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); }
579 else
580 { Object.assign(flight, flightPatch); }
581 const position = this.ecs.get(handle, Component.position);
582 const movement = this.ecs.get(handle, Component.movement);
583 const fromTileX = position.tileX;
584 const fromTileY = position.tileY;
585 const tileX = Math.floor(flight.x);
586 const tileY = Math.floor(flight.y);
587 position.tileX = tileX;
588 position.tileY = tileY;
589 const destRegionX = tileToRegion(tileX);
590 const destRegionY = tileToRegion(tileY);
591 if (!this.ownsRegion(destRegionX, destRegionY))
592 {
593 this.frozen.add(entityId);
594 return {
595 transferRequest: {
596 type: "transfer-request",
597 entityId,
598 fromTileX,
599 fromTileY,
600 destTileX: tileX,
601 destTileY: tileY,
602 toRegionX: destRegionX,
603 toRegionY: destRegionY
604 }
605 };
606 }
607 const dt = flight.lastAt && now > flight.lastAt
608 ? Math.min(0.25, (now - flight.lastAt) / 1000)
609 : 1 / 20;
610 return {
611 event: {
612 type: "entity-move",
613 entityId,
614 fromTileX,
615 fromTileY,
616 tileX,
617 tileY,
618 worldX: flight.x,
619 worldY: flight.y,
620 gait: movement?.gait ?? "walk",
621 lerpMs: Math.max(50, Math.round(dt * 1000)),
622 freeFlight: true
623 }
624 };
625 }
626
627 #moveTo (sessionId, characterId, tileX, tileY)
628 {
629 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
630 if (this.frozen.has(entityId))
631 { return; }
632 clearEngage(this.ecs, entityId);
633 clearFollow(this.ecs, entityId);
634 cancelGather(this.ecs, handle);
635 const position = this.ecs.get(handle, Component.position);
636 const movement = this.ecs.get(handle, Component.movement);
637 let path = this.ecs.get(handle, Component.path);
638 if (!path)
639 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
640 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
641 path.tiles = findPath(
642 position.tileX,
643 position.tileY,
644 tileX,
645 tileY,
646 (x, y) => this.walkableFor(entityId, x, y),
647 bounds.minX,
648 bounds.minY,
649 bounds.maxX,
650 bounds.maxY
651 );
652 movement.walkCarry = 0;
653 }
654
655 #attack (sessionId, characterId, targetEntityId, now)
656 {
657 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
658 if (targetEntityId === entityId)
659 {
660 const error = new Error("Cannot attack yourself.");
661 error.userFacing = true;
662 throw error;
663 }
664 const target = resolveCombatTarget(this, targetEntityId);
665 if (!target)
666 {
667 const error = new Error("Target is not here.");
668 error.userFacing = true;
669 throw error;
670 }
671 if (target.health && target.health.current <= 0)
672 {
673 const error = new Error("That cannot be attacked.");
674 error.userFacing = true;
675 throw error;
676 }
677 if (!this.ecs.get(handle, Component.combat))
678 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
679 clearFollow(this.ecs, entityId);
680 cancelGather(this.ecs, handle);
681 // Engage only the attacker. Targets retaliate on the first resolved swing.
682 engageTarget(this.ecs, entityId, targetEntityId, now);
683 const path = this.ecs.get(handle, Component.path);
684 if (path)
685 { path.tiles = []; }
686 return { events: [] };
687 }
688
689 #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })
690 {
691 // Kept for cross-worker hooks; retaliation happens on swing resolution, not Attack click.
692 void attackerEntityId;
693 void targetEntityId;
694 void now;
695 return { events: [] };
696 }
697
698 #applyRemoteMelee (payload)
699 {
700 return applyRemoteMeleeSwing(this, payload);
701 }
702
703 #applyCombatHitXp ({ entityId, profile })
704 {
705 const handle = this.ecs.handleOf(entityId);
706 if (handle == null)
707 { return { events: [] }; }
708 const character = this.ecs.get(handle, Component.character);
709 if (!character)
710 { return { events: [] }; }
711 const xpAward = awardCombatHitXp(this.ecs, handle, profile);
712 if (!xpAward)
713 { return { events: [] }; }
714 return {
715 events: [{
716 type: "skills-updated",
717 entityId,
718 characterId: character.characterId,
719 skills: xpAward.view,
720 stored: xpAward.stored
721 }]
722 };
723 }
724
725 #cancelAttack (sessionId, characterId)
726 {
727 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
728 clearEngage(this.ecs, entityId);
729 return { events: [] };
730 }
731
732 #interact (sessionId, characterId, targetEntityId)
733 {
734 this.#requireOwnedEntity(sessionId, characterId);
735 const targetHandle = this.ecs.handleOf(targetEntityId);
736 if (targetHandle == null)
737 {
738 const error = new Error("Target is not here.");
739 error.userFacing = true;
740 throw error;
741 }
742 if (isUntargetable(this.ecs, targetHandle))
743 {
744 const error = new Error("Nothing to say.");
745 error.userFacing = true;
746 throw error;
747 }
748 const creature = this.ecs.get(targetHandle, Component.creature);
749 const def = creature ? mobDefinition(creature.mobTypeId) : null;
750 const shop = this.ecs.get(targetHandle, Component.shop);
751 if (shopHasInterface(shop))
752 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
753 if (!def?.talkable)
754 {
755 const error = new Error("They have nothing to say.");
756 error.userFacing = true;
757 throw error;
758 }
759 // Dialogue comes later; talkable NPCs without stock are a no-op for now.
760 return { events: [] };
761 }
762
763 #follow (sessionId, characterId, targetEntityId)
764 {
765 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
766 const targetHandle = this.ecs.handleOf(targetEntityId);
767 if (targetHandle == null)
768 {
769 const error = new Error("Target is not here.");
770 error.userFacing = true;
771 throw error;
772 }
773 if (targetEntityId === entityId)
774 {
775 const error = new Error("Cannot follow yourself.");
776 error.userFacing = true;
777 throw error;
778 }
779 if (!this.ecs.get(targetHandle, Component.position))
780 {
781 const error = new Error("That cannot be followed.");
782 error.userFacing = true;
783 throw error;
784 }
785 clearEngage(this.ecs, entityId);
786 setFollow(this.ecs, entityId, targetEntityId);
787 const path = this.ecs.get(handle, Component.path);
788 if (path)
789 { path.tiles = []; }
790 return { events: [] };
791 }
792
793 #cancelFollow (sessionId, characterId)
794 {
795 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
796 clearFollow(this.ecs, entityId);
797 return { events: [] };
798 }
799
800 #setGait (sessionId, characterId, gait)
801 {
802 if (gait !== GAIT.walk && gait !== GAIT.run)
803 {
804 const error = new Error("Gait must be walk or run.");
805 error.userFacing = true;
806 throw error;
807 }
808 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
809 const movement = this.ecs.get(handle, Component.movement);
810 const stamina = this.ecs.get(handle, Component.stamina);
811 if (gait === GAIT.run && !(Number(stamina?.current) > 0))
812 {
813 const error = new Error("You are too exhausted to run.");
814 error.userFacing = true;
815 throw error;
816 }
817 movement.gait = gait;
818 const character = this.ecs.get(handle, Component.character);
819 return {
820 events: character
821 ? [this.#staminaEvent(handle, character.characterId, movement.gait)]
822 : []
823 };
824 }
825
826 #staminaEvent (handle, characterId, gait = null)
827 {
828 const stamina = this.ecs.get(handle, Component.stamina);
829 const movement = this.ecs.get(handle, Component.movement);
830 return {
831 type: "stamina",
832 characterId,
833 ...publicStaminaView(stamina),
834 gait: gait ?? movement?.gait ?? GAIT.walk
835 };
836 }
837
838 #consumeRunStamina (handle, events)
839 {
840 const character = this.ecs.get(handle, Component.character);
841 if (!character)
842 { return; }
843 let stamina = this.ecs.get(handle, Component.stamina);
844 if (!stamina)
845 {
846 stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 });
847 }
848 const skills = this.ecs.get(handle, Component.skills);
849 syncPlayerStamina(this.ecs, handle);
850 const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond);
851 stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost);
852 stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost;
853 let skillsChanged = false;
854 while (stamina.xpDebt >= 1 && skills?.xp)
855 {
856 stamina.xpDebt -= 1;
857 if (addSkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT))
858 {
859 skillsChanged = true;
860 syncPlayerStamina(this.ecs, handle);
861 }
862 }
863 const movement = this.ecs.get(handle, Component.movement);
864 if (stamina.current <= 0 && movement)
865 {
866 stamina.current = 0;
867 movement.gait = GAIT.walk;
868 }
869 events.push(this.#staminaEvent(handle, character.characterId));
870 if (skillsChanged)
871 {
872 events.push({
873 type: "skills-updated",
874 characterId: character.characterId,
875 skills: publicSkillsView(skills),
876 stored: storedSkillXp(skills)
877 });
878 }
879 }
880
881 #regenStamina (dt, events)
882 {
883 if (!(dt > 0))
884 { return; }
885 for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement))
886 {
887 const { handle, character, stamina, movement } = entity;
888 if (this.ecs.has(handle, Component.dead))
889 { continue; }
890 // Run gait only blocks regen while actually stepping along a path.
891 const path = this.ecs.get(handle, Component.path);
892 if (movement.gait === GAIT.run && path?.tiles?.length)
893 { continue; }
894 syncPlayerStamina(this.ecs, handle);
895 const before = Number(stamina.current) || 0;
896 if (before >= stamina.max)
897 { continue; }
898 stamina.current = Math.min(stamina.max, before + dt * STAMINA_REGEN_PER_SECOND);
899 const after = Number(stamina.current) || 0;
900 // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
901 if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
902 { events.push(this.#staminaEvent(handle, character.characterId)); }
903 }
904 }
905
906 #requireOwnedEntity (sessionId, characterId)
907 {
908 const entityId = this.characterEntities.get(characterId);
909 if (!entityId)
910 {
911 const error = new Error("Character is not in the world.");
912 error.userFacing = true;
913 throw error;
914 }
915 const handle = this.ecs.handleOf(entityId);
916 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
917 if (!identity || identity.sessionId !== sessionId)
918 {
919 const error = new Error("Character is not in the world.");
920 error.userFacing = true;
921 throw error;
922 }
923 if (this.ecs.has(handle, Component.dead))
924 {
925 const error = new Error("You are dead.");
926 error.userFacing = true;
927 throw error;
928 }
929 return { handle, entityId };
930 }
931
932 #stepSystems (now = Date.now(), dt = 1 / 20)
933 {
934 const events = [];
935 const transferRequests = [];
936 this.#regenStamina(dt, events);
937 const flight = stepFreeFlight(this, now);
938 for (const event of flight)
939 {
940 if (event.type === "transfer-request")
941 {
942 const payload = serializeEntity(this.ecs, event.entityId);
943 transferRequests.push({
944 entityId: event.entityId,
945 fromTileX: event.fromTileX,
946 fromTileY: event.fromTileY,
947 destTileX: event.destTileX,
948 destTileY: event.destTileY,
949 toRegionX: event.toRegionX,
950 toRegionY: event.toRegionY,
951 payload
952 });
953 continue;
954 }
955 events.push(event);
956 }
957 stepAggression(this, now);
958 events.push(...stepCombat(this, now));
959 stepFollow(this);
960 const gather = stepGather(this, now);
961 events.push(...gather.events);
962 for (const entry of gather.privates ?? [])
963 {
964 events.push({
965 type: "inventory",
966 characterId: entry.characterId,
967 ...entry.bag
968 });
969 }
970 const craft = stepCrafting(this, now);
971 events.push(...craft.events);
972 for (const entry of craft.privates ?? [])
973 {
974 events.push({
975 type: "inventory",
976 characterId: entry.characterId,
977 ...entry.bag
978 });
979 }
980 return { events, transferRequests };
981 }
982
983 #stepMovement (now = Date.now())
984 {
985 const events = expireGroundItems(this, now);
986 const transferRequests = [];
987 events.push(...pruneShopBrowsers(this));
988 this.#queueAmbientWander();
989 this.#queueSpawnerWander();
990 this.#queueExchangeStations();
991 for (const entity of this.ecs.query(Component.position, Component.movement))
992 {
993 const { handle, entityId, position, movement } = entity;
994 if (this.ecs.has(handle, Component.dead))
995 { continue; }
996 if (this.ecs.has(handle, Component.flight))
997 { continue; }
998 const path = this.ecs.get(handle, Component.path);
999 const tiles = path?.tiles;
1000 if (this.frozen.has(entityId) || !tiles?.length)
1001 {
1002 if (path)
1003 { path.stuckSince = null; }
1004 continue;
1005 }
1006 if (!this.chunkIsSimulating(position.tileX, position.tileY))
1007 { continue; }
1008
1009 this.#repathIfNavigationStuck(entityId, position, movement, path, now);
1010
1011 const stamina = this.ecs.get(handle, Component.stamina);
1012 if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))
1013 { movement.gait = GAIT.walk; }
1014 const isWalk = movement.gait !== GAIT.run;
1015 if (isWalk)
1016 {
1017 movement.walkCarry = (movement.walkCarry + 1) % 2;
1018 if (movement.walkCarry !== 0)
1019 { continue; }
1020 }
1021
1022 const next = tiles[0];
1023 if (!next)
1024 { continue; }
1025 const destRegionX = tileToRegion(next.x);
1026 const destRegionY = tileToRegion(next.y);
1027 if (!this.ownsRegion(destRegionX, destRegionY))
1028 {
1029 this.frozen.add(entityId);
1030 transferRequests.push({
1031 entityId,
1032 fromTileX: position.tileX,
1033 fromTileY: position.tileY,
1034 destTileX: next.x,
1035 destTileY: next.y,
1036 toRegionX: destRegionX,
1037 toRegionY: destRegionY,
1038 payload: serializeEntity(this.ecs, entityId)
1039 });
1040 continue;
1041 }
1042
1043 if (!this.walkableFor(entityId, next.x, next.y))
1044 {
1045 const combat = this.ecs.get(handle, Component.combat);
1046 if (combat?.targetEntityId != null)
1047 {
1048 const targetHandle = this.ecs.handleOf(combat.targetEntityId);
1049 const targetPos = targetHandle != null
1050 ? this.ecs.get(targetHandle, Component.position)
1051 : null;
1052 const blockedByTarget = targetPos
1053 && next.x === targetPos.tileX
1054 && next.y === targetPos.tileY;
1055 if (!blockedByTarget)
1056 { path.tiles = []; }
1057 }
1058 continue;
1059 }
1060
1061 const fromTileX = position.tileX;
1062 const fromTileY = position.tileY;
1063 const flying = this.#isFlying(handle);
1064 if (!flying)
1065 { this.#vacate(entityId, fromTileX, fromTileY); }
1066 position.tileX = next.x;
1067 position.tileY = next.y;
1068 tiles.shift();
1069 if (!flying)
1070 { this.#occupy(entityId, position.tileX, position.tileY); }
1071 path.stuckSince = now;
1072 path.stuckTileX = position.tileX;
1073 path.stuckTileY = position.tileY;
1074 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
1075 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
1076 if (!isWalk)
1077 { this.#consumeRunStamina(handle, events); }
1078 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
1079 }
1080 return { events, transferRequests };
1081 }
1082
1083 /**
1084 * If we still have a destination but have not left this tile for NAV_STUCK_MS,
1085 * recompute A* to the same goal (around whoever is blocking the old route).
1086 */
1087 #repathIfNavigationStuck (entityId, position, movement, path, now)
1088 {
1089 if (!path?.tiles?.length)
1090 {
1091 path.stuckSince = null;
1092 return;
1093 }
1094 if (
1095 path.stuckSince == null
1096 || path.stuckTileX !== position.tileX
1097 || path.stuckTileY !== position.tileY
1098 )
1099 {
1100 path.stuckSince = now;
1101 path.stuckTileX = position.tileX;
1102 path.stuckTileY = position.tileY;
1103 return;
1104 }
1105 if (now - path.stuckSince < NAV_STUCK_MS)
1106 { return; }
1107
1108 const goal = path.tiles[path.tiles.length - 1];
1109 if (!goal || (goal.x === position.tileX && goal.y === position.tileY))
1110 {
1111 path.tiles = [];
1112 path.stuckSince = null;
1113 return;
1114 }
1115 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1116 path.tiles = findPath(
1117 position.tileX,
1118 position.tileY,
1119 goal.x,
1120 goal.y,
1121 (x, y) => this.walkableFor(entityId, x, y),
1122 bounds.minX,
1123 bounds.minY,
1124 bounds.maxX,
1125 bounds.maxY
1126 );
1127 path.stuckSince = now;
1128 path.stuckTileX = position.tileX;
1129 path.stuckTileY = position.tileY;
1130 if (movement)
1131 { movement.walkCarry = 0; }
1132 }
1133
1134 #queueAmbientWander ()
1135 {
1136 for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
1137 {
1138 const def = mobDefinition(entity.creature.mobTypeId);
1139 if (!def?.ambient || def.freeFlight)
1140 { continue; }
1141 if (this.ecs.get(entity.handle, Component.spawnOrigin))
1142 { continue; }
1143 const path = this.ecs.get(entity.handle, Component.path);
1144 if (!path)
1145 { continue; }
1146 if (path.tiles?.length)
1147 { continue; }
1148 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
1149 { continue; }
1150 if (Math.random() > 0.35)
1151 { continue; }
1152 const dirs = [
1153 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
1154 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
1155 ];
1156 const dir = dirs[Math.floor(Math.random() * dirs.length)];
1157 const nextX = entity.position.tileX + dir.x;
1158 const nextY = entity.position.tileY + dir.y;
1159 if (!this.walkableFor(entity.entityId, nextX, nextY))
1160 { continue; }
1161 path.tiles = [{ x: nextX, y: nextY }];
1162 }
1163 }
1164
1165 /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner. Combat chase is unrestricted. */
1166 #queueSpawnerWander ()
1167 {
1168 for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin))
1169 {
1170 const combat = this.ecs.get(entity.handle, Component.combat);
1171 if (combat?.targetEntityId != null)
1172 { continue; }
1173 const follow = this.ecs.get(entity.handle, Component.follow);
1174 if (follow?.targetEntityId != null)
1175 { continue; }
1176 const shop = this.ecs.get(entity.handle, Component.shop);
1177 if (shopHasActiveBrowsers(shop))
1178 { continue; }
1179 const origin = entity.spawnOrigin;
1180 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1181 { continue; }
1182 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1183 if (def?.freeFlight)
1184 { continue; }
1185 const path = this.ecs.get(entity.handle, Component.path);
1186 if (!path || path.tiles?.length)
1187 { continue; }
1188 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
1189 { continue; }
1190 if (Math.random() > 0.4)
1191 { continue; }
1192
1193 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1194 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1195 const range = Math.max(0, origin.wanderRangeTiles | 0);
1196 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
1197 if (!goal)
1198 { continue; }
1199 if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY)
1200 { continue; }
1201 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1202 const tiles = findPath(
1203 entity.position.tileX,
1204 entity.position.tileY,
1205 goal.tileX,
1206 goal.tileY,
1207 (x, y) => this.walkableFor(entity.entityId, x, y),
1208 bounds.minX,
1209 bounds.minY,
1210 bounds.maxX,
1211 bounds.maxY
1212 );
1213 if (!tiles?.length)
1214 { continue; }
1215 path.tiles = tiles;
1216 }
1217 }
1218
1219 /**
1220 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1221 * message: { stationTileX, stationTileY }
1222 */
1223 #stationExchangeClerk (message)
1224 {
1225 const stationTileX = message.stationTileX | 0;
1226 const stationTileY = message.stationTileY | 0;
1227 if (!this.isEnterable(stationTileX, stationTileY))
1228 { return { ok: false, reason: "blocked" }; }
1229
1230 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1231 {
1232 if (!entity.spawnOrigin?.centralExchange)
1233 { continue; }
1234 if (
1235 Number.isInteger(entity.spawnOrigin.stationTileX)
1236 && entity.spawnOrigin.stationTileX === stationTileX
1237 && entity.spawnOrigin.stationTileY === stationTileY
1238 )
1239 { return { ok: true, entityId: entity.entityId, already: true }; }
1240 }
1241
1242 let best = null;
1243 let bestDist = Infinity;
1244 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1245 {
1246 if (!entity.spawnOrigin?.centralExchange)
1247 { continue; }
1248 if (Number.isInteger(entity.spawnOrigin.stationTileX))
1249 { continue; }
1250 const dist = Math.max(
1251 Math.abs(entity.position.tileX - stationTileX),
1252 Math.abs(entity.position.tileY - stationTileY)
1253 );
1254 if (dist < bestDist)
1255 {
1256 bestDist = dist;
1257 best = entity;
1258 }
1259 }
1260 if (!best)
1261 { return { ok: false, reason: "none-available" }; }
1262
1263 const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS);
1264 const tiles = findPath(
1265 best.position.tileX,
1266 best.position.tileY,
1267 stationTileX,
1268 stationTileY,
1269 (x, y) => this.walkableFor(best.entityId, x, y),
1270 bounds.minX,
1271 bounds.minY,
1272 bounds.maxX,
1273 bounds.maxY
1274 );
1275 best.spawnOrigin.stationTileX = stationTileX;
1276 best.spawnOrigin.stationTileY = stationTileY;
1277 if (tiles?.length)
1278 { best.path.tiles = tiles; }
1279 else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY)
1280 { best.path.tiles = []; }
1281 else
1282 { return { ok: false, reason: "no-path" }; }
1283 return { ok: true, entityId: best.entityId };
1284 }
1285
1286 /**
1287 * Clear a CE clerk's station assignment so wander can resume.
1288 * message: { stationTileX, stationTileY }
1289 */
1290 #releaseExchangeClerk (message)
1291 {
1292 const stationTileX = message.stationTileX | 0;
1293 const stationTileY = message.stationTileY | 0;
1294 let released = 0;
1295 for (const entity of this.ecs.query(Component.spawnOrigin, Component.path))
1296 {
1297 if (!entity.spawnOrigin?.centralExchange)
1298 { continue; }
1299 if (
1300 entity.spawnOrigin.stationTileX !== stationTileX
1301 || entity.spawnOrigin.stationTileY !== stationTileY
1302 )
1303 { continue; }
1304 entity.spawnOrigin.stationTileX = null;
1305 entity.spawnOrigin.stationTileY = null;
1306 entity.path.tiles = [];
1307 released += 1;
1308 }
1309 return { ok: true, released };
1310 }
1311
1312 /** Keep stationed CE clerks at their counter tile. */
1313 #queueExchangeStations ()
1314 {
1315 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1316 {
1317 if (!entity.spawnOrigin?.centralExchange)
1318 { continue; }
1319 const sx = entity.spawnOrigin.stationTileX;
1320 const sy = entity.spawnOrigin.stationTileY;
1321 if (!Number.isInteger(sx) || !Number.isInteger(sy))
1322 { continue; }
1323 if (entity.position.tileX === sx && entity.position.tileY === sy)
1324 {
1325 entity.path.tiles = [];
1326 continue;
1327 }
1328 if (entity.path.tiles?.length)
1329 { continue; }
1330 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1331 const tiles = findPath(
1332 entity.position.tileX,
1333 entity.position.tileY,
1334 sx,
1335 sy,
1336 (x, y) => this.walkableFor(entity.entityId, x, y),
1337 bounds.minX,
1338 bounds.minY,
1339 bounds.maxX,
1340 bounds.maxY
1341 );
1342 if (tiles?.length)
1343 { entity.path.tiles = tiles; }
1344 }
1345 }
1346
1347 #applyTransfer (message)
1348 {
1349 const payload = message.payload;
1350 const entityId = payload.entityId;
1351 if (this.ecs.hasEntity(entityId))
1352 { return { accepted: false, reason: "already-present" }; }
1353
1354 const position = payload.components?.position;
1355 const destTileX = message.destTileX ?? position?.tileX;
1356 const destTileY = message.destTileY ?? position?.tileY;
1357 if (destTileX == null || destTileY == null)
1358 { return { accepted: false, reason: "missing-destination" }; }
1359 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
1360 { return { accepted: false, reason: "not-owner" }; }
1361
1362 const creature = payload.components?.creature;
1363 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
1364 if (flying)
1365 {
1366 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY));
1367 if (!data?.open)
1368 { return { accepted: false, reason: "blocked" }; }
1369 }
1370 else if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
1371 { return { accepted: false, reason: "blocked" }; }
1372
1373 deserializeEntity(this.ecs, payload);
1374 const handle = this.ecs.handleOf(entityId);
1375 const livePosition = this.ecs.get(handle, Component.position);
1376 const path = this.ecs.get(handle, Component.path);
1377 livePosition.tileX = destTileX;
1378 livePosition.tileY = destTileY;
1379 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
1380 { path.tiles.shift(); }
1381 if (!flying)
1382 { this.#occupy(entityId, destTileX, destTileY); }
1383 const character = this.ecs.get(handle, Component.character);
1384 if (character?.characterId)
1385 { this.characterEntities.set(character.characterId, entityId); }
1386 this.frozen.delete(entityId);
1387 return {
1388 accepted: true,
1389 entity: publicEntityView(this.ecs, entityId)
1390 };
1391 }
1392
1393 #commitTransfer (entityId)
1394 {
1395 if (!this.ecs.hasEntity(entityId))
1396 { return null; }
1397 return this.#destroyEntity(entityId);
1398 }
1399
1400 #abortTransfer (entityId)
1401 {
1402 this.frozen.delete(entityId);
1403 return publicEntityView(this.ecs, entityId);
1404 }
1405
1406 #listLoaders ()
1407 {
1408 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
1409 entityId: entity.entityId,
1410 tileX: entity.position.tileX,
1411 tileY: entity.position.tileY,
1412 chunkLoader: { ...entity.chunkLoader }
1413 }));
1414 }
1415
1416 #listPublicEntities ()
1417 {
1418 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
1419 }
1420
1421 #entitiesInRegion (regionX, regionY)
1422 {
1423 const records = [];
1424 for (const entity of this.ecs.query(Component.position))
1425 {
1426 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
1427 { continue; }
1428 records.push({
1429 ...publicEntityView(this.ecs, entity.entityId),
1430 persistent: this.ecs.has(entity.handle, Component.persistent),
1431 payload: serializeEntity(this.ecs, entity.entityId)
1432 });
1433 }
1434 return records;
1435 }
1436
1437 #chunkSnapshot (chunkX, chunkY)
1438 {
1439 const data = this.#chunkData(chunkX, chunkY);
1440 const entities = [];
1441 for (const entity of this.ecs.query(Component.position, Component.appearance))
1442 {
1443 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
1444 { continue; }
1445 entities.push(publicEntityView(this.ecs, entity.entityId));
1446 }
1447 return {
1448 chunkX,
1449 chunkY,
1450 open: data.open,
1451 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
1452 grounds: data.grounds,
1453 blocks: data.blocks,
1454 light: data.light,
1455 entities,
1456 groundItems: groundItemsInChunk(this, chunkX, chunkY)
1457 };
1458 }
1459
1460 #moveEvent (entityId, fromTileX, fromTileY)
1461 {
1462 const view = publicEntityView(this.ecs, entityId);
1463 return {
1464 type: "entity-move",
1465 entityId,
1466 fromTileX,
1467 fromTileY,
1468 tileX: view.tileX,
1469 tileY: view.tileY,
1470 worldX: view.worldX,
1471 worldY: view.worldY,
1472 gait: view.gait,
1473 freeFlight: !!view.freeFlight
1474 };
1475 }
1476
1477 chunkIsSimulating (tileX, tileY)
1478 {
1479 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
1480 return !!chunk && !chunk.replica && chunk.simulating;
1481 }
1482
1483 chunkData (chunkX, chunkY)
1484 {
1485 return this.#chunkData(chunkX, chunkY);
1486 }
1487
1488 walkableFor (entityId, tileX, tileY)
1489 {
1490 const handle = this.ecs.handleOf(entityId);
1491 if (this.#isFlying(handle))
1492 {
1493 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1494 return !!data?.open;
1495 }
1496 if (!this.isEnterable(tileX, tileY))
1497 { return false; }
1498 const occupant = this.#occupied(tileX, tileY);
1499 return !occupant || occupant === entityId;
1500 }
1501
1502 destroyEntity (entityId)
1503 {
1504 return this.#destroyEntity(entityId);
1505 }
1506
1507 occupied (tileX, tileY)
1508 {
1509 return this.#occupied(tileX, tileY);
1510 }
1511
1512 #chunkIsSimulating (tileX, tileY)
1513 {
1514 return this.chunkIsSimulating(tileX, tileY);
1515 }
1516
1517 #chunkData (chunkX, chunkY)
1518 {
1519 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
1520 if (loaded)
1521 { return loaded.data; }
1522 return createEmptyChunkData(this.settings.defaultGroundTypeId);
1523 }
1524
1525 isEnterable (tileX, tileY)
1526 {
1527 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1528 if (!data.open)
1529 { return false; }
1530 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1531 }
1532
1533 #walkableFor (entityId, tileX, tileY)
1534 {
1535 return this.walkableFor(entityId, tileX, tileY);
1536 }
1537
1538 #isFlying (handle)
1539 {
1540 if (handle == null)
1541 { return false; }
1542 const creature = this.ecs.get(handle, Component.creature);
1543 return !!mobDefinition(creature?.mobTypeId)?.flying;
1544 }
1545
1546 #occupy (entityId, tileX, tileY)
1547 {
1548 this.occupancy.set(tileKey(tileX, tileY), entityId);
1549 }
1550
1551 #vacate (entityId, tileX, tileY)
1552 {
1553 const key = tileKey(tileX, tileY);
1554 if (this.occupancy.get(key) === entityId)
1555 { this.occupancy.delete(key); }
1556 }
1557
1558 #occupied (tileX, tileY)
1559 {
1560 return this.occupancy.get(tileKey(tileX, tileY))
1561 ?? this.ghostOccupancy.get(tileKey(tileX, tileY))
1562 ?? null;
1563 }
1564}
1565
1566function pickWanderGoalInRange (world, entityId, originX, originY, range)
1567{
1568 const radius = Math.max(0, range | 0);
1569 for (let attempt = 0; attempt < 24; attempt++)
1570 {
1571 const tileX = originX + randInt(-radius, radius);
1572 const tileY = originY + randInt(-radius, radius);
1573 if (!world.walkableFor(entityId, tileX, tileY))
1574 { continue; }
1575 return { tileX, tileY };
1576 }
1577 return null;
1578}
1579
1580function randInt (min, max)
1581{
1582 return min + Math.floor(Math.random() * (max - min + 1));
1583}
1584
1585export function replicaNeededForOwnedChunks (ownedChunkKeys)
1586{
1587 const needed = new Set();
1588 for (const key of ownedChunkKeys)
1589 {
1590 const { chunkX, chunkY } = parseChunkKey(key);
1591 for (let dy = -1; dy <= 1; dy++)
1592 {
1593 for (let dx = -1; dx <= 1; dx++)
1594 {
1595 if (dx === 0 && dy === 0)
1596 { continue; }
1597 needed.add(chunkKey(chunkX + dx, chunkY + dy));
1598 }
1599 }
1600 }
1601 return needed;
1602}