Add the simulation tick, open-chunk movement, and 3x3 snapshots.
Co-authored-by: Cursor <cursoragent@cursor.com>
@@ -21,9 +21,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
21
21
22
22
## Open and closed chunks
23
23
24
**Status:** not implemented
25
**Spec:** Never-edited chunks are closed. Closed chunks are visible in the 3×3 view but cannot be entered. Pathfinding and spawners treat them as impassable.
26
**Code:** —
24
**Status:** full
25
**Spec:** Never-edited chunks are closed grass. Closed chunks can be replicated but cannot be entered; pathfinding treats them as impassable.
26
**Code:** `server/src/world/chunkData.js` (`open` flag), `server/src/simulation/simulation.js` (`isEnterable`, `#walkableFor`), editor save in `server/src/editor/service.js`
27
27
28
28
## ECS registry and components
29
29
@@ -33,9 +33,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
33
33
34
34
## Simulation tick
35
35
36
**Status:** not implemented
37
**Spec:** Fixed tick from `WorldSettings.simulationTickHz` (default 20 Hz). Commands drain at tick boundaries.
38
**Code:** —
36
**Status:** partial
37
**Spec:** Fixed tick from `WorldSettings.simulationTickHz` (default 20 Hz). Commands drain at tick boundaries. Single process; no region workers.
38
**Code:** `server/src/simulation/simulation.js` (`step`), `server/src/index.js`
39
39
40
40
## Authored world and runtime state persistence
41
41
@@ -67,6 +67,12 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
67
67
**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks, write changelog bullets, edit world settings, and apply the pending revision. Marketplace/bank/spawner placement is later.
68
68
**Code:** `server/src/editor/service.js`
69
69
70
## World editor (client)
71
72
**Status:** not implemented
73
**Spec:** Separate admin UI. One chunk at a time, chunk-step navigation, paint palette, open/closed, changelog, night preview slider, settings modal.
74
**Code:** —
75
70
76
## Per-chunk changelog
71
77
72
78
**Status:** full
@@ -99,21 +105,21 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
99
105
100
106
## 3×3 chunk replication
101
107
102
**Status:** not implemented
103
**Spec:** Players receive the current chunk and eight neighbours as snapshots, then deltas. Closed chunks are still sent.
104
**Code:** —
108
**Status:** partial
109
**Spec:** Players receive the current chunk and eight neighbours as snapshots. Closed chunks are still sent. Entity moves are incremental; tile deltas are not used yet because live tile edits wait for Apply now.
110
**Code:** `server/src/simulation/simulation.js` (`snapshotFor`), `server/src/gateway/websocket.js` (`syncSubscriptions`)
105
111
106
112
## Click-to-move and A\* pathfinding
107
113
108
**Status:** partial
109
**Spec:** Four-direction A\* with a binary heap over a bounded search (the visible 3×3 once wired to movement). Passability is supplied by the caller.
110
**Code:** `server/src/navigation/astar.js`, tests in `server/tests/astar.test.js`
114
**Status:** full
115
**Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Occupied tiles block. Server commits integer tiles on the movement cadence.
116
**Code:** `server/src/navigation/astar.js`, `server/src/simulation/simulation.js` (`#moveTo`, `#stepMovement`)
111
117
112
118
## Global walk/run cadence
113
119
114
**Status:** not implemented
120
**Status:** full
115
121
**Spec:** Walk 2 tiles/s, run double. Movement ticks at run rate. `SetGait` chooses every-other vs every movement tick.
116
**Code:** —
122
**Code:** `server/src/simulation/simulation.js` (`#stepMovement`, `#setGait`)
117
123
118
124
## Client movement interpolation
119
125
@@ -153,9 +159,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
153
159
154
160
## ChunkLoader activation and unload persistence
155
161
156
**Status:** not implemented
157
**Spec:** Reference-counted loaders keep chunks simulating. Persist on unload, not on a timer.
158
**Code:** —
162
**Status:** partial
163
**Spec:** Chunks around players are loaded into memory for simulation and visibility. Character positions persist on despawn. There is no grace-period unload writer yet; authored data is already in `world.sqlite`.
164
**Code:** `server/src/simulation/simulation.js` (`#ensureChunk`, `despawnCharacter`)
159
165
160
166
## Midnight restart and Git deploy
161
167
@@ -21,9 +21,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi21
21
22
## Open and closed chunks22
## Open and closed chunks23
23
24
**Status:** not implemented 24
**Status:** full 25
**Spec:** Never-edited chunks are closed. Closed chunks are visible in the 3×3 view but cannot be entered. Pathfinding and spawners treat them as impassable. 25
**Spec:** Never-edited chunks are closed grass. Closed chunks can be replicated but cannot be entered; pathfinding treats them as impassable. 26
**Code:** —26
**Code:** `server/src/world/chunkData.js` (`open` flag), `server/src/simulation/simulation.js` (`isEnterable`, `#walkableFor`), editor save in `server/src/editor/service.js`27
27
28
## ECS registry and components28
## ECS registry and components29
29
@@ -33,9 +33,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi33
33
34
## Simulation tick34
## Simulation tick35
35
36
**Status:** not implemented 36
**Status:** partial 37
**Spec:** Fixed tick from `WorldSettings.simulationTickHz` (default 20 Hz). Commands drain at tick boundaries. 37
**Spec:** Fixed tick from `WorldSettings.simulationTickHz` (default 20 Hz). Commands drain at tick boundaries. Single process; no region workers. 38
**Code:** —38
**Code:** `server/src/simulation/simulation.js` (`step`), `server/src/index.js`39
39
40
## Authored world and runtime state persistence40
## Authored world and runtime state persistence41
41
@@ -67,6 +67,12 @@ Each entry is a short note on behaviour and where the code lives. Update this fi67
**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks, write changelog bullets, edit world settings, and apply the pending revision. Marketplace/bank/spawner placement is later. 67
**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks, write changelog bullets, edit world settings, and apply the pending revision. Marketplace/bank/spawner placement is later. 68
**Code:** `server/src/editor/service.js`68
**Code:** `server/src/editor/service.js`69
69
70
## World editor (client)71
72
**Status:** not implemented 73
**Spec:** Separate admin UI. One chunk at a time, chunk-step navigation, paint palette, open/closed, changelog, night preview slider, settings modal. 74
**Code:** —75
70
## Per-chunk changelog76
## Per-chunk changelog71
77
72
**Status:** full 78
**Status:** full @@ -99,21 +105,21 @@ Each entry is a short note on behaviour and where the code lives. Update this fi99
105
100
## 3×3 chunk replication106
## 3×3 chunk replication101
107
102
**Status:** not implemented 108
**Status:** partial 103
**Spec:** Players receive the current chunk and eight neighbours as snapshots, then deltas. Closed chunks are still sent. 109
**Spec:** Players receive the current chunk and eight neighbours as snapshots. Closed chunks are still sent. Entity moves are incremental; tile deltas are not used yet because live tile edits wait for Apply now. 104
**Code:** —110
**Code:** `server/src/simulation/simulation.js` (`snapshotFor`), `server/src/gateway/websocket.js` (`syncSubscriptions`)105
111
106
## Click-to-move and A\* pathfinding112
## Click-to-move and A\* pathfinding107
113
108
**Status:** partial 114
**Status:** full 109
**Spec:** Four-direction A\* with a binary heap over a bounded search (the visible 3×3 once wired to movement). Passability is supplied by the caller. 115
**Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Occupied tiles block. Server commits integer tiles on the movement cadence. 110
**Code:** `server/src/navigation/astar.js`, tests in `server/tests/astar.test.js`116
**Code:** `server/src/navigation/astar.js`, `server/src/simulation/simulation.js` (`#moveTo`, `#stepMovement`)111
117
112
## Global walk/run cadence118
## Global walk/run cadence113
119
114
**Status:** not implemented 120
**Status:** full 115
**Spec:** Walk 2 tiles/s, run double. Movement ticks at run rate. `SetGait` chooses every-other vs every movement tick. 121
**Spec:** Walk 2 tiles/s, run double. Movement ticks at run rate. `SetGait` chooses every-other vs every movement tick. 116
**Code:** —122
**Code:** `server/src/simulation/simulation.js` (`#stepMovement`, `#setGait`)117
123
118
## Client movement interpolation124
## Client movement interpolation119
125
@@ -153,9 +159,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi153
159
154
## ChunkLoader activation and unload persistence160
## ChunkLoader activation and unload persistence155
161
156
**Status:** not implemented 162
**Status:** partial 157
**Spec:** Reference-counted loaders keep chunks simulating. Persist on unload, not on a timer. 163
**Spec:** Chunks around players are loaded into memory for simulation and visibility. Character positions persist on despawn. There is no grace-period unload writer yet; authored data is already in `world.sqlite`. 158
**Code:** —164
**Code:** `server/src/simulation/simulation.js` (`#ensureChunk`, `despawnCharacter`)159
165
160
## Midnight restart and Git deploy166
## Midnight restart and Git deploy161
167
@@ -0,0 +1,375 @@
1
import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS, WORLD_YEAR_OFFSET } from "../../../shared/protocol/constants.js";
2
import { tileToChunk, tileToLocal, chunkKey, visibleChunkCoords, tileKey } from "../world/coordinates.js";
3
import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";
4
import { EcsWorld } from "../ecs/world.js";
5
import { chunkBoundsAround, findPath } from "../navigation/astar.js";
6
7
export class Simulation
8
{
9
constructor (worldDb, stateDb)
10
{
11
this.worldDb = worldDb;
12
this.stateDb = stateDb;
13
this.ecs = new EcsWorld();
14
this.chunks = new Map();
15
this.occupancy = new Map();
16
this.characterEntities = new Map();
17
this.commandQueue = [];
18
this.movementTickCounter = 0;
19
this.activeRevisionId = worldDb.getActiveRevisionId();
20
this.settings = worldDb.getSettings(this.activeRevisionId);
21
this.tickIndex = 0;
22
this.reloadWorld();
23
}
24
25
reloadWorld ()
26
{
27
this.activeRevisionId = this.worldDb.getActiveRevisionId();
28
this.settings = this.worldDb.getSettings(this.activeRevisionId);
29
this.chunks.clear();
30
for (const entity of this.ecs.query("position"))
31
{
32
const pos = entity.position;
33
this.#ensureChunk(tileToChunk(pos.tileX), tileToChunk(pos.tileY));
34
}
35
}
36
37
enqueue (sessionId, command)
38
{
39
this.commandQueue.push({ sessionId, command, receivedAt: Date.now() });
40
}
41
42
step (now = Date.now())
43
{
44
this.tickIndex += 1;
45
const commands = this.commandQueue.splice(0);
46
const events = [];
47
for (const item of commands)
48
{
49
try
50
{
51
const produced = this.#handleCommand(item.sessionId, item.command) ?? [];
52
events.push(...produced);
53
}
54
catch (error)
55
{
56
events.push({
57
sessionId: item.sessionId,
58
type: "command-error",
59
message: error.userFacing ? error.message : "Command failed."
60
});
61
}
62
}
63
64
const movementHz = this.settings.walkTilesPerSecond * 2;
65
const simHz = this.settings.simulationTickHz;
66
const movementEvery = Math.max(1, Math.round(simHz / movementHz));
67
if (this.tickIndex % movementEvery === 0)
68
{
69
this.movementTickCounter += 1;
70
events.push(...this.#stepMovement());
71
}
72
73
return { now, events };
74
}
75
76
worldTime (now = Date.now())
77
{
78
const date = new Date(now);
79
date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
80
return {
81
unixMs: now,
82
worldUnixMs: date.getTime(),
83
iso: date.toISOString(),
84
hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600
85
};
86
}
87
88
spawnCharacter (sessionId, character)
89
{
90
this.despawnCharacter(character.character_id);
91
const tileX = character.tile_x;
92
const tileY = character.tile_y;
93
if (!this.isEnterable(tileX, tileY))
94
{
95
const spawn = this.findOpenSpawn();
96
if (!spawn)
97
{
98
const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
99
error.userFacing = true;
100
throw error;
101
}
102
character.tile_x = spawn.tileX;
103
character.tile_y = spawn.tileY;
104
this.stateDb.saveCharacterPosition(character.character_id, spawn.tileX, spawn.tileY, character.gait);
105
}
106
107
const id = this.ecs.entity();
108
this.ecs.add(id, "position", { tileX: character.tile_x, tileY: character.tile_y });
109
this.ecs.add(id, "movement", { gait: character.gait || GAIT.walk, path: [], walkCarry: 0 });
110
this.ecs.add(id, "appearance", {
111
sex: character.sex,
112
firstName: character.first_name,
113
lastName: character.last_name
114
});
115
this.ecs.add(id, "character", {
116
characterId: character.character_id,
117
accountId: character.account_id,
118
sessionId
119
});
120
this.characterEntities.set(character.character_id, id);
121
this.#occupy(id, character.tile_x, character.tile_y);
122
this.#ensureVisibleChunks(character.tile_x, character.tile_y);
123
return id;
124
}
125
126
despawnCharacter (characterId)
127
{
128
const id = this.characterEntities.get(characterId);
129
if (!id)
130
{ return; }
131
132
const position = this.ecs.get(id, "position");
133
const movement = this.ecs.get(id, "movement");
134
if (position)
135
{
136
this.#vacate(id, position.tileX, position.tileY);
137
this.stateDb.saveCharacterPosition(characterId, position.tileX, position.tileY, movement?.gait ?? GAIT.walk);
138
}
139
this.ecs.destroy(id);
140
this.characterEntities.delete(characterId);
141
}
142
143
entityForCharacter (characterId)
144
{
145
return this.characterEntities.get(characterId) ?? null;
146
}
147
148
snapshotFor (entityId)
149
{
150
const position = this.ecs.get(entityId, "position");
151
if (!position)
152
{ return []; }
153
154
const coords = visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS);
155
return coords.map((coord) => this.#chunkSnapshot(coord.chunkX, coord.chunkY));
156
}
157
158
findOpenSpawn ()
159
{
160
const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
161
for (const coord of coords)
162
{
163
const data = this.#ensureChunk(coord.chunk_x, coord.chunk_y);
164
if (!data.open)
165
{ continue; }
166
for (let localY = 0; localY < CHUNK_SIZE; localY++)
167
{
168
for (let localX = 0; localX < CHUNK_SIZE; localX++)
169
{
170
const tileX = coord.chunk_x * CHUNK_SIZE + localX;
171
const tileY = coord.chunk_y * CHUNK_SIZE + localY;
172
if (this.isEnterable(tileX, tileY) && !this.#occupied(tileX, tileY))
173
{ return { tileX, tileY }; }
174
}
175
}
176
}
177
return null;
178
}
179
180
isEnterable (tileX, tileY)
181
{
182
const data = this.#ensureChunk(tileToChunk(tileX), tileToChunk(tileY));
183
if (!data.open)
184
{ return false; }
185
return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
186
}
187
188
#handleCommand (sessionId, command)
189
{
190
switch (command.type)
191
{
192
case "move-to":
193
return this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
194
case "set-gait":
195
return this.#setGait(sessionId, command.characterId, command.gait);
196
default:
197
return [];
198
}
199
}
200
201
#moveTo (sessionId, characterId, tileX, tileY)
202
{
203
const id = this.#requireOwnedEntity(sessionId, characterId);
204
const position = this.ecs.get(id, "position");
205
const movement = this.ecs.get(id, "movement");
206
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
207
const path = findPath(
208
position.tileX,
209
position.tileY,
210
tileX,
211
tileY,
212
(x, y) => this.#walkableFor(id, x, y),
213
bounds.minX,
214
bounds.minY,
215
bounds.maxX,
216
bounds.maxY
217
);
218
movement.path = path;
219
movement.walkCarry = 0;
220
return [];
221
}
222
223
#setGait (sessionId, characterId, gait)
224
{
225
if (gait !== GAIT.walk && gait !== GAIT.run)
226
{
227
const error = new Error("Gait must be walk or run.");
228
error.userFacing = true;
229
throw error;
230
}
231
const id = this.#requireOwnedEntity(sessionId, characterId);
232
this.ecs.get(id, "movement").gait = gait;
233
return [];
234
}
235
236
#requireOwnedEntity (sessionId, characterId)
237
{
238
const id = this.characterEntities.get(characterId);
239
if (!id)
240
{
241
const error = new Error("Character is not in the world.");
242
error.userFacing = true;
243
throw error;
244
}
245
const character = this.ecs.get(id, "character");
246
if (!character || character.sessionId !== sessionId)
247
{
248
const error = new Error("Character is not in the world.");
249
error.userFacing = true;
250
throw error;
251
}
252
return id;
253
}
254
255
#stepMovement ()
256
{
257
const events = [];
258
for (const entity of this.ecs.query("position", "movement"))
259
{
260
const { id, position, movement } = entity;
261
if (!movement.path.length)
262
{ continue; }
263
264
const isWalk = movement.gait !== GAIT.run;
265
if (isWalk)
266
{
267
movement.walkCarry = (movement.walkCarry + 1) % 2;
268
if (movement.walkCarry !== 0)
269
{ continue; }
270
}
271
272
const next = movement.path[0];
273
if (!this.#walkableFor(id, next.x, next.y))
274
{ continue; }
275
276
const fromTileX = position.tileX;
277
const fromTileY = position.tileY;
278
this.#vacate(id, fromTileX, fromTileY);
279
position.tileX = next.x;
280
position.tileY = next.y;
281
movement.path.shift();
282
this.#occupy(id, position.tileX, position.tileY);
283
this.#ensureVisibleChunks(position.tileX, position.tileY);
284
const character = this.ecs.get(id, "character");
285
events.push({
286
type: "entity-move",
287
entityId: id,
288
characterId: character?.characterId,
289
fromTileX,
290
fromTileY,
291
tileX: position.tileX,
292
tileY: position.tileY,
293
gait: movement.gait
294
});
295
}
296
return events;
297
}
298
299
#walkableFor (entityId, tileX, tileY)
300
{
301
if (!this.isEnterable(tileX, tileY))
302
{ return false; }
303
const occupant = this.#occupied(tileX, tileY);
304
return !occupant || occupant === entityId;
305
}
306
307
#ensureVisibleChunks (tileX, tileY)
308
{
309
for (const coord of visibleChunkCoords(tileToChunk(tileX), tileToChunk(tileY), VISIBLE_CHUNK_RADIUS))
310
{ this.#ensureChunk(coord.chunkX, coord.chunkY); }
311
}
312
313
#ensureChunk (chunkX, chunkY)
314
{
315
const key = chunkKey(chunkX, chunkY);
316
if (this.chunks.has(key))
317
{ return this.chunks.get(key); }
318
319
const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
320
const data = row
321
? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
322
: createEmptyChunkData(this.settings.defaultGroundTypeId);
323
this.chunks.set(key, data);
324
return data;
325
}
326
327
#chunkSnapshot (chunkX, chunkY)
328
{
329
const data = this.#ensureChunk(chunkX, chunkY);
330
const entities = [];
331
for (const entity of this.ecs.query("position", "appearance"))
332
{
333
if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
334
{ continue; }
335
const movement = this.ecs.get(entity.id, "movement");
336
const character = this.ecs.get(entity.id, "character");
337
entities.push({
338
entityId: entity.id,
339
characterId: character?.characterId ?? null,
340
tileX: entity.position.tileX,
341
tileY: entity.position.tileY,
342
gait: movement?.gait ?? GAIT.walk,
343
sex: entity.appearance.sex,
344
firstName: entity.appearance.firstName,
345
lastName: entity.appearance.lastName
346
});
347
}
348
return {
349
chunkX,
350
chunkY,
351
open: data.open,
352
grounds: data.grounds,
353
blocks: data.blocks,
354
light: data.light,
355
entities
356
};
357
}
358
359
#occupy (entityId, tileX, tileY)
360
{
361
this.occupancy.set(tileKey(tileX, tileY), entityId);
362
}
363
364
#vacate (entityId, tileX, tileY)
365
{
366
const key = tileKey(tileX, tileY);
367
if (this.occupancy.get(key) === entityId)
368
{ this.occupancy.delete(key); }
369
}
370
371
#occupied (tileX, tileY)
372
{
373
return this.occupancy.get(tileKey(tileX, tileY)) ?? null;
374
}
375
}
@@ -0,0 +1,375 @@1
import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS, WORLD_YEAR_OFFSET } from "../../../shared/protocol/constants.js";2
import { tileToChunk, tileToLocal, chunkKey, visibleChunkCoords, tileKey } from "../world/coordinates.js";3
import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";4
import { EcsWorld } from "../ecs/world.js";5
import { chunkBoundsAround, findPath } from "../navigation/astar.js";6
7
export class Simulation8
{9
constructor (worldDb, stateDb)10
{11
this.worldDb = worldDb;12
this.stateDb = stateDb;13
this.ecs = new EcsWorld();14
this.chunks = new Map();15
this.occupancy = new Map();16
this.characterEntities = new Map();17
this.commandQueue = [];18
this.movementTickCounter = 0;19
this.activeRevisionId = worldDb.getActiveRevisionId();20
this.settings = worldDb.getSettings(this.activeRevisionId);21
this.tickIndex = 0;22
this.reloadWorld();23
}24
25
reloadWorld ()26
{27
this.activeRevisionId = this.worldDb.getActiveRevisionId();28
this.settings = this.worldDb.getSettings(this.activeRevisionId);29
this.chunks.clear();30
for (const entity of this.ecs.query("position"))31
{32
const pos = entity.position;33
this.#ensureChunk(tileToChunk(pos.tileX), tileToChunk(pos.tileY));34
}35
}36
37
enqueue (sessionId, command)38
{39
this.commandQueue.push({ sessionId, command, receivedAt: Date.now() });40
}41
42
step (now = Date.now())43
{44
this.tickIndex += 1;45
const commands = this.commandQueue.splice(0);46
const events = [];47
for (const item of commands)48
{49
try50
{51
const produced = this.#handleCommand(item.sessionId, item.command) ?? [];52
events.push(...produced);53
}54
catch (error)55
{56
events.push({57
sessionId: item.sessionId,58
type: "command-error",59
message: error.userFacing ? error.message : "Command failed."60
});61
}62
}63
64
const movementHz = this.settings.walkTilesPerSecond * 2;65
const simHz = this.settings.simulationTickHz;66
const movementEvery = Math.max(1, Math.round(simHz / movementHz));67
if (this.tickIndex % movementEvery === 0)68
{69
this.movementTickCounter += 1;70
events.push(...this.#stepMovement());71
}72
73
return { now, events };74
}75
76
worldTime (now = Date.now())77
{78
const date = new Date(now);79
date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);80
return {81
unixMs: now,82
worldUnixMs: date.getTime(),83
iso: date.toISOString(),84
hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 360085
};86
}87
88
spawnCharacter (sessionId, character)89
{90
this.despawnCharacter(character.character_id);91
const tileX = character.tile_x;92
const tileY = character.tile_y;93
if (!this.isEnterable(tileX, tileY))94
{95
const spawn = this.findOpenSpawn();96
if (!spawn)97
{98
const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");99
error.userFacing = true;100
throw error;101
}102
character.tile_x = spawn.tileX;103
character.tile_y = spawn.tileY;104
this.stateDb.saveCharacterPosition(character.character_id, spawn.tileX, spawn.tileY, character.gait);105
}106
107
const id = this.ecs.entity();108
this.ecs.add(id, "position", { tileX: character.tile_x, tileY: character.tile_y });109
this.ecs.add(id, "movement", { gait: character.gait || GAIT.walk, path: [], walkCarry: 0 });110
this.ecs.add(id, "appearance", {111
sex: character.sex,112
firstName: character.first_name,113
lastName: character.last_name114
});115
this.ecs.add(id, "character", {116
characterId: character.character_id,117
accountId: character.account_id,118
sessionId119
});120
this.characterEntities.set(character.character_id, id);121
this.#occupy(id, character.tile_x, character.tile_y);122
this.#ensureVisibleChunks(character.tile_x, character.tile_y);123
return id;124
}125
126
despawnCharacter (characterId)127
{128
const id = this.characterEntities.get(characterId);129
if (!id)130
{ return; }131
132
const position = this.ecs.get(id, "position");133
const movement = this.ecs.get(id, "movement");134
if (position)135
{136
this.#vacate(id, position.tileX, position.tileY);137
this.stateDb.saveCharacterPosition(characterId, position.tileX, position.tileY, movement?.gait ?? GAIT.walk);138
}139
this.ecs.destroy(id);140
this.characterEntities.delete(characterId);141
}142
143
entityForCharacter (characterId)144
{145
return this.characterEntities.get(characterId) ?? null;146
}147
148
snapshotFor (entityId)149
{150
const position = this.ecs.get(entityId, "position");151
if (!position)152
{ return []; }153
154
const coords = visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS);155
return coords.map((coord) => this.#chunkSnapshot(coord.chunkX, coord.chunkY));156
}157
158
findOpenSpawn ()159
{160
const coords = this.worldDb.listChunkCoords(this.activeRevisionId);161
for (const coord of coords)162
{163
const data = this.#ensureChunk(coord.chunk_x, coord.chunk_y);164
if (!data.open)165
{ continue; }166
for (let localY = 0; localY < CHUNK_SIZE; localY++)167
{168
for (let localX = 0; localX < CHUNK_SIZE; localX++)169
{170
const tileX = coord.chunk_x * CHUNK_SIZE + localX;171
const tileY = coord.chunk_y * CHUNK_SIZE + localY;172
if (this.isEnterable(tileX, tileY) && !this.#occupied(tileX, tileY))173
{ return { tileX, tileY }; }174
}175
}176
}177
return null;178
}179
180
isEnterable (tileX, tileY)181
{182
const data = this.#ensureChunk(tileToChunk(tileX), tileToChunk(tileY));183
if (!data.open)184
{ return false; }185
return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));186
}187
188
#handleCommand (sessionId, command)189
{190
switch (command.type)191
{192
case "move-to":193
return this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);194
case "set-gait":195
return this.#setGait(sessionId, command.characterId, command.gait);196
default:197
return [];198
}199
}200
201
#moveTo (sessionId, characterId, tileX, tileY)202
{203
const id = this.#requireOwnedEntity(sessionId, characterId);204
const position = this.ecs.get(id, "position");205
const movement = this.ecs.get(id, "movement");206
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);207
const path = findPath(208
position.tileX,209
position.tileY,210
tileX,211
tileY,212
(x, y) => this.#walkableFor(id, x, y),213
bounds.minX,214
bounds.minY,215
bounds.maxX,216
bounds.maxY217
);218
movement.path = path;219
movement.walkCarry = 0;220
return [];221
}222
223
#setGait (sessionId, characterId, gait)224
{225
if (gait !== GAIT.walk && gait !== GAIT.run)226
{227
const error = new Error("Gait must be walk or run.");228
error.userFacing = true;229
throw error;230
}231
const id = this.#requireOwnedEntity(sessionId, characterId);232
this.ecs.get(id, "movement").gait = gait;233
return [];234
}235
236
#requireOwnedEntity (sessionId, characterId)237
{238
const id = this.characterEntities.get(characterId);239
if (!id)240
{241
const error = new Error("Character is not in the world.");242
error.userFacing = true;243
throw error;244
}245
const character = this.ecs.get(id, "character");246
if (!character || character.sessionId !== sessionId)247
{248
const error = new Error("Character is not in the world.");249
error.userFacing = true;250
throw error;251
}252
return id;253
}254
255
#stepMovement ()256
{257
const events = [];258
for (const entity of this.ecs.query("position", "movement"))259
{260
const { id, position, movement } = entity;261
if (!movement.path.length)262
{ continue; }263
264
const isWalk = movement.gait !== GAIT.run;265
if (isWalk)266
{267
movement.walkCarry = (movement.walkCarry + 1) % 2;268
if (movement.walkCarry !== 0)269
{ continue; }270
}271
272
const next = movement.path[0];273
if (!this.#walkableFor(id, next.x, next.y))274
{ continue; }275
276
const fromTileX = position.tileX;277
const fromTileY = position.tileY;278
this.#vacate(id, fromTileX, fromTileY);279
position.tileX = next.x;280
position.tileY = next.y;281
movement.path.shift();282
this.#occupy(id, position.tileX, position.tileY);283
this.#ensureVisibleChunks(position.tileX, position.tileY);284
const character = this.ecs.get(id, "character");285
events.push({286
type: "entity-move",287
entityId: id,288
characterId: character?.characterId,289
fromTileX,290
fromTileY,291
tileX: position.tileX,292
tileY: position.tileY,293
gait: movement.gait294
});295
}296
return events;297
}298
299
#walkableFor (entityId, tileX, tileY)300
{301
if (!this.isEnterable(tileX, tileY))302
{ return false; }303
const occupant = this.#occupied(tileX, tileY);304
return !occupant || occupant === entityId;305
}306
307
#ensureVisibleChunks (tileX, tileY)308
{309
for (const coord of visibleChunkCoords(tileToChunk(tileX), tileToChunk(tileY), VISIBLE_CHUNK_RADIUS))310
{ this.#ensureChunk(coord.chunkX, coord.chunkY); }311
}312
313
#ensureChunk (chunkX, chunkY)314
{315
const key = chunkKey(chunkX, chunkY);316
if (this.chunks.has(key))317
{ return this.chunks.get(key); }318
319
const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);320
const data = row321
? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)322
: createEmptyChunkData(this.settings.defaultGroundTypeId);323
this.chunks.set(key, data);324
return data;325
}326
327
#chunkSnapshot (chunkX, chunkY)328
{329
const data = this.#ensureChunk(chunkX, chunkY);330
const entities = [];331
for (const entity of this.ecs.query("position", "appearance"))332
{333
if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)334
{ continue; }335
const movement = this.ecs.get(entity.id, "movement");336
const character = this.ecs.get(entity.id, "character");337
entities.push({338
entityId: entity.id,339
characterId: character?.characterId ?? null,340
tileX: entity.position.tileX,341
tileY: entity.position.tileY,342
gait: movement?.gait ?? GAIT.walk,343
sex: entity.appearance.sex,344
firstName: entity.appearance.firstName,345
lastName: entity.appearance.lastName346
});347
}348
return {349
chunkX,350
chunkY,351
open: data.open,352
grounds: data.grounds,353
blocks: data.blocks,354
light: data.light,355
entities356
};357
}358
359
#occupy (entityId, tileX, tileY)360
{361
this.occupancy.set(tileKey(tileX, tileY), entityId);362
}363
364
#vacate (entityId, tileX, tileY)365
{366
const key = tileKey(tileX, tileY);367
if (this.occupancy.get(key) === entityId)368
{ this.occupancy.delete(key); }369
}370
371
#occupied (tileX, tileY)372
{373
return this.occupancy.get(tileKey(tileX, tileY)) ?? null;374
}375
}