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
|
/**
* @author tint
*/
import { GameState, Message, PlayerInput } from "../types.js";
import { Game } from "./game";
export function multiplayer(
game: Game,
code: string,
onStart: (
startFrame: number,
latency: number,
connection: number,
update: (input: PlayerInput, frame: number) => void,
ping: () => Promise<number>,
desyncCheck: (frame: number) => Promise<boolean>,
) => boolean
) {
const url = new URL("api/join/" + encodeURIComponent(code), window.location.toString());
url.protocol = url.protocol.replace("http", "ws");
const socket = new WebSocket(url);
let requestStateTime: number;
let hasState = false;
let connectionId: number;
let cachedInputs = [];
let connections = [];
let pingPromise: (type: Promise<number>) => void;
function send(obj: any) {
socket.send(JSON.stringify(obj));
}
function applyInput(input: Message) {
let prev = game.getHistory(input.frame);
let newInput = prev && prev.input ? {...prev.input} : { players: {} };
if(input.type === "input") {
if(input.connection === undefined) { // local input
if(input.data) {
// send it to the server
send(input);
// then apply it
newInput.players[connectionId] = input.data;
}
} else {
newInput.players[input.connection] = input.data;
}
} else if(input.type === "connections") {
if(input.added !== null) {
newInput.added = (newInput.added || []).concat([input.added]);
}
if(input.removed !== null) {
if(newInput.added) {
newInput.added = newInput.added.filter(n => n !== input.removed);
}
newInput.removed = (newInput.removed || []).concat([input.removed]);
}
}
game.setInput(input.frame, newInput);
}
function flushCachedInputs(latency = 0): boolean {
for(const input of cachedInputs) {
// only care about inputs after the new state
if(input.frame <= game.historyStart) {
continue;
}
applyInput(input);
}
cachedInputs = [];
return onStart(game.getFrame(), latency, connectionId, update, ping, desyncCheck);
}
function update(input: PlayerInput, frame: number) {
if(input === undefined) { // used to update the game locally
if(hasState) {
applyInput({})
}
return;
}
const data = {
type: "input",
data: input,
frame: frame,
};
if(!hasState) {
cachedInputs.push(data);
} else {
applyInput(data);
}
}
async function ping() {
send({
type: "ping",
frame: Math.max(0, game.currentFrame),
});
const frame: number = await new Promise(r => pingPromise = r);
return game.currentFrame - frame;
}
async function desyncCheck(frame: number): Promise<boolean> {
const history = game.getHistory(frame);
if(!history) {
console.error("tried to check for desyncs on a frame not in memory", frame);
return true;
}
// const localstate = history.data;
const proms = connections
.filter(n => n !== connectionId)
.map(connection => {
send({
type: "requeststate",
frame,
connection,
});
return new Promise(r => {
stateRequests[frame + "," + connection] = (state: GameState) => {
r({
state,
connection,
});
}
});
});
if(!proms.length) {
return false; // this is the only connection, no check necessary
}
// const states = await Promise.all(proms);
// if(!states.every(({ state }) => objeq(localstate, state))) {
// console.error("desync! remote states:", states, "local state:", localstate);
// return true;
// }
return false;
}
let stateRequests = {};
socket.onmessage = message => {
const data = JSON.parse(message.data.toString());
switch(data.type) {
case "error":
console.error(data);
break;
case "framerequest":
send({
type: "frame",
frame: Math.max(game.currentFrame, 1),
});
break;
case "state":
if(data.frame + "," + data.connection in stateRequests) {
stateRequests[data.frame + "," + data.connection](data.state);
}
if(!hasState) {
game.startHistory(data.frame, data.state);
hasState = true;
// this state is from the past
// i want to find out exactly how far in the past
// the sequence of requests looks like:
// client -[staterequest]-> server -[staterequest]-> client2
// client2 -[state]-> server -[state]-> client
// and the time i'm concerned with is the second half,
// how long it takes the state to come from client2
let delta = 0;
if(requestStateTime !== undefined) {
delta = performance.now() - requestStateTime;
}
if (!flushCachedInputs(delta / 2)) {
socket.close()
document.getElementById("lobby").style.display = "none"
document.getElementById("join").style.display = ""
return
}
}
break;
case "requeststate":
// wait until there's some state to send
const startTime = performance.now();
const check = () => {
if(performance.now() - startTime > 5000) {
return; // give up after 5s
}
const state = game.getHistory(data.frame);
if(!state) {
return;
}
send({
type: "state",
frame: data.frame,
state: state.data,
});
clearInterval(interval);
}
const interval = setInterval(check, 100);
check();
break;
case "connections":
connections = data.connections;
if(connectionId === undefined) {
console.log("setting connection id", data.id);
connectionId = data.id;
if(data.connections.length === 1) { // no need to request state
hasState = true;
applyInput(data);
flushCachedInputs(); // just in case, also it calls onStart
break;
}
// grab the state from another client
console.log("requesting state");
// measure the time it takes for state to be delivered
requestStateTime = performance.now();
send({
type: "requeststate",
frame: data.frame,
});
}
if(!hasState) {
cachedInputs.push(data);
} else {
applyInput(data);
}
break;
case "input":
if(!hasState) {
cachedInputs.push(data);
} else {
applyInput(data);
}
break;
case "pong":
if(pingPromise) {
pingPromise(data.frame);
pingPromise = undefined;
}
break;
default:
console.warn("unknown server message", data);
break;
}
}
}
// compare two plain objects (things that can be JSON.stringified)
function objeq(a: any, b: any) {
if(typeof(a) !== typeof(b)) {
return false;
}
// array diff
if(Array.isArray(a) && Array.isArray(b)) {
if(a.length !== b.length) {
return false;
}
for(let i = 0; i < a.length; i++) {
if(!objeq(a[i], b[i])) {
return false;
}
}
return true;
}
switch(typeof(a)) {
// primitives can be compared directly
case "number":
case "boolean":
case "string":
case "undefined": return a === b;
case "object":
// typeof(null) = "object" but null can be compared directly
if(a === null || b === null) {
return a === b;
}
// object diff
for(let k in a) {
if(!(k in b) || !objeq(a[k], b[k])) {
return false;
}
}
for(let k in b) {
if(!(k in a)) {
return false;
}
}
return true;
default: // incomparable things
return false;
}
}
|