BlueGit

timfa questward

Add the HTTP and WebSocket gateway for play and editor clients.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-08-24 · 2 months ago

Hash
2833c721e4b6c570076f4981317ad803a61b6be4
Parent
c49e9fa4
4 files changed +439 −3
docs/FEATURES.md +3 −3
@@ -81,9 +81,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
81 81
82 82 ## WebSocket gateway
83 83
84 **Status:** not implemented
85 **Spec:** Connections belong to a gateway. Clients send intentions. JSON messages for the first version.
86 **Code:** —
84 **Status:** full
85 **Spec:** JSON WebSocket on `/ws`, HTTP static files for the client. Connections belong to the gateway. Clients send intentions that are queued onto the simulation tick. Editor messages are admin-only.
86 **Code:** `server/src/gateway/websocket.js`, `server/src/gateway/http.js`, `server/src/index.js`
87 87
88 88 ## Stub authentication
89 89
@@ -81,9 +81,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
81
81
82## WebSocket gateway
82## WebSocket gateway
83
83
84**Status:** not implemented
84**Status:** full
85**Spec:** Connections belong to a gateway. Clients send intentions. JSON messages for the first version.
85**Spec:** JSON WebSocket on `/ws`, HTTP static files for the client. Connections belong to the gateway. Clients send intentions that are queued onto the simulation tick. Editor messages are admin-only.
86**Code:** —
86**Code:** `server/src/gateway/websocket.js`, `server/src/gateway/http.js`, `server/src/index.js`
87
87
88## Stub authentication
88## Stub authentication
89
89
server/src/gateway/http.js added +76 −0
@@ -0,0 +1,76 @@
1 import { createServer } from "node:http";
2 import { createReadStream, existsSync, statSync } from "node:fs";
3 import { extname, join, normalize, relative, sep } from "node:path";
4 import { fileURLToPath } from "node:url";
5
6 const MIME = {
7 ".html": "text/html; charset=utf-8",
8 ".js": "text/javascript; charset=utf-8",
9 ".css": "text/css; charset=utf-8",
10 ".png": "image/png",
11 ".json": "application/json; charset=utf-8",
12 ".svg": "image/svg+xml",
13 ".ico": "image/x-icon"
14 };
15
16 export function createHttpServer (rootDir)
17 {
18 const clientDir = join(rootDir, "client");
19 const sharedDir = join(rootDir, "shared");
20 const frameworkDir = join(clientDir, "frameworkv3", "js");
21
22 return createServer((req, res) =>
23 {
24 try
25 {
26 const url = new URL(req.url ?? "/", "http://localhost");
27 const filePath = resolvePublicPath(url.pathname, clientDir, sharedDir, frameworkDir);
28 if (!filePath)
29 {
30 res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
31 res.end("Not found");
32 return;
33 }
34 res.writeHead(200, { "content-type": MIME[extname(filePath)] ?? "application/octet-stream" });
35 createReadStream(filePath).pipe(res);
36 }
37 catch (error)
38 {
39 res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
40 res.end(error.message);
41 }
42 });
43 }
44
45 function resolvePublicPath (pathname, clientDir, sharedDir, frameworkDir)
46 {
47 if (pathname === "/" || pathname === "/index.html")
48 { return join(clientDir, "index.html"); }
49 if (pathname === "/editor" || pathname === "/editor.html")
50 { return join(clientDir, "editor.html"); }
51
52 if (pathname.startsWith("/shared/"))
53 { return safeJoin(sharedDir, pathname.slice("/shared/".length)); }
54 if (pathname.startsWith("/framework/"))
55 { return safeJoin(frameworkDir, pathname.slice("/framework/".length)); }
56 if (pathname.startsWith("/src/") || pathname.startsWith("/assets/") || pathname.startsWith("/ui/"))
57 { return safeJoin(clientDir, pathname.slice(1)); }
58
59 return null;
60 }
61
62 function safeJoin (root, relativePath)
63 {
64 const resolved = normalize(join(root, relativePath));
65 const rel = relative(root, resolved);
66 if (rel.startsWith("..") || rel.startsWith(sep) || rel.includes(`..${sep}`))
67 { return null; }
68 if (!existsSync(resolved) || !statSync(resolved).isFile())
69 { return null; }
70 return resolved;
71 }
72
73 export function repoRootFrom (url)
74 {
75 return join(fileURLToPath(new URL(".", url)), "../..");
76 }
@@ -0,0 +1,76 @@
1import { createServer } from "node:http";
2import { createReadStream, existsSync, statSync } from "node:fs";
3import { extname, join, normalize, relative, sep } from "node:path";
4import { fileURLToPath } from "node:url";
5
6const MIME = {
7 ".html": "text/html; charset=utf-8",
8 ".js": "text/javascript; charset=utf-8",
9 ".css": "text/css; charset=utf-8",
10 ".png": "image/png",
11 ".json": "application/json; charset=utf-8",
12 ".svg": "image/svg+xml",
13 ".ico": "image/x-icon"
14};
15
16export function createHttpServer (rootDir)
17{
18 const clientDir = join(rootDir, "client");
19 const sharedDir = join(rootDir, "shared");
20 const frameworkDir = join(clientDir, "frameworkv3", "js");
21
22 return createServer((req, res) =>
23 {
24 try
25 {
26 const url = new URL(req.url ?? "/", "http://localhost");
27 const filePath = resolvePublicPath(url.pathname, clientDir, sharedDir, frameworkDir);
28 if (!filePath)
29 {
30 res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
31 res.end("Not found");
32 return;
33 }
34 res.writeHead(200, { "content-type": MIME[extname(filePath)] ?? "application/octet-stream" });
35 createReadStream(filePath).pipe(res);
36 }
37 catch (error)
38 {
39 res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
40 res.end(error.message);
41 }
42 });
43}
44
45function resolvePublicPath (pathname, clientDir, sharedDir, frameworkDir)
46{
47 if (pathname === "/" || pathname === "/index.html")
48 { return join(clientDir, "index.html"); }
49 if (pathname === "/editor" || pathname === "/editor.html")
50 { return join(clientDir, "editor.html"); }
51
52 if (pathname.startsWith("/shared/"))
53 { return safeJoin(sharedDir, pathname.slice("/shared/".length)); }
54 if (pathname.startsWith("/framework/"))
55 { return safeJoin(frameworkDir, pathname.slice("/framework/".length)); }
56 if (pathname.startsWith("/src/") || pathname.startsWith("/assets/") || pathname.startsWith("/ui/"))
57 { return safeJoin(clientDir, pathname.slice(1)); }
58
59 return null;
60}
61
62function safeJoin (root, relativePath)
63{
64 const resolved = normalize(join(root, relativePath));
65 const rel = relative(root, resolved);
66 if (rel.startsWith("..") || rel.startsWith(sep) || rel.includes(`..${sep}`))
67 { return null; }
68 if (!existsSync(resolved) || !statSync(resolved).isFile())
69 { return null; }
70 return resolved;
71}
72
73export function repoRootFrom (url)
74{
75 return join(fileURLToPath(new URL(".", url)), "../..");
76}
server/src/gateway/websocket.js added +307 −0
@@ -0,0 +1,307 @@
1 import { WebSocketServer } from "ws";
2 import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3 import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4 import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5
6 let nextSessionId = 1;
7
8 export function attachGateway ({ httpServer, auth, stateDb, characters, editor, simulation })
9 {
10 const wss = new WebSocketServer({ server: httpServer, path: "/ws" });
11 const sessions = new Map();
12
13 wss.on("connection", (socket) =>
14 {
15 const identity = auth.claimIdentity();
16 const account = stateDb.ensureAccount(identity.authSubject, identity.isAdmin, identity.email);
17 const session = {
18 id: nextSessionId++,
19 socket,
20 account,
21 authSubject: identity.authSubject,
22 characterId: null,
23 entityId: null,
24 subscribed: new Set()
25 };
26 auth.register(session);
27 sessions.set(session.id, session);
28 send(session, {
29 type: MessageType.session,
30 accountId: account.account_id,
31 authSubject: account.auth_subject,
32 isAdmin: !!account.is_admin,
33 characters: characters.list(account.account_id)
34 });
35
36 socket.on("message", (raw) =>
37 {
38 let message;
39 try
40 { message = JSON.parse(String(raw)); }
41 catch
42 {
43 send(session, { type: MessageType.error, message: "Invalid JSON." });
44 return;
45 }
46 try
47 { handleMessage(session, message); }
48 catch (error)
49 {
50 send(session, {
51 type: MessageType.error,
52 message: error.userFacing ? error.message : "Request failed."
53 });
54 }
55 });
56
57 socket.on("close", () =>
58 {
59 leaveWorld(session);
60 auth.release(session);
61 sessions.delete(session.id);
62 });
63 });
64
65 function handleMessage (session, message)
66 {
67 switch (message.type)
68 {
69 case MessageType.createCharacter:
70 characters.create(session.account, message.firstName, message.lastName, message.sex);
71 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
72 break;
73 case MessageType.selectCharacter:
74 enterWorld(session, message.characterId);
75 break;
76 case MessageType.scheduleDeleteCharacter:
77 characters.scheduleDelete(session.account, message.characterId, simulation.settings.characterDeletionDelayMs);
78 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
79 break;
80 case MessageType.cancelDeleteCharacter:
81 characters.cancelDelete(session.account, message.characterId);
82 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
83 break;
84 case MessageType.leaveWorld:
85 leaveWorld(session);
86 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
87 break;
88 case MessageType.moveTo:
89 requirePlaying(session);
90 simulation.enqueue(session.id, {
91 type: "move-to",
92 characterId: session.characterId,
93 tileX: message.tileX | 0,
94 tileY: message.tileY | 0
95 });
96 break;
97 case MessageType.setGait:
98 requirePlaying(session);
99 simulation.enqueue(session.id, {
100 type: "set-gait",
101 characterId: session.characterId,
102 gait: message.gait === GAIT.run ? GAIT.run : GAIT.walk
103 });
104 break;
105 case MessageType.editorLoadChunk:
106 requireAdmin(session);
107 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
108 break;
109 case MessageType.editorSaveChunk:
110 requireAdmin(session);
111 send(session, {
112 type: MessageType.editorChunk,
113 ...editor.saveChunk(message.chunkX | 0, message.chunkY | 0, message.draft, session.authSubject)
114 });
115 break;
116 case MessageType.editorSaveSettings:
117 requireAdmin(session);
118 send(session, {
119 type: MessageType.editorChunk,
120 settingsSaved: editor.saveSettings(message.settings ?? {}, session.authSubject)
121 });
122 break;
123 case MessageType.editorApplyRevision:
124 requireAdmin(session);
125 editor.applyPendingRevision();
126 simulation.reloadWorld();
127 for (const other of sessions.values())
128 {
129 if (other.entityId)
130 { syncSubscriptions(other, true); }
131 }
132 broadcastStatus();
133 break;
134 default:
135 send(session, { type: MessageType.error, message: `Unknown message ${message.type}` });
136 }
137 }
138
139 function enterWorld (session, characterId)
140 {
141 leaveWorld(session);
142 const character = characters.getOwned(session.account.account_id, characterId);
143 if (character.deletion_scheduled_at)
144 {
145 const error = new Error("That character is marked for deletion.");
146 error.userFacing = true;
147 throw error;
148 }
149 for (const other of sessions.values())
150 {
151 if (other !== session && other.account.account_id === session.account.account_id && other.characterId)
152 {
153 const error = new Error("This account already has a character in the world.");
154 error.userFacing = true;
155 throw error;
156 }
157 }
158 session.characterId = character.character_id;
159 session.entityId = simulation.spawnCharacter(session.id, character);
160 const appearance = simulation.ecs.get(session.entityId, "appearance");
161 const position = simulation.ecs.get(session.entityId, "position");
162 const movement = simulation.ecs.get(session.entityId, "movement");
163 send(session, {
164 type: MessageType.enterWorld,
165 entityId: session.entityId,
166 characterId: session.characterId,
167 tileX: position.tileX,
168 tileY: position.tileY,
169 gait: movement.gait,
170 sex: appearance.sex,
171 firstName: appearance.firstName,
172 lastName: appearance.lastName,
173 settings: simulation.settings,
174 worldTime: simulation.worldTime()
175 });
176 syncSubscriptions(session, true);
177 }
178
179 function leaveWorld (session)
180 {
181 if (session.characterId)
182 { simulation.despawnCharacter(session.characterId); }
183 session.characterId = null;
184 session.entityId = null;
185 session.subscribed.clear();
186 }
187
188 function syncSubscriptions (session, forceSnapshots)
189 {
190 if (!session.entityId)
191 { return; }
192 const position = simulation.ecs.get(session.entityId, "position");
193 if (!position)
194 { return; }
195
196 const next = new Set(
197 visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS)
198 .map((coord) => chunkKey(coord.chunkX, coord.chunkY))
199 );
200 for (const key of session.subscribed)
201 {
202 if (!next.has(key))
203 {
204 const [chunkX, chunkY] = key.split(",").map(Number);
205 send(session, { type: MessageType.unsubscribeChunk, chunkX, chunkY });
206 }
207 }
208 const snapshots = simulation.snapshotFor(session.entityId);
209 for (const snapshot of snapshots)
210 {
211 const key = chunkKey(snapshot.chunkX, snapshot.chunkY);
212 if (forceSnapshots || !session.subscribed.has(key))
213 { send(session, { type: MessageType.chunkSnapshot, ...snapshot }); }
214 }
215 session.subscribed = next;
216 }
217
218 function requirePlaying (session)
219 {
220 if (!session.characterId)
221 {
222 const error = new Error("Select a character first.");
223 error.userFacing = true;
224 throw error;
225 }
226 }
227
228 function requireAdmin (session)
229 {
230 if (!session.account.is_admin)
231 {
232 const error = new Error("Admin only.");
233 error.userFacing = true;
234 throw error;
235 }
236 }
237
238 function broadcastStatus ()
239 {
240 const worldTime = simulation.worldTime();
241 for (const session of sessions.values())
242 {
243 if (session.entityId)
244 {
245 send(session, {
246 type: MessageType.worldStatus,
247 worldTime,
248 settings: simulation.settings,
249 activeRevisionId: simulation.activeRevisionId
250 });
251 }
252 }
253 }
254
255 function onTickResult (result)
256 {
257 for (const event of result.events)
258 {
259 if (event.type === "command-error")
260 {
261 const session = sessions.get(event.sessionId);
262 if (session)
263 { send(session, { type: MessageType.error, message: event.message }); }
264 continue;
265 }
266 if (event.type === "entity-move")
267 {
268 const fromKey = chunkKey(tileToChunk(event.fromTileX), tileToChunk(event.fromTileY));
269 const toKey = chunkKey(tileToChunk(event.tileX), tileToChunk(event.tileY));
270 for (const session of sessions.values())
271 {
272 if (!session.entityId)
273 { continue; }
274 const seesFrom = session.subscribed.has(fromKey);
275 const seesTo = session.subscribed.has(toKey);
276 if (seesTo)
277 {
278 send(session, {
279 type: MessageType.entityMove,
280 entityId: event.entityId,
281 characterId: event.characterId,
282 tileX: event.tileX,
283 tileY: event.tileY,
284 gait: event.gait
285 });
286 }
287 else if (seesFrom)
288 {
289 send(session, { type: MessageType.entityDespawn, entityId: event.entityId });
290 }
291 if (session.entityId === event.entityId)
292 { syncSubscriptions(session, false); }
293 }
294 }
295 }
296 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
297 { broadcastStatus(); }
298 }
299
300 return { sessions, onTickResult, wss };
301 }
302
303 function send (session, payload)
304 {
305 if (session.socket.readyState === 1)
306 { session.socket.send(JSON.stringify(payload)); }
307 }
@@ -0,0 +1,307 @@
1import { WebSocketServer } from "ws";
2import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5
6let nextSessionId = 1;
7
8export function attachGateway ({ httpServer, auth, stateDb, characters, editor, simulation })
9{
10 const wss = new WebSocketServer({ server: httpServer, path: "/ws" });
11 const sessions = new Map();
12
13 wss.on("connection", (socket) =>
14 {
15 const identity = auth.claimIdentity();
16 const account = stateDb.ensureAccount(identity.authSubject, identity.isAdmin, identity.email);
17 const session = {
18 id: nextSessionId++,
19 socket,
20 account,
21 authSubject: identity.authSubject,
22 characterId: null,
23 entityId: null,
24 subscribed: new Set()
25 };
26 auth.register(session);
27 sessions.set(session.id, session);
28 send(session, {
29 type: MessageType.session,
30 accountId: account.account_id,
31 authSubject: account.auth_subject,
32 isAdmin: !!account.is_admin,
33 characters: characters.list(account.account_id)
34 });
35
36 socket.on("message", (raw) =>
37 {
38 let message;
39 try
40 { message = JSON.parse(String(raw)); }
41 catch
42 {
43 send(session, { type: MessageType.error, message: "Invalid JSON." });
44 return;
45 }
46 try
47 { handleMessage(session, message); }
48 catch (error)
49 {
50 send(session, {
51 type: MessageType.error,
52 message: error.userFacing ? error.message : "Request failed."
53 });
54 }
55 });
56
57 socket.on("close", () =>
58 {
59 leaveWorld(session);
60 auth.release(session);
61 sessions.delete(session.id);
62 });
63 });
64
65 function handleMessage (session, message)
66 {
67 switch (message.type)
68 {
69 case MessageType.createCharacter:
70 characters.create(session.account, message.firstName, message.lastName, message.sex);
71 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
72 break;
73 case MessageType.selectCharacter:
74 enterWorld(session, message.characterId);
75 break;
76 case MessageType.scheduleDeleteCharacter:
77 characters.scheduleDelete(session.account, message.characterId, simulation.settings.characterDeletionDelayMs);
78 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
79 break;
80 case MessageType.cancelDeleteCharacter:
81 characters.cancelDelete(session.account, message.characterId);
82 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
83 break;
84 case MessageType.leaveWorld:
85 leaveWorld(session);
86 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
87 break;
88 case MessageType.moveTo:
89 requirePlaying(session);
90 simulation.enqueue(session.id, {
91 type: "move-to",
92 characterId: session.characterId,
93 tileX: message.tileX | 0,
94 tileY: message.tileY | 0
95 });
96 break;
97 case MessageType.setGait:
98 requirePlaying(session);
99 simulation.enqueue(session.id, {
100 type: "set-gait",
101 characterId: session.characterId,
102 gait: message.gait === GAIT.run ? GAIT.run : GAIT.walk
103 });
104 break;
105 case MessageType.editorLoadChunk:
106 requireAdmin(session);
107 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
108 break;
109 case MessageType.editorSaveChunk:
110 requireAdmin(session);
111 send(session, {
112 type: MessageType.editorChunk,
113 ...editor.saveChunk(message.chunkX | 0, message.chunkY | 0, message.draft, session.authSubject)
114 });
115 break;
116 case MessageType.editorSaveSettings:
117 requireAdmin(session);
118 send(session, {
119 type: MessageType.editorChunk,
120 settingsSaved: editor.saveSettings(message.settings ?? {}, session.authSubject)
121 });
122 break;
123 case MessageType.editorApplyRevision:
124 requireAdmin(session);
125 editor.applyPendingRevision();
126 simulation.reloadWorld();
127 for (const other of sessions.values())
128 {
129 if (other.entityId)
130 { syncSubscriptions(other, true); }
131 }
132 broadcastStatus();
133 break;
134 default:
135 send(session, { type: MessageType.error, message: `Unknown message ${message.type}` });
136 }
137 }
138
139 function enterWorld (session, characterId)
140 {
141 leaveWorld(session);
142 const character = characters.getOwned(session.account.account_id, characterId);
143 if (character.deletion_scheduled_at)
144 {
145 const error = new Error("That character is marked for deletion.");
146 error.userFacing = true;
147 throw error;
148 }
149 for (const other of sessions.values())
150 {
151 if (other !== session && other.account.account_id === session.account.account_id && other.characterId)
152 {
153 const error = new Error("This account already has a character in the world.");
154 error.userFacing = true;
155 throw error;
156 }
157 }
158 session.characterId = character.character_id;
159 session.entityId = simulation.spawnCharacter(session.id, character);
160 const appearance = simulation.ecs.get(session.entityId, "appearance");
161 const position = simulation.ecs.get(session.entityId, "position");
162 const movement = simulation.ecs.get(session.entityId, "movement");
163 send(session, {
164 type: MessageType.enterWorld,
165 entityId: session.entityId,
166 characterId: session.characterId,
167 tileX: position.tileX,
168 tileY: position.tileY,
169 gait: movement.gait,
170 sex: appearance.sex,
171 firstName: appearance.firstName,
172 lastName: appearance.lastName,
173 settings: simulation.settings,
174 worldTime: simulation.worldTime()
175 });
176 syncSubscriptions(session, true);
177 }
178
179 function leaveWorld (session)
180 {
181 if (session.characterId)
182 { simulation.despawnCharacter(session.characterId); }
183 session.characterId = null;
184 session.entityId = null;
185 session.subscribed.clear();
186 }
187
188 function syncSubscriptions (session, forceSnapshots)
189 {
190 if (!session.entityId)
191 { return; }
192 const position = simulation.ecs.get(session.entityId, "position");
193 if (!position)
194 { return; }
195
196 const next = new Set(
197 visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS)
198 .map((coord) => chunkKey(coord.chunkX, coord.chunkY))
199 );
200 for (const key of session.subscribed)
201 {
202 if (!next.has(key))
203 {
204 const [chunkX, chunkY] = key.split(",").map(Number);
205 send(session, { type: MessageType.unsubscribeChunk, chunkX, chunkY });
206 }
207 }
208 const snapshots = simulation.snapshotFor(session.entityId);
209 for (const snapshot of snapshots)
210 {
211 const key = chunkKey(snapshot.chunkX, snapshot.chunkY);
212 if (forceSnapshots || !session.subscribed.has(key))
213 { send(session, { type: MessageType.chunkSnapshot, ...snapshot }); }
214 }
215 session.subscribed = next;
216 }
217
218 function requirePlaying (session)
219 {
220 if (!session.characterId)
221 {
222 const error = new Error("Select a character first.");
223 error.userFacing = true;
224 throw error;
225 }
226 }
227
228 function requireAdmin (session)
229 {
230 if (!session.account.is_admin)
231 {
232 const error = new Error("Admin only.");
233 error.userFacing = true;
234 throw error;
235 }
236 }
237
238 function broadcastStatus ()
239 {
240 const worldTime = simulation.worldTime();
241 for (const session of sessions.values())
242 {
243 if (session.entityId)
244 {
245 send(session, {
246 type: MessageType.worldStatus,
247 worldTime,
248 settings: simulation.settings,
249 activeRevisionId: simulation.activeRevisionId
250 });
251 }
252 }
253 }
254
255 function onTickResult (result)
256 {
257 for (const event of result.events)
258 {
259 if (event.type === "command-error")
260 {
261 const session = sessions.get(event.sessionId);
262 if (session)
263 { send(session, { type: MessageType.error, message: event.message }); }
264 continue;
265 }
266 if (event.type === "entity-move")
267 {
268 const fromKey = chunkKey(tileToChunk(event.fromTileX), tileToChunk(event.fromTileY));
269 const toKey = chunkKey(tileToChunk(event.tileX), tileToChunk(event.tileY));
270 for (const session of sessions.values())
271 {
272 if (!session.entityId)
273 { continue; }
274 const seesFrom = session.subscribed.has(fromKey);
275 const seesTo = session.subscribed.has(toKey);
276 if (seesTo)
277 {
278 send(session, {
279 type: MessageType.entityMove,
280 entityId: event.entityId,
281 characterId: event.characterId,
282 tileX: event.tileX,
283 tileY: event.tileY,
284 gait: event.gait
285 });
286 }
287 else if (seesFrom)
288 {
289 send(session, { type: MessageType.entityDespawn, entityId: event.entityId });
290 }
291 if (session.entityId === event.entityId)
292 { syncSubscriptions(session, false); }
293 }
294 }
295 }
296 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
297 { broadcastStatus(); }
298 }
299
300 return { sessions, onTickResult, wss };
301}
302
303function send (session, payload)
304{
305 if (session.socket.readyState === 1)
306 { session.socket.send(JSON.stringify(payload)); }
307}
server/src/index.js added +53 −0
@@ -0,0 +1,53 @@
1 import { join } from "node:path";
2 import { WorldDatabase } from "./persistence/worldDb.js";
3 import { StateDatabase } from "./persistence/stateDb.js";
4 import { EditorService } from "./editor/service.js";
5 import { CharacterService } from "./characters/service.js";
6 import { StubAuth } from "./auth/stub.js";
7 import { Simulation } from "./simulation/simulation.js";
8 import { createHttpServer, repoRootFrom } from "./gateway/http.js";
9 import { attachGateway } from "./gateway/websocket.js";
10
11 const rootDir = repoRootFrom(import.meta.url);
12 const dataDir = join(rootDir, "server", "data");
13 const port = Number(process.env.PORT ?? 8080);
14
15 const worldDb = new WorldDatabase(join(dataDir, "world.sqlite"));
16 const stateDb = new StateDatabase(join(dataDir, "state.sqlite"));
17 const editor = new EditorService(worldDb);
18 const characters = new CharacterService(stateDb, console);
19 const simulation = new Simulation(worldDb, stateDb);
20 const auth = new StubAuth();
21 const httpServer = createHttpServer(rootDir);
22 const gateway = attachGateway({ httpServer, auth, stateDb, characters, editor, simulation });
23
24 const tickMs = Math.round(1000 / simulation.settings.simulationTickHz);
25 const tickTimer = setInterval(() =>
26 {
27 characters.processDueDeletions();
28 const result = simulation.step();
29 gateway.onTickResult(result);
30 }, tickMs);
31
32 httpServer.listen(port, () =>
33 {
34 console.log(`Tile MMO listening on http://localhost:${port}`);
35 console.log(`World editor: http://localhost:${port}/editor`);
36 });
37
38 function shutdown ()
39 {
40 clearInterval(tickTimer);
41 for (const session of gateway.sessions.values())
42 {
43 if (session.characterId)
44 { simulation.despawnCharacter(session.characterId); }
45 }
46 worldDb.close();
47 stateDb.close();
48 httpServer.close();
49 process.exit(0);
50 }
51
52 process.on("SIGINT", shutdown);
53 process.on("SIGTERM", shutdown);
@@ -0,0 +1,53 @@
1import { join } from "node:path";
2import { WorldDatabase } from "./persistence/worldDb.js";
3import { StateDatabase } from "./persistence/stateDb.js";
4import { EditorService } from "./editor/service.js";
5import { CharacterService } from "./characters/service.js";
6import { StubAuth } from "./auth/stub.js";
7import { Simulation } from "./simulation/simulation.js";
8import { createHttpServer, repoRootFrom } from "./gateway/http.js";
9import { attachGateway } from "./gateway/websocket.js";
10
11const rootDir = repoRootFrom(import.meta.url);
12const dataDir = join(rootDir, "server", "data");
13const port = Number(process.env.PORT ?? 8080);
14
15const worldDb = new WorldDatabase(join(dataDir, "world.sqlite"));
16const stateDb = new StateDatabase(join(dataDir, "state.sqlite"));
17const editor = new EditorService(worldDb);
18const characters = new CharacterService(stateDb, console);
19const simulation = new Simulation(worldDb, stateDb);
20const auth = new StubAuth();
21const httpServer = createHttpServer(rootDir);
22const gateway = attachGateway({ httpServer, auth, stateDb, characters, editor, simulation });
23
24const tickMs = Math.round(1000 / simulation.settings.simulationTickHz);
25const tickTimer = setInterval(() =>
26{
27 characters.processDueDeletions();
28 const result = simulation.step();
29 gateway.onTickResult(result);
30}, tickMs);
31
32httpServer.listen(port, () =>
33{
34 console.log(`Tile MMO listening on http://localhost:${port}`);
35 console.log(`World editor: http://localhost:${port}/editor`);
36});
37
38function shutdown ()
39{
40 clearInterval(tickTimer);
41 for (const session of gateway.sessions.values())
42 {
43 if (session.characterId)
44 { simulation.despawnCharacter(session.characterId); }
45 }
46 worldDb.close();
47 stateDb.close();
48 httpServer.close();
49 process.exit(0);
50}
51
52process.on("SIGINT", shutdown);
53process.on("SIGTERM", shutdown);