-
Notifications
You must be signed in to change notification settings - Fork 54
/
EOSLobbyManager.cs
2242 lines (1838 loc) · 88.5 KB
/
EOSLobbyManager.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
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
/*
* Copyright (c) 2021 PlayEveryWare
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System;
using System.Collections.Generic;
using UnityEngine;
using Epic.OnlineServices;
using Epic.OnlineServices.Lobby;
using Epic.OnlineServices.RTC;
using Epic.OnlineServices.RTCAudio;
namespace PlayEveryWare.EpicOnlineServices.Samples
{
/// <summary>
/// Class represents all Lobby properties
/// </summary>
public class Lobby
{
public string Id;
public ProductUserId LobbyOwner = new ProductUserId();
public EpicAccountId LobbyOwnerAccountId = new EpicAccountId();
public string LobbyOwnerDisplayName;
public string BucketId;
public uint MaxNumLobbyMembers = 0;
public LobbyPermissionLevel LobbyPermissionLevel = LobbyPermissionLevel.Publicadvertised;
public uint AvailableSlots = 0;
public bool AllowInvites = true;
// Cached copy of the RoomName of the RTC room that our lobby has, if any
public string RTCRoomName = string.Empty;
// Are we currently connected to an RTC room?
public bool RTCRoomConnected = false;
/** Notification for RTC connection status changes */
public NotifyEventHandle RTCRoomConnectionChanged; // EOS_INVALID_NOTIFICATIONID;
/** Notification for RTC room participant updates (new players or players leaving) */
public NotifyEventHandle RTCRoomParticipantUpdate; // EOS_INVALID_NOTIFICATIONID;
/** Notification for RTC audio updates (talking status or mute changes) */
public NotifyEventHandle RTCRoomParticipantAudioUpdate; // EOS_INVALID_NOTIFICATIONID;
public bool PresenceEnabled = false;
public bool RTCRoomEnabled = false;
public List<LobbyAttribute> Attributes = new List<LobbyAttribute>();
public List<LobbyMember> Members = new List<LobbyMember>();
// Utility data
public bool _SearchResult = false;
public bool _BeingCreated = false;
/// <summary>
/// Checks if Lobby Id is valid
/// </summary>
/// <returns>True if valid</returns>
public bool IsValid()
{
return !string.IsNullOrEmpty(Id);
}
/// <summary>
/// Checks if the specified <c>ProductUserId</c> is the current owner
/// </summary>
/// <param name="userProductId">Specified <c>ProductUserId</c></param>
/// <returns>True if specified user is owner</returns>
public bool IsOwner(ProductUserId userProductId)
{
return userProductId == LobbyOwner;
}
/// <summary>
/// Clears local cache of Lobby Id, owner, attributes and members
/// </summary>
public void Clear()
{
Id = string.Empty;
LobbyOwner = new ProductUserId();
Attributes.Clear();
Members.Clear();
}
/// <summary>
/// Initializing the given Lobby Id and caches all relevant attributes
/// </summary>
/// <param name="lobbyId">Specified Lobby Id</param>
public void InitFromLobbyHandle(string lobbyId)
{
if (string.IsNullOrEmpty(lobbyId))
{
return;
}
Id = lobbyId;
CopyLobbyDetailsHandleOptions options = new CopyLobbyDetailsHandleOptions();
options.LobbyId = Id;
options.LocalUserId = EOSManager.Instance.GetProductUserId();
Result result = EOSManager.Instance.GetEOSLobbyInterface().CopyLobbyDetailsHandle(options, out LobbyDetails outLobbyDetailsHandle);
if (result != Result.Success)
{
Debug.LogErrorFormat("Lobbies (InitFromLobbyHandle): can't get lobby info handle. Error code: {0}", result);
return;
}
if (outLobbyDetailsHandle == null)
{
Debug.LogError("Lobbies (InitFromLobbyHandle): can't get lobby info handle. outLobbyDetailsHandle is null");
return;
}
InitFromLobbyDetails(outLobbyDetailsHandle);
}
/// <summary>
/// Initializing the given <c>LobbyDetails</c> handle and caches all relevant attributes
/// </summary>
/// <param name="lobbyId">Specified <c>LobbyDetails</c> handle</param>
public void InitFromLobbyDetails(LobbyDetails outLobbyDetailsHandle)
{
// get owner
ProductUserId newLobbyOwner = outLobbyDetailsHandle.GetLobbyOwner(new LobbyDetailsGetLobbyOwnerOptions());
if (newLobbyOwner != LobbyOwner)
{
LobbyOwner = newLobbyOwner;
LobbyOwnerAccountId = new EpicAccountId();
LobbyOwnerDisplayName = string.Empty;
}
// copy lobby info
Result infoResult = outLobbyDetailsHandle.CopyInfo(new LobbyDetailsCopyInfoOptions(), out LobbyDetailsInfo outLobbyDetailsInfo);
if (infoResult != Result.Success)
{
Debug.LogErrorFormat("Lobbies (InitFromLobbyDetails): can't copy lobby info. Error code: {0}", infoResult);
return;
}
if (outLobbyDetailsInfo == null)
{
Debug.LogError("Lobbies: (InitFromLobbyDetails) could not copy info: outLobbyDetailsInfo is null.");
return;
}
Id = outLobbyDetailsInfo.LobbyId;
MaxNumLobbyMembers = outLobbyDetailsInfo.MaxMembers;
LobbyPermissionLevel = outLobbyDetailsInfo.PermissionLevel;
AllowInvites = outLobbyDetailsInfo.AllowInvites;
AvailableSlots = outLobbyDetailsInfo.AvailableSlots;
BucketId = outLobbyDetailsInfo.BucketId;
RTCRoomEnabled = outLobbyDetailsInfo.RTCRoomEnabled;
// get attributes
Attributes.Clear();
uint attrCount = outLobbyDetailsHandle.GetAttributeCount(new LobbyDetailsGetAttributeCountOptions());
for (uint i = 0; i < attrCount; i++)
{
LobbyDetailsCopyAttributeByIndexOptions attrOptions = new LobbyDetailsCopyAttributeByIndexOptions();
attrOptions.AttrIndex = i;
Result copyAttrResult = outLobbyDetailsHandle.CopyAttributeByIndex(attrOptions, out Epic.OnlineServices.Lobby.Attribute outAttribute);
if (copyAttrResult == Result.Success && outAttribute != null && outAttribute.Data != null)
{
LobbyAttribute attr = new LobbyAttribute();
attr.InitFromAttribute(outAttribute);
Attributes.Add(attr);
}
}
// get members
List<LobbyMember> OldMembers = new List<LobbyMember>(Members);
Members.Clear();
uint memberCount = outLobbyDetailsHandle.GetMemberCount(new LobbyDetailsGetMemberCountOptions());
for (int memberIndex = 0; memberIndex < memberCount; memberIndex++)
{
ProductUserId memberId = outLobbyDetailsHandle.GetMemberByIndex(new LobbyDetailsGetMemberByIndexOptions() { MemberIndex = (uint)memberIndex });
Members.Insert((int)memberIndex, new LobbyMember() { ProductId = memberId });
// member attributes
int memberAttributeCount = (int)outLobbyDetailsHandle.GetMemberAttributeCount(new LobbyDetailsGetMemberAttributeCountOptions() { TargetUserId = memberId });
for (int attributeIndex = 0; attributeIndex < memberAttributeCount; attributeIndex++)
{
Result memberAttributeResult = outLobbyDetailsHandle.CopyMemberAttributeByIndex(new LobbyDetailsCopyMemberAttributeByIndexOptions() { AttrIndex = (uint)attributeIndex, TargetUserId = memberId }, out Epic.OnlineServices.Lobby.Attribute outAttribute);
if (memberAttributeResult != Result.Success)
{
Debug.LogFormat("Lobbies (InitFromLobbyDetails): can't copy member attribute. Error code: {0}", memberAttributeResult);
continue;
}
LobbyAttribute newAttribute = new LobbyAttribute();
newAttribute.InitFromAttribute(outAttribute);
Members[memberIndex].MemberAttributes.Add(newAttribute.Key, newAttribute);
}
// Copy RTC Status from old members
foreach(LobbyMember oldLobbyMember in OldMembers)
{
LobbyMember newMember = Members[memberIndex];
if(oldLobbyMember.ProductId != newMember.ProductId)
{
continue;
}
// Copy RTC status to new object
newMember.RTCState = oldLobbyMember.RTCState;
break;
}
}
}
}
/// <summary>
/// Class represents all Lobby Invite properties
/// </summary>
public class LobbyInvite
{
public Lobby Lobby = new Lobby();
public LobbyDetails LobbyInfo = new LobbyDetails();
public ProductUserId FriendId;
public EpicAccountId FriendEpicId;
public string FriendDisplayName;
public string InviteId;
public bool IsValid()
{
return Lobby.IsValid();
}
public void Clear()
{
Lobby.Clear();
LobbyInfo.Release();
FriendId = new ProductUserId();
FriendEpicId = new EpicAccountId();
FriendDisplayName = string.Empty;
InviteId = string.Empty;
}
}
/// <summary>
/// Class represents all Lobby Attribute properties
/// </summary>
public class LobbyAttribute
{
public LobbyAttributeVisibility Visibility = LobbyAttributeVisibility.Public;
public AttributeType ValueType = AttributeType.String;
public string Key;
//Only one of the following properties will have valid data (depending on 'ValueType')
public long? AsInt64 = 0;
public double? AsDouble = 0.0;
public bool? AsBool = false;
public string AsString;
public AttributeData AsAttribute
{
get
{
AttributeData attrData = new AttributeData();
attrData.Key = Key;
attrData.Value = new AttributeDataValue();
switch (ValueType)
{
case AttributeType.String:
attrData.Value.AsUtf8 = AsString;
break;
case AttributeType.Int64:
attrData.Value.AsInt64 = AsInt64;
break;
case AttributeType.Double:
attrData.Value.AsDouble = AsDouble;
break;
case AttributeType.Boolean:
attrData.Value.AsBool = AsBool;
break;
}
return attrData;
}
}
public override bool Equals(object other)
{
LobbyAttribute lobbyAttr = (LobbyAttribute)other;
return ValueType == lobbyAttr.ValueType &&
AsInt64 == lobbyAttr.AsInt64 &&
AsDouble == lobbyAttr.AsDouble &&
AsBool == lobbyAttr.AsBool &&
AsString == lobbyAttr.AsString &&
Key == lobbyAttr.Key &&
Visibility == lobbyAttr.Visibility;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public void InitFromAttribute(Epic.OnlineServices.Lobby.Attribute attributeParam)
{
Key = attributeParam.Data.Key;
ValueType = attributeParam.Data.Value.ValueType;
switch (attributeParam.Data.Value.ValueType)
{
case AttributeType.Boolean:
AsBool = attributeParam.Data.Value.AsBool;
break;
case AttributeType.Int64:
AsInt64 = attributeParam.Data.Value.AsInt64;
break;
case AttributeType.Double:
AsDouble = attributeParam.Data.Value.AsDouble;
break;
case AttributeType.String:
AsString = attributeParam.Data.Value.AsUtf8;
break;
}
}
}
/// <summary>
/// Class represents all Lobby Member properties
/// </summary>
public class LobbyMember
{
public EpicAccountId AccountId;
public ProductUserId ProductId;
public string DisplayName;
public Dictionary<string, LobbyAttribute> MemberAttributes = new Dictionary<string, LobbyAttribute>();
public LobbyRTCState RTCState = new LobbyRTCState();
}
/// <summary>
/// Class represents RTC State (Voice) of a Lobby
/// </summary>
public class LobbyRTCState
{
// Is this person currently connected to the RTC room?
public bool IsInRTCRoom = false;
// Is this person currently talking (audible sounds from their audio output)
public bool IsTalking = false;
// We have locally muted this person (others can still hear them)
public bool IsLocalMuted = false;
// Has this person muted their own audio output (nobody can hear them)
public bool IsAudioOutputDisabled = false;
// Are we currently muting this person?
public bool MuteActionInProgress = false;
}
/// <summary>
/// Class represents a request to Join a lobby
/// </summary>
public class LobbyJoinRequest
{
string Id = string.Empty;
LobbyDetails LobbyInfo = new LobbyDetails();
public bool IsValid()
{
return !string.IsNullOrEmpty(Id);
}
public void Clear()
{
Id = string.Empty;
LobbyInfo = new LobbyDetails();
}
}
/// <summary>
/// Class <c>EOSLobbyManager</c> is a simplified wrapper for EOS [Lobby Interface](https://dev.epicgames.com/docs/services/en-US/Interfaces/Lobby/index.html).
/// </summary>
public class EOSLobbyManager : IEOSSubManager
{
private Lobby CurrentLobby;
private LobbyJoinRequest ActiveJoin;
// Pending invites (up to one invite per friend)
private Dictionary<ProductUserId, LobbyInvite> Invites;
private LobbyInvite CurrentInvite;
// Search
private LobbySearch CurrentSearch;
private Dictionary<Lobby, LobbyDetails> SearchResults;
//NotificationId
private NotifyEventHandle LobbyUpdateNotification;
private NotifyEventHandle LobbyMemberUpdateNotification;
private NotifyEventHandle LobbyMemberStatusNotification;
private NotifyEventHandle LobbyInviteNotification;
private NotifyEventHandle LobbyInviteAcceptedNotification;
private NotifyEventHandle JoinLobbyAcceptedNotification;
// TODO: Does this constant exist in the EOS SDK C# Wrapper?
private const ulong EOS_INVALID_NOTIFICATIONID = 0;
public bool _Dirty = true;
// Manager Callbacks
private OnLobbyCallback LobbyCreatedCallback;
private OnLobbyCallback LobbyModifyCallback;
private OnLobbyCallback JoinLobbyCallback;
private OnLobbyCallback LeaveLobbyCallback;
private OnLobbyCallback DestroyLobbyCallback;
private OnLobbyCallback ToggleMuteCallback;
private OnLobbyCallback KickMemberCallback;
private OnLobbyCallback PromoteMemberCallback;
private OnLobbySearchCallback LobbySearchCallback;
public delegate void OnLobbyCallback(Result result);
public delegate void OnLobbySearchCallback(Result result);
// Init
public EOSLobbyManager()
{
CurrentLobby = new Lobby();
ActiveJoin = new LobbyJoinRequest();
Invites = new Dictionary<ProductUserId, LobbyInvite>();
CurrentInvite = null;
CurrentSearch = new LobbySearch();
SearchResults = new Dictionary<Lobby, LobbyDetails>();
SubscribeToLobbyUpdates();
SubscribeToLobbyInvites();
LobbyCreatedCallback = null;
LobbyModifyCallback = null;
JoinLobbyCallback = null;
LeaveLobbyCallback = null;
LobbySearchCallback = null;
}
public Lobby GetCurrentLobby()
{
return CurrentLobby;
}
public Dictionary<ProductUserId, LobbyInvite> GetInvites()
{
return Invites;
}
public LobbyInvite GetCurrentInvite()
{
return CurrentInvite;
}
public LobbySearch GetCurrentSearch()
{
return CurrentSearch;
}
public Dictionary<Lobby, LobbyDetails> GetSearchResults()
{
return SearchResults;
}
private bool IsLobbyNotificationValid(NotifyEventHandle handle)
{
return handle != null && handle.IsValid();
}
private void SubscribeToLobbyUpdates()
{
if(IsLobbyNotificationValid(LobbyUpdateNotification) ||
IsLobbyNotificationValid(LobbyMemberUpdateNotification) ||
IsLobbyNotificationValid(LobbyMemberStatusNotification))
{
Debug.LogError("Lobbies (SubscribeToLobbyUpdates): SubscribeToLobbyUpdates called but already subscribed!");
return;
}
var lobbyInterface = EOSManager.Instance.GetEOSLobbyInterface();
LobbyUpdateNotification = new NotifyEventHandle(lobbyInterface.AddNotifyLobbyUpdateReceived(new AddNotifyLobbyUpdateReceivedOptions(), null, OnLobbyUpdateReceived), (ulong handle) =>
{
EOSManager.Instance.GetEOSLobbyInterface().RemoveNotifyLobbyUpdateReceived(handle);
});
LobbyMemberUpdateNotification = new NotifyEventHandle(lobbyInterface.AddNotifyLobbyMemberUpdateReceived(new AddNotifyLobbyMemberUpdateReceivedOptions(), null, OnMemberUpdateReceived), (ulong handle) =>
{
EOSManager.Instance.GetEOSLobbyInterface().RemoveNotifyLobbyMemberUpdateReceived(handle);
});
LobbyMemberStatusNotification = new NotifyEventHandle(lobbyInterface.AddNotifyLobbyMemberStatusReceived(new AddNotifyLobbyMemberStatusReceivedOptions(), null, OnMemberStatusReceived), (ulong handle) =>
{
EOSManager.Instance.GetEOSLobbyInterface().RemoveNotifyLobbyMemberStatusReceived(handle);
});
}
private void UnsubscribeFromLobbyUpdates()
{
LobbyUpdateNotification.Dispose();
LobbyMemberUpdateNotification.Dispose();
LobbyMemberStatusNotification.Dispose();
}
//-------------------------------------------------------------------------
private void SubscribeToLobbyInvites()
{
if (IsLobbyNotificationValid(LobbyInviteNotification) ||
IsLobbyNotificationValid(LobbyInviteAcceptedNotification) ||
IsLobbyNotificationValid(JoinLobbyAcceptedNotification) )
{
Debug.LogError("Lobbies (SubscribeToLobbyInvites): SubscribeToLobbyInvites called but already subscribed!");
return;
}
var lobbyInterface = EOSManager.Instance.GetEOSLobbyInterface();
LobbyInviteNotification = new NotifyEventHandle(lobbyInterface.AddNotifyLobbyInviteReceived(new AddNotifyLobbyInviteReceivedOptions(), null, OnLobbyInviteReceived), (ulong handle) =>
{
EOSManager.Instance.GetEOSLobbyInterface().RemoveNotifyLobbyInviteReceived(handle);
});
LobbyInviteAcceptedNotification = new NotifyEventHandle(lobbyInterface.AddNotifyLobbyInviteAccepted(new AddNotifyLobbyInviteAcceptedOptions(), null, OnLobbyInviteAccepted), (ulong handle) =>
{
EOSManager.Instance.GetEOSLobbyInterface().RemoveNotifyLobbyInviteAccepted(handle);
});
JoinLobbyAcceptedNotification = new NotifyEventHandle(lobbyInterface.AddNotifyJoinLobbyAccepted(new AddNotifyJoinLobbyAcceptedOptions(), null, OnJoinLobbyAccepted), (ulong handle) =>
{
EOSManager.Instance.GetEOSLobbyInterface().RemoveNotifyJoinLobbyAccepted(handle);
});
}
//-------------------------------------------------------------------------
private void UnsubscribeFromLobbyInvites()
{
LobbyInviteNotification.Dispose();
LobbyInviteAcceptedNotification.Dispose();
JoinLobbyAcceptedNotification.Dispose();
}
private string GetRTCRoomName()
{
GetRTCRoomNameOptions options = new GetRTCRoomNameOptions()
{
LobbyId = CurrentLobby.Id,
LocalUserId = EOSManager.Instance.GetProductUserId()
};
Result result = EOSManager.Instance.GetEOSLobbyInterface().GetRTCRoomName(options, out string roomName);
if(result != Result.Success)
{
Debug.LogFormat("Lobbies (GetRTCRoomName): Could not get RTC Room Name. Error Code: {0}", result);
return string.Empty;
}
Debug.LogFormat("Lobbies (GetRTCRoomName): Found RTC Room Name for lobby. RooName={0}", roomName);
return roomName;
}
private void UnsubscribeFromRTCEvents()
{
if(!CurrentLobby.RTCRoomEnabled)
{
return;
}
CurrentLobby.RTCRoomParticipantAudioUpdate.Dispose();
CurrentLobby.RTCRoomParticipantUpdate.Dispose();
CurrentLobby.RTCRoomConnectionChanged.Dispose();
CurrentLobby.RTCRoomName = string.Empty;
}
private void SubscribeToRTCEvents()
{
if(!CurrentLobby.RTCRoomEnabled)
{
Debug.LogWarning("Lobbies (SubscribeToRTCEvents): RTC Room is disabled.");
return;
}
CurrentLobby.RTCRoomName = GetRTCRoomName();
if(string.IsNullOrEmpty(CurrentLobby.RTCRoomName))
{
Debug.LogError("Lobbies (SubscribeToRTCEvents): Unable to bind to RTC Room Name, failing to bind delegates.");
return;
}
LobbyInterface lobbyInterface = EOSManager.Instance.GetEOSLobbyInterface();
// Register for connection status changes
AddNotifyRTCRoomConnectionChangedOptions addNotifyRTCRoomConnectionChangedOptions = new AddNotifyRTCRoomConnectionChangedOptions()
{
LobbyId = CurrentLobby.Id,
LocalUserId = EOSManager.Instance.GetProductUserId()
};
CurrentLobby.RTCRoomConnectionChanged = new NotifyEventHandle(lobbyInterface.AddNotifyRTCRoomConnectionChanged(addNotifyRTCRoomConnectionChangedOptions, null, OnRTCRoomConnectionChangedReceived), (ulong handle) =>
{
EOSManager.Instance.GetEOSLobbyInterface().RemoveNotifyRTCRoomConnectionChanged(handle);
});
if(!CurrentLobby.RTCRoomConnectionChanged.IsValid())
{
Debug.LogError("Lobbies (SubscribeToRTCEvents): Failed to bind to Lobby NotifyRTCRoomConnectionChanged notification.");
}
// Get the current room connection status now that we're listening for changes
IsRTCRoomConnectedOptions isRTCRoomConnectedOptions = new IsRTCRoomConnectedOptions()
{
LobbyId = CurrentLobby.Id,
LocalUserId = EOSManager.Instance.GetProductUserId()
};
Result result = lobbyInterface.IsRTCRoomConnected(isRTCRoomConnectedOptions, out bool isConnected);
if (result != Result.Success)
{
Debug.LogFormat("Lobbies (SubscribeToRTCEvents): Failed to get RTC Room connection status:. Error Code: {0}", result);
}
else
{
CurrentLobby.RTCRoomConnected = isConnected;
}
RTCInterface rtcHandle = EOSManager.Instance.GetEOSRTCInterface();
RTCAudioInterface rtcAudioHandle = rtcHandle.GetAudioInterface();
// Register for RTC Room participant changes
AddNotifyParticipantStatusChangedOptions addNotifyParticipantsStatusChangedOptions = new AddNotifyParticipantStatusChangedOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
RoomName = CurrentLobby.RTCRoomName
};
CurrentLobby.RTCRoomParticipantUpdate = new NotifyEventHandle(rtcHandle.AddNotifyParticipantStatusChanged(addNotifyParticipantsStatusChangedOptions, null, OnRTCRoomParticipantStatusChanged), (ulong handle) =>
{
EOSManager.Instance.GetEOSRTCInterface().RemoveNotifyParticipantStatusChanged(handle);
});
if(!CurrentLobby.RTCRoomParticipantUpdate.IsValid())
{
Debug.LogError("Lobbies (SubscribeToRTCEvents): Failed to bind to RTC AddNotifyParticipantStatusChanged notification.");
}
// Register for talking changes
AddNotifyParticipantUpdatedOptions addNotifyParticipantUpdatedOptions = new AddNotifyParticipantUpdatedOptions()
{
LocalUserId = EOSManager.Instance.GetProductUserId(),
RoomName = CurrentLobby.RTCRoomName
};
CurrentLobby.RTCRoomParticipantAudioUpdate = new NotifyEventHandle(rtcAudioHandle.AddNotifyParticipantUpdated(addNotifyParticipantUpdatedOptions, null, OnRTCRoomParticipantAudioUpdateRecieved), (ulong handle) =>
{
EOSManager.Instance.GetEOSRTCInterface().GetAudioInterface().RemoveNotifyParticipantUpdated(handle);
});
}
private void OnRTCRoomConnectionChangedReceived(RTCRoomConnectionChangedCallbackInfo data)
{
if (data == null)
{
Debug.LogError("Lobbies (OnRTCRoomConnectionChangedReceived): RTCRoomConnectionChangedCallbackInfo data is null");
return;
}
Debug.LogFormat("Lobbies (OnRTCRoomConnectionChangedReceived): connection status changed. LobbyId={0}, IsConnected={1}, DisconnectReason={2}", data.LobbyId, data.IsConnected, data.DisconnectReason);
// OnRTCRoomConnectionChanged
if(!CurrentLobby.IsValid() || CurrentLobby.Id != data.LobbyId)
{
return;
}
if(EOSManager.Instance.GetLocalUserId() != data.LocalUserId)
{
return;
}
CurrentLobby.RTCRoomConnected = data.IsConnected;
foreach(LobbyMember lobbyMember in CurrentLobby.Members)
{
if(lobbyMember.ProductId == EOSManager.Instance.GetProductUserId())
{
lobbyMember.RTCState.IsInRTCRoom = data.IsConnected;
if(!data.IsConnected)
{
lobbyMember.RTCState.IsTalking = false;
}
break;
}
}
_Dirty = true;
}
private void OnRTCRoomParticipantStatusChanged(ParticipantStatusChangedCallbackInfo data)
{
if (data == null)
{
Debug.LogError("Lobbies (OnRTCRoomParticipantStatusChanged): ParticipantStatusChangedCallbackInfo data is null");
return;
}
int metadataCount = 0;
if (data.ParticipantMetadata != null)
{
metadataCount = data.ParticipantMetadata.Length;
}
Debug.LogFormat("Lobbies (OnRTCRoomParticipantStatusChanged): LocalUserId={0}, Room={1}, ParticipantUserId={2}, ParticipantStatus={3}, MetadataCount={4}",
data.LocalUserId,
data.RoomName,
data.ParticipantId,
data.ParticipantStatus == RTCParticipantStatus.Joined ? "Joined" : "Left",
metadataCount);
// Ensure this update is for our room
if (string.IsNullOrEmpty(CurrentLobby.RTCRoomName) || CurrentLobby.RTCRoomName.Equals(data.RoomName, StringComparison.OrdinalIgnoreCase))
{
return;
}
//OnRTCRoomParticipantJoined / OnRTCRoomParticipantLeft
// Find this participant in our list
foreach (LobbyMember lobbyMember in CurrentLobby.Members)
{
if(lobbyMember.ProductId != data.ParticipantId)
{
continue;
}
// Update in-room status
if (data.ParticipantStatus == RTCParticipantStatus.Joined)
{
lobbyMember.RTCState.IsInRTCRoom = true;
}
else
{
lobbyMember.RTCState.IsInRTCRoom = false;
lobbyMember.RTCState.IsTalking = false;
}
_Dirty = true;
break;
}
}
private void OnRTCRoomParticipantAudioUpdateRecieved(ParticipantUpdatedCallbackInfo data)
{
if (data == null)
{
Debug.LogError("Lobbies (OnRTCRoomParticipantAudioUpdateRecieved): ParticipantUpdatedCallbackInfo data is null");
return;
}
/* Verbose Logging: Uncomment to print each time audio is received.
Debug.LogFormat("Lobbies (OnRTCRoomParticipantAudioUpdateRecieved): participant audio updated. LocalUserId={0}, Room={1}, ParticipantUserId={2}, IsTalking={3}, IsAudioDisabled={4}",
data.LocalUserId,
data.RoomName,
data.ParticipantId,
data.Speaking,
data.AudioStatus != RTCAudioStatus.Enabled);
*/
// OnRTCRoomParticipantAudioUpdated
// Ensure this update is for our room
if (string.IsNullOrEmpty(CurrentLobby.RTCRoomName) || !CurrentLobby.RTCRoomName.Equals(data.RoomName, StringComparison.OrdinalIgnoreCase))
{
return;
}
// Find this participant in our list
foreach(LobbyMember lobbyMember in CurrentLobby.Members)
{
if(lobbyMember.ProductId != data.ParticipantId)
{
continue;
}
// Update talking status
if(lobbyMember.RTCState.IsTalking != data.Speaking)
{
lobbyMember.RTCState.IsTalking = data.Speaking;
}
// Only update the audio status for other players (we control their own status)
if(lobbyMember.ProductId != EOSManager.Instance.GetProductUserId())
{
lobbyMember.RTCState.IsAudioOutputDisabled = data.AudioStatus != RTCAudioStatus.Enabled;
}
_Dirty = true;
break;
}
}
/// <summary>User Logged In actions</summary>
/// <list type="bullet">
/// <item><description>Reset local cache for Invites</description></item>
/// </list>
public void OnLoggedIn()
{
_Dirty = true;
CurrentInvite = null;
}
/// <summary>User Logged Out actions</summary>
/// <list type="bullet">
/// <item><description>Leaves current lobby</description></item>
/// <item><description>Unsubscribe from Lobby invites and updates</description></item>
/// <item><description>Reset local cache for <c>Lobby</c>, <c>LobbyJoinRequest</c>, Invites, <c>LobbySearch</c> and </description></item>
/// </list>
public void OnLoggedOut()
{
LeaveLobby(null);
UnsubscribeFromLobbyInvites();
UnsubscribeFromLobbyUpdates();
CurrentLobby = new Lobby();
ActiveJoin = new LobbyJoinRequest();
Invites.Clear();
CurrentInvite = null;
CurrentSearch = new LobbySearch();
SearchResults.Clear();
}
/// <summary>
/// Wrapper for calling [EOS_Lobby_CreateLobby](https://dev.epicgames.com/docs/services/en-US/API/Members/Functions/Lobby/EOS_Lobby_CreateLobby/index.html)
/// </summary>
/// <param name="lobbyProperties"><b>Lobby</b> properties used to create new lobby</param>
/// <param name="CreateLobbyCompleted">Callback when create lobby is completed</param>
public void CreateLobby(Lobby lobbyProperties, OnLobbyCallback CreateLobbyCompleted)
{
ProductUserId currentUserProductId = EOSManager.Instance.GetProductUserId();
if (!currentUserProductId.IsValid())
{
Debug.LogError("Lobbies (CreateLobby): Current player is invalid!");
CreateLobbyCompleted?.Invoke(Result.InvalidProductUserID);
return;
}
// Check if there is current session. Leave it.
if (CurrentLobby.IsValid())
{
Debug.LogWarningFormat("Lobbies (Create Lobby): Leaving Current Lobby '{0}'", CurrentLobby.Id);
LeaveLobby(null);
}
// Create new lobby
// Max Players
CreateLobbyOptions createLobbyOptions = new CreateLobbyOptions();
createLobbyOptions.LocalUserId = currentUserProductId;
createLobbyOptions.MaxLobbyMembers = lobbyProperties.MaxNumLobbyMembers;
createLobbyOptions.PermissionLevel = lobbyProperties.LobbyPermissionLevel;
createLobbyOptions.PresenceEnabled = lobbyProperties.PresenceEnabled;
createLobbyOptions.AllowInvites = lobbyProperties.AllowInvites;
createLobbyOptions.BucketId = lobbyProperties.BucketId;
// Voice Chat
if(lobbyProperties.RTCRoomEnabled)
{
LocalRTCOptions rtcOptions = new LocalRTCOptions()
{
Flags = 0, //EOS_RTC_JOINROOMFLAGS_ENABLE_ECHO;
UseManualAudioInput = false,
UseManualAudioOutput = false,
LocalAudioDeviceInputStartsMuted = false
};
createLobbyOptions.EnableRTCRoom = true;
createLobbyOptions.LocalRTCOptions = rtcOptions;
}
else
{
createLobbyOptions.EnableRTCRoom = false;
createLobbyOptions.LocalRTCOptions = null;
}
// Note: Attributes are handled in ModifyLobby
LobbyCreatedCallback = CreateLobbyCompleted;
EOSManager.Instance.GetEOSLobbyInterface().CreateLobby(createLobbyOptions, null, OnCreateLobbyCompleted);
// Save lobby data for modification
CurrentLobby = lobbyProperties;
CurrentLobby._BeingCreated = true;
CurrentLobby.LobbyOwner = currentUserProductId;
}
/// <summary>
/// Wrapper for calling [EOS_Lobby_UpdateLobby](https://dev.epicgames.com/docs/services/en-US/API/Members/Functions/Lobby/EOS_Lobby_UpdateLobby/index.html)
/// </summary>
/// <param name="lobbyUpdates"><b>Lobby</b> properties used to update current lobby</param>
/// <param name="ModififyLobbyCompleted">Callback when modify lobby is completed</param>
public void ModifyLobby(Lobby lobbyUpdates, OnLobbyCallback ModififyLobbyCompleted)
{
// Validate current lobby
if (!CurrentLobby.IsValid())
{
Debug.LogError("Lobbies (ModifyLobby): Current Lobby {0} is invalid!");
ModififyLobbyCompleted?.Invoke(Result.InvalidState);
return;
}
ProductUserId currentProductUserId = EOSManager.Instance.GetProductUserId();
if (!currentProductUserId.IsValid())
{
Debug.LogError("Lobbies (ModifyLobby): Current player is invalid!");
ModififyLobbyCompleted?.Invoke(Result.InvalidProductUserID);
return;
}
if (!CurrentLobby.IsOwner(currentProductUserId))
{
Debug.LogError("Lobbies (ModifyLobby): Current player is not lobby owner!");
ModififyLobbyCompleted?.Invoke(Result.LobbyNotOwner);
return;
}
UpdateLobbyModificationOptions options = new UpdateLobbyModificationOptions();
options.LobbyId = CurrentLobby.Id;
options.LocalUserId = currentProductUserId;
// Get LobbyModification object handle
Result result = EOSManager.Instance.GetEOSLobbyInterface().UpdateLobbyModification(options, out LobbyModification outLobbyModificationHandle);
if (result != Result.Success)
{
Debug.LogErrorFormat("Lobbies (ModifyLobby): Could not create lobby modification. Error code: {0}", result);
ModififyLobbyCompleted?.Invoke(result);
return;
}
// Bucket Id
if(!string.Equals(lobbyUpdates.BucketId, CurrentLobby.BucketId))
{
outLobbyModificationHandle.SetBucketId(new LobbyModificationSetBucketIdOptions() { BucketId = lobbyUpdates.BucketId });
if (result != Result.Success)
{
Debug.LogErrorFormat("Lobbies (ModifyLobby): Could not set bucket id. Error code: {0}", result);
ModififyLobbyCompleted?.Invoke(result);
return;
}
}
// Max Players
if (lobbyUpdates.MaxNumLobbyMembers > 0)
{
result = outLobbyModificationHandle.SetMaxMembers(new LobbyModificationSetMaxMembersOptions() { MaxMembers = lobbyUpdates.MaxNumLobbyMembers });
if (result != Result.Success)
{
Debug.LogErrorFormat("Lobbies (ModifyLobby): Could not set max players. Error code: {0}", result);
ModififyLobbyCompleted?.Invoke(result);
return;
}
}