-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathSteamIntegration.cs
463 lines (398 loc) · 15.5 KB
/
SteamIntegration.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
using Steamworks;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BonelabMultiplayerMockup.Nodes;
using BonelabMultiplayerMockup.Object;
using BonelabMultiplayerMockup.Packets;
using BonelabMultiplayerMockup.Packets.Player;
using BonelabMultiplayerMockup.Representations;
using Discord;
using MelonLoader;
using UnityEngine;
using UnityEngine.SceneManagement;
using Lobby = Steamworks.Data.Lobby;
using Result = Steamworks.Result;
namespace BonelabMultiplayerMockup
{
public class SteamIntegration
{
public static SteamIntegration Instance;
public static uint gameAppId = 480;
public string currentName { get; set; }
public static SteamId currentId { get; set; }
public static bool hasLobby = false;
public static ulong ownerId = 0;
private string ownerIdIdentifier = "ownerId";
private bool connectedToSteam = false;
public static List<ulong> connectedIds = new List<ulong>();
public static Dictionary<SteamId, Friend> userData = new Dictionary<SteamId, Friend>();
public static Dictionary<byte, ulong> byteIds = new Dictionary<byte, ulong>();
public static Dictionary<NetworkChannel, P2PSend> networkChannels = new Dictionary<NetworkChannel, P2PSend>();
public static Dictionary<NetworkChannel, P2PSend> reliableChannels = new Dictionary<NetworkChannel, P2PSend>();
public Lobby currentLobby;
private Lobby hostedMultiplayerLobby;
public static bool isHost = false;
private bool applicationHasQuit = false;
public static byte localByteId = 0;
public static byte lastByteId = 1;
public SteamIntegration()
{
Instance = this;
currentName = "";
// Create client
SteamClient.Init(gameAppId, true);
if (!SteamClient.IsValid)
{
MelonLogger.Msg("Steam client not valid");
throw new Exception();
}
currentName = SteamClient.Name;
currentId = SteamClient.SteamId;
connectedToSteam = true;
MelonLogger.Msg("Steam initialized: " + currentName);
OpenNetworkChannels();
MelonLogger.Msg("Opened network channels");
Instance.Start();
SteamNetworking.AllowP2PPacketRelay(true);
}
public IEnumerator WaitToSendIndexes(SteamId friend)
{
yield return new WaitForSecondsRealtime(3);
MelonLogger.Msg("Sending byte indexes to user!");
foreach (var valuePair in byteIds)
{
if (valuePair.Value == currentId) continue;
var addMessageData = new ShortIdData
{
userId = valuePair.Value,
byteId = valuePair.Key
};
var packetByteBuf =
PacketHandler.CompressMessage(NetworkMessageType.ShortIdUpdatePacket, addMessageData);
SteamPacketNode.BroadcastMessage((byte)NetworkChannel.Reliable, packetByteBuf.getBytes());
}
var idMessageData = new ShortIdData
{
userId = friend,
byteId = RegisterUser(friend)
};
var secondBuff = PacketHandler.CompressMessage(NetworkMessageType.ShortIdUpdatePacket, idMessageData);
SteamPacketNode.BroadcastMessage((byte)NetworkChannel.Reliable, secondBuff.getBytes());
var joinCatchupData = new JoinCatchupData
{
lastId = SyncedObject.lastId,
lastGroupId = SyncedObject.lastGroupId
};
var catchupBuff = PacketHandler.CompressMessage(NetworkMessageType.IdCatchupPacket, joinCatchupData);
SteamPacketNode.SendMessage(friend, (byte)NetworkChannel.Reliable, catchupBuff.getBytes());
}
public static void RegisterUser(byte byteId, ulong longId)
{
if (!byteIds.ContainsKey(byteId))
{
MelonLogger.Msg("Registered "+longId+" as byte: "+byteId);
byteIds.Add(byteId, longId);
}
}
public static void Init()
{
if (Instance == null)
{
SteamIntegration steamIntegration = new SteamIntegration();
}
}
public static void Disconnect(bool fullyShutDown)
{
if (isHost)
{
DiscordRichPresence.lobbyManager.DeleteLobby(DiscordRichPresence.currentLobby.Id, result => { });
DiscordRichPresence.currentLobby = new Discord.Lobby();
DiscordRichPresence.hasLobby = false;
DiscordRichPresence.DefaultRichPresence();
}
else
{
DiscordRichPresence.lobbyManager.DisconnectLobby(DiscordRichPresence.currentLobby.Id, result => { });
DiscordRichPresence.currentLobby = new Discord.Lobby();
DiscordRichPresence.hasLobby = false;
DiscordRichPresence.DefaultRichPresence();
}
hasLobby = false;
isHost = false;
Instance.CleanData();
Instance.LeaveLobby();
if (fullyShutDown)
{
SteamClient.Shutdown();
}
}
public void OpenNetworkChannels()
{
networkChannels.Add(NetworkChannel.Unreliable, P2PSend.Unreliable);
networkChannels.Add(NetworkChannel.Reliable, P2PSend.Reliable);
networkChannels.Add(NetworkChannel.Object, P2PSend.Reliable);
networkChannels.Add(NetworkChannel.Attack, P2PSend.Reliable);
networkChannels.Add(NetworkChannel.Transaction, P2PSend.Reliable);
reliableChannels.Add(NetworkChannel.Reliable, P2PSend.Reliable);
reliableChannels.Add(NetworkChannel.Object, P2PSend.Reliable);
reliableChannels.Add(NetworkChannel.Attack, P2PSend.Reliable);
reliableChannels.Add(NetworkChannel.Transaction, P2PSend.Reliable);
}
public void CleanData()
{
foreach (PlayerRepresentation rep in PlayerRepresentation.representations.Values) {
GameObject.Destroy(rep.playerRep);
}
connectedIds.Clear();
PlayerRepresentation.representations.Clear();
SyncedObject.CleanData();
byteIds.Clear();
userData.Clear();
lastByteId = 0;
localByteId = 0;
BonelabMultiplayerMockup.idsReadyForPlayerInfo = new List<ulong>();
}
public bool ConnectedToSteam()
{
return connectedToSteam;
}
void Start()
{
MelonLogger.Msg("Running start method.");
// Callbacks
SteamMatchmaking.OnLobbyGameCreated += OnLobbyGameCreatedCallback;
SteamMatchmaking.OnLobbyCreated += OnLobbyCreated;
SteamMatchmaking.OnLobbyEntered += OnLobbyEnteredCallback;
SteamMatchmaking.OnLobbyMemberJoined += OnLobbyMemberJoined;
SteamMatchmaking.OnChatMessage += OnChatMessageCallback;
SteamMatchmaking.OnLobbyMemberDisconnected += OnLobbyMemberDisconnectedCallback;
SteamMatchmaking.OnLobbyMemberLeave += OnLobbyMemberLeaveCallback;
SteamFriends.OnGameLobbyJoinRequested += OnInviteClicked;
MelonLogger.Msg("Finished registering start method.");
}
public async Task EstablishThenTerminateConnection()
{
var createLobbyOutput = await SteamMatchmaking.CreateLobbyAsync(10);
if (createLobbyOutput.HasValue)
{
currentLobby = createLobbyOutput.Value;
LeaveLobby();
}
}
public void Update()
{
SteamClient.RunCallbacks();
}
void OnLobbyMemberDisconnectedCallback(Lobby lobby, Friend friend)
{
ProcessMemberLeft(friend);
}
void OnLobbyMemberLeaveCallback(Lobby lobby, Friend friend)
{
ProcessMemberLeft(friend);
}
private void ProcessMemberLeft(Friend friend)
{
if (friend.Id != currentId)
{
DiscordRichPresence.activity.Party.Size.CurrentSize -= 1;
DiscordRichPresence.UpdateActivity();
try
{
PlayerRepresentation playerRepresentation = PlayerRepresentation.representations[friend.Id];
playerRepresentation.DeleteRepresentation();
connectedIds.Remove(friend.Id);
userData.Remove(friend.Id);
byteIds.Remove(GetByteId(friend.Id));
SteamNetworking.CloseP2PSessionWithUser(friend.Id);
}
catch
{
MelonLogger.Msg("Unable to update disconnected player nameplate / process disconnect cleanly");
}
}
}
void OnLobbyGameCreatedCallback(Lobby lobby, uint ip, ushort port, SteamId steamId)
{
// MelonLogger.Msg("Created game.");
}
private void AcceptP2P(SteamId playerId)
{
try
{
SteamNetworking.AcceptP2PSessionWithUser(playerId);
}
catch
{
MelonLogger.Msg("Unable to accept P2P Session with user");
}
}
void OnChatMessageCallback(Lobby lobby, Friend friend, string message)
{
if (friend.Id != currentId)
{
MelonLogger.Msg("incoming chat message");
MelonLogger.Msg(message);
}
}
void OnLobbyEnteredCallback(Lobby lobby)
{
if (lobby.MemberCount !=
1)
{
ownerId = ulong.Parse(lobby.GetData(ownerIdIdentifier));
hasLobby = true;
lobby.SendChatString("I have connected to the lobby!");
currentLobby = lobby;
HandlePlayerConnection(new Friend(ownerId));
foreach (var connectedFriend in currentLobby.Members)
{
if (connectedFriend.Id != currentId)
{
HandlePlayerConnection(connectedFriend);
}
}
}
}
async void OnInviteClicked(Lobby joinedLobby, SteamId id)
{
RoomEnter joinedLobbySuccess = await joinedLobby.Join();
if (joinedLobbySuccess != RoomEnter.Success)
{
MelonLogger.Error("Lobby could not be joined.");
}
else
{
isHost = false;
hasLobby = true;
MelonLogger.Msg("Joined lobby.");
currentLobby = joinedLobby;
}
}
void OnLobbyCreated(Result result, Lobby lobby)
{
if (result != Result.OK)
{
MelonLogger.Msg("lobby creation result not ok");
MelonLogger.Msg(result.ToString());
}
else
{
MelonLogger.Msg("Created lobby successfully");
isHost = true;
hasLobby = true;
}
}
void OnLobbyMemberJoined(Lobby lobby, Friend friend)
{
// Not us, means its another player.
if (friend.Id != currentId)
{
if (isHost)
{
MelonCoroutines.Start(WaitToSendIndexes(friend.Id));
}
DiscordRichPresence.activity.Party.Size.CurrentSize = 1 + DiscordRichPresence.activity.Party.Size.CurrentSize;
DiscordRichPresence.UpdateActivity();
MelonLogger.Msg(friend.Name+" has joined the lobby.");
HandlePlayerConnection(friend);
// Send byte indexing data if we are currently the host.
}
}
public static byte RegisterUser(ulong userId)
{
var byteId = lastByteId++;
RegisterUser(byteId, userId);
return byteId;
}
public void HandlePlayerConnection(Friend friend)
{
if (connectedIds.Contains(friend.Id))
return;
MelonLogger.Msg("Added "+friend.Name+" to connected users.");
connectedIds.Add(friend.Id);
MelonLogger.Msg("Fetched user: "+friend.Name);
if (!PlayerRepresentation.representations.ContainsKey(friend.Id))
{
PlayerRepresentation.representations.Add(friend.Id, new PlayerRepresentation(friend));
}
MelonLogger.Msg("Added representation");
userData.Add(friend.Id, friend);
MelonLogger.Msg("Added userdata");
AcceptP2P(friend.Id);
}
private void LeaveLobby()
{
isHost = false;
hasLobby = false;
try
{
currentLobby.Leave();
}
catch
{
MelonLogger.Error("Error leaving current lobby");
return;
}
try
{
foreach (SteamId connectedId in connectedIds) {
SteamNetworking.CloseP2PSessionWithUser(connectedId);
}
connectedIds.Clear();
userData.Clear();
Instance.CleanData();
}
catch
{
MelonLogger.Error("Something went wrong when a P2P session was trying to be closed.");
}
}
public async Task CreateLobby()
{
if (hasLobby)
{
MelonLogger.Msg("Already in a lobby! Cannot create another one.");
return;
}
try
{
var createLobbyOutput = await SteamMatchmaking.CreateLobbyAsync(10);
if (!createLobbyOutput.HasValue)
{
MelonLogger.Error("Lobby was not created properly!");
return;
}
hostedMultiplayerLobby = createLobbyOutput.Value;
hostedMultiplayerLobby.SetJoinable(true);
hostedMultiplayerLobby.SetFriendsOnly();
hostedMultiplayerLobby.SetData(ownerIdIdentifier, currentId.ToString());
currentLobby = hostedMultiplayerLobby;
isHost = true;
hasLobby = true;
MelonLogger.Msg("Created lobby.");
DiscordRichPresence.MakeDiscordLobby();
}
catch (Exception exception)
{
MelonLogger.Msg("Failed to create multiplayer lobby");
MelonLogger.Msg(exception.ToString());
}
}
public static byte GetByteId(SteamId longId) {
if (longId == currentId) return localByteId;
return byteIds.FirstOrDefault(o => o.Value == longId).Key;
}
public static SteamId GetLongId(byte shortId) {
if (shortId == 0) return ownerId;
if (byteIds.ContainsKey(shortId))
{
return byteIds[shortId];
}
return 1278;
}
}
}