BlueGit

timfa questward

Files

questward / server / src / simulation / workerWorld.js

workerWorld.js

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