BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

workerWorld.js 27.2 KiB Download Raw
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS } 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 expireGroundItems,
25 groundItemsInChunk,
26 groundItemsInRegion,
27 handleItemCommand,
28 removeGroundItem,
29 setGroundItemsForRegion
30} from "../items/bags.js";
31import {
32 clearEngage,
33 engageTarget,
34 ensureMobCombat,
35 isUntargetable,
36 stepCombat
37} from "../combat/service.js";
38import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
39import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
40
41export class WorkerWorld
42{
43 constructor (workerId)
44 {
45 this.workerId = workerId;
46 this.ecs = new EcsWorld();
47 this.chunks = new Map();
48 this.ownedRegions = new Set();
49 this.occupancy = new Map();
50 this.ghosts = new Map();
51 this.ghostOccupancy = new Map();
52 this.characterEntities = new Map();
53 this.frozen = new Set();
54 this.groundItems = new Map();
55 this.groundByTile = new Map();
56 this.settings = { ...DEFAULT_WORLD_SETTINGS };
57 this.activeRevisionId = 1;
58 }
59
60 handle (message)
61 {
62 switch (message.type)
63 {
64 case WorkerMessage.configure:
65 return this.#configure(message);
66 case WorkerMessage.assignRegion:
67 return this.#assignRegion(message);
68 case WorkerMessage.dropRegion:
69 return this.#dropRegion(message);
70 case WorkerMessage.replaceRegionChunks:
71 return this.#replaceRegionChunks(message);
72 case WorkerMessage.setReplicas:
73 return this.#setReplicas(message);
74 case WorkerMessage.setSimulatingChunks:
75 return this.#setSimulatingChunks(message);
76 case WorkerMessage.setGhosts:
77 return this.#setGhosts(message);
78 case WorkerMessage.spawn:
79 return this.#spawn(message);
80 case WorkerMessage.despawn:
81 return this.#despawn(message.entityId);
82 case WorkerMessage.despawnCharacter:
83 return this.#despawnCharacter(message.characterId);
84 case WorkerMessage.command:
85 return this.#command(message);
86 case WorkerMessage.stepMovement:
87 return this.#stepMovement(message.now);
88 case WorkerMessage.stepSystems:
89 return this.#stepSystems(message.now);
90 case WorkerMessage.stepSpawners:
91 return { spawnRequests: collectSpawnRequests(this) };
92 case WorkerMessage.setGroundItems:
93 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
94 return { ok: true };
95 case WorkerMessage.inspectBag:
96 return this.#inspectBag(message.entityId);
97 case WorkerMessage.inspectSkills:
98 return this.#inspectSkills(message.entityId);
99 case WorkerMessage.applyBag:
100 return this.#applyBag(message.entityId, message.bag);
101 case WorkerMessage.updateFlight:
102 return this.#updateFlight(message.entityId, message.flight, message.now);
103 case WorkerMessage.chunkIsSimulating:
104 return this.chunkIsSimulating(message.tileX, message.tileY);
105 case WorkerMessage.applyTransfer:
106 return this.#applyTransfer(message);
107 case WorkerMessage.commitTransfer:
108 return this.#commitTransfer(message.entityId);
109 case WorkerMessage.abortTransfer:
110 return this.#abortTransfer(message.entityId);
111 case WorkerMessage.snapshotChunk:
112 return this.#chunkSnapshot(message.chunkX, message.chunkY);
113 case WorkerMessage.listLoaders:
114 return this.#listLoaders();
115 case WorkerMessage.listPublicEntities:
116 return this.#listPublicEntities();
117 case WorkerMessage.entitiesInRegion:
118 return this.#entitiesInRegion(message.regionX, message.regionY);
119 case WorkerMessage.inspect:
120 return publicEntityView(this.ecs, message.entityId);
121 default:
122 throw new Error(`Unknown worker message ${message.type}`);
123 }
124 }
125
126 ownsRegion (regionX, regionY)
127 {
128 return this.ownedRegions.has(regionKey(regionX, regionY));
129 }
130
131 requireOwnedEntity (sessionId, characterId)
132 {
133 return this.#requireOwnedEntity(sessionId, characterId);
134 }
135
136 chunkData (chunkX, chunkY)
137 {
138 return this.#chunkData(chunkX, chunkY);
139 }
140
141 occupied (tileX, tileY)
142 {
143 return this.#occupied(tileX, tileY);
144 }
145
146 #configure (message)
147 {
148 if (message.settings)
149 { this.settings = { ...this.settings, ...message.settings }; }
150 if (message.activeRevisionId != null)
151 { this.activeRevisionId = message.activeRevisionId; }
152 return { ok: true };
153 }
154
155 #assignRegion (message)
156 {
157 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
158 for (const chunk of message.chunks ?? [])
159 {
160 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
161 data: cloneChunkData(chunk.data),
162 simulating: false,
163 replica: false
164 });
165 }
166 return { ok: true };
167 }
168
169 #replaceRegionChunks (message)
170 {
171 for (const chunk of message.chunks ?? [])
172 {
173 const key = chunkKey(chunk.chunkX, chunk.chunkY);
174 const existing = this.chunks.get(key);
175 this.chunks.set(key, {
176 data: cloneChunkData(chunk.data),
177 simulating: existing?.simulating ?? false,
178 replica: existing?.replica ?? false
179 });
180 }
181 return { ok: true };
182 }
183
184 #dropRegion (message)
185 {
186 const dropped = [];
187 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
188 {
189 const components = record.payload?.components;
190 if (components?.creature && !components?.character && components?.health)
191 { components.health.current = components.health.max; }
192 dropped.push(record);
193 this.#destroyEntity(record.entityId);
194 }
195 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
196 for (const item of groundItems)
197 { removeGroundItem(this, item.groundItemId); }
198 for (const [key, chunk] of [...this.chunks.entries()])
199 {
200 const { chunkX, chunkY } = parseChunkKey(key);
201 if (chunk.replica)
202 { continue; }
203 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
204 { this.chunks.delete(key); }
205 }
206 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
207 return { dropped, groundItems };
208 }
209
210 #setReplicas (message)
211 {
212 const keep = new Set();
213 for (const chunk of message.chunks ?? [])
214 {
215 const key = chunkKey(chunk.chunkX, chunk.chunkY);
216 keep.add(key);
217 const existing = this.chunks.get(key);
218 if (existing && !existing.replica)
219 { continue; }
220 this.chunks.set(key, {
221 data: cloneChunkData(chunk.data),
222 simulating: false,
223 replica: true
224 });
225 }
226 for (const [key, chunk] of [...this.chunks.entries()])
227 {
228 if (chunk.replica && !keep.has(key))
229 { this.chunks.delete(key); }
230 }
231 return { ok: true };
232 }
233
234 #setSimulatingChunks (message)
235 {
236 const simulating = new Set(message.chunkKeys ?? []);
237 for (const [key, chunk] of this.chunks)
238 {
239 if (chunk.replica)
240 {
241 chunk.simulating = false;
242 continue;
243 }
244 chunk.simulating = simulating.has(key);
245 }
246 return { ok: true };
247 }
248
249 #setGhosts (message)
250 {
251 this.ghosts.clear();
252 this.ghostOccupancy.clear();
253 for (const ghost of message.ghosts ?? [])
254 {
255 this.ghosts.set(ghost.entityId, ghost);
256 this.ghostOccupancy.set(tileKey(ghost.tileX, ghost.tileY), ghost.entityId);
257 }
258 return { ok: true };
259 }
260
261 #spawn (message)
262 {
263 const entityId = deserializeEntity(this.ecs, message);
264 const handle = this.ecs.handleOf(entityId);
265 const position = this.ecs.get(handle, Component.position);
266 if (!position)
267 {
268 this.ecs.destroy(handle);
269 throw new Error("Spawned entity is missing position.");
270 }
271 const flying = this.#isFlying(handle);
272 if (!flying)
273 {
274 const occupant = this.#occupied(position.tileX, position.tileY);
275 if (occupant && occupant !== entityId)
276 {
277 this.ecs.destroy(handle);
278 const error = new Error("That tile is occupied.");
279 error.userFacing = true;
280 throw error;
281 }
282 this.#occupy(entityId, position.tileX, position.tileY);
283 }
284 const creature = this.ecs.get(handle, Component.creature);
285 const def = creature ? mobDefinition(creature.mobTypeId) : null;
286 if (def?.freeFlight)
287 { ensureFlightComponent(this.ecs, handle, position, def); }
288 const character = this.ecs.get(handle, Component.character);
289 if (character?.characterId)
290 { this.characterEntities.set(character.characterId, entityId); }
291 return publicEntityView(this.ecs, entityId);
292 }
293
294 #despawn (entityId)
295 {
296 return this.#destroyEntity(entityId);
297 }
298
299 #despawnCharacter (characterId)
300 {
301 const entityId = this.characterEntities.get(characterId);
302 if (!entityId)
303 { return null; }
304 return this.#destroyEntity(entityId);
305 }
306
307 #destroyEntity (entityId)
308 {
309 const handle = this.ecs.handleOf(entityId);
310 if (handle == null)
311 { return null; }
312 const view = publicEntityView(this.ecs, entityId);
313 const position = this.ecs.get(handle, Component.position);
314 const character = this.ecs.get(handle, Component.character);
315 if (position && !this.#isFlying(handle))
316 { this.#vacate(entityId, position.tileX, position.tileY); }
317 if (character?.characterId)
318 { this.characterEntities.delete(character.characterId); }
319 this.frozen.delete(entityId);
320 this.ecs.destroy(handle);
321 return view;
322 }
323
324 #command (message)
325 {
326 const { sessionId, command } = message;
327 switch (command.type)
328 {
329 case "move-to":
330 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
331 return { events: [] };
332 case "set-gait":
333 this.#setGait(sessionId, command.characterId, command.gait);
334 return { events: [] };
335 case "attack":
336 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
337 case "cancel-attack":
338 return this.#cancelAttack(sessionId, command.characterId);
339 case "interact":
340 return this.#interact(sessionId, command.characterId, command.targetEntityId);
341 case "follow":
342 return this.#follow(sessionId, command.characterId, command.targetEntityId);
343 case "cancel-follow":
344 return this.#cancelFollow(sessionId, command.characterId);
345 default:
346 {
347 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
348 return result ?? { events: [] };
349 }
350 }
351 }
352
353 #inspectBag (entityId)
354 {
355 const handle = this.ecs.handleOf(entityId);
356 if (handle == null)
357 { return null; }
358 return bagView(this.ecs, handle);
359 }
360
361 #inspectSkills (entityId)
362 {
363 const handle = this.ecs.handleOf(entityId);
364 if (handle == null)
365 { return null; }
366 const skills = this.ecs.get(handle, Component.skills);
367 if (!skills?.xp)
368 { return null; }
369 return skills;
370 }
371
372 #applyBag (entityId, bag)
373 {
374 const handle = this.ecs.handleOf(entityId);
375 if (handle == null)
376 { return null; }
377 return applyBagView(this.ecs, handle, bag);
378 }
379
380 #updateFlight (entityId, flightPatch, now = Date.now())
381 {
382 const handle = this.ecs.handleOf(entityId);
383 if (handle == null)
384 { return null; }
385 let flight = this.ecs.get(handle, Component.flight);
386 if (!flight)
387 { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); }
388 else
389 { Object.assign(flight, flightPatch); }
390 const position = this.ecs.get(handle, Component.position);
391 const movement = this.ecs.get(handle, Component.movement);
392 const fromTileX = position.tileX;
393 const fromTileY = position.tileY;
394 const tileX = Math.floor(flight.x);
395 const tileY = Math.floor(flight.y);
396 position.tileX = tileX;
397 position.tileY = tileY;
398 const destRegionX = tileToRegion(tileX);
399 const destRegionY = tileToRegion(tileY);
400 if (!this.ownsRegion(destRegionX, destRegionY))
401 {
402 this.frozen.add(entityId);
403 return {
404 transferRequest: {
405 type: "transfer-request",
406 entityId,
407 fromTileX,
408 fromTileY,
409 destTileX: tileX,
410 destTileY: tileY,
411 toRegionX: destRegionX,
412 toRegionY: destRegionY
413 }
414 };
415 }
416 const dt = flight.lastAt && now > flight.lastAt
417 ? Math.min(0.25, (now - flight.lastAt) / 1000)
418 : 1 / 20;
419 return {
420 event: {
421 type: "entity-move",
422 entityId,
423 fromTileX,
424 fromTileY,
425 tileX,
426 tileY,
427 worldX: flight.x,
428 worldY: flight.y,
429 gait: movement?.gait ?? "walk",
430 lerpMs: Math.max(50, Math.round(dt * 1000)),
431 freeFlight: true
432 }
433 };
434 }
435
436 #moveTo (sessionId, characterId, tileX, tileY)
437 {
438 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
439 if (this.frozen.has(entityId))
440 { return; }
441 clearEngage(this.ecs, entityId);
442 clearFollow(this.ecs, entityId);
443 const position = this.ecs.get(handle, Component.position);
444 const movement = this.ecs.get(handle, Component.movement);
445 let path = this.ecs.get(handle, Component.path);
446 if (!path)
447 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
448 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
449 path.tiles = findPath(
450 position.tileX,
451 position.tileY,
452 tileX,
453 tileY,
454 (x, y) => this.walkableFor(entityId, x, y),
455 bounds.minX,
456 bounds.minY,
457 bounds.maxX,
458 bounds.maxY
459 );
460 movement.walkCarry = 0;
461 }
462
463 #attack (sessionId, characterId, targetEntityId, now)
464 {
465 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
466 const targetHandle = this.ecs.handleOf(targetEntityId);
467 if (targetHandle == null)
468 {
469 const error = new Error("Target is not here.");
470 error.userFacing = true;
471 throw error;
472 }
473 if (targetEntityId === entityId)
474 {
475 const error = new Error("Cannot attack yourself.");
476 error.userFacing = true;
477 throw error;
478 }
479 if (isUntargetable(this.ecs, targetHandle))
480 {
481 const error = new Error("That cannot be attacked.");
482 error.userFacing = true;
483 throw error;
484 }
485 const health = this.ecs.get(targetHandle, Component.health);
486 if (!health)
487 {
488 const error = new Error("That cannot be attacked.");
489 error.userFacing = true;
490 throw error;
491 }
492 if (!this.ecs.get(handle, Component.combat))
493 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
494 clearFollow(this.ecs, entityId);
495 engageTarget(this.ecs, entityId, targetEntityId, now);
496 if (ensureMobCombat(this.ecs, targetEntityId))
497 { engageTarget(this.ecs, targetEntityId, entityId, now); }
498 const path = this.ecs.get(handle, Component.path);
499 if (path)
500 { path.tiles = []; }
501 return { events: [] };
502 }
503
504 #cancelAttack (sessionId, characterId)
505 {
506 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
507 clearEngage(this.ecs, entityId);
508 return { events: [] };
509 }
510
511 #interact (sessionId, characterId, targetEntityId)
512 {
513 this.#requireOwnedEntity(sessionId, characterId);
514 const targetHandle = this.ecs.handleOf(targetEntityId);
515 if (targetHandle == null)
516 {
517 const error = new Error("Target is not here.");
518 error.userFacing = true;
519 throw error;
520 }
521 if (isUntargetable(this.ecs, targetHandle))
522 {
523 const error = new Error("Nothing to say.");
524 error.userFacing = true;
525 throw error;
526 }
527 const creature = this.ecs.get(targetHandle, Component.creature);
528 const def = creature ? mobDefinition(creature.mobTypeId) : null;
529 if (!def?.talkable)
530 {
531 const error = new Error("They have nothing to say.");
532 error.userFacing = true;
533 throw error;
534 }
535 return { events: [] };
536 }
537
538 #follow (sessionId, characterId, targetEntityId)
539 {
540 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
541 const targetHandle = this.ecs.handleOf(targetEntityId);
542 if (targetHandle == null)
543 {
544 const error = new Error("Target is not here.");
545 error.userFacing = true;
546 throw error;
547 }
548 if (targetEntityId === entityId)
549 {
550 const error = new Error("Cannot follow yourself.");
551 error.userFacing = true;
552 throw error;
553 }
554 if (!this.ecs.get(targetHandle, Component.position))
555 {
556 const error = new Error("That cannot be followed.");
557 error.userFacing = true;
558 throw error;
559 }
560 clearEngage(this.ecs, entityId);
561 setFollow(this.ecs, entityId, targetEntityId);
562 const path = this.ecs.get(handle, Component.path);
563 if (path)
564 { path.tiles = []; }
565 return { events: [] };
566 }
567
568 #cancelFollow (sessionId, characterId)
569 {
570 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
571 clearFollow(this.ecs, entityId);
572 return { events: [] };
573 }
574
575 #setGait (sessionId, characterId, gait)
576 {
577 if (gait !== GAIT.walk && gait !== GAIT.run)
578 {
579 const error = new Error("Gait must be walk or run.");
580 error.userFacing = true;
581 throw error;
582 }
583 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
584 this.ecs.get(handle, Component.movement).gait = gait;
585 }
586
587 #requireOwnedEntity (sessionId, characterId)
588 {
589 const entityId = this.characterEntities.get(characterId);
590 if (!entityId)
591 {
592 const error = new Error("Character is not in the world.");
593 error.userFacing = true;
594 throw error;
595 }
596 const handle = this.ecs.handleOf(entityId);
597 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
598 if (!identity || identity.sessionId !== sessionId)
599 {
600 const error = new Error("Character is not in the world.");
601 error.userFacing = true;
602 throw error;
603 }
604 return { handle, entityId };
605 }
606
607 #stepSystems (now = Date.now())
608 {
609 const events = [];
610 const transferRequests = [];
611 const flight = stepFreeFlight(this, now);
612 for (const event of flight)
613 {
614 if (event.type === "transfer-request")
615 {
616 const payload = serializeEntity(this.ecs, event.entityId);
617 transferRequests.push({
618 entityId: event.entityId,
619 fromTileX: event.fromTileX,
620 fromTileY: event.fromTileY,
621 destTileX: event.destTileX,
622 destTileY: event.destTileY,
623 toRegionX: event.toRegionX,
624 toRegionY: event.toRegionY,
625 payload
626 });
627 continue;
628 }
629 events.push(event);
630 }
631 events.push(...stepCombat(this, now));
632 stepFollow(this);
633 return { events, transferRequests };
634 }
635
636 #stepMovement (now = Date.now())
637 {
638 const events = expireGroundItems(this, now);
639 const transferRequests = [];
640 this.#queueAmbientWander();
641 for (const entity of this.ecs.query(Component.position, Component.movement))
642 {
643 const { handle, entityId, position, movement } = entity;
644 if (this.ecs.has(handle, Component.flight))
645 { continue; }
646 const path = this.ecs.get(handle, Component.path);
647 const tiles = path?.tiles;
648 if (this.frozen.has(entityId) || !tiles?.length)
649 { continue; }
650 if (!this.chunkIsSimulating(position.tileX, position.tileY))
651 { continue; }
652
653 const isWalk = movement.gait !== GAIT.run;
654 if (isWalk)
655 {
656 movement.walkCarry = (movement.walkCarry + 1) % 2;
657 if (movement.walkCarry !== 0)
658 { continue; }
659 }
660
661 const next = tiles[0];
662 const destRegionX = tileToRegion(next.x);
663 const destRegionY = tileToRegion(next.y);
664 if (!this.ownsRegion(destRegionX, destRegionY))
665 {
666 this.frozen.add(entityId);
667 transferRequests.push({
668 entityId,
669 fromTileX: position.tileX,
670 fromTileY: position.tileY,
671 destTileX: next.x,
672 destTileY: next.y,
673 toRegionX: destRegionX,
674 toRegionY: destRegionY,
675 payload: serializeEntity(this.ecs, entityId)
676 });
677 continue;
678 }
679
680 if (!this.walkableFor(entityId, next.x, next.y))
681 {
682 const combat = this.ecs.get(handle, Component.combat);
683 if (combat?.targetEntityId != null)
684 {
685 const targetHandle = this.ecs.handleOf(combat.targetEntityId);
686 const targetPos = targetHandle != null
687 ? this.ecs.get(targetHandle, Component.position)
688 : null;
689 const blockedByTarget = targetPos
690 && next.x === targetPos.tileX
691 && next.y === targetPos.tileY;
692 if (!blockedByTarget)
693 { path.tiles = []; }
694 }
695 continue;
696 }
697
698 const fromTileX = position.tileX;
699 const fromTileY = position.tileY;
700 const flying = this.#isFlying(handle);
701 if (!flying)
702 { this.#vacate(entityId, fromTileX, fromTileY); }
703 position.tileX = next.x;
704 position.tileY = next.y;
705 tiles.shift();
706 if (!flying)
707 { this.#occupy(entityId, position.tileX, position.tileY); }
708 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
709 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
710 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
711 }
712 return { events, transferRequests };
713 }
714
715 #queueAmbientWander ()
716 {
717 for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
718 {
719 const def = mobDefinition(entity.creature.mobTypeId);
720 if (!def?.ambient || def.freeFlight)
721 { continue; }
722 const path = this.ecs.get(entity.handle, Component.path);
723 if (!path)
724 { continue; }
725 if (path.tiles?.length)
726 { continue; }
727 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
728 { continue; }
729 if (Math.random() > 0.35)
730 { continue; }
731 const dirs = [
732 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
733 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
734 ];
735 const dir = dirs[Math.floor(Math.random() * dirs.length)];
736 const nextX = entity.position.tileX + dir.x;
737 const nextY = entity.position.tileY + dir.y;
738 if (!this.walkableFor(entity.entityId, nextX, nextY))
739 { continue; }
740 path.tiles = [{ x: nextX, y: nextY }];
741 }
742 }
743
744 #applyTransfer (message)
745 {
746 const payload = message.payload;
747 const entityId = payload.entityId;
748 if (this.ecs.hasEntity(entityId))
749 { return { accepted: false, reason: "already-present" }; }
750
751 const position = payload.components?.position;
752 const destTileX = message.destTileX ?? position?.tileX;
753 const destTileY = message.destTileY ?? position?.tileY;
754 if (destTileX == null || destTileY == null)
755 { return { accepted: false, reason: "missing-destination" }; }
756 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
757 { return { accepted: false, reason: "not-owner" }; }
758
759 const creature = payload.components?.creature;
760 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
761 if (flying)
762 {
763 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY));
764 if (!data?.open)
765 { return { accepted: false, reason: "blocked" }; }
766 }
767 else if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
768 { return { accepted: false, reason: "blocked" }; }
769
770 deserializeEntity(this.ecs, payload);
771 const handle = this.ecs.handleOf(entityId);
772 const livePosition = this.ecs.get(handle, Component.position);
773 const path = this.ecs.get(handle, Component.path);
774 livePosition.tileX = destTileX;
775 livePosition.tileY = destTileY;
776 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
777 { path.tiles.shift(); }
778 if (!flying)
779 { this.#occupy(entityId, destTileX, destTileY); }
780 const character = this.ecs.get(handle, Component.character);
781 if (character?.characterId)
782 { this.characterEntities.set(character.characterId, entityId); }
783 this.frozen.delete(entityId);
784 return {
785 accepted: true,
786 entity: publicEntityView(this.ecs, entityId)
787 };
788 }
789
790 #commitTransfer (entityId)
791 {
792 if (!this.ecs.hasEntity(entityId))
793 { return null; }
794 return this.#destroyEntity(entityId);
795 }
796
797 #abortTransfer (entityId)
798 {
799 this.frozen.delete(entityId);
800 return publicEntityView(this.ecs, entityId);
801 }
802
803 #listLoaders ()
804 {
805 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
806 entityId: entity.entityId,
807 tileX: entity.position.tileX,
808 tileY: entity.position.tileY,
809 chunkLoader: { ...entity.chunkLoader }
810 }));
811 }
812
813 #listPublicEntities ()
814 {
815 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
816 }
817
818 #entitiesInRegion (regionX, regionY)
819 {
820 const records = [];
821 for (const entity of this.ecs.query(Component.position))
822 {
823 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
824 { continue; }
825 records.push({
826 ...publicEntityView(this.ecs, entity.entityId),
827 persistent: this.ecs.has(entity.handle, Component.persistent),
828 payload: serializeEntity(this.ecs, entity.entityId)
829 });
830 }
831 return records;
832 }
833
834 #chunkSnapshot (chunkX, chunkY)
835 {
836 const data = this.#chunkData(chunkX, chunkY);
837 const entities = [];
838 for (const entity of this.ecs.query(Component.position, Component.appearance))
839 {
840 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
841 { continue; }
842 entities.push(publicEntityView(this.ecs, entity.entityId));
843 }
844 return {
845 chunkX,
846 chunkY,
847 open: data.open,
848 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
849 grounds: data.grounds,
850 blocks: data.blocks,
851 light: data.light,
852 entities,
853 groundItems: groundItemsInChunk(this, chunkX, chunkY)
854 };
855 }
856
857 #moveEvent (entityId, fromTileX, fromTileY)
858 {
859 const view = publicEntityView(this.ecs, entityId);
860 return {
861 type: "entity-move",
862 entityId,
863 fromTileX,
864 fromTileY,
865 tileX: view.tileX,
866 tileY: view.tileY,
867 worldX: view.worldX,
868 worldY: view.worldY,
869 gait: view.gait,
870 freeFlight: !!view.freeFlight
871 };
872 }
873
874 chunkIsSimulating (tileX, tileY)
875 {
876 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
877 return !!chunk && !chunk.replica && chunk.simulating;
878 }
879
880 chunkData (chunkX, chunkY)
881 {
882 return this.#chunkData(chunkX, chunkY);
883 }
884
885 walkableFor (entityId, tileX, tileY)
886 {
887 const handle = this.ecs.handleOf(entityId);
888 if (this.#isFlying(handle))
889 {
890 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
891 return !!data?.open;
892 }
893 if (!this.isEnterable(tileX, tileY))
894 { return false; }
895 const occupant = this.#occupied(tileX, tileY);
896 return !occupant || occupant === entityId;
897 }
898
899 destroyEntity (entityId)
900 {
901 return this.#destroyEntity(entityId);
902 }
903
904 occupied (tileX, tileY)
905 {
906 return this.#occupied(tileX, tileY);
907 }
908
909 #chunkIsSimulating (tileX, tileY)
910 {
911 return this.chunkIsSimulating(tileX, tileY);
912 }
913
914 #chunkData (chunkX, chunkY)
915 {
916 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
917 if (loaded)
918 { return loaded.data; }
919 return createEmptyChunkData(this.settings.defaultGroundTypeId);
920 }
921
922 isEnterable (tileX, tileY)
923 {
924 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
925 if (!data.open)
926 { return false; }
927 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
928 }
929
930 #walkableFor (entityId, tileX, tileY)
931 {
932 return this.walkableFor(entityId, tileX, tileY);
933 }
934
935 #isFlying (handle)
936 {
937 if (handle == null)
938 { return false; }
939 const creature = this.ecs.get(handle, Component.creature);
940 return !!mobDefinition(creature?.mobTypeId)?.flying;
941 }
942
943 #occupy (entityId, tileX, tileY)
944 {
945 this.occupancy.set(tileKey(tileX, tileY), entityId);
946 }
947
948 #vacate (entityId, tileX, tileY)
949 {
950 const key = tileKey(tileX, tileY);
951 if (this.occupancy.get(key) === entityId)
952 { this.occupancy.delete(key); }
953 }
954
955 #occupied (tileX, tileY)
956 {
957 return this.occupancy.get(tileKey(tileX, tileY))
958 ?? this.ghostOccupancy.get(tileKey(tileX, tileY))
959 ?? null;
960 }
961}
962
963export function replicaNeededForOwnedChunks (ownedChunkKeys)
964{
965 const needed = new Set();
966 for (const key of ownedChunkKeys)
967 {
968 const { chunkX, chunkY } = parseChunkKey(key);
969 for (let dy = -1; dy <= 1; dy++)
970 {
971 for (let dx = -1; dx <= 1; dx++)
972 {
973 if (dx === 0 && dy === 0)
974 { continue; }
975 needed.add(chunkKey(chunkX + dx, chunkY + dy));
976 }
977 }
978 }
979 return needed;
980}