-
Notifications
You must be signed in to change notification settings - Fork 1
/
SteamMultiplayerPeer.cs
598 lines (514 loc) · 18.6 KB
/
SteamMultiplayerPeer.cs
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
using Godot;
using System;
using System.Collections.Generic;
using GodotSteam;
using Godot.Collections;
using System.Linq;
public partial class SteamMultiplayerPeer : MultiplayerPeerExtension
{
private const int MaxMessageCount = 255;
private const int MaxSteamPacketSize = 512 * 1024;
private const int SteamNetConnectionInvalid = 0;
public bool NoNagle { get; set; } = false;
public bool NoDelay { get; set; } = false;
private System.Collections.Generic.Dictionary<ulong, SteamConnection> connectionsBySteamId64 = new System.Collections.Generic.Dictionary<ulong, SteamConnection>();
private System.Collections.Generic.Dictionary<int, SteamConnection> peerIdToSteamId = new System.Collections.Generic.Dictionary<int, SteamConnection>();
private int transferMode = (int)TransferModeEnum.Reliable;
private uint listenSocket = 0;
private Queue<SteamPacketPeer> incomingPackets = new Queue<SteamPacketPeer>();
private ConnectionStatus connectionStatus = ConnectionStatus.Disconnected;
private MultiplayerPeerMode mode = MultiplayerPeerMode.NONE;
private int targetPeer = -1;
private uint uniqueId = 0;
private Godot.Collections.Array _configs;
public Array<Steam.NetworkingConfigValue> Configs {
set {
_configs = new Godot.Collections.Array();
foreach (var item in value) {
_configs.Add((long) item);
}
}
get {
return new Array<Steam.NetworkingConfigValue>(_configs);
}
}
public SteamMultiplayerPeer()
{
Steam.NetworkConnectionStatusChanged += _OnNetworkConnectionStatusChanged;
Configs = new Array<Steam.NetworkingConfigValue>();
}
public Error CreateServer(int localVirtualPort) {
if (IsActive()) {
GD.PrintErr("The multiplayer instance is already active");
return Error.AlreadyInUse;
}
Steam.InitRelayNetworkAccess();
listenSocket = Steam.CreateListenSocketP2P(localVirtualPort, _configs);
if (listenSocket == SteamNetConnectionInvalid) {
return Error.CantCreate;
}
uniqueId = 1;
mode = MultiplayerPeerMode.SERVER;
connectionStatus = ConnectionStatus.Connected;
return Error.Ok;
}
public Error CreateClient(ulong identityRemote, int remoteVirtualPort) {
if (IsActive()) {
GD.PrintErr("The multiplayer instance is already active");
return Error.AlreadyInUse;
}
uniqueId = GenerateUniqueId();
Steam.InitRelayNetworkAccess();
uint connection = Steam.ConnectP2P(identityRemote, remoteVirtualPort, _configs);
if (connection == SteamNetConnectionInvalid) {
uniqueId = 0;
GD.PrintErr("Failed to connect; connection is invalid");
return Error.CantConnect;
}
mode = MultiplayerPeerMode.CLIENT;
connectionStatus = ConnectionStatus.Connecting;
return Error.Ok;
}
public override byte[] _GetPacketScript()
{
if (incomingPackets.Count == 0)
{
return new byte[]{};
}
SteamPacketPeer nextReceivedPacket = incomingPackets.Dequeue();
return nextReceivedPacket.Data;
}
public override Error _PutPacketScript(byte[] buffer)
{
if (!IsActive() || connectionStatus != ConnectionStatus.Connected || !peerIdToSteamId.ContainsKey(Math.Abs(targetPeer)))
{
return Error.Unconfigured;
}
int packetTransferMode = GetSteamTransferFlag();
if (targetPeer == 0)
{
Error returnValue = Error.Ok;
foreach (var connection in connectionsBySteamId64)
{
SteamPacketPeer packet = new SteamPacketPeer(buffer, transferMode: packetTransferMode);
Error errorCode = connection.Value.Send(packet);
if (errorCode != Error.Ok)
{
returnValue = errorCode;
}
}
return returnValue;
}
else
{
SteamPacketPeer packet = new SteamPacketPeer(buffer, transferMode: packetTransferMode);
return GetConnectionByPeer(targetPeer).Send(packet);
}
}
public override int _GetAvailablePacketCount()
{
return incomingPackets.Count;
}
public override int _GetMaxPacketSize()
{
return MaxSteamPacketSize;
}
public override TransferModeEnum _GetPacketMode()
{
if (!IsActive() || incomingPackets.Count == 0)
{
return TransferModeEnum.Reliable;
}
return incomingPackets.Peek().TransferMode == Steam.NetworkingSendReliable
? TransferModeEnum.Reliable
: TransferModeEnum.Unreliable;
}
public override void _SetTransferMode(TransferModeEnum mode)
{
transferMode = (int) mode;
}
public override TransferModeEnum _GetTransferMode()
{
return (TransferModeEnum)transferMode;
}
public override void _SetTransferChannel(int pChannel)
{
// Channels not implemented yet
}
public override int _GetTransferChannel()
{
// Channels not implemented yet
return 0;
}
public override void _SetTargetPeer(int peer)
{
targetPeer = peer;
}
public override int _GetPacketPeer()
{
if (!IsActive() || incomingPackets.Count == 0)
{
return 1;
}
return connectionsBySteamId64[incomingPackets.Peek().Sender].PeerId;
}
public override int _GetPacketChannel()
{
return 0;
}
public override bool _IsServer()
{
return uniqueId == 1;
}
public bool IsActive() {
return mode != MultiplayerPeerMode.NONE;
}
public override void _Poll()
{
if (!IsActive())
{
return;
}
foreach (var entry in connectionsBySteamId64)
{
var messages = Steam.ReceiveMessagesOnConnection(entry.Value.ConnectionHandle, MaxMessageCount);
foreach (Dictionary message in messages) {
if (GetPeerIdFromSteam64(message["identity"].AsUInt64()) != -1)
{
ProcessMessage(message);
}
else
{
ProcessPing(message);
}
}
}
}
public override void _Close()
{
if (!IsActive() || connectionStatus != ConnectionStatus.Connected)
{
return;
}
foreach (var entry in connectionsBySteamId64)
{
entry.Value.Close();
}
if (_IsServer())
{
CloseListenSocket();
}
peerIdToSteamId.Clear();
connectionsBySteamId64.Clear();
mode = MultiplayerPeerMode.NONE;
uniqueId = 0;
connectionStatus = ConnectionStatus.Disconnected;
}
public override void _DisconnectPeer(int peer, bool force)
{
if (!IsActive() || !peerIdToSteamId.ContainsKey(peer))
{
return;
}
SteamConnection connection = GetConnectionByPeer(peer);
if (!connection.Close())
{
return;
}
connection.Flush();
connectionsBySteamId64.Remove(connection.SteamId);
peerIdToSteamId.Remove(peer);
if (mode == MultiplayerPeerMode.CLIENT || mode == MultiplayerPeerMode.SERVER)
{
GetConnectionByPeer(0).Flush();
}
else if (force)
{
connectionsBySteamId64.Clear();
Close();
}
}
public override int _GetUniqueId()
{
if (!IsActive())
{
return 0;
}
return (int) uniqueId;
}
public override bool _IsServerRelaySupported()
{
return mode == MultiplayerPeerMode.SERVER || mode == MultiplayerPeerMode.CLIENT;
}
public override ConnectionStatus _GetConnectionStatus()
{
return connectionStatus;
}
private int GetSteamTransferFlag()
{
TransferModeEnum transferMode = _GetTransferMode();
int flags = (int) ((Steam.NetworkingSendNoNagle * Convert.ToInt64(NoNagle)) | (Steam.NetworkingSendNoDelay * Convert.ToInt64(NoDelay)));
return transferMode switch
{
TransferModeEnum.Reliable => (int) Steam.NetworkingSendReliable | flags,
TransferModeEnum.Unreliable => (int) Steam.NetworkingSendUnreliable | flags,
_ => throw new InvalidOperationException("Unknown transfer mode")
};
}
private void _OnNetworkConnectionStatusChanged(long connectHandle, Dictionary connection, long oldState)
{
ulong steamId = connection["identity"].AsUInt64();
Steam.NetworkingConnectionState oldStateEnum = (Steam.NetworkingConnectionState) oldState;
Steam.NetworkingConnectionState newStateEnum = (Steam.NetworkingConnectionState) connection["connection_state"].AsInt32();
if (connection["listen_socket"].AsUInt32() != 0 &&
oldStateEnum == Steam.NetworkingConnectionState.None &&
newStateEnum == Steam.NetworkingConnectionState.Connecting)
{
// TODO: Confirm connectHandle is supposed to be a uint
ErrorResult result = (ErrorResult) Steam.AcceptConnection((uint)connectHandle);
if (result != ErrorResult.Ok)
{
Steam.CloseConnection((uint)connectHandle, (int) Steam.NetworkingConnectionEnd.AppExceptionGeneric, "Failed to accept connection", false);
}
}
if ((oldStateEnum == Steam.NetworkingConnectionState.Connecting ||
oldStateEnum == Steam.NetworkingConnectionState.FindingRoute) &&
newStateEnum == Steam.NetworkingConnectionState.Connected)
{
AddConnection(steamId, (uint) connectHandle);
if (!_IsServer())
{
connectionStatus = ConnectionStatus.Connected;
connectionsBySteamId64[steamId].SendPeer(uniqueId);
}
}
if ((oldStateEnum == Steam.NetworkingConnectionState.Connecting ||
oldStateEnum == Steam.NetworkingConnectionState.Connected) &&
newStateEnum == Steam.NetworkingConnectionState.ClosedByPeer)
{
if (!_IsServer())
{
if (connectionStatus == ConnectionStatus.Connected)
{
EmitSignal("peer_disconnected", 1);
}
Close();
}
else
{
if (connectionsBySteamId64.ContainsKey(steamId))
{
SteamConnection steamConnection = connectionsBySteamId64[steamId];
int peerId = steamConnection.PeerId;
if (peerId != -1)
{
EmitSignal("peer_disconnected", peerId);
peerIdToSteamId.Remove(peerId);
}
connectionsBySteamId64.Remove(steamId);
}
}
}
if ((oldStateEnum == Steam.NetworkingConnectionState.Connecting ||
oldStateEnum == Steam.NetworkingConnectionState.Connected) &&
newStateEnum == Steam.NetworkingConnectionState.ProblemDetectedLocally)
{
if (!_IsServer())
{
if (connectionStatus == ConnectionStatus.Connected)
{
EmitSignal("peer_disconnected", 1);
}
Close();
}
else
{
if (connectionsBySteamId64.ContainsKey(steamId))
{
SteamConnection steamConnection = connectionsBySteamId64[steamId];
int peerId = steamConnection.PeerId;
if (peerId != -1)
{
EmitSignal("peer_disconnected", peerId);
peerIdToSteamId.Remove(peerId);
}
connectionsBySteamId64.Remove(steamId);
}
}
}
}
public int GetPeerIdFromSteam64(ulong steam64)
{
if (connectionsBySteamId64.ContainsKey(steam64))
{
return connectionsBySteamId64[steam64].PeerId;
}
return -1;
}
private void SetSteamIdPeer(ulong steamId, int peerId) {
if (steamId == Steam.GetSteamID()) {
GD.PrintErr("Cannot add self as a new peer");
return;
}
if (!connectionsBySteamId64.ContainsKey(steamId)) {
GD.PrintErr("Steam ID missing");
return;
}
SteamConnection connection = connectionsBySteamId64[steamId];
if (connection.PeerId == -1) {
connection.PeerId = peerId;
peerIdToSteamId[peerId] = connection;
}
}
private SteamConnection GetConnectionByPeer(int peerId)
{
if (peerIdToSteamId.ContainsKey(peerId))
{
return peerIdToSteamId[peerId];
}
return null;
}
private void ProcessMessage(Dictionary message)
{
byte[] data = message["payload"].AsByteArray();
ulong identity = message["identity"].AsUInt64();
incomingPackets.Enqueue(new SteamPacketPeer(data, sender: identity));
}
private void ProcessPing(Dictionary message)
{
int peerId = BitConverter.ToInt32(message["payload"].AsByteArray());
ulong steamId = message["identity"].AsUInt64();
SteamConnection connection = connectionsBySteamId64[steamId];
if (peerId != 0) {
if (connection.PeerId == -1) {
SetSteamIdPeer(steamId, peerId);
}
if (_IsServer()) {
Error error = connection.SendPeer(uniqueId);
if (error != Error.Ok) {
GD.PrintErr("Error sending server peer ID to client: ", error);
}
}
EmitSignal(SignalName.PeerConnected, connection.PeerId);
}
}
private void AddConnection(ulong steamId, uint connectionHandle)
{
if (steamId == Steam.GetSteamID()) {
GD.PrintErr("Cannot add self as a new peer");
}
if (!connectionsBySteamId64.ContainsKey(steamId))
{
SteamConnection connection = new SteamConnection
{
SteamId = steamId,
ConnectionHandle = connectionHandle,
};
connectionsBySteamId64.Add(steamId, connection);
}
}
private void CloseListenSocket()
{
if (listenSocket != 0)
{
Steam.CloseListenSocket(listenSocket);
listenSocket = 0;
}
}
private enum MultiplayerPeerMode {
NONE, SERVER, CLIENT
}
private class SteamPacketPeer {
public byte[] Data { get; private set; } = new byte[MaxSteamPacketSize];
public ulong Sender { get; set; }
public long TransferMode { get; private set; } = Steam.NetworkingSendReliable;
public SteamPacketPeer(byte[] buffer, ulong sender = 0, long transferMode = Steam.NetworkingSendReliable)
{
if (buffer.Length > MaxSteamPacketSize)
{
GD.PrintErr("Error: Tried to send a packet larger than MaxSteamPacketSize");
return;
}
Sender = sender;
Data = buffer;
TransferMode = transferMode;
}
}
private class SteamConnection {
public ulong SteamId { get; set; }
public uint ConnectionHandle { get; set; }
public int PeerId { get; set; } = -1;
List<SteamPacketPeer> pendingRetryPackets = new List<SteamPacketPeer>();
~SteamConnection() {
Steam.CloseConnection(ConnectionHandle, (int) Steam.NetworkingConnectionEnd.AppGeneric, "Disconnect Default!", true);
}
public ErrorResult RawSend(SteamPacketPeer packet) {
Dictionary result = Steam.SendMessageToConnection(ConnectionHandle, packet.Data, packet.TransferMode);
return (ErrorResult) result["result"].AsInt32();
}
public Error SendPending() {
while (pendingRetryPackets.Count > 0) {
var packet = pendingRetryPackets.First();
ErrorResult errorCode = RawSend(packet);
if (errorCode == ErrorResult.Ok) {
pendingRetryPackets.RemoveAt(0);
} else {
string errorString = ConvertErrorResultToString(errorCode);
if ((packet.TransferMode & Steam.NetworkingSendReliable) != 0) {
GD.PrintErr("Send error (reliable, will retry): ", errorString);
break;
} else {
GD.PrintErr("Send error (unreliable, won't retry): ", errorString);
pendingRetryPackets.RemoveAt(0);
}
}
}
return Error.Ok;
}
public void AddPacket(SteamPacketPeer packet) {
pendingRetryPackets.Add(packet);
}
public Error Send(SteamPacketPeer packet) {
AddPacket(packet);
return SendPending();
}
public void Flush() {
if (ConnectionHandle == SteamNetConnectionInvalid) {
return;
}
Steam.FlushMessagesOnConnection(ConnectionHandle);
}
public bool Close() {
if (ConnectionHandle == SteamNetConnectionInvalid) {
return false;
}
return Steam.CloseConnection(ConnectionHandle, (int) Steam.NetworkingConnectionEnd.AppGeneric, "Failed to accept connection", false);
}
public override bool Equals(object obj)
{
return obj is SteamConnection other &&
SteamId == other.SteamId;
}
public override int GetHashCode()
{
return SteamId.GetHashCode();
}
public Error SendPeer(uint peerId) {
SetupPeerPayload payload = new SetupPeerPayload(peerId);
return SendSetupPeer(payload);
}
private Error SendSetupPeer(SetupPeerPayload payload) {
var packet = new SteamPacketPeer(BitConverter.GetBytes(payload.PeerId), transferMode: (long) TransferModeEnum.Reliable);
return Send(packet);
}
string ConvertErrorResultToString(ErrorResult errorResult) {
return errorResult.ToString();
}
struct SetupPeerPayload {
public uint PeerId { get; private set; }
public SetupPeerPayload(uint peerId) {
PeerId = peerId;
}
}
}
}