BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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