-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathworker.ts
More file actions
executable file
·395 lines (344 loc) · 11.2 KB
/
Copy pathworker.ts
File metadata and controls
executable file
·395 lines (344 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/// <reference path='./types.d.ts' />
/// <reference path='./emscripten.d.ts' />
/// Methods exported via our Makefile.
declare type FSType = typeof FS;
interface ModuleExports {
callMain: (args?: string[]) => void;
FS: FSType,
IDBFS: Emscripten.FileSystemType,
}
// Our module creation function, from Makefile.emscripten.
declare function createAngbandModule(defaults: any): Promise<ModuleExports>;
namespace angband {
interface KeyEvent {
readonly key: string;
readonly code: number;
readonly modifiers: number;
}
// A special "wake up" event which is ignored on the C side.
const WAKE_UP_EVENT: KeyEvent = {
key: "",
code: -1,
modifiers: 0,
};
// A class which gets called from C source.
export class ThreadWorker {
// List of queued events.
eventQueue: KeyEvent[] = [];
// Promise resolved when a new event is received.
eventPromise: Promise<boolean>;
// Callback to resolve the promise.
eventPromiseCallback: (val: boolean) => void;
// Enqueued render events, to be sent in flushDrawing().
enqueuedRenderEvents: RenderEvent[] = [];
// Emscripten gets salty if we have multiple fsyncs going at once.
fsyncRequested: boolean = false;
fsyncInFlight: boolean = false;
// Graphics mode, or 0 for ASCII.
public desiredGraphicsMode: number = 0;
// Whether FS initialization has been performed.
fsInitialized: boolean = false;
// If set, activate the borg (and clear this flag) on next check.
activateBorg: boolean = false;
// Whee!
public turbo: boolean = false;
// The module object.
// This is set once the module is loaded.
public module: ModuleExports | undefined = undefined;
// \return whether we have at least one event.
hasEvent(): boolean { return this.eventQueue.length > 0; }
constructor(private worker: Worker) {
this.eventPromiseCallback = (_b) => { }; // satisfy the compiler that this is assigned.
this.eventPromise = new Promise((resolve) => {
this.eventPromiseCallback = resolve;
});
}
// Post a message to our renderer.
postMessage(msg: RenderEvent) {
this.worker.postMessage(msg);
}
// Post an error message to our renderer.
public reportError(text: string): void {
const msg: ERROR_MSG = {
name: "ERROR",
text,
};
this.postMessage(msg);
}
// Post a key event to our queue.
postKeyEvent(evt: KeyEvent) {
this.eventQueue.push(evt);
let cb = this.eventPromiseCallback;
this.eventPromise = new Promise((resolve) => {
this.eventPromiseCallback = resolve;
});
cb(this.hasEvent());
}
// Called when we receive an event.
gotEvent(evt: KEY_EVENT_MSG) {
this.postKeyEvent(<KeyEvent>{
key: evt.key,
code: evt.code,
modifiers: evt.modifiers,
});
}
// Update the desired graphics mode.
setGraphicsMode(mode: number) {
if (mode !== this.desiredGraphicsMode) {
this.desiredGraphicsMode = mode;
this.postKeyEvent(WAKE_UP_EVENT);
}
}
setActivateBorg(_msg: ACTIVATE_BORG_MSG) {
this.activateBorg = true;
this.postKeyEvent(WAKE_UP_EVENT);
}
getSavefileContents(_msg: GET_SAVEFILE_CONTENTS_MSG) {
// We could go through C but it is easier to just use the FS API.
// Here we hard-code the Angband savefile name.
let contents: ArrayBuffer | undefined;
try {
let data = this.fs().readFile("/lib/save/PLAYER");
contents = data.buffer.slice(data.byteOffset, data.byteLength + data.byteOffset);
} catch (_err) {
// e.g. file not found
contents = undefined;
}
const msg: GOT_SAVEFILE_MSG = {
name: "GOT_SAVEFILE",
contents,
};
this.postMessage(msg);
}
// Incoming message handler.
public onMessage = (msg: MessageEvent) => {
let evt = msg.data as WorkerEvent;
switch (evt.name) {
case 'KEY_EVENT':
this.gotEvent(evt as KEY_EVENT_MSG);
break;
case 'SET_TURBO':
this.turbo = (evt as SET_TURBO_MSG).value;
break;
case 'SET_GRAPHICS':
this.setGraphicsMode((evt as SET_GRAPHICS_MSG).mode);
break;
case 'ACTIVATE_BORG':
this.setActivateBorg(evt as ACTIVATE_BORG_MSG);
break;
case 'GET_SAVEFILE_CONTENTS':
this.getSavefileContents(evt as GET_SAVEFILE_CONTENTS_MSG);
break;
default:
this.reportError("Unknown event: " + JSON.stringify(evt));
break;
}
}
// Report status in our Emscripten module.
public moduleSetStatus(text: string) {
const msg: STATUS_MSG = {
name: "STATUS",
text,
};
this.postMessage(msg);
}
// Reflect anything printed to stdout.
public modulePrint(text: string) {
const msg: PRINT_MSG = {
name: "PRINT",
text,
stderr: false,
};
this.postMessage(msg);
}
public modulePrintErr(text: string) {
const msg: PRINT_MSG = {
name: "PRINT",
text,
stderr: true,
};
this.postMessage(msg);
}
// Report run dependencies.
public getModuleDependencyMonitor(): (a: number) => void {
let totalDependencies = 0;
return (left: number) => {
if (totalDependencies < left) totalDependencies = left;
this.moduleSetStatus(left ? 'Preparing... (' + (totalDependencies - left) + '/' + totalDependencies + ')' : 'All downloads complete.');
};
}
// \return our filesystem, asserting that we have one.
fs(): FSType {
if (this.module === undefined) throw new Error("No module set");
return this.module.FS;
}
/** The following functions are called from emscripten **/
// Called from C to perform any initial setup.
public initializeFilesystem() {
if (this.fsInitialized) return;
if (this.module === undefined) throw new Error("Module not set");
this.fsInitialized = true;
this.fs().mkdir("/lib/save");
this.fs().mount(this.module.IDBFS, {}, "/lib/save");
this.fsync(true /* populate */);
}
// Called to trigger an syncfs().
public fsync(populate: boolean | undefined) {
if (this.fsyncInFlight) {
this.fsyncRequested = true;
return;
}
// Collapse undefined to false.
this.fsyncRequested = false;
this.fsyncInFlight = true;
this.fs().syncfs(populate || false, (err) => {
if (err) ANGBAND.reportError(JSON.stringify(err));
// fsync is complete. Perhaps run another one.
this.fsyncInFlight = false;
if (this.fsyncRequested) {
setTimeout(() => {
if (this.fsyncRequested && !this.fsyncInFlight) this.fsync(false);
}, 0);
}
});
}
// Called when quitting from C.
// Emscripten is salty about calling main again.
// We just drop our entire WebWorker and reincarnate.
public quitWithGreatForce() {
const msg: RESTART_MSG = {
name: "RESTART",
};
this.postMessage(msg);
this.worker.terminate();
}
// Set a cell at (row, col) to the given character code, with the given color.
public setCell(row: number, col: number, charCode: number, rgb: number) {
const msg: SET_CELL_MSG = {
name: "SET_CELL",
row,
col,
charCode,
rgb,
};
this.enqueuedRenderEvents.push(msg);
}
// Draw a picture in a cell. The 'mode' is an index into the "graphics.txt" document.
public setCellPict(row: number, col: number, mode: number, pictRow: number, pictCol: number, terrRow: number, terrCol: number) {
const msg: SET_CELL_PICT_MSG = {
name: "SET_CELL_PICT",
row,
col,
mode,
pictRow,
pictCol,
terrRow,
terrCol,
};
this.enqueuedRenderEvents.push(msg);
}
// Wipe N cells at (row, column).
public wipeCells(row: number, col: number, count: number) {
if (count <= 0) return;
const msg: WIPE_CELLS_MSG = {
name: "WIPE_CELLS",
row,
col,
count,
};
this.enqueuedRenderEvents.push(msg);
}
// Clear the entire screen.
public clearScreen() {
const msg: CLEAR_SCREEN_MSG = {
name: "CLEAR_SCREEN"
};
this.enqueuedRenderEvents.push(msg);
}
// Flush all drawing to the screen. Note this can affect frame rates.
public flushDrawing() {
const flush: FLUSH_DRAWING_MSG = {
name: "FLUSH_DRAWING"
};
this.enqueuedRenderEvents.push(flush);
const batch: BATCH_RENDER_MSG = {
name: "BATCH_RENDER",
events: this.enqueuedRenderEvents,
};
this.enqueuedRenderEvents = [];
this.postMessage(batch);
}
// Move the cursor to a cell.
public setCursor(row: number, col: number) {
const msg: SET_CURSOR_MSG = {
name: "SET_CURSOR",
row,
col,
};
this.enqueuedRenderEvents.push(msg);
}
// Wait for events, optionally blocking.
public gatherEvent(block: boolean): Promise<boolean> {
if (this.hasEvent()) {
// Already have one.
//console.log("Already had event");
return new Promise((resolve) => resolve(true));
} else if (block) {
// Wait until we get the next event.
//console.log("Waiting for event");
return this.eventPromise;
} else {
// Pump the event loop and then see.
//console.log("Briefly checking for event");
return new Promise((resolve) => {
setTimeout(() => resolve(this.hasEvent()), 0)
});
}
}
// \return the key code for the current event.
public eventKeyCode(): number {
return this.eventQueue[0].code;
}
// \return the event modifiers for the current event.
public eventModifiers(): number {
return this.eventQueue[0].modifiers;
}
// Remove the current event.
public popEvent() {
let evt = this.eventQueue.shift();
if (evt === undefined) throw new Error("No events");
}
// \return if we should activate the borg, clearing the flag.
public checkActivateBorg() {
let res = this.activateBorg;
this.activateBorg = false;
return res;
}
}
// Hack: we rename angband-gen.data to angband-gen.data.bmp so github pages will gzip it.
export function locateFile(path: string, directory: string) {
if (path === 'angband-gen.data') path += '.bmp';
return directory + path;
}
}
var ANGBAND: angband.ThreadWorker = new angband.ThreadWorker(self as unknown as Worker);
// JS has a global worker onmessage hook.
onmessage = ANGBAND.onMessage.bind(ANGBAND);
try {
importScripts('angband-gen.js');
// Set up our Module object for emscripten.
var moduleDefaults = {
setStatus: ANGBAND.moduleSetStatus.bind(ANGBAND),
monitorRunDependencies: ANGBAND.getModuleDependencyMonitor(),
print: ANGBAND.modulePrint.bind(ANGBAND),
printErr: ANGBAND.modulePrintErr.bind(ANGBAND),
locateFile: angband.locateFile,
noInitialRun: true,
};
createAngbandModule(moduleDefaults).then((module: ModuleExports) => {
ANGBAND.module = module;
module.callMain();
});
} catch (error) {
ANGBAND.reportError(error.message);
}