-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc2mp.js
More file actions
1594 lines (1281 loc) · 40.6 KB
/
c2mp.js
File metadata and controls
1594 lines (1281 loc) · 40.6 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
(function () {
// Get unprefixed versions of the classes we use
var RTCPeerConnection = window["RTCPeerConnection"] || window["webkitRTCPeerConnection"] || window["mozRTCPeerConnection"] || window["msRTCPeerConnection"];
var RTCSessionDescription = window["RTCSessionDescription"] || window["webkitRTCSessionDescription"] || window["mozRTCSessionDescription"] || window["msRTCSessionDescription"];
var RTCIceCandidate = window["RTCIceCandidate"] || window["webkitRTCIceCandidate"] || window["mozRTCIceCandidate"] || window["msRTCIceCandidate"];
// Note Firefox uses name DataChannel instead of RTCDataChannel. See https://bugzilla.mozilla.org/show_bug.cgi?id=1173851
var RTCDataChannel = window["RTCDataChannel"] || window["DataChannel"] || window["webkitRTCDataChannel"] || window["mozRTCDataChannel"] || window["msRTCDataChannel"];
var Peer = window["C2Peer"];
var RegisteredObject = window["C2RegisteredObject"];
var NetValue = window["C2NetValue"];
// Config options
var DEFAULT_SERVER_LIST_URL = "http://www.scirra.com/multiplayer/serverlist.json";
var SIGNALLING_WEBSOCKET_PROTOCOL = "c2multiplayer";
var SIGNALLING_PROTOCOL_REVISION = 1;
var MAGIC_NUMBER = 0x63326D70; // to identify non-fragmented messages originating from this protocol
var DEFAULT_ICE_SERVER_LIST = [
{ "urls": "stun:stun.l.google.com:19302" }
];
window["C2Multiplayer_IsSupported"] = function ()
{
// Note Edge 16 supports RTCPeerConnection but not RTCDataChannel, so check for that too
return !!RTCPeerConnection && !!RTCDataChannel && typeof ArrayBuffer !== "undefined" && typeof DataView !== "undefined";
};
// Multiplayer object
function C2Multiplayer()
{
this.INTERP_NONE = 0;
this.INTERP_LINEAR = 1;
this.INTERP_ANGULAR = 2;
this.PRECISION_HIGH = 0; // 8 bytes double
this.PRECISION_NORMAL = 1; // 4 bytes float
this.PRECISION_LOW = 2; // 2 bytes int16
this.PRECISION_VERYLOW = 3; // 1 byte uint8
this.ice_servers = [];
this.server_list = []; // Server list if any after requestServerList()
this.sigws = null; // WebSocket to signalling server
this.signalling_connected = false;
this.signalling_loggedin = false;
// Signalling server info
this.sigserv_protocolrev = 0;
this.sigserv_version = 0;
this.sigserv_name = "";
this.sigserv_operator = "";
this.sigserv_motd = "";
this.myid = "";
this.myalias = "";
this.game = ""; // Game name joined if any
this.gameinstance = ""; // Game instance name joined if any
this.room = ""; // Room name joined if any
this.peers = []; // List of peers in room
this.peers_by_id = {};
this.nextPeerNid = 0;
this.usedPeerNids = {};
this.me = null; // Peer representing local user
this.host = null; // Peer representing host
// Overridable events
this.onserverlist = null; // Fires after requestServerList() completes
this.onsignallingopen = null; // Fires when connection to signalling server opens
this.onsignallingerror = null; // Fires when error in connection to signalling server
this.onsignallingclose = null; // Fires when connection to signalling server closes
this.onsignallingwelcome = null; // Fires when welcome message received
this.onsignallinglogin = null;
this.onsignallingjoin = null;
this.onsignallingleave = null;
this.onsignallingkicked = null;
this.onsignallinginstancelist = null;
this.onsignallingroomlist = null;
this.onbeforeclientupdate = null;
this.onpeeropen = null; // function (peer)
this.onpeerclose = null; // function (peer)
this.onpeererror = null; // function (peer, e)
this.onpeermessage = null; // function (peer, type, m)
this.oninstancedestroyed = null; // function (ro, nid)
this.ongetobjectcount = null; // function (obj)
this.ongetobjectvalue = null; // function (obj, index, netvalue)
this.clientDelay = 80; // client-side delay (ms)
this.hostUpdateRateSec = 30; // number of times to send outbound updates as host
this.peerUpdateRateSec = 30; // number of times to send outbound updates as peer
this.lastUpdateTime = 0;
this.stats = {
lastSecondTime: 0, // for measuring the per second counts
outboundPerSec: 0, // number of messages outbound per second
outboundCount: 0,
outboundBandwidthPerSec: 0, // uploaded payload bytes per second
outboundBandwidthCount: 0,
inboundPerSec: 0, // number of messages inbound per second
inboundCount: 0,
inboundBandwidthPerSec: 0, // downloaded payload bytes per second
inboundBandwidthCount: 0
};
// Array buffer for generating outbound updates
this.dataBuffer = new ArrayBuffer(262144); // 256kb max size per message; use views to reduce transmitted size
this.dataView = new DataView(this.dataBuffer);
// Object tracking
this.registeredObjects = [];
this.nextObjectNid = 1;
this.objectsByNid = {};
// Latency simulation
this.simLatency = 0;
this.simPdv = 0;
this.simPacketLoss = 0;
// Clock synchronisation
this.lastTimeDiffs = [];
this.targetHostTimeDiff = 0;
this.hostTimeDiff = 0;
this.targetSimDelay = this.clientDelay;
this.simDelay = this.clientDelay;
// Client input state values
this.clientvalues = [];
this.clientvalue_by_tag = {};
this.receivedClientValues = false;
this.mergeIceServerList(DEFAULT_ICE_SERVER_LIST);
var self = this;
// Update pings every 2 seconds
setInterval(function () {
self.doPings();
}, 2000);
// Closing browser window doesn't appear to close connections - the other
// end just times out. So onunload force disconnect, which sends notifications.
window.addEventListener("unload", function ()
{
self.removeAllPeers("quit");
});
};
C2Multiplayer.prototype.isConnected = function ()
{
return this.signalling_connected;
};
C2Multiplayer.prototype.isLoggedIn = function ()
{
return this.isConnected() && this.signalling_loggedin;
};
C2Multiplayer.prototype.isInRoom = function ()
{
return this.isLoggedIn() && this.room;
};
C2Multiplayer.prototype.isHost = function ()
{
return this.isInRoom() && this.me && (this.host === this.me);
};
C2Multiplayer.prototype.getMyID = function ()
{
return this.isLoggedIn() ? this.myid : "";
};
C2Multiplayer.prototype.getMyAlias = function ()
{
return this.isLoggedIn() ? this.myalias : "";
};
C2Multiplayer.prototype.getCurrentGame = function ()
{
return this.isLoggedIn() ? this.game : "";
};
C2Multiplayer.prototype.getCurrentGameInstance = function ()
{
return this.isLoggedIn() ? this.gameinstance : "";
};
C2Multiplayer.prototype.getCurrentRoom = function ()
{
return this.isInRoom() ? this.room : "";
};
C2Multiplayer.prototype.getHostID = function ()
{
return this.host ? this.host.id : "";
};
C2Multiplayer.prototype.getHostAlias = function ()
{
return this.host ? this.host.alias : "";
};
C2Multiplayer.prototype.setLatencySimulation = function (latency_, pdv_, loss_)
{
this.simLatency = latency_;
this.simPdv = pdv_;
this.simPacketLoss = loss_;
if (this.simLatency < 0)
this.simLatency = 0;
if (this.simPdv < 0)
this.simPdv = 0;
if (this.simPacketLoss < 0)
this.simPacketLoss = 0;
};
C2Multiplayer.prototype.requestServerList = function (url_)
{
var self = this;
var xhr = new XMLHttpRequest();
// If anything goes wrong, call onserverlist with null argument
var errorFunc = function (e)
{
console.error("Error requesting server list");
if (self.onsignallingerror)
self.onsignallingerror(e);
};
xhr.onerror = errorFunc;
xhr.ontimeout = errorFunc;
xhr.onabort = errorFunc;
xhr.onload = function ()
{
var o;
try {
o = JSON.parse(xhr.responseText);
}
catch (e) {
errorFunc(e);
return;
}
self.server_list = o["server_list"];
if (self.onserverlist)
self.onserverlist(self.server_list);
else
errorFunc("response did not contain a server list");
};
xhr.open("GET", url_ || DEFAULT_SERVER_LIST_URL);
try {
xhr.responseType = "text";
} catch (e) {}
xhr.timeout = 10000; // 10 second timeout
xhr.send();
};
C2Multiplayer.prototype.signallingConnect = function (url_)
{
// Ignore if already connected
if (this.sigws || this.signalling_connected)
return;
var self = this;
try {
this.sigws = new WebSocket(url_, SIGNALLING_WEBSOCKET_PROTOCOL);
}
catch (e) {
// May be unable to parse URL address
this.sigws = null;
if (this.onsignallingerror)
this.onsignallingerror(e);
return;
}
this.sigws.onopen = function ()
{
// Check server websocket supports this protocol
if (self.sigws.protocol.indexOf(SIGNALLING_WEBSOCKET_PROTOCOL) === -1)
{
if (self.onsignallingerror)
self.onsignallingerror("server does not support '" + SIGNALLING_WEBSOCKET_PROTOCOL + "' protocol");
self.sigws.close(1002, "'" + SIGNALLING_WEBSOCKET_PROTOCOL + "' protocol required");
self.sigws = null;
self.signalling_connected = false;
return;
}
self.signalling_connected = true;
if (self.onsignallingopen)
self.onsignallingopen();
};
this.sigws.onclose = function (e)
{
if (self.onsignallingclose)
self.onsignallingclose(e);
self.signalling_connected = false;
self.signalling_loggedin = false;
self.sigws = null;
};
this.sigws.onerror = function (e)
{
console.error("Signalling server error: ", e);
if (self.onsignallingerror)
self.onsignallingerror(e);
};
this.sigws.onmessage = function (m)
{
self.onSignallingMessage(m);
};
};
C2Multiplayer.prototype.signallingDisconnect = function ()
{
if (!this.sigws || !this.signalling_connected)
return;
this.sigws.close();
this.sigws = null;
this.signalling_connected = false;
};
C2Multiplayer.prototype.onSignallingMessage = function (m)
{
var o;
try {
o = JSON.parse(m.data);
}
catch (e) {
if (this.onsignallingerror)
this.onsignallingerror(e);
return;
}
switch (o.message) {
case "welcome":
this.onSignallingReceiveWelcome(o);
break;
case "login-ok":
this.onSignallingReceiveLoginOK(o);
break;
case "join-ok":
this.onSignallingReceiveJoinOK(o);
break;
case "leave-ok":
this.onSignallingReceiveLeaveOK(o);
break;
case "kicked":
this.onSignallingReceiveKicked(o);
break;
case "peer-joined":
this.onSignallingReceivePeerJoined(o);
break;
case "peer-quit":
this.onSignallingReceivePeerQuit(o);
break;
case "icecandidate":
this.onSignallingReceiveIceCandidate(o);
break;
case "offer":
this.onSignallingReceiveOffer(o);
break;
case "answer":
this.onSignallingReceiveAnswer(o);
break;
case "instance-list":
this.onSignallingReceiveInstanceList(o);
break;
case "room-list":
this.onSignallingReceiveRoomList(o);
break;
case "error":
if (this.onsignallingerror)
this.onsignallingerror(o.details);
break;
default:
if (this.onsignallingerror)
this.onsignallingerror("received unknown signalling message");
break;
}
};
C2Multiplayer.prototype.hasIceServerUrl = function (server)
{
var i, len, s;
for (i = 0, len = this.ice_servers.length; i < len; ++i)
{
s = this.ice_servers[i];
if (s["urls"] === server["urls"])
return true;
}
return false;
};
C2Multiplayer.prototype.mergeIceServerList = function (arr)
{
if (!arr)
return;
var i, len, o;
for (i = 0, len = arr.length; i < len; ++i)
{
o = arr[i];
if (typeof arr[i] === "string") // old style signalling server sending string URLs instead of objects
{
// Make in to object instead
o = { "urls": arr[i] };
}
if (!this.hasIceServerUrl(o))
{
// Make sure the "urls" property is duplicated as "url" for compatibility with Firefox
if (!o.hasOwnProperty("url"))
o["url"] = o["urls"];
this.ice_servers.push(o);
}
}
};
C2Multiplayer.prototype.getIceServerList = function ()
{
return this.ice_servers;
};
C2Multiplayer.prototype.onSignallingReceiveWelcome = function (o)
{
if (o.protocolrev < 1 || o.protocolrev > SIGNALLING_PROTOCOL_REVISION)
{
if (this.onsignallingerror)
this.onsignallingerror("signalling server protocol revision not supported");
this.signallingDisconnect();
return;
}
this.myid = o.clientid;
this.sigserv_protocolrev = o.protocolrev;
this.sigserv_version = o.version;
this.sigserv_name = o.name;
this.sigserv_operator = o.operator;
this.sigserv_motd = o.motd;
this.mergeIceServerList(o.ice_servers);
if (this.onsignallingwelcome)
this.onsignallingwelcome();
};
C2Multiplayer.prototype.onSignallingReceiveLoginOK = function (o)
{
this.myalias = o.alias;
this.signalling_loggedin = true;
if (this.onsignallinglogin)
this.onsignallinglogin();
};
C2Multiplayer.prototype.allocatePeerNid = function ()
{
if (this.me !== this.host)
return; // peers cannot allocate nids
this.nextPeerNid++;
if (this.nextPeerNid > 65535)
this.nextPeerNid = 0;
// Skip over any used values to the next free value
while (this.usedPeerNids.hasOwnProperty(this.nextPeerNid))
{
this.nextPeerNid++;
if (this.nextPeerNid > 65535)
this.nextPeerNid = 0;
}
// We can now use this NID
var nid = this.nextPeerNid;
this.usedPeerNids[nid] = true;
return nid;
};
C2Multiplayer.prototype.freePeerNid = function (nid)
{
if (this.me !== this.host)
return;
if (this.usedPeerNids.hasOwnProperty(nid))
delete this.usedPeerNids[nid];
};
C2Multiplayer.prototype.onSignallingReceiveJoinOK = function (o)
{
// Disconnect from any existing peers if still running old room
this.removeAllPeers("disconnect");
this.game = o.game;
this.gameinstance = o.instance;
this.room = o.room;
this.me = new Peer(this, this.myid, this.myalias);
// Local client was assigned host
if (o.host)
{
this.host = this.me;
this.nextPeerNid = 0;
this.usedPeerNids = {};
this.host.nid = this.allocatePeerNid();
}
else
{
this.lastTimeDiffs.length = 0;
this.targetHostTimeDiff = 0;
this.hostTimeDiff = 0;
// Reset to conservative bandwidth profile and await updated settings from host
this.clientDelay = 80;
this.hostUpdateRateSec = 30;
this.peerUpdateRateSec = 30;
this.targetSimDelay = this.clientDelay;
this.simDelay = this.clientDelay;
this.host = new Peer(this, o.hostid, o.hostalias);
this.host.connect();
}
if (this.onsignallingjoin)
this.onsignallingjoin(!!o.host);
};
C2Multiplayer.prototype.onSignallingReceiveLeaveOK = function (o)
{
this.room = "";
if (this.onsignallingleave)
this.onsignallingleave();
};
C2Multiplayer.prototype.onSignallingReceiveKicked = function (o)
{
this.disconnectRoom(false);
this.room = "";
if (this.onsignallingkicked)
this.onsignallingkicked();
};
C2Multiplayer.prototype.onPeerKicked = function ()
{
this.room = "";
// note same callback as signalling kick event
if (this.onsignallingkicked)
this.onsignallingkicked();
};
C2Multiplayer.prototype.onSignallingReceivePeerJoined = function (o)
{
if (!this.signalling_loggedin || !this.room || this.me !== this.host)
return;
// If the same peer ID is timing out, it's possible the same peer ID can join twice.
// Make sure we forcibly remove the old peer first
if (this.peers_by_id.hasOwnProperty(o.peerid))
this.peers_by_id[o.peerid].remove("rejoin");
var peer = new Peer(this, o.peerid, o.peeralias);
peer.connect();
};
C2Multiplayer.prototype.onSignallingReceivePeerQuit = function (o)
{
if (!this.signalling_loggedin || !this.room || this.me !== this.host)
return;
// Signalling server has indicated for us to remove this peer
if (this.peers_by_id.hasOwnProperty(o.id))
this.peers_by_id[o.id].remove(o.reason);
};
C2Multiplayer.prototype.onSignallingReceiveIceCandidate = function (o)
{
if (!this.signalling_loggedin || !this.room)
return;
var peer = this.peers_by_id[o.from];
if (peer && peer.pc)
{
peer.pc.addIceCandidate(new RTCIceCandidate(o.icecandidate));
}
};
C2Multiplayer.prototype.onSignallingReceiveOffer = function (o)
{
if (!this.signalling_loggedin || !this.room || this.me === this.host || !this.me || !this.host || !this.host.pc)
return;
if (o.from !== this.host.id)
return;
var self = this;
this.host.pc.setRemoteDescription(new RTCSessionDescription(o.offer))
.then(function ()
{
self.host.pc.createAnswer()
.then(function (answer)
{
self.host.pc.setLocalDescription(answer);
self.signallingSend({
message: "answer",
toclientid: self.host.id,
answer: answer
});
})
.catch(function (err)
{
console.error("Peer error creating answer: ", err);
if (self.onpeererror)
self.onpeererror(self.me, "could not create answer to host offer");
});
})
.catch(function (err)
{
console.error("Peer error setting remote description: ", err);
if (self.onpeererror)
self.onpeererror(self.me, "could not set remote description");
});
};
C2Multiplayer.prototype.onSignallingReceiveAnswer = function (o)
{
if (!this.signalling_loggedin || !this.room || this.me !== this.host)
return;
var peer = this.peers_by_id[o.from];
if (!peer)
return;
peer.pc.setRemoteDescription(new RTCSessionDescription(o.answer))
.catch(function (err) {
console.error("Host error setting remote description: ", err);
});
};
C2Multiplayer.prototype.onSignallingReceiveInstanceList = function (o)
{
if (this.onsignallinginstancelist)
this.onsignallinginstancelist(o["list"]);
};
C2Multiplayer.prototype.onSignallingReceiveRoomList = function (o)
{
if (this.onsignallingroomlist)
this.onsignallingroomlist(o["list"]);
};
C2Multiplayer.prototype.signallingSend = function (o)
{
if (this.sigws && this.signalling_connected)
this.sigws.send(JSON.stringify(o));
};
C2Multiplayer.prototype.signallingLogin = function (alias_)
{
if (this.signalling_loggedin)
return;
this.signallingSend({
message: "login",
protocolrev: SIGNALLING_PROTOCOL_REVISION,
alias: alias_
});
};
C2Multiplayer.prototype.signallingJoinGameRoom = function (game_, instance_, room_, max_clients_)
{
if (!this.signalling_loggedin || this.room)
return;
this.signallingSend({
message: "join",
game: game_,
instance: instance_,
room: room_,
max_clients: max_clients_
});
};
C2Multiplayer.prototype.signallingAutoJoinGameRoom = function (game_, instance_, room_, max_clients_, lock_when_full_)
{
if (!this.signalling_loggedin || this.room)
return;
this.signallingSend({
message: "auto-join",
game: game_,
instance: instance_,
room: room_,
max_clients: max_clients_,
lock_when_full: lock_when_full_
});
};
C2Multiplayer.prototype.signallingLeaveRoom = function ()
{
if (!this.signalling_loggedin)
return;
this.signallingSend({
message: "leave"
});
};
C2Multiplayer.prototype.signallingConfirmPeer = function (id_)
{
if (!this.signalling_loggedin || !this.isHost())
return;
this.signallingSend({
message: "confirm-peer",
id: id_
});
};
C2Multiplayer.prototype.signallingRequestGameInstanceList = function (game_)
{
if (!this.sigws || !this.signalling_connected)
return;
this.signallingSend({
message: "list-instances",
game: game_
});
};
C2Multiplayer.prototype.signallingRequestRoomList = function (game_, instance_, which_)
{
if (!this.sigws || !this.signalling_connected)
return;
this.signallingSend({
message: "list-rooms",
game: game_,
instance: instance_,
which: which_
});
};
C2Multiplayer.prototype.disconnectRoom = function (signalling_leave_room)
{
this.lastTimeDiffs.length = 0;
this.targetHostTimeDiff = 0;
this.hostTimeDiff = 0;
this.removeAllPeers("disconnect");
if (signalling_leave_room)
this.signallingLeaveRoom();
};
var isRemovingAllPeers = false;
C2Multiplayer.prototype.removeAllPeers = function (reason)
{
// Prevent recursion since removing key peers will also call removeAllPeers()
if (isRemovingAllPeers)
return;
isRemovingAllPeers = true;
while (this.peers.length)
this.peers[0].remove(reason);
isRemovingAllPeers = false;
};
C2Multiplayer.prototype.getPeerById = function (id)
{
if (this.peers_by_id.hasOwnProperty(id))
return this.peers_by_id[id];
else
return null;
};
C2Multiplayer.prototype.getAliasFromId = function (id)
{
if (this.peers_by_id.hasOwnProperty(id))
return this.peers_by_id[id].alias;
else
return "";
};
C2Multiplayer.prototype.getPeerByNid = function (nid)
{
var i, len, p;
for (i = 0, len = this.peers.length; i < len; ++i)
{
p = this.peers[i];
if (p.nid === nid)
return p;
}
return null;
};
var tmpArr = [];
C2Multiplayer.prototype.hostBroadcast = function (type, m, skip_peer)
{
if (this.me !== this.host)
return;
var i, len, p;
// send() can fail and remove the peer, which crashes while iterating the peers array.
// To avoid this, shallow copy the peers to broadcast to so any getting removed during
// broadcast don't matter.
window.cr_shallowAssignArray(tmpArr, this.peers);
for (i = 0, len = tmpArr.length; i < len; ++i)
{
p = tmpArr[i];
if (!p)
continue;
if ((p !== this.me) && (p !== skip_peer))
p.send(type, m);
}
tmpArr.length = 0;
};
C2Multiplayer.prototype.doPings = function ()
{
var i, len, p;
var nowtime = window.cr_performance_now();
// Host: ping everybody but me
if (this.me === this.host)
{
// sendPing() can fail and remove the peer, which crashes while iterating the peers array.
// Same workaround as hostBroadcast used here.
window.cr_shallowAssignArray(tmpArr, this.peers);
for (i = 0, len = tmpArr.length; i < len; ++i)
{
p = tmpArr[i];
if (!p)
continue;
if (p !== this.me)
p.sendPing(nowtime, false);
}
tmpArr.length = 0;
}
// Peer: only ping host
else
{
if (this.host)
this.host.sendPing(nowtime, false);
}
};
C2Multiplayer.prototype.registerObject = function (obj, sid, bandwidth)
{
return new RegisteredObject(this, obj, sid, bandwidth);
};
C2Multiplayer.prototype.getRegisteredObjectsMap = function ()
{
var ret = {};
var p, ro;
for (p in this.objectsByNid)
{
if (this.objectsByNid.hasOwnProperty(p))
{
ro = this.objectsByNid[p];
ret[ro.sid] = {
"nid": parseInt(p, 10),
"nvs": ro.getNetValuesJson()
};
}
}
return ret;
};
C2Multiplayer.prototype.mapObjectNids = function (objs)
{
// Run through all our registered objects and update their NIDs from what the host
// told us they are
this.objectsByNid = {}; // override with what host tells us
var i, len, ro, o;
for (i = 0, len = this.registeredObjects.length; i < len; ++i)
{
ro = this.registeredObjects[i];
if (objs.hasOwnProperty(ro.sid.toString()))
{
o = objs[ro.sid.toString()];
ro.nid = o["nid"];
this.objectsByNid[ro.nid] = ro;
ro.setNetValuesFrom(o["nvs"]);
}
else
{
console.warn("Could not map object SID '" + ro.sid + "' - host did not send NID for it");
ro.nid = -1;
}
}
};
C2Multiplayer.prototype.tick = function (dt)
{
if (!this.isInRoom())
return;
var nowtime = window.cr_performance_now();
// Aim to reach the target rate of updates per second.
// Allow a 5ms inaccuracy in the timer, since ticking at 60 Hz could drop an update
// that was a tiny bit early.
var updateRate = (this.me === this.host ? this.hostUpdateRateSec : this.peerUpdateRateSec);
if ((nowtime - this.lastUpdateTime) >= ((1000 / updateRate) - 5))
{
this.sendUpdate(nowtime);
this.lastUpdateTime = nowtime;
}
// Stat tracking per second
if ((nowtime - this.stats.lastSecondTime) >= 1000)
{
this.stats.outboundPerSec = this.stats.outboundCount;
this.stats.outboundBandwidthPerSec = this.stats.outboundBandwidthCount;
this.stats.inboundPerSec = this.stats.inboundCount;
this.stats.inboundBandwidthPerSec = this.stats.inboundBandwidthCount;
this.stats.outboundCount = 0;
this.stats.outboundBandwidthCount = 0;
this.stats.inboundCount = 0;
this.stats.inboundBandwidthCount = 0;
this.stats.lastSecondTime += 1000;