Merge pull request #227 from misternebula/qnet-cleanup

cleanup
This commit is contained in:
Mister_Nebula 2020-12-16 08:08:47 +00:00 committed by GitHub
commit bf45b4744c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
69 changed files with 1629 additions and 2478 deletions

View File

@ -145,15 +145,9 @@ namespace QSB.Animation
private void OnBecomeUngrounded() => _netAnim.SetTrigger("Ungrounded");
public void SendCrouch(float value = 0)
{
GlobalMessenger<float>.FireEvent(EventNames.QSBCrouch, value);
}
public void SendCrouch(float value = 0) => GlobalMessenger<float>.FireEvent(EventNames.QSBCrouch, value);
public void HandleCrouch(float value)
{
_crouchSync.CrouchParam.Target = value;
}
public void HandleCrouch(float value) => _crouchSync.CrouchParam.Target = value;
private void SuitUp()
{

View File

@ -1,5 +1,5 @@
using QSB.Messaging;
using QuantumUNET;
using QuantumUNET.Transport;
namespace QSB.ConversationSync.Events
{

View File

@ -1,5 +1,5 @@
using QSB.Messaging;
using QuantumUNET;
using QuantumUNET.Transport;
namespace QSB.ConversationSync.Events
{

View File

@ -1,5 +1,5 @@
using QSB.Messaging;
using QuantumUNET;
using QuantumUNET.Transport;
namespace QSB.DialogueConditionSync.Events
{

View File

@ -1,4 +1,4 @@
using QuantumUNET;
using QuantumUNET.Transport;
namespace QSB.Messaging
{

View File

@ -1,4 +1,4 @@
using QuantumUNET;
using QuantumUNET.Transport;
namespace QSB.Messaging
{

View File

@ -1,5 +1,5 @@
using QuantumUNET;
using QuantumUNET.Messages;
using QuantumUNET.Messages;
using QuantumUNET.Transport;
namespace QSB.Messaging
{

View File

@ -1,4 +1,4 @@
using QuantumUNET;
using QuantumUNET.Transport;
namespace QSB.Messaging
{

View File

@ -1,5 +1,5 @@
using QSB.Messaging;
using QuantumUNET;
using QuantumUNET.Transport;
namespace QSB.OrbSync.Events
{

View File

@ -1,5 +1,5 @@
using QSB.Messaging;
using QuantumUNET;
using QuantumUNET.Transport;
namespace QSB.Player.Events
{

View File

@ -1,5 +1,5 @@
using QSB.Messaging;
using QuantumUNET;
using QuantumUNET.Transport;
namespace QSB.Player.Events
{

View File

@ -191,7 +191,6 @@
<Compile Include="SectorSync\QSBSectorManager.cs" />
<Compile Include="TransformSync\TransformSync.cs" />
<Compile Include="Utility\GOExtensions.cs" />
<Compile Include="Utility\ListExtensions.cs" />
<Compile Include="Utility\UnetExtensions.cs" />
<Compile Include="WorldSync\Events\BoolWorldObjectMessage.cs" />
<Compile Include="WorldSync\Events\WorldObjectMessage.cs" />

View File

@ -43,6 +43,7 @@ namespace QSB
public void Awake()
{
base.Awake();
Instance = this;
_lobby = gameObject.AddComponent<QSBNetworkLobby>();

View File

@ -1,5 +1,5 @@
using QSB.Messaging;
using QuantumUNET;
using QuantumUNET.Transport;
namespace QSB.TimeSync.Events
{

View File

@ -1,4 +1,4 @@
using QuantumUNET;
using QuantumUNET.Transport;
namespace QSB.WorldSync.Events
{

View File

@ -1,5 +1,5 @@
using QSB.Messaging;
using QuantumUNET;
using QuantumUNET.Transport;
namespace QSB.WorldSync.Events
{

View File

@ -1,4 +1,5 @@
using QuantumUNET.Messages;
using QuantumUNET.Transport;
using UnityEngine;
namespace QuantumUNET.Components
@ -32,22 +33,22 @@ namespace QuantumUNET.Components
public void SetParameterAutoSend(int index, bool value)
{
if (value)
{
m_ParameterSendBits |= (uint)(1 << index);
}
else
{
m_ParameterSendBits &= (uint)~(1 << index);
}
}
public bool GetParameterAutoSend(int index)
{
return ((int)m_ParameterSendBits & 1 << index) != 0;
}
public bool GetParameterAutoSend(int index) =>
((int)m_ParameterSendBits & (1 << index)) != 0;
public override void OnStartAuthority()
{
public override void OnStartAuthority() =>
m_ParameterWriter = new QSBNetworkWriter();
}
private void FixedUpdate()
public void FixedUpdate()
{
if (m_ParameterWriter == null)
{
@ -134,7 +135,10 @@ namespace QuantumUNET.Components
else
{
if (!IsServer || LocalPlayerAuthority)
{
return;
}
QSBNetworkServer.SendToReady(gameObject, 41, parametersMessage);
}
}
@ -161,14 +165,11 @@ namespace QuantumUNET.Components
ReadParameters(reader, true);
}
internal void HandleAnimTriggerMsg(int hash)
{
m_Animator.SetTrigger(hash);
}
internal void HandleAnimTriggerMsg(int hash) => m_Animator.SetTrigger(hash);
private void WriteParameters(QSBNetworkWriter writer, bool autoSend)
{
for (int index = 0; index < m_Animator.parameters.Length; ++index)
for (var index = 0; index < m_Animator.parameters.Length; ++index)
{
if (!autoSend || GetParameterAutoSend(index))
{
@ -193,7 +194,7 @@ namespace QuantumUNET.Components
private void ReadParameters(QSBNetworkReader reader, bool autoSend)
{
for (int index = 0; index < m_Animator.parameters.Length; ++index)
for (var index = 0; index < m_Animator.parameters.Length; ++index)
{
if (!autoSend || GetParameterAutoSend(index))
{
@ -257,10 +258,7 @@ namespace QuantumUNET.Components
m_Animator.Play(stateNameHash, 0, normalizedTime);
}
public void SetTrigger(string triggerName)
{
SetTrigger(Animator.StringToHash(triggerName));
}
public void SetTrigger(string triggerName) => SetTrigger(Animator.StringToHash(triggerName));
public void SetTrigger(int hash)
{
@ -338,10 +336,16 @@ namespace QuantumUNET.Components
netMsg.ReadMessage(AnimationMessage);
var localObject = QSBClientScene.FindLocalObject(AnimationMessage.netId);
if (localObject == null)
{
return;
}
var component = localObject.GetComponent<QSBNetworkAnimator>();
if (component == null)
{
return;
}
var reader = new QSBNetworkReader(AnimationMessage.parameters);
component.HandleAnimMsg(AnimationMessage, reader);
}
@ -351,10 +355,16 @@ namespace QuantumUNET.Components
netMsg.ReadMessage(ParametersMessage);
var localObject = QSBClientScene.FindLocalObject(ParametersMessage.netId);
if (localObject == null)
{
return;
}
var component = localObject.GetComponent<QSBNetworkAnimator>();
if (component == null)
{
return;
}
var reader = new QSBNetworkReader(ParametersMessage.parameters);
component.HandleAnimParamsMsg(ParametersMessage, reader);
}
@ -364,10 +374,16 @@ namespace QuantumUNET.Components
netMsg.ReadMessage(TriggersMessage);
var localObject = QSBClientScene.FindLocalObject(TriggersMessage.netId);
if (localObject == null)
{
return;
}
var component = localObject.GetComponent<QSBNetworkAnimator>();
if (component == null)
{
return;
}
component.HandleAnimTriggerMsg(TriggersMessage.hash);
}
}

View File

@ -1,10 +1,10 @@
using OWML.Logging;
using QuantumUNET.Messages;
using QuantumUNET.Transport;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using UnityEngine;
using UnityEngine.Networking;
namespace QuantumUNET.Components
{
@ -13,10 +13,10 @@ namespace QuantumUNET.Components
public bool IsClient { get; private set; }
public bool IsServer => m_IsServer && QSBNetworkServer.active && m_IsServer;
public bool HasAuthority { get; private set; }
public NetworkInstanceId NetId { get; private set; }
public NetworkSceneId SceneId => m_SceneId;
public QSBNetworkInstanceId NetId { get; private set; }
public QSBNetworkSceneId SceneId => m_SceneId;
public QSBNetworkConnection ClientAuthorityOwner { get; private set; }
public NetworkHash128 AssetId => m_AssetId;
public QSBNetworkHash128 AssetId => m_AssetId;
public bool IsLocalPlayer { get; private set; }
public short PlayerControllerId { get; private set; } = -1;
public QSBNetworkConnection ConnectionToServer { get; private set; }
@ -64,7 +64,7 @@ namespace QuantumUNET.Components
internal void RemoveSubIdentity(QSBNetworkIdentity identityToRemove)
=> SubIdentities.Remove(identityToRemove);
internal void SetDynamicAssetId(NetworkHash128 newAssetId)
internal void SetDynamicAssetId(QSBNetworkHash128 newAssetId)
{
if (!m_AssetId.IsValid() || m_AssetId.Equals(newAssetId))
{
@ -121,18 +121,18 @@ namespace QuantumUNET.Components
}
}
internal static NetworkInstanceId GetNextNetworkId()
internal static QSBNetworkInstanceId GetNextNetworkId()
{
var value = s_NextNetworkId;
s_NextNetworkId += 1U;
return new NetworkInstanceId(value);
return new QSBNetworkInstanceId(value);
}
private void CacheBehaviours()
{
if (m_NetworkBehaviours == null)
{
m_NetworkBehaviours = base.GetComponents<QSBNetworkBehaviour>();
m_NetworkBehaviours = GetComponents<QSBNetworkBehaviour>();
}
}
@ -144,7 +144,7 @@ namespace QuantumUNET.Components
}
}
internal void SetNetworkInstanceId(NetworkInstanceId newNetId)
internal void SetNetworkInstanceId(QSBNetworkInstanceId newNetId)
{
NetId = newNetId;
if (newNetId.Value == 0U)
@ -153,7 +153,7 @@ namespace QuantumUNET.Components
}
}
public void ForceSceneId(int newSceneId) => m_SceneId = new NetworkSceneId((uint)newSceneId);
public void ForceSceneId(int newSceneId) => m_SceneId = new QSBNetworkSceneId((uint)newSceneId);
internal void UpdateClientServer(bool isClientFlag, bool isServerFlag)
{
@ -179,11 +179,11 @@ namespace QuantumUNET.Components
}
}
private void OnDestroy()
public void OnDestroy()
{
if (m_IsServer && QSBNetworkServer.active)
{
QSBNetworkServer.Destroy(base.gameObject);
QSBNetworkServer.Destroy(gameObject);
}
}
@ -233,7 +233,7 @@ namespace QuantumUNET.Components
}
if (QSBNetworkClient.active && QSBNetworkServer.localClientActive)
{
QSBClientScene.SetLocalObject(NetId, base.gameObject);
QSBClientScene.SetLocalObject(NetId, gameObject);
OnStartClient();
}
if (HasAuthority)
@ -253,7 +253,7 @@ namespace QuantumUNET.Components
Debug.Log(string.Concat(new object[]
{
"OnStartClient ",
base.gameObject,
gameObject,
" GUID:",
NetId,
" localPlayerAuthority:",
@ -355,7 +355,7 @@ namespace QuantumUNET.Components
{
if (!LocalPlayerAuthority)
{
Debug.LogError("HandleClientAuthority " + base.gameObject + " does not have localPlayerAuthority");
Debug.LogError("HandleClientAuthority " + gameObject + " does not have localPlayerAuthority");
}
else
{
@ -384,7 +384,7 @@ namespace QuantumUNET.Components
"Found no behaviour for incoming [",
cmdHashHandlerName,
"] on ",
base.gameObject,
gameObject,
", the server and client should have the same NetworkBehaviour instances [netId=",
NetId,
"]."
@ -402,7 +402,7 @@ namespace QuantumUNET.Components
internal void HandleSyncEvent(int cmdHash, QSBNetworkReader reader)
{
if (base.gameObject == null)
if (gameObject == null)
{
var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash);
Debug.LogWarning(string.Concat(new object[]
@ -422,7 +422,7 @@ namespace QuantumUNET.Components
"Found no receiver for incoming [",
cmdHashHandlerName2,
"] on ",
base.gameObject,
gameObject,
", the server and client should have the same NetworkBehaviour instances [netId=",
NetId,
"]."
@ -448,7 +448,7 @@ namespace QuantumUNET.Components
internal void HandleSyncList(int cmdHash, QSBNetworkReader reader)
{
if (base.gameObject == null)
if (gameObject == null)
{
var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash);
Debug.LogWarning(string.Concat(new object[]
@ -468,7 +468,7 @@ namespace QuantumUNET.Components
"Found no receiver for incoming [",
cmdHashHandlerName2,
"] on ",
base.gameObject,
gameObject,
", the server and client should have the same NetworkBehaviour instances [netId=",
NetId,
"]."
@ -494,7 +494,7 @@ namespace QuantumUNET.Components
internal void HandleCommand(int cmdHash, QSBNetworkReader reader)
{
if (base.gameObject == null)
if (gameObject == null)
{
var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash);
Debug.LogWarning(string.Concat(new object[]
@ -514,7 +514,7 @@ namespace QuantumUNET.Components
"Found no receiver for incoming [",
cmdHashHandlerName2,
"] on ",
base.gameObject,
gameObject,
", the server and client should have the same NetworkBehaviour instances [netId=",
NetId,
"]."
@ -540,7 +540,7 @@ namespace QuantumUNET.Components
internal void HandleRPC(int cmdHash, QSBNetworkReader reader)
{
if (base.gameObject == null)
if (gameObject == null)
{
var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(cmdHash);
Debug.LogWarning(string.Concat(new object[]
@ -560,7 +560,7 @@ namespace QuantumUNET.Components
"Found no receiver for incoming [",
cmdHashHandlerName2,
"] on ",
base.gameObject,
gameObject,
", the server and client should have the same NetworkBehaviour instances [netId=",
NetId,
"]."
@ -627,7 +627,7 @@ namespace QuantumUNET.Components
Debug.LogWarning(string.Concat(new object[]
{
"Large state update of ",
(int)(s_UpdateWriter.Position - position),
s_UpdateWriter.Position - position,
" bytes for netId:",
NetId,
" from script:",
@ -639,7 +639,7 @@ namespace QuantumUNET.Components
if (flag)
{
s_UpdateWriter.FinishMessage();
QSBNetworkServer.SendWriterToReady(base.gameObject, s_UpdateWriter, j);
QSBNetworkServer.SendWriterToReady(gameObject, s_UpdateWriter, j);
}
}
IL_197:
@ -654,7 +654,7 @@ namespace QuantumUNET.Components
{
if (initialState && m_NetworkBehaviours == null)
{
m_NetworkBehaviours = base.GetComponents<QSBNetworkBehaviour>();
m_NetworkBehaviours = GetComponents<QSBNetworkBehaviour>();
}
for (var i = 0; i < m_NetworkBehaviours.Length; i++)
{
@ -668,7 +668,7 @@ namespace QuantumUNET.Components
ModConsole.OwmlConsole.WriteLine($"SetLocalPlayer {localPlayerControllerId}");
IsLocalPlayer = true;
PlayerControllerId = localPlayerControllerId;
var hasAuthority = this.HasAuthority;
var hasAuthority = HasAuthority;
if (LocalPlayerAuthority)
{
HasAuthority = true;
@ -723,7 +723,7 @@ namespace QuantumUNET.Components
{
if (m_Observers == null)
{
Debug.LogError("AddObserver for " + base.gameObject + " observer list is null");
Debug.LogError("AddObserver for " + gameObject + " observer list is null");
}
else if (m_ObserverConnections.Contains(conn.connectionId))
{
@ -732,7 +732,7 @@ namespace QuantumUNET.Components
"Duplicate observer ",
conn.address,
" added for ",
base.gameObject
gameObject
}));
}
else
@ -742,7 +742,7 @@ namespace QuantumUNET.Components
"Added observer ",
conn.address,
" added for ",
base.gameObject
gameObject
}));
m_Observers.Add(conn);
m_ObserverConnections.Add(conn.connectionId);
@ -812,7 +812,7 @@ namespace QuantumUNET.Components
Debug.LogWarning(string.Concat(new object[]
{
"Observer is not ready for ",
base.gameObject,
gameObject,
" ",
networkConnection3
}));
@ -823,7 +823,7 @@ namespace QuantumUNET.Components
Debug.Log(string.Concat(new object[]
{
"New Observer for ",
base.gameObject,
gameObject,
" ",
networkConnection3
}));
@ -839,7 +839,7 @@ namespace QuantumUNET.Components
Debug.Log(string.Concat(new object[]
{
"Removed Observer for ",
base.gameObject,
gameObject,
" ",
networkConnection4
}));
@ -883,12 +883,12 @@ namespace QuantumUNET.Components
}
else if (ClientAuthorityOwner == null)
{
Debug.LogError("RemoveClientAuthority for " + base.gameObject + " has no clientAuthority owner.");
Debug.LogError("RemoveClientAuthority for " + gameObject + " has no clientAuthority owner.");
return false;
}
else if (ClientAuthorityOwner != conn)
{
Debug.LogError("RemoveClientAuthority for " + base.gameObject + " has different owner.");
Debug.LogError("RemoveClientAuthority for " + gameObject + " has different owner.");
return false;
}
ClientAuthorityOwner.RemoveOwnedObject(this);
@ -917,12 +917,12 @@ namespace QuantumUNET.Components
}
else if (ClientAuthorityOwner != null && conn != ClientAuthorityOwner)
{
ModConsole.OwmlConsole.WriteLine("AssignClientAuthority for " + base.gameObject + " already has an owner. Use RemoveClientAuthority() first.");
ModConsole.OwmlConsole.WriteLine("AssignClientAuthority for " + gameObject + " already has an owner. Use RemoveClientAuthority() first.");
return false;
}
else if (conn == null)
{
ModConsole.OwmlConsole.WriteLine("AssignClientAuthority for " + base.gameObject + " owner cannot be null. Use RemoveClientAuthority() instead.");
ModConsole.OwmlConsole.WriteLine("AssignClientAuthority for " + gameObject + " owner cannot be null. Use RemoveClientAuthority() instead.");
return false;
}
ClientAuthorityOwner = conn;
@ -948,7 +948,7 @@ namespace QuantumUNET.Components
m_IsServer = false;
IsClient = false;
HasAuthority = false;
NetId = (NetworkInstanceId)typeof(NetworkInstanceId).GetField("Zero", System.Reflection.BindingFlags.Static).GetValue(null);
NetId = (QSBNetworkInstanceId)typeof(QSBNetworkInstanceId).GetField("Zero", System.Reflection.BindingFlags.Static).GetValue(null);
IsLocalPlayer = false;
ConnectionToServer = null;
ConnectionToClient = null;
@ -967,10 +967,10 @@ namespace QuantumUNET.Components
}
[SerializeField]
private NetworkSceneId m_SceneId;
private QSBNetworkSceneId m_SceneId;
[SerializeField]
private NetworkHash128 m_AssetId;
private QSBNetworkHash128 m_AssetId;
[SerializeField]
private bool m_ServerOnly;

View File

@ -9,10 +9,7 @@ namespace QuantumUNET.Components
public int offsetX;
public int offsetY;
private void Awake()
{
manager = GetComponent<QSBNetworkManagerUNET>();
}
private void Awake() => manager = GetComponent<QSBNetworkManagerUNET>();
private void OnGUI()
{

View File

@ -31,7 +31,6 @@ namespace QuantumUNET.Components
public float packetLossPercentage { get; set; }
public float maxDelay { get; set; } = 0.01f;
public GameObject playerPrefab { get; set; }
public PlayerSpawnMethod playerSpawnMethod { get; set; }
public List<GameObject> spawnPrefabs { get; } = new List<GameObject>();
public QSBNetworkClient client;
public int maxConnections { get; set; } = 4;
@ -41,8 +40,6 @@ namespace QuantumUNET.Components
private GlobalConfig m_GlobalConfig;
private int m_MaxBufferedPackets = 16;
private bool m_AllowFragmentation = true;
private static List<Transform> s_StartPositions = new List<Transform>();
private static int s_StartPositionIndex;
private static QSBAddPlayerMessage s_AddPlayerMessage = new QSBAddPlayerMessage();
private static QSBRemovePlayerMessage s_RemovePlayerMessage = new QSBRemovePlayerMessage();
private static QSBErrorMessage s_ErrorMessage = new QSBErrorMessage();
@ -50,14 +47,6 @@ namespace QuantumUNET.Components
private static QSBNetworkConnection s_ClientReadyConnection;
private static string s_Address;
public List<Transform> startPositions
{
get
{
return s_StartPositions;
}
}
public bool customConfig { get; set; }
public ConnectionConfig connectionConfig
@ -107,10 +96,7 @@ namespace QuantumUNET.Components
}
}
private void Awake()
{
InitializeSingleton();
}
public void Awake() => InitializeSingleton();
private void InitializeSingleton()
{
@ -121,14 +107,14 @@ namespace QuantumUNET.Components
if (singleton != null)
{
Debug.Log("Multiple NetworkManagers detected in the scene. Only one NetworkManager can exist at a time. The duplicate NetworkManager will not be used.");
Destroy(base.gameObject);
Destroy(gameObject);
return;
}
Debug.Log("NetworkManager created singleton (DontDestroyOnLoad)");
singleton = this;
if (Application.isPlaying)
{
DontDestroyOnLoad(base.gameObject);
DontDestroyOnLoad(gameObject);
}
}
else
@ -157,10 +143,7 @@ namespace QuantumUNET.Components
QSBNetworkServer.RegisterHandler(QSBMsgType.Error, new QSBNetworkMessageDelegate(OnServerErrorInternal));
}
public bool StartServer()
{
return StartServer(null, -1);
}
public bool StartServer() => StartServer(null, -1);
private bool StartServer(ConnectionConfig config, int maxConnections)
{
@ -193,26 +176,17 @@ namespace QuantumUNET.Components
{
if (!QSBNetworkServer.Listen(serverBindAddress, networkPort))
{
if (LogFilter.logError)
{
Debug.LogError("StartServer listen on " + serverBindAddress + " failed.");
}
Debug.LogError("StartServer listen on " + serverBindAddress + " failed.");
return false;
}
}
else if (!QSBNetworkServer.Listen(networkPort))
{
if (LogFilter.logError)
{
Debug.LogError("StartServer listen failed.");
}
Debug.LogError("StartServer listen failed.");
return false;
}
RegisterServerMessages();
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager StartServer port:" + networkPort);
}
Debug.Log("NetworkManager StartServer port:" + networkPort);
isNetworkActive = true;
var name = SceneManager.GetSceneAt(0).name;
if (!string.IsNullOrEmpty(onlineScene) && onlineScene != name && onlineScene != offlineScene)
@ -339,15 +313,9 @@ namespace QuantumUNET.Components
return client;
}
public QSBNetworkClient StartClient()
{
return StartClient(null);
}
public QSBNetworkClient StartClient() => StartClient(null);
public QSBNetworkClient StartClient(ConnectionConfig config)
{
return StartClient(config, 0);
}
public QSBNetworkClient StartClient(ConnectionConfig config) => StartClient(config, 0);
public virtual QSBNetworkClient StartHost(ConnectionConfig config, int maxConnections)
{
@ -386,10 +354,7 @@ namespace QuantumUNET.Components
private QSBNetworkClient ConnectLocalClient()
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager StartHost port:" + networkPort);
}
Debug.Log("NetworkManager StartHost port:" + networkPort);
networkAddress = "localhost";
client = QSBClientScene.ConnectLocalServer();
RegisterClientMessages(client);
@ -408,10 +373,7 @@ namespace QuantumUNET.Components
if (QSBNetworkServer.active)
{
OnStopServer();
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager StopServer");
}
Debug.Log("NetworkManager StopServer");
isNetworkActive = false;
QSBNetworkServer.Shutdown();
if (!string.IsNullOrEmpty(offlineScene))
@ -425,10 +387,7 @@ namespace QuantumUNET.Components
public void StopClient()
{
OnStopClient();
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager StopClient");
}
Debug.Log("NetworkManager StopClient");
isNetworkActive = false;
if (client != null)
{
@ -448,24 +407,16 @@ namespace QuantumUNET.Components
{
if (string.IsNullOrEmpty(newSceneName))
{
if (LogFilter.logError)
{
Debug.LogError("ServerChangeScene empty scene name");
}
Debug.LogError("ServerChangeScene empty scene name");
}
else
{
if (LogFilter.logDebug)
{
Debug.Log("ServerChangeScene " + newSceneName);
}
Debug.Log("ServerChangeScene " + newSceneName);
QSBNetworkServer.SetAllClientsNotReady();
networkSceneName = newSceneName;
s_LoadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName);
var msg = new QSBStringMessage(networkSceneName);
QSBNetworkServer.SendToAll(39, msg);
s_StartPositionIndex = 0;
s_StartPositions.Clear();
}
}
@ -481,17 +432,11 @@ namespace QuantumUNET.Components
{
if (string.IsNullOrEmpty(newSceneName))
{
if (LogFilter.logError)
{
Debug.LogError("ClientChangeScene empty scene name");
}
Debug.LogError("ClientChangeScene empty scene name");
}
else
{
if (LogFilter.logDebug)
{
Debug.Log("ClientChangeScene newSceneName:" + newSceneName + " networkSceneName:" + networkSceneName);
}
Debug.Log("ClientChangeScene newSceneName:" + newSceneName + " networkSceneName:" + networkSceneName);
if (newSceneName == networkSceneName)
{
if (!forceReload)
@ -549,47 +494,12 @@ namespace QuantumUNET.Components
}
}
public static void RegisterStartPosition(Transform start)
{
if (LogFilter.logDebug)
{
Debug.Log(string.Concat(new object[]
{
"RegisterStartPosition: (",
start.gameObject.name,
") ",
start.position
}));
}
s_StartPositions.Add(start);
}
public static void UnRegisterStartPosition(Transform start)
{
if (LogFilter.logDebug)
{
Debug.Log(string.Concat(new object[]
{
"UnRegisterStartPosition: (",
start.gameObject.name,
") ",
start.position
}));
}
s_StartPositions.Remove(start);
}
public bool IsClientConnected()
{
return client != null && client.isConnected;
}
public bool IsClientConnected() => client != null && client.isConnected;
public static void Shutdown()
{
if (!(singleton == null))
{
s_StartPositions.Clear();
s_StartPositionIndex = 0;
s_ClientReadyConnection = null;
singleton.StopHost();
singleton = null;
@ -598,10 +508,7 @@ namespace QuantumUNET.Components
internal void OnServerConnectInternal(QSBNetworkMessage netMsg)
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager:OnServerConnectInternal");
}
Debug.Log("NetworkManager:OnServerConnectInternal");
netMsg.Connection.SetMaxDelay(maxDelay);
if (m_MaxBufferedPackets != 512)
{
@ -627,28 +534,19 @@ namespace QuantumUNET.Components
internal void OnServerDisconnectInternal(QSBNetworkMessage netMsg)
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager:OnServerDisconnectInternal");
}
Debug.Log("NetworkManager:OnServerDisconnectInternal");
OnServerDisconnect(netMsg.Connection);
}
internal void OnServerReadyMessageInternal(QSBNetworkMessage netMsg)
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager:OnServerReadyMessageInternal");
}
Debug.Log("NetworkManager:OnServerReadyMessageInternal");
OnServerReady(netMsg.Connection);
}
internal void OnServerAddPlayerMessageInternal(QSBNetworkMessage netMsg)
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager:OnServerAddPlayerMessageInternal");
}
Debug.Log("NetworkManager:OnServerAddPlayerMessageInternal");
netMsg.ReadMessage<QSBAddPlayerMessage>(s_AddPlayerMessage);
if (s_AddPlayerMessage.msgSize != 0)
{
@ -663,10 +561,7 @@ namespace QuantumUNET.Components
internal void OnServerRemovePlayerMessageInternal(QSBNetworkMessage netMsg)
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager:OnServerRemovePlayerMessageInternal");
}
Debug.Log("NetworkManager:OnServerRemovePlayerMessageInternal");
netMsg.ReadMessage<QSBRemovePlayerMessage>(s_RemovePlayerMessage);
netMsg.Connection.GetPlayerController(s_RemovePlayerMessage.PlayerControllerId, out var player);
OnServerRemovePlayer(netMsg.Connection, player);
@ -675,20 +570,14 @@ namespace QuantumUNET.Components
internal void OnServerErrorInternal(QSBNetworkMessage netMsg)
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager:OnServerErrorInternal");
}
Debug.Log("NetworkManager:OnServerErrorInternal");
netMsg.ReadMessage<QSBErrorMessage>(s_ErrorMessage);
OnServerError(netMsg.Connection, s_ErrorMessage.errorCode);
}
internal void OnClientConnectInternal(QSBNetworkMessage netMsg)
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager:OnClientConnectInternal");
}
Debug.Log("NetworkManager:OnClientConnectInternal");
netMsg.Connection.SetMaxDelay(maxDelay);
var name = SceneManager.GetSceneAt(0).name;
if (string.IsNullOrEmpty(onlineScene) || onlineScene == offlineScene || name == onlineScene)
@ -704,10 +593,7 @@ namespace QuantumUNET.Components
internal void OnClientDisconnectInternal(QSBNetworkMessage netMsg)
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager:OnClientDisconnectInternal");
}
Debug.Log("NetworkManager:OnClientDisconnectInternal");
if (!string.IsNullOrEmpty(offlineScene))
{
ClientChangeScene(offlineScene, false);
@ -717,30 +603,21 @@ namespace QuantumUNET.Components
internal void OnClientNotReadyMessageInternal(QSBNetworkMessage netMsg)
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager:OnClientNotReadyMessageInternal");
}
Debug.Log("NetworkManager:OnClientNotReadyMessageInternal");
QSBClientScene.SetNotReady();
OnClientNotReady(netMsg.Connection);
}
internal void OnClientErrorInternal(QSBNetworkMessage netMsg)
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager:OnClientErrorInternal");
}
Debug.Log("NetworkManager:OnClientErrorInternal");
netMsg.ReadMessage<QSBErrorMessage>(s_ErrorMessage);
OnClientError(netMsg.Connection, s_ErrorMessage.errorCode);
}
internal void OnClientSceneInternal(QSBNetworkMessage netMsg)
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkManager:OnClientSceneInternal");
}
Debug.Log("NetworkManager:OnClientSceneInternal");
var newSceneName = netMsg.Reader.ReadString();
if (IsClientConnected() && !QSBNetworkServer.active)
{
@ -757,10 +634,7 @@ namespace QuantumUNET.Components
QSBNetworkServer.DestroyPlayersForConnection(conn);
if (conn.LastError != NetworkError.Ok)
{
if (LogFilter.logError)
{
Debug.LogError("ServerDisconnected due to error: " + conn.LastError);
}
Debug.LogError("ServerDisconnected due to error: " + conn.LastError);
}
}
@ -768,98 +642,36 @@ namespace QuantumUNET.Components
{
if (conn.PlayerControllers.Count == 0)
{
if (LogFilter.logDebug)
{
Debug.Log("Ready with no player object");
}
Debug.Log("Ready with no player object");
}
QSBNetworkServer.SetClientReady(conn);
}
public virtual void OnServerAddPlayer(QSBNetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader)
{
OnServerAddPlayerInternal(conn, playerControllerId);
}
public virtual void OnServerAddPlayer(QSBNetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader) => OnServerAddPlayerInternal(conn, playerControllerId);
public virtual void OnServerAddPlayer(QSBNetworkConnection conn, short playerControllerId)
{
OnServerAddPlayerInternal(conn, playerControllerId);
}
public virtual void OnServerAddPlayer(QSBNetworkConnection conn, short playerControllerId) => OnServerAddPlayerInternal(conn, playerControllerId);
private void OnServerAddPlayerInternal(QSBNetworkConnection conn, short playerControllerId)
{
if (playerPrefab == null)
{
if (LogFilter.logError)
{
ModConsole.OwmlConsole.WriteLine("Error - The PlayerPrefab is empty on the QSBNetworkManager. Please setup a PlayerPrefab object.");
}
ModConsole.OwmlConsole.WriteLine("Error - The PlayerPrefab is empty on the QSBNetworkManager. Please setup a PlayerPrefab object.");
}
else if (playerPrefab.GetComponent<QSBNetworkIdentity>() == null)
{
if (LogFilter.logError)
{
ModConsole.OwmlConsole.WriteLine("Error - The PlayerPrefab does not have a QSBNetworkIdentity. Please add a QSBNetworkIdentity to the player prefab.");
}
ModConsole.OwmlConsole.WriteLine("Error - The PlayerPrefab does not have a QSBNetworkIdentity. Please add a QSBNetworkIdentity to the player prefab.");
}
else if (playerControllerId < conn.PlayerControllers.Count && conn.PlayerControllers[playerControllerId].IsValid && conn.PlayerControllers[playerControllerId].Gameobject != null)
{
if (LogFilter.logError)
{
ModConsole.OwmlConsole.WriteLine("Warning - There is already a player at that playerControllerId for this connections.");
}
ModConsole.OwmlConsole.WriteLine("Warning - There is already a player at that playerControllerId for this connections.");
}
else
{
var startPosition = GetStartPosition();
GameObject player;
if (startPosition != null)
{
player = Instantiate<GameObject>(playerPrefab, startPosition.position, startPosition.rotation);
}
else
{
player = Instantiate<GameObject>(playerPrefab, Vector3.zero, Quaternion.identity);
}
var player = Instantiate<GameObject>(playerPrefab, Vector3.zero, Quaternion.identity);
QSBNetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
}
}
public Transform GetStartPosition()
{
if (s_StartPositions.Count > 0)
{
for (var i = s_StartPositions.Count - 1; i >= 0; i--)
{
if (s_StartPositions[i] == null)
{
s_StartPositions.RemoveAt(i);
}
}
}
Transform result;
if (playerSpawnMethod == PlayerSpawnMethod.Random && s_StartPositions.Count > 0)
{
var index = UnityEngine.Random.Range(0, s_StartPositions.Count);
result = s_StartPositions[index];
}
else if (playerSpawnMethod == PlayerSpawnMethod.RoundRobin && s_StartPositions.Count > 0)
{
if (s_StartPositionIndex >= s_StartPositions.Count)
{
s_StartPositionIndex = 0;
}
var transform = s_StartPositions[s_StartPositionIndex];
s_StartPositionIndex++;
result = transform;
}
else
{
result = null;
}
return result;
}
public virtual void OnServerRemovePlayer(QSBNetworkConnection conn, QSBPlayerController player)
{
if (player.Gameobject != null)
@ -893,10 +705,7 @@ namespace QuantumUNET.Components
StopClient();
if (conn.LastError != NetworkError.Ok)
{
if (LogFilter.logError)
{
Debug.LogError("ClientDisconnected due to error: " + conn.LastError);
}
Debug.LogError("ClientDisconnected due to error: " + conn.LastError);
}
}

View File

@ -1,5 +1,6 @@
using OWML.Logging;
using QuantumUNET.Messages;
using QuantumUNET.Transport;
using UnityEngine;
using UnityEngine.Networking;
@ -8,86 +9,22 @@ namespace QuantumUNET.Components
public class QSBNetworkTransform : QSBNetworkBehaviour
{
public float SendInterval { get; set; } = 0.1f;
public AxisSyncMode SyncRotationAxis { get; set; } = AxisSyncMode.AxisXYZ;
public CompressionSyncMode RotationSyncCompression { get; set; } = CompressionSyncMode.None;
public bool SyncSpin { get; set; }
public float MovementTheshold { get; set; } = 0.001f;
public float velocityThreshold { get; set; } = 0.0001f;
public float SnapThreshold { get; set; } = 5f;
public float InterpolateRotation { get; set; } = 1f;
public float InterpolateMovement { get; set; } = 1f;
public ClientMoveCallback3D clientMoveCallback3D { get; set; }
public float LastSyncTime { get; private set; }
public Vector3 TargetSyncPosition
{
get
{
return m_TargetSyncPosition;
}
}
public Vector3 targetSyncVelocity
{
get
{
return m_TargetSyncVelocity;
}
}
public Quaternion targetSyncRotation3D
{
get
{
return m_TargetSyncRotation3D;
}
}
public Vector3 TargetSyncPosition => m_TargetSyncPosition;
public Vector3 targetSyncVelocity => m_TargetSyncVelocity;
public Quaternion targetSyncRotation3D => m_TargetSyncRotation3D;
public bool Grounded { get; set; } = true;
private void OnValidate()
{
if (SendInterval < 0f)
{
SendInterval = 0f;
}
if (SyncRotationAxis < AxisSyncMode.None || SyncRotationAxis > AxisSyncMode.AxisXYZ)
{
SyncRotationAxis = AxisSyncMode.None;
}
if (MovementTheshold < 0f)
{
MovementTheshold = 0f;
}
if (velocityThreshold < 0f)
{
velocityThreshold = 0f;
}
if (SnapThreshold < 0f)
{
SnapThreshold = 0.01f;
}
if (InterpolateRotation < 0f)
{
InterpolateRotation = 0.01f;
}
if (InterpolateMovement < 0f)
{
InterpolateMovement = 0.01f;
}
}
private void Awake()
public void Awake()
{
m_PrevPosition = transform.position;
m_PrevRotation = transform.rotation;
@ -97,10 +34,7 @@ namespace QuantumUNET.Components
}
}
public override void OnStartServer()
{
LastSyncTime = 0f;
}
public override void OnStartServer() => LastSyncTime = 0f;
public override bool OnSerialize(QSBNetworkWriter writer, bool initialState)
{
@ -294,10 +228,7 @@ namespace QuantumUNET.Components
component.UnserializeModeTransform(netMsg.Reader, false);
component.LastSyncTime = Time.time;
}
else if (LogFilter.logWarn)
{
ModConsole.OwmlConsole.WriteLine("Warning - HandleTransform netId:" + networkInstanceId + " is not for a valid player");
}
ModConsole.OwmlConsole.WriteLine("Warning - HandleTransform netId:" + networkInstanceId + " is not for a valid player");
}
}
@ -336,12 +267,12 @@ namespace QuantumUNET.Components
}
else
{
result = (float)reader.ReadInt16();
result = reader.ReadInt16();
}
}
else
{
result = (float)reader.ReadInt16();
result = reader.ReadInt16();
}
}
else
@ -351,10 +282,8 @@ namespace QuantumUNET.Components
return result;
}
public static void SerializeVelocity3D(QSBNetworkWriter writer, Vector3 velocity, CompressionSyncMode compression)
{
public static void SerializeVelocity3D(QSBNetworkWriter writer, Vector3 velocity, CompressionSyncMode compression) =>
writer.Write(velocity);
}
public static void SerializeRotation3D(QSBNetworkWriter writer, Quaternion rot, AxisSyncMode mode, CompressionSyncMode compression)
{
@ -434,10 +363,7 @@ namespace QuantumUNET.Components
}
}
public static Vector3 UnserializeVelocity3D(QSBNetworkReader reader, CompressionSyncMode compression)
{
return reader.ReadVector3();
}
public static Vector3 UnserializeVelocity3D(QSBNetworkReader reader, CompressionSyncMode compression) => reader.ReadVector3();
public static Quaternion UnserializeRotation3D(QSBNetworkReader reader, AxisSyncMode mode, CompressionSyncMode compression)
{
@ -519,20 +445,11 @@ namespace QuantumUNET.Components
return zero;
}
public override int GetNetworkChannel()
{
return 1;
}
public override int GetNetworkChannel() => 1;
public override float GetNetworkSendInterval()
{
return SendInterval;
}
public override float GetNetworkSendInterval() => SendInterval;
public override void OnStartAuthority()
{
LastSyncTime = 0f;
}
public override void OnStartAuthority() => LastSyncTime = 0f;
private Vector3 m_TargetSyncPosition;

View File

@ -1,4 +1,6 @@
namespace QuantumUNET.Messages
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
internal class QSBAddPlayerMessage : QSBMessageBase
{
@ -6,6 +8,12 @@
public int msgSize;
public byte[] msgData;
public override void Serialize(QSBNetworkWriter writer)
{
writer.Write(playerControllerId);
writer.WriteBytesAndSize(msgData, msgSize);
}
public override void Deserialize(QSBNetworkReader reader)
{
playerControllerId = reader.ReadInt16();
@ -19,11 +27,5 @@
msgSize = msgData.Length;
}
}
public override void Serialize(QSBNetworkWriter writer)
{
writer.Write(playerControllerId);
writer.WriteBytesAndSize(msgData, msgSize);
}
}
}

View File

@ -1,22 +1,14 @@
using UnityEngine.Networking;
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
internal class QSBAnimationMessage : QSBMessageBase
{
public NetworkInstanceId netId;
public QSBNetworkInstanceId netId;
public int stateHash;
public float normalizedTime;
public byte[] parameters;
public override void Deserialize(QSBNetworkReader reader)
{
netId = reader.ReadNetworkId();
stateHash = (int)reader.ReadPackedUInt32();
normalizedTime = reader.ReadSingle();
parameters = reader.ReadBytesAndSize();
}
public override void Serialize(QSBNetworkWriter writer)
{
writer.Write(netId);
@ -31,5 +23,13 @@ namespace QuantumUNET.Messages
writer.WriteBytesAndSize(parameters, parameters.Length);
}
}
public override void Deserialize(QSBNetworkReader reader)
{
netId = reader.ReadNetworkId();
stateHash = (int)reader.ReadPackedUInt32();
normalizedTime = reader.ReadSingle();
parameters = reader.ReadBytesAndSize();
}
}
}

View File

@ -1,10 +1,10 @@
using UnityEngine.Networking;
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
internal class QSBAnimationParametersMessage : QSBMessageBase
{
public NetworkInstanceId netId;
public QSBNetworkInstanceId netId;
public byte[] parameters;
public override void Deserialize(QSBNetworkReader reader)

View File

@ -1,10 +1,10 @@
using UnityEngine.Networking;
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
internal class QSBAnimationTriggerMessage : QSBMessageBase
{
public NetworkInstanceId netId;
public QSBNetworkInstanceId netId;
public int hash;
public override void Deserialize(QSBNetworkReader reader)

View File

@ -1,4 +1,6 @@
namespace QuantumUNET.Messages
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
internal class QSBCRCMessage : QSBMessageBase
{

View File

@ -1,10 +1,10 @@
using UnityEngine.Networking;
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
internal class QSBClientAuthorityMessage : QSBMessageBase
{
public NetworkInstanceId netId;
public QSBNetworkInstanceId netId;
public bool authority;
public override void Deserialize(QSBNetworkReader reader)

View File

@ -1,13 +1,10 @@
namespace QuantumUNET.Messages
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
public class QSBEmptyMessage : QSBMessageBase
{
public override void Deserialize(QSBNetworkReader reader)
{
}
public override void Serialize(QSBNetworkWriter writer)
{
}
public override void Serialize(QSBNetworkWriter writer) { }
public override void Deserialize(QSBNetworkReader reader) { }
}
}

View File

@ -1,17 +1,13 @@
namespace QuantumUNET.Messages
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
public class QSBErrorMessage : QSBMessageBase
{
public override void Deserialize(QSBNetworkReader reader)
{
this.errorCode = (int)reader.ReadUInt16();
}
public override void Serialize(QSBNetworkWriter writer)
{
writer.Write((ushort)this.errorCode);
}
public int errorCode;
public override void Serialize(QSBNetworkWriter writer) => writer.Write((ushort)errorCode);
public override void Deserialize(QSBNetworkReader reader) => errorCode = reader.ReadUInt16();
}
}

View File

@ -1,13 +1,11 @@
namespace QuantumUNET.Messages
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
public abstract class QSBMessageBase
{
public virtual void Deserialize(QSBNetworkReader reader)
{
}
public virtual void Serialize(QSBNetworkWriter writer) { }
public virtual void Serialize(QSBNetworkWriter writer)
{
}
public virtual void Deserialize(QSBNetworkReader reader) { }
}
}

View File

@ -11,7 +11,7 @@
}
else
{
string text = msgLabels[(int)value];
var text = msgLabels[value];
if (string.IsNullOrEmpty(text))
{
text = "[" + value + "]";

View File

@ -1,10 +1,10 @@
using System;
using QuantumUNET.Transport;
using System;
namespace QuantumUNET.Messages
{
public class QSBNetworkMessage
{
public const int MaxMessageSize = 65535;
public short MsgType;
public QSBNetworkConnection Connection;
public QSBNetworkReader Reader;
@ -17,9 +17,7 @@ namespace QuantumUNET.Messages
return result;
}
public void ReadMessage<TMsg>(TMsg msg) where TMsg : QSBMessageBase
{
public void ReadMessage<TMsg>(TMsg msg) where TMsg : QSBMessageBase =>
msg.Deserialize(Reader);
}
}
}

View File

@ -1,19 +1,13 @@
using UnityEngine.Networking;
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
internal class QSBObjectDestroyMessage : QSBMessageBase
{
public NetworkInstanceId NetId;
public QSBNetworkInstanceId NetId;
public override void Deserialize(QSBNetworkReader reader)
{
NetId = reader.ReadNetworkId();
}
public override void Serialize(QSBNetworkWriter writer) => writer.Write(NetId);
public override void Serialize(QSBNetworkWriter writer)
{
writer.Write(NetId);
}
public override void Deserialize(QSBNetworkReader reader) => NetId = reader.ReadNetworkId();
}
}

View File

@ -1,17 +1,13 @@
namespace QuantumUNET.Messages
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
internal class QSBObjectSpawnFinishedMessage : QSBMessageBase
{
public uint State;
public override void Deserialize(QSBNetworkReader reader)
{
State = reader.ReadPackedUInt32();
}
public override void Serialize(QSBNetworkWriter writer) => writer.WritePackedUInt32(State);
public override void Serialize(QSBNetworkWriter writer)
{
writer.WritePackedUInt32(State);
}
public override void Deserialize(QSBNetworkReader reader) => State = reader.ReadPackedUInt32();
}
}

View File

@ -1,16 +1,25 @@
using UnityEngine;
using UnityEngine.Networking;
using QuantumUNET.Transport;
using UnityEngine;
namespace QuantumUNET.Messages
{
internal class QSBObjectSpawnMessage : QSBMessageBase
{
public NetworkInstanceId NetId;
public NetworkHash128 assetId;
public QSBNetworkInstanceId NetId;
public QSBNetworkHash128 assetId;
public Vector3 Position;
public byte[] Payload;
public Quaternion Rotation;
public override void Serialize(QSBNetworkWriter writer)
{
writer.Write(NetId);
writer.Write(assetId);
writer.Write(Position);
writer.WriteBytesFull(Payload);
writer.Write(Rotation);
}
public override void Deserialize(QSBNetworkReader reader)
{
NetId = reader.ReadNetworkId();
@ -22,14 +31,5 @@ namespace QuantumUNET.Messages
Rotation = reader.ReadQuaternion();
}
}
public override void Serialize(QSBNetworkWriter writer)
{
writer.Write(NetId);
writer.Write(assetId);
writer.Write(Position);
writer.WriteBytesFull(Payload);
writer.Write(Rotation);
}
}
}

View File

@ -1,23 +1,15 @@
using UnityEngine;
using UnityEngine.Networking;
using QuantumUNET.Transport;
using UnityEngine;
namespace QuantumUNET.Messages
{
internal class QSBObjectSpawnSceneMessage : QSBMessageBase
{
public NetworkInstanceId NetId;
public NetworkSceneId SceneId;
public QSBNetworkInstanceId NetId;
public QSBNetworkSceneId SceneId;
public Vector3 Position;
public byte[] Payload;
public override void Deserialize(QSBNetworkReader reader)
{
NetId = reader.ReadNetworkId();
SceneId = reader.ReadSceneId();
Position = reader.ReadVector3();
Payload = reader.ReadBytesAndSize();
}
public override void Serialize(QSBNetworkWriter writer)
{
writer.Write(NetId);
@ -25,5 +17,13 @@ namespace QuantumUNET.Messages
writer.Write(Position);
writer.WriteBytesFull(Payload);
}
public override void Deserialize(QSBNetworkReader reader)
{
NetId = reader.ReadNetworkId();
SceneId = reader.ReadSceneId();
Position = reader.ReadVector3();
Payload = reader.ReadBytesAndSize();
}
}
}

View File

@ -1,22 +1,22 @@
using UnityEngine.Networking;
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
internal class QSBOwnerMessage : QSBMessageBase
{
public NetworkInstanceId NetId;
public QSBNetworkInstanceId NetId;
public short PlayerControllerId;
public override void Deserialize(QSBNetworkReader reader)
{
NetId = reader.ReadNetworkId();
PlayerControllerId = (short)reader.ReadPackedUInt32();
}
public override void Serialize(QSBNetworkWriter writer)
{
writer.Write(NetId);
writer.WritePackedUInt32((uint)PlayerControllerId);
}
public override void Deserialize(QSBNetworkReader reader)
{
NetId = reader.ReadNetworkId();
PlayerControllerId = (short)reader.ReadPackedUInt32();
}
}
}

View File

@ -1,80 +0,0 @@
using System.Collections.Generic;
namespace QuantumUNET.Messages
{
public class QSBPeerInfoMessage : QSBMessageBase
{
public override void Deserialize(QSBNetworkReader reader)
{
this.connectionId = (int)reader.ReadPackedUInt32();
this.address = reader.ReadString();
this.port = (int)reader.ReadPackedUInt32();
this.isHost = reader.ReadBoolean();
this.isYou = reader.ReadBoolean();
uint num = reader.ReadPackedUInt32();
if (num > 0U)
{
List<QSBPeerInfoPlayer> list = new List<QSBPeerInfoPlayer>();
for (uint num2 = 0U; num2 < num; num2 += 1U)
{
QSBPeerInfoPlayer item;
item.netId = reader.ReadNetworkId();
item.playerControllerId = (short)reader.ReadPackedUInt32();
list.Add(item);
}
this.playerIds = list.ToArray();
}
}
public override void Serialize(QSBNetworkWriter writer)
{
writer.WritePackedUInt32((uint)this.connectionId);
writer.Write(this.address);
writer.WritePackedUInt32((uint)this.port);
writer.Write(this.isHost);
writer.Write(this.isYou);
if (this.playerIds == null)
{
writer.WritePackedUInt32(0U);
}
else
{
writer.WritePackedUInt32((uint)this.playerIds.Length);
for (int i = 0; i < this.playerIds.Length; i++)
{
writer.Write(this.playerIds[i].netId);
writer.WritePackedUInt32((uint)this.playerIds[i].playerControllerId);
}
}
}
public override string ToString()
{
return string.Concat(new object[]
{
"PeerInfo conn:",
this.connectionId,
" addr:",
this.address,
":",
this.port,
" host:",
this.isHost,
" isYou:",
this.isYou
});
}
public int connectionId;
public string address;
public int port;
public bool isHost;
public bool isYou;
public QSBPeerInfoPlayer[] playerIds;
}
}

View File

@ -1,30 +0,0 @@
using UnityEngine.Networking;
namespace QuantumUNET.Messages
{
public class QSBReconnectMessage : QSBMessageBase
{
public int oldConnectionId;
public short playerControllerId;
public NetworkInstanceId netId;
public int msgSize;
public byte[] msgData;
public override void Deserialize(QSBNetworkReader reader)
{
oldConnectionId = (int)reader.ReadPackedUInt32();
playerControllerId = (short)reader.ReadPackedUInt32();
netId = reader.ReadNetworkId();
msgData = reader.ReadBytesAndSize();
msgSize = msgData.Length;
}
public override void Serialize(QSBNetworkWriter writer)
{
writer.WritePackedUInt32((uint)oldConnectionId);
writer.WritePackedUInt32((uint)playerControllerId);
writer.Write(netId);
writer.WriteBytesAndSize(msgData, msgSize);
}
}
}

View File

@ -1,17 +1,13 @@
namespace QuantumUNET.Messages
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
public class QSBRemovePlayerMessage : QSBMessageBase
{
public short PlayerControllerId;
public override void Deserialize(QSBNetworkReader reader)
{
PlayerControllerId = (short)reader.ReadUInt16();
}
public override void Serialize(QSBNetworkWriter writer) => writer.Write((ushort)PlayerControllerId);
public override void Serialize(QSBNetworkWriter writer)
{
writer.Write((ushort)PlayerControllerId);
}
public override void Deserialize(QSBNetworkReader reader) => PlayerControllerId = (short)reader.ReadUInt16();
}
}

View File

@ -0,0 +1,6 @@
using UnityEngine;
namespace QuantumUNET
{
public delegate GameObject QSBSpawnDelegate(Vector3 position, QSBNetworkHash128 assetId);
}

View File

@ -1,26 +1,18 @@
namespace QuantumUNET.Messages
using QuantumUNET.Transport;
namespace QuantumUNET.Messages
{
public class QSBStringMessage : QSBMessageBase
{
public QSBStringMessage()
{
}
public string value;
public QSBStringMessage(string v)
{
this.value = v;
value = v;
}
public override void Deserialize(QSBNetworkReader reader)
{
this.value = reader.ReadString();
}
public override void Serialize(QSBNetworkWriter writer) => writer.Write(value);
public override void Serialize(QSBNetworkWriter writer)
{
writer.Write(this.value);
}
public string value;
public override void Deserialize(QSBNetworkReader reader) => value = reader.ReadString();
}
}

View File

@ -1,82 +0,0 @@
using System;
using UnityEngine;
using UnityEngine.Networking;
namespace QuantumUNET
{
internal struct QSBChannelPacket
{
public QSBChannelPacket(int packetSize, bool isReliable)
{
this.m_Position = 0;
this.m_Buffer = new byte[packetSize];
this.m_IsReliable = isReliable;
}
public void Reset()
{
this.m_Position = 0;
}
public bool IsEmpty()
{
return this.m_Position == 0;
}
public void Write(byte[] bytes, int numBytes)
{
Array.Copy(bytes, 0, this.m_Buffer, this.m_Position, numBytes);
this.m_Position += numBytes;
}
public bool HasSpace(int numBytes)
{
return this.m_Position + numBytes <= this.m_Buffer.Length;
}
public bool SendToTransport(QSBNetworkConnection conn, int channelId)
{
bool result = true;
byte b;
if (!conn.TransportSend(this.m_Buffer, (int)((ushort)this.m_Position), channelId, out b))
{
if (!this.m_IsReliable || b != 4)
{
Debug.LogError(string.Concat(new object[]
{
"Failed to send internal buffer channel:",
channelId,
" bytesToSend:",
this.m_Position
}));
result = false;
}
}
if (b != 0)
{
if (this.m_IsReliable && b == 4)
{
return false;
}
Debug.LogError(string.Concat(new object[]
{
"Send Error: ",
(NetworkError)b,
" channel:",
channelId,
" bytesToSend:",
this.m_Position
}));
result = false;
}
this.m_Position = 0;
return result;
}
private int m_Position;
private byte[] m_Buffer;
private bool m_IsReliable;
}
}

View File

@ -1,5 +1,6 @@
using QuantumUNET.Components;
using QuantumUNET.Messages;
using QuantumUNET.Transport;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
@ -8,18 +9,6 @@ namespace QuantumUNET
{
public class QSBClientScene
{
private static bool HasMigrationPending() => reconnectId != -1;
public static void SetReconnectId(int newReconnectId, QSBPeerInfoMessage[] peers)
{
reconnectId = newReconnectId;
s_Peers = peers;
if (LogFilter.logDebug)
{
Debug.Log("ClientScene::SetReconnectId: " + newReconnectId);
}
}
internal static void SetNotReady() => ready = false;
public static List<QSBPlayerController> localPlayers { get; private set; } = new List<QSBPlayerController>();
@ -30,11 +19,11 @@ namespace QuantumUNET
public static int reconnectId { get; private set; } = -1;
public static Dictionary<NetworkInstanceId, QSBNetworkIdentity> Objects => s_NetworkScene.localObjects;
public static Dictionary<QSBNetworkInstanceId, QSBNetworkIdentity> Objects => s_NetworkScene.localObjects;
public static Dictionary<NetworkHash128, GameObject> Prefabs => QSBNetworkScene.guidToPrefab;
public static Dictionary<QSBNetworkHash128, GameObject> Prefabs => QSBNetworkScene.guidToPrefab;
public static Dictionary<NetworkSceneId, QSBNetworkIdentity> SpawnableObjects { get; private set; }
public static Dictionary<QSBNetworkSceneId, QSBNetworkIdentity> SpawnableObjects { get; private set; }
internal static void Shutdown()
{
@ -54,7 +43,7 @@ namespace QuantumUNET
{
player = null;
bool result;
if ((int)playerControllerId >= localPlayers.Count)
if (playerControllerId >= localPlayers.Count)
{
if (LogFilter.logWarn)
{
@ -62,7 +51,7 @@ namespace QuantumUNET
}
result = false;
}
else if (localPlayers[(int)playerControllerId] == null)
else if (localPlayers[playerControllerId] == null)
{
if (LogFilter.logWarn)
{
@ -72,7 +61,7 @@ namespace QuantumUNET
}
else
{
player = localPlayers[(int)playerControllerId];
player = localPlayers[playerControllerId];
result = (player.Gameobject != null);
}
return result;
@ -84,13 +73,13 @@ namespace QuantumUNET
{
Debug.LogWarning("ClientScene::InternalAddPlayer: playerControllerId : " + playerControllerId);
}
if ((int)playerControllerId >= localPlayers.Count)
if (playerControllerId >= localPlayers.Count)
{
if (LogFilter.logWarn)
{
Debug.LogWarning("ClientScene::InternalAddPlayer: playerControllerId higher than expected: " + playerControllerId);
}
while ((int)playerControllerId >= localPlayers.Count)
while (playerControllerId >= localPlayers.Count)
{
localPlayers.Add(new QSBPlayerController());
}
@ -101,7 +90,7 @@ namespace QuantumUNET
PlayerControllerId = playerControllerId,
UnetView = view
};
localPlayers[(int)playerControllerId] = playerController;
localPlayers[playerControllerId] = playerController;
readyConnection.SetPlayerController(playerController);
}
@ -114,24 +103,18 @@ namespace QuantumUNET
bool result;
if (playerControllerId < 0)
{
if (LogFilter.logError)
{
Debug.LogError("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is negative");
}
Debug.LogError("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is negative");
result = false;
}
else if (playerControllerId > 32)
{
if (LogFilter.logError)
Debug.LogError(string.Concat(new object[]
{
Debug.LogError(string.Concat(new object[]
{
"ClientScene::AddPlayer: playerControllerId of ",
playerControllerId,
" is too high, max is ",
32
}));
}
}));
result = false;
}
else
@ -143,7 +126,7 @@ namespace QuantumUNET
Debug.LogWarning("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is unusually high");
}
}
while ((int)playerControllerId >= localPlayers.Count)
while (playerControllerId >= localPlayers.Count)
{
localPlayers.Add(new QSBPlayerController());
}
@ -194,7 +177,7 @@ namespace QuantumUNET
var networkWriter = new QSBNetworkWriter();
extraMessage.Serialize(networkWriter);
addPlayerMessage.msgData = networkWriter.ToArray();
addPlayerMessage.msgSize = (int)networkWriter.Position;
addPlayerMessage.msgSize = networkWriter.Position;
}
readyConnection.Send(37, addPlayerMessage);
result = true;
@ -224,8 +207,8 @@ namespace QuantumUNET
};
readyConnection.Send(38, removePlayerMessage);
readyConnection.RemovePlayerController(playerControllerId);
localPlayers[(int)playerControllerId] = new QSBPlayerController();
UnityEngine.Object.Destroy(playerController.Gameobject);
localPlayers[playerControllerId] = new QSBPlayerController();
Object.Destroy(playerController.Gameobject);
result = true;
}
else
@ -306,7 +289,7 @@ namespace QuantumUNET
internal static void PrepareToSpawnSceneObjects()
{
SpawnableObjects = new Dictionary<NetworkSceneId, QSBNetworkIdentity>();
SpawnableObjects = new Dictionary<QSBNetworkSceneId, QSBNetworkIdentity>();
foreach (var networkIdentity in Resources.FindObjectsOfTypeAll<QSBNetworkIdentity>())
{
if (!networkIdentity.gameObject.activeSelf)
@ -326,7 +309,7 @@ namespace QuantumUNET
}
}
internal static QSBNetworkIdentity SpawnSceneObject(NetworkSceneId sceneId)
internal static QSBNetworkIdentity SpawnSceneObject(QSBNetworkSceneId sceneId)
{
QSBNetworkIdentity result;
if (SpawnableObjects.ContainsKey(sceneId))
@ -346,32 +329,32 @@ namespace QuantumUNET
{
if (localClient)
{
client.RegisterHandlerSafe((short)1, new QSBNetworkMessageDelegate(OnLocalClientObjectDestroy));
client.RegisterHandlerSafe((short)13, new QSBNetworkMessageDelegate(OnLocalClientObjectHide));
client.RegisterHandlerSafe((short)3, new QSBNetworkMessageDelegate(OnLocalClientObjectSpawn));
client.RegisterHandlerSafe((short)10, new QSBNetworkMessageDelegate(OnLocalClientObjectSpawnScene));
client.RegisterHandlerSafe((short)15, new QSBNetworkMessageDelegate(OnClientAuthority));
client.RegisterHandlerSafe(1, new QSBNetworkMessageDelegate(OnLocalClientObjectDestroy));
client.RegisterHandlerSafe(13, new QSBNetworkMessageDelegate(OnLocalClientObjectHide));
client.RegisterHandlerSafe(3, new QSBNetworkMessageDelegate(OnLocalClientObjectSpawn));
client.RegisterHandlerSafe(10, new QSBNetworkMessageDelegate(OnLocalClientObjectSpawnScene));
client.RegisterHandlerSafe(15, new QSBNetworkMessageDelegate(OnClientAuthority));
}
else
{
client.RegisterHandlerSafe((short)3, new QSBNetworkMessageDelegate(OnObjectSpawn));
client.RegisterHandlerSafe((short)10, new QSBNetworkMessageDelegate(OnObjectSpawnScene));
client.RegisterHandlerSafe((short)12, new QSBNetworkMessageDelegate(OnObjectSpawnFinished));
client.RegisterHandlerSafe((short)1, new QSBNetworkMessageDelegate(OnObjectDestroy));
client.RegisterHandlerSafe((short)13, new QSBNetworkMessageDelegate(OnObjectDestroy));
client.RegisterHandlerSafe((short)8, new QSBNetworkMessageDelegate(OnUpdateVarsMessage));
client.RegisterHandlerSafe((short)4, new QSBNetworkMessageDelegate(OnOwnerMessage));
client.RegisterHandlerSafe((short)9, new QSBNetworkMessageDelegate(OnSyncListMessage));
client.RegisterHandlerSafe((short)40, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationClientMessage));
client.RegisterHandlerSafe((short)41, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationParametersClientMessage));
client.RegisterHandlerSafe((short)15, new QSBNetworkMessageDelegate(OnClientAuthority));
client.RegisterHandlerSafe(3, new QSBNetworkMessageDelegate(OnObjectSpawn));
client.RegisterHandlerSafe(10, new QSBNetworkMessageDelegate(OnObjectSpawnScene));
client.RegisterHandlerSafe(12, new QSBNetworkMessageDelegate(OnObjectSpawnFinished));
client.RegisterHandlerSafe(1, new QSBNetworkMessageDelegate(OnObjectDestroy));
client.RegisterHandlerSafe(13, new QSBNetworkMessageDelegate(OnObjectDestroy));
client.RegisterHandlerSafe(8, new QSBNetworkMessageDelegate(OnUpdateVarsMessage));
client.RegisterHandlerSafe(4, new QSBNetworkMessageDelegate(OnOwnerMessage));
client.RegisterHandlerSafe(9, new QSBNetworkMessageDelegate(OnSyncListMessage));
client.RegisterHandlerSafe(40, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationClientMessage));
client.RegisterHandlerSafe(41, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationParametersClientMessage));
client.RegisterHandlerSafe(15, new QSBNetworkMessageDelegate(OnClientAuthority));
}
client.RegisterHandlerSafe((short)2, new QSBNetworkMessageDelegate(OnRPCMessage));
client.RegisterHandlerSafe((short)7, new QSBNetworkMessageDelegate(OnSyncEventMessage));
client.RegisterHandlerSafe((short)42, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationTriggerClientMessage));
client.RegisterHandlerSafe(2, new QSBNetworkMessageDelegate(OnRPCMessage));
client.RegisterHandlerSafe(7, new QSBNetworkMessageDelegate(OnSyncEventMessage));
client.RegisterHandlerSafe(42, new QSBNetworkMessageDelegate(QSBNetworkAnimator.OnAnimationTriggerClientMessage));
}
internal static string GetStringForAssetId(NetworkHash128 assetId)
internal static string GetStringForAssetId(QSBNetworkHash128 assetId)
{
string result;
if (QSBNetworkScene.GetPrefab(assetId, out var gameObject))
@ -389,27 +372,27 @@ namespace QuantumUNET
return result;
}
public static void RegisterPrefab(GameObject prefab, NetworkHash128 newAssetId) => QSBNetworkScene.RegisterPrefab(prefab, newAssetId);
public static void RegisterPrefab(GameObject prefab, QSBNetworkHash128 newAssetId) => QSBNetworkScene.RegisterPrefab(prefab, newAssetId);
public static void RegisterPrefab(GameObject prefab) => QSBNetworkScene.RegisterPrefab(prefab);
public static void RegisterPrefab(GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) => QSBNetworkScene.RegisterPrefab(prefab, spawnHandler, unspawnHandler);
public static void RegisterPrefab(GameObject prefab, QSBSpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) => QSBNetworkScene.RegisterPrefab(prefab, spawnHandler, unspawnHandler);
public static void UnregisterPrefab(GameObject prefab) => QSBNetworkScene.UnregisterPrefab(prefab);
public static void RegisterSpawnHandler(NetworkHash128 assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) => QSBNetworkScene.RegisterSpawnHandler(assetId, spawnHandler, unspawnHandler);
public static void RegisterSpawnHandler(QSBNetworkHash128 assetId, QSBSpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) => QSBNetworkScene.RegisterSpawnHandler(assetId, spawnHandler, unspawnHandler);
public static void UnregisterSpawnHandler(NetworkHash128 assetId) => QSBNetworkScene.UnregisterSpawnHandler(assetId);
public static void UnregisterSpawnHandler(QSBNetworkHash128 assetId) => QSBNetworkScene.UnregisterSpawnHandler(assetId);
public static void ClearSpawners() => QSBNetworkScene.ClearSpawners();
public static void DestroyAllClientObjects() => s_NetworkScene.DestroyAllClientObjects();
public static void SetLocalObject(NetworkInstanceId netId, GameObject obj) => s_NetworkScene.SetLocalObject(netId, obj, s_IsSpawnFinished, false);
public static void SetLocalObject(QSBNetworkInstanceId netId, GameObject obj) => s_NetworkScene.SetLocalObject(netId, obj, s_IsSpawnFinished, false);
public static GameObject FindLocalObject(NetworkInstanceId netId) => s_NetworkScene.FindLocalObject(netId);
public static GameObject FindLocalObject(QSBNetworkInstanceId netId) => s_NetworkScene.FindLocalObject(netId);
private static void ApplySpawnPayload(QSBNetworkIdentity uv, Vector3 position, byte[] payload, NetworkInstanceId netId, GameObject newGameObject)
private static void ApplySpawnPayload(QSBNetworkIdentity uv, Vector3 position, byte[] payload, QSBNetworkInstanceId netId, GameObject newGameObject)
{
if (!uv.gameObject.activeSelf)
{
@ -449,7 +432,7 @@ namespace QuantumUNET
}
else if (QSBNetworkScene.GetPrefab(s_ObjectSpawnMessage.assetId, out var original))
{
GameObject gameObject = UnityEngine.Object.Instantiate<GameObject>(original, s_ObjectSpawnMessage.Position, s_ObjectSpawnMessage.Rotation);
var gameObject = Object.Instantiate<GameObject>(original, s_ObjectSpawnMessage.Position, s_ObjectSpawnMessage.Rotation);
component = gameObject.GetComponent<QSBNetworkIdentity>();
if (component == null)
{
@ -572,7 +555,7 @@ namespace QuantumUNET
{
if (networkIdentity.SceneId.IsEmpty())
{
UnityEngine.Object.Destroy(networkIdentity.gameObject);
Object.Destroy(networkIdentity.gameObject);
}
else
{
@ -663,7 +646,7 @@ namespace QuantumUNET
}
else if (LogFilter.logWarn)
{
string cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(num);
var cmdHashHandlerName = QSBNetworkBehaviour.GetCmdHashHandlerName(num);
Debug.LogWarningFormat("Could not find target object with netId:{0} for RPC call {1}", new object[]
{
networkInstanceId,
@ -811,13 +794,11 @@ namespace QuantumUNET
public const int ReconnectIdHost = 0;
private static QSBPeerInfoMessage[] s_Peers;
private static List<PendingOwner> s_PendingOwnerIds = new List<PendingOwner>();
private struct PendingOwner
{
public NetworkInstanceId netId;
public QSBNetworkInstanceId netId;
public short playerControllerId;
}

View File

@ -1,4 +1,5 @@
using QuantumUNET.Messages;
using QuantumUNET.Transport;
using System.Collections.Generic;
using UnityEngine;
@ -14,7 +15,7 @@ namespace QuantumUNET
PostInternalMessage(33);
m_Connected = false;
}
m_AsyncConnect = QSBNetworkClient.ConnectState.Disconnected;
m_AsyncConnect = ConnectState.Disconnected;
m_LocalServer.RemoveLocalClient(m_Connection);
}
@ -31,11 +32,11 @@ namespace QuantumUNET
}
m_LocalServer = QSBNetworkServer.instance;
m_Connection = new QSBULocalConnectionToServer(m_LocalServer);
base.SetHandlers(m_Connection);
SetHandlers(m_Connection);
m_Connection.connectionId = m_LocalServer.AddLocalClient(this);
m_AsyncConnect = QSBNetworkClient.ConnectState.Connected;
QSBNetworkClient.SetActive(true);
base.RegisterSystemHandlers(true);
m_AsyncConnect = ConnectState.Connected;
SetActive(true);
RegisterSystemHandlers(true);
if (generateConnectMsg)
{
PostInternalMessage(32);
@ -108,11 +109,11 @@ namespace QuantumUNET
}
s_InternalMessage.Reader.ReadInt16();
s_InternalMessage.ChannelId = t.channelId;
s_InternalMessage.Connection = base.connection;
s_InternalMessage.Connection = connection;
s_InternalMessage.MsgType = s_InternalMessage.Reader.ReadInt16();
m_Connection.InvokeHandler(s_InternalMessage);
m_FreeMessages.Push(t);
base.connection.lastMessageTime = Time.time;
connection.lastMessageTime = Time.time;
}
m_InternalMsgs = internalMsgs;
m_InternalMsgs.Clear();

View File

@ -1,198 +0,0 @@
using System;
using UnityEngine;
namespace QuantumUNET
{
internal class QSBNetBuffer
{
public QSBNetBuffer()
{
m_Buffer = new byte[64];
}
public QSBNetBuffer(byte[] buffer)
{
m_Buffer = buffer;
}
public uint Position
{
get
{
return m_Pos;
}
}
public int Length
{
get
{
return m_Buffer.Length;
}
}
public byte ReadByte()
{
if ((ulong)m_Pos >= (ulong)((long)m_Buffer.Length))
{
throw new IndexOutOfRangeException("NetworkReader:ReadByte out of range:" + ToString());
}
return m_Buffer[(int)((UIntPtr)(m_Pos++))];
}
public void ReadBytes(byte[] buffer, uint count)
{
if ((ulong)(m_Pos + count) > (ulong)((long)m_Buffer.Length))
{
throw new IndexOutOfRangeException(string.Concat(new object[]
{
"NetworkReader:ReadBytes out of range: (",
count,
") ",
ToString()
}));
}
ushort num = 0;
while ((uint)num < count)
{
buffer[(int)num] = m_Buffer[(int)((UIntPtr)(m_Pos + (uint)num))];
num += 1;
}
m_Pos += count;
}
internal ArraySegment<byte> AsArraySegment()
{
return new ArraySegment<byte>(m_Buffer, 0, (int)m_Pos);
}
public void WriteByte(byte value)
{
WriteCheckForSpace(1);
m_Buffer[(int)((UIntPtr)m_Pos)] = value;
m_Pos += 1U;
}
public void WriteByte2(byte value0, byte value1)
{
WriteCheckForSpace(2);
m_Buffer[(int)((UIntPtr)m_Pos)] = value0;
m_Buffer[(int)((UIntPtr)(m_Pos + 1U))] = value1;
m_Pos += 2U;
}
public void WriteByte4(byte value0, byte value1, byte value2, byte value3)
{
WriteCheckForSpace(4);
m_Buffer[(int)((UIntPtr)m_Pos)] = value0;
m_Buffer[(int)((UIntPtr)(m_Pos + 1U))] = value1;
m_Buffer[(int)((UIntPtr)(m_Pos + 2U))] = value2;
m_Buffer[(int)((UIntPtr)(m_Pos + 3U))] = value3;
m_Pos += 4U;
}
public void WriteByte8(byte value0, byte value1, byte value2, byte value3, byte value4, byte value5, byte value6, byte value7)
{
WriteCheckForSpace(8);
m_Buffer[(int)((UIntPtr)m_Pos)] = value0;
m_Buffer[(int)((UIntPtr)(m_Pos + 1U))] = value1;
m_Buffer[(int)((UIntPtr)(m_Pos + 2U))] = value2;
m_Buffer[(int)((UIntPtr)(m_Pos + 3U))] = value3;
m_Buffer[(int)((UIntPtr)(m_Pos + 4U))] = value4;
m_Buffer[(int)((UIntPtr)(m_Pos + 5U))] = value5;
m_Buffer[(int)((UIntPtr)(m_Pos + 6U))] = value6;
m_Buffer[(int)((UIntPtr)(m_Pos + 7U))] = value7;
m_Pos += 8U;
}
public void WriteBytesAtOffset(byte[] buffer, ushort targetOffset, ushort count)
{
uint num = (uint)(count + targetOffset);
WriteCheckForSpace((ushort)num);
if (targetOffset == 0 && (int)count == buffer.Length)
{
buffer.CopyTo(m_Buffer, (int)m_Pos);
}
else
{
for (int i = 0; i < (int)count; i++)
{
m_Buffer[(int)targetOffset + i] = buffer[i];
}
}
if (num > m_Pos)
{
m_Pos = num;
}
}
public void WriteBytes(byte[] buffer, ushort count)
{
WriteCheckForSpace(count);
if ((int)count == buffer.Length)
{
buffer.CopyTo(m_Buffer, (int)m_Pos);
}
else
{
for (int i = 0; i < (int)count; i++)
{
m_Buffer[(int)(checked((IntPtr)(unchecked((ulong)m_Pos + (ulong)((long)i)))))] = buffer[i];
}
}
m_Pos += (uint)count;
}
private void WriteCheckForSpace(ushort count)
{
if ((ulong)(m_Pos + (uint)count) >= (ulong)((long)m_Buffer.Length))
{
int num = (int)Math.Ceiling((double)((float)m_Buffer.Length * 1.5f));
while ((ulong)(m_Pos + (uint)count) >= (ulong)((long)num))
{
num = (int)Math.Ceiling((double)((float)num * 1.5f));
if (num > 134217728)
{
Debug.LogWarning("NetworkBuffer size is " + num + " bytes!");
}
}
byte[] array = new byte[num];
m_Buffer.CopyTo(array, 0);
m_Buffer = array;
}
}
public void FinishMessage()
{
ushort num = (ushort)(m_Pos - 4U);
m_Buffer[0] = (byte)(num & 255);
m_Buffer[1] = (byte)(num >> 8 & 255);
}
public void SeekZero()
{
m_Pos = 0U;
}
public void Replace(byte[] buffer)
{
m_Buffer = buffer;
m_Pos = 0U;
}
public override string ToString()
{
return string.Format("NetBuf sz:{0} pos:{1}", m_Buffer.Length, m_Pos);
}
private byte[] m_Buffer;
private uint m_Pos;
private const int k_InitialSize = 64;
private const float k_GrowthFactor = 1.5f;
private const int k_BufferSizeWarning = 134217728;
}
}

View File

@ -1,5 +1,6 @@
using OWML.Logging;
using QuantumUNET.Components;
using QuantumUNET.Transport;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
@ -15,7 +16,7 @@ namespace QuantumUNET
public bool IsClient => MyView.IsClient;
public bool IsLocalPlayer => MyView.IsLocalPlayer;
public bool HasAuthority => MyView.HasAuthority;
public NetworkInstanceId NetId => MyView.NetId;
public QSBNetworkInstanceId NetId => MyView.NetId;
public QSBNetworkConnection ConnectionToServer => MyView.ConnectionToServer;
public QSBNetworkConnection ConnectionToClient => MyView.ConnectionToClient;
public short PlayerControllerId => MyView.PlayerControllerId;
@ -77,7 +78,7 @@ namespace QuantumUNET
}
}
writer.FinishMessage();
QSBNetworkServer.SendWriterToReady(base.gameObject, writer, channelId);
QSBNetworkServer.SendWriterToReady(gameObject, writer, channelId);
}
protected void SendTargetRPCInternal(QSBNetworkConnection conn, QSBNetworkWriter writer, int channelId, string rpcName)
@ -404,11 +405,11 @@ namespace QuantumUNET
internal static string GetCmdHashListName(int cmdHash)
=> GetCmdHashPrefixName(cmdHash, "InvokeSyncList");
protected void SetSyncVarGameObject(GameObject newGameObject, ref GameObject gameObjectField, uint dirtyBit, ref NetworkInstanceId netIdField)
protected void SetSyncVarGameObject(GameObject newGameObject, ref GameObject gameObjectField, uint dirtyBit, ref QSBNetworkInstanceId netIdField)
{
if (!SyncVarHookGuard)
{
NetworkInstanceId networkInstanceId = default;
QSBNetworkInstanceId networkInstanceId = default;
if (newGameObject != null)
{
var component = newGameObject.GetComponent<QSBNetworkIdentity>();
@ -424,7 +425,7 @@ namespace QuantumUNET
}
}
}
NetworkInstanceId networkInstanceId2 = default;
QSBNetworkInstanceId networkInstanceId2 = default;
if (gameObjectField != null)
{
networkInstanceId2 = gameObjectField.GetComponent<QSBNetworkIdentity>().NetId;
@ -434,7 +435,7 @@ namespace QuantumUNET
Debug.Log(string.Concat(new object[]
{
"SetSyncVar GameObject ",
base.GetType().Name,
GetType().Name,
" bit [",
dirtyBit,
"] netfieldId:",

View File

@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Networking;
namespace QuantumUNET
{
@ -20,13 +18,7 @@ namespace QuantumUNET
}
}
public Dictionary<string, int> scripts
{
get
{
return this.m_Scripts;
}
}
public Dictionary<string, int> scripts { get; } = new Dictionary<string, int>();
public static bool scriptCRCCheck
{
@ -42,12 +34,12 @@ namespace QuantumUNET
public static void ReinitializeScriptCRCs(Assembly callingAssembly)
{
singleton.m_Scripts.Clear();
foreach (Type type in callingAssembly.GetTypes())
singleton.scripts.Clear();
foreach (var type in callingAssembly.GetTypes())
{
if (type.GetBaseType() == typeof(QSBNetworkBehaviour))
{
MethodInfo method = type.GetMethod(".cctor", BindingFlags.Static);
var method = type.GetMethod(".cctor", BindingFlags.Static);
if (method != null)
{
method.Invoke(null, new object[0]);
@ -56,76 +48,58 @@ namespace QuantumUNET
}
}
public static void RegisterBehaviour(string name, int channel)
{
singleton.m_Scripts[name] = channel;
}
public static void RegisterBehaviour(string name, int channel) => singleton.scripts[name] = channel;
internal static bool Validate(QSBCRCMessageEntry[] scripts, int numChannels)
{
return singleton.ValidateInternal(scripts, numChannels);
}
internal static bool Validate(QSBCRCMessageEntry[] scripts, int numChannels) => singleton.ValidateInternal(scripts, numChannels);
private bool ValidateInternal(QSBCRCMessageEntry[] remoteScripts, int numChannels)
{
bool result;
if (this.m_Scripts.Count != remoteScripts.Length)
if (scripts.Count != remoteScripts.Length)
{
if (LogFilter.logWarn)
{
Debug.LogWarning("Network configuration mismatch detected. The number of networked scripts on the client does not match the number of networked scripts on the server. This could be caused by lazy loading of scripts on the client. This warning can be disabled by the checkbox in NetworkManager Script CRC Check.");
}
this.Dump(remoteScripts);
Debug.LogWarning("Network configuration mismatch detected. The number of networked scripts on the client does not match the number of networked scripts on the server. This could be caused by lazy loading of scripts on the client. This warning can be disabled by the checkbox in NetworkManager Script CRC Check.");
Dump(remoteScripts);
result = false;
}
else
{
foreach (QSBCRCMessageEntry crcmessageEntry in remoteScripts)
foreach (var crcmessageEntry in remoteScripts)
{
if (LogFilter.logDebug)
Debug.Log(string.Concat(new object[]
{
Debug.Log(string.Concat(new object[]
"Script: ",
crcmessageEntry.name,
" Channel: ",
crcmessageEntry.channel
}));
if (scripts.ContainsKey(crcmessageEntry.name))
{
var num = scripts[crcmessageEntry.name];
if (num != crcmessageEntry.channel)
{
"Script: ",
Debug.LogError(string.Concat(new object[]
{
"HLAPI CRC Channel Mismatch. Script: ",
crcmessageEntry.name,
" LocalChannel: ",
num,
" RemoteChannel: ",
crcmessageEntry.channel
}));
Dump(remoteScripts);
return false;
}
}
if (crcmessageEntry.channel >= numChannels)
{
Debug.LogError(string.Concat(new object[]
{
"HLAPI CRC channel out of range! Script: ",
crcmessageEntry.name,
" Channel: ",
crcmessageEntry.channel
}));
}
if (this.m_Scripts.ContainsKey(crcmessageEntry.name))
{
int num = this.m_Scripts[crcmessageEntry.name];
if (num != (int)crcmessageEntry.channel)
{
if (LogFilter.logError)
{
Debug.LogError(string.Concat(new object[]
{
"HLAPI CRC Channel Mismatch. Script: ",
crcmessageEntry.name,
" LocalChannel: ",
num,
" RemoteChannel: ",
crcmessageEntry.channel
}));
}
this.Dump(remoteScripts);
return false;
}
}
if ((int)crcmessageEntry.channel >= numChannels)
{
if (LogFilter.logError)
{
Debug.LogError(string.Concat(new object[]
{
"HLAPI CRC channel out of range! Script: ",
crcmessageEntry.name,
" Channel: ",
crcmessageEntry.channel
}));
}
this.Dump(remoteScripts);
Dump(remoteScripts);
return false;
}
}
@ -136,17 +110,17 @@ namespace QuantumUNET
private void Dump(QSBCRCMessageEntry[] remoteScripts)
{
foreach (string text in this.m_Scripts.Keys)
foreach (var text in scripts.Keys)
{
Debug.Log(string.Concat(new object[]
{
"CRC Local Dump ",
text,
" : ",
this.m_Scripts[text]
scripts[text]
}));
}
foreach (QSBCRCMessageEntry crcmessageEntry in remoteScripts)
foreach (var crcmessageEntry in remoteScripts)
{
Debug.Log(string.Concat(new object[]
{
@ -159,9 +133,6 @@ namespace QuantumUNET
}
internal static QSBNetworkCRC s_Singleton;
private Dictionary<string, int> m_Scripts = new Dictionary<string, int>();
private bool m_ScriptCRCCheck;
}
}

View File

@ -1,5 +1,6 @@
using OWML.Logging;
using QuantumUNET.Messages;
using QuantumUNET.Transport;
using System;
using System.Collections.Generic;
using System.Net;
@ -30,82 +31,25 @@ namespace QuantumUNET
RegisterSystemHandlers(false);
}
public static List<QSBNetworkClient> allClients
{
get
{
return s_Clients;
}
}
public static List<QSBNetworkClient> allClients { get; private set; } = new List<QSBNetworkClient>();
public static bool active
{
get
{
return s_IsActive;
}
}
public static bool active { get; private set; }
internal void SetHandlers(QSBNetworkConnection conn)
{
conn.SetHandlers(m_MessageHandlers);
}
internal void SetHandlers(QSBNetworkConnection conn) => conn.SetHandlers(m_MessageHandlers);
public string serverIp
{
get
{
return m_ServerIp;
}
}
public string serverIp { get; private set; } = "";
public int serverPort
{
get
{
return m_ServerPort;
}
}
public int serverPort { get; private set; }
public QSBNetworkConnection connection
{
get
{
return m_Connection;
}
}
public QSBNetworkConnection connection => m_Connection;
internal int hostId
{
get
{
return m_ClientId;
}
}
internal int hostId { get; private set; } = -1;
public Dictionary<short, QSBNetworkMessageDelegate> handlers
{
get
{
return m_MessageHandlers.GetHandlers();
}
}
public Dictionary<short, QSBNetworkMessageDelegate> handlers => m_MessageHandlers.GetHandlers();
public int numChannels
{
get
{
return m_HostTopology.DefaultConfig.ChannelCount;
}
}
public int numChannels => hostTopology.DefaultConfig.ChannelCount;
public HostTopology hostTopology
{
get
{
return m_HostTopology;
}
}
public HostTopology hostTopology { get; private set; }
public int hostPort
{
@ -127,36 +71,21 @@ namespace QuantumUNET
}
}
public bool isConnected
{
get
{
return m_AsyncConnect == ConnectState.Connected;
}
}
public bool isConnected => m_AsyncConnect == ConnectState.Connected;
public Type networkConnectionClass
{
get
{
return m_NetworkConnectionClass;
}
}
public Type networkConnectionClass { get; private set; } = typeof(QSBNetworkConnection);
public void SetNetworkConnectionClass<T>() where T : QSBNetworkConnection
{
m_NetworkConnectionClass = typeof(T);
}
public void SetNetworkConnectionClass<T>() where T : QSBNetworkConnection => networkConnectionClass = typeof(T);
public bool Configure(ConnectionConfig config, int maxConnections)
{
HostTopology topology = new HostTopology(config, maxConnections);
var topology = new HostTopology(config, maxConnections);
return Configure(topology);
}
public bool Configure(HostTopology topology)
{
m_HostTopology = topology;
hostTopology = topology;
return true;
}
@ -195,16 +124,16 @@ namespace QuantumUNET
QSBClientScene.ClearLocalPlayers();
m_Connection.Disconnect();
m_Connection = null;
m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort);
m_ServerPort = serverPort;
hostId = NetworkTransport.AddHost(hostTopology, m_HostPort);
this.serverPort = serverPort;
if (Application.platform == RuntimePlatform.WebGLPlayer)
{
m_ServerIp = serverIp;
this.serverIp = serverIp;
m_AsyncConnect = ConnectState.Resolved;
}
else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost"))
{
m_ServerIp = "127.0.0.1";
this.serverIp = "127.0.0.1";
m_AsyncConnect = ConnectState.Resolved;
}
else
@ -250,7 +179,7 @@ namespace QuantumUNET
QSBClientScene.ClearLocalPlayers();
m_Connection.Disconnect();
m_Connection = null;
m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort);
hostId = NetworkTransport.AddHost(hostTopology, m_HostPort);
if (secureTunnelEndPoint == null)
{
if (LogFilter.logError)
@ -271,11 +200,11 @@ namespace QuantumUNET
}
else
{
string fullName = secureTunnelEndPoint.GetType().FullName;
var fullName = secureTunnelEndPoint.GetType().FullName;
if (fullName == "System.Net.IPEndPoint")
{
IPEndPoint ipendPoint = (IPEndPoint)secureTunnelEndPoint;
this.Connect(ipendPoint.Address.ToString(), ipendPoint.Port);
var ipendPoint = (IPEndPoint)secureTunnelEndPoint;
Connect(ipendPoint.Address.ToString(), ipendPoint.Port);
result = (m_AsyncConnect != ConnectState.Failed);
}
else if (fullName != "UnityEngine.XboxOne.XboxOneEndPoint" && fullName != "UnityEngine.PS4.SceEndPoint")
@ -289,12 +218,12 @@ namespace QuantumUNET
}
else
{
byte b = 0;
m_RemoteEndPoint = secureTunnelEndPoint;
m_AsyncConnect = ConnectState.Connecting;
byte b;
try
{
m_ClientConnectionId = NetworkTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, 0, out b);
m_ClientConnectionId = NetworkTransport.ConnectEndPoint(hostId, m_RemoteEndPoint, 0, out b);
}
catch (Exception arg)
{
@ -316,9 +245,9 @@ namespace QuantumUNET
}
else
{
m_Connection = (QSBNetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass);
m_Connection = (QSBNetworkConnection)Activator.CreateInstance(networkConnectionClass);
m_Connection.SetHandlers(m_MessageHandlers);
m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology);
m_Connection.Initialize(serverIp, hostId, m_ClientConnectionId, hostTopology);
result = true;
}
}
@ -337,7 +266,7 @@ namespace QuantumUNET
private static bool IsValidIpV6(string address)
{
foreach (char c in address)
foreach (var c in address)
{
if (c != ':' && (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F'))
{
@ -357,20 +286,20 @@ namespace QuantumUNET
":",
serverPort
}));
m_ServerPort = serverPort;
this.serverPort = serverPort;
if (Application.platform == RuntimePlatform.WebGLPlayer)
{
m_ServerIp = serverIp;
this.serverIp = serverIp;
m_AsyncConnect = ConnectState.Resolved;
}
else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost"))
{
m_ServerIp = "127.0.0.1";
this.serverIp = "127.0.0.1";
m_AsyncConnect = ConnectState.Resolved;
}
else if (serverIp.IndexOf(":") != -1 && IsValidIpV6(serverIp))
{
m_ServerIp = serverIp;
this.serverIp = serverIp;
m_AsyncConnect = ConnectState.Resolved;
}
else
@ -385,7 +314,7 @@ namespace QuantumUNET
public void Connect(EndPoint secureTunnelEndPoint)
{
//bool usePlatformSpecificProtocols = NetworkTransport.DoesEndPointUsePlatformProtocols(secureTunnelEndPoint);
bool usePlatformSpecificProtocols = false;
var usePlatformSpecificProtocols = false;
PrepareForConnect(usePlatformSpecificProtocols);
if (LogFilter.logDebug)
{
@ -409,11 +338,11 @@ namespace QuantumUNET
}
else
{
string fullName = secureTunnelEndPoint.GetType().FullName;
var fullName = secureTunnelEndPoint.GetType().FullName;
if (fullName == "System.Net.IPEndPoint")
{
IPEndPoint ipendPoint = (IPEndPoint)secureTunnelEndPoint;
this.Connect(ipendPoint.Address.ToString(), ipendPoint.Port);
var ipendPoint = (IPEndPoint)secureTunnelEndPoint;
Connect(ipendPoint.Address.ToString(), ipendPoint.Port);
}
else if (fullName != "UnityEngine.XboxOne.XboxOneEndPoint" && fullName != "UnityEngine.PS4.SceEndPoint" && fullName != "UnityEngine.PSVita.SceEndPoint")
{
@ -430,7 +359,7 @@ namespace QuantumUNET
m_AsyncConnect = ConnectState.Connecting;
try
{
m_ClientConnectionId = NetworkTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, 0, out b);
m_ClientConnectionId = NetworkTransport.ConnectEndPoint(hostId, m_RemoteEndPoint, 0, out b);
}
catch (Exception arg)
{
@ -451,39 +380,36 @@ namespace QuantumUNET
}
else
{
m_Connection = (QSBNetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass);
m_Connection = (QSBNetworkConnection)Activator.CreateInstance(networkConnectionClass);
m_Connection.SetHandlers(m_MessageHandlers);
m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology);
m_Connection.Initialize(serverIp, hostId, m_ClientConnectionId, hostTopology);
}
}
}
}
private void PrepareForConnect()
{
PrepareForConnect(false);
}
private void PrepareForConnect() => PrepareForConnect(false);
private void PrepareForConnect(bool usePlatformSpecificProtocols)
{
SetActive(true);
RegisterSystemHandlers(false);
if (m_HostTopology == null)
if (hostTopology == null)
{
ConnectionConfig connectionConfig = new ConnectionConfig();
var connectionConfig = new ConnectionConfig();
connectionConfig.AddChannel(QosType.ReliableSequenced);
connectionConfig.AddChannel(QosType.Unreliable);
connectionConfig.UsePlatformSpecificProtocols = usePlatformSpecificProtocols;
m_HostTopology = new HostTopology(connectionConfig, 8);
hostTopology = new HostTopology(connectionConfig, 8);
}
if (m_UseSimulator)
{
int num = m_SimulatedLatency / 3 - 1;
var num = (m_SimulatedLatency / 3) - 1;
if (num < 1)
{
num = 1;
}
int num2 = m_SimulatedLatency * 3;
var num2 = m_SimulatedLatency * 3;
ModConsole.OwmlConsole.WriteLine(string.Concat(new object[]
{
"AddHost Using Simulator ",
@ -491,11 +417,11 @@ namespace QuantumUNET
"/",
num2
}));
m_ClientId = NetworkTransport.AddHostWithSimulator(m_HostTopology, num, num2, m_HostPort);
hostId = NetworkTransport.AddHostWithSimulator(hostTopology, num, num2, m_HostPort);
}
else
{
m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort);
hostId = NetworkTransport.AddHost(hostTopology, m_HostPort);
}
}
@ -503,8 +429,8 @@ namespace QuantumUNET
{
try
{
IPAddress[] array = Dns.EndGetHostAddresses(ar);
QSBNetworkClient networkClient = (QSBNetworkClient)ar.AsyncState;
var array = Dns.EndGetHostAddresses(ar);
var networkClient = (QSBNetworkClient)ar.AsyncState;
if (array.Length == 0)
{
Debug.LogError("DNS lookup failed for:" + networkClient.m_RequestedServerHost);
@ -512,22 +438,22 @@ namespace QuantumUNET
}
else
{
networkClient.m_ServerIp = array[0].ToString();
networkClient.serverIp = array[0].ToString();
networkClient.m_AsyncConnect = ConnectState.Resolved;
Debug.Log(string.Concat(new string[]
{
"Async DNS Result:",
networkClient.m_ServerIp,
networkClient.serverIp,
" for ",
networkClient.m_RequestedServerHost,
": ",
networkClient.m_ServerIp
networkClient.serverIp
}));
}
}
catch (SocketException ex)
{
QSBNetworkClient networkClient2 = (QSBNetworkClient)ar.AsyncState;
var networkClient2 = (QSBNetworkClient)ar.AsyncState;
Debug.LogError("DNS resolution failed: " + ex.GetErrorCode());
Debug.LogError("Exception:" + ex);
networkClient2.m_AsyncConnect = ConnectState.Failed;
@ -538,7 +464,7 @@ namespace QuantumUNET
{
if (m_UseSimulator)
{
int num = m_SimulatedLatency / 3;
var num = m_SimulatedLatency / 3;
if (num < 1)
{
num = 1;
@ -550,18 +476,16 @@ namespace QuantumUNET
"/",
m_SimulatedLatency
}));
ConnectionSimulatorConfig conf = new ConnectionSimulatorConfig(num, m_SimulatedLatency, num, m_SimulatedLatency, m_PacketLoss);
byte b;
m_ClientConnectionId = NetworkTransport.ConnectWithSimulator(m_ClientId, m_ServerIp, m_ServerPort, 0, out b, conf);
var conf = new ConnectionSimulatorConfig(num, m_SimulatedLatency, num, m_SimulatedLatency, m_PacketLoss);
m_ClientConnectionId = NetworkTransport.ConnectWithSimulator(hostId, serverIp, serverPort, 0, out var b, conf);
}
else
{
byte b;
m_ClientConnectionId = NetworkTransport.Connect(m_ClientId, m_ServerIp, m_ServerPort, 0, out b);
m_ClientConnectionId = NetworkTransport.Connect(hostId, serverIp, serverPort, 0, out var b);
}
m_Connection = (QSBNetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass);
m_Connection = (QSBNetworkConnection)Activator.CreateInstance(networkConnectionClass);
m_Connection.SetHandlers(m_MessageHandlers);
m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology);
m_Connection.Initialize(serverIp, hostId, m_ClientConnectionId, hostTopology);
}
public virtual void Disconnect()
@ -573,10 +497,10 @@ namespace QuantumUNET
m_Connection.Disconnect();
m_Connection.Dispose();
m_Connection = null;
if (m_ClientId != -1)
if (hostId != -1)
{
NetworkTransport.RemoveHost(m_ClientId);
m_ClientId = -1;
NetworkTransport.RemoveHost(hostId);
hostId = -1;
}
}
}
@ -745,15 +669,15 @@ namespace QuantumUNET
{
if (LogFilter.logDebug)
{
Debug.Log("Shutting down client " + m_ClientId);
Debug.Log("Shutting down client " + hostId);
}
if (m_ClientId != -1)
if (hostId != -1)
{
NetworkTransport.RemoveHost(m_ClientId);
m_ClientId = -1;
NetworkTransport.RemoveHost(hostId);
hostId = -1;
}
RemoveClient(this);
if (s_Clients.Count == 0)
if (allClients.Count == 0)
{
SetActive(false);
}
@ -761,7 +685,7 @@ namespace QuantumUNET
internal virtual void Update()
{
if (m_ClientId != -1)
if (hostId != -1)
{
switch (m_AsyncConnect)
{
@ -788,14 +712,11 @@ namespace QuantumUNET
m_StatResetTime = (int)Time.time;
}
}
int num = 0;
var num = 0;
byte b;
for (; ; )
{
int num2;
int channelId;
int numBytes;
NetworkEventType networkEventType = NetworkTransport.ReceiveFromHost(m_ClientId, out num2, out channelId, m_MsgBuffer, (int)((ushort)m_MsgBuffer.Length), out numBytes, out b);
var networkEventType = NetworkTransport.ReceiveFromHost(hostId, out var num2, out var channelId, m_MsgBuffer, (ushort)m_MsgBuffer.Length, out var numBytes, out b);
if (m_Connection != null)
{
m_Connection.LastError = (NetworkError)b;
@ -834,7 +755,7 @@ namespace QuantumUNET
{
if (b != 6)
{
GenerateDisconnectError((int)b);
GenerateDisconnectError(b);
}
}
QSBClientScene.HandleClientDisconnect(m_Connection);
@ -858,7 +779,7 @@ namespace QuantumUNET
{
goto Block_17;
}
if (m_ClientId == -1)
if (hostId == -1)
{
goto Block_19;
}
@ -868,10 +789,10 @@ namespace QuantumUNET
}
}
Block_10:
GenerateConnectError((int)b);
GenerateConnectError(b);
return;
Block_11:
GenerateDataError((int)b);
GenerateDataError(b);
return;
Block_17:
if (LogFilter.logDebug)
@ -916,19 +837,21 @@ namespace QuantumUNET
private void GenerateError(int error)
{
QSBNetworkMessageDelegate handler = m_MessageHandlers.GetHandler(34);
var handler = m_MessageHandlers.GetHandler(34);
if (handler == null)
{
handler = m_MessageHandlers.GetHandler(34);
}
if (handler != null)
{
QSBErrorMessage errorMessage = new QSBErrorMessage();
errorMessage.errorCode = error;
byte[] buffer = new byte[200];
QSBNetworkWriter writer = new QSBNetworkWriter(buffer);
var errorMessage = new QSBErrorMessage
{
errorCode = error
};
var buffer = new byte[200];
var writer = new QSBNetworkWriter(buffer);
errorMessage.Serialize(writer);
QSBNetworkReader reader = new QSBNetworkReader(buffer);
var reader = new QSBNetworkReader(buffer);
handler(new QSBNetworkMessage
{
MsgType = 34,
@ -986,14 +909,13 @@ namespace QuantumUNET
public int GetRTT()
{
int result;
if (m_ClientId == -1)
if (hostId == -1)
{
result = 0;
}
else
{
byte b;
result = NetworkTransport.GetCurrentRTT(m_ClientId, m_ClientConnectionId, out b);
result = NetworkTransport.GetCurrentRTT(hostId, m_ClientConnectionId, out var b);
}
return result;
}
@ -1001,7 +923,7 @@ namespace QuantumUNET
internal void RegisterSystemHandlers(bool localClient)
{
QSBClientScene.RegisterSystemHandlers(this, localClient);
this.RegisterHandlerSafe(14, new QSBNetworkMessageDelegate(OnCRC));
RegisterHandlerSafe(14, new QSBNetworkMessageDelegate(OnCRC));
}
private void OnCRC(QSBNetworkMessage netMsg)
@ -1010,33 +932,24 @@ namespace QuantumUNET
QSBNetworkCRC.Validate(s_CRCMessage.scripts, numChannels);
}
public void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler)
{
m_MessageHandlers.RegisterHandler(msgType, handler);
}
public void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) => m_MessageHandlers.RegisterHandler(msgType, handler);
public void RegisterHandlerSafe(short msgType, QSBNetworkMessageDelegate handler)
{
m_MessageHandlers.RegisterHandlerSafe(msgType, handler);
}
public void RegisterHandlerSafe(short msgType, QSBNetworkMessageDelegate handler) => m_MessageHandlers.RegisterHandlerSafe(msgType, handler);
public void UnregisterHandler(short msgType)
{
m_MessageHandlers.UnregisterHandler(msgType);
}
public void UnregisterHandler(short msgType) => m_MessageHandlers.UnregisterHandler(msgType);
public static Dictionary<short, QSBNetworkConnection.PacketStat> GetTotalConnectionStats()
{
Dictionary<short, QSBNetworkConnection.PacketStat> dictionary = new Dictionary<short, QSBNetworkConnection.PacketStat>();
for (int i = 0; i < s_Clients.Count; i++)
var dictionary = new Dictionary<short, QSBNetworkConnection.PacketStat>();
for (var i = 0; i < allClients.Count; i++)
{
QSBNetworkClient networkClient = s_Clients[i];
Dictionary<short, QSBNetworkConnection.PacketStat> connectionStats = networkClient.GetConnectionStats();
foreach (short key in connectionStats.Keys)
var networkClient = allClients[i];
var connectionStats = networkClient.GetConnectionStats();
foreach (var key in connectionStats.Keys)
{
if (dictionary.ContainsKey(key))
{
QSBNetworkConnection.PacketStat packetStat = dictionary[key];
var packetStat = dictionary[key];
packetStat.count += connectionStats[key].count;
packetStat.bytes += connectionStats[key].bytes;
dictionary[key] = packetStat;
@ -1050,61 +963,46 @@ namespace QuantumUNET
return dictionary;
}
internal static void AddClient(QSBNetworkClient client)
{
s_Clients.Add(client);
}
internal static void AddClient(QSBNetworkClient client) => allClients.Add(client);
internal static bool RemoveClient(QSBNetworkClient client)
{
return s_Clients.Remove(client);
}
internal static bool RemoveClient(QSBNetworkClient client) => allClients.Remove(client);
internal static void UpdateClients()
{
for (int i = 0; i < s_Clients.Count; i++)
for (var i = 0; i < allClients.Count; i++)
{
if (s_Clients[i] != null)
if (allClients[i] != null)
{
s_Clients[i].Update();
allClients[i].Update();
}
else
{
s_Clients.RemoveAt(i);
allClients.RemoveAt(i);
}
}
}
public static void ShutdownAll()
{
while (s_Clients.Count != 0)
while (allClients.Count != 0)
{
s_Clients[0].Shutdown();
allClients[0].Shutdown();
}
s_Clients = new List<QSBNetworkClient>();
s_IsActive = false;
allClients = new List<QSBNetworkClient>();
active = false;
QSBClientScene.Shutdown();
}
internal static void SetActive(bool state)
{
if (!s_IsActive && state)
if (!active && state)
{
NetworkTransport.Init();
}
s_IsActive = state;
active = state;
}
private Type m_NetworkConnectionClass = typeof(QSBNetworkConnection);
private const int k_MaxEventsPerFrame = 500;
private static List<QSBNetworkClient> s_Clients = new List<QSBNetworkClient>();
private static bool s_IsActive;
private HostTopology m_HostTopology;
private int m_HostPort;
private bool m_UseSimulator;
@ -1112,13 +1010,6 @@ namespace QuantumUNET
private int m_SimulatedLatency;
private float m_PacketLoss;
private string m_ServerIp = "";
private int m_ServerPort;
private int m_ClientId = -1;
private int m_ClientConnectionId = -1;
private int m_StatResetTime;

View File

@ -1,6 +1,7 @@
using OWML.Logging;
using QuantumUNET.Components;
using QuantumUNET.Messages;
using QuantumUNET.Transport;
using System;
using System.Collections.Generic;
using System.Text;
@ -20,7 +21,7 @@ namespace QuantumUNET
public List<QSBPlayerController> PlayerControllers { get; } = new List<QSBPlayerController>();
public HashSet<NetworkInstanceId> ClientOwnedObjects { get; private set; }
public HashSet<QSBNetworkInstanceId> ClientOwnedObjects { get; private set; }
public bool isConnected => hostId != -1;
@ -47,7 +48,7 @@ namespace QuantumUNET
var bufferSize = packetSize;
if (channelQOS.QOS == QosType.ReliableFragmented || channelQOS.QOS == QosType.UnreliableFragmented)
{
bufferSize = (int)(hostTopology.DefaultConfig.FragmentSize * 128);
bufferSize = hostTopology.DefaultConfig.FragmentSize * 128;
}
m_Channels[i] = new QSBChannelBuffer(this, bufferSize, (byte)i, IsReliableQoS(channelQOS.QOS), IsSequencedQoS(channelQOS.QOS));
}
@ -102,8 +103,7 @@ namespace QuantumUNET
QSBClientScene.HandleClientDisconnect(this);
if (hostId != -1)
{
byte b;
NetworkTransport.Disconnect(hostId, connectionId, out b);
NetworkTransport.Disconnect(hostId, connectionId, out var b);
RemoveObservers();
}
}
@ -182,18 +182,18 @@ namespace QuantumUNET
internal void SetPlayerController(QSBPlayerController player)
{
while ((int)player.PlayerControllerId >= PlayerControllers.Count)
while (player.PlayerControllerId >= PlayerControllers.Count)
{
PlayerControllers.Add(new QSBPlayerController());
}
PlayerControllers[(int)player.PlayerControllerId] = player;
PlayerControllers[player.PlayerControllerId] = player;
}
internal void RemovePlayerController(short playerControllerId)
{
for (var i = PlayerControllers.Count; i >= 0; i--)
{
if ((int)playerControllerId == i && playerControllerId == PlayerControllers[i].PlayerControllerId)
if (playerControllerId == i && playerControllerId == PlayerControllers[i].PlayerControllerId)
{
PlayerControllers[i] = new QSBPlayerController();
return;
@ -263,15 +263,9 @@ namespace QuantumUNET
return SendWriter(m_Writer, channelId);
}
public virtual bool SendBytes(byte[] bytes, int numBytes, int channelId)
{
return CheckChannel(channelId) && m_Channels[channelId].SendBytes(bytes, numBytes);
}
public virtual bool SendBytes(byte[] bytes, int numBytes, int channelId) => CheckChannel(channelId) && m_Channels[channelId].SendBytes(bytes, numBytes);
public virtual bool SendWriter(QSBNetworkWriter writer, int channelId)
{
return CheckChannel(channelId) && m_Channels[channelId].SendWriter(writer);
}
public virtual bool SendWriter(QSBNetworkWriter writer, int channelId) => CheckChannel(channelId) && m_Channels[channelId].SendWriter(writer);
private void LogSend(byte[] bytes)
{
@ -279,7 +273,7 @@ namespace QuantumUNET
var num = networkReader.ReadUInt16();
var num2 = networkReader.ReadUInt16();
var stringBuilder = new StringBuilder();
for (var i = 4; i < (int)(4 + num); i++)
for (var i = 4; i < 4 + num; i++)
{
stringBuilder.AppendFormat("{0:X2}", bytes[i]);
if (i > 150)
@ -348,7 +342,7 @@ namespace QuantumUNET
{
var num = reader.ReadUInt16();
var num2 = reader.ReadInt16();
var array = reader.ReadBytes((int)num);
var array = reader.ReadBytes(num);
var reader2 = new QSBNetworkReader(array);
QSBNetworkMessageDelegate networkMessageDelegate = null;
if (m_MessageHandlersDict.ContainsKey(num2))
@ -446,7 +440,7 @@ namespace QuantumUNET
{
if (ClientOwnedObjects == null)
{
ClientOwnedObjects = new HashSet<NetworkInstanceId>();
ClientOwnedObjects = new HashSet<QSBNetworkInstanceId>();
}
ClientOwnedObjects.Add(obj.NetId);
}

View File

@ -0,0 +1,125 @@
using System;
namespace QuantumUNET
{
[Serializable]
public struct QSBNetworkHash128
{
public byte i0;
public byte i1;
public byte i2;
public byte i3;
public byte i4;
public byte i5;
public byte i6;
public byte i7;
public byte i8;
public byte i9;
public byte i10;
public byte i11;
public byte i12;
public byte i13;
public byte i14;
public byte i15;
public void Reset()
{
i0 = 0;
i1 = 0;
i2 = 0;
i3 = 0;
i4 = 0;
i5 = 0;
i6 = 0;
i7 = 0;
i8 = 0;
i9 = 0;
i10 = 0;
i11 = 0;
i12 = 0;
i13 = 0;
i14 = 0;
i15 = 0;
}
public bool IsValid()
=> (i0 | i1 | i2 | i3 | i4 | i5 | i6 | i7 | i8 | i9 | i10 | i11 | i12 | i13 | i14 | i15) != 0;
private static int HexToNumber(char c)
{
int result;
if (c >= '0' && c <= '9')
{
result = c - '0';
}
else if (c >= 'a' && c <= 'f')
{
result = c - 'a' + '\n';
}
else if (c >= 'A' && c <= 'F')
{
result = c - 'A' + '\n';
}
else
{
result = 0;
}
return result;
}
public static QSBNetworkHash128 Parse(string text)
{
var length = text.Length;
if (length < 32)
{
var str = "";
for (var i = 0; i < 32 - length; i++)
{
str += "0";
}
text = str + text;
}
QSBNetworkHash128 result;
result.i0 = (byte)(HexToNumber(text[0]) * 16 + HexToNumber(text[1]));
result.i1 = (byte)(HexToNumber(text[2]) * 16 + HexToNumber(text[3]));
result.i2 = (byte)(HexToNumber(text[4]) * 16 + HexToNumber(text[5]));
result.i3 = (byte)(HexToNumber(text[6]) * 16 + HexToNumber(text[7]));
result.i4 = (byte)(HexToNumber(text[8]) * 16 + HexToNumber(text[9]));
result.i5 = (byte)(HexToNumber(text[10]) * 16 + HexToNumber(text[11]));
result.i6 = (byte)(HexToNumber(text[12]) * 16 + HexToNumber(text[13]));
result.i7 = (byte)(HexToNumber(text[14]) * 16 + HexToNumber(text[15]));
result.i8 = (byte)(HexToNumber(text[16]) * 16 + HexToNumber(text[17]));
result.i9 = (byte)(HexToNumber(text[18]) * 16 + HexToNumber(text[19]));
result.i10 = (byte)(HexToNumber(text[20]) * 16 + HexToNumber(text[21]));
result.i11 = (byte)(HexToNumber(text[22]) * 16 + HexToNumber(text[23]));
result.i12 = (byte)(HexToNumber(text[24]) * 16 + HexToNumber(text[25]));
result.i13 = (byte)(HexToNumber(text[26]) * 16 + HexToNumber(text[27]));
result.i14 = (byte)(HexToNumber(text[28]) * 16 + HexToNumber(text[29]));
result.i15 = (byte)(HexToNumber(text[30]) * 16 + HexToNumber(text[31]));
return result;
}
public override string ToString()
{
return string.Format("{0:x2}{1:x2}{2:x2}{3:x2}{4:x2}{5:x2}{6:x2}{7:x2}{8:x2}{9:x2}{10:x2}{11:x2}{12:x2}{13:x2}{14:x2}{15:x2}", new object[]
{
i0,
i1,
i2,
i3,
i4,
i5,
i6,
i7,
i8,
i9,
i10,
i11,
i12,
i13,
i14,
i15
});
}
}
}

View File

@ -0,0 +1,41 @@
using System;
using UnityEngine;
namespace QuantumUNET
{
[Serializable]
public struct QSBNetworkInstanceId
{
public uint Value => m_Value;
[SerializeField]
private readonly uint m_Value;
public QSBNetworkInstanceId(uint value)
{
m_Value = value;
}
public bool IsEmpty()
=> m_Value == 0U;
public override int GetHashCode()
=> (int)m_Value;
public override bool Equals(object obj)
=> obj is QSBNetworkInstanceId id && this == id;
public static bool operator ==(QSBNetworkInstanceId c1, QSBNetworkInstanceId c2)
=> c1.m_Value == c2.m_Value;
public static bool operator !=(QSBNetworkInstanceId c1, QSBNetworkInstanceId c2)
=> c1.m_Value != c2.m_Value;
public override string ToString()
=> m_Value.ToString();
public static QSBNetworkInstanceId Invalid = new QSBNetworkInstanceId(uint.MaxValue);
internal static QSBNetworkInstanceId Zero = new QSBNetworkInstanceId(0U);
}
}

View File

@ -7,21 +7,13 @@ namespace QuantumUNET
{
internal class QSBNetworkScene
{
private Dictionary<NetworkInstanceId, QSBNetworkIdentity> m_LocalObjects = new Dictionary<NetworkInstanceId, QSBNetworkIdentity>();
internal static Dictionary<QSBNetworkHash128, GameObject> guidToPrefab { get; } = new Dictionary<QSBNetworkHash128, GameObject>();
internal static Dictionary<NetworkHash128, GameObject> guidToPrefab { get; } = new Dictionary<NetworkHash128, GameObject>();
internal static Dictionary<QSBNetworkHash128, QSBSpawnDelegate> spawnHandlers { get; } = new Dictionary<QSBNetworkHash128, QSBSpawnDelegate>();
internal static Dictionary<NetworkHash128, SpawnDelegate> spawnHandlers { get; } = new Dictionary<NetworkHash128, SpawnDelegate>();
internal static Dictionary<QSBNetworkHash128, UnSpawnDelegate> unspawnHandlers { get; } = new Dictionary<QSBNetworkHash128, UnSpawnDelegate>();
internal static Dictionary<NetworkHash128, UnSpawnDelegate> unspawnHandlers { get; } = new Dictionary<NetworkHash128, UnSpawnDelegate>();
internal Dictionary<NetworkInstanceId, QSBNetworkIdentity> localObjects
{
get
{
return m_LocalObjects;
}
}
internal Dictionary<QSBNetworkInstanceId, QSBNetworkIdentity> localObjects { get; } = new Dictionary<QSBNetworkInstanceId, QSBNetworkIdentity>();
internal void Shutdown()
{
@ -29,7 +21,7 @@ namespace QuantumUNET
ClearSpawners();
}
internal void SetLocalObject(NetworkInstanceId netId, GameObject obj, bool isClient, bool isServer)
internal void SetLocalObject(QSBNetworkInstanceId netId, GameObject obj, bool isClient, bool isServer)
{
if (obj == null)
{
@ -51,7 +43,7 @@ namespace QuantumUNET
}
}
internal GameObject FindLocalObject(NetworkInstanceId netId)
internal GameObject FindLocalObject(QSBNetworkInstanceId netId)
{
if (localObjects.ContainsKey(netId))
{
@ -64,7 +56,7 @@ namespace QuantumUNET
return null;
}
internal bool GetNetworkIdentity(NetworkInstanceId netId, out QSBNetworkIdentity uv)
internal bool GetNetworkIdentity(QSBNetworkInstanceId netId, out QSBNetworkIdentity uv)
{
bool result;
if (localObjects.ContainsKey(netId) && localObjects[netId] != null)
@ -80,18 +72,15 @@ namespace QuantumUNET
return result;
}
internal bool RemoveLocalObject(NetworkInstanceId netId)
{
return localObjects.Remove(netId);
}
internal bool RemoveLocalObject(QSBNetworkInstanceId netId) => localObjects.Remove(netId);
internal bool RemoveLocalObjectAndDestroy(NetworkInstanceId netId)
internal bool RemoveLocalObjectAndDestroy(QSBNetworkInstanceId netId)
{
bool result;
if (localObjects.ContainsKey(netId))
{
var networkIdentity = localObjects[netId];
UnityEngine.Object.Destroy(networkIdentity.gameObject);
Object.Destroy(networkIdentity.gameObject);
result = localObjects.Remove(netId);
}
else
@ -101,12 +90,9 @@ namespace QuantumUNET
return result;
}
internal void ClearLocalObjects()
{
localObjects.Clear();
}
internal void ClearLocalObjects() => localObjects.Clear();
internal static void RegisterPrefab(GameObject prefab, NetworkHash128 newAssetId)
internal static void RegisterPrefab(GameObject prefab, QSBNetworkHash128 newAssetId)
{
var component = prefab.GetComponent<QSBNetworkIdentity>();
if (component)
@ -141,7 +127,7 @@ namespace QuantumUNET
}
}
internal static bool GetPrefab(NetworkHash128 assetId, out GameObject prefab)
internal static bool GetPrefab(QSBNetworkHash128 assetId, out GameObject prefab)
{
bool result;
if (!assetId.IsValid())
@ -169,13 +155,13 @@ namespace QuantumUNET
unspawnHandlers.Clear();
}
public static void UnregisterSpawnHandler(NetworkHash128 assetId)
public static void UnregisterSpawnHandler(QSBNetworkHash128 assetId)
{
spawnHandlers.Remove(assetId);
unspawnHandlers.Remove(assetId);
}
internal static void RegisterSpawnHandler(NetworkHash128 assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
internal static void RegisterSpawnHandler(QSBNetworkHash128 assetId, QSBSpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
{
if (spawnHandler == null || unspawnHandler == null)
{
@ -208,7 +194,7 @@ namespace QuantumUNET
}
}
internal static void RegisterPrefab(GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
internal static void RegisterPrefab(GameObject prefab, QSBSpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
{
var component = prefab.GetComponent<QSBNetworkIdentity>();
if (component == null)
@ -230,7 +216,7 @@ namespace QuantumUNET
}
}
internal static bool GetSpawnHandler(NetworkHash128 assetId, out SpawnDelegate handler)
internal static bool GetSpawnHandler(QSBNetworkHash128 assetId, out QSBSpawnDelegate handler)
{
bool result;
if (spawnHandlers.ContainsKey(assetId))
@ -246,7 +232,7 @@ namespace QuantumUNET
return result;
}
internal static bool InvokeUnSpawnHandler(NetworkHash128 assetId, GameObject obj)
internal static bool InvokeUnSpawnHandler(QSBNetworkHash128 assetId, GameObject obj)
{
bool result;
if (unspawnHandlers.ContainsKey(assetId) && unspawnHandlers[assetId] != null)
@ -273,7 +259,7 @@ namespace QuantumUNET
{
if (networkIdentity.SceneId.IsEmpty())
{
UnityEngine.Object.Destroy(networkIdentity.gameObject);
Object.Destroy(networkIdentity.gameObject);
}
else
{

View File

@ -0,0 +1,36 @@
using System;
using UnityEngine;
namespace QuantumUNET
{
[Serializable]
public struct QSBNetworkSceneId
{
public uint Value => m_Value;
[SerializeField]
private uint m_Value;
public QSBNetworkSceneId(uint value)
{
m_Value = value;
}
public bool IsEmpty()
=> m_Value == 0U;
public override int GetHashCode()
=> (int)m_Value;
public override bool Equals(object obj)
=> obj is QSBNetworkSceneId id && this == id;
public static bool operator ==(QSBNetworkSceneId c1, QSBNetworkSceneId c2)
=> c1.m_Value == c2.m_Value;
public static bool operator !=(QSBNetworkSceneId c1, QSBNetworkSceneId c2)
=> c1.m_Value != c2.m_Value;
public override string ToString() => m_Value.ToString();
}
}

View File

@ -1,6 +1,7 @@
using OWML.Logging;
using QuantumUNET.Components;
using QuantumUNET.Messages;
using QuantumUNET.Transport;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@ -15,67 +16,25 @@ namespace QuantumUNET
private QSBNetworkServer()
{
NetworkTransport.Init();
m_RemoveList = new HashSet<NetworkInstanceId>();
m_RemoveList = new HashSet<QSBNetworkInstanceId>();
m_ExternalConnections = new HashSet<int>();
m_NetworkScene = new QSBNetworkScene();
m_SimpleServerSimple = new ServerSimpleWrapper(this);
}
public static List<QSBNetworkConnection> localConnections
{
get
{
return instance.m_LocalConnectionsFakeList;
}
}
public static List<QSBNetworkConnection> localConnections => instance.m_LocalConnectionsFakeList;
public static int listenPort
{
get
{
return instance.m_SimpleServerSimple.listenPort;
}
}
public static int listenPort => instance.m_SimpleServerSimple.listenPort;
public static int serverHostId
{
get
{
return instance.m_SimpleServerSimple.serverHostId;
}
}
public static int serverHostId => instance.m_SimpleServerSimple.serverHostId;
public static ReadOnlyCollection<QSBNetworkConnection> connections
{
get
{
return instance.m_SimpleServerSimple.connections;
}
}
public static ReadOnlyCollection<QSBNetworkConnection> connections => instance.m_SimpleServerSimple.connections;
public static Dictionary<short, QSBNetworkMessageDelegate> handlers
{
get
{
return instance.m_SimpleServerSimple.handlers;
}
}
public static Dictionary<short, QSBNetworkMessageDelegate> handlers => instance.m_SimpleServerSimple.handlers;
public static HostTopology hostTopology
{
get
{
return instance.m_SimpleServerSimple.hostTopology;
}
}
public static HostTopology hostTopology => instance.m_SimpleServerSimple.hostTopology;
public static Dictionary<NetworkInstanceId, QSBNetworkIdentity> objects
{
get
{
return instance.m_NetworkScene.localObjects;
}
}
public static Dictionary<QSBNetworkInstanceId, QSBNetworkIdentity> objects => instance.m_NetworkScene.localObjects;
public static bool dontListen { get; set; }
@ -112,21 +71,9 @@ namespace QuantumUNET
public static bool active { get; private set; }
public static bool localClientActive
{
get
{
return instance.m_LocalClientActive;
}
}
public static bool localClientActive => instance.m_LocalClientActive;
public static int numChannels
{
get
{
return instance.m_SimpleServerSimple.hostTopology.DefaultConfig.ChannelCount;
}
}
public static int numChannels => instance.m_SimpleServerSimple.hostTopology.DefaultConfig.ChannelCount;
public static float maxDelay
{
@ -140,28 +87,13 @@ namespace QuantumUNET
}
}
public static Type networkConnectionClass
{
get
{
return instance.m_SimpleServerSimple.networkConnectionClass;
}
}
public static Type networkConnectionClass => instance.m_SimpleServerSimple.networkConnectionClass;
public static void SetNetworkConnectionClass<T>() where T : QSBNetworkConnection
{
instance.m_SimpleServerSimple.SetNetworkConnectionClass<T>();
}
public static void SetNetworkConnectionClass<T>() where T : QSBNetworkConnection => instance.m_SimpleServerSimple.SetNetworkConnectionClass<T>();
public static bool Configure(ConnectionConfig config, int maxConnections)
{
return instance.m_SimpleServerSimple.Configure(config, maxConnections);
}
public static bool Configure(ConnectionConfig config, int maxConnections) => instance.m_SimpleServerSimple.Configure(config, maxConnections);
public static bool Configure(HostTopology topology)
{
return instance.m_SimpleServerSimple.Configure(topology);
}
public static bool Configure(HostTopology topology) => instance.m_SimpleServerSimple.Configure(topology);
public static void Reset()
{
@ -200,10 +132,7 @@ namespace QuantumUNET
maxPacketSize = hostTopology.DefaultConfig.PacketSize;
}
public static void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId)
{
instance.InternalListenRelay(relayIp, relayPort, netGuid, sourceId, nodeId);
}
public static void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId) => instance.InternalListenRelay(relayIp, relayPort, netGuid, sourceId, nodeId);
private void InternalListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId)
{
@ -212,15 +141,9 @@ namespace QuantumUNET
RegisterMessageHandlers();
}
public static bool Listen(int serverPort)
{
return instance.InternalListen(null, serverPort);
}
public static bool Listen(int serverPort) => instance.InternalListen(null, serverPort);
public static bool Listen(string ipAddress, int serverPort)
{
return instance.InternalListen(ipAddress, serverPort);
}
public static bool Listen(string ipAddress, int serverPort) => instance.InternalListen(ipAddress, serverPort);
internal bool InternalListen(string ipAddress, int serverPort)
{
@ -293,7 +216,7 @@ namespace QuantumUNET
m_SimpleServerSimple.RemoveConnectionAtIndex(0);
}
internal void SetLocalObjectOnServer(NetworkInstanceId netId, GameObject obj)
internal void SetLocalObjectOnServer(QSBNetworkInstanceId netId, GameObject obj)
{
Debug.Log(string.Concat(new object[]
{
@ -585,10 +508,7 @@ namespace QuantumUNET
return result;
}
public static void DisconnectAll()
{
instance.InternalDisconnectAll();
}
public static void DisconnectAll() => instance.InternalDisconnectAll();
internal void InternalDisconnectAll()
{
@ -690,10 +610,7 @@ namespace QuantumUNET
conn.Dispose();
}
private void OnData(QSBNetworkConnection conn, int receivedSize, int channelId)
{
conn.TransportReceive(m_SimpleServerSimple.messageBuffer, receivedSize, channelId);
}
private void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) => conn.TransportReceive(m_SimpleServerSimple.messageBuffer, receivedSize, channelId);
private void GenerateConnectError(int error)
{
@ -734,8 +651,10 @@ namespace QuantumUNET
{
if (handlers.ContainsKey(34))
{
var errorMessage = new QSBErrorMessage();
errorMessage.errorCode = error;
var errorMessage = new QSBErrorMessage
{
errorCode = error
};
var writer = new QSBNetworkWriter();
errorMessage.Serialize(writer);
var reader = new QSBNetworkReader(writer);
@ -743,25 +662,13 @@ namespace QuantumUNET
}
}
public static void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler)
{
instance.m_SimpleServerSimple.RegisterHandler(msgType, handler);
}
public static void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) => instance.m_SimpleServerSimple.RegisterHandler(msgType, handler);
public static void UnregisterHandler(short msgType)
{
instance.m_SimpleServerSimple.UnregisterHandler(msgType);
}
public static void UnregisterHandler(short msgType) => instance.m_SimpleServerSimple.UnregisterHandler(msgType);
public static void ClearHandlers()
{
instance.m_SimpleServerSimple.ClearHandlers();
}
public static void ClearHandlers() => instance.m_SimpleServerSimple.ClearHandlers();
public static void ClearSpawners()
{
QSBNetworkScene.ClearSpawners();
}
public static void ClearSpawners() => QSBNetworkScene.ClearSpawners();
public static void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond)
{
@ -774,11 +681,7 @@ namespace QuantumUNET
var networkConnection = connections[i];
if (networkConnection != null)
{
int num;
int num2;
int num3;
int num4;
networkConnection.GetStatsOut(out num, out num2, out num3, out num4);
networkConnection.GetStatsOut(out var num, out var num2, out var num3, out var num4);
numMsgs += num;
numBufferedMsgs += num2;
numBytes += num3;
@ -796,9 +699,7 @@ namespace QuantumUNET
var networkConnection = connections[i];
if (networkConnection != null)
{
int num;
int num2;
networkConnection.GetStatsIn(out num, out num2);
networkConnection.GetStatsIn(out var num, out var num2);
numMsgs += num;
numBytes += num2;
}
@ -846,16 +747,12 @@ namespace QuantumUNET
}
}
public static bool AddPlayerForConnection(QSBNetworkConnection conn, GameObject player, short playerControllerId)
{
return instance.InternalAddPlayerForConnection(conn, player, playerControllerId);
}
public static bool AddPlayerForConnection(QSBNetworkConnection conn, GameObject player, short playerControllerId) => instance.InternalAddPlayerForConnection(conn, player, playerControllerId);
internal bool InternalAddPlayerForConnection(QSBNetworkConnection conn, GameObject playerGameObject, short playerControllerId)
{
QSBNetworkIdentity networkIdentity;
bool result;
if (!GetNetworkIdentity(playerGameObject, out networkIdentity))
if (!GetNetworkIdentity(playerGameObject, out var networkIdentity))
{
if (LogFilter.logError)
{
@ -872,9 +769,8 @@ namespace QuantumUNET
}
else
{
QSBPlayerController playerController = null;
GameObject x = null;
if (conn.GetPlayerController(playerControllerId, out playerController))
if (conn.GetPlayerController(playerControllerId, out var playerController))
{
x = playerController.Gameobject;
}
@ -963,9 +859,8 @@ namespace QuantumUNET
private bool SetupLocalPlayerForConnection(QSBNetworkConnection conn, QSBNetworkIdentity uv, QSBPlayerController newPlayerController)
{
Debug.Log("NetworkServer SetupLocalPlayerForConnection netID:" + uv.NetId);
var ulocalConnectionToClient = conn as QSBULocalConnectionToClient;
bool result;
if (ulocalConnectionToClient != null)
if (conn is QSBULocalConnectionToClient ulocalConnectionToClient)
{
Debug.Log("NetworkServer AddPlayer handling ULocalConnectionToClient");
if (uv.NetId.IsEmpty())
@ -1002,9 +897,8 @@ namespace QuantumUNET
internal bool InternalReplacePlayerForConnection(QSBNetworkConnection conn, GameObject playerGameObject, short playerControllerId)
{
QSBNetworkIdentity networkIdentity;
bool result;
if (!GetNetworkIdentity(playerGameObject, out networkIdentity))
if (!GetNetworkIdentity(playerGameObject, out var networkIdentity))
{
if (LogFilter.logError)
{
@ -1019,8 +913,7 @@ namespace QuantumUNET
else
{
Debug.Log("NetworkServer ReplacePlayer");
QSBPlayerController playerController;
if (conn.GetPlayerController(playerControllerId, out playerController))
if (conn.GetPlayerController(playerControllerId, out var playerController))
{
playerController.UnetView.SetNotLocalPlayer();
playerController.UnetView.ClearClientOwner();
@ -1072,10 +965,7 @@ namespace QuantumUNET
return result;
}
public static void SetClientReady(QSBNetworkConnection conn)
{
instance.SetClientReadyInternal(conn);
}
public static void SetClientReady(QSBNetworkConnection conn) => instance.SetClientReadyInternal(conn);
internal void SetClientReadyInternal(QSBNetworkConnection conn)
{
@ -1100,15 +990,14 @@ namespace QuantumUNET
}
}
conn.isReady = true;
var ulocalConnectionToClient = conn as QSBULocalConnectionToClient;
if (ulocalConnectionToClient != null)
if (conn is QSBULocalConnectionToClient ulocalConnectionToClient)
{
Debug.Log("NetworkServer Ready handling ULocalConnectionToClient");
foreach (var networkIdentity in objects.Values)
{
if (networkIdentity != null && networkIdentity.gameObject != null)
{
bool flag = networkIdentity.OnCheckObserver(conn);
var flag = networkIdentity.OnCheckObserver(conn);
if (flag)
{
networkIdentity.AddObserver(conn);
@ -1133,8 +1022,10 @@ namespace QuantumUNET
conn.connectionId
}));
}
var objectSpawnFinishedMessage = new QSBObjectSpawnFinishedMessage();
objectSpawnFinishedMessage.State = 0U;
var objectSpawnFinishedMessage = new QSBObjectSpawnFinishedMessage
{
State = 0U
};
conn.Send(12, objectSpawnFinishedMessage);
foreach (var networkIdentity2 in objects.Values)
{
@ -1157,7 +1048,7 @@ namespace QuantumUNET
networkIdentity2.NetId
}));
}
bool flag2 = networkIdentity2.OnCheckObserver(conn);
var flag2 = networkIdentity2.OnCheckObserver(conn);
if (flag2)
{
networkIdentity2.AddObserver(conn);
@ -1198,10 +1089,7 @@ namespace QuantumUNET
}
}
public static void SetClientNotReady(QSBNetworkConnection conn)
{
instance.InternalSetClientNotReady(conn);
}
public static void SetClientNotReady(QSBNetworkConnection conn) => instance.InternalSetClientNotReady(conn);
internal void InternalSetClientNotReady(QSBNetworkConnection conn)
{
@ -1230,8 +1118,7 @@ namespace QuantumUNET
private static void OnRemovePlayerMessage(QSBNetworkMessage netMsg)
{
netMsg.ReadMessage<QSBRemovePlayerMessage>(s_RemovePlayerMessage);
QSBPlayerController playerController = null;
netMsg.Connection.GetPlayerController(s_RemovePlayerMessage.PlayerControllerId, out playerController);
netMsg.Connection.GetPlayerController(s_RemovePlayerMessage.PlayerControllerId, out var playerController);
if (playerController != null)
{
netMsg.Connection.RemovePlayerController(s_RemovePlayerMessage.PlayerControllerId);
@ -1302,12 +1189,11 @@ namespace QuantumUNET
internal void SpawnObject(GameObject obj)
{
QSBNetworkIdentity networkIdentity;
if (!active)
{
ModConsole.OwmlConsole.WriteLine("Error - SpawnObject for " + obj + ", NetworkServer is not active. Cannot spawn objects without an active server.");
}
else if (!GetNetworkIdentity(obj, out networkIdentity))
else if (!GetNetworkIdentity(obj, out var networkIdentity))
{
Debug.LogError(string.Concat(new object[]
{
@ -1331,11 +1217,13 @@ namespace QuantumUNET
{
if (uv.SceneId.IsEmpty())
{
var objectSpawnMessage = new QSBObjectSpawnMessage();
objectSpawnMessage.NetId = uv.NetId;
objectSpawnMessage.assetId = uv.AssetId;
objectSpawnMessage.Position = uv.transform.position;
objectSpawnMessage.Rotation = uv.transform.rotation;
var objectSpawnMessage = new QSBObjectSpawnMessage
{
NetId = uv.NetId,
assetId = uv.AssetId,
Position = uv.transform.position,
Rotation = uv.transform.rotation
};
var networkWriter = new QSBNetworkWriter();
uv.UNetSerializeAllVars(networkWriter);
if (networkWriter.Position > 0)
@ -1353,10 +1241,12 @@ namespace QuantumUNET
}
else
{
var objectSpawnSceneMessage = new QSBObjectSpawnSceneMessage();
objectSpawnSceneMessage.NetId = uv.NetId;
objectSpawnSceneMessage.SceneId = uv.SceneId;
objectSpawnSceneMessage.Position = uv.transform.position;
var objectSpawnSceneMessage = new QSBObjectSpawnSceneMessage
{
NetId = uv.NetId,
SceneId = uv.SceneId,
Position = uv.transform.position
};
var networkWriter2 = new QSBNetworkWriter();
uv.UNetSerializeAllVars(networkWriter2);
if (networkWriter2.Position > 0)
@ -1388,7 +1278,7 @@ namespace QuantumUNET
{
if (conn.ClientOwnedObjects != null)
{
var hashSet = new HashSet<NetworkInstanceId>(conn.ClientOwnedObjects);
var hashSet = new HashSet<QSBNetworkInstanceId>(conn.ClientOwnedObjects);
foreach (var netId in hashSet)
{
var gameObject = FindLocalObject(netId);
@ -1416,30 +1306,25 @@ namespace QuantumUNET
private static void UnSpawnObject(GameObject obj)
{
QSBNetworkIdentity uv;
if (obj == null)
{
Debug.Log("NetworkServer UnspawnObject is null");
}
else if (GetNetworkIdentity(obj, out uv))
else if (GetNetworkIdentity(obj, out var uv))
{
UnSpawnObject(uv);
}
}
private static void UnSpawnObject(QSBNetworkIdentity uv)
{
DestroyObject(uv, false);
}
private static void UnSpawnObject(QSBNetworkIdentity uv) => DestroyObject(uv, false);
private static void DestroyObject(GameObject obj)
{
QSBNetworkIdentity uv;
if (obj == null)
{
Debug.Log("NetworkServer DestroyObject is null");
}
else if (GetNetworkIdentity(obj, out uv))
else if (GetNetworkIdentity(obj, out var uv))
{
DestroyObject(uv, true);
}
@ -1459,8 +1344,10 @@ namespace QuantumUNET
{
uv.ClientAuthorityOwner.RemoveOwnedObject(uv);
}
var objectDestroyMessage = new QSBObjectDestroyMessage();
objectDestroyMessage.NetId = uv.NetId;
var objectDestroyMessage = new QSBObjectDestroyMessage
{
NetId = uv.NetId
};
SendToObservers(uv.gameObject, 1, objectDestroyMessage);
uv.ClearObservers();
if (QSBNetworkClient.active && instance.m_LocalClientActive)
@ -1475,10 +1362,7 @@ namespace QuantumUNET
uv.MarkForReset();
}
public static void ClearLocalObjects()
{
objects.Clear();
}
public static void ClearLocalObjects() => objects.Clear();
public static void Spawn(GameObject obj)
{
@ -1488,10 +1372,7 @@ namespace QuantumUNET
}
}
private static bool CheckForPrefab(GameObject obj)
{
return false;
}
private static bool CheckForPrefab(GameObject obj) => false;
private static bool VerifyCanSpawn(GameObject obj)
{
@ -1549,19 +1430,18 @@ namespace QuantumUNET
return result;
}
public static bool SpawnWithClientAuthority(GameObject obj, NetworkHash128 assetId, QSBNetworkConnection conn)
public static bool SpawnWithClientAuthority(GameObject obj, QSBNetworkHash128 assetId, QSBNetworkConnection conn)
{
Spawn(obj, assetId);
var component = obj.GetComponent<QSBNetworkIdentity>();
return !(component == null) && component.IsServer && component.AssignClientAuthority(conn);
}
public static void Spawn(GameObject obj, NetworkHash128 assetId)
public static void Spawn(GameObject obj, QSBNetworkHash128 assetId)
{
if (VerifyCanSpawn(obj))
{
QSBNetworkIdentity networkIdentity;
if (GetNetworkIdentity(obj, out networkIdentity))
if (GetNetworkIdentity(obj, out var networkIdentity))
{
networkIdentity.SetDynamicAssetId(assetId);
}
@ -1569,15 +1449,9 @@ namespace QuantumUNET
}
}
public static void Destroy(GameObject obj)
{
DestroyObject(obj);
}
public static void Destroy(GameObject obj) => DestroyObject(obj);
public static void UnSpawn(GameObject obj)
{
UnSpawnObject(obj);
}
public static void UnSpawn(GameObject obj) => UnSpawnObject(obj);
internal bool InvokeBytes(QSBULocalConnectionToServer conn, byte[] buffer, int numBytes, int channelId)
{
@ -1625,15 +1499,9 @@ namespace QuantumUNET
return result;
}
public static GameObject FindLocalObject(NetworkInstanceId netId)
{
return instance.m_NetworkScene.FindLocalObject(netId);
}
public static GameObject FindLocalObject(QSBNetworkInstanceId netId) => instance.m_NetworkScene.FindLocalObject(netId);
private static bool ValidateSceneObject(QSBNetworkIdentity netId)
{
return netId.gameObject.hideFlags != HideFlags.NotEditable && netId.gameObject.hideFlags != HideFlags.HideAndDontSave && !netId.SceneId.IsEmpty();
}
private static bool ValidateSceneObject(QSBNetworkIdentity netId) => netId.gameObject.hideFlags != HideFlags.NotEditable && netId.gameObject.hideFlags != HideFlags.HideAndDontSave && !netId.SceneId.IsEmpty();
public static bool SpawnObjects()
{
@ -1684,7 +1552,7 @@ namespace QuantumUNET
{
var crcmessage = new QSBCRCMessage();
var list = new List<QSBCRCMessageEntry>();
foreach (string text in QSBNetworkCRC.singleton.scripts.Keys)
foreach (var text in QSBNetworkCRC.singleton.scripts.Keys)
{
list.Add(new QSBCRCMessageEntry
{
@ -1716,7 +1584,7 @@ namespace QuantumUNET
private float m_MaxDelay = 0.1f;
private HashSet<NetworkInstanceId> m_RemoveList;
private HashSet<QSBNetworkInstanceId> m_RemoveList;
private int m_RemoveListCount;
@ -1733,35 +1601,17 @@ namespace QuantumUNET
m_Server = server;
}
public override void OnConnectError(int connectionId, byte error)
{
m_Server.GenerateConnectError((int)error);
}
public override void OnConnectError(int connectionId, byte error) => m_Server.GenerateConnectError(error);
public override void OnDataError(QSBNetworkConnection conn, byte error)
{
m_Server.GenerateDataError(conn, (int)error);
}
public override void OnDataError(QSBNetworkConnection conn, byte error) => m_Server.GenerateDataError(conn, error);
public override void OnDisconnectError(QSBNetworkConnection conn, byte error)
{
m_Server.GenerateDisconnectError(conn, (int)error);
}
public override void OnDisconnectError(QSBNetworkConnection conn, byte error) => m_Server.GenerateDisconnectError(conn, error);
public override void OnConnected(QSBNetworkConnection conn)
{
m_Server.OnConnected(conn);
}
public override void OnConnected(QSBNetworkConnection conn) => m_Server.OnConnected(conn);
public override void OnDisconnected(QSBNetworkConnection conn)
{
m_Server.OnDisconnected(conn);
}
public override void OnDisconnected(QSBNetworkConnection conn) => m_Server.OnDisconnected(conn);
public override void OnData(QSBNetworkConnection conn, int receivedSize, int channelId)
{
m_Server.OnData(conn, receivedSize, channelId);
}
public override void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) => m_Server.OnData(conn, receivedSize, channelId);
private QSBNetworkServer m_Server;
}

View File

@ -1,4 +1,5 @@
using QuantumUNET.Messages;
using QuantumUNET.Transport;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@ -12,112 +13,43 @@ namespace QuantumUNET
{
public QSBNetworkServerSimple()
{
this.m_ConnectionsReadOnly = new ReadOnlyCollection<QSBNetworkConnection>(this.m_Connections);
connections = new ReadOnlyCollection<QSBNetworkConnection>(m_Connections);
}
public int listenPort
{
get
{
return this.m_ListenPort;
}
set
{
this.m_ListenPort = value;
}
}
public int listenPort { get; set; }
public int serverHostId
{
get
{
return this.m_ServerHostId;
}
set
{
this.m_ServerHostId = value;
}
}
public int serverHostId { get; set; } = -1;
public HostTopology hostTopology
{
get
{
return this.m_HostTopology;
}
}
public HostTopology hostTopology { get; private set; }
public bool useWebSockets
{
get
{
return this.m_UseWebSockets;
}
set
{
this.m_UseWebSockets = value;
}
}
public bool useWebSockets { get; set; }
public ReadOnlyCollection<QSBNetworkConnection> connections
{
get
{
return this.m_ConnectionsReadOnly;
}
}
public ReadOnlyCollection<QSBNetworkConnection> connections { get; }
public Dictionary<short, QSBNetworkMessageDelegate> handlers
{
get
{
return this.m_MessageHandlers.GetHandlers();
}
}
public Dictionary<short, QSBNetworkMessageDelegate> handlers => m_MessageHandlers.GetHandlers();
public byte[] messageBuffer
{
get
{
return this.m_MsgBuffer;
}
}
public byte[] messageBuffer { get; private set; } = null;
public NetworkReader messageReader
{
get
{
return this.m_MsgReader;
}
}
public NetworkReader messageReader { get; private set; } = null;
public Type networkConnectionClass
{
get
{
return this.m_NetworkConnectionClass;
}
}
public Type networkConnectionClass { get; private set; } = typeof(QSBNetworkConnection);
public void SetNetworkConnectionClass<T>() where T : QSBNetworkConnection
{
this.m_NetworkConnectionClass = typeof(T);
}
public void SetNetworkConnectionClass<T>() where T : QSBNetworkConnection => networkConnectionClass = typeof(T);
public virtual void Initialize()
{
if (!this.m_Initialized)
if (!m_Initialized)
{
this.m_Initialized = true;
m_Initialized = true;
NetworkTransport.Init();
this.m_MsgBuffer = new byte[65535];
this.m_MsgReader = new NetworkReader(this.m_MsgBuffer);
if (this.m_HostTopology == null)
messageBuffer = new byte[65535];
messageReader = new NetworkReader(messageBuffer);
if (hostTopology == null)
{
ConnectionConfig connectionConfig = new ConnectionConfig();
var connectionConfig = new ConnectionConfig();
connectionConfig.AddChannel(QosType.ReliableSequenced);
connectionConfig.AddChannel(QosType.Unreliable);
this.m_HostTopology = new HostTopology(connectionConfig, 8);
hostTopology = new HostTopology(connectionConfig, 8);
}
if (LogFilter.logDebug)
{
@ -128,30 +60,30 @@ namespace QuantumUNET
public bool Configure(ConnectionConfig config, int maxConnections)
{
HostTopology topology = new HostTopology(config, maxConnections);
return this.Configure(topology);
var topology = new HostTopology(config, maxConnections);
return Configure(topology);
}
public bool Configure(HostTopology topology)
{
this.m_HostTopology = topology;
hostTopology = topology;
return true;
}
public bool Listen(string ipAddress, int serverListenPort)
{
this.Initialize();
this.m_ListenPort = serverListenPort;
if (this.m_UseWebSockets)
Initialize();
listenPort = serverListenPort;
if (useWebSockets)
{
this.m_ServerHostId = NetworkTransport.AddWebsocketHost(this.m_HostTopology, serverListenPort, ipAddress);
serverHostId = NetworkTransport.AddWebsocketHost(hostTopology, serverListenPort, ipAddress);
}
else
{
this.m_ServerHostId = NetworkTransport.AddHost(this.m_HostTopology, serverListenPort, ipAddress);
serverHostId = NetworkTransport.AddHost(hostTopology, serverListenPort, ipAddress);
}
bool result;
if (this.m_ServerHostId == -1)
if (serverHostId == -1)
{
result = false;
}
@ -164,7 +96,7 @@ namespace QuantumUNET
"NetworkServerSimple listen: ",
ipAddress,
":",
this.m_ListenPort
listenPort
}));
}
result = true;
@ -172,26 +104,23 @@ namespace QuantumUNET
return result;
}
public bool Listen(int serverListenPort)
{
return this.Listen(serverListenPort, this.m_HostTopology);
}
public bool Listen(int serverListenPort) => Listen(serverListenPort, hostTopology);
public bool Listen(int serverListenPort, HostTopology topology)
{
this.m_HostTopology = topology;
this.Initialize();
this.m_ListenPort = serverListenPort;
if (this.m_UseWebSockets)
hostTopology = topology;
Initialize();
listenPort = serverListenPort;
if (useWebSockets)
{
this.m_ServerHostId = NetworkTransport.AddWebsocketHost(this.m_HostTopology, serverListenPort);
serverHostId = NetworkTransport.AddWebsocketHost(hostTopology, serverListenPort);
}
else
{
this.m_ServerHostId = NetworkTransport.AddHost(this.m_HostTopology, serverListenPort);
serverHostId = NetworkTransport.AddHost(hostTopology, serverListenPort);
}
bool result;
if (this.m_ServerHostId == -1)
if (serverHostId == -1)
{
result = false;
}
@ -199,7 +128,7 @@ namespace QuantumUNET
{
if (LogFilter.logDebug)
{
Debug.Log("NetworkServerSimple listen " + this.m_ListenPort);
Debug.Log("NetworkServerSimple listen " + listenPort);
}
result = true;
}
@ -208,19 +137,18 @@ namespace QuantumUNET
public void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId)
{
this.Initialize();
this.m_ServerHostId = NetworkTransport.AddHost(this.m_HostTopology, this.listenPort);
Initialize();
serverHostId = NetworkTransport.AddHost(hostTopology, listenPort);
if (LogFilter.logDebug)
{
Debug.Log("Server Host Slot Id: " + this.m_ServerHostId);
Debug.Log("Server Host Slot Id: " + serverHostId);
}
this.Update();
byte b;
NetworkTransport.ConnectAsNetworkHost(this.m_ServerHostId, relayIp, relayPort, netGuid, sourceId, nodeId, out b);
this.m_RelaySlotId = 0;
Update();
NetworkTransport.ConnectAsNetworkHost(serverHostId, relayIp, relayPort, netGuid, sourceId, nodeId, out var b);
m_RelaySlotId = 0;
if (LogFilter.logDebug)
{
Debug.Log("Relay Slot Id: " + this.m_RelaySlotId);
Debug.Log("Relay Slot Id: " + m_RelaySlotId);
}
}
@ -230,35 +158,23 @@ namespace QuantumUNET
{
Debug.Log("NetworkServerSimple stop ");
}
NetworkTransport.RemoveHost(this.m_ServerHostId);
this.m_ServerHostId = -1;
NetworkTransport.RemoveHost(serverHostId);
serverHostId = -1;
}
internal void RegisterHandlerSafe(short msgType, QSBNetworkMessageDelegate handler)
{
m_MessageHandlers.RegisterHandlerSafe(msgType, handler);
}
internal void RegisterHandlerSafe(short msgType, QSBNetworkMessageDelegate handler) => m_MessageHandlers.RegisterHandlerSafe(msgType, handler);
public void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler)
{
this.m_MessageHandlers.RegisterHandler(msgType, handler);
}
public void RegisterHandler(short msgType, QSBNetworkMessageDelegate handler) => m_MessageHandlers.RegisterHandler(msgType, handler);
public void UnregisterHandler(short msgType)
{
this.m_MessageHandlers.UnregisterHandler(msgType);
}
public void UnregisterHandler(short msgType) => m_MessageHandlers.UnregisterHandler(msgType);
public void ClearHandlers()
{
this.m_MessageHandlers.ClearMessageHandlers();
}
public void ClearHandlers() => m_MessageHandlers.ClearMessageHandlers();
public void UpdateConnections()
{
for (int i = 0; i < this.m_Connections.Count; i++)
for (var i = 0; i < m_Connections.Count; i++)
{
QSBNetworkConnection networkConnection = this.m_Connections[i];
var networkConnection = m_Connections[i];
if (networkConnection != null)
{
networkConnection.FlushChannels();
@ -268,13 +184,12 @@ namespace QuantumUNET
public void Update()
{
if (this.m_ServerHostId != -1)
if (serverHostId != -1)
{
NetworkEventType networkEventType;
if (this.m_RelaySlotId != -1)
if (m_RelaySlotId != -1)
{
byte b;
networkEventType = NetworkTransport.ReceiveRelayEventFromHost(this.m_ServerHostId, out b);
networkEventType = NetworkTransport.ReceiveRelayEventFromHost(serverHostId, out var b);
if (networkEventType != NetworkEventType.Nothing)
{
if (LogFilter.logDebug)
@ -299,17 +214,13 @@ namespace QuantumUNET
}
do
{
byte b;
int connectionId;
int channelId;
int receivedSize;
networkEventType = NetworkTransport.ReceiveFromHost(this.m_ServerHostId, out connectionId, out channelId, this.m_MsgBuffer, this.m_MsgBuffer.Length, out receivedSize, out b);
networkEventType = NetworkTransport.ReceiveFromHost(serverHostId, out var connectionId, out var channelId, messageBuffer, messageBuffer.Length, out var receivedSize, out var b);
if (networkEventType != NetworkEventType.Nothing)
{
Debug.Log(string.Concat(new object[]
{
"Server event: host=",
this.m_ServerHostId,
serverHostId,
" event=",
networkEventType,
" error=",
@ -319,15 +230,15 @@ namespace QuantumUNET
switch (networkEventType)
{
case NetworkEventType.DataEvent:
this.HandleData(connectionId, channelId, receivedSize, b);
HandleData(connectionId, channelId, receivedSize, b);
break;
case NetworkEventType.ConnectEvent:
this.HandleConnect(connectionId, b);
HandleConnect(connectionId, b);
break;
case NetworkEventType.DisconnectEvent:
this.HandleDisconnect(connectionId, b);
HandleDisconnect(connectionId, b);
break;
case NetworkEventType.Nothing:
@ -342,39 +253,39 @@ namespace QuantumUNET
}
}
while (networkEventType != NetworkEventType.Nothing);
this.UpdateConnections();
UpdateConnections();
}
}
public QSBNetworkConnection FindConnection(int connectionId)
{
QSBNetworkConnection result;
if (connectionId < 0 || connectionId >= this.m_Connections.Count)
if (connectionId < 0 || connectionId >= m_Connections.Count)
{
result = null;
}
else
{
result = this.m_Connections[connectionId];
result = m_Connections[connectionId];
}
return result;
}
public bool SetConnectionAtIndex(QSBNetworkConnection conn)
{
while (this.m_Connections.Count <= conn.connectionId)
while (m_Connections.Count <= conn.connectionId)
{
this.m_Connections.Add(null);
m_Connections.Add(null);
}
bool result;
if (this.m_Connections[conn.connectionId] != null)
if (m_Connections[conn.connectionId] != null)
{
result = false;
}
else
{
this.m_Connections[conn.connectionId] = conn;
conn.SetHandlers(this.m_MessageHandlers);
m_Connections[conn.connectionId] = conn;
conn.SetHandlers(m_MessageHandlers);
result = true;
}
return result;
@ -383,13 +294,13 @@ namespace QuantumUNET
public bool RemoveConnectionAtIndex(int connectionId)
{
bool result;
if (connectionId < 0 || connectionId >= this.m_Connections.Count)
if (connectionId < 0 || connectionId >= m_Connections.Count)
{
result = false;
}
else
{
this.m_Connections[connectionId] = null;
m_Connections[connectionId] = null;
result = true;
}
return result;
@ -403,26 +314,21 @@ namespace QuantumUNET
}
if (error != 0)
{
this.OnConnectError(connectionId, error);
OnConnectError(connectionId, error);
}
else
{
string networkAddress;
int num;
NetworkID networkID;
NodeID nodeID;
byte lastError;
NetworkTransport.GetConnectionInfo(this.m_ServerHostId, connectionId, out networkAddress, out num, out networkID, out nodeID, out lastError);
QSBNetworkConnection networkConnection = (QSBNetworkConnection)Activator.CreateInstance(this.m_NetworkConnectionClass);
networkConnection.SetHandlers(this.m_MessageHandlers);
networkConnection.Initialize(networkAddress, this.m_ServerHostId, connectionId, this.m_HostTopology);
NetworkTransport.GetConnectionInfo(serverHostId, connectionId, out var networkAddress, out var num, out var networkID, out var nodeID, out var lastError);
var networkConnection = (QSBNetworkConnection)Activator.CreateInstance(networkConnectionClass);
networkConnection.SetHandlers(m_MessageHandlers);
networkConnection.Initialize(networkAddress, serverHostId, connectionId, hostTopology);
networkConnection.LastError = (NetworkError)lastError;
while (this.m_Connections.Count <= connectionId)
while (m_Connections.Count <= connectionId)
{
this.m_Connections.Add(null);
m_Connections.Add(null);
}
this.m_Connections[connectionId] = networkConnection;
this.OnConnected(networkConnection);
m_Connections[connectionId] = networkConnection;
OnConnected(networkConnection);
}
}
@ -432,7 +338,7 @@ namespace QuantumUNET
{
Debug.Log("NetworkServerSimple disconnect client:" + connectionId);
}
QSBNetworkConnection networkConnection = this.FindConnection(connectionId);
var networkConnection = FindConnection(connectionId);
if (networkConnection != null)
{
networkConnection.LastError = (NetworkError)error;
@ -440,7 +346,7 @@ namespace QuantumUNET
{
if (error != 6)
{
this.m_Connections[connectionId] = null;
m_Connections[connectionId] = null;
if (LogFilter.logError)
{
Debug.LogError(string.Concat(new object[]
@ -451,23 +357,23 @@ namespace QuantumUNET
(NetworkError)error
}));
}
this.OnDisconnectError(networkConnection, error);
OnDisconnectError(networkConnection, error);
return;
}
}
networkConnection.Disconnect();
this.m_Connections[connectionId] = null;
m_Connections[connectionId] = null;
if (LogFilter.logDebug)
{
Debug.Log("Server lost client:" + connectionId);
}
this.OnDisconnected(networkConnection);
OnDisconnected(networkConnection);
}
}
private void HandleData(int connectionId, int channelId, int receivedSize, byte error)
{
QSBNetworkConnection networkConnection = this.FindConnection(connectionId);
var networkConnection = FindConnection(connectionId);
if (networkConnection == null)
{
if (LogFilter.logError)
@ -480,19 +386,19 @@ namespace QuantumUNET
networkConnection.LastError = (NetworkError)error;
if (error != 0)
{
this.OnDataError(networkConnection, error);
OnDataError(networkConnection, error);
}
else
{
this.m_MsgReader.SeekZero();
this.OnData(networkConnection, receivedSize, channelId);
messageReader.SeekZero();
OnData(networkConnection, receivedSize, channelId);
}
}
}
public void SendBytesTo(int connectionId, byte[] bytes, int numBytes, int channelId)
{
QSBNetworkConnection networkConnection = this.FindConnection(connectionId);
var networkConnection = FindConnection(connectionId);
if (networkConnection != null)
{
networkConnection.SendBytes(bytes, numBytes, channelId);
@ -501,7 +407,7 @@ namespace QuantumUNET
public void SendWriterTo(int connectionId, QSBNetworkWriter writer, int channelId)
{
QSBNetworkConnection networkConnection = this.FindConnection(connectionId);
var networkConnection = FindConnection(connectionId);
if (networkConnection != null)
{
networkConnection.SendWriter(writer, channelId);
@ -510,19 +416,19 @@ namespace QuantumUNET
public void Disconnect(int connectionId)
{
QSBNetworkConnection networkConnection = this.FindConnection(connectionId);
var networkConnection = FindConnection(connectionId);
if (networkConnection != null)
{
networkConnection.Disconnect();
this.m_Connections[connectionId] = null;
m_Connections[connectionId] = null;
}
}
public void DisconnectAllConnections()
{
for (int i = 0; i < this.m_Connections.Count; i++)
for (var i = 0; i < m_Connections.Count; i++)
{
QSBNetworkConnection networkConnection = this.m_Connections[i];
var networkConnection = m_Connections[i];
if (networkConnection != null)
{
networkConnection.Disconnect();
@ -531,58 +437,21 @@ namespace QuantumUNET
}
}
public virtual void OnConnectError(int connectionId, byte error)
{
Debug.LogError("OnConnectError error:" + error);
}
public virtual void OnConnectError(int connectionId, byte error) => Debug.LogError("OnConnectError error:" + error);
public virtual void OnDataError(QSBNetworkConnection conn, byte error)
{
Debug.LogError("OnDataError error:" + error);
}
public virtual void OnDataError(QSBNetworkConnection conn, byte error) => Debug.LogError("OnDataError error:" + error);
public virtual void OnDisconnectError(QSBNetworkConnection conn, byte error)
{
Debug.LogError("OnDisconnectError error:" + error);
}
public virtual void OnDisconnectError(QSBNetworkConnection conn, byte error) => Debug.LogError("OnDisconnectError error:" + error);
public virtual void OnConnected(QSBNetworkConnection conn)
{
conn.InvokeHandlerNoData(32);
}
public virtual void OnConnected(QSBNetworkConnection conn) => conn.InvokeHandlerNoData(32);
public virtual void OnDisconnected(QSBNetworkConnection conn)
{
conn.InvokeHandlerNoData(33);
}
public virtual void OnDisconnected(QSBNetworkConnection conn) => conn.InvokeHandlerNoData(33);
public virtual void OnData(QSBNetworkConnection conn, int receivedSize, int channelId)
{
conn.TransportReceive(this.m_MsgBuffer, receivedSize, channelId);
}
public virtual void OnData(QSBNetworkConnection conn, int receivedSize, int channelId) => conn.TransportReceive(messageBuffer, receivedSize, channelId);
private bool m_Initialized = false;
private int m_ListenPort;
private int m_ServerHostId = -1;
private int m_RelaySlotId = -1;
private bool m_UseWebSockets;
private byte[] m_MsgBuffer = null;
private NetworkReader m_MsgReader = null;
private Type m_NetworkConnectionClass = typeof(QSBNetworkConnection);
private HostTopology m_HostTopology;
private List<QSBNetworkConnection> m_Connections = new List<QSBNetworkConnection>();
private ReadOnlyCollection<QSBNetworkConnection> m_ConnectionsReadOnly;
private QSBNetworkMessageHandlers m_MessageHandlers = new QSBNetworkMessageHandlers();
}
}

View File

@ -1,537 +0,0 @@
using QuantumUNET.Components;
using QuantumUNET.Messages;
using System;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
namespace QuantumUNET
{
public class QSBNetworkWriter
{
public QSBNetworkWriter()
{
this.m_Buffer = new QSBNetBuffer();
if (s_Encoding == null)
{
s_Encoding = new UTF8Encoding();
s_StringWriteBuffer = new byte[32768];
}
}
public QSBNetworkWriter(byte[] buffer)
{
this.m_Buffer = new QSBNetBuffer(buffer);
if (s_Encoding == null)
{
s_Encoding = new UTF8Encoding();
s_StringWriteBuffer = new byte[32768];
}
}
public short Position
{
get
{
return (short)this.m_Buffer.Position;
}
}
public byte[] ToArray()
{
byte[] array = new byte[this.m_Buffer.AsArraySegment().Count];
Array.Copy(this.m_Buffer.AsArraySegment().Array, array, this.m_Buffer.AsArraySegment().Count);
return array;
}
public byte[] AsArray()
{
return this.AsArraySegment().Array;
}
internal ArraySegment<byte> AsArraySegment()
{
return this.m_Buffer.AsArraySegment();
}
public void WritePackedUInt32(uint value)
{
if (value <= 240U)
{
this.Write((byte)value);
}
else if (value <= 2287U)
{
this.Write((byte)((value - 240U) / 256U + 241U));
this.Write((byte)((value - 240U) % 256U));
}
else if (value <= 67823U)
{
this.Write(249);
this.Write((byte)((value - 2288U) / 256U));
this.Write((byte)((value - 2288U) % 256U));
}
else if (value <= 16777215U)
{
this.Write(250);
this.Write((byte)(value & 255U));
this.Write((byte)(value >> 8 & 255U));
this.Write((byte)(value >> 16 & 255U));
}
else
{
this.Write(251);
this.Write((byte)(value & 255U));
this.Write((byte)(value >> 8 & 255U));
this.Write((byte)(value >> 16 & 255U));
this.Write((byte)(value >> 24 & 255U));
}
}
public void WritePackedUInt64(ulong value)
{
if (value <= 240UL)
{
this.Write((byte)value);
}
else if (value <= 2287UL)
{
this.Write((byte)((value - 240UL) / 256UL + 241UL));
this.Write((byte)((value - 240UL) % 256UL));
}
else if (value <= 67823UL)
{
this.Write(249);
this.Write((byte)((value - 2288UL) / 256UL));
this.Write((byte)((value - 2288UL) % 256UL));
}
else if (value <= 16777215UL)
{
this.Write(250);
this.Write((byte)(value & 255UL));
this.Write((byte)(value >> 8 & 255UL));
this.Write((byte)(value >> 16 & 255UL));
}
else if (value <= uint.MaxValue)
{
this.Write(251);
this.Write((byte)(value & 255UL));
this.Write((byte)(value >> 8 & 255UL));
this.Write((byte)(value >> 16 & 255UL));
this.Write((byte)(value >> 24 & 255UL));
}
else if (value <= 1099511627775UL)
{
this.Write(252);
this.Write((byte)(value & 255UL));
this.Write((byte)(value >> 8 & 255UL));
this.Write((byte)(value >> 16 & 255UL));
this.Write((byte)(value >> 24 & 255UL));
this.Write((byte)(value >> 32 & 255UL));
}
else if (value <= 281474976710655UL)
{
this.Write(253);
this.Write((byte)(value & 255UL));
this.Write((byte)(value >> 8 & 255UL));
this.Write((byte)(value >> 16 & 255UL));
this.Write((byte)(value >> 24 & 255UL));
this.Write((byte)(value >> 32 & 255UL));
this.Write((byte)(value >> 40 & 255UL));
}
else if (value <= 72057594037927935UL)
{
this.Write(254);
this.Write((byte)(value & 255UL));
this.Write((byte)(value >> 8 & 255UL));
this.Write((byte)(value >> 16 & 255UL));
this.Write((byte)(value >> 24 & 255UL));
this.Write((byte)(value >> 32 & 255UL));
this.Write((byte)(value >> 40 & 255UL));
this.Write((byte)(value >> 48 & 255UL));
}
else
{
this.Write(byte.MaxValue);
this.Write((byte)(value & 255UL));
this.Write((byte)(value >> 8 & 255UL));
this.Write((byte)(value >> 16 & 255UL));
this.Write((byte)(value >> 24 & 255UL));
this.Write((byte)(value >> 32 & 255UL));
this.Write((byte)(value >> 40 & 255UL));
this.Write((byte)(value >> 48 & 255UL));
this.Write((byte)(value >> 56 & 255UL));
}
}
public void Write(NetworkInstanceId value)
{
this.WritePackedUInt32(value.Value);
}
public void Write(NetworkSceneId value)
{
this.WritePackedUInt32(value.Value);
}
public void Write(char value)
{
this.m_Buffer.WriteByte((byte)value);
}
public void Write(byte value)
{
this.m_Buffer.WriteByte(value);
}
public void Write(sbyte value)
{
this.m_Buffer.WriteByte((byte)value);
}
public void Write(short value)
{
this.m_Buffer.WriteByte2((byte)(value & 255), (byte)(value >> 8 & 255));
}
public void Write(ushort value)
{
this.m_Buffer.WriteByte2((byte)(value & 255), (byte)(value >> 8 & 255));
}
public void Write(int value)
{
this.m_Buffer.WriteByte4((byte)(value & 255), (byte)(value >> 8 & 255), (byte)(value >> 16 & 255), (byte)(value >> 24 & 255));
}
public void Write(uint value)
{
this.m_Buffer.WriteByte4((byte)(value & 255U), (byte)(value >> 8 & 255U), (byte)(value >> 16 & 255U), (byte)(value >> 24 & 255U));
}
public void Write(long value)
{
this.m_Buffer.WriteByte8((byte)(value & 255L), (byte)(value >> 8 & 255L), (byte)(value >> 16 & 255L), (byte)(value >> 24 & 255L), (byte)(value >> 32 & 255L), (byte)(value >> 40 & 255L), (byte)(value >> 48 & 255L), (byte)(value >> 56 & 255L));
}
public void Write(ulong value)
{
this.m_Buffer.WriteByte8((byte)(value & 255UL), (byte)(value >> 8 & 255UL), (byte)(value >> 16 & 255UL), (byte)(value >> 24 & 255UL), (byte)(value >> 32 & 255UL), (byte)(value >> 40 & 255UL), (byte)(value >> 48 & 255UL), (byte)(value >> 56 & 255UL));
}
public void Write(float value)
{
m_Buffer.WriteBytes(BitConverter.GetBytes(value), 4);
}
public void Write(double value)
{
m_Buffer.WriteBytes(BitConverter.GetBytes(value), 8);
}
public void Write(decimal value)
{
int[] bits = decimal.GetBits(value);
this.Write(bits[0]);
this.Write(bits[1]);
this.Write(bits[2]);
this.Write(bits[3]);
}
public void Write(string value)
{
if (value == null)
{
this.m_Buffer.WriteByte2(0, 0);
}
else
{
int byteCount = s_Encoding.GetByteCount(value);
if (byteCount >= 32768)
{
throw new IndexOutOfRangeException("Serialize(string) too long: " + value.Length);
}
this.Write((ushort)byteCount);
int bytes = s_Encoding.GetBytes(value, 0, value.Length, s_StringWriteBuffer, 0);
this.m_Buffer.WriteBytes(s_StringWriteBuffer, (ushort)bytes);
}
}
public void Write(bool value)
{
if (value)
{
this.m_Buffer.WriteByte(1);
}
else
{
this.m_Buffer.WriteByte(0);
}
}
public void Write(byte[] buffer, int count)
{
if (count > 65535)
{
if (LogFilter.logError)
{
Debug.LogError("NetworkWriter Write: buffer is too large (" + count + ") bytes. The maximum buffer size is 64K bytes.");
}
}
else
{
this.m_Buffer.WriteBytes(buffer, (ushort)count);
}
}
public void Write(byte[] buffer, int offset, int count)
{
if (count > 65535)
{
if (LogFilter.logError)
{
Debug.LogError("NetworkWriter Write: buffer is too large (" + count + ") bytes. The maximum buffer size is 64K bytes.");
}
}
else
{
this.m_Buffer.WriteBytesAtOffset(buffer, (ushort)offset, (ushort)count);
}
}
public void WriteBytesAndSize(byte[] buffer, int count)
{
if (buffer == null || count == 0)
{
this.Write(0);
}
else if (count > 65535)
{
if (LogFilter.logError)
{
Debug.LogError("NetworkWriter WriteBytesAndSize: buffer is too large (" + count + ") bytes. The maximum buffer size is 64K bytes.");
}
}
else
{
this.Write((ushort)count);
this.m_Buffer.WriteBytes(buffer, (ushort)count);
}
}
public void WriteBytesFull(byte[] buffer)
{
if (buffer == null)
{
this.Write(0);
}
else if (buffer.Length > 65535)
{
if (LogFilter.logError)
{
Debug.LogError("NetworkWriter WriteBytes: buffer is too large (" + buffer.Length + ") bytes. The maximum buffer size is 64K bytes.");
}
}
else
{
this.Write((ushort)buffer.Length);
this.m_Buffer.WriteBytes(buffer, (ushort)buffer.Length);
}
}
public void Write(Vector2 value)
{
this.Write(value.x);
this.Write(value.y);
}
public void Write(Vector3 value)
{
this.Write(value.x);
this.Write(value.y);
this.Write(value.z);
}
public void Write(Vector4 value)
{
this.Write(value.x);
this.Write(value.y);
this.Write(value.z);
this.Write(value.w);
}
public void Write(Color value)
{
this.Write(value.r);
this.Write(value.g);
this.Write(value.b);
this.Write(value.a);
}
public void Write(Color32 value)
{
this.Write(value.r);
this.Write(value.g);
this.Write(value.b);
this.Write(value.a);
}
public void Write(Quaternion value)
{
this.Write(value.x);
this.Write(value.y);
this.Write(value.z);
this.Write(value.w);
}
public void Write(Rect value)
{
this.Write(value.xMin);
this.Write(value.yMin);
this.Write(value.width);
this.Write(value.height);
}
public void Write(Plane value)
{
this.Write(value.normal);
this.Write(value.distance);
}
public void Write(Ray value)
{
this.Write(value.direction);
this.Write(value.origin);
}
public void Write(Matrix4x4 value)
{
this.Write(value.m00);
this.Write(value.m01);
this.Write(value.m02);
this.Write(value.m03);
this.Write(value.m10);
this.Write(value.m11);
this.Write(value.m12);
this.Write(value.m13);
this.Write(value.m20);
this.Write(value.m21);
this.Write(value.m22);
this.Write(value.m23);
this.Write(value.m30);
this.Write(value.m31);
this.Write(value.m32);
this.Write(value.m33);
}
public void Write(NetworkHash128 value)
{
this.Write(value.i0);
this.Write(value.i1);
this.Write(value.i2);
this.Write(value.i3);
this.Write(value.i4);
this.Write(value.i5);
this.Write(value.i6);
this.Write(value.i7);
this.Write(value.i8);
this.Write(value.i9);
this.Write(value.i10);
this.Write(value.i11);
this.Write(value.i12);
this.Write(value.i13);
this.Write(value.i14);
this.Write(value.i15);
}
public void Write(NetworkIdentity value)
{
if (value == null)
{
this.WritePackedUInt32(0U);
}
else
{
this.Write(value.netId);
}
}
public void Write(Transform value)
{
if (value == null || value.gameObject == null)
{
this.WritePackedUInt32(0U);
}
else
{
NetworkIdentity component = value.gameObject.GetComponent<NetworkIdentity>();
if (component != null)
{
this.Write(component.netId);
}
else
{
if (LogFilter.logWarn)
{
Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity");
}
this.WritePackedUInt32(0U);
}
}
}
public void Write(GameObject value)
{
if (value == null)
{
this.WritePackedUInt32(0U);
}
else
{
QSBNetworkIdentity component = value.GetComponent<QSBNetworkIdentity>();
if (component != null)
{
this.Write(component.NetId);
}
else
{
if (LogFilter.logWarn)
{
Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity");
}
this.WritePackedUInt32(0U);
}
}
}
public void Write(QSBMessageBase msg)
{
msg.Serialize(this);
}
public void SeekZero()
{
this.m_Buffer.SeekZero();
}
public void StartMessage(short msgType)
{
this.SeekZero();
this.m_Buffer.WriteByte2(0, 0);
this.Write(msgType);
}
public void FinishMessage()
{
this.m_Buffer.FinishMessage();
}
private const int k_MaxStringLength = 32768;
private QSBNetBuffer m_Buffer;
private static Encoding s_Encoding;
private static byte[] s_StringWriteBuffer;
}
}

View File

@ -1,11 +0,0 @@
using UnityEngine.Networking;
namespace QuantumUNET
{
public struct QSBPeerInfoPlayer
{
public NetworkInstanceId netId;
public short playerControllerId;
}
}

View File

@ -9,6 +9,7 @@ namespace QuantumUNET
public QSBNetworkIdentity UnetView;
public GameObject Gameobject;
public const int MaxPlayersPerClient = 32;
public bool IsValid => PlayerControllerId != -1;
internal const short kMaxLocalPlayers = 8;
@ -23,8 +24,6 @@ namespace QuantumUNET
PlayerControllerId = playerControllerId;
}
public bool IsValid => PlayerControllerId != -1;
public override string ToString()
{
return string.Format("ID={0} NetworkIdentity NetID={1} Player={2}", new object[]

View File

@ -1,4 +1,5 @@
using QuantumUNET.Messages;
using QuantumUNET.Transport;
namespace QuantumUNET
{

View File

@ -1,4 +1,5 @@
using QuantumUNET.Messages;
using QuantumUNET.Transport;
using UnityEngine;
using UnityEngine.Networking;
@ -12,20 +13,14 @@ namespace QuantumUNET
m_LocalServer = localServer;
}
public override bool Send(short msgType, QSBMessageBase msg)
{
return m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 0);
}
public override bool Send(short msgType, QSBMessageBase msg) =>
m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 0);
public override bool SendUnreliable(short msgType, QSBMessageBase msg)
{
return m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 1);
}
public override bool SendUnreliable(short msgType, QSBMessageBase msg) =>
m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, 1);
public override bool SendByChannel(short msgType, QSBMessageBase msg, int channelId)
{
return m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, channelId);
}
public override bool SendByChannel(short msgType, QSBMessageBase msg, int channelId) =>
m_LocalServer.InvokeHandlerOnServer(this, msgType, msg, channelId);
public override bool SendBytes(byte[] bytes, int numBytes, int channelId)
{
@ -45,10 +40,8 @@ namespace QuantumUNET
return result;
}
public override bool SendWriter(QSBNetworkWriter writer, int channelId)
{
return m_LocalServer.InvokeBytes(this, writer.AsArray(), (int)((short)writer.AsArray().Length), channelId);
}
public override bool SendWriter(QSBNetworkWriter writer, int channelId) =>
m_LocalServer.InvokeBytes(this, writer.AsArray(), (short)writer.AsArray().Length, channelId);
public override void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond)
{

View File

@ -1,32 +0,0 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking.Types;
namespace QuantumUNET
{
public class QSBUtility
{
private static readonly Dictionary<NetworkID, NetworkAccessToken> _dictTokens = new Dictionary<NetworkID, NetworkAccessToken>();
public static SourceID GetSourceID()
=> (SourceID)SystemInfo.deviceUniqueIdentifier.GetHashCode();
public static void SetAccessTokenForNetwork(NetworkID netId, NetworkAccessToken accessToken)
{
if (_dictTokens.ContainsKey(netId))
{
_dictTokens.Remove(netId);
}
_dictTokens.Add(netId, accessToken);
}
public static NetworkAccessToken GetAccessTokenForNetwork(NetworkID netId)
{
if (!_dictTokens.TryGetValue(netId, out var result))
{
result = new NetworkAccessToken();
}
return result;
}
}
}

View File

@ -100,8 +100,8 @@
<Compile Include="Messages\QSBAnimationMessage.cs" />
<Compile Include="Messages\QSBAnimationParametersMessage.cs" />
<Compile Include="Messages\QSBAnimationTriggerMessage.cs" />
<Compile Include="QSBChannelBuffer.cs" />
<Compile Include="QSBChannelPacket.cs" />
<Compile Include="Transport\QSBChannelBuffer.cs" />
<Compile Include="Transport\QSBChannelPacket.cs" />
<Compile Include="Messages\QSBClientAuthorityMessage.cs" />
<Compile Include="QSBClientScene.cs" />
<Compile Include="Messages\QSBCRCMessage.cs" />
@ -110,7 +110,7 @@
<Compile Include="Messages\QSBErrorMessage.cs" />
<Compile Include="QSBLocalClient.cs" />
<Compile Include="Messages\QSBMessageBase.cs" />
<Compile Include="QSBNetBuffer.cs" />
<Compile Include="Transport\QSBNetBuffer.cs" />
<Compile Include="Components\QSBNetworkAnimator.cs" />
<Compile Include="QSBNetworkBehaviour.cs" />
<Compile Include="QSBNetworkClient.cs" />
@ -121,29 +121,29 @@
<Compile Include="Components\QSBNetworkManagerUNET.cs" />
<Compile Include="Messages\QSBNetworkMessage.cs" />
<Compile Include="Messages\QSBNetworkMessageDelegate.cs" />
<Compile Include="QSBNetworkHash128.cs" />
<Compile Include="QSBNetworkInstanceId.cs" />
<Compile Include="QSBNetworkMessageHandlers.cs" />
<Compile Include="QSBNetworkReader.cs" />
<Compile Include="Transport\QSBNetworkReader.cs" />
<Compile Include="QSBNetworkScene.cs" />
<Compile Include="QSBNetworkSceneId.cs" />
<Compile Include="QSBNetworkServer.cs" />
<Compile Include="QSBNetworkServerSimple.cs" />
<Compile Include="Components\QSBNetworkTransform.cs" />
<Compile Include="QSBNetworkWriter.cs" />
<Compile Include="Transport\QSBNetworkWriter.cs" />
<Compile Include="Messages\QSBNotReadyMessage.cs" />
<Compile Include="Messages\QSBObjectDestroyMessage.cs" />
<Compile Include="Messages\QSBObjectSpawnFinishedMessage.cs" />
<Compile Include="Messages\QSBObjectSpawnMessage.cs" />
<Compile Include="Messages\QSBObjectSpawnSceneMessage.cs" />
<Compile Include="Messages\QSBOwnerMessage.cs" />
<Compile Include="Messages\QSBPeerInfoMessage.cs" />
<Compile Include="QSBPeerInfoPlayer.cs" />
<Compile Include="QSBPlayerController.cs" />
<Compile Include="Messages\QSBReadyMessage.cs" />
<Compile Include="Messages\QSBReconnectMessage.cs" />
<Compile Include="Messages\QSBRemovePlayerMessage.cs" />
<Compile Include="Messages\QSBStringMessage.cs" />
<Compile Include="Messages\QSBSpawnDelegate.cs" />
<Compile Include="QSBULocalConnectionToClient.cs" />
<Compile Include="QSBULocalConnectionToServer.cs" />
<Compile Include="QSBUtility.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />

View File

@ -4,7 +4,7 @@ using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
namespace QuantumUNET
namespace QuantumUNET.Transport
{
internal class QSBChannelBuffer : IDisposable
{
@ -99,26 +99,17 @@ namespace QuantumUNET
}
else if (!_currentPacket.IsEmpty() || _pendingPackets.Count > 0)
{
if (LogFilter.logError)
{
Debug.LogError("Cannot set MaxPacketSize after sending data.");
}
Debug.LogError("Cannot set MaxPacketSize after sending data.");
result = false;
}
else if (value <= 0)
{
if (LogFilter.logError)
{
Debug.LogError("Cannot set MaxPacketSize less than one.");
}
Debug.LogError("Cannot set MaxPacketSize less than one.");
result = false;
}
else if (value > _maxPacketSize)
{
if (LogFilter.logError)
{
Debug.LogError("Cannot set MaxPacketSize to greater than the existing maximum (" + _maxPacketSize + ").");
}
Debug.LogError("Cannot set MaxPacketSize to greater than the existing maximum (" + _maxPacketSize + ").");
result = false;
}
else
@ -140,16 +131,13 @@ namespace QuantumUNET
}
else if (value < 0 || value >= 512)
{
if (LogFilter.logError)
Debug.LogError(string.Concat(new object[]
{
Debug.LogError(string.Concat(new object[]
{
"Invalid MaxPendingBuffers for channel ",
_channelId,
". Must be greater than zero and less than ",
512
}));
}
}));
result = false;
}
else
@ -240,18 +228,12 @@ namespace QuantumUNET
bool result;
if (bytesToSend >= 65535)
{
if (LogFilter.logError)
{
Debug.LogError("ChannelBuffer:SendBytes cannot send packet larger than " + ushort.MaxValue + " bytes");
}
Debug.LogError("ChannelBuffer:SendBytes cannot send packet larger than " + ushort.MaxValue + " bytes");
result = false;
}
else if (bytesToSend <= 0)
{
if (LogFilter.logError)
{
Debug.LogError("ChannelBuffer:SendBytes cannot send zero bytes");
}
Debug.LogError("ChannelBuffer:SendBytes cannot send zero bytes");
result = false;
}
else if (bytesToSend > _maxPacketSize)
@ -262,18 +244,15 @@ namespace QuantumUNET
}
else
{
if (LogFilter.logError)
Debug.LogError(string.Concat(new object[]
{
Debug.LogError(string.Concat(new object[]
{
"Failed to send big message of ",
bytesToSend,
" bytes. The maximum is ",
_maxPacketSize,
" bytes on channel:",
_channelId
}));
}
}));
result = false;
}
}
@ -294,10 +273,7 @@ namespace QuantumUNET
{
if (!_isBroken)
{
if (LogFilter.logError)
{
Debug.LogError("ChannelBuffer buffer limit of " + _pendingPackets.Count + " packets reached.");
}
Debug.LogError("ChannelBuffer buffer limit of " + _pendingPackets.Count + " packets reached.");
}
_isBroken = true;
result = false;
@ -311,10 +287,7 @@ namespace QuantumUNET
}
else if (!_currentPacket.SendToTransport(_connection, _channelId))
{
if (LogFilter.logError)
{
Debug.Log("ChannelBuffer SendBytes no space on unreliable channel " + _channelId);
}
Debug.Log("ChannelBuffer SendBytes no space on unreliable channel " + _channelId);
result = false;
}
else
@ -380,10 +353,7 @@ namespace QuantumUNET
FreePacket(channelPacket);
if (_isBroken && _pendingPackets.Count < _maxPendingPacketCount / 2)
{
if (LogFilter.logWarn)
{
Debug.LogWarning("ChannelBuffer recovered from overflow but data was lost.");
}
Debug.LogWarning("ChannelBuffer recovered from overflow but data was lost.");
_isBroken = false;
}
}

View File

@ -0,0 +1,56 @@
using System;
using UnityEngine;
using UnityEngine.Networking;
namespace QuantumUNET.Transport
{
internal struct QSBChannelPacket
{
private int m_Position;
private byte[] m_Buffer;
private bool m_IsReliable;
public QSBChannelPacket(int packetSize, bool isReliable)
{
m_Position = 0;
m_Buffer = new byte[packetSize];
m_IsReliable = isReliable;
}
public void Reset() => m_Position = 0;
public bool IsEmpty() => m_Position == 0;
public void Write(byte[] bytes, int numBytes)
{
Array.Copy(bytes, 0, m_Buffer, m_Position, numBytes);
m_Position += numBytes;
}
public bool HasSpace(int numBytes) => m_Position + numBytes <= m_Buffer.Length;
public bool SendToTransport(QSBNetworkConnection conn, int channelId)
{
var result = true;
if (!conn.TransportSend(m_Buffer, (ushort)m_Position, channelId, out var b))
{
if (!m_IsReliable || b != 4)
{
Debug.LogError($"Failed to send internal buffer channel:{channelId} bytesToSend:{m_Position}");
result = false;
}
}
if (b != 0)
{
if (m_IsReliable && b == 4)
{
return false;
}
Debug.LogError($"Send Error: {(NetworkError)b} channel:{channelId} bytesToSend:{m_Position}");
result = false;
}
m_Position = 0;
return result;
}
}
}

View File

@ -0,0 +1,169 @@
using System;
using UnityEngine;
namespace QuantumUNET.Transport
{
internal class QSBNetBuffer
{
public QSBNetBuffer()
{
m_Buffer = new byte[64];
}
public QSBNetBuffer(byte[] buffer)
{
m_Buffer = buffer;
}
public uint Position { get; private set; }
public int Length => m_Buffer.Length;
public byte ReadByte()
{
if (Position >= (ulong)m_Buffer.Length)
{
throw new IndexOutOfRangeException("NetworkReader:ReadByte out of range:" + ToString());
}
return m_Buffer[(int)((UIntPtr)(Position++))];
}
public void ReadBytes(byte[] buffer, uint count)
{
if (Position + count > (ulong)m_Buffer.Length)
{
throw new IndexOutOfRangeException(string.Concat(new object[]
{
"NetworkReader:ReadBytes out of range: (",
count,
") ",
ToString()
}));
}
ushort num = 0;
while (num < count)
{
buffer[num] = m_Buffer[(int)((UIntPtr)(Position + num))];
num += 1;
}
Position += count;
}
internal ArraySegment<byte> AsArraySegment() => new ArraySegment<byte>(m_Buffer, 0, (int)Position);
public void WriteByte(byte value)
{
WriteCheckForSpace(1);
m_Buffer[(int)((UIntPtr)Position)] = value;
Position += 1U;
}
public void WriteByte2(byte value0, byte value1)
{
WriteCheckForSpace(2);
m_Buffer[(int)((UIntPtr)Position)] = value0;
m_Buffer[(int)((UIntPtr)(Position + 1U))] = value1;
Position += 2U;
}
public void WriteByte4(byte value0, byte value1, byte value2, byte value3)
{
WriteCheckForSpace(4);
m_Buffer[(int)((UIntPtr)Position)] = value0;
m_Buffer[(int)((UIntPtr)(Position + 1U))] = value1;
m_Buffer[(int)((UIntPtr)(Position + 2U))] = value2;
m_Buffer[(int)((UIntPtr)(Position + 3U))] = value3;
Position += 4U;
}
public void WriteByte8(byte value0, byte value1, byte value2, byte value3, byte value4, byte value5, byte value6, byte value7)
{
WriteCheckForSpace(8);
m_Buffer[(int)((UIntPtr)Position)] = value0;
m_Buffer[(int)((UIntPtr)(Position + 1U))] = value1;
m_Buffer[(int)((UIntPtr)(Position + 2U))] = value2;
m_Buffer[(int)((UIntPtr)(Position + 3U))] = value3;
m_Buffer[(int)((UIntPtr)(Position + 4U))] = value4;
m_Buffer[(int)((UIntPtr)(Position + 5U))] = value5;
m_Buffer[(int)((UIntPtr)(Position + 6U))] = value6;
m_Buffer[(int)((UIntPtr)(Position + 7U))] = value7;
Position += 8U;
}
public void WriteBytesAtOffset(byte[] buffer, ushort targetOffset, ushort count)
{
var num = (uint)(count + targetOffset);
WriteCheckForSpace((ushort)num);
if (targetOffset == 0 && count == buffer.Length)
{
buffer.CopyTo(m_Buffer, (int)Position);
}
else
{
for (var i = 0; i < count; i++)
{
m_Buffer[targetOffset + i] = buffer[i];
}
}
if (num > Position)
{
Position = num;
}
}
public void WriteBytes(byte[] buffer, ushort count)
{
WriteCheckForSpace(count);
if (count == buffer.Length)
{
buffer.CopyTo(m_Buffer, (int)Position);
}
else
{
for (var i = 0; i < count; i++)
{
m_Buffer[(int)(checked((IntPtr)(unchecked(Position + (ulong)i))))] = buffer[i];
}
}
Position += count;
}
private void WriteCheckForSpace(ushort count)
{
if (Position + count >= (ulong)m_Buffer.Length)
{
var num = (int)Math.Ceiling(m_Buffer.Length * 1.5f);
while (Position + count >= (ulong)num)
{
num = (int)Math.Ceiling(num * 1.5f);
if (num > 134217728)
{
Debug.LogWarning("NetworkBuffer size is " + num + " bytes!");
}
}
var array = new byte[num];
m_Buffer.CopyTo(array, 0);
m_Buffer = array;
}
}
public void FinishMessage()
{
var num = (ushort)(Position - 4U);
m_Buffer[0] = (byte)(num & 255);
m_Buffer[1] = (byte)((num >> 8) & 255);
}
public void SeekZero() =>
Position = 0U;
public void Replace(byte[] buffer)
{
m_Buffer = buffer;
Position = 0U;
}
public override string ToString() => string.Format("NetBuf sz:{0} pos:{1}", m_Buffer.Length, Position);
private byte[] m_Buffer;
}
}

View File

@ -5,7 +5,7 @@ using System.Text;
using UnityEngine;
using UnityEngine.Networking;
namespace QuantumUNET
namespace QuantumUNET.Transport
{
public class QSBNetworkReader
{
@ -162,9 +162,9 @@ namespace QuantumUNET
return result;
}
public NetworkInstanceId ReadNetworkId() => new NetworkInstanceId(ReadPackedUInt32());
public QSBNetworkInstanceId ReadNetworkId() => new QSBNetworkInstanceId(ReadPackedUInt32());
public NetworkSceneId ReadSceneId() => new NetworkSceneId(ReadPackedUInt32());
public QSBNetworkSceneId ReadSceneId() => new QSBNetworkSceneId(ReadPackedUInt32());
public byte ReadByte() => m_buf.ReadByte();
@ -363,9 +363,9 @@ namespace QuantumUNET
};
}
public NetworkHash128 ReadNetworkHash128()
public QSBNetworkHash128 ReadNetworkHash128()
{
NetworkHash128 result;
QSBNetworkHash128 result;
result.i0 = ReadByte();
result.i1 = ReadByte();
result.i2 = ReadByte();

View File

@ -0,0 +1,477 @@
using QuantumUNET.Components;
using QuantumUNET.Messages;
using System;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
namespace QuantumUNET.Transport
{
public class QSBNetworkWriter
{
public QSBNetworkWriter()
{
m_Buffer = new QSBNetBuffer();
if (s_Encoding == null)
{
s_Encoding = new UTF8Encoding();
s_StringWriteBuffer = new byte[32768];
}
}
public QSBNetworkWriter(byte[] buffer)
{
m_Buffer = new QSBNetBuffer(buffer);
if (s_Encoding == null)
{
s_Encoding = new UTF8Encoding();
s_StringWriteBuffer = new byte[32768];
}
}
public short Position => (short)m_Buffer.Position;
public byte[] ToArray()
{
var array = new byte[m_Buffer.AsArraySegment().Count];
Array.Copy(m_Buffer.AsArraySegment().Array, array, m_Buffer.AsArraySegment().Count);
return array;
}
public byte[] AsArray() => AsArraySegment().Array;
internal ArraySegment<byte> AsArraySegment() => m_Buffer.AsArraySegment();
public void WritePackedUInt32(uint value)
{
if (value <= 240U)
{
Write((byte)value);
}
else if (value <= 2287U)
{
Write((byte)(((value - 240U) / 256U) + 241U));
Write((byte)((value - 240U) % 256U));
}
else if (value <= 67823U)
{
Write(249);
Write((byte)((value - 2288U) / 256U));
Write((byte)((value - 2288U) % 256U));
}
else if (value <= 16777215U)
{
Write(250);
Write((byte)(value & 255U));
Write((byte)((value >> 8) & 255U));
Write((byte)((value >> 16) & 255U));
}
else
{
Write(251);
Write((byte)(value & 255U));
Write((byte)((value >> 8) & 255U));
Write((byte)((value >> 16) & 255U));
Write((byte)((value >> 24) & 255U));
}
}
public void WritePackedUInt64(ulong value)
{
if (value <= 240UL)
{
Write((byte)value);
}
else if (value <= 2287UL)
{
Write((byte)(((value - 240UL) / 256UL) + 241UL));
Write((byte)((value - 240UL) % 256UL));
}
else if (value <= 67823UL)
{
Write(249);
Write((byte)((value - 2288UL) / 256UL));
Write((byte)((value - 2288UL) % 256UL));
}
else if (value <= 16777215UL)
{
Write(250);
Write((byte)(value & 255UL));
Write((byte)((value >> 8) & 255UL));
Write((byte)((value >> 16) & 255UL));
}
else if (value <= uint.MaxValue)
{
Write(251);
Write((byte)(value & 255UL));
Write((byte)((value >> 8) & 255UL));
Write((byte)((value >> 16) & 255UL));
Write((byte)((value >> 24) & 255UL));
}
else if (value <= 1099511627775UL)
{
Write(252);
Write((byte)(value & 255UL));
Write((byte)((value >> 8) & 255UL));
Write((byte)((value >> 16) & 255UL));
Write((byte)((value >> 24) & 255UL));
Write((byte)((value >> 32) & 255UL));
}
else if (value <= 281474976710655UL)
{
Write(253);
Write((byte)(value & 255UL));
Write((byte)((value >> 8) & 255UL));
Write((byte)((value >> 16) & 255UL));
Write((byte)((value >> 24) & 255UL));
Write((byte)((value >> 32) & 255UL));
Write((byte)((value >> 40) & 255UL));
}
else if (value <= 72057594037927935UL)
{
Write(254);
Write((byte)(value & 255UL));
Write((byte)((value >> 8) & 255UL));
Write((byte)((value >> 16) & 255UL));
Write((byte)((value >> 24) & 255UL));
Write((byte)((value >> 32) & 255UL));
Write((byte)((value >> 40) & 255UL));
Write((byte)((value >> 48) & 255UL));
}
else
{
Write(byte.MaxValue);
Write((byte)(value & 255UL));
Write((byte)((value >> 8) & 255UL));
Write((byte)((value >> 16) & 255UL));
Write((byte)((value >> 24) & 255UL));
Write((byte)((value >> 32) & 255UL));
Write((byte)((value >> 40) & 255UL));
Write((byte)((value >> 48) & 255UL));
Write((byte)((value >> 56) & 255UL));
}
}
public void Write(QSBNetworkInstanceId value) => WritePackedUInt32(value.Value);
public void Write(QSBNetworkSceneId value) => WritePackedUInt32(value.Value);
public void Write(char value) => m_Buffer.WriteByte((byte)value);
public void Write(byte value) => m_Buffer.WriteByte(value);
public void Write(sbyte value) => m_Buffer.WriteByte((byte)value);
public void Write(short value) => m_Buffer.WriteByte2((byte)(value & 255), (byte)((value >> 8) & 255));
public void Write(ushort value) => m_Buffer.WriteByte2((byte)(value & 255), (byte)((value >> 8) & 255));
public void Write(int value) => m_Buffer.WriteByte4((byte)(value & 255), (byte)((value >> 8) & 255), (byte)((value >> 16) & 255), (byte)((value >> 24) & 255));
public void Write(uint value) => m_Buffer.WriteByte4((byte)(value & 255U), (byte)((value >> 8) & 255U), (byte)((value >> 16) & 255U), (byte)((value >> 24) & 255U));
public void Write(long value) => m_Buffer.WriteByte8((byte)(value & 255L), (byte)((value >> 8) & 255L), (byte)((value >> 16) & 255L), (byte)((value >> 24) & 255L), (byte)((value >> 32) & 255L), (byte)((value >> 40) & 255L), (byte)((value >> 48) & 255L), (byte)((value >> 56) & 255L));
public void Write(ulong value) => m_Buffer.WriteByte8((byte)(value & 255UL), (byte)((value >> 8) & 255UL), (byte)((value >> 16) & 255UL), (byte)((value >> 24) & 255UL), (byte)((value >> 32) & 255UL), (byte)((value >> 40) & 255UL), (byte)((value >> 48) & 255UL), (byte)((value >> 56) & 255UL));
public void Write(float value) => m_Buffer.WriteBytes(BitConverter.GetBytes(value), 4);
public void Write(double value) => m_Buffer.WriteBytes(BitConverter.GetBytes(value), 8);
public void Write(decimal value)
{
var bits = decimal.GetBits(value);
Write(bits[0]);
Write(bits[1]);
Write(bits[2]);
Write(bits[3]);
}
public void Write(string value)
{
if (value == null)
{
m_Buffer.WriteByte2(0, 0);
}
else
{
var byteCount = s_Encoding.GetByteCount(value);
if (byteCount >= 32768)
{
throw new IndexOutOfRangeException("Serialize(string) too long: " + value.Length);
}
Write((ushort)byteCount);
var bytes = s_Encoding.GetBytes(value, 0, value.Length, s_StringWriteBuffer, 0);
m_Buffer.WriteBytes(s_StringWriteBuffer, (ushort)bytes);
}
}
public void Write(bool value)
{
if (value)
{
m_Buffer.WriteByte(1);
}
else
{
m_Buffer.WriteByte(0);
}
}
public void Write(byte[] buffer, int count)
{
if (count > 65535)
{
if (LogFilter.logError)
{
Debug.LogError("NetworkWriter Write: buffer is too large (" + count + ") bytes. The maximum buffer size is 64K bytes.");
}
}
else
{
m_Buffer.WriteBytes(buffer, (ushort)count);
}
}
public void Write(byte[] buffer, int offset, int count)
{
if (count > 65535)
{
if (LogFilter.logError)
{
Debug.LogError("NetworkWriter Write: buffer is too large (" + count + ") bytes. The maximum buffer size is 64K bytes.");
}
}
else
{
m_Buffer.WriteBytesAtOffset(buffer, (ushort)offset, (ushort)count);
}
}
public void WriteBytesAndSize(byte[] buffer, int count)
{
if (buffer == null || count == 0)
{
Write(0);
}
else if (count > 65535)
{
if (LogFilter.logError)
{
Debug.LogError("NetworkWriter WriteBytesAndSize: buffer is too large (" + count + ") bytes. The maximum buffer size is 64K bytes.");
}
}
else
{
Write((ushort)count);
m_Buffer.WriteBytes(buffer, (ushort)count);
}
}
public void WriteBytesFull(byte[] buffer)
{
if (buffer == null)
{
Write(0);
}
else if (buffer.Length > 65535)
{
if (LogFilter.logError)
{
Debug.LogError("NetworkWriter WriteBytes: buffer is too large (" + buffer.Length + ") bytes. The maximum buffer size is 64K bytes.");
}
}
else
{
Write((ushort)buffer.Length);
m_Buffer.WriteBytes(buffer, (ushort)buffer.Length);
}
}
public void Write(Vector2 value)
{
Write(value.x);
Write(value.y);
}
public void Write(Vector3 value)
{
Write(value.x);
Write(value.y);
Write(value.z);
}
public void Write(Vector4 value)
{
Write(value.x);
Write(value.y);
Write(value.z);
Write(value.w);
}
public void Write(Color value)
{
Write(value.r);
Write(value.g);
Write(value.b);
Write(value.a);
}
public void Write(Color32 value)
{
Write(value.r);
Write(value.g);
Write(value.b);
Write(value.a);
}
public void Write(Quaternion value)
{
Write(value.x);
Write(value.y);
Write(value.z);
Write(value.w);
}
public void Write(Rect value)
{
Write(value.xMin);
Write(value.yMin);
Write(value.width);
Write(value.height);
}
public void Write(Plane value)
{
Write(value.normal);
Write(value.distance);
}
public void Write(Ray value)
{
Write(value.direction);
Write(value.origin);
}
public void Write(Matrix4x4 value)
{
Write(value.m00);
Write(value.m01);
Write(value.m02);
Write(value.m03);
Write(value.m10);
Write(value.m11);
Write(value.m12);
Write(value.m13);
Write(value.m20);
Write(value.m21);
Write(value.m22);
Write(value.m23);
Write(value.m30);
Write(value.m31);
Write(value.m32);
Write(value.m33);
}
public void Write(QSBNetworkHash128 value)
{
Write(value.i0);
Write(value.i1);
Write(value.i2);
Write(value.i3);
Write(value.i4);
Write(value.i5);
Write(value.i6);
Write(value.i7);
Write(value.i8);
Write(value.i9);
Write(value.i10);
Write(value.i11);
Write(value.i12);
Write(value.i13);
Write(value.i14);
Write(value.i15);
}
public void Write(QSBNetworkIdentity value)
{
if (value == null)
{
WritePackedUInt32(0U);
}
else
{
Write(value.NetId);
}
}
public void Write(Transform value)
{
if (value == null || value.gameObject == null)
{
WritePackedUInt32(0U);
}
else
{
var component = value.gameObject.GetComponent<QSBNetworkIdentity>();
if (component != null)
{
Write(component.NetId);
}
else
{
if (LogFilter.logWarn)
{
Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity");
}
WritePackedUInt32(0U);
}
}
}
public void Write(GameObject value)
{
if (value == null)
{
WritePackedUInt32(0U);
}
else
{
var component = value.GetComponent<QSBNetworkIdentity>();
if (component != null)
{
Write(component.NetId);
}
else
{
if (LogFilter.logWarn)
{
Debug.LogWarning("NetworkWriter " + value + " has no NetworkIdentity");
}
WritePackedUInt32(0U);
}
}
}
public void Write(QSBMessageBase msg) => msg.Serialize(this);
public void SeekZero() => m_Buffer.SeekZero();
public void StartMessage(short msgType)
{
SeekZero();
m_Buffer.WriteByte2(0, 0);
Write(msgType);
}
public void FinishMessage() => m_Buffer.FinishMessage();
private const int k_MaxStringLength = 32768;
private QSBNetBuffer m_Buffer;
private static Encoding s_Encoding;
private static byte[] s_StringWriteBuffer;
}
}

View File

@ -1,6 +1,6 @@
# Quantum Space Buddies - Outer Wilds Online Multiplayer Mod
Quantum Space Buddies (QSB) is a multiplayer mod for Outer Wilds. The mod uses the OWML mod loader and customized UNET code (internally referred to as "QuantumUNET") for networking.
Quantum Space Buddies (QSB) is a multiplayer mod for Outer Wilds. The mod uses the OWML mod loader and customized UNET code (internally referred to as QNet or QuantumUNET) for networking.
**Disclamer - The mod authors (misternebula, AmazingAlek and Raicuparta) take no responsibility for any damages that are caused through opening ports on your network, or connecting to servers. Do not attempt to change your router settings without prior knowledge of what you are doing. Only share your public IP with people you trust, and don't connect to IPs that you do not know the source of. It is good practice to close ports/firewall exceptions after you have finished playing.**