BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

workerWorld.js 34.8 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 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 applyRemoteMeleeSwing,
36 clearEngage,
37 engageTarget,
38 ensureMobCombat,
39 isUntargetable,
40 resolveCombatTarget,
41 stepCombat
42} from "../combat/service.js";
43import { awardCombatHitXp } from "../skills/service.js";
44import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
45import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
46
47export class WorkerWorld
48{
49 constructor (workerId)
50 {
51 this.workerId = workerId;
52 this.ecs = new EcsWorld();
53 this.chunks = new Map();
54 this.ownedRegions = new Set();
55 this.occupancy = new Map();
56 this.ghosts = new Map();
57 this.ghostOccupancy = new Map();
58 this.characterEntities = new Map();
59 this.frozen = new Set();
60 this.groundItems = new Map();
61 this.groundByTile = new Map();
62 this.settings = { ...DEFAULT_WORLD_SETTINGS };
63 this.activeRevisionId = 1;
64 }
65
66 handle (message)
67 {
68 switch (message.type)
69 {
70 case WorkerMessage.configure:
71 return this.#configure(message);
72 case WorkerMessage.assignRegion:
73 return this.#assignRegion(message);
74 case WorkerMessage.dropRegion:
75 return this.#dropRegion(message);
76 case WorkerMessage.replaceRegionChunks:
77 return this.#replaceRegionChunks(message);
78 case WorkerMessage.setReplicas:
79 return this.#setReplicas(message);
80 case WorkerMessage.setSimulatingChunks:
81 return this.#setSimulatingChunks(message);
82 case WorkerMessage.setGhosts:
83 return this.#setGhosts(message);
84 case WorkerMessage.spawn:
85 return this.#spawn(message);
86 case WorkerMessage.despawn:
87 return this.#despawn(message.entityId);
88 case WorkerMessage.despawnCharacter:
89 return this.#despawnCharacter(message.characterId);
90 case WorkerMessage.command:
91 return this.#command(message);
92 case WorkerMessage.stepMovement:
93 return this.#stepMovement(message.now);
94 case WorkerMessage.stepSystems:
95 return this.#stepSystems(message.now);
96 case WorkerMessage.stepSpawners:
97 return { spawnRequests: collectSpawnRequests(this) };
98 case WorkerMessage.setGroundItems:
99 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
100 return { ok: true };
101 case WorkerMessage.inspectBag:
102 return this.#inspectBag(message.entityId);
103 case WorkerMessage.inspectSkills:
104 return this.#inspectSkills(message.entityId);
105 case WorkerMessage.applyBag:
106 return this.#applyBag(message.entityId, message.bag);
107 case WorkerMessage.updateFlight:
108 return this.#updateFlight(message.entityId, message.flight, message.now);
109 case WorkerMessage.chunkIsSimulating:
110 return this.chunkIsSimulating(message.tileX, message.tileY);
111 case WorkerMessage.applyTransfer:
112 return this.#applyTransfer(message);
113 case WorkerMessage.commitTransfer:
114 return this.#commitTransfer(message.entityId);
115 case WorkerMessage.abortTransfer:
116 return this.#abortTransfer(message.entityId);
117 case WorkerMessage.snapshotChunk:
118 return this.#chunkSnapshot(message.chunkX, message.chunkY);
119 case WorkerMessage.listLoaders:
120 return this.#listLoaders();
121 case WorkerMessage.listPublicEntities:
122 return this.#listPublicEntities();
123 case WorkerMessage.entitiesInRegion:
124 return this.#entitiesInRegion(message.regionX, message.regionY);
125 case WorkerMessage.inspect:
126 return publicEntityView(this.ecs, message.entityId);
127 case WorkerMessage.remoteCombatEngage:
128 return this.#remoteCombatEngage(message);
129 case WorkerMessage.applyRemoteMelee:
130 return this.#applyRemoteMelee(message);
131 case WorkerMessage.applyCombatHitXp:
132 return this.#applyCombatHitXp(message);
133 case WorkerMessage.spawnCorpseDrops:
134 return this.#spawnCorpseDrops(message);
135 case WorkerMessage.applyRespawn:
136 return this.#applyRespawn(message);
137 case WorkerMessage.clearCombat:
138 clearEngage(this.ecs, message.entityId);
139 for (const entity of this.ecs.query(Component.combat))
140 {
141 if (entity.combat.targetEntityId === message.targetEntityId)
142 { entity.combat.targetEntityId = null; }
143 }
144 return { ok: true };
145 default:
146 throw new Error(`Unknown worker message ${message.type}`);
147 }
148 }
149
150 ownsRegion (regionX, regionY)
151 {
152 return this.ownedRegions.has(regionKey(regionX, regionY));
153 }
154
155 requireOwnedEntity (sessionId, characterId)
156 {
157 return this.#requireOwnedEntity(sessionId, characterId);
158 }
159
160 chunkData (chunkX, chunkY)
161 {
162 return this.#chunkData(chunkX, chunkY);
163 }
164
165 occupied (tileX, tileY)
166 {
167 return this.#occupied(tileX, tileY);
168 }
169
170 #configure (message)
171 {
172 if (message.settings)
173 { this.settings = { ...this.settings, ...message.settings }; }
174 if (message.activeRevisionId != null)
175 { this.activeRevisionId = message.activeRevisionId; }
176 return { ok: true };
177 }
178
179 #assignRegion (message)
180 {
181 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
182 for (const chunk of message.chunks ?? [])
183 {
184 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
185 data: cloneChunkData(chunk.data),
186 simulating: false,
187 replica: false
188 });
189 }
190 return { ok: true };
191 }
192
193 #replaceRegionChunks (message)
194 {
195 for (const chunk of message.chunks ?? [])
196 {
197 const key = chunkKey(chunk.chunkX, chunk.chunkY);
198 const existing = this.chunks.get(key);
199 this.chunks.set(key, {
200 data: cloneChunkData(chunk.data),
201 simulating: existing?.simulating ?? false,
202 replica: existing?.replica ?? false
203 });
204 }
205 return { ok: true };
206 }
207
208 #dropRegion (message)
209 {
210 const dropped = [];
211 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
212 {
213 const components = record.payload?.components;
214 if (components?.creature && !components?.character && components?.health)
215 { components.health.current = components.health.max; }
216 dropped.push(record);
217 this.#destroyEntity(record.entityId);
218 }
219 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
220 for (const item of groundItems)
221 { removeGroundItem(this, item.groundItemId); }
222 for (const [key, chunk] of [...this.chunks.entries()])
223 {
224 const { chunkX, chunkY } = parseChunkKey(key);
225 if (chunk.replica)
226 { continue; }
227 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
228 { this.chunks.delete(key); }
229 }
230 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
231 return { dropped, groundItems };
232 }
233
234 #setReplicas (message)
235 {
236 const keep = new Set();
237 for (const chunk of message.chunks ?? [])
238 {
239 const key = chunkKey(chunk.chunkX, chunk.chunkY);
240 keep.add(key);
241 const existing = this.chunks.get(key);
242 if (existing && !existing.replica)
243 { continue; }
244 this.chunks.set(key, {
245 data: cloneChunkData(chunk.data),
246 simulating: false,
247 replica: true
248 });
249 }
250 for (const [key, chunk] of [...this.chunks.entries()])
251 {
252 if (chunk.replica && !keep.has(key))
253 { this.chunks.delete(key); }
254 }
255 return { ok: true };
256 }
257
258 #setSimulatingChunks (message)
259 {
260 const simulating = new Set(message.chunkKeys ?? []);
261 for (const [key, chunk] of this.chunks)
262 {
263 if (chunk.replica)
264 {
265 chunk.simulating = false;
266 continue;
267 }
268 chunk.simulating = simulating.has(key);
269 }
270 return { ok: true };
271 }
272
273 #setGhosts (message)
274 {
275 this.ghosts.clear();
276 this.ghostOccupancy.clear();
277 for (const ghost of message.ghosts ?? [])
278 {
279 this.ghosts.set(ghost.entityId, ghost);
280 this.ghostOccupancy.set(tileKey(ghost.tileX, ghost.tileY), ghost.entityId);
281 }
282 return { ok: true };
283 }
284
285 #spawn (message)
286 {
287 const entityId = deserializeEntity(this.ecs, message);
288 const handle = this.ecs.handleOf(entityId);
289 const position = this.ecs.get(handle, Component.position);
290 if (!position)
291 {
292 this.ecs.destroy(handle);
293 throw new Error("Spawned entity is missing position.");
294 }
295 const flying = this.#isFlying(handle);
296 if (!flying)
297 {
298 const occupant = this.#occupied(position.tileX, position.tileY);
299 if (occupant && occupant !== entityId)
300 {
301 this.ecs.destroy(handle);
302 const error = new Error("That tile is occupied.");
303 error.userFacing = true;
304 throw error;
305 }
306 this.#occupy(entityId, position.tileX, position.tileY);
307 }
308 const creature = this.ecs.get(handle, Component.creature);
309 const def = creature ? mobDefinition(creature.mobTypeId) : null;
310 if (def?.freeFlight)
311 { ensureFlightComponent(this.ecs, handle, position, def); }
312 const character = this.ecs.get(handle, Component.character);
313 if (character?.characterId)
314 { this.characterEntities.set(character.characterId, entityId); }
315 return publicEntityView(this.ecs, entityId);
316 }
317
318 #despawn (entityId)
319 {
320 return this.#destroyEntity(entityId);
321 }
322
323 #despawnCharacter (characterId)
324 {
325 const entityId = this.characterEntities.get(characterId);
326 if (!entityId)
327 { return null; }
328 return this.#destroyEntity(entityId);
329 }
330
331 #destroyEntity (entityId)
332 {
333 const handle = this.ecs.handleOf(entityId);
334 if (handle == null)
335 { return null; }
336 const view = publicEntityView(this.ecs, entityId);
337 const position = this.ecs.get(handle, Component.position);
338 const character = this.ecs.get(handle, Component.character);
339 if (position && !this.#isFlying(handle))
340 { this.#vacate(entityId, position.tileX, position.tileY); }
341 if (character?.characterId)
342 { this.characterEntities.delete(character.characterId); }
343 this.frozen.delete(entityId);
344 this.ecs.destroy(handle);
345 return view;
346 }
347
348 #command (message)
349 {
350 const { sessionId, command } = message;
351 switch (command.type)
352 {
353 case "move-to":
354 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
355 return { events: [] };
356 case "set-gait":
357 this.#setGait(sessionId, command.characterId, command.gait);
358 return { events: [] };
359 case "attack":
360 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
361 case "cancel-attack":
362 return this.#cancelAttack(sessionId, command.characterId);
363 case "interact":
364 return this.#interact(sessionId, command.characterId, command.targetEntityId);
365 case "follow":
366 return this.#follow(sessionId, command.characterId, command.targetEntityId);
367 case "cancel-follow":
368 return this.#cancelFollow(sessionId, command.characterId);
369 default:
370 {
371 const alchemy = handleAlchemyCommand(this, sessionId, command);
372 if (alchemy)
373 { return alchemy; }
374 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
375 return result ?? { events: [] };
376 }
377 }
378 }
379
380 #spawnCorpseDrops (message)
381 {
382 const events = [];
383 for (const drop of message.drops ?? [])
384 {
385 const item = {
386 groundItemId: drop.groundItemId,
387 tileX: message.tileX,
388 tileY: message.tileY,
389 stack: { itemId: drop.itemId, quantity: 1 },
390 droppedAt: message.now,
391 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
392 source: "player-death",
393 droppedByCharacterId: message.characterId
394 };
395 addGroundItem(this, item);
396 events.push({
397 type: "ground-item-appear",
398 ...publicGroundItem(item),
399 stack: item.stack,
400 droppedAt: item.droppedAt,
401 source: item.source,
402 droppedByCharacterId: item.droppedByCharacterId,
403 expiresAt: item.expiresAt
404 });
405 }
406 return { events };
407 }
408
409 #applyRespawn (message)
410 {
411 const handle = this.ecs.handleOf(message.entityId);
412 if (handle == null || !this.ecs.has(handle, Component.dead))
413 { return { accepted: false }; }
414 const position = this.ecs.get(handle, Component.position);
415 const fromTileX = position.tileX;
416 const fromTileY = position.tileY;
417 const health = this.ecs.get(handle, Component.health);
418 const stamina = this.ecs.get(handle, Component.stamina);
419 if (health)
420 {
421 health.max = message.maxHealth;
422 health.current = message.maxHealth;
423 }
424 if (stamina)
425 {
426 stamina.max = message.maxStamina;
427 stamina.current = message.maxStamina;
428 }
429 else
430 { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); }
431 this.ecs.remove(handle, Component.dead);
432 clearEngage(this.ecs, message.entityId);
433 const path = this.ecs.get(handle, Component.path);
434 if (path)
435 { path.tiles = []; }
436 clearFollow(this.ecs, message.entityId);
437
438 const destRegionX = tileToRegion(message.tileX);
439 const destRegionY = tileToRegion(message.tileY);
440 if (!this.ownsRegion(destRegionX, destRegionY))
441 {
442 this.frozen.add(message.entityId);
443 return {
444 accepted: true,
445 transferRequest: {
446 entityId: message.entityId,
447 fromTileX,
448 fromTileY,
449 destTileX: message.tileX,
450 destTileY: message.tileY,
451 toRegionX: destRegionX,
452 toRegionY: destRegionY,
453 payload: serializeEntity(this.ecs, message.entityId)
454 }
455 };
456 }
457 const occupant = this.#occupied(message.tileX, message.tileY);
458 if (!this.isEnterable(message.tileX, message.tileY)
459 || (occupant && occupant !== message.entityId))
460 { return { accepted: false }; }
461 this.#vacate(message.entityId, fromTileX, fromTileY);
462 position.tileX = message.tileX;
463 position.tileY = message.tileY;
464 this.#occupy(message.entityId, position.tileX, position.tileY);
465 return {
466 accepted: true,
467 event: {
468 type: "entity-move",
469 entityId: message.entityId,
470 fromTileX,
471 fromTileY,
472 tileX: position.tileX,
473 tileY: position.tileY,
474 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
475 }
476 };
477 }
478
479 #inspectBag (entityId)
480 {
481 const handle = this.ecs.handleOf(entityId);
482 if (handle == null)
483 { return null; }
484 return bagView(this.ecs, handle);
485 }
486
487 #inspectSkills (entityId)
488 {
489 const handle = this.ecs.handleOf(entityId);
490 if (handle == null)
491 { return null; }
492 const skills = this.ecs.get(handle, Component.skills);
493 if (!skills?.xp)
494 { return null; }
495 return skills;
496 }
497
498 #applyBag (entityId, bag)
499 {
500 const handle = this.ecs.handleOf(entityId);
501 if (handle == null)
502 { return null; }
503 return applyBagView(this.ecs, handle, bag);
504 }
505
506 #updateFlight (entityId, flightPatch, now = Date.now())
507 {
508 const handle = this.ecs.handleOf(entityId);
509 if (handle == null)
510 { return null; }
511 let flight = this.ecs.get(handle, Component.flight);
512 if (!flight)
513 { flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); }
514 else
515 { Object.assign(flight, flightPatch); }
516 const position = this.ecs.get(handle, Component.position);
517 const movement = this.ecs.get(handle, Component.movement);
518 const fromTileX = position.tileX;
519 const fromTileY = position.tileY;
520 const tileX = Math.floor(flight.x);
521 const tileY = Math.floor(flight.y);
522 position.tileX = tileX;
523 position.tileY = tileY;
524 const destRegionX = tileToRegion(tileX);
525 const destRegionY = tileToRegion(tileY);
526 if (!this.ownsRegion(destRegionX, destRegionY))
527 {
528 this.frozen.add(entityId);
529 return {
530 transferRequest: {
531 type: "transfer-request",
532 entityId,
533 fromTileX,
534 fromTileY,
535 destTileX: tileX,
536 destTileY: tileY,
537 toRegionX: destRegionX,
538 toRegionY: destRegionY
539 }
540 };
541 }
542 const dt = flight.lastAt && now > flight.lastAt
543 ? Math.min(0.25, (now - flight.lastAt) / 1000)
544 : 1 / 20;
545 return {
546 event: {
547 type: "entity-move",
548 entityId,
549 fromTileX,
550 fromTileY,
551 tileX,
552 tileY,
553 worldX: flight.x,
554 worldY: flight.y,
555 gait: movement?.gait ?? "walk",
556 lerpMs: Math.max(50, Math.round(dt * 1000)),
557 freeFlight: true
558 }
559 };
560 }
561
562 #moveTo (sessionId, characterId, tileX, tileY)
563 {
564 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
565 if (this.frozen.has(entityId))
566 { return; }
567 clearEngage(this.ecs, entityId);
568 clearFollow(this.ecs, entityId);
569 const position = this.ecs.get(handle, Component.position);
570 const movement = this.ecs.get(handle, Component.movement);
571 let path = this.ecs.get(handle, Component.path);
572 if (!path)
573 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
574 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
575 path.tiles = findPath(
576 position.tileX,
577 position.tileY,
578 tileX,
579 tileY,
580 (x, y) => this.walkableFor(entityId, x, y),
581 bounds.minX,
582 bounds.minY,
583 bounds.maxX,
584 bounds.maxY
585 );
586 movement.walkCarry = 0;
587 }
588
589 #attack (sessionId, characterId, targetEntityId, now)
590 {
591 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
592 if (targetEntityId === entityId)
593 {
594 const error = new Error("Cannot attack yourself.");
595 error.userFacing = true;
596 throw error;
597 }
598 const target = resolveCombatTarget(this, targetEntityId);
599 if (!target)
600 {
601 const error = new Error("Target is not here.");
602 error.userFacing = true;
603 throw error;
604 }
605 if (target.health && target.health.current <= 0)
606 {
607 const error = new Error("That cannot be attacked.");
608 error.userFacing = true;
609 throw error;
610 }
611 if (!this.ecs.get(handle, Component.combat))
612 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
613 clearFollow(this.ecs, entityId);
614 engageTarget(this.ecs, entityId, targetEntityId, now);
615 if (target.local)
616 {
617 if (ensureMobCombat(this.ecs, targetEntityId))
618 { engageTarget(this.ecs, targetEntityId, entityId, now); }
619 const targetPath = this.ecs.get(target.handle, Component.path);
620 if (targetPath)
621 { targetPath.tiles = []; }
622 }
623 const path = this.ecs.get(handle, Component.path);
624 if (path)
625 { path.tiles = []; }
626 return { events: [] };
627 }
628
629 #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })
630 {
631 const targetHandle = this.ecs.handleOf(targetEntityId);
632 if (targetHandle == null)
633 { return { events: [] }; }
634 if (ensureMobCombat(this.ecs, targetEntityId))
635 {
636 engageTarget(this.ecs, targetEntityId, attackerEntityId, now);
637 const targetPath = this.ecs.get(targetHandle, Component.path);
638 if (targetPath)
639 { targetPath.tiles = []; }
640 }
641 else if (this.ecs.get(targetHandle, Component.character))
642 {
643 engageTarget(this.ecs, targetEntityId, attackerEntityId, now);
644 const targetPath = this.ecs.get(targetHandle, Component.path);
645 if (targetPath)
646 { targetPath.tiles = []; }
647 }
648 return { events: [] };
649 }
650
651 #applyRemoteMelee (payload)
652 {
653 return applyRemoteMeleeSwing(this, payload);
654 }
655
656 #applyCombatHitXp ({ entityId, profile })
657 {
658 const handle = this.ecs.handleOf(entityId);
659 if (handle == null)
660 { return { events: [] }; }
661 const character = this.ecs.get(handle, Component.character);
662 if (!character)
663 { return { events: [] }; }
664 const xpAward = awardCombatHitXp(this.ecs, handle, profile);
665 if (!xpAward)
666 { return { events: [] }; }
667 return {
668 events: [{
669 type: "skills-updated",
670 entityId,
671 characterId: character.characterId,
672 skills: xpAward.view,
673 stored: xpAward.stored
674 }]
675 };
676 }
677
678 #cancelAttack (sessionId, characterId)
679 {
680 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
681 clearEngage(this.ecs, entityId);
682 return { events: [] };
683 }
684
685 #interact (sessionId, characterId, targetEntityId)
686 {
687 this.#requireOwnedEntity(sessionId, characterId);
688 const targetHandle = this.ecs.handleOf(targetEntityId);
689 if (targetHandle == null)
690 {
691 const error = new Error("Target is not here.");
692 error.userFacing = true;
693 throw error;
694 }
695 if (isUntargetable(this.ecs, targetHandle))
696 {
697 const error = new Error("Nothing to say.");
698 error.userFacing = true;
699 throw error;
700 }
701 const creature = this.ecs.get(targetHandle, Component.creature);
702 const def = creature ? mobDefinition(creature.mobTypeId) : null;
703 if (!def?.talkable)
704 {
705 const error = new Error("They have nothing to say.");
706 error.userFacing = true;
707 throw error;
708 }
709 return { events: [] };
710 }
711
712 #follow (sessionId, characterId, targetEntityId)
713 {
714 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
715 const targetHandle = this.ecs.handleOf(targetEntityId);
716 if (targetHandle == null)
717 {
718 const error = new Error("Target is not here.");
719 error.userFacing = true;
720 throw error;
721 }
722 if (targetEntityId === entityId)
723 {
724 const error = new Error("Cannot follow yourself.");
725 error.userFacing = true;
726 throw error;
727 }
728 if (!this.ecs.get(targetHandle, Component.position))
729 {
730 const error = new Error("That cannot be followed.");
731 error.userFacing = true;
732 throw error;
733 }
734 clearEngage(this.ecs, entityId);
735 setFollow(this.ecs, entityId, targetEntityId);
736 const path = this.ecs.get(handle, Component.path);
737 if (path)
738 { path.tiles = []; }
739 return { events: [] };
740 }
741
742 #cancelFollow (sessionId, characterId)
743 {
744 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
745 clearFollow(this.ecs, entityId);
746 return { events: [] };
747 }
748
749 #setGait (sessionId, characterId, gait)
750 {
751 if (gait !== GAIT.walk && gait !== GAIT.run)
752 {
753 const error = new Error("Gait must be walk or run.");
754 error.userFacing = true;
755 throw error;
756 }
757 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
758 this.ecs.get(handle, Component.movement).gait = gait;
759 }
760
761 #requireOwnedEntity (sessionId, characterId)
762 {
763 const entityId = this.characterEntities.get(characterId);
764 if (!entityId)
765 {
766 const error = new Error("Character is not in the world.");
767 error.userFacing = true;
768 throw error;
769 }
770 const handle = this.ecs.handleOf(entityId);
771 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
772 if (!identity || identity.sessionId !== sessionId)
773 {
774 const error = new Error("Character is not in the world.");
775 error.userFacing = true;
776 throw error;
777 }
778 if (this.ecs.has(handle, Component.dead))
779 {
780 const error = new Error("You are dead.");
781 error.userFacing = true;
782 throw error;
783 }
784 return { handle, entityId };
785 }
786
787 #stepSystems (now = Date.now())
788 {
789 const events = [];
790 const transferRequests = [];
791 const flight = stepFreeFlight(this, now);
792 for (const event of flight)
793 {
794 if (event.type === "transfer-request")
795 {
796 const payload = serializeEntity(this.ecs, event.entityId);
797 transferRequests.push({
798 entityId: event.entityId,
799 fromTileX: event.fromTileX,
800 fromTileY: event.fromTileY,
801 destTileX: event.destTileX,
802 destTileY: event.destTileY,
803 toRegionX: event.toRegionX,
804 toRegionY: event.toRegionY,
805 payload
806 });
807 continue;
808 }
809 events.push(event);
810 }
811 events.push(...stepCombat(this, now));
812 stepFollow(this);
813 return { events, transferRequests };
814 }
815
816 #stepMovement (now = Date.now())
817 {
818 const events = expireGroundItems(this, now);
819 const transferRequests = [];
820 this.#queueAmbientWander();
821 this.#queueSpawnerWander();
822 for (const entity of this.ecs.query(Component.position, Component.movement))
823 {
824 const { handle, entityId, position, movement } = entity;
825 if (this.ecs.has(handle, Component.dead))
826 { continue; }
827 if (this.ecs.has(handle, Component.flight))
828 { continue; }
829 const path = this.ecs.get(handle, Component.path);
830 const tiles = path?.tiles;
831 if (this.frozen.has(entityId) || !tiles?.length)
832 { continue; }
833 if (!this.chunkIsSimulating(position.tileX, position.tileY))
834 { continue; }
835
836 const isWalk = movement.gait !== GAIT.run;
837 if (isWalk)
838 {
839 movement.walkCarry = (movement.walkCarry + 1) % 2;
840 if (movement.walkCarry !== 0)
841 { continue; }
842 }
843
844 const next = tiles[0];
845 const destRegionX = tileToRegion(next.x);
846 const destRegionY = tileToRegion(next.y);
847 if (!this.ownsRegion(destRegionX, destRegionY))
848 {
849 this.frozen.add(entityId);
850 transferRequests.push({
851 entityId,
852 fromTileX: position.tileX,
853 fromTileY: position.tileY,
854 destTileX: next.x,
855 destTileY: next.y,
856 toRegionX: destRegionX,
857 toRegionY: destRegionY,
858 payload: serializeEntity(this.ecs, entityId)
859 });
860 continue;
861 }
862
863 if (!this.walkableFor(entityId, next.x, next.y))
864 {
865 const combat = this.ecs.get(handle, Component.combat);
866 if (combat?.targetEntityId != null)
867 {
868 const targetHandle = this.ecs.handleOf(combat.targetEntityId);
869 const targetPos = targetHandle != null
870 ? this.ecs.get(targetHandle, Component.position)
871 : null;
872 const blockedByTarget = targetPos
873 && next.x === targetPos.tileX
874 && next.y === targetPos.tileY;
875 if (!blockedByTarget)
876 { path.tiles = []; }
877 }
878 continue;
879 }
880
881 const fromTileX = position.tileX;
882 const fromTileY = position.tileY;
883 const flying = this.#isFlying(handle);
884 if (!flying)
885 { this.#vacate(entityId, fromTileX, fromTileY); }
886 position.tileX = next.x;
887 position.tileY = next.y;
888 tiles.shift();
889 if (!flying)
890 { this.#occupy(entityId, position.tileX, position.tileY); }
891 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
892 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
893 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
894 }
895 return { events, transferRequests };
896 }
897
898 #queueAmbientWander ()
899 {
900 for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
901 {
902 const def = mobDefinition(entity.creature.mobTypeId);
903 if (!def?.ambient || def.freeFlight)
904 { continue; }
905 if (this.ecs.get(entity.handle, Component.spawnOrigin))
906 { continue; }
907 const path = this.ecs.get(entity.handle, Component.path);
908 if (!path)
909 { continue; }
910 if (path.tiles?.length)
911 { continue; }
912 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
913 { continue; }
914 if (Math.random() > 0.35)
915 { continue; }
916 const dirs = [
917 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
918 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
919 ];
920 const dir = dirs[Math.floor(Math.random() * dirs.length)];
921 const nextX = entity.position.tileX + dir.x;
922 const nextY = entity.position.tileY + dir.y;
923 if (!this.walkableFor(entity.entityId, nextX, nextY))
924 { continue; }
925 path.tiles = [{ x: nextX, y: nextY }];
926 }
927 }
928
929 /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner. Combat chase is unrestricted. */
930 #queueSpawnerWander ()
931 {
932 for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin))
933 {
934 const combat = this.ecs.get(entity.handle, Component.combat);
935 if (combat?.targetEntityId != null)
936 { continue; }
937 const follow = this.ecs.get(entity.handle, Component.follow);
938 if (follow?.targetEntityId != null)
939 { continue; }
940 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
941 if (def?.freeFlight)
942 { continue; }
943 const path = this.ecs.get(entity.handle, Component.path);
944 if (!path || path.tiles?.length)
945 { continue; }
946 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
947 { continue; }
948 if (Math.random() > 0.4)
949 { continue; }
950
951 const origin = entity.spawnOrigin;
952 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
953 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
954 const range = Math.max(0, origin.wanderRangeTiles | 0);
955 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
956 if (!goal)
957 { continue; }
958 if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY)
959 { continue; }
960 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
961 const tiles = findPath(
962 entity.position.tileX,
963 entity.position.tileY,
964 goal.tileX,
965 goal.tileY,
966 (x, y) => this.walkableFor(entity.entityId, x, y),
967 bounds.minX,
968 bounds.minY,
969 bounds.maxX,
970 bounds.maxY
971 );
972 if (!tiles?.length)
973 { continue; }
974 path.tiles = tiles;
975 }
976 }
977
978 #applyTransfer (message)
979 {
980 const payload = message.payload;
981 const entityId = payload.entityId;
982 if (this.ecs.hasEntity(entityId))
983 { return { accepted: false, reason: "already-present" }; }
984
985 const position = payload.components?.position;
986 const destTileX = message.destTileX ?? position?.tileX;
987 const destTileY = message.destTileY ?? position?.tileY;
988 if (destTileX == null || destTileY == null)
989 { return { accepted: false, reason: "missing-destination" }; }
990 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
991 { return { accepted: false, reason: "not-owner" }; }
992
993 const creature = payload.components?.creature;
994 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
995 if (flying)
996 {
997 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY));
998 if (!data?.open)
999 { return { accepted: false, reason: "blocked" }; }
1000 }
1001 else if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
1002 { return { accepted: false, reason: "blocked" }; }
1003
1004 deserializeEntity(this.ecs, payload);
1005 const handle = this.ecs.handleOf(entityId);
1006 const livePosition = this.ecs.get(handle, Component.position);
1007 const path = this.ecs.get(handle, Component.path);
1008 livePosition.tileX = destTileX;
1009 livePosition.tileY = destTileY;
1010 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
1011 { path.tiles.shift(); }
1012 if (!flying)
1013 { this.#occupy(entityId, destTileX, destTileY); }
1014 const character = this.ecs.get(handle, Component.character);
1015 if (character?.characterId)
1016 { this.characterEntities.set(character.characterId, entityId); }
1017 this.frozen.delete(entityId);
1018 return {
1019 accepted: true,
1020 entity: publicEntityView(this.ecs, entityId)
1021 };
1022 }
1023
1024 #commitTransfer (entityId)
1025 {
1026 if (!this.ecs.hasEntity(entityId))
1027 { return null; }
1028 return this.#destroyEntity(entityId);
1029 }
1030
1031 #abortTransfer (entityId)
1032 {
1033 this.frozen.delete(entityId);
1034 return publicEntityView(this.ecs, entityId);
1035 }
1036
1037 #listLoaders ()
1038 {
1039 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
1040 entityId: entity.entityId,
1041 tileX: entity.position.tileX,
1042 tileY: entity.position.tileY,
1043 chunkLoader: { ...entity.chunkLoader }
1044 }));
1045 }
1046
1047 #listPublicEntities ()
1048 {
1049 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
1050 }
1051
1052 #entitiesInRegion (regionX, regionY)
1053 {
1054 const records = [];
1055 for (const entity of this.ecs.query(Component.position))
1056 {
1057 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
1058 { continue; }
1059 records.push({
1060 ...publicEntityView(this.ecs, entity.entityId),
1061 persistent: this.ecs.has(entity.handle, Component.persistent),
1062 payload: serializeEntity(this.ecs, entity.entityId)
1063 });
1064 }
1065 return records;
1066 }
1067
1068 #chunkSnapshot (chunkX, chunkY)
1069 {
1070 const data = this.#chunkData(chunkX, chunkY);
1071 const entities = [];
1072 for (const entity of this.ecs.query(Component.position, Component.appearance))
1073 {
1074 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
1075 { continue; }
1076 entities.push(publicEntityView(this.ecs, entity.entityId));
1077 }
1078 return {
1079 chunkX,
1080 chunkY,
1081 open: data.open,
1082 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
1083 grounds: data.grounds,
1084 blocks: data.blocks,
1085 light: data.light,
1086 entities,
1087 groundItems: groundItemsInChunk(this, chunkX, chunkY)
1088 };
1089 }
1090
1091 #moveEvent (entityId, fromTileX, fromTileY)
1092 {
1093 const view = publicEntityView(this.ecs, entityId);
1094 return {
1095 type: "entity-move",
1096 entityId,
1097 fromTileX,
1098 fromTileY,
1099 tileX: view.tileX,
1100 tileY: view.tileY,
1101 worldX: view.worldX,
1102 worldY: view.worldY,
1103 gait: view.gait,
1104 freeFlight: !!view.freeFlight
1105 };
1106 }
1107
1108 chunkIsSimulating (tileX, tileY)
1109 {
1110 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
1111 return !!chunk && !chunk.replica && chunk.simulating;
1112 }
1113
1114 chunkData (chunkX, chunkY)
1115 {
1116 return this.#chunkData(chunkX, chunkY);
1117 }
1118
1119 walkableFor (entityId, tileX, tileY)
1120 {
1121 const handle = this.ecs.handleOf(entityId);
1122 if (this.#isFlying(handle))
1123 {
1124 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1125 return !!data?.open;
1126 }
1127 if (!this.isEnterable(tileX, tileY))
1128 { return false; }
1129 const occupant = this.#occupied(tileX, tileY);
1130 return !occupant || occupant === entityId;
1131 }
1132
1133 destroyEntity (entityId)
1134 {
1135 return this.#destroyEntity(entityId);
1136 }
1137
1138 occupied (tileX, tileY)
1139 {
1140 return this.#occupied(tileX, tileY);
1141 }
1142
1143 #chunkIsSimulating (tileX, tileY)
1144 {
1145 return this.chunkIsSimulating(tileX, tileY);
1146 }
1147
1148 #chunkData (chunkX, chunkY)
1149 {
1150 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
1151 if (loaded)
1152 { return loaded.data; }
1153 return createEmptyChunkData(this.settings.defaultGroundTypeId);
1154 }
1155
1156 isEnterable (tileX, tileY)
1157 {
1158 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1159 if (!data.open)
1160 { return false; }
1161 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1162 }
1163
1164 #walkableFor (entityId, tileX, tileY)
1165 {
1166 return this.walkableFor(entityId, tileX, tileY);
1167 }
1168
1169 #isFlying (handle)
1170 {
1171 if (handle == null)
1172 { return false; }
1173 const creature = this.ecs.get(handle, Component.creature);
1174 return !!mobDefinition(creature?.mobTypeId)?.flying;
1175 }
1176
1177 #occupy (entityId, tileX, tileY)
1178 {
1179 this.occupancy.set(tileKey(tileX, tileY), entityId);
1180 }
1181
1182 #vacate (entityId, tileX, tileY)
1183 {
1184 const key = tileKey(tileX, tileY);
1185 if (this.occupancy.get(key) === entityId)
1186 { this.occupancy.delete(key); }
1187 }
1188
1189 #occupied (tileX, tileY)
1190 {
1191 return this.occupancy.get(tileKey(tileX, tileY))
1192 ?? this.ghostOccupancy.get(tileKey(tileX, tileY))
1193 ?? null;
1194 }
1195}
1196
1197function pickWanderGoalInRange (world, entityId, originX, originY, range)
1198{
1199 const radius = Math.max(0, range | 0);
1200 for (let attempt = 0; attempt < 24; attempt++)
1201 {
1202 const tileX = originX + randInt(-radius, radius);
1203 const tileY = originY + randInt(-radius, radius);
1204 if (!world.walkableFor(entityId, tileX, tileY))
1205 { continue; }
1206 return { tileX, tileY };
1207 }
1208 return null;
1209}
1210
1211function randInt (min, max)
1212{
1213 return min + Math.floor(Math.random() * (max - min + 1));
1214}
1215
1216export function replicaNeededForOwnedChunks (ownedChunkKeys)
1217{
1218 const needed = new Set();
1219 for (const key of ownedChunkKeys)
1220 {
1221 const { chunkX, chunkY } = parseChunkKey(key);
1222 for (let dy = -1; dy <= 1; dy++)
1223 {
1224 for (let dx = -1; dx <= 1; dx++)
1225 {
1226 if (dx === 0 && dy === 0)
1227 { continue; }
1228 needed.add(chunkKey(chunkX + dx, chunkY + dy));
1229 }
1230 }
1231 }
1232 return needed;
1233}