BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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