From 06c2d883fb6efab71951f8a29f586441cac67743 Mon Sep 17 00:00:00 2001 From: Tore Bergebakken Date: Sun, 26 May 2024 21:31:24 +0200 Subject: [PATCH] Handle disconnect and server/client stop --- Assets/Scenes/CraterTown.unity | 2 +- Assets/Scenes/Menu.unity | 14 +- Assets/Scenes/TrainingMode.unity | 18 ++- .../Augment/AugmentImplementations/Fire.cs | 2 +- Assets/Scripts/Augment/BulletController.cs | 1 - .../BulletModifiers/ZigzagPathModifier.cs | 1 - Assets/Scripts/Augment/GunController.cs | 4 - .../Control&Input/ItemSelectManager.cs | 42 +++--- .../Scripts/Control&Input/ItemSelectMenu.cs | 3 +- .../Control&Input/Peer2PeerTransport.cs | 113 +++++++++----- .../Control&Input/ReturnToMainMenuGate.cs | 5 +- .../PortalExtensionController.cs | 20 +-- Assets/Scripts/Gamestate/MatchController.cs | 18 +-- Assets/Scripts/Gamestate/PlayerFactory.cs | 138 +----------------- Assets/Scripts/Gamestate/PlayerManager.cs | 1 + Assets/Scripts/Utils/SteamManager.cs | 16 +- 16 files changed, 144 insertions(+), 254 deletions(-) diff --git a/Assets/Scenes/CraterTown.unity b/Assets/Scenes/CraterTown.unity index 474cf8220..f051065a6 100644 --- a/Assets/Scenes/CraterTown.unity +++ b/Assets/Scenes/CraterTown.unity @@ -38,7 +38,7 @@ RenderSettings: m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 662445327} - m_IndirectSpecularColor: {r: 0.062285002, g: 0.21922584, b: 0.4949425, a: 1} + m_IndirectSpecularColor: {r: 0.062542364, g: 0.2194215, b: 0.49499997, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: diff --git a/Assets/Scenes/Menu.unity b/Assets/Scenes/Menu.unity index 9e9c33ab7..00f05f1e3 100644 --- a/Assets/Scenes/Menu.unity +++ b/Assets/Scenes/Menu.unity @@ -38,7 +38,7 @@ RenderSettings: m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 785370674} - m_IndirectSpecularColor: {r: 0.062482566, g: 0.21938902, b: 0.4950583, a: 1} + m_IndirectSpecularColor: {r: 0.062451348, g: 0.21931733, b: 0.49487647, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: @@ -416,18 +416,6 @@ PrefabInstance: serializedVersion: 3 m_TransformParent: {fileID: 0} m_Modifications: - - target: {fileID: 3717336014748129540, guid: 0e2ad36662a02c3488301a5286b27635, type: 3} - propertyPath: startingBody - value: - objectReference: {fileID: 11400000, guid: 0abfdcb5f304f2647b378f82907d538c, type: 2} - - target: {fileID: 3717336014748129540, guid: 0e2ad36662a02c3488301a5286b27635, type: 3} - propertyPath: startingBarrel - value: - objectReference: {fileID: 11400000, guid: 9c1da148c8d07ab428c6bc9a70aecae8, type: 2} - - target: {fileID: 3717336014748129540, guid: 0e2ad36662a02c3488301a5286b27635, type: 3} - propertyPath: startingExtension - value: - objectReference: {fileID: 11400000, guid: 2c332edf0b10a07489ea78f82b8f7045, type: 2} - target: {fileID: 8579357797008554893, guid: 0e2ad36662a02c3488301a5286b27635, type: 3} propertyPath: m_Name value: StaticInfo diff --git a/Assets/Scenes/TrainingMode.unity b/Assets/Scenes/TrainingMode.unity index e8360e2e7..d75dbc329 100644 --- a/Assets/Scenes/TrainingMode.unity +++ b/Assets/Scenes/TrainingMode.unity @@ -565,15 +565,9 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: b18a938eb13d13540b14e958b874d1b0, type: 3} m_Name: m_EditorClassIdentifier: - playerPrefab: {fileID: 2770875744502568649, guid: 1ccbc17fde8c55a21ac6331f0517f402, type: 3} spawnPoints: - {fileID: 1104924655} playerSelectItemPrefab: {fileID: 0} - aIOpponent: {fileID: 0} - aIBidder: {fileID: 0} - aiIdentity: {fileID: 0} - globalHUDController: {fileID: 0} - overrideMatchManager: 1 --- !u!4 &168459266 Transform: m_ObjectHideFlags: 0 @@ -4278,6 +4272,10 @@ PrefabInstance: propertyPath: m_ConstrainProportionsScale value: 1 objectReference: {fileID: 0} + - target: {fileID: 508678544827238946, guid: e795d78bc3458864bad12d1dc75182fb, type: 3} + propertyPath: m_Enabled + value: 0 + objectReference: {fileID: 0} - target: {fileID: 1245620792704334073, guid: e795d78bc3458864bad12d1dc75182fb, type: 3} propertyPath: m_Materials.Array.size value: 1 @@ -4294,7 +4292,13 @@ PrefabInstance: propertyPath: m_Mesh value: objectReference: {fileID: 962209921104072034, guid: 96e02cb082c4f82d495b4b45861a50f6, type: 3} - m_RemovedComponents: [] + - target: {fileID: 5543259695900803521, guid: e795d78bc3458864bad12d1dc75182fb, type: 3} + propertyPath: m_IsTrigger + value: 1 + objectReference: {fileID: 0} + m_RemovedComponents: + - {fileID: 508678544827238946, guid: e795d78bc3458864bad12d1dc75182fb, type: 3} + - {fileID: 3873721530690488933, guid: e795d78bc3458864bad12d1dc75182fb, type: 3} m_RemovedGameObjects: [] m_AddedGameObjects: [] m_AddedComponents: diff --git a/Assets/Scripts/Augment/AugmentImplementations/Fire.cs b/Assets/Scripts/Augment/AugmentImplementations/Fire.cs index af95bcad5..8673d6ab9 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/Fire.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/Fire.cs @@ -176,7 +176,7 @@ private void AddFireToProjectile(GunStats gunstats) private void PlayShotAudio(GunStats stats) { - if (!gunController) + if (!gunController || !audioSource) return; audioSource.clip = lighterSounds.RandomElement(); audioSource.Play(); diff --git a/Assets/Scripts/Augment/BulletController.cs b/Assets/Scripts/Augment/BulletController.cs index d6266d9d0..d5570d6a4 100644 --- a/Assets/Scripts/Augment/BulletController.cs +++ b/Assets/Scripts/Augment/BulletController.cs @@ -64,7 +64,6 @@ private void Start() [ClientRpc] private void RpcSeedRandom(int seed) { - Debug.Log($"Seed {seed}"); random = new Random(seed); } diff --git a/Assets/Scripts/Augment/BulletModifiers/ZigzagPathModifier.cs b/Assets/Scripts/Augment/BulletModifiers/ZigzagPathModifier.cs index 89853ec03..12931c654 100644 --- a/Assets/Scripts/Augment/BulletModifiers/ZigzagPathModifier.cs +++ b/Assets/Scripts/Augment/BulletModifiers/ZigzagPathModifier.cs @@ -27,7 +27,6 @@ private void Start() [ClientRpc] private void RpcSeedRandom(int seed) { - Debug.Log($"Seed {seed}"); random = new System.Random(seed); } diff --git a/Assets/Scripts/Augment/GunController.cs b/Assets/Scripts/Augment/GunController.cs index b88ce54c0..3d0b59b8d 100644 --- a/Assets/Scripts/Augment/GunController.cs +++ b/Assets/Scripts/Augment/GunController.cs @@ -172,10 +172,6 @@ private void CmdFire(Quaternion rotation) private void RpcFire(Quaternion rotation) { onFireStart?.Invoke(stats); - // TODO does this work? if so, remove output - //if (authority) - //projectile.projectileOutput = outputs[0]; - //projectile.projectileOutput = outputs[0]; projectile.projectileOutput = outputs[0]; projectile.projectileRotation = rotation; ActuallyFire(); diff --git a/Assets/Scripts/Control&Input/ItemSelectManager.cs b/Assets/Scripts/Control&Input/ItemSelectManager.cs index 42e2b8e4f..d9c296aa0 100644 --- a/Assets/Scripts/Control&Input/ItemSelectManager.cs +++ b/Assets/Scripts/Control&Input/ItemSelectManager.cs @@ -1,18 +1,10 @@ +using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Mirror; using UnityEngine; -// TODO remove first two structs if unused -internal struct StartTrackingMessage : NetworkMessage -{ -} - -internal struct ReadyToTrackMessage : NetworkMessage -{ -} - internal struct ClientReadyMessage : NetworkMessage { } @@ -45,27 +37,29 @@ public void StartTrackingMenus() if (isServer) { - InitializeServerData(); - NetworkServer.RegisterHandler(OnClientReady); - NetworkServer.RegisterHandler(OnClientNotReady); + InitializeServerState(); } } + private void InitializeServerState() + { + clientReadyByID = Peer2PeerTransport.Connections + .ToDictionary(c => c.connectionId, c => false); + ((Peer2PeerTransport)NetworkManager.singleton).OnDisconnect += OnDisconnect; + NetworkServer.RegisterHandler(OnClientReady); + NetworkServer.RegisterHandler(OnClientNotReady); + } + private void OnDestroy() { if (isServer) { + ((Peer2PeerTransport)Peer2PeerTransport.singleton).OnDisconnect -= OnDisconnect; NetworkServer.UnregisterHandler(); NetworkServer.UnregisterHandler(); } } - private void InitializeServerData() - { - clientReadyByID = Peer2PeerTransport.Connections - .ToDictionary(c => c.connectionId, c => false); - } - [Server] private void Finish() { @@ -75,6 +69,7 @@ private void Finish() [ClientRpc] private void RpcFinish() { + ((Peer2PeerTransport)Peer2PeerTransport.singleton).UpdateLoadout(); StartCoroutine(MatchController.Singleton.WaitAndStartNextRound()); } @@ -107,9 +102,20 @@ private void OnClientNotReady(NetworkConnectionToClient connection, ClientNotRea } } + private void OnDisconnect(int connectionID) + { + clientReadyByID.Remove(connectionID); + CheckIfAllAreReady(); + } + private void OnClientReady(NetworkConnectionToClient connection, ClientReadyMessage message) { clientReadyByID[connection.connectionId] = true; + CheckIfAllAreReady(); + } + + private void CheckIfAllAreReady() + { var allClientsAreReady = clientReadyByID.Values.All(m => m); if (allClientsAreReady) { diff --git a/Assets/Scripts/Control&Input/ItemSelectMenu.cs b/Assets/Scripts/Control&Input/ItemSelectMenu.cs index 647d73a31..5b569810e 100644 --- a/Assets/Scripts/Control&Input/ItemSelectMenu.cs +++ b/Assets/Scripts/Control&Input/ItemSelectMenu.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; -using TMPro; using SecretName; public class ItemSelectMenu : MonoBehaviour @@ -60,7 +59,7 @@ public class ItemSelectMenu : MonoBehaviour private AugmentType selectedType = AugmentType.Body; - private ItemSelectSlot selectedSlot => (selectedType) switch + private ItemSelectSlot selectedSlot => selectedType switch { AugmentType.Body => bodySlot, AugmentType.Barrel => barrelSlot, diff --git a/Assets/Scripts/Control&Input/Peer2PeerTransport.cs b/Assets/Scripts/Control&Input/Peer2PeerTransport.cs index b6071e9f9..d5b218602 100644 --- a/Assets/Scripts/Control&Input/Peer2PeerTransport.cs +++ b/Assets/Scripts/Control&Input/Peer2PeerTransport.cs @@ -1,4 +1,3 @@ -using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -132,33 +131,42 @@ public class Peer2PeerTransport : NetworkManager /// private static List connections = new(); private static Dictionary> playersForConnection = new(); + private static List connectedPlayers = new(); public static ReadOnlyCollection Connections; public delegate void LobbyPlayerEvent(PlayerDetails details); public LobbyPlayerEvent OnPlayerRecieved; - public override void OnStartServer() - { - base.OnStartServer(); - NetworkServer.RegisterHandler(OnSpawnPlayerInput); - NetworkServer.RegisterHandler(OnReceiveUpdateLoadout); + public delegate void ConnectionEvent(int connectionID); + public ConnectionEvent OnDisconnect; - // Reinitialize player lookups + private void ResetState() + { + playerIndex = 0; players = new(); playerInstances = new(); PlayerInstanceByID = new(playerInstances); - playerIndex = 0; + localPlayerIds = new(); + connections = new(); + connectedPlayers = new(); playersForConnection = new(); Connections = new(connections); } + public override void OnStartServer() + { + NetworkServer.RegisterHandler(OnSpawnPlayerInput); + NetworkServer.RegisterHandler(OnReceiveUpdateLoadout); + + ResetState(); + } + #region Player joining public override void OnClientConnect() { base.OnClientConnect(); - NetworkClient.RegisterHandler(OnStartMatch); NetworkClient.RegisterHandler(OnReceivePlayerDetails); NetworkClient.RegisterHandler(InitializeFPSPlayer); @@ -168,30 +176,45 @@ public override void OnClientConnect() // TODO doesn't work if players haven't pressed a key yet PlayerInputManagerController.Singleton.JoinAllInputs(); - players = new(); - playerInstances = new(); - PlayerInstanceByID = new(playerInstances); - playerIndex = 0; + ResetState(); + } + + public override void OnServerDisconnect(NetworkConnectionToClient connection) + { + if (!playersForConnection.ContainsKey(connection.connectionId)) + return; + Debug.Log($"Removed connection {connections.IndexOf(connection)} which has players {playersForConnection[connection.connectionId].ToCommaSeparatedString()}"); + connections.Remove(connection); + connectedPlayers.RemoveAll(id => playersForConnection[connection.connectionId].Contains(id)); + playersForConnection.Remove(connection.connectionId); + // TODO send msg to ItemSelectManager that this connection is invalid + OnDisconnect?.Invoke(connection.connectionId); + } + + public override void OnStopServer() + { + Debug.Log("Stopped server"); + ResetState(); + } + + public override void OnStopClient() + { + Debug.Log("Stopped client"); + ResetState(); + } + + public override void OnClientDisconnect() + { + Debug.Log("Disconnected as client"); + LoadingScreen.Singleton.Hide(); + MusicTrackManager.Singleton.SwitchTo(MusicType.Menu); + PlayerInputManagerController.Singleton.ChangeInputMaps("Menu"); + SceneManager.LoadSceneAsync(Scenes.Menu); + if (NetworkClient.active) + StopClient(); + else + ResetState(); } - // TODO OnClientDisconnect and the like must be implemented!!! - // - OnServerDisconnect seems to be the one that runs on the server when a client disconnects - - //public override void OnServerDisconnect(NetworkConnectionToClient conn) - //{ - // base.OnServerDisconnect(conn); - // throw new NotImplementedException(); - //} - //public override void OnClientDisconnect() - //{ - // base.OnClientDisconnect(); - // throw new NotImplementedException(); - //} - //// TODO should this be different? - //public override void OnStopClient() - //{ - // base.OnStopClient(); - // throw new NotImplementedException(); - //} public void JoinLobby(string address = "127.0.0.1") { @@ -221,6 +244,7 @@ public static void StartTrainingMode() color = PlayerInputManagerController.Singleton.PlayerColors[i], }; players.Add((uint)i, details); + connectedPlayers.Add((uint)i); NetworkServer.SendToAll(new InitialPlayerDetailsMessage(details)); } @@ -229,9 +253,12 @@ public static void StartTrainingMode() private static IEnumerator WaitAndSwitchToTrainingMode() { + LoadingScreen.Singleton.Show(); while (!NetworkClient.isConnected && !singleton.isNetworkActive && players.Count < PlayerInputManagerController.Singleton.LocalPlayerInputs.Count) yield return new WaitForEndOfFrame(); singleton.ServerChangeScene(Scenes.TrainingMode); + // TODO until after spawned + LoadingScreen.Singleton.Hide(); } // TODO custom method for leaving training mode :) @@ -266,7 +293,10 @@ private void OnSpawnPlayerInput(NetworkConnectionToClient connection, PlayerConn // Register connection PlayerInputManagerController.Singleton.NetworkClients.Add(connection); if (!connections.Contains(connection)) + { connections.Add(connection); + connectedPlayers.Add((uint)playerIndex); + } if (!playersForConnection.ContainsKey(connection.connectionId)) playersForConnection[connection.connectionId] = new(); playersForConnection[connection.connectionId].Add((uint)playerIndex); @@ -412,7 +442,6 @@ public override void OnServerChangeScene(string newSceneName) AddAiPlayers(); } - switch (newSceneName) { case Scenes.Bidding: @@ -427,12 +456,9 @@ public override void OnServerChangeScene(string newSceneName) NetworkServer.ReplaceHandler(OnSpawnFPSPlayer); break; } - - base.OnServerChangeScene(newSceneName); } - // TODO move to ItemSelectManager (?) - private void UpdateLoadout() + public void UpdateLoadout() { Debug.Log($"Found {FindObjectsByType(FindObjectsInactive.Exclude, FindObjectsSortMode.None).Count()} identitites!"); foreach (var identity in FindObjectsByType(FindObjectsInactive.Exclude, FindObjectsSortMode.None)) @@ -469,7 +495,6 @@ private void OnReceiveUpdateLoadout(NetworkConnectionToClient connection, Update public override void OnClientChangeScene(string newSceneName, SceneOperation sceneOperation, bool customHandling) { - UpdateLoadout(); var originalSceneName = SceneManager.GetActiveScene().name; switch (newSceneName) { @@ -502,10 +527,22 @@ private IEnumerator SendSpawnRequestsAfterSceneLoad(string originalSceneName) { NetworkClient.Send(new SpawnPlayerMessage(id, PlayerType.Local)); } + + if (!NetworkServer.active) + yield break; + + // TODO rework this for dedicated server stuff + // (where it needs to do this on server change scene, and without a network client) + // (perhaps you could call the spawn methods directly?) foreach (var p in players.Values.Where(p => p.type == PlayerType.AI)) { NetworkClient.Send(new SpawnPlayerMessage(p.id, PlayerType.AI)); } + + foreach (var p in players.Values.Where(p => p.type is PlayerType.Remote && !connectedPlayers.Contains(p.id))) + { + NetworkClient.Send(new SpawnPlayerMessage(p.id, PlayerType.Local)); + } } #endregion diff --git a/Assets/Scripts/Control&Input/ReturnToMainMenuGate.cs b/Assets/Scripts/Control&Input/ReturnToMainMenuGate.cs index f6e94ae42..e1615f41d 100644 --- a/Assets/Scripts/Control&Input/ReturnToMainMenuGate.cs +++ b/Assets/Scripts/Control&Input/ReturnToMainMenuGate.cs @@ -9,10 +9,9 @@ public void Interact(PlayerManager player) ReturnToMainMenu(); } - private void OnCollisionEnter(Collision collision) + private void OnTriggerEnter(Collider other) { - var contact = collision.GetContact(0); - if (contact.otherCollider.TryGetComponent(out var _)) + if (other.TryGetComponent(out var _)) ReturnToMainMenu(); } diff --git a/Assets/Scripts/Extensions/PortalExtension/PortalExtensionController.cs b/Assets/Scripts/Extensions/PortalExtension/PortalExtensionController.cs index 5e77ebbb6..b0b926ac5 100644 --- a/Assets/Scripts/Extensions/PortalExtension/PortalExtensionController.cs +++ b/Assets/Scripts/Extensions/PortalExtension/PortalExtensionController.cs @@ -12,7 +12,7 @@ public class PortalExtensionController : GunExtension private Transform portalMover; - private GunController gunGontroller; + private GunController gunController; private Transform playerView; private InputManager inputManager; @@ -22,12 +22,12 @@ public class PortalExtensionController : GunExtension private void Start() { - if (!gunGontroller) - gunGontroller = GetComponentInParent(); + if (!gunController) + gunController = GetComponentInParent(); - if (gunGontroller != null) + if (gunController != null) { - gunGontroller.AimCorrectionEnabled = false; + gunController.AimCorrectionEnabled = false; inputManager = GetComponentInParent().inputManager; if (inputManager) playerView = inputManager.transform; @@ -36,8 +36,8 @@ private void Start() private void OnDestroy() { - if (gunGontroller) - gunGontroller.AimCorrectionEnabled = true; + if (gunController) + gunController.AimCorrectionEnabled = true; if (portalMover) Destroy(portalMover.gameObject); } @@ -111,17 +111,17 @@ private void Update() public override Transform[] AttachToTransforms(Transform[] transforms) { - gunGontroller = GetComponentInParent(); + gunController = GetComponentInParent(); var portalMoverObject = Instantiate(portalMoverPrefab); output = portalMoverObject.GetComponent().Output; portalMoverObject.transform.rotation = transform.rotation; portalMoverObject.transform.position = transform.position - output.localPosition; portalMover = portalMoverObject.transform; outputs = new Transform[] { output }; - var barrel = gunGontroller.GetComponentInChildren(); + var barrel = gunController.GetComponentInChildren(); if (barrel && barrel.MuzzleFlash) barrel.MuzzleFlash.enabled = false; - if (!gunGontroller || !gunGontroller.Player) + if (!gunController || !gunController.Player) foreach (Transform child in portalMoverObject.transform) child.gameObject.SetActive(false); return new Transform[] { output }; diff --git a/Assets/Scripts/Gamestate/MatchController.cs b/Assets/Scripts/Gamestate/MatchController.cs index 8013f7f00..f4f28ce2a 100644 --- a/Assets/Scripts/Gamestate/MatchController.cs +++ b/Assets/Scripts/Gamestate/MatchController.cs @@ -14,10 +14,7 @@ public class MatchController : MonoBehaviour { public static MatchController Singleton { get; private set; } - private PlayerFactory playerFactory; - public delegate void MatchEvent(); - public MatchEvent? onOutcomeDecided; public MatchEvent? onRoundEnd; public MatchEvent? onRoundStart; @@ -34,9 +31,6 @@ public class MatchController : MonoBehaviour [SerializeField] private float roundEndDelay; - [SerializeField] - private float biddingEndDelay = 10; - [SerializeField] private float matchEndDelay = 5; @@ -102,6 +96,7 @@ private void Awake() #endregion Singleton boilerplate + players = new(); Players = new ReadOnlyCollection(players); } @@ -111,7 +106,6 @@ void Start() { PlayerInputManagerController.Singleton.LocalPlayerInputs.ForEach(input => input.GetComponent().ResetItems()); } - playerFactory = FindObjectOfType(); currentMapName ??= SceneManager.GetActiveScene().name; @@ -318,8 +312,14 @@ public void ReturnToMainMenu() .Where(identity => identity.IsAI) .ToList().ForEach(aiIdentity => Destroy(aiIdentity)); - MusicTrackManager.Singleton.SwitchTo(MusicType.Menu); rounds = new List(); - NetworkManager.singleton.ServerChangeScene(Scenes.Menu); + MusicTrackManager.Singleton.SwitchTo(MusicType.Menu); + PlayerInputManagerController.Singleton.ChangeInputMaps("Menu"); + SceneManager.LoadSceneAsync(Scenes.Menu); + + if (NetworkServer.active) + NetworkManager.singleton.StopHost(); + else + NetworkManager.singleton.StopClient(); } } diff --git a/Assets/Scripts/Gamestate/PlayerFactory.cs b/Assets/Scripts/Gamestate/PlayerFactory.cs index 4b462f225..0b2c57d92 100644 --- a/Assets/Scripts/Gamestate/PlayerFactory.cs +++ b/Assets/Scripts/Gamestate/PlayerFactory.cs @@ -2,34 +2,17 @@ using UnityEngine.SceneManagement; using System.Collections.Generic; using UnityEngine; -using System.Linq; using CollectionExtensions; -using Mirror; public class PlayerFactory : MonoBehaviour { - - [SerializeField] - private GameObject playerPrefab; [SerializeField] private Transform[] spawnPoints; [SerializeField] private GameObject playerSelectItemPrefab; - [SerializeField] - private GameObject aIOpponent; - [SerializeField] - private GameObject aIBidder; - [SerializeField] - private GameObject aiIdentity; - private List existingAiIdentities; private float spawnInterval = 0f; private PlayerInputManagerController playerInputManagerController; - [SerializeField] - private GlobalHUDController globalHUDController; - [SerializeField] - private bool overrideMatchManager = false; - private void Awake() { if (PlayerInputManagerController.Singleton == null) @@ -41,34 +24,11 @@ private void Awake() playerInputManagerController = PlayerInputManagerController.Singleton; // Enable splitscreen + // TODO nullrefexcept playerInputManagerController.PlayerInputManager.DisableJoining(); playerInputManagerController.PlayerInputManager.splitScreen = true; - - existingAiIdentities = FindObjectsOfType() - .Where(identity => identity.IsAI).ToList(); - - if (!overrideMatchManager) - return; - - playerInputManagerController.LocalPlayerInputs.ForEach(input => input.GetComponent().ResetItems()); - InstantiatePlayersFPS(); } - public List InstantiatePlayersFPS(int aiPlayerCount = 0) - { - playerInputManagerController.ChangeInputMaps("FPS"); - if (NetworkManager.singleton.isNetworkActive) - return new List(); - return InstantiateInputsOnSpawnpoints(InstantiateFPSPlayer, InstantiateFPSAI, aiPlayerCount); - } - - public void InstantiatePlayersBidding(int aiPLayerCount = 0) - { - playerInputManagerController.ChangeInputMaps("Bidding"); - if (NetworkManager.singleton.isNetworkActive) - return; - InstantiateInputsOnSpawnpoints(InstantiateBiddingPlayer, InstantiateBiddingAI, aiPLayerCount); - } public void InstantiatePlayerSelectItems() { playerInputManagerController.ChangeInputMaps("Menu"); @@ -100,73 +60,6 @@ public Transform[] GetRandomSpawnpoints() return spawnPoints.ShuffledCopy(); } - - /// - /// Spawns a playerPrefab and attaches a playerInput to it as a child. - /// This function is where you should add delegate events for them to be properly invoked. - /// - /// PlayerInput to tie the player prefab to. - public PlayerManager InstantiateFPSPlayer(InputManager inputManager, Transform spawnPoint) - { - // Spawn player at spawnPoint's position with spawnPoint's rotation - GameObject player = Instantiate(playerPrefab, spawnPoint.position, spawnPoint.rotation); - Transform cameraOffset = player.transform.Find("CameraOffset"); - - // Make playerInput child of player it's attached to - inputManager.transform.parent = player.transform; - - // Tell the network synchronization that the player prefab should be synced - if (inputManager.TryGetComponent(out var networkTransform)) - { - networkTransform.target = player.transform; - var animator = inputManager.GetComponent(); - animator.animator = player.GetComponent().Animator; - animator.enabled = true; - } - - - // Set recieved playerInput (and most importantly its camera) at an offset from player's position - inputManager.transform.localPosition = cameraOffset.localPosition; - inputManager.transform.rotation = player.transform.rotation; - - // Enable Camera - inputManager.PlayerCamera.enabled = true; - inputManager.PlayerCamera.orthographic = false; - - // Update player's movement script with which playerInput it should attach listeners to - var playerManager = player.GetComponent(); - playerManager.SetPlayerInput(inputManager); - playerManager.SetGun(inputManager.transform.GetChild(0)); - - // TODO determine a better place to put this! - if (GunFactory.TryGetGunAchievement(playerManager.identity.Body, playerManager.identity.Barrel, playerManager.identity.Extension, out var achievement)) - SteamManager.Singleton.UnlockAchievement(achievement); - - // Set unique layer for player - playerManager.SetLayer(inputManager.playerInput.playerIndex); - playerManager.GetComponent().SetInitialRotation(spawnPoint.eulerAngles.y * Mathf.Deg2Rad); - return playerManager; - } - - private PlayerManager InstantiateBiddingPlayer(InputManager inputManager, Transform spawnPoint) - { - // Spawn player at spawnPoint's position with spawnPoint's rotation - GameObject player = Instantiate(playerPrefab, spawnPoint.position, spawnPoint.rotation); - Transform cameraOffset = player.transform.Find("CameraOffset"); - // Make playerInput child of player it's attached to - inputManager.transform.parent = player.transform; - // Make playerInput (with the gun) get placed at correct position - inputManager.transform.localPosition = cameraOffset.localPosition; - inputManager.transform.rotation = player.transform.rotation; - // Disable Camera - inputManager.PlayerCamera.enabled = false; - // Update player's movement script with which playerInput it should attach listeners to - var playerManager = player.GetComponent(); - playerManager.SetPlayerInput(inputManager); - player.GetComponent().enabled = false; - return playerManager; - } - private PlayerManager InstantiateItemSelectPlayer(InputManager inputManager, Transform spawnPoint) { inputManager.PlayerCamera.enabled = true; @@ -177,33 +70,4 @@ private PlayerManager InstantiateItemSelectPlayer(InputManager inputManager, Tra StartCoroutine(player.GetComponent().SpawnItems(inputManager)); return null; } - - private AIManager InstantiateFPSAI(int index, Transform spawnPoint) - { - PlayerIdentity identity = null; - - if (existingAiIdentities.Count == 0) - { - var identityObject = Instantiate(aiIdentity); - identity = identityObject.GetComponent(); - identity.playerName = $"HCU {index + 1}"; - DontDestroyOnLoad(identityObject); - } - - var aiOpponent = Instantiate(aIOpponent, spawnPoint.position, spawnPoint.rotation); - AIManager manager = aiOpponent.GetComponent(); - manager.SetLayer(index); - manager.SetIdentity(identity ? identity : existingAiIdentities[index - playerInputManagerController.LocalPlayerInputs.Count]); - manager.GetComponent().SetInitialRotation(spawnPoint.eulerAngles.y * Mathf.Deg2Rad); - return manager; - } - - private AIManager InstantiateBiddingAI(int index, Transform spawnPoint) - { - var aiOpponent = Instantiate(aIBidder, spawnPoint.position, spawnPoint.rotation); - AIManager manager = aiOpponent.GetComponent(); - manager.SetLayer(index); - manager.SetIdentity(existingAiIdentities[index - playerInputManagerController.LocalPlayerInputs.Count]); - return manager; - } } diff --git a/Assets/Scripts/Gamestate/PlayerManager.cs b/Assets/Scripts/Gamestate/PlayerManager.cs index 3c21d587e..4b0972796 100644 --- a/Assets/Scripts/Gamestate/PlayerManager.cs +++ b/Assets/Scripts/Gamestate/PlayerManager.cs @@ -262,6 +262,7 @@ public void ApplyIdentity() meshBase.GetComponentInChildren().material.color = identity.color; if (playerIK.TryGetComponent(out var biddingPlayer)) { + // TODO refactor identity subscriptions biddingPlayer.SetIdentity(); } } diff --git a/Assets/Scripts/Utils/SteamManager.cs b/Assets/Scripts/Utils/SteamManager.cs index 5c10451ca..738b9b102 100644 --- a/Assets/Scripts/Utils/SteamManager.cs +++ b/Assets/Scripts/Utils/SteamManager.cs @@ -28,7 +28,7 @@ public class SteamManager : MonoBehaviour { private const int steamAppID = 2717710; public static SteamManager Singleton; - public int ConnectedPlayers => transportProtocol.numPlayers; + public int ConnectedPlayers => NetworkManager.singleton.numPlayers; private static bool isSteamInitialized; public static bool IsSteamActive => isSteamInitialized; public bool IsHosting = false; @@ -54,8 +54,6 @@ public class SteamManager : MonoBehaviour private Callback lobbyDataRequest; private const string hostkey = "HostAddress"; - [SerializeField] - private Peer2PeerTransport transportProtocol; private void Awake() { @@ -155,7 +153,7 @@ private void OnlobbyCreated(LobbyCreated_t callback) { if (callback.m_eResult != EResult.k_EResultOK) return; - transportProtocol.StartHost(); + NetworkManager.singleton.StartHost(); IsHosting = true; SteamMatchmaking.SetLobbyData(new CSteamID(callback.m_ulSteamIDLobby), hostkey, SteamUser.GetSteamID().ToString()); SteamMatchmaking.SetLobbyData(new CSteamID(callback.m_ulSteamIDLobby), "name", UserName); @@ -193,7 +191,7 @@ private void OnLobbyEnter(LobbyEnter_t callback) if (NetworkServer.active) return; // Only clients from here! - transportProtocol.JoinLobby(SteamMatchmaking.GetLobbyData(new CSteamID(callback.m_ulSteamIDLobby), hostkey)); + ((Peer2PeerTransport)NetworkManager.singleton).JoinLobby(SteamMatchmaking.GetLobbyData(new CSteamID(callback.m_ulSteamIDLobby), hostkey)); } private void OnLobbyUpdate(LobbyChatUpdate_t callback) @@ -208,7 +206,7 @@ public void HostLobby() return; // TODO support public and friend lobbies - SteamMatchmaking.CreateLobby(ELobbyType.k_ELobbyTypePublic, transportProtocol.maxConnections); + SteamMatchmaking.CreateLobby(ELobbyType.k_ELobbyTypePublic, NetworkManager.singleton.maxConnections); } public void LeaveLobby() @@ -217,13 +215,13 @@ public void LeaveLobby() return; if (IsHosting) { - transportProtocol.StopHost(); + NetworkManager.singleton.StopHost(); IsHosting = false; } else { - if (transportProtocol.isNetworkActive) - transportProtocol.StopClient(); + if (NetworkManager.singleton.isNetworkActive) + NetworkManager.singleton.StopClient(); } }