BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

simulation.js 10.2 KiB Download Raw
1import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS, WORLD_YEAR_OFFSET } from "../../../shared/protocol/constants.js";
2import { tileToChunk, tileToLocal, chunkKey, visibleChunkCoords, tileKey } from "../world/coordinates.js";
3import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";
4import { EcsWorld } from "../ecs/world.js";
5import { chunkBoundsAround, findPath } from "../navigation/astar.js";
6import { closedNeighborEdges } from "../world/chunkFlags.js";
7
8export class Simulation
9{
10 constructor (worldDb, stateDb)
11 {
12 this.worldDb = worldDb;
13 this.stateDb = stateDb;
14 this.ecs = new EcsWorld();
15 this.chunks = new Map();
16 this.occupancy = new Map();
17 this.characterEntities = new Map();
18 this.commandQueue = [];
19 this.movementTickCounter = 0;
20 this.activeRevisionId = worldDb.getActiveRevisionId();
21 this.settings = worldDb.getLiveSettings();
22 this.tickIndex = 0;
23 this.reloadWorld();
24 }
25
26 applySettings (settings)
27 {
28 this.settings = { ...this.settings, ...settings };
29 }
30
31 reloadWorld ()
32 {
33 this.activeRevisionId = this.worldDb.getActiveRevisionId();
34 this.settings = this.worldDb.getLiveSettings();
35 this.chunks.clear();
36 for (const entity of this.ecs.query("position"))
37 {
38 const pos = entity.position;
39 this.#ensureChunk(tileToChunk(pos.tileX), tileToChunk(pos.tileY));
40 }
41 }
42
43 enqueue (sessionId, command)
44 {
45 this.commandQueue.push({ sessionId, command, receivedAt: Date.now() });
46 }
47
48 step (now = Date.now())
49 {
50 this.tickIndex += 1;
51 const commands = this.commandQueue.splice(0);
52 const events = [];
53 for (const item of commands)
54 {
55 try
56 {
57 const produced = this.#handleCommand(item.sessionId, item.command) ?? [];
58 events.push(...produced);
59 }
60 catch (error)
61 {
62 events.push({
63 sessionId: item.sessionId,
64 type: "command-error",
65 message: error.userFacing ? error.message : "Command failed."
66 });
67 }
68 }
69
70 const movementHz = this.settings.walkTilesPerSecond * 2;
71 const simHz = this.settings.simulationTickHz;
72 const movementEvery = Math.max(1, Math.round(simHz / movementHz));
73 if (this.tickIndex % movementEvery === 0)
74 {
75 this.movementTickCounter += 1;
76 events.push(...this.#stepMovement());
77 }
78
79 return { now, events };
80 }
81
82 worldTime (now = Date.now())
83 {
84 const date = new Date(now);
85 date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
86 return {
87 unixMs: now,
88 worldUnixMs: date.getTime(),
89 iso: date.toISOString(),
90 hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600
91 };
92 }
93
94 spawnCharacter (sessionId, character)
95 {
96 this.despawnCharacter(character.character_id);
97 const tileX = character.tile_x;
98 const tileY = character.tile_y;
99 if (!this.isEnterable(tileX, tileY))
100 {
101 const spawn = this.findOpenSpawn();
102 if (!spawn)
103 {
104 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
105 error.userFacing = true;
106 throw error;
107 }
108 character.tile_x = spawn.tileX;
109 character.tile_y = spawn.tileY;
110 this.stateDb.saveCharacterPosition(character.character_id, spawn.tileX, spawn.tileY, character.gait);
111 }
112
113 const id = this.ecs.entity();
114 this.ecs.add(id, "position", { tileX: character.tile_x, tileY: character.tile_y });
115 this.ecs.add(id, "movement", { gait: character.gait || GAIT.walk, path: [], walkCarry: 0 });
116 this.ecs.add(id, "appearance", {
117 sex: character.sex,
118 firstName: character.first_name,
119 lastName: character.last_name
120 });
121 this.ecs.add(id, "character", {
122 characterId: character.character_id,
123 accountId: character.account_id,
124 sessionId
125 });
126 this.characterEntities.set(character.character_id, id);
127 this.#occupy(id, character.tile_x, character.tile_y);
128 this.#ensureVisibleChunks(character.tile_x, character.tile_y);
129 return id;
130 }
131
132 despawnCharacter (characterId)
133 {
134 const id = this.characterEntities.get(characterId);
135 if (!id)
136 { return; }
137
138 const position = this.ecs.get(id, "position");
139 const movement = this.ecs.get(id, "movement");
140 if (position)
141 {
142 this.#vacate(id, position.tileX, position.tileY);
143 this.stateDb.saveCharacterPosition(characterId, position.tileX, position.tileY, movement?.gait ?? GAIT.walk);
144 }
145 this.ecs.destroy(id);
146 this.characterEntities.delete(characterId);
147 }
148
149 entityForCharacter (characterId)
150 {
151 return this.characterEntities.get(characterId) ?? null;
152 }
153
154 snapshotFor (entityId)
155 {
156 const position = this.ecs.get(entityId, "position");
157 if (!position)
158 { return []; }
159
160 const coords = visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS);
161 return coords.map((coord) => this.#chunkSnapshot(coord.chunkX, coord.chunkY));
162 }
163
164 findOpenSpawn ()
165 {
166 const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
167 for (const coord of coords)
168 {
169 const data = this.#ensureChunk(coord.chunk_x, coord.chunk_y);
170 if (!data.open)
171 { continue; }
172 for (let localY = 0; localY < CHUNK_SIZE; localY++)
173 {
174 for (let localX = 0; localX < CHUNK_SIZE; localX++)
175 {
176 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
177 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
178 if (this.isEnterable(tileX, tileY) && !this.#occupied(tileX, tileY))
179 { return { tileX, tileY }; }
180 }
181 }
182 }
183 return null;
184 }
185
186 isEnterable (tileX, tileY)
187 {
188 const data = this.#ensureChunk(tileToChunk(tileX), tileToChunk(tileY));
189 if (!data.open)
190 { return false; }
191 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
192 }
193
194 #handleCommand (sessionId, command)
195 {
196 switch (command.type)
197 {
198 case "move-to":
199 return this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
200 case "set-gait":
201 return this.#setGait(sessionId, command.characterId, command.gait);
202 default:
203 return [];
204 }
205 }
206
207 #moveTo (sessionId, characterId, tileX, tileY)
208 {
209 const id = this.#requireOwnedEntity(sessionId, characterId);
210 const position = this.ecs.get(id, "position");
211 const movement = this.ecs.get(id, "movement");
212 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
213 const path = findPath(
214 position.tileX,
215 position.tileY,
216 tileX,
217 tileY,
218 (x, y) => this.#walkableFor(id, x, y),
219 bounds.minX,
220 bounds.minY,
221 bounds.maxX,
222 bounds.maxY
223 );
224 movement.path = path;
225 movement.walkCarry = 0;
226 return [];
227 }
228
229 #setGait (sessionId, characterId, gait)
230 {
231 if (gait !== GAIT.walk && gait !== GAIT.run)
232 {
233 const error = new Error("Gait must be walk or run.");
234 error.userFacing = true;
235 throw error;
236 }
237 const id = this.#requireOwnedEntity(sessionId, characterId);
238 this.ecs.get(id, "movement").gait = gait;
239 return [];
240 }
241
242 #requireOwnedEntity (sessionId, characterId)
243 {
244 const id = this.characterEntities.get(characterId);
245 if (!id)
246 {
247 const error = new Error("Character is not in the world.");
248 error.userFacing = true;
249 throw error;
250 }
251 const character = this.ecs.get(id, "character");
252 if (!character || character.sessionId !== sessionId)
253 {
254 const error = new Error("Character is not in the world.");
255 error.userFacing = true;
256 throw error;
257 }
258 return id;
259 }
260
261 #stepMovement ()
262 {
263 const events = [];
264 for (const entity of this.ecs.query("position", "movement"))
265 {
266 const { id, position, movement } = entity;
267 if (!movement.path.length)
268 { continue; }
269
270 const isWalk = movement.gait !== GAIT.run;
271 if (isWalk)
272 {
273 movement.walkCarry = (movement.walkCarry + 1) % 2;
274 if (movement.walkCarry !== 0)
275 { continue; }
276 }
277
278 const next = movement.path[0];
279 if (!this.#walkableFor(id, next.x, next.y))
280 { continue; }
281
282 const fromTileX = position.tileX;
283 const fromTileY = position.tileY;
284 this.#vacate(id, fromTileX, fromTileY);
285 position.tileX = next.x;
286 position.tileY = next.y;
287 movement.path.shift();
288 this.#occupy(id, position.tileX, position.tileY);
289 this.#ensureVisibleChunks(position.tileX, position.tileY);
290 const character = this.ecs.get(id, "character");
291 events.push({
292 type: "entity-move",
293 entityId: id,
294 characterId: character?.characterId,
295 fromTileX,
296 fromTileY,
297 tileX: position.tileX,
298 tileY: position.tileY,
299 gait: movement.gait
300 });
301 }
302 return events;
303 }
304
305 #walkableFor (entityId, tileX, tileY)
306 {
307 if (!this.isEnterable(tileX, tileY))
308 { return false; }
309 const occupant = this.#occupied(tileX, tileY);
310 return !occupant || occupant === entityId;
311 }
312
313 #ensureVisibleChunks (tileX, tileY)
314 {
315 for (const coord of visibleChunkCoords(tileToChunk(tileX), tileToChunk(tileY), VISIBLE_CHUNK_RADIUS))
316 { this.#ensureChunk(coord.chunkX, coord.chunkY); }
317 }
318
319 #ensureChunk (chunkX, chunkY)
320 {
321 const key = chunkKey(chunkX, chunkY);
322 if (this.chunks.has(key))
323 { return this.chunks.get(key); }
324
325 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
326 const data = row
327 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
328 : createEmptyChunkData(this.settings.defaultGroundTypeId);
329 this.chunks.set(key, data);
330 return data;
331 }
332
333 #chunkSnapshot (chunkX, chunkY)
334 {
335 const data = this.#ensureChunk(chunkX, chunkY);
336 const entities = [];
337 for (const entity of this.ecs.query("position", "appearance"))
338 {
339 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
340 { continue; }
341 const movement = this.ecs.get(entity.id, "movement");
342 const character = this.ecs.get(entity.id, "character");
343 entities.push({
344 entityId: entity.id,
345 characterId: character?.characterId ?? null,
346 tileX: entity.position.tileX,
347 tileY: entity.position.tileY,
348 gait: movement?.gait ?? GAIT.walk,
349 sex: entity.appearance.sex,
350 firstName: entity.appearance.firstName,
351 lastName: entity.appearance.lastName
352 });
353 }
354 return {
355 chunkX,
356 chunkY,
357 open: data.open,
358 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#ensureChunk(x, y).open),
359 grounds: data.grounds,
360 blocks: data.blocks,
361 light: data.light,
362 entities
363 };
364 }
365
366 #occupy (entityId, tileX, tileY)
367 {
368 this.occupancy.set(tileKey(tileX, tileY), entityId);
369 }
370
371 #vacate (entityId, tileX, tileY)
372 {
373 const key = tileKey(tileX, tileY);
374 if (this.occupancy.get(key) === entityId)
375 { this.occupancy.delete(key); }
376 }
377
378 #occupied (tileX, tileY)
379 {
380 return this.occupancy.get(tileKey(tileX, tileY)) ?? null;
381 }
382}