BlueGit

timfa questward

Files

questward / server / src / simulation / simulation.js

simulation.js

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