| 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 { FriendService } from "./friends/service.js"; |
| 7 | import { StubAuth } from "./auth/stub.js"; |
| 8 | import { Simulation } from "./simulation/simulation.js"; |
| 9 | import { createHttpServer, repoRootFrom } from "./gateway/http.js"; |
| 10 | import { attachGateway } from "./gateway/websocket.js"; |
| 11 | |
| 12 | const rootDir = repoRootFrom(import.meta.url); |
| 13 | const dataDir = join(rootDir, "server", "data"); |
| 14 | const port = Number(process.env.PORT ?? 8080); |
| 15 | |
| 16 | const worldDb = new WorldDatabase(join(dataDir, "world.sqlite")); |
| 17 | const stateDb = new StateDatabase(join(dataDir, "state.sqlite")); |
| 18 | const editor = new EditorService(worldDb); |
| 19 | const characters = new CharacterService(stateDb, console); |
| 20 | const friends = new FriendService(stateDb); |
| 21 | const simulation = new Simulation(worldDb, stateDb); |
| 22 | const auth = new StubAuth(); |
| 23 | const httpServer = createHttpServer(rootDir); |
| 24 | const gateway = attachGateway({ httpServer, auth, stateDb, characters, friends, editor, simulation }); |
| 25 | |
| 26 | let tickTimer = null; |
| 27 | let shuttingDown = false; |
| 28 | |
| 29 | function scheduleTick () |
| 30 | { |
| 31 | if (shuttingDown) |
| 32 | { return; } |
| 33 | const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20))); |
| 34 | tickTimer = setTimeout(() => |
| 35 | { |
| 36 | characters.processDueDeletions(Date.now(), (characterId) => simulation.despawnCharacter(characterId)); |
| 37 | const result = simulation.step(); |
| 38 | gateway.onTickResult(result); |
| 39 | scheduleTick(); |
| 40 | }, tickMs); |
| 41 | } |
| 42 | scheduleTick(); |
| 43 | |
| 44 | httpServer.listen(port, () => |
| 45 | { |
| 46 | console.log(`Tile MMO listening on http://localhost:${port}`); |
| 47 | console.log(`World editor: http://localhost:${port}/editor`); |
| 48 | }); |
| 49 | |
| 50 | async function shutdown (signal) |
| 51 | { |
| 52 | if (shuttingDown) |
| 53 | { return; } |
| 54 | shuttingDown = true; |
| 55 | console.log(`Shutting down (${signal})…`); |
| 56 | clearTimeout(tickTimer); |
| 57 | try |
| 58 | { await gateway.shutdown(); } |
| 59 | catch (error) |
| 60 | { console.error("Graceful shutdown error:", error); } |
| 61 | worldDb.close(); |
| 62 | stateDb.close(); |
| 63 | await new Promise((resolve) => httpServer.close(resolve)); |
| 64 | process.exit(0); |
| 65 | } |
| 66 | |
| 67 | process.on("SIGINT", () => { void shutdown("SIGINT"); }); |
| 68 | process.on("SIGTERM", () => { void shutdown("SIGTERM"); }); |