@muhammedaksam/opentui-doom 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Save Game Manager for OpenTUI-DOOM
3
+ *
4
+ * Handles persistence of DOOM save games to ~/.opentui-doom/
5
+ * DOOM uses 6 save slots (0-5) with files named doomsav{N}.dsg
6
+ */
7
+
8
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync } from "fs";
9
+ import { join } from "path";
10
+ import { homedir } from "os";
11
+ import { debugLog } from "./debug";
12
+
13
+ // Save game directory path
14
+ const SAVE_DIR = join(homedir(), ".opentui-doom");
15
+
16
+ // DOOM save file format: doomsav{0-5}.dsg
17
+ const SAVE_FILE_PATTERN = /^doomsav([0-5])\.dsg$/;
18
+
19
+ /**
20
+ * Ensure the save directory exists
21
+ */
22
+ export function ensureSaveDir(): void {
23
+ if (!existsSync(SAVE_DIR)) {
24
+ mkdirSync(SAVE_DIR, { recursive: true });
25
+ debugLog("Saves", `Created save directory: ${SAVE_DIR}`);
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Get the save game directory path
31
+ */
32
+ export function getSaveGameDir(): string {
33
+ ensureSaveDir();
34
+ return SAVE_DIR;
35
+ }
36
+
37
+ /**
38
+ * Get the path to a save file for a given slot (0-5)
39
+ */
40
+ export function getSaveFilePath(slot: number): string {
41
+ if (slot < 0 || slot > 5) {
42
+ throw new Error(`Invalid save slot: ${slot}. Must be 0-5.`);
43
+ }
44
+ return join(SAVE_DIR, `doomsav${slot}.dsg`);
45
+ }
46
+
47
+ /**
48
+ * Load all existing save games from disk
49
+ * Returns a Map of slot number to file contents (Uint8Array)
50
+ */
51
+ export function loadExistingSaves(): Map<number, Uint8Array> {
52
+ ensureSaveDir();
53
+ const saves = new Map<number, Uint8Array>();
54
+
55
+ try {
56
+ const files = readdirSync(SAVE_DIR);
57
+ for (const file of files) {
58
+ const match = file.match(SAVE_FILE_PATTERN);
59
+ if (match && match[1]) {
60
+ const slot = parseInt(match[1], 10);
61
+ const filePath = join(SAVE_DIR, file);
62
+ try {
63
+ const data = readFileSync(filePath);
64
+ saves.set(slot, new Uint8Array(data));
65
+ debugLog("Saves", `Loaded save slot ${slot}: ${data.length} bytes`);
66
+ } catch (e) {
67
+ debugLog("Saves", `Failed to read save file ${filePath}: ${e}`);
68
+ }
69
+ }
70
+ }
71
+ } catch (e) {
72
+ debugLog("Saves", `Failed to list save directory: ${e}`);
73
+ }
74
+
75
+ debugLog("Saves", `Loaded ${saves.size} existing saves`);
76
+ return saves;
77
+ }
78
+
79
+ /**
80
+ * Write a save game to disk
81
+ */
82
+ export function writeSave(slot: number, data: Uint8Array): boolean {
83
+ ensureSaveDir();
84
+ const filePath = getSaveFilePath(slot);
85
+
86
+ try {
87
+ writeFileSync(filePath, data);
88
+ debugLog("Saves", `Wrote save slot ${slot}: ${data.length} bytes to ${filePath}`);
89
+ return true;
90
+ } catch (e) {
91
+ debugLog("Saves", `Failed to write save slot ${slot}: ${e}`);
92
+ return false;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Check if a save exists for a given slot
98
+ */
99
+ export function saveExists(slot: number): boolean {
100
+ const filePath = getSaveFilePath(slot);
101
+ return existsSync(filePath);
102
+ }
103
+
104
+ /**
105
+ * Read a save game from disk
106
+ */
107
+ export function readSave(slot: number): Uint8Array | null {
108
+ const filePath = getSaveFilePath(slot);
109
+
110
+ if (!existsSync(filePath)) {
111
+ return null;
112
+ }
113
+
114
+ try {
115
+ const data = readFileSync(filePath);
116
+ return new Uint8Array(data);
117
+ } catch (e) {
118
+ debugLog("Saves", `Failed to read save slot ${slot}: ${e}`);
119
+ return null;
120
+ }
121
+ }
package/src/index.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  import { DoomEngine, DOOM_WIDTH, DOOM_HEIGHT } from "./doom-engine";
19
19
  import { createDoomInputHandler, getControlsHelp } from "./doom-input";
20
20
  import { shutdownAudio } from "./doom-audio";
21
+ import { debugLog } from "./debug";
21
22
  import { parseArgs } from "util";
22
23
 
23
24
  // Parse command line arguments
@@ -60,12 +61,42 @@ const renderer = await createCliRenderer({
60
61
 
61
62
  // Handle graceful shutdown
62
63
  const cleanup = (signal?: string) => {
64
+ debugLog('Exit', `cleanup called with signal: ${signal}`);
65
+
66
+ // Set flag to stop the game loop FIRST - this is critical
67
+ isExiting = true;
68
+ debugLog('Exit', 'isExiting set to true');
69
+
70
+ // Sync saves before exiting
71
+ if (doomEngine) {
72
+ try {
73
+ doomEngine.syncSaves();
74
+ debugLog('Exit', 'saves synced to disk');
75
+ } catch (e) {
76
+ debugLog('Exit', `failed to sync saves: ${e}`);
77
+ }
78
+ }
79
+
80
+ // Clear the frame callback to stop DOOM from ticking
81
+ try {
82
+ renderer.setFrameCallback(null as any);
83
+ debugLog('Exit', 'frame callback cleared');
84
+ } catch (e) {
85
+ debugLog('Exit', `failed to clear frame callback: ${e}`);
86
+ }
87
+
63
88
  shutdownAudio();
89
+ debugLog('Exit', 'shutdownAudio completed');
90
+
64
91
  try {
65
92
  renderer.stop();
93
+ debugLog('Exit', 'renderer.stop completed');
66
94
  } catch (e) {
67
- // Ignore error if renderer already stopped
95
+ debugLog('Exit', `renderer.stop error: ${e}`);
68
96
  }
97
+
98
+ // Exit the process
99
+ debugLog('Exit', 'calling process.exit(0)');
69
100
  process.exit(0);
70
101
  };
71
102
 
@@ -96,12 +127,18 @@ container.add(loadingText);
96
127
  // Try to initialize DOOM engine
97
128
  let doomEngine: DoomEngine | null = null;
98
129
  let framebufferRenderable: FrameBufferRenderable | null = null;
130
+ let isExiting = false; // Flag to stop the game loop when exiting
131
+ let lastSaveSyncTime = 0; // Track when we last synced saves
132
+ const SAVE_SYNC_INTERVAL = 5000; // Sync saves every 5 seconds
99
133
 
100
134
  async function initDoom() {
101
135
  try {
102
136
  loadingText.content = `Loading DOOM from: ${values.wad}`;
103
137
 
104
- doomEngine = new DoomEngine(values.wad!);
138
+ doomEngine = new DoomEngine({
139
+ wadPath: values.wad!,
140
+ onQuit: cleanup,
141
+ });
105
142
  await doomEngine.init();
106
143
 
107
144
  // Remove loading text
@@ -172,10 +209,20 @@ async function initDoom() {
172
209
  }
173
210
 
174
211
  async function gameLoop(deltaMs: number) {
212
+ // Bail out immediately if we're exiting
213
+ if (isExiting) return;
214
+
175
215
  if (!doomEngine || !framebufferRenderable) return;
176
216
 
177
217
  // Run DOOM tick
178
218
  doomEngine.tick();
219
+
220
+ // Periodic save sync (every 5 seconds)
221
+ const now = Date.now();
222
+ if (now - lastSaveSyncTime > SAVE_SYNC_INTERVAL) {
223
+ doomEngine.syncSaves();
224
+ lastSaveSyncTime = now;
225
+ }
179
226
 
180
227
  // Get framebuffer from DOOM
181
228
  const pixels = doomEngine.getFrameBuffer();