-
Notifications
You must be signed in to change notification settings - Fork 1
/
Networking.cs
1319 lines (1064 loc) · 38.4 KB
/
Networking.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
#define ENABLE_LOGS
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using Fusion;
using Fusion.Photon.Realtime;
using Fusion.Plugin;
using Fusion.Sockets;
using Hathora.Cloud.Sdk.Model;
using Hathora.Core.Scripts.Runtime.Common.Utils;
using Hathora.Core.Scripts.Runtime.Server;
using Hathora.Core.Scripts.Runtime.Server.ApiWrapper;
using HathoraPhoton;
using Application = UnityEngine.Application;
using Assert = UnityEngine.Assertions.Assert;
using UnityScene = UnityEngine.SceneManagement.Scene;
using HathoraRegion = Hathora.Cloud.Sdk.Model.Region;
namespace TPSBR
{
public struct SessionRequest
{
public string UserID;
public GameMode GameMode;
public string DisplayName;
public string SessionName;
public string ScenePath;
public EGameplayType GameplayType;
public int MaxPlayers;
public int ExtraPeers;
public string CustomLobby;
public string IPAddress;
public ushort Port;
}
// This Networking class is complex due to handling of reconnection of extra peers that we used for initial batch testing.
// We suggest to use standard approach (inheriting from NetworkSceneManagerBase for custom loading
// functionality and directly starting via NetworkRunner) for your game unless such functionality is needed.
public class Networking : MonoBehaviour
{
// HATHORA
private static HathoraServerConfig hathoraServerConfig =>
Global.Settings.HathoraServerConfig;
/// <summary>Useful for local testing or within the editor</summary>
private const bool USE_MOCK_HATHORA_PROCESS_ID = false;
/// <summary>
/// Create a Room (5m ttl) -> manually toss the processId here -> set USE_MOCK_HATHORA_PROCESS_ID
/// </summary>
private const string MOCK_HATHORA_PROCESS_ID = "eb4b7dc9-9c9e-4967-bf6e-d22f13b23455";
public static HathoraRegion HATHORA_FALLBACK_REGION => Region.WashingtonDC;
/// <summary>ByRef wrapper; passing just `ref` has issues with async/coroutines/tasks</summary>
private class StartGameArgsContainer
{
public StartGameArgs StartGameArgs;
public StartGameArgsContainer(StartGameArgs _args)
{
this.StartGameArgs = _args;
}
}
// CONSTANTS
public const string DISPLAY_NAME_KEY = "name";
public const string MAP_KEY = "map";
public const string TYPE_KEY = "type";
public const string MODE_KEY = "mode";
public const string STATUS_SERVER_CLOSED = "Server Closed";
// PUBLIC MEMBERS
public string Status { get; private set; }
public string StatusDescription { get; private set; }
public string ErrorStatus { get; private set; }
public bool HasSession => _pendingSession != null || _currentSession != null;
public bool IsConnecting => _pendingSession != null || _currentSession.IsConnected == false;
public bool IsConnected => _currentSession != null && _pendingSession == null && _currentSession.IsConnected == true;
public int PeerCount => _currentSession != null ? _currentSession.GamePeers.SafeCount() : 0;
// PRIVATE MEMBERS
private Session _pendingSession;
private Session _currentSession;
private bool _stopGameOnDisconnect;
private string _loadingScene;
private Coroutine _coroutine;
// PUBLIC METHODS
public void StartGame(SessionRequest request)
{
var session = new Session();
if (request.ExtraPeers > 0 && NetworkProjectConfig.Global.PeerMode == NetworkProjectConfig.PeerModes.Single)
{
Debug.LogError("Cannot start with multiple peers. PeerMode is set to Single.");
request.ExtraPeers = 0;
}
SceneRef sceneRef = SceneUtility.GetBuildIndexByScenePath(request.ScenePath);
int totalPeers = 1 + request.ExtraPeers;
session.GamePeers = new GamePeer[totalPeers];
for (int i = 0; i < totalPeers; i++)
{
session.GamePeers[i] = new GamePeer(i)
{
UserID = i == 0 ? request.UserID : $"{request.UserID}.{i}",
Scene = sceneRef,
GameMode = i == 0 ? request.GameMode : GameMode.Client,
Request = request,
};
}
session.ConnectionRequested = true;
_pendingSession = session;
_stopGameOnDisconnect = false;
ErrorStatus = null;
Log($"StartGame() UserID:{request.UserID} GameMode:{request.GameMode} DisplayName:{request.DisplayName} SessionName:{request.SessionName} ScenePath:{request.ScenePath} GameplayType:{request.GameplayType} MaxPlayers:{request.MaxPlayers} ExtraPeers:{request.ExtraPeers} CustomLobby:{request.CustomLobby}");
}
public void StopGame(string errorStatus = null)
{
Log($"StopGame()");
_pendingSession = null;
_stopGameOnDisconnect = false;
if (_currentSession != null)
{
_currentSession.ConnectionRequested = false;
}
ErrorStatus = errorStatus;
}
public void StopGameOnDisconnect()
{
Log($"StopGameOnDisconnect()");
_stopGameOnDisconnect = true;
}
public void ClearErrorStatus()
{
ErrorStatus = null;
}
// MONOBEHAVIOUR
protected void Awake()
{
_loadingScene = Global.Settings.LoadingScene;
}
protected void Update()
{
if (_pendingSession != null)
{
if (_currentSession == null)
{
_currentSession = _pendingSession;
_pendingSession = null;
}
else
{
// Request end of current session
_currentSession.ConnectionRequested = false;
}
}
UpdateCurrentSession();
// Check if current session finished
if (_coroutine == null && _currentSession != null && _currentSession.IsConnected == false)
{
if (_pendingSession == null)
{
Log($"Starting LoadMenuCoroutine()");
// Current session is finished and there is no pending session, let's go to menu
_coroutine = StartCoroutine(LoadMenuCoroutine());
}
_currentSession = null;
}
}
// PRIVATE MEMBERS
public async void UpdateCurrentSession()
{
if (_currentSession == null)
{
Status = string.Empty;
StatusDescription = string.Empty;
return;
}
if (_coroutine != null)
return;
var peers = _currentSession.GamePeers;
if (_stopGameOnDisconnect == true)
{
for (int i = 0; i < peers.Length; i++)
{
if (_currentSession.ConnectionRequested == true && peers[i].IsConnected == false)
{
Log($"Stopping game after disconnect");
_stopGameOnDisconnect = false;
StopGame();
return;
}
}
}
for (int i = 0; i < peers.Length; i++)
{
var peer = peers[i];
bool isConnected = peer.IsConnected;
if (_currentSession.ConnectionRequested == true && peer.Loaded == false && isConnected == false && peer.CanConnect == true)
{
// First connect or reconnect after failed connect
Status = peer.WasConnected == false ? "Starting" : "Reconnecting";
Log($"Starting ConnectPeerCoroutine() - {Status} - Peer {peer.ID}");
_coroutine = StartCoroutine(ConnectPeerCoroutine(peer));
return;
}
else if (_currentSession.ConnectionRequested == false && (isConnected == true || peer.Loaded == true))
{
// Disconnect requested
Status = "Quitting";
Log($"Starting DisconnectPeerCoroutine() - {Status} - Peer {peer.ID}");
_coroutine = StartCoroutine(DisconnectPeerCoroutine(peer));
return;
}
else if (peer.Loaded == true && isConnected == false)
{
// Connection lost
Status = "Connection Lost";
Log($"Starting DisconnectPeerCoroutine() - {Status} - Peer {peer.ID}");
_coroutine = StartCoroutine(DisconnectPeerCoroutine(peer));
return;
}
}
UpdatePeerSwitch(_currentSession.GamePeers);
ValidateMultiPeers(_currentSession.GamePeers);
}
/// <summary>
/// TODO: Convert this to async/await?
/// </summary>
/// <param name="peer"></param>
/// <param name="connectionTimeout"></param>
/// <param name="loadTimeout"></param>
/// <returns></returns>
private IEnumerator ConnectPeerCoroutine(GamePeer peer, float connectionTimeout = 10f, float loadTimeout = 45f)
{
peer.Loaded = true;
if (peer.WasConnected == true)
{
peer.ReconnectionTries--;
}
else
{
peer.ConnectionTries--;
}
StatusDescription = "Unloading current scene";
UnityScene activeScene = SceneManager.GetActiveScene();
if (IsSameScene(activeScene.path, peer.Request.ScenePath) == false && activeScene.name != _loadingScene)
{
Log($"Show loading scene");
yield return ShowLoadingSceneCoroutine(true);
var currentScene = activeScene.GetComponent<Scene>();
if (currentScene != null)
{
Log($"Deinitializing Scene");
currentScene.Deinitialize();
}
Log($"Unloading scene {activeScene.name}");
yield return SceneManager.UnloadSceneAsync(activeScene);
yield return null;
}
float baseTime = Time.realtimeSinceStartup;
float limitTime = baseTime + connectionTimeout;
string peerName = $"{peer.GameMode}#{peer.ID}";
Log($"Starting {peerName} ...");
StatusDescription = "Starting network connection";
yield return null;
NetworkObjectPool pool = new NetworkObjectPool();
NetworkRunner runner = Instantiate(Global.Settings.RunnerPrefab);
runner.name = peerName;
peer.Runner = runner;
peer.SceneManager = runner.GetComponent<NetworkSceneManager>();
peer.LoadedScene = default;
StartGameArgs startGameArgs = new StartGameArgs();
startGameArgs.GameMode = peer.GameMode;
startGameArgs.SessionName = peer.Request.SessionName;
startGameArgs.Scene = peer.Scene;
startGameArgs.Initialized = OnGamePeerInitialized;
startGameArgs.ObjectPool = pool;
startGameArgs.CustomLobbyName = peer.Request.CustomLobby;
startGameArgs.SceneManager = peer.SceneManager;
startGameArgs.DisableClientSessionCreation = true;
if (peer.Request.MaxPlayers > 0)
startGameArgs.PlayerCount = peer.Request.MaxPlayers;
if (peer.GameMode is GameMode.Host or GameMode.Server)
{
// If Host, essentially treat it as a Client for Hathora purposes
// Eg: "Create" should go through Lobby with client auth token
startGameArgs.SessionProperties = CreateSessionProperties(peer.Request);
}
#region Hathora
// ################################################################################################
switch (peer.GameMode)
{
case GameMode.Server:
{
StatusDescription = "Creating Hathora Room (as Server)";
StartGameArgsContainer startGameArgsByRef = new(startGameArgs);
yield return new HathoraTaskUtils.WaitForTaskCompletion(
hathoraServerGetIpAsync(startGameArgsByRef));
startGameArgs = startGameArgsByRef.StartGameArgs;
break;
}
case GameMode.Host:
{
StatusDescription = "Connecting to Hathora (as Host)";
throw new NotImplementedException("Host should have been handled " +
"at HathoraMatchmaking.cs, then changed to a Client (or hid the 'Create' UI)");
}
case GameMode.Client:
{
StatusDescription = "Connecting to Hathora (as Client)";
break;
}
}
// ################################################################################################
#endregion // Hathora
if (peer.Request.IPAddress.HasValue() == true)
{
// Sets the StandaloneMgr vals, if exists. For servers, don't set this. --Hathora
Log($"peer request IP&Port: " + peer.Request.IPAddress + " " + peer.Request.Port);
startGameArgs.Address = NetAddress.CreateFromIpPort(peer.Request.IPAddress, peer.Request.Port);
}
else if (peer.Request.Port > 0)
{
// Sets the StandaloneMgr vals, if exists. For servers, don't set this. --Hathora
Log($"peer request port: " + peer.Request.Port);
startGameArgs.Address = NetAddress.Any(peer.Request.Port);
}
Log($"NetworkRunner.StartGame()");
var startGameTask = runner.StartGame(startGameArgs);
while (startGameTask.IsCompleted == false)
{
yield return null;
if (Time.realtimeSinceStartup >= limitTime)
{
Debug.LogError(
$"{peerName} start timeout! IsCompleted: {startGameTask.IsCompleted} IsCanceled: {startGameTask.IsCanceled} IsFaulted: {startGameTask.IsFaulted}");
break;
}
if (_currentSession.ConnectionRequested == false)
{
Log($"Stopping coroutine (requested by user)");
// Stop requested by user
break;
}
}
if (startGameTask.IsCanceled == true || startGameTask.IsFaulted == true ||
startGameTask.IsCompleted == false)
{
Debug.LogError($"{peerName} failed to start!");
Log($"Starting DisconnectPeerCoroutine() - Peer {peer.ID}");
yield return DisconnectPeerCoroutine(peer);
_coroutine = null;
yield break;
}
var result = startGameTask.Result;
Log($"StartGame() Result: {result.ToString()} - Peer {peer.ID}");
if (result.Ok == false)
{
Debug.LogError($"{peerName} failed to start! Result: {result}");
// Probably incorrect start game parameters, go back to menu immediately
if (Application.isBatchMode == false)
{
StopGame();
}
if (peer.WasConnected == true && result.ShutdownReason == ShutdownReason.GameNotFound)
{
ErrorStatus = STATUS_SERVER_CLOSED;
}
else
{
ErrorStatus = StringToLabel(result.ShutdownReason.ToString());
}
Log($"Starting DisconnectPeerCoroutine() - Peer {peer.ID}");
yield return DisconnectPeerCoroutine(peer);
_coroutine = null;
yield break;
}
limitTime += loadTimeout;
Log($"Waiting for connection - Peer {peer.ID}");
StatusDescription = "Waiting for server connection";
while (peer.IsConnected == false)
{
yield return null;
if (Time.realtimeSinceStartup >= limitTime)
{
Debug.LogError(
$"{peerName} start timeout! IsCloudReady: {runner.IsCloudReady} IsRunning: {runner.IsRunning}");
Log($"Starting DisconnectPeerCoroutine() - Peer {peer.ID}");
yield return DisconnectPeerCoroutine(peer);
_coroutine = null;
yield break;
}
}
Log($"Loading gameplay scene - Peer {peer.ID}");
StatusDescription = "Loading gameplay scene";
while (runner.SimulationUnityScene.IsValid() == false || runner.SimulationUnityScene.isLoaded == false)
{
Log($"Waiting for NetworkRunner.SimulationUnityScene - Peer {peer.ID}");
yield return null;
if (Time.realtimeSinceStartup >= limitTime)
{
Debug.LogError($"{peerName} scene load timeout!");
Log($"Starting DisconnectPeerCoroutine() - Peer {peer.ID}");
yield return DisconnectPeerCoroutine(peer);
_coroutine = null;
yield break;
}
}
Debug.LogWarning(
$"{peerName} started on {runner.Simulation.GetLocalAddress()} in {(Time.realtimeSinceStartup - baseTime):0.00}s");
peer.LoadedScene = runner.SimulationUnityScene;
if (peer.ID == 0)
{
SceneManager.SetActiveScene(peer.LoadedScene);
}
StatusDescription = "Waiting for gameplay scene load";
var scene = peer.SceneManager.GameplayScene;
while (scene == null)
{
Log($"Waiting for GameplayScene - Peer {peer.ID}");
yield return null;
scene = peer.SceneManager.GameplayScene;
if (Time.realtimeSinceStartup >= limitTime)
{
Debug.LogError($"{peerName} GameplayScene query timeout!");
Log($"Starting DisconnectPeerCoroutine() - Peer {peer.ID}");
yield return DisconnectPeerCoroutine(peer);
_coroutine = null;
yield break;
}
}
Log($"Scene.PrepareContext() - Peer {peer.ID}");
scene.PrepareContext();
var sceneContext = scene.Context;
sceneContext.IsVisible = peer.ID == 0;
sceneContext.HasInput = peer.ID == 0;
sceneContext.Runner = peer.Runner;
sceneContext.PeerUserID = peer.UserID;
peer.Context = sceneContext;
pool.Context = sceneContext;
StatusDescription = "Waiting for networked game";
var networkGame = scene.GetComponentInChildren<NetworkGame>(true);
while (networkGame.Object == null)
{
Log($"Waiting for NetworkGame - Peer {peer.ID}");
yield return null;
if (Time.realtimeSinceStartup >= limitTime)
{
Debug.LogError($"{peerName} start timeout! Network game not started properly.");
Log($"Starting DisconnectPeerCoroutine() - Peer {peer.ID}");
yield return DisconnectPeerCoroutine(peer);
_coroutine = null;
yield break;
}
if (_currentSession.ConnectionRequested == false)
{
// Stop requested by user
Log(
$"Starting DisconnectPeerCoroutine() - Connection is not requested anymore - Peer {peer.ID}");
yield return DisconnectPeerCoroutine(peer);
_coroutine = null;
yield break;
}
}
StatusDescription = "Waiting for gameplay load";
Log($"NetworkGame.Initialize() - Peer {peer.ID}");
networkGame.Initialize(peer.Request.GameplayType);
while (scene.Context.GameplayMode == null)
{
Log($"Waiting for GameplayMode - Peer {peer.ID}");
yield return null;
if (Time.realtimeSinceStartup >= limitTime)
{
Debug.LogError($"{peerName} start timeout! Gameplay mode not started properly.");
Log($"Starting DisconnectPeerCoroutine() - Peer {peer.ID}");
yield return DisconnectPeerCoroutine(peer);
_coroutine = null;
yield break;
}
}
StatusDescription = "Activating scene";
Log($"Scene.Initialize() - Peer {peer.ID}");
scene.Initialize();
Log($"Scene.Activate() - Peer {peer.ID}");
yield return scene.Activate();
StatusDescription = "Activating network game";
Log($"NetworkGame.Activate() - Peer {peer.ID}");
networkGame.Activate();
if (SceneManager.GetSceneByName(_loadingScene).IsValid() == true)
{
// Wait a little bit for scene activation before showing it
yield return new WaitForSeconds(1f);
Log($"Hide loading scene");
yield return ShowLoadingSceneCoroutine(false);
}
if (peer.WasConnected == true)
{
peer.ReconnectionTries++;
}
peer.WasConnected = true;
_coroutine = null;
Log($"ConnectPeerCoroutine() finished");
}
/// <summary>Game started as a Photon "Host": We'll create a Lobby as a Client</summary>
/// <param name="_startGameArgsByRef">Wrapped the Struct in a Class for ByRef while async</param>
private async Task connectHathoraHostAsync(StartGameArgsContainer _startGameArgsByRef)
{
Log(nameof(connectHathoraHostAsync));
string logPefix = $"[Networking.{nameof(connectHathoraHostAsync)}]";
HathoraPhotonClientMgr clientMgr = HathoraPhotonClientMgr.Singleton;
// We should already be logged in from Start() @ Menu via HathoraManager prefab
Assert.IsTrue(clientMgr.HathoraClientSession.IsAuthed, "!IsAuthed");
// ----------------------------------
// // == Auth =>
//
// bool isSuccess = false;
// try
// {
// isSuccess = await hathoraPhotonClientMgr.ConnectAsClient();
// }
// catch (Exception e)
// {
// Debug.LogError($"{logPefix} {nameof(hathoraPhotonClientMgr.ConnectAsClient)} " +
// $"=> failed: {e.Message}");
// throw;
// }
//
// Assert.IsTrue(isSuccess, "!IsAuthed");
// if (_startGameArgsByRef.StartGameArgs.GameMode is not GameMode.Host)
// return;
// ----------------------------------
// Host Create Lobby =>
// Get the selected Photon Region -> Map to closest Hathora Region
HathoraRegion hathoraRegion = getHathoraRegionFromPhoton();
// string initConfigJsonStr = JsonConvert.SerializeObject(someStatefulConfig); // TODO
Lobby lobby = null;
try
{
lobby = await clientMgr.CreateLobbyAsync(hathoraRegion); // public visibility
}
catch (Exception e)
{
Debug.LogError($"Error: {e}");
throw;
}
Assert.IsNotNull(lobby?.RoomId, "!lobby.RoomId");
// ----------------------------------
// Host get connection info (ip:port) from Lobby roomId =>
ConnectionInfoV2 connectionInfo = null;
try
{
connectionInfo = await clientMgr.GetActiveConnectionInfo(lobby.RoomId);
}
catch (Exception e)
{
Debug.LogError($"{logPefix} {nameof(clientMgr.GetActiveConnectionInfo)} " +
$"=> failed: {e.Message}");
throw;
}
Assert.IsTrue(connectionInfo?.ExposedPort?.Port > 0,
"!ConnectionInfo.ExposedPort.Port");
// ----------------------------------
// We now [should] have host:port. 1st, convert host to IP
IPAddress ip = await HathoraUtils.ConvertHostToIpAddress(connectionInfo.ExposedPort.Host);
ushort port = (ushort)connectionInfo.ExposedPort.Port;
serverSetCustomPublicAddress(
ip,
port,
_startGameArgsByRef); // validates + logs
}
private HathoraRegion getHathoraRegionFromPhoton()
{
string photonRegionStr = PhotonAppSettings.Instance.AppSettings.FixedRegion;
bool hasPhotonRegionStr = !string.IsNullOrEmpty(photonRegionStr);
HathoraRegion hathoraRegion = hasPhotonRegionStr
? (HathoraRegion)HathoraRegionMap.GetHathoraRegionIndexFromPhoton(photonRegionStr)
: HATHORA_FALLBACK_REGION;
return hathoraRegion;
}
/// <summary>TODO: Throw this in a Hathora server script</summary>
/// <param name="_startGameArgsContainer">ByRef</param>
/// <returns>ByRef changes in _startGameArgsContainer</returns>
private async Task<(IPAddress ip, ushort port)> hathoraServerGetIpAsync(
StartGameArgsContainer _startGameArgsContainer)
{
Log(nameof(hathoraServerGetIpAsync));
// ===============================================================================
//
// OBSERVATIONS:
// - If we completely omit this #region, Photon's discovery protocols will *still*
// find/register the server deployed in Hathora and you'll see Room logs when
// the player connects, *but* CCU !registers in the Hathora Console (and, thus,
// shuts itself [the Processs] down after 5m).
//
// ===============================================================================
//
// HATHORA FLOW:
// 1. Serialize HathoraServerConfig @ Photon's GlobalSettingg ScriptableObject
// 2. Get server ip:port via Hathora server `Process` API wrapper to get processId
// 3. Convert the host name to IP addresss
// 4. Set Photon's startGameArgs.CustomPublicAddress
//
// ===============================================================================
// Coroutine workaround for async/await: Loop the Task until we have a result =>
(IPAddress ip, ushort port) ipPort;
try
{
ipPort = await GetHathoraServerIpPortAsync();
}
catch (Exception e)
{
Debug.LogError($"{nameof(GetHathoraServerIpPortAsync)} failed: {e.Message}");
throw;
}
// We [should] now have ip:port from Hathora Process
if (ipPort.port > 0)
{
serverSetCustomPublicAddress(
ipPort.ip,
ipPort.port,
_startGameArgsContainer); // validates + logs
}
return ipPort;
}
#region Hathora Utils
/// <summary>
/// Gets processsId from env var ->
/// </summary>
/// <returns></returns>
private async Task<(IPAddress ip, ushort port)> GetHathoraServerIpPortAsync()
{
// Mock it, or get the actual env var?
string HATHORA_PROCESS_ID = USE_MOCK_HATHORA_PROCESS_ID && !string.IsNullOrEmpty(MOCK_HATHORA_PROCESS_ID)
? MOCK_HATHORA_PROCESS_ID
: Environment.GetEnvironmentVariable("HATHORA_PROCESS_ID");
if (USE_MOCK_HATHORA_PROCESS_ID)
Log("[GetHathoraServerIpPortAsync] <color=yellow>(!) USE_MOCK_HATHORA_PROCESS_ID</color>");
Log($"[ConnectPeerCoroutine.GetHathoraServerIpPortAsync] " +
$"HATHORA_PROCESS_ID: {HATHORA_PROCESS_ID}");
bool hasHathoraProcId = !string.IsNullOrEmpty(HATHORA_PROCESS_ID);
(IPAddress ip, ushort port) processIpPort = default;
if (!hasHathoraProcId)
return processIpPort; // failed, but done
// -----------------------------------------------------
// Get ip:port from Hathora ProcessId; OR local fallback
try
{
processIpPort = await hathoraServerGetProcessAsync(HATHORA_PROCESS_ID);
}
catch (Exception e)
{
Debug.LogError("[initServerSetPublicAddress] GetHathoraServerIpPortAsync " +
$"=> Error: {e}");
throw;
}
// Done
processIpPort.ip = processIpPort.ip;
processIpPort.port = processIpPort.port;
return processIpPort;
}
private void serverSetCustomPublicAddress(
string _host,
ushort _port,
StartGameArgsContainer _startGameArgsContainer)
{
}
/// <summary>Validates -> logs -> sets ip:port</summary>
/// <param name="_ip"></param>
/// <param name="_port"></param>
/// <param name="_startGameArgsContainer">Passed ByRef to set `CustomPublicAddress`</param>
private void serverSetCustomPublicAddress(
IPAddress _ip,
ushort _port,
StartGameArgsContainer _startGameArgsContainer)
{
Log($"[setCustomPublicAddress] ip:port == `{_ip}:{_port}`");
_startGameArgsContainer.StartGameArgs.CustomPublicAddress = _ip == null
? NetAddress.Any(_port)
: NetAddress.CreateFromIpPort(_ip.ToString(), _port);
}
/// <summary>Hathora local testing util, if launched with CLI -args or with env vars set</summary>
[Obsolete("Possibly unnecesssary due to Photon's Discovery protocols")]
private (IPAddress ip, ushort port) getIpPortFromEnvVars()
{
// Get env vars
Log("getIpPortFromEnvVars");
string LOCAL_SERVER_IP = Environment.GetEnvironmentVariable(nameof(LOCAL_SERVER_IP))?.Trim();
string SERVER_PORT = Environment.GetEnvironmentVariable(nameof(SERVER_PORT))?.Trim();
// Validate exists
if (string.IsNullOrEmpty(LOCAL_SERVER_IP))
return default;
if (string.IsNullOrEmpty(SERVER_PORT))
return default;
// Parse string to the return val types
ushort.TryParse(SERVER_PORT, out ushort ipUint);
IPAddress ipAddress = IPAddress.Parse(LOCAL_SERVER_IP);
return (ipAddress, ipUint);
}
/// <summary>Validates -> Gets hathora Process async; converts host name to IP</summary>
/// <param name="_hathoraProcessId"></param>
/// <param name="_cancelToken"></param>
/// <returns>(IPAddress ip, ushort port) named Tuple</returns>
private async Task<(IPAddress ip, ushort port)> hathoraServerGetProcessAsync(
string _hathoraProcessId,
CancellationToken _cancelToken = default)
{
string logPrefix = $"[Networking.{nameof(hathoraServerGetProcessAsync)}]";
// Validate Hathora Server Config + Auth Token
if (hathoraServerConfig == null)
throw new NullReferenceException($"{logPrefix} !hathoraServerConfig: Serialize it @ GlobalSettings.cs");
if (!hathoraServerConfig.HathoraCoreOpts.DevAuthOpts.HasAuthToken)
{
throw new NullReferenceException($"{logPrefix} !hathoraServerConfig.HathoraCoreOpts" +
".DevAuthOpts.HasAuthToken: Ensure you are authenticated to Hathora via HathoraServerConfig file " +
"(find via top menu: `Hathora/ServerConfigFinder`)");
}
// Set ip:port via Hathora API's procId >>
HathoraServerProcessApi processApi = new(hathoraServerConfig);
// Normally this is an `await`, but we're inside a coroutine =>
Process process = null;
try
{
process = await processApi.GetProcessInfoAsync(
_hathoraProcessId,
_cancelToken: _cancelToken);
}
catch (Exception e)
{
Debug.LogError($"{logPrefix} GetProcessInfoAsync => Error: {e}");
throw;
}
Assert.IsNotNull(process?.ExposedPort?.Host, $"{logPrefix} Expected `process.ExposedPort.Host`");
Assert.IsTrue(process?.ExposedPort?.Port > 0, $"{logPrefix} Expected `process.ExposedPort.Port > 0`");
// Get the IP address from the host name; this can return > 1, but we just want 1st
(IPAddress ip, ushort port) ipPort;
ipPort.ip = await HathoraUtils.ConvertHostToIpAddress(process.ExposedPort.Host);
ipPort.port = (ushort)process.ExposedPort.Port;
return ipPort;
}
#endregion // Hathora Utils
private IEnumerator DisconnectPeerCoroutine(GamePeer peer)
{
StatusDescription = "Disconnecting from server";
UnityScene gameplayScene = default;
try
{
if (peer.Runner != null)
{
// Possible exception when runner tries to read config
gameplayScene = peer.Runner.SimulationUnityScene;
// Close and hide the room
if (peer.Runner.IsServer == true && peer.Runner.SessionInfo != null)
{
Log($"Closing the room");
peer.Runner.SessionInfo.IsOpen = false;
peer.Runner.SessionInfo.IsVisible = false;
}
}
}
catch (Exception exception)
{
Debug.LogException(exception);
}
if (gameplayScene.IsValid() == false)
{
gameplayScene = peer.LoadedScene;
}
if (gameplayScene.IsValid() == true)
{
Scene scene = gameplayScene.GetComponent<Scene>(true);
if (scene != null)
{
try
{
Log($"Deinitializing Scene");
scene.Deinitialize();
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
}
Task shutdownTask = null;
if (peer.Runner != null)
{
Debug.LogWarning($"Shutdown {peer.Runner.name} ...");
try
{
shutdownTask = peer.Runner.Shutdown(true);
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
Log($"Show loading scene");
yield return ShowLoadingSceneCoroutine(true);
if (shutdownTask != null)
{
float operationTimeout = 10.0f;
while (operationTimeout > 0.0f && shutdownTask.IsCompleted == false)
{
yield return null;
operationTimeout -= Time.unscaledDeltaTime;
}
}