forked from matrix-org/thirdroom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GameWorker.ts
174 lines (142 loc) · 4.67 KB
/
GameWorker.ts
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
import { addEntity, createWorld } from "bitecs";
import { maxEntities, tickRate } from "./config.common";
import { InitializeGameWorkerMessage, WorkerMessageType } from "./WorkerMessage";
import { Message, registerModules, Thread } from "./module/module.common";
import gameConfig from "./config.game";
import { GameContext, World } from "./GameTypes";
const workerScope = globalThis as typeof globalThis & Worker;
const isFirefox = navigator.userAgent.toLowerCase().includes("gecko/");
async function onInitMessage({ data }: MessageEvent) {
if (typeof data !== "object") {
return;
}
const { dest, message } = data;
if (dest !== Thread.Game) {
return;
}
if (message.type === WorkerMessageType.InitializeGameWorker) {
workerScope.removeEventListener("message", onInitMessage);
onInit(message);
}
}
workerScope.addEventListener("message", onInitMessage);
async function onInit({
renderWorkerMessagePort,
mainToGameTripleBufferFlags,
renderToGameTripleBufferFlags,
gameToMainTripleBufferFlags,
gameToRenderTripleBufferFlags,
}: InitializeGameWorkerMessage) {
const renderPort = renderWorkerMessagePort || workerScope;
const world = createWorld<World>(maxEntities);
// noop entity
addEntity(world);
const ctx: GameContext = {
thread: Thread.Game,
renderToGameTripleBufferFlags,
mainToGameTripleBufferFlags,
gameToMainTripleBufferFlags,
gameToRenderTripleBufferFlags,
elapsed: performance.now(),
dt: 0,
tick: 0,
world,
systems: gameConfig.systems,
messageHandlers: new Map(),
modules: new Map(),
sendMessage: gameWorkerSendMessage,
// HACK: Figure out how to create the context such that these are initially set
resourceManager: undefined as any,
worldResource: undefined as any,
editorLoaded: false,
};
const onMessage = ({ data }: MessageEvent) => {
if (typeof data !== "object") {
return;
}
const { message, dest } = data;
if (dest !== Thread.Game) {
return;
}
const handlers = ctx.messageHandlers.get(message.type);
if (handlers) {
for (let i = 0; i < handlers.length; i++) {
handlers[i](ctx, message);
}
}
};
function gameWorkerSendMessage<M extends Message<any>>(thread: Thread, message: M, transferList: Transferable[]) {
if (thread === Thread.Main) {
workerScope.postMessage({ dest: thread, message }, transferList);
} else if (thread === Thread.Render) {
renderPort.postMessage({ dest: thread, message }, transferList);
} else if (thread === Thread.Game) {
const handlers = ctx.messageHandlers.get(message.type);
if (handlers) {
for (let i = 0; i < handlers.length; i++) {
handlers[i](ctx, message);
}
}
}
}
workerScope.addEventListener("message", onMessage);
if (renderWorkerMessagePort) {
renderWorkerMessagePort.addEventListener("message", onMessage);
}
// Sends message to main thread saying we're ready to register modules (send modules in message)
// Initially blocks until main thread tells game thread to register modules
// Register all modules
// Then wait for main thread to start this worker and we call update()
const modulePromise = registerModules(Thread.Game, ctx, gameConfig.modules);
if (renderWorkerMessagePort) {
renderWorkerMessagePort.start();
}
await modulePromise;
console.log("GameWorker initialized");
let interval: any;
const intervalGameLoop = () => {
interval = setInterval(() => {
const then = performance.now();
try {
update(ctx);
} catch (error) {
clearInterval(interval);
throw error;
}
const elapsed = performance.now() - then;
if (elapsed > 1000 / tickRate) {
console.warn("game worker tick duration breached tick rate. elapsed:", elapsed);
clearInterval(interval);
try {
update(ctx);
} catch (error) {
clearInterval(interval);
throw error;
}
interval = intervalGameLoop();
}
}, 1000 / tickRate);
return interval;
};
if (isFirefox) {
// there is some kind of issue with firefox's setInterval
// it causes extreme jitter when sending data to other peers
timeoutGameLoop(ctx);
} else {
intervalGameLoop();
}
}
function timeoutGameLoop(ctx: GameContext) {
// need to call setTimeout immediately, otherwise network jitter ensues
setTimeout(() => timeoutGameLoop(ctx), 1000 / tickRate);
update(ctx);
}
function update(ctx: GameContext) {
const now = performance.now();
ctx.dt = (now - ctx.elapsed) / 1000;
ctx.elapsed = now;
ctx.tick++;
for (let i = 0; i < ctx.systems.length; i++) {
ctx.systems[i](ctx);
}
}