Skip to content

Commit

Permalink
feat: move spawned dictionary to com/som (#568)
Browse files Browse the repository at this point in the history
* feat: add pawned dictionary to com/som

* simplify

* update most refs. some still remain

* client uses serverobjectmanagers dictionary when in host mode

* com and som use own collections now

* remove old spawned collections from server and client

* remove unused using

* fix code smells
  • Loading branch information
uweeby committed Feb 15, 2021
1 parent 93d7884 commit 1ad8f3d
Show file tree
Hide file tree
Showing 9 changed files with 65 additions and 56 deletions.
43 changes: 31 additions & 12 deletions Assets/Mirror/Runtime/ClientObjectManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,25 @@ public class SpawnEvent : UnityEvent<NetworkIdentity> { }
/// </summary>
public readonly Dictionary<ulong, NetworkIdentity> spawnableObjects = new Dictionary<ulong, NetworkIdentity>();

/// <summary>
/// List of all objects spawned in this client
/// </summary>
public Dictionary<uint, NetworkIdentity> SpawnedObjects
{
get
{
// if we are in host mode, the list of spawned object is the same as the server list
if (Client.IsLocalClient)
return ServerObjectManager.SpawnedObjects;
else
return spawnedObjects;
}
}

internal readonly Dictionary<uint, NetworkIdentity> spawnedObjects = new Dictionary<uint, NetworkIdentity>();

internal ServerObjectManager ServerObjectManager;

public void Start()
{
if (Client != null)
Expand Down Expand Up @@ -318,14 +337,14 @@ void UnSpawn(NetworkIdentity identity)
/// </summary>
public void DestroyAllClientObjects()
{
foreach (NetworkIdentity identity in Client.Spawned.Values)
foreach (NetworkIdentity identity in SpawnedObjects.Values)
{
if (identity != null && identity.gameObject != null)
{
UnSpawn(identity);
}
}
Client.Spawned.Clear();
SpawnedObjects.Clear();
}

void ApplySpawnPayload(NetworkIdentity identity, SpawnMessage msg)
Expand Down Expand Up @@ -360,7 +379,7 @@ void ApplySpawnPayload(NetworkIdentity identity, SpawnMessage msg)
}
}

Client.Spawned[msg.netId] = identity;
SpawnedObjects[msg.netId] = identity;

// objects spawned as part of initial state are started on a second pass
identity.NotifyAuthority();
Expand Down Expand Up @@ -402,7 +421,7 @@ internal void OnSpawn(SpawnMessage msg)

NetworkIdentity GetExistingObject(uint netid)
{
Client.Spawned.TryGetValue(netid, out NetworkIdentity localObject);
SpawnedObjects.TryGetValue(netid, out NetworkIdentity localObject);
return localObject;
}

Expand Down Expand Up @@ -477,10 +496,10 @@ void DestroyObject(uint netId)
{
if (logger.LogEnabled()) logger.Log("ClientScene.OnObjDestroy netId:" + netId);

if (Client.Spawned.TryGetValue(netId, out NetworkIdentity localObject) && localObject != null)
if (SpawnedObjects.TryGetValue(netId, out NetworkIdentity localObject) && localObject != null)
{
UnSpawn(localObject);
Client.Spawned.Remove(netId);
SpawnedObjects.Remove(netId);
}
else
{
Expand All @@ -492,22 +511,22 @@ internal void OnHostClientObjectDestroy(ObjectDestroyMessage msg)
{
if (logger.LogEnabled()) logger.Log("ClientScene.OnLocalObjectObjDestroy netId:" + msg.netId);

Client.Spawned.Remove(msg.netId);
SpawnedObjects.Remove(msg.netId);
}

internal void OnHostClientObjectHide(ObjectHideMessage msg)
{
if (logger.LogEnabled()) logger.Log("ClientScene::OnLocalObjectObjHide netId:" + msg.netId);

if (Client.Spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null)
if (SpawnedObjects.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null)
{
localObject.OnSetHostVisibility(false);
}
}

internal void OnHostClientSpawn(SpawnMessage msg)
{
if (Client.Spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null)
if (SpawnedObjects.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null)
{
if (msg.isLocalPlayer)
InternalAddPlayer(localObject);
Expand All @@ -526,7 +545,7 @@ internal void OnUpdateVarsMessage(UpdateVarsMessage msg)
{
if (logger.LogEnabled()) logger.Log("ClientScene.OnUpdateVarsMessage " + msg.netId);

if (Client.Spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null)
if (SpawnedObjects.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null)
{
using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(msg.payload))
localObject.OnDeserializeAllSafely(networkReader, false);
Expand All @@ -547,7 +566,7 @@ internal void OnRpcMessage(RpcMessage msg)
{
throw new MethodInvocationException($"Invalid RPC call with id {msg.functionHash}");
}
if (Client.Spawned.TryGetValue(msg.netId, out NetworkIdentity identity) && identity != null)
if (SpawnedObjects.TryGetValue(msg.netId, out NetworkIdentity identity) && identity != null)
{
using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(msg.payload))
{
Expand Down Expand Up @@ -593,7 +612,7 @@ private void OnServerRpcReply(INetworkConnection connection, ServerRpcReply repl
{
get
{
Client.Spawned.TryGetValue(netId, out NetworkIdentity identity);
SpawnedObjects.TryGetValue(netId, out NetworkIdentity identity);
return identity;
}
}
Expand Down
20 changes: 1 addition & 19 deletions Assets/Mirror/Runtime/NetworkClient.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Cysharp.Threading.Tasks;
using UnityEngine;
Expand Down Expand Up @@ -32,8 +31,6 @@ public class NetworkClient : MonoBehaviour, INetworkClient
[Tooltip("Authentication component attached to this object")]
public NetworkAuthenticator authenticator;

internal readonly Dictionary<uint, NetworkIdentity> spawned = new Dictionary<uint, NetworkIdentity>();

[Header("Events")]
/// <summary>
/// Event fires once the Client has connected its Server.
Expand Down Expand Up @@ -75,21 +72,6 @@ public class NetworkClient : MonoBehaviour, INetworkClient

public readonly NetworkTime Time = new NetworkTime();

/// <summary>
/// List of all objects spawned in this client
/// </summary>
public Dictionary<uint, NetworkIdentity> Spawned
{
get
{
// if we are in host mode, the list of spawned object is the same as the server list
if (hostServer != null)
return hostServer.Spawned;
else
return spawned;
}
}

/// <summary>
/// The host server
/// </summary>
Expand Down Expand Up @@ -318,4 +300,4 @@ void Cleanup()
}
}
}
}
}
4 changes: 1 addition & 3 deletions Assets/Mirror/Runtime/NetworkServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,6 @@ public class NetworkServer : MonoBehaviour, INetworkServer
/// </summary>
public bool Active { get; private set; }

public readonly Dictionary<uint, NetworkIdentity> Spawned = new Dictionary<uint, NetworkIdentity>();

// Time kept in this server
public readonly NetworkTime Time = new NetworkTime();

Expand Down Expand Up @@ -392,4 +390,4 @@ internal void OnAuthenticated(INetworkConnection conn)
Authenticated?.Invoke(conn);
}
}
}
}
30 changes: 20 additions & 10 deletions Assets/Mirror/Runtime/ServerObjectManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ public class SpawnEvent : UnityEvent<NetworkIdentity> { }
uint nextNetworkId = 1;
uint GetNextNetworkId() => nextNetworkId++;

public readonly Dictionary<uint, NetworkIdentity> SpawnedObjects = new Dictionary<uint, NetworkIdentity>();

public readonly HashSet<NetworkIdentity> DirtyObjects = new HashSet<NetworkIdentity>();
private readonly List<NetworkIdentity> DirtyObjectsTmp = new List<NetworkIdentity>();
Expand All @@ -53,7 +54,7 @@ public class SpawnEvent : UnityEvent<NetworkIdentity> { }
{
get
{
Server.Spawned.TryGetValue(netId, out NetworkIdentity identity);
SpawnedObjects.TryGetValue(netId, out NetworkIdentity identity);
return identity;
}
}
Expand All @@ -63,6 +64,7 @@ public void Start()
if (Server != null)
{
Server.Started.AddListener(SpawnOrActivate);
Server.OnStartHost.AddListener(StartedHost);
Server.Authenticated.AddListener(OnAuthenticated);
Server.Stopped.AddListener(OnServerStopped);
NetworkSceneManager.ServerChangeScene.AddListener(OnServerChangeScene);
Expand Down Expand Up @@ -108,13 +110,13 @@ void OnAuthenticated(INetworkConnection connection)

void OnServerStopped()
{
foreach (NetworkIdentity obj in Server.Spawned.Values.Reverse())
foreach (NetworkIdentity obj in SpawnedObjects.Values.Reverse())
{
if (obj.AssetId != Guid.Empty)
DestroyObject(obj, true);
}

Server.Spawned.Clear();
SpawnedObjects.Clear();
}

void OnServerChangeScene(string scenePath, SceneOperation sceneOperation)
Expand Down Expand Up @@ -142,14 +144,22 @@ void SpawnOrActivate()
}
}

void StartedHost()
{
if (TryGetComponent(out ClientObjectManager ClientObjectManager))
{
ClientObjectManager.ServerObjectManager = this;
}
}

/// <summary>
/// Loops spawned collection for NetworkIdentieis that are not IsClient and calls StartClient().
/// </summary>
internal void ActivateHostScene()
{
SpawnObjects();

foreach (NetworkIdentity identity in Server.Spawned.Values)
foreach (NetworkIdentity identity in SpawnedObjects.Values)
{
if (!identity.IsClient)
{
Expand Down Expand Up @@ -193,7 +203,7 @@ public bool ReplacePlayerForConnection(INetworkConnection conn, NetworkClient cl

void SpawnObserversForConnection(INetworkConnection conn)
{
if (logger.LogEnabled()) logger.Log("Spawning " + Server.Spawned.Count + " objects for conn " + conn);
if (logger.LogEnabled()) logger.Log("Spawning " + SpawnedObjects.Count + " objects for conn " + conn);

if (!conn.IsReady)
{
Expand All @@ -204,7 +214,7 @@ void SpawnObserversForConnection(INetworkConnection conn)

// add connection to each nearby NetworkIdentity's observers, which
// internally sends a spawn message for each one to the connection.
foreach (NetworkIdentity identity in Server.Spawned.Values)
foreach (NetworkIdentity identity in SpawnedObjects.Values)
{
if (identity.gameObject.activeSelf)
{
Expand Down Expand Up @@ -401,7 +411,7 @@ public void RemovePlayerForConnection(INetworkConnection conn, bool destroyServe
/// <param name="msg"></param>
void OnServerRpcMessage(INetworkConnection conn, ServerRpcMessage msg)
{
if (!Server.Spawned.TryGetValue(msg.netId, out NetworkIdentity identity) || identity is null)
if (!SpawnedObjects.TryGetValue(msg.netId, out NetworkIdentity identity) || identity is null)
{
if (logger.WarnEnabled()) logger.LogWarning("Spawned object not found when handling ServerRpc message [netId=" + msg.netId + "]");
return;
Expand Down Expand Up @@ -458,7 +468,7 @@ internal void SpawnObject(GameObject obj, INetworkConnection ownerConnection)
{
// the object has not been spawned yet
identity.NetId = GetNextNetworkId();
Server.Spawned[identity.NetId] = identity;
SpawnedObjects[identity.NetId] = identity;
identity.StartServer();
Spawned.Invoke(identity);
}
Expand Down Expand Up @@ -607,7 +617,7 @@ void DestroyObject(NetworkIdentity identity, bool destroyServerObject)
if (logger.LogEnabled()) logger.Log("DestroyObject instance:" + identity.NetId);
UnSpawned.Invoke(identity);

Server.Spawned.Remove(identity.NetId);
SpawnedObjects.Remove(identity.NetId);
identity.ConnectionToClient?.RemoveOwnedObject(identity);

identity.SendToObservers(new ObjectDestroyMessage { netId = identity.NetId });
Expand Down Expand Up @@ -772,4 +782,4 @@ void OnClientReadyMessage(INetworkConnection conn, ReadyMessage msg)
SetClientReady(conn);
}
}
}
}
2 changes: 1 addition & 1 deletion Assets/Mirror/Samples~/Tanks/Scripts/TankGameManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ void GameReadyCheck()

void CheckPlayersNotInList()
{
foreach (KeyValuePair<uint, NetworkIdentity> kvp in NetworkManager.Client.Spawned)
foreach (KeyValuePair<uint, NetworkIdentity> kvp in NetworkManager.ClientObjectManager.SpawnedObjects)
{
Tank comp = kvp.Value.GetComponent<Tank>();
if (comp != null && !players.Contains(comp))
Expand Down
6 changes: 3 additions & 3 deletions Assets/Tests/Runtime/ClientServer/GameObjectSyncvarTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Collections;
using System.Collections;
using Cysharp.Threading.Tasks;
using NUnit.Framework;
using UnityEngine;
Expand Down Expand Up @@ -63,10 +63,10 @@ public void UpdateAfterSpawn()
// wait until the client spawns it
uint newObjectId = newBehavior.NetId;
await UniTask.WaitUntil(() => client.Spawned.ContainsKey(newObjectId));
await UniTask.WaitUntil(() => clientObjectManager.SpawnedObjects.ContainsKey(newObjectId));
// check if the target was set correctly in the client
NetworkIdentity newClientObject = client.Spawned[newObjectId];
NetworkIdentity newClientObject = clientObjectManager.SpawnedObjects[newObjectId];
SampleBehaviorWithGO newClientBehavior = newClientObject.GetComponent<SampleBehaviorWithGO>();
Assert.That(newClientBehavior.target, Is.SameAs(clientPlayerGO));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Collections;
using System.Collections;
using Cysharp.Threading.Tasks;
using NUnit.Framework;
using UnityEngine.TestTools;
Expand Down Expand Up @@ -62,10 +62,10 @@ public void UpdateAfterSpawn()
// wait until the client spawns it
uint newObjectId = newBehavior.NetId;
await UniTask.WaitUntil(() => client.Spawned.ContainsKey(newObjectId));
await UniTask.WaitUntil(() => clientObjectManager.SpawnedObjects.ContainsKey(newObjectId));
// check if the target was set correctly in the client
NetworkIdentity newClientObject = client.Spawned[newObjectId];
NetworkIdentity newClientObject = clientObjectManager.SpawnedObjects[newObjectId];
SampleBehaviorWithNB newClientBehavior = newClientObject.GetComponent<SampleBehaviorWithNB>();
Assert.That(newClientBehavior.target, Is.SameAs(clientComponent));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Collections;
using System.Collections;
using Cysharp.Threading.Tasks;
using NUnit.Framework;
using UnityEngine.TestTools;
Expand Down Expand Up @@ -67,10 +67,10 @@ public void UpdateAfterSpawn()
// wait until the client spawns it
uint newObjectId = newBehavior.NetId;
await UniTask.WaitUntil(() => client.Spawned.ContainsKey(newObjectId));
await UniTask.WaitUntil(() => clientObjectManager.SpawnedObjects.ContainsKey(newObjectId));
// check if the target was set correctly in the client
NetworkIdentity newClientObject = client.Spawned[newObjectId];
NetworkIdentity newClientObject = clientObjectManager.SpawnedObjects[newObjectId];
SampleBehaviorWithNI newClientBehavior = newClientObject.GetComponent<SampleBehaviorWithNI>();
Assert.That(newClientBehavior.target, Is.SameAs(clientIdentity));
Expand Down
4 changes: 2 additions & 2 deletions Assets/Tests/Runtime/Host/ServerObjectManagerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,13 @@ public void UnSpawn()
serverObjectManager.Spawn(spawnTestObj);
//1 is the player. should be 2 at this point
Assert.That(server.Spawned.Count, Is.GreaterThan(1));
Assert.That(serverObjectManager.SpawnedObjects.Count, Is.GreaterThan(1));
server.Disconnect();
await AsyncUtil.WaitUntilWithTimeout(() => !server.Active);
Assert.That(server.Spawned.Count, Is.Zero);
Assert.That(serverObjectManager.SpawnedObjects.Count, Is.Zero);
});
}
}

0 comments on commit 1ad8f3d

Please sign in to comment.