/
server.js
379 lines (330 loc) · 11.5 KB
/
server.js
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
var EventEmitter = require('events').EventEmitter;
var WebSocketEmitter = require('./web-socket-emitter');
var uuid = require('hat');
// voxel dependencies
var Coordinates = require('./coordinates');
var encoder = require('./rle-encoder');
var fs = require('fs');
var stats = require('./voxel-stats');
var debug = false;
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
module.exports = Server;
function Server(config, chunkStore, serverSettings, clientSettings) {
// force instantiation via `new` keyword
//if(!(this instanceof Server)) { return new Server(serverSettings || {}, clientSettings || {}) }
this.config = config;
this.chunkStore = chunkStore;
this.serverSettings = serverSettings;
this.clientSettings = clientSettings;
this.requestedChunks = {};
var chunkSize = config.chunkSize;
var origin = [0, 0, 0];
var step = chunkSize * config.worldRadius;
this.lastWorldChunks = [
// Lower chunk
origin[0] - step,
origin[1] - step,
origin[2] - step,
// Farther chunk
origin[0] + step,
origin[1] + step,
origin[2] + step
];
this.initialize();
};
Server.prototype.initialize = function() {
var self = this;
var clients = this.clients = {};
this.emitter = new EventEmitter();
this.coords = Coordinates(self.config.chunkSize);
// Must pass this in, for now
this.encodedChunkCache = {};
// chunkId -> {clientIdA: true, clientIdB: true}
this.chunksForClients = {};
this.chunkStore.emitter.on('got', function(chunk) {
if (debug) {
console.log('got chunk ' + chunk.chunkID);
}
self.sendChunk(chunk);
});
// Prime our chunk store or LRU
self.requestNearbyChunks(this.clientSettings.initialPosition);
// send player position/rotation updates
setInterval(function() {
self.sendPlayers();
}, 1e3 / 3);
// 3 updates per second
// Send chunks every half-second
/*
setInterval(function() {
var sendChunksBatchSize = 20;
// Handle chunk generation
for (var id in self.clients) {
var client = self.clients[id];
var ready = [];
var chunkIDs;
for (var chunkId in client.requestedChunks) {
if (ready.length > sendChunksBatchSize) {
break;
}
// Make sure chunkID is valid, not out of range, etc
if (self.chunkStore.has(chunkID)) {
ready.push(chunkID);
delete client.requestedChunks[chunkID];
}
}
if (ready.length > 0) {
//console.log('Ready to send: ' + ready.length)
self.sendChunks(client.connection, ready);
}
}
}, 1e3 / 5);
*/
};
// Setup the client connection - register events, etc
Server.prototype.connectClient = function(wseSocket) {
var self = this;
var id = wseSocket.id = uuid();
var client = self.clients[id] = {
id: id,
// This gets updated when we get their position updates
// Server should remove stale clients
lastSeen: 0,
connected: true,
connection: wseSocket,
avatar: 'player',
position: null,
yaw: 0,
pitch: 0,
requestedChunks: {},
// The chunk ids this client cares about
onlyTheseChunks: []
};
// setup client response handlers
self.bindClientEvents(client);
// send client id and initial game settings
wseSocket.emit('settings', self.clientSettings, id);
};
Server.prototype.bindClientEvents = function(client) {
var self = this;
var id = client.id;
var connection = client.connection;
connection.on('error', function(message) {
console.log('Client connection error: ' + message);
});
connection.on('end', function() {
client.connected = false;
});
connection.on('close', function(error) {
client.connected = false;
delete self.clients[client.id];
});
// forward chat message
connection.on('chat', function(message) {
// ignore if no message provided
if (!message.text) return;
if (message.text.match(/script/i)) {
console.log('Found script tag in message. Dropping');
return;
}
// limit chat message length
if (message.text.length > 255) message.text = message.text.substr(0, 140);
self.broadcast(null, 'chat', message);
self.emitter.emit('chat', message);
});
// when user ready ( game created, etc )
connection.on('created', function() {
// emit client.created for module consumers
self.emitter.emit('client.created', client);
});
// client sends new position, rotation
// don't need to lerp on the server AND the client, just the client
connection.on('myPosition', function(position, yaw, pitch, avatar) {
client.position = position;
client.yaw = yaw;
client.pitch = pitch;
client.avatar = avatar;
self.emitter.emit('client.state', client);
});
// Client sent us voxel changes for one or more chunks
connection.on('chunkVoxelIndexValue', function(changes) {
// Update our chunk store
self.chunkStore.gotChunkChanges(changes);
// Re-broadcast this to the other players, too
for (var chunkID in changes) {
var chunkChanges = {};
chunkChanges[chunkID] = changes[chunkID];
delete self.encodedChunkCache[ chunkID ];
for (var clientId in self.clients) {
var client;
var connection;
// Don't broadcast to the client that sent us the info
if (clientId === id) {
continue;
}
client = self.clients[clientId];
if (!client.connected) {
continue;
}
if (debug) {
console.log('sending to', clientId, args);
}
// emit over connection
client.connection.emit('chunkVoxelIndexValue', chunkChanges);
}
}
});
// Client tells us which chunks it wants to hear about
connection.on('onlyTheseChunks', function(chunks) {
if (debug) {
console.log('Client only cares about these chunks', chunks);
}
client.chunks = chunks;
});
// Client wants chunks. Keep track of which client wants chunks
connection.on('needChunks', function(chunkIds) {
if (debug) {
console.log(client.id + ' needs chunks', chunkIds);
}
// Request the chunks we want
for (var i = 0; i < chunkIds.length; i++) {
var chunkId = chunkIds[i];
if (!self.isChunkInBounds(chunkId)) {
continue;
}
if (!(chunkId in self.chunksForClients)) {
self.chunksForClients[chunkId] = {};
}
// Keep track of which client wants this chunk
self.chunksForClients[ chunkId ][ client.id ] = true;
self.chunkStore.get(chunkId);
}
});
};
// send message to all clients
Server.prototype.broadcast = function(id, event) {
var self = this;
// normalize arguments
var len = arguments.length;
var args = new Array(len);
// skip client `id` argument
for (var i = 0, j = 1; j < len; i++, j++) {
args[i] = arguments[j];
}
// emit on self for module consumers, unless specified not to
if (id !== 'server') {
self.emitter.emit.apply(self, args);
}
for (var clientId in self.clients) {
var client;
var connection;
// Don't broadcast to the client that sent us the info
if (clientId === id) {
continue;
}
client = self.clients[clientId];
if (!client.connected) {
continue;
}
if (debug) {
console.log('sending to', clientId, args);
}
// emit over connection
client.connection.emit.apply(client.connection, args);
}
};
// broadcast position, rotation updates for each player
Server.prototype.sendPlayers = function() {
var self = this;
var clientIds = Object.keys(self.clients);
if (clientIds.length === 0) {
return;
}
//console.log('Sending updates for ' + clientIds.length + ' clients')
var players = {};
clientIds.map(function(id) {
var client = self.clients[id];
if (!client.position) {
return;
}
// TODO: Ignore client if they're really stale
players[id] = {
positions: [
client.position[0],
client.position[1],
client.position[2],
client.pitch,
client.yaw,
0
],
avatar: client.avatar
};
});
self.broadcast(null, 'players', players);
};
Server.prototype.requestNearbyChunks = function(position) {
var self = this;
this.coords.nearbyChunkIDsEach(position, 2, function(chunkID) {
self.chunkStore.get(chunkID);
});
};
Server.prototype.sendChunk = function(chunk) {
var self = this;
var chunkId = chunk.chunkID;
if (!(chunkId in this.chunksForClients)) {
// Nobody's waiting for this chunk
if (debug) {
console.log('Nobody is waiting for ', chunkId);
}
return;
}
// GET IDS SO NO LOOP ITERATION ISSUES
// LOOPS OVER CLIENT IDS TOO, PRUNING EMPTY OBJECTS
var clientIds = Object.keys(this.chunksForClients[chunkId]);
for (var i = 0; i < clientIds.length; i++) {
var clientId = clientIds[i];
var client;
if (clientId in self.clients) {
client = self.clients[clientId];
if (client.connected) {
if (chunkId in this.encodedChunkCache) {
encoded = self.encodedChunkCache[chunkId];
} else {
encoded = encoder(chunk.voxels);
self.encodedChunkCache[chunkId] = encoded;
}
if (debug) {
console.log('Sending ' + chunkId + ' to client ' + clientId);
}
// Send chunkID so we can use it on the receving end as the key in our chunksToDecodeAndMesh object
client.connection.emit('chunk', chunkId, encoded);
}
} else {
console.log(clientId, ' not found in self.clients');
}
delete this.chunksForClients[chunkId][clientId];
}
var chunkIds = Object.keys(this.chunksForClients);
for (var i = 0; i < chunkIds.length; i++) {
var chunkId = chunkIds[i];
var clientIds = Object.keys(this.chunksForClients[chunkId]);
if (clientIds.length == 0) {
delete this.chunksForClients[chunkId];
}
}
};
Server.prototype.isChunkInBounds = function(chunkID) {
var self = this;
var position = chunkID.split('|').map(function(value) {
return Number(value);
});
if (position[0] < self.lastWorldChunks[0] || position[1] < self.lastWorldChunks[1] || position[2] < self.lastWorldChunks[2] || position[0] > self.lastWorldChunks[3] || position[1] > self.lastWorldChunks[4] || position[2] > self.lastWorldChunks[5]) {
return false;
}
return true;
};
Server.prototype.on = function(name, callback) {
this.emitter.on(name, callback);
};